@godspeedai/cognate-protocol-connect 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +10 -2
  3. package/package.json +34 -4
  4. package/src/index.ts +715 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,11 @@
1
- # Temporary Holding Version
1
+ # @godspeedai/cognate-protocol-connect
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Maps `RuntimeService` (runtime-api) to the generated Connect service `cognate.v1.RuntimeService` (`@godspeedai/cognate-proto`), independent of the HTTP server.
4
+
5
+ - `registerRuntimeService(router, service, { authenticate, maxJsonDepth })` — server routes. The caller comes from request headers via `authenticate`, never from message bodies (§32). `google.protobuf.Value` inputs are depth-checked.
6
+ - `createRemoteRuntimeService(transport, tokenFor)` — a `RuntimeService` over any Connect transport; ServiceError codes round-trip exactly.
7
+ - `errorCodes` — ServiceError ↔ Connect code table.
8
+
9
+ Proof: `test/service.test.ts` runs the same service conformance kit as the in-process runtime, over JSON and binary encodings (CG-WIR-003, §40.G).
10
+
11
+ Mode matrix (DEBT-004): unary and server streaming only; client/bidi streaming are not offered.
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "@godspeedai/cognate-protocol-connect",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Maps RuntimeService to the generated Connect service (server routes and a remote client). Transport-agnostic.",
5
+ "type": "module",
6
+ "license": "Apache-2.0",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/GodSpeedAI/Cognate.git",
10
+ "directory": "packages/protocol-connect"
11
+ },
12
+ "engines": {
13
+ "bun": ">=1.4.0"
14
+ },
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "files": [
19
+ "src"
20
+ ],
21
+ "exports": {
22
+ ".": "./src/index.ts"
23
+ },
24
+ "dependencies": {
25
+ "@bufbuild/protobuf": "2.15.0",
26
+ "@godspeedai/cognate-events": "^0.1.1",
27
+ "@godspeedai/cognate-kernel-api": "^0.1.1",
28
+ "@godspeedai/cognate-proto": "^0.1.1",
29
+ "@godspeedai/cognate-runtime-api": "^0.1.1",
30
+ "@connectrpc/connect": "2.2.0"
31
+ },
32
+ "devDependencies": {
33
+ "@godspeedai/cognate-protocol-connect-bun": "workspace:*",
34
+ "@godspeedai/cognate-runtime-bun": "workspace:*"
35
+ }
36
+ }
package/src/index.ts ADDED
@@ -0,0 +1,715 @@
1
+ // Maps the transport-independent RuntimeService (spec §22, ADR-0011) onto the generated Connect
2
+ // service. Caller identity always comes from the transport's authenticator (spec §32), never from
3
+ // message bodies. The same ServiceError code round-trips through the wire in both directions.
4
+ import { fromJson, toJson } from "@bufbuild/protobuf";
5
+ import { type Value, ValueSchema } from "@bufbuild/protobuf/wkt";
6
+ import type { ConnectRouter, HandlerContext, Transport } from "@connectrpc/connect";
7
+ import { Code, ConnectError, createClient } from "@connectrpc/connect";
8
+ import {
9
+ type Continuation,
10
+ ContinuationAction as PbContinuationAction,
11
+ ContinuationStatus as PbContinuationStatus,
12
+ type Event as PbEvent,
13
+ type JsonPatchOp as PbJsonPatchOp,
14
+ ResolveOutcome as PbResolveOutcome,
15
+ type Run,
16
+ type RemoteCapabilityOffer as PbRemoteCapabilityOffer,
17
+ RunStatus as PbRunStatus,
18
+ RuntimeService as RuntimeServiceDesc,
19
+ type SemanticRef as PbSemanticRef,
20
+ type StateUpdate as PbStateUpdate,
21
+ } from "@godspeedai/cognate-proto";
22
+ import type { Json, StoredEvent } from "@godspeedai/cognate-events";
23
+ import type { SemanticRef } from "@godspeedai/cognate-kernel-api";
24
+ import type { Caller, ContinuationView, JsonPatchOp, RemoteCapabilityOffer, RunView, RuntimeService, ServiceErrorCode, StateUpdate } from "@godspeedai/cognate-runtime-api";
25
+ import { ServiceError } from "@godspeedai/cognate-runtime-api";
26
+
27
+ export interface HandlerOptions {
28
+ /** Establish the caller from request headers (e.g. `authorization: Bearer …`); undefined → unauthenticated. */
29
+ readonly authenticate: (headers: Headers) => Caller | undefined | Promise<Caller | undefined>;
30
+ /** Maximum nesting depth of JSON values (google.protobuf.Value) accepted from clients. */
31
+ readonly maxJsonDepth: number;
32
+ }
33
+
34
+ /** The ServiceError ↔ Connect code table (exported for tests and other transports). */
35
+ export const errorCodes: Readonly<Record<ServiceErrorCode, number>> = {
36
+ not_found: Code.NotFound,
37
+ permission_denied: Code.PermissionDenied,
38
+ invalid_argument: Code.InvalidArgument,
39
+ failed_precondition: Code.FailedPrecondition,
40
+ unavailable: Code.Unavailable,
41
+ deadline_exceeded: Code.DeadlineExceeded,
42
+ already_exists: Code.AlreadyExists,
43
+ unauthenticated: Code.Unauthenticated,
44
+ resource_exhausted: Code.ResourceExhausted,
45
+ };
46
+
47
+ const codeToServiceError: ReadonlyMap<number, ServiceErrorCode> = new Map(
48
+ (Object.entries(errorCodes) as [ServiceErrorCode, number][]).map(([code, connectCode]) => [connectCode, code]),
49
+ );
50
+
51
+ // ── JSON ↔ google.protobuf.Value ────────────────────────────────────────────────
52
+
53
+ function jsonToValue(json: Json): Value {
54
+ return fromJson(ValueSchema, json as never);
55
+ }
56
+
57
+ function valueToJson(value: Value | undefined): Json {
58
+ // An absent field, or a Value with no oneof case set (e.g. a bare object literal handed to the
59
+ // generated client's `create()` for a `google.protobuf.Value` field, which does not coerce plain
60
+ // JSON the way it does for `Struct`/`ListValue` fields), is treated as JSON null rather than
61
+ // raising `@bufbuild/protobuf`'s "must have a value" error.
62
+ if (value === undefined || value.kind.case === undefined) return null;
63
+ return toJson(ValueSchema, value) as Json;
64
+ }
65
+
66
+ function semanticRefInit(ref: SemanticRef | undefined) {
67
+ if (!ref) return undefined;
68
+ return { namespace: ref.namespace, id: ref.id, kind: ref.kind ?? "", source: { uri: ref.source.uri, digest: ref.source.digest }, projectionVersion: ref.projectionVersion };
69
+ }
70
+
71
+ function semanticRefFromWire(ref: PbSemanticRef | undefined): SemanticRef | undefined {
72
+ if (!ref) return undefined;
73
+ return { namespace: ref.namespace, id: ref.id, kind: ref.kind || undefined, source: { uri: ref.source?.uri ?? "", digest: ref.source?.digest ?? "" }, projectionVersion: ref.projectionVersion };
74
+ }
75
+
76
+ function jsonDepth(value: unknown): number {
77
+ if (value === null || typeof value !== "object") return 0;
78
+ const values = Array.isArray(value) ? value : Object.values(value as Record<string, unknown>);
79
+ let max = 0;
80
+ for (const v of values) max = Math.max(max, jsonDepth(v));
81
+ return values.length === 0 ? 1 : 1 + max;
82
+ }
83
+
84
+ /** Decode an incoming Value and enforce the configured depth bound (spec §32). */
85
+ function decodeValue(value: Value | undefined, maxJsonDepth: number): Json {
86
+ const json = valueToJson(value);
87
+ if (jsonDepth(json) > maxJsonDepth) {
88
+ throw new ConnectError(`value exceeds maximum JSON depth of ${maxJsonDepth}`, Code.InvalidArgument);
89
+ }
90
+ return json;
91
+ }
92
+
93
+ // ── uint64 ↔ number ───────────────────────────────────────────────────────────────
94
+
95
+ const toNumber = (v: bigint | undefined): number | undefined => (v === undefined ? undefined : Number(v));
96
+ const toBigInt = (v: number | null | undefined): bigint | undefined => (v === null || v === undefined ? undefined : BigInt(Math.trunc(v)));
97
+
98
+ // ── enums ↔ string unions ──────────────────────────────────────────────────────────
99
+
100
+ const runStatusToProto: Record<RunView["status"], PbRunStatus> = {
101
+ running: PbRunStatus.RUNNING,
102
+ waiting: PbRunStatus.WAITING,
103
+ completed: PbRunStatus.COMPLETED,
104
+ failed: PbRunStatus.FAILED,
105
+ cancelled: PbRunStatus.CANCELLED,
106
+ };
107
+ const runStatusFromProto: Record<number, RunView["status"]> = {
108
+ [PbRunStatus.RUNNING]: "running",
109
+ [PbRunStatus.WAITING]: "waiting",
110
+ [PbRunStatus.COMPLETED]: "completed",
111
+ [PbRunStatus.FAILED]: "failed",
112
+ [PbRunStatus.CANCELLED]: "cancelled",
113
+ };
114
+
115
+ const continuationStatusToProto: Record<ContinuationView["status"], PbContinuationStatus> = {
116
+ OPEN: PbContinuationStatus.OPEN,
117
+ RESUMED: PbContinuationStatus.RESUMED,
118
+ CANCELLED: PbContinuationStatus.CANCELLED,
119
+ EXPIRED: PbContinuationStatus.EXPIRED,
120
+ FAILED: PbContinuationStatus.FAILED,
121
+ BLOCKED: PbContinuationStatus.BLOCKED,
122
+ };
123
+ const continuationStatusFromProto: Record<number, ContinuationView["status"]> = {
124
+ [PbContinuationStatus.OPEN]: "OPEN",
125
+ [PbContinuationStatus.RESUMED]: "RESUMED",
126
+ [PbContinuationStatus.CANCELLED]: "CANCELLED",
127
+ [PbContinuationStatus.EXPIRED]: "EXPIRED",
128
+ [PbContinuationStatus.FAILED]: "FAILED",
129
+ [PbContinuationStatus.BLOCKED]: "BLOCKED",
130
+ };
131
+
132
+ const continuationActionToProto: Record<"resume" | "cancel", PbContinuationAction> = {
133
+ resume: PbContinuationAction.RESUME,
134
+ cancel: PbContinuationAction.CANCEL,
135
+ };
136
+ const continuationActionFromProto: Record<number, "resume" | "cancel"> = {
137
+ [PbContinuationAction.RESUME]: "resume",
138
+ [PbContinuationAction.CANCEL]: "cancel",
139
+ };
140
+
141
+ const resolveOutcomeFromProto: Record<number, "transitioned" | "duplicate" | "already_terminal"> = {
142
+ [PbResolveOutcome.TRANSITIONED]: "transitioned",
143
+ [PbResolveOutcome.DUPLICATE]: "duplicate",
144
+ [PbResolveOutcome.ALREADY_TERMINAL]: "already_terminal",
145
+ };
146
+ const resolveOutcomeToProto: Record<"transitioned" | "duplicate" | "already_terminal", PbResolveOutcome> = {
147
+ transitioned: PbResolveOutcome.TRANSITIONED,
148
+ duplicate: PbResolveOutcome.DUPLICATE,
149
+ already_terminal: PbResolveOutcome.ALREADY_TERMINAL,
150
+ };
151
+
152
+ // ── message ↔ view conversions ────────────────────────────────────────────────────
153
+
154
+ function runInit(run: RunView) {
155
+ return {
156
+ runId: run.runId,
157
+ agent: run.agent,
158
+ tenant: run.tenant,
159
+ status: runStatusToProto[run.status],
160
+ input: jsonToValue(run.input),
161
+ output: jsonToValue(run.output),
162
+ error: run.error ?? undefined,
163
+ correlationId: run.correlationId,
164
+ startedBy: run.startedBy,
165
+ waitingOn: [...run.waitingOn],
166
+ };
167
+ }
168
+
169
+ function runFromWire(run: Run): RunView {
170
+ return {
171
+ runId: run.runId,
172
+ agent: run.agent,
173
+ tenant: run.tenant,
174
+ status: runStatusFromProto[run.status] ?? "running",
175
+ input: valueToJson(run.input),
176
+ output: valueToJson(run.output),
177
+ error: run.error ?? null,
178
+ correlationId: run.correlationId,
179
+ startedBy: run.startedBy,
180
+ waitingOn: run.waitingOn,
181
+ };
182
+ }
183
+
184
+ function continuationInit(c: ContinuationView) {
185
+ return {
186
+ id: c.id,
187
+ runId: c.runId,
188
+ type: c.type,
189
+ status: continuationStatusToProto[c.status],
190
+ condition: jsonToValue(c.condition),
191
+ payload: jsonToValue(c.payload),
192
+ version: BigInt(c.version),
193
+ expiresAt: c.expiresAt === null ? undefined : BigInt(c.expiresAt),
194
+ };
195
+ }
196
+
197
+ function continuationFromWire(c: Continuation): ContinuationView {
198
+ return {
199
+ id: c.id,
200
+ runId: c.runId,
201
+ type: c.type,
202
+ status: continuationStatusFromProto[c.status] ?? "OPEN",
203
+ condition: valueToJson(c.condition),
204
+ payload: valueToJson(c.payload),
205
+ version: Number(c.version),
206
+ expiresAt: c.expiresAt === undefined ? null : Number(c.expiresAt),
207
+ };
208
+ }
209
+
210
+ function eventInit(e: StoredEvent) {
211
+ return {
212
+ eventId: e.eventId,
213
+ streamId: e.streamId,
214
+ streamSequence: BigInt(e.streamSequence),
215
+ position: BigInt(e.position),
216
+ eventType: e.eventType,
217
+ schemaVersion: e.schemaVersion,
218
+ occurredAt: e.occurredAt,
219
+ recordedAt: e.recordedAt,
220
+ tenant: e.tenant,
221
+ correlationId: e.correlationId,
222
+ causationId: e.causationId ?? undefined,
223
+ runId: e.runId ?? undefined,
224
+ scopeId: e.scopeId,
225
+ componentId: e.componentId,
226
+ fiberId: e.fiberId,
227
+ semanticRef: semanticRefInit(e.semanticRef),
228
+ payload: jsonToValue(e.payload),
229
+ metadata: e.metadata,
230
+ erasure: e.erasure ? { reason: e.erasure.reason, erasedAt: e.erasure.erasedAt } : undefined,
231
+ };
232
+ }
233
+
234
+ function eventFromWire(e: PbEvent): StoredEvent {
235
+ return {
236
+ eventId: e.eventId,
237
+ streamId: e.streamId,
238
+ streamSequence: Number(e.streamSequence),
239
+ position: Number(e.position),
240
+ eventType: e.eventType,
241
+ schemaVersion: e.schemaVersion,
242
+ occurredAt: e.occurredAt,
243
+ recordedAt: e.recordedAt,
244
+ tenant: e.tenant,
245
+ correlationId: e.correlationId,
246
+ causationId: e.causationId ?? null,
247
+ runId: e.runId ?? null,
248
+ scopeId: e.scopeId,
249
+ componentId: e.componentId,
250
+ fiberId: e.fiberId,
251
+ semanticRef: semanticRefFromWire(e.semanticRef),
252
+ payload: valueToJson(e.payload),
253
+ metadata: e.metadata as { readonly [key: string]: Json } | undefined,
254
+ erasure: e.erasure ? { reason: e.erasure.reason, erasedAt: e.erasure.erasedAt } : undefined,
255
+ };
256
+ }
257
+
258
+ // ── shared state (spec §29.1) ───────────────────────────────────────────────────────
259
+
260
+ function jsonPatchOpInit(op: JsonPatchOp) {
261
+ return {
262
+ op: op.op,
263
+ path: op.path,
264
+ from: "from" in op ? op.from : undefined,
265
+ value: jsonToValue("value" in op ? op.value : null),
266
+ };
267
+ }
268
+
269
+ function jsonPatchOpFromWire(op: PbJsonPatchOp): JsonPatchOp {
270
+ const value = valueToJson(op.value);
271
+ switch (op.op) {
272
+ case "add":
273
+ return { op: "add", path: op.path, value };
274
+ case "replace":
275
+ return { op: "replace", path: op.path, value };
276
+ case "remove":
277
+ return { op: "remove", path: op.path };
278
+ case "move":
279
+ return { op: "move", from: op.from ?? "", path: op.path };
280
+ case "copy":
281
+ return { op: "copy", from: op.from ?? "", path: op.path };
282
+ case "test":
283
+ return { op: "test", path: op.path, value };
284
+ default:
285
+ throw new ConnectError(`unknown JSON Patch op "${op.op}"`, Code.InvalidArgument);
286
+ }
287
+ }
288
+
289
+ function stateUpdateFieldInit(update: StateUpdate) {
290
+ if ("snapshot" in update) return { kind: { case: "snapshot" as const, value: jsonToValue(update.snapshot) } };
291
+ return { kind: { case: "patch" as const, value: { ops: update.patch.map(jsonPatchOpInit) } } };
292
+ }
293
+
294
+ function stateUpdateFromWire(update: PbStateUpdate | undefined): StateUpdate {
295
+ if (update?.kind.case === "patch") return { patch: update.kind.value.ops.map(jsonPatchOpFromWire) };
296
+ return { snapshot: valueToJson(update?.kind.case === "snapshot" ? update.kind.value : undefined) };
297
+ }
298
+
299
+ function offerInit(offer: RemoteCapabilityOffer) {
300
+ return {
301
+ id: offer.id, leaseId: offer.leaseId, agent: offer.agent, scopeId: offer.scopeId,
302
+ capability: offer.contract.id, contractVersion: offer.contract.version, attributes: jsonToValue(offer.contract.attributes ?? {}),
303
+ description: offer.description, inputSchema: jsonToValue(offer.inputSchema), outputSchema: offer.outputSchema === undefined ? undefined : jsonToValue(offer.outputSchema), expiresAt: BigInt(offer.expiresAt),
304
+ };
305
+ }
306
+
307
+ function offerFromWire(offer: PbRemoteCapabilityOffer): RemoteCapabilityOffer {
308
+ const attributes = valueToJson(offer.attributes);
309
+ return {
310
+ id: offer.id, leaseId: offer.leaseId, agent: offer.agent, scopeId: offer.scopeId,
311
+ contract: { id: offer.capability, version: offer.contractVersion, ...(attributes && typeof attributes === "object" && !Array.isArray(attributes) ? { attributes: attributes as Readonly<Record<string, Json>> } : {}) },
312
+ description: offer.description, inputSchema: valueToJson(offer.inputSchema), ...(offer.outputSchema === undefined ? {} : { outputSchema: valueToJson(offer.outputSchema) }), expiresAt: Number(offer.expiresAt),
313
+ };
314
+ }
315
+
316
+ // ── error mapping ─────────────────────────────────────────────────────────────────
317
+
318
+ function throwConnectError(e: unknown): never {
319
+ if (e instanceof ServiceError) {
320
+ throw new ConnectError(e.message, errorCodes[e.code]);
321
+ }
322
+ throw e;
323
+ }
324
+
325
+ function throwServiceError(e: unknown): never {
326
+ if (e instanceof ConnectError) {
327
+ const code = codeToServiceError.get(e.code) ?? "unavailable";
328
+ throw new ServiceError(code, e.rawMessage || e.message);
329
+ }
330
+ throw e;
331
+ }
332
+
333
+ /** Race a unary call against the handler's deadline signal (spec §32); the signal is set up by the transport. */
334
+ function withDeadline<T>(context: HandlerContext, work: Promise<T>): Promise<T> {
335
+ if (context.signal.aborted) {
336
+ return Promise.reject(new ConnectError("deadline exceeded", Code.DeadlineExceeded));
337
+ }
338
+ return new Promise<T>((resolve, reject) => {
339
+ const onAbort = () => reject(new ConnectError("deadline exceeded", Code.DeadlineExceeded));
340
+ context.signal.addEventListener("abort", onAbort, { once: true });
341
+ work.then(
342
+ (v) => {
343
+ context.signal.removeEventListener("abort", onAbort);
344
+ resolve(v);
345
+ },
346
+ (e) => {
347
+ context.signal.removeEventListener("abort", onAbort);
348
+ reject(e);
349
+ },
350
+ );
351
+ });
352
+ }
353
+
354
+ async function requireCaller(options: HandlerOptions, context: HandlerContext): Promise<Caller> {
355
+ const caller = await options.authenticate(context.requestHeader);
356
+ if (!caller) throw new ConnectError("unauthenticated", Code.Unauthenticated);
357
+ return caller;
358
+ }
359
+
360
+ /** Register the RuntimeService routes on a Connect router. ServiceError codes map to Connect codes. */
361
+ export function registerRuntimeService(router: ConnectRouter, service: RuntimeService, options: HandlerOptions): void {
362
+ const depth = options.maxJsonDepth;
363
+ router.service(RuntimeServiceDesc, {
364
+ async startRun(req, context) {
365
+ try {
366
+ const caller = await requireCaller(options, context);
367
+ const run = await withDeadline(
368
+ context,
369
+ service.startRun(caller, {
370
+ agent: req.agent,
371
+ input: decodeValue(req.input, depth),
372
+ idempotencyKey: req.idempotencyKey,
373
+ correlationId: req.correlationId,
374
+ state: req.state !== undefined ? decodeValue(req.state, depth) : undefined,
375
+ }),
376
+ );
377
+ return runInit(run);
378
+ } catch (e) {
379
+ throwConnectError(e);
380
+ }
381
+ },
382
+ async getRun(req, context) {
383
+ try {
384
+ const caller = await requireCaller(options, context);
385
+ const run = await withDeadline(context, service.getRun(caller, { runId: req.runId }));
386
+ return runInit(run);
387
+ } catch (e) {
388
+ throwConnectError(e);
389
+ }
390
+ },
391
+ async cancelRun(req, context) {
392
+ try {
393
+ const caller = await requireCaller(options, context);
394
+ const run = await withDeadline(context, service.cancelRun(caller, { runId: req.runId, reason: req.reason, idempotencyKey: req.idempotencyKey }));
395
+ return runInit(run);
396
+ } catch (e) {
397
+ throwConnectError(e);
398
+ }
399
+ },
400
+ async *streamEvents(req, context) {
401
+ const caller = await requireCaller(options, context);
402
+ try {
403
+ const iterable = service.events(caller, {
404
+ afterPosition: toNumber(req.afterPosition),
405
+ runId: req.runId,
406
+ correlationId: req.correlationId,
407
+ follow: req.follow,
408
+ signal: context.signal,
409
+ });
410
+ for await (const event of iterable) {
411
+ if (context.signal.aborted) return;
412
+ yield eventInit(event);
413
+ }
414
+ } catch (e) {
415
+ throwConnectError(e);
416
+ }
417
+ },
418
+ async listContinuations(req, context) {
419
+ try {
420
+ const caller = await requireCaller(options, context);
421
+ const status = req.status === PbContinuationStatus.UNSPECIFIED ? undefined : continuationStatusFromProto[req.status];
422
+ const continuations = await withDeadline(context, service.listContinuations(caller, { runId: req.runId, status }));
423
+ return { continuations: continuations.map(continuationInit) };
424
+ } catch (e) {
425
+ throwConnectError(e);
426
+ }
427
+ },
428
+ async resolveContinuation(req, context) {
429
+ try {
430
+ const caller = await requireCaller(options, context);
431
+ const result = await withDeadline(
432
+ context,
433
+ service.resolveContinuation(caller, {
434
+ continuationId: req.continuationId,
435
+ action: continuationActionFromProto[req.action] ?? "resume",
436
+ input: decodeValue(req.input, depth),
437
+ reason: req.reason,
438
+ idempotencyKey: req.idempotencyKey,
439
+ expectedVersion: toNumber(req.expectedVersion),
440
+ }),
441
+ );
442
+ return { outcome: resolveOutcomeToProto[result.outcome], continuation: continuationInit(result.continuation) };
443
+ } catch (e) {
444
+ throwConnectError(e);
445
+ }
446
+ },
447
+ async invoke(req, context) {
448
+ try {
449
+ const caller = await requireCaller(options, context);
450
+ const output = await withDeadline(
451
+ context,
452
+ service.invoke(caller, { capability: req.capability, input: decodeValue(req.input, depth), correlationId: req.correlationId, idempotencyKey: req.idempotencyKey, deadline: toNumber(req.deadline) }),
453
+ );
454
+ return { output: jsonToValue(output) };
455
+ } catch (e) {
456
+ throwConnectError(e);
457
+ }
458
+ },
459
+ async getArtifact(req, context) {
460
+ try {
461
+ const caller = await requireCaller(options, context);
462
+ const artifact = await withDeadline(context, service.getArtifact(caller, { artifactId: req.artifactId, representation: req.representation }));
463
+ return { id: artifact.id, name: artifact.name, mediaType: artifact.mediaType, contentHash: artifact.contentHash, bytes: artifact.bytes };
464
+ } catch (e) {
465
+ throwConnectError(e);
466
+ }
467
+ },
468
+ async readProjection(req, context) {
469
+ try {
470
+ const caller = await requireCaller(options, context);
471
+ const entries = await withDeadline(context, service.readProjection(caller, { name: req.name }));
472
+ return { entries: entries.map((entry) => ({ key: entry.key, value: jsonToValue(entry.value) })) };
473
+ } catch (e) {
474
+ throwConnectError(e);
475
+ }
476
+ },
477
+ async listRuns(req, context) {
478
+ try {
479
+ const caller = await requireCaller(options, context);
480
+ const runs = await withDeadline(context, service.listRuns(caller, { correlationId: req.correlationId, agent: req.agent }));
481
+ return { runs: runs.map(runInit) };
482
+ } catch (e) {
483
+ throwConnectError(e);
484
+ }
485
+ },
486
+ async updateState(req, context) {
487
+ try {
488
+ const caller = await requireCaller(options, context);
489
+ const result = await withDeadline(
490
+ context,
491
+ service.updateState(caller, { runId: req.runId, update: stateUpdateFromWire(req.update), idempotencyKey: req.idempotencyKey, expectedVersion: toNumber(req.expectedVersion) }),
492
+ );
493
+ return { state: jsonToValue(result.state), version: BigInt(result.version) };
494
+ } catch (e) {
495
+ throwConnectError(e);
496
+ }
497
+ },
498
+ async readSharedState(req, context) {
499
+ try {
500
+ const caller = await requireCaller(options, context);
501
+ const result = await withDeadline(context, service.readSharedState(caller, { threadId: req.threadId }));
502
+ return { state: jsonToValue(result.state), version: BigInt(result.version) };
503
+ } catch (e) { throwConnectError(e); }
504
+ },
505
+ async updateSharedState(req, context) {
506
+ try {
507
+ const caller = await requireCaller(options, context);
508
+ const result = await withDeadline(context, service.updateSharedState(caller, {
509
+ threadId: req.threadId,
510
+ update: stateUpdateFromWire(req.update),
511
+ idempotencyKey: req.idempotencyKey,
512
+ expectedVersion: toNumber(req.expectedVersion),
513
+ }));
514
+ return { state: jsonToValue(result.state), version: BigInt(result.version) };
515
+ } catch (e) { throwConnectError(e); }
516
+ },
517
+ async publishRemoteOffer(req, context) {
518
+ try {
519
+ const caller = await requireCaller(options, context);
520
+ const attributes = decodeValue(req.attributes, depth);
521
+ if (attributes === null || typeof attributes !== "object" || Array.isArray(attributes)) throw new ConnectError("offer attributes must be an object", Code.InvalidArgument);
522
+ const offer = await withDeadline(context, service.publishRemoteOffer(caller, { leaseId: req.leaseId, agent: req.agent, contract: { id: req.capability, version: req.contractVersion, attributes: attributes as Readonly<Record<string, Json>> }, description: req.description, inputSchema: decodeValue(req.inputSchema, depth), ...(req.outputSchema === undefined ? {} : { outputSchema: decodeValue(req.outputSchema, depth) }), ttlMs: Number(req.ttlMs) }));
523
+ return offerInit(offer);
524
+ } catch (e) { throwConnectError(e); }
525
+ },
526
+ async listRemoteOffers(req, context) {
527
+ try {
528
+ const caller = await requireCaller(options, context);
529
+ const offers = await withDeadline(context, service.listRemoteOffers(caller, { agent: req.agent }));
530
+ return { offers: offers.map(offerInit) };
531
+ } catch (e) { throwConnectError(e); }
532
+ },
533
+ async revokeRemoteOffer(req, context) {
534
+ try {
535
+ const caller = await requireCaller(options, context);
536
+ await withDeadline(context, service.revokeRemoteOffer(caller, { offerId: req.offerId }));
537
+ return {};
538
+ } catch (e) { throwConnectError(e); }
539
+ },
540
+ });
541
+ }
542
+
543
+ /** A RuntimeService backed by a remote Connect endpoint. `tokenFor` supplies the credential that authenticates a caller. */
544
+ export function createRemoteRuntimeService(transport: Transport, tokenFor: (caller: Caller) => string): RuntimeService {
545
+ const client = createClient(RuntimeServiceDesc, transport);
546
+ const headersFor = (caller: Caller) => ({ authorization: `Bearer ${tokenFor(caller)}` });
547
+
548
+ return {
549
+ async startRun(caller, request) {
550
+ try {
551
+ const run = await client.startRun(
552
+ {
553
+ agent: request.agent,
554
+ input: jsonToValue(request.input),
555
+ idempotencyKey: request.idempotencyKey,
556
+ correlationId: request.correlationId,
557
+ state: request.state !== undefined ? jsonToValue(request.state) : undefined,
558
+ },
559
+ { headers: headersFor(caller) },
560
+ );
561
+ return runFromWire(run);
562
+ } catch (e) {
563
+ throwServiceError(e);
564
+ }
565
+ },
566
+ async getRun(caller, request) {
567
+ try {
568
+ const run = await client.getRun({ runId: request.runId }, { headers: headersFor(caller) });
569
+ return runFromWire(run);
570
+ } catch (e) {
571
+ throwServiceError(e);
572
+ }
573
+ },
574
+ async cancelRun(caller, request) {
575
+ try {
576
+ const run = await client.cancelRun({ runId: request.runId, reason: request.reason, idempotencyKey: request.idempotencyKey }, { headers: headersFor(caller) });
577
+ return runFromWire(run);
578
+ } catch (e) {
579
+ throwServiceError(e);
580
+ }
581
+ },
582
+ events(caller, request) {
583
+ const headers = headersFor(caller);
584
+ const signal = request.signal;
585
+ return (async function* () {
586
+ try {
587
+ const stream = client.streamEvents(
588
+ { afterPosition: toBigInt(request.afterPosition), runId: request.runId, correlationId: request.correlationId, follow: request.follow ?? false },
589
+ { headers, signal },
590
+ );
591
+ for await (const event of stream) {
592
+ yield eventFromWire(event);
593
+ }
594
+ } catch (e) {
595
+ if (signal?.aborted) return;
596
+ throwServiceError(e);
597
+ }
598
+ })();
599
+ },
600
+ async listContinuations(caller, request) {
601
+ try {
602
+ const response = await client.listContinuations(
603
+ { runId: request.runId, status: request.status ? continuationStatusToProto[request.status] : PbContinuationStatus.UNSPECIFIED },
604
+ { headers: headersFor(caller) },
605
+ );
606
+ return response.continuations.map(continuationFromWire);
607
+ } catch (e) {
608
+ throwServiceError(e);
609
+ }
610
+ },
611
+ async resolveContinuation(caller, request) {
612
+ try {
613
+ const response = await client.resolveContinuation(
614
+ {
615
+ continuationId: request.continuationId,
616
+ action: continuationActionToProto[request.action],
617
+ input: jsonToValue(request.input ?? null),
618
+ reason: request.reason,
619
+ idempotencyKey: request.idempotencyKey,
620
+ expectedVersion: toBigInt(request.expectedVersion),
621
+ },
622
+ { headers: headersFor(caller) },
623
+ );
624
+ return { outcome: resolveOutcomeFromProto[response.outcome] ?? "transitioned", continuation: continuationFromWire(response.continuation!) };
625
+ } catch (e) {
626
+ throwServiceError(e);
627
+ }
628
+ },
629
+ async invoke(caller, request) {
630
+ try {
631
+ const response = await client.invoke(
632
+ { capability: request.capability, input: jsonToValue(request.input), correlationId: request.correlationId, idempotencyKey: request.idempotencyKey, deadline: toBigInt(request.deadline) },
633
+ { headers: headersFor(caller) },
634
+ );
635
+ return valueToJson(response.output);
636
+ } catch (e) {
637
+ throwServiceError(e);
638
+ }
639
+ },
640
+ async getArtifact(caller, request) {
641
+ try {
642
+ const artifact = await client.getArtifact({ artifactId: request.artifactId, representation: request.representation }, { headers: headersFor(caller) });
643
+ return { id: artifact.id, name: artifact.name, mediaType: artifact.mediaType, contentHash: artifact.contentHash, bytes: artifact.bytes };
644
+ } catch (e) {
645
+ throwServiceError(e);
646
+ }
647
+ },
648
+ async readProjection(caller, request) {
649
+ try {
650
+ const response = await client.readProjection({ name: request.name }, { headers: headersFor(caller) });
651
+ return response.entries.map((entry) => ({ key: entry.key, value: valueToJson(entry.value) }));
652
+ } catch (e) {
653
+ throwServiceError(e);
654
+ }
655
+ },
656
+ async listRuns(caller, request) {
657
+ try {
658
+ const response = await client.listRuns({ correlationId: request.correlationId, agent: request.agent }, { headers: headersFor(caller) });
659
+ return response.runs.map(runFromWire);
660
+ } catch (e) {
661
+ throwServiceError(e);
662
+ }
663
+ },
664
+ async updateState(caller, request) {
665
+ try {
666
+ const response = await client.updateState(
667
+ { runId: request.runId, update: stateUpdateFieldInit(request.update), idempotencyKey: request.idempotencyKey, expectedVersion: toBigInt(request.expectedVersion) },
668
+ { headers: headersFor(caller) },
669
+ );
670
+ return { state: valueToJson(response.state), version: Number(response.version) };
671
+ } catch (e) {
672
+ throwServiceError(e);
673
+ }
674
+ },
675
+ async readSharedState(caller, request) {
676
+ try {
677
+ const response = await client.readSharedState({ threadId: request.threadId }, { headers: headersFor(caller) });
678
+ return { state: valueToJson(response.state), version: Number(response.version) };
679
+ } catch (e) { throwServiceError(e); }
680
+ },
681
+ async updateSharedState(caller, request) {
682
+ try {
683
+ const response = await client.updateSharedState({
684
+ threadId: request.threadId,
685
+ update: stateUpdateFieldInit(request.update),
686
+ idempotencyKey: request.idempotencyKey,
687
+ expectedVersion: toBigInt(request.expectedVersion),
688
+ }, { headers: headersFor(caller) });
689
+ return { state: valueToJson(response.state), version: Number(response.version) };
690
+ } catch (e) { throwServiceError(e); }
691
+ },
692
+ async observe(_caller, _request) {
693
+ // Observation ingestion is an in-process, mechanism-layer door in v0 — deliberately not exposed over the
694
+ // public Connect surface (it is a provider/observer privilege, not a remote-caller capability).
695
+ throw new ServiceError("failed_precondition", "observation ingestion is an in-process door; not available over the remote Connect surface");
696
+ },
697
+ async publishRemoteOffer(caller, request) {
698
+ try {
699
+ const offer = await client.publishRemoteOffer({ leaseId: request.leaseId, agent: request.agent, capability: request.contract.id, contractVersion: request.contract.version, attributes: jsonToValue(request.contract.attributes ?? {}), description: request.description, inputSchema: jsonToValue(request.inputSchema), outputSchema: request.outputSchema === undefined ? undefined : jsonToValue(request.outputSchema), ttlMs: BigInt(request.ttlMs) }, { headers: headersFor(caller) });
700
+ return offerFromWire(offer);
701
+ } catch (e) { throwServiceError(e); }
702
+ },
703
+ async listRemoteOffers(caller, request) {
704
+ try {
705
+ const response = await client.listRemoteOffers({ agent: request.agent }, { headers: headersFor(caller) });
706
+ return response.offers.map(offerFromWire);
707
+ } catch (e) { throwServiceError(e); }
708
+ },
709
+ async revokeRemoteOffer(caller, request) {
710
+ try {
711
+ await client.revokeRemoteOffer({ offerId: request.offerId }, { headers: headersFor(caller) });
712
+ } catch (e) { throwServiceError(e); }
713
+ },
714
+ };
715
+ }