@fabric-harness/databricks 4.1.0 → 4.2.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.
package/dist/index.js CHANGED
@@ -1937,13 +1937,13 @@ function connectionResourceName(value) {
1937
1937
  ).join(".")}`;
1938
1938
  }
1939
1939
  function externalBasePath(value) {
1940
- const path = value.trim();
1941
- if (!path.startsWith("/") || path.startsWith("//") || path.includes("?") || path.includes("#")) {
1940
+ const path3 = value.trim();
1941
+ if (!path3.startsWith("/") || path3.startsWith("//") || path3.includes("?") || path3.includes("#")) {
1942
1942
  throw new Error(
1943
1943
  "databricks agent services: basePath must be an absolute URL path without a query or fragment."
1944
1944
  );
1945
1945
  }
1946
- return path;
1946
+ return path3;
1947
1947
  }
1948
1948
  function ucIdentifier(value, label) {
1949
1949
  const normalized = value.trim();
@@ -2356,25 +2356,30 @@ var DATABRICKS_RAW_PROTOCOL_RULES = [
2356
2356
  methods: ["GET"],
2357
2357
  path: /^\/api\/2\.0\/genie\/spaces\/[^/?#]+\/conversations\/[^/?#]+\/messages\/[^/?#]+\/attachments\/[^/?#]+\/query-result$/u
2358
2358
  },
2359
+ {
2360
+ id: "vector-search-query-sdk-compatibility",
2361
+ methods: ["POST"],
2362
+ path: /^\/api\/2\.0\/vector-search\/indexes\/[^/?#]+\/query$/u
2363
+ },
2359
2364
  {
2360
2365
  id: "responses-agent-custom-schema",
2361
2366
  methods: ["POST"],
2362
2367
  path: /^\/serving-endpoints\/[^/?#]+\/invocations$/u
2363
2368
  }
2364
2369
  ];
2365
- function assertRawProtocolAllowed(method, path) {
2370
+ function assertRawProtocolAllowed(method, path3) {
2366
2371
  const normalizedMethod = method.toUpperCase();
2367
- if (!path.startsWith("/") || path.includes("?") || path.includes("#")) {
2372
+ if (!path3.startsWith("/") || path3.includes("?") || path3.includes("#")) {
2368
2373
  throw new Error(
2369
- `databricks raw protocol denied: ${normalizedMethod} ${path}; pass a relative path and structured query parameters.`
2374
+ `databricks raw protocol denied: ${normalizedMethod} ${path3}; pass a relative path and structured query parameters.`
2370
2375
  );
2371
2376
  }
2372
2377
  const rule = DATABRICKS_RAW_PROTOCOL_RULES.find(
2373
- (candidate) => candidate.methods.includes(normalizedMethod) && candidate.path.test(path)
2378
+ (candidate) => candidate.methods.includes(normalizedMethod) && candidate.path.test(path3)
2374
2379
  );
2375
2380
  if (!rule) {
2376
2381
  throw new Error(
2377
- `databricks raw protocol denied: ${normalizedMethod} ${path}; use an official @databricks/sdk-* service client.`
2382
+ `databricks raw protocol denied: ${normalizedMethod} ${path3}; use an official @databricks/sdk-* service client.`
2378
2383
  );
2379
2384
  }
2380
2385
  }
@@ -2395,20 +2400,20 @@ var DatabricksRawProtocolClient = class {
2395
2400
  this.signal = options.signal;
2396
2401
  this.extraHeaders = options.extraHeaders;
2397
2402
  }
2398
- get(path, query, options) {
2399
- return this.requestJson("GET", path, void 0, query, options);
2403
+ get(path3, query, options) {
2404
+ return this.requestJson("GET", path3, void 0, query, options);
2400
2405
  }
2401
- post(path, body, query, options) {
2402
- return this.requestJson("POST", path, body, query, options);
2406
+ post(path3, body, query, options) {
2407
+ return this.requestJson("POST", path3, body, query, options);
2403
2408
  }
2404
- patch(path, body, query, options) {
2405
- return this.requestJson("PATCH", path, body, query, options);
2409
+ patch(path3, body, query, options) {
2410
+ return this.requestJson("PATCH", path3, body, query, options);
2406
2411
  }
2407
- delete(path, body, query, options) {
2408
- return this.requestJson("DELETE", path, body, query, options);
2412
+ delete(path3, body, query, options) {
2413
+ return this.requestJson("DELETE", path3, body, query, options);
2409
2414
  }
2410
- async requestJson(method, path, body, query = {}, options = {}) {
2411
- const response = await this.send(method, path, body, query, options);
2415
+ async requestJson(method, path3, body, query = {}, options = {}) {
2416
+ const response = await this.send(method, path3, body, query, options);
2412
2417
  if (response.status === 204) return void 0;
2413
2418
  return await response.json();
2414
2419
  }
@@ -2416,12 +2421,12 @@ var DatabricksRawProtocolClient = class {
2416
2421
  * Perform an authenticated request while leaving a successful response body unread. This is
2417
2422
  * intended for bounded binary downloads and streaming APIs such as Genie Agent Mode.
2418
2423
  */
2419
- postRaw(path, body, query = {}, options = {}) {
2420
- return this.send("POST", path, body, query, options);
2424
+ postRaw(path3, body, query = {}, options = {}) {
2425
+ return this.send("POST", path3, body, query, options);
2421
2426
  }
2422
- async send(method, path, body, query, options) {
2423
- assertRawProtocolAllowed(method, path);
2424
- const url2 = new URL(`${this.host}${path.startsWith("/") ? path : `/${path}`}`);
2427
+ async send(method, path3, body, query, options) {
2428
+ assertRawProtocolAllowed(method, path3);
2429
+ const url2 = new URL(`${this.host}${path3.startsWith("/") ? path3 : `/${path3}`}`);
2425
2430
  for (const [key, value] of Object.entries(query))
2426
2431
  if (value !== void 0) url2.searchParams.set(key, String(value));
2427
2432
  const canRetry = options.retry === "always" || options.retry !== "never" && (options.retry === "safe" || method === "GET" || method === "HEAD");
@@ -5323,12 +5328,12 @@ function parseStringArray(value, label) {
5323
5328
  throw new Error(`databricks governance: ${label} must be a string array.`);
5324
5329
  return value;
5325
5330
  }
5326
- function pointerSegments(path) {
5327
- return path.slice(1).split("/").map((segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~"));
5331
+ function pointerSegments(path3) {
5332
+ return path3.slice(1).split("/").map((segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~"));
5328
5333
  }
5329
- function pointerValues(input, path) {
5334
+ function pointerValues(input, path3) {
5330
5335
  let current = [input];
5331
- for (const segment of pointerSegments(path)) {
5336
+ for (const segment of pointerSegments(path3)) {
5332
5337
  current = current.flatMap((value) => {
5333
5338
  if (segment === "*") return Array.isArray(value) ? value : [];
5334
5339
  if (!value || typeof value !== "object" || Array.isArray(value)) return [];
@@ -6335,10 +6340,10 @@ function mergeDefs(...defs) {
6335
6340
  function cloneDef(schema) {
6336
6341
  return mergeDefs(schema._zod.def);
6337
6342
  }
6338
- function getElementAtPath(obj, path) {
6339
- if (!path)
6343
+ function getElementAtPath(obj, path3) {
6344
+ if (!path3)
6340
6345
  return obj;
6341
- return path.reduce((acc, key) => acc?.[key], obj);
6346
+ return path3.reduce((acc, key) => acc?.[key], obj);
6342
6347
  }
6343
6348
  function promiseAllObject(promisesObj) {
6344
6349
  const keys = Object.keys(promisesObj);
@@ -6747,11 +6752,11 @@ function explicitlyAborted(x2, startIndex = 0) {
6747
6752
  }
6748
6753
  return false;
6749
6754
  }
6750
- function prefixIssues(path, issues) {
6755
+ function prefixIssues(path3, issues) {
6751
6756
  return issues.map((iss) => {
6752
6757
  var _a3;
6753
6758
  (_a3 = iss).path ?? (_a3.path = []);
6754
- iss.path.unshift(path);
6759
+ iss.path.unshift(path3);
6755
6760
  return iss;
6756
6761
  });
6757
6762
  }
@@ -6898,16 +6903,16 @@ function flattenError(error51, mapper = (issue3) => issue3.message) {
6898
6903
  }
6899
6904
  function formatError(error51, mapper = (issue3) => issue3.message) {
6900
6905
  const fieldErrors = { _errors: [] };
6901
- const processError = (error52, path = []) => {
6906
+ const processError = (error52, path3 = []) => {
6902
6907
  for (const issue3 of error52.issues) {
6903
6908
  if (issue3.code === "invalid_union" && issue3.errors.length) {
6904
- issue3.errors.map((issues) => processError({ issues }, [...path, ...issue3.path]));
6909
+ issue3.errors.map((issues) => processError({ issues }, [...path3, ...issue3.path]));
6905
6910
  } else if (issue3.code === "invalid_key") {
6906
- processError({ issues: issue3.issues }, [...path, ...issue3.path]);
6911
+ processError({ issues: issue3.issues }, [...path3, ...issue3.path]);
6907
6912
  } else if (issue3.code === "invalid_element") {
6908
- processError({ issues: issue3.issues }, [...path, ...issue3.path]);
6913
+ processError({ issues: issue3.issues }, [...path3, ...issue3.path]);
6909
6914
  } else {
6910
- const fullpath = [...path, ...issue3.path];
6915
+ const fullpath = [...path3, ...issue3.path];
6911
6916
  if (fullpath.length === 0) {
6912
6917
  fieldErrors._errors.push(mapper(issue3));
6913
6918
  } else {
@@ -6934,17 +6939,17 @@ function formatError(error51, mapper = (issue3) => issue3.message) {
6934
6939
  }
6935
6940
  function treeifyError(error51, mapper = (issue3) => issue3.message) {
6936
6941
  const result = { errors: [] };
6937
- const processError = (error52, path = []) => {
6942
+ const processError = (error52, path3 = []) => {
6938
6943
  var _a3, _b;
6939
6944
  for (const issue3 of error52.issues) {
6940
6945
  if (issue3.code === "invalid_union" && issue3.errors.length) {
6941
- issue3.errors.map((issues) => processError({ issues }, [...path, ...issue3.path]));
6946
+ issue3.errors.map((issues) => processError({ issues }, [...path3, ...issue3.path]));
6942
6947
  } else if (issue3.code === "invalid_key") {
6943
- processError({ issues: issue3.issues }, [...path, ...issue3.path]);
6948
+ processError({ issues: issue3.issues }, [...path3, ...issue3.path]);
6944
6949
  } else if (issue3.code === "invalid_element") {
6945
- processError({ issues: issue3.issues }, [...path, ...issue3.path]);
6950
+ processError({ issues: issue3.issues }, [...path3, ...issue3.path]);
6946
6951
  } else {
6947
- const fullpath = [...path, ...issue3.path];
6952
+ const fullpath = [...path3, ...issue3.path];
6948
6953
  if (fullpath.length === 0) {
6949
6954
  result.errors.push(mapper(issue3));
6950
6955
  continue;
@@ -6976,8 +6981,8 @@ function treeifyError(error51, mapper = (issue3) => issue3.message) {
6976
6981
  }
6977
6982
  function toDotPath(_path) {
6978
6983
  const segs = [];
6979
- const path = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
6980
- for (const seg of path) {
6984
+ const path3 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
6985
+ for (const seg of path3) {
6981
6986
  if (typeof seg === "number")
6982
6987
  segs.push(`[${seg}]`);
6983
6988
  else if (typeof seg === "symbol")
@@ -19663,13 +19668,13 @@ function resolveRef(ref, ctx) {
19663
19668
  if (!ref.startsWith("#")) {
19664
19669
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
19665
19670
  }
19666
- const path = ref.slice(1).split("/").filter(Boolean);
19667
- if (path.length === 0) {
19671
+ const path3 = ref.slice(1).split("/").filter(Boolean);
19672
+ if (path3.length === 0) {
19668
19673
  return ctx.rootSchema;
19669
19674
  }
19670
19675
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
19671
- if (path[0] === defsKey) {
19672
- const key = path[1];
19676
+ if (path3[0] === defsKey) {
19677
+ const key = path3[1];
19673
19678
  if (!key || !ctx.defs[key]) {
19674
19679
  throw new Error(`Reference not found: ${ref}`);
19675
19680
  }
@@ -20366,10 +20371,10 @@ async function findInPath(name) {
20366
20371
  }
20367
20372
  throw legacyError ?? new U2mCredentialsError("CLI_NOT_FOUND", "databricks CLI not found");
20368
20373
  }
20369
- async function validateCliPath(path) {
20374
+ async function validateCliPath(path3) {
20370
20375
  let info;
20371
20376
  try {
20372
- info = await stat(path);
20377
+ info = await stat(path3);
20373
20378
  } catch {
20374
20379
  throw new U2mCredentialsError("CLI_NOT_FOUND", "databricks CLI not found");
20375
20380
  }
@@ -20379,7 +20384,7 @@ async function validateCliPath(path) {
20379
20384
  if (info.size < DATABRICKS_CLI_MIN_SIZE) {
20380
20385
  throw new U2mCredentialsError("LEGACY_CLI_DETECTED", "legacy databricks CLI detected; upgrade to >= 0.100.0");
20381
20386
  }
20382
- return path;
20387
+ return path3;
20383
20388
  }
20384
20389
 
20385
20390
  // ../../node_modules/.pnpm/@databricks+sdk-core@0.21.0/node_modules/@databricks/sdk-core/dist/profiles/errors.js
@@ -20573,9 +20578,9 @@ function defaultConfigFilePath() {
20573
20578
  return "";
20574
20579
  }
20575
20580
  }
20576
- async function fileExists(path) {
20581
+ async function fileExists(path3) {
20577
20582
  try {
20578
- await access(path);
20583
+ await access(path3);
20579
20584
  return true;
20580
20585
  } catch {
20581
20586
  return false;
@@ -20583,25 +20588,25 @@ async function fileExists(path) {
20583
20588
  }
20584
20589
  async function loadFile(filePath, profileName) {
20585
20590
  let explicitFile = filePath !== void 0;
20586
- let path;
20591
+ let path3;
20587
20592
  if (filePath !== void 0) {
20588
- path = filePath;
20593
+ path3 = filePath;
20589
20594
  } else {
20590
20595
  const envPath = process.env.DATABRICKS_CONFIG_FILE ?? "";
20591
20596
  if (envPath !== "") {
20592
- path = envPath;
20597
+ path3 = envPath;
20593
20598
  explicitFile = true;
20594
20599
  } else {
20595
- path = defaultConfigFilePath();
20600
+ path3 = defaultConfigFilePath();
20596
20601
  }
20597
20602
  }
20598
- if (!await fileExists(path)) {
20603
+ if (!await fileExists(path3)) {
20599
20604
  if (explicitFile) {
20600
- throw new ProfileError("CONFIG_FILE_NOT_FOUND", `config file not found: ${path}`);
20605
+ throw new ProfileError("CONFIG_FILE_NOT_FOUND", `config file not found: ${path3}`);
20601
20606
  }
20602
20607
  return {};
20603
20608
  }
20604
- const content = await readFile(path, "utf8");
20609
+ const content = await readFile(path3, "utf8");
20605
20610
  const data = parseIni(content);
20606
20611
  let resolved = profileName;
20607
20612
  if (resolved === void 0) {
@@ -20627,7 +20632,7 @@ async function loadFile(filePath, profileName) {
20627
20632
  const section = data.get(resolved);
20628
20633
  if (section === void 0 || isPhantomDefault(resolved, section)) {
20629
20634
  if (explicitProfile) {
20630
- throw new ProfileError("PROFILE_NOT_FOUND", `profile not found: "${resolved}" in ${path}`);
20635
+ throw new ProfileError("PROFILE_NOT_FOUND", `profile not found: "${resolved}" in ${path3}`);
20631
20636
  }
20632
20637
  return {};
20633
20638
  }
@@ -35777,8 +35782,8 @@ function parseResponse9(body, schema) {
35777
35782
  function marshalRequest8(data, schema) {
35778
35783
  return jsonBigint8.stringify(schema.parse(data));
35779
35784
  }
35780
- function encodeMultiSegmentPath(path) {
35781
- return path.split("/").map((segment) => encodeURIComponent(segment)).join("/");
35785
+ function encodeMultiSegmentPath(path3) {
35786
+ return path3.split("/").map((segment) => encodeURIComponent(segment)).join("/");
35782
35787
  }
35783
35788
  async function sendAndCheckError2(opts) {
35784
35789
  opts.logger.debug("HTTP request", {
@@ -58804,18 +58809,55 @@ function databricksAiSearch(options) {
58804
58809
  };
58805
58810
  if (opts.filter) body.filtersJson = JSON.stringify(opts.filter);
58806
58811
  if (queryType === "vector") {
58807
- if (!options.embeddings) throw new Error('databricks AI Search: queryType "vector" requires an embeddings provider.');
58812
+ if (!options.embeddings)
58813
+ throw new Error(
58814
+ 'databricks AI Search: queryType "vector" requires an embeddings provider.'
58815
+ );
58808
58816
  const [vector] = await options.embeddings.embed([query]);
58809
- if (!vector) throw new Error("databricks AI Search: embeddings returned no vector for the query.");
58817
+ if (!vector)
58818
+ throw new Error("databricks AI Search: embeddings returned no vector for the query.");
58810
58819
  body.queryVector = vector;
58811
58820
  } else {
58812
58821
  body.queryText = query;
58813
58822
  }
58814
- const response = await options.client.queryVectorIndex(body);
58823
+ const response = await queryVectorIndex(options, body);
58815
58824
  return mapResults(response, options, columns);
58816
58825
  }
58817
58826
  };
58818
58827
  }
58828
+ async function queryVectorIndex(options, body) {
58829
+ try {
58830
+ return await options.client.queryVectorIndex(body);
58831
+ } catch (error51) {
58832
+ if (!options.rawProtocolClient || !isGeneratedFloatingPointDecodeError(error51)) throw error51;
58833
+ const raw = await options.rawProtocolClient.post(
58834
+ `/api/2.0/vector-search/indexes/${encodeURIComponent(options.index)}/query`,
58835
+ {
58836
+ columns: body.columns,
58837
+ num_results: body.numResults,
58838
+ ...body.filtersJson !== void 0 ? { filters_json: body.filtersJson } : {},
58839
+ ...body.queryText !== void 0 ? { query_text: body.queryText } : {},
58840
+ ...body.queryVector !== void 0 ? { query_vector: body.queryVector } : {}
58841
+ },
58842
+ void 0,
58843
+ { retry: "safe" }
58844
+ );
58845
+ return {
58846
+ ...raw.manifest ? { manifest: raw.manifest } : {},
58847
+ ...raw.result ? {
58848
+ result: {
58849
+ ...raw.result.data_array ? { dataArray: raw.result.data_array } : {},
58850
+ ...raw.result.row_count !== void 0 ? { rowCount: raw.result.row_count } : {}
58851
+ }
58852
+ } : {},
58853
+ ...raw.next_page_token ? { nextPageToken: raw.next_page_token } : {}
58854
+ };
58855
+ }
58856
+ }
58857
+ function isGeneratedFloatingPointDecodeError(error51) {
58858
+ const message = error51 instanceof Error ? `${error51.name}: ${error51.message}` : String(error51);
58859
+ return /Cannot convert [-+]?\d+\.\d+(?:e[-+]?\d+)? to a BigInt/iu.test(message);
58860
+ }
58819
58861
  function mapResults(response, options, requestedColumns) {
58820
58862
  const names = (response.manifest?.columns ?? []).map((c2) => c2.name ?? "");
58821
58863
  const requested = new Set(requestedColumns);
@@ -58866,16 +58908,16 @@ var DatabricksWorkspaceAuthoring = class {
58866
58908
  { retry: "never" }
58867
58909
  );
58868
58910
  }
58869
- deleteWorkspaceObject(path, recursive = false) {
58911
+ deleteWorkspaceObject(path3, recursive = false) {
58870
58912
  return this.client.post(
58871
58913
  "/api/2.0/workspace/delete",
58872
- { path, recursive },
58914
+ { path: path3, recursive },
58873
58915
  {},
58874
58916
  { retry: "never" }
58875
58917
  );
58876
58918
  }
58877
- mkdirs(path) {
58878
- return this.client.post("/api/2.0/workspace/mkdirs", { path }, {}, { retry: "safe" });
58919
+ mkdirs(path3) {
58920
+ return this.client.post("/api/2.0/workspace/mkdirs", { path: path3 }, {}, { retry: "safe" });
58879
58921
  }
58880
58922
  };
58881
58923
  function databricksWorkspaceAuthoringTools(client) {
@@ -58954,6 +58996,141 @@ function base643(value) {
58954
58996
  return btoa(String.fromCharCode(...bytes));
58955
58997
  }
58956
58998
 
58999
+ // src/app-deployment.ts
59000
+ import { spawn } from "child_process";
59001
+ import { access as access2 } from "fs/promises";
59002
+ import path from "path";
59003
+ async function validateDatabricksAppArtifact(options) {
59004
+ const artifactDir = path.resolve(options.artifactDir);
59005
+ await access2(path.join(artifactDir, "databricks.yml"));
59006
+ const run = options.run ?? runDatabricksCommand;
59007
+ const args = [
59008
+ "bundle",
59009
+ "validate",
59010
+ ...options.target ? ["--target", options.target] : [],
59011
+ ...options.profile ? ["--profile", options.profile] : []
59012
+ ];
59013
+ const executable = options.executable ?? "databricks";
59014
+ options.onCommand?.({ executable, args });
59015
+ const result = await run(executable, args, {
59016
+ cwd: artifactDir,
59017
+ env: options.env ?? process.env
59018
+ });
59019
+ requireSuccess("Databricks bundle validation", result);
59020
+ return { valid: true, output: lastNonEmptyLine(result.stdout) };
59021
+ }
59022
+ async function deployDatabricksAppArtifact(options) {
59023
+ const artifactDir = path.resolve(options.artifactDir);
59024
+ await access2(path.join(artifactDir, "databricks.yml"));
59025
+ const run = options.run ?? runDatabricksCommand;
59026
+ const profileArgs = options.profile ? ["--profile", options.profile] : [];
59027
+ const env2 = options.env ?? process.env;
59028
+ const executable = options.executable ?? "databricks";
59029
+ const bundleArgs = [
59030
+ "bundle",
59031
+ "deploy",
59032
+ ...options.target ? ["--target", options.target] : [],
59033
+ ...profileArgs
59034
+ ];
59035
+ options.onCommand?.({ executable, args: bundleArgs });
59036
+ const bundle = await run(executable, bundleArgs, { cwd: artifactDir, env: env2 });
59037
+ requireSuccess("Databricks bundle synchronization", bundle);
59038
+ if (options.startBeforeDeploy && options.appName) {
59039
+ const startArgs = ["apps", "start", options.appName, ...profileArgs];
59040
+ options.onCommand?.({ executable, args: startArgs });
59041
+ const start = await run(executable, startArgs, { cwd: artifactDir, env: env2 });
59042
+ requireSuccess("Databricks App compute start", start);
59043
+ }
59044
+ const appArgs = [
59045
+ "apps",
59046
+ "deploy",
59047
+ ...options.appName ? [options.appName] : [],
59048
+ ...options.sourceCodePath ? ["--source-code-path", options.sourceCodePath] : [],
59049
+ ...options.mode ? ["--mode", options.mode] : [],
59050
+ "--skip-validation",
59051
+ "--auto-approve",
59052
+ ...profileArgs
59053
+ ];
59054
+ options.onCommand?.({ executable, args: appArgs });
59055
+ const app = await run(executable, appArgs, { cwd: artifactDir, env: env2 });
59056
+ requireSuccess("Databricks App snapshot activation", app);
59057
+ return {
59058
+ bundleSynchronized: true,
59059
+ appSnapshotActivated: true,
59060
+ bundleOutput: lastNonEmptyLine(bundle.stdout),
59061
+ appOutput: lastNonEmptyLine(app.stdout)
59062
+ };
59063
+ }
59064
+ async function runDatabricksCommand(command, args, options) {
59065
+ return new Promise((resolve2, reject) => {
59066
+ const child = spawn(command, [...args], {
59067
+ cwd: options.cwd,
59068
+ env: options.env,
59069
+ shell: false,
59070
+ stdio: ["ignore", "pipe", "pipe"]
59071
+ });
59072
+ let stdout = "";
59073
+ let stderr = "";
59074
+ child.stdout.on("data", (chunk) => {
59075
+ stdout += chunk.toString();
59076
+ });
59077
+ child.stderr.on("data", (chunk) => {
59078
+ stderr += chunk.toString();
59079
+ });
59080
+ child.once("error", reject);
59081
+ child.once("close", (code) => resolve2({ exitCode: code ?? -1, stdout, stderr }));
59082
+ });
59083
+ }
59084
+ function requireSuccess(label, result) {
59085
+ if (result.exitCode === 0) return;
59086
+ const detail = result.stderr.trim().slice(-2e3);
59087
+ throw new Error(
59088
+ `${label} failed with exit code ${result.exitCode}${detail ? `: ${detail}` : ""}`
59089
+ );
59090
+ }
59091
+ function lastNonEmptyLine(value) {
59092
+ return value.split("\n").map((line) => line.trim()).filter(Boolean).at(-1) ?? "";
59093
+ }
59094
+
59095
+ // src/artifact-digest.ts
59096
+ import { createHash as createHash2 } from "crypto";
59097
+ import { lstat, readFile as readFile2, readdir } from "fs/promises";
59098
+ import path2 from "path";
59099
+ async function digestDatabricksArtifact(target) {
59100
+ const targetInfo = await lstat(target);
59101
+ rejectUnsupportedEntry(target, targetInfo);
59102
+ if (targetInfo.isFile()) {
59103
+ return createHash2("sha256").update(await readFile2(target)).digest("hex");
59104
+ }
59105
+ const hash2 = createHash2("sha256");
59106
+ async function append(directory, relativeDirectory) {
59107
+ for (const name of (await readdir(directory)).sort()) {
59108
+ const candidate = path2.join(directory, name);
59109
+ const relative = path2.join(relativeDirectory, name).replaceAll(path2.sep, "/");
59110
+ const info = await lstat(candidate);
59111
+ rejectUnsupportedEntry(relative, info);
59112
+ if (info.isDirectory()) {
59113
+ hash2.update(`directory\0${relative}\0`);
59114
+ await append(candidate, relative);
59115
+ } else {
59116
+ const bytes = await readFile2(candidate);
59117
+ hash2.update(`file\0${relative}\0${bytes.byteLength}\0`);
59118
+ hash2.update(bytes);
59119
+ }
59120
+ }
59121
+ }
59122
+ await append(target, "");
59123
+ return hash2.digest("hex");
59124
+ }
59125
+ function rejectUnsupportedEntry(entry, info) {
59126
+ if (info.isSymbolicLink()) {
59127
+ throw new Error(`Databricks artifact digest rejects symbolic links: ${entry}`);
59128
+ }
59129
+ if (!info.isFile() && !info.isDirectory()) {
59130
+ throw new Error(`Databricks artifact digest rejects non-file entries: ${entry}`);
59131
+ }
59132
+ }
59133
+
58957
59134
  // src/persistence.ts
58958
59135
  function databricksPersistence(options) {
58959
59136
  const client = isLakebaseClient(options.lakebase) ? options.lakebase : lakebaseClient(options.lakebase);
@@ -59283,17 +59460,17 @@ var UcVolumesAttachmentStore = class {
59283
59460
  return `${this.bytesPath(scope, digest)}.json`;
59284
59461
  }
59285
59462
  // ─── Files API ────────────────────────────────────────────────────────────
59286
- async writeFile(path, bytes) {
59463
+ async writeFile(path3, bytes) {
59287
59464
  await this.client.uploadFile({
59288
- filePath: path,
59465
+ filePath: path3,
59289
59466
  overwrite: true,
59290
59467
  contents: new Blob([viewToBuffer(bytes)]).stream()
59291
59468
  });
59292
59469
  }
59293
59470
  /** Raw file bytes, or `null` when the file does not exist (404). */
59294
- async readFile(path) {
59471
+ async readFile(path3) {
59295
59472
  try {
59296
- const response = await this.client.downloadFile({ filePath: path });
59473
+ const response = await this.client.downloadFile({ filePath: path3 });
59297
59474
  if (!response.contents) return new Uint8Array();
59298
59475
  return new Uint8Array(await new Response(response.contents).arrayBuffer());
59299
59476
  } catch (error51) {
@@ -59302,9 +59479,9 @@ var UcVolumesAttachmentStore = class {
59302
59479
  }
59303
59480
  }
59304
59481
  /** True when the file existed and was deleted; false on 404. */
59305
- async deleteFile(path) {
59482
+ async deleteFile(path3) {
59306
59483
  try {
59307
- await this.client.deleteFile({ filePath: path });
59484
+ await this.client.deleteFile({ filePath: path3 });
59308
59485
  return true;
59309
59486
  } catch (error51) {
59310
59487
  if (isNotFound(error51)) return false;
@@ -59312,14 +59489,14 @@ var UcVolumesAttachmentStore = class {
59312
59489
  }
59313
59490
  }
59314
59491
  /** Immediate children of a directory; empty for a missing directory (404). */
59315
- async listDirectory(path) {
59492
+ async listDirectory(path3) {
59316
59493
  const entries = [];
59317
59494
  let pageToken;
59318
59495
  do {
59319
59496
  let listing;
59320
59497
  try {
59321
59498
  listing = await this.client.listDirectoryContents({
59322
- directoryPath: path,
59499
+ directoryPath: path3,
59323
59500
  ...pageToken ? { pageToken } : {}
59324
59501
  });
59325
59502
  } catch (error51) {
@@ -59475,7 +59652,7 @@ function parseInferenceMode(value) {
59475
59652
  }
59476
59653
 
59477
59654
  // src/app-user-authorization.ts
59478
- import { createHash as createHash2 } from "crypto";
59655
+ import { createHash as createHash3 } from "crypto";
59479
59656
  var DATABRICKS_APP_USER_PERMISSIONS = [
59480
59657
  "agent:invoke",
59481
59658
  "approval:read",
@@ -59491,13 +59668,32 @@ function createDatabricksAppUserAuthenticator(options) {
59491
59668
  if (!Number.isFinite(cacheTtlMs) || cacheTtlMs <= 0)
59492
59669
  throw new Error("cacheTtlMs must be a positive finite number.");
59493
59670
  const permissions = [...options.permissions ?? DATABRICKS_APP_USER_PERMISSIONS];
59671
+ const appAuthorizedCallerIds = new Set(
59672
+ (options.appAuthorizedCallerIds ?? []).map((value) => value.trim()).filter(Boolean)
59673
+ );
59494
59674
  const cache = /* @__PURE__ */ new Map();
59495
59675
  return async (request) => {
59496
59676
  const delegated = onBehalfOfFromHeaders(request.headers);
59497
- if (!delegated) return void 0;
59498
59677
  const now = options.now?.() ?? Date.now();
59678
+ const appPrincipal = options.appPrincipalId?.trim();
59679
+ if (delegated && appPrincipal && appAuthorizedCallerIds.size > 0 && await isAppAuthorizedCaller(request.headers, delegated, appAuthorizedCallerIds)) {
59680
+ return appPrincipalFor(appPrincipal, permissions);
59681
+ }
59682
+ if (!delegated) {
59683
+ const forwarded = options.trustForwardedServicePrincipal ? forwardedIdentity(request.headers) : void 0;
59684
+ const id = forwarded ?? appPrincipal;
59685
+ if (!id) return void 0;
59686
+ if (!forwarded) return appPrincipalFor(id, permissions);
59687
+ return {
59688
+ id,
59689
+ kind: "service-principal",
59690
+ provider: "databricks-apps",
59691
+ tenantId: `databricks-service-principal:${createHash3("sha256").update(id).digest("hex").slice(0, 24)}`,
59692
+ permissions: [...permissions]
59693
+ };
59694
+ }
59499
59695
  const token = await databricksIdentity(delegated)();
59500
- const digest = createHash2("sha256").update(token).digest("hex");
59696
+ const digest = createHash3("sha256").update(token).digest("hex");
59501
59697
  const cached4 = cache.get(digest);
59502
59698
  if (cached4 && cached4.expiresAt > now) return cached4.principal;
59503
59699
  try {
@@ -59508,7 +59704,7 @@ function createDatabricksAppUserAuthenticator(options) {
59508
59704
  ...options.now ? { now: options.now } : {}
59509
59705
  });
59510
59706
  const id = inspection.principal.id;
59511
- const tenantId = options.tenantId?.(inspection) ?? `databricks-user:${createHash2("sha256").update(id).digest("hex").slice(0, 24)}`;
59707
+ const tenantId = options.tenantId?.(inspection) ?? `databricks-user:${createHash3("sha256").update(id).digest("hex").slice(0, 24)}`;
59512
59708
  if (!tenantId) return false;
59513
59709
  const principal = {
59514
59710
  id,
@@ -59531,6 +59727,40 @@ function createDatabricksAppUserAuthenticator(options) {
59531
59727
  }
59532
59728
  };
59533
59729
  }
59730
+ function appPrincipalFor(id, permissions) {
59731
+ return {
59732
+ id,
59733
+ kind: "app-principal",
59734
+ provider: "databricks-apps",
59735
+ tenantId: `databricks-app:${createHash3("sha256").update(id).digest("hex").slice(0, 24)}`,
59736
+ permissions: [...permissions]
59737
+ };
59738
+ }
59739
+ async function isAppAuthorizedCaller(headers, delegated, allowed) {
59740
+ const forwarded = forwardedIdentity(headers);
59741
+ if (forwarded && allowed.has(forwarded)) return true;
59742
+ const claims = jwtIdentityClaims(await databricksIdentity(delegated)());
59743
+ return claims.some((value) => allowed.has(value));
59744
+ }
59745
+ function jwtIdentityClaims(token) {
59746
+ const payload = token.split(".")[1];
59747
+ if (!payload) return [];
59748
+ try {
59749
+ const claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
59750
+ return ["sub", "client_id", "clientId", "azp", "oid"].map((name) => claims[name]).filter((value) => typeof value === "string" && value.length > 0);
59751
+ } catch {
59752
+ return [];
59753
+ }
59754
+ }
59755
+ function forwardedIdentity(headers) {
59756
+ const read = (name) => {
59757
+ if (typeof headers.get === "function")
59758
+ return headers.get(name) ?? void 0;
59759
+ const value = headers[name];
59760
+ return Array.isArray(value) ? value[0] : value;
59761
+ };
59762
+ return (read("x-forwarded-user") ?? read("x-forwarded-preferred-username") ?? read("x-forwarded-email"))?.trim() || void 0;
59763
+ }
59534
59764
  async function inspectDatabricksAppUserAuthorization(options) {
59535
59765
  const delegated = onBehalfOfFromHeaders(options.headers);
59536
59766
  if (!delegated) throw new Error("Databricks App request did not include user authorization.");
@@ -59660,6 +59890,47 @@ ORDER BY last_request_at DESC`;
59660
59890
 
59661
59891
  // src/certification.ts
59662
59892
  import { redactText as redactText2 } from "@fabric-harness/sdk";
59893
+
59894
+ // src/sdk-error.ts
59895
+ function readProperty(value, key) {
59896
+ if (typeof value !== "object" && typeof value !== "function" || value === null)
59897
+ return void 0;
59898
+ try {
59899
+ return Reflect.get(value, key);
59900
+ } catch {
59901
+ return void 0;
59902
+ }
59903
+ }
59904
+ function databricksErrorStatusCode(error51) {
59905
+ for (const key of ["httpStatusCode", "statusCode", "status"]) {
59906
+ const value = readProperty(error51, key);
59907
+ if (typeof value === "number" && Number.isInteger(value) && value >= 100 && value <= 599)
59908
+ return value;
59909
+ if (typeof value === "string" && /^\d{3}$/u.test(value)) return Number(value);
59910
+ }
59911
+ return void 0;
59912
+ }
59913
+ function databricksErrorMessage(error51) {
59914
+ const message = error51 instanceof Error ? error51.message.trim() : "";
59915
+ const status = databricksErrorStatusCode(error51);
59916
+ const codeValue = readProperty(error51, "code") ?? readProperty(error51, "errorCode");
59917
+ const code = typeof codeValue === "string" && codeValue.trim() ? codeValue.trim() : void 0;
59918
+ const body = decodeHttpBody(readProperty(error51, "httpBody"));
59919
+ const metadata = [status !== void 0 ? `HTTP ${status}` : void 0, code].filter((value) => Boolean(value)).join("; ");
59920
+ if (message) return metadata ? `${message} (${metadata})` : message;
59921
+ if (body) return metadata ? `Databricks API error (${metadata}): ${body}` : body;
59922
+ if (metadata) return `Databricks API error (${metadata})`;
59923
+ const fallback = String(error51);
59924
+ return fallback && fallback !== "[object Object]" ? fallback : "Unknown Databricks SDK error.";
59925
+ }
59926
+ function decodeHttpBody(value) {
59927
+ if (!(value instanceof Uint8Array) || value.byteLength === 0) return void 0;
59928
+ const decoded = new TextDecoder().decode(value).trim();
59929
+ if (!decoded) return void 0;
59930
+ return decoded.length > 4096 ? `${decoded.slice(0, 4096)}\u2026` : decoded;
59931
+ }
59932
+
59933
+ // src/certification.ts
59663
59934
  var DATABRICKS_AUTHORING_CERTIFICATION_CHECKS = [
59664
59935
  "approval-provenance",
59665
59936
  "jobs-authoring",
@@ -59788,7 +60059,7 @@ async function runDatabricksAuthoringLifecycle(lifecycle, ledger = new Databrick
59788
60059
  }
59789
60060
  }
59790
60061
  function errorMessage(error51) {
59791
- return error51 instanceof Error ? error51.message : String(error51);
60062
+ return databricksErrorMessage(error51);
59792
60063
  }
59793
60064
  async function runDatabricksCertification(options) {
59794
60065
  const certificationStarted = Date.now();
@@ -59840,7 +60111,7 @@ async function runDatabricksCertification(options) {
59840
60111
  required: requiredCheck,
59841
60112
  status: "failed",
59842
60113
  durationMs: Date.now() - startedAt2,
59843
- error: redactText2(error51 instanceof Error ? error51.message : String(error51), {
60114
+ error: redactText2(databricksErrorMessage(error51), {
59844
60115
  additionalSecrets: options.secrets ?? []
59845
60116
  })
59846
60117
  });
@@ -59851,9 +60122,7 @@ async function runDatabricksCertification(options) {
59851
60122
  failed: results.filter((result) => result.status === "failed").length,
59852
60123
  notConfigured: results.filter((result) => result.status === "not-configured").length
59853
60124
  };
59854
- const passed = results.every(
59855
- (result) => result.required ? result.status === "passed" : result.status !== "failed"
59856
- );
60125
+ const passed = results.every((result) => !result.required || result.status === "passed");
59857
60126
  const certifiedPrincipalKind = options.principalKind ?? results.find((result) => result.id === "identity")?.details?.principalKind;
59858
60127
  const generatedAt = (/* @__PURE__ */ new Date()).toISOString();
59859
60128
  const environmentIdentity = [
@@ -62176,6 +62445,7 @@ function buildDatabricksBundle(config2, scope) {
62176
62445
  });
62177
62446
  retriever = databricksAiSearch({
62178
62447
  client: native.vectorSearch,
62448
+ rawProtocolClient: client,
62179
62449
  index: aiSearch.index,
62180
62450
  textColumn: aiSearch.textColumn,
62181
62451
  ...aiSearch.columns ? { columns: aiSearch.columns } : {},
@@ -62517,6 +62787,8 @@ export {
62517
62787
  databricksWorkspaceOrigin,
62518
62788
  defaultDatabricksCertificationChecks,
62519
62789
  defineDatabricksAgent,
62790
+ deployDatabricksAppArtifact,
62791
+ digestDatabricksArtifact,
62520
62792
  ensureDatabricksTelemetryTables,
62521
62793
  exportAgentEvaluationJsonl,
62522
62794
  exportMlflow3EvaluationJsonl,
@@ -62543,6 +62815,7 @@ export {
62543
62815
  resolveToolRefs,
62544
62816
  runDatabricksAuthoringLifecycle,
62545
62817
  runDatabricksCertification,
62818
+ runDatabricksCommand,
62546
62819
  scoreRagTurn,
62547
62820
  serializeDatabricksGenieAgentSpec,
62548
62821
  servingUsageCapture,
@@ -62551,6 +62824,7 @@ export {
62551
62824
  toAgentEvaluationRecord,
62552
62825
  toMlflow3EvaluationRecord,
62553
62826
  unityCatalogTablesTool,
62827
+ validateDatabricksAppArtifact,
62554
62828
  validateDatabricksCertificationEnvironment,
62555
62829
  validateDatabricksComputePolicy,
62556
62830
  validateDatabricksGenieSqlReferences,