minimal-forge-work-pack-sync 0.1.34 → 0.1.35

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 +1388 -333
  2. package/dist/repair.js +4385 -0
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -117,17 +117,17 @@ var require_visit = __commonJS({
117
117
  visit.BREAK = BREAK;
118
118
  visit.SKIP = SKIP;
119
119
  visit.REMOVE = REMOVE;
120
- function visit_(key, node, visitor, path7) {
121
- const ctrl = callVisitor(key, node, visitor, path7);
120
+ function visit_(key, node, visitor, path12) {
121
+ const ctrl = callVisitor(key, node, visitor, path12);
122
122
  if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
123
- replaceNode(key, path7, ctrl);
124
- return visit_(key, ctrl, visitor, path7);
123
+ replaceNode(key, path12, ctrl);
124
+ return visit_(key, ctrl, visitor, path12);
125
125
  }
126
126
  if (typeof ctrl !== "symbol") {
127
127
  if (identity.isCollection(node)) {
128
- path7 = Object.freeze(path7.concat(node));
128
+ path12 = Object.freeze(path12.concat(node));
129
129
  for (let i = 0; i < node.items.length; ++i) {
130
- const ci2 = visit_(i, node.items[i], visitor, path7);
130
+ const ci2 = visit_(i, node.items[i], visitor, path12);
131
131
  if (typeof ci2 === "number")
132
132
  i = ci2 - 1;
133
133
  else if (ci2 === BREAK)
@@ -138,13 +138,13 @@ var require_visit = __commonJS({
138
138
  }
139
139
  }
140
140
  } else if (identity.isPair(node)) {
141
- path7 = Object.freeze(path7.concat(node));
142
- const ck = visit_("key", node.key, visitor, path7);
141
+ path12 = Object.freeze(path12.concat(node));
142
+ const ck = visit_("key", node.key, visitor, path12);
143
143
  if (ck === BREAK)
144
144
  return BREAK;
145
145
  else if (ck === REMOVE)
146
146
  node.key = null;
147
- const cv = visit_("value", node.value, visitor, path7);
147
+ const cv = visit_("value", node.value, visitor, path12);
148
148
  if (cv === BREAK)
149
149
  return BREAK;
150
150
  else if (cv === REMOVE)
@@ -165,17 +165,17 @@ var require_visit = __commonJS({
165
165
  visitAsync.BREAK = BREAK;
166
166
  visitAsync.SKIP = SKIP;
167
167
  visitAsync.REMOVE = REMOVE;
168
- async function visitAsync_(key, node, visitor, path7) {
169
- const ctrl = await callVisitor(key, node, visitor, path7);
168
+ async function visitAsync_(key, node, visitor, path12) {
169
+ const ctrl = await callVisitor(key, node, visitor, path12);
170
170
  if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
171
- replaceNode(key, path7, ctrl);
172
- return visitAsync_(key, ctrl, visitor, path7);
171
+ replaceNode(key, path12, ctrl);
172
+ return visitAsync_(key, ctrl, visitor, path12);
173
173
  }
174
174
  if (typeof ctrl !== "symbol") {
175
175
  if (identity.isCollection(node)) {
176
- path7 = Object.freeze(path7.concat(node));
176
+ path12 = Object.freeze(path12.concat(node));
177
177
  for (let i = 0; i < node.items.length; ++i) {
178
- const ci2 = await visitAsync_(i, node.items[i], visitor, path7);
178
+ const ci2 = await visitAsync_(i, node.items[i], visitor, path12);
179
179
  if (typeof ci2 === "number")
180
180
  i = ci2 - 1;
181
181
  else if (ci2 === BREAK)
@@ -186,13 +186,13 @@ var require_visit = __commonJS({
186
186
  }
187
187
  }
188
188
  } else if (identity.isPair(node)) {
189
- path7 = Object.freeze(path7.concat(node));
190
- const ck = await visitAsync_("key", node.key, visitor, path7);
189
+ path12 = Object.freeze(path12.concat(node));
190
+ const ck = await visitAsync_("key", node.key, visitor, path12);
191
191
  if (ck === BREAK)
192
192
  return BREAK;
193
193
  else if (ck === REMOVE)
194
194
  node.key = null;
195
- const cv = await visitAsync_("value", node.value, visitor, path7);
195
+ const cv = await visitAsync_("value", node.value, visitor, path12);
196
196
  if (cv === BREAK)
197
197
  return BREAK;
198
198
  else if (cv === REMOVE)
@@ -219,23 +219,23 @@ var require_visit = __commonJS({
219
219
  }
220
220
  return visitor;
221
221
  }
222
- function callVisitor(key, node, visitor, path7) {
222
+ function callVisitor(key, node, visitor, path12) {
223
223
  if (typeof visitor === "function")
224
- return visitor(key, node, path7);
224
+ return visitor(key, node, path12);
225
225
  if (identity.isMap(node))
226
- return visitor.Map?.(key, node, path7);
226
+ return visitor.Map?.(key, node, path12);
227
227
  if (identity.isSeq(node))
228
- return visitor.Seq?.(key, node, path7);
228
+ return visitor.Seq?.(key, node, path12);
229
229
  if (identity.isPair(node))
230
- return visitor.Pair?.(key, node, path7);
230
+ return visitor.Pair?.(key, node, path12);
231
231
  if (identity.isScalar(node))
232
- return visitor.Scalar?.(key, node, path7);
232
+ return visitor.Scalar?.(key, node, path12);
233
233
  if (identity.isAlias(node))
234
- return visitor.Alias?.(key, node, path7);
234
+ return visitor.Alias?.(key, node, path12);
235
235
  return void 0;
236
236
  }
237
- function replaceNode(key, path7, node) {
238
- const parent = path7[path7.length - 1];
237
+ function replaceNode(key, path12, node) {
238
+ const parent = path12[path12.length - 1];
239
239
  if (identity.isCollection(parent)) {
240
240
  parent.items[key] = node;
241
241
  } else if (identity.isPair(parent)) {
@@ -847,10 +847,10 @@ var require_Collection = __commonJS({
847
847
  var createNode = require_createNode();
848
848
  var identity = require_identity();
849
849
  var Node = require_Node();
850
- function collectionFromPath(schema, path7, value) {
850
+ function collectionFromPath(schema, path12, value) {
851
851
  let v2 = value;
852
- for (let i = path7.length - 1; i >= 0; --i) {
853
- const k2 = path7[i];
852
+ for (let i = path12.length - 1; i >= 0; --i) {
853
+ const k2 = path12[i];
854
854
  if (typeof k2 === "number" && Number.isInteger(k2) && k2 >= 0) {
855
855
  const a = [];
856
856
  a[k2] = v2;
@@ -869,7 +869,7 @@ var require_Collection = __commonJS({
869
869
  sourceObjects: /* @__PURE__ */ new Map()
870
870
  });
871
871
  }
872
- var isEmptyPath = (path7) => path7 == null || typeof path7 === "object" && !!path7[Symbol.iterator]().next().done;
872
+ var isEmptyPath = (path12) => path12 == null || typeof path12 === "object" && !!path12[Symbol.iterator]().next().done;
873
873
  var Collection = class extends Node.NodeBase {
874
874
  constructor(type, schema) {
875
875
  super(type);
@@ -899,11 +899,11 @@ var require_Collection = __commonJS({
899
899
  * be a Pair instance or a `{ key, value }` object, which may not have a key
900
900
  * that already exists in the map.
901
901
  */
902
- addIn(path7, value) {
903
- if (isEmptyPath(path7))
902
+ addIn(path12, value) {
903
+ if (isEmptyPath(path12))
904
904
  this.add(value);
905
905
  else {
906
- const [key, ...rest] = path7;
906
+ const [key, ...rest] = path12;
907
907
  const node = this.get(key, true);
908
908
  if (identity.isCollection(node))
909
909
  node.addIn(rest, value);
@@ -917,8 +917,8 @@ var require_Collection = __commonJS({
917
917
  * Removes a value from the collection.
918
918
  * @returns `true` if the item was found and removed.
919
919
  */
920
- deleteIn(path7) {
921
- const [key, ...rest] = path7;
920
+ deleteIn(path12) {
921
+ const [key, ...rest] = path12;
922
922
  if (rest.length === 0)
923
923
  return this.delete(key);
924
924
  const node = this.get(key, true);
@@ -932,8 +932,8 @@ var require_Collection = __commonJS({
932
932
  * scalar values from their surrounding node; to disable set `keepScalar` to
933
933
  * `true` (collections are always returned intact).
934
934
  */
935
- getIn(path7, keepScalar) {
936
- const [key, ...rest] = path7;
935
+ getIn(path12, keepScalar) {
936
+ const [key, ...rest] = path12;
937
937
  const node = this.get(key, true);
938
938
  if (rest.length === 0)
939
939
  return !keepScalar && identity.isScalar(node) ? node.value : node;
@@ -951,8 +951,8 @@ var require_Collection = __commonJS({
951
951
  /**
952
952
  * Checks if the collection includes a value with the key `key`.
953
953
  */
954
- hasIn(path7) {
955
- const [key, ...rest] = path7;
954
+ hasIn(path12) {
955
+ const [key, ...rest] = path12;
956
956
  if (rest.length === 0)
957
957
  return this.has(key);
958
958
  const node = this.get(key, true);
@@ -962,8 +962,8 @@ var require_Collection = __commonJS({
962
962
  * Sets a value in this collection. For `!!set`, `value` needs to be a
963
963
  * boolean to add/remove the item from the set.
964
964
  */
965
- setIn(path7, value) {
966
- const [key, ...rest] = path7;
965
+ setIn(path12, value) {
966
+ const [key, ...rest] = path12;
967
967
  if (rest.length === 0) {
968
968
  this.set(key, value);
969
969
  } else {
@@ -3478,9 +3478,9 @@ var require_Document = __commonJS({
3478
3478
  this.contents.add(value);
3479
3479
  }
3480
3480
  /** Adds a value to the document. */
3481
- addIn(path7, value) {
3481
+ addIn(path12, value) {
3482
3482
  if (assertCollection(this.contents))
3483
- this.contents.addIn(path7, value);
3483
+ this.contents.addIn(path12, value);
3484
3484
  }
3485
3485
  /**
3486
3486
  * Create a new `Alias` node, ensuring that the target `node` has the required anchor.
@@ -3555,14 +3555,14 @@ var require_Document = __commonJS({
3555
3555
  * Removes a value from the document.
3556
3556
  * @returns `true` if the item was found and removed.
3557
3557
  */
3558
- deleteIn(path7) {
3559
- if (Collection.isEmptyPath(path7)) {
3558
+ deleteIn(path12) {
3559
+ if (Collection.isEmptyPath(path12)) {
3560
3560
  if (this.contents == null)
3561
3561
  return false;
3562
3562
  this.contents = null;
3563
3563
  return true;
3564
3564
  }
3565
- return assertCollection(this.contents) ? this.contents.deleteIn(path7) : false;
3565
+ return assertCollection(this.contents) ? this.contents.deleteIn(path12) : false;
3566
3566
  }
3567
3567
  /**
3568
3568
  * Returns item at `key`, or `undefined` if not found. By default unwraps
@@ -3577,10 +3577,10 @@ var require_Document = __commonJS({
3577
3577
  * scalar values from their surrounding node; to disable set `keepScalar` to
3578
3578
  * `true` (collections are always returned intact).
3579
3579
  */
3580
- getIn(path7, keepScalar) {
3581
- if (Collection.isEmptyPath(path7))
3580
+ getIn(path12, keepScalar) {
3581
+ if (Collection.isEmptyPath(path12))
3582
3582
  return !keepScalar && identity.isScalar(this.contents) ? this.contents.value : this.contents;
3583
- return identity.isCollection(this.contents) ? this.contents.getIn(path7, keepScalar) : void 0;
3583
+ return identity.isCollection(this.contents) ? this.contents.getIn(path12, keepScalar) : void 0;
3584
3584
  }
3585
3585
  /**
3586
3586
  * Checks if the document includes a value with the key `key`.
@@ -3591,10 +3591,10 @@ var require_Document = __commonJS({
3591
3591
  /**
3592
3592
  * Checks if the document includes a value at `path`.
3593
3593
  */
3594
- hasIn(path7) {
3595
- if (Collection.isEmptyPath(path7))
3594
+ hasIn(path12) {
3595
+ if (Collection.isEmptyPath(path12))
3596
3596
  return this.contents !== void 0;
3597
- return identity.isCollection(this.contents) ? this.contents.hasIn(path7) : false;
3597
+ return identity.isCollection(this.contents) ? this.contents.hasIn(path12) : false;
3598
3598
  }
3599
3599
  /**
3600
3600
  * Sets a value in this document. For `!!set`, `value` needs to be a
@@ -3611,13 +3611,13 @@ var require_Document = __commonJS({
3611
3611
  * Sets a value in this document. For `!!set`, `value` needs to be a
3612
3612
  * boolean to add/remove the item from the set.
3613
3613
  */
3614
- setIn(path7, value) {
3615
- if (Collection.isEmptyPath(path7)) {
3614
+ setIn(path12, value) {
3615
+ if (Collection.isEmptyPath(path12)) {
3616
3616
  this.contents = value;
3617
3617
  } else if (this.contents == null) {
3618
- this.contents = Collection.collectionFromPath(this.schema, Array.from(path7), value);
3618
+ this.contents = Collection.collectionFromPath(this.schema, Array.from(path12), value);
3619
3619
  } else if (assertCollection(this.contents)) {
3620
- this.contents.setIn(path7, value);
3620
+ this.contents.setIn(path12, value);
3621
3621
  }
3622
3622
  }
3623
3623
  /**
@@ -5578,9 +5578,9 @@ var require_cst_visit = __commonJS({
5578
5578
  visit.BREAK = BREAK;
5579
5579
  visit.SKIP = SKIP;
5580
5580
  visit.REMOVE = REMOVE;
5581
- visit.itemAtPath = (cst, path7) => {
5581
+ visit.itemAtPath = (cst, path12) => {
5582
5582
  let item = cst;
5583
- for (const [field, index] of path7) {
5583
+ for (const [field, index] of path12) {
5584
5584
  const tok = item?.[field];
5585
5585
  if (tok && "items" in tok) {
5586
5586
  item = tok.items[index];
@@ -5589,23 +5589,23 @@ var require_cst_visit = __commonJS({
5589
5589
  }
5590
5590
  return item;
5591
5591
  };
5592
- visit.parentCollection = (cst, path7) => {
5593
- const parent = visit.itemAtPath(cst, path7.slice(0, -1));
5594
- const field = path7[path7.length - 1][0];
5592
+ visit.parentCollection = (cst, path12) => {
5593
+ const parent = visit.itemAtPath(cst, path12.slice(0, -1));
5594
+ const field = path12[path12.length - 1][0];
5595
5595
  const coll = parent?.[field];
5596
5596
  if (coll && "items" in coll)
5597
5597
  return coll;
5598
5598
  throw new Error("Parent collection not found");
5599
5599
  };
5600
- function _visit(path7, item, visitor) {
5601
- let ctrl = visitor(item, path7);
5600
+ function _visit(path12, item, visitor) {
5601
+ let ctrl = visitor(item, path12);
5602
5602
  if (typeof ctrl === "symbol")
5603
5603
  return ctrl;
5604
5604
  for (const field of ["key", "value"]) {
5605
5605
  const token = item[field];
5606
5606
  if (token && "items" in token) {
5607
5607
  for (let i = 0; i < token.items.length; ++i) {
5608
- const ci2 = _visit(Object.freeze(path7.concat([[field, i]])), token.items[i], visitor);
5608
+ const ci2 = _visit(Object.freeze(path12.concat([[field, i]])), token.items[i], visitor);
5609
5609
  if (typeof ci2 === "number")
5610
5610
  i = ci2 - 1;
5611
5611
  else if (ci2 === BREAK)
@@ -5616,10 +5616,10 @@ var require_cst_visit = __commonJS({
5616
5616
  }
5617
5617
  }
5618
5618
  if (typeof ctrl === "function" && field === "key")
5619
- ctrl = ctrl(item, path7);
5619
+ ctrl = ctrl(item, path12);
5620
5620
  }
5621
5621
  }
5622
- return typeof ctrl === "function" ? ctrl(item, path7) : ctrl;
5622
+ return typeof ctrl === "function" ? ctrl(item, path12) : ctrl;
5623
5623
  }
5624
5624
  exports.visit = visit;
5625
5625
  }
@@ -7508,6 +7508,50 @@ var BUILT_IN_OPENROUTER_MODELS = [
7508
7508
  }
7509
7509
  ];
7510
7510
  var APPROVED_MODELS = BUILT_IN_OPENROUTER_MODELS.filter((model) => model.approvedByDefault).map(stripCatalogFlags);
7511
+ function knownOpenRouterModelMetadata(model) {
7512
+ const normalized = normalizeModelId(model).toLowerCase();
7513
+ if (isLegacyDirectZaiModelId(normalized)) return void 0;
7514
+ const builtIn = BUILT_IN_OPENROUTER_MODELS.find((candidate) => candidate.id.toLowerCase() === normalized);
7515
+ if (builtIn?.metadata) return structuredClone(builtIn.metadata);
7516
+ if (isLikelyReasoningModel(normalized)) {
7517
+ return {
7518
+ family: inferFamily(normalized),
7519
+ attachment: false,
7520
+ reasoning: true,
7521
+ temperature: true,
7522
+ tool_call: true,
7523
+ modalities: { input: ["text"], output: ["text"] }
7524
+ };
7525
+ }
7526
+ return void 0;
7527
+ }
7528
+ function knownModelMetadata(model) {
7529
+ return knownOpenRouterModelMetadata(model);
7530
+ }
7531
+ function modelInputSupport(model, modality) {
7532
+ const metadata = model.metadata ?? knownModelMetadata(model.id);
7533
+ if (!metadata) return "unknown";
7534
+ const input = metadata.modalities?.input;
7535
+ if (input) return input.includes(modality) ? "yes" : "no";
7536
+ if (modality === "image" && metadata.attachment === true) return "yes";
7537
+ if (modality === "image" && metadata.attachment === false) return "no";
7538
+ if (modality === "pdf" && metadata.attachment === true) return "unknown";
7539
+ if (modality === "pdf" && metadata.attachment === false) return "no";
7540
+ return "unknown";
7541
+ }
7542
+ function modelImageSupport(model) {
7543
+ return modelInputSupport(model, "image");
7544
+ }
7545
+ function modelPdfSupport(model) {
7546
+ return modelInputSupport(model, "pdf");
7547
+ }
7548
+ function normalizeModelId(model) {
7549
+ const trimmed = model.trim();
7550
+ return trimmed.startsWith("forge/") ? trimmed.slice("forge/".length) : trimmed;
7551
+ }
7552
+ function isLegacyDirectZaiModelId(model) {
7553
+ return /^zai-coding\/glm-[a-z0-9.-]+$/.test(normalizeModelId(model));
7554
+ }
7511
7555
  function cloneModel(model) {
7512
7556
  return {
7513
7557
  id: model.id,
@@ -7522,6 +7566,16 @@ function stripCatalogFlags(model) {
7522
7566
  const { approvedByDefault: _approvedByDefault, requiredInConfig: _requiredInConfig, ...approved } = model;
7523
7567
  return cloneModel(approved);
7524
7568
  }
7569
+ function isLikelyReasoningModel(model) {
7570
+ return model.includes("gpt-5") || /(^|\/)o[134](?:-|$)/.test(model) || model.includes("deepseek-r1") || model.includes("deepseek-reasoner") || model.includes("claude-sonnet-4") || model.includes("claude-opus-4") || model.includes("gemini-2.5") || model.includes("gemini-3");
7571
+ }
7572
+ function inferFamily(model) {
7573
+ if (model.includes("openai/") || model.includes("gpt-") || /(^|\/)o[134](?:-|$)/.test(model)) return "openai";
7574
+ if (model.includes("anthropic/") || model.includes("claude")) return "anthropic";
7575
+ if (model.includes("google/") || model.includes("gemini")) return "google";
7576
+ if (model.includes("deepseek")) return "deepseek";
7577
+ return void 0;
7578
+ }
7525
7579
  function openRouterReasoningVariants(efforts) {
7526
7580
  return Object.fromEntries(efforts.map((effort) => [effort, { reasoning: { effort } }]));
7527
7581
  }
@@ -7551,11 +7605,135 @@ var DEFAULT_DEBUG_TRACE_LIMITS = {
7551
7605
  };
7552
7606
 
7553
7607
  // packages/shared/src/contracts/settings.ts
7554
- var WORK_PACK_SYNC_PLUGIN_VERSION = "0.1.34";
7608
+ var DOCUMENT_READER_AGENT = "document-reader";
7609
+ var OPENROUTER_ALIAS_PROVIDER_NAME = "OpenRouter (via Forge)";
7610
+ var WORK_PACK_SYNC_PLUGIN_VERSION = "0.1.35";
7555
7611
  var WORK_PACK_SYNC_PLUGIN_PACKAGE = `minimal-forge-work-pack-sync@${WORK_PACK_SYNC_PLUGIN_VERSION}`;
7556
7612
  var WORK_PACK_SYNC_PLUGIN_FILENAME = `minimal-forge-work-pack-sync-${WORK_PACK_SYNC_PLUGIN_VERSION}.tgz`;
7557
7613
  var FIRECRAWL_KEYLESS_MCP_NAME = "firecrawl";
7614
+ var FIRECRAWL_KEYLESS_MCP_URL = "https://mcp.firecrawl.dev/v2/mcp";
7558
7615
  var FIRECRAWL_KEYLESS_PERMISSION = `${FIRECRAWL_KEYLESS_MCP_NAME}_*`;
7616
+ function mergeWorkerOpenCodeConfig(existing, manifest, forgeBaseUrl, forgeApiKey = "{env:FORGE_API_KEY}", options = {}) {
7617
+ const existingProvider = withoutLegacyForgeProviders(isRecord(existing.provider) ? existing.provider : {});
7618
+ const nextConfig = {
7619
+ ...existing
7620
+ };
7621
+ const permission = managedPermission(nextConfig.permission);
7622
+ delete nextConfig.permission;
7623
+ const mcp = isRecord(nextConfig.mcp) ? { ...nextConfig.mcp } : {};
7624
+ if (!(FIRECRAWL_KEYLESS_MCP_NAME in mcp)) {
7625
+ mcp[FIRECRAWL_KEYLESS_MCP_NAME] = {
7626
+ type: "remote",
7627
+ url: FIRECRAWL_KEYLESS_MCP_URL,
7628
+ enabled: true,
7629
+ oauth: false,
7630
+ timeout: 3e4
7631
+ };
7632
+ }
7633
+ delete nextConfig.mcp;
7634
+ const experimental = isRecord(nextConfig.experimental) ? { ...nextConfig.experimental } : {};
7635
+ delete nextConfig.experimental;
7636
+ if (!Array.isArray(nextConfig.instructions)) delete nextConfig.instructions;
7637
+ const forgeProvider = {
7638
+ npm: "@ai-sdk/openai-compatible",
7639
+ name: "Forge",
7640
+ options: {
7641
+ baseURL: `${manifest.gatewayBaseUrl ? normalizeGatewayBaseUrl(manifest.gatewayBaseUrl) : forgeBaseUrl.replace(/\/$/, "")}/v1`,
7642
+ apiKey: forgeApiKey
7643
+ },
7644
+ models: Object.fromEntries(
7645
+ manifest.config.models.map((model) => {
7646
+ const entry = normalizeManifestModel(model);
7647
+ return [entry.id, modelConfig(entry)];
7648
+ })
7649
+ )
7650
+ };
7651
+ const agents = isRecord(nextConfig.agent) ? { ...nextConfig.agent } : {};
7652
+ if (manifest.config.documentReaderModel) {
7653
+ agents[DOCUMENT_READER_AGENT] = documentReaderAgent(manifest.config.documentReaderModel);
7654
+ } else {
7655
+ delete agents[DOCUMENT_READER_AGENT];
7656
+ }
7657
+ delete nextConfig.agent;
7658
+ const plugins = (Array.isArray(nextConfig.plugin) ? nextConfig.plugin : []).filter((entry) => {
7659
+ if (options.removePluginPath && typeof entry === "string" && entry === options.removePluginPath) return false;
7660
+ const name = Array.isArray(entry) ? entry[0] : entry;
7661
+ return typeof name !== "string" || !/^minimal-forge-work-pack-sync@/.test(name);
7662
+ });
7663
+ if (options.automaticWorkPackSync) {
7664
+ plugins.push([
7665
+ WORK_PACK_SYNC_PLUGIN_PACKAGE,
7666
+ { forgeBaseUrl: forgeBaseUrl.replace(/\/$/, ""), ...options.localConfig ? { localConfig: true } : {} }
7667
+ ]);
7668
+ }
7669
+ delete nextConfig.plugin;
7670
+ return {
7671
+ ...nextConfig,
7672
+ $schema: "https://opencode.ai/config.json",
7673
+ share: "disabled",
7674
+ autoupdate: false,
7675
+ permission,
7676
+ mcp,
7677
+ experimental: {
7678
+ ...experimental,
7679
+ clickableFileReferences: true
7680
+ },
7681
+ model: `forge/${manifest.config.model}`,
7682
+ small_model: `forge/${manifest.config.small_model}`,
7683
+ provider: options.omitManagedProviders ? { ...existingProvider } : {
7684
+ ...existingProvider,
7685
+ forge: forgeProvider
7686
+ },
7687
+ ...Object.keys(agents).length > 0 ? { agent: agents } : {},
7688
+ ...plugins.length > 0 ? { plugin: plugins } : {}
7689
+ };
7690
+ }
7691
+ function managedPermission(value) {
7692
+ const existing = typeof value === "string" && ["allow", "ask", "deny"].includes(value) ? { "*": value } : isRecord(value) ? value : {};
7693
+ return {
7694
+ ...existing["*"] === "deny" ? {} : { [FIRECRAWL_KEYLESS_PERMISSION]: "ask" },
7695
+ ...existing,
7696
+ forge_decide: "allow",
7697
+ forge_decide_run: "allow",
7698
+ forge_generate_codebook: "allow",
7699
+ forge_feedback: "deny"
7700
+ };
7701
+ }
7702
+ function withoutLegacyForgeProviders(provider) {
7703
+ const next = { ...provider };
7704
+ delete next.forge;
7705
+ const openrouter = next.openrouter;
7706
+ if (isRecord(openrouter) && openrouter.name === OPENROUTER_ALIAS_PROVIDER_NAME) delete next.openrouter;
7707
+ return next;
7708
+ }
7709
+ function renderWorkerTuiConfig(manifest) {
7710
+ return {
7711
+ theme: manifest.config.theme
7712
+ };
7713
+ }
7714
+ function documentReaderAgent(documentReaderModel) {
7715
+ return {
7716
+ description: "L\xEA ficheiros de imagem (png, jpg, gif, webp) e PDFs, e descreve o que cont\xEAm. Use este agente sempre que for preciso ver uma imagem ou um PDF: d\xEA-lhe o caminho absoluto do ficheiro e pergunte o que precisa de saber.",
7717
+ mode: "subagent",
7718
+ model: `forge/${documentReaderModel}`,
7719
+ tools: { write: false, edit: false, bash: false }
7720
+ };
7721
+ }
7722
+ function isRecord(value) {
7723
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7724
+ }
7725
+ function normalizeManifestModel(model) {
7726
+ return typeof model === "string" ? { id: model, name: model } : model;
7727
+ }
7728
+ function modelConfig(model) {
7729
+ const metadata = model.metadata ?? knownModelMetadata(model.id) ?? {};
7730
+ const { limit, ...compatibleMetadata } = metadata;
7731
+ return {
7732
+ name: model.name,
7733
+ ...compatibleMetadata,
7734
+ ...limit && Number.isFinite(limit.context) && Number.isFinite(limit.output) ? { limit } : {}
7735
+ };
7736
+ }
7559
7737
  function normalizeGatewayBaseUrl(value) {
7560
7738
  const url2 = new URL(value);
7561
7739
  if (url2.protocol !== "https:" || url2.username || url2.password || url2.port || url2.pathname !== "/" || url2.search || url2.hash) {
@@ -7688,7 +7866,7 @@ async function probeHealth(url2, route, headers, healthyField, source) {
7688
7866
  }
7689
7867
 
7690
7868
  // packages/cli/src/workPackSyncPlugin.ts
7691
- import { createHash as createHash5, randomUUID as randomUUID2 } from "node:crypto";
7869
+ import { createHash as createHash6, randomUUID as randomUUID4 } from "node:crypto";
7692
7870
  import { pathToFileURL } from "node:url";
7693
7871
 
7694
7872
  // packages/cli/src/skillUsageReporter.ts
@@ -7760,7 +7938,75 @@ function skillUsageReporter(origin, credentialId, send) {
7760
7938
 
7761
7939
  // packages/cli/src/pluginWriter.ts
7762
7940
  var FORGE_PLUGIN_HEADER = "// Managed by Forge sync. Do not edit.";
7941
+ var FORGE_PLUGIN_FILENAME = "forge-attachment-bridge.js";
7763
7942
  var FORGE_EVIDENCE_PLUGIN_FILENAME = "forge-evidence.js";
7943
+ var FORGE_DEBUG_TRACE_PLUGIN_FILENAME = "forge-debug-trace.js";
7944
+ var IMAGE_MIMES = ["image/png", "image/jpeg", "image/gif", "image/webp"];
7945
+ var PDF_MIMES = ["application/pdf"];
7946
+ function attachmentBridgeRules(models) {
7947
+ const rules = {};
7948
+ for (const model of models.map((entry) => typeof entry === "string" ? { id: entry, name: entry } : entry)) {
7949
+ const unsupported = [
7950
+ ...modelImageSupport(model) === "no" ? IMAGE_MIMES : [],
7951
+ ...modelPdfSupport(model) === "no" ? PDF_MIMES : []
7952
+ ];
7953
+ if (unsupported.length > 0) rules[model.id] = unsupported;
7954
+ }
7955
+ return rules;
7956
+ }
7957
+ function renderAttachmentBridgePlugin(rules) {
7958
+ return `${FORGE_PLUGIN_HEADER}
7959
+ // Reescreve anexos bin\xE1rios como caminhos de ficheiros tempor\xE1rios para modelos que n\xE3o os conseguem ver,
7960
+ // para que o agente document-reader os possa ler. Em caso de erro, deixa a mensagem intacta.
7961
+ import { Buffer } from "node:buffer"
7962
+ import { mkdir, writeFile } from "node:fs/promises"
7963
+ import os from "node:os"
7964
+ import path from "node:path"
7965
+
7966
+ const BRIDGE_RULES = new Map(Object.entries(${JSON.stringify(rules)}))
7967
+ const BRIDGEABLE = new Set(["image/png", "image/jpeg", "image/gif", "image/webp", "application/pdf"])
7968
+ const EXT = { "image/png": ".png", "image/jpeg": ".jpg", "image/gif": ".gif", "image/webp": ".webp", "application/pdf": ".pdf" }
7969
+
7970
+ export const ForgeAttachmentBridge = async () => ({
7971
+ "chat.message": async (input, output) => {
7972
+ try {
7973
+ if (input?.model?.providerID !== "forge") return
7974
+ const unsupportedMimes = BRIDGE_RULES.get(input.model.modelID)
7975
+ if (!unsupportedMimes) return
7976
+ const parts = output?.parts
7977
+ if (!Array.isArray(parts)) return
7978
+ for (let i = 0; i < parts.length; i++) {
7979
+ const part = parts[i]
7980
+ if (!part || part.type !== "file") continue
7981
+ const mime = String(part.mime ?? "")
7982
+ if (!BRIDGEABLE.has(mime)) continue
7983
+ if (!unsupportedMimes.includes(mime)) continue
7984
+ const url = String(part.url ?? "")
7985
+ if (!url.startsWith("data:")) continue
7986
+ const comma = url.indexOf(",")
7987
+ if (comma === -1) continue
7988
+ const bytes = Buffer.from(url.slice(comma + 1), "base64")
7989
+ const dir = path.join(os.tmpdir(), "forge-attachments")
7990
+ await mkdir(dir, { recursive: true })
7991
+ const original = String(part.filename ?? "attachment").replace(/[^A-Za-z0-9._-]/g, "_")
7992
+ const unique = Date.now().toString(36) + "-" + i
7993
+ const filePath = path.join(dir, unique + "-" + original + (original.includes(".") ? "" : EXT[mime]))
7994
+ await writeFile(filePath, bytes)
7995
+ parts[i] = {
7996
+ id: part.id,
7997
+ sessionID: part.sessionID,
7998
+ messageID: part.messageID,
7999
+ type: "text",
8000
+ text: "[Ficheiro anexado guardado em " + filePath + "] Este modelo n\xE3o consegue ver este anexo diretamente. Use o agente document-reader com este caminho de ficheiro para o ler e depois continue com o pedido do utilizador."
8001
+ }
8002
+ }
8003
+ } catch (error) {
8004
+ console.error("[Forge attachment bridge] Failed to convert attachment, leaving message intact:", error instanceof Error ? error.message : String(error))
8005
+ }
8006
+ }
8007
+ })
8008
+ `;
8009
+ }
7764
8010
  function renderEvidencePlugin() {
7765
8011
  return `${FORGE_PLUGIN_HEADER}
7766
8012
  // Conta apenas atividade de sess\xE3o/fluxos de trabalho. N\xE3o envia texto de prompts, nomes de ficheiros nem conte\xFAdo.
@@ -7925,8 +8171,8 @@ async function replaceFile(filename, contents) {
7925
8171
 
7926
8172
  // packages/cli/src/workPackSyncPlugin.ts
7927
8173
  var import_yaml = __toESM(require_dist(), 1);
7928
- import { link, mkdir as mkdir3, mkdtemp as mkdtemp2, readdir as readdir4, readFile as readFile4, realpath, rename as rename4, rm as rm2, rmdir, stat, unlink, writeFile as writeFile4 } from "node:fs/promises";
7929
- import path6 from "node:path";
8174
+ import { link, mkdir as mkdir6, mkdtemp as mkdtemp2, readdir as readdir4, readFile as readFile10, realpath, rename as rename7, rm as rm5, rmdir, stat as stat2, unlink, writeFile as writeFile7 } from "node:fs/promises";
8175
+ import path11 from "node:path";
7930
8176
 
7931
8177
  // node_modules/@opencode-ai/plugin/node_modules/zod/v4/classic/external.js
7932
8178
  var external_exports = {};
@@ -8659,10 +8905,10 @@ function mergeDefs(...defs) {
8659
8905
  function cloneDef(schema) {
8660
8906
  return mergeDefs(schema._zod.def);
8661
8907
  }
8662
- function getElementAtPath(obj, path7) {
8663
- if (!path7)
8908
+ function getElementAtPath(obj, path12) {
8909
+ if (!path12)
8664
8910
  return obj;
8665
- return path7.reduce((acc, key) => acc?.[key], obj);
8911
+ return path12.reduce((acc, key) => acc?.[key], obj);
8666
8912
  }
8667
8913
  function promiseAllObject(promisesObj) {
8668
8914
  const keys = Object.keys(promisesObj);
@@ -9023,11 +9269,11 @@ function aborted(x, startIndex = 0) {
9023
9269
  }
9024
9270
  return false;
9025
9271
  }
9026
- function prefixIssues(path7, issues) {
9272
+ function prefixIssues(path12, issues) {
9027
9273
  return issues.map((iss) => {
9028
9274
  var _a;
9029
9275
  (_a = iss).path ?? (_a.path = []);
9030
- iss.path.unshift(path7);
9276
+ iss.path.unshift(path12);
9031
9277
  return iss;
9032
9278
  });
9033
9279
  }
@@ -9195,7 +9441,7 @@ function treeifyError(error45, _mapper) {
9195
9441
  return issue2.message;
9196
9442
  };
9197
9443
  const result = { errors: [] };
9198
- const processError = (error46, path7 = []) => {
9444
+ const processError = (error46, path12 = []) => {
9199
9445
  var _a, _b;
9200
9446
  for (const issue2 of error46.issues) {
9201
9447
  if (issue2.code === "invalid_union" && issue2.errors.length) {
@@ -9205,7 +9451,7 @@ function treeifyError(error45, _mapper) {
9205
9451
  } else if (issue2.code === "invalid_element") {
9206
9452
  processError({ issues: issue2.issues }, issue2.path);
9207
9453
  } else {
9208
- const fullpath = [...path7, ...issue2.path];
9454
+ const fullpath = [...path12, ...issue2.path];
9209
9455
  if (fullpath.length === 0) {
9210
9456
  result.errors.push(mapper(issue2));
9211
9457
  continue;
@@ -9237,8 +9483,8 @@ function treeifyError(error45, _mapper) {
9237
9483
  }
9238
9484
  function toDotPath(_path) {
9239
9485
  const segs = [];
9240
- const path7 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
9241
- for (const seg of path7) {
9486
+ const path12 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
9487
+ for (const seg of path12) {
9242
9488
  if (typeof seg === "number")
9243
9489
  segs.push(`[${seg}]`);
9244
9490
  else if (typeof seg === "symbol")
@@ -20350,18 +20596,29 @@ function tool(input) {
20350
20596
  }
20351
20597
  tool.schema = external_exports;
20352
20598
 
20599
+ // packages/cli/src/credentials.ts
20600
+ import { chmod, mkdir, readFile as readFile2, rename as rename2, rm, writeFile as writeFile2 } from "node:fs/promises";
20601
+ async function readCredentials(paths) {
20602
+ const raw = await readFile2(paths.credentialsPath, "utf8");
20603
+ const parsed = JSON.parse(raw);
20604
+ if (!parsed.forgeApiKey || !parsed.forgeBaseUrl) {
20605
+ throw new Error(`Ficheiro de credenciais inv\xE1lido em ${paths.credentialsPath}`);
20606
+ }
20607
+ return parsed;
20608
+ }
20609
+
20353
20610
  // packages/cli/src/paths.ts
20354
20611
  import os from "node:os";
20355
20612
  import path2 from "node:path";
20356
20613
  import { existsSync } from "node:fs";
20357
- function resolvePaths(home = os.homedir(), platform = process.platform, env = process.env, exists = existsSync) {
20614
+ function resolvePaths(home = os.homedir(), platform = process.platform, env = process.env, exists2 = existsSync) {
20358
20615
  const pathApi = platform === "win32" ? path2.win32 : path2.posix;
20359
20616
  const userHome = platform === "win32" ? env.USERPROFILE ?? home : home;
20360
20617
  const forgeConfigRoot = env.XDG_CONFIG_HOME ?? pathApi.join(userHome, ".config");
20361
20618
  const forgeDir = pathApi.join(forgeConfigRoot, "forge");
20362
20619
  const rollbackDir = pathApi.join(forgeDir, "rollback");
20363
20620
  const explicitOpenCodeConfig = env.OPENCODE_CONFIG;
20364
- const opencodeDir = explicitOpenCodeConfig ? pathApi.dirname(explicitOpenCodeConfig) : resolveOpenCodeDir(userHome, platform, env, exists, pathApi);
20621
+ const opencodeDir = explicitOpenCodeConfig ? pathApi.dirname(explicitOpenCodeConfig) : resolveOpenCodeDir(userHome, platform, env, exists2, pathApi);
20365
20622
  const opencodeDataDir = resolveOpenCodeDataDir(userHome, platform, env, pathApi);
20366
20623
  const opencodeJsonc = pathApi.join(opencodeDir, "opencode.jsonc");
20367
20624
  const opencodeJson = pathApi.join(opencodeDir, "opencode.json");
@@ -20377,7 +20634,7 @@ function resolvePaths(home = os.homedir(), platform = process.platform, env = pr
20377
20634
  opencodeDir,
20378
20635
  opencodeDataDir,
20379
20636
  opencodeAuthPath: pathApi.join(opencodeDataDir, "auth.json"),
20380
- opencodeConfigPath: explicitOpenCodeConfig ?? (exists(opencodeJsonc) ? opencodeJsonc : exists(opencodeJson) ? opencodeJson : opencodeJsonc),
20637
+ opencodeConfigPath: explicitOpenCodeConfig ?? (exists2(opencodeJsonc) ? opencodeJsonc : exists2(opencodeJson) ? opencodeJson : opencodeJsonc),
20381
20638
  tuiConfigPath: pathApi.join(opencodeDir, "tui.json"),
20382
20639
  skillsDir: pathApi.join(opencodeDir, "skills"),
20383
20640
  agentsDir: pathApi.join(opencodeDir, "agents"),
@@ -20389,7 +20646,7 @@ function resolveOpenCodeDataDir(userHome, platform, env, pathApi) {
20389
20646
  if (platform === "win32") return pathApi.join(userHome, ".local", "share", "opencode");
20390
20647
  return pathApi.join(env.XDG_DATA_HOME ?? pathApi.join(userHome, ".local", "share"), "opencode");
20391
20648
  }
20392
- function resolveOpenCodeDir(home, platform, env, exists, pathApi) {
20649
+ function resolveOpenCodeDir(home, platform, env, exists2, pathApi) {
20393
20650
  if (env.OPENCODE_CONFIG_DIR) return env.OPENCODE_CONFIG_DIR;
20394
20651
  if (platform !== "win32") return pathApi.join(env.XDG_CONFIG_HOME ?? pathApi.join(home, ".config"), "opencode");
20395
20652
  return pathApi.join(home, ".config", "opencode");
@@ -20447,7 +20704,7 @@ import path4 from "node:path";
20447
20704
 
20448
20705
  // packages/cli/src/workPackLocalState.ts
20449
20706
  import { createHash } from "node:crypto";
20450
- import { lstat as lstat2, mkdir, readFile as readFile2, readdir, rename as rename2, writeFile as writeFile2 } from "node:fs/promises";
20707
+ import { lstat as lstat2, mkdir as mkdir2, readFile as readFile3, readdir, rename as rename3, writeFile as writeFile3 } from "node:fs/promises";
20451
20708
  import path3 from "node:path";
20452
20709
  var WORK_PACK_LOCAL_STATE_FILENAME = ".forge-installed-state.json";
20453
20710
  async function writeWorkPackInstalledState(input) {
@@ -20482,7 +20739,7 @@ async function adoptWorkPackInstalledState(input) {
20482
20739
  async function readInstalledState(packDir) {
20483
20740
  const info = await lstat2(path3.join(packDir, WORK_PACK_LOCAL_STATE_FILENAME)).catch(() => void 0);
20484
20741
  if (!info?.isFile() || info.isSymbolicLink() || info.size > 1024 * 1024) return void 0;
20485
- const raw = await readFile2(path3.join(packDir, WORK_PACK_LOCAL_STATE_FILENAME), "utf8").catch(() => void 0);
20742
+ const raw = await readFile3(path3.join(packDir, WORK_PACK_LOCAL_STATE_FILENAME), "utf8").catch(() => void 0);
20486
20743
  if (!raw) return void 0;
20487
20744
  try {
20488
20745
  return parseWorkPackFileManifest(JSON.parse(raw));
@@ -20507,7 +20764,7 @@ async function digestPackTree(root) {
20507
20764
  continue;
20508
20765
  }
20509
20766
  if (!entry.isFile()) return false;
20510
- files.push({ path: relative, sha256: digest(await readFile2(absolute)) });
20767
+ files.push({ path: relative, sha256: digest(await readFile3(absolute)) });
20511
20768
  }
20512
20769
  return true;
20513
20770
  };
@@ -20521,7 +20778,7 @@ async function projectionsMatch(directory, expected) {
20521
20778
  const absolute = path3.join(directory, projection.filename);
20522
20779
  const info = await lstat2(absolute).catch(() => void 0);
20523
20780
  if (!info?.isFile() || info.isSymbolicLink()) return false;
20524
- const bytes = await readFile2(absolute).catch(() => void 0);
20781
+ const bytes = await readFile3(absolute).catch(() => void 0);
20525
20782
  if (!bytes || digest(bytes) !== projection.sha256) return false;
20526
20783
  }
20527
20784
  return true;
@@ -20544,11 +20801,11 @@ function digest(bytes) {
20544
20801
  return createHash("sha256").update(bytes).digest("hex");
20545
20802
  }
20546
20803
  async function writeJsonAtomic(filePath, value) {
20547
- await mkdir(path3.dirname(filePath), { recursive: true });
20804
+ await mkdir2(path3.dirname(filePath), { recursive: true });
20548
20805
  const tempPath = path3.join(path3.dirname(filePath), `.${path3.basename(filePath)}.${process.pid}.tmp`);
20549
- await writeFile2(tempPath, `${JSON.stringify(value, null, 2)}
20806
+ await writeFile3(tempPath, `${JSON.stringify(value, null, 2)}
20550
20807
  `);
20551
- await rename2(tempPath, filePath);
20808
+ await rename3(tempPath, filePath);
20552
20809
  }
20553
20810
  async function adoptWorkPackFileManifest(input) {
20554
20811
  if (!await matchesInstalledState({ ...input, allowAdditional: true }, input.expected)) return false;
@@ -20784,10 +21041,11 @@ function assertSlug(slug) {
20784
21041
  }
20785
21042
 
20786
21043
  // packages/cli/src/sync.ts
20787
- import { createHash as createHash3 } from "node:crypto";
20788
- import { chmod, cp, lstat as lstat4, mkdtemp, mkdir as mkdir2, readdir as readdir3, readFile as readFile3, rm, rename as rename3, writeFile as writeFile3 } from "node:fs/promises";
21044
+ import { createHash as createHash4 } from "node:crypto";
21045
+ import { spawnSync } from "node:child_process";
21046
+ import { chmod as chmod4, cp, lstat as lstat5, mkdtemp, mkdir as mkdir5, readdir as readdir3, readFile as readFile7, rm as rm4, rename as rename6, writeFile as writeFile6 } from "node:fs/promises";
20789
21047
  import os4 from "node:os";
20790
- import path5 from "node:path";
21048
+ import path8 from "node:path";
20791
21049
 
20792
21050
  // node_modules/tar/dist/esm/index.min.js
20793
21051
  import Qr from "events";
@@ -23758,6 +24016,492 @@ var To = (s3) => {
23758
24016
  s3.mtimeCache || (s3.mtimeCache = /* @__PURE__ */ new Map()), s3.filter = t ? (e, i) => t(e, i) && !((s3.mtimeCache?.get(e) ?? i.mtime ?? 0) > (i.mtime ?? 0)) : (e, i) => !((s3.mtimeCache?.get(e) ?? i.mtime ?? 0) > (i.mtime ?? 0));
23759
24017
  };
23760
24018
 
24019
+ // packages/cli/src/configWriter.ts
24020
+ function mergeOpenCodeConfig(existing, manifest, forgeBaseUrl, forgeApiKey = "{env:FORGE_API_KEY}", options = {}) {
24021
+ return mergeWorkerOpenCodeConfig(existing, manifest, forgeBaseUrl, forgeApiKey, options);
24022
+ }
24023
+ function renderTuiConfig(manifest) {
24024
+ return renderWorkerTuiConfig(manifest);
24025
+ }
24026
+
24027
+ // packages/cli/src/coreSyncTransaction.ts
24028
+ import { createHash as createHash3, randomUUID as randomUUID3 } from "node:crypto";
24029
+ import { chmod as chmod3, lstat as lstat4, mkdir as mkdir4, readFile as readFile4, rename as rename5, rm as rm3, writeFile as writeFile5 } from "node:fs/promises";
24030
+ import path6 from "node:path";
24031
+
24032
+ // packages/cli/src/ownerOnlyFile.ts
24033
+ import { spawnSync as nodeSpawnSync } from "node:child_process";
24034
+ import { randomUUID as randomUUID2 } from "node:crypto";
24035
+ import { chmod as chmod2, mkdir as mkdir3, rename as rename4, rm as rm2, stat, writeFile as writeFile4 } from "node:fs/promises";
24036
+ import path5 from "node:path";
24037
+ async function protectOwnerOnlyPath(filePath, kind, options = {}) {
24038
+ const platform = options.platform ?? process.platform;
24039
+ if (platform !== "win32") {
24040
+ await chmod2(filePath, kind === "directory" ? 448 : 384);
24041
+ return;
24042
+ }
24043
+ const spawn = options.spawnSync ?? nodeSpawnSync;
24044
+ const command = kind === "directory" ? "$ErrorActionPreference = 'Stop'; $path = [Console]::In.ReadToEnd(); $identity = [System.Security.Principal.WindowsIdentity]::GetCurrent().User; $acl = [System.Security.AccessControl.DirectorySecurity]::new(); $acl.SetAccessRuleProtection($true, $false); $inheritance = [System.Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [System.Security.AccessControl.InheritanceFlags]::ObjectInherit; $rule = [System.Security.AccessControl.FileSystemAccessRule]::new($identity, [System.Security.AccessControl.FileSystemRights]::FullControl, $inheritance, [System.Security.AccessControl.PropagationFlags]::None, [System.Security.AccessControl.AccessControlType]::Allow); [void]$acl.AddAccessRule($rule); [System.IO.Directory]::SetAccessControl($path, $acl)" : "$ErrorActionPreference = 'Stop'; $path = [Console]::In.ReadToEnd(); $identity = [System.Security.Principal.WindowsIdentity]::GetCurrent().User; $acl = [System.Security.AccessControl.FileSecurity]::new(); $acl.SetAccessRuleProtection($true, $false); $rule = [System.Security.AccessControl.FileSystemAccessRule]::new($identity, [System.Security.AccessControl.FileSystemRights]::FullControl, [System.Security.AccessControl.AccessControlType]::Allow); [void]$acl.AddAccessRule($rule); [System.IO.File]::SetAccessControl($path, $acl)";
24045
+ const result = spawn("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", command], {
24046
+ encoding: "utf8",
24047
+ input: filePath
24048
+ });
24049
+ if (result.status !== 0) {
24050
+ const detail = typeof result.stderr === "string" ? result.stderr.trim().replace(/\s+/g, " ").slice(0, 500) : "";
24051
+ const context = options.failureContext ?? (kind === "directory" ? "o diret\xF3rio" : "o ficheiro");
24052
+ throw new Error(`N\xE3o foi poss\xEDvel proteger ${context} em ${filePath}${detail ? `: ${detail}` : ""}`);
24053
+ }
24054
+ }
24055
+ async function assertExistingDirectoryIsSafe(directory, options) {
24056
+ const platform = options.platform ?? process.platform;
24057
+ if (platform !== "win32") {
24058
+ const info = await stat(directory);
24059
+ const currentUid = process.getuid?.();
24060
+ if (currentUid !== void 0 && info.uid !== currentUid || (info.mode & 18) !== 0) {
24061
+ const mode = (info.mode & 511).toString(8).padStart(3, "0");
24062
+ throw new Error(`O diret\xF3rio existente ${directory} n\xE3o \xE9 controlado apenas pelo utilizador atual (modo ${mode})`);
24063
+ }
24064
+ return;
24065
+ }
24066
+ const spawn = options.spawnSync ?? nodeSpawnSync;
24067
+ const command = "$ErrorActionPreference = 'Stop'; $path = [Console]::In.ReadToEnd(); $current = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value; $trusted = @($current, 'S-1-5-18', 'S-1-5-32-544'); $dangerous = [System.Security.AccessControl.FileSystemRights]::Write -bor [System.Security.AccessControl.FileSystemRights]::Delete -bor [System.Security.AccessControl.FileSystemRights]::DeleteSubdirectoriesAndFiles -bor [System.Security.AccessControl.FileSystemRights]::ChangePermissions -bor [System.Security.AccessControl.FileSystemRights]::TakeOwnership; $acl = [System.IO.Directory]::GetAccessControl($path); $rules = $acl.GetAccessRules($true, $true, [System.Security.Principal.SecurityIdentifier]); foreach ($rule in $rules) { if ($rule.AccessControlType -eq [System.Security.AccessControl.AccessControlType]::Allow -and $rule.PropagationFlags -ne [System.Security.AccessControl.PropagationFlags]::InheritOnly -and ($rule.FileSystemRights -band $dangerous) -ne 0 -and $trusted -notcontains $rule.IdentityReference.Value) { throw ('O diret\xF3rio permite escrita por ' + $rule.IdentityReference.Value) } }";
24068
+ const result = spawn("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", command], {
24069
+ encoding: "utf8",
24070
+ input: directory
24071
+ });
24072
+ if (result.status !== 0) {
24073
+ const detail = typeof result.stderr === "string" ? result.stderr.trim().replace(/\s+/g, " ").slice(0, 500) : "";
24074
+ throw new Error(`O diret\xF3rio existente ${directory} n\xE3o \xE9 controlado apenas pelo utilizador atual${detail ? `: ${detail}` : ""}`);
24075
+ }
24076
+ }
24077
+ async function prepareOwnerOnlyFileDestination(filePath, options = {}) {
24078
+ const directory = path5.dirname(filePath);
24079
+ const createdDirectory = await mkdir3(directory, { recursive: true, mode: 448 });
24080
+ if (createdDirectory !== void 0) await protectOwnerOnlyPath(directory, "directory", options);
24081
+ else await assertExistingDirectoryIsSafe(directory, options);
24082
+ }
24083
+ async function writeOwnerOnlyTextAtomic(filePath, content, options = {}) {
24084
+ const directory = path5.dirname(filePath);
24085
+ await prepareOwnerOnlyFileDestination(filePath, options);
24086
+ const temporary = path5.join(directory, `.${path5.basename(filePath)}.${randomUUID2()}.tmp`);
24087
+ try {
24088
+ await writeFile4(temporary, content, { flag: "wx", mode: 384 });
24089
+ await protectOwnerOnlyPath(temporary, "file", options);
24090
+ await rename4(temporary, filePath);
24091
+ await protectOwnerOnlyPath(filePath, "file", options);
24092
+ } catch (error45) {
24093
+ await rm2(temporary, { force: true }).catch(() => void 0);
24094
+ throw error45;
24095
+ }
24096
+ }
24097
+
24098
+ // packages/cli/src/coreSyncTransaction.ts
24099
+ var CORE_RUNTIME_MANIFEST_VERSION = 1;
24100
+ var CoreSyncUncertainError = class extends Error {
24101
+ constructor(message, paths) {
24102
+ super(message);
24103
+ this.paths = paths;
24104
+ }
24105
+ paths;
24106
+ };
24107
+ var defaultFs = { chmod: chmod3, lstat: lstat4, mkdir: mkdir4, readFile: readFile4, rename: rename5, rm: rm3, writeFile: writeFile5 };
24108
+ function coreRuntimeManifestDigest(files) {
24109
+ const canonical = [...files].sort((a, b2) => a.id.localeCompare(b2.id)).map((file2) => ({
24110
+ id: file2.id,
24111
+ path: path6.resolve(file2.path),
24112
+ exists: file2.bytes !== null,
24113
+ digest: file2.bytes === null ? void 0 : sha256(file2.bytes),
24114
+ mode: file2.mode,
24115
+ ownerOnly: file2.ownerOnly === true
24116
+ }));
24117
+ return sha256(Buffer.from(JSON.stringify(canonical)));
24118
+ }
24119
+ function validateCoreRuntimeManifest(manifest) {
24120
+ if (manifest.version !== CORE_RUNTIME_MANIFEST_VERSION) throw new Error(`Unsupported core runtime manifest version: ${String(manifest.version)}`);
24121
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/.test(manifest.id)) throw new Error("Invalid core runtime manifest id");
24122
+ if (!/^[a-f0-9]{64}$/.test(manifest.digest)) throw new Error("Invalid core runtime manifest digest");
24123
+ if (manifest.files.length === 0) throw new Error("Core runtime manifest must contain files");
24124
+ const ids = /* @__PURE__ */ new Set();
24125
+ const targets = /* @__PURE__ */ new Set();
24126
+ for (const file2 of manifest.files) {
24127
+ if (!file2.id || ids.has(file2.id)) throw new Error(`Duplicate core runtime file id: ${file2.id}`);
24128
+ const target = path6.resolve(file2.path);
24129
+ if (!path6.isAbsolute(file2.path) || targets.has(target)) throw new Error(`Invalid or duplicate core runtime target: ${file2.path}`);
24130
+ if (file2.mode !== void 0 && (!Number.isInteger(file2.mode) || file2.mode < 0 || file2.mode > 4095)) throw new Error(`Invalid mode for ${file2.id}`);
24131
+ if (file2.ownerOnly !== void 0 && typeof file2.ownerOnly !== "boolean") throw new Error(`Invalid owner-only flag for ${file2.id}`);
24132
+ ids.add(file2.id);
24133
+ targets.add(target);
24134
+ }
24135
+ if (coreRuntimeManifestDigest(manifest.files) !== manifest.digest) throw new Error("Core runtime manifest digest mismatch");
24136
+ }
24137
+ async function applyCoreSyncTransaction(options) {
24138
+ validateCoreRuntimeManifest(options.manifest);
24139
+ const fs2 = options.fs ?? defaultFs;
24140
+ const hooks = options.hooks;
24141
+ const existingRecovery = await recoverCoreSyncTransaction({ journalPath: options.journalPath, fs: fs2 });
24142
+ if (existingRecovery.status === "uncertain") throw new CoreSyncUncertainError(existingRecovery.message, existingRecovery.uncertainPaths);
24143
+ const transactionId = randomUUID3();
24144
+ const files = [];
24145
+ try {
24146
+ for (const desired of options.manifest.files) {
24147
+ const target = path6.resolve(desired.path);
24148
+ if (desired.ownerOnly && desired.bytes !== null && fs2 === defaultFs) await prepareOwnerOnlyFileDestination(target);
24149
+ else await fs2.mkdir(path6.dirname(target), { recursive: true });
24150
+ const original = await capture(target, fs2);
24151
+ const suffix = `.forge-core-${transactionId}`;
24152
+ const backup = original.exists ? `${target}${suffix}.backup` : void 0;
24153
+ const stage = desired.bytes === null ? void 0 : `${target}${suffix}.stage`;
24154
+ if (backup && original.bytes) await writeExact(backup, original.bytes, original.mode, fs2, desired.ownerOnly === true);
24155
+ if (stage && desired.bytes) await writeExact(stage, desired.bytes, desired.mode ?? original.mode ?? 384, fs2, desired.ownerOnly === true);
24156
+ files.push({
24157
+ id: desired.id,
24158
+ target,
24159
+ ...stage ? { stage } : {},
24160
+ ...backup ? { backup } : {},
24161
+ original: { exists: original.exists, ...original.mode === void 0 ? {} : { mode: original.mode }, ...original.bytes ? { digest: sha256(original.bytes) } : {} },
24162
+ desired: { exists: desired.bytes !== null, ...desired.bytes === null ? {} : { digest: sha256(desired.bytes), mode: desired.mode ?? original.mode ?? 384 } },
24163
+ ...desired.ownerOnly ? { ownerOnly: true } : {}
24164
+ });
24165
+ await hooks?.boundary?.(`after-prepare:${desired.id}`);
24166
+ }
24167
+ const journal = {
24168
+ schemaVersion: 1,
24169
+ transactionId,
24170
+ manifest: { version: 1, id: options.manifest.id, digest: options.manifest.digest },
24171
+ files
24172
+ };
24173
+ await hooks?.boundary?.("before-journal");
24174
+ await writeJournal(options.journalPath, journal, fs2);
24175
+ await hooks?.boundary?.("after-journal");
24176
+ for (const file2 of files) {
24177
+ await hooks?.boundary?.(`before-commit:${file2.id}`);
24178
+ await fs2.rm(file2.target, { force: true });
24179
+ if (file2.stage) await fs2.rename(file2.stage, file2.target);
24180
+ if (file2.stage && file2.ownerOnly && fs2 === defaultFs) await protectOwnerOnlyPath(file2.target, "file");
24181
+ await hooks?.boundary?.(`after-commit:${file2.id}`);
24182
+ }
24183
+ await hooks?.boundary?.("before-cleanup");
24184
+ await cleanup(journal, options.journalPath, fs2);
24185
+ await hooks?.boundary?.("after-cleanup");
24186
+ return { status: "committed", manifestId: options.manifest.id, digest: options.manifest.digest };
24187
+ } catch (error45) {
24188
+ if (!await exists(options.journalPath, fs2)) {
24189
+ await Promise.all(files.flatMap((file2) => [file2.stage, file2.backup].filter((item) => Boolean(item))).map((item) => fs2.rm(item, { force: true }).catch(() => void 0)));
24190
+ throw error45;
24191
+ }
24192
+ const recovery = await recoverCoreSyncTransaction({ journalPath: options.journalPath, fs: fs2 });
24193
+ if (recovery.status === "uncertain") throw new CoreSyncUncertainError(recovery.message, recovery.uncertainPaths);
24194
+ throw error45;
24195
+ }
24196
+ }
24197
+ async function recoverCoreSyncTransaction(options) {
24198
+ const fs2 = options.fs ?? defaultFs;
24199
+ let journal;
24200
+ try {
24201
+ journal = JSON.parse(await fs2.readFile(options.journalPath, "utf8"));
24202
+ } catch (error45) {
24203
+ if (isNotFound(error45)) return { status: "nothing-to-recover" };
24204
+ return { status: "uncertain", uncertainPaths: [options.journalPath], message: "Core sync journal is unreadable; exact recovery is uncertain." };
24205
+ }
24206
+ if (!validJournal(journal)) return { status: "uncertain", uncertainPaths: [options.journalPath], message: "Core sync journal is invalid; exact recovery is uncertain." };
24207
+ const uncertain = [];
24208
+ for (const file2 of journal.files) {
24209
+ try {
24210
+ if (!file2.original.exists) await fs2.rm(file2.target, { force: true });
24211
+ else {
24212
+ if (!file2.backup || !await exists(file2.backup, fs2)) throw new Error("backup missing");
24213
+ const bytes = await fs2.readFile(file2.backup);
24214
+ if (sha256(bytes) !== file2.original.digest) throw new Error("backup digest mismatch");
24215
+ await writeExact(`${file2.target}.forge-restore-${journal.transactionId}`, bytes, file2.original.mode, fs2, file2.ownerOnly === true);
24216
+ await fs2.rm(file2.target, { force: true });
24217
+ await fs2.rename(`${file2.target}.forge-restore-${journal.transactionId}`, file2.target);
24218
+ if (file2.ownerOnly && fs2 === defaultFs) await protectOwnerOnlyPath(file2.target, "file");
24219
+ const restored = await capture(file2.target, fs2);
24220
+ if (!restored.bytes || sha256(restored.bytes) !== file2.original.digest || restored.mode !== file2.original.mode) throw new Error("restore verification failed");
24221
+ }
24222
+ } catch {
24223
+ uncertain.push(file2.target);
24224
+ }
24225
+ }
24226
+ 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." };
24227
+ await cleanup(journal, options.journalPath, fs2);
24228
+ return { status: "restored", manifestId: journal.manifest.id };
24229
+ }
24230
+ async function capture(target, fs2) {
24231
+ try {
24232
+ const info = await fs2.lstat(target);
24233
+ if (!info.isFile()) throw new Error(`Core runtime target is not a regular file: ${target}`);
24234
+ return { exists: true, bytes: await fs2.readFile(target), mode: info.mode & 4095 };
24235
+ } catch (error45) {
24236
+ if (isNotFound(error45)) return { exists: false };
24237
+ throw error45;
24238
+ }
24239
+ }
24240
+ async function writeExact(target, bytes, mode, fs2, ownerOnly = false) {
24241
+ await fs2.writeFile(target, bytes, { flag: "wx", mode });
24242
+ await fs2.chmod(target, mode);
24243
+ if (ownerOnly && fs2 === defaultFs) await protectOwnerOnlyPath(target, "file");
24244
+ }
24245
+ async function writeJournal(target, journal, fs2) {
24246
+ await fs2.mkdir(path6.dirname(target), { recursive: true });
24247
+ const temporary = `${target}.next`;
24248
+ await fs2.rm(temporary, { force: true });
24249
+ await fs2.writeFile(temporary, `${JSON.stringify(journal, null, 2)}
24250
+ `, { flag: "wx", mode: 384 });
24251
+ await fs2.chmod(temporary, 384);
24252
+ await fs2.rename(temporary, target);
24253
+ }
24254
+ async function cleanup(journal, journalPath, fs2) {
24255
+ await Promise.all(journal.files.flatMap((file2) => [file2.stage, file2.backup].filter((item) => Boolean(item))).map((item) => fs2.rm(item, { force: true })));
24256
+ await fs2.rm(journalPath, { force: true });
24257
+ }
24258
+ async function exists(target, fs2) {
24259
+ try {
24260
+ await fs2.lstat(target);
24261
+ return true;
24262
+ } catch (error45) {
24263
+ if (isNotFound(error45)) return false;
24264
+ throw error45;
24265
+ }
24266
+ }
24267
+ function isNotFound(error45) {
24268
+ return Boolean(error45 && typeof error45 === "object" && "code" in error45 && error45.code === "ENOENT");
24269
+ }
24270
+ function sha256(value) {
24271
+ return createHash3("sha256").update(value).digest("hex");
24272
+ }
24273
+ function validJournal(value) {
24274
+ 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" && path6.isAbsolute(file2.target) && typeof file2.original?.exists === "boolean" && typeof file2.desired?.exists === "boolean" && (file2.ownerOnly === void 0 || typeof file2.ownerOnly === "boolean"));
24275
+ }
24276
+
24277
+ // packages/cli/src/jsonc.ts
24278
+ function parseJsonc(input) {
24279
+ return JSON.parse(stripTrailingCommas(stripJsonComments(input)));
24280
+ }
24281
+ function stripJsonComments(input) {
24282
+ let output = "";
24283
+ let inString = false;
24284
+ let escaped = false;
24285
+ let inLineComment = false;
24286
+ let inBlockComment = false;
24287
+ for (let index = 0; index < input.length; index += 1) {
24288
+ const char = input[index];
24289
+ const next = input[index + 1];
24290
+ if (inLineComment) {
24291
+ if (char === "\n" || char === "\r") {
24292
+ inLineComment = false;
24293
+ output += char;
24294
+ }
24295
+ continue;
24296
+ }
24297
+ if (inBlockComment) {
24298
+ if (char === "*" && next === "/") {
24299
+ inBlockComment = false;
24300
+ index += 1;
24301
+ } else if (char === "\n" || char === "\r") output += char;
24302
+ continue;
24303
+ }
24304
+ if (inString) {
24305
+ output += char;
24306
+ if (escaped) escaped = false;
24307
+ else if (char === "\\") escaped = true;
24308
+ else if (char === '"') inString = false;
24309
+ continue;
24310
+ }
24311
+ if (char === '"') {
24312
+ inString = true;
24313
+ output += char;
24314
+ } else if (char === "/" && next === "/") {
24315
+ inLineComment = true;
24316
+ index += 1;
24317
+ } else if (char === "/" && next === "*") {
24318
+ inBlockComment = true;
24319
+ index += 1;
24320
+ } else output += char;
24321
+ }
24322
+ return output;
24323
+ }
24324
+ function stripTrailingCommas(input) {
24325
+ let output = "";
24326
+ let inString = false;
24327
+ let escaped = false;
24328
+ for (let index = 0; index < input.length; index += 1) {
24329
+ const char = input[index];
24330
+ if (inString) {
24331
+ output += char;
24332
+ if (escaped) escaped = false;
24333
+ else if (char === "\\") escaped = true;
24334
+ else if (char === '"') inString = false;
24335
+ continue;
24336
+ }
24337
+ if (char === '"') {
24338
+ inString = true;
24339
+ output += char;
24340
+ continue;
24341
+ }
24342
+ if (char === ",") {
24343
+ let lookahead = index + 1;
24344
+ while (/\s/.test(input[lookahead] ?? "")) lookahead += 1;
24345
+ if (input[lookahead] === "}" || input[lookahead] === "]") continue;
24346
+ }
24347
+ output += char;
24348
+ }
24349
+ return output;
24350
+ }
24351
+
24352
+ // packages/cli/src/remoteConfig.ts
24353
+ import { readFile as readFile5 } from "node:fs/promises";
24354
+ var WELLKNOWN_ENV_KEY = "FORGE_API_KEY";
24355
+ async function removeWellKnownAuth(paths, credentials, previous) {
24356
+ const content = await prepareWellKnownAuthRemoval(paths, credentials, previous);
24357
+ if (content !== void 0) await writeOwnerOnlyTextAtomic(paths.opencodeAuthPath, content);
24358
+ }
24359
+ async function prepareWellKnownAuthRemoval(paths, credentials, previous) {
24360
+ const auth = await readAuthJson(paths);
24361
+ const owned = previous ? [credentials, previous] : [credentials];
24362
+ const ownedKeys = new Set(owned.map((entry) => entry.forgeApiKey));
24363
+ let changed = false;
24364
+ for (const url2 of owned.flatMap((entry) => [entry.forgeBaseUrl, ...entry.forgeOwnedWellKnownUrls ?? []])) {
24365
+ const key = normalizeBaseUrl(url2);
24366
+ const entry = auth[key];
24367
+ if (!isRecord2(entry) || entry.type !== "wellknown" || entry.key !== WELLKNOWN_ENV_KEY || typeof entry.token !== "string" || !entry.token.startsWith("forge_")) continue;
24368
+ if (!ownedKeys.has(entry.token)) {
24369
+ throw new Error("A autoriza\xE7\xE3o Forge foi alterada; preserve os ficheiros e pe\xE7a uma repara\xE7\xE3o acompanhada.");
24370
+ }
24371
+ delete auth[key];
24372
+ changed = true;
24373
+ }
24374
+ return changed ? `${JSON.stringify(auth, null, 2)}
24375
+ ` : void 0;
24376
+ }
24377
+ function stripForgeManagedConfig(config2) {
24378
+ const next = { ...config2 };
24379
+ delete next.model;
24380
+ delete next.small_model;
24381
+ delete next.share;
24382
+ delete next.autoupdate;
24383
+ const experimental = isRecord2(next.experimental) ? { ...next.experimental } : void 0;
24384
+ if (experimental) {
24385
+ delete experimental.clickableFileReferences;
24386
+ if (Object.keys(experimental).length > 0) next.experimental = experimental;
24387
+ else delete next.experimental;
24388
+ }
24389
+ const provider = isRecord2(next.provider) ? { ...next.provider } : void 0;
24390
+ if (provider) {
24391
+ delete provider.forge;
24392
+ const openrouter = provider.openrouter;
24393
+ if (isRecord2(openrouter) && openrouter.name === OPENROUTER_ALIAS_PROVIDER_NAME) delete provider.openrouter;
24394
+ if (Object.keys(provider).length > 0) next.provider = provider;
24395
+ else delete next.provider;
24396
+ }
24397
+ const agent = isRecord2(next.agent) ? { ...next.agent } : void 0;
24398
+ if (agent) {
24399
+ delete agent["document-reader"];
24400
+ if (Object.keys(agent).length > 0) next.agent = agent;
24401
+ else delete next.agent;
24402
+ }
24403
+ return next;
24404
+ }
24405
+ function normalizeBaseUrl(value) {
24406
+ return value.replace(/\/+$/, "");
24407
+ }
24408
+ async function readAuthJson(paths) {
24409
+ let raw;
24410
+ try {
24411
+ raw = await readFile5(paths.opencodeAuthPath, "utf8");
24412
+ } catch (error45) {
24413
+ if (error45.code === "ENOENT") return {};
24414
+ throw error45;
24415
+ }
24416
+ const parsed = JSON.parse(raw.startsWith("\uFEFF") ? raw.slice(1) : raw);
24417
+ if (!isRecord2(parsed)) throw new Error("A autentica\xE7\xE3o do OpenCode n\xE3o \xE9 um objeto JSON v\xE1lido");
24418
+ return parsed;
24419
+ }
24420
+ function isRecord2(value) {
24421
+ return typeof value === "object" && value !== null && !Array.isArray(value);
24422
+ }
24423
+
24424
+ // packages/cli/src/localConfigRecovery.ts
24425
+ import { readFile as readFile6 } from "node:fs/promises";
24426
+ import path7 from "node:path";
24427
+ var LocalConfigRecoveryError = class extends Error {
24428
+ };
24429
+ var LAST_GOOD_FILENAME = "last-good-opencode.json";
24430
+ function lastGoodLocalConfigFile(paths, credentials, content) {
24431
+ assertForgeConfig(content, credentials);
24432
+ return { id: "last-good-config", path: path7.join(paths.forgeDir, LAST_GOOD_FILENAME), bytes: Buffer.from(content), mode: 384, ownerOnly: true };
24433
+ }
24434
+ async function retiredLastGoodLocalConfigFile(paths) {
24435
+ const filePath = path7.join(paths.forgeDir, LAST_GOOD_FILENAME);
24436
+ return await readOptional(filePath) === void 0 ? void 0 : { id: "last-good-config", path: filePath, bytes: null };
24437
+ }
24438
+ async function inspectLocalConfigRecovery(paths, credentials) {
24439
+ const snapshot = await readOptional(path7.join(paths.forgeDir, LAST_GOOD_FILENAME));
24440
+ const current = await readOptional(paths.opencodeConfigPath);
24441
+ return {
24442
+ snapshot: snapshot === void 0 ? "missing" : isForgeConfig(snapshot, credentials) ? "available" : "invalid",
24443
+ current: current === void 0 ? "missing" : isForgeConfig(current, credentials) && (snapshot === void 0 || !isForgeConfig(snapshot, credentials) || sameSavedForgeFields(current, snapshot)) ? "valid" : "invalid"
24444
+ };
24445
+ }
24446
+ function assertForgeConfig(content, credentials) {
24447
+ if (!isForgeConfig(content, credentials)) {
24448
+ throw new LocalConfigRecoveryError("A c\xF3pia local n\xE3o corresponde \xE0s credenciais Forge atuais; a configura\xE7\xE3o n\xE3o foi alterada.");
24449
+ }
24450
+ }
24451
+ function isForgeConfig(content, credentials) {
24452
+ try {
24453
+ const config2 = parseJsonc(content);
24454
+ if (!isRecord3(config2) || !isRecord3(config2.provider) || !isRecord3(config2.provider.forge)) return false;
24455
+ assertForgeVisible(config2);
24456
+ const forge = config2.provider.forge;
24457
+ if (!isRecord3(forge.options) || forge.options.apiKey !== credentials.forgeApiKey || typeof forge.options.baseURL !== "string" || !forge.options.baseURL.endsWith("/v1") || !isRecord3(forge.models) || Object.keys(forge.models).length === 0) return false;
24458
+ if (typeof config2.model !== "string" || !config2.model.startsWith("forge/") || typeof config2.small_model !== "string" || !config2.small_model.startsWith("forge/")) return false;
24459
+ const plugins = forgePluginEntries(config2);
24460
+ return plugins.length === 1 && plugins.every(
24461
+ (entry) => Array.isArray(entry) && typeof entry[0] === "string" && /^minimal-forge-work-pack-sync@/.test(entry[0]) && isRecord3(entry[1]) && entry[1].forgeBaseUrl === credentials.forgeBaseUrl.replace(/\/+$/, "") && entry[1].localConfig === true
24462
+ );
24463
+ } catch {
24464
+ return false;
24465
+ }
24466
+ }
24467
+ function sameSavedForgeFields(current, snapshot) {
24468
+ const active = parseJsonc(current);
24469
+ const saved = parseJsonc(snapshot);
24470
+ const activeProvider = isRecord3(active.provider) ? active.provider.forge : void 0;
24471
+ const savedProvider = isRecord3(saved.provider) ? saved.provider.forge : void 0;
24472
+ return JSON.stringify(activeProvider) === JSON.stringify(savedProvider) && active.model === saved.model && active.small_model === saved.small_model && JSON.stringify(forgePluginEntries(active)) === JSON.stringify(forgePluginEntries(saved));
24473
+ }
24474
+ function forgePluginEntries(config2) {
24475
+ return (Array.isArray(config2.plugin) ? config2.plugin : []).filter((entry) => {
24476
+ const name = Array.isArray(entry) ? entry[0] : entry;
24477
+ return typeof name === "string" && /^minimal-forge-work-pack-sync@/.test(name);
24478
+ });
24479
+ }
24480
+ async function readOptional(filePath) {
24481
+ try {
24482
+ return await readFile6(filePath, "utf8");
24483
+ } catch (error45) {
24484
+ if (error45.code === "ENOENT") return void 0;
24485
+ throw error45;
24486
+ }
24487
+ }
24488
+ function isRecord3(value) {
24489
+ return typeof value === "object" && value !== null && !Array.isArray(value);
24490
+ }
24491
+ function assertForgeVisible(config2) {
24492
+ if (!isRecord3(config2)) return;
24493
+ if (Array.isArray(config2.disabled_providers) && config2.disabled_providers.includes("forge") || Array.isArray(config2.enabled_providers) && !config2.enabled_providers.includes("forge")) {
24494
+ throw new LocalConfigRecoveryError("O Forge est\xE1 oculto nas prefer\xEAncias de providers. Pe\xE7a ao respons\xE1vel para rever essa escolha; a configura\xE7\xE3o foi preservada.");
24495
+ }
24496
+ }
24497
+
24498
+ // packages/cli/src/syncReconciler.ts
24499
+ async function reconcileSyncSnapshot(steps) {
24500
+ const core = await steps.applyCore();
24501
+ const workPacks = await steps.applyWorkPacks();
24502
+ return { ...workPacks, ...core };
24503
+ }
24504
+
23761
24505
  // packages/cli/src/workPackReconciler.ts
23762
24506
  async function reconcileWorkPacks(input) {
23763
24507
  assertUniqueSlugs(input.desired, "desired");
@@ -23946,6 +24690,8 @@ function assertUniqueSlugs(packs, label) {
23946
24690
  }
23947
24691
 
23948
24692
  // packages/cli/src/sync.ts
24693
+ var FORGE_DEBUG_TRACE_CONFIG_FILENAME = "debug-trace.json";
24694
+ var FORGE_DEBUG_TRACE_MANAGED_BY = "minimal-forge";
23949
24695
  var WORK_PACK_COMMITTED_MARKER = ".forge-replacement-committed";
23950
24696
  var WORK_PACK_TRANSACTION_SUFFIX = ".transaction";
23951
24697
  var MAX_SYNC_ERROR_BODY_BYTES = 1536;
@@ -23966,7 +24712,8 @@ async function fetchManifest(credentials) {
23966
24712
  authorization: `Bearer ${credentials.forgeApiKey}`,
23967
24713
  "x-forge-hostname": os4.hostname(),
23968
24714
  "x-forge-agent-version": "0.1.0"
23969
- }
24715
+ },
24716
+ signal: AbortSignal.timeout(15e3)
23970
24717
  });
23971
24718
  } catch (error45) {
23972
24719
  throw new Error(
@@ -23985,17 +24732,138 @@ async function fetchManifest(credentials) {
23985
24732
  })
23986
24733
  );
23987
24734
  }
23988
- return await response.json();
24735
+ let parsed;
24736
+ try {
24737
+ parsed = await response.json();
24738
+ } catch {
24739
+ throw new Error("O manifesto Forge n\xE3o cont\xE9m JSON v\xE1lido; a configura\xE7\xE3o local foi preservada.");
24740
+ }
24741
+ if (!validCoreManifest(parsed)) {
24742
+ throw new Error("O manifesto Forge n\xE3o cont\xE9m um provider e modelos aprovados v\xE1lidos; a configura\xE7\xE3o local foi preservada.");
24743
+ }
24744
+ return parsed;
24745
+ }
24746
+ function validCoreManifest(value) {
24747
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
24748
+ const manifest = value;
24749
+ if (!manifest.config || typeof manifest.config !== "object" || Array.isArray(manifest.config) || !Array.isArray(manifest.skills)) return false;
24750
+ const config2 = manifest.config;
24751
+ if (typeof config2.model !== "string" || !config2.model || typeof config2.small_model !== "string" || !config2.small_model || typeof config2.theme !== "string" || typeof config2.instructionsUrl !== "string" || !Array.isArray(config2.models) || config2.models.length === 0) return false;
24752
+ const modelIds = config2.models.map((model) => model && typeof model === "object" && !Array.isArray(model) ? model.id : void 0);
24753
+ return modelIds.every((id) => typeof id === "string" && id.length > 0) && modelIds.includes(config2.model) && modelIds.includes(config2.small_model);
24754
+ }
24755
+ async function applyManifest(paths, credentials, manifest, options = {}) {
24756
+ const journalPath = path8.join(paths.forgeDir, "core-sync-journal.json");
24757
+ const recovery = await recoverCoreSyncTransaction({ journalPath });
24758
+ await retireDebugCapture(paths);
24759
+ if (recovery.status === "uncertain") {
24760
+ throw new CoreSyncUncertainError(recovery.message, recovery.uncertainPaths);
24761
+ }
24762
+ await mkdir5(paths.opencodeDir, { recursive: true });
24763
+ return reconcileSyncSnapshot({
24764
+ applyCore: () => applyCoreManifest(paths, credentials, manifest, options),
24765
+ applyWorkPacks: () => applyWorkPackManifest(paths, credentials, manifest, options)
24766
+ });
24767
+ }
24768
+ async function applyCoreManifest(paths, credentials, manifest, options) {
24769
+ const attachmentPluginPath = path8.join(paths.pluginDir, FORGE_PLUGIN_FILENAME);
24770
+ const evidencePluginPath = path8.join(paths.pluginDir, FORGE_EVIDENCE_PLUGIN_FILENAME);
24771
+ const debugTracePluginPath = path8.join(paths.pluginDir, FORGE_DEBUG_TRACE_PLUGIN_FILENAME);
24772
+ const legacyAttachmentPluginPath = path8.join(paths.opencodeDir, "plugin", FORGE_PLUGIN_FILENAME);
24773
+ const debugTraceConfigPath = path8.join(paths.forgeDir, FORGE_DEBUG_TRACE_CONFIG_FILENAME);
24774
+ const rules = attachmentBridgeRules(manifest.config.models);
24775
+ let bridgeEnabled = Boolean(manifest.config.documentReaderModel) && Object.keys(rules).length > 0;
24776
+ const existingConfig = await readJsoncObject(paths.opencodeConfigPath);
24777
+ const existingTuiConfig = await readJsoncObject(paths.tuiConfigPath);
24778
+ const legacyPluginManaged = legacyAttachmentPluginPath !== attachmentPluginPath && await isManagedPluginFile(legacyAttachmentPluginPath);
24779
+ const legacyPluginEntryStale = legacyAttachmentPluginPath !== attachmentPluginPath && hasPluginEntry(existingConfig, legacyAttachmentPluginPath);
24780
+ const attachmentPluginForeign = await isForeignPluginFile(attachmentPluginPath);
24781
+ const attachmentPluginManaged = await isManagedPluginFile(attachmentPluginPath);
24782
+ const evidencePluginForeign = await isForeignPluginFile(evidencePluginPath);
24783
+ const debugTracePluginForeign = await isForeignPluginFile(debugTracePluginPath);
24784
+ const debugTracePluginManaged = await isManagedPluginFile(debugTracePluginPath);
24785
+ const evidenceEnabled = !evidencePluginForeign;
24786
+ if (bridgeEnabled && attachmentPluginForeign) bridgeEnabled = false;
24787
+ const config2 = withPluginPaths(
24788
+ options.remoteConfig ? stripForgeManagedConfig(
24789
+ mergeOpenCodeConfig(existingConfig, manifest, credentials.forgeBaseUrl, credentials.forgeApiKey, {
24790
+ omitManagedProviders: true,
24791
+ ...legacyPluginManaged || legacyPluginEntryStale ? { removePluginPath: legacyAttachmentPluginPath } : {}
24792
+ })
24793
+ ) : mergeOpenCodeConfig(
24794
+ existingConfig,
24795
+ manifest,
24796
+ credentials.forgeBaseUrl,
24797
+ credentials.forgeApiKey,
24798
+ {
24799
+ automaticWorkPackSync: true,
24800
+ localConfig: true,
24801
+ ...legacyPluginManaged || legacyPluginEntryStale ? { removePluginPath: legacyAttachmentPluginPath } : {}
24802
+ }
24803
+ ),
24804
+ [evidenceEnabled ? evidencePluginPath : void 0],
24805
+ debugTracePluginForeign ? [] : [debugTracePluginPath]
24806
+ );
24807
+ const files = [
24808
+ {
24809
+ id: "opencode-config",
24810
+ path: paths.opencodeConfigPath,
24811
+ bytes: jsonBytes(config2),
24812
+ ...options.remoteConfig ? {} : { mode: 384, ownerOnly: true }
24813
+ },
24814
+ { id: "tui-config", path: paths.tuiConfigPath, bytes: jsonBytes({ ...existingTuiConfig, ...renderTuiConfig(manifest) }) }
24815
+ ];
24816
+ if (!attachmentPluginForeign && (bridgeEnabled || attachmentPluginManaged)) {
24817
+ files.push({
24818
+ id: "attachment-plugin",
24819
+ path: attachmentPluginPath,
24820
+ bytes: bridgeEnabled ? Buffer.from(renderAttachmentBridgePlugin(rules)) : null
24821
+ });
24822
+ }
24823
+ if (evidenceEnabled) {
24824
+ files.push({ id: "evidence-plugin", path: evidencePluginPath, bytes: Buffer.from(renderEvidencePlugin()) });
24825
+ }
24826
+ if (!debugTracePluginForeign && debugTracePluginManaged) {
24827
+ files.push({
24828
+ id: "debug-trace-plugin",
24829
+ path: debugTracePluginPath,
24830
+ bytes: null
24831
+ });
24832
+ }
24833
+ if (legacyPluginManaged) {
24834
+ files.push({ id: "legacy-attachment-plugin", path: legacyAttachmentPluginPath, bytes: null });
24835
+ }
24836
+ if (await isManagedDebugTraceConfig(debugTraceConfigPath)) {
24837
+ files.push({ id: "debug-trace-config", path: debugTraceConfigPath, bytes: null });
24838
+ }
24839
+ if (!options.remoteConfig) files.push(lastGoodLocalConfigFile(paths, credentials, JSON.stringify(config2, null, 2) + "\n"));
24840
+ else {
24841
+ const retired = await retiredLastGoodLocalConfigFile(paths);
24842
+ if (retired) files.push(retired);
24843
+ }
24844
+ const digest2 = coreRuntimeManifestDigest(files);
24845
+ await applyCoreSyncTransaction({
24846
+ manifest: {
24847
+ version: 1,
24848
+ id: `derived:${digest2.slice(0, 32)}`,
24849
+ digest: digest2,
24850
+ files
24851
+ },
24852
+ journalPath: path8.join(paths.forgeDir, "core-sync-journal.json"),
24853
+ hooks: options.coreTransactionHooks
24854
+ });
24855
+ await removeLegacyDebugTraceRuntime(paths);
24856
+ return { configPath: paths.opencodeConfigPath, tuiPath: paths.tuiConfigPath };
23989
24857
  }
23990
24858
  async function applyWorkPackManifest(paths, credentials, manifest, options) {
23991
- await mkdir2(paths.skillsDir, { recursive: true });
23992
- await mkdir2(paths.commandsDir, { recursive: true });
24859
+ await mkdir5(paths.skillsDir, { recursive: true });
24860
+ await mkdir5(paths.commandsDir, { recursive: true });
23993
24861
  const recovery = await recoverInterruptedWorkPackInstalls(paths, options.cleanupWorkPackBackup, options.workPackProjectionBoundary);
23994
24862
  const managed = await Promise.all((await managedWorkPackSlugs(paths.skillsDir)).map(async (slug) => ({
23995
24863
  slug,
23996
- version: (await readFile3(path5.join(paths.skillsDir, slug, ".forge-version"), "utf8")).trim(),
23997
- agents: await readAgentRecord(path5.join(paths.skillsDir, slug)),
23998
- commands: await readCommandRecord(path5.join(paths.skillsDir, slug))
24864
+ version: (await readFile7(path8.join(paths.skillsDir, slug, ".forge-version"), "utf8")).trim(),
24865
+ agents: await readAgentRecord(path8.join(paths.skillsDir, slug)),
24866
+ commands: await readCommandRecord(path8.join(paths.skillsDir, slug))
23999
24867
  })));
24000
24868
  const desired = manifest.skills.map((skill) => ({
24001
24869
  slug: skill.slug,
@@ -24019,7 +24887,7 @@ async function applyWorkPackManifest(paths, credentials, manifest, options) {
24019
24887
  options
24020
24888
  )),
24021
24889
  recoveryFailures: recovery.failures,
24022
- writeAtomicReceipt: (receipt) => writeJsonAtomic2(path5.join(paths.forgeDir, "work-pack-sync-receipt.json"), receipt)
24890
+ writeAtomicReceipt: (receipt) => writeJsonAtomic2(path8.join(paths.forgeDir, "work-pack-sync-receipt.json"), receipt)
24023
24891
  });
24024
24892
  const installed = workPacks.outcomes.filter((outcome) => outcome.status === "installed").map((outcome) => `${outcome.slug}@${outcome.version}`);
24025
24893
  const removed = workPacks.outcomes.filter((outcome) => outcome.status === "removed").map((outcome) => outcome.slug);
@@ -24030,7 +24898,7 @@ async function applyWorkPackManifest(paths, credentials, manifest, options) {
24030
24898
  async function collectWorkPackObservations(paths, reconciliation) {
24031
24899
  const installedVersions = /* @__PURE__ */ new Map();
24032
24900
  for (const slug of await managedWorkPackSlugs(paths.skillsDir)) {
24033
- const version2 = (await readFile3(path5.join(paths.skillsDir, slug, ".forge-version"), "utf8")).trim();
24901
+ const version2 = (await readFile7(path8.join(paths.skillsDir, slug, ".forge-version"), "utf8")).trim();
24034
24902
  if (version2) installedVersions.set(slug, version2);
24035
24903
  }
24036
24904
  const observations = new Map(
@@ -24061,7 +24929,7 @@ async function enrichIntegrityFailure(paths, operation, result) {
24061
24929
  }
24062
24930
  }
24063
24931
  async function operateWorkPack(paths, credentials, skillBySlug, approvedModelIds, cleanupPendingSlugs, recoveryFailures, operation, options) {
24064
- const target = path5.join(paths.skillsDir, operation.pack.slug);
24932
+ const target = path8.join(paths.skillsDir, operation.pack.slug);
24065
24933
  const recoveryFailure = recoveryFailures.get(operation.pack.slug);
24066
24934
  if (recoveryFailure) return { status: "failed", restoration: "exact", code: recoveryFailure };
24067
24935
  let ownership;
@@ -24100,7 +24968,7 @@ async function operateWorkPack(paths, credentials, skillBySlug, approvedModelIds
24100
24968
  let previousManagedPaths;
24101
24969
  let archive;
24102
24970
  try {
24103
- const currentVersion = await readFile3(path5.join(target, ".forge-version"), "utf8").catch(() => "");
24971
+ const currentVersion = await readFile7(path8.join(target, ".forge-version"), "utf8").catch(() => "");
24104
24972
  const sameVersion = currentVersion.trim() === skill.version;
24105
24973
  if (ownership === "managed") {
24106
24974
  let localState = await checkWorkPackInstalledState({
@@ -24124,7 +24992,7 @@ async function operateWorkPack(paths, credentials, skillBySlug, approvedModelIds
24124
24992
  }) ? "match" : "changed";
24125
24993
  } else if (sameVersion) {
24126
24994
  const candidateArchive = await downloadSkill(credentials, skill.url);
24127
- if (createHash3("sha256").update(candidateArchive).digest("hex") !== skill.sha256)
24995
+ if (createHash4("sha256").update(candidateArchive).digest("hex") !== skill.sha256)
24128
24996
  return { status: "failed", restoration: "exact", code: "local-baseline-missing" };
24129
24997
  localState = await adoptLegacyWorkPackState(paths, skill.slug, skill.version, candidateArchive, approvedModelIds) ? "match" : "changed";
24130
24998
  }
@@ -24144,8 +25012,8 @@ async function operateWorkPack(paths, credentials, skillBySlug, approvedModelIds
24144
25012
  }
24145
25013
  previousManagedPaths = await managedWorkPackPaths(paths, target);
24146
25014
  archive = await downloadSkill(credentials, skill.url);
24147
- const sha256 = createHash3("sha256").update(archive).digest("hex");
24148
- if (sha256 !== skill.sha256) return { status: "failed", restoration: "exact", code: "checksum-mismatch" };
25015
+ const sha2562 = createHash4("sha256").update(archive).digest("hex");
25016
+ if (sha2562 !== skill.sha256) return { status: "failed", restoration: "exact", code: "checksum-mismatch" };
24149
25017
  } catch (error45) {
24150
25018
  return exactPackFailure(error45);
24151
25019
  }
@@ -24206,6 +25074,52 @@ var WorkPackProjectionConflictError = class extends Error {
24206
25074
  kind;
24207
25075
  filename;
24208
25076
  };
25077
+ function jsonBytes(value) {
25078
+ return Buffer.from(`${JSON.stringify(value, null, 2)}
25079
+ `);
25080
+ }
25081
+ async function removeLegacyDebugTraceRuntime(paths) {
25082
+ const launchAgentPath = path8.join(os4.homedir(), "Library", "LaunchAgents", "com.minimal-forge.debug-trace.plist");
25083
+ const launchAgent = await readFile7(launchAgentPath, "utf8").catch((error45) => {
25084
+ if (error45.code === "ENOENT") return void 0;
25085
+ throw error45;
25086
+ });
25087
+ if (launchAgent?.includes("<string>com.minimal-forge.debug-trace</string>")) {
25088
+ if (process.platform === "darwin") {
25089
+ const domain2 = `gui/${process.getuid?.() ?? 0}`;
25090
+ const stopped = spawnSync("launchctl", ["bootout", domain2, launchAgentPath], { encoding: "utf8" });
25091
+ if (stopped.status !== 0) {
25092
+ const stillRunning = spawnSync("launchctl", ["print", `${domain2}/com.minimal-forge.debug-trace`], { encoding: "utf8" });
25093
+ if (stillRunning.status === 0) throw new Error("O servi\xE7o antigo de debug trace continua ativo; a sincroniza\xE7\xE3o n\xE3o removeu os seus ficheiros.");
25094
+ }
25095
+ }
25096
+ await rm4(launchAgentPath, { force: true });
25097
+ }
25098
+ for (const filename of [
25099
+ "debug-trace-service.sh",
25100
+ "debug-trace-service-state.json",
25101
+ "debug-trace-service.out.log",
25102
+ "debug-trace-service.err.log",
25103
+ "opencode-debug-trace"
25104
+ ]) {
25105
+ await rm4(path8.join(paths.forgeDir, filename), { force: true });
25106
+ }
25107
+ await rm4(path8.join(paths.forgeDir, "claude-tap-traces"), { recursive: true, force: true });
25108
+ await rm4(path8.join(paths.forgeDir, "verified-claude-tap"), { recursive: true, force: true });
25109
+ }
25110
+ async function isManagedDebugTraceConfig(configPath) {
25111
+ const raw = await readFile7(configPath, "utf8").catch((error45) => {
25112
+ if (error45.code === "ENOENT") return void 0;
25113
+ throw error45;
25114
+ });
25115
+ if (!raw) return false;
25116
+ try {
25117
+ const parsed = JSON.parse(raw);
25118
+ return Boolean(parsed && typeof parsed === "object" && !Array.isArray(parsed) && parsed["managedBy"] === FORGE_DEBUG_TRACE_MANAGED_BY);
25119
+ } catch {
25120
+ return false;
25121
+ }
25122
+ }
24209
25123
  async function downloadSkill(credentials, url2) {
24210
25124
  const forgeUrl = new URL(credentials.forgeBaseUrl);
24211
25125
  const archiveUrl = new URL(url2, forgeUrl);
@@ -24258,7 +25172,7 @@ var WorkPackLocalEditsError = class extends Error {
24258
25172
  async function assertWorkPackUnchangedAtBoundary(paths, target, snapshot) {
24259
25173
  const ownership = await workPackOwnership(target);
24260
25174
  if (ownership === "absent") return;
24261
- if (ownership === "foreign") throw foreignWorkPackError(path5.basename(target));
25175
+ if (ownership === "foreign") throw foreignWorkPackError(path8.basename(target));
24262
25176
  const localState = await checkWorkPackInstalledState({
24263
25177
  packDir: target,
24264
25178
  agentsDir: paths.agentsDir,
@@ -24300,31 +25214,31 @@ async function preserveWorkPackExtras(target, nextPath, actual) {
24300
25214
  `A nova vers\xE3o usa o caminho adicional "${name}". O pacote anterior e os ficheiros locais foram preservados.`
24301
25215
  );
24302
25216
  }
24303
- for (const directory of directories) await mkdir2(path5.join(nextPath, directory), { recursive: true });
25217
+ for (const directory of directories) await mkdir5(path8.join(nextPath, directory), { recursive: true });
24304
25218
  for (const file2 of extras) {
24305
- const destination = path5.join(nextPath, file2.path);
24306
- await mkdir2(path5.dirname(destination), { recursive: true });
24307
- await cp(path5.join(target, file2.path), destination, { errorOnExist: true, force: false });
24308
- if (createHash3("sha256").update(await readFile3(destination)).digest("hex") !== file2.sha256)
25219
+ const destination = path8.join(nextPath, file2.path);
25220
+ await mkdir5(path8.dirname(destination), { recursive: true });
25221
+ await cp(path8.join(target, file2.path), destination, { errorOnExist: true, force: false });
25222
+ if (createHash4("sha256").update(await readFile7(destination)).digest("hex") !== file2.sha256)
24309
25223
  throw new WorkPackLocalEditsError("local-edits-preserved");
24310
25224
  }
24311
25225
  }
24312
25226
  async function installSkillArchive(paths, slug, version2, archive, options = {}) {
24313
- const tempRoot = await mkdtemp(path5.join(os4.tmpdir(), `forge-${slug}-`));
24314
- const archivePath = path5.join(tempRoot, `${slug}.tar`);
24315
- const extractPath = path5.join(tempRoot, "extract");
24316
- const nextPath = path5.join(tempRoot, slug);
24317
- const target = path5.join(paths.skillsDir, slug);
24318
- const backup = path5.join(paths.skillsDir, `${slug}.previous`);
25227
+ const tempRoot = await mkdtemp(path8.join(os4.tmpdir(), `forge-${slug}-`));
25228
+ const archivePath = path8.join(tempRoot, `${slug}.tar`);
25229
+ const extractPath = path8.join(tempRoot, "extract");
25230
+ const nextPath = path8.join(tempRoot, slug);
25231
+ const target = path8.join(paths.skillsDir, slug);
25232
+ const backup = path8.join(paths.skillsDir, `${slug}.previous`);
24319
25233
  let agentFiles;
24320
25234
  let commandFiles;
24321
25235
  let previousAgents;
24322
25236
  let previousCommands;
24323
25237
  try {
24324
- await mkdir2(extractPath, { recursive: true });
24325
- await writeFile3(archivePath, archive);
25238
+ await mkdir5(extractPath, { recursive: true });
25239
+ await writeFile6(archivePath, archive);
24326
25240
  await So({ file: archivePath, cwd: extractPath, strict: true });
24327
- const extractedSkillPath = path5.join(extractPath, slug);
25241
+ const extractedSkillPath = path8.join(extractPath, slug);
24328
25242
  await assertNoReservedMarkerAliases(extractedSkillPath);
24329
25243
  await validateSkillFolder(extractedSkillPath, slug);
24330
25244
  agentFiles = await normalizePackAgentModels(
@@ -24345,21 +25259,21 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
24345
25259
  await assertNoForeignCommandConflicts(paths.commandsDir, commandFiles, previousCommands, slug);
24346
25260
  } catch (error45) {
24347
25261
  try {
24348
- await rm(tempRoot, { recursive: true, force: true });
25262
+ await rm4(tempRoot, { recursive: true, force: true });
24349
25263
  } catch (cleanupError) {
24350
25264
  throw new AggregateError([error45, cleanupError], `Falha ao validar e limpar o pacote de trabalho ${slug}`);
24351
25265
  }
24352
25266
  throw error45;
24353
25267
  }
24354
- await rename3(path5.join(extractPath, slug), nextPath);
24355
- await writeFile3(path5.join(nextPath, ".forge-version"), `${version2}
25268
+ await rename6(path8.join(extractPath, slug), nextPath);
25269
+ await writeFile6(path8.join(nextPath, ".forge-version"), `${version2}
24356
25270
  `);
24357
25271
  if (agentFiles.length > 0) {
24358
- await writeFile3(path5.join(nextPath, ".forge-agents"), `${agentFiles.map((agent) => agent.filename).join("\n")}
25272
+ await writeFile6(path8.join(nextPath, ".forge-agents"), `${agentFiles.map((agent) => agent.filename).join("\n")}
24359
25273
  `);
24360
25274
  }
24361
25275
  if (commandFiles.length > 0) {
24362
- await writeFile3(path5.join(nextPath, ".forge-commands"), `${commandFiles.map((command) => command.filename).join("\n")}
25276
+ await writeFile6(path8.join(nextPath, ".forge-commands"), `${commandFiles.map((command) => command.filename).join("\n")}
24363
25277
  `);
24364
25278
  }
24365
25279
  await writeWorkPackInstalledState({ packDir: nextPath, version: version2, agents: agentFiles, commands: commandFiles });
@@ -24370,13 +25284,13 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
24370
25284
  const agentTransactionState = new Map(
24371
25285
  [...agentSnapshot.keys()].map((filePath) => [
24372
25286
  filePath,
24373
- agentFiles.find((agent) => agent.filename === path5.basename(filePath))?.content
25287
+ agentFiles.find((agent) => agent.filename === path8.basename(filePath))?.content
24374
25288
  ])
24375
25289
  );
24376
25290
  const commandTransactionState = new Map(
24377
25291
  [...commandSnapshot.keys()].map((filePath) => [
24378
25292
  filePath,
24379
- commandFiles.find((command) => command.filename === path5.basename(filePath))?.content
25293
+ commandFiles.find((command) => command.filename === path8.basename(filePath))?.content
24380
25294
  ])
24381
25295
  );
24382
25296
  const previousManagedPaths = await managedWorkPackPaths(paths, target);
@@ -24393,57 +25307,57 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
24393
25307
  if (previousManagedPaths.length > 0) await options.beforeManagedPathsRemoved?.(previousManagedPaths);
24394
25308
  await assertWorkPackUnchangedAtBoundary(paths, target, originalTree);
24395
25309
  } catch (error45) {
24396
- await rm(tempRoot, { recursive: true, force: true });
25310
+ await rm4(tempRoot, { recursive: true, force: true });
24397
25311
  throw error45;
24398
25312
  }
24399
25313
  const writeProjection = options.writeWorkPackProjection ?? writeTextAtomic;
24400
- const claimedBackup = path5.join(tempRoot, `${slug}-claimed-previous`);
25314
+ const claimedBackup = path8.join(tempRoot, `${slug}-claimed-previous`);
24401
25315
  const transactionPath = `${backup}${WORK_PACK_TRANSACTION_SUFFIX}`;
24402
25316
  let targetBackedUp = false;
24403
25317
  let targetInstalled = false;
24404
25318
  let backupClaimed = false;
24405
25319
  try {
24406
- await rm(backup, { recursive: true, force: true });
24407
- await rm(transactionPath, { force: true });
25320
+ await rm4(backup, { recursive: true, force: true });
25321
+ await rm4(transactionPath, { force: true });
24408
25322
  await writeTextAtomic(transactionPath, "install\n");
24409
25323
  try {
24410
- await rename3(target, backup);
25324
+ await rename6(target, backup);
24411
25325
  targetBackedUp = true;
24412
25326
  } catch (error45) {
24413
25327
  if (error45.code !== "ENOENT") throw error45;
24414
- await rm(transactionPath, { force: true });
25328
+ await rm4(transactionPath, { force: true });
24415
25329
  }
24416
25330
  if (targetBackedUp) {
24417
25331
  await options.installWorkPackBoundary?.("after-backup");
24418
25332
  await assertWorkPackUnchangedAtBoundary(paths, backup, originalTree);
24419
25333
  }
24420
- await rename3(nextPath, target);
25334
+ await rename6(nextPath, target);
24421
25335
  targetInstalled = true;
24422
25336
  for (const filename of previousAgents.filter((name) => !nextAgentNames.has(name))) {
24423
- const filePath = path5.join(paths.agentsDir, filename);
25337
+ const filePath = path8.join(paths.agentsDir, filename);
24424
25338
  await options.workPackProjectionBoundary?.("install", filePath);
24425
25339
  await assertProjectionState(filePath, agentSnapshot.get(filePath));
24426
- await rm(filePath, { force: true });
25340
+ await rm4(filePath, { force: true });
24427
25341
  }
24428
25342
  if (agentFiles.length > 0) {
24429
- await mkdir2(paths.agentsDir, { recursive: true });
25343
+ await mkdir5(paths.agentsDir, { recursive: true });
24430
25344
  for (const agent of agentFiles) {
24431
- const filePath = path5.join(paths.agentsDir, agent.filename);
25345
+ const filePath = path8.join(paths.agentsDir, agent.filename);
24432
25346
  await options.workPackProjectionBoundary?.("install", filePath);
24433
25347
  await assertProjectionState(filePath, agentSnapshot.get(filePath));
24434
25348
  await writeProjection(filePath, agent.content);
24435
25349
  }
24436
25350
  }
24437
25351
  for (const filename of previousCommands.filter((name) => !nextCommandNames.has(name))) {
24438
- const filePath = path5.join(paths.commandsDir, filename);
25352
+ const filePath = path8.join(paths.commandsDir, filename);
24439
25353
  await options.workPackProjectionBoundary?.("install", filePath);
24440
25354
  await assertProjectionState(filePath, commandSnapshot.get(filePath));
24441
- await rm(filePath, { force: true });
25355
+ await rm4(filePath, { force: true });
24442
25356
  }
24443
25357
  if (commandFiles.length > 0) {
24444
- await mkdir2(paths.commandsDir, { recursive: true });
25358
+ await mkdir5(paths.commandsDir, { recursive: true });
24445
25359
  for (const command of commandFiles) {
24446
- const filePath = path5.join(paths.commandsDir, command.filename);
25360
+ const filePath = path8.join(paths.commandsDir, command.filename);
24447
25361
  await options.workPackProjectionBoundary?.("install", filePath);
24448
25362
  await assertProjectionState(filePath, commandSnapshot.get(filePath));
24449
25363
  await writeProjection(filePath, command.content);
@@ -24453,10 +25367,10 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
24453
25367
  if (targetBackedUp) await options.installWorkPackBoundary?.("before-commit");
24454
25368
  await assertWorkPackTreeUnchangedAtBoundary(target, installedTree);
24455
25369
  if (targetBackedUp) {
24456
- await rename3(backup, claimedBackup);
25370
+ await rename6(backup, claimedBackup);
24457
25371
  backupClaimed = true;
24458
25372
  await assertWorkPackTreeUnchangedAtBoundary(claimedBackup, originalTree);
24459
- await writeFile3(path5.join(claimedBackup, WORK_PACK_COMMITTED_MARKER), `${version2}
25373
+ await writeFile6(path8.join(claimedBackup, WORK_PACK_COMMITTED_MARKER), `${version2}
24460
25374
  `);
24461
25375
  await writeTextAtomic(transactionPath, "committed\n");
24462
25376
  }
@@ -24468,18 +25382,18 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
24468
25382
  await restoreProjectionState(commandSnapshot, commandTransactionState);
24469
25383
  }
24470
25384
  if (targetBackedUp) {
24471
- const restoredTarget = path5.join(tempRoot, `${slug}-restore`);
25385
+ const restoredTarget = path8.join(tempRoot, `${slug}-restore`);
24472
25386
  const rollbackSource = backupClaimed ? claimedBackup : backup;
24473
25387
  await cp(rollbackSource, restoredTarget, { recursive: true });
24474
- if (targetInstalled) await rm(target, { recursive: true, force: true });
24475
- await rename3(restoredTarget, target);
24476
- await rm(rollbackSource, { recursive: true, force: true });
24477
- await rm(transactionPath, { force: true });
25388
+ if (targetInstalled) await rm4(target, { recursive: true, force: true });
25389
+ await rename6(restoredTarget, target);
25390
+ await rm4(rollbackSource, { recursive: true, force: true });
25391
+ await rm4(transactionPath, { force: true });
24478
25392
  } else if (targetInstalled) {
24479
- await rm(target, { recursive: true, force: true });
25393
+ await rm4(target, { recursive: true, force: true });
24480
25394
  }
24481
- await rm(transactionPath, { force: true });
24482
- await rm(tempRoot, { recursive: true, force: true });
25395
+ await rm4(transactionPath, { force: true });
25396
+ await rm4(tempRoot, { recursive: true, force: true });
24483
25397
  } catch (restoreError) {
24484
25398
  throw new WorkPackRecoveryUncertainError(`Falha ao instalar e restaurar o pacote de trabalho ${slug}`, {
24485
25399
  cause: new AggregateError([error45, restoreError])
@@ -24487,43 +25401,43 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
24487
25401
  }
24488
25402
  throw error45;
24489
25403
  }
24490
- let cleanup = "complete";
25404
+ let cleanup2 = "complete";
24491
25405
  const cleanupTarget = backupClaimed ? claimedBackup : backup;
24492
25406
  try {
24493
25407
  await (options.cleanupWorkPackBackup ?? removeWorkPackBackup)(cleanupTarget);
24494
- await rm(transactionPath, { force: true });
25408
+ await rm4(transactionPath, { force: true });
24495
25409
  } catch {
24496
25410
  if (!await pathExists(cleanupTarget)) {
24497
- cleanup = "complete";
24498
- await rm(transactionPath, { force: true });
25411
+ cleanup2 = "complete";
25412
+ await rm4(transactionPath, { force: true });
24499
25413
  } else {
24500
- cleanup = "pending";
24501
- if (backupClaimed) await rename3(claimedBackup, backup);
25414
+ cleanup2 = "pending";
25415
+ if (backupClaimed) await rename6(claimedBackup, backup);
24502
25416
  }
24503
25417
  }
24504
- await rm(tempRoot, { recursive: true, force: true }).catch(() => void 0);
24505
- return { cleanup };
25418
+ await rm4(tempRoot, { recursive: true, force: true }).catch(() => void 0);
25419
+ return { cleanup: cleanup2 };
24506
25420
  }
24507
25421
  async function adoptLegacyWorkPackState(paths, slug, version2, archive, approvedModelIds) {
24508
- const comparisonRoot = await mkdtemp(path5.join(os4.tmpdir(), `forge-${slug}-baseline-`));
25422
+ const comparisonRoot = await mkdtemp(path8.join(os4.tmpdir(), `forge-${slug}-baseline-`));
24509
25423
  const comparisonPaths = {
24510
25424
  ...paths,
24511
- skillsDir: path5.join(comparisonRoot, "skills"),
24512
- agentsDir: path5.join(comparisonRoot, "agents"),
24513
- commandsDir: path5.join(comparisonRoot, "commands")
25425
+ skillsDir: path8.join(comparisonRoot, "skills"),
25426
+ agentsDir: path8.join(comparisonRoot, "agents"),
25427
+ commandsDir: path8.join(comparisonRoot, "commands")
24514
25428
  };
24515
25429
  try {
24516
- await mkdir2(comparisonPaths.skillsDir, { recursive: true });
25430
+ await mkdir5(comparisonPaths.skillsDir, { recursive: true });
24517
25431
  await installSkillArchive(comparisonPaths, slug, version2, archive, { approvedModelIds });
24518
25432
  return adoptWorkPackInstalledState({
24519
- expectedPackDir: path5.join(comparisonPaths.skillsDir, slug),
24520
- packDir: path5.join(paths.skillsDir, slug),
25433
+ expectedPackDir: path8.join(comparisonPaths.skillsDir, slug),
25434
+ packDir: path8.join(paths.skillsDir, slug),
24521
25435
  agentsDir: paths.agentsDir,
24522
25436
  commandsDir: paths.commandsDir,
24523
25437
  allowAdditional: true
24524
25438
  });
24525
25439
  } finally {
24526
- await rm(comparisonRoot, { recursive: true, force: true }).catch(() => void 0);
25440
+ await rm4(comparisonRoot, { recursive: true, force: true }).catch(() => void 0);
24527
25441
  }
24528
25442
  }
24529
25443
  async function recoverInterruptedWorkPackInstalls(paths, cleanupWorkPackBackup, workPackProjectionBoundary) {
@@ -24537,16 +25451,16 @@ async function recoverInterruptedWorkPackInstalls(paths, cleanupWorkPackBackup,
24537
25451
  if (!entry.name.endsWith(".previous")) continue;
24538
25452
  const slug = entry.name.slice(0, -".previous".length);
24539
25453
  if (!slug) continue;
24540
- const target = path5.join(paths.skillsDir, slug);
25454
+ const target = path8.join(paths.skillsDir, slug);
24541
25455
  const backup = `${target}.previous`;
24542
25456
  const transactionState = await readWorkPackTransactionState(backup);
24543
25457
  if (transactionState === "committed") {
24544
25458
  try {
24545
25459
  await (cleanupWorkPackBackup ?? removeWorkPackBackup)(backup);
24546
- await rm(`${backup}${WORK_PACK_TRANSACTION_SUFFIX}`, { force: true });
25460
+ await rm4(`${backup}${WORK_PACK_TRANSACTION_SUFFIX}`, { force: true });
24547
25461
  } catch {
24548
25462
  if (await pathExists(backup)) cleanupPending.add(slug);
24549
- else await rm(`${backup}${WORK_PACK_TRANSACTION_SUFFIX}`, { force: true });
25463
+ else await rm4(`${backup}${WORK_PACK_TRANSACTION_SUFFIX}`, { force: true });
24550
25464
  }
24551
25465
  continue;
24552
25466
  }
@@ -24570,9 +25484,9 @@ async function recoverInterruptedWorkPackInstall(paths, target, cleanupWorkPackB
24570
25484
  const backup = `${target}.previous`;
24571
25485
  const backupOwnership = await workPackOwnership(backup);
24572
25486
  if (backupOwnership === "absent") return "recovered";
24573
- if (backupOwnership === "foreign") throw foreignWorkPackError(path5.basename(target));
24574
- if (await workPackOwnership(target) === "foreign") throw foreignWorkPackError(path5.basename(target));
24575
- const committed = await readFile3(path5.join(backup, WORK_PACK_COMMITTED_MARKER), "utf8").catch((error45) => {
25487
+ if (backupOwnership === "foreign") throw foreignWorkPackError(path8.basename(target));
25488
+ if (await workPackOwnership(target) === "foreign") throw foreignWorkPackError(path8.basename(target));
25489
+ const committed = await readFile7(path8.join(backup, WORK_PACK_COMMITTED_MARKER), "utf8").catch((error45) => {
24576
25490
  if (error45.code === "ENOENT") return void 0;
24577
25491
  throw error45;
24578
25492
  });
@@ -24620,50 +25534,50 @@ async function recoverInterruptedWorkPackInstall(paths, target, cleanupWorkPackB
24620
25534
  );
24621
25535
  const previousAgentNames = new Set(previousAgents.map((agent) => agent.filename));
24622
25536
  const previousCommandNames = new Set(previousCommands.map((command) => command.filename));
24623
- const recoveryRoot = await mkdtemp(path5.join(os4.tmpdir(), "forge-recover-"));
24624
- const recoveredTarget = path5.join(recoveryRoot, path5.basename(target));
25537
+ const recoveryRoot = await mkdtemp(path8.join(os4.tmpdir(), "forge-recover-"));
25538
+ const recoveredTarget = path8.join(recoveryRoot, path8.basename(target));
24625
25539
  await cp(backup, recoveredTarget, { recursive: true });
24626
25540
  try {
24627
25541
  for (const filename of currentAgents.filter((name) => !previousAgentNames.has(name))) {
24628
- const filePath = path5.join(paths.agentsDir, filename);
25542
+ const filePath = path8.join(paths.agentsDir, filename);
24629
25543
  await workPackProjectionBoundary?.("recover", filePath);
24630
25544
  await assertProjectionState(filePath, agentRecoveryState.get(filePath));
24631
- await rm(filePath, { force: true });
25545
+ await rm4(filePath, { force: true });
24632
25546
  }
24633
- await mkdir2(paths.agentsDir, { recursive: true });
25547
+ await mkdir5(paths.agentsDir, { recursive: true });
24634
25548
  for (const agent of previousAgents) {
24635
- const filePath = path5.join(paths.agentsDir, agent.filename);
25549
+ const filePath = path8.join(paths.agentsDir, agent.filename);
24636
25550
  await workPackProjectionBoundary?.("recover", filePath);
24637
25551
  await assertProjectionState(filePath, agentRecoveryState.get(filePath));
24638
25552
  await writeTextAtomic(filePath, agent.content);
24639
25553
  }
24640
25554
  for (const filename of currentCommands.filter((name) => !previousCommandNames.has(name))) {
24641
- const filePath = path5.join(paths.commandsDir, filename);
25555
+ const filePath = path8.join(paths.commandsDir, filename);
24642
25556
  await workPackProjectionBoundary?.("recover", filePath);
24643
25557
  await assertProjectionState(filePath, commandRecoveryState.get(filePath));
24644
- await rm(filePath, { force: true });
25558
+ await rm4(filePath, { force: true });
24645
25559
  }
24646
- await mkdir2(paths.commandsDir, { recursive: true });
25560
+ await mkdir5(paths.commandsDir, { recursive: true });
24647
25561
  for (const command of previousCommands) {
24648
- const filePath = path5.join(paths.commandsDir, command.filename);
25562
+ const filePath = path8.join(paths.commandsDir, command.filename);
24649
25563
  await workPackProjectionBoundary?.("recover", filePath);
24650
25564
  await assertProjectionState(filePath, commandRecoveryState.get(filePath));
24651
25565
  await writeTextAtomic(filePath, command.content);
24652
25566
  }
24653
- await rm(target, { recursive: true, force: true });
24654
- await rename3(recoveredTarget, target);
24655
- await rm(backup, { recursive: true, force: true });
24656
- await rm(`${backup}${WORK_PACK_TRANSACTION_SUFFIX}`, { force: true });
25567
+ await rm4(target, { recursive: true, force: true });
25568
+ await rename6(recoveredTarget, target);
25569
+ await rm4(backup, { recursive: true, force: true });
25570
+ await rm4(`${backup}${WORK_PACK_TRANSACTION_SUFFIX}`, { force: true });
24657
25571
  } finally {
24658
- await rm(recoveryRoot, { recursive: true, force: true }).catch(() => void 0);
25572
+ await rm4(recoveryRoot, { recursive: true, force: true }).catch(() => void 0);
24659
25573
  }
24660
25574
  return "recovered";
24661
25575
  }
24662
25576
  async function removeWorkPackBackup(backupPath) {
24663
- await rm(backupPath, { recursive: true, force: true });
25577
+ await rm4(backupPath, { recursive: true, force: true });
24664
25578
  }
24665
25579
  async function readWorkPackTransactionFile(backup) {
24666
- return readFile3(`${backup}${WORK_PACK_TRANSACTION_SUFFIX}`, "utf8").catch((error45) => {
25580
+ return readFile7(`${backup}${WORK_PACK_TRANSACTION_SUFFIX}`, "utf8").catch((error45) => {
24667
25581
  if (error45.code === "ENOENT") return void 0;
24668
25582
  throw error45;
24669
25583
  });
@@ -24677,7 +25591,7 @@ function isManagedProjectionName(filename) {
24677
25591
  return filename.length > 0 && !filename.includes("/") && !filename.includes("\\") && filename !== "..";
24678
25592
  }
24679
25593
  async function recordRemovedProjection(transactionPath, kind, filename) {
24680
- const current = await readFile3(transactionPath, "utf8");
25594
+ const current = await readFile7(transactionPath, "utf8");
24681
25595
  await writeTextAtomic(transactionPath, `${current.trimEnd()}
24682
25596
  ${kind}:${filename}
24683
25597
  `);
@@ -24702,19 +25616,19 @@ async function readWorkPackRemovedProjections(backup) {
24702
25616
  return { agents, commands };
24703
25617
  }
24704
25618
  async function pathExists(filePath) {
24705
- return lstat4(filePath).then(() => true, (error45) => {
25619
+ return lstat5(filePath).then(() => true, (error45) => {
24706
25620
  if (error45.code === "ENOENT") return false;
24707
25621
  throw error45;
24708
25622
  });
24709
25623
  }
24710
25624
  async function workPackOwnership(target) {
24711
- const targetStat = await lstat4(target).catch((error45) => {
25625
+ const targetStat = await lstat5(target).catch((error45) => {
24712
25626
  if (error45.code === "ENOENT") return void 0;
24713
25627
  throw error45;
24714
25628
  });
24715
25629
  if (!targetStat) return "absent";
24716
25630
  if (!targetStat.isDirectory()) return "foreign";
24717
- const marker = await readFile3(path5.join(target, ".forge-version"), "utf8").catch((error45) => {
25631
+ const marker = await readFile7(path8.join(target, ".forge-version"), "utf8").catch((error45) => {
24718
25632
  if (error45.code === "ENOENT") return void 0;
24719
25633
  throw error45;
24720
25634
  });
@@ -24740,11 +25654,11 @@ async function assertProjectionRecoveryIsSafe(directory, currentFiles, previousF
24740
25654
  expected.set(file2.filename, contents);
24741
25655
  }
24742
25656
  for (const [filename, contents] of expected) {
24743
- const projected = await readFile3(path5.join(directory, filename), "utf8").catch((error45) => {
25657
+ const projected = await readFile7(path8.join(directory, filename), "utf8").catch((error45) => {
24744
25658
  if (error45.code === "ENOENT") return void 0;
24745
25659
  throw error45;
24746
25660
  });
24747
- validated.set(path5.join(directory, filename), projected);
25661
+ validated.set(path8.join(directory, filename), projected);
24748
25662
  const missingPreviousProjection = missingPreviousProjectionIsLocalDeletion(
24749
25663
  filename,
24750
25664
  projected,
@@ -24762,19 +25676,19 @@ async function assertProjectionRecoveryIsSafe(directory, currentFiles, previousF
24762
25676
  return validated;
24763
25677
  }
24764
25678
  async function assertProjectionState(filePath, expected) {
24765
- const current = await readFile3(filePath, "utf8").catch((error45) => {
25679
+ const current = await readFile7(filePath, "utf8").catch((error45) => {
24766
25680
  if (error45.code === "ENOENT") return void 0;
24767
25681
  throw error45;
24768
25682
  });
24769
25683
  if (current !== expected) {
24770
- throw new WorkPackLocalEditsError("local-edits-preserved", `A proje\xE7\xE3o ${path5.basename(filePath)} foi alterada durante a opera\xE7\xE3o`);
25684
+ throw new WorkPackLocalEditsError("local-edits-preserved", `A proje\xE7\xE3o ${path8.basename(filePath)} foi alterada durante a opera\xE7\xE3o`);
24771
25685
  }
24772
25686
  }
24773
25687
  async function captureProjectionState(directory, filenames) {
24774
25688
  const snapshot = /* @__PURE__ */ new Map();
24775
25689
  for (const filename of filenames) {
24776
- const filePath = path5.join(directory, filename);
24777
- const content = await readFile3(filePath, "utf8").catch((error45) => {
25690
+ const filePath = path8.join(directory, filename);
25691
+ const content = await readFile7(filePath, "utf8").catch((error45) => {
24778
25692
  if (error45.code === "ENOENT") return void 0;
24779
25693
  throw error45;
24780
25694
  });
@@ -24785,18 +25699,18 @@ async function captureProjectionState(directory, filenames) {
24785
25699
  async function restoreProjectionState(snapshot, transactionState) {
24786
25700
  for (const [filePath, content] of snapshot) {
24787
25701
  if (transactionState) {
24788
- const current = await readFile3(filePath, "utf8").catch((error45) => {
25702
+ const current = await readFile7(filePath, "utf8").catch((error45) => {
24789
25703
  if (error45.code === "ENOENT") return void 0;
24790
25704
  throw error45;
24791
25705
  });
24792
25706
  if (current !== transactionState.get(filePath)) continue;
24793
25707
  }
24794
- if (content === void 0) await rm(filePath, { force: true });
25708
+ if (content === void 0) await rm4(filePath, { force: true });
24795
25709
  else await writeTextAtomic(filePath, content);
24796
25710
  }
24797
25711
  }
24798
25712
  async function readPackAgentFiles(skillFolder, managedNames) {
24799
- const agentsFolder = path5.join(skillFolder, "agents");
25713
+ const agentsFolder = path8.join(skillFolder, "agents");
24800
25714
  const entries = await readdir3(agentsFolder, { withFileTypes: true }).catch((error45) => {
24801
25715
  if (error45.code === "ENOENT") return [];
24802
25716
  throw error45;
@@ -24805,7 +25719,7 @@ async function readPackAgentFiles(skillFolder, managedNames) {
24805
25719
  for (const entry of entries) {
24806
25720
  if (!entry.isFile() || !entry.name.endsWith(".md") || managedNames && !managedNames.has(entry.name)) continue;
24807
25721
  if (entry.name.startsWith("._")) continue;
24808
- const content = await readFile3(path5.join(agentsFolder, entry.name), "utf8");
25722
+ const content = await readFile7(path8.join(agentsFolder, entry.name), "utf8");
24809
25723
  validateAgentFile(entry.name, content);
24810
25724
  files.push({ filename: entry.name, content });
24811
25725
  }
@@ -24816,7 +25730,7 @@ async function normalizePackAgentModels(skillFolder, agentFiles, approvedModelId
24816
25730
  for (const agent of agentFiles) {
24817
25731
  const content = normalizePackAgentModel(agent.filename, agent.content, approvedModelIds, slug);
24818
25732
  if (content !== agent.content) {
24819
- await writeFile3(path5.join(skillFolder, "agents", agent.filename), content);
25733
+ await writeFile6(path8.join(skillFolder, "agents", agent.filename), content);
24820
25734
  }
24821
25735
  normalized.push({ ...agent, content });
24822
25736
  }
@@ -24836,7 +25750,7 @@ function normalizePackAgentModel(filename, content, approvedModelIds, slug) {
24836
25750
  return normalizePackExtensionModel(`agents/${filename}`, content, approvedModelIds, slug);
24837
25751
  }
24838
25752
  async function readPackCommandFiles(skillFolder, managedNames) {
24839
- const commandsFolder = path5.join(skillFolder, "commands");
25753
+ const commandsFolder = path8.join(skillFolder, "commands");
24840
25754
  const entries = await readdir3(commandsFolder, { withFileTypes: true }).catch((error45) => {
24841
25755
  if (error45.code === "ENOENT") return [];
24842
25756
  throw error45;
@@ -24845,7 +25759,7 @@ async function readPackCommandFiles(skillFolder, managedNames) {
24845
25759
  for (const entry of entries) {
24846
25760
  if (!entry.isFile() || !entry.name.endsWith(".md") || managedNames && !managedNames.has(entry.name)) continue;
24847
25761
  if (entry.name.startsWith("._")) continue;
24848
- const content = await readFile3(path5.join(commandsFolder, entry.name), "utf8");
25762
+ const content = await readFile7(path8.join(commandsFolder, entry.name), "utf8");
24849
25763
  validateCommandFile(entry.name, content);
24850
25764
  files.push({ filename: entry.name, content });
24851
25765
  }
@@ -24856,7 +25770,7 @@ async function normalizePackCommandModels(skillFolder, commandFiles, approvedMod
24856
25770
  for (const command of commandFiles) {
24857
25771
  const content = normalizePackExtensionModel(`commands/${command.filename}`, command.content, approvedModelIds, slug);
24858
25772
  if (content !== command.content) {
24859
- await writeFile3(path5.join(skillFolder, "commands", command.filename), content);
25773
+ await writeFile6(path8.join(skillFolder, "commands", command.filename), content);
24860
25774
  }
24861
25775
  normalized.push({ ...command, content });
24862
25776
  }
@@ -24878,7 +25792,7 @@ async function assertNoForeignAgentConflicts(agentsDir, agentFiles, ownedFilenam
24878
25792
  const owned = new Set(ownedFilenames);
24879
25793
  for (const agent of agentFiles) {
24880
25794
  if (owned.has(agent.filename)) continue;
24881
- const existing = await readFile3(path5.join(agentsDir, agent.filename), "utf8").catch((error45) => {
25795
+ const existing = await readFile7(path8.join(agentsDir, agent.filename), "utf8").catch((error45) => {
24882
25796
  if (error45.code === "ENOENT") return void 0;
24883
25797
  throw error45;
24884
25798
  });
@@ -24891,7 +25805,7 @@ async function assertNoForeignCommandConflicts(commandsDir, commandFiles, ownedF
24891
25805
  const owned = new Set(ownedFilenames);
24892
25806
  for (const command of commandFiles) {
24893
25807
  if (owned.has(command.filename)) continue;
24894
- const existing = await readFile3(path5.join(commandsDir, command.filename), "utf8").catch((error45) => {
25808
+ const existing = await readFile7(path8.join(commandsDir, command.filename), "utf8").catch((error45) => {
24895
25809
  if (error45.code === "ENOENT") return void 0;
24896
25810
  throw error45;
24897
25811
  });
@@ -24901,17 +25815,17 @@ async function assertNoForeignCommandConflicts(commandsDir, commandFiles, ownedF
24901
25815
  }
24902
25816
  }
24903
25817
  async function readAgentRecord(skillFolder) {
24904
- const raw = await readFile3(path5.join(skillFolder, ".forge-agents"), "utf8").catch(() => "");
25818
+ const raw = await readFile7(path8.join(skillFolder, ".forge-agents"), "utf8").catch(() => "");
24905
25819
  return raw.split("\n").map((line) => line.trim()).filter((line) => line.length > 0 && !line.includes("/") && !line.includes("\\") && line !== "..");
24906
25820
  }
24907
25821
  async function readCommandRecord(skillFolder) {
24908
- const raw = await readFile3(path5.join(skillFolder, ".forge-commands"), "utf8").catch(() => "");
25822
+ const raw = await readFile7(path8.join(skillFolder, ".forge-commands"), "utf8").catch(() => "");
24909
25823
  return raw.split("\n").map((line) => line.trim()).filter((line) => line.length > 0 && !line.includes("/") && !line.includes("\\") && line !== "..");
24910
25824
  }
24911
25825
  async function managedWorkPackPaths(paths, skillFolder) {
24912
25826
  const files = await listFilesRecursively(skillFolder);
24913
- const agents = (await readAgentRecord(skillFolder)).map((filename) => path5.join(paths.agentsDir, filename));
24914
- const commands = (await readCommandRecord(skillFolder)).map((filename) => path5.join(paths.commandsDir, filename));
25827
+ const agents = (await readAgentRecord(skillFolder)).map((filename) => path8.join(paths.agentsDir, filename));
25828
+ const commands = (await readCommandRecord(skillFolder)).map((filename) => path8.join(paths.commandsDir, filename));
24915
25829
  return [.../* @__PURE__ */ new Set([...files, ...agents, ...commands])];
24916
25830
  }
24917
25831
  async function managedWorkPackSlugs(skillsDir) {
@@ -24922,7 +25836,7 @@ async function managedWorkPackSlugs(skillsDir) {
24922
25836
  const slugs = [];
24923
25837
  for (const entry of entries) {
24924
25838
  if (!entry.isDirectory() || entry.name.endsWith(".previous")) continue;
24925
- if (await workPackOwnership(path5.join(skillsDir, entry.name)) === "managed") slugs.push(entry.name);
25839
+ if (await workPackOwnership(path8.join(skillsDir, entry.name)) === "managed") slugs.push(entry.name);
24926
25840
  }
24927
25841
  return slugs.sort((left, right) => left.localeCompare(right));
24928
25842
  }
@@ -24932,24 +25846,24 @@ async function removeManagedWorkPackTransaction(paths, target, options) {
24932
25846
  const agents = await readAgentRecord(target);
24933
25847
  const commands = await readCommandRecord(target);
24934
25848
  const snapshots = await Promise.all([
24935
- ...agents.map((filename) => captureExactFile(path5.join(paths.agentsDir, filename))),
24936
- ...commands.map((filename) => captureExactFile(path5.join(paths.commandsDir, filename)))
25849
+ ...agents.map((filename) => captureExactFile(path8.join(paths.agentsDir, filename))),
25850
+ ...commands.map((filename) => captureExactFile(path8.join(paths.commandsDir, filename)))
24937
25851
  ]);
24938
25852
  await assertWorkPackUnchangedAtBoundary(paths, target);
24939
25853
  const backup = `${target}.previous`;
24940
25854
  const transactionPath = `${backup}${WORK_PACK_TRANSACTION_SUFFIX}`;
24941
- const transactionRoot = await mkdtemp(path5.join(os4.tmpdir(), "forge-remove-"));
24942
- const claimedBackup = path5.join(transactionRoot, path5.basename(target));
25855
+ const transactionRoot = await mkdtemp(path8.join(os4.tmpdir(), "forge-remove-"));
25856
+ const claimedBackup = path8.join(transactionRoot, path8.basename(target));
24943
25857
  let projectionsRemoved = false;
24944
25858
  let backupClaimed = false;
24945
25859
  try {
24946
- await rm(backup, { recursive: true, force: true });
24947
- await rm(transactionPath, { force: true });
25860
+ await rm4(backup, { recursive: true, force: true });
25861
+ await rm4(transactionPath, { force: true });
24948
25862
  await writeTextAtomic(transactionPath, "remove\n");
24949
- await rename3(target, backup);
25863
+ await rename6(target, backup);
24950
25864
  } catch (error45) {
24951
- await rm(transactionPath, { force: true }).catch(() => void 0);
24952
- await rm(transactionRoot, { recursive: true, force: true }).catch(() => void 0);
25865
+ await rm4(transactionPath, { force: true }).catch(() => void 0);
25866
+ await rm4(transactionRoot, { recursive: true, force: true }).catch(() => void 0);
24953
25867
  throw error45;
24954
25868
  }
24955
25869
  try {
@@ -24957,42 +25871,42 @@ async function removeManagedWorkPackTransaction(paths, target, options) {
24957
25871
  await assertWorkPackUnchangedAtBoundary(paths, backup);
24958
25872
  projectionsRemoved = agents.length > 0;
24959
25873
  for (const filename of agents) {
24960
- const filePath = path5.join(paths.agentsDir, filename);
25874
+ const filePath = path8.join(paths.agentsDir, filename);
24961
25875
  await options.workPackProjectionBoundary?.("remove", filePath);
24962
25876
  await assertExactFileState(snapshots, filePath);
24963
25877
  await recordRemovedProjection(transactionPath, "agent", filename);
24964
- await rm(filePath, { force: true });
25878
+ await rm4(filePath, { force: true });
24965
25879
  }
24966
25880
  await options.removeWorkPackBoundary?.("after-agents");
24967
25881
  projectionsRemoved ||= commands.length > 0;
24968
25882
  for (const filename of commands) {
24969
- const filePath = path5.join(paths.commandsDir, filename);
25883
+ const filePath = path8.join(paths.commandsDir, filename);
24970
25884
  await options.workPackProjectionBoundary?.("remove", filePath);
24971
25885
  await assertExactFileState(snapshots, filePath);
24972
25886
  await recordRemovedProjection(transactionPath, "command", filename);
24973
- await rm(filePath, { force: true });
25887
+ await rm4(filePath, { force: true });
24974
25888
  }
24975
25889
  await options.removeWorkPackBoundary?.("after-commands");
24976
25890
  await assertWorkPackTreeUnchangedAtBoundary(backup);
24977
25891
  await options.removeWorkPackBoundary?.("before-commit");
24978
- await rename3(backup, claimedBackup);
25892
+ await rename6(backup, claimedBackup);
24979
25893
  backupClaimed = true;
24980
25894
  await assertWorkPackTreeUnchangedAtBoundary(claimedBackup);
24981
25895
  await writeTextAtomic(transactionPath, "committed\n");
24982
- await rm(claimedBackup, { recursive: true, force: true });
24983
- await rm(transactionPath, { force: true });
24984
- await rm(transactionRoot, { recursive: true, force: true }).catch(() => void 0);
25896
+ await rm4(claimedBackup, { recursive: true, force: true });
25897
+ await rm4(transactionPath, { force: true });
25898
+ await rm4(transactionRoot, { recursive: true, force: true }).catch(() => void 0);
24985
25899
  return pathsToRemove;
24986
25900
  } catch (error45) {
24987
25901
  try {
24988
25902
  if (projectionsRemoved) await restoreRemovedExactFiles(snapshots);
24989
- await rename3(backupClaimed ? claimedBackup : backup, target);
24990
- await rm(transactionPath, { force: true });
25903
+ await rename6(backupClaimed ? claimedBackup : backup, target);
25904
+ await rm4(transactionPath, { force: true });
24991
25905
  if (projectionsRemoved) await verifyRestoredOrLocallyChangedFiles(snapshots);
24992
25906
  if (await workPackOwnership(target) !== "managed") throw new Error("restored Work Pack marker missing");
24993
- await rm(transactionRoot, { recursive: true, force: true }).catch(() => void 0);
25907
+ await rm4(transactionRoot, { recursive: true, force: true }).catch(() => void 0);
24994
25908
  } catch (restoreError) {
24995
- throw new WorkPackRecoveryUncertainError(`Falha ao remover e restaurar o pacote de trabalho ${path5.basename(target)}`, {
25909
+ throw new WorkPackRecoveryUncertainError(`Falha ao remover e restaurar o pacote de trabalho ${path8.basename(target)}`, {
24996
25910
  cause: new AggregateError([error45, restoreError])
24997
25911
  });
24998
25912
  }
@@ -25001,9 +25915,9 @@ async function removeManagedWorkPackTransaction(paths, target, options) {
25001
25915
  }
25002
25916
  async function captureExactFile(filePath) {
25003
25917
  try {
25004
- const info = await lstat4(filePath);
25918
+ const info = await lstat5(filePath);
25005
25919
  if (!info.isFile()) throw new Error(`A proje\xE7\xE3o gerida n\xE3o \xE9 um ficheiro regular: ${filePath}`);
25006
- return { path: filePath, exists: true, bytes: await readFile3(filePath), mode: info.mode & 4095 };
25920
+ return { path: filePath, exists: true, bytes: await readFile7(filePath), mode: info.mode & 4095 };
25007
25921
  } catch (error45) {
25008
25922
  if (error45.code === "ENOENT") return { path: filePath, exists: false };
25009
25923
  throw error45;
@@ -25013,19 +25927,19 @@ async function assertExactFileState(snapshots, filePath) {
25013
25927
  const expected = snapshots.find((snapshot) => snapshot.path === filePath);
25014
25928
  const current = await captureExactFile(filePath);
25015
25929
  if (!expected || current.exists !== expected.exists) {
25016
- throw new WorkPackLocalEditsError("local-edits-preserved", `A proje\xE7\xE3o ${path5.basename(filePath)} foi alterada durante a opera\xE7\xE3o`);
25930
+ throw new WorkPackLocalEditsError("local-edits-preserved", `A proje\xE7\xE3o ${path8.basename(filePath)} foi alterada durante a opera\xE7\xE3o`);
25017
25931
  }
25018
25932
  if (current.exists && (!current.bytes?.equals(expected.bytes) || current.mode !== expected.mode)) {
25019
- throw new WorkPackLocalEditsError("local-edits-preserved", `A proje\xE7\xE3o ${path5.basename(filePath)} foi alterada durante a opera\xE7\xE3o`);
25933
+ throw new WorkPackLocalEditsError("local-edits-preserved", `A proje\xE7\xE3o ${path8.basename(filePath)} foi alterada durante a opera\xE7\xE3o`);
25020
25934
  }
25021
25935
  }
25022
25936
  async function restoreRemovedExactFiles(snapshots) {
25023
25937
  for (const snapshot of snapshots) {
25024
25938
  if ((await captureExactFile(snapshot.path)).exists) continue;
25025
25939
  if (!snapshot.exists) continue;
25026
- await mkdir2(path5.dirname(snapshot.path), { recursive: true });
25027
- await writeFile3(snapshot.path, snapshot.bytes);
25028
- await chmod(snapshot.path, snapshot.mode);
25940
+ await mkdir5(path8.dirname(snapshot.path), { recursive: true });
25941
+ await writeFile6(snapshot.path, snapshot.bytes);
25942
+ await chmod4(snapshot.path, snapshot.mode);
25029
25943
  }
25030
25944
  }
25031
25945
  async function verifyRestoredOrLocallyChangedFiles(snapshots) {
@@ -25041,14 +25955,14 @@ async function listFilesRecursively(root) {
25041
25955
  });
25042
25956
  const files = [];
25043
25957
  for (const entry of entries) {
25044
- const absolute = path5.join(root, entry.name);
25958
+ const absolute = path8.join(root, entry.name);
25045
25959
  if (entry.isDirectory()) files.push(...await listFilesRecursively(absolute));
25046
25960
  else if (entry.isFile()) files.push(absolute);
25047
25961
  }
25048
25962
  return files;
25049
25963
  }
25050
25964
  async function validateSkillFolder(folder, slug) {
25051
- const skillMd = await readFile3(path5.join(folder, "SKILL.md"), "utf8");
25965
+ const skillMd = await readFile7(path8.join(folder, "SKILL.md"), "utf8");
25052
25966
  const frontmatter = /^---\n([\s\S]+?)\n---/.exec(skillMd)?.[1] ?? "";
25053
25967
  if (!frontmatter.includes(`name: ${slug}`) && !frontmatter.includes(`name: "${slug}"`)) {
25054
25968
  throw new Error(`O campo name no frontmatter de SKILL.md tem de corresponder a ${slug}`);
@@ -25069,15 +25983,60 @@ async function writeJsonAtomic2(filePath, value) {
25069
25983
  await writeTextAtomic(filePath, content);
25070
25984
  }
25071
25985
  async function writeTextAtomic(filePath, content) {
25072
- const dir = path5.dirname(filePath);
25073
- await mkdir2(dir, { recursive: true });
25074
- const tempPath = path5.join(dir, `.${path5.basename(filePath)}.${process.pid}.tmp`);
25075
- await writeFile3(tempPath, content);
25076
- await rename3(tempPath, filePath);
25986
+ const dir = path8.dirname(filePath);
25987
+ await mkdir5(dir, { recursive: true });
25988
+ const tempPath = path8.join(dir, `.${path8.basename(filePath)}.${process.pid}.tmp`);
25989
+ await writeFile6(tempPath, content);
25990
+ await rename6(tempPath, filePath);
25991
+ }
25992
+ async function readPluginFile(pluginPath) {
25993
+ return readFile7(pluginPath, "utf8").catch((error45) => {
25994
+ if (error45.code === "ENOENT") return void 0;
25995
+ throw error45;
25996
+ });
25997
+ }
25998
+ async function isForeignPluginFile(pluginPath) {
25999
+ const current = await readPluginFile(pluginPath);
26000
+ return current !== void 0 && !current.startsWith(FORGE_PLUGIN_HEADER);
26001
+ }
26002
+ async function isManagedPluginFile(pluginPath) {
26003
+ const current = await readPluginFile(pluginPath);
26004
+ return current !== void 0 && current.startsWith(FORGE_PLUGIN_HEADER);
26005
+ }
26006
+ function hasPluginEntry(config2, pluginPath) {
26007
+ return Array.isArray(config2.plugin) && config2.plugin.some((entry) => entry === pluginPath);
26008
+ }
26009
+ function withPluginPaths(config2, pluginPaths, removePluginPaths = []) {
26010
+ const nextPluginPaths = pluginPaths.filter((entry) => typeof entry === "string" && entry.length > 0);
26011
+ if (nextPluginPaths.length === 0 && removePluginPaths.length === 0) return config2;
26012
+ const plugins = Array.isArray(config2.plugin) ? config2.plugin.filter((entry) => typeof entry === "string" || Array.isArray(entry) && typeof entry[0] === "string" && entry.length === 2) : [];
26013
+ const removed = new Set(removePluginPaths);
26014
+ const nextPlugins = [
26015
+ ...plugins.filter((entry) => typeof entry !== "string" || !removed.has(entry) && !nextPluginPaths.includes(entry)),
26016
+ ...nextPluginPaths
26017
+ ];
26018
+ const next = {
26019
+ ...config2,
26020
+ plugin: nextPlugins
26021
+ };
26022
+ if (nextPlugins.length === 0) delete next.plugin;
26023
+ return next;
26024
+ }
26025
+ async function readJsoncObject(filePath) {
26026
+ const raw = await readFile7(filePath, "utf8").catch((error45) => {
26027
+ if (error45.code === "ENOENT") return "";
26028
+ throw error45;
26029
+ });
26030
+ if (!raw.trim()) return {};
26031
+ const parsed = parseJsonc(raw);
26032
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
26033
+ throw new Error(`A configura\xE7\xE3o do OpenCode tem de ser um objeto JSON: ${filePath}`);
26034
+ }
26035
+ return parsed;
25077
26036
  }
25078
26037
 
25079
26038
  // packages/cli/src/workerPrompt.ts
25080
- import { createHash as createHash4 } from "node:crypto";
26039
+ import { createHash as createHash5 } from "node:crypto";
25081
26040
  var STOCK_OPENWORK_PROMPT_SHA256 = "b84527bf738ab37c726ccd43c3161df30fbddd5384aadbe7abf3cfeb3fced497";
25082
26041
  var FORGE_WORKER_PROMPT = `\xC9s o assistente de trabalho do Forge no OpenWork. Ajudas a pessoa a concluir
25083
26042
  tarefas com os ficheiros, fontes e ferramentas a que tem acesso. N\xE3o pressuponhas
@@ -25154,33 +26113,103 @@ limita\xE7\xF5es ou decis\xF5es pendentes.
25154
26113
  S\xF3 afirmes que o trabalho continuar\xE1 em segundo plano quando tiver sido
25155
26114
  efetivamente criada uma tarefa ou automatiza\xE7\xE3o para esse efeito.`;
25156
26115
  function applySharedWorkerPrompt(config2) {
25157
- if (config2.default_agent !== "openwork" || !isRecord(config2.agent)) return false;
26116
+ if (config2.default_agent !== "openwork" || !isRecord4(config2.agent)) return false;
25158
26117
  const agent = config2.agent.openwork;
25159
- if (!isRecord(agent) || agent.mode !== "primary" || typeof agent.prompt !== "string") return false;
26118
+ if (!isRecord4(agent) || agent.mode !== "primary" || typeof agent.prompt !== "string") return false;
25160
26119
  if (agent.prompt === FORGE_WORKER_PROMPT) return true;
25161
- const hash2 = createHash4("sha256").update(agent.prompt.replace(/\r\n/g, "\n").trim()).digest("hex");
26120
+ const hash2 = createHash5("sha256").update(agent.prompt.replace(/\r\n/g, "\n").trim()).digest("hex");
25162
26121
  if (hash2 !== STOCK_OPENWORK_PROMPT_SHA256) return false;
25163
26122
  config2.agent = { ...config2.agent, openwork: { ...agent, prompt: FORGE_WORKER_PROMPT } };
25164
26123
  return true;
25165
26124
  }
25166
- function isRecord(value) {
26125
+ function isRecord4(value) {
25167
26126
  return value !== null && typeof value === "object" && !Array.isArray(value);
25168
26127
  }
25169
26128
 
26129
+ // packages/cli/src/localWorkerSync.ts
26130
+ import { readFile as readFile9 } from "node:fs/promises";
26131
+ import path10 from "node:path";
26132
+
26133
+ // packages/cli/src/recoveryLauncher.ts
26134
+ import { chmod as chmod5, readFile as readFile8 } from "node:fs/promises";
26135
+ import { execFileSync } from "node:child_process";
26136
+ import path9 from "node:path";
26137
+ async function installRecoveryLauncher(paths, forgeBaseUrl, source = new URL("./repair.js", import.meta.url)) {
26138
+ const program = await readFile8(source, "utf8");
26139
+ let nodePath;
26140
+ try {
26141
+ const runtime = JSON.parse(execFileSync(
26142
+ "node",
26143
+ ["-p", 'JSON.stringify({ path: process.execPath, major: Number(process.versions.node.split(".")[0]) })'],
26144
+ { encoding: "utf8", timeout: 5e3, windowsHide: true }
26145
+ ));
26146
+ if (runtime.major < 22 || typeof runtime.major !== "number" || typeof runtime.path !== "string" || !path9.isAbsolute(runtime.path)) throw new Error();
26147
+ nodePath = runtime.path;
26148
+ } catch {
26149
+ 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.");
26150
+ }
26151
+ const launcherContent = renderRecoveryLauncher(nodePath, process.platform);
26152
+ await writeOwnerOnlyTextAtomic(path9.join(paths.forgeDir, "forge-repair.mjs"), program);
26153
+ await writeOwnerOnlyTextAtomic(path9.join(paths.forgeDir, "recovery-origin.json"), JSON.stringify({ forgeBaseUrl }) + "\n");
26154
+ const windows = process.platform === "win32";
26155
+ const launcher = path9.join(paths.forgeDir, windows ? "Reparar Forge.cmd" : "Reparar Forge.command");
26156
+ await writeOwnerOnlyTextAtomic(launcher, launcherContent);
26157
+ if (!windows) await chmod5(launcher, 448);
26158
+ return launcher;
26159
+ }
26160
+ function renderRecoveryLauncher(nodePath, platform) {
26161
+ if (/[\r\n"\0]/.test(nodePath)) throw new Error("O caminho do Node n\xE3o \xE9 suportado pela recupera\xE7\xE3o.");
26162
+ return platform === "win32" ? `@echo off\r
26163
+ setlocal DisableDelayedExpansion\r
26164
+ "${nodePath.replace(/%/g, "%%")}" "%~dp0forge-repair.mjs" %*\r
26165
+ set "repairExit=%errorlevel%"\r
26166
+ pause\r
26167
+ exit /b %repairExit%\r
26168
+ ` : `#!/bin/sh
26169
+ cd -- "\${0%/*}" || exit 1
26170
+ exec '${nodePath.replace(/'/g, "'\\''")}' ./forge-repair.mjs "$@"
26171
+ `;
26172
+ }
26173
+
26174
+ // packages/cli/src/localWorkerSync.ts
26175
+ async function syncLocalWorker(paths, credentials, manifest) {
26176
+ const recovery = await recoverCoreSyncTransaction({ journalPath: path10.join(paths.forgeDir, "core-sync-journal.json") });
26177
+ if (recovery.status === "uncertain") throw new CoreSyncUncertainError(recovery.message, recovery.uncertainPaths);
26178
+ let current;
26179
+ try {
26180
+ current = JSON.parse(await readFile9(paths.opencodeConfigPath, "utf8"));
26181
+ } catch {
26182
+ throw new Error("A configura\xE7\xE3o local n\xE3o \xE9 JSON simples v\xE1lido; preserve os ficheiros e pe\xE7a apoio.");
26183
+ }
26184
+ if (current?.provider?.forge?.options?.apiKey !== credentials.forgeApiKey || typeof current.model !== "string" || !current.model.startsWith("forge/")) {
26185
+ throw new Error("A configura\xE7\xE3o local Forge tem um conflito; pe\xE7a uma repara\xE7\xE3o acompanhada.");
26186
+ }
26187
+ const state = await inspectLocalConfigRecovery(paths, credentials);
26188
+ if (state.current !== "valid" || state.snapshot !== "missing" && state.snapshot !== "available") {
26189
+ 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.");
26190
+ }
26191
+ await installRecoveryLauncher(paths, credentials.forgeBaseUrl);
26192
+ const result = await applyManifest(paths, credentials, manifest);
26193
+ await removeWellKnownAuth(paths, credentials);
26194
+ return result;
26195
+ }
26196
+
25170
26197
  // packages/cli/src/workPackSyncPlugin.ts
25171
- var PLUGIN_VERSION = "0.1.34";
26198
+ var PLUGIN_VERSION = "0.1.35";
25172
26199
  var FORGE_DECISION_TIMEOUT_MS = 11e4;
25173
26200
  var STATUS_FILENAME = "work-pack-startup-status.json";
25174
26201
  var activeSync = /* @__PURE__ */ new Map();
25175
26202
  var ForgeWorkPackSyncServer = async (_input, options) => {
25176
26203
  const forgeBaseUrl = parseForgeBaseUrl(options);
25177
- let sync = activeSync.get(forgeBaseUrl);
26204
+ const localConfig = Boolean(options && typeof options === "object" && "localConfig" in options && options.localConfig === true);
26205
+ const syncKey = `${forgeBaseUrl}:${localConfig ? "local" : "remote"}`;
26206
+ let sync = activeSync.get(syncKey);
25178
26207
  if (!sync) {
25179
- sync = synchronizeAtStartup(forgeBaseUrl, _input);
25180
- activeSync.set(forgeBaseUrl, sync);
26208
+ sync = synchronizeAtStartup(forgeBaseUrl, _input, localConfig);
26209
+ activeSync.set(syncKey, sync);
25181
26210
  }
25182
26211
  const state = await sync;
25183
- const legacyPath = path6.join(state.paths.pluginDir, FORGE_EVIDENCE_PLUGIN_FILENAME);
26212
+ const legacyPath = path11.join(state.paths.pluginDir, FORGE_EVIDENCE_PLUGIN_FILENAME);
25184
26213
  const ownershipSymbol = /* @__PURE__ */ Symbol.for("minimal-forge.legacy-evidence-owners.v1");
25185
26214
  const shared = globalThis;
25186
26215
  const legacyOwners = shared[ownershipSymbol] ??= /* @__PURE__ */ new Set();
@@ -25191,13 +26220,13 @@ var ForgeWorkPackSyncServer = async (_input, options) => {
25191
26220
  const slug = typeof input.args?.name === "string" ? input.args.name.trim().toLowerCase() : "";
25192
26221
  if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug)) return;
25193
26222
  try {
25194
- await readFile4(path6.join(state.paths.skillsDir, slug, ".forge-version"), "utf8");
26223
+ await readFile10(path11.join(state.paths.skillsDir, slug, ".forge-version"), "utf8");
25195
26224
  } catch {
25196
26225
  return;
25197
26226
  }
25198
26227
  try {
25199
- const { forgeApiKey } = await readWellKnownForgeCredentials(state.paths.opencodeAuthPath, forgeBaseUrl);
25200
- const credentialId = createHash5("sha256").update(forgeApiKey).digest("hex");
26228
+ const { forgeApiKey } = await readForgeCredentials(state.paths, forgeBaseUrl);
26229
+ const credentialId = createHash6("sha256").update(forgeApiKey).digest("hex");
25201
26230
  const reportUsage = skillUsageReporter(forgeBaseUrl, credentialId, (events) => fetch(`${forgeBaseUrl}/sync/evidence`, {
25202
26231
  method: "POST",
25203
26232
  redirect: "error",
@@ -25216,10 +26245,10 @@ var ForgeWorkPackSyncServer = async (_input, options) => {
25216
26245
  const name = Array.isArray(entry) ? entry[0] : entry;
25217
26246
  return name === legacyPath || name === pathToFileURL(legacyPath).href;
25218
26247
  });
25219
- const legacy = registered ? await readFile4(legacyPath, "utf8").catch(() => "") : "";
26248
+ const legacy = registered ? await readFile10(legacyPath, "utf8").catch(() => "") : "";
25220
26249
  const oldLegacyRegistered = registered && legacy.startsWith(FORGE_PLUGIN_HEADER) && legacy.includes("work_pack_invocation") && !legacy.includes("minimal-forge.skill-usage.v1");
25221
26250
  if (oldLegacyRegistered) legacyOwners.add(legacyOwnerKey);
25222
- if (oldLegacyRegistered) await writeFile4(legacyPath, renderEvidencePlugin()).catch(() => {
26251
+ if (oldLegacyRegistered) await writeFile7(legacyPath, renderEvidencePlugin()).catch(() => {
25223
26252
  console.error("[Forge evidence] Legacy hook upgrade failed; existing hook retained");
25224
26253
  });
25225
26254
  await projectCurrentExtensions(config2, state);
@@ -25244,16 +26273,16 @@ function createForgeImageTool(forgeBaseUrl, gatewayBaseUrl, paths) {
25244
26273
  referencePath: tool.schema.string().optional().describe("Caminho expl\xEDcito de uma imagem PNG, JPEG ou WebP a editar")
25245
26274
  },
25246
26275
  async execute(args, context) {
25247
- const requestId = randomUUID2();
26276
+ const requestId = randomUUID4();
25248
26277
  let referenceDataUrl;
25249
26278
  if (args.referencePath) {
25250
- const bytes = await readFile4(args.referencePath);
26279
+ const bytes = await readFile10(args.referencePath);
25251
26280
  if (bytes.byteLength > 25e5) throw new Error("A imagem de refer\xEAncia \xE9 demasiado grande. Reduza-a antes de tentar novamente.");
25252
26281
  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;
25253
26282
  if (!mime) throw new Error("A refer\xEAncia tem de ser PNG, JPEG ou WebP.");
25254
26283
  referenceDataUrl = `data:${mime};base64,${bytes.toString("base64")}`;
25255
26284
  }
25256
- const credentials = await readWellKnownForgeCredentials(paths.opencodeAuthPath, forgeBaseUrl);
26285
+ const credentials = await readForgeCredentials(paths, forgeBaseUrl);
25257
26286
  let response;
25258
26287
  try {
25259
26288
  response = await fetch(`${gatewayBaseUrl}/v1/images`, {
@@ -25273,8 +26302,8 @@ function createForgeImageTool(forgeBaseUrl, gatewayBaseUrl, paths) {
25273
26302
  if (image.byteLength > 8 * 1024 * 1024 || !image.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) {
25274
26303
  throw new Error(`O PNG recebido \xE9 inv\xE1lido. Refer\xEAncia: ${requestId}`);
25275
26304
  }
25276
- const destination = path6.join(context.directory, `forge-image-${requestId}.png`);
25277
- await writeFile4(destination, image, { flag: "wx" });
26305
+ const destination = path11.join(context.directory, `forge-image-${requestId}.png`);
26306
+ await writeFile7(destination, image, { flag: "wx" });
25278
26307
  const reset = body.quota && new Intl.DateTimeFormat("pt-PT", { dateStyle: "long", timeZone: "Europe/Lisbon" }).format(new Date(body.quota.resetsAt));
25279
26308
  const remaining = body.quota ? ` Restam ${body.quota.remaining} imagens at\xE9 ${reset}.` : "";
25280
26309
  return `Imagem guardada em ${destination}.${remaining}
@@ -25320,7 +26349,7 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseD
25320
26349
  let requestBody;
25321
26350
  if (fromFile) {
25322
26351
  const file2 = await fileInsideWorkspace(context.directory, args.request_file);
25323
- const raw = await readFile4(file2, "utf8");
26352
+ const raw = await readFile10(file2, "utf8");
25324
26353
  if (Buffer.byteLength(raw) > 512 * 1024) throw new Error("O ficheiro de pedido excede 512 KiB.");
25325
26354
  let parsed;
25326
26355
  try {
@@ -25339,10 +26368,10 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseD
25339
26368
  if (args.state === void 0 || !args.questions || Object.keys(args.questions).length === 0) throw new Error("Indica state e questions.");
25340
26369
  requestBody = { state: args.state, questions: args.questions };
25341
26370
  }
25342
- const responseDir = await mkdtemp2(path6.join(responseDirectory ?? context.directory, ".forge-decision-"));
25343
- const responseFile = path6.join(responseDir, "response.json");
26371
+ const responseDir = await mkdtemp2(path11.join(responseDirectory ?? context.directory, ".forge-decision-"));
26372
+ const responseFile = path11.join(responseDir, "response.json");
25344
26373
  try {
25345
- const credentials = await readWellKnownForgeCredentials(paths.opencodeAuthPath, forgeBaseUrl);
26374
+ const credentials = await readForgeCredentials(paths, forgeBaseUrl);
25346
26375
  const response = await fetch(`${decisionBaseUrl}/v1/decisions`, {
25347
26376
  method: "POST",
25348
26377
  redirect: "error",
@@ -25361,7 +26390,7 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseD
25361
26390
  }
25362
26391
  if (response.ok && body && typeof body === "object" && body.answers && typeof body.answers === "object") {
25363
26392
  try {
25364
- await writeFile4(responseFile, raw, { flag: "wx", mode: 384 });
26393
+ await writeFile7(responseFile, raw, { flag: "wx", mode: 384 });
25365
26394
  return JSON.stringify({ ...body, response_file: responseFile }, null, 2);
25366
26395
  } catch {
25367
26396
  return JSON.stringify({
@@ -25386,14 +26415,14 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseD
25386
26415
  }
25387
26416
  async function fileInsideWorkspace(directory, candidate) {
25388
26417
  const workspace = await realpath(directory);
25389
- const file2 = await realpath(path6.resolve(workspace, candidate));
25390
- const relative = path6.relative(workspace, file2);
25391
- if (!relative || (relative === ".." || relative.startsWith(`..${path6.sep}`)) || path6.isAbsolute(relative)) throw new Error("O ficheiro tem de estar dentro do workspace.");
26418
+ const file2 = await realpath(path11.resolve(workspace, candidate));
26419
+ const relative = path11.relative(workspace, file2);
26420
+ if (!relative || (relative === ".." || relative.startsWith(`..${path11.sep}`)) || path11.isAbsolute(relative)) throw new Error("O ficheiro tem de estar dentro do workspace.");
25392
26421
  return file2;
25393
26422
  }
25394
26423
  async function fileExists(candidate) {
25395
26424
  try {
25396
- await stat(candidate);
26425
+ await stat2(candidate);
25397
26426
  return true;
25398
26427
  } catch (error45) {
25399
26428
  if (error45.code === "ENOENT") return false;
@@ -25414,19 +26443,19 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
25414
26443
  args: { plan_file: tool.schema.string().describe("Caminho de jev/plan.json dentro do workspace") },
25415
26444
  async execute(args, context) {
25416
26445
  const planFile = await fileInsideWorkspace(context.directory, args.plan_file);
25417
- if (path6.basename(planFile) !== "plan.json" || path6.basename(path6.dirname(planFile)) !== "jev") throw new Error("Indica o ficheiro jev/plan.json.");
25418
- const runDir = path6.dirname(path6.dirname(planFile));
25419
- const plan = JSON.parse(await readFile4(planFile, "utf8"));
26446
+ if (path11.basename(planFile) !== "plan.json" || path11.basename(path11.dirname(planFile)) !== "jev") throw new Error("Indica o ficheiro jev/plan.json.");
26447
+ const runDir = path11.dirname(path11.dirname(planFile));
26448
+ const plan = JSON.parse(await readFile10(planFile, "utf8"));
25420
26449
  if (plan.engine !== "jev-batch" || plan.model !== "typesafe/jev-1.13" || !Array.isArray(plan.batches)) throw new Error("O plano Jev \xE9 inv\xE1lido.");
25421
26450
  const batches = plan.batches;
25422
- const responsePath = path6.join(runDir, "jev", "responses");
25423
- await mkdir3(responsePath, { recursive: true });
26451
+ const responsePath = path11.join(runDir, "jev", "responses");
26452
+ await mkdir6(responsePath, { recursive: true });
25424
26453
  const responseDir = await fileInsideWorkspace(context.directory, responsePath);
25425
- if (path6.dirname(responseDir) !== path6.join(runDir, "jev")) throw new Error("A pasta de respostas tem de pertencer ao run Jev.");
26454
+ if (path11.dirname(responseDir) !== path11.join(runDir, "jev")) throw new Error("A pasta de respostas tem de pertencer ao run Jev.");
25426
26455
  const decide = createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseDir);
25427
- const lockDir = path6.join(runDir, "jev", ".decide-run.lock");
26456
+ const lockDir = path11.join(runDir, "jev", ".decide-run.lock");
25428
26457
  try {
25429
- await mkdir3(lockDir);
26458
+ await mkdir6(lockDir);
25430
26459
  } catch (error45) {
25431
26460
  if (error45.code !== "EEXIST") throw error45;
25432
26461
  throw new Error("Este plano j\xE1 est\xE1 em execu\xE7\xE3o ou tem uma chamada interrompida. Verificar as respostas e recuperar o lote antes de remover jev/.decide-run.lock; n\xE3o repetir chamadas incertas.");
@@ -25435,26 +26464,26 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
25435
26464
  let saved = 0;
25436
26465
  let skipped = 0;
25437
26466
  try {
25438
- await writeFile4(path6.join(lockDir, "owner.json"), JSON.stringify({ pid: process.pid, started_at: (/* @__PURE__ */ new Date()).toISOString() }), { mode: 384 });
26467
+ await writeFile7(path11.join(lockDir, "owner.json"), JSON.stringify({ pid: process.pid, started_at: (/* @__PURE__ */ new Date()).toISOString() }), { mode: 384 });
25439
26468
  for (const batch of batches) {
25440
26469
  context.abort.throwIfAborted();
25441
26470
  const batchId = batch.batch_id;
25442
26471
  if (typeof batchId !== "string" || !/^batch-[0-9]{4}-[A-Za-z0-9._-]+$/.test(batchId) || typeof batch.request_file !== "string" || typeof batch.request_fingerprint !== "string") {
25443
26472
  throw new Error("O plano Jev cont\xE9m um lote inv\xE1lido.");
25444
26473
  }
25445
- const acceptedFile = path6.join(runDir, "jev", "accepted", `${batchId}.json`);
25446
- const responseFile = path6.join(responseDir, `${batchId}.response.json`);
26474
+ const acceptedFile = path11.join(runDir, "jev", "accepted", `${batchId}.json`);
26475
+ const responseFile = path11.join(responseDir, `${batchId}.response.json`);
25447
26476
  const requestFile = await fileInsideWorkspace(context.directory, batch.request_file);
25448
- if (path6.dirname(requestFile) !== path6.join(runDir, "jev", "requests")) throw new Error(`${batchId}: pedido fora do run.`);
25449
- const request = JSON.parse(await readFile4(requestFile, "utf8"));
25450
- const fingerprint = createHash5("sha256").update(canonicalJson(request)).digest("hex");
26477
+ if (path11.dirname(requestFile) !== path11.join(runDir, "jev", "requests")) throw new Error(`${batchId}: pedido fora do run.`);
26478
+ const request = JSON.parse(await readFile10(requestFile, "utf8"));
26479
+ const fingerprint = createHash6("sha256").update(canonicalJson(request)).digest("hex");
25451
26480
  if (fingerprint !== batch.request_fingerprint) throw new Error(`${batchId}: fingerprint do pedido n\xE3o corresponde ao plano.`);
25452
26481
  if (await fileExists(acceptedFile) || await fileExists(responseFile)) {
25453
26482
  skipped++;
25454
26483
  continue;
25455
26484
  }
25456
26485
  let result;
25457
- await writeFile4(path6.join(lockDir, "owner.json"), JSON.stringify({ pid: process.pid, batch_id: batchId, request_fingerprint: fingerprint, started_at: (/* @__PURE__ */ new Date()).toISOString() }), { mode: 384 });
26486
+ await writeFile7(path11.join(lockDir, "owner.json"), JSON.stringify({ pid: process.pid, batch_id: batchId, request_fingerprint: fingerprint, started_at: (/* @__PURE__ */ new Date()).toISOString() }), { mode: 384 });
25458
26487
  try {
25459
26488
  const output = await decide.execute({ request_file: requestFile }, context);
25460
26489
  result = JSON.parse(typeof output === "string" ? output : output.output);
@@ -25479,7 +26508,7 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
25479
26508
  error: "Resposta conclu\xEDda mas n\xE3o copiada para o run; recuperar o ficheiro indicado, sem repetir a chamada."
25480
26509
  });
25481
26510
  }
25482
- await unlink(result.response_file).then(() => rmdir(path6.dirname(result.response_file))).catch(() => void 0);
26511
+ await unlink(result.response_file).then(() => rmdir(path11.dirname(result.response_file))).catch(() => void 0);
25483
26512
  saved++;
25484
26513
  }
25485
26514
  return JSON.stringify({
@@ -25491,7 +26520,7 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
25491
26520
  next_step: "Executar jev-accept sobre as respostas guardadas ainda n\xE3o aceites; depois jev-validate e jev-merge."
25492
26521
  });
25493
26522
  } finally {
25494
- if (releaseLock) await rm2(lockDir, { recursive: true });
26523
+ if (releaseLock) await rm5(lockDir, { recursive: true });
25495
26524
  }
25496
26525
  }
25497
26526
  });
@@ -25504,7 +26533,7 @@ function createForgeCodebookTool(forgeBaseUrl, gatewayBaseUrl, paths) {
25504
26533
  responses: tool.schema.array(tool.schema.string().trim().min(1).max(2e4)).min(1).max(2e3).describe("Respostas da mesma pergunta, sem identificadores pessoais desnecess\xE1rios")
25505
26534
  },
25506
26535
  async execute(args, context) {
25507
- const credentials = await readWellKnownForgeCredentials(paths.opencodeAuthPath, forgeBaseUrl);
26536
+ const credentials = await readForgeCredentials(paths, forgeBaseUrl);
25508
26537
  const response = await fetch(`${gatewayBaseUrl}/v1/codebooks`, {
25509
26538
  method: "POST",
25510
26539
  redirect: "error",
@@ -25528,7 +26557,7 @@ function createForgeFeedbackTool(forgeBaseUrl, paths) {
25528
26557
  message: tool.schema.string().trim().min(1).max(1e3).describe("Texto exato que a pessoa aprovou enviar")
25529
26558
  },
25530
26559
  async execute(args, context) {
25531
- const credentials = await readWellKnownForgeCredentials(paths.opencodeAuthPath, forgeBaseUrl);
26560
+ const credentials = await readForgeCredentials(paths, forgeBaseUrl);
25532
26561
  const response = await fetch(`${forgeBaseUrl}/sync/feedback`, {
25533
26562
  method: "POST",
25534
26563
  redirect: "error",
@@ -25548,7 +26577,7 @@ function createForgeFeedbackTool(forgeBaseUrl, paths) {
25548
26577
  }
25549
26578
  });
25550
26579
  }
25551
- async function synchronizeAtStartup(forgeBaseUrl, input) {
26580
+ async function synchronizeAtStartup(forgeBaseUrl, input, localConfig) {
25552
26581
  const paths = resolveStartupPaths();
25553
26582
  const before = await managedProjectionNames(paths);
25554
26583
  let credentials;
@@ -25557,11 +26586,11 @@ async function synchronizeAtStartup(forgeBaseUrl, input) {
25557
26586
  const runtime = await observeRuntime(input);
25558
26587
  try {
25559
26588
  await retireDebugCapture(paths);
25560
- credentials = await readWellKnownForgeCredentials(paths.opencodeAuthPath, forgeBaseUrl);
26589
+ credentials = await readForgeCredentials(paths, forgeBaseUrl);
25561
26590
  const manifest = await fetchManifest(credentials);
25562
26591
  decisionBaseUrl = resolveDecisionBaseUrl(manifest.gatewayBaseUrl, forgeBaseUrl);
25563
26592
  forgeConfigVerified = true;
25564
- const result = await applyWorkPackManifest(paths, credentials, manifest, {});
26593
+ const result = localConfig ? await syncLocalWorker(paths, credentials, manifest) : await applyWorkPackManifest(paths, credentials, manifest, {});
25565
26594
  await reportWorkPackObservations(credentials, "sync", result.workPackObservations, runtime);
25566
26595
  const failures = result.workPacks.outcomes.filter(
25567
26596
  (outcome) => outcome.status === "failed" || outcome.status === "recovery-uncertain"
@@ -25591,10 +26620,24 @@ async function synchronizeAtStartup(forgeBaseUrl, input) {
25591
26620
  message
25592
26621
  }).catch(() => void 0);
25593
26622
  if (credentials) await reportFailure(credentials, "sync", new Error(message), runtime);
26623
+ if (localConfig && !forgeConfigVerified && credentials) {
26624
+ decisionBaseUrl = await savedGatewayBaseUrl(paths, credentials, forgeBaseUrl) ?? decisionBaseUrl;
26625
+ }
25594
26626
  const after = await managedProjectionNames(paths).catch(() => before);
25595
26627
  return { paths, before, after, forgeConfigVerified, decisionBaseUrl };
25596
26628
  }
25597
26629
  }
26630
+ async function savedGatewayBaseUrl(paths, credentials, forgeBaseUrl) {
26631
+ try {
26632
+ const config2 = objectRecord(parseJsonc(await readFile10(paths.opencodeConfigPath, "utf8")));
26633
+ const options = objectRecord(objectRecord(objectRecord(config2.provider).forge).options);
26634
+ if (options.apiKey !== credentials.forgeApiKey || typeof options.baseURL !== "string" || !options.baseURL.endsWith("/v1")) return void 0;
26635
+ const origin = options.baseURL.slice(0, -"/v1".length);
26636
+ return origin === forgeBaseUrl ? origin : resolveDecisionBaseUrl(origin, forgeBaseUrl);
26637
+ } catch {
26638
+ return void 0;
26639
+ }
26640
+ }
25598
26641
  function resolveDecisionBaseUrl(gatewayBaseUrl, forgeBaseUrl) {
25599
26642
  if (!gatewayBaseUrl) return forgeBaseUrl;
25600
26643
  try {
@@ -25610,21 +26653,33 @@ function resolveStartupPaths() {
25610
26653
  delete env.OPENCODE_CONFIG_DIR;
25611
26654
  return resolvePaths(void 0, void 0, env);
25612
26655
  }
25613
- async function readWellKnownForgeCredentials(authPath, forgeBaseUrl) {
25614
- const raw = await readFile4(authPath, "utf8");
25615
- const parsed = JSON.parse(raw.startsWith("\uFEFF") ? raw.slice(1) : raw);
25616
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
25617
- throw new Error("A autentica\xE7\xE3o do OpenCode n\xE3o \xE9 um objeto JSON v\xE1lido");
25618
- }
25619
- const value = parsed[forgeBaseUrl];
25620
- if (!value || typeof value !== "object" || Array.isArray(value)) {
25621
- throw new Error("A autoriza\xE7\xE3o Forge desta organiza\xE7\xE3o n\xE3o existe no OpenCode");
26656
+ async function readForgeCredentials(paths, forgeBaseUrl) {
26657
+ const raw = await readFile10(paths.opencodeAuthPath, "utf8").catch((error45) => {
26658
+ if (error45.code === "ENOENT") return void 0;
26659
+ throw error45;
26660
+ });
26661
+ if (raw !== void 0) {
26662
+ const parsed = JSON.parse(raw.startsWith("\uFEFF") ? raw.slice(1) : raw);
26663
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
26664
+ throw new Error("A autentica\xE7\xE3o do OpenCode n\xE3o \xE9 um objeto JSON v\xE1lido");
26665
+ }
26666
+ const value = parsed[forgeBaseUrl];
26667
+ if (value !== void 0) {
26668
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
26669
+ throw new Error("A autoriza\xE7\xE3o Forge desta organiza\xE7\xE3o n\xE3o \xE9 v\xE1lida");
26670
+ }
26671
+ const record2 = value;
26672
+ if (record2.type !== "wellknown" || record2.key !== "FORGE_API_KEY" || typeof record2.token !== "string" || !record2.token.startsWith("forge_")) {
26673
+ throw new Error("A autoriza\xE7\xE3o Forge desta organiza\xE7\xE3o n\xE3o \xE9 v\xE1lida");
26674
+ }
26675
+ return { forgeBaseUrl, forgeApiKey: record2.token, installedAt: (/* @__PURE__ */ new Date()).toISOString() };
26676
+ }
25622
26677
  }
25623
- const record2 = value;
25624
- if (record2.type !== "wellknown" || record2.key !== "FORGE_API_KEY" || typeof record2.token !== "string" || !record2.token.startsWith("forge_")) {
25625
- throw new Error("A autoriza\xE7\xE3o Forge desta organiza\xE7\xE3o n\xE3o \xE9 v\xE1lida");
26678
+ const local = await readCredentials(paths);
26679
+ if (local.forgeBaseUrl.replace(/\/+$/, "") !== forgeBaseUrl || !local.forgeApiKey.startsWith("forge_")) {
26680
+ throw new Error("A credencial local do Forge n\xE3o corresponde a esta organiza\xE7\xE3o");
25626
26681
  }
25627
- return { forgeBaseUrl, forgeApiKey: record2.token, installedAt: (/* @__PURE__ */ new Date()).toISOString() };
26682
+ return local;
25628
26683
  }
25629
26684
  function parseForgeBaseUrl(options) {
25630
26685
  if (!options || typeof options !== "object" || Array.isArray(options)) {
@@ -25648,16 +26703,16 @@ async function managedProjectionNames(paths) {
25648
26703
  });
25649
26704
  for (const entry of entries) {
25650
26705
  if (!entry.isDirectory()) continue;
25651
- const folder = path6.join(paths.skillsDir, entry.name);
25652
- const marker = await readFile4(path6.join(folder, ".forge-version"), "utf8").catch(() => "");
26706
+ const folder = path11.join(paths.skillsDir, entry.name);
26707
+ const marker = await readFile10(path11.join(folder, ".forge-version"), "utf8").catch(() => "");
25653
26708
  if (!marker.trim()) continue;
25654
- for (const name of await readProjectionRecord(path6.join(folder, ".forge-agents"))) agents.add(stripMarkdownExtension(name));
25655
- for (const name of await readProjectionRecord(path6.join(folder, ".forge-commands"))) commands.add(stripMarkdownExtension(name));
26709
+ for (const name of await readProjectionRecord(path11.join(folder, ".forge-agents"))) agents.add(stripMarkdownExtension(name));
26710
+ for (const name of await readProjectionRecord(path11.join(folder, ".forge-commands"))) commands.add(stripMarkdownExtension(name));
25656
26711
  }
25657
26712
  return { agents, commands };
25658
26713
  }
25659
26714
  async function readProjectionRecord(filePath) {
25660
- const raw = await readFile4(filePath, "utf8").catch(() => "");
26715
+ const raw = await readFile10(filePath, "utf8").catch(() => "");
25661
26716
  return raw.split("\n").map((line) => line.trim()).filter(
25662
26717
  (line) => line.endsWith(".md") && !line.includes("/") && !line.includes("\\") && line !== ".."
25663
26718
  );
@@ -25668,21 +26723,21 @@ async function projectCurrentExtensions(config2, state) {
25668
26723
  for (const name of state.before.agents) if (!state.after.agents.has(name)) delete agents[name];
25669
26724
  for (const name of state.before.commands) if (!state.after.commands.has(name)) delete commands[name];
25670
26725
  for (const name of state.after.agents) {
25671
- agents[name] = await parseMarkdownConfig(path6.join(state.paths.agentsDir, `${name}.md`), "prompt");
26726
+ agents[name] = await parseMarkdownConfig(path11.join(state.paths.agentsDir, `${name}.md`), "prompt");
25672
26727
  }
25673
26728
  for (const name of state.after.commands) {
25674
- commands[name] = await parseMarkdownConfig(path6.join(state.paths.commandsDir, `${name}.md`), "template");
26729
+ commands[name] = await parseMarkdownConfig(path11.join(state.paths.commandsDir, `${name}.md`), "template");
25675
26730
  }
25676
26731
  config2.agent = agents;
25677
26732
  config2.command = commands;
25678
26733
  }
25679
26734
  async function parseMarkdownConfig(filePath, bodyField) {
25680
- const raw = await readFile4(filePath, "utf8");
26735
+ const raw = await readFile10(filePath, "utf8");
25681
26736
  const match = /^---\r?\n([\s\S]+?)\r?\n---\r?\n?([\s\S]*)$/.exec(raw);
25682
- if (!match) throw new Error(`A extens\xE3o Forge ${path6.basename(filePath)} n\xE3o tem frontmatter v\xE1lido`);
26737
+ if (!match) throw new Error(`A extens\xE3o Forge ${path11.basename(filePath)} n\xE3o tem frontmatter v\xE1lido`);
25683
26738
  const data = (0, import_yaml.parse)(match[1]);
25684
26739
  if (!data || typeof data !== "object" || Array.isArray(data)) {
25685
- throw new Error(`A extens\xE3o Forge ${path6.basename(filePath)} n\xE3o tem frontmatter v\xE1lido`);
26740
+ throw new Error(`A extens\xE3o Forge ${path11.basename(filePath)} n\xE3o tem frontmatter v\xE1lido`);
25686
26741
  }
25687
26742
  const config2 = { ...data, [bodyField]: match[2].trim() };
25688
26743
  if (bodyField === "prompt" && typeof config2.permission === "string" && ["allow", "ask", "deny"].includes(config2.permission)) {
@@ -25697,12 +26752,12 @@ function stripMarkdownExtension(filename) {
25697
26752
  return filename.slice(0, -3);
25698
26753
  }
25699
26754
  async function writeStatus(paths, value) {
25700
- await mkdir3(paths.forgeDir, { recursive: true });
25701
- const target = path6.join(paths.forgeDir, STATUS_FILENAME);
25702
- const temporary = path6.join(paths.forgeDir, `.${STATUS_FILENAME}.${process.pid}.tmp`);
25703
- await writeFile4(temporary, `${JSON.stringify(value, null, 2)}
26755
+ await mkdir6(paths.forgeDir, { recursive: true });
26756
+ const target = path11.join(paths.forgeDir, STATUS_FILENAME);
26757
+ const temporary = path11.join(paths.forgeDir, `.${STATUS_FILENAME}.${process.pid}.tmp`);
26758
+ await writeFile7(temporary, `${JSON.stringify(value, null, 2)}
25704
26759
  `, { mode: 384 });
25705
- await rename4(temporary, target);
26760
+ await rename7(temporary, target);
25706
26761
  }
25707
26762
  function safeErrorMessage(error45) {
25708
26763
  const message = error45 instanceof Error ? error45.message : "erro desconhecido";