@wrongstack/core 0.73.1 → 0.77.0

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 (41) hide show
  1. package/dist/{agent-bridge-C0Ze7Ldm.d.ts → agent-bridge-EWdqs8v6.d.ts} +1 -1
  2. package/dist/{agent-subagent-runner-BmITbs1Q.d.ts → agent-subagent-runner-D8qW8OSC.d.ts} +2 -2
  3. package/dist/coordination/index.d.ts +7 -7
  4. package/dist/coordination/index.js +64 -6
  5. package/dist/coordination/index.js.map +1 -1
  6. package/dist/defaults/index.d.ts +11 -11
  7. package/dist/defaults/index.js +107 -45
  8. package/dist/defaults/index.js.map +1 -1
  9. package/dist/{events-BBAlxBuw.d.ts → events-CYaoLN5_.d.ts} +37 -0
  10. package/dist/execution/index.d.ts +6 -6
  11. package/dist/extension/index.d.ts +2 -2
  12. package/dist/{index-yQbZ2NQx.d.ts → index-DIxjTOga.d.ts} +2 -2
  13. package/dist/{index-BN6i2Nfg.d.ts → index-Dsda0uCn.d.ts} +1 -1
  14. package/dist/index.d.ts +96 -23
  15. package/dist/index.js +234 -25
  16. package/dist/index.js.map +1 -1
  17. package/dist/infrastructure/index.d.ts +3 -3
  18. package/dist/infrastructure/index.js +16 -2
  19. package/dist/infrastructure/index.js.map +1 -1
  20. package/dist/kernel/index.d.ts +3 -3
  21. package/dist/kernel/index.js.map +1 -1
  22. package/dist/{logger-bOzkF5LL.d.ts → logger-BppKxDqZ.d.ts} +9 -0
  23. package/dist/{multi-agent-coordinator-BSBbZt0e.d.ts → multi-agent-coordinator-DpbG3wiy.d.ts} +1 -1
  24. package/dist/{null-fleet-bus-BCIRT_nV.d.ts → null-fleet-bus-u5ys3lW_.d.ts} +13 -4
  25. package/dist/observability/index.d.ts +1 -1
  26. package/dist/{parallel-eternal-engine-CjAYGaCw.d.ts → parallel-eternal-engine-Dn0P8Pbj.d.ts} +3 -3
  27. package/dist/{path-resolver-BnqXa9Ze.d.ts → path-resolver-B32v2JIq.d.ts} +1 -1
  28. package/dist/{plan-templates-DBgrTGPu.d.ts → plan-templates-BcUwLlMQ.d.ts} +7 -2
  29. package/dist/{provider-runner-n3KkHT_w.d.ts → provider-runner-CSi_7l0h.d.ts} +1 -1
  30. package/dist/sdd/index.d.ts +3 -3
  31. package/dist/storage/index.d.ts +3 -3
  32. package/dist/storage/index.js +22 -6
  33. package/dist/storage/index.js.map +1 -1
  34. package/dist/types/index.d.ts +10 -10
  35. package/dist/types/index.js +16 -2
  36. package/dist/types/index.js.map +1 -1
  37. package/dist/utils/index.d.ts +1 -1
  38. package/dist/utils/index.js +12 -2
  39. package/dist/utils/index.js.map +1 -1
  40. package/dist/{wstack-paths-eMXnY1_X.d.ts → wstack-paths-D7evAFWM.d.ts} +8 -1
  41. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -5,7 +5,7 @@ import { readFile, readdir, stat, mkdir } from 'fs/promises';
5
5
  import * as path6 from 'path';
6
6
  import { join, extname, relative, isAbsolute, resolve, sep } from 'path';
7
7
  import * as fs2 from 'fs';
8
- import * as os6 from 'os';
8
+ import * as os7 from 'os';
9
9
  import { execFile, spawn } from 'child_process';
10
10
  import { promisify } from 'util';
11
11
  import { EventEmitter } from 'events';
@@ -1404,11 +1404,13 @@ var DefaultLogger = class _DefaultLogger {
1404
1404
  file;
1405
1405
  bindings;
1406
1406
  pretty;
1407
+ stderr;
1407
1408
  constructor(opts = {}) {
1408
1409
  this.level = opts.level ?? process.env.WRONGSTACK_LOG_LEVEL ?? "info";
1409
1410
  this.file = opts.file;
1410
1411
  this.bindings = opts.bindings ?? {};
1411
1412
  this.pretty = opts.pretty ?? true;
1413
+ this.stderr = opts.stderr !== false;
1412
1414
  if (this.file) {
1413
1415
  try {
1414
1416
  fs2.mkdirSync(path6.dirname(this.file), { recursive: true });
@@ -1436,6 +1438,7 @@ var DefaultLogger = class _DefaultLogger {
1436
1438
  level: this.level,
1437
1439
  file: this.file,
1438
1440
  pretty: this.pretty,
1441
+ stderr: this.stderr,
1439
1442
  bindings: { ...this.bindings, ...bindings }
1440
1443
  });
1441
1444
  }
@@ -1455,6 +1458,7 @@ var DefaultLogger = class _DefaultLogger {
1455
1458
  } catch {
1456
1459
  }
1457
1460
  }
1461
+ if (!this.stderr) return;
1458
1462
  if (r <= LEVEL_RANK.warn || this.level === "debug" || this.level === "trace") {
1459
1463
  const head = `${color.dim(ts)} ${COLORS[level](level.toUpperCase().padEnd(5))} ${msg}`;
1460
1464
  if (ctx !== void 0) {
@@ -2000,7 +2004,11 @@ var PROJECT_MARKERS = [
2000
2004
  "go.mod",
2001
2005
  "Cargo.toml",
2002
2006
  "pyproject.toml",
2003
- ".wrongstack"
2007
+ // Use AGENTS.md, not the bare .wrongstack directory. A bare .wrongstack/
2008
+ // directory can be the global config directory (~/.wrongstack), which is
2009
+ // NOT a project marker. Only .wrongstack/AGENTS.md signals a real
2010
+ // WrongStack project.
2011
+ ".wrongstack/AGENTS.md"
2004
2012
  ];
2005
2013
  var DefaultPathResolver = class {
2006
2014
  projectRoot;
@@ -2012,7 +2020,12 @@ var DefaultPathResolver = class {
2012
2020
  detectProjectRoot(start) {
2013
2021
  let dir = path6.resolve(start);
2014
2022
  const root = path6.parse(dir).root;
2023
+ const home = path6.resolve(os7.homedir());
2024
+ const startPath = path6.resolve(start);
2015
2025
  while (dir !== root) {
2026
+ if (dir === home && dir !== startPath) {
2027
+ break;
2028
+ }
2016
2029
  for (const marker of PROJECT_MARKERS) {
2017
2030
  try {
2018
2031
  fs2.accessSync(path6.join(dir, marker));
@@ -2024,7 +2037,7 @@ var DefaultPathResolver = class {
2024
2037
  if (parent === dir) break;
2025
2038
  dir = parent;
2026
2039
  }
2027
- return path6.resolve(start);
2040
+ return startPath;
2028
2041
  }
2029
2042
  resolve(input) {
2030
2043
  const abs = path6.isAbsolute(input) ? input : path6.resolve(this.cwd, input);
@@ -4526,11 +4539,20 @@ function unifiedDiff(oldText, newText, opts = {}) {
4526
4539
  function projectHash(absRoot) {
4527
4540
  return createHash("sha256").update(path6.resolve(absRoot)).digest("hex").slice(0, 12);
4528
4541
  }
4542
+ function projectSlug(absRoot) {
4543
+ const base = slugify(path6.basename(absRoot));
4544
+ const hash = createHash("sha256").update(path6.resolve(absRoot)).digest("hex").slice(0, 6);
4545
+ return `${base}-${hash}`;
4546
+ }
4547
+ function slugify(name) {
4548
+ return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40) || "project";
4549
+ }
4529
4550
  function resolveWstackPaths(opts) {
4530
- const home = opts.userHome ?? os6.homedir();
4551
+ const home = opts.userHome ?? os7.homedir();
4531
4552
  const globalRoot = opts.globalRoot ?? path6.join(home, ".wrongstack");
4532
4553
  const hash = projectHash(opts.projectRoot);
4533
- const projectDir = path6.join(globalRoot, "projects", hash);
4554
+ const slug = projectSlug(opts.projectRoot);
4555
+ const projectDir = path6.join(globalRoot, "projects", slug);
4534
4556
  return {
4535
4557
  globalRoot,
4536
4558
  configDir: globalRoot,
@@ -4555,6 +4577,7 @@ function resolveWstackPaths(opts) {
4555
4577
  inProjectSkills: path6.join(opts.projectRoot, ".wrongstack", "skills"),
4556
4578
  inProjectWorktrees: path6.join(opts.projectRoot, ".wrongstack", "worktrees"),
4557
4579
  projectHash: hash,
4580
+ projectSlug: slug,
4558
4581
  projectGoal: path6.join(projectDir, "goal.json"),
4559
4582
  projectSpecs: path6.join(projectDir, "specs"),
4560
4583
  projectTaskGraphs: path6.join(projectDir, "task-graphs"),
@@ -4877,6 +4900,16 @@ function mergeCustomModelDefs(providerCustomModels, configModels) {
4877
4900
 
4878
4901
  // src/storage/session-store.ts
4879
4902
  init_atomic_write();
4903
+ function sanitizeModel(model) {
4904
+ return model.replace(/[^a-zA-Z0-9_-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "").slice(0, 40);
4905
+ }
4906
+ function generateSessionId(startedAt, model) {
4907
+ const date = startedAt.slice(0, 10);
4908
+ const time = startedAt.slice(11, 19).replace(/:/g, "-");
4909
+ const suffix = randomBytes(2).toString("hex");
4910
+ const modelPart = model ? `_${sanitizeModel(model)}` : "";
4911
+ return `${date}/${time}Z${modelPart}_${suffix}`;
4912
+ }
4880
4913
  var DefaultSessionStore = class {
4881
4914
  dir;
4882
4915
  events;
@@ -4890,15 +4923,21 @@ var DefaultSessionStore = class {
4890
4923
  sessionPath(id, ext) {
4891
4924
  return path6.join(this.dir, `${id}${ext}`);
4892
4925
  }
4893
- async ensureShardDir(_id) {
4894
- await ensureDir(this.dir);
4895
- return this.dir;
4926
+ /**
4927
+ * Ensure the directory implied by the session ID exists. When the ID
4928
+ * contains a date prefix like `2026-06-06/...`, this creates the date
4929
+ * subdirectory so sessions group naturally by day.
4930
+ */
4931
+ async ensureShardDir(id) {
4932
+ const dirPath = path6.dirname(path6.join(this.dir, id));
4933
+ await ensureDir(dirPath);
4934
+ return dirPath;
4896
4935
  }
4897
4936
  async create(meta) {
4898
4937
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
4899
- const id = meta.id ?? `${startedAt.replace(/[:.]/g, "-")}-${randomBytes(2).toString("hex")}`;
4938
+ const id = meta.id && meta.id.length > 0 ? meta.id : generateSessionId(startedAt, meta.model ?? meta.provider);
4900
4939
  const shardDir = await this.ensureShardDir(id);
4901
- const file = path6.join(shardDir, `${id}.jsonl`);
4940
+ const file = path6.join(shardDir, `${path6.basename(id)}.jsonl`);
4902
4941
  let handle;
4903
4942
  try {
4904
4943
  handle = await fsp3.open(file, "a", 384);
@@ -6244,7 +6283,7 @@ var RecoveryLock = class {
6244
6283
  constructor(opts) {
6245
6284
  this.file = path6.join(opts.dir, LOCK_FILE);
6246
6285
  this.pid = opts.pid ?? process.pid;
6247
- this.hostname = opts.hostname ?? os6.hostname();
6286
+ this.hostname = opts.hostname ?? os7.hostname();
6248
6287
  this.maxAgeMs = opts.maxAgeMs ?? DEFAULT_MAX_AGE_MS;
6249
6288
  this.sessionStore = opts.sessionStore;
6250
6289
  this.probe = opts.isPidAlive ?? defaultIsPidAlive;
@@ -6572,7 +6611,7 @@ async function loadTodosCheckpoint(filePath) {
6572
6611
  const parsed = JSON.parse(raw);
6573
6612
  if (parsed?.version !== 1 || !Array.isArray(parsed.todos)) return null;
6574
6613
  return parsed.todos.filter(
6575
- (t2) => !!t2 && typeof t2.id === "string" && typeof t2.content === "string" && typeof t2.status === "string"
6614
+ (t2) => !!t2 && typeof t2.id === "string" && typeof t2.content === "string" && typeof t2.status === "string" && (t2.activeForm === void 0 || typeof t2.activeForm === "string")
6576
6615
  );
6577
6616
  } catch {
6578
6617
  return null;
@@ -8868,7 +8907,7 @@ init_atomic_write();
8868
8907
  var MAX_JOURNAL_ENTRIES = 500;
8869
8908
  function goalFilePath(projectRoot) {
8870
8909
  const hash = createHash("sha256").update(path6.resolve(projectRoot)).digest("hex").slice(0, 12);
8871
- return path6.join(os6.homedir(), ".wrongstack", "projects", hash, "goal.json");
8910
+ return path6.join(os7.homedir(), ".wrongstack", "projects", hash, "goal.json");
8872
8911
  }
8873
8912
  async function loadGoal(filePath) {
8874
8913
  let raw;
@@ -16628,6 +16667,7 @@ function createDelegateTool(opts) {
16628
16667
  if (typeof i.task !== "string" || !i.task.trim()) {
16629
16668
  return { ok: false, error: "`task` is required." };
16630
16669
  }
16670
+ const target = i.role ?? i.name ?? "subagent";
16631
16671
  try {
16632
16672
  let director = await opts.host.ensureDirector();
16633
16673
  if (!director) {
@@ -16688,6 +16728,7 @@ function createDelegateTool(opts) {
16688
16728
  if (!cfg.timeoutMs) {
16689
16729
  cfg.timeoutMs = Math.max(3e4, timeoutMs - SUBAGENT_TIMEOUT_BUFFER_MS);
16690
16730
  }
16731
+ opts.events?.emit("delegate.started", { target, task: i.task });
16691
16732
  const subagentId = await director.spawn(cfg);
16692
16733
  const taskId = await director.assign({
16693
16734
  id: `${randomUUID()}`,
@@ -16722,6 +16763,17 @@ function createDelegateTool(opts) {
16722
16763
  });
16723
16764
  if ("__timeout" in result) {
16724
16765
  const partial2 = await readSubagentPartial(opts, subagentId);
16766
+ opts.events?.emit("delegate.completed", {
16767
+ target,
16768
+ task: i.task,
16769
+ ok: false,
16770
+ status: "host_timeout",
16771
+ summary: `[${target}] timed out \u2014 no result within ${Math.round(timeoutMs / 1e3)}s`,
16772
+ durationMs: timeoutMs,
16773
+ iterations: partial2?.events ?? 0,
16774
+ toolCalls: partial2?.toolUsesObserved ?? 0,
16775
+ subagentId
16776
+ });
16725
16777
  return {
16726
16778
  ok: false,
16727
16779
  stopReason: "host_timeout",
@@ -16738,6 +16790,24 @@ function createDelegateTool(opts) {
16738
16790
  const retryable = result.error?.retryable;
16739
16791
  const backoffMs = result.error?.backoffMs;
16740
16792
  const summary = buildDelegateSummary(i.role, result);
16793
+ let costUsd;
16794
+ try {
16795
+ costUsd = dir.snapshot().perSubagent[result.subagentId]?.cost;
16796
+ } catch {
16797
+ costUsd = void 0;
16798
+ }
16799
+ opts.events?.emit("delegate.completed", {
16800
+ target,
16801
+ task: i.task,
16802
+ ok: result.status === "success",
16803
+ status: result.status,
16804
+ summary,
16805
+ durationMs: result.durationMs,
16806
+ iterations: result.iterations,
16807
+ toolCalls: result.toolCalls,
16808
+ costUsd,
16809
+ subagentId: result.subagentId
16810
+ });
16741
16811
  return {
16742
16812
  ok: result.status === "success",
16743
16813
  status: result.status,
@@ -16759,10 +16829,21 @@ function createDelegateTool(opts) {
16759
16829
  summary
16760
16830
  };
16761
16831
  } catch (err) {
16832
+ const message = err instanceof Error ? err.message : String(err);
16833
+ opts.events?.emit("delegate.completed", {
16834
+ target,
16835
+ task: i.task,
16836
+ ok: false,
16837
+ status: "error",
16838
+ summary: `[${target}] failed \u2014 ${message}`,
16839
+ durationMs: 0,
16840
+ iterations: 0,
16841
+ toolCalls: 0
16842
+ });
16762
16843
  return {
16763
16844
  ok: false,
16764
16845
  stopReason: "error",
16765
- error: err instanceof Error ? err.message : String(err)
16846
+ error: message
16766
16847
  };
16767
16848
  }
16768
16849
  }
@@ -20810,7 +20891,7 @@ async function downloadGitHubTarball(parsed) {
20810
20891
  `Tarball too large (${(Number.parseInt(contentLength, 10) / 1024 / 1024).toFixed(1)}MB). Max: ${MAX_TARBALL_SIZE / 1024 / 1024}MB`
20811
20892
  );
20812
20893
  }
20813
- const tempDir = await fsp3.mkdtemp(path6.join(os6.tmpdir(), "wskill-"));
20894
+ const tempDir = await fsp3.mkdtemp(path6.join(os7.tmpdir(), "wskill-"));
20814
20895
  try {
20815
20896
  if (!response.body) {
20816
20897
  throw new Error("Empty response body from GitHub API");
@@ -24257,16 +24338,16 @@ Use \`/security report <number>\` to view a specific report.` };
24257
24338
  }
24258
24339
  const index = Number.parseInt(reportId, 10) - 1;
24259
24340
  if (!Number.isNaN(index) && reports[index]) {
24260
- const { readFile: readFile37 } = await import('fs/promises');
24261
- const content = await readFile37(join(reportsDir, reports[index]), "utf-8");
24341
+ const { readFile: readFile38 } = await import('fs/promises');
24342
+ const content = await readFile38(join(reportsDir, reports[index]), "utf-8");
24262
24343
  return { message: `# Security Report
24263
24344
 
24264
24345
  ${content}` };
24265
24346
  }
24266
24347
  const match = reports.find((r) => r.includes(reportId));
24267
24348
  if (match) {
24268
- const { readFile: readFile37 } = await import('fs/promises');
24269
- const content = await readFile37(join(reportsDir, match), "utf-8");
24349
+ const { readFile: readFile38 } = await import('fs/promises');
24350
+ const content = await readFile38(join(reportsDir, match), "utf-8");
24270
24351
  return { message: `# Security Report
24271
24352
 
24272
24353
  ${content}` };
@@ -26071,12 +26152,14 @@ async function bootConfig(options = {}) {
26071
26152
  const cwd = typeof flags["cwd"] === "string" ? path6.resolve(flags["cwd"]) : process.cwd();
26072
26153
  const pathResolver = new DefaultPathResolver(cwd);
26073
26154
  const projectRoot = pathResolver.projectRoot;
26074
- const userHome = os6.homedir();
26155
+ const userHome = os7.homedir();
26075
26156
  const wpaths = resolveWstackPaths({ projectRoot, userHome });
26076
26157
  await fsp3.mkdir(wpaths.globalRoot, { recursive: true });
26077
26158
  await fsp3.mkdir(wpaths.projectDir, { recursive: true });
26078
26159
  await fsp3.mkdir(wpaths.projectSessions, { recursive: true });
26079
26160
  await writeProjectMeta(wpaths, projectRoot);
26161
+ cleanupStaleProjects(wpaths).catch(() => {
26162
+ });
26080
26163
  const vault = new DefaultSecretVault({ keyFile: wpaths.secretsKey });
26081
26164
  for (const file of [wpaths.globalConfig, wpaths.projectLocalConfig]) {
26082
26165
  try {
@@ -26142,6 +26225,7 @@ async function writeProjectMeta(paths, projectRoot) {
26142
26225
  await fsp3.mkdir(paths.projectDir, { recursive: true });
26143
26226
  const meta = {
26144
26227
  hash: paths.projectHash,
26228
+ slug: paths.projectSlug,
26145
26229
  root: projectRoot,
26146
26230
  lastSeen: (/* @__PURE__ */ new Date()).toISOString()
26147
26231
  };
@@ -26149,6 +26233,31 @@ async function writeProjectMeta(paths, projectRoot) {
26149
26233
  } catch {
26150
26234
  }
26151
26235
  }
26236
+ async function cleanupStaleProjects(wpaths) {
26237
+ const projectsRoot = path6.dirname(wpaths.projectDir);
26238
+ let entries;
26239
+ try {
26240
+ entries = await fsp3.readdir(projectsRoot, { withFileTypes: true });
26241
+ } catch {
26242
+ return;
26243
+ }
26244
+ for (const entry of entries) {
26245
+ if (!entry.isDirectory()) continue;
26246
+ const metaPath = path6.join(projectsRoot, entry.name, "meta.json");
26247
+ try {
26248
+ const raw = await fsp3.readFile(metaPath, "utf8");
26249
+ const meta = JSON.parse(raw);
26250
+ if (typeof meta.root === "string") {
26251
+ try {
26252
+ await fsp3.access(meta.root);
26253
+ } catch {
26254
+ await fsp3.rm(path6.join(projectsRoot, entry.name), { recursive: true, force: true });
26255
+ }
26256
+ }
26257
+ } catch {
26258
+ }
26259
+ }
26260
+ }
26152
26261
 
26153
26262
  // src/core/conversation-state.ts
26154
26263
  var ConversationState = class {
@@ -26187,9 +26296,11 @@ var ConversationState = class {
26187
26296
  this.emit({ kind: "messages_replaced", messages: [...messages] });
26188
26297
  }
26189
26298
  replaceTodos(todos) {
26299
+ const allDone = todos.length > 0 && todos.every((t2) => t2.status === "completed");
26300
+ const effective = allDone ? [] : todos;
26190
26301
  this.ctx.todos.length = 0;
26191
- this.ctx.todos.splice(0, 0, ...todos);
26192
- this.emit({ kind: "todos_replaced", todos: [...todos] });
26302
+ this.ctx.todos.splice(0, 0, ...effective);
26303
+ this.emit({ kind: "todos_replaced", todos: [...effective] });
26193
26304
  }
26194
26305
  setMeta(key, value) {
26195
26306
  this.ctx.meta[key] = value;
@@ -26813,7 +26924,7 @@ summarize it, and let the tool result hold only the summary.`);
26813
26924
  const cached = this.envCacheByRoot.get(ctx.projectRoot);
26814
26925
  if (cached) return cached;
26815
26926
  const today = this.opts.todayIso ?? (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
26816
- const platform2 = `${os6.platform()} ${os6.release()}`;
26927
+ const platform2 = `${os7.platform()} ${os7.release()}`;
26817
26928
  const shell = process.env.SHELL ?? process.env.ComSpec ?? "unknown";
26818
26929
  const node = process.version;
26819
26930
  const isGit = await this.dirExists(path6.join(ctx.projectRoot, ".git"));
@@ -27752,6 +27863,104 @@ function wrapApiForCapabilityCheck(plugin, api, log, enforce = false) {
27752
27863
  });
27753
27864
  }
27754
27865
 
27866
+ // src/execution/prompt-enhancer.ts
27867
+ var ENHANCER_SYSTEM_PROMPT = `You are a request refiner embedded in a coding agent. Your ONLY job is to rewrite the user's message into a single, clearer, unambiguous instruction that the coding agent can act on confidently.
27868
+
27869
+ Rules:
27870
+ - Preserve the user's intent and scope EXACTLY. Do not add new requirements, features, constraints, or steps the user did not ask for. Do not remove anything they did ask for.
27871
+ - Do NOT answer, solve, or perform the request. Only restate it more clearly.
27872
+ - Keep all concrete details verbatim: file paths, identifiers, code, error text, numbers, names, URLs.
27873
+ - Resolve obvious ambiguity by making the implied subject explicit, not by inventing specifics. If something is genuinely unspecified, leave it general rather than guessing.
27874
+ - Be concise: one tight instruction (a few sentences at most). No preamble, no explanation, no quotes, no markdown headers.
27875
+ - If the message is already clear and complete, return it essentially unchanged.
27876
+ - Preserve the user's language (if they wrote in Turkish, refine in Turkish).
27877
+
27878
+ When earlier conversation turns are provided, they are CONTEXT ONLY. Use them to resolve references in the user's latest message \u2014 "it", "that", "the same", "the other one", "this file", "again" \u2014 so the refined instruction is self-contained. Refine ONLY the user's latest message; do not answer it, do not act on or restate earlier turns, and do not summarize the conversation.
27879
+
27880
+ Output ONLY the refined request text \u2014 nothing else.`;
27881
+ var AFFIRMATION_RE = /^(y|n|yes|no|yep|nope|ok|okay|sure|go|go ahead|continue|proceed|stop|cancel|done|next|skip|retry|again|please do|do it)\b[.! ]*$/i;
27882
+ function shouldEnhance(text) {
27883
+ const t2 = text.trim();
27884
+ if (!t2) return false;
27885
+ if (t2.startsWith("/")) return false;
27886
+ if (t2.length < 12) return false;
27887
+ if (AFFIRMATION_RE.test(t2)) return false;
27888
+ if (/^[\d\s.,]+$/.test(t2)) return false;
27889
+ const words = t2.split(/\s+/).filter(Boolean);
27890
+ if (words.length < 3) return false;
27891
+ return true;
27892
+ }
27893
+ function normalizedEqual(a, b) {
27894
+ const norm = (s) => s.trim().replace(/\s+/g, " ").toLowerCase();
27895
+ return norm(a) === norm(b);
27896
+ }
27897
+ function buildRefinerInput(text, history) {
27898
+ if (!history || history.length === 0) return text;
27899
+ const lines = history.map((t2) => `${t2.role === "user" ? "User" : "Assistant"}: ${t2.text}`);
27900
+ return [
27901
+ "Recent conversation (context only \u2014 do not act on it):",
27902
+ ...lines,
27903
+ "",
27904
+ "Latest message to refine:",
27905
+ text
27906
+ ].join("\n");
27907
+ }
27908
+ async function enhanceUserPrompt(opts) {
27909
+ const { provider, model, text } = opts;
27910
+ const timeoutMs = opts.timeoutMs ?? 25e3;
27911
+ const maxTokens = opts.maxTokens ?? 2048;
27912
+ const req = {
27913
+ model,
27914
+ system: [{ type: "text", text: ENHANCER_SYSTEM_PROMPT }],
27915
+ messages: [{ role: "user", content: buildRefinerInput(text, opts.history) }],
27916
+ maxTokens
27917
+ // NOTE: deliberately NO `temperature`. The main agent loop never sets it,
27918
+ // and reasoning models (DeepSeek reasoner, o1/o3, …) return HTTP 400 when
27919
+ // `temperature` is present — which would make every refine call fail and
27920
+ // silently fall back to the original (no panel shown).
27921
+ };
27922
+ const timer = new AbortController();
27923
+ const to = setTimeout(() => timer.abort(new Error("enhancer timeout")), timeoutMs);
27924
+ const signal = opts.signal ? AbortSignal.any([opts.signal, timer.signal]) : timer.signal;
27925
+ try {
27926
+ const res = await provider.complete(req, { signal });
27927
+ const refined = res.content.filter(isTextBlock).map((b) => b.text).join("\n").trim();
27928
+ if (!refined) {
27929
+ opts.onError?.("model returned no text");
27930
+ return null;
27931
+ }
27932
+ return refined;
27933
+ } catch (err) {
27934
+ if (opts.signal?.aborted) return null;
27935
+ if (timer.signal.aborted) {
27936
+ opts.onError?.(`timed out after ${Math.round(timeoutMs / 1e3)}s`);
27937
+ return null;
27938
+ }
27939
+ opts.onError?.(err instanceof Error ? err.message : String(err));
27940
+ return null;
27941
+ } finally {
27942
+ clearTimeout(to);
27943
+ }
27944
+ }
27945
+ function messageText(content) {
27946
+ if (typeof content === "string") return content;
27947
+ return content.filter(isTextBlock).map((b) => b.text).join("\n").trim();
27948
+ }
27949
+ function recentTextTurns(messages, maxTurns = 6, maxChars = 1500) {
27950
+ const turns = [];
27951
+ for (let i = messages.length - 1; i >= 0 && turns.length < maxTurns; i--) {
27952
+ const m = messages[i];
27953
+ if (!m || m.role !== "user" && m.role !== "assistant") continue;
27954
+ const text = messageText(m.content);
27955
+ if (!text) continue;
27956
+ turns.unshift({
27957
+ role: m.role,
27958
+ text: text.length > maxChars ? `${text.slice(0, maxChars - 1)}\u2026` : text
27959
+ });
27960
+ }
27961
+ return turns;
27962
+ }
27963
+
27755
27964
  // src/autophase/phase-graph-builder.ts
27756
27965
  var PhaseGraphBuilder = class _PhaseGraphBuilder {
27757
27966
  constructor(opts) {
@@ -30552,7 +30761,7 @@ function createSkillsPlugin(opts) {
30552
30761
  };
30553
30762
  }
30554
30763
  function makeInstaller(skillLoader, projectRoot) {
30555
- const globalRoot = path6.join(os6.homedir(), ".wrongstack");
30764
+ const globalRoot = path6.join(os7.homedir(), ".wrongstack");
30556
30765
  return new SkillInstaller({
30557
30766
  manifestPath: path6.join(globalRoot, "installed-skills.json"),
30558
30767
  projectSkillsDir: path6.join(projectRoot, ".wrongstack", "skills"),
@@ -30903,6 +31112,6 @@ ${formatPlan(updated)}`
30903
31112
  };
30904
31113
  }
30905
31114
 
30906
- export { ACP_AGENTS, AGENTS_BY_PHASE, AGENT_CATALOG, AISpecBuilder, ALL_AGENT_DEFINITIONS, ALL_FLEET_AGENTS, ALL_SYNC_CATEGORIES, AUDIT_LOG_AGENT, Agent, AgentError, AnnotationsStore, AutoApprovePermissionPolicy, AutoCompactionMiddleware, AutoExecutor, AutoPhasePlanner, AutoPhaseRunner, AutonomousRunner, BUG_HUNTER_AGENT, BrainDecisionQueue, BudgetExceededError, CONTEXT_WINDOW_MODES, CORE_RECONSTRUCT_EVENTS, CheckpointManager, CloudSync, CollaborationBus, ConfigError, ConfigMigrationError, Container, Context, ConversationState, DEFAULT_AUTONOMY_CONFIG, DEFAULT_CONFIG_MIGRATIONS, DEFAULT_CONTEXT_CONFIG, DEFAULT_CONTEXT_WINDOW_MODE_ID, DEFAULT_DIRECTOR_PREAMBLE, DEFAULT_DISPATCH_ROLE, DEFAULT_MAX_ITERATIONS, DEFAULT_MODES, DEFAULT_RECOVERY_STRATEGIES, DEFAULT_SESSION_LOGGING_CONFIG, DEFAULT_SPEC_TEMPLATE, DEFAULT_SUBAGENT_BASELINE, DEFAULT_TOOLS_CONFIG, DefaultAttachmentStore, DefaultBrainArbiter, DefaultConfigLoader, DefaultConfigStore, DefaultErrorHandler, DefaultHealthRegistry, DefaultLogger, DefaultMemoryStore, DefaultModeStore, DefaultModelsRegistry, DefaultMultiAgentCoordinator, DefaultPathResolver, DefaultPermissionPolicy, DefaultPluginAPI, DefaultPromptStore, DefaultProviderRunner, DefaultRetryPolicy, DefaultSecretScrubber, DefaultSecretVault, DefaultSessionReader, DefaultSessionRewinder, DefaultSessionStore, DefaultSkillLoader, DefaultSystemPromptBuilder, DefaultTaskStore, DefaultTokenCounter, Director, DirectorStateCheckpoint, DoneConditionChecker, ERROR_CODES, EternalAutonomyEngine, EventBus, ExtensionRegistry, FLEET_ROSTER, FLEET_ROSTER_BUDGETS, FLEET_ROSTER_WITHACP, FleetBus, FleetCostCapError, FleetManager, FleetSpawnBudgetError, FleetUsageAggregator, FsError, GitignoreUpdater, HookRegistry, HookRunner, HumanEscalatingBrainArbiter, HybridCompactor, InMemoryAgentBridge, InMemoryBridgeTransport, InMemoryMetricsSink, InputBuilder, IntelligentCompactor, KERNEL_API_VERSION, LAYER_1_IDENTITY, LLMSelector, MATRIX_PHASE_KEYS, MAX_JOURNAL_ENTRIES, NULL_FLEET_BUS, NoopMetricsSink, NoopTracer, OTelTracer, ObservableBrainArbiter, PROMETHEUS_CONTENT_TYPE, ParallelEternalEngine, PhaseGraphBuilder, PhaseOrchestrator, PhaseStore, Pipeline, PluginError, ProviderError, ProviderRegistry, QueueStore, REFACTOR_PLANNER_AGENT, RecoveryLock, ReplayLogStore, ReplayProviderRunner, ReportGenerator, RunController, SECURITY_SCANNER_AGENT, SPEC_TEMPLATES, STANDARD_AUDIT_EVENTS, ScopedEventBus, SddParallelRun, SddTaskDecomposer, SecurityScanner, SecurityScannerOrchestrator, SelectiveCompactor, SessionAnalyzer, SessionError, SessionRecovery, SkillGenerator, SkillInstaller, SkillManifestStore, SlashCommandRegistry, SpecDrivenDev, SpecParser, SpecStore, SpecVersioning, SubagentBudget, TOKENS, TaskFlow, TaskGenerator, TaskGraphStore, TaskTracker, TechStackDetector, ToolAuditLog, ToolError, ToolExecutor, ToolRegistry, WorktreeManager, WrongStackError, addPlanItem, allServers, analyzeCriticalPath, appendJournal, applyRosterBudget, asBlocks, asText, assertSafePath, atomicWrite, attachAutoExtend, attachPlanCheckpoint, attachTodosCheckpoint, awsServer, blockServer, bootConfig, braveSearchServer, buildBtwBlock, buildChildEnv, buildGoalPreamble, buildOtlpMetricsRequest, buildOtlpTracesRequest, buildRecoveryStrategies, classifyFamily, clearPlan, collabInjectMiddleware, collabPauseMiddleware, color, compileGlob, compileUserRegex, completePartialObject, composeDirectorPrompt, composeSubagentPrompt, computeTaskProgress, consumeBtwNotes, context7Server, contextManagerTool, createAutoExecutor, createAutoPhaseFromTaskGraph, createContextManagerTool, createDefaultPipelines, createDelegateTool, createGitPlugin, createMcpControlTool, createMessage, createObservabilityPlugin, createPlanPlugin, createPromptsPlugin, createSecurityPlugin, createSecuritySlashCommand, createSessionEventBridge, createSkillsPlugin, createSyncPlugin, createToolOutputSerializer, decryptConfigSecrets, defaultGitignoreUpdater, defaultOrchestrator, defaultReportGenerator, defaultSecurityScanner, defaultSkillGenerator, defaultTechStackDetector, deriveTodosFromPlanItem, detectNewlineStyle, dispatchAgent, downloadGitHubTarball, emptyGoal, emptyPlan, encryptConfigSecrets, ensureDir, estimateRequestTokens, estimateRequestTokensCalibrated, estimateTextTokens, estimateToolDefTokens, estimateToolInputTokens, estimateToolResultTokens, everArtServer, expandGlob, extractRunEnv, filesystemServer, findCriticalPath, flagsToConfigPatch, formatContextWindowModeList, formatGoal, formatHumanPrompt, formatPlan, formatPlanTemplates, formatTodosList, getAgentDefinition, getCalibrationState, getContextWindowMode, getPlanTemplate, getTemplate, getTermSize, githubServer, goalFilePath, googleMapsServer, hashRequest, hookMatcherMatches, isAgentError, isConfigError, isContextWindowModeId, isFsError, isImageBlock, isInteractive, isPluginError, isSessionError, isStdinTTY, isStdoutTTY, isTextBlock, isThinkingBlock, isToolError, isToolResultBlock, isToolUseBlock, isValidMatrixKey, isWrongStackError, listContextWindowModes, listPlanTemplates, listTemplates, loadDirectorState, loadGoal, loadPlan, loadPlugins, loadProjectModes, loadTodosCheckpoint, loadUserModes, makeAgentSubagentRunner, makeAskTool, makeAssignTool, makeAutonomyPromptContributor, makeAwaitTasksTool, makeCollabDebugTool, makeContinueToNextIterationTool, makeDirectorSessionFactory, makeFleetEmitTool, makeFleetHealthTool, makeFleetSessionTool, makeFleetStatusTool, makeFleetUsageTool, makeLLMClassifier, makeRollUpTool, makeSpawnTool, makeTerminateTool, matchAny, matchGlob, matrixKeyKind, mergeCustomModelDefs, mergeModelsPayload, migratePlaintextSecrets, miniMaxVisionServer, normalizeToLf, onResize, parseContinueDirective, parseSkillRef, pendingBtwCount, phaseForRole, projectHash, recordActualUsage, removePlanItem, renderProgress, renderPrometheus, renderSpecAnalysis, renderTaskGraph, renderTaskList, repairToolUseAdjacency, resetCalibration, resolveAuditLevel, resolveContextWindowPolicy, resolveModelMatrix, resolveSessionLoggingConfig, resolveWstackPaths, rewriteConfigEncrypted, rosterSummaryFromConfigs, runConfigMigrations, runProviderWithRetry, runShellHook, safeParse, safeStringify, sanitizeJsonString, saveGoal, savePlan, saveTodosCheckpoint, scoreAgents, securitySlashCommand, sentinelServer, setBtwNote, setPlanItemStatus, setRawMode, slackServer, stableStringify, startMetricsServer, startOtlpMetricsExporter, startOtlpTraceExporter, stripAnsi, summarizeUsage, templateToMarkdown, toStyle, toWrongStackError, topologicalSort, unifiedDiff, unloadPlugins, validateAgainstSchema, wireMetricsToEvents, wrapAsState, writeErr, writeOut, zaiVisionServer };
31115
+ export { ACP_AGENTS, AGENTS_BY_PHASE, AGENT_CATALOG, AISpecBuilder, ALL_AGENT_DEFINITIONS, ALL_FLEET_AGENTS, ALL_SYNC_CATEGORIES, AUDIT_LOG_AGENT, Agent, AgentError, AnnotationsStore, AutoApprovePermissionPolicy, AutoCompactionMiddleware, AutoExecutor, AutoPhasePlanner, AutoPhaseRunner, AutonomousRunner, BUG_HUNTER_AGENT, BrainDecisionQueue, BudgetExceededError, CONTEXT_WINDOW_MODES, CORE_RECONSTRUCT_EVENTS, CheckpointManager, CloudSync, CollaborationBus, ConfigError, ConfigMigrationError, Container, Context, ConversationState, DEFAULT_AUTONOMY_CONFIG, DEFAULT_CONFIG_MIGRATIONS, DEFAULT_CONTEXT_CONFIG, DEFAULT_CONTEXT_WINDOW_MODE_ID, DEFAULT_DIRECTOR_PREAMBLE, DEFAULT_DISPATCH_ROLE, DEFAULT_MAX_ITERATIONS, DEFAULT_MODES, DEFAULT_RECOVERY_STRATEGIES, DEFAULT_SESSION_LOGGING_CONFIG, DEFAULT_SPEC_TEMPLATE, DEFAULT_SUBAGENT_BASELINE, DEFAULT_TOOLS_CONFIG, DefaultAttachmentStore, DefaultBrainArbiter, DefaultConfigLoader, DefaultConfigStore, DefaultErrorHandler, DefaultHealthRegistry, DefaultLogger, DefaultMemoryStore, DefaultModeStore, DefaultModelsRegistry, DefaultMultiAgentCoordinator, DefaultPathResolver, DefaultPermissionPolicy, DefaultPluginAPI, DefaultPromptStore, DefaultProviderRunner, DefaultRetryPolicy, DefaultSecretScrubber, DefaultSecretVault, DefaultSessionReader, DefaultSessionRewinder, DefaultSessionStore, DefaultSkillLoader, DefaultSystemPromptBuilder, DefaultTaskStore, DefaultTokenCounter, Director, DirectorStateCheckpoint, DoneConditionChecker, ENHANCER_SYSTEM_PROMPT, ERROR_CODES, EternalAutonomyEngine, EventBus, ExtensionRegistry, FLEET_ROSTER, FLEET_ROSTER_BUDGETS, FLEET_ROSTER_WITHACP, FleetBus, FleetCostCapError, FleetManager, FleetSpawnBudgetError, FleetUsageAggregator, FsError, GitignoreUpdater, HookRegistry, HookRunner, HumanEscalatingBrainArbiter, HybridCompactor, InMemoryAgentBridge, InMemoryBridgeTransport, InMemoryMetricsSink, InputBuilder, IntelligentCompactor, KERNEL_API_VERSION, LAYER_1_IDENTITY, LLMSelector, MATRIX_PHASE_KEYS, MAX_JOURNAL_ENTRIES, NULL_FLEET_BUS, NoopMetricsSink, NoopTracer, OTelTracer, ObservableBrainArbiter, PROMETHEUS_CONTENT_TYPE, ParallelEternalEngine, PhaseGraphBuilder, PhaseOrchestrator, PhaseStore, Pipeline, PluginError, ProviderError, ProviderRegistry, QueueStore, REFACTOR_PLANNER_AGENT, RecoveryLock, ReplayLogStore, ReplayProviderRunner, ReportGenerator, RunController, SECURITY_SCANNER_AGENT, SPEC_TEMPLATES, STANDARD_AUDIT_EVENTS, ScopedEventBus, SddParallelRun, SddTaskDecomposer, SecurityScanner, SecurityScannerOrchestrator, SelectiveCompactor, SessionAnalyzer, SessionError, SessionRecovery, SkillGenerator, SkillInstaller, SkillManifestStore, SlashCommandRegistry, SpecDrivenDev, SpecParser, SpecStore, SpecVersioning, SubagentBudget, TOKENS, TaskFlow, TaskGenerator, TaskGraphStore, TaskTracker, TechStackDetector, ToolAuditLog, ToolError, ToolExecutor, ToolRegistry, WorktreeManager, WrongStackError, addPlanItem, allServers, analyzeCriticalPath, appendJournal, applyRosterBudget, asBlocks, asText, assertSafePath, atomicWrite, attachAutoExtend, attachPlanCheckpoint, attachTodosCheckpoint, awsServer, blockServer, bootConfig, braveSearchServer, buildBtwBlock, buildChildEnv, buildGoalPreamble, buildOtlpMetricsRequest, buildOtlpTracesRequest, buildRecoveryStrategies, classifyFamily, clearPlan, collabInjectMiddleware, collabPauseMiddleware, color, compileGlob, compileUserRegex, completePartialObject, composeDirectorPrompt, composeSubagentPrompt, computeTaskProgress, consumeBtwNotes, context7Server, contextManagerTool, createAutoExecutor, createAutoPhaseFromTaskGraph, createContextManagerTool, createDefaultPipelines, createDelegateTool, createGitPlugin, createMcpControlTool, createMessage, createObservabilityPlugin, createPlanPlugin, createPromptsPlugin, createSecurityPlugin, createSecuritySlashCommand, createSessionEventBridge, createSkillsPlugin, createSyncPlugin, createToolOutputSerializer, decryptConfigSecrets, defaultGitignoreUpdater, defaultOrchestrator, defaultReportGenerator, defaultSecurityScanner, defaultSkillGenerator, defaultTechStackDetector, deriveTodosFromPlanItem, detectNewlineStyle, dispatchAgent, downloadGitHubTarball, emptyGoal, emptyPlan, encryptConfigSecrets, enhanceUserPrompt, ensureDir, estimateRequestTokens, estimateRequestTokensCalibrated, estimateTextTokens, estimateToolDefTokens, estimateToolInputTokens, estimateToolResultTokens, everArtServer, expandGlob, extractRunEnv, filesystemServer, findCriticalPath, flagsToConfigPatch, formatContextWindowModeList, formatGoal, formatHumanPrompt, formatPlan, formatPlanTemplates, formatTodosList, getAgentDefinition, getCalibrationState, getContextWindowMode, getPlanTemplate, getTemplate, getTermSize, githubServer, goalFilePath, googleMapsServer, hashRequest, hookMatcherMatches, isAgentError, isConfigError, isContextWindowModeId, isFsError, isImageBlock, isInteractive, isPluginError, isSessionError, isStdinTTY, isStdoutTTY, isTextBlock, isThinkingBlock, isToolError, isToolResultBlock, isToolUseBlock, isValidMatrixKey, isWrongStackError, listContextWindowModes, listPlanTemplates, listTemplates, loadDirectorState, loadGoal, loadPlan, loadPlugins, loadProjectModes, loadTodosCheckpoint, loadUserModes, makeAgentSubagentRunner, makeAskTool, makeAssignTool, makeAutonomyPromptContributor, makeAwaitTasksTool, makeCollabDebugTool, makeContinueToNextIterationTool, makeDirectorSessionFactory, makeFleetEmitTool, makeFleetHealthTool, makeFleetSessionTool, makeFleetStatusTool, makeFleetUsageTool, makeLLMClassifier, makeRollUpTool, makeSpawnTool, makeTerminateTool, matchAny, matchGlob, matrixKeyKind, mergeCustomModelDefs, mergeModelsPayload, migratePlaintextSecrets, miniMaxVisionServer, normalizeToLf, normalizedEqual, onResize, parseContinueDirective, parseSkillRef, pendingBtwCount, phaseForRole, projectHash, projectSlug, recentTextTurns, recordActualUsage, removePlanItem, renderProgress, renderPrometheus, renderSpecAnalysis, renderTaskGraph, renderTaskList, repairToolUseAdjacency, resetCalibration, resolveAuditLevel, resolveContextWindowPolicy, resolveModelMatrix, resolveSessionLoggingConfig, resolveWstackPaths, rewriteConfigEncrypted, rosterSummaryFromConfigs, runConfigMigrations, runProviderWithRetry, runShellHook, safeParse, safeStringify, sanitizeJsonString, saveGoal, savePlan, saveTodosCheckpoint, scoreAgents, securitySlashCommand, sentinelServer, setBtwNote, setPlanItemStatus, setRawMode, shouldEnhance, slackServer, stableStringify, startMetricsServer, startOtlpMetricsExporter, startOtlpTraceExporter, stripAnsi, summarizeUsage, templateToMarkdown, toStyle, toWrongStackError, topologicalSort, unifiedDiff, unloadPlugins, validateAgainstSchema, wireMetricsToEvents, wrapAsState, writeErr, writeOut, zaiVisionServer };
30907
31116
  //# sourceMappingURL=index.js.map
30908
31117
  //# sourceMappingURL=index.js.map