minimal-forge-work-pack-sync 0.1.48 → 0.1.51
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 +730 -422
- 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,11 @@ 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
|
+
|
|
7373
7378
|
// packages/shared/src/contracts/models.ts
|
|
7374
7379
|
var BUILT_IN_OPENROUTER_MODELS = [
|
|
7375
7380
|
{
|
|
@@ -7610,7 +7615,7 @@ var WORKER_FEEDBACK_MAX_MESSAGE_LENGTH = 24e3;
|
|
|
7610
7615
|
// packages/shared/src/contracts/settings.ts
|
|
7611
7616
|
var DOCUMENT_READER_AGENT = "document-reader";
|
|
7612
7617
|
var OPENROUTER_ALIAS_PROVIDER_NAME = "OpenRouter (via Forge)";
|
|
7613
|
-
var WORK_PACK_SYNC_PLUGIN_VERSION = "0.1.
|
|
7618
|
+
var WORK_PACK_SYNC_PLUGIN_VERSION = "0.1.51";
|
|
7614
7619
|
var WORK_PACK_SYNC_PLUGIN_PACKAGE = `minimal-forge-work-pack-sync@${WORK_PACK_SYNC_PLUGIN_VERSION}`;
|
|
7615
7620
|
var WORK_PACK_SYNC_PLUGIN_FILENAME = `minimal-forge-work-pack-sync-${WORK_PACK_SYNC_PLUGIN_VERSION}.tgz`;
|
|
7616
7621
|
var FIRECRAWL_KEYLESS_MCP_NAME = "firecrawl";
|
|
@@ -7838,11 +7843,102 @@ function integrityKind(summary) {
|
|
|
7838
7843
|
return "match";
|
|
7839
7844
|
}
|
|
7840
7845
|
|
|
7846
|
+
// packages/cli/src/workPackExtensions.ts
|
|
7847
|
+
async function managedProjectionNames(paths, slugs) {
|
|
7848
|
+
const agents = /* @__PURE__ */ new Set();
|
|
7849
|
+
const commands = /* @__PURE__ */ new Set();
|
|
7850
|
+
if (slugs?.size === 0) return { agents, commands };
|
|
7851
|
+
const entries = await readdir(paths.skillsDir, { withFileTypes: true }).catch((error45) => {
|
|
7852
|
+
if (error45.code === "ENOENT") return [];
|
|
7853
|
+
throw error45;
|
|
7854
|
+
});
|
|
7855
|
+
for (const entry of entries) {
|
|
7856
|
+
if (!entry.isDirectory() || slugs && !slugs.has(entry.name)) continue;
|
|
7857
|
+
const folder = path.join(paths.skillsDir, entry.name);
|
|
7858
|
+
const marker = await readFile(path.join(folder, ".forge-version"), "utf8").catch(() => "");
|
|
7859
|
+
if (!marker.trim()) continue;
|
|
7860
|
+
for (const name of await readProjectionRecord(path.join(folder, ".forge-agents"))) agents.add(stripMarkdownExtension(name));
|
|
7861
|
+
for (const name of await readProjectionRecord(path.join(folder, ".forge-commands"))) commands.add(stripMarkdownExtension(name));
|
|
7862
|
+
}
|
|
7863
|
+
return { agents, commands };
|
|
7864
|
+
}
|
|
7865
|
+
async function readProjectionRecord(filePath) {
|
|
7866
|
+
const raw = await readFile(filePath, "utf8").catch(() => "");
|
|
7867
|
+
return raw.split("\n").map((line) => line.trim()).filter(
|
|
7868
|
+
(line) => line.endsWith(".md") && !line.includes("/") && !line.includes("\\") && line !== ".."
|
|
7869
|
+
);
|
|
7870
|
+
}
|
|
7871
|
+
async function projectCurrentExtensions(config2, state) {
|
|
7872
|
+
const agents = objectRecord(config2.agent);
|
|
7873
|
+
const commands = objectRecord(config2.command);
|
|
7874
|
+
for (const name of state.before.agents) if (!state.after.agents.has(name)) delete agents[name];
|
|
7875
|
+
for (const name of state.before.commands) if (!state.after.commands.has(name)) delete commands[name];
|
|
7876
|
+
for (const name of state.after.agents) {
|
|
7877
|
+
agents[name] = await parseMarkdownConfig(path.join(state.paths.agentsDir, `${name}.md`), "prompt");
|
|
7878
|
+
}
|
|
7879
|
+
for (const name of state.after.commands) {
|
|
7880
|
+
commands[name] = await parseMarkdownConfig(path.join(state.paths.commandsDir, `${name}.md`), "template");
|
|
7881
|
+
}
|
|
7882
|
+
config2.agent = agents;
|
|
7883
|
+
config2.command = commands;
|
|
7884
|
+
}
|
|
7885
|
+
async function refreshPartialProjections(config2, previous, paths, before, result) {
|
|
7886
|
+
const existing = objectRecord(previous);
|
|
7887
|
+
const agents = objectRecord(existing.agent);
|
|
7888
|
+
const commands = objectRecord(existing.command);
|
|
7889
|
+
if (!before.agents.has(DOCUMENT_READER_AGENT)) delete agents[DOCUMENT_READER_AGENT];
|
|
7890
|
+
for (const file2 of result.removedManagedPaths) {
|
|
7891
|
+
if (path.extname(file2) !== ".md") continue;
|
|
7892
|
+
const directory = path.dirname(file2);
|
|
7893
|
+
const name = path.basename(file2, ".md");
|
|
7894
|
+
if (directory === paths.agentsDir) delete agents[name];
|
|
7895
|
+
if (directory === paths.commandsDir) delete commands[name];
|
|
7896
|
+
}
|
|
7897
|
+
config2.agent = { ...objectRecord(config2.agent), ...agents };
|
|
7898
|
+
config2.command = commands;
|
|
7899
|
+
const confirmed = new Set(result.workPacks.outcomes.filter(
|
|
7900
|
+
({ action, status }) => action === "install" && (status === "installed" || status === "unchanged")
|
|
7901
|
+
).map(({ slug }) => slug));
|
|
7902
|
+
await projectInstalledExtensions(config2, paths, confirmed);
|
|
7903
|
+
}
|
|
7904
|
+
async function parseMarkdownConfig(filePath, bodyField) {
|
|
7905
|
+
const raw = await readFile(filePath, "utf8");
|
|
7906
|
+
const match = /^---\r?\n([\s\S]+?)\r?\n---\r?\n?([\s\S]*)$/.exec(raw);
|
|
7907
|
+
if (!match) throw new Error(`A extens\xE3o Forge ${path.basename(filePath)} n\xE3o tem frontmatter v\xE1lido`);
|
|
7908
|
+
const data = (0, import_yaml.parse)(match[1]);
|
|
7909
|
+
if (!data || typeof data !== "object" || Array.isArray(data)) {
|
|
7910
|
+
throw new Error(`A extens\xE3o Forge ${path.basename(filePath)} n\xE3o tem frontmatter v\xE1lido`);
|
|
7911
|
+
}
|
|
7912
|
+
const config2 = { ...data, [bodyField]: match[2].trim() };
|
|
7913
|
+
if (bodyField === "prompt" && typeof config2.permission === "string" && ["allow", "ask", "deny"].includes(config2.permission)) {
|
|
7914
|
+
config2.permission = { "*": config2.permission };
|
|
7915
|
+
}
|
|
7916
|
+
return config2;
|
|
7917
|
+
}
|
|
7918
|
+
function objectRecord(value) {
|
|
7919
|
+
return value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
|
|
7920
|
+
}
|
|
7921
|
+
function stripMarkdownExtension(filename) {
|
|
7922
|
+
return filename.slice(0, -3);
|
|
7923
|
+
}
|
|
7924
|
+
async function projectInstalledExtensions(config2, paths, slugs) {
|
|
7925
|
+
const names = await managedProjectionNames(paths, slugs);
|
|
7926
|
+
await projectCurrentExtensions(config2, { paths, before: names, after: names });
|
|
7927
|
+
for (const key of ["agent", "command"]) if (Object.keys(objectRecord(config2[key])).length === 0) delete config2[key];
|
|
7928
|
+
}
|
|
7929
|
+
|
|
7841
7930
|
// packages/cli/src/runtimeObservation.ts
|
|
7842
7931
|
var UNKNOWN_RUNTIME = {
|
|
7843
7932
|
opencode: { status: "unknown" },
|
|
7844
7933
|
openwork: { status: "unknown" }
|
|
7845
7934
|
};
|
|
7935
|
+
function observeOpenCode2Runtime(app) {
|
|
7936
|
+
const version2 = runtimeVersion(app?.version);
|
|
7937
|
+
return {
|
|
7938
|
+
opencode: version2 ? { status: "known", version: version2, source: "engine-health" } : { status: "unknown" },
|
|
7939
|
+
openwork: { status: "unknown" }
|
|
7940
|
+
};
|
|
7941
|
+
}
|
|
7846
7942
|
async function observeRuntime(input) {
|
|
7847
7943
|
const engine = input?.serverUrl;
|
|
7848
7944
|
const engineHeaders = {};
|
|
@@ -7892,7 +7988,7 @@ async function probeHealth(url2, route, headers, healthyField, source) {
|
|
|
7892
7988
|
import { spawnSync as nodeSpawnSync } from "node:child_process";
|
|
7893
7989
|
import { randomUUID } from "node:crypto";
|
|
7894
7990
|
import { chmod, mkdir, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
7895
|
-
import
|
|
7991
|
+
import path2 from "node:path";
|
|
7896
7992
|
async function protectOwnerOnlyPath(filePath, kind, options = {}) {
|
|
7897
7993
|
const platform = options.platform ?? process.platform;
|
|
7898
7994
|
if (platform !== "win32") {
|
|
@@ -7934,7 +8030,7 @@ async function assertExistingDirectoryIsSafe(directory, options) {
|
|
|
7934
8030
|
}
|
|
7935
8031
|
}
|
|
7936
8032
|
async function prepareOwnerOnlyFileDestination(filePath, options = {}) {
|
|
7937
|
-
const directory =
|
|
8033
|
+
const directory = path2.dirname(filePath);
|
|
7938
8034
|
let existing;
|
|
7939
8035
|
try {
|
|
7940
8036
|
existing = await stat(directory);
|
|
@@ -7958,9 +8054,9 @@ async function prepareOwnerOnlyFileDestination(filePath, options = {}) {
|
|
|
7958
8054
|
else await assertExistingDirectoryIsSafe(directory, options);
|
|
7959
8055
|
}
|
|
7960
8056
|
async function writeOwnerOnlyTextAtomic(filePath, content, options = {}) {
|
|
7961
|
-
const directory =
|
|
8057
|
+
const directory = path2.dirname(filePath);
|
|
7962
8058
|
await prepareOwnerOnlyFileDestination(filePath, options);
|
|
7963
|
-
const temporary =
|
|
8059
|
+
const temporary = path2.join(directory, `.${path2.basename(filePath)}.${randomUUID()}.tmp`);
|
|
7964
8060
|
try {
|
|
7965
8061
|
await writeFile(temporary, content, { flag: "wx", mode: 384 });
|
|
7966
8062
|
await protectOwnerOnlyPath(temporary, "file", options);
|
|
@@ -8233,16 +8329,16 @@ async function readForgeCredentials() {
|
|
|
8233
8329
|
}
|
|
8234
8330
|
|
|
8235
8331
|
// packages/cli/src/retireDebugCapture.ts
|
|
8236
|
-
import { lstat, readFile, rename as rename2, writeFile as writeFile2 } from "node:fs/promises";
|
|
8332
|
+
import { lstat, readFile as readFile2, rename as rename2, writeFile as writeFile2 } from "node:fs/promises";
|
|
8237
8333
|
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
8238
|
-
import
|
|
8334
|
+
import path3 from "node:path";
|
|
8239
8335
|
var MANAGED_HEADER = "// Managed by Forge sync. Do not edit.";
|
|
8240
8336
|
var RETIRED_DEBUG_PLUGIN = `${MANAGED_HEADER}
|
|
8241
8337
|
// Detailed capture retired. Keep this module loadable for old OpenCode configs.
|
|
8242
8338
|
export const ForgeDebugTrace = async () => ({})
|
|
8243
8339
|
`;
|
|
8244
8340
|
async function retireDebugCapture(paths) {
|
|
8245
|
-
const configPath =
|
|
8341
|
+
const configPath = path3.join(paths.forgeDir, "debug-trace.json");
|
|
8246
8342
|
const raw = await readRegularFile(configPath);
|
|
8247
8343
|
if (raw !== void 0) {
|
|
8248
8344
|
const config2 = JSON.parse(raw);
|
|
@@ -8251,7 +8347,7 @@ async function retireDebugCapture(paths) {
|
|
|
8251
8347
|
`);
|
|
8252
8348
|
}
|
|
8253
8349
|
}
|
|
8254
|
-
const pluginPath =
|
|
8350
|
+
const pluginPath = path3.join(paths.pluginDir, "forge-debug-trace.js");
|
|
8255
8351
|
const plugin = await readRegularFile(pluginPath);
|
|
8256
8352
|
if (plugin?.startsWith(MANAGED_HEADER) && plugin !== RETIRED_DEBUG_PLUGIN) {
|
|
8257
8353
|
await replaceFile(pluginPath, RETIRED_DEBUG_PLUGIN);
|
|
@@ -8259,12 +8355,12 @@ async function retireDebugCapture(paths) {
|
|
|
8259
8355
|
}
|
|
8260
8356
|
async function readRegularFile(filename) {
|
|
8261
8357
|
try {
|
|
8262
|
-
const directory = await lstat(
|
|
8358
|
+
const directory = await lstat(path3.dirname(filename));
|
|
8263
8359
|
const info = await lstat(filename);
|
|
8264
8360
|
if (!directory.isDirectory() || !info.isFile() || info.isSymbolicLink()) {
|
|
8265
8361
|
throw new Error("Legacy debug capture path must be a regular file in a real directory");
|
|
8266
8362
|
}
|
|
8267
|
-
return await
|
|
8363
|
+
return await readFile2(filename, "utf8");
|
|
8268
8364
|
} catch (error45) {
|
|
8269
8365
|
if (error45.code === "ENOENT") return void 0;
|
|
8270
8366
|
throw error45;
|
|
@@ -8483,12 +8579,6 @@ function createReasoningLoopGuard(client, log = console.error, report = () => vo
|
|
|
8483
8579
|
};
|
|
8484
8580
|
}
|
|
8485
8581
|
|
|
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
8582
|
// node_modules/@opencode-ai/plugin/node_modules/zod/v4/classic/external.js
|
|
8493
8583
|
var external_exports = {};
|
|
8494
8584
|
__export(external_exports, {
|
|
@@ -9220,10 +9310,10 @@ function mergeDefs(...defs) {
|
|
|
9220
9310
|
function cloneDef(schema) {
|
|
9221
9311
|
return mergeDefs(schema._zod.def);
|
|
9222
9312
|
}
|
|
9223
|
-
function getElementAtPath(obj,
|
|
9224
|
-
if (!
|
|
9313
|
+
function getElementAtPath(obj, path15) {
|
|
9314
|
+
if (!path15)
|
|
9225
9315
|
return obj;
|
|
9226
|
-
return
|
|
9316
|
+
return path15.reduce((acc, key) => acc?.[key], obj);
|
|
9227
9317
|
}
|
|
9228
9318
|
function promiseAllObject(promisesObj) {
|
|
9229
9319
|
const keys = Object.keys(promisesObj);
|
|
@@ -9584,11 +9674,11 @@ function aborted(x, startIndex = 0) {
|
|
|
9584
9674
|
}
|
|
9585
9675
|
return false;
|
|
9586
9676
|
}
|
|
9587
|
-
function prefixIssues(
|
|
9677
|
+
function prefixIssues(path15, issues) {
|
|
9588
9678
|
return issues.map((iss) => {
|
|
9589
9679
|
var _a;
|
|
9590
9680
|
(_a = iss).path ?? (_a.path = []);
|
|
9591
|
-
iss.path.unshift(
|
|
9681
|
+
iss.path.unshift(path15);
|
|
9592
9682
|
return iss;
|
|
9593
9683
|
});
|
|
9594
9684
|
}
|
|
@@ -9756,7 +9846,7 @@ function treeifyError(error45, _mapper) {
|
|
|
9756
9846
|
return issue2.message;
|
|
9757
9847
|
};
|
|
9758
9848
|
const result = { errors: [] };
|
|
9759
|
-
const processError = (error46,
|
|
9849
|
+
const processError = (error46, path15 = []) => {
|
|
9760
9850
|
var _a, _b;
|
|
9761
9851
|
for (const issue2 of error46.issues) {
|
|
9762
9852
|
if (issue2.code === "invalid_union" && issue2.errors.length) {
|
|
@@ -9766,7 +9856,7 @@ function treeifyError(error45, _mapper) {
|
|
|
9766
9856
|
} else if (issue2.code === "invalid_element") {
|
|
9767
9857
|
processError({ issues: issue2.issues }, issue2.path);
|
|
9768
9858
|
} else {
|
|
9769
|
-
const fullpath = [...
|
|
9859
|
+
const fullpath = [...path15, ...issue2.path];
|
|
9770
9860
|
if (fullpath.length === 0) {
|
|
9771
9861
|
result.errors.push(mapper(issue2));
|
|
9772
9862
|
continue;
|
|
@@ -9798,8 +9888,8 @@ function treeifyError(error45, _mapper) {
|
|
|
9798
9888
|
}
|
|
9799
9889
|
function toDotPath(_path) {
|
|
9800
9890
|
const segs = [];
|
|
9801
|
-
const
|
|
9802
|
-
for (const seg of
|
|
9891
|
+
const path15 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
|
|
9892
|
+
for (const seg of path15) {
|
|
9803
9893
|
if (typeof seg === "number")
|
|
9804
9894
|
segs.push(`[${seg}]`);
|
|
9805
9895
|
else if (typeof seg === "symbol")
|
|
@@ -20911,10 +21001,153 @@ function tool(input) {
|
|
|
20911
21001
|
}
|
|
20912
21002
|
tool.schema = external_exports;
|
|
20913
21003
|
|
|
21004
|
+
// packages/cli/src/opencode2Adapter.ts
|
|
21005
|
+
var z = tool.schema;
|
|
21006
|
+
function openCode2Tool(name, definition, directoryOf) {
|
|
21007
|
+
const schema = z.object(definition.args);
|
|
21008
|
+
return {
|
|
21009
|
+
name,
|
|
21010
|
+
description: definition.description,
|
|
21011
|
+
input: z.toJSONSchema(schema, { io: "input" }),
|
|
21012
|
+
options: { codemode: false },
|
|
21013
|
+
async execute(input, context) {
|
|
21014
|
+
const parsed = schema.safeParse(input);
|
|
21015
|
+
if (!parsed.success) {
|
|
21016
|
+
const issues = parsed.error.issues.map((issue2) => `- ${issue2.path.join(".") || "root"}: ${issue2.message}`);
|
|
21017
|
+
throw new Error(`Invalid arguments for tool "${name}":
|
|
21018
|
+
${issues.join("\n")}
|
|
21019
|
+
|
|
21020
|
+
Update the arguments and call the tool again.`);
|
|
21021
|
+
}
|
|
21022
|
+
const directory = await directoryOf(context.sessionID);
|
|
21023
|
+
const result = await definition.execute(parsed.data, { directory, abort: context.signal });
|
|
21024
|
+
return openCode2Result(result);
|
|
21025
|
+
}
|
|
21026
|
+
};
|
|
21027
|
+
}
|
|
21028
|
+
function sessionDirectoryResolver(ctx) {
|
|
21029
|
+
return async (sessionID) => {
|
|
21030
|
+
try {
|
|
21031
|
+
const directory = (await ctx.session.get({ sessionID })).location.directory;
|
|
21032
|
+
if (typeof directory === "string" && directory.length > 0) return directory;
|
|
21033
|
+
} catch {
|
|
21034
|
+
}
|
|
21035
|
+
return ctx.location.directory;
|
|
21036
|
+
};
|
|
21037
|
+
}
|
|
21038
|
+
function openCode2Result(result) {
|
|
21039
|
+
if (typeof result === "string") return { content: result };
|
|
21040
|
+
const files = (result.attachments ?? []).map((attachment) => ({
|
|
21041
|
+
type: "file",
|
|
21042
|
+
uri: attachment.url,
|
|
21043
|
+
mime: attachment.mime,
|
|
21044
|
+
...attachment.filename ? { name: attachment.filename } : {}
|
|
21045
|
+
}));
|
|
21046
|
+
return {
|
|
21047
|
+
content: files.length > 0 ? [{ type: "text", text: result.output }, ...files] : result.output,
|
|
21048
|
+
...result.metadata ? { metadata: result.metadata } : {}
|
|
21049
|
+
};
|
|
21050
|
+
}
|
|
21051
|
+
function completedSkillCall(event) {
|
|
21052
|
+
if (event.tool !== "skill" || event.status !== "completed") return void 0;
|
|
21053
|
+
const name = isRecord2(event.input) ? event.input.id : void 0;
|
|
21054
|
+
return { sessionID: event.sessionID, callID: event.id, name };
|
|
21055
|
+
}
|
|
21056
|
+
function guardEventsFor(event) {
|
|
21057
|
+
const data = isRecord2(event.data) ? event.data : void 0;
|
|
21058
|
+
const sessionID = data?.sessionID;
|
|
21059
|
+
if (!data || typeof sessionID !== "string") return [];
|
|
21060
|
+
const idle = { type: "session.idle", properties: { sessionID } };
|
|
21061
|
+
const error45 = { type: "session.error", properties: { sessionID } };
|
|
21062
|
+
switch (event.type) {
|
|
21063
|
+
case "session.reasoning.started":
|
|
21064
|
+
case "session.reasoning.delta":
|
|
21065
|
+
case "session.reasoning.ended": {
|
|
21066
|
+
const messageID = data.assistantMessageID;
|
|
21067
|
+
if (typeof messageID !== "string" || typeof data.ordinal !== "number") return [];
|
|
21068
|
+
const partID = `${messageID}:${data.ordinal}`;
|
|
21069
|
+
const announce = { type: "message.part.updated", properties: { part: { id: partID, sessionID, type: "reasoning", text: "" } } };
|
|
21070
|
+
if (event.type === "session.reasoning.started") return [announce];
|
|
21071
|
+
if (event.type === "session.reasoning.ended") {
|
|
21072
|
+
return typeof data.text === "string" ? [{ type: "message.part.updated", properties: { part: { id: partID, sessionID, type: "reasoning", text: data.text } } }] : [];
|
|
21073
|
+
}
|
|
21074
|
+
return typeof data.delta === "string" ? [announce, { type: "message.part.delta", properties: { sessionID, messageID, partID, field: "text", delta: data.delta } }] : [];
|
|
21075
|
+
}
|
|
21076
|
+
case "session.execution.succeeded":
|
|
21077
|
+
return [idle];
|
|
21078
|
+
case "session.execution.failed":
|
|
21079
|
+
case "session.execution.interrupted":
|
|
21080
|
+
return [error45, idle];
|
|
21081
|
+
case "session.deleted":
|
|
21082
|
+
return [{ type: "session.deleted", properties: { info: { id: sessionID } } }];
|
|
21083
|
+
default:
|
|
21084
|
+
return [];
|
|
21085
|
+
}
|
|
21086
|
+
}
|
|
21087
|
+
function openCode2GuardClient(ctx) {
|
|
21088
|
+
return {
|
|
21089
|
+
session: {
|
|
21090
|
+
abort: ({ path: path15 }) => ctx.session.interrupt({ sessionID: path15.id }),
|
|
21091
|
+
// The resume prompt runs with the session's current agent and model, so `body.agent` and `body.model` are not sent.
|
|
21092
|
+
promptAsync: ({ path: path15, body }) => ctx.session.prompt({ sessionID: path15.id, text: body.parts.map((part) => part.text).join("\n\n") })
|
|
21093
|
+
}
|
|
21094
|
+
};
|
|
21095
|
+
}
|
|
21096
|
+
var RESUBSCRIBE_DELAY_MS = 1e3;
|
|
21097
|
+
var MAX_CONSECUTIVE_STREAM_FAILURES = 5;
|
|
21098
|
+
function startReasoningLoopGuard(ctx, report, log = console.error) {
|
|
21099
|
+
const guard = createReasoningLoopGuard(openCode2GuardClient(ctx), log, report);
|
|
21100
|
+
const controller = new AbortController();
|
|
21101
|
+
const { signal } = controller;
|
|
21102
|
+
void (async () => {
|
|
21103
|
+
let failures = 0;
|
|
21104
|
+
while (!signal.aborted && failures < MAX_CONSECUTIVE_STREAM_FAILURES) {
|
|
21105
|
+
try {
|
|
21106
|
+
for await (const event of ctx.event.subscribe({ signal })) {
|
|
21107
|
+
failures = 0;
|
|
21108
|
+
try {
|
|
21109
|
+
for (const translated of guardEventsFor(event)) await guard({ event: translated });
|
|
21110
|
+
} catch (error45) {
|
|
21111
|
+
log(`[Forge reasoning guard] Event handling failed: ${error45 instanceof Error ? error45.message : String(error45)}`);
|
|
21112
|
+
}
|
|
21113
|
+
}
|
|
21114
|
+
return;
|
|
21115
|
+
} catch (error45) {
|
|
21116
|
+
if (signal.aborted) return;
|
|
21117
|
+
failures += 1;
|
|
21118
|
+
log(`[Forge reasoning guard] Event stream failed (${failures}/${MAX_CONSECUTIVE_STREAM_FAILURES}): ${error45 instanceof Error ? error45.message : String(error45)}`);
|
|
21119
|
+
await sleep(RESUBSCRIBE_DELAY_MS, signal);
|
|
21120
|
+
}
|
|
21121
|
+
}
|
|
21122
|
+
})();
|
|
21123
|
+
return () => controller.abort();
|
|
21124
|
+
}
|
|
21125
|
+
function sleep(ms2, signal) {
|
|
21126
|
+
return new Promise((resolve) => {
|
|
21127
|
+
if (signal.aborted) return resolve();
|
|
21128
|
+
const timer = setTimeout(done, ms2);
|
|
21129
|
+
timer.unref?.();
|
|
21130
|
+
signal.addEventListener("abort", done, { once: true });
|
|
21131
|
+
function done() {
|
|
21132
|
+
clearTimeout(timer);
|
|
21133
|
+
signal.removeEventListener("abort", done);
|
|
21134
|
+
resolve();
|
|
21135
|
+
}
|
|
21136
|
+
});
|
|
21137
|
+
}
|
|
21138
|
+
function isRecord2(value) {
|
|
21139
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
21140
|
+
}
|
|
21141
|
+
|
|
21142
|
+
// packages/cli/src/workPackSyncPlugin.ts
|
|
21143
|
+
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";
|
|
21144
|
+
import os5 from "node:os";
|
|
21145
|
+
import path14 from "node:path";
|
|
21146
|
+
|
|
20914
21147
|
// packages/cli/src/credentials.ts
|
|
20915
|
-
import { chmod as chmod2, mkdir as mkdir2, readFile as
|
|
21148
|
+
import { chmod as chmod2, mkdir as mkdir2, readFile as readFile3, rename as rename3, rm as rm2, writeFile as writeFile3 } from "node:fs/promises";
|
|
20916
21149
|
async function readCredentials(paths) {
|
|
20917
|
-
const raw = await
|
|
21150
|
+
const raw = await readFile3(paths.credentialsPath, "utf8");
|
|
20918
21151
|
const parsed = JSON.parse(raw);
|
|
20919
21152
|
if (!parsed.forgeApiKey || !parsed.forgeBaseUrl) {
|
|
20920
21153
|
throw new Error(`Ficheiro de credenciais inv\xE1lido em ${paths.credentialsPath}`);
|
|
@@ -20924,10 +21157,10 @@ async function readCredentials(paths) {
|
|
|
20924
21157
|
|
|
20925
21158
|
// packages/cli/src/paths.ts
|
|
20926
21159
|
import os from "node:os";
|
|
20927
|
-
import
|
|
21160
|
+
import path4 from "node:path";
|
|
20928
21161
|
import { existsSync } from "node:fs";
|
|
20929
21162
|
function resolvePaths(home = os.homedir(), platform = process.platform, env = process.env, exists2 = existsSync) {
|
|
20930
|
-
const pathApi = platform === "win32" ?
|
|
21163
|
+
const pathApi = platform === "win32" ? path4.win32 : path4.posix;
|
|
20931
21164
|
const userHome = platform === "win32" ? env.USERPROFILE ?? home : home;
|
|
20932
21165
|
const forgeConfigRoot = env.XDG_CONFIG_HOME ?? pathApi.join(userHome, ".config");
|
|
20933
21166
|
const forgeDir = pathApi.join(forgeConfigRoot, "forge");
|
|
@@ -21014,13 +21247,13 @@ async function reportWorkPackObservations(credentials, kind, workPacks, runtime
|
|
|
21014
21247
|
// packages/cli/src/workPackIntegrity.ts
|
|
21015
21248
|
import { createHash as createHash2 } from "node:crypto";
|
|
21016
21249
|
import { constants } from "node:fs";
|
|
21017
|
-
import { lstat as lstat3, open, readdir as
|
|
21018
|
-
import
|
|
21250
|
+
import { lstat as lstat3, open, readdir as readdir3 } from "node:fs/promises";
|
|
21251
|
+
import path6 from "node:path";
|
|
21019
21252
|
|
|
21020
21253
|
// packages/cli/src/workPackLocalState.ts
|
|
21021
21254
|
import { createHash } from "node:crypto";
|
|
21022
|
-
import { lstat as lstat2, mkdir as mkdir3, readFile as
|
|
21023
|
-
import
|
|
21255
|
+
import { lstat as lstat2, mkdir as mkdir3, readFile as readFile4, readdir as readdir2, rename as rename4, writeFile as writeFile4 } from "node:fs/promises";
|
|
21256
|
+
import path5 from "node:path";
|
|
21024
21257
|
var WORK_PACK_LOCAL_STATE_FILENAME = ".forge-installed-state.json";
|
|
21025
21258
|
async function writeWorkPackInstalledState(input) {
|
|
21026
21259
|
const tree = await digestPackTree(input.packDir);
|
|
@@ -21032,7 +21265,7 @@ async function writeWorkPackInstalledState(input) {
|
|
|
21032
21265
|
agents: digestProjectionContents(input.agents),
|
|
21033
21266
|
commands: digestProjectionContents(input.commands)
|
|
21034
21267
|
};
|
|
21035
|
-
await writeJsonAtomic(
|
|
21268
|
+
await writeJsonAtomic(path5.join(input.packDir, WORK_PACK_LOCAL_STATE_FILENAME), state);
|
|
21036
21269
|
}
|
|
21037
21270
|
async function checkWorkPackInstalledState(input) {
|
|
21038
21271
|
const state = await readInstalledState(input.packDir);
|
|
@@ -21048,13 +21281,13 @@ async function checkWorkPackTreeState(packDir, allowAdditional = false) {
|
|
|
21048
21281
|
async function adoptWorkPackInstalledState(input) {
|
|
21049
21282
|
const state = await readInstalledState(input.expectedPackDir);
|
|
21050
21283
|
if (!state || !await matchesInstalledState(input, state)) return false;
|
|
21051
|
-
await writeJsonAtomic(
|
|
21284
|
+
await writeJsonAtomic(path5.join(input.packDir, WORK_PACK_LOCAL_STATE_FILENAME), state);
|
|
21052
21285
|
return checkWorkPackInstalledState(input).then((result) => result === "match");
|
|
21053
21286
|
}
|
|
21054
21287
|
async function readInstalledState(packDir) {
|
|
21055
|
-
const info = await lstat2(
|
|
21288
|
+
const info = await lstat2(path5.join(packDir, WORK_PACK_LOCAL_STATE_FILENAME)).catch(() => void 0);
|
|
21056
21289
|
if (!info?.isFile() || info.isSymbolicLink() || info.size > 1024 * 1024) return void 0;
|
|
21057
|
-
const raw = await
|
|
21290
|
+
const raw = await readFile4(path5.join(packDir, WORK_PACK_LOCAL_STATE_FILENAME), "utf8").catch(() => void 0);
|
|
21058
21291
|
if (!raw) return void 0;
|
|
21059
21292
|
try {
|
|
21060
21293
|
return parseWorkPackFileManifest(JSON.parse(raw));
|
|
@@ -21066,11 +21299,11 @@ async function digestPackTree(root) {
|
|
|
21066
21299
|
const files = [];
|
|
21067
21300
|
const directories = [];
|
|
21068
21301
|
const visit = async (directory, prefix) => {
|
|
21069
|
-
const entries = await
|
|
21302
|
+
const entries = await readdir2(directory, { withFileTypes: true });
|
|
21070
21303
|
for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
|
|
21071
21304
|
if (!prefix && entry.name === WORK_PACK_LOCAL_STATE_FILENAME) continue;
|
|
21072
21305
|
const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
|
|
21073
|
-
const absolute =
|
|
21306
|
+
const absolute = path5.join(directory, entry.name);
|
|
21074
21307
|
const info = await lstat2(absolute);
|
|
21075
21308
|
if (info.isSymbolicLink() || info.isFile() && info.nlink > 1) return false;
|
|
21076
21309
|
if (entry.isDirectory()) {
|
|
@@ -21079,7 +21312,7 @@ async function digestPackTree(root) {
|
|
|
21079
21312
|
continue;
|
|
21080
21313
|
}
|
|
21081
21314
|
if (!entry.isFile()) return false;
|
|
21082
|
-
files.push({ path: relative, sha256: digest(await
|
|
21315
|
+
files.push({ path: relative, sha256: digest(await readFile4(absolute)) });
|
|
21083
21316
|
}
|
|
21084
21317
|
return true;
|
|
21085
21318
|
};
|
|
@@ -21090,10 +21323,10 @@ function digestProjectionContents(files) {
|
|
|
21090
21323
|
}
|
|
21091
21324
|
async function projectionsMatch(directory, expected) {
|
|
21092
21325
|
for (const projection of expected) {
|
|
21093
|
-
const absolute =
|
|
21326
|
+
const absolute = path5.join(directory, projection.filename);
|
|
21094
21327
|
const info = await lstat2(absolute).catch(() => void 0);
|
|
21095
21328
|
if (!info?.isFile() || info.isSymbolicLink()) return false;
|
|
21096
|
-
const bytes = await
|
|
21329
|
+
const bytes = await readFile4(absolute).catch(() => void 0);
|
|
21097
21330
|
if (!bytes || digest(bytes) !== projection.sha256) return false;
|
|
21098
21331
|
}
|
|
21099
21332
|
return true;
|
|
@@ -21116,15 +21349,15 @@ function digest(bytes) {
|
|
|
21116
21349
|
return createHash("sha256").update(bytes).digest("hex");
|
|
21117
21350
|
}
|
|
21118
21351
|
async function writeJsonAtomic(filePath, value) {
|
|
21119
|
-
await mkdir3(
|
|
21120
|
-
const tempPath =
|
|
21352
|
+
await mkdir3(path5.dirname(filePath), { recursive: true });
|
|
21353
|
+
const tempPath = path5.join(path5.dirname(filePath), `.${path5.basename(filePath)}.${process.pid}.tmp`);
|
|
21121
21354
|
await writeFile4(tempPath, `${JSON.stringify(value, null, 2)}
|
|
21122
21355
|
`);
|
|
21123
21356
|
await rename4(tempPath, filePath);
|
|
21124
21357
|
}
|
|
21125
21358
|
async function adoptWorkPackFileManifest(input) {
|
|
21126
21359
|
if (!await matchesInstalledState({ ...input, allowAdditional: true }, input.expected)) return false;
|
|
21127
|
-
await writeJsonAtomic(
|
|
21360
|
+
await writeJsonAtomic(path5.join(input.packDir, WORK_PACK_LOCAL_STATE_FILENAME), input.expected);
|
|
21128
21361
|
return true;
|
|
21129
21362
|
}
|
|
21130
21363
|
function containsOriginalTree(actual, expected) {
|
|
@@ -21160,7 +21393,7 @@ function emptySummary() {
|
|
|
21160
21393
|
}
|
|
21161
21394
|
async function inspectWorkPackIntegrity(input) {
|
|
21162
21395
|
assertSlug(input.slug);
|
|
21163
|
-
const packDir =
|
|
21396
|
+
const packDir = path6.join(input.paths.skillsDir, input.slug);
|
|
21164
21397
|
const result = { slug: input.slug, summary: emptySummary(), differences: [], differencesTruncated: false };
|
|
21165
21398
|
const add = (kind, area, name) => {
|
|
21166
21399
|
if (result.summary[kind] === MAX_ENTRIES) result.summary.truncated = true;
|
|
@@ -21188,7 +21421,7 @@ async function inspectWorkPackIntegrity(input) {
|
|
|
21188
21421
|
if (result.summary.truncated) return;
|
|
21189
21422
|
let children;
|
|
21190
21423
|
try {
|
|
21191
|
-
children = await
|
|
21424
|
+
children = await readdir3(directory, { withFileTypes: true });
|
|
21192
21425
|
} catch {
|
|
21193
21426
|
add("unreadable", "pack", prefix || ".");
|
|
21194
21427
|
blocked.push(prefix);
|
|
@@ -21200,7 +21433,7 @@ async function inspectWorkPackIntegrity(input) {
|
|
|
21200
21433
|
return;
|
|
21201
21434
|
}
|
|
21202
21435
|
const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
|
|
21203
|
-
const absolute =
|
|
21436
|
+
const absolute = path6.join(directory, entry.name);
|
|
21204
21437
|
const info = await lstat3(absolute).catch(() => void 0);
|
|
21205
21438
|
if (!info) {
|
|
21206
21439
|
add("unreadable", "pack", relative);
|
|
@@ -21250,7 +21483,7 @@ async function inspectWorkPackIntegrity(input) {
|
|
|
21250
21483
|
const source = match ? `${match[1] ?? ""}${match[2]}.py` : void 0;
|
|
21251
21484
|
if (source && unchanged.has(source)) {
|
|
21252
21485
|
add("runtimeArtifacts", "pack", name);
|
|
21253
|
-
cacheDirectories.add(
|
|
21486
|
+
cacheDirectories.add(path6.posix.dirname(name));
|
|
21254
21487
|
} else add("additional", "pack", name);
|
|
21255
21488
|
}
|
|
21256
21489
|
for (const name of extraDirectories) if (!cacheDirectories.has(name)) add("additional", "pack", name);
|
|
@@ -21264,7 +21497,7 @@ async function inspectWorkPackIntegrity(input) {
|
|
|
21264
21497
|
continue;
|
|
21265
21498
|
}
|
|
21266
21499
|
for (const item of items) {
|
|
21267
|
-
const absolute =
|
|
21500
|
+
const absolute = path6.join(directory, item.filename);
|
|
21268
21501
|
try {
|
|
21269
21502
|
const info = await lstat3(absolute);
|
|
21270
21503
|
if (!info.isFile() || info.isSymbolicLink() || info.nlink > 1) add("unsafe", area, item.filename);
|
|
@@ -21358,9 +21591,9 @@ function assertSlug(slug) {
|
|
|
21358
21591
|
// packages/cli/src/sync.ts
|
|
21359
21592
|
import { createHash as createHash4 } from "node:crypto";
|
|
21360
21593
|
import { spawnSync } from "node:child_process";
|
|
21361
|
-
import { chmod as chmod4, cp, lstat as lstat5, mkdtemp, mkdir as mkdir5, readdir as
|
|
21594
|
+
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
21595
|
import os4 from "node:os";
|
|
21363
|
-
import
|
|
21596
|
+
import path9 from "node:path";
|
|
21364
21597
|
|
|
21365
21598
|
// node_modules/tar/dist/esm/index.min.js
|
|
21366
21599
|
import Qr from "events";
|
|
@@ -21414,7 +21647,7 @@ var Ne = /* @__PURE__ */ Symbol("closed");
|
|
|
21414
21647
|
var Ns = /* @__PURE__ */ Symbol("read");
|
|
21415
21648
|
var Ae = /* @__PURE__ */ Symbol("flush");
|
|
21416
21649
|
var As = /* @__PURE__ */ Symbol("flushChunk");
|
|
21417
|
-
var
|
|
21650
|
+
var z2 = /* @__PURE__ */ Symbol("encoding");
|
|
21418
21651
|
var Mt = /* @__PURE__ */ Symbol("decoder");
|
|
21419
21652
|
var g = /* @__PURE__ */ Symbol("flowing");
|
|
21420
21653
|
var Qt = /* @__PURE__ */ Symbol("paused");
|
|
@@ -21474,7 +21707,7 @@ var A = class extends Di {
|
|
|
21474
21707
|
[N] = [];
|
|
21475
21708
|
[b] = [];
|
|
21476
21709
|
[L];
|
|
21477
|
-
[
|
|
21710
|
+
[z2];
|
|
21478
21711
|
[Z];
|
|
21479
21712
|
[Mt];
|
|
21480
21713
|
[Q] = false;
|
|
@@ -21493,7 +21726,7 @@ var A = class extends Di {
|
|
|
21493
21726
|
constructor(...t) {
|
|
21494
21727
|
let e = t[0] || {};
|
|
21495
21728
|
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[
|
|
21729
|
+
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
21730
|
let { signal: i } = e;
|
|
21498
21731
|
i && (this[Jt] = i, i.aborted ? this[xi]() : i.addEventListener("abort", () => this[xi]()));
|
|
21499
21732
|
}
|
|
@@ -21501,7 +21734,7 @@ var A = class extends Di {
|
|
|
21501
21734
|
return this[_];
|
|
21502
21735
|
}
|
|
21503
21736
|
get encoding() {
|
|
21504
|
-
return this[
|
|
21737
|
+
return this[z2];
|
|
21505
21738
|
}
|
|
21506
21739
|
set encoding(t) {
|
|
21507
21740
|
throw new Error("Encoding must be set at instantiation time");
|
|
@@ -21540,12 +21773,12 @@ var A = class extends Di {
|
|
|
21540
21773
|
else if (Vr(t)) t = Buffer.from(t);
|
|
21541
21774
|
else if (typeof t != "string") throw new Error("Non-contiguous data written to non-objectMode stream");
|
|
21542
21775
|
}
|
|
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[
|
|
21776
|
+
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
21777
|
}
|
|
21545
21778
|
read(t) {
|
|
21546
21779
|
if (this[S]) return null;
|
|
21547
21780
|
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[
|
|
21781
|
+
this[L] && (t = null), this[b].length > 1 && !this[L] && (this[b] = [this[z2] ? this[b].join("") : Buffer.concat(this[b], this[_])]);
|
|
21549
21782
|
let e = this[Ns](t || null, this[b][0]);
|
|
21550
21783
|
return this[J](), e;
|
|
21551
21784
|
}
|
|
@@ -21688,7 +21921,7 @@ var A = class extends Di {
|
|
|
21688
21921
|
async concat() {
|
|
21689
21922
|
if (this[L]) throw new Error("cannot concat in objectMode");
|
|
21690
21923
|
let t = await this.collect();
|
|
21691
|
-
return this[
|
|
21924
|
+
return this[z2] ? t.join("") : Buffer.concat(t, t.dataLength);
|
|
21692
21925
|
}
|
|
21693
21926
|
async promise() {
|
|
21694
21927
|
return new Promise((t, e) => {
|
|
@@ -24341,8 +24574,8 @@ function renderTuiConfig(manifest) {
|
|
|
24341
24574
|
|
|
24342
24575
|
// packages/cli/src/coreSyncTransaction.ts
|
|
24343
24576
|
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
|
|
24577
|
+
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";
|
|
24578
|
+
import path7 from "node:path";
|
|
24346
24579
|
var CORE_RUNTIME_MANIFEST_VERSION = 1;
|
|
24347
24580
|
var CoreSyncUncertainError = class extends Error {
|
|
24348
24581
|
constructor(message, paths) {
|
|
@@ -24351,11 +24584,11 @@ var CoreSyncUncertainError = class extends Error {
|
|
|
24351
24584
|
}
|
|
24352
24585
|
paths;
|
|
24353
24586
|
};
|
|
24354
|
-
var defaultFs = { chmod: chmod3, lstat: lstat4, mkdir: mkdir4, readFile:
|
|
24587
|
+
var defaultFs = { chmod: chmod3, lstat: lstat4, mkdir: mkdir4, readFile: readFile5, rename: rename5, rm: rm3, writeFile: writeFile5 };
|
|
24355
24588
|
function coreRuntimeManifestDigest(files) {
|
|
24356
24589
|
const canonical = [...files].sort((a, b2) => a.id.localeCompare(b2.id)).map((file2) => ({
|
|
24357
24590
|
id: file2.id,
|
|
24358
|
-
path:
|
|
24591
|
+
path: path7.resolve(file2.path),
|
|
24359
24592
|
exists: file2.bytes !== null,
|
|
24360
24593
|
digest: file2.bytes === null ? void 0 : sha256(file2.bytes),
|
|
24361
24594
|
mode: file2.mode,
|
|
@@ -24372,8 +24605,8 @@ function validateCoreRuntimeManifest(manifest) {
|
|
|
24372
24605
|
const targets = /* @__PURE__ */ new Set();
|
|
24373
24606
|
for (const file2 of manifest.files) {
|
|
24374
24607
|
if (!file2.id || ids.has(file2.id)) throw new Error(`Duplicate core runtime file id: ${file2.id}`);
|
|
24375
|
-
const target =
|
|
24376
|
-
if (!
|
|
24608
|
+
const target = path7.resolve(file2.path);
|
|
24609
|
+
if (!path7.isAbsolute(file2.path) || targets.has(target)) throw new Error(`Invalid or duplicate core runtime target: ${file2.path}`);
|
|
24377
24610
|
if (file2.mode !== void 0 && (!Number.isInteger(file2.mode) || file2.mode < 0 || file2.mode > 4095)) throw new Error(`Invalid mode for ${file2.id}`);
|
|
24378
24611
|
if (file2.ownerOnly !== void 0 && typeof file2.ownerOnly !== "boolean") throw new Error(`Invalid owner-only flag for ${file2.id}`);
|
|
24379
24612
|
ids.add(file2.id);
|
|
@@ -24391,9 +24624,9 @@ async function applyCoreSyncTransaction(options) {
|
|
|
24391
24624
|
const files = [];
|
|
24392
24625
|
try {
|
|
24393
24626
|
for (const desired of options.manifest.files) {
|
|
24394
|
-
const target =
|
|
24627
|
+
const target = path7.resolve(desired.path);
|
|
24395
24628
|
if (desired.ownerOnly && desired.bytes !== null && fs2 === defaultFs) await prepareOwnerOnlyFileDestination(target);
|
|
24396
|
-
else await fs2.mkdir(
|
|
24629
|
+
else await fs2.mkdir(path7.dirname(target), { recursive: true });
|
|
24397
24630
|
const original = await capture(target, fs2);
|
|
24398
24631
|
const suffix = `.forge-core-${transactionId}`;
|
|
24399
24632
|
const backup = original.exists ? `${target}${suffix}.backup` : void 0;
|
|
@@ -24490,7 +24723,7 @@ async function writeExact(target, bytes, mode, fs2, ownerOnly = false) {
|
|
|
24490
24723
|
if (ownerOnly && fs2 === defaultFs) await protectOwnerOnlyPath(target, "file");
|
|
24491
24724
|
}
|
|
24492
24725
|
async function writeJournal(target, journal, fs2) {
|
|
24493
|
-
await fs2.mkdir(
|
|
24726
|
+
await fs2.mkdir(path7.dirname(target), { recursive: true });
|
|
24494
24727
|
const temporary = `${target}.next`;
|
|
24495
24728
|
await fs2.rm(temporary, { force: true });
|
|
24496
24729
|
await fs2.writeFile(temporary, `${JSON.stringify(journal, null, 2)}
|
|
@@ -24518,7 +24751,7 @@ function sha256(value) {
|
|
|
24518
24751
|
return createHash3("sha256").update(value).digest("hex");
|
|
24519
24752
|
}
|
|
24520
24753
|
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" &&
|
|
24754
|
+
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
24755
|
}
|
|
24523
24756
|
|
|
24524
24757
|
// packages/cli/src/jsonc.ts
|
|
@@ -24597,7 +24830,7 @@ function stripTrailingCommas(input) {
|
|
|
24597
24830
|
}
|
|
24598
24831
|
|
|
24599
24832
|
// packages/cli/src/remoteConfig.ts
|
|
24600
|
-
import { readFile as
|
|
24833
|
+
import { readFile as readFile6 } from "node:fs/promises";
|
|
24601
24834
|
var WELLKNOWN_ENV_KEY = "FORGE_API_KEY";
|
|
24602
24835
|
async function removeWellKnownAuth(paths, credentials, previous) {
|
|
24603
24836
|
const content = await prepareWellKnownAuthRemoval(paths, credentials, previous);
|
|
@@ -24611,7 +24844,7 @@ async function prepareWellKnownAuthRemoval(paths, credentials, previous) {
|
|
|
24611
24844
|
for (const url2 of owned.flatMap((entry) => [entry.forgeBaseUrl, ...entry.forgeOwnedWellKnownUrls ?? []])) {
|
|
24612
24845
|
const key = normalizeBaseUrl(url2);
|
|
24613
24846
|
const entry = auth[key];
|
|
24614
|
-
if (!
|
|
24847
|
+
if (!isRecord3(entry) || entry.type !== "wellknown" || entry.key !== WELLKNOWN_ENV_KEY || typeof entry.token !== "string" || !entry.token.startsWith("forge_")) continue;
|
|
24615
24848
|
if (!ownedKeys.has(entry.token)) {
|
|
24616
24849
|
throw new Error("A autoriza\xE7\xE3o Forge foi alterada; preserve os ficheiros e pe\xE7a uma repara\xE7\xE3o acompanhada.");
|
|
24617
24850
|
}
|
|
@@ -24627,21 +24860,21 @@ function stripForgeManagedConfig(config2) {
|
|
|
24627
24860
|
delete next.small_model;
|
|
24628
24861
|
delete next.share;
|
|
24629
24862
|
delete next.autoupdate;
|
|
24630
|
-
const experimental =
|
|
24863
|
+
const experimental = isRecord3(next.experimental) ? { ...next.experimental } : void 0;
|
|
24631
24864
|
if (experimental) {
|
|
24632
24865
|
delete experimental.clickableFileReferences;
|
|
24633
24866
|
if (Object.keys(experimental).length > 0) next.experimental = experimental;
|
|
24634
24867
|
else delete next.experimental;
|
|
24635
24868
|
}
|
|
24636
|
-
const provider =
|
|
24869
|
+
const provider = isRecord3(next.provider) ? { ...next.provider } : void 0;
|
|
24637
24870
|
if (provider) {
|
|
24638
24871
|
delete provider.forge;
|
|
24639
24872
|
const openrouter = provider.openrouter;
|
|
24640
|
-
if (
|
|
24873
|
+
if (isRecord3(openrouter) && openrouter.name === OPENROUTER_ALIAS_PROVIDER_NAME) delete provider.openrouter;
|
|
24641
24874
|
if (Object.keys(provider).length > 0) next.provider = provider;
|
|
24642
24875
|
else delete next.provider;
|
|
24643
24876
|
}
|
|
24644
|
-
const agent =
|
|
24877
|
+
const agent = isRecord3(next.agent) ? { ...next.agent } : void 0;
|
|
24645
24878
|
if (agent) {
|
|
24646
24879
|
delete agent["document-reader"];
|
|
24647
24880
|
if (Object.keys(agent).length > 0) next.agent = agent;
|
|
@@ -24655,35 +24888,35 @@ function normalizeBaseUrl(value) {
|
|
|
24655
24888
|
async function readAuthJson(paths) {
|
|
24656
24889
|
let raw;
|
|
24657
24890
|
try {
|
|
24658
|
-
raw = await
|
|
24891
|
+
raw = await readFile6(paths.opencodeAuthPath, "utf8");
|
|
24659
24892
|
} catch (error45) {
|
|
24660
24893
|
if (error45.code === "ENOENT") return {};
|
|
24661
24894
|
throw error45;
|
|
24662
24895
|
}
|
|
24663
24896
|
const parsed = JSON.parse(raw.startsWith("\uFEFF") ? raw.slice(1) : raw);
|
|
24664
|
-
if (!
|
|
24897
|
+
if (!isRecord3(parsed)) throw new Error("A autentica\xE7\xE3o do OpenCode n\xE3o \xE9 um objeto JSON v\xE1lido");
|
|
24665
24898
|
return parsed;
|
|
24666
24899
|
}
|
|
24667
|
-
function
|
|
24900
|
+
function isRecord3(value) {
|
|
24668
24901
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
24669
24902
|
}
|
|
24670
24903
|
|
|
24671
24904
|
// packages/cli/src/localConfigRecovery.ts
|
|
24672
|
-
import { readFile as
|
|
24673
|
-
import
|
|
24905
|
+
import { readFile as readFile7 } from "node:fs/promises";
|
|
24906
|
+
import path8 from "node:path";
|
|
24674
24907
|
var LocalConfigRecoveryError = class extends Error {
|
|
24675
24908
|
};
|
|
24676
24909
|
var LAST_GOOD_FILENAME = "last-good-opencode.json";
|
|
24677
24910
|
function lastGoodLocalConfigFile(paths, credentials, content) {
|
|
24678
24911
|
assertForgeConfig(content, credentials);
|
|
24679
|
-
return { id: "last-good-config", path:
|
|
24912
|
+
return { id: "last-good-config", path: path8.join(paths.forgeDir, LAST_GOOD_FILENAME), bytes: Buffer.from(content), mode: 384, ownerOnly: true };
|
|
24680
24913
|
}
|
|
24681
24914
|
async function retiredLastGoodLocalConfigFile(paths) {
|
|
24682
|
-
const filePath =
|
|
24915
|
+
const filePath = path8.join(paths.forgeDir, LAST_GOOD_FILENAME);
|
|
24683
24916
|
return await readOptional(filePath) === void 0 ? void 0 : { id: "last-good-config", path: filePath, bytes: null };
|
|
24684
24917
|
}
|
|
24685
24918
|
async function inspectLocalConfigRecovery(paths, credentials) {
|
|
24686
|
-
const snapshot = await readOptional(
|
|
24919
|
+
const snapshot = await readOptional(path8.join(paths.forgeDir, LAST_GOOD_FILENAME));
|
|
24687
24920
|
const current = await readOptional(paths.opencodeConfigPath);
|
|
24688
24921
|
return {
|
|
24689
24922
|
snapshot: snapshot === void 0 ? "missing" : isForgeConfig(snapshot, credentials) ? "available" : "invalid",
|
|
@@ -24698,14 +24931,14 @@ function assertForgeConfig(content, credentials) {
|
|
|
24698
24931
|
function isForgeConfig(content, credentials) {
|
|
24699
24932
|
try {
|
|
24700
24933
|
const config2 = parseJsonc(content);
|
|
24701
|
-
if (!
|
|
24934
|
+
if (!isRecord4(config2) || !isRecord4(config2.provider) || !isRecord4(config2.provider.forge)) return false;
|
|
24702
24935
|
assertForgeVisible(config2);
|
|
24703
24936
|
const forge = config2.provider.forge;
|
|
24704
|
-
if (!
|
|
24937
|
+
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
24938
|
if (typeof config2.model !== "string" || !config2.model.startsWith("forge/") || typeof config2.small_model !== "string" || !config2.small_model.startsWith("forge/")) return false;
|
|
24706
24939
|
const plugins = forgePluginEntries(config2);
|
|
24707
24940
|
return plugins.length === 1 && plugins.every(
|
|
24708
|
-
(entry) => Array.isArray(entry) && typeof entry[0] === "string" && /^minimal-forge-work-pack-sync@/.test(entry[0]) &&
|
|
24941
|
+
(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
24942
|
);
|
|
24710
24943
|
} catch {
|
|
24711
24944
|
return false;
|
|
@@ -24714,8 +24947,8 @@ function isForgeConfig(content, credentials) {
|
|
|
24714
24947
|
function sameSavedForgeFields(current, snapshot) {
|
|
24715
24948
|
const active = parseJsonc(current);
|
|
24716
24949
|
const saved = parseJsonc(snapshot);
|
|
24717
|
-
const activeProvider =
|
|
24718
|
-
const savedProvider =
|
|
24950
|
+
const activeProvider = isRecord4(active.provider) ? active.provider.forge : void 0;
|
|
24951
|
+
const savedProvider = isRecord4(saved.provider) ? saved.provider.forge : void 0;
|
|
24719
24952
|
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
24953
|
}
|
|
24721
24954
|
function forgePluginEntries(config2) {
|
|
@@ -24726,17 +24959,17 @@ function forgePluginEntries(config2) {
|
|
|
24726
24959
|
}
|
|
24727
24960
|
async function readOptional(filePath) {
|
|
24728
24961
|
try {
|
|
24729
|
-
return await
|
|
24962
|
+
return await readFile7(filePath, "utf8");
|
|
24730
24963
|
} catch (error45) {
|
|
24731
24964
|
if (error45.code === "ENOENT") return void 0;
|
|
24732
24965
|
throw error45;
|
|
24733
24966
|
}
|
|
24734
24967
|
}
|
|
24735
|
-
function
|
|
24968
|
+
function isRecord4(value) {
|
|
24736
24969
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
24737
24970
|
}
|
|
24738
24971
|
function assertForgeVisible(config2) {
|
|
24739
|
-
if (!
|
|
24972
|
+
if (!isRecord4(config2)) return;
|
|
24740
24973
|
if (Array.isArray(config2.disabled_providers) && config2.disabled_providers.includes("forge") || Array.isArray(config2.enabled_providers) && !config2.enabled_providers.includes("forge")) {
|
|
24741
24974
|
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
24975
|
}
|
|
@@ -25002,7 +25235,7 @@ function validCoreManifest(value) {
|
|
|
25002
25235
|
return modelIds.every((id) => typeof id === "string" && id.length > 0) && modelIds.includes(config2.model) && modelIds.includes(config2.small_model);
|
|
25003
25236
|
}
|
|
25004
25237
|
async function applyManifest(paths, credentials, manifest, options = {}) {
|
|
25005
|
-
const journalPath =
|
|
25238
|
+
const journalPath = path9.join(paths.forgeDir, "core-sync-journal.json");
|
|
25006
25239
|
const recovery = await recoverCoreSyncTransaction({ journalPath });
|
|
25007
25240
|
await retireDebugCapture(paths);
|
|
25008
25241
|
if (recovery.status === "uncertain") {
|
|
@@ -25015,11 +25248,11 @@ async function applyManifest(paths, credentials, manifest, options = {}) {
|
|
|
25015
25248
|
});
|
|
25016
25249
|
}
|
|
25017
25250
|
async function applyCoreManifest(paths, credentials, manifest, options) {
|
|
25018
|
-
const attachmentPluginPath =
|
|
25019
|
-
const evidencePluginPath =
|
|
25020
|
-
const debugTracePluginPath =
|
|
25021
|
-
const legacyAttachmentPluginPath =
|
|
25022
|
-
const debugTraceConfigPath =
|
|
25251
|
+
const attachmentPluginPath = path9.join(paths.pluginDir, FORGE_PLUGIN_FILENAME);
|
|
25252
|
+
const evidencePluginPath = path9.join(paths.pluginDir, FORGE_EVIDENCE_PLUGIN_FILENAME);
|
|
25253
|
+
const debugTracePluginPath = path9.join(paths.pluginDir, FORGE_DEBUG_TRACE_PLUGIN_FILENAME);
|
|
25254
|
+
const legacyAttachmentPluginPath = path9.join(paths.opencodeDir, "plugin", FORGE_PLUGIN_FILENAME);
|
|
25255
|
+
const debugTraceConfigPath = path9.join(paths.forgeDir, FORGE_DEBUG_TRACE_CONFIG_FILENAME);
|
|
25023
25256
|
const rules = attachmentBridgeRules(manifest.config.models);
|
|
25024
25257
|
let bridgeEnabled = Boolean(manifest.config.documentReaderModel) && Object.keys(rules).length > 0;
|
|
25025
25258
|
const existingConfig = await readJsoncObject(paths.opencodeConfigPath);
|
|
@@ -25098,7 +25331,7 @@ async function applyCoreManifest(paths, credentials, manifest, options) {
|
|
|
25098
25331
|
digest: digest2,
|
|
25099
25332
|
files
|
|
25100
25333
|
},
|
|
25101
|
-
journalPath:
|
|
25334
|
+
journalPath: path9.join(paths.forgeDir, "core-sync-journal.json"),
|
|
25102
25335
|
hooks: options.coreTransactionHooks
|
|
25103
25336
|
});
|
|
25104
25337
|
await removeLegacyDebugTraceRuntime(paths);
|
|
@@ -25110,9 +25343,9 @@ async function applyWorkPackManifest(paths, credentials, manifest, options) {
|
|
|
25110
25343
|
const recovery = await recoverInterruptedWorkPackInstalls(paths, options.cleanupWorkPackBackup, options.workPackProjectionBoundary);
|
|
25111
25344
|
const managed = await Promise.all((await managedWorkPackSlugs(paths.skillsDir)).map(async (slug) => ({
|
|
25112
25345
|
slug,
|
|
25113
|
-
version: (await
|
|
25114
|
-
agents: await readAgentRecord(
|
|
25115
|
-
commands: await readCommandRecord(
|
|
25346
|
+
version: (await readFile8(path9.join(paths.skillsDir, slug, ".forge-version"), "utf8")).trim(),
|
|
25347
|
+
agents: await readAgentRecord(path9.join(paths.skillsDir, slug)),
|
|
25348
|
+
commands: await readCommandRecord(path9.join(paths.skillsDir, slug))
|
|
25116
25349
|
})));
|
|
25117
25350
|
const desired = manifest.skills.map((skill) => ({
|
|
25118
25351
|
slug: skill.slug,
|
|
@@ -25136,7 +25369,7 @@ async function applyWorkPackManifest(paths, credentials, manifest, options) {
|
|
|
25136
25369
|
options
|
|
25137
25370
|
)),
|
|
25138
25371
|
recoveryFailures: recovery.failures,
|
|
25139
|
-
writeAtomicReceipt: (receipt) => writeJsonAtomic2(
|
|
25372
|
+
writeAtomicReceipt: (receipt) => writeJsonAtomic2(path9.join(paths.forgeDir, "work-pack-sync-receipt.json"), receipt)
|
|
25140
25373
|
});
|
|
25141
25374
|
const installed = workPacks.outcomes.filter((outcome) => outcome.status === "installed").map((outcome) => `${outcome.slug}@${outcome.version}`);
|
|
25142
25375
|
const removed = workPacks.outcomes.filter((outcome) => outcome.status === "removed").map((outcome) => outcome.slug);
|
|
@@ -25147,7 +25380,7 @@ async function applyWorkPackManifest(paths, credentials, manifest, options) {
|
|
|
25147
25380
|
async function collectWorkPackObservations(paths, reconciliation) {
|
|
25148
25381
|
const installedVersions = /* @__PURE__ */ new Map();
|
|
25149
25382
|
for (const slug of await managedWorkPackSlugs(paths.skillsDir)) {
|
|
25150
|
-
const version2 = (await
|
|
25383
|
+
const version2 = (await readFile8(path9.join(paths.skillsDir, slug, ".forge-version"), "utf8")).trim();
|
|
25151
25384
|
if (version2) installedVersions.set(slug, version2);
|
|
25152
25385
|
}
|
|
25153
25386
|
const observations = new Map(
|
|
@@ -25178,7 +25411,7 @@ async function enrichIntegrityFailure(paths, operation, result) {
|
|
|
25178
25411
|
}
|
|
25179
25412
|
}
|
|
25180
25413
|
async function operateWorkPack(paths, credentials, skillBySlug, approvedModelIds, cleanupPendingSlugs, recoveryFailures, operation, options) {
|
|
25181
|
-
const target =
|
|
25414
|
+
const target = path9.join(paths.skillsDir, operation.pack.slug);
|
|
25182
25415
|
const recoveryFailure = recoveryFailures.get(operation.pack.slug);
|
|
25183
25416
|
if (recoveryFailure) return { status: "failed", restoration: "exact", code: recoveryFailure };
|
|
25184
25417
|
let ownership;
|
|
@@ -25217,7 +25450,7 @@ async function operateWorkPack(paths, credentials, skillBySlug, approvedModelIds
|
|
|
25217
25450
|
let previousManagedPaths;
|
|
25218
25451
|
let archive;
|
|
25219
25452
|
try {
|
|
25220
|
-
const currentVersion = await
|
|
25453
|
+
const currentVersion = await readFile8(path9.join(target, ".forge-version"), "utf8").catch(() => "");
|
|
25221
25454
|
const sameVersion = currentVersion.trim() === skill.version;
|
|
25222
25455
|
if (ownership === "managed") {
|
|
25223
25456
|
let localState = await checkWorkPackInstalledState({
|
|
@@ -25328,8 +25561,8 @@ function jsonBytes(value) {
|
|
|
25328
25561
|
`);
|
|
25329
25562
|
}
|
|
25330
25563
|
async function removeLegacyDebugTraceRuntime(paths) {
|
|
25331
|
-
const launchAgentPath =
|
|
25332
|
-
const launchAgent = await
|
|
25564
|
+
const launchAgentPath = path9.join(os4.homedir(), "Library", "LaunchAgents", "com.minimal-forge.debug-trace.plist");
|
|
25565
|
+
const launchAgent = await readFile8(launchAgentPath, "utf8").catch((error45) => {
|
|
25333
25566
|
if (error45.code === "ENOENT") return void 0;
|
|
25334
25567
|
throw error45;
|
|
25335
25568
|
});
|
|
@@ -25351,13 +25584,13 @@ async function removeLegacyDebugTraceRuntime(paths) {
|
|
|
25351
25584
|
"debug-trace-service.err.log",
|
|
25352
25585
|
"opencode-debug-trace"
|
|
25353
25586
|
]) {
|
|
25354
|
-
await rm4(
|
|
25587
|
+
await rm4(path9.join(paths.forgeDir, filename), { force: true });
|
|
25355
25588
|
}
|
|
25356
|
-
await rm4(
|
|
25357
|
-
await rm4(
|
|
25589
|
+
await rm4(path9.join(paths.forgeDir, "claude-tap-traces"), { recursive: true, force: true });
|
|
25590
|
+
await rm4(path9.join(paths.forgeDir, "verified-claude-tap"), { recursive: true, force: true });
|
|
25358
25591
|
}
|
|
25359
25592
|
async function isManagedDebugTraceConfig(configPath) {
|
|
25360
|
-
const raw = await
|
|
25593
|
+
const raw = await readFile8(configPath, "utf8").catch((error45) => {
|
|
25361
25594
|
if (error45.code === "ENOENT") return void 0;
|
|
25362
25595
|
throw error45;
|
|
25363
25596
|
});
|
|
@@ -25421,7 +25654,7 @@ var WorkPackLocalEditsError = class extends Error {
|
|
|
25421
25654
|
async function assertWorkPackUnchangedAtBoundary(paths, target, snapshot) {
|
|
25422
25655
|
const ownership = await workPackOwnership(target);
|
|
25423
25656
|
if (ownership === "absent") return;
|
|
25424
|
-
if (ownership === "foreign") throw foreignWorkPackError(
|
|
25657
|
+
if (ownership === "foreign") throw foreignWorkPackError(path9.basename(target));
|
|
25425
25658
|
const localState = await checkWorkPackInstalledState({
|
|
25426
25659
|
packDir: target,
|
|
25427
25660
|
agentsDir: paths.agentsDir,
|
|
@@ -25463,22 +25696,22 @@ async function preserveWorkPackExtras(target, nextPath, actual) {
|
|
|
25463
25696
|
`A nova vers\xE3o usa o caminho adicional "${name}". O pacote anterior e os ficheiros locais foram preservados.`
|
|
25464
25697
|
);
|
|
25465
25698
|
}
|
|
25466
|
-
for (const directory of directories) await mkdir5(
|
|
25699
|
+
for (const directory of directories) await mkdir5(path9.join(nextPath, directory), { recursive: true });
|
|
25467
25700
|
for (const file2 of extras) {
|
|
25468
|
-
const destination =
|
|
25469
|
-
await mkdir5(
|
|
25470
|
-
await cp(
|
|
25471
|
-
if (createHash4("sha256").update(await
|
|
25701
|
+
const destination = path9.join(nextPath, file2.path);
|
|
25702
|
+
await mkdir5(path9.dirname(destination), { recursive: true });
|
|
25703
|
+
await cp(path9.join(target, file2.path), destination, { errorOnExist: true, force: false });
|
|
25704
|
+
if (createHash4("sha256").update(await readFile8(destination)).digest("hex") !== file2.sha256)
|
|
25472
25705
|
throw new WorkPackLocalEditsError("local-edits-preserved");
|
|
25473
25706
|
}
|
|
25474
25707
|
}
|
|
25475
25708
|
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 =
|
|
25709
|
+
const tempRoot = await mkdtemp(path9.join(os4.tmpdir(), `forge-${slug}-`));
|
|
25710
|
+
const archivePath = path9.join(tempRoot, `${slug}.tar`);
|
|
25711
|
+
const extractPath = path9.join(tempRoot, "extract");
|
|
25712
|
+
const nextPath = path9.join(tempRoot, slug);
|
|
25713
|
+
const target = path9.join(paths.skillsDir, slug);
|
|
25714
|
+
const backup = path9.join(paths.skillsDir, `${slug}.previous`);
|
|
25482
25715
|
let agentFiles;
|
|
25483
25716
|
let commandFiles;
|
|
25484
25717
|
let previousAgents;
|
|
@@ -25487,7 +25720,7 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
|
|
|
25487
25720
|
await mkdir5(extractPath, { recursive: true });
|
|
25488
25721
|
await writeFile6(archivePath, archive);
|
|
25489
25722
|
await So({ file: archivePath, cwd: extractPath, strict: true });
|
|
25490
|
-
const extractedSkillPath =
|
|
25723
|
+
const extractedSkillPath = path9.join(extractPath, slug);
|
|
25491
25724
|
await assertNoReservedMarkerAliases(extractedSkillPath);
|
|
25492
25725
|
await validateSkillFolder(extractedSkillPath, slug);
|
|
25493
25726
|
agentFiles = await normalizePackAgentModels(
|
|
@@ -25514,15 +25747,15 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
|
|
|
25514
25747
|
}
|
|
25515
25748
|
throw error45;
|
|
25516
25749
|
}
|
|
25517
|
-
await rename6(
|
|
25518
|
-
await writeFile6(
|
|
25750
|
+
await rename6(path9.join(extractPath, slug), nextPath);
|
|
25751
|
+
await writeFile6(path9.join(nextPath, ".forge-version"), `${version2}
|
|
25519
25752
|
`);
|
|
25520
25753
|
if (agentFiles.length > 0) {
|
|
25521
|
-
await writeFile6(
|
|
25754
|
+
await writeFile6(path9.join(nextPath, ".forge-agents"), `${agentFiles.map((agent) => agent.filename).join("\n")}
|
|
25522
25755
|
`);
|
|
25523
25756
|
}
|
|
25524
25757
|
if (commandFiles.length > 0) {
|
|
25525
|
-
await writeFile6(
|
|
25758
|
+
await writeFile6(path9.join(nextPath, ".forge-commands"), `${commandFiles.map((command) => command.filename).join("\n")}
|
|
25526
25759
|
`);
|
|
25527
25760
|
}
|
|
25528
25761
|
await writeWorkPackInstalledState({ packDir: nextPath, version: version2, agents: agentFiles, commands: commandFiles });
|
|
@@ -25533,13 +25766,13 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
|
|
|
25533
25766
|
const agentTransactionState = new Map(
|
|
25534
25767
|
[...agentSnapshot.keys()].map((filePath) => [
|
|
25535
25768
|
filePath,
|
|
25536
|
-
agentFiles.find((agent) => agent.filename ===
|
|
25769
|
+
agentFiles.find((agent) => agent.filename === path9.basename(filePath))?.content
|
|
25537
25770
|
])
|
|
25538
25771
|
);
|
|
25539
25772
|
const commandTransactionState = new Map(
|
|
25540
25773
|
[...commandSnapshot.keys()].map((filePath) => [
|
|
25541
25774
|
filePath,
|
|
25542
|
-
commandFiles.find((command) => command.filename ===
|
|
25775
|
+
commandFiles.find((command) => command.filename === path9.basename(filePath))?.content
|
|
25543
25776
|
])
|
|
25544
25777
|
);
|
|
25545
25778
|
const previousManagedPaths = await managedWorkPackPaths(paths, target);
|
|
@@ -25560,7 +25793,7 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
|
|
|
25560
25793
|
throw error45;
|
|
25561
25794
|
}
|
|
25562
25795
|
const writeProjection = options.writeWorkPackProjection ?? writeTextAtomic;
|
|
25563
|
-
const claimedBackup =
|
|
25796
|
+
const claimedBackup = path9.join(tempRoot, `${slug}-claimed-previous`);
|
|
25564
25797
|
const transactionPath = `${backup}${WORK_PACK_TRANSACTION_SUFFIX}`;
|
|
25565
25798
|
let targetBackedUp = false;
|
|
25566
25799
|
let targetInstalled = false;
|
|
@@ -25583,7 +25816,7 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
|
|
|
25583
25816
|
await rename6(nextPath, target);
|
|
25584
25817
|
targetInstalled = true;
|
|
25585
25818
|
for (const filename of previousAgents.filter((name) => !nextAgentNames.has(name))) {
|
|
25586
|
-
const filePath =
|
|
25819
|
+
const filePath = path9.join(paths.agentsDir, filename);
|
|
25587
25820
|
await options.workPackProjectionBoundary?.("install", filePath);
|
|
25588
25821
|
await assertProjectionState(filePath, agentSnapshot.get(filePath));
|
|
25589
25822
|
await rm4(filePath, { force: true });
|
|
@@ -25591,14 +25824,14 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
|
|
|
25591
25824
|
if (agentFiles.length > 0) {
|
|
25592
25825
|
await mkdir5(paths.agentsDir, { recursive: true });
|
|
25593
25826
|
for (const agent of agentFiles) {
|
|
25594
|
-
const filePath =
|
|
25827
|
+
const filePath = path9.join(paths.agentsDir, agent.filename);
|
|
25595
25828
|
await options.workPackProjectionBoundary?.("install", filePath);
|
|
25596
25829
|
await assertProjectionState(filePath, agentSnapshot.get(filePath));
|
|
25597
25830
|
await writeProjection(filePath, agent.content);
|
|
25598
25831
|
}
|
|
25599
25832
|
}
|
|
25600
25833
|
for (const filename of previousCommands.filter((name) => !nextCommandNames.has(name))) {
|
|
25601
|
-
const filePath =
|
|
25834
|
+
const filePath = path9.join(paths.commandsDir, filename);
|
|
25602
25835
|
await options.workPackProjectionBoundary?.("install", filePath);
|
|
25603
25836
|
await assertProjectionState(filePath, commandSnapshot.get(filePath));
|
|
25604
25837
|
await rm4(filePath, { force: true });
|
|
@@ -25606,7 +25839,7 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
|
|
|
25606
25839
|
if (commandFiles.length > 0) {
|
|
25607
25840
|
await mkdir5(paths.commandsDir, { recursive: true });
|
|
25608
25841
|
for (const command of commandFiles) {
|
|
25609
|
-
const filePath =
|
|
25842
|
+
const filePath = path9.join(paths.commandsDir, command.filename);
|
|
25610
25843
|
await options.workPackProjectionBoundary?.("install", filePath);
|
|
25611
25844
|
await assertProjectionState(filePath, commandSnapshot.get(filePath));
|
|
25612
25845
|
await writeProjection(filePath, command.content);
|
|
@@ -25619,7 +25852,7 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
|
|
|
25619
25852
|
await rename6(backup, claimedBackup);
|
|
25620
25853
|
backupClaimed = true;
|
|
25621
25854
|
await assertWorkPackTreeUnchangedAtBoundary(claimedBackup, originalTree);
|
|
25622
|
-
await writeFile6(
|
|
25855
|
+
await writeFile6(path9.join(claimedBackup, WORK_PACK_COMMITTED_MARKER), `${version2}
|
|
25623
25856
|
`);
|
|
25624
25857
|
await writeTextAtomic(transactionPath, "committed\n");
|
|
25625
25858
|
}
|
|
@@ -25631,7 +25864,7 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
|
|
|
25631
25864
|
await restoreProjectionState(commandSnapshot, commandTransactionState);
|
|
25632
25865
|
}
|
|
25633
25866
|
if (targetBackedUp) {
|
|
25634
|
-
const restoredTarget =
|
|
25867
|
+
const restoredTarget = path9.join(tempRoot, `${slug}-restore`);
|
|
25635
25868
|
const rollbackSource = backupClaimed ? claimedBackup : backup;
|
|
25636
25869
|
await cp(rollbackSource, restoredTarget, { recursive: true });
|
|
25637
25870
|
if (targetInstalled) await rm4(target, { recursive: true, force: true });
|
|
@@ -25668,19 +25901,19 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
|
|
|
25668
25901
|
return { cleanup: cleanup2 };
|
|
25669
25902
|
}
|
|
25670
25903
|
async function adoptLegacyWorkPackState(paths, slug, version2, archive, approvedModelIds) {
|
|
25671
|
-
const comparisonRoot = await mkdtemp(
|
|
25904
|
+
const comparisonRoot = await mkdtemp(path9.join(os4.tmpdir(), `forge-${slug}-baseline-`));
|
|
25672
25905
|
const comparisonPaths = {
|
|
25673
25906
|
...paths,
|
|
25674
|
-
skillsDir:
|
|
25675
|
-
agentsDir:
|
|
25676
|
-
commandsDir:
|
|
25907
|
+
skillsDir: path9.join(comparisonRoot, "skills"),
|
|
25908
|
+
agentsDir: path9.join(comparisonRoot, "agents"),
|
|
25909
|
+
commandsDir: path9.join(comparisonRoot, "commands")
|
|
25677
25910
|
};
|
|
25678
25911
|
try {
|
|
25679
25912
|
await mkdir5(comparisonPaths.skillsDir, { recursive: true });
|
|
25680
25913
|
await installSkillArchive(comparisonPaths, slug, version2, archive, { approvedModelIds });
|
|
25681
25914
|
return adoptWorkPackInstalledState({
|
|
25682
|
-
expectedPackDir:
|
|
25683
|
-
packDir:
|
|
25915
|
+
expectedPackDir: path9.join(comparisonPaths.skillsDir, slug),
|
|
25916
|
+
packDir: path9.join(paths.skillsDir, slug),
|
|
25684
25917
|
agentsDir: paths.agentsDir,
|
|
25685
25918
|
commandsDir: paths.commandsDir,
|
|
25686
25919
|
allowAdditional: true
|
|
@@ -25692,7 +25925,7 @@ async function adoptLegacyWorkPackState(paths, slug, version2, archive, approved
|
|
|
25692
25925
|
async function recoverInterruptedWorkPackInstalls(paths, cleanupWorkPackBackup, workPackProjectionBoundary) {
|
|
25693
25926
|
const cleanupPending = /* @__PURE__ */ new Set();
|
|
25694
25927
|
const failures = /* @__PURE__ */ new Map();
|
|
25695
|
-
const entries = await
|
|
25928
|
+
const entries = await readdir4(paths.skillsDir, { withFileTypes: true }).catch((error45) => {
|
|
25696
25929
|
if (error45.code === "ENOENT") return [];
|
|
25697
25930
|
throw error45;
|
|
25698
25931
|
});
|
|
@@ -25700,7 +25933,7 @@ async function recoverInterruptedWorkPackInstalls(paths, cleanupWorkPackBackup,
|
|
|
25700
25933
|
if (!entry.name.endsWith(".previous")) continue;
|
|
25701
25934
|
const slug = entry.name.slice(0, -".previous".length);
|
|
25702
25935
|
if (!slug) continue;
|
|
25703
|
-
const target =
|
|
25936
|
+
const target = path9.join(paths.skillsDir, slug);
|
|
25704
25937
|
const backup = `${target}.previous`;
|
|
25705
25938
|
const transactionState = await readWorkPackTransactionState(backup);
|
|
25706
25939
|
if (transactionState === "committed") {
|
|
@@ -25733,9 +25966,9 @@ async function recoverInterruptedWorkPackInstall(paths, target, cleanupWorkPackB
|
|
|
25733
25966
|
const backup = `${target}.previous`;
|
|
25734
25967
|
const backupOwnership = await workPackOwnership(backup);
|
|
25735
25968
|
if (backupOwnership === "absent") return "recovered";
|
|
25736
|
-
if (backupOwnership === "foreign") throw foreignWorkPackError(
|
|
25737
|
-
if (await workPackOwnership(target) === "foreign") throw foreignWorkPackError(
|
|
25738
|
-
const committed = await
|
|
25969
|
+
if (backupOwnership === "foreign") throw foreignWorkPackError(path9.basename(target));
|
|
25970
|
+
if (await workPackOwnership(target) === "foreign") throw foreignWorkPackError(path9.basename(target));
|
|
25971
|
+
const committed = await readFile8(path9.join(backup, WORK_PACK_COMMITTED_MARKER), "utf8").catch((error45) => {
|
|
25739
25972
|
if (error45.code === "ENOENT") return void 0;
|
|
25740
25973
|
throw error45;
|
|
25741
25974
|
});
|
|
@@ -25783,32 +26016,32 @@ async function recoverInterruptedWorkPackInstall(paths, target, cleanupWorkPackB
|
|
|
25783
26016
|
);
|
|
25784
26017
|
const previousAgentNames = new Set(previousAgents.map((agent) => agent.filename));
|
|
25785
26018
|
const previousCommandNames = new Set(previousCommands.map((command) => command.filename));
|
|
25786
|
-
const recoveryRoot = await mkdtemp(
|
|
25787
|
-
const recoveredTarget =
|
|
26019
|
+
const recoveryRoot = await mkdtemp(path9.join(os4.tmpdir(), "forge-recover-"));
|
|
26020
|
+
const recoveredTarget = path9.join(recoveryRoot, path9.basename(target));
|
|
25788
26021
|
await cp(backup, recoveredTarget, { recursive: true });
|
|
25789
26022
|
try {
|
|
25790
26023
|
for (const filename of currentAgents.filter((name) => !previousAgentNames.has(name))) {
|
|
25791
|
-
const filePath =
|
|
26024
|
+
const filePath = path9.join(paths.agentsDir, filename);
|
|
25792
26025
|
await workPackProjectionBoundary?.("recover", filePath);
|
|
25793
26026
|
await assertProjectionState(filePath, agentRecoveryState.get(filePath));
|
|
25794
26027
|
await rm4(filePath, { force: true });
|
|
25795
26028
|
}
|
|
25796
26029
|
await mkdir5(paths.agentsDir, { recursive: true });
|
|
25797
26030
|
for (const agent of previousAgents) {
|
|
25798
|
-
const filePath =
|
|
26031
|
+
const filePath = path9.join(paths.agentsDir, agent.filename);
|
|
25799
26032
|
await workPackProjectionBoundary?.("recover", filePath);
|
|
25800
26033
|
await assertProjectionState(filePath, agentRecoveryState.get(filePath));
|
|
25801
26034
|
await writeTextAtomic(filePath, agent.content);
|
|
25802
26035
|
}
|
|
25803
26036
|
for (const filename of currentCommands.filter((name) => !previousCommandNames.has(name))) {
|
|
25804
|
-
const filePath =
|
|
26037
|
+
const filePath = path9.join(paths.commandsDir, filename);
|
|
25805
26038
|
await workPackProjectionBoundary?.("recover", filePath);
|
|
25806
26039
|
await assertProjectionState(filePath, commandRecoveryState.get(filePath));
|
|
25807
26040
|
await rm4(filePath, { force: true });
|
|
25808
26041
|
}
|
|
25809
26042
|
await mkdir5(paths.commandsDir, { recursive: true });
|
|
25810
26043
|
for (const command of previousCommands) {
|
|
25811
|
-
const filePath =
|
|
26044
|
+
const filePath = path9.join(paths.commandsDir, command.filename);
|
|
25812
26045
|
await workPackProjectionBoundary?.("recover", filePath);
|
|
25813
26046
|
await assertProjectionState(filePath, commandRecoveryState.get(filePath));
|
|
25814
26047
|
await writeTextAtomic(filePath, command.content);
|
|
@@ -25826,7 +26059,7 @@ async function removeWorkPackBackup(backupPath) {
|
|
|
25826
26059
|
await rm4(backupPath, { recursive: true, force: true });
|
|
25827
26060
|
}
|
|
25828
26061
|
async function readWorkPackTransactionFile(backup) {
|
|
25829
|
-
return
|
|
26062
|
+
return readFile8(`${backup}${WORK_PACK_TRANSACTION_SUFFIX}`, "utf8").catch((error45) => {
|
|
25830
26063
|
if (error45.code === "ENOENT") return void 0;
|
|
25831
26064
|
throw error45;
|
|
25832
26065
|
});
|
|
@@ -25840,7 +26073,7 @@ function isManagedProjectionName(filename) {
|
|
|
25840
26073
|
return filename.length > 0 && !filename.includes("/") && !filename.includes("\\") && filename !== "..";
|
|
25841
26074
|
}
|
|
25842
26075
|
async function recordRemovedProjection(transactionPath, kind, filename) {
|
|
25843
|
-
const current = await
|
|
26076
|
+
const current = await readFile8(transactionPath, "utf8");
|
|
25844
26077
|
await writeTextAtomic(transactionPath, `${current.trimEnd()}
|
|
25845
26078
|
${kind}:${filename}
|
|
25846
26079
|
`);
|
|
@@ -25877,7 +26110,7 @@ async function workPackOwnership(target) {
|
|
|
25877
26110
|
});
|
|
25878
26111
|
if (!targetStat) return "absent";
|
|
25879
26112
|
if (!targetStat.isDirectory()) return "foreign";
|
|
25880
|
-
const marker = await
|
|
26113
|
+
const marker = await readFile8(path9.join(target, ".forge-version"), "utf8").catch((error45) => {
|
|
25881
26114
|
if (error45.code === "ENOENT") return void 0;
|
|
25882
26115
|
throw error45;
|
|
25883
26116
|
});
|
|
@@ -25903,11 +26136,11 @@ async function assertProjectionRecoveryIsSafe(directory, currentFiles, previousF
|
|
|
25903
26136
|
expected.set(file2.filename, contents);
|
|
25904
26137
|
}
|
|
25905
26138
|
for (const [filename, contents] of expected) {
|
|
25906
|
-
const projected = await
|
|
26139
|
+
const projected = await readFile8(path9.join(directory, filename), "utf8").catch((error45) => {
|
|
25907
26140
|
if (error45.code === "ENOENT") return void 0;
|
|
25908
26141
|
throw error45;
|
|
25909
26142
|
});
|
|
25910
|
-
validated.set(
|
|
26143
|
+
validated.set(path9.join(directory, filename), projected);
|
|
25911
26144
|
const missingPreviousProjection = missingPreviousProjectionIsLocalDeletion(
|
|
25912
26145
|
filename,
|
|
25913
26146
|
projected,
|
|
@@ -25925,19 +26158,19 @@ async function assertProjectionRecoveryIsSafe(directory, currentFiles, previousF
|
|
|
25925
26158
|
return validated;
|
|
25926
26159
|
}
|
|
25927
26160
|
async function assertProjectionState(filePath, expected) {
|
|
25928
|
-
const current = await
|
|
26161
|
+
const current = await readFile8(filePath, "utf8").catch((error45) => {
|
|
25929
26162
|
if (error45.code === "ENOENT") return void 0;
|
|
25930
26163
|
throw error45;
|
|
25931
26164
|
});
|
|
25932
26165
|
if (current !== expected) {
|
|
25933
|
-
throw new WorkPackLocalEditsError("local-edits-preserved", `A proje\xE7\xE3o ${
|
|
26166
|
+
throw new WorkPackLocalEditsError("local-edits-preserved", `A proje\xE7\xE3o ${path9.basename(filePath)} foi alterada durante a opera\xE7\xE3o`);
|
|
25934
26167
|
}
|
|
25935
26168
|
}
|
|
25936
26169
|
async function captureProjectionState(directory, filenames) {
|
|
25937
26170
|
const snapshot = /* @__PURE__ */ new Map();
|
|
25938
26171
|
for (const filename of filenames) {
|
|
25939
|
-
const filePath =
|
|
25940
|
-
const content = await
|
|
26172
|
+
const filePath = path9.join(directory, filename);
|
|
26173
|
+
const content = await readFile8(filePath, "utf8").catch((error45) => {
|
|
25941
26174
|
if (error45.code === "ENOENT") return void 0;
|
|
25942
26175
|
throw error45;
|
|
25943
26176
|
});
|
|
@@ -25948,7 +26181,7 @@ async function captureProjectionState(directory, filenames) {
|
|
|
25948
26181
|
async function restoreProjectionState(snapshot, transactionState) {
|
|
25949
26182
|
for (const [filePath, content] of snapshot) {
|
|
25950
26183
|
if (transactionState) {
|
|
25951
|
-
const current = await
|
|
26184
|
+
const current = await readFile8(filePath, "utf8").catch((error45) => {
|
|
25952
26185
|
if (error45.code === "ENOENT") return void 0;
|
|
25953
26186
|
throw error45;
|
|
25954
26187
|
});
|
|
@@ -25959,8 +26192,8 @@ async function restoreProjectionState(snapshot, transactionState) {
|
|
|
25959
26192
|
}
|
|
25960
26193
|
}
|
|
25961
26194
|
async function readPackAgentFiles(skillFolder, managedNames) {
|
|
25962
|
-
const agentsFolder =
|
|
25963
|
-
const entries = await
|
|
26195
|
+
const agentsFolder = path9.join(skillFolder, "agents");
|
|
26196
|
+
const entries = await readdir4(agentsFolder, { withFileTypes: true }).catch((error45) => {
|
|
25964
26197
|
if (error45.code === "ENOENT") return [];
|
|
25965
26198
|
throw error45;
|
|
25966
26199
|
});
|
|
@@ -25968,7 +26201,7 @@ async function readPackAgentFiles(skillFolder, managedNames) {
|
|
|
25968
26201
|
for (const entry of entries) {
|
|
25969
26202
|
if (!entry.isFile() || !entry.name.endsWith(".md") || managedNames && !managedNames.has(entry.name)) continue;
|
|
25970
26203
|
if (entry.name.startsWith("._")) continue;
|
|
25971
|
-
const content = await
|
|
26204
|
+
const content = await readFile8(path9.join(agentsFolder, entry.name), "utf8");
|
|
25972
26205
|
validateAgentFile(entry.name, content);
|
|
25973
26206
|
files.push({ filename: entry.name, content });
|
|
25974
26207
|
}
|
|
@@ -25979,7 +26212,7 @@ async function normalizePackAgentModels(skillFolder, agentFiles, approvedModelId
|
|
|
25979
26212
|
for (const agent of agentFiles) {
|
|
25980
26213
|
const content = normalizePackAgentModel(agent.filename, agent.content, approvedModelIds, slug);
|
|
25981
26214
|
if (content !== agent.content) {
|
|
25982
|
-
await writeFile6(
|
|
26215
|
+
await writeFile6(path9.join(skillFolder, "agents", agent.filename), content);
|
|
25983
26216
|
}
|
|
25984
26217
|
normalized.push({ ...agent, content });
|
|
25985
26218
|
}
|
|
@@ -25999,8 +26232,8 @@ function normalizePackAgentModel(filename, content, approvedModelIds, slug) {
|
|
|
25999
26232
|
return normalizePackExtensionModel(`agents/${filename}`, content, approvedModelIds, slug);
|
|
26000
26233
|
}
|
|
26001
26234
|
async function readPackCommandFiles(skillFolder, managedNames) {
|
|
26002
|
-
const commandsFolder =
|
|
26003
|
-
const entries = await
|
|
26235
|
+
const commandsFolder = path9.join(skillFolder, "commands");
|
|
26236
|
+
const entries = await readdir4(commandsFolder, { withFileTypes: true }).catch((error45) => {
|
|
26004
26237
|
if (error45.code === "ENOENT") return [];
|
|
26005
26238
|
throw error45;
|
|
26006
26239
|
});
|
|
@@ -26008,7 +26241,7 @@ async function readPackCommandFiles(skillFolder, managedNames) {
|
|
|
26008
26241
|
for (const entry of entries) {
|
|
26009
26242
|
if (!entry.isFile() || !entry.name.endsWith(".md") || managedNames && !managedNames.has(entry.name)) continue;
|
|
26010
26243
|
if (entry.name.startsWith("._")) continue;
|
|
26011
|
-
const content = await
|
|
26244
|
+
const content = await readFile8(path9.join(commandsFolder, entry.name), "utf8");
|
|
26012
26245
|
validateCommandFile(entry.name, content);
|
|
26013
26246
|
files.push({ filename: entry.name, content });
|
|
26014
26247
|
}
|
|
@@ -26019,7 +26252,7 @@ async function normalizePackCommandModels(skillFolder, commandFiles, approvedMod
|
|
|
26019
26252
|
for (const command of commandFiles) {
|
|
26020
26253
|
const content = normalizePackExtensionModel(`commands/${command.filename}`, command.content, approvedModelIds, slug);
|
|
26021
26254
|
if (content !== command.content) {
|
|
26022
|
-
await writeFile6(
|
|
26255
|
+
await writeFile6(path9.join(skillFolder, "commands", command.filename), content);
|
|
26023
26256
|
}
|
|
26024
26257
|
normalized.push({ ...command, content });
|
|
26025
26258
|
}
|
|
@@ -26041,7 +26274,7 @@ async function assertNoForeignAgentConflicts(agentsDir, agentFiles, ownedFilenam
|
|
|
26041
26274
|
const owned = new Set(ownedFilenames);
|
|
26042
26275
|
for (const agent of agentFiles) {
|
|
26043
26276
|
if (owned.has(agent.filename)) continue;
|
|
26044
|
-
const existing = await
|
|
26277
|
+
const existing = await readFile8(path9.join(agentsDir, agent.filename), "utf8").catch((error45) => {
|
|
26045
26278
|
if (error45.code === "ENOENT") return void 0;
|
|
26046
26279
|
throw error45;
|
|
26047
26280
|
});
|
|
@@ -26054,7 +26287,7 @@ async function assertNoForeignCommandConflicts(commandsDir, commandFiles, ownedF
|
|
|
26054
26287
|
const owned = new Set(ownedFilenames);
|
|
26055
26288
|
for (const command of commandFiles) {
|
|
26056
26289
|
if (owned.has(command.filename)) continue;
|
|
26057
|
-
const existing = await
|
|
26290
|
+
const existing = await readFile8(path9.join(commandsDir, command.filename), "utf8").catch((error45) => {
|
|
26058
26291
|
if (error45.code === "ENOENT") return void 0;
|
|
26059
26292
|
throw error45;
|
|
26060
26293
|
});
|
|
@@ -26064,28 +26297,28 @@ async function assertNoForeignCommandConflicts(commandsDir, commandFiles, ownedF
|
|
|
26064
26297
|
}
|
|
26065
26298
|
}
|
|
26066
26299
|
async function readAgentRecord(skillFolder) {
|
|
26067
|
-
const raw = await
|
|
26300
|
+
const raw = await readFile8(path9.join(skillFolder, ".forge-agents"), "utf8").catch(() => "");
|
|
26068
26301
|
return raw.split("\n").map((line) => line.trim()).filter((line) => line.length > 0 && !line.includes("/") && !line.includes("\\") && line !== "..");
|
|
26069
26302
|
}
|
|
26070
26303
|
async function readCommandRecord(skillFolder) {
|
|
26071
|
-
const raw = await
|
|
26304
|
+
const raw = await readFile8(path9.join(skillFolder, ".forge-commands"), "utf8").catch(() => "");
|
|
26072
26305
|
return raw.split("\n").map((line) => line.trim()).filter((line) => line.length > 0 && !line.includes("/") && !line.includes("\\") && line !== "..");
|
|
26073
26306
|
}
|
|
26074
26307
|
async function managedWorkPackPaths(paths, skillFolder) {
|
|
26075
26308
|
const files = await listFilesRecursively(skillFolder);
|
|
26076
|
-
const agents = (await readAgentRecord(skillFolder)).map((filename) =>
|
|
26077
|
-
const commands = (await readCommandRecord(skillFolder)).map((filename) =>
|
|
26309
|
+
const agents = (await readAgentRecord(skillFolder)).map((filename) => path9.join(paths.agentsDir, filename));
|
|
26310
|
+
const commands = (await readCommandRecord(skillFolder)).map((filename) => path9.join(paths.commandsDir, filename));
|
|
26078
26311
|
return [.../* @__PURE__ */ new Set([...files, ...agents, ...commands])];
|
|
26079
26312
|
}
|
|
26080
26313
|
async function managedWorkPackSlugs(skillsDir) {
|
|
26081
|
-
const entries = await
|
|
26314
|
+
const entries = await readdir4(skillsDir, { withFileTypes: true }).catch((error45) => {
|
|
26082
26315
|
if (error45.code === "ENOENT") return [];
|
|
26083
26316
|
throw error45;
|
|
26084
26317
|
});
|
|
26085
26318
|
const slugs = [];
|
|
26086
26319
|
for (const entry of entries) {
|
|
26087
26320
|
if (!entry.isDirectory() || entry.name.endsWith(".previous")) continue;
|
|
26088
|
-
if (await workPackOwnership(
|
|
26321
|
+
if (await workPackOwnership(path9.join(skillsDir, entry.name)) === "managed") slugs.push(entry.name);
|
|
26089
26322
|
}
|
|
26090
26323
|
return slugs.sort((left, right) => left.localeCompare(right));
|
|
26091
26324
|
}
|
|
@@ -26095,14 +26328,14 @@ async function removeManagedWorkPackTransaction(paths, target, options) {
|
|
|
26095
26328
|
const agents = await readAgentRecord(target);
|
|
26096
26329
|
const commands = await readCommandRecord(target);
|
|
26097
26330
|
const snapshots = await Promise.all([
|
|
26098
|
-
...agents.map((filename) => captureExactFile(
|
|
26099
|
-
...commands.map((filename) => captureExactFile(
|
|
26331
|
+
...agents.map((filename) => captureExactFile(path9.join(paths.agentsDir, filename))),
|
|
26332
|
+
...commands.map((filename) => captureExactFile(path9.join(paths.commandsDir, filename)))
|
|
26100
26333
|
]);
|
|
26101
26334
|
await assertWorkPackUnchangedAtBoundary(paths, target);
|
|
26102
26335
|
const backup = `${target}.previous`;
|
|
26103
26336
|
const transactionPath = `${backup}${WORK_PACK_TRANSACTION_SUFFIX}`;
|
|
26104
|
-
const transactionRoot = await mkdtemp(
|
|
26105
|
-
const claimedBackup =
|
|
26337
|
+
const transactionRoot = await mkdtemp(path9.join(os4.tmpdir(), "forge-remove-"));
|
|
26338
|
+
const claimedBackup = path9.join(transactionRoot, path9.basename(target));
|
|
26106
26339
|
let projectionsRemoved = false;
|
|
26107
26340
|
let backupClaimed = false;
|
|
26108
26341
|
try {
|
|
@@ -26120,7 +26353,7 @@ async function removeManagedWorkPackTransaction(paths, target, options) {
|
|
|
26120
26353
|
await assertWorkPackUnchangedAtBoundary(paths, backup);
|
|
26121
26354
|
projectionsRemoved = agents.length > 0;
|
|
26122
26355
|
for (const filename of agents) {
|
|
26123
|
-
const filePath =
|
|
26356
|
+
const filePath = path9.join(paths.agentsDir, filename);
|
|
26124
26357
|
await options.workPackProjectionBoundary?.("remove", filePath);
|
|
26125
26358
|
await assertExactFileState(snapshots, filePath);
|
|
26126
26359
|
await recordRemovedProjection(transactionPath, "agent", filename);
|
|
@@ -26129,7 +26362,7 @@ async function removeManagedWorkPackTransaction(paths, target, options) {
|
|
|
26129
26362
|
await options.removeWorkPackBoundary?.("after-agents");
|
|
26130
26363
|
projectionsRemoved ||= commands.length > 0;
|
|
26131
26364
|
for (const filename of commands) {
|
|
26132
|
-
const filePath =
|
|
26365
|
+
const filePath = path9.join(paths.commandsDir, filename);
|
|
26133
26366
|
await options.workPackProjectionBoundary?.("remove", filePath);
|
|
26134
26367
|
await assertExactFileState(snapshots, filePath);
|
|
26135
26368
|
await recordRemovedProjection(transactionPath, "command", filename);
|
|
@@ -26155,7 +26388,7 @@ async function removeManagedWorkPackTransaction(paths, target, options) {
|
|
|
26155
26388
|
if (await workPackOwnership(target) !== "managed") throw new Error("restored Work Pack marker missing");
|
|
26156
26389
|
await rm4(transactionRoot, { recursive: true, force: true }).catch(() => void 0);
|
|
26157
26390
|
} catch (restoreError) {
|
|
26158
|
-
throw new WorkPackRecoveryUncertainError(`Falha ao remover e restaurar o pacote de trabalho ${
|
|
26391
|
+
throw new WorkPackRecoveryUncertainError(`Falha ao remover e restaurar o pacote de trabalho ${path9.basename(target)}`, {
|
|
26159
26392
|
cause: new AggregateError([error45, restoreError])
|
|
26160
26393
|
});
|
|
26161
26394
|
}
|
|
@@ -26166,7 +26399,7 @@ async function captureExactFile(filePath) {
|
|
|
26166
26399
|
try {
|
|
26167
26400
|
const info = await lstat5(filePath);
|
|
26168
26401
|
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
|
|
26402
|
+
return { path: filePath, exists: true, bytes: await readFile8(filePath), mode: info.mode & 4095 };
|
|
26170
26403
|
} catch (error45) {
|
|
26171
26404
|
if (error45.code === "ENOENT") return { path: filePath, exists: false };
|
|
26172
26405
|
throw error45;
|
|
@@ -26176,17 +26409,17 @@ async function assertExactFileState(snapshots, filePath) {
|
|
|
26176
26409
|
const expected = snapshots.find((snapshot) => snapshot.path === filePath);
|
|
26177
26410
|
const current = await captureExactFile(filePath);
|
|
26178
26411
|
if (!expected || current.exists !== expected.exists) {
|
|
26179
|
-
throw new WorkPackLocalEditsError("local-edits-preserved", `A proje\xE7\xE3o ${
|
|
26412
|
+
throw new WorkPackLocalEditsError("local-edits-preserved", `A proje\xE7\xE3o ${path9.basename(filePath)} foi alterada durante a opera\xE7\xE3o`);
|
|
26180
26413
|
}
|
|
26181
26414
|
if (current.exists && (!current.bytes?.equals(expected.bytes) || current.mode !== expected.mode)) {
|
|
26182
|
-
throw new WorkPackLocalEditsError("local-edits-preserved", `A proje\xE7\xE3o ${
|
|
26415
|
+
throw new WorkPackLocalEditsError("local-edits-preserved", `A proje\xE7\xE3o ${path9.basename(filePath)} foi alterada durante a opera\xE7\xE3o`);
|
|
26183
26416
|
}
|
|
26184
26417
|
}
|
|
26185
26418
|
async function restoreRemovedExactFiles(snapshots) {
|
|
26186
26419
|
for (const snapshot of snapshots) {
|
|
26187
26420
|
if ((await captureExactFile(snapshot.path)).exists) continue;
|
|
26188
26421
|
if (!snapshot.exists) continue;
|
|
26189
|
-
await mkdir5(
|
|
26422
|
+
await mkdir5(path9.dirname(snapshot.path), { recursive: true });
|
|
26190
26423
|
await writeFile6(snapshot.path, snapshot.bytes);
|
|
26191
26424
|
await chmod4(snapshot.path, snapshot.mode);
|
|
26192
26425
|
}
|
|
@@ -26198,20 +26431,20 @@ async function verifyRestoredOrLocallyChangedFiles(snapshots) {
|
|
|
26198
26431
|
}
|
|
26199
26432
|
}
|
|
26200
26433
|
async function listFilesRecursively(root) {
|
|
26201
|
-
const entries = await
|
|
26434
|
+
const entries = await readdir4(root, { withFileTypes: true }).catch((error45) => {
|
|
26202
26435
|
if (error45.code === "ENOENT") return [];
|
|
26203
26436
|
throw error45;
|
|
26204
26437
|
});
|
|
26205
26438
|
const files = [];
|
|
26206
26439
|
for (const entry of entries) {
|
|
26207
|
-
const absolute =
|
|
26440
|
+
const absolute = path9.join(root, entry.name);
|
|
26208
26441
|
if (entry.isDirectory()) files.push(...await listFilesRecursively(absolute));
|
|
26209
26442
|
else if (entry.isFile()) files.push(absolute);
|
|
26210
26443
|
}
|
|
26211
26444
|
return files;
|
|
26212
26445
|
}
|
|
26213
26446
|
async function validateSkillFolder(folder, slug) {
|
|
26214
|
-
const skillMd = await
|
|
26447
|
+
const skillMd = await readFile8(path9.join(folder, "SKILL.md"), "utf8");
|
|
26215
26448
|
const frontmatter = /^---\n([\s\S]+?)\n---/.exec(skillMd)?.[1] ?? "";
|
|
26216
26449
|
if (!frontmatter.includes(`name: ${slug}`) && !frontmatter.includes(`name: "${slug}"`)) {
|
|
26217
26450
|
throw new Error(`O campo name no frontmatter de SKILL.md tem de corresponder a ${slug}`);
|
|
@@ -26222,7 +26455,7 @@ async function validateSkillFolder(folder, slug) {
|
|
|
26222
26455
|
}
|
|
26223
26456
|
async function assertNoReservedMarkerAliases(skillFolder) {
|
|
26224
26457
|
const reserved = /* @__PURE__ */ new Set([".forge-version", ".forge-agents", ".forge-commands", WORK_PACK_LOCAL_STATE_FILENAME]);
|
|
26225
|
-
const entries = await
|
|
26458
|
+
const entries = await readdir4(skillFolder);
|
|
26226
26459
|
const marker = entries.find((entry) => reserved.has(entry.toLowerCase()));
|
|
26227
26460
|
if (marker) throw new Error(`O pacote de trabalho cont\xE9m o marcador Forge reservado ${marker}`);
|
|
26228
26461
|
}
|
|
@@ -26232,14 +26465,14 @@ async function writeJsonAtomic2(filePath, value) {
|
|
|
26232
26465
|
await writeTextAtomic(filePath, content);
|
|
26233
26466
|
}
|
|
26234
26467
|
async function writeTextAtomic(filePath, content) {
|
|
26235
|
-
const dir =
|
|
26468
|
+
const dir = path9.dirname(filePath);
|
|
26236
26469
|
await mkdir5(dir, { recursive: true });
|
|
26237
|
-
const tempPath =
|
|
26470
|
+
const tempPath = path9.join(dir, `.${path9.basename(filePath)}.${process.pid}.tmp`);
|
|
26238
26471
|
await writeFile6(tempPath, content);
|
|
26239
26472
|
await rename6(tempPath, filePath);
|
|
26240
26473
|
}
|
|
26241
26474
|
async function readPluginFile(pluginPath) {
|
|
26242
|
-
return
|
|
26475
|
+
return readFile8(pluginPath, "utf8").catch((error45) => {
|
|
26243
26476
|
if (error45.code === "ENOENT") return void 0;
|
|
26244
26477
|
throw error45;
|
|
26245
26478
|
});
|
|
@@ -26272,7 +26505,7 @@ function withPluginPaths(config2, pluginPaths, removePluginPaths = []) {
|
|
|
26272
26505
|
return next;
|
|
26273
26506
|
}
|
|
26274
26507
|
async function readJsoncObject(filePath) {
|
|
26275
|
-
const raw = await
|
|
26508
|
+
const raw = await readFile8(filePath, "utf8").catch((error45) => {
|
|
26276
26509
|
if (error45.code === "ENOENT") return "";
|
|
26277
26510
|
throw error45;
|
|
26278
26511
|
});
|
|
@@ -26362,29 +26595,29 @@ limita\xE7\xF5es ou decis\xF5es pendentes.
|
|
|
26362
26595
|
S\xF3 afirmes que o trabalho continuar\xE1 em segundo plano quando tiver sido
|
|
26363
26596
|
efetivamente criada uma tarefa ou automatiza\xE7\xE3o para esse efeito.`;
|
|
26364
26597
|
function applySharedWorkerPrompt(config2) {
|
|
26365
|
-
if (config2.default_agent !== "openwork" || !
|
|
26598
|
+
if (config2.default_agent !== "openwork" || !isRecord5(config2.agent)) return false;
|
|
26366
26599
|
const agent = config2.agent.openwork;
|
|
26367
|
-
if (!
|
|
26600
|
+
if (!isRecord5(agent) || agent.mode !== "primary" || typeof agent.prompt !== "string") return false;
|
|
26368
26601
|
if (agent.prompt === FORGE_WORKER_PROMPT) return true;
|
|
26369
26602
|
const hash2 = createHash5("sha256").update(agent.prompt.replace(/\r\n/g, "\n").trim()).digest("hex");
|
|
26370
26603
|
if (hash2 !== STOCK_OPENWORK_PROMPT_SHA256) return false;
|
|
26371
26604
|
config2.agent = { ...config2.agent, openwork: { ...agent, prompt: FORGE_WORKER_PROMPT } };
|
|
26372
26605
|
return true;
|
|
26373
26606
|
}
|
|
26374
|
-
function
|
|
26607
|
+
function isRecord5(value) {
|
|
26375
26608
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
26376
26609
|
}
|
|
26377
26610
|
|
|
26378
26611
|
// packages/cli/src/localWorkerSync.ts
|
|
26379
|
-
import { readFile as
|
|
26380
|
-
import
|
|
26612
|
+
import { readFile as readFile11 } from "node:fs/promises";
|
|
26613
|
+
import path12 from "node:path";
|
|
26381
26614
|
|
|
26382
26615
|
// packages/cli/src/recoveryLauncher.ts
|
|
26383
|
-
import { chmod as chmod5, readFile as
|
|
26616
|
+
import { chmod as chmod5, readFile as readFile9 } from "node:fs/promises";
|
|
26384
26617
|
import { execFileSync } from "node:child_process";
|
|
26385
|
-
import
|
|
26618
|
+
import path10 from "node:path";
|
|
26386
26619
|
async function installRecoveryLauncher(paths, forgeBaseUrl, source = new URL("./repair.js", import.meta.url)) {
|
|
26387
|
-
const program = await
|
|
26620
|
+
const program = await readFile9(source, "utf8");
|
|
26388
26621
|
let nodePath;
|
|
26389
26622
|
try {
|
|
26390
26623
|
const runtime = JSON.parse(execFileSync(
|
|
@@ -26392,16 +26625,16 @@ async function installRecoveryLauncher(paths, forgeBaseUrl, source = new URL("./
|
|
|
26392
26625
|
["-p", 'JSON.stringify({ path: process.execPath, major: Number(process.versions.node.split(".")[0]) })'],
|
|
26393
26626
|
{ encoding: "utf8", timeout: 5e3, windowsHide: true }
|
|
26394
26627
|
));
|
|
26395
|
-
if (runtime.major < 22 || typeof runtime.major !== "number" || typeof runtime.path !== "string" || !
|
|
26628
|
+
if (runtime.major < 22 || typeof runtime.major !== "number" || typeof runtime.path !== "string" || !path10.isAbsolute(runtime.path)) throw new Error();
|
|
26396
26629
|
nodePath = runtime.path;
|
|
26397
26630
|
} catch {
|
|
26398
26631
|
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
26632
|
}
|
|
26400
26633
|
const launcherContent = renderRecoveryLauncher(nodePath, process.platform);
|
|
26401
|
-
await writeOwnerOnlyTextAtomic(
|
|
26402
|
-
await writeOwnerOnlyTextAtomic(
|
|
26634
|
+
await writeOwnerOnlyTextAtomic(path10.join(paths.forgeDir, "forge-repair.mjs"), program);
|
|
26635
|
+
await writeOwnerOnlyTextAtomic(path10.join(paths.forgeDir, "recovery-origin.json"), JSON.stringify({ forgeBaseUrl }) + "\n");
|
|
26403
26636
|
const windows = process.platform === "win32";
|
|
26404
|
-
const launcher =
|
|
26637
|
+
const launcher = path10.join(paths.forgeDir, windows ? "Reparar Forge.cmd" : "Reparar Forge.command");
|
|
26405
26638
|
await writeOwnerOnlyTextAtomic(launcher, launcherContent);
|
|
26406
26639
|
if (!windows) await chmod5(launcher, 448);
|
|
26407
26640
|
return launcher;
|
|
@@ -26422,15 +26655,15 @@ exec '${nodePath.replace(/'/g, "'\\''")}' ./forge-repair.mjs "$@"
|
|
|
26422
26655
|
|
|
26423
26656
|
// packages/cli/src/rollback.ts
|
|
26424
26657
|
import { createHash as createHash6 } from "node:crypto";
|
|
26425
|
-
import { chmod as chmod6, mkdir as mkdir6, readFile as
|
|
26426
|
-
import
|
|
26658
|
+
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";
|
|
26659
|
+
import path11 from "node:path";
|
|
26427
26660
|
async function recordRollbackEvidencePlugin(paths, expectedContent) {
|
|
26428
26661
|
if ((await readRollbackLifecycle(paths))?.state !== "pilot") return;
|
|
26429
26662
|
const capsule = await readRollbackCapsule(paths);
|
|
26430
|
-
const pluginPath =
|
|
26663
|
+
const pluginPath = path11.join(paths.pluginDir, FORGE_EVIDENCE_PLUGIN_FILENAME);
|
|
26431
26664
|
const managed = capsule?.managed.files.find((file2) => file2.path === pluginPath);
|
|
26432
26665
|
if (!capsule || !managed) return;
|
|
26433
|
-
const current = await
|
|
26666
|
+
const current = await readFile10(pluginPath, "utf8").catch(() => void 0);
|
|
26434
26667
|
if (current !== expectedContent) return;
|
|
26435
26668
|
const fingerprint = sha2562(Buffer.from(current));
|
|
26436
26669
|
if (managed.sha256 === fingerprint) return;
|
|
@@ -26444,10 +26677,10 @@ async function readRollbackCapsule(paths) {
|
|
|
26444
26677
|
return readJson(paths.rollbackCapsulePath);
|
|
26445
26678
|
}
|
|
26446
26679
|
async function writeProtectedJsonAtomic(filePath, value) {
|
|
26447
|
-
const directory =
|
|
26680
|
+
const directory = path11.dirname(filePath);
|
|
26448
26681
|
await mkdir6(directory, { recursive: true, mode: 448 });
|
|
26449
26682
|
await protectRollbackPath(directory, "directory");
|
|
26450
|
-
const temporary =
|
|
26683
|
+
const temporary = path11.join(directory, `.${path11.basename(filePath)}.${process.pid}.tmp`);
|
|
26451
26684
|
await writeFile7(temporary, `${JSON.stringify(value, null, 2)}
|
|
26452
26685
|
`, { mode: 384 });
|
|
26453
26686
|
await protectRollbackPath(temporary, "file");
|
|
@@ -26457,7 +26690,7 @@ async function protectRollbackPath(filePath, kind, options = {}) {
|
|
|
26457
26690
|
await protectOwnerOnlyPath(filePath, kind, { ...options, failureContext: "o material de rollback" });
|
|
26458
26691
|
}
|
|
26459
26692
|
async function readJson(filePath) {
|
|
26460
|
-
const raw = await
|
|
26693
|
+
const raw = await readFile10(filePath, "utf8").catch((error45) => {
|
|
26461
26694
|
if (error45.code === "ENOENT") return void 0;
|
|
26462
26695
|
throw error45;
|
|
26463
26696
|
});
|
|
@@ -26470,11 +26703,11 @@ function sha2562(value) {
|
|
|
26470
26703
|
|
|
26471
26704
|
// packages/cli/src/localWorkerSync.ts
|
|
26472
26705
|
async function syncLocalWorker(paths, credentials, manifest) {
|
|
26473
|
-
const recovery = await recoverCoreSyncTransaction({ journalPath:
|
|
26706
|
+
const recovery = await recoverCoreSyncTransaction({ journalPath: path12.join(paths.forgeDir, "core-sync-journal.json") });
|
|
26474
26707
|
if (recovery.status === "uncertain") throw new CoreSyncUncertainError(recovery.message, recovery.uncertainPaths);
|
|
26475
26708
|
let current;
|
|
26476
26709
|
try {
|
|
26477
|
-
current = JSON.parse(await
|
|
26710
|
+
current = JSON.parse(await readFile11(paths.opencodeConfigPath, "utf8"));
|
|
26478
26711
|
} catch {
|
|
26479
26712
|
throw new Error("A configura\xE7\xE3o local n\xE3o \xE9 JSON simples v\xE1lido; preserve os ficheiros e pe\xE7a apoio.");
|
|
26480
26713
|
}
|
|
@@ -26492,27 +26725,92 @@ async function syncLocalWorker(paths, credentials, manifest) {
|
|
|
26492
26725
|
return result;
|
|
26493
26726
|
}
|
|
26494
26727
|
|
|
26728
|
+
// packages/cli/src/openworkEngine.ts
|
|
26729
|
+
import { lstat as lstat6, readFile as readFile12, realpath } from "node:fs/promises";
|
|
26730
|
+
import path13 from "node:path";
|
|
26731
|
+
var OPENWORK_ENGINE_HEADER = "// Minimal Forge OpenWork engine configuration\n";
|
|
26732
|
+
async function inspectOpenworkEngineConfig(directory) {
|
|
26733
|
+
if (!path13.isAbsolute(directory)) throw new Error("Indique a pasta absoluta de configura\xE7\xE3o do motor ativo.");
|
|
26734
|
+
const root = await realpath(directory);
|
|
26735
|
+
const generatedPath = path13.join(root, "opencode.json");
|
|
26736
|
+
const generatedEntry = await lstat6(generatedPath);
|
|
26737
|
+
if (!generatedEntry.isFile() || generatedEntry.isSymbolicLink()) throw new Error("Preserve a configura\xE7\xE3o do motor; o ficheiro gerado n\xE3o \xE9 regular.");
|
|
26738
|
+
let generated;
|
|
26739
|
+
try {
|
|
26740
|
+
generated = JSON.parse(await readFile12(generatedPath, "utf8"));
|
|
26741
|
+
} catch {
|
|
26742
|
+
throw new Error("N\xE3o foi poss\xEDvel reconhecer a configura\xE7\xE3o do motor OpenCode 2.");
|
|
26743
|
+
}
|
|
26744
|
+
if (!generated || typeof generated !== "object" || !generated.providers || typeof generated.providers !== "object") {
|
|
26745
|
+
throw new Error("Esta pasta n\xE3o cont\xE9m a configura\xE7\xE3o nativa do motor OpenCode 2 do OpenWork.");
|
|
26746
|
+
}
|
|
26747
|
+
const file2 = path13.join(root, "opencode.jsonc");
|
|
26748
|
+
let content;
|
|
26749
|
+
try {
|
|
26750
|
+
const entry = await lstat6(file2);
|
|
26751
|
+
if (!entry.isFile() || entry.isSymbolicLink()) throw new Error("Preserve o ficheiro complementar existente; n\xE3o \xE9 um ficheiro regular.");
|
|
26752
|
+
content = await readFile12(file2, "utf8");
|
|
26753
|
+
} catch (error45) {
|
|
26754
|
+
if (error45.code !== "ENOENT") throw error45;
|
|
26755
|
+
}
|
|
26756
|
+
if (content !== void 0 && !content.startsWith(OPENWORK_ENGINE_HEADER)) {
|
|
26757
|
+
throw new Error("J\xE1 existe uma configura\xE7\xE3o complementar alheia ao Forge. Preserve-a e pe\xE7a revis\xE3o acompanhada.");
|
|
26758
|
+
}
|
|
26759
|
+
return { directory: root, file: file2, configured: content !== void 0, content };
|
|
26760
|
+
}
|
|
26761
|
+
function renderOpenworkEngineConfig(manifest, credentials, paths, directory, existing = {}) {
|
|
26762
|
+
if (!manifest.workPackSyncPluginVersion) throw new Error("O servidor ainda n\xE3o aprovou uma vers\xE3o exata do plugin para o segundo motor.");
|
|
26763
|
+
const mcp = existing.mcp && typeof existing.mcp === "object" ? existing.mcp : {};
|
|
26764
|
+
const config2 = mergeWorkerOpenCodeConfig(
|
|
26765
|
+
{ permission: existing.permission, mcp: "firecrawl" in mcp ? { firecrawl: mcp.firecrawl } : {} },
|
|
26766
|
+
manifest,
|
|
26767
|
+
credentials.forgeBaseUrl,
|
|
26768
|
+
credentials.forgeApiKey,
|
|
26769
|
+
{ automaticWorkPackSync: true, localConfig: true }
|
|
26770
|
+
);
|
|
26771
|
+
const version2 = configuredWorkPackSyncPluginVersion(config2);
|
|
26772
|
+
const parts = version2?.split(".").map(Number);
|
|
26773
|
+
if (!parts || parts.length !== 3 || !(parts[0] > 0 || parts[1] > 1 || parts[1] === 1 && parts[2] >= 49)) {
|
|
26774
|
+
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.");
|
|
26775
|
+
}
|
|
26776
|
+
config2.plugin = (config2.plugin ?? []).map((entry) => Array.isArray(entry) ? [entry[0], { ...entry[1], openworkEngineConfigDir: directory }] : entry);
|
|
26777
|
+
return { ...config2, skills: [paths.skillsDir] };
|
|
26778
|
+
}
|
|
26779
|
+
async function writeOpenworkEngineConfig(directory, config2) {
|
|
26780
|
+
const state = await inspectOpenworkEngineConfig(directory);
|
|
26781
|
+
const content = OPENWORK_ENGINE_HEADER + JSON.stringify(config2, null, 2) + "\n";
|
|
26782
|
+
if (state.content === content) return { changed: false };
|
|
26783
|
+
await writeOwnerOnlyTextAtomic(state.file, content);
|
|
26784
|
+
return { changed: true };
|
|
26785
|
+
}
|
|
26786
|
+
|
|
26495
26787
|
// packages/cli/src/workPackSyncPlugin.ts
|
|
26496
|
-
var PLUGIN_VERSION = "0.1.
|
|
26788
|
+
var PLUGIN_VERSION = "0.1.51";
|
|
26497
26789
|
var FORGE_DECISION_TIMEOUT_MS = 11e4;
|
|
26498
26790
|
var STATUS_FILENAME = "work-pack-startup-status.json";
|
|
26499
26791
|
var activeSync = /* @__PURE__ */ new Map();
|
|
26500
|
-
|
|
26501
|
-
|
|
26502
|
-
|
|
26792
|
+
function isLocalConfig(options) {
|
|
26793
|
+
return Boolean(options && typeof options === "object" && "localConfig" in options && options.localConfig === true);
|
|
26794
|
+
}
|
|
26795
|
+
function startupSync(forgeBaseUrl, localConfig, observe, input) {
|
|
26503
26796
|
const syncKey = `${forgeBaseUrl}:${localConfig ? "local" : "remote"}`;
|
|
26504
26797
|
let sync = activeSync.get(syncKey);
|
|
26505
26798
|
if (!sync) {
|
|
26506
|
-
sync = synchronizeAtStartup(forgeBaseUrl,
|
|
26799
|
+
sync = synchronizeAtStartup(forgeBaseUrl, observe, localConfig, input);
|
|
26507
26800
|
activeSync.set(syncKey, sync);
|
|
26508
26801
|
}
|
|
26509
|
-
|
|
26510
|
-
|
|
26511
|
-
|
|
26512
|
-
|
|
26513
|
-
|
|
26514
|
-
|
|
26515
|
-
|
|
26802
|
+
return sync;
|
|
26803
|
+
}
|
|
26804
|
+
function createForgeTools(forgeBaseUrl, state) {
|
|
26805
|
+
return {
|
|
26806
|
+
forge_decide_run: createForgeDecisionRunTool(forgeBaseUrl, state.decisionBaseUrl, state.paths),
|
|
26807
|
+
forge_decide: createForgeDecisionTool(forgeBaseUrl, state.decisionBaseUrl, state.paths),
|
|
26808
|
+
forge_generate_codebook: createForgeCodebookTool(forgeBaseUrl, state.decisionBaseUrl, state.paths),
|
|
26809
|
+
forge_feedback: createForgeFeedbackTool(forgeBaseUrl, state.paths),
|
|
26810
|
+
forge_image: createForgeImageTool(forgeBaseUrl, state.decisionBaseUrl, state.paths)
|
|
26811
|
+
};
|
|
26812
|
+
}
|
|
26813
|
+
function createEvidenceReporters(forgeBaseUrl, state) {
|
|
26516
26814
|
const reportEvidence = async (sessionID, callID, slug, kind) => {
|
|
26517
26815
|
const { forgeApiKey } = await readForgeCredentials(state.paths, forgeBaseUrl);
|
|
26518
26816
|
const credentialId = createHash7("sha256").update(forgeApiKey).digest("hex");
|
|
@@ -26530,22 +26828,37 @@ var ForgeWorkPackSyncServer = async (_input, options) => {
|
|
|
26530
26828
|
console.error("[Forge evidence] Reasoning guard identity unavailable; event not queued");
|
|
26531
26829
|
});
|
|
26532
26830
|
};
|
|
26831
|
+
const reportSkillInvocation = async (sessionID, callID, name) => {
|
|
26832
|
+
const slug = typeof name === "string" ? name.trim().toLowerCase() : "";
|
|
26833
|
+
if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug)) return;
|
|
26834
|
+
try {
|
|
26835
|
+
await readFile13(path14.join(state.paths.skillsDir, slug, ".forge-version"), "utf8");
|
|
26836
|
+
} catch {
|
|
26837
|
+
return;
|
|
26838
|
+
}
|
|
26839
|
+
try {
|
|
26840
|
+
await reportEvidence(sessionID, callID, slug, "work_pack_invocation");
|
|
26841
|
+
} catch {
|
|
26842
|
+
console.error("[Forge evidence] Invocation identity unavailable; event not queued");
|
|
26843
|
+
}
|
|
26844
|
+
};
|
|
26845
|
+
return { reportReasoningLoop, reportSkillInvocation };
|
|
26846
|
+
}
|
|
26847
|
+
var ForgeWorkPackSyncServer = async (_input, options) => {
|
|
26848
|
+
const forgeBaseUrl = parseForgeBaseUrl(options);
|
|
26849
|
+
const state = await startupSync(forgeBaseUrl, isLocalConfig(options), () => observeRuntime(_input), _input);
|
|
26850
|
+
const legacyPath = path14.join(state.paths.pluginDir, FORGE_EVIDENCE_PLUGIN_FILENAME);
|
|
26851
|
+
const ownershipSymbol = /* @__PURE__ */ Symbol.for("minimal-forge.legacy-evidence-owners.v1");
|
|
26852
|
+
const shared = globalThis;
|
|
26853
|
+
const legacyOwners = shared[ownershipSymbol] ??= /* @__PURE__ */ new Set();
|
|
26854
|
+
const legacyOwnerKey = JSON.stringify([forgeBaseUrl, legacyPath]);
|
|
26855
|
+
const client = reasoningLoopGuardClient(_input);
|
|
26856
|
+
const { reportReasoningLoop, reportSkillInvocation } = createEvidenceReporters(forgeBaseUrl, state);
|
|
26533
26857
|
return {
|
|
26534
26858
|
...client ? { event: createReasoningLoopGuard(client, console.error, reportReasoningLoop) } : {},
|
|
26535
26859
|
"tool.execute.after": async (input) => {
|
|
26536
26860
|
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
|
-
}
|
|
26861
|
+
await reportSkillInvocation(input.sessionID, input.callID, input.args?.name);
|
|
26549
26862
|
},
|
|
26550
26863
|
config: async (config2) => {
|
|
26551
26864
|
const entries = Array.isArray(config2.plugin) ? config2.plugin : [];
|
|
@@ -26553,7 +26866,7 @@ var ForgeWorkPackSyncServer = async (_input, options) => {
|
|
|
26553
26866
|
const name = Array.isArray(entry) ? entry[0] : entry;
|
|
26554
26867
|
return name === legacyPath || name === pathToFileURL(legacyPath).href;
|
|
26555
26868
|
});
|
|
26556
|
-
const legacy = registered ? await
|
|
26869
|
+
const legacy = registered ? await readFile13(legacyPath, "utf8").catch(() => "") : "";
|
|
26557
26870
|
const oldLegacyRegistered = registered && legacy.startsWith(FORGE_PLUGIN_HEADER) && legacy.includes("work_pack_invocation") && !legacy.includes("minimal-forge.skill-usage.v1");
|
|
26558
26871
|
if (oldLegacyRegistered) legacyOwners.add(legacyOwnerKey);
|
|
26559
26872
|
if (oldLegacyRegistered) await writeFile8(legacyPath, renderEvidencePlugin()).catch(() => {
|
|
@@ -26562,15 +26875,61 @@ var ForgeWorkPackSyncServer = async (_input, options) => {
|
|
|
26562
26875
|
await projectCurrentExtensions(config2, state);
|
|
26563
26876
|
if (state.forgeConfigVerified) applySharedWorkerPrompt(config2);
|
|
26564
26877
|
},
|
|
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
|
-
}
|
|
26878
|
+
tool: createForgeTools(forgeBaseUrl, state)
|
|
26572
26879
|
};
|
|
26573
26880
|
};
|
|
26881
|
+
async function ForgeWorkPackSyncSetup(ctx) {
|
|
26882
|
+
const forgeBaseUrl = parseForgeBaseUrl(ctx.options);
|
|
26883
|
+
const paths = resolveStartupPaths();
|
|
26884
|
+
const sync = startupSync(forgeBaseUrl, isLocalConfig(ctx.options), async () => observeOpenCode2Runtime(ctx.app));
|
|
26885
|
+
sync.catch((error45) => console.error("[Forge work-pack sync] Startup sync could not run:", safeErrorMessage(error45)));
|
|
26886
|
+
const syncedTools = sync.then(async (state) => {
|
|
26887
|
+
const directory = ctx.options.openworkEngineConfigDir;
|
|
26888
|
+
if (typeof directory === "string" && state.manifest) {
|
|
26889
|
+
const active = process.env.OPENCODE_CONFIG_DIR;
|
|
26890
|
+
if (!active || await realpath2(active) !== await realpath2(directory)) {
|
|
26891
|
+
throw new Error("A pasta do motor ativo mudou. Confirme a liga\xE7\xE3o Forge neste perfil do OpenWork.");
|
|
26892
|
+
}
|
|
26893
|
+
const credentials = await readForgeCredentials(state.paths, forgeBaseUrl);
|
|
26894
|
+
const canonical = objectRecord2(parseJsonc(await readFile13(state.paths.opencodeConfigPath, "utf8")));
|
|
26895
|
+
const config2 = renderOpenworkEngineConfig(state.manifest, credentials, state.paths, directory, canonical);
|
|
26896
|
+
if (state.partialWorkPackSync) {
|
|
26897
|
+
const companion = await inspectOpenworkEngineConfig(directory);
|
|
26898
|
+
if (!companion.content) return createForgeTools(forgeBaseUrl, state);
|
|
26899
|
+
await refreshPartialProjections(config2, parseJsonc(companion.content), state.paths, state.before, state.partialWorkPackSync);
|
|
26900
|
+
} else {
|
|
26901
|
+
await projectCurrentExtensions(config2, state);
|
|
26902
|
+
}
|
|
26903
|
+
for (const key of ["agent", "command"]) if (Object.keys(objectRecord2(config2[key])).length === 0) delete config2[key];
|
|
26904
|
+
await writeOpenworkEngineConfig(directory, config2);
|
|
26905
|
+
}
|
|
26906
|
+
return createForgeTools(forgeBaseUrl, state);
|
|
26907
|
+
});
|
|
26908
|
+
syncedTools.catch(() => void 0);
|
|
26909
|
+
const { reportReasoningLoop, reportSkillInvocation } = createEvidenceReporters(forgeBaseUrl, { paths });
|
|
26910
|
+
const directoryOf = sessionDirectoryResolver(ctx);
|
|
26911
|
+
const registrations = Object.entries(createForgeTools(forgeBaseUrl, { paths, decisionBaseUrl: forgeBaseUrl })).filter(([name]) => name !== "forge_feedback").map(([name, shape]) => openCode2Tool(name, {
|
|
26912
|
+
description: shape.description,
|
|
26913
|
+
args: shape.args,
|
|
26914
|
+
async execute(args, context) {
|
|
26915
|
+
const tools = await syncedTools;
|
|
26916
|
+
context.abort.throwIfAborted();
|
|
26917
|
+
return tools[name].execute(args, context);
|
|
26918
|
+
}
|
|
26919
|
+
}, directoryOf));
|
|
26920
|
+
await ctx.tool.transform((editor) => {
|
|
26921
|
+
for (const registration of registrations) editor.add(registration);
|
|
26922
|
+
});
|
|
26923
|
+
await ctx.tool.hook("execute.after", async (event) => {
|
|
26924
|
+
try {
|
|
26925
|
+
const call = completedSkillCall(event);
|
|
26926
|
+
if (call) await reportSkillInvocation(call.sessionID, call.callID, call.name);
|
|
26927
|
+
} catch {
|
|
26928
|
+
console.error("[Forge evidence] Invocation could not be reported");
|
|
26929
|
+
}
|
|
26930
|
+
});
|
|
26931
|
+
return startReasoningLoopGuard(ctx, reportReasoningLoop);
|
|
26932
|
+
}
|
|
26574
26933
|
function reasoningLoopGuardClient(input) {
|
|
26575
26934
|
if (!input || typeof input !== "object" || !("client" in input)) return void 0;
|
|
26576
26935
|
const client = input.client;
|
|
@@ -26590,7 +26949,7 @@ function createForgeImageTool(forgeBaseUrl, gatewayBaseUrl, paths) {
|
|
|
26590
26949
|
const requestId = randomUUID4();
|
|
26591
26950
|
let referenceDataUrl;
|
|
26592
26951
|
if (args.referencePath) {
|
|
26593
|
-
const bytes = await
|
|
26952
|
+
const bytes = await readFile13(args.referencePath);
|
|
26594
26953
|
if (bytes.byteLength > 25e5) throw new Error("A imagem de refer\xEAncia \xE9 demasiado grande. Reduza-a antes de tentar novamente.");
|
|
26595
26954
|
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
26955
|
if (!mime) throw new Error("A refer\xEAncia tem de ser PNG, JPEG ou WebP.");
|
|
@@ -26616,14 +26975,14 @@ function createForgeImageTool(forgeBaseUrl, gatewayBaseUrl, paths) {
|
|
|
26616
26975
|
if (image.byteLength > 8 * 1024 * 1024 || !image.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) {
|
|
26617
26976
|
throw new Error(`O PNG recebido \xE9 inv\xE1lido. Refer\xEAncia: ${requestId}`);
|
|
26618
26977
|
}
|
|
26619
|
-
const destination =
|
|
26978
|
+
const destination = path14.join(context.directory, `forge-image-${requestId}.png`);
|
|
26620
26979
|
await writeFile8(destination, image, { flag: "wx" });
|
|
26621
26980
|
const reset = body.quota && new Intl.DateTimeFormat("pt-PT", { dateStyle: "long", timeZone: "Europe/Lisbon" }).format(new Date(body.quota.resetsAt));
|
|
26622
26981
|
const remaining = body.quota ? ` Restam ${body.quota.remaining} imagens at\xE9 ${reset}.` : "";
|
|
26623
26982
|
return {
|
|
26624
26983
|
title: "Imagem criada",
|
|
26625
26984
|
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:
|
|
26985
|
+
attachments: [{ type: "file", mime: "image/png", url: `data:image/png;base64,${body.b64_json}`, filename: path14.basename(destination) }]
|
|
26627
26986
|
};
|
|
26628
26987
|
}
|
|
26629
26988
|
});
|
|
@@ -26665,9 +27024,9 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseD
|
|
|
26665
27024
|
let requestBody;
|
|
26666
27025
|
if (fromFile) {
|
|
26667
27026
|
const file2 = await fileInsideWorkspace(context.directory, args.request_file);
|
|
26668
|
-
const planFile =
|
|
26669
|
-
if (!responseDirectory &&
|
|
26670
|
-
const plan = JSON.parse(await
|
|
27027
|
+
const planFile = path14.join(path14.dirname(path14.dirname(file2)), "plan.json");
|
|
27028
|
+
if (!responseDirectory && path14.basename(path14.dirname(file2)) === "requests" && await fileExists(planFile)) {
|
|
27029
|
+
const plan = JSON.parse(await readFile13(planFile, "utf8"));
|
|
26671
27030
|
if (plan?.engine === "jev-batch" && plan.model === "typesafe/jev-1.13" && Array.isArray(plan.batches)) {
|
|
26672
27031
|
let batch;
|
|
26673
27032
|
for (const candidate of plan.batches) {
|
|
@@ -26680,7 +27039,7 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseD
|
|
|
26680
27039
|
return createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths).execute({ plan_file: planFile, batch_id: batch.batch_id }, context);
|
|
26681
27040
|
}
|
|
26682
27041
|
}
|
|
26683
|
-
const raw = await
|
|
27042
|
+
const raw = await readFile13(file2, "utf8");
|
|
26684
27043
|
if (Buffer.byteLength(raw) > 512 * 1024) throw new Error("O ficheiro de pedido excede 512 KiB.");
|
|
26685
27044
|
let parsed;
|
|
26686
27045
|
try {
|
|
@@ -26699,11 +27058,11 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseD
|
|
|
26699
27058
|
if (args.state === void 0 || !args.questions || Object.keys(args.questions).length === 0) throw new Error("Indica state e questions.");
|
|
26700
27059
|
requestBody = { state: args.state, questions: args.questions };
|
|
26701
27060
|
}
|
|
26702
|
-
const responseDir = await mkdtemp2(
|
|
26703
|
-
const responseFile =
|
|
27061
|
+
const responseDir = await mkdtemp2(path14.join(responseDirectory ?? context.directory, ".forge-decision-"));
|
|
27062
|
+
const responseFile = path14.join(responseDir, "response.json");
|
|
26704
27063
|
try {
|
|
26705
27064
|
const credentials = await readForgeCredentials(paths, forgeBaseUrl);
|
|
26706
|
-
const probeFile =
|
|
27065
|
+
const probeFile = path14.join(responseDir, ".write-test");
|
|
26707
27066
|
await writeFile8(probeFile, "", { flag: "wx", mode: 384 });
|
|
26708
27067
|
await unlink(probeFile);
|
|
26709
27068
|
context.abort.throwIfAborted();
|
|
@@ -26752,10 +27111,10 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseD
|
|
|
26752
27111
|
});
|
|
26753
27112
|
}
|
|
26754
27113
|
async function fileInsideWorkspace(directory, candidate) {
|
|
26755
|
-
const workspace = await
|
|
26756
|
-
const file2 = await
|
|
26757
|
-
const relative =
|
|
26758
|
-
if (!relative || (relative === ".." || relative.startsWith(`..${
|
|
27114
|
+
const workspace = await realpath2(directory);
|
|
27115
|
+
const file2 = await realpath2(path14.resolve(workspace, candidate));
|
|
27116
|
+
const relative = path14.relative(workspace, file2);
|
|
27117
|
+
if (!relative || (relative === ".." || relative.startsWith(`..${path14.sep}`)) || path14.isAbsolute(relative)) throw new Error("O ficheiro tem de estar dentro do workspace.");
|
|
26759
27118
|
return file2;
|
|
26760
27119
|
}
|
|
26761
27120
|
async function fileExists(candidate) {
|
|
@@ -26770,7 +27129,7 @@ async function fileExists(candidate) {
|
|
|
26770
27129
|
async function ensureJevDirectory(directory, filesystem = { stat: stat3, mkdir: mkdir7 }) {
|
|
26771
27130
|
try {
|
|
26772
27131
|
if ((await filesystem.stat(directory)).isDirectory()) return;
|
|
26773
|
-
throw new Error(`O destino ${
|
|
27132
|
+
throw new Error(`O destino ${path14.basename(directory)} existe, mas n\xE3o \xE9 uma pasta. Preservar o conte\xFAdo e verificar o caminho.`);
|
|
26774
27133
|
} catch (error45) {
|
|
26775
27134
|
if (error45.code !== "ENOENT") throw error45;
|
|
26776
27135
|
}
|
|
@@ -26790,7 +27149,7 @@ function canonicalJson(value) {
|
|
|
26790
27149
|
return JSON.stringify(value);
|
|
26791
27150
|
}
|
|
26792
27151
|
async function validateSavedDecision(file2, request) {
|
|
26793
|
-
const body = JSON.parse(await
|
|
27152
|
+
const body = JSON.parse(await readFile13(file2, "utf8"));
|
|
26794
27153
|
const answers = body.answers;
|
|
26795
27154
|
const questions = request.questions;
|
|
26796
27155
|
const usage = body.usage;
|
|
@@ -26809,7 +27168,7 @@ async function acquireJevRunLock(lockDir) {
|
|
|
26809
27168
|
let owner;
|
|
26810
27169
|
let ownerRaw;
|
|
26811
27170
|
try {
|
|
26812
|
-
ownerRaw = await
|
|
27171
|
+
ownerRaw = await readFile13(path14.join(lockDir, "owner.json"), "utf8");
|
|
26813
27172
|
owner = JSON.parse(ownerRaw);
|
|
26814
27173
|
} catch {
|
|
26815
27174
|
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 +27202,41 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
|
|
|
26843
27202
|
},
|
|
26844
27203
|
async execute(args, context) {
|
|
26845
27204
|
const planFile = await fileInsideWorkspace(context.directory, args.plan_file);
|
|
26846
|
-
if (
|
|
26847
|
-
const runDir =
|
|
26848
|
-
const plan = JSON.parse(await
|
|
27205
|
+
if (path14.basename(planFile) !== "plan.json" || path14.basename(path14.dirname(planFile)) !== "jev") throw new Error("Indica o ficheiro jev/plan.json.");
|
|
27206
|
+
const runDir = path14.dirname(path14.dirname(planFile));
|
|
27207
|
+
const plan = JSON.parse(await readFile13(planFile, "utf8"));
|
|
26849
27208
|
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
27209
|
const allBatches = plan.batches;
|
|
26851
27210
|
const batches = args.batch_id ? allBatches.filter((batch) => batch.batch_id === args.batch_id) : allBatches;
|
|
26852
27211
|
if (args.batch_id && batches.length !== 1) throw new Error("O lote indicado n\xE3o pertence ao plano Jev.");
|
|
26853
|
-
const responsePath =
|
|
27212
|
+
const responsePath = path14.join(runDir, "jev", "responses");
|
|
26854
27213
|
await ensureJevDirectory(responsePath);
|
|
26855
27214
|
const responseDir = await fileInsideWorkspace(context.directory, responsePath);
|
|
26856
|
-
if (
|
|
26857
|
-
const lockDir =
|
|
27215
|
+
if (path14.dirname(responseDir) !== path14.join(runDir, "jev")) throw new Error("A pasta de respostas tem de pertencer ao run Jev.");
|
|
27216
|
+
const lockDir = path14.join(runDir, "jev", ".decide-run.lock");
|
|
26858
27217
|
const interrupted = await acquireJevRunLock(lockDir);
|
|
26859
27218
|
let saved = 0;
|
|
26860
27219
|
let skipped = 0;
|
|
26861
27220
|
let recovered = 0;
|
|
26862
27221
|
const repeated = [];
|
|
26863
27222
|
try {
|
|
26864
|
-
const ownerFile =
|
|
27223
|
+
const ownerFile = path14.join(lockDir, "owner.json");
|
|
26865
27224
|
await writeOwnerOnlyTextAtomic(ownerFile, JSON.stringify({ ...interrupted, pid: process.pid, hostname: os5.hostname(), started_at: (/* @__PURE__ */ new Date()).toISOString() }));
|
|
26866
|
-
const attemptsPath =
|
|
27225
|
+
const attemptsPath = path14.join(runDir, "jev", "attempts");
|
|
26867
27226
|
await ensureJevDirectory(attemptsPath);
|
|
26868
27227
|
const attemptsDir = await fileInsideWorkspace(context.directory, attemptsPath);
|
|
26869
|
-
if (
|
|
27228
|
+
if (path14.dirname(attemptsDir) !== path14.join(runDir, "jev")) throw new Error("A pasta de tentativas tem de pertencer ao run Jev.");
|
|
26870
27229
|
for (const batch of batches) {
|
|
26871
27230
|
context.abort.throwIfAborted();
|
|
26872
27231
|
const batchId = batch.batch_id;
|
|
26873
27232
|
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
27233
|
throw new Error("O plano Jev cont\xE9m um lote inv\xE1lido.");
|
|
26875
27234
|
}
|
|
26876
|
-
const acceptedFile =
|
|
26877
|
-
const responseFile =
|
|
27235
|
+
const acceptedFile = path14.join(runDir, "jev", "accepted", `${batchId}.json`);
|
|
27236
|
+
const responseFile = path14.join(responseDir, `${batchId}.response.json`);
|
|
26878
27237
|
const requestFile = await fileInsideWorkspace(context.directory, batch.request_file);
|
|
26879
|
-
if (
|
|
26880
|
-
const request = JSON.parse(await
|
|
27238
|
+
if (path14.dirname(requestFile) !== path14.join(runDir, "jev", "requests")) throw new Error(`${batchId}: pedido fora do run.`);
|
|
27239
|
+
const request = JSON.parse(await readFile13(requestFile, "utf8"));
|
|
26881
27240
|
const fingerprint = createHash7("sha256").update(canonicalJson(request)).digest("hex");
|
|
26882
27241
|
if (fingerprint !== batch.request_fingerprint) throw new Error(`${batchId}: fingerprint do pedido n\xE3o corresponde ao plano.`);
|
|
26883
27242
|
if (await fileExists(acceptedFile)) {
|
|
@@ -26890,9 +27249,9 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
|
|
|
26890
27249
|
skipped++;
|
|
26891
27250
|
continue;
|
|
26892
27251
|
}
|
|
26893
|
-
const attemptsFile =
|
|
27252
|
+
const attemptsFile = path14.join(attemptsDir, `${batchId}.json`);
|
|
26894
27253
|
let attempts = { request_fingerprint: fingerprint, attempts: 0, response_files: [] };
|
|
26895
|
-
if (await fileExists(attemptsFile)) attempts = JSON.parse(await
|
|
27254
|
+
if (await fileExists(attemptsFile)) attempts = JSON.parse(await readFile13(attemptsFile, "utf8"));
|
|
26896
27255
|
else if (interrupted.batch_id === batchId) {
|
|
26897
27256
|
if (interrupted.request_fingerprint !== fingerprint) throw new Error(`${batchId}: fingerprint da chamada interrompida n\xE3o corresponde ao plano.`);
|
|
26898
27257
|
attempts.attempts = 1;
|
|
@@ -26905,13 +27264,13 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
|
|
|
26905
27264
|
if (!await fileExists(attemptsFile) && attempts.attempts > 0) await persistAttempts();
|
|
26906
27265
|
const stop = (error45, detail = {}) => JSON.stringify({ verified: false, saved, skipped, recovered, repeated, stopped_at: batchId, ...detail, error: error45 });
|
|
26907
27266
|
const recoverResponse = async () => {
|
|
26908
|
-
const legacyAllocations = interrupted.batch_id === batchId && interrupted.request_fingerprint === fingerprint ? (await
|
|
27267
|
+
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
27268
|
const candidates = [...attempts.response_files, ...legacyAllocations];
|
|
26910
27269
|
for (const candidate of new Set(candidates)) {
|
|
26911
27270
|
if (typeof candidate !== "string") throw new Error("Registo de recupera\xE7\xE3o inv\xE1lido.");
|
|
26912
27271
|
if (!await fileExists(candidate)) continue;
|
|
26913
27272
|
const file2 = await fileInsideWorkspace(context.directory, candidate);
|
|
26914
|
-
if (
|
|
27273
|
+
if (path14.dirname(path14.dirname(file2)) !== responseDir) throw new Error("Resposta recuper\xE1vel fora da pasta do lote.");
|
|
26915
27274
|
try {
|
|
26916
27275
|
await validateSavedDecision(file2, request);
|
|
26917
27276
|
} catch {
|
|
@@ -26970,7 +27329,7 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
|
|
|
26970
27329
|
let identical = false;
|
|
26971
27330
|
if (error45.code === "EEXIST") {
|
|
26972
27331
|
try {
|
|
26973
|
-
identical = await
|
|
27332
|
+
identical = await readFile13(source, "utf8") === await readFile13(responseFile, "utf8");
|
|
26974
27333
|
} catch {
|
|
26975
27334
|
}
|
|
26976
27335
|
}
|
|
@@ -26978,7 +27337,7 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
|
|
|
26978
27337
|
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
27338
|
}
|
|
26980
27339
|
}
|
|
26981
|
-
await unlink(source).then(() => rmdir(
|
|
27340
|
+
await unlink(source).then(() => rmdir(path14.dirname(source))).catch(() => void 0);
|
|
26982
27341
|
saved++;
|
|
26983
27342
|
if (args.batch_id) return JSON.stringify({ ...await validateSavedDecision(responseFile, request), response_file: responseFile, repeated });
|
|
26984
27343
|
}
|
|
@@ -27056,14 +27415,15 @@ function createForgeFeedbackTool(forgeBaseUrl, paths) {
|
|
|
27056
27415
|
}
|
|
27057
27416
|
});
|
|
27058
27417
|
}
|
|
27059
|
-
async function synchronizeAtStartup(forgeBaseUrl,
|
|
27418
|
+
async function synchronizeAtStartup(forgeBaseUrl, observe, localConfig, input) {
|
|
27060
27419
|
const paths = resolveStartupPaths();
|
|
27061
27420
|
const before = await managedProjectionNames(paths);
|
|
27062
27421
|
let credentials;
|
|
27063
27422
|
let forgeConfigVerified = false;
|
|
27423
|
+
let appliedLocalSync;
|
|
27064
27424
|
let pluginUpdate;
|
|
27065
27425
|
let decisionBaseUrl = forgeBaseUrl;
|
|
27066
|
-
const runtime = await
|
|
27426
|
+
const runtime = await observe();
|
|
27067
27427
|
try {
|
|
27068
27428
|
await retireDebugCapture(paths);
|
|
27069
27429
|
credentials = await readForgeCredentials(paths, forgeBaseUrl);
|
|
@@ -27072,7 +27432,8 @@ async function synchronizeAtStartup(forgeBaseUrl, input, localConfig) {
|
|
|
27072
27432
|
forgeConfigVerified = true;
|
|
27073
27433
|
const result = localConfig ? await syncLocalWorker(paths, credentials, manifest) : await applyWorkPackManifest(paths, credentials, manifest, {});
|
|
27074
27434
|
if (localConfig) {
|
|
27075
|
-
|
|
27435
|
+
appliedLocalSync = { manifest, partialWorkPackSync: result };
|
|
27436
|
+
const config2 = objectRecord2(parseJsonc(await readFile13(paths.opencodeConfigPath, "utf8")));
|
|
27076
27437
|
const targetVersion = configuredWorkPackSyncPluginVersion(config2);
|
|
27077
27438
|
if (targetVersion) pluginUpdate = { targetVersion, restartRequired: targetVersion !== PLUGIN_VERSION };
|
|
27078
27439
|
if (pluginUpdate?.restartRequired) {
|
|
@@ -27102,7 +27463,7 @@ async function synchronizeAtStartup(forgeBaseUrl, input, localConfig) {
|
|
|
27102
27463
|
installed: result.installed,
|
|
27103
27464
|
removed: result.removed
|
|
27104
27465
|
});
|
|
27105
|
-
return { paths, before, after, forgeConfigVerified, decisionBaseUrl };
|
|
27466
|
+
return { paths, before, after, forgeConfigVerified, decisionBaseUrl, manifest };
|
|
27106
27467
|
} catch (error45) {
|
|
27107
27468
|
const message = safeErrorMessage(error45);
|
|
27108
27469
|
console.error("[Forge work-pack sync] Startup sync failed:", message);
|
|
@@ -27119,13 +27480,13 @@ async function synchronizeAtStartup(forgeBaseUrl, input, localConfig) {
|
|
|
27119
27480
|
decisionBaseUrl = await savedGatewayBaseUrl(paths, credentials, forgeBaseUrl) ?? decisionBaseUrl;
|
|
27120
27481
|
}
|
|
27121
27482
|
const after = await managedProjectionNames(paths).catch(() => before);
|
|
27122
|
-
return { paths, before, after, forgeConfigVerified, decisionBaseUrl };
|
|
27483
|
+
return { paths, before, after, forgeConfigVerified, decisionBaseUrl, ...appliedLocalSync };
|
|
27123
27484
|
}
|
|
27124
27485
|
}
|
|
27125
27486
|
async function savedGatewayBaseUrl(paths, credentials, forgeBaseUrl) {
|
|
27126
27487
|
try {
|
|
27127
|
-
const config2 =
|
|
27128
|
-
const options =
|
|
27488
|
+
const config2 = objectRecord2(parseJsonc(await readFile13(paths.opencodeConfigPath, "utf8")));
|
|
27489
|
+
const options = objectRecord2(objectRecord2(objectRecord2(config2.provider).forge).options);
|
|
27129
27490
|
if (options.apiKey !== credentials.forgeApiKey || typeof options.baseURL !== "string" || !options.baseURL.endsWith("/v1")) return void 0;
|
|
27130
27491
|
const origin = options.baseURL.slice(0, -"/v1".length);
|
|
27131
27492
|
return origin === forgeBaseUrl ? origin : resolveDecisionBaseUrl(origin, forgeBaseUrl);
|
|
@@ -27149,7 +27510,7 @@ function resolveStartupPaths() {
|
|
|
27149
27510
|
return resolvePaths(void 0, void 0, env);
|
|
27150
27511
|
}
|
|
27151
27512
|
async function readForgeCredentials(paths, forgeBaseUrl) {
|
|
27152
|
-
const raw = await
|
|
27513
|
+
const raw = await readFile13(paths.opencodeAuthPath, "utf8").catch((error45) => {
|
|
27153
27514
|
if (error45.code === "ENOENT") return void 0;
|
|
27154
27515
|
throw error45;
|
|
27155
27516
|
});
|
|
@@ -27189,67 +27550,13 @@ function parseForgeBaseUrl(options) {
|
|
|
27189
27550
|
}
|
|
27190
27551
|
return url2.origin;
|
|
27191
27552
|
}
|
|
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) {
|
|
27553
|
+
function objectRecord2(value) {
|
|
27244
27554
|
return value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
|
|
27245
27555
|
}
|
|
27246
|
-
function stripMarkdownExtension(filename) {
|
|
27247
|
-
return filename.slice(0, -3);
|
|
27248
|
-
}
|
|
27249
27556
|
async function writeStatus(paths, value) {
|
|
27250
27557
|
await mkdir7(paths.forgeDir, { recursive: true });
|
|
27251
|
-
const target =
|
|
27252
|
-
const temporary =
|
|
27558
|
+
const target = path14.join(paths.forgeDir, STATUS_FILENAME);
|
|
27559
|
+
const temporary = path14.join(paths.forgeDir, `.${STATUS_FILENAME}.${process.pid}.tmp`);
|
|
27253
27560
|
await writeFile8(temporary, `${JSON.stringify(value, null, 2)}
|
|
27254
27561
|
`, { mode: 384 });
|
|
27255
27562
|
await rename8(temporary, target);
|
|
@@ -27260,7 +27567,8 @@ function safeErrorMessage(error45) {
|
|
|
27260
27567
|
}
|
|
27261
27568
|
var ForgeWorkPackSyncPlugin = {
|
|
27262
27569
|
id: "minimal-forge.work-pack-sync",
|
|
27263
|
-
server: ForgeWorkPackSyncServer
|
|
27570
|
+
server: ForgeWorkPackSyncServer,
|
|
27571
|
+
setup: ForgeWorkPackSyncSetup
|
|
27264
27572
|
};
|
|
27265
27573
|
var workPackSyncPlugin_default = ForgeWorkPackSyncPlugin;
|
|
27266
27574
|
export {
|