@query-farm/vgi 0.50.1 → 0.52.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/README.md +45 -3
  2. package/dist/client-entry.js +833 -775
  3. package/dist/client-entry.js.map +10 -10
  4. package/dist/functions/aggregate.d.ts +25 -21
  5. package/dist/functions/execution-cache.d.ts +11 -0
  6. package/dist/functions/storage-blobs.d.ts +173 -0
  7. package/dist/functions/storage-cf-do.d.ts +50 -0
  8. package/dist/functions/storage-seal.d.ts +27 -0
  9. package/dist/functions/storage.d.ts +71 -1
  10. package/dist/functions/table-buffering.d.ts +30 -0
  11. package/dist/functions/table.d.ts +6 -1
  12. package/dist/generated/vgi-client.d.ts +7 -1
  13. package/dist/generated/vgi-protocol-schemas.d.ts +10 -9
  14. package/dist/generated/vgi-protocol-types.d.ts +244 -2
  15. package/dist/generated/vgi-service.d.ts +1 -1
  16. package/dist/hosted.d.ts +117 -0
  17. package/dist/http/blob-vendor.d.ts +33 -0
  18. package/dist/http/fetch.d.ts +60 -2
  19. package/dist/http/hosted-auth.d.ts +45 -0
  20. package/dist/index.core.d.ts +11 -3
  21. package/dist/index.js +8661 -6677
  22. package/dist/index.js.map +52 -34
  23. package/dist/protocol/arguments-ref.d.ts +107 -0
  24. package/dist/protocol/dispatch.d.ts +12 -2
  25. package/dist/protocol/handlers/aggregate.d.ts +1 -1
  26. package/dist/protocol/handlers/catalog/shared.d.ts +10 -0
  27. package/dist/protocol/handlers/function.d.ts +23 -0
  28. package/dist/protocol/handlers/table-buffering.d.ts +1 -1
  29. package/dist/protocol/serialize.d.ts +1 -1
  30. package/dist/protocol/serializers/bind.d.ts +27 -1
  31. package/dist/protocol/serializers/cardinality.d.ts +1 -1
  32. package/dist/protocol/serializers/splits.d.ts +7 -0
  33. package/dist/protocol/state-serializer.d.ts +8 -7
  34. package/dist/protocol/stream-init.d.ts +17 -0
  35. package/dist/protocol/types.d.ts +32 -0
  36. package/dist/secrets/lookups.d.ts +31 -0
  37. package/dist/serve-entry.d.ts +41 -6
  38. package/dist/serve-entry.js +8531 -6302
  39. package/dist/serve-entry.js.map +52 -35
  40. package/dist/worker-cf-entry.d.ts +5 -0
  41. package/dist/worker-cf-entry.js +7191 -4990
  42. package/dist/worker-cf-entry.js.map +59 -41
  43. package/package.json +5 -4
  44. package/src/functions/aggregate.ts +101 -152
  45. package/src/functions/copy-from.ts +2 -2
  46. package/src/functions/execution-cache.ts +59 -0
  47. package/src/functions/storage-blobs.ts +654 -0
  48. package/src/functions/storage-cf-do.ts +176 -22
  49. package/src/functions/storage-seal.ts +208 -0
  50. package/src/functions/storage.ts +174 -8
  51. package/src/functions/table-buffering.ts +104 -18
  52. package/src/functions/table-in-out.ts +3 -1
  53. package/src/functions/table.ts +12 -8
  54. package/src/generated/vgi-client.ts +9 -2
  55. package/src/generated/vgi-protocol-schemas.ts +115 -107
  56. package/src/generated/vgi-protocol-types.ts +640 -3
  57. package/src/generated/vgi-service.ts +2 -2
  58. package/src/hosted.ts +254 -0
  59. package/src/http/blob-vendor.ts +80 -0
  60. package/src/http/fetch.ts +179 -8
  61. package/src/http/hosted-auth.ts +326 -0
  62. package/src/index.core.ts +66 -1
  63. package/src/protocol/arguments-ref.ts +260 -0
  64. package/src/protocol/dispatch.ts +15 -4
  65. package/src/protocol/handlers/aggregate.ts +123 -82
  66. package/src/protocol/handlers/catalog/shared.ts +20 -0
  67. package/src/protocol/handlers/function.ts +135 -59
  68. package/src/protocol/handlers/table-buffering.ts +49 -32
  69. package/src/protocol/serialize.ts +3 -0
  70. package/src/protocol/serializers/bind.ts +96 -69
  71. package/src/protocol/serializers/cardinality.ts +4 -7
  72. package/src/protocol/serializers/init.ts +5 -11
  73. package/src/protocol/serializers/splits.ts +31 -4
  74. package/src/protocol/state-serializer.ts +27 -39
  75. package/src/protocol/stream-init.ts +87 -0
  76. package/src/protocol/types.ts +33 -0
  77. package/src/secrets/lookups.ts +53 -0
  78. package/src/serve-entry.ts +138 -11
  79. package/src/worker-cf-entry.ts +33 -0
  80. package/src/worker.ts +25 -0
  81. package/dist/protocol/carried-init-request.d.ts +0 -28
  82. package/dist/util/zstd-sync.d.ts +0 -7
  83. package/src/protocol/carried-init-request.ts +0 -139
  84. package/src/util/zstd-sync.ts +0 -50
@@ -0,0 +1,53 @@
1
+ // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
+
3
+ /**
4
+ * The secret-lookup fields an `onBind` may return to ask DuckDB for secrets.
5
+ *
6
+ * The three lists are parallel: entry `i` requests a secret of type
7
+ * `lookupSecretTypes[i]`, optionally narrowed by `lookupScopes[i]` and
8
+ * `lookupNames[i]` (`""` or a missing entry = unset). A lookup without a type
9
+ * cannot be expressed, so `lookupSecretTypes` drives the request.
10
+ */
11
+ export interface SecretLookupFields {
12
+ lookupSecretTypes?: string[];
13
+ lookupScopes?: string[];
14
+ lookupNames?: string[];
15
+ }
16
+
17
+ /**
18
+ * Check an `onBind` result's secret-lookup lists before they go on the wire.
19
+ *
20
+ * The extension reads one lookup per `lookupSecretTypes` entry, so a scope or
21
+ * name with no type at the same index was silently dropped: returning
22
+ * `lookupNames: ["prod"]` alone requested nothing and the secret arrived
23
+ * missing. That is now a bind error naming the fix.
24
+ *
25
+ * @param fnName function name, for the error message.
26
+ * @param result the `onBind` return value.
27
+ * @returns the three lists for `BindResponse`.
28
+ * @throws Error when `lookupScopes` or `lookupNames` is longer than `lookupSecretTypes`.
29
+ */
30
+ export function secretLookupWire(
31
+ fnName: string,
32
+ result: SecretLookupFields,
33
+ ): { lookup_secret_types: string[] | undefined; lookup_scopes: string[] | undefined; lookup_names: string[] | undefined } {
34
+ const types = result.lookupSecretTypes ?? [];
35
+ for (const [key, list] of [
36
+ ["lookupScopes", result.lookupScopes],
37
+ ["lookupNames", result.lookupNames],
38
+ ] as const) {
39
+ if (list && list.length > types.length) {
40
+ throw new Error(
41
+ `${fnName}: onBind returned ${list.length} ${key} but ${types.length} lookupSecretTypes. ` +
42
+ "The lists are parallel (entry i is lookupSecretTypes[i] narrowed by lookupScopes[i] / " +
43
+ "lookupNames[i]); every lookup needs a secret type, so the extra entries would request nothing. " +
44
+ 'Return e.g. { lookupSecretTypes: ["my_type"], lookupScopes: [""], lookupNames: ["prod"] }.',
45
+ );
46
+ }
47
+ }
48
+ return {
49
+ lookup_secret_types: result.lookupSecretTypes,
50
+ lookup_scopes: result.lookupScopes,
51
+ lookup_names: result.lookupNames,
52
+ };
53
+ }
@@ -33,10 +33,36 @@ import {
33
33
  type PeerResolutionOptions,
34
34
  } from "@query-farm/vgi-rpc";
35
35
  import { createVgiFetch } from "./http/fetch.js";
36
+ import { blobVendorHttpConfigFromEnv, type BlobVendorEnv, type BlobVendorHttpConfig } from "./http/blob-vendor.js";
36
37
  import { grantKeysFromArgv, type HostingOptions } from "./rpc-server.js";
38
+ import {
39
+ checkHostedEnvironment,
40
+ checkHostedSigningKey,
41
+ hostedModeEnabled,
42
+ OrchardHostedConfigError,
43
+ resolveHostedConfig,
44
+ type HostedConfig,
45
+ } from "./hosted.js";
46
+
47
+ // Orchard hosted mode (VGI_ORCHARD_HOSTED=1): Pass-only HTTP serving. See
48
+ // docs/orchard-hosted.md.
49
+ export {
50
+ HOSTED_ENV,
51
+ HOSTED_CHALLENGE,
52
+ HOSTED_AUTH_DOMAIN,
53
+ OrchardHostedConfigError,
54
+ hostedModeEnabled,
55
+ resolveHostedConfig,
56
+ orchardHostedFromEnv,
57
+ checkHostedEnvironment,
58
+ checkHostedSigningKey,
59
+ type HostedConfig,
60
+ type HostedEnv,
61
+ } from "./hosted.js";
62
+ export { hostedAuthenticate, isHostedAuthenticate, type HostedVerifierDeps } from "./http/hosted-auth.js";
37
63
 
38
64
  /** Environment variables `serveVgiWorker` reads. Injectable for testing. */
39
- export interface ServeEnv {
65
+ export interface ServeEnv extends BlobVendorEnv {
40
66
  PORT?: string;
41
67
  VGI_SIGNING_KEY?: string;
42
68
  VGI_TOKEN_TTL?: string;
@@ -49,10 +75,21 @@ export interface ServeEnv {
49
75
  VGI_RPC_GRANT_MAX_TTL_SECONDS?: string;
50
76
  /** Principals allowed to call `introspect_token`, comma-separated. */
51
77
  VGI_INTROSPECT_PRINCIPALS?: string;
78
+ /** `1` turns on Orchard hosted mode (see `docs/orchard-hosted.md`). */
79
+ VGI_ORCHARD_HOSTED?: string;
80
+ /** Hosted mode: the Front Desk issuer, exactly one value. */
81
+ VGI_JWT_ISSUER?: string;
82
+ /** Hosted mode: the canonical Desk Address, exactly one value. */
83
+ VGI_JWT_AUDIENCE?: string;
84
+ /** Hosted mode: the Front Desk's JWKS URL, exactly one value. */
85
+ VGI_JWT_JWKS_URI?: string;
86
+ /** Hosted mode: accepted Pass algorithms (default ES256; never none/HS*). */
87
+ VGI_JWT_ALGORITHMS?: string;
52
88
  }
53
89
 
54
90
  export const DEFAULT_PORT = 8787;
55
- export const DEFAULT_TOKEN_TTL = 3600;
91
+ /** Default state-token TTL: 6 h (vgi-rpc STATE_REF_V1.md, protocol 3.4). */
92
+ export const DEFAULT_TOKEN_TTL = 21600;
56
93
  /** Bytes of HMAC key `createHttpHandler` expects; 64 hex characters. */
57
94
  export const SIGNING_KEY_BYTES = 32;
58
95
 
@@ -71,7 +108,14 @@ export interface IrohHttpBridgeOptions {
71
108
  peerResolutionContext?: ((request: Request) => PeerResolutionOptions | Promise<PeerResolutionOptions>) | undefined;
72
109
  }
73
110
 
74
- export interface ServeVgiWorkerOptions extends HostingOptions {
111
+ /**
112
+ * The external-location fields ({@link BlobVendorHttpConfig}) default to the
113
+ * blob-vendor environment (`VGI_BLOB_VENDOR_URL`, `VGI_BLOB_VENDOR_TOKEN`,
114
+ * `VGI_RPC_EXTERNALIZE_THRESHOLD_BYTES`, `VGI_RPC_EXTERNAL_COMPRESSION`,
115
+ * `VGI_RPC_MAX_REQUEST_BYTES`, `VGI_RPC_MAX_UPLOAD_BYTES`); an explicit option
116
+ * wins.
117
+ */
118
+ export interface ServeVgiWorkerOptions extends HostingOptions, BlobVendorHttpConfig {
75
119
  /** Short worker name shown on the landing page, e.g. "ishares". */
76
120
  name: string;
77
121
  /** One-line description of what the worker serves. */
@@ -89,14 +133,18 @@ export interface ServeVgiWorkerOptions extends HostingOptions {
89
133
  port?: number | undefined;
90
134
  /** Bind address. Iroh bridge mode defaults to loopback; otherwise Bun's default. */
91
135
  hostname?: string | undefined;
92
- /** Overrides `$VGI_SIGNING_KEY`. 32 bytes. */
93
- signingKey?: Uint8Array | undefined;
136
+ /**
137
+ * Overrides `$VGI_SIGNING_KEY`: 32 bytes, or the same 64-hex-character string
138
+ * the env var takes. A string's UTF-8 bytes are also the storage-seal ikm
139
+ * (see {@link resolveStorageSealKey}); bytes are used unchanged.
140
+ */
141
+ signingKey?: Uint8Array | string | undefined;
94
142
  /**
95
143
  * Optional root key for secret ATTACH options (encrypted inside
96
144
  * `attach_opaque_data` for `attachOptions()`). Defaults to the signing key.
97
145
  */
98
146
  attachSecretKey?: Uint8Array | undefined;
99
- /** Overrides `$VGI_TOKEN_TTL` (default 3600 seconds). */
147
+ /** Overrides `$VGI_TOKEN_TTL` (default 21600 seconds, 6 h). */
100
148
  tokenTtl?: number | undefined;
101
149
  /** Overrides `$CORS_ORIGINS` (default "*"). Pass `null` to disable CORS. */
102
150
  corsOrigins?: string | null | undefined;
@@ -194,6 +242,27 @@ export function resolveSigningKey(
194
242
  return crypto.getRandomValues(new Uint8Array(SIGNING_KEY_BYTES));
195
243
  }
196
244
 
245
+ /**
246
+ * The ikm for sealed framework storage payloads (cross-SDK v1): the UTF-8 bytes
247
+ * of the signing key *as configured* -- an explicit string option, else the raw
248
+ * `$VGI_SIGNING_KEY` value, unmodified, exactly as vgi-python and vgi-java read
249
+ * it -- so one deployment key derives one payload key in every SDK. Explicit
250
+ * bytes are used unchanged; a generated key's bytes are used as-is (it is
251
+ * process-local anyway). Only the storage seal uses this; state tokens and
252
+ * opaque-data envelopes keep the hex-decoded key.
253
+ */
254
+ export function resolveStorageSealKey(
255
+ explicit: Uint8Array | string | undefined,
256
+ env: ServeEnv,
257
+ resolvedSigningKey: Uint8Array,
258
+ ): Uint8Array {
259
+ if (typeof explicit === "string") return new TextEncoder().encode(explicit);
260
+ if (explicit) return explicit;
261
+ const raw = env.VGI_SIGNING_KEY;
262
+ if (raw && raw.trim()) return new TextEncoder().encode(raw);
263
+ return resolvedSigningKey;
264
+ }
265
+
197
266
  function resolvePort(explicit: number | undefined, env: ServeEnv): number {
198
267
  if (explicit !== undefined) return explicit;
199
268
  const raw = env.PORT?.trim();
@@ -228,7 +297,16 @@ export function createVgiWorkerFetch(
228
297
  opts: ServeVgiWorkerOptions,
229
298
  ): (req: Request) => Promise<Response> {
230
299
  const env = opts.env ?? (process.env as ServeEnv);
231
- const signingKey = resolveSigningKey(opts.signingKey, env);
300
+ const argv = opts.argv ?? process.argv.slice(2);
301
+ // Orchard hosted mode is checked first, before the signing key is parsed or
302
+ // grant keys are read, so every misconfiguration surfaces as a hosted-mode
303
+ // refusal rather than whatever error the generic path would raise.
304
+ const orchardHosted = resolveServeHostedMode(opts, env, argv);
305
+ const signingKey = resolveSigningKey(
306
+ typeof opts.signingKey === "string" ? parseSigningKeyHex(opts.signingKey) : opts.signingKey,
307
+ env,
308
+ );
309
+ const storageSealKey = resolveStorageSealKey(opts.signingKey, env, signingKey);
232
310
  // Explicit option or `$VGI_SIGNING_KEY`: a key that survives a restart.
233
311
  // The generated fallback never enables attach tickets.
234
312
  const signingKeyConfigured = opts.signingKey !== undefined || !!env.VGI_SIGNING_KEY?.trim();
@@ -245,12 +323,20 @@ export function createVgiWorkerFetch(
245
323
  );
246
324
  }
247
325
  const trustedProxyAddresses = bridge?.trustedProxyAddresses ?? ["127.0.0.1"];
326
+ const blobVendor = blobVendorHttpConfigFromEnv(env);
248
327
 
249
328
  return createVgiFetch({
329
+ externalLocation: opts.externalLocation ?? blobVendor.externalLocation,
330
+ uploadUrlProvider: opts.uploadUrlProvider ?? blobVendor.uploadUrlProvider,
331
+ maxRequestBytes: opts.maxRequestBytes ?? blobVendor.maxRequestBytes,
332
+ maxUploadBytes: opts.maxUploadBytes ?? blobVendor.maxUploadBytes,
250
333
  protocol: { registry: opts.registry, catalogInterface: opts.catalogInterface, attachSecretKey: opts.attachSecretKey },
251
334
  signingKey,
252
335
  signingKeyConfigured,
336
+ storageSealKey,
253
337
  tokenTtl,
338
+ cursorRule: "error",
339
+ env: env as Readonly<Record<string, string | undefined>>,
254
340
  prefix: opts.prefix ?? "",
255
341
  serverId: opts.serverId ?? opts.name,
256
342
  corsOrigins,
@@ -269,14 +355,44 @@ export function createVgiWorkerFetch(
269
355
  mintGrant: opts.mintGrant,
270
356
  introspectPrincipals: opts.introspectPrincipals,
271
357
  maxAuthAge: opts.maxAuthAge,
272
- grantKeys:
273
- opts.grantKeys !== undefined
358
+ grantKeys: orchardHosted
359
+ ? undefined
360
+ : opts.grantKeys !== undefined
274
361
  ? opts.grantKeys
275
- : (grantKeysFromArgv(opts.argv ?? process.argv.slice(2), env as Record<string, string | undefined>) ??
362
+ : (grantKeysFromArgv(argv, env as Record<string, string | undefined>) ??
276
363
  GrantKeys.fromEnv(env as Record<string, string | undefined>)),
364
+ orchardHosted,
277
365
  });
278
366
  }
279
367
 
368
+ /**
369
+ * Orchard hosted mode for {@link createVgiWorkerFetch}: `undefined` when
370
+ * `VGI_ORCHARD_HOSTED` is off, else the validated configuration once every
371
+ * check has passed. Throws {@link OrchardHostedConfigError}.
372
+ */
373
+ function resolveServeHostedMode(
374
+ opts: ServeVgiWorkerOptions,
375
+ env: ServeEnv,
376
+ argv: readonly string[],
377
+ ): HostedConfig | undefined {
378
+ const hostedEnv = env as Record<string, string | undefined>;
379
+ if (!hostedModeEnabled(hostedEnv)) return undefined;
380
+ checkHostedSigningKey(hostedEnv, opts.signingKey);
381
+ checkHostedEnvironment(hostedEnv);
382
+ if (opts.grantKeys !== undefined && opts.grantKeys !== null) {
383
+ throw new OrchardHostedConfigError("sealed-grant keys (grantKeys) are configured.");
384
+ }
385
+ if (argv.some((a) => a === "--grant-key" || a.startsWith("--grant-key="))) {
386
+ throw new OrchardHostedConfigError("sealed-grant keys (--grant-key) are configured.");
387
+ }
388
+ if (opts.irohBridge) {
389
+ throw new OrchardHostedConfigError("an Iroh HTTP bridge (peer identity) is configured; hosted workers accept Passes only.");
390
+ }
391
+ // authenticate / resolveToken / mintGrant / peer identity are refused by
392
+ // createVgiFetch, which sees the same options.
393
+ return resolveHostedConfig(hostedEnv);
394
+ }
395
+
280
396
  /**
281
397
  * Serve a VGI worker over HTTP on Bun and return the running server.
282
398
  *
@@ -315,7 +431,18 @@ export function serveVgiWorker(opts: ServeVgiWorkerOptions): VgiHttpServer {
315
431
  },
316
432
  }
317
433
  : opts.irohBridge;
318
- const fetch = createVgiWorkerFetch({ ...opts, irohBridge: bridge });
434
+ let fetch: (req: Request) => Promise<Response>;
435
+ try {
436
+ fetch = createVgiWorkerFetch({ ...opts, irohBridge: bridge });
437
+ } catch (error) {
438
+ // A hosted-mode refusal is an operator error with one fix, not a crash:
439
+ // say what is wrong and exit non-zero, without a stack trace.
440
+ if (error instanceof OrchardHostedConfigError) {
441
+ process.stderr.write(`Error: ${error.message}\n`);
442
+ process.exit(1);
443
+ }
444
+ throw error;
445
+ }
319
446
  server = runtime.serve({ port, hostname, fetch });
320
447
 
321
448
  if (!opts.quiet) {
@@ -15,7 +15,40 @@
15
15
 
16
16
  export { createVgiFetch } from "./http/fetch.js";
17
17
  export type { VgiFetchOptions } from "./http/fetch.js";
18
+ // Blob vendor: spread blobVendorHttpConfigFromEnv(env) into createVgiFetch, and
19
+ // wrap the Durable Object storage with wrapStorageFromEnv(cfDo, { maxValueBytes:
20
+ // CF_DO_MAX_VALUE_BYTES, env }) before setStorage, so both read the Worker's env.
21
+ export { blobVendorHttpConfigFromEnv } from "./http/blob-vendor.js";
22
+ export type { BlobVendorEnv, BlobVendorHttpConfig } from "./http/blob-vendor.js";
23
+ export {
24
+ FunctionStorageCfDo,
25
+ CF_DO_MAX_VALUE_BYTES,
26
+ ExternalizingStorage,
27
+ wrapStorageFromEnv,
28
+ setStorage,
29
+ StorageBlobError,
30
+ StorageBlobIntegrityError,
31
+ StorageBlobMissingError,
32
+ StorageEnvelopeError,
33
+ StorageValueTooLargeError,
34
+ } from "./index.core.js";
18
35
  export type { HostingOptions } from "./rpc-server.js";
36
+ // Orchard hosted mode (VGI_ORCHARD_HOSTED=1): Pass-only HTTP serving. See
37
+ // docs/orchard-hosted.md.
38
+ export {
39
+ HOSTED_ENV,
40
+ HOSTED_CHALLENGE,
41
+ HOSTED_AUTH_DOMAIN,
42
+ OrchardHostedConfigError,
43
+ hostedModeEnabled,
44
+ resolveHostedConfig,
45
+ orchardHostedFromEnv,
46
+ checkHostedEnvironment,
47
+ checkHostedSigningKey,
48
+ type HostedConfig,
49
+ type HostedEnv,
50
+ } from "./hosted.js";
51
+ export { hostedAuthenticate, isHostedAuthenticate, type HostedVerifierDeps } from "./http/hosted-auth.js";
19
52
  export {
20
53
  AuthUnavailableError,
21
54
  GrantKeys,
package/src/worker.ts CHANGED
@@ -19,6 +19,7 @@ import { schemaDescriptorPath, type CatalogDescriptor } from "./catalog/descript
19
19
  import type { CatalogInterface } from "./catalog/interface.js";
20
20
  import { ReadOnlyCatalogInterface } from "./catalog/read-only.js";
21
21
  import { checkReservedAttachOptions } from "./catalog/attach-option.js";
22
+ import { hostedModeEnabled, OrchardHostedConfigError, refuseNonHttpTransportInHostedMode } from "./hosted.js";
22
23
 
23
24
  /**
24
25
  * Startup/lifecycle tracing, off unless `VGI_DEBUG` is set to something other
@@ -71,6 +72,20 @@ function parseTcpSpec(spec: string, out: LauncherArgs): void {
71
72
  }
72
73
  }
73
74
 
75
+ /** The transport `run()` would serve for `argv`, as named in a refusal. */
76
+ function transportName(argv: readonly string[]): string {
77
+ let launcher: LauncherArgs;
78
+ try {
79
+ launcher = parseLauncherArgs(argv);
80
+ } catch {
81
+ return "requested";
82
+ }
83
+ if (launcher.irohRawUpstream) return "--iroh-raw-upstream";
84
+ if (launcher.unixPath !== undefined) return "--unix";
85
+ if (launcher.tcpPort !== undefined) return "--tcp";
86
+ return "stdio";
87
+ }
88
+
74
89
  function parseLauncherArgs(argv: readonly string[]): LauncherArgs {
75
90
  const out: LauncherArgs = { irohTrustedProxyAddresses: [], irohAuthenticate: true };
76
91
  for (let i = 0; i < argv.length; i++) {
@@ -193,6 +208,15 @@ export class Worker {
193
208
 
194
209
  run(argv: readonly string[] = process.argv.slice(2)): void {
195
210
  debug(() => `[worker] starting, pid=${process.pid}`);
211
+ // Orchard hosted mode serves HTTP only (serveVgiWorker); every transport
212
+ // run() offers -- stdio, --unix, --tcp, --iroh-raw-upstream -- carries no Pass.
213
+ try {
214
+ if (hostedModeEnabled()) refuseNonHttpTransportInHostedMode(transportName(argv));
215
+ } catch (err) {
216
+ if (!(err instanceof OrchardHostedConfigError)) throw err;
217
+ process.stderr.write(`Error: ${err.message}\n`);
218
+ process.exit(1);
219
+ }
196
220
  // Refuse to serve a catalog that declares the reserved `vgi_attach_ticket`
197
221
  // attach option, before anything is read off the transport.
198
222
  checkReservedAttachOptions(this._catalogInterface).then(
@@ -330,6 +354,7 @@ export class Worker {
330
354
  readable: ReadableStream<Uint8Array> | NodeJS.ReadableStream,
331
355
  writable?: number | import("node:net").Socket | import("@query-farm/vgi-rpc").ByteSink,
332
356
  ): Promise<void> {
357
+ refuseNonHttpTransportInHostedMode("byte-stream");
333
358
  await serveStreamRpc(this.buildServer(this.buildProtocol(), "stream"), omitUndefined({ readable, writable }));
334
359
  }
335
360
  }
@@ -1,28 +0,0 @@
1
- import type { InitRequest } from "./types.js";
2
- /** Pack an init request's IPC bytes for the cursor: `u8 codec | payload`. */
3
- export declare function packInitRequest(ipc: Uint8Array): Uint8Array;
4
- /** What a continuation needs from the carried init request. */
5
- export interface CarriedInitRequest {
6
- /**
7
- * The parsed request -- a fresh top-level object with a fresh `bind_call`
8
- * each call, so the per-turn assignments the dispatcher makes (split
9
- * payloads) never reach the shared parse. The nested values (Arrow
10
- * schemas and batches, arguments) are shared and must be treated as
11
- * read-only, as they always were.
12
- */
13
- request: InitRequest;
14
- /** The raw bind-call IPC bytes, which the split-token fingerprint hashes. */
15
- bindCallIpc: Uint8Array;
16
- }
17
- /**
18
- * Parse the init request a cursor carries (as packed by
19
- * {@link packInitRequest}), from the process memo when this stream's turns have
20
- * been here before.
21
- */
22
- export declare function parseCarriedInitRequest(packed: Uint8Array): CarriedInitRequest;
23
- /** Cumulative parse / memo-hit counts for this process (observability and tests). */
24
- export declare function carriedInitRequestStats(): {
25
- parses: number;
26
- hits: number;
27
- entries: number;
28
- };
@@ -1,7 +0,0 @@
1
- /** A synchronous zstd codec. */
2
- export interface ZstdSync {
3
- compress(data: Uint8Array): Uint8Array;
4
- decompress(data: Uint8Array): Uint8Array;
5
- }
6
- /** This runtime's synchronous zstd codec, or `null` when it has none. */
7
- export declare function zstdSync(): ZstdSync | null;
@@ -1,139 +0,0 @@
1
- // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
- // The init request an HTTP stream carries in its cursor: packed once, parsed
3
- // once per process.
4
- //
5
- // An HTTP stream has no memory between turns, so its cursor carries the whole
6
- // init request (~9 KB of Arrow IPC for a DuckDB scan: the bind call with its
7
- // arguments, settings and sealed attach, the output schema, the filter
8
- // snapshot) and every turn used to re-parse it: the IPC read, the scalar-dict
9
- // walk and the nested bind-call / schema / filter reads cost ~0.9 ms, the
10
- // largest VGI-side share of the ~4 ms a 1000-row turn took. The cursor is also
11
- // re-sealed and base64-encoded on every turn, so its size is paid twice per
12
- // turn in AEAD and base64 work, and twice again on the wire.
13
- //
14
- // - `packInitRequest` zstd-compresses the request once, at /init (~9 KB ->
15
- // ~2.6 KB), behind a one-byte codec tag. A runtime without synchronous zstd
16
- // stores it raw.
17
- // - `parseCarriedInitRequest` keeps a small per-process LRU from the packed
18
- // bytes to their parse. It is a pure memo of a pure function: the key is the
19
- // exact bytes (hash, then a full comparison), so a hit returns precisely
20
- // what parsing those bytes would -- and those bytes came out of a cursor the
21
- // worker sealed. Nothing principal-dependent is cached: the split tokens and
22
- // the sealed attach are still opened, under the caller, on every turn. A
23
- // miss (cold process, eviction, another replica's stream) parses as before,
24
- // so correctness never depends on a hit.
25
-
26
- import { deserializeBatch } from "../arrow/index.js";
27
- import { batchToScalarDict } from "../util/arrow/index.js";
28
- import { zstdSync } from "../util/zstd-sync.js";
29
- import { deserializeInitRequest } from "./serialize.js";
30
- import type { InitRequest } from "./types.js";
31
-
32
- const RAW = 0;
33
- const ZSTD = 1;
34
-
35
- /** Pack an init request's IPC bytes for the cursor: `u8 codec | payload`. */
36
- export function packInitRequest(ipc: Uint8Array): Uint8Array {
37
- const codec = zstdSync();
38
- const compressed = codec ? codec.compress(ipc) : null;
39
- const useZstd = compressed !== null && compressed.byteLength < ipc.byteLength;
40
- const payload = useZstd ? compressed! : ipc;
41
- const packed = new Uint8Array(payload.byteLength + 1);
42
- packed[0] = useZstd ? ZSTD : RAW;
43
- packed.set(payload, 1);
44
- return packed;
45
- }
46
-
47
- function unpackInitRequest(packed: Uint8Array): Uint8Array {
48
- if (packed.byteLength === 0) throw new Error("state token carries no init request");
49
- switch (packed[0]) {
50
- case RAW:
51
- return packed.slice(1);
52
- case ZSTD: {
53
- const codec = zstdSync();
54
- if (!codec) {
55
- throw new Error(
56
- "state token carries a zstd-compressed init request, and this runtime has no synchronous zstd " +
57
- "(it was minted by a worker running under Bun or Node >= 22.15 with the same signing key)",
58
- );
59
- }
60
- return codec.decompress(packed.subarray(1));
61
- }
62
- default:
63
- throw new Error(`state token carries an init request with unknown codec ${packed[0]}`);
64
- }
65
- }
66
-
67
- /** What a continuation needs from the carried init request. */
68
- export interface CarriedInitRequest {
69
- /**
70
- * The parsed request -- a fresh top-level object with a fresh `bind_call`
71
- * each call, so the per-turn assignments the dispatcher makes (split
72
- * payloads) never reach the shared parse. The nested values (Arrow
73
- * schemas and batches, arguments) are shared and must be treated as
74
- * read-only, as they always were.
75
- */
76
- request: InitRequest;
77
- /** The raw bind-call IPC bytes, which the split-token fingerprint hashes. */
78
- bindCallIpc: Uint8Array;
79
- }
80
-
81
- interface Parsed {
82
- packed: Uint8Array;
83
- request: InitRequest;
84
- bindCallIpc: Uint8Array;
85
- }
86
-
87
- /** Streams whose parse a process keeps. Past this, the least recently used is dropped. */
88
- const MAX_ENTRIES = 128;
89
- const parsed = new Map<number, Parsed>();
90
- const stats = { parses: 0, hits: 0 };
91
-
92
- /** FNV-1a over the bytes, folded with the length. */
93
- function hashBytes(bytes: Uint8Array): number {
94
- let h = 0x811c9dc5 ^ bytes.byteLength;
95
- for (let i = 0; i < bytes.byteLength; i++) {
96
- h ^= bytes[i]!;
97
- h = Math.imul(h, 0x01000193);
98
- }
99
- return h >>> 0;
100
- }
101
-
102
- function sameBytes(a: Uint8Array, b: Uint8Array): boolean {
103
- if (a.byteLength !== b.byteLength) return false;
104
- for (let i = 0; i < a.byteLength; i++) if (a[i] !== b[i]) return false;
105
- return true;
106
- }
107
-
108
- /**
109
- * Parse the init request a cursor carries (as packed by
110
- * {@link packInitRequest}), from the process memo when this stream's turns have
111
- * been here before.
112
- */
113
- export function parseCarriedInitRequest(packed: Uint8Array): CarriedInitRequest {
114
- const key = hashBytes(packed);
115
- let entry = parsed.get(key);
116
- if (entry && sameBytes(entry.packed, packed)) {
117
- // Refresh its recency.
118
- parsed.delete(key);
119
- parsed.set(key, entry);
120
- stats.hits++;
121
- } else {
122
- const dict = batchToScalarDict(deserializeBatch(unpackInitRequest(packed)));
123
- stats.parses++;
124
- entry = { packed: packed.slice(), request: deserializeInitRequest(dict), bindCallIpc: dict.bind_call };
125
- // A hash collision simply replaces the other stream's entry.
126
- parsed.delete(key);
127
- if (parsed.size >= MAX_ENTRIES) parsed.delete(parsed.keys().next().value!);
128
- parsed.set(key, entry);
129
- }
130
- return {
131
- request: { ...entry.request, bind_call: { ...entry.request.bind_call } },
132
- bindCallIpc: entry.bindCallIpc,
133
- };
134
- }
135
-
136
- /** Cumulative parse / memo-hit counts for this process (observability and tests). */
137
- export function carriedInitRequestStats(): { parses: number; hits: number; entries: number } {
138
- return { ...stats, entries: parsed.size };
139
- }
@@ -1,50 +0,0 @@
1
- // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
- // Synchronous zstd, where the runtime has it.
3
- //
4
- // The state serializer is synchronous (vgi-rpc's StateSerializer contract), so
5
- // it cannot use the async helpers vgi-rpc exposes. Bun has
6
- // `Bun.zstdCompressSync`; Node >= 22.15 has `zlib.zstdCompressSync`, reached
7
- // from ESM through `process.getBuiltinModule`. Anything else (workerd, a
8
- // browser) gets `null` and callers fall back to storing bytes uncompressed.
9
-
10
- /** A synchronous zstd codec. */
11
- export interface ZstdSync {
12
- compress(data: Uint8Array): Uint8Array;
13
- decompress(data: Uint8Array): Uint8Array;
14
- }
15
-
16
- /** Level 3 is zstd's default: ~3.4x on an init request, ~50 us for 9 KB. */
17
- const LEVEL = 3;
18
-
19
- function resolveZstdSync(): ZstdSync | null {
20
- const bun = (globalThis as any).Bun;
21
- if (typeof bun?.zstdCompressSync === "function" && typeof bun?.zstdDecompressSync === "function") {
22
- return {
23
- compress: (data) => new Uint8Array(bun.zstdCompressSync(data, { level: LEVEL })),
24
- // Copied into a fresh buffer: Arrow readers want byteOffset 0.
25
- decompress: (data) => new Uint8Array(bun.zstdDecompressSync(data)),
26
- };
27
- }
28
- let zlib: any = null;
29
- try {
30
- zlib = (globalThis as any).process?.getBuiltinModule?.("node:zlib") ?? null;
31
- } catch {
32
- zlib = null;
33
- }
34
- if (typeof zlib?.zstdCompressSync === "function" && typeof zlib?.zstdDecompressSync === "function") {
35
- const params = { [zlib.constants.ZSTD_c_compressionLevel]: LEVEL };
36
- return {
37
- compress: (data) => new Uint8Array(zlib.zstdCompressSync(data, { params })),
38
- decompress: (data) => new Uint8Array(zlib.zstdDecompressSync(data)),
39
- };
40
- }
41
- return null;
42
- }
43
-
44
- let resolved: ZstdSync | null | undefined;
45
-
46
- /** This runtime's synchronous zstd codec, or `null` when it has none. */
47
- export function zstdSync(): ZstdSync | null {
48
- if (resolved === undefined) resolved = resolveZstdSync();
49
- return resolved;
50
- }