@query-farm/vgi 0.48.2 → 0.48.4

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 (54) hide show
  1. package/README.md +27 -0
  2. package/dist/arrow/impl-arrowjs/iterate.d.ts +7 -3
  3. package/dist/arrow/impl-flechette/iterate.d.ts +2 -1
  4. package/dist/catalog/descriptors.d.ts +30 -0
  5. package/dist/catalog/interface.d.ts +28 -0
  6. package/dist/catalog/read-only.d.ts +16 -2
  7. package/dist/client-entry.js +9 -25
  8. package/dist/client-entry.js.map +4 -4
  9. package/dist/functions/aggregate.d.ts +2 -1
  10. package/dist/functions/copy-from.d.ts +2 -1
  11. package/dist/functions/copy-to.d.ts +2 -1
  12. package/dist/functions/scalar.d.ts +2 -1
  13. package/dist/functions/table-buffering.d.ts +2 -1
  14. package/dist/functions/table-in-out.d.ts +3 -2
  15. package/dist/functions/table.d.ts +2 -1
  16. package/dist/functions/types.d.ts +2 -1
  17. package/dist/index.core.d.ts +4 -1
  18. package/dist/index.js +360 -72
  19. package/dist/index.js.map +25 -23
  20. package/dist/metadata/types.d.ts +3 -1
  21. package/dist/protocol/handlers/catalog/shared.d.ts +8 -0
  22. package/dist/secrets/helpers.d.ts +31 -3
  23. package/dist/secrets/requirements.d.ts +38 -0
  24. package/dist/serve-entry.js +51 -33
  25. package/dist/serve-entry.js.map +9 -9
  26. package/dist/worker-cf-entry.d.ts +2 -2
  27. package/dist/worker-cf-entry.js +296 -50
  28. package/dist/worker-cf-entry.js.map +21 -18
  29. package/dist/write-results.d.ts +57 -0
  30. package/package.json +1 -1
  31. package/src/arrow/impl-arrowjs/iterate.ts +17 -40
  32. package/src/arrow/impl-flechette/iterate.ts +5 -24
  33. package/src/catalog/descriptors.ts +30 -0
  34. package/src/catalog/interface.ts +51 -0
  35. package/src/catalog/read-only.ts +129 -21
  36. package/src/functions/aggregate.ts +3 -2
  37. package/src/functions/copy-from.ts +3 -2
  38. package/src/functions/copy-to.ts +2 -1
  39. package/src/functions/scalar.ts +3 -2
  40. package/src/functions/table-buffering.ts +3 -2
  41. package/src/functions/table-in-out.ts +5 -4
  42. package/src/functions/table.ts +3 -2
  43. package/src/functions/types.ts +2 -1
  44. package/src/index.core.ts +33 -0
  45. package/src/metadata/resolve.ts +2 -1
  46. package/src/metadata/serialize.ts +25 -5
  47. package/src/metadata/types.ts +3 -1
  48. package/src/protocol/handlers/catalog/shared.ts +17 -0
  49. package/src/protocol/handlers/catalog/table.ts +37 -0
  50. package/src/protocol/handlers/function.ts +42 -14
  51. package/src/secrets/helpers.ts +96 -9
  52. package/src/secrets/requirements.ts +121 -0
  53. package/src/worker-cf-entry.ts +14 -0
  54. package/src/write-results.ts +174 -0
@@ -3,6 +3,7 @@
3
3
  // Two-phase: INPUT phase receives and transforms batches,
4
4
  // FINALIZE phase emits final results.
5
5
 
6
+ import { normalizeRequiredSecrets, type RequiredSecret } from "../secrets/requirements.js";
6
7
  import { type VgiSchema, schema, type VgiField, type VgiDataType, type VgiBatch, nullType, isNull, withBatchMetadata, serializeBatch, deserializeBatch } from "../arrow/index.js";
7
8
  import type { OutputCollector } from "@query-farm/vgi-rpc";
8
9
  import { DEFAULT_MAX_WORKERS, TableInOutPhase } from "../types.js";
@@ -179,7 +180,7 @@ export interface TableInOutConfig<
179
180
  tags?: Record<string, string>;
180
181
  maxWorkers?: number;
181
182
  requiredSettings?: string[];
182
- requiredSecrets?: string[];
183
+ requiredSecrets?: RequiredSecret[];
183
184
  }
184
185
 
185
186
  export function defineTableInOutFunction<
@@ -250,7 +251,7 @@ export function defineTableInOutFunction<
250
251
  parameterDefaultValues: config.parameterDefaultValues,
251
252
  maxWorkers: config.maxWorkers,
252
253
  requiredSettings: config.requiredSettings,
253
- requiredSecrets: config.requiredSecrets,
254
+ requiredSecrets: normalizeRequiredSecrets(config.requiredSecrets, config.name),
254
255
  hasFinalize: !!config.finalize,
255
256
  };
256
257
 
@@ -861,7 +862,7 @@ export interface RowTransformConfig<TArgs = Record<string, any>, TState = null>
861
862
  tags?: Record<string, string>;
862
863
  maxWorkers?: number;
863
864
  requiredSettings?: string[];
864
- requiredSecrets?: string[];
865
+ requiredSecrets?: RequiredSecret[];
865
866
  }
866
867
 
867
868
  /**
@@ -954,7 +955,7 @@ export function defineRowTransformFunction<
954
955
  parameterDefaultValues: config.parameterDefaultValues,
955
956
  maxWorkers: config.maxWorkers,
956
957
  requiredSettings: config.requiredSettings,
957
- requiredSecrets: config.requiredSecrets,
958
+ requiredSecrets: normalizeRequiredSecrets(config.requiredSecrets, config.name),
958
959
  // Map-shaped, per-row: a blended function never has a finalize.
959
960
  hasFinalize: false,
960
961
  inputFromArgs: true,
@@ -2,6 +2,7 @@
2
2
  // Table function implementation.
3
3
  // Table functions produce output batches from arguments (no streaming input).
4
4
 
5
+ import { normalizeRequiredSecrets, type RequiredSecret } from "../secrets/requirements.js";
5
6
  import {
6
7
  type VgiSchema,
7
8
  type VgiBatch,
@@ -331,7 +332,7 @@ export interface TableFunctionConfig<
331
332
  tags?: Record<string, string>;
332
333
  maxWorkers?: number;
333
334
  requiredSettings?: string[];
334
- requiredSecrets?: string[];
335
+ requiredSecrets?: RequiredSecret[];
335
336
  /** Row-order preservation behavior; flows to DuckDB's
336
337
  * TableFunction::order_preservation_type. */
337
338
  preservesOrder?: OrderPreservation;
@@ -413,7 +414,7 @@ export function defineTableFunction<
413
414
  parameterDefaultValues: config.parameterDefaultValues,
414
415
  maxWorkers: config.maxWorkers,
415
416
  requiredSettings: config.requiredSettings,
416
- requiredSecrets: config.requiredSecrets,
417
+ requiredSecrets: normalizeRequiredSecrets(config.requiredSecrets, config.name),
417
418
  preservesOrder: config.preservesOrder,
418
419
  nullHandling: config.nullHandling,
419
420
  orderDependent: config.orderDependent,
@@ -1,6 +1,7 @@
1
1
  // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
2
  // Function config interfaces and VgiFunction base type.
3
3
 
4
+ import type { RequiredSecret } from "../secrets/requirements.js";
4
5
  import type { VgiSchema, VgiBatch, VgiDataType } from "../arrow/index.js";
5
6
  import type { OutputCollector } from "@query-farm/vgi-rpc";
6
7
  import type {
@@ -94,7 +95,7 @@ export interface FunctionMeta {
94
95
  preservesOrder?: OrderPreservation | undefined;
95
96
  maxWorkers?: number | undefined;
96
97
  requiredSettings?: string[] | undefined;
97
- requiredSecrets?: string[] | undefined;
98
+ requiredSecrets?: RequiredSecret[] | undefined;
98
99
  orderDependent?: OrderDependence | undefined;
99
100
  distinctDependent?: DistinctDependence | undefined;
100
101
  /**
package/src/index.core.ts CHANGED
@@ -30,6 +30,29 @@ export {
30
30
  type CacheScope,
31
31
  } from "./cache-control.js";
32
32
 
33
+ // Writable tables: result modes, row ids and the write_options decoder for
34
+ // INSERT / UPDATE / DELETE functions (TableDescriptor.insertFunction etc.).
35
+ export {
36
+ type WriteOperation,
37
+ type WriteResultMode,
38
+ type WriteOptions,
39
+ WRITE_OPERATIONS,
40
+ WRITE_RESULT_MODES,
41
+ ROW_ID_METADATA_KEY,
42
+ rowIdField,
43
+ userColumns,
44
+ validateWriteResultModes,
45
+ supportsWriteResultMode,
46
+ coerceWriteResultMode,
47
+ writeResultSchema,
48
+ writeCountBatch,
49
+ writeRowsBatch,
50
+ writeChangesBatch,
51
+ writeResultBatch,
52
+ writeOptions,
53
+ } from "./write-results.js";
54
+ export type { ScanFunctionResultRecord } from "./catalog/interface.js";
55
+
33
56
  // Function factories (primary API)
34
57
  export { defineScalarFunction, type ScalarFunctionConfig, type ScalarBindParameters, type ScalarComputeInfo, type ScalarParameterDef } from "./functions/scalar.js";
35
58
  export { defineTableFunction, type TableFunctionConfig, type TableBindParams, type TableProcessParams } from "./functions/table.js";
@@ -262,10 +285,20 @@ export {
262
285
  type SecretsDict,
263
286
  secretType,
264
287
  secretsOfType,
288
+ secretOfType,
289
+ requireSecretOfType,
290
+ secretByName,
265
291
  secretForScope,
266
292
  secretForScopeOfType,
267
293
  } from "./secrets/helpers.js";
268
294
 
295
+ export {
296
+ type RequiredSecret,
297
+ type SecretRequirement,
298
+ type SecretRequirementSpec,
299
+ normalizeRequiredSecrets,
300
+ } from "./secrets/requirements.js";
301
+
269
302
  export {
270
303
  serializeSchema,
271
304
  deserializeSchema,
@@ -1,6 +1,7 @@
1
1
  // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
2
  // Extract metadata from VgiFunction configs.
3
3
 
4
+ import { normalizeRequiredSecrets } from "../secrets/requirements.js";
4
5
  import {
5
6
  FunctionStability,
6
7
  NullHandling,
@@ -132,7 +133,7 @@ export function resolveMetadata(func: VgiFunction): ResolvedMetadata {
132
133
  nullHandling: meta.nullHandling ?? NullHandling.DEFAULT,
133
134
  argumentMonotonicity,
134
135
  requiredSettings: meta.requiredSettings ?? [],
135
- requiredSecrets: meta.requiredSecrets ?? [],
136
+ requiredSecrets: normalizeRequiredSecrets(meta.requiredSecrets, meta.name),
136
137
  projectionPushdown: meta.projectionPushdown ?? false,
137
138
  filterPushdown: meta.filterPushdown ?? false,
138
139
  samplingPushdown: meta.samplingPushdown ?? false,
@@ -18,6 +18,7 @@ import {
18
18
  } from "../arrow/index.js";
19
19
  import type { ResolvedMetadata, ParameterInfo, FunctionExample } from "./types.js";
20
20
  import type { ArgumentMonotonicity } from "../types.js";
21
+ import { normalizeRequiredSecrets, type SecretRequirement } from "../secrets/requirements.js";
21
22
 
22
23
  // ============================================================================
23
24
  // Schema definitions matching Python's _METADATA_SCHEMA exactly
@@ -54,6 +55,12 @@ const FILTER_CONTEXT_STRUCT = makeStruct([
54
55
  field("provider_fingerprint", utf8(), true),
55
56
  ]);
56
57
 
58
+ const SECRET_REQUIREMENT_STRUCT = makeStruct([
59
+ field("secret_type", utf8(), false),
60
+ field("secret_name", utf8(), true),
61
+ field("scope", utf8(), true),
62
+ ]);
63
+
57
64
  const METADATA_SCHEMA = makeSchema([
58
65
  field("name", utf8(), false),
59
66
  field("class_name", utf8(), false),
@@ -67,7 +74,7 @@ const METADATA_SCHEMA = makeSchema([
67
74
  field("null_handling", utf8(), false),
68
75
  field("argument_monotonicity", list(field("item", utf8(), true)), true),
69
76
  field("required_settings", list(field("item", utf8(), true)), false),
70
- field("required_secrets", list(field("item", utf8(), true)), false),
77
+ field("required_secrets", list(field("item", SECRET_REQUIREMENT_STRUCT, true)), false),
71
78
  field("projection_pushdown", bool(), false),
72
79
  field("filter_pushdown", bool(), false),
73
80
  field("filter_semantic_profiles", list(field("item", utf8(), true)), false),
@@ -116,7 +123,11 @@ function metadataToRow(m: ResolvedMetadata): Record<string, any> {
116
123
  null_handling: m.nullHandling,
117
124
  argument_monotonicity: m.argumentMonotonicity,
118
125
  required_settings: m.requiredSettings,
119
- required_secrets: m.requiredSecrets,
126
+ required_secrets: m.requiredSecrets.map((s) => ({
127
+ secret_type: s.secretType,
128
+ secret_name: s.secretName,
129
+ scope: s.scope,
130
+ })),
120
131
  projection_pushdown: m.projectionPushdown,
121
132
  filter_pushdown: m.filterPushdown,
122
133
  sampling_pushdown: m.samplingPushdown,
@@ -236,9 +247,18 @@ export function arrowToMetadatas(batch: VgiBatch): ResolvedMetadata[] {
236
247
  : [];
237
248
 
238
249
  const rawRequiredSecrets = get("required_secrets") as any ?? [];
239
- const requiredSecrets: string[] = rawRequiredSecrets
240
- ? [...rawRequiredSecrets].filter((s: any) => s != null)
241
- : [];
250
+ // Struct entries ({secret_type, secret_name, scope}); a bare string (the
251
+ // pre-0.48.3 list<utf8> layout) is still read as a type-only requirement.
252
+ const requiredSecrets: SecretRequirement[] = normalizeRequiredSecrets(
253
+ rawRequiredSecrets
254
+ ? [...rawRequiredSecrets].filter((s: any) => s != null).map((s: any) =>
255
+ typeof s === "string"
256
+ ? s
257
+ : { secretType: s.secret_type, secretName: s.secret_name ?? null, scope: s.scope ?? null },
258
+ )
259
+ : [],
260
+ (get("name") as string) ?? "<function>",
261
+ );
242
262
 
243
263
  results.push({
244
264
  name: (get("name") as string) ?? "",
@@ -1,6 +1,7 @@
1
1
  // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
2
  // Metadata types for function introspection and DuckDB registration.
3
3
 
4
+ import type { SecretRequirement } from "../secrets/requirements.js";
4
5
  import {
5
6
  FunctionStability,
6
7
  NullHandling,
@@ -61,7 +62,8 @@ export interface ResolvedMetadata {
61
62
  nullHandling: NullHandling;
62
63
  argumentMonotonicity: ArgumentMonotonicity[] | null;
63
64
  requiredSettings: string[];
64
- requiredSecrets: string[];
65
+ /** Validated static secret requirements (FunctionInfo `required_secrets`). */
66
+ requiredSecrets: SecretRequirement[];
65
67
  projectionPushdown: boolean;
66
68
  filterPushdown: boolean;
67
69
  samplingPushdown: boolean;
@@ -128,6 +128,23 @@ export async function sealTransaction(
128
128
  return sealBytes(plaintext, signingKey, transactionAad(auth, attachEnvelope), TRANSACTION_ENVELOPE_VERSION);
129
129
  }
130
130
 
131
+ /**
132
+ * Open a transaction_opaque_data envelope (sealed on HTTP only, no UUID prefix).
133
+ * `attachEnvelope` is the request's *sealed* attach, which the transaction
134
+ * envelope's AAD binds. A pass-through without a signing key or for an empty
135
+ * value. Catalog hooks and function bodies must see the same plaintext, or a
136
+ * worker cannot tie a function call to its transaction's commit/rollback.
137
+ */
138
+ export async function openTransaction(
139
+ envelope: Uint8Array,
140
+ attachEnvelope: Uint8Array,
141
+ auth: AuthContext | undefined,
142
+ signingKey: Uint8Array | undefined,
143
+ ): Promise<Uint8Array> {
144
+ if (!signingKey || envelope.length === 0) return envelope;
145
+ return openBytes(envelope, signingKey, transactionAad(auth, attachEnvelope), TRANSACTION_ENVELOPE_VERSION, "transaction_opaque_data");
146
+ }
147
+
131
148
  /**
132
149
  * Unwrap the attach_opaque_data / transaction_opaque_data fields of a catalog
133
150
  * request in place, so handler bodies always see plaintext. The transaction
@@ -162,6 +162,40 @@ export function catalogTableHandlers(getCatalog: GetCatalog, signingKey?: Uint8A
162
162
  return wrapResult(scanResult, ScanFunctionResultSchema);
163
163
  });
164
164
 
165
+ // catalog_table_{insert,update,delete}_function_get — the table in-out
166
+ // function backing each DML statement. A catalog whose tables inline these
167
+ // into TableInfo is only asked when the client skipped the inline value.
168
+ const optionalTx = (params: Record<string, any>): Uint8Array | undefined =>
169
+ params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined;
170
+ const catalogTableInsertFunctionGet = catalogHandler(signingKey, async (params) => {
171
+ const result = await getCatalog().tableInsertFunctionGet(
172
+ toUint8Array(params.attach_opaque_data),
173
+ params.schema_path,
174
+ params.name,
175
+ optionalTx(params),
176
+ params.writable_branch_function_name ?? null,
177
+ );
178
+ return wrapResult(result, ScanFunctionResultSchema);
179
+ });
180
+ const catalogTableUpdateFunctionGet = catalogHandler(signingKey, async (params) => {
181
+ const result = await getCatalog().tableUpdateFunctionGet(
182
+ toUint8Array(params.attach_opaque_data),
183
+ params.schema_path,
184
+ params.name,
185
+ optionalTx(params),
186
+ );
187
+ return wrapResult(result, ScanFunctionResultSchema);
188
+ });
189
+ const catalogTableDeleteFunctionGet = catalogHandler(signingKey, async (params) => {
190
+ const result = await getCatalog().tableDeleteFunctionGet(
191
+ toUint8Array(params.attach_opaque_data),
192
+ params.schema_path,
193
+ params.name,
194
+ optionalTx(params),
195
+ );
196
+ return wrapResult(result, ScanFunctionResultSchema);
197
+ });
198
+
165
199
  // catalog_table_scan_branches_get — branches-aware variant of
166
200
  // scan_function_get. The branches-aware C++ extension calls this for every
167
201
  // table scan; single-source catalogs synthesise a one-branch result.
@@ -350,6 +384,9 @@ export function catalogTableHandlers(getCatalog: GetCatalog, signingKey?: Uint8A
350
384
  catalogTableDrop,
351
385
  catalogTableColumnStatisticsGet,
352
386
  catalogTableScanFunctionGet,
387
+ catalogTableInsertFunctionGet,
388
+ catalogTableUpdateFunctionGet,
389
+ catalogTableDeleteFunctionGet,
353
390
  catalogTableScanBranchesGet,
354
391
  catalogTableCommentSet,
355
392
  catalogTableRename,
@@ -34,7 +34,7 @@ import {
34
34
  } from "../../generated/vgi-protocol-schemas.js";
35
35
  import { unwrapRequest, wrapResult, overloadContext } from "./shared.js";
36
36
  import { parseCarriedInitRequest } from "../carried-init-request.js";
37
- import { openAttach } from "./catalog/shared.js";
37
+ import { openAttach, openTransaction } from "./catalog/shared.js";
38
38
  import { currentRequestAuth } from "../../request-auth.js";
39
39
  import { batchFromColumns, serializeBatch } from "../../util/arrow/index.js";
40
40
  import {
@@ -93,9 +93,18 @@ async function liveSplitAnchor(
93
93
  ): Promise<Uint8Array | undefined> {
94
94
  if (!catalogInterface?.version || bindCall.attach_opaque_data == null) return undefined;
95
95
  const raw = toUint8Array(bindCall.attach_opaque_data);
96
- const txn = bindCall.transaction_opaque_data
97
- ? toUint8Array(bindCall.transaction_opaque_data)
98
- : undefined;
96
+ // The transaction id is likewise sealed at `plan` (HTTP) and already open at
97
+ // `init`; the catalog's version() takes plaintext, as its own RPC does, so
98
+ // open it when it opens under this attach and use it as-is otherwise. Both
99
+ // stages must ask the same question or mint and redemption disagree.
100
+ let txn = bindCall.transaction_opaque_data ? toUint8Array(bindCall.transaction_opaque_data) : undefined;
101
+ if (txn && txn.length > 0 && signingKey) {
102
+ try {
103
+ txn = await openTransaction(txn, raw, auth, signingKey);
104
+ } catch {
105
+ // already plaintext (init), keep it
106
+ }
107
+ }
99
108
 
100
109
  // The two call sites see the attach envelope at DIFFERENT processing stages —
101
110
  // `plan` receives it with the framework's 16-byte UUID prefix still attached,
@@ -212,19 +221,41 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
212
221
  return openAttach(env, ctx?.auth ?? currentRequestAuth(), signingKey);
213
222
  }
214
223
 
224
+ // Unseal a bind call's opaque values in place, as the catalog handlers do:
225
+ // the transaction first (its envelope binds the *sealed* attach), then the
226
+ // attach. Every function-side request goes through this, so function bodies
227
+ // see the same transaction plaintext that transactionCommit/Rollback get.
228
+ async function openOpaque(
229
+ bindCall: { attach_opaque_data?: Uint8Array | null; transaction_opaque_data?: Uint8Array | null },
230
+ ctx: any,
231
+ ): Promise<void> {
232
+ const sealedAttach = bindCall.attach_opaque_data != null ? toUint8Array(bindCall.attach_opaque_data) : new Uint8Array(0);
233
+ if (bindCall.transaction_opaque_data != null) {
234
+ bindCall.transaction_opaque_data = await openTransaction(
235
+ toUint8Array(bindCall.transaction_opaque_data),
236
+ sealedAttach,
237
+ ctx?.auth ?? currentRequestAuth(),
238
+ signingKey,
239
+ );
240
+ }
241
+ bindCall.attach_opaque_data = await stripAttach(bindCall.attach_opaque_data, ctx);
242
+ }
243
+
215
244
  // Build an overload context whose attach has been unsealed, so catalog
216
245
  // resolution sees the real route byte. The bind/init handlers strip their
217
246
  // request in place and can call overloadContext directly; every other site
218
247
  // still holds the sealed envelope (73 bytes on HTTP vs 16 plaintext), whose
219
248
  // leading byte would otherwise route to an arbitrary catalog.
220
249
  async function strippedContext(bindCall: any, ctx?: any) {
221
- let attach: Uint8Array | null = null;
250
+ const copy = { ...bindCall };
222
251
  try {
223
- attach = await stripAttach(bindCall.attach_opaque_data, ctx);
252
+ await openOpaque(copy, ctx);
224
253
  } catch {
225
- attach = null; // Unopenable (wrong key / not sealed) — resolve unscoped.
254
+ // Unopenable (wrong key / not sealed) — resolve unscoped.
255
+ copy.attach_opaque_data = null;
256
+ copy.transaction_opaque_data = null;
226
257
  }
227
- return overloadContext({ ...bindCall, attach_opaque_data: attach }, catalogInterface);
258
+ return overloadContext(copy, catalogInterface);
228
259
  }
229
260
 
230
261
  const emptySchema = schema([]);
@@ -243,7 +274,7 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
243
274
  const bind: VgiService["bind"] = async (params, ctx) => {
244
275
  const innerParams = unwrapRequest(params.request);
245
276
  const request = deserializeBindRequest(innerParams);
246
- request.attach_opaque_data = await stripAttach(request.attach_opaque_data, ctx);
277
+ await openOpaque(request, ctx);
247
278
  const func = registry.get(request.function_name, overloadContext(request, catalogInterface));
248
279
  const response = await func.bind(request);
249
280
  validateProjectionOffer(response);
@@ -280,10 +311,7 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
280
311
  // attach_opaque_data not recognized` on its first scan, i.e. this worker
281
312
  // could not serve authenticated traffic at all.
282
313
  const auth = ctx?.auth ?? currentRequestAuth();
283
- request.bind_call.attach_opaque_data = await stripAttach(
284
- request.bind_call.attach_opaque_data,
285
- ctx,
286
- );
314
+ await openOpaque(request.bind_call, ctx);
287
315
 
288
316
  // Verify and strip the split envelopes BEFORE any user code runs, so an
289
317
  // unverified token can never be acted on.
@@ -381,7 +409,7 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
381
409
  // a hard error here, as on the init turn: the cursor is caller-bound.)
382
410
  // `carried.request.bind_call` is a per-call copy, so this does not
383
411
  // disturb the memoised parse other turns share.
384
- request.bind_call.attach_opaque_data = await stripAttach(request.bind_call.attach_opaque_data, undefined);
412
+ await openOpaque(request.bind_call, undefined);
385
413
  // Re-derive the split payloads. The cursor carries the wire request,
386
414
  // which has `split_tokens` but not the opened `split_payloads` — that
387
415
  // field only ever existed in memory on the init turn. Without this a
@@ -1,10 +1,26 @@
1
1
  // Type- and scope-aware selection over resolved secrets.
2
2
  //
3
3
  // Resolved secrets reach a worker as a plain object keyed by each secret's
4
- // unique DuckDB secret name (so several secrets of the same type — e.g. one per
5
- // S3 bucket — coexist). Each secret carries its connector-serialized `type` (the
6
- // DuckDB secret type) and `scope` (newline-joined scope prefixes) fields, plus
7
- // type-specific fields. These helpers mirror `vgi::Secrets` in the Rust SDK.
4
+ // unique DuckDB secret NAME, not its type: an unnamed
5
+ // `CREATE SECRET (TYPE brave, ...)` arrives as `__default_brave`, and several
6
+ // secrets of one type (e.g. one per S3 bucket) coexist. Each secret carries its
7
+ // connector-serialized `type` (the DuckDB secret type), `name`, and `scope`
8
+ // (newline-joined scope prefixes) fields, plus type-specific fields.
9
+ //
10
+ // So never look a TYPE up as a key (`secrets["brave"]` finds the secret only
11
+ // when the user happened to name it after its type). Select with these helpers,
12
+ // which apply the same rules the client used to resolve the request
13
+ // (vgi-python `docs/protocol/vgi-secrets.md` section 5):
14
+ //
15
+ // by type -> secretOfType / secretsOfType / requireSecretOfType
16
+ // by name -> secretByName
17
+ // by scope -> secretForScopeOfType (longest prefix, else unscoped, else none)
18
+ //
19
+ // Every by-type selector matches the secret's `type` field. Only when no
20
+ // secret carries that type does it fall back to a secret whose KEY is the type
21
+ // and that has no `type` field at all: a bare key/value struct from a client
22
+ // that keys the batch by type (as vgi-python's standalone Client allows).
23
+ // These helpers mirror `vgi::Secrets` in the Rust SDK.
8
24
 
9
25
  export type SecretFields = Record<string, any>;
10
26
  export type SecretsDict = Record<string, SecretFields>;
@@ -20,28 +36,99 @@ export function secretType(secrets: SecretsDict, name: string): string | undefin
20
36
  return f && "type" in f ? scalarStr(f.type) : undefined;
21
37
  }
22
38
 
23
- /** Every resolved secret whose serialized `type` field matches `type`. */
39
+ /** True when the secret's serialized `type` field is absent or empty. */
40
+ function untyped(fields: SecretFields | undefined): boolean {
41
+ return !!fields && scalarStr(fields.type) === "";
42
+ }
43
+
44
+ /**
45
+ * The legacy by-key fallback: a secret stored under the key `type` that has no
46
+ * `type` field of its own (a client that keys the batch by type and sends bare
47
+ * key/value structs). A secret under that key whose `type` field names another
48
+ * type is NOT a match.
49
+ */
50
+ function keyedByType(secrets: SecretsDict, type: string): SecretFields | undefined {
51
+ const f = secrets?.[type];
52
+ return untyped(f) ? f : undefined;
53
+ }
54
+
55
+ /**
56
+ * Every resolved secret whose serialized `type` field matches `type`, in
57
+ * delivery order. Falls back to an untyped secret keyed by `type` only when no
58
+ * secret carries the type.
59
+ */
24
60
  export function secretsOfType(secrets: SecretsDict, type: string): SecretFields[] {
25
- return Object.values(secrets ?? {}).filter((f) => scalarStr(f.type) === type);
61
+ const typed = Object.values(secrets ?? {}).filter((f) => scalarStr(f.type) === type);
62
+ if (typed.length > 0) return typed;
63
+ const legacy = keyedByType(secrets, type);
64
+ return legacy ? [legacy] : [];
65
+ }
66
+
67
+ /**
68
+ * The secret a by-TYPE request refers to: a secret of `type` with an empty
69
+ * scope, else the first secret of `type`, else undefined. This is the rule the
70
+ * client applies to a `requiredSecrets: ["<type>"]` declaration, so it picks the
71
+ * secret that declaration resolved even when other same-type secrets (from
72
+ * scoped declarations) were delivered alongside it.
73
+ */
74
+ export function secretOfType(secrets: SecretsDict, type: string): SecretFields | undefined {
75
+ const all = secretsOfType(secrets, type);
76
+ return all.find((f) => scalarStr(f.scope) === "") ?? all[0];
77
+ }
78
+
79
+ /**
80
+ * Like {@link secretOfType}, but throws when no secret of `type` was resolved.
81
+ * Call it from `onBind` to fail the bind of a function that cannot run without
82
+ * credentials. The message names the type and never includes a secret value.
83
+ */
84
+ export function requireSecretOfType(secrets: SecretsDict, type: string): SecretFields {
85
+ const found = secretOfType(secrets, type);
86
+ if (!found) {
87
+ throw new Error(
88
+ `required secret of type '${type}' was not found; create one with CREATE SECRET (TYPE ${type}, ...)`,
89
+ );
90
+ }
91
+ return found;
92
+ }
93
+
94
+ /**
95
+ * The secret with DuckDB name `name` (its key in the resolved batch). With
96
+ * `type`, only if that secret's `type` field is `type` (or absent, for a bare
97
+ * key/value struct) — the rule the client applies to a by-name request.
98
+ */
99
+ export function secretByName(
100
+ secrets: SecretsDict,
101
+ name: string,
102
+ type?: string,
103
+ ): SecretFields | undefined {
104
+ if (!secrets || !Object.prototype.hasOwnProperty.call(secrets, name)) return undefined;
105
+ const f = secrets[name];
106
+ if (!f) return undefined;
107
+ if (type === undefined || untyped(f) || scalarStr(f.type) === type) return f;
108
+ return undefined;
26
109
  }
27
110
 
28
111
  /**
29
112
  * The secret whose `scope` is the longest prefix of `path`. The connector
30
113
  * serializes each secret's scope as a newline-joined list of prefixes; a secret
31
114
  * with no (or empty) scope matches as a last-resort fallback. Returns undefined
32
- * only when there are no candidate secrets.
115
+ * when no scope is a prefix of `path` and no unscoped secret was delivered.
33
116
  */
34
117
  export function secretForScope(secrets: SecretsDict, path: string): SecretFields | undefined {
35
118
  return selectForScope(secrets, path, undefined);
36
119
  }
37
120
 
38
- /** Like {@link secretForScope} but only over secrets of `type`. */
121
+ /**
122
+ * Like {@link secretForScope} but only over secrets of `type`: the one whose
123
+ * scope is the longest prefix of `path`, else one of `type` with an empty scope,
124
+ * else undefined.
125
+ */
39
126
  export function secretForScopeOfType(
40
127
  secrets: SecretsDict,
41
128
  path: string,
42
129
  type: string,
43
130
  ): SecretFields | undefined {
44
- return selectForScope(secrets, path, type);
131
+ return selectForScope(secrets, path, type) ?? keyedByType(secrets, type);
45
132
  }
46
133
 
47
134
  function selectForScope(