minimal-forge-work-pack-sync 0.1.15 → 0.1.17
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 +1041 -591
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -117,17 +117,17 @@ var require_visit = __commonJS({
|
|
|
117
117
|
visit.BREAK = BREAK;
|
|
118
118
|
visit.SKIP = SKIP;
|
|
119
119
|
visit.REMOVE = REMOVE;
|
|
120
|
-
function visit_(key, node, visitor,
|
|
121
|
-
const ctrl = callVisitor(key, node, visitor,
|
|
120
|
+
function visit_(key, node, visitor, path7) {
|
|
121
|
+
const ctrl = callVisitor(key, node, visitor, path7);
|
|
122
122
|
if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
|
|
123
|
-
replaceNode(key,
|
|
124
|
-
return visit_(key, ctrl, visitor,
|
|
123
|
+
replaceNode(key, path7, ctrl);
|
|
124
|
+
return visit_(key, ctrl, visitor, path7);
|
|
125
125
|
}
|
|
126
126
|
if (typeof ctrl !== "symbol") {
|
|
127
127
|
if (identity.isCollection(node)) {
|
|
128
|
-
|
|
128
|
+
path7 = Object.freeze(path7.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, path7);
|
|
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
|
+
path7 = Object.freeze(path7.concat(node));
|
|
142
|
+
const ck = visit_("key", node.key, visitor, path7);
|
|
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, path7);
|
|
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, path7) {
|
|
169
|
+
const ctrl = await callVisitor(key, node, visitor, path7);
|
|
170
170
|
if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
|
|
171
|
-
replaceNode(key,
|
|
172
|
-
return visitAsync_(key, ctrl, visitor,
|
|
171
|
+
replaceNode(key, path7, ctrl);
|
|
172
|
+
return visitAsync_(key, ctrl, visitor, path7);
|
|
173
173
|
}
|
|
174
174
|
if (typeof ctrl !== "symbol") {
|
|
175
175
|
if (identity.isCollection(node)) {
|
|
176
|
-
|
|
176
|
+
path7 = Object.freeze(path7.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, path7);
|
|
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
|
+
path7 = Object.freeze(path7.concat(node));
|
|
190
|
+
const ck = await visitAsync_("key", node.key, visitor, path7);
|
|
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, path7);
|
|
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, path7) {
|
|
223
223
|
if (typeof visitor === "function")
|
|
224
|
-
return visitor(key, node,
|
|
224
|
+
return visitor(key, node, path7);
|
|
225
225
|
if (identity.isMap(node))
|
|
226
|
-
return visitor.Map?.(key, node,
|
|
226
|
+
return visitor.Map?.(key, node, path7);
|
|
227
227
|
if (identity.isSeq(node))
|
|
228
|
-
return visitor.Seq?.(key, node,
|
|
228
|
+
return visitor.Seq?.(key, node, path7);
|
|
229
229
|
if (identity.isPair(node))
|
|
230
|
-
return visitor.Pair?.(key, node,
|
|
230
|
+
return visitor.Pair?.(key, node, path7);
|
|
231
231
|
if (identity.isScalar(node))
|
|
232
|
-
return visitor.Scalar?.(key, node,
|
|
232
|
+
return visitor.Scalar?.(key, node, path7);
|
|
233
233
|
if (identity.isAlias(node))
|
|
234
|
-
return visitor.Alias?.(key, node,
|
|
234
|
+
return visitor.Alias?.(key, node, path7);
|
|
235
235
|
return void 0;
|
|
236
236
|
}
|
|
237
|
-
function replaceNode(key,
|
|
238
|
-
const parent =
|
|
237
|
+
function replaceNode(key, path7, node) {
|
|
238
|
+
const parent = path7[path7.length - 1];
|
|
239
239
|
if (identity.isCollection(parent)) {
|
|
240
240
|
parent.items[key] = node;
|
|
241
241
|
} else if (identity.isPair(parent)) {
|
|
@@ -845,10 +845,10 @@ var require_Collection = __commonJS({
|
|
|
845
845
|
var createNode = require_createNode();
|
|
846
846
|
var identity = require_identity();
|
|
847
847
|
var Node = require_Node();
|
|
848
|
-
function collectionFromPath(schema,
|
|
848
|
+
function collectionFromPath(schema, path7, value) {
|
|
849
849
|
let v2 = value;
|
|
850
|
-
for (let i =
|
|
851
|
-
const k2 =
|
|
850
|
+
for (let i = path7.length - 1; i >= 0; --i) {
|
|
851
|
+
const k2 = path7[i];
|
|
852
852
|
if (typeof k2 === "number" && Number.isInteger(k2) && k2 >= 0) {
|
|
853
853
|
const a = [];
|
|
854
854
|
a[k2] = v2;
|
|
@@ -867,7 +867,7 @@ var require_Collection = __commonJS({
|
|
|
867
867
|
sourceObjects: /* @__PURE__ */ new Map()
|
|
868
868
|
});
|
|
869
869
|
}
|
|
870
|
-
var isEmptyPath = (
|
|
870
|
+
var isEmptyPath = (path7) => path7 == null || typeof path7 === "object" && !!path7[Symbol.iterator]().next().done;
|
|
871
871
|
var Collection = class extends Node.NodeBase {
|
|
872
872
|
constructor(type, schema) {
|
|
873
873
|
super(type);
|
|
@@ -897,11 +897,11 @@ var require_Collection = __commonJS({
|
|
|
897
897
|
* be a Pair instance or a `{ key, value }` object, which may not have a key
|
|
898
898
|
* that already exists in the map.
|
|
899
899
|
*/
|
|
900
|
-
addIn(
|
|
901
|
-
if (isEmptyPath(
|
|
900
|
+
addIn(path7, value) {
|
|
901
|
+
if (isEmptyPath(path7))
|
|
902
902
|
this.add(value);
|
|
903
903
|
else {
|
|
904
|
-
const [key, ...rest] =
|
|
904
|
+
const [key, ...rest] = path7;
|
|
905
905
|
const node = this.get(key, true);
|
|
906
906
|
if (identity.isCollection(node))
|
|
907
907
|
node.addIn(rest, value);
|
|
@@ -915,8 +915,8 @@ var require_Collection = __commonJS({
|
|
|
915
915
|
* Removes a value from the collection.
|
|
916
916
|
* @returns `true` if the item was found and removed.
|
|
917
917
|
*/
|
|
918
|
-
deleteIn(
|
|
919
|
-
const [key, ...rest] =
|
|
918
|
+
deleteIn(path7) {
|
|
919
|
+
const [key, ...rest] = path7;
|
|
920
920
|
if (rest.length === 0)
|
|
921
921
|
return this.delete(key);
|
|
922
922
|
const node = this.get(key, true);
|
|
@@ -930,8 +930,8 @@ var require_Collection = __commonJS({
|
|
|
930
930
|
* scalar values from their surrounding node; to disable set `keepScalar` to
|
|
931
931
|
* `true` (collections are always returned intact).
|
|
932
932
|
*/
|
|
933
|
-
getIn(
|
|
934
|
-
const [key, ...rest] =
|
|
933
|
+
getIn(path7, keepScalar) {
|
|
934
|
+
const [key, ...rest] = path7;
|
|
935
935
|
const node = this.get(key, true);
|
|
936
936
|
if (rest.length === 0)
|
|
937
937
|
return !keepScalar && identity.isScalar(node) ? node.value : node;
|
|
@@ -949,8 +949,8 @@ var require_Collection = __commonJS({
|
|
|
949
949
|
/**
|
|
950
950
|
* Checks if the collection includes a value with the key `key`.
|
|
951
951
|
*/
|
|
952
|
-
hasIn(
|
|
953
|
-
const [key, ...rest] =
|
|
952
|
+
hasIn(path7) {
|
|
953
|
+
const [key, ...rest] = path7;
|
|
954
954
|
if (rest.length === 0)
|
|
955
955
|
return this.has(key);
|
|
956
956
|
const node = this.get(key, true);
|
|
@@ -960,8 +960,8 @@ var require_Collection = __commonJS({
|
|
|
960
960
|
* Sets a value in this collection. For `!!set`, `value` needs to be a
|
|
961
961
|
* boolean to add/remove the item from the set.
|
|
962
962
|
*/
|
|
963
|
-
setIn(
|
|
964
|
-
const [key, ...rest] =
|
|
963
|
+
setIn(path7, value) {
|
|
964
|
+
const [key, ...rest] = path7;
|
|
965
965
|
if (rest.length === 0) {
|
|
966
966
|
this.set(key, value);
|
|
967
967
|
} else {
|
|
@@ -3476,9 +3476,9 @@ var require_Document = __commonJS({
|
|
|
3476
3476
|
this.contents.add(value);
|
|
3477
3477
|
}
|
|
3478
3478
|
/** Adds a value to the document. */
|
|
3479
|
-
addIn(
|
|
3479
|
+
addIn(path7, value) {
|
|
3480
3480
|
if (assertCollection(this.contents))
|
|
3481
|
-
this.contents.addIn(
|
|
3481
|
+
this.contents.addIn(path7, value);
|
|
3482
3482
|
}
|
|
3483
3483
|
/**
|
|
3484
3484
|
* Create a new `Alias` node, ensuring that the target `node` has the required anchor.
|
|
@@ -3553,14 +3553,14 @@ var require_Document = __commonJS({
|
|
|
3553
3553
|
* Removes a value from the document.
|
|
3554
3554
|
* @returns `true` if the item was found and removed.
|
|
3555
3555
|
*/
|
|
3556
|
-
deleteIn(
|
|
3557
|
-
if (Collection.isEmptyPath(
|
|
3556
|
+
deleteIn(path7) {
|
|
3557
|
+
if (Collection.isEmptyPath(path7)) {
|
|
3558
3558
|
if (this.contents == null)
|
|
3559
3559
|
return false;
|
|
3560
3560
|
this.contents = null;
|
|
3561
3561
|
return true;
|
|
3562
3562
|
}
|
|
3563
|
-
return assertCollection(this.contents) ? this.contents.deleteIn(
|
|
3563
|
+
return assertCollection(this.contents) ? this.contents.deleteIn(path7) : false;
|
|
3564
3564
|
}
|
|
3565
3565
|
/**
|
|
3566
3566
|
* Returns item at `key`, or `undefined` if not found. By default unwraps
|
|
@@ -3575,10 +3575,10 @@ var require_Document = __commonJS({
|
|
|
3575
3575
|
* scalar values from their surrounding node; to disable set `keepScalar` to
|
|
3576
3576
|
* `true` (collections are always returned intact).
|
|
3577
3577
|
*/
|
|
3578
|
-
getIn(
|
|
3579
|
-
if (Collection.isEmptyPath(
|
|
3578
|
+
getIn(path7, keepScalar) {
|
|
3579
|
+
if (Collection.isEmptyPath(path7))
|
|
3580
3580
|
return !keepScalar && identity.isScalar(this.contents) ? this.contents.value : this.contents;
|
|
3581
|
-
return identity.isCollection(this.contents) ? this.contents.getIn(
|
|
3581
|
+
return identity.isCollection(this.contents) ? this.contents.getIn(path7, keepScalar) : void 0;
|
|
3582
3582
|
}
|
|
3583
3583
|
/**
|
|
3584
3584
|
* Checks if the document includes a value with the key `key`.
|
|
@@ -3589,10 +3589,10 @@ var require_Document = __commonJS({
|
|
|
3589
3589
|
/**
|
|
3590
3590
|
* Checks if the document includes a value at `path`.
|
|
3591
3591
|
*/
|
|
3592
|
-
hasIn(
|
|
3593
|
-
if (Collection.isEmptyPath(
|
|
3592
|
+
hasIn(path7) {
|
|
3593
|
+
if (Collection.isEmptyPath(path7))
|
|
3594
3594
|
return this.contents !== void 0;
|
|
3595
|
-
return identity.isCollection(this.contents) ? this.contents.hasIn(
|
|
3595
|
+
return identity.isCollection(this.contents) ? this.contents.hasIn(path7) : false;
|
|
3596
3596
|
}
|
|
3597
3597
|
/**
|
|
3598
3598
|
* Sets a value in this document. For `!!set`, `value` needs to be a
|
|
@@ -3609,13 +3609,13 @@ var require_Document = __commonJS({
|
|
|
3609
3609
|
* Sets a value in this document. For `!!set`, `value` needs to be a
|
|
3610
3610
|
* boolean to add/remove the item from the set.
|
|
3611
3611
|
*/
|
|
3612
|
-
setIn(
|
|
3613
|
-
if (Collection.isEmptyPath(
|
|
3612
|
+
setIn(path7, value) {
|
|
3613
|
+
if (Collection.isEmptyPath(path7)) {
|
|
3614
3614
|
this.contents = value;
|
|
3615
3615
|
} else if (this.contents == null) {
|
|
3616
|
-
this.contents = Collection.collectionFromPath(this.schema, Array.from(
|
|
3616
|
+
this.contents = Collection.collectionFromPath(this.schema, Array.from(path7), value);
|
|
3617
3617
|
} else if (assertCollection(this.contents)) {
|
|
3618
|
-
this.contents.setIn(
|
|
3618
|
+
this.contents.setIn(path7, value);
|
|
3619
3619
|
}
|
|
3620
3620
|
}
|
|
3621
3621
|
/**
|
|
@@ -5575,9 +5575,9 @@ var require_cst_visit = __commonJS({
|
|
|
5575
5575
|
visit.BREAK = BREAK;
|
|
5576
5576
|
visit.SKIP = SKIP;
|
|
5577
5577
|
visit.REMOVE = REMOVE;
|
|
5578
|
-
visit.itemAtPath = (cst,
|
|
5578
|
+
visit.itemAtPath = (cst, path7) => {
|
|
5579
5579
|
let item = cst;
|
|
5580
|
-
for (const [field, index] of
|
|
5580
|
+
for (const [field, index] of path7) {
|
|
5581
5581
|
const tok = item?.[field];
|
|
5582
5582
|
if (tok && "items" in tok) {
|
|
5583
5583
|
item = tok.items[index];
|
|
@@ -5586,23 +5586,23 @@ var require_cst_visit = __commonJS({
|
|
|
5586
5586
|
}
|
|
5587
5587
|
return item;
|
|
5588
5588
|
};
|
|
5589
|
-
visit.parentCollection = (cst,
|
|
5590
|
-
const parent = visit.itemAtPath(cst,
|
|
5591
|
-
const field =
|
|
5589
|
+
visit.parentCollection = (cst, path7) => {
|
|
5590
|
+
const parent = visit.itemAtPath(cst, path7.slice(0, -1));
|
|
5591
|
+
const field = path7[path7.length - 1][0];
|
|
5592
5592
|
const coll = parent?.[field];
|
|
5593
5593
|
if (coll && "items" in coll)
|
|
5594
5594
|
return coll;
|
|
5595
5595
|
throw new Error("Parent collection not found");
|
|
5596
5596
|
};
|
|
5597
|
-
function _visit(
|
|
5598
|
-
let ctrl = visitor(item,
|
|
5597
|
+
function _visit(path7, item, visitor) {
|
|
5598
|
+
let ctrl = visitor(item, path7);
|
|
5599
5599
|
if (typeof ctrl === "symbol")
|
|
5600
5600
|
return ctrl;
|
|
5601
5601
|
for (const field of ["key", "value"]) {
|
|
5602
5602
|
const token = item[field];
|
|
5603
5603
|
if (token && "items" in token) {
|
|
5604
5604
|
for (let i = 0; i < token.items.length; ++i) {
|
|
5605
|
-
const ci2 = _visit(Object.freeze(
|
|
5605
|
+
const ci2 = _visit(Object.freeze(path7.concat([[field, i]])), token.items[i], visitor);
|
|
5606
5606
|
if (typeof ci2 === "number")
|
|
5607
5607
|
i = ci2 - 1;
|
|
5608
5608
|
else if (ci2 === BREAK)
|
|
@@ -5613,10 +5613,10 @@ var require_cst_visit = __commonJS({
|
|
|
5613
5613
|
}
|
|
5614
5614
|
}
|
|
5615
5615
|
if (typeof ctrl === "function" && field === "key")
|
|
5616
|
-
ctrl = ctrl(item,
|
|
5616
|
+
ctrl = ctrl(item, path7);
|
|
5617
5617
|
}
|
|
5618
5618
|
}
|
|
5619
|
-
return typeof ctrl === "function" ? ctrl(item,
|
|
5619
|
+
return typeof ctrl === "function" ? ctrl(item, path7) : ctrl;
|
|
5620
5620
|
}
|
|
5621
5621
|
exports.visit = visit;
|
|
5622
5622
|
}
|
|
@@ -7367,6 +7367,450 @@ var require_dist = __commonJS({
|
|
|
7367
7367
|
}
|
|
7368
7368
|
});
|
|
7369
7369
|
|
|
7370
|
+
// packages/cli/src/workPackSyncPlugin.ts
|
|
7371
|
+
import { createHash as createHash5 } from "node:crypto";
|
|
7372
|
+
import { pathToFileURL } from "node:url";
|
|
7373
|
+
|
|
7374
|
+
// packages/cli/src/skillUsageReporter.ts
|
|
7375
|
+
function skillUsageReporter(origin, credentialId, send) {
|
|
7376
|
+
const symbol2 = /* @__PURE__ */ Symbol.for("minimal-forge.skill-usage.v1");
|
|
7377
|
+
const shared = globalThis;
|
|
7378
|
+
const origins = shared[symbol2] ??= /* @__PURE__ */ new Map();
|
|
7379
|
+
let owner = origins.get(origin);
|
|
7380
|
+
if (!owner) {
|
|
7381
|
+
owner = { seen: /* @__PURE__ */ new Map(), reporters: /* @__PURE__ */ new Map() };
|
|
7382
|
+
origins.set(origin, owner);
|
|
7383
|
+
}
|
|
7384
|
+
const seen = owner.seen;
|
|
7385
|
+
let state = owner.reporters.get(credentialId);
|
|
7386
|
+
if (!state) {
|
|
7387
|
+
state = { pending: [], sending: false, nextSend: 0 };
|
|
7388
|
+
owner.reporters.set(credentialId, state);
|
|
7389
|
+
}
|
|
7390
|
+
const reporter = state;
|
|
7391
|
+
function schedule() {
|
|
7392
|
+
if (reporter.timer || reporter.sending || !reporter.pending.length) return;
|
|
7393
|
+
reporter.timer = setTimeout(() => {
|
|
7394
|
+
reporter.timer = void 0;
|
|
7395
|
+
void flush();
|
|
7396
|
+
}, Math.max(1e3, reporter.nextSend - Date.now()));
|
|
7397
|
+
reporter.timer.unref?.();
|
|
7398
|
+
}
|
|
7399
|
+
async function flush() {
|
|
7400
|
+
if (reporter.sending || !reporter.pending.length) return;
|
|
7401
|
+
reporter.sending = true;
|
|
7402
|
+
reporter.nextSend = Date.now() + 12e4;
|
|
7403
|
+
const batch = reporter.pending.splice(0, 100);
|
|
7404
|
+
try {
|
|
7405
|
+
const response = await send(batch);
|
|
7406
|
+
if (response.status === 429) {
|
|
7407
|
+
reporter.pending.unshift(...batch);
|
|
7408
|
+
if (reporter.pending.length > 1e3) {
|
|
7409
|
+
reporter.pending.length = 1e3;
|
|
7410
|
+
console.error("[Forge evidence] Local usage buffer full after rate rejection");
|
|
7411
|
+
}
|
|
7412
|
+
const retry = Number(response.headers.get("retry-after"));
|
|
7413
|
+
reporter.nextSend = Date.now() + Math.max(12e4, Number.isFinite(retry) ? retry * 1e3 : 0);
|
|
7414
|
+
} else if (!response.ok) console.error(`[Forge evidence] Upload rejected (HTTP ${response.status})`);
|
|
7415
|
+
} catch {
|
|
7416
|
+
console.error("[Forge evidence] Upload unconfirmed; batch not retried");
|
|
7417
|
+
} finally {
|
|
7418
|
+
reporter.sending = false;
|
|
7419
|
+
schedule();
|
|
7420
|
+
}
|
|
7421
|
+
}
|
|
7422
|
+
return (sessionID, callID, slug) => {
|
|
7423
|
+
if (!sessionID || !callID) return;
|
|
7424
|
+
const now = Date.now();
|
|
7425
|
+
for (const [key2, at2] of seen) if (now - at2 > 24 * 60 * 6e4) seen.delete(key2);
|
|
7426
|
+
const key = JSON.stringify([sessionID, callID]);
|
|
7427
|
+
if (seen.has(key)) return;
|
|
7428
|
+
if (seen.size >= 2e4 || reporter.pending.length >= 1e3) {
|
|
7429
|
+
console.error("[Forge evidence] Local usage buffer full");
|
|
7430
|
+
return;
|
|
7431
|
+
}
|
|
7432
|
+
seen.set(key, now);
|
|
7433
|
+
const day = new Date(now).toISOString().slice(0, 10);
|
|
7434
|
+
const existing = reporter.pending.find((event) => event.slug === slug && event.day === day && event.count < 100);
|
|
7435
|
+
if (existing) existing.count++;
|
|
7436
|
+
else reporter.pending.push({ kind: "work_pack_invocation", slug, day, count: 1 });
|
|
7437
|
+
schedule();
|
|
7438
|
+
};
|
|
7439
|
+
}
|
|
7440
|
+
|
|
7441
|
+
// packages/shared/src/contracts/models.ts
|
|
7442
|
+
var BUILT_IN_OPENROUTER_MODELS = [
|
|
7443
|
+
{
|
|
7444
|
+
id: "anthropic/claude-sonnet-4-6",
|
|
7445
|
+
name: "Assistente de trabalho profundo",
|
|
7446
|
+
approvedByDefault: true,
|
|
7447
|
+
requiredInConfig: false,
|
|
7448
|
+
upstreamModel: "anthropic/claude-sonnet-4.6",
|
|
7449
|
+
metadata: {
|
|
7450
|
+
family: "anthropic",
|
|
7451
|
+
release_date: "2026-02-17",
|
|
7452
|
+
attachment: true,
|
|
7453
|
+
reasoning: true,
|
|
7454
|
+
temperature: true,
|
|
7455
|
+
tool_call: true,
|
|
7456
|
+
limit: { context: 1e6, output: 128e3 },
|
|
7457
|
+
modalities: { input: ["text", "image", "pdf"], output: ["text"] }
|
|
7458
|
+
}
|
|
7459
|
+
},
|
|
7460
|
+
{
|
|
7461
|
+
id: "anthropic/claude-haiku-4-5",
|
|
7462
|
+
name: "Assistente r\xE1pido",
|
|
7463
|
+
approvedByDefault: true,
|
|
7464
|
+
requiredInConfig: false,
|
|
7465
|
+
upstreamModel: "anthropic/claude-haiku-4.5",
|
|
7466
|
+
metadata: {
|
|
7467
|
+
family: "anthropic",
|
|
7468
|
+
release_date: "2025-10-15",
|
|
7469
|
+
attachment: true,
|
|
7470
|
+
reasoning: true,
|
|
7471
|
+
temperature: true,
|
|
7472
|
+
tool_call: true,
|
|
7473
|
+
limit: { context: 2e5, output: 64e3 },
|
|
7474
|
+
modalities: { input: ["text", "image", "pdf"], output: ["text"] }
|
|
7475
|
+
}
|
|
7476
|
+
},
|
|
7477
|
+
{
|
|
7478
|
+
id: "openai/gpt-5.4-mini",
|
|
7479
|
+
name: "Assistente de ficheiros e ecr\xE3",
|
|
7480
|
+
approvedByDefault: true,
|
|
7481
|
+
requiredInConfig: false,
|
|
7482
|
+
metadata: {
|
|
7483
|
+
family: "gpt-mini",
|
|
7484
|
+
release_date: "2026-03-17",
|
|
7485
|
+
attachment: true,
|
|
7486
|
+
reasoning: true,
|
|
7487
|
+
temperature: false,
|
|
7488
|
+
tool_call: true,
|
|
7489
|
+
limit: { context: 4e5, input: 272e3, output: 128e3 },
|
|
7490
|
+
modalities: { input: ["text", "image", "pdf"], output: ["text"] },
|
|
7491
|
+
variants: openRouterReasoningVariants(["none", "xhigh"])
|
|
7492
|
+
}
|
|
7493
|
+
},
|
|
7494
|
+
{
|
|
7495
|
+
id: "minimax/minimax-m3",
|
|
7496
|
+
name: "Assistente de pesquisa",
|
|
7497
|
+
approvedByDefault: true,
|
|
7498
|
+
requiredInConfig: false,
|
|
7499
|
+
metadata: {
|
|
7500
|
+
family: "minimax",
|
|
7501
|
+
release_date: "2026-04-07",
|
|
7502
|
+
attachment: true,
|
|
7503
|
+
reasoning: true,
|
|
7504
|
+
temperature: true,
|
|
7505
|
+
tool_call: true,
|
|
7506
|
+
limit: { context: 524288, output: 512e3 },
|
|
7507
|
+
modalities: { input: ["text", "image", "video"], output: ["text"] }
|
|
7508
|
+
}
|
|
7509
|
+
},
|
|
7510
|
+
{
|
|
7511
|
+
id: "minimax/minimax-m2.7",
|
|
7512
|
+
name: "Assistente de reda\xE7\xE3o",
|
|
7513
|
+
approvedByDefault: true,
|
|
7514
|
+
requiredInConfig: false,
|
|
7515
|
+
metadata: {
|
|
7516
|
+
family: "minimax",
|
|
7517
|
+
release_date: "2026-03-18",
|
|
7518
|
+
attachment: false,
|
|
7519
|
+
reasoning: true,
|
|
7520
|
+
temperature: true,
|
|
7521
|
+
tool_call: true,
|
|
7522
|
+
limit: { context: 196608, output: 196608 },
|
|
7523
|
+
modalities: { input: ["text"], output: ["text"] }
|
|
7524
|
+
}
|
|
7525
|
+
},
|
|
7526
|
+
{
|
|
7527
|
+
id: "xiaomi/mimo-v2.5",
|
|
7528
|
+
name: "Assistente de revis\xE3o multim\xE9dia",
|
|
7529
|
+
approvedByDefault: true,
|
|
7530
|
+
requiredInConfig: false,
|
|
7531
|
+
metadata: {
|
|
7532
|
+
family: "mimo",
|
|
7533
|
+
release_date: "2026-04-22",
|
|
7534
|
+
attachment: true,
|
|
7535
|
+
reasoning: true,
|
|
7536
|
+
temperature: true,
|
|
7537
|
+
tool_call: true,
|
|
7538
|
+
interleaved: { field: "reasoning_details" },
|
|
7539
|
+
limit: { context: 32e3, output: 131072 },
|
|
7540
|
+
modalities: { input: ["text", "audio", "image", "video"], output: ["text"] }
|
|
7541
|
+
}
|
|
7542
|
+
},
|
|
7543
|
+
{
|
|
7544
|
+
id: "xiaomi/mimo-v2.5-pro",
|
|
7545
|
+
name: "Assistente de contexto longo",
|
|
7546
|
+
approvedByDefault: true,
|
|
7547
|
+
requiredInConfig: false,
|
|
7548
|
+
metadata: {
|
|
7549
|
+
family: "mimo",
|
|
7550
|
+
release_date: "2026-04-22",
|
|
7551
|
+
attachment: false,
|
|
7552
|
+
reasoning: true,
|
|
7553
|
+
temperature: true,
|
|
7554
|
+
tool_call: true,
|
|
7555
|
+
interleaved: { field: "reasoning_content" },
|
|
7556
|
+
limit: { context: 1048576, output: 131072 },
|
|
7557
|
+
modalities: { input: ["text"], output: ["text"] }
|
|
7558
|
+
}
|
|
7559
|
+
},
|
|
7560
|
+
{
|
|
7561
|
+
id: "z-ai/glm-5.2",
|
|
7562
|
+
name: "Assistente de an\xE1lise",
|
|
7563
|
+
approvedByDefault: false,
|
|
7564
|
+
requiredInConfig: false,
|
|
7565
|
+
metadata: {
|
|
7566
|
+
family: "glm",
|
|
7567
|
+
release_date: "2026-02-12",
|
|
7568
|
+
attachment: false,
|
|
7569
|
+
reasoning: true,
|
|
7570
|
+
temperature: true,
|
|
7571
|
+
tool_call: true,
|
|
7572
|
+
interleaved: { field: "reasoning_content" },
|
|
7573
|
+
limit: { context: 1048576, output: 32768 },
|
|
7574
|
+
modalities: { input: ["text"], output: ["text"] }
|
|
7575
|
+
}
|
|
7576
|
+
}
|
|
7577
|
+
];
|
|
7578
|
+
var APPROVED_MODELS = BUILT_IN_OPENROUTER_MODELS.filter((model) => model.approvedByDefault).map(stripCatalogFlags);
|
|
7579
|
+
function cloneModel(model) {
|
|
7580
|
+
return {
|
|
7581
|
+
id: model.id,
|
|
7582
|
+
name: model.name,
|
|
7583
|
+
...model.provider ? { provider: model.provider } : {},
|
|
7584
|
+
...model.upstreamModel ? { upstreamModel: model.upstreamModel } : {},
|
|
7585
|
+
...model.billingMode ? { billingMode: model.billingMode } : {},
|
|
7586
|
+
...model.metadata ? { metadata: structuredClone(model.metadata) } : {}
|
|
7587
|
+
};
|
|
7588
|
+
}
|
|
7589
|
+
function stripCatalogFlags(model) {
|
|
7590
|
+
const { approvedByDefault: _approvedByDefault, requiredInConfig: _requiredInConfig, ...approved } = model;
|
|
7591
|
+
return cloneModel(approved);
|
|
7592
|
+
}
|
|
7593
|
+
function openRouterReasoningVariants(efforts) {
|
|
7594
|
+
return Object.fromEntries(efforts.map((effort) => [effort, { reasoning: { effort } }]));
|
|
7595
|
+
}
|
|
7596
|
+
|
|
7597
|
+
// packages/shared/src/contracts/debugTrace.ts
|
|
7598
|
+
var DEFAULT_DEBUG_TRACE_LIMITS = {
|
|
7599
|
+
eventEnvelopeBytes: 256 * 1024,
|
|
7600
|
+
artifactChunkBytes: 2 * 1024 * 1024,
|
|
7601
|
+
// Serialized request bodies must remain comfortably below Vercel's 4.5 MB
|
|
7602
|
+
// function request limit after JSON and base64 overhead.
|
|
7603
|
+
uploadBatchBytes: 3 * 1024 * 1024,
|
|
7604
|
+
uploadBatchRecords: 100,
|
|
7605
|
+
fileSnapshotBytes: 1024 * 1024,
|
|
7606
|
+
serverTraceBudgetBytes: 250 * 1024 * 1024,
|
|
7607
|
+
workerTraceQuotaPer24h: 100,
|
|
7608
|
+
workerBytesQuotaPer24h: 1024 * 1024 * 1024,
|
|
7609
|
+
localQueueBytes: 1024 * 1024 * 1024,
|
|
7610
|
+
retryBackoffMinMs: 5e3,
|
|
7611
|
+
retryBackoffMaxMs: 5 * 60 * 1e3,
|
|
7612
|
+
queueMaxAgeDays: 7,
|
|
7613
|
+
rawTempExposureSeconds: 15 * 60
|
|
7614
|
+
};
|
|
7615
|
+
|
|
7616
|
+
// packages/shared/src/contracts/settings.ts
|
|
7617
|
+
var WORK_PACK_SYNC_PLUGIN_VERSION = "0.1.17";
|
|
7618
|
+
var WORK_PACK_SYNC_PLUGIN_PACKAGE = `minimal-forge-work-pack-sync@${WORK_PACK_SYNC_PLUGIN_VERSION}`;
|
|
7619
|
+
var WORK_PACK_SYNC_PLUGIN_FILENAME = `minimal-forge-work-pack-sync-${WORK_PACK_SYNC_PLUGIN_VERSION}.tgz`;
|
|
7620
|
+
var FIRECRAWL_KEYLESS_MCP_NAME = "firecrawl";
|
|
7621
|
+
var FIRECRAWL_KEYLESS_PERMISSION = `${FIRECRAWL_KEYLESS_MCP_NAME}_*`;
|
|
7622
|
+
|
|
7623
|
+
// packages/shared/src/workPackBaseline.ts
|
|
7624
|
+
function normalizePackExtensionModel(pathLabel, content, approvedModelIds, slug) {
|
|
7625
|
+
const match = /^---\n([\s\S]+?)\n---/.exec(content);
|
|
7626
|
+
const frontmatter = match?.[1];
|
|
7627
|
+
if (!match || frontmatter === void 0) return content;
|
|
7628
|
+
const modelLines = [...frontmatter.matchAll(/^model:\s*(.*?)\s*$/gm)];
|
|
7629
|
+
if (modelLines.length === 0) return content;
|
|
7630
|
+
if (modelLines.length > 1) {
|
|
7631
|
+
throw new Error(`A extens\xE3o ${pathLabel} do pacote de trabalho ${slug} define model mais do que uma vez`);
|
|
7632
|
+
}
|
|
7633
|
+
const rawModel = modelLines[0][1].replace(/^(['"])(.*)\1$/, "$2");
|
|
7634
|
+
const separator = rawModel.indexOf("/");
|
|
7635
|
+
const provider = separator > 0 ? rawModel.slice(0, separator) : "";
|
|
7636
|
+
const modelId = separator > 0 ? rawModel.slice(separator + 1) : "";
|
|
7637
|
+
if (provider !== "forge" && provider !== "openrouter" || !approvedModelIds.has(modelId)) {
|
|
7638
|
+
throw new Error(
|
|
7639
|
+
`A extens\xE3o ${pathLabel} do pacote de trabalho ${slug} usa um modelo que n\xE3o est\xE1 aprovado no Forge`
|
|
7640
|
+
);
|
|
7641
|
+
}
|
|
7642
|
+
if (provider === "forge") return content;
|
|
7643
|
+
const normalizedFrontmatter = frontmatter.replace(/^model:\s*.*?$/m, `model: forge/${modelId}`);
|
|
7644
|
+
return `${content.slice(0, match.index)}---
|
|
7645
|
+
${normalizedFrontmatter}
|
|
7646
|
+
---${content.slice(match.index + match[0].length)}`;
|
|
7647
|
+
}
|
|
7648
|
+
function canonicalWorkPackState(state) {
|
|
7649
|
+
const compare = (left, right) => left < right ? -1 : left > right ? 1 : 0;
|
|
7650
|
+
return JSON.stringify({
|
|
7651
|
+
schemaVersion: 1,
|
|
7652
|
+
version: state.version,
|
|
7653
|
+
files: [...state.files].sort((a, b2) => compare(a.path, b2.path)),
|
|
7654
|
+
directories: [...state.directories].sort(compare),
|
|
7655
|
+
agents: [...state.agents].sort((a, b2) => compare(a.filename, b2.filename)),
|
|
7656
|
+
commands: [...state.commands].sort((a, b2) => compare(a.filename, b2.filename))
|
|
7657
|
+
});
|
|
7658
|
+
}
|
|
7659
|
+
function parseWorkPackFileManifest(value) {
|
|
7660
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
|
|
7661
|
+
const state = value;
|
|
7662
|
+
if (state.schemaVersion !== 1 || typeof state.version !== "string" || !state.version || state.version.length > 14 * 1024) return void 0;
|
|
7663
|
+
const validPath = (name, filenameOnly = false) => typeof name === "string" && name.length > 0 && name.length <= 4096 && !/[\\\\:\u0000-\u001f\u007f]/.test(name) && name.split("/").every((part) => part && part !== "." && part !== "..") && (!filenameOnly || !name.includes("/"));
|
|
7664
|
+
const digests = (entries, key) => {
|
|
7665
|
+
if (!Array.isArray(entries) || entries.length > 5e3) return false;
|
|
7666
|
+
const names = /* @__PURE__ */ new Set();
|
|
7667
|
+
return entries.every((entry) => {
|
|
7668
|
+
if (!entry || typeof entry !== "object" || !validPath(entry[key], key === "filename") || typeof entry.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(entry.sha256) || Object.keys(entry).some((field) => field !== key && field !== "sha256") || names.has(entry[key])) return false;
|
|
7669
|
+
names.add(entry[key]);
|
|
7670
|
+
return true;
|
|
7671
|
+
});
|
|
7672
|
+
};
|
|
7673
|
+
if (Object.keys(state).some((key) => !["schemaVersion", "version", "files", "directories", "agents", "commands"].includes(key)) || !digests(state.files, "path") || !digests(state.agents, "filename") || !digests(state.commands, "filename") || !Array.isArray(state.directories) || state.directories.length > 5e3 || !state.directories.every((name) => validPath(name)) || new Set(state.directories).size !== state.directories.length) return void 0;
|
|
7674
|
+
const manifest = state;
|
|
7675
|
+
const directories = new Set(manifest.directories);
|
|
7676
|
+
if (manifest.files.some((file2) => directories.has(file2.path) || file2.path === ".forge-installed-state.json")) return void 0;
|
|
7677
|
+
for (const name of [...manifest.files.map((file2) => file2.path), ...manifest.directories]) {
|
|
7678
|
+
const parts = name.split("/");
|
|
7679
|
+
for (let i = 1; i < parts.length; i++) if (!directories.has(parts.slice(0, i).join("/"))) return void 0;
|
|
7680
|
+
}
|
|
7681
|
+
return manifest;
|
|
7682
|
+
}
|
|
7683
|
+
|
|
7684
|
+
// packages/shared/src/workPackIntegrity.ts
|
|
7685
|
+
function integrityKind(summary) {
|
|
7686
|
+
if (summary.unsafe || summary.unreadable || summary.truncated) return "unsafe-or-unreadable";
|
|
7687
|
+
if (summary.modified || summary.missing) return "source-changes";
|
|
7688
|
+
if (summary.additional) return "unknown-additions";
|
|
7689
|
+
if (summary.runtimeArtifacts) return "runtime-artifacts";
|
|
7690
|
+
return "match";
|
|
7691
|
+
}
|
|
7692
|
+
|
|
7693
|
+
// packages/cli/src/pluginWriter.ts
|
|
7694
|
+
var FORGE_PLUGIN_HEADER = "// Managed by Forge sync. Do not edit.";
|
|
7695
|
+
var FORGE_EVIDENCE_PLUGIN_FILENAME = "forge-evidence.js";
|
|
7696
|
+
function renderEvidencePlugin() {
|
|
7697
|
+
return `${FORGE_PLUGIN_HEADER}
|
|
7698
|
+
// Conta apenas atividade de sess\xE3o/fluxos de trabalho. N\xE3o envia texto de prompts, nomes de ficheiros nem conte\xFAdo.
|
|
7699
|
+
import { readFile } from "node:fs/promises"
|
|
7700
|
+
import { createHash } from "node:crypto"
|
|
7701
|
+
import os from "node:os"
|
|
7702
|
+
import path from "node:path"
|
|
7703
|
+
|
|
7704
|
+
${skillUsageReporter.toString()}
|
|
7705
|
+
|
|
7706
|
+
const QUEUE = []
|
|
7707
|
+
let FLUSHING = false
|
|
7708
|
+
|
|
7709
|
+
export const ForgeEvidence = async () => ({
|
|
7710
|
+
event: async (input) => {
|
|
7711
|
+
try {
|
|
7712
|
+
const event = input?.event ?? input
|
|
7713
|
+
const kind = evidenceKind(event)
|
|
7714
|
+
if (!kind) return
|
|
7715
|
+
const slug = workPackSlug(event)
|
|
7716
|
+
QUEUE.push({ kind, ...(slug ? { slug } : {}), day: currentUtcDay(), count: 1 })
|
|
7717
|
+
if (QUEUE.length >= 10) await flush()
|
|
7718
|
+
} catch (error) {
|
|
7719
|
+
console.error("[Forge evidence] Telemetry send failed:", error instanceof Error ? error.message : String(error))
|
|
7720
|
+
}
|
|
7721
|
+
},
|
|
7722
|
+
"tool.execute.after": async (input, output) => {
|
|
7723
|
+
try {
|
|
7724
|
+
if (input?.tool !== "skill") return
|
|
7725
|
+
const slug = workPackSlug(input?.args) ?? workPackSlug(output?.metadata) ?? workPackSlug(output)
|
|
7726
|
+
if (!slug) return
|
|
7727
|
+
if (!(await isForgeManagedWorkPack(slug))) return
|
|
7728
|
+
const credentials = await readForgeCredentials()
|
|
7729
|
+
if (!credentials) return
|
|
7730
|
+
const origin = credentials.forgeBaseUrl.replace(/\\/$/, "")
|
|
7731
|
+
const credentialId = createHash("sha256").update(credentials.forgeApiKey).digest("hex")
|
|
7732
|
+
const report = skillUsageReporter(origin, credentialId, (events) => fetch(origin + "/sync/evidence", {
|
|
7733
|
+
method: "POST", redirect: "error",
|
|
7734
|
+
headers: { authorization: "Bearer " + credentials.forgeApiKey, "content-type": "application/json" },
|
|
7735
|
+
body: JSON.stringify({ events }), signal: AbortSignal.timeout(5_000)
|
|
7736
|
+
}))
|
|
7737
|
+
report(input.sessionID, input.callID, slug)
|
|
7738
|
+
} catch (error) {
|
|
7739
|
+
console.error("[Forge evidence] Telemetry send failed:", error instanceof Error ? error.message : String(error))
|
|
7740
|
+
}
|
|
7741
|
+
}
|
|
7742
|
+
})
|
|
7743
|
+
|
|
7744
|
+
function evidenceKind(event) {
|
|
7745
|
+
const type = String(event?.type ?? event?.name ?? "")
|
|
7746
|
+
if (type.includes("session.start") || type.startsWith("session.created")) return "session_start"
|
|
7747
|
+
if (type.includes("session.complete")) return "session_complete"
|
|
7748
|
+
if (type.includes("session.error")) return "session_error"
|
|
7749
|
+
return undefined
|
|
7750
|
+
}
|
|
7751
|
+
|
|
7752
|
+
function currentUtcDay() {
|
|
7753
|
+
return new Date().toISOString().slice(0, 10)
|
|
7754
|
+
}
|
|
7755
|
+
|
|
7756
|
+
function workPackSlug(value) {
|
|
7757
|
+
const raw = value?.slug ?? value?.name ?? value?.skill ?? value?.workPack ?? value?.tool?.slug
|
|
7758
|
+
if (typeof raw !== "string") return undefined
|
|
7759
|
+
const slug = raw.trim().toLowerCase()
|
|
7760
|
+
return /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug) ? slug : undefined
|
|
7761
|
+
}
|
|
7762
|
+
|
|
7763
|
+
async function isForgeManagedWorkPack(slug) {
|
|
7764
|
+
try {
|
|
7765
|
+
await readFile(path.join(openCodeDir(), "skills", slug, ".forge-version"), "utf8")
|
|
7766
|
+
return true
|
|
7767
|
+
} catch {
|
|
7768
|
+
return false
|
|
7769
|
+
}
|
|
7770
|
+
}
|
|
7771
|
+
|
|
7772
|
+
function openCodeDir() {
|
|
7773
|
+
if (process.env.OPENCODE_CONFIG) return path.dirname(process.env.OPENCODE_CONFIG)
|
|
7774
|
+
if (process.env.OPENCODE_CONFIG_DIR) return process.env.OPENCODE_CONFIG_DIR
|
|
7775
|
+
const configRoot = process.env.XDG_CONFIG_HOME ?? path.join(os.homedir(), ".config")
|
|
7776
|
+
return path.join(configRoot, "opencode")
|
|
7777
|
+
}
|
|
7778
|
+
|
|
7779
|
+
async function flush() {
|
|
7780
|
+
if (FLUSHING || QUEUE.length === 0) return
|
|
7781
|
+
FLUSHING = true
|
|
7782
|
+
const batch = QUEUE.splice(0, 100)
|
|
7783
|
+
try {
|
|
7784
|
+
const credentials = await readForgeCredentials()
|
|
7785
|
+
if (!credentials) return
|
|
7786
|
+
await fetch(credentials.forgeBaseUrl.replace(/\\/$/, "") + "/sync/evidence", {
|
|
7787
|
+
method: "POST",
|
|
7788
|
+
headers: {
|
|
7789
|
+
authorization: "Bearer " + credentials.forgeApiKey,
|
|
7790
|
+
"content-type": "application/json"
|
|
7791
|
+
},
|
|
7792
|
+
body: JSON.stringify({ events: batch })
|
|
7793
|
+
})
|
|
7794
|
+
} catch (error) {
|
|
7795
|
+
console.error("[Forge evidence] Flush failed:", error instanceof Error ? error.message : String(error))
|
|
7796
|
+
} finally {
|
|
7797
|
+
FLUSHING = false
|
|
7798
|
+
}
|
|
7799
|
+
}
|
|
7800
|
+
|
|
7801
|
+
async function readForgeCredentials() {
|
|
7802
|
+
const configRoot = process.env.XDG_CONFIG_HOME ?? path.join(os.homedir(), ".config")
|
|
7803
|
+
try {
|
|
7804
|
+
const raw = await readFile(path.join(configRoot, "forge", "credentials.json"), "utf8")
|
|
7805
|
+
const parsed = JSON.parse(raw)
|
|
7806
|
+
if (typeof parsed?.forgeBaseUrl === "string" && typeof parsed?.forgeApiKey === "string") return parsed
|
|
7807
|
+
} catch {
|
|
7808
|
+
return undefined
|
|
7809
|
+
}
|
|
7810
|
+
}
|
|
7811
|
+
`;
|
|
7812
|
+
}
|
|
7813
|
+
|
|
7370
7814
|
// packages/cli/src/retireDebugCapture.ts
|
|
7371
7815
|
import { lstat, readFile, rename, writeFile } from "node:fs/promises";
|
|
7372
7816
|
import { randomUUID } from "node:crypto";
|
|
@@ -7413,8 +7857,8 @@ async function replaceFile(filename, contents) {
|
|
|
7413
7857
|
|
|
7414
7858
|
// packages/cli/src/workPackSyncPlugin.ts
|
|
7415
7859
|
var import_yaml = __toESM(require_dist(), 1);
|
|
7416
|
-
import { mkdir as mkdir3, readdir as
|
|
7417
|
-
import
|
|
7860
|
+
import { mkdir as mkdir3, readdir as readdir4, readFile as readFile4, rename as rename4, writeFile as writeFile4 } from "node:fs/promises";
|
|
7861
|
+
import path6 from "node:path";
|
|
7418
7862
|
|
|
7419
7863
|
// node_modules/@opencode-ai/plugin/node_modules/zod/v4/classic/external.js
|
|
7420
7864
|
var external_exports = {};
|
|
@@ -8147,10 +8591,10 @@ function mergeDefs(...defs) {
|
|
|
8147
8591
|
function cloneDef(schema) {
|
|
8148
8592
|
return mergeDefs(schema._zod.def);
|
|
8149
8593
|
}
|
|
8150
|
-
function getElementAtPath(obj,
|
|
8151
|
-
if (!
|
|
8594
|
+
function getElementAtPath(obj, path7) {
|
|
8595
|
+
if (!path7)
|
|
8152
8596
|
return obj;
|
|
8153
|
-
return
|
|
8597
|
+
return path7.reduce((acc, key) => acc?.[key], obj);
|
|
8154
8598
|
}
|
|
8155
8599
|
function promiseAllObject(promisesObj) {
|
|
8156
8600
|
const keys = Object.keys(promisesObj);
|
|
@@ -8511,11 +8955,11 @@ function aborted(x, startIndex = 0) {
|
|
|
8511
8955
|
}
|
|
8512
8956
|
return false;
|
|
8513
8957
|
}
|
|
8514
|
-
function prefixIssues(
|
|
8958
|
+
function prefixIssues(path7, issues) {
|
|
8515
8959
|
return issues.map((iss) => {
|
|
8516
8960
|
var _a;
|
|
8517
8961
|
(_a = iss).path ?? (_a.path = []);
|
|
8518
|
-
iss.path.unshift(
|
|
8962
|
+
iss.path.unshift(path7);
|
|
8519
8963
|
return iss;
|
|
8520
8964
|
});
|
|
8521
8965
|
}
|
|
@@ -8683,7 +9127,7 @@ function treeifyError(error45, _mapper) {
|
|
|
8683
9127
|
return issue2.message;
|
|
8684
9128
|
};
|
|
8685
9129
|
const result = { errors: [] };
|
|
8686
|
-
const processError = (error46,
|
|
9130
|
+
const processError = (error46, path7 = []) => {
|
|
8687
9131
|
var _a, _b;
|
|
8688
9132
|
for (const issue2 of error46.issues) {
|
|
8689
9133
|
if (issue2.code === "invalid_union" && issue2.errors.length) {
|
|
@@ -8693,7 +9137,7 @@ function treeifyError(error45, _mapper) {
|
|
|
8693
9137
|
} else if (issue2.code === "invalid_element") {
|
|
8694
9138
|
processError({ issues: issue2.issues }, issue2.path);
|
|
8695
9139
|
} else {
|
|
8696
|
-
const fullpath = [...
|
|
9140
|
+
const fullpath = [...path7, ...issue2.path];
|
|
8697
9141
|
if (fullpath.length === 0) {
|
|
8698
9142
|
result.errors.push(mapper(issue2));
|
|
8699
9143
|
continue;
|
|
@@ -8725,8 +9169,8 @@ function treeifyError(error45, _mapper) {
|
|
|
8725
9169
|
}
|
|
8726
9170
|
function toDotPath(_path) {
|
|
8727
9171
|
const segs = [];
|
|
8728
|
-
const
|
|
8729
|
-
for (const seg of
|
|
9172
|
+
const path7 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
|
|
9173
|
+
for (const seg of path7) {
|
|
8730
9174
|
if (typeof seg === "number")
|
|
8731
9175
|
segs.push(`[${seg}]`);
|
|
8732
9176
|
else if (typeof seg === "symbol")
|
|
@@ -19873,283 +20317,380 @@ function resolvePaths(home = os.homedir(), platform = process.platform, env = pr
|
|
|
19873
20317
|
pluginDir: pathApi.join(opencodeDir, "plugins")
|
|
19874
20318
|
};
|
|
19875
20319
|
}
|
|
19876
|
-
function resolveOpenCodeDataDir(userHome, platform, env, pathApi) {
|
|
19877
|
-
if (platform === "win32") return pathApi.join(userHome, ".local", "share", "opencode");
|
|
19878
|
-
return pathApi.join(env.XDG_DATA_HOME ?? pathApi.join(userHome, ".local", "share"), "opencode");
|
|
19879
|
-
}
|
|
19880
|
-
function resolveOpenCodeDir(home, platform, env, exists, pathApi) {
|
|
19881
|
-
if (env.OPENCODE_CONFIG_DIR) return env.OPENCODE_CONFIG_DIR;
|
|
19882
|
-
if (platform !== "win32") return pathApi.join(env.XDG_CONFIG_HOME ?? pathApi.join(home, ".config"), "opencode");
|
|
19883
|
-
return pathApi.join(home, ".config", "opencode");
|
|
19884
|
-
}
|
|
19885
|
-
|
|
19886
|
-
// packages/cli/src/report.ts
|
|
19887
|
-
import os2 from "node:os";
|
|
19888
|
-
var AGENT_VERSION = "0.1.0";
|
|
19889
|
-
async function reportFailure(credentials, kind, error45) {
|
|
19890
|
-
try {
|
|
19891
|
-
const message = error45 instanceof Error ? error45.message : String(error45);
|
|
19892
|
-
await fetch(`${credentials.forgeBaseUrl.replace(/\/$/, "")}/sync/report`, {
|
|
19893
|
-
method: "POST",
|
|
19894
|
-
headers: {
|
|
19895
|
-
authorization: `Bearer ${credentials.forgeApiKey}`,
|
|
19896
|
-
"content-type": "application/json",
|
|
19897
|
-
"x-forge-hostname": os2.hostname(),
|
|
19898
|
-
"x-forge-agent-version": AGENT_VERSION
|
|
19899
|
-
},
|
|
19900
|
-
body: JSON.stringify({
|
|
19901
|
-
kind,
|
|
19902
|
-
ok: false,
|
|
19903
|
-
message
|
|
19904
|
-
}),
|
|
19905
|
-
signal: AbortSignal.timeout(3e3)
|
|
19906
|
-
});
|
|
19907
|
-
} catch (error46) {
|
|
19908
|
-
console.error("[Forge] Failed to report failure to Forge server:", error46 instanceof Error ? error46.message : String(error46));
|
|
19909
|
-
}
|
|
19910
|
-
}
|
|
19911
|
-
async function reportWorkPackObservations(credentials, kind, workPacks) {
|
|
20320
|
+
function resolveOpenCodeDataDir(userHome, platform, env, pathApi) {
|
|
20321
|
+
if (platform === "win32") return pathApi.join(userHome, ".local", "share", "opencode");
|
|
20322
|
+
return pathApi.join(env.XDG_DATA_HOME ?? pathApi.join(userHome, ".local", "share"), "opencode");
|
|
20323
|
+
}
|
|
20324
|
+
function resolveOpenCodeDir(home, platform, env, exists, pathApi) {
|
|
20325
|
+
if (env.OPENCODE_CONFIG_DIR) return env.OPENCODE_CONFIG_DIR;
|
|
20326
|
+
if (platform !== "win32") return pathApi.join(env.XDG_CONFIG_HOME ?? pathApi.join(home, ".config"), "opencode");
|
|
20327
|
+
return pathApi.join(home, ".config", "opencode");
|
|
20328
|
+
}
|
|
20329
|
+
|
|
20330
|
+
// packages/cli/src/report.ts
|
|
20331
|
+
import os2 from "node:os";
|
|
20332
|
+
var AGENT_VERSION = "0.1.0";
|
|
20333
|
+
async function reportFailure(credentials, kind, error45) {
|
|
20334
|
+
try {
|
|
20335
|
+
const message = error45 instanceof Error ? error45.message : String(error45);
|
|
20336
|
+
await fetch(`${credentials.forgeBaseUrl.replace(/\/$/, "")}/sync/report`, {
|
|
20337
|
+
method: "POST",
|
|
20338
|
+
headers: {
|
|
20339
|
+
authorization: `Bearer ${credentials.forgeApiKey}`,
|
|
20340
|
+
"content-type": "application/json",
|
|
20341
|
+
"x-forge-hostname": os2.hostname(),
|
|
20342
|
+
"x-forge-agent-version": AGENT_VERSION
|
|
20343
|
+
},
|
|
20344
|
+
body: JSON.stringify({
|
|
20345
|
+
kind,
|
|
20346
|
+
ok: false,
|
|
20347
|
+
message
|
|
20348
|
+
}),
|
|
20349
|
+
signal: AbortSignal.timeout(3e3)
|
|
20350
|
+
});
|
|
20351
|
+
} catch (error46) {
|
|
20352
|
+
console.error("[Forge] Failed to report failure to Forge server:", error46 instanceof Error ? error46.message : String(error46));
|
|
20353
|
+
}
|
|
20354
|
+
}
|
|
20355
|
+
async function reportWorkPackObservations(credentials, kind, workPacks) {
|
|
20356
|
+
try {
|
|
20357
|
+
await fetch(`${credentials.forgeBaseUrl.replace(/\/$/, "")}/sync/report`, {
|
|
20358
|
+
method: "POST",
|
|
20359
|
+
headers: {
|
|
20360
|
+
authorization: `Bearer ${credentials.forgeApiKey}`,
|
|
20361
|
+
"content-type": "application/json",
|
|
20362
|
+
"x-forge-hostname": os2.hostname(),
|
|
20363
|
+
"x-forge-agent-version": AGENT_VERSION
|
|
20364
|
+
},
|
|
20365
|
+
body: JSON.stringify({ kind, ok: true, workPacks }),
|
|
20366
|
+
signal: AbortSignal.timeout(3e3)
|
|
20367
|
+
});
|
|
20368
|
+
} catch (error45) {
|
|
20369
|
+
console.error("[Forge] Failed to report Work Pack state to Forge server:", error45 instanceof Error ? error45.message : String(error45));
|
|
20370
|
+
}
|
|
20371
|
+
}
|
|
20372
|
+
|
|
20373
|
+
// packages/cli/src/workPackIntegrity.ts
|
|
20374
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
20375
|
+
import { constants } from "node:fs";
|
|
20376
|
+
import { lstat as lstat3, open, readdir as readdir2 } from "node:fs/promises";
|
|
20377
|
+
import path4 from "node:path";
|
|
20378
|
+
|
|
20379
|
+
// packages/cli/src/workPackLocalState.ts
|
|
20380
|
+
import { createHash } from "node:crypto";
|
|
20381
|
+
import { lstat as lstat2, mkdir, readFile as readFile2, readdir, rename as rename2, writeFile as writeFile2 } from "node:fs/promises";
|
|
20382
|
+
import path3 from "node:path";
|
|
20383
|
+
var WORK_PACK_LOCAL_STATE_FILENAME = ".forge-installed-state.json";
|
|
20384
|
+
async function writeWorkPackInstalledState(input) {
|
|
20385
|
+
const tree = await digestPackTree(input.packDir);
|
|
20386
|
+
if (!tree) throw new Error("O pacote de trabalho cont\xE9m uma entrada local n\xE3o regular");
|
|
20387
|
+
const state = {
|
|
20388
|
+
schemaVersion: 1,
|
|
20389
|
+
version: input.version,
|
|
20390
|
+
...tree,
|
|
20391
|
+
agents: digestProjectionContents(input.agents),
|
|
20392
|
+
commands: digestProjectionContents(input.commands)
|
|
20393
|
+
};
|
|
20394
|
+
await writeJsonAtomic(path3.join(input.packDir, WORK_PACK_LOCAL_STATE_FILENAME), state);
|
|
20395
|
+
}
|
|
20396
|
+
async function checkWorkPackInstalledState(input) {
|
|
20397
|
+
const state = await readInstalledState(input.packDir);
|
|
20398
|
+
if (!state) return "missing";
|
|
20399
|
+
return await matchesInstalledState(input, state) ? "match" : "changed";
|
|
20400
|
+
}
|
|
20401
|
+
async function checkWorkPackTreeState(packDir) {
|
|
20402
|
+
const state = await readInstalledState(packDir);
|
|
20403
|
+
if (!state) return "missing";
|
|
20404
|
+
const tree = await digestPackTree(packDir).catch(() => void 0);
|
|
20405
|
+
return tree && sameTree(tree, state) ? "match" : "changed";
|
|
20406
|
+
}
|
|
20407
|
+
async function adoptWorkPackInstalledState(input) {
|
|
20408
|
+
const state = await readInstalledState(input.expectedPackDir);
|
|
20409
|
+
if (!state || !await matchesInstalledState(input, state)) return false;
|
|
20410
|
+
await writeJsonAtomic(path3.join(input.packDir, WORK_PACK_LOCAL_STATE_FILENAME), state);
|
|
20411
|
+
return checkWorkPackInstalledState(input).then((result) => result === "match");
|
|
20412
|
+
}
|
|
20413
|
+
async function adoptVerifiedWorkPackState(input) {
|
|
20414
|
+
const tree = await digestPackTree(input.packDir);
|
|
20415
|
+
if (!tree) return false;
|
|
20416
|
+
const projections = async (kind, directory) => {
|
|
20417
|
+
const prefix = `${kind}/`;
|
|
20418
|
+
const expected = tree.files.filter((file2) => file2.path.startsWith(prefix) && !file2.path.slice(prefix.length).includes("/") && file2.path.endsWith(".md") && !file2.path.slice(prefix.length).startsWith("._"));
|
|
20419
|
+
const result = [];
|
|
20420
|
+
for (const file2 of expected) {
|
|
20421
|
+
const filename = file2.path.slice(prefix.length);
|
|
20422
|
+
const absolute = path3.join(directory, filename);
|
|
20423
|
+
const info = await lstat2(absolute);
|
|
20424
|
+
if (!info.isFile() || info.isSymbolicLink()) throw new Error("Unsafe projection");
|
|
20425
|
+
result.push({ filename, sha256: digest(await readFile2(absolute)) });
|
|
20426
|
+
}
|
|
20427
|
+
return result.sort((a, b2) => a.filename.localeCompare(b2.filename));
|
|
20428
|
+
};
|
|
20429
|
+
const state = {
|
|
20430
|
+
schemaVersion: 1,
|
|
20431
|
+
version: input.version,
|
|
20432
|
+
...tree,
|
|
20433
|
+
agents: await projections("agents", input.agentsDir),
|
|
20434
|
+
commands: await projections("commands", input.commandsDir)
|
|
20435
|
+
};
|
|
20436
|
+
if (digest(Buffer.from(canonicalWorkPackState(state))) !== input.fingerprint) return false;
|
|
20437
|
+
if (!await matchesInstalledState(input, state)) return false;
|
|
20438
|
+
await writeJsonAtomic(path3.join(input.packDir, WORK_PACK_LOCAL_STATE_FILENAME), state);
|
|
20439
|
+
return await checkWorkPackInstalledState(input) === "match";
|
|
20440
|
+
}
|
|
20441
|
+
async function readInstalledState(packDir) {
|
|
20442
|
+
const info = await lstat2(path3.join(packDir, WORK_PACK_LOCAL_STATE_FILENAME)).catch(() => void 0);
|
|
20443
|
+
if (!info?.isFile() || info.isSymbolicLink() || info.size > 1024 * 1024) return void 0;
|
|
20444
|
+
const raw = await readFile2(path3.join(packDir, WORK_PACK_LOCAL_STATE_FILENAME), "utf8").catch(() => void 0);
|
|
20445
|
+
if (!raw) return void 0;
|
|
19912
20446
|
try {
|
|
19913
|
-
|
|
19914
|
-
|
|
19915
|
-
|
|
19916
|
-
authorization: `Bearer ${credentials.forgeApiKey}`,
|
|
19917
|
-
"content-type": "application/json",
|
|
19918
|
-
"x-forge-hostname": os2.hostname(),
|
|
19919
|
-
"x-forge-agent-version": AGENT_VERSION
|
|
19920
|
-
},
|
|
19921
|
-
body: JSON.stringify({ kind, ok: true, workPacks }),
|
|
19922
|
-
signal: AbortSignal.timeout(3e3)
|
|
19923
|
-
});
|
|
19924
|
-
} catch (error45) {
|
|
19925
|
-
console.error("[Forge] Failed to report Work Pack state to Forge server:", error45 instanceof Error ? error45.message : String(error45));
|
|
20447
|
+
return parseWorkPackFileManifest(JSON.parse(raw));
|
|
20448
|
+
} catch {
|
|
20449
|
+
return void 0;
|
|
19926
20450
|
}
|
|
19927
20451
|
}
|
|
19928
|
-
|
|
19929
|
-
|
|
19930
|
-
|
|
19931
|
-
{
|
|
19932
|
-
|
|
19933
|
-
|
|
19934
|
-
|
|
19935
|
-
|
|
19936
|
-
|
|
19937
|
-
|
|
19938
|
-
|
|
19939
|
-
|
|
19940
|
-
|
|
19941
|
-
|
|
19942
|
-
|
|
19943
|
-
|
|
19944
|
-
limit: { context: 1e6, output: 128e3 },
|
|
19945
|
-
modalities: { input: ["text", "image", "pdf"], output: ["text"] }
|
|
19946
|
-
}
|
|
19947
|
-
},
|
|
19948
|
-
{
|
|
19949
|
-
id: "anthropic/claude-haiku-4-5",
|
|
19950
|
-
name: "Assistente r\xE1pido",
|
|
19951
|
-
approvedByDefault: true,
|
|
19952
|
-
requiredInConfig: false,
|
|
19953
|
-
upstreamModel: "anthropic/claude-haiku-4.5",
|
|
19954
|
-
metadata: {
|
|
19955
|
-
family: "anthropic",
|
|
19956
|
-
release_date: "2025-10-15",
|
|
19957
|
-
attachment: true,
|
|
19958
|
-
reasoning: true,
|
|
19959
|
-
temperature: true,
|
|
19960
|
-
tool_call: true,
|
|
19961
|
-
limit: { context: 2e5, output: 64e3 },
|
|
19962
|
-
modalities: { input: ["text", "image", "pdf"], output: ["text"] }
|
|
19963
|
-
}
|
|
19964
|
-
},
|
|
19965
|
-
{
|
|
19966
|
-
id: "openai/gpt-5.4-mini",
|
|
19967
|
-
name: "Assistente de ficheiros e ecr\xE3",
|
|
19968
|
-
approvedByDefault: true,
|
|
19969
|
-
requiredInConfig: false,
|
|
19970
|
-
metadata: {
|
|
19971
|
-
family: "gpt-mini",
|
|
19972
|
-
release_date: "2026-03-17",
|
|
19973
|
-
attachment: true,
|
|
19974
|
-
reasoning: true,
|
|
19975
|
-
temperature: false,
|
|
19976
|
-
tool_call: true,
|
|
19977
|
-
limit: { context: 4e5, input: 272e3, output: 128e3 },
|
|
19978
|
-
modalities: { input: ["text", "image", "pdf"], output: ["text"] },
|
|
19979
|
-
variants: openRouterReasoningVariants(["none", "xhigh"])
|
|
19980
|
-
}
|
|
19981
|
-
},
|
|
19982
|
-
{
|
|
19983
|
-
id: "minimax/minimax-m3",
|
|
19984
|
-
name: "Assistente de pesquisa",
|
|
19985
|
-
approvedByDefault: true,
|
|
19986
|
-
requiredInConfig: false,
|
|
19987
|
-
metadata: {
|
|
19988
|
-
family: "minimax",
|
|
19989
|
-
release_date: "2026-04-07",
|
|
19990
|
-
attachment: true,
|
|
19991
|
-
reasoning: true,
|
|
19992
|
-
temperature: true,
|
|
19993
|
-
tool_call: true,
|
|
19994
|
-
limit: { context: 524288, output: 512e3 },
|
|
19995
|
-
modalities: { input: ["text", "image", "video"], output: ["text"] }
|
|
19996
|
-
}
|
|
19997
|
-
},
|
|
19998
|
-
{
|
|
19999
|
-
id: "minimax/minimax-m2.7",
|
|
20000
|
-
name: "Assistente de reda\xE7\xE3o",
|
|
20001
|
-
approvedByDefault: true,
|
|
20002
|
-
requiredInConfig: false,
|
|
20003
|
-
metadata: {
|
|
20004
|
-
family: "minimax",
|
|
20005
|
-
release_date: "2026-03-18",
|
|
20006
|
-
attachment: false,
|
|
20007
|
-
reasoning: true,
|
|
20008
|
-
temperature: true,
|
|
20009
|
-
tool_call: true,
|
|
20010
|
-
limit: { context: 196608, output: 196608 },
|
|
20011
|
-
modalities: { input: ["text"], output: ["text"] }
|
|
20012
|
-
}
|
|
20013
|
-
},
|
|
20014
|
-
{
|
|
20015
|
-
id: "xiaomi/mimo-v2.5",
|
|
20016
|
-
name: "Assistente de revis\xE3o multim\xE9dia",
|
|
20017
|
-
approvedByDefault: true,
|
|
20018
|
-
requiredInConfig: false,
|
|
20019
|
-
metadata: {
|
|
20020
|
-
family: "mimo",
|
|
20021
|
-
release_date: "2026-04-22",
|
|
20022
|
-
attachment: true,
|
|
20023
|
-
reasoning: true,
|
|
20024
|
-
temperature: true,
|
|
20025
|
-
tool_call: true,
|
|
20026
|
-
interleaved: { field: "reasoning_details" },
|
|
20027
|
-
limit: { context: 32e3, output: 131072 },
|
|
20028
|
-
modalities: { input: ["text", "audio", "image", "video"], output: ["text"] }
|
|
20029
|
-
}
|
|
20030
|
-
},
|
|
20031
|
-
{
|
|
20032
|
-
id: "xiaomi/mimo-v2.5-pro",
|
|
20033
|
-
name: "Assistente de contexto longo",
|
|
20034
|
-
approvedByDefault: true,
|
|
20035
|
-
requiredInConfig: false,
|
|
20036
|
-
metadata: {
|
|
20037
|
-
family: "mimo",
|
|
20038
|
-
release_date: "2026-04-22",
|
|
20039
|
-
attachment: false,
|
|
20040
|
-
reasoning: true,
|
|
20041
|
-
temperature: true,
|
|
20042
|
-
tool_call: true,
|
|
20043
|
-
interleaved: { field: "reasoning_content" },
|
|
20044
|
-
limit: { context: 1048576, output: 131072 },
|
|
20045
|
-
modalities: { input: ["text"], output: ["text"] }
|
|
20046
|
-
}
|
|
20047
|
-
},
|
|
20048
|
-
{
|
|
20049
|
-
id: "z-ai/glm-5.2",
|
|
20050
|
-
name: "Assistente de an\xE1lise",
|
|
20051
|
-
approvedByDefault: false,
|
|
20052
|
-
requiredInConfig: false,
|
|
20053
|
-
metadata: {
|
|
20054
|
-
family: "glm",
|
|
20055
|
-
release_date: "2026-02-12",
|
|
20056
|
-
attachment: false,
|
|
20057
|
-
reasoning: true,
|
|
20058
|
-
temperature: true,
|
|
20059
|
-
tool_call: true,
|
|
20060
|
-
interleaved: { field: "reasoning_content" },
|
|
20061
|
-
limit: { context: 1048576, output: 32768 },
|
|
20062
|
-
modalities: { input: ["text"], output: ["text"] }
|
|
20452
|
+
async function digestPackTree(root) {
|
|
20453
|
+
const files = [];
|
|
20454
|
+
const directories = [];
|
|
20455
|
+
const visit = async (directory, prefix) => {
|
|
20456
|
+
const entries = await readdir(directory, { withFileTypes: true });
|
|
20457
|
+
for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
|
|
20458
|
+
if (!prefix && entry.name === WORK_PACK_LOCAL_STATE_FILENAME) continue;
|
|
20459
|
+
const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
|
|
20460
|
+
const absolute = path3.join(directory, entry.name);
|
|
20461
|
+
if (entry.isDirectory()) {
|
|
20462
|
+
directories.push(relative);
|
|
20463
|
+
if (!await visit(absolute, relative)) return false;
|
|
20464
|
+
continue;
|
|
20465
|
+
}
|
|
20466
|
+
if (!entry.isFile()) return false;
|
|
20467
|
+
files.push({ path: relative, sha256: digest(await readFile2(absolute)) });
|
|
20063
20468
|
}
|
|
20064
|
-
|
|
20065
|
-
];
|
|
20066
|
-
var APPROVED_MODELS = BUILT_IN_OPENROUTER_MODELS.filter((model) => model.approvedByDefault).map(stripCatalogFlags);
|
|
20067
|
-
function cloneModel(model) {
|
|
20068
|
-
return {
|
|
20069
|
-
id: model.id,
|
|
20070
|
-
name: model.name,
|
|
20071
|
-
...model.provider ? { provider: model.provider } : {},
|
|
20072
|
-
...model.upstreamModel ? { upstreamModel: model.upstreamModel } : {},
|
|
20073
|
-
...model.billingMode ? { billingMode: model.billingMode } : {},
|
|
20074
|
-
...model.metadata ? { metadata: structuredClone(model.metadata) } : {}
|
|
20469
|
+
return true;
|
|
20075
20470
|
};
|
|
20471
|
+
return await visit(root, "") ? { files, directories } : void 0;
|
|
20076
20472
|
}
|
|
20077
|
-
function
|
|
20078
|
-
|
|
20079
|
-
return cloneModel(approved);
|
|
20473
|
+
function digestProjectionContents(files) {
|
|
20474
|
+
return files.map((file2) => ({ filename: file2.filename, sha256: digest(Buffer.from(file2.content)) })).sort((left, right) => left.filename.localeCompare(right.filename));
|
|
20080
20475
|
}
|
|
20081
|
-
function
|
|
20082
|
-
|
|
20476
|
+
async function projectionsMatch(directory, expected) {
|
|
20477
|
+
for (const projection of expected) {
|
|
20478
|
+
const absolute = path3.join(directory, projection.filename);
|
|
20479
|
+
const info = await lstat2(absolute).catch(() => void 0);
|
|
20480
|
+
if (!info?.isFile() || info.isSymbolicLink()) return false;
|
|
20481
|
+
const bytes = await readFile2(absolute).catch(() => void 0);
|
|
20482
|
+
if (!bytes || digest(bytes) !== projection.sha256) return false;
|
|
20483
|
+
}
|
|
20484
|
+
return true;
|
|
20485
|
+
}
|
|
20486
|
+
async function matchesInstalledState(input, state) {
|
|
20487
|
+
const tree = await digestPackTree(input.packDir).catch(() => void 0);
|
|
20488
|
+
if (!tree || !sameTree(tree, state)) return false;
|
|
20489
|
+
if (!await projectionsMatch(input.agentsDir, state.agents)) return false;
|
|
20490
|
+
return projectionsMatch(input.commandsDir, state.commands);
|
|
20491
|
+
}
|
|
20492
|
+
function sameTree(left, right) {
|
|
20493
|
+
const directories = new Set(right.directories);
|
|
20494
|
+
return sameDigests(left.files, right.files) && left.directories.length === directories.size && left.directories.every((entry) => directories.has(entry));
|
|
20495
|
+
}
|
|
20496
|
+
function sameDigests(left, right) {
|
|
20497
|
+
const expected = new Map(right.map((entry) => [entry.path, entry.sha256]));
|
|
20498
|
+
return left.length === expected.size && left.every((entry) => entry.sha256 === expected.get(entry.path));
|
|
20499
|
+
}
|
|
20500
|
+
function digest(bytes) {
|
|
20501
|
+
return createHash("sha256").update(bytes).digest("hex");
|
|
20502
|
+
}
|
|
20503
|
+
async function writeJsonAtomic(filePath, value) {
|
|
20504
|
+
await mkdir(path3.dirname(filePath), { recursive: true });
|
|
20505
|
+
const tempPath = path3.join(path3.dirname(filePath), `.${path3.basename(filePath)}.${process.pid}.tmp`);
|
|
20506
|
+
await writeFile2(tempPath, `${JSON.stringify(value, null, 2)}
|
|
20507
|
+
`);
|
|
20508
|
+
await rename2(tempPath, filePath);
|
|
20083
20509
|
}
|
|
20084
20510
|
|
|
20085
|
-
// packages/
|
|
20086
|
-
var
|
|
20087
|
-
|
|
20088
|
-
|
|
20089
|
-
|
|
20090
|
-
|
|
20091
|
-
|
|
20092
|
-
|
|
20093
|
-
|
|
20094
|
-
|
|
20095
|
-
|
|
20096
|
-
|
|
20097
|
-
|
|
20098
|
-
|
|
20099
|
-
|
|
20100
|
-
|
|
20101
|
-
|
|
20102
|
-
|
|
20103
|
-
|
|
20104
|
-
|
|
20105
|
-
|
|
20106
|
-
|
|
20107
|
-
|
|
20108
|
-
|
|
20109
|
-
|
|
20110
|
-
|
|
20111
|
-
|
|
20112
|
-
|
|
20113
|
-
|
|
20114
|
-
|
|
20115
|
-
|
|
20116
|
-
const modelLines = [...frontmatter.matchAll(/^model:\s*(.*?)\s*$/gm)];
|
|
20117
|
-
if (modelLines.length === 0) return content;
|
|
20118
|
-
if (modelLines.length > 1) {
|
|
20119
|
-
throw new Error(`A extens\xE3o ${pathLabel} do pacote de trabalho ${slug} define model mais do que uma vez`);
|
|
20511
|
+
// packages/cli/src/workPackIntegrity.ts
|
|
20512
|
+
var MAX_ENTRIES = 1e4;
|
|
20513
|
+
var MAX_DIFFERENCES = 100;
|
|
20514
|
+
var MAX_FILE_BYTES = 64 * 1024 * 1024;
|
|
20515
|
+
function emptySummary() {
|
|
20516
|
+
return {
|
|
20517
|
+
reference: "unavailable",
|
|
20518
|
+
kind: "baseline-unavailable",
|
|
20519
|
+
modified: 0,
|
|
20520
|
+
missing: 0,
|
|
20521
|
+
additional: 0,
|
|
20522
|
+
runtimeArtifacts: 0,
|
|
20523
|
+
unsafe: 0,
|
|
20524
|
+
unreadable: 0,
|
|
20525
|
+
truncated: false
|
|
20526
|
+
};
|
|
20527
|
+
}
|
|
20528
|
+
async function inspectWorkPackIntegrity(input) {
|
|
20529
|
+
assertSlug(input.slug);
|
|
20530
|
+
const packDir = path4.join(input.paths.skillsDir, input.slug);
|
|
20531
|
+
const result = { slug: input.slug, summary: emptySummary(), differences: [], differencesTruncated: false };
|
|
20532
|
+
const add = (kind, area, name) => {
|
|
20533
|
+
if (result.summary[kind] === MAX_ENTRIES) result.summary.truncated = true;
|
|
20534
|
+
result.summary[kind] = Math.min(MAX_ENTRIES, result.summary[kind] + 1);
|
|
20535
|
+
if (result.differences.length < MAX_DIFFERENCES) result.differences.push({ kind, area, path: name });
|
|
20536
|
+
else result.differencesTruncated = true;
|
|
20537
|
+
};
|
|
20538
|
+
const root = await lstat3(packDir).catch(() => void 0);
|
|
20539
|
+
if (!root?.isDirectory() || root.isSymbolicLink()) {
|
|
20540
|
+
add(root ? "unsafe" : "unreadable", "pack", ".");
|
|
20541
|
+
return result;
|
|
20120
20542
|
}
|
|
20121
|
-
const
|
|
20122
|
-
|
|
20123
|
-
|
|
20124
|
-
|
|
20125
|
-
|
|
20126
|
-
|
|
20127
|
-
|
|
20128
|
-
|
|
20543
|
+
const expected = input.expected ? parseWorkPackFileManifest(input.expected) : await readInstalledState(packDir);
|
|
20544
|
+
if (!expected) return result;
|
|
20545
|
+
result.version = expected.version;
|
|
20546
|
+
result.summary.reference = input.expected ? input.reference ?? "server" : "installation-receipt";
|
|
20547
|
+
const readBudget = { remaining: 128 * 1024 * 1024, exceeded: false };
|
|
20548
|
+
const original = new Map(expected.files.map((file2) => [file2.path, file2.sha256]));
|
|
20549
|
+
const directories = new Set(expected.directories);
|
|
20550
|
+
const seenFiles = /* @__PURE__ */ new Set(), seenDirectories = /* @__PURE__ */ new Set(), unchanged = /* @__PURE__ */ new Set();
|
|
20551
|
+
const extraFiles = [], extraDirectories = [], blocked = [];
|
|
20552
|
+
let entries = 0;
|
|
20553
|
+
const walk = async (directory, prefix) => {
|
|
20554
|
+
if (result.summary.truncated) return;
|
|
20555
|
+
let children;
|
|
20556
|
+
try {
|
|
20557
|
+
children = await readdir2(directory, { withFileTypes: true });
|
|
20558
|
+
} catch {
|
|
20559
|
+
add("unreadable", "pack", prefix || ".");
|
|
20560
|
+
blocked.push(prefix);
|
|
20561
|
+
return;
|
|
20562
|
+
}
|
|
20563
|
+
for (const entry of children.sort((a, b2) => a.name < b2.name ? -1 : a.name > b2.name ? 1 : 0)) {
|
|
20564
|
+
if (++entries > MAX_ENTRIES) {
|
|
20565
|
+
result.summary.truncated = true;
|
|
20566
|
+
return;
|
|
20567
|
+
}
|
|
20568
|
+
const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
|
|
20569
|
+
const absolute = path4.join(directory, entry.name);
|
|
20570
|
+
const info = await lstat3(absolute).catch(() => void 0);
|
|
20571
|
+
if (!info) {
|
|
20572
|
+
add("unreadable", "pack", relative);
|
|
20573
|
+
blocked.push(relative);
|
|
20574
|
+
continue;
|
|
20575
|
+
}
|
|
20576
|
+
if (info.isSymbolicLink() || !info.isDirectory() && !info.isFile() || info.isFile() && info.nlink > 1) {
|
|
20577
|
+
add("unsafe", "pack", relative);
|
|
20578
|
+
blocked.push(relative);
|
|
20579
|
+
continue;
|
|
20580
|
+
}
|
|
20581
|
+
if (!prefix && entry.name === WORK_PACK_LOCAL_STATE_FILENAME) {
|
|
20582
|
+
if (!info.isFile()) add("unsafe", "pack", relative);
|
|
20583
|
+
continue;
|
|
20584
|
+
}
|
|
20585
|
+
if (info.isDirectory()) {
|
|
20586
|
+
seenDirectories.add(relative);
|
|
20587
|
+
if (!directories.has(relative)) extraDirectories.push(relative);
|
|
20588
|
+
if (original.has(relative)) add("unsafe", "pack", relative);
|
|
20589
|
+
if (relative.split("/").length > 64) {
|
|
20590
|
+
add("unsafe", "pack", relative);
|
|
20591
|
+
blocked.push(relative);
|
|
20592
|
+
continue;
|
|
20593
|
+
}
|
|
20594
|
+
await walk(absolute, relative);
|
|
20595
|
+
} else {
|
|
20596
|
+
seenFiles.add(relative);
|
|
20597
|
+
const expectedHash = original.get(relative);
|
|
20598
|
+
if (directories.has(relative)) add("unsafe", "pack", relative);
|
|
20599
|
+
if (expectedHash === void 0) extraFiles.push(relative);
|
|
20600
|
+
else {
|
|
20601
|
+
const digest2 = await regularFileDigest(absolute, readBudget);
|
|
20602
|
+
if (!digest2) add("unreadable", "pack", relative);
|
|
20603
|
+
else if (digest2 !== expectedHash) add("modified", "pack", relative);
|
|
20604
|
+
else unchanged.add(relative);
|
|
20605
|
+
}
|
|
20606
|
+
}
|
|
20607
|
+
}
|
|
20608
|
+
};
|
|
20609
|
+
await walk(packDir, "");
|
|
20610
|
+
const inaccessible = (name) => result.summary.truncated || blocked.some((parent) => !parent || name === parent || name.startsWith(`${parent}/`));
|
|
20611
|
+
for (const name of original.keys()) if (!seenFiles.has(name) && !seenDirectories.has(name) && !inaccessible(name)) add("missing", "pack", name);
|
|
20612
|
+
for (const name of directories) if (!seenDirectories.has(name) && !seenFiles.has(name) && !inaccessible(name)) add("missing", "pack", name);
|
|
20613
|
+
const cacheDirectories = /* @__PURE__ */ new Set();
|
|
20614
|
+
for (const name of extraFiles) {
|
|
20615
|
+
const match = /^(.*\/)?__pycache__\/([^/]+)\.cpython-[0-9]+(?:\.opt-[12])?\.pyc$/.exec(name);
|
|
20616
|
+
const source = match ? `${match[1] ?? ""}${match[2]}.py` : void 0;
|
|
20617
|
+
if (source && unchanged.has(source)) {
|
|
20618
|
+
add("runtimeArtifacts", "pack", name);
|
|
20619
|
+
cacheDirectories.add(path4.posix.dirname(name));
|
|
20620
|
+
} else add("additional", "pack", name);
|
|
20621
|
+
}
|
|
20622
|
+
for (const name of extraDirectories) if (!cacheDirectories.has(name)) add("additional", "pack", name);
|
|
20623
|
+
for (const area of ["agents", "commands"]) {
|
|
20624
|
+
const items = expected[area];
|
|
20625
|
+
if (!items.length) continue;
|
|
20626
|
+
const directory = area === "agents" ? input.paths.agentsDir : input.paths.commandsDir;
|
|
20627
|
+
const directoryInfo = await lstat3(directory).catch(() => void 0);
|
|
20628
|
+
if (directoryInfo && (!directoryInfo.isDirectory() || directoryInfo.isSymbolicLink())) {
|
|
20629
|
+
add("unsafe", area, ".");
|
|
20630
|
+
continue;
|
|
20631
|
+
}
|
|
20632
|
+
for (const item of items) {
|
|
20633
|
+
const absolute = path4.join(directory, item.filename);
|
|
20634
|
+
try {
|
|
20635
|
+
const info = await lstat3(absolute);
|
|
20636
|
+
if (!info.isFile() || info.isSymbolicLink() || info.nlink > 1) add("unsafe", area, item.filename);
|
|
20637
|
+
else {
|
|
20638
|
+
const digest2 = await regularFileDigest(absolute, readBudget);
|
|
20639
|
+
if (!digest2) add("unreadable", area, item.filename);
|
|
20640
|
+
else if (digest2 !== item.sha256) add("modified", area, item.filename);
|
|
20641
|
+
}
|
|
20642
|
+
} catch (error45) {
|
|
20643
|
+
add(error45.code === "ENOENT" ? "missing" : "unreadable", area, item.filename);
|
|
20644
|
+
}
|
|
20645
|
+
}
|
|
20129
20646
|
}
|
|
20130
|
-
|
|
20131
|
-
|
|
20132
|
-
return
|
|
20133
|
-
${normalizedFrontmatter}
|
|
20134
|
-
---${content.slice(match.index + match[0].length)}`;
|
|
20647
|
+
result.summary.truncated ||= readBudget.exceeded;
|
|
20648
|
+
result.summary.kind = integrityKind(result.summary);
|
|
20649
|
+
return result;
|
|
20135
20650
|
}
|
|
20136
|
-
function
|
|
20137
|
-
|
|
20138
|
-
|
|
20139
|
-
|
|
20140
|
-
|
|
20141
|
-
|
|
20142
|
-
|
|
20143
|
-
|
|
20144
|
-
|
|
20145
|
-
|
|
20651
|
+
async function regularFileDigest(filePath, budget) {
|
|
20652
|
+
try {
|
|
20653
|
+
const handle = await open(filePath, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
20654
|
+
try {
|
|
20655
|
+
const before = await handle.stat();
|
|
20656
|
+
if (!before.isFile() || before.nlink > 1 || before.size > MAX_FILE_BYTES) return void 0;
|
|
20657
|
+
if (before.size > budget.remaining) {
|
|
20658
|
+
budget.exceeded = true;
|
|
20659
|
+
return void 0;
|
|
20660
|
+
}
|
|
20661
|
+
const hash2 = createHash2("sha256");
|
|
20662
|
+
const buffer = Buffer.alloc(64 * 1024);
|
|
20663
|
+
let total = 0;
|
|
20664
|
+
while (true) {
|
|
20665
|
+
const { bytesRead } = await handle.read(buffer, 0, buffer.length, null);
|
|
20666
|
+
if (!bytesRead) break;
|
|
20667
|
+
total += bytesRead;
|
|
20668
|
+
budget.remaining -= bytesRead;
|
|
20669
|
+
if (budget.remaining < 0) {
|
|
20670
|
+
budget.exceeded = true;
|
|
20671
|
+
return void 0;
|
|
20672
|
+
}
|
|
20673
|
+
if (total > MAX_FILE_BYTES) return void 0;
|
|
20674
|
+
hash2.update(buffer.subarray(0, bytesRead));
|
|
20675
|
+
}
|
|
20676
|
+
const after = await handle.stat();
|
|
20677
|
+
return before.size === after.size && before.mtimeMs === after.mtimeMs && total === before.size ? hash2.digest("hex") : void 0;
|
|
20678
|
+
} finally {
|
|
20679
|
+
await handle.close();
|
|
20680
|
+
}
|
|
20681
|
+
} catch {
|
|
20682
|
+
return void 0;
|
|
20683
|
+
}
|
|
20684
|
+
}
|
|
20685
|
+
function assertSlug(slug) {
|
|
20686
|
+
if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug) || slug.length > 64) throw new Error("Identificador de skill inv\xE1lido");
|
|
20146
20687
|
}
|
|
20147
20688
|
|
|
20148
20689
|
// packages/cli/src/sync.ts
|
|
20149
|
-
import { createHash as
|
|
20150
|
-
import { chmod, cp, lstat as
|
|
20690
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
20691
|
+
import { chmod, cp, lstat as lstat4, mkdtemp, mkdir as mkdir2, readdir as readdir3, readFile as readFile3, rm, rename as rename3, writeFile as writeFile3 } from "node:fs/promises";
|
|
20151
20692
|
import os4 from "node:os";
|
|
20152
|
-
import
|
|
20693
|
+
import path5 from "node:path";
|
|
20153
20694
|
|
|
20154
20695
|
// node_modules/tar/dist/esm/index.min.js
|
|
20155
20696
|
import Qr from "events";
|
|
@@ -23215,12 +23756,14 @@ async function reconcileWorkPacks(input) {
|
|
|
23215
23756
|
const receiptValue = {
|
|
23216
23757
|
schemaVersion: 1,
|
|
23217
23758
|
completedAt: (input.now ?? (() => /* @__PURE__ */ new Date()))().toISOString(),
|
|
23218
|
-
outcomes: outcomes.map(({ slug, version: version2, action, reason, status }) => ({
|
|
23759
|
+
outcomes: outcomes.map(({ slug, version: version2, action, reason, status, code, integrity }) => ({
|
|
23219
23760
|
slug,
|
|
23220
23761
|
...version2 === void 0 ? {} : { version: version2 },
|
|
23221
23762
|
action,
|
|
23222
23763
|
reason,
|
|
23223
|
-
status
|
|
23764
|
+
status,
|
|
23765
|
+
...code ? { code } : {},
|
|
23766
|
+
...integrity ? { integrity } : {}
|
|
23224
23767
|
})),
|
|
23225
23768
|
omissionPrune
|
|
23226
23769
|
};
|
|
@@ -23261,6 +23804,7 @@ async function runOperation(operation, operate) {
|
|
|
23261
23804
|
...outcomeIdentity(operation),
|
|
23262
23805
|
status: "failed",
|
|
23263
23806
|
code: stableCode(result.code),
|
|
23807
|
+
...result.integrity ? { integrity: result.integrity } : {},
|
|
23264
23808
|
...result.projectionConflict ? { projectionConflict: result.projectionConflict } : {},
|
|
23265
23809
|
message: `O pacote "${operation.pack.slug}" falhou, mas o estado anterior foi restaurado exatamente. Corrija a causa indicada e volte a sincronizar.`
|
|
23266
23810
|
};
|
|
@@ -23304,152 +23848,6 @@ function assertUniqueSlugs(packs, label) {
|
|
|
23304
23848
|
}
|
|
23305
23849
|
}
|
|
23306
23850
|
|
|
23307
|
-
// packages/cli/src/workPackLocalState.ts
|
|
23308
|
-
import { createHash } from "node:crypto";
|
|
23309
|
-
import { lstat as lstat2, mkdir, readFile as readFile2, readdir, rename as rename2, writeFile as writeFile2 } from "node:fs/promises";
|
|
23310
|
-
import path3 from "node:path";
|
|
23311
|
-
var WORK_PACK_LOCAL_STATE_FILENAME = ".forge-installed-state.json";
|
|
23312
|
-
async function writeWorkPackInstalledState(input) {
|
|
23313
|
-
const tree = await digestPackTree(input.packDir);
|
|
23314
|
-
if (!tree) throw new Error("O pacote de trabalho cont\xE9m uma entrada local n\xE3o regular");
|
|
23315
|
-
const state = {
|
|
23316
|
-
schemaVersion: 1,
|
|
23317
|
-
version: input.version,
|
|
23318
|
-
...tree,
|
|
23319
|
-
agents: digestProjectionContents(input.agents),
|
|
23320
|
-
commands: digestProjectionContents(input.commands)
|
|
23321
|
-
};
|
|
23322
|
-
await writeJsonAtomic(path3.join(input.packDir, WORK_PACK_LOCAL_STATE_FILENAME), state);
|
|
23323
|
-
}
|
|
23324
|
-
async function checkWorkPackInstalledState(input) {
|
|
23325
|
-
const state = await readInstalledState(input.packDir);
|
|
23326
|
-
if (!state) return "missing";
|
|
23327
|
-
return await matchesInstalledState(input, state) ? "match" : "changed";
|
|
23328
|
-
}
|
|
23329
|
-
async function checkWorkPackTreeState(packDir) {
|
|
23330
|
-
const state = await readInstalledState(packDir);
|
|
23331
|
-
if (!state) return "missing";
|
|
23332
|
-
const tree = await digestPackTree(packDir).catch(() => void 0);
|
|
23333
|
-
return tree && sameTree(tree, state) ? "match" : "changed";
|
|
23334
|
-
}
|
|
23335
|
-
async function adoptWorkPackInstalledState(input) {
|
|
23336
|
-
const state = await readInstalledState(input.expectedPackDir);
|
|
23337
|
-
if (!state || !await matchesInstalledState(input, state)) return false;
|
|
23338
|
-
await writeJsonAtomic(path3.join(input.packDir, WORK_PACK_LOCAL_STATE_FILENAME), state);
|
|
23339
|
-
return checkWorkPackInstalledState(input).then((result) => result === "match");
|
|
23340
|
-
}
|
|
23341
|
-
async function adoptVerifiedWorkPackState(input) {
|
|
23342
|
-
const tree = await digestPackTree(input.packDir);
|
|
23343
|
-
if (!tree) return false;
|
|
23344
|
-
const projections = async (kind, directory) => {
|
|
23345
|
-
const prefix = `${kind}/`;
|
|
23346
|
-
const expected = tree.files.filter((file2) => file2.path.startsWith(prefix) && !file2.path.slice(prefix.length).includes("/") && file2.path.endsWith(".md") && !file2.path.slice(prefix.length).startsWith("._"));
|
|
23347
|
-
const result = [];
|
|
23348
|
-
for (const file2 of expected) {
|
|
23349
|
-
const filename = file2.path.slice(prefix.length);
|
|
23350
|
-
const absolute = path3.join(directory, filename);
|
|
23351
|
-
const info = await lstat2(absolute);
|
|
23352
|
-
if (!info.isFile() || info.isSymbolicLink()) throw new Error("Unsafe projection");
|
|
23353
|
-
result.push({ filename, sha256: digest(await readFile2(absolute)) });
|
|
23354
|
-
}
|
|
23355
|
-
return result.sort((a, b2) => a.filename.localeCompare(b2.filename));
|
|
23356
|
-
};
|
|
23357
|
-
const state = {
|
|
23358
|
-
schemaVersion: 1,
|
|
23359
|
-
version: input.version,
|
|
23360
|
-
...tree,
|
|
23361
|
-
agents: await projections("agents", input.agentsDir),
|
|
23362
|
-
commands: await projections("commands", input.commandsDir)
|
|
23363
|
-
};
|
|
23364
|
-
if (digest(Buffer.from(canonicalWorkPackState(state))) !== input.fingerprint) return false;
|
|
23365
|
-
if (!await matchesInstalledState(input, state)) return false;
|
|
23366
|
-
await writeJsonAtomic(path3.join(input.packDir, WORK_PACK_LOCAL_STATE_FILENAME), state);
|
|
23367
|
-
return await checkWorkPackInstalledState(input) === "match";
|
|
23368
|
-
}
|
|
23369
|
-
async function readInstalledState(packDir) {
|
|
23370
|
-
const raw = await readFile2(path3.join(packDir, WORK_PACK_LOCAL_STATE_FILENAME), "utf8").catch(() => void 0);
|
|
23371
|
-
if (!raw) return void 0;
|
|
23372
|
-
try {
|
|
23373
|
-
const value = JSON.parse(raw);
|
|
23374
|
-
if (value.schemaVersion !== 1 || typeof value.version !== "string") return void 0;
|
|
23375
|
-
if (!validDigests(value.files, "path") || !validDigests(value.agents, "filename") || !validDigests(value.commands, "filename")) {
|
|
23376
|
-
return void 0;
|
|
23377
|
-
}
|
|
23378
|
-
if (!validDirectories(value.directories)) return void 0;
|
|
23379
|
-
return value;
|
|
23380
|
-
} catch {
|
|
23381
|
-
return void 0;
|
|
23382
|
-
}
|
|
23383
|
-
}
|
|
23384
|
-
async function digestPackTree(root) {
|
|
23385
|
-
const files = [];
|
|
23386
|
-
const directories = [];
|
|
23387
|
-
const visit = async (directory, prefix) => {
|
|
23388
|
-
const entries = await readdir(directory, { withFileTypes: true });
|
|
23389
|
-
for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
|
|
23390
|
-
if (!prefix && entry.name === WORK_PACK_LOCAL_STATE_FILENAME) continue;
|
|
23391
|
-
const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
|
|
23392
|
-
const absolute = path3.join(directory, entry.name);
|
|
23393
|
-
if (entry.isDirectory()) {
|
|
23394
|
-
directories.push(relative);
|
|
23395
|
-
if (!await visit(absolute, relative)) return false;
|
|
23396
|
-
continue;
|
|
23397
|
-
}
|
|
23398
|
-
if (!entry.isFile()) return false;
|
|
23399
|
-
files.push({ path: relative, sha256: digest(await readFile2(absolute)) });
|
|
23400
|
-
}
|
|
23401
|
-
return true;
|
|
23402
|
-
};
|
|
23403
|
-
return await visit(root, "") ? { files, directories } : void 0;
|
|
23404
|
-
}
|
|
23405
|
-
function digestProjectionContents(files) {
|
|
23406
|
-
return files.map((file2) => ({ filename: file2.filename, sha256: digest(Buffer.from(file2.content)) })).sort((left, right) => left.filename.localeCompare(right.filename));
|
|
23407
|
-
}
|
|
23408
|
-
async function projectionsMatch(directory, expected) {
|
|
23409
|
-
for (const projection of expected) {
|
|
23410
|
-
const absolute = path3.join(directory, projection.filename);
|
|
23411
|
-
const info = await lstat2(absolute).catch(() => void 0);
|
|
23412
|
-
if (!info?.isFile() || info.isSymbolicLink()) return false;
|
|
23413
|
-
const bytes = await readFile2(absolute).catch(() => void 0);
|
|
23414
|
-
if (!bytes || digest(bytes) !== projection.sha256) return false;
|
|
23415
|
-
}
|
|
23416
|
-
return true;
|
|
23417
|
-
}
|
|
23418
|
-
function validDigests(value, pathKey) {
|
|
23419
|
-
return Array.isArray(value) && value.every((entry) => typeof entry === "object" && entry !== null && typeof entry[pathKey] === "string" && typeof entry.sha256 === "string" && /^[a-f0-9]{64}$/.test(entry.sha256) && validRelativePath(entry[pathKey], pathKey === "filename"));
|
|
23420
|
-
}
|
|
23421
|
-
function validDirectories(value) {
|
|
23422
|
-
return Array.isArray(value) && value.every((entry) => typeof entry === "string" && validRelativePath(entry, false));
|
|
23423
|
-
}
|
|
23424
|
-
async function matchesInstalledState(input, state) {
|
|
23425
|
-
const tree = await digestPackTree(input.packDir).catch(() => void 0);
|
|
23426
|
-
if (!tree || !sameTree(tree, state)) return false;
|
|
23427
|
-
if (!await projectionsMatch(input.agentsDir, state.agents)) return false;
|
|
23428
|
-
return projectionsMatch(input.commandsDir, state.commands);
|
|
23429
|
-
}
|
|
23430
|
-
function validRelativePath(value, filenameOnly) {
|
|
23431
|
-
if (!value || path3.isAbsolute(value) || value.includes("\\")) return false;
|
|
23432
|
-
const parts = value.split("/");
|
|
23433
|
-
if (parts.some((part) => !part || part === "." || part === "..")) return false;
|
|
23434
|
-
return !filenameOnly || parts.length === 1;
|
|
23435
|
-
}
|
|
23436
|
-
function sameTree(left, right) {
|
|
23437
|
-
return sameDigests(left.files, right.files) && left.directories.length === right.directories.length && left.directories.every((entry, index) => entry === right.directories[index]);
|
|
23438
|
-
}
|
|
23439
|
-
function sameDigests(left, right) {
|
|
23440
|
-
return left.length === right.length && left.every((entry, index) => entry.path === right[index]?.path && entry.sha256 === right[index]?.sha256);
|
|
23441
|
-
}
|
|
23442
|
-
function digest(bytes) {
|
|
23443
|
-
return createHash("sha256").update(bytes).digest("hex");
|
|
23444
|
-
}
|
|
23445
|
-
async function writeJsonAtomic(filePath, value) {
|
|
23446
|
-
await mkdir(path3.dirname(filePath), { recursive: true });
|
|
23447
|
-
const tempPath = path3.join(path3.dirname(filePath), `.${path3.basename(filePath)}.${process.pid}.tmp`);
|
|
23448
|
-
await writeFile2(tempPath, `${JSON.stringify(value, null, 2)}
|
|
23449
|
-
`);
|
|
23450
|
-
await rename2(tempPath, filePath);
|
|
23451
|
-
}
|
|
23452
|
-
|
|
23453
23851
|
// packages/cli/src/sync.ts
|
|
23454
23852
|
var WORK_PACK_COMMITTED_MARKER = ".forge-replacement-committed";
|
|
23455
23853
|
var WORK_PACK_TRANSACTION_SUFFIX = ".transaction";
|
|
@@ -23498,9 +23896,9 @@ async function applyWorkPackManifest(paths, credentials, manifest, options) {
|
|
|
23498
23896
|
const recovery = await recoverInterruptedWorkPackInstalls(paths, options.cleanupWorkPackBackup, options.workPackProjectionBoundary);
|
|
23499
23897
|
const managed = await Promise.all((await managedWorkPackSlugs(paths.skillsDir)).map(async (slug) => ({
|
|
23500
23898
|
slug,
|
|
23501
|
-
version: (await readFile3(
|
|
23502
|
-
agents: await readAgentRecord(
|
|
23503
|
-
commands: await readCommandRecord(
|
|
23899
|
+
version: (await readFile3(path5.join(paths.skillsDir, slug, ".forge-version"), "utf8")).trim(),
|
|
23900
|
+
agents: await readAgentRecord(path5.join(paths.skillsDir, slug)),
|
|
23901
|
+
commands: await readCommandRecord(path5.join(paths.skillsDir, slug))
|
|
23504
23902
|
})));
|
|
23505
23903
|
const desired = manifest.skills.map((skill) => ({
|
|
23506
23904
|
slug: skill.slug,
|
|
@@ -23513,7 +23911,7 @@ async function applyWorkPackManifest(paths, credentials, manifest, options) {
|
|
|
23513
23911
|
desired,
|
|
23514
23912
|
managed,
|
|
23515
23913
|
desiredIsComplete: manifest.workPacksComplete === true,
|
|
23516
|
-
operate: (operation) => operateWorkPack(
|
|
23914
|
+
operate: async (operation) => enrichIntegrityFailure(paths, operation, await operateWorkPack(
|
|
23517
23915
|
paths,
|
|
23518
23916
|
credentials,
|
|
23519
23917
|
skillBySlug,
|
|
@@ -23522,9 +23920,9 @@ async function applyWorkPackManifest(paths, credentials, manifest, options) {
|
|
|
23522
23920
|
recovery.failures,
|
|
23523
23921
|
operation,
|
|
23524
23922
|
options
|
|
23525
|
-
),
|
|
23923
|
+
)),
|
|
23526
23924
|
recoveryFailures: recovery.failures,
|
|
23527
|
-
writeAtomicReceipt: (receipt) => writeJsonAtomic2(
|
|
23925
|
+
writeAtomicReceipt: (receipt) => writeJsonAtomic2(path5.join(paths.forgeDir, "work-pack-sync-receipt.json"), receipt)
|
|
23528
23926
|
});
|
|
23529
23927
|
const installed = workPacks.outcomes.filter((outcome) => outcome.status === "installed").map((outcome) => `${outcome.slug}@${outcome.version}`);
|
|
23530
23928
|
const removed = workPacks.outcomes.filter((outcome) => outcome.status === "removed").map((outcome) => outcome.slug);
|
|
@@ -23535,7 +23933,7 @@ async function applyWorkPackManifest(paths, credentials, manifest, options) {
|
|
|
23535
23933
|
async function collectWorkPackObservations(paths, reconciliation) {
|
|
23536
23934
|
const installedVersions = /* @__PURE__ */ new Map();
|
|
23537
23935
|
for (const slug of await managedWorkPackSlugs(paths.skillsDir)) {
|
|
23538
|
-
const version2 = (await readFile3(
|
|
23936
|
+
const version2 = (await readFile3(path5.join(paths.skillsDir, slug, ".forge-version"), "utf8")).trim();
|
|
23539
23937
|
if (version2) installedVersions.set(slug, version2);
|
|
23540
23938
|
}
|
|
23541
23939
|
const observations = new Map(
|
|
@@ -23548,13 +23946,25 @@ async function collectWorkPackObservations(paths, reconciliation) {
|
|
|
23548
23946
|
state: "failed",
|
|
23549
23947
|
...outcome.version ? { version: outcome.version } : {},
|
|
23550
23948
|
...installedVersions.get(outcome.slug) ? { installedVersion: installedVersions.get(outcome.slug) } : {},
|
|
23551
|
-
errorCode: outcome.code ?? outcome.status
|
|
23949
|
+
errorCode: outcome.code ?? outcome.status,
|
|
23950
|
+
...outcome.integrity ? { integrity: outcome.integrity } : {}
|
|
23552
23951
|
});
|
|
23553
23952
|
}
|
|
23554
23953
|
return [...observations.values()].sort((a, b2) => a.slug.localeCompare(b2.slug));
|
|
23555
23954
|
}
|
|
23955
|
+
async function enrichIntegrityFailure(paths, operation, result) {
|
|
23956
|
+
if (result.status !== "failed" || !["local-edits-preserved", "local-baseline-missing"].includes(result.code)) return result;
|
|
23957
|
+
try {
|
|
23958
|
+
const { summary } = await inspectWorkPackIntegrity({ paths, slug: operation.pack.slug });
|
|
23959
|
+
if (summary.kind === "match") return result;
|
|
23960
|
+
const code = summary.kind === "runtime-artifacts" ? "local-runtime-artifacts" : summary.kind === "unknown-additions" ? "local-additions-preserved" : summary.kind === "unsafe-or-unreadable" ? "local-state-unreadable" : result.code;
|
|
23961
|
+
return { ...result, code, integrity: summary };
|
|
23962
|
+
} catch {
|
|
23963
|
+
return result;
|
|
23964
|
+
}
|
|
23965
|
+
}
|
|
23556
23966
|
async function operateWorkPack(paths, credentials, skillBySlug, approvedModelIds, cleanupPendingSlugs, recoveryFailures, operation, options) {
|
|
23557
|
-
const target =
|
|
23967
|
+
const target = path5.join(paths.skillsDir, operation.pack.slug);
|
|
23558
23968
|
const recoveryFailure = recoveryFailures.get(operation.pack.slug);
|
|
23559
23969
|
if (recoveryFailure) return { status: "failed", restoration: "exact", code: recoveryFailure };
|
|
23560
23970
|
let ownership;
|
|
@@ -23593,7 +24003,7 @@ async function operateWorkPack(paths, credentials, skillBySlug, approvedModelIds
|
|
|
23593
24003
|
let previousManagedPaths;
|
|
23594
24004
|
let archive;
|
|
23595
24005
|
try {
|
|
23596
|
-
const currentVersion = await readFile3(
|
|
24006
|
+
const currentVersion = await readFile3(path5.join(target, ".forge-version"), "utf8").catch(() => "");
|
|
23597
24007
|
const sameVersion = currentVersion.trim() === skill.version;
|
|
23598
24008
|
if (sameVersion) {
|
|
23599
24009
|
let localState = await checkWorkPackInstalledState({
|
|
@@ -23603,7 +24013,7 @@ async function operateWorkPack(paths, credentials, skillBySlug, approvedModelIds
|
|
|
23603
24013
|
});
|
|
23604
24014
|
if (localState === "missing") {
|
|
23605
24015
|
const candidateArchive = await downloadSkill(credentials, skill.url);
|
|
23606
|
-
const candidateSha256 =
|
|
24016
|
+
const candidateSha256 = createHash3("sha256").update(candidateArchive).digest("hex");
|
|
23607
24017
|
if (candidateSha256 !== skill.sha256) {
|
|
23608
24018
|
return { status: "failed", restoration: "exact", code: "local-baseline-missing" };
|
|
23609
24019
|
}
|
|
@@ -23652,7 +24062,7 @@ async function operateWorkPack(paths, credentials, skillBySlug, approvedModelIds
|
|
|
23652
24062
|
}
|
|
23653
24063
|
previousManagedPaths = await managedWorkPackPaths(paths, target);
|
|
23654
24064
|
archive = await downloadSkill(credentials, skill.url);
|
|
23655
|
-
const sha256 =
|
|
24065
|
+
const sha256 = createHash3("sha256").update(archive).digest("hex");
|
|
23656
24066
|
if (sha256 !== skill.sha256) return { status: "failed", restoration: "exact", code: "checksum-mismatch" };
|
|
23657
24067
|
} catch (error45) {
|
|
23658
24068
|
return exactPackFailure(error45);
|
|
@@ -23766,7 +24176,7 @@ var WorkPackLocalEditsError = class extends Error {
|
|
|
23766
24176
|
async function assertWorkPackUnchangedAtBoundary(paths, target) {
|
|
23767
24177
|
const ownership = await workPackOwnership(target);
|
|
23768
24178
|
if (ownership === "absent") return;
|
|
23769
|
-
if (ownership === "foreign") throw foreignWorkPackError(
|
|
24179
|
+
if (ownership === "foreign") throw foreignWorkPackError(path5.basename(target));
|
|
23770
24180
|
const localState = await checkWorkPackInstalledState({
|
|
23771
24181
|
packDir: target,
|
|
23772
24182
|
agentsDir: paths.agentsDir,
|
|
@@ -23790,12 +24200,12 @@ function skillSlugFromUrl(value) {
|
|
|
23790
24200
|
}
|
|
23791
24201
|
}
|
|
23792
24202
|
async function installSkillArchive(paths, slug, version2, archive, options = {}) {
|
|
23793
|
-
const tempRoot = await mkdtemp(
|
|
23794
|
-
const archivePath =
|
|
23795
|
-
const extractPath =
|
|
23796
|
-
const nextPath =
|
|
23797
|
-
const target =
|
|
23798
|
-
const backup =
|
|
24203
|
+
const tempRoot = await mkdtemp(path5.join(os4.tmpdir(), `forge-${slug}-`));
|
|
24204
|
+
const archivePath = path5.join(tempRoot, `${slug}.tar`);
|
|
24205
|
+
const extractPath = path5.join(tempRoot, "extract");
|
|
24206
|
+
const nextPath = path5.join(tempRoot, slug);
|
|
24207
|
+
const target = path5.join(paths.skillsDir, slug);
|
|
24208
|
+
const backup = path5.join(paths.skillsDir, `${slug}.previous`);
|
|
23799
24209
|
let agentFiles;
|
|
23800
24210
|
let commandFiles;
|
|
23801
24211
|
let previousAgents;
|
|
@@ -23804,7 +24214,7 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
|
|
|
23804
24214
|
await mkdir2(extractPath, { recursive: true });
|
|
23805
24215
|
await writeFile3(archivePath, archive);
|
|
23806
24216
|
await So({ file: archivePath, cwd: extractPath, strict: true });
|
|
23807
|
-
const extractedSkillPath =
|
|
24217
|
+
const extractedSkillPath = path5.join(extractPath, slug);
|
|
23808
24218
|
await assertNoReservedMarkerAliases(extractedSkillPath);
|
|
23809
24219
|
await validateSkillFolder(extractedSkillPath, slug);
|
|
23810
24220
|
agentFiles = await normalizePackAgentModels(
|
|
@@ -23831,15 +24241,15 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
|
|
|
23831
24241
|
}
|
|
23832
24242
|
throw error45;
|
|
23833
24243
|
}
|
|
23834
|
-
await rename3(
|
|
23835
|
-
await writeFile3(
|
|
24244
|
+
await rename3(path5.join(extractPath, slug), nextPath);
|
|
24245
|
+
await writeFile3(path5.join(nextPath, ".forge-version"), `${version2}
|
|
23836
24246
|
`);
|
|
23837
24247
|
if (agentFiles.length > 0) {
|
|
23838
|
-
await writeFile3(
|
|
24248
|
+
await writeFile3(path5.join(nextPath, ".forge-agents"), `${agentFiles.map((agent) => agent.filename).join("\n")}
|
|
23839
24249
|
`);
|
|
23840
24250
|
}
|
|
23841
24251
|
if (commandFiles.length > 0) {
|
|
23842
|
-
await writeFile3(
|
|
24252
|
+
await writeFile3(path5.join(nextPath, ".forge-commands"), `${commandFiles.map((command) => command.filename).join("\n")}
|
|
23843
24253
|
`);
|
|
23844
24254
|
}
|
|
23845
24255
|
await writeWorkPackInstalledState({ packDir: nextPath, version: version2, agents: agentFiles, commands: commandFiles });
|
|
@@ -23850,13 +24260,13 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
|
|
|
23850
24260
|
const agentTransactionState = new Map(
|
|
23851
24261
|
[...agentSnapshot.keys()].map((filePath) => [
|
|
23852
24262
|
filePath,
|
|
23853
|
-
agentFiles.find((agent) => agent.filename ===
|
|
24263
|
+
agentFiles.find((agent) => agent.filename === path5.basename(filePath))?.content
|
|
23854
24264
|
])
|
|
23855
24265
|
);
|
|
23856
24266
|
const commandTransactionState = new Map(
|
|
23857
24267
|
[...commandSnapshot.keys()].map((filePath) => [
|
|
23858
24268
|
filePath,
|
|
23859
|
-
commandFiles.find((command) => command.filename ===
|
|
24269
|
+
commandFiles.find((command) => command.filename === path5.basename(filePath))?.content
|
|
23860
24270
|
])
|
|
23861
24271
|
);
|
|
23862
24272
|
const previousManagedPaths = await managedWorkPackPaths(paths, target);
|
|
@@ -23868,7 +24278,7 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
|
|
|
23868
24278
|
throw error45;
|
|
23869
24279
|
}
|
|
23870
24280
|
const writeProjection = options.writeWorkPackProjection ?? writeTextAtomic;
|
|
23871
|
-
const claimedBackup =
|
|
24281
|
+
const claimedBackup = path5.join(tempRoot, `${slug}-claimed-previous`);
|
|
23872
24282
|
const transactionPath = `${backup}${WORK_PACK_TRANSACTION_SUFFIX}`;
|
|
23873
24283
|
let targetBackedUp = false;
|
|
23874
24284
|
let targetInstalled = false;
|
|
@@ -23891,7 +24301,7 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
|
|
|
23891
24301
|
await rename3(nextPath, target);
|
|
23892
24302
|
targetInstalled = true;
|
|
23893
24303
|
for (const filename of previousAgents.filter((name) => !nextAgentNames.has(name))) {
|
|
23894
|
-
const filePath =
|
|
24304
|
+
const filePath = path5.join(paths.agentsDir, filename);
|
|
23895
24305
|
await options.workPackProjectionBoundary?.("install", filePath);
|
|
23896
24306
|
await assertProjectionState(filePath, agentSnapshot.get(filePath));
|
|
23897
24307
|
await rm(filePath, { force: true });
|
|
@@ -23899,14 +24309,14 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
|
|
|
23899
24309
|
if (agentFiles.length > 0) {
|
|
23900
24310
|
await mkdir2(paths.agentsDir, { recursive: true });
|
|
23901
24311
|
for (const agent of agentFiles) {
|
|
23902
|
-
const filePath =
|
|
24312
|
+
const filePath = path5.join(paths.agentsDir, agent.filename);
|
|
23903
24313
|
await options.workPackProjectionBoundary?.("install", filePath);
|
|
23904
24314
|
await assertProjectionState(filePath, agentSnapshot.get(filePath));
|
|
23905
24315
|
await writeProjection(filePath, agent.content);
|
|
23906
24316
|
}
|
|
23907
24317
|
}
|
|
23908
24318
|
for (const filename of previousCommands.filter((name) => !nextCommandNames.has(name))) {
|
|
23909
|
-
const filePath =
|
|
24319
|
+
const filePath = path5.join(paths.commandsDir, filename);
|
|
23910
24320
|
await options.workPackProjectionBoundary?.("install", filePath);
|
|
23911
24321
|
await assertProjectionState(filePath, commandSnapshot.get(filePath));
|
|
23912
24322
|
await rm(filePath, { force: true });
|
|
@@ -23914,7 +24324,7 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
|
|
|
23914
24324
|
if (commandFiles.length > 0) {
|
|
23915
24325
|
await mkdir2(paths.commandsDir, { recursive: true });
|
|
23916
24326
|
for (const command of commandFiles) {
|
|
23917
|
-
const filePath =
|
|
24327
|
+
const filePath = path5.join(paths.commandsDir, command.filename);
|
|
23918
24328
|
await options.workPackProjectionBoundary?.("install", filePath);
|
|
23919
24329
|
await assertProjectionState(filePath, commandSnapshot.get(filePath));
|
|
23920
24330
|
await writeProjection(filePath, command.content);
|
|
@@ -23926,7 +24336,7 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
|
|
|
23926
24336
|
await rename3(backup, claimedBackup);
|
|
23927
24337
|
backupClaimed = true;
|
|
23928
24338
|
await assertWorkPackTreeUnchangedAtBoundary(claimedBackup);
|
|
23929
|
-
await writeFile3(
|
|
24339
|
+
await writeFile3(path5.join(claimedBackup, WORK_PACK_COMMITTED_MARKER), `${version2}
|
|
23930
24340
|
`);
|
|
23931
24341
|
await writeTextAtomic(transactionPath, "committed\n");
|
|
23932
24342
|
}
|
|
@@ -23937,7 +24347,7 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
|
|
|
23937
24347
|
await restoreProjectionState(commandSnapshot, commandTransactionState);
|
|
23938
24348
|
}
|
|
23939
24349
|
if (targetBackedUp) {
|
|
23940
|
-
const restoredTarget =
|
|
24350
|
+
const restoredTarget = path5.join(tempRoot, `${slug}-restore`);
|
|
23941
24351
|
const rollbackSource = backupClaimed ? claimedBackup : backup;
|
|
23942
24352
|
await cp(rollbackSource, restoredTarget, { recursive: true });
|
|
23943
24353
|
if (targetInstalled) await rm(target, { recursive: true, force: true });
|
|
@@ -23974,19 +24384,19 @@ async function installSkillArchive(paths, slug, version2, archive, options = {})
|
|
|
23974
24384
|
return { cleanup };
|
|
23975
24385
|
}
|
|
23976
24386
|
async function adoptLegacyWorkPackState(paths, slug, version2, archive, approvedModelIds) {
|
|
23977
|
-
const comparisonRoot = await mkdtemp(
|
|
24387
|
+
const comparisonRoot = await mkdtemp(path5.join(os4.tmpdir(), `forge-${slug}-baseline-`));
|
|
23978
24388
|
const comparisonPaths = {
|
|
23979
24389
|
...paths,
|
|
23980
|
-
skillsDir:
|
|
23981
|
-
agentsDir:
|
|
23982
|
-
commandsDir:
|
|
24390
|
+
skillsDir: path5.join(comparisonRoot, "skills"),
|
|
24391
|
+
agentsDir: path5.join(comparisonRoot, "agents"),
|
|
24392
|
+
commandsDir: path5.join(comparisonRoot, "commands")
|
|
23983
24393
|
};
|
|
23984
24394
|
try {
|
|
23985
24395
|
await mkdir2(comparisonPaths.skillsDir, { recursive: true });
|
|
23986
24396
|
await installSkillArchive(comparisonPaths, slug, version2, archive, { approvedModelIds });
|
|
23987
24397
|
return adoptWorkPackInstalledState({
|
|
23988
|
-
expectedPackDir:
|
|
23989
|
-
packDir:
|
|
24398
|
+
expectedPackDir: path5.join(comparisonPaths.skillsDir, slug),
|
|
24399
|
+
packDir: path5.join(paths.skillsDir, slug),
|
|
23990
24400
|
agentsDir: paths.agentsDir,
|
|
23991
24401
|
commandsDir: paths.commandsDir
|
|
23992
24402
|
});
|
|
@@ -23997,7 +24407,7 @@ async function adoptLegacyWorkPackState(paths, slug, version2, archive, approved
|
|
|
23997
24407
|
async function recoverInterruptedWorkPackInstalls(paths, cleanupWorkPackBackup, workPackProjectionBoundary) {
|
|
23998
24408
|
const cleanupPending = /* @__PURE__ */ new Set();
|
|
23999
24409
|
const failures = /* @__PURE__ */ new Map();
|
|
24000
|
-
const entries = await
|
|
24410
|
+
const entries = await readdir3(paths.skillsDir, { withFileTypes: true }).catch((error45) => {
|
|
24001
24411
|
if (error45.code === "ENOENT") return [];
|
|
24002
24412
|
throw error45;
|
|
24003
24413
|
});
|
|
@@ -24005,7 +24415,7 @@ async function recoverInterruptedWorkPackInstalls(paths, cleanupWorkPackBackup,
|
|
|
24005
24415
|
if (!entry.name.endsWith(".previous")) continue;
|
|
24006
24416
|
const slug = entry.name.slice(0, -".previous".length);
|
|
24007
24417
|
if (!slug) continue;
|
|
24008
|
-
const target =
|
|
24418
|
+
const target = path5.join(paths.skillsDir, slug);
|
|
24009
24419
|
const backup = `${target}.previous`;
|
|
24010
24420
|
const transactionState = await readWorkPackTransactionState(backup);
|
|
24011
24421
|
if (transactionState === "committed") {
|
|
@@ -24038,9 +24448,9 @@ async function recoverInterruptedWorkPackInstall(paths, target, cleanupWorkPackB
|
|
|
24038
24448
|
const backup = `${target}.previous`;
|
|
24039
24449
|
const backupOwnership = await workPackOwnership(backup);
|
|
24040
24450
|
if (backupOwnership === "absent") return "recovered";
|
|
24041
|
-
if (backupOwnership === "foreign") throw foreignWorkPackError(
|
|
24042
|
-
if (await workPackOwnership(target) === "foreign") throw foreignWorkPackError(
|
|
24043
|
-
const committed = await readFile3(
|
|
24451
|
+
if (backupOwnership === "foreign") throw foreignWorkPackError(path5.basename(target));
|
|
24452
|
+
if (await workPackOwnership(target) === "foreign") throw foreignWorkPackError(path5.basename(target));
|
|
24453
|
+
const committed = await readFile3(path5.join(backup, WORK_PACK_COMMITTED_MARKER), "utf8").catch((error45) => {
|
|
24044
24454
|
if (error45.code === "ENOENT") return void 0;
|
|
24045
24455
|
throw error45;
|
|
24046
24456
|
});
|
|
@@ -24082,32 +24492,32 @@ async function recoverInterruptedWorkPackInstall(paths, target, cleanupWorkPackB
|
|
|
24082
24492
|
);
|
|
24083
24493
|
const previousAgentNames = new Set(previousAgents.map((agent) => agent.filename));
|
|
24084
24494
|
const previousCommandNames = new Set(previousCommands.map((command) => command.filename));
|
|
24085
|
-
const recoveryRoot = await mkdtemp(
|
|
24086
|
-
const recoveredTarget =
|
|
24495
|
+
const recoveryRoot = await mkdtemp(path5.join(os4.tmpdir(), "forge-recover-"));
|
|
24496
|
+
const recoveredTarget = path5.join(recoveryRoot, path5.basename(target));
|
|
24087
24497
|
await cp(backup, recoveredTarget, { recursive: true });
|
|
24088
24498
|
try {
|
|
24089
24499
|
for (const filename of currentAgents.filter((name) => !previousAgentNames.has(name))) {
|
|
24090
|
-
const filePath =
|
|
24500
|
+
const filePath = path5.join(paths.agentsDir, filename);
|
|
24091
24501
|
await workPackProjectionBoundary?.("recover", filePath);
|
|
24092
24502
|
await assertProjectionState(filePath, agentRecoveryState.get(filePath));
|
|
24093
24503
|
await rm(filePath, { force: true });
|
|
24094
24504
|
}
|
|
24095
24505
|
await mkdir2(paths.agentsDir, { recursive: true });
|
|
24096
24506
|
for (const agent of previousAgents) {
|
|
24097
|
-
const filePath =
|
|
24507
|
+
const filePath = path5.join(paths.agentsDir, agent.filename);
|
|
24098
24508
|
await workPackProjectionBoundary?.("recover", filePath);
|
|
24099
24509
|
await assertProjectionState(filePath, agentRecoveryState.get(filePath));
|
|
24100
24510
|
await writeTextAtomic(filePath, agent.content);
|
|
24101
24511
|
}
|
|
24102
24512
|
for (const filename of currentCommands.filter((name) => !previousCommandNames.has(name))) {
|
|
24103
|
-
const filePath =
|
|
24513
|
+
const filePath = path5.join(paths.commandsDir, filename);
|
|
24104
24514
|
await workPackProjectionBoundary?.("recover", filePath);
|
|
24105
24515
|
await assertProjectionState(filePath, commandRecoveryState.get(filePath));
|
|
24106
24516
|
await rm(filePath, { force: true });
|
|
24107
24517
|
}
|
|
24108
24518
|
await mkdir2(paths.commandsDir, { recursive: true });
|
|
24109
24519
|
for (const command of previousCommands) {
|
|
24110
|
-
const filePath =
|
|
24520
|
+
const filePath = path5.join(paths.commandsDir, command.filename);
|
|
24111
24521
|
await workPackProjectionBoundary?.("recover", filePath);
|
|
24112
24522
|
await assertProjectionState(filePath, commandRecoveryState.get(filePath));
|
|
24113
24523
|
await writeTextAtomic(filePath, command.content);
|
|
@@ -24164,19 +24574,19 @@ async function readWorkPackRemovedProjections(backup) {
|
|
|
24164
24574
|
return { agents, commands };
|
|
24165
24575
|
}
|
|
24166
24576
|
async function pathExists(filePath) {
|
|
24167
|
-
return
|
|
24577
|
+
return lstat4(filePath).then(() => true, (error45) => {
|
|
24168
24578
|
if (error45.code === "ENOENT") return false;
|
|
24169
24579
|
throw error45;
|
|
24170
24580
|
});
|
|
24171
24581
|
}
|
|
24172
24582
|
async function workPackOwnership(target) {
|
|
24173
|
-
const targetStat = await
|
|
24583
|
+
const targetStat = await lstat4(target).catch((error45) => {
|
|
24174
24584
|
if (error45.code === "ENOENT") return void 0;
|
|
24175
24585
|
throw error45;
|
|
24176
24586
|
});
|
|
24177
24587
|
if (!targetStat) return "absent";
|
|
24178
24588
|
if (!targetStat.isDirectory()) return "foreign";
|
|
24179
|
-
const marker = await readFile3(
|
|
24589
|
+
const marker = await readFile3(path5.join(target, ".forge-version"), "utf8").catch((error45) => {
|
|
24180
24590
|
if (error45.code === "ENOENT") return void 0;
|
|
24181
24591
|
throw error45;
|
|
24182
24592
|
});
|
|
@@ -24202,11 +24612,11 @@ async function assertProjectionRecoveryIsSafe(directory, currentFiles, previousF
|
|
|
24202
24612
|
expected.set(file2.filename, contents);
|
|
24203
24613
|
}
|
|
24204
24614
|
for (const [filename, contents] of expected) {
|
|
24205
|
-
const projected = await readFile3(
|
|
24615
|
+
const projected = await readFile3(path5.join(directory, filename), "utf8").catch((error45) => {
|
|
24206
24616
|
if (error45.code === "ENOENT") return void 0;
|
|
24207
24617
|
throw error45;
|
|
24208
24618
|
});
|
|
24209
|
-
validated.set(
|
|
24619
|
+
validated.set(path5.join(directory, filename), projected);
|
|
24210
24620
|
const missingPreviousProjection = missingPreviousProjectionIsLocalDeletion(
|
|
24211
24621
|
filename,
|
|
24212
24622
|
projected,
|
|
@@ -24229,13 +24639,13 @@ async function assertProjectionState(filePath, expected) {
|
|
|
24229
24639
|
throw error45;
|
|
24230
24640
|
});
|
|
24231
24641
|
if (current !== expected) {
|
|
24232
|
-
throw new WorkPackLocalEditsError("local-edits-preserved", `A proje\xE7\xE3o ${
|
|
24642
|
+
throw new WorkPackLocalEditsError("local-edits-preserved", `A proje\xE7\xE3o ${path5.basename(filePath)} foi alterada durante a opera\xE7\xE3o`);
|
|
24233
24643
|
}
|
|
24234
24644
|
}
|
|
24235
24645
|
async function captureProjectionState(directory, filenames) {
|
|
24236
24646
|
const snapshot = /* @__PURE__ */ new Map();
|
|
24237
24647
|
for (const filename of filenames) {
|
|
24238
|
-
const filePath =
|
|
24648
|
+
const filePath = path5.join(directory, filename);
|
|
24239
24649
|
const content = await readFile3(filePath, "utf8").catch((error45) => {
|
|
24240
24650
|
if (error45.code === "ENOENT") return void 0;
|
|
24241
24651
|
throw error45;
|
|
@@ -24258,8 +24668,8 @@ async function restoreProjectionState(snapshot, transactionState) {
|
|
|
24258
24668
|
}
|
|
24259
24669
|
}
|
|
24260
24670
|
async function readPackAgentFiles(skillFolder) {
|
|
24261
|
-
const agentsFolder =
|
|
24262
|
-
const entries = await
|
|
24671
|
+
const agentsFolder = path5.join(skillFolder, "agents");
|
|
24672
|
+
const entries = await readdir3(agentsFolder, { withFileTypes: true }).catch((error45) => {
|
|
24263
24673
|
if (error45.code === "ENOENT") return [];
|
|
24264
24674
|
throw error45;
|
|
24265
24675
|
});
|
|
@@ -24267,7 +24677,7 @@ async function readPackAgentFiles(skillFolder) {
|
|
|
24267
24677
|
for (const entry of entries) {
|
|
24268
24678
|
if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
|
|
24269
24679
|
if (entry.name.startsWith("._")) continue;
|
|
24270
|
-
const content = await readFile3(
|
|
24680
|
+
const content = await readFile3(path5.join(agentsFolder, entry.name), "utf8");
|
|
24271
24681
|
validateAgentFile(entry.name, content);
|
|
24272
24682
|
files.push({ filename: entry.name, content });
|
|
24273
24683
|
}
|
|
@@ -24278,7 +24688,7 @@ async function normalizePackAgentModels(skillFolder, agentFiles, approvedModelId
|
|
|
24278
24688
|
for (const agent of agentFiles) {
|
|
24279
24689
|
const content = normalizePackAgentModel(agent.filename, agent.content, approvedModelIds, slug);
|
|
24280
24690
|
if (content !== agent.content) {
|
|
24281
|
-
await writeFile3(
|
|
24691
|
+
await writeFile3(path5.join(skillFolder, "agents", agent.filename), content);
|
|
24282
24692
|
}
|
|
24283
24693
|
normalized.push({ ...agent, content });
|
|
24284
24694
|
}
|
|
@@ -24298,8 +24708,8 @@ function normalizePackAgentModel(filename, content, approvedModelIds, slug) {
|
|
|
24298
24708
|
return normalizePackExtensionModel(`agents/${filename}`, content, approvedModelIds, slug);
|
|
24299
24709
|
}
|
|
24300
24710
|
async function readPackCommandFiles(skillFolder) {
|
|
24301
|
-
const commandsFolder =
|
|
24302
|
-
const entries = await
|
|
24711
|
+
const commandsFolder = path5.join(skillFolder, "commands");
|
|
24712
|
+
const entries = await readdir3(commandsFolder, { withFileTypes: true }).catch((error45) => {
|
|
24303
24713
|
if (error45.code === "ENOENT") return [];
|
|
24304
24714
|
throw error45;
|
|
24305
24715
|
});
|
|
@@ -24307,7 +24717,7 @@ async function readPackCommandFiles(skillFolder) {
|
|
|
24307
24717
|
for (const entry of entries) {
|
|
24308
24718
|
if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
|
|
24309
24719
|
if (entry.name.startsWith("._")) continue;
|
|
24310
|
-
const content = await readFile3(
|
|
24720
|
+
const content = await readFile3(path5.join(commandsFolder, entry.name), "utf8");
|
|
24311
24721
|
validateCommandFile(entry.name, content);
|
|
24312
24722
|
files.push({ filename: entry.name, content });
|
|
24313
24723
|
}
|
|
@@ -24318,7 +24728,7 @@ async function normalizePackCommandModels(skillFolder, commandFiles, approvedMod
|
|
|
24318
24728
|
for (const command of commandFiles) {
|
|
24319
24729
|
const content = normalizePackExtensionModel(`commands/${command.filename}`, command.content, approvedModelIds, slug);
|
|
24320
24730
|
if (content !== command.content) {
|
|
24321
|
-
await writeFile3(
|
|
24731
|
+
await writeFile3(path5.join(skillFolder, "commands", command.filename), content);
|
|
24322
24732
|
}
|
|
24323
24733
|
normalized.push({ ...command, content });
|
|
24324
24734
|
}
|
|
@@ -24340,7 +24750,7 @@ async function assertNoForeignAgentConflicts(agentsDir, agentFiles, ownedFilenam
|
|
|
24340
24750
|
const owned = new Set(ownedFilenames);
|
|
24341
24751
|
for (const agent of agentFiles) {
|
|
24342
24752
|
if (owned.has(agent.filename)) continue;
|
|
24343
|
-
const existing = await readFile3(
|
|
24753
|
+
const existing = await readFile3(path5.join(agentsDir, agent.filename), "utf8").catch((error45) => {
|
|
24344
24754
|
if (error45.code === "ENOENT") return void 0;
|
|
24345
24755
|
throw error45;
|
|
24346
24756
|
});
|
|
@@ -24353,7 +24763,7 @@ async function assertNoForeignCommandConflicts(commandsDir, commandFiles, ownedF
|
|
|
24353
24763
|
const owned = new Set(ownedFilenames);
|
|
24354
24764
|
for (const command of commandFiles) {
|
|
24355
24765
|
if (owned.has(command.filename)) continue;
|
|
24356
|
-
const existing = await readFile3(
|
|
24766
|
+
const existing = await readFile3(path5.join(commandsDir, command.filename), "utf8").catch((error45) => {
|
|
24357
24767
|
if (error45.code === "ENOENT") return void 0;
|
|
24358
24768
|
throw error45;
|
|
24359
24769
|
});
|
|
@@ -24363,28 +24773,28 @@ async function assertNoForeignCommandConflicts(commandsDir, commandFiles, ownedF
|
|
|
24363
24773
|
}
|
|
24364
24774
|
}
|
|
24365
24775
|
async function readAgentRecord(skillFolder) {
|
|
24366
|
-
const raw = await readFile3(
|
|
24776
|
+
const raw = await readFile3(path5.join(skillFolder, ".forge-agents"), "utf8").catch(() => "");
|
|
24367
24777
|
return raw.split("\n").map((line) => line.trim()).filter((line) => line.length > 0 && !line.includes("/") && !line.includes("\\") && line !== "..");
|
|
24368
24778
|
}
|
|
24369
24779
|
async function readCommandRecord(skillFolder) {
|
|
24370
|
-
const raw = await readFile3(
|
|
24780
|
+
const raw = await readFile3(path5.join(skillFolder, ".forge-commands"), "utf8").catch(() => "");
|
|
24371
24781
|
return raw.split("\n").map((line) => line.trim()).filter((line) => line.length > 0 && !line.includes("/") && !line.includes("\\") && line !== "..");
|
|
24372
24782
|
}
|
|
24373
24783
|
async function managedWorkPackPaths(paths, skillFolder) {
|
|
24374
24784
|
const files = await listFilesRecursively(skillFolder);
|
|
24375
|
-
const agents = (await readAgentRecord(skillFolder)).map((filename) =>
|
|
24376
|
-
const commands = (await readCommandRecord(skillFolder)).map((filename) =>
|
|
24785
|
+
const agents = (await readAgentRecord(skillFolder)).map((filename) => path5.join(paths.agentsDir, filename));
|
|
24786
|
+
const commands = (await readCommandRecord(skillFolder)).map((filename) => path5.join(paths.commandsDir, filename));
|
|
24377
24787
|
return [.../* @__PURE__ */ new Set([...files, ...agents, ...commands])];
|
|
24378
24788
|
}
|
|
24379
24789
|
async function managedWorkPackSlugs(skillsDir) {
|
|
24380
|
-
const entries = await
|
|
24790
|
+
const entries = await readdir3(skillsDir, { withFileTypes: true }).catch((error45) => {
|
|
24381
24791
|
if (error45.code === "ENOENT") return [];
|
|
24382
24792
|
throw error45;
|
|
24383
24793
|
});
|
|
24384
24794
|
const slugs = [];
|
|
24385
24795
|
for (const entry of entries) {
|
|
24386
24796
|
if (!entry.isDirectory() || entry.name.endsWith(".previous")) continue;
|
|
24387
|
-
if (await workPackOwnership(
|
|
24797
|
+
if (await workPackOwnership(path5.join(skillsDir, entry.name)) === "managed") slugs.push(entry.name);
|
|
24388
24798
|
}
|
|
24389
24799
|
return slugs.sort((left, right) => left.localeCompare(right));
|
|
24390
24800
|
}
|
|
@@ -24394,14 +24804,14 @@ async function removeManagedWorkPackTransaction(paths, target, options) {
|
|
|
24394
24804
|
const agents = await readAgentRecord(target);
|
|
24395
24805
|
const commands = await readCommandRecord(target);
|
|
24396
24806
|
const snapshots = await Promise.all([
|
|
24397
|
-
...agents.map((filename) => captureExactFile(
|
|
24398
|
-
...commands.map((filename) => captureExactFile(
|
|
24807
|
+
...agents.map((filename) => captureExactFile(path5.join(paths.agentsDir, filename))),
|
|
24808
|
+
...commands.map((filename) => captureExactFile(path5.join(paths.commandsDir, filename)))
|
|
24399
24809
|
]);
|
|
24400
24810
|
await assertWorkPackUnchangedAtBoundary(paths, target);
|
|
24401
24811
|
const backup = `${target}.previous`;
|
|
24402
24812
|
const transactionPath = `${backup}${WORK_PACK_TRANSACTION_SUFFIX}`;
|
|
24403
|
-
const transactionRoot = await mkdtemp(
|
|
24404
|
-
const claimedBackup =
|
|
24813
|
+
const transactionRoot = await mkdtemp(path5.join(os4.tmpdir(), "forge-remove-"));
|
|
24814
|
+
const claimedBackup = path5.join(transactionRoot, path5.basename(target));
|
|
24405
24815
|
let projectionsRemoved = false;
|
|
24406
24816
|
let backupClaimed = false;
|
|
24407
24817
|
try {
|
|
@@ -24419,7 +24829,7 @@ async function removeManagedWorkPackTransaction(paths, target, options) {
|
|
|
24419
24829
|
await assertWorkPackUnchangedAtBoundary(paths, backup);
|
|
24420
24830
|
projectionsRemoved = agents.length > 0;
|
|
24421
24831
|
for (const filename of agents) {
|
|
24422
|
-
const filePath =
|
|
24832
|
+
const filePath = path5.join(paths.agentsDir, filename);
|
|
24423
24833
|
await options.workPackProjectionBoundary?.("remove", filePath);
|
|
24424
24834
|
await assertExactFileState(snapshots, filePath);
|
|
24425
24835
|
await recordRemovedProjection(transactionPath, "agent", filename);
|
|
@@ -24428,7 +24838,7 @@ async function removeManagedWorkPackTransaction(paths, target, options) {
|
|
|
24428
24838
|
await options.removeWorkPackBoundary?.("after-agents");
|
|
24429
24839
|
projectionsRemoved ||= commands.length > 0;
|
|
24430
24840
|
for (const filename of commands) {
|
|
24431
|
-
const filePath =
|
|
24841
|
+
const filePath = path5.join(paths.commandsDir, filename);
|
|
24432
24842
|
await options.workPackProjectionBoundary?.("remove", filePath);
|
|
24433
24843
|
await assertExactFileState(snapshots, filePath);
|
|
24434
24844
|
await recordRemovedProjection(transactionPath, "command", filename);
|
|
@@ -24454,7 +24864,7 @@ async function removeManagedWorkPackTransaction(paths, target, options) {
|
|
|
24454
24864
|
if (await workPackOwnership(target) !== "managed") throw new Error("restored Work Pack marker missing");
|
|
24455
24865
|
await rm(transactionRoot, { recursive: true, force: true }).catch(() => void 0);
|
|
24456
24866
|
} catch (restoreError) {
|
|
24457
|
-
throw new WorkPackRecoveryUncertainError(`Falha ao remover e restaurar o pacote de trabalho ${
|
|
24867
|
+
throw new WorkPackRecoveryUncertainError(`Falha ao remover e restaurar o pacote de trabalho ${path5.basename(target)}`, {
|
|
24458
24868
|
cause: new AggregateError([error45, restoreError])
|
|
24459
24869
|
});
|
|
24460
24870
|
}
|
|
@@ -24463,7 +24873,7 @@ async function removeManagedWorkPackTransaction(paths, target, options) {
|
|
|
24463
24873
|
}
|
|
24464
24874
|
async function captureExactFile(filePath) {
|
|
24465
24875
|
try {
|
|
24466
|
-
const info = await
|
|
24876
|
+
const info = await lstat4(filePath);
|
|
24467
24877
|
if (!info.isFile()) throw new Error(`A proje\xE7\xE3o gerida n\xE3o \xE9 um ficheiro regular: ${filePath}`);
|
|
24468
24878
|
return { path: filePath, exists: true, bytes: await readFile3(filePath), mode: info.mode & 4095 };
|
|
24469
24879
|
} catch (error45) {
|
|
@@ -24475,17 +24885,17 @@ async function assertExactFileState(snapshots, filePath) {
|
|
|
24475
24885
|
const expected = snapshots.find((snapshot) => snapshot.path === filePath);
|
|
24476
24886
|
const current = await captureExactFile(filePath);
|
|
24477
24887
|
if (!expected || current.exists !== expected.exists) {
|
|
24478
|
-
throw new WorkPackLocalEditsError("local-edits-preserved", `A proje\xE7\xE3o ${
|
|
24888
|
+
throw new WorkPackLocalEditsError("local-edits-preserved", `A proje\xE7\xE3o ${path5.basename(filePath)} foi alterada durante a opera\xE7\xE3o`);
|
|
24479
24889
|
}
|
|
24480
24890
|
if (current.exists && (!current.bytes?.equals(expected.bytes) || current.mode !== expected.mode)) {
|
|
24481
|
-
throw new WorkPackLocalEditsError("local-edits-preserved", `A proje\xE7\xE3o ${
|
|
24891
|
+
throw new WorkPackLocalEditsError("local-edits-preserved", `A proje\xE7\xE3o ${path5.basename(filePath)} foi alterada durante a opera\xE7\xE3o`);
|
|
24482
24892
|
}
|
|
24483
24893
|
}
|
|
24484
24894
|
async function restoreRemovedExactFiles(snapshots) {
|
|
24485
24895
|
for (const snapshot of snapshots) {
|
|
24486
24896
|
if ((await captureExactFile(snapshot.path)).exists) continue;
|
|
24487
24897
|
if (!snapshot.exists) continue;
|
|
24488
|
-
await mkdir2(
|
|
24898
|
+
await mkdir2(path5.dirname(snapshot.path), { recursive: true });
|
|
24489
24899
|
await writeFile3(snapshot.path, snapshot.bytes);
|
|
24490
24900
|
await chmod(snapshot.path, snapshot.mode);
|
|
24491
24901
|
}
|
|
@@ -24497,20 +24907,20 @@ async function verifyRestoredOrLocallyChangedFiles(snapshots) {
|
|
|
24497
24907
|
}
|
|
24498
24908
|
}
|
|
24499
24909
|
async function listFilesRecursively(root) {
|
|
24500
|
-
const entries = await
|
|
24910
|
+
const entries = await readdir3(root, { withFileTypes: true }).catch((error45) => {
|
|
24501
24911
|
if (error45.code === "ENOENT") return [];
|
|
24502
24912
|
throw error45;
|
|
24503
24913
|
});
|
|
24504
24914
|
const files = [];
|
|
24505
24915
|
for (const entry of entries) {
|
|
24506
|
-
const absolute =
|
|
24916
|
+
const absolute = path5.join(root, entry.name);
|
|
24507
24917
|
if (entry.isDirectory()) files.push(...await listFilesRecursively(absolute));
|
|
24508
24918
|
else if (entry.isFile()) files.push(absolute);
|
|
24509
24919
|
}
|
|
24510
24920
|
return files;
|
|
24511
24921
|
}
|
|
24512
24922
|
async function validateSkillFolder(folder, slug) {
|
|
24513
|
-
const skillMd = await readFile3(
|
|
24923
|
+
const skillMd = await readFile3(path5.join(folder, "SKILL.md"), "utf8");
|
|
24514
24924
|
const frontmatter = /^---\n([\s\S]+?)\n---/.exec(skillMd)?.[1] ?? "";
|
|
24515
24925
|
if (!frontmatter.includes(`name: ${slug}`) && !frontmatter.includes(`name: "${slug}"`)) {
|
|
24516
24926
|
throw new Error(`O campo name no frontmatter de SKILL.md tem de corresponder a ${slug}`);
|
|
@@ -24521,7 +24931,7 @@ async function validateSkillFolder(folder, slug) {
|
|
|
24521
24931
|
}
|
|
24522
24932
|
async function assertNoReservedMarkerAliases(skillFolder) {
|
|
24523
24933
|
const reserved = /* @__PURE__ */ new Set([".forge-version", ".forge-agents", ".forge-commands", WORK_PACK_LOCAL_STATE_FILENAME]);
|
|
24524
|
-
const entries = await
|
|
24934
|
+
const entries = await readdir3(skillFolder);
|
|
24525
24935
|
const marker = entries.find((entry) => reserved.has(entry.toLowerCase()));
|
|
24526
24936
|
if (marker) throw new Error(`O pacote de trabalho cont\xE9m o marcador Forge reservado ${marker}`);
|
|
24527
24937
|
}
|
|
@@ -24531,15 +24941,15 @@ async function writeJsonAtomic2(filePath, value) {
|
|
|
24531
24941
|
await writeTextAtomic(filePath, content);
|
|
24532
24942
|
}
|
|
24533
24943
|
async function writeTextAtomic(filePath, content) {
|
|
24534
|
-
const dir =
|
|
24944
|
+
const dir = path5.dirname(filePath);
|
|
24535
24945
|
await mkdir2(dir, { recursive: true });
|
|
24536
|
-
const tempPath =
|
|
24946
|
+
const tempPath = path5.join(dir, `.${path5.basename(filePath)}.${process.pid}.tmp`);
|
|
24537
24947
|
await writeFile3(tempPath, content);
|
|
24538
24948
|
await rename3(tempPath, filePath);
|
|
24539
24949
|
}
|
|
24540
24950
|
|
|
24541
24951
|
// packages/cli/src/workerPrompt.ts
|
|
24542
|
-
import { createHash as
|
|
24952
|
+
import { createHash as createHash4 } from "node:crypto";
|
|
24543
24953
|
var STOCK_OPENWORK_PROMPT_SHA256 = "b84527bf738ab37c726ccd43c3161df30fbddd5384aadbe7abf3cfeb3fced497";
|
|
24544
24954
|
var FORGE_WORKER_PROMPT = `\xC9s o assistente de trabalho do Forge no OpenWork. Ajudas a pessoa a concluir
|
|
24545
24955
|
tarefas com os ficheiros, fontes e ferramentas a que tem acesso. N\xE3o pressuponhas
|
|
@@ -24620,7 +25030,7 @@ function applySharedWorkerPrompt(config2) {
|
|
|
24620
25030
|
const agent = config2.agent.openwork;
|
|
24621
25031
|
if (!isRecord(agent) || agent.mode !== "primary" || typeof agent.prompt !== "string") return false;
|
|
24622
25032
|
if (agent.prompt === FORGE_WORKER_PROMPT) return true;
|
|
24623
|
-
const hash2 =
|
|
25033
|
+
const hash2 = createHash4("sha256").update(agent.prompt.replace(/\r\n/g, "\n").trim()).digest("hex");
|
|
24624
25034
|
if (hash2 !== STOCK_OPENWORK_PROMPT_SHA256) return false;
|
|
24625
25035
|
config2.agent = { ...config2.agent, openwork: { ...agent, prompt: FORGE_WORKER_PROMPT } };
|
|
24626
25036
|
return true;
|
|
@@ -24630,7 +25040,7 @@ function isRecord(value) {
|
|
|
24630
25040
|
}
|
|
24631
25041
|
|
|
24632
25042
|
// packages/cli/src/workPackSyncPlugin.ts
|
|
24633
|
-
var PLUGIN_VERSION = "0.1.
|
|
25043
|
+
var PLUGIN_VERSION = "0.1.17";
|
|
24634
25044
|
var STATUS_FILENAME = "work-pack-startup-status.json";
|
|
24635
25045
|
var activeSync = /* @__PURE__ */ new Map();
|
|
24636
25046
|
var ForgeWorkPackSyncServer = async (_input, options) => {
|
|
@@ -24641,8 +25051,48 @@ var ForgeWorkPackSyncServer = async (_input, options) => {
|
|
|
24641
25051
|
activeSync.set(forgeBaseUrl, sync);
|
|
24642
25052
|
}
|
|
24643
25053
|
const state = await sync;
|
|
25054
|
+
const legacyPath = path6.join(state.paths.pluginDir, FORGE_EVIDENCE_PLUGIN_FILENAME);
|
|
25055
|
+
const ownershipSymbol = /* @__PURE__ */ Symbol.for("minimal-forge.legacy-evidence-owners.v1");
|
|
25056
|
+
const shared = globalThis;
|
|
25057
|
+
const legacyOwners = shared[ownershipSymbol] ??= /* @__PURE__ */ new Set();
|
|
25058
|
+
const legacyOwnerKey = JSON.stringify([forgeBaseUrl, legacyPath]);
|
|
24644
25059
|
return {
|
|
25060
|
+
"tool.execute.after": async (input) => {
|
|
25061
|
+
if (input.tool !== "skill" || legacyOwners.has(legacyOwnerKey)) return;
|
|
25062
|
+
const slug = typeof input.args?.name === "string" ? input.args.name.trim().toLowerCase() : "";
|
|
25063
|
+
if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug)) return;
|
|
25064
|
+
try {
|
|
25065
|
+
await readFile4(path6.join(state.paths.skillsDir, slug, ".forge-version"), "utf8");
|
|
25066
|
+
} catch {
|
|
25067
|
+
return;
|
|
25068
|
+
}
|
|
25069
|
+
try {
|
|
25070
|
+
const { forgeApiKey } = await readWellKnownForgeCredentials(state.paths.opencodeAuthPath, forgeBaseUrl);
|
|
25071
|
+
const credentialId = createHash5("sha256").update(forgeApiKey).digest("hex");
|
|
25072
|
+
const reportUsage = skillUsageReporter(forgeBaseUrl, credentialId, (events) => fetch(`${forgeBaseUrl}/sync/evidence`, {
|
|
25073
|
+
method: "POST",
|
|
25074
|
+
redirect: "error",
|
|
25075
|
+
headers: { authorization: `Bearer ${forgeApiKey}`, "content-type": "application/json" },
|
|
25076
|
+
body: JSON.stringify({ events }),
|
|
25077
|
+
signal: AbortSignal.timeout(5e3)
|
|
25078
|
+
}));
|
|
25079
|
+
reportUsage(input.sessionID, input.callID, slug);
|
|
25080
|
+
} catch {
|
|
25081
|
+
console.error("[Forge evidence] Invocation identity unavailable; event not queued");
|
|
25082
|
+
}
|
|
25083
|
+
},
|
|
24645
25084
|
config: async (config2) => {
|
|
25085
|
+
const entries = Array.isArray(config2.plugin) ? config2.plugin : [];
|
|
25086
|
+
const registered = entries.some((entry) => {
|
|
25087
|
+
const name = Array.isArray(entry) ? entry[0] : entry;
|
|
25088
|
+
return name === legacyPath || name === pathToFileURL(legacyPath).href;
|
|
25089
|
+
});
|
|
25090
|
+
const legacy = registered ? await readFile4(legacyPath, "utf8").catch(() => "") : "";
|
|
25091
|
+
const oldLegacyRegistered = registered && legacy.startsWith(FORGE_PLUGIN_HEADER) && legacy.includes("work_pack_invocation") && !legacy.includes("minimal-forge.skill-usage.v1");
|
|
25092
|
+
if (oldLegacyRegistered) legacyOwners.add(legacyOwnerKey);
|
|
25093
|
+
if (oldLegacyRegistered) await writeFile4(legacyPath, renderEvidencePlugin()).catch(() => {
|
|
25094
|
+
console.error("[Forge evidence] Legacy hook upgrade failed; existing hook retained");
|
|
25095
|
+
});
|
|
24646
25096
|
await projectCurrentExtensions(config2, state);
|
|
24647
25097
|
if (state.forgeConfigVerified) applySharedWorkerPrompt(config2);
|
|
24648
25098
|
},
|
|
@@ -24761,17 +25211,17 @@ function parseForgeBaseUrl(options) {
|
|
|
24761
25211
|
async function managedProjectionNames(paths) {
|
|
24762
25212
|
const agents = /* @__PURE__ */ new Set();
|
|
24763
25213
|
const commands = /* @__PURE__ */ new Set();
|
|
24764
|
-
const entries = await
|
|
25214
|
+
const entries = await readdir4(paths.skillsDir, { withFileTypes: true }).catch((error45) => {
|
|
24765
25215
|
if (error45.code === "ENOENT") return [];
|
|
24766
25216
|
throw error45;
|
|
24767
25217
|
});
|
|
24768
25218
|
for (const entry of entries) {
|
|
24769
25219
|
if (!entry.isDirectory()) continue;
|
|
24770
|
-
const folder =
|
|
24771
|
-
const marker = await readFile4(
|
|
25220
|
+
const folder = path6.join(paths.skillsDir, entry.name);
|
|
25221
|
+
const marker = await readFile4(path6.join(folder, ".forge-version"), "utf8").catch(() => "");
|
|
24772
25222
|
if (!marker.trim()) continue;
|
|
24773
|
-
for (const name of await readProjectionRecord(
|
|
24774
|
-
for (const name of await readProjectionRecord(
|
|
25223
|
+
for (const name of await readProjectionRecord(path6.join(folder, ".forge-agents"))) agents.add(stripMarkdownExtension(name));
|
|
25224
|
+
for (const name of await readProjectionRecord(path6.join(folder, ".forge-commands"))) commands.add(stripMarkdownExtension(name));
|
|
24775
25225
|
}
|
|
24776
25226
|
return { agents, commands };
|
|
24777
25227
|
}
|
|
@@ -24787,10 +25237,10 @@ async function projectCurrentExtensions(config2, state) {
|
|
|
24787
25237
|
for (const name of state.before.agents) if (!state.after.agents.has(name)) delete agents[name];
|
|
24788
25238
|
for (const name of state.before.commands) if (!state.after.commands.has(name)) delete commands[name];
|
|
24789
25239
|
for (const name of state.after.agents) {
|
|
24790
|
-
agents[name] = await parseMarkdownConfig(
|
|
25240
|
+
agents[name] = await parseMarkdownConfig(path6.join(state.paths.agentsDir, `${name}.md`), "prompt");
|
|
24791
25241
|
}
|
|
24792
25242
|
for (const name of state.after.commands) {
|
|
24793
|
-
commands[name] = await parseMarkdownConfig(
|
|
25243
|
+
commands[name] = await parseMarkdownConfig(path6.join(state.paths.commandsDir, `${name}.md`), "template");
|
|
24794
25244
|
}
|
|
24795
25245
|
config2.agent = agents;
|
|
24796
25246
|
config2.command = commands;
|
|
@@ -24798,10 +25248,10 @@ async function projectCurrentExtensions(config2, state) {
|
|
|
24798
25248
|
async function parseMarkdownConfig(filePath, bodyField) {
|
|
24799
25249
|
const raw = await readFile4(filePath, "utf8");
|
|
24800
25250
|
const match = /^---\r?\n([\s\S]+?)\r?\n---\r?\n?([\s\S]*)$/.exec(raw);
|
|
24801
|
-
if (!match) throw new Error(`A extens\xE3o Forge ${
|
|
25251
|
+
if (!match) throw new Error(`A extens\xE3o Forge ${path6.basename(filePath)} n\xE3o tem frontmatter v\xE1lido`);
|
|
24802
25252
|
const data = (0, import_yaml.parse)(match[1]);
|
|
24803
25253
|
if (!data || typeof data !== "object" || Array.isArray(data)) {
|
|
24804
|
-
throw new Error(`A extens\xE3o Forge ${
|
|
25254
|
+
throw new Error(`A extens\xE3o Forge ${path6.basename(filePath)} n\xE3o tem frontmatter v\xE1lido`);
|
|
24805
25255
|
}
|
|
24806
25256
|
const config2 = { ...data, [bodyField]: match[2].trim() };
|
|
24807
25257
|
if (bodyField === "prompt" && typeof config2.permission === "string" && ["allow", "ask", "deny"].includes(config2.permission)) {
|
|
@@ -24817,8 +25267,8 @@ function stripMarkdownExtension(filename) {
|
|
|
24817
25267
|
}
|
|
24818
25268
|
async function writeStatus(paths, value) {
|
|
24819
25269
|
await mkdir3(paths.forgeDir, { recursive: true });
|
|
24820
|
-
const target =
|
|
24821
|
-
const temporary =
|
|
25270
|
+
const target = path6.join(paths.forgeDir, STATUS_FILENAME);
|
|
25271
|
+
const temporary = path6.join(paths.forgeDir, `.${STATUS_FILENAME}.${process.pid}.tmp`);
|
|
24822
25272
|
await writeFile4(temporary, `${JSON.stringify(value, null, 2)}
|
|
24823
25273
|
`, { mode: 384 });
|
|
24824
25274
|
await rename4(temporary, target);
|