minimal-forge-work-pack-sync 0.1.31 → 0.1.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +112 -83
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -7551,7 +7551,7 @@ var DEFAULT_DEBUG_TRACE_LIMITS = {
7551
7551
  };
7552
7552
 
7553
7553
  // packages/shared/src/contracts/settings.ts
7554
- var WORK_PACK_SYNC_PLUGIN_VERSION = "0.1.31";
7554
+ var WORK_PACK_SYNC_PLUGIN_VERSION = "0.1.33";
7555
7555
  var WORK_PACK_SYNC_PLUGIN_PACKAGE = `minimal-forge-work-pack-sync@${WORK_PACK_SYNC_PLUGIN_VERSION}`;
7556
7556
  var WORK_PACK_SYNC_PLUGIN_FILENAME = `minimal-forge-work-pack-sync-${WORK_PACK_SYNC_PLUGIN_VERSION}.tgz`;
7557
7557
  var FIRECRAWL_KEYLESS_MCP_NAME = "firecrawl";
@@ -7925,7 +7925,7 @@ async function replaceFile(filename, contents) {
7925
7925
 
7926
7926
  // packages/cli/src/workPackSyncPlugin.ts
7927
7927
  var import_yaml = __toESM(require_dist(), 1);
7928
- import { link, mkdir as mkdir3, mkdtemp as mkdtemp2, readdir as readdir4, readFile as readFile4, realpath, rename as rename4, stat, writeFile as writeFile4 } from "node:fs/promises";
7928
+ import { link, mkdir as mkdir3, mkdtemp as mkdtemp2, readdir as readdir4, readFile as readFile4, realpath, rename as rename4, rm as rm2, rmdir, stat, unlink, writeFile as writeFile4 } from "node:fs/promises";
7929
7929
  import path6 from "node:path";
7930
7930
 
7931
7931
  // node_modules/@opencode-ai/plugin/node_modules/zod/v4/classic/external.js
@@ -25168,7 +25168,7 @@ function isRecord(value) {
25168
25168
  }
25169
25169
 
25170
25170
  // packages/cli/src/workPackSyncPlugin.ts
25171
- var PLUGIN_VERSION = "0.1.31";
25171
+ var PLUGIN_VERSION = "0.1.33";
25172
25172
  var FORGE_DECISION_TIMEOUT_MS = 11e4;
25173
25173
  var STATUS_FILENAME = "work-pack-startup-status.json";
25174
25174
  var activeSync = /* @__PURE__ */ new Map();
@@ -25233,7 +25233,9 @@ var ForgeWorkPackSyncServer = async (_input, options) => {
25233
25233
  }
25234
25234
  };
25235
25235
  };
25236
- function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths) {
25236
+ var ForgeDecisionRejectedError = class extends Error {
25237
+ };
25238
+ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseDirectory) {
25237
25239
  const question = tool.schema.discriminatedUnion("type", [
25238
25240
  tool.schema.object({
25239
25241
  type: tool.schema.literal("noul"),
@@ -25270,11 +25272,11 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths) {
25270
25272
  let requestBody;
25271
25273
  if (fromFile) {
25272
25274
  const file2 = await fileInsideWorkspace(context.directory, args.request_file);
25273
- const raw2 = await readFile4(file2, "utf8");
25274
- if (Buffer.byteLength(raw2) > 512 * 1024) throw new Error("O ficheiro de pedido excede 512 KiB.");
25275
+ const raw = await readFile4(file2, "utf8");
25276
+ if (Buffer.byteLength(raw) > 512 * 1024) throw new Error("O ficheiro de pedido excede 512 KiB.");
25275
25277
  let parsed;
25276
25278
  try {
25277
- parsed = JSON.parse(raw2);
25279
+ parsed = JSON.parse(raw);
25278
25280
  } catch {
25279
25281
  throw new Error("O ficheiro de pedido n\xE3o cont\xE9m JSON v\xE1lido.");
25280
25282
  }
@@ -25289,40 +25291,48 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths) {
25289
25291
  if (args.state === void 0 || !args.questions || Object.keys(args.questions).length === 0) throw new Error("Indica state e questions.");
25290
25292
  requestBody = { state: args.state, questions: args.questions };
25291
25293
  }
25292
- const responseDir = await mkdtemp2(path6.join(context.directory, ".forge-decision-"));
25294
+ const responseDir = await mkdtemp2(path6.join(responseDirectory ?? context.directory, ".forge-decision-"));
25293
25295
  const responseFile = path6.join(responseDir, "response.json");
25294
- const credentials = await readWellKnownForgeCredentials(paths.opencodeAuthPath, forgeBaseUrl);
25295
- const response = await fetch(`${decisionBaseUrl}/v1/decisions`, {
25296
- method: "POST",
25297
- redirect: "error",
25298
- headers: {
25299
- authorization: `Bearer ${credentials.forgeApiKey}`,
25300
- "content-type": "application/json"
25301
- },
25302
- body: JSON.stringify(requestBody),
25303
- signal: AbortSignal.any([context.abort, AbortSignal.timeout(FORGE_DECISION_TIMEOUT_MS)])
25304
- });
25305
- const raw = await response.text();
25306
- let body;
25307
25296
  try {
25308
- body = JSON.parse(raw);
25309
- } catch {
25310
- }
25311
- if (response.ok && body && typeof body === "object" && body.answers && typeof body.answers === "object") {
25297
+ const credentials = await readWellKnownForgeCredentials(paths.opencodeAuthPath, forgeBaseUrl);
25298
+ const response = await fetch(`${decisionBaseUrl}/v1/decisions`, {
25299
+ method: "POST",
25300
+ redirect: "error",
25301
+ headers: {
25302
+ authorization: `Bearer ${credentials.forgeApiKey}`,
25303
+ "content-type": "application/json"
25304
+ },
25305
+ body: JSON.stringify(requestBody),
25306
+ signal: AbortSignal.any([context.abort, AbortSignal.timeout(FORGE_DECISION_TIMEOUT_MS)])
25307
+ });
25308
+ const raw = await response.text();
25309
+ let body;
25312
25310
  try {
25313
- await writeFile4(responseFile, raw, { flag: "wx", mode: 384 });
25314
- return JSON.stringify({ ...body, response_file: responseFile }, null, 2);
25311
+ body = JSON.parse(raw);
25315
25312
  } catch {
25316
- return JSON.stringify({
25317
- ...body,
25318
- response_file: null,
25319
- persistence_error: "A decis\xE3o foi conclu\xEDda, mas n\xE3o foi poss\xEDvel guardar o ficheiro. Recuperar esta resposta do hist\xF3rico da ferramenta; n\xE3o repetir a chamada ao Jev."
25320
- }, null, 2);
25321
25313
  }
25314
+ if (response.ok && body && typeof body === "object" && body.answers && typeof body.answers === "object") {
25315
+ try {
25316
+ await writeFile4(responseFile, raw, { flag: "wx", mode: 384 });
25317
+ return JSON.stringify({ ...body, response_file: responseFile }, null, 2);
25318
+ } catch {
25319
+ return JSON.stringify({
25320
+ ...body,
25321
+ response_file: null,
25322
+ persistence_error: "A decis\xE3o foi conclu\xEDda, mas n\xE3o foi poss\xEDvel guardar o ficheiro. Recuperar esta resposta do hist\xF3rico da ferramenta; n\xE3o repetir a chamada ao Jev."
25323
+ }, null, 2);
25324
+ }
25325
+ }
25326
+ const nested = body?.error && typeof body.error === "object" && !Array.isArray(body.error) ? body.error.message : void 0;
25327
+ const safeError = typeof nested === "string" && nested.length <= 300 ? nested.replace(/forge_[A-Za-z0-9_-]+/g, "<credencial oculta>") : `O Forge n\xE3o concluiu a decis\xE3o (HTTP ${response.status})`;
25328
+ const code = body?.error && typeof body.error === "object" ? body.error.code : void 0;
25329
+ if (response.status === 401 || response.status === 403 || ["rate_limit_exceeded", "payload_too_large", "invalid_content_type", "invalid_json", "invalid_decision_request", "openrouter_key_missing"].includes(String(code))) {
25330
+ throw new ForgeDecisionRejectedError(safeError);
25331
+ }
25332
+ throw new Error(safeError);
25333
+ } finally {
25334
+ await rmdir(responseDir).catch(() => void 0);
25322
25335
  }
25323
- const nested = body?.error && typeof body.error === "object" && !Array.isArray(body.error) ? body.error.message : void 0;
25324
- const safeError = typeof nested === "string" && nested.length <= 300 ? nested.replace(/forge_[A-Za-z0-9_-]+/g, "<credencial oculta>") : `O Forge n\xE3o concluiu a decis\xE3o (HTTP ${response.status})`;
25325
- throw new Error(safeError);
25326
25336
  }
25327
25337
  });
25328
25338
  }
@@ -25351,7 +25361,6 @@ function canonicalJson(value) {
25351
25361
  return JSON.stringify(value);
25352
25362
  }
25353
25363
  function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
25354
- const decide = createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths);
25355
25364
  return tool({
25356
25365
  description: "Executa em c\xF3digo os lotes Jev pendentes de um plano preparado. Guarda cada resposta crua e nunca repete lotes com resposta ou aceita\xE7\xE3o j\xE1 guardada. Requer a aprova\xE7\xE3o habitual para as chamadas pagas antes de usar.",
25357
25366
  args: { plan_file: tool.schema.string().describe("Caminho de jev/plan.json dentro do workspace") },
@@ -25366,56 +25375,76 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
25366
25375
  await mkdir3(responsePath, { recursive: true });
25367
25376
  const responseDir = await fileInsideWorkspace(context.directory, responsePath);
25368
25377
  if (path6.dirname(responseDir) !== path6.join(runDir, "jev")) throw new Error("A pasta de respostas tem de pertencer ao run Jev.");
25378
+ const decide = createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseDir);
25379
+ const lockDir = path6.join(runDir, "jev", ".decide-run.lock");
25380
+ try {
25381
+ await mkdir3(lockDir);
25382
+ } catch (error45) {
25383
+ if (error45.code !== "EEXIST") throw error45;
25384
+ throw new Error("Este plano j\xE1 est\xE1 em execu\xE7\xE3o ou tem uma chamada interrompida. Verificar as respostas e recuperar o lote antes de remover jev/.decide-run.lock; n\xE3o repetir chamadas incertas.");
25385
+ }
25386
+ let releaseLock = true;
25369
25387
  let saved = 0;
25370
25388
  let skipped = 0;
25371
- for (const batch of batches) {
25372
- const batchId = batch.batch_id;
25373
- if (typeof batchId !== "string" || !/^batch-[0-9]{4}-[A-Za-z0-9._-]+$/.test(batchId) || typeof batch.request_file !== "string" || typeof batch.request_fingerprint !== "string") {
25374
- throw new Error("O plano Jev cont\xE9m um lote inv\xE1lido.");
25375
- }
25376
- const acceptedFile = path6.join(runDir, "jev", "accepted", `${batchId}.json`);
25377
- const responseFile = path6.join(responseDir, `${batchId}.response.json`);
25378
- if (await fileExists(acceptedFile) || await fileExists(responseFile)) {
25379
- skipped++;
25380
- continue;
25381
- }
25382
- const requestFile = await fileInsideWorkspace(context.directory, batch.request_file);
25383
- if (path6.dirname(requestFile) !== path6.join(runDir, "jev", "requests")) throw new Error(`${batchId}: pedido fora do run.`);
25384
- const request = JSON.parse(await readFile4(requestFile, "utf8"));
25385
- const fingerprint = createHash5("sha256").update(canonicalJson(request)).digest("hex");
25386
- if (fingerprint !== batch.request_fingerprint) throw new Error(`${batchId}: fingerprint do pedido n\xE3o corresponde ao plano.`);
25387
- let result;
25388
- try {
25389
- const output = await decide.execute({ request_file: requestFile }, context);
25390
- result = JSON.parse(typeof output === "string" ? output : output.output);
25391
- } catch (error45) {
25392
- return JSON.stringify({ verified: false, saved, skipped, stopped_at: batchId, error: error45 instanceof Error ? error45.message : "Falha na chamada Jev." });
25393
- }
25394
- if (typeof result.response_file !== "string") {
25395
- return JSON.stringify({ verified: false, saved, skipped, stopped_at: batchId, recovery_response: result, error: result.persistence_error ?? "Resposta Jev sem ficheiro guardado; recuperar do hist\xF3rico, sem repetir." });
25396
- }
25397
- try {
25398
- await link(result.response_file, responseFile);
25399
- } catch {
25400
- return JSON.stringify({
25401
- verified: false,
25402
- saved,
25403
- skipped,
25404
- stopped_at: batchId,
25405
- recovery_file: result.response_file,
25406
- error: "Resposta conclu\xEDda mas n\xE3o copiada para o run; recuperar o ficheiro indicado, sem repetir a chamada."
25407
- });
25408
- }
25409
- saved++;
25389
+ try {
25390
+ await writeFile4(path6.join(lockDir, "owner.json"), JSON.stringify({ pid: process.pid, started_at: (/* @__PURE__ */ new Date()).toISOString() }), { mode: 384 });
25391
+ for (const batch of batches) {
25392
+ context.abort.throwIfAborted();
25393
+ const batchId = batch.batch_id;
25394
+ if (typeof batchId !== "string" || !/^batch-[0-9]{4}-[A-Za-z0-9._-]+$/.test(batchId) || typeof batch.request_file !== "string" || typeof batch.request_fingerprint !== "string") {
25395
+ throw new Error("O plano Jev cont\xE9m um lote inv\xE1lido.");
25396
+ }
25397
+ const acceptedFile = path6.join(runDir, "jev", "accepted", `${batchId}.json`);
25398
+ const responseFile = path6.join(responseDir, `${batchId}.response.json`);
25399
+ const requestFile = await fileInsideWorkspace(context.directory, batch.request_file);
25400
+ if (path6.dirname(requestFile) !== path6.join(runDir, "jev", "requests")) throw new Error(`${batchId}: pedido fora do run.`);
25401
+ const request = JSON.parse(await readFile4(requestFile, "utf8"));
25402
+ const fingerprint = createHash5("sha256").update(canonicalJson(request)).digest("hex");
25403
+ if (fingerprint !== batch.request_fingerprint) throw new Error(`${batchId}: fingerprint do pedido n\xE3o corresponde ao plano.`);
25404
+ if (await fileExists(acceptedFile) || await fileExists(responseFile)) {
25405
+ skipped++;
25406
+ continue;
25407
+ }
25408
+ let result;
25409
+ await writeFile4(path6.join(lockDir, "owner.json"), JSON.stringify({ pid: process.pid, batch_id: batchId, request_fingerprint: fingerprint, started_at: (/* @__PURE__ */ new Date()).toISOString() }), { mode: 384 });
25410
+ try {
25411
+ const output = await decide.execute({ request_file: requestFile }, context);
25412
+ result = JSON.parse(typeof output === "string" ? output : output.output);
25413
+ } catch (error45) {
25414
+ releaseLock = error45 instanceof ForgeDecisionRejectedError;
25415
+ return JSON.stringify({ verified: false, saved, skipped, stopped_at: batchId, recovery_lock: releaseLock ? void 0 : lockDir, error: error45 instanceof Error ? error45.message : "Falha na chamada Jev." });
25416
+ }
25417
+ if (typeof result.response_file !== "string") {
25418
+ releaseLock = false;
25419
+ return JSON.stringify({ verified: false, saved, skipped, stopped_at: batchId, recovery_response: result, error: result.persistence_error ?? "Resposta Jev sem ficheiro guardado; recuperar do hist\xF3rico, sem repetir." });
25420
+ }
25421
+ try {
25422
+ await link(result.response_file, responseFile);
25423
+ } catch {
25424
+ releaseLock = false;
25425
+ return JSON.stringify({
25426
+ verified: false,
25427
+ saved,
25428
+ skipped,
25429
+ stopped_at: batchId,
25430
+ recovery_file: result.response_file,
25431
+ error: "Resposta conclu\xEDda mas n\xE3o copiada para o run; recuperar o ficheiro indicado, sem repetir a chamada."
25432
+ });
25433
+ }
25434
+ await unlink(result.response_file).then(() => rmdir(path6.dirname(result.response_file))).catch(() => void 0);
25435
+ saved++;
25436
+ }
25437
+ return JSON.stringify({
25438
+ verified: true,
25439
+ batch_count: batches.length,
25440
+ saved,
25441
+ skipped,
25442
+ response_dir: responseDir,
25443
+ next_step: "Executar jev-accept sobre as respostas guardadas ainda n\xE3o aceites; depois jev-validate e jev-merge."
25444
+ });
25445
+ } finally {
25446
+ if (releaseLock) await rm2(lockDir, { recursive: true });
25410
25447
  }
25411
- return JSON.stringify({
25412
- verified: true,
25413
- batch_count: batches.length,
25414
- saved,
25415
- skipped,
25416
- response_dir: responseDir,
25417
- next_step: "Executar jev-accept sobre as respostas guardadas ainda n\xE3o aceites; depois jev-validate e jev-merge."
25418
- });
25419
25448
  }
25420
25449
  });
25421
25450
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "minimal-forge-work-pack-sync",
3
- "version": "0.1.31",
3
+ "version": "0.1.33",
4
4
  "description": "Minimal Forge Work Pack startup synchronization for OpenCode and OpenWork.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {