@factiii/runner 0.23.0 → 0.23.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -963,8 +963,8 @@ var require_command = __commonJS({
963
963
  "node_modules/commander/lib/command.js"(exports2) {
964
964
  var EventEmitter = require("node:events").EventEmitter;
965
965
  var childProcess = require("node:child_process");
966
- var path29 = require("node:path");
967
- var fs21 = require("node:fs");
966
+ var path30 = require("node:path");
967
+ var fs22 = require("node:fs");
968
968
  var process3 = require("node:process");
969
969
  var { Argument: Argument2, humanReadableArgName } = require_argument();
970
970
  var { CommanderError: CommanderError2 } = require_error();
@@ -1896,11 +1896,11 @@ Expecting one of '${allowedValues.join("', '")}'`);
1896
1896
  let launchWithNode = false;
1897
1897
  const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1898
1898
  function findFile(baseDir, baseName) {
1899
- const localBin = path29.resolve(baseDir, baseName);
1900
- if (fs21.existsSync(localBin)) return localBin;
1901
- if (sourceExt.includes(path29.extname(baseName))) return void 0;
1899
+ const localBin = path30.resolve(baseDir, baseName);
1900
+ if (fs22.existsSync(localBin)) return localBin;
1901
+ if (sourceExt.includes(path30.extname(baseName))) return void 0;
1902
1902
  const foundExt = sourceExt.find(
1903
- (ext) => fs21.existsSync(`${localBin}${ext}`)
1903
+ (ext) => fs22.existsSync(`${localBin}${ext}`)
1904
1904
  );
1905
1905
  if (foundExt) return `${localBin}${foundExt}`;
1906
1906
  return void 0;
@@ -1912,21 +1912,21 @@ Expecting one of '${allowedValues.join("', '")}'`);
1912
1912
  if (this._scriptPath) {
1913
1913
  let resolvedScriptPath;
1914
1914
  try {
1915
- resolvedScriptPath = fs21.realpathSync(this._scriptPath);
1915
+ resolvedScriptPath = fs22.realpathSync(this._scriptPath);
1916
1916
  } catch (err2) {
1917
1917
  resolvedScriptPath = this._scriptPath;
1918
1918
  }
1919
- executableDir = path29.resolve(
1920
- path29.dirname(resolvedScriptPath),
1919
+ executableDir = path30.resolve(
1920
+ path30.dirname(resolvedScriptPath),
1921
1921
  executableDir
1922
1922
  );
1923
1923
  }
1924
1924
  if (executableDir) {
1925
1925
  let localFile = findFile(executableDir, executableFile);
1926
1926
  if (!localFile && !subcommand._executableFile && this._scriptPath) {
1927
- const legacyName = path29.basename(
1927
+ const legacyName = path30.basename(
1928
1928
  this._scriptPath,
1929
- path29.extname(this._scriptPath)
1929
+ path30.extname(this._scriptPath)
1930
1930
  );
1931
1931
  if (legacyName !== this._name) {
1932
1932
  localFile = findFile(
@@ -1937,7 +1937,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
1937
1937
  }
1938
1938
  executableFile = localFile || executableFile;
1939
1939
  }
1940
- launchWithNode = sourceExt.includes(path29.extname(executableFile));
1940
+ launchWithNode = sourceExt.includes(path30.extname(executableFile));
1941
1941
  let proc;
1942
1942
  if (process3.platform !== "win32") {
1943
1943
  if (launchWithNode) {
@@ -2777,7 +2777,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
2777
2777
  * @return {Command}
2778
2778
  */
2779
2779
  nameFromFilename(filename) {
2780
- this._name = path29.basename(filename, path29.extname(filename));
2780
+ this._name = path30.basename(filename, path30.extname(filename));
2781
2781
  return this;
2782
2782
  }
2783
2783
  /**
@@ -2791,9 +2791,9 @@ Expecting one of '${allowedValues.join("', '")}'`);
2791
2791
  * @param {string} [path]
2792
2792
  * @return {(string|null|Command)}
2793
2793
  */
2794
- executableDir(path30) {
2795
- if (path30 === void 0) return this._executableDir;
2796
- this._executableDir = path30;
2794
+ executableDir(path31) {
2795
+ if (path31 === void 0) return this._executableDir;
2796
+ this._executableDir = path31;
2797
2797
  return this;
2798
2798
  }
2799
2799
  /**
@@ -3026,7 +3026,7 @@ var require_commander = __commonJS({
3026
3026
  // ../../node_modules/xmlhttprequest-ssl/lib/XMLHttpRequest.js
3027
3027
  var require_XMLHttpRequest = __commonJS({
3028
3028
  "../../node_modules/xmlhttprequest-ssl/lib/XMLHttpRequest.js"(exports2, module2) {
3029
- var fs21 = require("fs");
3029
+ var fs22 = require("fs");
3030
3030
  var Url = require("url");
3031
3031
  var spawn7 = require("child_process").spawn;
3032
3032
  module2.exports = XMLHttpRequest3;
@@ -3089,8 +3089,8 @@ var require_XMLHttpRequest = __commonJS({
3089
3089
  this.response = Buffer.alloc(0);
3090
3090
  this.status = null;
3091
3091
  this.statusText = null;
3092
- var isAllowedHttpHeader = function(header) {
3093
- return disableHeaderCheck || header && forbiddenRequestHeaders.indexOf(header.toLowerCase()) === -1;
3092
+ var isAllowedHttpHeader = function(header2) {
3093
+ return disableHeaderCheck || header2 && forbiddenRequestHeaders.indexOf(header2.toLowerCase()) === -1;
3094
3094
  };
3095
3095
  var isAllowedHttpMethod = function(method) {
3096
3096
  return method && forbiddenRequestMethods.indexOf(method) === -1;
@@ -3114,23 +3114,23 @@ var require_XMLHttpRequest = __commonJS({
3114
3114
  this.setDisableHeaderCheck = function(state) {
3115
3115
  disableHeaderCheck = state;
3116
3116
  };
3117
- this.setRequestHeader = function(header, value2) {
3117
+ this.setRequestHeader = function(header2, value2) {
3118
3118
  if (this.readyState != this.OPENED) {
3119
3119
  throw new Error("INVALID_STATE_ERR: setRequestHeader can only be called when state is OPEN");
3120
3120
  }
3121
- if (!isAllowedHttpHeader(header)) {
3122
- console.warn('Refused to set unsafe header "' + header + '"');
3121
+ if (!isAllowedHttpHeader(header2)) {
3122
+ console.warn('Refused to set unsafe header "' + header2 + '"');
3123
3123
  return false;
3124
3124
  }
3125
3125
  if (sendFlag) {
3126
3126
  throw new Error("INVALID_STATE_ERR: send flag is true");
3127
3127
  }
3128
- headers[header] = value2;
3128
+ headers[header2] = value2;
3129
3129
  return true;
3130
3130
  };
3131
- this.getResponseHeader = function(header) {
3132
- if (typeof header === "string" && this.readyState > this.OPENED && response.headers[header.toLowerCase()] && !errorFlag) {
3133
- return response.headers[header.toLowerCase()];
3131
+ this.getResponseHeader = function(header2) {
3132
+ if (typeof header2 === "string" && this.readyState > this.OPENED && response.headers[header2.toLowerCase()] && !errorFlag) {
3133
+ return response.headers[header2.toLowerCase()];
3134
3134
  }
3135
3135
  return null;
3136
3136
  };
@@ -3184,7 +3184,7 @@ var require_XMLHttpRequest = __commonJS({
3184
3184
  throw new Error("XMLHttpRequest: Only GET method is supported");
3185
3185
  }
3186
3186
  if (settings.async) {
3187
- fs21.readFile(unescape(url3.pathname), function(error61, data2) {
3187
+ fs22.readFile(unescape(url3.pathname), function(error61, data2) {
3188
3188
  if (error61) {
3189
3189
  self.handleError(error61, error61.errno || -1);
3190
3190
  } else {
@@ -3196,7 +3196,7 @@ var require_XMLHttpRequest = __commonJS({
3196
3196
  });
3197
3197
  } else {
3198
3198
  try {
3199
- this.response = fs21.readFileSync(unescape(url3.pathname));
3199
+ this.response = fs22.readFileSync(unescape(url3.pathname));
3200
3200
  this.responseText = this.response.toString("utf8");
3201
3201
  this.status = 200;
3202
3202
  setState(self.DONE);
@@ -3322,15 +3322,15 @@ var require_XMLHttpRequest = __commonJS({
3322
3322
  } else {
3323
3323
  var contentFile = ".node-xmlhttprequest-content-" + process.pid;
3324
3324
  var syncFile = ".node-xmlhttprequest-sync-" + process.pid;
3325
- fs21.writeFileSync(syncFile, "", "utf8");
3325
+ fs22.writeFileSync(syncFile, "", "utf8");
3326
3326
  var execString = "var http = require('http'), https = require('https'), fs = require('fs');var doRequest = http" + (ssl ? "s" : "") + ".request;var options = " + JSON.stringify(options) + ";var responseText = '';var responseData = Buffer.alloc(0);var req = doRequest(options, function(response) {response.on('data', function(chunk) { var data = Buffer.from(chunk); responseText += data.toString('utf8'); responseData = Buffer.concat([responseData, data]);});response.on('end', function() {fs.writeFileSync('" + contentFile + "', JSON.stringify({err: null, data: {statusCode: response.statusCode, headers: response.headers, text: responseText, data: responseData.toString('base64')}}), 'utf8');fs.unlinkSync('" + syncFile + "');});response.on('error', function(error) {fs.writeFileSync('" + contentFile + "', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('" + syncFile + "');});}).on('error', function(error) {fs.writeFileSync('" + contentFile + "', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('" + syncFile + "');});" + (data ? "req.write('" + JSON.stringify(data).slice(1, -1).replace(/'/g, "\\'") + "');" : "") + "req.end();";
3327
3327
  var syncProc = spawn7(process.argv[0], ["-e", execString]);
3328
3328
  var statusText;
3329
- while (fs21.existsSync(syncFile)) {
3329
+ while (fs22.existsSync(syncFile)) {
3330
3330
  }
3331
- self.responseText = fs21.readFileSync(contentFile, "utf8");
3331
+ self.responseText = fs22.readFileSync(contentFile, "utf8");
3332
3332
  syncProc.stdin.end();
3333
- fs21.unlinkSync(contentFile);
3333
+ fs22.unlinkSync(contentFile);
3334
3334
  if (self.responseText.match(/^NODE-XMLHTTPREQUEST-ERROR:/)) {
3335
3335
  var errorObj = JSON.parse(self.responseText.replace(/^NODE-XMLHTTPREQUEST-ERROR:/, ""));
3336
3336
  self.handleError(errorObj, 503);
@@ -6346,7 +6346,7 @@ var require_extension = __commonJS({
6346
6346
  if (dest[name] === void 0) dest[name] = [elem];
6347
6347
  else dest[name].push(elem);
6348
6348
  }
6349
- function parse5(header) {
6349
+ function parse5(header2) {
6350
6350
  const offers = /* @__PURE__ */ Object.create(null);
6351
6351
  let params = /* @__PURE__ */ Object.create(null);
6352
6352
  let mustUnescape = false;
@@ -6358,8 +6358,8 @@ var require_extension = __commonJS({
6358
6358
  let code = -1;
6359
6359
  let end = -1;
6360
6360
  let i = 0;
6361
- for (; i < header.length; i++) {
6362
- code = header.charCodeAt(i);
6361
+ for (; i < header2.length; i++) {
6362
+ code = header2.charCodeAt(i);
6363
6363
  if (extensionName === void 0) {
6364
6364
  if (end === -1 && tokenChars[code] === 1) {
6365
6365
  if (start === -1) start = i;
@@ -6370,7 +6370,7 @@ var require_extension = __commonJS({
6370
6370
  throw new SyntaxError(`Unexpected character at index ${i}`);
6371
6371
  }
6372
6372
  if (end === -1) end = i;
6373
- const name = header.slice(start, end);
6373
+ const name = header2.slice(start, end);
6374
6374
  if (code === 44) {
6375
6375
  push(offers, name, params);
6376
6376
  params = /* @__PURE__ */ Object.create(null);
@@ -6391,7 +6391,7 @@ var require_extension = __commonJS({
6391
6391
  throw new SyntaxError(`Unexpected character at index ${i}`);
6392
6392
  }
6393
6393
  if (end === -1) end = i;
6394
- push(params, header.slice(start, end), true);
6394
+ push(params, header2.slice(start, end), true);
6395
6395
  if (code === 44) {
6396
6396
  push(offers, extensionName, params);
6397
6397
  params = /* @__PURE__ */ Object.create(null);
@@ -6399,7 +6399,7 @@ var require_extension = __commonJS({
6399
6399
  }
6400
6400
  start = end = -1;
6401
6401
  } else if (code === 61 && start !== -1 && end === -1) {
6402
- paramName = header.slice(start, i);
6402
+ paramName = header2.slice(start, i);
6403
6403
  start = end = -1;
6404
6404
  } else {
6405
6405
  throw new SyntaxError(`Unexpected character at index ${i}`);
@@ -6423,7 +6423,7 @@ var require_extension = __commonJS({
6423
6423
  } else {
6424
6424
  throw new SyntaxError(`Unexpected character at index ${i}`);
6425
6425
  }
6426
- } else if (code === 34 && header.charCodeAt(i - 1) === 61) {
6426
+ } else if (code === 34 && header2.charCodeAt(i - 1) === 61) {
6427
6427
  inQuotes = true;
6428
6428
  } else if (end === -1 && tokenChars[code] === 1) {
6429
6429
  if (start === -1) start = i;
@@ -6434,7 +6434,7 @@ var require_extension = __commonJS({
6434
6434
  throw new SyntaxError(`Unexpected character at index ${i}`);
6435
6435
  }
6436
6436
  if (end === -1) end = i;
6437
- let value2 = header.slice(start, end);
6437
+ let value2 = header2.slice(start, end);
6438
6438
  if (mustUnescape) {
6439
6439
  value2 = value2.replace(/\\/g, "");
6440
6440
  mustUnescape = false;
@@ -6456,7 +6456,7 @@ var require_extension = __commonJS({
6456
6456
  throw new SyntaxError("Unexpected end of input");
6457
6457
  }
6458
6458
  if (end === -1) end = i;
6459
- const token = header.slice(start, end);
6459
+ const token = header2.slice(start, end);
6460
6460
  if (extensionName === void 0) {
6461
6461
  push(offers, token, params);
6462
6462
  } else {
@@ -7489,13 +7489,13 @@ var require_subprotocol = __commonJS({
7489
7489
  "../../node_modules/ws/lib/subprotocol.js"(exports2, module2) {
7490
7490
  "use strict";
7491
7491
  var { tokenChars } = require_validation();
7492
- function parse5(header) {
7492
+ function parse5(header2) {
7493
7493
  const protocols = /* @__PURE__ */ new Set();
7494
7494
  let start = -1;
7495
7495
  let end = -1;
7496
7496
  let i = 0;
7497
- for (i; i < header.length; i++) {
7498
- const code = header.charCodeAt(i);
7497
+ for (i; i < header2.length; i++) {
7498
+ const code = header2.charCodeAt(i);
7499
7499
  if (end === -1 && tokenChars[code] === 1) {
7500
7500
  if (start === -1) start = i;
7501
7501
  } else if (i !== 0 && (code === 32 || code === 9)) {
@@ -7505,7 +7505,7 @@ var require_subprotocol = __commonJS({
7505
7505
  throw new SyntaxError(`Unexpected character at index ${i}`);
7506
7506
  }
7507
7507
  if (end === -1) end = i;
7508
- const protocol5 = header.slice(start, end);
7508
+ const protocol5 = header2.slice(start, end);
7509
7509
  if (protocols.has(protocol5)) {
7510
7510
  throw new SyntaxError(`The "${protocol5}" subprotocol is duplicated`);
7511
7511
  }
@@ -7518,7 +7518,7 @@ var require_subprotocol = __commonJS({
7518
7518
  if (start === -1 || end !== -1) {
7519
7519
  throw new SyntaxError("Unexpected end of input");
7520
7520
  }
7521
- const protocol4 = header.slice(start, i);
7521
+ const protocol4 = header2.slice(start, i);
7522
7522
  if (protocols.has(protocol4)) {
7523
7523
  throw new SyntaxError(`The "${protocol4}" subprotocol is duplicated`);
7524
7524
  }
@@ -7932,6 +7932,8 @@ var require_websocket_server = __commonJS({
7932
7932
 
7933
7933
  // src/cli.ts
7934
7934
  var import_node_dns = __toESM(require("node:dns"));
7935
+ var import_promises15 = __toESM(require("node:fs/promises"));
7936
+ var import_node_path3 = __toESM(require("node:path"));
7935
7937
 
7936
7938
  // node_modules/commander/esm.mjs
7937
7939
  var import_index = __toESM(require_commander(), 1);
@@ -8642,12 +8644,12 @@ function cleanRegex(source) {
8642
8644
  return source.slice(start, end);
8643
8645
  }
8644
8646
  function floatSafeRemainder(val, step) {
8645
- const ratio2 = val / step;
8646
- const roundedRatio = Math.round(ratio2);
8647
- const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio2), 1);
8648
- if (Math.abs(ratio2 - roundedRatio) < tolerance)
8647
+ const ratio3 = val / step;
8648
+ const roundedRatio = Math.round(ratio3);
8649
+ const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio3), 1);
8650
+ if (Math.abs(ratio3 - roundedRatio) < tolerance)
8649
8651
  return 0;
8650
- return ratio2 - roundedRatio;
8652
+ return ratio3 - roundedRatio;
8651
8653
  }
8652
8654
  var EVALUATING = /* @__PURE__ */ Symbol("evaluating");
8653
8655
  function defineLazy(object2, key, getter) {
@@ -8694,10 +8696,10 @@ function mergeDefs(...defs) {
8694
8696
  function cloneDef(schema) {
8695
8697
  return mergeDefs(schema._zod.def);
8696
8698
  }
8697
- function getElementAtPath(obj, path29) {
8698
- if (!path29)
8699
+ function getElementAtPath(obj, path30) {
8700
+ if (!path30)
8699
8701
  return obj;
8700
- return path29.reduce((acc, key) => acc?.[key], obj);
8702
+ return path30.reduce((acc, key) => acc?.[key], obj);
8701
8703
  }
8702
8704
  function promiseAllObject(promisesObj) {
8703
8705
  const keys = Object.keys(promisesObj);
@@ -9109,11 +9111,11 @@ function explicitlyAborted(x, startIndex = 0) {
9109
9111
  }
9110
9112
  return false;
9111
9113
  }
9112
- function prefixIssues(path29, issues) {
9114
+ function prefixIssues(path30, issues) {
9113
9115
  return issues.map((iss) => {
9114
9116
  var _a3;
9115
9117
  (_a3 = iss).path ?? (_a3.path = []);
9116
- iss.path.unshift(path29);
9118
+ iss.path.unshift(path30);
9117
9119
  return iss;
9118
9120
  });
9119
9121
  }
@@ -9546,16 +9548,16 @@ function flattenError(error61, mapper = (issue2) => issue2.message) {
9546
9548
  }
9547
9549
  function formatError(error61, mapper = (issue2) => issue2.message) {
9548
9550
  const fieldErrors = { _errors: [] };
9549
- const processError = (error62, path29 = []) => {
9551
+ const processError = (error62, path30 = []) => {
9550
9552
  for (const issue2 of error62.issues) {
9551
9553
  if (issue2.code === "invalid_union" && issue2.errors.length) {
9552
- issue2.errors.map((issues) => processError({ issues }, [...path29, ...issue2.path]));
9554
+ issue2.errors.map((issues) => processError({ issues }, [...path30, ...issue2.path]));
9553
9555
  } else if (issue2.code === "invalid_key") {
9554
- processError({ issues: issue2.issues }, [...path29, ...issue2.path]);
9556
+ processError({ issues: issue2.issues }, [...path30, ...issue2.path]);
9555
9557
  } else if (issue2.code === "invalid_element") {
9556
- processError({ issues: issue2.issues }, [...path29, ...issue2.path]);
9558
+ processError({ issues: issue2.issues }, [...path30, ...issue2.path]);
9557
9559
  } else {
9558
- const fullpath = [...path29, ...issue2.path];
9560
+ const fullpath = [...path30, ...issue2.path];
9559
9561
  if (fullpath.length === 0) {
9560
9562
  fieldErrors._errors.push(mapper(issue2));
9561
9563
  } else {
@@ -9594,17 +9596,17 @@ function formatError(error61, mapper = (issue2) => issue2.message) {
9594
9596
  }
9595
9597
  function treeifyError(error61, mapper = (issue2) => issue2.message) {
9596
9598
  const result = { errors: [] };
9597
- const processError = (error62, path29 = []) => {
9599
+ const processError = (error62, path30 = []) => {
9598
9600
  var _a3;
9599
9601
  for (const issue2 of error62.issues) {
9600
9602
  if (issue2.code === "invalid_union" && issue2.errors.length) {
9601
- issue2.errors.map((issues) => processError({ issues }, [...path29, ...issue2.path]));
9603
+ issue2.errors.map((issues) => processError({ issues }, [...path30, ...issue2.path]));
9602
9604
  } else if (issue2.code === "invalid_key") {
9603
- processError({ issues: issue2.issues }, [...path29, ...issue2.path]);
9605
+ processError({ issues: issue2.issues }, [...path30, ...issue2.path]);
9604
9606
  } else if (issue2.code === "invalid_element") {
9605
- processError({ issues: issue2.issues }, [...path29, ...issue2.path]);
9607
+ processError({ issues: issue2.issues }, [...path30, ...issue2.path]);
9606
9608
  } else {
9607
- const fullpath = [...path29, ...issue2.path];
9609
+ const fullpath = [...path30, ...issue2.path];
9608
9610
  if (fullpath.length === 0) {
9609
9611
  result.errors.push(mapper(issue2));
9610
9612
  continue;
@@ -9643,8 +9645,8 @@ function treeifyError(error61, mapper = (issue2) => issue2.message) {
9643
9645
  }
9644
9646
  function toDotPath(_path) {
9645
9647
  const segs = [];
9646
- const path29 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
9647
- for (const seg of path29) {
9648
+ const path30 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
9649
+ for (const seg of path30) {
9648
9650
  if (typeof seg === "number")
9649
9651
  segs.push(`[${seg}]`);
9650
9652
  else if (typeof seg === "symbol")
@@ -11045,10 +11047,10 @@ function isValidJWT(token, algorithm = null) {
11045
11047
  const tokensParts = token.split(".");
11046
11048
  if (tokensParts.length !== 3)
11047
11049
  return false;
11048
- const [header] = tokensParts;
11049
- if (!header)
11050
+ const [header2] = tokensParts;
11051
+ if (!header2)
11050
11052
  return false;
11051
- const parsedHeader = JSON.parse(atob(header));
11053
+ const parsedHeader = JSON.parse(atob(header2));
11052
11054
  if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT")
11053
11055
  return false;
11054
11056
  if (!parsedHeader.alg)
@@ -26007,13 +26009,13 @@ function resolveRef(ref, ctx) {
26007
26009
  if (!ref.startsWith("#")) {
26008
26010
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
26009
26011
  }
26010
- const path29 = ref.slice(1).split("/").filter(Boolean);
26011
- if (path29.length === 0) {
26012
+ const path30 = ref.slice(1).split("/").filter(Boolean);
26013
+ if (path30.length === 0) {
26012
26014
  return ctx.rootSchema;
26013
26015
  }
26014
26016
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
26015
- if (path29[0] === defsKey) {
26016
- const key = path29[1] === void 0 ? void 0 : decodeJSONPointerSegment(path29[1]);
26017
+ if (path30[0] === defsKey) {
26018
+ const key = path30[1] === void 0 ? void 0 : decodeJSONPointerSegment(path30[1]);
26017
26019
  if (!key || !ctx.defs[key]) {
26018
26020
  throw new Error(`Reference not found: ${ref}`);
26019
26021
  }
@@ -27814,7 +27816,7 @@ async function ensurePrimaryClone(target, cloneUrl, branch) {
27814
27816
  await target.sh(`mkdir -p ${target.paths.worktrees}`);
27815
27817
  }
27816
27818
  async function addWorktree(target, workName, baseBranch, kind) {
27817
- const path29 = worktreeFor(target.paths, workName);
27819
+ const path30 = worktreeFor(target.paths, workName);
27818
27820
  const branch = workBranch(workName, kind);
27819
27821
  await gitInDir(
27820
27822
  target,
@@ -27824,7 +27826,7 @@ async function addWorktree(target, workName, baseBranch, kind) {
27824
27826
  baseBranch
27825
27827
  ).catch(() => {
27826
27828
  });
27827
- await removeWorktree(target, path29).catch(() => {
27829
+ await removeWorktree(target, path30).catch(() => {
27828
27830
  });
27829
27831
  await gitInDir(
27830
27832
  target,
@@ -27833,35 +27835,35 @@ async function addWorktree(target, workName, baseBranch, kind) {
27833
27835
  "add",
27834
27836
  "-B",
27835
27837
  branch,
27836
- path29,
27838
+ path30,
27837
27839
  `origin/${baseBranch}`
27838
27840
  );
27839
- return { path: path29, branch };
27841
+ return { path: path30, branch };
27840
27842
  }
27841
- async function removeWorktree(target, path29) {
27843
+ async function removeWorktree(target, path30) {
27842
27844
  const refused = await gitInDir(
27843
27845
  target,
27844
27846
  target.paths.repo,
27845
27847
  "worktree",
27846
27848
  "remove",
27847
27849
  "--force",
27848
- path29
27850
+ path30
27849
27851
  ).then(
27850
27852
  () => null,
27851
27853
  (err2) => err2
27852
27854
  );
27853
- const inside = isWorktreePath(target, path29) && !path29.split("/").includes("..");
27855
+ const inside = isWorktreePath(target, path30) && !path30.split("/").includes("..");
27854
27856
  if (refused && inside) {
27855
- await target.run(["rm", "-rf", "--", path29]);
27857
+ await target.run(["rm", "-rf", "--", path30]);
27856
27858
  await pruneWorktrees(target);
27857
27859
  return;
27858
27860
  }
27859
27861
  if (refused) throw refused;
27860
27862
  }
27861
- async function removeWorktreeAndBranch(target, path29) {
27862
- const head = await gitInDir(target, path29, "rev-parse", "--abbrev-ref", "HEAD").then((out2) => out2.trim()).catch(() => "");
27863
- await removeWorktree(target, path29).catch(() => pruneWorktrees(target));
27864
- const own2 = workBranch(path29.slice(path29.lastIndexOf("/") + 1), "terminal");
27863
+ async function removeWorktreeAndBranch(target, path30) {
27864
+ const head = await gitInDir(target, path30, "rev-parse", "--abbrev-ref", "HEAD").then((out2) => out2.trim()).catch(() => "");
27865
+ await removeWorktree(target, path30).catch(() => pruneWorktrees(target));
27866
+ const own2 = workBranch(path30.slice(path30.lastIndexOf("/") + 1), "terminal");
27865
27867
  const branches = /* @__PURE__ */ new Set();
27866
27868
  if (head && head !== "HEAD") branches.add(head);
27867
27869
  if (own2 === head || !await hasUnpublishedCommits(target, own2)) {
@@ -27880,8 +27882,8 @@ async function pruneWorktrees(target) {
27880
27882
  }
27881
27883
  );
27882
27884
  }
27883
- function isWorktreePath(target, path29) {
27884
- return path29.startsWith(`${target.paths.worktrees}/`);
27885
+ function isWorktreePath(target, path30) {
27886
+ return path30.startsWith(`${target.paths.worktrees}/`);
27885
27887
  }
27886
27888
  async function setGitIdentity(target, name, email3, workdir = target.paths.workspace) {
27887
27889
  if (name) await gitInDir(target, workdir, "config", "user.name", name);
@@ -27907,13 +27909,13 @@ function parseStatus(raw) {
27907
27909
  const y = line[1];
27908
27910
  const rest = line.slice(3);
27909
27911
  const arrow = rest.indexOf(" -> ");
27910
- const path29 = arrow === -1 ? rest : rest.slice(arrow + 4);
27912
+ const path30 = arrow === -1 ? rest : rest.slice(arrow + 4);
27911
27913
  if (x === "?" || y === "?") {
27912
- unstaged.push({ path: path29, code: "A" });
27914
+ unstaged.push({ path: path30, code: "A" });
27913
27915
  continue;
27914
27916
  }
27915
- if (x !== " ") staged.push({ path: path29, code: x });
27916
- if (y !== " ") unstaged.push({ path: path29, code: y });
27917
+ if (x !== " ") staged.push({ path: path30, code: x });
27918
+ if (y !== " ") unstaged.push({ path: path30, code: y });
27917
27919
  }
27918
27920
  return { staged, unstaged };
27919
27921
  }
@@ -28037,6 +28039,60 @@ async function readCommitDiff(target, workdir, sha) {
28037
28039
  changedFiles: names ? names.split("\n").filter(Boolean) : []
28038
28040
  };
28039
28041
  }
28042
+ function parseNameStatus(raw) {
28043
+ const files = [];
28044
+ for (const line of raw.split("\n")) {
28045
+ const tab = line.indexOf(" ");
28046
+ if (tab <= 0) continue;
28047
+ const path30 = line.slice(tab + 1).trim();
28048
+ if (path30) files.push({ path: path30, code: line[0] });
28049
+ }
28050
+ return files;
28051
+ }
28052
+ async function readBranchCompare(target, workdir, base, preferred) {
28053
+ const git = (...args) => gitInDir(target, workdir, "--no-optional-locks", ...args).catch(() => "");
28054
+ const current = (await git("rev-parse", "--abbrev-ref", "HEAD")).trim();
28055
+ const branches = [];
28056
+ const refs = await git(
28057
+ "for-each-ref",
28058
+ "--format=%(refname)",
28059
+ "refs/heads",
28060
+ "refs/remotes"
28061
+ );
28062
+ for (const line of refs.split("\n")) {
28063
+ const ref = line.trim();
28064
+ const name = ref.replace(/^refs\/(heads|remotes)\//, "");
28065
+ if (!name || name === ref || ref.endsWith("/HEAD")) continue;
28066
+ if (name !== current) branches.push(name);
28067
+ }
28068
+ const empty2 = { branches, files: [], diff: "", ahead: 0, behind: 0 };
28069
+ if (base !== void 0 && !branches.includes(base)) {
28070
+ throw new Error(`No branch named ${base} here.`);
28071
+ }
28072
+ const chosen = base ?? preferred.find((name) => branches.includes(name));
28073
+ if (!chosen) return { base: "", ...empty2 };
28074
+ const range = `${chosen}...HEAD`;
28075
+ const files = parseNameStatus(
28076
+ await git(
28077
+ "-c",
28078
+ "core.quotePath=false",
28079
+ "diff",
28080
+ "--name-status",
28081
+ "--no-renames",
28082
+ range
28083
+ )
28084
+ );
28085
+ const diff = await git("diff", "--no-color", "--no-renames", range);
28086
+ const [behind, ahead] = (await git("rev-list", "--left-right", "--count", range)).trim().split(/\s+/).map((n) => Number(n) || 0);
28087
+ return {
28088
+ base: chosen,
28089
+ branches,
28090
+ files,
28091
+ diff,
28092
+ ahead: ahead ?? 0,
28093
+ behind: behind ?? 0
28094
+ };
28095
+ }
28040
28096
  async function listRemoteBranches(target, workdir = target.paths.workspace) {
28041
28097
  try {
28042
28098
  const stdout = await gitInDir(
@@ -28548,6 +28604,29 @@ async function resurrectRestore(target) {
28548
28604
  });
28549
28605
  }
28550
28606
  }
28607
+ var restoreTurn = Promise.resolve();
28608
+ function withTmuxRestoreTurn(work) {
28609
+ const mine = restoreTurn.then(work, work);
28610
+ restoreTurn = mine.catch(() => {
28611
+ });
28612
+ return mine;
28613
+ }
28614
+ var unclaimedRestores = /* @__PURE__ */ new Map();
28615
+ function unclaimedTmuxRestores(target) {
28616
+ const host = hostRoot(target);
28617
+ let names = unclaimedRestores.get(host);
28618
+ if (!names) {
28619
+ names = /* @__PURE__ */ new Set();
28620
+ unclaimedRestores.set(host, names);
28621
+ }
28622
+ return names;
28623
+ }
28624
+ async function keepOneTmuxPane(target, session) {
28625
+ await target.sh(
28626
+ `${tmuxCli(target)} kill-pane -a -t ${shellQuote([session])} 2>/dev/null || true`
28627
+ ).catch(() => {
28628
+ });
28629
+ }
28551
28630
  async function tmuxPanePaths(target) {
28552
28631
  const stdout = await target.sh(
28553
28632
  `${tmuxCli(target)} list-panes -a -F '#{session_name}|#{pane_current_path}' 2>/dev/null || true`
@@ -28865,6 +28944,7 @@ function toSummary(session) {
28865
28944
  error: session.error,
28866
28945
  startedAt: session.startedAt,
28867
28946
  agentState: session.agentState,
28947
+ exposed: session.exposed,
28868
28948
  targetBranch: session.targetBranch,
28869
28949
  taskTitle: session.taskTitle,
28870
28950
  todos: session.todos,
@@ -29259,6 +29339,9 @@ var MONTH_MS = 30 * DAY_MS;
29259
29339
  var CLAIM_STALE_MS = 5 * 60 * 1e3;
29260
29340
  var MIN_THRESHOLD_TRONS = TRONS_PER_CENT;
29261
29341
 
29342
+ // ../../shared/all/domains/passwordCode.ts
29343
+ var PASSWORD_CODE_LENGTH = 6;
29344
+
29262
29345
  // ../../shared/all/domains/posts.ts
29263
29346
  var postDataSort = /* @__PURE__ */ ((postDataSort2) => {
29264
29347
  postDataSort2["DAILY"] = "DAILY";
@@ -29477,6 +29560,11 @@ var passwordRegisterSchema = baseRegisterSchema.extend({
29477
29560
  password: external_exports.string().min(8, { message: "Password must contain at least 8 characters" }),
29478
29561
  recaptchaToken: external_exports.string().optional()
29479
29562
  });
29563
+ var passwordCodeSchema = external_exports.object({
29564
+ code: external_exports.string().regex(new RegExp(`^\\d{${PASSWORD_CODE_LENGTH}}$`), {
29565
+ message: "Enter the 6-digit code from the email."
29566
+ })
29567
+ });
29480
29568
  var createSourceSchema = external_exports.object({
29481
29569
  name: external_exports.string().min(1),
29482
29570
  description: external_exports.string().optional(),
@@ -30229,9 +30317,9 @@ async function gitCatFileBatch(cwd, shas) {
30229
30317
  while (buf.length) {
30230
30318
  const nl = buf.indexOf(10);
30231
30319
  if (nl === -1) break;
30232
- const header = buf.subarray(0, nl).toString("utf-8");
30320
+ const header2 = buf.subarray(0, nl).toString("utf-8");
30233
30321
  buf = buf.subarray(nl + 1);
30234
- const [sha, type, sizeText] = header.split(" ");
30322
+ const [sha, type, sizeText] = header2.split(" ");
30235
30323
  if (type === void 0 || sizeText === void 0) continue;
30236
30324
  const size = Number(sizeText);
30237
30325
  if (!Number.isFinite(size)) break;
@@ -31442,6 +31530,10 @@ EOF
31442
31530
  # nohup, not setsid: setsid does not exist on macOS.
31443
31531
  nohup frpc -c "$TOML" > "${p.runDir}/\${NAME}.log" 2>&1 < /dev/null &
31444
31532
  echo $! > "${p.runDir}/\${NAME}.pid"
31533
+ # Which terminal opened it, so the sessions list can show the link beside that
31534
+ # terminal. The pane is the one identity a shell has without being told (tmux
31535
+ # sets it); the Ports panel is not in a pane, so the runner names the owner.
31536
+ printf '%s' "\${FACTIII_EXPOSE_OWNER:-$TMUX_PANE}" > "${p.runDir}/\${NAME}.owner"
31445
31537
  # https: the Mini terminates TLS for *.dev.factiii.com on the dockerized nginx
31446
31538
  # (wildcard cert, DNS-01). :80 still works and frps only speaks HTTP behind it.
31447
31539
  echo "https://\${DOMAIN}"
@@ -31457,7 +31549,7 @@ fi
31457
31549
  PID_FILE="${p.runDir}/\${NAME}.pid"
31458
31550
  if [ -f "$PID_FILE" ]; then
31459
31551
  kill "$(cat "$PID_FILE")" 2>/dev/null || true
31460
- rm -f "$PID_FILE" "${p.runDir}/\${NAME}.toml" "${p.runDir}/\${NAME}.log"
31552
+ rm -f "$PID_FILE" "${p.runDir}/\${NAME}.toml" "${p.runDir}/\${NAME}.log" "${p.runDir}/\${NAME}.owner"
31461
31553
  echo "stopped \${NAME}"
31462
31554
  else
31463
31555
  echo "no tunnel named \${NAME}" >&2
@@ -31571,11 +31663,11 @@ var ROW_SEP = "|";
31571
31663
  function parseTunnelRows(raw) {
31572
31664
  const tunnels = [];
31573
31665
  for (const line of raw.split("\n")) {
31574
- const [name, port, url3] = line.trim().split(ROW_SEP);
31666
+ const [name, port, url3, owner] = line.trim().split(ROW_SEP);
31575
31667
  if (!name || !url3) continue;
31576
31668
  const localPort = Number(port);
31577
31669
  if (!Number.isInteger(localPort) || localPort <= 0) continue;
31578
- tunnels.push({ name, port: localPort, url: url3 });
31670
+ tunnels.push({ name, port: localPort, url: url3, ...owner ? { owner } : {} });
31579
31671
  }
31580
31672
  return tunnels;
31581
31673
  }
@@ -31598,7 +31690,8 @@ async function listLiveTunnels(target) {
31598
31690
  // https, matching what factiii-expose prints: the Mini terminates TLS for
31599
31691
  // *.dev.factiii.com on the dockerized nginx. Showing http:// here made the
31600
31692
  // Ports panel disagree with the URL the agent had just handed the user.
31601
- ` echo "$name${ROW_SEP}$port${ROW_SEP}https://$sub.$FACTIII_FRP_DOMAIN"`,
31693
+ ' owner=$(cat "$name.owner" 2>/dev/null || true)',
31694
+ ` echo "$name${ROW_SEP}$port${ROW_SEP}https://$sub.$FACTIII_FRP_DOMAIN${ROW_SEP}$owner"`,
31602
31695
  "done"
31603
31696
  ].join("\n");
31604
31697
  const out2 = await target.run(["sh", "-c", script]).catch(() => "");
@@ -31933,18 +32026,18 @@ var ClaudeModeEngine = class _ClaudeModeEngine {
31933
32026
  await this.core.ensureSpaceWorkspace();
31934
32027
  await assertAgentSignedIn(session.provider, this.core.target());
31935
32028
  if (hasGit) {
31936
- const { path: path29 } = await addWorktree(
32029
+ const { path: path30 } = await addWorktree(
31937
32030
  this.core.target(),
31938
32031
  session.taskId,
31939
32032
  baseBranch || config2.mainBranch || "main",
31940
32033
  "card"
31941
32034
  );
31942
- session.workspacePath = path29;
32035
+ session.workspacePath = path30;
31943
32036
  await setGitIdentity(
31944
32037
  this.core.target(),
31945
32038
  config2.gitName,
31946
32039
  config2.gitEmail,
31947
- path29
32040
+ path30
31948
32041
  );
31949
32042
  this.emitter.addLog(session, "system", "Worktree ready.");
31950
32043
  } else {
@@ -32168,18 +32261,18 @@ var ClaudeModeEngine = class _ClaudeModeEngine {
32168
32261
  this.emitter.addLog(session, "system", "Preparing environment...");
32169
32262
  await this.core.ensureSpaceWorkspace();
32170
32263
  await assertAgentSignedIn(session.provider, this.core.target());
32171
- const { path: path29 } = await addWorktree(
32264
+ const { path: path30 } = await addWorktree(
32172
32265
  this.core.target(),
32173
32266
  session.taskId,
32174
32267
  config2.mainBranch || "main",
32175
32268
  "card"
32176
32269
  );
32177
- session.workspacePath = path29;
32270
+ session.workspacePath = path30;
32178
32271
  await setGitIdentity(
32179
32272
  this.core.target(),
32180
32273
  config2.gitName,
32181
32274
  config2.gitEmail,
32182
- path29
32275
+ path30
32183
32276
  );
32184
32277
  await this.putCard(session);
32185
32278
  const patchDir = `${this.core.target().paths.root}/patches/${session.taskId}`;
@@ -33110,12 +33203,12 @@ var RETRY_MIN_MS = 500;
33110
33203
  var RETRY_MAX_MS = 15e3;
33111
33204
  var dynamicImport = new Function("s", "return import(s)");
33112
33205
  var importFs = new Function("s", "return import(s)");
33113
- async function resolveReal(path29) {
33206
+ async function resolveReal(path30) {
33114
33207
  try {
33115
33208
  const { realpath } = await importFs("fs/promises");
33116
- return await realpath(path29);
33209
+ return await realpath(path30);
33117
33210
  } catch {
33118
- return path29;
33211
+ return path30;
33119
33212
  }
33120
33213
  }
33121
33214
  var loadSubscribe = null;
@@ -33265,19 +33358,19 @@ var WorkspaceWatcher = class {
33265
33358
  }
33266
33359
  record(kind, relPath) {
33267
33360
  if (this.closed) return;
33268
- const path29 = "/" + relPath;
33269
- const expiry = this.selfWrites.get(path29);
33361
+ const path30 = "/" + relPath;
33362
+ const expiry = this.selfWrites.get(path30);
33270
33363
  if (expiry !== void 0) {
33271
33364
  if (expiry > Date.now()) return;
33272
- this.selfWrites.delete(path29);
33365
+ this.selfWrites.delete(path30);
33273
33366
  }
33274
33367
  const { added, changed, removed } = this.pending;
33275
- added.delete(path29);
33276
- changed.delete(path29);
33277
- removed.delete(path29);
33278
- if (kind === "added") added.add(path29);
33279
- else if (kind === "changed") changed.add(path29);
33280
- else removed.add(path29);
33368
+ added.delete(path30);
33369
+ changed.delete(path30);
33370
+ removed.delete(path30);
33371
+ if (kind === "added") added.add(path30);
33372
+ else if (kind === "changed") changed.add(path30);
33373
+ else removed.add(path30);
33281
33374
  if (added.size + changed.size + removed.size > MAX_BATCH) {
33282
33375
  this.pending = { ...emptyPending(), resync: true };
33283
33376
  }
@@ -33296,8 +33389,8 @@ var WorkspaceWatcher = class {
33296
33389
  this.pending = emptyPending();
33297
33390
  if (!resync && !added.size && !changed.size && !removed.size) return;
33298
33391
  const now = Date.now();
33299
- for (const [path29, expiry] of this.selfWrites) {
33300
- if (expiry <= now) this.selfWrites.delete(path29);
33392
+ for (const [path30, expiry] of this.selfWrites) {
33393
+ if (expiry <= now) this.selfWrites.delete(path30);
33301
33394
  }
33302
33395
  this.emit({
33303
33396
  added: resync ? [] : [...added],
@@ -33344,6 +33437,8 @@ async function writeBase64File(target, abs, b64, opts = {}) {
33344
33437
  );
33345
33438
  }
33346
33439
  var PANE_REREAD_MS = 1e3;
33440
+ var TUNNEL_POLL_MS = 5e3;
33441
+ var sameTunnels = (a, b) => a.length === b.length && a.every((t, i) => t.name === b[i].name && t.url === b[i].url);
33347
33442
  var TerminalModeEngine = class {
33348
33443
  constructor(core, emitter) {
33349
33444
  this.core = core;
@@ -33361,6 +33456,8 @@ var TerminalModeEngine = class {
33361
33456
  this.stateSub = null;
33362
33457
  /** Applies states one at a time; see the comment at the push site. */
33363
33458
  this.stateQueue = Promise.resolve();
33459
+ // ── which terminal opened which public link ──
33460
+ this.tunnelPoll = null;
33364
33461
  /** pane id -> tmux session name, refreshed only when a pane we have not seen
33365
33462
  * turns up. Panes outlive individual messages, so re-reading the whole map
33366
33463
  * per message would be a tmux call per hook. */
@@ -33427,6 +33524,48 @@ var TerminalModeEngine = class {
33427
33524
  if (this.sessions.size > 0) return;
33428
33525
  this.stateSub?.kill();
33429
33526
  this.stateSub = null;
33527
+ if (this.tunnelPoll) clearInterval(this.tunnelPoll);
33528
+ this.tunnelPoll = null;
33529
+ }
33530
+ /** Idempotent, like startStateSub. Stopped with it, in releaseStateSub. */
33531
+ startTunnelPoll() {
33532
+ if (this.tunnelPoll) return;
33533
+ this.tunnelPoll = setInterval(
33534
+ () => void this.refreshTunnels(),
33535
+ TUNNEL_POLL_MS
33536
+ );
33537
+ void this.refreshTunnels();
33538
+ }
33539
+ /** File every live tunnel under the session whose terminal opened it, and
33540
+ * tell the app about the sessions whose list changed. A tunnel with no
33541
+ * resolvable owner (its tab has closed, or an older `factiii-expose` opened
33542
+ * it) is on no session; the Ports panel still lists it. */
33543
+ async refreshTunnels() {
33544
+ if (this.sessions.size === 0) return;
33545
+ const tunnels = await listLiveTunnels(this.core.target()).catch(() => null);
33546
+ if (!tunnels) return;
33547
+ const byPost = /* @__PURE__ */ new Map();
33548
+ for (const { owner, ...tunnel } of tunnels) {
33549
+ if (!owner) continue;
33550
+ let name = owner;
33551
+ if (owner.startsWith("%")) {
33552
+ name = this.paneSessions.get(owner);
33553
+ if (!name) {
33554
+ await this.refreshPanes();
33555
+ name = this.paneSessions.get(owner);
33556
+ }
33557
+ }
33558
+ const postId = name ? postIdForSessionName(name, this.sessions.keys()) : null;
33559
+ if (!postId) continue;
33560
+ byPost.set(postId, [...byPost.get(postId) ?? [], tunnel]);
33561
+ }
33562
+ for (const [postId, session] of this.sessions) {
33563
+ if (session.mode !== "bare") continue;
33564
+ const next = byPost.get(postId) ?? [];
33565
+ if (sameTunnels(session.exposed ?? [], next)) continue;
33566
+ session.exposed = next;
33567
+ this.emitter.emitSessionUpdate(session);
33568
+ }
33430
33569
  }
33431
33570
  async applyPaneState(paneId, state) {
33432
33571
  let name = this.paneSessions.get(paneId);
@@ -33465,6 +33604,7 @@ var TerminalModeEngine = class {
33465
33604
  startWatching(session) {
33466
33605
  const postId = session.postId;
33467
33606
  void this.startStateSub();
33607
+ this.startTunnelPoll();
33468
33608
  if (this.watchers.has(postId)) return;
33469
33609
  const paths = this.core.target().paths;
33470
33610
  const root = session.workspacePath || paths.root;
@@ -33502,8 +33642,8 @@ var TerminalModeEngine = class {
33502
33642
  /** Suppress the change event our own write is about to produce, so a save
33503
33643
  * never comes back to the editor as an outside edit. Normalized to the form
33504
33644
  * the watcher emits, since callers spell the path either way. */
33505
- expectWrite(postId, path29) {
33506
- this.watchers.get(postId)?.expectWrite(posixNormalize(path29));
33645
+ expectWrite(postId, path30) {
33646
+ this.watchers.get(postId)?.expectWrite(posixNormalize(path30));
33507
33647
  }
33508
33648
  // ── Lifecycle / ModeEngine ──
33509
33649
  start(base, args) {
@@ -33673,18 +33813,18 @@ var TerminalModeEngine = class {
33673
33813
  this.reservedNames.values()
33674
33814
  );
33675
33815
  this.reservedNames.set(session.postId, workName);
33676
- const { path: path29 } = await addWorktree(
33816
+ const { path: path30 } = await addWorktree(
33677
33817
  this.core.target(),
33678
33818
  workName,
33679
33819
  branch,
33680
33820
  "terminal"
33681
33821
  );
33682
- session.workspacePath = path29;
33822
+ session.workspacePath = path30;
33683
33823
  await setGitIdentity(
33684
33824
  this.core.target(),
33685
33825
  config2.gitName,
33686
33826
  config2.gitEmail,
33687
- path29
33827
+ path30
33688
33828
  );
33689
33829
  this.emitter.addLog(session, "system", "Worktree ready.");
33690
33830
  } else {
@@ -33746,11 +33886,11 @@ var TerminalModeEngine = class {
33746
33886
  }
33747
33887
  async bareFsList({
33748
33888
  postId,
33749
- path: path29
33889
+ path: path30
33750
33890
  }) {
33751
33891
  const target = this.getBareTarget(postId);
33752
33892
  const root = this.getBareRoot(postId);
33753
- const abs = this.resolveBarePath(path29, root);
33893
+ const abs = this.resolveBarePath(path30, root);
33754
33894
  const relRoot = abs.slice(root.length) || "/";
33755
33895
  const out2 = await target.run([
33756
33896
  "sh",
@@ -33800,30 +33940,30 @@ var TerminalModeEngine = class {
33800
33940
  }
33801
33941
  async bareFsRead({
33802
33942
  postId,
33803
- path: path29
33943
+ path: path30
33804
33944
  }) {
33805
33945
  const target = this.getBareTarget(postId);
33806
- const abs = this.resolveBarePath(path29, this.getBareRoot(postId));
33946
+ const abs = this.resolveBarePath(path30, this.getBareRoot(postId));
33807
33947
  const b64 = (await target.sh(`base64 < ${shEscape(abs)} | tr -d '
33808
33948
  '`)).trim();
33809
33949
  return { content: b64, encoding: "base64" };
33810
33950
  }
33811
33951
  async bareFsWrite({
33812
33952
  postId,
33813
- path: path29,
33953
+ path: path30,
33814
33954
  content,
33815
33955
  encoding
33816
33956
  }) {
33817
33957
  const target = this.getBareTarget(postId);
33818
- const abs = this.resolveBarePath(path29, this.getBareRoot(postId));
33958
+ const abs = this.resolveBarePath(path30, this.getBareRoot(postId));
33819
33959
  const b64 = encoding === "base64" ? content : Buffer.from(content, "utf-8").toString("base64");
33820
33960
  if (!/^[A-Za-z0-9+/=\n\r]*$/.test(b64)) {
33821
33961
  throw new Error("Invalid base64 payload.");
33822
33962
  }
33823
- this.expectWrite(String(postId), path29);
33963
+ this.expectWrite(String(postId), path30);
33824
33964
  await writeBase64File(target, abs, b64);
33825
33965
  const session = this.sessions.get(String(postId));
33826
- if (session) delete session.buffers[path29];
33966
+ if (session) delete session.buffers[path30];
33827
33967
  }
33828
33968
  /** Append one chunk of a dropped image to the per-space drops dir
33829
33969
  * (`paths.root`, OUTSIDE the card worktree so it never touches the repo).
@@ -33873,39 +34013,39 @@ var TerminalModeEngine = class {
33873
34013
  }
33874
34014
  bareOpenFile({
33875
34015
  postId: rawPostId,
33876
- path: path29
34016
+ path: path30
33877
34017
  }) {
33878
34018
  const session = this.sessions.get(String(rawPostId));
33879
34019
  if (!session || session.mode !== "bare") return;
33880
- if (!session.openedFiles.includes(path29)) {
33881
- session.openedFiles.push(path29);
34020
+ if (!session.openedFiles.includes(path30)) {
34021
+ session.openedFiles.push(path30);
33882
34022
  }
33883
34023
  }
33884
34024
  bareCloseFile({
33885
34025
  postId: rawPostId,
33886
- path: path29
34026
+ path: path30
33887
34027
  }) {
33888
34028
  const session = this.sessions.get(String(rawPostId));
33889
34029
  if (!session || session.mode !== "bare") return;
33890
- session.openedFiles = session.openedFiles.filter((p) => p !== path29);
33891
- delete session.buffers[path29];
34030
+ session.openedFiles = session.openedFiles.filter((p) => p !== path30);
34031
+ delete session.buffers[path30];
33892
34032
  }
33893
34033
  bareBufferSet({
33894
34034
  postId: rawPostId,
33895
- path: path29,
34035
+ path: path30,
33896
34036
  content
33897
34037
  }) {
33898
34038
  const session = this.sessions.get(String(rawPostId));
33899
34039
  if (!session || session.mode !== "bare") return;
33900
- session.buffers[path29] = content;
34040
+ session.buffers[path30] = content;
33901
34041
  }
33902
34042
  async bareFsDelete({
33903
34043
  postId,
33904
- path: path29
34044
+ path: path30
33905
34045
  }) {
33906
34046
  const target = this.getBareTarget(postId);
33907
34047
  const root = this.getBareRoot(postId);
33908
- const abs = this.resolveBarePath(path29, root);
34048
+ const abs = this.resolveBarePath(path30, root);
33909
34049
  if (abs === root) {
33910
34050
  throw new Error("Refusing to delete the repo root.");
33911
34051
  }
@@ -33913,10 +34053,10 @@ var TerminalModeEngine = class {
33913
34053
  }
33914
34054
  async bareFsMkdir({
33915
34055
  postId,
33916
- path: path29
34056
+ path: path30
33917
34057
  }) {
33918
34058
  const target = this.getBareTarget(postId);
33919
- const abs = this.resolveBarePath(path29, this.getBareRoot(postId));
34059
+ const abs = this.resolveBarePath(path30, this.getBareRoot(postId));
33920
34060
  await target.sh(`mkdir -p ${shEscape(abs)}`);
33921
34061
  }
33922
34062
  async bareReview({
@@ -34028,6 +34168,36 @@ var TerminalModeEngine = class {
34028
34168
  if (!workdir) return { diff: "", changedFiles: [] };
34029
34169
  return await readCommitDiff(this.core.target(), workdir, sha);
34030
34170
  }
34171
+ async bareGitCompare({
34172
+ postId,
34173
+ base
34174
+ }) {
34175
+ const workdir = this.gitWorkdir(postId);
34176
+ if (!workdir) {
34177
+ return {
34178
+ base: "",
34179
+ branches: [],
34180
+ files: [],
34181
+ diff: "",
34182
+ ahead: 0,
34183
+ behind: 0
34184
+ };
34185
+ }
34186
+ const cut = this.sessions.get(String(postId))?.targetBranch;
34187
+ const preferred = [
34188
+ ...cut ? [`origin/${cut}`, cut] : [],
34189
+ "origin/main",
34190
+ "origin/master",
34191
+ "main",
34192
+ "master"
34193
+ ];
34194
+ return await readBranchCompare(
34195
+ this.core.target(),
34196
+ workdir,
34197
+ base,
34198
+ preferred
34199
+ );
34200
+ }
34031
34201
  /** `targetOverride` carries the cross-mode lookup, so tabs resolve for cards
34032
34202
  * this engine doesn't own - the crashed claude sessions users most need. */
34033
34203
  async bareListTerminals({ postId: rawPostId }, targetOverride) {
@@ -34200,11 +34370,15 @@ var TerminalModeEngine = class {
34200
34370
  if (!Number.isInteger(port) || port < 1 || port > 65535) {
34201
34371
  throw new Error("Port must be between 1 and 65535.");
34202
34372
  }
34203
- const out2 = (await target.sh(`factiii-expose ${port} ${shEscape(safeName)} 2>&1`)).trim();
34373
+ const owner = shEscape(tmuxName(`${postId}-ports`));
34374
+ const out2 = (await target.sh(
34375
+ `FACTIII_EXPOSE_OWNER=${owner} factiii-expose ${port} ${shEscape(safeName)} 2>&1`
34376
+ )).trim();
34204
34377
  const url3 = out2.split("\n").filter(Boolean).pop() || "";
34205
34378
  if (!/^https?:\/\//.test(url3)) {
34206
34379
  throw new Error(out2 || "Failed to expose port.");
34207
34380
  }
34381
+ void this.refreshTunnels();
34208
34382
  return { name: safeName, port, url: url3 };
34209
34383
  }
34210
34384
  async bareUnexpose({
@@ -34217,6 +34391,7 @@ var TerminalModeEngine = class {
34217
34391
  throw new Error("Invalid tunnel name.");
34218
34392
  }
34219
34393
  await target.sh(`factiii-unexpose ${shEscape(safeName)} 2>&1 || true`);
34394
+ void this.refreshTunnels();
34220
34395
  }
34221
34396
  /** Derived, never remembered: `factiii-expose` is on the agent's PATH, so the
34222
34397
  * terminal and the agent both open tunnels without telling us, and a runner
@@ -34226,7 +34401,8 @@ var TerminalModeEngine = class {
34226
34401
  }) {
34227
34402
  const session = this.sessions.get(String(postId));
34228
34403
  if (!session || session.mode !== "bare") return [];
34229
- return await listLiveTunnels(this.core.target());
34404
+ const tunnels = await listLiveTunnels(this.core.target());
34405
+ return tunnels.map(({ name, port, url: url3 }) => ({ name, port, url: url3 }));
34230
34406
  }
34231
34407
  };
34232
34408
 
@@ -34640,8 +34816,8 @@ async function pollGithubDeviceCode(clientId, deviceCode) {
34640
34816
  };
34641
34817
  }
34642
34818
  }
34643
- async function githubApi(token, path29) {
34644
- const res = await fetch(`${API_BASE}${path29}`, {
34819
+ async function githubApi(token, path30) {
34820
+ const res = await fetch(`${API_BASE}${path30}`, {
34645
34821
  headers: {
34646
34822
  Authorization: `Bearer ${token}`,
34647
34823
  Accept: "application/vnd.github+json",
@@ -34650,7 +34826,7 @@ async function githubApi(token, path29) {
34650
34826
  });
34651
34827
  if (!res.ok) {
34652
34828
  throw new Error(
34653
- `GitHub ${path29} failed (${res.status}): ${await res.text()}`
34829
+ `GitHub ${path30} failed (${res.status}): ${await res.text()}`
34654
34830
  );
34655
34831
  }
34656
34832
  return await res.json();
@@ -35378,6 +35554,77 @@ async function pruneSecretMeta(spaceDir) {
35378
35554
  }
35379
35555
  if (changed) await writeSecretMeta(spaceDir, all);
35380
35556
  }
35557
+ var BACKUP_TOP_LEVEL = /* @__PURE__ */ new Set([
35558
+ IDENTITY_FILE,
35559
+ RECIPIENT_FILE,
35560
+ ENV_FILE,
35561
+ META_FILE
35562
+ ]);
35563
+ function isBackupPath(rel) {
35564
+ if (BACKUP_TOP_LEVEL.has(rel)) return true;
35565
+ const [dir, file2, ...rest] = rel.split("/");
35566
+ if (dir !== FILES_DIR || !file2 || rest.length > 0) return false;
35567
+ return file2.endsWith(".enc") && SECRET_NAME.test(file2.slice(0, -4));
35568
+ }
35569
+ async function readBackupFiles(spaceDir, password) {
35570
+ const configDir = spaceKeyDir(spaceDir);
35571
+ if (!await exists(import_path12.default.join(configDir, IDENTITY_FILE))) {
35572
+ throw new Error(
35573
+ "This board has no secrets of its own yet, so there is nothing to back up."
35574
+ );
35575
+ }
35576
+ await unwrapIdentity(configDir, password);
35577
+ return withStoreLock(spaceDir, async () => {
35578
+ decryptIdentity(await readIdentityBox(configDir), password);
35579
+ const root = import_path12.default.join(spaceDir, "secrets");
35580
+ const files = {};
35581
+ const names = [
35582
+ ...BACKUP_TOP_LEVEL,
35583
+ ...(await import_promises9.default.readdir(filesDir(spaceDir)).catch(() => [])).map(
35584
+ (name) => `${FILES_DIR}/${name}`
35585
+ )
35586
+ ];
35587
+ for (const rel of names) {
35588
+ if (!isBackupPath(rel)) continue;
35589
+ const data = await import_promises9.default.readFile(import_path12.default.join(root, rel)).catch(() => null);
35590
+ if (data) files[rel] = data.toString("base64");
35591
+ }
35592
+ return files;
35593
+ });
35594
+ }
35595
+ async function writeBackupFiles(spaceDir, files) {
35596
+ const paths = Object.keys(files);
35597
+ const bad = paths.find((rel) => !isBackupPath(rel));
35598
+ if (bad !== void 0) {
35599
+ throw new Error(`This backup holds a file it should not: ${bad}`);
35600
+ }
35601
+ if (!paths.includes(IDENTITY_FILE)) {
35602
+ throw new Error("This backup has no key in it.");
35603
+ }
35604
+ await withStoreLock(spaceDir, async () => {
35605
+ const root = import_path12.default.join(spaceDir, "secrets");
35606
+ const existing = [
35607
+ ...await import_promises9.default.readdir(root).catch(() => []),
35608
+ ...(await import_promises9.default.readdir(filesDir(spaceDir)).catch(() => [])).map(
35609
+ (name) => `${FILES_DIR}/${name}`
35610
+ )
35611
+ ].filter(isBackupPath);
35612
+ if (existing.length > 0) {
35613
+ throw new Error(
35614
+ "This board already has secrets. A backup is only restored into a board that has none."
35615
+ );
35616
+ }
35617
+ await ensureSecretsDir(spaceDir);
35618
+ await import_promises9.default.mkdir(filesDir(spaceDir), { recursive: true, mode: 448 });
35619
+ for (const rel of paths) {
35620
+ await import_promises9.default.writeFile(
35621
+ import_path12.default.join(root, rel),
35622
+ Buffer.from(files[rel], "base64"),
35623
+ { mode: 384 }
35624
+ );
35625
+ }
35626
+ });
35627
+ }
35381
35628
 
35382
35629
  // ../../shared/all/helpers/board-agent-core/secrets-gate.ts
35383
35630
  var import_crypto7 = __toESM(require("crypto"));
@@ -36106,6 +36353,114 @@ ${clean}`;
36106
36353
  }
36107
36354
  }
36108
36355
 
36356
+ // ../../shared/all/helpers/board-agent-core/secrets-backup.ts
36357
+ var import_crypto8 = __toESM(require("crypto"));
36358
+
36359
+ // ../../shared/all/domains/secretsBackup.ts
36360
+ var MIN_BACKUP_PASSPHRASE = 12;
36361
+ function backupPassphraseProblem(passphrase, boardPassword) {
36362
+ if (passphrase.length < MIN_BACKUP_PASSPHRASE) {
36363
+ return `The backup passphrase needs at least ${MIN_BACKUP_PASSPHRASE} characters.`;
36364
+ }
36365
+ if (passphrase === boardPassword) {
36366
+ return "The backup passphrase must differ from the board password.";
36367
+ }
36368
+ return "";
36369
+ }
36370
+
36371
+ // ../../shared/all/helpers/board-agent-core/secrets-backup.ts
36372
+ var FORMAT = "factiii-secrets-backup";
36373
+ var VERSION = 1;
36374
+ var SCRYPT_N2 = 1 << 15;
36375
+ var SCRYPT_MAXMEM = 64 * 1024 * 1024;
36376
+ var deriveKey2 = (passphrase, salt) => import_crypto8.default.scryptSync(passphrase, salt, 32, {
36377
+ N: SCRYPT_N2,
36378
+ maxmem: SCRYPT_MAXMEM
36379
+ });
36380
+ var header = (b) => Buffer.from(`${FORMAT}
36381
+ ${b.version}
36382
+ ${b.board}
36383
+ ${b.createdAt}`, "utf-8");
36384
+ async function exportSecretsBackup(opts) {
36385
+ const problem = backupPassphraseProblem(opts.passphrase, opts.password);
36386
+ if (problem) throw new Error(problem);
36387
+ const files = await readBackupFiles(opts.spaceDir, opts.password);
36388
+ const meta3 = {
36389
+ version: VERSION,
36390
+ board: opts.board,
36391
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
36392
+ };
36393
+ const salt = import_crypto8.default.randomBytes(16);
36394
+ const iv = import_crypto8.default.randomBytes(12);
36395
+ const cipher = import_crypto8.default.createCipheriv(
36396
+ "aes-256-gcm",
36397
+ deriveKey2(opts.passphrase, salt),
36398
+ iv
36399
+ );
36400
+ cipher.setAAD(header(meta3));
36401
+ const data = Buffer.concat([
36402
+ cipher.update(JSON.stringify({ files }), "utf-8"),
36403
+ cipher.final()
36404
+ ]);
36405
+ const bundle = {
36406
+ format: FORMAT,
36407
+ ...meta3,
36408
+ salt: salt.toString("base64"),
36409
+ iv: iv.toString("base64"),
36410
+ tag: cipher.getAuthTag().toString("base64"),
36411
+ data: data.toString("base64")
36412
+ };
36413
+ return JSON.stringify(bundle);
36414
+ }
36415
+ function parseBundle(raw) {
36416
+ let parsed;
36417
+ try {
36418
+ parsed = JSON.parse(raw);
36419
+ } catch {
36420
+ throw new Error("That is not a secrets backup file.");
36421
+ }
36422
+ const b = parsed;
36423
+ if (!b || b.format !== FORMAT) {
36424
+ throw new Error("That is not a secrets backup file.");
36425
+ }
36426
+ if (b.version !== VERSION) {
36427
+ throw new Error(
36428
+ "This backup was made by a newer runner. Update the runner, then restore it."
36429
+ );
36430
+ }
36431
+ const strings = [b.board, b.createdAt, b.salt, b.iv, b.tag, b.data];
36432
+ if (strings.some((value2) => typeof value2 !== "string")) {
36433
+ throw new Error("That is not a secrets backup file.");
36434
+ }
36435
+ return b;
36436
+ }
36437
+ async function restoreSecretsBackup(opts) {
36438
+ const bundle = parseBundle(opts.bundle);
36439
+ const decipher = import_crypto8.default.createDecipheriv(
36440
+ "aes-256-gcm",
36441
+ deriveKey2(opts.passphrase, Buffer.from(bundle.salt, "base64")),
36442
+ Buffer.from(bundle.iv, "base64")
36443
+ );
36444
+ decipher.setAAD(header(bundle));
36445
+ decipher.setAuthTag(Buffer.from(bundle.tag, "base64"));
36446
+ let plain;
36447
+ try {
36448
+ plain = Buffer.concat([
36449
+ decipher.update(Buffer.from(bundle.data, "base64")),
36450
+ decipher.final()
36451
+ ]).toString("utf-8");
36452
+ } catch {
36453
+ throw new Error("Wrong backup passphrase, or the file was changed.");
36454
+ }
36455
+ const { files } = JSON.parse(plain);
36456
+ await writeBackupFiles(opts.spaceDir, files);
36457
+ return {
36458
+ board: bundle.board,
36459
+ createdAt: bundle.createdAt,
36460
+ files: Object.keys(files).length
36461
+ };
36462
+ }
36463
+
36109
36464
  // ../../shared/all/helpers/graphFetch.ts
36110
36465
  var GRAPH_MAX_RETRIES = 3;
36111
36466
  var GRAPH_MAX_WAIT_MS = 3e4;
@@ -36114,13 +36469,13 @@ var MS_PER_SECOND = 1e3;
36114
36469
  var THROTTLED_STATUSES = /* @__PURE__ */ new Set([429, 503]);
36115
36470
  var isGraphThrottled = (status) => THROTTLED_STATUSES.has(status);
36116
36471
  var graphRetryDelayMs = (retryAfter, attempt, maxWaitMs = GRAPH_MAX_WAIT_MS, now = Date.now()) => {
36117
- const header = retryAfter?.trim();
36118
- if (header) {
36119
- const seconds = Number(header);
36472
+ const header2 = retryAfter?.trim();
36473
+ if (header2) {
36474
+ const seconds = Number(header2);
36120
36475
  if (Number.isFinite(seconds) && seconds >= 0) {
36121
36476
  return Math.min(seconds * MS_PER_SECOND, maxWaitMs);
36122
36477
  }
36123
- const at = Date.parse(header);
36478
+ const at = Date.parse(header2);
36124
36479
  if (Number.isFinite(at)) {
36125
36480
  return Math.min(Math.max(at - now, 0), maxWaitMs);
36126
36481
  }
@@ -36438,7 +36793,7 @@ var ScratchpadStore = class {
36438
36793
  };
36439
36794
 
36440
36795
  // ../../shared/all/helpers/board-agent-core/jobs.ts
36441
- var import_crypto8 = __toESM(require("crypto"));
36796
+ var import_crypto9 = __toESM(require("crypto"));
36442
36797
  var JOBS_PATH = ".agents/skills/deploy/jobs.json";
36443
36798
  var MAX_CHUNKS = 5e3;
36444
36799
  var KEEP_MS = 24 * 60 * 6e4;
@@ -36559,7 +36914,7 @@ var JobRunner = class {
36559
36914
  opts.job,
36560
36915
  opts.params
36561
36916
  );
36562
- const callId = opts.callId || import_crypto8.default.randomUUID();
36917
+ const callId = opts.callId || import_crypto9.default.randomUUID();
36563
36918
  if (this.calls.has(callId)) {
36564
36919
  throw new Error("That call id is already in use.");
36565
36920
  }
@@ -37064,26 +37419,253 @@ var SecretsInbox = class {
37064
37419
  }
37065
37420
  };
37066
37421
 
37422
+ // ../../shared/all/helpers/board-agent-core/screen-store.ts
37423
+ var APP_NAME = "FactiiiScreen.app";
37424
+ var BUNDLE_ID = "com.factiii.runner.screen";
37425
+ var FRAMEWORKS = "-framework Foundation -framework AppKit -framework ApplicationServices -framework ScreenCaptureKit -framework VideoToolbox -framework CoreMedia -framework CoreVideo";
37426
+ var INFO_PLIST = `<?xml version="1.0" encoding="UTF-8"?>
37427
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
37428
+ <plist version="1.0"><dict>
37429
+ <key>CFBundleIdentifier</key><string>${BUNDLE_ID}</string>
37430
+ <key>CFBundleName</key><string>Factiii Screen</string>
37431
+ <key>CFBundleDisplayName</key><string>Factiii Screen</string>
37432
+ <key>CFBundleExecutable</key><string>screenhost</string>
37433
+ <key>CFBundlePackageType</key><string>APPL</string>
37434
+ <key>CFBundleVersion</key><string>1</string>
37435
+ <key>CFBundleShortVersionString</key><string>1.0</string>
37436
+ <key>LSUIElement</key><true/>
37437
+ <key>NSScreenCaptureUsageDescription</key><string>Shows this Mac's screen to the runner's owner in the Factiii app.</string>
37438
+ </dict></plist>
37439
+ `;
37440
+ function shEscape3(s) {
37441
+ return `'${s.replace(/'/g, `'\\''`)}'`;
37442
+ }
37443
+ var ratio = external_exports.number().finite().catch(0).transform((n) => Math.min(1, Math.max(0, n)));
37444
+ var delta = external_exports.number().finite().catch(0).transform((n) => Math.min(2e3, Math.max(-2e3, Math.round(n))));
37445
+ var screenInputSchema = external_exports.discriminatedUnion("type", [
37446
+ external_exports.object({
37447
+ type: external_exports.literal("pointer"),
37448
+ phase: external_exports.enum(["move", "down", "up"]),
37449
+ x: ratio,
37450
+ y: ratio,
37451
+ button: external_exports.enum(["left", "right"]).catch("left")
37452
+ }),
37453
+ external_exports.object({ type: external_exports.literal("scroll"), dx: delta, dy: delta }),
37454
+ // The keyboard page of the USB HID usage table, `a` to right-GUI.
37455
+ external_exports.object({
37456
+ type: external_exports.literal("key"),
37457
+ code: external_exports.number().int().min(4).max(231),
37458
+ down: external_exports.boolean()
37459
+ }),
37460
+ // Capped: the helper types it a character at a time.
37461
+ external_exports.object({ type: external_exports.literal("text"), text: external_exports.string().max(2e3) })
37462
+ ]);
37463
+ var screenAttachSchema = external_exports.object({
37464
+ width: external_exports.number().int().catch(0).transform((n) => n === 0 ? 0 : Math.min(3840, Math.max(640, n))),
37465
+ fps: external_exports.number().int().catch(30).transform((n) => Math.min(60, Math.max(1, n))),
37466
+ bitrate: external_exports.number().int().catch(4e6).transform((n) => Math.min(2e7, Math.max(5e5, n)))
37467
+ });
37468
+ function parseScreenPermissions(output2) {
37469
+ let found = null;
37470
+ for (const line of output2.split("\n")) {
37471
+ if (!line.startsWith("{")) continue;
37472
+ try {
37473
+ const parsed = JSON.parse(line);
37474
+ if (parsed.status !== "permissions") continue;
37475
+ found = { screen: parsed.screen === true, control: parsed.control === true };
37476
+ } catch {
37477
+ }
37478
+ }
37479
+ return found;
37480
+ }
37481
+ function lengthPrefixedReader(onUnit) {
37482
+ let buffered = new Uint8Array(0);
37483
+ return (chunk) => {
37484
+ const merged = new Uint8Array(buffered.length + chunk.length);
37485
+ merged.set(buffered);
37486
+ merged.set(chunk, buffered.length);
37487
+ buffered = merged;
37488
+ for (; ; ) {
37489
+ if (buffered.length < 4) return;
37490
+ const length = new DataView(
37491
+ buffered.buffer,
37492
+ buffered.byteOffset,
37493
+ buffered.length
37494
+ ).getUint32(0);
37495
+ if (buffered.length < 4 + length) return;
37496
+ const unit = buffered.subarray(4, 4 + length);
37497
+ buffered = buffered.subarray(4 + length);
37498
+ try {
37499
+ onUnit(unit);
37500
+ } catch {
37501
+ }
37502
+ }
37503
+ };
37504
+ }
37505
+ var UNSUPPORTED = {
37506
+ supported: false,
37507
+ screen: false,
37508
+ control: false,
37509
+ streaming: false
37510
+ };
37511
+ var ScreenStore = class {
37512
+ /**
37513
+ * @param target Resolved per call, never held.
37514
+ * @param emit One H.264 access unit, Annex-B.
37515
+ * @param nativeDir Where `screenhost.m` lives. Empty means no desktop view.
37516
+ */
37517
+ constructor(target, emit, nativeDir) {
37518
+ this.target = target;
37519
+ this.emit = emit;
37520
+ this.nativeDir = nativeDir;
37521
+ this.video = null;
37522
+ this.built = null;
37523
+ /** What the running helper last said, which is newer than any `--status`
37524
+ * run: the owner may flip a switch while it streams. */
37525
+ this.lastControl = null;
37526
+ }
37527
+ supported() {
37528
+ return Boolean(this.nativeDir) && typeof process !== "undefined" && process.platform === "darwin";
37529
+ }
37530
+ /** Whether this Mac can show its screen, and which of the two switches are
37531
+ * on. `request` makes macOS ask (once) and list the app in System Settings,
37532
+ * which has to happen with someone at the Mac. */
37533
+ async status(request = false) {
37534
+ if (!this.supported()) return UNSUPPORTED;
37535
+ const binary = await this.build();
37536
+ const output2 = await this.target().sh(
37537
+ `${shEscape3(binary)} --status${request ? " --request" : ""} 2>&1 || true`
37538
+ ).catch(() => "");
37539
+ const permissions = parseScreenPermissions(output2);
37540
+ return {
37541
+ supported: true,
37542
+ screen: permissions?.screen ?? false,
37543
+ control: this.lastControl ?? permissions?.control ?? false,
37544
+ streaming: this.video !== null
37545
+ };
37546
+ }
37547
+ /** Start pushing frames. Idempotent for the same options. Without Screen
37548
+ * Recording nothing starts: the answer says so, and asking has put the app
37549
+ * in System Settings for the owner to switch on. */
37550
+ async attach(raw) {
37551
+ const options = screenAttachSchema.parse(raw);
37552
+ const before = await this.status(true);
37553
+ if (!before.supported || !before.screen) return before;
37554
+ if (this.video) {
37555
+ const current = this.video.options;
37556
+ if (current.width === options.width && current.fps === options.fps && current.bitrate === options.bitrate) {
37557
+ return { ...before, streaming: true };
37558
+ }
37559
+ this.detach();
37560
+ }
37561
+ const binary = await this.build();
37562
+ const proc = await this.target().spawn([
37563
+ binary,
37564
+ "--fps",
37565
+ String(options.fps),
37566
+ "--width",
37567
+ String(options.width),
37568
+ "--bitrate",
37569
+ String(options.bitrate)
37570
+ ]);
37571
+ this.video = { proc, options };
37572
+ this.lastControl = before.control;
37573
+ const read = lengthPrefixedReader((unit) => this.emit(unit, Date.now()));
37574
+ proc.stdout?.on("data", (chunk) => {
37575
+ if (this.video?.proc === proc) read(chunk);
37576
+ });
37577
+ proc.stderr?.on("data", (chunk) => {
37578
+ const permissions = parseScreenPermissions(String(chunk));
37579
+ if (permissions && this.video?.proc === proc) {
37580
+ this.lastControl = permissions.control;
37581
+ }
37582
+ });
37583
+ proc.on("exit", () => {
37584
+ if (this.video?.proc === proc) this.video = null;
37585
+ });
37586
+ return { ...before, streaming: true };
37587
+ }
37588
+ /** Stop capturing: nobody watching, nothing to send. */
37589
+ detach() {
37590
+ const proc = this.video?.proc;
37591
+ this.video = null;
37592
+ this.lastControl = null;
37593
+ proc?.kill("SIGKILL");
37594
+ }
37595
+ /** One input event, to the helper that is streaming. Dropped when none is:
37596
+ * input with no picture is input nobody can see the result of. */
37597
+ input(raw) {
37598
+ const command = screenInputSchema.parse(raw);
37599
+ const proc = this.video?.proc;
37600
+ if (!proc || proc.exitCode !== null) return;
37601
+ proc.stdin?.write(`${JSON.stringify(command)}
37602
+ `);
37603
+ }
37604
+ destroy() {
37605
+ this.detach();
37606
+ }
37607
+ /**
37608
+ * Build the app bundle if it is missing or its source changed, and answer
37609
+ * with the binary inside it.
37610
+ *
37611
+ * One bundle for the machine, beside the boards rather than inside one: the
37612
+ * grant is to a program, and a copy per board would be a grant per board.
37613
+ *
37614
+ * Rebuilt only when the source's hash changes, never on its timestamp: the
37615
+ * bundle is signed ad hoc, so macOS knows it by the hash of the binary, and
37616
+ * a rebuild is a new program whose switches start off. An npm install
37617
+ * rewrites every timestamp; it must not cost the owner a trip to the Mac.
37618
+ */
37619
+ build() {
37620
+ this.built ??= this.buildOnce().catch((err2) => {
37621
+ this.built = null;
37622
+ throw err2;
37623
+ });
37624
+ return this.built;
37625
+ }
37626
+ async buildOnce() {
37627
+ const target = this.target();
37628
+ const root = target.paths.root;
37629
+ const host = root.slice(0, root.lastIndexOf("/"));
37630
+ const app = `${host}/helpers/${APP_NAME}`;
37631
+ const binary = `${app}/Contents/MacOS/screenhost`;
37632
+ const stamp = `${app}/Contents/Resources/source.sha256`;
37633
+ const source = `${this.nativeDir}/screenhost.m`;
37634
+ await target.sh(
37635
+ `set -e
37636
+ want=$(shasum -a 256 ${shEscape3(source)} | cut -d' ' -f1)
37637
+ have=$(cat ${shEscape3(stamp)} 2>/dev/null || true)
37638
+ if [ -x ${shEscape3(binary)} ] && [ "$want" = "$have" ]; then exit 0; fi
37639
+ mkdir -p ${shEscape3(`${app}/Contents/MacOS`)} ${shEscape3(`${app}/Contents/Resources`)}
37640
+ clang -fobjc-arc -Wno-deprecated-declarations ${FRAMEWORKS} -o ${shEscape3(binary)} ${shEscape3(source)}
37641
+ printf '%s' ${shEscape3(INFO_PLIST)} > ${shEscape3(`${app}/Contents/Info.plist`)}
37642
+ printf '%s' "$want" > ${shEscape3(stamp)}
37643
+ codesign --force --sign - --identifier ${BUNDLE_ID} ${shEscape3(app)}`
37644
+ );
37645
+ return binary;
37646
+ }
37647
+ };
37648
+
37067
37649
  // ../../shared/all/helpers/board-agent-core/simulator-store.ts
37068
- var FRAMEWORKS = {
37650
+ var FRAMEWORKS2 = {
37069
37651
  simstream: "-framework Foundation -framework IOSurface -framework VideoToolbox -framework CoreMedia -framework CoreVideo",
37070
37652
  simhid: "-framework Foundation -framework AppKit"
37071
37653
  };
37072
- function shEscape3(s) {
37654
+ function shEscape4(s) {
37073
37655
  return `'${s.replace(/'/g, `'\\''`)}'`;
37074
37656
  }
37075
37657
  var udid = external_exports.string().trim().min(1).max(128);
37076
- var ratio = external_exports.number().finite().catch(0).transform((n) => Math.min(1, Math.max(0, n)));
37658
+ var ratio2 = external_exports.number().finite().catch(0).transform((n) => Math.min(1, Math.max(0, n)));
37077
37659
  var simulatorInputSchema = external_exports.intersection(
37078
37660
  external_exports.object({ udid }),
37079
37661
  external_exports.discriminatedUnion("type", [
37080
37662
  external_exports.object({
37081
37663
  type: external_exports.literal("touch"),
37082
37664
  phase: external_exports.enum(["down", "move", "up"]),
37083
- x: ratio,
37084
- y: ratio
37665
+ x: ratio2,
37666
+ y: ratio2
37085
37667
  }),
37086
- external_exports.object({ type: external_exports.literal("tap"), x: ratio, y: ratio }),
37668
+ external_exports.object({ type: external_exports.literal("tap"), x: ratio2, y: ratio2 }),
37087
37669
  // Capped because the helper types it a keystroke at a time, sleeping
37088
37670
  // between them: an unbounded string is minutes of a device typing.
37089
37671
  external_exports.object({ type: external_exports.literal("text"), text: external_exports.string().max(2e3) }),
@@ -37265,8 +37847,8 @@ var SimulatorStore = class {
37265
37847
  const binary = `${this.target().paths.bin}/${helper}`;
37266
37848
  if (this.built.has(helper)) return binary;
37267
37849
  await this.target().sh(
37268
- `if [ ! -x ${shEscape3(binary)} ] || [ ${shEscape3(source)} -nt ${shEscape3(binary)} ]; then
37269
- clang -fobjc-arc -Wno-objc-method-access -Wno-deprecated-declarations ${FRAMEWORKS[helper]} -o ${shEscape3(binary)} ${shEscape3(source)}
37850
+ `if [ ! -x ${shEscape4(binary)} ] || [ ${shEscape4(source)} -nt ${shEscape4(binary)} ]; then
37851
+ clang -fobjc-arc -Wno-objc-method-access -Wno-deprecated-declarations ${FRAMEWORKS2[helper]} -o ${shEscape4(binary)} ${shEscape4(source)}
37270
37852
  fi`
37271
37853
  );
37272
37854
  this.built.add(helper);
@@ -37279,12 +37861,12 @@ var import_promises13 = require("fs/promises");
37279
37861
  var import_path17 = __toESM(require("path"));
37280
37862
 
37281
37863
  // ../../shared/all/helpers/board-agent-core/audit.ts
37282
- var import_crypto9 = __toESM(require("crypto"));
37864
+ var import_crypto10 = __toESM(require("crypto"));
37283
37865
  var import_promises12 = __toESM(require("fs/promises"));
37284
37866
  var import_path16 = __toESM(require("path"));
37285
37867
  var FILE = "audit.jsonl";
37286
37868
  var GENESIS = "0".repeat(64);
37287
- var sha256 = (line) => import_crypto9.default.createHash("sha256").update(line).digest("hex");
37869
+ var sha256 = (line) => import_crypto10.default.createHash("sha256").update(line).digest("hex");
37288
37870
  function auditPath(spaceDir) {
37289
37871
  return import_path16.default.join(spaceDir, FILE);
37290
37872
  }
@@ -38267,44 +38849,60 @@ var SpaceCore = class {
38267
38849
  const target = this.target();
38268
38850
  await ensureTmuxResurrect(target);
38269
38851
  const root = target.paths.root;
38270
- const before = await tmuxPanePaths(target);
38271
- const mineUp = [...before].some(
38272
- ([name, dir]) => name.startsWith("terminal-") && dir.startsWith(root)
38852
+ await withTmuxRestoreTurn(
38853
+ () => this.restoreTerminalsInTurn(target, root)
38273
38854
  );
38274
- if (mineUp) return;
38855
+ } catch {
38856
+ }
38857
+ }
38858
+ async restoreTerminalsInTurn(target, root) {
38859
+ const unclaimed = unclaimedTmuxRestores(target);
38860
+ const before = await tmuxPanePaths(target);
38861
+ const mineUp = [...before].some(
38862
+ ([name, dir]) => name.startsWith("terminal-") && dir.startsWith(root) && !unclaimed.has(name)
38863
+ );
38864
+ if (mineUp) return;
38865
+ const mineWaiting = [...unclaimed].some(
38866
+ (name) => (before.get(name) ?? "").startsWith(root)
38867
+ );
38868
+ if (!mineWaiting) {
38275
38869
  const restored = await resurrectRestore(target);
38276
- const paths = await tmuxPanePaths(target);
38277
- const revived = restored.filter(
38278
- (name) => !before.has(name) && (paths.get(name) ?? "").startsWith(root)
38279
- );
38280
- if (revived.length === 0) return;
38281
- const digest = await terminalDigest(target).catch(() => "");
38282
- for (const session of revived) {
38283
- await respawnTmuxPane({
38870
+ for (const name of restored) {
38871
+ if (!before.has(name)) unclaimed.add(name);
38872
+ }
38873
+ }
38874
+ const paths = await tmuxPanePaths(target);
38875
+ const revived = [...unclaimed].filter(
38876
+ (name) => (paths.get(name) ?? "").startsWith(root)
38877
+ );
38878
+ if (revived.length === 0) return;
38879
+ const digest = await terminalDigest(target).catch(() => "");
38880
+ for (const session of revived) {
38881
+ unclaimed.delete(session);
38882
+ await keepOneTmuxPane(target, session);
38883
+ await respawnTmuxPane({
38884
+ target,
38885
+ session,
38886
+ argv: [
38887
+ "bash",
38888
+ "-c",
38889
+ terminalInitScript(
38890
+ paths.get(session) || target.paths.workspace,
38891
+ target.paths.bin
38892
+ )
38893
+ ],
38894
+ cwd: paths.get(session) || target.paths.workspace,
38895
+ env: target.stateEnv()
38896
+ }).catch(() => {
38897
+ });
38898
+ if (digest) {
38899
+ await setTmuxSessionOption(
38284
38900
  target,
38285
38901
  session,
38286
- argv: [
38287
- "bash",
38288
- "-c",
38289
- terminalInitScript(
38290
- paths.get(session) || target.paths.workspace,
38291
- target.paths.bin
38292
- )
38293
- ],
38294
- cwd: paths.get(session) || target.paths.workspace,
38295
- env: target.stateEnv()
38296
- }).catch(() => {
38297
- });
38298
- if (digest) {
38299
- await setTmuxSessionOption(
38300
- target,
38301
- session,
38302
- TERMINAL_FP_OPTION,
38303
- digest
38304
- );
38305
- }
38902
+ TERMINAL_FP_OPTION,
38903
+ digest
38904
+ );
38306
38905
  }
38307
- } catch {
38308
38906
  }
38309
38907
  }
38310
38908
  async applyTerminalConfig() {
@@ -38444,6 +39042,12 @@ var BoardAgentEngine = class _BoardAgentEngine {
38444
39042
  options.nativeDir ?? ""
38445
39043
  );
38446
39044
  this.onSimulatorAttach = options.onSimulatorAttach;
39045
+ this.screen = new ScreenStore(
39046
+ () => this.core.target(),
39047
+ (unit, at) => options.onScreenFrame?.(unit, at),
39048
+ options.nativeDir ?? ""
39049
+ );
39050
+ this.onScreenAttach = options.onScreenAttach;
38447
39051
  this.onJobLog = options.onJobLog;
38448
39052
  this.onJobEnd = options.onJobEnd;
38449
39053
  this.onJobState = options.onJobState;
@@ -38581,6 +39185,39 @@ var BoardAgentEngine = class _BoardAgentEngine {
38581
39185
  });
38582
39186
  return result;
38583
39187
  }
39188
+ /** The owner's offline backup of this board's secrets (secrets-backup.ts).
39189
+ * A wrong board password counts against the guess limit and is logged like
39190
+ * any other; a backup that was made is logged too, because a copy of the
39191
+ * store leaving the machine is something the log should be able to say. */
39192
+ async secretsExportBackup(payload, ctx = OWNER_CONTEXT) {
39193
+ const { spaceDir } = this.secretsDirs();
39194
+ const board = (0, import_path18.basename)(spaceDir);
39195
+ const bundle = await this.auditPasswordFailure(
39196
+ ctx,
39197
+ "secrets backup",
39198
+ [],
39199
+ () => exportSecretsBackup({
39200
+ spaceDir,
39201
+ board,
39202
+ password: payload.password,
39203
+ passphrase: payload.passphrase
39204
+ })
39205
+ );
39206
+ await this.core.audit.append({
39207
+ actor: ctx.actor,
39208
+ via: ctx.via,
39209
+ action: "backup-export",
39210
+ job: null,
39211
+ keys: [],
39212
+ exitCode: null,
39213
+ durationMs: null,
39214
+ unlockedBy: null
39215
+ });
39216
+ return {
39217
+ filename: `${board}-secrets-${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}.factiii-backup`,
39218
+ bundle
39219
+ };
39220
+ }
38584
39221
  // ── Jobs (jobs.ts), the inbox (secrets-inbox.ts), the audit log ──
38585
39222
  /** The jobs.json on the default branch. A repo with none has no jobs. */
38586
39223
  async loadJobs() {
@@ -39818,6 +40455,9 @@ var BoardAgentEngine = class _BoardAgentEngine {
39818
40455
  bareGitCommitDiff(p) {
39819
40456
  return this.terminal.bareGitCommitDiff(p);
39820
40457
  }
40458
+ bareGitCompare(p) {
40459
+ return this.terminal.bareGitCompare(p);
40460
+ }
39821
40461
  bareGitStage(p) {
39822
40462
  return this.terminal.bareGitStage(p);
39823
40463
  }
@@ -39898,6 +40538,20 @@ var BoardAgentEngine = class _BoardAgentEngine {
39898
40538
  simulatorInput(p) {
39899
40539
  return this.simulator.input(p);
39900
40540
  }
40541
+ // The Mac's own screen (screen-store.ts). Owner only: runner-access.ts.
40542
+ screenStatus(p) {
40543
+ return this.screen.status(p?.request === true);
40544
+ }
40545
+ screenAttach(p) {
40546
+ this.onScreenAttach?.();
40547
+ return this.screen.attach(p);
40548
+ }
40549
+ screenDetach() {
40550
+ this.screen.detach();
40551
+ }
40552
+ screenInput(p) {
40553
+ this.screen.input(p);
40554
+ }
39901
40555
  // ── Cross-mode coordinators ──
39902
40556
  async cardExecute(payload) {
39903
40557
  const {
@@ -40232,6 +40886,7 @@ ${c.content.trim() || "(no description)"}`
40232
40886
  this.terminal.destroy();
40233
40887
  this.scratchpad.destroy();
40234
40888
  this.simulator.destroy();
40889
+ this.screen.destroy();
40235
40890
  this.core.destroy();
40236
40891
  }
40237
40892
  /** Route one action/payload to the right engine method, for both transports.
@@ -40398,6 +41053,11 @@ ${c.content.trim() || "(no description)"}`
40398
41053
  );
40399
41054
  case "secretsLock":
40400
41055
  return await this.secretsLock(ctx);
41056
+ case "secretsExportBackup":
41057
+ return await this.secretsExportBackup(
41058
+ payload,
41059
+ ctx
41060
+ );
40401
41061
  case "secretsChangePassword":
40402
41062
  return await this.secretsChangePassword(
40403
41063
  payload,
@@ -40569,6 +41229,10 @@ ${c.content.trim() || "(no description)"}`
40569
41229
  return await this.bareGitCommitDiff(
40570
41230
  payload
40571
41231
  );
41232
+ case "bareGitCompare":
41233
+ return await this.bareGitCompare(
41234
+ payload
41235
+ );
40572
41236
  case "bareGitStage":
40573
41237
  return await this.bareGitStage(
40574
41238
  payload
@@ -40651,6 +41315,22 @@ ${c.content.trim() || "(no description)"}`
40651
41315
  case "scratchpadClear":
40652
41316
  await this.scratchpadClear();
40653
41317
  return void 0;
41318
+ case "screenStatus":
41319
+ return await this.screenStatus(
41320
+ payload
41321
+ );
41322
+ case "screenAttach":
41323
+ return await this.screenAttach(
41324
+ payload
41325
+ );
41326
+ case "screenDetach":
41327
+ this.screenDetach();
41328
+ return void 0;
41329
+ case "screenInput":
41330
+ this.screenInput(
41331
+ payload
41332
+ );
41333
+ return void 0;
40654
41334
  case "simulatorList":
40655
41335
  return await this.simulatorList();
40656
41336
  case "simulatorStatus":
@@ -40678,7 +41358,7 @@ ${c.content.trim() || "(no description)"}`
40678
41358
 
40679
41359
  // ../../shared/all/helpers/board-agent-core/index-service.ts
40680
41360
  var import_child_process5 = require("child_process");
40681
- var import_crypto10 = require("crypto");
41361
+ var import_crypto11 = require("crypto");
40682
41362
  var import_fs6 = require("fs");
40683
41363
  var import_promises14 = __toESM(require("fs/promises"));
40684
41364
  var import_net3 = require("net");
@@ -40743,7 +41423,7 @@ var IndexService = class {
40743
41423
  /** Per-space bearer for MCP + file, derived from the control token (the
40744
41424
  * service computes the same). */
40745
41425
  bearerToken(spaceSlug) {
40746
- return (0, import_crypto10.createHmac)("sha256", this.opts.controlToken).update(`mcp:${spaceSlug}`).digest("hex");
41426
+ return (0, import_crypto11.createHmac)("sha256", this.opts.controlToken).update(`mcp:${spaceSlug}`).digest("hex");
40747
41427
  }
40748
41428
  /** MCP bridge for a space. Null until the service is up (which it kicks
40749
41429
  * off), so a bad :0 URL is never baked in; provisionMcpLane re-runs. */
@@ -41039,8 +41719,15 @@ var OWNER_ONLY_ACTIONS = /* @__PURE__ */ new Set([
41039
41719
  "auditRead",
41040
41720
  "runnerAccessSet",
41041
41721
  "secretsChangePassword",
41722
+ "secretsExportBackup",
41042
41723
  "deploySecretsSetFile",
41043
- "deploySecretsUnsetFile"
41724
+ "deploySecretsUnsetFile",
41725
+ // The desktop view is the whole machine, on screen and under the pointer.
41726
+ // "Share terminals" shares a shell in a board's folder, not this.
41727
+ "screenStatus",
41728
+ "screenAttach",
41729
+ "screenDetach",
41730
+ "screenInput"
41044
41731
  ]);
41045
41732
  function actionAllowed(role, access, action) {
41046
41733
  if (role === "owner") return true;
@@ -41072,6 +41759,7 @@ var RELAY_REFUSED_ACTIONS = /* @__PURE__ */ new Set([
41072
41759
  "setupAuthorize",
41073
41760
  "deployRunAuthorize",
41074
41761
  "secretsChangePassword",
41762
+ "secretsExportBackup",
41075
41763
  "secureUnlock",
41076
41764
  "secureSetPassword",
41077
41765
  "secureClearPassword"
@@ -41174,13 +41862,13 @@ function spaceDirPath(spaceSlug) {
41174
41862
  }
41175
41863
 
41176
41864
  // src/secureFile.ts
41177
- var import_crypto13 = __toESM(require("crypto"));
41865
+ var import_crypto14 = __toESM(require("crypto"));
41178
41866
  var import_fs10 = __toESM(require("fs"));
41179
41867
  var import_path25 = __toESM(require("path"));
41180
41868
 
41181
41869
  // src/keychain.ts
41182
41870
  var import_child_process6 = require("child_process");
41183
- var import_crypto11 = __toESM(require("crypto"));
41871
+ var import_crypto12 = __toESM(require("crypto"));
41184
41872
  var import_fs8 = __toESM(require("fs"));
41185
41873
  var import_path23 = __toESM(require("path"));
41186
41874
  var SERVICE = "factiii-runner";
@@ -41427,7 +42115,7 @@ function resolve() {
41427
42115
  cached2 = { key: null, status: diagnose() };
41428
42116
  return cached2;
41429
42117
  }
41430
- const fresh = import_crypto11.default.randomBytes(32);
42118
+ const fresh = import_crypto12.default.randomBytes(32);
41431
42119
  writeKey(fresh);
41432
42120
  const verify = readKey();
41433
42121
  if (verify.state !== "found" || !verify.key.equals(fresh)) {
@@ -41449,12 +42137,12 @@ function keychainStatus() {
41449
42137
  }
41450
42138
 
41451
42139
  // src/secureStore.ts
41452
- var import_crypto12 = __toESM(require("crypto"));
42140
+ var import_crypto13 = __toESM(require("crypto"));
41453
42141
  var import_fs9 = __toESM(require("fs"));
41454
42142
  var import_path24 = __toESM(require("path"));
41455
42143
  var VAULT_KEY_FILE = import_path24.default.join(CONFIG_DIR, "vault-key.json");
41456
42144
  var RETIRED_VAULT_KEY_FILE = import_path24.default.join(CONFIG_DIR, "vault-key.retired.json");
41457
- var SCRYPT_N2 = 1 << 15;
42145
+ var SCRYPT_N3 = 1 << 15;
41458
42146
  var SecureStoreError = class extends Error {
41459
42147
  code;
41460
42148
  fix;
@@ -41479,15 +42167,15 @@ function requireKeychainKey() {
41479
42167
  );
41480
42168
  }
41481
42169
  function passwordKey(password, salt) {
41482
- return import_crypto12.default.scryptSync(password, salt, 32, {
41483
- N: SCRYPT_N2,
42170
+ return import_crypto13.default.scryptSync(password, salt, 32, {
42171
+ N: SCRYPT_N3,
41484
42172
  maxmem: 64 * 1024 * 1024
41485
42173
  });
41486
42174
  }
41487
42175
  function wrapKey(machineKey, pwKey) {
41488
42176
  const ikm = pwKey ? Buffer.concat([machineKey, pwKey]) : machineKey;
41489
42177
  return Buffer.from(
41490
- import_crypto12.default.hkdfSync(
42178
+ import_crypto13.default.hkdfSync(
41491
42179
  "sha256",
41492
42180
  ikm,
41493
42181
  Buffer.alloc(0),
@@ -41498,7 +42186,7 @@ function wrapKey(machineKey, pwKey) {
41498
42186
  }
41499
42187
  function unseal(box, key) {
41500
42188
  try {
41501
- const decipher = import_crypto12.default.createDecipheriv(
42189
+ const decipher = import_crypto13.default.createDecipheriv(
41502
42190
  "aes-256-gcm",
41503
42191
  key,
41504
42192
  Buffer.from(box.iv, "base64")
@@ -41609,8 +42297,8 @@ function storeStatus() {
41609
42297
  // src/secureFile.ts
41610
42298
  var MAGIC = "FACTIII1";
41611
42299
  function encrypt(plain, key) {
41612
- const iv = import_crypto13.default.randomBytes(12);
41613
- const cipher = import_crypto13.default.createCipheriv("aes-256-gcm", key, iv);
42300
+ const iv = import_crypto14.default.randomBytes(12);
42301
+ const cipher = import_crypto14.default.createCipheriv("aes-256-gcm", key, iv);
41614
42302
  const data = Buffer.concat([cipher.update(plain), cipher.final()]);
41615
42303
  const envelope = {
41616
42304
  v: 1,
@@ -41621,7 +42309,7 @@ function encrypt(plain, key) {
41621
42309
  return `${MAGIC}${JSON.stringify(envelope)}`;
41622
42310
  }
41623
42311
  function decrypt(envelope, key) {
41624
- const decipher = import_crypto13.default.createDecipheriv(
42312
+ const decipher = import_crypto14.default.createDecipheriv(
41625
42313
  "aes-256-gcm",
41626
42314
  key,
41627
42315
  Buffer.from(envelope.iv, "base64")
@@ -42213,14 +42901,14 @@ var ApiError = class extends Error {
42213
42901
  function isNewAddress(err2) {
42214
42902
  return err2 instanceof ApiError && err2.message === RUNNER_IP_CHALLENGE_REQUIRED;
42215
42903
  }
42216
- async function unwrap(res, path29) {
42904
+ async function unwrap(res, path30) {
42217
42905
  const raw = await res.text();
42218
42906
  let body;
42219
42907
  try {
42220
42908
  body = JSON.parse(raw);
42221
42909
  } catch {
42222
42910
  throw new ApiError(
42223
- `${path29}: the server answered ${res.status} with a non-JSON body.`,
42911
+ `${path30}: the server answered ${res.status} with a non-JSON body.`,
42224
42912
  "BAD_RESPONSE",
42225
42913
  res.status
42226
42914
  );
@@ -42228,7 +42916,7 @@ async function unwrap(res, path29) {
42228
42916
  if (body.error || !res.ok) {
42229
42917
  const err2 = body.error?.json;
42230
42918
  throw new ApiError(
42231
- err2?.message ?? `${path29} failed (${res.status}).`,
42919
+ err2?.message ?? `${path30} failed (${res.status}).`,
42232
42920
  err2?.data?.code ?? "UNKNOWN",
42233
42921
  err2?.data?.httpStatus ?? res.status
42234
42922
  );
@@ -42244,21 +42932,21 @@ function createApi(opts) {
42244
42932
  };
42245
42933
  if (opts.token) headers[RUNNER_CLI_TOKEN_HEADER] = opts.token;
42246
42934
  return {
42247
- async query(path29, input2) {
42935
+ async query(path30, input2) {
42248
42936
  const q = encodeURIComponent(JSON.stringify({ json: input2 }));
42249
- const res = await doFetch(`${base}/${path29}?input=${q}`, {
42937
+ const res = await doFetch(`${base}/${path30}?input=${q}`, {
42250
42938
  method: "GET",
42251
42939
  headers
42252
42940
  });
42253
- return unwrap(res, path29);
42941
+ return unwrap(res, path30);
42254
42942
  },
42255
- async mutation(path29, input2) {
42256
- const res = await doFetch(`${base}/${path29}`, {
42943
+ async mutation(path30, input2) {
42944
+ const res = await doFetch(`${base}/${path30}`, {
42257
42945
  method: "POST",
42258
42946
  headers,
42259
42947
  body: JSON.stringify({ json: input2 })
42260
42948
  });
42261
- return unwrap(res, path29);
42949
+ return unwrap(res, path30);
42262
42950
  }
42263
42951
  };
42264
42952
  }
@@ -43346,7 +44034,7 @@ function agentSettledPhase(previous, current) {
43346
44034
  }
43347
44035
 
43348
44036
  // src/daemon.ts
43349
- var import_crypto14 = require("crypto");
44037
+ var import_crypto15 = require("crypto");
43350
44038
  var import_fs14 = __toESM(require("fs"));
43351
44039
  var import_node_datachannel = require("node-datachannel");
43352
44040
 
@@ -43611,25 +44299,25 @@ function createPacketEncoderStream() {
43611
44299
  transform(packet, controller) {
43612
44300
  encodePacketToBinary(packet, (encodedPacket) => {
43613
44301
  const payloadLength = encodedPacket.length;
43614
- let header;
44302
+ let header2;
43615
44303
  if (payloadLength < 126) {
43616
- header = new Uint8Array(1);
43617
- new DataView(header.buffer).setUint8(0, payloadLength);
44304
+ header2 = new Uint8Array(1);
44305
+ new DataView(header2.buffer).setUint8(0, payloadLength);
43618
44306
  } else if (payloadLength < 65536) {
43619
- header = new Uint8Array(3);
43620
- const view = new DataView(header.buffer);
44307
+ header2 = new Uint8Array(3);
44308
+ const view = new DataView(header2.buffer);
43621
44309
  view.setUint8(0, 126);
43622
44310
  view.setUint16(1, payloadLength);
43623
44311
  } else {
43624
- header = new Uint8Array(9);
43625
- const view = new DataView(header.buffer);
44312
+ header2 = new Uint8Array(9);
44313
+ const view = new DataView(header2.buffer);
43626
44314
  view.setUint8(0, 127);
43627
44315
  view.setBigUint64(1, BigInt(payloadLength));
43628
44316
  }
43629
44317
  if (packet.data && typeof packet.data !== "string") {
43630
- header[0] |= 128;
44318
+ header2[0] |= 128;
43631
44319
  }
43632
- controller.enqueue(header);
44320
+ controller.enqueue(header2);
43633
44321
  controller.enqueue(encodedPacket);
43634
44322
  });
43635
44323
  }
@@ -43673,9 +44361,9 @@ function createPacketDecoderStream(maxPayload, binaryType) {
43673
44361
  if (totalLength(chunks) < 1) {
43674
44362
  break;
43675
44363
  }
43676
- const header = concatChunks(chunks, 1);
43677
- isBinary2 = (header[0] & 128) === 128;
43678
- expectedLength = header[0] & 127;
44364
+ const header2 = concatChunks(chunks, 1);
44365
+ isBinary2 = (header2[0] & 128) === 128;
44366
+ expectedLength = header2[0] & 127;
43679
44367
  if (expectedLength < 126) {
43680
44368
  state = 3;
43681
44369
  } else if (expectedLength === 126) {
@@ -44664,12 +45352,12 @@ function parse4(str) {
44664
45352
  uri.queryKey = queryKey(uri, uri["query"]);
44665
45353
  return uri;
44666
45354
  }
44667
- function pathNames(obj, path29) {
44668
- const regx = /\/{2,9}/g, names = path29.replace(regx, "/").split("/");
44669
- if (path29.slice(0, 1) == "/" || path29.length === 0) {
45355
+ function pathNames(obj, path30) {
45356
+ const regx = /\/{2,9}/g, names = path30.replace(regx, "/").split("/");
45357
+ if (path30.slice(0, 1) == "/" || path30.length === 0) {
44670
45358
  names.splice(0, 1);
44671
45359
  }
44672
- if (path29.slice(-1) == "/") {
45360
+ if (path30.slice(-1) == "/") {
44673
45361
  names.splice(names.length - 1, 1);
44674
45362
  }
44675
45363
  return names;
@@ -45288,7 +45976,7 @@ var protocol2 = Socket.protocol;
45288
45976
  // ../../node_modules/socket.io-client/build/esm-debug/url.js
45289
45977
  var import_debug7 = __toESM(require_src(), 1);
45290
45978
  var debug7 = (0, import_debug7.default)("socket.io-client:url");
45291
- function url2(uri, path29 = "", loc) {
45979
+ function url2(uri, path30 = "", loc) {
45292
45980
  let obj = uri;
45293
45981
  loc = loc || typeof location !== "undefined" && location;
45294
45982
  if (null == uri)
@@ -45322,7 +46010,7 @@ function url2(uri, path29 = "", loc) {
45322
46010
  obj.path = obj.path || "/";
45323
46011
  const ipv63 = obj.host.indexOf(":") !== -1;
45324
46012
  const host = ipv63 ? "[" + obj.host + "]" : obj.host;
45325
- obj.id = obj.protocol + "://" + host + ":" + obj.port + path29;
46013
+ obj.id = obj.protocol + "://" + host + ":" + obj.port + path30;
45326
46014
  obj.href = obj.protocol + "://" + host + (loc && loc.port === obj.port ? "" : ":" + obj.port);
45327
46015
  return obj;
45328
46016
  }
@@ -46956,8 +47644,8 @@ function lookup(uri, opts) {
46956
47644
  const parsed = url2(uri, opts.path || "/socket.io");
46957
47645
  const source = parsed.source;
46958
47646
  const id = parsed.id;
46959
- const path29 = parsed.path;
46960
- const sameNamespace = cache[id] && path29 in cache[id]["nsps"];
47647
+ const path30 = parsed.path;
47648
+ const sameNamespace = cache[id] && path30 in cache[id]["nsps"];
46961
47649
  const newConnection = opts.forceNew || opts["force new connection"] || false === opts.multiplex || sameNamespace;
46962
47650
  let io;
46963
47651
  if (newConnection) {
@@ -47140,21 +47828,45 @@ async function startDaemon(config2) {
47140
47828
  const channelScopes = /* @__PURE__ */ new Map();
47141
47829
  const simulatorSinks = /* @__PURE__ */ new Set();
47142
47830
  let warnedNoSink = false;
47831
+ const SCREEN_IDLE_MS = 1e4;
47832
+ let screenLastSeen = 0;
47833
+ const sendScreenFrame = (accessUnit, capturedAt) => {
47834
+ const delivered = sendVideoFrame(
47835
+ accessUnit,
47836
+ capturedAt,
47837
+ (sink) => sink.role === "owner"
47838
+ );
47839
+ const now = Date.now();
47840
+ if (delivered || screenLastSeen === 0) screenLastSeen = now;
47841
+ if (now - screenLastSeen > SCREEN_IDLE_MS) {
47842
+ screenLastSeen = 0;
47843
+ for (const engine of engines.values()) engine.screenDetach();
47844
+ }
47845
+ };
47143
47846
  const sendSimulatorFrame = (accessUnit, capturedAt) => {
47847
+ sendVideoFrame(
47848
+ accessUnit,
47849
+ capturedAt,
47850
+ (sink) => rawUseAllowed(sink.role, runnerAccess, "simulator")
47851
+ );
47852
+ };
47853
+ const sendVideoFrame = (accessUnit, capturedAt, mayWatch) => {
47854
+ let delivered = false;
47144
47855
  if (!simulatorSinks.size) {
47145
47856
  if (!warnedNoSink) {
47146
47857
  warnedNoSink = true;
47147
47858
  console.log("[simulator] frames produced but no track is registered");
47148
47859
  }
47149
- return;
47860
+ return delivered;
47150
47861
  }
47151
47862
  for (const sink of simulatorSinks) {
47152
47863
  if (!sink.track.isOpen()) continue;
47153
- if (!rawUseAllowed(sink.role, runnerAccess, "simulator")) continue;
47864
+ if (!mayWatch(sink)) continue;
47154
47865
  try {
47155
47866
  for (const packet of sink.packetizer.packetize(accessUnit, capturedAt)) {
47156
47867
  sink.track.sendMessageBinary(Buffer.from(packet));
47157
47868
  }
47869
+ delivered = true;
47158
47870
  } catch (err2) {
47159
47871
  simulatorSinks.delete(sink);
47160
47872
  console.log(
@@ -47164,6 +47876,7 @@ async function startDaemon(config2) {
47164
47876
  continue;
47165
47877
  }
47166
47878
  }
47879
+ return delivered;
47167
47880
  };
47168
47881
  const terminalByChannel = /* @__PURE__ */ new WeakMap();
47169
47882
  const findCardTargetInScope = (scope, postId) => {
@@ -47264,7 +47977,7 @@ async function startDaemon(config2) {
47264
47977
  ];
47265
47978
  const indexDir = indexCandidates.find((p) => import_fs14.default.existsSync(p)) ?? indexCandidates[0];
47266
47979
  const odIndex = new IndexService({
47267
- controlToken: (0, import_crypto14.createHash)("sha256").update(config2.authToken).digest("hex"),
47980
+ controlToken: (0, import_crypto15.createHash)("sha256").update(config2.authToken).digest("hex"),
47268
47981
  embedUrl: () => config2.serverUrl,
47269
47982
  reportToken: () => config2.authToken,
47270
47983
  indexDir,
@@ -47357,6 +48070,17 @@ async function startDaemon(config2) {
47357
48070
  onSimulatorAttach: () => {
47358
48071
  for (const [slug, other] of engines) {
47359
48072
  if (slug !== spaceSlug) other.simulatorDetach();
48073
+ other.screenDetach();
48074
+ }
48075
+ },
48076
+ onScreenFrame: sendScreenFrame,
48077
+ // The same one-track rule: the screen replaces the simulator, and one
48078
+ // board's capture replaces another's.
48079
+ onScreenAttach: () => {
48080
+ screenLastSeen = 0;
48081
+ for (const [slug, other] of engines) {
48082
+ other.simulatorDetach();
48083
+ if (slug !== spaceSlug) other.screenDetach();
47360
48084
  }
47361
48085
  },
47362
48086
  // Re-report connection facts after any config/OneDrive write so the
@@ -48348,6 +49072,58 @@ program2.command("password").description(
48348
49072
  fail(err2);
48349
49073
  }
48350
49074
  });
49075
+ var backup = program2.command("backup").description("Back up or restore one board's secrets, on this machine");
49076
+ backup.command("export <board>").description("Write an encrypted backup of the board's secrets to a file").option("-o, --out <file>", "where to write it (default: the current folder)").action(async (board, opts) => {
49077
+ try {
49078
+ const password = await promptPassword(`${board} board password: `);
49079
+ const passphrase = await promptPassword("New backup passphrase: ");
49080
+ const again = await promptPassword("Backup passphrase again: ");
49081
+ if (!password || !passphrase) {
49082
+ throw new Error("A backup needs a terminal to type the passwords into.");
49083
+ }
49084
+ if (passphrase !== again) throw new Error("The passphrases differ.");
49085
+ const bundle = await exportSecretsBackup({
49086
+ spaceDir: spaceDirPath(board),
49087
+ board: safeSlug(board),
49088
+ password,
49089
+ passphrase
49090
+ });
49091
+ const file2 = import_node_path3.default.resolve(
49092
+ opts.out ?? `${safeSlug(board)}-secrets-${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}.factiii-backup`
49093
+ );
49094
+ await import_promises15.default.writeFile(file2, bundle, { mode: 384, flag: "wx" });
49095
+ console.log(
49096
+ `
49097
+ Backup written to ${file2}
49098
+ Keep it and its passphrase apart. Restoring also needs the board password as it is today.
49099
+ `
49100
+ );
49101
+ } catch (err2) {
49102
+ fail(err2);
49103
+ }
49104
+ });
49105
+ backup.command("restore <board> <file>").description("Restore a backup into a board that has no secrets").action(async (board, file2) => {
49106
+ try {
49107
+ const bundle = await import_promises15.default.readFile(import_node_path3.default.resolve(file2), "utf-8");
49108
+ const passphrase = await promptPassword("Backup passphrase: ");
49109
+ if (!passphrase) {
49110
+ throw new Error("A restore needs a terminal to type the passphrase into.");
49111
+ }
49112
+ const res = await restoreSecretsBackup({
49113
+ spaceDir: spaceDirPath(board),
49114
+ bundle,
49115
+ passphrase
49116
+ });
49117
+ console.log(
49118
+ `
49119
+ Restored ${res.files} files from the ${res.board} backup of ${res.createdAt.slice(0, 10)}.
49120
+ Unlock the board with the password it had on that day.
49121
+ `
49122
+ );
49123
+ } catch (err2) {
49124
+ fail(err2);
49125
+ }
49126
+ });
48351
49127
  registerRemoteCommands(program2);
48352
49128
  program2.parse(process.argv);
48353
49129
  /*! Bundled license information: