minimal-forge-work-pack-sync 0.1.39 → 0.1.41

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.39";
7610
+ var WORK_PACK_SYNC_PLUGIN_VERSION = "0.1.41";
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";
@@ -8170,6 +8170,172 @@ async function replaceFile(filename, contents) {
8170
8170
  await rename(temporary, filename);
8171
8171
  }
8172
8172
 
8173
+ // packages/cli/src/reasoningLoopGuard.ts
8174
+ var LINE_MIN_CHARS = 2;
8175
+ var LINE_KEY_MAX_CHARS = 400;
8176
+ var CYCLE_CHECK_STRIDE = 32;
8177
+ var MAX_CYCLE_PERIOD = 512;
8178
+ var MIN_CYCLE_SPAN = 512;
8179
+ var CYCLE_TAIL_CHARS = 4 * MAX_CYCLE_PERIOD;
8180
+ var MIN_REPEATED_LINE_CHARS = 2048;
8181
+ var MIN_REPEATED_LINE_COVERAGE = 0.6;
8182
+ var MIN_REPEATED_LINE_CONCENTRATION = 4;
8183
+ var MAX_DISTINCT_LINES = 5e3;
8184
+ var REASONING_LOOP_RESUME_TEXT = "[Forge] A gera\xE7\xE3o anterior foi interrompida porque o racioc\xEDnio estava a repetir-se sem avan\xE7ar. N\xE3o repitas o racioc\xEDnio anterior. Continua a tarefa a partir do ponto em que est\xE1: executa a pr\xF3xima a\xE7\xE3o ou d\xE1 a resposta final.";
8185
+ function trailingCycle(text, maxPeriod, minSpan) {
8186
+ for (let period = 1; period <= maxPeriod; period++) {
8187
+ if (text.length < period * 2) break;
8188
+ const need = Math.max(minSpan, 2 * period) - period;
8189
+ const limit = Math.min(text.length - period, need);
8190
+ let matched = 0;
8191
+ while (matched < limit && text[text.length - period - 1 - matched] === text[text.length - 1 - matched]) matched++;
8192
+ if (matched >= need && new Set(text.slice(text.length - period)).size >= 2) return matched + period;
8193
+ }
8194
+ return 0;
8195
+ }
8196
+ var ReasoningLoopDetector = class {
8197
+ tail = "";
8198
+ sinceCycleCheck = 0;
8199
+ partial = "";
8200
+ lines = /* @__PURE__ */ new Map();
8201
+ totalLineChars = 0;
8202
+ repeatedLineChars = 0;
8203
+ lineInstances = 0;
8204
+ rule;
8205
+ get tripped() {
8206
+ return this.rule;
8207
+ }
8208
+ push(text) {
8209
+ if (this.rule || !text) return this.rule;
8210
+ if (this.pushLines(text)) return this.rule = "reasoning-lines";
8211
+ this.tail = (this.tail + text).slice(-CYCLE_TAIL_CHARS);
8212
+ this.sinceCycleCheck += text.length;
8213
+ if (this.sinceCycleCheck < CYCLE_CHECK_STRIDE) return void 0;
8214
+ this.sinceCycleCheck = 0;
8215
+ if (trailingCycle(this.tail, MAX_CYCLE_PERIOD, MIN_CYCLE_SPAN) > 0) return this.rule = "reasoning-cycle";
8216
+ return void 0;
8217
+ }
8218
+ pushLines(text) {
8219
+ this.partial += text;
8220
+ let index;
8221
+ while ((index = this.partial.indexOf("\n")) >= 0) {
8222
+ this.addLine(this.partial.slice(0, index).trim());
8223
+ this.partial = this.partial.slice(index + 1);
8224
+ }
8225
+ if (this.partial.length > LINE_KEY_MAX_CHARS) this.partial = this.partial.slice(-LINE_KEY_MAX_CHARS);
8226
+ if (this.repeatedLineChars < MIN_REPEATED_LINE_CHARS || this.totalLineChars === 0) return false;
8227
+ if (this.repeatedLineChars / this.totalLineChars < MIN_REPEATED_LINE_COVERAGE) return false;
8228
+ return this.lineInstances / this.lines.size >= MIN_REPEATED_LINE_CONCENTRATION;
8229
+ }
8230
+ addLine(line) {
8231
+ if (line.length < LINE_MIN_CHARS) return;
8232
+ const key = line.slice(0, LINE_KEY_MAX_CHARS);
8233
+ const previous = this.lines.get(key) ?? 0;
8234
+ if (previous === 0 && this.lines.size >= MAX_DISTINCT_LINES) return;
8235
+ this.lines.set(key, previous + 1);
8236
+ this.totalLineChars += key.length;
8237
+ this.lineInstances += 1;
8238
+ if (previous === 1) this.repeatedLineChars += key.length * 2;
8239
+ else if (previous > 1) this.repeatedLineChars += key.length;
8240
+ }
8241
+ };
8242
+ var MAX_AUTOMATIC_RESUMES = 1;
8243
+ function createReasoningLoopGuard(client, log = console.error) {
8244
+ const sessions = /* @__PURE__ */ new Map();
8245
+ const session = (id) => {
8246
+ let state = sessions.get(id);
8247
+ if (!state) sessions.set(id, state = { parts: /* @__PURE__ */ new Map(), closedParts: /* @__PURE__ */ new Set(), interruptions: 0, interrupted: false, resumePending: false });
8248
+ return state;
8249
+ };
8250
+ const closeParts = (state) => {
8251
+ for (const partID of state.parts.keys()) state.closedParts.add(partID);
8252
+ state.parts.clear();
8253
+ };
8254
+ async function interrupt(sessionID, state, rule) {
8255
+ closeParts(state);
8256
+ state.interrupted = true;
8257
+ state.interruptions += 1;
8258
+ state.resumePending = state.interruptions <= MAX_AUTOMATIC_RESUMES;
8259
+ log(`[Forge reasoning guard] Repetitive reasoning interrupted (${rule}, interruption ${state.interruptions})`);
8260
+ try {
8261
+ await client.session.abort({ path: { id: sessionID } });
8262
+ } catch (error45) {
8263
+ state.resumePending = false;
8264
+ log(`[Forge reasoning guard] Abort failed: ${error45 instanceof Error ? error45.message : String(error45)}`);
8265
+ }
8266
+ }
8267
+ async function resume(sessionID, state) {
8268
+ state.resumePending = false;
8269
+ try {
8270
+ await client.session.promptAsync({
8271
+ path: { id: sessionID },
8272
+ body: {
8273
+ ...state.agent ? { agent: state.agent } : {},
8274
+ ...state.model ? { model: state.model } : {},
8275
+ parts: [{ type: "text", text: REASONING_LOOP_RESUME_TEXT }]
8276
+ }
8277
+ });
8278
+ } catch (error45) {
8279
+ log(`[Forge reasoning guard] Resume failed: ${error45 instanceof Error ? error45.message : String(error45)}`);
8280
+ }
8281
+ }
8282
+ async function reasoningText(sessionID, partID, text, absolute) {
8283
+ const state = session(sessionID);
8284
+ if (state.interrupted || state.closedParts.has(partID)) return;
8285
+ let part = state.parts.get(partID);
8286
+ if (!part) state.parts.set(partID, part = { detector: new ReasoningLoopDetector(), seen: 0 });
8287
+ const fresh = absolute ? text.slice(part.seen) : text;
8288
+ part.seen = absolute ? Math.max(part.seen, text.length) : part.seen + text.length;
8289
+ if (!fresh || part.detector.tripped) return;
8290
+ const rule = part.detector.push(fresh);
8291
+ if (rule) await interrupt(sessionID, state, rule);
8292
+ }
8293
+ return async ({ event }) => {
8294
+ try {
8295
+ const properties = event?.properties ?? {};
8296
+ if (event?.type === "message.part.updated") {
8297
+ const part = properties.part;
8298
+ if (part?.type !== "reasoning" || typeof part.id !== "string" || typeof part.sessionID !== "string") return;
8299
+ if (typeof part.text === "string") await reasoningText(part.sessionID, part.id, part.text, true);
8300
+ return;
8301
+ }
8302
+ if (event?.type === "message.part.delta") {
8303
+ const { sessionID, partID, field, delta } = properties;
8304
+ if (field !== "text" || typeof sessionID !== "string" || typeof partID !== "string" || typeof delta !== "string") return;
8305
+ if (!sessions.get(sessionID)?.parts.has(partID)) return;
8306
+ await reasoningText(sessionID, partID, delta, false);
8307
+ return;
8308
+ }
8309
+ if (event?.type === "message.updated") {
8310
+ const info = properties.info;
8311
+ if (info?.role !== "user" || typeof info.sessionID !== "string") return;
8312
+ const state = session(info.sessionID);
8313
+ if (typeof info.agent === "string") state.agent = info.agent;
8314
+ if (typeof info.model?.providerID === "string" && typeof info.model.modelID === "string") {
8315
+ state.model = { providerID: info.model.providerID, modelID: info.model.modelID };
8316
+ }
8317
+ return;
8318
+ }
8319
+ if (event?.type === "session.idle") {
8320
+ const sessionID = properties.sessionID;
8321
+ if (typeof sessionID !== "string") return;
8322
+ const state = sessions.get(sessionID);
8323
+ if (!state) return;
8324
+ closeParts(state);
8325
+ state.interrupted = false;
8326
+ if (state.resumePending) await resume(sessionID, state);
8327
+ return;
8328
+ }
8329
+ if (event?.type === "session.deleted") {
8330
+ const info = properties.info;
8331
+ if (typeof info?.id === "string") sessions.delete(info.id);
8332
+ }
8333
+ } catch (error45) {
8334
+ log(`[Forge reasoning guard] Event handling failed: ${error45 instanceof Error ? error45.message : String(error45)}`);
8335
+ }
8336
+ };
8337
+ }
8338
+
8173
8339
  // packages/cli/src/workPackSyncPlugin.ts
8174
8340
  var import_yaml = __toESM(require_dist(), 1);
8175
8341
  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";
@@ -20655,8 +20821,8 @@ function resolveOpenCodeDir(home, platform, env, exists2, pathApi) {
20655
20821
 
20656
20822
  // packages/cli/src/report.ts
20657
20823
  import os2 from "node:os";
20658
- var AGENT_VERSION = "0.1.0";
20659
- async function reportFailure(credentials, kind, error45, runtime = UNKNOWN_RUNTIME) {
20824
+ var CLI_AGENT_VERSION = "0.1.0";
20825
+ async function reportFailure(credentials, kind, error45, runtime = UNKNOWN_RUNTIME, agentVersion = CLI_AGENT_VERSION) {
20660
20826
  try {
20661
20827
  const message = error45 instanceof Error ? error45.message : String(error45);
20662
20828
  await fetch(`${credentials.forgeBaseUrl.replace(/\/$/, "")}/sync/report`, {
@@ -20665,7 +20831,7 @@ async function reportFailure(credentials, kind, error45, runtime = UNKNOWN_RUNTI
20665
20831
  authorization: `Bearer ${credentials.forgeApiKey}`,
20666
20832
  "content-type": "application/json",
20667
20833
  "x-forge-hostname": os2.hostname(),
20668
- "x-forge-agent-version": AGENT_VERSION
20834
+ "x-forge-agent-version": agentVersion
20669
20835
  },
20670
20836
  body: JSON.stringify({
20671
20837
  kind,
@@ -20679,7 +20845,7 @@ async function reportFailure(credentials, kind, error45, runtime = UNKNOWN_RUNTI
20679
20845
  console.error("[Forge] Failed to report failure to Forge server:", error46 instanceof Error ? error46.message : String(error46));
20680
20846
  }
20681
20847
  }
20682
- async function reportWorkPackObservations(credentials, kind, workPacks, runtime = UNKNOWN_RUNTIME) {
20848
+ async function reportWorkPackObservations(credentials, kind, workPacks, runtime = UNKNOWN_RUNTIME, agentVersion = CLI_AGENT_VERSION) {
20683
20849
  try {
20684
20850
  await fetch(`${credentials.forgeBaseUrl.replace(/\/$/, "")}/sync/report`, {
20685
20851
  method: "POST",
@@ -20687,7 +20853,7 @@ async function reportWorkPackObservations(credentials, kind, workPacks, runtime
20687
20853
  authorization: `Bearer ${credentials.forgeApiKey}`,
20688
20854
  "content-type": "application/json",
20689
20855
  "x-forge-hostname": os2.hostname(),
20690
- "x-forge-agent-version": AGENT_VERSION
20856
+ "x-forge-agent-version": agentVersion
20691
20857
  },
20692
20858
  body: JSON.stringify({ kind, ok: true, workPacks, ...runtime ? { runtime } : {} }),
20693
20859
  signal: AbortSignal.timeout(3e3)
@@ -24705,14 +24871,14 @@ function buildSyncFailureMessage(operation, details) {
24705
24871
  if (details.body) parts.push(`resposta=${JSON.stringify(details.body)}`);
24706
24872
  return parts.join(" | ");
24707
24873
  }
24708
- async function fetchManifest(credentials) {
24874
+ async function fetchManifest(credentials, agentVersion = "0.1.0") {
24709
24875
  let response;
24710
24876
  try {
24711
24877
  response = await fetch(`${credentials.forgeBaseUrl.replace(/\/$/, "")}/sync/manifest`, {
24712
24878
  headers: {
24713
24879
  authorization: `Bearer ${credentials.forgeApiKey}`,
24714
24880
  "x-forge-hostname": os4.hostname(),
24715
- "x-forge-agent-version": "0.1.0"
24881
+ "x-forge-agent-version": agentVersion
24716
24882
  },
24717
24883
  signal: AbortSignal.timeout(15e3)
24718
24884
  });
@@ -26245,7 +26411,7 @@ async function syncLocalWorker(paths, credentials, manifest) {
26245
26411
  }
26246
26412
 
26247
26413
  // packages/cli/src/workPackSyncPlugin.ts
26248
- var PLUGIN_VERSION = "0.1.39";
26414
+ var PLUGIN_VERSION = "0.1.41";
26249
26415
  var FORGE_DECISION_TIMEOUT_MS = 11e4;
26250
26416
  var STATUS_FILENAME = "work-pack-startup-status.json";
26251
26417
  var activeSync = /* @__PURE__ */ new Map();
@@ -26264,7 +26430,9 @@ var ForgeWorkPackSyncServer = async (_input, options) => {
26264
26430
  const shared = globalThis;
26265
26431
  const legacyOwners = shared[ownershipSymbol] ??= /* @__PURE__ */ new Set();
26266
26432
  const legacyOwnerKey = JSON.stringify([forgeBaseUrl, legacyPath]);
26433
+ const client = reasoningLoopGuardClient(_input);
26267
26434
  return {
26435
+ ...client ? { event: createReasoningLoopGuard(client) } : {},
26268
26436
  "tool.execute.after": async (input) => {
26269
26437
  if (input.tool !== "skill" || legacyOwners.has(legacyOwnerKey)) return;
26270
26438
  const slug = typeof input.args?.name === "string" ? input.args.name.trim().toLowerCase() : "";
@@ -26313,6 +26481,12 @@ var ForgeWorkPackSyncServer = async (_input, options) => {
26313
26481
  }
26314
26482
  };
26315
26483
  };
26484
+ function reasoningLoopGuardClient(input) {
26485
+ if (!input || typeof input !== "object" || !("client" in input)) return void 0;
26486
+ const client = input.client;
26487
+ if (typeof client?.session?.abort !== "function" || typeof client.session.promptAsync !== "function") return void 0;
26488
+ return client;
26489
+ }
26316
26490
  var ForgeDecisionRejectedError = class extends Error {
26317
26491
  };
26318
26492
  function createForgeImageTool(forgeBaseUrl, gatewayBaseUrl, paths) {
@@ -26645,11 +26819,11 @@ async function synchronizeAtStartup(forgeBaseUrl, input, localConfig) {
26645
26819
  try {
26646
26820
  await retireDebugCapture(paths);
26647
26821
  credentials = await readForgeCredentials(paths, forgeBaseUrl);
26648
- const manifest = await fetchManifest(credentials);
26822
+ const manifest = await fetchManifest(credentials, PLUGIN_VERSION);
26649
26823
  decisionBaseUrl = resolveDecisionBaseUrl(manifest.gatewayBaseUrl, forgeBaseUrl);
26650
26824
  forgeConfigVerified = true;
26651
26825
  const result = localConfig ? await syncLocalWorker(paths, credentials, manifest) : await applyWorkPackManifest(paths, credentials, manifest, {});
26652
- await reportWorkPackObservations(credentials, "sync", result.workPackObservations, runtime);
26826
+ await reportWorkPackObservations(credentials, "sync", result.workPackObservations, runtime, PLUGIN_VERSION);
26653
26827
  const failures = result.workPacks.outcomes.filter(
26654
26828
  (outcome) => outcome.status === "failed" || outcome.status === "recovery-uncertain"
26655
26829
  );
@@ -26677,7 +26851,7 @@ async function synchronizeAtStartup(forgeBaseUrl, input, localConfig) {
26677
26851
  attemptedAt: (/* @__PURE__ */ new Date()).toISOString(),
26678
26852
  message
26679
26853
  }).catch(() => void 0);
26680
- if (credentials) await reportFailure(credentials, "sync", new Error(message), runtime);
26854
+ if (credentials) await reportFailure(credentials, "sync", new Error(message), runtime, PLUGIN_VERSION);
26681
26855
  if (localConfig && !forgeConfigVerified && credentials) {
26682
26856
  decisionBaseUrl = await savedGatewayBaseUrl(paths, credentials, forgeBaseUrl) ?? decisionBaseUrl;
26683
26857
  }
package/dist/repair.js CHANGED
@@ -401,7 +401,7 @@ var DEVICE_ENROLLMENT_PROTOCOL_VERSION = 1;
401
401
  // packages/shared/src/contracts/settings.ts
402
402
  var DOCUMENT_READER_AGENT = "document-reader";
403
403
  var OPENROUTER_ALIAS_PROVIDER_NAME = "OpenRouter (via Forge)";
404
- var WORK_PACK_SYNC_PLUGIN_VERSION = "0.1.39";
404
+ var WORK_PACK_SYNC_PLUGIN_VERSION = "0.1.41";
405
405
  var WORK_PACK_SYNC_PLUGIN_PACKAGE = `minimal-forge-work-pack-sync@${WORK_PACK_SYNC_PLUGIN_VERSION}`;
406
406
  var WORK_PACK_SYNC_PLUGIN_FILENAME = `minimal-forge-work-pack-sync-${WORK_PACK_SYNC_PLUGIN_VERSION}.tgz`;
407
407
  var FIRECRAWL_KEYLESS_MCP_NAME = "firecrawl";
@@ -4187,14 +4187,14 @@ function buildSyncFailureMessage(operation, details) {
4187
4187
  if (details.body) parts.push(`resposta=${JSON.stringify(details.body)}`);
4188
4188
  return parts.join(" | ");
4189
4189
  }
4190
- async function fetchManifest(credentials) {
4190
+ async function fetchManifest(credentials, agentVersion = "0.1.0") {
4191
4191
  let response;
4192
4192
  try {
4193
4193
  response = await fetch(`${credentials.forgeBaseUrl.replace(/\/$/, "")}/sync/manifest`, {
4194
4194
  headers: {
4195
4195
  authorization: `Bearer ${credentials.forgeApiKey}`,
4196
4196
  "x-forge-hostname": os2.hostname(),
4197
- "x-forge-agent-version": "0.1.0"
4197
+ "x-forge-agent-version": agentVersion
4198
4198
  },
4199
4199
  signal: AbortSignal.timeout(15e3)
4200
4200
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "minimal-forge-work-pack-sync",
3
- "version": "0.1.39",
3
+ "version": "0.1.41",
4
4
  "description": "Minimal Forge Work Pack startup synchronization for OpenCode and OpenWork.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {