@factiii/runner 0.13.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -3712,8 +3712,8 @@ var require_common = __commonJS({
3712
3712
  }
3713
3713
  return debug12;
3714
3714
  }
3715
- function extend(namespace, delimiter) {
3716
- const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace);
3715
+ function extend(namespace, delimiter2) {
3716
+ const newDebug = createDebug(this.namespace + (typeof delimiter2 === "undefined" ? ":" : delimiter2) + namespace);
3717
3717
  newDebug.log = this.log;
3718
3718
  return newDebug;
3719
3719
  }
@@ -14612,7 +14612,8 @@ var tiktokPostOptionsSchema = external_exports.object({
14612
14612
  });
14613
14613
  var crossPostSubmitSchema = external_exports.object({
14614
14614
  postId: external_exports.string(),
14615
- platforms: external_exports.array(crossPostPlatformEnum).min(1).max(5)
14615
+ platforms: external_exports.array(crossPostPlatformEnum).min(1).max(5),
14616
+ scheduledFor: external_exports.coerce.date().optional()
14616
14617
  });
14617
14618
  var apiCostUpdateSchema = external_exports.object({
14618
14619
  platform: crossPostPlatformEnum,
@@ -14953,6 +14954,7 @@ async function checkDeployStatus(opts) {
14953
14954
  workspace,
14954
14955
  "fetch",
14955
14956
  "origin",
14957
+ "--prune",
14956
14958
  "+refs/heads/deploy-skill*:refs/remotes/origin/deploy-skill*"
14957
14959
  );
14958
14960
  const refs = await hostGit(
@@ -15172,6 +15174,18 @@ async function loadSkillDraft(opts) {
15172
15174
  }
15173
15175
  await checkDeployStatus(opts);
15174
15176
  const workspace = import_path6.default.join(opts.spaceDir, "workspace");
15177
+ const onRemote = await hostGit(
15178
+ workspace,
15179
+ "ls-remote",
15180
+ "--heads",
15181
+ "origin",
15182
+ branch
15183
+ ).catch(() => "");
15184
+ if (!onRemote.trim()) {
15185
+ throw new Error(
15186
+ `Branch ${branch} is no longer on origin - it was merged or deleted. Draft the deploy skill again.`
15187
+ );
15188
+ }
15175
15189
  await hostGit(
15176
15190
  workspace,
15177
15191
  "fetch",
@@ -16070,7 +16084,9 @@ EOF
16070
16084
  # nohup, not setsid: setsid does not exist on macOS.
16071
16085
  nohup frpc -c "$TOML" > "${p.runDir}/\${NAME}.log" 2>&1 < /dev/null &
16072
16086
  echo $! > "${p.runDir}/\${NAME}.pid"
16073
- echo "http://\${DOMAIN}"
16087
+ # https: the Mini terminates TLS for *.dev.factiii.com on the dockerized nginx
16088
+ # (wildcard cert, DNS-01). :80 still works and frps only speaks HTTP behind it.
16089
+ echo "https://\${DOMAIN}"
16074
16090
  `;
16075
16091
  }
16076
16092
  function frpcUnexposeScript(p) {
@@ -16221,7 +16237,10 @@ async function listLiveTunnels(target) {
16221
16237
  ` port=$(sed -n 's/^localPort = *//p' "$name.toml" | head -1)`,
16222
16238
  ` sub=$(sed -n 's/^subdomain = *//p' "$name.toml" | tr -d '"' | head -1)`,
16223
16239
  ' [ -n "$port" ] && [ -n "$sub" ] || continue',
16224
- ` echo "$name${ROW_SEP}$port${ROW_SEP}http://$sub.$FACTIII_FRP_DOMAIN"`,
16240
+ // https, matching what factiii-expose prints: the Mini terminates TLS for
16241
+ // *.dev.factiii.com on the dockerized nginx. Showing http:// here made the
16242
+ // Ports panel disagree with the URL the agent had just handed the user.
16243
+ ` echo "$name${ROW_SEP}$port${ROW_SEP}https://$sub.$FACTIII_FRP_DOMAIN"`,
16225
16244
  "done"
16226
16245
  ].join("\n");
16227
16246
  const out = await target.run(["sh", "-c", script]).catch(() => "");
@@ -17685,6 +17704,8 @@ var NOISE_GLOBS = ["**/.DS_Store", "**/4913", "**/*~", "**/.#*", "**/#*#"];
17685
17704
  var MAX_BATCH = 200;
17686
17705
  var FLUSH_MS = 120;
17687
17706
  var SELF_WRITE_MS = 2e3;
17707
+ var RETRY_MIN_MS = 500;
17708
+ var RETRY_MAX_MS = 15e3;
17688
17709
  var dynamicImport = new Function("s", "return import(s)");
17689
17710
  var importFs = new Function("s", "return import(s)");
17690
17711
  async function resolveReal(path23) {
@@ -17715,13 +17736,16 @@ var WorkspaceWatcher = class {
17715
17736
  * A no-git card's root is the space dir itself, which also
17716
17737
  * holds the runner's own bookkeeping.
17717
17738
  */
17718
- constructor(root, emit, exclude = []) {
17739
+ constructor(root, emit, exclude = [], subscribeImpl) {
17719
17740
  this.root = root;
17720
17741
  this.emit = emit;
17721
17742
  this.exclude = exclude;
17743
+ this.subscribeImpl = subscribeImpl;
17722
17744
  this.sub = null;
17723
17745
  this.pending = emptyPending();
17724
17746
  this.flushTimer = null;
17747
+ this.retryTimer = null;
17748
+ this.retryDelay = RETRY_MIN_MS;
17725
17749
  /** path -> expiry. Events for these are ours (the editor just saved) and must
17726
17750
  * not come back as "changed on disk". */
17727
17751
  this.selfWrites = /* @__PURE__ */ new Map();
@@ -17731,11 +17755,11 @@ var WorkspaceWatcher = class {
17731
17755
  /** Fire-and-forget: callers treat starting a watch as synchronous, and
17732
17756
  * nothing can be emitted before `subscribe` resolves anyway. */
17733
17757
  start() {
17734
- if (this.sub || this.closed) return;
17758
+ if (this.sub || this.closed || this.retryTimer) return;
17735
17759
  void this.open();
17736
17760
  }
17737
17761
  async open() {
17738
- const subscribe = await getSubscribe();
17762
+ const subscribe = this.subscribeImpl ?? await getSubscribe();
17739
17763
  if (!subscribe) return this.stop();
17740
17764
  this.watchRoot = await resolveReal(this.root);
17741
17765
  const exclude = await Promise.all(this.exclude.map(resolveReal));
@@ -17743,7 +17767,7 @@ var WorkspaceWatcher = class {
17743
17767
  const sub = await subscribe(
17744
17768
  this.watchRoot,
17745
17769
  (err, events) => {
17746
- if (err) return this.stop();
17770
+ if (err) return this.retry();
17747
17771
  for (const event of events) this.onEvent(event);
17748
17772
  },
17749
17773
  // Prunes the walk itself, so a pruned tree is never enumerated.
@@ -17760,10 +17784,39 @@ var WorkspaceWatcher = class {
17760
17784
  return;
17761
17785
  }
17762
17786
  this.sub = sub;
17787
+ this.retryDelay = RETRY_MIN_MS;
17763
17788
  } catch {
17764
- this.stop();
17789
+ this.retry();
17765
17790
  }
17766
17791
  }
17792
+ /**
17793
+ * Re-subscribe after the OS dropped the watch — a remount, a wake from
17794
+ * sleep, an inotify limit easing. Treating those as terminal left a runner
17795
+ * watching nothing for the rest of its life. `resync` on the way back up,
17796
+ * since whatever changed while it was down produced no events.
17797
+ */
17798
+ retry() {
17799
+ if (this.closed || this.retryTimer) return;
17800
+ const sub = this.sub;
17801
+ this.sub = null;
17802
+ if (sub) void sub.unsubscribe().catch(() => void 0);
17803
+ const delay = this.retryDelay;
17804
+ this.retryDelay = Math.min(this.retryDelay * 2, RETRY_MAX_MS);
17805
+ this.retryTimer = setTimeout(() => {
17806
+ this.retryTimer = null;
17807
+ if (this.closed) return;
17808
+ void this.open().then(() => {
17809
+ if (this.sub) {
17810
+ this.emit({
17811
+ added: [],
17812
+ changed: [],
17813
+ removed: [],
17814
+ resync: true
17815
+ });
17816
+ }
17817
+ });
17818
+ }, delay);
17819
+ }
17767
17820
  /** Give up and say so once, so the UI falls back to manual refresh rather
17768
17821
  * than showing a silently frozen tree. */
17769
17822
  stop() {
@@ -17799,6 +17852,10 @@ var WorkspaceWatcher = class {
17799
17852
  this.flushTimer = null;
17800
17853
  }
17801
17854
  this.pending = emptyPending();
17855
+ if (this.retryTimer) {
17856
+ clearTimeout(this.retryTimer);
17857
+ this.retryTimer = null;
17858
+ }
17802
17859
  this.selfWrites.clear();
17803
17860
  const sub = this.sub;
17804
17861
  this.sub = null;
@@ -19541,12 +19598,82 @@ async function unsetSecret(configDir, spaceDir, password, key) {
19541
19598
  const values = await readEnv(spaceDir, identity);
19542
19599
  delete values[key];
19543
19600
  await writeEnv(configDir, spaceDir, identity, values);
19601
+ await pruneSecretMeta(spaceDir);
19544
19602
  return { success: true };
19545
19603
  }
19546
19604
  async function secretsForInjection(configDir, spaceDir, password) {
19547
19605
  const identity = await identityFor(configDir, password);
19548
19606
  return readEnv(spaceDir, identity);
19549
19607
  }
19608
+ var META_FILE = "secrets.meta.json";
19609
+ function metaPath(spaceDir) {
19610
+ return import_path11.default.join(spaceDir, "secrets", META_FILE);
19611
+ }
19612
+ function normalizeMeta(raw) {
19613
+ const row = raw ?? {};
19614
+ const text = (v) => typeof v === "string" ? v.trim() : "";
19615
+ return {
19616
+ title: text(row.title),
19617
+ description: text(row.description),
19618
+ category: text(row.category),
19619
+ source: text(row.source)
19620
+ };
19621
+ }
19622
+ async function readSecretMeta(spaceDir) {
19623
+ const raw = await import_promises9.default.readFile(metaPath(spaceDir), "utf-8").catch(() => "");
19624
+ if (!raw) return {};
19625
+ let parsed;
19626
+ try {
19627
+ parsed = JSON.parse(raw);
19628
+ } catch {
19629
+ return {};
19630
+ }
19631
+ const keys = parsed.keys;
19632
+ if (!keys || typeof keys !== "object") return {};
19633
+ const out = {};
19634
+ for (const [key, row] of Object.entries(keys)) {
19635
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) continue;
19636
+ out[key] = normalizeMeta(row);
19637
+ }
19638
+ return out;
19639
+ }
19640
+ async function writeSecretMeta(spaceDir, keys) {
19641
+ const file = metaPath(spaceDir);
19642
+ await import_promises9.default.mkdir(import_path11.default.dirname(file), { recursive: true });
19643
+ const body = { v: 1, keys };
19644
+ const tmp = `${file}.${process.pid}.tmp`;
19645
+ await import_promises9.default.writeFile(tmp, `${JSON.stringify(body, null, 2)}
19646
+ `, {
19647
+ mode: 384
19648
+ });
19649
+ await import_promises9.default.rename(tmp, file);
19650
+ }
19651
+ async function setSecretMeta(spaceDir, key, patch) {
19652
+ if (!/^[A-Z][A-Z0-9_]*$/i.test(key)) {
19653
+ throw new Error("Key must be an env-style name (letters, digits, _).");
19654
+ }
19655
+ const all = await readSecretMeta(spaceDir);
19656
+ const next = normalizeMeta({ ...all[key] ?? {}, ...patch });
19657
+ if (!next.title && !next.description && !next.source) {
19658
+ delete all[key];
19659
+ } else {
19660
+ all[key] = next;
19661
+ }
19662
+ await writeSecretMeta(spaceDir, all);
19663
+ return { success: true };
19664
+ }
19665
+ async function pruneSecretMeta(spaceDir) {
19666
+ const all = await readSecretMeta(spaceDir);
19667
+ const stored = new Set(await storedSecretKeys(spaceDir));
19668
+ let changed = false;
19669
+ for (const key of Object.keys(all)) {
19670
+ if (!stored.has(key)) {
19671
+ delete all[key];
19672
+ changed = true;
19673
+ }
19674
+ }
19675
+ if (changed) await writeSecretMeta(spaceDir, all);
19676
+ }
19550
19677
 
19551
19678
  // ../../shared/all/helpers/board-agent-core/secrets-run.ts
19552
19679
  var COMMAND_IDLE_TIMEOUT_MS = 45 * 6e4;
@@ -19936,7 +20063,6 @@ var ScratchpadStore = class {
19936
20063
  */
19937
20064
  async list() {
19938
20065
  const dir = this.dir();
19939
- this.startWatching();
19940
20066
  const out = await this.target().run([
19941
20067
  "sh",
19942
20068
  "-c",
@@ -19946,6 +20072,7 @@ var ScratchpadStore = class {
19946
20072
  echo "$meta $f"
19947
20073
  done | LC_ALL=C sort -rn | head -n ${SCRATCHPAD_MAX_ITEMS}`
19948
20074
  ]);
20075
+ this.startWatching();
19949
20076
  const items = [];
19950
20077
  for (const line of out.split("\n")) {
19951
20078
  const match = /^(\d+) (\d+) (.+)$/.exec(line);
@@ -20062,6 +20189,16 @@ var ScratchpadStore = class {
20062
20189
  var import_promises10 = require("fs/promises");
20063
20190
  var import_path14 = __toESM(require("path"));
20064
20191
 
20192
+ // ../../shared/all/helpers/board-agent-core/secret-descriptions.ts
20193
+ var DEFAULT_SECRET_CATEGORY = "general";
20194
+ function describeSecret(meta, contract) {
20195
+ return {
20196
+ title: meta?.title || contract?.title || "",
20197
+ description: meta?.description || contract?.description || "",
20198
+ category: meta?.category || contract?.category || DEFAULT_SECRET_CATEGORY
20199
+ };
20200
+ }
20201
+
20065
20202
  // ../../shared/all/helpers/board-agent-core/toolchain.ts
20066
20203
  var TOOLS = [
20067
20204
  { bin: "git" },
@@ -20352,24 +20489,26 @@ var SpaceCore = class {
20352
20489
  }
20353
20490
  });
20354
20491
  }
20355
- /** Key NAMES and status, no password. The contract declares its keys in
20356
- * public on the default branch, and sops leaves names in cleartext, so this
20357
- * reveals nothing the repo and the file do not already say. */
20492
+ /** Key NAMES, status and purpose, no password. The contract declares its
20493
+ * keys in public on the default branch, sops leaves names in cleartext, and
20494
+ * the meta sidecar holds only descriptions - so this reveals nothing the
20495
+ * repo and the files do not already say. */
20358
20496
  async secretsKeyInfo() {
20359
20497
  const stored = new Set(await storedSecretKeys(this.spaceDir()));
20498
+ const meta = await readSecretMeta(this.spaceDir());
20360
20499
  const config = this.readConfig();
20361
- const declared = new Set(
20362
- config.repoUrl && config.githubToken ? await checkDeployStatus({
20363
- spaceDir: this.spaceDir(),
20364
- repoUrl: config.repoUrl,
20365
- mainBranch: config.mainBranch,
20366
- githubToken: config.githubToken
20367
- }).then((status) => status.variables.map((v) => v.key)).catch(() => []) : []
20368
- );
20369
- return [.../* @__PURE__ */ new Set([...declared, ...stored])].sort().map((key) => ({
20500
+ const variables = await (config.repoUrl && config.githubToken ? checkDeployStatus({
20501
+ spaceDir: this.spaceDir(),
20502
+ repoUrl: config.repoUrl,
20503
+ mainBranch: config.mainBranch,
20504
+ githubToken: config.githubToken
20505
+ }).then((status) => status.variables).catch(() => []) : []);
20506
+ const declared = new Map(variables.map((v) => [v.key, v]));
20507
+ return [.../* @__PURE__ */ new Set([...declared.keys(), ...stored])].sort().map((key) => ({
20370
20508
  key,
20371
20509
  stored: stored.has(key),
20372
- declared: declared.has(key)
20510
+ declared: declared.has(key),
20511
+ ...describeSecret(meta[key], declared.get(key))
20373
20512
  }));
20374
20513
  }
20375
20514
  /**
@@ -21488,7 +21627,8 @@ var BoardAgentEngine = class _BoardAgentEngine {
21488
21627
  async deploySecretsList(payload) {
21489
21628
  const { configDir, spaceDir } = this.secretsDirs();
21490
21629
  return {
21491
- keys: await listSecretKeys(configDir, spaceDir, payload.password)
21630
+ keys: await listSecretKeys(configDir, spaceDir, payload.password),
21631
+ meta: await readSecretMeta(spaceDir)
21492
21632
  };
21493
21633
  }
21494
21634
  deploySecretsSet(payload) {
@@ -21501,6 +21641,10 @@ var BoardAgentEngine = class _BoardAgentEngine {
21501
21641
  payload.value
21502
21642
  );
21503
21643
  }
21644
+ deploySecretsSetMeta(payload) {
21645
+ const { key, ...patch } = payload;
21646
+ return setSecretMeta(this.secretsDirs().spaceDir, key, patch);
21647
+ }
21504
21648
  deploySecretsUnset(payload) {
21505
21649
  const { configDir, spaceDir } = this.secretsDirs();
21506
21650
  return unsetSecret(configDir, spaceDir, payload.password, payload.key);
@@ -22405,6 +22549,10 @@ ${c.content.trim() || "(no description)"}`
22405
22549
  return await this.deploySecretsSet(
22406
22550
  payload
22407
22551
  );
22552
+ case "deploySecretsSetMeta":
22553
+ return await this.deploySecretsSetMeta(
22554
+ payload
22555
+ );
22408
22556
  case "deploySecretsUnset":
22409
22557
  return await this.deploySecretsUnset(
22410
22558
  payload
@@ -22718,7 +22866,8 @@ var IndexService = class {
22718
22866
  PORT: String(port),
22719
22867
  CONTROL_TOKEN: this.opts.controlToken,
22720
22868
  EMBED_URL: this.opts.embedUrl(),
22721
- INDEX_DATA_DIR: this.opts.dataDir
22869
+ INDEX_DATA_DIR: this.opts.dataDir,
22870
+ ...this.opts.reportToken?.() ? { REPORT_TOKEN: this.opts.reportToken() } : {}
22722
22871
  },
22723
22872
  stdio: log ? ["ignore", log, log] : "ignore",
22724
22873
  // Own process group so stop() reaps it; nothing else reaps orphans here.
@@ -22776,7 +22925,7 @@ var IndexService = class {
22776
22925
  // chosen interpreter has to lead PATH or the build targets the wrong ABI.
22777
22926
  env: {
22778
22927
  ...process.env,
22779
- PATH: `${(0, import_path17.dirname)(nodeBin)}:${process.env.PATH ?? ""}`
22928
+ PATH: `${(0, import_path17.dirname)(nodeBin)}${import_path17.delimiter}${process.env.PATH ?? ""}`
22780
22929
  }
22781
22930
  }
22782
22931
  );
@@ -23869,6 +24018,14 @@ function installLatest() {
23869
24018
  // src/supervisor.ts
23870
24019
  var import_node_child_process2 = require("node:child_process");
23871
24020
 
24021
+ // ../../shared/all/domains/socket.ts
24022
+ function agentSettledPhase(previous, current) {
24023
+ if (previous !== "working" || current === "working") return null;
24024
+ if (current === "idle") return "terminal-idle";
24025
+ if (current === "blocked") return "terminal-blocked";
24026
+ return null;
24027
+ }
24028
+
23872
24029
  // src/daemon.ts
23873
24030
  var import_crypto11 = require("crypto");
23874
24031
  var import_fs12 = __toESM(require("fs"));
@@ -27732,14 +27889,23 @@ async function startDaemon(config) {
27732
27889
  "bare-review"
27733
27890
  ]);
27734
27891
  const lastPhase = /* @__PURE__ */ new Map();
27892
+ const lastAgentState = /* @__PURE__ */ new Map();
27893
+ const settledEndPhase = (postId, s) => {
27894
+ const phase = s.phase ?? "";
27895
+ const previousPhase = lastPhase.get(postId);
27896
+ lastPhase.set(postId, phase);
27897
+ const previousState = lastAgentState.get(postId);
27898
+ lastAgentState.set(postId, s.agentState);
27899
+ if (previousPhase !== void 0 && previousPhase !== phase && END_PHASES.has(phase)) {
27900
+ return phase;
27901
+ }
27902
+ return agentSettledPhase(previousState, s.agentState);
27903
+ };
27735
27904
  const reportSettledSession = (spaceSlug, payload) => {
27736
27905
  const s = payload;
27737
27906
  if (!s || typeof s.postId !== "string") return;
27738
- const phase = s.phase ?? "";
27739
- const previous = lastPhase.get(s.postId);
27740
- lastPhase.set(s.postId, phase);
27741
- if (previous === void 0 || previous === phase) return;
27742
- if (!END_PHASES.has(phase)) return;
27907
+ const phase = settledEndPhase(s.postId, s);
27908
+ if (!phase) return;
27743
27909
  try {
27744
27910
  socket.emit("runnerSessionFinished", {
27745
27911
  spaceSlug,
@@ -27788,6 +27954,7 @@ async function startDaemon(config) {
27788
27954
  const odIndex = new IndexService({
27789
27955
  controlToken: (0, import_crypto11.createHash)("sha256").update(config.authToken).digest("hex"),
27790
27956
  embedUrl: () => config.serverUrl,
27957
+ reportToken: () => config.authToken,
27791
27958
  indexDir,
27792
27959
  dataDir: import_path24.default.join(CONFIG_DIR, "index-data")
27793
27960
  });
package/index/index.js CHANGED
@@ -15849,7 +15849,7 @@ var require_BufferList = __commonJS({
15849
15849
  this.tail = null;
15850
15850
  this.length = 0;
15851
15851
  }
15852
- BufferList.prototype.push = function push2(v) {
15852
+ BufferList.prototype.push = function push3(v) {
15853
15853
  var entry = { data: v, next: null };
15854
15854
  if (this.length > 0) this.tail.next = entry;
15855
15855
  else this.head = entry;
@@ -90706,12 +90706,12 @@ var readBodyBufferedBeforeDisconnect = (incoming, chunks) => {
90706
90706
  incomingWithRecovery[bodyBufferedBeforeDisconnectKey] = result2;
90707
90707
  return result2;
90708
90708
  };
90709
- var enqueueBufferedBody = (controller, buffered) => {
90710
- if (buffered instanceof Error) {
90711
- controller.error(buffered);
90709
+ var enqueueBufferedBody = (controller, buffered2) => {
90710
+ if (buffered2 instanceof Error) {
90711
+ controller.error(buffered2);
90712
90712
  return;
90713
90713
  }
90714
- if (buffered.length > 0) controller.enqueue(buffered);
90714
+ if (buffered2.length > 0) controller.enqueue(buffered2);
90715
90715
  controller.close();
90716
90716
  };
90717
90717
  var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
@@ -90737,9 +90737,9 @@ var newRequestFromIncoming = (method, url, headers, incoming, abortController) =
90737
90737
  init.body = new ReadableStream({ async pull(controller) {
90738
90738
  try {
90739
90739
  if (!reader) {
90740
- const buffered = readBodyBufferedBeforeDisconnect(incoming);
90741
- if (buffered !== void 0) {
90742
- enqueueBufferedBody(controller, buffered);
90740
+ const buffered2 = readBodyBufferedBeforeDisconnect(incoming);
90741
+ if (buffered2 !== void 0) {
90742
+ enqueueBufferedBody(controller, buffered2);
90743
90743
  return;
90744
90744
  }
90745
90745
  }
@@ -90752,9 +90752,9 @@ var newRequestFromIncoming = (method, url, headers, incoming, abortController) =
90752
90752
  }
90753
90753
  } });
90754
90754
  } else {
90755
- const buffered = readBodyBufferedBeforeDisconnect(incoming);
90756
- if (buffered !== void 0) init.body = new ReadableStream({ start(controller) {
90757
- enqueueBufferedBody(controller, buffered);
90755
+ const buffered2 = readBodyBufferedBeforeDisconnect(incoming);
90756
+ if (buffered2 !== void 0) init.body = new ReadableStream({ start(controller) {
90757
+ enqueueBufferedBody(controller, buffered2);
90758
90758
  } });
90759
90759
  else init.body = import_node_stream.Readable.toWeb(incoming);
90760
90760
  }
@@ -90861,11 +90861,11 @@ var readBodyDirect = (request) => {
90861
90861
  if (request[bodyReadPromiseKey]) return request[bodyReadPromiseKey];
90862
90862
  const incoming = request[incomingKey];
90863
90863
  if (incoming.readableDidRead) return rejectBodyUnusable();
90864
- const buffered = readBodyBufferedBeforeDisconnect(incoming);
90865
- if (buffered !== void 0) {
90866
- if (buffered instanceof Error) return Promise.reject(buffered);
90867
- request[bodyBufferKey] = buffered;
90868
- return Promise.resolve(buffered);
90864
+ const buffered2 = readBodyBufferedBeforeDisconnect(incoming);
90865
+ if (buffered2 !== void 0) {
90866
+ if (buffered2 instanceof Error) return Promise.reject(buffered2);
90867
+ request[bodyBufferKey] = buffered2;
90868
+ return Promise.resolve(buffered2);
90869
90869
  }
90870
90870
  const promise = new Promise((resolve, reject2) => {
90871
90871
  const chunks = [];
@@ -93227,6 +93227,93 @@ function listFiles(db2, pathPrefix) {
93227
93227
  ).all(`${pathPrefix}%`);
93228
93228
  }
93229
93229
 
93230
+ // ../../shared/all/helpers/errorRedaction.ts
93231
+ var REDACTED = "[redacted]";
93232
+ var SECRET_PARAMS = /\b(access_token|refresh_token|id_token|client_secret|client_id|code|token|tempauth|api[-_]?key|apikey|password|secret|authorization)=[^&\s"'<>)\]}]+/gi;
93233
+ var SECRET_FIELDS = /(["']?(?:access_?token|refresh_?token|id_?token|client_?secret|api_?key|password|secret|authorization)["']?\s*[:=]\s*)(["'][^"']*["']|[^\s,;}&]+)/gi;
93234
+ var BEARER = /\bBearer\s+[A-Za-z0-9\-._~+/]+=*/gi;
93235
+ var JWT = /\beyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}/g;
93236
+ var EMAIL = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g;
93237
+ var POSIX_HOME = /\/(Users|home)\/[^/\s"']+/g;
93238
+ var WINDOWS_HOME = /([A-Za-z]:\\Users\\)[^\\\s"']+/g;
93239
+ var DOCUMENT_FILE = /[^\n/\\"'<>:;,|?*]{1,120}\.(docx?|pptx?|xlsx?|pdf|txt|md|csv|rtf|odt|pages|key|numbers|epub|png|jpe?g|gif|webp|heic|tiff?|bmp|svg|mp[34]|m4a|mov|avi|mkv|wav|zip)\b/gi;
93240
+ function redactErrorText(input) {
93241
+ return input.replace(BEARER, `Bearer ${REDACTED}`).replace(JWT, REDACTED).replace(SECRET_PARAMS, (_m2, key) => `${key}=${REDACTED}`).replace(
93242
+ SECRET_FIELDS,
93243
+ (m, prefix, value) => value.includes(REDACTED) || /^(Bearer|Basic)$/i.test(value) ? m : `${prefix}${REDACTED}`
93244
+ ).replace(EMAIL, "[email]").replace(POSIX_HOME, (_m2, root2) => `/${root2}/[user]`).replace(WINDOWS_HOME, (_m2, root2) => `${root2}[user]`).replace(
93245
+ DOCUMENT_FILE,
93246
+ (_m2, ext) => `[file].${ext.toLowerCase()}`
93247
+ );
93248
+ }
93249
+ var MAX_REPORT_STACK = 4e3;
93250
+ function redactForReport(input) {
93251
+ const redacted = redactErrorText(input);
93252
+ return redacted.length > MAX_REPORT_STACK ? `${redacted.slice(0, MAX_REPORT_STACK)}\u2026[truncated]` : redacted;
93253
+ }
93254
+
93255
+ // src/reporter.ts
93256
+ var REPORT_TOKEN = process.env.REPORT_TOKEN || "";
93257
+ var REPORT_URL = process.env.EMBED_URL || "";
93258
+ var REPORT_TIMEOUT_MS = 1e4;
93259
+ var MAX_BUFFERED = 100;
93260
+ var MAX_PER_PUSH = 50;
93261
+ var buffered = [];
93262
+ function bufferReport(report) {
93263
+ buffered.push(report);
93264
+ if (buffered.length > MAX_BUFFERED) buffered.splice(0, buffered.length - MAX_BUFFERED);
93265
+ }
93266
+ async function push2(reports) {
93267
+ if (!REPORT_TOKEN || !REPORT_URL || reports.length === 0) return false;
93268
+ try {
93269
+ const res = await fetch(
93270
+ `${REPORT_URL.replace(/\/$/, "")}/trpc/runners.reportError`,
93271
+ {
93272
+ method: "POST",
93273
+ headers: {
93274
+ "content-type": "application/json",
93275
+ // authGuard rejects a request with no user agent outright.
93276
+ "user-agent": "factiii-index",
93277
+ // Same header the board MCP presents; the runner's pairing token.
93278
+ "x-factiii-bot-token": REPORT_TOKEN
93279
+ },
93280
+ // The server's tRPC runs a superjson transformer, so input arrives
93281
+ // under `json`. Every field here is a plain string, so there is no meta
93282
+ // to send and no need to pull superjson into this bundle.
93283
+ body: JSON.stringify({ json: { reports } }),
93284
+ signal: AbortSignal.timeout(REPORT_TIMEOUT_MS)
93285
+ }
93286
+ );
93287
+ return res.ok;
93288
+ } catch {
93289
+ return false;
93290
+ }
93291
+ }
93292
+ async function reportSyncError(summary, detail, severity) {
93293
+ const text2 = detail instanceof Error ? detail.stack ?? detail.message : String(detail);
93294
+ const report = {
93295
+ summary: redactForReport(summary),
93296
+ detail: redactForReport(text2),
93297
+ severity,
93298
+ occurredAt: (/* @__PURE__ */ new Date()).toISOString()
93299
+ };
93300
+ console.error(`[onedrive] ${report.summary}: ${report.detail}`);
93301
+ const batch = [...buffered.splice(0, MAX_PER_PUSH - 1), report];
93302
+ if (!await push2(batch)) batch.forEach(bufferReport);
93303
+ }
93304
+ async function flushSyncErrors() {
93305
+ let sent = 0;
93306
+ while (buffered.length > 0) {
93307
+ const batch = buffered.splice(0, MAX_PER_PUSH);
93308
+ if (!await push2(batch)) {
93309
+ batch.forEach(bufferReport);
93310
+ break;
93311
+ }
93312
+ sent += batch.length;
93313
+ }
93314
+ return sent;
93315
+ }
93316
+
93230
93317
  // src/indexer.ts
93231
93318
  function metaFromItem(item, filePath) {
93232
93319
  const info = item.fileSystemInfo ?? {};
@@ -93275,6 +93362,7 @@ async function runIndex(serverUrl, spaceSlug, conn, hooks = {}, full = false) {
93275
93362
  lastEmbedError = result2.lastEmbedError;
93276
93363
  }
93277
93364
  }
93365
+ void flushSyncErrors();
93278
93366
  hooks.onProgress?.(
93279
93367
  anyEmbedFailure && embedded === 0 ? {
93280
93368
  status: "error",
@@ -93288,6 +93376,7 @@ async function runIndex(serverUrl, spaceSlug, conn, hooks = {}, full = false) {
93288
93376
  done,
93289
93377
  error: err instanceof Error ? err.message : String(err)
93290
93378
  });
93379
+ await reportSyncError("OneDrive sync pass failed", err, "CRITICAL");
93291
93380
  throw err;
93292
93381
  } finally {
93293
93382
  db2.close();
@@ -93326,9 +93415,9 @@ async function indexFolder(db2, serverUrl, token, folder, full, hooks) {
93326
93415
  } catch (err) {
93327
93416
  embedFailure = true;
93328
93417
  lastEmbedError = err instanceof Error ? err.message : String(err);
93329
- console.error(
93330
- `[onedrive] embed failed for ${item.name}:`,
93331
- lastEmbedError
93418
+ void reportSyncError(
93419
+ `OneDrive embed failed (${fileExt(item.name) || "no ext"})`,
93420
+ err
93332
93421
  );
93333
93422
  }
93334
93423
  } else if (cTagChanged) {
@@ -93348,9 +93437,10 @@ async function embedFile(db2, serverUrl, token, item) {
93348
93437
  try {
93349
93438
  text2 = await extractText2(item.name, bytes);
93350
93439
  } catch (err) {
93351
- console.error(
93352
- `[onedrive] extract failed for ${item.name} (skipped):`,
93353
- err instanceof Error ? err.message : err
93440
+ void reportSyncError(
93441
+ `OneDrive extract failed (${fileExt(item.name) || "no ext"})`,
93442
+ err,
93443
+ "LOW"
93354
93444
  );
93355
93445
  text2 = null;
93356
93446
  }
@@ -93664,10 +93754,7 @@ var Store = class {
93664
93754
  });
93665
93755
  this.saveSub(spaceSlug, r.id, r.expirationDateTime);
93666
93756
  } catch (err) {
93667
- console.error(
93668
- `[onedrive] webhook ensure failed for ${spaceSlug}:`,
93669
- err instanceof Error ? err.message : err
93670
- );
93757
+ void reportSyncError(`OneDrive webhook ensure failed (${spaceSlug})`, err);
93671
93758
  }
93672
93759
  }
93673
93760
  saveSub(spaceSlug, id2, expiry) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@factiii/runner",
3
- "version": "0.13.0",
3
+ "version": "0.14.0",
4
4
  "description": "Factiii Runner, run Board AI agents on a machine you control. Pairs with the Factiii web/mobile clients over WebRTC.",
5
5
  "license": "ISC",
6
6
  "keywords": [
@@ -84,18 +84,30 @@ function parseKeys(argv) {
84
84
  return { keys, rest: argv.slice(i) };
85
85
  }
86
86
 
87
- /** `NAME status` rows, aligned, so a long store stays readable. */
87
+ /**
88
+ * `NAME status title` rows, aligned, each followed by its description
89
+ * indented underneath.
90
+ *
91
+ * The description is the reason to run this at all: a bare name says a
92
+ * credential exists, not which command wants it or what breaks without it.
93
+ * Older runners send no description, so every field here is optional and an
94
+ * undescribed store still prints exactly the rows it used to.
95
+ */
88
96
  function formatKeys(entries) {
89
97
  const width = entries.reduce((max, e) => Math.max(max, e.key.length), 0);
90
- return entries
91
- .map((entry) => {
92
- const status = [
93
- entry.stored ? 'set' : 'not set',
94
- entry.declared ? 'declared' : 'undeclared'
95
- ].join(', ');
96
- return `${entry.key.padEnd(width)} ${status}`;
97
- })
98
- .join('\n');
98
+ const lines = [];
99
+ for (const entry of entries) {
100
+ const status = [
101
+ entry.stored ? 'set' : 'not set',
102
+ entry.declared ? 'declared' : 'undeclared'
103
+ ].join(', ');
104
+ const title = entry.title ? ` ${entry.title}` : '';
105
+ lines.push(`${entry.key.padEnd(width)} ${status}${title}`);
106
+ if (entry.description) {
107
+ lines.push(`${' '.repeat(width + 2)}${entry.description}`);
108
+ }
109
+ }
110
+ return lines.join('\n');
99
111
  }
100
112
 
101
113
  /** `<spaceDir>/state/secrets.sock`. The env var is what the runner sets on
@@ -75,17 +75,25 @@ factiii-secrets list
75
75
  ```
76
76
 
77
77
  prints the key NAMES this workspace has, whether the store actually holds a
78
- value for each, and whether the deploy contract declares it:
78
+ value for each, whether the deploy contract declares it, and what each one is
79
+ FOR:
79
80
 
80
81
  ```
81
- DATABASE_URL set, declared
82
- EXPO_TOKEN not set, declared
82
+ DATABASE_URL set, declared Primary Postgres URL
83
+ The database migrations run against. Points at prod; staging
84
+ has its own.
85
+ EXPO_TOKEN not set, declared Expo access token
86
+ Authenticates the EAS CLI for mobile builds and submits.
83
87
  OLD_TOKEN set, undeclared
84
88
  ```
85
89
 
86
- Never their values; there is no command that prints a value, on purpose. Use
87
- it when you are unsure what a key is called - guessing a name gets you an
88
- empty variable, not the value.
90
+ Never their values; there is no command that prints a value, on purpose.
91
+
92
+ Read this before guessing. It answers both "what is the key called" - a
93
+ guessed name gets you an empty variable, not the value - and "which key does
94
+ this step actually need", which the name alone often does not say. A key with
95
+ no description is simply one nobody has described yet; ask the owner rather
96
+ than inferring a purpose from the name.
89
97
 
90
98
  ## Things that will waste your time
91
99
 
@@ -22,6 +22,31 @@ background and lives until the session ends or you stop it.
22
22
  second one, so it is safe to repeat.
23
23
  - Start the server FIRST. A URL for a port nothing is listening on answers
24
24
  with an error, which reads to the user like a broken tunnel.
25
+ - The URL is HTTPS. `http://` works too, on a different path through the Mini's
26
+ nginx, so prefer the https one you were given.
27
+
28
+ ## Sharing an app, not just a port
29
+
30
+ A web app usually needs two tunnels, and its own config has to name them before
31
+ it is built or booted. A client that still points at `localhost:5001` loads over
32
+ HTTPS and then has every API call blocked as mixed content, which looks like a
33
+ broken deploy rather than a config miss.
34
+
35
+ So: expose both ports first, put those URLs in the app's config (for this repo,
36
+ `NEXT_PUBLIC_SITE_URL` / `NEXT_PUBLIC_API_URL` / `ALLOWED_ORIGINS` in `.env`),
37
+ and only then start the servers. Getting that order wrong costs a restart of
38
+ both.
39
+
40
+ Two more `.env` values matter once the app has logins, and both fail silently:
41
+
42
+ - `COOKIE_DOMAIN` — the two tunnels are different hostnames under one parent, so
43
+ a host-only cookie set on the web host is never sent to the api host. Every
44
+ authenticated call 401s while the UI looks signed in.
45
+ - `NEXT_PUBLIC_COOKIE_PREFIX` — must differ from production's. A preview under
46
+ `*.dev.factiii.com` also receives cookies scoped to `.factiii.com`, so anyone
47
+ logged into the real site sends a same-named cookie that shadows the
48
+ preview's, and signing in simply does not stick. `.env.example` already ships
49
+ a distinct value; keep it distinct.
25
50
 
26
51
  ## Stop sharing
27
52
 
@@ -36,6 +61,12 @@ whatever that port serves. Do not expose a service that fronts real
36
61
  credentials, customer data, or a database. If you are unsure whether the user
37
62
  wants something reachable from outside, ask first.
38
63
 
39
- Always tell the user the URL you got back. They can also see every live
40
- tunnel, and stop any of them, in the card's Task Manager panel.
64
+ Always tell the user the URL you got back.
65
+
66
+ They can also see it themselves, in the card's **Tasks** panel — the button in
67
+ the session header, which lists what the card is running and which ports are
68
+ public. Point them there by that name. **Setup**, the button beside it, is a
69
+ different thing: a fixed log of how the workspace was prepared, which never
70
+ shows running servers. Saying "the task manager" or leaving it unnamed sends
71
+ people to Setup and looks like the tunnel failed.
41
72