@floless/app 0.106.0 → 0.108.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.
@@ -5489,7 +5489,7 @@ var require_thread_stream = __commonJS({
5489
5489
  var { version } = require_package();
5490
5490
  var { EventEmitter: EventEmitter2 } = require("events");
5491
5491
  var { Worker: Worker2 } = require("worker_threads");
5492
- var { join: join40 } = require("path");
5492
+ var { join: join41 } = require("path");
5493
5493
  var { pathToFileURL } = require("url");
5494
5494
  var { wait } = require_wait();
5495
5495
  var {
@@ -5540,7 +5540,7 @@ var require_thread_stream = __commonJS({
5540
5540
  function createWorker(stream, opts) {
5541
5541
  const { filename, workerData } = opts;
5542
5542
  const bundlerOverrides = "__bundlerPathsOverrides" in globalThis ? globalThis.__bundlerPathsOverrides : {};
5543
- const toExecute = bundlerOverrides["thread-stream-worker"] || join40(__dirname, "lib", "worker.js");
5543
+ const toExecute = bundlerOverrides["thread-stream-worker"] || join41(__dirname, "lib", "worker.js");
5544
5544
  const worker = new Worker2(toExecute, {
5545
5545
  ...opts.workerOpts,
5546
5546
  name: opts.workerOpts?.name || "thread-stream",
@@ -6006,9 +6006,9 @@ var require_transport = __commonJS({
6006
6006
  "node_modules/pino/lib/transport.js"(exports2, module2) {
6007
6007
  "use strict";
6008
6008
  var { createRequire: createRequire5 } = require("module");
6009
- var { existsSync: existsSync36 } = require("node:fs");
6009
+ var { existsSync: existsSync37 } = require("node:fs");
6010
6010
  var getCallers = require_caller();
6011
- var { join: join40, isAbsolute: isAbsolute2, sep: sep6 } = require("node:path");
6011
+ var { join: join41, isAbsolute: isAbsolute2, sep: sep6 } = require("node:path");
6012
6012
  var { fileURLToPath: fileURLToPath6 } = require("node:url");
6013
6013
  var sleep2 = require_atomic_sleep();
6014
6014
  var onExit = require_on_exit_leak_free();
@@ -6080,7 +6080,7 @@ var require_transport = __commonJS({
6080
6080
  return false;
6081
6081
  }
6082
6082
  }
6083
- return isAbsolute2(path) && !existsSync36(path);
6083
+ return isAbsolute2(path) && !existsSync37(path);
6084
6084
  }
6085
6085
  function stripQuotes(value) {
6086
6086
  const first = value[0];
@@ -6161,7 +6161,7 @@ var require_transport = __commonJS({
6161
6161
  throw new Error("only one of target or targets can be specified");
6162
6162
  }
6163
6163
  if (targets) {
6164
- target = bundlerOverrides["pino-worker"] || join40(__dirname, "worker.js");
6164
+ target = bundlerOverrides["pino-worker"] || join41(__dirname, "worker.js");
6165
6165
  options.targets = targets.filter((dest) => dest.target).map((dest) => {
6166
6166
  return {
6167
6167
  ...dest,
@@ -6179,7 +6179,7 @@ var require_transport = __commonJS({
6179
6179
  });
6180
6180
  });
6181
6181
  } else if (pipeline2) {
6182
- target = bundlerOverrides["pino-worker"] || join40(__dirname, "worker.js");
6182
+ target = bundlerOverrides["pino-worker"] || join41(__dirname, "worker.js");
6183
6183
  options.pipelines = [pipeline2.map((dest) => {
6184
6184
  return {
6185
6185
  ...dest,
@@ -6202,7 +6202,7 @@ var require_transport = __commonJS({
6202
6202
  return origin;
6203
6203
  }
6204
6204
  if (origin === "pino/file") {
6205
- return join40(__dirname, "..", "file.js");
6205
+ return join41(__dirname, "..", "file.js");
6206
6206
  }
6207
6207
  let fixTarget2;
6208
6208
  for (const filePath of callers) {
@@ -7182,7 +7182,7 @@ var require_safe_stable_stringify = __commonJS({
7182
7182
  return circularValue;
7183
7183
  }
7184
7184
  let res = "";
7185
- let join40 = ",";
7185
+ let join41 = ",";
7186
7186
  const originalIndentation = indentation;
7187
7187
  if (Array.isArray(value)) {
7188
7188
  if (value.length === 0) {
@@ -7196,7 +7196,7 @@ var require_safe_stable_stringify = __commonJS({
7196
7196
  indentation += spacer;
7197
7197
  res += `
7198
7198
  ${indentation}`;
7199
- join40 = `,
7199
+ join41 = `,
7200
7200
  ${indentation}`;
7201
7201
  }
7202
7202
  const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
@@ -7204,13 +7204,13 @@ ${indentation}`;
7204
7204
  for (; i < maximumValuesToStringify - 1; i++) {
7205
7205
  const tmp2 = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation);
7206
7206
  res += tmp2 !== void 0 ? tmp2 : "null";
7207
- res += join40;
7207
+ res += join41;
7208
7208
  }
7209
7209
  const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation);
7210
7210
  res += tmp !== void 0 ? tmp : "null";
7211
7211
  if (value.length - 1 > maximumBreadth) {
7212
7212
  const removedKeys = value.length - maximumBreadth - 1;
7213
- res += `${join40}"... ${getItemCount(removedKeys)} not stringified"`;
7213
+ res += `${join41}"... ${getItemCount(removedKeys)} not stringified"`;
7214
7214
  }
7215
7215
  if (spacer !== "") {
7216
7216
  res += `
@@ -7231,7 +7231,7 @@ ${originalIndentation}`;
7231
7231
  let separator = "";
7232
7232
  if (spacer !== "") {
7233
7233
  indentation += spacer;
7234
- join40 = `,
7234
+ join41 = `,
7235
7235
  ${indentation}`;
7236
7236
  whitespace = " ";
7237
7237
  }
@@ -7245,13 +7245,13 @@ ${indentation}`;
7245
7245
  const tmp = stringifyFnReplacer(key3, value, stack, replacer, spacer, indentation);
7246
7246
  if (tmp !== void 0) {
7247
7247
  res += `${separator}${strEscape(key3)}:${whitespace}${tmp}`;
7248
- separator = join40;
7248
+ separator = join41;
7249
7249
  }
7250
7250
  }
7251
7251
  if (keyLength > maximumBreadth) {
7252
7252
  const removedKeys = keyLength - maximumBreadth;
7253
7253
  res += `${separator}"...":${whitespace}"${getItemCount(removedKeys)} not stringified"`;
7254
- separator = join40;
7254
+ separator = join41;
7255
7255
  }
7256
7256
  if (spacer !== "" && separator.length > 1) {
7257
7257
  res = `
@@ -7292,7 +7292,7 @@ ${originalIndentation}`;
7292
7292
  }
7293
7293
  const originalIndentation = indentation;
7294
7294
  let res = "";
7295
- let join40 = ",";
7295
+ let join41 = ",";
7296
7296
  if (Array.isArray(value)) {
7297
7297
  if (value.length === 0) {
7298
7298
  return "[]";
@@ -7305,7 +7305,7 @@ ${originalIndentation}`;
7305
7305
  indentation += spacer;
7306
7306
  res += `
7307
7307
  ${indentation}`;
7308
- join40 = `,
7308
+ join41 = `,
7309
7309
  ${indentation}`;
7310
7310
  }
7311
7311
  const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
@@ -7313,13 +7313,13 @@ ${indentation}`;
7313
7313
  for (; i < maximumValuesToStringify - 1; i++) {
7314
7314
  const tmp2 = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation);
7315
7315
  res += tmp2 !== void 0 ? tmp2 : "null";
7316
- res += join40;
7316
+ res += join41;
7317
7317
  }
7318
7318
  const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation);
7319
7319
  res += tmp !== void 0 ? tmp : "null";
7320
7320
  if (value.length - 1 > maximumBreadth) {
7321
7321
  const removedKeys = value.length - maximumBreadth - 1;
7322
- res += `${join40}"... ${getItemCount(removedKeys)} not stringified"`;
7322
+ res += `${join41}"... ${getItemCount(removedKeys)} not stringified"`;
7323
7323
  }
7324
7324
  if (spacer !== "") {
7325
7325
  res += `
@@ -7332,7 +7332,7 @@ ${originalIndentation}`;
7332
7332
  let whitespace = "";
7333
7333
  if (spacer !== "") {
7334
7334
  indentation += spacer;
7335
- join40 = `,
7335
+ join41 = `,
7336
7336
  ${indentation}`;
7337
7337
  whitespace = " ";
7338
7338
  }
@@ -7341,7 +7341,7 @@ ${indentation}`;
7341
7341
  const tmp = stringifyArrayReplacer(key3, value[key3], stack, replacer, spacer, indentation);
7342
7342
  if (tmp !== void 0) {
7343
7343
  res += `${separator}${strEscape(key3)}:${whitespace}${tmp}`;
7344
- separator = join40;
7344
+ separator = join41;
7345
7345
  }
7346
7346
  }
7347
7347
  if (spacer !== "" && separator.length > 1) {
@@ -7399,20 +7399,20 @@ ${originalIndentation}`;
7399
7399
  indentation += spacer;
7400
7400
  let res2 = `
7401
7401
  ${indentation}`;
7402
- const join41 = `,
7402
+ const join42 = `,
7403
7403
  ${indentation}`;
7404
7404
  const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
7405
7405
  let i = 0;
7406
7406
  for (; i < maximumValuesToStringify - 1; i++) {
7407
7407
  const tmp2 = stringifyIndent(String(i), value[i], stack, spacer, indentation);
7408
7408
  res2 += tmp2 !== void 0 ? tmp2 : "null";
7409
- res2 += join41;
7409
+ res2 += join42;
7410
7410
  }
7411
7411
  const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation);
7412
7412
  res2 += tmp !== void 0 ? tmp : "null";
7413
7413
  if (value.length - 1 > maximumBreadth) {
7414
7414
  const removedKeys = value.length - maximumBreadth - 1;
7415
- res2 += `${join41}"... ${getItemCount(removedKeys)} not stringified"`;
7415
+ res2 += `${join42}"... ${getItemCount(removedKeys)} not stringified"`;
7416
7416
  }
7417
7417
  res2 += `
7418
7418
  ${originalIndentation}`;
@@ -7428,16 +7428,16 @@ ${originalIndentation}`;
7428
7428
  return '"[Object]"';
7429
7429
  }
7430
7430
  indentation += spacer;
7431
- const join40 = `,
7431
+ const join41 = `,
7432
7432
  ${indentation}`;
7433
7433
  let res = "";
7434
7434
  let separator = "";
7435
7435
  let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth);
7436
7436
  if (isTypedArrayWithEntries(value)) {
7437
- res += stringifyTypedArray(value, join40, maximumBreadth);
7437
+ res += stringifyTypedArray(value, join41, maximumBreadth);
7438
7438
  keys = keys.slice(value.length);
7439
7439
  maximumPropertiesToStringify -= value.length;
7440
- separator = join40;
7440
+ separator = join41;
7441
7441
  }
7442
7442
  if (deterministic) {
7443
7443
  keys = sort(keys, comparator);
@@ -7448,13 +7448,13 @@ ${indentation}`;
7448
7448
  const tmp = stringifyIndent(key3, value[key3], stack, spacer, indentation);
7449
7449
  if (tmp !== void 0) {
7450
7450
  res += `${separator}${strEscape(key3)}: ${tmp}`;
7451
- separator = join40;
7451
+ separator = join41;
7452
7452
  }
7453
7453
  }
7454
7454
  if (keyLength > maximumBreadth) {
7455
7455
  const removedKeys = keyLength - maximumBreadth;
7456
7456
  res += `${separator}"...": "${getItemCount(removedKeys)} not stringified"`;
7457
- separator = join40;
7457
+ separator = join41;
7458
7458
  }
7459
7459
  if (separator !== "") {
7460
7460
  res = `
@@ -41991,7 +41991,7 @@ var require_send = __commonJS({
41991
41991
  var { parseTokenList } = require_parseTokenList();
41992
41992
  var { createHttpError } = require_createHttpError();
41993
41993
  var extname4 = path.extname;
41994
- var join40 = path.join;
41994
+ var join41 = path.join;
41995
41995
  var normalize2 = path.normalize;
41996
41996
  var resolve11 = path.resolve;
41997
41997
  var sep6 = path.sep;
@@ -42078,7 +42078,7 @@ var require_send = __commonJS({
42078
42078
  return { statusCode: 403 };
42079
42079
  }
42080
42080
  parts = path2.split(sep6);
42081
- path2 = normalize2(join40(root3, path2));
42081
+ path2 = normalize2(join41(root3, path2));
42082
42082
  } else {
42083
42083
  if (UP_PATH_REGEXP.test(path2)) {
42084
42084
  debug('malicious path "%s"', path2);
@@ -42361,7 +42361,7 @@ var require_send = __commonJS({
42361
42361
  let err2;
42362
42362
  for (let i = 0; i < options.index.length; i++) {
42363
42363
  const index = options.index[i];
42364
- const p = join40(path2, index);
42364
+ const p = join41(path2, index);
42365
42365
  const { error, stat: stat4 } = await tryStat(p);
42366
42366
  if (error) {
42367
42367
  err2 = error;
@@ -43012,7 +43012,7 @@ var require_static = __commonJS({
43012
43012
  "use strict";
43013
43013
  var path = require("node:path");
43014
43014
  var { fileURLToPath: fileURLToPath6 } = require("node:url");
43015
- var { statSync: statSync16 } = require("node:fs");
43015
+ var { statSync: statSync17 } = require("node:fs");
43016
43016
  var { glob } = require_commonjs6();
43017
43017
  var fp = require_plugin2();
43018
43018
  var send = require_send2();
@@ -43375,7 +43375,7 @@ var require_static = __commonJS({
43375
43375
  }
43376
43376
  let pathStat;
43377
43377
  try {
43378
- pathStat = statSync16(rootPath);
43378
+ pathStat = statSync17(rootPath);
43379
43379
  } catch (e) {
43380
43380
  if (e.code === "ENOENT") {
43381
43381
  fastify.log.warn(`"root" path "${rootPath}" must exist`);
@@ -43399,7 +43399,7 @@ var require_static = __commonJS({
43399
43399
  return indexFiles.find((filename) => {
43400
43400
  const p = path.join(root3, pathname, filename);
43401
43401
  try {
43402
- const stats = statSync16(p);
43402
+ const stats = statSync17(p);
43403
43403
  return !stats.isDirectory();
43404
43404
  } catch {
43405
43405
  return false;
@@ -50827,9 +50827,9 @@ var import_node_readline2 = require("node:readline");
50827
50827
 
50828
50828
  // index.ts
50829
50829
  var import_node_url5 = require("node:url");
50830
- var import_node_path41 = require("node:path");
50831
- var import_node_os24 = require("node:os");
50832
- var import_node_fs44 = require("node:fs");
50830
+ var import_node_path42 = require("node:path");
50831
+ var import_node_os25 = require("node:os");
50832
+ var import_node_fs45 = require("node:fs");
50833
50833
  var import_node_child_process9 = require("node:child_process");
50834
50834
 
50835
50835
  // log.mjs
@@ -51021,8 +51021,129 @@ var import_node_os3 = require("node:os");
51021
51021
  var import_node_path3 = require("node:path");
51022
51022
  var import_node_crypto2 = require("node:crypto");
51023
51023
  var import_node_perf_hooks = require("node:perf_hooks");
51024
+ var MAX_EXPECTED_MS = 2 * 60 * 6e4;
51025
+ var MAX_LABEL_LENGTH = 60;
51026
+ function busyMeta(owner) {
51027
+ const label = typeof owner.label === "string" && owner.label.trim() && owner.label.length <= MAX_LABEL_LENGTH ? owner.label.trim() : null;
51028
+ const expectedMs = typeof owner.expectedMs === "number" && Number.isFinite(owner.expectedMs) && owner.expectedMs > 0 && owner.expectedMs <= MAX_EXPECTED_MS ? owner.expectedMs : null;
51029
+ return { label, expectedMs };
51030
+ }
51031
+ var LifecycleLockBusyError = class extends Error {
51032
+ constructor(message, busy) {
51033
+ super(message);
51034
+ this.busy = busy;
51035
+ this.name = "LifecycleLockBusyError";
51036
+ }
51037
+ busy;
51038
+ status = 409;
51039
+ };
51040
+ function subjectFor(kind) {
51041
+ if (kind === "project") return "This project";
51042
+ if (kind === "app") return "This workflow";
51043
+ return "This app";
51044
+ }
51045
+ function remainingPhrase(remainingMs) {
51046
+ if (remainingMs < 6e4) return "less than a minute left";
51047
+ const minutes = Math.round(remainingMs / 6e4);
51048
+ return `about ${minutes} minute${minutes === 1 ? "" : "s"} left`;
51049
+ }
51050
+ function busyDetail(kind, key, owner) {
51051
+ const { label, expectedMs } = busyMeta(owner);
51052
+ const startedMs = Date.parse(owner.acquiredAt);
51053
+ const elapsedMs = Number.isFinite(startedMs) ? Math.max(0, Date.now() - startedMs) : 0;
51054
+ const usableEta = expectedMs != null && Number.isFinite(startedMs) ? expectedMs : null;
51055
+ const remaining = usableEta == null ? null : usableEta - elapsedMs;
51056
+ return {
51057
+ kind,
51058
+ key,
51059
+ label,
51060
+ startedAt: owner.acquiredAt,
51061
+ expectedMs: usableEta,
51062
+ elapsedMs,
51063
+ remainingMs: remaining != null && remaining > 0 ? remaining : null
51064
+ };
51065
+ }
51066
+ function busyError(kind, key, owner) {
51067
+ const detail = owner ? busyDetail(kind, key, owner) : {
51068
+ kind,
51069
+ key,
51070
+ label: null,
51071
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
51072
+ expectedMs: null,
51073
+ elapsedMs: 0,
51074
+ remainingMs: null
51075
+ };
51076
+ const subject = subjectFor(kind);
51077
+ if (!detail.label) {
51078
+ return new LifecycleLockBusyError(`${subject} is busy with another operation. Try again when it finishes.`, detail);
51079
+ }
51080
+ if (detail.expectedMs == null) {
51081
+ return new LifecycleLockBusyError(`${subject} is busy ${detail.label}. Try again when it finishes.`, detail);
51082
+ }
51083
+ const clause = detail.remainingMs == null ? "taking longer than usual" : remainingPhrase(detail.remainingMs);
51084
+ return new LifecycleLockBusyError(`${subject} is busy ${detail.label} \u2014 ${clause}. Try again when it finishes.`, detail);
51085
+ }
51024
51086
  var held = new import_node_async_hooks.AsyncLocalStorage();
51025
51087
  var localTails = /* @__PURE__ */ new Map();
51088
+ var localIntents = /* @__PURE__ */ new Map();
51089
+ function registerIntent(token, options) {
51090
+ const { label, expectedMs } = busyMeta(options);
51091
+ const intent = { label, expectedMs, acquiredAt: null };
51092
+ const set2 = localIntents.get(token) ?? /* @__PURE__ */ new Set();
51093
+ set2.add(intent);
51094
+ localIntents.set(token, set2);
51095
+ return intent;
51096
+ }
51097
+ function forgetIntent(token, intent) {
51098
+ const set2 = localIntents.get(token);
51099
+ if (!set2) return;
51100
+ set2.delete(intent);
51101
+ if (!set2.size) localIntents.delete(token);
51102
+ }
51103
+ function localProjectedFreeAt(token, now, exclude) {
51104
+ const set2 = localIntents.get(token);
51105
+ if (!set2?.size) return { at: now, blocker: null };
51106
+ let at = now;
51107
+ let holding = null;
51108
+ let longest = null;
51109
+ for (const intent of set2) {
51110
+ if (intent === exclude) continue;
51111
+ if (intent.label) {
51112
+ if (intent.acquiredAt != null) holding = intent;
51113
+ if (!longest || (intent.expectedMs ?? 0) > (longest.expectedMs ?? 0)) longest = intent;
51114
+ }
51115
+ if (intent.expectedMs == null) continue;
51116
+ const start = intent.acquiredAt ?? Math.max(at, now);
51117
+ at = Math.max(now, start + intent.expectedMs);
51118
+ }
51119
+ return { at, blocker: holding ?? longest };
51120
+ }
51121
+ function localBusyError(kind, key, at, blocker, now) {
51122
+ const startedMs = blocker.acquiredAt ?? now;
51123
+ const expectedMs = blocker.expectedMs == null ? void 0 : Math.max(1, at - startedMs);
51124
+ return busyError(kind, key, {
51125
+ acquiredAt: new Date(startedMs).toISOString(),
51126
+ label: blocker.label ?? void 0,
51127
+ expectedMs
51128
+ });
51129
+ }
51130
+ function waitForTurn(previous, budget, onExpiry) {
51131
+ return new Promise((resolve11, reject) => {
51132
+ let settled = false;
51133
+ const timer = setTimeout(() => {
51134
+ if (settled) return;
51135
+ settled = true;
51136
+ reject(onExpiry());
51137
+ }, budget);
51138
+ previous.catch(() => {
51139
+ }).then(() => {
51140
+ if (settled) return;
51141
+ settled = true;
51142
+ clearTimeout(timer);
51143
+ resolve11();
51144
+ });
51145
+ });
51146
+ }
51026
51147
  var PROCESS_TOKEN = (0, import_node_crypto2.randomUUID)();
51027
51148
  var STALE_MS = 3e4;
51028
51149
  var WAIT_MS = 50;
@@ -51203,9 +51324,10 @@ function retireStaleLock(path, generation) {
51203
51324
  }
51204
51325
  return true;
51205
51326
  }
51206
- async function acquire(path) {
51327
+ async function acquire(path, kind, key, options) {
51207
51328
  (0, import_node_fs4.mkdirSync)(root(), { recursive: true });
51208
- const deadline = Date.now() + TIMEOUT_MS;
51329
+ const budget = options.timeoutMsForTest ?? TIMEOUT_MS;
51330
+ const deadline = Date.now() + budget;
51209
51331
  while (true) {
51210
51332
  try {
51211
51333
  (0, import_node_fs4.mkdirSync)(path);
@@ -51213,7 +51335,11 @@ async function acquire(path) {
51213
51335
  pid: process.pid,
51214
51336
  token: PROCESS_TOKEN,
51215
51337
  acquiredAt: (/* @__PURE__ */ new Date()).toISOString(),
51216
- started: PROCESS_STARTED
51338
+ started: PROCESS_STARTED,
51339
+ // Omitted entirely when undefined, so an undeclared lock writes byte-identical bytes
51340
+ // to what every previous build wrote.
51341
+ ...options.label ? { label: options.label } : {},
51342
+ ...options.expectedMs != null ? { expectedMs: options.expectedMs } : {}
51217
51343
  };
51218
51344
  if (publishExclusive(ownerPath(path), JSON.stringify(owner))) {
51219
51345
  const canonical = readOwner(path);
@@ -51226,16 +51352,30 @@ async function acquire(path) {
51226
51352
  const generation = staleGeneration(path);
51227
51353
  if (generation) {
51228
51354
  if (retireStaleLock(path, generation)) continue;
51355
+ } else {
51356
+ const owner = readOwner(path);
51357
+ const startedMs = owner ? Date.parse(owner.acquiredAt) : NaN;
51358
+ const expected = owner ? busyMeta(owner).expectedMs : null;
51359
+ if (owner && expected != null && startedMs + expected > deadline) {
51360
+ throw busyError(kind, key, owner);
51361
+ }
51229
51362
  }
51230
- if (Date.now() >= deadline) throw new Error(`timed out waiting for lifecycle lock ${path}`);
51363
+ if (Date.now() >= deadline) throw busyError(kind, key, readOwner(path));
51231
51364
  await sleep(WAIT_MS);
51232
51365
  }
51233
51366
  }
51234
51367
  }
51235
- async function withLifecycleLock(kind, key, fn) {
51368
+ async function withLifecycleLock(kind, key, fn, options = {}) {
51236
51369
  const token = `${kind}:${safe(key)}`;
51237
51370
  const inherited = held.getStore();
51238
51371
  if (inherited?.has(token)) return await fn();
51372
+ const budget = options.timeoutMsForTest ?? TIMEOUT_MS;
51373
+ const enteredAt = Date.now();
51374
+ const { at: freeAt, blocker } = localProjectedFreeAt(token, enteredAt);
51375
+ if (freeAt > enteredAt + budget) {
51376
+ throw blocker ? localBusyError(kind, key, freeAt, blocker, enteredAt) : busyError(kind, key, null);
51377
+ }
51378
+ const intent = registerIntent(token, options);
51239
51379
  const previous = localTails.get(token) ?? Promise.resolve();
51240
51380
  let releaseLocal;
51241
51381
  const mine = new Promise((resolve11) => {
@@ -51244,11 +51384,15 @@ async function withLifecycleLock(kind, key, fn) {
51244
51384
  const tail = previous.catch(() => {
51245
51385
  }).then(() => mine);
51246
51386
  localTails.set(token, tail);
51247
- await previous.catch(() => {
51248
- });
51249
51387
  const path = pathFor(kind, key);
51250
51388
  try {
51251
- await acquire(path);
51389
+ await waitForTurn(previous, budget, () => {
51390
+ const now = Date.now();
51391
+ const late = localProjectedFreeAt(token, now, intent);
51392
+ return late.blocker ? localBusyError(kind, key, late.at, late.blocker, now) : busyError(kind, key, null);
51393
+ });
51394
+ await acquire(path, kind, key, options);
51395
+ intent.acquiredAt = Date.now();
51252
51396
  const next = new Set(inherited ?? []);
51253
51397
  next.add(token);
51254
51398
  return await held.run(next, fn);
@@ -51262,6 +51406,7 @@ async function withLifecycleLock(kind, key, fn) {
51262
51406
  }
51263
51407
  }
51264
51408
  }
51409
+ forgetIntent(token, intent);
51265
51410
  releaseLocal();
51266
51411
  if (localTails.get(token) === tail) localTails.delete(token);
51267
51412
  }
@@ -52108,8 +52253,8 @@ function runRawWithEnv(args, env2, timeoutMs) {
52108
52253
  });
52109
52254
  });
52110
52255
  }
52111
- async function runJson(args) {
52112
- const { code, stdout, stderr } = await runRaw([...args, "--json"]);
52256
+ async function runJson(args, timeoutMs) {
52257
+ const { code, stdout, stderr } = await runRawWithEnv([...args, "--json"], void 0, timeoutMs);
52113
52258
  let env2;
52114
52259
  try {
52115
52260
  env2 = JSON.parse(stdout);
@@ -52648,7 +52793,7 @@ var aware = {
52648
52793
  * SHELL_META) and a large descriptor could blow cmd.exe's argv limit. Throws
52649
52794
  * AwareUnsupportedError on a pre-0.63 CLI so callers can degrade ("update AWARE").
52650
52795
  */
52651
- async agentInvoke(agent, command, inputs) {
52796
+ async agentInvoke(agent, command, inputs, opts = {}) {
52652
52797
  let inputsFile = null;
52653
52798
  try {
52654
52799
  let ref;
@@ -52657,7 +52802,7 @@ var aware = {
52657
52802
  (0, import_node_fs7.writeFileSync)(inputsFile, JSON.stringify(inputs));
52658
52803
  ref = `@${inputsFile}`;
52659
52804
  }
52660
- const { data } = await runJson(agentInvokeArgv(agent, command, ref));
52805
+ const { data } = await runJson(agentInvokeArgv(agent, command, ref), opts.timeoutMs);
52661
52806
  return data;
52662
52807
  } catch (err2) {
52663
52808
  if (err2 instanceof AwareError && isInvokeUnsupported(err2.detail)) {
@@ -53633,7 +53778,7 @@ function appVersion() {
53633
53778
  return resolveVersion({
53634
53779
  isSea: isSea2(),
53635
53780
  sqVersionXml: readSqVersionXml(),
53636
- define: true ? "0.106.0" : void 0,
53781
+ define: true ? "0.108.0" : void 0,
53637
53782
  pkgVersion: readPkgVersion()
53638
53783
  });
53639
53784
  }
@@ -53643,7 +53788,7 @@ function resolveChannel(s) {
53643
53788
  return "dev";
53644
53789
  }
53645
53790
  function appChannel() {
53646
- return resolveChannel({ isSea: isSea2(), define: true ? "0.106.0" : void 0 });
53791
+ return resolveChannel({ isSea: isSea2(), define: true ? "0.108.0" : void 0 });
53647
53792
  }
53648
53793
 
53649
53794
  // workflow-update.ts
@@ -54836,7 +54981,7 @@ function extractReportHtml(events) {
54836
54981
  var import_node_child_process4 = require("node:child_process");
54837
54982
  var import_node_fs14 = require("node:fs");
54838
54983
  var import_node_path13 = require("node:path");
54839
- var OPEN_EXTS = /* @__PURE__ */ new Set([".xls", ".xlsx", ".html", ".htm", ".csv", ".svg"]);
54984
+ var OPEN_EXTS = /* @__PURE__ */ new Set([".xls", ".xlsx", ".html", ".htm", ".csv", ".svg", ".png", ".mp4"]);
54840
54985
  var REVEAL_EXTS = /* @__PURE__ */ new Set([...OPEN_EXTS, ".ifc", ".nc1", ".dstv"]);
54841
54986
  function hasOpenableExt(path) {
54842
54987
  return OPEN_EXTS.has((0, import_node_path13.extname)(path).toLowerCase());
@@ -54846,13 +54991,13 @@ function validateOpenable(path, mode = "open") {
54846
54991
  if (path.includes("%")) return { ok: false, error: "unsupported file path" };
54847
54992
  const allowed = mode === "reveal" ? REVEAL_EXTS.has((0, import_node_path13.extname)(path).toLowerCase()) : hasOpenableExt(path);
54848
54993
  if (!allowed) return { ok: false, error: "unsupported file type" };
54849
- let isFile = false;
54994
+ let isFile2 = false;
54850
54995
  try {
54851
- isFile = (0, import_node_fs14.existsSync)(path) && (0, import_node_fs14.statSync)(path).isFile();
54996
+ isFile2 = (0, import_node_fs14.existsSync)(path) && (0, import_node_fs14.statSync)(path).isFile();
54852
54997
  } catch {
54853
- isFile = false;
54998
+ isFile2 = false;
54854
54999
  }
54855
- if (!isFile) return { ok: false, error: "file not found" };
55000
+ if (!isFile2) return { ok: false, error: "file not found" };
54856
55001
  return { ok: true, path };
54857
55002
  }
54858
55003
  function openFileCommand(path, platform = process.platform) {
@@ -58044,13 +58189,6 @@ var PreconditionFailedError = class extends Error {
58044
58189
  this.name = "PreconditionFailedError";
58045
58190
  }
58046
58191
  };
58047
- var StoreBusyError = class extends Error {
58048
- code = "store-busy";
58049
- constructor(message) {
58050
- super(message);
58051
- this.name = "StoreBusyError";
58052
- }
58053
- };
58054
58192
  var refused = /* @__PURE__ */ new Map();
58055
58193
  var REFUSAL_STORES_MAX = 256;
58056
58194
  function countRefusal(store) {
@@ -58116,17 +58254,9 @@ async function writeContractChecked(appId, doc, projectId, origin) {
58116
58254
  return { etag: etagOf(doc), conditional: !!(pre.ifMatch || pre.ifNoneMatch) };
58117
58255
  });
58118
58256
  } catch (e) {
58119
- if (e instanceof Error && /lifecycle lock/i.test(e.message)) {
58120
- throw new StoreBusyError("this project is busy publishing an export \u2014 try saving again in a moment");
58121
- }
58122
58257
  throw e;
58123
58258
  }
58124
- return run.catch((e) => {
58125
- if (e instanceof Error && /lifecycle lock/i.test(e.message)) {
58126
- throw new StoreBusyError("this project is busy publishing an export \u2014 try saving again in a moment");
58127
- }
58128
- throw e;
58129
- });
58259
+ return run;
58130
58260
  }
58131
58261
  function readAcceptedVersion(projectId, n, opts) {
58132
58262
  const doc = readVersion(projectId, n);
@@ -62434,7 +62564,9 @@ function projectExportFiles(appId, kindOf2 = appId) {
62434
62564
  return [
62435
62565
  { kind: "bom-csv", filename: `${appId}-bom.csv` },
62436
62566
  { kind: "bom-xlsx", filename: `${appId}-bom.xlsx` },
62437
- { kind: "ifc", filename: `${appId}.ifc` }
62567
+ { kind: "ifc", filename: `${appId}.ifc` },
62568
+ { kind: "render-png", filename: `${appId}-render.png` },
62569
+ { kind: "render-mp4", filename: `${appId}-turntable.mp4` }
62438
62570
  ];
62439
62571
  }
62440
62572
  function sanitizeExportName(name) {
@@ -62485,7 +62617,9 @@ var EXTENSIONS = {
62485
62617
  "bom-csv": ".csv",
62486
62618
  "bom-xlsx": ".xlsx",
62487
62619
  ifc: ".ifc",
62488
- svg: ".svg"
62620
+ svg: ".svg",
62621
+ "render-png": ".png",
62622
+ "render-mp4": ".mp4"
62489
62623
  };
62490
62624
  var RESERVED2 = /^\.floless-(?:txn|cleanup|tmp|backup)-/i;
62491
62625
  var projectExportIndexPath = (projectId) => (0, import_node_path25.join)(projectExportsDir(projectId), "index.json");
@@ -62505,12 +62639,22 @@ function validReceiptFilename(kind, filename) {
62505
62639
  if (!isPortablePlainFilename(filename) || filename === "index.json" || RESERVED2.test(filename) || (0, import_node_path25.basename)(filename) !== filename) return false;
62506
62640
  return filename.toLowerCase().endsWith(EXTENSIONS[kind]);
62507
62641
  }
62642
+ function isExportKind(v) {
62643
+ return typeof v === "string" && Object.prototype.hasOwnProperty.call(EXTENSIONS, v);
62644
+ }
62645
+ var VARIANT = /^[a-z0-9][a-z0-9-]{0,31}$/;
62646
+ function isValidVariant(v) {
62647
+ return v === void 0 || typeof v === "string" && VARIANT.test(v);
62648
+ }
62649
+ function receiptKey(kind, variant) {
62650
+ return `${kind}\0${variant ?? ""}`;
62651
+ }
62508
62652
  function isReceipt(v) {
62509
62653
  if (!v || typeof v !== "object" || Array.isArray(v)) return false;
62510
62654
  const r = v;
62511
62655
  const kind = r.kind;
62512
- if (kind !== "bom-csv" && kind !== "bom-xlsx" && kind !== "ifc" && kind !== "svg") return false;
62513
- return typeof r.filename === "string" && validReceiptFilename(kind, r.filename) && typeof r.exportId === "string" && !!r.exportId.trim() && typeof r.exportedAt === "string" && Number.isFinite(Date.parse(r.exportedAt)) && typeof r.bytes === "number" && Number.isSafeInteger(r.bytes) && r.bytes >= 0 && typeof r.version === "number" && Number.isSafeInteger(r.version) && r.version > 0 && typeof r.contractHash === "string" && /^[a-f0-9]{64}$/i.test(r.contractHash) && (r.encoding === void 0 || r.encoding === "utf8" || r.encoding === "base64");
62656
+ if (!isExportKind(kind)) return false;
62657
+ return isValidVariant(r.variant) && typeof r.filename === "string" && validReceiptFilename(kind, r.filename) && typeof r.exportId === "string" && !!r.exportId.trim() && typeof r.exportedAt === "string" && Number.isFinite(Date.parse(r.exportedAt)) && typeof r.bytes === "number" && Number.isSafeInteger(r.bytes) && r.bytes >= 0 && typeof r.version === "number" && Number.isSafeInteger(r.version) && r.version > 0 && typeof r.contractHash === "string" && /^[a-f0-9]{64}$/i.test(r.contractHash) && (r.encoding === void 0 || r.encoding === "utf8" || r.encoding === "base64");
62514
62658
  }
62515
62659
  function validateInput(receipt) {
62516
62660
  if (!validReceiptFilename(receipt.kind, receipt.filename)) {
@@ -62527,6 +62671,11 @@ function validateInput(receipt) {
62527
62671
  if (!/^[a-f0-9]{64}$/i.test(receipt.contractHash)) {
62528
62672
  throw new ProjectExportReceiptError("export receipt contractHash must be a SHA-256 hex digest.");
62529
62673
  }
62674
+ if (!isValidVariant(receipt.variant)) {
62675
+ throw new ProjectExportReceiptError(
62676
+ `invalid export receipt variant ${JSON.stringify(receipt.variant)}; expected a short lowercase slug.`
62677
+ );
62678
+ }
62530
62679
  }
62531
62680
  function parseIndexBytes(bytes) {
62532
62681
  let parsed;
@@ -62541,20 +62690,42 @@ function parseIndexBytes(bytes) {
62541
62690
  throw new ProjectExportReceiptError("project export index must be an object.");
62542
62691
  }
62543
62692
  const exportsValue = parsed.exports;
62544
- if (!Array.isArray(exportsValue) || !exportsValue.every(isReceipt)) {
62693
+ if (!Array.isArray(exportsValue)) {
62545
62694
  throw new ProjectExportReceiptError("project export index contains an invalid receipt.");
62546
62695
  }
62547
- const kinds = /* @__PURE__ */ new Set();
62548
- for (const receipt of exportsValue) {
62549
- if (kinds.has(receipt.kind)) {
62550
- throw new ProjectExportReceiptError(`project export index contains duplicate "${receipt.kind}" receipts.`);
62696
+ const kept = [];
62697
+ const opaque = [];
62698
+ const seen = /* @__PURE__ */ new Set();
62699
+ const dropped = [];
62700
+ for (const row of exportsValue) {
62701
+ const kind = row?.kind;
62702
+ if (!isExportKind(kind)) {
62703
+ dropped.push(`unknown kind ${JSON.stringify(kind)}`);
62704
+ opaque.push(row);
62705
+ continue;
62706
+ }
62707
+ if (!isReceipt(row)) {
62708
+ throw new ProjectExportReceiptError("project export index contains an invalid receipt.");
62709
+ }
62710
+ const key = receiptKey(row.kind, row.variant);
62711
+ if (seen.has(key)) {
62712
+ dropped.push(`duplicate "${key.trim()}"`);
62713
+ opaque.push(row);
62714
+ continue;
62551
62715
  }
62552
- kinds.add(receipt.kind);
62716
+ seen.add(key);
62717
+ kept.push(row);
62718
+ }
62719
+ if (dropped.length) {
62720
+ console.warn(
62721
+ `project export index: ignored ${dropped.length} unreadable receipt(s) \u2014 ${dropped.join(", ")}`
62722
+ );
62553
62723
  }
62554
- return { exports: exportsValue };
62724
+ return { exports: kept, opaque };
62555
62725
  }
62556
62726
  function indexBytes(body) {
62557
- return Buffer.from(`${JSON.stringify(body, null, 2)}
62727
+ const exports2 = [...body.exports, ...body.opaque];
62728
+ return Buffer.from(`${JSON.stringify({ exports: exports2 }, null, 2)}
62558
62729
  `, "utf8");
62559
62730
  }
62560
62731
  function syncFile(path) {
@@ -62595,7 +62766,7 @@ function durableReplace(path, bytes) {
62595
62766
  }
62596
62767
  function strictCurrent(projectId) {
62597
62768
  const path = projectExportIndexPath(projectId);
62598
- if (!(0, import_node_fs27.existsSync)(path)) return { bytes: null, body: { exports: [] } };
62769
+ if (!(0, import_node_fs27.existsSync)(path)) return { bytes: null, body: { exports: [], opaque: [] } };
62599
62770
  const bytes = (0, import_node_fs27.readFileSync)(path);
62600
62771
  return { bytes, body: parseIndexBytes(bytes) };
62601
62772
  }
@@ -62617,15 +62788,35 @@ function prepareProjectExport(projectId, receipt) {
62617
62788
  const dir = projectExportsDir(projectId);
62618
62789
  (0, import_node_fs27.mkdirSync)(dir, { recursive: true });
62619
62790
  const current = strictCurrent(projectId);
62620
- const prior = current.body.exports.find((row) => row.kind === receipt.kind) ?? null;
62791
+ const key = receiptKey(receipt.kind, receipt.variant);
62792
+ const prior = current.body.exports.find((row) => receiptKey(row.kind, row.variant) === key) ?? null;
62793
+ const rest = current.body.exports.filter((row) => receiptKey(row.kind, row.variant) !== key);
62794
+ const clash = rest.find((row) => row.filename === receipt.filename);
62795
+ if (clash) {
62796
+ throw new ProjectExportReceiptError(
62797
+ `export filename "${receipt.filename}" is already held by the "${receiptKey(clash.kind, clash.variant).trim()}" receipt.`
62798
+ );
62799
+ }
62800
+ if (current.body.opaque.some((row) => row?.filename === receipt.filename)) {
62801
+ throw new ProjectExportReceiptError(
62802
+ `export filename "${receipt.filename}" is already held by a receipt this version cannot read.`
62803
+ );
62804
+ }
62621
62805
  const next = {
62622
62806
  ...receipt,
62623
- exportId: `${receipt.version}-${receipt.kind}-${receipt.contractHash.slice(0, 12)}`,
62807
+ exportId: [receipt.version, receipt.kind, receipt.variant, receipt.contractHash.slice(0, 12)].filter(Boolean).join("-"),
62624
62808
  exportedAt: (/* @__PURE__ */ new Date()).toISOString()
62625
62809
  };
62626
- const rest = current.body.exports.filter((row) => row.kind !== receipt.kind);
62627
62810
  const afterBytes = indexBytes({
62628
- exports: [...rest, next].sort((a, b) => a.kind.localeCompare(b.kind))
62811
+ exports: [...rest, next].sort((a, b) => {
62812
+ const ka = receiptKey(a.kind, a.variant);
62813
+ const kb = receiptKey(b.kind, b.variant);
62814
+ return ka < kb ? -1 : ka > kb ? 1 : 0;
62815
+ }),
62816
+ // Carried, not dropped. `before` proves the ORIGINAL bytes and the CAS compares against them,
62817
+ // so building `after` from the filtered set would let the commit succeed while quietly deleting
62818
+ // every row this build could not read.
62819
+ opaque: current.body.opaque
62629
62820
  });
62630
62821
  return {
62631
62822
  projectId,
@@ -62675,6 +62866,15 @@ function restoreProjectExportTransition(transition) {
62675
62866
  function cleanupSupersededProjectExport(transition) {
62676
62867
  const superseded = transition.superseded;
62677
62868
  if (!superseded || superseded.filename === transition.next.filename) return;
62869
+ let stillReferenced = listProjectExportReceipts(transition.projectId).some((row) => row.filename === superseded.filename);
62870
+ if (!stillReferenced) {
62871
+ try {
62872
+ stillReferenced = strictCurrent(transition.projectId).body.opaque.some((row) => row?.filename === superseded.filename);
62873
+ } catch {
62874
+ stillReferenced = true;
62875
+ }
62876
+ }
62877
+ if (stillReferenced) return;
62678
62878
  const path = resolveProjectExportReceiptPath(transition.projectId, superseded);
62679
62879
  if (!path) return;
62680
62880
  try {
@@ -62771,7 +62971,14 @@ function currentApprovedSnapshot(projectId, version) {
62771
62971
  // workspace-data.ts
62772
62972
  var import_node_fs28 = require("node:fs");
62773
62973
  var VALID_INCLUDES = /* @__PURE__ */ new Set(["contract", "exports"]);
62774
- var VALID_EXPORT_KINDS = /* @__PURE__ */ new Set(["bom-csv", "bom-xlsx", "ifc", "svg"]);
62974
+ var VALID_EXPORT_KINDS = /* @__PURE__ */ new Set([
62975
+ "bom-csv",
62976
+ "bom-xlsx",
62977
+ "ifc",
62978
+ "svg",
62979
+ "render-png",
62980
+ "render-mp4"
62981
+ ]);
62775
62982
  var DEFAULT_MAX_BYTES = 1024 * 1024;
62776
62983
  function sendError(reply, status, error) {
62777
62984
  return reply.status(status).send({ ok: false, error });
@@ -62807,6 +63014,11 @@ function exportBody(projectId, receipt, opts) {
62807
63014
  if (!path) throw new Error(`invalid project export receipt path: ${receipt.filename}`);
62808
63015
  const body = {
62809
63016
  kind: receipt.kind,
63017
+ // A kind can now hold several artifacts — one render per viewpoint. Without the variant a
63018
+ // workflow asking for `render-png` receives rows it cannot tell apart, and picking "the hero
63019
+ // one" would mean parsing it back out of the filename. Omitted entirely for the single-artifact
63020
+ // kinds, so nothing gains an always-undefined field.
63021
+ ...receipt.variant ? { variant: receipt.variant } : {},
62810
63022
  filename: receipt.filename,
62811
63023
  exportId: receipt.exportId,
62812
63024
  exportedAt: receipt.exportedAt,
@@ -69911,6 +70123,165 @@ async function teklaReadiness(deps = DEFAULT_DEPS) {
69911
70123
  }
69912
70124
  }
69913
70125
 
70126
+ // render-readiness.ts
70127
+ var import_node_fs35 = require("node:fs");
70128
+ var import_node_path31 = require("node:path");
70129
+ var import_node_os18 = require("node:os");
70130
+ var RENDER_AWARE_FLOOR = "0.103.0";
70131
+ var RENDER_AGENT_ID = "blender";
70132
+ function isFile(path) {
70133
+ try {
70134
+ return (0, import_node_fs35.existsSync)(path) && (0, import_node_fs35.statSync)(path).isFile();
70135
+ } catch {
70136
+ return false;
70137
+ }
70138
+ }
70139
+ function lookupOnPath(command, env2) {
70140
+ const path = env2.PATH ?? env2.Path;
70141
+ if (!path) return null;
70142
+ for (const dir of path.split(import_node_path31.delimiter)) {
70143
+ if (!dir) continue;
70144
+ const candidate = (0, import_node_path31.join)(dir, command);
70145
+ if (isFile(candidate)) return candidate;
70146
+ }
70147
+ return null;
70148
+ }
70149
+ function compareVersionParts(a, b) {
70150
+ for (let i = 0; i < Math.max(a.length, b.length); i += 1) {
70151
+ const diff = (a[i] ?? 0) - (b[i] ?? 0);
70152
+ if (diff !== 0) return diff;
70153
+ }
70154
+ return 0;
70155
+ }
70156
+ function windowsCandidates(env2) {
70157
+ const roots = [];
70158
+ for (const variable of ["ProgramFiles", "ProgramW6432", "ProgramFiles(x86)"]) {
70159
+ const value = env2[variable];
70160
+ if (!value) continue;
70161
+ const root3 = (0, import_node_path31.join)(value, "Blender Foundation");
70162
+ if (!roots.includes(root3)) roots.push(root3);
70163
+ }
70164
+ const found = [];
70165
+ for (const root3 of roots) {
70166
+ let entries;
70167
+ try {
70168
+ entries = (0, import_node_fs35.readdirSync)(root3);
70169
+ } catch {
70170
+ continue;
70171
+ }
70172
+ for (const name of entries) {
70173
+ const match = /^Blender\s+(\d+(?:\.\d+)*)$/i.exec(name);
70174
+ if (!match) continue;
70175
+ const binary = (0, import_node_path31.join)(root3, name, "blender.exe");
70176
+ if (isFile(binary)) {
70177
+ found.push({ version: match[1].split(".").map(Number), name, binary });
70178
+ }
70179
+ }
70180
+ }
70181
+ found.sort((a, b) => compareVersionParts(b.version, a.version) || b.name.localeCompare(a.name));
70182
+ return found.map((row) => row.binary);
70183
+ }
70184
+ function platformDefaults(env2, isWin3) {
70185
+ if (isWin3) return windowsCandidates(env2);
70186
+ if (process.platform === "darwin") {
70187
+ return [
70188
+ "/Applications/Blender.app/Contents/MacOS/Blender",
70189
+ (0, import_node_path31.join)((0, import_node_os18.homedir)(), "Applications/Blender.app/Contents/MacOS/Blender")
70190
+ ];
70191
+ }
70192
+ return ["/usr/bin/blender", "/usr/local/bin/blender", "/snap/bin/blender"];
70193
+ }
70194
+ function findBlender(env2 = process.env) {
70195
+ const isWin3 = process.platform === "win32";
70196
+ const override = env2.AWARE_BLENDER?.trim();
70197
+ if (override) {
70198
+ return isFile(override) ? override : null;
70199
+ }
70200
+ const onPath = lookupOnPath(isWin3 ? "blender.exe" : "blender", env2);
70201
+ if (onPath) return onPath;
70202
+ for (const candidate of platformDefaults(env2, isWin3)) {
70203
+ if (isFile(candidate)) return candidate;
70204
+ }
70205
+ return null;
70206
+ }
70207
+ var DEFAULT_DEPS2 = {
70208
+ npmVersion: () => aware.npmVersion(),
70209
+ installedAgentIds: async () => (await aware.agentList()).map((row) => row.id),
70210
+ locateBlender: () => findBlender()
70211
+ };
70212
+ async function renderReadiness(deps = DEFAULT_DEPS2) {
70213
+ try {
70214
+ const version = deps.npmVersion();
70215
+ const current = !!version && compareSemver(version, RENDER_AWARE_FLOOR) >= 0;
70216
+ const base = {
70217
+ aware: { version, floor: RENDER_AWARE_FLOOR, current },
70218
+ agent: { installed: false },
70219
+ blender: { present: false, path: null }
70220
+ };
70221
+ if (!current) {
70222
+ return {
70223
+ ...base,
70224
+ ok: false,
70225
+ state: "aware-update-required",
70226
+ message: `AWARE ${RENDER_AWARE_FLOOR} or newer is required to render images.`,
70227
+ recovery: { action: "update-aware", label: "Update AWARE" }
70228
+ };
70229
+ }
70230
+ const installed = (await deps.installedAgentIds()).includes(RENDER_AGENT_ID);
70231
+ if (!installed) {
70232
+ return {
70233
+ ...base,
70234
+ ok: false,
70235
+ state: "agent-missing",
70236
+ message: "The Blender agent is not installed yet.",
70237
+ recovery: { action: "install-agent", label: "Install agent" }
70238
+ };
70239
+ }
70240
+ const blenderPath = deps.locateBlender();
70241
+ if (!blenderPath) {
70242
+ const override = process.env.AWARE_BLENDER?.trim();
70243
+ return {
70244
+ ...base,
70245
+ agent: { installed: true },
70246
+ ok: false,
70247
+ state: "blender-missing",
70248
+ message: override ? `AWARE_BLENDER is set to "${override}", but no file is readable there.` : "Blender was not found on this computer. It is a free download.",
70249
+ recovery: override ? { action: "retry", label: "Check again" } : { action: "install-blender", label: "How to install" }
70250
+ };
70251
+ }
70252
+ return {
70253
+ ...base,
70254
+ agent: { installed: true },
70255
+ blender: { present: true, path: blenderPath },
70256
+ ok: true,
70257
+ state: "ready",
70258
+ message: "Ready to render.",
70259
+ recovery: null
70260
+ };
70261
+ } catch (error) {
70262
+ return {
70263
+ ok: false,
70264
+ state: "error",
70265
+ message: error instanceof Error ? error.message : "Could not check whether rendering is available.",
70266
+ recovery: { action: "retry", label: "Check again" },
70267
+ aware: { version: null, floor: RENDER_AWARE_FLOOR, current: false },
70268
+ agent: { installed: false },
70269
+ blender: { present: false, path: null }
70270
+ };
70271
+ }
70272
+ }
70273
+
70274
+ // render-cost.ts
70275
+ var RENDER_COST_SECONDS = {
70276
+ still: { draft: [8, 15], production: [50, 115] },
70277
+ turntable: { draft: [390, 540], production: [390, 540] }
70278
+ };
70279
+ function renderExpectedMs(output, quality, viewpoints) {
70280
+ const effective = output === "turntable" ? "draft" : quality;
70281
+ const [, hi] = RENDER_COST_SECONDS[output][effective];
70282
+ return hi * 1e3 * Math.max(1, viewpoints);
70283
+ }
70284
+
69914
70285
  // downstream-bake.ts
69915
70286
  async function bakeDownstream(sourcePath, appId, contract) {
69916
70287
  const { scene } = contractToScene(contract);
@@ -69935,20 +70306,20 @@ async function bakeDownstream(sourcePath, appId, contract) {
69935
70306
  }
69936
70307
 
69937
70308
  // app-lifecycle.ts
70309
+ var import_node_fs38 = require("node:fs");
70310
+ var import_node_os20 = require("node:os");
70311
+ var import_node_path34 = require("node:path");
70312
+
70313
+ // routines.ts
69938
70314
  var import_node_fs37 = require("node:fs");
69939
- var import_node_os19 = require("node:os");
69940
70315
  var import_node_path33 = require("node:path");
69941
70316
 
69942
- // routines.ts
70317
+ // trigger-sessions.ts
69943
70318
  var import_node_fs36 = require("node:fs");
70319
+ var import_node_os19 = require("node:os");
69944
70320
  var import_node_path32 = require("node:path");
69945
-
69946
- // trigger-sessions.ts
69947
- var import_node_fs35 = require("node:fs");
69948
- var import_node_os18 = require("node:os");
69949
- var import_node_path31 = require("node:path");
69950
70321
  var import_yaml9 = __toESM(require_dist6(), 1);
69951
- var AGENTS_DIR2 = process.env.AWARE_HOME ? (0, import_node_path31.join)(process.env.AWARE_HOME, "agents") : (0, import_node_path31.join)((0, import_node_os18.homedir)(), ".aware", "agents");
70322
+ var AGENTS_DIR2 = process.env.AWARE_HOME ? (0, import_node_path32.join)(process.env.AWARE_HOME, "agents") : (0, import_node_path32.join)((0, import_node_os19.homedir)(), ".aware", "agents");
69952
70323
  function summarizeFire(data) {
69953
70324
  if (!data) return "event";
69954
70325
  const type = typeof data.type === "string" ? data.type : "";
@@ -69965,10 +70336,10 @@ function mapTriggerState(phase) {
69965
70336
  function isHostBacked(agent, agentsDir = AGENTS_DIR2) {
69966
70337
  const safe2 = (n) => !n.includes("/") && !n.includes("\\") && !n.includes("..");
69967
70338
  if (!safe2(agent)) return false;
69968
- const manifestPath2 = (0, import_node_path31.join)(agentsDir, agent, "manifest.yaml");
69969
- if (!(0, import_node_fs35.existsSync)(manifestPath2)) return false;
70339
+ const manifestPath2 = (0, import_node_path32.join)(agentsDir, agent, "manifest.yaml");
70340
+ if (!(0, import_node_fs36.existsSync)(manifestPath2)) return false;
69970
70341
  try {
69971
- const doc = (0, import_yaml9.parse)((0, import_node_fs35.readFileSync)(manifestPath2, "utf8"));
70342
+ const doc = (0, import_yaml9.parse)((0, import_node_fs36.readFileSync)(manifestPath2, "utf8"));
69972
70343
  const transport = doc?.transport;
69973
70344
  return !!(transport && typeof transport === "object" && "cli" in transport);
69974
70345
  } catch {
@@ -70253,7 +70624,7 @@ var RoutineError = class extends Error {
70253
70624
  }
70254
70625
  status;
70255
70626
  };
70256
- var ROUTINES_FILE = (0, import_node_path32.join)(flolessRoot, "routines.json");
70627
+ var ROUTINES_FILE = (0, import_node_path33.join)(flolessRoot, "routines.json");
70257
70628
  var routines = [];
70258
70629
  var loaded = false;
70259
70630
  function ensureLoaded() {
@@ -70289,10 +70660,10 @@ function sanitizeRoutine(raw) {
70289
70660
  };
70290
70661
  }
70291
70662
  function loadFromDisk() {
70292
- if (!(0, import_node_fs36.existsSync)(ROUTINES_FILE)) return [];
70663
+ if (!(0, import_node_fs37.existsSync)(ROUTINES_FILE)) return [];
70293
70664
  let text2;
70294
70665
  try {
70295
- text2 = (0, import_node_fs36.readFileSync)(ROUTINES_FILE, "utf8");
70666
+ text2 = (0, import_node_fs37.readFileSync)(ROUTINES_FILE, "utf8");
70296
70667
  } catch {
70297
70668
  return [];
70298
70669
  }
@@ -70301,17 +70672,17 @@ function loadFromDisk() {
70301
70672
  return Array.isArray(parsed) ? parsed.map(sanitizeRoutine).filter((r) => r !== null) : [];
70302
70673
  } catch {
70303
70674
  try {
70304
- (0, import_node_fs36.renameSync)(ROUTINES_FILE, `${ROUTINES_FILE}.corrupt-${Date.now()}`);
70675
+ (0, import_node_fs37.renameSync)(ROUTINES_FILE, `${ROUTINES_FILE}.corrupt-${Date.now()}`);
70305
70676
  } catch {
70306
70677
  }
70307
70678
  return [];
70308
70679
  }
70309
70680
  }
70310
70681
  function saveRoutines() {
70311
- if (!(0, import_node_fs36.existsSync)(flolessRoot)) (0, import_node_fs36.mkdirSync)(flolessRoot, { recursive: true });
70682
+ if (!(0, import_node_fs37.existsSync)(flolessRoot)) (0, import_node_fs37.mkdirSync)(flolessRoot, { recursive: true });
70312
70683
  const tmp = `${ROUTINES_FILE}.${process.pid}.tmp`;
70313
- (0, import_node_fs36.writeFileSync)(tmp, JSON.stringify(routines, null, 2));
70314
- (0, import_node_fs36.renameSync)(tmp, ROUTINES_FILE);
70684
+ (0, import_node_fs37.writeFileSync)(tmp, JSON.stringify(routines, null, 2));
70685
+ (0, import_node_fs37.renameSync)(tmp, ROUTINES_FILE);
70315
70686
  }
70316
70687
  function listRoutines() {
70317
70688
  ensureLoaded();
@@ -70719,13 +71090,13 @@ var AppLifecycleError = class extends Error {
70719
71090
  }
70720
71091
  };
70721
71092
  function appsDir() {
70722
- return process.env.AWARE_HOME ? (0, import_node_path33.join)(process.env.AWARE_HOME, "apps") : (0, import_node_path33.join)((0, import_node_os19.homedir)(), ".aware", "apps");
71093
+ return process.env.AWARE_HOME ? (0, import_node_path34.join)(process.env.AWARE_HOME, "apps") : (0, import_node_path34.join)((0, import_node_os20.homedir)(), ".aware", "apps");
70723
71094
  }
70724
71095
  function appDirPath(id) {
70725
- return (0, import_node_path33.join)(appsDir(), id);
71096
+ return (0, import_node_path34.join)(appsDir(), id);
70726
71097
  }
70727
71098
  function appInstalled(id) {
70728
- return APP_ID3.test(id) && (0, import_node_fs37.existsSync)(appDirPath(id));
71099
+ return APP_ID3.test(id) && (0, import_node_fs38.existsSync)(appDirPath(id));
70729
71100
  }
70730
71101
  function logCascade(what, e) {
70731
71102
  console.error(`[app-lifecycle] cascade step failed (${what}):`, e instanceof Error ? e.message : e);
@@ -70874,7 +71245,11 @@ var AWARE_ROUTES = [
70874
71245
  "/api/graft",
70875
71246
  "/api/run",
70876
71247
  "/api/debug",
70877
- "/api/tekla-readiness"
71248
+ "/api/tekla-readiness",
71249
+ // Mirrors /api/tekla-readiness. `/api/render/readiness` shells `aware agent list` and fires
71250
+ // automatically on every Exports-tab open — not only on a deliberate click — and
71251
+ // `/api/render/install-agent` shells `aware agent install`. Both must wait for bootstrap.
71252
+ "/api/render"
70878
71253
  ];
70879
71254
  var GATE_EXEMPT = /* @__PURE__ */ new Set(["/api/run/stop"]);
70880
71255
  var GATE_EXEMPT_PREFIXES = ["/api/bootstrap/"];
@@ -70890,16 +71265,19 @@ function isGatedAwareRoute(url, method) {
70890
71265
  if (path === "/api/trigger-run") return m === "POST";
70891
71266
  if (path.startsWith("/api/app/")) return m === "PATCH" || m === "POST" || m === "DELETE";
70892
71267
  if (path.startsWith("/api/contract/")) {
70893
- return m === "POST" && (path.endsWith("/approve") || path.endsWith("/export-3d") || path.endsWith("/export-ifc") || path.endsWith("/export-tekla"));
71268
+ return m === "POST" && (path.endsWith("/approve") || path.endsWith("/export-3d") || path.endsWith("/export-ifc") || path.endsWith("/export-tekla") || // `aware agent invoke` twice (ifc/write then the blender render). The `m === 'POST'` test
71269
+ // above is what keeps the `render-preview` GET out of here — that one only reads a file
71270
+ // off disk and must stay available while AWARE is still installing.
71271
+ path.endsWith("/render"));
70894
71272
  }
70895
71273
  return AWARE_ROUTES.some((p) => path.startsWith(p));
70896
71274
  }
70897
71275
 
70898
71276
  // autostart.mjs
70899
71277
  var import_node_child_process6 = require("node:child_process");
70900
- var import_node_fs38 = require("node:fs");
70901
- var import_node_os20 = require("node:os");
70902
- var import_node_path34 = require("node:path");
71278
+ var import_node_fs39 = require("node:fs");
71279
+ var import_node_os21 = require("node:os");
71280
+ var import_node_path35 = require("node:path");
70903
71281
 
70904
71282
  // teardown.mjs
70905
71283
  var RUN_KEY = "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run";
@@ -71011,8 +71389,8 @@ function removeLegacyRunKey() {
71011
71389
  }
71012
71390
  function logLine(msg) {
71013
71391
  try {
71014
- (0, import_node_fs38.mkdirSync)(logDir(), { recursive: true });
71015
- (0, import_node_fs38.appendFileSync)(logFilePath(), `${(/* @__PURE__ */ new Date()).toISOString()} ${msg}
71392
+ (0, import_node_fs39.mkdirSync)(logDir(), { recursive: true });
71393
+ (0, import_node_fs39.appendFileSync)(logFilePath(), `${(/* @__PURE__ */ new Date()).toISOString()} ${msg}
71016
71394
  `);
71017
71395
  } catch {
71018
71396
  }
@@ -71020,8 +71398,8 @@ function logLine(msg) {
71020
71398
  function registerAutostart(exePath) {
71021
71399
  if (!isWin) return;
71022
71400
  const xml = buildAutostartTaskXml(exePath, currentUserId());
71023
- const tmp = (0, import_node_path34.join)((0, import_node_os20.tmpdir)(), `floless-autostart-${process.pid}-${Date.now()}.xml`);
71024
- (0, import_node_fs38.writeFileSync)(tmp, "\uFEFF" + xml, { encoding: "utf16le" });
71401
+ const tmp = (0, import_node_path35.join)((0, import_node_os21.tmpdir)(), `floless-autostart-${process.pid}-${Date.now()}.xml`);
71402
+ (0, import_node_fs39.writeFileSync)(tmp, "\uFEFF" + xml, { encoding: "utf16le" });
71025
71403
  try {
71026
71404
  (0, import_node_child_process6.execFileSync)("schtasks", ["/Create", "/TN", TASK_NAME, "/XML", tmp, "/F"], {
71027
71405
  stdio: ["ignore", "ignore", "ignore"],
@@ -71032,7 +71410,7 @@ function registerAutostart(exePath) {
71032
71410
  throw err2;
71033
71411
  } finally {
71034
71412
  try {
71035
- (0, import_node_fs38.rmSync)(tmp, { force: true });
71413
+ (0, import_node_fs39.rmSync)(tmp, { force: true });
71036
71414
  } catch {
71037
71415
  }
71038
71416
  }
@@ -71067,26 +71445,26 @@ function unregisterAutostart() {
71067
71445
  // updater.ts
71068
71446
  var import_node_child_process7 = require("node:child_process");
71069
71447
  var import_node_crypto19 = require("node:crypto");
71070
- var import_node_fs40 = require("node:fs");
71448
+ var import_node_fs41 = require("node:fs");
71071
71449
  var import_node_stream3 = require("node:stream");
71072
71450
  var import_promises3 = require("node:stream/promises");
71073
- var import_node_path36 = require("node:path");
71451
+ var import_node_path37 = require("node:path");
71074
71452
 
71075
71453
  // post-update-marker.mjs
71076
- var import_node_fs39 = require("node:fs");
71077
- var import_node_os21 = require("node:os");
71078
- var import_node_path35 = require("node:path");
71454
+ var import_node_fs40 = require("node:fs");
71455
+ var import_node_os22 = require("node:os");
71456
+ var import_node_path36 = require("node:path");
71079
71457
  var FRESH_MS = 12e4;
71080
71458
  function markerPath() {
71081
71459
  const override = (process.env.FLOLESS_POST_UPDATE_MARKER ?? "").trim();
71082
71460
  if (override) return override;
71083
- const root3 = process.env.FLOLESS_HOME ?? (0, import_node_path35.join)((0, import_node_os21.homedir)(), ".floless");
71084
- return (0, import_node_path35.join)(root3, ".post-update");
71461
+ const root3 = process.env.FLOLESS_HOME ?? (0, import_node_path36.join)((0, import_node_os22.homedir)(), ".floless");
71462
+ return (0, import_node_path36.join)(root3, ".post-update");
71085
71463
  }
71086
71464
  function legacyMarkerPath() {
71087
71465
  if ((process.env.FLOLESS_POST_UPDATE_MARKER ?? "").trim()) return null;
71088
71466
  try {
71089
- return (0, import_node_path35.join)((0, import_node_path35.dirname)((0, import_node_path35.dirname)(process.execPath)), ".floless-post-update");
71467
+ return (0, import_node_path36.join)((0, import_node_path36.dirname)((0, import_node_path36.dirname)(process.execPath)), ".floless-post-update");
71090
71468
  } catch {
71091
71469
  return null;
71092
71470
  }
@@ -71096,7 +71474,7 @@ function writePostUpdateMarker() {
71096
71474
  for (const p of [markerPath(), legacyMarkerPath()]) {
71097
71475
  if (!p) continue;
71098
71476
  try {
71099
- (0, import_node_fs39.writeFileSync)(p, (/* @__PURE__ */ new Date()).toISOString());
71477
+ (0, import_node_fs40.writeFileSync)(p, (/* @__PURE__ */ new Date()).toISOString());
71100
71478
  wrote = true;
71101
71479
  } catch {
71102
71480
  }
@@ -71108,9 +71486,9 @@ function consumePostUpdateMarker() {
71108
71486
  for (const p of [markerPath(), legacyMarkerPath()]) {
71109
71487
  if (!p) continue;
71110
71488
  try {
71111
- if (!(0, import_node_fs39.existsSync)(p)) continue;
71112
- const ageMs = Date.now() - (0, import_node_fs39.statSync)(p).mtimeMs;
71113
- (0, import_node_fs39.rmSync)(p, { force: true });
71489
+ if (!(0, import_node_fs40.existsSync)(p)) continue;
71490
+ const ageMs = Date.now() - (0, import_node_fs40.statSync)(p).mtimeMs;
71491
+ (0, import_node_fs40.rmSync)(p, { force: true });
71114
71492
  if (ageMs < FRESH_MS) fresh = true;
71115
71493
  } catch {
71116
71494
  }
@@ -71127,13 +71505,13 @@ function currentVersion() {
71127
71505
  return appVersion();
71128
71506
  }
71129
71507
  function installRoot() {
71130
- return (0, import_node_path36.dirname)((0, import_node_path36.dirname)(process.execPath));
71508
+ return (0, import_node_path37.dirname)((0, import_node_path37.dirname)(process.execPath));
71131
71509
  }
71132
71510
  function updateExePath() {
71133
- return (0, import_node_path36.join)(installRoot(), "Update.exe");
71511
+ return (0, import_node_path37.join)(installRoot(), "Update.exe");
71134
71512
  }
71135
71513
  function packagesDir() {
71136
- return (0, import_node_path36.join)(installRoot(), "packages");
71514
+ return (0, import_node_path37.join)(installRoot(), "packages");
71137
71515
  }
71138
71516
  function feedUrl() {
71139
71517
  const env2 = (process.env.FLOLESS_UPDATE_URL ?? "").trim().replace(/\/+$/, "");
@@ -71226,22 +71604,22 @@ async function checkForUpdate() {
71226
71604
  }
71227
71605
  async function sha1OfFile(path) {
71228
71606
  const hash2 = (0, import_node_crypto19.createHash)("sha1");
71229
- await (0, import_promises3.pipeline)((0, import_node_fs40.createReadStream)(path), hash2);
71607
+ await (0, import_promises3.pipeline)((0, import_node_fs41.createReadStream)(path), hash2);
71230
71608
  return hash2.digest("hex").toUpperCase();
71231
71609
  }
71232
71610
  async function downloadPackage(asset) {
71233
71611
  if (!NUPKG_NAME.test(asset.FileName)) throw new Error(`refusing suspicious package name: ${asset.FileName}`);
71234
71612
  const want = asset.SHA1.toUpperCase();
71235
71613
  const dir = packagesDir();
71236
- (0, import_node_fs40.mkdirSync)(dir, { recursive: true });
71237
- const dest = (0, import_node_path36.join)(dir, asset.FileName);
71238
- if ((0, import_node_fs40.existsSync)(dest) && await sha1OfFile(dest) === want) return dest;
71614
+ (0, import_node_fs41.mkdirSync)(dir, { recursive: true });
71615
+ const dest = (0, import_node_path37.join)(dir, asset.FileName);
71616
+ if ((0, import_node_fs41.existsSync)(dest) && await sha1OfFile(dest) === want) return dest;
71239
71617
  const res = await authedFetch(`${feedUrl()}/${encodeURIComponent(asset.FileName)}`, {
71240
71618
  redirect: "follow",
71241
71619
  signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS)
71242
71620
  });
71243
71621
  if (!res.ok || !res.body) throw new Error(`download failed: HTTP ${res.status} for ${asset.FileName}`);
71244
- await (0, import_promises3.pipeline)(import_node_stream3.Readable.fromWeb(res.body), (0, import_node_fs40.createWriteStream)(dest));
71622
+ await (0, import_promises3.pipeline)(import_node_stream3.Readable.fromWeb(res.body), (0, import_node_fs41.createWriteStream)(dest));
71245
71623
  const got = await sha1OfFile(dest);
71246
71624
  if (got !== want) throw new Error(`SHA1 mismatch for ${asset.FileName}: feed=${want} got=${got}`);
71247
71625
  return dest;
@@ -71250,7 +71628,7 @@ async function applyUpdate(check, opts) {
71250
71628
  if (!check.supported) return { applied: false, message: check.reason ?? "auto-update not supported in this runtime" };
71251
71629
  if (!check.updateAvailable || !check.asset) return { applied: false, message: check.reason ?? "no update available" };
71252
71630
  const exe = updateExePath();
71253
- if (!(0, import_node_fs40.existsSync)(exe)) {
71631
+ if (!(0, import_node_fs41.existsSync)(exe)) {
71254
71632
  return { applied: false, message: `Update.exe not found at ${exe} \u2014 is this a Velopack install?` };
71255
71633
  }
71256
71634
  const pkg = await downloadPackage(check.asset);
@@ -71490,12 +71868,12 @@ function isTraceCorrupt(events) {
71490
71868
 
71491
71869
  // launch.mjs
71492
71870
  var import_node_child_process8 = require("node:child_process");
71493
- var import_node_path37 = require("node:path");
71871
+ var import_node_path38 = require("node:path");
71494
71872
  var import_node_url3 = require("node:url");
71495
- var import_node_fs41 = require("node:fs");
71873
+ var import_node_fs42 = require("node:fs");
71496
71874
  var import_node_http = __toESM(require("node:http"), 1);
71497
71875
  var import_node_readline = require("node:readline");
71498
- var __dirname2 = (0, import_node_path37.dirname)((0, import_node_url3.fileURLToPath)(__import_meta_url));
71876
+ var __dirname2 = (0, import_node_path38.dirname)((0, import_node_url3.fileURLToPath)(__import_meta_url));
71499
71877
  var PORT = Number(process.env.PORT ?? 4317);
71500
71878
  var HEALTH_URL = `http://127.0.0.1:${PORT}/api/health`;
71501
71879
  var BROWSER_URL = `http://floless.localhost:${PORT}`;
@@ -71567,8 +71945,8 @@ async function waitHealthy(timeoutMs = 3e4) {
71567
71945
  function resolveServerStart() {
71568
71946
  const packaged = /flolessapp\.exe$/i.test(process.execPath);
71569
71947
  if (packaged) return { cmd: process.execPath, args: ["--serve"], shell: false };
71570
- const bundle = (0, import_node_path37.join)(__dirname2, "dist", "floless-server.cjs");
71571
- if ((0, import_node_fs41.existsSync)(bundle)) return { cmd: process.execPath, args: [bundle, "--serve"], shell: false };
71948
+ const bundle = (0, import_node_path38.join)(__dirname2, "dist", "floless-server.cjs");
71949
+ if ((0, import_node_fs42.existsSync)(bundle)) return { cmd: process.execPath, args: [bundle, "--serve"], shell: false };
71572
71950
  return { cmd: "npm", args: ["run", "start"], shell: isWin2 };
71573
71951
  }
71574
71952
  function startServerDetached() {
@@ -71721,8 +72099,8 @@ function taskkillArgs(pid, { tree = true } = {}) {
71721
72099
  }
71722
72100
  function killSupervisor({ tree = true } = {}) {
71723
72101
  if (!isWin2) return;
71724
- const isNpmChannel = /^node(\.exe)?$/i.test((0, import_node_path37.basename)(process.execPath));
71725
- const scriptMatch = isNpmChannel ? (0, import_node_path37.basename)((0, import_node_url3.fileURLToPath)(__import_meta_url)) : void 0;
72102
+ const isNpmChannel = /^node(\.exe)?$/i.test((0, import_node_path38.basename)(process.execPath));
72103
+ const scriptMatch = isNpmChannel ? (0, import_node_path38.basename)((0, import_node_url3.fileURLToPath)(__import_meta_url)) : void 0;
71726
72104
  const realExe = resolveRealInstallExe(process.execPath);
71727
72105
  const exeMatch = realExe === process.execPath ? process.execPath : [process.execPath, realExe];
71728
72106
  const pids = supervisorPidsToKill(enumerateProcesses(), process.pid, exeMatch, scriptMatch);
@@ -71887,7 +72265,7 @@ async function runAction(arg, flagArgv = [], selfVersion = null) {
71887
72265
  }
71888
72266
  await action(parseTeardownFlags(flagArgv));
71889
72267
  }
71890
- var entry = (0, import_node_path37.basename)(process.argv[1] ?? "").toLowerCase();
72268
+ var entry = (0, import_node_path38.basename)(process.argv[1] ?? "").toLowerCase();
71891
72269
  if (entry === "launch.mjs") {
71892
72270
  runAction(process.argv[2], process.argv.slice(3)).catch((e) => {
71893
72271
  log(`error: ${e?.message ?? e}`);
@@ -71961,9 +72339,9 @@ function awareUpgradeBlockReason(s) {
71961
72339
  }
71962
72340
 
71963
72341
  // skill-sync.ts
71964
- var import_node_fs42 = require("node:fs");
71965
- var import_node_os22 = require("node:os");
71966
- var import_node_path38 = require("node:path");
72342
+ var import_node_fs43 = require("node:fs");
72343
+ var import_node_os23 = require("node:os");
72344
+ var import_node_path39 = require("node:path");
71967
72345
  var import_node_url4 = require("node:url");
71968
72346
  var import_yaml10 = __toESM(require_dist6(), 1);
71969
72347
 
@@ -72008,30 +72386,30 @@ function selectShippedSkillNames(names) {
72008
72386
  }
72009
72387
 
72010
72388
  // skill-sync.ts
72011
- var __dirname3 = (0, import_node_path38.dirname)((0, import_node_url4.fileURLToPath)(__import_meta_url));
72389
+ var __dirname3 = (0, import_node_path39.dirname)((0, import_node_url4.fileURLToPath)(__import_meta_url));
72012
72390
  function bundledSkillsRoot() {
72013
72391
  const candidates = [
72014
- (0, import_node_path38.join)(__dirname3, "skills"),
72015
- (0, import_node_path38.join)((0, import_node_path38.dirname)(process.execPath), "skills"),
72016
- (0, import_node_path38.join)(__dirname3, "..", ".claude", "skills")
72392
+ (0, import_node_path39.join)(__dirname3, "skills"),
72393
+ (0, import_node_path39.join)((0, import_node_path39.dirname)(process.execPath), "skills"),
72394
+ (0, import_node_path39.join)(__dirname3, "..", ".claude", "skills")
72017
72395
  ];
72018
- return candidates.find((p) => (0, import_node_fs42.existsSync)(p)) ?? null;
72396
+ return candidates.find((p) => (0, import_node_fs43.existsSync)(p)) ?? null;
72019
72397
  }
72020
72398
  function targetConfigDirs() {
72021
72399
  const override = process.env.FLOLESS_SKILL_TARGETS;
72022
72400
  if (override) {
72023
72401
  return override.split(";").map((d) => d.trim()).filter(Boolean).map((dir) => ({ runtime: "custom", dir }));
72024
72402
  }
72025
- const home = (0, import_node_os22.homedir)();
72403
+ const home = (0, import_node_os23.homedir)();
72026
72404
  return [
72027
- { runtime: "claude", dir: (0, import_node_path38.join)(home, ".claude") },
72028
- { runtime: "codex", dir: (0, import_node_path38.join)(home, ".codex") },
72029
- { runtime: "opencode", dir: (0, import_node_path38.join)(home, ".opencode") }
72405
+ { runtime: "claude", dir: (0, import_node_path39.join)(home, ".claude") },
72406
+ { runtime: "codex", dir: (0, import_node_path39.join)(home, ".codex") },
72407
+ { runtime: "opencode", dir: (0, import_node_path39.join)(home, ".opencode") }
72030
72408
  ];
72031
72409
  }
72032
72410
  function skillVersion(skillMdPath) {
72033
72411
  try {
72034
- const text2 = (0, import_node_fs42.readFileSync)(skillMdPath, "utf8");
72412
+ const text2 = (0, import_node_fs43.readFileSync)(skillMdPath, "utf8");
72035
72413
  const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text2);
72036
72414
  if (!m || m[1] === void 0) return null;
72037
72415
  const fm = (0, import_yaml10.parse)(m[1]);
@@ -72071,21 +72449,21 @@ function decideAction(installed, bundled) {
72071
72449
  function bundledSkills(root3) {
72072
72450
  let entries = [];
72073
72451
  try {
72074
- entries = selectShippedSkillNames((0, import_node_fs42.readdirSync)(root3));
72452
+ entries = selectShippedSkillNames((0, import_node_fs43.readdirSync)(root3));
72075
72453
  } catch {
72076
72454
  return [];
72077
72455
  }
72078
72456
  const out = [];
72079
72457
  for (const name of entries) {
72080
- const dir = (0, import_node_path38.join)(root3, name);
72458
+ const dir = (0, import_node_path39.join)(root3, name);
72081
72459
  let isDir = false;
72082
72460
  try {
72083
- isDir = (0, import_node_fs42.statSync)(dir).isDirectory();
72461
+ isDir = (0, import_node_fs43.statSync)(dir).isDirectory();
72084
72462
  } catch {
72085
72463
  isDir = false;
72086
72464
  }
72087
72465
  if (!isDir) continue;
72088
- const v = skillVersion((0, import_node_path38.join)(dir, "SKILL.md"));
72466
+ const v = skillVersion((0, import_node_path39.join)(dir, "SKILL.md"));
72089
72467
  if (!v) continue;
72090
72468
  out.push({ name, dir, version: v });
72091
72469
  }
@@ -72098,17 +72476,17 @@ function syncSkills() {
72098
72476
  const skills = bundledSkills(root3);
72099
72477
  if (!skills.length) return results;
72100
72478
  for (const { runtime, dir: cfg } of targetConfigDirs()) {
72101
- if (!(0, import_node_fs42.existsSync)(cfg)) continue;
72102
- const skillsDir = (0, import_node_path38.join)(cfg, "skills");
72479
+ if (!(0, import_node_fs43.existsSync)(cfg)) continue;
72480
+ const skillsDir = (0, import_node_path39.join)(cfg, "skills");
72103
72481
  for (const s of skills) {
72104
- const dest = (0, import_node_path38.join)(skillsDir, s.name);
72105
- const installedMd = (0, import_node_path38.join)(dest, "SKILL.md");
72106
- const installed = (0, import_node_fs42.existsSync)(installedMd) ? skillVersion(installedMd) : null;
72482
+ const dest = (0, import_node_path39.join)(skillsDir, s.name);
72483
+ const installedMd = (0, import_node_path39.join)(dest, "SKILL.md");
72484
+ const installed = (0, import_node_fs43.existsSync)(installedMd) ? skillVersion(installedMd) : null;
72107
72485
  const action = decideAction(installed, s.version);
72108
72486
  if (action === "installed" || action === "updated") {
72109
72487
  try {
72110
- if (action === "updated") (0, import_node_fs42.rmSync)(dest, { recursive: true, force: true });
72111
- (0, import_node_fs42.cpSync)(s.dir, dest, { recursive: true });
72488
+ if (action === "updated") (0, import_node_fs43.rmSync)(dest, { recursive: true, force: true });
72489
+ (0, import_node_fs43.cpSync)(s.dir, dest, { recursive: true });
72112
72490
  results.push({ runtime, skill: s.name, action, from: installed, to: s.version });
72113
72491
  } catch {
72114
72492
  }
@@ -72132,9 +72510,9 @@ function contractChangedEvent(appId, project, etag, rawMutationId) {
72132
72510
  }
72133
72511
 
72134
72512
  // watch.ts
72135
- var import_node_os23 = require("node:os");
72136
- var import_node_path40 = require("node:path");
72137
- var import_node_fs43 = require("node:fs");
72513
+ var import_node_os24 = require("node:os");
72514
+ var import_node_path41 = require("node:path");
72515
+ var import_node_fs44 = require("node:fs");
72138
72516
 
72139
72517
  // node_modules/chokidar/esm/index.js
72140
72518
  var import_fs2 = require("fs");
@@ -72145,7 +72523,7 @@ var sysPath2 = __toESM(require("path"), 1);
72145
72523
  // node_modules/readdirp/esm/index.js
72146
72524
  var import_promises4 = require("node:fs/promises");
72147
72525
  var import_node_stream4 = require("node:stream");
72148
- var import_node_path39 = require("node:path");
72526
+ var import_node_path40 = require("node:path");
72149
72527
  var EntryTypes = {
72150
72528
  FILE_TYPE: "files",
72151
72529
  DIR_TYPE: "directories",
@@ -72220,7 +72598,7 @@ var ReaddirpStream = class extends import_node_stream4.Readable {
72220
72598
  this._wantsDir = type ? DIR_TYPES.has(type) : false;
72221
72599
  this._wantsFile = type ? FILE_TYPES.has(type) : false;
72222
72600
  this._wantsEverything = type === EntryTypes.EVERYTHING_TYPE;
72223
- this._root = (0, import_node_path39.resolve)(root3);
72601
+ this._root = (0, import_node_path40.resolve)(root3);
72224
72602
  this._isDirent = !opts.alwaysStat;
72225
72603
  this._statsProp = this._isDirent ? "dirent" : "stats";
72226
72604
  this._rdOptions = { encoding: "utf8", withFileTypes: this._isDirent };
@@ -72291,8 +72669,8 @@ var ReaddirpStream = class extends import_node_stream4.Readable {
72291
72669
  let entry2;
72292
72670
  const basename9 = this._isDirent ? dirent.name : dirent;
72293
72671
  try {
72294
- const fullPath = (0, import_node_path39.resolve)((0, import_node_path39.join)(path, basename9));
72295
- entry2 = { path: (0, import_node_path39.relative)(this._root, fullPath), fullPath, basename: basename9 };
72672
+ const fullPath = (0, import_node_path40.resolve)((0, import_node_path40.join)(path, basename9));
72673
+ entry2 = { path: (0, import_node_path40.relative)(this._root, fullPath), fullPath, basename: basename9 };
72296
72674
  entry2[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
72297
72675
  } catch (err2) {
72298
72676
  this._onError(err2);
@@ -72326,7 +72704,7 @@ var ReaddirpStream = class extends import_node_stream4.Readable {
72326
72704
  }
72327
72705
  if (entryRealPathStats.isDirectory()) {
72328
72706
  const len = entryRealPath.length;
72329
- if (full.startsWith(entryRealPath) && full.substr(len, 1) === import_node_path39.sep) {
72707
+ if (full.startsWith(entryRealPath) && full.substr(len, 1) === import_node_path40.sep) {
72330
72708
  const recursiveError = new Error(`Circular symlink detected: "${full}" points to "${entryRealPath}"`);
72331
72709
  recursiveError.code = RECURSIVE_ERROR_CODE;
72332
72710
  return this._onError(recursiveError);
@@ -73834,33 +74212,33 @@ function appIdFromLogPath(path) {
73834
74212
  return i >= 0 && parts[i + 1] ? parts[i + 1] : null;
73835
74213
  }
73836
74214
  function samePath(a, b) {
73837
- const ra = (0, import_node_path40.resolve)(a);
73838
- const rb = (0, import_node_path40.resolve)(b);
74215
+ const ra = (0, import_node_path41.resolve)(a);
74216
+ const rb = (0, import_node_path41.resolve)(b);
73839
74217
  return process.platform === "win32" ? ra.toLowerCase() === rb.toLowerCase() : ra === rb;
73840
74218
  }
73841
74219
  function underDir(path, dir) {
73842
- const rp = (0, import_node_path40.resolve)(path);
73843
- const rd = (0, import_node_path40.resolve)(dir);
74220
+ const rp = (0, import_node_path41.resolve)(path);
74221
+ const rd = (0, import_node_path41.resolve)(dir);
73844
74222
  const [p, d] = process.platform === "win32" ? [rp.toLowerCase(), rd.toLowerCase()] : [rp, rd];
73845
- return p === d || p.startsWith(d + import_node_path40.sep);
74223
+ return p === d || p.startsWith(d + import_node_path41.sep);
73846
74224
  }
73847
74225
  function startWatcher() {
73848
- const awareDir = process.env.AWARE_HOME ?? (0, import_node_path40.join)((0, import_node_os23.homedir)(), ".aware");
73849
- const credentialsDir = (0, import_node_path40.join)(awareDir, "credentials");
73850
- if (!(0, import_node_fs43.existsSync)(credentialsDir)) {
74226
+ const awareDir = process.env.AWARE_HOME ?? (0, import_node_path41.join)((0, import_node_os24.homedir)(), ".aware");
74227
+ const credentialsDir = (0, import_node_path41.join)(awareDir, "credentials");
74228
+ if (!(0, import_node_fs44.existsSync)(credentialsDir)) {
73851
74229
  try {
73852
- (0, import_node_fs43.mkdirSync)(credentialsDir, { recursive: true });
74230
+ (0, import_node_fs44.mkdirSync)(credentialsDir, { recursive: true });
73853
74231
  } catch {
73854
74232
  }
73855
74233
  }
73856
- if (!(0, import_node_fs43.existsSync)(uiDir)) {
74234
+ if (!(0, import_node_fs44.existsSync)(uiDir)) {
73857
74235
  try {
73858
- (0, import_node_fs43.mkdirSync)(uiDir, { recursive: true });
74236
+ (0, import_node_fs44.mkdirSync)(uiDir, { recursive: true });
73859
74237
  } catch {
73860
74238
  }
73861
74239
  }
73862
- const targets = ["apps", "logs", "credentials"].map((d) => (0, import_node_path40.join)(awareDir, d)).filter((p) => (0, import_node_fs43.existsSync)(p));
73863
- if ((0, import_node_fs43.existsSync)(uiDir)) targets.push(uiDir);
74240
+ const targets = ["apps", "logs", "credentials"].map((d) => (0, import_node_path41.join)(awareDir, d)).filter((p) => (0, import_node_fs44.existsSync)(p));
74241
+ if ((0, import_node_fs44.existsSync)(uiDir)) targets.push(uiDir);
73864
74242
  if (targets.length === 0) {
73865
74243
  return null;
73866
74244
  }
@@ -73889,11 +74267,11 @@ function startWatcher() {
73889
74267
  const isCredential = path.split(/[\\/]/).includes("credentials");
73890
74268
  const kind = isCredential ? "credential" : path.endsWith(".jsonl") ? "trace" : path.endsWith(".lock") ? "lock" : path.endsWith(".flo") || path.endsWith(".app") ? "source" : "file";
73891
74269
  broadcast({ type: "fs-change", kind, event, path });
73892
- if (kind === "trace" && event !== "unlink" && (0, import_node_fs43.existsSync)(path)) {
74270
+ if (kind === "trace" && event !== "unlink" && (0, import_node_fs44.existsSync)(path)) {
73893
74271
  const id = appIdFromLogPath(path);
73894
74272
  if (!id) return;
73895
74273
  try {
73896
- broadcast({ type: "trace-file", id, runId: path.split(import_node_path40.sep).pop()?.replace(/\.jsonl$/, "") ?? null, events: parseTrace((0, import_node_fs43.readFileSync)(path, "utf8")) });
74274
+ broadcast({ type: "trace-file", id, runId: path.split(import_node_path41.sep).pop()?.replace(/\.jsonl$/, "") ?? null, events: parseTrace((0, import_node_fs44.readFileSync)(path, "utf8")) });
73897
74275
  } catch {
73898
74276
  }
73899
74277
  }
@@ -73902,10 +74280,10 @@ function startWatcher() {
73902
74280
  }
73903
74281
 
73904
74282
  // index.ts
73905
- var __dirname4 = (0, import_node_path41.dirname)((0, import_node_url5.fileURLToPath)(__import_meta_url));
73906
- var WEB_ROOT = [(0, import_node_path41.join)(__dirname4, "web"), (0, import_node_path41.join)((0, import_node_path41.dirname)(process.execPath), "web"), (0, import_node_path41.join)(__dirname4, "..", "web")].find(
73907
- (p) => (0, import_node_fs44.existsSync)(p)
73908
- ) ?? (0, import_node_path41.join)(__dirname4, "..", "web");
74283
+ var __dirname4 = (0, import_node_path42.dirname)((0, import_node_url5.fileURLToPath)(__import_meta_url));
74284
+ var WEB_ROOT = [(0, import_node_path42.join)(__dirname4, "web"), (0, import_node_path42.join)((0, import_node_path42.dirname)(process.execPath), "web"), (0, import_node_path42.join)(__dirname4, "..", "web")].find(
74285
+ (p) => (0, import_node_fs45.existsSync)(p)
74286
+ ) ?? (0, import_node_path42.join)(__dirname4, "..", "web");
73909
74287
  var PORT2 = Number(process.env.PORT ?? 4317);
73910
74288
  var HOST = "127.0.0.1";
73911
74289
  var crashHandlersInstalled = false;
@@ -73921,7 +74299,7 @@ function installCrashHandlers() {
73921
74299
  ${stack}
73922
74300
  `;
73923
74301
  try {
73924
- (0, import_node_fs44.appendFileSync)(logFilePath(), line);
74302
+ (0, import_node_fs45.appendFileSync)(logFilePath(), line);
73925
74303
  } catch {
73926
74304
  }
73927
74305
  if (process.stderr.isTTY) process.stderr.write(line);
@@ -74034,6 +74412,15 @@ async function startServer() {
74034
74412
  if (err2 instanceof ProjectError) {
74035
74413
  return reply.status(400).send({ ok: false, error: err2.message });
74036
74414
  }
74415
+ if (err2 instanceof LifecycleLockBusyError) {
74416
+ const retryAfter = err2.busy.remainingMs == null ? 5 : Math.min(60, Math.max(1, Math.ceil(err2.busy.remainingMs / 1e3)));
74417
+ return reply.status(err2.status).header("Retry-After", String(retryAfter)).send({
74418
+ ok: false,
74419
+ error: err2.message,
74420
+ code: "lifecycle-busy",
74421
+ busy: err2.busy
74422
+ });
74423
+ }
74037
74424
  if (err2 instanceof RoutineError) {
74038
74425
  return reply.status(err2.status).send({ ok: false, error: err2.message });
74039
74426
  }
@@ -74268,9 +74655,9 @@ async function startServer() {
74268
74655
  const { id, templateId, templatePath, srcPath, appDirPath: appDirPath2, fromVersion, contract, verb } = opts;
74269
74656
  const bdir = backupDir(id, fromVersion, Date.now());
74270
74657
  try {
74271
- (0, import_node_fs44.mkdirSync)((0, import_node_path41.dirname)(bdir), { recursive: true });
74272
- (0, import_node_fs44.cpSync)(appDirPath2, bdir, { recursive: true });
74273
- (0, import_node_fs44.cpSync)(templatePath, srcPath);
74658
+ (0, import_node_fs45.mkdirSync)((0, import_node_path42.dirname)(bdir), { recursive: true });
74659
+ (0, import_node_fs45.cpSync)(appDirPath2, bdir, { recursive: true });
74660
+ (0, import_node_fs45.cpSync)(templatePath, srcPath);
74274
74661
  if (id !== templateId) stampSourceAppId(srcPath, id);
74275
74662
  if (contract != null) {
74276
74663
  bakeContractIntoApp(srcPath, contract);
@@ -74281,8 +74668,8 @@ async function startServer() {
74281
74668
  } catch (e) {
74282
74669
  const msg = e instanceof Error ? e.message : String(e);
74283
74670
  try {
74284
- (0, import_node_fs44.rmSync)(appDirPath2, { recursive: true, force: true });
74285
- (0, import_node_fs44.cpSync)(bdir, appDirPath2, { recursive: true });
74671
+ (0, import_node_fs45.rmSync)(appDirPath2, { recursive: true, force: true });
74672
+ (0, import_node_fs45.cpSync)(bdir, appDirPath2, { recursive: true });
74286
74673
  } catch (re) {
74287
74674
  const rmsg = re instanceof Error ? re.message : String(re);
74288
74675
  throw new TemplateSwapError(`${verb} failed (${msg}) AND rollback failed (${rmsg}) \u2014 restore manually from ${bdir}`, "rollback-failed", bdir);
@@ -74314,7 +74701,7 @@ async function startServer() {
74314
74701
  return reply.status(409).send({ ok: false, error: `"${id}" is already at ${fromVersion}`, code: "up-to-date" });
74315
74702
  }
74316
74703
  const contract = readAcceptedForRequest(id, void 0);
74317
- if (contract == null && (0, import_node_fs44.existsSync)(contractPath(id))) {
74704
+ if (contract == null && (0, import_node_fs45.existsSync)(contractPath(id))) {
74318
74705
  return reply.status(409).send({ ok: false, error: `"${id}"'s saved data is unreadable \u2014 open it in the editor and re-save before updating`, code: "contract-corrupt" });
74319
74706
  }
74320
74707
  if (contract != null) {
@@ -74694,9 +75081,9 @@ async function startServer() {
74694
75081
  const bad = projectAppMismatch(req.params.appId, project);
74695
75082
  if (bad) return reply.status(404).send({ ok: false, error: bad });
74696
75083
  const safe2 = req.params.sheet.replace(/[^A-Za-z0-9._-]/g, "");
74697
- const file = (0, import_node_path41.join)((0, import_node_path41.dirname)(contractPath(req.params.appId, project)), "details", `${safe2}.svg`);
74698
- if (!(0, import_node_fs44.existsSync)(file)) return reply.status(404).send({ ok: false, error: "no vector for this sheet" });
74699
- return reply.type("image/svg+xml").send((0, import_node_fs44.readFileSync)(file, "utf8"));
75084
+ const file = (0, import_node_path42.join)((0, import_node_path42.dirname)(contractPath(req.params.appId, project)), "details", `${safe2}.svg`);
75085
+ if (!(0, import_node_fs45.existsSync)(file)) return reply.status(404).send({ ok: false, error: "no vector for this sheet" });
75086
+ return reply.type("image/svg+xml").send((0, import_node_fs45.readFileSync)(file, "utf8"));
74700
75087
  }
74701
75088
  );
74702
75089
  app.put(
@@ -74721,9 +75108,6 @@ async function startServer() {
74721
75108
  if (e instanceof PreconditionFailedError) {
74722
75109
  return reply.status(412).send({ ok: false, error: e.message, code: e.code });
74723
75110
  }
74724
- if (e instanceof StoreBusyError) {
74725
- return reply.status(503).header("Retry-After", "5").send({ ok: false, error: e.message, code: e.code });
74726
- }
74727
75111
  if (e instanceof ContractError) return reply.status(400).send({ ok: false, error: e.message, ...e.code ? { code: e.code } : {} });
74728
75112
  throw e;
74729
75113
  }
@@ -74849,20 +75233,35 @@ async function startServer() {
74849
75233
  throw error;
74850
75234
  }
74851
75235
  }
74852
- const byKind = new Map(currentReceipts.map((receipt) => [receipt.kind, receipt]));
74853
- const exports2 = projectExportFiles(req.params.appId, resolveTemplateId(req.params.appId)).map(({ kind, filename: legacy }) => {
74854
- const receipt = byKind.get(kind);
74855
- const filename = receipt?.filename ?? legacy;
74856
- const path = (0, import_node_path41.join)(dir, filename);
74857
- let exportedAt = null;
74858
- if (receipt) {
74859
- try {
74860
- const st = (0, import_node_fs44.statSync)(path);
74861
- if (st.isFile()) exportedAt = st.mtime.toISOString();
74862
- } catch {
74863
- }
75236
+ const byKind = /* @__PURE__ */ new Map();
75237
+ for (const receipt of currentReceipts) {
75238
+ const rows2 = byKind.get(receipt.kind);
75239
+ if (rows2) rows2.push(receipt);
75240
+ else byKind.set(receipt.kind, [receipt]);
75241
+ }
75242
+ const statedAt = (filename) => {
75243
+ try {
75244
+ const st = (0, import_node_fs45.statSync)((0, import_node_path42.join)(dir, filename));
75245
+ return st.isFile() ? st.mtime.toISOString() : null;
75246
+ } catch {
75247
+ return null;
74864
75248
  }
74865
- return { kind, filename, path, exportedAt };
75249
+ };
75250
+ const exports2 = projectExportFiles(req.params.appId, resolveTemplateId(req.params.appId)).map(({ kind, filename: legacy }) => {
75251
+ const rows2 = (byKind.get(kind) ?? []).map((receipt) => ({
75252
+ variant: receipt.variant ?? null,
75253
+ filename: receipt.filename,
75254
+ path: (0, import_node_path42.join)(dir, receipt.filename),
75255
+ exportedAt: statedAt(receipt.filename)
75256
+ })).sort((a, b) => String(b.exportedAt ?? "").localeCompare(String(a.exportedAt ?? "")));
75257
+ const headline = rows2[0];
75258
+ return {
75259
+ kind,
75260
+ filename: headline?.filename ?? legacy,
75261
+ path: headline?.path ?? (0, import_node_path42.join)(dir, legacy),
75262
+ exportedAt: headline?.exportedAt ?? null,
75263
+ ...rows2.length ? { variants: rows2 } : {}
75264
+ };
74866
75265
  });
74867
75266
  return { ok: true, approvedAt, exports: exports2 };
74868
75267
  });
@@ -74880,56 +75279,64 @@ async function startServer() {
74880
75279
  });
74881
75280
  }
74882
75281
  }
74883
- return withLifecycleLock(project ? "project" : "app", project || appId, async () => withLifecycleLock("app", `${appId}-3d`, async () => {
74884
- let projectSnapshot;
74885
- if (project) {
74886
- const gate = projectExportGate(appId, project);
74887
- if (gate) return reply.status(gate.status).send({ ok: false, error: gate.error });
75282
+ return withLifecycleLock(
75283
+ project ? "project" : "app",
75284
+ project || appId,
75285
+ async () => withLifecycleLock("app", `${appId}-3d`, async () => {
75286
+ let projectSnapshot;
75287
+ if (project) {
75288
+ const gate = projectExportGate(appId, project);
75289
+ if (gate) return reply.status(gate.status).send({ ok: false, error: gate.error });
75290
+ try {
75291
+ projectSnapshot = currentApprovedSnapshot(project);
75292
+ } catch (error) {
75293
+ if (error instanceof WorkspaceSnapshotError) return reply.status(error.status).send({ ok: false, error: error.message });
75294
+ throw error;
75295
+ }
75296
+ }
75297
+ const candidate = projectSnapshot ? projectSnapshot.contract : readAcceptedForRequest(appId, void 0);
75298
+ if (candidate == null) return reply.status(404).send({ ok: false, error: "no contract to export" });
75299
+ const steel = acceptSteelForRoute(candidate, { appId, projectId: project }, "stored");
75300
+ if (!steel.accepted) return reply.status(400).send(steel.refusal);
75301
+ const { scene, skipped } = contractToScene(steel.doc);
75302
+ if (scene.elements.length === 0) {
75303
+ return reply.status(422).send({ ok: false, error: "no resolvable members to render \u2014 every member is an RFI (no AISC size yet)", skipped });
75304
+ }
75305
+ const companionId = `${appId}-3d`;
75306
+ let flo;
74888
75307
  try {
74889
- projectSnapshot = currentApprovedSnapshot(project);
74890
- } catch (error) {
74891
- if (error instanceof WorkspaceSnapshotError) return reply.status(error.status).send({ ok: false, error: error.message });
74892
- throw error;
75308
+ flo = writeViewer3dApp(appPath(companionId), companionId, scene);
75309
+ } catch (e) {
75310
+ app.log.error({ companionId, err: e instanceof Error ? e.message : e }, "export-3d: companion app write failed");
75311
+ return reply.status(500).send({ ok: false, error: `could not write the 3D companion app: ${e instanceof Error ? e.message : "write error"}` });
74893
75312
  }
74894
- }
74895
- const candidate = projectSnapshot ? projectSnapshot.contract : readAcceptedForRequest(appId, void 0);
74896
- if (candidate == null) return reply.status(404).send({ ok: false, error: "no contract to export" });
74897
- const steel = acceptSteelForRoute(candidate, { appId, projectId: project }, "stored");
74898
- if (!steel.accepted) return reply.status(400).send(steel.refusal);
74899
- const { scene, skipped } = contractToScene(steel.doc);
74900
- if (scene.elements.length === 0) {
74901
- return reply.status(422).send({ ok: false, error: "no resolvable members to render \u2014 every member is an RFI (no AISC size yet)", skipped });
74902
- }
74903
- const companionId = `${appId}-3d`;
74904
- let flo;
74905
- try {
74906
- flo = writeViewer3dApp(appPath(companionId), companionId, scene);
74907
- } catch (e) {
74908
- app.log.error({ companionId, err: e instanceof Error ? e.message : e }, "export-3d: companion app write failed");
74909
- return reply.status(500).send({ ok: false, error: `could not write the 3D companion app: ${e instanceof Error ? e.message : "write error"}` });
74910
- }
74911
- try {
74912
- await aware.compile(flo);
74913
- } catch (e) {
74914
- app.log.warn({ companionId, detail: e instanceof AwareError ? e.detail : void 0 }, "3D compile failed");
74915
- return reply.status(422).send({ ok: false, error: `3D compile failed: ${e instanceof Error ? e.message : "compile error"}`, reason: awareStderr(e) });
74916
- }
74917
- let result;
74918
- try {
74919
- result = await aware.run(companionId, {});
74920
- } catch (e) {
74921
- if (e instanceof AwareError) {
74922
- app.log.warn({ companionId, detail: e.detail }, "3D render failed");
74923
- return reply.send({ ok: false, error: e.message, reason: awareStderr(e) });
75313
+ try {
75314
+ await aware.compile(flo);
75315
+ } catch (e) {
75316
+ app.log.warn({ companionId, detail: e instanceof AwareError ? e.detail : void 0 }, "3D compile failed");
75317
+ return reply.status(422).send({ ok: false, error: `3D compile failed: ${e instanceof Error ? e.message : "compile error"}`, reason: awareStderr(e) });
74924
75318
  }
74925
- throw e;
74926
- }
74927
- const events = result.traceText ? parseTrace(result.traceText) : [];
74928
- const extracted = extractReportHtml(events);
74929
- if (!extracted) return reply.send({ ok: false, error: "the 3D render produced no html" });
74930
- broadcast({ type: "apps-changed" });
74931
- return { ok: true, report: { ...extracted, interactive: true }, skipped };
74932
- }));
75319
+ let result;
75320
+ try {
75321
+ result = await aware.run(companionId, {});
75322
+ } catch (e) {
75323
+ if (e instanceof AwareError) {
75324
+ app.log.warn({ companionId, detail: e.detail }, "3D render failed");
75325
+ return reply.send({ ok: false, error: e.message, reason: awareStderr(e) });
75326
+ }
75327
+ throw e;
75328
+ }
75329
+ const events = result.traceText ? parseTrace(result.traceText) : [];
75330
+ const extracted = extractReportHtml(events);
75331
+ if (!extracted) return reply.send({ ok: false, error: "the 3D render produced no html" });
75332
+ broadcast({ type: "apps-changed" });
75333
+ return { ok: true, report: { ...extracted, interactive: true }, skipped };
75334
+ }),
75335
+ // Names the job for anyone blocked on the project, with no countdown — same reasoning as the
75336
+ // Tekla bake: slow sometimes, not predictably so. The label goes on the OUTER (project) lock,
75337
+ // which is the one a sibling export contends with.
75338
+ { label: "building the 3D view" }
75339
+ );
74933
75340
  });
74934
75341
  async function stableExportSourceId(appId, project) {
74935
75342
  const ownerId = project ? await getOrCreateProjectExportSourceId(project) : await getOrCreateWorkflowExportSourceId(appId);
@@ -74990,7 +75397,7 @@ async function startServer() {
74990
75397
  }
74991
75398
  if (!hasExportableSceneRecords(scene)) return reply.status(422).send({ ok: false, error: emptyError, skipped });
74992
75399
  const filename = `${exportFileBase(project, appId)}.ifc`;
74993
- const finalPath = (0, import_node_path41.join)(project ? projectExportsDir(project) : (0, import_node_path41.dirname)(bomExportPath(appId, "csv")), filename);
75400
+ const finalPath = (0, import_node_path42.join)(project ? projectExportsDir(project) : (0, import_node_path42.dirname)(bomExportPath(appId, "csv")), filename);
74994
75401
  const priorProjectIfc = project ? listProjectExportReceipts(project).find((row) => row.kind === "ifc") : void 0;
74995
75402
  const tempPath = requestIfcTempPath(finalPath);
74996
75403
  try {
@@ -74998,10 +75405,10 @@ async function startServer() {
74998
75405
  scene,
74999
75406
  "output-path": tempPath
75000
75407
  });
75001
- if (!(0, import_node_fs44.existsSync)(tempPath) || (0, import_node_fs44.statSync)(tempPath).size === 0) {
75408
+ if (!(0, import_node_fs45.existsSync)(tempPath) || (0, import_node_fs45.statSync)(tempPath).size === 0) {
75002
75409
  throw new ReceiptReconciliationError("AWARE reported a successful export but wrote no IFC file.");
75003
75410
  }
75004
- const artifactBytes = (0, import_node_fs44.readFileSync)(tempPath);
75411
+ const artifactBytes = (0, import_node_fs45.readFileSync)(tempPath);
75005
75412
  const receipt = reconcileIfcExportReceipt(scene, rawReceipt, producerUnsupported, {
75006
75413
  index: parseStepData(artifactBytes),
75007
75414
  bytes: artifactBytes
@@ -75054,13 +75461,206 @@ async function startServer() {
75054
75461
  return reply.status(status).send({
75055
75462
  ok: false,
75056
75463
  error: error instanceof Error ? error.message : "IFC export failed",
75057
- preservedPrevious: project && priorProjectIfc ? receiptHasFile(project, priorProjectIfc) : (0, import_node_fs44.existsSync)(finalPath)
75464
+ preservedPrevious: project && priorProjectIfc ? receiptHasFile(project, priorProjectIfc) : (0, import_node_fs45.existsSync)(finalPath)
75058
75465
  });
75059
75466
  } finally {
75060
75467
  cleanupIfcTemp(tempPath);
75061
75468
  }
75062
75469
  });
75063
75470
  });
75471
+ app.get("/api/render/readiness", async () => ({ ok: true, readiness: await renderReadiness() }));
75472
+ app.post("/api/render/install-agent", async (_req, reply) => {
75473
+ try {
75474
+ const { installed } = await aware.ensureAgentInstalled(RENDER_AGENT_ID);
75475
+ return { ok: true, installed, readiness: await renderReadiness() };
75476
+ } catch (error) {
75477
+ return reply.status(502).send({
75478
+ ok: false,
75479
+ error: error instanceof Error ? error.message : "installing the Blender agent failed"
75480
+ });
75481
+ }
75482
+ });
75483
+ app.get("/api/contract/:appId/render-preview", async (req, reply) => {
75484
+ const project = req.query.project;
75485
+ if (!project) return reply.status(400).send({ ok: false, error: "project is required" });
75486
+ const owner = getProject(project);
75487
+ if (!owner || owner.app !== req.params.appId) {
75488
+ return reply.status(404).send({ ok: false, error: "unknown project" });
75489
+ }
75490
+ let snapshot;
75491
+ try {
75492
+ snapshot = currentApprovedSnapshot(project);
75493
+ } catch (error) {
75494
+ if (error instanceof WorkspaceSnapshotError) {
75495
+ return reply.status(404).send({ ok: false, error: "nothing rendered for the approved version" });
75496
+ }
75497
+ throw error;
75498
+ }
75499
+ const stills = matchingProjectExportReceipts(
75500
+ project,
75501
+ snapshot.version.n,
75502
+ snapshot.contractHash,
75503
+ ["render-png"]
75504
+ );
75505
+ const wanted = typeof req.query.viewpoint === "string" ? req.query.viewpoint : null;
75506
+ const receipt = wanted ? stills.find((row) => row.variant === wanted) : [...stills].sort((a, b) => b.exportedAt.localeCompare(a.exportedAt))[0];
75507
+ if (!receipt) return reply.status(404).send({ ok: false, error: "nothing rendered yet" });
75508
+ const path = resolveProjectExportReceiptPath(project, receipt);
75509
+ if (!path || !(0, import_node_fs45.existsSync)(path)) {
75510
+ return reply.status(404).send({ ok: false, error: "the rendered image is no longer on disk" });
75511
+ }
75512
+ return reply.header("content-type", "image/png").header("cache-control", "private, max-age=31536000, immutable").send((0, import_node_fs45.readFileSync)(path));
75513
+ });
75514
+ const RENDER_VIEWPOINTS = /* @__PURE__ */ new Set(["hero", "iso", "front", "back", "left", "right", "top"]);
75515
+ app.post("/api/contract/:appId/render", async (req, reply) => {
75516
+ const appId = req.params.appId;
75517
+ const project = req.query.project || void 0;
75518
+ if (!/^[a-z0-9][a-z0-9._-]*$/i.test(appId)) {
75519
+ return reply.status(400).send({ ok: false, error: `invalid appId: ${appId}` });
75520
+ }
75521
+ if (!project) {
75522
+ return reply.status(400).send({ ok: false, error: "rendering is a project export \u2014 no project given" });
75523
+ }
75524
+ const body = req.body ?? {};
75525
+ const output = body.output === "turntable" ? "turntable" : "still";
75526
+ const quality = body.quality === "draft" ? "draft" : "production";
75527
+ const requested = Array.isArray(body.viewpoints) ? body.viewpoints : [typeof body.viewpoint === "string" ? body.viewpoint : "hero"];
75528
+ const viewpoints = [...new Set(requested.map((v) => String(v)))];
75529
+ if (!viewpoints.length) {
75530
+ return reply.status(400).send({ ok: false, error: "pick at least one viewpoint" });
75531
+ }
75532
+ const unknown = viewpoints.filter((v) => !RENDER_VIEWPOINTS.has(v));
75533
+ if (unknown.length) {
75534
+ return reply.status(400).send({ ok: false, error: `unknown viewpoint: ${unknown.join(", ")}` });
75535
+ }
75536
+ if (viewpoints.length > RENDER_VIEWPOINTS.size) {
75537
+ return reply.status(400).send({ ok: false, error: "too many viewpoints" });
75538
+ }
75539
+ const readiness = await renderReadiness();
75540
+ if (!readiness.ok) {
75541
+ return reply.status(409).send({ ok: false, error: readiness.message, readiness });
75542
+ }
75543
+ return withLifecycleLock("project", project, async () => {
75544
+ const gate = projectExportGate(appId, project);
75545
+ if (gate) return reply.status(gate.status).send({ ok: false, error: gate.error });
75546
+ let projectSnapshot;
75547
+ try {
75548
+ projectSnapshot = currentApprovedSnapshot(project);
75549
+ } catch (error) {
75550
+ if (error instanceof WorkspaceSnapshotError) {
75551
+ return reply.status(error.status).send({ ok: false, error: error.message });
75552
+ }
75553
+ throw error;
75554
+ }
75555
+ const steel = acceptSteelForRoute(projectSnapshot.contract, { appId, projectId: project }, "stored");
75556
+ if (!steel.accepted) return reply.status(400).send(steel.refusal);
75557
+ const doc = steel.doc;
75558
+ const sourceId = await stableExportSourceId(appId, project);
75559
+ const built = contractToAwareScene(doc, sourceId);
75560
+ if (!hasExportableSceneRecords(built.scene)) {
75561
+ return reply.status(422).send({
75562
+ ok: false,
75563
+ error: "no resolvable members to render \u2014 every member is an RFI (no AISC size yet)",
75564
+ skipped: built.skipped
75565
+ });
75566
+ }
75567
+ const kind = output === "turntable" ? "render-mp4" : "render-png";
75568
+ const extension = output === "turntable" ? ".mp4" : ".png";
75569
+ const scratch = (0, import_node_fs45.mkdtempSync)((0, import_node_path42.join)((0, import_node_os25.tmpdir)(), "floless-render-"));
75570
+ const ifcPath = (0, import_node_path42.join)(scratch, "model.ifc");
75571
+ const rendered = [];
75572
+ const progress = (stage, extra = {}) => {
75573
+ try {
75574
+ broadcast({ type: "render-progress", project, appId, stage, total: viewpoints.length, ...extra });
75575
+ } catch {
75576
+ }
75577
+ };
75578
+ try {
75579
+ progress("preparing");
75580
+ await aware.agentInvoke("ifc", "write", { scene: built.scene, "output-path": ifcPath });
75581
+ if (!(0, import_node_fs45.existsSync)(ifcPath) || (0, import_node_fs45.statSync)(ifcPath).size === 0) {
75582
+ throw new Error("AWARE reported a successful IFC write but produced no file to render");
75583
+ }
75584
+ const renderBudgetMs = output === "turntable" ? 30 * 6e4 : 10 * 6e4;
75585
+ for (const [i, viewpoint] of viewpoints.entries()) {
75586
+ progress("rendering", { viewpoint, index: i + 1, output });
75587
+ const artifactPath = (0, import_node_path42.join)(scratch, `render-${viewpoint}${extension}`);
75588
+ const receipt = await aware.agentInvoke(RENDER_AGENT_ID, output === "turntable" ? "render.turntable" : "render.still", {
75589
+ "ifc-path": ifcPath,
75590
+ "output-path": artifactPath,
75591
+ direction: viewpoint,
75592
+ "timeout-seconds": Math.round(renderBudgetMs / 1e3),
75593
+ // Lighting is deliberately fixed. Every environment renders the same neutral backdrop and
75594
+ // only changes the light, so exposing eight of them buys a decision with no visible
75595
+ // consequence and one more way for a project's renders to drift apart.
75596
+ environment: "studio",
75597
+ ...output === "turntable" ? { "duration-seconds": 12, fps: 24, "width-pixels": 1280, "height-pixels": 720 } : { quality, "width-pixels": 1920, "height-pixels": 1080 }
75598
+ }, { timeoutMs: renderBudgetMs });
75599
+ if (!(0, import_node_fs45.existsSync)(artifactPath) || (0, import_node_fs45.statSync)(artifactPath).size === 0) {
75600
+ throw new Error(`the ${viewpoint} render reported success but produced no image`);
75601
+ }
75602
+ const bytes = (0, import_node_fs45.readFileSync)(artifactPath);
75603
+ const preferred = `${exportFileBase(project, appId)}-${viewpoint}${extension}`;
75604
+ const filename = uniqueProjectExportFilename(project, preferred);
75605
+ publishProjectExportArtifact(project, {
75606
+ kind,
75607
+ variant: viewpoint,
75608
+ filename,
75609
+ encoding: "base64",
75610
+ bytes: bytes.length,
75611
+ version: projectSnapshot.version.n,
75612
+ contractHash: projectSnapshot.contractHash
75613
+ }, bytes);
75614
+ rendered.push({
75615
+ viewpoint,
75616
+ filename,
75617
+ bytes: bytes.length,
75618
+ // From the agent's OWN receipt, not from what was asked for. A turntable's frame count
75619
+ // and length are the difference between "it span twice as slowly" and "I set an input
75620
+ // and assumed", and only the receipt can settle that.
75621
+ ...output === "turntable" ? {
75622
+ frames: typeof receipt?.frames === "number" ? receipt.frames : null,
75623
+ seconds: typeof receipt?.["duration-seconds"] === "number" ? receipt["duration-seconds"] : null
75624
+ } : {}
75625
+ });
75626
+ progress("rendered", { viewpoint, index: i + 1, filename });
75627
+ }
75628
+ progress("done", { count: rendered.length });
75629
+ return {
75630
+ ok: true,
75631
+ kind,
75632
+ output,
75633
+ quality: output === "turntable" ? "draft" : quality,
75634
+ rendered,
75635
+ // Kept for a single-viewpoint caller so the existing shape still reads naturally.
75636
+ filename: rendered[0]?.filename,
75637
+ viewpoint: rendered[0]?.viewpoint,
75638
+ savedTo: rendered[0] ? (0, import_node_path42.join)(projectExportsDir(project), rendered[0].filename) : void 0
75639
+ };
75640
+ } catch (error) {
75641
+ app.log.warn(
75642
+ { appId, project, output, viewpoints, err: error instanceof Error ? error.message : error },
75643
+ "render failed"
75644
+ );
75645
+ progress("failed", { count: rendered.length });
75646
+ return reply.status(502).send({
75647
+ ok: false,
75648
+ error: error instanceof Error ? error.message : "rendering failed",
75649
+ // A partial batch is not a rollback: the viewpoints that DID render are published and on
75650
+ // disk, and pretending otherwise would leave the user unable to find them.
75651
+ rendered
75652
+ });
75653
+ } finally {
75654
+ (0, import_node_fs45.rmSync)(scratch, { recursive: true, force: true });
75655
+ }
75656
+ }, {
75657
+ // What anyone blocked on this project is told, and for how long to expect it. Erring long
75658
+ // on purpose: over-declaring costs a waiter one needless refusal, under-declaring costs it
75659
+ // a silent multi-minute stall, which is the failure this exists to remove.
75660
+ label: "rendering",
75661
+ expectedMs: renderExpectedMs(output, quality, viewpoints.length)
75662
+ });
75663
+ });
75064
75664
  app.post("/api/contract/:appId/export-tekla", async (req, reply) => {
75065
75665
  const appId = req.params.appId;
75066
75666
  const project = req.query.project || void 0;
@@ -75156,7 +75756,7 @@ async function startServer() {
75156
75756
  app.log.error({ companionId: companion.id, error: error instanceof Error ? error.message : error }, "could not remove Tekla export companion");
75157
75757
  }
75158
75758
  }
75159
- });
75759
+ }, { label: "sending the model to Tekla" });
75160
75760
  });
75161
75761
  app.post("/api/contract/:appId/export-bom/:format", async (req, reply) => {
75162
75762
  const { appId, format } = req.params;
@@ -75193,10 +75793,10 @@ async function startServer() {
75193
75793
  }
75194
75794
  const preferredFilename = `${exportFileBase(project, appId)}-bom.${format}`;
75195
75795
  const filename = project ? uniqueProjectExportFilename(project, preferredFilename) : preferredFilename;
75196
- const outPath = project ? (0, import_node_path41.join)(projectExportsDir(project), filename) : bomExportPath(appId, format);
75197
- const dir = (0, import_node_path41.dirname)(outPath);
75796
+ const outPath = project ? (0, import_node_path42.join)(projectExportsDir(project), filename) : bomExportPath(appId, format);
75797
+ const dir = (0, import_node_path42.dirname)(outPath);
75198
75798
  try {
75199
- (0, import_node_fs44.mkdirSync)(dir, { recursive: true });
75799
+ (0, import_node_fs45.mkdirSync)(dir, { recursive: true });
75200
75800
  if (format === "csv") {
75201
75801
  const text2 = bomToCsv(bom);
75202
75802
  if (project && projectSnapshot) {
@@ -75208,7 +75808,7 @@ async function startServer() {
75208
75808
  version: projectSnapshot.version.n,
75209
75809
  contractHash: projectSnapshot.contractHash
75210
75810
  }, Buffer.from(text2, "utf8"));
75211
- } else (0, import_node_fs44.writeFileSync)(outPath, text2, "utf8");
75811
+ } else (0, import_node_fs45.writeFileSync)(outPath, text2, "utf8");
75212
75812
  return { ok: true, filename, encoding: "utf8", content: text2, bytes: Buffer.byteLength(text2), savedTo: outPath };
75213
75813
  }
75214
75814
  const buf = await bomToXlsx(bom);
@@ -75221,7 +75821,7 @@ async function startServer() {
75221
75821
  version: projectSnapshot.version.n,
75222
75822
  contractHash: projectSnapshot.contractHash
75223
75823
  }, buf);
75224
- } else (0, import_node_fs44.writeFileSync)(outPath, buf);
75824
+ } else (0, import_node_fs45.writeFileSync)(outPath, buf);
75225
75825
  return { ok: true, filename, encoding: "base64", content: buf.toString("base64"), bytes: buf.length, savedTo: outPath };
75226
75826
  } catch (e) {
75227
75827
  app.log.error({ appId, format, err: e instanceof Error ? e.message : e }, "export-bom: generation failed");
@@ -75259,9 +75859,9 @@ async function startServer() {
75259
75859
  const svg = contractToSvg(cleaned);
75260
75860
  const preferredFilename = `${exportFileBase(project, req.params.appId)}.svg`;
75261
75861
  const filename = project ? uniqueProjectExportFilename(project, preferredFilename) : preferredFilename;
75262
- const outPath = project ? (0, import_node_path41.join)(projectExportsDir(project), filename) : (0, import_node_path41.join)(appPath(req.params.appId), filename);
75862
+ const outPath = project ? (0, import_node_path42.join)(projectExportsDir(project), filename) : (0, import_node_path42.join)(appPath(req.params.appId), filename);
75263
75863
  try {
75264
- (0, import_node_fs44.mkdirSync)((0, import_node_path41.dirname)(outPath), { recursive: true });
75864
+ (0, import_node_fs45.mkdirSync)((0, import_node_path42.dirname)(outPath), { recursive: true });
75265
75865
  if (project && projectSnapshot) {
75266
75866
  publishProjectExportArtifact(project, {
75267
75867
  kind: "svg",
@@ -75271,7 +75871,7 @@ async function startServer() {
75271
75871
  version: projectSnapshot.version.n,
75272
75872
  contractHash: projectSnapshot.contractHash
75273
75873
  }, Buffer.from(svg, "utf8"));
75274
- } else (0, import_node_fs44.writeFileSync)(outPath, svg, "utf8");
75874
+ } else (0, import_node_fs45.writeFileSync)(outPath, svg, "utf8");
75275
75875
  return { ok: true, filename, encoding: "utf8", content: svg, bytes: Buffer.byteLength(svg), savedTo: outPath };
75276
75876
  } catch (e) {
75277
75877
  app.log.error({ appId: req.params.appId, err: e instanceof Error ? e.message : e }, "export-svg: write failed");
@@ -75354,7 +75954,7 @@ async function startServer() {
75354
75954
  return reply.status(404).send({ ok: false, error: `"${id}" is not installed`, code: "not-installed" });
75355
75955
  }
75356
75956
  const contract = readAcceptedForRequest(id, void 0);
75357
- if (contract == null && (0, import_node_fs44.existsSync)(contractPath(id))) {
75957
+ if (contract == null && (0, import_node_fs45.existsSync)(contractPath(id))) {
75358
75958
  return reply.status(409).send({ ok: false, error: `"${id}"'s saved data is unreadable \u2014 open it in the editor and re-save before restoring`, code: "contract-corrupt" });
75359
75959
  }
75360
75960
  if (contract != null) {
@@ -75435,11 +76035,11 @@ async function startServer() {
75435
76035
  return reply.status(409).send({ ok: false, error: `a workflow named "${id}" is already installed \u2014 remove it first, or rename the file's app: id`, code: "exists", id });
75436
76036
  }
75437
76037
  await deleteOrigin(id);
75438
- const stageRoot = (0, import_node_fs44.mkdtempSync)((0, import_node_path41.join)((0, import_node_os24.tmpdir)(), "floless-import-"));
76038
+ const stageRoot = (0, import_node_fs45.mkdtempSync)((0, import_node_path42.join)((0, import_node_os25.tmpdir)(), "floless-import-"));
75439
76039
  try {
75440
- const stageDir = (0, import_node_path41.join)(stageRoot, id);
75441
- (0, import_node_fs44.mkdirSync)(stageDir);
75442
- (0, import_node_fs44.writeFileSync)((0, import_node_path41.join)(stageDir, `${id}.flo`), content);
76040
+ const stageDir = (0, import_node_path42.join)(stageRoot, id);
76041
+ (0, import_node_fs45.mkdirSync)(stageDir);
76042
+ (0, import_node_fs45.writeFileSync)((0, import_node_path42.join)(stageDir, `${id}.flo`), content);
75443
76043
  await aware.install(stageDir);
75444
76044
  } catch (err2) {
75445
76045
  try {
@@ -75450,7 +76050,7 @@ async function startServer() {
75450
76050
  const reason = awareStderr(err2);
75451
76051
  return reply.status(502).send({ ok: false, error: `import failed: ${msg}`, code: "install-failed", reason, agentsUnavailable: unavailableAgents(reason) });
75452
76052
  } finally {
75453
- (0, import_node_fs44.rmSync)(stageRoot, { recursive: true, force: true });
76053
+ (0, import_node_fs45.rmSync)(stageRoot, { recursive: true, force: true });
75454
76054
  }
75455
76055
  broadcast({ type: "apps-changed", id });
75456
76056
  return { ok: true, id };
@@ -75465,13 +76065,13 @@ async function startServer() {
75465
76065
  }
75466
76066
  const inputs = appData.inputs.map((i) => ({ name: i.name, type: i.type }));
75467
76067
  const baked = bakeFloSource(appData.source.text, inputs);
75468
- const tmpRoot = (0, import_node_fs44.mkdtempSync)((0, import_node_path41.join)((0, import_node_os24.tmpdir)(), "floless-bake-"));
75469
- const backupDir2 = (0, import_node_path41.join)(tmpRoot, `${id}-backup`);
75470
- const bakeDir = (0, import_node_path41.join)(tmpRoot, id);
75471
- (0, import_node_fs44.cpSync)(appDir(id), backupDir2, { recursive: true });
75472
- (0, import_node_fs44.cpSync)(appDir(id), bakeDir, { recursive: true });
76068
+ const tmpRoot = (0, import_node_fs45.mkdtempSync)((0, import_node_path42.join)((0, import_node_os25.tmpdir)(), "floless-bake-"));
76069
+ const backupDir2 = (0, import_node_path42.join)(tmpRoot, `${id}-backup`);
76070
+ const bakeDir = (0, import_node_path42.join)(tmpRoot, id);
76071
+ (0, import_node_fs45.cpSync)(appDir(id), backupDir2, { recursive: true });
76072
+ (0, import_node_fs45.cpSync)(appDir(id), bakeDir, { recursive: true });
75473
76073
  const floName = appData.source.path.split(/[\\/]/).pop();
75474
- (0, import_node_fs44.writeFileSync)((0, import_node_path41.join)(bakeDir, floName), baked);
76074
+ (0, import_node_fs45.writeFileSync)((0, import_node_path42.join)(bakeDir, floName), baked);
75475
76075
  let appInstalled2 = true;
75476
76076
  try {
75477
76077
  await aware.uninstall(id);
@@ -75493,17 +76093,17 @@ async function startServer() {
75493
76093
  throw installErr;
75494
76094
  }
75495
76095
  try {
75496
- await aware.compile((0, import_node_path41.join)(appDir(id), floName));
76096
+ await aware.compile((0, import_node_path42.join)(appDir(id), floName));
75497
76097
  } catch (compileErr) {
75498
76098
  app.log.warn({ id, compileErr: String(compileErr) }, "bake: post-install recompile failed (app baked but may need a manual Compile)");
75499
76099
  }
75500
76100
  broadcast({ type: "baked", id });
75501
76101
  return { ok: true, id, agent: id, inputs };
75502
76102
  } finally {
75503
- if (appInstalled2) (0, import_node_fs44.rmSync)(tmpRoot, { recursive: true, force: true });
76103
+ if (appInstalled2) (0, import_node_fs45.rmSync)(tmpRoot, { recursive: true, force: true });
75504
76104
  }
75505
76105
  });
75506
- const graftAgentsDir = () => (0, import_node_path41.join)((0, import_node_os24.homedir)(), ".aware", "agents");
76106
+ const graftAgentsDir = () => (0, import_node_path42.join)((0, import_node_os25.homedir)(), ".aware", "agents");
75507
76107
  app.post("/api/graft/match", async (req, reply) => {
75508
76108
  const { glob } = req.body ?? {};
75509
76109
  if (!glob) return reply.status(400).send({ ok: false, error: "glob required" });
@@ -75520,7 +76120,7 @@ async function startServer() {
75520
76120
  if (!sourceKind || !sourceRef) {
75521
76121
  return reply.status(400).send({ ok: false, error: "sourceKind and sourceRef required" });
75522
76122
  }
75523
- const tempHome = (0, import_node_fs44.mkdtempSync)((0, import_node_path41.join)((0, import_node_os24.tmpdir)(), "floless-graft-"));
76123
+ const tempHome = (0, import_node_fs45.mkdtempSync)((0, import_node_path42.join)((0, import_node_os25.tmpdir)(), "floless-graft-"));
75524
76124
  let result;
75525
76125
  try {
75526
76126
  result = await aware.build({
@@ -75533,19 +76133,19 @@ async function startServer() {
75533
76133
  awareHome: tempHome
75534
76134
  });
75535
76135
  } catch (err2) {
75536
- (0, import_node_fs44.rmSync)(tempHome, { recursive: true, force: true });
76136
+ (0, import_node_fs45.rmSync)(tempHome, { recursive: true, force: true });
75537
76137
  const msg = err2 instanceof AwareError ? err2.message : String(err2?.message ?? err2);
75538
76138
  return reply.status(422).send({ ok: false, error: msg });
75539
76139
  }
75540
76140
  const manifest = readStagedManifest(result.agentDir);
75541
76141
  if (!manifest) {
75542
- (0, import_node_fs44.rmSync)(tempHome, { recursive: true, force: true });
76142
+ (0, import_node_fs45.rmSync)(tempHome, { recursive: true, force: true });
75543
76143
  return reply.status(502).send({ ok: false, error: `build produced output at ${result.agentDir} but no manifest.yaml` });
75544
76144
  }
75545
76145
  const token = (0, import_node_crypto20.randomUUID)();
75546
76146
  registerStage(token, tempHome, result.agentId);
75547
76147
  const preview2 = buildPreview(manifest, sourceKind, sourceRef, token);
75548
- if ((0, import_node_fs44.existsSync)((0, import_node_path41.join)(graftAgentsDir(), result.agentId))) {
76148
+ if ((0, import_node_fs45.existsSync)((0, import_node_path42.join)(graftAgentsDir(), result.agentId))) {
75549
76149
  preview2.warnings.unshift(`An agent named "${result.agentId}" is already installed \u2014 creating it will overwrite it.`);
75550
76150
  }
75551
76151
  return { ok: true, preview: preview2 };
@@ -75564,7 +76164,7 @@ async function startServer() {
75564
76164
  registerStage(stagedRef, stage.tempDir, stage.agentId);
75565
76165
  return reply.status(409).send({ ok: false, error: err2.message, agentId: stage.agentId, collision: true });
75566
76166
  }
75567
- (0, import_node_fs44.rmSync)(stage.tempDir, { recursive: true, force: true });
76167
+ (0, import_node_fs45.rmSync)(stage.tempDir, { recursive: true, force: true });
75568
76168
  throw err2;
75569
76169
  }
75570
76170
  broadcast({ type: "grafted", id: stage.agentId });
@@ -75881,11 +76481,11 @@ async function startServer() {
75881
76481
  app.get("/api/requests/:id/snapshot/:n", async (req, reply) => {
75882
76482
  const n = Number.parseInt(req.params.n, 10);
75883
76483
  const p = Number.isInteger(n) ? snapshotPathFor(req.params.id, n) : null;
75884
- if (!p || !(0, import_node_fs44.existsSync)(p)) return reply.status(404).send({ ok: false, error: "snapshot not found" });
76484
+ if (!p || !(0, import_node_fs45.existsSync)(p)) return reply.status(404).send({ ok: false, error: "snapshot not found" });
75885
76485
  const ext = p.split(".").pop().toLowerCase();
75886
76486
  reply.header("Content-Type", ext === "png" ? "image/png" : ext === "webp" ? "image/webp" : ext === "pdf" ? "application/pdf" : "image/jpeg");
75887
76487
  reply.header("Cache-Control", "no-store");
75888
- return (0, import_node_fs44.readFileSync)(p);
76488
+ return (0, import_node_fs45.readFileSync)(p);
75889
76489
  });
75890
76490
  app.post(
75891
76491
  "/api/tweak",
@@ -76112,7 +76712,7 @@ async function startServer() {
76112
76712
  warn(`last-run-status:${ref} \u2014 trace exists but couldn't be parsed (corrupt/truncated)`);
76113
76713
  let finishedAt2 = null;
76114
76714
  try {
76115
- finishedAt2 = (0, import_node_fs44.statSync)(latest.path).mtime.toISOString();
76715
+ finishedAt2 = (0, import_node_fs45.statSync)(latest.path).mtime.toISOString();
76116
76716
  } catch {
76117
76717
  finishedAt2 = null;
76118
76718
  }
@@ -76122,7 +76722,7 @@ async function startServer() {
76122
76722
  let finishedAt = typeof runEnd?.ts === "string" ? runEnd.ts : null;
76123
76723
  if (!finishedAt) {
76124
76724
  try {
76125
- finishedAt = (0, import_node_fs44.statSync)(latest.path).mtime.toISOString();
76725
+ finishedAt = (0, import_node_fs45.statSync)(latest.path).mtime.toISOString();
76126
76726
  } catch {
76127
76727
  finishedAt = null;
76128
76728
  }