minimal-forge-work-pack-sync 0.1.49 → 0.1.53

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.js +507 -326
  2. package/dist/repair.js +223 -69
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -7374,63 +7374,6 @@ var require_dist = __commonJS({
7374
7374
  var import_yaml = __toESM(require_dist(), 1);
7375
7375
  import { readFile, readdir } from "node:fs/promises";
7376
7376
  import path from "node:path";
7377
- async function managedProjectionNames(paths) {
7378
- const agents = /* @__PURE__ */ new Set();
7379
- const commands = /* @__PURE__ */ new Set();
7380
- const entries = await readdir(paths.skillsDir, { withFileTypes: true }).catch((error45) => {
7381
- if (error45.code === "ENOENT") return [];
7382
- throw error45;
7383
- });
7384
- for (const entry of entries) {
7385
- if (!entry.isDirectory()) continue;
7386
- const folder = path.join(paths.skillsDir, entry.name);
7387
- const marker = await readFile(path.join(folder, ".forge-version"), "utf8").catch(() => "");
7388
- if (!marker.trim()) continue;
7389
- for (const name of await readProjectionRecord(path.join(folder, ".forge-agents"))) agents.add(stripMarkdownExtension(name));
7390
- for (const name of await readProjectionRecord(path.join(folder, ".forge-commands"))) commands.add(stripMarkdownExtension(name));
7391
- }
7392
- return { agents, commands };
7393
- }
7394
- async function readProjectionRecord(filePath) {
7395
- const raw = await readFile(filePath, "utf8").catch(() => "");
7396
- return raw.split("\n").map((line) => line.trim()).filter(
7397
- (line) => line.endsWith(".md") && !line.includes("/") && !line.includes("\\") && line !== ".."
7398
- );
7399
- }
7400
- async function projectCurrentExtensions(config2, state) {
7401
- const agents = objectRecord(config2.agent);
7402
- const commands = objectRecord(config2.command);
7403
- for (const name of state.before.agents) if (!state.after.agents.has(name)) delete agents[name];
7404
- for (const name of state.before.commands) if (!state.after.commands.has(name)) delete commands[name];
7405
- for (const name of state.after.agents) {
7406
- agents[name] = await parseMarkdownConfig(path.join(state.paths.agentsDir, `${name}.md`), "prompt");
7407
- }
7408
- for (const name of state.after.commands) {
7409
- commands[name] = await parseMarkdownConfig(path.join(state.paths.commandsDir, `${name}.md`), "template");
7410
- }
7411
- config2.agent = agents;
7412
- config2.command = commands;
7413
- }
7414
- async function parseMarkdownConfig(filePath, bodyField) {
7415
- const raw = await readFile(filePath, "utf8");
7416
- const match = /^---\r?\n([\s\S]+?)\r?\n---\r?\n?([\s\S]*)$/.exec(raw);
7417
- if (!match) throw new Error(`A extens\xE3o Forge ${path.basename(filePath)} n\xE3o tem frontmatter v\xE1lido`);
7418
- const data = (0, import_yaml.parse)(match[1]);
7419
- if (!data || typeof data !== "object" || Array.isArray(data)) {
7420
- throw new Error(`A extens\xE3o Forge ${path.basename(filePath)} n\xE3o tem frontmatter v\xE1lido`);
7421
- }
7422
- const config2 = { ...data, [bodyField]: match[2].trim() };
7423
- if (bodyField === "prompt" && typeof config2.permission === "string" && ["allow", "ask", "deny"].includes(config2.permission)) {
7424
- config2.permission = { "*": config2.permission };
7425
- }
7426
- return config2;
7427
- }
7428
- function objectRecord(value) {
7429
- return value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
7430
- }
7431
- function stripMarkdownExtension(filename) {
7432
- return filename.slice(0, -3);
7433
- }
7434
7377
 
7435
7378
  // packages/shared/src/contracts/models.ts
7436
7379
  var BUILT_IN_OPENROUTER_MODELS = [
@@ -7672,7 +7615,7 @@ var WORKER_FEEDBACK_MAX_MESSAGE_LENGTH = 24e3;
7672
7615
  // packages/shared/src/contracts/settings.ts
7673
7616
  var DOCUMENT_READER_AGENT = "document-reader";
7674
7617
  var OPENROUTER_ALIAS_PROVIDER_NAME = "OpenRouter (via Forge)";
7675
- var WORK_PACK_SYNC_PLUGIN_VERSION = "0.1.49";
7618
+ var WORK_PACK_SYNC_PLUGIN_VERSION = "0.1.53";
7676
7619
  var WORK_PACK_SYNC_PLUGIN_PACKAGE = `minimal-forge-work-pack-sync@${WORK_PACK_SYNC_PLUGIN_VERSION}`;
7677
7620
  var WORK_PACK_SYNC_PLUGIN_FILENAME = `minimal-forge-work-pack-sync-${WORK_PACK_SYNC_PLUGIN_VERSION}.tgz`;
7678
7621
  var FIRECRAWL_KEYLESS_MCP_NAME = "firecrawl";
@@ -7900,6 +7843,90 @@ function integrityKind(summary) {
7900
7843
  return "match";
7901
7844
  }
7902
7845
 
7846
+ // packages/cli/src/workPackExtensions.ts
7847
+ async function managedProjectionNames(paths, slugs) {
7848
+ const agents = /* @__PURE__ */ new Set();
7849
+ const commands = /* @__PURE__ */ new Set();
7850
+ if (slugs?.size === 0) return { agents, commands };
7851
+ const entries = await readdir(paths.skillsDir, { withFileTypes: true }).catch((error45) => {
7852
+ if (error45.code === "ENOENT") return [];
7853
+ throw error45;
7854
+ });
7855
+ for (const entry of entries) {
7856
+ if (!entry.isDirectory() || slugs && !slugs.has(entry.name)) continue;
7857
+ const folder = path.join(paths.skillsDir, entry.name);
7858
+ const marker = await readFile(path.join(folder, ".forge-version"), "utf8").catch(() => "");
7859
+ if (!marker.trim()) continue;
7860
+ for (const name of await readProjectionRecord(path.join(folder, ".forge-agents"))) agents.add(stripMarkdownExtension(name));
7861
+ for (const name of await readProjectionRecord(path.join(folder, ".forge-commands"))) commands.add(stripMarkdownExtension(name));
7862
+ }
7863
+ return { agents, commands };
7864
+ }
7865
+ async function readProjectionRecord(filePath) {
7866
+ const raw = await readFile(filePath, "utf8").catch(() => "");
7867
+ return raw.split("\n").map((line) => line.trim()).filter(
7868
+ (line) => line.endsWith(".md") && !line.includes("/") && !line.includes("\\") && line !== ".."
7869
+ );
7870
+ }
7871
+ async function projectCurrentExtensions(config2, state) {
7872
+ const agents = objectRecord(config2.agent);
7873
+ const commands = objectRecord(config2.command);
7874
+ for (const name of state.before.agents) if (!state.after.agents.has(name)) delete agents[name];
7875
+ for (const name of state.before.commands) if (!state.after.commands.has(name)) delete commands[name];
7876
+ for (const name of state.after.agents) {
7877
+ agents[name] = await parseMarkdownConfig(path.join(state.paths.agentsDir, `${name}.md`), "prompt");
7878
+ }
7879
+ for (const name of state.after.commands) {
7880
+ commands[name] = await parseMarkdownConfig(path.join(state.paths.commandsDir, `${name}.md`), "template");
7881
+ }
7882
+ config2.agent = agents;
7883
+ config2.command = commands;
7884
+ }
7885
+ async function refreshPartialProjections(config2, previous, paths, before, result) {
7886
+ const existing = objectRecord(previous);
7887
+ const agents = objectRecord(existing.agent);
7888
+ const commands = objectRecord(existing.command);
7889
+ if (!before.agents.has(DOCUMENT_READER_AGENT)) delete agents[DOCUMENT_READER_AGENT];
7890
+ for (const file2 of result.removedManagedPaths) {
7891
+ if (path.extname(file2) !== ".md") continue;
7892
+ const directory = path.dirname(file2);
7893
+ const name = path.basename(file2, ".md");
7894
+ if (directory === paths.agentsDir) delete agents[name];
7895
+ if (directory === paths.commandsDir) delete commands[name];
7896
+ }
7897
+ config2.agent = { ...objectRecord(config2.agent), ...agents };
7898
+ config2.command = commands;
7899
+ const confirmed = new Set(result.workPacks.outcomes.filter(
7900
+ ({ action, status }) => action === "install" && (status === "installed" || status === "unchanged")
7901
+ ).map(({ slug }) => slug));
7902
+ await projectInstalledExtensions(config2, paths, confirmed);
7903
+ }
7904
+ async function parseMarkdownConfig(filePath, bodyField) {
7905
+ const raw = await readFile(filePath, "utf8");
7906
+ const match = /^---\r?\n([\s\S]+?)\r?\n---\r?\n?([\s\S]*)$/.exec(raw);
7907
+ if (!match) throw new Error(`A extens\xE3o Forge ${path.basename(filePath)} n\xE3o tem frontmatter v\xE1lido`);
7908
+ const data = (0, import_yaml.parse)(match[1]);
7909
+ if (!data || typeof data !== "object" || Array.isArray(data)) {
7910
+ throw new Error(`A extens\xE3o Forge ${path.basename(filePath)} n\xE3o tem frontmatter v\xE1lido`);
7911
+ }
7912
+ const config2 = { ...data, [bodyField]: match[2].trim() };
7913
+ if (bodyField === "prompt" && typeof config2.permission === "string" && ["allow", "ask", "deny"].includes(config2.permission)) {
7914
+ config2.permission = { "*": config2.permission };
7915
+ }
7916
+ return config2;
7917
+ }
7918
+ function objectRecord(value) {
7919
+ return value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
7920
+ }
7921
+ function stripMarkdownExtension(filename) {
7922
+ return filename.slice(0, -3);
7923
+ }
7924
+ async function projectInstalledExtensions(config2, paths, slugs) {
7925
+ const names = await managedProjectionNames(paths, slugs);
7926
+ await projectCurrentExtensions(config2, { paths, before: names, after: names });
7927
+ for (const key of ["agent", "command"]) if (Object.keys(objectRecord(config2[key])).length === 0) delete config2[key];
7928
+ }
7929
+
7903
7930
  // packages/cli/src/runtimeObservation.ts
7904
7931
  var UNKNOWN_RUNTIME = {
7905
7932
  opencode: { status: "unknown" },
@@ -8042,7 +8069,7 @@ async function writeOwnerOnlyTextAtomic(filePath, content, options = {}) {
8042
8069
  }
8043
8070
 
8044
8071
  // packages/cli/src/workPackSyncPlugin.ts
8045
- import { createHash as createHash7, randomUUID as randomUUID4 } from "node:crypto";
8072
+ import { createHash as createHash7, randomUUID as randomUUID5 } from "node:crypto";
8046
8073
  import { pathToFileURL } from "node:url";
8047
8074
 
8048
8075
  // packages/cli/src/skillUsageReporter.ts
@@ -21113,7 +21140,7 @@ function isRecord2(value) {
21113
21140
  }
21114
21141
 
21115
21142
  // packages/cli/src/workPackSyncPlugin.ts
21116
- import { link, mkdir as mkdir7, mkdtemp as mkdtemp2, readdir as readdir6, readFile as readFile13, realpath as realpath2, rename as rename8, rm as rm6, rmdir, stat as stat3, unlink, writeFile as writeFile8 } from "node:fs/promises";
21143
+ import { link, mkdir as mkdir8, mkdtemp as mkdtemp2, readdir as readdir7, readFile as readFile14, realpath as realpath2, rename as rename9, rm as rm6, rmdir as rmdir2, stat as stat3, unlink as unlink2, writeFile as writeFile9 } from "node:fs/promises";
21117
21144
  import os5 from "node:os";
21118
21145
  import path14 from "node:path";
21119
21146
 
@@ -21564,9 +21591,9 @@ function assertSlug(slug) {
21564
21591
  // packages/cli/src/sync.ts
21565
21592
  import { createHash as createHash4 } from "node:crypto";
21566
21593
  import { spawnSync } from "node:child_process";
21567
- import { chmod as chmod4, cp, lstat as lstat5, mkdtemp, mkdir as mkdir5, readdir as readdir4, readFile as readFile8, rm as rm4, rename as rename6, writeFile as writeFile6 } from "node:fs/promises";
21594
+ import { chmod as chmod4, cp, lstat as lstat5, mkdtemp, mkdir as mkdir6, readdir as readdir5, readFile as readFile9, rm as rm4, rename as rename7, writeFile as writeFile7 } from "node:fs/promises";
21568
21595
  import os4 from "node:os";
21569
- import path9 from "node:path";
21596
+ import path10 from "node:path";
21570
21597
 
21571
21598
  // node_modules/tar/dist/esm/index.min.js
21572
21599
  import Qr from "events";
@@ -24546,9 +24573,98 @@ function renderTuiConfig(manifest) {
24546
24573
  }
24547
24574
 
24548
24575
  // packages/cli/src/coreSyncTransaction.ts
24549
- import { createHash as createHash3, randomUUID as randomUUID3 } from "node:crypto";
24550
- import { chmod as chmod3, lstat as lstat4, mkdir as mkdir4, readFile as readFile5, rename as rename5, rm as rm3, writeFile as writeFile5 } from "node:fs/promises";
24576
+ import { createHash as createHash3, randomUUID as randomUUID4 } from "node:crypto";
24577
+ import { chmod as chmod3, lstat as lstat4, mkdir as mkdir5, readFile as readFile6, rename as rename6, rm as rm3, writeFile as writeFile6 } from "node:fs/promises";
24578
+ import path8 from "node:path";
24579
+
24580
+ // packages/cli/src/coreSyncLock.ts
24581
+ import { randomUUID as randomUUID3 } from "node:crypto";
24582
+ import { mkdir as mkdir4, readdir as readdir4, readFile as readFile5, rename as rename5, rmdir, unlink, writeFile as writeFile5 } from "node:fs/promises";
24583
+ import { hostname as hostname3 } from "node:os";
24551
24584
  import path7 from "node:path";
24585
+ function hasCode(error45, ...codes) {
24586
+ return error45 instanceof Error && codes.includes(error45.code ?? "");
24587
+ }
24588
+ function busy() {
24589
+ return new Error("Outra sincroniza\xE7\xE3o Forge pode estar em curso. Aguarde que termine e volte a tentar.");
24590
+ }
24591
+ function unknownOwner() {
24592
+ return new Error("O propriet\xE1rio do bloqueio de sincroniza\xE7\xE3o Forge n\xE3o foi confirmado nesta m\xE1quina. Pe\xE7a ao operador para verificar o processo e a m\xE1quina de origem.");
24593
+ }
24594
+ async function removeEmpty(directory) {
24595
+ try {
24596
+ await rmdir(directory);
24597
+ } catch (error45) {
24598
+ if (!hasCode(error45, "ENOENT", "EEXIST", "ENOTEMPTY")) throw error45;
24599
+ }
24600
+ }
24601
+ async function reclaim(lockPath, renameError) {
24602
+ let entries;
24603
+ try {
24604
+ entries = await readdir4(lockPath);
24605
+ } catch (error45) {
24606
+ if (!hasCode(error45, "ENOENT")) throw error45;
24607
+ if (hasCode(renameError, "EACCES", "EPERM")) throw renameError;
24608
+ return;
24609
+ }
24610
+ if (entries.length) {
24611
+ const marker = entries[0];
24612
+ const match = /^owner-([1-9]\d*)-[0-9a-f-]{36}$/.exec(marker);
24613
+ if (entries.length !== 1 || !match) throw unknownOwner();
24614
+ const markerPath = path7.join(lockPath, marker);
24615
+ let host;
24616
+ try {
24617
+ host = await readFile5(markerPath, "utf8");
24618
+ } catch (error45) {
24619
+ if (hasCode(error45, "ENOENT")) return;
24620
+ throw error45;
24621
+ }
24622
+ if (host !== hostname3()) throw unknownOwner();
24623
+ try {
24624
+ process.kill(Number(match[1]), 0);
24625
+ } catch (error45) {
24626
+ if (!hasCode(error45, "ESRCH")) throw error45;
24627
+ await unlink(markerPath).catch((cause) => {
24628
+ if (!hasCode(cause, "ENOENT")) throw cause;
24629
+ });
24630
+ await removeEmpty(lockPath);
24631
+ return;
24632
+ }
24633
+ throw busy();
24634
+ }
24635
+ await removeEmpty(lockPath);
24636
+ }
24637
+ async function withCoreSyncLock(journalPath, operation) {
24638
+ const lockPath = journalPath + ".lock";
24639
+ const id = randomUUID3();
24640
+ const candidate = lockPath + "-" + id;
24641
+ const marker = `owner-${process.pid}-${id}`;
24642
+ await mkdir4(path7.dirname(lockPath), { recursive: true });
24643
+ await mkdir4(candidate, { mode: 448 });
24644
+ let directory = candidate;
24645
+ try {
24646
+ await writeFile5(path7.join(candidate, marker), hostname3(), { mode: 384, flag: "wx" });
24647
+ for (let attempt = 0; attempt < 3; attempt++) {
24648
+ try {
24649
+ await rename5(candidate, lockPath);
24650
+ } catch (error45) {
24651
+ if (!hasCode(error45, "EEXIST", "ENOTEMPTY", "EPERM", "EACCES")) throw error45;
24652
+ await reclaim(lockPath, error45);
24653
+ continue;
24654
+ }
24655
+ directory = lockPath;
24656
+ return await operation();
24657
+ }
24658
+ throw busy();
24659
+ } finally {
24660
+ await unlink(path7.join(directory, marker)).catch((error45) => {
24661
+ if (!hasCode(error45, "ENOENT")) throw error45;
24662
+ });
24663
+ await removeEmpty(directory);
24664
+ }
24665
+ }
24666
+
24667
+ // packages/cli/src/coreSyncTransaction.ts
24552
24668
  var CORE_RUNTIME_MANIFEST_VERSION = 1;
24553
24669
  var CoreSyncUncertainError = class extends Error {
24554
24670
  constructor(message, paths) {
@@ -24557,11 +24673,11 @@ var CoreSyncUncertainError = class extends Error {
24557
24673
  }
24558
24674
  paths;
24559
24675
  };
24560
- var defaultFs = { chmod: chmod3, lstat: lstat4, mkdir: mkdir4, readFile: readFile5, rename: rename5, rm: rm3, writeFile: writeFile5 };
24676
+ var defaultFs = { chmod: chmod3, lstat: lstat4, mkdir: mkdir5, readFile: readFile6, rename: rename6, rm: rm3, writeFile: writeFile6 };
24561
24677
  function coreRuntimeManifestDigest(files) {
24562
24678
  const canonical = [...files].sort((a, b2) => a.id.localeCompare(b2.id)).map((file2) => ({
24563
24679
  id: file2.id,
24564
- path: path7.resolve(file2.path),
24680
+ path: path8.resolve(file2.path),
24565
24681
  exists: file2.bytes !== null,
24566
24682
  digest: file2.bytes === null ? void 0 : sha256(file2.bytes),
24567
24683
  mode: file2.mode,
@@ -24578,8 +24694,8 @@ function validateCoreRuntimeManifest(manifest) {
24578
24694
  const targets = /* @__PURE__ */ new Set();
24579
24695
  for (const file2 of manifest.files) {
24580
24696
  if (!file2.id || ids.has(file2.id)) throw new Error(`Duplicate core runtime file id: ${file2.id}`);
24581
- const target = path7.resolve(file2.path);
24582
- if (!path7.isAbsolute(file2.path) || targets.has(target)) throw new Error(`Invalid or duplicate core runtime target: ${file2.path}`);
24697
+ const target = path8.resolve(file2.path);
24698
+ if (!path8.isAbsolute(file2.path) || targets.has(target)) throw new Error(`Invalid or duplicate core runtime target: ${file2.path}`);
24583
24699
  if (file2.mode !== void 0 && (!Number.isInteger(file2.mode) || file2.mode < 0 || file2.mode > 4095)) throw new Error(`Invalid mode for ${file2.id}`);
24584
24700
  if (file2.ownerOnly !== void 0 && typeof file2.ownerOnly !== "boolean") throw new Error(`Invalid owner-only flag for ${file2.id}`);
24585
24701
  ids.add(file2.id);
@@ -24587,19 +24703,28 @@ function validateCoreRuntimeManifest(manifest) {
24587
24703
  }
24588
24704
  if (coreRuntimeManifestDigest(manifest.files) !== manifest.digest) throw new Error("Core runtime manifest digest mismatch");
24589
24705
  }
24590
- async function applyCoreSyncTransaction(options) {
24591
- validateCoreRuntimeManifest(options.manifest);
24706
+ async function withRecoveredCoreSync(journalPath, operation, options = {}) {
24707
+ const fs2 = options.fs ?? defaultFs;
24708
+ return withCoreSyncLock(journalPath, async () => {
24709
+ const recovery = await recoverUnderLock(journalPath, fs2);
24710
+ await options.afterRecovery?.();
24711
+ if (recovery.status === "uncertain") throw new CoreSyncUncertainError(recovery.message, recovery.uncertainPaths);
24712
+ return operation((manifest, hooks) => {
24713
+ validateCoreRuntimeManifest(manifest);
24714
+ return commitCoreFiles({ manifest, journalPath, fs: fs2, hooks });
24715
+ });
24716
+ });
24717
+ }
24718
+ async function commitCoreFiles(options) {
24592
24719
  const fs2 = options.fs ?? defaultFs;
24593
24720
  const hooks = options.hooks;
24594
- const existingRecovery = await recoverCoreSyncTransaction({ journalPath: options.journalPath, fs: fs2 });
24595
- if (existingRecovery.status === "uncertain") throw new CoreSyncUncertainError(existingRecovery.message, existingRecovery.uncertainPaths);
24596
- const transactionId = randomUUID3();
24721
+ const transactionId = randomUUID4();
24597
24722
  const files = [];
24598
24723
  try {
24599
24724
  for (const desired of options.manifest.files) {
24600
- const target = path7.resolve(desired.path);
24725
+ const target = path8.resolve(desired.path);
24601
24726
  if (desired.ownerOnly && desired.bytes !== null && fs2 === defaultFs) await prepareOwnerOnlyFileDestination(target);
24602
- else await fs2.mkdir(path7.dirname(target), { recursive: true });
24727
+ else await fs2.mkdir(path8.dirname(target), { recursive: true });
24603
24728
  const original = await capture(target, fs2);
24604
24729
  const suffix = `.forge-core-${transactionId}`;
24605
24730
  const backup = original.exists ? `${target}${suffix}.backup` : void 0;
@@ -24628,58 +24753,93 @@ async function applyCoreSyncTransaction(options) {
24628
24753
  await hooks?.boundary?.("after-journal");
24629
24754
  for (const file2 of files) {
24630
24755
  await hooks?.boundary?.(`before-commit:${file2.id}`);
24631
- await fs2.rm(file2.target, { force: true });
24632
24756
  if (file2.stage) await fs2.rename(file2.stage, file2.target);
24757
+ else await fs2.rm(file2.target, { force: true });
24633
24758
  if (file2.stage && file2.ownerOnly && fs2 === defaultFs) await protectOwnerOnlyPath(file2.target, "file");
24634
24759
  await hooks?.boundary?.(`after-commit:${file2.id}`);
24635
24760
  }
24636
24761
  await hooks?.boundary?.("before-cleanup");
24637
- await cleanup(journal, options.journalPath, fs2);
24638
- await hooks?.boundary?.("after-cleanup");
24639
- return { status: "committed", manifestId: options.manifest.id, digest: options.manifest.digest };
24762
+ await fs2.rename(options.journalPath, cleanupPath(options.journalPath));
24640
24763
  } catch (error45) {
24641
24764
  if (!await exists(options.journalPath, fs2)) {
24642
24765
  await Promise.all(files.flatMap((file2) => [file2.stage, file2.backup].filter((item) => Boolean(item))).map((item) => fs2.rm(item, { force: true }).catch(() => void 0)));
24643
24766
  throw error45;
24644
24767
  }
24645
- const recovery = await recoverCoreSyncTransaction({ journalPath: options.journalPath, fs: fs2 });
24768
+ const recovery = await recoverUnderLock(options.journalPath, fs2);
24646
24769
  if (recovery.status === "uncertain") throw new CoreSyncUncertainError(recovery.message, recovery.uncertainPaths);
24647
24770
  throw error45;
24648
24771
  }
24649
- }
24650
- async function recoverCoreSyncTransaction(options) {
24651
- const fs2 = options.fs ?? defaultFs;
24652
- let journal;
24772
+ const committed = { status: "committed", manifestId: options.manifest.id, digest: options.manifest.digest };
24653
24773
  try {
24654
- journal = JSON.parse(await fs2.readFile(options.journalPath, "utf8"));
24655
- } catch (error45) {
24656
- if (isNotFound(error45)) return { status: "nothing-to-recover" };
24657
- return { status: "uncertain", uncertainPaths: [options.journalPath], message: "Core sync journal is unreadable; exact recovery is uncertain." };
24774
+ await cleanup(files, cleanupPath(options.journalPath), fs2);
24775
+ } catch {
24776
+ return committed;
24658
24777
  }
24659
- if (!validJournal(journal)) return { status: "uncertain", uncertainPaths: [options.journalPath], message: "Core sync journal is invalid; exact recovery is uncertain." };
24778
+ await hooks?.boundary?.("after-cleanup");
24779
+ return committed;
24780
+ }
24781
+ async function recoverUnderLock(activePath, fs2) {
24782
+ const retiredPath = cleanupPath(activePath);
24783
+ for (const journalPath of [retiredPath, activePath]) {
24784
+ let journal;
24785
+ try {
24786
+ journal = JSON.parse(await fs2.readFile(journalPath, "utf8"));
24787
+ if (!validJournal(journal)) throw new Error("Invalid journal");
24788
+ } catch (error45) {
24789
+ if (isNotFound(error45)) continue;
24790
+ return { status: "uncertain", uncertainPaths: [journalPath], message: "Core sync journal is unreadable or invalid; exact recovery is uncertain." };
24791
+ }
24792
+ if (journalPath === retiredPath) {
24793
+ await cleanup(journal.files, retiredPath, fs2);
24794
+ } else {
24795
+ return restoreJournal(journal, journalPath, fs2);
24796
+ }
24797
+ }
24798
+ return { status: "nothing-to-recover" };
24799
+ }
24800
+ async function restoreJournal(journal, journalPath, fs2) {
24660
24801
  const uncertain = [];
24802
+ const backups = /* @__PURE__ */ new Map();
24661
24803
  for (const file2 of journal.files) {
24804
+ if (!file2.original.exists) continue;
24662
24805
  try {
24663
- if (!file2.original.exists) await fs2.rm(file2.target, { force: true });
24664
- else {
24665
- if (!file2.backup || !await exists(file2.backup, fs2)) throw new Error("backup missing");
24666
- const bytes = await fs2.readFile(file2.backup);
24667
- if (sha256(bytes) !== file2.original.digest) throw new Error("backup digest mismatch");
24668
- await writeExact(`${file2.target}.forge-restore-${journal.transactionId}`, bytes, file2.original.mode, fs2, file2.ownerOnly === true);
24806
+ if (!file2.backup) throw new Error("backup missing");
24807
+ const bytes = await fs2.readFile(file2.backup);
24808
+ if (sha256(bytes) !== file2.original.digest) throw new Error("backup digest mismatch");
24809
+ backups.set(file2, bytes);
24810
+ } catch {
24811
+ uncertain.push(file2.target);
24812
+ }
24813
+ }
24814
+ if (uncertain.length) return uncertainRestore(journal, uncertain);
24815
+ for (const file2 of journal.files) {
24816
+ try {
24817
+ if (!file2.original.exists) {
24669
24818
  await fs2.rm(file2.target, { force: true });
24670
- await fs2.rename(`${file2.target}.forge-restore-${journal.transactionId}`, file2.target);
24671
- if (file2.ownerOnly && fs2 === defaultFs) await protectOwnerOnlyPath(file2.target, "file");
24672
- const restored = await capture(file2.target, fs2);
24673
- if (!restored.bytes || sha256(restored.bytes) !== file2.original.digest || restored.mode !== file2.original.mode) throw new Error("restore verification failed");
24819
+ continue;
24820
+ }
24821
+ const restorePath = `${file2.target}.forge-restore-${journal.transactionId}`;
24822
+ await fs2.rm(restorePath, { force: true });
24823
+ await writeExact(restorePath, backups.get(file2), file2.original.mode, fs2, file2.ownerOnly);
24824
+ await fs2.rename(restorePath, file2.target);
24825
+ if (file2.ownerOnly && fs2 === defaultFs) await protectOwnerOnlyPath(file2.target, "file");
24826
+ const restored = await capture(file2.target, fs2);
24827
+ if (!restored.bytes || sha256(restored.bytes) !== file2.original.digest || restored.mode !== effectiveMode(file2.original.mode, file2.ownerOnly)) {
24828
+ throw new Error("restore verification failed");
24674
24829
  }
24675
24830
  } catch {
24676
24831
  uncertain.push(file2.target);
24677
24832
  }
24678
24833
  }
24679
- if (uncertain.length > 0) return { status: "uncertain", manifestId: journal.manifest.id, uncertainPaths: uncertain, message: "Core sync could not prove an exact restore for every path." };
24680
- await cleanup(journal, options.journalPath, fs2);
24834
+ if (uncertain.length) return uncertainRestore(journal, uncertain);
24835
+ const retiredPath = cleanupPath(journalPath);
24836
+ await fs2.rename(journalPath, retiredPath);
24837
+ await cleanup(journal.files, retiredPath, fs2);
24681
24838
  return { status: "restored", manifestId: journal.manifest.id };
24682
24839
  }
24840
+ function uncertainRestore(journal, paths) {
24841
+ return { status: "uncertain", manifestId: journal.manifest.id, uncertainPaths: paths, message: "Core sync could not prove an exact restore for every path." };
24842
+ }
24683
24843
  async function capture(target, fs2) {
24684
24844
  try {
24685
24845
  const info = await fs2.lstat(target);
@@ -24690,13 +24850,17 @@ async function capture(target, fs2) {
24690
24850
  throw error45;
24691
24851
  }
24692
24852
  }
24853
+ function effectiveMode(mode, ownerOnly = false) {
24854
+ return ownerOnly && process.platform !== "win32" ? 384 : mode;
24855
+ }
24693
24856
  async function writeExact(target, bytes, mode, fs2, ownerOnly = false) {
24694
- await fs2.writeFile(target, bytes, { flag: "wx", mode });
24695
- await fs2.chmod(target, mode);
24857
+ const permissions = effectiveMode(mode, ownerOnly);
24858
+ await fs2.writeFile(target, bytes, { flag: "wx", mode: permissions });
24859
+ await fs2.chmod(target, permissions);
24696
24860
  if (ownerOnly && fs2 === defaultFs) await protectOwnerOnlyPath(target, "file");
24697
24861
  }
24698
24862
  async function writeJournal(target, journal, fs2) {
24699
- await fs2.mkdir(path7.dirname(target), { recursive: true });
24863
+ await fs2.mkdir(path8.dirname(target), { recursive: true });
24700
24864
  const temporary = `${target}.next`;
24701
24865
  await fs2.rm(temporary, { force: true });
24702
24866
  await fs2.writeFile(temporary, `${JSON.stringify(journal, null, 2)}
@@ -24704,8 +24868,14 @@ async function writeJournal(target, journal, fs2) {
24704
24868
  await fs2.chmod(temporary, 384);
24705
24869
  await fs2.rename(temporary, target);
24706
24870
  }
24707
- async function cleanup(journal, journalPath, fs2) {
24708
- await Promise.all(journal.files.flatMap((file2) => [file2.stage, file2.backup].filter((item) => Boolean(item))).map((item) => fs2.rm(item, { force: true })));
24871
+ function cleanupPath(journalPath) {
24872
+ return `${journalPath}.cleanup`;
24873
+ }
24874
+ async function cleanup(files, journalPath, fs2) {
24875
+ for (const file2 of files) {
24876
+ if (file2.stage) await fs2.rm(file2.stage, { force: true });
24877
+ if (file2.backup) await fs2.rm(file2.backup, { force: true });
24878
+ }
24709
24879
  await fs2.rm(journalPath, { force: true });
24710
24880
  }
24711
24881
  async function exists(target, fs2) {
@@ -24724,7 +24894,12 @@ function sha256(value) {
24724
24894
  return createHash3("sha256").update(value).digest("hex");
24725
24895
  }
24726
24896
  function validJournal(value) {
24727
- return value?.schemaVersion === 1 && typeof value.transactionId === "string" && value.manifest?.version === 1 && typeof value.manifest.id === "string" && Array.isArray(value.files) && value.files.every((file2) => typeof file2.id === "string" && path7.isAbsolute(file2.target) && typeof file2.original?.exists === "boolean" && typeof file2.desired?.exists === "boolean" && (file2.ownerOnly === void 0 || typeof file2.ownerOnly === "boolean"));
24897
+ if (value?.schemaVersion !== 1 || typeof value.transactionId !== "string" || !/^[a-zA-Z0-9_-]+$/.test(value.transactionId) || value.manifest?.version !== 1 || typeof value.manifest.id !== "string" || !Array.isArray(value.files)) return false;
24898
+ return value.files.every((file2) => {
24899
+ if (typeof file2?.id !== "string" || typeof file2.target !== "string" || !path8.isAbsolute(file2.target)) return false;
24900
+ const prefix = `${file2.target}.forge-core-${value.transactionId}`;
24901
+ return (file2.stage === void 0 || file2.stage === `${prefix}.stage`) && (file2.backup === void 0 || file2.backup === `${prefix}.backup`) && typeof file2.original?.exists === "boolean" && typeof file2.desired?.exists === "boolean" && (file2.ownerOnly === void 0 || typeof file2.ownerOnly === "boolean");
24902
+ });
24728
24903
  }
24729
24904
 
24730
24905
  // packages/cli/src/jsonc.ts
@@ -24803,7 +24978,7 @@ function stripTrailingCommas(input) {
24803
24978
  }
24804
24979
 
24805
24980
  // packages/cli/src/remoteConfig.ts
24806
- import { readFile as readFile6 } from "node:fs/promises";
24981
+ import { readFile as readFile7 } from "node:fs/promises";
24807
24982
  var WELLKNOWN_ENV_KEY = "FORGE_API_KEY";
24808
24983
  async function removeWellKnownAuth(paths, credentials, previous) {
24809
24984
  const content = await prepareWellKnownAuthRemoval(paths, credentials, previous);
@@ -24861,7 +25036,7 @@ function normalizeBaseUrl(value) {
24861
25036
  async function readAuthJson(paths) {
24862
25037
  let raw;
24863
25038
  try {
24864
- raw = await readFile6(paths.opencodeAuthPath, "utf8");
25039
+ raw = await readFile7(paths.opencodeAuthPath, "utf8");
24865
25040
  } catch (error45) {
24866
25041
  if (error45.code === "ENOENT") return {};
24867
25042
  throw error45;
@@ -24875,21 +25050,21 @@ function isRecord3(value) {
24875
25050
  }
24876
25051
 
24877
25052
  // packages/cli/src/localConfigRecovery.ts
24878
- import { readFile as readFile7 } from "node:fs/promises";
24879
- import path8 from "node:path";
25053
+ import { readFile as readFile8 } from "node:fs/promises";
25054
+ import path9 from "node:path";
24880
25055
  var LocalConfigRecoveryError = class extends Error {
24881
25056
  };
24882
25057
  var LAST_GOOD_FILENAME = "last-good-opencode.json";
24883
25058
  function lastGoodLocalConfigFile(paths, credentials, content) {
24884
25059
  assertForgeConfig(content, credentials);
24885
- return { id: "last-good-config", path: path8.join(paths.forgeDir, LAST_GOOD_FILENAME), bytes: Buffer.from(content), mode: 384, ownerOnly: true };
25060
+ return { id: "last-good-config", path: path9.join(paths.forgeDir, LAST_GOOD_FILENAME), bytes: Buffer.from(content), mode: 384, ownerOnly: true };
24886
25061
  }
24887
25062
  async function retiredLastGoodLocalConfigFile(paths) {
24888
- const filePath = path8.join(paths.forgeDir, LAST_GOOD_FILENAME);
25063
+ const filePath = path9.join(paths.forgeDir, LAST_GOOD_FILENAME);
24889
25064
  return await readOptional(filePath) === void 0 ? void 0 : { id: "last-good-config", path: filePath, bytes: null };
24890
25065
  }
24891
25066
  async function inspectLocalConfigRecovery(paths, credentials) {
24892
- const snapshot = await readOptional(path8.join(paths.forgeDir, LAST_GOOD_FILENAME));
25067
+ const snapshot = await readOptional(path9.join(paths.forgeDir, LAST_GOOD_FILENAME));
24893
25068
  const current = await readOptional(paths.opencodeConfigPath);
24894
25069
  return {
24895
25070
  snapshot: snapshot === void 0 ? "missing" : isForgeConfig(snapshot, credentials) ? "available" : "invalid",
@@ -24932,7 +25107,7 @@ function forgePluginEntries(config2) {
24932
25107
  }
24933
25108
  async function readOptional(filePath) {
24934
25109
  try {
24935
- return await readFile7(filePath, "utf8");
25110
+ return await readFile8(filePath, "utf8");
24936
25111
  } catch (error45) {
24937
25112
  if (error45.code === "ENOENT") return void 0;
24938
25113
  throw error45;
@@ -25208,24 +25383,24 @@ function validCoreManifest(value) {
25208
25383
  return modelIds.every((id) => typeof id === "string" && id.length > 0) && modelIds.includes(config2.model) && modelIds.includes(config2.small_model);
25209
25384
  }
25210
25385
  async function applyManifest(paths, credentials, manifest, options = {}) {
25211
- const journalPath = path9.join(paths.forgeDir, "core-sync-journal.json");
25212
- const recovery = await recoverCoreSyncTransaction({ journalPath });
25213
- await retireDebugCapture(paths);
25214
- if (recovery.status === "uncertain") {
25215
- throw new CoreSyncUncertainError(recovery.message, recovery.uncertainPaths);
25216
- }
25217
- await mkdir5(paths.opencodeDir, { recursive: true });
25386
+ const journalPath = path10.join(paths.forgeDir, "core-sync-journal.json");
25218
25387
  return reconcileSyncSnapshot({
25219
- applyCore: () => applyCoreManifest(paths, credentials, manifest, options),
25388
+ applyCore: () => withRecoveredCoreSync(
25389
+ journalPath,
25390
+ (apply) => applyCoreManifest(paths, credentials, manifest, options, apply),
25391
+ { afterRecovery: () => retireDebugCapture(paths) }
25392
+ ),
25220
25393
  applyWorkPacks: () => applyWorkPackManifest(paths, credentials, manifest, options)
25221
25394
  });
25222
25395
  }
25223
- async function applyCoreManifest(paths, credentials, manifest, options) {
25224
- const attachmentPluginPath = path9.join(paths.pluginDir, FORGE_PLUGIN_FILENAME);
25225
- const evidencePluginPath = path9.join(paths.pluginDir, FORGE_EVIDENCE_PLUGIN_FILENAME);
25226
- const debugTracePluginPath = path9.join(paths.pluginDir, FORGE_DEBUG_TRACE_PLUGIN_FILENAME);
25227
- const legacyAttachmentPluginPath = path9.join(paths.opencodeDir, "plugin", FORGE_PLUGIN_FILENAME);
25228
- const debugTraceConfigPath = path9.join(paths.forgeDir, FORGE_DEBUG_TRACE_CONFIG_FILENAME);
25396
+ async function applyCoreManifest(paths, credentials, manifest, options, apply) {
25397
+ await options.beforeCore?.();
25398
+ await mkdir6(paths.opencodeDir, { recursive: true });
25399
+ const attachmentPluginPath = path10.join(paths.pluginDir, FORGE_PLUGIN_FILENAME);
25400
+ const evidencePluginPath = path10.join(paths.pluginDir, FORGE_EVIDENCE_PLUGIN_FILENAME);
25401
+ const debugTracePluginPath = path10.join(paths.pluginDir, FORGE_DEBUG_TRACE_PLUGIN_FILENAME);
25402
+ const legacyAttachmentPluginPath = path10.join(paths.opencodeDir, "plugin", FORGE_PLUGIN_FILENAME);
25403
+ const debugTraceConfigPath = path10.join(paths.forgeDir, FORGE_DEBUG_TRACE_CONFIG_FILENAME);
25229
25404
  const rules = attachmentBridgeRules(manifest.config.models);
25230
25405
  let bridgeEnabled = Boolean(manifest.config.documentReaderModel) && Object.keys(rules).length > 0;
25231
25406
  const existingConfig = await readJsoncObject(paths.opencodeConfigPath);
@@ -25297,28 +25472,25 @@ async function applyCoreManifest(paths, credentials, manifest, options) {
25297
25472
  if (retired) files.push(retired);
25298
25473
  }
25299
25474
  const digest2 = coreRuntimeManifestDigest(files);
25300
- await applyCoreSyncTransaction({
25301
- manifest: {
25302
- version: 1,
25303
- id: `derived:${digest2.slice(0, 32)}`,
25304
- digest: digest2,
25305
- files
25306
- },
25307
- journalPath: path9.join(paths.forgeDir, "core-sync-journal.json"),
25308
- hooks: options.coreTransactionHooks
25309
- });
25475
+ await apply({
25476
+ version: 1,
25477
+ id: `derived:${digest2.slice(0, 32)}`,
25478
+ digest: digest2,
25479
+ files
25480
+ }, options.coreTransactionHooks);
25310
25481
  await removeLegacyDebugTraceRuntime(paths);
25482
+ await options.afterCore?.();
25311
25483
  return { configPath: paths.opencodeConfigPath, tuiPath: paths.tuiConfigPath };
25312
25484
  }
25313
25485
  async function applyWorkPackManifest(paths, credentials, manifest, options) {
25314
- await mkdir5(paths.skillsDir, { recursive: true });
25315
- await mkdir5(paths.commandsDir, { recursive: true });
25486
+ await mkdir6(paths.skillsDir, { recursive: true });
25487
+ await mkdir6(paths.commandsDir, { recursive: true });
25316
25488
  const recovery = await recoverInterruptedWorkPackInstalls(paths, options.cleanupWorkPackBackup, options.workPackProjectionBoundary);
25317
25489
  const managed = await Promise.all((await managedWorkPackSlugs(paths.skillsDir)).map(async (slug) => ({
25318
25490
  slug,
25319
- version: (await readFile8(path9.join(paths.skillsDir, slug, ".forge-version"), "utf8")).trim(),
25320
- agents: await readAgentRecord(path9.join(paths.skillsDir, slug)),
25321
- commands: await readCommandRecord(path9.join(paths.skillsDir, slug))
25491
+ version: (await readFile9(path10.join(paths.skillsDir, slug, ".forge-version"), "utf8")).trim(),
25492
+ agents: await readAgentRecord(path10.join(paths.skillsDir, slug)),
25493
+ commands: await readCommandRecord(path10.join(paths.skillsDir, slug))
25322
25494
  })));
25323
25495
  const desired = manifest.skills.map((skill) => ({
25324
25496
  slug: skill.slug,
@@ -25342,7 +25514,7 @@ async function applyWorkPackManifest(paths, credentials, manifest, options) {
25342
25514
  options
25343
25515
  )),
25344
25516
  recoveryFailures: recovery.failures,
25345
- writeAtomicReceipt: (receipt) => writeJsonAtomic2(path9.join(paths.forgeDir, "work-pack-sync-receipt.json"), receipt)
25517
+ writeAtomicReceipt: (receipt) => writeJsonAtomic2(path10.join(paths.forgeDir, "work-pack-sync-receipt.json"), receipt)
25346
25518
  });
25347
25519
  const installed = workPacks.outcomes.filter((outcome) => outcome.status === "installed").map((outcome) => `${outcome.slug}@${outcome.version}`);
25348
25520
  const removed = workPacks.outcomes.filter((outcome) => outcome.status === "removed").map((outcome) => outcome.slug);
@@ -25353,7 +25525,7 @@ async function applyWorkPackManifest(paths, credentials, manifest, options) {
25353
25525
  async function collectWorkPackObservations(paths, reconciliation) {
25354
25526
  const installedVersions = /* @__PURE__ */ new Map();
25355
25527
  for (const slug of await managedWorkPackSlugs(paths.skillsDir)) {
25356
- const version2 = (await readFile8(path9.join(paths.skillsDir, slug, ".forge-version"), "utf8")).trim();
25528
+ const version2 = (await readFile9(path10.join(paths.skillsDir, slug, ".forge-version"), "utf8")).trim();
25357
25529
  if (version2) installedVersions.set(slug, version2);
25358
25530
  }
25359
25531
  const observations = new Map(
@@ -25384,7 +25556,7 @@ async function enrichIntegrityFailure(paths, operation, result) {
25384
25556
  }
25385
25557
  }
25386
25558
  async function operateWorkPack(paths, credentials, skillBySlug, approvedModelIds, cleanupPendingSlugs, recoveryFailures, operation, options) {
25387
- const target = path9.join(paths.skillsDir, operation.pack.slug);
25559
+ const target = path10.join(paths.skillsDir, operation.pack.slug);
25388
25560
  const recoveryFailure = recoveryFailures.get(operation.pack.slug);
25389
25561
  if (recoveryFailure) return { status: "failed", restoration: "exact", code: recoveryFailure };
25390
25562
  let ownership;
@@ -25423,7 +25595,7 @@ async function operateWorkPack(paths, credentials, skillBySlug, approvedModelIds
25423
25595
  let previousManagedPaths;
25424
25596
  let archive;
25425
25597
  try {
25426
- const currentVersion = await readFile8(path9.join(target, ".forge-version"), "utf8").catch(() => "");
25598
+ const currentVersion = await readFile9(path10.join(target, ".forge-version"), "utf8").catch(() => "");
25427
25599
  const sameVersion = currentVersion.trim() === skill.version;
25428
25600
  if (ownership === "managed") {
25429
25601
  let localState = await checkWorkPackInstalledState({
@@ -25534,8 +25706,8 @@ function jsonBytes(value) {
25534
25706
  `);
25535
25707
  }
25536
25708
  async function removeLegacyDebugTraceRuntime(paths) {
25537
- const launchAgentPath = path9.join(os4.homedir(), "Library", "LaunchAgents", "com.minimal-forge.debug-trace.plist");
25538
- const launchAgent = await readFile8(launchAgentPath, "utf8").catch((error45) => {
25709
+ const launchAgentPath = path10.join(os4.homedir(), "Library", "LaunchAgents", "com.minimal-forge.debug-trace.plist");
25710
+ const launchAgent = await readFile9(launchAgentPath, "utf8").catch((error45) => {
25539
25711
  if (error45.code === "ENOENT") return void 0;
25540
25712
  throw error45;
25541
25713
  });
@@ -25557,13 +25729,13 @@ async function removeLegacyDebugTraceRuntime(paths) {
25557
25729
  "debug-trace-service.err.log",
25558
25730
  "opencode-debug-trace"
25559
25731
  ]) {
25560
- await rm4(path9.join(paths.forgeDir, filename), { force: true });
25732
+ await rm4(path10.join(paths.forgeDir, filename), { force: true });
25561
25733
  }
25562
- await rm4(path9.join(paths.forgeDir, "claude-tap-traces"), { recursive: true, force: true });
25563
- await rm4(path9.join(paths.forgeDir, "verified-claude-tap"), { recursive: true, force: true });
25734
+ await rm4(path10.join(paths.forgeDir, "claude-tap-traces"), { recursive: true, force: true });
25735
+ await rm4(path10.join(paths.forgeDir, "verified-claude-tap"), { recursive: true, force: true });
25564
25736
  }
25565
25737
  async function isManagedDebugTraceConfig(configPath) {
25566
- const raw = await readFile8(configPath, "utf8").catch((error45) => {
25738
+ const raw = await readFile9(configPath, "utf8").catch((error45) => {
25567
25739
  if (error45.code === "ENOENT") return void 0;
25568
25740
  throw error45;
25569
25741
  });
@@ -25627,7 +25799,7 @@ var WorkPackLocalEditsError = class extends Error {
25627
25799
  async function assertWorkPackUnchangedAtBoundary(paths, target, snapshot) {
25628
25800
  const ownership = await workPackOwnership(target);
25629
25801
  if (ownership === "absent") return;
25630
- if (ownership === "foreign") throw foreignWorkPackError(path9.basename(target));
25802
+ if (ownership === "foreign") throw foreignWorkPackError(path10.basename(target));
25631
25803
  const localState = await checkWorkPackInstalledState({
25632
25804
  packDir: target,
25633
25805
  agentsDir: paths.agentsDir,
@@ -25669,31 +25841,31 @@ async function preserveWorkPackExtras(target, nextPath, actual) {
25669
25841
  `A nova vers\xE3o usa o caminho adicional "${name}". O pacote anterior e os ficheiros locais foram preservados.`
25670
25842
  );
25671
25843
  }
25672
- for (const directory of directories) await mkdir5(path9.join(nextPath, directory), { recursive: true });
25844
+ for (const directory of directories) await mkdir6(path10.join(nextPath, directory), { recursive: true });
25673
25845
  for (const file2 of extras) {
25674
- const destination = path9.join(nextPath, file2.path);
25675
- await mkdir5(path9.dirname(destination), { recursive: true });
25676
- await cp(path9.join(target, file2.path), destination, { errorOnExist: true, force: false });
25677
- if (createHash4("sha256").update(await readFile8(destination)).digest("hex") !== file2.sha256)
25846
+ const destination = path10.join(nextPath, file2.path);
25847
+ await mkdir6(path10.dirname(destination), { recursive: true });
25848
+ await cp(path10.join(target, file2.path), destination, { errorOnExist: true, force: false });
25849
+ if (createHash4("sha256").update(await readFile9(destination)).digest("hex") !== file2.sha256)
25678
25850
  throw new WorkPackLocalEditsError("local-edits-preserved");
25679
25851
  }
25680
25852
  }
25681
25853
  async function installSkillArchive(paths, slug, version2, archive, options = {}) {
25682
- const tempRoot = await mkdtemp(path9.join(os4.tmpdir(), `forge-${slug}-`));
25683
- const archivePath = path9.join(tempRoot, `${slug}.tar`);
25684
- const extractPath = path9.join(tempRoot, "extract");
25685
- const nextPath = path9.join(tempRoot, slug);
25686
- const target = path9.join(paths.skillsDir, slug);
25687
- const backup = path9.join(paths.skillsDir, `${slug}.previous`);
25854
+ const tempRoot = await mkdtemp(path10.join(os4.tmpdir(), `forge-${slug}-`));
25855
+ const archivePath = path10.join(tempRoot, `${slug}.tar`);
25856
+ const extractPath = path10.join(tempRoot, "extract");
25857
+ const nextPath = path10.join(tempRoot, slug);
25858
+ const target = path10.join(paths.skillsDir, slug);
25859
+ const backup = path10.join(paths.skillsDir, `${slug}.previous`);
25688
25860
  let agentFiles;
25689
25861
  let commandFiles;
25690
25862
  let previousAgents;
25691
25863
  let previousCommands;
25692
25864
  try {
25693
- await mkdir5(extractPath, { recursive: true });
25694
- await writeFile6(archivePath, archive);
25865
+ await mkdir6(extractPath, { recursive: true });
25866
+ await writeFile7(archivePath, archive);
25695
25867
  await So({ file: archivePath, cwd: extractPath, strict: true });
25696
- const extractedSkillPath = path9.join(extractPath, slug);
25868
+ const extractedSkillPath = path10.join(extractPath, slug);
25697
25869
  await assertNoReservedMarkerAliases(extractedSkillPath);
25698
25870
  await validateSkillFolder(extractedSkillPath, slug);
25699
25871
  agentFiles = await normalizePackAgentModels(
@@ -25720,15 +25892,15 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
25720
25892
  }
25721
25893
  throw error45;
25722
25894
  }
25723
- await rename6(path9.join(extractPath, slug), nextPath);
25724
- await writeFile6(path9.join(nextPath, ".forge-version"), `${version2}
25895
+ await rename7(path10.join(extractPath, slug), nextPath);
25896
+ await writeFile7(path10.join(nextPath, ".forge-version"), `${version2}
25725
25897
  `);
25726
25898
  if (agentFiles.length > 0) {
25727
- await writeFile6(path9.join(nextPath, ".forge-agents"), `${agentFiles.map((agent) => agent.filename).join("\n")}
25899
+ await writeFile7(path10.join(nextPath, ".forge-agents"), `${agentFiles.map((agent) => agent.filename).join("\n")}
25728
25900
  `);
25729
25901
  }
25730
25902
  if (commandFiles.length > 0) {
25731
- await writeFile6(path9.join(nextPath, ".forge-commands"), `${commandFiles.map((command) => command.filename).join("\n")}
25903
+ await writeFile7(path10.join(nextPath, ".forge-commands"), `${commandFiles.map((command) => command.filename).join("\n")}
25732
25904
  `);
25733
25905
  }
25734
25906
  await writeWorkPackInstalledState({ packDir: nextPath, version: version2, agents: agentFiles, commands: commandFiles });
@@ -25739,13 +25911,13 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
25739
25911
  const agentTransactionState = new Map(
25740
25912
  [...agentSnapshot.keys()].map((filePath) => [
25741
25913
  filePath,
25742
- agentFiles.find((agent) => agent.filename === path9.basename(filePath))?.content
25914
+ agentFiles.find((agent) => agent.filename === path10.basename(filePath))?.content
25743
25915
  ])
25744
25916
  );
25745
25917
  const commandTransactionState = new Map(
25746
25918
  [...commandSnapshot.keys()].map((filePath) => [
25747
25919
  filePath,
25748
- commandFiles.find((command) => command.filename === path9.basename(filePath))?.content
25920
+ commandFiles.find((command) => command.filename === path10.basename(filePath))?.content
25749
25921
  ])
25750
25922
  );
25751
25923
  const previousManagedPaths = await managedWorkPackPaths(paths, target);
@@ -25766,7 +25938,7 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
25766
25938
  throw error45;
25767
25939
  }
25768
25940
  const writeProjection = options.writeWorkPackProjection ?? writeTextAtomic;
25769
- const claimedBackup = path9.join(tempRoot, `${slug}-claimed-previous`);
25941
+ const claimedBackup = path10.join(tempRoot, `${slug}-claimed-previous`);
25770
25942
  const transactionPath = `${backup}${WORK_PACK_TRANSACTION_SUFFIX}`;
25771
25943
  let targetBackedUp = false;
25772
25944
  let targetInstalled = false;
@@ -25776,7 +25948,7 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
25776
25948
  await rm4(transactionPath, { force: true });
25777
25949
  await writeTextAtomic(transactionPath, "install\n");
25778
25950
  try {
25779
- await rename6(target, backup);
25951
+ await rename7(target, backup);
25780
25952
  targetBackedUp = true;
25781
25953
  } catch (error45) {
25782
25954
  if (error45.code !== "ENOENT") throw error45;
@@ -25786,33 +25958,33 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
25786
25958
  await options.installWorkPackBoundary?.("after-backup");
25787
25959
  await assertWorkPackUnchangedAtBoundary(paths, backup, originalTree);
25788
25960
  }
25789
- await rename6(nextPath, target);
25961
+ await rename7(nextPath, target);
25790
25962
  targetInstalled = true;
25791
25963
  for (const filename of previousAgents.filter((name) => !nextAgentNames.has(name))) {
25792
- const filePath = path9.join(paths.agentsDir, filename);
25964
+ const filePath = path10.join(paths.agentsDir, filename);
25793
25965
  await options.workPackProjectionBoundary?.("install", filePath);
25794
25966
  await assertProjectionState(filePath, agentSnapshot.get(filePath));
25795
25967
  await rm4(filePath, { force: true });
25796
25968
  }
25797
25969
  if (agentFiles.length > 0) {
25798
- await mkdir5(paths.agentsDir, { recursive: true });
25970
+ await mkdir6(paths.agentsDir, { recursive: true });
25799
25971
  for (const agent of agentFiles) {
25800
- const filePath = path9.join(paths.agentsDir, agent.filename);
25972
+ const filePath = path10.join(paths.agentsDir, agent.filename);
25801
25973
  await options.workPackProjectionBoundary?.("install", filePath);
25802
25974
  await assertProjectionState(filePath, agentSnapshot.get(filePath));
25803
25975
  await writeProjection(filePath, agent.content);
25804
25976
  }
25805
25977
  }
25806
25978
  for (const filename of previousCommands.filter((name) => !nextCommandNames.has(name))) {
25807
- const filePath = path9.join(paths.commandsDir, filename);
25979
+ const filePath = path10.join(paths.commandsDir, filename);
25808
25980
  await options.workPackProjectionBoundary?.("install", filePath);
25809
25981
  await assertProjectionState(filePath, commandSnapshot.get(filePath));
25810
25982
  await rm4(filePath, { force: true });
25811
25983
  }
25812
25984
  if (commandFiles.length > 0) {
25813
- await mkdir5(paths.commandsDir, { recursive: true });
25985
+ await mkdir6(paths.commandsDir, { recursive: true });
25814
25986
  for (const command of commandFiles) {
25815
- const filePath = path9.join(paths.commandsDir, command.filename);
25987
+ const filePath = path10.join(paths.commandsDir, command.filename);
25816
25988
  await options.workPackProjectionBoundary?.("install", filePath);
25817
25989
  await assertProjectionState(filePath, commandSnapshot.get(filePath));
25818
25990
  await writeProjection(filePath, command.content);
@@ -25822,10 +25994,10 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
25822
25994
  if (targetBackedUp) await options.installWorkPackBoundary?.("before-commit");
25823
25995
  await assertWorkPackTreeUnchangedAtBoundary(target, installedTree);
25824
25996
  if (targetBackedUp) {
25825
- await rename6(backup, claimedBackup);
25997
+ await rename7(backup, claimedBackup);
25826
25998
  backupClaimed = true;
25827
25999
  await assertWorkPackTreeUnchangedAtBoundary(claimedBackup, originalTree);
25828
- await writeFile6(path9.join(claimedBackup, WORK_PACK_COMMITTED_MARKER), `${version2}
26000
+ await writeFile7(path10.join(claimedBackup, WORK_PACK_COMMITTED_MARKER), `${version2}
25829
26001
  `);
25830
26002
  await writeTextAtomic(transactionPath, "committed\n");
25831
26003
  }
@@ -25837,11 +26009,11 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
25837
26009
  await restoreProjectionState(commandSnapshot, commandTransactionState);
25838
26010
  }
25839
26011
  if (targetBackedUp) {
25840
- const restoredTarget = path9.join(tempRoot, `${slug}-restore`);
26012
+ const restoredTarget = path10.join(tempRoot, `${slug}-restore`);
25841
26013
  const rollbackSource = backupClaimed ? claimedBackup : backup;
25842
26014
  await cp(rollbackSource, restoredTarget, { recursive: true });
25843
26015
  if (targetInstalled) await rm4(target, { recursive: true, force: true });
25844
- await rename6(restoredTarget, target);
26016
+ await rename7(restoredTarget, target);
25845
26017
  await rm4(rollbackSource, { recursive: true, force: true });
25846
26018
  await rm4(transactionPath, { force: true });
25847
26019
  } else if (targetInstalled) {
@@ -25867,26 +26039,26 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
25867
26039
  await rm4(transactionPath, { force: true });
25868
26040
  } else {
25869
26041
  cleanup2 = "pending";
25870
- if (backupClaimed) await rename6(claimedBackup, backup);
26042
+ if (backupClaimed) await rename7(claimedBackup, backup);
25871
26043
  }
25872
26044
  }
25873
26045
  await rm4(tempRoot, { recursive: true, force: true }).catch(() => void 0);
25874
26046
  return { cleanup: cleanup2 };
25875
26047
  }
25876
26048
  async function adoptLegacyWorkPackState(paths, slug, version2, archive, approvedModelIds) {
25877
- const comparisonRoot = await mkdtemp(path9.join(os4.tmpdir(), `forge-${slug}-baseline-`));
26049
+ const comparisonRoot = await mkdtemp(path10.join(os4.tmpdir(), `forge-${slug}-baseline-`));
25878
26050
  const comparisonPaths = {
25879
26051
  ...paths,
25880
- skillsDir: path9.join(comparisonRoot, "skills"),
25881
- agentsDir: path9.join(comparisonRoot, "agents"),
25882
- commandsDir: path9.join(comparisonRoot, "commands")
26052
+ skillsDir: path10.join(comparisonRoot, "skills"),
26053
+ agentsDir: path10.join(comparisonRoot, "agents"),
26054
+ commandsDir: path10.join(comparisonRoot, "commands")
25883
26055
  };
25884
26056
  try {
25885
- await mkdir5(comparisonPaths.skillsDir, { recursive: true });
26057
+ await mkdir6(comparisonPaths.skillsDir, { recursive: true });
25886
26058
  await installSkillArchive(comparisonPaths, slug, version2, archive, { approvedModelIds });
25887
26059
  return adoptWorkPackInstalledState({
25888
- expectedPackDir: path9.join(comparisonPaths.skillsDir, slug),
25889
- packDir: path9.join(paths.skillsDir, slug),
26060
+ expectedPackDir: path10.join(comparisonPaths.skillsDir, slug),
26061
+ packDir: path10.join(paths.skillsDir, slug),
25890
26062
  agentsDir: paths.agentsDir,
25891
26063
  commandsDir: paths.commandsDir,
25892
26064
  allowAdditional: true
@@ -25898,7 +26070,7 @@ async function adoptLegacyWorkPackState(paths, slug, version2, archive, approved
25898
26070
  async function recoverInterruptedWorkPackInstalls(paths, cleanupWorkPackBackup, workPackProjectionBoundary) {
25899
26071
  const cleanupPending = /* @__PURE__ */ new Set();
25900
26072
  const failures = /* @__PURE__ */ new Map();
25901
- const entries = await readdir4(paths.skillsDir, { withFileTypes: true }).catch((error45) => {
26073
+ const entries = await readdir5(paths.skillsDir, { withFileTypes: true }).catch((error45) => {
25902
26074
  if (error45.code === "ENOENT") return [];
25903
26075
  throw error45;
25904
26076
  });
@@ -25906,7 +26078,7 @@ async function recoverInterruptedWorkPackInstalls(paths, cleanupWorkPackBackup,
25906
26078
  if (!entry.name.endsWith(".previous")) continue;
25907
26079
  const slug = entry.name.slice(0, -".previous".length);
25908
26080
  if (!slug) continue;
25909
- const target = path9.join(paths.skillsDir, slug);
26081
+ const target = path10.join(paths.skillsDir, slug);
25910
26082
  const backup = `${target}.previous`;
25911
26083
  const transactionState = await readWorkPackTransactionState(backup);
25912
26084
  if (transactionState === "committed") {
@@ -25939,9 +26111,9 @@ async function recoverInterruptedWorkPackInstall(paths, target, cleanupWorkPackB
25939
26111
  const backup = `${target}.previous`;
25940
26112
  const backupOwnership = await workPackOwnership(backup);
25941
26113
  if (backupOwnership === "absent") return "recovered";
25942
- if (backupOwnership === "foreign") throw foreignWorkPackError(path9.basename(target));
25943
- if (await workPackOwnership(target) === "foreign") throw foreignWorkPackError(path9.basename(target));
25944
- const committed = await readFile8(path9.join(backup, WORK_PACK_COMMITTED_MARKER), "utf8").catch((error45) => {
26114
+ if (backupOwnership === "foreign") throw foreignWorkPackError(path10.basename(target));
26115
+ if (await workPackOwnership(target) === "foreign") throw foreignWorkPackError(path10.basename(target));
26116
+ const committed = await readFile9(path10.join(backup, WORK_PACK_COMMITTED_MARKER), "utf8").catch((error45) => {
25945
26117
  if (error45.code === "ENOENT") return void 0;
25946
26118
  throw error45;
25947
26119
  });
@@ -25989,38 +26161,38 @@ async function recoverInterruptedWorkPackInstall(paths, target, cleanupWorkPackB
25989
26161
  );
25990
26162
  const previousAgentNames = new Set(previousAgents.map((agent) => agent.filename));
25991
26163
  const previousCommandNames = new Set(previousCommands.map((command) => command.filename));
25992
- const recoveryRoot = await mkdtemp(path9.join(os4.tmpdir(), "forge-recover-"));
25993
- const recoveredTarget = path9.join(recoveryRoot, path9.basename(target));
26164
+ const recoveryRoot = await mkdtemp(path10.join(os4.tmpdir(), "forge-recover-"));
26165
+ const recoveredTarget = path10.join(recoveryRoot, path10.basename(target));
25994
26166
  await cp(backup, recoveredTarget, { recursive: true });
25995
26167
  try {
25996
26168
  for (const filename of currentAgents.filter((name) => !previousAgentNames.has(name))) {
25997
- const filePath = path9.join(paths.agentsDir, filename);
26169
+ const filePath = path10.join(paths.agentsDir, filename);
25998
26170
  await workPackProjectionBoundary?.("recover", filePath);
25999
26171
  await assertProjectionState(filePath, agentRecoveryState.get(filePath));
26000
26172
  await rm4(filePath, { force: true });
26001
26173
  }
26002
- await mkdir5(paths.agentsDir, { recursive: true });
26174
+ await mkdir6(paths.agentsDir, { recursive: true });
26003
26175
  for (const agent of previousAgents) {
26004
- const filePath = path9.join(paths.agentsDir, agent.filename);
26176
+ const filePath = path10.join(paths.agentsDir, agent.filename);
26005
26177
  await workPackProjectionBoundary?.("recover", filePath);
26006
26178
  await assertProjectionState(filePath, agentRecoveryState.get(filePath));
26007
26179
  await writeTextAtomic(filePath, agent.content);
26008
26180
  }
26009
26181
  for (const filename of currentCommands.filter((name) => !previousCommandNames.has(name))) {
26010
- const filePath = path9.join(paths.commandsDir, filename);
26182
+ const filePath = path10.join(paths.commandsDir, filename);
26011
26183
  await workPackProjectionBoundary?.("recover", filePath);
26012
26184
  await assertProjectionState(filePath, commandRecoveryState.get(filePath));
26013
26185
  await rm4(filePath, { force: true });
26014
26186
  }
26015
- await mkdir5(paths.commandsDir, { recursive: true });
26187
+ await mkdir6(paths.commandsDir, { recursive: true });
26016
26188
  for (const command of previousCommands) {
26017
- const filePath = path9.join(paths.commandsDir, command.filename);
26189
+ const filePath = path10.join(paths.commandsDir, command.filename);
26018
26190
  await workPackProjectionBoundary?.("recover", filePath);
26019
26191
  await assertProjectionState(filePath, commandRecoveryState.get(filePath));
26020
26192
  await writeTextAtomic(filePath, command.content);
26021
26193
  }
26022
26194
  await rm4(target, { recursive: true, force: true });
26023
- await rename6(recoveredTarget, target);
26195
+ await rename7(recoveredTarget, target);
26024
26196
  await rm4(backup, { recursive: true, force: true });
26025
26197
  await rm4(`${backup}${WORK_PACK_TRANSACTION_SUFFIX}`, { force: true });
26026
26198
  } finally {
@@ -26032,7 +26204,7 @@ async function removeWorkPackBackup(backupPath) {
26032
26204
  await rm4(backupPath, { recursive: true, force: true });
26033
26205
  }
26034
26206
  async function readWorkPackTransactionFile(backup) {
26035
- return readFile8(`${backup}${WORK_PACK_TRANSACTION_SUFFIX}`, "utf8").catch((error45) => {
26207
+ return readFile9(`${backup}${WORK_PACK_TRANSACTION_SUFFIX}`, "utf8").catch((error45) => {
26036
26208
  if (error45.code === "ENOENT") return void 0;
26037
26209
  throw error45;
26038
26210
  });
@@ -26046,7 +26218,7 @@ function isManagedProjectionName(filename) {
26046
26218
  return filename.length > 0 && !filename.includes("/") && !filename.includes("\\") && filename !== "..";
26047
26219
  }
26048
26220
  async function recordRemovedProjection(transactionPath, kind, filename) {
26049
- const current = await readFile8(transactionPath, "utf8");
26221
+ const current = await readFile9(transactionPath, "utf8");
26050
26222
  await writeTextAtomic(transactionPath, `${current.trimEnd()}
26051
26223
  ${kind}:${filename}
26052
26224
  `);
@@ -26083,7 +26255,7 @@ async function workPackOwnership(target) {
26083
26255
  });
26084
26256
  if (!targetStat) return "absent";
26085
26257
  if (!targetStat.isDirectory()) return "foreign";
26086
- const marker = await readFile8(path9.join(target, ".forge-version"), "utf8").catch((error45) => {
26258
+ const marker = await readFile9(path10.join(target, ".forge-version"), "utf8").catch((error45) => {
26087
26259
  if (error45.code === "ENOENT") return void 0;
26088
26260
  throw error45;
26089
26261
  });
@@ -26109,11 +26281,11 @@ async function assertProjectionRecoveryIsSafe(directory, currentFiles, previousF
26109
26281
  expected.set(file2.filename, contents);
26110
26282
  }
26111
26283
  for (const [filename, contents] of expected) {
26112
- const projected = await readFile8(path9.join(directory, filename), "utf8").catch((error45) => {
26284
+ const projected = await readFile9(path10.join(directory, filename), "utf8").catch((error45) => {
26113
26285
  if (error45.code === "ENOENT") return void 0;
26114
26286
  throw error45;
26115
26287
  });
26116
- validated.set(path9.join(directory, filename), projected);
26288
+ validated.set(path10.join(directory, filename), projected);
26117
26289
  const missingPreviousProjection = missingPreviousProjectionIsLocalDeletion(
26118
26290
  filename,
26119
26291
  projected,
@@ -26131,19 +26303,19 @@ async function assertProjectionRecoveryIsSafe(directory, currentFiles, previousF
26131
26303
  return validated;
26132
26304
  }
26133
26305
  async function assertProjectionState(filePath, expected) {
26134
- const current = await readFile8(filePath, "utf8").catch((error45) => {
26306
+ const current = await readFile9(filePath, "utf8").catch((error45) => {
26135
26307
  if (error45.code === "ENOENT") return void 0;
26136
26308
  throw error45;
26137
26309
  });
26138
26310
  if (current !== expected) {
26139
- throw new WorkPackLocalEditsError("local-edits-preserved", `A proje\xE7\xE3o ${path9.basename(filePath)} foi alterada durante a opera\xE7\xE3o`);
26311
+ throw new WorkPackLocalEditsError("local-edits-preserved", `A proje\xE7\xE3o ${path10.basename(filePath)} foi alterada durante a opera\xE7\xE3o`);
26140
26312
  }
26141
26313
  }
26142
26314
  async function captureProjectionState(directory, filenames) {
26143
26315
  const snapshot = /* @__PURE__ */ new Map();
26144
26316
  for (const filename of filenames) {
26145
- const filePath = path9.join(directory, filename);
26146
- const content = await readFile8(filePath, "utf8").catch((error45) => {
26317
+ const filePath = path10.join(directory, filename);
26318
+ const content = await readFile9(filePath, "utf8").catch((error45) => {
26147
26319
  if (error45.code === "ENOENT") return void 0;
26148
26320
  throw error45;
26149
26321
  });
@@ -26154,7 +26326,7 @@ async function captureProjectionState(directory, filenames) {
26154
26326
  async function restoreProjectionState(snapshot, transactionState) {
26155
26327
  for (const [filePath, content] of snapshot) {
26156
26328
  if (transactionState) {
26157
- const current = await readFile8(filePath, "utf8").catch((error45) => {
26329
+ const current = await readFile9(filePath, "utf8").catch((error45) => {
26158
26330
  if (error45.code === "ENOENT") return void 0;
26159
26331
  throw error45;
26160
26332
  });
@@ -26165,8 +26337,8 @@ async function restoreProjectionState(snapshot, transactionState) {
26165
26337
  }
26166
26338
  }
26167
26339
  async function readPackAgentFiles(skillFolder, managedNames) {
26168
- const agentsFolder = path9.join(skillFolder, "agents");
26169
- const entries = await readdir4(agentsFolder, { withFileTypes: true }).catch((error45) => {
26340
+ const agentsFolder = path10.join(skillFolder, "agents");
26341
+ const entries = await readdir5(agentsFolder, { withFileTypes: true }).catch((error45) => {
26170
26342
  if (error45.code === "ENOENT") return [];
26171
26343
  throw error45;
26172
26344
  });
@@ -26174,7 +26346,7 @@ async function readPackAgentFiles(skillFolder, managedNames) {
26174
26346
  for (const entry of entries) {
26175
26347
  if (!entry.isFile() || !entry.name.endsWith(".md") || managedNames && !managedNames.has(entry.name)) continue;
26176
26348
  if (entry.name.startsWith("._")) continue;
26177
- const content = await readFile8(path9.join(agentsFolder, entry.name), "utf8");
26349
+ const content = await readFile9(path10.join(agentsFolder, entry.name), "utf8");
26178
26350
  validateAgentFile(entry.name, content);
26179
26351
  files.push({ filename: entry.name, content });
26180
26352
  }
@@ -26185,7 +26357,7 @@ async function normalizePackAgentModels(skillFolder, agentFiles, approvedModelId
26185
26357
  for (const agent of agentFiles) {
26186
26358
  const content = normalizePackAgentModel(agent.filename, agent.content, approvedModelIds, slug);
26187
26359
  if (content !== agent.content) {
26188
- await writeFile6(path9.join(skillFolder, "agents", agent.filename), content);
26360
+ await writeFile7(path10.join(skillFolder, "agents", agent.filename), content);
26189
26361
  }
26190
26362
  normalized.push({ ...agent, content });
26191
26363
  }
@@ -26205,8 +26377,8 @@ function normalizePackAgentModel(filename, content, approvedModelIds, slug) {
26205
26377
  return normalizePackExtensionModel(`agents/${filename}`, content, approvedModelIds, slug);
26206
26378
  }
26207
26379
  async function readPackCommandFiles(skillFolder, managedNames) {
26208
- const commandsFolder = path9.join(skillFolder, "commands");
26209
- const entries = await readdir4(commandsFolder, { withFileTypes: true }).catch((error45) => {
26380
+ const commandsFolder = path10.join(skillFolder, "commands");
26381
+ const entries = await readdir5(commandsFolder, { withFileTypes: true }).catch((error45) => {
26210
26382
  if (error45.code === "ENOENT") return [];
26211
26383
  throw error45;
26212
26384
  });
@@ -26214,7 +26386,7 @@ async function readPackCommandFiles(skillFolder, managedNames) {
26214
26386
  for (const entry of entries) {
26215
26387
  if (!entry.isFile() || !entry.name.endsWith(".md") || managedNames && !managedNames.has(entry.name)) continue;
26216
26388
  if (entry.name.startsWith("._")) continue;
26217
- const content = await readFile8(path9.join(commandsFolder, entry.name), "utf8");
26389
+ const content = await readFile9(path10.join(commandsFolder, entry.name), "utf8");
26218
26390
  validateCommandFile(entry.name, content);
26219
26391
  files.push({ filename: entry.name, content });
26220
26392
  }
@@ -26225,7 +26397,7 @@ async function normalizePackCommandModels(skillFolder, commandFiles, approvedMod
26225
26397
  for (const command of commandFiles) {
26226
26398
  const content = normalizePackExtensionModel(`commands/${command.filename}`, command.content, approvedModelIds, slug);
26227
26399
  if (content !== command.content) {
26228
- await writeFile6(path9.join(skillFolder, "commands", command.filename), content);
26400
+ await writeFile7(path10.join(skillFolder, "commands", command.filename), content);
26229
26401
  }
26230
26402
  normalized.push({ ...command, content });
26231
26403
  }
@@ -26247,7 +26419,7 @@ async function assertNoForeignAgentConflicts(agentsDir, agentFiles, ownedFilenam
26247
26419
  const owned = new Set(ownedFilenames);
26248
26420
  for (const agent of agentFiles) {
26249
26421
  if (owned.has(agent.filename)) continue;
26250
- const existing = await readFile8(path9.join(agentsDir, agent.filename), "utf8").catch((error45) => {
26422
+ const existing = await readFile9(path10.join(agentsDir, agent.filename), "utf8").catch((error45) => {
26251
26423
  if (error45.code === "ENOENT") return void 0;
26252
26424
  throw error45;
26253
26425
  });
@@ -26260,7 +26432,7 @@ async function assertNoForeignCommandConflicts(commandsDir, commandFiles, ownedF
26260
26432
  const owned = new Set(ownedFilenames);
26261
26433
  for (const command of commandFiles) {
26262
26434
  if (owned.has(command.filename)) continue;
26263
- const existing = await readFile8(path9.join(commandsDir, command.filename), "utf8").catch((error45) => {
26435
+ const existing = await readFile9(path10.join(commandsDir, command.filename), "utf8").catch((error45) => {
26264
26436
  if (error45.code === "ENOENT") return void 0;
26265
26437
  throw error45;
26266
26438
  });
@@ -26270,28 +26442,28 @@ async function assertNoForeignCommandConflicts(commandsDir, commandFiles, ownedF
26270
26442
  }
26271
26443
  }
26272
26444
  async function readAgentRecord(skillFolder) {
26273
- const raw = await readFile8(path9.join(skillFolder, ".forge-agents"), "utf8").catch(() => "");
26445
+ const raw = await readFile9(path10.join(skillFolder, ".forge-agents"), "utf8").catch(() => "");
26274
26446
  return raw.split("\n").map((line) => line.trim()).filter((line) => line.length > 0 && !line.includes("/") && !line.includes("\\") && line !== "..");
26275
26447
  }
26276
26448
  async function readCommandRecord(skillFolder) {
26277
- const raw = await readFile8(path9.join(skillFolder, ".forge-commands"), "utf8").catch(() => "");
26449
+ const raw = await readFile9(path10.join(skillFolder, ".forge-commands"), "utf8").catch(() => "");
26278
26450
  return raw.split("\n").map((line) => line.trim()).filter((line) => line.length > 0 && !line.includes("/") && !line.includes("\\") && line !== "..");
26279
26451
  }
26280
26452
  async function managedWorkPackPaths(paths, skillFolder) {
26281
26453
  const files = await listFilesRecursively(skillFolder);
26282
- const agents = (await readAgentRecord(skillFolder)).map((filename) => path9.join(paths.agentsDir, filename));
26283
- const commands = (await readCommandRecord(skillFolder)).map((filename) => path9.join(paths.commandsDir, filename));
26454
+ const agents = (await readAgentRecord(skillFolder)).map((filename) => path10.join(paths.agentsDir, filename));
26455
+ const commands = (await readCommandRecord(skillFolder)).map((filename) => path10.join(paths.commandsDir, filename));
26284
26456
  return [.../* @__PURE__ */ new Set([...files, ...agents, ...commands])];
26285
26457
  }
26286
26458
  async function managedWorkPackSlugs(skillsDir) {
26287
- const entries = await readdir4(skillsDir, { withFileTypes: true }).catch((error45) => {
26459
+ const entries = await readdir5(skillsDir, { withFileTypes: true }).catch((error45) => {
26288
26460
  if (error45.code === "ENOENT") return [];
26289
26461
  throw error45;
26290
26462
  });
26291
26463
  const slugs = [];
26292
26464
  for (const entry of entries) {
26293
26465
  if (!entry.isDirectory() || entry.name.endsWith(".previous")) continue;
26294
- if (await workPackOwnership(path9.join(skillsDir, entry.name)) === "managed") slugs.push(entry.name);
26466
+ if (await workPackOwnership(path10.join(skillsDir, entry.name)) === "managed") slugs.push(entry.name);
26295
26467
  }
26296
26468
  return slugs.sort((left, right) => left.localeCompare(right));
26297
26469
  }
@@ -26301,21 +26473,21 @@ async function removeManagedWorkPackTransaction(paths, target, options) {
26301
26473
  const agents = await readAgentRecord(target);
26302
26474
  const commands = await readCommandRecord(target);
26303
26475
  const snapshots = await Promise.all([
26304
- ...agents.map((filename) => captureExactFile(path9.join(paths.agentsDir, filename))),
26305
- ...commands.map((filename) => captureExactFile(path9.join(paths.commandsDir, filename)))
26476
+ ...agents.map((filename) => captureExactFile(path10.join(paths.agentsDir, filename))),
26477
+ ...commands.map((filename) => captureExactFile(path10.join(paths.commandsDir, filename)))
26306
26478
  ]);
26307
26479
  await assertWorkPackUnchangedAtBoundary(paths, target);
26308
26480
  const backup = `${target}.previous`;
26309
26481
  const transactionPath = `${backup}${WORK_PACK_TRANSACTION_SUFFIX}`;
26310
- const transactionRoot = await mkdtemp(path9.join(os4.tmpdir(), "forge-remove-"));
26311
- const claimedBackup = path9.join(transactionRoot, path9.basename(target));
26482
+ const transactionRoot = await mkdtemp(path10.join(os4.tmpdir(), "forge-remove-"));
26483
+ const claimedBackup = path10.join(transactionRoot, path10.basename(target));
26312
26484
  let projectionsRemoved = false;
26313
26485
  let backupClaimed = false;
26314
26486
  try {
26315
26487
  await rm4(backup, { recursive: true, force: true });
26316
26488
  await rm4(transactionPath, { force: true });
26317
26489
  await writeTextAtomic(transactionPath, "remove\n");
26318
- await rename6(target, backup);
26490
+ await rename7(target, backup);
26319
26491
  } catch (error45) {
26320
26492
  await rm4(transactionPath, { force: true }).catch(() => void 0);
26321
26493
  await rm4(transactionRoot, { recursive: true, force: true }).catch(() => void 0);
@@ -26326,7 +26498,7 @@ async function removeManagedWorkPackTransaction(paths, target, options) {
26326
26498
  await assertWorkPackUnchangedAtBoundary(paths, backup);
26327
26499
  projectionsRemoved = agents.length > 0;
26328
26500
  for (const filename of agents) {
26329
- const filePath = path9.join(paths.agentsDir, filename);
26501
+ const filePath = path10.join(paths.agentsDir, filename);
26330
26502
  await options.workPackProjectionBoundary?.("remove", filePath);
26331
26503
  await assertExactFileState(snapshots, filePath);
26332
26504
  await recordRemovedProjection(transactionPath, "agent", filename);
@@ -26335,7 +26507,7 @@ async function removeManagedWorkPackTransaction(paths, target, options) {
26335
26507
  await options.removeWorkPackBoundary?.("after-agents");
26336
26508
  projectionsRemoved ||= commands.length > 0;
26337
26509
  for (const filename of commands) {
26338
- const filePath = path9.join(paths.commandsDir, filename);
26510
+ const filePath = path10.join(paths.commandsDir, filename);
26339
26511
  await options.workPackProjectionBoundary?.("remove", filePath);
26340
26512
  await assertExactFileState(snapshots, filePath);
26341
26513
  await recordRemovedProjection(transactionPath, "command", filename);
@@ -26344,7 +26516,7 @@ async function removeManagedWorkPackTransaction(paths, target, options) {
26344
26516
  await options.removeWorkPackBoundary?.("after-commands");
26345
26517
  await assertWorkPackTreeUnchangedAtBoundary(backup);
26346
26518
  await options.removeWorkPackBoundary?.("before-commit");
26347
- await rename6(backup, claimedBackup);
26519
+ await rename7(backup, claimedBackup);
26348
26520
  backupClaimed = true;
26349
26521
  await assertWorkPackTreeUnchangedAtBoundary(claimedBackup);
26350
26522
  await writeTextAtomic(transactionPath, "committed\n");
@@ -26355,13 +26527,13 @@ async function removeManagedWorkPackTransaction(paths, target, options) {
26355
26527
  } catch (error45) {
26356
26528
  try {
26357
26529
  if (projectionsRemoved) await restoreRemovedExactFiles(snapshots);
26358
- await rename6(backupClaimed ? claimedBackup : backup, target);
26530
+ await rename7(backupClaimed ? claimedBackup : backup, target);
26359
26531
  await rm4(transactionPath, { force: true });
26360
26532
  if (projectionsRemoved) await verifyRestoredOrLocallyChangedFiles(snapshots);
26361
26533
  if (await workPackOwnership(target) !== "managed") throw new Error("restored Work Pack marker missing");
26362
26534
  await rm4(transactionRoot, { recursive: true, force: true }).catch(() => void 0);
26363
26535
  } catch (restoreError) {
26364
- throw new WorkPackRecoveryUncertainError(`Falha ao remover e restaurar o pacote de trabalho ${path9.basename(target)}`, {
26536
+ throw new WorkPackRecoveryUncertainError(`Falha ao remover e restaurar o pacote de trabalho ${path10.basename(target)}`, {
26365
26537
  cause: new AggregateError([error45, restoreError])
26366
26538
  });
26367
26539
  }
@@ -26372,7 +26544,7 @@ async function captureExactFile(filePath) {
26372
26544
  try {
26373
26545
  const info = await lstat5(filePath);
26374
26546
  if (!info.isFile()) throw new Error(`A proje\xE7\xE3o gerida n\xE3o \xE9 um ficheiro regular: ${filePath}`);
26375
- return { path: filePath, exists: true, bytes: await readFile8(filePath), mode: info.mode & 4095 };
26547
+ return { path: filePath, exists: true, bytes: await readFile9(filePath), mode: info.mode & 4095 };
26376
26548
  } catch (error45) {
26377
26549
  if (error45.code === "ENOENT") return { path: filePath, exists: false };
26378
26550
  throw error45;
@@ -26382,18 +26554,18 @@ async function assertExactFileState(snapshots, filePath) {
26382
26554
  const expected = snapshots.find((snapshot) => snapshot.path === filePath);
26383
26555
  const current = await captureExactFile(filePath);
26384
26556
  if (!expected || current.exists !== expected.exists) {
26385
- throw new WorkPackLocalEditsError("local-edits-preserved", `A proje\xE7\xE3o ${path9.basename(filePath)} foi alterada durante a opera\xE7\xE3o`);
26557
+ throw new WorkPackLocalEditsError("local-edits-preserved", `A proje\xE7\xE3o ${path10.basename(filePath)} foi alterada durante a opera\xE7\xE3o`);
26386
26558
  }
26387
26559
  if (current.exists && (!current.bytes?.equals(expected.bytes) || current.mode !== expected.mode)) {
26388
- throw new WorkPackLocalEditsError("local-edits-preserved", `A proje\xE7\xE3o ${path9.basename(filePath)} foi alterada durante a opera\xE7\xE3o`);
26560
+ throw new WorkPackLocalEditsError("local-edits-preserved", `A proje\xE7\xE3o ${path10.basename(filePath)} foi alterada durante a opera\xE7\xE3o`);
26389
26561
  }
26390
26562
  }
26391
26563
  async function restoreRemovedExactFiles(snapshots) {
26392
26564
  for (const snapshot of snapshots) {
26393
26565
  if ((await captureExactFile(snapshot.path)).exists) continue;
26394
26566
  if (!snapshot.exists) continue;
26395
- await mkdir5(path9.dirname(snapshot.path), { recursive: true });
26396
- await writeFile6(snapshot.path, snapshot.bytes);
26567
+ await mkdir6(path10.dirname(snapshot.path), { recursive: true });
26568
+ await writeFile7(snapshot.path, snapshot.bytes);
26397
26569
  await chmod4(snapshot.path, snapshot.mode);
26398
26570
  }
26399
26571
  }
@@ -26404,20 +26576,20 @@ async function verifyRestoredOrLocallyChangedFiles(snapshots) {
26404
26576
  }
26405
26577
  }
26406
26578
  async function listFilesRecursively(root) {
26407
- const entries = await readdir4(root, { withFileTypes: true }).catch((error45) => {
26579
+ const entries = await readdir5(root, { withFileTypes: true }).catch((error45) => {
26408
26580
  if (error45.code === "ENOENT") return [];
26409
26581
  throw error45;
26410
26582
  });
26411
26583
  const files = [];
26412
26584
  for (const entry of entries) {
26413
- const absolute = path9.join(root, entry.name);
26585
+ const absolute = path10.join(root, entry.name);
26414
26586
  if (entry.isDirectory()) files.push(...await listFilesRecursively(absolute));
26415
26587
  else if (entry.isFile()) files.push(absolute);
26416
26588
  }
26417
26589
  return files;
26418
26590
  }
26419
26591
  async function validateSkillFolder(folder, slug) {
26420
- const skillMd = await readFile8(path9.join(folder, "SKILL.md"), "utf8");
26592
+ const skillMd = await readFile9(path10.join(folder, "SKILL.md"), "utf8");
26421
26593
  const frontmatter = /^---\n([\s\S]+?)\n---/.exec(skillMd)?.[1] ?? "";
26422
26594
  if (!frontmatter.includes(`name: ${slug}`) && !frontmatter.includes(`name: "${slug}"`)) {
26423
26595
  throw new Error(`O campo name no frontmatter de SKILL.md tem de corresponder a ${slug}`);
@@ -26428,7 +26600,7 @@ async function validateSkillFolder(folder, slug) {
26428
26600
  }
26429
26601
  async function assertNoReservedMarkerAliases(skillFolder) {
26430
26602
  const reserved = /* @__PURE__ */ new Set([".forge-version", ".forge-agents", ".forge-commands", WORK_PACK_LOCAL_STATE_FILENAME]);
26431
- const entries = await readdir4(skillFolder);
26603
+ const entries = await readdir5(skillFolder);
26432
26604
  const marker = entries.find((entry) => reserved.has(entry.toLowerCase()));
26433
26605
  if (marker) throw new Error(`O pacote de trabalho cont\xE9m o marcador Forge reservado ${marker}`);
26434
26606
  }
@@ -26438,14 +26610,14 @@ async function writeJsonAtomic2(filePath, value) {
26438
26610
  await writeTextAtomic(filePath, content);
26439
26611
  }
26440
26612
  async function writeTextAtomic(filePath, content) {
26441
- const dir = path9.dirname(filePath);
26442
- await mkdir5(dir, { recursive: true });
26443
- const tempPath = path9.join(dir, `.${path9.basename(filePath)}.${process.pid}.tmp`);
26444
- await writeFile6(tempPath, content);
26445
- await rename6(tempPath, filePath);
26613
+ const dir = path10.dirname(filePath);
26614
+ await mkdir6(dir, { recursive: true });
26615
+ const tempPath = path10.join(dir, `.${path10.basename(filePath)}.${process.pid}.tmp`);
26616
+ await writeFile7(tempPath, content);
26617
+ await rename7(tempPath, filePath);
26446
26618
  }
26447
26619
  async function readPluginFile(pluginPath) {
26448
- return readFile8(pluginPath, "utf8").catch((error45) => {
26620
+ return readFile9(pluginPath, "utf8").catch((error45) => {
26449
26621
  if (error45.code === "ENOENT") return void 0;
26450
26622
  throw error45;
26451
26623
  });
@@ -26478,7 +26650,7 @@ function withPluginPaths(config2, pluginPaths, removePluginPaths = []) {
26478
26650
  return next;
26479
26651
  }
26480
26652
  async function readJsoncObject(filePath) {
26481
- const raw = await readFile8(filePath, "utf8").catch((error45) => {
26653
+ const raw = await readFile9(filePath, "utf8").catch((error45) => {
26482
26654
  if (error45.code === "ENOENT") return "";
26483
26655
  throw error45;
26484
26656
  });
@@ -26582,15 +26754,14 @@ function isRecord5(value) {
26582
26754
  }
26583
26755
 
26584
26756
  // packages/cli/src/localWorkerSync.ts
26585
- import { readFile as readFile11 } from "node:fs/promises";
26586
- import path12 from "node:path";
26757
+ import { readFile as readFile12 } from "node:fs/promises";
26587
26758
 
26588
26759
  // packages/cli/src/recoveryLauncher.ts
26589
- import { chmod as chmod5, readFile as readFile9 } from "node:fs/promises";
26760
+ import { chmod as chmod5, readFile as readFile10 } from "node:fs/promises";
26590
26761
  import { execFileSync } from "node:child_process";
26591
- import path10 from "node:path";
26762
+ import path11 from "node:path";
26592
26763
  async function installRecoveryLauncher(paths, forgeBaseUrl, source = new URL("./repair.js", import.meta.url)) {
26593
- const program = await readFile9(source, "utf8");
26764
+ const program = await readFile10(source, "utf8");
26594
26765
  let nodePath;
26595
26766
  try {
26596
26767
  const runtime = JSON.parse(execFileSync(
@@ -26598,16 +26769,16 @@ async function installRecoveryLauncher(paths, forgeBaseUrl, source = new URL("./
26598
26769
  ["-p", 'JSON.stringify({ path: process.execPath, major: Number(process.versions.node.split(".")[0]) })'],
26599
26770
  { encoding: "utf8", timeout: 5e3, windowsHide: true }
26600
26771
  ));
26601
- if (runtime.major < 22 || typeof runtime.major !== "number" || typeof runtime.path !== "string" || !path10.isAbsolute(runtime.path)) throw new Error();
26772
+ if (runtime.major < 22 || typeof runtime.major !== "number" || typeof runtime.path !== "string" || !path11.isAbsolute(runtime.path)) throw new Error();
26602
26773
  nodePath = runtime.path;
26603
26774
  } catch {
26604
26775
  throw new Error("A recupera\xE7\xE3o precisa do Node 22 ou superior j\xE1 previsto na prepara\xE7\xE3o do computador. Pe\xE7a ao respons\xE1vel para verificar a instala\xE7\xE3o.");
26605
26776
  }
26606
26777
  const launcherContent = renderRecoveryLauncher(nodePath, process.platform);
26607
- await writeOwnerOnlyTextAtomic(path10.join(paths.forgeDir, "forge-repair.mjs"), program);
26608
- await writeOwnerOnlyTextAtomic(path10.join(paths.forgeDir, "recovery-origin.json"), JSON.stringify({ forgeBaseUrl }) + "\n");
26778
+ await writeOwnerOnlyTextAtomic(path11.join(paths.forgeDir, "forge-repair.mjs"), program);
26779
+ await writeOwnerOnlyTextAtomic(path11.join(paths.forgeDir, "recovery-origin.json"), JSON.stringify({ forgeBaseUrl }) + "\n");
26609
26780
  const windows = process.platform === "win32";
26610
- const launcher = path10.join(paths.forgeDir, windows ? "Reparar Forge.cmd" : "Reparar Forge.command");
26781
+ const launcher = path11.join(paths.forgeDir, windows ? "Reparar Forge.cmd" : "Reparar Forge.command");
26611
26782
  await writeOwnerOnlyTextAtomic(launcher, launcherContent);
26612
26783
  if (!windows) await chmod5(launcher, 448);
26613
26784
  return launcher;
@@ -26628,15 +26799,15 @@ exec '${nodePath.replace(/'/g, "'\\''")}' ./forge-repair.mjs "$@"
26628
26799
 
26629
26800
  // packages/cli/src/rollback.ts
26630
26801
  import { createHash as createHash6 } from "node:crypto";
26631
- import { chmod as chmod6, mkdir as mkdir6, readFile as readFile10, readdir as readdir5, rename as rename7, rm as rm5, stat as stat2, writeFile as writeFile7 } from "node:fs/promises";
26632
- import path11 from "node:path";
26802
+ import { chmod as chmod6, mkdir as mkdir7, readFile as readFile11, readdir as readdir6, rename as rename8, rm as rm5, stat as stat2, writeFile as writeFile8 } from "node:fs/promises";
26803
+ import path12 from "node:path";
26633
26804
  async function recordRollbackEvidencePlugin(paths, expectedContent) {
26634
26805
  if ((await readRollbackLifecycle(paths))?.state !== "pilot") return;
26635
26806
  const capsule = await readRollbackCapsule(paths);
26636
- const pluginPath = path11.join(paths.pluginDir, FORGE_EVIDENCE_PLUGIN_FILENAME);
26807
+ const pluginPath = path12.join(paths.pluginDir, FORGE_EVIDENCE_PLUGIN_FILENAME);
26637
26808
  const managed = capsule?.managed.files.find((file2) => file2.path === pluginPath);
26638
26809
  if (!capsule || !managed) return;
26639
- const current = await readFile10(pluginPath, "utf8").catch(() => void 0);
26810
+ const current = await readFile11(pluginPath, "utf8").catch(() => void 0);
26640
26811
  if (current !== expectedContent) return;
26641
26812
  const fingerprint = sha2562(Buffer.from(current));
26642
26813
  if (managed.sha256 === fingerprint) return;
@@ -26650,20 +26821,20 @@ async function readRollbackCapsule(paths) {
26650
26821
  return readJson(paths.rollbackCapsulePath);
26651
26822
  }
26652
26823
  async function writeProtectedJsonAtomic(filePath, value) {
26653
- const directory = path11.dirname(filePath);
26654
- await mkdir6(directory, { recursive: true, mode: 448 });
26824
+ const directory = path12.dirname(filePath);
26825
+ await mkdir7(directory, { recursive: true, mode: 448 });
26655
26826
  await protectRollbackPath(directory, "directory");
26656
- const temporary = path11.join(directory, `.${path11.basename(filePath)}.${process.pid}.tmp`);
26657
- await writeFile7(temporary, `${JSON.stringify(value, null, 2)}
26827
+ const temporary = path12.join(directory, `.${path12.basename(filePath)}.${process.pid}.tmp`);
26828
+ await writeFile8(temporary, `${JSON.stringify(value, null, 2)}
26658
26829
  `, { mode: 384 });
26659
26830
  await protectRollbackPath(temporary, "file");
26660
- await rename7(temporary, filePath);
26831
+ await rename8(temporary, filePath);
26661
26832
  }
26662
26833
  async function protectRollbackPath(filePath, kind, options = {}) {
26663
26834
  await protectOwnerOnlyPath(filePath, kind, { ...options, failureContext: "o material de rollback" });
26664
26835
  }
26665
26836
  async function readJson(filePath) {
26666
- const raw = await readFile10(filePath, "utf8").catch((error45) => {
26837
+ const raw = await readFile11(filePath, "utf8").catch((error45) => {
26667
26838
  if (error45.code === "ENOENT") return void 0;
26668
26839
  throw error45;
26669
26840
  });
@@ -26676,11 +26847,17 @@ function sha2562(value) {
26676
26847
 
26677
26848
  // packages/cli/src/localWorkerSync.ts
26678
26849
  async function syncLocalWorker(paths, credentials, manifest) {
26679
- const recovery = await recoverCoreSyncTransaction({ journalPath: path12.join(paths.forgeDir, "core-sync-journal.json") });
26680
- if (recovery.status === "uncertain") throw new CoreSyncUncertainError(recovery.message, recovery.uncertainPaths);
26850
+ const result = await applyManifest(paths, credentials, manifest, {
26851
+ beforeCore: () => prepareLocalStartup(paths, credentials),
26852
+ afterCore: () => removeWellKnownAuth(paths, credentials)
26853
+ });
26854
+ await recordRollbackEvidencePlugin(paths, renderEvidencePlugin());
26855
+ return result;
26856
+ }
26857
+ async function prepareLocalStartup(paths, credentials) {
26681
26858
  let current;
26682
26859
  try {
26683
- current = JSON.parse(await readFile11(paths.opencodeConfigPath, "utf8"));
26860
+ current = JSON.parse(await readFile12(paths.opencodeConfigPath, "utf8"));
26684
26861
  } catch {
26685
26862
  throw new Error("A configura\xE7\xE3o local n\xE3o \xE9 JSON simples v\xE1lido; preserve os ficheiros e pe\xE7a apoio.");
26686
26863
  }
@@ -26692,14 +26869,10 @@ async function syncLocalWorker(paths, credentials, manifest) {
26692
26869
  throw new Error("A configura\xE7\xE3o local foi alterada ou a c\xF3pia v\xE1lida n\xE3o corresponde \xE0 credencial; preserve os ficheiros e pe\xE7a apoio.");
26693
26870
  }
26694
26871
  await installRecoveryLauncher(paths, credentials.forgeBaseUrl);
26695
- const result = await applyManifest(paths, credentials, manifest);
26696
- await removeWellKnownAuth(paths, credentials);
26697
- await recordRollbackEvidencePlugin(paths, renderEvidencePlugin());
26698
- return result;
26699
26872
  }
26700
26873
 
26701
26874
  // packages/cli/src/openworkEngine.ts
26702
- import { lstat as lstat6, readFile as readFile12, realpath } from "node:fs/promises";
26875
+ import { lstat as lstat6, readFile as readFile13, realpath } from "node:fs/promises";
26703
26876
  import path13 from "node:path";
26704
26877
  var OPENWORK_ENGINE_HEADER = "// Minimal Forge OpenWork engine configuration\n";
26705
26878
  async function inspectOpenworkEngineConfig(directory) {
@@ -26710,7 +26883,7 @@ async function inspectOpenworkEngineConfig(directory) {
26710
26883
  if (!generatedEntry.isFile() || generatedEntry.isSymbolicLink()) throw new Error("Preserve a configura\xE7\xE3o do motor; o ficheiro gerado n\xE3o \xE9 regular.");
26711
26884
  let generated;
26712
26885
  try {
26713
- generated = JSON.parse(await readFile12(generatedPath, "utf8"));
26886
+ generated = JSON.parse(await readFile13(generatedPath, "utf8"));
26714
26887
  } catch {
26715
26888
  throw new Error("N\xE3o foi poss\xEDvel reconhecer a configura\xE7\xE3o do motor OpenCode 2.");
26716
26889
  }
@@ -26722,7 +26895,7 @@ async function inspectOpenworkEngineConfig(directory) {
26722
26895
  try {
26723
26896
  const entry = await lstat6(file2);
26724
26897
  if (!entry.isFile() || entry.isSymbolicLink()) throw new Error("Preserve o ficheiro complementar existente; n\xE3o \xE9 um ficheiro regular.");
26725
- content = await readFile12(file2, "utf8");
26898
+ content = await readFile13(file2, "utf8");
26726
26899
  } catch (error45) {
26727
26900
  if (error45.code !== "ENOENT") throw error45;
26728
26901
  }
@@ -26758,7 +26931,7 @@ async function writeOpenworkEngineConfig(directory, config2) {
26758
26931
  }
26759
26932
 
26760
26933
  // packages/cli/src/workPackSyncPlugin.ts
26761
- var PLUGIN_VERSION = "0.1.49";
26934
+ var PLUGIN_VERSION = "0.1.53";
26762
26935
  var FORGE_DECISION_TIMEOUT_MS = 11e4;
26763
26936
  var STATUS_FILENAME = "work-pack-startup-status.json";
26764
26937
  var activeSync = /* @__PURE__ */ new Map();
@@ -26797,7 +26970,7 @@ function createEvidenceReporters(forgeBaseUrl, state) {
26797
26970
  report(sessionID, callID, slug, kind);
26798
26971
  };
26799
26972
  const reportReasoningLoop = (sessionID, outcome) => {
26800
- reportEvidence(sessionID, `reasoning-loop:${randomUUID4()}`, outcome, "reasoning_loop").catch(() => {
26973
+ reportEvidence(sessionID, `reasoning-loop:${randomUUID5()}`, outcome, "reasoning_loop").catch(() => {
26801
26974
  console.error("[Forge evidence] Reasoning guard identity unavailable; event not queued");
26802
26975
  });
26803
26976
  };
@@ -26805,7 +26978,7 @@ function createEvidenceReporters(forgeBaseUrl, state) {
26805
26978
  const slug = typeof name === "string" ? name.trim().toLowerCase() : "";
26806
26979
  if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug)) return;
26807
26980
  try {
26808
- await readFile13(path14.join(state.paths.skillsDir, slug, ".forge-version"), "utf8");
26981
+ await readFile14(path14.join(state.paths.skillsDir, slug, ".forge-version"), "utf8");
26809
26982
  } catch {
26810
26983
  return;
26811
26984
  }
@@ -26839,10 +27012,10 @@ var ForgeWorkPackSyncServer = async (_input, options) => {
26839
27012
  const name = Array.isArray(entry) ? entry[0] : entry;
26840
27013
  return name === legacyPath || name === pathToFileURL(legacyPath).href;
26841
27014
  });
26842
- const legacy = registered ? await readFile13(legacyPath, "utf8").catch(() => "") : "";
27015
+ const legacy = registered ? await readFile14(legacyPath, "utf8").catch(() => "") : "";
26843
27016
  const oldLegacyRegistered = registered && legacy.startsWith(FORGE_PLUGIN_HEADER) && legacy.includes("work_pack_invocation") && !legacy.includes("minimal-forge.skill-usage.v1");
26844
27017
  if (oldLegacyRegistered) legacyOwners.add(legacyOwnerKey);
26845
- if (oldLegacyRegistered) await writeFile8(legacyPath, renderEvidencePlugin()).catch(() => {
27018
+ if (oldLegacyRegistered) await writeFile9(legacyPath, renderEvidencePlugin()).catch(() => {
26846
27019
  console.error("[Forge evidence] Legacy hook upgrade failed; existing hook retained");
26847
27020
  });
26848
27021
  await projectCurrentExtensions(config2, state);
@@ -26864,9 +27037,15 @@ async function ForgeWorkPackSyncSetup(ctx) {
26864
27037
  throw new Error("A pasta do motor ativo mudou. Confirme a liga\xE7\xE3o Forge neste perfil do OpenWork.");
26865
27038
  }
26866
27039
  const credentials = await readForgeCredentials(state.paths, forgeBaseUrl);
26867
- const canonical = objectRecord2(parseJsonc(await readFile13(state.paths.opencodeConfigPath, "utf8")));
27040
+ const canonical = objectRecord2(parseJsonc(await readFile14(state.paths.opencodeConfigPath, "utf8")));
26868
27041
  const config2 = renderOpenworkEngineConfig(state.manifest, credentials, state.paths, directory, canonical);
26869
- await projectCurrentExtensions(config2, state);
27042
+ if (state.partialWorkPackSync) {
27043
+ const companion = await inspectOpenworkEngineConfig(directory);
27044
+ if (!companion.content) return createForgeTools(forgeBaseUrl, state);
27045
+ await refreshPartialProjections(config2, parseJsonc(companion.content), state.paths, state.before, state.partialWorkPackSync);
27046
+ } else {
27047
+ await projectCurrentExtensions(config2, state);
27048
+ }
26870
27049
  for (const key of ["agent", "command"]) if (Object.keys(objectRecord2(config2[key])).length === 0) delete config2[key];
26871
27050
  await writeOpenworkEngineConfig(directory, config2);
26872
27051
  }
@@ -26913,10 +27092,10 @@ function createForgeImageTool(forgeBaseUrl, gatewayBaseUrl, paths) {
26913
27092
  referencePath: tool.schema.string().optional().describe("Caminho absoluto de uma imagem PNG, JPEG ou WebP a editar, at\xE9 2,5 MB")
26914
27093
  },
26915
27094
  async execute(args, context) {
26916
- const requestId = randomUUID4();
27095
+ const requestId = randomUUID5();
26917
27096
  let referenceDataUrl;
26918
27097
  if (args.referencePath) {
26919
- const bytes = await readFile13(args.referencePath);
27098
+ const bytes = await readFile14(args.referencePath);
26920
27099
  if (bytes.byteLength > 25e5) throw new Error("A imagem de refer\xEAncia \xE9 demasiado grande. Reduza-a antes de tentar novamente.");
26921
27100
  const mime = bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])) ? "image/png" : bytes.subarray(0, 3).equals(Buffer.from([255, 216, 255])) ? "image/jpeg" : bytes.subarray(0, 4).toString() === "RIFF" && bytes.subarray(8, 12).toString() === "WEBP" ? "image/webp" : void 0;
26922
27101
  if (!mime) throw new Error("A refer\xEAncia tem de ser PNG, JPEG ou WebP.");
@@ -26943,7 +27122,7 @@ function createForgeImageTool(forgeBaseUrl, gatewayBaseUrl, paths) {
26943
27122
  throw new Error(`O PNG recebido \xE9 inv\xE1lido. Refer\xEAncia: ${requestId}`);
26944
27123
  }
26945
27124
  const destination = path14.join(context.directory, `forge-image-${requestId}.png`);
26946
- await writeFile8(destination, image, { flag: "wx" });
27125
+ await writeFile9(destination, image, { flag: "wx" });
26947
27126
  const reset = body.quota && new Intl.DateTimeFormat("pt-PT", { dateStyle: "long", timeZone: "Europe/Lisbon" }).format(new Date(body.quota.resetsAt));
26948
27127
  const remaining = body.quota ? ` Restam ${body.quota.remaining} imagens at\xE9 ${reset}.` : "";
26949
27128
  return {
@@ -26993,7 +27172,7 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseD
26993
27172
  const file2 = await fileInsideWorkspace(context.directory, args.request_file);
26994
27173
  const planFile = path14.join(path14.dirname(path14.dirname(file2)), "plan.json");
26995
27174
  if (!responseDirectory && path14.basename(path14.dirname(file2)) === "requests" && await fileExists(planFile)) {
26996
- const plan = JSON.parse(await readFile13(planFile, "utf8"));
27175
+ const plan = JSON.parse(await readFile14(planFile, "utf8"));
26997
27176
  if (plan?.engine === "jev-batch" && plan.model === "typesafe/jev-1.13" && Array.isArray(plan.batches)) {
26998
27177
  let batch;
26999
27178
  for (const candidate of plan.batches) {
@@ -27006,7 +27185,7 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseD
27006
27185
  return createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths).execute({ plan_file: planFile, batch_id: batch.batch_id }, context);
27007
27186
  }
27008
27187
  }
27009
- const raw = await readFile13(file2, "utf8");
27188
+ const raw = await readFile14(file2, "utf8");
27010
27189
  if (Buffer.byteLength(raw) > 512 * 1024) throw new Error("O ficheiro de pedido excede 512 KiB.");
27011
27190
  let parsed;
27012
27191
  try {
@@ -27030,8 +27209,8 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseD
27030
27209
  try {
27031
27210
  const credentials = await readForgeCredentials(paths, forgeBaseUrl);
27032
27211
  const probeFile = path14.join(responseDir, ".write-test");
27033
- await writeFile8(probeFile, "", { flag: "wx", mode: 384 });
27034
- await unlink(probeFile);
27212
+ await writeFile9(probeFile, "", { flag: "wx", mode: 384 });
27213
+ await unlink2(probeFile);
27035
27214
  context.abort.throwIfAborted();
27036
27215
  await beforeCall?.(responseFile);
27037
27216
  const response = await fetch(`${decisionBaseUrl}/v1/decisions`, {
@@ -27052,7 +27231,7 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseD
27052
27231
  }
27053
27232
  if (response.ok && body && typeof body === "object" && body.answers && typeof body.answers === "object") {
27054
27233
  try {
27055
- await writeFile8(responseFile, raw, { flag: "wx", mode: 384 });
27234
+ await writeFile9(responseFile, raw, { flag: "wx", mode: 384 });
27056
27235
  return JSON.stringify({ ...body, response_file: responseFile }, null, 2);
27057
27236
  } catch (error45) {
27058
27237
  return JSON.stringify({
@@ -27072,7 +27251,7 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseD
27072
27251
  }
27073
27252
  throw new Error(safeError);
27074
27253
  } finally {
27075
- await rmdir(responseDir).catch(() => void 0);
27254
+ await rmdir2(responseDir).catch(() => void 0);
27076
27255
  }
27077
27256
  }
27078
27257
  });
@@ -27093,7 +27272,7 @@ async function fileExists(candidate) {
27093
27272
  throw error45;
27094
27273
  }
27095
27274
  }
27096
- async function ensureJevDirectory(directory, filesystem = { stat: stat3, mkdir: mkdir7 }) {
27275
+ async function ensureJevDirectory(directory, filesystem = { stat: stat3, mkdir: mkdir8 }) {
27097
27276
  try {
27098
27277
  if ((await filesystem.stat(directory)).isDirectory()) return;
27099
27278
  throw new Error(`O destino ${path14.basename(directory)} existe, mas n\xE3o \xE9 uma pasta. Preservar o conte\xFAdo e verificar o caminho.`);
@@ -27116,7 +27295,7 @@ function canonicalJson(value) {
27116
27295
  return JSON.stringify(value);
27117
27296
  }
27118
27297
  async function validateSavedDecision(file2, request) {
27119
- const body = JSON.parse(await readFile13(file2, "utf8"));
27298
+ const body = JSON.parse(await readFile14(file2, "utf8"));
27120
27299
  const answers = body.answers;
27121
27300
  const questions = request.questions;
27122
27301
  const usage = body.usage;
@@ -27127,7 +27306,7 @@ async function validateSavedDecision(file2, request) {
27127
27306
  }
27128
27307
  async function acquireJevRunLock(lockDir) {
27129
27308
  try {
27130
- await mkdir7(lockDir);
27309
+ await mkdir8(lockDir);
27131
27310
  return {};
27132
27311
  } catch (error45) {
27133
27312
  if (error45.code !== "EEXIST") throw error45;
@@ -27135,7 +27314,7 @@ async function acquireJevRunLock(lockDir) {
27135
27314
  let owner;
27136
27315
  let ownerRaw;
27137
27316
  try {
27138
- ownerRaw = await readFile13(path14.join(lockDir, "owner.json"), "utf8");
27317
+ ownerRaw = await readFile14(path14.join(lockDir, "owner.json"), "utf8");
27139
27318
  owner = JSON.parse(ownerRaw);
27140
27319
  } catch {
27141
27320
  throw new Error("Chamada interrompida com lock sem identifica\xE7\xE3o; n\xE3o \xE9 poss\xEDvel confirmar que terminou. Preservar o lock e verificar a execu\xE7\xE3o.");
@@ -27148,9 +27327,9 @@ async function acquireJevRunLock(lockDir) {
27148
27327
  } catch (error45) {
27149
27328
  if (error45.code === "ESRCH") {
27150
27329
  const archived = `${lockDir}.interrupted-${createHash7("sha256").update(ownerRaw).digest("hex")}`;
27151
- await rename8(lockDir, archived);
27330
+ await rename9(lockDir, archived);
27152
27331
  try {
27153
- await mkdir7(lockDir);
27332
+ await mkdir8(lockDir);
27154
27333
  } catch {
27155
27334
  throw new Error("Este plano j\xE1 est\xE1 em execu\xE7\xE3o; a recupera\xE7\xE3o ficou preservada.");
27156
27335
  }
@@ -27171,7 +27350,7 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
27171
27350
  const planFile = await fileInsideWorkspace(context.directory, args.plan_file);
27172
27351
  if (path14.basename(planFile) !== "plan.json" || path14.basename(path14.dirname(planFile)) !== "jev") throw new Error("Indica o ficheiro jev/plan.json.");
27173
27352
  const runDir = path14.dirname(path14.dirname(planFile));
27174
- const plan = JSON.parse(await readFile13(planFile, "utf8"));
27353
+ const plan = JSON.parse(await readFile14(planFile, "utf8"));
27175
27354
  if (plan.engine !== "jev-batch" || plan.model !== "typesafe/jev-1.13" || !Array.isArray(plan.batches)) throw new Error("O plano Jev \xE9 inv\xE1lido.");
27176
27355
  const allBatches = plan.batches;
27177
27356
  const batches = args.batch_id ? allBatches.filter((batch) => batch.batch_id === args.batch_id) : allBatches;
@@ -27203,7 +27382,7 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
27203
27382
  const responseFile = path14.join(responseDir, `${batchId}.response.json`);
27204
27383
  const requestFile = await fileInsideWorkspace(context.directory, batch.request_file);
27205
27384
  if (path14.dirname(requestFile) !== path14.join(runDir, "jev", "requests")) throw new Error(`${batchId}: pedido fora do run.`);
27206
- const request = JSON.parse(await readFile13(requestFile, "utf8"));
27385
+ const request = JSON.parse(await readFile14(requestFile, "utf8"));
27207
27386
  const fingerprint = createHash7("sha256").update(canonicalJson(request)).digest("hex");
27208
27387
  if (fingerprint !== batch.request_fingerprint) throw new Error(`${batchId}: fingerprint do pedido n\xE3o corresponde ao plano.`);
27209
27388
  if (await fileExists(acceptedFile)) {
@@ -27218,7 +27397,7 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
27218
27397
  }
27219
27398
  const attemptsFile = path14.join(attemptsDir, `${batchId}.json`);
27220
27399
  let attempts = { request_fingerprint: fingerprint, attempts: 0, response_files: [] };
27221
- if (await fileExists(attemptsFile)) attempts = JSON.parse(await readFile13(attemptsFile, "utf8"));
27400
+ if (await fileExists(attemptsFile)) attempts = JSON.parse(await readFile14(attemptsFile, "utf8"));
27222
27401
  else if (interrupted.batch_id === batchId) {
27223
27402
  if (interrupted.request_fingerprint !== fingerprint) throw new Error(`${batchId}: fingerprint da chamada interrompida n\xE3o corresponde ao plano.`);
27224
27403
  attempts.attempts = 1;
@@ -27231,7 +27410,7 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
27231
27410
  if (!await fileExists(attemptsFile) && attempts.attempts > 0) await persistAttempts();
27232
27411
  const stop = (error45, detail = {}) => JSON.stringify({ verified: false, saved, skipped, recovered, repeated, stopped_at: batchId, ...detail, error: error45 });
27233
27412
  const recoverResponse = async () => {
27234
- const legacyAllocations = interrupted.batch_id === batchId && interrupted.request_fingerprint === fingerprint ? (await readdir6(responseDir)).filter((name) => name.startsWith(".forge-decision-")).map((name) => path14.join(responseDir, name, "response.json")) : [];
27413
+ const legacyAllocations = interrupted.batch_id === batchId && interrupted.request_fingerprint === fingerprint ? (await readdir7(responseDir)).filter((name) => name.startsWith(".forge-decision-")).map((name) => path14.join(responseDir, name, "response.json")) : [];
27235
27414
  const candidates = [...attempts.response_files, ...legacyAllocations];
27236
27415
  for (const candidate of new Set(candidates)) {
27237
27416
  if (typeof candidate !== "string") throw new Error("Registo de recupera\xE7\xE3o inv\xE1lido.");
@@ -27296,7 +27475,7 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
27296
27475
  let identical = false;
27297
27476
  if (error45.code === "EEXIST") {
27298
27477
  try {
27299
- identical = await readFile13(source, "utf8") === await readFile13(responseFile, "utf8");
27478
+ identical = await readFile14(source, "utf8") === await readFile14(responseFile, "utf8");
27300
27479
  } catch {
27301
27480
  }
27302
27481
  }
@@ -27304,7 +27483,7 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
27304
27483
  return stop("Resposta conclu\xEDda mas n\xE3o guardada no destino do lote; resolver a grava\xE7\xE3o e retomar sem nova chamada.", { recovery_file: source, persistence_code: error45.code });
27305
27484
  }
27306
27485
  }
27307
- await unlink(source).then(() => rmdir(path14.dirname(source))).catch(() => void 0);
27486
+ await unlink2(source).then(() => rmdir2(path14.dirname(source))).catch(() => void 0);
27308
27487
  saved++;
27309
27488
  if (args.batch_id) return JSON.stringify({ ...await validateSavedDecision(responseFile, request), response_file: responseFile, repeated });
27310
27489
  }
@@ -27387,6 +27566,7 @@ async function synchronizeAtStartup(forgeBaseUrl, observe, localConfig, input) {
27387
27566
  const before = await managedProjectionNames(paths);
27388
27567
  let credentials;
27389
27568
  let forgeConfigVerified = false;
27569
+ let appliedLocalSync;
27390
27570
  let pluginUpdate;
27391
27571
  let decisionBaseUrl = forgeBaseUrl;
27392
27572
  const runtime = await observe();
@@ -27398,7 +27578,8 @@ async function synchronizeAtStartup(forgeBaseUrl, observe, localConfig, input) {
27398
27578
  forgeConfigVerified = true;
27399
27579
  const result = localConfig ? await syncLocalWorker(paths, credentials, manifest) : await applyWorkPackManifest(paths, credentials, manifest, {});
27400
27580
  if (localConfig) {
27401
- const config2 = objectRecord2(parseJsonc(await readFile13(paths.opencodeConfigPath, "utf8")));
27581
+ appliedLocalSync = { manifest, partialWorkPackSync: result };
27582
+ const config2 = objectRecord2(parseJsonc(await readFile14(paths.opencodeConfigPath, "utf8")));
27402
27583
  const targetVersion = configuredWorkPackSyncPluginVersion(config2);
27403
27584
  if (targetVersion) pluginUpdate = { targetVersion, restartRequired: targetVersion !== PLUGIN_VERSION };
27404
27585
  if (pluginUpdate?.restartRequired) {
@@ -27445,12 +27626,12 @@ async function synchronizeAtStartup(forgeBaseUrl, observe, localConfig, input) {
27445
27626
  decisionBaseUrl = await savedGatewayBaseUrl(paths, credentials, forgeBaseUrl) ?? decisionBaseUrl;
27446
27627
  }
27447
27628
  const after = await managedProjectionNames(paths).catch(() => before);
27448
- return { paths, before, after, forgeConfigVerified, decisionBaseUrl };
27629
+ return { paths, before, after, forgeConfigVerified, decisionBaseUrl, ...appliedLocalSync };
27449
27630
  }
27450
27631
  }
27451
27632
  async function savedGatewayBaseUrl(paths, credentials, forgeBaseUrl) {
27452
27633
  try {
27453
- const config2 = objectRecord2(parseJsonc(await readFile13(paths.opencodeConfigPath, "utf8")));
27634
+ const config2 = objectRecord2(parseJsonc(await readFile14(paths.opencodeConfigPath, "utf8")));
27454
27635
  const options = objectRecord2(objectRecord2(objectRecord2(config2.provider).forge).options);
27455
27636
  if (options.apiKey !== credentials.forgeApiKey || typeof options.baseURL !== "string" || !options.baseURL.endsWith("/v1")) return void 0;
27456
27637
  const origin = options.baseURL.slice(0, -"/v1".length);
@@ -27475,7 +27656,7 @@ function resolveStartupPaths() {
27475
27656
  return resolvePaths(void 0, void 0, env);
27476
27657
  }
27477
27658
  async function readForgeCredentials(paths, forgeBaseUrl) {
27478
- const raw = await readFile13(paths.opencodeAuthPath, "utf8").catch((error45) => {
27659
+ const raw = await readFile14(paths.opencodeAuthPath, "utf8").catch((error45) => {
27479
27660
  if (error45.code === "ENOENT") return void 0;
27480
27661
  throw error45;
27481
27662
  });
@@ -27519,12 +27700,12 @@ function objectRecord2(value) {
27519
27700
  return value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
27520
27701
  }
27521
27702
  async function writeStatus(paths, value) {
27522
- await mkdir7(paths.forgeDir, { recursive: true });
27703
+ await mkdir8(paths.forgeDir, { recursive: true });
27523
27704
  const target = path14.join(paths.forgeDir, STATUS_FILENAME);
27524
27705
  const temporary = path14.join(paths.forgeDir, `.${STATUS_FILENAME}.${process.pid}.tmp`);
27525
- await writeFile8(temporary, `${JSON.stringify(value, null, 2)}
27706
+ await writeFile9(temporary, `${JSON.stringify(value, null, 2)}
27526
27707
  `, { mode: 384 });
27527
- await rename8(temporary, target);
27708
+ await rename9(temporary, target);
27528
27709
  }
27529
27710
  function safeErrorMessage(error45) {
27530
27711
  const message = error45 instanceof Error ? error45.message : "erro desconhecido";