minimal-forge-work-pack-sync 0.1.43 → 0.1.45

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 CHANGED
@@ -7607,7 +7607,7 @@ var DEFAULT_DEBUG_TRACE_LIMITS = {
7607
7607
  // packages/shared/src/contracts/settings.ts
7608
7608
  var DOCUMENT_READER_AGENT = "document-reader";
7609
7609
  var OPENROUTER_ALIAS_PROVIDER_NAME = "OpenRouter (via Forge)";
7610
- var WORK_PACK_SYNC_PLUGIN_VERSION = "0.1.43";
7610
+ var WORK_PACK_SYNC_PLUGIN_VERSION = "0.1.45";
7611
7611
  var WORK_PACK_SYNC_PLUGIN_PACKAGE = `minimal-forge-work-pack-sync@${WORK_PACK_SYNC_PLUGIN_VERSION}`;
7612
7612
  var WORK_PACK_SYNC_PLUGIN_FILENAME = `minimal-forge-work-pack-sync-${WORK_PACK_SYNC_PLUGIN_VERSION}.tgz`;
7613
7613
  var FIRECRAWL_KEYLESS_MCP_NAME = "firecrawl";
@@ -7662,7 +7662,7 @@ function mergeWorkerOpenCodeConfig(existing, manifest, forgeBaseUrl, forgeApiKey
7662
7662
  });
7663
7663
  if (options.automaticWorkPackSync) {
7664
7664
  plugins.push([
7665
- WORK_PACK_SYNC_PLUGIN_PACKAGE,
7665
+ `minimal-forge-work-pack-sync@${targetWorkPackSyncPluginVersion(manifest, existing)}`,
7666
7666
  { forgeBaseUrl: forgeBaseUrl.replace(/\/$/, ""), ...options.localConfig ? { localConfig: true } : {} }
7667
7667
  ]);
7668
7668
  }
@@ -7688,6 +7688,25 @@ function mergeWorkerOpenCodeConfig(existing, manifest, forgeBaseUrl, forgeApiKey
7688
7688
  ...plugins.length > 0 ? { plugin: plugins } : {}
7689
7689
  };
7690
7690
  }
7691
+ function isWorkPackSyncPluginVersion(value) {
7692
+ return typeof value === "string" && value.length <= 64 && /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(value);
7693
+ }
7694
+ function configuredWorkPackSyncPluginVersion(config2) {
7695
+ for (const entry of Array.isArray(config2.plugin) ? config2.plugin : []) {
7696
+ const name = Array.isArray(entry) ? entry[0] : entry;
7697
+ if (typeof name !== "string" || !name.startsWith("minimal-forge-work-pack-sync@")) continue;
7698
+ const version2 = name.slice("minimal-forge-work-pack-sync@".length);
7699
+ if (isWorkPackSyncPluginVersion(version2)) return version2;
7700
+ }
7701
+ return void 0;
7702
+ }
7703
+ function targetWorkPackSyncPluginVersion(manifest, existing) {
7704
+ if (manifest.workPackSyncPluginVersion !== void 0) {
7705
+ if (!isWorkPackSyncPluginVersion(manifest.workPackSyncPluginVersion)) throw new Error("A vers\xE3o do plugin Forge recebida n\xE3o \xE9 v\xE1lida.");
7706
+ return manifest.workPackSyncPluginVersion;
7707
+ }
7708
+ return configuredWorkPackSyncPluginVersion(existing) ?? WORK_PACK_SYNC_PLUGIN_VERSION;
7709
+ }
7691
7710
  function managedPermission(value) {
7692
7711
  const existing = typeof value === "string" && ["allow", "ask", "deny"].includes(value) ? { "*": value } : isRecord(value) ? value : {};
7693
7712
  return {
@@ -7866,6 +7885,90 @@ async function probeHealth(url2, route, headers, healthyField, source) {
7866
7885
  }
7867
7886
  }
7868
7887
 
7888
+ // packages/cli/src/ownerOnlyFile.ts
7889
+ import { spawnSync as nodeSpawnSync } from "node:child_process";
7890
+ import { randomUUID } from "node:crypto";
7891
+ import { chmod, mkdir, rename, rm, stat, writeFile } from "node:fs/promises";
7892
+ import path from "node:path";
7893
+ async function protectOwnerOnlyPath(filePath, kind, options = {}) {
7894
+ const platform = options.platform ?? process.platform;
7895
+ if (platform !== "win32") {
7896
+ await chmod(filePath, kind === "directory" ? 448 : 384);
7897
+ return;
7898
+ }
7899
+ const spawn = options.spawnSync ?? nodeSpawnSync;
7900
+ const command = kind === "directory" ? "$ErrorActionPreference = 'Stop'; $path = [Console]::In.ReadToEnd(); $identity = [System.Security.Principal.WindowsIdentity]::GetCurrent().User; $acl = [System.Security.AccessControl.DirectorySecurity]::new(); $acl.SetAccessRuleProtection($true, $false); $inheritance = [System.Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [System.Security.AccessControl.InheritanceFlags]::ObjectInherit; $rule = [System.Security.AccessControl.FileSystemAccessRule]::new($identity, [System.Security.AccessControl.FileSystemRights]::FullControl, $inheritance, [System.Security.AccessControl.PropagationFlags]::None, [System.Security.AccessControl.AccessControlType]::Allow); [void]$acl.AddAccessRule($rule); [System.IO.Directory]::SetAccessControl($path, $acl)" : "$ErrorActionPreference = 'Stop'; $path = [Console]::In.ReadToEnd(); $identity = [System.Security.Principal.WindowsIdentity]::GetCurrent().User; $acl = [System.Security.AccessControl.FileSecurity]::new(); $acl.SetAccessRuleProtection($true, $false); $rule = [System.Security.AccessControl.FileSystemAccessRule]::new($identity, [System.Security.AccessControl.FileSystemRights]::FullControl, [System.Security.AccessControl.AccessControlType]::Allow); [void]$acl.AddAccessRule($rule); [System.IO.File]::SetAccessControl($path, $acl)";
7901
+ const result = spawn("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", command], {
7902
+ encoding: "utf8",
7903
+ input: filePath
7904
+ });
7905
+ if (result.status !== 0) {
7906
+ const detail = typeof result.stderr === "string" ? result.stderr.trim().replace(/\s+/g, " ").slice(0, 500) : "";
7907
+ const context = options.failureContext ?? (kind === "directory" ? "o diret\xF3rio" : "o ficheiro");
7908
+ throw new Error(`N\xE3o foi poss\xEDvel proteger ${context} em ${filePath}${detail ? `: ${detail}` : ""}`);
7909
+ }
7910
+ }
7911
+ async function assertExistingDirectoryIsSafe(directory, options) {
7912
+ const platform = options.platform ?? process.platform;
7913
+ if (platform !== "win32") {
7914
+ const info = await stat(directory);
7915
+ const currentUid = process.getuid?.();
7916
+ if (currentUid !== void 0 && info.uid !== currentUid || (info.mode & 18) !== 0) {
7917
+ const mode = (info.mode & 511).toString(8).padStart(3, "0");
7918
+ throw new Error(`O diret\xF3rio existente ${directory} n\xE3o \xE9 controlado apenas pelo utilizador atual (modo ${mode})`);
7919
+ }
7920
+ return;
7921
+ }
7922
+ const spawn = options.spawnSync ?? nodeSpawnSync;
7923
+ const command = "$ErrorActionPreference = 'Stop'; $path = [Console]::In.ReadToEnd(); $current = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value; $trusted = @($current, 'S-1-5-18', 'S-1-5-32-544'); $dangerous = [System.Security.AccessControl.FileSystemRights]::Write -bor [System.Security.AccessControl.FileSystemRights]::Delete -bor [System.Security.AccessControl.FileSystemRights]::DeleteSubdirectoriesAndFiles -bor [System.Security.AccessControl.FileSystemRights]::ChangePermissions -bor [System.Security.AccessControl.FileSystemRights]::TakeOwnership; $acl = [System.IO.Directory]::GetAccessControl($path); $rules = $acl.GetAccessRules($true, $true, [System.Security.Principal.SecurityIdentifier]); foreach ($rule in $rules) { if ($rule.AccessControlType -eq [System.Security.AccessControl.AccessControlType]::Allow -and $rule.PropagationFlags -ne [System.Security.AccessControl.PropagationFlags]::InheritOnly -and ($rule.FileSystemRights -band $dangerous) -ne 0 -and $trusted -notcontains $rule.IdentityReference.Value) { throw ('O diret\xF3rio permite escrita por ' + $rule.IdentityReference.Value) } }";
7924
+ const result = spawn("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", command], {
7925
+ encoding: "utf8",
7926
+ input: directory
7927
+ });
7928
+ if (result.status !== 0) {
7929
+ const detail = typeof result.stderr === "string" ? result.stderr.trim().replace(/\s+/g, " ").slice(0, 500) : "";
7930
+ throw new Error(`O diret\xF3rio existente ${directory} n\xE3o \xE9 controlado apenas pelo utilizador atual${detail ? `: ${detail}` : ""}`);
7931
+ }
7932
+ }
7933
+ async function prepareOwnerOnlyFileDestination(filePath, options = {}) {
7934
+ const directory = path.dirname(filePath);
7935
+ let existing;
7936
+ try {
7937
+ existing = await stat(directory);
7938
+ } catch (error45) {
7939
+ if (error45.code !== "ENOENT") throw error45;
7940
+ }
7941
+ if (existing) {
7942
+ if (!existing.isDirectory()) throw new Error(`O destino ${directory} existe, mas n\xE3o \xE9 um diret\xF3rio`);
7943
+ await assertExistingDirectoryIsSafe(directory, options);
7944
+ return;
7945
+ }
7946
+ let createdDirectory;
7947
+ try {
7948
+ createdDirectory = await mkdir(directory, { recursive: true, mode: 448 });
7949
+ } catch (error45) {
7950
+ if (error45.code !== "EEXIST" || !(await stat(directory)).isDirectory()) throw error45;
7951
+ await assertExistingDirectoryIsSafe(directory, options);
7952
+ return;
7953
+ }
7954
+ if (createdDirectory !== void 0) await protectOwnerOnlyPath(directory, "directory", options);
7955
+ else await assertExistingDirectoryIsSafe(directory, options);
7956
+ }
7957
+ async function writeOwnerOnlyTextAtomic(filePath, content, options = {}) {
7958
+ const directory = path.dirname(filePath);
7959
+ await prepareOwnerOnlyFileDestination(filePath, options);
7960
+ const temporary = path.join(directory, `.${path.basename(filePath)}.${randomUUID()}.tmp`);
7961
+ try {
7962
+ await writeFile(temporary, content, { flag: "wx", mode: 384 });
7963
+ await protectOwnerOnlyPath(temporary, "file", options);
7964
+ await rename(temporary, filePath);
7965
+ await protectOwnerOnlyPath(filePath, "file", options);
7966
+ } catch (error45) {
7967
+ await rm(temporary, { force: true }).catch(() => void 0);
7968
+ throw error45;
7969
+ }
7970
+ }
7971
+
7869
7972
  // packages/cli/src/workPackSyncPlugin.ts
7870
7973
  import { createHash as createHash7, randomUUID as randomUUID4 } from "node:crypto";
7871
7974
  import { pathToFileURL } from "node:url";
@@ -8127,16 +8230,16 @@ async function readForgeCredentials() {
8127
8230
  }
8128
8231
 
8129
8232
  // packages/cli/src/retireDebugCapture.ts
8130
- import { lstat, readFile, rename, writeFile } from "node:fs/promises";
8131
- import { randomUUID } from "node:crypto";
8132
- import path from "node:path";
8233
+ import { lstat, readFile, rename as rename2, writeFile as writeFile2 } from "node:fs/promises";
8234
+ import { randomUUID as randomUUID2 } from "node:crypto";
8235
+ import path2 from "node:path";
8133
8236
  var MANAGED_HEADER = "// Managed by Forge sync. Do not edit.";
8134
8237
  var RETIRED_DEBUG_PLUGIN = `${MANAGED_HEADER}
8135
8238
  // Detailed capture retired. Keep this module loadable for old OpenCode configs.
8136
8239
  export const ForgeDebugTrace = async () => ({})
8137
8240
  `;
8138
8241
  async function retireDebugCapture(paths) {
8139
- const configPath = path.join(paths.forgeDir, "debug-trace.json");
8242
+ const configPath = path2.join(paths.forgeDir, "debug-trace.json");
8140
8243
  const raw = await readRegularFile(configPath);
8141
8244
  if (raw !== void 0) {
8142
8245
  const config2 = JSON.parse(raw);
@@ -8145,7 +8248,7 @@ async function retireDebugCapture(paths) {
8145
8248
  `);
8146
8249
  }
8147
8250
  }
8148
- const pluginPath = path.join(paths.pluginDir, "forge-debug-trace.js");
8251
+ const pluginPath = path2.join(paths.pluginDir, "forge-debug-trace.js");
8149
8252
  const plugin = await readRegularFile(pluginPath);
8150
8253
  if (plugin?.startsWith(MANAGED_HEADER) && plugin !== RETIRED_DEBUG_PLUGIN) {
8151
8254
  await replaceFile(pluginPath, RETIRED_DEBUG_PLUGIN);
@@ -8153,7 +8256,7 @@ async function retireDebugCapture(paths) {
8153
8256
  }
8154
8257
  async function readRegularFile(filename) {
8155
8258
  try {
8156
- const directory = await lstat(path.dirname(filename));
8259
+ const directory = await lstat(path2.dirname(filename));
8157
8260
  const info = await lstat(filename);
8158
8261
  if (!directory.isDirectory() || !info.isFile() || info.isSymbolicLink()) {
8159
8262
  throw new Error("Legacy debug capture path must be a regular file in a real directory");
@@ -8165,9 +8268,9 @@ async function readRegularFile(filename) {
8165
8268
  }
8166
8269
  }
8167
8270
  async function replaceFile(filename, contents) {
8168
- const temporary = `${filename}.retired-${randomUUID()}`;
8169
- await writeFile(temporary, contents, { flag: "wx", mode: 384 });
8170
- await rename(temporary, filename);
8271
+ const temporary = `${filename}.retired-${randomUUID2()}`;
8272
+ await writeFile2(temporary, contents, { flag: "wx", mode: 384 });
8273
+ await rename2(temporary, filename);
8171
8274
  }
8172
8275
 
8173
8276
  // packages/cli/src/reasoningLoopGuard.ts
@@ -8380,6 +8483,7 @@ function createReasoningLoopGuard(client, log = console.error, report = () => vo
8380
8483
  // packages/cli/src/workPackSyncPlugin.ts
8381
8484
  var import_yaml = __toESM(require_dist(), 1);
8382
8485
  import { link, mkdir as mkdir7, mkdtemp as mkdtemp2, readdir as readdir5, readFile as readFile11, realpath, rename as rename8, rm as rm6, rmdir, stat as stat3, unlink, writeFile as writeFile8 } from "node:fs/promises";
8486
+ import os5 from "node:os";
8383
8487
  import path12 from "node:path";
8384
8488
 
8385
8489
  // node_modules/@opencode-ai/plugin/node_modules/zod/v4/classic/external.js
@@ -20805,7 +20909,7 @@ function tool(input) {
20805
20909
  tool.schema = external_exports;
20806
20910
 
20807
20911
  // packages/cli/src/credentials.ts
20808
- import { chmod, mkdir, readFile as readFile2, rename as rename2, rm, writeFile as writeFile2 } from "node:fs/promises";
20912
+ import { chmod as chmod2, mkdir as mkdir2, readFile as readFile2, rename as rename3, rm as rm2, writeFile as writeFile3 } from "node:fs/promises";
20809
20913
  async function readCredentials(paths) {
20810
20914
  const raw = await readFile2(paths.credentialsPath, "utf8");
20811
20915
  const parsed = JSON.parse(raw);
@@ -20817,10 +20921,10 @@ async function readCredentials(paths) {
20817
20921
 
20818
20922
  // packages/cli/src/paths.ts
20819
20923
  import os from "node:os";
20820
- import path2 from "node:path";
20924
+ import path3 from "node:path";
20821
20925
  import { existsSync } from "node:fs";
20822
20926
  function resolvePaths(home = os.homedir(), platform = process.platform, env = process.env, exists2 = existsSync) {
20823
- const pathApi = platform === "win32" ? path2.win32 : path2.posix;
20927
+ const pathApi = platform === "win32" ? path3.win32 : path3.posix;
20824
20928
  const userHome = platform === "win32" ? env.USERPROFILE ?? home : home;
20825
20929
  const forgeConfigRoot = env.XDG_CONFIG_HOME ?? pathApi.join(userHome, ".config");
20826
20930
  const forgeDir = pathApi.join(forgeConfigRoot, "forge");
@@ -20908,12 +21012,12 @@ async function reportWorkPackObservations(credentials, kind, workPacks, runtime
20908
21012
  import { createHash as createHash2 } from "node:crypto";
20909
21013
  import { constants } from "node:fs";
20910
21014
  import { lstat as lstat3, open, readdir as readdir2 } from "node:fs/promises";
20911
- import path4 from "node:path";
21015
+ import path5 from "node:path";
20912
21016
 
20913
21017
  // packages/cli/src/workPackLocalState.ts
20914
21018
  import { createHash } from "node:crypto";
20915
- import { lstat as lstat2, mkdir as mkdir2, readFile as readFile3, readdir, rename as rename3, writeFile as writeFile3 } from "node:fs/promises";
20916
- import path3 from "node:path";
21019
+ import { lstat as lstat2, mkdir as mkdir3, readFile as readFile3, readdir, rename as rename4, writeFile as writeFile4 } from "node:fs/promises";
21020
+ import path4 from "node:path";
20917
21021
  var WORK_PACK_LOCAL_STATE_FILENAME = ".forge-installed-state.json";
20918
21022
  async function writeWorkPackInstalledState(input) {
20919
21023
  const tree = await digestPackTree(input.packDir);
@@ -20925,7 +21029,7 @@ async function writeWorkPackInstalledState(input) {
20925
21029
  agents: digestProjectionContents(input.agents),
20926
21030
  commands: digestProjectionContents(input.commands)
20927
21031
  };
20928
- await writeJsonAtomic(path3.join(input.packDir, WORK_PACK_LOCAL_STATE_FILENAME), state);
21032
+ await writeJsonAtomic(path4.join(input.packDir, WORK_PACK_LOCAL_STATE_FILENAME), state);
20929
21033
  }
20930
21034
  async function checkWorkPackInstalledState(input) {
20931
21035
  const state = await readInstalledState(input.packDir);
@@ -20941,13 +21045,13 @@ async function checkWorkPackTreeState(packDir, allowAdditional = false) {
20941
21045
  async function adoptWorkPackInstalledState(input) {
20942
21046
  const state = await readInstalledState(input.expectedPackDir);
20943
21047
  if (!state || !await matchesInstalledState(input, state)) return false;
20944
- await writeJsonAtomic(path3.join(input.packDir, WORK_PACK_LOCAL_STATE_FILENAME), state);
21048
+ await writeJsonAtomic(path4.join(input.packDir, WORK_PACK_LOCAL_STATE_FILENAME), state);
20945
21049
  return checkWorkPackInstalledState(input).then((result) => result === "match");
20946
21050
  }
20947
21051
  async function readInstalledState(packDir) {
20948
- const info = await lstat2(path3.join(packDir, WORK_PACK_LOCAL_STATE_FILENAME)).catch(() => void 0);
21052
+ const info = await lstat2(path4.join(packDir, WORK_PACK_LOCAL_STATE_FILENAME)).catch(() => void 0);
20949
21053
  if (!info?.isFile() || info.isSymbolicLink() || info.size > 1024 * 1024) return void 0;
20950
- const raw = await readFile3(path3.join(packDir, WORK_PACK_LOCAL_STATE_FILENAME), "utf8").catch(() => void 0);
21054
+ const raw = await readFile3(path4.join(packDir, WORK_PACK_LOCAL_STATE_FILENAME), "utf8").catch(() => void 0);
20951
21055
  if (!raw) return void 0;
20952
21056
  try {
20953
21057
  return parseWorkPackFileManifest(JSON.parse(raw));
@@ -20963,7 +21067,7 @@ async function digestPackTree(root) {
20963
21067
  for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
20964
21068
  if (!prefix && entry.name === WORK_PACK_LOCAL_STATE_FILENAME) continue;
20965
21069
  const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
20966
- const absolute = path3.join(directory, entry.name);
21070
+ const absolute = path4.join(directory, entry.name);
20967
21071
  const info = await lstat2(absolute);
20968
21072
  if (info.isSymbolicLink() || info.isFile() && info.nlink > 1) return false;
20969
21073
  if (entry.isDirectory()) {
@@ -20983,7 +21087,7 @@ function digestProjectionContents(files) {
20983
21087
  }
20984
21088
  async function projectionsMatch(directory, expected) {
20985
21089
  for (const projection of expected) {
20986
- const absolute = path3.join(directory, projection.filename);
21090
+ const absolute = path4.join(directory, projection.filename);
20987
21091
  const info = await lstat2(absolute).catch(() => void 0);
20988
21092
  if (!info?.isFile() || info.isSymbolicLink()) return false;
20989
21093
  const bytes = await readFile3(absolute).catch(() => void 0);
@@ -21009,15 +21113,15 @@ function digest(bytes) {
21009
21113
  return createHash("sha256").update(bytes).digest("hex");
21010
21114
  }
21011
21115
  async function writeJsonAtomic(filePath, value) {
21012
- await mkdir2(path3.dirname(filePath), { recursive: true });
21013
- const tempPath = path3.join(path3.dirname(filePath), `.${path3.basename(filePath)}.${process.pid}.tmp`);
21014
- await writeFile3(tempPath, `${JSON.stringify(value, null, 2)}
21116
+ await mkdir3(path4.dirname(filePath), { recursive: true });
21117
+ const tempPath = path4.join(path4.dirname(filePath), `.${path4.basename(filePath)}.${process.pid}.tmp`);
21118
+ await writeFile4(tempPath, `${JSON.stringify(value, null, 2)}
21015
21119
  `);
21016
- await rename3(tempPath, filePath);
21120
+ await rename4(tempPath, filePath);
21017
21121
  }
21018
21122
  async function adoptWorkPackFileManifest(input) {
21019
21123
  if (!await matchesInstalledState({ ...input, allowAdditional: true }, input.expected)) return false;
21020
- await writeJsonAtomic(path3.join(input.packDir, WORK_PACK_LOCAL_STATE_FILENAME), input.expected);
21124
+ await writeJsonAtomic(path4.join(input.packDir, WORK_PACK_LOCAL_STATE_FILENAME), input.expected);
21021
21125
  return true;
21022
21126
  }
21023
21127
  function containsOriginalTree(actual, expected) {
@@ -21053,7 +21157,7 @@ function emptySummary() {
21053
21157
  }
21054
21158
  async function inspectWorkPackIntegrity(input) {
21055
21159
  assertSlug(input.slug);
21056
- const packDir = path4.join(input.paths.skillsDir, input.slug);
21160
+ const packDir = path5.join(input.paths.skillsDir, input.slug);
21057
21161
  const result = { slug: input.slug, summary: emptySummary(), differences: [], differencesTruncated: false };
21058
21162
  const add = (kind, area, name) => {
21059
21163
  if (result.summary[kind] === MAX_ENTRIES) result.summary.truncated = true;
@@ -21093,7 +21197,7 @@ async function inspectWorkPackIntegrity(input) {
21093
21197
  return;
21094
21198
  }
21095
21199
  const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
21096
- const absolute = path4.join(directory, entry.name);
21200
+ const absolute = path5.join(directory, entry.name);
21097
21201
  const info = await lstat3(absolute).catch(() => void 0);
21098
21202
  if (!info) {
21099
21203
  add("unreadable", "pack", relative);
@@ -21143,7 +21247,7 @@ async function inspectWorkPackIntegrity(input) {
21143
21247
  const source = match ? `${match[1] ?? ""}${match[2]}.py` : void 0;
21144
21248
  if (source && unchanged.has(source)) {
21145
21249
  add("runtimeArtifacts", "pack", name);
21146
- cacheDirectories.add(path4.posix.dirname(name));
21250
+ cacheDirectories.add(path5.posix.dirname(name));
21147
21251
  } else add("additional", "pack", name);
21148
21252
  }
21149
21253
  for (const name of extraDirectories) if (!cacheDirectories.has(name)) add("additional", "pack", name);
@@ -21157,7 +21261,7 @@ async function inspectWorkPackIntegrity(input) {
21157
21261
  continue;
21158
21262
  }
21159
21263
  for (const item of items) {
21160
- const absolute = path4.join(directory, item.filename);
21264
+ const absolute = path5.join(directory, item.filename);
21161
21265
  try {
21162
21266
  const info = await lstat3(absolute);
21163
21267
  if (!info.isFile() || info.isSymbolicLink() || info.nlink > 1) add("unsafe", area, item.filename);
@@ -24236,74 +24340,6 @@ function renderTuiConfig(manifest) {
24236
24340
  import { createHash as createHash3, randomUUID as randomUUID3 } from "node:crypto";
24237
24341
  import { chmod as chmod3, lstat as lstat4, mkdir as mkdir4, readFile as readFile4, rename as rename5, rm as rm3, writeFile as writeFile5 } from "node:fs/promises";
24238
24342
  import path6 from "node:path";
24239
-
24240
- // packages/cli/src/ownerOnlyFile.ts
24241
- import { spawnSync as nodeSpawnSync } from "node:child_process";
24242
- import { randomUUID as randomUUID2 } from "node:crypto";
24243
- import { chmod as chmod2, mkdir as mkdir3, rename as rename4, rm as rm2, stat, writeFile as writeFile4 } from "node:fs/promises";
24244
- import path5 from "node:path";
24245
- async function protectOwnerOnlyPath(filePath, kind, options = {}) {
24246
- const platform = options.platform ?? process.platform;
24247
- if (platform !== "win32") {
24248
- await chmod2(filePath, kind === "directory" ? 448 : 384);
24249
- return;
24250
- }
24251
- const spawn = options.spawnSync ?? nodeSpawnSync;
24252
- const command = kind === "directory" ? "$ErrorActionPreference = 'Stop'; $path = [Console]::In.ReadToEnd(); $identity = [System.Security.Principal.WindowsIdentity]::GetCurrent().User; $acl = [System.Security.AccessControl.DirectorySecurity]::new(); $acl.SetAccessRuleProtection($true, $false); $inheritance = [System.Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [System.Security.AccessControl.InheritanceFlags]::ObjectInherit; $rule = [System.Security.AccessControl.FileSystemAccessRule]::new($identity, [System.Security.AccessControl.FileSystemRights]::FullControl, $inheritance, [System.Security.AccessControl.PropagationFlags]::None, [System.Security.AccessControl.AccessControlType]::Allow); [void]$acl.AddAccessRule($rule); [System.IO.Directory]::SetAccessControl($path, $acl)" : "$ErrorActionPreference = 'Stop'; $path = [Console]::In.ReadToEnd(); $identity = [System.Security.Principal.WindowsIdentity]::GetCurrent().User; $acl = [System.Security.AccessControl.FileSecurity]::new(); $acl.SetAccessRuleProtection($true, $false); $rule = [System.Security.AccessControl.FileSystemAccessRule]::new($identity, [System.Security.AccessControl.FileSystemRights]::FullControl, [System.Security.AccessControl.AccessControlType]::Allow); [void]$acl.AddAccessRule($rule); [System.IO.File]::SetAccessControl($path, $acl)";
24253
- const result = spawn("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", command], {
24254
- encoding: "utf8",
24255
- input: filePath
24256
- });
24257
- if (result.status !== 0) {
24258
- const detail = typeof result.stderr === "string" ? result.stderr.trim().replace(/\s+/g, " ").slice(0, 500) : "";
24259
- const context = options.failureContext ?? (kind === "directory" ? "o diret\xF3rio" : "o ficheiro");
24260
- throw new Error(`N\xE3o foi poss\xEDvel proteger ${context} em ${filePath}${detail ? `: ${detail}` : ""}`);
24261
- }
24262
- }
24263
- async function assertExistingDirectoryIsSafe(directory, options) {
24264
- const platform = options.platform ?? process.platform;
24265
- if (platform !== "win32") {
24266
- const info = await stat(directory);
24267
- const currentUid = process.getuid?.();
24268
- if (currentUid !== void 0 && info.uid !== currentUid || (info.mode & 18) !== 0) {
24269
- const mode = (info.mode & 511).toString(8).padStart(3, "0");
24270
- throw new Error(`O diret\xF3rio existente ${directory} n\xE3o \xE9 controlado apenas pelo utilizador atual (modo ${mode})`);
24271
- }
24272
- return;
24273
- }
24274
- const spawn = options.spawnSync ?? nodeSpawnSync;
24275
- const command = "$ErrorActionPreference = 'Stop'; $path = [Console]::In.ReadToEnd(); $current = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value; $trusted = @($current, 'S-1-5-18', 'S-1-5-32-544'); $dangerous = [System.Security.AccessControl.FileSystemRights]::Write -bor [System.Security.AccessControl.FileSystemRights]::Delete -bor [System.Security.AccessControl.FileSystemRights]::DeleteSubdirectoriesAndFiles -bor [System.Security.AccessControl.FileSystemRights]::ChangePermissions -bor [System.Security.AccessControl.FileSystemRights]::TakeOwnership; $acl = [System.IO.Directory]::GetAccessControl($path); $rules = $acl.GetAccessRules($true, $true, [System.Security.Principal.SecurityIdentifier]); foreach ($rule in $rules) { if ($rule.AccessControlType -eq [System.Security.AccessControl.AccessControlType]::Allow -and $rule.PropagationFlags -ne [System.Security.AccessControl.PropagationFlags]::InheritOnly -and ($rule.FileSystemRights -band $dangerous) -ne 0 -and $trusted -notcontains $rule.IdentityReference.Value) { throw ('O diret\xF3rio permite escrita por ' + $rule.IdentityReference.Value) } }";
24276
- const result = spawn("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", command], {
24277
- encoding: "utf8",
24278
- input: directory
24279
- });
24280
- if (result.status !== 0) {
24281
- const detail = typeof result.stderr === "string" ? result.stderr.trim().replace(/\s+/g, " ").slice(0, 500) : "";
24282
- throw new Error(`O diret\xF3rio existente ${directory} n\xE3o \xE9 controlado apenas pelo utilizador atual${detail ? `: ${detail}` : ""}`);
24283
- }
24284
- }
24285
- async function prepareOwnerOnlyFileDestination(filePath, options = {}) {
24286
- const directory = path5.dirname(filePath);
24287
- const createdDirectory = await mkdir3(directory, { recursive: true, mode: 448 });
24288
- if (createdDirectory !== void 0) await protectOwnerOnlyPath(directory, "directory", options);
24289
- else await assertExistingDirectoryIsSafe(directory, options);
24290
- }
24291
- async function writeOwnerOnlyTextAtomic(filePath, content, options = {}) {
24292
- const directory = path5.dirname(filePath);
24293
- await prepareOwnerOnlyFileDestination(filePath, options);
24294
- const temporary = path5.join(directory, `.${path5.basename(filePath)}.${randomUUID2()}.tmp`);
24295
- try {
24296
- await writeFile4(temporary, content, { flag: "wx", mode: 384 });
24297
- await protectOwnerOnlyPath(temporary, "file", options);
24298
- await rename4(temporary, filePath);
24299
- await protectOwnerOnlyPath(filePath, "file", options);
24300
- } catch (error45) {
24301
- await rm2(temporary, { force: true }).catch(() => void 0);
24302
- throw error45;
24303
- }
24304
- }
24305
-
24306
- // packages/cli/src/coreSyncTransaction.ts
24307
24343
  var CORE_RUNTIME_MANIFEST_VERSION = 1;
24308
24344
  var CoreSyncUncertainError = class extends Error {
24309
24345
  constructor(message, paths) {
@@ -24921,6 +24957,7 @@ async function fetchManifest(credentials, agentVersion = "0.1.0") {
24921
24957
  "x-forge-hostname": os4.hostname(),
24922
24958
  "x-forge-agent-version": agentVersion
24923
24959
  },
24960
+ redirect: "error",
24924
24961
  signal: AbortSignal.timeout(15e3)
24925
24962
  });
24926
24963
  } catch (error45) {
@@ -24955,6 +24992,7 @@ function validCoreManifest(value) {
24955
24992
  if (!value || typeof value !== "object" || Array.isArray(value)) return false;
24956
24993
  const manifest = value;
24957
24994
  if (!manifest.config || typeof manifest.config !== "object" || Array.isArray(manifest.config) || !Array.isArray(manifest.skills)) return false;
24995
+ if (manifest.workPackSyncPluginVersion !== void 0 && !isWorkPackSyncPluginVersion(manifest.workPackSyncPluginVersion)) return false;
24958
24996
  const config2 = manifest.config;
24959
24997
  if (typeof config2.model !== "string" || !config2.model || typeof config2.small_model !== "string" || !config2.small_model || typeof config2.theme !== "string" || typeof config2.instructionsUrl !== "string" || !Array.isArray(config2.models) || config2.models.length === 0) return false;
24960
24998
  const modelIds = config2.models.map((model) => model && typeof model === "object" && !Array.isArray(model) ? model.id : void 0);
@@ -26452,7 +26490,7 @@ async function syncLocalWorker(paths, credentials, manifest) {
26452
26490
  }
26453
26491
 
26454
26492
  // packages/cli/src/workPackSyncPlugin.ts
26455
- var PLUGIN_VERSION = "0.1.43";
26493
+ var PLUGIN_VERSION = "0.1.45";
26456
26494
  var FORGE_DECISION_TIMEOUT_MS = 11e4;
26457
26495
  var STATUS_FILENAME = "work-pack-startup-status.json";
26458
26496
  var activeSync = /* @__PURE__ */ new Map();
@@ -26587,7 +26625,7 @@ function createForgeImageTool(forgeBaseUrl, gatewayBaseUrl, paths) {
26587
26625
  }
26588
26626
  });
26589
26627
  }
26590
- function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseDirectory) {
26628
+ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseDirectory, beforeCall) {
26591
26629
  const question = tool.schema.discriminatedUnion("type", [
26592
26630
  tool.schema.object({
26593
26631
  type: tool.schema.literal("noul"),
@@ -26624,6 +26662,21 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseD
26624
26662
  let requestBody;
26625
26663
  if (fromFile) {
26626
26664
  const file2 = await fileInsideWorkspace(context.directory, args.request_file);
26665
+ const planFile = path12.join(path12.dirname(path12.dirname(file2)), "plan.json");
26666
+ if (!responseDirectory && path12.basename(path12.dirname(file2)) === "requests" && await fileExists(planFile)) {
26667
+ const plan = JSON.parse(await readFile11(planFile, "utf8"));
26668
+ if (plan?.engine === "jev-batch" && plan.model === "typesafe/jev-1.13" && Array.isArray(plan.batches)) {
26669
+ let batch;
26670
+ for (const candidate of plan.batches) {
26671
+ if (await fileInsideWorkspace(context.directory, candidate.request_file) === file2) {
26672
+ batch = candidate;
26673
+ break;
26674
+ }
26675
+ }
26676
+ if (!batch) throw new Error("O pedido n\xE3o pertence ao plano Jev guardado.");
26677
+ return createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths).execute({ plan_file: planFile, batch_id: batch.batch_id }, context);
26678
+ }
26679
+ }
26627
26680
  const raw = await readFile11(file2, "utf8");
26628
26681
  if (Buffer.byteLength(raw) > 512 * 1024) throw new Error("O ficheiro de pedido excede 512 KiB.");
26629
26682
  let parsed;
@@ -26647,6 +26700,11 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseD
26647
26700
  const responseFile = path12.join(responseDir, "response.json");
26648
26701
  try {
26649
26702
  const credentials = await readForgeCredentials(paths, forgeBaseUrl);
26703
+ const probeFile = path12.join(responseDir, ".write-test");
26704
+ await writeFile8(probeFile, "", { flag: "wx", mode: 384 });
26705
+ await unlink(probeFile);
26706
+ context.abort.throwIfAborted();
26707
+ await beforeCall?.(responseFile);
26650
26708
  const response = await fetch(`${decisionBaseUrl}/v1/decisions`, {
26651
26709
  method: "POST",
26652
26710
  redirect: "error",
@@ -26667,11 +26725,13 @@ function createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseD
26667
26725
  try {
26668
26726
  await writeFile8(responseFile, raw, { flag: "wx", mode: 384 });
26669
26727
  return JSON.stringify({ ...body, response_file: responseFile }, null, 2);
26670
- } catch {
26728
+ } catch (error45) {
26671
26729
  return JSON.stringify({
26672
26730
  ...body,
26673
26731
  response_file: null,
26674
- 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."
26732
+ persistence_code: error45.code,
26733
+ recovery_file: responseFile,
26734
+ 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; resolver a grava\xE7\xE3o antes de retomar o lote pelo runner."
26675
26735
  }, null, 2);
26676
26736
  }
26677
26737
  }
@@ -26704,6 +26764,20 @@ async function fileExists(candidate) {
26704
26764
  throw error45;
26705
26765
  }
26706
26766
  }
26767
+ async function ensureJevDirectory(directory, filesystem = { stat: stat3, mkdir: mkdir7 }) {
26768
+ try {
26769
+ if ((await filesystem.stat(directory)).isDirectory()) return;
26770
+ throw new Error(`O destino ${path12.basename(directory)} existe, mas n\xE3o \xE9 uma pasta. Preservar o conte\xFAdo e verificar o caminho.`);
26771
+ } catch (error45) {
26772
+ if (error45.code !== "ENOENT") throw error45;
26773
+ }
26774
+ try {
26775
+ await filesystem.mkdir(directory, { recursive: true });
26776
+ } catch (error45) {
26777
+ if (error45.code === "EEXIST" && (await filesystem.stat(directory)).isDirectory()) return;
26778
+ throw error45;
26779
+ }
26780
+ }
26707
26781
  function canonicalJson(value) {
26708
26782
  if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
26709
26783
  if (value && typeof value === "object") {
@@ -26712,34 +26786,84 @@ function canonicalJson(value) {
26712
26786
  }
26713
26787
  return JSON.stringify(value);
26714
26788
  }
26789
+ async function validateSavedDecision(file2, request) {
26790
+ const body = JSON.parse(await readFile11(file2, "utf8"));
26791
+ const answers = body.answers;
26792
+ const questions = request.questions;
26793
+ const usage = body.usage;
26794
+ if (typeof body.model !== "string" || !/^typesafe\/jev-1\.13(?:-|$)/.test(body.model) || !answers || Array.isArray(answers) || !usage || !Number.isInteger(usage.input_tokens) || !Number.isInteger(usage.output_tokens) || Object.keys(answers).sort().join("\n") !== Object.keys(questions).sort().join("\n") || Object.entries(questions).some(([id, question]) => !answers[id] || answers[id].type !== question.type || question.type === "noul" && (typeof answers[id].noul !== "number" || !Number.isFinite(answers[id].noul)))) {
26795
+ throw new Error("Resposta Jev guardada inv\xE1lida; preservar o ficheiro e verificar antes de continuar.");
26796
+ }
26797
+ return body;
26798
+ }
26799
+ async function acquireJevRunLock(lockDir) {
26800
+ try {
26801
+ await mkdir7(lockDir);
26802
+ return {};
26803
+ } catch (error45) {
26804
+ if (error45.code !== "EEXIST") throw error45;
26805
+ }
26806
+ let owner;
26807
+ let ownerRaw;
26808
+ try {
26809
+ ownerRaw = await readFile11(path12.join(lockDir, "owner.json"), "utf8");
26810
+ owner = JSON.parse(ownerRaw);
26811
+ } catch {
26812
+ throw new Error("Chamada interrompida com lock sem identifica\xE7\xE3o; n\xE3o \xE9 poss\xEDvel confirmar que terminou. Preservar o lock e verificar a execu\xE7\xE3o.");
26813
+ }
26814
+ if (!Number.isInteger(owner.pid) || owner.pid <= 0 || owner.hostname && owner.hostname !== os5.hostname()) {
26815
+ throw new Error("N\xE3o \xE9 poss\xEDvel confirmar que a execu\xE7\xE3o do lock terminou nesta m\xE1quina. Preservar o lock.");
26816
+ }
26817
+ try {
26818
+ process.kill(owner.pid, 0);
26819
+ } catch (error45) {
26820
+ if (error45.code === "ESRCH") {
26821
+ const archived = `${lockDir}.interrupted-${createHash7("sha256").update(ownerRaw).digest("hex")}`;
26822
+ await rename8(lockDir, archived);
26823
+ try {
26824
+ await mkdir7(lockDir);
26825
+ } catch {
26826
+ throw new Error("Este plano j\xE1 est\xE1 em execu\xE7\xE3o; a recupera\xE7\xE3o ficou preservada.");
26827
+ }
26828
+ return owner;
26829
+ }
26830
+ throw new Error("N\xE3o \xE9 poss\xEDvel verificar o processo do lock. Preservar o lock.");
26831
+ }
26832
+ throw new Error("Este plano j\xE1 est\xE1 em execu\xE7\xE3o. Aguardar o fim da chamada antes de retomar.");
26833
+ }
26715
26834
  function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
26716
26835
  return tool({
26717
- 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.",
26718
- args: { plan_file: tool.schema.string().describe("Caminho de jev/plan.json dentro do workspace") },
26836
+ description: "Executa os lotes Jev pendentes, recupera respostas v\xE1lidas e permite no m\xE1ximo uma repeti\xE7\xE3o por lote com resultado perdido. Requer a aprova\xE7\xE3o habitual para as chamadas pagas antes de usar.",
26837
+ args: {
26838
+ plan_file: tool.schema.string().describe("Caminho de jev/plan.json dentro do workspace"),
26839
+ batch_id: tool.schema.string().optional().describe("Executar apenas este lote, com o mesmo limite de recupera\xE7\xE3o")
26840
+ },
26719
26841
  async execute(args, context) {
26720
26842
  const planFile = await fileInsideWorkspace(context.directory, args.plan_file);
26721
26843
  if (path12.basename(planFile) !== "plan.json" || path12.basename(path12.dirname(planFile)) !== "jev") throw new Error("Indica o ficheiro jev/plan.json.");
26722
26844
  const runDir = path12.dirname(path12.dirname(planFile));
26723
26845
  const plan = JSON.parse(await readFile11(planFile, "utf8"));
26724
26846
  if (plan.engine !== "jev-batch" || plan.model !== "typesafe/jev-1.13" || !Array.isArray(plan.batches)) throw new Error("O plano Jev \xE9 inv\xE1lido.");
26725
- const batches = plan.batches;
26847
+ const allBatches = plan.batches;
26848
+ const batches = args.batch_id ? allBatches.filter((batch) => batch.batch_id === args.batch_id) : allBatches;
26849
+ if (args.batch_id && batches.length !== 1) throw new Error("O lote indicado n\xE3o pertence ao plano Jev.");
26726
26850
  const responsePath = path12.join(runDir, "jev", "responses");
26727
- await mkdir7(responsePath, { recursive: true });
26851
+ await ensureJevDirectory(responsePath);
26728
26852
  const responseDir = await fileInsideWorkspace(context.directory, responsePath);
26729
26853
  if (path12.dirname(responseDir) !== path12.join(runDir, "jev")) throw new Error("A pasta de respostas tem de pertencer ao run Jev.");
26730
- const decide = createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseDir);
26731
26854
  const lockDir = path12.join(runDir, "jev", ".decide-run.lock");
26732
- try {
26733
- await mkdir7(lockDir);
26734
- } catch (error45) {
26735
- if (error45.code !== "EEXIST") throw error45;
26736
- 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.");
26737
- }
26738
- let releaseLock = true;
26855
+ const interrupted = await acquireJevRunLock(lockDir);
26739
26856
  let saved = 0;
26740
26857
  let skipped = 0;
26858
+ let recovered = 0;
26859
+ const repeated = [];
26741
26860
  try {
26742
- await writeFile8(path12.join(lockDir, "owner.json"), JSON.stringify({ pid: process.pid, started_at: (/* @__PURE__ */ new Date()).toISOString() }), { mode: 384 });
26861
+ const ownerFile = path12.join(lockDir, "owner.json");
26862
+ await writeOwnerOnlyTextAtomic(ownerFile, JSON.stringify({ ...interrupted, pid: process.pid, hostname: os5.hostname(), started_at: (/* @__PURE__ */ new Date()).toISOString() }));
26863
+ const attemptsPath = path12.join(runDir, "jev", "attempts");
26864
+ await ensureJevDirectory(attemptsPath);
26865
+ const attemptsDir = await fileInsideWorkspace(context.directory, attemptsPath);
26866
+ if (path12.dirname(attemptsDir) !== path12.join(runDir, "jev")) throw new Error("A pasta de tentativas tem de pertencer ao run Jev.");
26743
26867
  for (const batch of batches) {
26744
26868
  context.abort.throwIfAborted();
26745
26869
  const batchId = batch.batch_id;
@@ -26753,49 +26877,120 @@ function createForgeDecisionRunTool(forgeBaseUrl, decisionBaseUrl, paths) {
26753
26877
  const request = JSON.parse(await readFile11(requestFile, "utf8"));
26754
26878
  const fingerprint = createHash7("sha256").update(canonicalJson(request)).digest("hex");
26755
26879
  if (fingerprint !== batch.request_fingerprint) throw new Error(`${batchId}: fingerprint do pedido n\xE3o corresponde ao plano.`);
26756
- if (await fileExists(acceptedFile) || await fileExists(responseFile)) {
26880
+ if (await fileExists(acceptedFile)) {
26757
26881
  skipped++;
26758
26882
  continue;
26759
26883
  }
26760
- let result;
26761
- await writeFile8(path12.join(lockDir, "owner.json"), JSON.stringify({ pid: process.pid, batch_id: batchId, request_fingerprint: fingerprint, started_at: (/* @__PURE__ */ new Date()).toISOString() }), { mode: 384 });
26762
- try {
26763
- const output = await decide.execute({ request_file: requestFile }, context);
26764
- result = JSON.parse(typeof output === "string" ? output : output.output);
26765
- } catch (error45) {
26766
- releaseLock = error45 instanceof ForgeDecisionRejectedError;
26767
- 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." });
26884
+ if (await fileExists(responseFile)) {
26885
+ const body = await validateSavedDecision(await fileInsideWorkspace(context.directory, responseFile), request);
26886
+ if (args.batch_id) return JSON.stringify({ ...body, response_file: responseFile });
26887
+ skipped++;
26888
+ continue;
26768
26889
  }
26769
- if (typeof result.response_file !== "string") {
26770
- releaseLock = false;
26771
- 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." });
26890
+ const attemptsFile = path12.join(attemptsDir, `${batchId}.json`);
26891
+ let attempts = { request_fingerprint: fingerprint, attempts: 0, response_files: [] };
26892
+ if (await fileExists(attemptsFile)) attempts = JSON.parse(await readFile11(attemptsFile, "utf8"));
26893
+ else if (interrupted.batch_id === batchId) {
26894
+ if (interrupted.request_fingerprint !== fingerprint) throw new Error(`${batchId}: fingerprint da chamada interrompida n\xE3o corresponde ao plano.`);
26895
+ attempts.attempts = 1;
26772
26896
  }
26773
- try {
26774
- await link(result.response_file, responseFile);
26775
- } catch {
26776
- releaseLock = false;
26777
- return JSON.stringify({
26778
- verified: false,
26779
- saved,
26780
- skipped,
26781
- stopped_at: batchId,
26782
- recovery_file: result.response_file,
26783
- error: "Resposta conclu\xEDda mas n\xE3o copiada para o run; recuperar o ficheiro indicado, sem repetir a chamada."
26897
+ if (attempts.request_fingerprint !== fingerprint || !Number.isInteger(attempts.attempts) || attempts.attempts < 0 || attempts.attempts > 2 || !Array.isArray(attempts.response_files)) {
26898
+ throw new Error(`${batchId}: registo de tentativas inv\xE1lido; preservar e verificar antes de continuar.`);
26899
+ }
26900
+ if (attempts.repeated_at) repeated.push(batchId);
26901
+ const persistAttempts = () => writeOwnerOnlyTextAtomic(attemptsFile, JSON.stringify(attempts));
26902
+ if (!await fileExists(attemptsFile) && attempts.attempts > 0) await persistAttempts();
26903
+ const stop = (error45, detail = {}) => JSON.stringify({ verified: false, saved, skipped, recovered, repeated, stopped_at: batchId, ...detail, error: error45 });
26904
+ const recoverResponse = async () => {
26905
+ const legacyAllocations = interrupted.batch_id === batchId && interrupted.request_fingerprint === fingerprint ? (await readdir5(responseDir)).filter((name) => name.startsWith(".forge-decision-")).map((name) => path12.join(responseDir, name, "response.json")) : [];
26906
+ const candidates = [...attempts.response_files, ...legacyAllocations];
26907
+ for (const candidate of new Set(candidates)) {
26908
+ if (typeof candidate !== "string") throw new Error("Registo de recupera\xE7\xE3o inv\xE1lido.");
26909
+ if (!await fileExists(candidate)) continue;
26910
+ const file2 = await fileInsideWorkspace(context.directory, candidate);
26911
+ if (path12.dirname(path12.dirname(file2)) !== responseDir) throw new Error("Resposta recuper\xE1vel fora da pasta do lote.");
26912
+ try {
26913
+ await validateSavedDecision(file2, request);
26914
+ } catch {
26915
+ continue;
26916
+ }
26917
+ if (!attempts.response_files.includes(file2)) {
26918
+ attempts.response_files.push(file2);
26919
+ await persistAttempts();
26920
+ }
26921
+ return file2;
26922
+ }
26923
+ return void 0;
26924
+ };
26925
+ let source = await recoverResponse();
26926
+ if (source) recovered++;
26927
+ while (!source) {
26928
+ context.abort.throwIfAborted();
26929
+ if (attempts.attempts >= 2) return stop("A \xFAnica repeti\xE7\xE3o deste lote j\xE1 foi usada. Preservar o progresso e recuperar a resposta do hist\xF3rico acess\xEDvel.");
26930
+ const previousAttempts = attempts.attempts;
26931
+ const decide = createForgeDecisionTool(forgeBaseUrl, decisionBaseUrl, paths, responseDir, async (allocated) => {
26932
+ await writeOwnerOnlyTextAtomic(ownerFile, JSON.stringify({ pid: process.pid, hostname: os5.hostname(), batch_id: batchId, request_fingerprint: fingerprint, started_at: (/* @__PURE__ */ new Date()).toISOString() }));
26933
+ const next = { ...attempts, attempts: attempts.attempts + 1, response_files: [...attempts.response_files, allocated] };
26934
+ if (next.attempts === 2) next.repeated_at = (/* @__PURE__ */ new Date()).toISOString();
26935
+ await writeOwnerOnlyTextAtomic(attemptsFile, JSON.stringify(next));
26936
+ attempts = next;
26784
26937
  });
26938
+ let result;
26939
+ try {
26940
+ result = JSON.parse(await decide.execute({ request_file: requestFile }, context));
26941
+ } catch (error45) {
26942
+ if (error45 instanceof ForgeDecisionRejectedError) {
26943
+ attempts.attempts = previousAttempts;
26944
+ if (previousAttempts < 2) delete attempts.repeated_at;
26945
+ await persistAttempts();
26946
+ return stop(error45.message);
26947
+ }
26948
+ if (attempts.attempts === previousAttempts) return stop(error45 instanceof Error ? error45.message : "Falha local antes da chamada Jev.");
26949
+ if (attempts.attempts === 2 && !repeated.includes(batchId)) repeated.push(batchId);
26950
+ if (context.abort.aborted) return stop("Execu\xE7\xE3o interrompida; preservar o progresso e retomar quando poss\xEDvel.");
26951
+ source = await recoverResponse();
26952
+ if (source) recovered++;
26953
+ continue;
26954
+ }
26955
+ if (attempts.attempts === 2 && !repeated.includes(batchId)) repeated.push(batchId);
26956
+ if (typeof result.response_file !== "string") return stop(String(result.persistence_error), { recovery_response: result, persistence_code: result.persistence_code });
26957
+ source = result.response_file;
26958
+ try {
26959
+ await validateSavedDecision(source, request);
26960
+ } catch (error45) {
26961
+ return stop(error45 instanceof Error ? error45.message : "Resposta inv\xE1lida.", { recovery_file: source });
26962
+ }
26785
26963
  }
26786
- await unlink(result.response_file).then(() => rmdir(path12.dirname(result.response_file))).catch(() => void 0);
26964
+ try {
26965
+ await link(source, responseFile);
26966
+ } catch (error45) {
26967
+ let identical = false;
26968
+ if (error45.code === "EEXIST") {
26969
+ try {
26970
+ identical = await readFile11(source, "utf8") === await readFile11(responseFile, "utf8");
26971
+ } catch {
26972
+ }
26973
+ }
26974
+ if (!identical) {
26975
+ return stop("Resposta conclu\xEDda mas n\xE3o guardada no destino do lote; resolver a grava\xE7\xE3o e retomar sem nova chamada.", { recovery_file: source, persistence_code: error45.code });
26976
+ }
26977
+ }
26978
+ await unlink(source).then(() => rmdir(path12.dirname(source))).catch(() => void 0);
26787
26979
  saved++;
26980
+ if (args.batch_id) return JSON.stringify({ ...await validateSavedDecision(responseFile, request), response_file: responseFile, repeated });
26788
26981
  }
26789
26982
  return JSON.stringify({
26790
26983
  verified: true,
26791
26984
  batch_count: batches.length,
26792
26985
  saved,
26793
26986
  skipped,
26987
+ recovered,
26988
+ repeated,
26794
26989
  response_dir: responseDir,
26795
26990
  next_step: "Executar jev-accept sobre as respostas guardadas ainda n\xE3o aceites; depois jev-validate e jev-merge."
26796
26991
  });
26797
26992
  } finally {
26798
- if (releaseLock) await rm6(lockDir, { recursive: true });
26993
+ await rm6(lockDir, { recursive: true });
26799
26994
  }
26800
26995
  }
26801
26996
  });
@@ -26863,6 +27058,7 @@ async function synchronizeAtStartup(forgeBaseUrl, input, localConfig) {
26863
27058
  const before = await managedProjectionNames(paths);
26864
27059
  let credentials;
26865
27060
  let forgeConfigVerified = false;
27061
+ let pluginUpdate;
26866
27062
  let decisionBaseUrl = forgeBaseUrl;
26867
27063
  const runtime = await observeRuntime(input);
26868
27064
  try {
@@ -26872,6 +27068,19 @@ async function synchronizeAtStartup(forgeBaseUrl, input, localConfig) {
26872
27068
  decisionBaseUrl = resolveDecisionBaseUrl(manifest.gatewayBaseUrl, forgeBaseUrl);
26873
27069
  forgeConfigVerified = true;
26874
27070
  const result = localConfig ? await syncLocalWorker(paths, credentials, manifest) : await applyWorkPackManifest(paths, credentials, manifest, {});
27071
+ if (localConfig) {
27072
+ const config2 = objectRecord(parseJsonc(await readFile11(paths.opencodeConfigPath, "utf8")));
27073
+ const targetVersion = configuredWorkPackSyncPluginVersion(config2);
27074
+ if (targetVersion) pluginUpdate = { targetVersion, restartRequired: targetVersion !== PLUGIN_VERSION };
27075
+ if (pluginUpdate?.restartRequired) {
27076
+ const message = "Atualiza\xE7\xE3o preparada. Quando terminar o trabalho, feche e volte a abrir o OpenWork para a aplicar.";
27077
+ console.info(`[Forge] ${message}`);
27078
+ const client = input && typeof input === "object" ? input.client : void 0;
27079
+ if (client?.tui?.showToast) {
27080
+ void Promise.resolve().then(() => client.tui.showToast({ body: { title: "Forge", message, variant: "info", duration: 1e4 } })).catch(() => void 0);
27081
+ }
27082
+ }
27083
+ }
26875
27084
  await reportWorkPackObservations(credentials, "sync", result.workPackObservations, runtime, PLUGIN_VERSION);
26876
27085
  const failures = result.workPacks.outcomes.filter(
26877
27086
  (outcome) => outcome.status === "failed" || outcome.status === "recovery-uncertain"
@@ -26884,6 +27093,7 @@ async function synchronizeAtStartup(forgeBaseUrl, input, localConfig) {
26884
27093
  await writeStatus(paths, {
26885
27094
  version: 1,
26886
27095
  pluginVersion: PLUGIN_VERSION,
27096
+ ...pluginUpdate ? { pluginUpdate } : {},
26887
27097
  status: result.workPacks.receipt.status,
26888
27098
  syncedAt: (/* @__PURE__ */ new Date()).toISOString(),
26889
27099
  installed: result.installed,
@@ -26896,6 +27106,7 @@ async function synchronizeAtStartup(forgeBaseUrl, input, localConfig) {
26896
27106
  await writeStatus(paths, {
26897
27107
  version: 1,
26898
27108
  pluginVersion: PLUGIN_VERSION,
27109
+ ...pluginUpdate ? { pluginUpdate } : {},
26899
27110
  status: "failed",
26900
27111
  attemptedAt: (/* @__PURE__ */ new Date()).toISOString(),
26901
27112
  message
@@ -27053,5 +27264,6 @@ export {
27053
27264
  FORGE_DECISION_TIMEOUT_MS,
27054
27265
  ForgeWorkPackSyncServer,
27055
27266
  workPackSyncPlugin_default as default,
27267
+ ensureJevDirectory,
27056
27268
  resolveDecisionBaseUrl
27057
27269
  };
package/dist/repair.js CHANGED
@@ -161,7 +161,25 @@ async function assertExistingDirectoryIsSafe(directory, options) {
161
161
  }
162
162
  async function prepareOwnerOnlyFileDestination(filePath, options = {}) {
163
163
  const directory = path.dirname(filePath);
164
- const createdDirectory = await mkdir2(directory, { recursive: true, mode: 448 });
164
+ let existing;
165
+ try {
166
+ existing = await stat(directory);
167
+ } catch (error) {
168
+ if (error.code !== "ENOENT") throw error;
169
+ }
170
+ if (existing) {
171
+ if (!existing.isDirectory()) throw new Error(`O destino ${directory} existe, mas n\xE3o \xE9 um diret\xF3rio`);
172
+ await assertExistingDirectoryIsSafe(directory, options);
173
+ return;
174
+ }
175
+ let createdDirectory;
176
+ try {
177
+ createdDirectory = await mkdir2(directory, { recursive: true, mode: 448 });
178
+ } catch (error) {
179
+ if (error.code !== "EEXIST" || !(await stat(directory)).isDirectory()) throw error;
180
+ await assertExistingDirectoryIsSafe(directory, options);
181
+ return;
182
+ }
165
183
  if (createdDirectory !== void 0) await protectOwnerOnlyPath(directory, "directory", options);
166
184
  else await assertExistingDirectoryIsSafe(directory, options);
167
185
  }
@@ -401,7 +419,7 @@ var DEVICE_ENROLLMENT_PROTOCOL_VERSION = 1;
401
419
  // packages/shared/src/contracts/settings.ts
402
420
  var DOCUMENT_READER_AGENT = "document-reader";
403
421
  var OPENROUTER_ALIAS_PROVIDER_NAME = "OpenRouter (via Forge)";
404
- var WORK_PACK_SYNC_PLUGIN_VERSION = "0.1.43";
422
+ var WORK_PACK_SYNC_PLUGIN_VERSION = "0.1.45";
405
423
  var WORK_PACK_SYNC_PLUGIN_PACKAGE = `minimal-forge-work-pack-sync@${WORK_PACK_SYNC_PLUGIN_VERSION}`;
406
424
  var WORK_PACK_SYNC_PLUGIN_FILENAME = `minimal-forge-work-pack-sync-${WORK_PACK_SYNC_PLUGIN_VERSION}.tgz`;
407
425
  var FIRECRAWL_KEYLESS_MCP_NAME = "firecrawl";
@@ -456,7 +474,7 @@ function mergeWorkerOpenCodeConfig(existing, manifest, forgeBaseUrl, forgeApiKey
456
474
  });
457
475
  if (options.automaticWorkPackSync) {
458
476
  plugins.push([
459
- WORK_PACK_SYNC_PLUGIN_PACKAGE,
477
+ `minimal-forge-work-pack-sync@${targetWorkPackSyncPluginVersion(manifest, existing)}`,
460
478
  { forgeBaseUrl: forgeBaseUrl.replace(/\/$/, ""), ...options.localConfig ? { localConfig: true } : {} }
461
479
  ]);
462
480
  }
@@ -482,6 +500,25 @@ function mergeWorkerOpenCodeConfig(existing, manifest, forgeBaseUrl, forgeApiKey
482
500
  ...plugins.length > 0 ? { plugin: plugins } : {}
483
501
  };
484
502
  }
503
+ function isWorkPackSyncPluginVersion(value) {
504
+ return typeof value === "string" && value.length <= 64 && /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(value);
505
+ }
506
+ function configuredWorkPackSyncPluginVersion(config) {
507
+ for (const entry of Array.isArray(config.plugin) ? config.plugin : []) {
508
+ const name = Array.isArray(entry) ? entry[0] : entry;
509
+ if (typeof name !== "string" || !name.startsWith("minimal-forge-work-pack-sync@")) continue;
510
+ const version = name.slice("minimal-forge-work-pack-sync@".length);
511
+ if (isWorkPackSyncPluginVersion(version)) return version;
512
+ }
513
+ return void 0;
514
+ }
515
+ function targetWorkPackSyncPluginVersion(manifest, existing) {
516
+ if (manifest.workPackSyncPluginVersion !== void 0) {
517
+ if (!isWorkPackSyncPluginVersion(manifest.workPackSyncPluginVersion)) throw new Error("A vers\xE3o do plugin Forge recebida n\xE3o \xE9 v\xE1lida.");
518
+ return manifest.workPackSyncPluginVersion;
519
+ }
520
+ return configuredWorkPackSyncPluginVersion(existing) ?? WORK_PACK_SYNC_PLUGIN_VERSION;
521
+ }
485
522
  function managedPermission(value) {
486
523
  const existing = typeof value === "string" && ["allow", "ask", "deny"].includes(value) ? { "*": value } : isRecord(value) ? value : {};
487
524
  return {
@@ -4196,6 +4233,7 @@ async function fetchManifest(credentials, agentVersion = "0.1.0") {
4196
4233
  "x-forge-hostname": os2.hostname(),
4197
4234
  "x-forge-agent-version": agentVersion
4198
4235
  },
4236
+ redirect: "error",
4199
4237
  signal: AbortSignal.timeout(15e3)
4200
4238
  });
4201
4239
  } catch (error) {
@@ -4230,6 +4268,7 @@ function validCoreManifest(value) {
4230
4268
  if (!value || typeof value !== "object" || Array.isArray(value)) return false;
4231
4269
  const manifest = value;
4232
4270
  if (!manifest.config || typeof manifest.config !== "object" || Array.isArray(manifest.config) || !Array.isArray(manifest.skills)) return false;
4271
+ if (manifest.workPackSyncPluginVersion !== void 0 && !isWorkPackSyncPluginVersion(manifest.workPackSyncPluginVersion)) return false;
4233
4272
  const config = manifest.config;
4234
4273
  if (typeof config.model !== "string" || !config.model || typeof config.small_model !== "string" || !config.small_model || typeof config.theme !== "string" || typeof config.instructionsUrl !== "string" || !Array.isArray(config.models) || config.models.length === 0) return false;
4235
4274
  const modelIds = config.models.map((model) => model && typeof model === "object" && !Array.isArray(model) ? model.id : void 0);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "minimal-forge-work-pack-sync",
3
- "version": "0.1.43",
3
+ "version": "0.1.45",
4
4
  "description": "Minimal Forge Work Pack startup synchronization for OpenCode and OpenWork.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {