@fabric-harness/databricks 4.1.1 → 4.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/dist/agent-services.js +142 -0
  2. package/dist/agent-services.js.map +1 -0
  3. package/dist/agent.js +1727 -1727
  4. package/dist/agent.js.map +1 -1
  5. package/dist/ai-gateway.js +51 -0
  6. package/dist/ai-gateway.js.map +1 -0
  7. package/dist/ai-search-admin.js +194 -0
  8. package/dist/ai-search-admin.js.map +1 -0
  9. package/dist/ai.js +22 -0
  10. package/dist/ai.js.map +1 -0
  11. package/dist/app-deployment.d.ts +79 -0
  12. package/dist/app-deployment.d.ts.map +1 -0
  13. package/dist/app-user-authorization.js +38942 -0
  14. package/dist/app-user-authorization.js.map +1 -0
  15. package/dist/app.js +143 -0
  16. package/dist/app.js.map +1 -0
  17. package/dist/authoring-certification.js +476 -0
  18. package/dist/authoring-certification.js.map +1 -0
  19. package/dist/capabilities.js +633 -0
  20. package/dist/capabilities.js.map +1 -0
  21. package/dist/certification-resource.js +17 -0
  22. package/dist/certification-resource.js.map +1 -0
  23. package/dist/certification-sweeper.js +128 -0
  24. package/dist/certification-sweeper.js.map +1 -0
  25. package/dist/certification.js +236 -0
  26. package/dist/certification.js.map +1 -0
  27. package/dist/client.d.ts +58 -0
  28. package/dist/client.d.ts.map +1 -0
  29. package/dist/client.js +184 -0
  30. package/dist/client.js.map +1 -0
  31. package/dist/compatibility.js +88 -0
  32. package/dist/compatibility.js.map +1 -0
  33. package/dist/consumption.js +85 -0
  34. package/dist/consumption.js.map +1 -0
  35. package/dist/cost-budget-actuals.js +316 -0
  36. package/dist/cost-budget-actuals.js.map +1 -0
  37. package/dist/embeddings.js +24 -0
  38. package/dist/embeddings.js.map +1 -0
  39. package/dist/feature-serving.js +29 -0
  40. package/dist/feature-serving.js.map +1 -0
  41. package/dist/genie-agent-mode.js +374 -0
  42. package/dist/genie-agent-mode.js.map +1 -0
  43. package/dist/genie-authoring.js +898 -0
  44. package/dist/genie-authoring.js.map +1 -0
  45. package/dist/genie.js +405 -0
  46. package/dist/genie.js.map +1 -0
  47. package/dist/governance.js +353 -0
  48. package/dist/governance.js.map +1 -0
  49. package/dist/identity.js +229 -0
  50. package/dist/identity.js.map +1 -0
  51. package/dist/index.d.ts +4 -1
  52. package/dist/index.d.ts.map +1 -1
  53. package/dist/index.js +1446 -1288
  54. package/dist/index.js.map +1 -1
  55. package/dist/jobs-authoring.js +570 -0
  56. package/dist/jobs-authoring.js.map +1 -0
  57. package/dist/jobs.js +173 -0
  58. package/dist/jobs.js.map +1 -0
  59. package/dist/lakebase.js +110 -0
  60. package/dist/lakebase.js.map +1 -0
  61. package/dist/lakeflow-authoring.js +115 -0
  62. package/dist/lakeflow-authoring.js.map +1 -0
  63. package/dist/lakeflow.js +75 -0
  64. package/dist/lakeflow.js.map +1 -0
  65. package/dist/managed-resource.js +197 -0
  66. package/dist/managed-resource.js.map +1 -0
  67. package/dist/mlflow-tracing.js +167 -0
  68. package/dist/mlflow-tracing.js.map +1 -0
  69. package/dist/mock-provider.js +66 -0
  70. package/dist/mock-provider.js.map +1 -0
  71. package/dist/model.js +173 -0
  72. package/dist/model.js.map +1 -0
  73. package/dist/persistence.js +82 -0
  74. package/dist/persistence.js.map +1 -0
  75. package/dist/rag-chain.js +212 -0
  76. package/dist/rag-chain.js.map +1 -0
  77. package/dist/rag-eval.js +151 -0
  78. package/dist/rag-eval.js.map +1 -0
  79. package/dist/secrets-authoring.js +78 -0
  80. package/dist/secrets-authoring.js.map +1 -0
  81. package/dist/secrets.js +25 -0
  82. package/dist/secrets.js.map +1 -0
  83. package/dist/serving-admin.js +255 -0
  84. package/dist/serving-admin.js.map +1 -0
  85. package/dist/serving-usage.js +100 -0
  86. package/dist/serving-usage.js.map +1 -0
  87. package/dist/sql-exec.js +36 -0
  88. package/dist/sql-exec.js.map +1 -0
  89. package/dist/telemetry-sink.js +180 -0
  90. package/dist/telemetry-sink.js.map +1 -0
  91. package/dist/tools.js +167 -0
  92. package/dist/tools.js.map +1 -0
  93. package/dist/unity-catalog-admin.js +166 -0
  94. package/dist/unity-catalog-admin.js.map +1 -0
  95. package/dist/vector-search.js +65 -0
  96. package/dist/vector-search.js.map +1 -0
  97. package/dist/volumes-attachment-store.js +172 -0
  98. package/dist/volumes-attachment-store.js.map +1 -0
  99. package/dist/workspace-authoring.js +78 -0
  100. package/dist/workspace-authoring.js.map +1 -0
  101. package/package.json +15 -11
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();
@@ -1953,6 +1953,55 @@ function ucIdentifier(value, label) {
1953
1953
  return normalized;
1954
1954
  }
1955
1955
 
1956
+ // src/ai-gateway.ts
1957
+ async function ensureDatabricksAiGateway(client) {
1958
+ await client.get("/api/ai-gateway/v2/endpoints", { page_size: 1 });
1959
+ }
1960
+ async function listDatabricksModelServices(client, options = {}) {
1961
+ const pageSize = positiveInteger(options.pageSize ?? 100, "pageSize");
1962
+ const maxPages = positiveInteger(options.maxPages ?? 100, "maxPages");
1963
+ const requiredPrefix = options.requiredPrefix ?? "system.ai.";
1964
+ const services = /* @__PURE__ */ new Map();
1965
+ const seenTokens = /* @__PURE__ */ new Set();
1966
+ let pageToken;
1967
+ for (let page = 0; page < maxPages; page += 1) {
1968
+ const response = await client.get(
1969
+ "/api/2.1/unity-catalog/model-services",
1970
+ { page_size: pageSize, ...pageToken ? { page_token: pageToken } : {} }
1971
+ );
1972
+ for (const raw of response.model_services ?? []) {
1973
+ const service = normalizeModelService(raw, requiredPrefix);
1974
+ if (service) services.set(service.name, service);
1975
+ }
1976
+ const next = response.next_page_token?.trim();
1977
+ if (!next) return [...services.values()].sort((a2, b2) => a2.name.localeCompare(b2.name));
1978
+ if (seenTokens.has(next))
1979
+ throw new Error(
1980
+ `databricks model-services pagination repeated token after page ${page + 1}.`
1981
+ );
1982
+ seenTokens.add(next);
1983
+ pageToken = next;
1984
+ }
1985
+ throw new Error(`databricks model-services pagination exceeded ${maxPages} pages.`);
1986
+ }
1987
+ function normalizeModelService(raw, requiredPrefix) {
1988
+ const rawName = typeof raw.name === "string" ? raw.name.trim() : "";
1989
+ const name = rawName.replace(/^model-services\//, "");
1990
+ if (!name.startsWith(requiredPrefix)) return void 0;
1991
+ return {
1992
+ name,
1993
+ ...typeof raw.comment === "string" ? { comment: raw.comment } : {},
1994
+ ...typeof raw.creator === "string" ? { creator: raw.creator } : {},
1995
+ ...typeof raw.created_at === "number" ? { createdAt: raw.created_at } : {},
1996
+ ...typeof raw.updated_at === "number" ? { updatedAt: raw.updated_at } : {}
1997
+ };
1998
+ }
1999
+ function positiveInteger(value, name) {
2000
+ if (!Number.isSafeInteger(value) || value <= 0)
2001
+ throw new Error(`${name} must be a positive integer.`);
2002
+ return value;
2003
+ }
2004
+
1956
2005
  // src/ai-search-admin.ts
1957
2006
  var DatabricksAiSearchAdmin = class {
1958
2007
  constructor(client) {
@@ -2193,55 +2242,6 @@ function jitter(ms) {
2193
2242
  return Math.max(1, Math.round(ms * (0.9 + Math.random() * 0.2)));
2194
2243
  }
2195
2244
 
2196
- // src/ai-gateway.ts
2197
- async function ensureDatabricksAiGateway(client) {
2198
- await client.get("/api/ai-gateway/v2/endpoints", { page_size: 1 });
2199
- }
2200
- async function listDatabricksModelServices(client, options = {}) {
2201
- const pageSize = positiveInteger(options.pageSize ?? 100, "pageSize");
2202
- const maxPages = positiveInteger(options.maxPages ?? 100, "maxPages");
2203
- const requiredPrefix = options.requiredPrefix ?? "system.ai.";
2204
- const services = /* @__PURE__ */ new Map();
2205
- const seenTokens = /* @__PURE__ */ new Set();
2206
- let pageToken;
2207
- for (let page = 0; page < maxPages; page += 1) {
2208
- const response = await client.get(
2209
- "/api/2.1/unity-catalog/model-services",
2210
- { page_size: pageSize, ...pageToken ? { page_token: pageToken } : {} }
2211
- );
2212
- for (const raw of response.model_services ?? []) {
2213
- const service = normalizeModelService(raw, requiredPrefix);
2214
- if (service) services.set(service.name, service);
2215
- }
2216
- const next = response.next_page_token?.trim();
2217
- if (!next) return [...services.values()].sort((a2, b2) => a2.name.localeCompare(b2.name));
2218
- if (seenTokens.has(next))
2219
- throw new Error(
2220
- `databricks model-services pagination repeated token after page ${page + 1}.`
2221
- );
2222
- seenTokens.add(next);
2223
- pageToken = next;
2224
- }
2225
- throw new Error(`databricks model-services pagination exceeded ${maxPages} pages.`);
2226
- }
2227
- function normalizeModelService(raw, requiredPrefix) {
2228
- const rawName = typeof raw.name === "string" ? raw.name.trim() : "";
2229
- const name = rawName.replace(/^model-services\//, "");
2230
- if (!name.startsWith(requiredPrefix)) return void 0;
2231
- return {
2232
- name,
2233
- ...typeof raw.comment === "string" ? { comment: raw.comment } : {},
2234
- ...typeof raw.creator === "string" ? { creator: raw.creator } : {},
2235
- ...typeof raw.created_at === "number" ? { createdAt: raw.created_at } : {},
2236
- ...typeof raw.updated_at === "number" ? { updatedAt: raw.updated_at } : {}
2237
- };
2238
- }
2239
- function positiveInteger(value, name) {
2240
- if (!Number.isSafeInteger(value) || value <= 0)
2241
- throw new Error(`${name} must be a positive integer.`);
2242
- return value;
2243
- }
2244
-
2245
2245
  // src/sql-exec.ts
2246
2246
  var TERMINAL_STATES = /* @__PURE__ */ new Set(["SUCCEEDED", "FAILED", "CANCELED", "CLOSED"]);
2247
2247
  async function runStatement(client, warehouseId, statement, parameters, poll) {
@@ -2300,199 +2300,6 @@ function databricksAiQueryTool(client, options) {
2300
2300
  };
2301
2301
  }
2302
2302
 
2303
- // src/raw-protocol-client.ts
2304
- import { redactText } from "@fabric-harness/sdk";
2305
-
2306
- // src/workspace-origin.ts
2307
- function databricksWorkspaceOrigin(host) {
2308
- const value = host.trim();
2309
- if (!value) throw new Error("databricks: workspace host cannot be empty.");
2310
- const url2 = new URL(value.includes("://") ? value : `https://${value}`);
2311
- if (url2.username || url2.password)
2312
- throw new Error("databricks: workspace host must not contain credentials.");
2313
- return url2.origin;
2314
- }
2315
-
2316
- // src/raw-protocol-client.ts
2317
- function isRetryableStatus(status) {
2318
- return status === 429 || status === 499 || status >= 500 && status <= 599;
2319
- }
2320
- function retryDelayMs(response, attempt, base2) {
2321
- const retryAfter = response.headers.get("retry-after");
2322
- if (retryAfter) {
2323
- const seconds = Number(retryAfter);
2324
- if (Number.isFinite(seconds)) return seconds * 1e3;
2325
- }
2326
- return base2 * 2 ** attempt;
2327
- }
2328
- var DATABRICKS_RAW_PROTOCOL_RULES = [
2329
- {
2330
- id: "workspace-objects",
2331
- methods: ["GET", "POST"],
2332
- path: /^\/api\/2\.0\/workspace\/(?:delete|export|get-status|import|list|mkdirs)$/u
2333
- },
2334
- {
2335
- id: "mlflow-traces-v3",
2336
- methods: ["POST"],
2337
- path: /^\/api\/3\.0\/mlflow\/traces$/u
2338
- },
2339
- {
2340
- id: "ai-gateway-discovery",
2341
- methods: ["GET"],
2342
- path: /^\/api\/(?:ai-gateway\/v2\/endpoints|2\.1\/unity-catalog\/model-services)$/u
2343
- },
2344
- {
2345
- id: "agent-services-beta",
2346
- methods: ["GET", "POST", "PATCH", "DELETE"],
2347
- path: /^\/api\/2\.1\/unity-catalog\/(?:agent-services(?:\/[^/?#]+)?|permissions\/AGENT_SERVICE\/[^/?#]+)$/u
2348
- },
2349
- {
2350
- id: "genie-agent-mode-beta",
2351
- methods: ["GET", "POST"],
2352
- path: /^\/api\/2\.0\/genie\/agents\/[^/?#]+\/(?:responses|conversations\/[^/?#]+\/items)$/u
2353
- },
2354
- {
2355
- id: "genie-query-result-sdk-compatibility",
2356
- methods: ["GET"],
2357
- path: /^\/api\/2\.0\/genie\/spaces\/[^/?#]+\/conversations\/[^/?#]+\/messages\/[^/?#]+\/attachments\/[^/?#]+\/query-result$/u
2358
- },
2359
- {
2360
- id: "vector-search-query-sdk-compatibility",
2361
- methods: ["POST"],
2362
- path: /^\/api\/2\.0\/vector-search\/indexes\/[^/?#]+\/query$/u
2363
- },
2364
- {
2365
- id: "responses-agent-custom-schema",
2366
- methods: ["POST"],
2367
- path: /^\/serving-endpoints\/[^/?#]+\/invocations$/u
2368
- }
2369
- ];
2370
- function assertRawProtocolAllowed(method, path) {
2371
- const normalizedMethod = method.toUpperCase();
2372
- if (!path.startsWith("/") || path.includes("?") || path.includes("#")) {
2373
- throw new Error(
2374
- `databricks raw protocol denied: ${normalizedMethod} ${path}; pass a relative path and structured query parameters.`
2375
- );
2376
- }
2377
- const rule = DATABRICKS_RAW_PROTOCOL_RULES.find(
2378
- (candidate) => candidate.methods.includes(normalizedMethod) && candidate.path.test(path)
2379
- );
2380
- if (!rule) {
2381
- throw new Error(
2382
- `databricks raw protocol denied: ${normalizedMethod} ${path}; use an official @databricks/sdk-* service client.`
2383
- );
2384
- }
2385
- }
2386
- var DatabricksRawProtocolClient = class {
2387
- host;
2388
- token;
2389
- fetchImpl;
2390
- maxRetries;
2391
- retryBaseDelayMs;
2392
- signal;
2393
- extraHeaders;
2394
- constructor(options) {
2395
- this.host = databricksWorkspaceOrigin(options.host);
2396
- this.token = options.token;
2397
- this.fetchImpl = options.fetchImpl ?? fetch;
2398
- this.maxRetries = options.maxRetries ?? 3;
2399
- this.retryBaseDelayMs = options.retryBaseDelayMs ?? 500;
2400
- this.signal = options.signal;
2401
- this.extraHeaders = options.extraHeaders;
2402
- }
2403
- get(path, query, options) {
2404
- return this.requestJson("GET", path, void 0, query, options);
2405
- }
2406
- post(path, body, query, options) {
2407
- return this.requestJson("POST", path, body, query, options);
2408
- }
2409
- patch(path, body, query, options) {
2410
- return this.requestJson("PATCH", path, body, query, options);
2411
- }
2412
- delete(path, body, query, options) {
2413
- return this.requestJson("DELETE", path, body, query, options);
2414
- }
2415
- async requestJson(method, path, body, query = {}, options = {}) {
2416
- const response = await this.send(method, path, body, query, options);
2417
- if (response.status === 204) return void 0;
2418
- return await response.json();
2419
- }
2420
- /**
2421
- * Perform an authenticated request while leaving a successful response body unread. This is
2422
- * intended for bounded binary downloads and streaming APIs such as Genie Agent Mode.
2423
- */
2424
- postRaw(path, body, query = {}, options = {}) {
2425
- return this.send("POST", path, body, query, options);
2426
- }
2427
- async send(method, path, body, query, options) {
2428
- assertRawProtocolAllowed(method, path);
2429
- const url2 = new URL(`${this.host}${path.startsWith("/") ? path : `/${path}`}`);
2430
- for (const [key, value] of Object.entries(query))
2431
- if (value !== void 0) url2.searchParams.set(key, String(value));
2432
- const canRetry = options.retry === "always" || options.retry !== "never" && (options.retry === "safe" || method === "GET" || method === "HEAD");
2433
- const maxRetries = canRetry ? options.maxRetries ?? this.maxRetries : 0;
2434
- const signal = combineAbortSignals(this.signal, options.signal);
2435
- for (let attempt = 0; ; attempt += 1) {
2436
- const token = typeof this.token === "function" ? await this.token() : this.token;
2437
- const extra = typeof this.extraHeaders === "function" ? await this.extraHeaders() : this.extraHeaders;
2438
- const init = {
2439
- method,
2440
- headers: {
2441
- authorization: `Bearer ${token}`,
2442
- ...options.accept ? { accept: options.accept } : {},
2443
- ...body !== void 0 ? { "content-type": "application/json" } : {},
2444
- ...extra
2445
- },
2446
- ...body !== void 0 ? { body: JSON.stringify(body) } : {},
2447
- ...signal ? { signal } : {}
2448
- };
2449
- let response;
2450
- try {
2451
- response = await this.fetchImpl(url2, init);
2452
- } catch (error51) {
2453
- if (signal?.aborted || attempt >= maxRetries) throw error51;
2454
- await abortableSleep(this.retryBaseDelayMs * 2 ** attempt, signal);
2455
- continue;
2456
- }
2457
- if (response.ok) {
2458
- return response;
2459
- }
2460
- if (isRetryableStatus(response.status) && attempt < maxRetries) {
2461
- await response.body?.cancel();
2462
- await abortableSleep(retryDelayMs(response, attempt, this.retryBaseDelayMs), signal);
2463
- continue;
2464
- }
2465
- const text = redactText(await response.text(), { additionalSecrets: [token] });
2466
- throw new Error(
2467
- `databricks: ${response.status} ${response.statusText}: ${text.slice(0, 2e3)}`
2468
- );
2469
- }
2470
- }
2471
- };
2472
- function combineAbortSignals(clientSignal, requestSignal) {
2473
- if (!clientSignal) return requestSignal;
2474
- if (!requestSignal || requestSignal === clientSignal) return clientSignal;
2475
- return AbortSignal.any([clientSignal, requestSignal]);
2476
- }
2477
- function abortableSleep(ms, signal) {
2478
- if (signal?.aborted)
2479
- return Promise.reject(
2480
- signal.reason ?? new DOMException("The operation was aborted.", "AbortError")
2481
- );
2482
- if (!signal) return new Promise((resolve2) => setTimeout(resolve2, ms));
2483
- return new Promise((resolve2, reject) => {
2484
- const timer = setTimeout(() => {
2485
- signal.removeEventListener("abort", abort);
2486
- resolve2();
2487
- }, ms);
2488
- const abort = () => {
2489
- clearTimeout(timer);
2490
- reject(signal.reason ?? new DOMException("The operation was aborted.", "AbortError"));
2491
- };
2492
- signal.addEventListener("abort", abort, { once: true });
2493
- });
2494
- }
2495
-
2496
2303
  // src/consumption.ts
2497
2304
  var GROUP_COLUMNS = {
2498
2305
  sku: { select: "u.sku_name AS sku, u.usage_unit AS unit", group: "u.sku_name, u.usage_unit" },
@@ -4752,7 +4559,7 @@ var DatabricksGenieClient = class {
4752
4559
  const remaining = deadline - Date.now();
4753
4560
  if (remaining <= 0)
4754
4561
  throw new DatabricksGenieTimeoutError(conversationId, messageId, timeoutMs);
4755
- await abortableSleep2(
4562
+ await abortableSleep(
4756
4563
  Math.min(jitter2(this.pollIntervalMs, this.pollJitterRatio), remaining),
4757
4564
  options.signal
4758
4565
  );
@@ -5070,7 +4877,7 @@ function throwIfAborted(signal) {
5070
4877
  if (signal?.aborted)
5071
4878
  throw signal.reason ?? new DOMException("The operation was aborted.", "AbortError");
5072
4879
  }
5073
- function abortableSleep2(ms, signal) {
4880
+ function abortableSleep(ms, signal) {
5074
4881
  throwIfAborted(signal);
5075
4882
  if (!signal) return new Promise((resolve2) => setTimeout(resolve2, ms));
5076
4883
  return new Promise((resolve2, reject) => {
@@ -5328,12 +5135,12 @@ function parseStringArray(value, label) {
5328
5135
  throw new Error(`databricks governance: ${label} must be a string array.`);
5329
5136
  return value;
5330
5137
  }
5331
- function pointerSegments(path) {
5332
- return path.slice(1).split("/").map((segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~"));
5138
+ function pointerSegments(path3) {
5139
+ return path3.slice(1).split("/").map((segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~"));
5333
5140
  }
5334
- function pointerValues(input, path) {
5141
+ function pointerValues(input, path3) {
5335
5142
  let current = [input];
5336
- for (const segment of pointerSegments(path)) {
5143
+ for (const segment of pointerSegments(path3)) {
5337
5144
  current = current.flatMap((value) => {
5338
5145
  if (segment === "*") return Array.isArray(value) ? value : [];
5339
5146
  if (!value || typeof value !== "object" || Array.isArray(value)) return [];
@@ -6340,10 +6147,10 @@ function mergeDefs(...defs) {
6340
6147
  function cloneDef(schema) {
6341
6148
  return mergeDefs(schema._zod.def);
6342
6149
  }
6343
- function getElementAtPath(obj, path) {
6344
- if (!path)
6150
+ function getElementAtPath(obj, path3) {
6151
+ if (!path3)
6345
6152
  return obj;
6346
- return path.reduce((acc, key) => acc?.[key], obj);
6153
+ return path3.reduce((acc, key) => acc?.[key], obj);
6347
6154
  }
6348
6155
  function promiseAllObject(promisesObj) {
6349
6156
  const keys = Object.keys(promisesObj);
@@ -6752,11 +6559,11 @@ function explicitlyAborted(x2, startIndex = 0) {
6752
6559
  }
6753
6560
  return false;
6754
6561
  }
6755
- function prefixIssues(path, issues) {
6562
+ function prefixIssues(path3, issues) {
6756
6563
  return issues.map((iss) => {
6757
6564
  var _a3;
6758
6565
  (_a3 = iss).path ?? (_a3.path = []);
6759
- iss.path.unshift(path);
6566
+ iss.path.unshift(path3);
6760
6567
  return iss;
6761
6568
  });
6762
6569
  }
@@ -6903,16 +6710,16 @@ function flattenError(error51, mapper = (issue3) => issue3.message) {
6903
6710
  }
6904
6711
  function formatError(error51, mapper = (issue3) => issue3.message) {
6905
6712
  const fieldErrors = { _errors: [] };
6906
- const processError = (error52, path = []) => {
6713
+ const processError = (error52, path3 = []) => {
6907
6714
  for (const issue3 of error52.issues) {
6908
6715
  if (issue3.code === "invalid_union" && issue3.errors.length) {
6909
- issue3.errors.map((issues) => processError({ issues }, [...path, ...issue3.path]));
6716
+ issue3.errors.map((issues) => processError({ issues }, [...path3, ...issue3.path]));
6910
6717
  } else if (issue3.code === "invalid_key") {
6911
- processError({ issues: issue3.issues }, [...path, ...issue3.path]);
6718
+ processError({ issues: issue3.issues }, [...path3, ...issue3.path]);
6912
6719
  } else if (issue3.code === "invalid_element") {
6913
- processError({ issues: issue3.issues }, [...path, ...issue3.path]);
6720
+ processError({ issues: issue3.issues }, [...path3, ...issue3.path]);
6914
6721
  } else {
6915
- const fullpath = [...path, ...issue3.path];
6722
+ const fullpath = [...path3, ...issue3.path];
6916
6723
  if (fullpath.length === 0) {
6917
6724
  fieldErrors._errors.push(mapper(issue3));
6918
6725
  } else {
@@ -6939,17 +6746,17 @@ function formatError(error51, mapper = (issue3) => issue3.message) {
6939
6746
  }
6940
6747
  function treeifyError(error51, mapper = (issue3) => issue3.message) {
6941
6748
  const result = { errors: [] };
6942
- const processError = (error52, path = []) => {
6749
+ const processError = (error52, path3 = []) => {
6943
6750
  var _a3, _b;
6944
6751
  for (const issue3 of error52.issues) {
6945
6752
  if (issue3.code === "invalid_union" && issue3.errors.length) {
6946
- issue3.errors.map((issues) => processError({ issues }, [...path, ...issue3.path]));
6753
+ issue3.errors.map((issues) => processError({ issues }, [...path3, ...issue3.path]));
6947
6754
  } else if (issue3.code === "invalid_key") {
6948
- processError({ issues: issue3.issues }, [...path, ...issue3.path]);
6755
+ processError({ issues: issue3.issues }, [...path3, ...issue3.path]);
6949
6756
  } else if (issue3.code === "invalid_element") {
6950
- processError({ issues: issue3.issues }, [...path, ...issue3.path]);
6757
+ processError({ issues: issue3.issues }, [...path3, ...issue3.path]);
6951
6758
  } else {
6952
- const fullpath = [...path, ...issue3.path];
6759
+ const fullpath = [...path3, ...issue3.path];
6953
6760
  if (fullpath.length === 0) {
6954
6761
  result.errors.push(mapper(issue3));
6955
6762
  continue;
@@ -6981,8 +6788,8 @@ function treeifyError(error51, mapper = (issue3) => issue3.message) {
6981
6788
  }
6982
6789
  function toDotPath(_path) {
6983
6790
  const segs = [];
6984
- const path = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
6985
- for (const seg of path) {
6791
+ const path3 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
6792
+ for (const seg of path3) {
6986
6793
  if (typeof seg === "number")
6987
6794
  segs.push(`[${seg}]`);
6988
6795
  else if (typeof seg === "symbol")
@@ -19668,13 +19475,13 @@ function resolveRef(ref, ctx) {
19668
19475
  if (!ref.startsWith("#")) {
19669
19476
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
19670
19477
  }
19671
- const path = ref.slice(1).split("/").filter(Boolean);
19672
- if (path.length === 0) {
19478
+ const path3 = ref.slice(1).split("/").filter(Boolean);
19479
+ if (path3.length === 0) {
19673
19480
  return ctx.rootSchema;
19674
19481
  }
19675
19482
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
19676
- if (path[0] === defsKey) {
19677
- const key = path[1];
19483
+ if (path3[0] === defsKey) {
19484
+ const key = path3[1];
19678
19485
  if (!key || !ctx.defs[key]) {
19679
19486
  throw new Error(`Reference not found: ${ref}`);
19680
19487
  }
@@ -20371,10 +20178,10 @@ async function findInPath(name) {
20371
20178
  }
20372
20179
  throw legacyError ?? new U2mCredentialsError("CLI_NOT_FOUND", "databricks CLI not found");
20373
20180
  }
20374
- async function validateCliPath(path) {
20181
+ async function validateCliPath(path3) {
20375
20182
  let info;
20376
20183
  try {
20377
- info = await stat(path);
20184
+ info = await stat(path3);
20378
20185
  } catch {
20379
20186
  throw new U2mCredentialsError("CLI_NOT_FOUND", "databricks CLI not found");
20380
20187
  }
@@ -20384,7 +20191,7 @@ async function validateCliPath(path) {
20384
20191
  if (info.size < DATABRICKS_CLI_MIN_SIZE) {
20385
20192
  throw new U2mCredentialsError("LEGACY_CLI_DETECTED", "legacy databricks CLI detected; upgrade to >= 0.100.0");
20386
20193
  }
20387
- return path;
20194
+ return path3;
20388
20195
  }
20389
20196
 
20390
20197
  // ../../node_modules/.pnpm/@databricks+sdk-core@0.21.0/node_modules/@databricks/sdk-core/dist/profiles/errors.js
@@ -20578,9 +20385,9 @@ function defaultConfigFilePath() {
20578
20385
  return "";
20579
20386
  }
20580
20387
  }
20581
- async function fileExists(path) {
20388
+ async function fileExists(path3) {
20582
20389
  try {
20583
- await access(path);
20390
+ await access(path3);
20584
20391
  return true;
20585
20392
  } catch {
20586
20393
  return false;
@@ -20588,25 +20395,25 @@ async function fileExists(path) {
20588
20395
  }
20589
20396
  async function loadFile(filePath, profileName) {
20590
20397
  let explicitFile = filePath !== void 0;
20591
- let path;
20398
+ let path3;
20592
20399
  if (filePath !== void 0) {
20593
- path = filePath;
20400
+ path3 = filePath;
20594
20401
  } else {
20595
20402
  const envPath = process.env.DATABRICKS_CONFIG_FILE ?? "";
20596
20403
  if (envPath !== "") {
20597
- path = envPath;
20404
+ path3 = envPath;
20598
20405
  explicitFile = true;
20599
20406
  } else {
20600
- path = defaultConfigFilePath();
20407
+ path3 = defaultConfigFilePath();
20601
20408
  }
20602
20409
  }
20603
- if (!await fileExists(path)) {
20410
+ if (!await fileExists(path3)) {
20604
20411
  if (explicitFile) {
20605
- throw new ProfileError("CONFIG_FILE_NOT_FOUND", `config file not found: ${path}`);
20412
+ throw new ProfileError("CONFIG_FILE_NOT_FOUND", `config file not found: ${path3}`);
20606
20413
  }
20607
20414
  return {};
20608
20415
  }
20609
- const content = await readFile(path, "utf8");
20416
+ const content = await readFile(path3, "utf8");
20610
20417
  const data = parseIni(content);
20611
20418
  let resolved = profileName;
20612
20419
  if (resolved === void 0) {
@@ -20632,7 +20439,7 @@ async function loadFile(filePath, profileName) {
20632
20439
  const section = data.get(resolved);
20633
20440
  if (section === void 0 || isPhantomDefault(resolved, section)) {
20634
20441
  if (explicitProfile) {
20635
- throw new ProfileError("PROFILE_NOT_FOUND", `profile not found: "${resolved}" in ${path}`);
20442
+ throw new ProfileError("PROFILE_NOT_FOUND", `profile not found: "${resolved}" in ${path3}`);
20636
20443
  }
20637
20444
  return {};
20638
20445
  }
@@ -20791,6 +20598,16 @@ function defaultCredentials(options) {
20791
20598
  return new DefaultCredentials(STRATEGIES, loadProfile);
20792
20599
  }
20793
20600
 
20601
+ // src/workspace-origin.ts
20602
+ function databricksWorkspaceOrigin(host) {
20603
+ const value = host.trim();
20604
+ if (!value) throw new Error("databricks: workspace host cannot be empty.");
20605
+ const url2 = new URL(value.includes("://") ? value : `https://${value}`);
20606
+ if (url2.username || url2.password)
20607
+ throw new Error("databricks: workspace host must not contain credentials.");
20608
+ return url2.origin;
20609
+ }
20610
+
20794
20611
  // src/identity.ts
20795
20612
  function databricksCredentials(principal) {
20796
20613
  if (principal.kind === "pat") return newPatCredentials(principal.token);
@@ -21596,306 +21413,908 @@ function submitSchema() {
21596
21413
  };
21597
21414
  }
21598
21415
 
21599
- // ../../node_modules/.pnpm/@databricks+sdk-core@0.21.0/node_modules/@databricks/sdk-core/dist/clientinfo/clientinfo.js
21600
- var ClientInfoError = class extends Error {
21601
- code;
21602
- constructor(code, message) {
21603
- super(message);
21604
- this.name = "ClientInfoError";
21605
- this.code = code;
21606
- }
21607
- };
21608
- var SEMVER_CORE = String.raw`(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)`;
21609
- var SEMVER_PRERELEASE = String.raw`(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?`;
21610
- var SEMVER_BUILDMETADATA = String.raw`(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?`;
21611
- var REGEXP_SEMVER = new RegExp("^" + SEMVER_CORE + SEMVER_PRERELEASE + SEMVER_BUILDMETADATA + "$");
21612
- var REGEXP_VALID_SEGMENT = /^[-0-9A-Za-z_.+]+$/;
21613
- var REGEXP_INVALID_SEGMENT_CHAR = /[^-0-9A-Za-z_.+]/g;
21614
- function isValidSegment(s2) {
21615
- return REGEXP_VALID_SEGMENT.test(s2);
21616
- }
21617
- function sanitize(s2) {
21618
- return s2.replace(REGEXP_INVALID_SEGMENT_CHAR, "-");
21619
- }
21620
- var ClientInfo = class _ClientInfo {
21621
- static EMPTY = new _ClientInfo();
21622
- segments;
21623
- constructor(segments = []) {
21624
- this.segments = [...segments];
21625
- }
21626
- /**
21627
- * Returns a new {@link ClientInfo} with the given items appended. Accepts
21628
- * either individual key/value pairs or another {@link ClientInfo} whose
21629
- * segments are merged in order. The original is not modified; mixing the
21630
- * two forms in a single call is supported.
21631
- *
21632
- * Keys and values on pair arguments must contain only alphanumeric
21633
- * characters plus `_`, `.`, `+`, or `-`. Exact key+value duplicates are
21634
- * silently ignored. On error, an exception is thrown (all-or-nothing).
21635
- *
21636
- * @example
21637
- * ```ts
21638
- * base.with({key: 'partner', value: 'acme'});
21639
- * base.with(pkgClientInfo);
21640
- * base.with(pkgClientInfo, {key: 'sdk-feature', value: 'pagination'});
21641
- * ```
21642
- */
21643
- with(...items) {
21644
- if (items.length === 0) {
21645
- return this;
21416
+ // src/lakebase.ts
21417
+ import { createRequire } from "module";
21418
+ var require2 = createRequire(import.meta.url);
21419
+ function lakebaseCredentialProvider(options) {
21420
+ const now = options.now ?? Date.now;
21421
+ const random = options.random ?? Math.random;
21422
+ const refreshBeforeMs = options.refreshBeforeMs ?? 5 * 6e4;
21423
+ const refreshJitterMs = options.refreshJitterMs ?? 3e4;
21424
+ let cached4;
21425
+ let refreshing;
21426
+ const refresh = async () => {
21427
+ const value = await options.client.generateDatabaseCredential({ endpoint: options.endpoint });
21428
+ if (typeof value.token !== "string" || !value.token) {
21429
+ throw new Error("Lakebase credential exchange returned no token.");
21646
21430
  }
21647
- const newSegments = [...this.segments];
21648
- for (const item of items) {
21649
- const pairs = item instanceof _ClientInfo ? item.segments : [item];
21650
- for (const { key, value } of pairs) {
21651
- if (!isValidSegment(key)) {
21652
- throw new ClientInfoError("INVALID_KEY", `Invalid key: ${key}.`);
21653
- }
21654
- if (!isValidSegment(value)) {
21655
- throw new ClientInfoError("INVALID_VALUE", `Invalid value for "${key}": ${value}.`);
21656
- }
21657
- if (newSegments.some((s2) => s2.key === key && s2.value === value)) {
21658
- continue;
21659
- }
21660
- newSegments.push({ key, value });
21661
- }
21431
+ const expiresAt = value.expireTime?.epochMilliseconds ?? Number.NaN;
21432
+ if (!Number.isFinite(expiresAt)) {
21433
+ throw new Error("Lakebase credential exchange returned an invalid expire_time.");
21662
21434
  }
21663
- return new _ClientInfo(newSegments);
21664
- }
21665
- /**
21666
- * Returns a string representation of the client info suitable for
21667
- * inclusion in HTTP headers. Key/value pairs are formatted as
21668
- * "key/value" and joined by spaces in the order they were inserted.
21669
- */
21670
- toString() {
21671
- return this.segments.map((s2) => `${s2.key}/${s2.value}`).join(" ");
21672
- }
21673
- };
21674
-
21675
- // ../../node_modules/.pnpm/@databricks+sdk-core@0.21.0/node_modules/@databricks/sdk-core/package.json
21676
- var package_default2 = {
21677
- name: "@databricks/sdk-core",
21678
- version: "0.21.0",
21679
- description: "Databricks core library for JavaScript/TypeScript",
21680
- type: "module",
21681
- main: "./dist/index.js",
21682
- types: "./dist/index.d.ts",
21683
- exports: {
21684
- ".": {
21685
- types: "./dist/index.d.ts",
21686
- import: "./dist/index.js",
21687
- default: "./dist/index.js"
21688
- },
21689
- "./profiles": {
21690
- types: "./dist/profiles/index.d.ts",
21691
- import: "./dist/profiles/index.js",
21692
- default: "./dist/profiles/index.js"
21693
- },
21694
- "./profiles/browser": {
21695
- types: "./dist/profiles/index.browser.d.ts",
21696
- import: "./dist/profiles/index.browser.js",
21697
- default: "./dist/profiles/index.browser.js"
21698
- },
21699
- "./wkt": {
21700
- types: "./dist/wkt/index.d.ts",
21701
- import: "./dist/wkt/index.js",
21702
- default: "./dist/wkt/index.js"
21703
- },
21704
- "./clientinfo": {
21705
- browser: {
21706
- types: "./dist/clientinfo/index.browser.d.ts",
21707
- import: "./dist/clientinfo/index.browser.js",
21708
- default: "./dist/clientinfo/index.browser.js"
21709
- },
21710
- default: {
21711
- types: "./dist/clientinfo/index.d.ts",
21712
- import: "./dist/clientinfo/index.js",
21713
- default: "./dist/clientinfo/index.js"
21714
- }
21715
- },
21716
- "./clientinfo/browser": {
21717
- types: "./dist/clientinfo/index.browser.d.ts",
21718
- import: "./dist/clientinfo/index.browser.js",
21719
- default: "./dist/clientinfo/index.browser.js"
21720
- },
21721
- "./http": {
21722
- types: "./dist/http/index.d.ts",
21723
- import: "./dist/http/index.js",
21724
- default: "./dist/http/index.js"
21725
- },
21726
- "./logger": {
21727
- types: "./dist/logger/index.d.ts",
21728
- import: "./dist/logger/index.js",
21729
- default: "./dist/logger/index.js"
21730
- },
21731
- "./ops": {
21732
- types: "./dist/ops/index.d.ts",
21733
- import: "./dist/ops/index.js",
21734
- default: "./dist/ops/index.js"
21735
- },
21736
- "./apierror": {
21737
- types: "./dist/apierror/index.d.ts",
21738
- import: "./dist/apierror/index.js",
21739
- default: "./dist/apierror/index.js"
21740
- },
21741
- "./apierror/codes": {
21742
- types: "./dist/apierror/codes/index.d.ts",
21743
- import: "./dist/apierror/codes/index.js",
21744
- default: "./dist/apierror/codes/index.js"
21435
+ const jitter4 = Math.max(0, refreshJitterMs) * random();
21436
+ cached4 = {
21437
+ token: value.token,
21438
+ refreshAt: Math.max(now(), expiresAt - Math.max(0, refreshBeforeMs) - jitter4)
21439
+ };
21440
+ return value.token;
21441
+ };
21442
+ return async () => {
21443
+ if (cached4 && now() < cached4.refreshAt) return cached4.token;
21444
+ refreshing ??= refresh().finally(() => {
21445
+ refreshing = void 0;
21446
+ });
21447
+ return refreshing;
21448
+ };
21449
+ }
21450
+ function lakebaseClient(options) {
21451
+ const factory2 = options.poolFactory ?? defaultPoolFactory();
21452
+ let password = options.password;
21453
+ if (password === void 0) {
21454
+ if (!options.credentialClient || !options.endpoint) {
21455
+ throw new Error(
21456
+ "Lakebase OAuth requires credentialClient and endpoint. A workspace token cannot be used directly as the Postgres password."
21457
+ );
21745
21458
  }
21746
- },
21747
- files: [
21748
- "dist",
21749
- "LICENSE"
21750
- ],
21751
- scripts: {
21752
- build: "tsc -b",
21753
- lint: "eslint src tests --ext .ts",
21754
- "lint:fix": "eslint src tests --ext .ts --fix",
21755
- format: 'prettier --write "src/**/*.ts" "tests/**/*.ts"',
21756
- "format:check": 'prettier --check "src/**/*.ts" "tests/**/*.ts"',
21757
- test: "vitest run",
21758
- "test:browser": "vitest run --config vitest.config.browser.ts",
21759
- typecheck: "tsc --noEmit",
21760
- clean: "rm -rf dist tsconfig.tsbuildinfo"
21761
- },
21762
- author: "Databricks",
21763
- license: "Apache-2.0",
21764
- engines: {
21765
- node: ">=22.0.0"
21766
- },
21767
- dependencies: {
21768
- "json-bigint": "^1.0.0",
21769
- zod: "^4.3.6"
21459
+ password = lakebaseCredentialProvider({
21460
+ client: options.credentialClient,
21461
+ endpoint: options.endpoint,
21462
+ ...options.refreshBeforeMs !== void 0 ? { refreshBeforeMs: options.refreshBeforeMs } : {},
21463
+ ...options.refreshJitterMs !== void 0 ? { refreshJitterMs: options.refreshJitterMs } : {}
21464
+ });
21770
21465
  }
21771
- };
21772
-
21773
- // ../../node_modules/.pnpm/@databricks+sdk-core@0.21.0/node_modules/@databricks/sdk-core/dist/clientinfo/base.js
21774
- var MODULE_NAME = "sdk-js-core";
21775
- var VERSION2 = package_default2.version;
21776
- var base = ClientInfo.EMPTY;
21777
- function getBase() {
21778
- return base;
21466
+ const client = factory2({
21467
+ host: options.host,
21468
+ port: options.port ?? 5432,
21469
+ database: options.database,
21470
+ user: options.user,
21471
+ password,
21472
+ ssl: options.ssl ?? { rejectUnauthorized: true },
21473
+ ...options.max !== void 0 ? { max: options.max } : {}
21474
+ });
21475
+ client.on?.("error", options.onPoolError ?? (() => void 0));
21476
+ return client;
21477
+ }
21478
+ function defaultPoolFactory() {
21479
+ let PoolCtor;
21480
+ try {
21481
+ PoolCtor = require2("pg").Pool;
21482
+ } catch (error51) {
21483
+ throw new Error(
21484
+ `Lakebase store requires the optional "pg" package to be installed by the application. Run: pnpm add pg. ${error51 instanceof Error ? error51.message : String(error51)}`
21485
+ );
21486
+ }
21487
+ return (config2) => new PoolCtor(config2);
21779
21488
  }
21780
21489
 
21781
- // ../../node_modules/.pnpm/@databricks+sdk-core@0.21.0/node_modules/@databricks/sdk-core/dist/clientinfo/agent.js
21782
- var AGENT_ENV_VAR = "AGENT";
21783
- var AI_AGENT_ENV_VAR = "AI_AGENT";
21784
- var MAX_AGENT_FALLBACK_LEN = 64;
21785
- var KNOWN_AGENTS = [
21786
- // The amp agent also sets AGENT=amp, handled by the central fallback.
21787
- { envVar: "AMP_CURRENT_THREAD_ID", product: "amp" },
21788
- { envVar: "ANTIGRAVITY_AGENT", product: "antigravity" },
21789
- { envVar: "AUGMENT_AGENT", product: "augment" },
21790
- { envVar: "CLAUDECODE", product: "claude-code" },
21791
- { envVar: "CLINE_ACTIVE", product: "cline" },
21792
- { envVar: "CODEX_CI", product: "codex" },
21793
- { envVar: "COPILOT_CLI", product: "copilot-cli" },
21794
- { envVar: "CURSOR_AGENT", product: "cursor" },
21795
- { envVar: "GEMINI_CLI", product: "gemini-cli" },
21796
- // The goose agent also sets AGENT=goose, handled by the central
21797
- // fallback.
21798
- { envVar: "GOOSE_TERMINAL", product: "goose" },
21799
- { envVar: "KIRO", product: "kiro" },
21800
- { envVar: "OPENCLAW_SHELL", product: "openclaw" },
21801
- { envVar: "OPENCODE", product: "opencode" },
21802
- // Set by VS Code 1.121+ for agent-initiated terminal commands
21803
- // (https://code.visualstudio.com/updates/v1_121).
21804
- { envVar: "VSCODE_AGENT", product: "vscode-agent" },
21805
- { envVar: "WINDSURF_AGENT", product: "windsurf" }
21806
- ];
21807
- function agentEnvFallback() {
21808
- let v2 = process.env[AGENT_ENV_VAR];
21809
- if (v2 === void 0 || v2 === "") {
21810
- v2 = process.env[AI_AGENT_ENV_VAR];
21490
+ // src/lakeflow-authoring.ts
21491
+ var DatabricksLakeflowAuthoring = class {
21492
+ constructor(client, statements) {
21493
+ this.client = client;
21494
+ this.statements = statements;
21811
21495
  }
21812
- if (v2 === void 0 || v2 === "") {
21813
- return "";
21496
+ async createPipeline(spec) {
21497
+ const response = await this.client.create(serialize(spec));
21498
+ if (!response.pipelineId)
21499
+ throw new Error("Databricks Lakeflow create response did not contain pipeline_id.");
21500
+ return { pipelineId: response.pipelineId };
21814
21501
  }
21815
- return sanitize(v2).slice(0, MAX_AGENT_FALLBACK_LEN);
21816
- }
21817
- function lookupAgentProvider() {
21818
- const matches = [];
21819
- for (const a2 of KNOWN_AGENTS) {
21820
- if (a2.envVar in process.env) {
21821
- matches.push(a2.product);
21822
- }
21502
+ async updatePipeline(pipelineId, spec) {
21503
+ await this.client.edit({ pipelineId, id: pipelineId, ...serialize(spec) });
21823
21504
  }
21824
- if (matches.length === 1) {
21825
- return matches[0];
21505
+ async deletePipeline(pipelineId) {
21506
+ await this.client.delete({ pipelineId });
21826
21507
  }
21827
- if (matches.length > 1) {
21828
- return "multiple";
21508
+ async pipelineEvents(pipelineId, warehouseId, limit = 100) {
21509
+ const escaped = pipelineId.replace(/'/g, "''");
21510
+ if (!this.statements)
21511
+ throw new Error("Databricks Lakeflow events require a Statement Execution client.");
21512
+ return runStatement(
21513
+ this.statements,
21514
+ warehouseId,
21515
+ `SELECT * FROM event_log('${escaped}') ORDER BY timestamp DESC LIMIT ${Math.max(1, Math.min(1e3, Math.floor(limit)))}`,
21516
+ [],
21517
+ { intervalMs: 2e3, timeoutMs: 12e4 }
21518
+ );
21829
21519
  }
21830
- return agentEnvFallback();
21520
+ };
21521
+ function databricksLakeflowAuthoringTools(client, options = {}) {
21522
+ const api = new DatabricksLakeflowAuthoring(client, options.statements);
21523
+ const spec = specSchema();
21524
+ const specProperties2 = spec.properties;
21525
+ const resources = [
21526
+ { kind: "pipeline", path: "/name" },
21527
+ { kind: "catalog", path: "/catalog", catalogQualified: true, optional: true },
21528
+ { kind: "notebook", path: "/libraries/*/notebook/path", optional: true }
21529
+ ];
21530
+ const tools = [
21531
+ tool2(
21532
+ "databricks_create_pipeline",
21533
+ "write",
21534
+ spec,
21535
+ resources,
21536
+ (input) => api.createPipeline(input)
21537
+ ),
21538
+ tool2(
21539
+ "databricks_update_pipeline",
21540
+ "write",
21541
+ {
21542
+ type: "object",
21543
+ additionalProperties: false,
21544
+ properties: { pipelineId: { type: "string" }, ...specProperties2 },
21545
+ required: ["pipelineId", "name", "libraries"]
21546
+ },
21547
+ [{ kind: "pipeline", path: "/pipelineId" }, ...resources.slice(1)],
21548
+ (input) => api.updatePipeline(input.pipelineId, input)
21549
+ ),
21550
+ tool2(
21551
+ "databricks_delete_pipeline",
21552
+ "write",
21553
+ idSchema3(),
21554
+ [{ kind: "pipeline", path: "/pipelineId" }],
21555
+ (input) => api.deletePipeline(input.pipelineId)
21556
+ )
21557
+ ];
21558
+ const warehouseId = options.warehouseId;
21559
+ if (warehouseId)
21560
+ tools.push(
21561
+ tool2(
21562
+ "databricks_pipeline_events",
21563
+ "read",
21564
+ {
21565
+ type: "object",
21566
+ additionalProperties: false,
21567
+ properties: { pipelineId: { type: "string" }, limit: { type: "number" } },
21568
+ required: ["pipelineId"]
21569
+ },
21570
+ [{ kind: "pipeline", path: "/pipelineId" }],
21571
+ (input) => api.pipelineEvents(
21572
+ input.pipelineId,
21573
+ warehouseId,
21574
+ input.limit
21575
+ )
21576
+ )
21577
+ );
21578
+ return tools;
21831
21579
  }
21832
- var cached2;
21833
- function agentProvider() {
21834
- cached2 ??= lookupAgentProvider();
21835
- return cached2;
21580
+ function tool2(name, effect, inputSchema, resources, execute2) {
21581
+ return {
21582
+ name,
21583
+ description: name.replaceAll("_", " "),
21584
+ inputSchema,
21585
+ metadata: { effect, provider: "databricks", service: "lakeflow", governance: { resources } },
21586
+ execute: execute2
21587
+ };
21836
21588
  }
21837
-
21838
- // ../../node_modules/.pnpm/@databricks+sdk-core@0.21.0/node_modules/@databricks/sdk-core/dist/clientinfo/meta-harness.js
21839
- var KNOWN_META_HARNESSES = [
21840
- // OMNIGENT is set by the omnigent meta-harness
21841
- // (https://github.com/omnigent-ai/omnigent).
21842
- { envVar: "OMNIGENT", product: "omnigent" }
21843
- ];
21844
- function lookupMetaHarnessProvider() {
21845
- const matches = [];
21846
- for (const h2 of KNOWN_META_HARNESSES) {
21847
- if (h2.envVar in process.env) {
21848
- matches.push(h2.product);
21849
- }
21850
- }
21851
- if (matches.length === 1) {
21852
- return matches[0];
21853
- }
21854
- if (matches.length > 1) {
21855
- return "multiple";
21856
- }
21857
- return "";
21589
+ function idSchema3() {
21590
+ return {
21591
+ type: "object",
21592
+ additionalProperties: false,
21593
+ properties: { pipelineId: { type: "string" } },
21594
+ required: ["pipelineId"]
21595
+ };
21858
21596
  }
21859
- var cached3;
21860
- function metaHarnessProvider() {
21861
- cached3 ??= lookupMetaHarnessProvider();
21862
- return cached3;
21597
+ function specSchema() {
21598
+ return {
21599
+ type: "object",
21600
+ additionalProperties: false,
21601
+ properties: {
21602
+ name: { type: "string" },
21603
+ libraries: {
21604
+ type: "array",
21605
+ items: {
21606
+ type: "object",
21607
+ properties: {
21608
+ notebook: { type: "object", properties: { path: { type: "string" } } },
21609
+ file: { type: "object", properties: { path: { type: "string" } } },
21610
+ jar: { type: "string" },
21611
+ whl: { type: "string" }
21612
+ }
21613
+ }
21614
+ },
21615
+ catalog: { type: "string" },
21616
+ target: { type: "string" },
21617
+ continuous: { type: "boolean" },
21618
+ serverless: { type: "boolean" },
21619
+ development: { type: "boolean" },
21620
+ configuration: { type: "object", additionalProperties: { type: "string" } },
21621
+ clusters: { type: "array", items: { type: "object", additionalProperties: true } }
21622
+ },
21623
+ required: ["name", "libraries"]
21624
+ };
21625
+ }
21626
+ function serialize(spec) {
21627
+ return {
21628
+ name: spec.name,
21629
+ libraries: spec.libraries.map(serializeLibrary),
21630
+ ...spec.catalog ? { catalog: spec.catalog } : {},
21631
+ ...spec.target ? { target: spec.target } : {},
21632
+ ...spec.continuous !== void 0 ? { continuous: spec.continuous } : {},
21633
+ ...spec.serverless !== void 0 ? { serverless: spec.serverless } : {},
21634
+ ...spec.development !== void 0 ? { development: spec.development } : {},
21635
+ ...spec.configuration ? { configuration: spec.configuration } : {},
21636
+ ...spec.clusters ? { clusters: spec.clusters } : {}
21637
+ };
21638
+ }
21639
+ function serializeLibrary(library) {
21640
+ if (library.notebook)
21641
+ return { lib: { $case: "notebook", notebook: { path: library.notebook.path } } };
21642
+ if (library.file) return { lib: { $case: "file", file: { path: library.file.path } } };
21643
+ if (library.jar) return { lib: { $case: "jar", jar: library.jar } };
21644
+ if (library.whl) return { lib: { $case: "whl", whl: library.whl } };
21645
+ throw new Error("Databricks Lakeflow library requires notebook, file, jar, or whl.");
21863
21646
  }
21864
21647
 
21865
- // ../../node_modules/.pnpm/@databricks+sdk-core@0.21.0/node_modules/@databricks/sdk-core/dist/clientinfo/default.js
21866
- var CICD_PROVIDERS = [
21867
- {
21868
- name: "github",
21869
- envVars: [{ name: "GITHUB_ACTIONS", expectedValue: "true" }]
21870
- },
21871
- {
21872
- name: "gitlab",
21873
- envVars: [{ name: "GITLAB_CI", expectedValue: "true" }]
21874
- },
21875
- { name: "jenkins", envVars: [{ name: "JENKINS_URL", expectedValue: "" }] },
21876
- {
21877
- name: "azure-devops",
21878
- envVars: [{ name: "TF_BUILD", expectedValue: "True" }]
21879
- },
21880
- {
21881
- name: "circle",
21882
- envVars: [{ name: "CIRCLECI", expectedValue: "true" }]
21883
- },
21884
- { name: "travis", envVars: [{ name: "TRAVIS", expectedValue: "true" }] },
21885
- {
21886
- name: "bitbucket",
21887
- envVars: [{ name: "BITBUCKET_BUILD_NUMBER", expectedValue: "" }]
21888
- },
21889
- {
21890
- name: "google-cloud-build",
21891
- envVars: [
21892
- { name: "PROJECT_ID", expectedValue: "" },
21893
- { name: "BUILD_ID", expectedValue: "" },
21894
- { name: "PROJECT_NUMBER", expectedValue: "" },
21895
- { name: "LOCATION", expectedValue: "" }
21896
- ]
21897
- },
21898
- {
21648
+ // src/lakeflow.ts
21649
+ function databricksPipelineListTool(client, options = {}) {
21650
+ return {
21651
+ name: options.name ?? "databricks_pipeline_list",
21652
+ description: options.description ?? "List Lakeflow Declarative Pipelines (DLT) in the workspace.",
21653
+ inputSchema: {
21654
+ type: "object",
21655
+ additionalProperties: false,
21656
+ properties: { maxResults: { type: "number", minimum: 1 }, filter: { type: "string" } }
21657
+ },
21658
+ metadata: { effect: "read", provider: "databricks", service: "lakeflow" },
21659
+ execute: (input) => client.list({
21660
+ ...input.maxResults !== void 0 ? { maxResults: input.maxResults } : {},
21661
+ ...input.filter ? { filter: input.filter } : {}
21662
+ })
21663
+ };
21664
+ }
21665
+ function databricksPipelineStatusTool(client, options = {}) {
21666
+ return {
21667
+ name: options.name ?? "databricks_pipeline_status",
21668
+ description: options.description ?? "Get a Lakeflow pipeline, including its state and latest updates.",
21669
+ inputSchema: {
21670
+ type: "object",
21671
+ additionalProperties: false,
21672
+ properties: { pipelineId: { type: "string" } },
21673
+ required: ["pipelineId"]
21674
+ },
21675
+ metadata: { effect: "read", provider: "databricks", service: "lakeflow" },
21676
+ execute: (input) => client.get({ pipelineId: input.pipelineId })
21677
+ };
21678
+ }
21679
+ function databricksPipelineStartTool(client, options = {}) {
21680
+ return {
21681
+ name: options.name ?? "databricks_pipeline_start",
21682
+ description: options.description ?? "Trigger a Lakeflow pipeline update (run). Set fullRefresh to reprocess all data.",
21683
+ inputSchema: {
21684
+ type: "object",
21685
+ additionalProperties: false,
21686
+ properties: { pipelineId: { type: "string" }, fullRefresh: { type: "boolean" } },
21687
+ required: ["pipelineId"]
21688
+ },
21689
+ metadata: { effect: "execute", provider: "databricks", service: "lakeflow" },
21690
+ execute: (input) => client.start({
21691
+ pipelineId: input.pipelineId,
21692
+ ...input.fullRefresh !== void 0 ? { fullRefresh: input.fullRefresh } : {}
21693
+ })
21694
+ };
21695
+ }
21696
+ function databricksPipelineStopTool(client, options = {}) {
21697
+ return {
21698
+ name: options.name ?? "databricks_pipeline_stop",
21699
+ description: options.description ?? "Stop the active update of a Lakeflow pipeline.",
21700
+ inputSchema: {
21701
+ type: "object",
21702
+ additionalProperties: false,
21703
+ properties: { pipelineId: { type: "string" } },
21704
+ required: ["pipelineId"]
21705
+ },
21706
+ metadata: { effect: "execute", provider: "databricks", service: "lakeflow" },
21707
+ execute: (input) => client.stop({ pipelineId: input.pipelineId })
21708
+ };
21709
+ }
21710
+ function databricksLakeflowTools(client) {
21711
+ return [
21712
+ databricksPipelineListTool(client),
21713
+ databricksPipelineStatusTool(client),
21714
+ databricksPipelineStartTool(client),
21715
+ databricksPipelineStopTool(client)
21716
+ ];
21717
+ }
21718
+
21719
+ // src/mlflow-tracing.ts
21720
+ import { createHash } from "crypto";
21721
+ import { eventToTelemetrySpan } from "@fabric-harness/sdk";
21722
+ function mlflowTraceExporter(options) {
21723
+ const onError = options.onError ?? ((context, error51) => {
21724
+ console.error(`[fabric-harness:mlflow-tracing] ${context}:`, error51);
21725
+ });
21726
+ const buffers = /* @__PURE__ */ new Map();
21727
+ return {
21728
+ sink: {
21729
+ record(event) {
21730
+ try {
21731
+ const key = `agent:${event.agent}:${event.instanceId}:${event.session}`;
21732
+ if (event.type === "submission_started") {
21733
+ buffers.set(key, {
21734
+ submissionId: event.submissionId,
21735
+ agent: event.agent,
21736
+ instanceId: event.instanceId,
21737
+ session: event.session,
21738
+ startedAtMs: event.at,
21739
+ attemptCount: event.attemptCount,
21740
+ ...event.tenantId !== void 0 ? { tenantId: event.tenantId } : {},
21741
+ spans: []
21742
+ });
21743
+ return;
21744
+ }
21745
+ if (event.type !== "submission_settled") return;
21746
+ const buffer = buffers.get(key);
21747
+ buffers.delete(key);
21748
+ const startedAtMs = buffer?.startedAtMs ?? event.at - (event.durationMs ?? 0);
21749
+ const attemptCount = event.attemptCount ?? buffer?.attemptCount;
21750
+ const trace = buildMlflowTrace({
21751
+ submissionId: event.submissionId,
21752
+ agent: event.agent,
21753
+ instanceId: event.instanceId,
21754
+ session: event.session,
21755
+ experimentId: options.experimentId,
21756
+ startedAtMs,
21757
+ settledAtMs: event.at,
21758
+ state: event.outcome === "completed" ? "OK" : "ERROR",
21759
+ spans: buffer?.spans ?? [],
21760
+ ...attemptCount !== void 0 ? { attemptCount } : {},
21761
+ ...event.tenantId !== void 0 ? { tenantId: event.tenantId } : {},
21762
+ ...event.error !== void 0 ? { error: event.error } : {}
21763
+ });
21764
+ void options.client.post("/api/3.0/mlflow/traces", trace).catch((error51) => onError(`trace export failed for ${event.submissionId}`, error51));
21765
+ } catch (error51) {
21766
+ onError("telemetry event handling failed", error51);
21767
+ }
21768
+ }
21769
+ },
21770
+ onEvent(event) {
21771
+ try {
21772
+ if (!event.sessionId) return;
21773
+ const buffer = buffers.get(event.sessionId);
21774
+ if (!buffer) return;
21775
+ const span = eventToTelemetrySpan(event);
21776
+ if (span) buffer.spans.push(span);
21777
+ } catch (error51) {
21778
+ onError("event buffering failed", error51);
21779
+ }
21780
+ }
21781
+ };
21782
+ }
21783
+ function buildMlflowTrace(input) {
21784
+ const traceBytes = sha256(input.submissionId).subarray(0, 16);
21785
+ const traceIdBase64 = traceBytes.toString("base64");
21786
+ const rootSpanId = spanIdFor(input.submissionId, 0);
21787
+ const durationSeconds = Math.max(0, input.settledAtMs - input.startedAtMs) / 1e3;
21788
+ const rootSpan = {
21789
+ trace_id: traceIdBase64,
21790
+ span_id: rootSpanId,
21791
+ name: `fabric.submission ${input.agent}`,
21792
+ start_time_unix_nano: toUnixNano(input.startedAtMs),
21793
+ end_time_unix_nano: toUnixNano(input.settledAtMs),
21794
+ attributes: toOtlpAttributes({
21795
+ "fabric.submission_id": input.submissionId,
21796
+ "fabric.agent": input.agent,
21797
+ "fabric.instance_id": input.instanceId,
21798
+ "fabric.session": input.session,
21799
+ ...input.attemptCount !== void 0 ? { "fabric.attempt_count": input.attemptCount } : {},
21800
+ ...input.error !== void 0 ? { "fabric.error": input.error } : {}
21801
+ }),
21802
+ status: {
21803
+ code: input.state === "OK" ? "STATUS_CODE_OK" : "STATUS_CODE_ERROR",
21804
+ ...input.error !== void 0 ? { message: input.error } : {}
21805
+ }
21806
+ };
21807
+ const childSpans = input.spans.map(
21808
+ (span, index) => ({
21809
+ trace_id: traceIdBase64,
21810
+ span_id: spanIdFor(input.submissionId, index + 1),
21811
+ parent_span_id: rootSpanId,
21812
+ name: span.name,
21813
+ start_time_unix_nano: toUnixNano(Date.parse(span.startedAt)),
21814
+ end_time_unix_nano: toUnixNano(Date.parse(span.endedAt)),
21815
+ attributes: toOtlpAttributes(span.attributes),
21816
+ status: { code: "STATUS_CODE_OK" }
21817
+ })
21818
+ );
21819
+ return {
21820
+ trace: {
21821
+ trace_info: {
21822
+ trace_id: `tr-${traceBytes.toString("hex")}`,
21823
+ trace_location: {
21824
+ type: "MLFLOW_EXPERIMENT",
21825
+ mlflow_experiment: { experiment_id: input.experimentId }
21826
+ },
21827
+ request_time: new Date(input.startedAtMs).toISOString(),
21828
+ execution_duration: `${durationSeconds.toFixed(3)}s`,
21829
+ state: input.state,
21830
+ trace_metadata: {
21831
+ "fabric.submission_id": input.submissionId,
21832
+ "fabric.agent": input.agent,
21833
+ "fabric.instance_id": input.instanceId,
21834
+ "fabric.session": input.session,
21835
+ ...input.attemptCount !== void 0 ? { "fabric.attempt_count": String(input.attemptCount) } : {}
21836
+ },
21837
+ tags: {
21838
+ "fabric.agent": input.agent,
21839
+ ...input.tenantId !== void 0 ? { "fabric.tenant_id": input.tenantId } : {}
21840
+ }
21841
+ },
21842
+ trace_data: { spans: [rootSpan, ...childSpans] }
21843
+ }
21844
+ };
21845
+ }
21846
+ function sha256(seed) {
21847
+ return createHash("sha256").update(seed).digest();
21848
+ }
21849
+ function spanIdFor(submissionId, index) {
21850
+ return sha256(`${submissionId}:span:${index}`).subarray(0, 8).toString("base64");
21851
+ }
21852
+ function toUnixNano(epochMs) {
21853
+ return `${Math.round(epochMs)}000000`;
21854
+ }
21855
+ function toOtlpAttributes(attributes) {
21856
+ return Object.entries(attributes).map(([key, value]) => {
21857
+ if (typeof value === "number") {
21858
+ return Number.isInteger(value) ? { key, value: { int_value: String(value) } } : { key, value: { double_value: value } };
21859
+ }
21860
+ return { key, value: { string_value: String(value) } };
21861
+ });
21862
+ }
21863
+
21864
+ // src/model.ts
21865
+ import {
21866
+ OpenAICompatibleModelProvider,
21867
+ currentSubmissionContext as currentSubmissionContext2,
21868
+ registerModelProvider
21869
+ } from "@fabric-harness/sdk";
21870
+ function databricksModelBaseUrl(host, mode) {
21871
+ const normalized = databricksWorkspaceOrigin(host);
21872
+ return mode === "ai-gateway" ? `${normalized}/ai-gateway/mlflow/v1` : `${normalized}/serving-endpoints`;
21873
+ }
21874
+ function isDatabricksModelService(model) {
21875
+ return model?.startsWith("system.ai.") ?? false;
21876
+ }
21877
+ var DatabricksModelProvider = class {
21878
+ name = "databricks";
21879
+ options;
21880
+ gateway;
21881
+ serving;
21882
+ explicit;
21883
+ constructor(options) {
21884
+ this.options = options;
21885
+ const common = {
21886
+ name: this.name,
21887
+ apiKey: typeof options.token === "string" ? options.token : "",
21888
+ ...typeof options.token === "function" ? { tokenProvider: options.token } : {},
21889
+ ...options.defaultModel !== void 0 ? { defaultModel: options.defaultModel } : {},
21890
+ ...options.fetchImpl ? { fetchImpl: options.fetchImpl } : {}
21891
+ };
21892
+ this.gateway = new OpenAICompatibleModelProvider({
21893
+ ...common,
21894
+ baseUrl: databricksModelBaseUrl(options.host, "ai-gateway"),
21895
+ headers: () => this.resolveHeaders(true)
21896
+ });
21897
+ this.serving = new OpenAICompatibleModelProvider({
21898
+ ...common,
21899
+ baseUrl: databricksModelBaseUrl(options.host, "serving-endpoints"),
21900
+ headers: () => this.resolveHeaders(false)
21901
+ });
21902
+ this.explicit = options.baseUrl ? new OpenAICompatibleModelProvider({
21903
+ ...common,
21904
+ baseUrl: options.baseUrl,
21905
+ headers: () => this.resolveHeaders(options.baseUrl?.includes("/ai-gateway/") ?? false)
21906
+ }) : void 0;
21907
+ }
21908
+ generate(request) {
21909
+ return this.providerFor(request.model).generate(request);
21910
+ }
21911
+ stream(request) {
21912
+ const provider = this.providerFor(request.model);
21913
+ if (!provider.stream)
21914
+ throw new Error("databricks: selected provider does not support streaming.");
21915
+ return provider.stream(request);
21916
+ }
21917
+ getModelMetadata(model = this.options.defaultModel) {
21918
+ const mode = this.modeFor(model);
21919
+ return {
21920
+ provider: this.name,
21921
+ ...model ? { model } : {},
21922
+ gateway: this.options.baseUrl ?? databricksModelBaseUrl(this.options.host, mode),
21923
+ ...model && this.options.modelMetadata?.[model] ? this.options.modelMetadata[model] : {}
21924
+ };
21925
+ }
21926
+ providerFor(model = this.options.defaultModel) {
21927
+ if (this.explicit) return this.explicit;
21928
+ return this.modeFor(model) === "ai-gateway" ? this.gateway : this.serving;
21929
+ }
21930
+ modeFor(model) {
21931
+ const configured = this.options.mode ?? "auto";
21932
+ if (configured !== "auto") return configured;
21933
+ return isDatabricksModelService(model) ? "ai-gateway" : "serving-endpoints";
21934
+ }
21935
+ async resolveHeaders(gateway) {
21936
+ const configured = typeof this.options.headers === "function" ? await this.options.headers() : this.options.headers ?? {};
21937
+ if (!gateway) return configured;
21938
+ const supplied = typeof this.options.requestTags === "function" ? await this.options.requestTags() : this.options.requestTags ?? {};
21939
+ const context = currentSubmissionContext2();
21940
+ const tags = compactTags({
21941
+ ...context?.submissionId ? { submission_id: context.submissionId } : {},
21942
+ ...context?.attemptId ? { attempt_id: context.attemptId } : {},
21943
+ ...context?.tenantId ? { tenant_id: context.tenantId } : {},
21944
+ ...context?.agent ? { agent: context.agent } : {},
21945
+ ...supplied
21946
+ });
21947
+ return Object.keys(tags).length > 0 ? { ...configured, "Databricks-Ai-Gateway-Request-Tags": JSON.stringify(tags) } : configured;
21948
+ }
21949
+ };
21950
+ function compactTags(tags) {
21951
+ return Object.fromEntries(
21952
+ Object.entries(tags).filter(([key, value]) => key.length > 0 && value.length > 0).map(([key, value]) => [key.slice(0, 128), value.slice(0, 512)])
21953
+ );
21954
+ }
21955
+ function databricksFoundationModelProvider(options) {
21956
+ return new DatabricksModelProvider(options);
21957
+ }
21958
+ function inferenceMode(value) {
21959
+ if (!value) return void 0;
21960
+ if (value === "auto" || value === "ai-gateway" || value === "serving-endpoints") return value;
21961
+ throw new Error(
21962
+ `Invalid DATABRICKS_INFERENCE_MODE "${value}". Use auto, ai-gateway, or serving-endpoints.`
21963
+ );
21964
+ }
21965
+ function origin(value) {
21966
+ try {
21967
+ return new URL(value).origin;
21968
+ } catch {
21969
+ return value;
21970
+ }
21971
+ }
21972
+ var factory = (parsed, providers, env2, warnings) => {
21973
+ const settings = providers?.databricks;
21974
+ const configuredUrl = settings?.baseUrl;
21975
+ const rawHost = env2.DATABRICKS_HOST ?? (configuredUrl ? origin(configuredUrl) : void 0);
21976
+ if (!rawHost)
21977
+ throw new Error(
21978
+ "Missing Databricks host. Set DATABRICKS_HOST or providers.databricks.baseUrl."
21979
+ );
21980
+ const host = rawHost.includes("://") ? rawHost : `https://${rawHost}`;
21981
+ const staticToken = settings?.apiKey?.trim() || env2[settings?.apiKeyEnv ?? "DATABRICKS_TOKEN"]?.trim() || env2.DATABRICKS_API_KEY?.trim();
21982
+ let principal;
21983
+ if (!staticToken) {
21984
+ try {
21985
+ principal = databricksPrincipalFromEnv(env2);
21986
+ } catch {
21987
+ }
21988
+ }
21989
+ if (!staticToken && !principal)
21990
+ throw new Error(
21991
+ "Missing Databricks credentials. Set DATABRICKS_TOKEN, DATABRICKS_CLIENT_ID + DATABRICKS_CLIENT_SECRET, or providers.databricks.apiKey/apiKeyEnv."
21992
+ );
21993
+ const token = staticToken ?? databricksIdentity(principal);
21994
+ const explicitBaseUrl = env2.DATABRICKS_AI_GATEWAY_BASE_URL ?? (configuredUrl && new URL(configuredUrl).pathname !== "/" ? configuredUrl : void 0);
21995
+ const mode = inferenceMode(env2.DATABRICKS_INFERENCE_MODE);
21996
+ return {
21997
+ model: parsed.modelId,
21998
+ provider: databricksFoundationModelProvider({
21999
+ host,
22000
+ token,
22001
+ defaultModel: parsed.modelId,
22002
+ ...explicitBaseUrl ? { baseUrl: explicitBaseUrl } : {},
22003
+ ...mode ? { mode } : {},
22004
+ ...settings?.headers ? { headers: settings.headers } : {}
22005
+ }),
22006
+ providerName: "databricks",
22007
+ modelId: parsed.modelId,
22008
+ warnings
22009
+ };
22010
+ };
22011
+ var registered = false;
22012
+ function registerDatabricksModelProvider() {
22013
+ if (registered) return;
22014
+ registered = true;
22015
+ registerModelProvider("databricks", factory);
22016
+ }
22017
+
22018
+ // ../../node_modules/.pnpm/@databricks+sdk-core@0.21.0/node_modules/@databricks/sdk-core/dist/clientinfo/clientinfo.js
22019
+ var ClientInfoError = class extends Error {
22020
+ code;
22021
+ constructor(code, message) {
22022
+ super(message);
22023
+ this.name = "ClientInfoError";
22024
+ this.code = code;
22025
+ }
22026
+ };
22027
+ var SEMVER_CORE = String.raw`(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)`;
22028
+ var SEMVER_PRERELEASE = String.raw`(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?`;
22029
+ var SEMVER_BUILDMETADATA = String.raw`(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?`;
22030
+ var REGEXP_SEMVER = new RegExp("^" + SEMVER_CORE + SEMVER_PRERELEASE + SEMVER_BUILDMETADATA + "$");
22031
+ var REGEXP_VALID_SEGMENT = /^[-0-9A-Za-z_.+]+$/;
22032
+ var REGEXP_INVALID_SEGMENT_CHAR = /[^-0-9A-Za-z_.+]/g;
22033
+ function isValidSegment(s2) {
22034
+ return REGEXP_VALID_SEGMENT.test(s2);
22035
+ }
22036
+ function sanitize(s2) {
22037
+ return s2.replace(REGEXP_INVALID_SEGMENT_CHAR, "-");
22038
+ }
22039
+ var ClientInfo = class _ClientInfo {
22040
+ static EMPTY = new _ClientInfo();
22041
+ segments;
22042
+ constructor(segments = []) {
22043
+ this.segments = [...segments];
22044
+ }
22045
+ /**
22046
+ * Returns a new {@link ClientInfo} with the given items appended. Accepts
22047
+ * either individual key/value pairs or another {@link ClientInfo} whose
22048
+ * segments are merged in order. The original is not modified; mixing the
22049
+ * two forms in a single call is supported.
22050
+ *
22051
+ * Keys and values on pair arguments must contain only alphanumeric
22052
+ * characters plus `_`, `.`, `+`, or `-`. Exact key+value duplicates are
22053
+ * silently ignored. On error, an exception is thrown (all-or-nothing).
22054
+ *
22055
+ * @example
22056
+ * ```ts
22057
+ * base.with({key: 'partner', value: 'acme'});
22058
+ * base.with(pkgClientInfo);
22059
+ * base.with(pkgClientInfo, {key: 'sdk-feature', value: 'pagination'});
22060
+ * ```
22061
+ */
22062
+ with(...items) {
22063
+ if (items.length === 0) {
22064
+ return this;
22065
+ }
22066
+ const newSegments = [...this.segments];
22067
+ for (const item of items) {
22068
+ const pairs = item instanceof _ClientInfo ? item.segments : [item];
22069
+ for (const { key, value } of pairs) {
22070
+ if (!isValidSegment(key)) {
22071
+ throw new ClientInfoError("INVALID_KEY", `Invalid key: ${key}.`);
22072
+ }
22073
+ if (!isValidSegment(value)) {
22074
+ throw new ClientInfoError("INVALID_VALUE", `Invalid value for "${key}": ${value}.`);
22075
+ }
22076
+ if (newSegments.some((s2) => s2.key === key && s2.value === value)) {
22077
+ continue;
22078
+ }
22079
+ newSegments.push({ key, value });
22080
+ }
22081
+ }
22082
+ return new _ClientInfo(newSegments);
22083
+ }
22084
+ /**
22085
+ * Returns a string representation of the client info suitable for
22086
+ * inclusion in HTTP headers. Key/value pairs are formatted as
22087
+ * "key/value" and joined by spaces in the order they were inserted.
22088
+ */
22089
+ toString() {
22090
+ return this.segments.map((s2) => `${s2.key}/${s2.value}`).join(" ");
22091
+ }
22092
+ };
22093
+
22094
+ // ../../node_modules/.pnpm/@databricks+sdk-core@0.21.0/node_modules/@databricks/sdk-core/package.json
22095
+ var package_default2 = {
22096
+ name: "@databricks/sdk-core",
22097
+ version: "0.21.0",
22098
+ description: "Databricks core library for JavaScript/TypeScript",
22099
+ type: "module",
22100
+ main: "./dist/index.js",
22101
+ types: "./dist/index.d.ts",
22102
+ exports: {
22103
+ ".": {
22104
+ types: "./dist/index.d.ts",
22105
+ import: "./dist/index.js",
22106
+ default: "./dist/index.js"
22107
+ },
22108
+ "./profiles": {
22109
+ types: "./dist/profiles/index.d.ts",
22110
+ import: "./dist/profiles/index.js",
22111
+ default: "./dist/profiles/index.js"
22112
+ },
22113
+ "./profiles/browser": {
22114
+ types: "./dist/profiles/index.browser.d.ts",
22115
+ import: "./dist/profiles/index.browser.js",
22116
+ default: "./dist/profiles/index.browser.js"
22117
+ },
22118
+ "./wkt": {
22119
+ types: "./dist/wkt/index.d.ts",
22120
+ import: "./dist/wkt/index.js",
22121
+ default: "./dist/wkt/index.js"
22122
+ },
22123
+ "./clientinfo": {
22124
+ browser: {
22125
+ types: "./dist/clientinfo/index.browser.d.ts",
22126
+ import: "./dist/clientinfo/index.browser.js",
22127
+ default: "./dist/clientinfo/index.browser.js"
22128
+ },
22129
+ default: {
22130
+ types: "./dist/clientinfo/index.d.ts",
22131
+ import: "./dist/clientinfo/index.js",
22132
+ default: "./dist/clientinfo/index.js"
22133
+ }
22134
+ },
22135
+ "./clientinfo/browser": {
22136
+ types: "./dist/clientinfo/index.browser.d.ts",
22137
+ import: "./dist/clientinfo/index.browser.js",
22138
+ default: "./dist/clientinfo/index.browser.js"
22139
+ },
22140
+ "./http": {
22141
+ types: "./dist/http/index.d.ts",
22142
+ import: "./dist/http/index.js",
22143
+ default: "./dist/http/index.js"
22144
+ },
22145
+ "./logger": {
22146
+ types: "./dist/logger/index.d.ts",
22147
+ import: "./dist/logger/index.js",
22148
+ default: "./dist/logger/index.js"
22149
+ },
22150
+ "./ops": {
22151
+ types: "./dist/ops/index.d.ts",
22152
+ import: "./dist/ops/index.js",
22153
+ default: "./dist/ops/index.js"
22154
+ },
22155
+ "./apierror": {
22156
+ types: "./dist/apierror/index.d.ts",
22157
+ import: "./dist/apierror/index.js",
22158
+ default: "./dist/apierror/index.js"
22159
+ },
22160
+ "./apierror/codes": {
22161
+ types: "./dist/apierror/codes/index.d.ts",
22162
+ import: "./dist/apierror/codes/index.js",
22163
+ default: "./dist/apierror/codes/index.js"
22164
+ }
22165
+ },
22166
+ files: [
22167
+ "dist",
22168
+ "LICENSE"
22169
+ ],
22170
+ scripts: {
22171
+ build: "tsc -b",
22172
+ lint: "eslint src tests --ext .ts",
22173
+ "lint:fix": "eslint src tests --ext .ts --fix",
22174
+ format: 'prettier --write "src/**/*.ts" "tests/**/*.ts"',
22175
+ "format:check": 'prettier --check "src/**/*.ts" "tests/**/*.ts"',
22176
+ test: "vitest run",
22177
+ "test:browser": "vitest run --config vitest.config.browser.ts",
22178
+ typecheck: "tsc --noEmit",
22179
+ clean: "rm -rf dist tsconfig.tsbuildinfo"
22180
+ },
22181
+ author: "Databricks",
22182
+ license: "Apache-2.0",
22183
+ engines: {
22184
+ node: ">=22.0.0"
22185
+ },
22186
+ dependencies: {
22187
+ "json-bigint": "^1.0.0",
22188
+ zod: "^4.3.6"
22189
+ }
22190
+ };
22191
+
22192
+ // ../../node_modules/.pnpm/@databricks+sdk-core@0.21.0/node_modules/@databricks/sdk-core/dist/clientinfo/base.js
22193
+ var MODULE_NAME = "sdk-js-core";
22194
+ var VERSION2 = package_default2.version;
22195
+ var base = ClientInfo.EMPTY;
22196
+ function getBase() {
22197
+ return base;
22198
+ }
22199
+
22200
+ // ../../node_modules/.pnpm/@databricks+sdk-core@0.21.0/node_modules/@databricks/sdk-core/dist/clientinfo/agent.js
22201
+ var AGENT_ENV_VAR = "AGENT";
22202
+ var AI_AGENT_ENV_VAR = "AI_AGENT";
22203
+ var MAX_AGENT_FALLBACK_LEN = 64;
22204
+ var KNOWN_AGENTS = [
22205
+ // The amp agent also sets AGENT=amp, handled by the central fallback.
22206
+ { envVar: "AMP_CURRENT_THREAD_ID", product: "amp" },
22207
+ { envVar: "ANTIGRAVITY_AGENT", product: "antigravity" },
22208
+ { envVar: "AUGMENT_AGENT", product: "augment" },
22209
+ { envVar: "CLAUDECODE", product: "claude-code" },
22210
+ { envVar: "CLINE_ACTIVE", product: "cline" },
22211
+ { envVar: "CODEX_CI", product: "codex" },
22212
+ { envVar: "COPILOT_CLI", product: "copilot-cli" },
22213
+ { envVar: "CURSOR_AGENT", product: "cursor" },
22214
+ { envVar: "GEMINI_CLI", product: "gemini-cli" },
22215
+ // The goose agent also sets AGENT=goose, handled by the central
22216
+ // fallback.
22217
+ { envVar: "GOOSE_TERMINAL", product: "goose" },
22218
+ { envVar: "KIRO", product: "kiro" },
22219
+ { envVar: "OPENCLAW_SHELL", product: "openclaw" },
22220
+ { envVar: "OPENCODE", product: "opencode" },
22221
+ // Set by VS Code 1.121+ for agent-initiated terminal commands
22222
+ // (https://code.visualstudio.com/updates/v1_121).
22223
+ { envVar: "VSCODE_AGENT", product: "vscode-agent" },
22224
+ { envVar: "WINDSURF_AGENT", product: "windsurf" }
22225
+ ];
22226
+ function agentEnvFallback() {
22227
+ let v2 = process.env[AGENT_ENV_VAR];
22228
+ if (v2 === void 0 || v2 === "") {
22229
+ v2 = process.env[AI_AGENT_ENV_VAR];
22230
+ }
22231
+ if (v2 === void 0 || v2 === "") {
22232
+ return "";
22233
+ }
22234
+ return sanitize(v2).slice(0, MAX_AGENT_FALLBACK_LEN);
22235
+ }
22236
+ function lookupAgentProvider() {
22237
+ const matches = [];
22238
+ for (const a2 of KNOWN_AGENTS) {
22239
+ if (a2.envVar in process.env) {
22240
+ matches.push(a2.product);
22241
+ }
22242
+ }
22243
+ if (matches.length === 1) {
22244
+ return matches[0];
22245
+ }
22246
+ if (matches.length > 1) {
22247
+ return "multiple";
22248
+ }
22249
+ return agentEnvFallback();
22250
+ }
22251
+ var cached2;
22252
+ function agentProvider() {
22253
+ cached2 ??= lookupAgentProvider();
22254
+ return cached2;
22255
+ }
22256
+
22257
+ // ../../node_modules/.pnpm/@databricks+sdk-core@0.21.0/node_modules/@databricks/sdk-core/dist/clientinfo/meta-harness.js
22258
+ var KNOWN_META_HARNESSES = [
22259
+ // OMNIGENT is set by the omnigent meta-harness
22260
+ // (https://github.com/omnigent-ai/omnigent).
22261
+ { envVar: "OMNIGENT", product: "omnigent" }
22262
+ ];
22263
+ function lookupMetaHarnessProvider() {
22264
+ const matches = [];
22265
+ for (const h2 of KNOWN_META_HARNESSES) {
22266
+ if (h2.envVar in process.env) {
22267
+ matches.push(h2.product);
22268
+ }
22269
+ }
22270
+ if (matches.length === 1) {
22271
+ return matches[0];
22272
+ }
22273
+ if (matches.length > 1) {
22274
+ return "multiple";
22275
+ }
22276
+ return "";
22277
+ }
22278
+ var cached3;
22279
+ function metaHarnessProvider() {
22280
+ cached3 ??= lookupMetaHarnessProvider();
22281
+ return cached3;
22282
+ }
22283
+
22284
+ // ../../node_modules/.pnpm/@databricks+sdk-core@0.21.0/node_modules/@databricks/sdk-core/dist/clientinfo/default.js
22285
+ var CICD_PROVIDERS = [
22286
+ {
22287
+ name: "github",
22288
+ envVars: [{ name: "GITHUB_ACTIONS", expectedValue: "true" }]
22289
+ },
22290
+ {
22291
+ name: "gitlab",
22292
+ envVars: [{ name: "GITLAB_CI", expectedValue: "true" }]
22293
+ },
22294
+ { name: "jenkins", envVars: [{ name: "JENKINS_URL", expectedValue: "" }] },
22295
+ {
22296
+ name: "azure-devops",
22297
+ envVars: [{ name: "TF_BUILD", expectedValue: "True" }]
22298
+ },
22299
+ {
22300
+ name: "circle",
22301
+ envVars: [{ name: "CIRCLECI", expectedValue: "true" }]
22302
+ },
22303
+ { name: "travis", envVars: [{ name: "TRAVIS", expectedValue: "true" }] },
22304
+ {
22305
+ name: "bitbucket",
22306
+ envVars: [{ name: "BITBUCKET_BUILD_NUMBER", expectedValue: "" }]
22307
+ },
22308
+ {
22309
+ name: "google-cloud-build",
22310
+ envVars: [
22311
+ { name: "PROJECT_ID", expectedValue: "" },
22312
+ { name: "BUILD_ID", expectedValue: "" },
22313
+ { name: "PROJECT_NUMBER", expectedValue: "" },
22314
+ { name: "LOCATION", expectedValue: "" }
22315
+ ]
22316
+ },
22317
+ {
21899
22318
  name: "aws-code-build",
21900
22319
  envVars: [{ name: "CODEBUILD_BUILD_ARN", expectedValue: "" }]
21901
22320
  },
@@ -35782,8 +36201,8 @@ function parseResponse9(body, schema) {
35782
36201
  function marshalRequest8(data, schema) {
35783
36202
  return jsonBigint8.stringify(schema.parse(data));
35784
36203
  }
35785
- function encodeMultiSegmentPath(path) {
35786
- return path.split("/").map((segment) => encodeURIComponent(segment)).join("/");
36204
+ function encodeMultiSegmentPath(path3) {
36205
+ return path3.split("/").map((segment) => encodeURIComponent(segment)).join("/");
35787
36206
  }
35788
36207
  async function sendAndCheckError2(opts) {
35789
36208
  opts.logger.debug("HTTP request", {
@@ -56886,728 +57305,307 @@ var UpdateRoleOperation = class {
56886
57305
  const op = await this.getOperation({
56887
57306
  name: this.operation.name
56888
57307
  }, callSignal !== void 0 ? { signal: callSignal } : void 0);
56889
- this.operation = op;
56890
- if (op.done === void 0) {
56891
- throw new Error("operation is missing the done field");
56892
- }
56893
- if (!op.done) {
56894
- throw new StillRunningError6();
56895
- }
56896
- if (op.result?.$case === "error") {
56897
- const err = op.result.error;
56898
- const msg = err.message !== void 0 && err.message !== "" ? err.message : "unknown error";
56899
- const errorMsg = err.errorCode !== void 0 ? `[${err.errorCode}] ${msg}` : msg;
56900
- throw new Error(`operation failed: ${errorMsg}`, {
56901
- cause: err
56902
- });
56903
- }
56904
- if (op.result?.$case !== "response") {
56905
- throw new Error("operation completed without a response");
56906
- }
56907
- result = external_exports.lazy(() => unmarshalRoleSchema2).parse(op.result.response);
56908
- };
56909
- await executeWait6(call, options);
56910
- if (result === void 0) {
56911
- throw new Error("operation completed without a result.");
56912
- }
56913
- return result;
56914
- }
56915
- /** Checks whether the operation has completed */
56916
- async done(options) {
56917
- const op = await this.getOperation({ name: this.operation.name }, options);
56918
- this.operation = op;
56919
- return op.done;
56920
- }
56921
- };
56922
-
56923
- // src/native-sdk.ts
56924
- function databricksSdk(options) {
56925
- const tokenProvider = databricksIdentity(options.principal);
56926
- return stableDatabricksSdkClients(
56927
- createDatabricksNativeClients({
56928
- host: options.host,
56929
- credentials: databricksCredentials(options.principal),
56930
- tokenProvider,
56931
- ...options.fetchImpl ? { fetchImpl: options.fetchImpl } : {},
56932
- ...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {},
56933
- ...options.extraHeaders ? { extraHeaders: options.extraHeaders } : {}
56934
- })
56935
- );
56936
- }
56937
- function stableDatabricksSdkClients(clients) {
56938
- const { rawProtocol: _rawProtocol, ...sdk } = clients;
56939
- return sdk;
56940
- }
56941
- function createDatabricksNativeClients(options) {
56942
- const clientOptions = generatedClientOptions(options);
56943
- return {
56944
- accessManagement: new AccessManagementClient(clientOptions),
56945
- jobs: new JobsClient(clientOptions),
56946
- statements: new StatementExecutionClient(clientOptions),
56947
- pipelines: new PipelinesClient(clientOptions),
56948
- vectorSearch: new VectorSearchClient(clientOptions),
56949
- modelServing: new ModelServingClient(clientOptions),
56950
- modelServingQuery: new ModelServingQueryClient(clientOptions),
56951
- files: new FilesClient(clientOptions),
56952
- secrets: new SecretsClient(clientOptions),
56953
- genie: new GenieClient(clientOptions),
56954
- catalogs: new CatalogsClient(clientOptions),
56955
- schemas: new SchemasClient(clientOptions),
56956
- volumes: new VolumesClient(clientOptions),
56957
- grants: new GrantsClient(clientOptions),
56958
- tables: new TablesClient(clientOptions),
56959
- scim: new ScimClient(clientOptions),
56960
- experiments: new ExperimentsClient(clientOptions),
56961
- postgres: new PostgresClient(clientOptions),
56962
- rawProtocol: new DatabricksRawProtocolClient({
56963
- host: options.host,
56964
- token: options.tokenProvider,
56965
- ...options.fetchImpl ? { fetchImpl: options.fetchImpl } : {},
56966
- ...options.extraHeaders ? { extraHeaders: options.extraHeaders } : {}
56967
- })
56968
- };
56969
- }
56970
- function createDatabricksScimClient(options) {
56971
- return new ScimClient(generatedClientOptions(options));
56972
- }
56973
- function generatedClientOptions(options) {
56974
- return {
56975
- host: options.host,
56976
- credentials: options.credentials,
56977
- httpClient: fabricHttpClient(options.fetchImpl ?? fetch, options.extraHeaders),
56978
- profileOptions: { noProfile: true, disableEnv: true },
56979
- ...options.timeoutMs !== void 0 ? { timeout: options.timeoutMs } : {}
56980
- };
56981
- }
56982
- function fabricHttpClient(fetchImpl, extraHeaders) {
56983
- return {
56984
- async send(request) {
56985
- const headers = new Headers(request.headers);
56986
- const resolved = typeof extraHeaders === "function" ? await extraHeaders() : extraHeaders;
56987
- for (const [key, value] of Object.entries(resolved ?? {})) headers.set(key, value);
56988
- const body = request.body instanceof Uint8Array ? request.body.buffer.slice(
56989
- request.body.byteOffset,
56990
- request.body.byteOffset + request.body.byteLength
56991
- ) : request.body;
56992
- const init = {
56993
- method: request.method,
56994
- headers,
56995
- ...body !== void 0 ? { body } : {},
56996
- ...request.signal ? { signal: request.signal } : {}
56997
- };
56998
- if (request.body instanceof ReadableStream) {
56999
- init.duplex = "half";
57000
- }
57001
- const response = await fetchImpl(request.url, init);
57002
- return {
57003
- statusCode: response.status,
57004
- headers: response.headers,
57005
- body: response.body
57006
- };
57007
- }
57008
- };
57009
- }
57010
-
57011
- // src/lakebase.ts
57012
- import { createRequire } from "module";
57013
- var require2 = createRequire(import.meta.url);
57014
- function lakebaseCredentialProvider(options) {
57015
- const now = options.now ?? Date.now;
57016
- const random = options.random ?? Math.random;
57017
- const refreshBeforeMs = options.refreshBeforeMs ?? 5 * 6e4;
57018
- const refreshJitterMs = options.refreshJitterMs ?? 3e4;
57019
- let cached4;
57020
- let refreshing;
57021
- const refresh = async () => {
57022
- const value = await options.client.generateDatabaseCredential({ endpoint: options.endpoint });
57023
- if (typeof value.token !== "string" || !value.token) {
57024
- throw new Error("Lakebase credential exchange returned no token.");
57025
- }
57026
- const expiresAt = value.expireTime?.epochMilliseconds ?? Number.NaN;
57027
- if (!Number.isFinite(expiresAt)) {
57028
- throw new Error("Lakebase credential exchange returned an invalid expire_time.");
57029
- }
57030
- const jitter4 = Math.max(0, refreshJitterMs) * random();
57031
- cached4 = {
57032
- token: value.token,
57033
- refreshAt: Math.max(now(), expiresAt - Math.max(0, refreshBeforeMs) - jitter4)
57034
- };
57035
- return value.token;
57036
- };
57037
- return async () => {
57038
- if (cached4 && now() < cached4.refreshAt) return cached4.token;
57039
- refreshing ??= refresh().finally(() => {
57040
- refreshing = void 0;
57041
- });
57042
- return refreshing;
57043
- };
57044
- }
57045
- function lakebaseClient(options) {
57046
- const factory2 = options.poolFactory ?? defaultPoolFactory();
57047
- let password = options.password;
57048
- if (password === void 0) {
57049
- if (!options.credentialClient || !options.endpoint) {
57050
- throw new Error(
57051
- "Lakebase OAuth requires credentialClient and endpoint. A workspace token cannot be used directly as the Postgres password."
57052
- );
57053
- }
57054
- password = lakebaseCredentialProvider({
57055
- client: options.credentialClient,
57056
- endpoint: options.endpoint,
57057
- ...options.refreshBeforeMs !== void 0 ? { refreshBeforeMs: options.refreshBeforeMs } : {},
57058
- ...options.refreshJitterMs !== void 0 ? { refreshJitterMs: options.refreshJitterMs } : {}
57059
- });
57060
- }
57061
- const client = factory2({
57062
- host: options.host,
57063
- port: options.port ?? 5432,
57064
- database: options.database,
57065
- user: options.user,
57066
- password,
57067
- ssl: options.ssl ?? { rejectUnauthorized: true },
57068
- ...options.max !== void 0 ? { max: options.max } : {}
57069
- });
57070
- client.on?.("error", options.onPoolError ?? (() => void 0));
57071
- return client;
57072
- }
57073
- function defaultPoolFactory() {
57074
- let PoolCtor;
57075
- try {
57076
- PoolCtor = require2("pg").Pool;
57077
- } catch (error51) {
57078
- throw new Error(
57079
- `Lakebase store requires the optional "pg" package to be installed by the application. Run: pnpm add pg. ${error51 instanceof Error ? error51.message : String(error51)}`
57080
- );
57081
- }
57082
- return (config2) => new PoolCtor(config2);
57083
- }
57084
-
57085
- // src/lakeflow-authoring.ts
57086
- var DatabricksLakeflowAuthoring = class {
57087
- constructor(client, statements) {
57088
- this.client = client;
57089
- this.statements = statements;
57090
- }
57091
- async createPipeline(spec) {
57092
- const response = await this.client.create(serialize(spec));
57093
- if (!response.pipelineId)
57094
- throw new Error("Databricks Lakeflow create response did not contain pipeline_id.");
57095
- return { pipelineId: response.pipelineId };
57096
- }
57097
- async updatePipeline(pipelineId, spec) {
57098
- await this.client.edit({ pipelineId, id: pipelineId, ...serialize(spec) });
57099
- }
57100
- async deletePipeline(pipelineId) {
57101
- await this.client.delete({ pipelineId });
57102
- }
57103
- async pipelineEvents(pipelineId, warehouseId, limit = 100) {
57104
- const escaped = pipelineId.replace(/'/g, "''");
57105
- if (!this.statements)
57106
- throw new Error("Databricks Lakeflow events require a Statement Execution client.");
57107
- return runStatement(
57108
- this.statements,
57109
- warehouseId,
57110
- `SELECT * FROM event_log('${escaped}') ORDER BY timestamp DESC LIMIT ${Math.max(1, Math.min(1e3, Math.floor(limit)))}`,
57111
- [],
57112
- { intervalMs: 2e3, timeoutMs: 12e4 }
57113
- );
57114
- }
57115
- };
57116
- function databricksLakeflowAuthoringTools(client, options = {}) {
57117
- const api = new DatabricksLakeflowAuthoring(client, options.statements);
57118
- const spec = specSchema();
57119
- const specProperties2 = spec.properties;
57120
- const resources = [
57121
- { kind: "pipeline", path: "/name" },
57122
- { kind: "catalog", path: "/catalog", catalogQualified: true, optional: true },
57123
- { kind: "notebook", path: "/libraries/*/notebook/path", optional: true }
57124
- ];
57125
- const tools = [
57126
- tool2(
57127
- "databricks_create_pipeline",
57128
- "write",
57129
- spec,
57130
- resources,
57131
- (input) => api.createPipeline(input)
57132
- ),
57133
- tool2(
57134
- "databricks_update_pipeline",
57135
- "write",
57136
- {
57137
- type: "object",
57138
- additionalProperties: false,
57139
- properties: { pipelineId: { type: "string" }, ...specProperties2 },
57140
- required: ["pipelineId", "name", "libraries"]
57141
- },
57142
- [{ kind: "pipeline", path: "/pipelineId" }, ...resources.slice(1)],
57143
- (input) => api.updatePipeline(input.pipelineId, input)
57144
- ),
57145
- tool2(
57146
- "databricks_delete_pipeline",
57147
- "write",
57148
- idSchema3(),
57149
- [{ kind: "pipeline", path: "/pipelineId" }],
57150
- (input) => api.deletePipeline(input.pipelineId)
57151
- )
57152
- ];
57153
- const warehouseId = options.warehouseId;
57154
- if (warehouseId)
57155
- tools.push(
57156
- tool2(
57157
- "databricks_pipeline_events",
57158
- "read",
57159
- {
57160
- type: "object",
57161
- additionalProperties: false,
57162
- properties: { pipelineId: { type: "string" }, limit: { type: "number" } },
57163
- required: ["pipelineId"]
57164
- },
57165
- [{ kind: "pipeline", path: "/pipelineId" }],
57166
- (input) => api.pipelineEvents(
57167
- input.pipelineId,
57168
- warehouseId,
57169
- input.limit
57170
- )
57171
- )
57172
- );
57173
- return tools;
57174
- }
57175
- function tool2(name, effect, inputSchema, resources, execute2) {
57176
- return {
57177
- name,
57178
- description: name.replaceAll("_", " "),
57179
- inputSchema,
57180
- metadata: { effect, provider: "databricks", service: "lakeflow", governance: { resources } },
57181
- execute: execute2
57182
- };
57183
- }
57184
- function idSchema3() {
57185
- return {
57186
- type: "object",
57187
- additionalProperties: false,
57188
- properties: { pipelineId: { type: "string" } },
57189
- required: ["pipelineId"]
57190
- };
57191
- }
57192
- function specSchema() {
57193
- return {
57194
- type: "object",
57195
- additionalProperties: false,
57196
- properties: {
57197
- name: { type: "string" },
57198
- libraries: {
57199
- type: "array",
57200
- items: {
57201
- type: "object",
57202
- properties: {
57203
- notebook: { type: "object", properties: { path: { type: "string" } } },
57204
- file: { type: "object", properties: { path: { type: "string" } } },
57205
- jar: { type: "string" },
57206
- whl: { type: "string" }
57207
- }
57208
- }
57209
- },
57210
- catalog: { type: "string" },
57211
- target: { type: "string" },
57212
- continuous: { type: "boolean" },
57213
- serverless: { type: "boolean" },
57214
- development: { type: "boolean" },
57215
- configuration: { type: "object", additionalProperties: { type: "string" } },
57216
- clusters: { type: "array", items: { type: "object", additionalProperties: true } }
57217
- },
57218
- required: ["name", "libraries"]
57219
- };
57220
- }
57221
- function serialize(spec) {
57222
- return {
57223
- name: spec.name,
57224
- libraries: spec.libraries.map(serializeLibrary),
57225
- ...spec.catalog ? { catalog: spec.catalog } : {},
57226
- ...spec.target ? { target: spec.target } : {},
57227
- ...spec.continuous !== void 0 ? { continuous: spec.continuous } : {},
57228
- ...spec.serverless !== void 0 ? { serverless: spec.serverless } : {},
57229
- ...spec.development !== void 0 ? { development: spec.development } : {},
57230
- ...spec.configuration ? { configuration: spec.configuration } : {},
57231
- ...spec.clusters ? { clusters: spec.clusters } : {}
57232
- };
57233
- }
57234
- function serializeLibrary(library) {
57235
- if (library.notebook)
57236
- return { lib: { $case: "notebook", notebook: { path: library.notebook.path } } };
57237
- if (library.file) return { lib: { $case: "file", file: { path: library.file.path } } };
57238
- if (library.jar) return { lib: { $case: "jar", jar: library.jar } };
57239
- if (library.whl) return { lib: { $case: "whl", whl: library.whl } };
57240
- throw new Error("Databricks Lakeflow library requires notebook, file, jar, or whl.");
57241
- }
57242
-
57243
- // src/lakeflow.ts
57244
- function databricksPipelineListTool(client, options = {}) {
57245
- return {
57246
- name: options.name ?? "databricks_pipeline_list",
57247
- description: options.description ?? "List Lakeflow Declarative Pipelines (DLT) in the workspace.",
57248
- inputSchema: {
57249
- type: "object",
57250
- additionalProperties: false,
57251
- properties: { maxResults: { type: "number", minimum: 1 }, filter: { type: "string" } }
57252
- },
57253
- metadata: { effect: "read", provider: "databricks", service: "lakeflow" },
57254
- execute: (input) => client.list({
57255
- ...input.maxResults !== void 0 ? { maxResults: input.maxResults } : {},
57256
- ...input.filter ? { filter: input.filter } : {}
57257
- })
57258
- };
57259
- }
57260
- function databricksPipelineStatusTool(client, options = {}) {
57261
- return {
57262
- name: options.name ?? "databricks_pipeline_status",
57263
- description: options.description ?? "Get a Lakeflow pipeline, including its state and latest updates.",
57264
- inputSchema: {
57265
- type: "object",
57266
- additionalProperties: false,
57267
- properties: { pipelineId: { type: "string" } },
57268
- required: ["pipelineId"]
57269
- },
57270
- metadata: { effect: "read", provider: "databricks", service: "lakeflow" },
57271
- execute: (input) => client.get({ pipelineId: input.pipelineId })
57272
- };
57273
- }
57274
- function databricksPipelineStartTool(client, options = {}) {
57275
- return {
57276
- name: options.name ?? "databricks_pipeline_start",
57277
- description: options.description ?? "Trigger a Lakeflow pipeline update (run). Set fullRefresh to reprocess all data.",
57278
- inputSchema: {
57279
- type: "object",
57280
- additionalProperties: false,
57281
- properties: { pipelineId: { type: "string" }, fullRefresh: { type: "boolean" } },
57282
- required: ["pipelineId"]
57283
- },
57284
- metadata: { effect: "execute", provider: "databricks", service: "lakeflow" },
57285
- execute: (input) => client.start({
57286
- pipelineId: input.pipelineId,
57287
- ...input.fullRefresh !== void 0 ? { fullRefresh: input.fullRefresh } : {}
57288
- })
57289
- };
57290
- }
57291
- function databricksPipelineStopTool(client, options = {}) {
57292
- return {
57293
- name: options.name ?? "databricks_pipeline_stop",
57294
- description: options.description ?? "Stop the active update of a Lakeflow pipeline.",
57295
- inputSchema: {
57296
- type: "object",
57297
- additionalProperties: false,
57298
- properties: { pipelineId: { type: "string" } },
57299
- required: ["pipelineId"]
57300
- },
57301
- metadata: { effect: "execute", provider: "databricks", service: "lakeflow" },
57302
- execute: (input) => client.stop({ pipelineId: input.pipelineId })
57303
- };
57304
- }
57305
- function databricksLakeflowTools(client) {
57306
- return [
57307
- databricksPipelineListTool(client),
57308
- databricksPipelineStatusTool(client),
57309
- databricksPipelineStartTool(client),
57310
- databricksPipelineStopTool(client)
57311
- ];
57312
- }
57313
-
57314
- // src/mlflow-tracing.ts
57315
- import { createHash } from "crypto";
57316
- import { eventToTelemetrySpan } from "@fabric-harness/sdk";
57317
- function mlflowTraceExporter(options) {
57318
- const onError = options.onError ?? ((context, error51) => {
57319
- console.error(`[fabric-harness:mlflow-tracing] ${context}:`, error51);
57320
- });
57321
- const buffers = /* @__PURE__ */ new Map();
57322
- return {
57323
- sink: {
57324
- record(event) {
57325
- try {
57326
- const key = `agent:${event.agent}:${event.instanceId}:${event.session}`;
57327
- if (event.type === "submission_started") {
57328
- buffers.set(key, {
57329
- submissionId: event.submissionId,
57330
- agent: event.agent,
57331
- instanceId: event.instanceId,
57332
- session: event.session,
57333
- startedAtMs: event.at,
57334
- attemptCount: event.attemptCount,
57335
- ...event.tenantId !== void 0 ? { tenantId: event.tenantId } : {},
57336
- spans: []
57337
- });
57338
- return;
57339
- }
57340
- if (event.type !== "submission_settled") return;
57341
- const buffer = buffers.get(key);
57342
- buffers.delete(key);
57343
- const startedAtMs = buffer?.startedAtMs ?? event.at - (event.durationMs ?? 0);
57344
- const attemptCount = event.attemptCount ?? buffer?.attemptCount;
57345
- const trace = buildMlflowTrace({
57346
- submissionId: event.submissionId,
57347
- agent: event.agent,
57348
- instanceId: event.instanceId,
57349
- session: event.session,
57350
- experimentId: options.experimentId,
57351
- startedAtMs,
57352
- settledAtMs: event.at,
57353
- state: event.outcome === "completed" ? "OK" : "ERROR",
57354
- spans: buffer?.spans ?? [],
57355
- ...attemptCount !== void 0 ? { attemptCount } : {},
57356
- ...event.tenantId !== void 0 ? { tenantId: event.tenantId } : {},
57357
- ...event.error !== void 0 ? { error: event.error } : {}
57358
- });
57359
- void options.client.post("/api/3.0/mlflow/traces", trace).catch((error51) => onError(`trace export failed for ${event.submissionId}`, error51));
57360
- } catch (error51) {
57361
- onError("telemetry event handling failed", error51);
57362
- }
57308
+ this.operation = op;
57309
+ if (op.done === void 0) {
57310
+ throw new Error("operation is missing the done field");
57363
57311
  }
57364
- },
57365
- onEvent(event) {
57366
- try {
57367
- if (!event.sessionId) return;
57368
- const buffer = buffers.get(event.sessionId);
57369
- if (!buffer) return;
57370
- const span = eventToTelemetrySpan(event);
57371
- if (span) buffer.spans.push(span);
57372
- } catch (error51) {
57373
- onError("event buffering failed", error51);
57312
+ if (!op.done) {
57313
+ throw new StillRunningError6();
57374
57314
  }
57315
+ if (op.result?.$case === "error") {
57316
+ const err = op.result.error;
57317
+ const msg = err.message !== void 0 && err.message !== "" ? err.message : "unknown error";
57318
+ const errorMsg = err.errorCode !== void 0 ? `[${err.errorCode}] ${msg}` : msg;
57319
+ throw new Error(`operation failed: ${errorMsg}`, {
57320
+ cause: err
57321
+ });
57322
+ }
57323
+ if (op.result?.$case !== "response") {
57324
+ throw new Error("operation completed without a response");
57325
+ }
57326
+ result = external_exports.lazy(() => unmarshalRoleSchema2).parse(op.result.response);
57327
+ };
57328
+ await executeWait6(call, options);
57329
+ if (result === void 0) {
57330
+ throw new Error("operation completed without a result.");
57375
57331
  }
57376
- };
57377
- }
57378
- function buildMlflowTrace(input) {
57379
- const traceBytes = sha256(input.submissionId).subarray(0, 16);
57380
- const traceIdBase64 = traceBytes.toString("base64");
57381
- const rootSpanId = spanIdFor(input.submissionId, 0);
57382
- const durationSeconds = Math.max(0, input.settledAtMs - input.startedAtMs) / 1e3;
57383
- const rootSpan = {
57384
- trace_id: traceIdBase64,
57385
- span_id: rootSpanId,
57386
- name: `fabric.submission ${input.agent}`,
57387
- start_time_unix_nano: toUnixNano(input.startedAtMs),
57388
- end_time_unix_nano: toUnixNano(input.settledAtMs),
57389
- attributes: toOtlpAttributes({
57390
- "fabric.submission_id": input.submissionId,
57391
- "fabric.agent": input.agent,
57392
- "fabric.instance_id": input.instanceId,
57393
- "fabric.session": input.session,
57394
- ...input.attemptCount !== void 0 ? { "fabric.attempt_count": input.attemptCount } : {},
57395
- ...input.error !== void 0 ? { "fabric.error": input.error } : {}
57396
- }),
57397
- status: {
57398
- code: input.state === "OK" ? "STATUS_CODE_OK" : "STATUS_CODE_ERROR",
57399
- ...input.error !== void 0 ? { message: input.error } : {}
57400
- }
57401
- };
57402
- const childSpans = input.spans.map(
57403
- (span, index) => ({
57404
- trace_id: traceIdBase64,
57405
- span_id: spanIdFor(input.submissionId, index + 1),
57406
- parent_span_id: rootSpanId,
57407
- name: span.name,
57408
- start_time_unix_nano: toUnixNano(Date.parse(span.startedAt)),
57409
- end_time_unix_nano: toUnixNano(Date.parse(span.endedAt)),
57410
- attributes: toOtlpAttributes(span.attributes),
57411
- status: { code: "STATUS_CODE_OK" }
57412
- })
57413
- );
57414
- return {
57415
- trace: {
57416
- trace_info: {
57417
- trace_id: `tr-${traceBytes.toString("hex")}`,
57418
- trace_location: {
57419
- type: "MLFLOW_EXPERIMENT",
57420
- mlflow_experiment: { experiment_id: input.experimentId }
57421
- },
57422
- request_time: new Date(input.startedAtMs).toISOString(),
57423
- execution_duration: `${durationSeconds.toFixed(3)}s`,
57424
- state: input.state,
57425
- trace_metadata: {
57426
- "fabric.submission_id": input.submissionId,
57427
- "fabric.agent": input.agent,
57428
- "fabric.instance_id": input.instanceId,
57429
- "fabric.session": input.session,
57430
- ...input.attemptCount !== void 0 ? { "fabric.attempt_count": String(input.attemptCount) } : {}
57431
- },
57432
- tags: {
57433
- "fabric.agent": input.agent,
57434
- ...input.tenantId !== void 0 ? { "fabric.tenant_id": input.tenantId } : {}
57435
- }
57436
- },
57437
- trace_data: { spans: [rootSpan, ...childSpans] }
57438
- }
57439
- };
57440
- }
57441
- function sha256(seed) {
57442
- return createHash("sha256").update(seed).digest();
57443
- }
57444
- function spanIdFor(submissionId, index) {
57445
- return sha256(`${submissionId}:span:${index}`).subarray(0, 8).toString("base64");
57446
- }
57447
- function toUnixNano(epochMs) {
57448
- return `${Math.round(epochMs)}000000`;
57449
- }
57450
- function toOtlpAttributes(attributes) {
57451
- return Object.entries(attributes).map(([key, value]) => {
57452
- if (typeof value === "number") {
57453
- return Number.isInteger(value) ? { key, value: { int_value: String(value) } } : { key, value: { double_value: value } };
57454
- }
57455
- return { key, value: { string_value: String(value) } };
57456
- });
57457
- }
57332
+ return result;
57333
+ }
57334
+ /** Checks whether the operation has completed */
57335
+ async done(options) {
57336
+ const op = await this.getOperation({ name: this.operation.name }, options);
57337
+ this.operation = op;
57338
+ return op.done;
57339
+ }
57340
+ };
57458
57341
 
57459
- // src/model.ts
57460
- import {
57461
- OpenAICompatibleModelProvider,
57462
- currentSubmissionContext as currentSubmissionContext2,
57463
- registerModelProvider
57464
- } from "@fabric-harness/sdk";
57465
- function databricksModelBaseUrl(host, mode) {
57466
- const normalized = databricksWorkspaceOrigin(host);
57467
- return mode === "ai-gateway" ? `${normalized}/ai-gateway/mlflow/v1` : `${normalized}/serving-endpoints`;
57342
+ // src/raw-protocol-client.ts
57343
+ import { redactText } from "@fabric-harness/sdk";
57344
+ function isRetryableStatus(status) {
57345
+ return status === 429 || status === 499 || status >= 500 && status <= 599;
57468
57346
  }
57469
- function isDatabricksModelService(model) {
57470
- return model?.startsWith("system.ai.") ?? false;
57347
+ function retryDelayMs(response, attempt, base2) {
57348
+ const retryAfter = response.headers.get("retry-after");
57349
+ if (retryAfter) {
57350
+ const seconds = Number(retryAfter);
57351
+ if (Number.isFinite(seconds)) return seconds * 1e3;
57352
+ }
57353
+ return base2 * 2 ** attempt;
57471
57354
  }
57472
- var DatabricksModelProvider = class {
57473
- name = "databricks";
57474
- options;
57475
- gateway;
57476
- serving;
57477
- explicit;
57355
+ var DATABRICKS_RAW_PROTOCOL_RULES = [
57356
+ {
57357
+ id: "workspace-objects",
57358
+ methods: ["GET", "POST"],
57359
+ path: /^\/api\/2\.0\/workspace\/(?:delete|export|get-status|import|list|mkdirs)$/u
57360
+ },
57361
+ {
57362
+ id: "mlflow-traces-v3",
57363
+ methods: ["POST"],
57364
+ path: /^\/api\/3\.0\/mlflow\/traces$/u
57365
+ },
57366
+ {
57367
+ id: "ai-gateway-discovery",
57368
+ methods: ["GET"],
57369
+ path: /^\/api\/(?:ai-gateway\/v2\/endpoints|2\.1\/unity-catalog\/model-services)$/u
57370
+ },
57371
+ {
57372
+ id: "agent-services-beta",
57373
+ methods: ["GET", "POST", "PATCH", "DELETE"],
57374
+ path: /^\/api\/2\.1\/unity-catalog\/(?:agent-services(?:\/[^/?#]+)?|permissions\/AGENT_SERVICE\/[^/?#]+)$/u
57375
+ },
57376
+ {
57377
+ id: "genie-agent-mode-beta",
57378
+ methods: ["GET", "POST"],
57379
+ path: /^\/api\/2\.0\/genie\/agents\/[^/?#]+\/(?:responses|conversations\/[^/?#]+\/items)$/u
57380
+ },
57381
+ {
57382
+ id: "genie-query-result-sdk-compatibility",
57383
+ methods: ["GET"],
57384
+ path: /^\/api\/2\.0\/genie\/spaces\/[^/?#]+\/conversations\/[^/?#]+\/messages\/[^/?#]+\/attachments\/[^/?#]+\/query-result$/u
57385
+ },
57386
+ {
57387
+ id: "vector-search-query-sdk-compatibility",
57388
+ methods: ["POST"],
57389
+ path: /^\/api\/2\.0\/vector-search\/indexes\/[^/?#]+\/query$/u
57390
+ },
57391
+ {
57392
+ id: "responses-agent-custom-schema",
57393
+ methods: ["POST"],
57394
+ path: /^\/serving-endpoints\/[^/?#]+\/invocations$/u
57395
+ }
57396
+ ];
57397
+ function assertRawProtocolAllowed(method, path3) {
57398
+ const normalizedMethod = method.toUpperCase();
57399
+ if (!path3.startsWith("/") || path3.includes("?") || path3.includes("#")) {
57400
+ throw new Error(
57401
+ `databricks raw protocol denied: ${normalizedMethod} ${path3}; pass a relative path and structured query parameters.`
57402
+ );
57403
+ }
57404
+ const rule = DATABRICKS_RAW_PROTOCOL_RULES.find(
57405
+ (candidate) => candidate.methods.includes(normalizedMethod) && candidate.path.test(path3)
57406
+ );
57407
+ if (!rule) {
57408
+ throw new Error(
57409
+ `databricks raw protocol denied: ${normalizedMethod} ${path3}; use an official @databricks/sdk-* service client.`
57410
+ );
57411
+ }
57412
+ }
57413
+ var DatabricksRawProtocolClient = class {
57414
+ host;
57415
+ token;
57416
+ fetchImpl;
57417
+ maxRetries;
57418
+ retryBaseDelayMs;
57419
+ signal;
57420
+ extraHeaders;
57478
57421
  constructor(options) {
57479
- this.options = options;
57480
- const common = {
57481
- name: this.name,
57482
- apiKey: typeof options.token === "string" ? options.token : "",
57483
- ...typeof options.token === "function" ? { tokenProvider: options.token } : {},
57484
- ...options.defaultModel !== void 0 ? { defaultModel: options.defaultModel } : {},
57485
- ...options.fetchImpl ? { fetchImpl: options.fetchImpl } : {}
57486
- };
57487
- this.gateway = new OpenAICompatibleModelProvider({
57488
- ...common,
57489
- baseUrl: databricksModelBaseUrl(options.host, "ai-gateway"),
57490
- headers: () => this.resolveHeaders(true)
57491
- });
57492
- this.serving = new OpenAICompatibleModelProvider({
57493
- ...common,
57494
- baseUrl: databricksModelBaseUrl(options.host, "serving-endpoints"),
57495
- headers: () => this.resolveHeaders(false)
57496
- });
57497
- this.explicit = options.baseUrl ? new OpenAICompatibleModelProvider({
57498
- ...common,
57499
- baseUrl: options.baseUrl,
57500
- headers: () => this.resolveHeaders(options.baseUrl?.includes("/ai-gateway/") ?? false)
57501
- }) : void 0;
57422
+ this.host = databricksWorkspaceOrigin(options.host);
57423
+ this.token = options.token;
57424
+ this.fetchImpl = options.fetchImpl ?? fetch;
57425
+ this.maxRetries = options.maxRetries ?? 3;
57426
+ this.retryBaseDelayMs = options.retryBaseDelayMs ?? 500;
57427
+ this.signal = options.signal;
57428
+ this.extraHeaders = options.extraHeaders;
57502
57429
  }
57503
- generate(request) {
57504
- return this.providerFor(request.model).generate(request);
57430
+ get(path3, query, options) {
57431
+ return this.requestJson("GET", path3, void 0, query, options);
57505
57432
  }
57506
- stream(request) {
57507
- const provider = this.providerFor(request.model);
57508
- if (!provider.stream)
57509
- throw new Error("databricks: selected provider does not support streaming.");
57510
- return provider.stream(request);
57433
+ post(path3, body, query, options) {
57434
+ return this.requestJson("POST", path3, body, query, options);
57511
57435
  }
57512
- getModelMetadata(model = this.options.defaultModel) {
57513
- const mode = this.modeFor(model);
57514
- return {
57515
- provider: this.name,
57516
- ...model ? { model } : {},
57517
- gateway: this.options.baseUrl ?? databricksModelBaseUrl(this.options.host, mode),
57518
- ...model && this.options.modelMetadata?.[model] ? this.options.modelMetadata[model] : {}
57519
- };
57436
+ patch(path3, body, query, options) {
57437
+ return this.requestJson("PATCH", path3, body, query, options);
57520
57438
  }
57521
- providerFor(model = this.options.defaultModel) {
57522
- if (this.explicit) return this.explicit;
57523
- return this.modeFor(model) === "ai-gateway" ? this.gateway : this.serving;
57439
+ delete(path3, body, query, options) {
57440
+ return this.requestJson("DELETE", path3, body, query, options);
57524
57441
  }
57525
- modeFor(model) {
57526
- const configured = this.options.mode ?? "auto";
57527
- if (configured !== "auto") return configured;
57528
- return isDatabricksModelService(model) ? "ai-gateway" : "serving-endpoints";
57442
+ async requestJson(method, path3, body, query = {}, options = {}) {
57443
+ const response = await this.send(method, path3, body, query, options);
57444
+ if (response.status === 204) return void 0;
57445
+ return await response.json();
57529
57446
  }
57530
- async resolveHeaders(gateway) {
57531
- const configured = typeof this.options.headers === "function" ? await this.options.headers() : this.options.headers ?? {};
57532
- if (!gateway) return configured;
57533
- const supplied = typeof this.options.requestTags === "function" ? await this.options.requestTags() : this.options.requestTags ?? {};
57534
- const context = currentSubmissionContext2();
57535
- const tags = compactTags({
57536
- ...context?.submissionId ? { submission_id: context.submissionId } : {},
57537
- ...context?.attemptId ? { attempt_id: context.attemptId } : {},
57538
- ...context?.tenantId ? { tenant_id: context.tenantId } : {},
57539
- ...context?.agent ? { agent: context.agent } : {},
57540
- ...supplied
57541
- });
57542
- return Object.keys(tags).length > 0 ? { ...configured, "Databricks-Ai-Gateway-Request-Tags": JSON.stringify(tags) } : configured;
57447
+ /**
57448
+ * Perform an authenticated request while leaving a successful response body unread. This is
57449
+ * intended for bounded binary downloads and streaming APIs such as Genie Agent Mode.
57450
+ */
57451
+ postRaw(path3, body, query = {}, options = {}) {
57452
+ return this.send("POST", path3, body, query, options);
57453
+ }
57454
+ async send(method, path3, body, query, options) {
57455
+ assertRawProtocolAllowed(method, path3);
57456
+ const url2 = new URL(`${this.host}${path3.startsWith("/") ? path3 : `/${path3}`}`);
57457
+ for (const [key, value] of Object.entries(query))
57458
+ if (value !== void 0) url2.searchParams.set(key, String(value));
57459
+ const canRetry = options.retry === "always" || options.retry !== "never" && (options.retry === "safe" || method === "GET" || method === "HEAD");
57460
+ const maxRetries = canRetry ? options.maxRetries ?? this.maxRetries : 0;
57461
+ const signal = combineAbortSignals(this.signal, options.signal);
57462
+ for (let attempt = 0; ; attempt += 1) {
57463
+ const token = typeof this.token === "function" ? await this.token() : this.token;
57464
+ const extra = typeof this.extraHeaders === "function" ? await this.extraHeaders() : this.extraHeaders;
57465
+ const init = {
57466
+ method,
57467
+ headers: {
57468
+ authorization: `Bearer ${token}`,
57469
+ ...options.accept ? { accept: options.accept } : {},
57470
+ ...body !== void 0 ? { "content-type": "application/json" } : {},
57471
+ ...extra
57472
+ },
57473
+ ...body !== void 0 ? { body: JSON.stringify(body) } : {},
57474
+ ...signal ? { signal } : {}
57475
+ };
57476
+ let response;
57477
+ try {
57478
+ response = await this.fetchImpl(url2, init);
57479
+ } catch (error51) {
57480
+ if (signal?.aborted || attempt >= maxRetries) throw error51;
57481
+ await abortableSleep2(this.retryBaseDelayMs * 2 ** attempt, signal);
57482
+ continue;
57483
+ }
57484
+ if (response.ok) {
57485
+ return response;
57486
+ }
57487
+ if (isRetryableStatus(response.status) && attempt < maxRetries) {
57488
+ await response.body?.cancel();
57489
+ await abortableSleep2(retryDelayMs(response, attempt, this.retryBaseDelayMs), signal);
57490
+ continue;
57491
+ }
57492
+ const text = redactText(await response.text(), { additionalSecrets: [token] });
57493
+ throw new Error(
57494
+ `databricks: ${response.status} ${response.statusText}: ${text.slice(0, 2e3)}`
57495
+ );
57496
+ }
57543
57497
  }
57544
57498
  };
57545
- function compactTags(tags) {
57546
- return Object.fromEntries(
57547
- Object.entries(tags).filter(([key, value]) => key.length > 0 && value.length > 0).map(([key, value]) => [key.slice(0, 128), value.slice(0, 512)])
57548
- );
57499
+ function combineAbortSignals(clientSignal, requestSignal) {
57500
+ if (!clientSignal) return requestSignal;
57501
+ if (!requestSignal || requestSignal === clientSignal) return clientSignal;
57502
+ return AbortSignal.any([clientSignal, requestSignal]);
57549
57503
  }
57550
- function databricksFoundationModelProvider(options) {
57551
- return new DatabricksModelProvider(options);
57504
+ function abortableSleep2(ms, signal) {
57505
+ if (signal?.aborted)
57506
+ return Promise.reject(
57507
+ signal.reason ?? new DOMException("The operation was aborted.", "AbortError")
57508
+ );
57509
+ if (!signal) return new Promise((resolve2) => setTimeout(resolve2, ms));
57510
+ return new Promise((resolve2, reject) => {
57511
+ const timer = setTimeout(() => {
57512
+ signal.removeEventListener("abort", abort);
57513
+ resolve2();
57514
+ }, ms);
57515
+ const abort = () => {
57516
+ clearTimeout(timer);
57517
+ reject(signal.reason ?? new DOMException("The operation was aborted.", "AbortError"));
57518
+ };
57519
+ signal.addEventListener("abort", abort, { once: true });
57520
+ });
57552
57521
  }
57553
- function inferenceMode(value) {
57554
- if (!value) return void 0;
57555
- if (value === "auto" || value === "ai-gateway" || value === "serving-endpoints") return value;
57556
- throw new Error(
57557
- `Invalid DATABRICKS_INFERENCE_MODE "${value}". Use auto, ai-gateway, or serving-endpoints.`
57522
+
57523
+ // src/native-sdk.ts
57524
+ function databricksSdk(options) {
57525
+ const tokenProvider = databricksIdentity(options.principal);
57526
+ return stableDatabricksSdkClients(
57527
+ createDatabricksNativeClients({
57528
+ host: options.host,
57529
+ credentials: databricksCredentials(options.principal),
57530
+ tokenProvider,
57531
+ ...options.fetchImpl ? { fetchImpl: options.fetchImpl } : {},
57532
+ ...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {},
57533
+ ...options.extraHeaders ? { extraHeaders: options.extraHeaders } : {}
57534
+ })
57558
57535
  );
57559
57536
  }
57560
- function origin(value) {
57561
- try {
57562
- return new URL(value).origin;
57563
- } catch {
57564
- return value;
57565
- }
57537
+ function stableDatabricksSdkClients(clients) {
57538
+ const { rawProtocol: _rawProtocol, ...sdk } = clients;
57539
+ return sdk;
57566
57540
  }
57567
- var factory = (parsed, providers, env2, warnings) => {
57568
- const settings = providers?.databricks;
57569
- const configuredUrl = settings?.baseUrl;
57570
- const rawHost = env2.DATABRICKS_HOST ?? (configuredUrl ? origin(configuredUrl) : void 0);
57571
- if (!rawHost)
57572
- throw new Error(
57573
- "Missing Databricks host. Set DATABRICKS_HOST or providers.databricks.baseUrl."
57574
- );
57575
- const host = rawHost.includes("://") ? rawHost : `https://${rawHost}`;
57576
- const staticToken = settings?.apiKey?.trim() || env2[settings?.apiKeyEnv ?? "DATABRICKS_TOKEN"]?.trim() || env2.DATABRICKS_API_KEY?.trim();
57577
- let principal;
57578
- if (!staticToken) {
57579
- try {
57580
- principal = databricksPrincipalFromEnv(env2);
57581
- } catch {
57582
- }
57583
- }
57584
- if (!staticToken && !principal)
57585
- throw new Error(
57586
- "Missing Databricks credentials. Set DATABRICKS_TOKEN, DATABRICKS_CLIENT_ID + DATABRICKS_CLIENT_SECRET, or providers.databricks.apiKey/apiKeyEnv."
57587
- );
57588
- const token = staticToken ?? databricksIdentity(principal);
57589
- const explicitBaseUrl = env2.DATABRICKS_AI_GATEWAY_BASE_URL ?? (configuredUrl && new URL(configuredUrl).pathname !== "/" ? configuredUrl : void 0);
57590
- const mode = inferenceMode(env2.DATABRICKS_INFERENCE_MODE);
57541
+ function createDatabricksNativeClients(options) {
57542
+ const clientOptions = generatedClientOptions(options);
57591
57543
  return {
57592
- model: parsed.modelId,
57593
- provider: databricksFoundationModelProvider({
57594
- host,
57595
- token,
57596
- defaultModel: parsed.modelId,
57597
- ...explicitBaseUrl ? { baseUrl: explicitBaseUrl } : {},
57598
- ...mode ? { mode } : {},
57599
- ...settings?.headers ? { headers: settings.headers } : {}
57600
- }),
57601
- providerName: "databricks",
57602
- modelId: parsed.modelId,
57603
- warnings
57544
+ accessManagement: new AccessManagementClient(clientOptions),
57545
+ jobs: new JobsClient(clientOptions),
57546
+ statements: new StatementExecutionClient(clientOptions),
57547
+ pipelines: new PipelinesClient(clientOptions),
57548
+ vectorSearch: new VectorSearchClient(clientOptions),
57549
+ modelServing: new ModelServingClient(clientOptions),
57550
+ modelServingQuery: new ModelServingQueryClient(clientOptions),
57551
+ files: new FilesClient(clientOptions),
57552
+ secrets: new SecretsClient(clientOptions),
57553
+ genie: new GenieClient(clientOptions),
57554
+ catalogs: new CatalogsClient(clientOptions),
57555
+ schemas: new SchemasClient(clientOptions),
57556
+ volumes: new VolumesClient(clientOptions),
57557
+ grants: new GrantsClient(clientOptions),
57558
+ tables: new TablesClient(clientOptions),
57559
+ scim: new ScimClient(clientOptions),
57560
+ experiments: new ExperimentsClient(clientOptions),
57561
+ postgres: new PostgresClient(clientOptions),
57562
+ rawProtocol: new DatabricksRawProtocolClient({
57563
+ host: options.host,
57564
+ token: options.tokenProvider,
57565
+ ...options.fetchImpl ? { fetchImpl: options.fetchImpl } : {},
57566
+ ...options.extraHeaders ? { extraHeaders: options.extraHeaders } : {}
57567
+ })
57568
+ };
57569
+ }
57570
+ function createDatabricksScimClient(options) {
57571
+ return new ScimClient(generatedClientOptions(options));
57572
+ }
57573
+ function generatedClientOptions(options) {
57574
+ return {
57575
+ host: options.host,
57576
+ credentials: options.credentials,
57577
+ httpClient: fabricHttpClient(options.fetchImpl ?? fetch, options.extraHeaders),
57578
+ profileOptions: { noProfile: true, disableEnv: true },
57579
+ ...options.timeoutMs !== void 0 ? { timeout: options.timeoutMs } : {}
57580
+ };
57581
+ }
57582
+ function fabricHttpClient(fetchImpl, extraHeaders) {
57583
+ return {
57584
+ async send(request) {
57585
+ const headers = new Headers(request.headers);
57586
+ const resolved = typeof extraHeaders === "function" ? await extraHeaders() : extraHeaders;
57587
+ for (const [key, value] of Object.entries(resolved ?? {})) headers.set(key, value);
57588
+ const body = request.body instanceof Uint8Array ? request.body.buffer.slice(
57589
+ request.body.byteOffset,
57590
+ request.body.byteOffset + request.body.byteLength
57591
+ ) : request.body;
57592
+ const init = {
57593
+ method: request.method,
57594
+ headers,
57595
+ ...body !== void 0 ? { body } : {},
57596
+ ...request.signal ? { signal: request.signal } : {}
57597
+ };
57598
+ if (request.body instanceof ReadableStream) {
57599
+ init.duplex = "half";
57600
+ }
57601
+ const response = await fetchImpl(request.url, init);
57602
+ return {
57603
+ statusCode: response.status,
57604
+ headers: response.headers,
57605
+ body: response.body
57606
+ };
57607
+ }
57604
57608
  };
57605
- };
57606
- var registered = false;
57607
- function registerDatabricksModelProvider() {
57608
- if (registered) return;
57609
- registered = true;
57610
- registerModelProvider("databricks", factory);
57611
57609
  }
57612
57610
 
57613
57611
  // src/secrets-authoring.ts
@@ -58908,16 +58906,16 @@ var DatabricksWorkspaceAuthoring = class {
58908
58906
  { retry: "never" }
58909
58907
  );
58910
58908
  }
58911
- deleteWorkspaceObject(path, recursive = false) {
58909
+ deleteWorkspaceObject(path3, recursive = false) {
58912
58910
  return this.client.post(
58913
58911
  "/api/2.0/workspace/delete",
58914
- { path, recursive },
58912
+ { path: path3, recursive },
58915
58913
  {},
58916
58914
  { retry: "never" }
58917
58915
  );
58918
58916
  }
58919
- mkdirs(path) {
58920
- return this.client.post("/api/2.0/workspace/mkdirs", { path }, {}, { retry: "safe" });
58917
+ mkdirs(path3) {
58918
+ return this.client.post("/api/2.0/workspace/mkdirs", { path: path3 }, {}, { retry: "safe" });
58921
58919
  }
58922
58920
  };
58923
58921
  function databricksWorkspaceAuthoringTools(client) {
@@ -58996,6 +58994,161 @@ function base643(value) {
58996
58994
  return btoa(String.fromCharCode(...bytes));
58997
58995
  }
58998
58996
 
58997
+ // src/app-deployment.ts
58998
+ import { spawn } from "child_process";
58999
+ import { access as access2 } from "fs/promises";
59000
+ import path from "path";
59001
+ async function validateDatabricksAppArtifact(options) {
59002
+ const artifactDir = path.resolve(options.artifactDir);
59003
+ await access2(path.join(artifactDir, "databricks.yml"));
59004
+ const run = options.run ?? runDatabricksCommand;
59005
+ const args = [
59006
+ "bundle",
59007
+ "validate",
59008
+ ...options.target ? ["--target", options.target] : [],
59009
+ ...options.profile ? ["--profile", options.profile] : []
59010
+ ];
59011
+ const executable = options.executable ?? "databricks";
59012
+ options.onCommand?.({ executable, args });
59013
+ const result = await run(executable, args, {
59014
+ cwd: artifactDir,
59015
+ env: options.env ?? process.env
59016
+ });
59017
+ requireSuccess("Databricks bundle validation", result);
59018
+ return { valid: true, output: lastNonEmptyLine(result.stdout) };
59019
+ }
59020
+ async function deployDatabricksAppArtifact(options) {
59021
+ const artifactDir = path.resolve(options.artifactDir);
59022
+ await access2(path.join(artifactDir, "databricks.yml"));
59023
+ const run = options.run ?? runDatabricksCommand;
59024
+ const profileArgs = options.profile ? ["--profile", options.profile] : [];
59025
+ const env2 = options.env ?? process.env;
59026
+ const executable = options.executable ?? "databricks";
59027
+ const bundleArgs = [
59028
+ "bundle",
59029
+ "deploy",
59030
+ ...options.target ? ["--target", options.target] : [],
59031
+ ...profileArgs
59032
+ ];
59033
+ options.onCommand?.({ executable, args: bundleArgs });
59034
+ const bundle = await run(executable, bundleArgs, { cwd: artifactDir, env: env2 });
59035
+ requireSuccess("Databricks bundle synchronization", bundle);
59036
+ if (options.startBeforeDeploy && options.appName) {
59037
+ const startArgs = ["apps", "start", options.appName, ...profileArgs];
59038
+ options.onCommand?.({ executable, args: startArgs });
59039
+ const start = await run(executable, startArgs, { cwd: artifactDir, env: env2 });
59040
+ requireSuccess("Databricks App compute start", start);
59041
+ }
59042
+ const appArgs = [
59043
+ "apps",
59044
+ "deploy",
59045
+ ...options.appName ? [options.appName] : [],
59046
+ ...options.sourceCodePath ? ["--source-code-path", options.sourceCodePath] : [],
59047
+ ...options.mode ? ["--mode", options.mode] : [],
59048
+ "--skip-validation",
59049
+ "--auto-approve",
59050
+ ...profileArgs
59051
+ ];
59052
+ options.onCommand?.({ executable, args: appArgs });
59053
+ const app = await run(executable, appArgs, { cwd: artifactDir, env: env2 });
59054
+ requireSuccess("Databricks App snapshot activation", app);
59055
+ return {
59056
+ bundleSynchronized: true,
59057
+ appSnapshotActivated: true,
59058
+ bundleOutput: lastNonEmptyLine(bundle.stdout),
59059
+ appOutput: lastNonEmptyLine(app.stdout)
59060
+ };
59061
+ }
59062
+ async function destroyDatabricksAppArtifact(options) {
59063
+ const artifactDir = path.resolve(options.artifactDir);
59064
+ await access2(path.join(artifactDir, "databricks.yml"));
59065
+ const run = options.run ?? runDatabricksCommand;
59066
+ const args = [
59067
+ "bundle",
59068
+ "destroy",
59069
+ "--auto-approve",
59070
+ ...options.target ? ["--target", options.target] : [],
59071
+ ...options.profile ? ["--profile", options.profile] : []
59072
+ ];
59073
+ const executable = options.executable ?? "databricks";
59074
+ options.onCommand?.({ executable, args });
59075
+ const result = await run(executable, args, {
59076
+ cwd: artifactDir,
59077
+ env: options.env ?? process.env
59078
+ });
59079
+ requireSuccess("Databricks bundle teardown", result);
59080
+ return { destroyed: true, output: lastNonEmptyLine(result.stdout) };
59081
+ }
59082
+ async function runDatabricksCommand(command, args, options) {
59083
+ return new Promise((resolve2, reject) => {
59084
+ const child = spawn(command, [...args], {
59085
+ cwd: options.cwd,
59086
+ env: options.env,
59087
+ shell: false,
59088
+ stdio: ["ignore", "pipe", "pipe"]
59089
+ });
59090
+ let stdout = "";
59091
+ let stderr = "";
59092
+ child.stdout.on("data", (chunk) => {
59093
+ stdout += chunk.toString();
59094
+ });
59095
+ child.stderr.on("data", (chunk) => {
59096
+ stderr += chunk.toString();
59097
+ });
59098
+ child.once("error", reject);
59099
+ child.once("close", (code) => resolve2({ exitCode: code ?? -1, stdout, stderr }));
59100
+ });
59101
+ }
59102
+ function requireSuccess(label, result) {
59103
+ if (result.exitCode === 0) return;
59104
+ const detail = result.stderr.trim().slice(-2e3);
59105
+ throw new Error(
59106
+ `${label} failed with exit code ${result.exitCode}${detail ? `: ${detail}` : ""}`
59107
+ );
59108
+ }
59109
+ function lastNonEmptyLine(value) {
59110
+ return value.split("\n").map((line) => line.trim()).filter(Boolean).at(-1) ?? "";
59111
+ }
59112
+
59113
+ // src/artifact-digest.ts
59114
+ import { createHash as createHash2 } from "crypto";
59115
+ import { lstat, readFile as readFile2, readdir } from "fs/promises";
59116
+ import path2 from "path";
59117
+ async function digestDatabricksArtifact(target) {
59118
+ const targetInfo = await lstat(target);
59119
+ rejectUnsupportedEntry(target, targetInfo);
59120
+ if (targetInfo.isFile()) {
59121
+ return createHash2("sha256").update(await readFile2(target)).digest("hex");
59122
+ }
59123
+ const hash2 = createHash2("sha256");
59124
+ async function append(directory, relativeDirectory) {
59125
+ for (const name of (await readdir(directory)).sort()) {
59126
+ const candidate = path2.join(directory, name);
59127
+ const relative = path2.join(relativeDirectory, name).replaceAll(path2.sep, "/");
59128
+ const info = await lstat(candidate);
59129
+ rejectUnsupportedEntry(relative, info);
59130
+ if (info.isDirectory()) {
59131
+ hash2.update(`directory\0${relative}\0`);
59132
+ await append(candidate, relative);
59133
+ } else {
59134
+ const bytes = await readFile2(candidate);
59135
+ hash2.update(`file\0${relative}\0${bytes.byteLength}\0`);
59136
+ hash2.update(bytes);
59137
+ }
59138
+ }
59139
+ }
59140
+ await append(target, "");
59141
+ return hash2.digest("hex");
59142
+ }
59143
+ function rejectUnsupportedEntry(entry, info) {
59144
+ if (info.isSymbolicLink()) {
59145
+ throw new Error(`Databricks artifact digest rejects symbolic links: ${entry}`);
59146
+ }
59147
+ if (!info.isFile() && !info.isDirectory()) {
59148
+ throw new Error(`Databricks artifact digest rejects non-file entries: ${entry}`);
59149
+ }
59150
+ }
59151
+
58999
59152
  // src/persistence.ts
59000
59153
  function databricksPersistence(options) {
59001
59154
  const client = isLakebaseClient(options.lakebase) ? options.lakebase : lakebaseClient(options.lakebase);
@@ -59325,17 +59478,17 @@ var UcVolumesAttachmentStore = class {
59325
59478
  return `${this.bytesPath(scope, digest)}.json`;
59326
59479
  }
59327
59480
  // ─── Files API ────────────────────────────────────────────────────────────
59328
- async writeFile(path, bytes) {
59481
+ async writeFile(path3, bytes) {
59329
59482
  await this.client.uploadFile({
59330
- filePath: path,
59483
+ filePath: path3,
59331
59484
  overwrite: true,
59332
59485
  contents: new Blob([viewToBuffer(bytes)]).stream()
59333
59486
  });
59334
59487
  }
59335
59488
  /** Raw file bytes, or `null` when the file does not exist (404). */
59336
- async readFile(path) {
59489
+ async readFile(path3) {
59337
59490
  try {
59338
- const response = await this.client.downloadFile({ filePath: path });
59491
+ const response = await this.client.downloadFile({ filePath: path3 });
59339
59492
  if (!response.contents) return new Uint8Array();
59340
59493
  return new Uint8Array(await new Response(response.contents).arrayBuffer());
59341
59494
  } catch (error51) {
@@ -59344,9 +59497,9 @@ var UcVolumesAttachmentStore = class {
59344
59497
  }
59345
59498
  }
59346
59499
  /** True when the file existed and was deleted; false on 404. */
59347
- async deleteFile(path) {
59500
+ async deleteFile(path3) {
59348
59501
  try {
59349
- await this.client.deleteFile({ filePath: path });
59502
+ await this.client.deleteFile({ filePath: path3 });
59350
59503
  return true;
59351
59504
  } catch (error51) {
59352
59505
  if (isNotFound(error51)) return false;
@@ -59354,14 +59507,14 @@ var UcVolumesAttachmentStore = class {
59354
59507
  }
59355
59508
  }
59356
59509
  /** Immediate children of a directory; empty for a missing directory (404). */
59357
- async listDirectory(path) {
59510
+ async listDirectory(path3) {
59358
59511
  const entries = [];
59359
59512
  let pageToken;
59360
59513
  do {
59361
59514
  let listing;
59362
59515
  try {
59363
59516
  listing = await this.client.listDirectoryContents({
59364
- directoryPath: path,
59517
+ directoryPath: path3,
59365
59518
  ...pageToken ? { pageToken } : {}
59366
59519
  });
59367
59520
  } catch (error51) {
@@ -59517,7 +59670,7 @@ function parseInferenceMode(value) {
59517
59670
  }
59518
59671
 
59519
59672
  // src/app-user-authorization.ts
59520
- import { createHash as createHash2 } from "crypto";
59673
+ import { createHash as createHash3 } from "crypto";
59521
59674
  var DATABRICKS_APP_USER_PERMISSIONS = [
59522
59675
  "agent:invoke",
59523
59676
  "approval:read",
@@ -59553,12 +59706,12 @@ function createDatabricksAppUserAuthenticator(options) {
59553
59706
  id,
59554
59707
  kind: "service-principal",
59555
59708
  provider: "databricks-apps",
59556
- tenantId: `databricks-service-principal:${createHash2("sha256").update(id).digest("hex").slice(0, 24)}`,
59709
+ tenantId: `databricks-service-principal:${createHash3("sha256").update(id).digest("hex").slice(0, 24)}`,
59557
59710
  permissions: [...permissions]
59558
59711
  };
59559
59712
  }
59560
59713
  const token = await databricksIdentity(delegated)();
59561
- const digest = createHash2("sha256").update(token).digest("hex");
59714
+ const digest = createHash3("sha256").update(token).digest("hex");
59562
59715
  const cached4 = cache.get(digest);
59563
59716
  if (cached4 && cached4.expiresAt > now) return cached4.principal;
59564
59717
  try {
@@ -59569,7 +59722,7 @@ function createDatabricksAppUserAuthenticator(options) {
59569
59722
  ...options.now ? { now: options.now } : {}
59570
59723
  });
59571
59724
  const id = inspection.principal.id;
59572
- const tenantId = options.tenantId?.(inspection) ?? `databricks-user:${createHash2("sha256").update(id).digest("hex").slice(0, 24)}`;
59725
+ const tenantId = options.tenantId?.(inspection) ?? `databricks-user:${createHash3("sha256").update(id).digest("hex").slice(0, 24)}`;
59573
59726
  if (!tenantId) return false;
59574
59727
  const principal = {
59575
59728
  id,
@@ -59597,7 +59750,7 @@ function appPrincipalFor(id, permissions) {
59597
59750
  id,
59598
59751
  kind: "app-principal",
59599
59752
  provider: "databricks-apps",
59600
- tenantId: `databricks-app:${createHash2("sha256").update(id).digest("hex").slice(0, 24)}`,
59753
+ tenantId: `databricks-app:${createHash3("sha256").update(id).digest("hex").slice(0, 24)}`,
59601
59754
  permissions: [...permissions]
59602
59755
  };
59603
59756
  }
@@ -62652,6 +62805,9 @@ export {
62652
62805
  databricksWorkspaceOrigin,
62653
62806
  defaultDatabricksCertificationChecks,
62654
62807
  defineDatabricksAgent,
62808
+ deployDatabricksAppArtifact,
62809
+ destroyDatabricksAppArtifact,
62810
+ digestDatabricksArtifact,
62655
62811
  ensureDatabricksTelemetryTables,
62656
62812
  exportAgentEvaluationJsonl,
62657
62813
  exportMlflow3EvaluationJsonl,
@@ -62678,6 +62834,7 @@ export {
62678
62834
  resolveToolRefs,
62679
62835
  runDatabricksAuthoringLifecycle,
62680
62836
  runDatabricksCertification,
62837
+ runDatabricksCommand,
62681
62838
  scoreRagTurn,
62682
62839
  serializeDatabricksGenieAgentSpec,
62683
62840
  servingUsageCapture,
@@ -62686,6 +62843,7 @@ export {
62686
62843
  toAgentEvaluationRecord,
62687
62844
  toMlflow3EvaluationRecord,
62688
62845
  unityCatalogTablesTool,
62846
+ validateDatabricksAppArtifact,
62689
62847
  validateDatabricksCertificationEnvironment,
62690
62848
  validateDatabricksComputePolicy,
62691
62849
  validateDatabricksGenieSqlReferences,