@query-farm/vgi 0.48.2 → 0.48.3

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 (43) 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/client-entry.js +9 -25
  5. package/dist/client-entry.js.map +3 -3
  6. package/dist/functions/aggregate.d.ts +2 -1
  7. package/dist/functions/copy-from.d.ts +2 -1
  8. package/dist/functions/copy-to.d.ts +2 -1
  9. package/dist/functions/scalar.d.ts +2 -1
  10. package/dist/functions/table-buffering.d.ts +2 -1
  11. package/dist/functions/table-in-out.d.ts +3 -2
  12. package/dist/functions/table.d.ts +2 -1
  13. package/dist/functions/types.d.ts +2 -1
  14. package/dist/index.core.d.ts +2 -1
  15. package/dist/index.js +131 -39
  16. package/dist/index.js.map +18 -17
  17. package/dist/metadata/types.d.ts +3 -1
  18. package/dist/secrets/helpers.d.ts +31 -3
  19. package/dist/secrets/requirements.d.ts +38 -0
  20. package/dist/serve-entry.js +9 -25
  21. package/dist/serve-entry.js.map +5 -5
  22. package/dist/worker-cf-entry.d.ts +2 -2
  23. package/dist/worker-cf-entry.js +161 -32
  24. package/dist/worker-cf-entry.js.map +15 -13
  25. package/package.json +1 -1
  26. package/src/arrow/impl-arrowjs/iterate.ts +17 -40
  27. package/src/arrow/impl-flechette/iterate.ts +5 -24
  28. package/src/catalog/read-only.ts +6 -3
  29. package/src/functions/aggregate.ts +3 -2
  30. package/src/functions/copy-from.ts +3 -2
  31. package/src/functions/copy-to.ts +2 -1
  32. package/src/functions/scalar.ts +3 -2
  33. package/src/functions/table-buffering.ts +3 -2
  34. package/src/functions/table-in-out.ts +5 -4
  35. package/src/functions/table.ts +3 -2
  36. package/src/functions/types.ts +2 -1
  37. package/src/index.core.ts +10 -0
  38. package/src/metadata/resolve.ts +2 -1
  39. package/src/metadata/serialize.ts +25 -5
  40. package/src/metadata/types.ts +3 -1
  41. package/src/secrets/helpers.ts +96 -9
  42. package/src/secrets/requirements.ts +121 -0
  43. package/src/worker-cf-entry.ts +14 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@query-farm/vgi",
3
- "version": "0.48.2",
3
+ "version": "0.48.3",
4
4
  "description": "TypeScript framework for extending DuckDB with user-defined functions via the Vector Gateway Interface (VGI) over Arrow IPC.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "author": "Query Farm LLC (https://query.farm)",
@@ -93,9 +93,13 @@ export function decodeDictValue(value: any, index = 0): any {
93
93
  }
94
94
 
95
95
  /**
96
- * Extract single-row batch to a secret dict (column per secret, each value is a struct).
97
- * Handles both named secrets (column name = secret type) and scoped secrets
98
- * (column name = "secret_N" with secret_type in field metadata).
96
+ * Extract a single-row resolved-secrets batch to a dict: one entry per column,
97
+ * keyed by the column name — the secret's unique DuckDB NAME, not its type (an
98
+ * unnamed secret arrives as `__default_<type>`). Each value is the secret's
99
+ * struct as a plain object, including its serialized `type`, `name` and `scope`
100
+ * fields. Select from it with the helpers in `secrets/helpers.ts`
101
+ * (`secretOfType`, `secretByName`, `secretForScopeOfType`, ...), never by
102
+ * indexing it with a type. A null struct (secret not found) is skipped.
99
103
  */
100
104
  export function batchToSecretDict(
101
105
  batch: RecordBatch | VgiBatch | null
@@ -106,43 +110,16 @@ export function batchToSecretDict(
106
110
  const result: Record<string, Record<string, any>> = {};
107
111
  for (const field of a.schema.fields) {
108
112
  const col = a.getChild(field.name);
109
- if (col) {
110
- // Read in RICH form via the canonical reader + codec — a secret column is
111
- // a struct scalar, which surfaces as a plain { field: value } object
112
- // (same path as iterRows), so no Arrow-scalar toJSON() shimming is needed.
113
- const type = field.type as unknown as VgiDataType;
114
- const val = codecFor(type).canonicalToRich(readCanonicalValue(type, col, 0));
115
-
116
- // Determine the key: for scoped secrets (secret_N), use secret_type from metadata
117
- let key = field.name;
118
- let scope: string | undefined;
119
- if (field.name.startsWith("secret_")) {
120
- const secretType = field.metadata?.get?.("secret_type");
121
- if (secretType) {
122
- key = secretType;
123
- scope = field.metadata?.get?.("scope") ?? undefined;
124
- }
125
- }
126
-
127
- if (val && typeof val === "object" && !ArrayBuffer.isView(val)) {
128
- // Struct scalar -> already a plain object from the canonical reader.
129
- const dict: Record<string, any> = { ...(val as Record<string, any>) };
130
- if (key in result) {
131
- throw new Error(
132
- `batchToSecretDict: duplicate secret_type '${key}' (scope=${scope ?? "none"}). ` +
133
- `Use scoped secrets with distinct scopes to avoid collisions.`
134
- );
135
- }
136
- result[key] = dict;
137
- // Store scope-qualified key for disambiguation
138
- if (scope) {
139
- result[`${key}:${scope}`] = dict;
140
- }
141
- } else if (val === null || val === undefined) {
142
- // Skip null struct values (secret not found)
143
- } else {
144
- result[key] = {};
145
- }
113
+ if (!col) continue;
114
+ // Read in RICH form via the canonical reader + codec — a secret column is
115
+ // a struct scalar, which surfaces as a plain { field: value } object
116
+ // (same path as iterRows), so no Arrow-scalar toJSON() shimming is needed.
117
+ const type = field.type as unknown as VgiDataType;
118
+ const val = codecFor(type).canonicalToRich(readCanonicalValue(type, col, 0));
119
+ if (val && typeof val === "object" && !ArrayBuffer.isView(val)) {
120
+ result[field.name] = { ...(val as Record<string, any>) };
121
+ } else if (val !== null && val !== undefined) {
122
+ result[field.name] = {};
146
123
  }
147
124
  }
148
125
  return result;
@@ -66,7 +66,8 @@ export function decodeDictValue(value: any, _index = 0): any {
66
66
  }
67
67
 
68
68
  /**
69
- * Single-row batch → secret dict. Mirrors impl-arrowjs's same-named function.
69
+ * Single-row resolved-secrets batch → dict keyed by column name (the secret's
70
+ * unique DuckDB NAME, not its type). Mirrors impl-arrowjs's same-named function.
70
71
  */
71
72
  export function batchToSecretDict(
72
73
  batch: VgiBatch | null,
@@ -83,30 +84,10 @@ export function batchToSecretDict(
83
84
  // iterRows), identical to the arrow-js backend.
84
85
  const type = f.type as VgiDataType;
85
86
  const val = codecFor(type).canonicalToRich(readCanonicalValue(type, col, 0));
86
-
87
- let key = f.name;
88
- let scope: string | undefined;
89
- if (f.name.startsWith("secret_")) {
90
- const secretType = f.metadata?.get?.("secret_type");
91
- if (secretType) {
92
- key = secretType;
93
- scope = f.metadata?.get?.("scope") ?? undefined;
94
- }
95
- }
96
-
97
87
  if (val && typeof val === "object" && !ArrayBuffer.isView(val)) {
98
- const dict: Record<string, any> = { ...(val as Record<string, any>) };
99
- if (key in result) {
100
- throw new Error(
101
- `batchToSecretDict: duplicate secret_type '${key}' (scope=${scope ?? "none"}).`,
102
- );
103
- }
104
- result[key] = dict;
105
- if (scope) result[`${key}:${scope}`] = dict;
106
- } else if (val === null || val === undefined) {
107
- // skip
108
- } else {
109
- result[key] = {};
88
+ result[f.name] = { ...(val as Record<string, any>) };
89
+ } else if (val !== null && val !== undefined) {
90
+ result[f.name] = {};
110
91
  }
111
92
  }
112
93
  return result;
@@ -639,9 +639,12 @@ export class ReadOnlyCatalogInterface extends CatalogInterface {
639
639
  f.defaultOutputSchema ?? schema_([])
640
640
  );
641
641
 
642
- const requiredSecrets = (meta.requiredSecrets ?? []).map(
643
- (secretType: string) => ({ secret_type: secretType, scope: null, secret_name: null })
644
- );
642
+ // Every validated requirement reaches the wire: type, scope and name.
643
+ const requiredSecrets = meta.requiredSecrets.map((s) => ({
644
+ secret_type: s.secretType,
645
+ scope: s.scope,
646
+ secret_name: s.secretName,
647
+ }));
645
648
 
646
649
  // Function-level tags surfaced into duckdb_functions().tags. The wire
647
650
  // map is string→string, so the metadata linter (vgi-lint-check) and any
@@ -13,6 +13,7 @@
13
13
  // aggregate_finalize → emit one result row per group_id
14
14
  // aggregate_destructor → free states (best-effort; see Python worker.py)
15
15
 
16
+ import { normalizeRequiredSecrets, type RequiredSecret } from "../secrets/requirements.js";
16
17
  import { type VgiSchema, schema, type VgiField, field, type VgiBatch, type VgiDataType, nullType, isNull } from "../arrow/index.js";
17
18
  import type { Arguments } from "../arguments/arguments.js";
18
19
  import {
@@ -165,7 +166,7 @@ export interface AggregateFunctionConfig<TArgs = Record<string, any>, TState = a
165
166
  * empty ResolvedSecrets. Mirrors vgi-python's `Secret()` annotation on an
166
167
  * aggregate `on_bind`.
167
168
  */
168
- requiredSecrets?: string[];
169
+ requiredSecrets?: RequiredSecret[];
169
170
  }
170
171
 
171
172
  // Per-execution state registry. Value = (gid → state) + bind context.
@@ -376,7 +377,7 @@ export function defineAggregate<TArgs = Record<string, any>, TState = any>(
376
377
  tags: config.tags,
377
378
  parameterDefaultValues: config.parameterDefaultValues,
378
379
  nullHandling: config.nullHandling as any,
379
- requiredSecrets: config.requiredSecrets,
380
+ requiredSecrets: normalizeRequiredSecrets(config.requiredSecrets, config.name),
380
381
  };
381
382
 
382
383
  // The normal VgiFunction methods (bind/globalInit/createStreamHandlers) are
@@ -19,6 +19,7 @@
19
19
  // arrive as the function's normal named arguments. Mirrors vgi-python's
20
20
  // `vgi.copy_from_function.CopyFromFunction`.
21
21
 
22
+ import { normalizeRequiredSecrets, type RequiredSecret } from "../secrets/requirements.js";
22
23
  import { type VgiSchema, type VgiDataType } from "../arrow/index.js";
23
24
  import type { OutputCollector } from "@query-farm/vgi-rpc";
24
25
  import { DEFAULT_MAX_WORKERS } from "../types.js";
@@ -88,7 +89,7 @@ export interface CopyFromFunctionConfig<TArgs = Record<string, unknown>> {
88
89
  tags?: Record<string, string>;
89
90
  examples?: FunctionExample[];
90
91
  requiredSettings?: string[];
91
- requiredSecrets?: string[];
92
+ requiredSecrets?: RequiredSecret[];
92
93
  /**
93
94
  * Optional secret-bind hook: forward CREATE SECRET credentials for
94
95
  * secret-backed cloud sources (S3/GCS/HTTP/…). Called during bind (only on the
@@ -140,7 +141,7 @@ export function defineCopyFromFunction<TArgs = Record<string, unknown>>(
140
141
  tags: config.tags,
141
142
  examples: config.examples,
142
143
  requiredSettings: config.requiredSettings,
143
- requiredSecrets: config.requiredSecrets,
144
+ requiredSecrets: normalizeRequiredSecrets(config.requiredSecrets, config.name),
144
145
  copyFromFormat: config.format,
145
146
  copyFromDirection: config.direction ?? "from",
146
147
  copyFromComment: config.comment ?? null,
@@ -35,6 +35,7 @@
35
35
  // arguments. The source schema rides `BindRequest.input_schema`. Mirrors
36
36
  // vgi-python's `vgi.copy_to_function.CopyToFunction`.
37
37
 
38
+ import type { RequiredSecret } from "../secrets/requirements.js";
38
39
  import { type VgiSchema, schema, type VgiBatch, type VgiDataType } from "../arrow/index.js";
39
40
  import type { BindRequest } from "../protocol/types.js";
40
41
  import type { FunctionMeta, FunctionExample } from "./types.js";
@@ -134,7 +135,7 @@ export interface CopyToFunctionConfig<TArgs = Record<string, unknown>> {
134
135
  tags?: Record<string, string>;
135
136
  examples?: FunctionExample[];
136
137
  requiredSettings?: string[];
137
- requiredSecrets?: string[];
138
+ requiredSecrets?: RequiredSecret[];
138
139
  /**
139
140
  * Optional secret-bind hook: forward CREATE SECRET credentials for
140
141
  * secret-backed cloud writes (S3/GCS/HTTP/…). Called during bind (only on the
@@ -3,6 +3,7 @@
3
3
  // Scalar functions receive columnar input and produce a single output column
4
4
  // with 1:1 row mapping.
5
5
 
6
+ import { normalizeRequiredSecrets, type RequiredSecret } from "../secrets/requirements.js";
6
7
  import {
7
8
  type VgiSchema,
8
9
  type VgiField,
@@ -203,7 +204,7 @@ export interface ScalarFunctionConfig<
203
204
  parameterDefaultValues?: VgiBatch | null;
204
205
  maxWorkers?: number;
205
206
  requiredSettings?: string[];
206
- requiredSecrets?: string[];
207
+ requiredSecrets?: RequiredSecret[];
207
208
  /**
208
209
  * Result-cache opt-in: when set, this CacheControl's `vgi.cache.*` metadata
209
210
  * rides every output batch's custom metadata (per-batch — NOT the schema,
@@ -331,7 +332,7 @@ export function defineScalarFunction<
331
332
  parameterDefaultValues: config.parameterDefaultValues,
332
333
  maxWorkers: config.maxWorkers,
333
334
  requiredSettings: config.requiredSettings,
334
- requiredSecrets: config.requiredSecrets,
335
+ requiredSecrets: normalizeRequiredSecrets(config.requiredSecrets, config.name),
335
336
  };
336
337
 
337
338
  // Default output schema for catalog registration.
@@ -16,6 +16,7 @@
16
16
  // The Source phase may route a finalize_state_id to a worker process that
17
17
  // did NOT run the corresponding process() calls.
18
18
 
19
+ import { normalizeRequiredSecrets, type RequiredSecret } from "../secrets/requirements.js";
19
20
  import {
20
21
  type VgiSchema,
21
22
  schema,
@@ -179,7 +180,7 @@ export interface TableBufferingConfig<
179
180
  tags?: Record<string, string> | undefined;
180
181
  maxWorkers?: number | undefined;
181
182
  requiredSettings?: string[] | undefined;
182
- requiredSecrets?: string[] | undefined;
183
+ requiredSecrets?: RequiredSecret[] | undefined;
183
184
  }
184
185
 
185
186
  /**
@@ -257,7 +258,7 @@ export function defineTableBufferingFunction<
257
258
  parameterDefaultValues: config.parameterDefaultValues,
258
259
  maxWorkers: config.maxWorkers,
259
260
  requiredSettings: config.requiredSettings,
260
- requiredSecrets: config.requiredSecrets,
261
+ requiredSecrets: normalizeRequiredSecrets(config.requiredSecrets, config.name),
261
262
  // The Source phase always runs (it's how output is produced), so a
262
263
  // table_buffering function always advertises has_finalize.
263
264
  hasFinalize: true,
@@ -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
@@ -262,10 +262,20 @@ export {
262
262
  type SecretsDict,
263
263
  secretType,
264
264
  secretsOfType,
265
+ secretOfType,
266
+ requireSecretOfType,
267
+ secretByName,
265
268
  secretForScope,
266
269
  secretForScopeOfType,
267
270
  } from "./secrets/helpers.js";
268
271
 
272
+ export {
273
+ type RequiredSecret,
274
+ type SecretRequirement,
275
+ type SecretRequirementSpec,
276
+ normalizeRequiredSecrets,
277
+ } from "./secrets/requirements.js";
278
+
269
279
  export {
270
280
  serializeSchema,
271
281
  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;
@@ -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(