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

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 +168 -44
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -664,36 +664,38 @@ var require_Alias = __commonJS({
664
664
  if (node.anchor === this.source)
665
665
  found = node;
666
666
  }
667
+ if (found && ctx) {
668
+ const { anchors: anchors2, doc: doc2, maxAliasCount } = ctx;
669
+ let data = anchors2.get(found);
670
+ if (!data) {
671
+ toJS.toJS(found, null, ctx);
672
+ data = anchors2.get(found);
673
+ }
674
+ if (data?.res === void 0) {
675
+ const msg = "This should not happen: Alias anchor was not resolved?";
676
+ throw new ReferenceError(msg);
677
+ }
678
+ if (maxAliasCount >= 0) {
679
+ data.count += 1;
680
+ if (data.aliasCount === 0)
681
+ data.aliasCount = getAliasCount(doc2, found, anchors2);
682
+ if (data.count * data.aliasCount > maxAliasCount) {
683
+ const msg = "Excessive alias count indicates a resource exhaustion attack";
684
+ throw new ReferenceError(msg);
685
+ }
686
+ }
687
+ }
667
688
  return found;
668
689
  }
669
690
  toJSON(_arg, ctx) {
670
691
  if (!ctx)
671
692
  return { source: this.source };
672
- const { anchors: anchors2, doc, maxAliasCount } = ctx;
673
- const source = this.resolve(doc, ctx);
693
+ const source = this.resolve(ctx.doc, ctx);
674
694
  if (!source) {
675
695
  const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
676
696
  throw new ReferenceError(msg);
677
697
  }
678
- let data = anchors2.get(source);
679
- if (!data) {
680
- toJS.toJS(source, null, ctx);
681
- data = anchors2.get(source);
682
- }
683
- if (data?.res === void 0) {
684
- const msg = "This should not happen: Alias anchor was not resolved?";
685
- throw new ReferenceError(msg);
686
- }
687
- if (maxAliasCount >= 0) {
688
- data.count += 1;
689
- if (data.aliasCount === 0)
690
- data.aliasCount = getAliasCount(doc, source, anchors2);
691
- if (data.count * data.aliasCount > maxAliasCount) {
692
- const msg = "Excessive alias count indicates a resource exhaustion attack";
693
- throw new ReferenceError(msg);
694
- }
695
- }
696
- return data.res;
698
+ return ctx.anchors.get(source).res;
697
699
  }
698
700
  toString(ctx, _onComment, _onChompKeep) {
699
701
  const src = `*${this.source}`;
@@ -4695,37 +4697,38 @@ var require_resolve_flow_scalar = __commonJS({
4695
4697
  }
4696
4698
  if (badChar)
4697
4699
  onError(0, "BAD_SCALAR_START", `Plain value cannot start with ${badChar}`);
4698
- return foldLines(source);
4700
+ return unfoldLines(source);
4699
4701
  }
4700
4702
  function singleQuotedValue(source, onError) {
4701
4703
  if (source[source.length - 1] !== "'" || source.length === 1)
4702
4704
  onError(source.length, "MISSING_CHAR", "Missing closing 'quote");
4703
- return foldLines(source.slice(1, -1)).replace(/''/g, "'");
4705
+ return unfoldLines(source.slice(1, -1)).replace(/''/g, "'");
4704
4706
  }
4705
- function foldLines(source) {
4706
- let first, line;
4707
+ function unfoldLines(source) {
4708
+ const line = /(.*?)\r?\n/sy;
4709
+ let match = line.exec(source);
4710
+ if (!match)
4711
+ return source;
4712
+ let trimEnd, trimBoth;
4707
4713
  try {
4708
- first = new RegExp("(.*?)(?<![ ])[ ]*\r?\n", "sy");
4709
- line = new RegExp("[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?\n", "sy");
4714
+ trimEnd = new RegExp("(?<![ ])[ ]+$");
4715
+ trimBoth = new RegExp("^[ ]+|(?<![ ])[ ]+$", "g");
4710
4716
  } catch {
4711
- first = /(.*?)[ \t]*\r?\n/sy;
4712
- line = /[ \t]*(.*?)[ \t]*\r?\n/sy;
4717
+ trimEnd = /[ \t]+$/;
4718
+ trimBoth = /^[ \t]+|[ \t]+$/g;
4713
4719
  }
4714
- let match = first.exec(source);
4715
- if (!match)
4716
- return source;
4717
- let res = match[1];
4720
+ let res = match[1].replace(trimEnd, "");
4718
4721
  let sep = " ";
4719
- let pos = first.lastIndex;
4720
- line.lastIndex = pos;
4722
+ let pos = line.lastIndex;
4721
4723
  while (match = line.exec(source)) {
4722
- if (match[1] === "") {
4724
+ const lm = match[1].replace(trimBoth, "");
4725
+ if (lm === "") {
4723
4726
  if (sep === "\n")
4724
4727
  res += sep;
4725
4728
  else
4726
4729
  sep = "\n";
4727
4730
  } else {
4728
- res += sep + match[1];
4731
+ res += sep + lm;
4729
4732
  sep = " ";
4730
4733
  }
4731
4734
  pos = line.lastIndex;
@@ -7548,7 +7551,7 @@ var DEFAULT_DEBUG_TRACE_LIMITS = {
7548
7551
  };
7549
7552
 
7550
7553
  // packages/shared/src/contracts/settings.ts
7551
- var WORK_PACK_SYNC_PLUGIN_VERSION = "0.1.28";
7554
+ var WORK_PACK_SYNC_PLUGIN_VERSION = "0.1.31";
7552
7555
  var WORK_PACK_SYNC_PLUGIN_PACKAGE = `minimal-forge-work-pack-sync@${WORK_PACK_SYNC_PLUGIN_VERSION}`;
7553
7556
  var WORK_PACK_SYNC_PLUGIN_FILENAME = `minimal-forge-work-pack-sync-${WORK_PACK_SYNC_PLUGIN_VERSION}.tgz`;
7554
7557
  var FIRECRAWL_KEYLESS_MCP_NAME = "firecrawl";
@@ -7922,7 +7925,7 @@ async function replaceFile(filename, contents) {
7922
7925
 
7923
7926
  // packages/cli/src/workPackSyncPlugin.ts
7924
7927
  var import_yaml = __toESM(require_dist(), 1);
7925
- import { mkdir as mkdir3, mkdtemp as mkdtemp2, readdir as readdir4, readFile as readFile4, rename as rename4, 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, stat, writeFile as writeFile4 } from "node:fs/promises";
7926
7929
  import path6 from "node:path";
7927
7930
 
7928
7931
  // node_modules/@opencode-ai/plugin/node_modules/zod/v4/classic/external.js
@@ -25165,7 +25168,7 @@ function isRecord(value) {
25165
25168
  }
25166
25169
 
25167
25170
  // packages/cli/src/workPackSyncPlugin.ts
25168
- var PLUGIN_VERSION = "0.1.28";
25171
+ var PLUGIN_VERSION = "0.1.31";
25169
25172
  var FORGE_DECISION_TIMEOUT_MS = 11e4;
25170
25173
  var STATUS_FILENAME = "work-pack-startup-status.json";
25171
25174
  var activeSync = /* @__PURE__ */ new Map();
@@ -25223,6 +25226,7 @@ var ForgeWorkPackSyncServer = async (_input, options) => {
25223
25226
  if (state.forgeConfigVerified) applySharedWorkerPrompt(config2);
25224
25227
  },
25225
25228
  tool: {
25229
+ forge_decide_run: createForgeDecisionRunTool(forgeBaseUrl, state.decisionBaseUrl, state.paths),
25226
25230
  forge_decide: createForgeDecisionTool(forgeBaseUrl, state.decisionBaseUrl, state.paths),
25227
25231
  forge_generate_codebook: createForgeCodebookTool(forgeBaseUrl, state.decisionBaseUrl, state.paths),
25228
25232
  forge_feedback: createForgeFeedbackTool(forgeBaseUrl, state.paths)
@@ -25248,16 +25252,43 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths) {
25248
25252
  })
25249
25253
  ]);
25250
25254
  return tool({
25251
- description: "Pede ao Jev uma ou mais decis\xF5es estruturadas sobre o mesmo estado. Usa este recurso para classifica\xE7\xE3o, escolha ou pontua\xE7\xE3o; n\xE3o para gerar texto livre. Guarda a resposta integral num ficheiro local e devolve response_file; copiar esse ficheiro, sem transcrever o JSON.",
25255
+ description: "Pede ao Jev decis\xF5es estruturadas. Para um pedido preparado, passa request_file; a resposta crua fica guardada em response_file.",
25252
25256
  args: {
25257
+ request_file: tool.schema.string().optional().describe("Ficheiro JSON de pedido dentro do workspace"),
25253
25258
  state: tool.schema.union([
25254
25259
  tool.schema.string(),
25255
25260
  tool.schema.record(tool.schema.string(), tool.schema.any()),
25256
25261
  tool.schema.array(tool.schema.any())
25257
- ]).describe("Texto, objeto ou lista com toda a evid\xEAncia necess\xE1ria para decidir"),
25258
- questions: tool.schema.record(tool.schema.string(), question).describe("Perguntas identificadas por uma chave est\xE1vel")
25262
+ ]).optional().describe("Para chamadas diretas: evid\xEAncia necess\xE1ria para decidir"),
25263
+ questions: tool.schema.record(tool.schema.string(), question).optional().describe("Para chamadas diretas: perguntas identificadas por uma chave est\xE1vel")
25259
25264
  },
25260
25265
  async execute(args, context) {
25266
+ const fromFile = typeof args.request_file === "string" && args.request_file.trim().length > 0;
25267
+ if (fromFile === (args.state !== void 0 || args.questions !== void 0)) {
25268
+ throw new Error("Indica request_file ou state e questions, mas n\xE3o ambos.");
25269
+ }
25270
+ let requestBody;
25271
+ if (fromFile) {
25272
+ 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
+ let parsed;
25276
+ try {
25277
+ parsed = JSON.parse(raw2);
25278
+ } catch {
25279
+ throw new Error("O ficheiro de pedido n\xE3o cont\xE9m JSON v\xE1lido.");
25280
+ }
25281
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("O pedido n\xE3o \xE9 um objeto JSON.");
25282
+ const record2 = parsed;
25283
+ if (record2.model !== void 0 && record2.model !== "typesafe/jev-1.13") throw new Error("O modelo do pedido n\xE3o corresponde ao Jev configurado.");
25284
+ if (record2.state === void 0 || !record2.questions || typeof record2.questions !== "object" || Array.isArray(record2.questions) || Object.keys(record2.questions).length === 0) {
25285
+ throw new Error("O pedido deve conter state e questions.");
25286
+ }
25287
+ requestBody = { state: record2.state, questions: record2.questions };
25288
+ } else {
25289
+ if (args.state === void 0 || !args.questions || Object.keys(args.questions).length === 0) throw new Error("Indica state e questions.");
25290
+ requestBody = { state: args.state, questions: args.questions };
25291
+ }
25261
25292
  const responseDir = await mkdtemp2(path6.join(context.directory, ".forge-decision-"));
25262
25293
  const responseFile = path6.join(responseDir, "response.json");
25263
25294
  const credentials = await readWellKnownForgeCredentials(paths.opencodeAuthPath, forgeBaseUrl);
@@ -25268,7 +25299,7 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths) {
25268
25299
  authorization: `Bearer ${credentials.forgeApiKey}`,
25269
25300
  "content-type": "application/json"
25270
25301
  },
25271
- body: JSON.stringify({ state: args.state, questions: args.questions }),
25302
+ body: JSON.stringify(requestBody),
25272
25303
  signal: AbortSignal.any([context.abort, AbortSignal.timeout(FORGE_DECISION_TIMEOUT_MS)])
25273
25304
  });
25274
25305
  const raw = await response.text();
@@ -25295,6 +25326,99 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths) {
25295
25326
  }
25296
25327
  });
25297
25328
  }
25329
+ async function fileInsideWorkspace(directory, candidate) {
25330
+ const workspace = await realpath(directory);
25331
+ const file2 = await realpath(path6.resolve(workspace, candidate));
25332
+ const relative = path6.relative(workspace, file2);
25333
+ if (!relative || (relative === ".." || relative.startsWith(`..${path6.sep}`)) || path6.isAbsolute(relative)) throw new Error("O ficheiro tem de estar dentro do workspace.");
25334
+ return file2;
25335
+ }
25336
+ async function fileExists(candidate) {
25337
+ try {
25338
+ await stat(candidate);
25339
+ return true;
25340
+ } catch (error45) {
25341
+ if (error45.code === "ENOENT") return false;
25342
+ throw error45;
25343
+ }
25344
+ }
25345
+ function canonicalJson(value) {
25346
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
25347
+ if (value && typeof value === "object") {
25348
+ const record2 = value;
25349
+ return `{${Object.keys(record2).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(record2[key])}`).join(",")}}`;
25350
+ }
25351
+ return JSON.stringify(value);
25352
+ }
25353
+ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
25354
+ const decide = createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths);
25355
+ return tool({
25356
+ 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
+ args: { plan_file: tool.schema.string().describe("Caminho de jev/plan.json dentro do workspace") },
25358
+ async execute(args, context) {
25359
+ const planFile = await fileInsideWorkspace(context.directory, args.plan_file);
25360
+ if (path6.basename(planFile) !== "plan.json" || path6.basename(path6.dirname(planFile)) !== "jev") throw new Error("Indica o ficheiro jev/plan.json.");
25361
+ const runDir = path6.dirname(path6.dirname(planFile));
25362
+ const plan = JSON.parse(await readFile4(planFile, "utf8"));
25363
+ if (plan.engine !== "jev-batch" || plan.model !== "typesafe/jev-1.13" || !Array.isArray(plan.batches)) throw new Error("O plano Jev \xE9 inv\xE1lido.");
25364
+ const batches = plan.batches;
25365
+ const responsePath = path6.join(runDir, "jev", "responses");
25366
+ await mkdir3(responsePath, { recursive: true });
25367
+ const responseDir = await fileInsideWorkspace(context.directory, responsePath);
25368
+ if (path6.dirname(responseDir) !== path6.join(runDir, "jev")) throw new Error("A pasta de respostas tem de pertencer ao run Jev.");
25369
+ let saved = 0;
25370
+ 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++;
25410
+ }
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
+ }
25420
+ });
25421
+ }
25298
25422
  function createForgeCodebookTool(forgeBaseUrl, gatewayBaseUrl, paths) {
25299
25423
  return tool({
25300
25424
  description: "Gera um rascunho de codebook em portugu\xEAs europeu a partir de uma pergunta e das respostas. Apresentar para aprova\xE7\xE3o humana antes de codificar; n\xE3o aplica c\xF3digos nem altera ficheiros.",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "minimal-forge-work-pack-sync",
3
- "version": "0.1.28",
3
+ "version": "0.1.31",
4
4
  "description": "Minimal Forge Work Pack startup synchronization for OpenCode and OpenWork.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {