@agent-vm/agent-portal-sdk 0.0.120 → 0.0.122

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 (100) hide show
  1. package/dist/adapter-boundary/index.d.ts +2 -0
  2. package/dist/adapter-boundary/index.js +2 -0
  3. package/dist/adapter-boundary-BIagsTUH.js +29 -0
  4. package/dist/adapter-boundary-BIagsTUH.js.map +1 -0
  5. package/dist/approval-surface/index.d.ts +2 -0
  6. package/dist/approval-surface/index.js +2 -0
  7. package/dist/approval-surface-en5VAY5h.js +20 -0
  8. package/dist/approval-surface-en5VAY5h.js.map +1 -0
  9. package/dist/artifact-reference-schema-CiEjxYPd.js +13 -0
  10. package/dist/artifact-reference-schema-CiEjxYPd.js.map +1 -0
  11. package/dist/artifact-surface/index.d.ts +2 -0
  12. package/dist/artifact-surface/index.js +3 -0
  13. package/dist/artifact-surface-BstQxq6b.js +65 -0
  14. package/dist/artifact-surface-BstQxq6b.js.map +1 -0
  15. package/dist/capability-description-surface/index.d.ts +2 -0
  16. package/dist/capability-description-surface/index.js +3 -0
  17. package/dist/capability-description-surface-BdzknTKT.js +2 -0
  18. package/dist/capability-descriptor-schema-zRnfGjBc.js +86 -0
  19. package/dist/capability-descriptor-schema-zRnfGjBc.js.map +1 -0
  20. package/dist/cli/tool-portal.d.ts +1 -0
  21. package/dist/cli/tool-portal.js +207 -0
  22. package/dist/cli/tool-portal.js.map +1 -0
  23. package/dist/contracts/index.d.ts +2 -0
  24. package/dist/contracts/index.js +2 -0
  25. package/dist/contracts-RgGW0RX2.js +611 -0
  26. package/dist/contracts-RgGW0RX2.js.map +1 -0
  27. package/dist/gateway-runtime-client/index.d.ts +385 -0
  28. package/dist/gateway-runtime-client/index.d.ts.map +1 -0
  29. package/dist/gateway-runtime-client/index.js +1439 -0
  30. package/dist/gateway-runtime-client/index.js.map +1 -0
  31. package/dist/gateway-runtime-local-exec/gateway-runtime-local-exec-helper.d.ts +1 -0
  32. package/dist/gateway-runtime-local-exec/gateway-runtime-local-exec-helper.js +125 -0
  33. package/dist/gateway-runtime-local-exec/gateway-runtime-local-exec-helper.js.map +1 -0
  34. package/dist/gateway-runtime-local-exec/index.d.ts +54 -0
  35. package/dist/gateway-runtime-local-exec/index.d.ts.map +1 -0
  36. package/dist/gateway-runtime-local-exec/index.js +2 -0
  37. package/dist/gateway-runtime-local-exec-transport-B1hy2A3Q.js +427 -0
  38. package/dist/gateway-runtime-local-exec-transport-B1hy2A3Q.js.map +1 -0
  39. package/dist/index-B5hgm1KH.d.ts +84 -0
  40. package/dist/index-B5hgm1KH.d.ts.map +1 -0
  41. package/dist/index-BWE2_BcN.d.ts +64 -0
  42. package/dist/index-BWE2_BcN.d.ts.map +1 -0
  43. package/dist/index-BmH68K78.d.ts +41 -0
  44. package/dist/index-BmH68K78.d.ts.map +1 -0
  45. package/dist/index-ByAhyVbI.d.ts +142 -0
  46. package/dist/index-ByAhyVbI.d.ts.map +1 -0
  47. package/dist/index-C-NPMMvc.d.ts +2396 -0
  48. package/dist/index-C-NPMMvc.d.ts.map +1 -0
  49. package/dist/index-DKBSYuxW.d.ts +239 -0
  50. package/dist/index-DKBSYuxW.d.ts.map +1 -0
  51. package/dist/index-Dj4galCJ.d.ts +17 -0
  52. package/dist/index-Dj4galCJ.d.ts.map +1 -0
  53. package/dist/index-Dxoz-ORl.d.ts +229 -0
  54. package/dist/index-Dxoz-ORl.d.ts.map +1 -0
  55. package/dist/index-v8suC0qe.d.ts +69 -0
  56. package/dist/index-v8suC0qe.d.ts.map +1 -0
  57. package/dist/index-yeFGRMdv.d.ts +152 -0
  58. package/dist/index-yeFGRMdv.d.ts.map +1 -0
  59. package/dist/index.d.ts +12 -0
  60. package/dist/index.js +16 -0
  61. package/dist/json-value-schema-M87sjwWL.d.ts +18 -0
  62. package/dist/json-value-schema-M87sjwWL.d.ts.map +1 -0
  63. package/dist/json-value-schema-hdPkabRZ.js +29 -0
  64. package/dist/json-value-schema-hdPkabRZ.js.map +1 -0
  65. package/dist/node-tool-portal-mcp-transport-Cl2VKbLY.js +156 -0
  66. package/dist/node-tool-portal-mcp-transport-Cl2VKbLY.js.map +1 -0
  67. package/dist/portable-contracts/index.d.ts +2 -0
  68. package/dist/portable-contracts/index.js +3 -0
  69. package/dist/portable-contracts-Bca33zVa.js +326 -0
  70. package/dist/portable-contracts-Bca33zVa.js.map +1 -0
  71. package/dist/portable-refinement-authoring-ZSmR-amG.js +196 -0
  72. package/dist/portable-refinement-authoring-ZSmR-amG.js.map +1 -0
  73. package/dist/portal-call-request-schema-Cp6CMGs9.js +41 -0
  74. package/dist/portal-call-request-schema-Cp6CMGs9.js.map +1 -0
  75. package/dist/portal-call-result-schema-ByxHRCEN.js +158 -0
  76. package/dist/portal-call-result-schema-ByxHRCEN.js.map +1 -0
  77. package/dist/portal-call-result-schema-wSCaz3mC.d.ts +1485 -0
  78. package/dist/portal-call-result-schema-wSCaz3mC.d.ts.map +1 -0
  79. package/dist/portal-call-surface/index.d.ts +3 -0
  80. package/dist/portal-call-surface/index.js +5 -0
  81. package/dist/portal-call-surface-DjZVquFt.js +83 -0
  82. package/dist/portal-call-surface-DjZVquFt.js.map +1 -0
  83. package/dist/portal-error-schema-CQHgoFq4.js +71 -0
  84. package/dist/portal-error-schema-CQHgoFq4.js.map +1 -0
  85. package/dist/portal-event-surface/index.d.ts +2 -0
  86. package/dist/portal-event-surface/index.js +3 -0
  87. package/dist/portal-event-surface-CdScrgoN.js +51 -0
  88. package/dist/portal-event-surface-CdScrgoN.js.map +1 -0
  89. package/dist/testing/index.d.ts +19 -0
  90. package/dist/testing/index.d.ts.map +1 -0
  91. package/dist/testing/index.js +36 -0
  92. package/dist/testing/index.js.map +1 -0
  93. package/dist/tool-portal-mcp-client/index.d.ts +2 -0
  94. package/dist/tool-portal-mcp-client/index.js +2 -0
  95. package/dist/tool-portal-mcp-client/node-tool-portal-mcp-transport.d.ts +17 -0
  96. package/dist/tool-portal-mcp-client/node-tool-portal-mcp-transport.d.ts.map +1 -0
  97. package/dist/tool-portal-mcp-client/node-tool-portal-mcp-transport.js +2 -0
  98. package/dist/tool-portal-mcp-client-DwJF-48Y.js +90 -0
  99. package/dist/tool-portal-mcp-client-DwJF-48Y.js.map +1 -0
  100. package/package.json +1 -1
@@ -0,0 +1,1439 @@
1
+ import { d as PortalListResultSchema, i as PortalCallResultSchema, m as PortalSearchResultSchema, s as PortalDescribeResultSchema } from "../portal-call-result-schema-ByxHRCEN.js";
2
+ import { a as PortalArtifactReadRequestSchema, o as PortalArtifactReadResultSchema } from "../artifact-surface-BstQxq6b.js";
3
+ import { $ as SandboxExecStartResultSchema, A as SandboxProcessStartResultSchema, B as SandboxFsReadResultSchema, C as SandboxProcessCancelRequestSchema, D as SandboxProcessLogsRequestSchema, F as SandboxFsListRequestSchema, G as SandboxFsStatRequestSchema, H as SandboxFsRemoveResultSchema, I as SandboxFsListResultSchema, J as SandboxFsWriteResultSchema, K as SandboxFsStatResultSchema, L as SandboxFsMkdirRequestSchema, M as SandboxProcessWaitRequestSchema, N as SandboxProcessWaitResultSchema, O as SandboxProcessLogsResultSchema, Q as SandboxExecStartRequestSchema, R as SandboxFsMkdirResultSchema, S as SandboxStreamWriteResultSchema, T as SandboxProcessHandleRequestSchema, U as SandboxFsRenameRequestSchema, V as SandboxFsRemoveRequestSchema, W as SandboxFsRenameResultSchema, X as SandboxExecCancelResultSchema, Y as SandboxExecCancelRequestSchema, _ as SandboxStreamCloseRequestSchema, at as SandboxEnvironmentOpenRequestSchema, b as SandboxStreamReadResultSchema, c as GatewayRuntimeTrustedInvocationCorrelationSchema, et as SandboxExecWaitRequestSchema, ft as SandboxRetainedResultLookupRequestSchema, g as SandboxTerminalResizeResultSchema, h as SandboxTerminalResizeRequestSchema, it as SandboxEnvironmentHandleRequestSchema, j as SandboxProcessStatusResultSchema, k as SandboxProcessStartRequestSchema, l as GatewayRuntimeTrustedInvocationPrincipalSchema, m as SandboxTerminalAttachResultSchema, n as GatewayRuntimeAttachmentMetadataSchema, ot as SandboxEnvironmentOpenResultSchema, p as SandboxTerminalAttachRequestSchema, pt as SandboxRetainedResultLookupResultSchema, q as SandboxFsWriteRequestSchema, rt as SandboxEnvironmentCloseResultSchema, s as GatewayRuntimeTrustedInvocationContextSchema, st as SandboxEnvironmentStatusResultSchema, tt as SandboxExecWaitResultSchema, u as GatewayRuntimeTrustedInvocationRequesterSchema, v as SandboxStreamCloseResultSchema, w as SandboxProcessCancelResultSchema, x as SandboxStreamWriteRequestSchema, y as SandboxStreamReadRequestSchema, z as SandboxFsReadRequestSchema } from "../contracts-RgGW0RX2.js";
4
+ import { r as PortalCallRequestSchema } from "../portal-call-request-schema-Cp6CMGs9.js";
5
+ import { a as PortalListRequestSchema, r as PortalSearchRequestSchema, s as PortalDescribeRequestSchema } from "../portal-call-surface-DjZVquFt.js";
6
+ import { z } from "zod/v4";
7
+ import net from "node:net";
8
+ //#region src/gateway-runtime-client/gateway-runtime-sandbox-operations.ts
9
+ async function requestSandboxOperation(props) {
10
+ const publicRequest = props.requestSchema.parse(props.request);
11
+ const trustedContext = GatewayRuntimeTrustedInvocationContextSchema.parse(props.options.trustedContext);
12
+ const result = await props.client.request(props.method, {
13
+ publicRequest,
14
+ trustedContext
15
+ }, {
16
+ ...props.options.signal === void 0 ? {} : { signal: props.options.signal },
17
+ ...props.options.traceContext === void 0 ? {} : { traceContext: props.options.traceContext }
18
+ });
19
+ return props.resultSchema.parse(result);
20
+ }
21
+ var GatewayRuntimeSandboxEnvironmentOperations = class {
22
+ #client;
23
+ constructor(client) {
24
+ this.#client = client;
25
+ }
26
+ async open(request, options) {
27
+ return await requestSandboxOperation({
28
+ client: this.#client,
29
+ method: "sandbox.environment.open",
30
+ options,
31
+ request,
32
+ requestSchema: SandboxEnvironmentOpenRequestSchema,
33
+ resultSchema: SandboxEnvironmentOpenResultSchema
34
+ });
35
+ }
36
+ async close(request, options) {
37
+ return await requestSandboxOperation({
38
+ client: this.#client,
39
+ method: "sandbox.environment.close",
40
+ options,
41
+ request,
42
+ requestSchema: SandboxEnvironmentHandleRequestSchema,
43
+ resultSchema: SandboxEnvironmentCloseResultSchema
44
+ });
45
+ }
46
+ async status(request, options) {
47
+ return await requestSandboxOperation({
48
+ client: this.#client,
49
+ method: "sandbox.environment.status",
50
+ options,
51
+ request,
52
+ requestSchema: SandboxEnvironmentHandleRequestSchema,
53
+ resultSchema: SandboxEnvironmentStatusResultSchema
54
+ });
55
+ }
56
+ };
57
+ var GatewayRuntimeSandboxExecutionOperations = class {
58
+ #client;
59
+ constructor(client) {
60
+ this.#client = client;
61
+ }
62
+ async start(request, options) {
63
+ return await requestSandboxOperation({
64
+ client: this.#client,
65
+ method: "sandbox.exec.start",
66
+ options,
67
+ request,
68
+ requestSchema: SandboxExecStartRequestSchema,
69
+ resultSchema: SandboxExecStartResultSchema
70
+ });
71
+ }
72
+ async wait(request, options) {
73
+ return await requestSandboxOperation({
74
+ client: this.#client,
75
+ method: "sandbox.exec.wait",
76
+ options,
77
+ request,
78
+ requestSchema: SandboxExecWaitRequestSchema,
79
+ resultSchema: SandboxExecWaitResultSchema
80
+ });
81
+ }
82
+ async cancel(request, options) {
83
+ return await requestSandboxOperation({
84
+ client: this.#client,
85
+ method: "sandbox.exec.cancel",
86
+ options,
87
+ request,
88
+ requestSchema: SandboxExecCancelRequestSchema,
89
+ resultSchema: SandboxExecCancelResultSchema
90
+ });
91
+ }
92
+ };
93
+ var GatewayRuntimeSandboxRetainedResultOperations = class {
94
+ #client;
95
+ constructor(client) {
96
+ this.#client = client;
97
+ }
98
+ async lookup(request, options) {
99
+ return await requestSandboxOperation({
100
+ client: this.#client,
101
+ method: "sandbox.retained-result.lookup",
102
+ options,
103
+ request,
104
+ requestSchema: SandboxRetainedResultLookupRequestSchema,
105
+ resultSchema: SandboxRetainedResultLookupResultSchema
106
+ });
107
+ }
108
+ };
109
+ var GatewayRuntimeSandboxFilesystemOperations = class {
110
+ #client;
111
+ constructor(client) {
112
+ this.#client = client;
113
+ }
114
+ async stat(request, options) {
115
+ return await requestSandboxOperation({
116
+ client: this.#client,
117
+ method: "sandbox.fs.stat",
118
+ options,
119
+ request,
120
+ requestSchema: SandboxFsStatRequestSchema,
121
+ resultSchema: SandboxFsStatResultSchema
122
+ });
123
+ }
124
+ async list(request, options) {
125
+ return await requestSandboxOperation({
126
+ client: this.#client,
127
+ method: "sandbox.fs.list",
128
+ options,
129
+ request,
130
+ requestSchema: SandboxFsListRequestSchema,
131
+ resultSchema: SandboxFsListResultSchema
132
+ });
133
+ }
134
+ async read(request, options) {
135
+ return await requestSandboxOperation({
136
+ client: this.#client,
137
+ method: "sandbox.fs.read",
138
+ options,
139
+ request,
140
+ requestSchema: SandboxFsReadRequestSchema,
141
+ resultSchema: SandboxFsReadResultSchema
142
+ });
143
+ }
144
+ async write(request, options) {
145
+ return await requestSandboxOperation({
146
+ client: this.#client,
147
+ method: "sandbox.fs.write",
148
+ options,
149
+ request,
150
+ requestSchema: SandboxFsWriteRequestSchema,
151
+ resultSchema: SandboxFsWriteResultSchema
152
+ });
153
+ }
154
+ async mkdir(request, options) {
155
+ return await requestSandboxOperation({
156
+ client: this.#client,
157
+ method: "sandbox.fs.mkdir",
158
+ options,
159
+ request,
160
+ requestSchema: SandboxFsMkdirRequestSchema,
161
+ resultSchema: SandboxFsMkdirResultSchema
162
+ });
163
+ }
164
+ async rename(request, options) {
165
+ return await requestSandboxOperation({
166
+ client: this.#client,
167
+ method: "sandbox.fs.rename",
168
+ options,
169
+ request,
170
+ requestSchema: SandboxFsRenameRequestSchema,
171
+ resultSchema: SandboxFsRenameResultSchema
172
+ });
173
+ }
174
+ async remove(request, options) {
175
+ return await requestSandboxOperation({
176
+ client: this.#client,
177
+ method: "sandbox.fs.remove",
178
+ options,
179
+ request,
180
+ requestSchema: SandboxFsRemoveRequestSchema,
181
+ resultSchema: SandboxFsRemoveResultSchema
182
+ });
183
+ }
184
+ };
185
+ var GatewayRuntimeSandboxProcessOperations = class {
186
+ #client;
187
+ constructor(client) {
188
+ this.#client = client;
189
+ }
190
+ async start(request, options) {
191
+ return await requestSandboxOperation({
192
+ client: this.#client,
193
+ method: "sandbox.process.start",
194
+ options,
195
+ request,
196
+ requestSchema: SandboxProcessStartRequestSchema,
197
+ resultSchema: SandboxProcessStartResultSchema
198
+ });
199
+ }
200
+ async status(request, options) {
201
+ return await requestSandboxOperation({
202
+ client: this.#client,
203
+ method: "sandbox.process.status",
204
+ options,
205
+ request,
206
+ requestSchema: SandboxProcessHandleRequestSchema,
207
+ resultSchema: SandboxProcessStatusResultSchema
208
+ });
209
+ }
210
+ async wait(request, options) {
211
+ return await requestSandboxOperation({
212
+ client: this.#client,
213
+ method: "sandbox.process.wait",
214
+ options,
215
+ request,
216
+ requestSchema: SandboxProcessWaitRequestSchema,
217
+ resultSchema: SandboxProcessWaitResultSchema
218
+ });
219
+ }
220
+ async logs(request, options) {
221
+ return await requestSandboxOperation({
222
+ client: this.#client,
223
+ method: "sandbox.process.logs",
224
+ options,
225
+ request,
226
+ requestSchema: SandboxProcessLogsRequestSchema,
227
+ resultSchema: SandboxProcessLogsResultSchema
228
+ });
229
+ }
230
+ async cancel(request, options) {
231
+ return await requestSandboxOperation({
232
+ client: this.#client,
233
+ method: "sandbox.process.cancel",
234
+ options,
235
+ request,
236
+ requestSchema: SandboxProcessCancelRequestSchema,
237
+ resultSchema: SandboxProcessCancelResultSchema
238
+ });
239
+ }
240
+ };
241
+ var GatewayRuntimeSandboxStreamOperations = class {
242
+ #client;
243
+ constructor(client) {
244
+ this.#client = client;
245
+ }
246
+ async read(request, options) {
247
+ return await requestSandboxOperation({
248
+ client: this.#client,
249
+ method: "sandbox.stream.read",
250
+ options,
251
+ request,
252
+ requestSchema: SandboxStreamReadRequestSchema,
253
+ resultSchema: SandboxStreamReadResultSchema
254
+ });
255
+ }
256
+ async write(request, options) {
257
+ return await requestSandboxOperation({
258
+ client: this.#client,
259
+ method: "sandbox.stream.write",
260
+ options,
261
+ request,
262
+ requestSchema: SandboxStreamWriteRequestSchema,
263
+ resultSchema: SandboxStreamWriteResultSchema
264
+ });
265
+ }
266
+ async close(request, options) {
267
+ return await requestSandboxOperation({
268
+ client: this.#client,
269
+ method: "sandbox.stream.close",
270
+ options,
271
+ request,
272
+ requestSchema: SandboxStreamCloseRequestSchema,
273
+ resultSchema: SandboxStreamCloseResultSchema
274
+ });
275
+ }
276
+ };
277
+ var GatewayRuntimeSandboxTerminalOperations = class {
278
+ #client;
279
+ constructor(client) {
280
+ this.#client = client;
281
+ }
282
+ async attach(request, options) {
283
+ return await requestSandboxOperation({
284
+ client: this.#client,
285
+ method: "sandbox.terminal.attach",
286
+ options,
287
+ request,
288
+ requestSchema: SandboxTerminalAttachRequestSchema,
289
+ resultSchema: SandboxTerminalAttachResultSchema
290
+ });
291
+ }
292
+ async resize(request, options) {
293
+ return await requestSandboxOperation({
294
+ client: this.#client,
295
+ method: "sandbox.terminal.resize",
296
+ options,
297
+ request,
298
+ requestSchema: SandboxTerminalResizeRequestSchema,
299
+ resultSchema: SandboxTerminalResizeResultSchema
300
+ });
301
+ }
302
+ };
303
+ var GatewayRuntimeSandboxOperations = class {
304
+ environment;
305
+ execution;
306
+ filesystem;
307
+ process;
308
+ retainedResults;
309
+ stream;
310
+ terminal;
311
+ constructor(client) {
312
+ this.environment = new GatewayRuntimeSandboxEnvironmentOperations(client);
313
+ this.execution = new GatewayRuntimeSandboxExecutionOperations(client);
314
+ this.filesystem = new GatewayRuntimeSandboxFilesystemOperations(client);
315
+ this.process = new GatewayRuntimeSandboxProcessOperations(client);
316
+ this.retainedResults = new GatewayRuntimeSandboxRetainedResultOperations(client);
317
+ this.stream = new GatewayRuntimeSandboxStreamOperations(client);
318
+ this.terminal = new GatewayRuntimeSandboxTerminalOperations(client);
319
+ Object.freeze(this.environment);
320
+ Object.freeze(this.execution);
321
+ Object.freeze(this.filesystem);
322
+ Object.freeze(this.process);
323
+ Object.freeze(this.retainedResults);
324
+ Object.freeze(this.stream);
325
+ Object.freeze(this.terminal);
326
+ }
327
+ };
328
+ //#endregion
329
+ //#region src/gateway-runtime-client/gateway-runtime-startup-retry.ts
330
+ const DEFAULT_GATEWAY_RUNTIME_STARTUP_RETRY_POLICY = Object.freeze({
331
+ deadlineMs: 5e3,
332
+ intervalMs: 100,
333
+ maxAttempts: 50
334
+ });
335
+ /** A pre-handshake socket publication race that is safe to retry within the startup budget. */
336
+ var GatewayRuntimeStartupUnavailableError = class extends Error {
337
+ code = "startup-unavailable";
338
+ kind;
339
+ constructor(kind, options = {}) {
340
+ super(`Gateway runtime startup socket is unavailable: ${kind}.`, options);
341
+ this.name = "GatewayRuntimeStartupUnavailableError";
342
+ this.kind = kind;
343
+ }
344
+ };
345
+ const defaultGatewayRuntimeStartupRetryScheduler = {
346
+ now: () => performance.now(),
347
+ wait: async (delayMs, signal) => {
348
+ if (signal.aborted) throw signal.reason;
349
+ await new Promise((resolve, reject) => {
350
+ const timeout = setTimeout(() => {
351
+ cleanup();
352
+ resolve();
353
+ }, delayMs);
354
+ const onAbort = () => {
355
+ cleanup();
356
+ reject(signal.reason);
357
+ };
358
+ const cleanup = () => {
359
+ clearTimeout(timeout);
360
+ signal.removeEventListener("abort", onAbort);
361
+ };
362
+ signal.addEventListener("abort", onAbort, { once: true });
363
+ });
364
+ }
365
+ };
366
+ //#endregion
367
+ //#region src/gateway-runtime-client/gateway-runtime-trace-context.ts
368
+ const GATEWAY_RUNTIME_TRACEPARENT_MAX_LENGTH = 512;
369
+ const GATEWAY_RUNTIME_TRACESTATE_MAX_LENGTH = 512;
370
+ const GATEWAY_RUNTIME_TRACESTATE_MAX_MEMBERS = 32;
371
+ const lowercaseHexPattern = /^[0-9a-f]+$/u;
372
+ const tracestateSimpleKeyPattern = /^[a-z][a-z0-9_*/-]{0,255}$/u;
373
+ const tracestateMultiTenantKeyPattern = /^[a-z0-9][a-z0-9_*/-]{0,240}@[a-z][a-z0-9_*/-]{0,13}$/u;
374
+ const tracestateValuePattern = /^[\x20-\x2b\x2d-\x3c\x3e-\x7e]{0,255}[\x21-\x2b\x2d-\x3c\x3e-\x7e]$/u;
375
+ const futureTraceparentSuffixPattern = /^[\x21-\x7e]+$/u;
376
+ function traceparentIsValid(traceparent) {
377
+ if (traceparent.length < 55 || traceparent.length > 512) return false;
378
+ if (traceparent[2] !== "-" || traceparent[35] !== "-" || traceparent[52] !== "-") return false;
379
+ const version = traceparent.slice(0, 2);
380
+ const traceId = traceparent.slice(3, 35);
381
+ const parentId = traceparent.slice(36, 52);
382
+ const traceFlags = traceparent.slice(53, 55);
383
+ if (!lowercaseHexPattern.test(version) || version === "ff" || !lowercaseHexPattern.test(traceId) || traceId === "0".repeat(32) || !lowercaseHexPattern.test(parentId) || parentId === "0".repeat(16) || !lowercaseHexPattern.test(traceFlags)) return false;
384
+ if (traceparent.length === 55) return true;
385
+ if (version === "00" || traceparent[55] !== "-") return false;
386
+ return futureTraceparentSuffixPattern.test(traceparent.slice(56));
387
+ }
388
+ function tracestateIsValid(tracestate) {
389
+ if (tracestate.length > 512) return false;
390
+ const rawMembers = tracestate.split(",");
391
+ if (rawMembers.length > 32) return false;
392
+ const seenKeys = /* @__PURE__ */ new Set();
393
+ for (const rawMember of rawMembers) {
394
+ const member = rawMember.replace(/^[ \t]+|[ \t]+$/gu, "");
395
+ if (member.length === 0) continue;
396
+ const equalsIndex = member.indexOf("=");
397
+ if (equalsIndex <= 0 || equalsIndex !== member.lastIndexOf("=")) return false;
398
+ const key = member.slice(0, equalsIndex);
399
+ const value = member.slice(equalsIndex + 1);
400
+ if (!tracestateSimpleKeyPattern.test(key) && !tracestateMultiTenantKeyPattern.test(key) || !tracestateValuePattern.test(value)) return false;
401
+ if (seenKeys.has(key)) return false;
402
+ seenKeys.add(key);
403
+ }
404
+ return true;
405
+ }
406
+ const GatewayRuntimeTraceparentSchema = z.string().max(512).refine(traceparentIsValid, "traceparent must follow the bounded W3C Trace Context grammar.");
407
+ const GatewayRuntimeTracestateSchema = z.string().max(512).refine(tracestateIsValid, "tracestate must follow the bounded W3C Trace Context grammar.");
408
+ const GatewayRuntimeTraceContextSchema = z.object({
409
+ traceparent: GatewayRuntimeTraceparentSchema,
410
+ tracestate: GatewayRuntimeTracestateSchema.optional()
411
+ }).strict();
412
+ //#endregion
413
+ //#region src/gateway-runtime-client/gateway-runtime-protocol.ts
414
+ const DEFAULT_GATEWAY_RUNTIME_FRAME_LIMITS = Object.freeze({
415
+ maxBufferedBytes: 1056768,
416
+ maxContentBytes: 1048576,
417
+ maxFramesPerChunk: 32,
418
+ maxHeaderBytes: 8192
419
+ });
420
+ const headerDelimiter = new Uint8Array([
421
+ 13,
422
+ 10,
423
+ 13,
424
+ 10
425
+ ]);
426
+ const strictUtf8Decoder = new TextDecoder("utf-8", { fatal: true });
427
+ const utf8Encoder = new TextEncoder();
428
+ var GatewayRuntimeProtocolError = class extends Error {
429
+ code;
430
+ constructor(code, message) {
431
+ super(message);
432
+ this.name = "GatewayRuntimeProtocolError";
433
+ this.code = code;
434
+ }
435
+ };
436
+ function protocolError(code, message) {
437
+ return new GatewayRuntimeProtocolError(code, message);
438
+ }
439
+ function assertPositiveLimit(value, fieldName) {
440
+ if (!Number.isSafeInteger(value) || value <= 0) throw new Error(`${fieldName} must be a positive safe integer.`);
441
+ }
442
+ function resolveFrameLimits(overrides) {
443
+ const limits = {
444
+ ...DEFAULT_GATEWAY_RUNTIME_FRAME_LIMITS,
445
+ ...overrides
446
+ };
447
+ assertPositiveLimit(limits.maxBufferedBytes, "maxBufferedBytes");
448
+ assertPositiveLimit(limits.maxContentBytes, "maxContentBytes");
449
+ assertPositiveLimit(limits.maxFramesPerChunk, "maxFramesPerChunk");
450
+ assertPositiveLimit(limits.maxHeaderBytes, "maxHeaderBytes");
451
+ return Object.freeze(limits);
452
+ }
453
+ function concatenateBytes(left, right) {
454
+ if (left.byteLength === 0) return new Uint8Array(right);
455
+ if (right.byteLength === 0) return new Uint8Array(left);
456
+ const combinedBytes = new Uint8Array(left.byteLength + right.byteLength);
457
+ combinedBytes.set(left, 0);
458
+ combinedBytes.set(right, left.byteLength);
459
+ return combinedBytes;
460
+ }
461
+ function findHeaderDelimiter(bytes) {
462
+ outer: for (let offset = 0; offset <= bytes.byteLength - headerDelimiter.byteLength; offset += 1) {
463
+ for (let delimiterOffset = 0; delimiterOffset < headerDelimiter.byteLength; delimiterOffset += 1) if (bytes[offset + delimiterOffset] !== headerDelimiter[delimiterOffset]) continue outer;
464
+ return offset;
465
+ }
466
+ return -1;
467
+ }
468
+ function decodeUtf8(bytes, code) {
469
+ try {
470
+ return strictUtf8Decoder.decode(bytes);
471
+ } catch {
472
+ throw protocolError(code, "Gateway runtime frame contains invalid UTF-8.");
473
+ }
474
+ }
475
+ function parseContentLength(headerBytes) {
476
+ const headerLines = decodeUtf8(headerBytes, "MALFORMED_HEADER").split("\r\n");
477
+ let contentLengthText;
478
+ for (const headerLine of headerLines) {
479
+ const delimiterIndex = headerLine.indexOf(":");
480
+ if (delimiterIndex <= 0) throw protocolError("MALFORMED_HEADER", "Gateway runtime frame header is malformed.");
481
+ const headerName = headerLine.slice(0, delimiterIndex).trim().toLowerCase();
482
+ if (headerName !== "content-length") throw protocolError("UNKNOWN_HEADER", `Gateway runtime frame header '${headerName}' is unknown.`);
483
+ if (contentLengthText !== void 0) throw protocolError("DUPLICATE_CONTENT_LENGTH", "Gateway runtime frame contains duplicate Content-Length headers.");
484
+ contentLengthText = headerLine.slice(delimiterIndex + 1).trim();
485
+ }
486
+ if (contentLengthText === void 0 || contentLengthText.length === 0) throw protocolError("MALFORMED_HEADER", "Gateway runtime frame is missing Content-Length.");
487
+ if (contentLengthText.startsWith("-")) throw protocolError("NEGATIVE_CONTENT_LENGTH", "Content-Length must not be negative.");
488
+ if (!/^\d+$/u.test(contentLengthText)) throw protocolError("NON_DECIMAL_CONTENT_LENGTH", "Content-Length must contain decimal digits.");
489
+ const contentLengthBigInt = BigInt(contentLengthText);
490
+ if (contentLengthBigInt > BigInt(Number.MAX_SAFE_INTEGER)) throw protocolError("UNSAFE_CONTENT_LENGTH", "Content-Length exceeds the safe integer range.");
491
+ return Number(contentLengthBigInt);
492
+ }
493
+ function isJsonObject(value) {
494
+ return typeof value === "object" && value !== null && !Array.isArray(value);
495
+ }
496
+ function hasSupportedJsonRpcVersion(value) {
497
+ return value.jsonrpc === "2.0";
498
+ }
499
+ function jsonRpcIdIsValid(value) {
500
+ return typeof value === "string" || typeof value === "number" && Number.isSafeInteger(value) || value === null;
501
+ }
502
+ function jsonRpcParamsAreValid(value) {
503
+ return Array.isArray(value) || isJsonObject(value);
504
+ }
505
+ function hasOnlyKeys(record, allowedKeys) {
506
+ return Object.keys(record).every((key) => allowedKeys.has(key));
507
+ }
508
+ function validateJsonRpcErrorObject(value) {
509
+ if (!isJsonObject(value)) throw protocolError("INVALID_JSON_RPC_ENVELOPE", "JSON-RPC error object is invalid.");
510
+ if (!hasOnlyKeys(value, new Set([
511
+ "code",
512
+ "data",
513
+ "message"
514
+ ]))) throw protocolError("UNKNOWN_JSON_RPC_FIELD", "JSON-RPC error object has an unknown field.");
515
+ if (!Number.isSafeInteger(value.code) || typeof value.message !== "string") throw protocolError("INVALID_JSON_RPC_ENVELOPE", "JSON-RPC error object is invalid.");
516
+ }
517
+ function validateJsonRpcEnvelope(value) {
518
+ if (Array.isArray(value)) throw protocolError("JSON_RPC_BATCH_UNSUPPORTED", "JSON-RPC batches are not supported.");
519
+ if (!isJsonObject(value)) throw protocolError("INVALID_JSON_RPC_ENVELOPE", "JSON-RPC messages must be objects.");
520
+ if (!hasSupportedJsonRpcVersion(value)) throw protocolError("UNSUPPORTED_JSON_RPC_VERSION", "Gateway runtime requires JSON-RPC version 2.0.");
521
+ if (Object.hasOwn(value, "method")) {
522
+ if (!hasOnlyKeys(value, new Set([
523
+ "id",
524
+ "jsonrpc",
525
+ "method",
526
+ "params"
527
+ ]))) throw protocolError("UNKNOWN_JSON_RPC_FIELD", "JSON-RPC request has an unknown field.");
528
+ if (typeof value.method !== "string" || value.method.length === 0 || Object.hasOwn(value, "id") && !jsonRpcIdIsValid(value.id) || Object.hasOwn(value, "params") && !jsonRpcParamsAreValid(value.params)) throw protocolError("INVALID_JSON_RPC_ENVELOPE", "JSON-RPC request envelope is invalid.");
529
+ return value;
530
+ }
531
+ const hasResult = Object.hasOwn(value, "result");
532
+ const hasError = Object.hasOwn(value, "error");
533
+ if (!hasOnlyKeys(value, new Set([
534
+ "error",
535
+ "id",
536
+ "jsonrpc",
537
+ "result"
538
+ ]))) throw protocolError("UNKNOWN_JSON_RPC_FIELD", "JSON-RPC response has an unknown field.");
539
+ if (!Object.hasOwn(value, "id") || !jsonRpcIdIsValid(value.id) || hasResult === hasError) throw protocolError("INVALID_JSON_RPC_ENVELOPE", "JSON-RPC response envelope is invalid.");
540
+ if (hasError) validateJsonRpcErrorObject(value.error);
541
+ return value;
542
+ }
543
+ function parseFrameBody(bodyBytes) {
544
+ const bodyText = decodeUtf8(bodyBytes, "INVALID_UTF8");
545
+ let parsedBody;
546
+ try {
547
+ parsedBody = JSON.parse(bodyText);
548
+ } catch {
549
+ throw protocolError("INVALID_JSON", "Gateway runtime frame body is not valid JSON.");
550
+ }
551
+ return validateJsonRpcEnvelope(parsedBody);
552
+ }
553
+ var GatewayRuntimeFrameDecoder = class {
554
+ #limits;
555
+ #buffer = new Uint8Array(0);
556
+ #pendingFrameBody;
557
+ #terminalError;
558
+ constructor(limitOverrides = {}) {
559
+ this.#limits = resolveFrameLimits(limitOverrides);
560
+ }
561
+ get bufferedByteLength() {
562
+ return this.#buffer.byteLength;
563
+ }
564
+ #fail(error) {
565
+ this.#terminalError ??= error;
566
+ throw this.#terminalError;
567
+ }
568
+ push(chunk) {
569
+ if (this.#terminalError !== void 0) throw this.#terminalError;
570
+ if (chunk.byteLength > this.#limits.maxBufferedBytes - this.#buffer.byteLength) this.#fail(protocolError("BUFFER_LIMIT_EXCEEDED", "Gateway runtime decoder input exceeds its buffer limit."));
571
+ let workingBuffer = concatenateBytes(this.#buffer, chunk);
572
+ let pendingFrameBody = this.#pendingFrameBody;
573
+ const decodedMessages = [];
574
+ try {
575
+ while (workingBuffer.byteLength > 0) {
576
+ if (pendingFrameBody === void 0) {
577
+ const headerDelimiterOffset = findHeaderDelimiter(workingBuffer);
578
+ if (headerDelimiterOffset < 0) {
579
+ if (workingBuffer.byteLength > this.#limits.maxHeaderBytes) this.#fail(protocolError("HEADER_TOO_LARGE", "Gateway runtime frame header exceeds its limit."));
580
+ if (workingBuffer.byteLength > this.#limits.maxBufferedBytes) this.#fail(protocolError("BUFFER_LIMIT_EXCEEDED", "Gateway runtime decoder buffer is full."));
581
+ break;
582
+ }
583
+ if (headerDelimiterOffset > this.#limits.maxHeaderBytes) this.#fail(protocolError("HEADER_TOO_LARGE", "Gateway runtime frame header exceeds its limit."));
584
+ const bodyStartOffset = headerDelimiterOffset + headerDelimiter.byteLength;
585
+ const contentLength = parseContentLength(workingBuffer.subarray(0, headerDelimiterOffset));
586
+ if (contentLength > this.#limits.maxContentBytes) this.#fail(protocolError("CONTENT_TOO_LARGE", "Gateway runtime frame body exceeds its limit."));
587
+ if (bodyStartOffset + contentLength > this.#limits.maxBufferedBytes) this.#fail(protocolError("CONTENT_LENGTH_OVERFLOW", "Gateway runtime frame cannot fit within the decoder buffer limit."));
588
+ pendingFrameBody = {
589
+ bodyStartOffset,
590
+ contentLength
591
+ };
592
+ }
593
+ const bodyEndOffset = pendingFrameBody.bodyStartOffset + pendingFrameBody.contentLength;
594
+ if (workingBuffer.byteLength < bodyEndOffset) break;
595
+ if (decodedMessages.length >= this.#limits.maxFramesPerChunk) this.#fail(protocolError("FRAME_LIMIT_EXCEEDED", "Gateway runtime chunk contains too many complete frames."));
596
+ decodedMessages.push(parseFrameBody(workingBuffer.subarray(pendingFrameBody.bodyStartOffset, bodyEndOffset)));
597
+ workingBuffer = workingBuffer.slice(bodyEndOffset);
598
+ pendingFrameBody = void 0;
599
+ }
600
+ } catch (error) {
601
+ if (error instanceof GatewayRuntimeProtocolError) this.#fail(error);
602
+ throw error;
603
+ }
604
+ this.#buffer = workingBuffer;
605
+ this.#pendingFrameBody = pendingFrameBody;
606
+ return decodedMessages;
607
+ }
608
+ finish() {
609
+ if (this.#terminalError !== void 0) throw this.#terminalError;
610
+ if (this.#buffer.byteLength === 0) return;
611
+ if (this.#pendingFrameBody !== void 0) this.#fail(protocolError("INCOMPLETE_FRAME_BODY", "Gateway runtime frame body ended early."));
612
+ const code = new TextDecoder().decode(this.#buffer).includes("\r\n") ? "MISSING_HEADER_DELIMITER" : "INCOMPLETE_FRAME_HEADER";
613
+ this.#fail(protocolError(code, "Gateway runtime frame header ended early."));
614
+ }
615
+ };
616
+ function encodeGatewayRuntimeFrame(message, limitOverrides = {}) {
617
+ validateJsonRpcEnvelope(message);
618
+ const limits = resolveFrameLimits(limitOverrides);
619
+ let serializedMessage;
620
+ try {
621
+ serializedMessage = JSON.stringify(message);
622
+ } catch {
623
+ throw protocolError("INVALID_JSON_RPC_ENVELOPE", "JSON-RPC message is not serializable.");
624
+ }
625
+ if (serializedMessage === void 0) throw protocolError("INVALID_JSON_RPC_ENVELOPE", "JSON-RPC message is not serializable.");
626
+ validateJsonRpcEnvelope(JSON.parse(serializedMessage));
627
+ const bodyBytes = utf8Encoder.encode(serializedMessage);
628
+ if (bodyBytes.byteLength > limits.maxContentBytes) throw protocolError("CONTENT_TOO_LARGE", "Gateway runtime frame body exceeds its limit.");
629
+ const headerBytes = utf8Encoder.encode(`Content-Length: ${bodyBytes.byteLength}\r\n\r\n`);
630
+ if (headerBytes.byteLength - headerDelimiter.byteLength > limits.maxHeaderBytes) throw protocolError("HEADER_TOO_LARGE", "Gateway runtime frame header exceeds its limit.");
631
+ if (headerBytes.byteLength + bodyBytes.byteLength > limits.maxBufferedBytes) throw protocolError("CONTENT_LENGTH_OVERFLOW", "Gateway runtime frame cannot fit within the buffer limit.");
632
+ return concatenateBytes(headerBytes, bodyBytes);
633
+ }
634
+ //#endregion
635
+ //#region src/gateway-runtime-client/node-gateway-runtime-transport.ts
636
+ const GATEWAY_RUNTIME_REQUEST_CANCEL_NOTIFICATION_METHOD = "notifications/cancelled";
637
+ var NodeGatewayRuntimeTransportError = class extends Error {
638
+ code;
639
+ constructor(code, message, options = {}) {
640
+ super(message, options);
641
+ this.name = "NodeGatewayRuntimeTransportError";
642
+ this.code = code;
643
+ }
644
+ };
645
+ var GatewayRuntimeRemoteError = class extends Error {
646
+ code;
647
+ data;
648
+ constructor(code, message, data) {
649
+ super(message);
650
+ this.name = "GatewayRuntimeRemoteError";
651
+ this.code = code;
652
+ this.data = data;
653
+ }
654
+ };
655
+ function isRecord$1(value) {
656
+ return typeof value === "object" && value !== null && !Array.isArray(value);
657
+ }
658
+ function nodeErrorCode(error) {
659
+ return isRecord$1(error) && typeof error["code"] === "string" ? error["code"] : void 0;
660
+ }
661
+ function assertPositiveSafeInteger$1(value, fieldName) {
662
+ if (!Number.isSafeInteger(value) || value <= 0) throw new Error(`${fieldName} must be a positive safe integer.`);
663
+ }
664
+ function createRemoteError(errorObject) {
665
+ if (!isRecord$1(errorObject) || !Number.isSafeInteger(errorObject["code"]) || typeof errorObject["message"] !== "string") return new GatewayRuntimeRemoteError("invalid-remote-error", "Gateway runtime returned an invalid JSON-RPC error.");
666
+ return new GatewayRuntimeRemoteError(String(errorObject["code"]), errorObject["message"], errorObject["data"]);
667
+ }
668
+ var NodeGatewayRuntimeConnection = class {
669
+ #decoder;
670
+ #frameLimits;
671
+ #maxPendingRequests;
672
+ #discardedRequestIds = /* @__PURE__ */ new Set();
673
+ #pendingRequests = /* @__PURE__ */ new Map();
674
+ #socket;
675
+ #closed = false;
676
+ #nextRequestId = 1;
677
+ #pendingWrite = Promise.resolve();
678
+ constructor(options) {
679
+ this.#decoder = new GatewayRuntimeFrameDecoder(options.frameLimits);
680
+ this.#frameLimits = options.frameLimits;
681
+ this.#maxPendingRequests = options.maxPendingRequests;
682
+ this.#socket = options.socket;
683
+ this.#socket.on("data", (chunk) => this.#receiveChunk(chunk));
684
+ this.#socket.once("close", () => {
685
+ this.#failConnection(new NodeGatewayRuntimeTransportError("connection-closed", "Gateway runtime connection closed."));
686
+ });
687
+ this.#socket.once("error", (error) => {
688
+ this.#failConnection(new NodeGatewayRuntimeTransportError("connection-failed", "Gateway runtime connection failed.", { cause: error }));
689
+ });
690
+ }
691
+ #failConnection(error) {
692
+ if (this.#closed) return;
693
+ this.#closed = true;
694
+ for (const pendingRequest of this.#pendingRequests.values()) pendingRequest.reject(error);
695
+ this.#pendingRequests.clear();
696
+ this.#discardedRequestIds.clear();
697
+ if (!this.#socket.destroyed) this.#socket.destroy();
698
+ }
699
+ #receiveChunk(chunk) {
700
+ if (this.#closed) return;
701
+ let messages;
702
+ try {
703
+ messages = this.#decoder.push(chunk);
704
+ } catch (error) {
705
+ this.#failConnection(new NodeGatewayRuntimeTransportError("protocol-failed", "Gateway runtime response framing failed.", { cause: error }));
706
+ return;
707
+ }
708
+ for (const message of messages) this.#receiveMessage(message);
709
+ }
710
+ #receiveMessage(message) {
711
+ if (!Object.hasOwn(message, "id") || Object.hasOwn(message, "method")) {
712
+ this.#failConnection(new NodeGatewayRuntimeTransportError("unexpected-message", "Gateway runtime client received an unexpected request or notification."));
713
+ return;
714
+ }
715
+ const requestId = message["id"];
716
+ if (typeof requestId !== "number" || !Number.isSafeInteger(requestId)) {
717
+ this.#failConnection(new NodeGatewayRuntimeTransportError("unexpected-message", "Gateway runtime response id is not a pending integer request id."));
718
+ return;
719
+ }
720
+ const pendingRequest = this.#pendingRequests.get(requestId);
721
+ if (pendingRequest === void 0) {
722
+ if (this.#discardedRequestIds.delete(requestId)) return;
723
+ this.#failConnection(new NodeGatewayRuntimeTransportError("unexpected-message", "Gateway runtime response does not match a pending request."));
724
+ return;
725
+ }
726
+ this.#pendingRequests.delete(requestId);
727
+ if (Object.hasOwn(message, "error")) {
728
+ pendingRequest.reject(createRemoteError(message["error"]));
729
+ return;
730
+ }
731
+ pendingRequest.resolve(message["result"]);
732
+ }
733
+ #allocateRequestId() {
734
+ if (!Number.isSafeInteger(this.#nextRequestId)) throw new NodeGatewayRuntimeTransportError("request-id-exhausted", "Gateway runtime request id space is exhausted.");
735
+ const requestId = this.#nextRequestId;
736
+ this.#nextRequestId += 1;
737
+ return requestId;
738
+ }
739
+ async #writeFrameImmediately(frame) {
740
+ if (this.#closed) throw new NodeGatewayRuntimeTransportError("connection-closed", "Gateway runtime connection is closed.");
741
+ await new Promise((resolve, reject) => {
742
+ const onError = (error) => {
743
+ cleanup();
744
+ reject(new NodeGatewayRuntimeTransportError("request-write-failed", "Gateway runtime request write failed.", { cause: error }));
745
+ };
746
+ const cleanup = () => {
747
+ this.#socket.off("error", onError);
748
+ };
749
+ this.#socket.once("error", onError);
750
+ this.#socket.write(frame, (error) => {
751
+ if (error !== void 0 && error !== null) {
752
+ onError(error);
753
+ return;
754
+ }
755
+ cleanup();
756
+ resolve();
757
+ });
758
+ });
759
+ if (!this.#socket.writableNeedDrain) return;
760
+ await new Promise((resolve, reject) => {
761
+ const onDrain = () => {
762
+ cleanup();
763
+ resolve();
764
+ };
765
+ const onError = (error) => {
766
+ cleanup();
767
+ reject(error);
768
+ };
769
+ const cleanup = () => {
770
+ this.#socket.off("drain", onDrain);
771
+ this.#socket.off("error", onError);
772
+ };
773
+ this.#socket.once("drain", onDrain);
774
+ this.#socket.once("error", onError);
775
+ });
776
+ }
777
+ async #writeFrame(frame) {
778
+ const write = this.#pendingWrite.then(async () => await this.#writeFrameImmediately(frame));
779
+ this.#pendingWrite = write.catch(() => void 0);
780
+ await write;
781
+ }
782
+ async handshake(attachment, options = {}) {
783
+ const decision = await this.request("managed-plugin.handshake", attachment, options);
784
+ if (isRecord$1(decision) && decision["kind"] === "accepted") return;
785
+ const rejectionCode = isRecord$1(decision) ? decision["code"] : void 0;
786
+ throw new GatewayRuntimeRemoteError(typeof rejectionCode === "string" ? rejectionCode : "invalid-handshake", "Gateway runtime rejected the managed-plugin attachment.", decision);
787
+ }
788
+ async request(method, params, options = {}) {
789
+ if (options.signal?.aborted === true) throw new NodeGatewayRuntimeTransportError("request-aborted", "Gateway runtime request was aborted before dispatch.", { cause: options.signal.reason });
790
+ if (this.#pendingRequests.size >= this.#maxPendingRequests) throw new NodeGatewayRuntimeTransportError("pending-request-limit-exceeded", "Gateway runtime pending request limit was reached.");
791
+ const requestId = this.#allocateRequestId();
792
+ const frame = encodeGatewayRuntimeFrame({
793
+ id: requestId,
794
+ jsonrpc: "2.0",
795
+ method,
796
+ params
797
+ }, this.#frameLimits);
798
+ return await new Promise((resolve, reject) => {
799
+ let settled = false;
800
+ const settleRejected = (error) => {
801
+ if (settled) return;
802
+ settled = true;
803
+ options.signal?.removeEventListener("abort", onAbort);
804
+ this.#pendingRequests.delete(requestId);
805
+ reject(error);
806
+ };
807
+ const settleResolved = (result) => {
808
+ if (settled) return;
809
+ settled = true;
810
+ options.signal?.removeEventListener("abort", onAbort);
811
+ resolve(result);
812
+ };
813
+ const onAbort = () => {
814
+ if (settled) return;
815
+ if (this.#discardedRequestIds.size >= this.#maxPendingRequests) {
816
+ const capacityError = new NodeGatewayRuntimeTransportError("pending-request-limit-exceeded", "Gateway runtime discarded-request limit was reached.");
817
+ settleRejected(capacityError);
818
+ this.#failConnection(capacityError);
819
+ return;
820
+ }
821
+ this.#discardedRequestIds.add(requestId);
822
+ settleRejected(new NodeGatewayRuntimeTransportError("request-aborted", "Gateway runtime request was aborted locally.", { cause: options.signal?.reason }));
823
+ const cancellationFrame = encodeGatewayRuntimeFrame({
824
+ jsonrpc: "2.0",
825
+ method: GATEWAY_RUNTIME_REQUEST_CANCEL_NOTIFICATION_METHOD,
826
+ params: { requestId }
827
+ }, this.#frameLimits);
828
+ this.#writeFrame(cancellationFrame).catch((error) => {
829
+ this.#failConnection(error instanceof Error ? error : new NodeGatewayRuntimeTransportError("request-write-failed", "Gateway runtime cancellation write failed."));
830
+ });
831
+ };
832
+ this.#pendingRequests.set(requestId, {
833
+ reject: settleRejected,
834
+ resolve: settleResolved
835
+ });
836
+ options.signal?.addEventListener("abort", onAbort, { once: true });
837
+ this.#writeFrame(frame).catch(settleRejected);
838
+ });
839
+ }
840
+ async close() {
841
+ if (this.#closed) return;
842
+ this.#failConnection(new NodeGatewayRuntimeTransportError("connection-closed", "Gateway runtime connection closed locally."));
843
+ }
844
+ };
845
+ function createNodeGatewayRuntimeTransportFactory(options = {}) {
846
+ const frameLimits = options.frameLimits ?? {};
847
+ const maxPendingRequests = options.maxPendingRequests ?? 64;
848
+ assertPositiveSafeInteger$1(maxPendingRequests, "maxPendingRequests");
849
+ return { connect: async ({ signal, socketPath }) => {
850
+ const socket = net.createConnection({
851
+ path: socketPath,
852
+ signal
853
+ });
854
+ await new Promise((resolve, reject) => {
855
+ const onConnect = () => {
856
+ cleanup();
857
+ resolve();
858
+ };
859
+ const onError = (error) => {
860
+ cleanup();
861
+ const errorCode = nodeErrorCode(error);
862
+ if (errorCode === "ENOENT" || errorCode === "ECONNREFUSED") {
863
+ reject(new GatewayRuntimeStartupUnavailableError(errorCode === "ENOENT" ? "socket-absent" : "socket-refused", { cause: error }));
864
+ return;
865
+ }
866
+ reject(new NodeGatewayRuntimeTransportError("connection-failed", "Gateway runtime UDS connection failed.", { cause: error }));
867
+ };
868
+ const cleanup = () => {
869
+ socket.off("connect", onConnect);
870
+ socket.off("error", onError);
871
+ };
872
+ socket.once("connect", onConnect);
873
+ socket.once("error", onError);
874
+ });
875
+ return new NodeGatewayRuntimeConnection({
876
+ frameLimits,
877
+ maxPendingRequests,
878
+ socket
879
+ });
880
+ } };
881
+ }
882
+ //#endregion
883
+ //#region src/gateway-runtime-client/gateway-runtime-flow-control.ts
884
+ const ZERO_RETAINED_BYTES = Object.freeze({
885
+ kernelSendBufferedBytes: 0,
886
+ nodeWritableBufferedBytes: 0,
887
+ parserBufferedBytes: 0,
888
+ sourceOwnedApplicationChunkBytes: 0
889
+ });
890
+ function assertNonnegativeSafeInteger(value, fieldName) {
891
+ if (!Number.isSafeInteger(value) || value < 0) throw new Error(`${fieldName} must be a nonnegative safe integer.`);
892
+ }
893
+ function assertPositiveSafeInteger(value, fieldName) {
894
+ if (!Number.isSafeInteger(value) || value <= 0) throw new Error(`${fieldName} must be a positive safe integer.`);
895
+ }
896
+ function assertUnreachable(value) {
897
+ throw new Error(`Unhandled Gateway runtime flow-control event: ${JSON.stringify(value)}`);
898
+ }
899
+ function assertWithinLimit(value, limit, measurementName) {
900
+ assertNonnegativeSafeInteger(value, measurementName);
901
+ if (value > limit) throw new Error(`${measurementName} exceeds its configured retained-byte limit.`);
902
+ }
903
+ function highWaterMeasurements(current, previousHighWater) {
904
+ return Object.freeze({
905
+ kernelSendBufferedBytes: Math.max(current.kernelSendBufferedBytes, previousHighWater.kernelSendBufferedBytes),
906
+ nodeWritableBufferedBytes: Math.max(current.nodeWritableBufferedBytes, previousHighWater.nodeWritableBufferedBytes),
907
+ parserBufferedBytes: Math.max(current.parserBufferedBytes, previousHighWater.parserBufferedBytes),
908
+ sourceOwnedApplicationChunkBytes: Math.max(current.sourceOwnedApplicationChunkBytes, previousHighWater.sourceOwnedApplicationChunkBytes)
909
+ });
910
+ }
911
+ function transitionChunkSender(state, effects = []) {
912
+ return {
913
+ effects,
914
+ state
915
+ };
916
+ }
917
+ function createGatewayRuntimeChunkSenderState(retainedByteLimits) {
918
+ assertPositiveSafeInteger(retainedByteLimits.maxKernelSendBufferedBytes, "maxKernelSendBufferedBytes");
919
+ assertPositiveSafeInteger(retainedByteLimits.maxNodeWritableBufferedBytes, "maxNodeWritableBufferedBytes");
920
+ assertPositiveSafeInteger(retainedByteLimits.maxParserBufferedBytes, "maxParserBufferedBytes");
921
+ assertPositiveSafeInteger(retainedByteLimits.maxSourceOwnedApplicationChunkBytes, "maxSourceOwnedApplicationChunkBytes");
922
+ return {
923
+ currentRetainedBytes: ZERO_RETAINED_BYTES,
924
+ highWaterRetainedBytes: ZERO_RETAINED_BYTES,
925
+ ownedApplicationChunkCount: 0,
926
+ phase: "idle",
927
+ retainedByteLimits: Object.freeze({ ...retainedByteLimits })
928
+ };
929
+ }
930
+ function reduceGatewayRuntimeChunkSenderState(state, event) {
931
+ if (event.kind === "disconnected") {
932
+ if (state.phase === "disconnected") return transitionChunkSender(state);
933
+ const currentRetainedBytes = Object.freeze({
934
+ ...state.currentRetainedBytes,
935
+ sourceOwnedApplicationChunkBytes: 0
936
+ });
937
+ return transitionChunkSender({
938
+ ...state,
939
+ currentRetainedBytes,
940
+ ownedApplicationChunkCount: 0,
941
+ phase: "disconnected"
942
+ });
943
+ }
944
+ if (state.phase === "disconnected") return transitionChunkSender(state);
945
+ switch (event.kind) {
946
+ case "start":
947
+ if (state.phase !== "idle") throw new Error("Gateway runtime chunk sender can only start from idle.");
948
+ return transitionChunkSender({
949
+ ...state,
950
+ phase: "reading-source"
951
+ }, [{ kind: "read-source" }]);
952
+ case "source-chunk-read": {
953
+ if (state.phase !== "reading-source" || state.ownedApplicationChunkCount !== 0) throw new Error("Gateway runtime chunk sender already owns an application chunk.");
954
+ assertWithinLimit(event.chunk.byteLength, state.retainedByteLimits.maxSourceOwnedApplicationChunkBytes, "source-owned application chunk");
955
+ const currentRetainedBytes = Object.freeze({
956
+ ...state.currentRetainedBytes,
957
+ sourceOwnedApplicationChunkBytes: event.chunk.byteLength
958
+ });
959
+ return transitionChunkSender({
960
+ ...state,
961
+ currentRetainedBytes,
962
+ highWaterRetainedBytes: highWaterMeasurements(currentRetainedBytes, state.highWaterRetainedBytes),
963
+ ownedApplicationChunkCount: 1,
964
+ phase: "writing-chunk"
965
+ }, [{
966
+ chunk: event.chunk,
967
+ kind: "encode-and-write"
968
+ }]);
969
+ }
970
+ case "write-result": {
971
+ if (state.phase !== "writing-chunk" || state.ownedApplicationChunkCount !== 1) throw new Error("Gateway runtime chunk sender has no application chunk being written.");
972
+ const currentRetainedBytes = Object.freeze({
973
+ ...state.currentRetainedBytes,
974
+ sourceOwnedApplicationChunkBytes: 0
975
+ });
976
+ return transitionChunkSender({
977
+ ...state,
978
+ currentRetainedBytes,
979
+ ownedApplicationChunkCount: 0,
980
+ phase: event.writableWithoutDrain ? "reading-source" : "waiting-for-drain"
981
+ }, event.writableWithoutDrain ? [{ kind: "read-source" }] : []);
982
+ }
983
+ case "drain":
984
+ if (state.phase !== "waiting-for-drain") throw new Error("Gateway runtime chunk sender received drain while not waiting for drain.");
985
+ return transitionChunkSender({
986
+ ...state,
987
+ phase: "reading-source"
988
+ }, [{ kind: "read-source" }]);
989
+ case "retained-bytes-observed": {
990
+ assertWithinLimit(event.kernelSendBufferedBytes, state.retainedByteLimits.maxKernelSendBufferedBytes, "kernel send buffer");
991
+ assertWithinLimit(event.nodeWritableBufferedBytes, state.retainedByteLimits.maxNodeWritableBufferedBytes, "Node writable buffer");
992
+ assertWithinLimit(event.parserBufferedBytes, state.retainedByteLimits.maxParserBufferedBytes, "parser buffer");
993
+ const currentRetainedBytes = Object.freeze({
994
+ kernelSendBufferedBytes: event.kernelSendBufferedBytes,
995
+ nodeWritableBufferedBytes: event.nodeWritableBufferedBytes,
996
+ parserBufferedBytes: event.parserBufferedBytes,
997
+ sourceOwnedApplicationChunkBytes: state.currentRetainedBytes.sourceOwnedApplicationChunkBytes
998
+ });
999
+ return transitionChunkSender({
1000
+ ...state,
1001
+ currentRetainedBytes,
1002
+ highWaterRetainedBytes: highWaterMeasurements(currentRetainedBytes, state.highWaterRetainedBytes)
1003
+ });
1004
+ }
1005
+ }
1006
+ return assertUnreachable(event);
1007
+ }
1008
+ function transitionClientRead(state, effects = []) {
1009
+ return {
1010
+ effects,
1011
+ state
1012
+ };
1013
+ }
1014
+ function enterDiscardDraining(state) {
1015
+ return transitionClientRead({
1016
+ ...state,
1017
+ phase: "discard-draining"
1018
+ }, [{ kind: "cancel-pause-deadline" }, { kind: "resume-socket-read" }]);
1019
+ }
1020
+ function createGatewayRuntimeClientReadState(options) {
1021
+ assertPositiveSafeInteger(options.pauseDeadlineMilliseconds, "pauseDeadlineMilliseconds");
1022
+ if (options.streamId.length === 0) throw new Error("streamId must not be empty.");
1023
+ return {
1024
+ pauseDeadlineMilliseconds: options.pauseDeadlineMilliseconds,
1025
+ phase: "flowing",
1026
+ streamId: options.streamId
1027
+ };
1028
+ }
1029
+ function reduceGatewayRuntimeClientReadState(state, event) {
1030
+ switch (event.kind) {
1031
+ case "downstream-pressure":
1032
+ if (state.phase !== "flowing") throw new Error("Gateway runtime client read can only pause while flowing.");
1033
+ return transitionClientRead({
1034
+ ...state,
1035
+ phase: "downstream-paused"
1036
+ }, [{ kind: "pause-socket-read" }, {
1037
+ afterMilliseconds: state.pauseDeadlineMilliseconds,
1038
+ kind: "schedule-pause-deadline"
1039
+ }]);
1040
+ case "downstream-resumed":
1041
+ if (state.phase !== "downstream-paused") throw new Error("Gateway runtime client read can only resume from a downstream pause.");
1042
+ return transitionClientRead({
1043
+ ...state,
1044
+ phase: "flowing"
1045
+ }, [{ kind: "cancel-pause-deadline" }, { kind: "resume-socket-read" }]);
1046
+ case "pause-deadline-expired":
1047
+ if (state.phase !== "downstream-paused") throw new Error("Gateway runtime pause deadline expired without a downstream pause.");
1048
+ return enterDiscardDraining(state);
1049
+ case "attachment-retired":
1050
+ case "local-cancel":
1051
+ case "local-close":
1052
+ if (state.phase === "downstream-paused") return enterDiscardDraining(state);
1053
+ if (state.phase === "completed") return transitionClientRead(state);
1054
+ return transitionClientRead({
1055
+ ...state,
1056
+ phase: "discard-draining"
1057
+ });
1058
+ case "frame-received": {
1059
+ if (state.phase === "completed") return transitionClientRead(state);
1060
+ const frame = event.frame;
1061
+ if (state.phase === "discard-draining" && frame.kind === "stream-data" && frame.streamId === state.streamId) return transitionClientRead(state, [{
1062
+ kind: "discard-stream-data",
1063
+ streamId: state.streamId
1064
+ }]);
1065
+ if (state.phase === "discard-draining" && frame.kind === "authoritative-stream-terminal" && frame.streamId === state.streamId) return transitionClientRead({
1066
+ ...state,
1067
+ phase: "completed"
1068
+ }, [{
1069
+ frame,
1070
+ kind: "forward-frame"
1071
+ }, {
1072
+ kind: "complete-stream",
1073
+ outcome: frame.outcome,
1074
+ streamId: state.streamId
1075
+ }]);
1076
+ return transitionClientRead(state, [{
1077
+ frame,
1078
+ kind: "forward-frame"
1079
+ }]);
1080
+ }
1081
+ }
1082
+ return assertUnreachable(event);
1083
+ }
1084
+ //#endregion
1085
+ //#region src/gateway-runtime-client/gateway-runtime-socket-read-flow.ts
1086
+ const defaultPauseDeadlineScheduler = { schedule: ({ afterMilliseconds, onDeadline }) => {
1087
+ const timeout = setTimeout(onDeadline, afterMilliseconds);
1088
+ return { cancel: () => clearTimeout(timeout) };
1089
+ } };
1090
+ /** Apply bounded per-stream discard state to one globally paused UDS reader. */
1091
+ var GatewayRuntimeSocketReadFlow = class {
1092
+ #deadlineScheduler;
1093
+ #forwardFrame;
1094
+ #onStreamCompleted;
1095
+ #pauseDeadlineMilliseconds;
1096
+ #socket;
1097
+ #streamStates = /* @__PURE__ */ new Map();
1098
+ #activePauseDeadline;
1099
+ #pausedStreamId;
1100
+ constructor(options) {
1101
+ this.#deadlineScheduler = options.deadlineScheduler ?? defaultPauseDeadlineScheduler;
1102
+ this.#forwardFrame = options.forwardFrame;
1103
+ this.#onStreamCompleted = options.onStreamCompleted;
1104
+ this.#pauseDeadlineMilliseconds = options.pauseDeadlineMilliseconds;
1105
+ this.#socket = options.socket;
1106
+ }
1107
+ #createStreamState(streamId) {
1108
+ return createGatewayRuntimeClientReadState({
1109
+ pauseDeadlineMilliseconds: this.#pauseDeadlineMilliseconds,
1110
+ streamId
1111
+ });
1112
+ }
1113
+ #applyEffects(streamId, effects) {
1114
+ for (const effect of effects) switch (effect.kind) {
1115
+ case "pause-socket-read":
1116
+ this.#socket.pause();
1117
+ this.#pausedStreamId = streamId;
1118
+ break;
1119
+ case "resume-socket-read":
1120
+ this.#socket.resume();
1121
+ if (this.#pausedStreamId === streamId) this.#pausedStreamId = void 0;
1122
+ break;
1123
+ case "schedule-pause-deadline":
1124
+ this.#activePauseDeadline = this.#deadlineScheduler.schedule({
1125
+ afterMilliseconds: effect.afterMilliseconds,
1126
+ onDeadline: () => this.#transitionStream(streamId, { kind: "pause-deadline-expired" })
1127
+ });
1128
+ break;
1129
+ case "cancel-pause-deadline":
1130
+ this.#activePauseDeadline?.cancel();
1131
+ this.#activePauseDeadline = void 0;
1132
+ break;
1133
+ case "discard-stream-data": break;
1134
+ case "forward-frame":
1135
+ this.#forwardFrame(effect.frame);
1136
+ break;
1137
+ case "complete-stream":
1138
+ this.#onStreamCompleted({
1139
+ outcome: effect.outcome,
1140
+ streamId: effect.streamId
1141
+ });
1142
+ break;
1143
+ }
1144
+ }
1145
+ #transitionStream(streamId, event) {
1146
+ const transition = reduceGatewayRuntimeClientReadState(this.#streamStates.get(streamId) ?? this.#createStreamState(streamId), event);
1147
+ this.#streamStates.set(streamId, transition.state);
1148
+ this.#applyEffects(streamId, transition.effects);
1149
+ if (transition.state.phase === "completed") this.#streamStates.delete(streamId);
1150
+ }
1151
+ applyDownstreamPressure(streamId) {
1152
+ if (this.#pausedStreamId !== void 0 && this.#pausedStreamId !== streamId) throw new Error(`Gateway runtime socket is already paused for stream '${this.#pausedStreamId}'.`);
1153
+ this.#transitionStream(streamId, { kind: "downstream-pressure" });
1154
+ }
1155
+ resumeDownstream(streamId) {
1156
+ this.#transitionStream(streamId, { kind: "downstream-resumed" });
1157
+ }
1158
+ cancelStream(streamId) {
1159
+ this.#transitionStream(streamId, { kind: "local-cancel" });
1160
+ }
1161
+ closeStream(streamId) {
1162
+ this.#transitionStream(streamId, { kind: "local-close" });
1163
+ }
1164
+ retireAttachment(streamId) {
1165
+ this.#transitionStream(streamId, { kind: "attachment-retired" });
1166
+ }
1167
+ receiveFrame(frame) {
1168
+ if (frame.kind === "control") {
1169
+ this.#forwardFrame(frame);
1170
+ return;
1171
+ }
1172
+ if (this.#streamStates.get(frame.streamId) === void 0) {
1173
+ this.#forwardFrame(frame);
1174
+ return;
1175
+ }
1176
+ this.#transitionStream(frame.streamId, {
1177
+ frame,
1178
+ kind: "frame-received"
1179
+ });
1180
+ }
1181
+ };
1182
+ //#endregion
1183
+ //#region src/gateway-runtime-client/index.ts
1184
+ const DEFAULT_GATEWAY_RUNTIME_SOCKET_PATH = "/run/agent-vm/gateway-runtime/managed-plugin.sock";
1185
+ var GatewayRuntimeClientError = class extends Error {
1186
+ code;
1187
+ constructor(code, message, options = {}) {
1188
+ super(message, options);
1189
+ this.name = "GatewayRuntimeClientError";
1190
+ this.code = code;
1191
+ }
1192
+ };
1193
+ function resolveStartupRetryPolicy(override) {
1194
+ const policy = {
1195
+ ...DEFAULT_GATEWAY_RUNTIME_STARTUP_RETRY_POLICY,
1196
+ ...override
1197
+ };
1198
+ if (!Number.isSafeInteger(policy.deadlineMs) || policy.deadlineMs <= 0 || !Number.isSafeInteger(policy.intervalMs) || policy.intervalMs <= 0 || !Number.isSafeInteger(policy.maxAttempts) || policy.maxAttempts <= 0 || policy.deadlineMs > 6e4 || policy.maxAttempts > 1e3 || policy.intervalMs > policy.deadlineMs) throw new GatewayRuntimeClientError("invalid-startup-retry-policy", "Gateway runtime startup retry policy must contain positive bounded integers.");
1199
+ return Object.freeze(policy);
1200
+ }
1201
+ function startupAbortedError(reason) {
1202
+ return new GatewayRuntimeClientError("startup-aborted", "Gateway runtime startup was aborted.", reason instanceof Error ? { cause: reason } : {});
1203
+ }
1204
+ function startupRetryExhaustedError(props) {
1205
+ return new GatewayRuntimeClientError("startup-retry-exhausted", `Gateway runtime startup retry was exhausted after ${props.attempts} attempts.`, props.cause === void 0 ? {} : { cause: props.cause });
1206
+ }
1207
+ const publicAuthorityFieldNames = [
1208
+ "allowedOperationGroups",
1209
+ "authority",
1210
+ "operationGroups",
1211
+ "principal",
1212
+ "surface"
1213
+ ];
1214
+ function isRecord(value) {
1215
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1216
+ }
1217
+ function validateAttachmentMetadata(attachment) {
1218
+ if (!isRecord(attachment)) throw new GatewayRuntimeClientError("invalid-attachment", "Gateway runtime attachment metadata must be an object.");
1219
+ if (publicAuthorityFieldNames.some((fieldName) => Object.hasOwn(attachment, fieldName))) throw new GatewayRuntimeClientError("public-authority-injection", "Gateway runtime attachment metadata cannot carry server-derived authority.");
1220
+ const parsedAttachment = GatewayRuntimeAttachmentMetadataSchema.safeParse(attachment);
1221
+ if (!parsedAttachment.success) throw new GatewayRuntimeClientError("invalid-attachment", "Gateway runtime attachment metadata is invalid.", { cause: parsedAttachment.error });
1222
+ Object.freeze(parsedAttachment.data.configuredAgentIds);
1223
+ return Object.freeze(parsedAttachment.data);
1224
+ }
1225
+ function createGatewayRuntimeRequestParams(props) {
1226
+ return {
1227
+ publicRequest: props.publicRequest,
1228
+ trustedContext: GatewayRuntimeTrustedInvocationContextSchema.parse(props.trustedContext)
1229
+ };
1230
+ }
1231
+ function gatewayRuntimeRequestOptions(options) {
1232
+ return {
1233
+ ...options.signal === void 0 ? {} : { signal: options.signal },
1234
+ ...options.traceContext === void 0 ? {} : { traceContext: options.traceContext }
1235
+ };
1236
+ }
1237
+ var GatewayRuntimePortalOperations = class {
1238
+ #client;
1239
+ constructor(client) {
1240
+ this.#client = client;
1241
+ }
1242
+ async list(request, options) {
1243
+ const validatedRequest = PortalListRequestSchema.parse(request);
1244
+ const result = await this.#client.request("portal.list", createGatewayRuntimeRequestParams({
1245
+ publicRequest: validatedRequest,
1246
+ trustedContext: options.trustedContext
1247
+ }), gatewayRuntimeRequestOptions(options));
1248
+ return PortalListResultSchema.parse(result);
1249
+ }
1250
+ async search(request, options) {
1251
+ const validatedRequest = PortalSearchRequestSchema.parse(request);
1252
+ const result = await this.#client.request("portal.search", createGatewayRuntimeRequestParams({
1253
+ publicRequest: validatedRequest,
1254
+ trustedContext: options.trustedContext
1255
+ }), gatewayRuntimeRequestOptions(options));
1256
+ return PortalSearchResultSchema.parse(result);
1257
+ }
1258
+ async describe(request, options) {
1259
+ const validatedRequest = PortalDescribeRequestSchema.parse(request);
1260
+ const result = await this.#client.request("portal.describe", createGatewayRuntimeRequestParams({
1261
+ publicRequest: validatedRequest,
1262
+ trustedContext: options.trustedContext
1263
+ }), gatewayRuntimeRequestOptions(options));
1264
+ return PortalDescribeResultSchema.parse(result);
1265
+ }
1266
+ async call(request, options) {
1267
+ const validatedRequest = PortalCallRequestSchema.parse(request);
1268
+ const result = await this.#client.request("portal.call", createGatewayRuntimeRequestParams({
1269
+ publicRequest: validatedRequest,
1270
+ trustedContext: options.trustedContext
1271
+ }), gatewayRuntimeRequestOptions(options));
1272
+ return PortalCallResultSchema.parse(result);
1273
+ }
1274
+ };
1275
+ var GatewayRuntimeArtifactOperations = class {
1276
+ #client;
1277
+ constructor(client) {
1278
+ this.#client = client;
1279
+ }
1280
+ async read(request, options) {
1281
+ const validatedRequest = PortalArtifactReadRequestSchema.parse(request);
1282
+ const result = await this.#client.request("artifact.read", createGatewayRuntimeRequestParams({
1283
+ publicRequest: validatedRequest,
1284
+ trustedContext: options.trustedContext
1285
+ }), gatewayRuntimeRequestOptions(options));
1286
+ return PortalArtifactReadResultSchema.parse(result);
1287
+ }
1288
+ };
1289
+ /** Rich private-UDS client for one current managed-framework attachment. */
1290
+ var GatewayRuntimeClient = class {
1291
+ #attachment;
1292
+ #socketPath;
1293
+ #startupRetryPolicy;
1294
+ #startupRetryScheduler;
1295
+ #traceContextProvider;
1296
+ #transportFactory;
1297
+ #connection;
1298
+ #connecting = false;
1299
+ #handshakeComplete = false;
1300
+ artifacts;
1301
+ portal;
1302
+ sandbox;
1303
+ constructor(options) {
1304
+ this.#attachment = validateAttachmentMetadata(options.attachment);
1305
+ this.#socketPath = options.socketPath ?? "/run/agent-vm/gateway-runtime/managed-plugin.sock";
1306
+ this.#startupRetryPolicy = resolveStartupRetryPolicy(options.startupRetryPolicy);
1307
+ this.#startupRetryScheduler = options.startupRetryScheduler ?? defaultGatewayRuntimeStartupRetryScheduler;
1308
+ this.#traceContextProvider = options.traceContextProvider;
1309
+ this.#transportFactory = options.transportFactory ?? createNodeGatewayRuntimeTransportFactory();
1310
+ this.artifacts = new GatewayRuntimeArtifactOperations(this);
1311
+ this.portal = new GatewayRuntimePortalOperations(this);
1312
+ this.sandbox = Object.freeze(new GatewayRuntimeSandboxOperations(this));
1313
+ }
1314
+ async #connectOnce(props) {
1315
+ const remainingMs = Math.max(1, props.deadlineAtMs - this.#startupRetryScheduler.now());
1316
+ const attemptCancellation = new AbortController();
1317
+ let deadlineExpired = false;
1318
+ const deadline = setTimeout(() => {
1319
+ deadlineExpired = true;
1320
+ attemptCancellation.abort(/* @__PURE__ */ new Error("Gateway runtime startup deadline expired."));
1321
+ }, remainingMs);
1322
+ const abortAttempt = () => attemptCancellation.abort(props.signal.reason);
1323
+ props.signal.addEventListener("abort", abortAttempt, { once: true });
1324
+ if (props.signal.aborted) abortAttempt();
1325
+ let connection;
1326
+ try {
1327
+ connection = await this.#transportFactory.connect({
1328
+ signal: attemptCancellation.signal,
1329
+ socketPath: this.#socketPath
1330
+ });
1331
+ await connection.handshake(this.#attachment, { signal: attemptCancellation.signal });
1332
+ return connection;
1333
+ } catch (error) {
1334
+ if (connection !== void 0) await connection.close();
1335
+ if (props.signal.aborted) throw startupAbortedError(props.signal.reason);
1336
+ if (deadlineExpired) throw startupRetryExhaustedError({
1337
+ attempts: props.attemptNumber,
1338
+ ...error instanceof Error ? { cause: error } : {}
1339
+ });
1340
+ throw error;
1341
+ } finally {
1342
+ clearTimeout(deadline);
1343
+ props.signal.removeEventListener("abort", abortAttempt);
1344
+ }
1345
+ }
1346
+ async #connectWithStartupRetry(props) {
1347
+ const attemptNumber = props.attemptsCompleted + 1;
1348
+ let unavailableError;
1349
+ try {
1350
+ return await this.#connectOnce({
1351
+ attemptNumber,
1352
+ deadlineAtMs: props.deadlineAtMs,
1353
+ signal: props.signal
1354
+ });
1355
+ } catch (error) {
1356
+ if (error instanceof GatewayRuntimeClientError) throw error;
1357
+ if (!(error instanceof GatewayRuntimeStartupUnavailableError)) throw error;
1358
+ unavailableError = error;
1359
+ }
1360
+ const remainingMs = props.deadlineAtMs - this.#startupRetryScheduler.now();
1361
+ if (attemptNumber >= this.#startupRetryPolicy.maxAttempts || remainingMs <= 0) throw startupRetryExhaustedError({
1362
+ attempts: attemptNumber,
1363
+ cause: unavailableError
1364
+ });
1365
+ try {
1366
+ await this.#startupRetryScheduler.wait(Math.min(this.#startupRetryPolicy.intervalMs, remainingMs), props.signal);
1367
+ } catch (error) {
1368
+ if (props.signal.aborted) throw startupAbortedError(props.signal.reason);
1369
+ throw error;
1370
+ }
1371
+ if (this.#startupRetryScheduler.now() >= props.deadlineAtMs) throw startupRetryExhaustedError({
1372
+ attempts: attemptNumber,
1373
+ cause: unavailableError
1374
+ });
1375
+ return await this.#connectWithStartupRetry({
1376
+ attemptsCompleted: attemptNumber,
1377
+ deadlineAtMs: props.deadlineAtMs,
1378
+ signal: props.signal
1379
+ });
1380
+ }
1381
+ async connect(options = {}) {
1382
+ if (this.#connection !== void 0 || this.#connecting) throw new GatewayRuntimeClientError("already-connected", "Gateway runtime client already has a connection.");
1383
+ const signal = options.signal ?? new AbortController().signal;
1384
+ if (signal.aborted) throw startupAbortedError(signal.reason);
1385
+ this.#connecting = true;
1386
+ const deadlineAtMs = this.#startupRetryScheduler.now() + this.#startupRetryPolicy.deadlineMs;
1387
+ try {
1388
+ const connection = await this.#connectWithStartupRetry({
1389
+ attemptsCompleted: 0,
1390
+ deadlineAtMs,
1391
+ signal
1392
+ });
1393
+ this.#connection = connection;
1394
+ this.#handshakeComplete = true;
1395
+ } finally {
1396
+ this.#connecting = false;
1397
+ }
1398
+ }
1399
+ async disconnect() {
1400
+ const connection = this.#connection;
1401
+ this.#connection = void 0;
1402
+ this.#handshakeComplete = false;
1403
+ if (connection !== void 0) await connection.close();
1404
+ }
1405
+ async reconnect(options = {}) {
1406
+ if (this.#connecting) throw new GatewayRuntimeClientError("already-connected", "Gateway runtime client already has a connection attempt in progress.");
1407
+ this.#connecting = true;
1408
+ try {
1409
+ await this.disconnect();
1410
+ const signal = options.signal ?? new AbortController().signal;
1411
+ if (signal.aborted) throw startupAbortedError(signal.reason);
1412
+ const connection = await this.#connectOnce({
1413
+ attemptNumber: 1,
1414
+ deadlineAtMs: this.#startupRetryScheduler.now() + this.#startupRetryPolicy.deadlineMs,
1415
+ signal
1416
+ });
1417
+ this.#connection = connection;
1418
+ this.#handshakeComplete = true;
1419
+ } finally {
1420
+ this.#connecting = false;
1421
+ }
1422
+ }
1423
+ async request(method, params, options = {}) {
1424
+ if (!this.#handshakeComplete || this.#connection === void 0) throw new GatewayRuntimeClientError("handshake-required", "Gateway runtime attachment handshake must complete before method calls.");
1425
+ const transportOptions = options.signal === void 0 ? {} : { signal: options.signal };
1426
+ const providedTraceContext = options.traceContext ?? this.#traceContextProvider?.();
1427
+ if (providedTraceContext === void 0) return await this.#connection.request(method, params, transportOptions);
1428
+ if (!isRecord(params)) throw new GatewayRuntimeClientError("invalid-request-metadata", "Gateway runtime trace context requires object request parameters.");
1429
+ const traceContext = GatewayRuntimeTraceContextSchema.parse(providedTraceContext);
1430
+ return await this.#connection.request(method, {
1431
+ ...params,
1432
+ traceContext
1433
+ }, transportOptions);
1434
+ }
1435
+ };
1436
+ //#endregion
1437
+ export { DEFAULT_GATEWAY_RUNTIME_FRAME_LIMITS, DEFAULT_GATEWAY_RUNTIME_SOCKET_PATH, DEFAULT_GATEWAY_RUNTIME_STARTUP_RETRY_POLICY, GATEWAY_RUNTIME_REQUEST_CANCEL_NOTIFICATION_METHOD, GATEWAY_RUNTIME_TRACEPARENT_MAX_LENGTH, GATEWAY_RUNTIME_TRACESTATE_MAX_LENGTH, GATEWAY_RUNTIME_TRACESTATE_MAX_MEMBERS, GatewayRuntimeClient, GatewayRuntimeClientError, GatewayRuntimeFrameDecoder, GatewayRuntimeProtocolError, GatewayRuntimeRemoteError, GatewayRuntimeSandboxEnvironmentOperations, GatewayRuntimeSandboxExecutionOperations, GatewayRuntimeSandboxFilesystemOperations, GatewayRuntimeSandboxOperations, GatewayRuntimeSandboxProcessOperations, GatewayRuntimeSandboxRetainedResultOperations, GatewayRuntimeSandboxStreamOperations, GatewayRuntimeSandboxTerminalOperations, GatewayRuntimeSocketReadFlow, GatewayRuntimeStartupUnavailableError, GatewayRuntimeTraceContextSchema, GatewayRuntimeTrustedInvocationContextSchema, GatewayRuntimeTrustedInvocationCorrelationSchema, GatewayRuntimeTrustedInvocationPrincipalSchema, GatewayRuntimeTrustedInvocationRequesterSchema, NodeGatewayRuntimeTransportError, createGatewayRuntimeChunkSenderState, createGatewayRuntimeClientReadState, createNodeGatewayRuntimeTransportFactory, encodeGatewayRuntimeFrame, reduceGatewayRuntimeChunkSenderState, reduceGatewayRuntimeClientReadState };
1438
+
1439
+ //# sourceMappingURL=index.js.map