service-bridge 1.9.0-dev.52 → 2.0.0-alpha

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/serde/contract-hash.ts","../src/serde/json-schema-serde.ts","../src/serde/serializer.ts","../src/connection/service-bridge.ts","../src/events/domain.ts","../src/pb/servicebridge/v1/events.ts","../src/events/drainer.ts","../src/events/errors.ts","../src/events/ids.ts","../src/events/publisher.ts","../src/events/subscriber.ts","../src/job/domain.ts","../src/pb/servicebridge/v1/registry.ts","../src/job/subscriber.ts","../src/pb/servicebridge/v1/control.ts","../src/pb/servicebridge/v1/jobs.ts","../src/pb/servicebridge/v1/telemetry.ts","../src/pb/servicebridge/v1/workflows.ts","../src/pb/google/protobuf/empty.ts","../src/http/route.ts","../src/registry/registry.ts","../src/registry/watch.ts","../src/rpc/circuit-breaker.ts","../src/rpc/client.ts","../src/telemetry/context.ts","../src/telemetry/ops.ts","../src/telemetry/payload-capture.ts","../src/telemetry/trace-context.ts","../src/rpc/lb.ts","../src/rpc/retry.ts","../src/rpc/direct-transport.ts","../src/connection/pem.ts","../src/connection/spiffe.ts","../src/pb/servicebridge/v1/call.ts","../src/telemetry/wire-trace.ts","../src/rpc/errors.ts","../src/rpc/domain.ts","../src/rpc/instance-cache.ts","../src/rpc/proxy-transport.ts","../src/pb/servicebridge/v1/invoke.ts","../src/rpc/server.ts","../src/rpc/acceptance.ts","../src/rpc/typed-client.ts","../src/sqlite/storage.ts","../src/telemetry/logs.ts","../src/telemetry/metrics.ts","../src/telemetry/process-sampler.ts","../src/telemetry/ring.ts","../src/telemetry/transport.ts","../src/workflow/canonical.ts","../src/workflow/errors.ts","../src/workflow/jsonpath.ts","../src/workflow/validate.ts","../src/workflow/domain.ts","../src/workflow/runtime-ops.ts","../src/workflow/compensate-opts.ts","../src/workflow/runner.ts","../src/workflow/subscriber.ts","../src/pb/servicebridge/v1/bootstrap.ts","../src/connection/key.ts","../src/connection/provision.ts","../src/connection/service-bridge-error.ts","../src/connection/session.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport type { SchemaPair, Serializer } from \"./serializer\";\n\n// computeContractHash returns the canonical SHA-256 (hex) of a SchemaPair.\n// The hash identifies an exact (input, output) schema combination — caller\n// and callee that load the SAME schema source MUST produce the SAME hash.\n//\n// Algorithm:\n// 1. Take input.toJsonSchema() and output.toJsonSchema() — both are\n// protobufjs Type descriptors (deterministic structure).\n// 2. Canonicalize each (sorted keys, no whitespace) into a JSON string.\n// Arrays preserve order; objects sort by key recursively.\n// 3. Concatenate as `<input_canonical>:<output_canonical>`.\n// 4. SHA-256, hex-encode.\n//\n// This is the SINGLE source of truth for contract hashing across the SDK.\n// Runtime stores the hash opaque and does NOT recompute (ADR 0005, variant 3).\n//\n// @public — см. ./README.md\nexport function computeContractHash(pair: SchemaPair): string {\n\tconst inputCanonical = canonicalize(pair.input.toJsonSchema());\n\tconst outputCanonical = canonicalize(pair.output.toJsonSchema());\n\treturn createHash(\"sha256\")\n\t\t.update(`${inputCanonical}:${outputCanonical}`)\n\t\t.digest(\"hex\");\n}\n\n// computeSerializerHash hashes a single Serializer (used when only one side\n// of the pair is relevant — e.g. event schemas in future branches).\nexport function computeSerializerHash(s: Serializer): string {\n\tconst canonical = canonicalize(s.toJsonSchema());\n\treturn createHash(\"sha256\").update(canonical).digest(\"hex\");\n}\n\n// canonicalize produces the deterministic JSON string used for hashing.\n// Rules:\n// - null / primitives → JSON.stringify (standard)\n// - arrays → preserve element order, recurse on each element\n// - objects → sort keys lexicographically, recurse on each value\n// - no whitespace, no trailing commas\n//\n// @internal — см. ./README.md\nexport function canonicalize(value: unknown): string {\n\tif (value === null || typeof value !== \"object\") {\n\t\treturn JSON.stringify(value);\n\t}\n\tif (Array.isArray(value)) {\n\t\treturn `[${value.map(canonicalize).join(\",\")}]`;\n\t}\n\tconst obj = value as Record<string, unknown>;\n\tconst keys = Object.keys(obj).sort();\n\treturn `{${keys\n\t\t.map((k) => `${JSON.stringify(k)}:${canonicalize(obj[k])}`)\n\t\t.join(\",\")}}`;\n}\n","import { readFileSync } from \"node:fs\";\nimport protobuf from \"protobufjs\";\nimport { computeSerializerHash } from \"./contract-hash\";\nimport type { SchemaPair, Serializer } from \"./serializer\";\n\n// JsonSchemaFileSpec references a .schema.json file describing both input and\n// output messages with explicit field numbers per property. Unlike inline JSON\n// schema (removed permanently), this format is safe for schema evolution\n// because field numbers are pinned by the schema author.\nexport interface JsonSchemaFileSpec {\n\tschemaFile: string;\n}\n\n// .schema.json file shape:\n// {\n// \"input\": { \"<MessageName>\": { \"<field>\": { type, fieldNumber }, ... } },\n// \"output\": { \"<MessageName>\": { ... } }\n// }\ninterface SchemaFile {\n\tinput: Record<string, SchemaFields>;\n\toutput: Record<string, SchemaFields>;\n}\n\ntype SchemaFields = Record<string, SchemaField>;\n\ninterface SchemaField {\n\ttype: ProtoFieldType;\n\tfieldNumber?: number;\n\t// For type=\"array\": the element type and its own field number rules.\n\t// The repeated field itself uses the outer `fieldNumber`.\n\tarray?: { type: ProtoFieldType; nested?: SchemaFields };\n\t// For type=\"object\": nested message fields with their own field numbers.\n\tnested?: SchemaFields;\n}\n\ntype ProtoFieldType =\n\t| \"string\"\n\t| \"bool\"\n\t| \"int32\"\n\t| \"int64\"\n\t| \"uint32\"\n\t| \"uint64\"\n\t| \"float\"\n\t| \"double\"\n\t| \"bytes\"\n\t| \"object\"\n\t| \"array\";\n\n// buildSchemaPairFromJsonFile loads the schema file, validates field numbers,\n// constructs protobufjs Types dynamically, and returns a SchemaPair compatible\n// with the rest of the rpc/serde stack.\nexport function buildSchemaPairFromJsonFile(\n\tspec: JsonSchemaFileSpec,\n): SchemaPair {\n\tlet raw: string;\n\ttry {\n\t\traw = readFileSync(spec.schemaFile, \"utf8\");\n\t} catch (err) {\n\t\tthrow new Error(\n\t\t\t`serde: read schema file ${spec.schemaFile}: ${(err as Error).message}`,\n\t\t);\n\t}\n\n\tlet parsed: SchemaFile;\n\ttry {\n\t\tparsed = JSON.parse(raw) as SchemaFile;\n\t} catch (err) {\n\t\tthrow new Error(\n\t\t\t`serde: parse schema file ${spec.schemaFile}: ${(err as Error).message}`,\n\t\t);\n\t}\n\n\tif (!parsed.input || !parsed.output) {\n\t\tthrow new Error(\n\t\t\t`serde: schema file ${spec.schemaFile} must have top-level \"input\" and \"output\" objects`,\n\t\t);\n\t}\n\n\tconst root = new protobuf.Root();\n\tconst inputType = buildType(root, \"Input\", firstMessage(parsed.input));\n\tconst outputType = buildType(root, \"Output\", firstMessage(parsed.output));\n\troot.add(inputType);\n\troot.add(outputType);\n\n\treturn {\n\t\tinput: typeToSerializer(inputType),\n\t\toutput: typeToSerializer(outputType),\n\t};\n}\n\n// firstMessage extracts the single message definition from { \"<MessageName>\": fields }.\n// Throws if the section is empty or has more than one entry — exactly one\n// message per input/output section is supported.\nfunction firstMessage(section: Record<string, SchemaFields>): SchemaFields {\n\tconst names = Object.keys(section);\n\tif (names.length !== 1) {\n\t\tthrow new Error(\n\t\t\t`serde: each of input/output must declare exactly one message, got ${names.length}`,\n\t\t);\n\t}\n\treturn section[names[0]!]!;\n}\n\n// buildType recursively constructs a protobufjs.Type from a SchemaFields tree.\nfunction buildType(\n\troot: protobuf.Root,\n\ttypeName: string,\n\tfields: SchemaFields,\n): protobuf.Type {\n\tconst type = new protobuf.Type(typeName);\n\tconst seenNumbers = new Set<number>();\n\n\tfor (const [name, field] of Object.entries(fields)) {\n\t\tif (typeof field.fieldNumber !== \"number\") {\n\t\t\tthrow new Error(\n\t\t\t\t`serde: field \"${name}\" missing required fieldNumber — schema evolution requires explicit numbers`,\n\t\t\t);\n\t\t}\n\t\tif (seenNumbers.has(field.fieldNumber)) {\n\t\t\tthrow new Error(\n\t\t\t\t`serde: duplicate fieldNumber ${field.fieldNumber} in ${typeName}`,\n\t\t\t);\n\t\t}\n\t\tseenNumbers.add(field.fieldNumber);\n\n\t\tif (field.type === \"object\") {\n\t\t\tif (!field.nested) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`serde: field \"${name}\" type=object requires nested fields`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst nestedTypeName = `${typeName}_${name}`;\n\t\t\tconst nestedType = buildType(root, nestedTypeName, field.nested);\n\t\t\troot.add(nestedType);\n\t\t\ttype.add(new protobuf.Field(name, field.fieldNumber, nestedTypeName));\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (field.type === \"array\") {\n\t\t\tif (!field.array) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`serde: field \"${name}\" type=array requires array spec`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (field.array.type === \"object\") {\n\t\t\t\tif (!field.array.nested) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`serde: array field \"${name}\" of objects requires nested fields`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst nestedTypeName = `${typeName}_${name}_elem`;\n\t\t\t\tconst nestedType = buildType(root, nestedTypeName, field.array.nested);\n\t\t\t\troot.add(nestedType);\n\t\t\t\ttype.add(\n\t\t\t\t\tnew protobuf.Field(\n\t\t\t\t\t\tname,\n\t\t\t\t\t\tfield.fieldNumber,\n\t\t\t\t\t\tnestedTypeName,\n\t\t\t\t\t\t\"repeated\",\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\ttype.add(\n\t\t\t\t\tnew protobuf.Field(\n\t\t\t\t\t\tname,\n\t\t\t\t\t\tfield.fieldNumber,\n\t\t\t\t\t\tfield.array.type,\n\t\t\t\t\t\t\"repeated\",\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Scalar.\n\t\ttype.add(new protobuf.Field(name, field.fieldNumber, field.type));\n\t}\n\n\treturn type;\n}\n\nfunction typeToSerializer(type: protobuf.Type): Serializer {\n\tconst jsonSchema = type.toJSON() as unknown as Record<string, unknown>;\n\t// Two-pass: build the serializer with a placeholder, then capture its own\n\t// hash via the shared algorithm. Per-serializer hash is informational only —\n\t// LB uses the SchemaPair hash from contract-hash.ts:computeContractHash.\n\tconst stub: Serializer = {\n\t\tencode: () => new Uint8Array(),\n\t\tdecode: () => null,\n\t\tcontractHash: () => \"\",\n\t\ttoJsonSchema: () => jsonSchema,\n\t};\n\tconst hash = computeSerializerHash(stub);\n\treturn {\n\t\tencode(value: unknown): Uint8Array {\n\t\t\tconst err = type.verify(value as object);\n\t\t\tif (err) {\n\t\t\t\tthrow new Error(`serde: encode ${type.name}: ${err}`);\n\t\t\t}\n\t\t\tconst msg = type.fromObject(value as object);\n\t\t\treturn type.encode(msg).finish();\n\t\t},\n\t\tdecode(bytes: Uint8Array): unknown {\n\t\t\tconst msg = type.decode(bytes);\n\t\t\treturn type.toObject(msg, { defaults: true });\n\t\t},\n\t\tcontractHash(): string {\n\t\t\treturn hash;\n\t\t},\n\t\ttoJsonSchema(): Record<string, unknown> {\n\t\t\treturn jsonSchema;\n\t\t},\n\t};\n}\n","import protobuf from \"protobufjs\";\nimport {\n\tbuildSchemaPairFromJsonFile,\n\ttype JsonSchemaFileSpec,\n} from \"./json-schema-serde\";\n\n// ProtoFileSpec references a user .proto file. `input`/`output` are optional —\n// when omitted, the SDK resolves them from the file's `service` definition by\n// matching the registered method name (gRPC-native, the only supported path).\n// Pass `input`/`output` explicitly for .proto files without a service block.\nexport interface ProtoFileSpec {\n\tprotoFile: string;\n\t// Optional: explicit message names. Required only when the .proto file has\n\t// no matching `service { rpc <method>(In) returns (Out); }` entry.\n\tinput?: string;\n\toutput?: string;\n\t// Optional: method name to resolve against the service definition. Defaults\n\t// to the name passed to `Handle.rpc`/`stream` (set automatically by Handle).\n\tmethod?: string;\n}\n\n// SchemaSpec is the public type for handler/caller schema declaration.\n// Two sources supported: .proto file or .schema.json file (with explicit\n// fieldNumber per property). See ./README.md and ./json-schema-serde.ts.\nexport type SchemaSpec = ProtoFileSpec | JsonSchemaFileSpec;\n\nfunction isProtoFileSpec(spec: SchemaSpec): spec is ProtoFileSpec {\n\treturn (spec as ProtoFileSpec).protoFile !== undefined;\n}\n\n// Serializer encodes/decodes a single Protobuf message type at runtime,\n// produced from a user-supplied .proto file via protobufjs.\nexport interface Serializer {\n\tencode(value: unknown): Uint8Array;\n\tdecode(bytes: Uint8Array): unknown;\n\tcontractHash(): string;\n\ttoJsonSchema(): Record<string, unknown>;\n}\n\nexport interface SchemaPair {\n\tinput: Serializer;\n\toutput: Serializer;\n}\n\n// buildSchemaPair dispatches to the correct loader based on SchemaSpec kind.\n// .proto files load via protobufjs.load (async); .schema.json files via\n// json-schema-serde (sync). Result is always a SchemaPair with stable contract\n// hashes.\nexport async function buildSchemaPair(spec: SchemaSpec): Promise<SchemaPair> {\n\tif (isProtoFileSpec(spec)) {\n\t\tlet root: protobuf.Root;\n\t\ttry {\n\t\t\troot = await protobuf.load(spec.protoFile);\n\t\t} catch (err) {\n\t\t\tthrow new Error(\n\t\t\t\t`serde: load proto file ${spec.protoFile}: ${(err as Error).message}`,\n\t\t\t);\n\t\t}\n\t\tconst { input, output } = resolveProtoMessages(root, spec);\n\t\treturn {\n\t\t\tinput: typeToSerializer(root, spec.protoFile, input),\n\t\t\toutput: typeToSerializer(root, spec.protoFile, output),\n\t\t};\n\t}\n\t// JsonSchemaFileSpec — synchronous file read + dynamic Type build.\n\treturn buildSchemaPairFromJsonFile(spec);\n}\n\n// resolveProtoMessages picks input/output message names from a ProtoFileSpec.\n// Resolution order:\n// 1. Explicit spec.input + spec.output → used as-is.\n// 2. spec.method provided + service { rpc <method>(In) returns (Out); } found\n// → take requestType/responseType from the service definition.\n//\n// Throws with a clear error otherwise — convention-based and unique-pair\n// fallbacks were removed (ADR 0001 / cleanup #32) because they hid contract\n// mistakes behind name similarity instead of failing loudly.\nfunction resolveProtoMessages(\n\troot: protobuf.Root,\n\tspec: ProtoFileSpec,\n): { input: string; output: string } {\n\tif (spec.input && spec.output) {\n\t\treturn { input: spec.input, output: spec.output };\n\t}\n\n\tconst method = spec.method;\n\tif (method) {\n\t\tconst fromService = findInService(root, method);\n\t\tif (fromService) return fromService;\n\t}\n\n\tthrow new Error(\n\t\t`serde: cannot resolve input/output for ${spec.protoFile}` +\n\t\t\t(method ? ` (method=${method})` : \"\") +\n\t\t\t\". Add a `service { rpc <method>(In) returns (Out); }` block or pass `input` and `output` explicitly.\",\n\t);\n}\n\nfunction findInService(\n\troot: protobuf.Root,\n\tmethod: string,\n): { input: string; output: string } | null {\n\tlet found: { input: string; output: string } | null = null;\n\twalk(root, (obj) => {\n\t\tif (!(obj instanceof protobuf.Service)) return;\n\t\tconst m = obj.methods[method];\n\t\tif (m) {\n\t\t\tfound = { input: m.requestType, output: m.responseType };\n\t\t}\n\t});\n\treturn found;\n}\n\nfunction walk(\n\tobj: protobuf.NamespaceBase,\n\tfn: (item: protobuf.ReflectionObject) => void,\n): void {\n\tfn(obj);\n\tconst nested = obj.nested;\n\tif (!nested) return;\n\tfor (const child of Object.values(nested)) {\n\t\tif (child instanceof protobuf.Namespace) {\n\t\t\twalk(child, fn);\n\t\t} else {\n\t\t\tfn(child);\n\t\t}\n\t}\n}\n\nfunction typeToSerializer(\n\troot: protobuf.Root,\n\tfile: string,\n\tmessageName: string,\n): Serializer {\n\tlet type: protobuf.Type;\n\ttry {\n\t\ttype = root.lookupType(messageName);\n\t} catch (err) {\n\t\tthrow new Error(\n\t\t\t`serde: message ${messageName} not found in ${file}: ${(err as Error).message}`,\n\t\t);\n\t}\n\n\tconst jsonSchema = type.toJSON() as unknown as Record<string, unknown>;\n\t// The per-serializer hash here is informational only; the cross-side\n\t// compatibility hash that LB filters on is computeContractHash(pair) from\n\t// ./contract-hash.ts, which combines input + output.\n\tconst hash = perSerializerHash(jsonSchema);\n\n\treturn {\n\t\tencode(value: unknown): Uint8Array {\n\t\t\tconst err = type.verify(value as object);\n\t\t\tif (err) {\n\t\t\t\tthrow new Error(`serde: encode ${messageName}: ${err}`);\n\t\t\t}\n\t\t\tconst msg = type.fromObject(value as object);\n\t\t\treturn type.encode(msg).finish();\n\t\t},\n\t\tdecode(bytes: Uint8Array): unknown {\n\t\t\tconst msg = type.decode(bytes);\n\t\t\treturn type.toObject(msg, { defaults: true });\n\t\t},\n\t\tcontractHash(): string {\n\t\t\treturn hash;\n\t\t},\n\t\ttoJsonSchema(): Record<string, unknown> {\n\t\t\treturn jsonSchema;\n\t\t},\n\t};\n}\n\n// perSerializerHash reuses the shared canonical-JSON algorithm from\n// contract-hash.ts so the per-serializer informational hash and the\n// SchemaPair compatibility hash stay in lockstep.\nimport { computeSerializerHash as sharedPerSerializerHash } from \"./contract-hash\";\n\nfunction perSerializerHash(descriptor: Record<string, unknown>): string {\n\t// Build a one-off Serializer-shaped object to reuse the shared algorithm.\n\treturn sharedPerSerializerHash({\n\t\tencode: () => new Uint8Array(),\n\t\tdecode: () => null,\n\t\tcontractHash: () => \"\",\n\t\ttoJsonSchema: () => descriptor,\n\t});\n}\n","import \"reflect-metadata\";\nimport * as grpc from \"@grpc/grpc-js\";\nimport { EventDomain } from \"../events/domain\";\nimport { Drainer } from \"../events/drainer\";\nimport type { SchemaIndex } from \"../events/publisher\";\nimport { Publisher } from \"../events/publisher\";\nimport type { EventHandler } from \"../events/subscriber\";\nimport { Subscriber } from \"../events/subscriber\";\nimport { JobDomain } from \"../job/domain\";\nimport { JobSubscriber } from \"../job/subscriber\";\nimport { ControlClient } from \"../pb/servicebridge/v1/control\";\nimport { EventsClient } from \"../pb/servicebridge/v1/events\";\nimport { JobsClient } from \"../pb/servicebridge/v1/jobs\";\nimport type {\n\tEventSubscriptionDescriptor,\n\tOutgoingCallDescriptor,\n\tPolicyEvaluation,\n\tRegistryClient,\n\tServiceInstanceInfo,\n} from \"../pb/servicebridge/v1/registry\";\nimport { RegistryClient as RegistryClientImpl } from \"../pb/servicebridge/v1/registry\";\nimport { TelemetryClient } from \"../pb/servicebridge/v1/telemetry\";\nimport { WorkflowsClient } from \"../pb/servicebridge/v1/workflows\";\nimport type { MethodDescriptor, ServiceDeps } from \"../registry/registry\";\nimport { MethodType, Registry } from \"../registry/registry\";\nimport { WatchStream } from \"../registry/watch\";\nimport { CircuitBreakerRegistry } from \"../rpc/circuit-breaker\";\nimport type { CallOpts } from \"../rpc/client\";\nimport { RpcClient, SchemaRegistry } from \"../rpc/client\";\nimport { DirectTransport } from \"../rpc/direct-transport\";\nimport { RpcDomain } from \"../rpc/domain\";\nimport { InstanceCache } from \"../rpc/instance-cache\";\nimport { LoadBalancer } from \"../rpc/lb\";\nimport { ProxyTransport } from \"../rpc/proxy-transport\";\nimport { type AdvertiseConfig, CallServer } from \"../rpc/server\";\nimport { extractServiceMethods, type TypedClient } from \"../rpc/typed-client\";\nimport { buildSchemaPair, type SchemaSpec } from \"../serde/serializer\";\nimport { Storage } from \"../sqlite/storage\";\nimport { currentTraceContext, runWithTrace } from \"../telemetry/context\";\nimport { type LogFields, makeLogger } from \"../telemetry/logs\";\nimport {\n\ttype Labels,\n\tmakeCounter,\n\tmakeGauge,\n\tmakeHistogram,\n} from \"../telemetry/metrics\";\nimport {\n\tChannel,\n\tOpHandle,\n\ttype StartOpParams,\n\tStatus,\n\tUserSubOp,\n} from \"../telemetry/ops\";\nimport {\n\ttype CaptureMode,\n\tDEFAULT_PAYLOAD_MAX_BYTES,\n} from \"../telemetry/payload-capture\";\nimport { ProcessSampler } from \"../telemetry/process-sampler\";\nimport { TelemetryRing } from \"../telemetry/ring\";\nimport { childContext } from \"../telemetry/trace-context\";\nimport {\n\tadaptTelemetryClient,\n\tTelemetryTransport,\n} from \"../telemetry/transport\";\nimport { formatXSbTrace, parseXSbTrace } from \"../telemetry/wire-trace\";\nimport { WorkflowDomain } from \"../workflow/domain\";\nimport { makeRuntimeOps } from \"../workflow/runtime-ops\";\nimport { WorkflowSubscriber } from \"../workflow/subscriber\";\nimport type { Step } from \"../workflow/types\";\nimport { parseBootstrapKey } from \"./key\";\nimport { derToPem } from \"./pem\";\nimport type { ProvisionResult } from \"./provision\";\nimport { provision as defaultProvision, refresh } from \"./provision\";\nimport { isRetryable, ServiceBridgeError } from \"./service-bridge-error\";\nimport type { SessionCallbacks } from \"./session\";\nimport { openControlStream, Session } from \"./session\";\n\nexport type { ServiceInstanceInfo } from \"../pb/servicebridge/v1/registry\";\nexport type {\n\tMethodDescriptor,\n\tMethodType,\n\tRpcHandlerOpts,\n\tServiceDeps,\n\tWorkflowHandlerOpts,\n} from \"../registry/registry\";\n\n/**\n * Entry в карте `sb.serviceMap()`. Группирует видимые caller'у методы сервиса\n * (`methods`) и его текущих живых инстансов с их endpoint'ами (`instances`).\n * `httpEndpoint` поле каждого инстанса — публичный HTTP host:port пользователя\n * (ADR 0001), пустая строка если у инстанса нет HTTP-интеграции.\n */\nexport interface ServiceMapEntry {\n\tmethods: MethodDescriptor[];\n\tinstances: ServiceInstanceInfo[];\n\t// ADR-0014 service-map enrichment (populated for caller's own service +\n\t// services in caller's outgoing-dep scope). Empty arrays when the runtime\n\t// doesn't carry that info for this service in the current snapshot.\n\teventSubscriptions: EventSubscriptionDescriptor[];\n\toutgoingCalls: OutgoingCallDescriptor[];\n}\nexport type { CallOpts } from \"../rpc/client\";\nexport type { AdvertiseConfig } from \"../rpc/server\";\nexport type { SchemaSpec } from \"../serde/serializer\";\n\n// Reconnect configuration.\nconst RECONNECT_INTERVAL_MS = 3_000;\nconst RECONNECT_ATTEMPTS = 3; // 0 = unlimited\n\n// Events defaults (overridden via ServiceBridgeOptions in ensureRpcReady).\nconst DEFAULT_MAX_OUTBOX_ROWS = 100_000;\nconst DEFAULT_DRAINER_BATCH = 50;\nconst DEFAULT_EVENTS_MAX_IN_FLIGHT = 32;\n// Default telemetry ops-ring byte budget. Override via\n// ServiceBridgeOptions.telemetryRingSize. Sized for the dense USER.SUBOP\n// step-span emission of a workflow run between flush ticks (≈800 op frames).\nconst DEFAULT_TELEMETRY_RING_SIZE = 256 * 1024;\n// Refresh cert 30 minutes before expiry.\nconst CERT_REFRESH_LEAD_MS = 30 * 60 * 1000;\n// Random offset added to the refresh delay to spread herd of N clients across a\n// window. With 10k clients started in lockstep this turns a 10k-RPS spike at\n// T+30min into ~8 RPS smeared across a 5-minute window.\nconst CERT_REFRESH_JITTER_MS = 5 * 60 * 1000;\n// During overlap rotation, wait at most this long for the new session to\n// produce a Welcome before closing the old session. With heartbeats removed\n// from Control, Welcome on the new stream is the only liveness signal.\nconst ROTATION_HANDSHAKE_TIMEOUT_MS = 10_000;\n\n// randomJitter returns an integer in [0, maxMs); 0 if maxMs <= 0.\n// Math.random is sufficient for load-spreading; not for security timing.\nfunction randomJitter(maxMs: number): number {\n\tif (maxMs <= 0) return 0;\n\treturn Math.floor(Math.random() * maxMs);\n}\n\n/**\n * Build the TelemetryAPI surface. Identity is resolved lazily so user code\n * may emit before start() — instance_id will be the empty string until the\n * first Welcome.\n * @internal\n */\nfunction makeTelemetryAPI(\n\tring: TelemetryRing,\n\tgetInstanceId: () => string,\n\tgetServiceId: () => string,\n\tgetCaptureModeForChannel: (channel: Channel) => CaptureMode,\n\tpayloadMaxBytes: number,\n): TelemetryAPI {\n\tconst log = makeLazyLogger(ring, getInstanceId);\n\treturn {\n\t\tstartOp(params) {\n\t\t\treturn OpHandle.start(ring, {\n\t\t\t\t...params,\n\t\t\t\teffectiveCaptureMode: getCaptureModeForChannel(params.channel),\n\t\t\t\tpayloadMaxBytes,\n\t\t\t});\n\t\t},\n\t\tcaptureModeForChannel: getCaptureModeForChannel,\n\t\tlog,\n\t\tcounter(name, labels) {\n\t\t\treturn makeCounter(ring, getInstanceId(), name, labels);\n\t\t},\n\t\tgauge(name, labels) {\n\t\t\treturn makeGauge(ring, getInstanceId(), name, labels);\n\t\t},\n\t\thistogram(name, unit, labels) {\n\t\t\treturn makeHistogram(ring, getInstanceId(), name, unit, labels);\n\t\t},\n\t};\n}\n\n/**\n * Lazy logger that resolves instanceId at emission time so logs published\n * after Welcome carry the correct identity even if the logger handle was\n * captured during construction.\n * @internal\n */\nfunction makeLazyLogger(\n\tring: TelemetryRing,\n\tgetInstanceId: () => string,\n): ReturnType<typeof makeLogger> {\n\tconst emit = (level: \"debug\" | \"info\" | \"warn\" | \"error\") => {\n\t\treturn (message: string, fields?: LogFields) => {\n\t\t\tmakeLogger(ring, getInstanceId())[level](message, fields);\n\t\t};\n\t};\n\treturn {\n\t\tdebug: emit(\"debug\"),\n\t\tinfo: emit(\"info\"),\n\t\twarn: emit(\"warn\"),\n\t\terror: emit(\"error\"),\n\t};\n}\n\n// mergeOpts combines two CallOpts where the per-call override wins. Used by\n// the typed client to layer { client-default ← per-call } on top of the\n// global ServiceBridge.callDefaults already applied by sb.rpc.call / sb.stream.\nfunction mergeOpts(base?: CallOpts, override?: CallOpts): CallOpts | undefined {\n\tif (!base && !override) return undefined;\n\treturn { ...(base ?? {}), ...(override ?? {}) };\n}\n\n// resolveAdvertise turns the user-provided advertise option into the\n// effective AdvertiseConfig the SDK will use, or null for caller-only.\n//\n// Resolution order:\n// 1. `false` → null (caller-only, no inbound server)\n// 2. explicit { host, port } → used as-is\n// 3. fallback → { host: \"127.0.0.1\", port: 0 } + console warn\n// (suitable for local dev; the loopback address is not reachable from\n// other hosts — pass { advertise: { host, port } } in containers / k8s).\nfunction resolveAdvertise(\n\tprovided: AdvertiseConfig | false | undefined,\n): AdvertiseConfig | null {\n\tif (provided === false) return null;\n\tif (provided) return provided;\n\tconsole.warn(\n\t\t\"[ServiceBridge] advertise not configured — falling back to 127.0.0.1. \" +\n\t\t\t\"Pass { advertise: { host, port } } for cross-host reachability.\",\n\t);\n\treturn { host: \"127.0.0.1\", port: 0 };\n}\n\n/**\n * TelemetryAPI is the public surface for emitting telemetry from user code\n * and from internal subsystems (RPC, HTTP plugins, events, workflow, jobs).\n *\n * @public — см. ../telemetry/README.md\n */\nexport interface TelemetryAPI {\n\t/** Start an op; returns a handle to `.end(status, message?)`. */\n\tstartOp(params: StartOpParams): OpHandle;\n\t/**\n\t * Runtime-pushed effective payload capture mode for the given op channel.\n\t * \"none\" until the first registry snapshot arrives (fail-safe). Read-only\n\t * introspection — capture itself is applied automatically inside startOp.\n\t */\n\tcaptureModeForChannel(channel: Channel): CaptureMode;\n\tlog: ReturnType<typeof makeLogger>;\n\tcounter(name: string, labels?: Labels): ReturnType<typeof makeCounter>;\n\tgauge(name: string, labels?: Labels): ReturnType<typeof makeGauge>;\n\thistogram(\n\t\tname: string,\n\t\tunit?: string,\n\t\tlabels?: Labels,\n\t): ReturnType<typeof makeHistogram>;\n}\n\nexport interface ConnectedEvent {\n\tsessionId: string;\n\tserviceId: string;\n\tserviceName: string;\n}\n\n/**\n * Identity of the current live session. Populated on Welcome (start + every\n * successful overlap rotation), cleared on stop / stream end. Read via\n * `ServiceBridge.identity()`.\n */\nexport interface Identity {\n\tsessionId: string;\n\tserviceId: string;\n\tserviceName: string;\n\tinstanceId: string;\n}\n\nexport interface ReconnectingEvent {\n\tattempt: number;\n\tdelayMs: number;\n\treason: string;\n}\n\nexport interface DisconnectedEvent {\n\treason: string;\n\terror?: ServiceBridgeError;\n}\n\n/**\n * One violation reported by the runtime in `RegistrySnapshot.policy.warnings`.\n * Emitted via `sb.on(\"policy_violation\", ...)` and logged via console.warn.\n *\n * Fields mirror `pb.PolicyViolation`:\n *\n * - `declaration` — what was declared, e.g. `rpc.call`, `event.handle`,\n * `event.publish`, `rpc.handle` (capability).\n * - `value` — concrete value, e.g. `payments/charge`, `orders.*`.\n * - `denySide` — `capability` | `self_egress` | `self_acceptance` | `peer_acceptance`.\n * - `reason` — human-readable explanation from the runtime.\n */\nexport interface PolicyViolationEvent {\n\tdeclaration: string;\n\tvalue: string;\n\tdenySide: string;\n\treason: string;\n}\n\ntype EventMap = {\n\tconnected: ConnectedEvent;\n\treconnecting: ReconnectingEvent;\n\tdisconnected: DisconnectedEvent;\n\t/**\n\t * Fired once per warning when the runtime sends a PolicyEvaluation in the\n\t * registry snapshot (after `start()` or after operator changes policy).\n\t */\n\tpolicy_violation: PolicyViolationEvent;\n};\n\ntype Handler<K extends keyof EventMap> = (event: EventMap[K]) => void;\n\n/** Public configuration. Documented in `./README.md` (Public contract). */\nexport interface ServiceBridgeOptions {\n\treconnectIntervalMs?: number;\n\treconnectAttempts?: number;\n\t/**\n\t * Advertise config for the inbound Call RPC server.\n\t *\n\t * - `{ host, port }` — explicit (recommended for prod, required in k8s with POD_IP)\n\t * - `undefined` (default) — bind \"127.0.0.1\" on a free port. Local dev\n\t * friendly; logs a warning when falling back to loopback so cross-host\n\t * limitations are visible.\n\t * - `false` — explicit caller-only mode: do not bind any inbound server.\n\t * Set this when you know the instance never serves RPC.\n\t */\n\tadvertise?: AdvertiseConfig | false;\n\t/**\n\t * Default options applied to every `sb.rpc.call()` unless overridden.\n\t */\n\tcallDefaults?: CallOpts;\n\t/**\n\t * ADR-0014: when `true`, any policy violation reported by the runtime in\n\t * the registry snapshot's `PolicyEvaluation.warnings` makes `start()`\n\t * surface a `disconnected` event with reason='policy' and the SDK stops.\n\t * Default `false` — warnings only (logged via console.warn + emitted as\n\t * `policy_violation` events).\n\t */\n\tfailOnPolicyViolation?: boolean;\n\t/**\n\t * Emit telemetry (ops, logs, metrics) to the runtime. `false` fully disables\n\t * the telemetry transport — the ring still buffers but nothing is drained.\n\t * Default `true`.\n\t */\n\ttelemetry?: boolean;\n\t/** Ops-ring byte budget. Default 262144 (256 KiB). */\n\ttelemetryRingSize?: number;\n\t/** Local SQLite outbox directory. Default \"./.servicebridge\". */\n\tdataDir?: string;\n\t/** Max rows kept in the event outbox before publish back-pressures. Default 100000. */\n\tmaxOutboxRows?: number;\n\t/** Rows the events drainer pulls per tick. Default 50. */\n\teventsDrainerBatch?: number;\n\t/** Max in-flight inbound events the subscriber processes concurrently. Default 32. */\n\teventsMaxInFlight?: number;\n\t/** Per-direction captured-payload byte cap. Default 65536. */\n\tpayloadMaxBytes?: number;\n}\n\n/**\n * @internal см. ./README.md\n */\ninterface ServiceBridgeInternalHooks extends ServiceBridgeOptions {\n\tcertRefreshLeadMs?: number;\n\tcertRefreshJitterMs?: number;\n\trotationHandshakeTimeoutMs?: number;\n\tprovisionFn?: typeof defaultProvision;\n\trefreshFn?: typeof refresh;\n\tclientFactory?: (\n\t\turl: string,\n\t\tcreds: grpc.ChannelCredentials,\n\t) => ControlClient;\n\tregistryClientFactory?: (\n\t\turl: string,\n\t\tcreds: grpc.ChannelCredentials,\n\t) => RegistryClient;\n}\n\ninterface ResolvedOptions {\n\treconnectIntervalMs: number;\n\treconnectAttempts: number;\n\tcertRefreshLeadMs: number;\n\tcertRefreshJitterMs: number;\n\trotationHandshakeTimeoutMs: number;\n\tprovisionFn: typeof defaultProvision;\n\trefreshFn: typeof refresh;\n\tclientFactory: (url: string, creds: grpc.ChannelCredentials) => ControlClient;\n\tregistryClientFactory: (\n\t\turl: string,\n\t\tcreds: grpc.ChannelCredentials,\n\t) => RegistryClient;\n\tadvertise: AdvertiseConfig | null;\n\tcallDefaults: CallOpts;\n\tfailOnPolicyViolation: boolean;\n\ttelemetry: boolean;\n\ttelemetryRingSize: number;\n\tdataDir: string;\n\tmaxOutboxRows: number;\n\teventsDrainerBatch: number;\n\teventsMaxInFlight: number;\n\tpayloadMaxBytes: number;\n}\n\n/**\n * ServiceBridge manages the full connection lifecycle:\n * 1. Parse the bootstrap key.\n * 2. Provision (Bootstrap.Provision) to get a leaf cert.\n * 3. Open a mTLS gRPC channel with the cert.\n * 4. Open (Control.Open) for the server-streamed Welcome / Drain signals.\n * 5. Auto-reconnect with configurable attempts.\n * 6. Cert rotation: overlap — new channel up AND Welcome received on the new\n * stream before closing the old stream.\n */\nexport class ServiceBridge {\n\tprivate readonly url: string;\n\tprivate readonly rawKey: string;\n\tprivate readonly opts: ResolvedOptions;\n\tprivate readonly handlers = new Map<\n\t\tkeyof EventMap,\n\t\tHandler<keyof EventMap>[]\n\t>();\n\tprivate stopped = false;\n\tprivate session: Session | null = null;\n\tprivate controlClient: ControlClient | null = null;\n\tprivate lastProvision: ProvisionResult | null = null;\n\tprivate certRefreshTimer: ReturnType<typeof setTimeout> | null = null;\n\tprivate currentIdentity: Identity | null = null;\n\n\tprivate readonly _registry: Registry = new Registry(() =>\n\t\tthis.onRegistrationChanged(),\n\t);\n\tprivate readonly _watchStream = new WatchStream();\n\tprivate readonly _instanceCache = new InstanceCache();\n\tprivate readonly _schemaRegistry = new SchemaRegistry();\n\tprivate _started = false;\n\tprivate _callServer: CallServer | null = null;\n\tprivate _proxyTransport: ProxyTransport | null = null;\n\tprivate _directTransport: DirectTransport | null = null;\n\tprivate _rpcClient: RpcClient | null = null;\n\tprivate readonly _cb = new CircuitBreakerRegistry();\n\tprivate readonly _lb = new LoadBalancer(this._cb);\n\n\t// Events infrastructure — lazy init in ensureRpcReady after storage is open.\n\tprivate _eventsClient: EventsClient | null = null;\n\tprivate _storage: Storage | null = null;\n\tprivate _publisher: Publisher | null = null;\n\tprivate _drainer: Drainer | null = null;\n\tprivate _subscriber: Subscriber | null = null;\n\n\t// Workflows infrastructure — lazy init in ensureRpcReady. Subscriber only\n\t// started when service has at least one workflow handler registered.\n\tprivate _workflowsClient: WorkflowsClient | null = null;\n\tprivate _workflowSubscriber: WorkflowSubscriber | null = null;\n\n\t// Jobs infrastructure — lazy init in ensureRpcReady. Subscriber started\n\t// on first Welcome when at least one job is registered.\n\tprivate _jobsClient: JobsClient | null = null;\n\tprivate _jobSubscriber: JobSubscriber | null = null;\n\n\t// Telemetry infrastructure — лежит на самом ServiceBridge, потому что её\n\t// lifecycle совпадает с lifecycle сессии (Welcome → start, stop → close).\n\t// Ring создаётся в конструкторе, чтобы prod-код мог писать логи / ops до\n\t// подключения; они буферятся в ring до старта transport'а. SDK всегда\n\t// flushes (ADR-0008); единственный off-switch — option telemetry: false,\n\t// который полностью отключает создание transport.\n\tprivate readonly _telemetryEnabled: boolean;\n\tprivate readonly _telemetryRing: TelemetryRing;\n\tprivate readonly _telemetryApi: TelemetryAPI;\n\tprivate _telemetryClient: TelemetryClient | null = null;\n\tprivate _telemetryTransport: TelemetryTransport | null = null;\n\tprivate _processSampler: ProcessSampler | null = null;\n\tprivate _telemetryInstanceId = \"\";\n\t// SchemaIndex adapter — single source of truth lives on Handle._published.\n\t// Publisher and Subscriber both read through this adapter; entries appear\n\t// after event.define(name, spec) resolves its async schema load in\n\t// Registry._handle.finalize() (called by start()).\n\tprivate readonly _schemaIndexAdapter: SchemaIndex = {\n\t\tget: (name: string) =>\n\t\t\tthis._registry._handle.getPublishedEvent(name) as ReturnType<\n\t\t\t\tSchemaIndex[\"get\"]\n\t\t\t>,\n\t};\n\n\t/** RPC domain — incoming handlers and outgoing calls. */\n\treadonly rpc: RpcDomain;\n\n\t/** Event domain — define published events, subscribe, publish. */\n\treadonly event: EventDomain;\n\n\t/** Workflow domain — register workflow handlers (stub; full impl in workflows.md). */\n\treadonly workflow: WorkflowDomain;\n\n\t/** Job domain — register scheduled job handlers via `.handle(name, opts, fn)`. */\n\treadonly job: JobDomain;\n\n\t/** Declares outgoing dependencies (rpc/workflows/http). Call before start(). */\n\tservice(serviceName: string, deps: ServiceDeps): void {\n\t\tthis._registry.service(serviceName, deps);\n\t}\n\n\tconstructor(\n\t\turl: string,\n\t\tkey: string,\n\t\toptions: ServiceBridgeOptions | ServiceBridgeInternalHooks = {},\n\t) {\n\t\tthis.url = url;\n\t\tthis.rawKey = key;\n\t\tconst hooks = options as ServiceBridgeInternalHooks;\n\t\tthis.opts = {\n\t\t\treconnectIntervalMs: options.reconnectIntervalMs ?? RECONNECT_INTERVAL_MS,\n\t\t\treconnectAttempts: options.reconnectAttempts ?? RECONNECT_ATTEMPTS,\n\t\t\tcertRefreshLeadMs: hooks.certRefreshLeadMs ?? CERT_REFRESH_LEAD_MS,\n\t\t\tcertRefreshJitterMs: hooks.certRefreshJitterMs ?? CERT_REFRESH_JITTER_MS,\n\t\t\trotationHandshakeTimeoutMs:\n\t\t\t\thooks.rotationHandshakeTimeoutMs ?? ROTATION_HANDSHAKE_TIMEOUT_MS,\n\t\t\tprovisionFn: hooks.provisionFn ?? defaultProvision,\n\t\t\trefreshFn: hooks.refreshFn ?? refresh,\n\t\t\tclientFactory: hooks.clientFactory ?? ((u, c) => new ControlClient(u, c)),\n\t\t\tregistryClientFactory:\n\t\t\t\thooks.registryClientFactory ?? ((u, c) => new RegistryClientImpl(u, c)),\n\t\t\tadvertise: resolveAdvertise(options.advertise),\n\t\t\tcallDefaults: options.callDefaults ?? {},\n\t\t\tfailOnPolicyViolation: options.failOnPolicyViolation ?? false,\n\t\t\ttelemetry: options.telemetry ?? true,\n\t\t\ttelemetryRingSize:\n\t\t\t\toptions.telemetryRingSize ?? DEFAULT_TELEMETRY_RING_SIZE,\n\t\t\tdataDir: options.dataDir ?? \"./.servicebridge\",\n\t\t\tmaxOutboxRows: options.maxOutboxRows ?? DEFAULT_MAX_OUTBOX_ROWS,\n\t\t\teventsDrainerBatch: options.eventsDrainerBatch ?? DEFAULT_DRAINER_BATCH,\n\t\t\teventsMaxInFlight:\n\t\t\t\toptions.eventsMaxInFlight ?? DEFAULT_EVENTS_MAX_IN_FLIGHT,\n\t\t\tpayloadMaxBytes: options.payloadMaxBytes ?? DEFAULT_PAYLOAD_MAX_BYTES,\n\t\t};\n\n\t\t// Telemetry wiring (ADR-0008). Ring is owned by the bridge so user code\n\t\t// may emit logs/ops/metrics before start(); they buffer in the ring and\n\t\t// the transport drains once it's up.\n\t\tthis._telemetryEnabled = this.opts.telemetry;\n\t\t// telemetryRingSize sets the ops ring byte budget (the kind under burst\n\t\t// pressure from dense workflow step-span emission). The ring's own per-kind\n\t\t// defaults apply when the value is non-finite or non-positive.\n\t\tconst opsBudget = this.opts.telemetryRingSize;\n\t\tthis._telemetryRing = new TelemetryRing(\n\t\t\tNumber.isFinite(opsBudget) && opsBudget > 0\n\t\t\t\t? { ops: opsBudget }\n\t\t\t\t: undefined,\n\t\t);\n\n\t\t// Telemetry API surface. Identity fields are resolved lazily — user code\n\t\t// may call sb.telemetry.log() before start(), in which case instance_id\n\t\t// will be empty (best-effort). After Welcome, all subsequent emits carry\n\t\t// the real instanceId from currentIdentity.\n\t\tthis._telemetryApi = makeTelemetryAPI(\n\t\t\tthis._telemetryRing,\n\t\t\t() => this._telemetryInstanceId,\n\t\t\t() => this.currentIdentity?.serviceId ?? \"\",\n\t\t\t(channel) => this._watchStream.captureModeForChannel(channel),\n\t\t\tthis.opts.payloadMaxBytes,\n\t\t);\n\n\t\t// Wire domain namespaces with lazy transport access. Call-time policy\n\t\t// denials (rpc.call / workflow.run / event.publish gates) are surfaced\n\t\t// through the same `policy_violation` channel as registration warnings.\n\t\tconst onPolicyViolation = (v: PolicyViolationEvent) =>\n\t\t\tthis.emitPolicyViolation(v);\n\t\tthis.rpc = new RpcDomain(\n\t\t\tthis._registry,\n\t\t\t() => this._rpcClient,\n\t\t\tonPolicyViolation,\n\t\t);\n\t\tthis.event = new EventDomain(this._registry, () => this._publisher);\n\t\tthis.workflow = new WorkflowDomain(this._registry, onPolicyViolation);\n\t\tthis.job = new JobDomain(this._registry);\n\t}\n\n\t/**\n\t * Surface a policy denial uniformly: log via console.warn and emit\n\t * `policy_violation`. Shared by the registration evaluation (gate #0\n\t * warnings) and call-time denials (rpc.call / workflow.run / event.publish).\n\t */\n\tprivate emitPolicyViolation(v: PolicyViolationEvent): void {\n\t\tconsole.warn(\n\t\t\t`[ServiceBridge] policy violation: ${v.declaration} ${v.value} ` +\n\t\t\t\t`(deny side: ${v.denySide}) — ${v.reason}`,\n\t\t);\n\t\tthis.emit(\"policy_violation\", v);\n\t}\n\n\t/**\n\t * Route collector — для использования ТОЛЬКО HTTP-интеграциями\n\t * (`servicebridge/express`, `servicebridge/fastify`, `servicebridge/hono`).\n\t * Прикладной код не вызывает это напрямую: роуты живут в Express/Fastify/Hono.\n\t * См. ADR 0001 и userDocs/integrations.md.\n\t */\n\tget routes() {\n\t\treturn this._registry.routes;\n\t}\n\n\t/**\n\t * Telemetry API surface — emit ops, logs, metrics from user code.\n\t * Resources buffer in the ring before start(); the transport drains once\n\t * Welcome arrives. parent_op_id/trace_id are inherited from the active\n\t * ALS TraceContext.\n\t *\n\t * @public — см. ../telemetry/README.md\n\t */\n\tget telemetry(): TelemetryAPI {\n\t\treturn this._telemetryApi;\n\t}\n\n\t/**\n\t * Structured logger — auto-injects instance_id and trace_id/op_id from the\n\t * active context. Kept as a top-level convenience surface; equivalent to\n\t * `sb.telemetry.log`.\n\t */\n\tget logger() {\n\t\treturn this._telemetryApi.log;\n\t}\n\n\t/**\n\t * Instance ID текущей сессии (`telemetry_spans.instance_id`) — 12-символьная\n\t * Crockford-base32 строка. До `start()` / до первого RegisterResponse\n\t * возвращает пустую строку. Используется HTTP-плагинами для автотрейсинга.\n\t * @public\n\t */\n\tinstanceIdString(): string {\n\t\treturn this._telemetryInstanceId;\n\t}\n\n\t/**\n\t * Дёргается `RouteCollector.publishHttp(...)` после `sb.start()`, когда\n\t * интеграция узнала фактический host:port HTTP-сервера и хочет, чтобы\n\t * runtime увидел его моментально (а не ждал natural reconnect).\n\t *\n\t * Безопасно если `start()` ещё не вызван — endpoint просто оседает в\n\t * Registry и попадёт в первый RegisterRequest.\n\t */\n\tprivate onRegistrationChanged(): void {\n\t\tif (!this._started) return;\n\t\tif (this.stopped) return;\n\t\tthis.session?.updateRegistration(this._registry.buildRegisterRequest());\n\t}\n\n\ton<K extends keyof EventMap>(event: K, handler: Handler<K>): this {\n\t\tconst list = this.handlers.get(event) ?? [];\n\t\tlist.push(handler as Handler<keyof EventMap>);\n\t\tthis.handlers.set(event, list);\n\t\treturn this;\n\t}\n\n\tasync start(): Promise<void> {\n\t\tthis.stopped = false;\n\t\tthis._started = true;\n\t\t// Finalize any pending RPC handler schema loads before sending RegisterRequest.\n\t\tawait this._registry._handle.finalize();\n\n\t\t// Open local SQLite outbox before connecting — drainer needs storage ready.\n\t\tif (!this._storage) {\n\t\t\tthis._storage = Storage.open({ dataDir: this.opts.dataDir });\n\t\t}\n\n\t\t// Start the inbound Call server if advertise is configured. We need the\n\t\t// runtime-issued leaf cert + CA chain — those arrive from Bootstrap.Provision\n\t\t// during connect(). Defer the actual bind until we have a ProvisionResult.\n\t\tthis._instanceCache.bind(this._watchStream);\n\t\tthis._proxyTransport = null;\n\t\tthis._directTransport = null;\n\t\tthis._rpcClient = null;\n\n\t\tawait this.connect(1);\n\t}\n\n\tasync stop(): Promise<void> {\n\t\tthis.stopped = true;\n\t\tthis._started = false;\n\t\tthis.clearTimers();\n\t\tthis._watchStream.stop();\n\t\tthis.session?.close();\n\t\tthis.session = null;\n\t\tthis.currentIdentity = null;\n\t\tthis._instanceCache.dispose();\n\t\tif (this._callServer) {\n\t\t\tawait this._callServer.stop();\n\t\t\tthis._callServer = null;\n\t\t}\n\t\tthis._proxyTransport?.close();\n\t\tthis._proxyTransport = null;\n\t\tthis._directTransport?.close();\n\t\tthis._directTransport = null;\n\t\tthis._rpcClient = null;\n\n\t\t// Telemetry teardown — before events teardown so any final logs from\n\t\t// drainer/subscriber/storage close paths still have a sink (best-effort).\n\t\tif (this._processSampler) {\n\t\t\tthis._processSampler.close();\n\t\t\tthis._processSampler = null;\n\t\t}\n\t\tif (this._telemetryTransport) {\n\t\t\tawait this._telemetryTransport.stop();\n\t\t\tthis._telemetryTransport = null;\n\t\t}\n\t\tif (this._telemetryClient) {\n\t\t\tthis._telemetryClient.close();\n\t\t\tthis._telemetryClient = null;\n\t\t}\n\n\t\t// Workflows teardown: subscriber → client. Subscriber owns the heartbeat\n\t\t// timers and the long-lived Subscribe stream; close() stops both.\n\t\tif (this._workflowSubscriber) {\n\t\t\tthis._workflowSubscriber.close();\n\t\t\tthis._workflowSubscriber = null;\n\t\t}\n\t\tif (this._workflowsClient) {\n\t\t\tthis._workflowsClient.close();\n\t\t\tthis._workflowsClient = null;\n\t\t}\n\n\t\t// Jobs teardown: subscriber → client.\n\t\tif (this._jobSubscriber) {\n\t\t\tawait this._jobSubscriber.stop();\n\t\t\tthis._jobSubscriber = null;\n\t\t}\n\t\tif (this._jobsClient) {\n\t\t\tthis._jobsClient.close();\n\t\t\tthis._jobsClient = null;\n\t\t}\n\n\t\t// Events teardown: subscriber → drainer → events client → storage.\n\t\tif (this._subscriber) {\n\t\t\tawait this._subscriber.stop();\n\t\t\tthis._subscriber = null;\n\t\t}\n\t\tif (this._drainer) {\n\t\t\tawait this._drainer.stop();\n\t\t\tthis._drainer = null;\n\t\t}\n\t\tif (this._eventsClient) {\n\t\t\tthis._eventsClient.close();\n\t\t\tthis._eventsClient = null;\n\t\t}\n\t\tif (this._storage) {\n\t\t\tthis._storage.close();\n\t\t\tthis._storage = null;\n\t\t}\n\t\tthis._publisher = null;\n\t}\n\n\t/**\n\t * Registers a SchemaPair on the caller side for the given (service, method).\n\t * Must be called before `sb.rpc.call()` is invoked for that method. The schema\n\t * MUST match the one used by the target service (same .proto file).\n\t *\n\t * For an ergonomic alternative that handles dependency declaration, schema\n\t * loading and typed method calls in one shot — see `client()`.\n\t */\n\tasync useSchema(\n\t\tserviceName: string,\n\t\tmethodName: string,\n\t\tspec: SchemaSpec,\n\t): Promise<void> {\n\t\tconst pair = await buildSchemaPair({\n\t\t\t...spec,\n\t\t\t// Propagate method into ProtoFileSpec so service-block auto-resolution\n\t\t\t// can find the right request/response types.\n\t\t\t...(\"protoFile\" in spec && !spec.method ? { method: methodName } : {}),\n\t\t} as SchemaSpec);\n\t\tthis._schemaRegistry.set(serviceName, methodName, pair);\n\t}\n\n\t/**\n\t * High-level typed caller: reads the `.proto` file once, registers all\n\t * methods in its `service` block as outgoing dependencies, loads schemas,\n\t * and returns a proxy object with typed method calls.\n\t *\n\t * ```ts\n\t * const payment = await sb.client(\"payment-svc\", \"./payment.proto\");\n\t * await sb.start();\n\t * const res = await payment.Charge({ userId: \"u\", amount: 100 });\n\t *\n\t * // streaming method auto-detected from `rpc Generate(...) returns (stream Chunk)`\n\t * for await (const chunk of payment.Generate({ prompt: \"...\" })) { ... }\n\t * ```\n\t *\n\t * Must be called BEFORE `start()` — declared dependencies are sent in the\n\t * initial RegisterRequest. Pass `methods` to bind only a subset; otherwise\n\t * every method in any service block is exposed.\n\t */\n\tasync client(\n\t\tserviceName: string,\n\t\tprotoFile: string,\n\t\topts?: { methods?: string[]; callDefaults?: CallOpts },\n\t): Promise<TypedClient> {\n\t\tconst all = await extractServiceMethods(protoFile);\n\t\tconst allowed = opts?.methods ? new Set(opts.methods) : null;\n\t\tconst selected = allowed ? all.filter((m) => allowed.has(m.name)) : all;\n\t\tif (selected.length === 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`rpc: client(${serviceName}, ${protoFile}): no methods to bind`,\n\t\t\t);\n\t\t}\n\n\t\t// Register outgoing dependency for each method.\n\t\tthis._registry.service(serviceName, {\n\t\t\trpc: selected.map((m) => m.name),\n\t\t});\n\n\t\t// Load schema for every method up front.\n\t\tfor (const m of selected) {\n\t\t\tconst pair = await buildSchemaPair({\n\t\t\t\tprotoFile,\n\t\t\t\tinput: m.requestType,\n\t\t\t\toutput: m.responseType,\n\t\t\t});\n\t\t\tthis._schemaRegistry.set(serviceName, m.name, pair);\n\t\t}\n\n\t\tconst proxy = {} as Record<string, unknown>;\n\t\tfor (const m of selected) {\n\t\t\tif (m.responseStream) {\n\t\t\t\tproxy[m.name] = (req: unknown, callOpts?: CallOpts) =>\n\t\t\t\t\tthis.stream(\n\t\t\t\t\t\tserviceName,\n\t\t\t\t\t\tm.name,\n\t\t\t\t\t\treq,\n\t\t\t\t\t\tmergeOpts(opts?.callDefaults, callOpts),\n\t\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tproxy[m.name] = (req: unknown, callOpts?: CallOpts) =>\n\t\t\t\t\tthis.rpc.call(\n\t\t\t\t\t\tserviceName,\n\t\t\t\t\t\tm.name,\n\t\t\t\t\t\treq,\n\t\t\t\t\t\tmergeOpts(opts?.callDefaults, callOpts),\n\t\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\treturn proxy as TypedClient;\n\t}\n\n\t/**\n\t * Server-side streaming RPC. Returns an AsyncIterable of decoded chunks.\n\t * Cancelling the for-await loop (break/return) closes the underlying gRPC\n\t * stream which propagates to the callee.\n\t */\n\tstream<Req = unknown, Chunk = unknown>(\n\t\tserviceName: string,\n\t\tmethodName: string,\n\t\tpayload: Req,\n\t\topts?: CallOpts,\n\t): AsyncIterable<Chunk> {\n\t\tif (!this._rpcClient) {\n\t\t\tthrow new Error(\n\t\t\t\t\"ServiceBridge: rpc client not ready — call start() and wait for 'connected' event before calling sb.stream()\",\n\t\t\t);\n\t\t}\n\t\tconst merged: CallOpts = { ...this.opts.callDefaults, ...(opts ?? {}) };\n\t\treturn this._rpcClient.stream<Req, Chunk>(\n\t\t\tserviceName,\n\t\t\tmethodName,\n\t\t\tpayload,\n\t\t\tmerged,\n\t\t);\n\t}\n\n\t/**\n\t * Returns the identity of the current live session, or `null` if not\n\t * connected (before first Welcome, during reconnect, or after stop()).\n\t */\n\tidentity(): Identity | null {\n\t\treturn this.currentIdentity;\n\t}\n\n\t/**\n\t * Live snapshot of the service registry grouped by serviceName. Each entry\n\t * carries both the method descriptors visible to this caller (subject to\n\t * outgoing-dep subscriptions) и список текущих живых инстансов с их\n\t * endpoint'ами (`callEndpoint` для gRPC, `httpEndpoint` для HTTP-сервера\n\t * пользователя по ADR 0001).\n\t */\n\tserviceMap(): ReadonlyMap<string, ServiceMapEntry> {\n\t\tconst blank = (): ServiceMapEntry => ({\n\t\t\tmethods: [],\n\t\t\tinstances: [],\n\t\t\teventSubscriptions: [],\n\t\t\toutgoingCalls: [],\n\t\t});\n\t\tconst result = new Map<string, ServiceMapEntry>();\n\t\tfor (const m of this._watchStream.snapshot().values()) {\n\t\t\tconst entry = result.get(m.serviceName) ?? blank();\n\t\t\tentry.methods.push(m);\n\t\t\tresult.set(m.serviceName, entry);\n\t\t}\n\t\tfor (const i of this._watchStream.instancesSnapshot().values()) {\n\t\t\tconst entry = result.get(i.serviceName) ?? blank();\n\t\t\tentry.instances.push(i);\n\t\t\tresult.set(i.serviceName, entry);\n\t\t}\n\t\t// ADR-0014 enrichment. Subscriptions are keyed by serviceId — find the\n\t\t// matching ServiceMapEntry by walking known instances/methods.\n\t\tconst byServiceId = new Map<string, ServiceMapEntry>();\n\t\tfor (const [name, entry] of result) {\n\t\t\tvoid name;\n\t\t\tfor (const m of entry.methods) byServiceId.set(m.serviceId, entry);\n\t\t\tfor (const i of entry.instances) byServiceId.set(i.serviceId, entry);\n\t\t}\n\t\tfor (const es of this._watchStream.eventSubscriptionsSnapshot().values()) {\n\t\t\tconst entry = byServiceId.get(es.serviceId);\n\t\t\tif (entry) entry.eventSubscriptions.push(es);\n\t\t}\n\t\tfor (const oc of this._watchStream.outgoingCallsSnapshot().values()) {\n\t\t\tconst entry = byServiceId.get(oc.callerServiceId);\n\t\t\tif (entry) entry.outgoingCalls.push(oc);\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * ADR-0014: the caller's last-known PolicyEvaluation as pushed by the\n\t * runtime via `RegistrySnapshot.policy`. `null` until the first snapshot\n\t * frame arrives. Updated automatically when the operator edits policy and\n\t * Postgres NOTIFY fires → runtime re-emits.\n\t */\n\tpolicyEvaluation(): PolicyEvaluation | null {\n\t\treturn this._watchStream.policyEvaluation();\n\t}\n\n\t// ── internals ──────────────────────────────────────────────────────────────\n\n\tprivate emit<K extends keyof EventMap>(event: K, data: EventMap[K]): void {\n\t\tconst list = this.handlers.get(event) ?? [];\n\t\tfor (const h of list) {\n\t\t\t(h as Handler<K>)(data);\n\t\t}\n\t}\n\n\tprivate async connect(attempt: number): Promise<void> {\n\t\tif (this.stopped) return;\n\t\ttry {\n\t\t\tconst key = parseBootstrapKey(this.rawKey);\n\t\t\tconst result = await this.opts.provisionFn(this.url, key);\n\t\t\tawait this.openSession(result, attempt);\n\t\t} catch (err) {\n\t\t\tconst sbErr = new ServiceBridgeError(\"provision\", err);\n\t\t\tif (!isRetryable(sbErr.code)) {\n\t\t\t\tthis.emit(\"disconnected\", { reason: sbErr.message, error: sbErr });\n\t\t\t\tvoid this.stop();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.scheduleReconnect(attempt + 1, sbErr.message);\n\t\t}\n\t}\n\n\tprivate async openSession(\n\t\tprov: ProvisionResult,\n\t\tattempt: number,\n\t): Promise<void> {\n\t\tconst creds = this.buildMTLSCredentials(prov);\n\t\tconst client = this.opts.clientFactory(this.url, creds);\n\t\tconst stream = openControlStream(client);\n\t\tthis.controlClient = client;\n\t\tthis.lastProvision = prov;\n\n\t\t// Wire up RPC infrastructure BEFORE building RegisterRequest — call_endpoint\n\t\t// must be present in the very first registration so callers see it.\n\t\tawait this.ensureRpcReady(prov, creds);\n\n\t\tconst registryClient = this.opts.registryClientFactory(this.url, creds);\n\t\t// ADR-0014: subscribe to PolicyEvaluation BEFORE start() so the first\n\t\t// snapshot frame's `policy.warnings` triggers `console.warn` + the\n\t\t// `policy_violation` event for each violation. Listener is idempotent\n\t\t// across reconnects; restart() preserves it.\n\t\tthis._watchStream.onPolicyEvaluation((policy) => {\n\t\t\tfor (const w of policy.warnings) {\n\t\t\t\tthis.emitPolicyViolation({\n\t\t\t\t\tdeclaration: w.declaration,\n\t\t\t\t\tvalue: w.value,\n\t\t\t\t\tdenySide: w.denySide,\n\t\t\t\t\treason: w.reason,\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (this.opts.failOnPolicyViolation && policy.warnings.length > 0) {\n\t\t\t\t// Surface as a clear ServiceBridgeError; the upcoming connect\n\t\t\t\t// loop catches and emits 'disconnected'.\n\t\t\t\tconst message = policy.warnings\n\t\t\t\t\t.map((w) => `${w.declaration} ${w.value}: ${w.reason}`)\n\t\t\t\t\t.join(\"; \");\n\t\t\t\tconst err = new ServiceBridgeError(\n\t\t\t\t\t\"policy\",\n\t\t\t\t\tnew Error(`policy violations on start: ${message}`),\n\t\t\t\t);\n\t\t\t\tthis.emit(\"disconnected\", { reason: err.message, error: err });\n\t\t\t\tvoid this.stop();\n\t\t\t}\n\t\t});\n\t\tthis._watchStream.start(\n\t\t\tthis._registry.buildRegisterRequest(),\n\t\t\tregistryClient,\n\t\t\t(_err) => {},\n\t\t);\n\n\t\tconst callbacks: SessionCallbacks = {\n\t\t\tonWelcome: (welcome) => {\n\t\t\t\tthis.scheduleCertRefresh(prov);\n\t\t\t\tthis.currentIdentity = {\n\t\t\t\t\tsessionId: welcome.sessionId,\n\t\t\t\t\tserviceId: welcome.serviceId,\n\t\t\t\t\tserviceName: welcome.serviceName,\n\t\t\t\t\tinstanceId: prov.instanceId,\n\t\t\t\t};\n\t\t\t\tthis._telemetryInstanceId = prov.instanceId;\n\t\t\t\tthis.maybeStartWorkflowSubscriber();\n\t\t\t\tthis.maybeStartJobSubscriber();\n\t\t\t\tthis.emit(\"connected\", {\n\t\t\t\t\tsessionId: welcome.sessionId,\n\t\t\t\t\tserviceId: welcome.serviceId,\n\t\t\t\t\tserviceName: welcome.serviceName,\n\t\t\t\t});\n\t\t\t},\n\t\t\tonDrain: (reason) => {\n\t\t\t\tif (!this.stopped) {\n\t\t\t\t\tthis.emit(\"disconnected\", { reason: `drain: ${reason}` });\n\t\t\t\t}\n\t\t\t},\n\t\t\tonError: (err) => {\n\t\t\t\tif (!this.stopped) {\n\t\t\t\t\tthis.scheduleReconnect(attempt + 1, err.message);\n\t\t\t\t}\n\t\t\t},\n\t\t\tonEnd: () => {\n\t\t\t\tthis.clearTimers();\n\t\t\t\tif (!this.stopped) {\n\t\t\t\t\tthis.scheduleReconnect(attempt + 1, \"stream ended\");\n\t\t\t\t}\n\t\t\t},\n\t\t};\n\n\t\tthis.session = new Session(\n\t\t\tstream,\n\t\t\tcallbacks,\n\t\t\tthis._watchStream,\n\t\t\tregistryClient,\n\t\t);\n\t}\n\n\t// ensureRpcReady starts the inbound CallServer (if advertise is set) and\n\t// wires up the outbound ProxyTransport + DirectTransport + RpcClient.\n\t// Called from openSession once a ProvisionResult is in hand. Idempotent\n\t// across reconnects; refreshes DirectTransport creds on cert rotation.\n\tprivate async ensureRpcReady(\n\t\tprov: ProvisionResult,\n\t\tcreds: grpc.ChannelCredentials,\n\t): Promise<void> {\n\t\t// Outbound side: proxy + direct transports.\n\t\tif (!this._proxyTransport) {\n\t\t\tthis._proxyTransport = new ProxyTransport(this.url, creds);\n\t\t}\n\n\t\tconst directCreds = {\n\t\t\tcaChainDer: Buffer.from(prov.caChainDer),\n\t\t\tleafCertDer: Buffer.from(prov.certDer),\n\t\t\tprivateKeyDer: Buffer.from(prov.privateKeyDer),\n\t\t\tnotAfterUnix: prov.notAfterUnix,\n\t\t};\n\t\tif (this._directTransport) {\n\t\t\tthis._directTransport.updateCredentials(directCreds);\n\t\t} else {\n\t\t\tthis._directTransport = new DirectTransport(directCreds);\n\t\t}\n\n\t\tif (!this._rpcClient) {\n\t\t\tthis._rpcClient = new RpcClient(\n\t\t\t\tthis._proxyTransport,\n\t\t\t\tthis._directTransport,\n\t\t\t\tthis._instanceCache,\n\t\t\t\tthis._schemaRegistry.asResolver(),\n\t\t\t\tthis.currentIdentity?.serviceId ?? \"\",\n\t\t\t\tthis._cb,\n\t\t\t\tthis._lb,\n\t\t\t\tthis,\n\t\t\t);\n\t\t}\n\n\t\t// Events infrastructure: EventsClient → Drainer → Publisher (idempotent).\n\t\tif (!this._eventsClient) {\n\t\t\tthis._eventsClient = new EventsClient(this.url, creds);\n\t\t}\n\t\tif (this._storage && !this._publisher) {\n\t\t\tconst maxOutboxRows = this.opts.maxOutboxRows;\n\t\t\tconst batchSize = this.opts.eventsDrainerBatch;\n\t\t\tconst drainer = new Drainer({\n\t\t\t\tstorage: this._storage,\n\t\t\t\trpcClient: this._eventsClient,\n\t\t\t\tidentity: () => this.currentIdentity,\n\t\t\t\tbatchSize,\n\t\t\t\tlogger: { warn: console.warn, error: console.error },\n\t\t\t\tonPolicyViolation: (v) => this.emitPolicyViolation(v),\n\t\t\t});\n\t\t\tdrainer.start();\n\t\t\tthis._drainer = drainer;\n\t\t\tthis._publisher = new Publisher({\n\t\t\t\tstorage: this._storage,\n\t\t\t\trpcClient: this._eventsClient,\n\t\t\t\tschemaIndex: this._schemaIndexAdapter,\n\t\t\t\tdrainer,\n\t\t\t\tidentity: () => this.currentIdentity,\n\t\t\t\tmaxOutboxRows,\n\t\t\t\tlogger: { warn: console.warn, error: console.error },\n\t\t\t\tsb: this,\n\t\t\t\t// Propagate ALS trace context so events published inside a\n\t\t\t\t// workflow run (or any wrapped scope) inherit the parent trace.\n\t\t\t\txSbTraceFn: () => {\n\t\t\t\t\tconst ctx = currentTraceContext();\n\t\t\t\t\tif (!ctx) return \"\";\n\t\t\t\t\treturn formatXSbTrace(ctx.traceId, ctx.parentOpId);\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\n\t\t// Telemetry transport: idempotent across reconnects. Creds change on cert\n\t\t// rotation but the gRPC channel underneath the TelemetryClient already\n\t\t// re-resolves; we keep the same client + transport instance.\n\t\tif (this._telemetryEnabled && !this._telemetryClient) {\n\t\t\tthis._telemetryClient = new TelemetryClient(this.url, creds);\n\t\t\tthis._telemetryTransport = new TelemetryTransport({\n\t\t\t\tclient: adaptTelemetryClient(this._telemetryClient),\n\t\t\t\tring: this._telemetryRing,\n\t\t\t\t// No default onDrop: a library must not spam the host's console on\n\t\t\t\t// every drop-count tick. Drop observability is host opt-in via the\n\t\t\t\t// TelemetryTransportOptions.onDrop hook.\n\t\t\t});\n\t\t\tawait this._telemetryTransport.start();\n\t\t\tthis._processSampler = new ProcessSampler(\n\t\t\t\tthis._telemetryRing,\n\t\t\t\t() => this._telemetryInstanceId,\n\t\t\t);\n\t\t\tthis._processSampler.start();\n\t\t}\n\n\t\t// Workflows: WorkflowsClient is the single channel used by both caller-side\n\t\t// ops (WorkflowDomain.start/signal/cancel/...) and the owner-side subscriber.\n\t\t// Attached on every (re)connect — creds change on cert rotation, but we\n\t\t// reuse the same client; gRPC re-resolves underneath. Subscriber starts\n\t\t// only when this service has at least one workflow handler registered.\n\t\tif (!this._workflowsClient) {\n\t\t\tthis._workflowsClient = new WorkflowsClient(this.url, creds);\n\t\t\tthis.workflow._attachRpc(this._workflowsClient);\n\t\t}\n\n\t\tif (!this._jobsClient) {\n\t\t\tthis._jobsClient = new JobsClient(this.url, creds);\n\t\t}\n\n\t\t// Events subscriber: long-lived bidi Subscribe stream (idempotent).\n\t\tif (this._storage && this._eventsClient && !this._subscriber) {\n\t\t\tthis._subscriber = new Subscriber({\n\t\t\t\trpcClient: this._eventsClient,\n\t\t\t\tschemaIndex: this._schemaIndexAdapter,\n\t\t\t\tidentity: () => {\n\t\t\t\t\tconst id = this.currentIdentity;\n\t\t\t\t\treturn id\n\t\t\t\t\t\t? { serviceId: id.serviceId, instanceId: id.instanceId }\n\t\t\t\t\t\t: null;\n\t\t\t\t},\n\t\t\t\thandlers: () => this.handlersForSubscriber(),\n\t\t\t\tmaxInFlight: this.opts.eventsMaxInFlight,\n\t\t\t\tlogger: { warn: console.warn, error: console.error },\n\t\t\t\trunWithTrace: this.runHandlerWithTrace,\n\t\t\t\tsb: this,\n\t\t\t});\n\t\t\tthis._subscriber.start();\n\t\t}\n\n\t\t// Inbound side — only when advertise is configured.\n\t\tif (!this.opts.advertise || this._callServer) return;\n\t\tconst cs = new CallServer(\n\t\t\tthis._registry._handle.asDispatchPort(),\n\t\t\t{\n\t\t\t\tcaChainDer: Buffer.from(prov.caChainDer),\n\t\t\t\tleafCertDer: Buffer.from(prov.certDer),\n\t\t\t\tprivateKeyDer: Buffer.from(prov.privateKeyDer),\n\t\t\t},\n\t\t\t() => this._watchStream.policyEvaluation(),\n\t\t);\n\t\ttry {\n\t\t\tconst endpoint = await cs.start(this.opts.advertise);\n\t\t\tthis._callServer = cs;\n\t\t\tthis._registry.setCallEndpoint(endpoint);\n\t\t} catch (err) {\n\t\t\t// CallServer bind failed — treat as fatal for this attempt, surface as\n\t\t\t// disconnected and let the reconnect cycle retry.\n\t\t\tthis.emit(\"disconnected\", {\n\t\t\t\treason: `call-server bind: ${(err as Error).message}`,\n\t\t\t});\n\t\t}\n\t}\n\n\tprivate buildMTLSCredentials(prov: ProvisionResult): grpc.ChannelCredentials {\n\t\tconst caChainPem = derToPem(prov.caChainDer, \"CERTIFICATE\");\n\t\tconst certPem = derToPem(prov.certDer, \"CERTIFICATE\");\n\t\tconst keyPem = derToPem(prov.privateKeyDer, \"PRIVATE KEY\");\n\n\t\t// Server cert has no SAN; chain validates against the embedded CA cert.\n\t\tconst verifyOptions: Parameters<typeof grpc.credentials.createSsl>[3] = {\n\t\t\tcheckServerIdentity: () => undefined,\n\t\t};\n\n\t\treturn grpc.credentials.createSsl(\n\t\t\tcaChainPem,\n\t\t\tkeyPem,\n\t\t\tcertPem,\n\t\t\tverifyOptions,\n\t\t);\n\t}\n\n\t// Owner-side workflow subscriber: started on first Welcome after start(),\n\t// only when at least one workflow handler is registered. Idempotent across\n\t// reconnects/rotations — the subscriber's reconnect ladder owns its own\n\t// stream lifecycle and the WorkflowsClient gRPC channel re-resolves under\n\t// the hood on cert rotation.\n\tprivate maybeStartWorkflowSubscriber(): void {\n\t\tif (this._workflowSubscriber) return;\n\t\tif (!this._workflowsClient) return;\n\t\tconst id = this.currentIdentity;\n\t\tif (!id) return;\n\t\tconst hasWorkflowHandlers = this._registry._handle._entries.some(\n\t\t\t(e) => e.type === MethodType.METHOD_TYPE_WORKFLOW,\n\t\t);\n\t\tif (!hasWorkflowHandlers) return;\n\t\tconst rpc = this._workflowsClient;\n\t\tconst telemetryApi = this._telemetryApi;\n\t\tconst sub = new WorkflowSubscriber({\n\t\t\trpc,\n\t\t\tserviceId: id.serviceId,\n\t\t\tinstanceId: id.instanceId,\n\t\t\tdeps: {\n\t\t\t\tsb: { rpc: this.rpc, event: this.event, workflow: this.workflow },\n\t\t\t\tops: makeRuntimeOps(rpc, () => this.currentIdentity?.instanceId ?? \"\"),\n\t\t\t\t// Step span emission (T-022 / ADR-0026 nesting): the runner calls\n\t\t\t\t// this around every executed unit — each step, each fanout group,\n\t\t\t\t// each fanout branch, each compensation. We open one USER.SUBOP\n\t\t\t\t// op (parent = the current trace context, i.e. the run root or an\n\t\t\t\t// enclosing group/branch span) and run the unit inside a child\n\t\t\t\t// context rooted at that span's op_id. That child context is what\n\t\t\t\t// makes the unit's nested sb.rpc.call / sb.event.publish /\n\t\t\t\t// sub-workflow.start emit X-SB-Trace with parent = the step span,\n\t\t\t\t// turning a flat trace into the run → step → op tree. Compensation\n\t\t\t\t// units carry is_compensation + compensates_for_step_id so the UI\n\t\t\t\t// correlates the compensation op back to the forward step that\n\t\t\t\t// shares its step_id.\n\t\t\t\twrapStep: async (info, fn) => {\n\t\t\t\t\tconst meta: Record<string, unknown> = {\n\t\t\t\t\t\tstep_id: info.stepId,\n\t\t\t\t\t\tstep_name: info.stepName,\n\t\t\t\t\t\tworkflow_run_id: info.runId,\n\t\t\t\t\t};\n\t\t\t\t\tif (info.isCompensation) {\n\t\t\t\t\t\tmeta.is_compensation = true;\n\t\t\t\t\t\tmeta.compensates_for_step_id = info.compensatesForStepId ?? \"\";\n\t\t\t\t\t}\n\t\t\t\t\tconst subject =\n\t\t\t\t\t\tinfo.role === \"compensation\"\n\t\t\t\t\t\t\t? `compensate:${info.compensatesForStepId ?? info.stepId}`\n\t\t\t\t\t\t\t: `${info.role}:${info.stepId}`;\n\t\t\t\t\tconst handle = telemetryApi.startOp({\n\t\t\t\t\t\tchannel: Channel.USER,\n\t\t\t\t\t\tkind: UserSubOp,\n\t\t\t\t\t\tsubject,\n\t\t\t\t\t\tbusinessKey: info.runId,\n\t\t\t\t\t\tmetaJson: Buffer.from(JSON.stringify(meta)),\n\t\t\t\t\t});\n\t\t\t\t\tconst parent = currentTraceContext();\n\t\t\t\t\tconst scoped = parent\n\t\t\t\t\t\t? () => runWithTrace(childContext(parent, handle.opId), fn)\n\t\t\t\t\t\t: fn;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst out = await scoped();\n\t\t\t\t\t\thandle.end(Status.SUCCESS);\n\t\t\t\t\t\treturn out;\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\thandle.end(\n\t\t\t\t\t\t\tStatus.ERROR,\n\t\t\t\t\t\t\terr instanceof Error ? err.message : String(err),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tthrow err;\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t},\n\t\t\tlogger: { warn: console.warn, error: console.error },\n\t\t\tlookupLocalGraph: (name) => {\n\t\t\t\tconst entry = this._registry._handle._entries.find(\n\t\t\t\t\t(e) => e.type === MethodType.METHOD_TYPE_WORKFLOW && e.name === name,\n\t\t\t\t);\n\t\t\t\treturn entry ? (entry.fn as unknown as Step[]) : null;\n\t\t\t},\n\t\t\tsb: this,\n\t\t});\n\t\tsub.start();\n\t\tthis._workflowSubscriber = sub;\n\t}\n\n\t// Wrap a handler invocation in the inbound trace context so nested\n\t// sb.rpc.call / sb.event.publish / sb.workflow.start inherit the job /\n\t// event op as their parent. Without this, work spawned inside a handler\n\t// detaches into its own root trace. Mirrors the WorkflowSubscriber's own\n\t// runWithTrace wrapping.\n\tprivate readonly runHandlerWithTrace = (\n\t\txSbTrace: string,\n\t\tfn: () => Promise<void>,\n\t): Promise<void> => {\n\t\tconst parsed = parseXSbTrace(xSbTrace);\n\t\treturn parsed ? runWithTrace(parsed, fn) : fn();\n\t};\n\n\tprivate maybeStartJobSubscriber(): void {\n\t\tif (this._jobSubscriber) return;\n\t\tif (!this._jobsClient) return;\n\t\tconst id = this.currentIdentity;\n\t\tif (!id) return;\n\t\tif (this.job.size() === 0) return;\n\n\t\t// Job definitions were already sent to the runtime via\n\t\t// Registry.RegisterAndWatch as IncomingMethod{type=JOB,...}; here we\n\t\t// only open the dispatch subscriber stream.\n\t\tconst sub = new JobSubscriber({\n\t\t\trpcClient: this._jobsClient,\n\t\t\tidentity: () => this.currentIdentity,\n\t\t\tdomain: this.job,\n\t\t\tlogger: { warn: console.warn, error: console.error },\n\t\t\trunWithTrace: this.runHandlerWithTrace,\n\t\t});\n\t\tsub.start();\n\t\tthis._jobSubscriber = sub;\n\t}\n\n\tprivate handlersForSubscriber(): EventHandler[] {\n\t\treturn this._registry._handle._entries\n\t\t\t.filter((e) => e.type === MethodType.METHOD_TYPE_EVENT)\n\t\t\t.map((e) => ({\n\t\t\t\tpattern: e.name,\n\t\t\t\tfn: e.fn as (payload: unknown) => Promise<void> | void,\n\t\t\t}));\n\t}\n\n\tprivate scheduleCertRefresh(prov: ProvisionResult): void {\n\t\tif (this.certRefreshTimer) {\n\t\t\tclearTimeout(this.certRefreshTimer);\n\t\t\tthis.certRefreshTimer = null;\n\t\t}\n\t\tconst now = BigInt(Math.floor(Date.now() / 1000));\n\t\tconst remainingMs =\n\t\t\tNumber(prov.notAfterUnix - now) * 1000 -\n\t\t\tthis.opts.certRefreshLeadMs +\n\t\t\trandomJitter(this.opts.certRefreshJitterMs);\n\t\tif (remainingMs <= 0) {\n\t\t\tvoid this.rotateCert();\n\t\t\treturn;\n\t\t}\n\t\tthis.certRefreshTimer = setTimeout(() => {\n\t\t\tvoid this.rotateCert();\n\t\t}, remainingMs);\n\t}\n\n\t/**\n\t * Overlap rotation:\n\t * 1. Re-provision (new cert).\n\t * 2. Open new mTLS channel + Control.Open stream.\n\t * 3. Wait for Welcome on the new stream.\n\t * 4. Only then close the old session.\n\t *\n\t * On failure: schedule a reconnect so the application sees a `reconnecting`\n\t * event; the next reconnect cycle will re-provision and proceed.\n\t */\n\tprivate async rotateCert(): Promise<void> {\n\t\tif (this.stopped) return;\n\t\tif (!this.controlClient || !this.lastProvision) {\n\t\t\t// No live session — nothing to refresh from. Let reconnect handle it.\n\t\t\tthis.scheduleReconnect(1, \"rotation: no live session\");\n\t\t\treturn;\n\t\t}\n\n\t\tlet newProv: ProvisionResult;\n\t\ttry {\n\t\t\tnewProv = await this.opts.refreshFn(\n\t\t\t\tthis.controlClient,\n\t\t\t\tthis.lastProvision,\n\t\t\t);\n\t\t} catch (err) {\n\t\t\tconst sbErr = new ServiceBridgeError(\"rotation refresh\", err);\n\t\t\tif (!isRetryable(sbErr.code)) {\n\t\t\t\tthis.emit(\"disconnected\", { reason: sbErr.message, error: sbErr });\n\t\t\t\tvoid this.stop();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.scheduleReconnect(1, sbErr.message);\n\t\t\treturn;\n\t\t}\n\n\t\tconst newCreds = this.buildMTLSCredentials(newProv);\n\t\tconst newRegistryClient = this.opts.registryClientFactory(\n\t\t\tthis.url,\n\t\t\tnewCreds,\n\t\t);\n\t\tconst newClient = this.opts.clientFactory(this.url, newCreds);\n\t\tconst newStream = openControlStream(newClient);\n\t\tconst oldSession = this.session;\n\n\t\tconst swapPromise = new Promise<void>((resolve, reject) => {\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\treject(new Error(\"rotation: handshake timeout\"));\n\t\t\t}, this.opts.rotationHandshakeTimeoutMs);\n\n\t\t\tlet welcomed = false;\n\t\t\tconst cbs: SessionCallbacks = {\n\t\t\t\tonWelcome: (welcome) => {\n\t\t\t\t\twelcomed = true;\n\t\t\t\t\tthis.session = newSession;\n\t\t\t\t\tthis.scheduleCertRefresh(newProv);\n\t\t\t\t\tthis.currentIdentity = {\n\t\t\t\t\t\tsessionId: welcome.sessionId,\n\t\t\t\t\t\tserviceId: welcome.serviceId,\n\t\t\t\t\t\tserviceName: welcome.serviceName,\n\t\t\t\t\t\tinstanceId: newProv.instanceId,\n\t\t\t\t\t};\n\t\t\t\t\tthis._telemetryInstanceId = newProv.instanceId;\n\t\t\t\t\tthis.maybeStartWorkflowSubscriber();\n\t\t\t\t\tthis.maybeStartJobSubscriber();\n\t\t\t\t\tthis.emit(\"connected\", {\n\t\t\t\t\t\tsessionId: welcome.sessionId,\n\t\t\t\t\t\tserviceId: welcome.serviceId,\n\t\t\t\t\t\tserviceName: welcome.serviceName,\n\t\t\t\t\t});\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\tresolve();\n\t\t\t\t},\n\t\t\t\tonDrain: (reason) => {\n\t\t\t\t\tif (!this.stopped)\n\t\t\t\t\t\tthis.emit(\"disconnected\", { reason: `drain: ${reason}` });\n\t\t\t\t},\n\t\t\t\tonError: (err) => {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\treject(err);\n\t\t\t\t},\n\t\t\t\tonEnd: () => {\n\t\t\t\t\tif (!welcomed) {\n\t\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\t\treject(new Error(\"rotation: new stream ended before welcome\"));\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t};\n\t\t\tconst newSession = new Session(\n\t\t\t\tnewStream,\n\t\t\t\tcbs,\n\t\t\t\tthis._watchStream,\n\t\t\t\tnewRegistryClient,\n\t\t\t);\n\t\t});\n\n\t\ttry {\n\t\t\tawait swapPromise;\n\t\t\t// Close the old session only after the new one is fully usable.\n\t\t\toldSession?.close();\n\t\t\tthis._watchStream.restart(\n\t\t\t\tthis._registry.buildRegisterRequest(),\n\t\t\t\tnewRegistryClient,\n\t\t\t\t(_err) => {},\n\t\t\t);\n\t\t} catch (err) {\n\t\t\t// Roll back to the previous session: keep oldSession alive and tear\n\t\t\t// down the partially-built new one. Schedule a reconnect to retry.\n\t\t\tif (this.session !== oldSession) {\n\t\t\t\tthis.session?.close();\n\t\t\t\tthis.session = oldSession;\n\t\t\t}\n\t\t\tthis.scheduleReconnect(\n\t\t\t\t1,\n\t\t\t\t`rotation: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate scheduleReconnect(attempt: number, reason: string): void {\n\t\tif (this.stopped) return;\n\t\tif (\n\t\t\tthis.opts.reconnectAttempts > 0 &&\n\t\t\tattempt > this.opts.reconnectAttempts\n\t\t) {\n\t\t\tthis.emit(\"disconnected\", { reason: \"exhausted\" });\n\t\t\tvoid this.stop();\n\t\t\treturn;\n\t\t}\n\t\tthis.emit(\"reconnecting\", {\n\t\t\tattempt,\n\t\t\tdelayMs: this.opts.reconnectIntervalMs,\n\t\t\treason,\n\t\t});\n\t\tsetTimeout(() => {\n\t\t\tvoid this.connect(attempt);\n\t\t}, this.opts.reconnectIntervalMs);\n\t}\n\n\tprivate clearTimers(): void {\n\t\tif (this.certRefreshTimer) {\n\t\t\tclearTimeout(this.certRefreshTimer);\n\t\t\tthis.certRefreshTimer = null;\n\t\t}\n\t}\n}\n","// @public — см. ./README.md\n\nimport type { Registry } from \"../registry/registry\";\nimport type { SchemaSpec } from \"../serde/serializer\";\nimport type { Publisher, PublishOpts } from \"./publisher\";\n\n// EventDomain — namespace `sb.event` for declaring published events,\n// subscribing to event patterns, and emitting events.\n//\n// Schema source is the same `SchemaSpec` used by `sb.rpc.handle` — either a\n// `.proto` file (ProtoFileSpec) or a `.schema.json` file with explicit\n// `fieldNumber` per property (JsonSchemaFileSpec). Inline JSON Schema is no\n// longer accepted (ADR-0013). The Protobuf encoder also runs `type.verify()`\n// on publish, so payload errors throw before reaching the outbox.\nexport class EventDomain {\n\tconstructor(\n\t\tprivate readonly registry: Registry,\n\t\tprivate readonly getPublisher: () => Publisher | null,\n\t) {}\n\n\tdefine(name: string, spec?: SchemaSpec): void {\n\t\tthis.registry._handle.publishEvent(name, spec);\n\t}\n\n\thandle(\n\t\tpattern: string,\n\t\tfn: (payload: unknown) => Promise<void> | void,\n\t): void {\n\t\tthis.registry._handle.event(pattern, fn);\n\t}\n\n\tasync publish<T = unknown>(\n\t\tname: string,\n\t\tpayload: T,\n\t\topts?: PublishOpts,\n\t): Promise<{ eventId: string }> {\n\t\tconst publisher = this.getPublisher();\n\t\tif (!publisher) {\n\t\t\tthrow new Error(\n\t\t\t\t\"ServiceBridge: events publisher not ready — call start() before sb.event.publish()\",\n\t\t\t);\n\t\t}\n\t\treturn publisher.publish(name, payload, opts);\n\t}\n}\n","// Code generated by protoc-gen-ts_proto. DO NOT EDIT.\n// versions:\n// protoc-gen-ts_proto v2.11.8\n// protoc unknown\n// source: servicebridge/v1/events.proto\n\n/* eslint-disable */\nimport { BinaryReader, BinaryWriter } from \"@bufbuild/protobuf/wire\";\nimport {\n type CallOptions,\n type ChannelCredentials,\n Client,\n type ClientDuplexStream,\n type ClientOptions,\n type ClientUnaryCall,\n type handleBidiStreamingCall,\n type handleUnaryCall,\n makeGenericClientConstructor,\n type Metadata,\n type ServiceError,\n type UntypedServiceImplementation,\n} from \"@grpc/grpc-js\";\n\nexport enum PublishStatus {\n PUBLISH_STATUS_UNSPECIFIED = 0,\n PUBLISH_STATUS_ACCEPTED = 1,\n PUBLISH_STATUS_REJECTED_DUPLICATE = 3,\n PUBLISH_STATUS_REJECTED_INVALID_NAME = 5,\n /**\n * PUBLISH_STATUS_REJECTED_FORBIDDEN - ADR-0014: publisher does not have event.publish action rule matching this\n * event name (or its capability is disabled). Per-envelope reject — other\n * events in the batch proceed.\n */\n PUBLISH_STATUS_REJECTED_FORBIDDEN = 6,\n UNRECOGNIZED = -1,\n}\n\nexport interface EventEnvelope {\n id: string;\n name: string;\n payload: Buffer;\n contractHash: string;\n partitionKey: string;\n idempotencyKey: string;\n fireAndForget: boolean;\n headers: { [key: string]: string };\n occurredAtUnixMs: number;\n /** X-SB-Trace propagation: carried in EventEnvelope for publisher→consumer. */\n xSbTrace: string;\n /**\n * payload_json — JSON-encoded view of the same payload, populated by the\n * publisher SDK alongside the canonical protobuf `payload`. Used by the\n * workflow signal router to evaluate JSON-path `wait_event` filters\n * without decoding the protobuf form (runtime treats payload as opaque\n * bytes per ADR-0013). Empty when publisher cannot produce JSON.\n */\n payloadJson: Buffer;\n}\n\nexport interface EventEnvelope_HeadersEntry {\n key: string;\n value: string;\n}\n\nexport interface PublishRequest {\n publisherServiceId: string;\n publisherInstanceId: string;\n events: EventEnvelope[];\n}\n\nexport interface PublishStatusEntry {\n eventId: string;\n status: PublishStatus;\n message: string;\n}\n\nexport interface PublishResponse {\n results: PublishStatusEntry[];\n}\n\nexport interface SubscribeInit {\n subscriberServiceId: string;\n subscriberInstanceId: string;\n maxInFlight: number;\n}\n\nexport interface Ack {\n deliveryId: string;\n eventId: Buffer;\n}\n\nexport interface Nack {\n deliveryId: string;\n errorMessage: string;\n eventId: Buffer;\n}\n\nexport interface SubscribeClientMessage {\n init?: SubscribeInit | undefined;\n ack?: Ack | undefined;\n nack?: Nack | undefined;\n}\n\nexport interface EventDelivery {\n deliveryId: string;\n envelope?: EventEnvelope | undefined;\n attempt: number;\n}\n\nexport interface SubscribeServerMessage {\n delivery?: EventDelivery | undefined;\n}\n\nexport interface ReplayDlqRequest {\n eventId: string;\n}\n\nexport interface ReplayDlqResponse {\n eventId: string;\n}\n\nexport interface ListDlqRequest {\n limit: number;\n cursor: string;\n}\n\nexport interface DlqEntry {\n eventId: string;\n eventName: string;\n consumerService: string;\n lastError: string;\n dlqAtUnixMs: number;\n replayCount: number;\n totalAttempts: number;\n}\n\nexport interface ListDlqResponse {\n entries: DlqEntry[];\n nextCursor: string;\n}\n\nfunction createBaseEventEnvelope(): EventEnvelope {\n return {\n id: \"\",\n name: \"\",\n payload: Buffer.alloc(0),\n contractHash: \"\",\n partitionKey: \"\",\n idempotencyKey: \"\",\n fireAndForget: false,\n headers: {},\n occurredAtUnixMs: 0,\n xSbTrace: \"\",\n payloadJson: Buffer.alloc(0),\n };\n}\n\nexport const EventEnvelope: MessageFns<EventEnvelope> = {\n encode(message: EventEnvelope, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.id !== \"\") {\n writer.uint32(10).string(message.id);\n }\n if (message.name !== \"\") {\n writer.uint32(18).string(message.name);\n }\n if (message.payload.length !== 0) {\n writer.uint32(26).bytes(message.payload);\n }\n if (message.contractHash !== \"\") {\n writer.uint32(34).string(message.contractHash);\n }\n if (message.partitionKey !== \"\") {\n writer.uint32(42).string(message.partitionKey);\n }\n if (message.idempotencyKey !== \"\") {\n writer.uint32(50).string(message.idempotencyKey);\n }\n if (message.fireAndForget !== false) {\n writer.uint32(56).bool(message.fireAndForget);\n }\n globalThis.Object.entries(message.headers).forEach(([key, value]: [string, string]) => {\n EventEnvelope_HeadersEntry.encode({ key: key as any, value }, writer.uint32(66).fork()).join();\n });\n if (message.occurredAtUnixMs !== 0) {\n writer.uint32(72).int64(message.occurredAtUnixMs);\n }\n if (message.xSbTrace !== \"\") {\n writer.uint32(82).string(message.xSbTrace);\n }\n if (message.payloadJson.length !== 0) {\n writer.uint32(90).bytes(message.payloadJson);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): EventEnvelope {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseEventEnvelope();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.id = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.name = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.payload = Buffer.from(reader.bytes());\n continue;\n }\n case 4: {\n if (tag !== 34) {\n break;\n }\n\n message.contractHash = reader.string();\n continue;\n }\n case 5: {\n if (tag !== 42) {\n break;\n }\n\n message.partitionKey = reader.string();\n continue;\n }\n case 6: {\n if (tag !== 50) {\n break;\n }\n\n message.idempotencyKey = reader.string();\n continue;\n }\n case 7: {\n if (tag !== 56) {\n break;\n }\n\n message.fireAndForget = reader.bool();\n continue;\n }\n case 8: {\n if (tag !== 66) {\n break;\n }\n\n const entry8 = EventEnvelope_HeadersEntry.decode(reader, reader.uint32());\n if (entry8.value !== undefined) {\n message.headers[entry8.key] = entry8.value;\n }\n continue;\n }\n case 9: {\n if (tag !== 72) {\n break;\n }\n\n message.occurredAtUnixMs = longToNumber(reader.int64());\n continue;\n }\n case 10: {\n if (tag !== 82) {\n break;\n }\n\n message.xSbTrace = reader.string();\n continue;\n }\n case 11: {\n if (tag !== 90) {\n break;\n }\n\n message.payloadJson = Buffer.from(reader.bytes());\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<EventEnvelope>, I>>(base?: I): EventEnvelope {\n return EventEnvelope.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<EventEnvelope>, I>>(object: I): EventEnvelope {\n const message = createBaseEventEnvelope();\n message.id = object.id ?? \"\";\n message.name = object.name ?? \"\";\n message.payload = object.payload ?? Buffer.alloc(0);\n message.contractHash = object.contractHash ?? \"\";\n message.partitionKey = object.partitionKey ?? \"\";\n message.idempotencyKey = object.idempotencyKey ?? \"\";\n message.fireAndForget = object.fireAndForget ?? false;\n message.headers = (globalThis.Object.entries(object.headers ?? {}) as [string, string][]).reduce(\n (acc: { [key: string]: string }, [key, value]: [string, string]) => {\n if (value !== undefined) {\n acc[key] = globalThis.String(value);\n }\n return acc;\n },\n {},\n );\n message.occurredAtUnixMs = object.occurredAtUnixMs ?? 0;\n message.xSbTrace = object.xSbTrace ?? \"\";\n message.payloadJson = object.payloadJson ?? Buffer.alloc(0);\n return message;\n },\n};\n\nfunction createBaseEventEnvelope_HeadersEntry(): EventEnvelope_HeadersEntry {\n return { key: \"\", value: \"\" };\n}\n\nexport const EventEnvelope_HeadersEntry: MessageFns<EventEnvelope_HeadersEntry> = {\n encode(message: EventEnvelope_HeadersEntry, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.key !== \"\") {\n writer.uint32(10).string(message.key);\n }\n if (message.value !== \"\") {\n writer.uint32(18).string(message.value);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): EventEnvelope_HeadersEntry {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseEventEnvelope_HeadersEntry();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.key = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.value = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<EventEnvelope_HeadersEntry>, I>>(base?: I): EventEnvelope_HeadersEntry {\n return EventEnvelope_HeadersEntry.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<EventEnvelope_HeadersEntry>, I>>(object: I): EventEnvelope_HeadersEntry {\n const message = createBaseEventEnvelope_HeadersEntry();\n message.key = object.key ?? \"\";\n message.value = object.value ?? \"\";\n return message;\n },\n};\n\nfunction createBasePublishRequest(): PublishRequest {\n return { publisherServiceId: \"\", publisherInstanceId: \"\", events: [] };\n}\n\nexport const PublishRequest: MessageFns<PublishRequest> = {\n encode(message: PublishRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.publisherServiceId !== \"\") {\n writer.uint32(10).string(message.publisherServiceId);\n }\n if (message.publisherInstanceId !== \"\") {\n writer.uint32(18).string(message.publisherInstanceId);\n }\n for (const v of message.events) {\n EventEnvelope.encode(v!, writer.uint32(26).fork()).join();\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): PublishRequest {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBasePublishRequest();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.publisherServiceId = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.publisherInstanceId = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.events.push(EventEnvelope.decode(reader, reader.uint32()));\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<PublishRequest>, I>>(base?: I): PublishRequest {\n return PublishRequest.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<PublishRequest>, I>>(object: I): PublishRequest {\n const message = createBasePublishRequest();\n message.publisherServiceId = object.publisherServiceId ?? \"\";\n message.publisherInstanceId = object.publisherInstanceId ?? \"\";\n message.events = object.events?.map((e) => EventEnvelope.fromPartial(e)) || [];\n return message;\n },\n};\n\nfunction createBasePublishStatusEntry(): PublishStatusEntry {\n return { eventId: \"\", status: 0, message: \"\" };\n}\n\nexport const PublishStatusEntry: MessageFns<PublishStatusEntry> = {\n encode(message: PublishStatusEntry, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.eventId !== \"\") {\n writer.uint32(10).string(message.eventId);\n }\n if (message.status !== 0) {\n writer.uint32(16).int32(message.status);\n }\n if (message.message !== \"\") {\n writer.uint32(26).string(message.message);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): PublishStatusEntry {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBasePublishStatusEntry();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.eventId = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 16) {\n break;\n }\n\n message.status = reader.int32() as any;\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.message = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<PublishStatusEntry>, I>>(base?: I): PublishStatusEntry {\n return PublishStatusEntry.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<PublishStatusEntry>, I>>(object: I): PublishStatusEntry {\n const message = createBasePublishStatusEntry();\n message.eventId = object.eventId ?? \"\";\n message.status = object.status ?? 0;\n message.message = object.message ?? \"\";\n return message;\n },\n};\n\nfunction createBasePublishResponse(): PublishResponse {\n return { results: [] };\n}\n\nexport const PublishResponse: MessageFns<PublishResponse> = {\n encode(message: PublishResponse, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n for (const v of message.results) {\n PublishStatusEntry.encode(v!, writer.uint32(10).fork()).join();\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): PublishResponse {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBasePublishResponse();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.results.push(PublishStatusEntry.decode(reader, reader.uint32()));\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<PublishResponse>, I>>(base?: I): PublishResponse {\n return PublishResponse.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<PublishResponse>, I>>(object: I): PublishResponse {\n const message = createBasePublishResponse();\n message.results = object.results?.map((e) => PublishStatusEntry.fromPartial(e)) || [];\n return message;\n },\n};\n\nfunction createBaseSubscribeInit(): SubscribeInit {\n return { subscriberServiceId: \"\", subscriberInstanceId: \"\", maxInFlight: 0 };\n}\n\nexport const SubscribeInit: MessageFns<SubscribeInit> = {\n encode(message: SubscribeInit, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.subscriberServiceId !== \"\") {\n writer.uint32(10).string(message.subscriberServiceId);\n }\n if (message.subscriberInstanceId !== \"\") {\n writer.uint32(18).string(message.subscriberInstanceId);\n }\n if (message.maxInFlight !== 0) {\n writer.uint32(24).int32(message.maxInFlight);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): SubscribeInit {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseSubscribeInit();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.subscriberServiceId = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.subscriberInstanceId = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 24) {\n break;\n }\n\n message.maxInFlight = reader.int32();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<SubscribeInit>, I>>(base?: I): SubscribeInit {\n return SubscribeInit.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<SubscribeInit>, I>>(object: I): SubscribeInit {\n const message = createBaseSubscribeInit();\n message.subscriberServiceId = object.subscriberServiceId ?? \"\";\n message.subscriberInstanceId = object.subscriberInstanceId ?? \"\";\n message.maxInFlight = object.maxInFlight ?? 0;\n return message;\n },\n};\n\nfunction createBaseAck(): Ack {\n return { deliveryId: \"\", eventId: Buffer.alloc(0) };\n}\n\nexport const Ack: MessageFns<Ack> = {\n encode(message: Ack, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.deliveryId !== \"\") {\n writer.uint32(10).string(message.deliveryId);\n }\n if (message.eventId.length !== 0) {\n writer.uint32(18).bytes(message.eventId);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): Ack {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseAck();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.deliveryId = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.eventId = Buffer.from(reader.bytes());\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<Ack>, I>>(base?: I): Ack {\n return Ack.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<Ack>, I>>(object: I): Ack {\n const message = createBaseAck();\n message.deliveryId = object.deliveryId ?? \"\";\n message.eventId = object.eventId ?? Buffer.alloc(0);\n return message;\n },\n};\n\nfunction createBaseNack(): Nack {\n return { deliveryId: \"\", errorMessage: \"\", eventId: Buffer.alloc(0) };\n}\n\nexport const Nack: MessageFns<Nack> = {\n encode(message: Nack, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.deliveryId !== \"\") {\n writer.uint32(10).string(message.deliveryId);\n }\n if (message.errorMessage !== \"\") {\n writer.uint32(18).string(message.errorMessage);\n }\n if (message.eventId.length !== 0) {\n writer.uint32(26).bytes(message.eventId);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): Nack {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseNack();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.deliveryId = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.errorMessage = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.eventId = Buffer.from(reader.bytes());\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<Nack>, I>>(base?: I): Nack {\n return Nack.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<Nack>, I>>(object: I): Nack {\n const message = createBaseNack();\n message.deliveryId = object.deliveryId ?? \"\";\n message.errorMessage = object.errorMessage ?? \"\";\n message.eventId = object.eventId ?? Buffer.alloc(0);\n return message;\n },\n};\n\nfunction createBaseSubscribeClientMessage(): SubscribeClientMessage {\n return { init: undefined, ack: undefined, nack: undefined };\n}\n\nexport const SubscribeClientMessage: MessageFns<SubscribeClientMessage> = {\n encode(message: SubscribeClientMessage, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.init !== undefined) {\n SubscribeInit.encode(message.init, writer.uint32(10).fork()).join();\n }\n if (message.ack !== undefined) {\n Ack.encode(message.ack, writer.uint32(18).fork()).join();\n }\n if (message.nack !== undefined) {\n Nack.encode(message.nack, writer.uint32(26).fork()).join();\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): SubscribeClientMessage {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseSubscribeClientMessage();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.init = SubscribeInit.decode(reader, reader.uint32());\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.ack = Ack.decode(reader, reader.uint32());\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.nack = Nack.decode(reader, reader.uint32());\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<SubscribeClientMessage>, I>>(base?: I): SubscribeClientMessage {\n return SubscribeClientMessage.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<SubscribeClientMessage>, I>>(object: I): SubscribeClientMessage {\n const message = createBaseSubscribeClientMessage();\n message.init = (object.init !== undefined && object.init !== null)\n ? SubscribeInit.fromPartial(object.init)\n : undefined;\n message.ack = (object.ack !== undefined && object.ack !== null) ? Ack.fromPartial(object.ack) : undefined;\n message.nack = (object.nack !== undefined && object.nack !== null) ? Nack.fromPartial(object.nack) : undefined;\n return message;\n },\n};\n\nfunction createBaseEventDelivery(): EventDelivery {\n return { deliveryId: \"\", envelope: undefined, attempt: 0 };\n}\n\nexport const EventDelivery: MessageFns<EventDelivery> = {\n encode(message: EventDelivery, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.deliveryId !== \"\") {\n writer.uint32(10).string(message.deliveryId);\n }\n if (message.envelope !== undefined) {\n EventEnvelope.encode(message.envelope, writer.uint32(18).fork()).join();\n }\n if (message.attempt !== 0) {\n writer.uint32(24).int32(message.attempt);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): EventDelivery {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseEventDelivery();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.deliveryId = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.envelope = EventEnvelope.decode(reader, reader.uint32());\n continue;\n }\n case 3: {\n if (tag !== 24) {\n break;\n }\n\n message.attempt = reader.int32();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<EventDelivery>, I>>(base?: I): EventDelivery {\n return EventDelivery.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<EventDelivery>, I>>(object: I): EventDelivery {\n const message = createBaseEventDelivery();\n message.deliveryId = object.deliveryId ?? \"\";\n message.envelope = (object.envelope !== undefined && object.envelope !== null)\n ? EventEnvelope.fromPartial(object.envelope)\n : undefined;\n message.attempt = object.attempt ?? 0;\n return message;\n },\n};\n\nfunction createBaseSubscribeServerMessage(): SubscribeServerMessage {\n return { delivery: undefined };\n}\n\nexport const SubscribeServerMessage: MessageFns<SubscribeServerMessage> = {\n encode(message: SubscribeServerMessage, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.delivery !== undefined) {\n EventDelivery.encode(message.delivery, writer.uint32(10).fork()).join();\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): SubscribeServerMessage {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseSubscribeServerMessage();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.delivery = EventDelivery.decode(reader, reader.uint32());\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<SubscribeServerMessage>, I>>(base?: I): SubscribeServerMessage {\n return SubscribeServerMessage.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<SubscribeServerMessage>, I>>(object: I): SubscribeServerMessage {\n const message = createBaseSubscribeServerMessage();\n message.delivery = (object.delivery !== undefined && object.delivery !== null)\n ? EventDelivery.fromPartial(object.delivery)\n : undefined;\n return message;\n },\n};\n\nfunction createBaseReplayDlqRequest(): ReplayDlqRequest {\n return { eventId: \"\" };\n}\n\nexport const ReplayDlqRequest: MessageFns<ReplayDlqRequest> = {\n encode(message: ReplayDlqRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.eventId !== \"\") {\n writer.uint32(10).string(message.eventId);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): ReplayDlqRequest {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseReplayDlqRequest();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.eventId = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<ReplayDlqRequest>, I>>(base?: I): ReplayDlqRequest {\n return ReplayDlqRequest.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<ReplayDlqRequest>, I>>(object: I): ReplayDlqRequest {\n const message = createBaseReplayDlqRequest();\n message.eventId = object.eventId ?? \"\";\n return message;\n },\n};\n\nfunction createBaseReplayDlqResponse(): ReplayDlqResponse {\n return { eventId: \"\" };\n}\n\nexport const ReplayDlqResponse: MessageFns<ReplayDlqResponse> = {\n encode(message: ReplayDlqResponse, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.eventId !== \"\") {\n writer.uint32(10).string(message.eventId);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): ReplayDlqResponse {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseReplayDlqResponse();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.eventId = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<ReplayDlqResponse>, I>>(base?: I): ReplayDlqResponse {\n return ReplayDlqResponse.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<ReplayDlqResponse>, I>>(object: I): ReplayDlqResponse {\n const message = createBaseReplayDlqResponse();\n message.eventId = object.eventId ?? \"\";\n return message;\n },\n};\n\nfunction createBaseListDlqRequest(): ListDlqRequest {\n return { limit: 0, cursor: \"\" };\n}\n\nexport const ListDlqRequest: MessageFns<ListDlqRequest> = {\n encode(message: ListDlqRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.limit !== 0) {\n writer.uint32(8).int32(message.limit);\n }\n if (message.cursor !== \"\") {\n writer.uint32(18).string(message.cursor);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): ListDlqRequest {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseListDlqRequest();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 8) {\n break;\n }\n\n message.limit = reader.int32();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.cursor = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<ListDlqRequest>, I>>(base?: I): ListDlqRequest {\n return ListDlqRequest.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<ListDlqRequest>, I>>(object: I): ListDlqRequest {\n const message = createBaseListDlqRequest();\n message.limit = object.limit ?? 0;\n message.cursor = object.cursor ?? \"\";\n return message;\n },\n};\n\nfunction createBaseDlqEntry(): DlqEntry {\n return {\n eventId: \"\",\n eventName: \"\",\n consumerService: \"\",\n lastError: \"\",\n dlqAtUnixMs: 0,\n replayCount: 0,\n totalAttempts: 0,\n };\n}\n\nexport const DlqEntry: MessageFns<DlqEntry> = {\n encode(message: DlqEntry, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.eventId !== \"\") {\n writer.uint32(10).string(message.eventId);\n }\n if (message.eventName !== \"\") {\n writer.uint32(18).string(message.eventName);\n }\n if (message.consumerService !== \"\") {\n writer.uint32(26).string(message.consumerService);\n }\n if (message.lastError !== \"\") {\n writer.uint32(34).string(message.lastError);\n }\n if (message.dlqAtUnixMs !== 0) {\n writer.uint32(40).int64(message.dlqAtUnixMs);\n }\n if (message.replayCount !== 0) {\n writer.uint32(48).int32(message.replayCount);\n }\n if (message.totalAttempts !== 0) {\n writer.uint32(56).int32(message.totalAttempts);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): DlqEntry {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseDlqEntry();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.eventId = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.eventName = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.consumerService = reader.string();\n continue;\n }\n case 4: {\n if (tag !== 34) {\n break;\n }\n\n message.lastError = reader.string();\n continue;\n }\n case 5: {\n if (tag !== 40) {\n break;\n }\n\n message.dlqAtUnixMs = longToNumber(reader.int64());\n continue;\n }\n case 6: {\n if (tag !== 48) {\n break;\n }\n\n message.replayCount = reader.int32();\n continue;\n }\n case 7: {\n if (tag !== 56) {\n break;\n }\n\n message.totalAttempts = reader.int32();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<DlqEntry>, I>>(base?: I): DlqEntry {\n return DlqEntry.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<DlqEntry>, I>>(object: I): DlqEntry {\n const message = createBaseDlqEntry();\n message.eventId = object.eventId ?? \"\";\n message.eventName = object.eventName ?? \"\";\n message.consumerService = object.consumerService ?? \"\";\n message.lastError = object.lastError ?? \"\";\n message.dlqAtUnixMs = object.dlqAtUnixMs ?? 0;\n message.replayCount = object.replayCount ?? 0;\n message.totalAttempts = object.totalAttempts ?? 0;\n return message;\n },\n};\n\nfunction createBaseListDlqResponse(): ListDlqResponse {\n return { entries: [], nextCursor: \"\" };\n}\n\nexport const ListDlqResponse: MessageFns<ListDlqResponse> = {\n encode(message: ListDlqResponse, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n for (const v of message.entries) {\n DlqEntry.encode(v!, writer.uint32(10).fork()).join();\n }\n if (message.nextCursor !== \"\") {\n writer.uint32(18).string(message.nextCursor);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): ListDlqResponse {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseListDlqResponse();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.entries.push(DlqEntry.decode(reader, reader.uint32()));\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.nextCursor = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<ListDlqResponse>, I>>(base?: I): ListDlqResponse {\n return ListDlqResponse.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<ListDlqResponse>, I>>(object: I): ListDlqResponse {\n const message = createBaseListDlqResponse();\n message.entries = object.entries?.map((e) => DlqEntry.fromPartial(e)) || [];\n message.nextCursor = object.nextCursor ?? \"\";\n return message;\n },\n};\n\nexport type EventsService = typeof EventsService;\nexport const EventsService = {\n publish: {\n path: \"/servicebridge.v1.Events/Publish\" as const,\n requestStream: false as const,\n responseStream: false as const,\n requestSerialize: (value: PublishRequest): Buffer => Buffer.from(PublishRequest.encode(value).finish()),\n requestDeserialize: (value: Buffer): PublishRequest => PublishRequest.decode(value),\n responseSerialize: (value: PublishResponse): Buffer => Buffer.from(PublishResponse.encode(value).finish()),\n responseDeserialize: (value: Buffer): PublishResponse => PublishResponse.decode(value),\n },\n subscribe: {\n path: \"/servicebridge.v1.Events/Subscribe\" as const,\n requestStream: true as const,\n responseStream: true as const,\n requestSerialize: (value: SubscribeClientMessage): Buffer =>\n Buffer.from(SubscribeClientMessage.encode(value).finish()),\n requestDeserialize: (value: Buffer): SubscribeClientMessage => SubscribeClientMessage.decode(value),\n responseSerialize: (value: SubscribeServerMessage): Buffer =>\n Buffer.from(SubscribeServerMessage.encode(value).finish()),\n responseDeserialize: (value: Buffer): SubscribeServerMessage => SubscribeServerMessage.decode(value),\n },\n replayDlq: {\n path: \"/servicebridge.v1.Events/ReplayDlq\" as const,\n requestStream: false as const,\n responseStream: false as const,\n requestSerialize: (value: ReplayDlqRequest): Buffer => Buffer.from(ReplayDlqRequest.encode(value).finish()),\n requestDeserialize: (value: Buffer): ReplayDlqRequest => ReplayDlqRequest.decode(value),\n responseSerialize: (value: ReplayDlqResponse): Buffer => Buffer.from(ReplayDlqResponse.encode(value).finish()),\n responseDeserialize: (value: Buffer): ReplayDlqResponse => ReplayDlqResponse.decode(value),\n },\n listDlq: {\n path: \"/servicebridge.v1.Events/ListDlq\" as const,\n requestStream: false as const,\n responseStream: false as const,\n requestSerialize: (value: ListDlqRequest): Buffer => Buffer.from(ListDlqRequest.encode(value).finish()),\n requestDeserialize: (value: Buffer): ListDlqRequest => ListDlqRequest.decode(value),\n responseSerialize: (value: ListDlqResponse): Buffer => Buffer.from(ListDlqResponse.encode(value).finish()),\n responseDeserialize: (value: Buffer): ListDlqResponse => ListDlqResponse.decode(value),\n },\n} as const;\n\nexport interface EventsServer extends UntypedServiceImplementation {\n publish: handleUnaryCall<PublishRequest, PublishResponse>;\n subscribe: handleBidiStreamingCall<SubscribeClientMessage, SubscribeServerMessage>;\n replayDlq: handleUnaryCall<ReplayDlqRequest, ReplayDlqResponse>;\n listDlq: handleUnaryCall<ListDlqRequest, ListDlqResponse>;\n}\n\nexport interface EventsClient extends Client {\n publish(\n request: PublishRequest,\n callback: (error: ServiceError | null, response: PublishResponse) => void,\n ): ClientUnaryCall;\n publish(\n request: PublishRequest,\n metadata: Metadata,\n callback: (error: ServiceError | null, response: PublishResponse) => void,\n ): ClientUnaryCall;\n publish(\n request: PublishRequest,\n metadata: Metadata,\n options: Partial<CallOptions>,\n callback: (error: ServiceError | null, response: PublishResponse) => void,\n ): ClientUnaryCall;\n subscribe(): ClientDuplexStream<SubscribeClientMessage, SubscribeServerMessage>;\n subscribe(options: Partial<CallOptions>): ClientDuplexStream<SubscribeClientMessage, SubscribeServerMessage>;\n subscribe(\n metadata: Metadata,\n options?: Partial<CallOptions>,\n ): ClientDuplexStream<SubscribeClientMessage, SubscribeServerMessage>;\n replayDlq(\n request: ReplayDlqRequest,\n callback: (error: ServiceError | null, response: ReplayDlqResponse) => void,\n ): ClientUnaryCall;\n replayDlq(\n request: ReplayDlqRequest,\n metadata: Metadata,\n callback: (error: ServiceError | null, response: ReplayDlqResponse) => void,\n ): ClientUnaryCall;\n replayDlq(\n request: ReplayDlqRequest,\n metadata: Metadata,\n options: Partial<CallOptions>,\n callback: (error: ServiceError | null, response: ReplayDlqResponse) => void,\n ): ClientUnaryCall;\n listDlq(\n request: ListDlqRequest,\n callback: (error: ServiceError | null, response: ListDlqResponse) => void,\n ): ClientUnaryCall;\n listDlq(\n request: ListDlqRequest,\n metadata: Metadata,\n callback: (error: ServiceError | null, response: ListDlqResponse) => void,\n ): ClientUnaryCall;\n listDlq(\n request: ListDlqRequest,\n metadata: Metadata,\n options: Partial<CallOptions>,\n callback: (error: ServiceError | null, response: ListDlqResponse) => void,\n ): ClientUnaryCall;\n}\n\nexport const EventsClient = makeGenericClientConstructor(EventsService, \"servicebridge.v1.Events\") as unknown as {\n new (address: string, credentials: ChannelCredentials, options?: Partial<ClientOptions>): EventsClient;\n service: typeof EventsService;\n serviceName: string;\n};\n\ntype Builtin = Date | Function | Uint8Array | string | number | boolean | undefined;\n\ntype DeepPartial<T> = T extends Builtin ? T\n : T extends globalThis.Array<infer U> ? globalThis.Array<DeepPartial<U>>\n : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>>\n : T extends {} ? { [K in keyof T]?: DeepPartial<T[K]> }\n : Partial<T>;\n\ntype KeysOfUnion<T> = T extends T ? keyof T : never;\ntype Exact<P, I extends P> = P extends Builtin ? P\n : P & { [K in keyof P]: Exact<P[K], I[K]> } & { [K in Exclude<keyof I, KeysOfUnion<P>>]: never };\n\nfunction longToNumber(int64: { toString(): string }): number {\n const num = globalThis.Number(int64.toString());\n if (num > globalThis.Number.MAX_SAFE_INTEGER) {\n throw new globalThis.Error(\"Value is larger than Number.MAX_SAFE_INTEGER\");\n }\n if (num < globalThis.Number.MIN_SAFE_INTEGER) {\n throw new globalThis.Error(\"Value is smaller than Number.MIN_SAFE_INTEGER\");\n }\n return num;\n}\n\ninterface MessageFns<T> {\n encode(message: T, writer?: BinaryWriter): BinaryWriter;\n decode(input: BinaryReader | Uint8Array, length?: number): T;\n create<I extends Exact<DeepPartial<T>, I>>(base?: I): T;\n fromPartial<I extends Exact<DeepPartial<T>, I>>(object: I): T;\n}\n","import type { Identity } from \"../connection/service-bridge\";\nimport type { EventsClient } from \"../pb/servicebridge/v1/events\";\nimport { PublishStatus } from \"../pb/servicebridge/v1/events\";\nimport type { Storage } from \"../sqlite/storage\";\nimport type { Logger } from \"./publisher\";\n\n// BACKOFF_MS is the retry delay ladder after network failures (±25% jitter applied).\n// @internal\nconst BACKOFF_MS = [1_000, 5_000, 30_000, 120_000, 600_000] as const;\n// MAX_ATTEMPTS before an outbox row is permanently failed.\n// @internal\nconst MAX_ATTEMPTS = 5;\n\n// OutboxRow is a row selected from event_outbox.\n// @internal\ninterface OutboxRow {\n\tid: string;\n\tname: string;\n\tpayload: Buffer;\n\tpayload_json: Buffer;\n\tcontract_hash: string;\n\tpartition_key: string;\n\tidempotency_key: string;\n\tfire_and_forget: number;\n\theaders: string;\n\toccurred_at_ms: number;\n\tenqueued_at_ms: number;\n\tstatus: string;\n\tattempts: number;\n\tlast_error: string;\n\tnext_attempt_at_ms: number;\n\tx_sb_trace: string;\n}\n\n// @public — см. ./README.md\nexport interface DrainerDeps {\n\tstorage: Storage;\n\trpcClient: EventsClient;\n\tidentity: () => Identity | null;\n\tbatchSize: number;\n\tlogger: Logger;\n\tclockFn?: () => number;\n\tsleepFn?: (ms: number) => Promise<void>;\n\t// Invoked when the runtime rejects a publish for policy reasons\n\t// (PUBLISH_STATUS_REJECTED_FORBIDDEN). Lets the owner surface a\n\t// `policy_violation` event for an async (outbox) denial that can't be\n\t// thrown back to the publish() caller.\n\tonPolicyViolation?: (v: {\n\t\tdeclaration: string;\n\t\tvalue: string;\n\t\tdenySide: string;\n\t\treason: string;\n\t}) => void;\n}\n\n// Drainer reads pending rows from the SQLite outbox, publishes them to the\n// runtime via Events.Publish, and updates their status based on the response.\n// Edge-triggered: kick() schedules an immediate wakeup from the wait state.\n// @public — см. ./README.md\nexport class Drainer {\n\tprivate readonly deps: DrainerDeps;\n\tprivate readonly clockFn: () => number;\n\tprivate readonly sleepFn: (ms: number) => Promise<void>;\n\n\tprivate running = false;\n\tprivate pendingKick = false;\n\tprivate wakeResolve: (() => void) | null = null;\n\tprivate loopDone: Promise<void> = Promise.resolve();\n\n\tconstructor(deps: DrainerDeps) {\n\t\tthis.deps = deps;\n\t\tthis.clockFn = deps.clockFn ?? (() => Date.now());\n\t\tthis.sleepFn =\n\t\t\tdeps.sleepFn ?? ((ms) => new Promise<void>((r) => setTimeout(r, ms)));\n\t}\n\n\t// start begins the background drain loop.\n\tstart(): void {\n\t\tif (this.running) return;\n\t\tthis.running = true;\n\t\tthis.loopDone = this.loop();\n\t}\n\n\t// kick wakes up the drainer immediately if it is waiting.\n\t// Edge-triggered: if already running an iteration, marks pendingKick\n\t// so the next wait is also skipped.\n\tkick(): void {\n\t\tthis.pendingKick = true;\n\t\tif (this.wakeResolve) {\n\t\t\tconst resolve = this.wakeResolve;\n\t\t\tthis.wakeResolve = null;\n\t\t\tresolve();\n\t\t}\n\t}\n\n\t// stop signals the loop to exit and waits for the current iteration to finish.\n\tasync stop(): Promise<void> {\n\t\tthis.running = false;\n\t\tthis.kick(); // wake up from any wait\n\t\tawait this.loopDone;\n\t}\n\n\tprivate async loop(): Promise<void> {\n\t\twhile (this.running) {\n\t\t\tconst now = this.clockFn();\n\t\t\tconst { storage, rpcClient, identity, batchSize } = this.deps;\n\n\t\t\t// Select pending rows whose next_attempt_at_ms is due.\n\t\t\tconst rows = storage\n\t\t\t\t.prepare(\n\t\t\t\t\t`SELECT * FROM event_outbox\n WHERE status='pending' AND next_attempt_at_ms <= ?\n ORDER BY enqueued_at_ms ASC, id ASC\n LIMIT ?`,\n\t\t\t\t)\n\t\t\t\t.all(now, batchSize) as OutboxRow[];\n\n\t\t\tif (rows.length === 0) {\n\t\t\t\tif (!this.running) break;\n\t\t\t\t// Edge-triggered wait: consume pendingKick or wait for kick()/1s timer.\n\t\t\t\tif (this.pendingKick) {\n\t\t\t\t\tthis.pendingKick = false;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tawait Promise.race([\n\t\t\t\t\tnew Promise<void>((resolve) => {\n\t\t\t\t\t\tthis.wakeResolve = resolve;\n\t\t\t\t\t}),\n\t\t\t\t\tthis.sleepFn(1_000),\n\t\t\t\t]);\n\t\t\t\tthis.wakeResolve = null;\n\t\t\t\tthis.pendingKick = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Claim: mark rows as inflight so a crash-restart resets them.\n\t\t\tconst ids = rows.map((r) => r.id);\n\t\t\tconst placeholders = ids.map(() => \"?\").join(\",\");\n\t\t\tstorage\n\t\t\t\t.prepare(\n\t\t\t\t\t`UPDATE event_outbox SET status='inflight' WHERE id IN (${placeholders})`,\n\t\t\t\t)\n\t\t\t\t.run(...ids);\n\n\t\t\t// Build and send PublishRequest.\n\t\t\tconst ident = identity();\n\t\t\tconst events = rows.map((r) => ({\n\t\t\t\tid: r.id,\n\t\t\t\tname: r.name,\n\t\t\t\tpayload: r.payload,\n\t\t\t\tpayloadJson: r.payload_json ?? Buffer.alloc(0),\n\t\t\t\tcontractHash: r.contract_hash,\n\t\t\t\tpartitionKey: r.partition_key,\n\t\t\t\tidempotencyKey: r.idempotency_key,\n\t\t\t\tfireAndForget: false,\n\t\t\t\theaders: (() => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\treturn JSON.parse(r.headers) as Record<string, string>;\n\t\t\t\t\t} catch {\n\t\t\t\t\t\treturn {};\n\t\t\t\t\t}\n\t\t\t\t})(),\n\t\t\t\toccurredAtUnixMs: r.occurred_at_ms,\n\t\t\t\txSbTrace: r.x_sb_trace ?? \"\",\n\t\t\t}));\n\n\t\t\tlet results: {\n\t\t\t\teventId: string;\n\t\t\t\tstatus: PublishStatus;\n\t\t\t\tmessage: string;\n\t\t\t}[] = [];\n\t\t\tlet netError: Error | null = null;\n\n\t\t\ttry {\n\t\t\t\tconst response = await new Promise<{\n\t\t\t\t\tresults: {\n\t\t\t\t\t\teventId: string;\n\t\t\t\t\t\tstatus: PublishStatus;\n\t\t\t\t\t\tmessage: string;\n\t\t\t\t\t}[];\n\t\t\t\t}>((resolve, reject) => {\n\t\t\t\t\trpcClient.publish(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpublisherServiceId: ident?.serviceId ?? \"\",\n\t\t\t\t\t\t\tpublisherInstanceId: ident?.instanceId ?? \"\",\n\t\t\t\t\t\t\tevents,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t(err, res) => {\n\t\t\t\t\t\t\tif (err) reject(err);\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tresolve(\n\t\t\t\t\t\t\t\t\tres ?? {\n\t\t\t\t\t\t\t\t\t\tresults: [],\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t},\n\t\t\t\t\t);\n\t\t\t\t});\n\t\t\t\tresults = response.results;\n\t\t\t} catch (err) {\n\t\t\t\tnetError = err instanceof Error ? err : new Error(String(err));\n\t\t\t}\n\n\t\t\tif (netError) {\n\t\t\t\t// Network error: retry all inflight rows with backoff.\n\t\t\t\tconst nowRetry = this.clockFn();\n\t\t\t\tfor (const row of rows) {\n\t\t\t\t\tconst newAttempts = row.attempts + 1;\n\t\t\t\t\tif (newAttempts >= MAX_ATTEMPTS) {\n\t\t\t\t\t\tstorage\n\t\t\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\t\t`UPDATE event_outbox\n SET status='failed', attempts=?, last_error='max_attempts'\n WHERE id=?`,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.run(newAttempts, row.id);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst baseDelay =\n\t\t\t\t\t\t\tBACKOFF_MS[Math.min(newAttempts - 1, 4)] ?? 600_000;\n\t\t\t\t\t\tconst jitter = Math.floor(\n\t\t\t\t\t\t\tbaseDelay * 0.25 * (Math.random() * 2 - 1),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst nextAt = nowRetry + baseDelay + jitter;\n\t\t\t\t\t\tstorage\n\t\t\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\t\t`UPDATE event_outbox\n SET status='pending', attempts=?, last_error=?, next_attempt_at_ms=?\n WHERE id=?`,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.run(newAttempts, netError.message, nextAt, row.id);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Continue loop — will respect backoff via next_attempt_at_ms filter.\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Process per-event results.\n\t\t\tconst resultMap = new Map(results.map((r) => [r.eventId, r]));\n\t\t\tfor (const row of rows) {\n\t\t\t\tconst entry = resultMap.get(row.id);\n\t\t\t\tconst status =\n\t\t\t\t\tentry?.status ?? PublishStatus.PUBLISH_STATUS_UNSPECIFIED;\n\n\t\t\t\tswitch (status) {\n\t\t\t\t\tcase PublishStatus.PUBLISH_STATUS_ACCEPTED:\n\t\t\t\t\tcase PublishStatus.PUBLISH_STATUS_REJECTED_DUPLICATE:\n\t\t\t\t\t\t// Success or idempotent duplicate — delete from outbox.\n\t\t\t\t\t\tstorage.prepare(\"DELETE FROM event_outbox WHERE id=?\").run(row.id);\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase PublishStatus.PUBLISH_STATUS_REJECTED_INVALID_NAME:\n\t\t\t\t\t\t// Terminal failures — mark as failed.\n\t\t\t\t\t\tstorage\n\t\t\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\t\t`UPDATE event_outbox\n SET status='failed', attempts=?, last_error=?\n WHERE id=?`,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.run(row.attempts + 1, `rejected:${status}`, row.id);\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase PublishStatus.PUBLISH_STATUS_REJECTED_FORBIDDEN: {\n\t\t\t\t\t\t// Policy denial (event.publish gate). Terminal — retrying\n\t\t\t\t\t\t// won't help; mark failed and surface a policy_violation so\n\t\t\t\t\t\t// the async denial is observable (publish() is fire-and-forget\n\t\t\t\t\t\t// into the outbox, so it can't be thrown back to the caller).\n\t\t\t\t\t\tconst reason = entry?.message || \"event.publish denied by policy\";\n\t\t\t\t\t\tstorage\n\t\t\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\t\t`UPDATE event_outbox\n SET status='failed', attempts=?, last_error=?\n WHERE id=?`,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.run(row.attempts + 1, `forbidden:${reason}`, row.id);\n\t\t\t\t\t\tthis.deps.logger.warn(\n\t\t\t\t\t\t\t`drainer: event ${row.name} (${row.id}) rejected — ${reason}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tthis.deps.onPolicyViolation?.({\n\t\t\t\t\t\t\tdeclaration: \"event.publish\",\n\t\t\t\t\t\t\tvalue: row.name,\n\t\t\t\t\t\t\tdenySide: \"self_egress\",\n\t\t\t\t\t\t\treason,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\t// Transient unspecified — treat as retryable.\n\t\t\t\t\t\tthis.deps.logger.warn(\n\t\t\t\t\t\t\t`drainer: UNSPECIFIED status for event ${row.id} — treating as transient`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tconst newAttempts = row.attempts + 1;\n\t\t\t\t\t\t\tif (newAttempts >= MAX_ATTEMPTS) {\n\t\t\t\t\t\t\t\tstorage\n\t\t\t\t\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\t\t\t\t`UPDATE event_outbox\n SET status='failed', attempts=?, last_error='max_attempts'\n WHERE id=?`,\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t.run(newAttempts, row.id);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tconst baseDelay =\n\t\t\t\t\t\t\t\t\tBACKOFF_MS[Math.min(newAttempts - 1, 4)] ?? 600_000;\n\t\t\t\t\t\t\t\tconst jitter = Math.floor(\n\t\t\t\t\t\t\t\t\tbaseDelay * 0.25 * (Math.random() * 2 - 1),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tconst nextAt = this.clockFn() + baseDelay + jitter;\n\t\t\t\t\t\t\t\tstorage\n\t\t\t\t\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\t\t\t\t`UPDATE event_outbox\n SET status='pending', attempts=?, last_error='unspecified', next_attempt_at_ms=?\n WHERE id=?`,\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t.run(newAttempts, nextAt, row.id);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If kick was requested during this iteration, loop immediately.\n\t\t\tif (this.pendingKick) {\n\t\t\t\tthis.pendingKick = false;\n\t\t\t}\n\t\t}\n\t}\n}\n","// @public — см. ./README.md\nexport class InvalidEventNameError extends Error {\n\toverride readonly name = \"InvalidEventNameError\";\n\n\tconstructor(eventName: string) {\n\t\tsuper(\n\t\t\t`events: invalid event name \"${eventName}\" — must match ^[a-z0-9_-]+(\\\\.[a-z0-9_-]+)*$`,\n\t\t);\n\t}\n}\n\n// @public — см. ./README.md\nexport class OutboxFullError extends Error {\n\toverride readonly name = \"OutboxFullError\";\n\n\tconstructor(cap: number) {\n\t\tsuper(\n\t\t\t`events: outbox cap reached (${cap} rows) — cannot enqueue new event`,\n\t\t);\n\t}\n}\n","// ids.ts — monotonic UUID v7 generator (ADR-0006).\n// @public — см. ./README.md\n\nimport { uuidv7 } from \"uuidv7\";\n\n// uuidv7 generates a monotonic UUID v7. The `uuidv7` package guarantees the\n// same clock-skew property ADR-0006 required (sequential ids within the same\n// ms via an internal counter), running on plain Node (node:crypto) and Bun\n// alike. Re-exported here so call sites depend on a single SDK entry point.\n// @public — см. ./README.md\nexport { uuidv7 };\n","import type { Identity, ServiceBridge } from \"../connection/service-bridge\";\nimport type { EventsClient } from \"../pb/servicebridge/v1/events\";\nimport type { SchemaPair } from \"../serde/serializer\";\nimport type { Storage } from \"../sqlite/storage\";\nimport { InvalidEventNameError, OutboxFullError } from \"./errors\";\nimport { uuidv7 } from \"./ids\";\n\n// EVENT_NAME_RE validates that an event name consists of dot-separated\n// lowercase alphanumeric/underscore/hyphen segments with no empty segments.\n// @internal\nconst EVENT_NAME_RE = /^[a-z0-9_-]+(\\.[a-z0-9_-]+)*$/;\n\n// @public — см. ./README.md\nexport interface PublishOpts {\n\tidempotencyKey?: string;\n\tpartitionKey?: string;\n\tfireAndForget?: boolean;\n\theaders?: Record<string, string>;\n\toccurredAtMs?: number;\n}\n\n// SchemaIndex maps event name to its contract hash and schema pair.\n// @internal\nexport interface SchemaIndex {\n\tget(name: string): { contractHash: string; pair: SchemaPair } | undefined;\n}\n\n// DrainerHandle exposes the kick signal for edge-triggered wakeup.\n// @internal\nexport interface DrainerHandle {\n\tkick(): void;\n}\n\n// Logger abstraction — compatible with a subset of the slog API shape.\n// @internal\nexport interface Logger {\n\twarn(msg: string, ...args: unknown[]): void;\n\terror(msg: string, ...args: unknown[]): void;\n}\n\n// @internal\nexport interface PublisherDeps {\n\tstorage: Storage;\n\trpcClient: EventsClient;\n\tschemaIndex: SchemaIndex;\n\tdrainer: DrainerHandle;\n\tidentity: () => Identity | null;\n\tmaxOutboxRows: number;\n\tlogger: Logger;\n\tsb?: ServiceBridge;\n\t// xSbTraceFn returns the current X-SB-Trace header to attach to outbound\n\t// envelopes, read from the active AsyncLocalStorage trace scope. Returns \"\"\n\t// when no trace context is active, in which case the runtime mints a fresh\n\t// root trace on ingest (T-017). Mandatory: a missing hook would silently\n\t// break trace propagation across the publish boundary.\n\t// @internal\n\txSbTraceFn: () => string;\n}\n\n// Publisher enqueues events into the local SQLite outbox (durable path) or\n// sends them directly to the runtime (fireAndForget path).\n// @public — см. ./README.md\nexport class Publisher {\n\tprivate readonly deps: PublisherDeps;\n\tprivate readonly xSbTraceFn: () => string;\n\n\tconstructor(deps: PublisherDeps) {\n\t\tthis.deps = deps;\n\t\tthis.xSbTraceFn = deps.xSbTraceFn;\n\t}\n\n\t// publish enqueues or directly sends an event.\n\t// Throws InvalidEventNameError if name is malformed.\n\t// Throws Error if schema not registered.\n\t// Throws OutboxFullError if outbox cap exceeded.\n\tasync publish(\n\t\tname: string,\n\t\tpayload: unknown,\n\t\topts?: PublishOpts,\n\t): Promise<{ eventId: string }> {\n\t\tif (!EVENT_NAME_RE.test(name)) {\n\t\t\tthrow new InvalidEventNameError(name);\n\t\t}\n\n\t\tconst entry = this.deps.schemaIndex.get(name);\n\t\tif (entry === undefined) {\n\t\t\tthrow new Error(\n\t\t\t\t`events: no schema registered for event \"${name}\" — call sb.publish(\"${name}\", schema) before start()`,\n\t\t\t);\n\t\t}\n\n\t\tconst encoded = entry.pair.input.encode(payload);\n\t\t// JSON view of the same payload — runtime treats it as opaque bytes\n\t\t// (ADR-0013) but uses it for workflow wait_event JSON-path filters.\n\t\t// Falls back to empty bytes when payload is not JSON-serializable.\n\t\tlet payloadJsonBytes: Buffer;\n\t\ttry {\n\t\t\tpayloadJsonBytes = Buffer.from(JSON.stringify(payload ?? null));\n\t\t} catch {\n\t\t\tpayloadJsonBytes = Buffer.alloc(0);\n\t\t}\n\t\tconst eventId = uuidv7();\n\t\tconst occurredAtMs = opts?.occurredAtMs ?? Date.now();\n\t\tconst xSbTrace = this.xSbTraceFn();\n\n\t\tif (opts?.fireAndForget) {\n\t\t\tconst ident = this.deps.identity();\n\t\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\t\tthis.deps.rpcClient.publish(\n\t\t\t\t\t{\n\t\t\t\t\t\tpublisherServiceId: ident?.serviceId ?? \"\",\n\t\t\t\t\t\tpublisherInstanceId: ident?.instanceId ?? \"\",\n\t\t\t\t\t\tevents: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tid: eventId,\n\t\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\t\tpayload: Buffer.from(encoded),\n\t\t\t\t\t\t\t\tpayloadJson: payloadJsonBytes,\n\t\t\t\t\t\t\t\tcontractHash: entry.contractHash,\n\t\t\t\t\t\t\t\tpartitionKey: opts?.partitionKey ?? \"\",\n\t\t\t\t\t\t\t\tidempotencyKey: opts?.idempotencyKey ?? \"\",\n\t\t\t\t\t\t\t\tfireAndForget: true,\n\t\t\t\t\t\t\t\theaders: opts?.headers ?? {},\n\t\t\t\t\t\t\t\toccurredAtUnixMs: occurredAtMs,\n\t\t\t\t\t\t\t\txSbTrace,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t},\n\t\t\t\t\t(err) => {\n\t\t\t\t\t\tif (err) reject(err);\n\t\t\t\t\t\telse resolve();\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t});\n\t\t\treturn { eventId };\n\t\t}\n\n\t\t// Durable path: insert into outbox inside a transaction.\n\t\t// Cap check + INSERT are atomic to prevent races.\n\t\tconst { storage, maxOutboxRows } = this.deps;\n\t\tconst now = Date.now();\n\n\t\tstorage.transaction(() => {\n\t\t\tconst row = storage\n\t\t\t\t.prepare(\"SELECT COUNT(*) AS count FROM event_outbox\")\n\t\t\t\t.get() as { count: number } | null;\n\t\t\tconst count = row?.count ?? 0;\n\t\t\tif (count >= maxOutboxRows) {\n\t\t\t\tthrow new OutboxFullError(maxOutboxRows);\n\t\t\t}\n\n\t\t\tstorage\n\t\t\t\t.prepare(\n\t\t\t\t\t`INSERT INTO event_outbox\n (id, name, payload, payload_json, contract_hash, partition_key, idempotency_key,\n fire_and_forget, headers, occurred_at_ms, enqueued_at_ms, status,\n attempts, last_error, next_attempt_at_ms, x_sb_trace)\n VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, 'pending', 0, '', 0, ?)`,\n\t\t\t\t)\n\t\t\t\t.run(\n\t\t\t\t\teventId,\n\t\t\t\t\tname,\n\t\t\t\t\tBuffer.from(encoded),\n\t\t\t\t\tpayloadJsonBytes,\n\t\t\t\t\tentry.contractHash,\n\t\t\t\t\topts?.partitionKey ?? \"\",\n\t\t\t\t\topts?.idempotencyKey ?? \"\",\n\t\t\t\t\tJSON.stringify(opts?.headers ?? {}),\n\t\t\t\t\toccurredAtMs,\n\t\t\t\t\tnow,\n\t\t\t\t\txSbTrace,\n\t\t\t\t);\n\t\t});\n\n\t\tthis.deps.drainer.kick();\n\t\treturn { eventId };\n\t}\n}\n","import type { ServiceBridge } from \"../connection/service-bridge\";\nimport type {\n\tEventsClient,\n\tSubscribeClientMessage,\n} from \"../pb/servicebridge/v1/events\";\nimport {\n\tAck,\n\tNack,\n\tSubscribeClientMessage as SubscribeClientMessageFns,\n\tSubscribeInit,\n} from \"../pb/servicebridge/v1/events\";\nimport type { SchemaPair } from \"../serde/serializer\";\nimport type { Logger } from \"./publisher\";\n\n// Fixed reconnect ladder — deterministic for tests; saturates at the last\n// rung. Wildcards and rare-event hooks do not belong here, only timing.\nconst RECONNECT_LADDER_MS = [1000, 5000, 15000, 30000, 60000] as const;\n\nfunction nextDelay(attempt: number): number {\n\tconst idx = Math.min(Math.max(attempt, 0), RECONNECT_LADDER_MS.length - 1);\n\treturn RECONNECT_LADDER_MS[idx]!;\n}\n\n// @internal\ninterface SubscriberIdentity {\n\tserviceId: string;\n\tinstanceId: string;\n}\n\n// EventHandler is the registered handler for one event name. Dispatch is by\n// exact name match — wildcards are server-side only (ADR-0011).\n// @internal\nexport interface EventHandler {\n\tpattern: string;\n\tfn: (payload: unknown) => Promise<void> | void;\n}\n\n// SchemaIndex for subscriber — maps event name to its schema pair.\n// @internal\nexport interface SubscriberSchemaIndex {\n\tget(name: string): { contractHash: string; pair: SchemaPair } | undefined;\n}\n\nconst DEFAULT_MAX_IN_FLIGHT = 32;\n\n// @public — см. ./README.md\nexport interface SubscriberDeps {\n\trpcClient: EventsClient;\n\tschemaIndex: SubscriberSchemaIndex;\n\tidentity: () => SubscriberIdentity | null;\n\thandlers: () => EventHandler[];\n\tmaxInFlight?: number;\n\tlogger?: Logger;\n\tsb?: ServiceBridge;\n\t// runWithTrace runs the handler inside an AsyncLocalStorage trace context\n\t// derived from envelope.xSbTrace so nested RPC/event calls inherit the trace.\n\t// Mandatory: a missing hook would silently drop trace propagation into the\n\t// delivered handler.\n\t// @internal\n\trunWithTrace: (xSbTrace: string, fn: () => Promise<void>) => Promise<void>;\n}\n\n// Subscriber opens a long-lived bidi Subscribe stream and dispatches inbound\n// EventDelivery messages to registered handlers by exact event name. Routing\n// + dedup live on the server (ADR-0011); handlers must be idempotent.\n// @public — см. ./README.md\nexport class Subscriber {\n\tprivate readonly deps: SubscriberDeps;\n\tprivate readonly logger: Logger;\n\tprivate readonly maxInFlight: number;\n\tprivate readonly runWithTrace: (\n\t\txSbTrace: string,\n\t\tfn: () => Promise<void>,\n\t) => Promise<void>;\n\n\tprivate _stopped = false;\n\tprivate _attempt = 0;\n\tprivate _timer: ReturnType<typeof setTimeout> | null = null;\n\t// biome-ignore lint/suspicious/noExplicitAny: grpc stream type is opaque\n\tprivate _stream: any | null = null;\n\n\t// Per-partition serial queues. Events that share a partition_key must reach\n\t// their handlers in publication order — the server enforces «one in_flight\n\t// per partition» but the gRPC stream \"data\" listener fires async, so two\n\t// deliveries can arrive in quick succession and race on handler scheduling.\n\t// We serialize by chaining a Promise per partition key. Empty partition_key\n\t// stays parallel (no FIFO requirement). Keys with no pending work are\n\t// dropped from the map after their chain drains.\n\tprivate partitionQueues = new Map<string, Promise<void>>();\n\n\tconstructor(deps: SubscriberDeps) {\n\t\tthis.deps = deps;\n\t\tthis.maxInFlight = deps.maxInFlight ?? DEFAULT_MAX_IN_FLIGHT;\n\t\tthis.logger = deps.logger ?? { warn: console.warn, error: console.error };\n\t\tthis.runWithTrace = deps.runWithTrace;\n\t}\n\n\tstart(): void {\n\t\tif (this._stopped) return;\n\t\tthis.connect();\n\t}\n\n\tasync stop(): Promise<void> {\n\t\tthis._stopped = true;\n\t\tif (this._timer !== null) {\n\t\t\tclearTimeout(this._timer);\n\t\t\tthis._timer = null;\n\t\t}\n\t\tif (this._stream) {\n\t\t\ttry {\n\t\t\t\tthis._stream.cancel?.();\n\t\t\t\tthis._stream.end?.();\n\t\t\t} catch {\n\t\t\t\t// ignore close errors\n\t\t\t}\n\t\t\tthis._stream = null;\n\t\t}\n\t}\n\n\tprivate connect(): void {\n\t\tif (this._stopped) return;\n\n\t\tconst id = this.deps.identity();\n\t\tif (!id) {\n\t\t\t// Identity not yet available — schedule reconnect.\n\t\t\tconst delay = nextDelay(++this._attempt);\n\t\t\tthis.scheduleReconnect(delay);\n\t\t\treturn;\n\t\t}\n\n\t\tconst stream = this.deps.rpcClient.subscribe();\n\t\tthis._stream = stream;\n\n\t\t// Send SubscribeInit as the first message.\n\t\tstream.write(\n\t\t\tSubscribeClientMessageFns.create({\n\t\t\t\tinit: SubscribeInit.create({\n\t\t\t\t\tsubscriberServiceId: id.serviceId,\n\t\t\t\t\tsubscriberInstanceId: id.instanceId,\n\t\t\t\t\tmaxInFlight: this.maxInFlight,\n\t\t\t\t}),\n\t\t\t}),\n\t\t);\n\n\t\tstream.on(\n\t\t\t\"data\",\n\t\t\t(msg: {\n\t\t\t\tdelivery?: {\n\t\t\t\t\tdeliveryId: string;\n\t\t\t\t\tenvelope?: {\n\t\t\t\t\t\tid: string;\n\t\t\t\t\t\tname: string;\n\t\t\t\t\t\tpayload: Uint8Array;\n\t\t\t\t\t\tpartitionKey?: string;\n\t\t\t\t\t\txSbTrace?: string;\n\t\t\t\t\t};\n\t\t\t\t\tattempt: number;\n\t\t\t\t};\n\t\t\t}) => {\n\t\t\t\tif (msg.delivery) {\n\t\t\t\t\tconst delivery = msg.delivery;\n\t\t\t\t\tconst key = delivery.envelope?.partitionKey ?? \"\";\n\t\t\t\t\tconst xSbTrace = delivery.envelope?.xSbTrace ?? \"\";\n\t\t\t\t\tconst work = () =>\n\t\t\t\t\t\tthis.runWithTrace(xSbTrace, () =>\n\t\t\t\t\t\t\tthis.handleDelivery(stream, delivery),\n\t\t\t\t\t\t);\n\t\t\t\t\tif (key === \"\") {\n\t\t\t\t\t\t// No partition → parallel processing OK.\n\t\t\t\t\t\tvoid work();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\t// Chain onto the partition's queue so the next handler waits\n\t\t\t\t\t// for the previous one's full handler→ack cycle to complete.\n\t\t\t\t\tconst prev = this.partitionQueues.get(key) ?? Promise.resolve();\n\t\t\t\t\tconst next = prev.then(work, work);\n\t\t\t\t\tthis.partitionQueues.set(key, next);\n\t\t\t\t\tvoid next.finally(() => {\n\t\t\t\t\t\tif (this.partitionQueues.get(key) === next) {\n\t\t\t\t\t\t\tthis.partitionQueues.delete(key);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t},\n\t\t);\n\n\t\tstream.on(\"error\", (err: Error) => {\n\t\t\tthis.logger.warn(\"events: subscriber: stream error\", err.message);\n\t\t\tthis._stream = null;\n\t\t\tif (!this._stopped) {\n\t\t\t\tconst delay = nextDelay(++this._attempt);\n\t\t\t\tthis.scheduleReconnect(delay);\n\t\t\t}\n\t\t});\n\n\t\tstream.on(\"end\", () => {\n\t\t\tthis._stream = null;\n\t\t\tif (!this._stopped) {\n\t\t\t\tconst delay = nextDelay(++this._attempt);\n\t\t\t\tthis.scheduleReconnect(delay);\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate scheduleReconnect(delayMs: number): void {\n\t\tif (this._stopped) return;\n\t\tthis._timer = setTimeout(() => {\n\t\t\tthis._timer = null;\n\t\t\tthis.connect();\n\t\t}, delayMs);\n\t}\n\n\tprivate async handleDelivery(\n\t\t// biome-ignore lint/suspicious/noExplicitAny: grpc stream write\n\t\tstream: any,\n\t\tdelivery: {\n\t\t\tdeliveryId: string;\n\t\t\tenvelope?: { id: string; name: string; payload: Uint8Array };\n\t\t\tattempt: number;\n\t\t},\n\t): Promise<void> {\n\t\tconst { deliveryId, envelope } = delivery;\n\t\tif (!envelope) {\n\t\t\tthis.sendNack(stream, deliveryId, \"missing envelope\");\n\t\t\treturn;\n\t\t}\n\n\t\tconst { id: eventId, name, payload } = envelope;\n\t\tconst schemaEntry = this.deps.schemaIndex.get(name);\n\t\tif (!schemaEntry) {\n\t\t\tthis.sendNack(stream, deliveryId, \"no_schema\", eventId);\n\t\t\treturn;\n\t\t}\n\n\t\t// Dispatch by exact name — server is the single source of truth for\n\t\t// routing (ADR-0011). Handlers must be idempotent.\n\t\tconst handlers = this.deps.handlers().filter((h) => h.pattern === name);\n\t\tif (handlers.length === 0) {\n\t\t\tthis.sendAck(stream, deliveryId, eventId);\n\t\t\treturn;\n\t\t}\n\n\t\t// Decode payload once.\n\t\tlet decoded: unknown;\n\t\ttry {\n\t\t\tdecoded = schemaEntry.pair.input.decode(payload);\n\t\t} catch (decodeErr) {\n\t\t\tthis.sendNack(\n\t\t\t\tstream,\n\t\t\t\tdeliveryId,\n\t\t\t\t`decode_error: ${String(decodeErr)}`,\n\t\t\t\teventId,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tfor (const handler of handlers) {\n\t\t\ttry {\n\t\t\t\tawait handler.fn(decoded);\n\t\t\t} catch (err) {\n\t\t\t\tthis.sendNack(stream, deliveryId, String(err), eventId);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tthis.sendAck(stream, deliveryId, eventId);\n\n\t\t// Successful delivery — reset attempt counter.\n\t\tthis._attempt = 0;\n\t}\n\n\t// biome-ignore lint/suspicious/noExplicitAny: grpc stream write\n\tprivate sendAck(stream: any, deliveryId: string, eventId?: string): void {\n\t\ttry {\n\t\t\tconst msg: SubscribeClientMessage = {\n\t\t\t\tack: Ack.create({\n\t\t\t\t\tdeliveryId,\n\t\t\t\t\teventId: eventId ? Buffer.from(eventId) : Buffer.alloc(0),\n\t\t\t\t}),\n\t\t\t};\n\t\t\tstream.write(msg);\n\t\t} catch (err) {\n\t\t\tthis.logger.warn(\"events: subscriber: ack write failed\", String(err));\n\t\t}\n\t}\n\n\tprivate sendNack(\n\t\t// biome-ignore lint/suspicious/noExplicitAny: grpc stream write\n\t\tstream: any,\n\t\tdeliveryId: string,\n\t\terrorMessage: string,\n\t\teventId?: string,\n\t): void {\n\t\ttry {\n\t\t\tconst msg: SubscribeClientMessage = {\n\t\t\t\tnack: Nack.create({\n\t\t\t\t\tdeliveryId,\n\t\t\t\t\terrorMessage,\n\t\t\t\t\teventId: eventId ? Buffer.from(eventId) : Buffer.alloc(0),\n\t\t\t\t}),\n\t\t\t};\n\t\t\tstream.write(msg);\n\t\t} catch (err) {\n\t\t\tthis.logger.warn(\"events: subscriber: nack write failed\", String(err));\n\t\t}\n\t}\n}\n","// @public — см. ./README.md\n\nimport { createHash } from \"node:crypto\";\nimport { MethodType } from \"../pb/servicebridge/v1/registry\";\nimport type { Registry } from \"../registry/registry\";\nimport type {\n\tCatchupPolicy,\n\tDeclaredDep,\n\tJobHandler,\n\tJobOpts,\n\tOverlapPolicy,\n\tRetryPolicy,\n\tTrigger,\n} from \"./types\";\n\n// JobDomain — namespace `sb.job` for declaring scheduled jobs. Mirrors\n// EventDomain / WorkflowDomain shape: singular namespace, `handle()` verb,\n// (name, opts, fn) positional signature.\n//\n// Registration goes through Registry.RegisterAndWatch via an IncomingMethod\n// with type=JOB and a canonical-spec JSON in input_schema_json. The runtime\n// side parses the canonical spec (CanonicalJobSpec) and creates the\n// definition + schedule via jobs.Registrar.RegisterJob.\n//\n// JobDomain also stores a local lookup table (name → {opts, fn}) so the\n// JobSubscriber can resolve incoming JobExecution messages to the right\n// handler + per-job concurrency settings.\nexport class JobDomain {\n\tprivate readonly _byName = new Map<\n\t\tstring,\n\t\t{ opts: JobOpts; fn: JobHandler }\n\t>();\n\n\tconstructor(private readonly registry: Registry) {}\n\n\thandle(name: string, opts: JobOpts, fn: JobHandler): void {\n\t\tvalidateOpts(name, opts);\n\t\tif (this._byName.has(name)) {\n\t\t\tthrow new Error(\n\t\t\t\t`sb.job.handle: duplicate job name ${JSON.stringify(name)}`,\n\t\t\t);\n\t\t}\n\t\tconst canonical = canonicalJobSpec(opts);\n\t\tconst json = JSON.stringify(canonical);\n\t\tconst contractHash = sha256Hex(json);\n\t\tthis.registry._handle.job(name, contractHash, json, fn);\n\t\tthis._byName.set(name, { opts, fn });\n\t}\n\n\t/** @internal — used by JobSubscriber to dispatch incoming executions. */\n\tlookup(name: string): { opts: JobOpts; fn: JobHandler } | undefined {\n\t\treturn this._byName.get(name);\n\t}\n\n\t/** @internal — used by ServiceBridge to skip subscriber startup when empty. */\n\tsize(): number {\n\t\treturn this._byName.size;\n\t}\n}\n\n// canonicalJobSpec converts user-facing JobOpts into the on-wire canonical\n// shape matching runtime/internal/jobs/canonical.go::CanonicalJobSpec.\n//\n// Field order and key names MUST stay aligned with the Go struct — any drift\n// silently changes contract_hash on either side.\ninterface CanonicalJobSpec {\n\ttrigger: CanonicalTrigger;\n\tcatchup?: CatchupPolicy;\n\toverlap?: OverlapPolicy;\n\tdeps?: Array<{ kind: string; target: string }>;\n\tmaxAttempts?: number;\n\tleaseTtlMs?: number;\n\tmaxConcurrent?: number;\n\tretry?: RetryPolicy;\n}\n\ninterface CanonicalTrigger {\n\tcron?: { expr: string; tz?: string };\n\tdelayed?: { runAtUnixMs: number };\n\tinterval?: { everyMs: number };\n}\n\nfunction canonicalJobSpec(opts: JobOpts): CanonicalJobSpec {\n\tconst out: CanonicalJobSpec = {\n\t\ttrigger: canonicalTrigger(opts.trigger),\n\t};\n\tif (opts.catchup) out.catchup = opts.catchup;\n\tif (opts.overlap) out.overlap = opts.overlap;\n\tif (opts.deps && opts.deps.length > 0) {\n\t\tout.deps = opts.deps.map(depToCanonical);\n\t}\n\tif (opts.maxAttempts !== undefined) out.maxAttempts = opts.maxAttempts;\n\tif (opts.leaseTtlMs !== undefined) out.leaseTtlMs = opts.leaseTtlMs;\n\tif (opts.maxConcurrent !== undefined) out.maxConcurrent = opts.maxConcurrent;\n\tif (opts.retry) out.retry = opts.retry;\n\treturn out;\n}\n\nfunction canonicalTrigger(t: Trigger): CanonicalTrigger {\n\tif (\"cron\" in t) {\n\t\tconst c: CanonicalTrigger[\"cron\"] = { expr: t.cron };\n\t\tif (t.tz) c.tz = t.tz;\n\t\treturn { cron: c };\n\t}\n\tif (\"delayed\" in t) {\n\t\tconst at = t.delayed.at;\n\t\tlet ms: number;\n\t\tif (at instanceof Date) ms = at.getTime();\n\t\telse if (typeof at === \"number\") ms = at;\n\t\telse ms = new Date(at).getTime();\n\t\tif (Number.isNaN(ms)) {\n\t\t\tthrow new Error(\n\t\t\t\t\"sb.job.handle: delayed.at is not a valid Date / number / string\",\n\t\t\t);\n\t\t}\n\t\treturn { delayed: { runAtUnixMs: ms } };\n\t}\n\tif (\"interval\" in t) {\n\t\treturn { interval: { everyMs: t.interval } };\n\t}\n\tthrow new Error(\"sb.job.handle: trigger must be cron | delayed | interval\");\n}\n\nfunction depToCanonical(d: DeclaredDep): { kind: string; target: string } {\n\tif (\"rpc\" in d) return { kind: \"rpc\", target: d.rpc };\n\tif (\"event\" in d) return { kind: \"event\", target: d.event };\n\tif (\"workflow\" in d) return { kind: \"workflow\", target: d.workflow };\n\tthrow new Error(\"sb.job.handle: dep must be {rpc} | {event} | {workflow}\");\n}\n\nfunction validateOpts(name: string, opts: JobOpts): void {\n\tif (!name || typeof name !== \"string\") {\n\t\tthrow new Error(\"sb.job.handle: name is required\");\n\t}\n\tif (!opts || typeof opts !== \"object\") {\n\t\tthrow new Error(\"sb.job.handle: opts is required\");\n\t}\n\tif (!opts.trigger) {\n\t\tthrow new Error(\"sb.job.handle: opts.trigger is required\");\n\t}\n\tconst t = opts.trigger as Record<string, unknown>;\n\tconst keys = [\"cron\", \"delayed\", \"interval\"].filter(\n\t\t(k) => t[k] !== undefined,\n\t);\n\tif (keys.length !== 1) {\n\t\tthrow new Error(\n\t\t\t`sb.job.handle: trigger must have exactly one of cron|delayed|interval, got ${keys.length}`,\n\t\t);\n\t}\n\tif (\"cron\" in t && typeof t.cron === \"string\") {\n\t\tconst fields = t.cron.trim().split(/\\s+/);\n\t\tif (fields.length !== 5) {\n\t\t\tthrow new Error(\n\t\t\t\t`sb.job.handle: cron must be 5-field (no seconds); got ${fields.length} fields`,\n\t\t\t);\n\t\t}\n\t}\n\tif (\"interval\" in t && typeof t.interval === \"number\") {\n\t\tif (t.interval <= 0) {\n\t\t\tthrow new Error(\"sb.job.handle: interval must be > 0 ms\");\n\t\t}\n\t}\n}\n\nfunction sha256Hex(s: string): string {\n\treturn createHash(\"sha256\").update(s).digest(\"hex\");\n}\n","// Code generated by protoc-gen-ts_proto. DO NOT EDIT.\n// versions:\n// protoc-gen-ts_proto v2.11.8\n// protoc unknown\n// source: servicebridge/v1/registry.proto\n\n/* eslint-disable */\nimport { BinaryReader, BinaryWriter } from \"@bufbuild/protobuf/wire\";\nimport {\n type CallOptions,\n type ChannelCredentials,\n Client,\n type ClientOptions,\n type ClientReadableStream,\n type handleServerStreamingCall,\n makeGenericClientConstructor,\n type Metadata,\n type UntypedServiceImplementation,\n} from \"@grpc/grpc-js\";\n\nexport enum MethodType {\n METHOD_TYPE_UNSPECIFIED = 0,\n METHOD_TYPE_RPC = 1,\n METHOD_TYPE_EVENT = 2,\n METHOD_TYPE_WORKFLOW = 3,\n METHOD_TYPE_JOB = 4,\n METHOD_TYPE_HTTP = 5,\n UNRECOGNIZED = -1,\n}\n\n/**\n * CaptureMode is one channel's payload capture policy. The runtime is the\n * single authority: it resolves each channel's mode from runtime settings and\n * pushes the whole CaptureModes set to every SDK over RegisterAndWatch. SDKs\n * apply the mode for an op's channel as its effective capture mode; a per-handler\n * override may only narrow it (privacy ordering NONE < ERRORS < ALL), never\n * widen it.\n */\nexport enum CaptureMode {\n CAPTURE_MODE_UNSPECIFIED = 0,\n CAPTURE_MODE_ALL = 1,\n CAPTURE_MODE_ERRORS = 2,\n CAPTURE_MODE_NONE = 3,\n UNRECOGNIZED = -1,\n}\n\n/**\n * CaptureModes carries the per-channel payload capture policy pushed to SDKs.\n * One CaptureMode per op channel; the runtime resolves each from its matching\n * <channel>.payload_capture setting. The SDK picks the mode for an op's channel.\n * Jobs carry no input/output payload (JobExecution has no args, the handler\n * returns void), so the job channel has no capture mode — field 5 is reserved.\n */\nexport interface CaptureModes {\n rpc: CaptureMode;\n http: CaptureMode;\n event: CaptureMode;\n workflow: CaptureMode;\n}\n\nexport interface IncomingMethod {\n type: MethodType;\n name: string;\n inputSchemaJson: Buffer;\n outputSchemaJson: Buffer;\n streaming: boolean;\n /**\n * SDK-supplied contract hash (hex SHA-256). Runtime stores opaque,\n * does not recompute. Empty for non-RPC method types (event/workflow/job/http).\n */\n contractHash: string;\n}\n\nexport interface PublishedEvent {\n name: string;\n schemaJson: Buffer;\n /**\n * SDK-supplied contract hash (hex SHA-256) of the Protobuf descriptor for\n * this event's payload schema. Empty when the publisher declared the event\n * without a schema. Runtime stores opaque, does not recompute (ADR-0005).\n */\n contractHash: string;\n}\n\nexport interface OutgoingDep {\n serviceName: string;\n methodName: string;\n type: MethodType;\n}\n\nexport interface EventSubscription {\n pattern: string;\n durable: boolean;\n}\n\nexport interface RegisterRequest {\n incoming: IncomingMethod[];\n published: PublishedEvent[];\n outgoing: OutgoingDep[];\n callEndpoint: string;\n eventSubscriptions: EventSubscription[];\n /**\n * Public HTTP host:port of this SDK instance (ADR 0001 — HTTP lives in user\n * app). Used only by Service Map / Discovery; runtime does not proxy HTTP.\n * Empty when SDK has no HTTP integration registered.\n */\n httpEndpoint: string;\n}\n\nexport interface MethodDescriptor {\n serviceName: string;\n serviceId: string;\n instanceId: string;\n type: MethodType;\n name: string;\n contractHash: string;\n published: boolean;\n inputSchema: Buffer;\n outputSchema: Buffer;\n streaming: boolean;\n}\n\nexport interface ServiceInstanceInfo {\n instanceId: string;\n serviceId: string;\n serviceName: string;\n callEndpoint: string;\n status: string;\n /**\n * Public HTTP host:port of this instance (ADR 0001). Empty when instance has\n * no HTTP integration or after disconnect.\n */\n httpEndpoint: string;\n /**\n * Start of the current unhealthy window for this instance (ADR-0008 §6).\n * Unix-ms timestamp; 0 when the instance is healthy. SDK-side LB treats it as a hint.\n */\n isUnhealthySinceUnixMs: number;\n}\n\nexport interface RegistrySnapshot {\n methods: MethodDescriptor[];\n instances: ServiceInstanceInfo[];\n /**\n * ── Service-map enrichment (ADR-0014) ────────────────────────────────────\n * Per-service event subscriptions visible to the caller. Combined with\n * event publishers from `methods` (METHOD_TYPE_EVENT + published=true) this\n * lets UI / SDK draw the full pub/sub graph including wildcards.\n */\n eventSubscriptions: EventSubscriptionDescriptor[];\n /**\n * Per-service outgoing call declarations from sb.service(...). One row per\n * (caller_service, target_service, target_method, target_type) tuple.\n */\n outgoingCalls: OutgoingCallDescriptor[];\n /**\n * Policy evaluation for the caller of this RegisterAndWatch stream — the\n * caller's effective capabilities + rules + per-declaration warnings.\n */\n policy?:\n | PolicyEvaluation\n | undefined;\n /**\n * Per-channel payload capture modes. Always stamped on the snapshot so the\n * SDK has an effective mode per channel from the first frame (before any\n * update).\n */\n captureModes?: CaptureModes | undefined;\n}\n\nexport interface RegistryUpdate {\n added: MethodDescriptor[];\n removed: MethodDescriptor[];\n addedInstances: ServiceInstanceInfo[];\n removedInstances: ServiceInstanceInfo[];\n /** Same enrichment as RegistrySnapshot.* but incremental. */\n addedEventSubscriptions: EventSubscriptionDescriptor[];\n removedEventSubscriptions: EventSubscriptionDescriptor[];\n addedOutgoingCalls: OutgoingCallDescriptor[];\n removedOutgoingCalls: OutgoingCallDescriptor[];\n /**\n * When policy changes (NOTIFY policy_changed touches caller), runtime\n * re-emits the full PolicyEvaluation. Not incremental on purpose: policy\n * edits are rare and the evaluation is small.\n */\n policy?:\n | PolicyEvaluation\n | undefined;\n /**\n * Derived from per-field diff after a policy push. peer_id is in\n * added_peers when it first appears in the caller's scope; in removed_peers\n * when the last method/instance/subscription from that peer disappears from\n * scope. SDK uses these to update serviceMap and close stale direct-conns.\n */\n addedPeers: string[];\n removedPeers: string[];\n /**\n * Re-emitted full per-channel capture modes when any channel's mode changes.\n * Like policy, not incremental: the whole set is sent on change.\n */\n captureModes?: CaptureModes | undefined;\n}\n\nexport interface RegistryEvent {\n snapshot?: RegistrySnapshot | undefined;\n update?: RegistryUpdate | undefined;\n}\n\nexport interface EventSubscriptionDescriptor {\n serviceId: string;\n serviceName: string;\n /** AMQP pattern, supports * and # */\n pattern: string;\n durable: boolean;\n}\n\nexport interface OutgoingCallDescriptor {\n callerServiceId: string;\n callerServiceName: string;\n targetServiceId: string;\n targetServiceName: string;\n targetMethod: string;\n /** RPC, WORKFLOW, HTTP */\n targetType: MethodType;\n}\n\nexport interface PolicyEvaluation {\n /**\n * Capability flags currently enabled for the caller — names of the four\n * booleans on services that are TRUE: \"rpc.handle\", \"event.handle\",\n * \"workflow.handle\", \"job.handle\".\n */\n capabilities: string[];\n /** The caller's effective egress rules. */\n egress: PolicyRule[];\n /** The caller's effective acceptance rules. */\n acceptance: PolicyRule[];\n /** Per-declaration violations from the most recent registration. */\n warnings: PolicyViolation[];\n}\n\nexport interface PolicyRule {\n /**\n * 'rpc.call' | 'workflow.run' | 'event.publish' for egress;\n * 'rpc.handle' | 'workflow.handle' | 'event.handle' for acceptance.\n */\n action: string;\n /**\n * For rpc.* /workflow.*: peer service UUID (target for egress, caller for\n * acceptance). Empty string for event.* (no per-service routing).\n */\n peerServiceId: string;\n /** Human-readable peer service name (for UI / sb-policy show). */\n peerServiceName: string;\n /**\n * Method name pattern (literal or '*') for rpc.* /workflow.*; AMQP pattern\n * for event.*.\n */\n targetName: string;\n}\n\nexport interface PolicyViolation {\n /**\n * Declaration type, e.g. 'rpc.call', 'event.handle', 'event.publish',\n * 'rpc.handle' (capability), etc.\n */\n declaration: string;\n /** Concrete value, e.g. 'payments/charge', 'orders.*'. */\n value: string;\n /** 'capability' | 'self_egress' | 'self_acceptance' | 'peer_acceptance'. */\n denySide: string;\n /** Human-readable explanation. */\n reason: string;\n}\n\nfunction createBaseCaptureModes(): CaptureModes {\n return { rpc: 0, http: 0, event: 0, workflow: 0 };\n}\n\nexport const CaptureModes: MessageFns<CaptureModes> = {\n encode(message: CaptureModes, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.rpc !== 0) {\n writer.uint32(8).int32(message.rpc);\n }\n if (message.http !== 0) {\n writer.uint32(16).int32(message.http);\n }\n if (message.event !== 0) {\n writer.uint32(24).int32(message.event);\n }\n if (message.workflow !== 0) {\n writer.uint32(32).int32(message.workflow);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): CaptureModes {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseCaptureModes();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 8) {\n break;\n }\n\n message.rpc = reader.int32() as any;\n continue;\n }\n case 2: {\n if (tag !== 16) {\n break;\n }\n\n message.http = reader.int32() as any;\n continue;\n }\n case 3: {\n if (tag !== 24) {\n break;\n }\n\n message.event = reader.int32() as any;\n continue;\n }\n case 4: {\n if (tag !== 32) {\n break;\n }\n\n message.workflow = reader.int32() as any;\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<CaptureModes>, I>>(base?: I): CaptureModes {\n return CaptureModes.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<CaptureModes>, I>>(object: I): CaptureModes {\n const message = createBaseCaptureModes();\n message.rpc = object.rpc ?? 0;\n message.http = object.http ?? 0;\n message.event = object.event ?? 0;\n message.workflow = object.workflow ?? 0;\n return message;\n },\n};\n\nfunction createBaseIncomingMethod(): IncomingMethod {\n return {\n type: 0,\n name: \"\",\n inputSchemaJson: Buffer.alloc(0),\n outputSchemaJson: Buffer.alloc(0),\n streaming: false,\n contractHash: \"\",\n };\n}\n\nexport const IncomingMethod: MessageFns<IncomingMethod> = {\n encode(message: IncomingMethod, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.type !== 0) {\n writer.uint32(8).int32(message.type);\n }\n if (message.name !== \"\") {\n writer.uint32(18).string(message.name);\n }\n if (message.inputSchemaJson.length !== 0) {\n writer.uint32(26).bytes(message.inputSchemaJson);\n }\n if (message.outputSchemaJson.length !== 0) {\n writer.uint32(34).bytes(message.outputSchemaJson);\n }\n if (message.streaming !== false) {\n writer.uint32(40).bool(message.streaming);\n }\n if (message.contractHash !== \"\") {\n writer.uint32(50).string(message.contractHash);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): IncomingMethod {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseIncomingMethod();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 8) {\n break;\n }\n\n message.type = reader.int32() as any;\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.name = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.inputSchemaJson = Buffer.from(reader.bytes());\n continue;\n }\n case 4: {\n if (tag !== 34) {\n break;\n }\n\n message.outputSchemaJson = Buffer.from(reader.bytes());\n continue;\n }\n case 5: {\n if (tag !== 40) {\n break;\n }\n\n message.streaming = reader.bool();\n continue;\n }\n case 6: {\n if (tag !== 50) {\n break;\n }\n\n message.contractHash = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<IncomingMethod>, I>>(base?: I): IncomingMethod {\n return IncomingMethod.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<IncomingMethod>, I>>(object: I): IncomingMethod {\n const message = createBaseIncomingMethod();\n message.type = object.type ?? 0;\n message.name = object.name ?? \"\";\n message.inputSchemaJson = object.inputSchemaJson ?? Buffer.alloc(0);\n message.outputSchemaJson = object.outputSchemaJson ?? Buffer.alloc(0);\n message.streaming = object.streaming ?? false;\n message.contractHash = object.contractHash ?? \"\";\n return message;\n },\n};\n\nfunction createBasePublishedEvent(): PublishedEvent {\n return { name: \"\", schemaJson: Buffer.alloc(0), contractHash: \"\" };\n}\n\nexport const PublishedEvent: MessageFns<PublishedEvent> = {\n encode(message: PublishedEvent, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.name !== \"\") {\n writer.uint32(10).string(message.name);\n }\n if (message.schemaJson.length !== 0) {\n writer.uint32(18).bytes(message.schemaJson);\n }\n if (message.contractHash !== \"\") {\n writer.uint32(26).string(message.contractHash);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): PublishedEvent {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBasePublishedEvent();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.name = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.schemaJson = Buffer.from(reader.bytes());\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.contractHash = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<PublishedEvent>, I>>(base?: I): PublishedEvent {\n return PublishedEvent.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<PublishedEvent>, I>>(object: I): PublishedEvent {\n const message = createBasePublishedEvent();\n message.name = object.name ?? \"\";\n message.schemaJson = object.schemaJson ?? Buffer.alloc(0);\n message.contractHash = object.contractHash ?? \"\";\n return message;\n },\n};\n\nfunction createBaseOutgoingDep(): OutgoingDep {\n return { serviceName: \"\", methodName: \"\", type: 0 };\n}\n\nexport const OutgoingDep: MessageFns<OutgoingDep> = {\n encode(message: OutgoingDep, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.serviceName !== \"\") {\n writer.uint32(10).string(message.serviceName);\n }\n if (message.methodName !== \"\") {\n writer.uint32(18).string(message.methodName);\n }\n if (message.type !== 0) {\n writer.uint32(24).int32(message.type);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): OutgoingDep {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseOutgoingDep();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.serviceName = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.methodName = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 24) {\n break;\n }\n\n message.type = reader.int32() as any;\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<OutgoingDep>, I>>(base?: I): OutgoingDep {\n return OutgoingDep.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<OutgoingDep>, I>>(object: I): OutgoingDep {\n const message = createBaseOutgoingDep();\n message.serviceName = object.serviceName ?? \"\";\n message.methodName = object.methodName ?? \"\";\n message.type = object.type ?? 0;\n return message;\n },\n};\n\nfunction createBaseEventSubscription(): EventSubscription {\n return { pattern: \"\", durable: false };\n}\n\nexport const EventSubscription: MessageFns<EventSubscription> = {\n encode(message: EventSubscription, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.pattern !== \"\") {\n writer.uint32(10).string(message.pattern);\n }\n if (message.durable !== false) {\n writer.uint32(16).bool(message.durable);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): EventSubscription {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseEventSubscription();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.pattern = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 16) {\n break;\n }\n\n message.durable = reader.bool();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<EventSubscription>, I>>(base?: I): EventSubscription {\n return EventSubscription.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<EventSubscription>, I>>(object: I): EventSubscription {\n const message = createBaseEventSubscription();\n message.pattern = object.pattern ?? \"\";\n message.durable = object.durable ?? false;\n return message;\n },\n};\n\nfunction createBaseRegisterRequest(): RegisterRequest {\n return { incoming: [], published: [], outgoing: [], callEndpoint: \"\", eventSubscriptions: [], httpEndpoint: \"\" };\n}\n\nexport const RegisterRequest: MessageFns<RegisterRequest> = {\n encode(message: RegisterRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n for (const v of message.incoming) {\n IncomingMethod.encode(v!, writer.uint32(10).fork()).join();\n }\n for (const v of message.published) {\n PublishedEvent.encode(v!, writer.uint32(18).fork()).join();\n }\n for (const v of message.outgoing) {\n OutgoingDep.encode(v!, writer.uint32(26).fork()).join();\n }\n if (message.callEndpoint !== \"\") {\n writer.uint32(34).string(message.callEndpoint);\n }\n for (const v of message.eventSubscriptions) {\n EventSubscription.encode(v!, writer.uint32(42).fork()).join();\n }\n if (message.httpEndpoint !== \"\") {\n writer.uint32(50).string(message.httpEndpoint);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): RegisterRequest {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseRegisterRequest();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.incoming.push(IncomingMethod.decode(reader, reader.uint32()));\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.published.push(PublishedEvent.decode(reader, reader.uint32()));\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.outgoing.push(OutgoingDep.decode(reader, reader.uint32()));\n continue;\n }\n case 4: {\n if (tag !== 34) {\n break;\n }\n\n message.callEndpoint = reader.string();\n continue;\n }\n case 5: {\n if (tag !== 42) {\n break;\n }\n\n message.eventSubscriptions.push(EventSubscription.decode(reader, reader.uint32()));\n continue;\n }\n case 6: {\n if (tag !== 50) {\n break;\n }\n\n message.httpEndpoint = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<RegisterRequest>, I>>(base?: I): RegisterRequest {\n return RegisterRequest.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<RegisterRequest>, I>>(object: I): RegisterRequest {\n const message = createBaseRegisterRequest();\n message.incoming = object.incoming?.map((e) => IncomingMethod.fromPartial(e)) || [];\n message.published = object.published?.map((e) => PublishedEvent.fromPartial(e)) || [];\n message.outgoing = object.outgoing?.map((e) => OutgoingDep.fromPartial(e)) || [];\n message.callEndpoint = object.callEndpoint ?? \"\";\n message.eventSubscriptions = object.eventSubscriptions?.map((e) => EventSubscription.fromPartial(e)) || [];\n message.httpEndpoint = object.httpEndpoint ?? \"\";\n return message;\n },\n};\n\nfunction createBaseMethodDescriptor(): MethodDescriptor {\n return {\n serviceName: \"\",\n serviceId: \"\",\n instanceId: \"\",\n type: 0,\n name: \"\",\n contractHash: \"\",\n published: false,\n inputSchema: Buffer.alloc(0),\n outputSchema: Buffer.alloc(0),\n streaming: false,\n };\n}\n\nexport const MethodDescriptor: MessageFns<MethodDescriptor> = {\n encode(message: MethodDescriptor, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.serviceName !== \"\") {\n writer.uint32(10).string(message.serviceName);\n }\n if (message.serviceId !== \"\") {\n writer.uint32(18).string(message.serviceId);\n }\n if (message.instanceId !== \"\") {\n writer.uint32(26).string(message.instanceId);\n }\n if (message.type !== 0) {\n writer.uint32(32).int32(message.type);\n }\n if (message.name !== \"\") {\n writer.uint32(42).string(message.name);\n }\n if (message.contractHash !== \"\") {\n writer.uint32(50).string(message.contractHash);\n }\n if (message.published !== false) {\n writer.uint32(56).bool(message.published);\n }\n if (message.inputSchema.length !== 0) {\n writer.uint32(66).bytes(message.inputSchema);\n }\n if (message.outputSchema.length !== 0) {\n writer.uint32(74).bytes(message.outputSchema);\n }\n if (message.streaming !== false) {\n writer.uint32(80).bool(message.streaming);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): MethodDescriptor {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseMethodDescriptor();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.serviceName = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.serviceId = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.instanceId = reader.string();\n continue;\n }\n case 4: {\n if (tag !== 32) {\n break;\n }\n\n message.type = reader.int32() as any;\n continue;\n }\n case 5: {\n if (tag !== 42) {\n break;\n }\n\n message.name = reader.string();\n continue;\n }\n case 6: {\n if (tag !== 50) {\n break;\n }\n\n message.contractHash = reader.string();\n continue;\n }\n case 7: {\n if (tag !== 56) {\n break;\n }\n\n message.published = reader.bool();\n continue;\n }\n case 8: {\n if (tag !== 66) {\n break;\n }\n\n message.inputSchema = Buffer.from(reader.bytes());\n continue;\n }\n case 9: {\n if (tag !== 74) {\n break;\n }\n\n message.outputSchema = Buffer.from(reader.bytes());\n continue;\n }\n case 10: {\n if (tag !== 80) {\n break;\n }\n\n message.streaming = reader.bool();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<MethodDescriptor>, I>>(base?: I): MethodDescriptor {\n return MethodDescriptor.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<MethodDescriptor>, I>>(object: I): MethodDescriptor {\n const message = createBaseMethodDescriptor();\n message.serviceName = object.serviceName ?? \"\";\n message.serviceId = object.serviceId ?? \"\";\n message.instanceId = object.instanceId ?? \"\";\n message.type = object.type ?? 0;\n message.name = object.name ?? \"\";\n message.contractHash = object.contractHash ?? \"\";\n message.published = object.published ?? false;\n message.inputSchema = object.inputSchema ?? Buffer.alloc(0);\n message.outputSchema = object.outputSchema ?? Buffer.alloc(0);\n message.streaming = object.streaming ?? false;\n return message;\n },\n};\n\nfunction createBaseServiceInstanceInfo(): ServiceInstanceInfo {\n return {\n instanceId: \"\",\n serviceId: \"\",\n serviceName: \"\",\n callEndpoint: \"\",\n status: \"\",\n httpEndpoint: \"\",\n isUnhealthySinceUnixMs: 0,\n };\n}\n\nexport const ServiceInstanceInfo: MessageFns<ServiceInstanceInfo> = {\n encode(message: ServiceInstanceInfo, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.instanceId !== \"\") {\n writer.uint32(10).string(message.instanceId);\n }\n if (message.serviceId !== \"\") {\n writer.uint32(18).string(message.serviceId);\n }\n if (message.serviceName !== \"\") {\n writer.uint32(26).string(message.serviceName);\n }\n if (message.callEndpoint !== \"\") {\n writer.uint32(34).string(message.callEndpoint);\n }\n if (message.status !== \"\") {\n writer.uint32(42).string(message.status);\n }\n if (message.httpEndpoint !== \"\") {\n writer.uint32(50).string(message.httpEndpoint);\n }\n if (message.isUnhealthySinceUnixMs !== 0) {\n writer.uint32(56).int64(message.isUnhealthySinceUnixMs);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): ServiceInstanceInfo {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseServiceInstanceInfo();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.instanceId = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.serviceId = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.serviceName = reader.string();\n continue;\n }\n case 4: {\n if (tag !== 34) {\n break;\n }\n\n message.callEndpoint = reader.string();\n continue;\n }\n case 5: {\n if (tag !== 42) {\n break;\n }\n\n message.status = reader.string();\n continue;\n }\n case 6: {\n if (tag !== 50) {\n break;\n }\n\n message.httpEndpoint = reader.string();\n continue;\n }\n case 7: {\n if (tag !== 56) {\n break;\n }\n\n message.isUnhealthySinceUnixMs = longToNumber(reader.int64());\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<ServiceInstanceInfo>, I>>(base?: I): ServiceInstanceInfo {\n return ServiceInstanceInfo.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<ServiceInstanceInfo>, I>>(object: I): ServiceInstanceInfo {\n const message = createBaseServiceInstanceInfo();\n message.instanceId = object.instanceId ?? \"\";\n message.serviceId = object.serviceId ?? \"\";\n message.serviceName = object.serviceName ?? \"\";\n message.callEndpoint = object.callEndpoint ?? \"\";\n message.status = object.status ?? \"\";\n message.httpEndpoint = object.httpEndpoint ?? \"\";\n message.isUnhealthySinceUnixMs = object.isUnhealthySinceUnixMs ?? 0;\n return message;\n },\n};\n\nfunction createBaseRegistrySnapshot(): RegistrySnapshot {\n return {\n methods: [],\n instances: [],\n eventSubscriptions: [],\n outgoingCalls: [],\n policy: undefined,\n captureModes: undefined,\n };\n}\n\nexport const RegistrySnapshot: MessageFns<RegistrySnapshot> = {\n encode(message: RegistrySnapshot, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n for (const v of message.methods) {\n MethodDescriptor.encode(v!, writer.uint32(10).fork()).join();\n }\n for (const v of message.instances) {\n ServiceInstanceInfo.encode(v!, writer.uint32(18).fork()).join();\n }\n for (const v of message.eventSubscriptions) {\n EventSubscriptionDescriptor.encode(v!, writer.uint32(26).fork()).join();\n }\n for (const v of message.outgoingCalls) {\n OutgoingCallDescriptor.encode(v!, writer.uint32(34).fork()).join();\n }\n if (message.policy !== undefined) {\n PolicyEvaluation.encode(message.policy, writer.uint32(42).fork()).join();\n }\n if (message.captureModes !== undefined) {\n CaptureModes.encode(message.captureModes, writer.uint32(58).fork()).join();\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): RegistrySnapshot {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseRegistrySnapshot();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.methods.push(MethodDescriptor.decode(reader, reader.uint32()));\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.instances.push(ServiceInstanceInfo.decode(reader, reader.uint32()));\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.eventSubscriptions.push(EventSubscriptionDescriptor.decode(reader, reader.uint32()));\n continue;\n }\n case 4: {\n if (tag !== 34) {\n break;\n }\n\n message.outgoingCalls.push(OutgoingCallDescriptor.decode(reader, reader.uint32()));\n continue;\n }\n case 5: {\n if (tag !== 42) {\n break;\n }\n\n message.policy = PolicyEvaluation.decode(reader, reader.uint32());\n continue;\n }\n case 7: {\n if (tag !== 58) {\n break;\n }\n\n message.captureModes = CaptureModes.decode(reader, reader.uint32());\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<RegistrySnapshot>, I>>(base?: I): RegistrySnapshot {\n return RegistrySnapshot.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<RegistrySnapshot>, I>>(object: I): RegistrySnapshot {\n const message = createBaseRegistrySnapshot();\n message.methods = object.methods?.map((e) => MethodDescriptor.fromPartial(e)) || [];\n message.instances = object.instances?.map((e) => ServiceInstanceInfo.fromPartial(e)) || [];\n message.eventSubscriptions = object.eventSubscriptions?.map((e) => EventSubscriptionDescriptor.fromPartial(e)) ||\n [];\n message.outgoingCalls = object.outgoingCalls?.map((e) => OutgoingCallDescriptor.fromPartial(e)) || [];\n message.policy = (object.policy !== undefined && object.policy !== null)\n ? PolicyEvaluation.fromPartial(object.policy)\n : undefined;\n message.captureModes = (object.captureModes !== undefined && object.captureModes !== null)\n ? CaptureModes.fromPartial(object.captureModes)\n : undefined;\n return message;\n },\n};\n\nfunction createBaseRegistryUpdate(): RegistryUpdate {\n return {\n added: [],\n removed: [],\n addedInstances: [],\n removedInstances: [],\n addedEventSubscriptions: [],\n removedEventSubscriptions: [],\n addedOutgoingCalls: [],\n removedOutgoingCalls: [],\n policy: undefined,\n addedPeers: [],\n removedPeers: [],\n captureModes: undefined,\n };\n}\n\nexport const RegistryUpdate: MessageFns<RegistryUpdate> = {\n encode(message: RegistryUpdate, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n for (const v of message.added) {\n MethodDescriptor.encode(v!, writer.uint32(10).fork()).join();\n }\n for (const v of message.removed) {\n MethodDescriptor.encode(v!, writer.uint32(18).fork()).join();\n }\n for (const v of message.addedInstances) {\n ServiceInstanceInfo.encode(v!, writer.uint32(26).fork()).join();\n }\n for (const v of message.removedInstances) {\n ServiceInstanceInfo.encode(v!, writer.uint32(34).fork()).join();\n }\n for (const v of message.addedEventSubscriptions) {\n EventSubscriptionDescriptor.encode(v!, writer.uint32(42).fork()).join();\n }\n for (const v of message.removedEventSubscriptions) {\n EventSubscriptionDescriptor.encode(v!, writer.uint32(50).fork()).join();\n }\n for (const v of message.addedOutgoingCalls) {\n OutgoingCallDescriptor.encode(v!, writer.uint32(58).fork()).join();\n }\n for (const v of message.removedOutgoingCalls) {\n OutgoingCallDescriptor.encode(v!, writer.uint32(66).fork()).join();\n }\n if (message.policy !== undefined) {\n PolicyEvaluation.encode(message.policy, writer.uint32(74).fork()).join();\n }\n for (const v of message.addedPeers) {\n writer.uint32(82).string(v!);\n }\n for (const v of message.removedPeers) {\n writer.uint32(90).string(v!);\n }\n if (message.captureModes !== undefined) {\n CaptureModes.encode(message.captureModes, writer.uint32(106).fork()).join();\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): RegistryUpdate {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseRegistryUpdate();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.added.push(MethodDescriptor.decode(reader, reader.uint32()));\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.removed.push(MethodDescriptor.decode(reader, reader.uint32()));\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.addedInstances.push(ServiceInstanceInfo.decode(reader, reader.uint32()));\n continue;\n }\n case 4: {\n if (tag !== 34) {\n break;\n }\n\n message.removedInstances.push(ServiceInstanceInfo.decode(reader, reader.uint32()));\n continue;\n }\n case 5: {\n if (tag !== 42) {\n break;\n }\n\n message.addedEventSubscriptions.push(EventSubscriptionDescriptor.decode(reader, reader.uint32()));\n continue;\n }\n case 6: {\n if (tag !== 50) {\n break;\n }\n\n message.removedEventSubscriptions.push(EventSubscriptionDescriptor.decode(reader, reader.uint32()));\n continue;\n }\n case 7: {\n if (tag !== 58) {\n break;\n }\n\n message.addedOutgoingCalls.push(OutgoingCallDescriptor.decode(reader, reader.uint32()));\n continue;\n }\n case 8: {\n if (tag !== 66) {\n break;\n }\n\n message.removedOutgoingCalls.push(OutgoingCallDescriptor.decode(reader, reader.uint32()));\n continue;\n }\n case 9: {\n if (tag !== 74) {\n break;\n }\n\n message.policy = PolicyEvaluation.decode(reader, reader.uint32());\n continue;\n }\n case 10: {\n if (tag !== 82) {\n break;\n }\n\n message.addedPeers.push(reader.string());\n continue;\n }\n case 11: {\n if (tag !== 90) {\n break;\n }\n\n message.removedPeers.push(reader.string());\n continue;\n }\n case 13: {\n if (tag !== 106) {\n break;\n }\n\n message.captureModes = CaptureModes.decode(reader, reader.uint32());\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<RegistryUpdate>, I>>(base?: I): RegistryUpdate {\n return RegistryUpdate.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<RegistryUpdate>, I>>(object: I): RegistryUpdate {\n const message = createBaseRegistryUpdate();\n message.added = object.added?.map((e) => MethodDescriptor.fromPartial(e)) || [];\n message.removed = object.removed?.map((e) => MethodDescriptor.fromPartial(e)) || [];\n message.addedInstances = object.addedInstances?.map((e) => ServiceInstanceInfo.fromPartial(e)) || [];\n message.removedInstances = object.removedInstances?.map((e) => ServiceInstanceInfo.fromPartial(e)) || [];\n message.addedEventSubscriptions =\n object.addedEventSubscriptions?.map((e) => EventSubscriptionDescriptor.fromPartial(e)) || [];\n message.removedEventSubscriptions =\n object.removedEventSubscriptions?.map((e) => EventSubscriptionDescriptor.fromPartial(e)) || [];\n message.addedOutgoingCalls = object.addedOutgoingCalls?.map((e) => OutgoingCallDescriptor.fromPartial(e)) || [];\n message.removedOutgoingCalls = object.removedOutgoingCalls?.map((e) => OutgoingCallDescriptor.fromPartial(e)) || [];\n message.policy = (object.policy !== undefined && object.policy !== null)\n ? PolicyEvaluation.fromPartial(object.policy)\n : undefined;\n message.addedPeers = object.addedPeers?.map((e) => e) || [];\n message.removedPeers = object.removedPeers?.map((e) => e) || [];\n message.captureModes = (object.captureModes !== undefined && object.captureModes !== null)\n ? CaptureModes.fromPartial(object.captureModes)\n : undefined;\n return message;\n },\n};\n\nfunction createBaseRegistryEvent(): RegistryEvent {\n return { snapshot: undefined, update: undefined };\n}\n\nexport const RegistryEvent: MessageFns<RegistryEvent> = {\n encode(message: RegistryEvent, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.snapshot !== undefined) {\n RegistrySnapshot.encode(message.snapshot, writer.uint32(10).fork()).join();\n }\n if (message.update !== undefined) {\n RegistryUpdate.encode(message.update, writer.uint32(18).fork()).join();\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): RegistryEvent {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseRegistryEvent();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.snapshot = RegistrySnapshot.decode(reader, reader.uint32());\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.update = RegistryUpdate.decode(reader, reader.uint32());\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<RegistryEvent>, I>>(base?: I): RegistryEvent {\n return RegistryEvent.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<RegistryEvent>, I>>(object: I): RegistryEvent {\n const message = createBaseRegistryEvent();\n message.snapshot = (object.snapshot !== undefined && object.snapshot !== null)\n ? RegistrySnapshot.fromPartial(object.snapshot)\n : undefined;\n message.update = (object.update !== undefined && object.update !== null)\n ? RegistryUpdate.fromPartial(object.update)\n : undefined;\n return message;\n },\n};\n\nfunction createBaseEventSubscriptionDescriptor(): EventSubscriptionDescriptor {\n return { serviceId: \"\", serviceName: \"\", pattern: \"\", durable: false };\n}\n\nexport const EventSubscriptionDescriptor: MessageFns<EventSubscriptionDescriptor> = {\n encode(message: EventSubscriptionDescriptor, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.serviceId !== \"\") {\n writer.uint32(10).string(message.serviceId);\n }\n if (message.serviceName !== \"\") {\n writer.uint32(18).string(message.serviceName);\n }\n if (message.pattern !== \"\") {\n writer.uint32(26).string(message.pattern);\n }\n if (message.durable !== false) {\n writer.uint32(32).bool(message.durable);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): EventSubscriptionDescriptor {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseEventSubscriptionDescriptor();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.serviceId = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.serviceName = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.pattern = reader.string();\n continue;\n }\n case 4: {\n if (tag !== 32) {\n break;\n }\n\n message.durable = reader.bool();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<EventSubscriptionDescriptor>, I>>(base?: I): EventSubscriptionDescriptor {\n return EventSubscriptionDescriptor.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<EventSubscriptionDescriptor>, I>>(object: I): EventSubscriptionDescriptor {\n const message = createBaseEventSubscriptionDescriptor();\n message.serviceId = object.serviceId ?? \"\";\n message.serviceName = object.serviceName ?? \"\";\n message.pattern = object.pattern ?? \"\";\n message.durable = object.durable ?? false;\n return message;\n },\n};\n\nfunction createBaseOutgoingCallDescriptor(): OutgoingCallDescriptor {\n return {\n callerServiceId: \"\",\n callerServiceName: \"\",\n targetServiceId: \"\",\n targetServiceName: \"\",\n targetMethod: \"\",\n targetType: 0,\n };\n}\n\nexport const OutgoingCallDescriptor: MessageFns<OutgoingCallDescriptor> = {\n encode(message: OutgoingCallDescriptor, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.callerServiceId !== \"\") {\n writer.uint32(10).string(message.callerServiceId);\n }\n if (message.callerServiceName !== \"\") {\n writer.uint32(18).string(message.callerServiceName);\n }\n if (message.targetServiceId !== \"\") {\n writer.uint32(26).string(message.targetServiceId);\n }\n if (message.targetServiceName !== \"\") {\n writer.uint32(34).string(message.targetServiceName);\n }\n if (message.targetMethod !== \"\") {\n writer.uint32(42).string(message.targetMethod);\n }\n if (message.targetType !== 0) {\n writer.uint32(48).int32(message.targetType);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): OutgoingCallDescriptor {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseOutgoingCallDescriptor();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.callerServiceId = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.callerServiceName = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.targetServiceId = reader.string();\n continue;\n }\n case 4: {\n if (tag !== 34) {\n break;\n }\n\n message.targetServiceName = reader.string();\n continue;\n }\n case 5: {\n if (tag !== 42) {\n break;\n }\n\n message.targetMethod = reader.string();\n continue;\n }\n case 6: {\n if (tag !== 48) {\n break;\n }\n\n message.targetType = reader.int32() as any;\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<OutgoingCallDescriptor>, I>>(base?: I): OutgoingCallDescriptor {\n return OutgoingCallDescriptor.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<OutgoingCallDescriptor>, I>>(object: I): OutgoingCallDescriptor {\n const message = createBaseOutgoingCallDescriptor();\n message.callerServiceId = object.callerServiceId ?? \"\";\n message.callerServiceName = object.callerServiceName ?? \"\";\n message.targetServiceId = object.targetServiceId ?? \"\";\n message.targetServiceName = object.targetServiceName ?? \"\";\n message.targetMethod = object.targetMethod ?? \"\";\n message.targetType = object.targetType ?? 0;\n return message;\n },\n};\n\nfunction createBasePolicyEvaluation(): PolicyEvaluation {\n return { capabilities: [], egress: [], acceptance: [], warnings: [] };\n}\n\nexport const PolicyEvaluation: MessageFns<PolicyEvaluation> = {\n encode(message: PolicyEvaluation, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n for (const v of message.capabilities) {\n writer.uint32(10).string(v!);\n }\n for (const v of message.egress) {\n PolicyRule.encode(v!, writer.uint32(18).fork()).join();\n }\n for (const v of message.acceptance) {\n PolicyRule.encode(v!, writer.uint32(26).fork()).join();\n }\n for (const v of message.warnings) {\n PolicyViolation.encode(v!, writer.uint32(34).fork()).join();\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): PolicyEvaluation {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBasePolicyEvaluation();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.capabilities.push(reader.string());\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.egress.push(PolicyRule.decode(reader, reader.uint32()));\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.acceptance.push(PolicyRule.decode(reader, reader.uint32()));\n continue;\n }\n case 4: {\n if (tag !== 34) {\n break;\n }\n\n message.warnings.push(PolicyViolation.decode(reader, reader.uint32()));\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<PolicyEvaluation>, I>>(base?: I): PolicyEvaluation {\n return PolicyEvaluation.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<PolicyEvaluation>, I>>(object: I): PolicyEvaluation {\n const message = createBasePolicyEvaluation();\n message.capabilities = object.capabilities?.map((e) => e) || [];\n message.egress = object.egress?.map((e) => PolicyRule.fromPartial(e)) || [];\n message.acceptance = object.acceptance?.map((e) => PolicyRule.fromPartial(e)) || [];\n message.warnings = object.warnings?.map((e) => PolicyViolation.fromPartial(e)) || [];\n return message;\n },\n};\n\nfunction createBasePolicyRule(): PolicyRule {\n return { action: \"\", peerServiceId: \"\", peerServiceName: \"\", targetName: \"\" };\n}\n\nexport const PolicyRule: MessageFns<PolicyRule> = {\n encode(message: PolicyRule, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.action !== \"\") {\n writer.uint32(10).string(message.action);\n }\n if (message.peerServiceId !== \"\") {\n writer.uint32(18).string(message.peerServiceId);\n }\n if (message.peerServiceName !== \"\") {\n writer.uint32(26).string(message.peerServiceName);\n }\n if (message.targetName !== \"\") {\n writer.uint32(34).string(message.targetName);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): PolicyRule {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBasePolicyRule();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.action = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.peerServiceId = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.peerServiceName = reader.string();\n continue;\n }\n case 4: {\n if (tag !== 34) {\n break;\n }\n\n message.targetName = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<PolicyRule>, I>>(base?: I): PolicyRule {\n return PolicyRule.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<PolicyRule>, I>>(object: I): PolicyRule {\n const message = createBasePolicyRule();\n message.action = object.action ?? \"\";\n message.peerServiceId = object.peerServiceId ?? \"\";\n message.peerServiceName = object.peerServiceName ?? \"\";\n message.targetName = object.targetName ?? \"\";\n return message;\n },\n};\n\nfunction createBasePolicyViolation(): PolicyViolation {\n return { declaration: \"\", value: \"\", denySide: \"\", reason: \"\" };\n}\n\nexport const PolicyViolation: MessageFns<PolicyViolation> = {\n encode(message: PolicyViolation, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.declaration !== \"\") {\n writer.uint32(10).string(message.declaration);\n }\n if (message.value !== \"\") {\n writer.uint32(18).string(message.value);\n }\n if (message.denySide !== \"\") {\n writer.uint32(26).string(message.denySide);\n }\n if (message.reason !== \"\") {\n writer.uint32(34).string(message.reason);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): PolicyViolation {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBasePolicyViolation();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.declaration = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.value = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.denySide = reader.string();\n continue;\n }\n case 4: {\n if (tag !== 34) {\n break;\n }\n\n message.reason = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<PolicyViolation>, I>>(base?: I): PolicyViolation {\n return PolicyViolation.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<PolicyViolation>, I>>(object: I): PolicyViolation {\n const message = createBasePolicyViolation();\n message.declaration = object.declaration ?? \"\";\n message.value = object.value ?? \"\";\n message.denySide = object.denySide ?? \"\";\n message.reason = object.reason ?? \"\";\n return message;\n },\n};\n\nexport type RegistryService = typeof RegistryService;\nexport const RegistryService = {\n registerAndWatch: {\n path: \"/servicebridge.v1.Registry/RegisterAndWatch\" as const,\n requestStream: false as const,\n responseStream: true as const,\n requestSerialize: (value: RegisterRequest): Buffer => Buffer.from(RegisterRequest.encode(value).finish()),\n requestDeserialize: (value: Buffer): RegisterRequest => RegisterRequest.decode(value),\n responseSerialize: (value: RegistryEvent): Buffer => Buffer.from(RegistryEvent.encode(value).finish()),\n responseDeserialize: (value: Buffer): RegistryEvent => RegistryEvent.decode(value),\n },\n} as const;\n\nexport interface RegistryServer extends UntypedServiceImplementation {\n registerAndWatch: handleServerStreamingCall<RegisterRequest, RegistryEvent>;\n}\n\nexport interface RegistryClient extends Client {\n registerAndWatch(request: RegisterRequest, options?: Partial<CallOptions>): ClientReadableStream<RegistryEvent>;\n registerAndWatch(\n request: RegisterRequest,\n metadata?: Metadata,\n options?: Partial<CallOptions>,\n ): ClientReadableStream<RegistryEvent>;\n}\n\nexport const RegistryClient = makeGenericClientConstructor(RegistryService, \"servicebridge.v1.Registry\") as unknown as {\n new (address: string, credentials: ChannelCredentials, options?: Partial<ClientOptions>): RegistryClient;\n service: typeof RegistryService;\n serviceName: string;\n};\n\ntype Builtin = Date | Function | Uint8Array | string | number | boolean | undefined;\n\ntype DeepPartial<T> = T extends Builtin ? T\n : T extends globalThis.Array<infer U> ? globalThis.Array<DeepPartial<U>>\n : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>>\n : T extends {} ? { [K in keyof T]?: DeepPartial<T[K]> }\n : Partial<T>;\n\ntype KeysOfUnion<T> = T extends T ? keyof T : never;\ntype Exact<P, I extends P> = P extends Builtin ? P\n : P & { [K in keyof P]: Exact<P[K], I[K]> } & { [K in Exclude<keyof I, KeysOfUnion<P>>]: never };\n\nfunction longToNumber(int64: { toString(): string }): number {\n const num = globalThis.Number(int64.toString());\n if (num > globalThis.Number.MAX_SAFE_INTEGER) {\n throw new globalThis.Error(\"Value is larger than Number.MAX_SAFE_INTEGER\");\n }\n if (num < globalThis.Number.MIN_SAFE_INTEGER) {\n throw new globalThis.Error(\"Value is smaller than Number.MIN_SAFE_INTEGER\");\n }\n return num;\n}\n\ninterface MessageFns<T> {\n encode(message: T, writer?: BinaryWriter): BinaryWriter;\n decode(input: BinaryReader | Uint8Array, length?: number): T;\n create<I extends Exact<DeepPartial<T>, I>>(base?: I): T;\n fromPartial<I extends Exact<DeepPartial<T>, I>>(object: I): T;\n}\n","// @internal — см. ./README.md\n\nimport type { ClientReadableStream, ServiceError } from \"@grpc/grpc-js\";\nimport type { JobExecution, JobsClient } from \"../pb/servicebridge/v1/jobs\";\nimport type { JobDomain } from \"./domain\";\nimport type { JobHandler, JobHandlerCtx, JobOpts } from \"./types\";\n\nconst RECONNECT_LADDER_MS = [1000, 5000, 15000, 30000, 60000] as const;\nconst HEARTBEAT_INTERVAL_MS = 5_000;\nconst HEARTBEAT_FAIL_THRESHOLD = 3;\n\nexport interface Logger {\n\twarn(msg: string): void;\n\terror(msg: string): void;\n}\n\nexport interface IdentityProvider {\n\tserviceId: string;\n\tinstanceId: string;\n}\n\nfunction nextDelay(attempt: number): number {\n\tconst idx = Math.min(Math.max(attempt, 0), RECONNECT_LADDER_MS.length - 1);\n\treturn (\n\t\tRECONNECT_LADDER_MS[idx] ??\n\t\tRECONNECT_LADDER_MS[RECONNECT_LADDER_MS.length - 1] ??\n\t\t60000\n\t);\n}\n\n// Semaphore limits concurrent in-flight job executions.\nclass Semaphore {\n\tprivate _count: number;\n\tprivate readonly _queue: Array<() => void> = [];\n\n\tconstructor(limit: number) {\n\t\tthis._count = limit;\n\t}\n\n\tacquire(): Promise<void> {\n\t\tif (this._count > 0) {\n\t\t\tthis._count--;\n\t\t\treturn Promise.resolve();\n\t\t}\n\t\treturn new Promise((resolve) => {\n\t\t\tthis._queue.push(resolve);\n\t\t});\n\t}\n\n\trelease(): void {\n\t\tconst next = this._queue.shift();\n\t\tif (next) {\n\t\t\tnext();\n\t\t} else {\n\t\t\tthis._count++;\n\t\t}\n\t}\n}\n\n// @public — см. ./README.md\nexport interface SubscriberDeps {\n\trpcClient: JobsClient;\n\tidentity: () => IdentityProvider | null;\n\tdomain: JobDomain;\n\tlogger: Logger;\n\t// runWithTrace runs the handler inside an AsyncLocalStorage trace context\n\t// derived from JobExecution.xSbTrace so nested RPC/event calls inherit the\n\t// trace. Mandatory: a missing hook would silently drop trace propagation\n\t// into the job handler.\n\trunWithTrace: (xSbTrace: string, fn: () => Promise<void>) => Promise<void>;\n}\n\nexport class JobSubscriber {\n\tprivate _stream: ClientReadableStream<JobExecution> | null = null;\n\tprivate _closed = false;\n\tprivate _heartbeatTimer: ReturnType<typeof setInterval> | null = null;\n\tprivate _heartbeatFailures = 0;\n\tprivate readonly _semaphores = new Map<string, Semaphore>();\n\tprivate readonly runWithTrace: (\n\t\txSbTrace: string,\n\t\tfn: () => Promise<void>,\n\t) => Promise<void>;\n\n\tconstructor(private readonly d: SubscriberDeps) {\n\t\tthis.runWithTrace = d.runWithTrace;\n\t}\n\n\tstart(): void {\n\t\tvoid this.connectLoop(0);\n\t\tthis.startHeartbeat();\n\t}\n\n\tasync stop(): Promise<void> {\n\t\tthis._closed = true;\n\t\tthis.stopHeartbeat();\n\t\tthis._stream?.cancel();\n\t}\n\n\tprivate async connectLoop(attempt: number): Promise<void> {\n\t\twhile (!this._closed) {\n\t\t\ttry {\n\t\t\t\tawait this.runOnce();\n\t\t\t\tattempt = 0;\n\t\t\t} catch (err) {\n\t\t\t\tif (this._closed) return;\n\t\t\t\tthis.d.logger.warn(\n\t\t\t\t\t`jobs subscriber: stream error: ${(err as Error).message}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst delay = nextDelay(attempt++);\n\t\t\tawait new Promise((r) => setTimeout(r, delay));\n\t\t}\n\t}\n\n\tprivate runOnce(): Promise<void> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst id = this.d.identity();\n\t\t\tif (!id) {\n\t\t\t\treject(new Error(\"jobs subscriber: no identity yet\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst stream = this.d.rpcClient.subscribe({\n\t\t\t\tserviceId: id.serviceId,\n\t\t\t\tinstanceId: id.instanceId,\n\t\t\t});\n\t\t\tthis._stream = stream;\n\n\t\t\tstream.on(\"data\", (exec: JobExecution) => {\n\t\t\t\tvoid this.dispatch(exec).catch((err) => {\n\t\t\t\t\tthis.d.logger.error(\n\t\t\t\t\t\t`jobs: dispatch error for execution ${exec.executionId}: ${(err as Error).message}`,\n\t\t\t\t\t);\n\t\t\t\t});\n\t\t\t});\n\t\t\tstream.on(\"error\", (err: ServiceError) => reject(err));\n\t\t\tstream.on(\"end\", () => resolve());\n\t\t});\n\t}\n\n\tprivate async dispatch(exec: JobExecution): Promise<void> {\n\t\tconst id = this.d.identity();\n\t\tif (!id) {\n\t\t\tthis.d.logger.warn(\n\t\t\t\t`jobs: no identity, dropping execution ${exec.executionId}`,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tconst reg = this.d.domain.lookup(exec.jobName);\n\t\tif (!reg) {\n\t\t\tthis.d.logger.warn(\n\t\t\t\t`jobs: no handler for job \"${exec.jobName}\", dropping execution ${exec.executionId}`,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tconst maxConcurrent = reg.opts.maxConcurrent ?? 0;\n\t\tconst sem = this.getSemaphore(exec.jobName, maxConcurrent);\n\n\t\tawait sem.acquire();\n\t\ttry {\n\t\t\tawait this.run(exec, reg.fn, reg.opts, id.instanceId);\n\t\t} finally {\n\t\t\tsem.release();\n\t\t}\n\t}\n\n\tprivate async run(\n\t\texec: JobExecution,\n\t\tfn: JobHandler,\n\t\t_opts: JobOpts,\n\t\tinstanceId: string,\n\t): Promise<void> {\n\t\tconst abortCtrl = new AbortController();\n\t\tconst ctx: JobHandlerCtx = {\n\t\t\tjobName: exec.jobName,\n\t\t\texecutionId: exec.executionId,\n\t\t\tscheduledAt: new Date(exec.scheduledAtUnixMs),\n\t\t\tlocalScheduledAt: new Date(exec.localScheduledAtUnixMs),\n\t\t\tattempt: exec.attempt,\n\t\t\tidempotencyKey: exec.idempotencyKey,\n\t\t\tsignal: abortCtrl.signal,\n\t\t};\n\n\t\t// xSbTrace is the canonical \"<traceID>-<parentOpID>\" header per\n\t\t// ADR T-017. The runtime always emits it for telemetry-enabled\n\t\t// executions; absent (empty string) means runtime telemetry was\n\t\t// disabled — handler still runs, just without trace propagation.\n\t\tconst xSbTrace = exec.xSbTrace ?? \"\";\n\n\t\ttry {\n\t\t\tawait this.runWithTrace(xSbTrace, () => Promise.resolve(fn(ctx)));\n\t\t\tthis.sendResult(exec, instanceId, true);\n\t\t} catch (err) {\n\t\t\tconst error = err as Error & { retryable?: boolean };\n\t\t\tconst retryable = error.retryable !== false;\n\t\t\tthis.sendResult(exec, instanceId, false, {\n\t\t\t\terrorMessage: error.message ?? \"unknown error\",\n\t\t\t\tretryable,\n\t\t\t});\n\t\t}\n\t}\n\n\tprivate sendResult(\n\t\texec: JobExecution,\n\t\tinstanceId: string,\n\t\tsuccess: true,\n\t\tfailure?: undefined,\n\t): void;\n\tprivate sendResult(\n\t\texec: JobExecution,\n\t\tinstanceId: string,\n\t\tsuccess: false,\n\t\tfailure: { errorMessage: string; retryable: boolean },\n\t): void;\n\tprivate sendResult(\n\t\texec: JobExecution,\n\t\tinstanceId: string,\n\t\tsuccess: boolean,\n\t\tfailure?: { errorMessage: string; retryable: boolean },\n\t): void {\n\t\tconst request = success\n\t\t\t? {\n\t\t\t\t\texecutionId: exec.executionId,\n\t\t\t\t\tinstanceId,\n\t\t\t\t\tleaseEpoch: exec.leaseEpoch,\n\t\t\t\t\tsuccess: {},\n\t\t\t\t\tfailure: undefined,\n\t\t\t\t}\n\t\t\t: {\n\t\t\t\t\texecutionId: exec.executionId,\n\t\t\t\t\tinstanceId,\n\t\t\t\t\tleaseEpoch: exec.leaseEpoch,\n\t\t\t\t\tsuccess: undefined,\n\t\t\t\t\tfailure: {\n\t\t\t\t\t\terrorMessage: failure?.errorMessage ?? \"unknown error\",\n\t\t\t\t\t\tretryable: failure?.retryable ?? true,\n\t\t\t\t\t},\n\t\t\t\t};\n\n\t\tthis.d.rpcClient.jobResult(request, (err) => {\n\t\t\tif (err) {\n\t\t\t\tthis.d.logger.warn(\n\t\t\t\t\t`jobs: failed to send result for execution ${exec.executionId}: ${err.message}`,\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate getSemaphore(jobName: string, maxConcurrent: number): Semaphore {\n\t\tconst existing = this._semaphores.get(jobName);\n\t\tif (existing) return existing;\n\t\tconst limit = maxConcurrent > 0 ? maxConcurrent : Number.MAX_SAFE_INTEGER;\n\t\tconst sem = new Semaphore(limit);\n\t\tthis._semaphores.set(jobName, sem);\n\t\treturn sem;\n\t}\n\n\tprivate startHeartbeat(): void {\n\t\tthis._heartbeatFailures = 0;\n\t\tthis._heartbeatTimer = setInterval(() => {\n\t\t\tif (this._closed) {\n\t\t\t\tthis.stopHeartbeat();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst id = this.d.identity();\n\t\t\tif (!id) return;\n\t\t\ttry {\n\t\t\t\tthis.d.rpcClient.heartbeat(\n\t\t\t\t\t{ serviceId: id.serviceId, instanceId: id.instanceId },\n\t\t\t\t\t(err) => {\n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\tthis._heartbeatFailures++;\n\t\t\t\t\t\t\tthis.d.logger.warn(\n\t\t\t\t\t\t\t\t`jobs: heartbeat failed (${this._heartbeatFailures}/${HEARTBEAT_FAIL_THRESHOLD}): ${err.message}`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (this._heartbeatFailures >= HEARTBEAT_FAIL_THRESHOLD) {\n\t\t\t\t\t\t\t\tthis.d.logger.warn(\n\t\t\t\t\t\t\t\t\t\"jobs: heartbeat threshold reached, reconnecting\",\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tthis._stream?.cancel();\n\t\t\t\t\t\t\t\tthis._heartbeatFailures = 0;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tthis._heartbeatFailures = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\tthis.stopHeartbeat();\n\t\t\t}\n\t\t}, HEARTBEAT_INTERVAL_MS);\n\t}\n\n\tprivate stopHeartbeat(): void {\n\t\tif (this._heartbeatTimer) {\n\t\t\tclearInterval(this._heartbeatTimer);\n\t\t\tthis._heartbeatTimer = null;\n\t\t}\n\t}\n}\n","// Code generated by protoc-gen-ts_proto. DO NOT EDIT.\n// versions:\n// protoc-gen-ts_proto v2.11.8\n// protoc unknown\n// source: servicebridge/v1/control.proto\n\n/* eslint-disable */\nimport { BinaryReader, BinaryWriter } from \"@bufbuild/protobuf/wire\";\nimport {\n type CallOptions,\n type ChannelCredentials,\n Client,\n type ClientOptions,\n type ClientReadableStream,\n type ClientUnaryCall,\n type handleServerStreamingCall,\n type handleUnaryCall,\n makeGenericClientConstructor,\n type Metadata,\n type ServiceError,\n type UntypedServiceImplementation,\n} from \"@grpc/grpc-js\";\n\nexport interface OpenRequest {\n}\n\nexport interface RefreshCertRequest {\n csrDer: Buffer;\n}\n\nexport interface RefreshCertResponse {\n certDer: Buffer;\n caChainDer: Buffer;\n notAfterUnix: number;\n instanceId: string;\n}\n\nexport interface ServerControl {\n welcome?: Welcome | undefined;\n drain?: Drain | undefined;\n}\n\nexport interface Welcome {\n sessionId: string;\n serviceId: string;\n serviceName: string;\n}\n\nexport interface Drain {\n reason: string;\n}\n\nfunction createBaseOpenRequest(): OpenRequest {\n return {};\n}\n\nexport const OpenRequest: MessageFns<OpenRequest> = {\n encode(_: OpenRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): OpenRequest {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseOpenRequest();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<OpenRequest>, I>>(base?: I): OpenRequest {\n return OpenRequest.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<OpenRequest>, I>>(_: I): OpenRequest {\n const message = createBaseOpenRequest();\n return message;\n },\n};\n\nfunction createBaseRefreshCertRequest(): RefreshCertRequest {\n return { csrDer: Buffer.alloc(0) };\n}\n\nexport const RefreshCertRequest: MessageFns<RefreshCertRequest> = {\n encode(message: RefreshCertRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.csrDer.length !== 0) {\n writer.uint32(10).bytes(message.csrDer);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): RefreshCertRequest {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseRefreshCertRequest();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.csrDer = Buffer.from(reader.bytes());\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<RefreshCertRequest>, I>>(base?: I): RefreshCertRequest {\n return RefreshCertRequest.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<RefreshCertRequest>, I>>(object: I): RefreshCertRequest {\n const message = createBaseRefreshCertRequest();\n message.csrDer = object.csrDer ?? Buffer.alloc(0);\n return message;\n },\n};\n\nfunction createBaseRefreshCertResponse(): RefreshCertResponse {\n return { certDer: Buffer.alloc(0), caChainDer: Buffer.alloc(0), notAfterUnix: 0, instanceId: \"\" };\n}\n\nexport const RefreshCertResponse: MessageFns<RefreshCertResponse> = {\n encode(message: RefreshCertResponse, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.certDer.length !== 0) {\n writer.uint32(10).bytes(message.certDer);\n }\n if (message.caChainDer.length !== 0) {\n writer.uint32(18).bytes(message.caChainDer);\n }\n if (message.notAfterUnix !== 0) {\n writer.uint32(24).int64(message.notAfterUnix);\n }\n if (message.instanceId !== \"\") {\n writer.uint32(34).string(message.instanceId);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): RefreshCertResponse {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseRefreshCertResponse();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.certDer = Buffer.from(reader.bytes());\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.caChainDer = Buffer.from(reader.bytes());\n continue;\n }\n case 3: {\n if (tag !== 24) {\n break;\n }\n\n message.notAfterUnix = longToNumber(reader.int64());\n continue;\n }\n case 4: {\n if (tag !== 34) {\n break;\n }\n\n message.instanceId = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<RefreshCertResponse>, I>>(base?: I): RefreshCertResponse {\n return RefreshCertResponse.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<RefreshCertResponse>, I>>(object: I): RefreshCertResponse {\n const message = createBaseRefreshCertResponse();\n message.certDer = object.certDer ?? Buffer.alloc(0);\n message.caChainDer = object.caChainDer ?? Buffer.alloc(0);\n message.notAfterUnix = object.notAfterUnix ?? 0;\n message.instanceId = object.instanceId ?? \"\";\n return message;\n },\n};\n\nfunction createBaseServerControl(): ServerControl {\n return { welcome: undefined, drain: undefined };\n}\n\nexport const ServerControl: MessageFns<ServerControl> = {\n encode(message: ServerControl, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.welcome !== undefined) {\n Welcome.encode(message.welcome, writer.uint32(10).fork()).join();\n }\n if (message.drain !== undefined) {\n Drain.encode(message.drain, writer.uint32(18).fork()).join();\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): ServerControl {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseServerControl();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.welcome = Welcome.decode(reader, reader.uint32());\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.drain = Drain.decode(reader, reader.uint32());\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<ServerControl>, I>>(base?: I): ServerControl {\n return ServerControl.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<ServerControl>, I>>(object: I): ServerControl {\n const message = createBaseServerControl();\n message.welcome = (object.welcome !== undefined && object.welcome !== null)\n ? Welcome.fromPartial(object.welcome)\n : undefined;\n message.drain = (object.drain !== undefined && object.drain !== null) ? Drain.fromPartial(object.drain) : undefined;\n return message;\n },\n};\n\nfunction createBaseWelcome(): Welcome {\n return { sessionId: \"\", serviceId: \"\", serviceName: \"\" };\n}\n\nexport const Welcome: MessageFns<Welcome> = {\n encode(message: Welcome, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.sessionId !== \"\") {\n writer.uint32(10).string(message.sessionId);\n }\n if (message.serviceId !== \"\") {\n writer.uint32(18).string(message.serviceId);\n }\n if (message.serviceName !== \"\") {\n writer.uint32(26).string(message.serviceName);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): Welcome {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseWelcome();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.sessionId = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.serviceId = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.serviceName = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<Welcome>, I>>(base?: I): Welcome {\n return Welcome.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<Welcome>, I>>(object: I): Welcome {\n const message = createBaseWelcome();\n message.sessionId = object.sessionId ?? \"\";\n message.serviceId = object.serviceId ?? \"\";\n message.serviceName = object.serviceName ?? \"\";\n return message;\n },\n};\n\nfunction createBaseDrain(): Drain {\n return { reason: \"\" };\n}\n\nexport const Drain: MessageFns<Drain> = {\n encode(message: Drain, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.reason !== \"\") {\n writer.uint32(10).string(message.reason);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): Drain {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseDrain();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.reason = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<Drain>, I>>(base?: I): Drain {\n return Drain.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<Drain>, I>>(object: I): Drain {\n const message = createBaseDrain();\n message.reason = object.reason ?? \"\";\n return message;\n },\n};\n\n/**\n * Control plane stream. After Telemetry feature heartbeat moved out — Control\n * несёт только server-driven signalling: Welcome (один раз) и Drain (при\n * shutdown). Cert refresh — отдельным unary RPC.\n */\nexport type ControlService = typeof ControlService;\nexport const ControlService = {\n open: {\n path: \"/servicebridge.v1.Control/Open\" as const,\n requestStream: false as const,\n responseStream: true as const,\n requestSerialize: (value: OpenRequest): Buffer => Buffer.from(OpenRequest.encode(value).finish()),\n requestDeserialize: (value: Buffer): OpenRequest => OpenRequest.decode(value),\n responseSerialize: (value: ServerControl): Buffer => Buffer.from(ServerControl.encode(value).finish()),\n responseDeserialize: (value: Buffer): ServerControl => ServerControl.decode(value),\n },\n /**\n * RefreshCert reissues the caller's leaf cert via the existing mTLS\n * session (SPIFFE from cert == source of truth, no argon2).\n */\n refreshCert: {\n path: \"/servicebridge.v1.Control/RefreshCert\" as const,\n requestStream: false as const,\n responseStream: false as const,\n requestSerialize: (value: RefreshCertRequest): Buffer => Buffer.from(RefreshCertRequest.encode(value).finish()),\n requestDeserialize: (value: Buffer): RefreshCertRequest => RefreshCertRequest.decode(value),\n responseSerialize: (value: RefreshCertResponse): Buffer => Buffer.from(RefreshCertResponse.encode(value).finish()),\n responseDeserialize: (value: Buffer): RefreshCertResponse => RefreshCertResponse.decode(value),\n },\n} as const;\n\nexport interface ControlServer extends UntypedServiceImplementation {\n open: handleServerStreamingCall<OpenRequest, ServerControl>;\n /**\n * RefreshCert reissues the caller's leaf cert via the existing mTLS\n * session (SPIFFE from cert == source of truth, no argon2).\n */\n refreshCert: handleUnaryCall<RefreshCertRequest, RefreshCertResponse>;\n}\n\nexport interface ControlClient extends Client {\n open(request: OpenRequest, options?: Partial<CallOptions>): ClientReadableStream<ServerControl>;\n open(request: OpenRequest, metadata?: Metadata, options?: Partial<CallOptions>): ClientReadableStream<ServerControl>;\n /**\n * RefreshCert reissues the caller's leaf cert via the existing mTLS\n * session (SPIFFE from cert == source of truth, no argon2).\n */\n refreshCert(\n request: RefreshCertRequest,\n callback: (error: ServiceError | null, response: RefreshCertResponse) => void,\n ): ClientUnaryCall;\n refreshCert(\n request: RefreshCertRequest,\n metadata: Metadata,\n callback: (error: ServiceError | null, response: RefreshCertResponse) => void,\n ): ClientUnaryCall;\n refreshCert(\n request: RefreshCertRequest,\n metadata: Metadata,\n options: Partial<CallOptions>,\n callback: (error: ServiceError | null, response: RefreshCertResponse) => void,\n ): ClientUnaryCall;\n}\n\nexport const ControlClient = makeGenericClientConstructor(ControlService, \"servicebridge.v1.Control\") as unknown as {\n new (address: string, credentials: ChannelCredentials, options?: Partial<ClientOptions>): ControlClient;\n service: typeof ControlService;\n serviceName: string;\n};\n\ntype Builtin = Date | Function | Uint8Array | string | number | boolean | undefined;\n\ntype DeepPartial<T> = T extends Builtin ? T\n : T extends globalThis.Array<infer U> ? globalThis.Array<DeepPartial<U>>\n : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>>\n : T extends {} ? { [K in keyof T]?: DeepPartial<T[K]> }\n : Partial<T>;\n\ntype KeysOfUnion<T> = T extends T ? keyof T : never;\ntype Exact<P, I extends P> = P extends Builtin ? P\n : P & { [K in keyof P]: Exact<P[K], I[K]> } & { [K in Exclude<keyof I, KeysOfUnion<P>>]: never };\n\nfunction longToNumber(int64: { toString(): string }): number {\n const num = globalThis.Number(int64.toString());\n if (num > globalThis.Number.MAX_SAFE_INTEGER) {\n throw new globalThis.Error(\"Value is larger than Number.MAX_SAFE_INTEGER\");\n }\n if (num < globalThis.Number.MIN_SAFE_INTEGER) {\n throw new globalThis.Error(\"Value is smaller than Number.MIN_SAFE_INTEGER\");\n }\n return num;\n}\n\ninterface MessageFns<T> {\n encode(message: T, writer?: BinaryWriter): BinaryWriter;\n decode(input: BinaryReader | Uint8Array, length?: number): T;\n create<I extends Exact<DeepPartial<T>, I>>(base?: I): T;\n fromPartial<I extends Exact<DeepPartial<T>, I>>(object: I): T;\n}\n","// Code generated by protoc-gen-ts_proto. DO NOT EDIT.\n// versions:\n// protoc-gen-ts_proto v2.11.8\n// protoc unknown\n// source: servicebridge/v1/jobs.proto\n\n/* eslint-disable */\nimport { BinaryReader, BinaryWriter } from \"@bufbuild/protobuf/wire\";\nimport {\n type CallOptions,\n type ChannelCredentials,\n Client,\n type ClientOptions,\n type ClientReadableStream,\n type ClientUnaryCall,\n type handleServerStreamingCall,\n type handleUnaryCall,\n makeGenericClientConstructor,\n type Metadata,\n type ServiceError,\n type UntypedServiceImplementation,\n} from \"@grpc/grpc-js\";\n\nexport interface JobsSubscribeRequest {\n serviceId: string;\n instanceId: string;\n}\n\nexport interface JobExecution {\n executionId: string;\n jobDefinitionId: string;\n jobName: string;\n scheduledAtUnixMs: number;\n localScheduledAtUnixMs: number;\n attempt: number;\n leaseEpoch: number;\n idempotencyKey: string;\n /** \"traceID-parentOpID\" canonical format (T-017) */\n xSbTrace: string;\n}\n\nexport interface JobResultRequest {\n executionId: string;\n instanceId: string;\n leaseEpoch: number;\n success?: JobSuccess | undefined;\n failure?: JobFailure | undefined;\n}\n\nexport interface JobSuccess {\n}\n\nexport interface JobFailure {\n errorMessage: string;\n retryable: boolean;\n}\n\nexport interface JobResultResponse {\n accepted: boolean;\n}\n\nexport interface JobsHeartbeatRequest {\n serviceId: string;\n instanceId: string;\n}\n\nexport interface JobsHeartbeatResponse {\n}\n\nfunction createBaseJobsSubscribeRequest(): JobsSubscribeRequest {\n return { serviceId: \"\", instanceId: \"\" };\n}\n\nexport const JobsSubscribeRequest: MessageFns<JobsSubscribeRequest> = {\n encode(message: JobsSubscribeRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.serviceId !== \"\") {\n writer.uint32(10).string(message.serviceId);\n }\n if (message.instanceId !== \"\") {\n writer.uint32(18).string(message.instanceId);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): JobsSubscribeRequest {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseJobsSubscribeRequest();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.serviceId = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.instanceId = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<JobsSubscribeRequest>, I>>(base?: I): JobsSubscribeRequest {\n return JobsSubscribeRequest.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<JobsSubscribeRequest>, I>>(object: I): JobsSubscribeRequest {\n const message = createBaseJobsSubscribeRequest();\n message.serviceId = object.serviceId ?? \"\";\n message.instanceId = object.instanceId ?? \"\";\n return message;\n },\n};\n\nfunction createBaseJobExecution(): JobExecution {\n return {\n executionId: \"\",\n jobDefinitionId: \"\",\n jobName: \"\",\n scheduledAtUnixMs: 0,\n localScheduledAtUnixMs: 0,\n attempt: 0,\n leaseEpoch: 0,\n idempotencyKey: \"\",\n xSbTrace: \"\",\n };\n}\n\nexport const JobExecution: MessageFns<JobExecution> = {\n encode(message: JobExecution, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.executionId !== \"\") {\n writer.uint32(10).string(message.executionId);\n }\n if (message.jobDefinitionId !== \"\") {\n writer.uint32(18).string(message.jobDefinitionId);\n }\n if (message.jobName !== \"\") {\n writer.uint32(26).string(message.jobName);\n }\n if (message.scheduledAtUnixMs !== 0) {\n writer.uint32(32).int64(message.scheduledAtUnixMs);\n }\n if (message.localScheduledAtUnixMs !== 0) {\n writer.uint32(40).int64(message.localScheduledAtUnixMs);\n }\n if (message.attempt !== 0) {\n writer.uint32(48).uint32(message.attempt);\n }\n if (message.leaseEpoch !== 0) {\n writer.uint32(56).uint64(message.leaseEpoch);\n }\n if (message.idempotencyKey !== \"\") {\n writer.uint32(66).string(message.idempotencyKey);\n }\n if (message.xSbTrace !== \"\") {\n writer.uint32(74).string(message.xSbTrace);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): JobExecution {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseJobExecution();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.executionId = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.jobDefinitionId = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.jobName = reader.string();\n continue;\n }\n case 4: {\n if (tag !== 32) {\n break;\n }\n\n message.scheduledAtUnixMs = longToNumber(reader.int64());\n continue;\n }\n case 5: {\n if (tag !== 40) {\n break;\n }\n\n message.localScheduledAtUnixMs = longToNumber(reader.int64());\n continue;\n }\n case 6: {\n if (tag !== 48) {\n break;\n }\n\n message.attempt = reader.uint32();\n continue;\n }\n case 7: {\n if (tag !== 56) {\n break;\n }\n\n message.leaseEpoch = longToNumber(reader.uint64());\n continue;\n }\n case 8: {\n if (tag !== 66) {\n break;\n }\n\n message.idempotencyKey = reader.string();\n continue;\n }\n case 9: {\n if (tag !== 74) {\n break;\n }\n\n message.xSbTrace = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<JobExecution>, I>>(base?: I): JobExecution {\n return JobExecution.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<JobExecution>, I>>(object: I): JobExecution {\n const message = createBaseJobExecution();\n message.executionId = object.executionId ?? \"\";\n message.jobDefinitionId = object.jobDefinitionId ?? \"\";\n message.jobName = object.jobName ?? \"\";\n message.scheduledAtUnixMs = object.scheduledAtUnixMs ?? 0;\n message.localScheduledAtUnixMs = object.localScheduledAtUnixMs ?? 0;\n message.attempt = object.attempt ?? 0;\n message.leaseEpoch = object.leaseEpoch ?? 0;\n message.idempotencyKey = object.idempotencyKey ?? \"\";\n message.xSbTrace = object.xSbTrace ?? \"\";\n return message;\n },\n};\n\nfunction createBaseJobResultRequest(): JobResultRequest {\n return { executionId: \"\", instanceId: \"\", leaseEpoch: 0, success: undefined, failure: undefined };\n}\n\nexport const JobResultRequest: MessageFns<JobResultRequest> = {\n encode(message: JobResultRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.executionId !== \"\") {\n writer.uint32(10).string(message.executionId);\n }\n if (message.instanceId !== \"\") {\n writer.uint32(18).string(message.instanceId);\n }\n if (message.leaseEpoch !== 0) {\n writer.uint32(24).uint64(message.leaseEpoch);\n }\n if (message.success !== undefined) {\n JobSuccess.encode(message.success, writer.uint32(34).fork()).join();\n }\n if (message.failure !== undefined) {\n JobFailure.encode(message.failure, writer.uint32(42).fork()).join();\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): JobResultRequest {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseJobResultRequest();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.executionId = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.instanceId = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 24) {\n break;\n }\n\n message.leaseEpoch = longToNumber(reader.uint64());\n continue;\n }\n case 4: {\n if (tag !== 34) {\n break;\n }\n\n message.success = JobSuccess.decode(reader, reader.uint32());\n continue;\n }\n case 5: {\n if (tag !== 42) {\n break;\n }\n\n message.failure = JobFailure.decode(reader, reader.uint32());\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<JobResultRequest>, I>>(base?: I): JobResultRequest {\n return JobResultRequest.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<JobResultRequest>, I>>(object: I): JobResultRequest {\n const message = createBaseJobResultRequest();\n message.executionId = object.executionId ?? \"\";\n message.instanceId = object.instanceId ?? \"\";\n message.leaseEpoch = object.leaseEpoch ?? 0;\n message.success = (object.success !== undefined && object.success !== null)\n ? JobSuccess.fromPartial(object.success)\n : undefined;\n message.failure = (object.failure !== undefined && object.failure !== null)\n ? JobFailure.fromPartial(object.failure)\n : undefined;\n return message;\n },\n};\n\nfunction createBaseJobSuccess(): JobSuccess {\n return {};\n}\n\nexport const JobSuccess: MessageFns<JobSuccess> = {\n encode(_: JobSuccess, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): JobSuccess {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseJobSuccess();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<JobSuccess>, I>>(base?: I): JobSuccess {\n return JobSuccess.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<JobSuccess>, I>>(_: I): JobSuccess {\n const message = createBaseJobSuccess();\n return message;\n },\n};\n\nfunction createBaseJobFailure(): JobFailure {\n return { errorMessage: \"\", retryable: false };\n}\n\nexport const JobFailure: MessageFns<JobFailure> = {\n encode(message: JobFailure, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.errorMessage !== \"\") {\n writer.uint32(10).string(message.errorMessage);\n }\n if (message.retryable !== false) {\n writer.uint32(16).bool(message.retryable);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): JobFailure {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseJobFailure();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.errorMessage = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 16) {\n break;\n }\n\n message.retryable = reader.bool();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<JobFailure>, I>>(base?: I): JobFailure {\n return JobFailure.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<JobFailure>, I>>(object: I): JobFailure {\n const message = createBaseJobFailure();\n message.errorMessage = object.errorMessage ?? \"\";\n message.retryable = object.retryable ?? false;\n return message;\n },\n};\n\nfunction createBaseJobResultResponse(): JobResultResponse {\n return { accepted: false };\n}\n\nexport const JobResultResponse: MessageFns<JobResultResponse> = {\n encode(message: JobResultResponse, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.accepted !== false) {\n writer.uint32(8).bool(message.accepted);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): JobResultResponse {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseJobResultResponse();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 8) {\n break;\n }\n\n message.accepted = reader.bool();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<JobResultResponse>, I>>(base?: I): JobResultResponse {\n return JobResultResponse.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<JobResultResponse>, I>>(object: I): JobResultResponse {\n const message = createBaseJobResultResponse();\n message.accepted = object.accepted ?? false;\n return message;\n },\n};\n\nfunction createBaseJobsHeartbeatRequest(): JobsHeartbeatRequest {\n return { serviceId: \"\", instanceId: \"\" };\n}\n\nexport const JobsHeartbeatRequest: MessageFns<JobsHeartbeatRequest> = {\n encode(message: JobsHeartbeatRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.serviceId !== \"\") {\n writer.uint32(10).string(message.serviceId);\n }\n if (message.instanceId !== \"\") {\n writer.uint32(18).string(message.instanceId);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): JobsHeartbeatRequest {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseJobsHeartbeatRequest();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.serviceId = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.instanceId = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<JobsHeartbeatRequest>, I>>(base?: I): JobsHeartbeatRequest {\n return JobsHeartbeatRequest.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<JobsHeartbeatRequest>, I>>(object: I): JobsHeartbeatRequest {\n const message = createBaseJobsHeartbeatRequest();\n message.serviceId = object.serviceId ?? \"\";\n message.instanceId = object.instanceId ?? \"\";\n return message;\n },\n};\n\nfunction createBaseJobsHeartbeatResponse(): JobsHeartbeatResponse {\n return {};\n}\n\nexport const JobsHeartbeatResponse: MessageFns<JobsHeartbeatResponse> = {\n encode(_: JobsHeartbeatResponse, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): JobsHeartbeatResponse {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseJobsHeartbeatResponse();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<JobsHeartbeatResponse>, I>>(base?: I): JobsHeartbeatResponse {\n return JobsHeartbeatResponse.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<JobsHeartbeatResponse>, I>>(_: I): JobsHeartbeatResponse {\n const message = createBaseJobsHeartbeatResponse();\n return message;\n },\n};\n\n/**\n * Jobs — data-plane RPCs for runtime-triggered scheduled tasks.\n *\n * Registration is NOT here: it flows through Registry.RegisterAndWatch as\n * IncomingMethod{type=METHOD_TYPE_JOB, ...} just like RPC / Event / Workflow.\n * The canonical job spec (trigger, catchup, overlap, deps, retry policy)\n * travels in IncomingMethod.input_schema_json. Mirrors workflow's pattern.\n */\nexport type JobsService = typeof JobsService;\nexport const JobsService = {\n /** Owner-side: server-stream of JobExecution pushes for this instance. */\n subscribe: {\n path: \"/servicebridge.v1.Jobs/Subscribe\" as const,\n requestStream: false as const,\n responseStream: true as const,\n requestSerialize: (value: JobsSubscribeRequest): Buffer => Buffer.from(JobsSubscribeRequest.encode(value).finish()),\n requestDeserialize: (value: Buffer): JobsSubscribeRequest => JobsSubscribeRequest.decode(value),\n responseSerialize: (value: JobExecution): Buffer => Buffer.from(JobExecution.encode(value).finish()),\n responseDeserialize: (value: Buffer): JobExecution => JobExecution.decode(value),\n },\n /** Owner-side: report execution outcome. Stale ACK is silently dropped. */\n jobResult: {\n path: \"/servicebridge.v1.Jobs/JobResult\" as const,\n requestStream: false as const,\n responseStream: false as const,\n requestSerialize: (value: JobResultRequest): Buffer => Buffer.from(JobResultRequest.encode(value).finish()),\n requestDeserialize: (value: Buffer): JobResultRequest => JobResultRequest.decode(value),\n responseSerialize: (value: JobResultResponse): Buffer => Buffer.from(JobResultResponse.encode(value).finish()),\n responseDeserialize: (value: Buffer): JobResultResponse => JobResultResponse.decode(value),\n },\n /** Owner-side: application-level heartbeat. */\n heartbeat: {\n path: \"/servicebridge.v1.Jobs/Heartbeat\" as const,\n requestStream: false as const,\n responseStream: false as const,\n requestSerialize: (value: JobsHeartbeatRequest): Buffer => Buffer.from(JobsHeartbeatRequest.encode(value).finish()),\n requestDeserialize: (value: Buffer): JobsHeartbeatRequest => JobsHeartbeatRequest.decode(value),\n responseSerialize: (value: JobsHeartbeatResponse): Buffer =>\n Buffer.from(JobsHeartbeatResponse.encode(value).finish()),\n responseDeserialize: (value: Buffer): JobsHeartbeatResponse => JobsHeartbeatResponse.decode(value),\n },\n} as const;\n\nexport interface JobsServer extends UntypedServiceImplementation {\n /** Owner-side: server-stream of JobExecution pushes for this instance. */\n subscribe: handleServerStreamingCall<JobsSubscribeRequest, JobExecution>;\n /** Owner-side: report execution outcome. Stale ACK is silently dropped. */\n jobResult: handleUnaryCall<JobResultRequest, JobResultResponse>;\n /** Owner-side: application-level heartbeat. */\n heartbeat: handleUnaryCall<JobsHeartbeatRequest, JobsHeartbeatResponse>;\n}\n\nexport interface JobsClient extends Client {\n /** Owner-side: server-stream of JobExecution pushes for this instance. */\n subscribe(request: JobsSubscribeRequest, options?: Partial<CallOptions>): ClientReadableStream<JobExecution>;\n subscribe(\n request: JobsSubscribeRequest,\n metadata?: Metadata,\n options?: Partial<CallOptions>,\n ): ClientReadableStream<JobExecution>;\n /** Owner-side: report execution outcome. Stale ACK is silently dropped. */\n jobResult(\n request: JobResultRequest,\n callback: (error: ServiceError | null, response: JobResultResponse) => void,\n ): ClientUnaryCall;\n jobResult(\n request: JobResultRequest,\n metadata: Metadata,\n callback: (error: ServiceError | null, response: JobResultResponse) => void,\n ): ClientUnaryCall;\n jobResult(\n request: JobResultRequest,\n metadata: Metadata,\n options: Partial<CallOptions>,\n callback: (error: ServiceError | null, response: JobResultResponse) => void,\n ): ClientUnaryCall;\n /** Owner-side: application-level heartbeat. */\n heartbeat(\n request: JobsHeartbeatRequest,\n callback: (error: ServiceError | null, response: JobsHeartbeatResponse) => void,\n ): ClientUnaryCall;\n heartbeat(\n request: JobsHeartbeatRequest,\n metadata: Metadata,\n callback: (error: ServiceError | null, response: JobsHeartbeatResponse) => void,\n ): ClientUnaryCall;\n heartbeat(\n request: JobsHeartbeatRequest,\n metadata: Metadata,\n options: Partial<CallOptions>,\n callback: (error: ServiceError | null, response: JobsHeartbeatResponse) => void,\n ): ClientUnaryCall;\n}\n\nexport const JobsClient = makeGenericClientConstructor(JobsService, \"servicebridge.v1.Jobs\") as unknown as {\n new (address: string, credentials: ChannelCredentials, options?: Partial<ClientOptions>): JobsClient;\n service: typeof JobsService;\n serviceName: string;\n};\n\ntype Builtin = Date | Function | Uint8Array | string | number | boolean | undefined;\n\ntype DeepPartial<T> = T extends Builtin ? T\n : T extends globalThis.Array<infer U> ? globalThis.Array<DeepPartial<U>>\n : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>>\n : T extends {} ? { [K in keyof T]?: DeepPartial<T[K]> }\n : Partial<T>;\n\ntype KeysOfUnion<T> = T extends T ? keyof T : never;\ntype Exact<P, I extends P> = P extends Builtin ? P\n : P & { [K in keyof P]: Exact<P[K], I[K]> } & { [K in Exclude<keyof I, KeysOfUnion<P>>]: never };\n\nfunction longToNumber(int64: { toString(): string }): number {\n const num = globalThis.Number(int64.toString());\n if (num > globalThis.Number.MAX_SAFE_INTEGER) {\n throw new globalThis.Error(\"Value is larger than Number.MAX_SAFE_INTEGER\");\n }\n if (num < globalThis.Number.MIN_SAFE_INTEGER) {\n throw new globalThis.Error(\"Value is smaller than Number.MIN_SAFE_INTEGER\");\n }\n return num;\n}\n\ninterface MessageFns<T> {\n encode(message: T, writer?: BinaryWriter): BinaryWriter;\n decode(input: BinaryReader | Uint8Array, length?: number): T;\n create<I extends Exact<DeepPartial<T>, I>>(base?: I): T;\n fromPartial<I extends Exact<DeepPartial<T>, I>>(object: I): T;\n}\n","// Code generated by protoc-gen-ts_proto. DO NOT EDIT.\n// versions:\n// protoc-gen-ts_proto v2.11.8\n// protoc unknown\n// source: servicebridge/v1/telemetry.proto\n\n/* eslint-disable */\nimport { BinaryReader, BinaryWriter } from \"@bufbuild/protobuf/wire\";\nimport {\n type CallOptions,\n type ChannelCredentials,\n Client,\n type ClientDuplexStream,\n type ClientOptions,\n type ClientUnaryCall,\n type handleBidiStreamingCall,\n type handleUnaryCall,\n makeGenericClientConstructor,\n type Metadata,\n type ServiceError,\n type UntypedServiceImplementation,\n} from \"@grpc/grpc-js\";\n\n/**\n * Channel classifies the transport/execution context of an operation.\n * Mirrors the SQL CHECK constraint in migration 051.\n * source of truth: migrations/051_operations.up.sql\n */\nexport enum Channel {\n CHANNEL_UNSPECIFIED = 0,\n HTTP = 1,\n RPC = 2,\n EVENT = 3,\n WORKFLOW = 4,\n JOB = 5,\n USER = 6,\n UNRECOGNIZED = -1,\n}\n\n/** Status represents the lifecycle state of an operation. */\nexport enum Status {\n STATUS_UNSPECIFIED = 0,\n PENDING = 1,\n SUCCESS = 2,\n ERROR = 3,\n TIMEOUT = 4,\n ABANDONED = 5,\n UNRECOGNIZED = -1,\n}\n\nexport enum LogLevel {\n LOG_LEVEL_UNSPECIFIED = 0,\n LOG_LEVEL_DEBUG = 1,\n LOG_LEVEL_INFO = 2,\n LOG_LEVEL_WARN = 3,\n LOG_LEVEL_ERROR = 4,\n UNRECOGNIZED = -1,\n}\n\nexport enum MetricKind {\n METRIC_KIND_UNSPECIFIED = 0,\n METRIC_KIND_COUNTER = 1,\n METRIC_KIND_GAUGE = 2,\n METRIC_KIND_HISTOGRAM = 3,\n UNRECOGNIZED = -1,\n}\n\n/**\n * TelemetryBatch is the request message for the Report bidi stream.\n * Each batch carries exactly one kind of payload.\n * @public — см. ./README.md\n */\nexport interface TelemetryBatch {\n ops?: OpBatch | undefined;\n logs?: LogBatch | undefined;\n metrics?: MetricBatch | undefined;\n payloads?: PayloadBatch | undefined;\n}\n\nexport interface OpBatch {\n items: OpReport[];\n}\n\nexport interface LogBatch {\n items: Log[];\n}\n\nexport interface MetricBatch {\n items: MetricPoint[];\n}\n\nexport interface PayloadBatch {\n items: PayloadAttachment[];\n}\n\n/**\n * OpReport is a single operation lifecycle event.\n * finished_at_ms absent = START frame; present = END frame (T-014).\n * actor identity is taken from the mTLS cert on the server side (ADR-T-026).\n * @public — см. ./README.md\n */\nexport interface OpReport {\n /** UUIDv7 canonical string */\n traceId: string;\n /** UUIDv7 canonical string */\n opId: string;\n /** empty for root */\n parentOpId: string;\n channel: Channel;\n /** per-channel kind value; see enums.go */\n kind: number;\n /** T-019 format: \"channel.kind:actor/target\" */\n subject: string;\n /** UUID canonical string, optional */\n peerServiceId: string;\n /** idempotency/correlation key per kind */\n businessKey: string;\n attempt: number;\n /** unix-ms */\n startedAtMs: number;\n /** unix-ms; absent = START, present = END */\n finishedAtMs?: number | undefined;\n status: Status;\n statusMessage: string;\n /** per-kind structured meta; cap 8KB */\n metaJson: Buffer;\n /** free-form key-value; cap 2KB */\n attrsJson: Buffer;\n}\n\n/**\n * Log is a structured log entry.\n * trace_id and op_id are optional UUID canonical strings.\n * @public — см. ./README.md\n */\nexport interface Log {\n atUnixMs: number;\n level: LogLevel;\n message: string;\n /** JSON-encoded Record<string, unknown> */\n fieldsJson: Buffer;\n /** UUID canonical, optional */\n traceId: string;\n /** UUID canonical, optional (renamed from span_id) */\n opId: string;\n instanceId: string;\n /** 'sdk' | 'console' | 'runtime' */\n source: string;\n}\n\n/**\n * MetricPoint is a single metric observation.\n * @public — см. ./README.md\n */\nexport interface MetricPoint {\n atUnixMs: number;\n name: string;\n kind: MetricKind;\n labels: { [key: string]: string };\n instanceId: string;\n value: number;\n /** UCUM: 's', 'By', '1' */\n unit: string;\n /** [{le, count}] JSON for histograms */\n bucketsJson: Buffer;\n}\n\nexport interface MetricPoint_LabelsEntry {\n key: string;\n value: string;\n}\n\n/**\n * PayloadAttachment carries a captured request/response payload.\n * @public — см. ./README.md\n */\nexport interface PayloadAttachment {\n /** UUID canonical */\n traceId: string;\n /** UUID canonical */\n opId: string;\n /** 1=IN, 2=OUT */\n direction: number;\n bytes: Buffer;\n originalSize: number;\n contractHash: string;\n}\n\n/**\n * TelemetryAck is sent periodically by the server on the Report stream.\n * It provides flow control and signals drain.\n * @public — см. ./README.md\n */\nexport interface TelemetryAck {\n receivedBytesHighWater: number;\n /** 0=normal, 1=slow, 2=pause */\n backpressureLevel: number;\n dropCountServerSide: number;\n /** non-empty → graceful close requested */\n drainReason: string;\n}\n\nexport interface ListTracesRequest {\n channelFilter: Channel[];\n statusFilter: Status[];\n fromMs: number;\n toMs: number;\n serviceId: string;\n /** searched in subject + business_key */\n textQuery: string;\n limit: number;\n cursor: string;\n}\n\nexport interface TraceSummary {\n /** UUIDv7 */\n traceId: string;\n rootSubject: string;\n rootServiceId: string;\n startedAtMs: number;\n durationMs: number;\n opCount: number;\n overallStatus: Status;\n hasRunning: boolean;\n}\n\nexport interface ListTracesResponse {\n traces: TraceSummary[];\n nextCursor: string;\n}\n\nexport interface GetTraceRequest {\n traceId: string;\n limit: number;\n cursor: string;\n}\n\nexport interface OperationView {\n opId: string;\n traceId: string;\n parentOpId: string;\n channel: Channel;\n kind: number;\n subject: string;\n actorServiceId: string;\n actorInstanceId: string;\n peerServiceId: string;\n businessKey: string;\n attempt: number;\n startedAtMs: number;\n finishedAtMs?: number | undefined;\n status: Status;\n statusMessage: string;\n metaJson: Buffer;\n attrsJson: Buffer;\n}\n\nexport interface GetTraceResponse {\n ops: OperationView[];\n nextCursor: string;\n truncated: boolean;\n}\n\nexport interface GetOperationRequest {\n opId: string;\n}\n\nexport interface GetOperationResponse {\n op?: OperationView | undefined;\n}\n\nexport interface GetPayloadRequest {\n traceId: string;\n opId: string;\n /** 1=IN, 2=OUT */\n direction: number;\n}\n\nexport interface GetPayloadResponse {\n rawBytes: Buffer;\n decodedBytes: Buffer;\n originalSize: number;\n contractHash: string;\n schemaDrift: boolean;\n}\n\nexport interface QueryLogsRequest {\n serviceId: string;\n instanceId: string;\n fromUnixMs: number;\n toUnixMs: number;\n minLevel: LogLevel;\n /** UUID canonical, optional filter */\n traceId: string;\n textQuery: string;\n limit: number;\n cursor: string;\n}\n\nexport interface QueryLogsResponse {\n entries: Log[];\n nextCursor: string;\n}\n\nexport interface QueryMetricsRequest {\n serviceId: string;\n instanceId: string;\n name: string;\n fromUnixMs: number;\n toUnixMs: number;\n labelFilters: { [key: string]: string };\n stepSeconds: number;\n percentiles: number[];\n}\n\nexport interface QueryMetricsRequest_LabelFiltersEntry {\n key: string;\n value: string;\n}\n\nexport interface MetricSeries {\n name: string;\n labels: { [key: string]: string };\n instanceId: string;\n tsUnixMs: number[];\n /** bucket average */\n values: number[];\n /** bucket peak (parallel to values), preserves spikes hidden by the average */\n maxValues: number[];\n}\n\nexport interface MetricSeries_LabelsEntry {\n key: string;\n value: string;\n}\n\nexport interface QueryMetricsResponse {\n series: MetricSeries[];\n}\n\nfunction createBaseTelemetryBatch(): TelemetryBatch {\n return { ops: undefined, logs: undefined, metrics: undefined, payloads: undefined };\n}\n\nexport const TelemetryBatch: MessageFns<TelemetryBatch> = {\n encode(message: TelemetryBatch, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.ops !== undefined) {\n OpBatch.encode(message.ops, writer.uint32(10).fork()).join();\n }\n if (message.logs !== undefined) {\n LogBatch.encode(message.logs, writer.uint32(18).fork()).join();\n }\n if (message.metrics !== undefined) {\n MetricBatch.encode(message.metrics, writer.uint32(26).fork()).join();\n }\n if (message.payloads !== undefined) {\n PayloadBatch.encode(message.payloads, writer.uint32(34).fork()).join();\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): TelemetryBatch {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseTelemetryBatch();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.ops = OpBatch.decode(reader, reader.uint32());\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.logs = LogBatch.decode(reader, reader.uint32());\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.metrics = MetricBatch.decode(reader, reader.uint32());\n continue;\n }\n case 4: {\n if (tag !== 34) {\n break;\n }\n\n message.payloads = PayloadBatch.decode(reader, reader.uint32());\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<TelemetryBatch>, I>>(base?: I): TelemetryBatch {\n return TelemetryBatch.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<TelemetryBatch>, I>>(object: I): TelemetryBatch {\n const message = createBaseTelemetryBatch();\n message.ops = (object.ops !== undefined && object.ops !== null) ? OpBatch.fromPartial(object.ops) : undefined;\n message.logs = (object.logs !== undefined && object.logs !== null) ? LogBatch.fromPartial(object.logs) : undefined;\n message.metrics = (object.metrics !== undefined && object.metrics !== null)\n ? MetricBatch.fromPartial(object.metrics)\n : undefined;\n message.payloads = (object.payloads !== undefined && object.payloads !== null)\n ? PayloadBatch.fromPartial(object.payloads)\n : undefined;\n return message;\n },\n};\n\nfunction createBaseOpBatch(): OpBatch {\n return { items: [] };\n}\n\nexport const OpBatch: MessageFns<OpBatch> = {\n encode(message: OpBatch, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n for (const v of message.items) {\n OpReport.encode(v!, writer.uint32(10).fork()).join();\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): OpBatch {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseOpBatch();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.items.push(OpReport.decode(reader, reader.uint32()));\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<OpBatch>, I>>(base?: I): OpBatch {\n return OpBatch.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<OpBatch>, I>>(object: I): OpBatch {\n const message = createBaseOpBatch();\n message.items = object.items?.map((e) => OpReport.fromPartial(e)) || [];\n return message;\n },\n};\n\nfunction createBaseLogBatch(): LogBatch {\n return { items: [] };\n}\n\nexport const LogBatch: MessageFns<LogBatch> = {\n encode(message: LogBatch, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n for (const v of message.items) {\n Log.encode(v!, writer.uint32(10).fork()).join();\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): LogBatch {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseLogBatch();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.items.push(Log.decode(reader, reader.uint32()));\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<LogBatch>, I>>(base?: I): LogBatch {\n return LogBatch.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<LogBatch>, I>>(object: I): LogBatch {\n const message = createBaseLogBatch();\n message.items = object.items?.map((e) => Log.fromPartial(e)) || [];\n return message;\n },\n};\n\nfunction createBaseMetricBatch(): MetricBatch {\n return { items: [] };\n}\n\nexport const MetricBatch: MessageFns<MetricBatch> = {\n encode(message: MetricBatch, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n for (const v of message.items) {\n MetricPoint.encode(v!, writer.uint32(10).fork()).join();\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): MetricBatch {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseMetricBatch();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.items.push(MetricPoint.decode(reader, reader.uint32()));\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<MetricBatch>, I>>(base?: I): MetricBatch {\n return MetricBatch.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<MetricBatch>, I>>(object: I): MetricBatch {\n const message = createBaseMetricBatch();\n message.items = object.items?.map((e) => MetricPoint.fromPartial(e)) || [];\n return message;\n },\n};\n\nfunction createBasePayloadBatch(): PayloadBatch {\n return { items: [] };\n}\n\nexport const PayloadBatch: MessageFns<PayloadBatch> = {\n encode(message: PayloadBatch, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n for (const v of message.items) {\n PayloadAttachment.encode(v!, writer.uint32(10).fork()).join();\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): PayloadBatch {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBasePayloadBatch();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.items.push(PayloadAttachment.decode(reader, reader.uint32()));\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<PayloadBatch>, I>>(base?: I): PayloadBatch {\n return PayloadBatch.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<PayloadBatch>, I>>(object: I): PayloadBatch {\n const message = createBasePayloadBatch();\n message.items = object.items?.map((e) => PayloadAttachment.fromPartial(e)) || [];\n return message;\n },\n};\n\nfunction createBaseOpReport(): OpReport {\n return {\n traceId: \"\",\n opId: \"\",\n parentOpId: \"\",\n channel: 0,\n kind: 0,\n subject: \"\",\n peerServiceId: \"\",\n businessKey: \"\",\n attempt: 0,\n startedAtMs: 0,\n finishedAtMs: undefined,\n status: 0,\n statusMessage: \"\",\n metaJson: Buffer.alloc(0),\n attrsJson: Buffer.alloc(0),\n };\n}\n\nexport const OpReport: MessageFns<OpReport> = {\n encode(message: OpReport, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.traceId !== \"\") {\n writer.uint32(10).string(message.traceId);\n }\n if (message.opId !== \"\") {\n writer.uint32(18).string(message.opId);\n }\n if (message.parentOpId !== \"\") {\n writer.uint32(26).string(message.parentOpId);\n }\n if (message.channel !== 0) {\n writer.uint32(32).int32(message.channel);\n }\n if (message.kind !== 0) {\n writer.uint32(40).uint32(message.kind);\n }\n if (message.subject !== \"\") {\n writer.uint32(50).string(message.subject);\n }\n if (message.peerServiceId !== \"\") {\n writer.uint32(74).string(message.peerServiceId);\n }\n if (message.businessKey !== \"\") {\n writer.uint32(82).string(message.businessKey);\n }\n if (message.attempt !== 0) {\n writer.uint32(88).int32(message.attempt);\n }\n if (message.startedAtMs !== 0) {\n writer.uint32(96).int64(message.startedAtMs);\n }\n if (message.finishedAtMs !== undefined) {\n writer.uint32(104).int64(message.finishedAtMs);\n }\n if (message.status !== 0) {\n writer.uint32(112).int32(message.status);\n }\n if (message.statusMessage !== \"\") {\n writer.uint32(122).string(message.statusMessage);\n }\n if (message.metaJson.length !== 0) {\n writer.uint32(130).bytes(message.metaJson);\n }\n if (message.attrsJson.length !== 0) {\n writer.uint32(138).bytes(message.attrsJson);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): OpReport {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseOpReport();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.traceId = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.opId = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.parentOpId = reader.string();\n continue;\n }\n case 4: {\n if (tag !== 32) {\n break;\n }\n\n message.channel = reader.int32() as any;\n continue;\n }\n case 5: {\n if (tag !== 40) {\n break;\n }\n\n message.kind = reader.uint32();\n continue;\n }\n case 6: {\n if (tag !== 50) {\n break;\n }\n\n message.subject = reader.string();\n continue;\n }\n case 9: {\n if (tag !== 74) {\n break;\n }\n\n message.peerServiceId = reader.string();\n continue;\n }\n case 10: {\n if (tag !== 82) {\n break;\n }\n\n message.businessKey = reader.string();\n continue;\n }\n case 11: {\n if (tag !== 88) {\n break;\n }\n\n message.attempt = reader.int32();\n continue;\n }\n case 12: {\n if (tag !== 96) {\n break;\n }\n\n message.startedAtMs = longToNumber(reader.int64());\n continue;\n }\n case 13: {\n if (tag !== 104) {\n break;\n }\n\n message.finishedAtMs = longToNumber(reader.int64());\n continue;\n }\n case 14: {\n if (tag !== 112) {\n break;\n }\n\n message.status = reader.int32() as any;\n continue;\n }\n case 15: {\n if (tag !== 122) {\n break;\n }\n\n message.statusMessage = reader.string();\n continue;\n }\n case 16: {\n if (tag !== 130) {\n break;\n }\n\n message.metaJson = Buffer.from(reader.bytes());\n continue;\n }\n case 17: {\n if (tag !== 138) {\n break;\n }\n\n message.attrsJson = Buffer.from(reader.bytes());\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<OpReport>, I>>(base?: I): OpReport {\n return OpReport.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<OpReport>, I>>(object: I): OpReport {\n const message = createBaseOpReport();\n message.traceId = object.traceId ?? \"\";\n message.opId = object.opId ?? \"\";\n message.parentOpId = object.parentOpId ?? \"\";\n message.channel = object.channel ?? 0;\n message.kind = object.kind ?? 0;\n message.subject = object.subject ?? \"\";\n message.peerServiceId = object.peerServiceId ?? \"\";\n message.businessKey = object.businessKey ?? \"\";\n message.attempt = object.attempt ?? 0;\n message.startedAtMs = object.startedAtMs ?? 0;\n message.finishedAtMs = object.finishedAtMs ?? undefined;\n message.status = object.status ?? 0;\n message.statusMessage = object.statusMessage ?? \"\";\n message.metaJson = object.metaJson ?? Buffer.alloc(0);\n message.attrsJson = object.attrsJson ?? Buffer.alloc(0);\n return message;\n },\n};\n\nfunction createBaseLog(): Log {\n return {\n atUnixMs: 0,\n level: 0,\n message: \"\",\n fieldsJson: Buffer.alloc(0),\n traceId: \"\",\n opId: \"\",\n instanceId: \"\",\n source: \"\",\n };\n}\n\nexport const Log: MessageFns<Log> = {\n encode(message: Log, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.atUnixMs !== 0) {\n writer.uint32(8).int64(message.atUnixMs);\n }\n if (message.level !== 0) {\n writer.uint32(16).int32(message.level);\n }\n if (message.message !== \"\") {\n writer.uint32(26).string(message.message);\n }\n if (message.fieldsJson.length !== 0) {\n writer.uint32(34).bytes(message.fieldsJson);\n }\n if (message.traceId !== \"\") {\n writer.uint32(42).string(message.traceId);\n }\n if (message.opId !== \"\") {\n writer.uint32(50).string(message.opId);\n }\n if (message.instanceId !== \"\") {\n writer.uint32(58).string(message.instanceId);\n }\n if (message.source !== \"\") {\n writer.uint32(66).string(message.source);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): Log {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseLog();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 8) {\n break;\n }\n\n message.atUnixMs = longToNumber(reader.int64());\n continue;\n }\n case 2: {\n if (tag !== 16) {\n break;\n }\n\n message.level = reader.int32() as any;\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.message = reader.string();\n continue;\n }\n case 4: {\n if (tag !== 34) {\n break;\n }\n\n message.fieldsJson = Buffer.from(reader.bytes());\n continue;\n }\n case 5: {\n if (tag !== 42) {\n break;\n }\n\n message.traceId = reader.string();\n continue;\n }\n case 6: {\n if (tag !== 50) {\n break;\n }\n\n message.opId = reader.string();\n continue;\n }\n case 7: {\n if (tag !== 58) {\n break;\n }\n\n message.instanceId = reader.string();\n continue;\n }\n case 8: {\n if (tag !== 66) {\n break;\n }\n\n message.source = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<Log>, I>>(base?: I): Log {\n return Log.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<Log>, I>>(object: I): Log {\n const message = createBaseLog();\n message.atUnixMs = object.atUnixMs ?? 0;\n message.level = object.level ?? 0;\n message.message = object.message ?? \"\";\n message.fieldsJson = object.fieldsJson ?? Buffer.alloc(0);\n message.traceId = object.traceId ?? \"\";\n message.opId = object.opId ?? \"\";\n message.instanceId = object.instanceId ?? \"\";\n message.source = object.source ?? \"\";\n return message;\n },\n};\n\nfunction createBaseMetricPoint(): MetricPoint {\n return {\n atUnixMs: 0,\n name: \"\",\n kind: 0,\n labels: {},\n instanceId: \"\",\n value: 0,\n unit: \"\",\n bucketsJson: Buffer.alloc(0),\n };\n}\n\nexport const MetricPoint: MessageFns<MetricPoint> = {\n encode(message: MetricPoint, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.atUnixMs !== 0) {\n writer.uint32(8).int64(message.atUnixMs);\n }\n if (message.name !== \"\") {\n writer.uint32(18).string(message.name);\n }\n if (message.kind !== 0) {\n writer.uint32(24).int32(message.kind);\n }\n globalThis.Object.entries(message.labels).forEach(([key, value]: [string, string]) => {\n MetricPoint_LabelsEntry.encode({ key: key as any, value }, writer.uint32(34).fork()).join();\n });\n if (message.instanceId !== \"\") {\n writer.uint32(42).string(message.instanceId);\n }\n if (message.value !== 0) {\n writer.uint32(49).double(message.value);\n }\n if (message.unit !== \"\") {\n writer.uint32(58).string(message.unit);\n }\n if (message.bucketsJson.length !== 0) {\n writer.uint32(66).bytes(message.bucketsJson);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): MetricPoint {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseMetricPoint();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 8) {\n break;\n }\n\n message.atUnixMs = longToNumber(reader.int64());\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.name = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 24) {\n break;\n }\n\n message.kind = reader.int32() as any;\n continue;\n }\n case 4: {\n if (tag !== 34) {\n break;\n }\n\n const entry4 = MetricPoint_LabelsEntry.decode(reader, reader.uint32());\n if (entry4.value !== undefined) {\n message.labels[entry4.key] = entry4.value;\n }\n continue;\n }\n case 5: {\n if (tag !== 42) {\n break;\n }\n\n message.instanceId = reader.string();\n continue;\n }\n case 6: {\n if (tag !== 49) {\n break;\n }\n\n message.value = reader.double();\n continue;\n }\n case 7: {\n if (tag !== 58) {\n break;\n }\n\n message.unit = reader.string();\n continue;\n }\n case 8: {\n if (tag !== 66) {\n break;\n }\n\n message.bucketsJson = Buffer.from(reader.bytes());\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<MetricPoint>, I>>(base?: I): MetricPoint {\n return MetricPoint.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<MetricPoint>, I>>(object: I): MetricPoint {\n const message = createBaseMetricPoint();\n message.atUnixMs = object.atUnixMs ?? 0;\n message.name = object.name ?? \"\";\n message.kind = object.kind ?? 0;\n message.labels = (globalThis.Object.entries(object.labels ?? {}) as [string, string][]).reduce(\n (acc: { [key: string]: string }, [key, value]: [string, string]) => {\n if (value !== undefined) {\n acc[key] = globalThis.String(value);\n }\n return acc;\n },\n {},\n );\n message.instanceId = object.instanceId ?? \"\";\n message.value = object.value ?? 0;\n message.unit = object.unit ?? \"\";\n message.bucketsJson = object.bucketsJson ?? Buffer.alloc(0);\n return message;\n },\n};\n\nfunction createBaseMetricPoint_LabelsEntry(): MetricPoint_LabelsEntry {\n return { key: \"\", value: \"\" };\n}\n\nexport const MetricPoint_LabelsEntry: MessageFns<MetricPoint_LabelsEntry> = {\n encode(message: MetricPoint_LabelsEntry, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.key !== \"\") {\n writer.uint32(10).string(message.key);\n }\n if (message.value !== \"\") {\n writer.uint32(18).string(message.value);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): MetricPoint_LabelsEntry {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseMetricPoint_LabelsEntry();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.key = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.value = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<MetricPoint_LabelsEntry>, I>>(base?: I): MetricPoint_LabelsEntry {\n return MetricPoint_LabelsEntry.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<MetricPoint_LabelsEntry>, I>>(object: I): MetricPoint_LabelsEntry {\n const message = createBaseMetricPoint_LabelsEntry();\n message.key = object.key ?? \"\";\n message.value = object.value ?? \"\";\n return message;\n },\n};\n\nfunction createBasePayloadAttachment(): PayloadAttachment {\n return { traceId: \"\", opId: \"\", direction: 0, bytes: Buffer.alloc(0), originalSize: 0, contractHash: \"\" };\n}\n\nexport const PayloadAttachment: MessageFns<PayloadAttachment> = {\n encode(message: PayloadAttachment, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.traceId !== \"\") {\n writer.uint32(10).string(message.traceId);\n }\n if (message.opId !== \"\") {\n writer.uint32(18).string(message.opId);\n }\n if (message.direction !== 0) {\n writer.uint32(24).uint32(message.direction);\n }\n if (message.bytes.length !== 0) {\n writer.uint32(34).bytes(message.bytes);\n }\n if (message.originalSize !== 0) {\n writer.uint32(40).int32(message.originalSize);\n }\n if (message.contractHash !== \"\") {\n writer.uint32(50).string(message.contractHash);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): PayloadAttachment {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBasePayloadAttachment();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.traceId = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.opId = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 24) {\n break;\n }\n\n message.direction = reader.uint32();\n continue;\n }\n case 4: {\n if (tag !== 34) {\n break;\n }\n\n message.bytes = Buffer.from(reader.bytes());\n continue;\n }\n case 5: {\n if (tag !== 40) {\n break;\n }\n\n message.originalSize = reader.int32();\n continue;\n }\n case 6: {\n if (tag !== 50) {\n break;\n }\n\n message.contractHash = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<PayloadAttachment>, I>>(base?: I): PayloadAttachment {\n return PayloadAttachment.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<PayloadAttachment>, I>>(object: I): PayloadAttachment {\n const message = createBasePayloadAttachment();\n message.traceId = object.traceId ?? \"\";\n message.opId = object.opId ?? \"\";\n message.direction = object.direction ?? 0;\n message.bytes = object.bytes ?? Buffer.alloc(0);\n message.originalSize = object.originalSize ?? 0;\n message.contractHash = object.contractHash ?? \"\";\n return message;\n },\n};\n\nfunction createBaseTelemetryAck(): TelemetryAck {\n return { receivedBytesHighWater: 0, backpressureLevel: 0, dropCountServerSide: 0, drainReason: \"\" };\n}\n\nexport const TelemetryAck: MessageFns<TelemetryAck> = {\n encode(message: TelemetryAck, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.receivedBytesHighWater !== 0) {\n writer.uint32(8).uint64(message.receivedBytesHighWater);\n }\n if (message.backpressureLevel !== 0) {\n writer.uint32(16).uint32(message.backpressureLevel);\n }\n if (message.dropCountServerSide !== 0) {\n writer.uint32(24).uint64(message.dropCountServerSide);\n }\n if (message.drainReason !== \"\") {\n writer.uint32(34).string(message.drainReason);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): TelemetryAck {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseTelemetryAck();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 8) {\n break;\n }\n\n message.receivedBytesHighWater = longToNumber(reader.uint64());\n continue;\n }\n case 2: {\n if (tag !== 16) {\n break;\n }\n\n message.backpressureLevel = reader.uint32();\n continue;\n }\n case 3: {\n if (tag !== 24) {\n break;\n }\n\n message.dropCountServerSide = longToNumber(reader.uint64());\n continue;\n }\n case 4: {\n if (tag !== 34) {\n break;\n }\n\n message.drainReason = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<TelemetryAck>, I>>(base?: I): TelemetryAck {\n return TelemetryAck.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<TelemetryAck>, I>>(object: I): TelemetryAck {\n const message = createBaseTelemetryAck();\n message.receivedBytesHighWater = object.receivedBytesHighWater ?? 0;\n message.backpressureLevel = object.backpressureLevel ?? 0;\n message.dropCountServerSide = object.dropCountServerSide ?? 0;\n message.drainReason = object.drainReason ?? \"\";\n return message;\n },\n};\n\nfunction createBaseListTracesRequest(): ListTracesRequest {\n return {\n channelFilter: [],\n statusFilter: [],\n fromMs: 0,\n toMs: 0,\n serviceId: \"\",\n textQuery: \"\",\n limit: 0,\n cursor: \"\",\n };\n}\n\nexport const ListTracesRequest: MessageFns<ListTracesRequest> = {\n encode(message: ListTracesRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n writer.uint32(10).fork();\n for (const v of message.channelFilter) {\n writer.int32(v);\n }\n writer.join();\n writer.uint32(18).fork();\n for (const v of message.statusFilter) {\n writer.int32(v);\n }\n writer.join();\n if (message.fromMs !== 0) {\n writer.uint32(24).int64(message.fromMs);\n }\n if (message.toMs !== 0) {\n writer.uint32(32).int64(message.toMs);\n }\n if (message.serviceId !== \"\") {\n writer.uint32(42).string(message.serviceId);\n }\n if (message.textQuery !== \"\") {\n writer.uint32(50).string(message.textQuery);\n }\n if (message.limit !== 0) {\n writer.uint32(56).uint32(message.limit);\n }\n if (message.cursor !== \"\") {\n writer.uint32(66).string(message.cursor);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): ListTracesRequest {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseListTracesRequest();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag === 8) {\n message.channelFilter.push(reader.int32() as any);\n\n continue;\n }\n\n if (tag === 10) {\n const end2 = reader.uint32() + reader.pos;\n while (reader.pos < end2) {\n message.channelFilter.push(reader.int32() as any);\n }\n\n continue;\n }\n\n break;\n }\n case 2: {\n if (tag === 16) {\n message.statusFilter.push(reader.int32() as any);\n\n continue;\n }\n\n if (tag === 18) {\n const end2 = reader.uint32() + reader.pos;\n while (reader.pos < end2) {\n message.statusFilter.push(reader.int32() as any);\n }\n\n continue;\n }\n\n break;\n }\n case 3: {\n if (tag !== 24) {\n break;\n }\n\n message.fromMs = longToNumber(reader.int64());\n continue;\n }\n case 4: {\n if (tag !== 32) {\n break;\n }\n\n message.toMs = longToNumber(reader.int64());\n continue;\n }\n case 5: {\n if (tag !== 42) {\n break;\n }\n\n message.serviceId = reader.string();\n continue;\n }\n case 6: {\n if (tag !== 50) {\n break;\n }\n\n message.textQuery = reader.string();\n continue;\n }\n case 7: {\n if (tag !== 56) {\n break;\n }\n\n message.limit = reader.uint32();\n continue;\n }\n case 8: {\n if (tag !== 66) {\n break;\n }\n\n message.cursor = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<ListTracesRequest>, I>>(base?: I): ListTracesRequest {\n return ListTracesRequest.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<ListTracesRequest>, I>>(object: I): ListTracesRequest {\n const message = createBaseListTracesRequest();\n message.channelFilter = object.channelFilter?.map((e) => e) || [];\n message.statusFilter = object.statusFilter?.map((e) => e) || [];\n message.fromMs = object.fromMs ?? 0;\n message.toMs = object.toMs ?? 0;\n message.serviceId = object.serviceId ?? \"\";\n message.textQuery = object.textQuery ?? \"\";\n message.limit = object.limit ?? 0;\n message.cursor = object.cursor ?? \"\";\n return message;\n },\n};\n\nfunction createBaseTraceSummary(): TraceSummary {\n return {\n traceId: \"\",\n rootSubject: \"\",\n rootServiceId: \"\",\n startedAtMs: 0,\n durationMs: 0,\n opCount: 0,\n overallStatus: 0,\n hasRunning: false,\n };\n}\n\nexport const TraceSummary: MessageFns<TraceSummary> = {\n encode(message: TraceSummary, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.traceId !== \"\") {\n writer.uint32(10).string(message.traceId);\n }\n if (message.rootSubject !== \"\") {\n writer.uint32(18).string(message.rootSubject);\n }\n if (message.rootServiceId !== \"\") {\n writer.uint32(26).string(message.rootServiceId);\n }\n if (message.startedAtMs !== 0) {\n writer.uint32(32).int64(message.startedAtMs);\n }\n if (message.durationMs !== 0) {\n writer.uint32(40).int64(message.durationMs);\n }\n if (message.opCount !== 0) {\n writer.uint32(48).uint32(message.opCount);\n }\n if (message.overallStatus !== 0) {\n writer.uint32(56).int32(message.overallStatus);\n }\n if (message.hasRunning !== false) {\n writer.uint32(64).bool(message.hasRunning);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): TraceSummary {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseTraceSummary();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.traceId = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.rootSubject = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.rootServiceId = reader.string();\n continue;\n }\n case 4: {\n if (tag !== 32) {\n break;\n }\n\n message.startedAtMs = longToNumber(reader.int64());\n continue;\n }\n case 5: {\n if (tag !== 40) {\n break;\n }\n\n message.durationMs = longToNumber(reader.int64());\n continue;\n }\n case 6: {\n if (tag !== 48) {\n break;\n }\n\n message.opCount = reader.uint32();\n continue;\n }\n case 7: {\n if (tag !== 56) {\n break;\n }\n\n message.overallStatus = reader.int32() as any;\n continue;\n }\n case 8: {\n if (tag !== 64) {\n break;\n }\n\n message.hasRunning = reader.bool();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<TraceSummary>, I>>(base?: I): TraceSummary {\n return TraceSummary.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<TraceSummary>, I>>(object: I): TraceSummary {\n const message = createBaseTraceSummary();\n message.traceId = object.traceId ?? \"\";\n message.rootSubject = object.rootSubject ?? \"\";\n message.rootServiceId = object.rootServiceId ?? \"\";\n message.startedAtMs = object.startedAtMs ?? 0;\n message.durationMs = object.durationMs ?? 0;\n message.opCount = object.opCount ?? 0;\n message.overallStatus = object.overallStatus ?? 0;\n message.hasRunning = object.hasRunning ?? false;\n return message;\n },\n};\n\nfunction createBaseListTracesResponse(): ListTracesResponse {\n return { traces: [], nextCursor: \"\" };\n}\n\nexport const ListTracesResponse: MessageFns<ListTracesResponse> = {\n encode(message: ListTracesResponse, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n for (const v of message.traces) {\n TraceSummary.encode(v!, writer.uint32(10).fork()).join();\n }\n if (message.nextCursor !== \"\") {\n writer.uint32(18).string(message.nextCursor);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): ListTracesResponse {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseListTracesResponse();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.traces.push(TraceSummary.decode(reader, reader.uint32()));\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.nextCursor = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<ListTracesResponse>, I>>(base?: I): ListTracesResponse {\n return ListTracesResponse.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<ListTracesResponse>, I>>(object: I): ListTracesResponse {\n const message = createBaseListTracesResponse();\n message.traces = object.traces?.map((e) => TraceSummary.fromPartial(e)) || [];\n message.nextCursor = object.nextCursor ?? \"\";\n return message;\n },\n};\n\nfunction createBaseGetTraceRequest(): GetTraceRequest {\n return { traceId: \"\", limit: 0, cursor: \"\" };\n}\n\nexport const GetTraceRequest: MessageFns<GetTraceRequest> = {\n encode(message: GetTraceRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.traceId !== \"\") {\n writer.uint32(10).string(message.traceId);\n }\n if (message.limit !== 0) {\n writer.uint32(16).uint32(message.limit);\n }\n if (message.cursor !== \"\") {\n writer.uint32(26).string(message.cursor);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): GetTraceRequest {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseGetTraceRequest();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.traceId = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 16) {\n break;\n }\n\n message.limit = reader.uint32();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.cursor = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<GetTraceRequest>, I>>(base?: I): GetTraceRequest {\n return GetTraceRequest.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<GetTraceRequest>, I>>(object: I): GetTraceRequest {\n const message = createBaseGetTraceRequest();\n message.traceId = object.traceId ?? \"\";\n message.limit = object.limit ?? 0;\n message.cursor = object.cursor ?? \"\";\n return message;\n },\n};\n\nfunction createBaseOperationView(): OperationView {\n return {\n opId: \"\",\n traceId: \"\",\n parentOpId: \"\",\n channel: 0,\n kind: 0,\n subject: \"\",\n actorServiceId: \"\",\n actorInstanceId: \"\",\n peerServiceId: \"\",\n businessKey: \"\",\n attempt: 0,\n startedAtMs: 0,\n finishedAtMs: undefined,\n status: 0,\n statusMessage: \"\",\n metaJson: Buffer.alloc(0),\n attrsJson: Buffer.alloc(0),\n };\n}\n\nexport const OperationView: MessageFns<OperationView> = {\n encode(message: OperationView, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.opId !== \"\") {\n writer.uint32(10).string(message.opId);\n }\n if (message.traceId !== \"\") {\n writer.uint32(18).string(message.traceId);\n }\n if (message.parentOpId !== \"\") {\n writer.uint32(26).string(message.parentOpId);\n }\n if (message.channel !== 0) {\n writer.uint32(32).int32(message.channel);\n }\n if (message.kind !== 0) {\n writer.uint32(40).uint32(message.kind);\n }\n if (message.subject !== \"\") {\n writer.uint32(50).string(message.subject);\n }\n if (message.actorServiceId !== \"\") {\n writer.uint32(58).string(message.actorServiceId);\n }\n if (message.actorInstanceId !== \"\") {\n writer.uint32(66).string(message.actorInstanceId);\n }\n if (message.peerServiceId !== \"\") {\n writer.uint32(74).string(message.peerServiceId);\n }\n if (message.businessKey !== \"\") {\n writer.uint32(82).string(message.businessKey);\n }\n if (message.attempt !== 0) {\n writer.uint32(88).int32(message.attempt);\n }\n if (message.startedAtMs !== 0) {\n writer.uint32(96).int64(message.startedAtMs);\n }\n if (message.finishedAtMs !== undefined) {\n writer.uint32(104).int64(message.finishedAtMs);\n }\n if (message.status !== 0) {\n writer.uint32(112).int32(message.status);\n }\n if (message.statusMessage !== \"\") {\n writer.uint32(122).string(message.statusMessage);\n }\n if (message.metaJson.length !== 0) {\n writer.uint32(130).bytes(message.metaJson);\n }\n if (message.attrsJson.length !== 0) {\n writer.uint32(138).bytes(message.attrsJson);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): OperationView {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseOperationView();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.opId = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.traceId = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.parentOpId = reader.string();\n continue;\n }\n case 4: {\n if (tag !== 32) {\n break;\n }\n\n message.channel = reader.int32() as any;\n continue;\n }\n case 5: {\n if (tag !== 40) {\n break;\n }\n\n message.kind = reader.uint32();\n continue;\n }\n case 6: {\n if (tag !== 50) {\n break;\n }\n\n message.subject = reader.string();\n continue;\n }\n case 7: {\n if (tag !== 58) {\n break;\n }\n\n message.actorServiceId = reader.string();\n continue;\n }\n case 8: {\n if (tag !== 66) {\n break;\n }\n\n message.actorInstanceId = reader.string();\n continue;\n }\n case 9: {\n if (tag !== 74) {\n break;\n }\n\n message.peerServiceId = reader.string();\n continue;\n }\n case 10: {\n if (tag !== 82) {\n break;\n }\n\n message.businessKey = reader.string();\n continue;\n }\n case 11: {\n if (tag !== 88) {\n break;\n }\n\n message.attempt = reader.int32();\n continue;\n }\n case 12: {\n if (tag !== 96) {\n break;\n }\n\n message.startedAtMs = longToNumber(reader.int64());\n continue;\n }\n case 13: {\n if (tag !== 104) {\n break;\n }\n\n message.finishedAtMs = longToNumber(reader.int64());\n continue;\n }\n case 14: {\n if (tag !== 112) {\n break;\n }\n\n message.status = reader.int32() as any;\n continue;\n }\n case 15: {\n if (tag !== 122) {\n break;\n }\n\n message.statusMessage = reader.string();\n continue;\n }\n case 16: {\n if (tag !== 130) {\n break;\n }\n\n message.metaJson = Buffer.from(reader.bytes());\n continue;\n }\n case 17: {\n if (tag !== 138) {\n break;\n }\n\n message.attrsJson = Buffer.from(reader.bytes());\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<OperationView>, I>>(base?: I): OperationView {\n return OperationView.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<OperationView>, I>>(object: I): OperationView {\n const message = createBaseOperationView();\n message.opId = object.opId ?? \"\";\n message.traceId = object.traceId ?? \"\";\n message.parentOpId = object.parentOpId ?? \"\";\n message.channel = object.channel ?? 0;\n message.kind = object.kind ?? 0;\n message.subject = object.subject ?? \"\";\n message.actorServiceId = object.actorServiceId ?? \"\";\n message.actorInstanceId = object.actorInstanceId ?? \"\";\n message.peerServiceId = object.peerServiceId ?? \"\";\n message.businessKey = object.businessKey ?? \"\";\n message.attempt = object.attempt ?? 0;\n message.startedAtMs = object.startedAtMs ?? 0;\n message.finishedAtMs = object.finishedAtMs ?? undefined;\n message.status = object.status ?? 0;\n message.statusMessage = object.statusMessage ?? \"\";\n message.metaJson = object.metaJson ?? Buffer.alloc(0);\n message.attrsJson = object.attrsJson ?? Buffer.alloc(0);\n return message;\n },\n};\n\nfunction createBaseGetTraceResponse(): GetTraceResponse {\n return { ops: [], nextCursor: \"\", truncated: false };\n}\n\nexport const GetTraceResponse: MessageFns<GetTraceResponse> = {\n encode(message: GetTraceResponse, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n for (const v of message.ops) {\n OperationView.encode(v!, writer.uint32(10).fork()).join();\n }\n if (message.nextCursor !== \"\") {\n writer.uint32(18).string(message.nextCursor);\n }\n if (message.truncated !== false) {\n writer.uint32(24).bool(message.truncated);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): GetTraceResponse {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseGetTraceResponse();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.ops.push(OperationView.decode(reader, reader.uint32()));\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.nextCursor = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 24) {\n break;\n }\n\n message.truncated = reader.bool();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<GetTraceResponse>, I>>(base?: I): GetTraceResponse {\n return GetTraceResponse.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<GetTraceResponse>, I>>(object: I): GetTraceResponse {\n const message = createBaseGetTraceResponse();\n message.ops = object.ops?.map((e) => OperationView.fromPartial(e)) || [];\n message.nextCursor = object.nextCursor ?? \"\";\n message.truncated = object.truncated ?? false;\n return message;\n },\n};\n\nfunction createBaseGetOperationRequest(): GetOperationRequest {\n return { opId: \"\" };\n}\n\nexport const GetOperationRequest: MessageFns<GetOperationRequest> = {\n encode(message: GetOperationRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.opId !== \"\") {\n writer.uint32(10).string(message.opId);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): GetOperationRequest {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseGetOperationRequest();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.opId = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<GetOperationRequest>, I>>(base?: I): GetOperationRequest {\n return GetOperationRequest.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<GetOperationRequest>, I>>(object: I): GetOperationRequest {\n const message = createBaseGetOperationRequest();\n message.opId = object.opId ?? \"\";\n return message;\n },\n};\n\nfunction createBaseGetOperationResponse(): GetOperationResponse {\n return { op: undefined };\n}\n\nexport const GetOperationResponse: MessageFns<GetOperationResponse> = {\n encode(message: GetOperationResponse, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.op !== undefined) {\n OperationView.encode(message.op, writer.uint32(10).fork()).join();\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): GetOperationResponse {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseGetOperationResponse();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.op = OperationView.decode(reader, reader.uint32());\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<GetOperationResponse>, I>>(base?: I): GetOperationResponse {\n return GetOperationResponse.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<GetOperationResponse>, I>>(object: I): GetOperationResponse {\n const message = createBaseGetOperationResponse();\n message.op = (object.op !== undefined && object.op !== null) ? OperationView.fromPartial(object.op) : undefined;\n return message;\n },\n};\n\nfunction createBaseGetPayloadRequest(): GetPayloadRequest {\n return { traceId: \"\", opId: \"\", direction: 0 };\n}\n\nexport const GetPayloadRequest: MessageFns<GetPayloadRequest> = {\n encode(message: GetPayloadRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.traceId !== \"\") {\n writer.uint32(10).string(message.traceId);\n }\n if (message.opId !== \"\") {\n writer.uint32(18).string(message.opId);\n }\n if (message.direction !== 0) {\n writer.uint32(24).uint32(message.direction);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): GetPayloadRequest {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseGetPayloadRequest();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.traceId = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.opId = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 24) {\n break;\n }\n\n message.direction = reader.uint32();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<GetPayloadRequest>, I>>(base?: I): GetPayloadRequest {\n return GetPayloadRequest.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<GetPayloadRequest>, I>>(object: I): GetPayloadRequest {\n const message = createBaseGetPayloadRequest();\n message.traceId = object.traceId ?? \"\";\n message.opId = object.opId ?? \"\";\n message.direction = object.direction ?? 0;\n return message;\n },\n};\n\nfunction createBaseGetPayloadResponse(): GetPayloadResponse {\n return {\n rawBytes: Buffer.alloc(0),\n decodedBytes: Buffer.alloc(0),\n originalSize: 0,\n contractHash: \"\",\n schemaDrift: false,\n };\n}\n\nexport const GetPayloadResponse: MessageFns<GetPayloadResponse> = {\n encode(message: GetPayloadResponse, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.rawBytes.length !== 0) {\n writer.uint32(10).bytes(message.rawBytes);\n }\n if (message.decodedBytes.length !== 0) {\n writer.uint32(18).bytes(message.decodedBytes);\n }\n if (message.originalSize !== 0) {\n writer.uint32(24).int32(message.originalSize);\n }\n if (message.contractHash !== \"\") {\n writer.uint32(34).string(message.contractHash);\n }\n if (message.schemaDrift !== false) {\n writer.uint32(40).bool(message.schemaDrift);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): GetPayloadResponse {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseGetPayloadResponse();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.rawBytes = Buffer.from(reader.bytes());\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.decodedBytes = Buffer.from(reader.bytes());\n continue;\n }\n case 3: {\n if (tag !== 24) {\n break;\n }\n\n message.originalSize = reader.int32();\n continue;\n }\n case 4: {\n if (tag !== 34) {\n break;\n }\n\n message.contractHash = reader.string();\n continue;\n }\n case 5: {\n if (tag !== 40) {\n break;\n }\n\n message.schemaDrift = reader.bool();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<GetPayloadResponse>, I>>(base?: I): GetPayloadResponse {\n return GetPayloadResponse.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<GetPayloadResponse>, I>>(object: I): GetPayloadResponse {\n const message = createBaseGetPayloadResponse();\n message.rawBytes = object.rawBytes ?? Buffer.alloc(0);\n message.decodedBytes = object.decodedBytes ?? Buffer.alloc(0);\n message.originalSize = object.originalSize ?? 0;\n message.contractHash = object.contractHash ?? \"\";\n message.schemaDrift = object.schemaDrift ?? false;\n return message;\n },\n};\n\nfunction createBaseQueryLogsRequest(): QueryLogsRequest {\n return {\n serviceId: \"\",\n instanceId: \"\",\n fromUnixMs: 0,\n toUnixMs: 0,\n minLevel: 0,\n traceId: \"\",\n textQuery: \"\",\n limit: 0,\n cursor: \"\",\n };\n}\n\nexport const QueryLogsRequest: MessageFns<QueryLogsRequest> = {\n encode(message: QueryLogsRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.serviceId !== \"\") {\n writer.uint32(10).string(message.serviceId);\n }\n if (message.instanceId !== \"\") {\n writer.uint32(18).string(message.instanceId);\n }\n if (message.fromUnixMs !== 0) {\n writer.uint32(24).int64(message.fromUnixMs);\n }\n if (message.toUnixMs !== 0) {\n writer.uint32(32).int64(message.toUnixMs);\n }\n if (message.minLevel !== 0) {\n writer.uint32(40).int32(message.minLevel);\n }\n if (message.traceId !== \"\") {\n writer.uint32(50).string(message.traceId);\n }\n if (message.textQuery !== \"\") {\n writer.uint32(58).string(message.textQuery);\n }\n if (message.limit !== 0) {\n writer.uint32(64).uint32(message.limit);\n }\n if (message.cursor !== \"\") {\n writer.uint32(74).string(message.cursor);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): QueryLogsRequest {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseQueryLogsRequest();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.serviceId = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.instanceId = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 24) {\n break;\n }\n\n message.fromUnixMs = longToNumber(reader.int64());\n continue;\n }\n case 4: {\n if (tag !== 32) {\n break;\n }\n\n message.toUnixMs = longToNumber(reader.int64());\n continue;\n }\n case 5: {\n if (tag !== 40) {\n break;\n }\n\n message.minLevel = reader.int32() as any;\n continue;\n }\n case 6: {\n if (tag !== 50) {\n break;\n }\n\n message.traceId = reader.string();\n continue;\n }\n case 7: {\n if (tag !== 58) {\n break;\n }\n\n message.textQuery = reader.string();\n continue;\n }\n case 8: {\n if (tag !== 64) {\n break;\n }\n\n message.limit = reader.uint32();\n continue;\n }\n case 9: {\n if (tag !== 74) {\n break;\n }\n\n message.cursor = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<QueryLogsRequest>, I>>(base?: I): QueryLogsRequest {\n return QueryLogsRequest.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<QueryLogsRequest>, I>>(object: I): QueryLogsRequest {\n const message = createBaseQueryLogsRequest();\n message.serviceId = object.serviceId ?? \"\";\n message.instanceId = object.instanceId ?? \"\";\n message.fromUnixMs = object.fromUnixMs ?? 0;\n message.toUnixMs = object.toUnixMs ?? 0;\n message.minLevel = object.minLevel ?? 0;\n message.traceId = object.traceId ?? \"\";\n message.textQuery = object.textQuery ?? \"\";\n message.limit = object.limit ?? 0;\n message.cursor = object.cursor ?? \"\";\n return message;\n },\n};\n\nfunction createBaseQueryLogsResponse(): QueryLogsResponse {\n return { entries: [], nextCursor: \"\" };\n}\n\nexport const QueryLogsResponse: MessageFns<QueryLogsResponse> = {\n encode(message: QueryLogsResponse, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n for (const v of message.entries) {\n Log.encode(v!, writer.uint32(10).fork()).join();\n }\n if (message.nextCursor !== \"\") {\n writer.uint32(18).string(message.nextCursor);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): QueryLogsResponse {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseQueryLogsResponse();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.entries.push(Log.decode(reader, reader.uint32()));\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.nextCursor = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<QueryLogsResponse>, I>>(base?: I): QueryLogsResponse {\n return QueryLogsResponse.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<QueryLogsResponse>, I>>(object: I): QueryLogsResponse {\n const message = createBaseQueryLogsResponse();\n message.entries = object.entries?.map((e) => Log.fromPartial(e)) || [];\n message.nextCursor = object.nextCursor ?? \"\";\n return message;\n },\n};\n\nfunction createBaseQueryMetricsRequest(): QueryMetricsRequest {\n return {\n serviceId: \"\",\n instanceId: \"\",\n name: \"\",\n fromUnixMs: 0,\n toUnixMs: 0,\n labelFilters: {},\n stepSeconds: 0,\n percentiles: [],\n };\n}\n\nexport const QueryMetricsRequest: MessageFns<QueryMetricsRequest> = {\n encode(message: QueryMetricsRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.serviceId !== \"\") {\n writer.uint32(10).string(message.serviceId);\n }\n if (message.instanceId !== \"\") {\n writer.uint32(18).string(message.instanceId);\n }\n if (message.name !== \"\") {\n writer.uint32(26).string(message.name);\n }\n if (message.fromUnixMs !== 0) {\n writer.uint32(32).int64(message.fromUnixMs);\n }\n if (message.toUnixMs !== 0) {\n writer.uint32(40).int64(message.toUnixMs);\n }\n globalThis.Object.entries(message.labelFilters).forEach(([key, value]: [string, string]) => {\n QueryMetricsRequest_LabelFiltersEntry.encode({ key: key as any, value }, writer.uint32(50).fork()).join();\n });\n if (message.stepSeconds !== 0) {\n writer.uint32(56).uint32(message.stepSeconds);\n }\n writer.uint32(66).fork();\n for (const v of message.percentiles) {\n writer.double(v);\n }\n writer.join();\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): QueryMetricsRequest {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseQueryMetricsRequest();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.serviceId = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.instanceId = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.name = reader.string();\n continue;\n }\n case 4: {\n if (tag !== 32) {\n break;\n }\n\n message.fromUnixMs = longToNumber(reader.int64());\n continue;\n }\n case 5: {\n if (tag !== 40) {\n break;\n }\n\n message.toUnixMs = longToNumber(reader.int64());\n continue;\n }\n case 6: {\n if (tag !== 50) {\n break;\n }\n\n const entry6 = QueryMetricsRequest_LabelFiltersEntry.decode(reader, reader.uint32());\n if (entry6.value !== undefined) {\n message.labelFilters[entry6.key] = entry6.value;\n }\n continue;\n }\n case 7: {\n if (tag !== 56) {\n break;\n }\n\n message.stepSeconds = reader.uint32();\n continue;\n }\n case 8: {\n if (tag === 65) {\n message.percentiles.push(reader.double());\n\n continue;\n }\n\n if (tag === 66) {\n const end2 = reader.uint32() + reader.pos;\n while (reader.pos < end2) {\n message.percentiles.push(reader.double());\n }\n\n continue;\n }\n\n break;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<QueryMetricsRequest>, I>>(base?: I): QueryMetricsRequest {\n return QueryMetricsRequest.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<QueryMetricsRequest>, I>>(object: I): QueryMetricsRequest {\n const message = createBaseQueryMetricsRequest();\n message.serviceId = object.serviceId ?? \"\";\n message.instanceId = object.instanceId ?? \"\";\n message.name = object.name ?? \"\";\n message.fromUnixMs = object.fromUnixMs ?? 0;\n message.toUnixMs = object.toUnixMs ?? 0;\n message.labelFilters = (globalThis.Object.entries(object.labelFilters ?? {}) as [string, string][]).reduce(\n (acc: { [key: string]: string }, [key, value]: [string, string]) => {\n if (value !== undefined) {\n acc[key] = globalThis.String(value);\n }\n return acc;\n },\n {},\n );\n message.stepSeconds = object.stepSeconds ?? 0;\n message.percentiles = object.percentiles?.map((e) => e) || [];\n return message;\n },\n};\n\nfunction createBaseQueryMetricsRequest_LabelFiltersEntry(): QueryMetricsRequest_LabelFiltersEntry {\n return { key: \"\", value: \"\" };\n}\n\nexport const QueryMetricsRequest_LabelFiltersEntry: MessageFns<QueryMetricsRequest_LabelFiltersEntry> = {\n encode(message: QueryMetricsRequest_LabelFiltersEntry, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.key !== \"\") {\n writer.uint32(10).string(message.key);\n }\n if (message.value !== \"\") {\n writer.uint32(18).string(message.value);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): QueryMetricsRequest_LabelFiltersEntry {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseQueryMetricsRequest_LabelFiltersEntry();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.key = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.value = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<QueryMetricsRequest_LabelFiltersEntry>, I>>(\n base?: I,\n ): QueryMetricsRequest_LabelFiltersEntry {\n return QueryMetricsRequest_LabelFiltersEntry.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<QueryMetricsRequest_LabelFiltersEntry>, I>>(\n object: I,\n ): QueryMetricsRequest_LabelFiltersEntry {\n const message = createBaseQueryMetricsRequest_LabelFiltersEntry();\n message.key = object.key ?? \"\";\n message.value = object.value ?? \"\";\n return message;\n },\n};\n\nfunction createBaseMetricSeries(): MetricSeries {\n return { name: \"\", labels: {}, instanceId: \"\", tsUnixMs: [], values: [], maxValues: [] };\n}\n\nexport const MetricSeries: MessageFns<MetricSeries> = {\n encode(message: MetricSeries, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.name !== \"\") {\n writer.uint32(10).string(message.name);\n }\n globalThis.Object.entries(message.labels).forEach(([key, value]: [string, string]) => {\n MetricSeries_LabelsEntry.encode({ key: key as any, value }, writer.uint32(18).fork()).join();\n });\n if (message.instanceId !== \"\") {\n writer.uint32(26).string(message.instanceId);\n }\n writer.uint32(34).fork();\n for (const v of message.tsUnixMs) {\n writer.int64(v);\n }\n writer.join();\n writer.uint32(42).fork();\n for (const v of message.values) {\n writer.double(v);\n }\n writer.join();\n writer.uint32(50).fork();\n for (const v of message.maxValues) {\n writer.double(v);\n }\n writer.join();\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): MetricSeries {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseMetricSeries();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.name = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n const entry2 = MetricSeries_LabelsEntry.decode(reader, reader.uint32());\n if (entry2.value !== undefined) {\n message.labels[entry2.key] = entry2.value;\n }\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.instanceId = reader.string();\n continue;\n }\n case 4: {\n if (tag === 32) {\n message.tsUnixMs.push(longToNumber(reader.int64()));\n\n continue;\n }\n\n if (tag === 34) {\n const end2 = reader.uint32() + reader.pos;\n while (reader.pos < end2) {\n message.tsUnixMs.push(longToNumber(reader.int64()));\n }\n\n continue;\n }\n\n break;\n }\n case 5: {\n if (tag === 41) {\n message.values.push(reader.double());\n\n continue;\n }\n\n if (tag === 42) {\n const end2 = reader.uint32() + reader.pos;\n while (reader.pos < end2) {\n message.values.push(reader.double());\n }\n\n continue;\n }\n\n break;\n }\n case 6: {\n if (tag === 49) {\n message.maxValues.push(reader.double());\n\n continue;\n }\n\n if (tag === 50) {\n const end2 = reader.uint32() + reader.pos;\n while (reader.pos < end2) {\n message.maxValues.push(reader.double());\n }\n\n continue;\n }\n\n break;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<MetricSeries>, I>>(base?: I): MetricSeries {\n return MetricSeries.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<MetricSeries>, I>>(object: I): MetricSeries {\n const message = createBaseMetricSeries();\n message.name = object.name ?? \"\";\n message.labels = (globalThis.Object.entries(object.labels ?? {}) as [string, string][]).reduce(\n (acc: { [key: string]: string }, [key, value]: [string, string]) => {\n if (value !== undefined) {\n acc[key] = globalThis.String(value);\n }\n return acc;\n },\n {},\n );\n message.instanceId = object.instanceId ?? \"\";\n message.tsUnixMs = object.tsUnixMs?.map((e) => e) || [];\n message.values = object.values?.map((e) => e) || [];\n message.maxValues = object.maxValues?.map((e) => e) || [];\n return message;\n },\n};\n\nfunction createBaseMetricSeries_LabelsEntry(): MetricSeries_LabelsEntry {\n return { key: \"\", value: \"\" };\n}\n\nexport const MetricSeries_LabelsEntry: MessageFns<MetricSeries_LabelsEntry> = {\n encode(message: MetricSeries_LabelsEntry, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.key !== \"\") {\n writer.uint32(10).string(message.key);\n }\n if (message.value !== \"\") {\n writer.uint32(18).string(message.value);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): MetricSeries_LabelsEntry {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseMetricSeries_LabelsEntry();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.key = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.value = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<MetricSeries_LabelsEntry>, I>>(base?: I): MetricSeries_LabelsEntry {\n return MetricSeries_LabelsEntry.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<MetricSeries_LabelsEntry>, I>>(object: I): MetricSeries_LabelsEntry {\n const message = createBaseMetricSeries_LabelsEntry();\n message.key = object.key ?? \"\";\n message.value = object.value ?? \"\";\n return message;\n },\n};\n\nfunction createBaseQueryMetricsResponse(): QueryMetricsResponse {\n return { series: [] };\n}\n\nexport const QueryMetricsResponse: MessageFns<QueryMetricsResponse> = {\n encode(message: QueryMetricsResponse, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n for (const v of message.series) {\n MetricSeries.encode(v!, writer.uint32(10).fork()).join();\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): QueryMetricsResponse {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseQueryMetricsResponse();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.series.push(MetricSeries.decode(reader, reader.uint32()));\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<QueryMetricsResponse>, I>>(base?: I): QueryMetricsResponse {\n return QueryMetricsResponse.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<QueryMetricsResponse>, I>>(object: I): QueryMetricsResponse {\n const message = createBaseQueryMetricsResponse();\n message.series = object.series?.map((e) => MetricSeries.fromPartial(e)) || [];\n return message;\n },\n};\n\n/**\n * Telemetry — unified channel for ops, logs, metrics, payloads.\n *\n * One bidi stream per SDK instance carries TelemetryBatch (oneof kind).\n * Server-side acks via TelemetryAck provide flow control.\n * Read-side unary RPCs serve the UI dashboard.\n *\n * ADR T-025: single stream per identity binding → one disconnect event for\n * ABANDONED sweep, one HTTP/2 stream per SDK instance.\n */\nexport type TelemetryService = typeof TelemetryService;\nexport const TelemetryService = {\n report: {\n path: \"/servicebridge.v1.Telemetry/Report\" as const,\n requestStream: true as const,\n responseStream: true as const,\n requestSerialize: (value: TelemetryBatch): Buffer => Buffer.from(TelemetryBatch.encode(value).finish()),\n requestDeserialize: (value: Buffer): TelemetryBatch => TelemetryBatch.decode(value),\n responseSerialize: (value: TelemetryAck): Buffer => Buffer.from(TelemetryAck.encode(value).finish()),\n responseDeserialize: (value: Buffer): TelemetryAck => TelemetryAck.decode(value),\n },\n listTraces: {\n path: \"/servicebridge.v1.Telemetry/ListTraces\" as const,\n requestStream: false as const,\n responseStream: false as const,\n requestSerialize: (value: ListTracesRequest): Buffer => Buffer.from(ListTracesRequest.encode(value).finish()),\n requestDeserialize: (value: Buffer): ListTracesRequest => ListTracesRequest.decode(value),\n responseSerialize: (value: ListTracesResponse): Buffer => Buffer.from(ListTracesResponse.encode(value).finish()),\n responseDeserialize: (value: Buffer): ListTracesResponse => ListTracesResponse.decode(value),\n },\n getTrace: {\n path: \"/servicebridge.v1.Telemetry/GetTrace\" as const,\n requestStream: false as const,\n responseStream: false as const,\n requestSerialize: (value: GetTraceRequest): Buffer => Buffer.from(GetTraceRequest.encode(value).finish()),\n requestDeserialize: (value: Buffer): GetTraceRequest => GetTraceRequest.decode(value),\n responseSerialize: (value: GetTraceResponse): Buffer => Buffer.from(GetTraceResponse.encode(value).finish()),\n responseDeserialize: (value: Buffer): GetTraceResponse => GetTraceResponse.decode(value),\n },\n getOperation: {\n path: \"/servicebridge.v1.Telemetry/GetOperation\" as const,\n requestStream: false as const,\n responseStream: false as const,\n requestSerialize: (value: GetOperationRequest): Buffer => Buffer.from(GetOperationRequest.encode(value).finish()),\n requestDeserialize: (value: Buffer): GetOperationRequest => GetOperationRequest.decode(value),\n responseSerialize: (value: GetOperationResponse): Buffer =>\n Buffer.from(GetOperationResponse.encode(value).finish()),\n responseDeserialize: (value: Buffer): GetOperationResponse => GetOperationResponse.decode(value),\n },\n getPayload: {\n path: \"/servicebridge.v1.Telemetry/GetPayload\" as const,\n requestStream: false as const,\n responseStream: false as const,\n requestSerialize: (value: GetPayloadRequest): Buffer => Buffer.from(GetPayloadRequest.encode(value).finish()),\n requestDeserialize: (value: Buffer): GetPayloadRequest => GetPayloadRequest.decode(value),\n responseSerialize: (value: GetPayloadResponse): Buffer => Buffer.from(GetPayloadResponse.encode(value).finish()),\n responseDeserialize: (value: Buffer): GetPayloadResponse => GetPayloadResponse.decode(value),\n },\n queryLogs: {\n path: \"/servicebridge.v1.Telemetry/QueryLogs\" as const,\n requestStream: false as const,\n responseStream: false as const,\n requestSerialize: (value: QueryLogsRequest): Buffer => Buffer.from(QueryLogsRequest.encode(value).finish()),\n requestDeserialize: (value: Buffer): QueryLogsRequest => QueryLogsRequest.decode(value),\n responseSerialize: (value: QueryLogsResponse): Buffer => Buffer.from(QueryLogsResponse.encode(value).finish()),\n responseDeserialize: (value: Buffer): QueryLogsResponse => QueryLogsResponse.decode(value),\n },\n queryMetrics: {\n path: \"/servicebridge.v1.Telemetry/QueryMetrics\" as const,\n requestStream: false as const,\n responseStream: false as const,\n requestSerialize: (value: QueryMetricsRequest): Buffer => Buffer.from(QueryMetricsRequest.encode(value).finish()),\n requestDeserialize: (value: Buffer): QueryMetricsRequest => QueryMetricsRequest.decode(value),\n responseSerialize: (value: QueryMetricsResponse): Buffer =>\n Buffer.from(QueryMetricsResponse.encode(value).finish()),\n responseDeserialize: (value: Buffer): QueryMetricsResponse => QueryMetricsResponse.decode(value),\n },\n} as const;\n\nexport interface TelemetryServer extends UntypedServiceImplementation {\n report: handleBidiStreamingCall<TelemetryBatch, TelemetryAck>;\n listTraces: handleUnaryCall<ListTracesRequest, ListTracesResponse>;\n getTrace: handleUnaryCall<GetTraceRequest, GetTraceResponse>;\n getOperation: handleUnaryCall<GetOperationRequest, GetOperationResponse>;\n getPayload: handleUnaryCall<GetPayloadRequest, GetPayloadResponse>;\n queryLogs: handleUnaryCall<QueryLogsRequest, QueryLogsResponse>;\n queryMetrics: handleUnaryCall<QueryMetricsRequest, QueryMetricsResponse>;\n}\n\nexport interface TelemetryClient extends Client {\n report(): ClientDuplexStream<TelemetryBatch, TelemetryAck>;\n report(options: Partial<CallOptions>): ClientDuplexStream<TelemetryBatch, TelemetryAck>;\n report(metadata: Metadata, options?: Partial<CallOptions>): ClientDuplexStream<TelemetryBatch, TelemetryAck>;\n listTraces(\n request: ListTracesRequest,\n callback: (error: ServiceError | null, response: ListTracesResponse) => void,\n ): ClientUnaryCall;\n listTraces(\n request: ListTracesRequest,\n metadata: Metadata,\n callback: (error: ServiceError | null, response: ListTracesResponse) => void,\n ): ClientUnaryCall;\n listTraces(\n request: ListTracesRequest,\n metadata: Metadata,\n options: Partial<CallOptions>,\n callback: (error: ServiceError | null, response: ListTracesResponse) => void,\n ): ClientUnaryCall;\n getTrace(\n request: GetTraceRequest,\n callback: (error: ServiceError | null, response: GetTraceResponse) => void,\n ): ClientUnaryCall;\n getTrace(\n request: GetTraceRequest,\n metadata: Metadata,\n callback: (error: ServiceError | null, response: GetTraceResponse) => void,\n ): ClientUnaryCall;\n getTrace(\n request: GetTraceRequest,\n metadata: Metadata,\n options: Partial<CallOptions>,\n callback: (error: ServiceError | null, response: GetTraceResponse) => void,\n ): ClientUnaryCall;\n getOperation(\n request: GetOperationRequest,\n callback: (error: ServiceError | null, response: GetOperationResponse) => void,\n ): ClientUnaryCall;\n getOperation(\n request: GetOperationRequest,\n metadata: Metadata,\n callback: (error: ServiceError | null, response: GetOperationResponse) => void,\n ): ClientUnaryCall;\n getOperation(\n request: GetOperationRequest,\n metadata: Metadata,\n options: Partial<CallOptions>,\n callback: (error: ServiceError | null, response: GetOperationResponse) => void,\n ): ClientUnaryCall;\n getPayload(\n request: GetPayloadRequest,\n callback: (error: ServiceError | null, response: GetPayloadResponse) => void,\n ): ClientUnaryCall;\n getPayload(\n request: GetPayloadRequest,\n metadata: Metadata,\n callback: (error: ServiceError | null, response: GetPayloadResponse) => void,\n ): ClientUnaryCall;\n getPayload(\n request: GetPayloadRequest,\n metadata: Metadata,\n options: Partial<CallOptions>,\n callback: (error: ServiceError | null, response: GetPayloadResponse) => void,\n ): ClientUnaryCall;\n queryLogs(\n request: QueryLogsRequest,\n callback: (error: ServiceError | null, response: QueryLogsResponse) => void,\n ): ClientUnaryCall;\n queryLogs(\n request: QueryLogsRequest,\n metadata: Metadata,\n callback: (error: ServiceError | null, response: QueryLogsResponse) => void,\n ): ClientUnaryCall;\n queryLogs(\n request: QueryLogsRequest,\n metadata: Metadata,\n options: Partial<CallOptions>,\n callback: (error: ServiceError | null, response: QueryLogsResponse) => void,\n ): ClientUnaryCall;\n queryMetrics(\n request: QueryMetricsRequest,\n callback: (error: ServiceError | null, response: QueryMetricsResponse) => void,\n ): ClientUnaryCall;\n queryMetrics(\n request: QueryMetricsRequest,\n metadata: Metadata,\n callback: (error: ServiceError | null, response: QueryMetricsResponse) => void,\n ): ClientUnaryCall;\n queryMetrics(\n request: QueryMetricsRequest,\n metadata: Metadata,\n options: Partial<CallOptions>,\n callback: (error: ServiceError | null, response: QueryMetricsResponse) => void,\n ): ClientUnaryCall;\n}\n\nexport const TelemetryClient = makeGenericClientConstructor(\n TelemetryService,\n \"servicebridge.v1.Telemetry\",\n) as unknown as {\n new (address: string, credentials: ChannelCredentials, options?: Partial<ClientOptions>): TelemetryClient;\n service: typeof TelemetryService;\n serviceName: string;\n};\n\ntype Builtin = Date | Function | Uint8Array | string | number | boolean | undefined;\n\ntype DeepPartial<T> = T extends Builtin ? T\n : T extends globalThis.Array<infer U> ? globalThis.Array<DeepPartial<U>>\n : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>>\n : T extends {} ? { [K in keyof T]?: DeepPartial<T[K]> }\n : Partial<T>;\n\ntype KeysOfUnion<T> = T extends T ? keyof T : never;\ntype Exact<P, I extends P> = P extends Builtin ? P\n : P & { [K in keyof P]: Exact<P[K], I[K]> } & { [K in Exclude<keyof I, KeysOfUnion<P>>]: never };\n\nfunction longToNumber(int64: { toString(): string }): number {\n const num = globalThis.Number(int64.toString());\n if (num > globalThis.Number.MAX_SAFE_INTEGER) {\n throw new globalThis.Error(\"Value is larger than Number.MAX_SAFE_INTEGER\");\n }\n if (num < globalThis.Number.MIN_SAFE_INTEGER) {\n throw new globalThis.Error(\"Value is smaller than Number.MIN_SAFE_INTEGER\");\n }\n return num;\n}\n\ninterface MessageFns<T> {\n encode(message: T, writer?: BinaryWriter): BinaryWriter;\n decode(input: BinaryReader | Uint8Array, length?: number): T;\n create<I extends Exact<DeepPartial<T>, I>>(base?: I): T;\n fromPartial<I extends Exact<DeepPartial<T>, I>>(object: I): T;\n}\n","// Code generated by protoc-gen-ts_proto. DO NOT EDIT.\n// versions:\n// protoc-gen-ts_proto v2.11.8\n// protoc unknown\n// source: servicebridge/v1/workflows.proto\n\n/* eslint-disable */\nimport { BinaryReader, BinaryWriter } from \"@bufbuild/protobuf/wire\";\nimport {\n type CallOptions,\n type ChannelCredentials,\n Client,\n type ClientOptions,\n type ClientReadableStream,\n type ClientUnaryCall,\n type handleServerStreamingCall,\n type handleUnaryCall,\n makeGenericClientConstructor,\n type Metadata,\n type ServiceError,\n type UntypedServiceImplementation,\n} from \"@grpc/grpc-js\";\nimport { Empty } from \"../../google/protobuf/empty\";\n\nexport interface StartRunRequest {\n workflowName: string;\n /** JSON-encoded workflow input */\n input: Buffer;\n idempotencyKey: string;\n /** 0 = no global timeout override */\n timeoutSec: number;\n /** X-SB-Trace propagation from caller. */\n xSbTrace: string;\n /**\n * parent_run_id — when non-empty, the request originates from a workflow\n * step on an in-flight parent run. Runtime enforces dynamic cycle\n * detection (ADR-W-019) by walking the ancestor chain via this id.\n * Empty for top-level starts initiated by external callers.\n */\n parentRunId: string;\n}\n\nexport interface StartRunResponse {\n runId: string;\n}\n\nexport interface CancelRunRequest {\n runId: string;\n}\n\nexport interface SignalRunRequest {\n runId: string;\n signalName: string;\n payload: Buffer;\n}\n\nexport interface QueryRunRequest {\n runId: string;\n}\n\nexport interface QueryRunResponse {\n runId: string;\n status: string;\n /** JSON-encoded run state map */\n state: Buffer;\n steps: StepInfo[];\n}\n\nexport interface StepInfo {\n stepId: string;\n status: string;\n output: Buffer;\n lastError: string;\n /** step_id of the compensation step, if compensated */\n compensatedBy: string;\n}\n\nexport interface AwaitRunRequest {\n runId: string;\n}\n\nexport interface RunStatusUpdate {\n runId: string;\n status: string;\n /** JSON-encoded final state; non-empty only on terminal status */\n state: Buffer;\n}\n\nexport interface ReplayRunRequest {\n runId: string;\n fromStepId: string;\n}\n\nexport interface ReplayRunResponse {\n /** new run id */\n runId: string;\n}\n\nexport interface SubscribeRequest {\n /** UUID */\n serviceId: string;\n /** UUID */\n instanceId: string;\n}\n\nexport interface RunAssignment {\n runId: string;\n workflowName: string;\n fingerprint: string;\n /** canonical JSON graph */\n frozenPlan: Buffer;\n /** JSON-encoded workflow input */\n input: Buffer;\n /** JSON-encoded current state (checkpointed outputs) */\n state: Buffer;\n leaseEpoch: number;\n maxParallelism: number;\n /** X-SB-Trace propagation — workflow root op. */\n xSbTrace: string;\n /** Compensation: if set, SDK must execute compensation steps. */\n compensating: boolean;\n /** cancel_reason mirrors workflow_runs.cancel_reason. Values: '' | 'user_cancel' | 'step_failure'. */\n cancelReason: string;\n}\n\nexport interface BeginStepRequest {\n runId: string;\n stepId: string;\n /** empty for top-level steps */\n parentStepId: string;\n /** call|publish|sleep|wait_event|wait_signal|workflow|parallel|sequence|local */\n kind: string;\n /** JSON-encoded resolved inputs */\n inputSnapshot: Buffer;\n leaseEpoch: number;\n /** UUID of the claiming SDK instance */\n instanceId: string;\n}\n\nexport interface BeginStepResponse {\n /**\n * If the step was already completed (idempotent replay), cached_output is\n * non-nil and the SDK must use it without re-executing.\n */\n cachedOutput: Buffer;\n alreadyDone: boolean;\n leaseEpoch: number;\n}\n\nexport interface CompleteStepRequest {\n runId: string;\n stepId: string;\n /** JSON-encoded step output */\n output: Buffer;\n leaseEpoch: number;\n}\n\nexport interface FailStepRequest {\n runId: string;\n stepId: string;\n errorCode: string;\n errorMessage: string;\n leaseEpoch: number;\n retriable: boolean;\n}\n\nexport interface FailStepResponse {\n /** Runtime's decision after the failure. */\n nextAction: string;\n retryDelaySec: number;\n}\n\nexport interface ParkRequest {\n runId: string;\n stepId: string;\n leaseEpoch: number;\n sleep?: SleepSpec | undefined;\n eventWait?: EventWaitSpec | undefined;\n signalWait?: SignalWaitSpec | undefined;\n nestedRun?: NestedRunSpec | undefined;\n}\n\nexport interface SleepSpec {\n durationSec: number;\n}\n\nexport interface EventWaitSpec {\n event: string;\n /** JSON-encoded {\"$.path\": \"expected\"} filter; empty = match all */\n filterJson: string;\n /** 0 = no timeout */\n timeoutSec: number;\n}\n\nexport interface SignalWaitSpec {\n signal: string;\n /** 0 = no timeout */\n timeoutSec: number;\n}\n\nexport interface NestedRunSpec {\n childRunId: string;\n}\n\nexport interface CompleteRunRequest {\n runId: string;\n /** JSON-encoded final state map (output of last step) */\n finalState: Buffer;\n leaseEpoch: number;\n /**\n * terminal_status: 'success' | 'failed_compensated' | 'cancelled'.\n * If empty, defaults to 'success'.\n */\n terminalStatus: string;\n}\n\nexport interface HeartbeatRequest {\n runId: string;\n /** UUID */\n instanceId: string;\n leaseEpoch: number;\n}\n\nfunction createBaseStartRunRequest(): StartRunRequest {\n return { workflowName: \"\", input: Buffer.alloc(0), idempotencyKey: \"\", timeoutSec: 0, xSbTrace: \"\", parentRunId: \"\" };\n}\n\nexport const StartRunRequest: MessageFns<StartRunRequest> = {\n encode(message: StartRunRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.workflowName !== \"\") {\n writer.uint32(10).string(message.workflowName);\n }\n if (message.input.length !== 0) {\n writer.uint32(18).bytes(message.input);\n }\n if (message.idempotencyKey !== \"\") {\n writer.uint32(26).string(message.idempotencyKey);\n }\n if (message.timeoutSec !== 0) {\n writer.uint32(32).uint32(message.timeoutSec);\n }\n if (message.xSbTrace !== \"\") {\n writer.uint32(42).string(message.xSbTrace);\n }\n if (message.parentRunId !== \"\") {\n writer.uint32(66).string(message.parentRunId);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): StartRunRequest {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseStartRunRequest();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.workflowName = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.input = Buffer.from(reader.bytes());\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.idempotencyKey = reader.string();\n continue;\n }\n case 4: {\n if (tag !== 32) {\n break;\n }\n\n message.timeoutSec = reader.uint32();\n continue;\n }\n case 5: {\n if (tag !== 42) {\n break;\n }\n\n message.xSbTrace = reader.string();\n continue;\n }\n case 8: {\n if (tag !== 66) {\n break;\n }\n\n message.parentRunId = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<StartRunRequest>, I>>(base?: I): StartRunRequest {\n return StartRunRequest.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<StartRunRequest>, I>>(object: I): StartRunRequest {\n const message = createBaseStartRunRequest();\n message.workflowName = object.workflowName ?? \"\";\n message.input = object.input ?? Buffer.alloc(0);\n message.idempotencyKey = object.idempotencyKey ?? \"\";\n message.timeoutSec = object.timeoutSec ?? 0;\n message.xSbTrace = object.xSbTrace ?? \"\";\n message.parentRunId = object.parentRunId ?? \"\";\n return message;\n },\n};\n\nfunction createBaseStartRunResponse(): StartRunResponse {\n return { runId: \"\" };\n}\n\nexport const StartRunResponse: MessageFns<StartRunResponse> = {\n encode(message: StartRunResponse, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.runId !== \"\") {\n writer.uint32(10).string(message.runId);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): StartRunResponse {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseStartRunResponse();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.runId = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<StartRunResponse>, I>>(base?: I): StartRunResponse {\n return StartRunResponse.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<StartRunResponse>, I>>(object: I): StartRunResponse {\n const message = createBaseStartRunResponse();\n message.runId = object.runId ?? \"\";\n return message;\n },\n};\n\nfunction createBaseCancelRunRequest(): CancelRunRequest {\n return { runId: \"\" };\n}\n\nexport const CancelRunRequest: MessageFns<CancelRunRequest> = {\n encode(message: CancelRunRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.runId !== \"\") {\n writer.uint32(10).string(message.runId);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): CancelRunRequest {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseCancelRunRequest();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.runId = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<CancelRunRequest>, I>>(base?: I): CancelRunRequest {\n return CancelRunRequest.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<CancelRunRequest>, I>>(object: I): CancelRunRequest {\n const message = createBaseCancelRunRequest();\n message.runId = object.runId ?? \"\";\n return message;\n },\n};\n\nfunction createBaseSignalRunRequest(): SignalRunRequest {\n return { runId: \"\", signalName: \"\", payload: Buffer.alloc(0) };\n}\n\nexport const SignalRunRequest: MessageFns<SignalRunRequest> = {\n encode(message: SignalRunRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.runId !== \"\") {\n writer.uint32(10).string(message.runId);\n }\n if (message.signalName !== \"\") {\n writer.uint32(18).string(message.signalName);\n }\n if (message.payload.length !== 0) {\n writer.uint32(26).bytes(message.payload);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): SignalRunRequest {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseSignalRunRequest();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.runId = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.signalName = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.payload = Buffer.from(reader.bytes());\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<SignalRunRequest>, I>>(base?: I): SignalRunRequest {\n return SignalRunRequest.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<SignalRunRequest>, I>>(object: I): SignalRunRequest {\n const message = createBaseSignalRunRequest();\n message.runId = object.runId ?? \"\";\n message.signalName = object.signalName ?? \"\";\n message.payload = object.payload ?? Buffer.alloc(0);\n return message;\n },\n};\n\nfunction createBaseQueryRunRequest(): QueryRunRequest {\n return { runId: \"\" };\n}\n\nexport const QueryRunRequest: MessageFns<QueryRunRequest> = {\n encode(message: QueryRunRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.runId !== \"\") {\n writer.uint32(10).string(message.runId);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): QueryRunRequest {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseQueryRunRequest();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.runId = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<QueryRunRequest>, I>>(base?: I): QueryRunRequest {\n return QueryRunRequest.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<QueryRunRequest>, I>>(object: I): QueryRunRequest {\n const message = createBaseQueryRunRequest();\n message.runId = object.runId ?? \"\";\n return message;\n },\n};\n\nfunction createBaseQueryRunResponse(): QueryRunResponse {\n return { runId: \"\", status: \"\", state: Buffer.alloc(0), steps: [] };\n}\n\nexport const QueryRunResponse: MessageFns<QueryRunResponse> = {\n encode(message: QueryRunResponse, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.runId !== \"\") {\n writer.uint32(10).string(message.runId);\n }\n if (message.status !== \"\") {\n writer.uint32(18).string(message.status);\n }\n if (message.state.length !== 0) {\n writer.uint32(26).bytes(message.state);\n }\n for (const v of message.steps) {\n StepInfo.encode(v!, writer.uint32(34).fork()).join();\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): QueryRunResponse {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseQueryRunResponse();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.runId = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.status = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.state = Buffer.from(reader.bytes());\n continue;\n }\n case 4: {\n if (tag !== 34) {\n break;\n }\n\n message.steps.push(StepInfo.decode(reader, reader.uint32()));\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<QueryRunResponse>, I>>(base?: I): QueryRunResponse {\n return QueryRunResponse.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<QueryRunResponse>, I>>(object: I): QueryRunResponse {\n const message = createBaseQueryRunResponse();\n message.runId = object.runId ?? \"\";\n message.status = object.status ?? \"\";\n message.state = object.state ?? Buffer.alloc(0);\n message.steps = object.steps?.map((e) => StepInfo.fromPartial(e)) || [];\n return message;\n },\n};\n\nfunction createBaseStepInfo(): StepInfo {\n return { stepId: \"\", status: \"\", output: Buffer.alloc(0), lastError: \"\", compensatedBy: \"\" };\n}\n\nexport const StepInfo: MessageFns<StepInfo> = {\n encode(message: StepInfo, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.stepId !== \"\") {\n writer.uint32(10).string(message.stepId);\n }\n if (message.status !== \"\") {\n writer.uint32(18).string(message.status);\n }\n if (message.output.length !== 0) {\n writer.uint32(26).bytes(message.output);\n }\n if (message.lastError !== \"\") {\n writer.uint32(34).string(message.lastError);\n }\n if (message.compensatedBy !== \"\") {\n writer.uint32(42).string(message.compensatedBy);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): StepInfo {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseStepInfo();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.stepId = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.status = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.output = Buffer.from(reader.bytes());\n continue;\n }\n case 4: {\n if (tag !== 34) {\n break;\n }\n\n message.lastError = reader.string();\n continue;\n }\n case 5: {\n if (tag !== 42) {\n break;\n }\n\n message.compensatedBy = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<StepInfo>, I>>(base?: I): StepInfo {\n return StepInfo.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<StepInfo>, I>>(object: I): StepInfo {\n const message = createBaseStepInfo();\n message.stepId = object.stepId ?? \"\";\n message.status = object.status ?? \"\";\n message.output = object.output ?? Buffer.alloc(0);\n message.lastError = object.lastError ?? \"\";\n message.compensatedBy = object.compensatedBy ?? \"\";\n return message;\n },\n};\n\nfunction createBaseAwaitRunRequest(): AwaitRunRequest {\n return { runId: \"\" };\n}\n\nexport const AwaitRunRequest: MessageFns<AwaitRunRequest> = {\n encode(message: AwaitRunRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.runId !== \"\") {\n writer.uint32(10).string(message.runId);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): AwaitRunRequest {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseAwaitRunRequest();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.runId = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<AwaitRunRequest>, I>>(base?: I): AwaitRunRequest {\n return AwaitRunRequest.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<AwaitRunRequest>, I>>(object: I): AwaitRunRequest {\n const message = createBaseAwaitRunRequest();\n message.runId = object.runId ?? \"\";\n return message;\n },\n};\n\nfunction createBaseRunStatusUpdate(): RunStatusUpdate {\n return { runId: \"\", status: \"\", state: Buffer.alloc(0) };\n}\n\nexport const RunStatusUpdate: MessageFns<RunStatusUpdate> = {\n encode(message: RunStatusUpdate, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.runId !== \"\") {\n writer.uint32(10).string(message.runId);\n }\n if (message.status !== \"\") {\n writer.uint32(18).string(message.status);\n }\n if (message.state.length !== 0) {\n writer.uint32(26).bytes(message.state);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): RunStatusUpdate {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseRunStatusUpdate();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.runId = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.status = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.state = Buffer.from(reader.bytes());\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<RunStatusUpdate>, I>>(base?: I): RunStatusUpdate {\n return RunStatusUpdate.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<RunStatusUpdate>, I>>(object: I): RunStatusUpdate {\n const message = createBaseRunStatusUpdate();\n message.runId = object.runId ?? \"\";\n message.status = object.status ?? \"\";\n message.state = object.state ?? Buffer.alloc(0);\n return message;\n },\n};\n\nfunction createBaseReplayRunRequest(): ReplayRunRequest {\n return { runId: \"\", fromStepId: \"\" };\n}\n\nexport const ReplayRunRequest: MessageFns<ReplayRunRequest> = {\n encode(message: ReplayRunRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.runId !== \"\") {\n writer.uint32(10).string(message.runId);\n }\n if (message.fromStepId !== \"\") {\n writer.uint32(18).string(message.fromStepId);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): ReplayRunRequest {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseReplayRunRequest();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.runId = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.fromStepId = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<ReplayRunRequest>, I>>(base?: I): ReplayRunRequest {\n return ReplayRunRequest.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<ReplayRunRequest>, I>>(object: I): ReplayRunRequest {\n const message = createBaseReplayRunRequest();\n message.runId = object.runId ?? \"\";\n message.fromStepId = object.fromStepId ?? \"\";\n return message;\n },\n};\n\nfunction createBaseReplayRunResponse(): ReplayRunResponse {\n return { runId: \"\" };\n}\n\nexport const ReplayRunResponse: MessageFns<ReplayRunResponse> = {\n encode(message: ReplayRunResponse, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.runId !== \"\") {\n writer.uint32(10).string(message.runId);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): ReplayRunResponse {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseReplayRunResponse();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.runId = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<ReplayRunResponse>, I>>(base?: I): ReplayRunResponse {\n return ReplayRunResponse.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<ReplayRunResponse>, I>>(object: I): ReplayRunResponse {\n const message = createBaseReplayRunResponse();\n message.runId = object.runId ?? \"\";\n return message;\n },\n};\n\nfunction createBaseSubscribeRequest(): SubscribeRequest {\n return { serviceId: \"\", instanceId: \"\" };\n}\n\nexport const SubscribeRequest: MessageFns<SubscribeRequest> = {\n encode(message: SubscribeRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.serviceId !== \"\") {\n writer.uint32(10).string(message.serviceId);\n }\n if (message.instanceId !== \"\") {\n writer.uint32(18).string(message.instanceId);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): SubscribeRequest {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseSubscribeRequest();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.serviceId = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.instanceId = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<SubscribeRequest>, I>>(base?: I): SubscribeRequest {\n return SubscribeRequest.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<SubscribeRequest>, I>>(object: I): SubscribeRequest {\n const message = createBaseSubscribeRequest();\n message.serviceId = object.serviceId ?? \"\";\n message.instanceId = object.instanceId ?? \"\";\n return message;\n },\n};\n\nfunction createBaseRunAssignment(): RunAssignment {\n return {\n runId: \"\",\n workflowName: \"\",\n fingerprint: \"\",\n frozenPlan: Buffer.alloc(0),\n input: Buffer.alloc(0),\n state: Buffer.alloc(0),\n leaseEpoch: 0,\n maxParallelism: 0,\n xSbTrace: \"\",\n compensating: false,\n cancelReason: \"\",\n };\n}\n\nexport const RunAssignment: MessageFns<RunAssignment> = {\n encode(message: RunAssignment, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.runId !== \"\") {\n writer.uint32(10).string(message.runId);\n }\n if (message.workflowName !== \"\") {\n writer.uint32(18).string(message.workflowName);\n }\n if (message.fingerprint !== \"\") {\n writer.uint32(26).string(message.fingerprint);\n }\n if (message.frozenPlan.length !== 0) {\n writer.uint32(34).bytes(message.frozenPlan);\n }\n if (message.input.length !== 0) {\n writer.uint32(42).bytes(message.input);\n }\n if (message.state.length !== 0) {\n writer.uint32(50).bytes(message.state);\n }\n if (message.leaseEpoch !== 0) {\n writer.uint32(56).uint64(message.leaseEpoch);\n }\n if (message.maxParallelism !== 0) {\n writer.uint32(64).uint32(message.maxParallelism);\n }\n if (message.xSbTrace !== \"\") {\n writer.uint32(74).string(message.xSbTrace);\n }\n if (message.compensating !== false) {\n writer.uint32(96).bool(message.compensating);\n }\n if (message.cancelReason !== \"\") {\n writer.uint32(106).string(message.cancelReason);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): RunAssignment {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseRunAssignment();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.runId = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.workflowName = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.fingerprint = reader.string();\n continue;\n }\n case 4: {\n if (tag !== 34) {\n break;\n }\n\n message.frozenPlan = Buffer.from(reader.bytes());\n continue;\n }\n case 5: {\n if (tag !== 42) {\n break;\n }\n\n message.input = Buffer.from(reader.bytes());\n continue;\n }\n case 6: {\n if (tag !== 50) {\n break;\n }\n\n message.state = Buffer.from(reader.bytes());\n continue;\n }\n case 7: {\n if (tag !== 56) {\n break;\n }\n\n message.leaseEpoch = longToNumber(reader.uint64());\n continue;\n }\n case 8: {\n if (tag !== 64) {\n break;\n }\n\n message.maxParallelism = reader.uint32();\n continue;\n }\n case 9: {\n if (tag !== 74) {\n break;\n }\n\n message.xSbTrace = reader.string();\n continue;\n }\n case 12: {\n if (tag !== 96) {\n break;\n }\n\n message.compensating = reader.bool();\n continue;\n }\n case 13: {\n if (tag !== 106) {\n break;\n }\n\n message.cancelReason = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<RunAssignment>, I>>(base?: I): RunAssignment {\n return RunAssignment.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<RunAssignment>, I>>(object: I): RunAssignment {\n const message = createBaseRunAssignment();\n message.runId = object.runId ?? \"\";\n message.workflowName = object.workflowName ?? \"\";\n message.fingerprint = object.fingerprint ?? \"\";\n message.frozenPlan = object.frozenPlan ?? Buffer.alloc(0);\n message.input = object.input ?? Buffer.alloc(0);\n message.state = object.state ?? Buffer.alloc(0);\n message.leaseEpoch = object.leaseEpoch ?? 0;\n message.maxParallelism = object.maxParallelism ?? 0;\n message.xSbTrace = object.xSbTrace ?? \"\";\n message.compensating = object.compensating ?? false;\n message.cancelReason = object.cancelReason ?? \"\";\n return message;\n },\n};\n\nfunction createBaseBeginStepRequest(): BeginStepRequest {\n return {\n runId: \"\",\n stepId: \"\",\n parentStepId: \"\",\n kind: \"\",\n inputSnapshot: Buffer.alloc(0),\n leaseEpoch: 0,\n instanceId: \"\",\n };\n}\n\nexport const BeginStepRequest: MessageFns<BeginStepRequest> = {\n encode(message: BeginStepRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.runId !== \"\") {\n writer.uint32(10).string(message.runId);\n }\n if (message.stepId !== \"\") {\n writer.uint32(18).string(message.stepId);\n }\n if (message.parentStepId !== \"\") {\n writer.uint32(26).string(message.parentStepId);\n }\n if (message.kind !== \"\") {\n writer.uint32(34).string(message.kind);\n }\n if (message.inputSnapshot.length !== 0) {\n writer.uint32(42).bytes(message.inputSnapshot);\n }\n if (message.leaseEpoch !== 0) {\n writer.uint32(48).uint64(message.leaseEpoch);\n }\n if (message.instanceId !== \"\") {\n writer.uint32(58).string(message.instanceId);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): BeginStepRequest {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseBeginStepRequest();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.runId = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.stepId = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.parentStepId = reader.string();\n continue;\n }\n case 4: {\n if (tag !== 34) {\n break;\n }\n\n message.kind = reader.string();\n continue;\n }\n case 5: {\n if (tag !== 42) {\n break;\n }\n\n message.inputSnapshot = Buffer.from(reader.bytes());\n continue;\n }\n case 6: {\n if (tag !== 48) {\n break;\n }\n\n message.leaseEpoch = longToNumber(reader.uint64());\n continue;\n }\n case 7: {\n if (tag !== 58) {\n break;\n }\n\n message.instanceId = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<BeginStepRequest>, I>>(base?: I): BeginStepRequest {\n return BeginStepRequest.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<BeginStepRequest>, I>>(object: I): BeginStepRequest {\n const message = createBaseBeginStepRequest();\n message.runId = object.runId ?? \"\";\n message.stepId = object.stepId ?? \"\";\n message.parentStepId = object.parentStepId ?? \"\";\n message.kind = object.kind ?? \"\";\n message.inputSnapshot = object.inputSnapshot ?? Buffer.alloc(0);\n message.leaseEpoch = object.leaseEpoch ?? 0;\n message.instanceId = object.instanceId ?? \"\";\n return message;\n },\n};\n\nfunction createBaseBeginStepResponse(): BeginStepResponse {\n return { cachedOutput: Buffer.alloc(0), alreadyDone: false, leaseEpoch: 0 };\n}\n\nexport const BeginStepResponse: MessageFns<BeginStepResponse> = {\n encode(message: BeginStepResponse, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.cachedOutput.length !== 0) {\n writer.uint32(10).bytes(message.cachedOutput);\n }\n if (message.alreadyDone !== false) {\n writer.uint32(16).bool(message.alreadyDone);\n }\n if (message.leaseEpoch !== 0) {\n writer.uint32(24).uint64(message.leaseEpoch);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): BeginStepResponse {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseBeginStepResponse();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.cachedOutput = Buffer.from(reader.bytes());\n continue;\n }\n case 2: {\n if (tag !== 16) {\n break;\n }\n\n message.alreadyDone = reader.bool();\n continue;\n }\n case 3: {\n if (tag !== 24) {\n break;\n }\n\n message.leaseEpoch = longToNumber(reader.uint64());\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<BeginStepResponse>, I>>(base?: I): BeginStepResponse {\n return BeginStepResponse.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<BeginStepResponse>, I>>(object: I): BeginStepResponse {\n const message = createBaseBeginStepResponse();\n message.cachedOutput = object.cachedOutput ?? Buffer.alloc(0);\n message.alreadyDone = object.alreadyDone ?? false;\n message.leaseEpoch = object.leaseEpoch ?? 0;\n return message;\n },\n};\n\nfunction createBaseCompleteStepRequest(): CompleteStepRequest {\n return { runId: \"\", stepId: \"\", output: Buffer.alloc(0), leaseEpoch: 0 };\n}\n\nexport const CompleteStepRequest: MessageFns<CompleteStepRequest> = {\n encode(message: CompleteStepRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.runId !== \"\") {\n writer.uint32(10).string(message.runId);\n }\n if (message.stepId !== \"\") {\n writer.uint32(18).string(message.stepId);\n }\n if (message.output.length !== 0) {\n writer.uint32(26).bytes(message.output);\n }\n if (message.leaseEpoch !== 0) {\n writer.uint32(32).uint64(message.leaseEpoch);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): CompleteStepRequest {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseCompleteStepRequest();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.runId = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.stepId = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.output = Buffer.from(reader.bytes());\n continue;\n }\n case 4: {\n if (tag !== 32) {\n break;\n }\n\n message.leaseEpoch = longToNumber(reader.uint64());\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<CompleteStepRequest>, I>>(base?: I): CompleteStepRequest {\n return CompleteStepRequest.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<CompleteStepRequest>, I>>(object: I): CompleteStepRequest {\n const message = createBaseCompleteStepRequest();\n message.runId = object.runId ?? \"\";\n message.stepId = object.stepId ?? \"\";\n message.output = object.output ?? Buffer.alloc(0);\n message.leaseEpoch = object.leaseEpoch ?? 0;\n return message;\n },\n};\n\nfunction createBaseFailStepRequest(): FailStepRequest {\n return { runId: \"\", stepId: \"\", errorCode: \"\", errorMessage: \"\", leaseEpoch: 0, retriable: false };\n}\n\nexport const FailStepRequest: MessageFns<FailStepRequest> = {\n encode(message: FailStepRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.runId !== \"\") {\n writer.uint32(10).string(message.runId);\n }\n if (message.stepId !== \"\") {\n writer.uint32(18).string(message.stepId);\n }\n if (message.errorCode !== \"\") {\n writer.uint32(26).string(message.errorCode);\n }\n if (message.errorMessage !== \"\") {\n writer.uint32(34).string(message.errorMessage);\n }\n if (message.leaseEpoch !== 0) {\n writer.uint32(40).uint64(message.leaseEpoch);\n }\n if (message.retriable !== false) {\n writer.uint32(48).bool(message.retriable);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): FailStepRequest {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseFailStepRequest();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.runId = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.stepId = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.errorCode = reader.string();\n continue;\n }\n case 4: {\n if (tag !== 34) {\n break;\n }\n\n message.errorMessage = reader.string();\n continue;\n }\n case 5: {\n if (tag !== 40) {\n break;\n }\n\n message.leaseEpoch = longToNumber(reader.uint64());\n continue;\n }\n case 6: {\n if (tag !== 48) {\n break;\n }\n\n message.retriable = reader.bool();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<FailStepRequest>, I>>(base?: I): FailStepRequest {\n return FailStepRequest.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<FailStepRequest>, I>>(object: I): FailStepRequest {\n const message = createBaseFailStepRequest();\n message.runId = object.runId ?? \"\";\n message.stepId = object.stepId ?? \"\";\n message.errorCode = object.errorCode ?? \"\";\n message.errorMessage = object.errorMessage ?? \"\";\n message.leaseEpoch = object.leaseEpoch ?? 0;\n message.retriable = object.retriable ?? false;\n return message;\n },\n};\n\nfunction createBaseFailStepResponse(): FailStepResponse {\n return { nextAction: \"\", retryDelaySec: 0 };\n}\n\nexport const FailStepResponse: MessageFns<FailStepResponse> = {\n encode(message: FailStepResponse, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.nextAction !== \"\") {\n writer.uint32(10).string(message.nextAction);\n }\n if (message.retryDelaySec !== 0) {\n writer.uint32(16).uint32(message.retryDelaySec);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): FailStepResponse {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseFailStepResponse();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.nextAction = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 16) {\n break;\n }\n\n message.retryDelaySec = reader.uint32();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<FailStepResponse>, I>>(base?: I): FailStepResponse {\n return FailStepResponse.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<FailStepResponse>, I>>(object: I): FailStepResponse {\n const message = createBaseFailStepResponse();\n message.nextAction = object.nextAction ?? \"\";\n message.retryDelaySec = object.retryDelaySec ?? 0;\n return message;\n },\n};\n\nfunction createBaseParkRequest(): ParkRequest {\n return {\n runId: \"\",\n stepId: \"\",\n leaseEpoch: 0,\n sleep: undefined,\n eventWait: undefined,\n signalWait: undefined,\n nestedRun: undefined,\n };\n}\n\nexport const ParkRequest: MessageFns<ParkRequest> = {\n encode(message: ParkRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.runId !== \"\") {\n writer.uint32(10).string(message.runId);\n }\n if (message.stepId !== \"\") {\n writer.uint32(18).string(message.stepId);\n }\n if (message.leaseEpoch !== 0) {\n writer.uint32(24).uint64(message.leaseEpoch);\n }\n if (message.sleep !== undefined) {\n SleepSpec.encode(message.sleep, writer.uint32(34).fork()).join();\n }\n if (message.eventWait !== undefined) {\n EventWaitSpec.encode(message.eventWait, writer.uint32(42).fork()).join();\n }\n if (message.signalWait !== undefined) {\n SignalWaitSpec.encode(message.signalWait, writer.uint32(50).fork()).join();\n }\n if (message.nestedRun !== undefined) {\n NestedRunSpec.encode(message.nestedRun, writer.uint32(58).fork()).join();\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): ParkRequest {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseParkRequest();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.runId = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.stepId = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 24) {\n break;\n }\n\n message.leaseEpoch = longToNumber(reader.uint64());\n continue;\n }\n case 4: {\n if (tag !== 34) {\n break;\n }\n\n message.sleep = SleepSpec.decode(reader, reader.uint32());\n continue;\n }\n case 5: {\n if (tag !== 42) {\n break;\n }\n\n message.eventWait = EventWaitSpec.decode(reader, reader.uint32());\n continue;\n }\n case 6: {\n if (tag !== 50) {\n break;\n }\n\n message.signalWait = SignalWaitSpec.decode(reader, reader.uint32());\n continue;\n }\n case 7: {\n if (tag !== 58) {\n break;\n }\n\n message.nestedRun = NestedRunSpec.decode(reader, reader.uint32());\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<ParkRequest>, I>>(base?: I): ParkRequest {\n return ParkRequest.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<ParkRequest>, I>>(object: I): ParkRequest {\n const message = createBaseParkRequest();\n message.runId = object.runId ?? \"\";\n message.stepId = object.stepId ?? \"\";\n message.leaseEpoch = object.leaseEpoch ?? 0;\n message.sleep = (object.sleep !== undefined && object.sleep !== null)\n ? SleepSpec.fromPartial(object.sleep)\n : undefined;\n message.eventWait = (object.eventWait !== undefined && object.eventWait !== null)\n ? EventWaitSpec.fromPartial(object.eventWait)\n : undefined;\n message.signalWait = (object.signalWait !== undefined && object.signalWait !== null)\n ? SignalWaitSpec.fromPartial(object.signalWait)\n : undefined;\n message.nestedRun = (object.nestedRun !== undefined && object.nestedRun !== null)\n ? NestedRunSpec.fromPartial(object.nestedRun)\n : undefined;\n return message;\n },\n};\n\nfunction createBaseSleepSpec(): SleepSpec {\n return { durationSec: 0 };\n}\n\nexport const SleepSpec: MessageFns<SleepSpec> = {\n encode(message: SleepSpec, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.durationSec !== 0) {\n writer.uint32(8).uint32(message.durationSec);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): SleepSpec {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseSleepSpec();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 8) {\n break;\n }\n\n message.durationSec = reader.uint32();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<SleepSpec>, I>>(base?: I): SleepSpec {\n return SleepSpec.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<SleepSpec>, I>>(object: I): SleepSpec {\n const message = createBaseSleepSpec();\n message.durationSec = object.durationSec ?? 0;\n return message;\n },\n};\n\nfunction createBaseEventWaitSpec(): EventWaitSpec {\n return { event: \"\", filterJson: \"\", timeoutSec: 0 };\n}\n\nexport const EventWaitSpec: MessageFns<EventWaitSpec> = {\n encode(message: EventWaitSpec, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.event !== \"\") {\n writer.uint32(10).string(message.event);\n }\n if (message.filterJson !== \"\") {\n writer.uint32(18).string(message.filterJson);\n }\n if (message.timeoutSec !== 0) {\n writer.uint32(24).uint32(message.timeoutSec);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): EventWaitSpec {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseEventWaitSpec();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.event = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.filterJson = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 24) {\n break;\n }\n\n message.timeoutSec = reader.uint32();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<EventWaitSpec>, I>>(base?: I): EventWaitSpec {\n return EventWaitSpec.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<EventWaitSpec>, I>>(object: I): EventWaitSpec {\n const message = createBaseEventWaitSpec();\n message.event = object.event ?? \"\";\n message.filterJson = object.filterJson ?? \"\";\n message.timeoutSec = object.timeoutSec ?? 0;\n return message;\n },\n};\n\nfunction createBaseSignalWaitSpec(): SignalWaitSpec {\n return { signal: \"\", timeoutSec: 0 };\n}\n\nexport const SignalWaitSpec: MessageFns<SignalWaitSpec> = {\n encode(message: SignalWaitSpec, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.signal !== \"\") {\n writer.uint32(10).string(message.signal);\n }\n if (message.timeoutSec !== 0) {\n writer.uint32(16).uint32(message.timeoutSec);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): SignalWaitSpec {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseSignalWaitSpec();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.signal = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 16) {\n break;\n }\n\n message.timeoutSec = reader.uint32();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<SignalWaitSpec>, I>>(base?: I): SignalWaitSpec {\n return SignalWaitSpec.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<SignalWaitSpec>, I>>(object: I): SignalWaitSpec {\n const message = createBaseSignalWaitSpec();\n message.signal = object.signal ?? \"\";\n message.timeoutSec = object.timeoutSec ?? 0;\n return message;\n },\n};\n\nfunction createBaseNestedRunSpec(): NestedRunSpec {\n return { childRunId: \"\" };\n}\n\nexport const NestedRunSpec: MessageFns<NestedRunSpec> = {\n encode(message: NestedRunSpec, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.childRunId !== \"\") {\n writer.uint32(10).string(message.childRunId);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): NestedRunSpec {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseNestedRunSpec();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.childRunId = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<NestedRunSpec>, I>>(base?: I): NestedRunSpec {\n return NestedRunSpec.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<NestedRunSpec>, I>>(object: I): NestedRunSpec {\n const message = createBaseNestedRunSpec();\n message.childRunId = object.childRunId ?? \"\";\n return message;\n },\n};\n\nfunction createBaseCompleteRunRequest(): CompleteRunRequest {\n return { runId: \"\", finalState: Buffer.alloc(0), leaseEpoch: 0, terminalStatus: \"\" };\n}\n\nexport const CompleteRunRequest: MessageFns<CompleteRunRequest> = {\n encode(message: CompleteRunRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.runId !== \"\") {\n writer.uint32(10).string(message.runId);\n }\n if (message.finalState.length !== 0) {\n writer.uint32(18).bytes(message.finalState);\n }\n if (message.leaseEpoch !== 0) {\n writer.uint32(24).uint64(message.leaseEpoch);\n }\n if (message.terminalStatus !== \"\") {\n writer.uint32(34).string(message.terminalStatus);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): CompleteRunRequest {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseCompleteRunRequest();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.runId = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.finalState = Buffer.from(reader.bytes());\n continue;\n }\n case 3: {\n if (tag !== 24) {\n break;\n }\n\n message.leaseEpoch = longToNumber(reader.uint64());\n continue;\n }\n case 4: {\n if (tag !== 34) {\n break;\n }\n\n message.terminalStatus = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<CompleteRunRequest>, I>>(base?: I): CompleteRunRequest {\n return CompleteRunRequest.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<CompleteRunRequest>, I>>(object: I): CompleteRunRequest {\n const message = createBaseCompleteRunRequest();\n message.runId = object.runId ?? \"\";\n message.finalState = object.finalState ?? Buffer.alloc(0);\n message.leaseEpoch = object.leaseEpoch ?? 0;\n message.terminalStatus = object.terminalStatus ?? \"\";\n return message;\n },\n};\n\nfunction createBaseHeartbeatRequest(): HeartbeatRequest {\n return { runId: \"\", instanceId: \"\", leaseEpoch: 0 };\n}\n\nexport const HeartbeatRequest: MessageFns<HeartbeatRequest> = {\n encode(message: HeartbeatRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.runId !== \"\") {\n writer.uint32(10).string(message.runId);\n }\n if (message.instanceId !== \"\") {\n writer.uint32(18).string(message.instanceId);\n }\n if (message.leaseEpoch !== 0) {\n writer.uint32(24).uint64(message.leaseEpoch);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): HeartbeatRequest {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseHeartbeatRequest();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.runId = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.instanceId = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 24) {\n break;\n }\n\n message.leaseEpoch = longToNumber(reader.uint64());\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<HeartbeatRequest>, I>>(base?: I): HeartbeatRequest {\n return HeartbeatRequest.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<HeartbeatRequest>, I>>(object: I): HeartbeatRequest {\n const message = createBaseHeartbeatRequest();\n message.runId = object.runId ?? \"\";\n message.instanceId = object.instanceId ?? \"\";\n message.leaseEpoch = object.leaseEpoch ?? 0;\n return message;\n },\n};\n\n/**\n * Workflows — durable workflow execution service.\n * Caller-side RPCs: Start, Cancel, Signal, Query, Await, Replay.\n * Owner-side RPCs: Subscribe, BeginStep, CompleteStep, FailStep, Park, Heartbeat.\n */\nexport type WorkflowsService = typeof WorkflowsService;\nexport const WorkflowsService = {\n /** Caller-side */\n start: {\n path: \"/servicebridge.v1.Workflows/Start\" as const,\n requestStream: false as const,\n responseStream: false as const,\n requestSerialize: (value: StartRunRequest): Buffer => Buffer.from(StartRunRequest.encode(value).finish()),\n requestDeserialize: (value: Buffer): StartRunRequest => StartRunRequest.decode(value),\n responseSerialize: (value: StartRunResponse): Buffer => Buffer.from(StartRunResponse.encode(value).finish()),\n responseDeserialize: (value: Buffer): StartRunResponse => StartRunResponse.decode(value),\n },\n cancel: {\n path: \"/servicebridge.v1.Workflows/Cancel\" as const,\n requestStream: false as const,\n responseStream: false as const,\n requestSerialize: (value: CancelRunRequest): Buffer => Buffer.from(CancelRunRequest.encode(value).finish()),\n requestDeserialize: (value: Buffer): CancelRunRequest => CancelRunRequest.decode(value),\n responseSerialize: (value: Empty): Buffer => Buffer.from(Empty.encode(value).finish()),\n responseDeserialize: (value: Buffer): Empty => Empty.decode(value),\n },\n signal: {\n path: \"/servicebridge.v1.Workflows/Signal\" as const,\n requestStream: false as const,\n responseStream: false as const,\n requestSerialize: (value: SignalRunRequest): Buffer => Buffer.from(SignalRunRequest.encode(value).finish()),\n requestDeserialize: (value: Buffer): SignalRunRequest => SignalRunRequest.decode(value),\n responseSerialize: (value: Empty): Buffer => Buffer.from(Empty.encode(value).finish()),\n responseDeserialize: (value: Buffer): Empty => Empty.decode(value),\n },\n query: {\n path: \"/servicebridge.v1.Workflows/Query\" as const,\n requestStream: false as const,\n responseStream: false as const,\n requestSerialize: (value: QueryRunRequest): Buffer => Buffer.from(QueryRunRequest.encode(value).finish()),\n requestDeserialize: (value: Buffer): QueryRunRequest => QueryRunRequest.decode(value),\n responseSerialize: (value: QueryRunResponse): Buffer => Buffer.from(QueryRunResponse.encode(value).finish()),\n responseDeserialize: (value: Buffer): QueryRunResponse => QueryRunResponse.decode(value),\n },\n await: {\n path: \"/servicebridge.v1.Workflows/Await\" as const,\n requestStream: false as const,\n responseStream: true as const,\n requestSerialize: (value: AwaitRunRequest): Buffer => Buffer.from(AwaitRunRequest.encode(value).finish()),\n requestDeserialize: (value: Buffer): AwaitRunRequest => AwaitRunRequest.decode(value),\n responseSerialize: (value: RunStatusUpdate): Buffer => Buffer.from(RunStatusUpdate.encode(value).finish()),\n responseDeserialize: (value: Buffer): RunStatusUpdate => RunStatusUpdate.decode(value),\n },\n replay: {\n path: \"/servicebridge.v1.Workflows/Replay\" as const,\n requestStream: false as const,\n responseStream: false as const,\n requestSerialize: (value: ReplayRunRequest): Buffer => Buffer.from(ReplayRunRequest.encode(value).finish()),\n requestDeserialize: (value: Buffer): ReplayRunRequest => ReplayRunRequest.decode(value),\n responseSerialize: (value: ReplayRunResponse): Buffer => Buffer.from(ReplayRunResponse.encode(value).finish()),\n responseDeserialize: (value: Buffer): ReplayRunResponse => ReplayRunResponse.decode(value),\n },\n /** Owner-side */\n subscribe: {\n path: \"/servicebridge.v1.Workflows/Subscribe\" as const,\n requestStream: false as const,\n responseStream: true as const,\n requestSerialize: (value: SubscribeRequest): Buffer => Buffer.from(SubscribeRequest.encode(value).finish()),\n requestDeserialize: (value: Buffer): SubscribeRequest => SubscribeRequest.decode(value),\n responseSerialize: (value: RunAssignment): Buffer => Buffer.from(RunAssignment.encode(value).finish()),\n responseDeserialize: (value: Buffer): RunAssignment => RunAssignment.decode(value),\n },\n beginStep: {\n path: \"/servicebridge.v1.Workflows/BeginStep\" as const,\n requestStream: false as const,\n responseStream: false as const,\n requestSerialize: (value: BeginStepRequest): Buffer => Buffer.from(BeginStepRequest.encode(value).finish()),\n requestDeserialize: (value: Buffer): BeginStepRequest => BeginStepRequest.decode(value),\n responseSerialize: (value: BeginStepResponse): Buffer => Buffer.from(BeginStepResponse.encode(value).finish()),\n responseDeserialize: (value: Buffer): BeginStepResponse => BeginStepResponse.decode(value),\n },\n completeStep: {\n path: \"/servicebridge.v1.Workflows/CompleteStep\" as const,\n requestStream: false as const,\n responseStream: false as const,\n requestSerialize: (value: CompleteStepRequest): Buffer => Buffer.from(CompleteStepRequest.encode(value).finish()),\n requestDeserialize: (value: Buffer): CompleteStepRequest => CompleteStepRequest.decode(value),\n responseSerialize: (value: Empty): Buffer => Buffer.from(Empty.encode(value).finish()),\n responseDeserialize: (value: Buffer): Empty => Empty.decode(value),\n },\n completeRun: {\n path: \"/servicebridge.v1.Workflows/CompleteRun\" as const,\n requestStream: false as const,\n responseStream: false as const,\n requestSerialize: (value: CompleteRunRequest): Buffer => Buffer.from(CompleteRunRequest.encode(value).finish()),\n requestDeserialize: (value: Buffer): CompleteRunRequest => CompleteRunRequest.decode(value),\n responseSerialize: (value: Empty): Buffer => Buffer.from(Empty.encode(value).finish()),\n responseDeserialize: (value: Buffer): Empty => Empty.decode(value),\n },\n failStep: {\n path: \"/servicebridge.v1.Workflows/FailStep\" as const,\n requestStream: false as const,\n responseStream: false as const,\n requestSerialize: (value: FailStepRequest): Buffer => Buffer.from(FailStepRequest.encode(value).finish()),\n requestDeserialize: (value: Buffer): FailStepRequest => FailStepRequest.decode(value),\n responseSerialize: (value: FailStepResponse): Buffer => Buffer.from(FailStepResponse.encode(value).finish()),\n responseDeserialize: (value: Buffer): FailStepResponse => FailStepResponse.decode(value),\n },\n park: {\n path: \"/servicebridge.v1.Workflows/Park\" as const,\n requestStream: false as const,\n responseStream: false as const,\n requestSerialize: (value: ParkRequest): Buffer => Buffer.from(ParkRequest.encode(value).finish()),\n requestDeserialize: (value: Buffer): ParkRequest => ParkRequest.decode(value),\n responseSerialize: (value: Empty): Buffer => Buffer.from(Empty.encode(value).finish()),\n responseDeserialize: (value: Buffer): Empty => Empty.decode(value),\n },\n heartbeat: {\n path: \"/servicebridge.v1.Workflows/Heartbeat\" as const,\n requestStream: false as const,\n responseStream: false as const,\n requestSerialize: (value: HeartbeatRequest): Buffer => Buffer.from(HeartbeatRequest.encode(value).finish()),\n requestDeserialize: (value: Buffer): HeartbeatRequest => HeartbeatRequest.decode(value),\n responseSerialize: (value: Empty): Buffer => Buffer.from(Empty.encode(value).finish()),\n responseDeserialize: (value: Buffer): Empty => Empty.decode(value),\n },\n} as const;\n\nexport interface WorkflowsServer extends UntypedServiceImplementation {\n /** Caller-side */\n start: handleUnaryCall<StartRunRequest, StartRunResponse>;\n cancel: handleUnaryCall<CancelRunRequest, Empty>;\n signal: handleUnaryCall<SignalRunRequest, Empty>;\n query: handleUnaryCall<QueryRunRequest, QueryRunResponse>;\n await: handleServerStreamingCall<AwaitRunRequest, RunStatusUpdate>;\n replay: handleUnaryCall<ReplayRunRequest, ReplayRunResponse>;\n /** Owner-side */\n subscribe: handleServerStreamingCall<SubscribeRequest, RunAssignment>;\n beginStep: handleUnaryCall<BeginStepRequest, BeginStepResponse>;\n completeStep: handleUnaryCall<CompleteStepRequest, Empty>;\n completeRun: handleUnaryCall<CompleteRunRequest, Empty>;\n failStep: handleUnaryCall<FailStepRequest, FailStepResponse>;\n park: handleUnaryCall<ParkRequest, Empty>;\n heartbeat: handleUnaryCall<HeartbeatRequest, Empty>;\n}\n\nexport interface WorkflowsClient extends Client {\n /** Caller-side */\n start(\n request: StartRunRequest,\n callback: (error: ServiceError | null, response: StartRunResponse) => void,\n ): ClientUnaryCall;\n start(\n request: StartRunRequest,\n metadata: Metadata,\n callback: (error: ServiceError | null, response: StartRunResponse) => void,\n ): ClientUnaryCall;\n start(\n request: StartRunRequest,\n metadata: Metadata,\n options: Partial<CallOptions>,\n callback: (error: ServiceError | null, response: StartRunResponse) => void,\n ): ClientUnaryCall;\n cancel(request: CancelRunRequest, callback: (error: ServiceError | null, response: Empty) => void): ClientUnaryCall;\n cancel(\n request: CancelRunRequest,\n metadata: Metadata,\n callback: (error: ServiceError | null, response: Empty) => void,\n ): ClientUnaryCall;\n cancel(\n request: CancelRunRequest,\n metadata: Metadata,\n options: Partial<CallOptions>,\n callback: (error: ServiceError | null, response: Empty) => void,\n ): ClientUnaryCall;\n signal(request: SignalRunRequest, callback: (error: ServiceError | null, response: Empty) => void): ClientUnaryCall;\n signal(\n request: SignalRunRequest,\n metadata: Metadata,\n callback: (error: ServiceError | null, response: Empty) => void,\n ): ClientUnaryCall;\n signal(\n request: SignalRunRequest,\n metadata: Metadata,\n options: Partial<CallOptions>,\n callback: (error: ServiceError | null, response: Empty) => void,\n ): ClientUnaryCall;\n query(\n request: QueryRunRequest,\n callback: (error: ServiceError | null, response: QueryRunResponse) => void,\n ): ClientUnaryCall;\n query(\n request: QueryRunRequest,\n metadata: Metadata,\n callback: (error: ServiceError | null, response: QueryRunResponse) => void,\n ): ClientUnaryCall;\n query(\n request: QueryRunRequest,\n metadata: Metadata,\n options: Partial<CallOptions>,\n callback: (error: ServiceError | null, response: QueryRunResponse) => void,\n ): ClientUnaryCall;\n await(request: AwaitRunRequest, options?: Partial<CallOptions>): ClientReadableStream<RunStatusUpdate>;\n await(\n request: AwaitRunRequest,\n metadata?: Metadata,\n options?: Partial<CallOptions>,\n ): ClientReadableStream<RunStatusUpdate>;\n replay(\n request: ReplayRunRequest,\n callback: (error: ServiceError | null, response: ReplayRunResponse) => void,\n ): ClientUnaryCall;\n replay(\n request: ReplayRunRequest,\n metadata: Metadata,\n callback: (error: ServiceError | null, response: ReplayRunResponse) => void,\n ): ClientUnaryCall;\n replay(\n request: ReplayRunRequest,\n metadata: Metadata,\n options: Partial<CallOptions>,\n callback: (error: ServiceError | null, response: ReplayRunResponse) => void,\n ): ClientUnaryCall;\n /** Owner-side */\n subscribe(request: SubscribeRequest, options?: Partial<CallOptions>): ClientReadableStream<RunAssignment>;\n subscribe(\n request: SubscribeRequest,\n metadata?: Metadata,\n options?: Partial<CallOptions>,\n ): ClientReadableStream<RunAssignment>;\n beginStep(\n request: BeginStepRequest,\n callback: (error: ServiceError | null, response: BeginStepResponse) => void,\n ): ClientUnaryCall;\n beginStep(\n request: BeginStepRequest,\n metadata: Metadata,\n callback: (error: ServiceError | null, response: BeginStepResponse) => void,\n ): ClientUnaryCall;\n beginStep(\n request: BeginStepRequest,\n metadata: Metadata,\n options: Partial<CallOptions>,\n callback: (error: ServiceError | null, response: BeginStepResponse) => void,\n ): ClientUnaryCall;\n completeStep(\n request: CompleteStepRequest,\n callback: (error: ServiceError | null, response: Empty) => void,\n ): ClientUnaryCall;\n completeStep(\n request: CompleteStepRequest,\n metadata: Metadata,\n callback: (error: ServiceError | null, response: Empty) => void,\n ): ClientUnaryCall;\n completeStep(\n request: CompleteStepRequest,\n metadata: Metadata,\n options: Partial<CallOptions>,\n callback: (error: ServiceError | null, response: Empty) => void,\n ): ClientUnaryCall;\n completeRun(\n request: CompleteRunRequest,\n callback: (error: ServiceError | null, response: Empty) => void,\n ): ClientUnaryCall;\n completeRun(\n request: CompleteRunRequest,\n metadata: Metadata,\n callback: (error: ServiceError | null, response: Empty) => void,\n ): ClientUnaryCall;\n completeRun(\n request: CompleteRunRequest,\n metadata: Metadata,\n options: Partial<CallOptions>,\n callback: (error: ServiceError | null, response: Empty) => void,\n ): ClientUnaryCall;\n failStep(\n request: FailStepRequest,\n callback: (error: ServiceError | null, response: FailStepResponse) => void,\n ): ClientUnaryCall;\n failStep(\n request: FailStepRequest,\n metadata: Metadata,\n callback: (error: ServiceError | null, response: FailStepResponse) => void,\n ): ClientUnaryCall;\n failStep(\n request: FailStepRequest,\n metadata: Metadata,\n options: Partial<CallOptions>,\n callback: (error: ServiceError | null, response: FailStepResponse) => void,\n ): ClientUnaryCall;\n park(request: ParkRequest, callback: (error: ServiceError | null, response: Empty) => void): ClientUnaryCall;\n park(\n request: ParkRequest,\n metadata: Metadata,\n callback: (error: ServiceError | null, response: Empty) => void,\n ): ClientUnaryCall;\n park(\n request: ParkRequest,\n metadata: Metadata,\n options: Partial<CallOptions>,\n callback: (error: ServiceError | null, response: Empty) => void,\n ): ClientUnaryCall;\n heartbeat(\n request: HeartbeatRequest,\n callback: (error: ServiceError | null, response: Empty) => void,\n ): ClientUnaryCall;\n heartbeat(\n request: HeartbeatRequest,\n metadata: Metadata,\n callback: (error: ServiceError | null, response: Empty) => void,\n ): ClientUnaryCall;\n heartbeat(\n request: HeartbeatRequest,\n metadata: Metadata,\n options: Partial<CallOptions>,\n callback: (error: ServiceError | null, response: Empty) => void,\n ): ClientUnaryCall;\n}\n\nexport const WorkflowsClient = makeGenericClientConstructor(\n WorkflowsService,\n \"servicebridge.v1.Workflows\",\n) as unknown as {\n new (address: string, credentials: ChannelCredentials, options?: Partial<ClientOptions>): WorkflowsClient;\n service: typeof WorkflowsService;\n serviceName: string;\n};\n\ntype Builtin = Date | Function | Uint8Array | string | number | boolean | undefined;\n\ntype DeepPartial<T> = T extends Builtin ? T\n : T extends globalThis.Array<infer U> ? globalThis.Array<DeepPartial<U>>\n : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>>\n : T extends {} ? { [K in keyof T]?: DeepPartial<T[K]> }\n : Partial<T>;\n\ntype KeysOfUnion<T> = T extends T ? keyof T : never;\ntype Exact<P, I extends P> = P extends Builtin ? P\n : P & { [K in keyof P]: Exact<P[K], I[K]> } & { [K in Exclude<keyof I, KeysOfUnion<P>>]: never };\n\nfunction longToNumber(int64: { toString(): string }): number {\n const num = globalThis.Number(int64.toString());\n if (num > globalThis.Number.MAX_SAFE_INTEGER) {\n throw new globalThis.Error(\"Value is larger than Number.MAX_SAFE_INTEGER\");\n }\n if (num < globalThis.Number.MIN_SAFE_INTEGER) {\n throw new globalThis.Error(\"Value is smaller than Number.MIN_SAFE_INTEGER\");\n }\n return num;\n}\n\ninterface MessageFns<T> {\n encode(message: T, writer?: BinaryWriter): BinaryWriter;\n decode(input: BinaryReader | Uint8Array, length?: number): T;\n create<I extends Exact<DeepPartial<T>, I>>(base?: I): T;\n fromPartial<I extends Exact<DeepPartial<T>, I>>(object: I): T;\n}\n","// Code generated by protoc-gen-ts_proto. DO NOT EDIT.\n// versions:\n// protoc-gen-ts_proto v2.11.8\n// protoc unknown\n// source: google/protobuf/empty.proto\n\n/* eslint-disable */\nimport { BinaryReader, BinaryWriter } from \"@bufbuild/protobuf/wire\";\n\n/**\n * A generic empty message that you can re-use to avoid defining duplicated\n * empty messages in your APIs. A typical example is to use it as the request\n * or the response type of an API method. For instance:\n *\n * service Foo {\n * rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);\n * }\n */\nexport interface Empty {\n}\n\nfunction createBaseEmpty(): Empty {\n return {};\n}\n\nexport const Empty: MessageFns<Empty> = {\n encode(_: Empty, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): Empty {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseEmpty();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<Empty>, I>>(base?: I): Empty {\n return Empty.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<Empty>, I>>(_: I): Empty {\n const message = createBaseEmpty();\n return message;\n },\n};\n\ntype Builtin = Date | Function | Uint8Array | string | number | boolean | undefined;\n\ntype DeepPartial<T> = T extends Builtin ? T\n : T extends globalThis.Array<infer U> ? globalThis.Array<DeepPartial<U>>\n : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>>\n : T extends {} ? { [K in keyof T]?: DeepPartial<T[K]> }\n : Partial<T>;\n\ntype KeysOfUnion<T> = T extends T ? keyof T : never;\ntype Exact<P, I extends P> = P extends Builtin ? P\n : P & { [K in keyof P]: Exact<P[K], I[K]> } & { [K in Exclude<keyof I, KeysOfUnion<P>>]: never };\n\ninterface MessageFns<T> {\n encode(message: T, writer?: BinaryWriter): BinaryWriter;\n decode(input: BinaryReader | Uint8Array, length?: number): T;\n create<I extends Exact<DeepPartial<T>, I>>(base?: I): T;\n fromPartial<I extends Exact<DeepPartial<T>, I>>(object: I): T;\n}\n","/**\n * Route — canonical HTTP route entry collected by an integration (Express /\n * Fastify / Hono) and published into the SB registry as METHOD_TYPE_HTTP.\n *\n * @internal — потребляется только интеграциями `servicebridge/{express,\n * fastify,hono}` через `ServiceBridge.routes`. Прикладной код использует\n * subpath-API, см. ../../userDocs/integrations.md.\n */\nexport interface Route {\n\t/** Uppercase HTTP method: \"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\", etc. */\n\tmethod: string;\n\t/** Raw framework pattern. SDK не нормализует — косметика на UI Service Map. */\n\tpattern: string;\n\t/** Source framework, for diagnostics and (later) Service Map UI badges. */\n\tsource: \"express\" | \"fastify\" | \"hono\";\n}\n\n/**\n * Хук, передаваемый коллектору при конструировании. Реализуется `ServiceBridge`:\n * `setEndpoint` синхронно обновляет `Registry._httpEndpoint`; `triggerRestart`\n * рестартует Registry-watch стрим, если SDK уже запущен (no-op до `start()`).\n *\n * @internal\n */\nexport interface RouteSink {\n\tsetEndpoint(endpoint: string): void;\n\ttriggerRestart(): void;\n}\n\n/**\n * RouteCollector аккумулирует роуты по ключу `${method} ${pattern}` (дедуп) и\n * управляет HTTP-endpoint жизненным циклом инстанса.\n *\n * Один публичный метод `publishHttp({host, port})`:\n * 1. Записывает endpoint в Registry (`sink.setEndpoint`).\n * 2. Триггерит `sink.triggerRestart()` — рестарт Registry-watch стрима.\n * Если SDK ещё не стартовал, `triggerRestart` — no-op; endpoint просто\n * оседает и попадёт в первый `RegisterRequest`.\n *\n * @internal\n */\nexport class RouteCollector {\n\tprivate readonly _routes = new Map<string, Route>();\n\tprivate readonly _sink: RouteSink;\n\n\tconstructor(sink: RouteSink) {\n\t\tthis._sink = sink;\n\t}\n\n\t/** Добавляет роут. Дедуп по `${method} ${pattern}`. */\n\tadd(route: Route): void {\n\t\tconst key = `${route.method} ${route.pattern}`;\n\t\tthis._routes.set(key, route);\n\t}\n\n\t/** Сколько роутов уже собрано (для диагностики тестов). */\n\tsize(): number {\n\t\treturn this._routes.size;\n\t}\n\n\t/**\n\t * Записывает endpoint в Registry и триггерит `triggerRestart` callback.\n\t * Безопасен до `sb.start()` — `triggerRestart` тогда no-op.\n\t */\n\tpublishHttp(endpoint: { host: string; port: number }): void {\n\t\tthis._sink.setEndpoint(`${endpoint.host}:${endpoint.port}`);\n\t\tthis._sink.triggerRestart();\n\t}\n\n\t/** Snapshot собранных роутов в порядке добавления (insertion order Map). */\n\tsnapshot(): readonly Route[] {\n\t\treturn Array.from(this._routes.values());\n\t}\n}\n","import { RouteCollector } from \"../http/route\";\nimport type {\n\tIncomingMethod as PbIncomingMethod,\n\tOutgoingDep as PbOutgoingDep,\n\tPublishedEvent as PbPublishedEvent,\n\tRegisterRequest,\n} from \"../pb/servicebridge/v1/registry\";\nimport { MethodType } from \"../pb/servicebridge/v1/registry\";\nimport type {\n\tDispatchPort,\n\tStreamItem,\n\tUnaryResult,\n} from \"../rpc/dispatch-port\";\nimport { computeContractHash } from \"../serde/contract-hash\";\nimport type { SchemaPair, SchemaSpec } from \"../serde/serializer\";\nimport type { CaptureMode } from \"../telemetry/payload-capture\";\n\nexport type { MethodDescriptor } from \"../pb/servicebridge/v1/registry\";\nexport { MethodType } from \"../pb/servicebridge/v1/registry\";\n\n// RpcHandlerOpts accepts a SchemaSpec (.proto file + message names) for both\n// input and output. `schema` is required — every RPC handler must declare a\n// schema so the dispatcher can decode payloads and the LB can filter by\n// contract hash (ADR 0005 / 0012). Declaration-only registry tests use the\n// internal `_declareForTests()` path.\nexport interface RpcHandlerOpts {\n\tschema: SchemaSpec;\n\t// captureMode — per-handler override for payload capture (\"all\"|\"errors\"|\n\t// \"none\"). May only NARROW the runtime-pushed effective mode (privacy\n\t// ordering none < errors < all), never widen it.\n\tcaptureMode?: CaptureMode;\n}\n\n// WorkflowHandlerOpts — input-only schema. Workflow output never exists at the\n// transport level: каждый step возвращает обновлённый state (см.\n// `userDocs/workflows.md`). Финального output у workflow как сущности нет.\nexport interface WorkflowHandlerOpts {\n\tinput?: Record<string, unknown>;\n}\n\nexport interface ServiceDeps {\n\trpc?: string[];\n\tworkflows?: string[];\n\thttp?: string[];\n}\n\n// RpcHandlerFn is the function shape accepted by Handle.rpc().\nexport type RpcHandlerFn<Req = unknown, Res = unknown> = (\n\treq: Req,\n) => Promise<Res> | Res;\n\n// RpcStreamHandlerFn is the function shape accepted by Handle.stream().\n// Implementations return an AsyncIterable / async generator that yields one\n// chunk at a time. Termination (return) ends the stream; thrown errors are\n// caught by the CallServer and mapped to the final StreamChunk.error_code.\nexport type RpcStreamHandlerFn<Req = unknown, Chunk = unknown> = (\n\treq: Req,\n) => AsyncIterable<Chunk>;\n\ninterface HandlerEntry {\n\ttype: MethodType;\n\tname: string;\n\tinputSchemaJson: Buffer | null;\n\toutputSchemaJson: Buffer | null;\n\tfn: unknown;\n\tstreaming?: boolean;\n\tschemaPair?: SchemaPair;\n\t// contractHashOverride — used by workflow entries (ADR-W-002): the graph\n\t// fingerprint is computed by WorkflowDomain over the canonical JSON, NOT\n\t// derived from a SchemaPair. When present, incomingMethods() emits it\n\t// verbatim into IncomingMethod.contract_hash.\n\tcontractHashOverride?: string;\n\tcaptureMode?: CaptureMode;\n}\n\n// PublishedEntry stores a published event declaration plus its async-loaded\n// schema. `schemaPair` and `contractHash` populate after buildSchemaPair\n// resolves in finalize(); they remain undefined / \"\" forever when the event\n// was declared without a spec.\ninterface PublishedEntry {\n\tname: string;\n\tinputSchemaJson: Buffer | null;\n\tcontractHash: string;\n\tschemaPair?: SchemaPair;\n\t// Reference identity for \"same spec\" no-op detection on repeated define().\n\t// Two define(name, spec) calls with the same SchemaSpec object are no-op;\n\t// distinct SchemaSpec objects throw. Schema equivalence by structure is\n\t// out of scope — users pass the same `import`ed spec or get the error.\n\tspec?: SchemaSpec;\n}\n\ninterface OutgoingEntry {\n\tserviceName: string;\n\tmethodName: string;\n\ttype: MethodType;\n}\n\nfunction schemaToBuffer(schema?: Record<string, unknown>): Buffer | null {\n\tif (!schema) return null;\n\treturn Buffer.from(JSON.stringify(schema));\n}\n\n// Handle — internal storage for incoming handler entries AND published-event\n// declarations. Accessed only through domain classes (RpcDomain, EventDomain,\n// WorkflowDomain, JobDomain).\n// @internal — см. ./README.md\nexport class Handle {\n\treadonly _entries: HandlerEntry[] = [];\n\t// Published events declared via sb.event.define. Symmetric to _entries —\n\t// schema loading is async, finalized() must await before serialization.\n\treadonly _published: PublishedEntry[] = [];\n\n\t// Pending registrations awaiting their async SchemaPair to load. Covers\n\t// rpc / stream handlers AND publishEvent declarations.\n\t// finalize() resolves all of them before incomingMethods() /\n\t// publishedEvents() are called.\n\tprivate pending: Promise<void>[] = [];\n\n\trpc<Req = unknown, Res = unknown>(\n\t\tname: string,\n\t\tfn: RpcHandlerFn<Req, Res>,\n\t\topts: RpcHandlerOpts,\n\t): void {\n\t\tthis.registerRpc(name, fn, false, opts);\n\t}\n\n\t// stream registers a server-side streaming RPC. The handler is an async\n\t// generator (or any AsyncIterable). Each yielded value is encoded as a\n\t// StreamChunk and pushed to the caller. Thrown errors terminate the stream\n\t// with a final chunk carrying error_code/error_message.\n\tstream<Req = unknown, Chunk = unknown>(\n\t\tname: string,\n\t\tfn: RpcStreamHandlerFn<Req, Chunk>,\n\t\topts: RpcHandlerOpts,\n\t): void {\n\t\tthis.registerRpc(name, fn, true, opts);\n\t}\n\n\t// _declareForTests registers an RPC entry without a schema. Tests use this\n\t// to assemble Handle / Registry fixtures that exercise registration paths\n\t// without loading real .proto files. Production code MUST go through `rpc`\n\t// or `stream` with an explicit `schema`.\n\t//\n\t// @internal — см. ./README.md\n\t_declareForTests(name: string, streaming = false): void {\n\t\tthis._entries.push({\n\t\t\ttype: MethodType.METHOD_TYPE_RPC,\n\t\t\tname,\n\t\t\tinputSchemaJson: null,\n\t\t\toutputSchemaJson: null,\n\t\t\tfn: () => undefined,\n\t\t\tstreaming,\n\t\t});\n\t}\n\n\tprivate registerRpc(\n\t\tname: string,\n\t\tfn: unknown,\n\t\tstreaming: boolean,\n\t\topts: RpcHandlerOpts,\n\t): void {\n\t\tconst entry: HandlerEntry = {\n\t\t\ttype: MethodType.METHOD_TYPE_RPC,\n\t\t\tname,\n\t\t\tinputSchemaJson: null,\n\t\t\toutputSchemaJson: null,\n\t\t\tfn,\n\t\t\tstreaming,\n\t\t\tcaptureMode: opts.captureMode,\n\t\t};\n\t\tthis._entries.push(entry);\n\n\t\t// For ProtoFileSpec without explicit input/output, propagate the method\n\t\t// name so buildSchemaPair can look it up in the .proto service block.\n\t\tconst spec: SchemaSpec =\n\t\t\t\"protoFile\" in opts.schema && !opts.schema.method\n\t\t\t\t? { ...opts.schema, method: name }\n\t\t\t\t: opts.schema;\n\t\tconst load = import(\"../serde/serializer\").then(({ buildSchemaPair }) =>\n\t\t\tbuildSchemaPair(spec).then((pair) => {\n\t\t\t\tentry.schemaPair = pair;\n\t\t\t\tentry.inputSchemaJson = Buffer.from(\n\t\t\t\t\tJSON.stringify(pair.input.toJsonSchema()),\n\t\t\t\t);\n\t\t\t\tentry.outputSchemaJson = Buffer.from(\n\t\t\t\t\tJSON.stringify(pair.output.toJsonSchema()),\n\t\t\t\t);\n\t\t\t}),\n\t\t);\n\t\tthis.pending.push(load);\n\t}\n\n\t// publishEvent declares a published event (publisher-side). `spec` is the\n\t// Protobuf schema source — either a .proto file or a .schema.json file with\n\t// explicit fieldNumber per property. Symmetric to rpc(): the SchemaPair is\n\t// loaded asynchronously and finalize() awaits it before\n\t// publishedEvents() reflects the contract hash.\n\t//\n\t// Re-declaration with the same SchemaSpec object is no-op. Re-declaration\n\t// with a different SchemaSpec throws — there must be one canonical schema\n\t// per (process, event-name).\n\tpublishEvent(name: string, spec?: SchemaSpec): void {\n\t\tconst existing = this._published.find((p) => p.name === name);\n\t\tif (existing) {\n\t\t\tif (existing.spec === spec) return; // idempotent re-define with same spec\n\t\t\tif (existing.spec === undefined && spec === undefined) return;\n\t\t\tthrow new Error(\n\t\t\t\t`event.define: event \"${name}\" already declared with a different schema spec`,\n\t\t\t);\n\t\t}\n\n\t\tconst entry: PublishedEntry = {\n\t\t\tname,\n\t\t\tinputSchemaJson: null,\n\t\t\tcontractHash: \"\",\n\t\t\tspec,\n\t\t};\n\t\tthis._published.push(entry);\n\n\t\tif (!spec) return; // schema-less event — registered name only\n\n\t\t// For ProtoFileSpec without explicit input/output, propagate the event\n\t\t// name so buildSchemaPair can look it up in the .proto service block.\n\t\tconst resolvedSpec: SchemaSpec =\n\t\t\t\"protoFile\" in spec && !spec.method ? { ...spec, method: name } : spec;\n\n\t\tconst load = Promise.all([\n\t\t\timport(\"../serde/serializer\"),\n\t\t\timport(\"../serde/contract-hash\"),\n\t\t]).then(async ([{ buildSchemaPair }, { computeContractHash }]) => {\n\t\t\tconst pair = await buildSchemaPair(resolvedSpec);\n\t\t\tentry.schemaPair = pair;\n\t\t\tentry.inputSchemaJson = Buffer.from(\n\t\t\t\tJSON.stringify(pair.input.toJsonSchema()),\n\t\t\t);\n\t\t\tentry.contractHash = computeContractHash(pair);\n\t\t});\n\t\tthis.pending.push(load);\n\t}\n\n\t// getPublishedEvent — schema lookup for Publisher / Subscriber. Returns the\n\t// loaded SchemaPair plus contractHash, or undefined when the event was not\n\t// declared (or declared without a spec, or finalize() not yet called).\n\tgetPublishedEvent(\n\t\tname: string,\n\t): { contractHash: string; pair: SchemaPair } | undefined {\n\t\tconst entry = this._published.find((e) => e.name === name);\n\t\tif (!entry || !entry.schemaPair) return undefined;\n\t\treturn { contractHash: entry.contractHash, pair: entry.schemaPair };\n\t}\n\n\t// _declarePublishedEventForTests — registers a published event without a\n\t// real schema spec. Bypasses async load; tests use this to exercise\n\t// registration paths without .proto files. Production code MUST go through\n\t// publishEvent(name, spec) with an explicit schema.\n\t// @internal\n\t_declarePublishedEventForTests(name: string): void {\n\t\tif (this._published.find((p) => p.name === name)) return;\n\t\tthis._published.push({\n\t\t\tname,\n\t\t\tinputSchemaJson: null,\n\t\t\tcontractHash: \"\",\n\t\t});\n\t}\n\n\t// event registers a durable event subscription. Pattern может быть точным\n\t// именем или AMQP wildcard. Схема payload-а живёт у publisher'а (event.define)\n\t// и используется и для encode, и для decode — handler-side schema смысла не\n\t// имеет (один pattern матчит много событий с разными схемами).\n\tevent(name: string, fn: unknown): void {\n\t\tthis._entries.push({\n\t\t\ttype: MethodType.METHOD_TYPE_EVENT,\n\t\t\tname,\n\t\t\tinputSchemaJson: null,\n\t\t\toutputSchemaJson: null,\n\t\t\tfn,\n\t\t});\n\t}\n\n\tworkflow(\n\t\tname: string,\n\t\tsteps: unknown,\n\t\topts?: WorkflowHandlerOpts,\n\t\t// Workflow-graph payload (ADR-W-002). When present, `graphJson`\n\t\t// overrides the schema-derived input_schema_json (the graph IS the\n\t\t// declaration), and `contractHash` is the canonical-graph fingerprint\n\t\t// that travels as IncomingMethod.contract_hash.\n\t\tgraphJson?: Buffer,\n\t\tcontractHash?: string,\n\t): void {\n\t\tthis._entries.push({\n\t\t\ttype: MethodType.METHOD_TYPE_WORKFLOW,\n\t\t\tname,\n\t\t\tinputSchemaJson: graphJson ?? schemaToBuffer(opts?.input),\n\t\t\toutputSchemaJson: null,\n\t\t\tfn: steps,\n\t\t\tcontractHashOverride: contractHash,\n\t\t});\n\t}\n\n\t// job registers a scheduled job. `contractHash` is the SDK-computed\n\t// SHA-256 of the canonical-spec JSON; `specJson` is the canonical spec\n\t// itself (CanonicalJobSpec, see runtime/internal/jobs/canonical.go).\n\t// fn is the handler — it is stored locally and not sent over the wire.\n\t// @internal — used by JobDomain.handle.\n\tjob(name: string, contractHash: string, specJson: string, fn: unknown): void {\n\t\tthis._entries.push({\n\t\t\ttype: MethodType.METHOD_TYPE_JOB,\n\t\t\tname,\n\t\t\tinputSchemaJson: Buffer.from(specJson, \"utf8\"),\n\t\t\toutputSchemaJson: null,\n\t\t\tfn,\n\t\t\tcontractHashOverride: contractHash,\n\t\t});\n\t}\n\n\t// finalize resolves any pending schema loads. Called by ServiceBridge.start()\n\t// before buildRegisterRequest() so IncomingMethod.input_schema_json reflects\n\t// the real protobuf descriptors.\n\tasync finalize(): Promise<void> {\n\t\tif (this.pending.length === 0) return;\n\t\tconst pending = this.pending;\n\t\tthis.pending = [];\n\t\tawait Promise.all(pending);\n\t}\n\n\t// incomingMethods emits ВСЕ типы кроме EVENT. Event subscriptions едут только\n\t// через RegisterRequest.event_subscriptions — единственный канал для них.\n\t// См. ADR 0006 + registry README.\n\tincomingMethods(): PbIncomingMethod[] {\n\t\treturn this._entries\n\t\t\t.filter((e) => e.type !== MethodType.METHOD_TYPE_EVENT)\n\t\t\t.map((e) => ({\n\t\t\t\ttype: e.type,\n\t\t\t\tname: e.name,\n\t\t\t\tinputSchemaJson: e.inputSchemaJson ?? Buffer.alloc(0),\n\t\t\t\toutputSchemaJson: e.outputSchemaJson ?? Buffer.alloc(0),\n\t\t\t\tstreaming: e.streaming ?? false,\n\t\t\t\t// SDK computes the contract hash; runtime stores opaque (ADR 0005).\n\t\t\t\t// Workflow entries carry a graph fingerprint (ADR-W-002) via\n\t\t\t\t// contractHashOverride. Empty when neither source is set.\n\t\t\t\tcontractHash: e.contractHashOverride\n\t\t\t\t\t? e.contractHashOverride\n\t\t\t\t\t: e.schemaPair\n\t\t\t\t\t\t? computeContractHash(e.schemaPair)\n\t\t\t\t\t\t: \"\",\n\t\t\t}));\n\t}\n\n\t// publishedEvents emits PublishedEvent rows for RegisterRequest. ADR-0013:\n\t// publishers carry contract_hash so the runtime keep-history per schema\n\t// version (different hashes coexist for the same name) works correctly.\n\tpublishedEvents(): PbPublishedEvent[] {\n\t\treturn this._published.map((e) => ({\n\t\t\tname: e.name,\n\t\t\tschemaJson: e.inputSchemaJson ?? Buffer.alloc(0),\n\t\t\tcontractHash: e.contractHash,\n\t\t}));\n\t}\n\n\t// asDispatchPort exposes a DispatchPort over the registered handlers.\n\t// CallServer uses this instead of reaching into private _entries.\n\tasDispatchPort(): DispatchPort {\n\t\tconst findRpc = (method: string): HandlerEntry | undefined =>\n\t\t\tthis._entries.find(\n\t\t\t\t(e) => e.type === MethodType.METHOD_TYPE_RPC && e.name === method,\n\t\t\t);\n\n\t\tconst handle = this;\n\n\t\treturn {\n\t\t\tdispatchUnary: async (\n\t\t\t\tmethod: string,\n\t\t\t\tpayload: Uint8Array,\n\t\t\t): Promise<UnaryResult> => {\n\t\t\t\tconst entry = findRpc(method);\n\t\t\t\tif (!entry) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tpayload: new Uint8Array(0),\n\t\t\t\t\t\terrorCode: \"NOT_FOUND\",\n\t\t\t\t\t\terrorMessage: `no RPC handler for method ${method}`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (entry.streaming) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tpayload: new Uint8Array(0),\n\t\t\t\t\t\terrorCode: \"FAILED_PRECONDITION\",\n\t\t\t\t\t\terrorMessage: `method ${method} is streaming — call via Stream`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (!entry.schemaPair) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tpayload: new Uint8Array(0),\n\t\t\t\t\t\terrorCode: \"INTERNAL\",\n\t\t\t\t\t\terrorMessage: `schema not loaded for method ${method}`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tlet request: unknown;\n\t\t\t\ttry {\n\t\t\t\t\trequest = entry.schemaPair.input.decode(payload);\n\t\t\t\t} catch (err) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tpayload: new Uint8Array(0),\n\t\t\t\t\t\terrorCode: \"INVALID_ARGUMENT\",\n\t\t\t\t\t\terrorMessage: `decode: ${(err as Error).message}`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tconst fn = entry.fn as RpcHandlerFn;\n\t\t\t\t\tconst result = await fn(request);\n\t\t\t\t\tconst bytes = entry.schemaPair.output.encode(\n\t\t\t\t\t\tresult as Record<string, unknown>,\n\t\t\t\t\t);\n\t\t\t\t\treturn { payload: bytes };\n\t\t\t\t} catch (err) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tpayload: new Uint8Array(0),\n\t\t\t\t\t\terrorCode: \"INTERNAL\",\n\t\t\t\t\t\terrorMessage: (err as Error).message,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t},\n\t\t\tcaptureMode: (method: string): CaptureMode | undefined => {\n\t\t\t\treturn findRpc(method)?.captureMode;\n\t\t\t},\n\t\t\tdispatchStream: async function* (\n\t\t\t\tmethod: string,\n\t\t\t\tpayload: Uint8Array,\n\t\t\t): AsyncIterable<StreamItem> {\n\t\t\t\tvoid handle;\n\t\t\t\tconst entry = findRpc(method);\n\t\t\t\tif (!entry || !entry.streaming) {\n\t\t\t\t\tyield {\n\t\t\t\t\t\terrorCode: \"NOT_FOUND\",\n\t\t\t\t\t\terrorMessage: `no streaming handler for method ${method}`,\n\t\t\t\t\t};\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (!entry.schemaPair) {\n\t\t\t\t\tyield {\n\t\t\t\t\t\terrorCode: \"INTERNAL\",\n\t\t\t\t\t\terrorMessage: `schema not loaded for method ${method}`,\n\t\t\t\t\t};\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tlet request: unknown;\n\t\t\t\ttry {\n\t\t\t\t\trequest = entry.schemaPair.input.decode(payload);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tyield {\n\t\t\t\t\t\terrorCode: \"INVALID_ARGUMENT\",\n\t\t\t\t\t\terrorMessage: `decode: ${(err as Error).message}`,\n\t\t\t\t\t};\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tconst fn = entry.fn as RpcStreamHandlerFn;\n\t\t\t\t\tfor await (const chunk of fn(request)) {\n\t\t\t\t\t\tconst bytes = entry.schemaPair.output.encode(\n\t\t\t\t\t\t\tchunk as Record<string, unknown>,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tyield { payload: bytes };\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tyield {\n\t\t\t\t\t\terrorCode: \"INTERNAL\",\n\t\t\t\t\t\terrorMessage: (err as Error).message,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t},\n\t\t};\n\t}\n}\n\nexport class Registry {\n\t// Internal storage for incoming handlers and published events — accessed\n\t// via domain classes.\n\t// @internal\n\treadonly _handle = new Handle();\n\t/**\n\t * Public-but-undocumented route collector. Используется только интеграциями\n\t * `servicebridge/{express,fastify,hono}`. Прикладной код пишет роуты в свой\n\t * фреймворк, не сюда. См. ADR 0001 и userDocs/integrations.md.\n\t */\n\treadonly routes: RouteCollector;\n\tprivate readonly _outgoing: OutgoingEntry[] = [];\n\n\t/**\n\t * @param onRestart — вызывается из `routes.publishHttp(...)` после записи\n\t * нового endpoint'а. ServiceBridge подставляет туда рестарт Registry-watch\n\t * стрима. До `sb.start()` callback ожидает no-op.\n\t */\n\tconstructor(onRestart: () => void = () => {}) {\n\t\tthis.routes = new RouteCollector({\n\t\t\tsetEndpoint: (ep: string) => {\n\t\t\t\tthis._httpEndpoint = ep;\n\t\t\t},\n\t\t\ttriggerRestart: onRestart,\n\t\t});\n\t}\n\n\tservice(serviceName: string, deps: ServiceDeps): void {\n\t\tfor (const method of deps.rpc ?? []) {\n\t\t\tthis._outgoing.push({\n\t\t\t\tserviceName,\n\t\t\t\tmethodName: method,\n\t\t\t\ttype: MethodType.METHOD_TYPE_RPC,\n\t\t\t});\n\t\t}\n\t\tfor (const method of deps.workflows ?? []) {\n\t\t\tthis._outgoing.push({\n\t\t\t\tserviceName,\n\t\t\t\tmethodName: method,\n\t\t\t\ttype: MethodType.METHOD_TYPE_WORKFLOW,\n\t\t\t});\n\t\t}\n\t\tfor (const method of deps.http ?? []) {\n\t\t\tthis._outgoing.push({\n\t\t\t\tserviceName,\n\t\t\t\tmethodName: method,\n\t\t\t\ttype: MethodType.METHOD_TYPE_HTTP,\n\t\t\t});\n\t\t}\n\t}\n\n\tbuildRegisterRequest(): RegisterRequest {\n\t\tconst incoming: PbIncomingMethod[] = this._handle.incomingMethods();\n\n\t\t// HTTP routes collected by an integration are emitted as METHOD_TYPE_HTTP\n\t\t// IncomingMethod entries (ADR 0001). No schema, no contract hash —\n\t\t// HTTP routes are declared, not transported through the runtime.\n\t\tfor (const r of this.routes.snapshot()) {\n\t\t\tincoming.push({\n\t\t\t\ttype: MethodType.METHOD_TYPE_HTTP,\n\t\t\t\tname: `${r.method} ${r.pattern}`,\n\t\t\t\tinputSchemaJson: Buffer.alloc(0),\n\t\t\t\toutputSchemaJson: Buffer.alloc(0),\n\t\t\t\tstreaming: false,\n\t\t\t\tcontractHash: \"\",\n\t\t\t});\n\t\t}\n\n\t\tconst published: PbPublishedEvent[] = this._handle.publishedEvents();\n\n\t\tconst outgoing: PbOutgoingDep[] = this._outgoing.map((o) => ({\n\t\t\tserviceName: o.serviceName,\n\t\t\tmethodName: o.methodName,\n\t\t\ttype: o.type,\n\t\t}));\n\n\t\t// Dedup event subscriptions by pattern. Multiple `event.handle(name, fn)`\n\t\t// calls with the same pattern produce multiple HandlerEntry rows (so the\n\t\t// subscriber dispatches to all matching handlers locally — that's the\n\t\t// fan-out-within-SDK semantics tests rely on), but the runtime's\n\t\t// `event_subscriptions` table has PRIMARY KEY (subscriber_id, pattern),\n\t\t// so sending duplicates would trip the unique constraint inside\n\t\t// `ReplaceEventSubs` and roll back the entire registration. One row per\n\t\t// distinct pattern is enough — the SDK side handles in-process fan-out.\n\t\tconst seenPatterns = new Set<string>();\n\t\tconst eventSubscriptions: { pattern: string; durable: boolean }[] = [];\n\t\tfor (const e of this._handle._entries) {\n\t\t\tif (e.type !== MethodType.METHOD_TYPE_EVENT) continue;\n\t\t\tif (seenPatterns.has(e.name)) continue;\n\t\t\tseenPatterns.add(e.name);\n\t\t\teventSubscriptions.push({ pattern: e.name, durable: true });\n\t\t}\n\n\t\treturn {\n\t\t\tincoming,\n\t\t\tpublished,\n\t\t\toutgoing,\n\t\t\tcallEndpoint: this._callEndpoint,\n\t\t\teventSubscriptions,\n\t\t\thttpEndpoint: this._httpEndpoint,\n\t\t};\n\t}\n\n\tsetCallEndpoint(endpoint: string): void {\n\t\tthis._callEndpoint = endpoint;\n\t}\n\n\tprivate _callEndpoint = \"\";\n\tprivate _httpEndpoint = \"\";\n}\n","import type {\n\tEventSubscriptionDescriptor,\n\tMethodDescriptor,\n\tOutgoingCallDescriptor,\n\tPolicyEvaluation,\n\tCaptureModes as ProtoCaptureModes,\n\tRegisterRequest,\n\tRegistryClient,\n\tRegistryEvent,\n\tServiceInstanceInfo,\n} from \"../pb/servicebridge/v1/registry\";\nimport { CaptureMode as ProtoCaptureMode } from \"../pb/servicebridge/v1/registry\";\nimport { Channel } from \"../pb/servicebridge/v1/telemetry\";\nimport type { CaptureMode } from \"../telemetry/payload-capture\";\n\n// captureModeFromProto maps the runtime-pushed registry enum to the SDK string\n// mode. UNSPECIFIED and unknown values fail safe to \"none\".\nfunction captureModeFromProto(m: ProtoCaptureMode): CaptureMode {\n\tswitch (m) {\n\t\tcase ProtoCaptureMode.CAPTURE_MODE_ALL:\n\t\t\treturn \"all\";\n\t\tcase ProtoCaptureMode.CAPTURE_MODE_ERRORS:\n\t\t\treturn \"errors\";\n\t\tdefault:\n\t\t\treturn \"none\";\n\t}\n}\n\n// ChannelCaptureModes is the SDK-side per-channel effective capture mode set,\n// keyed by op Channel. Every channel defaults to \"none\" (fail-safe) until the\n// runtime pushes a snapshot.\ntype ChannelCaptureModes = Record<Channel, CaptureMode>;\n\nfunction defaultChannelCaptureModes(): ChannelCaptureModes {\n\treturn {\n\t\t[Channel.CHANNEL_UNSPECIFIED]: \"none\",\n\t\t[Channel.HTTP]: \"none\",\n\t\t[Channel.RPC]: \"none\",\n\t\t[Channel.EVENT]: \"none\",\n\t\t[Channel.WORKFLOW]: \"none\",\n\t\t[Channel.JOB]: \"none\",\n\t\t[Channel.USER]: \"none\",\n\t\t[Channel.UNRECOGNIZED]: \"none\",\n\t};\n}\n\n// channelCaptureModesFromProto maps the runtime-pushed CaptureModes message to\n// the SDK per-channel record. A missing message leaves every channel at \"none\".\nfunction channelCaptureModesFromProto(\n\tm: ProtoCaptureModes | undefined,\n): ChannelCaptureModes {\n\tconst out = defaultChannelCaptureModes();\n\tif (!m) return out;\n\tout[Channel.RPC] = captureModeFromProto(m.rpc);\n\tout[Channel.HTTP] = captureModeFromProto(m.http);\n\tout[Channel.EVENT] = captureModeFromProto(m.event);\n\tout[Channel.WORKFLOW] = captureModeFromProto(m.workflow);\n\treturn out;\n}\n\nfunction channelModesEqual(\n\ta: ChannelCaptureModes,\n\tb: ChannelCaptureModes,\n): boolean {\n\treturn (\n\t\ta[Channel.RPC] === b[Channel.RPC] &&\n\t\ta[Channel.HTTP] === b[Channel.HTTP] &&\n\t\ta[Channel.EVENT] === b[Channel.EVENT] &&\n\t\ta[Channel.WORKFLOW] === b[Channel.WORKFLOW]\n\t);\n}\n\n// cacheKey builds a unique key for a MethodDescriptor.\nfunction cacheKey(d: MethodDescriptor): string {\n\treturn `${d.instanceId}:${d.type}:${d.name}:${d.published}`;\n}\n\n// eventSubKey: subscriptions are keyed by (service_id, pattern) — matches the\n// PRIMARY KEY of event_subscriptions on the server.\nfunction eventSubKey(d: EventSubscriptionDescriptor): string {\n\treturn `${d.serviceId}|${d.pattern}`;\n}\n\n// outgoingKey: outgoing decls are keyed by (caller, target, method, type).\nfunction outgoingKey(d: OutgoingCallDescriptor): string {\n\treturn `${d.callerServiceId}|${d.targetServiceId}|${d.targetMethod}|${d.targetType}`;\n}\n\n// WatchStream manages the gRPC Registry.RegisterAndWatch stream.\n// @internal — см. ./README.md\nexport class WatchStream {\n\tprivate stream: ReturnType<RegistryClient[\"registerAndWatch\"]> | null = null;\n\tprivate cache = new Map<string, MethodDescriptor>();\n\tprivate instances = new Map<string, ServiceInstanceInfo>();\n\t// ADR-0014 enrichment: caller's own event subscriptions + outgoing calls\n\t// plus its current PolicyEvaluation. Updated from snapshot + update frames.\n\tprivate eventSubs = new Map<string, EventSubscriptionDescriptor>();\n\tprivate outgoing = new Map<string, OutgoingCallDescriptor>();\n\tprivate policy: PolicyEvaluation | null = null;\n\t// Runtime-pushed effective capture mode per op channel. Every channel is\n\t// \"none\" until the first snapshot arrives (fail-safe — never capture before\n\t// the runtime authorises it).\n\tprivate _captureModes: ChannelCaptureModes = defaultChannelCaptureModes();\n\tprivate captureModeListeners = new Set<\n\t\t(modes: ChannelCaptureModes) => void\n\t>();\n\tprivate onError: (err: Error) => void = () => {};\n\tprivate instanceListeners = new Set<\n\t\t(added: ServiceInstanceInfo[], removed: ServiceInstanceInfo[]) => void\n\t>();\n\tprivate policyListeners = new Set<(policy: PolicyEvaluation) => void>();\n\tprivate peersChangeListeners = new Set<\n\t\t(added: string[], removed: string[]) => void\n\t>();\n\n\tstart(\n\t\treq: RegisterRequest,\n\t\tclient: RegistryClient,\n\t\tonError?: (err: Error) => void,\n\t): void {\n\t\tif (onError) this.onError = onError;\n\t\tthis.stream = client.registerAndWatch(req);\n\t\tthis.stream.on(\"data\", (evt: RegistryEvent) => this.handleEvent(evt));\n\t\tthis.stream.on(\"error\", (err: Error) => this.onError(err));\n\t}\n\n\tstop(): void {\n\t\tif (this.stream) {\n\t\t\tthis.stream.cancel();\n\t\t\tthis.stream = null;\n\t\t}\n\t}\n\n\trestart(\n\t\treq: RegisterRequest,\n\t\tclient: RegistryClient,\n\t\tonError?: (err: Error) => void,\n\t): void {\n\t\tthis.stop();\n\t\tthis.start(req, client, onError);\n\t}\n\n\tsnapshot(): ReadonlyMap<string, MethodDescriptor> {\n\t\treturn new Map(this.cache);\n\t}\n\n\tinstancesSnapshot(): Map<string, ServiceInstanceInfo> {\n\t\treturn this.instances;\n\t}\n\n\t// ADR-0014: snapshot accessors for service-map enrichment.\n\teventSubscriptionsSnapshot(): Map<string, EventSubscriptionDescriptor> {\n\t\treturn new Map(this.eventSubs);\n\t}\n\n\toutgoingCallsSnapshot(): Map<string, OutgoingCallDescriptor> {\n\t\treturn new Map(this.outgoing);\n\t}\n\n\tpolicyEvaluation(): PolicyEvaluation | null {\n\t\treturn this.policy;\n\t}\n\n\t// captureModeForChannel returns the runtime-pushed effective payload capture\n\t// mode for the given op channel. \"none\" until the first registry snapshot\n\t// arrives, and for any channel the runtime did not push a mode for.\n\tcaptureModeForChannel(channel: Channel): CaptureMode {\n\t\treturn this._captureModes[channel] ?? \"none\";\n\t}\n\n\t// onCaptureModes fires whenever the runtime pushes a (changed) per-channel\n\t// capture mode set on the snapshot or an update.\n\tonCaptureModes(fn: (modes: ChannelCaptureModes) => void): () => void {\n\t\tthis.captureModeListeners.add(fn);\n\t\treturn () => this.captureModeListeners.delete(fn);\n\t}\n\n\tprivate applyCaptureModes(next: ChannelCaptureModes): void {\n\t\tif (channelModesEqual(next, this._captureModes)) return;\n\t\tthis._captureModes = next;\n\t\tfor (const fn of this.captureModeListeners) fn(next);\n\t}\n\n\tonInstancesChange(\n\t\tfn: (added: ServiceInstanceInfo[], removed: ServiceInstanceInfo[]) => void,\n\t): () => void {\n\t\tthis.instanceListeners.add(fn);\n\t\treturn () => this.instanceListeners.delete(fn);\n\t}\n\n\t// onPolicyEvaluation fires every time a fresh PolicyEvaluation lands on the\n\t// stream (initial snapshot, plus future RegistryUpdate.policy when policy\n\t// rules change live for this caller).\n\tonPolicyEvaluation(fn: (policy: PolicyEvaluation) => void): () => void {\n\t\tthis.policyListeners.add(fn);\n\t\treturn () => this.policyListeners.delete(fn);\n\t}\n\n\t// onPeersChange fires when added_peers or removed_peers arrive in a\n\t// RegistryUpdate. SDK uses this to update serviceMap and close stale\n\t// direct connections.\n\tonPeersChange(fn: (added: string[], removed: string[]) => void): () => void {\n\t\tthis.peersChangeListeners.add(fn);\n\t\treturn () => this.peersChangeListeners.delete(fn);\n\t}\n\n\tprivate emitInstances(\n\t\tadded: ServiceInstanceInfo[],\n\t\tremoved: ServiceInstanceInfo[],\n\t): void {\n\t\tif (added.length === 0 && removed.length === 0) return;\n\t\tfor (const fn of this.instanceListeners) fn(added, removed);\n\t}\n\n\tprivate emitPolicy(policy: PolicyEvaluation): void {\n\t\tfor (const fn of this.policyListeners) fn(policy);\n\t}\n\n\tprivate handleEvent(evt: RegistryEvent): void {\n\t\tif (evt.snapshot) {\n\t\t\tthis.cache.clear();\n\t\t\tfor (const m of evt.snapshot.methods) {\n\t\t\t\tthis.cache.set(cacheKey(m), m);\n\t\t\t}\n\t\t\tconst prev = Array.from(this.instances.values());\n\t\t\tthis.instances.clear();\n\t\t\tfor (const i of evt.snapshot.instances) {\n\t\t\t\tthis.instances.set(i.instanceId, i);\n\t\t\t}\n\t\t\tthis.eventSubs.clear();\n\t\t\tfor (const es of evt.snapshot.eventSubscriptions ?? []) {\n\t\t\t\tthis.eventSubs.set(eventSubKey(es), es);\n\t\t\t}\n\t\t\tthis.outgoing.clear();\n\t\t\tfor (const oc of evt.snapshot.outgoingCalls ?? []) {\n\t\t\t\tthis.outgoing.set(outgoingKey(oc), oc);\n\t\t\t}\n\t\t\tif (evt.snapshot.policy) {\n\t\t\t\tthis.policy = evt.snapshot.policy;\n\t\t\t\tthis.emitPolicy(evt.snapshot.policy);\n\t\t\t}\n\t\t\tthis.applyCaptureModes(\n\t\t\t\tchannelCaptureModesFromProto(evt.snapshot.captureModes),\n\t\t\t);\n\t\t\tthis.emitInstances(evt.snapshot.instances, prev);\n\t\t} else if (evt.update) {\n\t\t\tfor (const m of evt.update.added) {\n\t\t\t\tthis.cache.set(cacheKey(m), m);\n\t\t\t}\n\t\t\tfor (const m of evt.update.removed) {\n\t\t\t\tthis.cache.delete(cacheKey(m));\n\t\t\t}\n\t\t\tfor (const i of evt.update.addedInstances) {\n\t\t\t\tthis.instances.set(i.instanceId, i);\n\t\t\t}\n\t\t\tfor (const i of evt.update.removedInstances) {\n\t\t\t\tthis.instances.delete(i.instanceId);\n\t\t\t}\n\t\t\tfor (const es of evt.update.addedEventSubscriptions ?? []) {\n\t\t\t\tthis.eventSubs.set(eventSubKey(es), es);\n\t\t\t}\n\t\t\tfor (const es of evt.update.removedEventSubscriptions ?? []) {\n\t\t\t\tthis.eventSubs.delete(eventSubKey(es));\n\t\t\t}\n\t\t\tfor (const oc of evt.update.addedOutgoingCalls ?? []) {\n\t\t\t\tthis.outgoing.set(outgoingKey(oc), oc);\n\t\t\t}\n\t\t\tfor (const oc of evt.update.removedOutgoingCalls ?? []) {\n\t\t\t\tthis.outgoing.delete(outgoingKey(oc));\n\t\t\t}\n\t\t\t// removedPeers: when a peer falls out of the caller's policy scope\n\t\t\t// (e.g. rule revoked), runtime emits the peer's serviceId in\n\t\t\t// removedPeers. SDK must drop every cached entry tied to that peer\n\t\t\t// so serviceMap loses the entry within the same propagation window.\n\t\t\tconst removedPeers = evt.update.removedPeers ?? [];\n\t\t\tif (removedPeers.length > 0) {\n\t\t\t\tconst removedSet = new Set(removedPeers);\n\t\t\t\tconst removedInstancesByPeer: ServiceInstanceInfo[] = [];\n\t\t\t\tfor (const [k, m] of this.cache) {\n\t\t\t\t\tif (removedSet.has(m.serviceId)) this.cache.delete(k);\n\t\t\t\t}\n\t\t\t\tfor (const [k, inst] of this.instances) {\n\t\t\t\t\tif (removedSet.has(inst.serviceId)) {\n\t\t\t\t\t\tremovedInstancesByPeer.push(inst);\n\t\t\t\t\t\tthis.instances.delete(k);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (const [k, es] of this.eventSubs) {\n\t\t\t\t\tif (removedSet.has(es.serviceId)) this.eventSubs.delete(k);\n\t\t\t\t}\n\t\t\t\tfor (const [k, oc] of this.outgoing) {\n\t\t\t\t\tif (removedSet.has(oc.targetServiceId)) this.outgoing.delete(k);\n\t\t\t\t}\n\t\t\t\tif (removedInstancesByPeer.length > 0) {\n\t\t\t\t\tthis.emitInstances([], removedInstancesByPeer);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (evt.update.policy) {\n\t\t\t\tthis.policy = evt.update.policy;\n\t\t\t\tthis.emitPolicy(evt.update.policy);\n\t\t\t}\n\t\t\tthis.applyCaptureModes(\n\t\t\t\tchannelCaptureModesFromProto(evt.update.captureModes),\n\t\t\t);\n\t\t\tconst addedPeers = evt.update.addedPeers ?? [];\n\t\t\tif (addedPeers.length > 0 || removedPeers.length > 0) {\n\t\t\t\tfor (const fn of this.peersChangeListeners) {\n\t\t\t\t\tfn(addedPeers, removedPeers);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.emitInstances(\n\t\t\t\tevt.update.addedInstances,\n\t\t\t\tevt.update.removedInstances,\n\t\t\t);\n\t\t}\n\t}\n}\n","// Per-instance circuit breaker. State per (serviceId, instanceId) — scope\n// matches ADR 0001 #2 + ADR 0009: per-pod, not synchronized across caller pods.\n// Multi-pod coherence comes from runtime telemetry hints (ADR 0009 §3), not\n// from a shared CB state.\n//\n// State machine:\n// CLOSED → OPEN when totalRequests >= MIN_REQUESTS and errorRate > ERROR_THRESHOLD\n// in the sliding window.\n// OPEN → HALF_OPEN after OPEN_DURATION_MS since opening (lazy transition\n// on the next canCall / state read).\n// HALF_OPEN → CLOSED on probe success.\n// HALF_OPEN → OPEN on probe failure (re-opens for another OPEN_DURATION_MS).\n//\n// Only one probe is allowed in HALF_OPEN — concurrent callers see canCall()=false\n// until the probe completes or the probe window times out (probe ownership is\n// best-effort within a pod; ADR 0009 §1 accepts duplicate probes across pods).\n//\n// @internal — см. ./README.md\n\nexport const WINDOW_SIZE_MS = 10_000;\nexport const BUCKET_COUNT = 10;\nexport const BUCKET_MS = WINDOW_SIZE_MS / BUCKET_COUNT;\nexport const MIN_REQUESTS = 10;\nexport const ERROR_THRESHOLD = 0.5;\nexport const OPEN_DURATION_MS = 30_000;\n\ntype State = \"CLOSED\" | \"OPEN\" | \"HALF_OPEN\";\n\ninterface Bucket {\n\tstart: number; // bucket window start, ms\n\tsuccesses: number;\n\terrors: number;\n}\n\ninterface Entry {\n\tstate: State;\n\topenedAt: number;\n\tprobeInFlight: boolean;\n\tbuckets: Bucket[]; // ring buffer of length BUCKET_COUNT\n}\n\nfunction newEntry(now: number): Entry {\n\tconst buckets: Bucket[] = [];\n\tfor (let i = 0; i < BUCKET_COUNT; i++) {\n\t\tbuckets.push({\n\t\t\tstart: now - (BUCKET_COUNT - 1 - i) * BUCKET_MS,\n\t\t\tsuccesses: 0,\n\t\t\terrors: 0,\n\t\t});\n\t}\n\treturn { state: \"CLOSED\", openedAt: 0, probeInFlight: false, buckets };\n}\n\n// currentBucket rotates the ring buffer in place so that the head bucket\n// always covers `now`. Buckets that fall outside the window are zeroed.\nfunction currentBucket(e: Entry, now: number): Bucket {\n\tconst headStart = Math.floor(now / BUCKET_MS) * BUCKET_MS;\n\tlet head = e.buckets[e.buckets.length - 1]!;\n\tif (head.start === headStart) return head;\n\t// Advance the ring forward bucket-by-bucket until the head matches.\n\tconst stepsRaw = Math.floor((headStart - head.start) / BUCKET_MS);\n\tconst steps = Math.min(stepsRaw, BUCKET_COUNT);\n\tfor (let i = 0; i < steps; i++) {\n\t\tconst oldest = e.buckets.shift()!;\n\t\toldest.start = e.buckets[e.buckets.length - 1]!.start + BUCKET_MS;\n\t\toldest.successes = 0;\n\t\toldest.errors = 0;\n\t\te.buckets.push(oldest);\n\t}\n\t// When stepsRaw exceeded BUCKET_COUNT the loop above only reset every\n\t// bucket once — that's enough since they all become stale at once. Now\n\t// snap the head start to the exact current bucket.\n\thead = e.buckets[e.buckets.length - 1]!;\n\tif (head.start !== headStart) {\n\t\tconst delta = headStart - head.start;\n\t\tfor (const b of e.buckets) b.start += delta;\n\t}\n\treturn e.buckets[e.buckets.length - 1]!;\n}\n\nfunction windowTotals(\n\te: Entry,\n\tnow: number,\n): { total: number; errors: number } {\n\tconst cutoff = now - WINDOW_SIZE_MS;\n\tlet total = 0;\n\tlet errors = 0;\n\tfor (const b of e.buckets) {\n\t\tif (b.start + BUCKET_MS <= cutoff) continue;\n\t\ttotal += b.successes + b.errors;\n\t\terrors += b.errors;\n\t}\n\treturn { total, errors };\n}\n\nexport class CircuitBreakerRegistry {\n\tprivate map = new Map<string, Entry>();\n\tprivate now: () => number;\n\n\tconstructor(now: () => number = Date.now) {\n\t\tthis.now = now;\n\t}\n\n\t// canCall returns true when the breaker is CLOSED, or when it has been\n\t// OPEN long enough to transition to HALF_OPEN and no probe is in flight.\n\tcanCall(key: string): boolean {\n\t\tconst e = this.map.get(key);\n\t\tif (!e) return true;\n\t\tthis.maybeHalfOpen(e);\n\t\tif (e.state === \"CLOSED\") return true;\n\t\tif (e.state === \"HALF_OPEN\") {\n\t\t\tif (e.probeInFlight) return false;\n\t\t\te.probeInFlight = true;\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\trecordSuccess(key: string): void {\n\t\tconst now = this.now();\n\t\tconst e = this.entry(key, now);\n\t\tif (e.state === \"HALF_OPEN\") {\n\t\t\te.state = \"CLOSED\";\n\t\t\te.probeInFlight = false;\n\t\t\tthis.resetWindow(e, now);\n\t\t\treturn;\n\t\t}\n\t\tcurrentBucket(e, now).successes++;\n\t}\n\n\trecordFailure(key: string): void {\n\t\tconst now = this.now();\n\t\tconst e = this.entry(key, now);\n\t\tif (e.state === \"HALF_OPEN\") {\n\t\t\te.state = \"OPEN\";\n\t\t\te.openedAt = now;\n\t\t\te.probeInFlight = false;\n\t\t\treturn;\n\t\t}\n\t\tcurrentBucket(e, now).errors++;\n\t\tif (e.state === \"OPEN\") return;\n\t\tconst { total, errors } = windowTotals(e, now);\n\t\tif (total >= MIN_REQUESTS && errors / total > ERROR_THRESHOLD) {\n\t\t\te.state = \"OPEN\";\n\t\t\te.openedAt = now;\n\t\t}\n\t}\n\n\tstate(key: string): State {\n\t\tconst e = this.map.get(key);\n\t\tif (!e) return \"CLOSED\";\n\t\tthis.maybeHalfOpen(e);\n\t\treturn e.state;\n\t}\n\n\treset(key: string): void {\n\t\tthis.map.delete(key);\n\t}\n\n\tprivate entry(key: string, now: number): Entry {\n\t\tlet e = this.map.get(key);\n\t\tif (!e) {\n\t\t\te = newEntry(now);\n\t\t\tthis.map.set(key, e);\n\t\t}\n\t\treturn e;\n\t}\n\n\tprivate maybeHalfOpen(e: Entry): void {\n\t\tif (e.state !== \"OPEN\") return;\n\t\tif (this.now() - e.openedAt >= OPEN_DURATION_MS) {\n\t\t\te.state = \"HALF_OPEN\";\n\t\t\te.probeInFlight = false;\n\t\t}\n\t}\n\n\tprivate resetWindow(e: Entry, now: number): void {\n\t\tfor (let i = 0; i < BUCKET_COUNT; i++) {\n\t\t\tconst b = e.buckets[i]!;\n\t\t\tb.start = now - (BUCKET_COUNT - 1 - i) * BUCKET_MS;\n\t\t\tb.successes = 0;\n\t\t\tb.errors = 0;\n\t\t}\n\t}\n}\n","import { randomUUID } from \"node:crypto\";\nimport type { ServiceBridge } from \"../connection/service-bridge\";\nimport { computeContractHash } from \"../serde/contract-hash\";\nimport type { SchemaPair } from \"../serde/serializer\";\nimport { runWithTrace, streamWithContext } from \"../telemetry/context\";\nimport { Channel, type OpHandle, RpcCall, Status } from \"../telemetry/ops\";\nimport type { CircuitBreakerRegistry } from \"./circuit-breaker\";\nimport type { DirectTransport } from \"./direct-transport\";\nimport type { InstanceCache } from \"./instance-cache\";\nimport {\n\ttype Candidate,\n\tcbKey,\n\ttype LoadBalancer,\n\tNoLiveInstanceError,\n} from \"./lb\";\nimport type { ProxyTransport } from \"./proxy-transport\";\nimport { backoffDelay, isRetryable, mergeRetryOpts } from \"./retry\";\n\n// CallOpts is the per-call configuration accepted by ServiceBridge.call().\n// Defaults are sourced from ServiceBridge.options.callDefaults, then overridden\n// by per-call values.\nexport interface CallOpts {\n\ttimeout?: string; // e.g. \"10s\", \"500ms\" — default \"30s\"\n\trequestId?: string; // auto-generated UUID v4 if omitted\n\t// transport selects how the call reaches the callee:\n\t// - \"direct\" : caller → callee mTLS, error if callee has no call_endpoint\n\t// - \"proxy\" : caller → runtime Invoke → callee (even if direct possible)\n\t// - \"auto\" : direct if endpoint is known, else proxy (DEFAULT)\n\ttransport?: \"direct\" | \"proxy\" | \"auto\";\n\t// idempotencyKey opts the call into runtime-side dedup (ADR 0012). When\n\t// set, the runtime claims the key before forwarding and replays of the\n\t// same key within the TTL return the cached response. Omit for read-only\n\t// or otherwise non-idempotent calls — INTERNAL/ABORTED/UNKNOWN errors\n\t// then surface as non-retryable.\n\tidempotencyKey?: string;\n\t// Retry policy. Defaults: maxAttempts=3, baseDelayMs=200, factor=2,\n\t// maxDelayMs=5000, jitter=0.3. Set maxAttempts=1 to disable retry.\n\tretry?: Partial<RetryOpts>;\n}\n\nexport interface RetryOpts {\n\tmaxAttempts: number;\n\tbaseDelayMs: number;\n\tfactor: number;\n\tmaxDelayMs: number;\n\tjitter: number; // fraction in [0, 1]\n}\n\n// CallerSchema bundles the SchemaPair with its precomputed contract hash so\n// the LB can filter instances whose hash differs (ADR 0005 — version routing).\nexport interface CallerSchema {\n\tpair: SchemaPair;\n\tcontractHash: string;\n}\n\n// SchemaResolver is invoked by RpcClient when a method's CallerSchema is not yet\n// cached. Implementations look up the spec from registered handlers (handler\n// side knows the .proto path; caller side reuses the same spec or fetches\n// from local config).\nexport type SchemaResolver = (\n\tserviceName: string,\n\tmethodName: string,\n) => CallerSchema | undefined;\n\n// RpcClient is the entry point for outbound RPC calls.\n// @internal — см. ./README.md\nexport class RpcClient {\n\tconstructor(\n\t\tprivate readonly proxy: ProxyTransport,\n\t\tprivate readonly directTransport: DirectTransport | null,\n\t\tprivate readonly instances: InstanceCache,\n\t\tprivate readonly resolveSchema: SchemaResolver,\n\t\tprivate readonly callerService: string,\n\t\tprivate readonly cb: CircuitBreakerRegistry,\n\t\tprivate readonly lb: LoadBalancer,\n\t\t// sb owns the instance identity and telemetry ring used for RPC.CALL emission.\n\t\t// Per ADR-0036, the caller SDK emits RPC.CALL for every outbound call.\n\t\tprivate readonly sb: ServiceBridge,\n\t) {}\n\n\t// stream invokes a server-side streaming method, returning an AsyncIterable\n\t// of decoded chunks. Transport selection follows the same transport opt\n\t// rules as call(). Retry is NOT applied — streams are single-pick by design\n\t// (ADR 0004): mid-stream replay would re-deliver already-received chunks.\n\tasync *stream<Req = unknown, Chunk = unknown>(\n\t\tserviceName: string,\n\t\tmethodName: string,\n\t\tpayload: Req,\n\t\topts?: CallOpts,\n\t): AsyncIterable<Chunk> {\n\t\tconst descriptor = this.instances.descriptorFor(serviceName, methodName);\n\t\tif (!descriptor) {\n\t\t\tthrow new Error(\n\t\t\t\t`rpc: no descriptor for ${serviceName}/${methodName} — not subscribed or target offline`,\n\t\t\t);\n\t\t}\n\t\tif (!descriptor.streaming) {\n\t\t\tthrow new Error(\n\t\t\t\t`rpc: ${serviceName}/${methodName} is not a streaming method — use sb.rpc.call()`,\n\t\t\t);\n\t\t}\n\n\t\tconst schema = this.resolveSchema(serviceName, methodName);\n\t\tif (!schema) {\n\t\t\tthrow new Error(`rpc: no SchemaPair for ${serviceName}/${methodName}`);\n\t\t}\n\n\t\tconst reqBytes = schema.pair.input.encode(payload as object);\n\t\tconst requestId = opts?.requestId ?? randomUUID();\n\t\tconst idempotencyKey = opts?.idempotencyKey ?? \"\";\n\t\tconst timeoutMs = parseTimeout(opts?.timeout) ?? 30_000;\n\t\tconst transport = opts?.transport ?? \"auto\";\n\n\t\tconst candidate = this.pickCandidate(\n\t\t\tserviceName,\n\t\t\tmethodName,\n\t\t\tschema.contractHash,\n\t\t\ttransport,\n\t\t);\n\t\tconst useDirect = this.shouldUseDirect(candidate, transport);\n\n\t\t// One RPC.CALL op for the entire stream lifetime (ADR-0037..0042).\n\t\tconst callOp = this.sb.telemetry.startOp({\n\t\t\tchannel: Channel.RPC,\n\t\t\tkind: RpcCall,\n\t\t\tsubject: formatRpcCallSubject(serviceName, methodName),\n\t\t\tpeerServiceId: candidate.instance.serviceId,\n\t\t\tattempt: 0,\n\t\t\tmetaJson: Buffer.from(\n\t\t\t\tJSON.stringify({\n\t\t\t\t\tmethod: methodName,\n\t\t\t\t\tvia_proxy: !useDirect,\n\t\t\t\t\trequestId,\n\t\t\t\t\tidempotencyKey,\n\t\t\t\t}),\n\t\t\t),\n\t\t});\n\n\t\t// Streaming captures only the request payload (IN). The response is a\n\t\t// chunk stream; concatenating chunks into one blob would break streaming\n\t\t// memory bounds, so OUT is not captured for streams.\n\t\tcallOp.captureIn(reqBytes, schema.contractHash);\n\n\t\tconst release = this.lb.acquire(candidate.instance.instanceId);\n\t\tconst childCtx = { traceId: callOp.traceId, parentOpId: callOp.opId };\n\t\tconst directTransport = this.directTransport;\n\t\tconst proxy = this.proxy;\n\t\tconst callerService = this.callerService;\n\t\tconst decoded = async function* (): AsyncIterable<Chunk> {\n\t\t\tconst source = useDirect\n\t\t\t\t? directTransport!.callStream(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tendpoint: candidate.instance.callEndpoint,\n\t\t\t\t\t\t\tserviceId: candidate.instance.serviceId,\n\t\t\t\t\t\t\tinstanceId: candidate.instance.instanceId,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tmethodName,\n\t\t\t\t\t\treqBytes,\n\t\t\t\t\t\tcallerService,\n\t\t\t\t\t\trequestId,\n\t\t\t\t\t\tidempotencyKey,\n\t\t\t\t\t\ttimeoutMs,\n\t\t\t\t\t)\n\t\t\t\t: proxy.callStream(\n\t\t\t\t\t\tcandidate.instance.serviceId,\n\t\t\t\t\t\tmethodName,\n\t\t\t\t\t\treqBytes,\n\t\t\t\t\t\trequestId,\n\t\t\t\t\t\tidempotencyKey,\n\t\t\t\t\t\ttimeoutMs,\n\t\t\t\t\t\tschema.contractHash,\n\t\t\t\t\t);\n\t\t\tfor await (const bytes of source) {\n\t\t\t\tyield schema.pair.output.decode(bytes) as Chunk;\n\t\t\t}\n\t\t};\n\t\tlet endStatus: Status = Status.SUCCESS;\n\t\tlet endMsg: string | undefined;\n\t\ttry {\n\t\t\tyield* streamWithContext(childCtx, decoded);\n\t\t\tthis.cb.recordSuccess(cbKey(candidate.instance));\n\t\t} catch (err) {\n\t\t\tendStatus = Status.ERROR;\n\t\t\tendMsg = err instanceof Error ? err.message : String(err);\n\t\t\tthis.cb.recordFailure(cbKey(candidate.instance));\n\t\t\tthrow err;\n\t\t} finally {\n\t\t\tcallOp.end(endStatus, endMsg);\n\t\t\trelease();\n\t\t}\n\t}\n\n\tasync call<Req = unknown, Res = unknown>(\n\t\tserviceName: string,\n\t\tmethodName: string,\n\t\tpayload: Req,\n\t\topts?: CallOpts,\n\t): Promise<Res> {\n\t\tconst descriptor = this.instances.descriptorFor(serviceName, methodName);\n\t\tif (!descriptor) {\n\t\t\tthrow new Error(\n\t\t\t\t`rpc: no descriptor for ${serviceName}/${methodName} — not subscribed or target offline`,\n\t\t\t);\n\t\t}\n\t\tif (descriptor.streaming) {\n\t\t\tthrow new Error(\n\t\t\t\t`rpc: ${serviceName}/${methodName} is a streaming method — use sb.stream() instead`,\n\t\t\t);\n\t\t}\n\n\t\tconst schema = this.resolveSchema(serviceName, methodName);\n\t\tif (!schema) {\n\t\t\tthrow new Error(\n\t\t\t\t`rpc: no SchemaPair for ${serviceName}/${methodName} — caller must register schema for this method`,\n\t\t\t);\n\t\t}\n\n\t\tconst reqBytes = schema.pair.input.encode(payload as object);\n\t\tconst requestId = opts?.requestId ?? randomUUID();\n\t\t// Idempotency is opt-in (ADR 0012). Empty string is the wire signal for\n\t\t// \"no key\" — runtime then skips Claim/Save entirely.\n\t\tconst idempotencyKey = opts?.idempotencyKey ?? \"\";\n\t\tconst timeoutMs = parseTimeout(opts?.timeout) ?? 30_000;\n\t\tconst transport = opts?.transport ?? \"auto\";\n\t\tconst retry = mergeRetryOpts(opts?.retry);\n\t\tconst hasIdempotency = idempotencyKey.length > 0;\n\n\t\t// One RPC.CALL op for the whole logical call (ADR-0037..0042). Retries\n\t\t// bump the attempt counter on the SAME row — no op per attempt. The op is\n\t\t// started lazily on the first successful candidate pick so peer_service_id\n\t\t// and via_proxy reflect the transport actually used.\n\t\tlet callOp: OpHandle | null = null;\n\t\tlet lastErr: unknown = null;\n\t\tfor (let attempt = 0; attempt < retry.maxAttempts; attempt++) {\n\t\t\tlet candidate: Candidate;\n\t\t\ttry {\n\t\t\t\tcandidate = this.pickCandidate(\n\t\t\t\t\tserviceName,\n\t\t\t\t\tmethodName,\n\t\t\t\t\tschema.contractHash,\n\t\t\t\t\ttransport,\n\t\t\t\t);\n\t\t\t} catch (err) {\n\t\t\t\tconst wrapped =\n\t\t\t\t\terr instanceof NoLiveInstanceError\n\t\t\t\t\t\t? Object.assign(\n\t\t\t\t\t\t\t\tnew Error(\n\t\t\t\t\t\t\t\t\t`rpc: no instance of ${serviceName}/${methodName} matches caller contract ${schema.contractHash}`,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t{ code: 14 },\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t: err;\n\t\t\t\tlastErr = wrapped;\n\t\t\t\tif (\n\t\t\t\t\tattempt === retry.maxAttempts - 1 ||\n\t\t\t\t\t!isRetryable(wrapped, hasIdempotency)\n\t\t\t\t) {\n\t\t\t\t\t// Close the CALL row if it was already started on a prior attempt.\n\t\t\t\t\tcallOp?.setAttempt(attempt);\n\t\t\t\t\tcallOp?.end(\n\t\t\t\t\t\tStatus.ERROR,\n\t\t\t\t\t\twrapped instanceof Error ? wrapped.message : String(wrapped),\n\t\t\t\t\t);\n\t\t\t\t\tthrow wrapped;\n\t\t\t\t}\n\t\t\t\tawait sleep(backoffDelay(retry, attempt));\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst useDirect = this.shouldUseDirect(candidate, transport);\n\n\t\t\tif (callOp === null) {\n\t\t\t\tcallOp = this.sb.telemetry.startOp({\n\t\t\t\t\tchannel: Channel.RPC,\n\t\t\t\t\tkind: RpcCall,\n\t\t\t\t\tsubject: formatRpcCallSubject(serviceName, methodName),\n\t\t\t\t\tpeerServiceId: candidate.instance.serviceId,\n\t\t\t\t\tattempt,\n\t\t\t\t\tmetaJson: Buffer.from(\n\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\tmethod: methodName,\n\t\t\t\t\t\t\tvia_proxy: !useDirect,\n\t\t\t\t\t\t\trequestId,\n\t\t\t\t\t\t\tidempotencyKey,\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t});\n\t\t\t\t// Caller owns the RPC.CALL payloads: request (IN) once per logical\n\t\t\t\t// call, response (OUT) captured below before decode.\n\t\t\t\tcallOp.captureIn(reqBytes, schema.contractHash);\n\t\t\t} else {\n\t\t\t\tcallOp.setAttempt(attempt);\n\t\t\t}\n\n\t\t\tconst release = this.lb.acquire(candidate.instance.instanceId);\n\t\t\ttry {\n\t\t\t\t// Wrap invoke in child context so transport reads callOp.opId as\n\t\t\t\t// parentOpId — the callee handler then runs under parent=CALL.op_id.\n\t\t\t\tconst childCtx = { traceId: callOp.traceId, parentOpId: callOp.opId };\n\t\t\t\tconst invoke = async () => {\n\t\t\t\t\tconst respBytes = useDirect\n\t\t\t\t\t\t? await this.directTransport!.callUnary(\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tendpoint: candidate.instance.callEndpoint,\n\t\t\t\t\t\t\t\t\tserviceId: candidate.instance.serviceId,\n\t\t\t\t\t\t\t\t\tinstanceId: candidate.instance.instanceId,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tmethodName,\n\t\t\t\t\t\t\t\treqBytes,\n\t\t\t\t\t\t\t\tthis.callerService,\n\t\t\t\t\t\t\t\trequestId,\n\t\t\t\t\t\t\t\tidempotencyKey,\n\t\t\t\t\t\t\t\ttimeoutMs,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t: await this.proxy.callUnary(\n\t\t\t\t\t\t\t\tcandidate.instance.serviceId,\n\t\t\t\t\t\t\t\tmethodName,\n\t\t\t\t\t\t\t\treqBytes,\n\t\t\t\t\t\t\t\trequestId,\n\t\t\t\t\t\t\t\tidempotencyKey,\n\t\t\t\t\t\t\t\ttimeoutMs,\n\t\t\t\t\t\t\t\tschema.contractHash,\n\t\t\t\t\t\t\t);\n\t\t\t\t\tcallOp?.captureOut(respBytes, schema.contractHash);\n\t\t\t\t\treturn schema.pair.output.decode(respBytes) as Res;\n\t\t\t\t};\n\t\t\t\tconst result = (await runWithTrace(childCtx, invoke)) as Res;\n\t\t\t\tcallOp.end(Status.SUCCESS);\n\t\t\t\tthis.cb.recordSuccess(cbKey(candidate.instance));\n\t\t\t\treturn result;\n\t\t\t} catch (err) {\n\t\t\t\tlastErr = err;\n\t\t\t\tthis.cb.recordFailure(cbKey(candidate.instance));\n\t\t\t\tif (\n\t\t\t\t\tattempt === retry.maxAttempts - 1 ||\n\t\t\t\t\t!isRetryable(err, hasIdempotency)\n\t\t\t\t) {\n\t\t\t\t\tcallOp.end(\n\t\t\t\t\t\tStatus.ERROR,\n\t\t\t\t\t\terr instanceof Error ? err.message : String(err),\n\t\t\t\t\t);\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t\tawait sleep(backoffDelay(retry, attempt));\n\t\t\t} finally {\n\t\t\t\trelease();\n\t\t\t}\n\t\t}\n\t\t// unreachable, but keep TS happy\n\t\tthrow lastErr as Error;\n\t}\n\n\t// pickCandidate resolves descriptor + instance via the instance cache,\n\t// filters by contract hash, runs P2C through the LB, and surfaces the\n\t// errors callers need to map onto retry decisions.\n\tprivate pickCandidate(\n\t\tserviceName: string,\n\t\tmethodName: string,\n\t\tcallerHash: string,\n\t\ttransport: \"direct\" | \"proxy\" | \"auto\",\n\t): Candidate {\n\t\tconst all = this.instances\n\t\t\t.pickAll(serviceName, methodName)\n\t\t\t.filter((c) => c.descriptor.contractHash === callerHash);\n\t\tif (all.length === 0) {\n\t\t\tthrow Object.assign(\n\t\t\t\tnew Error(\n\t\t\t\t\t`rpc: no instance of ${serviceName}/${methodName} matches caller contract ${callerHash}`,\n\t\t\t\t),\n\t\t\t\t{ code: 14 },\n\t\t\t);\n\t\t}\n\t\tconst candidate = this.lb.pick(all);\n\t\tif (transport === \"direct\" && !candidate.instance.callEndpoint) {\n\t\t\tthrow new Error(\n\t\t\t\t`rpc: transport=\"direct\" requested but no endpoint for ${serviceName}/${methodName} matching contract ${callerHash}`,\n\t\t\t);\n\t\t}\n\t\treturn candidate;\n\t}\n\n\tprivate shouldUseDirect(\n\t\tcandidate: Candidate,\n\t\ttransport: \"direct\" | \"proxy\" | \"auto\",\n\t): boolean {\n\t\treturn (\n\t\t\tthis.directTransport !== null &&\n\t\t\ttransport !== \"proxy\" &&\n\t\t\tcandidate.instance.callEndpoint !== \"\"\n\t\t);\n\t}\n}\n\n// formatRpcCallSubject mirrors Go's telemetry.FormatSubject(ChannelRPC, KindRPCCall, svc, method)\n// → \"rpc.call:<svc>/<method>\" (ADR-T-019).\nfunction formatRpcCallSubject(serviceName: string, methodName: string): string {\n\treturn `rpc.call:${serviceName}/${methodName}`;\n}\n\nfunction sleep(ms: number): Promise<void> {\n\treturn new Promise((r) => setTimeout(r, ms));\n}\n\nfunction parseTimeout(s: string | undefined): number | undefined {\n\tif (!s) return undefined;\n\tconst m = /^(\\d+)(ms|s|m)$/.exec(s.trim());\n\tif (!m) throw new Error(`rpc: invalid timeout ${s}`);\n\tconst n = Number.parseInt(m[1]!, 10);\n\tswitch (m[2]) {\n\t\tcase \"ms\":\n\t\t\treturn n;\n\t\tcase \"s\":\n\t\t\treturn n * 1000;\n\t\tcase \"m\":\n\t\t\treturn n * 60_000;\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\n// SchemaRegistry is the caller-side mapping from (serviceName, methodName)\n// to a SchemaPair. Populated by ServiceBridge when the user calls\n// sb.service(..., { schemas: ... }) or directly via a low-level setter that\n// registers the same .proto schemas used by callees.\nexport class SchemaRegistry {\n\tprivate map = new Map<string, CallerSchema>();\n\n\tset(serviceName: string, methodName: string, pair: SchemaPair): void {\n\t\tthis.map.set(`${serviceName}/${methodName}`, {\n\t\t\tpair,\n\t\t\tcontractHash: computeContractHash(pair),\n\t\t});\n\t}\n\n\tget(serviceName: string, methodName: string): CallerSchema | undefined {\n\t\treturn this.map.get(`${serviceName}/${methodName}`);\n\t}\n\n\tasResolver(): SchemaResolver {\n\t\treturn (service, method) => this.get(service, method);\n\t}\n}\n","// context.ts — AsyncLocalStorage-based trace context carrier.\n// Consumers import runWithTrace + currentTraceContext.\n// @internal — см. ./README.md\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { TraceContext } from \"./trace-context\";\n\n/**\n * @internal — exported only for hook-style frameworks (Fastify) that need\n * `als.enterWith(ctx)` because they don't expose a next() callback.\n */\nexport const als = new AsyncLocalStorage<TraceContext>();\n\n/**\n * Run fn inside a trace context scope. All async continuations spawned from fn\n * inherit the context automatically via Node/Bun AsyncLocalStorage.\n */\nexport function runWithTrace<T>(ctx: TraceContext, fn: () => T): T {\n\treturn als.run(ctx, fn);\n}\n\n/**\n * Return the active trace context, or undefined if outside any runWithTrace scope.\n */\nexport function currentTraceContext(): TraceContext | undefined {\n\treturn als.getStore();\n}\n\n// streamWithContext wraps an async-generator factory so that each chunk\n// iteration runs inside the given ALS context. This is necessary because\n// Bun/Node ALS does NOT propagate through async-generator continuations\n// based solely on where the generator object was constructed — each .next()\n// inherits the context of its call-site, not the construction site.\nexport async function* streamWithContext<T>(\n\tctx: TraceContext,\n\tgen: () => AsyncIterable<T>,\n): AsyncIterable<T> {\n\tconst iter = gen()[Symbol.asyncIterator]();\n\twhile (true) {\n\t\tconst result = await als.run(ctx, () => iter.next());\n\t\tif (result.done) break;\n\t\tyield result.value;\n\t}\n}\n","// ops.ts — OpHandle for SDK-side operation lifecycle (START + END frames).\n// START frame = OpReport without finished_at_ms.\n// END frame = OpReport with finished_at_ms set.\n// @public — см. ./README.md\n\nimport { uuidv7 } from \"uuidv7\";\nimport {\n\tChannel,\n\ttype OpReport,\n\ttype PayloadAttachment,\n\tStatus,\n} from \"../pb/servicebridge/v1/telemetry\";\nimport { currentTraceContext } from \"./context\";\nimport {\n\ttype CapturedAttachment,\n\ttype CaptureMode,\n\tcapPayload,\n\tDEFAULT_PAYLOAD_MAX_BYTES,\n\tresolveCaptureMode,\n} from \"./payload-capture\";\nimport type { TelemetryRing } from \"./ring\";\nimport { ZERO_OP_ID } from \"./trace-context\";\n\nexport { Channel, Status };\n\n// Runtime queues `meta`/`attrs` JSON via `jsonOrNull(buf)` — an empty buffer\n// becomes SQL NULL, which violates the NOT NULL constraint on operations.meta\n// and operations.attrs. Default to '{}' so the START frame always carries a\n// valid JSON object.\nconst EMPTY_JSON_OBJECT = Buffer.from(\"{}\");\n\n// OpKind numeric values per-channel (mirrors Go enums.go).\nexport const RpcCall = 1;\nexport const EventPublish = 1;\nexport const EventDeliver = 2;\nexport const WorkflowRun = 1;\nexport const WorkflowSleep = 2;\nexport const WorkflowWaitEvent = 3;\nexport const WorkflowWaitSignal = 4;\nexport const JobExec = 1;\nexport const HttpHandle = 1;\nexport const UserSubOp = 1;\n\nexport interface StartOpParams {\n\t/** Required when called directly without ALS context. Otherwise inherited. */\n\ttraceId?: string;\n\t/** Auto-minted UUIDv7 when omitted. */\n\topId?: string;\n\t/** Auto-resolved from currentTraceContext().parentOpId when omitted. */\n\tparentOpId?: string;\n\tchannel: Channel;\n\tkind: number;\n\tsubject: string;\n\tpeerServiceId?: string;\n\tbusinessKey?: string;\n\tattempt?: number;\n\tstartedAtMs?: number;\n\tmetaJson?: Buffer;\n\tattrsJson?: Buffer;\n\t/**\n\t * Per-handler capture override. May only narrow the runtime-pushed effective\n\t * mode (privacy ordering none < errors < all), never widen it.\n\t */\n\tcaptureMode?: CaptureMode;\n\t/**\n\t * Runtime-pushed effective capture mode (from the registry stream). The\n\t * single authority for what may be captured. Defaults to \"none\" until the\n\t * first registry snapshot arrives (fail-safe).\n\t */\n\teffectiveCaptureMode?: CaptureMode;\n\t/**\n\t * Per-direction payload byte cap for captured payloads. Defaults to\n\t * DEFAULT_PAYLOAD_MAX_BYTES; threaded from ServiceBridgeOptions.payloadMaxBytes.\n\t */\n\tpayloadMaxBytes?: number;\n}\n\ninterface ResolvedParams {\n\ttraceId: string;\n\topId: string;\n\tparentOpId: string;\n\tchannel: Channel;\n\tkind: number;\n\tsubject: string;\n\tpeerServiceId: string;\n\tbusinessKey: string;\n\tattempt: number;\n\tmetaJson: Buffer;\n\tattrsJson: Buffer;\n\tcaptureMode: CaptureMode;\n\tpayloadMaxBytes: number;\n}\n\n// OpHandle controls the END frame for an in-flight operation.\n// @public — см. ./README.md\nexport class OpHandle {\n\tprivate readonly ring: TelemetryRing;\n\tprivate readonly params: ResolvedParams;\n\tprivate readonly startedAtMs: number;\n\tprivate ended = false;\n\t// Buffered attachments for \"errors\" mode — emitted on ERROR end, dropped on\n\t// OK. Keyed by direction (1=IN, 2=OUT) so a re-capture of the same direction\n\t// (e.g. OUT on retry) overwrites last-wins instead of buffering a duplicate.\n\tprivate readonly bufferedPayloads = new Map<number, CapturedAttachment>();\n\n\tprivate constructor(\n\t\tring: TelemetryRing,\n\t\tparams: ResolvedParams,\n\t\tstartedAtMs: number,\n\t) {\n\t\tthis.ring = ring;\n\t\tthis.params = params;\n\t\tthis.startedAtMs = startedAtMs;\n\t}\n\n\t/**\n\t * Start an operation, enqueue the START frame, return a handle for END.\n\t * traceId / parentOpId default to the active TraceContext from ALS\n\t * (set via runWithTrace). opId is auto-minted as a fresh UUIDv7.\n\t */\n\tstatic start(ring: TelemetryRing, params: StartOpParams): OpHandle {\n\t\tconst ctx = currentTraceContext();\n\t\tconst traceId = params.traceId ?? ctx?.traceId ?? uuidv7();\n\t\tconst parentOpId = params.parentOpId ?? ctx?.parentOpId ?? ZERO_OP_ID;\n\t\tconst opId = params.opId ?? uuidv7();\n\t\tconst startedAtMs = params.startedAtMs ?? Date.now();\n\n\t\tconst resolved: ResolvedParams = {\n\t\t\ttraceId,\n\t\t\topId,\n\t\t\tparentOpId,\n\t\t\tchannel: params.channel,\n\t\t\tkind: params.kind,\n\t\t\tsubject: params.subject,\n\t\t\tpeerServiceId: params.peerServiceId ?? \"\",\n\t\t\tbusinessKey: params.businessKey ?? \"\",\n\t\t\tattempt: params.attempt ?? 0,\n\t\t\tmetaJson: params.metaJson ?? EMPTY_JSON_OBJECT,\n\t\t\tattrsJson: params.attrsJson ?? EMPTY_JSON_OBJECT,\n\t\t\tcaptureMode: resolveCaptureMode(\n\t\t\t\tparams.effectiveCaptureMode ?? \"none\",\n\t\t\t\tparams.captureMode,\n\t\t\t),\n\t\t\tpayloadMaxBytes: params.payloadMaxBytes ?? DEFAULT_PAYLOAD_MAX_BYTES,\n\t\t};\n\n\t\tconst handle = new OpHandle(ring, resolved, startedAtMs);\n\t\thandle.enqueueStartFrame();\n\t\treturn handle;\n\t}\n\n\t/** Op identifier for this in-flight op (UUIDv7). */\n\tget opId(): string {\n\t\treturn this.params.opId;\n\t}\n\n\t/**\n\t * Record the retry attempt count on this in-flight op. The END frame carries\n\t * the final value so a single RPC.CALL row reflects how many tries it took\n\t * (ADR-0037..0042). No new row is minted per attempt.\n\t */\n\tsetAttempt(attempt: number): void {\n\t\tthis.params.attempt = attempt;\n\t}\n\n\t/** Trace identifier this op belongs to. */\n\tget traceId(): string {\n\t\treturn this.params.traceId;\n\t}\n\n\t/**\n\t * Capture the inbound (request/input) payload for this op. Direction = IN.\n\t * \"all\" emits immediately; \"errors\" buffers until end; \"none\" is a no-op.\n\t */\n\tcaptureIn(bytes: Uint8Array, contractHash: string): void {\n\t\tthis.capture(1, bytes, contractHash);\n\t}\n\n\t/**\n\t * Capture the outbound (response/output) payload for this op. Direction = OUT.\n\t */\n\tcaptureOut(bytes: Uint8Array, contractHash: string): void {\n\t\tthis.capture(2, bytes, contractHash);\n\t}\n\n\tprivate capture(\n\t\tdirection: number,\n\t\tbytes: Uint8Array,\n\t\tcontractHash: string,\n\t): void {\n\t\tif (this.params.captureMode === \"none\") return;\n\t\tconst { bytes: capped, originalSize } = capPayload(\n\t\t\tbytes,\n\t\t\tthis.params.payloadMaxBytes,\n\t\t);\n\t\tconst att: CapturedAttachment = {\n\t\t\tdirection,\n\t\t\tbytes: capped,\n\t\t\toriginalSize,\n\t\t\tcontractHash,\n\t\t};\n\t\tif (this.params.captureMode === \"all\") {\n\t\t\tthis.emitPayload(att);\n\t\t} else {\n\t\t\t// \"errors\": hold until end() learns the status. Last-wins per direction.\n\t\t\tthis.bufferedPayloads.set(direction, att);\n\t\t}\n\t}\n\n\tprivate emitPayload(att: CapturedAttachment): void {\n\t\tconst msg: PayloadAttachment = {\n\t\t\ttraceId: this.params.traceId,\n\t\t\topId: this.params.opId,\n\t\t\tdirection: att.direction,\n\t\t\tbytes: Buffer.from(att.bytes),\n\t\t\toriginalSize: att.originalSize,\n\t\t\tcontractHash: att.contractHash,\n\t\t};\n\t\tthis.ring.push(\"payloads\", msg);\n\t}\n\n\t/**\n\t * End the operation, enqueue the END frame.\n\t * Idempotent — calling end() twice is a no-op.\n\t */\n\tend(status: Status, statusMessage?: string): void {\n\t\tif (this.ended) return;\n\t\tthis.ended = true;\n\t\tthis.flushBufferedPayloads(status);\n\t\tthis.enqueueEndFrame(status, statusMessage ?? \"\");\n\t}\n\n\t// flushBufferedPayloads emits \"errors\"-mode buffered attachments when the op\n\t// failed, and clears the buffer either way. Statuses other than OK/RUNNING\n\t// (ERROR, TIMEOUT, ABANDONED) count as failures worth capturing.\n\tprivate flushBufferedPayloads(status: Status): void {\n\t\tconst failed = status !== Status.SUCCESS && status !== Status.PENDING;\n\t\tif (failed) {\n\t\t\tfor (const att of this.bufferedPayloads.values()) this.emitPayload(att);\n\t\t}\n\t\tthis.bufferedPayloads.clear();\n\t}\n\n\tprivate enqueueStartFrame(): void {\n\t\tconst report: OpReport = {\n\t\t\ttraceId: this.params.traceId,\n\t\t\topId: this.params.opId,\n\t\t\tparentOpId: this.params.parentOpId,\n\t\t\tchannel: this.params.channel,\n\t\t\tkind: this.params.kind,\n\t\t\tsubject: this.params.subject,\n\t\t\tpeerServiceId: this.params.peerServiceId,\n\t\t\tbusinessKey: this.params.businessKey,\n\t\t\tattempt: this.params.attempt,\n\t\t\tstartedAtMs: this.startedAtMs,\n\t\t\tfinishedAtMs: undefined,\n\t\t\tstatus: Status.PENDING,\n\t\t\tstatusMessage: \"\",\n\t\t\tmetaJson: this.params.metaJson,\n\t\t\tattrsJson: this.params.attrsJson,\n\t\t};\n\t\tthis.ring.push(\"ops\", report);\n\t}\n\n\tprivate enqueueEndFrame(status: Status, statusMessage: string): void {\n\t\t// END delta: only fields that change from START. Runtime upserts finished op.\n\t\tconst report: OpReport = {\n\t\t\ttraceId: this.params.traceId,\n\t\t\topId: this.params.opId,\n\t\t\tparentOpId: \"\",\n\t\t\tchannel: this.params.channel,\n\t\t\tkind: this.params.kind,\n\t\t\tsubject: \"\",\n\t\t\tpeerServiceId: \"\",\n\t\t\tbusinessKey: \"\",\n\t\t\tattempt: this.params.attempt,\n\t\t\tstartedAtMs: 0,\n\t\t\tfinishedAtMs: Date.now(),\n\t\t\tstatus,\n\t\t\tstatusMessage,\n\t\t\tmetaJson: Buffer.alloc(0),\n\t\t\tattrsJson: Buffer.alloc(0),\n\t\t};\n\t\tthis.ring.push(\"ops\", report);\n\t}\n}\n","// payload-capture.ts — SDK-side payload capture engine.\n//\n// Three modes applied per-op: \"all\" emits captured payloads immediately,\n// \"errors\" buffers them and emits only when the op fails, \"none\" captures\n// nothing. The mode is NOT an SDK setting — the runtime is the single authority\n// and pushes a per-channel mode set over the registry stream. An op resolves the\n// pushed mode for its own channel; a per-handler override may only NARROW it\n// (privacy ordering NONE < ERRORS < ALL), never widen it. Payloads larger than\n// the configured cap are truncated while the original byte length is preserved\n// for UI badges.\n// @public — см. ./README.md\n\nexport type CaptureMode = \"all\" | \"errors\" | \"none\";\n\n// Default per-direction payload byte cap, used when the caller passes no\n// explicit cap. Overridable via ServiceBridgeOptions.payloadMaxBytes.\n// @public — см. ./README.md\nexport const DEFAULT_PAYLOAD_MAX_BYTES = 65536;\n\nconst VALID_MODES: ReadonlySet<string> = new Set([\"all\", \"errors\", \"none\"]);\n\n// Privacy ordering: a higher rank captures strictly more. Narrowing picks the\n// lower rank (more private). NONE < ERRORS < ALL.\nconst PRIVACY_RANK: Record<CaptureMode, number> = {\n\tnone: 0,\n\terrors: 1,\n\tall: 2,\n};\n\n// resolveCaptureMode computes the effective mode for an op from the\n// runtime-pushed mode and an optional per-handler override. The override can\n// only narrow (lower the privacy rank), never widen beyond what the runtime\n// permits. Invalid pushed modes fail safe to \"none\"; an invalid override is\n// ignored (the pushed mode stands).\n// @public — см. ./README.md\nexport function resolveCaptureMode(\n\tpushed: CaptureMode,\n\tperHandler?: CaptureMode,\n): CaptureMode {\n\tconst effective: CaptureMode = VALID_MODES.has(pushed) ? pushed : \"none\";\n\tif (!perHandler || !VALID_MODES.has(perHandler)) return effective;\n\t// Narrow only: keep whichever captures less.\n\treturn PRIVACY_RANK[perHandler] < PRIVACY_RANK[effective]\n\t\t? perHandler\n\t\t: effective;\n}\n\n// capPayload truncates bytes to maxBytes and reports the original length so the\n// UI can badge \"truncated (original N)\". maxBytes defaults to\n// DEFAULT_PAYLOAD_MAX_BYTES; a non-finite or non-positive value falls back to it.\n// @public — см. ./README.md\nexport function capPayload(\n\tbytes: Uint8Array,\n\tmaxBytes: number = DEFAULT_PAYLOAD_MAX_BYTES,\n): {\n\tbytes: Uint8Array;\n\toriginalSize: number;\n} {\n\tconst cap =\n\t\tNumber.isFinite(maxBytes) && maxBytes > 0\n\t\t\t? maxBytes\n\t\t\t: DEFAULT_PAYLOAD_MAX_BYTES;\n\tconst originalSize = bytes.byteLength;\n\tif (originalSize <= cap) return { bytes, originalSize };\n\treturn { bytes: bytes.subarray(0, cap), originalSize };\n}\n\n// CapturedAttachment is one direction's captured (already capped) payload.\n// @public — см. ./README.md\nexport interface CapturedAttachment {\n\tdirection: number; // 1=IN, 2=OUT\n\tbytes: Uint8Array;\n\toriginalSize: number;\n\tcontractHash: string;\n}\n","// trace-context.ts — UUID-based trace context (ADR T-017).\n// traceId and parentOpId are RFC 9562 UUID strings.\n// @internal — см. ./README.md\n\nimport { uuidv7 } from \"uuidv7\";\n\n/** All-zeros UUID used as sentinel parentOpId for root operations. */\nexport const ZERO_OP_ID = \"00000000-0000-0000-0000-000000000000\";\n\nexport interface TraceContext {\n\ttraceId: string;\n\tparentOpId: string;\n}\n\n/** Mint a new root trace context with a fresh UUIDv7 traceId. */\nexport function mintRootContext(): TraceContext {\n\treturn {\n\t\ttraceId: uuidv7(),\n\t\tparentOpId: ZERO_OP_ID,\n\t};\n}\n\n/**\n * Derive a child context: inherits traceId, sets parentOpId to newOpId.\n * Use when a parent operation (newOpId) spawns a nested call and needs\n * to propagate the trace with the parent as the new context root.\n */\nexport function childContext(\n\tparent: TraceContext,\n\tnewOpId: string,\n): TraceContext {\n\treturn {\n\t\ttraceId: parent.traceId,\n\t\tparentOpId: newOpId,\n\t};\n}\n","import type {\n\tMethodDescriptor,\n\tServiceInstanceInfo,\n} from \"../pb/servicebridge/v1/registry\";\nimport type { CircuitBreakerRegistry } from \"./circuit-breaker\";\n\n// Power-of-Two-Choices load balancer with per-pod inflight tracking (ADR 0009).\n// Local CB filter excludes OPEN instances; runtime `is_unhealthy_since_unix_ms` hint\n// excludes instances marked unhealthy by the runtime within the last\n// HEALTH_HINT_TTL_MS. After the TTL the hint is treated as stale (runtime may\n// itself be broken) and the local CB carries the routing decision.\n//\n// @internal — см. ./README.md\n\n// HEALTH_HINT_TTL_MS bounds how long a runtime-supplied unhealthy hint is\n// trusted. Bound = 2× the runtime HealthTracker healing window (ADR 0009 §3).\nexport const HEALTH_HINT_TTL_MS = 60_000;\n\nexport interface Candidate {\n\tdescriptor: MethodDescriptor;\n\tinstance: ServiceInstanceInfo;\n\t// isUnhealthyAt is the wall-clock time the runtime first marked this\n\t// instance unhealthy through the watch snapshot (ADR 0009 §3). Null when\n\t// the runtime has no opinion or has not yet wired the hint.\n\tisUnhealthyAt: Date | null;\n}\n\nexport class NoLiveInstanceError extends Error {\n\tconstructor(message?: string) {\n\t\tsuper(message ?? \"rpc: no live instance\");\n\t\tthis.name = \"NoLiveInstanceError\";\n\t}\n}\n\nexport class LoadBalancer {\n\tprivate inflight = new Map<string, number>();\n\tprivate now: () => number;\n\tprivate random: () => number;\n\n\tconstructor(\n\t\tprivate readonly cb: CircuitBreakerRegistry,\n\t\topts?: { now?: () => number; random?: () => number },\n\t) {\n\t\tthis.now = opts?.now ?? Date.now;\n\t\tthis.random = opts?.random ?? Math.random;\n\t}\n\n\t// pick selects an eligible candidate via Power of Two Choices. Eligibility:\n\t// - candidate has a non-empty call_endpoint\n\t// - the runtime health hint is stale or absent\n\t// - the local circuit breaker is not OPEN for the instance\n\t// Throws NoLiveInstanceError when no candidate is eligible. Picking is\n\t// random when fewer than two eligible candidates exist or when inflight\n\t// counters tie. Caller MUST pair every successful pick with a `release`\n\t// call in a finally block so inflight stays balanced.\n\tpick(candidates: Candidate[]): Candidate {\n\t\tconst now = this.now();\n\t\tconst live = candidates.filter((c) => {\n\t\t\tif (!c.instance.callEndpoint) return false;\n\t\t\tconst hintActive =\n\t\t\t\tc.isUnhealthyAt !== null &&\n\t\t\t\tnow - c.isUnhealthyAt.getTime() < HEALTH_HINT_TTL_MS;\n\t\t\tif (hintActive) return false;\n\t\t\treturn this.cb.state(cbKey(c.instance)) !== \"OPEN\";\n\t\t});\n\t\tif (live.length === 0) throw new NoLiveInstanceError();\n\t\tif (live.length === 1) return live[0]!;\n\n\t\tconst i = Math.floor(this.random() * live.length);\n\t\tlet j = Math.floor(this.random() * (live.length - 1));\n\t\tif (j >= i) j++;\n\t\tconst a = live[i]!;\n\t\tconst b = live[j]!;\n\t\tconst ai = this.inflight.get(a.instance.instanceId) ?? 0;\n\t\tconst bi = this.inflight.get(b.instance.instanceId) ?? 0;\n\t\treturn ai <= bi ? a : b;\n\t}\n\n\t// acquire increments the inflight counter for an instance before the call\n\t// is dispatched. Always returns a matching release closure that decrements\n\t// the counter exactly once.\n\tacquire(instanceId: string): () => void {\n\t\tthis.inflight.set(instanceId, (this.inflight.get(instanceId) ?? 0) + 1);\n\t\tlet released = false;\n\t\treturn () => {\n\t\t\tif (released) return;\n\t\t\treleased = true;\n\t\t\tconst cur = this.inflight.get(instanceId) ?? 0;\n\t\t\tif (cur <= 1) {\n\t\t\t\tthis.inflight.delete(instanceId);\n\t\t\t} else {\n\t\t\t\tthis.inflight.set(instanceId, cur - 1);\n\t\t\t}\n\t\t};\n\t}\n\n\t// inflightOf returns the current inflight count — for tests / metrics.\n\tinflightOf(instanceId: string): number {\n\t\treturn this.inflight.get(instanceId) ?? 0;\n\t}\n}\n\nexport function cbKey(instance: ServiceInstanceInfo): string {\n\treturn `${instance.serviceId}:${instance.instanceId}`;\n}\n","import type { RetryOpts } from \"./client\";\n\n// Retry policy defaults — match the contract from the original user spec:\n// retry: { maxAttempts: 3, baseDelayMs: 200, factor: 2, maxDelayMs: 5000, jitter: 0.3 }\nexport const DEFAULT_RETRY: RetryOpts = {\n\tmaxAttempts: 3,\n\tbaseDelayMs: 200,\n\tfactor: 2,\n\tmaxDelayMs: 5000,\n\tjitter: 0.3,\n};\n\n// gRPC status codes — keep numeric to avoid a circular import on grpc-js.\nexport const GRPC_CODE_UNAVAILABLE = 14;\nexport const GRPC_CODE_RESOURCE_EXHAUSTED = 8;\nexport const GRPC_CODE_DEADLINE_EXCEEDED = 4;\nexport const GRPC_CODE_INTERNAL = 13;\nexport const GRPC_CODE_ABORTED = 10;\nexport const GRPC_CODE_UNKNOWN = 2;\n\n// Codes that are always safe to retry — transient by definition.\nconst ALWAYS_RETRYABLE = new Set([\n\tGRPC_CODE_UNAVAILABLE,\n\tGRPC_CODE_RESOURCE_EXHAUSTED,\n\tGRPC_CODE_DEADLINE_EXCEEDED,\n]);\n\n// Codes safe to retry ONLY when the caller passed an idempotency_key — the\n// runtime de-dups replays so a second invocation cannot create a double effect\n// (ADR 0012).\nconst RETRYABLE_WITH_IDEMPOTENCY = new Set([\n\tGRPC_CODE_INTERNAL,\n\tGRPC_CODE_ABORTED,\n\tGRPC_CODE_UNKNOWN,\n]);\n\nexport function mergeRetryOpts(override?: Partial<RetryOpts>): RetryOpts {\n\treturn { ...DEFAULT_RETRY, ...(override ?? {}) };\n}\n\n// isRetryable inspects a thrown gRPC-js error (or any object with a `.code`)\n// and decides whether to retry. Errors without a numeric `.code` are treated\n// as non-retryable (application errors thrown by the handler, schema errors).\nexport function isRetryable(err: unknown, hasIdempotency: boolean): boolean {\n\tconst code = (err as { code?: unknown })?.code;\n\tif (typeof code !== \"number\") return false;\n\tif (ALWAYS_RETRYABLE.has(code)) return true;\n\tif (hasIdempotency && RETRYABLE_WITH_IDEMPOTENCY.has(code)) return true;\n\treturn false;\n}\n\n// backoffDelay returns the actual sleep duration for attempt N (0-indexed)\n// given the policy. Formula:\n// delay = min(baseDelayMs * factor^attempt, maxDelayMs)\n// actual = delay * (1 - jitter + random * 2 * jitter)\nexport function backoffDelay(\n\topts: RetryOpts,\n\tattempt: number,\n\trand: () => number = Math.random,\n): number {\n\tconst raw = Math.min(\n\t\topts.baseDelayMs * opts.factor ** attempt,\n\t\topts.maxDelayMs,\n\t);\n\tconst factor = 1 - opts.jitter + rand() * 2 * opts.jitter;\n\treturn Math.max(0, Math.round(raw * factor));\n}\n","import type { PeerCertificate } from \"node:tls\";\nimport * as grpc from \"@grpc/grpc-js\";\nimport { derToPem } from \"../connection/pem\";\nimport { SPIFFE_TRUST_DOMAIN } from \"../connection/spiffe\";\nimport { CallClient, type StreamChunk } from \"../pb/servicebridge/v1/call\";\nimport { currentTraceContext } from \"../telemetry/context\";\nimport { formatXSbTrace } from \"../telemetry/wire-trace\";\n\n// X_SB_TRACE_HEADER is the gRPC metadata key the runtime + callee read for\n// trace context propagation (T-017). Keep in sync with rpc/server.go.\nconst X_SB_TRACE_HEADER = \"x-sb-trace\";\n\n// currentTraceHeader returns the X-SB-Trace wire value for the active ALS\n// trace context, or empty string when no context is in scope. Both the gRPC\n// metadata header and the CallRequest.xSbTrace body field must carry it —\n// the runtime reads the header (Invoke path), the SDK CallServer reads the\n// body field (Direct path).\nfunction currentTraceHeader(): string {\n\tconst ctx = currentTraceContext();\n\tif (!ctx) return \"\";\n\treturn formatXSbTrace(ctx.traceId, ctx.parentOpId);\n}\n\n// buildTraceMetadata mints a Metadata with x-sb-trace set from the active ALS\n// trace context, or an empty Metadata when no context is in scope.\nfunction buildTraceMetadata(header: string): grpc.Metadata {\n\tconst md = new grpc.Metadata();\n\tif (header) {\n\t\tmd.set(X_SB_TRACE_HEADER, header);\n\t}\n\treturn md;\n}\n\n// DirectCredentials are the same DER-encoded creds the SDK obtained from\n// Bootstrap.Provision. Caller uses them as client cert; the same CA chain\n// is the trust anchor for callee server cert.\nexport interface DirectCredentials {\n\tcaChainDer: Buffer;\n\tleafCertDer: Buffer;\n\tprivateKeyDer: Buffer;\n\tnotAfterUnix: bigint;\n}\n\n// DirectTarget is the resolved (endpoint, identity) pair used to build a\n// SPIFFE-validating gRPC channel.\nexport interface DirectTarget {\n\tendpoint: string; // host:port from ServiceInstanceInfo.call_endpoint\n\tserviceId: string; // expected SPIFFE service id\n\tinstanceId: string; // expected SPIFFE instance id\n}\n\ninterface CacheEntry {\n\tclient: CallClient;\n\texpiresAt: number; // ms epoch — entry discarded after this\n}\n\n// TTL is set to min(caller leaf cert lifetime, configured lead) - 5min so\n// the cache is invalidated before the cert that signs it expires.\nconst TTL_LEAD_MS = 5 * 60 * 1000;\n\n// DirectTransport maintains per-endpoint gRPC clients with mTLS + SPIFFE\n// verification of the callee's leaf cert. Endpoint addresses come from the\n// registry (ServiceInstanceInfo.call_endpoint).\n//\n// @internal — см. ./README.md\nexport class DirectTransport {\n\tprivate cache = new Map<string, CacheEntry>();\n\tprivate credsEpoch = 0;\n\n\tconstructor(private creds: DirectCredentials) {}\n\n\t// updateCredentials rotates the caller's cert (overlap rotation in\n\t// service-bridge.ts). All cached connections are dropped — they used the\n\t// previous cert and will reject after rotation.\n\tupdateCredentials(creds: DirectCredentials): void {\n\t\tthis.creds = creds;\n\t\tthis.credsEpoch++;\n\t\tfor (const [endpoint, entry] of this.cache) {\n\t\t\tentry.client.close();\n\t\t\tthis.cache.delete(endpoint);\n\t\t}\n\t}\n\n\tclose(): void {\n\t\tfor (const [endpoint, entry] of this.cache) {\n\t\t\tentry.client.close();\n\t\t\tthis.cache.delete(endpoint);\n\t\t}\n\t}\n\n\t// callUnary opens (or reuses) a direct channel to target.endpoint and issues\n\t// Call.Unary. Returns the response payload bytes on success.\n\t// callStream — direct counterpart of ProxyTransport.callStream. Mirrors the\n\t// AsyncIterable<Uint8Array> contract.\n\tasync *callStream(\n\t\ttarget: DirectTarget,\n\t\tmethod: string,\n\t\tpayload: Uint8Array,\n\t\tcallerService: string,\n\t\trequestId: string,\n\t\tidempotencyKey: string,\n\t\tdeadlineMs: number,\n\t): AsyncIterable<Uint8Array> {\n\t\tconst client = this.clientFor(target);\n\t\tconst traceHeader = currentTraceHeader();\n\t\tconst stream = client.stream(\n\t\t\t{\n\t\t\t\tmethod,\n\t\t\t\tpayload: Buffer.from(payload),\n\t\t\t\tcallerService,\n\t\t\t\trequestId,\n\t\t\t\tidempotencyKey,\n\t\t\t\txSbTrace: traceHeader,\n\t\t\t},\n\t\t\tbuildTraceMetadata(traceHeader),\n\t\t\t{ deadline: new Date(Date.now() + deadlineMs) },\n\t\t);\n\t\ttry {\n\t\t\tfor await (const chunk of stream as AsyncIterable<StreamChunk>) {\n\t\t\t\tif (chunk.errorCode) {\n\t\t\t\t\tconst err = new Error(chunk.errorMessage || chunk.errorCode);\n\t\t\t\t\terr.name = chunk.errorCode;\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t\tyield new Uint8Array(chunk.payload);\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tthis.evict(target.endpoint);\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tcallUnary(\n\t\ttarget: DirectTarget,\n\t\tmethod: string,\n\t\tpayload: Uint8Array,\n\t\tcallerService: string,\n\t\trequestId: string,\n\t\tidempotencyKey: string,\n\t\tdeadlineMs: number,\n\t): Promise<Uint8Array> {\n\t\tconst client = this.clientFor(target);\n\t\tconst traceHeader = currentTraceHeader();\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tclient.unary(\n\t\t\t\t{\n\t\t\t\t\tmethod,\n\t\t\t\t\tpayload: Buffer.from(payload),\n\t\t\t\t\tcallerService,\n\t\t\t\t\trequestId,\n\t\t\t\t\tidempotencyKey,\n\t\t\t\t\txSbTrace: traceHeader,\n\t\t\t\t},\n\t\t\t\tbuildTraceMetadata(traceHeader),\n\t\t\t\t{ deadline: new Date(Date.now() + deadlineMs) },\n\t\t\t\t(err, resp) => {\n\t\t\t\t\tif (err) {\n\t\t\t\t\t\t// Drop the conn if it is permanently bad — next call will redial.\n\t\t\t\t\t\tthis.evict(target.endpoint);\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (resp.errorCode) {\n\t\t\t\t\t\tconst appErr = new Error(resp.errorMessage || resp.errorCode);\n\t\t\t\t\t\tappErr.name = resp.errorCode;\n\t\t\t\t\t\treject(appErr);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tresolve(new Uint8Array(resp.payload));\n\t\t\t\t},\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate clientFor(target: DirectTarget): CallClient {\n\t\tconst cached = this.cache.get(target.endpoint);\n\t\tif (cached && cached.expiresAt > Date.now()) {\n\t\t\treturn cached.client;\n\t\t}\n\t\tif (cached) {\n\t\t\tcached.client.close();\n\t\t\tthis.cache.delete(target.endpoint);\n\t\t}\n\n\t\tconst caChainPem = derToPem(this.creds.caChainDer, \"CERTIFICATE\");\n\t\tconst certPem = derToPem(this.creds.leafCertDer, \"CERTIFICATE\");\n\t\tconst keyPem = derToPem(this.creds.privateKeyDer, \"PRIVATE KEY\");\n\n\t\tconst expectedSpiffe = `spiffe://${SPIFFE_TRUST_DOMAIN}/service/${target.serviceId}/instance/${target.instanceId}`;\n\n\t\tconst channelCreds = grpc.credentials.createSsl(\n\t\t\tcaChainPem,\n\t\t\tkeyPem,\n\t\t\tcertPem,\n\t\t\t{ checkServerIdentity: makeSpiffeCheck(expectedSpiffe) },\n\t\t);\n\n\t\t// SDK callee advertises host:port — `host` is often an IP (POD_IP), which\n\t\t// Node TLS rejects as servername (SNI). Override SNI with a placeholder\n\t\t// so the TLS extension carries a valid DNS-like name; SPIFFE verification\n\t\t// above is what actually authenticates the peer.\n\t\tconst client = new CallClient(target.endpoint, channelCreds, {\n\t\t\t\"grpc.ssl_target_name_override\": \"servicebridge.peer\",\n\t\t\t\"grpc.default_authority\": \"servicebridge.peer\",\n\t\t});\n\t\tconst ttlMs =\n\t\t\tNumber(this.creds.notAfterUnix) * 1000 - Date.now() - TTL_LEAD_MS;\n\t\tconst expiresAt = Date.now() + Math.max(ttlMs, 60_000);\n\t\tthis.cache.set(target.endpoint, { client, expiresAt });\n\t\treturn client;\n\t}\n\n\tprivate evict(endpoint: string): void {\n\t\tconst entry = this.cache.get(endpoint);\n\t\tif (entry) {\n\t\t\tentry.client.close();\n\t\t\tthis.cache.delete(endpoint);\n\t\t}\n\t}\n\n\t// Test-only: inspect cache size.\n\tcacheSize(): number {\n\t\treturn this.cache.size;\n\t}\n}\n\n// makeSpiffeCheck returns a Node TLS checkServerIdentity callback that asserts\n// the peer cert's SAN URI matches `expectedUri`. Without this, gRPC would only\n// verify cert chain — different instances signed by the same CA could\n// impersonate each other.\nfunction makeSpiffeCheck(\n\texpectedUri: string,\n): (hostname: string, cert: PeerCertificate) => Error | undefined {\n\treturn (_hostname, cert) => {\n\t\tconst sanUris = extractSanUris(cert);\n\t\tif (!sanUris.includes(expectedUri)) {\n\t\t\treturn new Error(\n\t\t\t\t`rpc: SPIFFE mismatch — expected ${expectedUri}, got ${sanUris.join(\", \") || \"<none>\"}`,\n\t\t\t);\n\t\t}\n\t\treturn undefined;\n\t};\n}\n\n// extractSanUris reads URI SANs from a PeerCertificate. node:tls exposes them\n// via subjectaltname (string) and infoAccess; we parse subjectaltname for \"URI:\"\n// entries — same shape on Node and Bun.\nfunction extractSanUris(cert: PeerCertificate): string[] {\n\tconst sub = (cert as PeerCertificate & { subjectaltname?: string })\n\t\t.subjectaltname;\n\tif (!sub) return [];\n\treturn sub\n\t\t.split(\",\")\n\t\t.map((s) => s.trim())\n\t\t.filter((s) => s.startsWith(\"URI:\"))\n\t\t.map((s) => s.slice(4));\n}\n","/**\n * derToPem wraps a DER buffer in PEM (label defaults to \"CERTIFICATE\").\n */\nexport function derToPem(der: Buffer, label = \"CERTIFICATE\"): Buffer {\n\tconst b64 = der.toString(\"base64\");\n\tconst lines = b64.match(/.{1,64}/g) ?? [];\n\treturn Buffer.from(\n\t\t`-----BEGIN ${label}-----\\n${lines.join(\"\\n\")}\\n-----END ${label}-----\\n`,\n\t);\n}\n","// SPIFFE_TRUST_DOMAIN is the trust domain for all ServiceBridge identities.\n// Must stay in sync with connection.SPIFFETrustDomain in the Go runtime.\nexport const SPIFFE_TRUST_DOMAIN = \"servicebridge\";\n","// Code generated by protoc-gen-ts_proto. DO NOT EDIT.\n// versions:\n// protoc-gen-ts_proto v2.11.8\n// protoc unknown\n// source: servicebridge/v1/call.proto\n\n/* eslint-disable */\nimport { BinaryReader, BinaryWriter } from \"@bufbuild/protobuf/wire\";\nimport {\n type CallOptions,\n type ChannelCredentials,\n Client,\n type ClientOptions,\n type ClientReadableStream,\n type ClientUnaryCall,\n type handleServerStreamingCall,\n type handleUnaryCall,\n makeGenericClientConstructor,\n type Metadata,\n type ServiceError,\n type UntypedServiceImplementation,\n} from \"@grpc/grpc-js\";\n\nexport interface CallRequest {\n method: string;\n payload: Buffer;\n callerService: string;\n requestId: string;\n idempotencyKey: string;\n /**\n * X-SB-Trace propagation: trace_id and parent_op_id are carried via gRPC\n * metadata under \"x-sb-trace\" key (T-017). Not in the wire message itself.\n */\n xSbTrace: string;\n}\n\nexport interface CallResponse {\n payload: Buffer;\n errorCode: string;\n errorMessage: string;\n}\n\n/** StreamChunk — один элемент server-streaming ответа. */\nexport interface StreamChunk {\n payload: Buffer;\n errorCode: string;\n errorMessage: string;\n}\n\nfunction createBaseCallRequest(): CallRequest {\n return { method: \"\", payload: Buffer.alloc(0), callerService: \"\", requestId: \"\", idempotencyKey: \"\", xSbTrace: \"\" };\n}\n\nexport const CallRequest: MessageFns<CallRequest> = {\n encode(message: CallRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.method !== \"\") {\n writer.uint32(10).string(message.method);\n }\n if (message.payload.length !== 0) {\n writer.uint32(18).bytes(message.payload);\n }\n if (message.callerService !== \"\") {\n writer.uint32(26).string(message.callerService);\n }\n if (message.requestId !== \"\") {\n writer.uint32(34).string(message.requestId);\n }\n if (message.idempotencyKey !== \"\") {\n writer.uint32(42).string(message.idempotencyKey);\n }\n if (message.xSbTrace !== \"\") {\n writer.uint32(50).string(message.xSbTrace);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): CallRequest {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseCallRequest();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.method = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.payload = Buffer.from(reader.bytes());\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.callerService = reader.string();\n continue;\n }\n case 4: {\n if (tag !== 34) {\n break;\n }\n\n message.requestId = reader.string();\n continue;\n }\n case 5: {\n if (tag !== 42) {\n break;\n }\n\n message.idempotencyKey = reader.string();\n continue;\n }\n case 6: {\n if (tag !== 50) {\n break;\n }\n\n message.xSbTrace = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<CallRequest>, I>>(base?: I): CallRequest {\n return CallRequest.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<CallRequest>, I>>(object: I): CallRequest {\n const message = createBaseCallRequest();\n message.method = object.method ?? \"\";\n message.payload = object.payload ?? Buffer.alloc(0);\n message.callerService = object.callerService ?? \"\";\n message.requestId = object.requestId ?? \"\";\n message.idempotencyKey = object.idempotencyKey ?? \"\";\n message.xSbTrace = object.xSbTrace ?? \"\";\n return message;\n },\n};\n\nfunction createBaseCallResponse(): CallResponse {\n return { payload: Buffer.alloc(0), errorCode: \"\", errorMessage: \"\" };\n}\n\nexport const CallResponse: MessageFns<CallResponse> = {\n encode(message: CallResponse, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.payload.length !== 0) {\n writer.uint32(10).bytes(message.payload);\n }\n if (message.errorCode !== \"\") {\n writer.uint32(18).string(message.errorCode);\n }\n if (message.errorMessage !== \"\") {\n writer.uint32(26).string(message.errorMessage);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): CallResponse {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseCallResponse();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.payload = Buffer.from(reader.bytes());\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.errorCode = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.errorMessage = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<CallResponse>, I>>(base?: I): CallResponse {\n return CallResponse.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<CallResponse>, I>>(object: I): CallResponse {\n const message = createBaseCallResponse();\n message.payload = object.payload ?? Buffer.alloc(0);\n message.errorCode = object.errorCode ?? \"\";\n message.errorMessage = object.errorMessage ?? \"\";\n return message;\n },\n};\n\nfunction createBaseStreamChunk(): StreamChunk {\n return { payload: Buffer.alloc(0), errorCode: \"\", errorMessage: \"\" };\n}\n\nexport const StreamChunk: MessageFns<StreamChunk> = {\n encode(message: StreamChunk, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.payload.length !== 0) {\n writer.uint32(10).bytes(message.payload);\n }\n if (message.errorCode !== \"\") {\n writer.uint32(18).string(message.errorCode);\n }\n if (message.errorMessage !== \"\") {\n writer.uint32(26).string(message.errorMessage);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): StreamChunk {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseStreamChunk();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.payload = Buffer.from(reader.bytes());\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.errorCode = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.errorMessage = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<StreamChunk>, I>>(base?: I): StreamChunk {\n return StreamChunk.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<StreamChunk>, I>>(object: I): StreamChunk {\n const message = createBaseStreamChunk();\n message.payload = object.payload ?? Buffer.alloc(0);\n message.errorCode = object.errorCode ?? \"\";\n message.errorMessage = object.errorMessage ?? \"\";\n return message;\n },\n};\n\n/**\n * Call — inbound RPC сервер SDK-инстанса.\n * Используется и в direct-режиме (caller → callee), и в proxy-режиме (runtime → callee).\n */\nexport type CallService = typeof CallService;\nexport const CallService = {\n unary: {\n path: \"/servicebridge.v1.Call/Unary\" as const,\n requestStream: false as const,\n responseStream: false as const,\n requestSerialize: (value: CallRequest): Buffer => Buffer.from(CallRequest.encode(value).finish()),\n requestDeserialize: (value: Buffer): CallRequest => CallRequest.decode(value),\n responseSerialize: (value: CallResponse): Buffer => Buffer.from(CallResponse.encode(value).finish()),\n responseDeserialize: (value: Buffer): CallResponse => CallResponse.decode(value),\n },\n /**\n * Stream — server-side streaming: каллер шлёт один запрос, callee стримит\n * chunks (например, LLM token streaming). Bidirectional streaming не в scope.\n */\n stream: {\n path: \"/servicebridge.v1.Call/Stream\" as const,\n requestStream: false as const,\n responseStream: true as const,\n requestSerialize: (value: CallRequest): Buffer => Buffer.from(CallRequest.encode(value).finish()),\n requestDeserialize: (value: Buffer): CallRequest => CallRequest.decode(value),\n responseSerialize: (value: StreamChunk): Buffer => Buffer.from(StreamChunk.encode(value).finish()),\n responseDeserialize: (value: Buffer): StreamChunk => StreamChunk.decode(value),\n },\n} as const;\n\nexport interface CallServer extends UntypedServiceImplementation {\n unary: handleUnaryCall<CallRequest, CallResponse>;\n /**\n * Stream — server-side streaming: каллер шлёт один запрос, callee стримит\n * chunks (например, LLM token streaming). Bidirectional streaming не в scope.\n */\n stream: handleServerStreamingCall<CallRequest, StreamChunk>;\n}\n\nexport interface CallClient extends Client {\n unary(request: CallRequest, callback: (error: ServiceError | null, response: CallResponse) => void): ClientUnaryCall;\n unary(\n request: CallRequest,\n metadata: Metadata,\n callback: (error: ServiceError | null, response: CallResponse) => void,\n ): ClientUnaryCall;\n unary(\n request: CallRequest,\n metadata: Metadata,\n options: Partial<CallOptions>,\n callback: (error: ServiceError | null, response: CallResponse) => void,\n ): ClientUnaryCall;\n /**\n * Stream — server-side streaming: каллер шлёт один запрос, callee стримит\n * chunks (например, LLM token streaming). Bidirectional streaming не в scope.\n */\n stream(request: CallRequest, options?: Partial<CallOptions>): ClientReadableStream<StreamChunk>;\n stream(request: CallRequest, metadata?: Metadata, options?: Partial<CallOptions>): ClientReadableStream<StreamChunk>;\n}\n\nexport const CallClient = makeGenericClientConstructor(CallService, \"servicebridge.v1.Call\") as unknown as {\n new (address: string, credentials: ChannelCredentials, options?: Partial<ClientOptions>): CallClient;\n service: typeof CallService;\n serviceName: string;\n};\n\ntype Builtin = Date | Function | Uint8Array | string | number | boolean | undefined;\n\ntype DeepPartial<T> = T extends Builtin ? T\n : T extends globalThis.Array<infer U> ? globalThis.Array<DeepPartial<U>>\n : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>>\n : T extends {} ? { [K in keyof T]?: DeepPartial<T[K]> }\n : Partial<T>;\n\ntype KeysOfUnion<T> = T extends T ? keyof T : never;\ntype Exact<P, I extends P> = P extends Builtin ? P\n : P & { [K in keyof P]: Exact<P[K], I[K]> } & { [K in Exclude<keyof I, KeysOfUnion<P>>]: never };\n\ninterface MessageFns<T> {\n encode(message: T, writer?: BinaryWriter): BinaryWriter;\n decode(input: BinaryReader | Uint8Array, length?: number): T;\n create<I extends Exact<DeepPartial<T>, I>>(base?: I): T;\n fromPartial<I extends Exact<DeepPartial<T>, I>>(object: I): T;\n}\n","// wire-trace.ts — X-SB-Trace header parse and format.\n// Format: \"<traceId>-<parentOpId>\" where both are canonical RFC 9562 UUID\n// strings. Matches runtime/internal/telemetry/header.go (T-017 / proto\n// contract). UUID itself contains '-', so the separator is identified by\n// position (36) rather than indexOf.\n// @internal — см. ./README.md\n\n// UUID pattern: 8-4-4-4-12 hex chars, case-insensitive.\nconst UUID_RE =\n\t/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n// Canonical UUID string length: 36 chars. Header total: 36 + 1 + 36 = 73.\nconst UUID_LEN = 36;\nconst HEADER_LEN = UUID_LEN + 1 + UUID_LEN;\n\nexport interface ParsedXSbTrace {\n\ttraceId: string;\n\tparentOpId: string;\n}\n\n/**\n * Parse the X-SB-Trace header value.\n * Returns null on any malformed input — caller must mint a new root context.\n */\nexport function parseXSbTrace(\n\tvalue: string | null | undefined,\n): ParsedXSbTrace | null {\n\tif (!value) return null;\n\tif (value.length !== HEADER_LEN) return null;\n\tif (value[UUID_LEN] !== \"-\") return null;\n\tconst traceId = value.slice(0, UUID_LEN);\n\tconst parentOpId = value.slice(UUID_LEN + 1);\n\tif (!UUID_RE.test(traceId) || !UUID_RE.test(parentOpId)) return null;\n\treturn { traceId, parentOpId };\n}\n\n/**\n * Format a trace context as the X-SB-Trace header value.\n */\nexport function formatXSbTrace(traceId: string, parentOpId: string): string {\n\treturn `${traceId}-${parentOpId}`;\n}\n","// RPC-domain error classes surfaced to callers.\n//\n// @public — см. ./README.md\n\n// RpcAccessDeniedError — gate #3 bilateral check failed on rpc.call\n// (caller egress rpc.call + callee acceptance rpc.handle, ADR-0014). Maps from\n// the gRPC PERMISSION_DENIED the runtime returns at call time.\nexport class RpcAccessDeniedError extends Error {\n\tconstructor(\n\t\tpublic readonly serviceName: string,\n\t\tpublic readonly methodName: string,\n\t\tpublic readonly reason: string,\n\t) {\n\t\tsuper(`rpc.call ${serviceName}/${methodName}: access denied — ${reason}`);\n\t\tthis.name = \"RpcAccessDeniedError\";\n\t}\n}\n","// @public — см. ./README.md\nimport type {\n\tRegistry,\n\tRpcHandlerFn,\n\tRpcHandlerOpts,\n\tRpcStreamHandlerFn,\n} from \"../registry/registry\";\nimport type { CallOpts, RpcClient } from \"./client\";\nimport { RpcAccessDeniedError } from \"./errors\";\n\n// gRPC PERMISSION_DENIED numeric code (matches @grpc/grpc-js).\nconst GRPC_PERMISSION_DENIED = 7;\n\n// Sink for call-time policy denials; the owner wires it to emit\n// `policy_violation`. Structural type avoids importing from connection.\ntype PolicyViolationSink = (v: {\n\tdeclaration: string;\n\tvalue: string;\n\tdenySide: string;\n\treason: string;\n}) => void;\n\nexport class RpcDomain {\n\tconstructor(\n\t\tprivate readonly registry: Registry,\n\t\tprivate readonly getClient: () => RpcClient | null,\n\t\tprivate readonly onPolicyViolation?: PolicyViolationSink,\n\t) {}\n\n\thandle<Req = unknown, Res = unknown>(\n\t\tname: string,\n\t\tfn: RpcHandlerFn<Req, Res>,\n\t\topts: RpcHandlerOpts,\n\t): void {\n\t\tthis.registry._handle.rpc(name, fn, opts);\n\t}\n\n\thandleStream<Req = unknown, Chunk = unknown>(\n\t\tname: string,\n\t\tfn: RpcStreamHandlerFn<Req, Chunk>,\n\t\topts: RpcHandlerOpts,\n\t): void {\n\t\tthis.registry._handle.stream(name, fn, opts);\n\t}\n\n\t// _declareForTests registers an RPC entry without a schema. E2E tests use this\n\t// to assemble fixtures that exercise registration paths without loading real\n\t// .proto files. Production code MUST use handle() with an explicit schema.\n\t//\n\t// @internal — см. ./README.md\n\t_declareForTests(name: string, streaming = false): void {\n\t\tthis.registry._handle._declareForTests(name, streaming);\n\t}\n\n\tasync call<Req = unknown, Res = unknown>(\n\t\tserviceName: string,\n\t\tmethodName: string,\n\t\tpayload: Req,\n\t\topts?: CallOpts,\n\t): Promise<Res> {\n\t\tconst client = this.getClient();\n\t\tif (!client) {\n\t\t\tthrow new Error(\n\t\t\t\t\"ServiceBridge: rpc client not ready — call start() and wait for 'connected' event before calling sb.rpc.call()\",\n\t\t\t);\n\t\t}\n\t\ttry {\n\t\t\treturn await client.call<Req, Res>(\n\t\t\t\tserviceName,\n\t\t\t\tmethodName,\n\t\t\t\tpayload,\n\t\t\t\topts,\n\t\t\t);\n\t\t} catch (err) {\n\t\t\t// Gate #3 denial (ADR-0014): surface as a typed, catchable error and\n\t\t\t// emit a policy_violation so call-time denials are observable on the\n\t\t\t// same channel as registration warnings.\n\t\t\tif ((err as { code?: number }).code === GRPC_PERMISSION_DENIED) {\n\t\t\t\tconst reason =\n\t\t\t\t\t(err as { details?: string }).details ||\n\t\t\t\t\t(err instanceof Error ? err.message : String(err));\n\t\t\t\tthis.onPolicyViolation?.({\n\t\t\t\t\tdeclaration: \"rpc.call\",\n\t\t\t\t\tvalue: `${serviceName}/${methodName}`,\n\t\t\t\t\tdenySide: \"self_egress\",\n\t\t\t\t\treason,\n\t\t\t\t});\n\t\t\t\tthrow new RpcAccessDeniedError(serviceName, methodName, reason);\n\t\t\t}\n\t\t\tthrow err;\n\t\t}\n\t}\n}\n","import type {\n\tMethodDescriptor,\n\tServiceInstanceInfo,\n} from \"../pb/servicebridge/v1/registry\";\nimport type { WatchStream } from \"../registry/watch\";\nimport type { Candidate } from \"./lb\";\n\n// InstanceCache joins MethodDescriptor (per-method contract) with\n// ServiceInstanceInfo (per-instance endpoint/status) using data observed via\n// WatchStream events. Used by the call client to look up target instances for\n// a given (serviceName, methodName) pair.\n//\n// Only the primary `byService` index is kept (ADR 0009 §4): at ≤1000 services\n// the per-call linear scan over methods is single-digit microseconds, whereas\n// a secondary `byServiceMethod` index needs O(methods) rebuild on every\n// snapshot tick.\n//\n// @internal — см. ./README.md\n\n// Instance bundles the registry-supplied ServiceInstanceInfo with the\n// runtime-supplied health hint. `isUnhealthyAt` is the wall-clock the runtime\n// first marked this instance unhealthy via HealthTracker (ADR-0008); null\n// means \"healthy or unknown\". The LB filter treats hints older than\n// HEALTH_HINT_TTL_MS as stale (ADR-0009 §3).\nexport interface Instance extends ServiceInstanceInfo {\n\tisUnhealthyAt: Date | null;\n}\n\nexport class InstanceCache {\n\tprivate byService = new Map<string, MethodDescriptor[]>();\n\tprivate instances = new Map<string, Instance>();\n\tprivate unsubscribe: (() => void) | null = null;\n\tprivate watch: WatchStream | null = null;\n\n\tbind(watch: WatchStream): void {\n\t\tthis.watch = watch;\n\t\tthis.refresh();\n\t\tthis.unsubscribe = watch.onInstancesChange(() => this.refresh());\n\t}\n\n\tdispose(): void {\n\t\tthis.unsubscribe?.();\n\t\tthis.unsubscribe = null;\n\t\tthis.watch = null;\n\t\tthis.byService.clear();\n\t\tthis.instances.clear();\n\t}\n\n\t// pickAll returns every (descriptor, instance) candidate for the given\n\t// (serviceName, methodName) pair where the instance is connected. Hash\n\t// filtering for contract-version routing is the caller's job — pickAll\n\t// returns all descriptors so the caller can compare hashes once after\n\t// reading the schema. Used by the LB for P2C selection.\n\tpickAll(serviceName: string, methodName: string): Candidate[] {\n\t\tconst descs = this.byService.get(serviceName);\n\t\tif (!descs || descs.length === 0) return [];\n\t\tconst out: Candidate[] = [];\n\t\tfor (const d of descs) {\n\t\t\tif (d.name !== methodName) continue;\n\t\t\tconst inst = this.instances.get(d.instanceId);\n\t\t\tif (!inst) continue;\n\t\t\tout.push({\n\t\t\t\tdescriptor: d,\n\t\t\t\tinstance: inst,\n\t\t\t\tisUnhealthyAt: inst.isUnhealthyAt,\n\t\t\t});\n\t\t}\n\t\treturn out;\n\t}\n\n\t// descriptorFor returns the contract for one (service, method) pair without\n\t// resolving an endpoint. Used to access schema during encoding when no LB\n\t// pick has yet happened.\n\tdescriptorFor(\n\t\tserviceName: string,\n\t\tmethodName: string,\n\t): MethodDescriptor | null {\n\t\tconst descs = this.byService.get(serviceName);\n\t\tif (!descs) return null;\n\t\treturn descs.find((d) => d.name === methodName) ?? null;\n\t}\n\n\tprivate refresh(): void {\n\t\tif (!this.watch) return;\n\t\tthis.instances.clear();\n\t\tfor (const [id, info] of this.watch.instancesSnapshot()) {\n\t\t\tthis.instances.set(id, {\n\t\t\t\t...info,\n\t\t\t\tisUnhealthyAt: info.isUnhealthySinceUnixMs\n\t\t\t\t\t? new Date(info.isUnhealthySinceUnixMs)\n\t\t\t\t\t: null,\n\t\t\t});\n\t\t}\n\n\t\tthis.byService.clear();\n\t\tfor (const desc of this.watch.snapshot().values()) {\n\t\t\tconst arr = this.byService.get(desc.serviceName);\n\t\t\tif (arr) arr.push(desc);\n\t\t\telse this.byService.set(desc.serviceName, [desc]);\n\t\t}\n\t}\n}\n","import { type ChannelCredentials, Metadata } from \"@grpc/grpc-js\";\nimport { type InvokeChunk, InvokeClient } from \"../pb/servicebridge/v1/invoke\";\nimport { currentTraceContext } from \"../telemetry/context\";\nimport { formatXSbTrace } from \"../telemetry/wire-trace\";\n\n// X_SB_TRACE_HEADER is the gRPC metadata key under which the runtime reads\n// the caller's trace context (T-017). Keep in sync with rpc/server.go.\nconst X_SB_TRACE_HEADER = \"x-sb-trace\";\n\n// currentTraceHeader returns the X-SB-Trace wire value for the active ALS\n// trace context, or empty string when no context is in scope. Both the gRPC\n// metadata header and the CallRequest.xSbTrace body field carry it — kept\n// in sync with direct-transport for symmetric Invoke/Direct semantics.\nfunction currentTraceHeader(): string {\n\tconst ctx = currentTraceContext();\n\tif (!ctx) return \"\";\n\treturn formatXSbTrace(ctx.traceId, ctx.parentOpId);\n}\n\n// buildTraceMetadata returns a Metadata with x-sb-trace set from the given\n// header value, or an empty Metadata when the header is empty.\nfunction buildTraceMetadata(header: string): Metadata {\n\tconst md = new Metadata();\n\tif (header) {\n\t\tmd.set(X_SB_TRACE_HEADER, header);\n\t}\n\treturn md;\n}\n\n// ProxyTransport routes outbound RPC calls through the runtime's Invoke service.\n// Reuses the SDK's mTLS credentials to the runtime — same URL and creds as the\n// Control/Registry streams. The caller-side contract hash is forwarded so the\n// runtime Resolver can filter target instances by it (ADR 0012).\n//\n// @internal — см. ./README.md\nexport class ProxyTransport {\n\tprivate client: InvokeClient;\n\n\tconstructor(runtimeAddr: string, creds: ChannelCredentials) {\n\t\tthis.client = new InvokeClient(runtimeAddr, creds);\n\t}\n\n\tclose(): void {\n\t\tthis.client.close();\n\t}\n\n\t// callStream invokes Invoke.Stream and returns an AsyncIterable of payload\n\t// bytes. Application errors (errorCode non-empty in a chunk) terminate the\n\t// iterator with a thrown Error whose name is the errorCode.\n\tasync *callStream(\n\t\ttargetServiceId: string,\n\t\tmethod: string,\n\t\tpayload: Uint8Array,\n\t\trequestId: string,\n\t\tidempotencyKey: string,\n\t\tdeadlineMs: number,\n\t\tcontractHash: string,\n\t): AsyncIterable<Uint8Array> {\n\t\tconst deadline = new Date(Date.now() + deadlineMs);\n\t\tconst traceHeader = currentTraceHeader();\n\t\tconst stream = this.client.stream(\n\t\t\t{\n\t\t\t\ttargetServiceId,\n\t\t\t\tmethod,\n\t\t\t\tpayload: Buffer.from(payload),\n\t\t\t\trequestId,\n\t\t\t\tidempotencyKey,\n\t\t\t\tcontractHash: Buffer.from(contractHash, \"utf8\"),\n\t\t\t\txSbTrace: traceHeader,\n\t\t\t},\n\t\t\tbuildTraceMetadata(traceHeader),\n\t\t\t{ deadline },\n\t\t);\n\t\tfor await (const chunk of stream as AsyncIterable<InvokeChunk>) {\n\t\t\tif (chunk.errorCode) {\n\t\t\t\tconst err = new Error(chunk.errorMessage || chunk.errorCode);\n\t\t\t\terr.name = chunk.errorCode;\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t\tyield new Uint8Array(chunk.payload);\n\t\t}\n\t}\n\n\t// callUnary forwards a single Invoke.Unary call to the runtime and resolves\n\t// with the response payload bytes. Application errors (callee handler threw)\n\t// are returned as a rejected promise with name/message set from error_code.\n\tcallUnary(\n\t\ttargetServiceId: string,\n\t\tmethod: string,\n\t\tpayload: Uint8Array,\n\t\trequestId: string,\n\t\tidempotencyKey: string,\n\t\tdeadlineMs: number,\n\t\tcontractHash: string,\n\t): Promise<Uint8Array> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst deadline = new Date(Date.now() + deadlineMs);\n\t\t\tconst traceHeader = currentTraceHeader();\n\t\t\tthis.client.unary(\n\t\t\t\t{\n\t\t\t\t\ttargetServiceId,\n\t\t\t\t\tmethod,\n\t\t\t\t\tpayload: Buffer.from(payload),\n\t\t\t\t\trequestId,\n\t\t\t\t\tidempotencyKey,\n\t\t\t\t\tcontractHash: Buffer.from(contractHash, \"utf8\"),\n\t\t\t\t\txSbTrace: traceHeader,\n\t\t\t\t},\n\t\t\t\tbuildTraceMetadata(traceHeader),\n\t\t\t\t{ deadline },\n\t\t\t\t(err, resp) => {\n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (resp.errorCode) {\n\t\t\t\t\t\tconst appErr = new Error(resp.errorMessage || resp.errorCode);\n\t\t\t\t\t\tappErr.name = resp.errorCode;\n\t\t\t\t\t\treject(appErr);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tresolve(new Uint8Array(resp.payload));\n\t\t\t\t},\n\t\t\t);\n\t\t});\n\t}\n}\n","// Code generated by protoc-gen-ts_proto. DO NOT EDIT.\n// versions:\n// protoc-gen-ts_proto v2.11.8\n// protoc unknown\n// source: servicebridge/v1/invoke.proto\n\n/* eslint-disable */\nimport { BinaryReader, BinaryWriter } from \"@bufbuild/protobuf/wire\";\nimport {\n type CallOptions,\n type ChannelCredentials,\n Client,\n type ClientOptions,\n type ClientReadableStream,\n type ClientUnaryCall,\n type handleServerStreamingCall,\n type handleUnaryCall,\n makeGenericClientConstructor,\n type Metadata,\n type ServiceError,\n type UntypedServiceImplementation,\n} from \"@grpc/grpc-js\";\n\nexport interface InvokeRequest {\n /** UUID of the target service (services.id) */\n targetServiceId: string;\n method: string;\n payload: Buffer;\n requestId: string;\n idempotencyKey: string;\n /** X-SB-Trace propagation: carried via gRPC metadata \"x-sb-trace\" (T-017). */\n xSbTrace: string;\n /**\n * Caller-side contract hash for (method input, output) schemas. Resolver\n * filters target instances to those advertising the same hash on this\n * method (ADR-0012). Empty for non-RPC paths or when the caller has no\n * schema registered — matched only against instances that advertise an\n * empty hash for the method.\n */\n contractHash: Buffer;\n}\n\nexport interface InvokeResponse {\n payload: Buffer;\n errorCode: string;\n errorMessage: string;\n}\n\n/** InvokeChunk — proxy-mirror of StreamChunk. Bytes-level passthrough. */\nexport interface InvokeChunk {\n payload: Buffer;\n errorCode: string;\n errorMessage: string;\n}\n\nfunction createBaseInvokeRequest(): InvokeRequest {\n return {\n targetServiceId: \"\",\n method: \"\",\n payload: Buffer.alloc(0),\n requestId: \"\",\n idempotencyKey: \"\",\n xSbTrace: \"\",\n contractHash: Buffer.alloc(0),\n };\n}\n\nexport const InvokeRequest: MessageFns<InvokeRequest> = {\n encode(message: InvokeRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.targetServiceId !== \"\") {\n writer.uint32(10).string(message.targetServiceId);\n }\n if (message.method !== \"\") {\n writer.uint32(18).string(message.method);\n }\n if (message.payload.length !== 0) {\n writer.uint32(26).bytes(message.payload);\n }\n if (message.requestId !== \"\") {\n writer.uint32(34).string(message.requestId);\n }\n if (message.idempotencyKey !== \"\") {\n writer.uint32(42).string(message.idempotencyKey);\n }\n if (message.xSbTrace !== \"\") {\n writer.uint32(50).string(message.xSbTrace);\n }\n if (message.contractHash.length !== 0) {\n writer.uint32(58).bytes(message.contractHash);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): InvokeRequest {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseInvokeRequest();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.targetServiceId = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.method = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.payload = Buffer.from(reader.bytes());\n continue;\n }\n case 4: {\n if (tag !== 34) {\n break;\n }\n\n message.requestId = reader.string();\n continue;\n }\n case 5: {\n if (tag !== 42) {\n break;\n }\n\n message.idempotencyKey = reader.string();\n continue;\n }\n case 6: {\n if (tag !== 50) {\n break;\n }\n\n message.xSbTrace = reader.string();\n continue;\n }\n case 7: {\n if (tag !== 58) {\n break;\n }\n\n message.contractHash = Buffer.from(reader.bytes());\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<InvokeRequest>, I>>(base?: I): InvokeRequest {\n return InvokeRequest.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<InvokeRequest>, I>>(object: I): InvokeRequest {\n const message = createBaseInvokeRequest();\n message.targetServiceId = object.targetServiceId ?? \"\";\n message.method = object.method ?? \"\";\n message.payload = object.payload ?? Buffer.alloc(0);\n message.requestId = object.requestId ?? \"\";\n message.idempotencyKey = object.idempotencyKey ?? \"\";\n message.xSbTrace = object.xSbTrace ?? \"\";\n message.contractHash = object.contractHash ?? Buffer.alloc(0);\n return message;\n },\n};\n\nfunction createBaseInvokeResponse(): InvokeResponse {\n return { payload: Buffer.alloc(0), errorCode: \"\", errorMessage: \"\" };\n}\n\nexport const InvokeResponse: MessageFns<InvokeResponse> = {\n encode(message: InvokeResponse, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.payload.length !== 0) {\n writer.uint32(10).bytes(message.payload);\n }\n if (message.errorCode !== \"\") {\n writer.uint32(18).string(message.errorCode);\n }\n if (message.errorMessage !== \"\") {\n writer.uint32(26).string(message.errorMessage);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): InvokeResponse {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseInvokeResponse();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.payload = Buffer.from(reader.bytes());\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.errorCode = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.errorMessage = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<InvokeResponse>, I>>(base?: I): InvokeResponse {\n return InvokeResponse.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<InvokeResponse>, I>>(object: I): InvokeResponse {\n const message = createBaseInvokeResponse();\n message.payload = object.payload ?? Buffer.alloc(0);\n message.errorCode = object.errorCode ?? \"\";\n message.errorMessage = object.errorMessage ?? \"\";\n return message;\n },\n};\n\nfunction createBaseInvokeChunk(): InvokeChunk {\n return { payload: Buffer.alloc(0), errorCode: \"\", errorMessage: \"\" };\n}\n\nexport const InvokeChunk: MessageFns<InvokeChunk> = {\n encode(message: InvokeChunk, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.payload.length !== 0) {\n writer.uint32(10).bytes(message.payload);\n }\n if (message.errorCode !== \"\") {\n writer.uint32(18).string(message.errorCode);\n }\n if (message.errorMessage !== \"\") {\n writer.uint32(26).string(message.errorMessage);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): InvokeChunk {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseInvokeChunk();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.payload = Buffer.from(reader.bytes());\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.errorCode = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.errorMessage = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<InvokeChunk>, I>>(base?: I): InvokeChunk {\n return InvokeChunk.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<InvokeChunk>, I>>(object: I): InvokeChunk {\n const message = createBaseInvokeChunk();\n message.payload = object.payload ?? Buffer.alloc(0);\n message.errorCode = object.errorCode ?? \"\";\n message.errorMessage = object.errorMessage ?? \"\";\n return message;\n },\n};\n\n/**\n * Invoke — proxy RPC сервис на рантайме.\n * Принимает вызов от caller-SDK, резолвит инстанс target-сервиса, проксирует Call.Unary к нему.\n * Payload — passthrough bytes, рантайм не декодирует.\n */\nexport type InvokeService = typeof InvokeService;\nexport const InvokeService = {\n unary: {\n path: \"/servicebridge.v1.Invoke/Unary\" as const,\n requestStream: false as const,\n responseStream: false as const,\n requestSerialize: (value: InvokeRequest): Buffer => Buffer.from(InvokeRequest.encode(value).finish()),\n requestDeserialize: (value: Buffer): InvokeRequest => InvokeRequest.decode(value),\n responseSerialize: (value: InvokeResponse): Buffer => Buffer.from(InvokeResponse.encode(value).finish()),\n responseDeserialize: (value: Buffer): InvokeResponse => InvokeResponse.decode(value),\n },\n /**\n * Stream — proxy server-side streaming. Runtime получает один запрос,\n * открывает Call.Stream к выбранному callee, пробрасывает chunks обратно.\n */\n stream: {\n path: \"/servicebridge.v1.Invoke/Stream\" as const,\n requestStream: false as const,\n responseStream: true as const,\n requestSerialize: (value: InvokeRequest): Buffer => Buffer.from(InvokeRequest.encode(value).finish()),\n requestDeserialize: (value: Buffer): InvokeRequest => InvokeRequest.decode(value),\n responseSerialize: (value: InvokeChunk): Buffer => Buffer.from(InvokeChunk.encode(value).finish()),\n responseDeserialize: (value: Buffer): InvokeChunk => InvokeChunk.decode(value),\n },\n} as const;\n\nexport interface InvokeServer extends UntypedServiceImplementation {\n unary: handleUnaryCall<InvokeRequest, InvokeResponse>;\n /**\n * Stream — proxy server-side streaming. Runtime получает один запрос,\n * открывает Call.Stream к выбранному callee, пробрасывает chunks обратно.\n */\n stream: handleServerStreamingCall<InvokeRequest, InvokeChunk>;\n}\n\nexport interface InvokeClient extends Client {\n unary(\n request: InvokeRequest,\n callback: (error: ServiceError | null, response: InvokeResponse) => void,\n ): ClientUnaryCall;\n unary(\n request: InvokeRequest,\n metadata: Metadata,\n callback: (error: ServiceError | null, response: InvokeResponse) => void,\n ): ClientUnaryCall;\n unary(\n request: InvokeRequest,\n metadata: Metadata,\n options: Partial<CallOptions>,\n callback: (error: ServiceError | null, response: InvokeResponse) => void,\n ): ClientUnaryCall;\n /**\n * Stream — proxy server-side streaming. Runtime получает один запрос,\n * открывает Call.Stream к выбранному callee, пробрасывает chunks обратно.\n */\n stream(request: InvokeRequest, options?: Partial<CallOptions>): ClientReadableStream<InvokeChunk>;\n stream(\n request: InvokeRequest,\n metadata?: Metadata,\n options?: Partial<CallOptions>,\n ): ClientReadableStream<InvokeChunk>;\n}\n\nexport const InvokeClient = makeGenericClientConstructor(InvokeService, \"servicebridge.v1.Invoke\") as unknown as {\n new (address: string, credentials: ChannelCredentials, options?: Partial<ClientOptions>): InvokeClient;\n service: typeof InvokeService;\n serviceName: string;\n};\n\ntype Builtin = Date | Function | Uint8Array | string | number | boolean | undefined;\n\ntype DeepPartial<T> = T extends Builtin ? T\n : T extends globalThis.Array<infer U> ? globalThis.Array<DeepPartial<U>>\n : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>>\n : T extends {} ? { [K in keyof T]?: DeepPartial<T[K]> }\n : Partial<T>;\n\ntype KeysOfUnion<T> = T extends T ? keyof T : never;\ntype Exact<P, I extends P> = P extends Builtin ? P\n : P & { [K in keyof P]: Exact<P[K], I[K]> } & { [K in Exclude<keyof I, KeysOfUnion<P>>]: never };\n\ninterface MessageFns<T> {\n encode(message: T, writer?: BinaryWriter): BinaryWriter;\n decode(input: BinaryReader | Uint8Array, length?: number): T;\n create<I extends Exact<DeepPartial<T>, I>>(base?: I): T;\n fromPartial<I extends Exact<DeepPartial<T>, I>>(object: I): T;\n}\n","import * as grpc from \"@grpc/grpc-js\";\nimport { derToPem } from \"../connection/pem\";\nimport {\n\ttype CallRequest,\n\ttype CallResponse,\n\tCallService,\n\ttype StreamChunk,\n} from \"../pb/servicebridge/v1/call\";\nimport type { PolicyEvaluation } from \"../pb/servicebridge/v1/registry\";\nimport { runWithTrace } from \"../telemetry/context\";\nimport { mintRootContext, type TraceContext } from \"../telemetry/trace-context\";\nimport { parseXSbTrace } from \"../telemetry/wire-trace\";\nimport { evaluatePeerAcceptance, getPeerCertFromCall } from \"./acceptance\";\nimport type { DispatchPort } from \"./dispatch-port\";\n\n// Credentials for the inbound call server: leaf cert + key (DER), CA chain (DER).\n// Reuses the same certs the SDK obtained from runtime Bootstrap.\nexport interface CallServerCredentials {\n\tcaChainDer: Buffer;\n\tleafCertDer: Buffer;\n\tprivateKeyDer: Buffer;\n}\n\n// AdvertiseConfig is the operator-supplied advertise address. host is mandatory\n// (no auto-detect — k8s/docker need explicit POD_IP via downward API), port=0\n// asks the OS to pick a free port.\nexport interface AdvertiseConfig {\n\thost: string;\n\tport: number;\n}\n\n/**\n * Parse the inbound trace context from a CallRequest. Falls back to a fresh\n * root context when xSbTrace is missing or malformed — that keeps the local\n * trace consistent even when the caller side has not yet been wired for\n * propagation.\n * @internal\n */\nfunction inboundTraceContext(req: CallRequest): TraceContext {\n\tconst parsed = parseXSbTrace(req.xSbTrace);\n\treturn parsed ?? mintRootContext();\n}\n// CallServer hosts the inbound Call.Unary gRPC service on the SDK instance.\n// All incoming requests are dispatched to the DispatchPort which owns handler\n// registration and schema (de)serialization. Errors thrown by handlers are\n// converted to CallResponse.error_code/error_message — gRPC status stays OK.\n//\n// Acceptance check (Layer 2, ADR-0014 Gap 1): for each incoming direct call,\n// the server extracts the caller's SPIFFE service UUID from the peer TLS cert\n// and checks it against the callee's rpc.handle acceptance rules. If the\n// private grpc-js accessor path is broken the server fails closed — all direct\n// calls are rejected with PermissionDenied until the accessor is restored.\n//\n// Tracing (ADR-0037..0042): the server emits NO op. It runs the handler inside\n// the inbound call's trace context (parent = caller CALL.op_id) so the handler's\n// nested ops (rpc.call / event.publish) parent to the single caller-owned\n// RPC.CALL row. Callee errors flow back in the CallResponse and the caller\n// records them on the CALL row.\n//\n// @internal — см. ./README.md\nexport class CallServer {\n\tprivate server: grpc.Server | null = null;\n\tprivate advertised: string | null = null;\n\t// Set to true when the grpc-js peer-cert accessor path is confirmed working.\n\tprivate peerCertAccessorOk = false;\n\n\tconstructor(\n\t\tprivate readonly dispatch: DispatchPort,\n\t\tprivate readonly creds: CallServerCredentials,\n\t\t// Returns the current PolicyEvaluation for this service. May return null\n\t\t// when policy is not yet loaded (default-allow in that case).\n\t\tprivate readonly getPolicy: () => PolicyEvaluation | null = () => null,\n\t) {}\n\n\tasync start(cfg: AdvertiseConfig): Promise<string> {\n\t\tif (this.server) {\n\t\t\tthrow new Error(\"rpc: call server already started\");\n\t\t}\n\t\tif (!cfg.host) {\n\t\t\tthrow new Error(\"rpc: advertise.host is required\");\n\t\t}\n\n\t\t// Smoke-test the peer-cert accessor path. We use the public\n\t\t// getAuthContext() API on grpc-js ServerCall — verify the fallback\n\t\t// shape walker still works on a dummy with a getAuthContext function.\n\t\tconst testCall = {\n\t\t\tgetAuthContext: () => ({ sslPeerCertificate: { subjectaltname: \"\" } }),\n\t\t};\n\t\tconst testCert = getPeerCertFromCall(testCall);\n\t\tthis.peerCertAccessorOk = testCert !== null;\n\n\t\tconst server = new grpc.Server();\n\t\tserver.addService(CallService, {\n\t\t\tunary: (\n\t\t\t\tcall: grpc.ServerUnaryCall<CallRequest, CallResponse>,\n\t\t\t\tcallback: grpc.sendUnaryData<CallResponse>,\n\t\t\t) => {\n\t\t\t\tthis.handleUnary(call, callback);\n\t\t\t},\n\t\t\tstream: (call: grpc.ServerWritableStream<CallRequest, StreamChunk>) => {\n\t\t\t\tvoid this.handleStream(call);\n\t\t\t},\n\t\t});\n\n\t\t// grpc-js ServerCredentials.createSsl requires PEM-encoded buffers.\n\t\tconst caChainPem = derToPem(this.creds.caChainDer, \"CERTIFICATE\");\n\t\tconst certPem = derToPem(this.creds.leafCertDer, \"CERTIFICATE\");\n\t\tconst keyPem = derToPem(this.creds.privateKeyDer, \"PRIVATE KEY\");\n\n\t\tconst bound = await new Promise<number>((resolve, reject) => {\n\t\t\tconst sc = grpc.ServerCredentials.createSsl(\n\t\t\t\tcaChainPem,\n\t\t\t\t[{ private_key: keyPem, cert_chain: certPem }],\n\t\t\t\ttrue, // checkClientCertificate\n\t\t\t);\n\t\t\t// Bind on the advertise host directly so SO_REUSEADDR / IPv4 vs IPv6\n\t\t\t// matches the address that will be published in the registry. grpc-js\n\t\t\t// requires a non-empty hostname (it does not accept 0.0.0.0:0 with the\n\t\t\t// current TLS credentials path).\n\t\t\tserver.bindAsync(`${cfg.host}:${cfg.port}`, sc, (err, port) => {\n\t\t\t\tif (err) reject(err);\n\t\t\t\telse resolve(port);\n\t\t\t});\n\t\t});\n\n\t\tthis.server = server;\n\t\tthis.advertised = `${cfg.host}:${bound}`;\n\t\treturn this.advertised;\n\t}\n\n\tendpoint(): string {\n\t\tif (!this.advertised) throw new Error(\"rpc: call server not started\");\n\t\treturn this.advertised;\n\t}\n\n\tasync stop(): Promise<void> {\n\t\tif (!this.server) return;\n\t\tconst server = this.server;\n\t\tthis.server = null;\n\t\tthis.advertised = null;\n\t\tawait new Promise<void>((resolve) => {\n\t\t\tserver.tryShutdown((err) => {\n\t\t\t\tif (err) server.forceShutdown();\n\t\t\t\tresolve();\n\t\t\t});\n\t\t});\n\t}\n\n\tprivate async handleUnary(\n\t\tcall: grpc.ServerUnaryCall<CallRequest, CallResponse>,\n\t\tcallback: grpc.sendUnaryData<CallResponse>,\n\t): Promise<void> {\n\t\tconst denial = this.checkPeerAcceptance(call, call.request.method);\n\t\tif (denial) {\n\t\t\tcallback({\n\t\t\t\tcode: grpc.status.PERMISSION_DENIED,\n\t\t\t\tmessage: denial,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tconst req = call.request;\n\t\tconst traceCtx = inboundTraceContext(req);\n\t\t// The handler runs in the call's trace context (parent = caller CALL.op_id)\n\t\t// so its nested ops parent to CALL. No RPC.HANDLE op is emitted — the single\n\t\t// RPC.CALL row owned by the caller SDK is the whole call (ADR-0037..0042).\n\t\tawait runWithTrace(traceCtx, async () => {\n\t\t\ttry {\n\t\t\t\tconst result = await this.dispatch.dispatchUnary(\n\t\t\t\t\treq.method,\n\t\t\t\t\treq.payload,\n\t\t\t\t);\n\t\t\t\tcallback(null, {\n\t\t\t\t\tpayload: Buffer.from(result.payload),\n\t\t\t\t\terrorCode: result.errorCode ?? \"\",\n\t\t\t\t\terrorMessage: result.errorMessage ?? \"\",\n\t\t\t\t});\n\t\t\t} catch (err) {\n\t\t\t\tconst msg = (err as Error).message;\n\t\t\t\tcallback(null, {\n\t\t\t\t\tpayload: Buffer.alloc(0),\n\t\t\t\t\terrorCode: \"INTERNAL\",\n\t\t\t\t\terrorMessage: msg,\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t}\n\n\t// checkPeerAcceptance returns a denial reason string when the caller is not\n\t// permitted, or null when the call should proceed.\n\tprivate checkPeerAcceptance(call: object, methodName: string): string | null {\n\t\treturn evaluatePeerAcceptance(\n\t\t\tthis.peerCertAccessorOk,\n\t\t\tthis.getPolicy(),\n\t\t\tcall,\n\t\t\tmethodName,\n\t\t);\n\t}\n\n\tprivate async handleStream(\n\t\tcall: grpc.ServerWritableStream<CallRequest, StreamChunk>,\n\t): Promise<void> {\n\t\tconst denial = this.checkPeerAcceptance(call, call.request.method);\n\t\tif (denial) {\n\t\t\tcall.write({\n\t\t\t\tpayload: Buffer.alloc(0),\n\t\t\t\terrorCode: \"PERMISSION_DENIED\",\n\t\t\t\terrorMessage: denial,\n\t\t\t});\n\t\t\tcall.end();\n\t\t\treturn;\n\t\t}\n\t\tconst req = call.request;\n\t\tconst traceCtx = inboundTraceContext(req);\n\t\t// Handler runs in the call's trace context; no RPC.HANDLE op (ADR-0037..0042).\n\t\tawait runWithTrace(traceCtx, async () => {\n\t\t\ttry {\n\t\t\t\tfor await (const item of this.dispatch.dispatchStream(\n\t\t\t\t\treq.method,\n\t\t\t\t\treq.payload,\n\t\t\t\t)) {\n\t\t\t\t\tif (item.errorCode) {\n\t\t\t\t\t\tcall.write({\n\t\t\t\t\t\t\tpayload: Buffer.alloc(0),\n\t\t\t\t\t\t\terrorCode: item.errorCode,\n\t\t\t\t\t\t\terrorMessage: item.errorMessage ?? \"\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\tcall.end();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tcall.write({\n\t\t\t\t\t\tpayload: Buffer.from(item.payload ?? new Uint8Array()),\n\t\t\t\t\t\terrorCode: \"\",\n\t\t\t\t\t\terrorMessage: \"\",\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tcall.end();\n\t\t\t} catch (err) {\n\t\t\t\tconst msg = (err as Error).message;\n\t\t\t\tcall.write({\n\t\t\t\t\tpayload: Buffer.alloc(0),\n\t\t\t\t\terrorCode: \"INTERNAL\",\n\t\t\t\t\terrorMessage: msg,\n\t\t\t\t});\n\t\t\t\tcall.end();\n\t\t\t}\n\t\t});\n\t}\n}\n","import \"reflect-metadata\";\nimport * as x509 from \"@peculiar/x509\";\nimport { SPIFFE_TRUST_DOMAIN } from \"../connection/spiffe\";\nimport type { PolicyEvaluation } from \"../pb/servicebridge/v1/registry\";\n\n// SpiffeIdentity is the parsed SPIFFE URI for a ServiceBridge peer.\nexport interface SpiffeIdentity {\n\tserviceId: string;\n\tinstanceId: string;\n}\n\n// parsePeerSpiffeUri parses a full SPIFFE URI of the form:\n// spiffe://servicebridge/service/<serviceId>/instance/<instanceId>\n// Returns null for any other URI.\nexport function parsePeerSpiffeUri(uri: string): SpiffeIdentity | null {\n\tconst prefix = `spiffe://${SPIFFE_TRUST_DOMAIN}/service/`;\n\tif (!uri.startsWith(prefix)) return null;\n\tconst rest = uri.slice(prefix.length);\n\tconst parts = rest.split(\"/instance/\");\n\tif (parts.length !== 2 || !parts[0] || !parts[1]) return null;\n\treturn { serviceId: parts[0], instanceId: parts[1] };\n}\n\n// extractSpiffeServiceId extracts the caller's service UUID from a\n// PeerCertificate-like object. Tries both `subjectaltname` (Node TLS short\n// form) and `raw` (DER buffer) — Node sometimes leaves `subjectaltname` empty\n// for URI SAN-only certs, in which case we parse the DER ourselves via\n// @peculiar/x509 (the SubjectAlternativeName extension carries the URI).\nexport function extractSpiffeServiceId(cert: {\n\tsubjectaltname?: string;\n\traw?: Buffer | Uint8Array;\n}): string | null {\n\tconst altName = cert.subjectaltname;\n\tif (altName) {\n\t\tfor (const part of altName.split(\",\")) {\n\t\t\tconst trimmed = part.trim();\n\t\t\tif (!trimmed.startsWith(\"URI:\")) continue;\n\t\t\tconst uri = trimmed.slice(4);\n\t\t\tconst id = parsePeerSpiffeUri(uri);\n\t\t\tif (id) return id.serviceId;\n\t\t}\n\t}\n\t// Node TLS sometimes leaves `subjectaltname` empty when the SAN extension\n\t// contains only URI entries — fall through to parsing the raw DER.\n\tif (cert.raw) {\n\t\ttry {\n\t\t\tconst parsed = new x509.X509Certificate(cert.raw);\n\t\t\tconst sanExt = parsed.getExtension(x509.SubjectAlternativeNameExtension);\n\t\t\tif (sanExt) {\n\t\t\t\tfor (const name of sanExt.names.items) {\n\t\t\t\t\tif (name.type === \"url\") {\n\t\t\t\t\t\tconst id = parsePeerSpiffeUri(name.value);\n\t\t\t\t\t\tif (id) return id.serviceId;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\t// fall through\n\t\t}\n\t}\n\treturn null;\n}\n\n// checkAcceptance evaluates whether callerServiceId may call methodName on\n// this service, based on the service's current PolicyEvaluation.acceptance\n// rules. Default-allow when acceptance rules are empty.\n//\n// Rule matching:\n// - peerServiceId == \"\" → wildcard (any caller)\n// - targetName == \"*\" → any method\n// - otherwise exact match on both fields\nexport function checkAcceptance(\n\tcallerServiceId: string,\n\tmethodName: string,\n\tpolicy: PolicyEvaluation,\n): boolean {\n\tconst rules = policy.acceptance.filter((r) => r.action === \"rpc.handle\");\n\tif (rules.length === 0) return true; // default-allow\n\n\tfor (const rule of rules) {\n\t\tconst peerMatch =\n\t\t\trule.peerServiceId === \"\" || rule.peerServiceId === callerServiceId;\n\t\tconst methodMatch =\n\t\t\trule.targetName === \"*\" || rule.targetName === methodName;\n\t\tif (peerMatch && methodMatch) return true;\n\t}\n\treturn false;\n}\n\n// evaluatePeerAcceptance is the pure decision function used by CallServer for\n// every incoming direct call. Returns a denial reason string when the call\n// should be rejected, or null when it should proceed.\n//\n// Fail-closed when peerCertAccessorOk = false (smoke-test failed at startup).\n// Default-allow when policy is null or has no rpc.handle rules.\nexport function evaluatePeerAcceptance(\n\tpeerCertAccessorOk: boolean,\n\tpolicy: PolicyEvaluation | null,\n\tcall: object,\n\tmethodName: string,\n): string | null {\n\tif (!peerCertAccessorOk) {\n\t\treturn \"rpc: peer-cert accessor broken — direct calls rejected (fail-closed)\";\n\t}\n\tif (!policy) return null;\n\tconst rpcHandleRules = policy.acceptance.filter(\n\t\t(r) => r.action === \"rpc.handle\",\n\t);\n\tif (rpcHandleRules.length === 0) return null;\n\tconst cert = getPeerCertFromCall(call);\n\tif (!cert) {\n\t\treturn \"rpc: could not extract peer certificate from direct call\";\n\t}\n\tconst callerServiceId = extractSpiffeServiceId(cert);\n\tif (!callerServiceId) {\n\t\t// No SPIFFE service URI ⇒ peer is the runtime proxying a call. The\n\t\t// runtime has already enforced caller-side gate #3 against the\n\t\t// originating service. Trust that and let the call through. (Local\n\t\t// callee identity is only meaningful for direct SDK→SDK connections,\n\t\t// where the leaf cert carries a SPIFFE URI.)\n\t\treturn null;\n\t}\n\tif (!checkAcceptance(callerServiceId, methodName, policy)) {\n\t\treturn `rpc: acceptance denied for caller ${callerServiceId} method ${methodName}`;\n\t}\n\treturn null;\n}\n\n// getPeerCertFromCall extracts the peer TLS certificate from a grpc-js server\n// call. Uses the public `getAuthContext()` API exposed on ServerUnaryCall /\n// ServerWritableStream — internally grpc-js reads it via\n// `stream.session.socket.getPeerCertificate()` (server-interceptors.js:785).\n// Returns null if the call is not over TLS or the cert is unavailable.\n//\n// Test helpers may pass a plain object exposing the same legacy private path\n// `call.handler.session.socket.getPeerCertificate()`; that fallback is kept\n// for unit tests where we cannot construct a real grpc-js call.\nexport function getPeerCertFromCall(\n\tcall: object,\n): { subjectaltname?: string; [k: string]: unknown } | null {\n\ttry {\n\t\t// Walk to the underlying TLS socket through the documented grpc-js layout:\n\t\t// ServerUnaryCall.call → BaseServerInterceptingCall.stream → http2 stream\n\t\t// → session.socket (TLSSocket).\n\t\t// Test helpers may instead use the legacy `call.handler.session.socket`\n\t\t// shape — we accept both. getPeerCertificate(true) returns the detailed\n\t\t// form which includes `subjectaltname`.\n\t\tconst candidates: unknown[] = [];\n\t\tconst outer = call as Record<string, unknown>;\n\t\tconst inner = outer.call as Record<string, unknown> | undefined;\n\t\tif (inner) {\n\t\t\tconst stream = inner.stream as Record<string, unknown> | undefined;\n\t\t\tif (stream?.session) candidates.push(stream.session);\n\t\t\tconst handler = inner.handler as Record<string, unknown> | undefined;\n\t\t\tif (handler?.session) candidates.push(handler.session);\n\t\t}\n\t\t// Also try outer.stream / outer.session for completeness.\n\t\tconst directStream = outer.stream as Record<string, unknown> | undefined;\n\t\tif (directStream?.session) candidates.push(directStream.session);\n\n\t\tfor (const session of candidates) {\n\t\t\tconst s = session as Record<string, unknown>;\n\t\t\tconst socket = s.socket as Record<string, unknown> | undefined;\n\t\t\tif (!socket) continue;\n\t\t\tconst getCert = socket.getPeerCertificate;\n\t\t\tif (typeof getCert !== \"function\") continue;\n\t\t\tconst cert = (getCert as (detailed?: boolean) => unknown).call(\n\t\t\t\tsocket,\n\t\t\t\ttrue,\n\t\t\t);\n\t\t\tif (cert && typeof cert === \"object\") {\n\t\t\t\treturn cert as { subjectaltname?: string };\n\t\t\t}\n\t\t}\n\n\t\t// Last-resort fallback for getAuthContext-based mocks.\n\t\tconst c = call as {\n\t\t\tgetAuthContext?: () => {\n\t\t\t\tsslPeerCertificate?: { subjectaltname?: string };\n\t\t\t};\n\t\t};\n\t\tif (typeof c.getAuthContext === \"function\") {\n\t\t\tconst ctx = c.getAuthContext();\n\t\t\tif (ctx?.sslPeerCertificate) return ctx.sslPeerCertificate;\n\t\t}\n\t\treturn null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n","import protobuf from \"protobufjs\";\nimport type { CallOpts } from \"./client\";\n\n// TypedClient is the dynamic proxy returned by `sb.client(svc, protoFile)`.\n// Methods listed in the .proto's `service` block become callable directly:\n//\n// const payment = await sb.client(\"payment-svc\", \"./payment.proto\");\n// const res = await payment.Charge({ userId: \"u-1\", amount: 100 });\n// for await (const tok of payment.Generate({ prompt: \"...\" })) { ... }\n//\n// Unary methods return Promise<Res>; streaming methods (responseStream=true)\n// return AsyncIterable<Chunk>. CallOpts can be passed as a second argument to\n// any method.\n//\n// @public — см. ./README.md\nexport type TypedClient = Record<\n\tstring,\n\t((req: unknown, opts?: CallOpts) => Promise<unknown>) &\n\t\t((req: unknown, opts?: CallOpts) => AsyncIterable<unknown>)\n>;\n\n// MethodSpec describes one method extracted from a .proto service block.\n// Used internally by ServiceBridge.client() to wire up the typed proxy.\nexport interface MethodSpec {\n\tname: string;\n\trequestType: string;\n\tresponseType: string;\n\tresponseStream: boolean;\n}\n\n// extractServiceMethods loads a .proto file and returns the list of methods\n// defined in ANY service block. Throws if the file has no service.\n//\n// @internal — см. ./README.md\nexport async function extractServiceMethods(\n\tprotoFile: string,\n): Promise<MethodSpec[]> {\n\tlet root: protobuf.Root;\n\ttry {\n\t\troot = await protobuf.load(protoFile);\n\t} catch (err) {\n\t\tthrow new Error(\n\t\t\t`rpc: client(${protoFile}): load proto: ${(err as Error).message}`,\n\t\t);\n\t}\n\n\tconst methods: MethodSpec[] = [];\n\tvisit(root, (obj) => {\n\t\tif (!(obj instanceof protobuf.Service)) return;\n\t\tfor (const m of Object.values(obj.methods)) {\n\t\t\tmethods.push({\n\t\t\t\tname: m.name,\n\t\t\t\trequestType: m.requestType,\n\t\t\t\tresponseType: m.responseType,\n\t\t\t\tresponseStream: m.responseStream === true,\n\t\t\t});\n\t\t}\n\t});\n\n\tif (methods.length === 0) {\n\t\tthrow new Error(\n\t\t\t`rpc: client(${protoFile}): no service block found — typed client requires gRPC-native service definition`,\n\t\t);\n\t}\n\treturn methods;\n}\n\nfunction visit(\n\tobj: protobuf.NamespaceBase,\n\tfn: (item: protobuf.ReflectionObject) => void,\n): void {\n\tfn(obj);\n\tconst nested = obj.nested;\n\tif (!nested) return;\n\tfor (const child of Object.values(nested)) {\n\t\tif (child instanceof protobuf.Namespace) {\n\t\t\tvisit(child, fn);\n\t\t} else {\n\t\t\tfn(child);\n\t\t}\n\t}\n}\n","import * as fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\n\n// @public — см. ./README.md\nexport interface StorageOpenOpts {\n\tdataDir?: string;\n}\n\n// Prepared statement surface the outbox relies on. Both bun:sqlite and\n// better-sqlite3 satisfy it (positional `?` binds, run/get/all).\n// @internal — см. ./README.md\ninterface SqliteStatement {\n\trun(...params: unknown[]): unknown;\n\tget(...params: unknown[]): unknown;\n\tall(...params: unknown[]): unknown[];\n}\n\n// Database surface the outbox relies on. The common subset of bun:sqlite and\n// better-sqlite3.\n// @internal — см. ./README.md\ninterface SqliteDatabase {\n\texec(sql: string): unknown;\n\tprepare(sql: string): SqliteStatement;\n\ttransaction<T>(fn: (...args: unknown[]) => T): (...args: unknown[]) => T;\n\tclose(): void;\n}\n\ntype SqliteConstructor = new (path: string) => SqliteDatabase;\n\n// openDatabase loads the native SQLite driver for the current runtime and opens\n// the file at `path`. Bun ships `bun:sqlite`; plain Node uses `better-sqlite3`.\n// Both are loaded synchronously via createRequire so Storage.open stays sync,\n// and the specifier stays a runtime string so a Node bundler never tries to\n// resolve `bun:sqlite`. The two drivers share the run/get/all/transaction/exec\n// surface this module uses.\nfunction openDatabase(path: string): SqliteDatabase {\n\tconst req = createRequire(import.meta.url);\n\tconst isBun = typeof (globalThis as { Bun?: unknown }).Bun !== \"undefined\";\n\tif (isBun) {\n\t\tconst { Database } = req(\"bun:sqlite\") as { Database: SqliteConstructor };\n\t\treturn new Database(path);\n\t}\n\tconst Database = req(\"better-sqlite3\") as SqliteConstructor;\n\treturn new Database(path);\n}\n\n// Storage wraps a native SQLite database with the event_outbox schema, WAL\n// mode, and crash-recovery reset of in-flight outbox rows. It runs on plain\n// Node (better-sqlite3) and on Bun (bun:sqlite) with identical behavior.\n// @public — см. ./README.md\nexport class Storage {\n\tprivate readonly db: SqliteDatabase;\n\n\tprivate constructor(db: SqliteDatabase) {\n\t\tthis.db = db;\n\t}\n\n\t// open creates or opens the SQLite database at dataDir/sdk.db, ensures the\n\t// event_outbox schema exists (CREATE IF NOT EXISTS), enables WAL mode, and\n\t// resets any rows stuck in 'inflight' status from a previous crash\n\t// (reset-on-start crash recovery).\n\tstatic open(opts?: StorageOpenOpts): Storage {\n\t\tconst dir = opts?.dataDir ?? \"./.servicebridge\";\n\t\tfs.mkdirSync(dir, { recursive: true });\n\n\t\tconst db = openDatabase(`${dir}/sdk.db`);\n\t\tdb.exec(\"PRAGMA journal_mode = WAL\");\n\t\tdb.exec(\"PRAGMA synchronous = NORMAL\");\n\n\t\tdb.exec(`\nCREATE TABLE IF NOT EXISTS event_outbox (\n id TEXT PRIMARY KEY,\n name TEXT NOT NULL,\n payload BLOB NOT NULL,\n payload_json BLOB NOT NULL DEFAULT x'',\n contract_hash TEXT NOT NULL,\n partition_key TEXT NOT NULL DEFAULT '',\n idempotency_key TEXT NOT NULL DEFAULT '',\n fire_and_forget INTEGER NOT NULL DEFAULT 0,\n headers TEXT NOT NULL DEFAULT '{}',\n occurred_at_ms INTEGER NOT NULL,\n enqueued_at_ms INTEGER NOT NULL,\n status TEXT NOT NULL CHECK(status IN ('pending','inflight','done','failed')),\n attempts INTEGER NOT NULL DEFAULT 0,\n last_error TEXT NOT NULL DEFAULT '',\n next_attempt_at_ms INTEGER NOT NULL DEFAULT 0,\n x_sb_trace TEXT NOT NULL DEFAULT ''\n);\nCREATE INDEX IF NOT EXISTS event_outbox_pending_idx\n ON event_outbox(next_attempt_at_ms)\n WHERE status='pending';\n\t\t`);\n\n\t\t// An existing on-disk outbox DB may lack payload_json / x_sb_trace, and\n\t\t// CREATE TABLE IF NOT EXISTS won't add columns to an existing table — so\n\t\t// Publisher.publish() would INSERT into a missing column. Reconcile the\n\t\t// schema via PRAGMA inspection + ADD COLUMN (idempotent).\n\t\tconst cols = (\n\t\t\tdb.prepare(\"PRAGMA table_info(event_outbox)\").all() as { name: string }[]\n\t\t).map((r) => r.name);\n\t\tif (!cols.includes(\"payload_json\")) {\n\t\t\tdb.exec(\n\t\t\t\t\"ALTER TABLE event_outbox ADD COLUMN payload_json BLOB NOT NULL DEFAULT x''\",\n\t\t\t);\n\t\t}\n\t\tif (!cols.includes(\"x_sb_trace\")) {\n\t\t\tdb.exec(\n\t\t\t\t\"ALTER TABLE event_outbox ADD COLUMN x_sb_trace TEXT NOT NULL DEFAULT ''\",\n\t\t\t);\n\t\t}\n\n\t\t// Crash recovery: any rows left as 'inflight' by a previous drainer run\n\t\t// that was interrupted (SIGKILL, process crash) are reset to 'pending'\n\t\t// so they will be retried on this start.\n\t\tdb.exec(\"UPDATE event_outbox SET status='pending' WHERE status='inflight'\");\n\n\t\treturn new Storage(db);\n\t}\n\n\t// transaction executes fn inside a SQLite transaction. The driver serializes\n\t// all transactions — this is intentional (cap check + INSERT in one atomic\n\t// op).\n\ttransaction<T>(fn: () => T): T {\n\t\treturn this.db.transaction(fn)();\n\t}\n\n\t// prepare returns a prepared statement for the given SQL.\n\tprepare(sql: string): SqliteStatement {\n\t\treturn this.db.prepare(sql);\n\t}\n\n\tclose(): void {\n\t\tthis.db.close();\n\t}\n}\n","// logs.ts — structured logging into the telemetry ring.\n// @public — см. ./README.md\n\nimport { type Log, LogLevel } from \"../pb/servicebridge/v1/telemetry\";\nimport type { TelemetryRing } from \"./ring\";\n\nexport { LogLevel };\n\nexport type LogFields = Record<string, unknown>;\n\n// logger pushes a Log entry into the ring.\n// @public — см. ./README.md\nexport function makeLogger(ring: TelemetryRing, instanceId: string) {\n\treturn {\n\t\tdebug(message: string, fields?: LogFields): void {\n\t\t\tpush(ring, instanceId, LogLevel.LOG_LEVEL_DEBUG, message, fields);\n\t\t},\n\t\tinfo(message: string, fields?: LogFields): void {\n\t\t\tpush(ring, instanceId, LogLevel.LOG_LEVEL_INFO, message, fields);\n\t\t},\n\t\twarn(message: string, fields?: LogFields): void {\n\t\t\tpush(ring, instanceId, LogLevel.LOG_LEVEL_WARN, message, fields);\n\t\t},\n\t\terror(message: string, fields?: LogFields): void {\n\t\t\tpush(ring, instanceId, LogLevel.LOG_LEVEL_ERROR, message, fields);\n\t\t},\n\t};\n}\n\nfunction push(\n\tring: TelemetryRing,\n\tinstanceId: string,\n\tlevel: LogLevel,\n\tmessage: string,\n\tfields?: LogFields,\n): void {\n\tconst entry: Log = {\n\t\tatUnixMs: Date.now(),\n\t\tlevel,\n\t\tmessage,\n\t\tfieldsJson: fields ? encode(fields) : Buffer.alloc(0),\n\t\ttraceId: \"\",\n\t\topId: \"\",\n\t\tinstanceId,\n\t\tsource: \"sdk\",\n\t};\n\tring.push(\"logs\", entry);\n}\n\nfunction encode(fields: LogFields): Buffer {\n\treturn Buffer.from(JSON.stringify(fields));\n}\n","// metrics.ts — counter/gauge/histogram emission into the telemetry ring.\n// @public — см. ./README.md\n\nimport { MetricKind, type MetricPoint } from \"../pb/servicebridge/v1/telemetry\";\nimport type { TelemetryRing } from \"./ring\";\n\nexport { MetricKind };\n\nexport type Labels = Record<string, string>;\n\nfunction encodeLabels(labels: Labels): Labels {\n\treturn labels;\n}\n\nfunction pushPoint(\n\tring: TelemetryRing,\n\tinstanceId: string,\n\tpoint: MetricPoint,\n): void {\n\tring.push(\"metrics\", point);\n}\n\n// Counter is a monotonically increasing metric.\n// @public — см. ./README.md\nexport function makeCounter(\n\tring: TelemetryRing,\n\tinstanceId: string,\n\tname: string,\n\tlabels: Labels = {},\n) {\n\treturn {\n\t\tinc(amount = 1): void {\n\t\t\tpushPoint(ring, instanceId, {\n\t\t\t\tatUnixMs: Date.now(),\n\t\t\t\tname,\n\t\t\t\tkind: MetricKind.METRIC_KIND_COUNTER,\n\t\t\t\tlabels: encodeLabels(labels),\n\t\t\t\tinstanceId,\n\t\t\t\tvalue: amount,\n\t\t\t\tunit: \"1\",\n\t\t\t\tbucketsJson: Buffer.alloc(0),\n\t\t\t});\n\t\t},\n\t};\n}\n\n// Gauge can go up or down.\n// @public — см. ./README.md\nexport function makeGauge(\n\tring: TelemetryRing,\n\tinstanceId: string,\n\tname: string,\n\tlabels: Labels = {},\n) {\n\treturn {\n\t\tset(value: number): void {\n\t\t\tpushPoint(ring, instanceId, {\n\t\t\t\tatUnixMs: Date.now(),\n\t\t\t\tname,\n\t\t\t\tkind: MetricKind.METRIC_KIND_GAUGE,\n\t\t\t\tlabels: encodeLabels(labels),\n\t\t\t\tinstanceId,\n\t\t\t\tvalue,\n\t\t\t\tunit: \"1\",\n\t\t\t\tbucketsJson: Buffer.alloc(0),\n\t\t\t});\n\t\t},\n\t};\n}\n\n// Histogram records distribution observations.\n// @public — см. ./README.md\nexport function makeHistogram(\n\tring: TelemetryRing,\n\tinstanceId: string,\n\tname: string,\n\tunit = \"s\",\n\tlabels: Labels = {},\n) {\n\treturn {\n\t\tobserve(value: number): void {\n\t\t\tpushPoint(ring, instanceId, {\n\t\t\t\tatUnixMs: Date.now(),\n\t\t\t\tname,\n\t\t\t\tkind: MetricKind.METRIC_KIND_HISTOGRAM,\n\t\t\t\tlabels: encodeLabels(labels),\n\t\t\t\tinstanceId,\n\t\t\t\tvalue,\n\t\t\t\tunit,\n\t\t\t\tbucketsJson: Buffer.alloc(0),\n\t\t\t});\n\t\t},\n\t};\n}\n","// process-sampler.ts — periodic per-process CPU% and RSS gauge emission.\n// @public — см. ./README.md\n\nimport { MetricKind } from \"../pb/servicebridge/v1/telemetry\";\nimport type { TelemetryRing } from \"./ring\";\n\nconst SAMPLE_INTERVAL_MS = 30_000;\n\n/**\n * cpuPercent computes process CPU utilisation as a percentage.\n *\n * Formula: (userDeltaMicros + systemDeltaMicros) / (elapsedMs * 1_000) * 100\n *\n * Result is normalised to a single-core-equivalent percent — a process\n * saturating 2 cores over the interval returns ~200. elapsedMs=0 returns 0.\n *\n * @public — см. ./README.md\n */\nexport function cpuPercent(\n\tprev: NodeJS.CpuUsage,\n\tcur: NodeJS.CpuUsage,\n\telapsedMs: number,\n): number {\n\tif (elapsedMs <= 0) return 0;\n\tconst cpuDeltaMicros = cur.user - prev.user + (cur.system - prev.system);\n\treturn (cpuDeltaMicros / (elapsedMs * 1_000)) * 100;\n}\n\n/**\n * ProcessSampler owns a periodic timer that emits `process.cpu_percent` and\n * `process.rss_bytes` gauges into the telemetry ring. One instance per SDK\n * client; lifecycle mirrors the client: start() on connect, close() on stop.\n *\n * `getInstanceId` is resolved at each tick — the same lazy-identity pattern\n * used by the rest of the telemetry API; the sampler can be started before\n * Welcome and will carry the correct instance_id once it arrives.\n *\n * @public — см. ./README.md\n */\nexport class ProcessSampler {\n\tprivate readonly ring: TelemetryRing;\n\tprivate readonly getInstanceId: () => string;\n\tprivate readonly intervalMs: number;\n\tprivate timer: ReturnType<typeof setInterval> | null = null;\n\tprivate closed = false;\n\tprivate prevCpu: NodeJS.CpuUsage = process.cpuUsage();\n\tprivate prevAt = Date.now();\n\n\tconstructor(\n\t\tring: TelemetryRing,\n\t\tgetInstanceId: () => string,\n\t\tintervalMs = SAMPLE_INTERVAL_MS,\n\t) {\n\t\tthis.ring = ring;\n\t\tthis.getInstanceId = getInstanceId;\n\t\tthis.intervalMs = intervalMs;\n\t}\n\n\tstart(): void {\n\t\tif (this.closed) return;\n\t\tif (this.timer) return;\n\t\t// Первый сэмпл — сразу при старте, чтобы только что подключившийся\n\t\t// сервис показывал ресурсы с момента инициализации, а не только после\n\t\t// первого интервала. CPU% на этой точке — среднее за всё время жизни\n\t\t// процесса (baseline = старт процесса); tick() затем сбросит prev* на\n\t\t// \"сейчас\", и последующие тики считают дельту за интервал.\n\t\tthis.prevCpu = { user: 0, system: 0 };\n\t\tthis.prevAt = Date.now() - Math.round(process.uptime() * 1000);\n\t\tthis.tick();\n\t\tconst t = setInterval(() => this.tick(), this.intervalMs);\n\t\t// Do not keep the process alive solely due to the sampler.\n\t\tif (typeof t.unref === \"function\") t.unref();\n\t\tthis.timer = t;\n\t}\n\n\tclose(): void {\n\t\tthis.closed = true;\n\t\tif (this.timer) {\n\t\t\tclearInterval(this.timer);\n\t\t\tthis.timer = null;\n\t\t}\n\t}\n\n\t/** tick samples CPU and RSS and pushes two gauge points into the ring. */\n\ttick(): void {\n\t\tif (this.closed) return;\n\t\tconst now = Date.now();\n\t\tconst curCpu = process.cpuUsage();\n\t\tconst elapsed = now - this.prevAt;\n\n\t\tconst cpu = cpuPercent(this.prevCpu, curCpu, elapsed);\n\t\tconst rss = process.memoryUsage().rss;\n\n\t\tthis.prevCpu = curCpu;\n\t\tthis.prevAt = now;\n\n\t\tconst atUnixMs = now;\n\t\tconst empty = Buffer.alloc(0);\n\n\t\tconst instanceId = this.getInstanceId();\n\n\t\tthis.ring.push(\"metrics\", {\n\t\t\tatUnixMs,\n\t\t\tname: \"process.cpu_percent\",\n\t\t\tkind: MetricKind.METRIC_KIND_GAUGE,\n\t\t\tlabels: {},\n\t\t\tinstanceId,\n\t\t\tvalue: cpu,\n\t\t\tunit: \"%\",\n\t\t\tbucketsJson: empty,\n\t\t});\n\n\t\tthis.ring.push(\"metrics\", {\n\t\t\tatUnixMs,\n\t\t\tname: \"process.rss_bytes\",\n\t\t\tkind: MetricKind.METRIC_KIND_GAUGE,\n\t\t\tlabels: {},\n\t\t\tinstanceId,\n\t\t\tvalue: rss,\n\t\t\tunit: \"By\",\n\t\t\tbucketsJson: empty,\n\t\t});\n\t}\n}\n","// ring.ts — per-kind byte-budgeted ring buffer for typed telemetry messages.\n// Oldest-drop on overflow. Defaults: ops=256KiB, logs=64KiB, metrics=16KiB.\n// Stores decoded proto messages (not bytes): the transport feeds them straight\n// into a TelemetryBatch and grpc-js serializes once at write — no decode round\n// trip. Byte budget uses a cheap per-kind size estimate, never a full encode.\n// @public — см. ./README.md\n\nimport type {\n\tLog,\n\tMetricPoint,\n\tOpReport,\n\tPayloadAttachment,\n} from \"../pb/servicebridge/v1/telemetry\";\n\nexport type RingKind = \"ops\" | \"logs\" | \"metrics\" | \"payloads\";\n\n// RingMessage is the typed message stored for each kind.\n// @public — см. ./README.md\nexport type RingMessage = {\n\tops: OpReport;\n\tlogs: Log;\n\tmetrics: MetricPoint;\n\tpayloads: PayloadAttachment;\n};\n\n// RingItem is one buffered, typed telemetry message ready for transport.\n// @public — см. ./README.md\nexport interface RingItem<K extends RingKind = RingKind> {\n\tid: number;\n\tkind: K;\n\tmessage: RingMessage[K];\n\tbytes: number;\n}\n\n// RingBudgets overrides the per-kind byte budget. Any omitted kind keeps its\n// default. @public — см. ./README.md\nexport type RingBudgets = Partial<Record<RingKind, number>>;\n\n// Per-kind byte budgets. The ops budget holds the dense USER.SUBOP step-span\n// emission a workflow run produces between 250ms flush ticks — a 4KiB budget\n// (≈13 frames) silently dropped step spans once per-step spans landed, so the\n// default is sized for ≥800 typical op frames.\nconst DEFAULT_KIND_BUDGETS: Record<RingKind, number> = {\n\tops: 256 * 1024,\n\tlogs: 64 * 1024,\n\tmetrics: 16 * 1024,\n\tpayloads: 256 * 1024,\n};\n\nlet _nextId = 1;\n\n// estimateSize returns a cheap byte-cost estimate for memory accounting. It\n// never serializes the message — the transport does that once at write. The\n// estimate covers the variable-length fields that dominate memory; a fixed base\n// covers the rest. Accuracy is not required: this only bounds buffer growth.\nfunction estimateSize(kind: RingKind, msg: RingMessage[RingKind]): number {\n\tconst base = 64;\n\tswitch (kind) {\n\t\tcase \"ops\": {\n\t\t\tconst m = msg as OpReport;\n\t\t\treturn (\n\t\t\t\tbase +\n\t\t\t\tm.traceId.length +\n\t\t\t\tm.opId.length +\n\t\t\t\tm.parentOpId.length +\n\t\t\t\tm.subject.length +\n\t\t\t\tm.peerServiceId.length +\n\t\t\t\tm.businessKey.length +\n\t\t\t\tm.statusMessage.length +\n\t\t\t\tbyteLen(m.metaJson) +\n\t\t\t\tbyteLen(m.attrsJson)\n\t\t\t);\n\t\t}\n\t\tcase \"logs\": {\n\t\t\tconst m = msg as Log;\n\t\t\treturn base + m.message.length + byteLen(m.fieldsJson);\n\t\t}\n\t\tcase \"metrics\": {\n\t\t\tconst m = msg as MetricPoint;\n\t\t\treturn base + m.name.length + byteLen(m.bucketsJson);\n\t\t}\n\t\tcase \"payloads\": {\n\t\t\tconst m = msg as PayloadAttachment;\n\t\t\treturn base + byteLen(m.bytes) + m.contractHash.length;\n\t\t}\n\t}\n}\n\nfunction byteLen(b: Uint8Array | undefined): number {\n\treturn b ? b.byteLength : 0;\n}\n\nclass KindRing<K extends RingKind> {\n\tprivate readonly budget: number;\n\tprivate items: RingItem<K>[] = [];\n\tprivate usedBytes = 0;\n\tdropCount = 0;\n\treadonly kind: K;\n\n\tconstructor(kind: K, budget: number) {\n\t\tthis.kind = kind;\n\t\tthis.budget = budget;\n\t}\n\n\tpush(message: RingMessage[K]): void {\n\t\tconst bytes = estimateSize(this.kind, message);\n\t\tif (bytes > this.budget) {\n\t\t\t// Single item exceeds budget — drop immediately.\n\t\t\tthis.dropCount++;\n\t\t\treturn;\n\t\t}\n\t\twhile (this.usedBytes + bytes > this.budget && this.items.length > 0) {\n\t\t\tconst dropped = this.items.shift()!;\n\t\t\tthis.usedBytes -= dropped.bytes;\n\t\t\tthis.dropCount++;\n\t\t}\n\t\tthis.items.push({ id: _nextId++, kind: this.kind, message, bytes });\n\t\tthis.usedBytes += bytes;\n\t}\n\n\t// peek returns up to maxItems from the head WITHOUT removing them. Items stay\n\t// in the ring until commit() releases them — this is the at-least-once\n\t// contract: a peeked batch stays in the ring (oldest-first) and is re-peeked\n\t// on the next stream if the runtime never acks it.\n\tpeek(maxItems: number): RingItem<K>[] {\n\t\tconst take = Math.min(maxItems, this.items.length);\n\t\treturn this.items.slice(0, take);\n\t}\n\n\t// commit removes items whose ids are in the acked set, releasing the bytes.\n\tcommit(ackedIds: Set<number>): void {\n\t\tif (ackedIds.size === 0) return;\n\t\tconst kept: RingItem<K>[] = [];\n\t\tfor (const item of this.items) {\n\t\t\tif (ackedIds.has(item.id)) {\n\t\t\t\tthis.usedBytes -= item.bytes;\n\t\t\t} else {\n\t\t\t\tkept.push(item);\n\t\t\t}\n\t\t}\n\t\tthis.items = kept;\n\t}\n\n\tget size(): number {\n\t\treturn this.items.length;\n\t}\n\n\tget bytes(): number {\n\t\treturn this.usedBytes;\n\t}\n}\n\n// TelemetryRing holds one KindRing per kind and exposes a unified peek/commit\n// interface. The transport peeks a batch, writes it, and commits on ack.\n// @public — см. ./README.md\nexport class TelemetryRing {\n\tprivate readonly rings: {\n\t\tops: KindRing<\"ops\">;\n\t\tlogs: KindRing<\"logs\">;\n\t\tmetrics: KindRing<\"metrics\">;\n\t\tpayloads: KindRing<\"payloads\">;\n\t};\n\n\tconstructor(budgets?: RingBudgets) {\n\t\tthis.rings = {\n\t\t\tops: new KindRing(\"ops\", budgets?.ops ?? DEFAULT_KIND_BUDGETS.ops),\n\t\t\tlogs: new KindRing(\"logs\", budgets?.logs ?? DEFAULT_KIND_BUDGETS.logs),\n\t\t\tmetrics: new KindRing(\n\t\t\t\t\"metrics\",\n\t\t\t\tbudgets?.metrics ?? DEFAULT_KIND_BUDGETS.metrics,\n\t\t\t),\n\t\t\tpayloads: new KindRing(\n\t\t\t\t\"payloads\",\n\t\t\t\tbudgets?.payloads ?? DEFAULT_KIND_BUDGETS.payloads,\n\t\t\t),\n\t\t};\n\t}\n\n\tpush<K extends RingKind>(kind: K, message: RingMessage[K]): void {\n\t\t(this.rings[kind] as KindRing<K>).push(message);\n\t}\n\n\t// peek returns up to maxPerKind items from each kind without removing them.\n\tpeek(maxPerKind = 100): RingItem[] {\n\t\tconst out: RingItem[] = [];\n\t\tfor (const kind of [\"ops\", \"logs\", \"metrics\", \"payloads\"] as RingKind[]) {\n\t\t\tout.push(...(this.rings[kind] as KindRing<RingKind>).peek(maxPerKind));\n\t\t}\n\t\treturn out;\n\t}\n\n\t// commit releases the acked items from each kind ring.\n\tcommit(items: RingItem[]): void {\n\t\tif (items.length === 0) return;\n\t\tconst byKind: Record<RingKind, Set<number>> = {\n\t\t\tops: new Set(),\n\t\t\tlogs: new Set(),\n\t\t\tmetrics: new Set(),\n\t\t\tpayloads: new Set(),\n\t\t};\n\t\tfor (const it of items) byKind[it.kind].add(it.id);\n\t\tfor (const kind of [\"ops\", \"logs\", \"metrics\", \"payloads\"] as RingKind[]) {\n\t\t\t(this.rings[kind] as KindRing<RingKind>).commit(byKind[kind]);\n\t\t}\n\t}\n\n\tdropCount(kind: RingKind): number {\n\t\treturn this.rings[kind].dropCount;\n\t}\n\n\ttotalDropCount(): number {\n\t\treturn (\n\t\t\tthis.rings.ops.dropCount +\n\t\t\tthis.rings.logs.dropCount +\n\t\t\tthis.rings.metrics.dropCount +\n\t\t\tthis.rings.payloads.dropCount\n\t\t);\n\t}\n\n\tsize(kind: RingKind): number {\n\t\treturn this.rings[kind].size;\n\t}\n\n\tbytes(kind: RingKind): number {\n\t\treturn this.rings[kind].bytes;\n\t}\n}\n","// transport.ts — real bidi gRPC Telemetry.Report client.\n// Peeks typed messages from the TelemetryRing into TelemetryBatch frames, writes\n// them on the long-lived bidi stream, and commits (releases) them only after the\n// runtime acks — at-least-once delivery (C1). Reopens the stream on disconnect\n// with an exponential backoff that resets on the first successful ack (C2).\n// @public — см. ./README.md\n\nimport type { ClientDuplexStream } from \"@grpc/grpc-js\";\nimport type {\n\tLog,\n\tMetricPoint,\n\tOpReport,\n\tPayloadAttachment,\n} from \"../pb/servicebridge/v1/telemetry\";\nimport {\n\tLogBatch,\n\tMetricBatch,\n\tOpBatch,\n\tPayloadBatch,\n\ttype TelemetryAck,\n\ttype TelemetryBatch,\n\ttype TelemetryClient,\n} from \"../pb/servicebridge/v1/telemetry\";\nimport type { RingItem, TelemetryRing } from \"./ring\";\n\n/**\n * Minimal stream shape we depend on. The generated gRPC client returns\n * `ClientDuplexStream<TelemetryBatch, TelemetryAck>` which satisfies this.\n * Test mocks implement the same shape with a plain EventEmitter.\n * @internal\n */\nexport interface ClientTelemetryStream {\n\twrite(msg: TelemetryBatch): boolean;\n\tend(): void;\n\ton(event: \"data\", listener: (ack: TelemetryAck) => void): unknown;\n\ton(event: \"end\", listener: () => void): unknown;\n\ton(event: \"error\", listener: (err: Error) => void): unknown;\n\ton(event: string, listener: (...args: never[]) => void): unknown;\n}\n\n/**\n * Minimal client shape. Production wires a real `TelemetryClient` via the\n * adapter inside `service-bridge.ts`. Test mocks implement this directly.\n * @internal\n */\nexport interface TelemetryClientLike {\n\topenStream(): ClientTelemetryStream;\n}\n\n/** @internal */\nexport function adaptTelemetryClient(\n\tclient: TelemetryClient,\n): TelemetryClientLike {\n\treturn {\n\t\topenStream(): ClientTelemetryStream {\n\t\t\tconst stream = client.report() as ClientDuplexStream<\n\t\t\t\tTelemetryBatch,\n\t\t\t\tTelemetryAck\n\t\t\t>;\n\t\t\treturn stream as unknown as ClientTelemetryStream;\n\t\t},\n\t};\n}\n\n/**\n * Observability hook. Fires when the SDK learns about dropped telemetry — either\n * from the runtime (`serverDrops` rises) or from the local ring overflow\n * (`ringDrops` rises). Lets the host surface a metric/log so backpressure is not\n * silent (C4). @public — см. ./README.md\n */\nexport type DropObserver = (info: {\n\tserverDrops: number;\n\tringDrops: number;\n\tbackpressureLevel: number;\n}) => void;\n\n/** @public — см. ./README.md */\nexport interface TelemetryTransportOptions {\n\tclient: TelemetryClientLike;\n\tring: TelemetryRing;\n\t/** Periodic flush interval in ms. Default 250ms. */\n\tflushIntervalMs?: number;\n\t/** Max items per batch (per kind). Default 256. */\n\tmaxBatchItems?: number;\n\t/** Reconnect backoff ladder in ms. Default [1000, 5000, 15000, 30000]. */\n\treconnectDelays?: number[];\n\t/** Called when server-side or ring drop counts rise. Optional. */\n\tonDrop?: DropObserver;\n}\n\nconst DEFAULT_FLUSH_INTERVAL_MS = 250;\nconst DEFAULT_MAX_BATCH_ITEMS = 256;\nconst DEFAULT_RECONNECT_DELAYS = [1_000, 5_000, 15_000, 30_000];\n\n/**\n * TelemetryTransport owns the lifecycle of the Telemetry.Report bidi stream:\n *\n * - Periodically peeks the ring and writes TelemetryBatch frames, tracking the\n * peeked items as in-flight.\n * - Commits (releases) in-flight items only when the runtime acks — at-least-once.\n * - On `error`/`end` from the stream — drops the in-flight marker (items stay in\n * the ring) and reopens with an exponential backoff.\n * - Reconnect backoff resets on the FIRST successful ack, not on openStream.\n * - On `drainReason` ack — flushes once more, closes the local end gracefully.\n *\n * @public — см. ./README.md\n */\nexport class TelemetryTransport {\n\tprivate readonly client: TelemetryClientLike;\n\tprivate readonly ring: TelemetryRing;\n\tprivate readonly flushIntervalMs: number;\n\tprivate readonly maxBatchItems: number;\n\tprivate readonly reconnectDelays: number[];\n\tprivate readonly onDrop?: DropObserver;\n\n\tprivate stream: ClientTelemetryStream | null = null;\n\tprivate flushTimer: ReturnType<typeof setInterval> | null = null;\n\tprivate reconnectTimer: ReturnType<typeof setTimeout> | null = null;\n\tprivate backpressureLevel = 0;\n\tprivate draining = false;\n\tprivate stopped = false;\n\tprivate reconnectAttempt = 0;\n\t// Items written on the current stream but not yet released. Committed on the\n\t// next ack; left in the ring (uncommitted) if the stream dies first.\n\tprivate inflight: RingItem[] = [];\n\t// Ids currently in-flight, so repeated flushes before an ack do not re-write\n\t// the same items (peek leaves them in the ring).\n\tprivate inflightIds = new Set<number>();\n\t// Last drop counts we reported via onDrop, to fire only on increase.\n\tprivate lastServerDrops = 0;\n\tprivate lastRingDrops = 0;\n\n\tconstructor(opts: TelemetryTransportOptions) {\n\t\tthis.client = opts.client;\n\t\tthis.ring = opts.ring;\n\t\tthis.flushIntervalMs = opts.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS;\n\t\tthis.maxBatchItems = opts.maxBatchItems ?? DEFAULT_MAX_BATCH_ITEMS;\n\t\tthis.reconnectDelays = opts.reconnectDelays ?? DEFAULT_RECONNECT_DELAYS;\n\t\tthis.onDrop = opts.onDrop;\n\t}\n\n\tasync start(): Promise<void> {\n\t\tthis.stopped = false;\n\t\tthis.openStream();\n\t\tthis.flushTimer = setInterval(() => {\n\t\t\tvoid this.flushNow();\n\t\t}, this.flushIntervalMs);\n\t}\n\n\tasync stop(): Promise<void> {\n\t\tthis.stopped = true;\n\t\tif (this.flushTimer) {\n\t\t\tclearInterval(this.flushTimer);\n\t\t\tthis.flushTimer = null;\n\t\t}\n\t\tif (this.reconnectTimer) {\n\t\t\tclearTimeout(this.reconnectTimer);\n\t\t\tthis.reconnectTimer = null;\n\t\t}\n\t\tif (this.stream) {\n\t\t\ttry {\n\t\t\t\t// Best-effort final flush so in-flight ops reach the runtime on shutdown.\n\t\t\t\tthis.writeBatchToStream();\n\t\t\t\tthis.stream.end();\n\t\t\t} catch {\n\t\t\t\t// Stream already torn down — nothing to do.\n\t\t\t}\n\t\t\tthis.stream = null;\n\t\t}\n\t}\n\n\t/**\n\t * Force an immediate flush. Exposed for tests; production also calls it\n\t * periodically via the flush timer. The runtime's backpressure level is\n\t * advisory only — we never pause the flusher, because pausing while producers\n\t * keep pushing causes oldest-drop of START frames in the ring (worse than\n\t * sending). The runtime sheds load on its side via the windowed level.\n\t */\n\tasync flushNow(): Promise<void> {\n\t\tif (this.stopped) return;\n\t\tif (!this.stream) return;\n\t\tthis.writeBatchToStream();\n\t}\n\n\t// writeBatchToStream peeks the ring, writes one TelemetryBatch per non-empty\n\t// kind, and records the peeked items as in-flight (released on the next ack).\n\t// Peek does NOT remove from the ring, so a stream death before the ack leaves\n\t// the items in place for the next stream (at-least-once).\n\tprivate writeBatchToStream(): void {\n\t\tif (!this.stream) return;\n\t\t// Peek leaves items in the ring, so a repeated flush before an ack sees the\n\t\t// same items again — skip the ones already on the wire (in-flight) so we do\n\t\t// not double-write them every tick.\n\t\tconst items = this.ring\n\t\t\t.peek(this.maxBatchItems)\n\t\t\t.filter((it) => !this.inflightIds.has(it.id));\n\t\tif (items.length === 0) return;\n\t\tconst byKind = groupByKind(items);\n\t\tif (byKind.ops.length > 0) {\n\t\t\tthis.stream.write({ ops: OpBatch.fromPartial({ items: byKind.ops }) });\n\t\t}\n\t\tif (byKind.logs.length > 0) {\n\t\t\tthis.stream.write({ logs: LogBatch.fromPartial({ items: byKind.logs }) });\n\t\t}\n\t\tif (byKind.metrics.length > 0) {\n\t\t\tthis.stream.write({\n\t\t\t\tmetrics: MetricBatch.fromPartial({ items: byKind.metrics }),\n\t\t\t});\n\t\t}\n\t\tif (byKind.payloads.length > 0) {\n\t\t\tthis.stream.write({\n\t\t\t\tpayloads: PayloadBatch.fromPartial({ items: byKind.payloads }),\n\t\t\t});\n\t\t}\n\t\t// Track everything written on this stream as in-flight. The next ack\n\t\t// confirms the runtime processed (or at least received) it.\n\t\tfor (const it of items) this.inflightIds.add(it.id);\n\t\tthis.inflight.push(...items);\n\t}\n\n\tprivate openStream(): void {\n\t\tif (this.stopped) return;\n\t\tconst stream = this.client.openStream();\n\t\tthis.stream = stream;\n\t\tstream.on(\"data\", (ack: TelemetryAck) => {\n\t\t\tthis.handleAck(ack);\n\t\t});\n\t\tstream.on(\"error\", () => {\n\t\t\tthis.handleStreamGone();\n\t\t});\n\t\tstream.on(\"end\", () => {\n\t\t\tthis.handleStreamGone();\n\t\t});\n\t}\n\n\tprivate handleAck(ack: TelemetryAck): void {\n\t\t// First successful ack proves the stream is healthy — reset the backoff\n\t\t// ladder so a future disconnect starts from the shortest delay (C2/I12).\n\t\tthis.reconnectAttempt = 0;\n\n\t\tthis.backpressureLevel = ack.backpressureLevel;\n\n\t\t// Release everything written before this ack: the runtime has received it.\n\t\tif (this.inflight.length > 0) {\n\t\t\tthis.ring.commit(this.inflight);\n\t\t\tthis.inflight = [];\n\t\t\tthis.inflightIds.clear();\n\t\t}\n\n\t\tthis.reportDrops(ack);\n\n\t\tif (ack.drainReason && !this.draining) {\n\t\t\tthis.draining = true;\n\t\t\t// Final flush of everything still in the ring, then graceful local close.\n\t\t\t// The runtime sends EOF; handleStreamGone reopens after a delay so future\n\t\t\t// ops are not silently dropped if the process keeps running.\n\t\t\tthis.writeBatchToStream();\n\t\t\ttry {\n\t\t\t\tthis.stream?.end();\n\t\t\t} catch {\n\t\t\t\t// Already torn down.\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate reportDrops(ack: TelemetryAck): void {\n\t\tif (!this.onDrop) return;\n\t\tconst serverDrops = Number(ack.dropCountServerSide);\n\t\tconst ringDrops = this.ring.totalDropCount();\n\t\tif (serverDrops > this.lastServerDrops || ringDrops > this.lastRingDrops) {\n\t\t\tthis.lastServerDrops = serverDrops;\n\t\t\tthis.lastRingDrops = ringDrops;\n\t\t\tthis.onDrop({\n\t\t\t\tserverDrops,\n\t\t\t\tringDrops,\n\t\t\t\tbackpressureLevel: ack.backpressureLevel,\n\t\t\t});\n\t\t}\n\t}\n\n\tprivate handleStreamGone(): void {\n\t\t// In-flight items were never acked — drop the marker, leave them in the\n\t\t// ring. They are re-peeked and resent on the next stream (at-least-once).\n\t\tthis.inflight = [];\n\t\tthis.inflightIds.clear();\n\t\tthis.draining = false;\n\t\tthis.stream = null;\n\t\tif (this.stopped) return;\n\t\tconst delay =\n\t\t\tthis.reconnectDelays[\n\t\t\t\tMath.min(this.reconnectAttempt, this.reconnectDelays.length - 1)\n\t\t\t] ??\n\t\t\tthis.reconnectDelays[this.reconnectDelays.length - 1] ??\n\t\t\t1000;\n\t\tthis.reconnectAttempt++;\n\t\tif (this.reconnectTimer) clearTimeout(this.reconnectTimer);\n\t\tthis.reconnectTimer = setTimeout(() => {\n\t\t\tthis.reconnectTimer = null;\n\t\t\tif (this.stopped) return;\n\t\t\tthis.openStream();\n\t\t}, delay);\n\t}\n}\n\ninterface Grouped {\n\tops: OpReport[];\n\tlogs: Log[];\n\tmetrics: MetricPoint[];\n\tpayloads: PayloadAttachment[];\n}\n\nfunction groupByKind(items: RingItem[]): Grouped {\n\tconst out: Grouped = { ops: [], logs: [], metrics: [], payloads: [] };\n\tfor (const it of items) {\n\t\tif (it.kind === \"ops\") out.ops.push(it.message as OpReport);\n\t\telse if (it.kind === \"logs\") out.logs.push(it.message as Log);\n\t\telse if (it.kind === \"metrics\") out.metrics.push(it.message as MetricPoint);\n\t\telse if (it.kind === \"payloads\")\n\t\t\tout.payloads.push(it.message as PayloadAttachment);\n\t}\n\treturn out;\n}\n","// Canonical JSON serializer for workflow graph fingerprinting (ADR-W-002).\n//\n// Rules:\n// - Object keys sorted lexicographically (Unicode codepoint order).\n// - No whitespace.\n// - Arrays preserve order (semantic — DAG steps).\n// - Numbers, booleans, null, strings — JSON.stringify defaults.\n// - `undefined` properties and functions are omitted (functions appear in\n// LocalStep.fn — they are not part of the graph fingerprint).\n//\n// Fingerprint = sha256(canonical_bytes), hex-encoded.\n//\n// @internal — см. ./README.md\n\nimport { createHash } from \"node:crypto\";\n\nexport function canonicalize(value: unknown): string {\n\treturn stringify(value);\n}\n\nexport function fingerprint(value: unknown): string {\n\tconst canonical = canonicalize(value);\n\treturn createHash(\"sha256\").update(canonical).digest(\"hex\");\n}\n\nfunction stringify(v: unknown): string {\n\tif (v === null) return \"null\";\n\tconst t = typeof v;\n\tif (t === \"string\") return JSON.stringify(v);\n\tif (t === \"number\") {\n\t\tif (!Number.isFinite(v)) {\n\t\t\tthrow new Error(\n\t\t\t\t`workflow/canonical: non-finite number not representable in JSON: ${String(v)}`,\n\t\t\t);\n\t\t}\n\t\treturn JSON.stringify(v);\n\t}\n\tif (t === \"boolean\") return v ? \"true\" : \"false\";\n\tif (t === \"undefined\" || t === \"function\") {\n\t\t// undefined / function never appear as JSON values; callers must\n\t\t// strip them before serialization. The case is reached only for\n\t\t// element-of-array contexts.\n\t\treturn \"null\";\n\t}\n\tif (Array.isArray(v)) {\n\t\treturn `[${v.map((x) => stringify(stripUnencodable(x))).join(\",\")}]`;\n\t}\n\t// object\n\tconst obj = v as Record<string, unknown>;\n\tconst keys = Object.keys(obj)\n\t\t.filter((k) => {\n\t\t\tconst val = obj[k];\n\t\t\treturn val !== undefined && typeof val !== \"function\";\n\t\t})\n\t\t.sort();\n\tconst parts: string[] = [];\n\tfor (const k of keys) {\n\t\tparts.push(`${JSON.stringify(k)}:${stringify(obj[k])}`);\n\t}\n\treturn `{${parts.join(\",\")}}`;\n}\n\nfunction stripUnencodable(x: unknown): unknown {\n\treturn x === undefined || typeof x === \"function\" ? null : x;\n}\n","// Workflow-domain error classes surfaced to callers.\n//\n// @public — см. ./README.md\n\n// WorkflowAccessDeniedError — gate #5 bilateral check failed on workflow.Start\n// (ADR-0014 / ADR-W-016). Maps from gRPC PERMISSION_DENIED.\nexport class WorkflowAccessDeniedError extends Error {\n\tconstructor(\n\t\tpublic readonly workflowName: string,\n\t\tpublic readonly reason: string,\n\t) {\n\t\tsuper(`workflow.start(\"${workflowName}\"): access denied — ${reason}`);\n\t\tthis.name = \"WorkflowAccessDeniedError\";\n\t}\n}\n\n// WorkflowNotFoundError — runtime has no definition with that name (after\n// fingerprint resolution).\nexport class WorkflowNotFoundError extends Error {\n\tconstructor(public readonly workflowName: string) {\n\t\tsuper(`workflow.start(\"${workflowName}\"): not found`);\n\t\tthis.name = \"WorkflowNotFoundError\";\n\t}\n}\n\n// WorkflowTerminalError — Signal/Cancel attempted against a run already in a\n// terminal state.\nexport class WorkflowTerminalError extends Error {\n\tconstructor(\n\t\tpublic readonly runId: string,\n\t\tpublic readonly status: string,\n\t) {\n\t\tsuper(`workflow run ${runId}: already terminal (${status})`);\n\t\tthis.name = \"WorkflowTerminalError\";\n\t}\n}\n","// JSONPath-lite evaluator for workflow state expressions.\n//\n// Supported syntax (workflows.md §JSONPath-lite):\n// - $.foo.bar — path lookup\n// - $.list[N] — array index (non-negative integer)\n// - $.list[*] — entire array (passes through)\n// - $.list[*].field — map field over every array element\n//\n// Anything outside this grammar — invalid expression, throws.\n// Strings not starting with \"$.\" are literals (returned as-is).\n// { literal: \"$.weird\" } escapes a literal that would otherwise parse.\n//\n// @internal — см. ./README.md\n\n// JsonExpression is the declarative expression type accepted in `input`,\n// `idempotencyKey`, `forEach.from`, `when`, `compensate.input` etc.\n// - string starting with \"$.\" — path\n// - { literal: string } — escape for literals that look like paths\n// - any other JSON value (literal object/array/number/boolean/null) — passes through,\n// but object children are recursively evaluated as JsonExpressions\nexport type JsonExpression =\n\t| string\n\t| number\n\t| boolean\n\t| null\n\t| { literal: string }\n\t| JsonExpression[]\n\t| { [key: string]: JsonExpression };\n\n// Predicate — `when` clauses.\nexport type Predicate =\n\t| string // truthy JsonExpression\n\t| { not: Predicate }\n\t| { equals: [JsonExpression, JsonExpression] }\n\t| { in: [JsonExpression, JsonExpression] } // [value, array]\n\t| { and: Predicate[] }\n\t| { or: Predicate[] };\n\nexport type State = Record<string, unknown>;\n\n// JsonPathError is thrown for malformed path expressions. Missing paths are\n// NOT errors — they resolve to `undefined`.\nexport class JsonPathError extends Error {\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic readonly expr: string,\n\t) {\n\t\tsuper(`workflow/jsonpath: ${message}: \"${expr}\"`);\n\t\tthis.name = \"JsonPathError\";\n\t}\n}\n\n// PATH_TOKEN_RE matches one path segment after the leading \"$\":\n// .name — dotted identifier (alnum + underscore)\n// [123] — numeric index\n// [*] — wildcard\n// Anything else fails parsing.\nconst PATH_TOKEN_RE = /^\\.([a-zA-Z_][a-zA-Z0-9_]*)|^\\[(\\*|\\d+)\\]/;\n\nfunction isLiteralEscape(v: unknown): v is { literal: string } {\n\treturn (\n\t\ttypeof v === \"object\" &&\n\t\tv !== null &&\n\t\t!Array.isArray(v) &&\n\t\tObject.keys(v).length === 1 &&\n\t\ttypeof (v as { literal?: unknown }).literal === \"string\"\n\t);\n}\n\n// evalPath resolves a `$.…` path against state. Returns `undefined` on miss.\n// Throws JsonPathError on syntax errors.\nexport function evalPath(expr: string, state: State): unknown {\n\tif (!expr.startsWith(\"$\")) {\n\t\tthrow new JsonPathError(\"path must start with $\", expr);\n\t}\n\tlet rest = expr.slice(1);\n\t// Iterator over the current value(s). Starts as a single scalar (state).\n\t// Wildcards convert it into an array; subsequent `.field` maps over it.\n\tlet cursor: unknown = state;\n\tlet wildcardActive = false;\n\n\twhile (rest.length > 0) {\n\t\tconst m = PATH_TOKEN_RE.exec(rest);\n\t\tif (!m) {\n\t\t\tthrow new JsonPathError(\"unparsable token\", expr);\n\t\t}\n\t\trest = rest.slice(m[0].length);\n\t\tconst field = m[1];\n\t\tconst bracket = m[2];\n\n\t\tif (field !== undefined) {\n\t\t\tif (wildcardActive && Array.isArray(cursor)) {\n\t\t\t\tcursor = cursor.map((item) =>\n\t\t\t\t\titem !== null && typeof item === \"object\"\n\t\t\t\t\t\t? (item as Record<string, unknown>)[field]\n\t\t\t\t\t\t: undefined,\n\t\t\t\t);\n\t\t\t} else if (cursor !== null && typeof cursor === \"object\") {\n\t\t\t\tcursor = (cursor as Record<string, unknown>)[field];\n\t\t\t} else {\n\t\t\t\tcursor = undefined;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\t// bracket access\n\t\tif (bracket === \"*\") {\n\t\t\tif (cursor === undefined || cursor === null) {\n\t\t\t\tcursor = [];\n\t\t\t\twildcardActive = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!Array.isArray(cursor)) {\n\t\t\t\tthrow new JsonPathError(\"[*] on non-array\", expr);\n\t\t\t}\n\t\t\twildcardActive = true;\n\t\t\tcontinue;\n\t\t}\n\t\t// numeric index\n\t\tconst idx = Number.parseInt(bracket!, 10);\n\t\tif (Array.isArray(cursor)) {\n\t\t\tcursor = cursor[idx];\n\t\t} else {\n\t\t\tcursor = undefined;\n\t\t}\n\t\t// numeric index collapses wildcard if it was active\n\t\twildcardActive = false;\n\t}\n\n\treturn cursor;\n}\n\n// evalLiteralOrPath evaluates a JsonExpression node against state.\n// - \"$.foo\" → path lookup\n// - \"literal\" → \"literal\"\n// - { literal: \"x\" } → \"x\"\n// - array → array of evaluated elements\n// - object → object with evaluated values\n// - number/bool/null → passed through\nexport function evalLiteralOrPath(expr: JsonExpression, state: State): unknown {\n\tif (expr === null) return null;\n\tif (typeof expr === \"string\") {\n\t\treturn expr.startsWith(\"$.\") || expr === \"$\" ? evalPath(expr, state) : expr;\n\t}\n\tif (typeof expr === \"number\" || typeof expr === \"boolean\") return expr;\n\tif (Array.isArray(expr)) {\n\t\treturn expr.map((e) => evalLiteralOrPath(e, state));\n\t}\n\tif (isLiteralEscape(expr)) return expr.literal;\n\tconst out: Record<string, unknown> = {};\n\tfor (const [k, v] of Object.entries(expr)) {\n\t\tout[k] = evalLiteralOrPath(v as JsonExpression, state);\n\t}\n\treturn out;\n}\n\nfunction deepEqual(a: unknown, b: unknown): boolean {\n\tif (a === b) return true;\n\tif (a === null || b === null) return false;\n\tif (typeof a !== typeof b) return false;\n\tif (typeof a !== \"object\") return false;\n\tif (Array.isArray(a) !== Array.isArray(b)) return false;\n\tif (Array.isArray(a)) {\n\t\tconst ba = b as unknown[];\n\t\tif (a.length !== ba.length) return false;\n\t\treturn a.every((v, i) => deepEqual(v, ba[i]));\n\t}\n\tconst ao = a as Record<string, unknown>;\n\tconst bo = b as Record<string, unknown>;\n\tconst ak = Object.keys(ao);\n\tconst bk = Object.keys(bo);\n\tif (ak.length !== bk.length) return false;\n\treturn ak.every((k) => deepEqual(ao[k], bo[k]));\n}\n\n// evalPredicate evaluates a `when` predicate to boolean.\nexport function evalPredicate(pred: Predicate, state: State): boolean {\n\tif (typeof pred === \"string\") {\n\t\treturn Boolean(evalLiteralOrPath(pred, state));\n\t}\n\tif (\"not\" in pred) return !evalPredicate(pred.not, state);\n\tif (\"equals\" in pred) {\n\t\tconst [l, r] = pred.equals;\n\t\treturn deepEqual(evalLiteralOrPath(l, state), evalLiteralOrPath(r, state));\n\t}\n\tif (\"in\" in pred) {\n\t\tconst [v, arr] = pred.in;\n\t\tconst value = evalLiteralOrPath(v, state);\n\t\tconst list = evalLiteralOrPath(arr, state);\n\t\tif (!Array.isArray(list)) return false;\n\t\treturn list.some((x) => deepEqual(x, value));\n\t}\n\tif (\"and\" in pred) return pred.and.every((p) => evalPredicate(p, state));\n\tif (\"or\" in pred) return pred.or.some((p) => evalPredicate(p, state));\n\tthrow new Error(\n\t\t`workflow/jsonpath: unknown predicate shape: ${JSON.stringify(pred)}`,\n\t);\n}\n","// Workflow graph static validation.\n//\n// Per ADR-W-018, this validator covers ONLY graph control:\n// - id uniqueness and format `^[a-z0-9_]+$`\n// - waitFor topological acyclicity\n// - depth and size caps\n// - compensate only on call/publish\n// - forEach.from JSONPath parseable\n// - workflow self-ref check\n// - JsonExpression syntax (parses every $.… expression)\n//\n// It does NOT validate `opts` (retry, transport, idempotencyKey, timeout, …).\n// Those live with the owner module — checks happen at step execution time via\n// `sb.rpc.call`/`sb.event.publish`/`sb.workflow.start`.\n//\n// @internal — см. ./README.md\n\nimport type { JsonExpression } from \"./jsonpath\";\nimport { evalPath, JsonPathError } from \"./jsonpath\";\nimport type { CompensateSpec, Step, WorkflowDef } from \"./types\";\n\nexport class WorkflowValidationError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(`workflow/validate: ${message}`);\n\t\tthis.name = \"WorkflowValidationError\";\n\t}\n}\n\nconst ID_RE = /^[a-z0-9_]+$/;\nconst MAX_DEPTH = 16;\nconst MAX_STEPS = 512;\n\nexport interface ValidateOptions {\n\t// Workflow name — used for self-ref check on `type: \"workflow\"` steps.\n\tworkflowName: string;\n}\n\nexport function validate(def: WorkflowDef, opts: ValidateOptions): void {\n\tif (!def || !Array.isArray(def.steps)) {\n\t\tthrow new WorkflowValidationError(\"def.steps must be an array\");\n\t}\n\tconst counter = { count: 0 };\n\tconst allIds = new Set<string>();\n\twalkSteps(def.steps, 0, allIds, counter, opts);\n\tvalidateWaitFor(def.steps, allIds);\n}\n\nfunction walkSteps(\n\tsteps: Step[],\n\tdepth: number,\n\tallIds: Set<string>,\n\tcounter: { count: number },\n\topts: ValidateOptions,\n): void {\n\tif (depth > MAX_DEPTH) {\n\t\tthrow new WorkflowValidationError(\n\t\t\t`max nesting depth ${MAX_DEPTH} exceeded`,\n\t\t);\n\t}\n\tfor (const step of steps) {\n\t\tcounter.count += 1;\n\t\tif (counter.count > MAX_STEPS) {\n\t\t\tthrow new WorkflowValidationError(`max step count ${MAX_STEPS} exceeded`);\n\t\t}\n\t\tvalidateStep(step, depth, allIds, counter, opts);\n\t}\n}\n\nfunction validateStep(\n\tstep: Step,\n\tdepth: number,\n\tallIds: Set<string>,\n\tcounter: { count: number },\n\topts: ValidateOptions,\n): void {\n\tif (typeof step.id !== \"string\" || !ID_RE.test(step.id)) {\n\t\tthrow new WorkflowValidationError(\n\t\t\t`step id must match ${ID_RE} (got \"${String(step.id)}\")`,\n\t\t);\n\t}\n\tif (allIds.has(step.id)) {\n\t\tthrow new WorkflowValidationError(`duplicate step id \"${step.id}\"`);\n\t}\n\tallIds.add(step.id);\n\n\t// compensate — only on call/publish\n\tconst hasCompensate = (step as { compensate?: CompensateSpec }).compensate;\n\tif (hasCompensate && step.type !== \"call\" && step.type !== \"publish\") {\n\t\tthrow new WorkflowValidationError(\n\t\t\t`step \"${step.id}\": compensate allowed only on call/publish steps (got ${step.type})`,\n\t\t);\n\t}\n\tif (hasCompensate) {\n\t\tvalidateJsonExpression(hasCompensate.input, `${step.id}.compensate.input`);\n\t}\n\n\tswitch (step.type) {\n\t\tcase \"call\": {\n\t\t\tvalidateMaybePathOrLiteral(step.service, `${step.id}.service`);\n\t\t\tvalidateMaybePathOrLiteral(step.method, `${step.id}.method`);\n\t\t\tvalidateJsonExpression(step.input, `${step.id}.input`);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"publish\": {\n\t\t\tvalidateMaybePathOrLiteral(step.event, `${step.id}.event`);\n\t\t\tvalidateJsonExpression(step.input, `${step.id}.input`);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"sleep\": {\n\t\t\tif (\n\t\t\t\ttypeof step.durationSec !== \"number\" ||\n\t\t\t\t!Number.isInteger(step.durationSec) ||\n\t\t\t\tstep.durationSec < 0\n\t\t\t) {\n\t\t\t\tthrow new WorkflowValidationError(\n\t\t\t\t\t`step \"${step.id}\": durationSec must be a non-negative integer`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase \"wait_event\": {\n\t\t\tif (typeof step.event !== \"string\" || step.event.length === 0) {\n\t\t\t\tthrow new WorkflowValidationError(\n\t\t\t\t\t`step \"${step.id}\": wait_event.event must be a non-empty string`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (step.filter) {\n\t\t\t\tfor (const [k, v] of Object.entries(step.filter)) {\n\t\t\t\t\tvalidateJsonExpression(v, `${step.id}.filter.${k}`);\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase \"wait_signal\": {\n\t\t\tif (typeof step.signal !== \"string\" || step.signal.length === 0) {\n\t\t\t\tthrow new WorkflowValidationError(\n\t\t\t\t\t`step \"${step.id}\": wait_signal.signal must be a non-empty string`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase \"workflow\": {\n\t\t\tvalidateMaybePathOrLiteral(step.workflow, `${step.id}.workflow`);\n\t\t\tif (\n\t\t\t\ttypeof step.workflow === \"string\" &&\n\t\t\t\t!step.workflow.startsWith(\"$.\") &&\n\t\t\t\tstep.workflow === opts.workflowName\n\t\t\t) {\n\t\t\t\tthrow new WorkflowValidationError(\n\t\t\t\t\t`step \"${step.id}\": workflow self-reference to \"${opts.workflowName}\" rejected (ADR-W-015 static)`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tvalidateJsonExpression(step.input, `${step.id}.input`);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"parallel\":\n\t\tcase \"sequence\": {\n\t\t\tif (step.forEach) {\n\t\t\t\tvalidateMaybePathOrLiteral(\n\t\t\t\t\tstep.forEach.from,\n\t\t\t\t\t`${step.id}.forEach.from`,\n\t\t\t\t);\n\t\t\t\tif (\n\t\t\t\t\ttypeof step.forEach.as !== \"string\" ||\n\t\t\t\t\t!ID_RE.test(step.forEach.as)\n\t\t\t\t) {\n\t\t\t\t\tthrow new WorkflowValidationError(\n\t\t\t\t\t\t`step \"${step.id}\": forEach.as must match ${ID_RE}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!Array.isArray(step.steps) || step.steps.length === 0) {\n\t\t\t\tthrow new WorkflowValidationError(\n\t\t\t\t\t`step \"${step.id}\": ${step.type}.steps must be a non-empty array`,\n\t\t\t\t);\n\t\t\t}\n\t\t\twalkSteps(step.steps, depth + 1, allIds, counter, opts);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"local\": {\n\t\t\tif (typeof step.fn !== \"function\") {\n\t\t\t\tthrow new WorkflowValidationError(\n\t\t\t\t\t`step \"${step.id}\": local.fn must be a function`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = step;\n\t\t\tthrow new WorkflowValidationError(\n\t\t\t\t`unknown step type: ${JSON.stringify(_exhaustive)}`,\n\t\t\t);\n\t\t}\n\t}\n}\n\nfunction validateMaybePathOrLiteral(\n\tv: string | JsonExpression,\n\tctx: string,\n): void {\n\tif (typeof v === \"string\") {\n\t\tif (v.startsWith(\"$.\") || v === \"$\") {\n\t\t\tvalidatePathSyntax(v, ctx);\n\t\t}\n\t\treturn;\n\t}\n\tvalidateJsonExpression(v, ctx);\n}\n\nfunction validateJsonExpression(expr: JsonExpression, ctx: string): void {\n\tif (expr === null) return;\n\tif (typeof expr === \"string\") {\n\t\tif (expr.startsWith(\"$.\") || expr === \"$\") {\n\t\t\tvalidatePathSyntax(expr, ctx);\n\t\t}\n\t\treturn;\n\t}\n\tif (\n\t\ttypeof expr === \"number\" ||\n\t\ttypeof expr === \"boolean\" ||\n\t\ttypeof expr === \"undefined\"\n\t) {\n\t\treturn;\n\t}\n\tif (Array.isArray(expr)) {\n\t\tfor (let i = 0; i < expr.length; i++) {\n\t\t\tvalidateJsonExpression(expr[i] as JsonExpression, `${ctx}[${i}]`);\n\t\t}\n\t\treturn;\n\t}\n\t// object — { literal } passes through, else recurse\n\tconst obj = expr as Record<string, JsonExpression>;\n\tif (Object.keys(obj).length === 1 && typeof obj.literal === \"string\") return;\n\tfor (const [k, v] of Object.entries(obj)) {\n\t\tvalidateJsonExpression(v, `${ctx}.${k}`);\n\t}\n}\n\nfunction validatePathSyntax(expr: string, ctx: string): void {\n\ttry {\n\t\tevalPath(expr, {});\n\t} catch (err) {\n\t\tif (err instanceof JsonPathError) {\n\t\t\tthrow new WorkflowValidationError(\n\t\t\t\t`${ctx}: invalid JsonExpression: ${err.message}`,\n\t\t\t);\n\t\t}\n\t\tthrow err;\n\t}\n}\n\n// validateWaitFor — flat topo on top-level + recursive on groups; reports\n// cycles and unknown references.\nfunction validateWaitFor(steps: Step[], allIds: Set<string>): void {\n\tconst visited = new Set<string>();\n\tconst onStack = new Set<string>();\n\tconst byId = new Map<string, Step>();\n\tindexById(steps, byId);\n\n\tfunction visit(id: string): void {\n\t\tif (visited.has(id)) return;\n\t\tif (onStack.has(id)) {\n\t\t\tthrow new WorkflowValidationError(\n\t\t\t\t`waitFor cycle detected at step \"${id}\"`,\n\t\t\t);\n\t\t}\n\t\tconst step = byId.get(id);\n\t\tif (!step) return; // unknown id surfaces below\n\t\tonStack.add(id);\n\t\tconst deps = step.waitFor ?? [];\n\t\tfor (const dep of deps) {\n\t\t\tif (!allIds.has(dep)) {\n\t\t\t\tthrow new WorkflowValidationError(\n\t\t\t\t\t`step \"${id}\": waitFor references unknown step \"${dep}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tvisit(dep);\n\t\t}\n\t\tonStack.delete(id);\n\t\tvisited.add(id);\n\t}\n\n\tfor (const id of byId.keys()) visit(id);\n}\n\nfunction indexById(steps: Step[], out: Map<string, Step>): void {\n\tfor (const s of steps) {\n\t\tout.set(s.id, s);\n\t\tif (s.type === \"parallel\" || s.type === \"sequence\") {\n\t\t\tindexById(s.steps, out);\n\t\t}\n\t}\n}\n","// @public — см. ./README.md\nimport type {\n\tQueryRunResponse,\n\tRunStatusUpdate,\n\tWorkflowsClient,\n} from \"../pb/servicebridge/v1/workflows\";\nimport type { Registry, WorkflowHandlerOpts } from \"../registry/registry\";\nimport { currentTraceContext } from \"../telemetry/context\";\nimport { formatXSbTrace } from \"../telemetry/wire-trace\";\nimport { canonicalize, fingerprint } from \"./canonical\";\nimport {\n\tWorkflowAccessDeniedError,\n\tWorkflowNotFoundError,\n\tWorkflowTerminalError,\n} from \"./errors\";\nimport type { WorkflowDef, WorkflowStartOpts } from \"./types\";\nimport { validate } from \"./validate\";\n\nexport type { WorkflowDef } from \"./types\";\n\n// CanonicalGraph is the on-wire shape that runtime persists in\n// `workflow_definitions.graph` (ADR-W-002).\ninterface CanonicalGraph {\n\tgraph: WorkflowDef[\"steps\"];\n\tretry?: WorkflowDef[\"retry\"];\n\tmaxParallelism?: number;\n\ttimeoutSec?: number;\n\t// Per ADR-W-009: the JSON Schema for run input lives inside the canonical\n\t// graph and is what the runtime stores in workflow_definitions.input_schema.\n\tinputSchema?: WorkflowDef[\"input\"];\n}\n\n// gRPC status codes — match @grpc/grpc-js numeric values; kept numeric to\n// avoid the dynamic import.\nconst GRPC_NOT_FOUND = 5;\nconst GRPC_PERMISSION_DENIED = 7;\nconst GRPC_FAILED_PRECONDITION = 9;\n\ninterface GrpcLikeError {\n\tcode?: number;\n\tdetails?: string;\n\tmessage: string;\n}\n\n// Sink for call-time policy denials; the owner wires it to emit\n// `policy_violation`. Structural type avoids importing from connection.\ntype PolicyViolationSink = (v: {\n\tdeclaration: string;\n\tvalue: string;\n\tdenySide: string;\n\treason: string;\n}) => void;\n\nexport class WorkflowDomain {\n\t// rpc is set by ServiceBridge.start(); until then caller-side ops throw.\n\tprivate rpc: WorkflowsClient | null = null;\n\n\tconstructor(\n\t\tprivate readonly registry: Registry,\n\t\tprivate readonly onPolicyViolation?: PolicyViolationSink,\n\t) {}\n\n\t// @internal — wired by ServiceBridge.start() once the gRPC channel is up.\n\t_attachRpc(rpc: WorkflowsClient): void {\n\t\tthis.rpc = rpc;\n\t}\n\n\thandle(name: string, def: WorkflowDef, opts?: WorkflowHandlerOpts): void {\n\t\tvalidate(def, { workflowName: name });\n\n\t\tconst inputSchema = opts?.input ?? def.input;\n\t\tconst canonical: CanonicalGraph = {\n\t\t\tgraph: def.steps,\n\t\t\tretry: def.retry,\n\t\t\tmaxParallelism: def.maxParallelism,\n\t\t\ttimeoutSec: def.timeoutSec,\n\t\t\tinputSchema,\n\t\t};\n\t\tconst canonicalJson = canonicalize(canonical);\n\t\tconst fp = fingerprint(canonical);\n\t\tconst graphBuf = Buffer.from(canonicalJson, \"utf8\");\n\n\t\tthis.registry._handle.workflow(\n\t\t\tname,\n\t\t\tdef.steps,\n\t\t\tinputSchema ? { input: inputSchema } : undefined,\n\t\t\tgraphBuf,\n\t\t\tfp,\n\t\t);\n\t}\n\n\t// start — schedule a new run. Per ADR-W-016 gate #5 PermissionDenied\n\t// surfaces as WorkflowAccessDeniedError.\n\tasync start(\n\t\tname: string,\n\t\tinput: unknown,\n\t\topts?: WorkflowStartOpts,\n\t): Promise<{ runId: string }> {\n\t\tconst rpc = this.requireRpc();\n\t\t// Trace context propagation (T-017 X-SB-Trace): when an active trace\n\t\t// context exists in ALS, format it into x_sb_trace so a nested workflow\n\t\t// run inherits the parent trace and root-op linkage. Empty string when\n\t\t// no scope is active — runtime mints a fresh root in that case.\n\t\tconst ctx = currentTraceContext();\n\t\tconst xSbTrace = ctx ? formatXSbTrace(ctx.traceId, ctx.parentOpId) : \"\";\n\t\treturn new Promise((resolve, reject) => {\n\t\t\trpc.start(\n\t\t\t\t{\n\t\t\t\t\tworkflowName: name,\n\t\t\t\t\tinput: Buffer.from(JSON.stringify(input ?? null), \"utf8\"),\n\t\t\t\t\tidempotencyKey: opts?.idempotencyKey ?? \"\",\n\t\t\t\t\ttimeoutSec: opts?.timeoutSec ?? 0,\n\t\t\t\t\tparentRunId: opts?.parentRunId ?? \"\",\n\t\t\t\t\txSbTrace,\n\t\t\t\t},\n\t\t\t\t(err: GrpcLikeError | null, resp: { runId: string }) => {\n\t\t\t\t\tif (err)\n\t\t\t\t\t\treturn reject(mapStartError(name, err, this.onPolicyViolation));\n\t\t\t\t\tresolve({ runId: resp.runId });\n\t\t\t\t},\n\t\t\t);\n\t\t});\n\t}\n\n\t// signal — deliver an external signal to a parked wait_signal step.\n\tasync signal(\n\t\trunId: string,\n\t\tsignalName: string,\n\t\tpayload: unknown,\n\t): Promise<void> {\n\t\tconst rpc = this.requireRpc();\n\t\treturn new Promise((resolve, reject) => {\n\t\t\trpc.signal(\n\t\t\t\t{\n\t\t\t\t\trunId,\n\t\t\t\t\tsignalName,\n\t\t\t\t\tpayload: Buffer.from(JSON.stringify(payload ?? null), \"utf8\"),\n\t\t\t\t},\n\t\t\t\t(err) => {\n\t\t\t\t\tif (err)\n\t\t\t\t\t\treturn reject(mapRunError(runId, err, this.onPolicyViolation));\n\t\t\t\t\tresolve();\n\t\t\t\t},\n\t\t\t);\n\t\t});\n\t}\n\n\t// cancel — request cooperative cancellation; runtime moves the run to\n\t// `compensating` and dispatches compensation steps in reverse order.\n\tasync cancel(runId: string): Promise<void> {\n\t\tconst rpc = this.requireRpc();\n\t\treturn new Promise((resolve, reject) => {\n\t\t\trpc.cancel({ runId }, (err) => {\n\t\t\t\tif (err) return reject(mapRunError(runId, err, this.onPolicyViolation));\n\t\t\t\tresolve();\n\t\t\t});\n\t\t});\n\t}\n\n\t// await — block until the run reaches a terminal status. Returns the\n\t// final state map as parsed JSON.\n\tasync await(runId: string): Promise<Record<string, unknown>> {\n\t\tconst rpc = this.requireRpc();\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst stream = rpc.await({ runId });\n\t\t\tlet final: RunStatusUpdate | null = null;\n\t\t\tstream.on(\"data\", (u: RunStatusUpdate) => {\n\t\t\t\tfinal = u;\n\t\t\t});\n\t\t\tstream.on(\"error\", (err: GrpcLikeError) =>\n\t\t\t\treject(mapRunError(runId, err, this.onPolicyViolation)),\n\t\t\t);\n\t\t\tstream.on(\"end\", () => {\n\t\t\t\tif (!final) {\n\t\t\t\t\treturn reject(\n\t\t\t\t\t\tnew Error(`workflow.await(${runId}): stream ended with no update`),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst f = final as RunStatusUpdate;\n\t\t\t\tconst stateJson =\n\t\t\t\t\tf.state.length > 0 ? Buffer.from(f.state).toString(\"utf8\") : \"{}\";\n\t\t\t\tif (f.status !== \"success\") {\n\t\t\t\t\treturn reject(\n\t\t\t\t\t\tnew Error(\n\t\t\t\t\t\t\t`workflow.await(${runId}): terminal status \"${f.status}\"`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tresolve(JSON.parse(stateJson) as Record<string, unknown>);\n\t\t\t\t} catch (parseErr) {\n\t\t\t\t\treject(parseErr);\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n\n\t// query — point-in-time snapshot of run status, state, and per-step info.\n\tasync query(runId: string): Promise<{\n\t\tstatus: string;\n\t\tstate: Record<string, unknown>;\n\t\tsteps: Array<{\n\t\t\tstepId: string;\n\t\t\tstatus: string;\n\t\t\toutput: unknown;\n\t\t\tlastError: string;\n\t\t\tcompensatedBy?: string;\n\t\t}>;\n\t}> {\n\t\tconst rpc = this.requireRpc();\n\t\treturn new Promise((resolve, reject) => {\n\t\t\trpc.query({ runId }, (err, resp: QueryRunResponse) => {\n\t\t\t\tif (err) return reject(mapRunError(runId, err, this.onPolicyViolation));\n\t\t\t\tconst stateJson =\n\t\t\t\t\tresp.state.length > 0\n\t\t\t\t\t\t? Buffer.from(resp.state).toString(\"utf8\")\n\t\t\t\t\t\t: \"{}\";\n\t\t\t\tresolve({\n\t\t\t\t\tstatus: resp.status,\n\t\t\t\t\tstate: JSON.parse(stateJson) as Record<string, unknown>,\n\t\t\t\t\tsteps: resp.steps.map((s) => ({\n\t\t\t\t\t\tstepId: s.stepId,\n\t\t\t\t\t\tstatus: s.status,\n\t\t\t\t\t\toutput:\n\t\t\t\t\t\t\ts.output.length > 0\n\t\t\t\t\t\t\t\t? JSON.parse(Buffer.from(s.output).toString(\"utf8\"))\n\t\t\t\t\t\t\t\t: null,\n\t\t\t\t\t\tlastError: s.lastError,\n\t\t\t\t\t\tcompensatedBy: s.compensatedBy || undefined,\n\t\t\t\t\t})),\n\t\t\t\t});\n\t\t\t});\n\t\t});\n\t}\n\n\t// replay — create a new run forked from `runId` at `fromStepId`. Reuses\n\t// the source frozen_plan and re-executes from the named step.\n\tasync replay(\n\t\trunId: string,\n\t\topts?: { fromStepId?: string },\n\t): Promise<{ runId: string }> {\n\t\tconst rpc = this.requireRpc();\n\t\treturn new Promise((resolve, reject) => {\n\t\t\trpc.replay({ runId, fromStepId: opts?.fromStepId ?? \"\" }, (err, resp) => {\n\t\t\t\tif (err) return reject(mapRunError(runId, err, this.onPolicyViolation));\n\t\t\t\tresolve({ runId: resp.runId });\n\t\t\t});\n\t\t});\n\t}\n\n\tprivate requireRpc(): WorkflowsClient {\n\t\tif (!this.rpc) {\n\t\t\tthrow new Error(\n\t\t\t\t\"workflow: caller-side ops require ServiceBridge.start() to have completed (RPC channel not yet attached)\",\n\t\t\t);\n\t\t}\n\t\treturn this.rpc;\n\t}\n}\n\nfunction mapStartError(\n\tname: string,\n\terr: GrpcLikeError,\n\tonPolicyViolation?: PolicyViolationSink,\n): Error {\n\tif (err.code === GRPC_PERMISSION_DENIED) {\n\t\tconst reason = err.details ?? err.message;\n\t\tonPolicyViolation?.({\n\t\t\tdeclaration: \"workflow.run\",\n\t\t\tvalue: name,\n\t\t\tdenySide: \"self_egress\",\n\t\t\treason,\n\t\t});\n\t\treturn new WorkflowAccessDeniedError(name, reason);\n\t}\n\tif (err.code === GRPC_NOT_FOUND) {\n\t\treturn new WorkflowNotFoundError(name);\n\t}\n\treturn err as unknown as Error;\n}\n\nfunction mapRunError(\n\trunId: string,\n\terr: GrpcLikeError,\n\tonPolicyViolation?: PolicyViolationSink,\n): Error {\n\tif (err.code === GRPC_FAILED_PRECONDITION) {\n\t\treturn new WorkflowTerminalError(runId, err.details ?? err.message);\n\t}\n\tif (err.code === GRPC_PERMISSION_DENIED) {\n\t\tconst reason = err.details ?? err.message;\n\t\tonPolicyViolation?.({\n\t\t\tdeclaration: \"workflow.run\",\n\t\t\tvalue: runId,\n\t\t\tdenySide: \"self_egress\",\n\t\t\treason,\n\t\t});\n\t\treturn new WorkflowAccessDeniedError(runId, reason);\n\t}\n\treturn err as unknown as Error;\n}\n","// Thin gRPC adapter from RuntimeOps (runner-facing) to WorkflowsClient\n// (wire-facing). Used by ServiceBridge to feed the WorkflowSubscriber.\n//\n// All JSON encoding lives here so the runner stays transport-agnostic.\n//\n// @internal — см. ./README.md\n\nimport type { WorkflowsClient } from \"../pb/servicebridge/v1/workflows\";\nimport type { RuntimeOps } from \"./runner\";\n\nexport function makeRuntimeOps(\n\trpc: WorkflowsClient,\n\tgetInstanceId: () => string,\n): RuntimeOps {\n\treturn {\n\t\tbeginStep(args) {\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\trpc.beginStep(\n\t\t\t\t\t{\n\t\t\t\t\t\trunId: args.runId,\n\t\t\t\t\t\tstepId: args.stepId,\n\t\t\t\t\t\tparentStepId: args.parentStepId,\n\t\t\t\t\t\tkind: args.kind,\n\t\t\t\t\t\tinputSnapshot: Buffer.from(\n\t\t\t\t\t\t\tJSON.stringify(args.inputSnapshot ?? null),\n\t\t\t\t\t\t\t\"utf8\",\n\t\t\t\t\t\t),\n\t\t\t\t\t\tleaseEpoch: args.leaseEpoch,\n\t\t\t\t\t\tinstanceId: getInstanceId(),\n\t\t\t\t\t},\n\t\t\t\t\t(err, resp) => {\n\t\t\t\t\t\tif (err) return reject(err);\n\t\t\t\t\t\tif (resp.alreadyDone && resp.cachedOutput.length > 0) {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tconst cached = JSON.parse(\n\t\t\t\t\t\t\t\t\tBuffer.from(resp.cachedOutput).toString(\"utf8\"),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\treturn resolve({ alreadyDone: true, cachedOutput: cached });\n\t\t\t\t\t\t\t} catch (parseErr) {\n\t\t\t\t\t\t\t\treturn reject(parseErr);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tresolve({ alreadyDone: resp.alreadyDone });\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t});\n\t\t},\n\t\tcompleteStep(args) {\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\trpc.completeStep(\n\t\t\t\t\t{\n\t\t\t\t\t\trunId: args.runId,\n\t\t\t\t\t\tstepId: args.stepId,\n\t\t\t\t\t\toutput: Buffer.from(JSON.stringify(args.output ?? null), \"utf8\"),\n\t\t\t\t\t\tleaseEpoch: args.leaseEpoch,\n\t\t\t\t\t},\n\t\t\t\t\t(err) => {\n\t\t\t\t\t\tif (err) return reject(err);\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t});\n\t\t},\n\t\tfailStep(args) {\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\trpc.failStep(\n\t\t\t\t\t{\n\t\t\t\t\t\trunId: args.runId,\n\t\t\t\t\t\tstepId: args.stepId,\n\t\t\t\t\t\terrorCode: args.errorCode,\n\t\t\t\t\t\terrorMessage: args.errorMessage,\n\t\t\t\t\t\tleaseEpoch: args.leaseEpoch,\n\t\t\t\t\t\tretriable: args.retriable,\n\t\t\t\t\t},\n\t\t\t\t\t(err, resp) => {\n\t\t\t\t\t\tif (err) return reject(err);\n\t\t\t\t\t\tresolve({ nextAction: resp.nextAction });\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t});\n\t\t},\n\t\tpark(args) {\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\trpc.park(\n\t\t\t\t\t{\n\t\t\t\t\t\trunId: args.runId,\n\t\t\t\t\t\tstepId: args.stepId,\n\t\t\t\t\t\tleaseEpoch: args.leaseEpoch,\n\t\t\t\t\t\tsleep: args.sleep,\n\t\t\t\t\t\teventWait: args.eventWait,\n\t\t\t\t\t\tsignalWait: args.signalWait,\n\t\t\t\t\t\tnestedRun: args.nestedRun,\n\t\t\t\t\t},\n\t\t\t\t\t(err) => {\n\t\t\t\t\t\tif (err) return reject(err);\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t});\n\t\t},\n\t\tcompleteRun(args) {\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\trpc.completeRun(\n\t\t\t\t\t{\n\t\t\t\t\t\trunId: args.runId,\n\t\t\t\t\t\tfinalState: Buffer.from(\n\t\t\t\t\t\t\tJSON.stringify(args.finalState ?? {}),\n\t\t\t\t\t\t\t\"utf8\",\n\t\t\t\t\t\t),\n\t\t\t\t\t\tleaseEpoch: args.leaseEpoch,\n\t\t\t\t\t\tterminalStatus: args.terminalStatus ?? \"\",\n\t\t\t\t\t},\n\t\t\t\t\t(err) => {\n\t\t\t\t\t\tif (err) return reject(err);\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t});\n\t\t},\n\t};\n}\n","// Builds the opts object passed to sb.rpc.call / sb.event.publish during\n// compensation. Lives in a separate file so the runner module is free of\n// declarative-option field names (anti-regression grep, ADR-W-018).\n//\n// Note: this is pure pass-through. The runner does NOT implement option\n// semantics — they live in the owner modules (rpc/client.ts, events/publisher.ts).\n//\n// @internal — см. ./README.md\n\nimport type { CompensateSpec } from \"./compensate\";\n\nexport function buildCompensateOpts(\n\tcomp: CompensateSpec,\n): Record<string, unknown> {\n\tconst out: Record<string, unknown> = {};\n\tfor (const key of [\n\t\t\"idempotencyKey\",\n\t\t\"retry\",\n\t] as const satisfies readonly (keyof CompensateSpec)[]) {\n\t\tif (comp[key] !== undefined) out[key] = comp[key];\n\t}\n\treturn out;\n}\n","// Thin workflow runner — executes a frozen plan on the owner SDK.\n//\n// ADR-W-018: each case body is exactly\n// (1) eval JsonExpressions in opts/input → (2) await sb.<domain>.<op>(...)\n// → (3) Complete/FailStep.\n// The runner does NOT implement its own retry / backoff / idempotency /\n// circuit-breaker / timeout loop for call/publish/workflow — those live in\n// sb.rpc.call / sb.event.publish / sb.workflow.start and are applied\n// transitively.\n//\n// @internal — см. ./README.md\n\nimport { buildCompensateOpts } from \"./compensate-opts\";\nimport type { JsonExpression, Predicate, State } from \"./jsonpath\";\nimport { evalLiteralOrPath, evalPredicate } from \"./jsonpath\";\nimport type {\n\tCallStep,\n\tCompensateSpec,\n\tLocalStep,\n\tParallelStep,\n\tPublishStep,\n\tSequenceStep,\n\tSleepStep,\n\tStep,\n\tWaitEventStep,\n\tWaitSignalStep,\n\tWorkflowStep,\n} from \"./types\";\n\n// SbDomains — the surface area the runner depends on (ADR-W-018: thin).\n// The real implementation is `ServiceBridge.{rpc,event,workflow}`; tests\n// substitute a mock that observes argument shapes.\nexport interface SbDomains {\n\trpc: {\n\t\tcall(\n\t\t\tservice: string,\n\t\t\tmethod: string,\n\t\t\tpayload: unknown,\n\t\t\topts?: Record<string, unknown>,\n\t\t): Promise<unknown>;\n\t};\n\tevent: {\n\t\tpublish(\n\t\t\tname: string,\n\t\t\tpayload: unknown,\n\t\t\topts?: Record<string, unknown>,\n\t\t): Promise<unknown>;\n\t};\n\tworkflow: {\n\t\tstart(\n\t\t\tname: string,\n\t\t\tinput: unknown,\n\t\t\topts?: Record<string, unknown>,\n\t\t): Promise<{ runId: string }>;\n\t\tawait(runId: string): Promise<unknown>;\n\t};\n}\n\n// RuntimeOps — the runtime-facing checkpoint surface. Real impl talks to\n// gRPC WorkflowsClient; tests can mock.\nexport interface RuntimeOps {\n\tbeginStep(args: {\n\t\trunId: string;\n\t\tstepId: string;\n\t\tparentStepId: string;\n\t\tkind: Step[\"type\"];\n\t\tinputSnapshot: unknown;\n\t\tleaseEpoch: number;\n\t}): Promise<{ alreadyDone: boolean; cachedOutput?: unknown }>;\n\tcompleteStep(args: {\n\t\trunId: string;\n\t\tstepId: string;\n\t\toutput: unknown;\n\t\tleaseEpoch: number;\n\t}): Promise<void>;\n\tfailStep(args: {\n\t\trunId: string;\n\t\tstepId: string;\n\t\terrorCode: string;\n\t\terrorMessage: string;\n\t\tleaseEpoch: number;\n\t\tretriable: boolean;\n\t}): Promise<{ nextAction: string }>;\n\tpark(args: {\n\t\trunId: string;\n\t\tstepId: string;\n\t\tleaseEpoch: number;\n\t\tsleep?: { durationSec: number };\n\t\teventWait?: {\n\t\t\tevent: string;\n\t\t\tfilterJson: string;\n\t\t\ttimeoutSec: number;\n\t\t};\n\t\tsignalWait?: { signal: string; timeoutSec: number };\n\t\tnestedRun?: { childRunId: string };\n\t}): Promise<void>;\n\tcompleteRun(args: {\n\t\trunId: string;\n\t\tfinalState: unknown;\n\t\tleaseEpoch: number;\n\t\tterminalStatus?: string;\n\t}): Promise<void>;\n}\n\nexport interface RunContext {\n\trunId: string;\n\tleaseEpoch: number;\n\tstate: State;\n\tcompensating: boolean;\n\tmaxParallelism: number; // 0 = unlimited\n}\n\n// StepSpanInfo describes the USER.SUBOP step span the runner asks the caller to\n// open around a unit of workflow execution. `role` distinguishes a plain step\n// from the two fanout container levels (the group span, and one branch span per\n// iteration) so the caller can label them and the UI can render the\n// group → branch → step nesting.\nexport interface StepSpanInfo {\n\trunId: string;\n\tstepId: string;\n\tstepName: string;\n\trole: \"step\" | \"group\" | \"branch\" | \"compensation\";\n\tisCompensation?: boolean;\n\tcompensatesForStepId?: string;\n}\n\nexport interface RunnerDeps {\n\tsb: SbDomains;\n\tops: RuntimeOps;\n\t// Optional hook the runner calls around every executed unit (each step,\n\t// each fanout group, each fanout branch, each compensation). The caller\n\t// emits one USER.SUBOP step span and runs `fn` inside a child trace context\n\t// rooted at that span's op_id, so the step's nested sb.rpc.call /\n\t// sb.event.publish / sub-workflow.start inherit the span as their parent\n\t// and the trace renders as a tree. Absent in unit tests that do not assert\n\t// on telemetry — execution then runs unwrapped.\n\twrapStep?: <T>(info: StepSpanInfo, fn: () => Promise<T>) => Promise<T>;\n}\n\n// run executes a frozen plan to completion (or until a Park happens, which\n// surrenders control back to runtime). Returns the final state.\nexport async function run(\n\tsteps: Step[],\n\tctx: RunContext,\n\tdeps: RunnerDeps,\n): Promise<State> {\n\tif (ctx.compensating) {\n\t\tawait runCompensation(steps, ctx, deps);\n\t\treturn ctx.state;\n\t}\n\n\tconst byId = new Map<string, Step>();\n\tindexById(steps, byId);\n\tconst completed = new Set<string>(Object.keys(ctx.state));\n\tcompleted.delete(\"input\"); // input is not a step id\n\n\t// Dependency-based scheduling — repeatedly find steps whose waitFor is\n\t// satisfied and run them, honoring maxParallelism.\n\twhile (true) {\n\t\tconst ready: Step[] = [];\n\t\tfor (const step of steps) {\n\t\t\tif (completed.has(step.id)) continue;\n\t\t\tconst deps = step.waitFor ?? [];\n\t\t\tif (deps.every((d) => completed.has(d))) ready.push(step);\n\t\t}\n\t\tif (ready.length === 0) break;\n\n\t\tconst cap =\n\t\t\tctx.maxParallelism > 0\n\t\t\t\t? Math.min(ready.length, ctx.maxParallelism)\n\t\t\t\t: ready.length;\n\t\tconst batch = ready.slice(0, cap);\n\n\t\tawait Promise.all(batch.map((s) => executeStep(s, ctx, deps, completed)));\n\t}\n\n\treturn ctx.state;\n}\n\nfunction indexById(steps: Step[], out: Map<string, Step>): void {\n\tfor (const s of steps) {\n\t\tout.set(s.id, s);\n\t\tif (s.type === \"parallel\" || s.type === \"sequence\") {\n\t\t\tindexById(s.steps, out);\n\t\t}\n\t}\n}\n\nasync function executeStep(\n\tstep: Step,\n\tctx: RunContext,\n\tdeps: RunnerDeps,\n\tcompleted: Set<string>,\n): Promise<void> {\n\t// `when` predicate — skip if false.\n\tif (\n\t\tstep.when !== undefined &&\n\t\t!evalPredicate(step.when as Predicate, ctx.state)\n\t) {\n\t\tctx.state[step.id] = null;\n\t\tcompleted.add(step.id);\n\t\treturn;\n\t}\n\n\tconst begin = await deps.ops.beginStep({\n\t\trunId: ctx.runId,\n\t\tstepId: step.id,\n\t\tparentStepId: \"\",\n\t\tkind: step.type,\n\t\tinputSnapshot: snapshotInput(step, ctx.state),\n\t\tleaseEpoch: ctx.leaseEpoch,\n\t});\n\n\tif (begin.alreadyDone) {\n\t\tctx.state[step.id] = begin.cachedOutput ?? null;\n\t\tcompleted.add(step.id);\n\t\treturn;\n\t}\n\n\ttry {\n\t\t// One USER.SUBOP step span per executed unit. Group steps\n\t\t// (parallel/sequence) get role \"group\" so dispatchGroup's branch spans\n\t\t// nest under it; everything else is a plain \"step\". The span scope\n\t\t// established by wrapStep is what makes the step's nested rpc/event/\n\t\t// sub-workflow ops parent to the span instead of the run root.\n\t\tconst role: StepSpanInfo[\"role\"] =\n\t\t\tstep.type === \"parallel\" || step.type === \"sequence\" ? \"group\" : \"step\";\n\t\tconst runStep = () => dispatch(step, ctx, deps);\n\t\tconst output = deps.wrapStep\n\t\t\t? await deps.wrapStep(\n\t\t\t\t\t{\n\t\t\t\t\t\trunId: ctx.runId,\n\t\t\t\t\t\tstepId: step.id,\n\t\t\t\t\t\tstepName: step.id,\n\t\t\t\t\t\trole,\n\t\t\t\t\t},\n\t\t\t\t\trunStep,\n\t\t\t\t)\n\t\t\t: await runStep();\n\t\t// Park-typed steps surrender control; they have no synchronous output.\n\t\t// dispatch returns the sentinel `PARKED` and the runtime will resume\n\t\t// the run after the timer/event/signal fires.\n\t\tif (output === PARKED) {\n\t\t\tthrow new RunnerParkedError(step.id);\n\t\t}\n\t\tawait deps.ops.completeStep({\n\t\t\trunId: ctx.runId,\n\t\t\tstepId: step.id,\n\t\t\toutput,\n\t\t\tleaseEpoch: ctx.leaseEpoch,\n\t\t});\n\t\tctx.state[step.id] = output ?? null;\n\t\tcompleted.add(step.id);\n\t} catch (err) {\n\t\tif (err instanceof RunnerParkedError) throw err;\n\t\tconst { code, message } = unpackError(err);\n\t\tawait deps.ops.failStep({\n\t\t\trunId: ctx.runId,\n\t\t\tstepId: step.id,\n\t\t\terrorCode: code,\n\t\t\terrorMessage: message,\n\t\t\tleaseEpoch: ctx.leaseEpoch,\n\t\t\tretriable: false,\n\t\t});\n\t\tthrow err;\n\t}\n}\n\nconst PARKED = Symbol(\"workflow.parked\");\n\nexport class RunnerParkedError extends Error {\n\tconstructor(public readonly stepId: string) {\n\t\tsuper(`workflow/runner: parked at step \"${stepId}\" — runtime will resume`);\n\t\tthis.name = \"RunnerParkedError\";\n\t}\n}\n\nfunction snapshotInput(step: Step, state: State): unknown {\n\tswitch (step.type) {\n\t\tcase \"call\":\n\t\tcase \"publish\":\n\t\tcase \"workflow\":\n\t\t\treturn evalLiteralOrPath(step.input as JsonExpression, state);\n\t\tcase \"sleep\":\n\t\t\treturn { durationSec: step.durationSec };\n\t\tcase \"wait_event\":\n\t\t\treturn { event: step.event, filter: step.filter ?? null };\n\t\tcase \"wait_signal\":\n\t\t\treturn { signal: step.signal };\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n\nasync function dispatch(\n\tstep: Step,\n\tctx: RunContext,\n\tdeps: RunnerDeps,\n): Promise<unknown> {\n\tswitch (step.type) {\n\t\tcase \"call\":\n\t\t\treturn dispatchCall(step, ctx, deps);\n\t\tcase \"publish\":\n\t\t\treturn dispatchPublish(step, ctx, deps);\n\t\tcase \"workflow\":\n\t\t\treturn dispatchSubWorkflow(step, ctx, deps);\n\t\tcase \"sleep\":\n\t\t\treturn dispatchSleep(step, ctx, deps);\n\t\tcase \"wait_event\":\n\t\t\treturn dispatchWaitEvent(step, ctx, deps);\n\t\tcase \"wait_signal\":\n\t\t\treturn dispatchWaitSignal(step, ctx, deps);\n\t\tcase \"parallel\":\n\t\tcase \"sequence\":\n\t\t\treturn dispatchGroup(step, ctx, deps);\n\t\tcase \"local\":\n\t\t\treturn dispatchLocal(step, ctx, deps);\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = step;\n\t\t\tthrow new Error(\n\t\t\t\t`workflow/runner: unknown step type ${JSON.stringify(_exhaustive)}`,\n\t\t\t);\n\t\t}\n\t}\n}\n\n// dispatchCall — single sb.rpc.call. No retry, no backoff, no\n// idempotency-lookup, no circuit-breaker, no timeout-loop here. Those live in\n// sb.rpc.call (ADR-W-018).\nasync function dispatchCall(\n\tstep: CallStep,\n\tctx: RunContext,\n\tdeps: RunnerDeps,\n): Promise<unknown> {\n\tconst service = evalLiteralOrPath(step.service as JsonExpression, ctx.state);\n\tconst method = evalLiteralOrPath(step.method as JsonExpression, ctx.state);\n\tconst input = evalLiteralOrPath(step.input, ctx.state);\n\tconst opts = step.opts ? evalOpts(step.opts, ctx.state) : undefined;\n\treturn deps.sb.rpc.call(asString(service), asString(method), input, opts);\n}\n\nasync function dispatchPublish(\n\tstep: PublishStep,\n\tctx: RunContext,\n\tdeps: RunnerDeps,\n): Promise<unknown> {\n\tconst event = evalLiteralOrPath(step.event as JsonExpression, ctx.state);\n\tconst payload = evalLiteralOrPath(step.input, ctx.state);\n\tconst opts = step.opts ? evalOpts(step.opts, ctx.state) : undefined;\n\treturn deps.sb.event.publish(asString(event), payload, opts);\n}\n\nasync function dispatchSubWorkflow(\n\tstep: WorkflowStep,\n\tctx: RunContext,\n\tdeps: RunnerDeps,\n): Promise<unknown> {\n\tconst name = evalLiteralOrPath(step.workflow as JsonExpression, ctx.state);\n\tconst input = evalLiteralOrPath(step.input, ctx.state);\n\tconst baseOpts = step.opts ? evalOpts(step.opts, ctx.state) : undefined;\n\t// Propagate parent run id so the runtime can enforce dynamic cycle\n\t// detection across the ancestor chain (ADR-W-019).\n\tconst opts = { ...(baseOpts ?? {}), parentRunId: ctx.runId };\n\tconst { runId } = await deps.sb.workflow.start(asString(name), input, opts);\n\treturn deps.sb.workflow.await(runId);\n}\n\nasync function dispatchSleep(\n\tstep: SleepStep,\n\tctx: RunContext,\n\tdeps: RunnerDeps,\n): Promise<unknown> {\n\tawait deps.ops.park({\n\t\trunId: ctx.runId,\n\t\tstepId: step.id,\n\t\tleaseEpoch: ctx.leaseEpoch,\n\t\tsleep: { durationSec: step.durationSec },\n\t});\n\treturn PARKED;\n}\n\nasync function dispatchWaitEvent(\n\tstep: WaitEventStep,\n\tctx: RunContext,\n\tdeps: RunnerDeps,\n): Promise<unknown> {\n\tconst filter = step.filter\n\t\t? JSON.stringify(\n\t\t\t\tObject.fromEntries(\n\t\t\t\t\tObject.entries(step.filter).map(([k, v]) => [\n\t\t\t\t\t\tk,\n\t\t\t\t\t\tevalLiteralOrPath(v, ctx.state),\n\t\t\t\t\t]),\n\t\t\t\t),\n\t\t\t)\n\t\t: \"\";\n\tawait deps.ops.park({\n\t\trunId: ctx.runId,\n\t\tstepId: step.id,\n\t\tleaseEpoch: ctx.leaseEpoch,\n\t\teventWait: {\n\t\t\tevent: step.event,\n\t\t\tfilterJson: filter,\n\t\t\ttimeoutSec: step.timeoutSec ?? 0,\n\t\t},\n\t});\n\treturn PARKED;\n}\n\nasync function dispatchWaitSignal(\n\tstep: WaitSignalStep,\n\tctx: RunContext,\n\tdeps: RunnerDeps,\n): Promise<unknown> {\n\tawait deps.ops.park({\n\t\trunId: ctx.runId,\n\t\tstepId: step.id,\n\t\tleaseEpoch: ctx.leaseEpoch,\n\t\tsignalWait: { signal: step.signal, timeoutSec: step.timeoutSec ?? 0 },\n\t});\n\treturn PARKED;\n}\n\nasync function dispatchGroup(\n\tstep: ParallelStep | SequenceStep,\n\tctx: RunContext,\n\tdeps: RunnerDeps,\n): Promise<unknown> {\n\t// Iterations: each one is a (template-steps[], extra state bindings) pair.\n\tconst iterations: { steps: Step[]; bindings: State; suffix: string }[] = [];\n\tif (step.forEach) {\n\t\tconst items = evalLiteralOrPath(step.forEach.from, ctx.state);\n\t\tif (!Array.isArray(items)) {\n\t\t\tthrow new Error(\n\t\t\t\t`workflow/runner: forEach.from must resolve to array (got ${typeof items})`,\n\t\t\t);\n\t\t}\n\t\titems.forEach((item, idx) => {\n\t\t\titerations.push({\n\t\t\t\tsteps: step.steps.map((s) => rewriteStepIds(s, `${idx}`)),\n\t\t\t\tbindings: { [step.forEach!.as]: item },\n\t\t\t\tsuffix: `${idx}`,\n\t\t\t});\n\t\t});\n\t} else {\n\t\titerations.push({ steps: step.steps, bindings: {}, suffix: \"\" });\n\t}\n\n\tconst groupOutput: Record<string, unknown> = {};\n\tconst runIteration = async (\n\t\tit: (typeof iterations)[number],\n\t): Promise<void> => {\n\t\tconst subState: State = { ...ctx.state, ...it.bindings };\n\t\tconst subCtx: RunContext = { ...ctx, state: subState };\n\t\tconst runBranchBody = async (): Promise<void> => {\n\t\t\tif (step.type === \"parallel\") {\n\t\t\t\tawait Promise.all(\n\t\t\t\t\tit.steps.map((s) =>\n\t\t\t\t\t\texecuteStep(s, subCtx, deps, new Set(Object.keys(subState))),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tconst completed = new Set<string>(Object.keys(subState));\n\t\t\t\tfor (const s of it.steps) {\n\t\t\t\t\tawait executeStep(s, subCtx, deps, completed);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\t// One branch span per iteration, nested under the group span (R1: each\n\t\t// branch enters its own span scope inside its own async scope, so\n\t\t// parallel siblings never leak each other's parentOpId via shared ALS).\n\t\t// The non-forEach single iteration (suffix \"\") needs no extra branch\n\t\t// level — its steps already nest directly under the group span.\n\t\tif (it.suffix !== \"\" && deps.wrapStep) {\n\t\t\tawait deps.wrapStep(\n\t\t\t\t{\n\t\t\t\t\trunId: ctx.runId,\n\t\t\t\t\tstepId: `${step.id}:${it.suffix}`,\n\t\t\t\t\tstepName: `${step.id}[${it.suffix}]`,\n\t\t\t\t\trole: \"branch\",\n\t\t\t\t},\n\t\t\t\trunBranchBody,\n\t\t\t);\n\t\t} else {\n\t\t\tawait runBranchBody();\n\t\t}\n\t\tfor (const s of it.steps) {\n\t\t\tgroupOutput[s.id] = subState[s.id] ?? null;\n\t\t}\n\t};\n\n\tif (step.type === \"parallel\") {\n\t\tawait Promise.all(iterations.map(runIteration));\n\t} else {\n\t\tfor (const it of iterations) await runIteration(it);\n\t}\n\treturn groupOutput;\n}\n\nfunction rewriteStepIds(step: Step, suffix: string): Step {\n\tconst copy: Step = { ...step, id: `${step.id}:${suffix}` };\n\tif (copy.type === \"parallel\" || copy.type === \"sequence\") {\n\t\tcopy.steps = copy.steps.map((c) => rewriteStepIds(c, suffix));\n\t}\n\treturn copy;\n}\n\nasync function dispatchLocal(\n\tstep: LocalStep,\n\tctx: RunContext,\n\t_deps: RunnerDeps,\n): Promise<unknown> {\n\treturn step.fn(ctx.state);\n}\n\nfunction evalOpts(\n\topts: Record<string, JsonExpression>,\n\tstate: State,\n): Record<string, unknown> {\n\tconst out: Record<string, unknown> = {};\n\tfor (const [k, v] of Object.entries(opts)) {\n\t\tout[k] = evalLiteralOrPath(v, state);\n\t}\n\treturn out;\n}\n\nfunction asString(v: unknown): string {\n\tif (typeof v !== \"string\") {\n\t\tthrow new Error(\n\t\t\t`workflow/runner: expected string from JsonExpression, got ${typeof v}`,\n\t\t);\n\t}\n\treturn v;\n}\n\nfunction unpackError(err: unknown): { code: string; message: string } {\n\tif (err instanceof Error) {\n\t\tconst raw = (err as unknown as { code?: string | number }).code;\n\t\tconst code = raw !== undefined ? String(raw) : \"UNKNOWN\";\n\t\treturn { code, message: err.message };\n\t}\n\treturn { code: \"UNKNOWN\", message: String(err) };\n}\n\n// runCompensation — reverse-order traversal of completed call/publish steps\n// that declare `compensate`. Per ADR-W-007: shape inputs against final state\n// and replay through the corresponding owner-module operation.\nasync function runCompensation(\n\tsteps: Step[],\n\tctx: RunContext,\n\tdeps: RunnerDeps,\n): Promise<void> {\n\tconst flat: Step[] = [];\n\tflatten(steps, flat);\n\tconst reversed = [...flat].reverse();\n\tfor (const step of reversed) {\n\t\tif (!(step.type === \"call\" || step.type === \"publish\")) continue;\n\t\tconst comp = (step as { compensate?: CompensateSpec }).compensate;\n\t\tif (!comp) continue;\n\t\tif (ctx.state[step.id] === undefined || ctx.state[step.id] === null) {\n\t\t\tcontinue; // not completed → nothing to compensate\n\t\t}\n\t\tconst input = evalLiteralOrPath(comp.input, ctx.state);\n\t\tconst compStepId = `${step.id}.compensate`;\n\t\tawait deps.ops.beginStep({\n\t\t\trunId: ctx.runId,\n\t\t\tstepId: compStepId,\n\t\t\tparentStepId: step.id,\n\t\t\tkind: comp.type ?? (step.type === \"call\" ? \"call\" : \"publish\"),\n\t\t\tinputSnapshot: input,\n\t\t\tleaseEpoch: ctx.leaseEpoch,\n\t\t});\n\t\tconst kind = comp.type ?? step.type;\n\t\t// Forward CompensateSpec fields as opts to the owner-module op. The\n\t\t// runner itself does NOT implement any policy loop — it only transports\n\t\t// declarative options down to sb.rpc.call / sb.event.publish, which\n\t\t// own their semantics (ADR-W-018).\n\t\tconst opts = buildCompensateOpts(comp);\n\n\t\tconst executeCompensateOp = async (): Promise<unknown> => {\n\t\t\tif (kind === \"call\") {\n\t\t\t\treturn deps.sb.rpc.call(\n\t\t\t\t\tcomp.service ?? ((step as CallStep).service as string),\n\t\t\t\t\tcomp.method ?? ((step as CallStep).method as string),\n\t\t\t\t\tinput,\n\t\t\t\t\topts,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn deps.sb.event.publish(\n\t\t\t\tcomp.event ?? ((step as PublishStep).event as string),\n\t\t\t\tinput,\n\t\t\t\topts,\n\t\t\t);\n\t\t};\n\n\t\tconst output = deps.wrapStep\n\t\t\t? await deps.wrapStep(\n\t\t\t\t\t{\n\t\t\t\t\t\trunId: ctx.runId,\n\t\t\t\t\t\tstepId: compStepId,\n\t\t\t\t\t\tstepName: `compensate ${step.id}`,\n\t\t\t\t\t\trole: \"compensation\",\n\t\t\t\t\t\tisCompensation: true,\n\t\t\t\t\t\tcompensatesForStepId: step.id,\n\t\t\t\t\t},\n\t\t\t\t\texecuteCompensateOp,\n\t\t\t\t)\n\t\t\t: await executeCompensateOp();\n\n\t\tawait deps.ops.completeStep({\n\t\t\trunId: ctx.runId,\n\t\t\tstepId: compStepId,\n\t\t\toutput,\n\t\t\tleaseEpoch: ctx.leaseEpoch,\n\t\t});\n\t}\n}\n\nfunction flatten(steps: Step[], out: Step[]): void {\n\tfor (const s of steps) {\n\t\tout.push(s);\n\t\tif (s.type === \"parallel\" || s.type === \"sequence\") {\n\t\t\tflatten(s.steps, out);\n\t\t}\n\t}\n}\n","// Owner-side workflow subscriber: long-poll `Workflows.Subscribe`, hand each\n// RunAssignment to the thin runner, manage lease heartbeat.\n//\n// Mirrors `events/subscriber.ts` ladder semantics. Reconnect is fixed.\n//\n// Telemetry (T-022): the runtime owns the WORKFLOW.RUN root op. The SDK wraps\n// dispatch in runWithTrace(parent = run root) to establish the run-root trace\n// scope; the runner then opens one USER.SUBOP step span per executed unit\n// (step / fanout group / branch / compensation) inside that scope, so nested\n// rpc/event/sub-workflow ops nest under their step span. Cross-RPC/EVENT\n// propagation rides X-SB-Trace through `a.xSbTrace`.\n//\n// @internal — см. ./README.md\n\nimport type { ClientReadableStream, ServiceError } from \"@grpc/grpc-js\";\nimport type { ServiceBridge } from \"../connection/service-bridge\";\nimport type { Logger } from \"../events/publisher\";\nimport type {\n\tRunAssignment,\n\tWorkflowsClient,\n} from \"../pb/servicebridge/v1/workflows\";\nimport { runWithTrace } from \"../telemetry/context\";\nimport { parseXSbTrace } from \"../telemetry/wire-trace\";\nimport { type RunnerDeps, RunnerParkedError, run } from \"./runner\";\nimport type { Step } from \"./types\";\n\nconst RECONNECT_LADDER_MS = [1000, 5000, 15000, 30000, 60000] as const;\nconst HEARTBEAT_INTERVAL_MS = 10_000;\n\nfunction nextDelay(attempt: number): number {\n\tconst idx = Math.min(Math.max(attempt, 0), RECONNECT_LADDER_MS.length - 1);\n\treturn RECONNECT_LADDER_MS[idx]!;\n}\n\ninterface SubscriberDeps {\n\trpc: WorkflowsClient;\n\tserviceId: string;\n\tinstanceId: string;\n\tdeps: RunnerDeps;\n\tlogger: Logger;\n\t// lookupLocalGraph resolves a workflow name to the locally-registered\n\t// `Step[]` (with `local.fn` retained — closures cannot survive\n\t// JSON-roundtrip via the wire `frozenPlan`). Returns null when the SDK\n\t// has no handler for that name.\n\tlookupLocalGraph: (workflowName: string) => Step[] | null;\n\tsb?: ServiceBridge;\n}\n\n// FrozenPlan — on-wire JSON shape produced by `WorkflowDomain.handle` and\n// echoed back in RunAssignment.frozenPlan. ADR-W-002.\ninterface FrozenPlan {\n\tgraph: Step[];\n\tmaxParallelism?: number;\n}\n\nexport class WorkflowSubscriber {\n\tprivate stream: ClientReadableStream<RunAssignment> | null = null;\n\tprivate closed = false;\n\tprivate heartbeats = new Map<\n\t\tstring,\n\t\t{ timer: NodeJS.Timeout; leaseEpoch: number }\n\t>();\n\n\tconstructor(private readonly d: SubscriberDeps) {}\n\n\tstart(): void {\n\t\tvoid this.connectLoop(0);\n\t}\n\n\tclose(): void {\n\t\tthis.closed = true;\n\t\tthis.stream?.cancel();\n\t\tfor (const t of this.heartbeats.values()) clearInterval(t.timer);\n\t\tthis.heartbeats.clear();\n\t}\n\n\tprivate async connectLoop(attempt: number): Promise<void> {\n\t\twhile (!this.closed) {\n\t\t\ttry {\n\t\t\t\tawait this.runOnce();\n\t\t\t\tattempt = 0;\n\t\t\t} catch (err) {\n\t\t\t\tif (this.closed) return;\n\t\t\t\tthis.d.logger.warn(\n\t\t\t\t\t\"workflow subscriber: stream error\",\n\t\t\t\t\t(err as Error).message,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst delay = nextDelay(attempt++);\n\t\t\tawait new Promise((r) => setTimeout(r, delay));\n\t\t}\n\t}\n\n\tprivate runOnce(): Promise<void> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst stream = this.d.rpc.subscribe({\n\t\t\t\tserviceId: this.d.serviceId,\n\t\t\t\tinstanceId: this.d.instanceId,\n\t\t\t});\n\t\t\tthis.stream = stream;\n\n\t\t\tstream.on(\"data\", (a: RunAssignment) => {\n\t\t\t\tvoid this.dispatch(a).catch((err) => {\n\t\t\t\t\tthis.d.logger.error(\n\t\t\t\t\t\t`workflow run ${a.runId} dispatch failed: ${(err as Error).message}`,\n\t\t\t\t\t);\n\t\t\t\t});\n\t\t\t});\n\t\t\tstream.on(\"error\", (err: ServiceError) => reject(err));\n\t\t\tstream.on(\"end\", () => resolve());\n\t\t});\n\t}\n\n\tprivate async dispatch(a: RunAssignment): Promise<void> {\n\t\tif (this.closed) return;\n\t\tlet plan: FrozenPlan;\n\t\ttry {\n\t\t\tplan = JSON.parse(Buffer.from(a.frozenPlan).toString(\"utf8\"));\n\t\t} catch (err) {\n\t\t\tthis.d.logger.error(\n\t\t\t\t`workflow run ${a.runId}: bad frozenPlan: ${(err as Error).message}`,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\t// Replace the wire graph with the locally-registered one so that\n\t\t// `local.fn` closures (stripped by JSON.stringify on the registration\n\t\t// path) are restored. ADR-W-002: the wire frozenPlan is for runtime\n\t\t// canonicalization + fingerprint; the SDK runs against its own copy.\n\t\tconst localGraph = this.d.lookupLocalGraph(a.workflowName);\n\t\tif (localGraph) {\n\t\t\tplan.graph = localGraph;\n\t\t}\n\t\tconst inputJson =\n\t\t\ta.input.length > 0 ? Buffer.from(a.input).toString(\"utf8\") : \"null\";\n\t\tconst stateJson =\n\t\t\ta.state.length > 0 ? Buffer.from(a.state).toString(\"utf8\") : \"{}\";\n\t\tconst state: Record<string, unknown> = JSON.parse(stateJson);\n\t\tstate.input = JSON.parse(inputJson);\n\n\t\tthis.startHeartbeat(a.runId, a.leaseEpoch);\n\n\t\t// T-017/T-022: trace context arrives in `a.xSbTrace` formatted as\n\t\t// \"<traceId>-<rootOpId>\". Wrap plan execution in runWithTrace to seed the\n\t\t// run-root trace scope; the runner's per-step USER.SUBOP spans nest under\n\t\t// it so each step's child rpc/event/sub-workflow ops emit X-SB-Trace\n\t\t// pointing at their step span, not the run root. Without this seed the\n\t\t// child ops land in a fresh trace and the tree fragments.\n\t\tconst parsed = parseXSbTrace(a.xSbTrace);\n\t\tconst runnerDeps: typeof this.d.deps = this.d.deps;\n\t\tconst exec = async () => {\n\t\t\ttry {\n\t\t\t\tconst finalState = await run(\n\t\t\t\t\tplan.graph,\n\t\t\t\t\t{\n\t\t\t\t\t\trunId: a.runId,\n\t\t\t\t\t\tleaseEpoch: a.leaseEpoch,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\tcompensating: a.compensating,\n\t\t\t\t\t\tmaxParallelism: plan.maxParallelism ?? 0,\n\t\t\t\t\t},\n\t\t\t\t\trunnerDeps,\n\t\t\t\t);\n\t\t\t\t// All steps completed successfully — mark the run terminal.\n\t\t\t\t// terminalStatus is derived from the assignment's compensating flag and cancel reason:\n\t\t\t\t// - forward run completing → 'success'\n\t\t\t\t// - compensation completing after step_failure → 'failed_compensated'\n\t\t\t\t// - compensation completing after user_cancel → 'cancelled'\n\t\t\t\tlet terminalStatus = \"success\";\n\t\t\t\tif (a.compensating) {\n\t\t\t\t\tterminalStatus =\n\t\t\t\t\t\ta.cancelReason === \"step_failure\"\n\t\t\t\t\t\t\t? \"failed_compensated\"\n\t\t\t\t\t\t\t: \"cancelled\";\n\t\t\t\t}\n\t\t\t\tawait this.d.deps.ops.completeRun({\n\t\t\t\t\trunId: a.runId,\n\t\t\t\t\tfinalState,\n\t\t\t\t\tleaseEpoch: a.leaseEpoch,\n\t\t\t\t\tterminalStatus,\n\t\t\t\t});\n\t\t\t} catch (err) {\n\t\t\t\tif (!(err instanceof RunnerParkedError)) {\n\t\t\t\t\tthis.d.logger.warn(\n\t\t\t\t\t\t`workflow run ${a.runId}: ${(err as Error).message}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tthis.stopHeartbeat(a.runId);\n\t\t\t\t// Telemetry: WORKFLOW.RUN END is emitted by the runtime when\n\t\t\t\t// CompleteRun/Cancel commits. SDK no longer owns root-op lifecycle.\n\t\t\t}\n\t\t};\n\n\t\tif (parsed) {\n\t\t\tawait runWithTrace(\n\t\t\t\t{ traceId: parsed.traceId, parentOpId: parsed.parentOpId },\n\t\t\t\texec,\n\t\t\t);\n\t\t} else {\n\t\t\tawait exec();\n\t\t}\n\t}\n\n\tprivate startHeartbeat(runId: string, leaseEpoch: number): void {\n\t\tif (this.closed) return;\n\t\tconst timer = setInterval(() => {\n\t\t\tif (this.closed) {\n\t\t\t\tclearInterval(timer);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tthis.d.rpc.heartbeat(\n\t\t\t\t\t{ runId, instanceId: this.d.instanceId, leaseEpoch },\n\t\t\t\t\t(err) => {\n\t\t\t\t\t\tif (err)\n\t\t\t\t\t\t\tthis.d.logger.warn(\n\t\t\t\t\t\t\t\t`workflow heartbeat ${runId} failed: ${err.message}`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\tclearInterval(timer);\n\t\t\t\tthis.heartbeats.delete(runId);\n\t\t\t}\n\t\t}, HEARTBEAT_INTERVAL_MS);\n\t\tthis.heartbeats.set(runId, { timer, leaseEpoch });\n\t}\n\n\tprivate stopHeartbeat(runId: string): void {\n\t\tconst t = this.heartbeats.get(runId);\n\t\tif (t) {\n\t\t\tclearInterval(t.timer);\n\t\t\tthis.heartbeats.delete(runId);\n\t\t}\n\t}\n}\n","// Code generated by protoc-gen-ts_proto. DO NOT EDIT.\n// versions:\n// protoc-gen-ts_proto v2.11.8\n// protoc unknown\n// source: servicebridge/v1/bootstrap.proto\n\n/* eslint-disable */\nimport { BinaryReader, BinaryWriter } from \"@bufbuild/protobuf/wire\";\nimport {\n type CallOptions,\n type ChannelCredentials,\n Client,\n type ClientOptions,\n type ClientUnaryCall,\n type handleUnaryCall,\n makeGenericClientConstructor,\n type Metadata,\n type ServiceError,\n type UntypedServiceImplementation,\n} from \"@grpc/grpc-js\";\n\n/**\n * BootstrapKeyPayload is the wire-format struct for the bootstrap key.\n * Serialised with proto.Marshal and base64url-encoded with an \"sb.\" prefix.\n */\nexport interface BootstrapKeyPayload {\n keyId: Buffer;\n secret: Buffer;\n caCertDer: Buffer;\n}\n\nexport interface ProvisionRequest {\n /** 8 bytes */\n keyId: Buffer;\n /** 32 bytes */\n secret: Buffer;\n /** PKCS#10, client holds privkey in memory */\n csrDer: Buffer;\n}\n\nexport interface ProvisionResponse {\n certDer: Buffer;\n caChainDer: Buffer;\n /** stable UUID, in SAN cert */\n serviceId: string;\n /** human label, mutable, NOT in cert */\n serviceName: string;\n /** UUID of this instance, in SAN cert */\n instanceId: string;\n /** cert expiry for scheduling refresh */\n notAfterUnix: number;\n}\n\nfunction createBaseBootstrapKeyPayload(): BootstrapKeyPayload {\n return { keyId: Buffer.alloc(0), secret: Buffer.alloc(0), caCertDer: Buffer.alloc(0) };\n}\n\nexport const BootstrapKeyPayload: MessageFns<BootstrapKeyPayload> = {\n encode(message: BootstrapKeyPayload, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.keyId.length !== 0) {\n writer.uint32(10).bytes(message.keyId);\n }\n if (message.secret.length !== 0) {\n writer.uint32(18).bytes(message.secret);\n }\n if (message.caCertDer.length !== 0) {\n writer.uint32(26).bytes(message.caCertDer);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): BootstrapKeyPayload {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseBootstrapKeyPayload();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.keyId = Buffer.from(reader.bytes());\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.secret = Buffer.from(reader.bytes());\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.caCertDer = Buffer.from(reader.bytes());\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<BootstrapKeyPayload>, I>>(base?: I): BootstrapKeyPayload {\n return BootstrapKeyPayload.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<BootstrapKeyPayload>, I>>(object: I): BootstrapKeyPayload {\n const message = createBaseBootstrapKeyPayload();\n message.keyId = object.keyId ?? Buffer.alloc(0);\n message.secret = object.secret ?? Buffer.alloc(0);\n message.caCertDer = object.caCertDer ?? Buffer.alloc(0);\n return message;\n },\n};\n\nfunction createBaseProvisionRequest(): ProvisionRequest {\n return { keyId: Buffer.alloc(0), secret: Buffer.alloc(0), csrDer: Buffer.alloc(0) };\n}\n\nexport const ProvisionRequest: MessageFns<ProvisionRequest> = {\n encode(message: ProvisionRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.keyId.length !== 0) {\n writer.uint32(10).bytes(message.keyId);\n }\n if (message.secret.length !== 0) {\n writer.uint32(18).bytes(message.secret);\n }\n if (message.csrDer.length !== 0) {\n writer.uint32(26).bytes(message.csrDer);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): ProvisionRequest {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseProvisionRequest();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.keyId = Buffer.from(reader.bytes());\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.secret = Buffer.from(reader.bytes());\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.csrDer = Buffer.from(reader.bytes());\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<ProvisionRequest>, I>>(base?: I): ProvisionRequest {\n return ProvisionRequest.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<ProvisionRequest>, I>>(object: I): ProvisionRequest {\n const message = createBaseProvisionRequest();\n message.keyId = object.keyId ?? Buffer.alloc(0);\n message.secret = object.secret ?? Buffer.alloc(0);\n message.csrDer = object.csrDer ?? Buffer.alloc(0);\n return message;\n },\n};\n\nfunction createBaseProvisionResponse(): ProvisionResponse {\n return {\n certDer: Buffer.alloc(0),\n caChainDer: Buffer.alloc(0),\n serviceId: \"\",\n serviceName: \"\",\n instanceId: \"\",\n notAfterUnix: 0,\n };\n}\n\nexport const ProvisionResponse: MessageFns<ProvisionResponse> = {\n encode(message: ProvisionResponse, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.certDer.length !== 0) {\n writer.uint32(10).bytes(message.certDer);\n }\n if (message.caChainDer.length !== 0) {\n writer.uint32(18).bytes(message.caChainDer);\n }\n if (message.serviceId !== \"\") {\n writer.uint32(26).string(message.serviceId);\n }\n if (message.serviceName !== \"\") {\n writer.uint32(34).string(message.serviceName);\n }\n if (message.instanceId !== \"\") {\n writer.uint32(42).string(message.instanceId);\n }\n if (message.notAfterUnix !== 0) {\n writer.uint32(48).int64(message.notAfterUnix);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): ProvisionResponse {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseProvisionResponse();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.certDer = Buffer.from(reader.bytes());\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.caChainDer = Buffer.from(reader.bytes());\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.serviceId = reader.string();\n continue;\n }\n case 4: {\n if (tag !== 34) {\n break;\n }\n\n message.serviceName = reader.string();\n continue;\n }\n case 5: {\n if (tag !== 42) {\n break;\n }\n\n message.instanceId = reader.string();\n continue;\n }\n case 6: {\n if (tag !== 48) {\n break;\n }\n\n message.notAfterUnix = longToNumber(reader.int64());\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<ProvisionResponse>, I>>(base?: I): ProvisionResponse {\n return ProvisionResponse.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<ProvisionResponse>, I>>(object: I): ProvisionResponse {\n const message = createBaseProvisionResponse();\n message.certDer = object.certDer ?? Buffer.alloc(0);\n message.caChainDer = object.caChainDer ?? Buffer.alloc(0);\n message.serviceId = object.serviceId ?? \"\";\n message.serviceName = object.serviceName ?? \"\";\n message.instanceId = object.instanceId ?? \"\";\n message.notAfterUnix = object.notAfterUnix ?? 0;\n return message;\n },\n};\n\nexport type BootstrapService = typeof BootstrapService;\nexport const BootstrapService = {\n provision: {\n path: \"/servicebridge.v1.Bootstrap/Provision\" as const,\n requestStream: false as const,\n responseStream: false as const,\n requestSerialize: (value: ProvisionRequest): Buffer => Buffer.from(ProvisionRequest.encode(value).finish()),\n requestDeserialize: (value: Buffer): ProvisionRequest => ProvisionRequest.decode(value),\n responseSerialize: (value: ProvisionResponse): Buffer => Buffer.from(ProvisionResponse.encode(value).finish()),\n responseDeserialize: (value: Buffer): ProvisionResponse => ProvisionResponse.decode(value),\n },\n} as const;\n\nexport interface BootstrapServer extends UntypedServiceImplementation {\n provision: handleUnaryCall<ProvisionRequest, ProvisionResponse>;\n}\n\nexport interface BootstrapClient extends Client {\n provision(\n request: ProvisionRequest,\n callback: (error: ServiceError | null, response: ProvisionResponse) => void,\n ): ClientUnaryCall;\n provision(\n request: ProvisionRequest,\n metadata: Metadata,\n callback: (error: ServiceError | null, response: ProvisionResponse) => void,\n ): ClientUnaryCall;\n provision(\n request: ProvisionRequest,\n metadata: Metadata,\n options: Partial<CallOptions>,\n callback: (error: ServiceError | null, response: ProvisionResponse) => void,\n ): ClientUnaryCall;\n}\n\nexport const BootstrapClient = makeGenericClientConstructor(\n BootstrapService,\n \"servicebridge.v1.Bootstrap\",\n) as unknown as {\n new (address: string, credentials: ChannelCredentials, options?: Partial<ClientOptions>): BootstrapClient;\n service: typeof BootstrapService;\n serviceName: string;\n};\n\ntype Builtin = Date | Function | Uint8Array | string | number | boolean | undefined;\n\ntype DeepPartial<T> = T extends Builtin ? T\n : T extends globalThis.Array<infer U> ? globalThis.Array<DeepPartial<U>>\n : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>>\n : T extends {} ? { [K in keyof T]?: DeepPartial<T[K]> }\n : Partial<T>;\n\ntype KeysOfUnion<T> = T extends T ? keyof T : never;\ntype Exact<P, I extends P> = P extends Builtin ? P\n : P & { [K in keyof P]: Exact<P[K], I[K]> } & { [K in Exclude<keyof I, KeysOfUnion<P>>]: never };\n\nfunction longToNumber(int64: { toString(): string }): number {\n const num = globalThis.Number(int64.toString());\n if (num > globalThis.Number.MAX_SAFE_INTEGER) {\n throw new globalThis.Error(\"Value is larger than Number.MAX_SAFE_INTEGER\");\n }\n if (num < globalThis.Number.MIN_SAFE_INTEGER) {\n throw new globalThis.Error(\"Value is smaller than Number.MIN_SAFE_INTEGER\");\n }\n return num;\n}\n\ninterface MessageFns<T> {\n encode(message: T, writer?: BinaryWriter): BinaryWriter;\n decode(input: BinaryReader | Uint8Array, length?: number): T;\n create<I extends Exact<DeepPartial<T>, I>>(base?: I): T;\n fromPartial<I extends Exact<DeepPartial<T>, I>>(object: I): T;\n}\n","// Bootstrap key format:\n// sb.<base64url(proto.Marshal(BootstrapKeyPayload))>\n//\n// The CA cert is embedded in the key so the SDK can construct mTLS channel\n// credentials without a separate trust-on-first-use step (which is unreliable\n// on runtimes that don't expose the full cert chain through node:tls, e.g.\n// Bun's getPeerCertificate).\n\nimport { BootstrapKeyPayload } from \"../pb/servicebridge/v1/bootstrap\";\n\nconst PREFIX = \"sb.\";\n\nexport interface BootstrapKey {\n\tkeyID: Buffer;\n\tsecret: Buffer;\n\tcaCertDer: Buffer;\n}\n\n/**\n * Parses a ServiceBridge bootstrap key string into its components.\n * Throws on malformed input (wrong prefix, truncated, invalid base64url,\n * or proto message with empty required fields).\n */\nexport function parseBootstrapKey(raw: string): BootstrapKey {\n\tif (!raw.startsWith(PREFIX)) {\n\t\tthrow new Error(`bootstrap key: missing \"sb.\" prefix`);\n\t}\n\tconst bytes = Buffer.from(raw.slice(PREFIX.length), \"base64url\");\n\tconst msg = BootstrapKeyPayload.decode(bytes);\n\tif (!msg.keyId || msg.keyId.length === 0) {\n\t\tthrow new Error(\"bootstrap key: key_id is empty\");\n\t}\n\tif (!msg.secret || msg.secret.length === 0) {\n\t\tthrow new Error(\"bootstrap key: secret is empty\");\n\t}\n\tif (!msg.caCertDer || msg.caCertDer.length === 0) {\n\t\tthrow new Error(\"bootstrap key: ca_cert_der is empty\");\n\t}\n\treturn {\n\t\tkeyID: Buffer.from(msg.keyId),\n\t\tsecret: Buffer.from(msg.secret),\n\t\tcaCertDer: Buffer.from(msg.caCertDer),\n\t};\n}\n","import \"reflect-metadata\";\nimport * as grpc from \"@grpc/grpc-js\";\nimport * as x509 from \"@peculiar/x509\";\nimport { BootstrapClient } from \"../pb/servicebridge/v1/bootstrap\";\nimport type { ControlClient } from \"../pb/servicebridge/v1/control\";\nimport type { BootstrapKey } from \"./key\";\nimport { derToPem } from \"./pem\";\nimport { ServiceBridgeError } from \"./service-bridge-error\";\n\n/** @internal см. ./README.md */\nexport interface Keypair {\n\tprivateKey: CryptoKey;\n\tpublicKey: CryptoKey;\n\tcsrDer: Uint8Array;\n}\n\nexport interface ProvisionResult {\n\tcertDer: Buffer;\n\tcaChainDer: Buffer;\n\tserviceId: string;\n\tserviceName: string;\n\tinstanceId: string;\n\tnotAfterUnix: bigint;\n\tprivateKey: CryptoKey;\n\tprivateKeyDer: Buffer; // PKCS#8 DER for sync mTLS credential construction\n}\n\n/** @internal см. ./README.md */\nexport function parseURL(url: string): { host: string; port: number } {\n\tconst idx = url.lastIndexOf(\":\");\n\tif (idx < 0) throw new Error(`invalid URL (host:port required): ${url}`);\n\tconst host = url.slice(0, idx);\n\tconst port = Number(url.slice(idx + 1));\n\tif (!Number.isFinite(port) || port <= 0 || port > 65535) {\n\t\tthrow new Error(`invalid port in URL: ${url}`);\n\t}\n\treturn { host, port };\n}\n\n/** @internal см. ./README.md */\nexport async function generateKeypairAndCSR(): Promise<Keypair> {\n\tconst keyPair = await crypto.subtle.generateKey(\n\t\t{ name: \"ECDSA\", namedCurve: \"P-256\" },\n\t\ttrue,\n\t\t[\"sign\", \"verify\"],\n\t);\n\n\tconst csr = await x509.Pkcs10CertificateRequestGenerator.create({\n\t\tname: \"CN=servicebridge-instance\",\n\t\tkeys: keyPair,\n\t\tsigningAlgorithm: { name: \"ECDSA\", hash: \"SHA-256\" },\n\t});\n\n\treturn {\n\t\tprivateKey: keyPair.privateKey,\n\t\tpublicKey: keyPair.publicKey,\n\t\tcsrDer: new Uint8Array(csr.rawData),\n\t};\n}\n\n/** @internal см. ./README.md */\nexport function buildPinnedCredentials(\n\tcaCertDer: Buffer,\n): grpc.ChannelCredentials {\n\tconst caPem = derToPem(caCertDer);\n\tconst verifyOptions: Parameters<typeof grpc.credentials.createSsl>[3] = {\n\t\tcheckServerIdentity: () => undefined, // hostname check disabled, chain is enough\n\t};\n\treturn grpc.credentials.createSsl(caPem, null, null, verifyOptions);\n}\n\n/** @internal см. ./README.md */\nexport function newBootstrapClient(\n\turl: string,\n\tcaCertDer: Buffer,\n): BootstrapClient {\n\tconst creds = buildPinnedCredentials(caCertDer);\n\treturn new BootstrapClient(url, creds);\n}\n\n/**\n * Runs the full Provision flow:\n * 1. Use the CA cert embedded in the bootstrap key as the trusted root.\n * 2. Generate keypair + CSR.\n * 3. Call Bootstrap.Provision over a gRPC channel rooted at that CA.\n */\nexport async function provision(\n\turl: string,\n\tkey: BootstrapKey,\n): Promise<ProvisionResult> {\n\tparseURL(url); // validate format early — throws on garbage\n\tconst { privateKey, csrDer } = await generateKeypairAndCSR();\n\tconst privateKeyDer = Buffer.from(\n\t\tawait crypto.subtle.exportKey(\"pkcs8\", privateKey),\n\t);\n\tconst client = newBootstrapClient(url, key.caCertDer);\n\n\treturn new Promise((resolve, reject) => {\n\t\tclient.provision(\n\t\t\t{\n\t\t\t\tkeyId: key.keyID,\n\t\t\t\tsecret: key.secret,\n\t\t\t\tcsrDer: Buffer.from(csrDer),\n\t\t\t},\n\t\t\t(err, response) => {\n\t\t\t\tif (err) {\n\t\t\t\t\treject(new ServiceBridgeError(\"provision\", err));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (!response) {\n\t\t\t\t\treject(\n\t\t\t\t\t\tnew Error(\"provision: empty response\", {\n\t\t\t\t\t\t\tcause: new Error(\"gRPC returned null response\"),\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tresolve({\n\t\t\t\t\tcertDer: Buffer.from(response.certDer),\n\t\t\t\t\tcaChainDer: Buffer.from(response.caChainDer),\n\t\t\t\t\tserviceId: response.serviceId,\n\t\t\t\t\tserviceName: response.serviceName,\n\t\t\t\t\tinstanceId: response.instanceId,\n\t\t\t\t\tnotAfterUnix: BigInt(response.notAfterUnix),\n\t\t\t\t\tprivateKey,\n\t\t\t\t\tprivateKeyDer,\n\t\t\t\t});\n\t\t\t},\n\t\t);\n\t});\n}\n\n/**\n * Reissues a leaf cert via Control.RefreshCert under the existing mTLS channel.\n * No argon2 — identity is proven by the live client cert. The runtime generates\n * a fresh instance_id (preserving overlap-rotation semantics); the CA cert\n * and parent service identity carry over from the previous provision.\n *\n * Caller must reuse the existing mTLS ControlClient — RefreshCert is in the\n * default-deny set and rejects unauthenticated channels.\n */\nexport async function refresh(\n\tclient: ControlClient,\n\tprevious: ProvisionResult,\n): Promise<ProvisionResult> {\n\tconst { privateKey, csrDer } = await generateKeypairAndCSR();\n\tconst privateKeyDer = Buffer.from(\n\t\tawait crypto.subtle.exportKey(\"pkcs8\", privateKey),\n\t);\n\n\treturn new Promise((resolve, reject) => {\n\t\tclient.refreshCert({ csrDer: Buffer.from(csrDer) }, (err, response) => {\n\t\t\tif (err) {\n\t\t\t\treject(new ServiceBridgeError(\"refresh\", err));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!response) {\n\t\t\t\treject(\n\t\t\t\t\tnew Error(\"refresh: empty response\", {\n\t\t\t\t\t\tcause: new Error(\"gRPC returned null response\"),\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tresolve({\n\t\t\t\tcertDer: Buffer.from(response.certDer),\n\t\t\t\tcaChainDer: Buffer.from(response.caChainDer),\n\t\t\t\tserviceId: previous.serviceId,\n\t\t\t\tserviceName: previous.serviceName,\n\t\t\t\tinstanceId: response.instanceId,\n\t\t\t\tnotAfterUnix: BigInt(response.notAfterUnix),\n\t\t\t\tprivateKey,\n\t\t\t\tprivateKeyDer,\n\t\t\t});\n\t\t});\n\t});\n}\n","import { status as GrpcStatus } from \"@grpc/grpc-js\";\n\nconst NON_RETRYABLE = new Set([\n\tGrpcStatus.UNAUTHENTICATED,\n\tGrpcStatus.PERMISSION_DENIED,\n\tGrpcStatus.NOT_FOUND,\n\tGrpcStatus.INVALID_ARGUMENT,\n]);\n\n// isRetryable returns true if the gRPC status code is transient (worth a retry).\n// Used by the connection lifecycle to decide between scheduling a reconnect\n// and emitting a terminal `disconnected` event.\n//\n// @internal — см. ./README.md\nexport function isRetryable(grpcCode: number): boolean {\n\treturn grpcCode === -1 || !NON_RETRYABLE.has(grpcCode);\n}\n\n/** @public см. ./README.md */\nexport class ServiceBridgeError extends Error {\n\treadonly code: number;\n\n\tconstructor(scope: string, cause: unknown) {\n\t\tconst grpcCode =\n\t\t\tcause != null &&\n\t\t\ttypeof cause === \"object\" &&\n\t\t\t\"code\" in cause &&\n\t\t\ttypeof (cause as { code: unknown }).code === \"number\"\n\t\t\t\t? (cause as { code: number }).code\n\t\t\t\t: -1;\n\n\t\tconst message = cause instanceof Error ? cause.message : String(cause);\n\t\tsuper(`${scope}: ${message}`, { cause });\n\n\t\tthis.name = \"ServiceBridgeError\";\n\t\tthis.code = grpcCode;\n\t}\n}\n","import type {\n\tControlClient,\n\tOpenRequest as OpenRequestType,\n\tServerControl,\n\tWelcome,\n} from \"../pb/servicebridge/v1/control\";\nimport { OpenRequest } from \"../pb/servicebridge/v1/control\";\nimport type {\n\tRegisterRequest,\n\tRegistryClient,\n} from \"../pb/servicebridge/v1/registry\";\nimport type { WatchStream } from \"../registry/watch\";\n\nexport type ServerStream = ReturnType<ControlClient[\"open\"]>;\n\nexport interface SessionCallbacks {\n\tonWelcome(welcome: Welcome): void;\n\tonDrain(reason: string): void;\n\tonError(err: Error): void;\n\tonEnd(): void;\n}\n\n/**\n * Wraps a single live SDK→runtime connection. Owns both server-streams used by\n * the connection lifecycle:\n * - `Control.Open` — server-streamed Welcome/Drain signals (identity by mTLS).\n * - `Registry.RegisterAndWatch` — push-based registry view; restartable via\n * `updateRegistration(req)` when local state (e.g. HTTP endpoint) changes.\n *\n * Heartbeats moved out of Control entirely (now part of the Telemetry stream),\n * so the SDK side of `Control.Open` is read-only here.\n */\nexport class Session {\n\tprivate readonly stream: ServerStream;\n\tprivate readonly callbacks: SessionCallbacks;\n\tprivate readonly watch: WatchStream;\n\tprivate readonly registryClient: RegistryClient;\n\tprivate closed = false;\n\tprivate expectedClose = false;\n\n\tconstructor(\n\t\tstream: ServerStream,\n\t\tcallbacks: SessionCallbacks,\n\t\twatch: WatchStream,\n\t\tregistryClient: RegistryClient,\n\t) {\n\t\tthis.stream = stream;\n\t\tthis.callbacks = callbacks;\n\t\tthis.watch = watch;\n\t\tthis.registryClient = registryClient;\n\n\t\tstream.on(\"data\", (msg: ServerControl) => this.handleMessage(msg));\n\t\tstream.on(\"end\", () => this.onEnd());\n\t\tstream.on(\"error\", (err: Error) => {\n\t\t\tif (this.expectedClose) return;\n\t\t\tcallbacks.onError(err);\n\t\t});\n\t}\n\n\t/**\n\t * Restarts the Registry.RegisterAndWatch stream with a fresh RegisterRequest.\n\t * Used when local registration state changes after `start()` (HTTP endpoint\n\t * publishHttp from integrations). Safe to call after close() — becomes no-op.\n\t */\n\tupdateRegistration(req: RegisterRequest): void {\n\t\tif (this.closed) return;\n\t\tthis.watch.restart(req, this.registryClient, (_err) => {});\n\t}\n\n\t/**\n\t * close() cancels the server stream and suppresses subsequent onEnd /\n\t * onError callbacks. The caller knows the close is expected and reconnect\n\t * logic must NOT fire.\n\t */\n\tclose(): void {\n\t\tif (this.closed) return;\n\t\tthis.closed = true;\n\t\tthis.expectedClose = true;\n\t\tconst cancellable = this.stream as unknown as { cancel?: () => void };\n\t\tif (typeof cancellable.cancel === \"function\") {\n\t\t\ttry {\n\t\t\t\tcancellable.cancel();\n\t\t\t} catch {\n\t\t\t\t// stream may already be done — fine.\n\t\t\t}\n\t\t}\n\t}\n\n\tisClosed(): boolean {\n\t\treturn this.closed;\n\t}\n\n\tprivate handleMessage(msg: ServerControl): void {\n\t\tif (msg.welcome) {\n\t\t\tthis.callbacks.onWelcome(msg.welcome);\n\t\t} else if (msg.drain) {\n\t\t\tthis.callbacks.onDrain(msg.drain.reason);\n\t\t}\n\t}\n\n\tprivate onEnd(): void {\n\t\tconst expected = this.expectedClose;\n\t\tthis.closed = true;\n\t\tif (expected) return;\n\t\tthis.callbacks.onEnd();\n\t}\n}\n\n// openControlStream is the canonical way callers construct the server-stream.\n// Kept separate so tests can stub it without binding to the proto-generated\n// ControlClient interface.\nexport function openControlStream(client: ControlClient): ServerStream {\n\tconst req: OpenRequestType = OpenRequest.create();\n\treturn client.open(req);\n}\n"],"mappings":";;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAS,cAAAA,mBAAkB;AAmBpB,SAAS,oBAAoB,MAA0B;AAC7D,QAAM,iBAAiB,aAAa,KAAK,MAAM,aAAa,CAAC;AAC7D,QAAM,kBAAkB,aAAa,KAAK,OAAO,aAAa,CAAC;AAC/D,SAAOA,YAAW,QAAQ,EACxB,OAAO,GAAG,cAAc,IAAI,eAAe,EAAE,EAC7C,OAAO,KAAK;AACf;AAIO,SAAS,sBAAsB,GAAuB;AAC5D,QAAM,YAAY,aAAa,EAAE,aAAa,CAAC;AAC/C,SAAOA,YAAW,QAAQ,EAAE,OAAO,SAAS,EAAE,OAAO,KAAK;AAC3D;AAUO,SAAS,aAAa,OAAwB;AACpD,MAAI,UAAU,QAAQ,OAAO,UAAU,UAAU;AAChD,WAAO,KAAK,UAAU,KAAK;AAAA,EAC5B;AACA,MAAI,MAAM,QAAQ,KAAK,GAAG;AACzB,WAAO,IAAI,MAAM,IAA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AAAA,QACtB;AAAA,QACA;AAAA,QACA,KAAK;AAAA,QACL;AAAA,MACD;AAAA,IACD,CAAC;AAED,QAAI;AACH,YAAM;AAEN,kBAAY,MAAM;AAClB,WAAK,aAAa;AAAA,QACjB,KAAK,UAAU,qBAAqB;AAAA,QACpC;AAAA,QACA,CAAC,SAAS;AAAA,QAAC;AAAA,MACZ;AAAA,IACD,SAAS,KAAK;AAGb,UAAI,KAAK,YAAY,YAAY;AAChC,aAAK,SAAS,MAAM;AACpB,aAAK,UAAU;AAAA,MAChB;AACA,WAAK;AAAA,QACJ;AAAA,QACA,aAAa,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA,MAC9D;AAAA,IACD;AAAA,EACD;AAAA,EAEQ,kBAAkB,SAAiB,QAAsB;AAChE,QAAI,KAAK,QAAS;AAClB,QACC,KAAK,KAAK,oBAAoB,KAC9B,UAAU,KAAK,KAAK,mBACnB;AACD,WAAK,KAAK,gBAAgB,EAAE,QAAQ,YAAY,CAAC;AACjD,WAAK,KAAK,KAAK;AACf;AAAA,IACD;AACA,SAAK,KAAK,gBAAgB;AAAA,MACzB;AAAA,MACA,SAAS,KAAK,KAAK;AAAA,MACnB;AAAA,IACD,CAAC;AACD,eAAW,MAAM;AAChB,WAAK,KAAK,QAAQ,OAAO;AAAA,IAC1B,GAAG,KAAK,KAAK,mBAAmB;AAAA,EACjC;AAAA,EAEQ,cAAoB;AAC3B,QAAI,KAAK,kBAAkB;AAC1B,mBAAa,KAAK,gBAAgB;AAClC,WAAK,mBAAmB;AAAA,IACzB;AAAA,EACD;AACD;","names":["createHash","protobuf","typeToSerializer","grpc","status","BinaryReader","BinaryWriter","makeGenericClientConstructor","BinaryWriter","BinaryReader","longToNumber","makeGenericClientConstructor","RECONNECT_LADDER_MS","nextDelay","BinaryReader","BinaryWriter","makeGenericClientConstructor","longToNumber","BinaryReader","BinaryWriter","makeGenericClientConstructor","longToNumber","BinaryReader","BinaryWriter","makeGenericClientConstructor","BinaryWriter","BinaryReader","longToNumber","makeGenericClientConstructor","BinaryReader","BinaryWriter","makeGenericClientConstructor","BinaryReader","BinaryWriter","BinaryWriter","BinaryReader","longToNumber","makeGenericClientConstructor","buildSchemaPair","computeContractHash","uuidv7","uuidv7","uuidv7","status","BinaryReader","BinaryWriter","makeGenericClientConstructor","Metadata","BinaryReader","BinaryWriter","makeGenericClientConstructor","X_SB_TRACE_HEADER","currentTraceHeader","buildTraceMetadata","Metadata","grpc","dispatch","protobuf","Database","createHash","canonicalize","status","visit","GRPC_PERMISSION_DENIED","canonicalize","indexById","deps","RECONNECT_LADDER_MS","HEARTBEAT_INTERVAL_MS","nextDelay","BinaryReader","BinaryWriter","makeGenericClientConstructor","longToNumber","grpc","x509","isRetryable","isRetryable"]}