windmill-cli 1.811.1 → 1.813.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 (2) hide show
  1. package/esm/main.js +1243 -912
  2. package/package.json +1 -1
package/esm/main.js CHANGED
@@ -16766,7 +16766,7 @@ var init_OpenAPI = __esm(() => {
16766
16766
  PASSWORD: undefined,
16767
16767
  TOKEN: getEnv3("WM_TOKEN"),
16768
16768
  USERNAME: undefined,
16769
- VERSION: "1.811.1",
16769
+ VERSION: "1.813.0",
16770
16770
  WITH_CREDENTIALS: true,
16771
16771
  interceptors: {
16772
16772
  request: new Interceptors,
@@ -17066,6 +17066,37 @@ var getAuditLog = (data) => {
17066
17066
  all_workspaces: data.allWorkspaces
17067
17067
  }
17068
17068
  });
17069
+ }, listTrash = (data) => {
17070
+ return request(OpenAPI, {
17071
+ method: "GET",
17072
+ url: "/w/{workspace}/trash/list",
17073
+ path: {
17074
+ workspace: data.workspace
17075
+ },
17076
+ query: {
17077
+ item_kind: data.itemKind,
17078
+ page: data.page,
17079
+ per_page: data.perPage
17080
+ }
17081
+ });
17082
+ }, getTrashItem = (data) => {
17083
+ return request(OpenAPI, {
17084
+ method: "GET",
17085
+ url: "/w/{workspace}/trash/get/{id}",
17086
+ path: {
17087
+ workspace: data.workspace,
17088
+ id: data.id
17089
+ }
17090
+ });
17091
+ }, restoreTrashItem = (data) => {
17092
+ return request(OpenAPI, {
17093
+ method: "POST",
17094
+ url: "/w/{workspace}/trash/restore/{id}",
17095
+ path: {
17096
+ workspace: data.workspace,
17097
+ id: data.id
17098
+ }
17099
+ });
17069
17100
  }, login = (data) => {
17070
17101
  return request(OpenAPI, {
17071
17102
  method: "POST",
@@ -19971,352 +20002,7 @@ var init_auth = __esm(async () => {
19971
20002
  });
19972
20003
 
19973
20004
  // src/core/constants.ts
19974
- var WM_FORK_PREFIX = "wm-fork", VERSION = "1.811.1";
19975
-
19976
- // src/utils/git.ts
19977
- import { execSync, spawnSync } from "node:child_process";
19978
- function getCurrentGitBranch() {
19979
- try {
19980
- const result = execSync("git rev-parse --abbrev-ref HEAD", {
19981
- encoding: "utf8",
19982
- stdio: "pipe"
19983
- });
19984
- const branch = result.trim();
19985
- return branch || null;
19986
- } catch (error) {
19987
- debug(`Failed to get Git branch: ${error}`);
19988
- return null;
19989
- }
19990
- }
19991
- function gitBranchExists(branchName) {
19992
- const r = spawnSync("git", ["show-ref", "--verify", "--quiet", `refs/heads/${branchName}`], { stdio: "pipe" });
19993
- return r.status === 0;
19994
- }
19995
- function renameCurrentGitBranch(newName) {
19996
- const r = spawnSync("git", ["branch", "-m", newName], {
19997
- encoding: "utf8",
19998
- stdio: "pipe"
19999
- });
20000
- if ((r.status ?? 1) !== 0) {
20001
- throw new Error(`git branch -m ${newName} failed (exit ${r.status}): ${r.stderr ?? ""}`);
20002
- }
20003
- }
20004
- function getOriginalBranchForWorkspaceForks(branchName) {
20005
- if (!branchName || !branchName.startsWith(WM_FORK_PREFIX)) {
20006
- return null;
20007
- }
20008
- const start = branchName.indexOf("/") + 1;
20009
- const end = branchName.lastIndexOf("/");
20010
- if (start < 0 || end < 0 || end - start <= 0) {
20011
- return null;
20012
- }
20013
- return branchName.slice(start, end);
20014
- }
20015
- function getWorkspaceIdForWorkspaceForkFromBranchName(branchName) {
20016
- if (!branchName.startsWith(WM_FORK_PREFIX)) {
20017
- return null;
20018
- }
20019
- const start = branchName.lastIndexOf("/") + 1;
20020
- if (start < 0) {
20021
- return null;
20022
- }
20023
- return `${WM_FORK_PREFIX}-${branchName.slice(start)}`;
20024
- }
20025
- function gitRecordedDatatableMigrationPaths() {
20026
- if (!isGitRepository()) {
20027
- return {
20028
- kind: "unknown",
20029
- reason: "this directory is not a git repository",
20030
- remedy: "Run the push from a git checkout of the synced repository"
20031
- };
20032
- }
20033
- const shallow = spawnSync("git", ["rev-parse", "--is-shallow-repository"], {
20034
- encoding: "utf8",
20035
- stdio: "pipe"
20036
- });
20037
- if ((shallow.stdout ?? "").trim() === "true") {
20038
- return {
20039
- kind: "unknown",
20040
- reason: "this is a shallow clone, so its history is truncated",
20041
- remedy: "Fetch the full history (for actions/checkout, fetch-depth: 0)"
20042
- };
20043
- }
20044
- const sparse = spawnSync("git", ["config", "--type=bool", "--get", "core.sparseCheckout"], { encoding: "utf8", stdio: "pipe" });
20045
- if ((sparse.stdout ?? "").trim() === "true") {
20046
- return {
20047
- kind: "unknown",
20048
- reason: "this is a sparse checkout, so its working tree may not hold every tracked file",
20049
- remedy: "Run the push from a full (non-sparse) checkout"
20050
- };
20051
- }
20052
- const prefixOut = spawnSync("git", ["rev-parse", "--show-prefix"], {
20053
- encoding: "utf8",
20054
- stdio: "pipe"
20055
- });
20056
- if ((prefixOut.status ?? 1) !== 0) {
20057
- return {
20058
- kind: "unknown",
20059
- reason: "the repository root could not be resolved",
20060
- remedy: "Check that git runs correctly in this directory"
20061
- };
20062
- }
20063
- const prefix = (prefixOut.stdout ?? "").trim();
20064
- const r = spawnSync("git", ["log", "HEAD", "--format=", "--name-only", "--", "migrations/datatable"], { encoding: "utf8", stdio: "pipe", maxBuffer: 64 * 1024 * 1024 });
20065
- if ((r.status ?? 1) !== 0) {
20066
- debug(`Could not read git history for migrations: ${r.stderr ?? ""}`);
20067
- return {
20068
- kind: "unknown",
20069
- reason: "its history could not be read",
20070
- remedy: "Check that git runs correctly in this directory"
20071
- };
20072
- }
20073
- const paths = new Set;
20074
- for (const line of (r.stdout ?? "").split(`
20075
- `)) {
20076
- const p = line.trim();
20077
- if (p.length === 0)
20078
- continue;
20079
- if (prefix.length > 0) {
20080
- if (!p.startsWith(prefix))
20081
- continue;
20082
- paths.add(p.slice(prefix.length));
20083
- } else {
20084
- paths.add(p);
20085
- }
20086
- }
20087
- return { kind: "known", paths };
20088
- }
20089
- function isGitRepository() {
20090
- try {
20091
- execSync("git rev-parse --git-dir", {
20092
- encoding: "utf8",
20093
- stdio: "pipe"
20094
- });
20095
- return true;
20096
- } catch (error) {
20097
- debug(`Failed to check Git repository: ${error}`);
20098
- return false;
20099
- }
20100
- }
20101
- function isForkWorkspace(workspaceId, parentWorkspaceId) {
20102
- return !!parentWorkspaceId || workspaceId.startsWith(FORK_WORKSPACE_PREFIX);
20103
- }
20104
- function forkBranchName(workspaceId, originalBranch, devWorkspaceLabel) {
20105
- if (devWorkspaceLabel) {
20106
- return devWorkspaceLabel;
20107
- }
20108
- const branchPrefix = `${WM_FORK_PREFIX}/${originalBranch}/`;
20109
- return workspaceId.startsWith(FORK_WORKSPACE_PREFIX) ? workspaceId.replace(FORK_WORKSPACE_PREFIX, branchPrefix) : `${branchPrefix}${workspaceId}`;
20110
- }
20111
- function computeGitSyncDeployBranch(params) {
20112
- const {
20113
- workspaceId,
20114
- parentWorkspaceId,
20115
- devWorkspaceLabel,
20116
- items,
20117
- useIndividualBranch,
20118
- groupByFolder,
20119
- clonedBranchName
20120
- } = params;
20121
- const isDevWorkspace = !!devWorkspaceLabel;
20122
- if (isForkWorkspace(workspaceId, parentWorkspaceId) && !(isDevWorkspace && useIndividualBranch)) {
20123
- return forkBranchName(workspaceId, clonedBranchName, devWorkspaceLabel);
20124
- }
20125
- const fallback = isDevWorkspace ? forkBranchName(workspaceId, clonedBranchName, devWorkspaceLabel) : null;
20126
- if (items.length === 0)
20127
- return fallback;
20128
- const first = items[0];
20129
- if (!useIndividualBranch || first.path_type === "user" || first.path_type === "group") {
20130
- return fallback;
20131
- }
20132
- const ref = first.path || first.parent_path;
20133
- if (!ref)
20134
- return fallback;
20135
- return groupByFolder ? `wm_deploy/${workspaceId}/${ref.split("/").slice(0, 2).join("__")}` : `wm_deploy/${workspaceId}/${first.path_type}/${ref.replaceAll("/", "__")}`;
20136
- }
20137
- function composeGitSyncCommitHeader(items) {
20138
- const typeCounts = new Map;
20139
- for (const item of items) {
20140
- typeCounts.set(item.path_type, (typeCounts.get(item.path_type) ?? 0) + 1);
20141
- }
20142
- const sorted = Array.from(typeCounts.entries()).sort((a, b) => b[1] - a[1]);
20143
- const parts = [];
20144
- let othersCount = 0;
20145
- for (let i = 0;i < sorted.length; i++) {
20146
- const [pathType, count] = sorted[i];
20147
- if (i < 3) {
20148
- const label = count > 1 ? `${pathType}s` : pathType;
20149
- if (i === 2 && sorted.length === 3) {
20150
- parts.push(`and ${count} ${label}`);
20151
- } else {
20152
- parts.push(`${count} ${label}`);
20153
- }
20154
- } else {
20155
- othersCount += count;
20156
- }
20157
- }
20158
- let header = `[WM]: Deployed ${parts.join(", ")}`;
20159
- if (othersCount > 0) {
20160
- header += ` and ${othersCount} other object${othersCount > 1 ? "s" : ""}`;
20161
- }
20162
- return header;
20163
- }
20164
- function gitSyncCommitMessage(items) {
20165
- const descs = items.map((i) => i.commit_msg);
20166
- const [h, d] = descs.length === 1 ? [descs[0], ""] : [composeGitSyncCommitHeader(items), descs.join(`
20167
- `)];
20168
- return {
20169
- header: h === undefined || h === "" ? "no commit msg" : h,
20170
- description: d ?? ""
20171
- };
20172
- }
20173
- function gitSyncIncludePattern(pathType, path) {
20174
- switch (pathType) {
20175
- case "flow":
20176
- return `${path}.flow/*,${path}__flow/*`;
20177
- case "app":
20178
- return `${path}.app/*,${path}__app/*`;
20179
- case "raw_app":
20180
- return `${path}.raw_app/**,${path}__raw_app/**`;
20181
- case "folder":
20182
- return `${path}/folder.meta.*`;
20183
- case "resourcetype":
20184
- return `${path}.resource-type.*`;
20185
- case "resource":
20186
- return `${path}.resource.*`;
20187
- case "variable":
20188
- return `${path}.variable.*`;
20189
- case "schedule":
20190
- return `${path}.schedule.*`;
20191
- case "user":
20192
- return `${path}.user.*`;
20193
- case "group":
20194
- return `${path}.group.*`;
20195
- case "httptrigger":
20196
- return `${path}.http_trigger.*`;
20197
- case "websockettrigger":
20198
- return `${path}.websocket_trigger.*`;
20199
- case "kafkatrigger":
20200
- return `${path}.kafka_trigger.*`;
20201
- case "natstrigger":
20202
- return `${path}.nats_trigger.*`;
20203
- case "postgrestrigger":
20204
- return `${path}.postgres_trigger.*`;
20205
- case "mqtttrigger":
20206
- return `${path}.mqtt_trigger.*`;
20207
- case "amqptrigger":
20208
- return `${path}.amqp_trigger.*`;
20209
- case "sqstrigger":
20210
- return `${path}.sqs_trigger.*`;
20211
- case "gcptrigger":
20212
- return `${path}.gcp_trigger.*`;
20213
- case "azuretrigger":
20214
- return `${path}.azure_trigger.*`;
20215
- case "emailtrigger":
20216
- return `${path}.email_trigger.*`;
20217
- case "datatable_migration":
20218
- return `${path}.up.sql,${path}.down.sql`;
20219
- default:
20220
- return `${path}.*,${path}__mod/**`;
20221
- }
20222
- }
20223
- function deriveGitSyncDeployIncludes(items, useIndividualBranch) {
20224
- const extraIncludes = [];
20225
- for (const { path_type, path, parent_path } of items) {
20226
- if (path) {
20227
- extraIncludes.push(...gitSyncIncludePattern(path_type, path).split(","));
20228
- }
20229
- if (parent_path) {
20230
- extraIncludes.push(...gitSyncIncludePattern(path_type, parent_path).split(","));
20231
- }
20232
- }
20233
- const forcedIncludes = {};
20234
- if (!useIndividualBranch) {
20235
- const has = (pred) => items.some((i) => pred(i.path_type));
20236
- if (has((t) => t === "schedule"))
20237
- forcedIncludes.includeSchedules = true;
20238
- if (has((t) => t === "group"))
20239
- forcedIncludes.includeGroups = true;
20240
- if (has((t) => t === "user"))
20241
- forcedIncludes.includeUsers = true;
20242
- if (has((t) => t.includes("trigger")))
20243
- forcedIncludes.includeTriggers = true;
20244
- if (has((t) => t === "settings"))
20245
- forcedIncludes.includeSettings = true;
20246
- if (has((t) => t === "key"))
20247
- forcedIncludes.includeKey = true;
20248
- }
20249
- return { extraIncludes, forcedIncludes };
20250
- }
20251
- function git(args, opts) {
20252
- const r = spawnSync("git", args, { encoding: "utf8", stdio: "pipe" });
20253
- const status = r.status ?? 1;
20254
- if (r.error) {
20255
- if (opts?.allowFail)
20256
- return { status, stdout: "", stderr: String(r.error) };
20257
- throw r.error;
20258
- }
20259
- if (status !== 0 && !opts?.allowFail) {
20260
- throw new Error(`git ${args.join(" ")} failed (exit ${status}): ${r.stderr ?? ""}`);
20261
- }
20262
- return { status, stdout: r.stdout ?? "", stderr: r.stderr ?? "" };
20263
- }
20264
- function checkoutGitSyncDeployBranch(branch) {
20265
- const existing = git(["checkout", branch], { allowFail: true });
20266
- if (existing.status === 0) {
20267
- info(`Switched to existing branch ${branch}`);
20268
- return;
20269
- }
20270
- git(["checkout", "-b", branch]);
20271
- git(["config", "--add", "--bool", "push.autoSetupRemote", "true"]);
20272
- info(`Created and switched to branch ${branch}`);
20273
- }
20274
- function gitSyncDeployPush(params) {
20275
- const { items, authorName, authorEmail, onlyCreateBranch } = params;
20276
- const committerName = params.committerName ?? authorName;
20277
- const committerEmail = params.committerEmail ?? authorEmail;
20278
- git(["config", "user.email", committerEmail]);
20279
- git(["config", "user.name", committerName]);
20280
- if (onlyCreateBranch) {
20281
- git(["push", "--porcelain"]);
20282
- return { pushed: true };
20283
- }
20284
- for (const { path, parent_path } of items) {
20285
- if (path) {
20286
- git(["add", "wmill-lock.yaml", `${path}**`], { allowFail: true });
20287
- }
20288
- if (parent_path) {
20289
- git(["add", "wmill-lock.yaml", `${parent_path}**`], { allowFail: true });
20290
- }
20291
- }
20292
- const staged = git(["diff", "--cached", "--quiet"], { allowFail: true });
20293
- if (staged.status === 0) {
20294
- info("No changes detected, nothing to commit.");
20295
- return { pushed: false };
20296
- }
20297
- const { header, description } = gitSyncCommitMessage(items);
20298
- git([
20299
- "commit",
20300
- "--author",
20301
- `${authorName} <${authorEmail}>`,
20302
- "-m",
20303
- header,
20304
- "-m",
20305
- description
20306
- ]);
20307
- const push = git(["push", "--porcelain"], { allowFail: true });
20308
- if (push.status !== 0) {
20309
- info(`Push failed, rebasing and retrying: ${push.stderr}`);
20310
- git(["pull", "--rebase"]);
20311
- git(["push", "--porcelain"]);
20312
- }
20313
- return { pushed: true };
20314
- }
20315
- var FORK_WORKSPACE_PREFIX;
20316
- var init_git = __esm(() => {
20317
- init_log();
20318
- FORK_WORKSPACE_PREFIX = `${WM_FORK_PREFIX}-`;
20319
- });
20005
+ var WM_FORK_PREFIX = "wm-fork", VERSION = "1.813.0";
20320
20006
 
20321
20007
  // src/utils/resource_folders.ts
20322
20008
  import { existsSync } from "node:fs";
@@ -20683,6 +20369,575 @@ var init_resource_folders = __esm(async () => {
20683
20369
  DBT_ENV_VAR_CALL = /\{\{\s*env_var\(\s*['"]([^'"]+)['"]\s*(?:,\s*['"]([^'"]*)['"]\s*)?\)\s*\}\}/g;
20684
20370
  });
20685
20371
 
20372
+ // src/utils/script_common.ts
20373
+ function workspaceDependenciesPathToLanguageAndFilename(path) {
20374
+ const relativePath = path.replace("dependencies/", "");
20375
+ for (const { filename, language } of workspaceDependenciesLanguages) {
20376
+ if (relativePath.endsWith(filename)) {
20377
+ return {
20378
+ name: relativePath === filename ? undefined : relativePath.replace("." + filename, ""),
20379
+ language
20380
+ };
20381
+ }
20382
+ }
20383
+ }
20384
+ function extractWorkspaceDepsAnnotation(scriptContent, language) {
20385
+ const config = LANG_ANNOTATION_CONFIG[language];
20386
+ if (!config)
20387
+ return null;
20388
+ const { comment, keyword, validityRe } = config;
20389
+ const extraMarkerUnderscore = `extra_${keyword}:`;
20390
+ const extraMarkerHyphen = `extra-${keyword}:`;
20391
+ const manualMarker = `${keyword}:`;
20392
+ const stripComment = (l) => {
20393
+ if (!l.startsWith(comment))
20394
+ return null;
20395
+ return l.substring(comment.length).trimStart();
20396
+ };
20397
+ const isExtra = (l) => {
20398
+ const s = stripComment(l);
20399
+ return s !== null && (s.startsWith(extraMarkerUnderscore) || s.startsWith(extraMarkerHyphen));
20400
+ };
20401
+ const isManual = (l) => {
20402
+ const s = stripComment(l);
20403
+ return s !== null && s.startsWith(manualMarker);
20404
+ };
20405
+ const lines = scriptContent.split(`
20406
+ `);
20407
+ let pos = -1;
20408
+ for (let i = 0;i < lines.length; i++) {
20409
+ if (isExtra(lines[i]) || isManual(lines[i])) {
20410
+ pos = i;
20411
+ break;
20412
+ }
20413
+ }
20414
+ if (pos === -1)
20415
+ return null;
20416
+ const annotationLine = lines[pos];
20417
+ const mode = isExtra(annotationLine) ? "extra" : "manual";
20418
+ const marker = mode === "extra" ? annotationLine.includes(extraMarkerUnderscore) ? extraMarkerUnderscore : extraMarkerHyphen : manualMarker;
20419
+ const unparsed = annotationLine.replaceAll(marker, "").replaceAll(comment, "");
20420
+ const external = unparsed.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
20421
+ const inlineParts = [];
20422
+ for (let i = pos + 1;i < lines.length; i++) {
20423
+ const l = lines[i];
20424
+ if (validityRe) {
20425
+ const match = validityRe.exec(l);
20426
+ if (match && match[1]) {
20427
+ inlineParts.push(match[1]);
20428
+ } else {
20429
+ break;
20430
+ }
20431
+ } else {
20432
+ if (!l.startsWith(comment)) {
20433
+ break;
20434
+ }
20435
+ inlineParts.push(l.substring(comment.length));
20436
+ }
20437
+ }
20438
+ const inlineStr = inlineParts.join(`
20439
+ `);
20440
+ const inline = inlineStr.trim().length > 0 ? inlineStr : null;
20441
+ return { mode, external, inline };
20442
+ }
20443
+ function hasLockAffectingAnnotation(scriptContent, language) {
20444
+ const comment = LANG_COMMENT_LIT[language];
20445
+ const names = LANG_ANNOTATIONS[language];
20446
+ if (!comment || !names)
20447
+ return false;
20448
+ for (const line of scriptContent.split(`
20449
+ `)) {
20450
+ const trimmed = line.trim();
20451
+ if (trimmed === "")
20452
+ continue;
20453
+ if (!trimmed.startsWith(comment))
20454
+ break;
20455
+ if (language === "python3" && /^#\s?py:/.test(line))
20456
+ return true;
20457
+ const body = trimmed.slice(comment.length).trim();
20458
+ const key = body.split("=")[0].trim();
20459
+ if (names.includes(key))
20460
+ return true;
20461
+ }
20462
+ return false;
20463
+ }
20464
+ function sharedLockPathFor(depFilePath) {
20465
+ const name = depFilePath.replaceAll("\\", "/").split("/").pop();
20466
+ return `${SHARED_LOCK_DIR}/${name}.lock`;
20467
+ }
20468
+ function depFileOfSharedLock(p) {
20469
+ const normalized = p.replaceAll("\\", "/");
20470
+ if (!normalized.startsWith(SHARED_LOCK_DIR + "/"))
20471
+ return;
20472
+ const name = normalized.slice(SHARED_LOCK_DIR.length + 1);
20473
+ if (name.includes("/") || !name.endsWith(".lock"))
20474
+ return;
20475
+ const depFile = "dependencies/" + name.slice(0, -".lock".length);
20476
+ const info = workspaceDependenciesPathToLanguageAndFilename(depFile);
20477
+ return info && languageNeedsLock(info.language) ? depFile : undefined;
20478
+ }
20479
+ function isSharedLockPath(p) {
20480
+ return depFileOfSharedLock(p) !== undefined;
20481
+ }
20482
+ function languageNeedsLock(language) {
20483
+ return workspaceDependenciesLanguages.some((l) => l.language === language) && language !== "powershell" || language === "deno" || language === "rust" || language === "ansible";
20484
+ }
20485
+ function inferContentTypeFromFilePath(contentPath, defaultTs) {
20486
+ if (contentPath.endsWith(".py")) {
20487
+ return "python3";
20488
+ } else if (contentPath.endsWith("fetch.ts")) {
20489
+ return "nativets";
20490
+ } else if (contentPath.endsWith("bun.ts")) {
20491
+ return "bun";
20492
+ } else if (contentPath.endsWith("deno.ts")) {
20493
+ return "deno";
20494
+ } else if (contentPath.endsWith(".ts")) {
20495
+ return defaultTs ?? "bun";
20496
+ } else if (contentPath.endsWith(".go")) {
20497
+ return "go";
20498
+ } else if (contentPath.endsWith(".my.sql")) {
20499
+ return "mysql";
20500
+ } else if (contentPath.endsWith(".bq.sql")) {
20501
+ return "bigquery";
20502
+ } else if (contentPath.endsWith(".odb.sql")) {
20503
+ return "oracledb";
20504
+ } else if (contentPath.endsWith(".duckdb.sql")) {
20505
+ return "duckdb";
20506
+ } else if (contentPath.endsWith(".sf.sql")) {
20507
+ return "snowflake";
20508
+ } else if (contentPath.endsWith(".ms.sql")) {
20509
+ return "mssql";
20510
+ } else if (contentPath.endsWith(".pg.sql")) {
20511
+ return "postgresql";
20512
+ } else if (contentPath.endsWith(".gql")) {
20513
+ return "graphql";
20514
+ } else if (contentPath.endsWith(".sh")) {
20515
+ return "bash";
20516
+ } else if (contentPath.endsWith(".ps1")) {
20517
+ return "powershell";
20518
+ } else if (contentPath.endsWith(".php")) {
20519
+ return "php";
20520
+ } else if (contentPath.endsWith(".rs")) {
20521
+ return "rust";
20522
+ } else if (contentPath.endsWith(".cs")) {
20523
+ return "csharp";
20524
+ } else if (contentPath.endsWith(".playbook.yml")) {
20525
+ return "ansible";
20526
+ } else if (contentPath.endsWith(".nu")) {
20527
+ return "nu";
20528
+ } else if (contentPath.endsWith(".java")) {
20529
+ return "java";
20530
+ } else if (contentPath.endsWith(".rb")) {
20531
+ return "ruby";
20532
+ } else if (isDbtDescriptorPath(contentPath)) {
20533
+ return "dbt";
20534
+ } else if (contentPath.endsWith(".r")) {
20535
+ return "rlang";
20536
+ } else {
20537
+ const ext = contentPath.substring(contentPath.lastIndexOf("."));
20538
+ let hint = "";
20539
+ if (ext === ".sql") {
20540
+ hint = `
20541
+ Bare .sql is ambiguous — use a dialect extension: .pg.sql (postgresql), .my.sql (mysql), .bq.sql (bigquery), .sf.sql (snowflake), .ms.sql (mssql), .odb.sql (oracledb), .duckdb.sql (duckdb)`;
20542
+ }
20543
+ throw new Error(`Cannot infer script language from extension '${ext}' (file ${contentPath}).` + hint + "\nSupported extensions: .ts (bun/deno), .py, .go, .sh, .ps1, .php, .rs, .cs, .nu, .java, .rb, .r, .gql, .playbook.yml, .pg.sql, .my.sql, .bq.sql, .sf.sql, .ms.sql, .odb.sql, .duckdb.sql, and a dbt project folder `<name>__dbt/`");
20544
+ }
20545
+ }
20546
+ var workspaceDependenciesLanguages, LANG_ANNOTATION_CONFIG, LANG_COMMENT_LIT, LANG_ANNOTATIONS, SHARED_LOCK_DIR = "locks";
20547
+ var init_script_common = __esm(async () => {
20548
+ await init_resource_folders();
20549
+ workspaceDependenciesLanguages = [
20550
+ { language: "bun", filename: "package.json" },
20551
+ { language: "python3", filename: "requirements.in" },
20552
+ { language: "php", filename: "composer.json" },
20553
+ { language: "go", filename: "go.mod" },
20554
+ { language: "powershell", filename: "modules.json" }
20555
+ ];
20556
+ LANG_ANNOTATION_CONFIG = {
20557
+ python3: { comment: "#", keyword: "requirements", validityRe: /^#\s?(\S+)\s*$/ },
20558
+ bun: { comment: "//", keyword: "package_json" },
20559
+ nativets: { comment: "//", keyword: "package_json" },
20560
+ go: { comment: "//", keyword: "go_mod" },
20561
+ php: { comment: "//", keyword: "composer_json" },
20562
+ powershell: { comment: "#", keyword: "modules_json" }
20563
+ };
20564
+ LANG_COMMENT_LIT = {
20565
+ python3: "#",
20566
+ ansible: "#",
20567
+ powershell: "#",
20568
+ bun: "//",
20569
+ nativets: "//",
20570
+ deno: "//",
20571
+ go: "//",
20572
+ php: "//",
20573
+ rust: "//!"
20574
+ };
20575
+ LANG_ANNOTATIONS = {
20576
+ python3: [
20577
+ "no_cache",
20578
+ "no_postinstall",
20579
+ "py_select_latest",
20580
+ "skip_result_postprocessing",
20581
+ "py310",
20582
+ "py311",
20583
+ "py312",
20584
+ "py313",
20585
+ "sandbox"
20586
+ ],
20587
+ bun: ["npm", "nodejs", "native", "nobundling", "sandbox"],
20588
+ nativets: ["npm", "nodejs", "native", "nobundling", "sandbox"],
20589
+ deno: ["npm", "nodejs", "native", "nobundling", "sandbox"],
20590
+ go: ["go1_22_compat"]
20591
+ };
20592
+ });
20593
+
20594
+ // src/utils/git.ts
20595
+ import { execSync, spawnSync } from "node:child_process";
20596
+ function getCurrentGitBranch() {
20597
+ try {
20598
+ const result = execSync("git rev-parse --abbrev-ref HEAD", {
20599
+ encoding: "utf8",
20600
+ stdio: "pipe"
20601
+ });
20602
+ const branch = result.trim();
20603
+ return branch || null;
20604
+ } catch (error) {
20605
+ debug(`Failed to get Git branch: ${error}`);
20606
+ return null;
20607
+ }
20608
+ }
20609
+ function gitBranchExists(branchName) {
20610
+ const r = spawnSync("git", ["show-ref", "--verify", "--quiet", `refs/heads/${branchName}`], { stdio: "pipe" });
20611
+ return r.status === 0;
20612
+ }
20613
+ function renameCurrentGitBranch(newName) {
20614
+ const r = spawnSync("git", ["branch", "-m", newName], {
20615
+ encoding: "utf8",
20616
+ stdio: "pipe"
20617
+ });
20618
+ if ((r.status ?? 1) !== 0) {
20619
+ throw new Error(`git branch -m ${newName} failed (exit ${r.status}): ${r.stderr ?? ""}`);
20620
+ }
20621
+ }
20622
+ function getOriginalBranchForWorkspaceForks(branchName) {
20623
+ if (!branchName || !branchName.startsWith(WM_FORK_PREFIX)) {
20624
+ return null;
20625
+ }
20626
+ const start = branchName.indexOf("/") + 1;
20627
+ const end = branchName.lastIndexOf("/");
20628
+ if (start < 0 || end < 0 || end - start <= 0) {
20629
+ return null;
20630
+ }
20631
+ return branchName.slice(start, end);
20632
+ }
20633
+ function getWorkspaceIdForWorkspaceForkFromBranchName(branchName) {
20634
+ if (!branchName.startsWith(WM_FORK_PREFIX)) {
20635
+ return null;
20636
+ }
20637
+ const start = branchName.lastIndexOf("/") + 1;
20638
+ if (start < 0) {
20639
+ return null;
20640
+ }
20641
+ return `${WM_FORK_PREFIX}-${branchName.slice(start)}`;
20642
+ }
20643
+ function gitRecordedDatatableMigrationPaths() {
20644
+ if (!isGitRepository()) {
20645
+ return {
20646
+ kind: "unknown",
20647
+ reason: "this directory is not a git repository",
20648
+ remedy: "Run the push from a git checkout of the synced repository"
20649
+ };
20650
+ }
20651
+ const shallow = spawnSync("git", ["rev-parse", "--is-shallow-repository"], {
20652
+ encoding: "utf8",
20653
+ stdio: "pipe"
20654
+ });
20655
+ if ((shallow.stdout ?? "").trim() === "true") {
20656
+ return {
20657
+ kind: "unknown",
20658
+ reason: "this is a shallow clone, so its history is truncated",
20659
+ remedy: "Fetch the full history (for actions/checkout, fetch-depth: 0)"
20660
+ };
20661
+ }
20662
+ const sparse = spawnSync("git", ["config", "--type=bool", "--get", "core.sparseCheckout"], { encoding: "utf8", stdio: "pipe" });
20663
+ if ((sparse.stdout ?? "").trim() === "true") {
20664
+ return {
20665
+ kind: "unknown",
20666
+ reason: "this is a sparse checkout, so its working tree may not hold every tracked file",
20667
+ remedy: "Run the push from a full (non-sparse) checkout"
20668
+ };
20669
+ }
20670
+ const prefixOut = spawnSync("git", ["rev-parse", "--show-prefix"], {
20671
+ encoding: "utf8",
20672
+ stdio: "pipe"
20673
+ });
20674
+ if ((prefixOut.status ?? 1) !== 0) {
20675
+ return {
20676
+ kind: "unknown",
20677
+ reason: "the repository root could not be resolved",
20678
+ remedy: "Check that git runs correctly in this directory"
20679
+ };
20680
+ }
20681
+ const prefix = (prefixOut.stdout ?? "").trim();
20682
+ const r = spawnSync("git", ["log", "HEAD", "--format=", "--name-only", "--", "migrations/datatable"], { encoding: "utf8", stdio: "pipe", maxBuffer: 64 * 1024 * 1024 });
20683
+ if ((r.status ?? 1) !== 0) {
20684
+ debug(`Could not read git history for migrations: ${r.stderr ?? ""}`);
20685
+ return {
20686
+ kind: "unknown",
20687
+ reason: "its history could not be read",
20688
+ remedy: "Check that git runs correctly in this directory"
20689
+ };
20690
+ }
20691
+ const paths = new Set;
20692
+ for (const line of (r.stdout ?? "").split(`
20693
+ `)) {
20694
+ const p = line.trim();
20695
+ if (p.length === 0)
20696
+ continue;
20697
+ if (prefix.length > 0) {
20698
+ if (!p.startsWith(prefix))
20699
+ continue;
20700
+ paths.add(p.slice(prefix.length));
20701
+ } else {
20702
+ paths.add(p);
20703
+ }
20704
+ }
20705
+ return { kind: "known", paths };
20706
+ }
20707
+ function isGitRepository() {
20708
+ try {
20709
+ execSync("git rev-parse --git-dir", {
20710
+ encoding: "utf8",
20711
+ stdio: "pipe"
20712
+ });
20713
+ return true;
20714
+ } catch (error) {
20715
+ debug(`Failed to check Git repository: ${error}`);
20716
+ return false;
20717
+ }
20718
+ }
20719
+ function isForkWorkspace(workspaceId, parentWorkspaceId) {
20720
+ return !!parentWorkspaceId || workspaceId.startsWith(FORK_WORKSPACE_PREFIX);
20721
+ }
20722
+ function forkBranchName(workspaceId, originalBranch, devWorkspaceLabel) {
20723
+ if (devWorkspaceLabel) {
20724
+ return devWorkspaceLabel;
20725
+ }
20726
+ const branchPrefix = `${WM_FORK_PREFIX}/${originalBranch}/`;
20727
+ return workspaceId.startsWith(FORK_WORKSPACE_PREFIX) ? workspaceId.replace(FORK_WORKSPACE_PREFIX, branchPrefix) : `${branchPrefix}${workspaceId}`;
20728
+ }
20729
+ function computeGitSyncDeployBranch(params) {
20730
+ const {
20731
+ workspaceId,
20732
+ parentWorkspaceId,
20733
+ devWorkspaceLabel,
20734
+ items,
20735
+ useIndividualBranch,
20736
+ groupByFolder,
20737
+ clonedBranchName
20738
+ } = params;
20739
+ const isDevWorkspace = !!devWorkspaceLabel;
20740
+ if (isForkWorkspace(workspaceId, parentWorkspaceId) && !(isDevWorkspace && useIndividualBranch)) {
20741
+ return forkBranchName(workspaceId, clonedBranchName, devWorkspaceLabel);
20742
+ }
20743
+ const fallback = isDevWorkspace ? forkBranchName(workspaceId, clonedBranchName, devWorkspaceLabel) : null;
20744
+ if (items.length === 0)
20745
+ return fallback;
20746
+ const first = items[0];
20747
+ if (!useIndividualBranch || first.path_type === "user" || first.path_type === "group") {
20748
+ return fallback;
20749
+ }
20750
+ const ref = first.path || first.parent_path;
20751
+ if (!ref)
20752
+ return fallback;
20753
+ return groupByFolder ? `wm_deploy/${workspaceId}/${ref.split("/").slice(0, 2).join("__")}` : `wm_deploy/${workspaceId}/${first.path_type}/${ref.replaceAll("/", "__")}`;
20754
+ }
20755
+ function composeGitSyncCommitHeader(items) {
20756
+ const typeCounts = new Map;
20757
+ for (const item of items) {
20758
+ typeCounts.set(item.path_type, (typeCounts.get(item.path_type) ?? 0) + 1);
20759
+ }
20760
+ const sorted = Array.from(typeCounts.entries()).sort((a, b) => b[1] - a[1]);
20761
+ const parts = [];
20762
+ let othersCount = 0;
20763
+ for (let i = 0;i < sorted.length; i++) {
20764
+ const [pathType, count] = sorted[i];
20765
+ if (i < 3) {
20766
+ const label = count > 1 ? `${pathType}s` : pathType;
20767
+ if (i === 2 && sorted.length === 3) {
20768
+ parts.push(`and ${count} ${label}`);
20769
+ } else {
20770
+ parts.push(`${count} ${label}`);
20771
+ }
20772
+ } else {
20773
+ othersCount += count;
20774
+ }
20775
+ }
20776
+ let header = `[WM]: Deployed ${parts.join(", ")}`;
20777
+ if (othersCount > 0) {
20778
+ header += ` and ${othersCount} other object${othersCount > 1 ? "s" : ""}`;
20779
+ }
20780
+ return header;
20781
+ }
20782
+ function gitSyncCommitMessage(items) {
20783
+ const descs = items.map((i) => i.commit_msg);
20784
+ const [h, d] = descs.length === 1 ? [descs[0], ""] : [composeGitSyncCommitHeader(items), descs.join(`
20785
+ `)];
20786
+ return {
20787
+ header: h === undefined || h === "" ? "no commit msg" : h,
20788
+ description: d ?? ""
20789
+ };
20790
+ }
20791
+ function gitSyncIncludePattern(pathType, path) {
20792
+ switch (pathType) {
20793
+ case "flow":
20794
+ return `${path}.flow/*,${path}__flow/*`;
20795
+ case "app":
20796
+ return `${path}.app/*,${path}__app/*`;
20797
+ case "raw_app":
20798
+ return `${path}.raw_app/**,${path}__raw_app/**`;
20799
+ case "folder":
20800
+ return `${path}/folder.meta.*`;
20801
+ case "resourcetype":
20802
+ return `${path}.resource-type.*`;
20803
+ case "resource":
20804
+ return `${path}.resource.*`;
20805
+ case "variable":
20806
+ return `${path}.variable.*`;
20807
+ case "schedule":
20808
+ return `${path}.schedule.*`;
20809
+ case "user":
20810
+ return `${path}.user.*`;
20811
+ case "group":
20812
+ return `${path}.group.*`;
20813
+ case "httptrigger":
20814
+ return `${path}.http_trigger.*`;
20815
+ case "websockettrigger":
20816
+ return `${path}.websocket_trigger.*`;
20817
+ case "kafkatrigger":
20818
+ return `${path}.kafka_trigger.*`;
20819
+ case "natstrigger":
20820
+ return `${path}.nats_trigger.*`;
20821
+ case "postgrestrigger":
20822
+ return `${path}.postgres_trigger.*`;
20823
+ case "mqtttrigger":
20824
+ return `${path}.mqtt_trigger.*`;
20825
+ case "amqptrigger":
20826
+ return `${path}.amqp_trigger.*`;
20827
+ case "sqstrigger":
20828
+ return `${path}.sqs_trigger.*`;
20829
+ case "gcptrigger":
20830
+ return `${path}.gcp_trigger.*`;
20831
+ case "azuretrigger":
20832
+ return `${path}.azure_trigger.*`;
20833
+ case "emailtrigger":
20834
+ return `${path}.email_trigger.*`;
20835
+ case "datatable_migration":
20836
+ return `${path}.up.sql,${path}.down.sql`;
20837
+ default:
20838
+ return `${path}.*,${path}__mod/**`;
20839
+ }
20840
+ }
20841
+ function deriveGitSyncDeployIncludes(items, useIndividualBranch) {
20842
+ const extraIncludes = [];
20843
+ for (const { path_type, path, parent_path } of items) {
20844
+ if (path) {
20845
+ extraIncludes.push(...gitSyncIncludePattern(path_type, path).split(","));
20846
+ }
20847
+ if (parent_path) {
20848
+ extraIncludes.push(...gitSyncIncludePattern(path_type, parent_path).split(","));
20849
+ }
20850
+ }
20851
+ const forcedIncludes = {};
20852
+ if (!useIndividualBranch) {
20853
+ const has = (pred) => items.some((i) => pred(i.path_type));
20854
+ if (has((t) => t === "schedule"))
20855
+ forcedIncludes.includeSchedules = true;
20856
+ if (has((t) => t === "group"))
20857
+ forcedIncludes.includeGroups = true;
20858
+ if (has((t) => t === "user"))
20859
+ forcedIncludes.includeUsers = true;
20860
+ if (has((t) => t.includes("trigger")))
20861
+ forcedIncludes.includeTriggers = true;
20862
+ if (has((t) => t === "settings"))
20863
+ forcedIncludes.includeSettings = true;
20864
+ if (has((t) => t === "key"))
20865
+ forcedIncludes.includeKey = true;
20866
+ }
20867
+ return { extraIncludes, forcedIncludes };
20868
+ }
20869
+ function git(args, opts) {
20870
+ const r = spawnSync("git", args, { encoding: "utf8", stdio: "pipe" });
20871
+ const status = r.status ?? 1;
20872
+ if (r.error) {
20873
+ if (opts?.allowFail)
20874
+ return { status, stdout: "", stderr: String(r.error) };
20875
+ throw r.error;
20876
+ }
20877
+ if (status !== 0 && !opts?.allowFail) {
20878
+ throw new Error(`git ${args.join(" ")} failed (exit ${status}): ${r.stderr ?? ""}`);
20879
+ }
20880
+ return { status, stdout: r.stdout ?? "", stderr: r.stderr ?? "" };
20881
+ }
20882
+ function checkoutGitSyncDeployBranch(branch) {
20883
+ const existing = git(["checkout", branch], { allowFail: true });
20884
+ if (existing.status === 0) {
20885
+ info(`Switched to existing branch ${branch}`);
20886
+ return;
20887
+ }
20888
+ git(["checkout", "-b", branch]);
20889
+ git(["config", "--add", "--bool", "push.autoSetupRemote", "true"]);
20890
+ info(`Created and switched to branch ${branch}`);
20891
+ }
20892
+ function gitSyncDeployPush(params) {
20893
+ const { items, authorName, authorEmail, onlyCreateBranch } = params;
20894
+ const committerName = params.committerName ?? authorName;
20895
+ const committerEmail = params.committerEmail ?? authorEmail;
20896
+ git(["config", "user.email", committerEmail]);
20897
+ git(["config", "user.name", committerName]);
20898
+ if (onlyCreateBranch) {
20899
+ git(["push", "--porcelain"]);
20900
+ return { pushed: true };
20901
+ }
20902
+ for (const { path, parent_path } of items) {
20903
+ if (path) {
20904
+ git(["add", "wmill-lock.yaml", `${path}**`], { allowFail: true });
20905
+ }
20906
+ if (parent_path) {
20907
+ git(["add", "wmill-lock.yaml", `${parent_path}**`], { allowFail: true });
20908
+ }
20909
+ }
20910
+ git(["add", "-A", "--", SHARED_LOCK_DIR], { allowFail: true });
20911
+ const staged = git(["diff", "--cached", "--quiet"], { allowFail: true });
20912
+ if (staged.status === 0) {
20913
+ info("No changes detected, nothing to commit.");
20914
+ return { pushed: false };
20915
+ }
20916
+ const { header, description } = gitSyncCommitMessage(items);
20917
+ git([
20918
+ "commit",
20919
+ "--author",
20920
+ `${authorName} <${authorEmail}>`,
20921
+ "-m",
20922
+ header,
20923
+ "-m",
20924
+ description
20925
+ ]);
20926
+ const push = git(["push", "--porcelain"], { allowFail: true });
20927
+ if (push.status !== 0) {
20928
+ info(`Push failed, rebasing and retrying: ${push.stderr}`);
20929
+ git(["pull", "--rebase"]);
20930
+ git(["push", "--porcelain"]);
20931
+ }
20932
+ return { pushed: true };
20933
+ }
20934
+ var FORK_WORKSPACE_PREFIX;
20935
+ var init_git = __esm(async () => {
20936
+ init_log();
20937
+ await init_script_common();
20938
+ FORK_WORKSPACE_PREFIX = `${WM_FORK_PREFIX}-`;
20939
+ });
20940
+
20686
20941
  // src/core/conf.ts
20687
20942
  import { join as join6, dirname as dirname6, resolve as resolve5, relative as relative4 } from "node:path";
20688
20943
  import { existsSync as existsSync3 } from "node:fs";
@@ -21068,10 +21323,10 @@ function convertGitBranchesToWorkspaces(gitBranches) {
21068
21323
  var import_yaml3, showDiffs = false, SUPPORTED_SYNC_BEHAVIOR_VERSION = 1, GLOBAL_CONFIG_OPT, legacyConfigWarned = false, DEFAULT_SYNC_OPTIONS, RESERVED_WORKSPACE_KEYS;
21069
21324
  var init_conf = __esm(async () => {
21070
21325
  init_log();
21071
- init_git();
21072
21326
  await __promiseAll([
21073
21327
  init_yaml(),
21074
21328
  init_confirm(),
21329
+ init_git(),
21075
21330
  init_resource_folders()
21076
21331
  ]);
21077
21332
  import_yaml3 = __toESM(require_dist(), 1);
@@ -21465,10 +21720,10 @@ var init_fork = __esm(async () => {
21465
21720
  init_log();
21466
21721
  init_client();
21467
21722
  init_services_gen();
21468
- init_git();
21469
21723
  await __promiseAll([
21470
21724
  init_input(),
21471
21725
  init_workspace(),
21726
+ init_git(),
21472
21727
  init_context(),
21473
21728
  init_conf()
21474
21729
  ]);
@@ -23089,7 +23344,7 @@ async function getWorkspaceByName(workspaceName, configDirOverride) {
23089
23344
  return;
23090
23345
  }
23091
23346
  async function forkBranchAutoTargetNote() {
23092
- await Promise.resolve().then(() => init_git());
23347
+ await init_git();
23093
23348
  const branch = getCurrentGitBranch();
23094
23349
  if (!branch || !getOriginalBranchForWorkspaceForks(branch)) {
23095
23350
  return;
@@ -23306,7 +23561,7 @@ async function whoami2(_opts) {
23306
23561
  const whoamiInfo = await requireLogin(_opts);
23307
23562
  info(JSON.stringify(whoamiInfo, null, 2));
23308
23563
  const activeName = await getActiveWorkspaceName(_opts);
23309
- await Promise.resolve().then(() => init_git());
23564
+ await init_git();
23310
23565
  const branch = getCurrentGitBranch();
23311
23566
  const originalBranch = branch ? getOriginalBranchForWorkspaceForks(branch) : null;
23312
23567
  if (originalBranch) {
@@ -23404,7 +23659,7 @@ async function getActiveWorkspaceOrFallback(opts) {
23404
23659
  return activeWorkspace;
23405
23660
  }
23406
23661
  async function bind(opts, doBind) {
23407
- await Promise.resolve().then(() => init_git());
23662
+ await init_git();
23408
23663
  await init_conf();
23409
23664
  const { stringify: yamlStringify } = await Promise.resolve().then(() => __toESM(require_dist(), 1));
23410
23665
  const config = await readConfigFile();
@@ -24105,7 +24360,6 @@ var init_context = __esm(async () => {
24105
24360
  init_log();
24106
24361
  init_mod6();
24107
24362
  init_http_guards();
24108
- init_git();
24109
24363
  init_levenshtein_distance();
24110
24364
  await __promiseAll([
24111
24365
  init_select(),
@@ -24115,7 +24369,8 @@ var init_context = __esm(async () => {
24115
24369
  init_utils(),
24116
24370
  init_workspace(),
24117
24371
  init_branch_profiles(),
24118
- init_conf()
24372
+ init_conf(),
24373
+ init_git()
24119
24374
  ]);
24120
24375
  REMOTE_PATH_RE = /^[ufg](\/[^/]+){2,}$/;
24121
24376
  });
@@ -24378,6 +24633,14 @@ function capitalize(str) {
24378
24633
  function formatTimestamp(ts) {
24379
24634
  return new Date(ts).toISOString().replace("T", " ").substring(0, 19);
24380
24635
  }
24636
+ function apiErrorMessage(e) {
24637
+ if (!(e && typeof e === "object" && ("name" in e) && e.name === "ApiError")) {
24638
+ return;
24639
+ }
24640
+ const { body, statusText } = e;
24641
+ const bodyStr = typeof body === "object" && body !== null ? JSON.stringify(body) : String(body ?? "");
24642
+ return statusText + ": " + bodyStr.replace(/\s*[@(]\w+\.rs:\d+[:\d]*\)?/g, "");
24643
+ }
24381
24644
  function validateRequiredArgs(schema) {
24382
24645
  const required = schema?.required ?? [];
24383
24646
  if (required.length > 0) {
@@ -34562,228 +34825,6 @@ main <- function(x, name = "default") {
34562
34825
  };
34563
34826
  });
34564
34827
 
34565
- // src/utils/script_common.ts
34566
- function workspaceDependenciesPathToLanguageAndFilename(path) {
34567
- const relativePath = path.replace("dependencies/", "");
34568
- for (const { filename, language } of workspaceDependenciesLanguages) {
34569
- if (relativePath.endsWith(filename)) {
34570
- return {
34571
- name: relativePath === filename ? undefined : relativePath.replace("." + filename, ""),
34572
- language
34573
- };
34574
- }
34575
- }
34576
- }
34577
- function extractWorkspaceDepsAnnotation(scriptContent, language) {
34578
- const config = LANG_ANNOTATION_CONFIG[language];
34579
- if (!config)
34580
- return null;
34581
- const { comment, keyword, validityRe } = config;
34582
- const extraMarkerUnderscore = `extra_${keyword}:`;
34583
- const extraMarkerHyphen = `extra-${keyword}:`;
34584
- const manualMarker = `${keyword}:`;
34585
- const stripComment = (l) => {
34586
- if (!l.startsWith(comment))
34587
- return null;
34588
- return l.substring(comment.length).trimStart();
34589
- };
34590
- const isExtra = (l) => {
34591
- const s = stripComment(l);
34592
- return s !== null && (s.startsWith(extraMarkerUnderscore) || s.startsWith(extraMarkerHyphen));
34593
- };
34594
- const isManual = (l) => {
34595
- const s = stripComment(l);
34596
- return s !== null && s.startsWith(manualMarker);
34597
- };
34598
- const lines = scriptContent.split(`
34599
- `);
34600
- let pos = -1;
34601
- for (let i = 0;i < lines.length; i++) {
34602
- if (isExtra(lines[i]) || isManual(lines[i])) {
34603
- pos = i;
34604
- break;
34605
- }
34606
- }
34607
- if (pos === -1)
34608
- return null;
34609
- const annotationLine = lines[pos];
34610
- const mode = isExtra(annotationLine) ? "extra" : "manual";
34611
- const marker = mode === "extra" ? annotationLine.includes(extraMarkerUnderscore) ? extraMarkerUnderscore : extraMarkerHyphen : manualMarker;
34612
- const unparsed = annotationLine.replaceAll(marker, "").replaceAll(comment, "");
34613
- const external = unparsed.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
34614
- const inlineParts = [];
34615
- for (let i = pos + 1;i < lines.length; i++) {
34616
- const l = lines[i];
34617
- if (validityRe) {
34618
- const match = validityRe.exec(l);
34619
- if (match && match[1]) {
34620
- inlineParts.push(match[1]);
34621
- } else {
34622
- break;
34623
- }
34624
- } else {
34625
- if (!l.startsWith(comment)) {
34626
- break;
34627
- }
34628
- inlineParts.push(l.substring(comment.length));
34629
- }
34630
- }
34631
- const inlineStr = inlineParts.join(`
34632
- `);
34633
- const inline = inlineStr.trim().length > 0 ? inlineStr : null;
34634
- return { mode, external, inline };
34635
- }
34636
- function hasLockAffectingAnnotation(scriptContent, language) {
34637
- const comment = LANG_COMMENT_LIT[language];
34638
- const names = LANG_ANNOTATIONS[language];
34639
- if (!comment || !names)
34640
- return false;
34641
- for (const line of scriptContent.split(`
34642
- `)) {
34643
- const trimmed = line.trim();
34644
- if (trimmed === "")
34645
- continue;
34646
- if (!trimmed.startsWith(comment))
34647
- break;
34648
- if (language === "python3" && /^#\s?py:/.test(line))
34649
- return true;
34650
- const body = trimmed.slice(comment.length).trim();
34651
- const key = body.split("=")[0].trim();
34652
- if (names.includes(key))
34653
- return true;
34654
- }
34655
- return false;
34656
- }
34657
- function sharedLockPathFor(depFilePath) {
34658
- const name = depFilePath.replaceAll("\\", "/").split("/").pop();
34659
- return `${SHARED_LOCK_DIR}/${name}.lock`;
34660
- }
34661
- function depFileOfSharedLock(p) {
34662
- const normalized = p.replaceAll("\\", "/");
34663
- if (!normalized.startsWith(SHARED_LOCK_DIR + "/"))
34664
- return;
34665
- const name = normalized.slice(SHARED_LOCK_DIR.length + 1);
34666
- if (name.includes("/") || !name.endsWith(".lock"))
34667
- return;
34668
- const depFile = "dependencies/" + name.slice(0, -".lock".length);
34669
- const info = workspaceDependenciesPathToLanguageAndFilename(depFile);
34670
- return info && languageNeedsLock(info.language) ? depFile : undefined;
34671
- }
34672
- function isSharedLockPath(p) {
34673
- return depFileOfSharedLock(p) !== undefined;
34674
- }
34675
- function languageNeedsLock(language) {
34676
- return workspaceDependenciesLanguages.some((l) => l.language === language) && language !== "powershell" || language === "deno" || language === "rust" || language === "ansible";
34677
- }
34678
- function inferContentTypeFromFilePath(contentPath, defaultTs) {
34679
- if (contentPath.endsWith(".py")) {
34680
- return "python3";
34681
- } else if (contentPath.endsWith("fetch.ts")) {
34682
- return "nativets";
34683
- } else if (contentPath.endsWith("bun.ts")) {
34684
- return "bun";
34685
- } else if (contentPath.endsWith("deno.ts")) {
34686
- return "deno";
34687
- } else if (contentPath.endsWith(".ts")) {
34688
- return defaultTs ?? "bun";
34689
- } else if (contentPath.endsWith(".go")) {
34690
- return "go";
34691
- } else if (contentPath.endsWith(".my.sql")) {
34692
- return "mysql";
34693
- } else if (contentPath.endsWith(".bq.sql")) {
34694
- return "bigquery";
34695
- } else if (contentPath.endsWith(".odb.sql")) {
34696
- return "oracledb";
34697
- } else if (contentPath.endsWith(".duckdb.sql")) {
34698
- return "duckdb";
34699
- } else if (contentPath.endsWith(".sf.sql")) {
34700
- return "snowflake";
34701
- } else if (contentPath.endsWith(".ms.sql")) {
34702
- return "mssql";
34703
- } else if (contentPath.endsWith(".pg.sql")) {
34704
- return "postgresql";
34705
- } else if (contentPath.endsWith(".gql")) {
34706
- return "graphql";
34707
- } else if (contentPath.endsWith(".sh")) {
34708
- return "bash";
34709
- } else if (contentPath.endsWith(".ps1")) {
34710
- return "powershell";
34711
- } else if (contentPath.endsWith(".php")) {
34712
- return "php";
34713
- } else if (contentPath.endsWith(".rs")) {
34714
- return "rust";
34715
- } else if (contentPath.endsWith(".cs")) {
34716
- return "csharp";
34717
- } else if (contentPath.endsWith(".playbook.yml")) {
34718
- return "ansible";
34719
- } else if (contentPath.endsWith(".nu")) {
34720
- return "nu";
34721
- } else if (contentPath.endsWith(".java")) {
34722
- return "java";
34723
- } else if (contentPath.endsWith(".rb")) {
34724
- return "ruby";
34725
- } else if (isDbtDescriptorPath(contentPath)) {
34726
- return "dbt";
34727
- } else if (contentPath.endsWith(".r")) {
34728
- return "rlang";
34729
- } else {
34730
- const ext = contentPath.substring(contentPath.lastIndexOf("."));
34731
- let hint = "";
34732
- if (ext === ".sql") {
34733
- hint = `
34734
- Bare .sql is ambiguous — use a dialect extension: .pg.sql (postgresql), .my.sql (mysql), .bq.sql (bigquery), .sf.sql (snowflake), .ms.sql (mssql), .odb.sql (oracledb), .duckdb.sql (duckdb)`;
34735
- }
34736
- throw new Error(`Cannot infer script language from extension '${ext}' (file ${contentPath}).` + hint + "\nSupported extensions: .ts (bun/deno), .py, .go, .sh, .ps1, .php, .rs, .cs, .nu, .java, .rb, .r, .gql, .playbook.yml, .pg.sql, .my.sql, .bq.sql, .sf.sql, .ms.sql, .odb.sql, .duckdb.sql, and a dbt project folder `<name>__dbt/`");
34737
- }
34738
- }
34739
- var workspaceDependenciesLanguages, LANG_ANNOTATION_CONFIG, LANG_COMMENT_LIT, LANG_ANNOTATIONS, SHARED_LOCK_DIR = "locks";
34740
- var init_script_common = __esm(async () => {
34741
- await init_resource_folders();
34742
- workspaceDependenciesLanguages = [
34743
- { language: "bun", filename: "package.json" },
34744
- { language: "python3", filename: "requirements.in" },
34745
- { language: "php", filename: "composer.json" },
34746
- { language: "go", filename: "go.mod" },
34747
- { language: "powershell", filename: "modules.json" }
34748
- ];
34749
- LANG_ANNOTATION_CONFIG = {
34750
- python3: { comment: "#", keyword: "requirements", validityRe: /^#\s?(\S+)\s*$/ },
34751
- bun: { comment: "//", keyword: "package_json" },
34752
- nativets: { comment: "//", keyword: "package_json" },
34753
- go: { comment: "//", keyword: "go_mod" },
34754
- php: { comment: "//", keyword: "composer_json" },
34755
- powershell: { comment: "#", keyword: "modules_json" }
34756
- };
34757
- LANG_COMMENT_LIT = {
34758
- python3: "#",
34759
- ansible: "#",
34760
- powershell: "#",
34761
- bun: "//",
34762
- nativets: "//",
34763
- deno: "//",
34764
- go: "//",
34765
- php: "//",
34766
- rust: "//!"
34767
- };
34768
- LANG_ANNOTATIONS = {
34769
- python3: [
34770
- "no_cache",
34771
- "no_postinstall",
34772
- "py_select_latest",
34773
- "skip_result_postprocessing",
34774
- "py310",
34775
- "py311",
34776
- "py312",
34777
- "py313",
34778
- "sandbox"
34779
- ],
34780
- bun: ["npm", "nodejs", "native", "nobundling", "sandbox"],
34781
- nativets: ["npm", "nodejs", "native", "nobundling", "sandbox"],
34782
- deno: ["npm", "nodejs", "native", "nobundling", "sandbox"],
34783
- go: ["go1_22_compat"]
34784
- };
34785
- });
34786
-
34787
34828
  // node_modules/balanced-match/dist/esm/index.js
34788
34829
  var balanced = (a, b, str) => {
34789
34830
  const ma = a instanceof RegExp ? maybeMatch(a, str) : a;
@@ -56381,7 +56422,7 @@ var init_openflow = __esm(() => {
56381
56422
  openflow_default = {
56382
56423
  openapi: "3.0.3",
56383
56424
  info: {
56384
- version: "1.811.1",
56425
+ version: "1.813.0",
56385
56426
  title: "OpenFlow Spec",
56386
56427
  contact: {
56387
56428
  name: "Ruben Fiszel",
@@ -57802,6 +57843,22 @@ Example: { type: 'object', properties: { name: { type: 'string' }, age: { type:
57802
57843
  description: `Array of file references (images or PDFs) for the AI agent.
57803
57844
  Format: Array<{ bucket: string, key: string }> - S3 object references
57804
57845
  Example: [{ bucket: 'my-bucket', key: 'documents/report.pdf' }]
57846
+ `
57847
+ },
57848
+ enabled_tools: {
57849
+ allOf: [
57850
+ {
57851
+ $ref: "#/components/schemas/InputTransform"
57852
+ }
57853
+ ],
57854
+ description: `Array of strings naming which of the tools configured in \`tools\` the agent may call
57855
+ this run. Leaving it unset carries every one of them; an empty array carries none.
57856
+ A tool is named as the model is shown it. An entry the model is shown nothing of is
57857
+ named by what identifies it instead: an MCP server by its resource path, carrying
57858
+ every tool it exposes (which of them stays that entry's include_tools/exclude_tools),
57859
+ and a websearch entry by the reserved name '__wm_web_search', whatever summary it carries
57860
+ (no tool may take that name).
57861
+ Example: ['get_user', 'u/admin/github_mcp', '__wm_web_search']
57805
57862
  `
57806
57863
  },
57807
57864
  max_completion_tokens: {
@@ -57869,7 +57926,7 @@ Range: 1-1000.
57869
57926
  description: `Path of a reusable \`ai_agent\` resource (hybrid linking). When set, the agent brain
57870
57927
  config (provider/model/system prompt/etc.) and tool set are resolved at runtime from
57871
57928
  that resource; the module's input_transforms then only carry the flow-local inputs
57872
- (user_message/user_attachments).
57929
+ (user_message/user_attachments/enabled_tools).
57873
57930
  `
57874
57931
  },
57875
57932
  tool_inputs: {
@@ -58726,6 +58783,16 @@ Frontend appends a \`*\` to the displayed name.
58726
58783
  type: "boolean",
58727
58784
  description: "If true, passes the request body as a raw string instead of parsing as JSON"
58728
58785
  },
58786
+ allowed_origins: {
58787
+ type: "array",
58788
+ nullable: true,
58789
+ maxItems: 100,
58790
+ items: {
58791
+ type: "string",
58792
+ maxLength: 256
58793
+ },
58794
+ description: "Origins allowed to call this route cross-origin, matched against the request's Origin header (ignoring case) and echoed back on a match. When set, the list governs both the preflight and the response, overriding any Access-Control-Allow-Origin the runnable returns via wm_headers. Use ['*'] to opt out of any restriction, including the http_route_default_allowed_origins instance setting. An empty list is not a configuration and resolves exactly as null does. When null, the instance setting applies, or Access-Control-Allow-Origin: * if it is unset. Ignored on a static website, which has no authentication of its own and so hands out public files: restricting which browsers may read them protects nothing while breaking cross-origin webfonts and fetches. A single-file static asset is not exempt, since it can carry an authentication_method."
58795
+ },
58729
58796
  error_handler_path: {
58730
58797
  type: "string",
58731
58798
  description: "Path to a script to run when the triggered job fails. A bare path, without the script/ or flow/ prefix a schedule error handler takes; it cannot be a flow."
@@ -60747,8 +60814,8 @@ function isWorkspaceSpecificFile(path) {
60747
60814
  var workspacePatternCache;
60748
60815
  var init_specific_items = __esm(async () => {
60749
60816
  init_esm2();
60750
- init_git();
60751
60817
  await __promiseAll([
60818
+ init_git(),
60752
60819
  init_utils(),
60753
60820
  init_conf(),
60754
60821
  init_types()
@@ -60774,286 +60841,6 @@ var init_tar = __esm(() => {
60774
60841
  init_tar_stream();
60775
60842
  });
60776
60843
 
60777
- // src/utils/dependency_tree.ts
60778
- async function uploadScripts(tree, workspace) {
60779
- const scriptHashes = {};
60780
- const workspaceDeps = [];
60781
- for (const path of tree.allPaths()) {
60782
- const content = tree.getContent(path);
60783
- const itemType = tree.getItemType(path);
60784
- if (itemType === "dependencies") {
60785
- if (content === undefined)
60786
- continue;
60787
- const info = workspaceDependenciesPathToLanguageAndFilename(path);
60788
- if (info) {
60789
- const hash = await generateHash(content);
60790
- workspaceDeps.push({ path, language: info.language, name: info.name, hash });
60791
- }
60792
- } else if (itemType === "script") {
60793
- if (!content)
60794
- continue;
60795
- const hash = await generateHash(content);
60796
- scriptHashes[path] = hash;
60797
- }
60798
- }
60799
- if (Object.keys(scriptHashes).length === 0 && workspaceDeps.length === 0)
60800
- return;
60801
- const mismatched = await diffRawScriptsWithDeployed({
60802
- workspace: workspace.workspaceId,
60803
- requestBody: {
60804
- scripts: scriptHashes,
60805
- workspace_deps: workspaceDeps
60806
- }
60807
- });
60808
- for (const path of mismatched) {
60809
- const content = tree.getContent(path);
60810
- const itemType = tree.getItemType(path);
60811
- if (itemType === "dependencies") {
60812
- if (content !== undefined) {
60813
- tree.setContentHash(path, "mismatched");
60814
- }
60815
- } else if (content) {
60816
- const hash = await storeRawScriptTemp({
60817
- workspace: workspace.workspaceId,
60818
- requestBody: content
60819
- });
60820
- tree.setContentHash(path, hash);
60821
- }
60822
- }
60823
- }
60824
-
60825
- class DoubleLinkedDependencyTree {
60826
- nodes = new Map;
60827
- workspaceDeps = {};
60828
- setWorkspaceDeps(deps) {
60829
- this.workspaceDeps = deps;
60830
- }
60831
- async addNode(path, content, language, metadata, imports, itemType, folder, originalPath, isDirectlyStale, isRawApp) {
60832
- const hasWorkspaceDeps = itemType === "script" || itemType === "inline_script";
60833
- const filteredDeps = hasWorkspaceDeps ? filterWorkspaceDependencies(this.workspaceDeps, content, language) : {};
60834
- const stalenessHash = await generateScriptHash({}, content, metadata);
60835
- if (!this.nodes.has(path)) {
60836
- this.nodes.set(path, {
60837
- content: "",
60838
- stalenessHash: "",
60839
- language: "deno",
60840
- metadata: "",
60841
- imports: new Set,
60842
- importedBy: new Set,
60843
- itemType: "script",
60844
- folder: "",
60845
- originalPath: "",
60846
- isDirectlyStale: false
60847
- });
60848
- }
60849
- const node = this.nodes.get(path);
60850
- node.content = content;
60851
- node.stalenessHash = stalenessHash;
60852
- node.language = language;
60853
- node.metadata = metadata;
60854
- node.itemType = itemType;
60855
- node.folder = folder;
60856
- node.originalPath = originalPath;
60857
- node.isDirectlyStale = isDirectlyStale;
60858
- node.isRawApp = isRawApp;
60859
- const filteredDepsPaths = Object.keys(filteredDeps);
60860
- for (const depsPath of filteredDepsPaths) {
60861
- if (!this.nodes.has(depsPath)) {
60862
- const depsInfo = workspaceDependenciesPathToLanguageAndFilename(depsPath);
60863
- const contentHash = await generateHash(filteredDeps[depsPath] + depsPath);
60864
- const isUpToDate = await checkifMetadataUptodate(depsPath, contentHash, undefined);
60865
- this.nodes.set(depsPath, {
60866
- content: filteredDeps[depsPath],
60867
- stalenessHash: "",
60868
- language: depsInfo?.language ?? "deno",
60869
- metadata: "",
60870
- imports: new Set,
60871
- importedBy: new Set,
60872
- itemType: "dependencies",
60873
- folder: "",
60874
- originalPath: depsPath,
60875
- isDirectlyStale: !isUpToDate
60876
- });
60877
- }
60878
- }
60879
- const allImports = [...imports, ...filteredDepsPaths];
60880
- for (const importPath of allImports) {
60881
- node.imports.add(importPath);
60882
- if (!this.nodes.has(importPath)) {
60883
- this.nodes.set(importPath, {
60884
- content: "",
60885
- stalenessHash: "",
60886
- language: "deno",
60887
- metadata: "",
60888
- imports: new Set,
60889
- importedBy: new Set,
60890
- itemType: "script",
60891
- folder: "",
60892
- originalPath: "",
60893
- isDirectlyStale: false
60894
- });
60895
- }
60896
- this.nodes.get(importPath).importedBy.add(path);
60897
- }
60898
- }
60899
- getContent(path) {
60900
- return this.nodes.get(path)?.content;
60901
- }
60902
- getStalenessHash(path) {
60903
- return this.nodes.get(path)?.stalenessHash;
60904
- }
60905
- getContentHash(path) {
60906
- return this.nodes.get(path)?.contentHash;
60907
- }
60908
- setContentHash(path, hash) {
60909
- const node = this.nodes.get(path);
60910
- if (node) {
60911
- node.contentHash = hash;
60912
- }
60913
- }
60914
- getLanguage(path) {
60915
- return this.nodes.get(path)?.language;
60916
- }
60917
- getMetadata(path) {
60918
- return this.nodes.get(path)?.metadata;
60919
- }
60920
- getStaleReason(path) {
60921
- return this.nodes.get(path)?.staleReason;
60922
- }
60923
- getItemType(path) {
60924
- return this.nodes.get(path)?.itemType;
60925
- }
60926
- getFolder(path) {
60927
- return this.nodes.get(path)?.folder;
60928
- }
60929
- getIsRawApp(path) {
60930
- return this.nodes.get(path)?.isRawApp;
60931
- }
60932
- getIsDirectlyStale(path) {
60933
- return this.nodes.get(path)?.isDirectlyStale ?? false;
60934
- }
60935
- getOriginalPath(path) {
60936
- return this.nodes.get(path)?.originalPath;
60937
- }
60938
- getImports(path) {
60939
- return this.nodes.get(path)?.imports;
60940
- }
60941
- isStale(path) {
60942
- return this.nodes.get(path)?.staleReason !== undefined;
60943
- }
60944
- propagateStaleness() {
60945
- const directlyStale = new Set;
60946
- for (const [path, node] of this.nodes.entries()) {
60947
- if (node.isDirectlyStale) {
60948
- directlyStale.add(path);
60949
- node.staleReason = "content changed";
60950
- }
60951
- }
60952
- const allStale = new Set(directlyStale);
60953
- const queue = [...directlyStale];
60954
- const visited = new Set;
60955
- while (queue.length > 0) {
60956
- const scriptPath = queue.shift();
60957
- if (visited.has(scriptPath))
60958
- continue;
60959
- visited.add(scriptPath);
60960
- const node = this.nodes.get(scriptPath);
60961
- if (!node)
60962
- continue;
60963
- for (const importer of node.importedBy) {
60964
- if (!allStale.has(importer)) {
60965
- allStale.add(importer);
60966
- queue.push(importer);
60967
- const importerNode = this.nodes.get(importer);
60968
- if (importerNode)
60969
- importerNode.staleReason = `depends on ${scriptPath}`;
60970
- }
60971
- }
60972
- }
60973
- }
60974
- traverseTransitive(scriptPath, callback) {
60975
- const queue = [scriptPath];
60976
- const visited = new Set;
60977
- while (queue.length > 0) {
60978
- const current = queue.shift();
60979
- if (visited.has(current))
60980
- continue;
60981
- visited.add(current);
60982
- const node = this.nodes.get(current);
60983
- if (!node)
60984
- continue;
60985
- for (const importPath of node.imports) {
60986
- const importNode = this.nodes.get(importPath);
60987
- if (importNode) {
60988
- const stop = callback(importPath, importNode);
60989
- if (!stop) {
60990
- queue.push(importPath);
60991
- }
60992
- }
60993
- }
60994
- }
60995
- }
60996
- allPaths() {
60997
- return this.nodes.keys();
60998
- }
60999
- *stalePaths() {
61000
- for (const [path, node] of this.nodes.entries()) {
61001
- if (node.staleReason) {
61002
- yield path;
61003
- }
61004
- }
61005
- }
61006
- has(path) {
61007
- return this.nodes.has(path);
61008
- }
61009
- getMismatchedWorkspaceDeps() {
61010
- const result = {};
61011
- for (const [path, node] of this.nodes.entries()) {
61012
- if (node.itemType === "dependencies" && node.contentHash && node.content !== undefined) {
61013
- result[path] = node.content;
61014
- }
61015
- }
61016
- return result;
61017
- }
61018
- getTempScriptRefs(scriptPath) {
61019
- const result = {};
61020
- this.traverseTransitive(scriptPath, (_path, node) => {
61021
- if (node.contentHash) {
61022
- result[_path] = node.contentHash;
61023
- }
61024
- });
61025
- return result;
61026
- }
61027
- getAllTempScriptRefs() {
61028
- const result = {};
61029
- for (const [path, node] of this.nodes.entries()) {
61030
- if (node.contentHash) {
61031
- result[path] = node.contentHash;
61032
- }
61033
- }
61034
- return result;
61035
- }
61036
- async persistDepsHashes(depsPaths) {
61037
- for (const path of depsPaths) {
61038
- const node = this.nodes.get(path);
61039
- if (node?.itemType === "dependencies" && node.content !== undefined) {
61040
- const hash = await generateHash(node.content + path);
61041
- await updateMetadataGlobalLock(path, hash);
61042
- }
61043
- }
61044
- }
61045
- get size() {
61046
- return this.nodes.size;
61047
- }
61048
- }
61049
- var init_dependency_tree = __esm(async () => {
61050
- init_services_gen();
61051
- await __promiseAll([
61052
- init_metadata(),
61053
- init_utils()
61054
- ]);
61055
- });
61056
-
61057
60844
  // src/utils/relative_imports.ts
61058
60845
  async function extractRelativeImports(code, scriptPath, language) {
61059
60846
  try {
@@ -61081,6 +60868,321 @@ var init_relative_imports = __esm(async () => {
61081
60868
  await init_metadata();
61082
60869
  });
61083
60870
 
60871
+ // src/utils/dependency_tree.ts
60872
+ async function resolvePlaceholdersFromLocal(tree, localScripts, defaultTs) {
60873
+ for (;; ) {
60874
+ let resolved = false;
60875
+ for (const remotePath of tree.placeholderPaths()) {
60876
+ const local = localScripts.get(remotePath);
60877
+ if (!local)
60878
+ continue;
60879
+ let language;
60880
+ try {
60881
+ language = inferContentTypeFromFilePath(local.localPath, defaultTs);
60882
+ } catch {
60883
+ continue;
60884
+ }
60885
+ const imports = await extractRelativeImports(local.content, remotePath, language);
60886
+ await tree.addNode(remotePath, local.content, language, "", imports, "script", remotePath, local.localPath, false);
60887
+ resolved = true;
60888
+ }
60889
+ if (!resolved)
60890
+ break;
60891
+ }
60892
+ }
60893
+ async function uploadScripts(tree, workspace) {
60894
+ const scriptHashes = {};
60895
+ const workspaceDeps = [];
60896
+ for (const path of tree.allPaths()) {
60897
+ const content = tree.getContent(path);
60898
+ const itemType = tree.getItemType(path);
60899
+ if (itemType === "dependencies") {
60900
+ if (content === undefined)
60901
+ continue;
60902
+ const info = workspaceDependenciesPathToLanguageAndFilename(path);
60903
+ if (info) {
60904
+ const hash = await generateHash(content);
60905
+ workspaceDeps.push({ path, language: info.language, name: info.name, hash });
60906
+ }
60907
+ } else if (itemType === "script") {
60908
+ if (!content)
60909
+ continue;
60910
+ const hash = await generateHash(content);
60911
+ scriptHashes[path] = hash;
60912
+ }
60913
+ }
60914
+ if (Object.keys(scriptHashes).length === 0 && workspaceDeps.length === 0)
60915
+ return;
60916
+ const mismatched = await diffRawScriptsWithDeployed({
60917
+ workspace: workspace.workspaceId,
60918
+ requestBody: {
60919
+ scripts: scriptHashes,
60920
+ workspace_deps: workspaceDeps
60921
+ }
60922
+ });
60923
+ for (const path of mismatched) {
60924
+ const content = tree.getContent(path);
60925
+ const itemType = tree.getItemType(path);
60926
+ if (itemType === "dependencies") {
60927
+ if (content !== undefined) {
60928
+ tree.setContentHash(path, "mismatched");
60929
+ }
60930
+ } else if (content) {
60931
+ const hash = await storeRawScriptTemp({
60932
+ workspace: workspace.workspaceId,
60933
+ requestBody: content
60934
+ });
60935
+ tree.setContentHash(path, hash);
60936
+ }
60937
+ }
60938
+ }
60939
+
60940
+ class DoubleLinkedDependencyTree {
60941
+ nodes = new Map;
60942
+ workspaceDeps = {};
60943
+ setWorkspaceDeps(deps) {
60944
+ this.workspaceDeps = deps;
60945
+ }
60946
+ async addNode(path, content, language, metadata, imports, itemType, folder, originalPath, isDirectlyStale, isRawApp) {
60947
+ const hasWorkspaceDeps = itemType === "script" || itemType === "inline_script";
60948
+ const filteredDeps = hasWorkspaceDeps ? filterWorkspaceDependencies(this.workspaceDeps, content, language) : {};
60949
+ const stalenessHash = await generateScriptHash({}, content, metadata);
60950
+ if (!this.nodes.has(path)) {
60951
+ this.nodes.set(path, {
60952
+ content: "",
60953
+ stalenessHash: "",
60954
+ language: "deno",
60955
+ metadata: "",
60956
+ imports: new Set,
60957
+ importedBy: new Set,
60958
+ itemType: "script",
60959
+ folder: "",
60960
+ originalPath: "",
60961
+ isDirectlyStale: false,
60962
+ isPlaceholder: true
60963
+ });
60964
+ }
60965
+ const node = this.nodes.get(path);
60966
+ node.isPlaceholder = false;
60967
+ node.content = content;
60968
+ node.stalenessHash = stalenessHash;
60969
+ node.language = language;
60970
+ node.metadata = metadata;
60971
+ node.itemType = itemType;
60972
+ node.folder = folder;
60973
+ node.originalPath = originalPath;
60974
+ node.isDirectlyStale = isDirectlyStale;
60975
+ node.isRawApp = isRawApp;
60976
+ const filteredDepsPaths = Object.keys(filteredDeps);
60977
+ for (const depsPath of filteredDepsPaths) {
60978
+ if (!this.nodes.has(depsPath)) {
60979
+ const depsInfo = workspaceDependenciesPathToLanguageAndFilename(depsPath);
60980
+ const contentHash = await generateHash(filteredDeps[depsPath] + depsPath);
60981
+ const isUpToDate = await checkifMetadataUptodate(depsPath, contentHash, undefined);
60982
+ this.nodes.set(depsPath, {
60983
+ content: filteredDeps[depsPath],
60984
+ stalenessHash: "",
60985
+ language: depsInfo?.language ?? "deno",
60986
+ metadata: "",
60987
+ imports: new Set,
60988
+ importedBy: new Set,
60989
+ itemType: "dependencies",
60990
+ folder: "",
60991
+ originalPath: depsPath,
60992
+ isDirectlyStale: !isUpToDate,
60993
+ isPlaceholder: false
60994
+ });
60995
+ }
60996
+ }
60997
+ const allImports = [...imports, ...filteredDepsPaths];
60998
+ for (const importPath of allImports) {
60999
+ node.imports.add(importPath);
61000
+ if (!this.nodes.has(importPath)) {
61001
+ this.nodes.set(importPath, {
61002
+ content: "",
61003
+ stalenessHash: "",
61004
+ language: "deno",
61005
+ metadata: "",
61006
+ imports: new Set,
61007
+ importedBy: new Set,
61008
+ itemType: "script",
61009
+ folder: "",
61010
+ originalPath: "",
61011
+ isDirectlyStale: false,
61012
+ isPlaceholder: true
61013
+ });
61014
+ }
61015
+ this.nodes.get(importPath).importedBy.add(path);
61016
+ }
61017
+ }
61018
+ getContent(path) {
61019
+ return this.nodes.get(path)?.content;
61020
+ }
61021
+ getStalenessHash(path) {
61022
+ return this.nodes.get(path)?.stalenessHash;
61023
+ }
61024
+ getContentHash(path) {
61025
+ return this.nodes.get(path)?.contentHash;
61026
+ }
61027
+ setContentHash(path, hash) {
61028
+ const node = this.nodes.get(path);
61029
+ if (node) {
61030
+ node.contentHash = hash;
61031
+ }
61032
+ }
61033
+ getLanguage(path) {
61034
+ return this.nodes.get(path)?.language;
61035
+ }
61036
+ getMetadata(path) {
61037
+ return this.nodes.get(path)?.metadata;
61038
+ }
61039
+ getStaleReason(path) {
61040
+ return this.nodes.get(path)?.staleReason;
61041
+ }
61042
+ getItemType(path) {
61043
+ return this.nodes.get(path)?.itemType;
61044
+ }
61045
+ getFolder(path) {
61046
+ return this.nodes.get(path)?.folder;
61047
+ }
61048
+ getIsRawApp(path) {
61049
+ return this.nodes.get(path)?.isRawApp;
61050
+ }
61051
+ getIsDirectlyStale(path) {
61052
+ return this.nodes.get(path)?.isDirectlyStale ?? false;
61053
+ }
61054
+ getOriginalPath(path) {
61055
+ return this.nodes.get(path)?.originalPath;
61056
+ }
61057
+ getImports(path) {
61058
+ return this.nodes.get(path)?.imports;
61059
+ }
61060
+ isStale(path) {
61061
+ return this.nodes.get(path)?.staleReason !== undefined;
61062
+ }
61063
+ propagateStaleness() {
61064
+ const directlyStale = new Set;
61065
+ for (const [path, node] of this.nodes.entries()) {
61066
+ if (node.isDirectlyStale) {
61067
+ directlyStale.add(path);
61068
+ node.staleReason = "content changed";
61069
+ }
61070
+ }
61071
+ const allStale = new Set(directlyStale);
61072
+ const queue = [...directlyStale];
61073
+ const visited = new Set;
61074
+ while (queue.length > 0) {
61075
+ const scriptPath = queue.shift();
61076
+ if (visited.has(scriptPath))
61077
+ continue;
61078
+ visited.add(scriptPath);
61079
+ const node = this.nodes.get(scriptPath);
61080
+ if (!node)
61081
+ continue;
61082
+ for (const importer of node.importedBy) {
61083
+ if (!allStale.has(importer)) {
61084
+ allStale.add(importer);
61085
+ queue.push(importer);
61086
+ const importerNode = this.nodes.get(importer);
61087
+ if (importerNode)
61088
+ importerNode.staleReason = `depends on ${scriptPath}`;
61089
+ }
61090
+ }
61091
+ }
61092
+ }
61093
+ traverseTransitive(scriptPath, callback) {
61094
+ const queue = [scriptPath];
61095
+ const visited = new Set;
61096
+ while (queue.length > 0) {
61097
+ const current = queue.shift();
61098
+ if (visited.has(current))
61099
+ continue;
61100
+ visited.add(current);
61101
+ const node = this.nodes.get(current);
61102
+ if (!node)
61103
+ continue;
61104
+ for (const importPath of node.imports) {
61105
+ const importNode = this.nodes.get(importPath);
61106
+ if (importNode) {
61107
+ const stop = callback(importPath, importNode);
61108
+ if (!stop) {
61109
+ queue.push(importPath);
61110
+ }
61111
+ }
61112
+ }
61113
+ }
61114
+ }
61115
+ allPaths() {
61116
+ return this.nodes.keys();
61117
+ }
61118
+ placeholderPaths() {
61119
+ const result = [];
61120
+ for (const [path, node] of this.nodes.entries()) {
61121
+ if (node.isPlaceholder)
61122
+ result.push(path);
61123
+ }
61124
+ return result;
61125
+ }
61126
+ *stalePaths() {
61127
+ for (const [path, node] of this.nodes.entries()) {
61128
+ if (node.staleReason) {
61129
+ yield path;
61130
+ }
61131
+ }
61132
+ }
61133
+ has(path) {
61134
+ return this.nodes.has(path);
61135
+ }
61136
+ getMismatchedWorkspaceDeps() {
61137
+ const result = {};
61138
+ for (const [path, node] of this.nodes.entries()) {
61139
+ if (node.itemType === "dependencies" && node.contentHash && node.content !== undefined) {
61140
+ result[path] = node.content;
61141
+ }
61142
+ }
61143
+ return result;
61144
+ }
61145
+ getTempScriptRefs(scriptPath) {
61146
+ const result = {};
61147
+ this.traverseTransitive(scriptPath, (_path, node) => {
61148
+ if (node.contentHash) {
61149
+ result[_path] = node.contentHash;
61150
+ }
61151
+ });
61152
+ return result;
61153
+ }
61154
+ getAllTempScriptRefs() {
61155
+ const result = {};
61156
+ for (const [path, node] of this.nodes.entries()) {
61157
+ if (node.contentHash) {
61158
+ result[path] = node.contentHash;
61159
+ }
61160
+ }
61161
+ return result;
61162
+ }
61163
+ async persistDepsHashes(depsPaths) {
61164
+ for (const path of depsPaths) {
61165
+ const node = this.nodes.get(path);
61166
+ if (node?.itemType === "dependencies" && node.content !== undefined) {
61167
+ const hash = await generateHash(node.content + path);
61168
+ await updateMetadataGlobalLock(path, hash);
61169
+ }
61170
+ }
61171
+ }
61172
+ get size() {
61173
+ return this.nodes.size;
61174
+ }
61175
+ }
61176
+ var init_dependency_tree = __esm(async () => {
61177
+ init_services_gen();
61178
+ await __promiseAll([
61179
+ init_script_common(),
61180
+ init_metadata(),
61181
+ init_utils(),
61182
+ init_relative_imports()
61183
+ ]);
61184
+ });
61185
+
61084
61186
  // windmill-utils-internal/src/path-utils/path-assigner.ts
61085
61187
  function getLanguageExtension(language, defaultTs = "bun") {
61086
61188
  if (language === defaultTs || language === "bunnative") {
@@ -63426,7 +63528,6 @@ var init_script = __esm(async () => {
63426
63528
  init_log();
63427
63529
  init_http_guards();
63428
63530
  init_services_gen();
63429
- init_git();
63430
63531
  init_script_bootstrap();
63431
63532
  init_job_polling();
63432
63533
  init_tar();
@@ -63438,6 +63539,7 @@ var init_script = __esm(async () => {
63438
63539
  init_confirm(),
63439
63540
  init_utils(),
63440
63541
  init_specific_items(),
63542
+ init_git(),
63441
63543
  init_metadata(),
63442
63544
  init_utils(),
63443
63545
  init_script_common(),
@@ -64422,13 +64524,13 @@ var init_resource = __esm(async () => {
64422
64524
  init_colors2();
64423
64525
  init_log();
64424
64526
  init_services_gen();
64425
- init_git();
64426
64527
  await __promiseAll([
64427
64528
  init_types(),
64428
64529
  init_auth(),
64429
64530
  init_context(),
64430
64531
  init_utils(),
64431
- init_specific_items()
64532
+ init_specific_items(),
64533
+ init_git()
64432
64534
  ]);
64433
64535
  import_yaml11 = __toESM(require_dist(), 1);
64434
64536
  command7 = new Command().description("resource related commands").option("--json", "Output as JSON (for piping to jq)").action(list5).command("list", "list all resources").option("--json", "Output as JSON (for piping to jq)").action(list5).command("get", "get a resource's details").arguments("<path:string>").option("--json", "Output as JSON (for piping to jq)").action(get3).command("new", "create a new resource locally").arguments("<path:string>").action(newResource).command("push", "push a local resource spec. This overrides any remote versions.").arguments("<file_path:string> <remote_path:string>").action(push3);
@@ -66198,6 +66300,14 @@ function preservePendingScriptLocks(remote, local) {
66198
66300
  remote[lockKey] = local[lockKey];
66199
66301
  }
66200
66302
  }
66303
+ function stripUnappliedSettingsFields(local, remote) {
66304
+ delete local?.name;
66305
+ delete remote?.name;
66306
+ if (local?.color == null) {
66307
+ delete local?.color;
66308
+ delete remote?.color;
66309
+ }
66310
+ }
66201
66311
  async function compareDynFSElement(els1, els2, ignore, json, skips, ignoreMetadataDeletion, codebases, ignoreCodebaseChanges, specificItems, branchOverride, isEls1Remote, caseInsensitiveFs, parentOwnsScheduleEnabled) {
66202
66312
  let [m1, m2] = els2 ? await Promise.all([
66203
66313
  elementsToMap(els1, ignore, json, skips, specificItems, branchOverride, isEls1Remote),
@@ -66313,6 +66423,9 @@ async function compareDynFSElement(els1, els2, ignore, json, skips, ignoreMetada
66313
66423
  delete parsedV?.enabled;
66314
66424
  delete parsedM2?.enabled;
66315
66425
  }
66426
+ if (isEls1Remote === false && isWorkspaceSettingsFile(k)) {
66427
+ stripUnappliedSettingsFields(parsedV, parsedM2);
66428
+ }
66316
66429
  if (deepEqual(parsedV, parsedM2)) {
66317
66430
  continue;
66318
66431
  }
@@ -66323,6 +66436,9 @@ async function compareDynFSElement(els1, els2, ignore, json, skips, ignoreMetada
66323
66436
  delete before?.enabled;
66324
66437
  delete after?.enabled;
66325
66438
  }
66439
+ if (isEls1Remote === false && isWorkspaceSettingsFile(k)) {
66440
+ stripUnappliedSettingsFields(after, before);
66441
+ }
66326
66442
  if (deepEqual(before, after)) {
66327
66443
  continue;
66328
66444
  }
@@ -66510,6 +66626,32 @@ function countDatatableMigrationRecords(changes) {
66510
66626
  function untrackedDatatableMigrationDeletions(changes, recorded) {
66511
66627
  return changes.filter((c) => c.name === "deleted" && isDatatableMigrationPath(c.path) && !(recorded.kind === "known" && recorded.paths.has(c.path)));
66512
66628
  }
66629
+ function secretBearingObjectKind(p) {
66630
+ if (isFilesetResource(p))
66631
+ return;
66632
+ if (p.endsWith(".lock"))
66633
+ return;
66634
+ let typ;
66635
+ try {
66636
+ typ = getTypeStrFromPath(p);
66637
+ } catch {
66638
+ return;
66639
+ }
66640
+ return typ === "variable" || typ === "resource" ? typ : undefined;
66641
+ }
66642
+ function secretBearingObjectPath(p) {
66643
+ const normalized = p.replaceAll(SEP9, "/");
66644
+ return secretBearingObjectKind(p) === "resource" ? removeResourceSuffix(normalized) : normalized.replace(/\.variable\.(yaml|json)$/, "");
66645
+ }
66646
+ function describeSecretBearingChanges(changes) {
66647
+ const objects = { variable: new Set, resource: new Set };
66648
+ for (const c of changes) {
66649
+ const kind = secretBearingObjectKind(c.path);
66650
+ if (kind)
66651
+ objects[kind].add(secretBearingObjectPath(c.path));
66652
+ }
66653
+ return ["variable", "resource"].filter((k) => objects[k].size > 0).map((k) => `${objects[k].size} ${k}${objects[k].size > 1 ? "s" : ""}`).join(" and ");
66654
+ }
66513
66655
  function removesDbtDescriptor(change) {
66514
66656
  return isDbtDescriptorPath(change.path) && (change.name === "added" && change.content === "" || change.name === "edited" && change.after === "");
66515
66657
  }
@@ -66603,6 +66745,19 @@ async function addToChangedIfNotExists(p, tracker) {
66603
66745
  } catch {}
66604
66746
  }
66605
66747
  }
66748
+ function localScriptsByRemotePath(localMap) {
66749
+ const byRemotePath = new Map;
66750
+ for (const [p, content] of Object.entries(localMap)) {
66751
+ if (isScriptModulePath(p)) {
66752
+ if (!isModuleEntryPoint(p))
66753
+ continue;
66754
+ } else if (!hasScriptExt(p) || isDatatableMigrationPath(p) || isFileResource(p) || isFilesetResource(p) || isFlowPath(p) || isAppPath(p) || isRawAppPath(p)) {
66755
+ continue;
66756
+ }
66757
+ byRemotePath.set(scriptPathToRemotePath(p), { localPath: p, content });
66758
+ }
66759
+ return byRemotePath;
66760
+ }
66606
66761
  async function buildTracker(changes) {
66607
66762
  const tracker = {
66608
66763
  scripts: [],
@@ -67385,6 +67540,7 @@ Push aborted: ${lockIssues.length} script(s) missing locks.`));
67385
67540
  }
67386
67541
  }
67387
67542
  if (autoRegenerate && tree) {
67543
+ await resolvePlaceholdersFromLocal(tree, localScriptsByRemotePath(localMap), opts.defaultTs);
67388
67544
  tree.propagateStaleness();
67389
67545
  try {
67390
67546
  await uploadScripts(tree, workspace);
@@ -68318,6 +68474,10 @@ ${pushedCount} of ${changes.length} changes pushed to the remote workspace ${wor
68318
68474
  info(colors.bold.green.underline(`
68319
68475
  Done! All ${changes.length} changes pushed to the remote workspace ${workspace.workspaceId} named ${workspace.name} (${(performance.now() - start).toFixed(0)}ms)`));
68320
68476
  }
68477
+ const deletedSecretBearing = changes.filter((c) => c.name === "deleted" && secretBearingObjectKind(c.path) !== undefined && !failedChanges.some((f) => f.path === c.path));
68478
+ if (deletedSecretBearing.length > 0) {
68479
+ info(colors.gray(`${describeSecretBearingChanges(deletedSecretBearing)} deleted. The workspace trashbin keeps a deleted item for three days; a workspace admin can restore it with \`wmill trash list\` and \`wmill trash restore <id>\`, or from Workspace settings -> Trashbin.`));
68480
+ }
68321
68481
  if (failedChanges.length > 0) {
68322
68482
  process.exitCode = 1;
68323
68483
  }
@@ -68339,7 +68499,7 @@ Done! All ${changes.length} changes pushed to the remote workspace ${workspace.w
68339
68499
  }
68340
68500
  }
68341
68501
  }
68342
- var import_yaml14, branchDeprecationWarned = false, yamlOptions, _caseInsensitiveFsCache, isNotWmillFile = (p, isDirectory) => {
68502
+ var import_yaml14, branchDeprecationWarned = false, yamlOptions, _caseInsensitiveFsCache, isWorkspaceSettingsFile = (p) => /^settings(\.[^./\\]+)?\.(yaml|json)$/.test(p), isNotWmillFile = (p, isDirectory) => {
68343
68503
  if (p.endsWith(SEP9)) {
68344
68504
  return false;
68345
68505
  }
@@ -68377,7 +68537,6 @@ var init_sync = __esm(async () => {
68377
68537
  init_log();
68378
68538
  init_esm2();
68379
68539
  init_services_gen();
68380
- init_git();
68381
68540
  init_path_assigner();
68382
68541
  init_extractor();
68383
68542
  await __promiseAll([
@@ -68396,6 +68555,7 @@ var init_sync = __esm(async () => {
68396
68555
  init_conf(),
68397
68556
  init_permissioned_as(),
68398
68557
  init_specific_items(),
68558
+ init_git(),
68399
68559
  init_types(),
68400
68560
  init_codebase(),
68401
68561
  init_metadata(),
@@ -74162,6 +74322,11 @@ async function pushWorkspaceSettings(workspace, _path, settings, localSettings)
74162
74322
  }
74163
74323
  const { slack_team_id: _lst, slack_name: _lsn, name: _ln, ...comparableLocal } = localSettings;
74164
74324
  const { slack_team_id: _rst, slack_name: _rsn, name: _rn, ...comparableRemote } = settings;
74325
+ const colorManaged = localSettings.color != null;
74326
+ if (!colorManaged) {
74327
+ delete comparableLocal.color;
74328
+ delete comparableRemote.color;
74329
+ }
74165
74330
  if (isSuperset(comparableLocal, comparableRemote)) {
74166
74331
  debug(`Workspace settings are up to date`);
74167
74332
  return;
@@ -74277,7 +74442,7 @@ async function pushWorkspaceSettings(workspace, _path, settings, localSettings)
74277
74442
  }
74278
74443
  });
74279
74444
  }
74280
- if (localSettings.color != settings.color) {
74445
+ if (colorManaged && localSettings.color != settings.color) {
74281
74446
  debug(`Updating workspace color...`);
74282
74447
  await changeWorkspaceColor({
74283
74448
  workspace,
@@ -75912,10 +76077,10 @@ var init_trigger = __esm(async () => {
75912
76077
  init_mod6();
75913
76078
  init_colors2();
75914
76079
  init_log();
75915
- init_git();
75916
76080
  await __promiseAll([
75917
76081
  init_types(),
75918
76082
  init_specific_items(),
76083
+ init_git(),
75919
76084
  init_auth(),
75920
76085
  init_context(),
75921
76086
  init_permissioned_as(),
@@ -77981,13 +78146,13 @@ var init_pull2 = __esm(async () => {
77981
78146
  init_colors2();
77982
78147
  init_log();
77983
78148
  init_services_gen();
77984
- init_git();
77985
78149
  await __promiseAll([
77986
78150
  init_auth(),
77987
78151
  init_context(),
77988
78152
  init_conf(),
77989
78153
  init_sync(),
77990
78154
  init_utils(),
78155
+ init_git(),
77991
78156
  init_legacySettings(),
77992
78157
  init_utils2()
77993
78158
  ]);
@@ -78243,10 +78408,10 @@ var init_status = __esm(async () => {
78243
78408
  init_colors2();
78244
78409
  init_log();
78245
78410
  init_services_gen();
78246
- init_git();
78247
78411
  await __promiseAll([
78248
78412
  init_auth(),
78249
- init_context()
78413
+ init_context(),
78414
+ init_git()
78250
78415
  ]);
78251
78416
  });
78252
78417
 
@@ -78393,6 +78558,8 @@ No CI workflow runs \`wmill sync push\` automatically, so deploy directly from t
78393
78558
  - \`wmill sync push --dry-run\` to preview.
78394
78559
  - \`wmill sync push\` to apply.
78395
78560
 
78561
+ A push deletes remote items that have no local file. They land in the workspace trashbin for three days: \`wmill trash list\` shows them and \`wmill trash restore <id>\` puts one back (both need a workspace admin).
78562
+
78396
78563
  ### In both cases
78397
78564
 
78398
78565
  Only deploy when the user explicitly asks to deploy, publish, push, or ship — not when they say "run", "try", or "test". For testing local edits use the per-entity \`preview\` commands (\`wmill script preview\`, \`wmill flow preview\`) — they don't deploy.
@@ -83047,6 +83214,14 @@ def parse_sql_client_name(name: str) -> tuple[str, Optional[str]]
83047
83214
  # it grows with both the width of the fan-out and \`\`attempts\`\`. Retries with
83048
83215
  # no \`\`delay\`\` all go out in a single round.
83049
83216
  #
83217
+ # \`\`cache_ttl\`\` serves a previous result of the task for that many seconds
83218
+ # instead of running it again. A task is keyed on its step key (its name and
83219
+ # call order) and the workflow's input, not on the arguments it is called
83220
+ # with, so cache one only when whether it runs, and what it receives, follow
83221
+ # from the workflow's input alone. A \`\`task_script\`\` target is keyed on the
83222
+ # arguments it is called with. It has no effect on a \`\`task_flow\`\` target,
83223
+ # which keeps its flow's own cache policy.
83224
+ #
83050
83225
  # Usage::
83051
83226
  #
83052
83227
  # @task
@@ -84013,7 +84188,7 @@ Reference a specific resource using \`$res:\` prefix:
84013
84188
 
84014
84189
  ## OpenFlow Schema
84015
84190
 
84016
- {"OpenFlow":{"type":"object","description":"Top-level flow definition containing metadata, configuration, and the flow structure","properties":{"summary":{"type":"string","description":"Short description of what this flow does"},"description":{"type":"string","description":"Detailed documentation for this flow"},"value":{"$ref":"#/components/schemas/FlowValue"},"schema":{"type":"object","description":"JSON Schema for flow inputs. Use this to define input parameters, their types, defaults, and validation. For resource inputs, set type to 'object' and format to 'resource-<type>' (e.g., 'resource-stripe')"},"on_behalf_of_email":{"type":"string","description":"Address of the account the flow runs on behalf of. Derived from on_behalf_of on read; accepted on write, where it is resolved to the account it names."},"on_behalf_of":{"type":"string","description":"The flow runs with the permissions of this identity: u/{username}, g/{group}, or a bare email when the username is itself email-shaped. The only stored half of the identity; on_behalf_of_email is derived from it. Omit it when writing and it is resolved from that address instead."}},"required":["summary","value"]},"FlowValue":{"type":"object","description":"The flow structure containing modules and optional preprocessor/failure handlers","properties":{"modules":{"type":"array","description":"Array of steps that execute in sequence. Each step can be a script, subflow, loop, or branch","items":{"$ref":"#/components/schemas/FlowModule"}},"failure_module":{"description":"Special module that executes when the flow fails. Receives error object with message, name, stack, and step_id. Must have id 'failure'. Only supports script/rawscript types","$ref":"#/components/schemas/FlowModule"},"preprocessor_module":{"description":"Special module that runs before the first step on external triggers. Must have id 'preprocessor'. Only supports script/rawscript types. Cannot reference other step results","$ref":"#/components/schemas/FlowModule"},"same_worker":{"type":"boolean","description":"If true, all steps run on the same worker for better performance"},"preserve_step_tags":{"type":"boolean","description":"If true and the flow runs on a custom worker tag, steps that declare their own non-empty tag run on it instead of inheriting the flow tag. Steps without their own tag still inherit the flow tag."},"concurrent_limit":{"type":"number","description":"Maximum number of concurrent executions of this flow"},"concurrency_key":{"type":"string","description":"Expression to group concurrent executions (e.g., by user ID)"},"concurrency_time_window_s":{"type":"number","description":"Time window in seconds for concurrent_limit"},"debounce_delay_s":{"type":"integer","description":"Delay in seconds to debounce flow executions"},"debounce_key":{"type":"string","description":"Expression to group debounced executions"},"debounce_args_to_accumulate":{"type":"array","description":"Arguments to accumulate across debounced executions","items":{"type":"string"}},"max_total_debouncing_time":{"type":"integer","description":"Maximum total time in seconds that a job can be debounced"},"max_total_debounces_amount":{"type":"integer","description":"Maximum number of times a job can be debounced"},"skip_expr":{"type":"string","description":"JavaScript expression to conditionally skip the entire flow"},"cache_ttl":{"type":"number","description":"Cache duration in seconds for flow results"},"cache_ignore_s3_path":{"type":"boolean"},"delete_after_secs":{"type":"integer","description":"If set, delete the flow job's args, result and logs after this many seconds following job completion"},"flow_env":{"type":"object","description":"Environment variables available to all steps. Values can be strings, JSON values, or special references: '$var:path' (workspace variable) or '$res:path' (resource).","additionalProperties":{}},"priority":{"type":"number","description":"Execution priority (higher numbers run first)"},"early_return":{"type":"string","description":"JavaScript expression to return early from the flow"},"chat_input_enabled":{"type":"boolean","description":"Whether this flow accepts chat-style input"},"notes":{"type":"array","description":"Sticky notes attached to the flow","items":{"$ref":"#/components/schemas/FlowNote"}},"groups":{"type":"array","description":"Semantic groups of modules for organizational purposes","items":{"$ref":"#/components/schemas/FlowGroup"}}},"required":["modules"]},"Retry":{"type":"object","description":"Retry configuration for failed module executions","properties":{"constant":{"type":"object","description":"Retry with constant delay between attempts","properties":{"attempts":{"type":"integer","description":"Number of retry attempts"},"seconds":{"type":"integer","description":"Seconds to wait between retries"}}},"exponential":{"type":"object","description":"Retry with exponential backoff (delay doubles each time)","properties":{"attempts":{"type":"integer","description":"Number of retry attempts"},"multiplier":{"type":"integer","description":"Multiplier for exponential backoff"},"seconds":{"type":"integer","minimum":1,"description":"Initial delay in seconds"},"random_factor":{"type":"integer","minimum":0,"maximum":100,"description":"Random jitter percentage (0-100) to avoid thundering herd"}}},"retry_if":{"$ref":"#/components/schemas/RetryIf"}}},"FlowNote":{"type":"object","description":"A sticky note attached to a flow for documentation and annotation","properties":{"id":{"type":"string","description":"Unique identifier for the note"},"text":{"type":"string","description":"Content of the note"},"position":{"type":"object","description":"Position of the note in the flow editor","properties":{"x":{"type":"number","description":"X coordinate"},"y":{"type":"number","description":"Y coordinate"}},"required":["x","y"]},"size":{"type":"object","description":"Size of the note in the flow editor","properties":{"width":{"type":"number","description":"Width in pixels"},"height":{"type":"number","description":"Height in pixels"}},"required":["width","height"]},"color":{"type":"string","description":"Color of the note (e.g., \\"yellow\\", \\"#ffff00\\")"},"type":{"type":"string","enum":["free","group"],"description":"Type of note - 'free' for standalone notes, 'group' for notes that group other nodes"},"locked":{"type":"boolean","default":false,"description":"Whether the note is locked and cannot be edited or moved"},"contained_node_ids":{"type":"array","items":{"type":"string"},"description":"For group notes, the IDs of nodes contained within this group"}},"required":["id","text","color","type"]},"FlowGroup":{"type":"object","description":"A semantic group of flow modules for organizational purposes. Does not affect execution \\u2014 modules remain in their original position in the flow. Groups provide naming and collapsibility in the editor. Members are computed dynamically from all nodes on paths between start_id and end_id.","properties":{"summary":{"type":"string","description":"Display name for this group"},"note":{"type":"string","description":"Markdown note shown below the group header"},"autocollapse":{"type":"boolean","default":false,"description":"If true, this group is collapsed by default in the flow editor. UI hint only."},"start_id":{"type":"string","description":"ID of the first flow module in this group (topological entry point)"},"end_id":{"type":"string","description":"ID of the last flow module in this group (topological exit point)"},"color":{"type":"string","description":"Color for the group in the flow editor"}},"required":["start_id","end_id"]},"RetryIf":{"type":"object","description":"Conditional retry based on error or result","properties":{"expr":{"type":"string","description":"JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables"}},"required":["expr"]},"StopAfterIf":{"type":"object","description":"Early termination condition for a module","properties":{"skip_if_stopped":{"type":"boolean","description":"If true, following steps are skipped when this condition triggers"},"expr":{"type":"string","description":"JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"},"error_message":{"type":"string","nullable":true,"description":"Custom error message when stopping with an error. Mutually exclusive with skip_if_stopped. If set to a non-empty string, the flow stops with this error. If empty string, a default error message is used. If null or omitted, no error is raised."},"error_include_result":{"type":"boolean","description":"When stopping with an error (error_message set), embed the stopping step's own result inside the raised error object (as error.result) instead of discarding it. The top-level result stays { error }. Defaults to false."}},"required":["expr"]},"FlowModule":{"type":"object","description":"A single step in a flow. Can be a script, subflow, loop, or branch","properties":{"id":{"type":"string","description":"Unique identifier for this step. Used to reference results via 'results.step_id'. Must be a valid identifier (alphanumeric, underscore, hyphen)"},"value":{"$ref":"#/components/schemas/FlowModuleValue"},"stop_after_if":{"description":"Early termination condition evaluated after this step completes","$ref":"#/components/schemas/StopAfterIf"},"stop_after_all_iters_if":{"description":"For loops only - early termination condition evaluated after all iterations complete","$ref":"#/components/schemas/StopAfterIf"},"skip_if":{"type":"object","description":"Conditionally skip this step based on previous results or flow inputs","properties":{"expr":{"type":"string","description":"JavaScript expression that returns true to skip. Can use 'flow_input' or 'results.<step_id>'"}},"required":["expr"]},"sleep":{"description":"Delay before executing this step (in seconds or as expression)","$ref":"#/components/schemas/InputTransform"},"cache_ttl":{"type":"number","description":"Cache duration in seconds for this step's results"},"cache_ignore_s3_path":{"type":"boolean"},"timeout":{"description":"Maximum execution time in seconds (static value or expression)","$ref":"#/components/schemas/InputTransform"},"delete_after_secs":{"type":"integer","description":"If set, delete the step's args, result and logs after this many seconds following job completion"},"summary":{"type":"string","description":"Short description of what this step does"},"mock":{"type":"object","description":"Mock configuration for testing without executing the actual step","properties":{"enabled":{"type":"boolean","description":"If true, return mock value instead of executing"},"return_value":{"description":"Value to return when mocked"}}},"suspend":{"type":"object","description":"Configuration for approval/resume steps that wait for user input","properties":{"required_events":{"type":"integer","description":"Number of approvals required before continuing"},"timeout":{"type":"integer","description":"Timeout in seconds before auto-continuing or canceling"},"resume_form":{"type":"object","description":"Form schema for collecting input when resuming","properties":{"schema":{"type":"object","description":"JSON Schema for the resume form"}}},"user_auth_required":{"type":"boolean","description":"If true, only authenticated users can approve"},"user_groups_required":{"description":"Expression or list of groups that can approve","$ref":"#/components/schemas/InputTransform"},"self_approval_disabled":{"type":"boolean","description":"If true, the user who started the flow cannot approve"},"hide_cancel":{"type":"boolean","description":"If true, hide the cancel button on the approval form"},"continue_on_disapprove_timeout":{"type":"boolean","description":"If true, continue flow on timeout instead of canceling"},"skin":{"type":"string","enum":["detailed","minimal"],"description":"How the approval request is presented, on the approval page and in Slack/Teams approval messages. 'detailed' (used when unset) shows the flow details (arguments, graph, approvers); 'minimal' shows only the request: the step description, form and approve/reject actions"}}},"priority":{"type":"number","description":"Execution priority for this step (higher numbers run first)"},"continue_on_error":{"type":"boolean","description":"If true, flow continues even if this step fails"},"retry":{"description":"Retry configuration if this step fails","$ref":"#/components/schemas/Retry"},"debouncing":{"description":"Debounce configuration for this step (EE only)","type":"object","properties":{"debounce_delay_s":{"type":"integer","description":"Delay in seconds to debounce this step's executions across flow runs"},"debounce_key":{"type":"string","description":"Expression to group debounced executions. Supports $workspace and $args[name]. Default: $workspace/flow/<flow_path>-<step_id>"},"debounce_args_to_accumulate":{"type":"array","description":"Array-type arguments to accumulate across debounced executions","items":{"type":"string"}},"max_total_debouncing_time":{"type":"integer","description":"Maximum total time in seconds before forced execution"},"max_total_debounces_amount":{"type":"integer","description":"Maximum number of debounces before forced execution"}}}},"required":["value","id"]},"InputTransform":{"description":"Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs","oneOf":[{"$ref":"#/components/schemas/StaticTransform"},{"$ref":"#/components/schemas/JavascriptTransform"},{"$ref":"#/components/schemas/AiTransform"}],"discriminator":{"propertyName":"type","mapping":{"static":"#/components/schemas/StaticTransform","javascript":"#/components/schemas/JavascriptTransform","ai":"#/components/schemas/AiTransform"}}},"StaticTransform":{"type":"object","description":"Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'","properties":{"value":{"description":"The static value. For resources, use format '$res:path/to/resource'"},"type":{"type":"string","enum":["static"]}},"required":["type"]},"JavascriptTransform":{"type":"object","description":"JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')","properties":{"expr":{"type":"string","description":"JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"},"type":{"type":"string","enum":["javascript"]}},"required":["expr","type"]},"AiTransform":{"type":"object","description":"Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.","properties":{"type":{"type":"string","enum":["ai"]}},"required":["type"]},"AIProviderKind":{"type":"string","description":"Supported AI provider types","enum":["openai","azure_openai","azure_foundry","anthropic","mistral","deepseek","googleai","groq","openrouter","togetherai","customai","aws_bedrock"]},"ProviderConfig":{"type":"object","description":"Complete AI provider configuration with resource reference and model selection","properties":{"kind":{"$ref":"#/components/schemas/AIProviderKind"},"resource":{"type":"string","description":"Resource reference in format '$res:{resource_path}' pointing to provider credentials"},"model":{"type":"string","description":"Model identifier (e.g., 'gpt-4', 'claude-3-opus-20240229', 'gemini-pro')"},"reasoning_effort":{"type":"string","description":"Provider-native reasoning effort token (e.g. 'low', 'high', 'none') for models that support extended thinking. Optional; unset leaves the provider default."}},"required":["kind","resource","model"]},"StaticProviderTransform":{"type":"object","description":"Static provider configuration passed directly to the AI agent","properties":{"value":{"$ref":"#/components/schemas/ProviderConfig"},"type":{"type":"string","enum":["static"]}},"required":["type","value"]},"ProviderTransform":{"description":"Provider configuration - can be static (ProviderConfig), JavaScript expression, or AI-determined","oneOf":[{"$ref":"#/components/schemas/StaticProviderTransform"},{"$ref":"#/components/schemas/JavascriptTransform"},{"$ref":"#/components/schemas/AiTransform"}],"discriminator":{"propertyName":"type","mapping":{"static":"#/components/schemas/StaticProviderTransform","javascript":"#/components/schemas/JavascriptTransform","ai":"#/components/schemas/AiTransform"}}},"MemoryOff":{"type":"object","description":"No conversation memory/context","properties":{"kind":{"type":"string","enum":["off"]}},"required":["kind"]},"MemoryAuto":{"type":"object","description":"Automatic context management","properties":{"kind":{"type":"string","enum":["auto"]},"context_length":{"type":"integer","description":"Maximum number of messages to retain in context"},"memory_id":{"type":"string","description":"Identifier for persistent memory across agent invocations"}},"required":["kind"]},"MemoryMessage":{"type":"object","description":"A single message in conversation history","properties":{"role":{"type":"string","enum":["user","assistant","system"]},"content":{"type":"string"}},"required":["role","content"]},"MemoryManual":{"type":"object","description":"Explicit message history","properties":{"kind":{"type":"string","enum":["manual"]},"messages":{"type":"array","items":{"$ref":"#/components/schemas/MemoryMessage"}}},"required":["kind","messages"]},"MemoryConfig":{"description":"Conversation memory configuration","oneOf":[{"$ref":"#/components/schemas/MemoryOff"},{"$ref":"#/components/schemas/MemoryAuto"},{"$ref":"#/components/schemas/MemoryManual"}],"discriminator":{"propertyName":"kind","mapping":{"off":"#/components/schemas/MemoryOff","auto":"#/components/schemas/MemoryAuto","manual":"#/components/schemas/MemoryManual"}}},"StaticMemoryTransform":{"type":"object","description":"Static memory configuration passed directly to the AI agent","properties":{"value":{"$ref":"#/components/schemas/MemoryConfig"},"type":{"type":"string","enum":["static"]}},"required":["type","value"]},"MemoryTransform":{"description":"Memory configuration - can be static (MemoryConfig), JavaScript expression, or AI-determined","oneOf":[{"$ref":"#/components/schemas/StaticMemoryTransform"},{"$ref":"#/components/schemas/JavascriptTransform"},{"$ref":"#/components/schemas/AiTransform"}],"discriminator":{"propertyName":"type","mapping":{"static":"#/components/schemas/StaticMemoryTransform","javascript":"#/components/schemas/JavascriptTransform","ai":"#/components/schemas/AiTransform"}}},"FlowModuleValue":{"description":"The actual implementation of a flow step. Can be a script (inline or referenced), subflow, loop, branch, or special module type","oneOf":[{"$ref":"#/components/schemas/RawScript"},{"$ref":"#/components/schemas/PathScript"},{"$ref":"#/components/schemas/PathFlow"},{"$ref":"#/components/schemas/ForloopFlow"},{"$ref":"#/components/schemas/WhileloopFlow"},{"$ref":"#/components/schemas/BranchOne"},{"$ref":"#/components/schemas/BranchAll"},{"$ref":"#/components/schemas/Identity"},{"$ref":"#/components/schemas/AiAgent"}],"discriminator":{"propertyName":"type","mapping":{"rawscript":"#/components/schemas/RawScript","script":"#/components/schemas/PathScript","flow":"#/components/schemas/PathFlow","forloopflow":"#/components/schemas/ForloopFlow","whileloopflow":"#/components/schemas/WhileloopFlow","branchone":"#/components/schemas/BranchOne","branchall":"#/components/schemas/BranchAll","identity":"#/components/schemas/Identity","aiagent":"#/components/schemas/AiAgent"}}},"RawScript":{"type":"object","description":"Inline script with code defined directly in the flow. Use 'bun' as default language if unspecified. The script receives arguments from input_transforms","properties":{"input_transforms":{"type":"object","description":"Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}},"content":{"type":"string","description":"The script source code. Should export a 'main' function"},"language":{"type":"string","description":"Programming language for this script","enum":["deno","bun","bunnative","python3","go","bash","powershell","postgresql","mysql","bigquery","snowflake","mssql","oracledb","graphql","nativets","php","rust","ansible","csharp","nu","java","ruby","rlang","duckdb"]},"path":{"type":"string","description":"Optional path for saving this script"},"lock":{"type":"string","description":"Lock file content for dependencies"},"type":{"type":"string","enum":["rawscript"]},"tag":{"type":"string","description":"Worker group tag for execution routing"},"concurrent_limit":{"type":"number","description":"Maximum concurrent executions of this script"},"concurrency_time_window_s":{"type":"number","description":"Time window for concurrent_limit"},"custom_concurrency_key":{"type":"string","description":"Custom key for grouping concurrent executions"},"is_trigger":{"type":"boolean","description":"If true, this script is a trigger that can start the flow"},"assets":{"type":"array","description":"External resources this script accesses (S3 objects, resources, etc.)","items":{"type":"object","required":["path","kind"],"properties":{"path":{"type":"string","description":"Path to the asset"},"kind":{"type":"string","description":"Type of asset","enum":["s3object","resource","ducklake","datatable","volume","dbt"]},"access_type":{"type":"string","nullable":true,"description":"Access level for this asset","enum":["r","w","rw"]},"alt_access_type":{"type":"string","nullable":true,"description":"Alternative access level","enum":["r","w","rw"]}}}}},"required":["type","content","language","input_transforms"]},"PathScript":{"type":"object","description":"Reference to an existing script by path. Use this when calling a previously saved script instead of writing inline code","properties":{"input_transforms":{"type":"object","description":"Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}},"path":{"type":"string","description":"Path to the script in the workspace (e.g., 'f/scripts/send_email')"},"hash":{"type":"string","description":"Optional specific version hash of the script to use"},"type":{"type":"string","enum":["script"]},"tag_override":{"type":"string","description":"Override the script's default worker group tag"},"is_trigger":{"type":"boolean","description":"If true, this script is a trigger that can start the flow"}},"required":["type","path","input_transforms"]},"PathFlow":{"type":"object","description":"Reference to an existing flow by path. Use this to call another flow as a subflow","properties":{"input_transforms":{"type":"object","description":"Map of parameter names to their values (static or JavaScript expressions). These become the subflow's input arguments","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}},"path":{"type":"string","description":"Path to the flow in the workspace (e.g., 'f/flows/process_user')"},"type":{"type":"string","enum":["flow"]}},"required":["type","path","input_transforms"]},"ForloopFlow":{"type":"object","description":"Executes nested modules in a loop over an iterator. Inside the loop, use 'flow_input.iter.value' to access the current iteration value, and 'flow_input.iter.index' for the index. Supports parallel execution for better performance on I/O-bound operations","properties":{"modules":{"type":"array","description":"Steps to execute for each iteration. These can reference the iteration value via 'flow_input.iter.value'","items":{"$ref":"#/components/schemas/FlowModule"}},"iterator":{"description":"JavaScript expression that returns an array to iterate over. Can reference 'results.step_id' or 'flow_input'","$ref":"#/components/schemas/InputTransform"},"skip_failures":{"type":"boolean","description":"If true, iteration failures don't stop the loop. Failed iterations return null"},"type":{"type":"string","enum":["forloopflow"]},"parallel":{"type":"boolean","description":"If true, iterations run concurrently (faster for I/O-bound operations). Use with parallelism to control concurrency"},"parallelism":{"description":"Maximum number of concurrent iterations when parallel=true. Limits resource usage. Can be static number or expression","$ref":"#/components/schemas/InputTransform"},"squash":{"type":"boolean"}},"required":["modules","iterator","skip_failures","type"]},"WhileloopFlow":{"type":"object","description":"Executes nested modules repeatedly until stopped. The implicit iterator is the iteration counter, so 'flow_input.iter.value' equals 'flow_input.iter.index' (0, 1, 2, ...) and never carries state. To carry state across iterations, a step reads its own previous-iteration result via 'results.<its_own_id>' with a first-iteration fallback - the loop's stop_after_if must then be on that inner step (a plain single-step body with stop_after_if on the loop module does not resolve 'results' across iterations and never terminates); plain counters can instead be derived from 'flow_input.iter.index', which works in every configuration. stop_after_if is evaluated after each iteration - on the loop module 'result' is the last iteration's result","properties":{"modules":{"type":"array","description":"Steps to execute in each iteration","items":{"$ref":"#/components/schemas/FlowModule"}},"skip_failures":{"type":"boolean","description":"If true, iteration failures don't stop the loop. Failed iterations return null"},"type":{"type":"string","enum":["whileloopflow"]},"parallel":{"type":"boolean","description":"If true, iterations run concurrently (use with caution in while loops)"},"parallelism":{"description":"Maximum number of concurrent iterations when parallel=true","$ref":"#/components/schemas/InputTransform"},"squash":{"type":"boolean"}},"required":["modules","skip_failures","type"]},"BranchOne":{"type":"object","description":"Conditional branching where only the first matching branch executes. Branches are evaluated in order, and the first one with a true expression runs. If no branches match, the default branch executes","properties":{"branches":{"type":"array","description":"Array of branches to evaluate in order. The first branch with expr evaluating to true executes","items":{"type":"object","properties":{"summary":{"type":"string","description":"Short description of this branch condition"},"expr":{"type":"string","description":"JavaScript expression that returns boolean. Can use 'results.step_id' or 'flow_input'. First true expr wins"},"modules":{"type":"array","description":"Steps to execute if this branch's expr is true","items":{"$ref":"#/components/schemas/FlowModule"}}},"required":["modules","expr"]}},"default":{"type":"array","description":"Steps to execute if no branch expressions match","items":{"$ref":"#/components/schemas/FlowModule"}},"type":{"type":"string","enum":["branchone"]}},"required":["branches","default","type"]},"BranchAll":{"type":"object","description":"Parallel branching where all branches execute simultaneously. Unlike BranchOne, all branches run regardless of conditions. Useful for executing independent tasks concurrently","properties":{"branches":{"type":"array","description":"Array of branches that all execute (either in parallel or sequentially)","items":{"type":"object","properties":{"summary":{"type":"string","description":"Short description of this branch's purpose"},"skip_failure":{"type":"boolean","description":"If true, failure in this branch doesn't fail the entire flow"},"modules":{"type":"array","description":"Steps to execute in this branch","items":{"$ref":"#/components/schemas/FlowModule"}}},"required":["modules"]}},"type":{"type":"string","enum":["branchall"]},"parallel":{"type":"boolean","description":"If true, all branches execute concurrently. If false, they execute sequentially"}},"required":["branches","type"]},"AgentTool":{"type":"object","description":"A tool available to an AI agent. Can be a flow module or an external MCP (Model Context Protocol) tool","properties":{"id":{"type":"string","description":"Unique identifier for this tool. Cannot contain spaces - use underscores instead (e.g., 'get_user_data' not 'get user data')"},"summary":{"type":"string","description":"The name the AI agent calls this tool by, not a human label. On a flowmodule tool it must match ^[a-zA-Z0-9_]+$ - letters, numbers and underscores only (e.g. 'search_documentation', not 'Search documentation') - and always be set; on an mcp or websearch tool it is a plain label. Put the human-readable explanation in 'description'."},"description":{"type":"string","description":"Free-text description of the tool given to the AI to decide when and how to call it. Overrides the description auto-derived from the underlying script."},"value":{"$ref":"#/components/schemas/ToolValue"}},"required":["id","value"]},"ToolValue":{"description":"The implementation of a tool. Can be a flow module (script/flow) or an MCP tool reference","oneOf":[{"$ref":"#/components/schemas/FlowModuleTool"},{"$ref":"#/components/schemas/McpToolValue"},{"$ref":"#/components/schemas/WebsearchToolValue"}],"discriminator":{"propertyName":"tool_type","mapping":{"flowmodule":"#/components/schemas/FlowModuleTool","mcp":"#/components/schemas/McpToolValue","websearch":"#/components/schemas/WebsearchToolValue"}}},"FlowModuleTool":{"description":"A tool implemented as a flow module (script, flow, etc.). The AI can call this like any other flow module","allOf":[{"type":"object","properties":{"tool_type":{"type":"string","enum":["flowmodule"]}},"required":["tool_type"]},{"$ref":"#/components/schemas/FlowModuleValue"}]},"WebsearchToolValue":{"type":"object","description":"A tool implemented as a websearch tool. The AI can call this like any other websearch tool","properties":{"tool_type":{"type":"string","enum":["websearch"]}},"required":["tool_type"]},"McpToolValue":{"type":"object","description":"Reference to an external MCP (Model Context Protocol) tool. The AI can call tools from MCP servers","properties":{"tool_type":{"type":"string","enum":["mcp"]},"resource_path":{"type":"string","description":"Path to the MCP resource/server configuration"},"include_tools":{"type":"array","description":"Whitelist of specific tools to include from this MCP server","items":{"type":"string"}},"exclude_tools":{"type":"array","description":"Blacklist of tools to exclude from this MCP server","items":{"type":"string"}}},"required":["tool_type","resource_path"]},"AiAgent":{"type":"object","description":"AI agent step that can use tools to accomplish tasks. The agent receives inputs and can call any of its configured tools to complete the task","properties":{"input_transforms":{"type":"object","description":"Input parameters for the AI agent mapped to their values","properties":{"provider":{"$ref":"#/components/schemas/ProviderTransform"},"output_type":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Output format type.\\nValid values: 'text' (default) - plain text response, 'image' - image generation\\n"},"user_message":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"The user's prompt/message to the AI agent. Supports variable interpolation with flow.input syntax."},"system_prompt":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"System instructions that guide the AI's behavior, persona, and response style. Optional."},"streaming":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Boolean. If true, stream the AI response incrementally.\\nStreaming events include: token_delta, reasoning_token_delta, tool_call, tool_call_arguments, tool_execution, tool_result\\n"},"memory":{"$ref":"#/components/schemas/MemoryTransform"},"output_schema":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"JSON Schema object defining structured output format. Used when you need the AI to return data in a specific shape.\\nSupports standard JSON Schema properties: type, properties, required, items, enum, pattern, minLength, maxLength, minimum, maximum, etc.\\nExample: { type: 'object', properties: { name: { type: 'string' }, age: { type: 'integer' } }, required: ['name'] }\\n"},"user_attachments":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Array of file references (images or PDFs) for the AI agent.\\nFormat: Array<{ bucket: string, key: string }> - S3 object references\\nExample: [{ bucket: 'my-bucket', key: 'documents/report.pdf' }]\\n"},"max_completion_tokens":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Integer. Maximum number of tokens the AI will generate in its response.\\nRange: 1 to 4,294,967,295. Typical values: 256-4096 for most use cases.\\n"},"temperature":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Float. Controls randomness/creativity of responses.\\nRange: 0.0 to 2.0 (provider-dependent)\\n- 0.0 = deterministic, focused responses\\n- 0.7 = balanced (common default)\\n- 1.0+ = more creative/random\\n"},"max_iterations":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Number. Limits how many times the agent can loop through reasoning and tool use.\\nRange: 1-1000.\\n"}},"required":["user_message"]},"tools":{"type":"array","description":"Array of tools the agent can use. The agent decides which tools to call based on the task","items":{"$ref":"#/components/schemas/AgentTool"}},"type":{"type":"string","enum":["aiagent"]},"tag":{"type":"string","description":"Worker group tag for execution routing. If not set, the AI agent step runs on the flow's tag (default \`flow\`)"},"omit_output_from_conversation":{"type":"boolean","default":false,"description":"If true, this AI agent step does not persist its assistant or tool messages to the flow conversation when chat mode is enabled."},"agent":{"type":"string","description":"Path of a reusable \`ai_agent\` resource (hybrid linking). When set, the agent brain\\nconfig (provider/model/system prompt/etc.) and tool set are resolved at runtime from\\nthat resource; the module's input_transforms then only carry the flow-local inputs\\n(user_message/user_attachments).\\n"},"tool_inputs":{"type":"object","description":"Host-local wiring for an agent's tool inputs, keyed by tool id then input key. Binds the\\nreferenced agent's tools to this flow's context (flow_input/results) without mutating the\\nshared resource; overlaid onto the tools' input_transforms at runtime \\u2014 including when\\n\`agent\` is unset, since a step forked for editing keeps these overrides until it is saved\\nback or unlinked.\\n","additionalProperties":{"type":"object","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}}},"parallel":{"type":"boolean","description":"If true, the agent can execute multiple tool calls in parallel"}},"required":["type","input_transforms"]},"Identity":{"type":"object","description":"Pass-through module that returns its input unchanged. Useful for flow structure or as a placeholder","properties":{"type":{"type":"string","enum":["identity"]},"flow":{"type":"boolean","description":"If true, marks this as a flow identity (special handling)"}},"required":["type"]},"FlowStatus":{"type":"object","properties":{"step":{"type":"integer"},"modules":{"type":"array","items":{"$ref":"#/components/schemas/FlowStatusModule"}},"user_states":{"additionalProperties":true},"preprocessor_module":{"allOf":[{"$ref":"#/components/schemas/FlowStatusModule"}]},"failure_module":{"allOf":[{"$ref":"#/components/schemas/FlowStatusModule"},{"type":"object","properties":{"parent_module":{"type":"string"}}}]},"retry":{"type":"object","properties":{"fail_count":{"type":"integer"},"failed_jobs":{"type":"array","items":{"type":"string","format":"uuid"}}}}},"required":["step","modules","failure_module"]},"FlowStatusModule":{"type":"object","properties":{"type":{"type":"string","enum":["WaitingForPriorSteps","WaitingForEvents","WaitingForExecutor","InProgress","Success","Failure"]},"id":{"type":"string"},"job":{"type":"string","format":"uuid"},"count":{"type":"integer"},"progress":{"type":"integer"},"iterator":{"type":"object","properties":{"index":{"type":"integer"},"itered":{"type":"array","items":{}},"itered_len":{"type":"integer"},"args":{}}},"flow_jobs":{"type":"array","items":{"type":"string"}},"flow_jobs_success":{"type":"array","items":{"type":"boolean"}},"flow_jobs_duration":{"type":"object","properties":{"started_at":{"type":"array","items":{"type":"string"}},"duration_ms":{"type":"array","items":{"type":"integer"}}}},"branch_chosen":{"type":"object","properties":{"type":{"type":"string","enum":["branch","default"]},"branch":{"type":"integer"}},"required":["type"]},"branchall":{"type":"object","properties":{"branch":{"type":"integer"},"len":{"type":"integer"}},"required":["branch","len"]},"approvers":{"type":"array","items":{"type":"object","properties":{"resume_id":{"type":"integer"},"approver":{"type":"string"}},"required":["resume_id","approver"]}},"failed_retries":{"type":"array","items":{"type":"string","format":"uuid"}},"skipped":{"type":"boolean"},"agent_actions":{"type":"array","items":{"type":"object","oneOf":[{"type":"object","properties":{"job_id":{"type":"string","format":"uuid"},"function_name":{"type":"string"},"type":{"type":"string","enum":["tool_call"]},"module_id":{"type":"string"}},"required":["job_id","function_name","type","module_id"]},{"type":"object","properties":{"call_id":{"type":"string","format":"uuid"},"function_name":{"type":"string"},"resource_path":{"type":"string"},"type":{"type":"string","enum":["mcp_tool_call"]},"arguments":{"type":"object"}},"required":["call_id","function_name","resource_path","type"]},{"type":"object","properties":{"type":{"type":"string","enum":["web_search"]}},"required":["type"]},{"type":"object","properties":{"type":{"type":"string","enum":["message"]}},"required":["content","type"]}]}},"agent_actions_success":{"type":"array","items":{"type":"boolean"}}},"required":["type"]}}`,
84191
+ {"OpenFlow":{"type":"object","description":"Top-level flow definition containing metadata, configuration, and the flow structure","properties":{"summary":{"type":"string","description":"Short description of what this flow does"},"description":{"type":"string","description":"Detailed documentation for this flow"},"value":{"$ref":"#/components/schemas/FlowValue"},"schema":{"type":"object","description":"JSON Schema for flow inputs. Use this to define input parameters, their types, defaults, and validation. For resource inputs, set type to 'object' and format to 'resource-<type>' (e.g., 'resource-stripe')"},"on_behalf_of_email":{"type":"string","description":"Address of the account the flow runs on behalf of. Derived from on_behalf_of on read; accepted on write, where it is resolved to the account it names."},"on_behalf_of":{"type":"string","description":"The flow runs with the permissions of this identity: u/{username}, g/{group}, or a bare email when the username is itself email-shaped. The only stored half of the identity; on_behalf_of_email is derived from it. Omit it when writing and it is resolved from that address instead."}},"required":["summary","value"]},"FlowValue":{"type":"object","description":"The flow structure containing modules and optional preprocessor/failure handlers","properties":{"modules":{"type":"array","description":"Array of steps that execute in sequence. Each step can be a script, subflow, loop, or branch","items":{"$ref":"#/components/schemas/FlowModule"}},"failure_module":{"description":"Special module that executes when the flow fails. Receives error object with message, name, stack, and step_id. Must have id 'failure'. Only supports script/rawscript types","$ref":"#/components/schemas/FlowModule"},"preprocessor_module":{"description":"Special module that runs before the first step on external triggers. Must have id 'preprocessor'. Only supports script/rawscript types. Cannot reference other step results","$ref":"#/components/schemas/FlowModule"},"same_worker":{"type":"boolean","description":"If true, all steps run on the same worker for better performance"},"preserve_step_tags":{"type":"boolean","description":"If true and the flow runs on a custom worker tag, steps that declare their own non-empty tag run on it instead of inheriting the flow tag. Steps without their own tag still inherit the flow tag."},"concurrent_limit":{"type":"number","description":"Maximum number of concurrent executions of this flow"},"concurrency_key":{"type":"string","description":"Expression to group concurrent executions (e.g., by user ID)"},"concurrency_time_window_s":{"type":"number","description":"Time window in seconds for concurrent_limit"},"debounce_delay_s":{"type":"integer","description":"Delay in seconds to debounce flow executions"},"debounce_key":{"type":"string","description":"Expression to group debounced executions"},"debounce_args_to_accumulate":{"type":"array","description":"Arguments to accumulate across debounced executions","items":{"type":"string"}},"max_total_debouncing_time":{"type":"integer","description":"Maximum total time in seconds that a job can be debounced"},"max_total_debounces_amount":{"type":"integer","description":"Maximum number of times a job can be debounced"},"skip_expr":{"type":"string","description":"JavaScript expression to conditionally skip the entire flow"},"cache_ttl":{"type":"number","description":"Cache duration in seconds for flow results"},"cache_ignore_s3_path":{"type":"boolean"},"delete_after_secs":{"type":"integer","description":"If set, delete the flow job's args, result and logs after this many seconds following job completion"},"flow_env":{"type":"object","description":"Environment variables available to all steps. Values can be strings, JSON values, or special references: '$var:path' (workspace variable) or '$res:path' (resource).","additionalProperties":{}},"priority":{"type":"number","description":"Execution priority (higher numbers run first)"},"early_return":{"type":"string","description":"JavaScript expression to return early from the flow"},"chat_input_enabled":{"type":"boolean","description":"Whether this flow accepts chat-style input"},"notes":{"type":"array","description":"Sticky notes attached to the flow","items":{"$ref":"#/components/schemas/FlowNote"}},"groups":{"type":"array","description":"Semantic groups of modules for organizational purposes","items":{"$ref":"#/components/schemas/FlowGroup"}}},"required":["modules"]},"Retry":{"type":"object","description":"Retry configuration for failed module executions","properties":{"constant":{"type":"object","description":"Retry with constant delay between attempts","properties":{"attempts":{"type":"integer","description":"Number of retry attempts"},"seconds":{"type":"integer","description":"Seconds to wait between retries"}}},"exponential":{"type":"object","description":"Retry with exponential backoff (delay doubles each time)","properties":{"attempts":{"type":"integer","description":"Number of retry attempts"},"multiplier":{"type":"integer","description":"Multiplier for exponential backoff"},"seconds":{"type":"integer","minimum":1,"description":"Initial delay in seconds"},"random_factor":{"type":"integer","minimum":0,"maximum":100,"description":"Random jitter percentage (0-100) to avoid thundering herd"}}},"retry_if":{"$ref":"#/components/schemas/RetryIf"}}},"FlowNote":{"type":"object","description":"A sticky note attached to a flow for documentation and annotation","properties":{"id":{"type":"string","description":"Unique identifier for the note"},"text":{"type":"string","description":"Content of the note"},"position":{"type":"object","description":"Position of the note in the flow editor","properties":{"x":{"type":"number","description":"X coordinate"},"y":{"type":"number","description":"Y coordinate"}},"required":["x","y"]},"size":{"type":"object","description":"Size of the note in the flow editor","properties":{"width":{"type":"number","description":"Width in pixels"},"height":{"type":"number","description":"Height in pixels"}},"required":["width","height"]},"color":{"type":"string","description":"Color of the note (e.g., \\"yellow\\", \\"#ffff00\\")"},"type":{"type":"string","enum":["free","group"],"description":"Type of note - 'free' for standalone notes, 'group' for notes that group other nodes"},"locked":{"type":"boolean","default":false,"description":"Whether the note is locked and cannot be edited or moved"},"contained_node_ids":{"type":"array","items":{"type":"string"},"description":"For group notes, the IDs of nodes contained within this group"}},"required":["id","text","color","type"]},"FlowGroup":{"type":"object","description":"A semantic group of flow modules for organizational purposes. Does not affect execution \\u2014 modules remain in their original position in the flow. Groups provide naming and collapsibility in the editor. Members are computed dynamically from all nodes on paths between start_id and end_id.","properties":{"summary":{"type":"string","description":"Display name for this group"},"note":{"type":"string","description":"Markdown note shown below the group header"},"autocollapse":{"type":"boolean","default":false,"description":"If true, this group is collapsed by default in the flow editor. UI hint only."},"start_id":{"type":"string","description":"ID of the first flow module in this group (topological entry point)"},"end_id":{"type":"string","description":"ID of the last flow module in this group (topological exit point)"},"color":{"type":"string","description":"Color for the group in the flow editor"}},"required":["start_id","end_id"]},"RetryIf":{"type":"object","description":"Conditional retry based on error or result","properties":{"expr":{"type":"string","description":"JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables"}},"required":["expr"]},"StopAfterIf":{"type":"object","description":"Early termination condition for a module","properties":{"skip_if_stopped":{"type":"boolean","description":"If true, following steps are skipped when this condition triggers"},"expr":{"type":"string","description":"JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"},"error_message":{"type":"string","nullable":true,"description":"Custom error message when stopping with an error. Mutually exclusive with skip_if_stopped. If set to a non-empty string, the flow stops with this error. If empty string, a default error message is used. If null or omitted, no error is raised."},"error_include_result":{"type":"boolean","description":"When stopping with an error (error_message set), embed the stopping step's own result inside the raised error object (as error.result) instead of discarding it. The top-level result stays { error }. Defaults to false."}},"required":["expr"]},"FlowModule":{"type":"object","description":"A single step in a flow. Can be a script, subflow, loop, or branch","properties":{"id":{"type":"string","description":"Unique identifier for this step. Used to reference results via 'results.step_id'. Must be a valid identifier (alphanumeric, underscore, hyphen)"},"value":{"$ref":"#/components/schemas/FlowModuleValue"},"stop_after_if":{"description":"Early termination condition evaluated after this step completes","$ref":"#/components/schemas/StopAfterIf"},"stop_after_all_iters_if":{"description":"For loops only - early termination condition evaluated after all iterations complete","$ref":"#/components/schemas/StopAfterIf"},"skip_if":{"type":"object","description":"Conditionally skip this step based on previous results or flow inputs","properties":{"expr":{"type":"string","description":"JavaScript expression that returns true to skip. Can use 'flow_input' or 'results.<step_id>'"}},"required":["expr"]},"sleep":{"description":"Delay before executing this step (in seconds or as expression)","$ref":"#/components/schemas/InputTransform"},"cache_ttl":{"type":"number","description":"Cache duration in seconds for this step's results"},"cache_ignore_s3_path":{"type":"boolean"},"timeout":{"description":"Maximum execution time in seconds (static value or expression)","$ref":"#/components/schemas/InputTransform"},"delete_after_secs":{"type":"integer","description":"If set, delete the step's args, result and logs after this many seconds following job completion"},"summary":{"type":"string","description":"Short description of what this step does"},"mock":{"type":"object","description":"Mock configuration for testing without executing the actual step","properties":{"enabled":{"type":"boolean","description":"If true, return mock value instead of executing"},"return_value":{"description":"Value to return when mocked"}}},"suspend":{"type":"object","description":"Configuration for approval/resume steps that wait for user input","properties":{"required_events":{"type":"integer","description":"Number of approvals required before continuing"},"timeout":{"type":"integer","description":"Timeout in seconds before auto-continuing or canceling"},"resume_form":{"type":"object","description":"Form schema for collecting input when resuming","properties":{"schema":{"type":"object","description":"JSON Schema for the resume form"}}},"user_auth_required":{"type":"boolean","description":"If true, only authenticated users can approve"},"user_groups_required":{"description":"Expression or list of groups that can approve","$ref":"#/components/schemas/InputTransform"},"self_approval_disabled":{"type":"boolean","description":"If true, the user who started the flow cannot approve"},"hide_cancel":{"type":"boolean","description":"If true, hide the cancel button on the approval form"},"continue_on_disapprove_timeout":{"type":"boolean","description":"If true, continue flow on timeout instead of canceling"},"skin":{"type":"string","enum":["detailed","minimal"],"description":"How the approval request is presented, on the approval page and in Slack/Teams approval messages. 'detailed' (used when unset) shows the flow details (arguments, graph, approvers); 'minimal' shows only the request: the step description, form and approve/reject actions"}}},"priority":{"type":"number","description":"Execution priority for this step (higher numbers run first)"},"continue_on_error":{"type":"boolean","description":"If true, flow continues even if this step fails"},"retry":{"description":"Retry configuration if this step fails","$ref":"#/components/schemas/Retry"},"debouncing":{"description":"Debounce configuration for this step (EE only)","type":"object","properties":{"debounce_delay_s":{"type":"integer","description":"Delay in seconds to debounce this step's executions across flow runs"},"debounce_key":{"type":"string","description":"Expression to group debounced executions. Supports $workspace and $args[name]. Default: $workspace/flow/<flow_path>-<step_id>"},"debounce_args_to_accumulate":{"type":"array","description":"Array-type arguments to accumulate across debounced executions","items":{"type":"string"}},"max_total_debouncing_time":{"type":"integer","description":"Maximum total time in seconds before forced execution"},"max_total_debounces_amount":{"type":"integer","description":"Maximum number of debounces before forced execution"}}}},"required":["value","id"]},"InputTransform":{"description":"Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs","oneOf":[{"$ref":"#/components/schemas/StaticTransform"},{"$ref":"#/components/schemas/JavascriptTransform"},{"$ref":"#/components/schemas/AiTransform"}],"discriminator":{"propertyName":"type","mapping":{"static":"#/components/schemas/StaticTransform","javascript":"#/components/schemas/JavascriptTransform","ai":"#/components/schemas/AiTransform"}}},"StaticTransform":{"type":"object","description":"Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'","properties":{"value":{"description":"The static value. For resources, use format '$res:path/to/resource'"},"type":{"type":"string","enum":["static"]}},"required":["type"]},"JavascriptTransform":{"type":"object","description":"JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')","properties":{"expr":{"type":"string","description":"JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"},"type":{"type":"string","enum":["javascript"]}},"required":["expr","type"]},"AiTransform":{"type":"object","description":"Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.","properties":{"type":{"type":"string","enum":["ai"]}},"required":["type"]},"AIProviderKind":{"type":"string","description":"Supported AI provider types","enum":["openai","azure_openai","azure_foundry","anthropic","mistral","deepseek","googleai","groq","openrouter","togetherai","customai","aws_bedrock"]},"ProviderConfig":{"type":"object","description":"Complete AI provider configuration with resource reference and model selection","properties":{"kind":{"$ref":"#/components/schemas/AIProviderKind"},"resource":{"type":"string","description":"Resource reference in format '$res:{resource_path}' pointing to provider credentials"},"model":{"type":"string","description":"Model identifier (e.g., 'gpt-4', 'claude-3-opus-20240229', 'gemini-pro')"},"reasoning_effort":{"type":"string","description":"Provider-native reasoning effort token (e.g. 'low', 'high', 'none') for models that support extended thinking. Optional; unset leaves the provider default."}},"required":["kind","resource","model"]},"StaticProviderTransform":{"type":"object","description":"Static provider configuration passed directly to the AI agent","properties":{"value":{"$ref":"#/components/schemas/ProviderConfig"},"type":{"type":"string","enum":["static"]}},"required":["type","value"]},"ProviderTransform":{"description":"Provider configuration - can be static (ProviderConfig), JavaScript expression, or AI-determined","oneOf":[{"$ref":"#/components/schemas/StaticProviderTransform"},{"$ref":"#/components/schemas/JavascriptTransform"},{"$ref":"#/components/schemas/AiTransform"}],"discriminator":{"propertyName":"type","mapping":{"static":"#/components/schemas/StaticProviderTransform","javascript":"#/components/schemas/JavascriptTransform","ai":"#/components/schemas/AiTransform"}}},"MemoryOff":{"type":"object","description":"No conversation memory/context","properties":{"kind":{"type":"string","enum":["off"]}},"required":["kind"]},"MemoryAuto":{"type":"object","description":"Automatic context management","properties":{"kind":{"type":"string","enum":["auto"]},"context_length":{"type":"integer","description":"Maximum number of messages to retain in context"},"memory_id":{"type":"string","description":"Identifier for persistent memory across agent invocations"}},"required":["kind"]},"MemoryMessage":{"type":"object","description":"A single message in conversation history","properties":{"role":{"type":"string","enum":["user","assistant","system"]},"content":{"type":"string"}},"required":["role","content"]},"MemoryManual":{"type":"object","description":"Explicit message history","properties":{"kind":{"type":"string","enum":["manual"]},"messages":{"type":"array","items":{"$ref":"#/components/schemas/MemoryMessage"}}},"required":["kind","messages"]},"MemoryConfig":{"description":"Conversation memory configuration","oneOf":[{"$ref":"#/components/schemas/MemoryOff"},{"$ref":"#/components/schemas/MemoryAuto"},{"$ref":"#/components/schemas/MemoryManual"}],"discriminator":{"propertyName":"kind","mapping":{"off":"#/components/schemas/MemoryOff","auto":"#/components/schemas/MemoryAuto","manual":"#/components/schemas/MemoryManual"}}},"StaticMemoryTransform":{"type":"object","description":"Static memory configuration passed directly to the AI agent","properties":{"value":{"$ref":"#/components/schemas/MemoryConfig"},"type":{"type":"string","enum":["static"]}},"required":["type","value"]},"MemoryTransform":{"description":"Memory configuration - can be static (MemoryConfig), JavaScript expression, or AI-determined","oneOf":[{"$ref":"#/components/schemas/StaticMemoryTransform"},{"$ref":"#/components/schemas/JavascriptTransform"},{"$ref":"#/components/schemas/AiTransform"}],"discriminator":{"propertyName":"type","mapping":{"static":"#/components/schemas/StaticMemoryTransform","javascript":"#/components/schemas/JavascriptTransform","ai":"#/components/schemas/AiTransform"}}},"FlowModuleValue":{"description":"The actual implementation of a flow step. Can be a script (inline or referenced), subflow, loop, branch, or special module type","oneOf":[{"$ref":"#/components/schemas/RawScript"},{"$ref":"#/components/schemas/PathScript"},{"$ref":"#/components/schemas/PathFlow"},{"$ref":"#/components/schemas/ForloopFlow"},{"$ref":"#/components/schemas/WhileloopFlow"},{"$ref":"#/components/schemas/BranchOne"},{"$ref":"#/components/schemas/BranchAll"},{"$ref":"#/components/schemas/Identity"},{"$ref":"#/components/schemas/AiAgent"}],"discriminator":{"propertyName":"type","mapping":{"rawscript":"#/components/schemas/RawScript","script":"#/components/schemas/PathScript","flow":"#/components/schemas/PathFlow","forloopflow":"#/components/schemas/ForloopFlow","whileloopflow":"#/components/schemas/WhileloopFlow","branchone":"#/components/schemas/BranchOne","branchall":"#/components/schemas/BranchAll","identity":"#/components/schemas/Identity","aiagent":"#/components/schemas/AiAgent"}}},"RawScript":{"type":"object","description":"Inline script with code defined directly in the flow. Use 'bun' as default language if unspecified. The script receives arguments from input_transforms","properties":{"input_transforms":{"type":"object","description":"Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}},"content":{"type":"string","description":"The script source code. Should export a 'main' function"},"language":{"type":"string","description":"Programming language for this script","enum":["deno","bun","bunnative","python3","go","bash","powershell","postgresql","mysql","bigquery","snowflake","mssql","oracledb","graphql","nativets","php","rust","ansible","csharp","nu","java","ruby","rlang","duckdb"]},"path":{"type":"string","description":"Optional path for saving this script"},"lock":{"type":"string","description":"Lock file content for dependencies"},"type":{"type":"string","enum":["rawscript"]},"tag":{"type":"string","description":"Worker group tag for execution routing"},"concurrent_limit":{"type":"number","description":"Maximum concurrent executions of this script"},"concurrency_time_window_s":{"type":"number","description":"Time window for concurrent_limit"},"custom_concurrency_key":{"type":"string","description":"Custom key for grouping concurrent executions"},"is_trigger":{"type":"boolean","description":"If true, this script is a trigger that can start the flow"},"assets":{"type":"array","description":"External resources this script accesses (S3 objects, resources, etc.)","items":{"type":"object","required":["path","kind"],"properties":{"path":{"type":"string","description":"Path to the asset"},"kind":{"type":"string","description":"Type of asset","enum":["s3object","resource","ducklake","datatable","volume","dbt"]},"access_type":{"type":"string","nullable":true,"description":"Access level for this asset","enum":["r","w","rw"]},"alt_access_type":{"type":"string","nullable":true,"description":"Alternative access level","enum":["r","w","rw"]}}}}},"required":["type","content","language","input_transforms"]},"PathScript":{"type":"object","description":"Reference to an existing script by path. Use this when calling a previously saved script instead of writing inline code","properties":{"input_transforms":{"type":"object","description":"Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}},"path":{"type":"string","description":"Path to the script in the workspace (e.g., 'f/scripts/send_email')"},"hash":{"type":"string","description":"Optional specific version hash of the script to use"},"type":{"type":"string","enum":["script"]},"tag_override":{"type":"string","description":"Override the script's default worker group tag"},"is_trigger":{"type":"boolean","description":"If true, this script is a trigger that can start the flow"}},"required":["type","path","input_transforms"]},"PathFlow":{"type":"object","description":"Reference to an existing flow by path. Use this to call another flow as a subflow","properties":{"input_transforms":{"type":"object","description":"Map of parameter names to their values (static or JavaScript expressions). These become the subflow's input arguments","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}},"path":{"type":"string","description":"Path to the flow in the workspace (e.g., 'f/flows/process_user')"},"type":{"type":"string","enum":["flow"]}},"required":["type","path","input_transforms"]},"ForloopFlow":{"type":"object","description":"Executes nested modules in a loop over an iterator. Inside the loop, use 'flow_input.iter.value' to access the current iteration value, and 'flow_input.iter.index' for the index. Supports parallel execution for better performance on I/O-bound operations","properties":{"modules":{"type":"array","description":"Steps to execute for each iteration. These can reference the iteration value via 'flow_input.iter.value'","items":{"$ref":"#/components/schemas/FlowModule"}},"iterator":{"description":"JavaScript expression that returns an array to iterate over. Can reference 'results.step_id' or 'flow_input'","$ref":"#/components/schemas/InputTransform"},"skip_failures":{"type":"boolean","description":"If true, iteration failures don't stop the loop. Failed iterations return null"},"type":{"type":"string","enum":["forloopflow"]},"parallel":{"type":"boolean","description":"If true, iterations run concurrently (faster for I/O-bound operations). Use with parallelism to control concurrency"},"parallelism":{"description":"Maximum number of concurrent iterations when parallel=true. Limits resource usage. Can be static number or expression","$ref":"#/components/schemas/InputTransform"},"squash":{"type":"boolean"}},"required":["modules","iterator","skip_failures","type"]},"WhileloopFlow":{"type":"object","description":"Executes nested modules repeatedly until stopped. The implicit iterator is the iteration counter, so 'flow_input.iter.value' equals 'flow_input.iter.index' (0, 1, 2, ...) and never carries state. To carry state across iterations, a step reads its own previous-iteration result via 'results.<its_own_id>' with a first-iteration fallback - the loop's stop_after_if must then be on that inner step (a plain single-step body with stop_after_if on the loop module does not resolve 'results' across iterations and never terminates); plain counters can instead be derived from 'flow_input.iter.index', which works in every configuration. stop_after_if is evaluated after each iteration - on the loop module 'result' is the last iteration's result","properties":{"modules":{"type":"array","description":"Steps to execute in each iteration","items":{"$ref":"#/components/schemas/FlowModule"}},"skip_failures":{"type":"boolean","description":"If true, iteration failures don't stop the loop. Failed iterations return null"},"type":{"type":"string","enum":["whileloopflow"]},"parallel":{"type":"boolean","description":"If true, iterations run concurrently (use with caution in while loops)"},"parallelism":{"description":"Maximum number of concurrent iterations when parallel=true","$ref":"#/components/schemas/InputTransform"},"squash":{"type":"boolean"}},"required":["modules","skip_failures","type"]},"BranchOne":{"type":"object","description":"Conditional branching where only the first matching branch executes. Branches are evaluated in order, and the first one with a true expression runs. If no branches match, the default branch executes","properties":{"branches":{"type":"array","description":"Array of branches to evaluate in order. The first branch with expr evaluating to true executes","items":{"type":"object","properties":{"summary":{"type":"string","description":"Short description of this branch condition"},"expr":{"type":"string","description":"JavaScript expression that returns boolean. Can use 'results.step_id' or 'flow_input'. First true expr wins"},"modules":{"type":"array","description":"Steps to execute if this branch's expr is true","items":{"$ref":"#/components/schemas/FlowModule"}}},"required":["modules","expr"]}},"default":{"type":"array","description":"Steps to execute if no branch expressions match","items":{"$ref":"#/components/schemas/FlowModule"}},"type":{"type":"string","enum":["branchone"]}},"required":["branches","default","type"]},"BranchAll":{"type":"object","description":"Parallel branching where all branches execute simultaneously. Unlike BranchOne, all branches run regardless of conditions. Useful for executing independent tasks concurrently","properties":{"branches":{"type":"array","description":"Array of branches that all execute (either in parallel or sequentially)","items":{"type":"object","properties":{"summary":{"type":"string","description":"Short description of this branch's purpose"},"skip_failure":{"type":"boolean","description":"If true, failure in this branch doesn't fail the entire flow"},"modules":{"type":"array","description":"Steps to execute in this branch","items":{"$ref":"#/components/schemas/FlowModule"}}},"required":["modules"]}},"type":{"type":"string","enum":["branchall"]},"parallel":{"type":"boolean","description":"If true, all branches execute concurrently. If false, they execute sequentially"}},"required":["branches","type"]},"AgentTool":{"type":"object","description":"A tool available to an AI agent. Can be a flow module or an external MCP (Model Context Protocol) tool","properties":{"id":{"type":"string","description":"Unique identifier for this tool. Cannot contain spaces - use underscores instead (e.g., 'get_user_data' not 'get user data')"},"summary":{"type":"string","description":"The name the AI agent calls this tool by, not a human label. On a flowmodule tool it must match ^[a-zA-Z0-9_]+$ - letters, numbers and underscores only (e.g. 'search_documentation', not 'Search documentation') - and always be set; on an mcp or websearch tool it is a plain label. Put the human-readable explanation in 'description'."},"description":{"type":"string","description":"Free-text description of the tool given to the AI to decide when and how to call it. Overrides the description auto-derived from the underlying script."},"value":{"$ref":"#/components/schemas/ToolValue"}},"required":["id","value"]},"ToolValue":{"description":"The implementation of a tool. Can be a flow module (script/flow) or an MCP tool reference","oneOf":[{"$ref":"#/components/schemas/FlowModuleTool"},{"$ref":"#/components/schemas/McpToolValue"},{"$ref":"#/components/schemas/WebsearchToolValue"}],"discriminator":{"propertyName":"tool_type","mapping":{"flowmodule":"#/components/schemas/FlowModuleTool","mcp":"#/components/schemas/McpToolValue","websearch":"#/components/schemas/WebsearchToolValue"}}},"FlowModuleTool":{"description":"A tool implemented as a flow module (script, flow, etc.). The AI can call this like any other flow module","allOf":[{"type":"object","properties":{"tool_type":{"type":"string","enum":["flowmodule"]}},"required":["tool_type"]},{"$ref":"#/components/schemas/FlowModuleValue"}]},"WebsearchToolValue":{"type":"object","description":"A tool implemented as a websearch tool. The AI can call this like any other websearch tool","properties":{"tool_type":{"type":"string","enum":["websearch"]}},"required":["tool_type"]},"McpToolValue":{"type":"object","description":"Reference to an external MCP (Model Context Protocol) tool. The AI can call tools from MCP servers","properties":{"tool_type":{"type":"string","enum":["mcp"]},"resource_path":{"type":"string","description":"Path to the MCP resource/server configuration"},"include_tools":{"type":"array","description":"Whitelist of specific tools to include from this MCP server","items":{"type":"string"}},"exclude_tools":{"type":"array","description":"Blacklist of tools to exclude from this MCP server","items":{"type":"string"}}},"required":["tool_type","resource_path"]},"AiAgent":{"type":"object","description":"AI agent step that can use tools to accomplish tasks. The agent receives inputs and can call any of its configured tools to complete the task","properties":{"input_transforms":{"type":"object","description":"Input parameters for the AI agent mapped to their values","properties":{"provider":{"$ref":"#/components/schemas/ProviderTransform"},"output_type":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Output format type.\\nValid values: 'text' (default) - plain text response, 'image' - image generation\\n"},"user_message":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"The user's prompt/message to the AI agent. Supports variable interpolation with flow.input syntax."},"system_prompt":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"System instructions that guide the AI's behavior, persona, and response style. Optional."},"streaming":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Boolean. If true, stream the AI response incrementally.\\nStreaming events include: token_delta, reasoning_token_delta, tool_call, tool_call_arguments, tool_execution, tool_result\\n"},"memory":{"$ref":"#/components/schemas/MemoryTransform"},"output_schema":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"JSON Schema object defining structured output format. Used when you need the AI to return data in a specific shape.\\nSupports standard JSON Schema properties: type, properties, required, items, enum, pattern, minLength, maxLength, minimum, maximum, etc.\\nExample: { type: 'object', properties: { name: { type: 'string' }, age: { type: 'integer' } }, required: ['name'] }\\n"},"user_attachments":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Array of file references (images or PDFs) for the AI agent.\\nFormat: Array<{ bucket: string, key: string }> - S3 object references\\nExample: [{ bucket: 'my-bucket', key: 'documents/report.pdf' }]\\n"},"enabled_tools":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Array of strings naming which of the tools configured in \`tools\` the agent may call\\nthis run. Leaving it unset carries every one of them; an empty array carries none.\\nA tool is named as the model is shown it. An entry the model is shown nothing of is\\nnamed by what identifies it instead: an MCP server by its resource path, carrying\\nevery tool it exposes (which of them stays that entry's include_tools/exclude_tools),\\nand a websearch entry by the reserved name '__wm_web_search', whatever summary it carries\\n(no tool may take that name).\\nExample: ['get_user', 'u/admin/github_mcp', '__wm_web_search']\\n"},"max_completion_tokens":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Integer. Maximum number of tokens the AI will generate in its response.\\nRange: 1 to 4,294,967,295. Typical values: 256-4096 for most use cases.\\n"},"temperature":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Float. Controls randomness/creativity of responses.\\nRange: 0.0 to 2.0 (provider-dependent)\\n- 0.0 = deterministic, focused responses\\n- 0.7 = balanced (common default)\\n- 1.0+ = more creative/random\\n"},"max_iterations":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Number. Limits how many times the agent can loop through reasoning and tool use.\\nRange: 1-1000.\\n"}},"required":["user_message"]},"tools":{"type":"array","description":"Array of tools the agent can use. The agent decides which tools to call based on the task","items":{"$ref":"#/components/schemas/AgentTool"}},"type":{"type":"string","enum":["aiagent"]},"tag":{"type":"string","description":"Worker group tag for execution routing. If not set, the AI agent step runs on the flow's tag (default \`flow\`)"},"omit_output_from_conversation":{"type":"boolean","default":false,"description":"If true, this AI agent step does not persist its assistant or tool messages to the flow conversation when chat mode is enabled."},"agent":{"type":"string","description":"Path of a reusable \`ai_agent\` resource (hybrid linking). When set, the agent brain\\nconfig (provider/model/system prompt/etc.) and tool set are resolved at runtime from\\nthat resource; the module's input_transforms then only carry the flow-local inputs\\n(user_message/user_attachments/enabled_tools).\\n"},"tool_inputs":{"type":"object","description":"Host-local wiring for an agent's tool inputs, keyed by tool id then input key. Binds the\\nreferenced agent's tools to this flow's context (flow_input/results) without mutating the\\nshared resource; overlaid onto the tools' input_transforms at runtime \\u2014 including when\\n\`agent\` is unset, since a step forked for editing keeps these overrides until it is saved\\nback or unlinked.\\n","additionalProperties":{"type":"object","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}}},"parallel":{"type":"boolean","description":"If true, the agent can execute multiple tool calls in parallel"}},"required":["type","input_transforms"]},"Identity":{"type":"object","description":"Pass-through module that returns its input unchanged. Useful for flow structure or as a placeholder","properties":{"type":{"type":"string","enum":["identity"]},"flow":{"type":"boolean","description":"If true, marks this as a flow identity (special handling)"}},"required":["type"]},"FlowStatus":{"type":"object","properties":{"step":{"type":"integer"},"modules":{"type":"array","items":{"$ref":"#/components/schemas/FlowStatusModule"}},"user_states":{"additionalProperties":true},"preprocessor_module":{"allOf":[{"$ref":"#/components/schemas/FlowStatusModule"}]},"failure_module":{"allOf":[{"$ref":"#/components/schemas/FlowStatusModule"},{"type":"object","properties":{"parent_module":{"type":"string"}}}]},"retry":{"type":"object","properties":{"fail_count":{"type":"integer"},"failed_jobs":{"type":"array","items":{"type":"string","format":"uuid"}}}}},"required":["step","modules","failure_module"]},"FlowStatusModule":{"type":"object","properties":{"type":{"type":"string","enum":["WaitingForPriorSteps","WaitingForEvents","WaitingForExecutor","InProgress","Success","Failure"]},"id":{"type":"string"},"job":{"type":"string","format":"uuid"},"count":{"type":"integer"},"progress":{"type":"integer"},"iterator":{"type":"object","properties":{"index":{"type":"integer"},"itered":{"type":"array","items":{}},"itered_len":{"type":"integer"},"args":{}}},"flow_jobs":{"type":"array","items":{"type":"string"}},"flow_jobs_success":{"type":"array","items":{"type":"boolean"}},"flow_jobs_duration":{"type":"object","properties":{"started_at":{"type":"array","items":{"type":"string"}},"duration_ms":{"type":"array","items":{"type":"integer"}}}},"branch_chosen":{"type":"object","properties":{"type":{"type":"string","enum":["branch","default"]},"branch":{"type":"integer"}},"required":["type"]},"branchall":{"type":"object","properties":{"branch":{"type":"integer"},"len":{"type":"integer"}},"required":["branch","len"]},"approvers":{"type":"array","items":{"type":"object","properties":{"resume_id":{"type":"integer"},"approver":{"type":"string"}},"required":["resume_id","approver"]}},"failed_retries":{"type":"array","items":{"type":"string","format":"uuid"}},"skipped":{"type":"boolean"},"agent_actions":{"type":"array","items":{"type":"object","oneOf":[{"type":"object","properties":{"job_id":{"type":"string","format":"uuid"},"function_name":{"type":"string"},"type":{"type":"string","enum":["tool_call"]},"module_id":{"type":"string"}},"required":["job_id","function_name","type","module_id"]},{"type":"object","properties":{"call_id":{"type":"string","format":"uuid"},"function_name":{"type":"string"},"resource_path":{"type":"string"},"type":{"type":"string","enum":["mcp_tool_call"]},"arguments":{"type":"object"}},"required":["call_id","function_name","resource_path","type"]},{"type":"object","properties":{"type":{"type":"string","enum":["web_search"]}},"required":["type"]},{"type":"object","properties":{"type":{"type":"string","enum":["message"]}},"required":["content","type"]}]}},"agent_actions_success":{"type":"array","items":{"type":"boolean"}}},"required":["type"]}}`,
84017
84192
  "raw-app": `---
84018
84193
  name: raw-app
84019
84194
  description: MUST use when creating raw apps.
@@ -84346,6 +84521,19 @@ An app can be demoed by recording a session: every interaction becomes a step ca
84346
84521
 
84347
84522
  Apply it to customer data, internal notes and anything else a viewer of the demo should not see. It costs nothing when the app is never recorded.
84348
84523
 
84524
+ ### Chat UIs over a flow in chat mode
84525
+
84526
+ A flow deployed with chat mode on is a chat backend (streaming answer, tool calls, memory, conversation history). Do not drive it through a runnable: add \`windmill-chat\` to \`package.json\` and use it directly, it detects the app's Windmill and credential.
84527
+
84528
+ \`\`\`tsx
84529
+ import { useWindmillChat } from 'windmill-chat/react'
84530
+
84531
+ const chat = useWindmillChat({ flowPath: 'f/support/assistant' })
84532
+ // chat.messages ({ role, content, pending, success, tool? }), chat.status, chat.sendMessage(text), chat.stop()
84533
+ \`\`\`
84534
+
84535
+ \`windmill-chat/ai-sdk\` gives a \`ChatTransport\` for the Vercel AI SDK's \`useChat\`, \`windmill-chat/assistant-ui\` a runtime for assistant-ui. The flow must be deployed, not a draft. A sandboxed app needs \`jobs:run\` in its frontend SDK scopes, plus \`flow_conversations:write\` for the conversation sidebar; without them the chat keeps history in the browser.
84536
+
84349
84537
  ## Backend runnables
84350
84538
 
84351
84539
  Each runnable has a unique key (used to call it from the frontend) and one of four types:
@@ -84438,8 +84626,8 @@ export async function main(user_id: string) {
84438
84626
  const users = await sql\`SELECT * FROM users WHERE active = \${true}\`.fetch();
84439
84627
 
84440
84628
  // Insert/Update
84441
- await sql\`INSERT INTO users (name, email) VALUES (\${name}, \${email})\`;
84442
- await sql\`UPDATE users SET name = \${newName} WHERE id = \${user_id}\`;
84629
+ await sql\`INSERT INTO users (name, email) VALUES (\${name}, \${email})\`.execute();
84630
+ await sql\`UPDATE users SET name = \${newName} WHERE id = \${user_id}\`.execute();
84443
84631
 
84444
84632
  return user;
84445
84633
  }
@@ -84458,8 +84646,8 @@ def main(user_id: str):
84458
84646
  users = db.query('SELECT * FROM users WHERE active = $1', True).fetch()
84459
84647
 
84460
84648
  # Insert/Update
84461
- db.query('INSERT INTO users (name, email) VALUES ($1, $2)', name, email)
84462
- db.query('UPDATE users SET name = $1 WHERE id = $2', new_name, user_id)
84649
+ db.query('INSERT INTO users (name, email) VALUES ($1, $2)', name, email).execute()
84650
+ db.query('UPDATE users SET name = $1 WHERE id = $2', new_name, user_id).execute()
84463
84651
 
84464
84652
  return user
84465
84653
  \`\`\`
@@ -84468,12 +84656,14 @@ def main(user_id: str):
84468
84656
 
84469
84657
  1. **Check existing tables** before creating new ones — reuse beats schema growth.
84470
84658
  2. **Use parameterized queries** — never concatenate user input into SQL.
84471
- 3. **Keep runnables focused** — one function per runnable; small surface area.
84472
- 4. **Use descriptive keys** — \`get_user\`, not \`a\`.
84473
- 5. **Always whitelist tables** — adding a runnable that queries a new table requires the table to be in \`data.tables\` first.
84474
- 6. **Mark sensitive UI with \`data-wm-no-record\`** — it is what keeps that data out of a recorded demo; passwords are handled for you.
84475
- 7. **Reach for \`backendAsync\` + \`waitJob\`** for long work — never a hand-written job-polling runnable.
84476
- 8. **Deploy what a path runnable points at** — a path runnable aimed at a draft fails at runtime; tell the user what needs deploying.
84659
+ 3. **Terminate every datatable statement** — the tagged template and \`db.query(...)\` only build a statement. It runs when you call \`fetch\` / \`fetchOne\` / \`fetchOneScalar\` / \`execute\` (\`fetch\` / \`fetch_one\` / \`fetch_one_scalar\` / \`execute\` in Python). An INSERT or UPDATE without one writes nothing and raises nothing. Awaiting the statement itself is a no-op — it is not a promise.
84660
+ 4. **Keep runnables focused** — one function per runnable; small surface area.
84661
+ 5. **Use descriptive keys** — \`get_user\`, not \`a\`.
84662
+ 6. **Always whitelist tables** — adding a runnable that queries a new table requires the table to be in \`data.tables\` first.
84663
+ 7. **Mark sensitive UI with \`data-wm-no-record\`** — it is what keeps that data out of a recorded demo; passwords are handled for you.
84664
+ 8. **Reach for \`backendAsync\` + \`waitJob\`** for long work — never a hand-written job-polling runnable.
84665
+ 9. **Deploy what a path runnable points at** — a path runnable aimed at a draft fails at runtime; tell the user what needs deploying.
84666
+ 10. **Use \`windmill-chat\` for a chat over a chat-mode flow** — never a runnable that runs the flow and polls its stream.
84477
84667
  `,
84478
84668
  triggers: `---
84479
84669
  name: triggers
@@ -85166,6 +85356,13 @@ export interface TaskRetry {
85166
85356
  export interface TaskOptions {
85167
85357
  timeout?: number;
85168
85358
  tag?: string;
85359
+ /** Seconds during which a previous result of this task is served instead of
85360
+ * running it again. A task written inline in the workflow is keyed on its
85361
+ * step key (its name and call order) and the workflow's input, not on the
85362
+ * arguments it is called with, so cache one only when whether it runs, and
85363
+ * what it receives, follow from the workflow's input alone. A \`taskScript\`
85364
+ * target is keyed on the arguments it is called with. It has no effect on a
85365
+ * \`taskFlow\` target, which keeps its flow's own cache policy. */
85169
85366
  cache_ttl?: number;
85170
85367
  priority?: number;
85171
85368
  concurrency_limit?: number;
@@ -85357,6 +85554,14 @@ def get_resume_urls(approver: str = None, flow_level: bool = None) -> dict
85357
85554
  # it grows with both the width of the fan-out and \`\`attempts\`\`. Retries with
85358
85555
  # no \`\`delay\`\` all go out in a single round.
85359
85556
  #
85557
+ # \`\`cache_ttl\`\` serves a previous result of the task for that many seconds
85558
+ # instead of running it again. A task is keyed on its step key (its name and
85559
+ # call order) and the workflow's input, not on the arguments it is called
85560
+ # with, so cache one only when whether it runs, and what it receives, follow
85561
+ # from the workflow's input alone. A \`\`task_script\`\` target is keyed on the
85562
+ # arguments it is called with. It has no effect on a \`\`task_flow\`\` target,
85563
+ # which keeps its flow's own cache policy.
85564
+ #
85360
85565
  # Usage::
85361
85566
  #
85362
85567
  # @task
@@ -86159,6 +86364,27 @@ Manage API tokens
86159
86364
  - \`--expiration <expiration:string>\` - Token expiration (ISO 8601 timestamp)
86160
86365
  - \`token delete <token_prefix:string>\` - Delete a token by its prefix
86161
86366
 
86367
+ ### trash
86368
+
86369
+ List, inspect and restore items deleted in the last three days (requires admin)
86370
+
86371
+ **Options:**
86372
+ - \`--json\` - Output as JSON (for piping to jq)
86373
+ - \`--kind <kind:string>\` - Only items of this kind: script, flow, app, schedule, variable, resource or a trigger kind such as http_trigger
86374
+ - \`--limit <limit:integer>\` - Number of items to return (default 100, max 1000)
86375
+ - \`--page <page:integer>\` - Page to return, starting at 1
86376
+
86377
+ **Subcommands:**
86378
+
86379
+ - \`trash list\` - List trashed items, most recently deleted first
86380
+ - \`--json\` - Output as JSON (for piping to jq)
86381
+ - \`--kind <kind:string>\` - Only items of this kind: script, flow, app, schedule, variable, resource or a trigger kind such as http_trigger
86382
+ - \`--limit <limit:integer>\` - Number of items to return (default 100, max 1000)
86383
+ - \`--page <page:integer>\` - Page to return, starting at 1
86384
+ - \`trash get <id:integer>\` - Show a trashed item and the data it was deleted with
86385
+ - \`--json\` - Output as JSON (for piping to jq)
86386
+ - \`trash restore <ids...:integer>\` - Put trashed items back at their paths
86387
+
86162
86388
  ### trigger
86163
86389
 
86164
86390
  trigger related commands
@@ -86962,6 +87188,21 @@ properties:
86962
87188
  type: boolean
86963
87189
  description: If true, passes the request body as a raw string instead of parsing
86964
87190
  as JSON
87191
+ allowed_origins:
87192
+ type: array
87193
+ items:
87194
+ type: string
87195
+ description: 'Origins allowed to call this route cross-origin, matched against
87196
+ the request''s Origin header (ignoring case) and echoed back on a match. When
87197
+ set, the list governs both the preflight and the response, overriding any Access-Control-Allow-Origin
87198
+ the runnable returns via wm_headers. Use [''*''] to opt out of any restriction,
87199
+ including the http_route_default_allowed_origins instance setting. An empty
87200
+ list is not a configuration and resolves exactly as null does. When null, the
87201
+ instance setting applies, or Access-Control-Allow-Origin: * if it is unset.
87202
+ Ignored on a static website, which has no authentication of its own and so hands
87203
+ out public files: restricting which browsers may read them protects nothing
87204
+ while breaking cross-origin webfonts and fetches. A single-file static asset
87205
+ is not exempt, since it can carry an authentication_method.'
86965
87206
  error_handler_path:
86966
87207
  type: string
86967
87208
  description: Path to a script to run when the triggered job fails. A bare path,
@@ -89537,7 +89778,7 @@ async function pull2(opts) {
89537
89778
  info("failed to parse schema for " + x.name);
89538
89779
  continue;
89539
89780
  }
89540
- if (resourceTypes.find((y) => y.name === x.name && typeof y.schema !== "string" && deepEqual(y.schema, x.schema) && y.description === x.description && (y.is_fileset ?? false) === (x.is_fileset ?? false) && (y.format_extension ?? null) === (x.format_extension ?? null))) {
89781
+ if (resourceTypes.find((y) => y.name === x.name && typeof y.schema !== "string" && deepEqual(y.schema, x.schema) && y.description === x.description && (y.is_fileset ?? false) === (x.is_fileset ?? false) && (y.format_extension ?? null) === (x.format_extension ?? null) && (x.display_name === undefined || (y.display_name ?? null) === x.display_name))) {
89541
89782
  info("skipping " + x.name + " (same as current)");
89542
89783
  continue;
89543
89784
  }
@@ -92021,7 +92262,7 @@ async function initAction(opts) {
92021
92262
  if (await stat20("wmill.yaml").catch(() => null)) {
92022
92263
  info("wmill.yaml already exists, skipping config generation");
92023
92264
  } else {
92024
- await Promise.resolve().then(() => init_git());
92265
+ await init_git();
92025
92266
  let branchName;
92026
92267
  let wsBindings;
92027
92268
  const inGitRepo = isGitRepository();
@@ -92979,6 +93220,98 @@ async function deleteToken2(opts, tokenPrefix) {
92979
93220
  var command38 = new Command().description("Manage API tokens").option("--json", "Output as JSON (for piping to jq)").action(list16).command("list", "List API tokens").option("--json", "Output as JSON (for piping to jq)").action(list16).command("create", "Create a new API token").option("--label <label:string>", "Token label").option("--expiration <expiration:string>", "Token expiration (ISO 8601 timestamp)").action(create2).command("delete", "Delete a token by its prefix").arguments("<token_prefix:string>").action(deleteToken2);
92980
93221
  var token_default = command38;
92981
93222
 
93223
+ // src/commands/trash/trash.ts
93224
+ init_mod3();
93225
+ init_mod6();
93226
+ init_colors2();
93227
+ init_log();
93228
+ init_services_gen();
93229
+ await __promiseAll([
93230
+ init_auth(),
93231
+ init_context(),
93232
+ init_conf(),
93233
+ init_utils()
93234
+ ]);
93235
+ async function list17(opts) {
93236
+ if (opts.json)
93237
+ setSilent(true);
93238
+ opts = await mergeConfigWithConfigFile(opts);
93239
+ const workspace = await resolveWorkspace(opts);
93240
+ await requireLogin(opts);
93241
+ if (opts.page !== undefined && opts.page < 1) {
93242
+ throw new Error("--page starts at 1");
93243
+ }
93244
+ const items = await listTrash({
93245
+ workspace: workspace.workspaceId,
93246
+ itemKind: opts.kind,
93247
+ page: opts.page === undefined ? undefined : opts.page - 1,
93248
+ perPage: opts.limit
93249
+ });
93250
+ if (opts.json) {
93251
+ console.log(JSON.stringify(items));
93252
+ return;
93253
+ }
93254
+ if (items.length === 0) {
93255
+ info("No trashed items found.");
93256
+ return;
93257
+ }
93258
+ new Table2().header(["ID", "Kind", "Path", "Deleted by", "Deleted at", "Expires at"]).padding(2).border(true).body(items.map((item) => [
93259
+ String(item.id),
93260
+ item.item_kind,
93261
+ item.item_path,
93262
+ item.deleted_by,
93263
+ formatTimestamp(item.deleted_at),
93264
+ formatTimestamp(item.expires_at)
93265
+ ])).render();
93266
+ info(colors.gray("`wmill trash get <id>` shows what an item held, `wmill trash restore <id>` puts it back."));
93267
+ }
93268
+ async function get13(opts, id) {
93269
+ if (opts.json)
93270
+ setSilent(true);
93271
+ opts = await mergeConfigWithConfigFile(opts);
93272
+ const workspace = await resolveWorkspace(opts);
93273
+ await requireLogin(opts);
93274
+ const item = await getTrashItem({
93275
+ workspace: workspace.workspaceId,
93276
+ id
93277
+ });
93278
+ if (opts.json) {
93279
+ console.log(JSON.stringify(item));
93280
+ return;
93281
+ }
93282
+ console.log(colors.bold("ID:") + " " + item.id);
93283
+ console.log(colors.bold("Kind:") + " " + item.item_kind);
93284
+ console.log(colors.bold("Path:") + " " + item.item_path);
93285
+ console.log(colors.bold("Deleted by:") + " " + item.deleted_by);
93286
+ console.log(colors.bold("Deleted at:") + " " + formatTimestamp(item.deleted_at));
93287
+ console.log(colors.bold("Expires at:") + " " + formatTimestamp(item.expires_at));
93288
+ console.log(colors.bold("Data:"));
93289
+ console.log(JSON.stringify(item.item_data, null, 2));
93290
+ }
93291
+ async function restore(opts, ...ids) {
93292
+ opts = await mergeConfigWithConfigFile(opts);
93293
+ const workspace = await resolveWorkspace(opts);
93294
+ await requireLogin(opts);
93295
+ let failed = 0;
93296
+ for (const id of ids) {
93297
+ try {
93298
+ const message = await restoreTrashItem({
93299
+ workspace: workspace.workspaceId,
93300
+ id
93301
+ });
93302
+ info(colors.green(message));
93303
+ } catch (e) {
93304
+ failed += 1;
93305
+ error(`Could not restore trash item ${id}: ${apiErrorMessage(e) ?? String(e)}`);
93306
+ }
93307
+ }
93308
+ if (failed > 0) {
93309
+ process.exitCode = 1;
93310
+ }
93311
+ }
93312
+ var command39 = new Command().description("List, inspect and restore items deleted in the last three days (requires admin)").option("--json", "Output as JSON (for piping to jq)").option("--kind <kind:string>", "Only items of this kind: script, flow, app, schedule, variable, resource or a trigger kind such as http_trigger").option("--limit <limit:integer>", "Number of items to return (default 100, max 1000)").option("--page <page:integer>", "Page to return, starting at 1").action(list17).command("list", "List trashed items, most recently deleted first").option("--json", "Output as JSON (for piping to jq)").option("--kind <kind:string>", "Only items of this kind: script, flow, app, schedule, variable, resource or a trigger kind such as http_trigger").option("--limit <limit:integer>", "Number of items to return (default 100, max 1000)").option("--page <page:integer>", "Page to return, starting at 1").action(list17).command("get", "Show a trashed item and the data it was deleted with").arguments("<id:integer>").option("--json", "Output as JSON (for piping to jq)").action(get13).command("restore", "Put trashed items back at their paths").arguments("<ids...:integer>").action(restore);
93313
+ var trash_default = command39;
93314
+
92982
93315
  // src/main.ts
92983
93316
  await init_generate_metadata();
92984
93317
 
@@ -93038,8 +93371,8 @@ ${await res.text()}`);
93038
93371
  console.log();
93039
93372
  }
93040
93373
  }
93041
- var command39 = new Command().name("docs").description("Search Windmill documentation.").arguments("<query:string>").option("--json", "Output results as JSON.").action(docs);
93042
- var docs_default = command39;
93374
+ var command40 = new Command().name("docs").description("Search Windmill documentation.").arguments("<query:string>").option("--json", "Output results as JSON.").action(docs);
93375
+ var docs_default = command40;
93043
93376
 
93044
93377
  // src/commands/config/config.ts
93045
93378
  init_mod3();
@@ -93109,8 +93442,8 @@ async function migrateAction() {
93109
93442
  info(` Also removed additional legacy keys: ${legacyKeys.slice(1).join(", ")}`);
93110
93443
  }
93111
93444
  }
93112
- var command40 = new Command().name("config").description("Show all available wmill.yaml configuration options").option("--json", "Output as JSON for programmatic consumption").action(configAction).command("migrate").description("Migrate wmill.yaml from gitBranches/environments to workspaces format").action(migrateAction);
93113
- var config_default = command40;
93445
+ var command41 = new Command().name("config").description("Show all available wmill.yaml configuration options").option("--json", "Output as JSON for programmatic consumption").action(configAction).command("migrate").description("Migrate wmill.yaml from gitBranches/environments to workspaces format").action(migrateAction);
93446
+ var config_default = command41;
93114
93447
 
93115
93448
  // src/commands/datatable/datatable.ts
93116
93449
  init_mod3();
@@ -95001,7 +95334,7 @@ function signalToNumber(name) {
95001
95334
  // src/commands/datatable/datatable.ts
95002
95335
  await init_datatable_migrations();
95003
95336
  var DEFAULT_DATATABLE_NAME2 = "main";
95004
- async function list17(opts) {
95337
+ async function list18(opts) {
95005
95338
  if (opts.json)
95006
95339
  setSilent(true);
95007
95340
  const workspace = await resolveWorkspace(opts);
@@ -95078,8 +95411,8 @@ async function serve2(opts) {
95078
95411
  async function psql2(opts) {
95079
95412
  await psql(opts);
95080
95413
  }
95081
- var command41 = new Command().description("datatable related commands").command("list", "list all datatables in the workspace").option("--json", "Output as JSON (for piping to jq)").action(list17).command("run", "run a SQL query on a datatable").arguments("<sql:string>").option("-n --name <name:string>", "Datatable name (default: main)").option("-s --silent", "Output only the final result as JSON. Useful for scripting.").action(run4).command("migrate", migrateCommand).command("create", "register a datatable database in the workspace (default: instance-backed 'main') so scripts can use datatable://<name>").arguments("[name:string]").option("--resource <resource:string>", "Back the datatable with an existing postgresql resource path instead of the instance database").option("--force", "Allow adding to a workspace that already has datatables (fork metadata on existing ones is not preserved)").action(create3).command("serve", "Serve all datatables as a Postgres-wire endpoint (psql, DBeaver, pgAdmin); the client picks the datatable via the database name in its connection string").option("--port <port:number>", "Port to listen on (default: first free port in 5433-5500)").option("--host <host:string>", "Bind address (default: 127.0.0.1)").option("--password <password:string>", "Password for Postgres clients (default: generate a random password at startup)").action(serve2).command("psql", "Start a serve listener and launch psql connected to it").option("-n --name <name:string>", "Datatable to connect psql to (default: main)").option("--port <port:number>", "Port the proxy listens on (default: first free port in 5433-5500)").option("--host <host:string>", "Bind address for the proxy (default: 127.0.0.1)").option("--password <password:string>", "Password for the temporary Postgres proxy (default: generate a random password at startup)").action(psql2);
95082
- var datatable_default = command41;
95414
+ var command42 = new Command().description("datatable related commands").command("list", "list all datatables in the workspace").option("--json", "Output as JSON (for piping to jq)").action(list18).command("run", "run a SQL query on a datatable").arguments("<sql:string>").option("-n --name <name:string>", "Datatable name (default: main)").option("-s --silent", "Output only the final result as JSON. Useful for scripting.").action(run4).command("migrate", migrateCommand).command("create", "register a datatable database in the workspace (default: instance-backed 'main') so scripts can use datatable://<name>").arguments("[name:string]").option("--resource <resource:string>", "Back the datatable with an existing postgresql resource path instead of the instance database").option("--force", "Allow adding to a workspace that already has datatables (fork metadata on existing ones is not preserved)").action(create3).command("serve", "Serve all datatables as a Postgres-wire endpoint (psql, DBeaver, pgAdmin); the client picks the datatable via the database name in its connection string").option("--port <port:number>", "Port to listen on (default: first free port in 5433-5500)").option("--host <host:string>", "Bind address (default: 127.0.0.1)").option("--password <password:string>", "Password for Postgres clients (default: generate a random password at startup)").action(serve2).command("psql", "Start a serve listener and launch psql connected to it").option("-n --name <name:string>", "Datatable to connect psql to (default: main)").option("--port <port:number>", "Port the proxy listens on (default: first free port in 5433-5500)").option("--host <host:string>", "Bind address for the proxy (default: 127.0.0.1)").option("--password <password:string>", "Password for the temporary Postgres proxy (default: generate a random password at startup)").action(psql2);
95415
+ var datatable_default = command42;
95083
95416
 
95084
95417
  // src/commands/pipeline/pipeline.ts
95085
95418
  init_mod3();
@@ -96369,8 +96702,8 @@ async function dev3(opts, folderArg) {
96369
96702
  process27.exit(0);
96370
96703
  });
96371
96704
  }
96372
- var command42 = new Command().description("Live-preview a data pipeline from local files: watch an `f/<folder>` of `// pipeline` scripts, push the working-tree graph to the dev page, and run the cascade via preview (no deploy).").arguments("[folder:string]").option("--port <port:number>", "Port for the dev WebSocket server.").option("--no-open", "Do not open the browser automatically.").option("--frontend <origin:string>", "Origin serving the /pipeline_dev page (e.g. http://localhost:3000 for a locally-run frontend). Defaults to the workspace remote; use it when the remote's deployed frontend predates the dev page.").action(dev3);
96373
- var dev_default3 = command42;
96705
+ var command43 = new Command().description("Live-preview a data pipeline from local files: watch an `f/<folder>` of `// pipeline` scripts, push the working-tree graph to the dev page, and run the cascade via preview (no deploy).").arguments("[folder:string]").option("--port <port:number>", "Port for the dev WebSocket server.").option("--no-open", "Do not open the browser automatically.").option("--frontend <origin:string>", "Origin serving the /pipeline_dev page (e.g. http://localhost:3000 for a locally-run frontend). Defaults to the workspace remote; use it when the remote's deployed frontend predates the dev page.").action(dev3);
96706
+ var dev_default3 = command43;
96374
96707
 
96375
96708
  // src/commands/pipeline/docs.ts
96376
96709
  init_gen();
@@ -96688,7 +97021,7 @@ async function apiGet(path) {
96688
97021
  }
96689
97022
  return await response.json();
96690
97023
  }
96691
- async function list18(opts) {
97024
+ async function list19(opts) {
96692
97025
  if (opts.json)
96693
97026
  setSilent(true);
96694
97027
  const workspace = await resolveWorkspace(opts);
@@ -97261,8 +97594,8 @@ Full logs: ${runUrl}`);
97261
97594
  info(colors.green.bold(`Bounded run complete — ${order.length} script(s) succeeded.`));
97262
97595
  }
97263
97596
  }
97264
- var command43 = new Command().description("inspect asset-driven pipelines (scripts marked `// pipeline`, wired by `// on <spec>` annotations)").command("list", "list pipeline folders in the workspace").option("--json", "Output as JSON (for piping to jq)").action(list18).command("show", "render a pipeline folder's DAG (sources, lineage, subscriptions) in the terminal").arguments("<folder:string>").option("--json", "Output the raw asset graph as JSON").option("--local", "Build the graph from local working-tree files (// pipeline scripts) instead of the deployed workspace — no deploy needed.").action(show2).command("run", "run a cascade: from --from (a root OR any mid-DAG model), fan downstream up to the --to end node(s)").arguments("<folder:string>").option("--from <script:string>", "Start script (short name or path). May be any node, including a mid-DAG model — that node plus its transitive downstream runs, upstream is NOT re-run (dbt `--select model+`). Defaults to the folder's sole schedule/manual root.").option("--to <node:string>", "End node(s) to stop at — script names/paths or asset URIs (e.g. datatable://main/staged). Repeatable or comma-separated. Omit to run the full downstream.", { collect: true }).option("--dry-run", "Print the topological run plan without executing.").option("--json", "Output the plan as JSON (for piping to jq).").option("--local", "Run the local working-tree scripts via preview (no deploy) instead of the deployed versions; the graph is built from local files.").option("--upload <binding:string>", "Bind an object to a data_upload/webhook entry point so it runs in the cascade, as SCRIPT[:PARAM]=SOURCE (SOURCE is a local file or an s3://key). Local files are uploaded to the workspace store; the S3Object param is inferred when the script has exactly one. Repeatable.", { collect: true }).option("--arg <binding:string>", "Pass a plain run arg to a script in the cascade, as SCRIPT:PARAM=VALUE (VALUE is parsed as JSON when possible, else taken as a string — e.g. daily_report:partition=2026-07-02). Repeatable.", { collect: true }).option("--partition <value:string>", "Partition value for `// partitioned` scripts in the run (e.g. 2026-06-30) — use it to backfill a past slice. With --local, time kinds (daily/hourly/weekly/monthly) default to the current UTC period when omitted; `dynamic` always needs it. Deployed runs without it defer to backend run-start resolution.").action(run5).command("docs", "generate PIPELINE.md (+ AGENTS.md pointer) describing a folder's pipeline graph and datatable schemas, for an editor / agentic loop").arguments("<folder:string>").option("--local", "Build the graph from local working-tree files instead of the deployed workspace.").action(generatePipelineDocs).command("dev", dev_default3);
97265
- var pipeline_default = command43;
97597
+ var command44 = new Command().description("inspect asset-driven pipelines (scripts marked `// pipeline`, wired by `// on <spec>` annotations)").command("list", "list pipeline folders in the workspace").option("--json", "Output as JSON (for piping to jq)").action(list19).command("show", "render a pipeline folder's DAG (sources, lineage, subscriptions) in the terminal").arguments("<folder:string>").option("--json", "Output the raw asset graph as JSON").option("--local", "Build the graph from local working-tree files (// pipeline scripts) instead of the deployed workspace — no deploy needed.").action(show2).command("run", "run a cascade: from --from (a root OR any mid-DAG model), fan downstream up to the --to end node(s)").arguments("<folder:string>").option("--from <script:string>", "Start script (short name or path). May be any node, including a mid-DAG model — that node plus its transitive downstream runs, upstream is NOT re-run (dbt `--select model+`). Defaults to the folder's sole schedule/manual root.").option("--to <node:string>", "End node(s) to stop at — script names/paths or asset URIs (e.g. datatable://main/staged). Repeatable or comma-separated. Omit to run the full downstream.", { collect: true }).option("--dry-run", "Print the topological run plan without executing.").option("--json", "Output the plan as JSON (for piping to jq).").option("--local", "Run the local working-tree scripts via preview (no deploy) instead of the deployed versions; the graph is built from local files.").option("--upload <binding:string>", "Bind an object to a data_upload/webhook entry point so it runs in the cascade, as SCRIPT[:PARAM]=SOURCE (SOURCE is a local file or an s3://key). Local files are uploaded to the workspace store; the S3Object param is inferred when the script has exactly one. Repeatable.", { collect: true }).option("--arg <binding:string>", "Pass a plain run arg to a script in the cascade, as SCRIPT:PARAM=VALUE (VALUE is parsed as JSON when possible, else taken as a string — e.g. daily_report:partition=2026-07-02). Repeatable.", { collect: true }).option("--partition <value:string>", "Partition value for `// partitioned` scripts in the run (e.g. 2026-06-30) — use it to backfill a past slice. With --local, time kinds (daily/hourly/weekly/monthly) default to the current UTC period when omitted; `dynamic` always needs it. Deployed runs without it defer to backend run-start resolution.").action(run5).command("docs", "generate PIPELINE.md (+ AGENTS.md pointer) describing a folder's pipeline graph and datatable schemas, for an editor / agentic loop").arguments("<folder:string>").option("--local", "Build the graph from local working-tree files instead of the deployed workspace.").action(generatePipelineDocs).command("dev", dev_default3);
97598
+ var pipeline_default = command44;
97266
97599
 
97267
97600
  // src/commands/ducklake/ducklake.ts
97268
97601
  init_mod3();
@@ -97274,7 +97607,7 @@ await __promiseAll([
97274
97607
  init_context()
97275
97608
  ]);
97276
97609
  var DEFAULT_DUCKLAKE_NAME = "main";
97277
- async function list19(opts) {
97610
+ async function list20(opts) {
97278
97611
  if (opts.json)
97279
97612
  setSilent(true);
97280
97613
  const workspace = await resolveWorkspace(opts);
@@ -97292,8 +97625,8 @@ async function run6(opts, sql) {
97292
97625
  const name = opts.name ?? DEFAULT_DUCKLAKE_NAME;
97293
97626
  await runCatalogQuery(opts, "ducklake", name, sql);
97294
97627
  }
97295
- var command44 = new Command().description("ducklake related commands").command("list", "list all ducklakes in the workspace").option("--json", "Output as JSON (for piping to jq)").action(list19).command("run", "run a SQL query on a ducklake").arguments("<sql:string>").option("-n --name <name:string>", "Ducklake name (default: main)").option("-s --silent", "Output only the final result as JSON. Useful for scripting.").action(run6);
97296
- var ducklake_default = command44;
97628
+ var command45 = new Command().description("ducklake related commands").command("list", "list all ducklakes in the workspace").option("--json", "Output as JSON (for piping to jq)").action(list20).command("run", "run a SQL query on a ducklake").arguments("<sql:string>").option("-n --name <name:string>", "Ducklake name (default: main)").option("-s --silent", "Output only the final result as JSON. Useful for scripting.").action(run6);
97629
+ var ducklake_default = command45;
97297
97630
 
97298
97631
  // src/commands/object-storage/object-storage.ts
97299
97632
  init_mod3();
@@ -97494,8 +97827,8 @@ async function preview3(opts, fileKey) {
97494
97827
  `);
97495
97828
  }
97496
97829
  }
97497
- var command45 = new Command().alias("s3").description("Object storage (S3) related commands. Operates on the workspace's default object storage; use --storage to target a configured secondary storage.").action(listStorages).command("list", "List configured object storages for the workspace (default + secondary).").option("--json", "Output as JSON (for piping to jq)").action(listStorages).command("files", "List files in an object storage. Optionally filter by prefix.").alias("ls").arguments("[prefix:string]").option("--json", "Output as JSON (for piping to jq)").option("--max-keys <maxKeys:number>", "Page size (default 100)").option("--marker <marker:string>", "Pagination marker from a previous response").option("--storage <storage:string>", "Secondary storage name (omit for the workspace default)").action(listFiles).command("upload", "Upload a local file to object storage at the given file key.").arguments("<local_path:string> <file_key:string>").option("--storage <storage:string>", "Secondary storage name").option("--content-type <contentType:string>", "Content-Type header to set on the object").option("--content-disposition <contentDisposition:string>", "Content-Disposition header to set on the object").action(upload).command("download", "Download an object to a local file (or stdout). Default output path is the basename of the file key in the current directory.").arguments("<file_key:string> [output_path:string]").option("--storage <storage:string>", "Secondary storage name").option("--stdout", "Write file contents to stdout instead of a file").action(download).command("delete", "Delete an object from object storage. Prompts for confirmation unless --yes is set.").arguments("<file_key:string>").option("--storage <storage:string>", "Secondary storage name").option("--yes", "Skip the confirmation prompt").action(del).command("move", "Move an object within the same storage (rename or relocate by key).").arguments("<src_file_key:string> <dest_file_key:string>").option("--storage <storage:string>", "Secondary storage name").action(move).command("info", "Show metadata (size, mime, last-modified) for an object.").arguments("<file_key:string>").option("--json", "Output as JSON (for piping to jq)").option("--storage <storage:string>", "Secondary storage name").action(info2).command("preview", "Preview the contents of an object (text/CSV). Use --bytes-from / --bytes-length to peek at a slice of binary files.").arguments("<file_key:string>").option("--storage <storage:string>", "Secondary storage name").option("--mime <mime:string>", "Override the detected mime type (e.g. text/csv)").option("--bytes-from <bytesFrom:number>", "Start offset in bytes").option("--bytes-length <bytesLength:number>", "Number of bytes to read").option("--csv-separator <csvSeparator:string>", "CSV column separator (default ,)").option("--csv-header", "Treat the first CSV row as a header").action(preview3);
97498
- var object_storage_default = command45;
97830
+ var command46 = new Command().alias("s3").description("Object storage (S3) related commands. Operates on the workspace's default object storage; use --storage to target a configured secondary storage.").action(listStorages).command("list", "List configured object storages for the workspace (default + secondary).").option("--json", "Output as JSON (for piping to jq)").action(listStorages).command("files", "List files in an object storage. Optionally filter by prefix.").alias("ls").arguments("[prefix:string]").option("--json", "Output as JSON (for piping to jq)").option("--max-keys <maxKeys:number>", "Page size (default 100)").option("--marker <marker:string>", "Pagination marker from a previous response").option("--storage <storage:string>", "Secondary storage name (omit for the workspace default)").action(listFiles).command("upload", "Upload a local file to object storage at the given file key.").arguments("<local_path:string> <file_key:string>").option("--storage <storage:string>", "Secondary storage name").option("--content-type <contentType:string>", "Content-Type header to set on the object").option("--content-disposition <contentDisposition:string>", "Content-Disposition header to set on the object").action(upload).command("download", "Download an object to a local file (or stdout). Default output path is the basename of the file key in the current directory.").arguments("<file_key:string> [output_path:string]").option("--storage <storage:string>", "Secondary storage name").option("--stdout", "Write file contents to stdout instead of a file").action(download).command("delete", "Delete an object from object storage. Prompts for confirmation unless --yes is set.").arguments("<file_key:string>").option("--storage <storage:string>", "Secondary storage name").option("--yes", "Skip the confirmation prompt").action(del).command("move", "Move an object within the same storage (rename or relocate by key).").arguments("<src_file_key:string> <dest_file_key:string>").option("--storage <storage:string>", "Secondary storage name").action(move).command("info", "Show metadata (size, mime, last-modified) for an object.").arguments("<file_key:string>").option("--json", "Output as JSON (for piping to jq)").option("--storage <storage:string>", "Secondary storage name").action(info2).command("preview", "Preview the contents of an object (text/CSV). Use --bytes-from / --bytes-length to peek at a slice of binary files.").arguments("<file_key:string>").option("--storage <storage:string>", "Secondary storage name").option("--mime <mime:string>", "Override the detected mime type (e.g. text/csv)").option("--bytes-from <bytesFrom:number>", "Start offset in bytes").option("--bytes-length <bytesLength:number>", "Number of bytes to read").option("--csv-separator <csvSeparator:string>", "CSV column separator (default ,)").option("--csv-header", "Treat the first CSV row as a header").action(preview3);
97831
+ var object_storage_default = command46;
97499
97832
 
97500
97833
  // src/main.ts
97501
97834
  await init_context();
@@ -97515,7 +97848,7 @@ async function checkVersionSafe(cmd) {
97515
97848
  }
97516
97849
  mainCommand.version(`${currentVersion} (New version available: ${latestVersion}. Run '${mainCommand.getName()} upgrade' to upgrade to the latest version!)`);
97517
97850
  }
97518
- var command46 = new Command().name("wmill").action(() => info(`Welcome to Windmill CLI ${VERSION}. Use -h for help.`)).description("Windmill CLI").globalOption("--workspace <workspace:string>", "Specify the target workspace. This overrides the default workspace.").globalOption("--debug --verbose", "Show debug/verbose logs").globalOption("--show-diffs", "Show diff informations when syncing (may show sensitive informations)").globalOption("--token <token:string>", "Specify an API token. This will override any stored token.").globalOption("--base-url <baseUrl:string>", "Specify the base URL of the API. If used, --token and --workspace are required and no local remote/workspace already set will be used.").globalOption("--config-dir <configDir:string>", "Specify a custom config directory. Overrides WMILL_CONFIG_DIR environment variable and default ~/.config location.").env("HEADERS <headers:string>", `Specify headers to use for all requests. e.g: "HEADERS='h1: v1, h2: v2'"`).version(VERSION).versionOption(false).helpOption("-h, --help", "Show this help.", {
97851
+ var command47 = new Command().name("wmill").action(() => info(`Welcome to Windmill CLI ${VERSION}. Use -h for help.`)).description("Windmill CLI").globalOption("--workspace <workspace:string>", "Specify the target workspace. This overrides the default workspace.").globalOption("--debug --verbose", "Show debug/verbose logs").globalOption("--show-diffs", "Show diff informations when syncing (may show sensitive informations)").globalOption("--token <token:string>", "Specify an API token. This will override any stored token.").globalOption("--base-url <baseUrl:string>", "Specify the base URL of the API. If used, --token and --workspace are required and no local remote/workspace already set will be used.").globalOption("--config-dir <configDir:string>", "Specify a custom config directory. Overrides WMILL_CONFIG_DIR environment variable and default ~/.config location.").env("HEADERS <headers:string>", `Specify headers to use for all requests. e.g: "HEADERS='h1: v1, h2: v2'"`).version(VERSION).versionOption(false).helpOption("-h, --help", "Show this help.", {
97519
97852
  action: async function() {
97520
97853
  const self2 = this;
97521
97854
  const long = self2.getRawArgs().includes(`--${self2.getHelpOption()?.name}`);
@@ -97527,7 +97860,7 @@ var command46 = new Command().name("wmill").action(() => info(`Welcome to Windmi
97527
97860
  self2.showHelp({ long });
97528
97861
  self2.exit();
97529
97862
  }
97530
- }).command("init", init_default).command("refresh", refresh_default).command("app", app_default).command("flow", flow_default).command("script", script_default).command("workspace", workspace_default).command("resource", resource_default).command("resource-type", resource_type_default).command("user", user_default).command("variable", variable_default).command("hub", hub_default).command("folder", folder_default).command("schedule", schedule_default2).command("trigger", trigger_default).command("dev", dev_default2).command("sync", sync_default).command("lint", lint_default).command("gitsync-settings", gitsync_settings_default).command("protection-rules", protection_rules_default).command("instance", instance_default).command("worker-groups", worker_groups_default).command("workers", workers_default).command("queues", queues_default).command("dependencies", dependencies_default).command("jobs", jobs_default).command("job", job_default).command("group", group_default).command("audit", audit_default).command("token", token_default).command("generate-metadata", generate_metadata_default).command("docs", docs_default).command("config", config_default).command("datatable", datatable_default).command("pipeline", pipeline_default).command("ducklake", ducklake_default).command("object-storage", object_storage_default).command("version --version", "Show version information").action(async (opts) => {
97863
+ }).command("init", init_default).command("refresh", refresh_default).command("app", app_default).command("flow", flow_default).command("script", script_default).command("workspace", workspace_default).command("resource", resource_default).command("resource-type", resource_type_default).command("user", user_default).command("variable", variable_default).command("hub", hub_default).command("folder", folder_default).command("schedule", schedule_default2).command("trigger", trigger_default).command("dev", dev_default2).command("sync", sync_default).command("lint", lint_default).command("gitsync-settings", gitsync_settings_default).command("protection-rules", protection_rules_default).command("instance", instance_default).command("worker-groups", worker_groups_default).command("workers", workers_default).command("queues", queues_default).command("dependencies", dependencies_default).command("jobs", jobs_default).command("job", job_default).command("group", group_default).command("audit", audit_default).command("token", token_default).command("trash", trash_default).command("generate-metadata", generate_metadata_default).command("docs", docs_default).command("config", config_default).command("datatable", datatable_default).command("pipeline", pipeline_default).command("ducklake", ducklake_default).command("object-storage", object_storage_default).command("version --version", "Show version information").action(async (opts) => {
97531
97864
  console.log("CLI version: " + VERSION);
97532
97865
  try {
97533
97866
  const provider = new NpmProvider({ package: "windmill-cli" });
@@ -97557,20 +97890,20 @@ var command46 = new Command().name("wmill").action(() => info(`Welcome to Windmi
97557
97890
  error(e);
97558
97891
  info("Try running with sudo and otherwise check the result of the command: npm uninstall windmill-cli && npm install -g windmill-cli");
97559
97892
  })).command("completions", new Command().description("Generate shell completions.").command("bash", new Command().description("Generate bash completions.").action(() => {
97560
- process.stdout.write(generateShellCompletions(command46, "bash") + `
97893
+ process.stdout.write(generateShellCompletions(command47, "bash") + `
97561
97894
  `);
97562
97895
  })).command("zsh", new Command().description("Generate zsh completions.").action(() => {
97563
- process.stdout.write(generateShellCompletions(command46, "zsh") + `
97896
+ process.stdout.write(generateShellCompletions(command47, "zsh") + `
97564
97897
  `);
97565
97898
  })).command("fish", new Command().description("Generate fish completions.").action(() => {
97566
- process.stdout.write(generateShellCompletions(command46, "fish") + `
97899
+ process.stdout.write(generateShellCompletions(command47, "fish") + `
97567
97900
  `);
97568
97901
  })));
97569
97902
  async function main2() {
97570
97903
  try {
97571
97904
  const args = process.argv.slice(2);
97572
97905
  if (args.length === 0) {
97573
- command46.showHelp();
97906
+ command47.showHelp();
97574
97907
  }
97575
97908
  const LOG_LEVEL = args.includes("--verbose") || args.includes("--debug") ? "DEBUG" : "INFO";
97576
97909
  setShowDiffs(args.includes("--show-diffs"));
@@ -97591,13 +97924,11 @@ async function main2() {
97591
97924
  await init_tsconfig();
97592
97925
  await warnIfTsconfigStale().catch(() => {});
97593
97926
  }
97594
- await command46.parse(args);
97927
+ await command47.parse(args);
97595
97928
  } catch (e) {
97596
- if (e && typeof e === "object" && "name" in e && e.name === "ApiError") {
97597
- const body = e.body;
97598
- let bodyStr = typeof body === "object" && body !== null ? JSON.stringify(body) : String(body ?? "");
97599
- bodyStr = bodyStr.replace(/\s*[@(]\w+\.rs:\d+[:\d]*\)?/g, "");
97600
- error("Server failed. " + e.statusText + ": " + bodyStr);
97929
+ const apiError = apiErrorMessage(e);
97930
+ if (apiError !== undefined) {
97931
+ error("Server failed. " + apiError);
97601
97932
  } else if (e instanceof Error) {
97602
97933
  error(e.message);
97603
97934
  } else if (e !== undefined && e !== null) {
@@ -97627,7 +97958,7 @@ if (isMain()) {
97627
97958
  process.stdin.destroy();
97628
97959
  });
97629
97960
  }
97630
- var main_default = command46;
97961
+ var main_default = command47;
97631
97962
  export {
97632
97963
  VERSION,
97633
97964
  WM_FORK_PREFIX,