@wrongstack/core 0.109.1 → 0.119.1

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 (62) hide show
  1. package/dist/{agent-bridge-mOxbpFcg.d.ts → agent-bridge-PRAbEX-9.d.ts} +1 -1
  2. package/dist/{agent-subagent-runner-DukQLUcS.d.ts → agent-subagent-runner-DXWImnNV.d.ts} +7 -8
  3. package/dist/{brain-Dfv4Y82E.d.ts → brain-NZZqL8sn.d.ts} +1 -1
  4. package/dist/{compactor-DXLxLcmU.d.ts → compactor-C3stu664.d.ts} +1 -1
  5. package/dist/{config-BSU-6vah.d.ts → config-DZV9VK9n.d.ts} +104 -3
  6. package/dist/{context-CNRYfhUv.d.ts → context-hvXINa6a.d.ts} +31 -1
  7. package/dist/coordination/index.d.ts +12 -13
  8. package/dist/coordination/index.js +198 -0
  9. package/dist/coordination/index.js.map +1 -1
  10. package/dist/defaults/index.d.ts +26 -27
  11. package/dist/defaults/index.js +243 -35
  12. package/dist/defaults/index.js.map +1 -1
  13. package/dist/execution/index.d.ts +15 -16
  14. package/dist/execution/index.js +209 -5
  15. package/dist/execution/index.js.map +1 -1
  16. package/dist/extension/index.d.ts +6 -7
  17. package/dist/{goal-preamble-CI8lxeY1.d.ts → goal-preamble-COpt55W8.d.ts} +10 -10
  18. package/dist/{index-DIKEcfgC.d.ts → index-4VVHuTZF.d.ts} +7 -6
  19. package/dist/{index-BWRN6wOb.d.ts → index-Cj3le7TI.d.ts} +9 -10
  20. package/dist/index.d.ts +40 -41
  21. package/dist/index.js +298 -43
  22. package/dist/index.js.map +1 -1
  23. package/dist/infrastructure/index.d.ts +6 -7
  24. package/dist/kernel/index.d.ts +10 -11
  25. package/dist/llm-selector-Bmx4PsVM.d.ts +58 -0
  26. package/dist/{mcp-servers-CXCsANdY.d.ts → mcp-servers-CofNHOqn.d.ts} +3 -3
  27. package/dist/{mode-ARA3HrkY.d.ts → mode-CZlO9iU1.d.ts} +1 -1
  28. package/dist/models/index.d.ts +157 -53
  29. package/dist/models/index.js +423 -1
  30. package/dist/models/index.js.map +1 -1
  31. package/dist/{models-registry-DU64QxQa.d.ts → models-registry-BzlsjKcy.d.ts} +1 -1
  32. package/dist/{multi-agent-coordinator-51LvnXkD.d.ts → multi-agent-coordinator-CmDmUgq2.d.ts} +1 -1
  33. package/dist/{null-fleet-bus-D09hMzFQ.d.ts → null-fleet-bus-CyH2YqP4.d.ts} +6 -6
  34. package/dist/observability/index.d.ts +2 -2
  35. package/dist/{parallel-eternal-engine-B2CbsKpc.d.ts → parallel-eternal-engine-uxVm4y4V.d.ts} +8 -8
  36. package/dist/{path-resolver-DDJiMAtX.d.ts → path-resolver-gfoGxpdd.d.ts} +3 -3
  37. package/dist/{permission-BDv7z0mk.d.ts → permission-DhLrgA30.d.ts} +1 -1
  38. package/dist/{permission-policy-dF74EpDp.d.ts → permission-policy-DGOvne7i.d.ts} +2 -2
  39. package/dist/{pipeline-BqiA_UMr.d.ts → pipeline-CqF7uju2.d.ts} +2 -2
  40. package/dist/{plan-templates-BdDxl9cI.d.ts → plan-templates-DoKhzenv.d.ts} +6 -6
  41. package/dist/{provider-runner-BUunikwY.d.ts → provider-runner-BPlI5sPZ.d.ts} +3 -3
  42. package/dist/{retry-policy-BcmuT_V0.d.ts → retry-policy-B4Q-FZgE.d.ts} +1 -1
  43. package/dist/sdd/index.d.ts +8 -9
  44. package/dist/sdd/index.js +198 -0
  45. package/dist/sdd/index.js.map +1 -1
  46. package/dist/{secret-vault-DrOhc2i5.d.ts → secret-vault-B7GnL6o9.d.ts} +1 -1
  47. package/dist/security/index.d.ts +4 -4
  48. package/dist/{selector-C7wcdqMA.d.ts → selector-BakeMnWR.d.ts} +1 -1
  49. package/dist/{session-event-bridge-BpJ5trO9.d.ts → session-event-bridge-DE5Oekwx.d.ts} +1 -1
  50. package/dist/{session-reader-DDz1Ek4V.d.ts → session-reader-DFC81-4p.d.ts} +1 -1
  51. package/dist/storage/index.d.ts +11 -12
  52. package/dist/storage/index.js +43 -34
  53. package/dist/storage/index.js.map +1 -1
  54. package/dist/types/index.d.ts +19 -20
  55. package/dist/types/index.js +35 -1
  56. package/dist/types/index.js.map +1 -1
  57. package/dist/utils/index.d.ts +3 -4
  58. package/dist/utils/index.js +2 -1
  59. package/dist/utils/index.js.map +1 -1
  60. package/dist/{wstack-paths-_lqjzErq.d.ts → wstack-paths-DD50Omgn.d.ts} +3 -0
  61. package/package.json +1 -1
  62. package/dist/models-registry-B6_KfS65.d.ts +0 -95
package/dist/index.js CHANGED
@@ -1114,6 +1114,39 @@ function describeStatus(status, type) {
1114
1114
  function truncate(s, n) {
1115
1115
  return s.length <= n ? s : `${s.slice(0, n - 1)}\u2026`;
1116
1116
  }
1117
+ var StreamHangError = class extends ProviderError {
1118
+ /** Name of the provider that hung, e.g. "zai", "anthropic". */
1119
+ hungProviderId;
1120
+ /** Model that was being called when the hang occurred. */
1121
+ hungModel;
1122
+ /** How long (ms) we waited for the next chunk before declaring a hang. */
1123
+ hangTimeoutMs;
1124
+ /** How many bytes were received before the hang. */
1125
+ bytesReceived;
1126
+ /** Elapsed time (ms) from the start of the stream until the hang. */
1127
+ elapsedMs;
1128
+ constructor(opts) {
1129
+ super(
1130
+ `Stream hang: ${opts.providerId}/${opts.model} \u2014 no data for ${opts.hangTimeoutMs}ms after ${opts.bytesReceived} bytes (${opts.elapsedMs}ms elapsed)`,
1131
+ 599,
1132
+ true,
1133
+ // always retryable
1134
+ opts.providerId,
1135
+ {
1136
+ body: {
1137
+ message: `Stream stalled after ${opts.elapsedMs}ms, ${opts.bytesReceived} bytes received`
1138
+ },
1139
+ cause: opts.cause
1140
+ }
1141
+ );
1142
+ this.name = "StreamHangError";
1143
+ this.hungProviderId = opts.providerId;
1144
+ this.hungModel = opts.model;
1145
+ this.hangTimeoutMs = opts.hangTimeoutMs;
1146
+ this.bytesReceived = opts.bytesReceived;
1147
+ this.elapsedMs = opts.elapsedMs;
1148
+ }
1149
+ };
1117
1150
  function providerStatusToCode(status, type) {
1118
1151
  if (status === 0) return ERROR_CODES.PROVIDER_NETWORK_ERROR;
1119
1152
  if (type === "rate_limit_error" || status === 429) return ERROR_CODES.PROVIDER_RATE_LIMITED;
@@ -2322,6 +2355,7 @@ var DefaultRetryPolicy = class {
2322
2355
  if (err instanceof ProviderError) {
2323
2356
  if (err.status === 429) return 5;
2324
2357
  if (err.status === 529) return 3;
2358
+ if (err.status === 599) return 5;
2325
2359
  if (err.status >= 500) return 3;
2326
2360
  return 0;
2327
2361
  }
@@ -4451,7 +4485,7 @@ function computeTaskItemProgress(tasks) {
4451
4485
  let failed = 0;
4452
4486
  let review = 0;
4453
4487
  let estimatedHours = 0;
4454
- let actualHours = 0;
4488
+ const actualHours = 0;
4455
4489
  for (const t2 of tasks) {
4456
4490
  switch (t2.status) {
4457
4491
  case "completed":
@@ -4815,6 +4849,7 @@ function resolveWstackPaths(opts) {
4815
4849
  projectTrust: path6.join(projectDir, "trust.json"),
4816
4850
  projectMeta: path6.join(projectDir, "meta.json"),
4817
4851
  projectLocalConfig: path6.join(projectDir, "config.local.json"),
4852
+ inProjectConfig: path6.join(opts.projectRoot, ".wrongstack", "config.json"),
4818
4853
  inProjectAgentsFile: path6.join(opts.projectRoot, ".wrongstack", "AGENTS.md"),
4819
4854
  inProjectSkills: path6.join(opts.projectRoot, ".wrongstack", "skills"),
4820
4855
  inProjectWorktrees: path6.join(opts.projectRoot, ".wrongstack", "worktrees"),
@@ -6252,39 +6287,41 @@ ${line}`;
6252
6287
  }
6253
6288
  async forget(scope, query, filePath) {
6254
6289
  const file = this.resolveFile(filePath, scope);
6255
- let existing;
6256
- try {
6257
- existing = await fsp3.readFile(file, "utf8");
6258
- } catch {
6259
- return 0;
6260
- }
6261
- const needle = query.toLowerCase();
6262
- const idMatcher = /mem_\d+_\w+/;
6263
- let removed = 0;
6264
- const lines = existing.split("\n").filter((line) => {
6265
- const trimmed = line.trim();
6266
- if (!trimmed.startsWith("- ")) return true;
6267
- if (idMatcher.test(query)) {
6268
- const entryIdMatch = /mem_\d+_\w+/.exec(trimmed);
6269
- if (entryIdMatch && entryIdMatch[0] === query) {
6290
+ return withFileLock(file, async () => {
6291
+ let existing;
6292
+ try {
6293
+ existing = await fsp3.readFile(file, "utf8");
6294
+ } catch {
6295
+ return 0;
6296
+ }
6297
+ const needle = query.toLowerCase();
6298
+ const idMatcher = /mem_\d+_\w+/;
6299
+ let removed = 0;
6300
+ const lines = existing.split("\n").filter((line) => {
6301
+ const trimmed = line.trim();
6302
+ if (!trimmed.startsWith("- ")) return true;
6303
+ if (idMatcher.test(query)) {
6304
+ const entryIdMatch = /mem_\d+_\w+/.exec(trimmed);
6305
+ if (entryIdMatch && entryIdMatch[0] === query) {
6306
+ removed++;
6307
+ return false;
6308
+ }
6309
+ }
6310
+ if (trimmed.toLowerCase().includes(needle)) {
6270
6311
  removed++;
6271
6312
  return false;
6272
6313
  }
6314
+ return true;
6315
+ });
6316
+ if (removed > 0) {
6317
+ if (lines.length === 0 || lines.length === 1 && !lines[0]?.trim()) {
6318
+ await atomicWrite(file, "");
6319
+ } else {
6320
+ await atomicWrite(file, lines.join("\n"));
6321
+ }
6273
6322
  }
6274
- if (trimmed.toLowerCase().includes(needle)) {
6275
- removed++;
6276
- return false;
6277
- }
6278
- return true;
6323
+ return removed;
6279
6324
  });
6280
- if (removed > 0) {
6281
- if (lines.length === 0 || lines.length === 1 && !lines[0]?.trim()) {
6282
- await atomicWrite(file, "");
6283
- } else {
6284
- await atomicWrite(file, lines.join("\n"));
6285
- }
6286
- }
6287
- return removed;
6288
6325
  }
6289
6326
  async readAll(scope, filePath) {
6290
6327
  const file = this.resolveFile(filePath, scope);
@@ -6904,12 +6941,14 @@ var DefaultConfigLoader = class {
6904
6941
  }
6905
6942
  async load(opts = {}) {
6906
6943
  let cfg = { ...BEHAVIOR_DEFAULTS };
6907
- const [global, local] = await Promise.all([
6944
+ const [global, local, inProject] = await Promise.all([
6908
6945
  this.readJson(this.paths.globalConfig),
6909
- this.readJson(this.paths.projectLocalConfig)
6946
+ this.readJson(this.paths.projectLocalConfig),
6947
+ this.readJson(this.paths.inProjectConfig)
6910
6948
  ]);
6911
6949
  cfg = deepMerge2(cfg, global);
6912
6950
  cfg = deepMerge2(cfg, local);
6951
+ cfg = deepMerge2(cfg, inProject);
6913
6952
  for (const [key, fn] of Object.entries(ENV_MAP)) {
6914
6953
  const v = process.env[key];
6915
6954
  if (v) fn(cfg, v);
@@ -9748,16 +9787,20 @@ async function loadGoal(filePath) {
9748
9787
  let raw;
9749
9788
  try {
9750
9789
  raw = await fsp3.readFile(filePath, "utf8");
9751
- } catch {
9752
- return null;
9790
+ } catch (err) {
9791
+ const code = err.code;
9792
+ if (code === "ENOENT") return null;
9793
+ throw err;
9753
9794
  }
9754
9795
  try {
9755
9796
  const parsed = JSON.parse(raw);
9756
9797
  if (parsed?.version !== 1 || typeof parsed.goal !== "string" || !Array.isArray(parsed.journal)) {
9798
+ console.warn(`[goal-store] Corrupt goal.json at ${filePath} \u2014 invalid schema. Consider deleting it and re-creating.`);
9757
9799
  return null;
9758
9800
  }
9759
9801
  return parsed;
9760
9802
  } catch {
9803
+ console.warn(`[goal-store] Corrupt goal.json at ${filePath} \u2014 JSON parse failed. Consider deleting it and re-creating.`);
9761
9804
  return null;
9762
9805
  }
9763
9806
  }
@@ -9906,7 +9949,7 @@ function computeTrend(history) {
9906
9949
  const recent = history.slice(-5);
9907
9950
  const deltas = [];
9908
9951
  for (let i = 1; i < recent.length; i++) {
9909
- deltas.push(recent[i].progress - recent[i - 1].progress);
9952
+ deltas.push((recent[i]?.progress ?? 0) - (recent[i - 1]?.progress ?? 0));
9910
9953
  }
9911
9954
  if (deltas.length < 2) return void 0;
9912
9955
  const avgDelta = deltas.reduce((a, b) => a + b, 0) / deltas.length;
@@ -10493,8 +10536,8 @@ ${recentJournal}` : "No prior iterations.",
10493
10536
  await saveGoal(this.goalPath, abandoned);
10494
10537
  }
10495
10538
  try {
10496
- const { unlink: unlink14 } = await import('fs/promises');
10497
- await unlink14(this.goalPath);
10539
+ const { unlink: unlink15 } = await import('fs/promises');
10540
+ await unlink15(this.goalPath);
10498
10541
  } catch {
10499
10542
  }
10500
10543
  this.opts.onEternalStop?.();
@@ -11495,6 +11538,53 @@ Working rules:
11495
11538
  "flaws"
11496
11539
  ]
11497
11540
  }
11541
+ },
11542
+ {
11543
+ config: {
11544
+ id: "refactor-planner",
11545
+ name: "Refactor Planner",
11546
+ role: "refactor-planner",
11547
+ tools: [...PLAN_TOOLS, "diff"],
11548
+ prompt: `You are the Refactor Planner agent. Your job is to analyze code
11549
+ structure and produce a concrete, phased refactoring plan with risk
11550
+ assessment, dependency ordering, and rollback strategy.
11551
+
11552
+ Scope:
11553
+ - Map module-level dependencies (import graph)
11554
+ - Identify coupling hotspots (high fan-in/out modules)
11555
+ - Assess refactoring risk by complexity and test coverage
11556
+ - Generate phased plans with checkpoint milestones
11557
+ - Produce diff-friendly task lists (one task = one concern)
11558
+
11559
+ Input format you accept:
11560
+ { "task": "plan | assess | roadmap", "target": "src/core", "constraint": "no-breaking-changes | minimal-downtime | full-rewrite", "focus": "architecture | performance | maintainability" }
11561
+
11562
+ Output: Markdown refactor plan with phases (Low Risk / Medium Risk / High Risk),
11563
+ dependency graph, rollback strategy, and exit criteria.
11564
+
11565
+ Working rules:
11566
+ - Always include rollback strategy \u2014 every refactor can fail
11567
+ - Merge tasks that take <1h into a single phase
11568
+ - Respect team constraints (reviewer availability, parallelization)
11569
+ - Never plan without analyzing the actual code first`
11570
+ },
11571
+ budget: HEAVY_BUDGET,
11572
+ capability: {
11573
+ phase: "planning",
11574
+ summary: "Refactoring planner: analyzes code structure, maps dependencies, produces risk-scored phased plans with rollback strategy.",
11575
+ keywords: [
11576
+ "refactor",
11577
+ "refactoring",
11578
+ "restructure",
11579
+ "debt",
11580
+ "technical debt",
11581
+ "clean up",
11582
+ "modularize",
11583
+ "decouple",
11584
+ "dependency graph",
11585
+ "code structure"
11586
+ ]
11587
+ }
11498
11588
  }
11499
11589
  ];
11500
11590
 
@@ -12034,6 +12124,157 @@ Working rules:
12034
12124
  "robustness"
12035
12125
  ]
12036
12126
  }
12127
+ },
12128
+ {
12129
+ config: {
12130
+ id: "security-scanner",
12131
+ name: "Security Scanner",
12132
+ role: "security-scanner",
12133
+ tools: [...TOOLS.inspect],
12134
+ prompt: `You are the Security Scanner agent. Your job is to scan code,
12135
+ configs, and dependencies for security issues from hardcoded secrets to
12136
+ supply chain risks.
12137
+
12138
+ Scope:
12139
+ - Detect hardcoded secrets: API keys, tokens, passwords, private keys
12140
+ - Find injection vectors: eval, innerHTML, SQL concat, shell injection
12141
+ - Identify insecure patterns: weak crypto, hardcoded IVs, disabled TLS
12142
+ - Scan dependencies for known CVEs (via npm/pnpm audit)
12143
+ - Flag supply chain risks: postinstall hooks, unverified scripts
12144
+
12145
+ Input format you accept:
12146
+ { "task": "scan | audit | secrets | dependencies", "paths": ["src", "config"], "depth": "quick | normal | deep" }
12147
+
12148
+ Output: Markdown security report with severity-ranked findings, injection
12149
+ vectors, dependency issues, and a remediation checklist.
12150
+
12151
+ Working rules:
12152
+ - Never scan node_modules \u2014 use npm audit instead
12153
+ - Always provide remediation steps, not just findings
12154
+ - Verify regex-based secrets before flagging (false positive risk)
12155
+ - When in doubt, flag as medium rather than ignoring potential issues`
12156
+ },
12157
+ budget: HEAVY_BUDGET,
12158
+ capability: {
12159
+ phase: "verify",
12160
+ summary: "Security scanner: detects hardcoded secrets, injection vectors, insecure patterns, and supply-chain risks with remediation.",
12161
+ keywords: [
12162
+ "security",
12163
+ "scan",
12164
+ "vulnerability",
12165
+ "secret",
12166
+ "api key",
12167
+ "hardcoded",
12168
+ "injection",
12169
+ "cve",
12170
+ "audit dependencies",
12171
+ "supply chain",
12172
+ "xss",
12173
+ "sqli",
12174
+ "shell injection",
12175
+ "sensitive data",
12176
+ "credential"
12177
+ ]
12178
+ }
12179
+ },
12180
+ {
12181
+ config: {
12182
+ id: "bug-hunter",
12183
+ name: "Bug Hunter",
12184
+ role: "bug-hunter",
12185
+ tools: [...TOOLS.inspect],
12186
+ prompt: `You are the Bug Hunter agent. Your job is to systematically scan
12187
+ source code for bugs, anti-patterns, and code smells using pattern matching
12188
+ and heuristics. Output a prioritized hit list with file:line references.
12189
+
12190
+ Scope:
12191
+ - Detect common bug patterns (uncaught errors, resource leaks, race conditions)
12192
+ - Identify anti-patterns (callback hell, God objects, circular deps)
12193
+ - Find TypeScript-specific issues (unsafe any, missing null checks, branded types)
12194
+ - Flag security-sensitive constructs (eval, innerHTML, hardcoded secrets)
12195
+ - Rank findings: critical > high > medium > low
12196
+
12197
+ Input format you accept:
12198
+ { "task": "scan | hunt | check", "paths": ["src/**/*.ts"], "focus": "bugs | patterns | security | all", "severityThreshold": "medium" }
12199
+
12200
+ Output: Markdown bug hunt report with critically/high/medium/low sections.
12201
+ Each entry: **[TYPE]** \`file:line\` \u2014 description + suggested fix
12202
+
12203
+ Working rules:
12204
+ - Never scan node_modules \u2014 it's noise
12205
+ - Always include file:line for every finding
12206
+ - If >30% of findings are false positives, note the confidence level
12207
+ - Ask director for clarification if paths are ambiguous`
12208
+ },
12209
+ budget: HEAVY_BUDGET,
12210
+ capability: {
12211
+ phase: "verify",
12212
+ summary: "Bug hunter: scans source code for bugs, anti-patterns, and code smells, producing a file:line-ranked hit list with fixes.",
12213
+ keywords: [
12214
+ "bug",
12215
+ "hunt",
12216
+ "scan",
12217
+ "code smell",
12218
+ "anti-pattern",
12219
+ "race condition",
12220
+ "memory leak",
12221
+ "null deref",
12222
+ "type safety",
12223
+ "unhandled error",
12224
+ "find bugs",
12225
+ "audit code",
12226
+ "code quality"
12227
+ ]
12228
+ }
12229
+ },
12230
+ {
12231
+ config: {
12232
+ id: "audit-log",
12233
+ name: "Audit Log",
12234
+ role: "audit-log",
12235
+ tools: [...TOOLS.inspect],
12236
+ prompt: `You are the Audit Log agent. Your job is to analyze structured JSONL
12237
+ session logs and produce actionable markdown reports.
12238
+
12239
+ Scope:
12240
+ - Parse session logs (iteration counts, tool calls, errors, usage)
12241
+ - Detect repeated failure patterns across multiple runs
12242
+ - Identify tool usage anomalies (over-use, failures, unexpected chains)
12243
+ - Track token consumption trends
12244
+ - Generate structured audit reports with severity ratings
12245
+
12246
+ Input format you accept:
12247
+ { "task": "analyze | report | trends", "sessionPath": "<path>", "focus": "errors | tools | usage | all" }
12248
+
12249
+ Output: Markdown audit report with Summary, Top Errors, Tool Usage table,
12250
+ Anomalies, and Cost Trend sections.
12251
+
12252
+ Working rules:
12253
+ - Never fabricate numbers \u2014 read the actual logs first
12254
+ - Always include file:line references for errors
12255
+ - If sessionPath is missing, ask the director to provide it
12256
+ - Report confidence level: high (>90% accuracy), medium, low`
12257
+ },
12258
+ budget: MEDIUM_BUDGET,
12259
+ capability: {
12260
+ phase: "verify",
12261
+ summary: "Audit log analyzer: parses session JSONL, detects failure patterns, tool anomalies, and cost trends with structured reports.",
12262
+ keywords: [
12263
+ "audit",
12264
+ "log",
12265
+ "logs",
12266
+ "session",
12267
+ "trace",
12268
+ "analyze logs",
12269
+ "error patterns",
12270
+ "cost analysis",
12271
+ "tool usage",
12272
+ "token usage",
12273
+ "post-mortem",
12274
+ "trend",
12275
+ "anomaly"
12276
+ ]
12277
+ }
12037
12278
  }
12038
12279
  ];
12039
12280
 
@@ -22916,7 +23157,7 @@ var SessionMemoryConsolidator = class {
22916
23157
  for (const op of parsed.operations) {
22917
23158
  switch (op.action) {
22918
23159
  case "add": {
22919
- if (op.text && op.text.trim()) {
23160
+ if (op.text?.trim()) {
22920
23161
  await this.memoryStore.remember(op.text.trim(), void 0, {
22921
23162
  type: op.type,
22922
23163
  tags: op.tags,
@@ -27212,6 +27453,12 @@ function requestLimitExtension(opts) {
27212
27453
  function toError(err) {
27213
27454
  return err instanceof Error ? err : new Error(String(err));
27214
27455
  }
27456
+ function signalAbortReason(signal) {
27457
+ const r = signal.reason;
27458
+ if (r instanceof Error) return r.message || r.name;
27459
+ if (typeof r === "string" && r.length > 0) return r;
27460
+ return "aborted";
27461
+ }
27215
27462
  function createAgentLoopHandler(a, handlers) {
27216
27463
  async function compactContextIfNeeded() {
27217
27464
  await a.pipelines.contextWindow.run(a.ctx);
@@ -27297,7 +27544,7 @@ function createAgentLoopHandler(a, handlers) {
27297
27544
  for (let i = 0; ; i++) {
27298
27545
  iterations = i + 1;
27299
27546
  if (controller.signal.aborted) {
27300
- return { status: "aborted", iterations };
27547
+ return { status: "aborted", iterations, abortReason: signalAbortReason(controller.signal) };
27301
27548
  }
27302
27549
  await a.ctx.session.writeInFlightMarker(`iteration ${i} / max ${a.maxIterations}`).catch((err) => {
27303
27550
  (a.logger.debug ?? a.logger.warn)?.(
@@ -27340,7 +27587,7 @@ function createAgentLoopHandler(a, handlers) {
27340
27587
  } catch (err) {
27341
27588
  if (controller.signal.aborted) {
27342
27589
  a.events.emit("error", { err: toError(err), phase: "provider" });
27343
- return { status: "aborted", iterations, error: toWrongStackError(err, "AGENT_ABORTED") };
27590
+ return { status: "aborted", iterations, error: toWrongStackError(err, "AGENT_ABORTED"), abortReason: signalAbortReason(controller.signal) };
27344
27591
  }
27345
27592
  const extDecision = await a.extensions.runOnError(a.ctx, err, "provider", i);
27346
27593
  if (extDecision) {
@@ -27388,7 +27635,7 @@ function createAgentLoopHandler(a, handlers) {
27388
27635
  }
27389
27636
  const responseResult = await handlers.response.processResponse(res, req);
27390
27637
  if (responseResult.aborted) {
27391
- return { status: "aborted", iterations, finalText: responseResult.finalText, delegateSummaries };
27638
+ return { status: "aborted", iterations, finalText: responseResult.finalText, delegateSummaries, abortReason: signalAbortReason(controller.signal) };
27392
27639
  }
27393
27640
  if (responseResult.done) {
27394
27641
  return { status: "done", iterations, finalText: responseResult.finalText, delegateSummaries };
@@ -27408,7 +27655,14 @@ function createAgentLoopHandler(a, handlers) {
27408
27655
  }
27409
27656
  return { status: "done", iterations, finalText, delegateSummaries };
27410
27657
  }
27411
- await handlers.tools.executeTools(toolUses);
27658
+ try {
27659
+ await handlers.tools.executeTools(toolUses);
27660
+ } catch (toolErr) {
27661
+ if (controller.signal.aborted) {
27662
+ return { status: "aborted", iterations, finalText, delegateSummaries, abortReason: signalAbortReason(controller.signal) };
27663
+ }
27664
+ throw toolErr;
27665
+ }
27412
27666
  if (autonomousContinue && consumeAutonomousContinue(a.ctx)) {
27413
27667
  emitContextPct();
27414
27668
  a.events.emit("iteration.completed", { ctx: a.ctx, index: i });
@@ -27575,7 +27829,8 @@ var Agent = class {
27575
27829
  const result = {
27576
27830
  status: signal.aborted ? "aborted" : "failed",
27577
27831
  iterations: 0,
27578
- error: wse
27832
+ error: wse,
27833
+ abortReason: signal.aborted ? signalAbortReason(signal) : void 0
27579
27834
  };
27580
27835
  await this.extensions.runAfterRun(this.ctx, result);
27581
27836
  return result;
@@ -32943,6 +33198,6 @@ ${formatPlan(updated)}`
32943
33198
  };
32944
33199
  }
32945
33200
 
32946
- 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_SESSION_PRUNE_DAYS, 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, FileMemoryBackend, FleetBus, FleetCostCapError, FleetManager, FleetSpawnBudgetError, FleetUsageAggregator, FsError, GitignoreUpdater, GraphMemoryBackend, HookRegistry, HookRunner, HumanEscalatingBrainArbiter, HybridCompactor, InMemoryAgentBridge, InMemoryBridgeTransport, InMemoryMetricsSink, InputBuilder, IntelligentCompactor, KERNEL_API_VERSION, LAYER_1_IDENTITY, LLMSelector, MATRIX_PHASE_KEYS, MAX_JOURNAL_ENTRIES, MAX_PROGRESS_HISTORY, MEMORY_TYPE_LABELS, 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, SessionMemoryConsolidator, 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, computeTaskItemProgress, 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, emptyTaskFile, encryptConfigSecrets, enhanceUserPrompt, ensureDir, estimateRequestTokens, estimateRequestTokensCalibrated, estimateTextTokens, estimateToolDefTokens, estimateToolInputTokens, estimateToolResultTokens, everArtServer, expandGlob, expectDefined, extractRunEnv, filesystemServer, findCriticalPath, flagsToConfigPatch, formatContextWindowModeList, formatGoal, formatHumanPrompt, formatPlan, formatPlanTemplates, formatTaskList, formatTaskProgress, 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, loadTasks, 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, parseEntries, parseProgressFromText, parseSkillRef, pendingBtwCount, phaseForRole, projectHash, projectSlug, recentTextTurns, recordActualUsage, recordProgress, removePlanItem, renderProgress, renderPrometheus, renderSpecAnalysis, renderTaskGraph, renderTaskList, repairToolUseAdjacency, resetCalibration, resolveAuditLevel, resolveContextWindowPolicy, resolveModelMatrix, resolveSessionLoggingConfig, resolveWstackPaths, rewriteConfigEncrypted, rosterSummaryFromConfigs, runConfigMigrations, runProviderWithRetry, runShellHook, safeParse, safeStringify, sanitizeJsonString, saveGoal, savePlan, saveTasks, saveTodosCheckpoint, scoreAgents, securitySlashCommand, sentinelServer, setBtwNote, setOutputLineGuard, setPlanItemStatus, setProgress, setRawMode, shouldEnhance, slackServer, sleep, stableStringify, startMetricsServer, startOtlpMetricsExporter, startOtlpTraceExporter, stripAnsi, summarizeUsage, templateToMarkdown, toStyle, toWrongStackError, topologicalSort, unifiedDiff, unloadPlugins, validateAgainstSchema, wireMetricsToEvents, withFileLock, wrapAsState, writeErr, writeOut, zaiVisionServer };
33201
+ 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_SESSION_PRUNE_DAYS, 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, FileMemoryBackend, FleetBus, FleetCostCapError, FleetManager, FleetSpawnBudgetError, FleetUsageAggregator, FsError, GitignoreUpdater, GraphMemoryBackend, HookRegistry, HookRunner, HumanEscalatingBrainArbiter, HybridCompactor, InMemoryAgentBridge, InMemoryBridgeTransport, InMemoryMetricsSink, InputBuilder, IntelligentCompactor, KERNEL_API_VERSION, LAYER_1_IDENTITY, LLMSelector, MATRIX_PHASE_KEYS, MAX_JOURNAL_ENTRIES, MAX_PROGRESS_HISTORY, MEMORY_TYPE_LABELS, 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, SessionMemoryConsolidator, SessionRecovery, SkillGenerator, SkillInstaller, SkillManifestStore, SlashCommandRegistry, SpecDrivenDev, SpecParser, SpecStore, SpecVersioning, StreamHangError, 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, computeTaskItemProgress, 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, emptyTaskFile, encryptConfigSecrets, enhanceUserPrompt, ensureDir, estimateRequestTokens, estimateRequestTokensCalibrated, estimateTextTokens, estimateToolDefTokens, estimateToolInputTokens, estimateToolResultTokens, everArtServer, expandGlob, expectDefined, extractRunEnv, filesystemServer, findCriticalPath, flagsToConfigPatch, formatContextWindowModeList, formatGoal, formatHumanPrompt, formatPlan, formatPlanTemplates, formatTaskList, formatTaskProgress, 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, loadTasks, 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, parseEntries, parseProgressFromText, parseSkillRef, pendingBtwCount, phaseForRole, projectHash, projectSlug, recentTextTurns, recordActualUsage, recordProgress, removePlanItem, renderProgress, renderPrometheus, renderSpecAnalysis, renderTaskGraph, renderTaskList, repairToolUseAdjacency, resetCalibration, resolveAuditLevel, resolveContextWindowPolicy, resolveModelMatrix, resolveSessionLoggingConfig, resolveWstackPaths, rewriteConfigEncrypted, rosterSummaryFromConfigs, runConfigMigrations, runProviderWithRetry, runShellHook, safeParse, safeStringify, sanitizeJsonString, saveGoal, savePlan, saveTasks, saveTodosCheckpoint, scoreAgents, securitySlashCommand, sentinelServer, setBtwNote, setOutputLineGuard, setPlanItemStatus, setProgress, setRawMode, shouldEnhance, slackServer, sleep, stableStringify, startMetricsServer, startOtlpMetricsExporter, startOtlpTraceExporter, stripAnsi, summarizeUsage, templateToMarkdown, toStyle, toWrongStackError, topologicalSort, unifiedDiff, unloadPlugins, validateAgainstSchema, wireMetricsToEvents, withFileLock, wrapAsState, writeErr, writeOut, zaiVisionServer };
32947
33202
  //# sourceMappingURL=index.js.map
32948
33203
  //# sourceMappingURL=index.js.map