minimal-forge-work-pack-sync 0.1.48 → 0.1.49
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 +694 -421
- package/dist/repair.js +1 -1
- package/package.json +2 -2
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,
|
|
121
|
-
const ctrl = callVisitor(key, node, visitor,
|
|
120
|
+
function visit_(key, node, visitor, path15) {
|
|
121
|
+
const ctrl = callVisitor(key, node, visitor, path15);
|
|
122
122
|
if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
|
|
123
|
-
replaceNode(key,
|
|
124
|
-
return visit_(key, ctrl, visitor,
|
|
123
|
+
replaceNode(key, path15, ctrl);
|
|
124
|
+
return visit_(key, ctrl, visitor, path15);
|
|
125
125
|
}
|
|
126
126
|
if (typeof ctrl !== "symbol") {
|
|
127
127
|
if (identity.isCollection(node)) {
|
|
128
|
-
|
|
128
|
+
path15 = Object.freeze(path15.concat(node));
|
|
129
129
|
for (let i = 0; i < node.items.length; ++i) {
|
|
130
|
-
const ci2 = visit_(i, node.items[i], visitor,
|
|
130
|
+
const ci2 = visit_(i, node.items[i], visitor, path15);
|
|
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
|
-
|
|
142
|
-
const ck = visit_("key", node.key, visitor,
|
|
141
|
+
path15 = Object.freeze(path15.concat(node));
|
|
142
|
+
const ck = visit_("key", node.key, visitor, path15);
|
|
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,
|
|
147
|
+
const cv = visit_("value", node.value, visitor, path15);
|
|
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,
|
|
169
|
-
const ctrl = await callVisitor(key, node, visitor,
|
|
168
|
+
async function visitAsync_(key, node, visitor, path15) {
|
|
169
|
+
const ctrl = await callVisitor(key, node, visitor, path15);
|
|
170
170
|
if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
|
|
171
|
-
replaceNode(key,
|
|
172
|
-
return visitAsync_(key, ctrl, visitor,
|
|
171
|
+
replaceNode(key, path15, ctrl);
|
|
172
|
+
return visitAsync_(key, ctrl, visitor, path15);
|
|
173
173
|
}
|
|
174
174
|
if (typeof ctrl !== "symbol") {
|
|
175
175
|
if (identity.isCollection(node)) {
|
|
176
|
-
|
|
176
|
+
path15 = Object.freeze(path15.concat(node));
|
|
177
177
|
for (let i = 0; i < node.items.length; ++i) {
|
|
178
|
-
const ci2 = await visitAsync_(i, node.items[i], visitor,
|
|
178
|
+
const ci2 = await visitAsync_(i, node.items[i], visitor, path15);
|
|
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
|
-
|
|
190
|
-
const ck = await visitAsync_("key", node.key, visitor,
|
|
189
|
+
path15 = Object.freeze(path15.concat(node));
|
|
190
|
+
const ck = await visitAsync_("key", node.key, visitor, path15);
|
|
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,
|
|
195
|
+
const cv = await visitAsync_("value", node.value, visitor, path15);
|
|
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,
|
|
222
|
+
function callVisitor(key, node, visitor, path15) {
|
|
223
223
|
if (typeof visitor === "function")
|
|
224
|
-
return visitor(key, node,
|
|
224
|
+
return visitor(key, node, path15);
|
|
225
225
|
if (identity.isMap(node))
|
|
226
|
-
return visitor.Map?.(key, node,
|
|
226
|
+
return visitor.Map?.(key, node, path15);
|
|
227
227
|
if (identity.isSeq(node))
|
|
228
|
-
return visitor.Seq?.(key, node,
|
|
228
|
+
return visitor.Seq?.(key, node, path15);
|
|
229
229
|
if (identity.isPair(node))
|
|
230
|
-
return visitor.Pair?.(key, node,
|
|
230
|
+
return visitor.Pair?.(key, node, path15);
|
|
231
231
|
if (identity.isScalar(node))
|
|
232
|
-
return visitor.Scalar?.(key, node,
|
|
232
|
+
return visitor.Scalar?.(key, node, path15);
|
|
233
233
|
if (identity.isAlias(node))
|
|
234
|
-
return visitor.Alias?.(key, node,
|
|
234
|
+
return visitor.Alias?.(key, node, path15);
|
|
235
235
|
return void 0;
|
|
236
236
|
}
|
|
237
|
-
function replaceNode(key,
|
|
238
|
-
const parent =
|
|
237
|
+
function replaceNode(key, path15, node) {
|
|
238
|
+
const parent = path15[path15.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,
|
|
850
|
+
function collectionFromPath(schema, path15, value) {
|
|
851
851
|
let v2 = value;
|
|
852
|
-
for (let i =
|
|
853
|
-
const k2 =
|
|
852
|
+
for (let i = path15.length - 1; i >= 0; --i) {
|
|
853
|
+
const k2 = path15[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 = (
|
|
872
|
+
var isEmptyPath = (path15) => path15 == null || typeof path15 === "object" && !!path15[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(
|
|
903
|
-
if (isEmptyPath(
|
|
902
|
+
addIn(path15, value) {
|
|
903
|
+
if (isEmptyPath(path15))
|
|
904
904
|
this.add(value);
|
|
905
905
|
else {
|
|
906
|
-
const [key, ...rest] =
|
|
906
|
+
const [key, ...rest] = path15;
|
|
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(
|
|
921
|
-
const [key, ...rest] =
|
|
920
|
+
deleteIn(path15) {
|
|
921
|
+
const [key, ...rest] = path15;
|
|
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(
|
|
936
|
-
const [key, ...rest] =
|
|
935
|
+
getIn(path15, keepScalar) {
|
|
936
|
+
const [key, ...rest] = path15;
|
|
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(
|
|
955
|
-
const [key, ...rest] =
|
|
954
|
+
hasIn(path15) {
|
|
955
|
+
const [key, ...rest] = path15;
|
|
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(
|
|
966
|
-
const [key, ...rest] =
|
|
965
|
+
setIn(path15, value) {
|
|
966
|
+
const [key, ...rest] = path15;
|
|
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(
|
|
3481
|
+
addIn(path15, value) {
|
|
3482
3482
|
if (assertCollection(this.contents))
|
|
3483
|
-
this.contents.addIn(
|
|
3483
|
+
this.contents.addIn(path15, 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(
|
|
3559
|
-
if (Collection.isEmptyPath(
|
|
3558
|
+
deleteIn(path15) {
|
|
3559
|
+
if (Collection.isEmptyPath(path15)) {
|
|
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(
|
|
3565
|
+
return assertCollection(this.contents) ? this.contents.deleteIn(path15) : 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(
|
|
3581
|
-
if (Collection.isEmptyPath(
|
|
3580
|
+
getIn(path15, keepScalar) {
|
|
3581
|
+
if (Collection.isEmptyPath(path15))
|
|
3582
3582
|
return !keepScalar && identity.isScalar(this.contents) ? this.contents.value : this.contents;
|
|
3583
|
-
return identity.isCollection(this.contents) ? this.contents.getIn(
|
|
3583
|
+
return identity.isCollection(this.contents) ? this.contents.getIn(path15, 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(
|
|
3595
|
-
if (Collection.isEmptyPath(
|
|
3594
|
+
hasIn(path15) {
|
|
3595
|
+
if (Collection.isEmptyPath(path15))
|
|
3596
3596
|
return this.contents !== void 0;
|
|
3597
|
-
return identity.isCollection(this.contents) ? this.contents.hasIn(
|
|
3597
|
+
return identity.isCollection(this.contents) ? this.contents.hasIn(path15) : 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(
|
|
3615
|
-
if (Collection.isEmptyPath(
|
|
3614
|
+
setIn(path15, value) {
|
|
3615
|
+
if (Collection.isEmptyPath(path15)) {
|
|
3616
3616
|
this.contents = value;
|
|
3617
3617
|
} else if (this.contents == null) {
|
|
3618
|
-
this.contents = Collection.collectionFromPath(this.schema, Array.from(
|
|
3618
|
+
this.contents = Collection.collectionFromPath(this.schema, Array.from(path15), value);
|
|
3619
3619
|
} else if (assertCollection(this.contents)) {
|
|
3620
|
-
this.contents.setIn(
|
|
3620
|
+
this.contents.setIn(path15, 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,
|
|
5581
|
+
visit.itemAtPath = (cst, path15) => {
|
|
5582
5582
|
let item = cst;
|
|
5583
|
-
for (const [field, index] of
|
|
5583
|
+
for (const [field, index] of path15) {
|
|
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,
|
|
5593
|
-
const parent = visit.itemAtPath(cst,
|
|
5594
|
-
const field =
|
|
5592
|
+
visit.parentCollection = (cst, path15) => {
|
|
5593
|
+
const parent = visit.itemAtPath(cst, path15.slice(0, -1));
|
|
5594
|
+
const field = path15[path15.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(
|
|
5601
|
-
let ctrl = visitor(item,
|
|
5600
|
+
function _visit(path15, item, visitor) {
|
|
5601
|
+
let ctrl = visitor(item, path15);
|
|
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(
|
|
5608
|
+
const ci2 = _visit(Object.freeze(path15.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,
|
|
5619
|
+
ctrl = ctrl(item, path15);
|
|
5620
5620
|
}
|
|
5621
5621
|
}
|
|
5622
|
-
return typeof ctrl === "function" ? ctrl(item,
|
|
5622
|
+
return typeof ctrl === "function" ? ctrl(item, path15) : ctrl;
|
|
5623
5623
|
}
|
|
5624
5624
|
exports.visit = visit;
|
|
5625
5625
|
}
|
|
@@ -7370,6 +7370,68 @@ var require_dist = __commonJS({
|
|
|
7370
7370
|
}
|
|
7371
7371
|
});
|
|
7372
7372
|
|
|
7373
|
+
// packages/cli/src/workPackExtensions.ts
|
|
7374
|
+
var import_yaml = __toESM(require_dist(), 1);
|
|
7375
|
+
import { readFile, readdir } from "node:fs/promises";
|
|
7376
|
+
import path from "node:path";
|
|
7377
|
+
async function managedProjectionNames(paths) {
|
|
7378
|
+
const agents = /* @__PURE__ */ new Set();
|
|
7379
|
+
const commands = /* @__PURE__ */ new Set();
|
|
7380
|
+
const entries = await readdir(paths.skillsDir, { withFileTypes: true }).catch((error45) => {
|
|
7381
|
+
if (error45.code === "ENOENT") return [];
|
|
7382
|
+
throw error45;
|
|
7383
|
+
});
|
|
7384
|
+
for (const entry of entries) {
|
|
7385
|
+
if (!entry.isDirectory()) continue;
|
|
7386
|
+
const folder = path.join(paths.skillsDir, entry.name);
|
|
7387
|
+
const marker = await readFile(path.join(folder, ".forge-version"), "utf8").catch(() => "");
|
|
7388
|
+
if (!marker.trim()) continue;
|
|
7389
|
+
for (const name of await readProjectionRecord(path.join(folder, ".forge-agents"))) agents.add(stripMarkdownExtension(name));
|
|
7390
|
+
for (const name of await readProjectionRecord(path.join(folder, ".forge-commands"))) commands.add(stripMarkdownExtension(name));
|
|
7391
|
+
}
|
|
7392
|
+
return { agents, commands };
|
|
7393
|
+
}
|
|
7394
|
+
async function readProjectionRecord(filePath) {
|
|
7395
|
+
const raw = await readFile(filePath, "utf8").catch(() => "");
|
|
7396
|
+
return raw.split("\n").map((line) => line.trim()).filter(
|
|
7397
|
+
(line) => line.endsWith(".md") && !line.includes("/") && !line.includes("\\") && line !== ".."
|
|
7398
|
+
);
|
|
7399
|
+
}
|
|
7400
|
+
async function projectCurrentExtensions(config2, state) {
|
|
7401
|
+
const agents = objectRecord(config2.agent);
|
|
7402
|
+
const commands = objectRecord(config2.command);
|
|
7403
|
+
for (const name of state.before.agents) if (!state.after.agents.has(name)) delete agents[name];
|
|
7404
|
+
for (const name of state.before.commands) if (!state.after.commands.has(name)) delete commands[name];
|
|
7405
|
+
for (const name of state.after.agents) {
|
|
7406
|
+
agents[name] = await parseMarkdownConfig(path.join(state.paths.agentsDir, `${name}.md`), "prompt");
|
|
7407
|
+
}
|
|
7408
|
+
for (const name of state.after.commands) {
|
|
7409
|
+
commands[name] = await parseMarkdownConfig(path.join(state.paths.commandsDir, `${name}.md`), "template");
|
|
7410
|
+
}
|
|
7411
|
+
config2.agent = agents;
|
|
7412
|
+
config2.command = commands;
|
|
7413
|
+
}
|
|
7414
|
+
async function parseMarkdownConfig(filePath, bodyField) {
|
|
7415
|
+
const raw = await readFile(filePath, "utf8");
|
|
7416
|
+
const match = /^---\r?\n([\s\S]+?)\r?\n---\r?\n?([\s\S]*)$/.exec(raw);
|
|
7417
|
+
if (!match) throw new Error(`A extens\xE3o Forge ${path.basename(filePath)} n\xE3o tem frontmatter v\xE1lido`);
|
|
7418
|
+
const data = (0, import_yaml.parse)(match[1]);
|
|
7419
|
+
if (!data || typeof data !== "object" || Array.isArray(data)) {
|
|
7420
|
+
throw new Error(`A extens\xE3o Forge ${path.basename(filePath)} n\xE3o tem frontmatter v\xE1lido`);
|
|
7421
|
+
}
|
|
7422
|
+
const config2 = { ...data, [bodyField]: match[2].trim() };
|
|
7423
|
+
if (bodyField === "prompt" && typeof config2.permission === "string" && ["allow", "ask", "deny"].includes(config2.permission)) {
|
|
7424
|
+
config2.permission = { "*": config2.permission };
|
|
7425
|
+
}
|
|
7426
|
+
return config2;
|
|
7427
|
+
}
|
|
7428
|
+
function objectRecord(value) {
|
|
7429
|
+
return value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
|
|
7430
|
+
}
|
|
7431
|
+
function stripMarkdownExtension(filename) {
|
|
7432
|
+
return filename.slice(0, -3);
|
|
7433
|
+
}
|
|
7434
|
+
|
|
7373
7435
|
// packages/shared/src/contracts/models.ts
|
|
7374
7436
|
var BUILT_IN_OPENROUTER_MODELS = [
|
|
7375
7437
|
{
|
|
@@ -7610,7 +7672,7 @@ var WORKER_FEEDBACK_MAX_MESSAGE_LENGTH = 24e3;
|
|
|
7610
7672
|
// packages/shared/src/contracts/settings.ts
|
|
7611
7673
|
var DOCUMENT_READER_AGENT = "document-reader";
|
|
7612
7674
|
var OPENROUTER_ALIAS_PROVIDER_NAME = "OpenRouter (via Forge)";
|
|
7613
|
-
var WORK_PACK_SYNC_PLUGIN_VERSION = "0.1.
|
|
7675
|
+
var WORK_PACK_SYNC_PLUGIN_VERSION = "0.1.49";
|
|
7614
7676
|
var WORK_PACK_SYNC_PLUGIN_PACKAGE = `minimal-forge-work-pack-sync@${WORK_PACK_SYNC_PLUGIN_VERSION}`;
|
|
7615
7677
|
var WORK_PACK_SYNC_PLUGIN_FILENAME = `minimal-forge-work-pack-sync-${WORK_PACK_SYNC_PLUGIN_VERSION}.tgz`;
|
|
7616
7678
|
var FIRECRAWL_KEYLESS_MCP_NAME = "firecrawl";
|
|
@@ -7843,6 +7905,13 @@ var UNKNOWN_RUNTIME = {
|
|
|
7843
7905
|
opencode: { status: "unknown" },
|
|
7844
7906
|
openwork: { status: "unknown" }
|
|
7845
7907
|
};
|
|
7908
|
+
function observeOpenCode2Runtime(app) {
|
|
7909
|
+
const version2 = runtimeVersion(app?.version);
|
|
7910
|
+
return {
|
|
7911
|
+
opencode: version2 ? { status: "known", version: version2, source: "engine-health" } : { status: "unknown" },
|
|
7912
|
+
openwork: { status: "unknown" }
|
|
7913
|
+
};
|
|
7914
|
+
}
|
|
7846
7915
|
async function observeRuntime(input) {
|
|
7847
7916
|
const engine = input?.serverUrl;
|
|
7848
7917
|
const engineHeaders = {};
|
|
@@ -7892,7 +7961,7 @@ async function probeHealth(url2, route, headers, healthyField, source) {
|
|
|
7892
7961
|
import { spawnSync as nodeSpawnSync } from "node:child_process";
|
|
7893
7962
|
import { randomUUID } from "node:crypto";
|
|
7894
7963
|
import { chmod, mkdir, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
7895
|
-
import
|
|
7964
|
+
import path2 from "node:path";
|
|
7896
7965
|
async function protectOwnerOnlyPath(filePath, kind, options = {}) {
|
|
7897
7966
|
const platform = options.platform ?? process.platform;
|
|
7898
7967
|
if (platform !== "win32") {
|
|
@@ -7934,7 +8003,7 @@ async function assertExistingDirectoryIsSafe(directory, options) {
|
|
|
7934
8003
|
}
|
|
7935
8004
|
}
|
|
7936
8005
|
async function prepareOwnerOnlyFileDestination(filePath, options = {}) {
|
|
7937
|
-
const directory =
|
|
8006
|
+
const directory = path2.dirname(filePath);
|
|
7938
8007
|
let existing;
|
|
7939
8008
|
try {
|
|
7940
8009
|
existing = await stat(directory);
|
|
@@ -7958,9 +8027,9 @@ async function prepareOwnerOnlyFileDestination(filePath, options = {}) {
|
|
|
7958
8027
|
else await assertExistingDirectoryIsSafe(directory, options);
|
|
7959
8028
|
}
|
|
7960
8029
|
async function writeOwnerOnlyTextAtomic(filePath, content, options = {}) {
|
|
7961
|
-
const directory =
|
|
8030
|
+
const directory = path2.dirname(filePath);
|
|
7962
8031
|
await prepareOwnerOnlyFileDestination(filePath, options);
|
|
7963
|
-
const temporary =
|
|
8032
|
+
const temporary = path2.join(directory, `.${path2.basename(filePath)}.${randomUUID()}.tmp`);
|
|
7964
8033
|
try {
|
|
7965
8034
|
await writeFile(temporary, content, { flag: "wx", mode: 384 });
|
|
7966
8035
|
await protectOwnerOnlyPath(temporary, "file", options);
|
|
@@ -8233,16 +8302,16 @@ async function readForgeCredentials() {
|
|
|
8233
8302
|
}
|
|
8234
8303
|
|
|
8235
8304
|
// packages/cli/src/retireDebugCapture.ts
|
|
8236
|
-
import { lstat, readFile, rename as rename2, writeFile as writeFile2 } from "node:fs/promises";
|
|
8305
|
+
import { lstat, readFile as readFile2, rename as rename2, writeFile as writeFile2 } from "node:fs/promises";
|
|
8237
8306
|
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
8238
|
-
import
|
|
8307
|
+
import path3 from "node:path";
|
|
8239
8308
|
var MANAGED_HEADER = "// Managed by Forge sync. Do not edit.";
|
|
8240
8309
|
var RETIRED_DEBUG_PLUGIN = `${MANAGED_HEADER}
|
|
8241
8310
|
// Detailed capture retired. Keep this module loadable for old OpenCode configs.
|
|
8242
8311
|
export const ForgeDebugTrace = async () => ({})
|
|
8243
8312
|
`;
|
|
8244
8313
|
async function retireDebugCapture(paths) {
|
|
8245
|
-
const configPath =
|
|
8314
|
+
const configPath = path3.join(paths.forgeDir, "debug-trace.json");
|
|
8246
8315
|
const raw = await readRegularFile(configPath);
|
|
8247
8316
|
if (raw !== void 0) {
|
|
8248
8317
|
const config2 = JSON.parse(raw);
|
|
@@ -8251,7 +8320,7 @@ async function retireDebugCapture(paths) {
|
|
|
8251
8320
|
`);
|
|
8252
8321
|
}
|
|
8253
8322
|
}
|
|
8254
|
-
const pluginPath =
|
|
8323
|
+
const pluginPath = path3.join(paths.pluginDir, "forge-debug-trace.js");
|
|
8255
8324
|
const plugin = await readRegularFile(pluginPath);
|
|
8256
8325
|
if (plugin?.startsWith(MANAGED_HEADER) && plugin !== RETIRED_DEBUG_PLUGIN) {
|
|
8257
8326
|
await replaceFile(pluginPath, RETIRED_DEBUG_PLUGIN);
|
|
@@ -8259,12 +8328,12 @@ async function retireDebugCapture(paths) {
|
|
|
8259
8328
|
}
|
|
8260
8329
|
async function readRegularFile(filename) {
|
|
8261
8330
|
try {
|
|
8262
|
-
const directory = await lstat(
|
|
8331
|
+
const directory = await lstat(path3.dirname(filename));
|
|
8263
8332
|
const info = await lstat(filename);
|
|
8264
8333
|
if (!directory.isDirectory() || !info.isFile() || info.isSymbolicLink()) {
|
|
8265
8334
|
throw new Error("Legacy debug capture path must be a regular file in a real directory");
|
|
8266
8335
|
}
|
|
8267
|
-
return await
|
|
8336
|
+
return await readFile2(filename, "utf8");
|
|
8268
8337
|
} catch (error45) {
|
|
8269
8338
|
if (error45.code === "ENOENT") return void 0;
|
|
8270
8339
|
throw error45;
|
|
@@ -8483,12 +8552,6 @@ function createReasoningLoopGuard(client, log = console.error, report = () => vo
|
|
|
8483
8552
|
};
|
|
8484
8553
|
}
|
|
8485
8554
|
|
|
8486
|
-
// packages/cli/src/workPackSyncPlugin.ts
|
|
8487
|
-
var import_yaml = __toESM(require_dist(), 1);
|
|
8488
|
-
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";
|
|
8489
|
-
import os5 from "node:os";
|
|
8490
|
-
import path12 from "node:path";
|
|
8491
|
-
|
|
8492
8555
|
// node_modules/@opencode-ai/plugin/node_modules/zod/v4/classic/external.js
|
|
8493
8556
|
var external_exports = {};
|
|
8494
8557
|
__export(external_exports, {
|
|
@@ -9220,10 +9283,10 @@ function mergeDefs(...defs) {
|
|
|
9220
9283
|
function cloneDef(schema) {
|
|
9221
9284
|
return mergeDefs(schema._zod.def);
|
|
9222
9285
|
}
|
|
9223
|
-
function getElementAtPath(obj,
|
|
9224
|
-
if (!
|
|
9286
|
+
function getElementAtPath(obj, path15) {
|
|
9287
|
+
if (!path15)
|
|
9225
9288
|
return obj;
|
|
9226
|
-
return
|
|
9289
|
+
return path15.reduce((acc, key) => acc?.[key], obj);
|
|
9227
9290
|
}
|
|
9228
9291
|
function promiseAllObject(promisesObj) {
|
|
9229
9292
|
const keys = Object.keys(promisesObj);
|
|
@@ -9584,11 +9647,11 @@ function aborted(x, startIndex = 0) {
|
|
|
9584
9647
|
}
|
|
9585
9648
|
return false;
|
|
9586
9649
|
}
|
|
9587
|
-
function prefixIssues(
|
|
9650
|
+
function prefixIssues(path15, issues) {
|
|
9588
9651
|
return issues.map((iss) => {
|
|
9589
9652
|
var _a;
|
|
9590
9653
|
(_a = iss).path ?? (_a.path = []);
|
|
9591
|
-
iss.path.unshift(
|
|
9654
|
+
iss.path.unshift(path15);
|
|
9592
9655
|
return iss;
|
|
9593
9656
|
});
|
|
9594
9657
|
}
|
|
@@ -9756,7 +9819,7 @@ function treeifyError(error45, _mapper) {
|
|
|
9756
9819
|
return issue2.message;
|
|
9757
9820
|
};
|
|
9758
9821
|
const result = { errors: [] };
|
|
9759
|
-
const processError = (error46,
|
|
9822
|
+
const processError = (error46, path15 = []) => {
|
|
9760
9823
|
var _a, _b;
|
|
9761
9824
|
for (const issue2 of error46.issues) {
|
|
9762
9825
|
if (issue2.code === "invalid_union" && issue2.errors.length) {
|
|
@@ -9766,7 +9829,7 @@ function treeifyError(error45, _mapper) {
|
|
|
9766
9829
|
} else if (issue2.code === "invalid_element") {
|
|
9767
9830
|
processError({ issues: issue2.issues }, issue2.path);
|
|
9768
9831
|
} else {
|
|
9769
|
-
const fullpath = [...
|
|
9832
|
+
const fullpath = [...path15, ...issue2.path];
|
|
9770
9833
|
if (fullpath.length === 0) {
|
|
9771
9834
|
result.errors.push(mapper(issue2));
|
|
9772
9835
|
continue;
|
|
@@ -9798,8 +9861,8 @@ function treeifyError(error45, _mapper) {
|
|
|
9798
9861
|
}
|
|
9799
9862
|
function toDotPath(_path) {
|
|
9800
9863
|
const segs = [];
|
|
9801
|
-
const
|
|
9802
|
-
for (const seg of
|
|
9864
|
+
const path15 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
|
|
9865
|
+
for (const seg of path15) {
|
|
9803
9866
|
if (typeof seg === "number")
|
|
9804
9867
|
segs.push(`[${seg}]`);
|
|
9805
9868
|
else if (typeof seg === "symbol")
|
|
@@ -20911,10 +20974,153 @@ function tool(input) {
|
|
|
20911
20974
|
}
|
|
20912
20975
|
tool.schema = external_exports;
|
|
20913
20976
|
|
|
20977
|
+
// packages/cli/src/opencode2Adapter.ts
|
|
20978
|
+
var z = tool.schema;
|
|
20979
|
+
function openCode2Tool(name, definition, directoryOf) {
|
|
20980
|
+
const schema = z.object(definition.args);
|
|
20981
|
+
return {
|
|
20982
|
+
name,
|
|
20983
|
+
description: definition.description,
|
|
20984
|
+
input: z.toJSONSchema(schema, { io: "input" }),
|
|
20985
|
+
options: { codemode: false },
|
|
20986
|
+
async execute(input, context) {
|
|
20987
|
+
const parsed = schema.safeParse(input);
|
|
20988
|
+
if (!parsed.success) {
|
|
20989
|
+
const issues = parsed.error.issues.map((issue2) => `- ${issue2.path.join(".") || "root"}: ${issue2.message}`);
|
|
20990
|
+
throw new Error(`Invalid arguments for tool "${name}":
|
|
20991
|
+
${issues.join("\n")}
|
|
20992
|
+
|
|
20993
|
+
Update the arguments and call the tool again.`);
|
|
20994
|
+
}
|
|
20995
|
+
const directory = await directoryOf(context.sessionID);
|
|
20996
|
+
const result = await definition.execute(parsed.data, { directory, abort: context.signal });
|
|
20997
|
+
return openCode2Result(result);
|
|
20998
|
+
}
|
|
20999
|
+
};
|
|
21000
|
+
}
|
|
21001
|
+
function sessionDirectoryResolver(ctx) {
|
|
21002
|
+
return async (sessionID) => {
|
|
21003
|
+
try {
|
|
21004
|
+
const directory = (await ctx.session.get({ sessionID })).location.directory;
|
|
21005
|
+
if (typeof directory === "string" && directory.length > 0) return directory;
|
|
21006
|
+
} catch {
|
|
21007
|
+
}
|
|
21008
|
+
return ctx.location.directory;
|
|
21009
|
+
};
|
|
21010
|
+
}
|
|
21011
|
+
function openCode2Result(result) {
|
|
21012
|
+
if (typeof result === "string") return { content: result };
|
|
21013
|
+
const files = (result.attachments ?? []).map((attachment) => ({
|
|
21014
|
+
type: "file",
|
|
21015
|
+
uri: attachment.url,
|
|
21016
|
+
mime: attachment.mime,
|
|
21017
|
+
...attachment.filename ? { name: attachment.filename } : {}
|
|
21018
|
+
}));
|
|
21019
|
+
return {
|
|
21020
|
+
content: files.length > 0 ? [{ type: "text", text: result.output }, ...files] : result.output,
|
|
21021
|
+
...result.metadata ? { metadata: result.metadata } : {}
|
|
21022
|
+
};
|
|
21023
|
+
}
|
|
21024
|
+
function completedSkillCall(event) {
|
|
21025
|
+
if (event.tool !== "skill" || event.status !== "completed") return void 0;
|
|
21026
|
+
const name = isRecord2(event.input) ? event.input.id : void 0;
|
|
21027
|
+
return { sessionID: event.sessionID, callID: event.id, name };
|
|
21028
|
+
}
|
|
21029
|
+
function guardEventsFor(event) {
|
|
21030
|
+
const data = isRecord2(event.data) ? event.data : void 0;
|
|
21031
|
+
const sessionID = data?.sessionID;
|
|
21032
|
+
if (!data || typeof sessionID !== "string") return [];
|
|
21033
|
+
const idle = { type: "session.idle", properties: { sessionID } };
|
|
21034
|
+
const error45 = { type: "session.error", properties: { sessionID } };
|
|
21035
|
+
switch (event.type) {
|
|
21036
|
+
case "session.reasoning.started":
|
|
21037
|
+
case "session.reasoning.delta":
|
|
21038
|
+
case "session.reasoning.ended": {
|
|
21039
|
+
const messageID = data.assistantMessageID;
|
|
21040
|
+
if (typeof messageID !== "string" || typeof data.ordinal !== "number") return [];
|
|
21041
|
+
const partID = `${messageID}:${data.ordinal}`;
|
|
21042
|
+
const announce = { type: "message.part.updated", properties: { part: { id: partID, sessionID, type: "reasoning", text: "" } } };
|
|
21043
|
+
if (event.type === "session.reasoning.started") return [announce];
|
|
21044
|
+
if (event.type === "session.reasoning.ended") {
|
|
21045
|
+
return typeof data.text === "string" ? [{ type: "message.part.updated", properties: { part: { id: partID, sessionID, type: "reasoning", text: data.text } } }] : [];
|
|
21046
|
+
}
|
|
21047
|
+
return typeof data.delta === "string" ? [announce, { type: "message.part.delta", properties: { sessionID, messageID, partID, field: "text", delta: data.delta } }] : [];
|
|
21048
|
+
}
|
|
21049
|
+
case "session.execution.succeeded":
|
|
21050
|
+
return [idle];
|
|
21051
|
+
case "session.execution.failed":
|
|
21052
|
+
case "session.execution.interrupted":
|
|
21053
|
+
return [error45, idle];
|
|
21054
|
+
case "session.deleted":
|
|
21055
|
+
return [{ type: "session.deleted", properties: { info: { id: sessionID } } }];
|
|
21056
|
+
default:
|
|
21057
|
+
return [];
|
|
21058
|
+
}
|
|
21059
|
+
}
|
|
21060
|
+
function openCode2GuardClient(ctx) {
|
|
21061
|
+
return {
|
|
21062
|
+
session: {
|
|
21063
|
+
abort: ({ path: path15 }) => ctx.session.interrupt({ sessionID: path15.id }),
|
|
21064
|
+
// The resume prompt runs with the session's current agent and model, so `body.agent` and `body.model` are not sent.
|
|
21065
|
+
promptAsync: ({ path: path15, body }) => ctx.session.prompt({ sessionID: path15.id, text: body.parts.map((part) => part.text).join("\n\n") })
|
|
21066
|
+
}
|
|
21067
|
+
};
|
|
21068
|
+
}
|
|
21069
|
+
var RESUBSCRIBE_DELAY_MS = 1e3;
|
|
21070
|
+
var MAX_CONSECUTIVE_STREAM_FAILURES = 5;
|
|
21071
|
+
function startReasoningLoopGuard(ctx, report, log = console.error) {
|
|
21072
|
+
const guard = createReasoningLoopGuard(openCode2GuardClient(ctx), log, report);
|
|
21073
|
+
const controller = new AbortController();
|
|
21074
|
+
const { signal } = controller;
|
|
21075
|
+
void (async () => {
|
|
21076
|
+
let failures = 0;
|
|
21077
|
+
while (!signal.aborted && failures < MAX_CONSECUTIVE_STREAM_FAILURES) {
|
|
21078
|
+
try {
|
|
21079
|
+
for await (const event of ctx.event.subscribe({ signal })) {
|
|
21080
|
+
failures = 0;
|
|
21081
|
+
try {
|
|
21082
|
+
for (const translated of guardEventsFor(event)) await guard({ event: translated });
|
|
21083
|
+
} catch (error45) {
|
|
21084
|
+
log(`[Forge reasoning guard] Event handling failed: ${error45 instanceof Error ? error45.message : String(error45)}`);
|
|
21085
|
+
}
|
|
21086
|
+
}
|
|
21087
|
+
return;
|
|
21088
|
+
} catch (error45) {
|
|
21089
|
+
if (signal.aborted) return;
|
|
21090
|
+
failures += 1;
|
|
21091
|
+
log(`[Forge reasoning guard] Event stream failed (${failures}/${MAX_CONSECUTIVE_STREAM_FAILURES}): ${error45 instanceof Error ? error45.message : String(error45)}`);
|
|
21092
|
+
await sleep(RESUBSCRIBE_DELAY_MS, signal);
|
|
21093
|
+
}
|
|
21094
|
+
}
|
|
21095
|
+
})();
|
|
21096
|
+
return () => controller.abort();
|
|
21097
|
+
}
|
|
21098
|
+
function sleep(ms2, signal) {
|
|
21099
|
+
return new Promise((resolve) => {
|
|
21100
|
+
if (signal.aborted) return resolve();
|
|
21101
|
+
const timer = setTimeout(done, ms2);
|
|
21102
|
+
timer.unref?.();
|
|
21103
|
+
signal.addEventListener("abort", done, { once: true });
|
|
21104
|
+
function done() {
|
|
21105
|
+
clearTimeout(timer);
|
|
21106
|
+
signal.removeEventListener("abort", done);
|
|
21107
|
+
resolve();
|
|
21108
|
+
}
|
|
21109
|
+
});
|
|
21110
|
+
}
|
|
21111
|
+
function isRecord2(value) {
|
|
21112
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
21113
|
+
}
|
|
21114
|
+
|
|
21115
|
+
// packages/cli/src/workPackSyncPlugin.ts
|
|
21116
|
+
import { link, mkdir as mkdir7, mkdtemp as mkdtemp2, readdir as readdir6, readFile as readFile13, realpath as realpath2, rename as rename8, rm as rm6, rmdir, stat as stat3, unlink, writeFile as writeFile8 } from "node:fs/promises";
|
|
21117
|
+
import os5 from "node:os";
|
|
21118
|
+
import path14 from "node:path";
|
|
21119
|
+
|
|
20914
21120
|
// packages/cli/src/credentials.ts
|
|
20915
|
-
import { chmod as chmod2, mkdir as mkdir2, readFile as
|
|
21121
|
+
import { chmod as chmod2, mkdir as mkdir2, readFile as readFile3, rename as rename3, rm as rm2, writeFile as writeFile3 } from "node:fs/promises";
|
|
20916
21122
|
async function readCredentials(paths) {
|
|
20917
|
-
const raw = await
|
|
21123
|
+
const raw = await readFile3(paths.credentialsPath, "utf8");
|
|
20918
21124
|
const parsed = JSON.parse(raw);
|
|
20919
21125
|
if (!parsed.forgeApiKey || !parsed.forgeBaseUrl) {
|
|
20920
21126
|
throw new Error(`Ficheiro de credenciais inv\xE1lido em ${paths.credentialsPath}`);
|
|
@@ -20924,10 +21130,10 @@ async function readCredentials(paths) {
|
|
|
20924
21130
|
|
|
20925
21131
|
// packages/cli/src/paths.ts
|
|
20926
21132
|
import os from "node:os";
|
|
20927
|
-
import
|
|
21133
|
+
import path4 from "node:path";
|
|
20928
21134
|
import { existsSync } from "node:fs";
|
|
20929
21135
|
function resolvePaths(home = os.homedir(), platform = process.platform, env = process.env, exists2 = existsSync) {
|
|
20930
|
-
const pathApi = platform === "win32" ?
|
|
21136
|
+
const pathApi = platform === "win32" ? path4.win32 : path4.posix;
|
|
20931
21137
|
const userHome = platform === "win32" ? env.USERPROFILE ?? home : home;
|
|
20932
21138
|
const forgeConfigRoot = env.XDG_CONFIG_HOME ?? pathApi.join(userHome, ".config");
|
|
20933
21139
|
const forgeDir = pathApi.join(forgeConfigRoot, "forge");
|
|
@@ -21014,13 +21220,13 @@ async function reportWorkPackObservations(credentials, kind, workPacks, runtime
|
|
|
21014
21220
|
// packages/cli/src/workPackIntegrity.ts
|
|
21015
21221
|
import { createHash as createHash2 } from "node:crypto";
|
|
21016
21222
|
import { constants } from "node:fs";
|
|
21017
|
-
import { lstat as lstat3, open, readdir as
|
|
21018
|
-
import
|
|
21223
|
+
import { lstat as lstat3, open, readdir as readdir3 } from "node:fs/promises";
|
|
21224
|
+
import path6 from "node:path";
|
|
21019
21225
|
|
|
21020
21226
|
// packages/cli/src/workPackLocalState.ts
|
|
21021
21227
|
import { createHash } from "node:crypto";
|
|
21022
|
-
import { lstat as lstat2, mkdir as mkdir3, readFile as
|
|
21023
|
-
import
|
|
21228
|
+
import { lstat as lstat2, mkdir as mkdir3, readFile as readFile4, readdir as readdir2, rename as rename4, writeFile as writeFile4 } from "node:fs/promises";
|
|
21229
|
+
import path5 from "node:path";
|
|
21024
21230
|
var WORK_PACK_LOCAL_STATE_FILENAME = ".forge-installed-state.json";
|
|
21025
21231
|
async function writeWorkPackInstalledState(input) {
|
|
21026
21232
|
const tree = await digestPackTree(input.packDir);
|
|
@@ -21032,7 +21238,7 @@ async function writeWorkPackInstalledState(input) {
|
|
|
21032
21238
|
agents: digestProjectionContents(input.agents),
|
|
21033
21239
|
commands: digestProjectionContents(input.commands)
|
|
21034
21240
|
};
|
|
21035
|
-
await writeJsonAtomic(
|
|
21241
|
+
await writeJsonAtomic(path5.join(input.packDir, WORK_PACK_LOCAL_STATE_FILENAME), state);
|
|
21036
21242
|
}
|
|
21037
21243
|
async function checkWorkPackInstalledState(input) {
|
|
21038
21244
|
const state = await readInstalledState(input.packDir);
|
|
@@ -21048,13 +21254,13 @@ async function checkWorkPackTreeState(packDir, allowAdditional = false) {
|
|
|
21048
21254
|
async function adoptWorkPackInstalledState(input) {
|
|
21049
21255
|
const state = await readInstalledState(input.expectedPackDir);
|
|
21050
21256
|
if (!state || !await matchesInstalledState(input, state)) return false;
|
|
21051
|
-
await writeJsonAtomic(
|
|
21257
|
+
await writeJsonAtomic(path5.join(input.packDir, WORK_PACK_LOCAL_STATE_FILENAME), state);
|
|
21052
21258
|
return checkWorkPackInstalledState(input).then((result) => result === "match");
|
|
21053
21259
|
}
|
|
21054
21260
|
async function readInstalledState(packDir) {
|
|
21055
|
-
const info = await lstat2(
|
|
21261
|
+
const info = await lstat2(path5.join(packDir, WORK_PACK_LOCAL_STATE_FILENAME)).catch(() => void 0);
|
|
21056
21262
|
if (!info?.isFile() || info.isSymbolicLink() || info.size > 1024 * 1024) return void 0;
|
|
21057
|
-
const raw = await
|
|
21263
|
+
const raw = await readFile4(path5.join(packDir, WORK_PACK_LOCAL_STATE_FILENAME), "utf8").catch(() => void 0);
|
|
21058
21264
|
if (!raw) return void 0;
|
|
21059
21265
|
try {
|
|
21060
21266
|
return parseWorkPackFileManifest(JSON.parse(raw));
|
|
@@ -21066,11 +21272,11 @@ async function digestPackTree(root) {
|
|
|
21066
21272
|
const files = [];
|
|
21067
21273
|
const directories = [];
|
|
21068
21274
|
const visit = async (directory, prefix) => {
|
|
21069
|
-
const entries = await
|
|
21275
|
+
const entries = await readdir2(directory, { withFileTypes: true });
|
|
21070
21276
|
for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
|
|
21071
21277
|
if (!prefix && entry.name === WORK_PACK_LOCAL_STATE_FILENAME) continue;
|
|
21072
21278
|
const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
|
|
21073
|
-
const absolute =
|
|
21279
|
+
const absolute = path5.join(directory, entry.name);
|
|
21074
21280
|
const info = await lstat2(absolute);
|
|
21075
21281
|
if (info.isSymbolicLink() || info.isFile() && info.nlink > 1) return false;
|
|
21076
21282
|
if (entry.isDirectory()) {
|
|
@@ -21079,7 +21285,7 @@ async function digestPackTree(root) {
|
|
|
21079
21285
|
continue;
|
|
21080
21286
|
}
|
|
21081
21287
|
if (!entry.isFile()) return false;
|
|
21082
|
-
files.push({ path: relative, sha256: digest(await
|
|
21288
|
+
files.push({ path: relative, sha256: digest(await readFile4(absolute)) });
|
|
21083
21289
|
}
|
|
21084
21290
|
return true;
|
|
21085
21291
|
};
|
|
@@ -21090,10 +21296,10 @@ function digestProjectionContents(files) {
|
|
|
21090
21296
|
}
|
|
21091
21297
|
async function projectionsMatch(directory, expected) {
|
|
21092
21298
|
for (const projection of expected) {
|
|
21093
|
-
const absolute =
|
|
21299
|
+
const absolute = path5.join(directory, projection.filename);
|
|
21094
21300
|
const info = await lstat2(absolute).catch(() => void 0);
|
|
21095
21301
|
if (!info?.isFile() || info.isSymbolicLink()) return false;
|
|
21096
|
-
const bytes = await
|
|
21302
|
+
const bytes = await readFile4(absolute).catch(() => void 0);
|
|
21097
21303
|
if (!bytes || digest(bytes) !== projection.sha256) return false;
|
|
21098
21304
|
}
|
|
21099
21305
|
return true;
|
|
@@ -21116,15 +21322,15 @@ function digest(bytes) {
|
|
|
21116
21322
|
return createHash("sha256").update(bytes).digest("hex");
|
|
21117
21323
|
}
|
|
21118
21324
|
async function writeJsonAtomic(filePath, value) {
|
|
21119
|
-
await mkdir3(
|
|
21120
|
-
const tempPath =
|
|
21325
|
+
await mkdir3(path5.dirname(filePath), { recursive: true });
|
|
21326
|
+
const tempPath = path5.join(path5.dirname(filePath), `.${path5.basename(filePath)}.${process.pid}.tmp`);
|
|
21121
21327
|
await writeFile4(tempPath, `${JSON.stringify(value, null, 2)}
|
|
21122
21328
|
`);
|
|
21123
21329
|
await rename4(tempPath, filePath);
|
|
21124
21330
|
}
|
|
21125
21331
|
async function adoptWorkPackFileManifest(input) {
|
|
21126
21332
|
if (!await matchesInstalledState({ ...input, allowAdditional: true }, input.expected)) return false;
|
|
21127
|
-
await writeJsonAtomic(
|
|
21333
|
+
await writeJsonAtomic(path5.join(input.packDir, WORK_PACK_LOCAL_STATE_FILENAME), input.expected);
|
|
21128
21334
|
return true;
|
|
21129
21335
|
}
|
|
21130
21336
|
function containsOriginalTree(actual, expected) {
|
|
@@ -21160,7 +21366,7 @@ function emptySummary() {
|
|
|
21160
21366
|
}
|
|
21161
21367
|
async function inspectWorkPackIntegrity(input) {
|
|
21162
21368
|
assertSlug(input.slug);
|
|
21163
|
-
const packDir =
|
|
21369
|
+
const packDir = path6.join(input.paths.skillsDir, input.slug);
|
|
21164
21370
|
const result = { slug: input.slug, summary: emptySummary(), differences: [], differencesTruncated: false };
|
|
21165
21371
|
const add = (kind, area, name) => {
|
|
21166
21372
|
if (result.summary[kind] === MAX_ENTRIES) result.summary.truncated = true;
|
|
@@ -21188,7 +21394,7 @@ async function inspectWorkPackIntegrity(input) {
|
|
|
21188
21394
|
if (result.summary.truncated) return;
|
|
21189
21395
|
let children;
|
|
21190
21396
|
try {
|
|
21191
|
-
children = await
|
|
21397
|
+
children = await readdir3(directory, { withFileTypes: true });
|
|
21192
21398
|
} catch {
|
|
21193
21399
|
add("unreadable", "pack", prefix || ".");
|
|
21194
21400
|
blocked.push(prefix);
|
|
@@ -21200,7 +21406,7 @@ async function inspectWorkPackIntegrity(input) {
|
|
|
21200
21406
|
return;
|
|
21201
21407
|
}
|
|
21202
21408
|
const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
|
|
21203
|
-
const absolute =
|
|
21409
|
+
const absolute = path6.join(directory, entry.name);
|
|
21204
21410
|
const info = await lstat3(absolute).catch(() => void 0);
|
|
21205
21411
|
if (!info) {
|
|
21206
21412
|
add("unreadable", "pack", relative);
|
|
@@ -21250,7 +21456,7 @@ async function inspectWorkPackIntegrity(input) {
|
|
|
21250
21456
|
const source = match ? `${match[1] ?? ""}${match[2]}.py` : void 0;
|
|
21251
21457
|
if (source && unchanged.has(source)) {
|
|
21252
21458
|
add("runtimeArtifacts", "pack", name);
|
|
21253
|
-
cacheDirectories.add(
|
|
21459
|
+
cacheDirectories.add(path6.posix.dirname(name));
|
|
21254
21460
|
} else add("additional", "pack", name);
|
|
21255
21461
|
}
|
|
21256
21462
|
for (const name of extraDirectories) if (!cacheDirectories.has(name)) add("additional", "pack", name);
|
|
@@ -21264,7 +21470,7 @@ async function inspectWorkPackIntegrity(input) {
|
|
|
21264
21470
|
continue;
|
|
21265
21471
|
}
|
|
21266
21472
|
for (const item of items) {
|
|
21267
|
-
const absolute =
|
|
21473
|
+
const absolute = path6.join(directory, item.filename);
|
|
21268
21474
|
try {
|
|
21269
21475
|
const info = await lstat3(absolute);
|
|
21270
21476
|
if (!info.isFile() || info.isSymbolicLink() || info.nlink > 1) add("unsafe", area, item.filename);
|
|
@@ -21358,9 +21564,9 @@ function assertSlug(slug) {
|
|
|
21358
21564
|
// packages/cli/src/sync.ts
|
|
21359
21565
|
import { createHash as createHash4 } from "node:crypto";
|
|
21360
21566
|
import { spawnSync } from "node:child_process";
|
|
21361
|
-
import { chmod as chmod4, cp, lstat as lstat5, mkdtemp, mkdir as mkdir5, readdir as
|
|
21567
|
+
import { chmod as chmod4, cp, lstat as lstat5, mkdtemp, mkdir as mkdir5, readdir as readdir4, readFile as readFile8, rm as rm4, rename as rename6, writeFile as writeFile6 } from "node:fs/promises";
|
|
21362
21568
|
import os4 from "node:os";
|
|
21363
|
-
import
|
|
21569
|
+
import path9 from "node:path";
|
|
21364
21570
|
|
|
21365
21571
|
// node_modules/tar/dist/esm/index.min.js
|
|
21366
21572
|
import Qr from "events";
|
|
@@ -21414,7 +21620,7 @@ var Ne = /* @__PURE__ */ Symbol("closed");
|
|
|
21414
21620
|
var Ns = /* @__PURE__ */ Symbol("read");
|
|
21415
21621
|
var Ae = /* @__PURE__ */ Symbol("flush");
|
|
21416
21622
|
var As = /* @__PURE__ */ Symbol("flushChunk");
|
|
21417
|
-
var
|
|
21623
|
+
var z2 = /* @__PURE__ */ Symbol("encoding");
|
|
21418
21624
|
var Mt = /* @__PURE__ */ Symbol("decoder");
|
|
21419
21625
|
var g = /* @__PURE__ */ Symbol("flowing");
|
|
21420
21626
|
var Qt = /* @__PURE__ */ Symbol("paused");
|
|
@@ -21474,7 +21680,7 @@ var A = class extends Di {
|
|
|
21474
21680
|
[N] = [];
|
|
21475
21681
|
[b] = [];
|
|
21476
21682
|
[L];
|
|
21477
|
-
[
|
|
21683
|
+
[z2];
|
|
21478
21684
|
[Z];
|
|
21479
21685
|
[Mt];
|
|
21480
21686
|
[Q] = false;
|
|
@@ -21493,7 +21699,7 @@ var A = class extends Di {
|
|
|
21493
21699
|
constructor(...t) {
|
|
21494
21700
|
let e = t[0] || {};
|
|
21495
21701
|
if (super(), e.objectMode && typeof e.encoding == "string") throw new TypeError("Encoding and objectMode may not be used together");
|
|
21496
|
-
Xr(e) ? (this[L] = true, this[
|
|
21702
|
+
Xr(e) ? (this[L] = true, this[z2] = null) : qr(e) ? (this[z2] = e.encoding, this[L] = false) : (this[L] = false, this[z2] = null), this[Z] = !!e.async, this[Mt] = this[z2] ? new Hr(this[z2]) : null, e && e.debugExposeBuffer === true && Object.defineProperty(this, "buffer", { get: () => this[b] }), e && e.debugExposePipes === true && Object.defineProperty(this, "pipes", { get: () => this[N] });
|
|
21497
21703
|
let { signal: i } = e;
|
|
21498
21704
|
i && (this[Jt] = i, i.aborted ? this[xi]() : i.addEventListener("abort", () => this[xi]()));
|
|
21499
21705
|
}
|
|
@@ -21501,7 +21707,7 @@ var A = class extends Di {
|
|
|
21501
21707
|
return this[_];
|
|
21502
21708
|
}
|
|
21503
21709
|
get encoding() {
|
|
21504
|
-
return this[
|
|
21710
|
+
return this[z2];
|
|
21505
21711
|
}
|
|
21506
21712
|
set encoding(t) {
|
|
21507
21713
|
throw new Error("Encoding must be set at instantiation time");
|
|
@@ -21540,12 +21746,12 @@ var A = class extends Di {
|
|
|
21540
21746
|
else if (Vr(t)) t = Buffer.from(t);
|
|
21541
21747
|
else if (typeof t != "string") throw new Error("Non-contiguous data written to non-objectMode stream");
|
|
21542
21748
|
}
|
|
21543
|
-
return this[L] ? (this[g] && this[_] !== 0 && this[Ae](true), this[g] ? this.emit("data", t) : this[bi](t), this[_] !== 0 && this.emit("readable"), i && r(i), this[g]) : t.length ? (typeof t == "string" && !(e === this[
|
|
21749
|
+
return this[L] ? (this[g] && this[_] !== 0 && this[Ae](true), this[g] ? this.emit("data", t) : this[bi](t), this[_] !== 0 && this.emit("readable"), i && r(i), this[g]) : t.length ? (typeof t == "string" && !(e === this[z2] && !this[Mt]?.lastNeed) && (t = Buffer.from(t, e)), Buffer.isBuffer(t) && this[z2] && (t = this[Mt].write(t)), this[g] && this[_] !== 0 && this[Ae](true), this[g] ? this.emit("data", t) : this[bi](t), this[_] !== 0 && this.emit("readable"), i && r(i), this[g]) : (this[_] !== 0 && this.emit("readable"), i && r(i), this[g]);
|
|
21544
21750
|
}
|
|
21545
21751
|
read(t) {
|
|
21546
21752
|
if (this[S]) return null;
|
|
21547
21753
|
if (this[C] = false, this[_] === 0 || t === 0 || t && t > this[_]) return this[J](), null;
|
|
21548
|
-
this[L] && (t = null), this[b].length > 1 && !this[L] && (this[b] = [this[
|
|
21754
|
+
this[L] && (t = null), this[b].length > 1 && !this[L] && (this[b] = [this[z2] ? this[b].join("") : Buffer.concat(this[b], this[_])]);
|
|
21549
21755
|
let e = this[Ns](t || null, this[b][0]);
|
|
21550
21756
|
return this[J](), e;
|
|
21551
21757
|
}
|
|
@@ -21688,7 +21894,7 @@ var A = class extends Di {
|
|
|
21688
21894
|
async concat() {
|
|
21689
21895
|
if (this[L]) throw new Error("cannot concat in objectMode");
|
|
21690
21896
|
let t = await this.collect();
|
|
21691
|
-
return this[
|
|
21897
|
+
return this[z2] ? t.join("") : Buffer.concat(t, t.dataLength);
|
|
21692
21898
|
}
|
|
21693
21899
|
async promise() {
|
|
21694
21900
|
return new Promise((t, e) => {
|
|
@@ -24341,8 +24547,8 @@ function renderTuiConfig(manifest) {
|
|
|
24341
24547
|
|
|
24342
24548
|
// packages/cli/src/coreSyncTransaction.ts
|
|
24343
24549
|
import { createHash as createHash3, randomUUID as randomUUID3 } from "node:crypto";
|
|
24344
|
-
import { chmod as chmod3, lstat as lstat4, mkdir as mkdir4, readFile as
|
|
24345
|
-
import
|
|
24550
|
+
import { chmod as chmod3, lstat as lstat4, mkdir as mkdir4, readFile as readFile5, rename as rename5, rm as rm3, writeFile as writeFile5 } from "node:fs/promises";
|
|
24551
|
+
import path7 from "node:path";
|
|
24346
24552
|
var CORE_RUNTIME_MANIFEST_VERSION = 1;
|
|
24347
24553
|
var CoreSyncUncertainError = class extends Error {
|
|
24348
24554
|
constructor(message, paths) {
|
|
@@ -24351,11 +24557,11 @@ var CoreSyncUncertainError = class extends Error {
|
|
|
24351
24557
|
}
|
|
24352
24558
|
paths;
|
|
24353
24559
|
};
|
|
24354
|
-
var defaultFs = { chmod: chmod3, lstat: lstat4, mkdir: mkdir4, readFile:
|
|
24560
|
+
var defaultFs = { chmod: chmod3, lstat: lstat4, mkdir: mkdir4, readFile: readFile5, rename: rename5, rm: rm3, writeFile: writeFile5 };
|
|
24355
24561
|
function coreRuntimeManifestDigest(files) {
|
|
24356
24562
|
const canonical = [...files].sort((a, b2) => a.id.localeCompare(b2.id)).map((file2) => ({
|
|
24357
24563
|
id: file2.id,
|
|
24358
|
-
path:
|
|
24564
|
+
path: path7.resolve(file2.path),
|
|
24359
24565
|
exists: file2.bytes !== null,
|
|
24360
24566
|
digest: file2.bytes === null ? void 0 : sha256(file2.bytes),
|
|
24361
24567
|
mode: file2.mode,
|
|
@@ -24372,8 +24578,8 @@ function validateCoreRuntimeManifest(manifest) {
|
|
|
24372
24578
|
const targets = /* @__PURE__ */ new Set();
|
|
24373
24579
|
for (const file2 of manifest.files) {
|
|
24374
24580
|
if (!file2.id || ids.has(file2.id)) throw new Error(`Duplicate core runtime file id: ${file2.id}`);
|
|
24375
|
-
const target =
|
|
24376
|
-
if (!
|
|
24581
|
+
const target = path7.resolve(file2.path);
|
|
24582
|
+
if (!path7.isAbsolute(file2.path) || targets.has(target)) throw new Error(`Invalid or duplicate core runtime target: ${file2.path}`);
|
|
24377
24583
|
if (file2.mode !== void 0 && (!Number.isInteger(file2.mode) || file2.mode < 0 || file2.mode > 4095)) throw new Error(`Invalid mode for ${file2.id}`);
|
|
24378
24584
|
if (file2.ownerOnly !== void 0 && typeof file2.ownerOnly !== "boolean") throw new Error(`Invalid owner-only flag for ${file2.id}`);
|
|
24379
24585
|
ids.add(file2.id);
|
|
@@ -24391,9 +24597,9 @@ async function applyCoreSyncTransaction(options) {
|
|
|
24391
24597
|
const files = [];
|
|
24392
24598
|
try {
|
|
24393
24599
|
for (const desired of options.manifest.files) {
|
|
24394
|
-
const target =
|
|
24600
|
+
const target = path7.resolve(desired.path);
|
|
24395
24601
|
if (desired.ownerOnly && desired.bytes !== null && fs2 === defaultFs) await prepareOwnerOnlyFileDestination(target);
|
|
24396
|
-
else await fs2.mkdir(
|
|
24602
|
+
else await fs2.mkdir(path7.dirname(target), { recursive: true });
|
|
24397
24603
|
const original = await capture(target, fs2);
|
|
24398
24604
|
const suffix = `.forge-core-${transactionId}`;
|
|
24399
24605
|
const backup = original.exists ? `${target}${suffix}.backup` : void 0;
|
|
@@ -24490,7 +24696,7 @@ async function writeExact(target, bytes, mode, fs2, ownerOnly = false) {
|
|
|
24490
24696
|
if (ownerOnly && fs2 === defaultFs) await protectOwnerOnlyPath(target, "file");
|
|
24491
24697
|
}
|
|
24492
24698
|
async function writeJournal(target, journal, fs2) {
|
|
24493
|
-
await fs2.mkdir(
|
|
24699
|
+
await fs2.mkdir(path7.dirname(target), { recursive: true });
|
|
24494
24700
|
const temporary = `${target}.next`;
|
|
24495
24701
|
await fs2.rm(temporary, { force: true });
|
|
24496
24702
|
await fs2.writeFile(temporary, `${JSON.stringify(journal, null, 2)}
|
|
@@ -24518,7 +24724,7 @@ function sha256(value) {
|
|
|
24518
24724
|
return createHash3("sha256").update(value).digest("hex");
|
|
24519
24725
|
}
|
|
24520
24726
|
function validJournal(value) {
|
|
24521
|
-
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" &&
|
|
24727
|
+
return value?.schemaVersion === 1 && typeof value.transactionId === "string" && value.manifest?.version === 1 && typeof value.manifest.id === "string" && Array.isArray(value.files) && value.files.every((file2) => typeof file2.id === "string" && path7.isAbsolute(file2.target) && typeof file2.original?.exists === "boolean" && typeof file2.desired?.exists === "boolean" && (file2.ownerOnly === void 0 || typeof file2.ownerOnly === "boolean"));
|
|
24522
24728
|
}
|
|
24523
24729
|
|
|
24524
24730
|
// packages/cli/src/jsonc.ts
|
|
@@ -24597,7 +24803,7 @@ function stripTrailingCommas(input) {
|
|
|
24597
24803
|
}
|
|
24598
24804
|
|
|
24599
24805
|
// packages/cli/src/remoteConfig.ts
|
|
24600
|
-
import { readFile as
|
|
24806
|
+
import { readFile as readFile6 } from "node:fs/promises";
|
|
24601
24807
|
var WELLKNOWN_ENV_KEY = "FORGE_API_KEY";
|
|
24602
24808
|
async function removeWellKnownAuth(paths, credentials, previous) {
|
|
24603
24809
|
const content = await prepareWellKnownAuthRemoval(paths, credentials, previous);
|
|
@@ -24611,7 +24817,7 @@ async function prepareWellKnownAuthRemoval(paths, credentials, previous) {
|
|
|
24611
24817
|
for (const url2 of owned.flatMap((entry) => [entry.forgeBaseUrl, ...entry.forgeOwnedWellKnownUrls ?? []])) {
|
|
24612
24818
|
const key = normalizeBaseUrl(url2);
|
|
24613
24819
|
const entry = auth[key];
|
|
24614
|
-
if (!
|
|
24820
|
+
if (!isRecord3(entry) || entry.type !== "wellknown" || entry.key !== WELLKNOWN_ENV_KEY || typeof entry.token !== "string" || !entry.token.startsWith("forge_")) continue;
|
|
24615
24821
|
if (!ownedKeys.has(entry.token)) {
|
|
24616
24822
|
throw new Error("A autoriza\xE7\xE3o Forge foi alterada; preserve os ficheiros e pe\xE7a uma repara\xE7\xE3o acompanhada.");
|
|
24617
24823
|
}
|
|
@@ -24627,21 +24833,21 @@ function stripForgeManagedConfig(config2) {
|
|
|
24627
24833
|
delete next.small_model;
|
|
24628
24834
|
delete next.share;
|
|
24629
24835
|
delete next.autoupdate;
|
|
24630
|
-
const experimental =
|
|
24836
|
+
const experimental = isRecord3(next.experimental) ? { ...next.experimental } : void 0;
|
|
24631
24837
|
if (experimental) {
|
|
24632
24838
|
delete experimental.clickableFileReferences;
|
|
24633
24839
|
if (Object.keys(experimental).length > 0) next.experimental = experimental;
|
|
24634
24840
|
else delete next.experimental;
|
|
24635
24841
|
}
|
|
24636
|
-
const provider =
|
|
24842
|
+
const provider = isRecord3(next.provider) ? { ...next.provider } : void 0;
|
|
24637
24843
|
if (provider) {
|
|
24638
24844
|
delete provider.forge;
|
|
24639
24845
|
const openrouter = provider.openrouter;
|
|
24640
|
-
if (
|
|
24846
|
+
if (isRecord3(openrouter) && openrouter.name === OPENROUTER_ALIAS_PROVIDER_NAME) delete provider.openrouter;
|
|
24641
24847
|
if (Object.keys(provider).length > 0) next.provider = provider;
|
|
24642
24848
|
else delete next.provider;
|
|
24643
24849
|
}
|
|
24644
|
-
const agent =
|
|
24850
|
+
const agent = isRecord3(next.agent) ? { ...next.agent } : void 0;
|
|
24645
24851
|
if (agent) {
|
|
24646
24852
|
delete agent["document-reader"];
|
|
24647
24853
|
if (Object.keys(agent).length > 0) next.agent = agent;
|
|
@@ -24655,35 +24861,35 @@ function normalizeBaseUrl(value) {
|
|
|
24655
24861
|
async function readAuthJson(paths) {
|
|
24656
24862
|
let raw;
|
|
24657
24863
|
try {
|
|
24658
|
-
raw = await
|
|
24864
|
+
raw = await readFile6(paths.opencodeAuthPath, "utf8");
|
|
24659
24865
|
} catch (error45) {
|
|
24660
24866
|
if (error45.code === "ENOENT") return {};
|
|
24661
24867
|
throw error45;
|
|
24662
24868
|
}
|
|
24663
24869
|
const parsed = JSON.parse(raw.startsWith("\uFEFF") ? raw.slice(1) : raw);
|
|
24664
|
-
if (!
|
|
24870
|
+
if (!isRecord3(parsed)) throw new Error("A autentica\xE7\xE3o do OpenCode n\xE3o \xE9 um objeto JSON v\xE1lido");
|
|
24665
24871
|
return parsed;
|
|
24666
24872
|
}
|
|
24667
|
-
function
|
|
24873
|
+
function isRecord3(value) {
|
|
24668
24874
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
24669
24875
|
}
|
|
24670
24876
|
|
|
24671
24877
|
// packages/cli/src/localConfigRecovery.ts
|
|
24672
|
-
import { readFile as
|
|
24673
|
-
import
|
|
24878
|
+
import { readFile as readFile7 } from "node:fs/promises";
|
|
24879
|
+
import path8 from "node:path";
|
|
24674
24880
|
var LocalConfigRecoveryError = class extends Error {
|
|
24675
24881
|
};
|
|
24676
24882
|
var LAST_GOOD_FILENAME = "last-good-opencode.json";
|
|
24677
24883
|
function lastGoodLocalConfigFile(paths, credentials, content) {
|
|
24678
24884
|
assertForgeConfig(content, credentials);
|
|
24679
|
-
return { id: "last-good-config", path:
|
|
24885
|
+
return { id: "last-good-config", path: path8.join(paths.forgeDir, LAST_GOOD_FILENAME), bytes: Buffer.from(content), mode: 384, ownerOnly: true };
|
|
24680
24886
|
}
|
|
24681
24887
|
async function retiredLastGoodLocalConfigFile(paths) {
|
|
24682
|
-
const filePath =
|
|
24888
|
+
const filePath = path8.join(paths.forgeDir, LAST_GOOD_FILENAME);
|
|
24683
24889
|
return await readOptional(filePath) === void 0 ? void 0 : { id: "last-good-config", path: filePath, bytes: null };
|
|
24684
24890
|
}
|
|
24685
24891
|
async function inspectLocalConfigRecovery(paths, credentials) {
|
|
24686
|
-
const snapshot = await readOptional(
|
|
24892
|
+
const snapshot = await readOptional(path8.join(paths.forgeDir, LAST_GOOD_FILENAME));
|
|
24687
24893
|
const current = await readOptional(paths.opencodeConfigPath);
|
|
24688
24894
|
return {
|
|
24689
24895
|
snapshot: snapshot === void 0 ? "missing" : isForgeConfig(snapshot, credentials) ? "available" : "invalid",
|
|
@@ -24698,14 +24904,14 @@ function assertForgeConfig(content, credentials) {
|
|
|
24698
24904
|
function isForgeConfig(content, credentials) {
|
|
24699
24905
|
try {
|
|
24700
24906
|
const config2 = parseJsonc(content);
|
|
24701
|
-
if (!
|
|
24907
|
+
if (!isRecord4(config2) || !isRecord4(config2.provider) || !isRecord4(config2.provider.forge)) return false;
|
|
24702
24908
|
assertForgeVisible(config2);
|
|
24703
24909
|
const forge = config2.provider.forge;
|
|
24704
|
-
if (!
|
|
24910
|
+
if (!isRecord4(forge.options) || forge.options.apiKey !== credentials.forgeApiKey || typeof forge.options.baseURL !== "string" || !forge.options.baseURL.endsWith("/v1") || !isRecord4(forge.models) || Object.keys(forge.models).length === 0) return false;
|
|
24705
24911
|
if (typeof config2.model !== "string" || !config2.model.startsWith("forge/") || typeof config2.small_model !== "string" || !config2.small_model.startsWith("forge/")) return false;
|
|
24706
24912
|
const plugins = forgePluginEntries(config2);
|
|
24707
24913
|
return plugins.length === 1 && plugins.every(
|
|
24708
|
-
(entry) => Array.isArray(entry) && typeof entry[0] === "string" && /^minimal-forge-work-pack-sync@/.test(entry[0]) &&
|
|
24914
|
+
(entry) => Array.isArray(entry) && typeof entry[0] === "string" && /^minimal-forge-work-pack-sync@/.test(entry[0]) && isRecord4(entry[1]) && entry[1].forgeBaseUrl === credentials.forgeBaseUrl.replace(/\/+$/, "") && entry[1].localConfig === true
|
|
24709
24915
|
);
|
|
24710
24916
|
} catch {
|
|
24711
24917
|
return false;
|
|
@@ -24714,8 +24920,8 @@ function isForgeConfig(content, credentials) {
|
|
|
24714
24920
|
function sameSavedForgeFields(current, snapshot) {
|
|
24715
24921
|
const active = parseJsonc(current);
|
|
24716
24922
|
const saved = parseJsonc(snapshot);
|
|
24717
|
-
const activeProvider =
|
|
24718
|
-
const savedProvider =
|
|
24923
|
+
const activeProvider = isRecord4(active.provider) ? active.provider.forge : void 0;
|
|
24924
|
+
const savedProvider = isRecord4(saved.provider) ? saved.provider.forge : void 0;
|
|
24719
24925
|
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));
|
|
24720
24926
|
}
|
|
24721
24927
|
function forgePluginEntries(config2) {
|
|
@@ -24726,17 +24932,17 @@ function forgePluginEntries(config2) {
|
|
|
24726
24932
|
}
|
|
24727
24933
|
async function readOptional(filePath) {
|
|
24728
24934
|
try {
|
|
24729
|
-
return await
|
|
24935
|
+
return await readFile7(filePath, "utf8");
|
|
24730
24936
|
} catch (error45) {
|
|
24731
24937
|
if (error45.code === "ENOENT") return void 0;
|
|
24732
24938
|
throw error45;
|
|
24733
24939
|
}
|
|
24734
24940
|
}
|
|
24735
|
-
function
|
|
24941
|
+
function isRecord4(value) {
|
|
24736
24942
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
24737
24943
|
}
|
|
24738
24944
|
function assertForgeVisible(config2) {
|
|
24739
|
-
if (!
|
|
24945
|
+
if (!isRecord4(config2)) return;
|
|
24740
24946
|
if (Array.isArray(config2.disabled_providers) && config2.disabled_providers.includes("forge") || Array.isArray(config2.enabled_providers) && !config2.enabled_providers.includes("forge")) {
|
|
24741
24947
|
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.");
|
|
24742
24948
|
}
|
|
@@ -25002,7 +25208,7 @@ function validCoreManifest(value) {
|
|
|
25002
25208
|
return modelIds.every((id) => typeof id === "string" && id.length > 0) && modelIds.includes(config2.model) && modelIds.includes(config2.small_model);
|
|
25003
25209
|
}
|
|
25004
25210
|
async function applyManifest(paths, credentials, manifest, options = {}) {
|
|
25005
|
-
const journalPath =
|
|
25211
|
+
const journalPath = path9.join(paths.forgeDir, "core-sync-journal.json");
|
|
25006
25212
|
const recovery = await recoverCoreSyncTransaction({ journalPath });
|
|
25007
25213
|
await retireDebugCapture(paths);
|
|
25008
25214
|
if (recovery.status === "uncertain") {
|
|
@@ -25015,11 +25221,11 @@ async function applyManifest(paths, credentials, manifest, options = {}) {
|
|
|
25015
25221
|
});
|
|
25016
25222
|
}
|
|
25017
25223
|
async function applyCoreManifest(paths, credentials, manifest, options) {
|
|
25018
|
-
const attachmentPluginPath =
|
|
25019
|
-
const evidencePluginPath =
|
|
25020
|
-
const debugTracePluginPath =
|
|
25021
|
-
const legacyAttachmentPluginPath =
|
|
25022
|
-
const debugTraceConfigPath =
|
|
25224
|
+
const attachmentPluginPath = path9.join(paths.pluginDir, FORGE_PLUGIN_FILENAME);
|
|
25225
|
+
const evidencePluginPath = path9.join(paths.pluginDir, FORGE_EVIDENCE_PLUGIN_FILENAME);
|
|
25226
|
+
const debugTracePluginPath = path9.join(paths.pluginDir, FORGE_DEBUG_TRACE_PLUGIN_FILENAME);
|
|
25227
|
+
const legacyAttachmentPluginPath = path9.join(paths.opencodeDir, "plugin", FORGE_PLUGIN_FILENAME);
|
|
25228
|
+
const debugTraceConfigPath = path9.join(paths.forgeDir, FORGE_DEBUG_TRACE_CONFIG_FILENAME);
|
|
25023
25229
|
const rules = attachmentBridgeRules(manifest.config.models);
|
|
25024
25230
|
let bridgeEnabled = Boolean(manifest.config.documentReaderModel) && Object.keys(rules).length > 0;
|
|
25025
25231
|
const existingConfig = await readJsoncObject(paths.opencodeConfigPath);
|
|
@@ -25098,7 +25304,7 @@ async function applyCoreManifest(paths, credentials, manifest, options) {
|
|
|
25098
25304
|
digest: digest2,
|
|
25099
25305
|
files
|
|
25100
25306
|
},
|
|
25101
|
-
journalPath:
|
|
25307
|
+
journalPath: path9.join(paths.forgeDir, "core-sync-journal.json"),
|
|
25102
25308
|
hooks: options.coreTransactionHooks
|
|
25103
25309
|
});
|
|
25104
25310
|
await removeLegacyDebugTraceRuntime(paths);
|
|
@@ -25110,9 +25316,9 @@ async function applyWorkPackManifest(paths, credentials, manifest, options) {
|
|
|
25110
25316
|
const recovery = await recoverInterruptedWorkPackInstalls(paths, options.cleanupWorkPackBackup, options.workPackProjectionBoundary);
|
|
25111
25317
|
const managed = await Promise.all((await managedWorkPackSlugs(paths.skillsDir)).map(async (slug) => ({
|
|
25112
25318
|
slug,
|
|
25113
|
-
version: (await
|
|
25114
|
-
agents: await readAgentRecord(
|
|
25115
|
-
commands: await readCommandRecord(
|
|
25319
|
+
version: (await readFile8(path9.join(paths.skillsDir, slug, ".forge-version"), "utf8")).trim(),
|
|
25320
|
+
agents: await readAgentRecord(path9.join(paths.skillsDir, slug)),
|
|
25321
|
+
commands: await readCommandRecord(path9.join(paths.skillsDir, slug))
|
|
25116
25322
|
})));
|
|
25117
25323
|
const desired = manifest.skills.map((skill) => ({
|
|
25118
25324
|
slug: skill.slug,
|
|
@@ -25136,7 +25342,7 @@ async function applyWorkPackManifest(paths, credentials, manifest, options) {
|
|
|
25136
25342
|
options
|
|
25137
25343
|
)),
|
|
25138
25344
|
recoveryFailures: recovery.failures,
|
|
25139
|
-
writeAtomicReceipt: (receipt) => writeJsonAtomic2(
|
|
25345
|
+
writeAtomicReceipt: (receipt) => writeJsonAtomic2(path9.join(paths.forgeDir, "work-pack-sync-receipt.json"), receipt)
|
|
25140
25346
|
});
|
|
25141
25347
|
const installed = workPacks.outcomes.filter((outcome) => outcome.status === "installed").map((outcome) => `${outcome.slug}@${outcome.version}`);
|
|
25142
25348
|
const removed = workPacks.outcomes.filter((outcome) => outcome.status === "removed").map((outcome) => outcome.slug);
|
|
@@ -25147,7 +25353,7 @@ async function applyWorkPackManifest(paths, credentials, manifest, options) {
|
|
|
25147
25353
|
async function collectWorkPackObservations(paths, reconciliation) {
|
|
25148
25354
|
const installedVersions = /* @__PURE__ */ new Map();
|
|
25149
25355
|
for (const slug of await managedWorkPackSlugs(paths.skillsDir)) {
|
|
25150
|
-
const version2 = (await
|
|
25356
|
+
const version2 = (await readFile8(path9.join(paths.skillsDir, slug, ".forge-version"), "utf8")).trim();
|
|
25151
25357
|
if (version2) installedVersions.set(slug, version2);
|
|
25152
25358
|
}
|
|
25153
25359
|
const observations = new Map(
|
|
@@ -25178,7 +25384,7 @@ async function enrichIntegrityFailure(paths, operation, result) {
|
|
|
25178
25384
|
}
|
|
25179
25385
|
}
|
|
25180
25386
|
async function operateWorkPack(paths, credentials, skillBySlug, approvedModelIds, cleanupPendingSlugs, recoveryFailures, operation, options) {
|
|
25181
|
-
const target =
|
|
25387
|
+
const target = path9.join(paths.skillsDir, operation.pack.slug);
|
|
25182
25388
|
const recoveryFailure = recoveryFailures.get(operation.pack.slug);
|
|
25183
25389
|
if (recoveryFailure) return { status: "failed", restoration: "exact", code: recoveryFailure };
|
|
25184
25390
|
let ownership;
|
|
@@ -25217,7 +25423,7 @@ async function operateWorkPack(paths, credentials, skillBySlug, approvedModelIds
|
|
|
25217
25423
|
let previousManagedPaths;
|
|
25218
25424
|
let archive;
|
|
25219
25425
|
try {
|
|
25220
|
-
const currentVersion = await
|
|
25426
|
+
const currentVersion = await readFile8(path9.join(target, ".forge-version"), "utf8").catch(() => "");
|
|
25221
25427
|
const sameVersion = currentVersion.trim() === skill.version;
|
|
25222
25428
|
if (ownership === "managed") {
|
|
25223
25429
|
let localState = await checkWorkPackInstalledState({
|
|
@@ -25328,8 +25534,8 @@ function jsonBytes(value) {
|
|
|
25328
25534
|
`);
|
|
25329
25535
|
}
|
|
25330
25536
|
async function removeLegacyDebugTraceRuntime(paths) {
|
|
25331
|
-
const launchAgentPath =
|
|
25332
|
-
const launchAgent = await
|
|
25537
|
+
const launchAgentPath = path9.join(os4.homedir(), "Library", "LaunchAgents", "com.minimal-forge.debug-trace.plist");
|
|
25538
|
+
const launchAgent = await readFile8(launchAgentPath, "utf8").catch((error45) => {
|
|
25333
25539
|
if (error45.code === "ENOENT") return void 0;
|
|
25334
25540
|
throw error45;
|
|
25335
25541
|
});
|
|
@@ -25351,13 +25557,13 @@ async function removeLegacyDebugTraceRuntime(paths) {
|
|
|
25351
25557
|
"debug-trace-service.err.log",
|
|
25352
25558
|
"opencode-debug-trace"
|
|
25353
25559
|
]) {
|
|
25354
|
-
await rm4(
|
|
25560
|
+
await rm4(path9.join(paths.forgeDir, filename), { force: true });
|
|
25355
25561
|
}
|
|
25356
|
-
await rm4(
|
|
25357
|
-
await rm4(
|
|
25562
|
+
await rm4(path9.join(paths.forgeDir, "claude-tap-traces"), { recursive: true, force: true });
|
|
25563
|
+
await rm4(path9.join(paths.forgeDir, "verified-claude-tap"), { recursive: true, force: true });
|
|
25358
25564
|
}
|
|
25359
25565
|
async function isManagedDebugTraceConfig(configPath) {
|
|
25360
|
-
const raw = await
|
|
25566
|
+
const raw = await readFile8(configPath, "utf8").catch((error45) => {
|
|
25361
25567
|
if (error45.code === "ENOENT") return void 0;
|
|
25362
25568
|
throw error45;
|
|
25363
25569
|
});
|
|
@@ -25421,7 +25627,7 @@ var WorkPackLocalEditsError = class extends Error {
|
|
|
25421
25627
|
async function assertWorkPackUnchangedAtBoundary(paths, target, snapshot) {
|
|
25422
25628
|
const ownership = await workPackOwnership(target);
|
|
25423
25629
|
if (ownership === "absent") return;
|
|
25424
|
-
if (ownership === "foreign") throw foreignWorkPackError(
|
|
25630
|
+
if (ownership === "foreign") throw foreignWorkPackError(path9.basename(target));
|
|
25425
25631
|
const localState = await checkWorkPackInstalledState({
|
|
25426
25632
|
packDir: target,
|
|
25427
25633
|
agentsDir: paths.agentsDir,
|
|
@@ -25463,22 +25669,22 @@ async function preserveWorkPackExtras(target, nextPath, actual) {
|
|
|
25463
25669
|
`A nova vers\xE3o usa o caminho adicional "${name}". O pacote anterior e os ficheiros locais foram preservados.`
|
|
25464
25670
|
);
|
|
25465
25671
|
}
|
|
25466
|
-
for (const directory of directories) await mkdir5(
|
|
25672
|
+
for (const directory of directories) await mkdir5(path9.join(nextPath, directory), { recursive: true });
|
|
25467
25673
|
for (const file2 of extras) {
|
|
25468
|
-
const destination =
|
|
25469
|
-
await mkdir5(
|
|
25470
|
-
await cp(
|
|
25471
|
-
if (createHash4("sha256").update(await
|
|
25674
|
+
const destination = path9.join(nextPath, file2.path);
|
|
25675
|
+
await mkdir5(path9.dirname(destination), { recursive: true });
|
|
25676
|
+
await cp(path9.join(target, file2.path), destination, { errorOnExist: true, force: false });
|
|
25677
|
+
if (createHash4("sha256").update(await readFile8(destination)).digest("hex") !== file2.sha256)
|
|
25472
25678
|
throw new WorkPackLocalEditsError("local-edits-preserved");
|
|
25473
25679
|
}
|
|
25474
25680
|
}
|
|
25475
25681
|
async function installSkillArchive(paths, slug, version2, archive, options = {}) {
|
|
25476
|
-
const tempRoot = await mkdtemp(
|
|
25477
|
-
const archivePath =
|
|
25478
|
-
const extractPath =
|
|
25479
|
-
const nextPath =
|
|
25480
|
-
const target =
|
|
25481
|
-
const backup =
|
|
25682
|
+
const tempRoot = await mkdtemp(path9.join(os4.tmpdir(), `forge-${slug}-`));
|
|
25683
|
+
const archivePath = path9.join(tempRoot, `${slug}.tar`);
|
|
25684
|
+
const extractPath = path9.join(tempRoot, "extract");
|
|
25685
|
+
const nextPath = path9.join(tempRoot, slug);
|
|
25686
|
+
const target = path9.join(paths.skillsDir, slug);
|
|
25687
|
+
const backup = path9.join(paths.skillsDir, `${slug}.previous`);
|
|
25482
25688
|
let agentFiles;
|
|
25483
25689
|
let commandFiles;
|
|
25484
25690
|
let previousAgents;
|
|
@@ -25487,7 +25693,7 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
|
|
|
25487
25693
|
await mkdir5(extractPath, { recursive: true });
|
|
25488
25694
|
await writeFile6(archivePath, archive);
|
|
25489
25695
|
await So({ file: archivePath, cwd: extractPath, strict: true });
|
|
25490
|
-
const extractedSkillPath =
|
|
25696
|
+
const extractedSkillPath = path9.join(extractPath, slug);
|
|
25491
25697
|
await assertNoReservedMarkerAliases(extractedSkillPath);
|
|
25492
25698
|
await validateSkillFolder(extractedSkillPath, slug);
|
|
25493
25699
|
agentFiles = await normalizePackAgentModels(
|
|
@@ -25514,15 +25720,15 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
|
|
|
25514
25720
|
}
|
|
25515
25721
|
throw error45;
|
|
25516
25722
|
}
|
|
25517
|
-
await rename6(
|
|
25518
|
-
await writeFile6(
|
|
25723
|
+
await rename6(path9.join(extractPath, slug), nextPath);
|
|
25724
|
+
await writeFile6(path9.join(nextPath, ".forge-version"), `${version2}
|
|
25519
25725
|
`);
|
|
25520
25726
|
if (agentFiles.length > 0) {
|
|
25521
|
-
await writeFile6(
|
|
25727
|
+
await writeFile6(path9.join(nextPath, ".forge-agents"), `${agentFiles.map((agent) => agent.filename).join("\n")}
|
|
25522
25728
|
`);
|
|
25523
25729
|
}
|
|
25524
25730
|
if (commandFiles.length > 0) {
|
|
25525
|
-
await writeFile6(
|
|
25731
|
+
await writeFile6(path9.join(nextPath, ".forge-commands"), `${commandFiles.map((command) => command.filename).join("\n")}
|
|
25526
25732
|
`);
|
|
25527
25733
|
}
|
|
25528
25734
|
await writeWorkPackInstalledState({ packDir: nextPath, version: version2, agents: agentFiles, commands: commandFiles });
|
|
@@ -25533,13 +25739,13 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
|
|
|
25533
25739
|
const agentTransactionState = new Map(
|
|
25534
25740
|
[...agentSnapshot.keys()].map((filePath) => [
|
|
25535
25741
|
filePath,
|
|
25536
|
-
agentFiles.find((agent) => agent.filename ===
|
|
25742
|
+
agentFiles.find((agent) => agent.filename === path9.basename(filePath))?.content
|
|
25537
25743
|
])
|
|
25538
25744
|
);
|
|
25539
25745
|
const commandTransactionState = new Map(
|
|
25540
25746
|
[...commandSnapshot.keys()].map((filePath) => [
|
|
25541
25747
|
filePath,
|
|
25542
|
-
commandFiles.find((command) => command.filename ===
|
|
25748
|
+
commandFiles.find((command) => command.filename === path9.basename(filePath))?.content
|
|
25543
25749
|
])
|
|
25544
25750
|
);
|
|
25545
25751
|
const previousManagedPaths = await managedWorkPackPaths(paths, target);
|
|
@@ -25560,7 +25766,7 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
|
|
|
25560
25766
|
throw error45;
|
|
25561
25767
|
}
|
|
25562
25768
|
const writeProjection = options.writeWorkPackProjection ?? writeTextAtomic;
|
|
25563
|
-
const claimedBackup =
|
|
25769
|
+
const claimedBackup = path9.join(tempRoot, `${slug}-claimed-previous`);
|
|
25564
25770
|
const transactionPath = `${backup}${WORK_PACK_TRANSACTION_SUFFIX}`;
|
|
25565
25771
|
let targetBackedUp = false;
|
|
25566
25772
|
let targetInstalled = false;
|
|
@@ -25583,7 +25789,7 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
|
|
|
25583
25789
|
await rename6(nextPath, target);
|
|
25584
25790
|
targetInstalled = true;
|
|
25585
25791
|
for (const filename of previousAgents.filter((name) => !nextAgentNames.has(name))) {
|
|
25586
|
-
const filePath =
|
|
25792
|
+
const filePath = path9.join(paths.agentsDir, filename);
|
|
25587
25793
|
await options.workPackProjectionBoundary?.("install", filePath);
|
|
25588
25794
|
await assertProjectionState(filePath, agentSnapshot.get(filePath));
|
|
25589
25795
|
await rm4(filePath, { force: true });
|
|
@@ -25591,14 +25797,14 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
|
|
|
25591
25797
|
if (agentFiles.length > 0) {
|
|
25592
25798
|
await mkdir5(paths.agentsDir, { recursive: true });
|
|
25593
25799
|
for (const agent of agentFiles) {
|
|
25594
|
-
const filePath =
|
|
25800
|
+
const filePath = path9.join(paths.agentsDir, agent.filename);
|
|
25595
25801
|
await options.workPackProjectionBoundary?.("install", filePath);
|
|
25596
25802
|
await assertProjectionState(filePath, agentSnapshot.get(filePath));
|
|
25597
25803
|
await writeProjection(filePath, agent.content);
|
|
25598
25804
|
}
|
|
25599
25805
|
}
|
|
25600
25806
|
for (const filename of previousCommands.filter((name) => !nextCommandNames.has(name))) {
|
|
25601
|
-
const filePath =
|
|
25807
|
+
const filePath = path9.join(paths.commandsDir, filename);
|
|
25602
25808
|
await options.workPackProjectionBoundary?.("install", filePath);
|
|
25603
25809
|
await assertProjectionState(filePath, commandSnapshot.get(filePath));
|
|
25604
25810
|
await rm4(filePath, { force: true });
|
|
@@ -25606,7 +25812,7 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
|
|
|
25606
25812
|
if (commandFiles.length > 0) {
|
|
25607
25813
|
await mkdir5(paths.commandsDir, { recursive: true });
|
|
25608
25814
|
for (const command of commandFiles) {
|
|
25609
|
-
const filePath =
|
|
25815
|
+
const filePath = path9.join(paths.commandsDir, command.filename);
|
|
25610
25816
|
await options.workPackProjectionBoundary?.("install", filePath);
|
|
25611
25817
|
await assertProjectionState(filePath, commandSnapshot.get(filePath));
|
|
25612
25818
|
await writeProjection(filePath, command.content);
|
|
@@ -25619,7 +25825,7 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
|
|
|
25619
25825
|
await rename6(backup, claimedBackup);
|
|
25620
25826
|
backupClaimed = true;
|
|
25621
25827
|
await assertWorkPackTreeUnchangedAtBoundary(claimedBackup, originalTree);
|
|
25622
|
-
await writeFile6(
|
|
25828
|
+
await writeFile6(path9.join(claimedBackup, WORK_PACK_COMMITTED_MARKER), `${version2}
|
|
25623
25829
|
`);
|
|
25624
25830
|
await writeTextAtomic(transactionPath, "committed\n");
|
|
25625
25831
|
}
|
|
@@ -25631,7 +25837,7 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
|
|
|
25631
25837
|
await restoreProjectionState(commandSnapshot, commandTransactionState);
|
|
25632
25838
|
}
|
|
25633
25839
|
if (targetBackedUp) {
|
|
25634
|
-
const restoredTarget =
|
|
25840
|
+
const restoredTarget = path9.join(tempRoot, `${slug}-restore`);
|
|
25635
25841
|
const rollbackSource = backupClaimed ? claimedBackup : backup;
|
|
25636
25842
|
await cp(rollbackSource, restoredTarget, { recursive: true });
|
|
25637
25843
|
if (targetInstalled) await rm4(target, { recursive: true, force: true });
|
|
@@ -25668,19 +25874,19 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
|
|
|
25668
25874
|
return { cleanup: cleanup2 };
|
|
25669
25875
|
}
|
|
25670
25876
|
async function adoptLegacyWorkPackState(paths, slug, version2, archive, approvedModelIds) {
|
|
25671
|
-
const comparisonRoot = await mkdtemp(
|
|
25877
|
+
const comparisonRoot = await mkdtemp(path9.join(os4.tmpdir(), `forge-${slug}-baseline-`));
|
|
25672
25878
|
const comparisonPaths = {
|
|
25673
25879
|
...paths,
|
|
25674
|
-
skillsDir:
|
|
25675
|
-
agentsDir:
|
|
25676
|
-
commandsDir:
|
|
25880
|
+
skillsDir: path9.join(comparisonRoot, "skills"),
|
|
25881
|
+
agentsDir: path9.join(comparisonRoot, "agents"),
|
|
25882
|
+
commandsDir: path9.join(comparisonRoot, "commands")
|
|
25677
25883
|
};
|
|
25678
25884
|
try {
|
|
25679
25885
|
await mkdir5(comparisonPaths.skillsDir, { recursive: true });
|
|
25680
25886
|
await installSkillArchive(comparisonPaths, slug, version2, archive, { approvedModelIds });
|
|
25681
25887
|
return adoptWorkPackInstalledState({
|
|
25682
|
-
expectedPackDir:
|
|
25683
|
-
packDir:
|
|
25888
|
+
expectedPackDir: path9.join(comparisonPaths.skillsDir, slug),
|
|
25889
|
+
packDir: path9.join(paths.skillsDir, slug),
|
|
25684
25890
|
agentsDir: paths.agentsDir,
|
|
25685
25891
|
commandsDir: paths.commandsDir,
|
|
25686
25892
|
allowAdditional: true
|
|
@@ -25692,7 +25898,7 @@ async function adoptLegacyWorkPackState(paths, slug, version2, archive, approved
|
|
|
25692
25898
|
async function recoverInterruptedWorkPackInstalls(paths, cleanupWorkPackBackup, workPackProjectionBoundary) {
|
|
25693
25899
|
const cleanupPending = /* @__PURE__ */ new Set();
|
|
25694
25900
|
const failures = /* @__PURE__ */ new Map();
|
|
25695
|
-
const entries = await
|
|
25901
|
+
const entries = await readdir4(paths.skillsDir, { withFileTypes: true }).catch((error45) => {
|
|
25696
25902
|
if (error45.code === "ENOENT") return [];
|
|
25697
25903
|
throw error45;
|
|
25698
25904
|
});
|
|
@@ -25700,7 +25906,7 @@ async function recoverInterruptedWorkPackInstalls(paths, cleanupWorkPackBackup,
|
|
|
25700
25906
|
if (!entry.name.endsWith(".previous")) continue;
|
|
25701
25907
|
const slug = entry.name.slice(0, -".previous".length);
|
|
25702
25908
|
if (!slug) continue;
|
|
25703
|
-
const target =
|
|
25909
|
+
const target = path9.join(paths.skillsDir, slug);
|
|
25704
25910
|
const backup = `${target}.previous`;
|
|
25705
25911
|
const transactionState = await readWorkPackTransactionState(backup);
|
|
25706
25912
|
if (transactionState === "committed") {
|
|
@@ -25733,9 +25939,9 @@ async function recoverInterruptedWorkPackInstall(paths, target, cleanupWorkPackB
|
|
|
25733
25939
|
const backup = `${target}.previous`;
|
|
25734
25940
|
const backupOwnership = await workPackOwnership(backup);
|
|
25735
25941
|
if (backupOwnership === "absent") return "recovered";
|
|
25736
|
-
if (backupOwnership === "foreign") throw foreignWorkPackError(
|
|
25737
|
-
if (await workPackOwnership(target) === "foreign") throw foreignWorkPackError(
|
|
25738
|
-
const committed = await
|
|
25942
|
+
if (backupOwnership === "foreign") throw foreignWorkPackError(path9.basename(target));
|
|
25943
|
+
if (await workPackOwnership(target) === "foreign") throw foreignWorkPackError(path9.basename(target));
|
|
25944
|
+
const committed = await readFile8(path9.join(backup, WORK_PACK_COMMITTED_MARKER), "utf8").catch((error45) => {
|
|
25739
25945
|
if (error45.code === "ENOENT") return void 0;
|
|
25740
25946
|
throw error45;
|
|
25741
25947
|
});
|
|
@@ -25783,32 +25989,32 @@ async function recoverInterruptedWorkPackInstall(paths, target, cleanupWorkPackB
|
|
|
25783
25989
|
);
|
|
25784
25990
|
const previousAgentNames = new Set(previousAgents.map((agent) => agent.filename));
|
|
25785
25991
|
const previousCommandNames = new Set(previousCommands.map((command) => command.filename));
|
|
25786
|
-
const recoveryRoot = await mkdtemp(
|
|
25787
|
-
const recoveredTarget =
|
|
25992
|
+
const recoveryRoot = await mkdtemp(path9.join(os4.tmpdir(), "forge-recover-"));
|
|
25993
|
+
const recoveredTarget = path9.join(recoveryRoot, path9.basename(target));
|
|
25788
25994
|
await cp(backup, recoveredTarget, { recursive: true });
|
|
25789
25995
|
try {
|
|
25790
25996
|
for (const filename of currentAgents.filter((name) => !previousAgentNames.has(name))) {
|
|
25791
|
-
const filePath =
|
|
25997
|
+
const filePath = path9.join(paths.agentsDir, filename);
|
|
25792
25998
|
await workPackProjectionBoundary?.("recover", filePath);
|
|
25793
25999
|
await assertProjectionState(filePath, agentRecoveryState.get(filePath));
|
|
25794
26000
|
await rm4(filePath, { force: true });
|
|
25795
26001
|
}
|
|
25796
26002
|
await mkdir5(paths.agentsDir, { recursive: true });
|
|
25797
26003
|
for (const agent of previousAgents) {
|
|
25798
|
-
const filePath =
|
|
26004
|
+
const filePath = path9.join(paths.agentsDir, agent.filename);
|
|
25799
26005
|
await workPackProjectionBoundary?.("recover", filePath);
|
|
25800
26006
|
await assertProjectionState(filePath, agentRecoveryState.get(filePath));
|
|
25801
26007
|
await writeTextAtomic(filePath, agent.content);
|
|
25802
26008
|
}
|
|
25803
26009
|
for (const filename of currentCommands.filter((name) => !previousCommandNames.has(name))) {
|
|
25804
|
-
const filePath =
|
|
26010
|
+
const filePath = path9.join(paths.commandsDir, filename);
|
|
25805
26011
|
await workPackProjectionBoundary?.("recover", filePath);
|
|
25806
26012
|
await assertProjectionState(filePath, commandRecoveryState.get(filePath));
|
|
25807
26013
|
await rm4(filePath, { force: true });
|
|
25808
26014
|
}
|
|
25809
26015
|
await mkdir5(paths.commandsDir, { recursive: true });
|
|
25810
26016
|
for (const command of previousCommands) {
|
|
25811
|
-
const filePath =
|
|
26017
|
+
const filePath = path9.join(paths.commandsDir, command.filename);
|
|
25812
26018
|
await workPackProjectionBoundary?.("recover", filePath);
|
|
25813
26019
|
await assertProjectionState(filePath, commandRecoveryState.get(filePath));
|
|
25814
26020
|
await writeTextAtomic(filePath, command.content);
|
|
@@ -25826,7 +26032,7 @@ async function removeWorkPackBackup(backupPath) {
|
|
|
25826
26032
|
await rm4(backupPath, { recursive: true, force: true });
|
|
25827
26033
|
}
|
|
25828
26034
|
async function readWorkPackTransactionFile(backup) {
|
|
25829
|
-
return
|
|
26035
|
+
return readFile8(`${backup}${WORK_PACK_TRANSACTION_SUFFIX}`, "utf8").catch((error45) => {
|
|
25830
26036
|
if (error45.code === "ENOENT") return void 0;
|
|
25831
26037
|
throw error45;
|
|
25832
26038
|
});
|
|
@@ -25840,7 +26046,7 @@ function isManagedProjectionName(filename) {
|
|
|
25840
26046
|
return filename.length > 0 && !filename.includes("/") && !filename.includes("\\") && filename !== "..";
|
|
25841
26047
|
}
|
|
25842
26048
|
async function recordRemovedProjection(transactionPath, kind, filename) {
|
|
25843
|
-
const current = await
|
|
26049
|
+
const current = await readFile8(transactionPath, "utf8");
|
|
25844
26050
|
await writeTextAtomic(transactionPath, `${current.trimEnd()}
|
|
25845
26051
|
${kind}:${filename}
|
|
25846
26052
|
`);
|
|
@@ -25877,7 +26083,7 @@ async function workPackOwnership(target) {
|
|
|
25877
26083
|
});
|
|
25878
26084
|
if (!targetStat) return "absent";
|
|
25879
26085
|
if (!targetStat.isDirectory()) return "foreign";
|
|
25880
|
-
const marker = await
|
|
26086
|
+
const marker = await readFile8(path9.join(target, ".forge-version"), "utf8").catch((error45) => {
|
|
25881
26087
|
if (error45.code === "ENOENT") return void 0;
|
|
25882
26088
|
throw error45;
|
|
25883
26089
|
});
|
|
@@ -25903,11 +26109,11 @@ async function assertProjectionRecoveryIsSafe(directory, currentFiles, previousF
|
|
|
25903
26109
|
expected.set(file2.filename, contents);
|
|
25904
26110
|
}
|
|
25905
26111
|
for (const [filename, contents] of expected) {
|
|
25906
|
-
const projected = await
|
|
26112
|
+
const projected = await readFile8(path9.join(directory, filename), "utf8").catch((error45) => {
|
|
25907
26113
|
if (error45.code === "ENOENT") return void 0;
|
|
25908
26114
|
throw error45;
|
|
25909
26115
|
});
|
|
25910
|
-
validated.set(
|
|
26116
|
+
validated.set(path9.join(directory, filename), projected);
|
|
25911
26117
|
const missingPreviousProjection = missingPreviousProjectionIsLocalDeletion(
|
|
25912
26118
|
filename,
|
|
25913
26119
|
projected,
|
|
@@ -25925,19 +26131,19 @@ async function assertProjectionRecoveryIsSafe(directory, currentFiles, previousF
|
|
|
25925
26131
|
return validated;
|
|
25926
26132
|
}
|
|
25927
26133
|
async function assertProjectionState(filePath, expected) {
|
|
25928
|
-
const current = await
|
|
26134
|
+
const current = await readFile8(filePath, "utf8").catch((error45) => {
|
|
25929
26135
|
if (error45.code === "ENOENT") return void 0;
|
|
25930
26136
|
throw error45;
|
|
25931
26137
|
});
|
|
25932
26138
|
if (current !== expected) {
|
|
25933
|
-
throw new WorkPackLocalEditsError("local-edits-preserved", `A proje\xE7\xE3o ${
|
|
26139
|
+
throw new WorkPackLocalEditsError("local-edits-preserved", `A proje\xE7\xE3o ${path9.basename(filePath)} foi alterada durante a opera\xE7\xE3o`);
|
|
25934
26140
|
}
|
|
25935
26141
|
}
|
|
25936
26142
|
async function captureProjectionState(directory, filenames) {
|
|
25937
26143
|
const snapshot = /* @__PURE__ */ new Map();
|
|
25938
26144
|
for (const filename of filenames) {
|
|
25939
|
-
const filePath =
|
|
25940
|
-
const content = await
|
|
26145
|
+
const filePath = path9.join(directory, filename);
|
|
26146
|
+
const content = await readFile8(filePath, "utf8").catch((error45) => {
|
|
25941
26147
|
if (error45.code === "ENOENT") return void 0;
|
|
25942
26148
|
throw error45;
|
|
25943
26149
|
});
|
|
@@ -25948,7 +26154,7 @@ async function captureProjectionState(directory, filenames) {
|
|
|
25948
26154
|
async function restoreProjectionState(snapshot, transactionState) {
|
|
25949
26155
|
for (const [filePath, content] of snapshot) {
|
|
25950
26156
|
if (transactionState) {
|
|
25951
|
-
const current = await
|
|
26157
|
+
const current = await readFile8(filePath, "utf8").catch((error45) => {
|
|
25952
26158
|
if (error45.code === "ENOENT") return void 0;
|
|
25953
26159
|
throw error45;
|
|
25954
26160
|
});
|
|
@@ -25959,8 +26165,8 @@ async function restoreProjectionState(snapshot, transactionState) {
|
|
|
25959
26165
|
}
|
|
25960
26166
|
}
|
|
25961
26167
|
async function readPackAgentFiles(skillFolder, managedNames) {
|
|
25962
|
-
const agentsFolder =
|
|
25963
|
-
const entries = await
|
|
26168
|
+
const agentsFolder = path9.join(skillFolder, "agents");
|
|
26169
|
+
const entries = await readdir4(agentsFolder, { withFileTypes: true }).catch((error45) => {
|
|
25964
26170
|
if (error45.code === "ENOENT") return [];
|
|
25965
26171
|
throw error45;
|
|
25966
26172
|
});
|
|
@@ -25968,7 +26174,7 @@ async function readPackAgentFiles(skillFolder, managedNames) {
|
|
|
25968
26174
|
for (const entry of entries) {
|
|
25969
26175
|
if (!entry.isFile() || !entry.name.endsWith(".md") || managedNames && !managedNames.has(entry.name)) continue;
|
|
25970
26176
|
if (entry.name.startsWith("._")) continue;
|
|
25971
|
-
const content = await
|
|
26177
|
+
const content = await readFile8(path9.join(agentsFolder, entry.name), "utf8");
|
|
25972
26178
|
validateAgentFile(entry.name, content);
|
|
25973
26179
|
files.push({ filename: entry.name, content });
|
|
25974
26180
|
}
|
|
@@ -25979,7 +26185,7 @@ async function normalizePackAgentModels(skillFolder, agentFiles, approvedModelId
|
|
|
25979
26185
|
for (const agent of agentFiles) {
|
|
25980
26186
|
const content = normalizePackAgentModel(agent.filename, agent.content, approvedModelIds, slug);
|
|
25981
26187
|
if (content !== agent.content) {
|
|
25982
|
-
await writeFile6(
|
|
26188
|
+
await writeFile6(path9.join(skillFolder, "agents", agent.filename), content);
|
|
25983
26189
|
}
|
|
25984
26190
|
normalized.push({ ...agent, content });
|
|
25985
26191
|
}
|
|
@@ -25999,8 +26205,8 @@ function normalizePackAgentModel(filename, content, approvedModelIds, slug) {
|
|
|
25999
26205
|
return normalizePackExtensionModel(`agents/${filename}`, content, approvedModelIds, slug);
|
|
26000
26206
|
}
|
|
26001
26207
|
async function readPackCommandFiles(skillFolder, managedNames) {
|
|
26002
|
-
const commandsFolder =
|
|
26003
|
-
const entries = await
|
|
26208
|
+
const commandsFolder = path9.join(skillFolder, "commands");
|
|
26209
|
+
const entries = await readdir4(commandsFolder, { withFileTypes: true }).catch((error45) => {
|
|
26004
26210
|
if (error45.code === "ENOENT") return [];
|
|
26005
26211
|
throw error45;
|
|
26006
26212
|
});
|
|
@@ -26008,7 +26214,7 @@ async function readPackCommandFiles(skillFolder, managedNames) {
|
|
|
26008
26214
|
for (const entry of entries) {
|
|
26009
26215
|
if (!entry.isFile() || !entry.name.endsWith(".md") || managedNames && !managedNames.has(entry.name)) continue;
|
|
26010
26216
|
if (entry.name.startsWith("._")) continue;
|
|
26011
|
-
const content = await
|
|
26217
|
+
const content = await readFile8(path9.join(commandsFolder, entry.name), "utf8");
|
|
26012
26218
|
validateCommandFile(entry.name, content);
|
|
26013
26219
|
files.push({ filename: entry.name, content });
|
|
26014
26220
|
}
|
|
@@ -26019,7 +26225,7 @@ async function normalizePackCommandModels(skillFolder, commandFiles, approvedMod
|
|
|
26019
26225
|
for (const command of commandFiles) {
|
|
26020
26226
|
const content = normalizePackExtensionModel(`commands/${command.filename}`, command.content, approvedModelIds, slug);
|
|
26021
26227
|
if (content !== command.content) {
|
|
26022
|
-
await writeFile6(
|
|
26228
|
+
await writeFile6(path9.join(skillFolder, "commands", command.filename), content);
|
|
26023
26229
|
}
|
|
26024
26230
|
normalized.push({ ...command, content });
|
|
26025
26231
|
}
|
|
@@ -26041,7 +26247,7 @@ async function assertNoForeignAgentConflicts(agentsDir, agentFiles, ownedFilenam
|
|
|
26041
26247
|
const owned = new Set(ownedFilenames);
|
|
26042
26248
|
for (const agent of agentFiles) {
|
|
26043
26249
|
if (owned.has(agent.filename)) continue;
|
|
26044
|
-
const existing = await
|
|
26250
|
+
const existing = await readFile8(path9.join(agentsDir, agent.filename), "utf8").catch((error45) => {
|
|
26045
26251
|
if (error45.code === "ENOENT") return void 0;
|
|
26046
26252
|
throw error45;
|
|
26047
26253
|
});
|
|
@@ -26054,7 +26260,7 @@ async function assertNoForeignCommandConflicts(commandsDir, commandFiles, ownedF
|
|
|
26054
26260
|
const owned = new Set(ownedFilenames);
|
|
26055
26261
|
for (const command of commandFiles) {
|
|
26056
26262
|
if (owned.has(command.filename)) continue;
|
|
26057
|
-
const existing = await
|
|
26263
|
+
const existing = await readFile8(path9.join(commandsDir, command.filename), "utf8").catch((error45) => {
|
|
26058
26264
|
if (error45.code === "ENOENT") return void 0;
|
|
26059
26265
|
throw error45;
|
|
26060
26266
|
});
|
|
@@ -26064,28 +26270,28 @@ async function assertNoForeignCommandConflicts(commandsDir, commandFiles, ownedF
|
|
|
26064
26270
|
}
|
|
26065
26271
|
}
|
|
26066
26272
|
async function readAgentRecord(skillFolder) {
|
|
26067
|
-
const raw = await
|
|
26273
|
+
const raw = await readFile8(path9.join(skillFolder, ".forge-agents"), "utf8").catch(() => "");
|
|
26068
26274
|
return raw.split("\n").map((line) => line.trim()).filter((line) => line.length > 0 && !line.includes("/") && !line.includes("\\") && line !== "..");
|
|
26069
26275
|
}
|
|
26070
26276
|
async function readCommandRecord(skillFolder) {
|
|
26071
|
-
const raw = await
|
|
26277
|
+
const raw = await readFile8(path9.join(skillFolder, ".forge-commands"), "utf8").catch(() => "");
|
|
26072
26278
|
return raw.split("\n").map((line) => line.trim()).filter((line) => line.length > 0 && !line.includes("/") && !line.includes("\\") && line !== "..");
|
|
26073
26279
|
}
|
|
26074
26280
|
async function managedWorkPackPaths(paths, skillFolder) {
|
|
26075
26281
|
const files = await listFilesRecursively(skillFolder);
|
|
26076
|
-
const agents = (await readAgentRecord(skillFolder)).map((filename) =>
|
|
26077
|
-
const commands = (await readCommandRecord(skillFolder)).map((filename) =>
|
|
26282
|
+
const agents = (await readAgentRecord(skillFolder)).map((filename) => path9.join(paths.agentsDir, filename));
|
|
26283
|
+
const commands = (await readCommandRecord(skillFolder)).map((filename) => path9.join(paths.commandsDir, filename));
|
|
26078
26284
|
return [.../* @__PURE__ */ new Set([...files, ...agents, ...commands])];
|
|
26079
26285
|
}
|
|
26080
26286
|
async function managedWorkPackSlugs(skillsDir) {
|
|
26081
|
-
const entries = await
|
|
26287
|
+
const entries = await readdir4(skillsDir, { withFileTypes: true }).catch((error45) => {
|
|
26082
26288
|
if (error45.code === "ENOENT") return [];
|
|
26083
26289
|
throw error45;
|
|
26084
26290
|
});
|
|
26085
26291
|
const slugs = [];
|
|
26086
26292
|
for (const entry of entries) {
|
|
26087
26293
|
if (!entry.isDirectory() || entry.name.endsWith(".previous")) continue;
|
|
26088
|
-
if (await workPackOwnership(
|
|
26294
|
+
if (await workPackOwnership(path9.join(skillsDir, entry.name)) === "managed") slugs.push(entry.name);
|
|
26089
26295
|
}
|
|
26090
26296
|
return slugs.sort((left, right) => left.localeCompare(right));
|
|
26091
26297
|
}
|
|
@@ -26095,14 +26301,14 @@ async function removeManagedWorkPackTransaction(paths, target, options) {
|
|
|
26095
26301
|
const agents = await readAgentRecord(target);
|
|
26096
26302
|
const commands = await readCommandRecord(target);
|
|
26097
26303
|
const snapshots = await Promise.all([
|
|
26098
|
-
...agents.map((filename) => captureExactFile(
|
|
26099
|
-
...commands.map((filename) => captureExactFile(
|
|
26304
|
+
...agents.map((filename) => captureExactFile(path9.join(paths.agentsDir, filename))),
|
|
26305
|
+
...commands.map((filename) => captureExactFile(path9.join(paths.commandsDir, filename)))
|
|
26100
26306
|
]);
|
|
26101
26307
|
await assertWorkPackUnchangedAtBoundary(paths, target);
|
|
26102
26308
|
const backup = `${target}.previous`;
|
|
26103
26309
|
const transactionPath = `${backup}${WORK_PACK_TRANSACTION_SUFFIX}`;
|
|
26104
|
-
const transactionRoot = await mkdtemp(
|
|
26105
|
-
const claimedBackup =
|
|
26310
|
+
const transactionRoot = await mkdtemp(path9.join(os4.tmpdir(), "forge-remove-"));
|
|
26311
|
+
const claimedBackup = path9.join(transactionRoot, path9.basename(target));
|
|
26106
26312
|
let projectionsRemoved = false;
|
|
26107
26313
|
let backupClaimed = false;
|
|
26108
26314
|
try {
|
|
@@ -26120,7 +26326,7 @@ async function removeManagedWorkPackTransaction(paths, target, options) {
|
|
|
26120
26326
|
await assertWorkPackUnchangedAtBoundary(paths, backup);
|
|
26121
26327
|
projectionsRemoved = agents.length > 0;
|
|
26122
26328
|
for (const filename of agents) {
|
|
26123
|
-
const filePath =
|
|
26329
|
+
const filePath = path9.join(paths.agentsDir, filename);
|
|
26124
26330
|
await options.workPackProjectionBoundary?.("remove", filePath);
|
|
26125
26331
|
await assertExactFileState(snapshots, filePath);
|
|
26126
26332
|
await recordRemovedProjection(transactionPath, "agent", filename);
|
|
@@ -26129,7 +26335,7 @@ async function removeManagedWorkPackTransaction(paths, target, options) {
|
|
|
26129
26335
|
await options.removeWorkPackBoundary?.("after-agents");
|
|
26130
26336
|
projectionsRemoved ||= commands.length > 0;
|
|
26131
26337
|
for (const filename of commands) {
|
|
26132
|
-
const filePath =
|
|
26338
|
+
const filePath = path9.join(paths.commandsDir, filename);
|
|
26133
26339
|
await options.workPackProjectionBoundary?.("remove", filePath);
|
|
26134
26340
|
await assertExactFileState(snapshots, filePath);
|
|
26135
26341
|
await recordRemovedProjection(transactionPath, "command", filename);
|
|
@@ -26155,7 +26361,7 @@ async function removeManagedWorkPackTransaction(paths, target, options) {
|
|
|
26155
26361
|
if (await workPackOwnership(target) !== "managed") throw new Error("restored Work Pack marker missing");
|
|
26156
26362
|
await rm4(transactionRoot, { recursive: true, force: true }).catch(() => void 0);
|
|
26157
26363
|
} catch (restoreError) {
|
|
26158
|
-
throw new WorkPackRecoveryUncertainError(`Falha ao remover e restaurar o pacote de trabalho ${
|
|
26364
|
+
throw new WorkPackRecoveryUncertainError(`Falha ao remover e restaurar o pacote de trabalho ${path9.basename(target)}`, {
|
|
26159
26365
|
cause: new AggregateError([error45, restoreError])
|
|
26160
26366
|
});
|
|
26161
26367
|
}
|
|
@@ -26166,7 +26372,7 @@ async function captureExactFile(filePath) {
|
|
|
26166
26372
|
try {
|
|
26167
26373
|
const info = await lstat5(filePath);
|
|
26168
26374
|
if (!info.isFile()) throw new Error(`A proje\xE7\xE3o gerida n\xE3o \xE9 um ficheiro regular: ${filePath}`);
|
|
26169
|
-
return { path: filePath, exists: true, bytes: await
|
|
26375
|
+
return { path: filePath, exists: true, bytes: await readFile8(filePath), mode: info.mode & 4095 };
|
|
26170
26376
|
} catch (error45) {
|
|
26171
26377
|
if (error45.code === "ENOENT") return { path: filePath, exists: false };
|
|
26172
26378
|
throw error45;
|
|
@@ -26176,17 +26382,17 @@ async function assertExactFileState(snapshots, filePath) {
|
|
|
26176
26382
|
const expected = snapshots.find((snapshot) => snapshot.path === filePath);
|
|
26177
26383
|
const current = await captureExactFile(filePath);
|
|
26178
26384
|
if (!expected || current.exists !== expected.exists) {
|
|
26179
|
-
throw new WorkPackLocalEditsError("local-edits-preserved", `A proje\xE7\xE3o ${
|
|
26385
|
+
throw new WorkPackLocalEditsError("local-edits-preserved", `A proje\xE7\xE3o ${path9.basename(filePath)} foi alterada durante a opera\xE7\xE3o`);
|
|
26180
26386
|
}
|
|
26181
26387
|
if (current.exists && (!current.bytes?.equals(expected.bytes) || current.mode !== expected.mode)) {
|
|
26182
|
-
throw new WorkPackLocalEditsError("local-edits-preserved", `A proje\xE7\xE3o ${
|
|
26388
|
+
throw new WorkPackLocalEditsError("local-edits-preserved", `A proje\xE7\xE3o ${path9.basename(filePath)} foi alterada durante a opera\xE7\xE3o`);
|
|
26183
26389
|
}
|
|
26184
26390
|
}
|
|
26185
26391
|
async function restoreRemovedExactFiles(snapshots) {
|
|
26186
26392
|
for (const snapshot of snapshots) {
|
|
26187
26393
|
if ((await captureExactFile(snapshot.path)).exists) continue;
|
|
26188
26394
|
if (!snapshot.exists) continue;
|
|
26189
|
-
await mkdir5(
|
|
26395
|
+
await mkdir5(path9.dirname(snapshot.path), { recursive: true });
|
|
26190
26396
|
await writeFile6(snapshot.path, snapshot.bytes);
|
|
26191
26397
|
await chmod4(snapshot.path, snapshot.mode);
|
|
26192
26398
|
}
|
|
@@ -26198,20 +26404,20 @@ async function verifyRestoredOrLocallyChangedFiles(snapshots) {
|
|
|
26198
26404
|
}
|
|
26199
26405
|
}
|
|
26200
26406
|
async function listFilesRecursively(root) {
|
|
26201
|
-
const entries = await
|
|
26407
|
+
const entries = await readdir4(root, { withFileTypes: true }).catch((error45) => {
|
|
26202
26408
|
if (error45.code === "ENOENT") return [];
|
|
26203
26409
|
throw error45;
|
|
26204
26410
|
});
|
|
26205
26411
|
const files = [];
|
|
26206
26412
|
for (const entry of entries) {
|
|
26207
|
-
const absolute =
|
|
26413
|
+
const absolute = path9.join(root, entry.name);
|
|
26208
26414
|
if (entry.isDirectory()) files.push(...await listFilesRecursively(absolute));
|
|
26209
26415
|
else if (entry.isFile()) files.push(absolute);
|
|
26210
26416
|
}
|
|
26211
26417
|
return files;
|
|
26212
26418
|
}
|
|
26213
26419
|
async function validateSkillFolder(folder, slug) {
|
|
26214
|
-
const skillMd = await
|
|
26420
|
+
const skillMd = await readFile8(path9.join(folder, "SKILL.md"), "utf8");
|
|
26215
26421
|
const frontmatter = /^---\n([\s\S]+?)\n---/.exec(skillMd)?.[1] ?? "";
|
|
26216
26422
|
if (!frontmatter.includes(`name: ${slug}`) && !frontmatter.includes(`name: "${slug}"`)) {
|
|
26217
26423
|
throw new Error(`O campo name no frontmatter de SKILL.md tem de corresponder a ${slug}`);
|
|
@@ -26222,7 +26428,7 @@ async function validateSkillFolder(folder, slug) {
|
|
|
26222
26428
|
}
|
|
26223
26429
|
async function assertNoReservedMarkerAliases(skillFolder) {
|
|
26224
26430
|
const reserved = /* @__PURE__ */ new Set([".forge-version", ".forge-agents", ".forge-commands", WORK_PACK_LOCAL_STATE_FILENAME]);
|
|
26225
|
-
const entries = await
|
|
26431
|
+
const entries = await readdir4(skillFolder);
|
|
26226
26432
|
const marker = entries.find((entry) => reserved.has(entry.toLowerCase()));
|
|
26227
26433
|
if (marker) throw new Error(`O pacote de trabalho cont\xE9m o marcador Forge reservado ${marker}`);
|
|
26228
26434
|
}
|
|
@@ -26232,14 +26438,14 @@ async function writeJsonAtomic2(filePath, value) {
|
|
|
26232
26438
|
await writeTextAtomic(filePath, content);
|
|
26233
26439
|
}
|
|
26234
26440
|
async function writeTextAtomic(filePath, content) {
|
|
26235
|
-
const dir =
|
|
26441
|
+
const dir = path9.dirname(filePath);
|
|
26236
26442
|
await mkdir5(dir, { recursive: true });
|
|
26237
|
-
const tempPath =
|
|
26443
|
+
const tempPath = path9.join(dir, `.${path9.basename(filePath)}.${process.pid}.tmp`);
|
|
26238
26444
|
await writeFile6(tempPath, content);
|
|
26239
26445
|
await rename6(tempPath, filePath);
|
|
26240
26446
|
}
|
|
26241
26447
|
async function readPluginFile(pluginPath) {
|
|
26242
|
-
return
|
|
26448
|
+
return readFile8(pluginPath, "utf8").catch((error45) => {
|
|
26243
26449
|
if (error45.code === "ENOENT") return void 0;
|
|
26244
26450
|
throw error45;
|
|
26245
26451
|
});
|
|
@@ -26272,7 +26478,7 @@ function withPluginPaths(config2, pluginPaths, removePluginPaths = []) {
|
|
|
26272
26478
|
return next;
|
|
26273
26479
|
}
|
|
26274
26480
|
async function readJsoncObject(filePath) {
|
|
26275
|
-
const raw = await
|
|
26481
|
+
const raw = await readFile8(filePath, "utf8").catch((error45) => {
|
|
26276
26482
|
if (error45.code === "ENOENT") return "";
|
|
26277
26483
|
throw error45;
|
|
26278
26484
|
});
|
|
@@ -26362,29 +26568,29 @@ limita\xE7\xF5es ou decis\xF5es pendentes.
|
|
|
26362
26568
|
S\xF3 afirmes que o trabalho continuar\xE1 em segundo plano quando tiver sido
|
|
26363
26569
|
efetivamente criada uma tarefa ou automatiza\xE7\xE3o para esse efeito.`;
|
|
26364
26570
|
function applySharedWorkerPrompt(config2) {
|
|
26365
|
-
if (config2.default_agent !== "openwork" || !
|
|
26571
|
+
if (config2.default_agent !== "openwork" || !isRecord5(config2.agent)) return false;
|
|
26366
26572
|
const agent = config2.agent.openwork;
|
|
26367
|
-
if (!
|
|
26573
|
+
if (!isRecord5(agent) || agent.mode !== "primary" || typeof agent.prompt !== "string") return false;
|
|
26368
26574
|
if (agent.prompt === FORGE_WORKER_PROMPT) return true;
|
|
26369
26575
|
const hash2 = createHash5("sha256").update(agent.prompt.replace(/\r\n/g, "\n").trim()).digest("hex");
|
|
26370
26576
|
if (hash2 !== STOCK_OPENWORK_PROMPT_SHA256) return false;
|
|
26371
26577
|
config2.agent = { ...config2.agent, openwork: { ...agent, prompt: FORGE_WORKER_PROMPT } };
|
|
26372
26578
|
return true;
|
|
26373
26579
|
}
|
|
26374
|
-
function
|
|
26580
|
+
function isRecord5(value) {
|
|
26375
26581
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
26376
26582
|
}
|
|
26377
26583
|
|
|
26378
26584
|
// packages/cli/src/localWorkerSync.ts
|
|
26379
|
-
import { readFile as
|
|
26380
|
-
import
|
|
26585
|
+
import { readFile as readFile11 } from "node:fs/promises";
|
|
26586
|
+
import path12 from "node:path";
|
|
26381
26587
|
|
|
26382
26588
|
// packages/cli/src/recoveryLauncher.ts
|
|
26383
|
-
import { chmod as chmod5, readFile as
|
|
26589
|
+
import { chmod as chmod5, readFile as readFile9 } from "node:fs/promises";
|
|
26384
26590
|
import { execFileSync } from "node:child_process";
|
|
26385
|
-
import
|
|
26591
|
+
import path10 from "node:path";
|
|
26386
26592
|
async function installRecoveryLauncher(paths, forgeBaseUrl, source = new URL("./repair.js", import.meta.url)) {
|
|
26387
|
-
const program = await
|
|
26593
|
+
const program = await readFile9(source, "utf8");
|
|
26388
26594
|
let nodePath;
|
|
26389
26595
|
try {
|
|
26390
26596
|
const runtime = JSON.parse(execFileSync(
|
|
@@ -26392,16 +26598,16 @@ async function installRecoveryLauncher(paths, forgeBaseUrl, source = new URL("./
|
|
|
26392
26598
|
["-p", 'JSON.stringify({ path: process.execPath, major: Number(process.versions.node.split(".")[0]) })'],
|
|
26393
26599
|
{ encoding: "utf8", timeout: 5e3, windowsHide: true }
|
|
26394
26600
|
));
|
|
26395
|
-
if (runtime.major < 22 || typeof runtime.major !== "number" || typeof runtime.path !== "string" || !
|
|
26601
|
+
if (runtime.major < 22 || typeof runtime.major !== "number" || typeof runtime.path !== "string" || !path10.isAbsolute(runtime.path)) throw new Error();
|
|
26396
26602
|
nodePath = runtime.path;
|
|
26397
26603
|
} catch {
|
|
26398
26604
|
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.");
|
|
26399
26605
|
}
|
|
26400
26606
|
const launcherContent = renderRecoveryLauncher(nodePath, process.platform);
|
|
26401
|
-
await writeOwnerOnlyTextAtomic(
|
|
26402
|
-
await writeOwnerOnlyTextAtomic(
|
|
26607
|
+
await writeOwnerOnlyTextAtomic(path10.join(paths.forgeDir, "forge-repair.mjs"), program);
|
|
26608
|
+
await writeOwnerOnlyTextAtomic(path10.join(paths.forgeDir, "recovery-origin.json"), JSON.stringify({ forgeBaseUrl }) + "\n");
|
|
26403
26609
|
const windows = process.platform === "win32";
|
|
26404
|
-
const launcher =
|
|
26610
|
+
const launcher = path10.join(paths.forgeDir, windows ? "Reparar Forge.cmd" : "Reparar Forge.command");
|
|
26405
26611
|
await writeOwnerOnlyTextAtomic(launcher, launcherContent);
|
|
26406
26612
|
if (!windows) await chmod5(launcher, 448);
|
|
26407
26613
|
return launcher;
|
|
@@ -26422,15 +26628,15 @@ exec '${nodePath.replace(/'/g, "'\\''")}' ./forge-repair.mjs "$@"
|
|
|
26422
26628
|
|
|
26423
26629
|
// packages/cli/src/rollback.ts
|
|
26424
26630
|
import { createHash as createHash6 } from "node:crypto";
|
|
26425
|
-
import { chmod as chmod6, mkdir as mkdir6, readFile as
|
|
26426
|
-
import
|
|
26631
|
+
import { chmod as chmod6, mkdir as mkdir6, readFile as readFile10, readdir as readdir5, rename as rename7, rm as rm5, stat as stat2, writeFile as writeFile7 } from "node:fs/promises";
|
|
26632
|
+
import path11 from "node:path";
|
|
26427
26633
|
async function recordRollbackEvidencePlugin(paths, expectedContent) {
|
|
26428
26634
|
if ((await readRollbackLifecycle(paths))?.state !== "pilot") return;
|
|
26429
26635
|
const capsule = await readRollbackCapsule(paths);
|
|
26430
|
-
const pluginPath =
|
|
26636
|
+
const pluginPath = path11.join(paths.pluginDir, FORGE_EVIDENCE_PLUGIN_FILENAME);
|
|
26431
26637
|
const managed = capsule?.managed.files.find((file2) => file2.path === pluginPath);
|
|
26432
26638
|
if (!capsule || !managed) return;
|
|
26433
|
-
const current = await
|
|
26639
|
+
const current = await readFile10(pluginPath, "utf8").catch(() => void 0);
|
|
26434
26640
|
if (current !== expectedContent) return;
|
|
26435
26641
|
const fingerprint = sha2562(Buffer.from(current));
|
|
26436
26642
|
if (managed.sha256 === fingerprint) return;
|
|
@@ -26444,10 +26650,10 @@ async function readRollbackCapsule(paths) {
|
|
|
26444
26650
|
return readJson(paths.rollbackCapsulePath);
|
|
26445
26651
|
}
|
|
26446
26652
|
async function writeProtectedJsonAtomic(filePath, value) {
|
|
26447
|
-
const directory =
|
|
26653
|
+
const directory = path11.dirname(filePath);
|
|
26448
26654
|
await mkdir6(directory, { recursive: true, mode: 448 });
|
|
26449
26655
|
await protectRollbackPath(directory, "directory");
|
|
26450
|
-
const temporary =
|
|
26656
|
+
const temporary = path11.join(directory, `.${path11.basename(filePath)}.${process.pid}.tmp`);
|
|
26451
26657
|
await writeFile7(temporary, `${JSON.stringify(value, null, 2)}
|
|
26452
26658
|
`, { mode: 384 });
|
|
26453
26659
|
await protectRollbackPath(temporary, "file");
|
|
@@ -26457,7 +26663,7 @@ async function protectRollbackPath(filePath, kind, options = {}) {
|
|
|
26457
26663
|
await protectOwnerOnlyPath(filePath, kind, { ...options, failureContext: "o material de rollback" });
|
|
26458
26664
|
}
|
|
26459
26665
|
async function readJson(filePath) {
|
|
26460
|
-
const raw = await
|
|
26666
|
+
const raw = await readFile10(filePath, "utf8").catch((error45) => {
|
|
26461
26667
|
if (error45.code === "ENOENT") return void 0;
|
|
26462
26668
|
throw error45;
|
|
26463
26669
|
});
|
|
@@ -26470,11 +26676,11 @@ function sha2562(value) {
|
|
|
26470
26676
|
|
|
26471
26677
|
// packages/cli/src/localWorkerSync.ts
|
|
26472
26678
|
async function syncLocalWorker(paths, credentials, manifest) {
|
|
26473
|
-
const recovery = await recoverCoreSyncTransaction({ journalPath:
|
|
26679
|
+
const recovery = await recoverCoreSyncTransaction({ journalPath: path12.join(paths.forgeDir, "core-sync-journal.json") });
|
|
26474
26680
|
if (recovery.status === "uncertain") throw new CoreSyncUncertainError(recovery.message, recovery.uncertainPaths);
|
|
26475
26681
|
let current;
|
|
26476
26682
|
try {
|
|
26477
|
-
current = JSON.parse(await
|
|
26683
|
+
current = JSON.parse(await readFile11(paths.opencodeConfigPath, "utf8"));
|
|
26478
26684
|
} catch {
|
|
26479
26685
|
throw new Error("A configura\xE7\xE3o local n\xE3o \xE9 JSON simples v\xE1lido; preserve os ficheiros e pe\xE7a apoio.");
|
|
26480
26686
|
}
|
|
@@ -26492,27 +26698,92 @@ async function syncLocalWorker(paths, credentials, manifest) {
|
|
|
26492
26698
|
return result;
|
|
26493
26699
|
}
|
|
26494
26700
|
|
|
26701
|
+
// packages/cli/src/openworkEngine.ts
|
|
26702
|
+
import { lstat as lstat6, readFile as readFile12, realpath } from "node:fs/promises";
|
|
26703
|
+
import path13 from "node:path";
|
|
26704
|
+
var OPENWORK_ENGINE_HEADER = "// Minimal Forge OpenWork engine configuration\n";
|
|
26705
|
+
async function inspectOpenworkEngineConfig(directory) {
|
|
26706
|
+
if (!path13.isAbsolute(directory)) throw new Error("Indique a pasta absoluta de configura\xE7\xE3o do motor ativo.");
|
|
26707
|
+
const root = await realpath(directory);
|
|
26708
|
+
const generatedPath = path13.join(root, "opencode.json");
|
|
26709
|
+
const generatedEntry = await lstat6(generatedPath);
|
|
26710
|
+
if (!generatedEntry.isFile() || generatedEntry.isSymbolicLink()) throw new Error("Preserve a configura\xE7\xE3o do motor; o ficheiro gerado n\xE3o \xE9 regular.");
|
|
26711
|
+
let generated;
|
|
26712
|
+
try {
|
|
26713
|
+
generated = JSON.parse(await readFile12(generatedPath, "utf8"));
|
|
26714
|
+
} catch {
|
|
26715
|
+
throw new Error("N\xE3o foi poss\xEDvel reconhecer a configura\xE7\xE3o do motor OpenCode 2.");
|
|
26716
|
+
}
|
|
26717
|
+
if (!generated || typeof generated !== "object" || !generated.providers || typeof generated.providers !== "object") {
|
|
26718
|
+
throw new Error("Esta pasta n\xE3o cont\xE9m a configura\xE7\xE3o nativa do motor OpenCode 2 do OpenWork.");
|
|
26719
|
+
}
|
|
26720
|
+
const file2 = path13.join(root, "opencode.jsonc");
|
|
26721
|
+
let content;
|
|
26722
|
+
try {
|
|
26723
|
+
const entry = await lstat6(file2);
|
|
26724
|
+
if (!entry.isFile() || entry.isSymbolicLink()) throw new Error("Preserve o ficheiro complementar existente; n\xE3o \xE9 um ficheiro regular.");
|
|
26725
|
+
content = await readFile12(file2, "utf8");
|
|
26726
|
+
} catch (error45) {
|
|
26727
|
+
if (error45.code !== "ENOENT") throw error45;
|
|
26728
|
+
}
|
|
26729
|
+
if (content !== void 0 && !content.startsWith(OPENWORK_ENGINE_HEADER)) {
|
|
26730
|
+
throw new Error("J\xE1 existe uma configura\xE7\xE3o complementar alheia ao Forge. Preserve-a e pe\xE7a revis\xE3o acompanhada.");
|
|
26731
|
+
}
|
|
26732
|
+
return { directory: root, file: file2, configured: content !== void 0, content };
|
|
26733
|
+
}
|
|
26734
|
+
function renderOpenworkEngineConfig(manifest, credentials, paths, directory, existing = {}) {
|
|
26735
|
+
if (!manifest.workPackSyncPluginVersion) throw new Error("O servidor ainda n\xE3o aprovou uma vers\xE3o exata do plugin para o segundo motor.");
|
|
26736
|
+
const mcp = existing.mcp && typeof existing.mcp === "object" ? existing.mcp : {};
|
|
26737
|
+
const config2 = mergeWorkerOpenCodeConfig(
|
|
26738
|
+
{ permission: existing.permission, mcp: "firecrawl" in mcp ? { firecrawl: mcp.firecrawl } : {} },
|
|
26739
|
+
manifest,
|
|
26740
|
+
credentials.forgeBaseUrl,
|
|
26741
|
+
credentials.forgeApiKey,
|
|
26742
|
+
{ automaticWorkPackSync: true, localConfig: true }
|
|
26743
|
+
);
|
|
26744
|
+
const version2 = configuredWorkPackSyncPluginVersion(config2);
|
|
26745
|
+
const parts = version2?.split(".").map(Number);
|
|
26746
|
+
if (!parts || parts.length !== 3 || !(parts[0] > 0 || parts[1] > 1 || parts[1] === 1 && parts[2] >= 49)) {
|
|
26747
|
+
throw new Error("O servidor ainda n\xE3o aprovou um plugin com suporte OpenCode 2 (m\xEDnimo 0.1.49). N\xE3o altere o motor.");
|
|
26748
|
+
}
|
|
26749
|
+
config2.plugin = (config2.plugin ?? []).map((entry) => Array.isArray(entry) ? [entry[0], { ...entry[1], openworkEngineConfigDir: directory }] : entry);
|
|
26750
|
+
return { ...config2, skills: [paths.skillsDir] };
|
|
26751
|
+
}
|
|
26752
|
+
async function writeOpenworkEngineConfig(directory, config2) {
|
|
26753
|
+
const state = await inspectOpenworkEngineConfig(directory);
|
|
26754
|
+
const content = OPENWORK_ENGINE_HEADER + JSON.stringify(config2, null, 2) + "\n";
|
|
26755
|
+
if (state.content === content) return { changed: false };
|
|
26756
|
+
await writeOwnerOnlyTextAtomic(state.file, content);
|
|
26757
|
+
return { changed: true };
|
|
26758
|
+
}
|
|
26759
|
+
|
|
26495
26760
|
// packages/cli/src/workPackSyncPlugin.ts
|
|
26496
|
-
var PLUGIN_VERSION = "0.1.
|
|
26761
|
+
var PLUGIN_VERSION = "0.1.49";
|
|
26497
26762
|
var FORGE_DECISION_TIMEOUT_MS = 11e4;
|
|
26498
26763
|
var STATUS_FILENAME = "work-pack-startup-status.json";
|
|
26499
26764
|
var activeSync = /* @__PURE__ */ new Map();
|
|
26500
|
-
|
|
26501
|
-
|
|
26502
|
-
|
|
26765
|
+
function isLocalConfig(options) {
|
|
26766
|
+
return Boolean(options && typeof options === "object" && "localConfig" in options && options.localConfig === true);
|
|
26767
|
+
}
|
|
26768
|
+
function startupSync(forgeBaseUrl, localConfig, observe, input) {
|
|
26503
26769
|
const syncKey = `${forgeBaseUrl}:${localConfig ? "local" : "remote"}`;
|
|
26504
26770
|
let sync = activeSync.get(syncKey);
|
|
26505
26771
|
if (!sync) {
|
|
26506
|
-
sync = synchronizeAtStartup(forgeBaseUrl,
|
|
26772
|
+
sync = synchronizeAtStartup(forgeBaseUrl, observe, localConfig, input);
|
|
26507
26773
|
activeSync.set(syncKey, sync);
|
|
26508
26774
|
}
|
|
26509
|
-
|
|
26510
|
-
|
|
26511
|
-
|
|
26512
|
-
|
|
26513
|
-
|
|
26514
|
-
|
|
26515
|
-
|
|
26775
|
+
return sync;
|
|
26776
|
+
}
|
|
26777
|
+
function createForgeTools(forgeBaseUrl, state) {
|
|
26778
|
+
return {
|
|
26779
|
+
forge_decide_run: createForgeDecisionRunTool(forgeBaseUrl, state.decisionBaseUrl, state.paths),
|
|
26780
|
+
forge_decide: createForgeDecisionTool(forgeBaseUrl, state.decisionBaseUrl, state.paths),
|
|
26781
|
+
forge_generate_codebook: createForgeCodebookTool(forgeBaseUrl, state.decisionBaseUrl, state.paths),
|
|
26782
|
+
forge_feedback: createForgeFeedbackTool(forgeBaseUrl, state.paths),
|
|
26783
|
+
forge_image: createForgeImageTool(forgeBaseUrl, state.decisionBaseUrl, state.paths)
|
|
26784
|
+
};
|
|
26785
|
+
}
|
|
26786
|
+
function createEvidenceReporters(forgeBaseUrl, state) {
|
|
26516
26787
|
const reportEvidence = async (sessionID, callID, slug, kind) => {
|
|
26517
26788
|
const { forgeApiKey } = await readForgeCredentials(state.paths, forgeBaseUrl);
|
|
26518
26789
|
const credentialId = createHash7("sha256").update(forgeApiKey).digest("hex");
|
|
@@ -26530,22 +26801,37 @@ var ForgeWorkPackSyncServer = async (_input, options) => {
|
|
|
26530
26801
|
console.error("[Forge evidence] Reasoning guard identity unavailable; event not queued");
|
|
26531
26802
|
});
|
|
26532
26803
|
};
|
|
26804
|
+
const reportSkillInvocation = async (sessionID, callID, name) => {
|
|
26805
|
+
const slug = typeof name === "string" ? name.trim().toLowerCase() : "";
|
|
26806
|
+
if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug)) return;
|
|
26807
|
+
try {
|
|
26808
|
+
await readFile13(path14.join(state.paths.skillsDir, slug, ".forge-version"), "utf8");
|
|
26809
|
+
} catch {
|
|
26810
|
+
return;
|
|
26811
|
+
}
|
|
26812
|
+
try {
|
|
26813
|
+
await reportEvidence(sessionID, callID, slug, "work_pack_invocation");
|
|
26814
|
+
} catch {
|
|
26815
|
+
console.error("[Forge evidence] Invocation identity unavailable; event not queued");
|
|
26816
|
+
}
|
|
26817
|
+
};
|
|
26818
|
+
return { reportReasoningLoop, reportSkillInvocation };
|
|
26819
|
+
}
|
|
26820
|
+
var ForgeWorkPackSyncServer = async (_input, options) => {
|
|
26821
|
+
const forgeBaseUrl = parseForgeBaseUrl(options);
|
|
26822
|
+
const state = await startupSync(forgeBaseUrl, isLocalConfig(options), () => observeRuntime(_input), _input);
|
|
26823
|
+
const legacyPath = path14.join(state.paths.pluginDir, FORGE_EVIDENCE_PLUGIN_FILENAME);
|
|
26824
|
+
const ownershipSymbol = /* @__PURE__ */ Symbol.for("minimal-forge.legacy-evidence-owners.v1");
|
|
26825
|
+
const shared = globalThis;
|
|
26826
|
+
const legacyOwners = shared[ownershipSymbol] ??= /* @__PURE__ */ new Set();
|
|
26827
|
+
const legacyOwnerKey = JSON.stringify([forgeBaseUrl, legacyPath]);
|
|
26828
|
+
const client = reasoningLoopGuardClient(_input);
|
|
26829
|
+
const { reportReasoningLoop, reportSkillInvocation } = createEvidenceReporters(forgeBaseUrl, state);
|
|
26533
26830
|
return {
|
|
26534
26831
|
...client ? { event: createReasoningLoopGuard(client, console.error, reportReasoningLoop) } : {},
|
|
26535
26832
|
"tool.execute.after": async (input) => {
|
|
26536
26833
|
if (input.tool !== "skill" || legacyOwners.has(legacyOwnerKey)) return;
|
|
26537
|
-
|
|
26538
|
-
if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug)) return;
|
|
26539
|
-
try {
|
|
26540
|
-
await readFile11(path12.join(state.paths.skillsDir, slug, ".forge-version"), "utf8");
|
|
26541
|
-
} catch {
|
|
26542
|
-
return;
|
|
26543
|
-
}
|
|
26544
|
-
try {
|
|
26545
|
-
await reportEvidence(input.sessionID, input.callID, slug, "work_pack_invocation");
|
|
26546
|
-
} catch {
|
|
26547
|
-
console.error("[Forge evidence] Invocation identity unavailable; event not queued");
|
|
26548
|
-
}
|
|
26834
|
+
await reportSkillInvocation(input.sessionID, input.callID, input.args?.name);
|
|
26549
26835
|
},
|
|
26550
26836
|
config: async (config2) => {
|
|
26551
26837
|
const entries = Array.isArray(config2.plugin) ? config2.plugin : [];
|
|
@@ -26553,7 +26839,7 @@ var ForgeWorkPackSyncServer = async (_input, options) => {
|
|
|
26553
26839
|
const name = Array.isArray(entry) ? entry[0] : entry;
|
|
26554
26840
|
return name === legacyPath || name === pathToFileURL(legacyPath).href;
|
|
26555
26841
|
});
|
|
26556
|
-
const legacy = registered ? await
|
|
26842
|
+
const legacy = registered ? await readFile13(legacyPath, "utf8").catch(() => "") : "";
|
|
26557
26843
|
const oldLegacyRegistered = registered && legacy.startsWith(FORGE_PLUGIN_HEADER) && legacy.includes("work_pack_invocation") && !legacy.includes("minimal-forge.skill-usage.v1");
|
|
26558
26844
|
if (oldLegacyRegistered) legacyOwners.add(legacyOwnerKey);
|
|
26559
26845
|
if (oldLegacyRegistered) await writeFile8(legacyPath, renderEvidencePlugin()).catch(() => {
|
|
@@ -26562,15 +26848,55 @@ var ForgeWorkPackSyncServer = async (_input, options) => {
|
|
|
26562
26848
|
await projectCurrentExtensions(config2, state);
|
|
26563
26849
|
if (state.forgeConfigVerified) applySharedWorkerPrompt(config2);
|
|
26564
26850
|
},
|
|
26565
|
-
tool:
|
|
26566
|
-
forge_decide_run: createForgeDecisionRunTool(forgeBaseUrl, state.decisionBaseUrl, state.paths),
|
|
26567
|
-
forge_decide: createForgeDecisionTool(forgeBaseUrl, state.decisionBaseUrl, state.paths),
|
|
26568
|
-
forge_generate_codebook: createForgeCodebookTool(forgeBaseUrl, state.decisionBaseUrl, state.paths),
|
|
26569
|
-
forge_feedback: createForgeFeedbackTool(forgeBaseUrl, state.paths),
|
|
26570
|
-
forge_image: createForgeImageTool(forgeBaseUrl, state.decisionBaseUrl, state.paths)
|
|
26571
|
-
}
|
|
26851
|
+
tool: createForgeTools(forgeBaseUrl, state)
|
|
26572
26852
|
};
|
|
26573
26853
|
};
|
|
26854
|
+
async function ForgeWorkPackSyncSetup(ctx) {
|
|
26855
|
+
const forgeBaseUrl = parseForgeBaseUrl(ctx.options);
|
|
26856
|
+
const paths = resolveStartupPaths();
|
|
26857
|
+
const sync = startupSync(forgeBaseUrl, isLocalConfig(ctx.options), async () => observeOpenCode2Runtime(ctx.app));
|
|
26858
|
+
sync.catch((error45) => console.error("[Forge work-pack sync] Startup sync could not run:", safeErrorMessage(error45)));
|
|
26859
|
+
const syncedTools = sync.then(async (state) => {
|
|
26860
|
+
const directory = ctx.options.openworkEngineConfigDir;
|
|
26861
|
+
if (typeof directory === "string" && state.manifest) {
|
|
26862
|
+
const active = process.env.OPENCODE_CONFIG_DIR;
|
|
26863
|
+
if (!active || await realpath2(active) !== await realpath2(directory)) {
|
|
26864
|
+
throw new Error("A pasta do motor ativo mudou. Confirme a liga\xE7\xE3o Forge neste perfil do OpenWork.");
|
|
26865
|
+
}
|
|
26866
|
+
const credentials = await readForgeCredentials(state.paths, forgeBaseUrl);
|
|
26867
|
+
const canonical = objectRecord2(parseJsonc(await readFile13(state.paths.opencodeConfigPath, "utf8")));
|
|
26868
|
+
const config2 = renderOpenworkEngineConfig(state.manifest, credentials, state.paths, directory, canonical);
|
|
26869
|
+
await projectCurrentExtensions(config2, state);
|
|
26870
|
+
for (const key of ["agent", "command"]) if (Object.keys(objectRecord2(config2[key])).length === 0) delete config2[key];
|
|
26871
|
+
await writeOpenworkEngineConfig(directory, config2);
|
|
26872
|
+
}
|
|
26873
|
+
return createForgeTools(forgeBaseUrl, state);
|
|
26874
|
+
});
|
|
26875
|
+
syncedTools.catch(() => void 0);
|
|
26876
|
+
const { reportReasoningLoop, reportSkillInvocation } = createEvidenceReporters(forgeBaseUrl, { paths });
|
|
26877
|
+
const directoryOf = sessionDirectoryResolver(ctx);
|
|
26878
|
+
const registrations = Object.entries(createForgeTools(forgeBaseUrl, { paths, decisionBaseUrl: forgeBaseUrl })).filter(([name]) => name !== "forge_feedback").map(([name, shape]) => openCode2Tool(name, {
|
|
26879
|
+
description: shape.description,
|
|
26880
|
+
args: shape.args,
|
|
26881
|
+
async execute(args, context) {
|
|
26882
|
+
const tools = await syncedTools;
|
|
26883
|
+
context.abort.throwIfAborted();
|
|
26884
|
+
return tools[name].execute(args, context);
|
|
26885
|
+
}
|
|
26886
|
+
}, directoryOf));
|
|
26887
|
+
await ctx.tool.transform((editor) => {
|
|
26888
|
+
for (const registration of registrations) editor.add(registration);
|
|
26889
|
+
});
|
|
26890
|
+
await ctx.tool.hook("execute.after", async (event) => {
|
|
26891
|
+
try {
|
|
26892
|
+
const call = completedSkillCall(event);
|
|
26893
|
+
if (call) await reportSkillInvocation(call.sessionID, call.callID, call.name);
|
|
26894
|
+
} catch {
|
|
26895
|
+
console.error("[Forge evidence] Invocation could not be reported");
|
|
26896
|
+
}
|
|
26897
|
+
});
|
|
26898
|
+
return startReasoningLoopGuard(ctx, reportReasoningLoop);
|
|
26899
|
+
}
|
|
26574
26900
|
function reasoningLoopGuardClient(input) {
|
|
26575
26901
|
if (!input || typeof input !== "object" || !("client" in input)) return void 0;
|
|
26576
26902
|
const client = input.client;
|
|
@@ -26590,7 +26916,7 @@ function createForgeImageTool(forgeBaseUrl, gatewayBaseUrl, paths) {
|
|
|
26590
26916
|
const requestId = randomUUID4();
|
|
26591
26917
|
let referenceDataUrl;
|
|
26592
26918
|
if (args.referencePath) {
|
|
26593
|
-
const bytes = await
|
|
26919
|
+
const bytes = await readFile13(args.referencePath);
|
|
26594
26920
|
if (bytes.byteLength > 25e5) throw new Error("A imagem de refer\xEAncia \xE9 demasiado grande. Reduza-a antes de tentar novamente.");
|
|
26595
26921
|
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;
|
|
26596
26922
|
if (!mime) throw new Error("A refer\xEAncia tem de ser PNG, JPEG ou WebP.");
|
|
@@ -26616,14 +26942,14 @@ function createForgeImageTool(forgeBaseUrl, gatewayBaseUrl, paths) {
|
|
|
26616
26942
|
if (image.byteLength > 8 * 1024 * 1024 || !image.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) {
|
|
26617
26943
|
throw new Error(`O PNG recebido \xE9 inv\xE1lido. Refer\xEAncia: ${requestId}`);
|
|
26618
26944
|
}
|
|
26619
|
-
const destination =
|
|
26945
|
+
const destination = path14.join(context.directory, `forge-image-${requestId}.png`);
|
|
26620
26946
|
await writeFile8(destination, image, { flag: "wx" });
|
|
26621
26947
|
const reset = body.quota && new Intl.DateTimeFormat("pt-PT", { dateStyle: "long", timeZone: "Europe/Lisbon" }).format(new Date(body.quota.resetsAt));
|
|
26622
26948
|
const remaining = body.quota ? ` Restam ${body.quota.remaining} imagens at\xE9 ${reset}.` : "";
|
|
26623
26949
|
return {
|
|
26624
26950
|
title: "Imagem criada",
|
|
26625
26951
|
output: `Imagem guardada em ${destination}.${remaining} A pessoa j\xE1 v\xEA a imagem na conversa. Se n\xE3o a conseguires ver, isso n\xE3o \xE9 um erro: n\xE3o o reportes.`,
|
|
26626
|
-
attachments: [{ type: "file", mime: "image/png", url: `data:image/png;base64,${body.b64_json}`, filename:
|
|
26952
|
+
attachments: [{ type: "file", mime: "image/png", url: `data:image/png;base64,${body.b64_json}`, filename: path14.basename(destination) }]
|
|
26627
26953
|
};
|
|
26628
26954
|
}
|
|
26629
26955
|
});
|
|
@@ -26665,9 +26991,9 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseD
|
|
|
26665
26991
|
let requestBody;
|
|
26666
26992
|
if (fromFile) {
|
|
26667
26993
|
const file2 = await fileInsideWorkspace(context.directory, args.request_file);
|
|
26668
|
-
const planFile =
|
|
26669
|
-
if (!responseDirectory &&
|
|
26670
|
-
const plan = JSON.parse(await
|
|
26994
|
+
const planFile = path14.join(path14.dirname(path14.dirname(file2)), "plan.json");
|
|
26995
|
+
if (!responseDirectory && path14.basename(path14.dirname(file2)) === "requests" && await fileExists(planFile)) {
|
|
26996
|
+
const plan = JSON.parse(await readFile13(planFile, "utf8"));
|
|
26671
26997
|
if (plan?.engine === "jev-batch" && plan.model === "typesafe/jev-1.13" && Array.isArray(plan.batches)) {
|
|
26672
26998
|
let batch;
|
|
26673
26999
|
for (const candidate of plan.batches) {
|
|
@@ -26680,7 +27006,7 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseD
|
|
|
26680
27006
|
return createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths).execute({ plan_file: planFile, batch_id: batch.batch_id }, context);
|
|
26681
27007
|
}
|
|
26682
27008
|
}
|
|
26683
|
-
const raw = await
|
|
27009
|
+
const raw = await readFile13(file2, "utf8");
|
|
26684
27010
|
if (Buffer.byteLength(raw) > 512 * 1024) throw new Error("O ficheiro de pedido excede 512 KiB.");
|
|
26685
27011
|
let parsed;
|
|
26686
27012
|
try {
|
|
@@ -26699,11 +27025,11 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseD
|
|
|
26699
27025
|
if (args.state === void 0 || !args.questions || Object.keys(args.questions).length === 0) throw new Error("Indica state e questions.");
|
|
26700
27026
|
requestBody = { state: args.state, questions: args.questions };
|
|
26701
27027
|
}
|
|
26702
|
-
const responseDir = await mkdtemp2(
|
|
26703
|
-
const responseFile =
|
|
27028
|
+
const responseDir = await mkdtemp2(path14.join(responseDirectory ?? context.directory, ".forge-decision-"));
|
|
27029
|
+
const responseFile = path14.join(responseDir, "response.json");
|
|
26704
27030
|
try {
|
|
26705
27031
|
const credentials = await readForgeCredentials(paths, forgeBaseUrl);
|
|
26706
|
-
const probeFile =
|
|
27032
|
+
const probeFile = path14.join(responseDir, ".write-test");
|
|
26707
27033
|
await writeFile8(probeFile, "", { flag: "wx", mode: 384 });
|
|
26708
27034
|
await unlink(probeFile);
|
|
26709
27035
|
context.abort.throwIfAborted();
|
|
@@ -26752,10 +27078,10 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseD
|
|
|
26752
27078
|
});
|
|
26753
27079
|
}
|
|
26754
27080
|
async function fileInsideWorkspace(directory, candidate) {
|
|
26755
|
-
const workspace = await
|
|
26756
|
-
const file2 = await
|
|
26757
|
-
const relative =
|
|
26758
|
-
if (!relative || (relative === ".." || relative.startsWith(`..${
|
|
27081
|
+
const workspace = await realpath2(directory);
|
|
27082
|
+
const file2 = await realpath2(path14.resolve(workspace, candidate));
|
|
27083
|
+
const relative = path14.relative(workspace, file2);
|
|
27084
|
+
if (!relative || (relative === ".." || relative.startsWith(`..${path14.sep}`)) || path14.isAbsolute(relative)) throw new Error("O ficheiro tem de estar dentro do workspace.");
|
|
26759
27085
|
return file2;
|
|
26760
27086
|
}
|
|
26761
27087
|
async function fileExists(candidate) {
|
|
@@ -26770,7 +27096,7 @@ async function fileExists(candidate) {
|
|
|
26770
27096
|
async function ensureJevDirectory(directory, filesystem = { stat: stat3, mkdir: mkdir7 }) {
|
|
26771
27097
|
try {
|
|
26772
27098
|
if ((await filesystem.stat(directory)).isDirectory()) return;
|
|
26773
|
-
throw new Error(`O destino ${
|
|
27099
|
+
throw new Error(`O destino ${path14.basename(directory)} existe, mas n\xE3o \xE9 uma pasta. Preservar o conte\xFAdo e verificar o caminho.`);
|
|
26774
27100
|
} catch (error45) {
|
|
26775
27101
|
if (error45.code !== "ENOENT") throw error45;
|
|
26776
27102
|
}
|
|
@@ -26790,7 +27116,7 @@ function canonicalJson(value) {
|
|
|
26790
27116
|
return JSON.stringify(value);
|
|
26791
27117
|
}
|
|
26792
27118
|
async function validateSavedDecision(file2, request) {
|
|
26793
|
-
const body = JSON.parse(await
|
|
27119
|
+
const body = JSON.parse(await readFile13(file2, "utf8"));
|
|
26794
27120
|
const answers = body.answers;
|
|
26795
27121
|
const questions = request.questions;
|
|
26796
27122
|
const usage = body.usage;
|
|
@@ -26809,7 +27135,7 @@ async function acquireJevRunLock(lockDir) {
|
|
|
26809
27135
|
let owner;
|
|
26810
27136
|
let ownerRaw;
|
|
26811
27137
|
try {
|
|
26812
|
-
ownerRaw = await
|
|
27138
|
+
ownerRaw = await readFile13(path14.join(lockDir, "owner.json"), "utf8");
|
|
26813
27139
|
owner = JSON.parse(ownerRaw);
|
|
26814
27140
|
} catch {
|
|
26815
27141
|
throw new Error("Chamada interrompida com lock sem identifica\xE7\xE3o; n\xE3o \xE9 poss\xEDvel confirmar que terminou. Preservar o lock e verificar a execu\xE7\xE3o.");
|
|
@@ -26843,41 +27169,41 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
|
|
|
26843
27169
|
},
|
|
26844
27170
|
async execute(args, context) {
|
|
26845
27171
|
const planFile = await fileInsideWorkspace(context.directory, args.plan_file);
|
|
26846
|
-
if (
|
|
26847
|
-
const runDir =
|
|
26848
|
-
const plan = JSON.parse(await
|
|
27172
|
+
if (path14.basename(planFile) !== "plan.json" || path14.basename(path14.dirname(planFile)) !== "jev") throw new Error("Indica o ficheiro jev/plan.json.");
|
|
27173
|
+
const runDir = path14.dirname(path14.dirname(planFile));
|
|
27174
|
+
const plan = JSON.parse(await readFile13(planFile, "utf8"));
|
|
26849
27175
|
if (plan.engine !== "jev-batch" || plan.model !== "typesafe/jev-1.13" || !Array.isArray(plan.batches)) throw new Error("O plano Jev \xE9 inv\xE1lido.");
|
|
26850
27176
|
const allBatches = plan.batches;
|
|
26851
27177
|
const batches = args.batch_id ? allBatches.filter((batch) => batch.batch_id === args.batch_id) : allBatches;
|
|
26852
27178
|
if (args.batch_id && batches.length !== 1) throw new Error("O lote indicado n\xE3o pertence ao plano Jev.");
|
|
26853
|
-
const responsePath =
|
|
27179
|
+
const responsePath = path14.join(runDir, "jev", "responses");
|
|
26854
27180
|
await ensureJevDirectory(responsePath);
|
|
26855
27181
|
const responseDir = await fileInsideWorkspace(context.directory, responsePath);
|
|
26856
|
-
if (
|
|
26857
|
-
const lockDir =
|
|
27182
|
+
if (path14.dirname(responseDir) !== path14.join(runDir, "jev")) throw new Error("A pasta de respostas tem de pertencer ao run Jev.");
|
|
27183
|
+
const lockDir = path14.join(runDir, "jev", ".decide-run.lock");
|
|
26858
27184
|
const interrupted = await acquireJevRunLock(lockDir);
|
|
26859
27185
|
let saved = 0;
|
|
26860
27186
|
let skipped = 0;
|
|
26861
27187
|
let recovered = 0;
|
|
26862
27188
|
const repeated = [];
|
|
26863
27189
|
try {
|
|
26864
|
-
const ownerFile =
|
|
27190
|
+
const ownerFile = path14.join(lockDir, "owner.json");
|
|
26865
27191
|
await writeOwnerOnlyTextAtomic(ownerFile, JSON.stringify({ ...interrupted, pid: process.pid, hostname: os5.hostname(), started_at: (/* @__PURE__ */ new Date()).toISOString() }));
|
|
26866
|
-
const attemptsPath =
|
|
27192
|
+
const attemptsPath = path14.join(runDir, "jev", "attempts");
|
|
26867
27193
|
await ensureJevDirectory(attemptsPath);
|
|
26868
27194
|
const attemptsDir = await fileInsideWorkspace(context.directory, attemptsPath);
|
|
26869
|
-
if (
|
|
27195
|
+
if (path14.dirname(attemptsDir) !== path14.join(runDir, "jev")) throw new Error("A pasta de tentativas tem de pertencer ao run Jev.");
|
|
26870
27196
|
for (const batch of batches) {
|
|
26871
27197
|
context.abort.throwIfAborted();
|
|
26872
27198
|
const batchId = batch.batch_id;
|
|
26873
27199
|
if (typeof batchId !== "string" || !/^batch-[0-9]{4}-[A-Za-z0-9._-]+$/.test(batchId) || typeof batch.request_file !== "string" || typeof batch.request_fingerprint !== "string") {
|
|
26874
27200
|
throw new Error("O plano Jev cont\xE9m um lote inv\xE1lido.");
|
|
26875
27201
|
}
|
|
26876
|
-
const acceptedFile =
|
|
26877
|
-
const responseFile =
|
|
27202
|
+
const acceptedFile = path14.join(runDir, "jev", "accepted", `${batchId}.json`);
|
|
27203
|
+
const responseFile = path14.join(responseDir, `${batchId}.response.json`);
|
|
26878
27204
|
const requestFile = await fileInsideWorkspace(context.directory, batch.request_file);
|
|
26879
|
-
if (
|
|
26880
|
-
const request = JSON.parse(await
|
|
27205
|
+
if (path14.dirname(requestFile) !== path14.join(runDir, "jev", "requests")) throw new Error(`${batchId}: pedido fora do run.`);
|
|
27206
|
+
const request = JSON.parse(await readFile13(requestFile, "utf8"));
|
|
26881
27207
|
const fingerprint = createHash7("sha256").update(canonicalJson(request)).digest("hex");
|
|
26882
27208
|
if (fingerprint !== batch.request_fingerprint) throw new Error(`${batchId}: fingerprint do pedido n\xE3o corresponde ao plano.`);
|
|
26883
27209
|
if (await fileExists(acceptedFile)) {
|
|
@@ -26890,9 +27216,9 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
|
|
|
26890
27216
|
skipped++;
|
|
26891
27217
|
continue;
|
|
26892
27218
|
}
|
|
26893
|
-
const attemptsFile =
|
|
27219
|
+
const attemptsFile = path14.join(attemptsDir, `${batchId}.json`);
|
|
26894
27220
|
let attempts = { request_fingerprint: fingerprint, attempts: 0, response_files: [] };
|
|
26895
|
-
if (await fileExists(attemptsFile)) attempts = JSON.parse(await
|
|
27221
|
+
if (await fileExists(attemptsFile)) attempts = JSON.parse(await readFile13(attemptsFile, "utf8"));
|
|
26896
27222
|
else if (interrupted.batch_id === batchId) {
|
|
26897
27223
|
if (interrupted.request_fingerprint !== fingerprint) throw new Error(`${batchId}: fingerprint da chamada interrompida n\xE3o corresponde ao plano.`);
|
|
26898
27224
|
attempts.attempts = 1;
|
|
@@ -26905,13 +27231,13 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
|
|
|
26905
27231
|
if (!await fileExists(attemptsFile) && attempts.attempts > 0) await persistAttempts();
|
|
26906
27232
|
const stop = (error45, detail = {}) => JSON.stringify({ verified: false, saved, skipped, recovered, repeated, stopped_at: batchId, ...detail, error: error45 });
|
|
26907
27233
|
const recoverResponse = async () => {
|
|
26908
|
-
const legacyAllocations = interrupted.batch_id === batchId && interrupted.request_fingerprint === fingerprint ? (await
|
|
27234
|
+
const legacyAllocations = interrupted.batch_id === batchId && interrupted.request_fingerprint === fingerprint ? (await readdir6(responseDir)).filter((name) => name.startsWith(".forge-decision-")).map((name) => path14.join(responseDir, name, "response.json")) : [];
|
|
26909
27235
|
const candidates = [...attempts.response_files, ...legacyAllocations];
|
|
26910
27236
|
for (const candidate of new Set(candidates)) {
|
|
26911
27237
|
if (typeof candidate !== "string") throw new Error("Registo de recupera\xE7\xE3o inv\xE1lido.");
|
|
26912
27238
|
if (!await fileExists(candidate)) continue;
|
|
26913
27239
|
const file2 = await fileInsideWorkspace(context.directory, candidate);
|
|
26914
|
-
if (
|
|
27240
|
+
if (path14.dirname(path14.dirname(file2)) !== responseDir) throw new Error("Resposta recuper\xE1vel fora da pasta do lote.");
|
|
26915
27241
|
try {
|
|
26916
27242
|
await validateSavedDecision(file2, request);
|
|
26917
27243
|
} catch {
|
|
@@ -26970,7 +27296,7 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
|
|
|
26970
27296
|
let identical = false;
|
|
26971
27297
|
if (error45.code === "EEXIST") {
|
|
26972
27298
|
try {
|
|
26973
|
-
identical = await
|
|
27299
|
+
identical = await readFile13(source, "utf8") === await readFile13(responseFile, "utf8");
|
|
26974
27300
|
} catch {
|
|
26975
27301
|
}
|
|
26976
27302
|
}
|
|
@@ -26978,7 +27304,7 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
|
|
|
26978
27304
|
return stop("Resposta conclu\xEDda mas n\xE3o guardada no destino do lote; resolver a grava\xE7\xE3o e retomar sem nova chamada.", { recovery_file: source, persistence_code: error45.code });
|
|
26979
27305
|
}
|
|
26980
27306
|
}
|
|
26981
|
-
await unlink(source).then(() => rmdir(
|
|
27307
|
+
await unlink(source).then(() => rmdir(path14.dirname(source))).catch(() => void 0);
|
|
26982
27308
|
saved++;
|
|
26983
27309
|
if (args.batch_id) return JSON.stringify({ ...await validateSavedDecision(responseFile, request), response_file: responseFile, repeated });
|
|
26984
27310
|
}
|
|
@@ -27056,14 +27382,14 @@ function createForgeFeedbackTool(forgeBaseUrl, paths) {
|
|
|
27056
27382
|
}
|
|
27057
27383
|
});
|
|
27058
27384
|
}
|
|
27059
|
-
async function synchronizeAtStartup(forgeBaseUrl,
|
|
27385
|
+
async function synchronizeAtStartup(forgeBaseUrl, observe, localConfig, input) {
|
|
27060
27386
|
const paths = resolveStartupPaths();
|
|
27061
27387
|
const before = await managedProjectionNames(paths);
|
|
27062
27388
|
let credentials;
|
|
27063
27389
|
let forgeConfigVerified = false;
|
|
27064
27390
|
let pluginUpdate;
|
|
27065
27391
|
let decisionBaseUrl = forgeBaseUrl;
|
|
27066
|
-
const runtime = await
|
|
27392
|
+
const runtime = await observe();
|
|
27067
27393
|
try {
|
|
27068
27394
|
await retireDebugCapture(paths);
|
|
27069
27395
|
credentials = await readForgeCredentials(paths, forgeBaseUrl);
|
|
@@ -27072,7 +27398,7 @@ async function synchronizeAtStartup(forgeBaseUrl, input, localConfig) {
|
|
|
27072
27398
|
forgeConfigVerified = true;
|
|
27073
27399
|
const result = localConfig ? await syncLocalWorker(paths, credentials, manifest) : await applyWorkPackManifest(paths, credentials, manifest, {});
|
|
27074
27400
|
if (localConfig) {
|
|
27075
|
-
const config2 =
|
|
27401
|
+
const config2 = objectRecord2(parseJsonc(await readFile13(paths.opencodeConfigPath, "utf8")));
|
|
27076
27402
|
const targetVersion = configuredWorkPackSyncPluginVersion(config2);
|
|
27077
27403
|
if (targetVersion) pluginUpdate = { targetVersion, restartRequired: targetVersion !== PLUGIN_VERSION };
|
|
27078
27404
|
if (pluginUpdate?.restartRequired) {
|
|
@@ -27102,7 +27428,7 @@ async function synchronizeAtStartup(forgeBaseUrl, input, localConfig) {
|
|
|
27102
27428
|
installed: result.installed,
|
|
27103
27429
|
removed: result.removed
|
|
27104
27430
|
});
|
|
27105
|
-
return { paths, before, after, forgeConfigVerified, decisionBaseUrl };
|
|
27431
|
+
return { paths, before, after, forgeConfigVerified, decisionBaseUrl, manifest };
|
|
27106
27432
|
} catch (error45) {
|
|
27107
27433
|
const message = safeErrorMessage(error45);
|
|
27108
27434
|
console.error("[Forge work-pack sync] Startup sync failed:", message);
|
|
@@ -27124,8 +27450,8 @@ async function synchronizeAtStartup(forgeBaseUrl, input, localConfig) {
|
|
|
27124
27450
|
}
|
|
27125
27451
|
async function savedGatewayBaseUrl(paths, credentials, forgeBaseUrl) {
|
|
27126
27452
|
try {
|
|
27127
|
-
const config2 =
|
|
27128
|
-
const options =
|
|
27453
|
+
const config2 = objectRecord2(parseJsonc(await readFile13(paths.opencodeConfigPath, "utf8")));
|
|
27454
|
+
const options = objectRecord2(objectRecord2(objectRecord2(config2.provider).forge).options);
|
|
27129
27455
|
if (options.apiKey !== credentials.forgeApiKey || typeof options.baseURL !== "string" || !options.baseURL.endsWith("/v1")) return void 0;
|
|
27130
27456
|
const origin = options.baseURL.slice(0, -"/v1".length);
|
|
27131
27457
|
return origin === forgeBaseUrl ? origin : resolveDecisionBaseUrl(origin, forgeBaseUrl);
|
|
@@ -27149,7 +27475,7 @@ function resolveStartupPaths() {
|
|
|
27149
27475
|
return resolvePaths(void 0, void 0, env);
|
|
27150
27476
|
}
|
|
27151
27477
|
async function readForgeCredentials(paths, forgeBaseUrl) {
|
|
27152
|
-
const raw = await
|
|
27478
|
+
const raw = await readFile13(paths.opencodeAuthPath, "utf8").catch((error45) => {
|
|
27153
27479
|
if (error45.code === "ENOENT") return void 0;
|
|
27154
27480
|
throw error45;
|
|
27155
27481
|
});
|
|
@@ -27189,67 +27515,13 @@ function parseForgeBaseUrl(options) {
|
|
|
27189
27515
|
}
|
|
27190
27516
|
return url2.origin;
|
|
27191
27517
|
}
|
|
27192
|
-
|
|
27193
|
-
const agents = /* @__PURE__ */ new Set();
|
|
27194
|
-
const commands = /* @__PURE__ */ new Set();
|
|
27195
|
-
const entries = await readdir5(paths.skillsDir, { withFileTypes: true }).catch((error45) => {
|
|
27196
|
-
if (error45.code === "ENOENT") return [];
|
|
27197
|
-
throw error45;
|
|
27198
|
-
});
|
|
27199
|
-
for (const entry of entries) {
|
|
27200
|
-
if (!entry.isDirectory()) continue;
|
|
27201
|
-
const folder = path12.join(paths.skillsDir, entry.name);
|
|
27202
|
-
const marker = await readFile11(path12.join(folder, ".forge-version"), "utf8").catch(() => "");
|
|
27203
|
-
if (!marker.trim()) continue;
|
|
27204
|
-
for (const name of await readProjectionRecord(path12.join(folder, ".forge-agents"))) agents.add(stripMarkdownExtension(name));
|
|
27205
|
-
for (const name of await readProjectionRecord(path12.join(folder, ".forge-commands"))) commands.add(stripMarkdownExtension(name));
|
|
27206
|
-
}
|
|
27207
|
-
return { agents, commands };
|
|
27208
|
-
}
|
|
27209
|
-
async function readProjectionRecord(filePath) {
|
|
27210
|
-
const raw = await readFile11(filePath, "utf8").catch(() => "");
|
|
27211
|
-
return raw.split("\n").map((line) => line.trim()).filter(
|
|
27212
|
-
(line) => line.endsWith(".md") && !line.includes("/") && !line.includes("\\") && line !== ".."
|
|
27213
|
-
);
|
|
27214
|
-
}
|
|
27215
|
-
async function projectCurrentExtensions(config2, state) {
|
|
27216
|
-
const agents = objectRecord(config2.agent);
|
|
27217
|
-
const commands = objectRecord(config2.command);
|
|
27218
|
-
for (const name of state.before.agents) if (!state.after.agents.has(name)) delete agents[name];
|
|
27219
|
-
for (const name of state.before.commands) if (!state.after.commands.has(name)) delete commands[name];
|
|
27220
|
-
for (const name of state.after.agents) {
|
|
27221
|
-
agents[name] = await parseMarkdownConfig(path12.join(state.paths.agentsDir, `${name}.md`), "prompt");
|
|
27222
|
-
}
|
|
27223
|
-
for (const name of state.after.commands) {
|
|
27224
|
-
commands[name] = await parseMarkdownConfig(path12.join(state.paths.commandsDir, `${name}.md`), "template");
|
|
27225
|
-
}
|
|
27226
|
-
config2.agent = agents;
|
|
27227
|
-
config2.command = commands;
|
|
27228
|
-
}
|
|
27229
|
-
async function parseMarkdownConfig(filePath, bodyField) {
|
|
27230
|
-
const raw = await readFile11(filePath, "utf8");
|
|
27231
|
-
const match = /^---\r?\n([\s\S]+?)\r?\n---\r?\n?([\s\S]*)$/.exec(raw);
|
|
27232
|
-
if (!match) throw new Error(`A extens\xE3o Forge ${path12.basename(filePath)} n\xE3o tem frontmatter v\xE1lido`);
|
|
27233
|
-
const data = (0, import_yaml.parse)(match[1]);
|
|
27234
|
-
if (!data || typeof data !== "object" || Array.isArray(data)) {
|
|
27235
|
-
throw new Error(`A extens\xE3o Forge ${path12.basename(filePath)} n\xE3o tem frontmatter v\xE1lido`);
|
|
27236
|
-
}
|
|
27237
|
-
const config2 = { ...data, [bodyField]: match[2].trim() };
|
|
27238
|
-
if (bodyField === "prompt" && typeof config2.permission === "string" && ["allow", "ask", "deny"].includes(config2.permission)) {
|
|
27239
|
-
config2.permission = { "*": config2.permission };
|
|
27240
|
-
}
|
|
27241
|
-
return config2;
|
|
27242
|
-
}
|
|
27243
|
-
function objectRecord(value) {
|
|
27518
|
+
function objectRecord2(value) {
|
|
27244
27519
|
return value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
|
|
27245
27520
|
}
|
|
27246
|
-
function stripMarkdownExtension(filename) {
|
|
27247
|
-
return filename.slice(0, -3);
|
|
27248
|
-
}
|
|
27249
27521
|
async function writeStatus(paths, value) {
|
|
27250
27522
|
await mkdir7(paths.forgeDir, { recursive: true });
|
|
27251
|
-
const target =
|
|
27252
|
-
const temporary =
|
|
27523
|
+
const target = path14.join(paths.forgeDir, STATUS_FILENAME);
|
|
27524
|
+
const temporary = path14.join(paths.forgeDir, `.${STATUS_FILENAME}.${process.pid}.tmp`);
|
|
27253
27525
|
await writeFile8(temporary, `${JSON.stringify(value, null, 2)}
|
|
27254
27526
|
`, { mode: 384 });
|
|
27255
27527
|
await rename8(temporary, target);
|
|
@@ -27260,7 +27532,8 @@ function safeErrorMessage(error45) {
|
|
|
27260
27532
|
}
|
|
27261
27533
|
var ForgeWorkPackSyncPlugin = {
|
|
27262
27534
|
id: "minimal-forge.work-pack-sync",
|
|
27263
|
-
server: ForgeWorkPackSyncServer
|
|
27535
|
+
server: ForgeWorkPackSyncServer,
|
|
27536
|
+
setup: ForgeWorkPackSyncSetup
|
|
27264
27537
|
};
|
|
27265
27538
|
var workPackSyncPlugin_default = ForgeWorkPackSyncPlugin;
|
|
27266
27539
|
export {
|