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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/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, path12) {
121
- const ctrl = callVisitor(key, node, visitor, path12);
120
+ function visit_(key, node, visitor, path13) {
121
+ const ctrl = callVisitor(key, node, visitor, path13);
122
122
  if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
123
- replaceNode(key, path12, ctrl);
124
- return visit_(key, ctrl, visitor, path12);
123
+ replaceNode(key, path13, ctrl);
124
+ return visit_(key, ctrl, visitor, path13);
125
125
  }
126
126
  if (typeof ctrl !== "symbol") {
127
127
  if (identity.isCollection(node)) {
128
- path12 = Object.freeze(path12.concat(node));
128
+ path13 = Object.freeze(path13.concat(node));
129
129
  for (let i = 0; i < node.items.length; ++i) {
130
- const ci2 = visit_(i, node.items[i], visitor, path12);
130
+ const ci2 = visit_(i, node.items[i], visitor, path13);
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
- path12 = Object.freeze(path12.concat(node));
142
- const ck = visit_("key", node.key, visitor, path12);
141
+ path13 = Object.freeze(path13.concat(node));
142
+ const ck = visit_("key", node.key, visitor, path13);
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, path12);
147
+ const cv = visit_("value", node.value, visitor, path13);
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, path12) {
169
- const ctrl = await callVisitor(key, node, visitor, path12);
168
+ async function visitAsync_(key, node, visitor, path13) {
169
+ const ctrl = await callVisitor(key, node, visitor, path13);
170
170
  if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
171
- replaceNode(key, path12, ctrl);
172
- return visitAsync_(key, ctrl, visitor, path12);
171
+ replaceNode(key, path13, ctrl);
172
+ return visitAsync_(key, ctrl, visitor, path13);
173
173
  }
174
174
  if (typeof ctrl !== "symbol") {
175
175
  if (identity.isCollection(node)) {
176
- path12 = Object.freeze(path12.concat(node));
176
+ path13 = Object.freeze(path13.concat(node));
177
177
  for (let i = 0; i < node.items.length; ++i) {
178
- const ci2 = await visitAsync_(i, node.items[i], visitor, path12);
178
+ const ci2 = await visitAsync_(i, node.items[i], visitor, path13);
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
- path12 = Object.freeze(path12.concat(node));
190
- const ck = await visitAsync_("key", node.key, visitor, path12);
189
+ path13 = Object.freeze(path13.concat(node));
190
+ const ck = await visitAsync_("key", node.key, visitor, path13);
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, path12);
195
+ const cv = await visitAsync_("value", node.value, visitor, path13);
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, path12) {
222
+ function callVisitor(key, node, visitor, path13) {
223
223
  if (typeof visitor === "function")
224
- return visitor(key, node, path12);
224
+ return visitor(key, node, path13);
225
225
  if (identity.isMap(node))
226
- return visitor.Map?.(key, node, path12);
226
+ return visitor.Map?.(key, node, path13);
227
227
  if (identity.isSeq(node))
228
- return visitor.Seq?.(key, node, path12);
228
+ return visitor.Seq?.(key, node, path13);
229
229
  if (identity.isPair(node))
230
- return visitor.Pair?.(key, node, path12);
230
+ return visitor.Pair?.(key, node, path13);
231
231
  if (identity.isScalar(node))
232
- return visitor.Scalar?.(key, node, path12);
232
+ return visitor.Scalar?.(key, node, path13);
233
233
  if (identity.isAlias(node))
234
- return visitor.Alias?.(key, node, path12);
234
+ return visitor.Alias?.(key, node, path13);
235
235
  return void 0;
236
236
  }
237
- function replaceNode(key, path12, node) {
238
- const parent = path12[path12.length - 1];
237
+ function replaceNode(key, path13, node) {
238
+ const parent = path13[path13.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, path12, value) {
850
+ function collectionFromPath(schema, path13, value) {
851
851
  let v2 = value;
852
- for (let i = path12.length - 1; i >= 0; --i) {
853
- const k2 = path12[i];
852
+ for (let i = path13.length - 1; i >= 0; --i) {
853
+ const k2 = path13[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 = (path12) => path12 == null || typeof path12 === "object" && !!path12[Symbol.iterator]().next().done;
872
+ var isEmptyPath = (path13) => path13 == null || typeof path13 === "object" && !!path13[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(path12, value) {
903
- if (isEmptyPath(path12))
902
+ addIn(path13, value) {
903
+ if (isEmptyPath(path13))
904
904
  this.add(value);
905
905
  else {
906
- const [key, ...rest] = path12;
906
+ const [key, ...rest] = path13;
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(path12) {
921
- const [key, ...rest] = path12;
920
+ deleteIn(path13) {
921
+ const [key, ...rest] = path13;
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(path12, keepScalar) {
936
- const [key, ...rest] = path12;
935
+ getIn(path13, keepScalar) {
936
+ const [key, ...rest] = path13;
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(path12) {
955
- const [key, ...rest] = path12;
954
+ hasIn(path13) {
955
+ const [key, ...rest] = path13;
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(path12, value) {
966
- const [key, ...rest] = path12;
965
+ setIn(path13, value) {
966
+ const [key, ...rest] = path13;
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(path12, value) {
3481
+ addIn(path13, value) {
3482
3482
  if (assertCollection(this.contents))
3483
- this.contents.addIn(path12, value);
3483
+ this.contents.addIn(path13, 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(path12) {
3559
- if (Collection.isEmptyPath(path12)) {
3558
+ deleteIn(path13) {
3559
+ if (Collection.isEmptyPath(path13)) {
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(path12) : false;
3565
+ return assertCollection(this.contents) ? this.contents.deleteIn(path13) : 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(path12, keepScalar) {
3581
- if (Collection.isEmptyPath(path12))
3580
+ getIn(path13, keepScalar) {
3581
+ if (Collection.isEmptyPath(path13))
3582
3582
  return !keepScalar && identity.isScalar(this.contents) ? this.contents.value : this.contents;
3583
- return identity.isCollection(this.contents) ? this.contents.getIn(path12, keepScalar) : void 0;
3583
+ return identity.isCollection(this.contents) ? this.contents.getIn(path13, 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(path12) {
3595
- if (Collection.isEmptyPath(path12))
3594
+ hasIn(path13) {
3595
+ if (Collection.isEmptyPath(path13))
3596
3596
  return this.contents !== void 0;
3597
- return identity.isCollection(this.contents) ? this.contents.hasIn(path12) : false;
3597
+ return identity.isCollection(this.contents) ? this.contents.hasIn(path13) : 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(path12, value) {
3615
- if (Collection.isEmptyPath(path12)) {
3614
+ setIn(path13, value) {
3615
+ if (Collection.isEmptyPath(path13)) {
3616
3616
  this.contents = value;
3617
3617
  } else if (this.contents == null) {
3618
- this.contents = Collection.collectionFromPath(this.schema, Array.from(path12), value);
3618
+ this.contents = Collection.collectionFromPath(this.schema, Array.from(path13), value);
3619
3619
  } else if (assertCollection(this.contents)) {
3620
- this.contents.setIn(path12, value);
3620
+ this.contents.setIn(path13, 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, path12) => {
5581
+ visit.itemAtPath = (cst, path13) => {
5582
5582
  let item = cst;
5583
- for (const [field, index] of path12) {
5583
+ for (const [field, index] of path13) {
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, path12) => {
5593
- const parent = visit.itemAtPath(cst, path12.slice(0, -1));
5594
- const field = path12[path12.length - 1][0];
5592
+ visit.parentCollection = (cst, path13) => {
5593
+ const parent = visit.itemAtPath(cst, path13.slice(0, -1));
5594
+ const field = path13[path13.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(path12, item, visitor) {
5601
- let ctrl = visitor(item, path12);
5600
+ function _visit(path13, item, visitor) {
5601
+ let ctrl = visitor(item, path13);
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(path12.concat([[field, i]])), token.items[i], visitor);
5608
+ const ci2 = _visit(Object.freeze(path13.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, path12);
5619
+ ctrl = ctrl(item, path13);
5620
5620
  }
5621
5621
  }
5622
- return typeof ctrl === "function" ? ctrl(item, path12) : ctrl;
5622
+ return typeof ctrl === "function" ? ctrl(item, path13) : ctrl;
5623
5623
  }
5624
5624
  exports.visit = visit;
5625
5625
  }
@@ -7607,7 +7607,7 @@ var DEFAULT_DEBUG_TRACE_LIMITS = {
7607
7607
  // packages/shared/src/contracts/settings.ts
7608
7608
  var DOCUMENT_READER_AGENT = "document-reader";
7609
7609
  var OPENROUTER_ALIAS_PROVIDER_NAME = "OpenRouter (via Forge)";
7610
- var WORK_PACK_SYNC_PLUGIN_VERSION = "0.1.35";
7610
+ var WORK_PACK_SYNC_PLUGIN_VERSION = "0.1.37";
7611
7611
  var WORK_PACK_SYNC_PLUGIN_PACKAGE = `minimal-forge-work-pack-sync@${WORK_PACK_SYNC_PLUGIN_VERSION}`;
7612
7612
  var WORK_PACK_SYNC_PLUGIN_FILENAME = `minimal-forge-work-pack-sync-${WORK_PACK_SYNC_PLUGIN_VERSION}.tgz`;
7613
7613
  var FIRECRAWL_KEYLESS_MCP_NAME = "firecrawl";
@@ -7866,7 +7866,7 @@ async function probeHealth(url2, route, headers, healthyField, source) {
7866
7866
  }
7867
7867
 
7868
7868
  // packages/cli/src/workPackSyncPlugin.ts
7869
- import { createHash as createHash6, randomUUID as randomUUID4 } from "node:crypto";
7869
+ import { createHash as createHash7, randomUUID as randomUUID4 } from "node:crypto";
7870
7870
  import { pathToFileURL } from "node:url";
7871
7871
 
7872
7872
  // packages/cli/src/skillUsageReporter.ts
@@ -8171,8 +8171,8 @@ async function replaceFile(filename, contents) {
8171
8171
 
8172
8172
  // packages/cli/src/workPackSyncPlugin.ts
8173
8173
  var import_yaml = __toESM(require_dist(), 1);
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";
8174
+ import { link, mkdir as mkdir7, mkdtemp as mkdtemp2, readdir as readdir5, readFile as readFile11, realpath, rename as rename8, rm as rm6, rmdir, stat as stat3, unlink, writeFile as writeFile8 } from "node:fs/promises";
8175
+ import path12 from "node:path";
8176
8176
 
8177
8177
  // node_modules/@opencode-ai/plugin/node_modules/zod/v4/classic/external.js
8178
8178
  var external_exports = {};
@@ -8905,10 +8905,10 @@ function mergeDefs(...defs) {
8905
8905
  function cloneDef(schema) {
8906
8906
  return mergeDefs(schema._zod.def);
8907
8907
  }
8908
- function getElementAtPath(obj, path12) {
8909
- if (!path12)
8908
+ function getElementAtPath(obj, path13) {
8909
+ if (!path13)
8910
8910
  return obj;
8911
- return path12.reduce((acc, key) => acc?.[key], obj);
8911
+ return path13.reduce((acc, key) => acc?.[key], obj);
8912
8912
  }
8913
8913
  function promiseAllObject(promisesObj) {
8914
8914
  const keys = Object.keys(promisesObj);
@@ -9269,11 +9269,11 @@ function aborted(x, startIndex = 0) {
9269
9269
  }
9270
9270
  return false;
9271
9271
  }
9272
- function prefixIssues(path12, issues) {
9272
+ function prefixIssues(path13, issues) {
9273
9273
  return issues.map((iss) => {
9274
9274
  var _a;
9275
9275
  (_a = iss).path ?? (_a.path = []);
9276
- iss.path.unshift(path12);
9276
+ iss.path.unshift(path13);
9277
9277
  return iss;
9278
9278
  });
9279
9279
  }
@@ -9441,7 +9441,7 @@ function treeifyError(error45, _mapper) {
9441
9441
  return issue2.message;
9442
9442
  };
9443
9443
  const result = { errors: [] };
9444
- const processError = (error46, path12 = []) => {
9444
+ const processError = (error46, path13 = []) => {
9445
9445
  var _a, _b;
9446
9446
  for (const issue2 of error46.issues) {
9447
9447
  if (issue2.code === "invalid_union" && issue2.errors.length) {
@@ -9451,7 +9451,7 @@ function treeifyError(error45, _mapper) {
9451
9451
  } else if (issue2.code === "invalid_element") {
9452
9452
  processError({ issues: issue2.issues }, issue2.path);
9453
9453
  } else {
9454
- const fullpath = [...path12, ...issue2.path];
9454
+ const fullpath = [...path13, ...issue2.path];
9455
9455
  if (fullpath.length === 0) {
9456
9456
  result.errors.push(mapper(issue2));
9457
9457
  continue;
@@ -9483,8 +9483,8 @@ function treeifyError(error45, _mapper) {
9483
9483
  }
9484
9484
  function toDotPath(_path) {
9485
9485
  const segs = [];
9486
- const path12 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
9487
- for (const seg of path12) {
9486
+ const path13 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
9487
+ for (const seg of path13) {
9488
9488
  if (typeof seg === "number")
9489
9489
  segs.push(`[${seg}]`);
9490
9490
  else if (typeof seg === "symbol")
@@ -25012,8 +25012,8 @@ async function operateWorkPack(paths, credentials, skillBySlug, approvedModelIds
25012
25012
  }
25013
25013
  previousManagedPaths = await managedWorkPackPaths(paths, target);
25014
25014
  archive = await downloadSkill(credentials, skill.url);
25015
- const sha2562 = createHash4("sha256").update(archive).digest("hex");
25016
- if (sha2562 !== skill.sha256) return { status: "failed", restoration: "exact", code: "checksum-mismatch" };
25015
+ const sha2563 = createHash4("sha256").update(archive).digest("hex");
25016
+ if (sha2563 !== skill.sha256) return { status: "failed", restoration: "exact", code: "checksum-mismatch" };
25017
25017
  } catch (error45) {
25018
25018
  return exactPackFailure(error45);
25019
25019
  }
@@ -25079,21 +25079,21 @@ function jsonBytes(value) {
25079
25079
  `);
25080
25080
  }
25081
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) => {
25082
+ const launchAgentPath2 = path8.join(os4.homedir(), "Library", "LaunchAgents", "com.minimal-forge.debug-trace.plist");
25083
+ const launchAgent = await readFile7(launchAgentPath2, "utf8").catch((error45) => {
25084
25084
  if (error45.code === "ENOENT") return void 0;
25085
25085
  throw error45;
25086
25086
  });
25087
25087
  if (launchAgent?.includes("<string>com.minimal-forge.debug-trace</string>")) {
25088
25088
  if (process.platform === "darwin") {
25089
25089
  const domain2 = `gui/${process.getuid?.() ?? 0}`;
25090
- const stopped = spawnSync("launchctl", ["bootout", domain2, launchAgentPath], { encoding: "utf8" });
25090
+ const stopped = spawnSync("launchctl", ["bootout", domain2, launchAgentPath2], { encoding: "utf8" });
25091
25091
  if (stopped.status !== 0) {
25092
25092
  const stillRunning = spawnSync("launchctl", ["print", `${domain2}/com.minimal-forge.debug-trace`], { encoding: "utf8" });
25093
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
25094
  }
25095
25095
  }
25096
- await rm4(launchAgentPath, { force: true });
25096
+ await rm4(launchAgentPath2, { force: true });
25097
25097
  }
25098
25098
  for (const filename of [
25099
25099
  "debug-trace-service.sh",
@@ -26127,8 +26127,8 @@ function isRecord4(value) {
26127
26127
  }
26128
26128
 
26129
26129
  // packages/cli/src/localWorkerSync.ts
26130
- import { readFile as readFile9 } from "node:fs/promises";
26131
- import path10 from "node:path";
26130
+ import { readFile as readFile10 } from "node:fs/promises";
26131
+ import path11 from "node:path";
26132
26132
 
26133
26133
  // packages/cli/src/recoveryLauncher.ts
26134
26134
  import { chmod as chmod5, readFile as readFile8 } from "node:fs/promises";
@@ -26171,13 +26171,235 @@ exec '${nodePath.replace(/'/g, "'\\''")}' ./forge-repair.mjs "$@"
26171
26171
  `;
26172
26172
  }
26173
26173
 
26174
+ // packages/cli/src/rollback.ts
26175
+ import { createHash as createHash6 } from "node:crypto";
26176
+ import { chmod as chmod6, mkdir as mkdir6, readFile as readFile9, readdir as readdir4, rename as rename7, rm as rm5, stat as stat2, writeFile as writeFile7 } from "node:fs/promises";
26177
+ import os5 from "node:os";
26178
+ import path10 from "node:path";
26179
+
26180
+ // packages/cli/src/legacyDebugTraceRuntime.ts
26181
+ var FORGE_DEBUG_TRACE_SERVICE_LABEL = "com.minimal-forge.debug-trace";
26182
+ var FORGE_DEBUG_TRACE_SERVICE_RUNNER_FILENAME = "debug-trace-service.sh";
26183
+ var FORGE_DEBUG_TRACE_SERVICE_STATE_FILENAME = "debug-trace-service-state.json";
26184
+ var FORGE_DEBUG_TRACE_OPENCODE_LAUNCHER_FILENAME = "opencode-debug-trace";
26185
+ var FORGE_DEBUG_TRACE_TAP_OUTPUT_DIRNAME = "claude-tap-traces";
26186
+
26187
+ // packages/cli/src/rollback.ts
26188
+ async function recordRollbackManagedState(paths, options = {}) {
26189
+ const lifecycle = await readRollbackLifecycle(paths);
26190
+ if (lifecycle?.state !== "pilot") return;
26191
+ const capsule = await readRollbackCapsule(paths);
26192
+ if (!capsule) return;
26193
+ const config2 = await readJsoncObject2(paths.opencodeConfigPath);
26194
+ const tui = await readJsonObject(paths.tuiConfigPath) ?? {};
26195
+ const discoveredFiles = await discoverManagedFiles(paths, options);
26196
+ const refreshablePaths = await refreshedWorkPackPaths(paths, options.updatedWorkPackSlugs ?? []);
26197
+ const previousFiles = new Map(capsule.managed.files.map((file2) => [file2.path, file2]));
26198
+ const removedManagedPaths = new Set(options.removedManagedPaths ?? []);
26199
+ const files = discoveredFiles.map((file2) => {
26200
+ const previous = previousFiles.get(file2.path);
26201
+ if (!previous || options.refreshForgeStatic && isForgeStaticManagedPath(paths, options, file2.path) || refreshablePaths.has(file2.path)) return file2;
26202
+ if (removedManagedPaths.has(file2.path)) return { ...previous, removedByForge: true };
26203
+ return previous;
26204
+ });
26205
+ const observedPaths = new Set(files.map((file2) => file2.path));
26206
+ for (const previous of capsule.managed.files) {
26207
+ if (!observedPaths.has(previous.path)) {
26208
+ files.push(removedManagedPaths.has(previous.path) ? { ...previous, removedByForge: true } : previous);
26209
+ }
26210
+ }
26211
+ files.sort((left, right) => left.path.localeCompare(right.path));
26212
+ const credentials = await readJsonObject(paths.credentialsPath);
26213
+ const wellKnownUrls = [
26214
+ ...Array.isArray(credentials?.forgeOwnedWellKnownUrls) ? credentials.forgeOwnedWellKnownUrls.filter((entry) => typeof entry === "string") : [],
26215
+ ...typeof credentials?.forgeBaseUrl === "string" ? [credentials.forgeBaseUrl.replace(/\/+$/, "")] : []
26216
+ ];
26217
+ const managed = {
26218
+ files,
26219
+ config: managedEntries(config2, [
26220
+ ["$schema"],
26221
+ ["share"],
26222
+ ["autoupdate"],
26223
+ ["model"],
26224
+ ["small_model"],
26225
+ ["provider", "forge"],
26226
+ ["provider", "openrouter"],
26227
+ ["agent", "document-reader"]
26228
+ ]),
26229
+ tui: managedEntries(tui, [["theme"]]),
26230
+ dynamicPaths: dynamicPaths(paths),
26231
+ wellKnownUrls: [...new Set(wellKnownUrls)]
26232
+ };
26233
+ if (deepEqual(capsule.managed, managed)) return;
26234
+ await writeProtectedJsonAtomic(paths.rollbackCapsulePath, { ...capsule, managed });
26235
+ }
26236
+ async function readRollbackLifecycle(paths) {
26237
+ return readJson(paths.rollbackLifecyclePath);
26238
+ }
26239
+ async function readRollbackCapsule(paths) {
26240
+ return readJson(paths.rollbackCapsulePath);
26241
+ }
26242
+ async function discoverManagedFiles(paths, options) {
26243
+ const candidates = /* @__PURE__ */ new Set();
26244
+ for (const candidate of forgeStaticManagedPaths(paths)) candidates.add(candidate);
26245
+ for (const filename of [FORGE_PLUGIN_FILENAME, FORGE_EVIDENCE_PLUGIN_FILENAME, FORGE_DEBUG_TRACE_PLUGIN_FILENAME]) {
26246
+ const pluginPath = path10.join(paths.pluginDir, filename);
26247
+ const content = await readFile9(pluginPath, "utf8").catch(() => void 0);
26248
+ if (content?.startsWith(FORGE_PLUGIN_HEADER)) candidates.add(pluginPath);
26249
+ }
26250
+ const skillEntries = await readdir4(paths.skillsDir, { withFileTypes: true }).catch(() => []);
26251
+ for (const entry of skillEntries) {
26252
+ if (!entry.isDirectory() || entry.name.endsWith(".previous")) continue;
26253
+ const skillRoot = path10.join(paths.skillsDir, entry.name);
26254
+ if (!await stat2(path10.join(skillRoot, ".forge-version")).catch(() => void 0)) continue;
26255
+ await collectFiles(skillRoot, candidates);
26256
+ for (const [recordName, targetDir] of [
26257
+ [".forge-agents", paths.agentsDir],
26258
+ [".forge-commands", paths.commandsDir]
26259
+ ]) {
26260
+ const record2 = await readFile9(path10.join(skillRoot, recordName), "utf8").catch(() => "");
26261
+ for (const filename of safeRecordedFilenames(record2)) candidates.add(path10.join(targetDir, filename));
26262
+ }
26263
+ }
26264
+ const serviceState = await readJsonObject(path10.join(paths.forgeDir, FORGE_DEBUG_TRACE_SERVICE_STATE_FILENAME));
26265
+ const expectedLaunchAgent = launchAgentPath(options);
26266
+ const launchAgent = serviceState?.launchAgentPath === expectedLaunchAgent ? serviceState.launchAgentPath : expectedLaunchAgent;
26267
+ const launchAgentContent = await readFile9(launchAgent, "utf8").catch(() => void 0);
26268
+ if (launchAgentContent?.includes(FORGE_DEBUG_TRACE_SERVICE_LABEL)) candidates.add(launchAgent);
26269
+ const files = [];
26270
+ for (const candidate of [...candidates].sort()) {
26271
+ const content = await readFile9(candidate).catch(() => void 0);
26272
+ if (content) files.push({ path: candidate, sha256: sha2562(content) });
26273
+ }
26274
+ return files;
26275
+ }
26276
+ async function refreshedWorkPackPaths(paths, slugs) {
26277
+ const refreshed = /* @__PURE__ */ new Set();
26278
+ for (const slug of slugs) {
26279
+ const skillRoot = path10.join(paths.skillsDir, slug);
26280
+ if (!isWithin(skillRoot, paths.skillsDir)) continue;
26281
+ await collectFiles(skillRoot, refreshed);
26282
+ for (const [recordName, targetDir] of [
26283
+ [".forge-agents", paths.agentsDir],
26284
+ [".forge-commands", paths.commandsDir]
26285
+ ]) {
26286
+ const record2 = await readFile9(path10.join(skillRoot, recordName), "utf8").catch(() => "");
26287
+ for (const filename of safeRecordedFilenames(record2)) refreshed.add(path10.join(targetDir, filename));
26288
+ }
26289
+ }
26290
+ return refreshed;
26291
+ }
26292
+ function forgeStaticManagedPaths(paths) {
26293
+ return [
26294
+ paths.credentialsPath,
26295
+ paths.envPath,
26296
+ paths.powershellEnvPath,
26297
+ path10.join(paths.forgeDir, FORGE_DEBUG_TRACE_CONFIG_FILENAME),
26298
+ path10.join(paths.forgeDir, FORGE_DEBUG_TRACE_SERVICE_STATE_FILENAME),
26299
+ path10.join(paths.forgeDir, FORGE_DEBUG_TRACE_SERVICE_RUNNER_FILENAME),
26300
+ path10.join(paths.forgeDir, FORGE_DEBUG_TRACE_OPENCODE_LAUNCHER_FILENAME)
26301
+ ];
26302
+ }
26303
+ function isForgeStaticManagedPath(paths, options, candidate) {
26304
+ return forgeStaticManagedPaths(paths).includes(candidate) || candidate === launchAgentPath(options) || [FORGE_PLUGIN_FILENAME, FORGE_EVIDENCE_PLUGIN_FILENAME, FORGE_DEBUG_TRACE_PLUGIN_FILENAME].some((filename) => candidate === path10.join(paths.pluginDir, filename));
26305
+ }
26306
+ async function collectFiles(root, output, include = () => true) {
26307
+ const entries = await readdir4(root, { withFileTypes: true }).catch(() => []);
26308
+ for (const entry of entries) {
26309
+ const absolute = path10.join(root, entry.name);
26310
+ if (!include(absolute)) continue;
26311
+ if (entry.isDirectory()) await collectFiles(absolute, output, include);
26312
+ else if (entry.isFile()) output.add(absolute);
26313
+ }
26314
+ }
26315
+ function managedEntries(config2, paths) {
26316
+ return paths.map((entryPath) => {
26317
+ const current = getAtPath(config2, entryPath);
26318
+ return current.present ? { path: entryPath, present: true, value: structuredClone(current.value) } : { path: entryPath, present: false };
26319
+ });
26320
+ }
26321
+ function dynamicPaths(paths) {
26322
+ return [
26323
+ path10.join(paths.forgeDir, "debug-trace-queue"),
26324
+ path10.join(paths.forgeDir, FORGE_DEBUG_TRACE_TAP_OUTPUT_DIRNAME),
26325
+ path10.join(paths.forgeDir, "verified-claude-tap"),
26326
+ path10.join(paths.forgeDir, "debug-trace-service.out.log"),
26327
+ path10.join(paths.forgeDir, "debug-trace-service.err.log")
26328
+ ];
26329
+ }
26330
+ function getAtPath(root, entryPath) {
26331
+ let current = root;
26332
+ for (const segment of entryPath) {
26333
+ if (!isRecord5(current) || !Object.prototype.hasOwnProperty.call(current, segment)) return { present: false };
26334
+ current = current[segment];
26335
+ }
26336
+ return { present: true, value: current };
26337
+ }
26338
+ function safeRecordedFilenames(raw) {
26339
+ return raw.split("\n").map((line) => line.trim()).filter((line) => line.length > 0 && !line.includes("/") && !line.includes("\\") && line !== "..");
26340
+ }
26341
+ function deepEqual(left, right) {
26342
+ return JSON.stringify(left) === JSON.stringify(right);
26343
+ }
26344
+ function launchAgentPath(options) {
26345
+ const directory = options.launchAgentsDir ?? path10.join(os5.homedir(), "Library", "LaunchAgents");
26346
+ return path10.join(directory, `${FORGE_DEBUG_TRACE_SERVICE_LABEL}.plist`);
26347
+ }
26348
+ async function writeProtectedJsonAtomic(filePath, value) {
26349
+ const directory = path10.dirname(filePath);
26350
+ await mkdir6(directory, { recursive: true, mode: 448 });
26351
+ await protectRollbackPath(directory, "directory");
26352
+ const temporary = path10.join(directory, `.${path10.basename(filePath)}.${process.pid}.tmp`);
26353
+ await writeFile7(temporary, `${JSON.stringify(value, null, 2)}
26354
+ `, { mode: 384 });
26355
+ await protectRollbackPath(temporary, "file");
26356
+ await rename7(temporary, filePath);
26357
+ }
26358
+ async function protectRollbackPath(filePath, kind, options = {}) {
26359
+ await protectOwnerOnlyPath(filePath, kind, { ...options, failureContext: "o material de rollback" });
26360
+ }
26361
+ async function readJson(filePath) {
26362
+ const raw = await readFile9(filePath, "utf8").catch((error45) => {
26363
+ if (error45.code === "ENOENT") return void 0;
26364
+ throw error45;
26365
+ });
26366
+ if (!raw) return void 0;
26367
+ return JSON.parse(raw);
26368
+ }
26369
+ async function readJsonObject(filePath) {
26370
+ const value = await readJson(filePath);
26371
+ return isRecord5(value) ? value : void 0;
26372
+ }
26373
+ async function readJsoncObject2(filePath) {
26374
+ const raw = await readFile9(filePath, "utf8").catch((error45) => {
26375
+ if (error45.code === "ENOENT") return "{}";
26376
+ throw error45;
26377
+ });
26378
+ try {
26379
+ const parsed = parseJsonc(raw);
26380
+ return isRecord5(parsed) ? parsed : {};
26381
+ } catch (error45) {
26382
+ throw new Error(`Configura\xE7\xE3o JSON/JSONC inv\xE1lida em ${filePath}`, { cause: error45 });
26383
+ }
26384
+ }
26385
+ function isWithin(candidate, root) {
26386
+ const relative = path10.relative(root, candidate);
26387
+ return relative === "" || !relative.startsWith("..") && !path10.isAbsolute(relative);
26388
+ }
26389
+ function sha2562(value) {
26390
+ return createHash6("sha256").update(value).digest("hex");
26391
+ }
26392
+ function isRecord5(value) {
26393
+ return typeof value === "object" && value !== null && !Array.isArray(value);
26394
+ }
26395
+
26174
26396
  // packages/cli/src/localWorkerSync.ts
26175
26397
  async function syncLocalWorker(paths, credentials, manifest) {
26176
- const recovery = await recoverCoreSyncTransaction({ journalPath: path10.join(paths.forgeDir, "core-sync-journal.json") });
26398
+ const recovery = await recoverCoreSyncTransaction({ journalPath: path11.join(paths.forgeDir, "core-sync-journal.json") });
26177
26399
  if (recovery.status === "uncertain") throw new CoreSyncUncertainError(recovery.message, recovery.uncertainPaths);
26178
26400
  let current;
26179
26401
  try {
26180
- current = JSON.parse(await readFile9(paths.opencodeConfigPath, "utf8"));
26402
+ current = JSON.parse(await readFile10(paths.opencodeConfigPath, "utf8"));
26181
26403
  } catch {
26182
26404
  throw new Error("A configura\xE7\xE3o local n\xE3o \xE9 JSON simples v\xE1lido; preserve os ficheiros e pe\xE7a apoio.");
26183
26405
  }
@@ -26189,13 +26411,23 @@ async function syncLocalWorker(paths, credentials, manifest) {
26189
26411
  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
26412
  }
26191
26413
  await installRecoveryLauncher(paths, credentials.forgeBaseUrl);
26192
- const result = await applyManifest(paths, credentials, manifest);
26414
+ const result = await applyManifest(paths, credentials, manifest, {
26415
+ beforeManagedPathsRemoved: (removedManagedPaths) => recordRollbackManagedState(paths, { removedManagedPaths })
26416
+ });
26193
26417
  await removeWellKnownAuth(paths, credentials);
26418
+ await recordRollbackManagedState(paths, {
26419
+ refreshForgeStatic: true,
26420
+ updatedWorkPackSlugs: result.installed.map((entry) => {
26421
+ const separator = entry.lastIndexOf("@");
26422
+ return separator > 0 ? entry.slice(0, separator) : entry;
26423
+ }),
26424
+ removedManagedPaths: result.removedManagedPaths
26425
+ });
26194
26426
  return result;
26195
26427
  }
26196
26428
 
26197
26429
  // packages/cli/src/workPackSyncPlugin.ts
26198
- var PLUGIN_VERSION = "0.1.35";
26430
+ var PLUGIN_VERSION = "0.1.37";
26199
26431
  var FORGE_DECISION_TIMEOUT_MS = 11e4;
26200
26432
  var STATUS_FILENAME = "work-pack-startup-status.json";
26201
26433
  var activeSync = /* @__PURE__ */ new Map();
@@ -26209,7 +26441,7 @@ var ForgeWorkPackSyncServer = async (_input, options) => {
26209
26441
  activeSync.set(syncKey, sync);
26210
26442
  }
26211
26443
  const state = await sync;
26212
- const legacyPath = path11.join(state.paths.pluginDir, FORGE_EVIDENCE_PLUGIN_FILENAME);
26444
+ const legacyPath = path12.join(state.paths.pluginDir, FORGE_EVIDENCE_PLUGIN_FILENAME);
26213
26445
  const ownershipSymbol = /* @__PURE__ */ Symbol.for("minimal-forge.legacy-evidence-owners.v1");
26214
26446
  const shared = globalThis;
26215
26447
  const legacyOwners = shared[ownershipSymbol] ??= /* @__PURE__ */ new Set();
@@ -26220,13 +26452,13 @@ var ForgeWorkPackSyncServer = async (_input, options) => {
26220
26452
  const slug = typeof input.args?.name === "string" ? input.args.name.trim().toLowerCase() : "";
26221
26453
  if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug)) return;
26222
26454
  try {
26223
- await readFile10(path11.join(state.paths.skillsDir, slug, ".forge-version"), "utf8");
26455
+ await readFile11(path12.join(state.paths.skillsDir, slug, ".forge-version"), "utf8");
26224
26456
  } catch {
26225
26457
  return;
26226
26458
  }
26227
26459
  try {
26228
26460
  const { forgeApiKey } = await readForgeCredentials(state.paths, forgeBaseUrl);
26229
- const credentialId = createHash6("sha256").update(forgeApiKey).digest("hex");
26461
+ const credentialId = createHash7("sha256").update(forgeApiKey).digest("hex");
26230
26462
  const reportUsage = skillUsageReporter(forgeBaseUrl, credentialId, (events) => fetch(`${forgeBaseUrl}/sync/evidence`, {
26231
26463
  method: "POST",
26232
26464
  redirect: "error",
@@ -26245,10 +26477,10 @@ var ForgeWorkPackSyncServer = async (_input, options) => {
26245
26477
  const name = Array.isArray(entry) ? entry[0] : entry;
26246
26478
  return name === legacyPath || name === pathToFileURL(legacyPath).href;
26247
26479
  });
26248
- const legacy = registered ? await readFile10(legacyPath, "utf8").catch(() => "") : "";
26480
+ const legacy = registered ? await readFile11(legacyPath, "utf8").catch(() => "") : "";
26249
26481
  const oldLegacyRegistered = registered && legacy.startsWith(FORGE_PLUGIN_HEADER) && legacy.includes("work_pack_invocation") && !legacy.includes("minimal-forge.skill-usage.v1");
26250
26482
  if (oldLegacyRegistered) legacyOwners.add(legacyOwnerKey);
26251
- if (oldLegacyRegistered) await writeFile7(legacyPath, renderEvidencePlugin()).catch(() => {
26483
+ if (oldLegacyRegistered) await writeFile8(legacyPath, renderEvidencePlugin()).catch(() => {
26252
26484
  console.error("[Forge evidence] Legacy hook upgrade failed; existing hook retained");
26253
26485
  });
26254
26486
  await projectCurrentExtensions(config2, state);
@@ -26276,7 +26508,7 @@ function createForgeImageTool(forgeBaseUrl, gatewayBaseUrl, paths) {
26276
26508
  const requestId = randomUUID4();
26277
26509
  let referenceDataUrl;
26278
26510
  if (args.referencePath) {
26279
- const bytes = await readFile10(args.referencePath);
26511
+ const bytes = await readFile11(args.referencePath);
26280
26512
  if (bytes.byteLength > 25e5) throw new Error("A imagem de refer\xEAncia \xE9 demasiado grande. Reduza-a antes de tentar novamente.");
26281
26513
  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;
26282
26514
  if (!mime) throw new Error("A refer\xEAncia tem de ser PNG, JPEG ou WebP.");
@@ -26302,8 +26534,8 @@ function createForgeImageTool(forgeBaseUrl, gatewayBaseUrl, paths) {
26302
26534
  if (image.byteLength > 8 * 1024 * 1024 || !image.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) {
26303
26535
  throw new Error(`O PNG recebido \xE9 inv\xE1lido. Refer\xEAncia: ${requestId}`);
26304
26536
  }
26305
- const destination = path11.join(context.directory, `forge-image-${requestId}.png`);
26306
- await writeFile7(destination, image, { flag: "wx" });
26537
+ const destination = path12.join(context.directory, `forge-image-${requestId}.png`);
26538
+ await writeFile8(destination, image, { flag: "wx" });
26307
26539
  const reset = body.quota && new Intl.DateTimeFormat("pt-PT", { dateStyle: "long", timeZone: "Europe/Lisbon" }).format(new Date(body.quota.resetsAt));
26308
26540
  const remaining = body.quota ? ` Restam ${body.quota.remaining} imagens at\xE9 ${reset}.` : "";
26309
26541
  return `Imagem guardada em ${destination}.${remaining}
@@ -26349,7 +26581,7 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseD
26349
26581
  let requestBody;
26350
26582
  if (fromFile) {
26351
26583
  const file2 = await fileInsideWorkspace(context.directory, args.request_file);
26352
- const raw = await readFile10(file2, "utf8");
26584
+ const raw = await readFile11(file2, "utf8");
26353
26585
  if (Buffer.byteLength(raw) > 512 * 1024) throw new Error("O ficheiro de pedido excede 512 KiB.");
26354
26586
  let parsed;
26355
26587
  try {
@@ -26368,8 +26600,8 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseD
26368
26600
  if (args.state === void 0 || !args.questions || Object.keys(args.questions).length === 0) throw new Error("Indica state e questions.");
26369
26601
  requestBody = { state: args.state, questions: args.questions };
26370
26602
  }
26371
- const responseDir = await mkdtemp2(path11.join(responseDirectory ?? context.directory, ".forge-decision-"));
26372
- const responseFile = path11.join(responseDir, "response.json");
26603
+ const responseDir = await mkdtemp2(path12.join(responseDirectory ?? context.directory, ".forge-decision-"));
26604
+ const responseFile = path12.join(responseDir, "response.json");
26373
26605
  try {
26374
26606
  const credentials = await readForgeCredentials(paths, forgeBaseUrl);
26375
26607
  const response = await fetch(`${decisionBaseUrl}/v1/decisions`, {
@@ -26390,7 +26622,7 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseD
26390
26622
  }
26391
26623
  if (response.ok && body && typeof body === "object" && body.answers && typeof body.answers === "object") {
26392
26624
  try {
26393
- await writeFile7(responseFile, raw, { flag: "wx", mode: 384 });
26625
+ await writeFile8(responseFile, raw, { flag: "wx", mode: 384 });
26394
26626
  return JSON.stringify({ ...body, response_file: responseFile }, null, 2);
26395
26627
  } catch {
26396
26628
  return JSON.stringify({
@@ -26415,14 +26647,14 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseD
26415
26647
  }
26416
26648
  async function fileInsideWorkspace(directory, candidate) {
26417
26649
  const workspace = await realpath(directory);
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.");
26650
+ const file2 = await realpath(path12.resolve(workspace, candidate));
26651
+ const relative = path12.relative(workspace, file2);
26652
+ if (!relative || (relative === ".." || relative.startsWith(`..${path12.sep}`)) || path12.isAbsolute(relative)) throw new Error("O ficheiro tem de estar dentro do workspace.");
26421
26653
  return file2;
26422
26654
  }
26423
26655
  async function fileExists(candidate) {
26424
26656
  try {
26425
- await stat2(candidate);
26657
+ await stat3(candidate);
26426
26658
  return true;
26427
26659
  } catch (error45) {
26428
26660
  if (error45.code === "ENOENT") return false;
@@ -26443,19 +26675,19 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
26443
26675
  args: { plan_file: tool.schema.string().describe("Caminho de jev/plan.json dentro do workspace") },
26444
26676
  async execute(args, context) {
26445
26677
  const planFile = await fileInsideWorkspace(context.directory, args.plan_file);
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"));
26678
+ if (path12.basename(planFile) !== "plan.json" || path12.basename(path12.dirname(planFile)) !== "jev") throw new Error("Indica o ficheiro jev/plan.json.");
26679
+ const runDir = path12.dirname(path12.dirname(planFile));
26680
+ const plan = JSON.parse(await readFile11(planFile, "utf8"));
26449
26681
  if (plan.engine !== "jev-batch" || plan.model !== "typesafe/jev-1.13" || !Array.isArray(plan.batches)) throw new Error("O plano Jev \xE9 inv\xE1lido.");
26450
26682
  const batches = plan.batches;
26451
- const responsePath = path11.join(runDir, "jev", "responses");
26452
- await mkdir6(responsePath, { recursive: true });
26683
+ const responsePath = path12.join(runDir, "jev", "responses");
26684
+ await mkdir7(responsePath, { recursive: true });
26453
26685
  const responseDir = await fileInsideWorkspace(context.directory, responsePath);
26454
- if (path11.dirname(responseDir) !== path11.join(runDir, "jev")) throw new Error("A pasta de respostas tem de pertencer ao run Jev.");
26686
+ if (path12.dirname(responseDir) !== path12.join(runDir, "jev")) throw new Error("A pasta de respostas tem de pertencer ao run Jev.");
26455
26687
  const decide = createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseDir);
26456
- const lockDir = path11.join(runDir, "jev", ".decide-run.lock");
26688
+ const lockDir = path12.join(runDir, "jev", ".decide-run.lock");
26457
26689
  try {
26458
- await mkdir6(lockDir);
26690
+ await mkdir7(lockDir);
26459
26691
  } catch (error45) {
26460
26692
  if (error45.code !== "EEXIST") throw error45;
26461
26693
  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.");
@@ -26464,26 +26696,26 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
26464
26696
  let saved = 0;
26465
26697
  let skipped = 0;
26466
26698
  try {
26467
- await writeFile7(path11.join(lockDir, "owner.json"), JSON.stringify({ pid: process.pid, started_at: (/* @__PURE__ */ new Date()).toISOString() }), { mode: 384 });
26699
+ await writeFile8(path12.join(lockDir, "owner.json"), JSON.stringify({ pid: process.pid, started_at: (/* @__PURE__ */ new Date()).toISOString() }), { mode: 384 });
26468
26700
  for (const batch of batches) {
26469
26701
  context.abort.throwIfAborted();
26470
26702
  const batchId = batch.batch_id;
26471
26703
  if (typeof batchId !== "string" || !/^batch-[0-9]{4}-[A-Za-z0-9._-]+$/.test(batchId) || typeof batch.request_file !== "string" || typeof batch.request_fingerprint !== "string") {
26472
26704
  throw new Error("O plano Jev cont\xE9m um lote inv\xE1lido.");
26473
26705
  }
26474
- const acceptedFile = path11.join(runDir, "jev", "accepted", `${batchId}.json`);
26475
- const responseFile = path11.join(responseDir, `${batchId}.response.json`);
26706
+ const acceptedFile = path12.join(runDir, "jev", "accepted", `${batchId}.json`);
26707
+ const responseFile = path12.join(responseDir, `${batchId}.response.json`);
26476
26708
  const requestFile = await fileInsideWorkspace(context.directory, batch.request_file);
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");
26709
+ if (path12.dirname(requestFile) !== path12.join(runDir, "jev", "requests")) throw new Error(`${batchId}: pedido fora do run.`);
26710
+ const request = JSON.parse(await readFile11(requestFile, "utf8"));
26711
+ const fingerprint = createHash7("sha256").update(canonicalJson(request)).digest("hex");
26480
26712
  if (fingerprint !== batch.request_fingerprint) throw new Error(`${batchId}: fingerprint do pedido n\xE3o corresponde ao plano.`);
26481
26713
  if (await fileExists(acceptedFile) || await fileExists(responseFile)) {
26482
26714
  skipped++;
26483
26715
  continue;
26484
26716
  }
26485
26717
  let result;
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 });
26718
+ await writeFile8(path12.join(lockDir, "owner.json"), JSON.stringify({ pid: process.pid, batch_id: batchId, request_fingerprint: fingerprint, started_at: (/* @__PURE__ */ new Date()).toISOString() }), { mode: 384 });
26487
26719
  try {
26488
26720
  const output = await decide.execute({ request_file: requestFile }, context);
26489
26721
  result = JSON.parse(typeof output === "string" ? output : output.output);
@@ -26508,7 +26740,7 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
26508
26740
  error: "Resposta conclu\xEDda mas n\xE3o copiada para o run; recuperar o ficheiro indicado, sem repetir a chamada."
26509
26741
  });
26510
26742
  }
26511
- await unlink(result.response_file).then(() => rmdir(path11.dirname(result.response_file))).catch(() => void 0);
26743
+ await unlink(result.response_file).then(() => rmdir(path12.dirname(result.response_file))).catch(() => void 0);
26512
26744
  saved++;
26513
26745
  }
26514
26746
  return JSON.stringify({
@@ -26520,17 +26752,23 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
26520
26752
  next_step: "Executar jev-accept sobre as respostas guardadas ainda n\xE3o aceites; depois jev-validate e jev-merge."
26521
26753
  });
26522
26754
  } finally {
26523
- if (releaseLock) await rm5(lockDir, { recursive: true });
26755
+ if (releaseLock) await rm6(lockDir, { recursive: true });
26524
26756
  }
26525
26757
  }
26526
26758
  });
26527
26759
  }
26528
26760
  function createForgeCodebookTool(forgeBaseUrl, gatewayBaseUrl, paths) {
26529
26761
  return tool({
26530
- description: "Gera um rascunho de codebook em portugu\xEAs europeu a partir de uma pergunta e das respostas. Apresentar para aprova\xE7\xE3o humana antes de codificar; n\xE3o aplica c\xF3digos nem altera ficheiros.",
26762
+ description: "Gera um codebook ou enriquece as descri\xE7\xF5es em falta de uma grelha existente, preservando c\xF3digos e r\xF3tulos. Apresentar a proposta e review_notes para revis\xE3o humana antes de codificar; n\xE3o aplica c\xF3digos nem altera ficheiros.",
26531
26763
  args: {
26532
26764
  question: tool.schema.string().trim().min(1).max(1e4).describe("Texto da pergunta aberta"),
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")
26765
+ 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"),
26766
+ existing_codebook: tool.schema.array(tool.schema.object({
26767
+ code: tool.schema.number().int().nonnegative(),
26768
+ label: tool.schema.string().min(1).max(120),
26769
+ description: tool.schema.string().max(1e3).nullable().optional()
26770
+ })).min(1).max(100).optional().describe("Grelha completa a enriquecer, incluindo 98/99 se existirem; omitir para gerar de raiz"),
26771
+ context: tool.schema.string().max(1e4).optional().describe("Contexto conhecido, regras do estudo e exemplos humanos explicitamente aprovados; n\xE3o apresentar c\xF3digos anteriores de IA como verdade")
26534
26772
  },
26535
26773
  async execute(args, context) {
26536
26774
  const credentials = await readForgeCredentials(paths, forgeBaseUrl);
@@ -26538,7 +26776,7 @@ function createForgeCodebookTool(forgeBaseUrl, gatewayBaseUrl, paths) {
26538
26776
  method: "POST",
26539
26777
  redirect: "error",
26540
26778
  headers: { authorization: `Bearer ${credentials.forgeApiKey}`, "content-type": "application/json" },
26541
- body: JSON.stringify({ question: args.question, responses: args.responses }),
26779
+ body: JSON.stringify({ question: args.question, responses: args.responses, existing_codebook: args.existing_codebook, context: args.context }),
26542
26780
  signal: AbortSignal.any([context.abort, AbortSignal.timeout(FORGE_DECISION_TIMEOUT_MS)])
26543
26781
  });
26544
26782
  const body = await response.json().catch(() => void 0);
@@ -26629,7 +26867,7 @@ async function synchronizeAtStartup(forgeBaseUrl, input, localConfig) {
26629
26867
  }
26630
26868
  async function savedGatewayBaseUrl(paths, credentials, forgeBaseUrl) {
26631
26869
  try {
26632
- const config2 = objectRecord(parseJsonc(await readFile10(paths.opencodeConfigPath, "utf8")));
26870
+ const config2 = objectRecord(parseJsonc(await readFile11(paths.opencodeConfigPath, "utf8")));
26633
26871
  const options = objectRecord(objectRecord(objectRecord(config2.provider).forge).options);
26634
26872
  if (options.apiKey !== credentials.forgeApiKey || typeof options.baseURL !== "string" || !options.baseURL.endsWith("/v1")) return void 0;
26635
26873
  const origin = options.baseURL.slice(0, -"/v1".length);
@@ -26654,7 +26892,7 @@ function resolveStartupPaths() {
26654
26892
  return resolvePaths(void 0, void 0, env);
26655
26893
  }
26656
26894
  async function readForgeCredentials(paths, forgeBaseUrl) {
26657
- const raw = await readFile10(paths.opencodeAuthPath, "utf8").catch((error45) => {
26895
+ const raw = await readFile11(paths.opencodeAuthPath, "utf8").catch((error45) => {
26658
26896
  if (error45.code === "ENOENT") return void 0;
26659
26897
  throw error45;
26660
26898
  });
@@ -26697,22 +26935,22 @@ function parseForgeBaseUrl(options) {
26697
26935
  async function managedProjectionNames(paths) {
26698
26936
  const agents = /* @__PURE__ */ new Set();
26699
26937
  const commands = /* @__PURE__ */ new Set();
26700
- const entries = await readdir4(paths.skillsDir, { withFileTypes: true }).catch((error45) => {
26938
+ const entries = await readdir5(paths.skillsDir, { withFileTypes: true }).catch((error45) => {
26701
26939
  if (error45.code === "ENOENT") return [];
26702
26940
  throw error45;
26703
26941
  });
26704
26942
  for (const entry of entries) {
26705
26943
  if (!entry.isDirectory()) continue;
26706
- const folder = path11.join(paths.skillsDir, entry.name);
26707
- const marker = await readFile10(path11.join(folder, ".forge-version"), "utf8").catch(() => "");
26944
+ const folder = path12.join(paths.skillsDir, entry.name);
26945
+ const marker = await readFile11(path12.join(folder, ".forge-version"), "utf8").catch(() => "");
26708
26946
  if (!marker.trim()) continue;
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));
26947
+ for (const name of await readProjectionRecord(path12.join(folder, ".forge-agents"))) agents.add(stripMarkdownExtension(name));
26948
+ for (const name of await readProjectionRecord(path12.join(folder, ".forge-commands"))) commands.add(stripMarkdownExtension(name));
26711
26949
  }
26712
26950
  return { agents, commands };
26713
26951
  }
26714
26952
  async function readProjectionRecord(filePath) {
26715
- const raw = await readFile10(filePath, "utf8").catch(() => "");
26953
+ const raw = await readFile11(filePath, "utf8").catch(() => "");
26716
26954
  return raw.split("\n").map((line) => line.trim()).filter(
26717
26955
  (line) => line.endsWith(".md") && !line.includes("/") && !line.includes("\\") && line !== ".."
26718
26956
  );
@@ -26723,21 +26961,21 @@ async function projectCurrentExtensions(config2, state) {
26723
26961
  for (const name of state.before.agents) if (!state.after.agents.has(name)) delete agents[name];
26724
26962
  for (const name of state.before.commands) if (!state.after.commands.has(name)) delete commands[name];
26725
26963
  for (const name of state.after.agents) {
26726
- agents[name] = await parseMarkdownConfig(path11.join(state.paths.agentsDir, `${name}.md`), "prompt");
26964
+ agents[name] = await parseMarkdownConfig(path12.join(state.paths.agentsDir, `${name}.md`), "prompt");
26727
26965
  }
26728
26966
  for (const name of state.after.commands) {
26729
- commands[name] = await parseMarkdownConfig(path11.join(state.paths.commandsDir, `${name}.md`), "template");
26967
+ commands[name] = await parseMarkdownConfig(path12.join(state.paths.commandsDir, `${name}.md`), "template");
26730
26968
  }
26731
26969
  config2.agent = agents;
26732
26970
  config2.command = commands;
26733
26971
  }
26734
26972
  async function parseMarkdownConfig(filePath, bodyField) {
26735
- const raw = await readFile10(filePath, "utf8");
26973
+ const raw = await readFile11(filePath, "utf8");
26736
26974
  const match = /^---\r?\n([\s\S]+?)\r?\n---\r?\n?([\s\S]*)$/.exec(raw);
26737
- if (!match) throw new Error(`A extens\xE3o Forge ${path11.basename(filePath)} n\xE3o tem frontmatter v\xE1lido`);
26975
+ if (!match) throw new Error(`A extens\xE3o Forge ${path12.basename(filePath)} n\xE3o tem frontmatter v\xE1lido`);
26738
26976
  const data = (0, import_yaml.parse)(match[1]);
26739
26977
  if (!data || typeof data !== "object" || Array.isArray(data)) {
26740
- throw new Error(`A extens\xE3o Forge ${path11.basename(filePath)} n\xE3o tem frontmatter v\xE1lido`);
26978
+ throw new Error(`A extens\xE3o Forge ${path12.basename(filePath)} n\xE3o tem frontmatter v\xE1lido`);
26741
26979
  }
26742
26980
  const config2 = { ...data, [bodyField]: match[2].trim() };
26743
26981
  if (bodyField === "prompt" && typeof config2.permission === "string" && ["allow", "ask", "deny"].includes(config2.permission)) {
@@ -26752,12 +26990,12 @@ function stripMarkdownExtension(filename) {
26752
26990
  return filename.slice(0, -3);
26753
26991
  }
26754
26992
  async function writeStatus(paths, value) {
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)}
26993
+ await mkdir7(paths.forgeDir, { recursive: true });
26994
+ const target = path12.join(paths.forgeDir, STATUS_FILENAME);
26995
+ const temporary = path12.join(paths.forgeDir, `.${STATUS_FILENAME}.${process.pid}.tmp`);
26996
+ await writeFile8(temporary, `${JSON.stringify(value, null, 2)}
26759
26997
  `, { mode: 384 });
26760
- await rename7(temporary, target);
26998
+ await rename8(temporary, target);
26761
26999
  }
26762
27000
  function safeErrorMessage(error45) {
26763
27001
  const message = error45 instanceof Error ? error45.message : "erro desconhecido";
package/dist/repair.js CHANGED
@@ -401,7 +401,7 @@ var DEVICE_ENROLLMENT_PROTOCOL_VERSION = 1;
401
401
  // packages/shared/src/contracts/settings.ts
402
402
  var DOCUMENT_READER_AGENT = "document-reader";
403
403
  var OPENROUTER_ALIAS_PROVIDER_NAME = "OpenRouter (via Forge)";
404
- var WORK_PACK_SYNC_PLUGIN_VERSION = "0.1.35";
404
+ var WORK_PACK_SYNC_PLUGIN_VERSION = "0.1.37";
405
405
  var WORK_PACK_SYNC_PLUGIN_PACKAGE = `minimal-forge-work-pack-sync@${WORK_PACK_SYNC_PLUGIN_VERSION}`;
406
406
  var WORK_PACK_SYNC_PLUGIN_FILENAME = `minimal-forge-work-pack-sync-${WORK_PACK_SYNC_PLUGIN_VERSION}.tgz`;
407
407
  var FIRECRAWL_KEYLESS_MCP_NAME = "firecrawl";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "minimal-forge-work-pack-sync",
3
- "version": "0.1.35",
3
+ "version": "0.1.37",
4
4
  "description": "Minimal Forge Work Pack startup synchronization for OpenCode and OpenWork.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {