reasonix 0.36.2 → 0.38.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 (87) hide show
  1. package/README.md +48 -75
  2. package/README.zh-CN.md +48 -32
  3. package/dist/cli/{chat-QSM6JKUA.js → chat-FPEYKTMI.js} +16 -17
  4. package/dist/cli/{chunk-T52GAWPP.js → chunk-3VTV4WAH.js} +2 -2
  5. package/dist/cli/{chunk-NHV5YGTB.js → chunk-4PNXH2MH.js} +1860 -1249
  6. package/dist/cli/chunk-4PNXH2MH.js.map +1 -0
  7. package/dist/cli/{chunk-DFP4YSVM.js → chunk-6CXT5JRM.js} +17 -2
  8. package/dist/cli/{chunk-DFP4YSVM.js.map → chunk-6CXT5JRM.js.map} +1 -1
  9. package/dist/cli/{chunk-G3XNWSFN.js → chunk-6NMWJSES.js} +2 -2
  10. package/dist/cli/{chunk-4D6TT2IB.js → chunk-A63QT566.js} +36 -15
  11. package/dist/cli/chunk-A63QT566.js.map +1 -0
  12. package/dist/cli/{chunk-4Q3GRJIU.js → chunk-AATCLE5N.js} +2 -2
  13. package/dist/cli/{chunk-BHLHOS5Y.js → chunk-BW2HWSYH.js} +315 -5
  14. package/dist/cli/chunk-BW2HWSYH.js.map +1 -0
  15. package/dist/cli/{chunk-ZJR4QLXB.js → chunk-FB46F6H4.js} +2 -2
  16. package/dist/cli/{chunk-MLXUGPJE.js → chunk-FYKZB6TX.js} +490 -8
  17. package/dist/cli/chunk-FYKZB6TX.js.map +1 -0
  18. package/dist/cli/{chunk-XQIFIB3U.js → chunk-JOFZ6AW5.js} +2 -2
  19. package/dist/cli/{chunk-IPCPEZWQ.js → chunk-LMNAMITH.js} +2 -2
  20. package/dist/cli/{chunk-S4GF3HPO.js → chunk-LY352GTC.js} +6 -4
  21. package/dist/cli/chunk-LY352GTC.js.map +1 -0
  22. package/dist/cli/{chunk-C5543CRX.js → chunk-NYP2DDDV.js} +41 -2
  23. package/dist/cli/chunk-NYP2DDDV.js.map +1 -0
  24. package/dist/cli/{chunk-BJ376EN3.js → chunk-T5U5JO7Q.js} +12 -9
  25. package/dist/cli/chunk-T5U5JO7Q.js.map +1 -0
  26. package/dist/cli/{chunk-K6W64QVE.js → chunk-XOIDSPMQ.js} +27 -7
  27. package/dist/cli/chunk-XOIDSPMQ.js.map +1 -0
  28. package/dist/cli/{chunk-RNSZYYGB.js → chunk-YJKLNYCP.js} +122 -33
  29. package/dist/cli/chunk-YJKLNYCP.js.map +1 -0
  30. package/dist/cli/{code-6C5A2CY3.js → code-GTE65OUT.js} +28 -21
  31. package/dist/cli/code-GTE65OUT.js.map +1 -0
  32. package/dist/cli/{commands-FE2UDFBC.js → commands-R4JWISND.js} +3 -4
  33. package/dist/cli/{commands-FE2UDFBC.js.map → commands-R4JWISND.js.map} +1 -1
  34. package/dist/cli/{commit-3IAGB22T.js → commit-TQ4DMUNS.js} +2 -3
  35. package/dist/cli/{commit-3IAGB22T.js.map → commit-TQ4DMUNS.js.map} +1 -1
  36. package/dist/cli/{doctor-DKD34EFD.js → doctor-GGK2JKTA.js} +7 -8
  37. package/dist/cli/{events-P27CX7LN.js → events-SQXPVV7B.js} +3 -3
  38. package/dist/cli/index.js +38 -37
  39. package/dist/cli/index.js.map +1 -1
  40. package/dist/cli/{mcp-2RDEQST6.js → mcp-M7I23TQ7.js} +2 -3
  41. package/dist/cli/{mcp-2RDEQST6.js.map → mcp-M7I23TQ7.js.map} +1 -1
  42. package/dist/cli/{mcp-browse-VM5GLRBQ.js → mcp-browse-TWO7RYT4.js} +2 -3
  43. package/dist/cli/{mcp-browse-VM5GLRBQ.js.map → mcp-browse-TWO7RYT4.js.map} +1 -1
  44. package/dist/cli/prompt-ODPFOKSH.js +13 -0
  45. package/dist/cli/{prune-sessions-ERL6B4G5.js → prune-sessions-FCFOYCBP.js} +2 -2
  46. package/dist/cli/{replay-D7RT2DR7.js → replay-R3QRXPI2.js} +13 -9
  47. package/dist/cli/replay-R3QRXPI2.js.map +1 -0
  48. package/dist/cli/{run-AG4Y45X7.js → run-WGSPYYOJ.js} +9 -10
  49. package/dist/cli/{run-AG4Y45X7.js.map → run-WGSPYYOJ.js.map} +1 -1
  50. package/dist/cli/{server-GNHR5K3N.js → server-IZPWQYG3.js} +98 -53
  51. package/dist/cli/{server-GNHR5K3N.js.map → server-IZPWQYG3.js.map} +1 -1
  52. package/dist/cli/{sessions-MHRF3GU4.js → sessions-E4UH5JYL.js} +9 -10
  53. package/dist/cli/{sessions-MHRF3GU4.js.map → sessions-E4UH5JYL.js.map} +1 -1
  54. package/dist/cli/{setup-IIAJXHP4.js → setup-FTZNN3TZ.js} +60 -15
  55. package/dist/cli/setup-FTZNN3TZ.js.map +1 -0
  56. package/dist/cli/{version-7AL4JZ63.js → version-MDVCFTKA.js} +9 -10
  57. package/dist/cli/{version-7AL4JZ63.js.map → version-MDVCFTKA.js.map} +1 -1
  58. package/dist/index.d.ts +9 -2
  59. package/dist/index.js +714 -54
  60. package/dist/index.js.map +1 -1
  61. package/package.json +1 -1
  62. package/dist/cli/chunk-4D6TT2IB.js.map +0 -1
  63. package/dist/cli/chunk-BHLHOS5Y.js.map +0 -1
  64. package/dist/cli/chunk-BJ376EN3.js.map +0 -1
  65. package/dist/cli/chunk-C5543CRX.js.map +0 -1
  66. package/dist/cli/chunk-K6W64QVE.js.map +0 -1
  67. package/dist/cli/chunk-MLXUGPJE.js.map +0 -1
  68. package/dist/cli/chunk-NHV5YGTB.js.map +0 -1
  69. package/dist/cli/chunk-RNSZYYGB.js.map +0 -1
  70. package/dist/cli/chunk-S4GF3HPO.js.map +0 -1
  71. package/dist/cli/chunk-WUI3P4RA.js +0 -319
  72. package/dist/cli/chunk-WUI3P4RA.js.map +0 -1
  73. package/dist/cli/code-6C5A2CY3.js.map +0 -1
  74. package/dist/cli/prompt-QSEB7HNQ.js +0 -11
  75. package/dist/cli/replay-D7RT2DR7.js.map +0 -1
  76. package/dist/cli/setup-IIAJXHP4.js.map +0 -1
  77. /package/dist/cli/{chat-QSM6JKUA.js.map → chat-FPEYKTMI.js.map} +0 -0
  78. /package/dist/cli/{chunk-T52GAWPP.js.map → chunk-3VTV4WAH.js.map} +0 -0
  79. /package/dist/cli/{chunk-G3XNWSFN.js.map → chunk-6NMWJSES.js.map} +0 -0
  80. /package/dist/cli/{chunk-4Q3GRJIU.js.map → chunk-AATCLE5N.js.map} +0 -0
  81. /package/dist/cli/{chunk-ZJR4QLXB.js.map → chunk-FB46F6H4.js.map} +0 -0
  82. /package/dist/cli/{chunk-XQIFIB3U.js.map → chunk-JOFZ6AW5.js.map} +0 -0
  83. /package/dist/cli/{chunk-IPCPEZWQ.js.map → chunk-LMNAMITH.js.map} +0 -0
  84. /package/dist/cli/{doctor-DKD34EFD.js.map → doctor-GGK2JKTA.js.map} +0 -0
  85. /package/dist/cli/{events-P27CX7LN.js.map → events-SQXPVV7B.js.map} +0 -0
  86. /package/dist/cli/{prompt-QSEB7HNQ.js.map → prompt-ODPFOKSH.js.map} +0 -0
  87. /package/dist/cli/{prune-sessions-ERL6B4G5.js.map → prune-sessions-FCFOYCBP.js.map} +0 -0
@@ -68,15 +68,21 @@ var TUI_FORMATTING_RULES = `Formatting (rendered in a TUI with a real markdown r
68
68
  - Code, file paths with line ranges, and shell commands \u2192 fenced code blocks (\`\`\`).
69
69
  - Do NOT draw decorative frames around content with \`\u250C\u2500\u2500\u2510 \u2502 \u2514\u2500\u2500\u2518\` characters. The renderer adds its own borders; extra ASCII art adds noise and shatters at narrow widths.
70
70
  - For flow charts and diagrams: a plain bullet list with \`\u2192\` or \`\u2193\` between steps. Don't try to draw boxes-and-arrows in ASCII; it never survives word-wrap.`;
71
- var ESCALATION_CONTRACT = `Cost-aware escalation (when you're running on deepseek-v4-flash):
71
+ function escalationContract(modelId) {
72
+ if (modelId === "deepseek-v4-pro") {
73
+ return `Cost-aware escalation note: you are running on \`${modelId}\` \u2014 the escalation tier. There is no higher tier to escalate to, so the \`<<<NEEDS_PRO>>>\` marker is a no-op for you; deliver the strongest answer you can directly. If asked which model you are, answer \`${modelId}\`.`;
74
+ }
75
+ return `Cost-aware escalation (you are running on \`${modelId}\`):
72
76
 
73
- If a task CLEARLY exceeds what flash can do well \u2014 complex cross-file architecture refactors, subtle concurrency / security / correctness invariants you can't resolve with confidence, or a design trade-off you'd be guessing at \u2014 output the marker as the FIRST line of your response (nothing before it, not even whitespace on a separate line). This aborts the current call and retries this turn on deepseek-v4-pro, one shot.
77
+ If a task CLEARLY exceeds what this tier can do well \u2014 complex cross-file architecture refactors, subtle concurrency / security / correctness invariants you can't resolve with confidence, or a design trade-off you'd be guessing at \u2014 output the marker as the FIRST line of your response (nothing before it, not even whitespace on a separate line). This aborts the current call and retries this turn on deepseek-v4-pro, one shot.
74
78
 
75
79
  Two accepted forms:
76
80
  - \`<<<NEEDS_PRO>>>\` \u2014 bare marker, no rationale.
77
81
  - \`<<<NEEDS_PRO: <one-sentence reason>>>>\` \u2014 preferred. The reason text appears in the user-visible warning ("\u21E7 flash requested escalation \u2014 <your reason>"), so they understand WHY a more expensive call is happening. Keep it under ~150 chars, no newlines, no nested \`>\` characters. Examples: \`<<<NEEDS_PRO: cross-file refactor across 6 modules with circular imports>>>\` or \`<<<NEEDS_PRO: subtle session-token race; flash would likely miss the locking invariant>>>\`.
78
82
 
79
- Do NOT emit any other content in the same response when you request escalation. Use this sparingly: normal tasks \u2014 reading files, small edits, clear bug fixes, straightforward feature additions \u2014 stay on flash. Request escalation ONLY when you would otherwise produce a guess or a visibly-mediocre answer. If in doubt, attempt the task on flash first; the system also escalates automatically if you hit 3+ repair / SEARCH-mismatch errors in a single turn (the user sees a typed breakdown).`;
83
+ Do NOT emit any other content in the same response when you request escalation. Use this sparingly: normal tasks \u2014 reading files, small edits, clear bug fixes, straightforward feature additions \u2014 stay on this tier. Request escalation ONLY when you would otherwise produce a guess or a visibly-mediocre answer. If in doubt, attempt the task here first; the system also escalates automatically if you hit 3+ repair / SEARCH-mismatch errors in a single turn (the user sees a typed breakdown). If asked which model you are, answer \`${modelId}\`.`;
84
+ }
85
+ var ESCALATION_CONTRACT = escalationContract("deepseek-v4-flash");
80
86
  var NEGATIVE_CLAIM_RULE = `Negative claims ("X is missing", "Y isn't implemented", "there's no Z") are the #1 hallucination shape. They feel safe to write because no citation seems possible \u2014 but that's exactly why you must NOT write them on instinct.
81
87
 
82
88
  If you have a search tool (\`search_content\`, \`grep\`, web search), call it FIRST before asserting absence:
@@ -93,6 +99,16 @@ var SKILLS_DIRNAME = "skills";
93
99
  var SKILL_FILE = "SKILL.md";
94
100
  var SKILLS_INDEX_MAX_CHARS = 4e3;
95
101
  var VALID_SKILL_NAME = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/;
102
+ function validateSkillFrontmatter(raw) {
103
+ const { data } = parseFrontmatter(raw);
104
+ const desc = (data.description ?? "").trim();
105
+ if (!desc) {
106
+ return {
107
+ error: `skill frontmatter is missing a non-empty "description:" line \u2014 without it the skill will not appear in the model's skills index`
108
+ };
109
+ }
110
+ return { ok: true };
111
+ }
96
112
  function parseFrontmatter(raw) {
97
113
  const lines = raw.split(/\r?\n/);
98
114
  if (lines[0] !== "---") return { data: {}, body: raw };
@@ -278,11 +294,14 @@ function skillIndexLine(s) {
278
294
  const clipped = safeDesc.length > max ? `${safeDesc.slice(0, Math.max(1, max - 1))}\u2026` : safeDesc;
279
295
  return clipped ? `- ${s.name}${tag} \u2014 ${clipped}` : `- ${s.name}${tag}`;
280
296
  }
297
+ var MISSING_DESCRIPTION_PLACEHOLDER = '(no description \u2014 frontmatter is missing a "description:" line; tell the user to add one)';
281
298
  function applySkillsIndex(basePrompt, opts = {}) {
282
299
  const store = new SkillStore(opts);
283
- const skills = store.list().filter((s) => s.description);
300
+ const skills = store.list();
284
301
  if (skills.length === 0) return basePrompt;
285
- const lines = skills.map(skillIndexLine);
302
+ const lines = skills.map(
303
+ (s) => skillIndexLine(s.description ? s : { ...s, description: MISSING_DESCRIPTION_PLACEHOLDER })
304
+ );
286
305
  const joined = lines.join("\n");
287
306
  const truncated = joined.length > SKILLS_INDEX_MAX_CHARS ? `${joined.slice(0, SKILLS_INDEX_MAX_CHARS)}
288
307
  \u2026 (truncated ${joined.length - SKILLS_INDEX_MAX_CHARS} chars)` : joined;
@@ -492,11 +511,12 @@ export {
492
511
  memoryEnabled,
493
512
  applyProjectMemory,
494
513
  TUI_FORMATTING_RULES,
495
- ESCALATION_CONTRACT,
514
+ escalationContract,
496
515
  NEGATIVE_CLAIM_RULE,
497
516
  SKILLS_DIRNAME,
498
517
  SKILL_FILE,
518
+ validateSkillFrontmatter,
499
519
  SkillStore,
500
520
  applySkillsIndex
501
521
  };
502
- //# sourceMappingURL=chunk-K6W64QVE.js.map
522
+ //# sourceMappingURL=chunk-XOIDSPMQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/memory/project.ts","../../src/prompt-fragments.ts","../../src/skills.ts"],"sourcesContent":["/** REASONIX.md pinned into ImmutablePrefix.system; edits invalidate the prefix-cache fingerprint. */\n\nimport { existsSync, readFileSync, statSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nexport const PROJECT_MEMORY_FILE = \"REASONIX.md\";\nexport const PROJECT_MEMORY_MAX_CHARS = 8000;\n\n/** Marker filenames that signal a foreign agent-platform workspace. */\nconst FOREIGN_PLATFORM_FILE_MARKERS = [\"SOUL.md\", \"AGENT.md\", \"PERSONA.md\"] as const;\n\n/** Returns the marker(s) that flagged rootDir as a foreign agent-platform data dir; null on a normal coding project. */\nexport function detectForeignAgentPlatform(rootDir: string): string[] | null {\n const hits: string[] = [];\n for (const name of FOREIGN_PLATFORM_FILE_MARKERS) {\n if (existsSync(join(rootDir, name))) hits.push(name);\n }\n if (isDir(join(rootDir, \"skills\")) && isDir(join(rootDir, \"memories\"))) {\n hits.push(\"skills/ + memories/\");\n }\n return hits.length > 0 ? hits : null;\n}\n\nfunction isDir(path: string): boolean {\n try {\n return statSync(path).isDirectory();\n } catch {\n return false;\n }\n}\n\nexport interface ProjectMemory {\n /** Absolute path the memory was read from. */\n path: string;\n /** Post-truncation content (may include a \"… (truncated N chars)\" marker). */\n content: string;\n /** Original byte length before truncation. */\n originalChars: number;\n /** True iff `originalChars > PROJECT_MEMORY_MAX_CHARS`. */\n truncated: boolean;\n}\n\n/** Empty / whitespace-only files return null so they don't perturb the cache prefix. */\nexport function readProjectMemory(rootDir: string): ProjectMemory | null {\n const path = join(rootDir, PROJECT_MEMORY_FILE);\n if (!existsSync(path)) return null;\n let raw: string;\n try {\n raw = readFileSync(path, \"utf8\");\n } catch {\n return null;\n }\n const trimmed = raw.trim();\n if (!trimmed) return null;\n const originalChars = trimmed.length;\n const truncated = originalChars > PROJECT_MEMORY_MAX_CHARS;\n const content = truncated\n ? `${trimmed.slice(0, PROJECT_MEMORY_MAX_CHARS)}\\n… (truncated ${\n originalChars - PROJECT_MEMORY_MAX_CHARS\n } chars)`\n : trimmed;\n return { path, content, originalChars, truncated };\n}\n\nexport function memoryEnabled(): boolean {\n const env = process.env.REASONIX_MEMORY;\n if (env === \"off\" || env === \"false\" || env === \"0\") return false;\n return true;\n}\n\n/** Deterministic — same memory file always yields the same prefix hash. */\nexport function applyProjectMemory(basePrompt: string, rootDir: string): string {\n if (!memoryEnabled()) return basePrompt;\n const mem = readProjectMemory(rootDir);\n if (!mem) return basePrompt;\n return `${basePrompt}\n\n# Project memory (REASONIX.md)\n\nThe user pinned these notes about this project — treat them as authoritative context for every turn:\n\n\\`\\`\\`\n${mem.content}\n\\`\\`\\`\n`;\n}\n","/** Shared prompt fragments — single source so house-style rules can't drift across agent/subagent/skill prompts. */\n\n/** Embedded literally — no interpolation, so prefix-cache hash stays stable across sessions. */\nexport const TUI_FORMATTING_RULES = `Formatting (rendered in a TUI with a real markdown renderer):\n- Tabular data → GitHub-Flavored Markdown tables with ASCII pipes (\\`| col | col |\\` header + \\`| --- | --- |\\` separator). Never use Unicode box-drawing characters (│ ─ ┼ ┌ ┐ └ ┘ ├ ┤) — they look intentional but break terminal word-wrap and render as garbled columns at narrow widths.\n- Keep table cells short (one phrase each). If a cell needs a paragraph, use bullets below the table instead.\n- Code, file paths with line ranges, and shell commands → fenced code blocks (\\`\\`\\`).\n- Do NOT draw decorative frames around content with \\`┌──┐ │ └──┘\\` characters. The renderer adds its own borders; extra ASCII art adds noise and shatters at narrow widths.\n- For flow charts and diagrams: a plain bullet list with \\`→\\` or \\`↓\\` between steps. Don't try to draw boxes-and-arrows in ASCII; it never survives word-wrap.`;\n\n/** Pro is the top tier — escalation is a no-op for it; flash + others get the full ladder. */\nexport function escalationContract(modelId: string): string {\n if (modelId === \"deepseek-v4-pro\") {\n return `Cost-aware escalation note: you are running on \\`${modelId}\\` — the escalation tier. There is no higher tier to escalate to, so the \\`<<<NEEDS_PRO>>>\\` marker is a no-op for you; deliver the strongest answer you can directly. If asked which model you are, answer \\`${modelId}\\`.`;\n }\n return `Cost-aware escalation (you are running on \\`${modelId}\\`):\n\nIf a task CLEARLY exceeds what this tier can do well — complex cross-file architecture refactors, subtle concurrency / security / correctness invariants you can't resolve with confidence, or a design trade-off you'd be guessing at — output the marker as the FIRST line of your response (nothing before it, not even whitespace on a separate line). This aborts the current call and retries this turn on deepseek-v4-pro, one shot.\n\nTwo accepted forms:\n- \\`<<<NEEDS_PRO>>>\\` — bare marker, no rationale.\n- \\`<<<NEEDS_PRO: <one-sentence reason>>>>\\` — preferred. The reason text appears in the user-visible warning (\"⇧ flash requested escalation — <your reason>\"), so they understand WHY a more expensive call is happening. Keep it under ~150 chars, no newlines, no nested \\`>\\` characters. Examples: \\`<<<NEEDS_PRO: cross-file refactor across 6 modules with circular imports>>>\\` or \\`<<<NEEDS_PRO: subtle session-token race; flash would likely miss the locking invariant>>>\\`.\n\nDo NOT emit any other content in the same response when you request escalation. Use this sparingly: normal tasks — reading files, small edits, clear bug fixes, straightforward feature additions — stay on this tier. Request escalation ONLY when you would otherwise produce a guess or a visibly-mediocre answer. If in doubt, attempt the task here first; the system also escalates automatically if you hit 3+ repair / SEARCH-mismatch errors in a single turn (the user sees a typed breakdown). If asked which model you are, answer \\`${modelId}\\`.`;\n}\n\n/** Backward-compat — pre-#582 callers (and the `CODE_SYSTEM_PROMPT` public-API const) keep the historical flash phrasing. */\nexport const ESCALATION_CONTRACT = escalationContract(\"deepseek-v4-flash\");\n\nexport const NEGATIVE_CLAIM_RULE = `Negative claims (\"X is missing\", \"Y isn't implemented\", \"there's no Z\") are the #1 hallucination shape. They feel safe to write because no citation seems possible — but that's exactly why you must NOT write them on instinct.\n\nIf you have a search tool (\\`search_content\\`, \\`grep\\`, web search), call it FIRST before asserting absence:\n- Returns matches → you were wrong; correct yourself and cite the matches.\n- Returns nothing → state the absence WITH the search query as evidence: \\`No callers of \\\\\\`foo()\\\\\\` found (search_content \"foo\").\\`\n\nIf you have no search tool, qualify hard: \"I haven't verified — this is a guess.\" Never assert absence with fake authority.`;\n","/** Project scope wins over global. Only names+descriptions enter the prefix; bodies load lazily into the append-only log. */\n\nimport { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { NEGATIVE_CLAIM_RULE, TUI_FORMATTING_RULES } from \"./prompt-fragments.js\";\n\nexport const SKILLS_DIRNAME = \"skills\";\nexport const SKILL_FILE = \"SKILL.md\";\n/** Cap on the pinned skills-index block, mirrors memory-index cap. */\nexport const SKILLS_INDEX_MAX_CHARS = 4000;\n/** Skill identifier shape — alnum + `_` + `-` + interior `.`, 1-64 chars. */\nconst VALID_SKILL_NAME = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/;\n\nexport type SkillScope = \"project\" | \"global\" | \"builtin\";\n\n/** inline = body enters parent log; subagent = isolated child loop, only final answer returns. */\nexport type SkillRunAs = \"inline\" | \"subagent\";\n\nexport interface Skill {\n /** Canonical name — sanitized, matches the directory / filename stem. */\n name: string;\n /** One-line description shown in the pinned index. */\n description: string;\n /** Full markdown body (post-frontmatter). Loaded on demand. */\n body: string;\n /** Which scope this skill was loaded from. */\n scope: SkillScope;\n /** Absolute path to the SKILL.md (or {name}.md) file, or \"(builtin)\" for shipped defaults. */\n path: string;\n /** Parsed `allowed-tools` frontmatter — when present, the spawned subagent's registry is scoped to these literal tool names. */\n allowedTools?: readonly string[];\n runAs: SkillRunAs;\n /** Subagent model override; only meaningful when `runAs === \"subagent\"`. */\n model?: string;\n}\n\nexport interface SkillStoreOptions {\n /** Override `$HOME` — tests point this at a tmpdir. */\n homeDir?: string;\n /** Required for project-scope skills; omit to read only the global scope. */\n projectRoot?: string;\n /** Suppress bundled built-ins — for tests asserting exact list contents. */\n disableBuiltins?: boolean;\n}\n\n/** Reject skill files that would silently disappear from the prefix index — `description:` is what `applySkillsIndex` keys on. */\nexport function validateSkillFrontmatter(raw: string): { ok: true } | { error: string } {\n const { data } = parseFrontmatter(raw);\n const desc = (data.description ?? \"\").trim();\n if (!desc) {\n return {\n error:\n 'skill frontmatter is missing a non-empty \"description:\" line — without it the skill will not appear in the model\\'s skills index',\n };\n }\n return { ok: true };\n}\n\nfunction parseFrontmatter(raw: string): { data: Record<string, string>; body: string } {\n const lines = raw.split(/\\r?\\n/);\n if (lines[0] !== \"---\") return { data: {}, body: raw };\n const end = lines.indexOf(\"---\", 1);\n if (end < 0) return { data: {}, body: raw };\n const data: Record<string, string> = {};\n for (let i = 1; i < end; i++) {\n const line = lines[i];\n if (!line) continue;\n const m = line.match(/^([a-zA-Z_][a-zA-Z0-9_-]*):\\s*(.*)$/);\n if (m?.[1]) data[m[1]] = (m[2] ?? \"\").trim();\n }\n return {\n data,\n body: lines\n .slice(end + 1)\n .join(\"\\n\")\n .replace(/^\\n+/, \"\"),\n };\n}\n\nfunction isValidSkillName(name: string): boolean {\n return VALID_SKILL_NAME.test(name);\n}\n\nfunction parseAllowedTools(raw: string | undefined): readonly string[] | undefined {\n if (raw === undefined) return undefined;\n const names = raw\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n return names.length > 0 ? Object.freeze(names) : undefined;\n}\n\nexport class SkillStore {\n private readonly homeDir: string;\n private readonly projectRoot: string | undefined;\n private readonly disableBuiltins: boolean;\n\n constructor(opts: SkillStoreOptions = {}) {\n this.homeDir = opts.homeDir ?? homedir();\n this.projectRoot = opts.projectRoot ? resolve(opts.projectRoot) : undefined;\n this.disableBuiltins = opts.disableBuiltins === true;\n }\n\n /** True iff this store was configured with a project root. */\n hasProjectScope(): boolean {\n return this.projectRoot !== undefined;\n }\n\n /** Project scope first so per-repo skill overrides a global with the same name. */\n roots(): Array<{ dir: string; scope: SkillScope }> {\n const out: Array<{ dir: string; scope: SkillScope }> = [];\n if (this.projectRoot) {\n out.push({\n dir: join(this.projectRoot, \".reasonix\", SKILLS_DIRNAME),\n scope: \"project\",\n });\n }\n out.push({ dir: join(this.homeDir, \".reasonix\", SKILLS_DIRNAME), scope: \"global\" });\n return out;\n }\n\n /** Higher-priority root wins on collision (project > global > builtin); sorted for stable prefix hash. */\n list(): Skill[] {\n const byName = new Map<string, Skill>();\n for (const { dir, scope } of this.roots()) {\n if (!existsSync(dir)) continue;\n let entries: import(\"node:fs\").Dirent[];\n try {\n entries = readdirSync(dir, { withFileTypes: true });\n } catch {\n continue;\n }\n for (const entry of entries) {\n const skill = this.readEntry(dir, scope, entry);\n if (!skill) continue;\n if (!byName.has(skill.name)) byName.set(skill.name, skill);\n }\n }\n // Builtins last so user/project files override on name collision.\n if (!this.disableBuiltins) {\n for (const skill of BUILTIN_SKILLS) {\n if (!byName.has(skill.name)) byName.set(skill.name, skill);\n }\n }\n return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name));\n }\n\n /** Scaffold a new skill stub at the chosen scope. Refuses to overwrite. */\n create(name: string, scope: \"project\" | \"global\"): { path: string } | { error: string } {\n return this.createWithContent(name, scope, skillStubBody(name));\n }\n\n /** Like `create` but writes caller-supplied file contents instead of the stub — used by the scaffold tool. */\n createWithContent(\n name: string,\n scope: \"project\" | \"global\",\n content: string,\n ): { path: string } | { error: string } {\n if (!isValidSkillName(name)) {\n return { error: `invalid skill name: \"${name}\" — use letters, digits, _, -, .` };\n }\n if (scope === \"project\" && !this.projectRoot) {\n return { error: \"project scope requires a workspace — run from `reasonix code`\" };\n }\n const root =\n scope === \"project\"\n ? join(this.projectRoot ?? \"\", \".reasonix\", SKILLS_DIRNAME)\n : join(this.homeDir, \".reasonix\", SKILLS_DIRNAME);\n const flat = join(root, `${name}.md`);\n const folder = join(root, name, SKILL_FILE);\n if (existsSync(folder)) {\n return { error: `skill \"${name}\" already exists at ${folder}` };\n }\n mkdirSync(dirname(flat), { recursive: true });\n try {\n writeFileSync(flat, content, { encoding: \"utf8\", flag: \"wx\" });\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"EEXIST\") {\n return { error: `skill \"${name}\" already exists at ${flat}` };\n }\n throw err;\n }\n return { path: flat };\n }\n\n /** Resolve one skill by name. Returns `null` if not found or malformed. */\n read(name: string): Skill | null {\n if (!isValidSkillName(name)) return null;\n for (const { dir, scope } of this.roots()) {\n if (!existsSync(dir)) continue;\n const dirCandidate = join(dir, name, SKILL_FILE);\n if (existsSync(dirCandidate) && statSync(dirCandidate).isFile()) {\n return this.parse(dirCandidate, name, scope);\n }\n const flatCandidate = join(dir, `${name}.md`);\n if (existsSync(flatCandidate) && statSync(flatCandidate).isFile()) {\n return this.parse(flatCandidate, name, scope);\n }\n }\n if (!this.disableBuiltins) {\n for (const skill of BUILTIN_SKILLS) {\n if (skill.name === name) return skill;\n }\n }\n return null;\n }\n\n private readEntry(dir: string, scope: SkillScope, entry: import(\"node:fs\").Dirent): Skill | null {\n if (entry.isDirectory()) {\n if (!isValidSkillName(entry.name)) return null;\n const file = join(dir, entry.name, SKILL_FILE);\n if (!existsSync(file)) return null;\n return this.parse(file, entry.name, scope);\n }\n if (entry.isFile() && entry.name.endsWith(\".md\")) {\n const stem = entry.name.slice(0, -3);\n if (!isValidSkillName(stem)) return null;\n return this.parse(join(dir, entry.name), stem, scope);\n }\n return null;\n }\n\n private parse(path: string, stem: string, scope: SkillScope): Skill | null {\n let raw: string;\n try {\n raw = readFileSync(path, \"utf8\");\n } catch {\n return null;\n }\n const { data, body } = parseFrontmatter(raw);\n const name = data.name && isValidSkillName(data.name) ? data.name : stem;\n return {\n name,\n description: (data.description ?? \"\").trim(),\n body: body.trim(),\n scope,\n path,\n allowedTools: parseAllowedTools(data[\"allowed-tools\"]),\n runAs: parseRunAs(data.runAs),\n model: data.model?.startsWith(\"deepseek-\") ? data.model : undefined,\n };\n }\n}\n\n/** Unknown values default to the safe (non-spawning) `inline` mode. */\nfunction parseRunAs(raw: string | undefined): SkillRunAs {\n return raw?.trim() === \"subagent\" ? \"subagent\" : \"inline\";\n}\n\n/** Stub markdown for `/skill new` — minimal frontmatter + scaffolding the user fills in. */\nfunction skillStubBody(name: string): string {\n return `---\nname: ${name}\ndescription: One-liner — what does this skill do?\n---\n\n# ${name}\n\nReplace this body with the playbook the model should follow when this skill is invoked.\n\nTips:\n- Reference tools by name (run_command, edit_file, search_content, ...)\n- Add \\`runAs: subagent\\` to frontmatter to spawn an isolated subagent loop\n- Add \\`allowed-tools: read_file, search_content\\` to scope a subagent's tools\n`;\n}\n\n/** Subagent tag goes AFTER the name in brackets — leading-marker tags get copied into `name` arg verbatim. */\nfunction skillIndexLine(s: Pick<Skill, \"name\" | \"description\" | \"runAs\">): string {\n const safeDesc = s.description.replace(/\\n/g, \" \").trim();\n const tag = s.runAs === \"subagent\" ? \" [🧬 subagent]\" : \"\";\n const max = 130 - s.name.length - tag.length;\n const clipped = safeDesc.length > max ? `${safeDesc.slice(0, Math.max(1, max - 1))}…` : safeDesc;\n return clipped ? `- ${s.name}${tag} — ${clipped}` : `- ${s.name}${tag}`;\n}\n\nconst MISSING_DESCRIPTION_PLACEHOLDER =\n '(no description — frontmatter is missing a \"description:\" line; tell the user to add one)';\n\n/** Bodies stay out — prefix must stay short + cacheable; bodies load on demand. */\nexport function applySkillsIndex(basePrompt: string, opts: SkillStoreOptions = {}): string {\n const store = new SkillStore(opts);\n const skills = store.list();\n if (skills.length === 0) return basePrompt;\n const lines = skills.map((s) =>\n skillIndexLine(s.description ? s : { ...s, description: MISSING_DESCRIPTION_PLACEHOLDER }),\n );\n const joined = lines.join(\"\\n\");\n const truncated =\n joined.length > SKILLS_INDEX_MAX_CHARS\n ? `${joined.slice(0, SKILLS_INDEX_MAX_CHARS)}\\n… (truncated ${\n joined.length - SKILLS_INDEX_MAX_CHARS\n } chars)`\n : joined;\n return [\n basePrompt,\n \"\",\n \"# Skills — playbooks you can invoke\",\n \"\",\n 'One-liner index. Each entry is either a built-in or a user-authored playbook. Call `run_skill({ name: \"<skill-name>\", arguments: \"<task>\" })` — the `name` is JUST the skill identifier (e.g. `\"explore\"`), NOT the `[🧬 subagent]` tag that appears after it. Entries tagged `[🧬 subagent]` spawn an **isolated subagent** — its tool calls and reasoning never enter your context, only its final answer does. Use subagent skills for tasks that would otherwise flood your context (deep exploration, multi-step research, anything where you only need the conclusion). Plain skills are inlined: their body becomes a tool result you read and act on directly. The user can also invoke a skill via `/skill <name>`.',\n \"\",\n \"```\",\n truncated,\n \"```\",\n ].join(\"\\n\");\n}\n\nconst BUILTIN_EXPLORE_BODY = `You are running as an exploration subagent. Your job is to investigate the codebase the parent agent pointed you at, then return one focused, distilled answer.\n\nHow to operate:\n- Use read_file, search_files, search_content, directory_tree, list_directory, get_file_info as your primary tools. Stay read-only.\n- For \"find all places that call / reference / use X\" questions, use \\`search_content\\` (content grep) — NOT \\`search_files\\` (which only matches file names). This is the most common subagent mistake; using the wrong tool gives empty results and you waste your iter budget chasing a phantom.\n- Cast a wide net first (search_content for symbol references, directory_tree for structure) to map the territory; then read the 3-10 most relevant files in full.\n- Don't read every file — be selective. Aim for breadth on the first pass, depth only where the question demands it.\n- Stop exploring as soon as you can answer the question. The parent doesn't see your tool calls, so over-exploration is pure waste.\n\nYour final answer:\n- One paragraph (or a few short bullets). Lead with the conclusion.\n- Cite specific file paths + line ranges when they support the answer.\n- If the question can't be answered from what you found, say so plainly and suggest where to look next.\n- No follow-up offers, no \"let me know if you need more.\" The parent will ask again if they need more.\n\n${NEGATIVE_CLAIM_RULE}\n\n${TUI_FORMATTING_RULES}\n\nThe 'task' the parent gave you is the question you must answer. Treat any other reading of it as scope creep.`;\n\nconst BUILTIN_RESEARCH_BODY = `You are running as a research subagent. Your job is to gather information from code AND the web, synthesize it, and return one focused conclusion.\n\nHow to operate:\n- Combine code reading (read_file, search_files) with web tools (web_search, web_fetch) as appropriate to the question.\n- For \"how does X work\" / \"is Y supported\" questions: web first to find the canonical reference, then verify against the local code.\n- For \"what's our policy on Z\" / \"where do we use Q\": local code first, web only if you need to compare against external standards.\n- Cap yourself at ~10 tool calls. If you can't converge in 10, return what you have plus a note about what's missing.\n\nYour final answer:\n- One paragraph (or short bullets). Lead with the conclusion.\n- Cite both code (file:line) AND web sources (URL) when they back the answer.\n- Distinguish \"I verified this in code\" from \"I read this on a docs page\" — the parent will trust the former more.\n- If the answer is uncertain, say so. Don't invent confidence.\n\n${NEGATIVE_CLAIM_RULE}\n\n${TUI_FORMATTING_RULES}\n\nThe 'task' the parent gave you is the research question. Stay on it.`;\n\nconst BUILTIN_REVIEW_BODY = `You are running as a code-review subagent. Your job is to inspect the changes the user is about to ship — usually the current git branch vs its upstream — and produce a focused review the parent can hand back to the user.\n\nHow to operate:\n- Default scope: the current branch's diff vs the default branch. If the user's task names a specific commit range or files, honor that instead.\n- Discover scope first: \\`run_command git status\\`, \\`git diff --stat\\`, \\`git log --oneline\\` to see what changed. Then \\`git diff\\` (or \\`git diff <base>...HEAD\\`) for the actual hunks.\n- Read the touched files (\\`read_file\\`) when the diff alone doesn't carry enough context — function signatures, surrounding invariants, callers.\n- For \"any callers depending on this?\" questions: \\`search_content\\` against the symbol BEFORE asserting impact.\n- Stay read-only. Never \\`run_command git commit\\`, never write files, never propose SEARCH/REPLACE blocks. The parent decides whether to act on your findings.\n- Cap yourself at ~12 tool calls. If the diff is too big to review in one pass, pick the riskiest 2-3 files and say so explicitly.\n\nWhat to look for, in priority order:\n1. **Correctness bugs** — off-by-one, null/undefined handling, race conditions, wrong sign / wrong operator, edge cases the code doesn't handle.\n2. **Security** — injection (SQL, shell, path traversal), secrets in code, missing authz checks, unsafe deserialization.\n3. **Behavior changes the diff hides** — renames that miss callers, removed branches that were load-bearing, error-handling that now swallows what used to surface.\n4. **Tests** — does the change have tests for the new behavior? Are existing tests still meaningful, or did the change make them tautological?\n5. **Style + consistency** — only flag deviations that matter (unsafe \\`any\\`, missing types in TypeScript, inconsistent error shape). Don't pile on cosmetic nits if the substance is clean.\n\nYour final answer:\n- Lead with a one-sentence verdict: \"ship as-is\" / \"minor nits, OK to ship after\" / \"blocking issues, do not ship\".\n- Then a short bulleted list of issues, each with: file:line citation + the problem in one sentence + what to change.\n- Group by severity if you have more than 4 items: **Blocking**, **Should-fix**, **Nits**.\n- If everything looks clean, say so plainly. Don't manufacture concerns.\n\n${NEGATIVE_CLAIM_RULE}\n\n${TUI_FORMATTING_RULES}\n\nThe 'task' the parent gave you describes WHAT to review (a branch, a file set, or \"the pending changes\"). Stay on it; don't redesign the feature.`;\n\nconst BUILTIN_SECURITY_REVIEW_BODY = `You are running as a security-review subagent. Your job is to inspect the changes the user is about to ship — usually the current git branch vs its upstream — through a security lens specifically, and report exploitable issues.\n\nHow to operate:\n- Default scope: the current branch's diff vs the default branch. If the user names a different range or a directory, honor that.\n- Discover scope first: \\`git status\\`, \\`git diff --stat\\`, \\`git diff <base>...HEAD\\`. Read touched files (\\`read_file\\`) when the diff alone doesn't carry security context — auth checks, input validation, the actual handler that calls into the changed function.\n- Use \\`search_content\\` to verify \"is this user-controlled input ever sanitized later?\" / \"are there other call sites that depend on this validation?\" before asserting impact.\n- Stay read-only. Never write, never run destructive commands, never propose SEARCH/REPLACE blocks. The parent decides what to act on.\n- Cap yourself at ~12 tool calls. If the diff is too big, focus on the riskiest 2-3 files and say so explicitly.\n\nThreat model — flag with severity:\n\n**CRITICAL** (do-not-ship):\n- SQL / NoSQL / shell / template injection — user input concatenated into a query, command, or template without parameterization.\n- Path traversal — user-controlled filenames touching the filesystem without canonicalization + sandbox check.\n- Authentication / authorization missing — endpoints / actions that should require a session check but don't.\n- Hardcoded secrets — API keys, passwords, signing tokens visible in the diff.\n- Deserialization of untrusted input — \\`pickle.loads\\`, \\`yaml.load\\` (non-safe), \\`eval\\`, \\`Function()\\`, \\`unserialize()\\`.\n- Cryptographic mistakes — homemade crypto, weak hashes (MD5/SHA-1) for passwords, missing IVs, ECB mode, predictable nonces.\n\n**HIGH**:\n- XSS — user input rendered into HTML without escaping (or wrong escaping context).\n- SSRF — fetching URLs from user input without an allowlist.\n- Race conditions in security-relevant code — TOCTOU on auth/file checks.\n- Open redirects — user-controlled URL passed to a redirect helper.\n- Insufficient logging on security events (login failure, permission denial) — only flag if the codebase clearly DOES log elsewhere.\n\n**MEDIUM**:\n- Verbose error messages leaking internal paths / stack traces / SQL.\n- Missing rate limiting on a credential / token endpoint.\n- Cross-origin / cookie-flag issues (missing \\`Secure\\` / \\`HttpOnly\\` / \\`SameSite\\`).\n\nThings to NOT pile on (out of scope here — the regular /review covers them):\n- Style, formatting, naming.\n- Performance, refactor opportunities, test coverage gaps that aren't security-relevant.\n- \"Should be a constant\" / \"extract this helper\" — irrelevant to ship-blocking.\n\nYour final answer:\n- Lead with a one-sentence verdict: \"no security issues found\", \"minor concerns\", or \"blocking issues\".\n- Then a list grouped by severity. Each item: file:line + 1-sentence threat + 1-sentence fix direction (no full SEARCH/REPLACE — the user / parent agent will write that).\n- If clean, say so plainly. Don't manufacture findings.\n\n${NEGATIVE_CLAIM_RULE}\n\n${TUI_FORMATTING_RULES}\n\nThe 'task' the parent gave you names what to review. Stay on it; don't redesign the feature.`;\n\nconst BUILTIN_TEST_BODY = `You are running as the parent agent — this skill is INLINED, not a subagent. The user invoked /test (or asked you to \"run the tests and fix failures\"). Your job: run the project's test suite, diagnose any failure, propose fixes as SEARCH/REPLACE edit blocks, then re-run. Repeat until green or you hit a wall you should escalate.\n\nHow to operate:\n\n1. **Detect the test command**.\n - Look for \\`package.json\\` → \\`scripts.test\\` first (most common: \\`npm test\\`, \\`pnpm test\\`, \\`yarn test\\`).\n - If no package.json or no test script: try \\`pytest\\`, \\`go test ./...\\`, \\`cargo test\\` based on what files exist (pyproject.toml/requirements.txt → pytest; go.mod → go test; Cargo.toml → cargo test).\n - If you can't tell, ASK the user for the command — don't guess. One question, one tool call to confirm.\n\n2. **Run it via run_command** (typical timeout 120s, bigger if the suite is large). Capture stdout + stderr.\n\n3. **Read the failures**. Pull out: which test names failed, the actual error/traceback, the file + line that threw. Don't just paraphrase — locate the exact assertion or stack frame.\n\n4. **Propose fixes**. For each distinct failure:\n - If the failure is in PRODUCTION code (test catches a real bug) → propose a SEARCH/REPLACE that fixes the production code.\n - If the failure is in TEST code (test is wrong, codebase is right) → propose a SEARCH/REPLACE that updates the test, AND say so explicitly: \"This is a test bug, not a production bug — updating the assertion.\"\n - If the failure is environmental (missing dep, wrong node version, missing fixture file) → say so and stop. Don't try to install packages or change config without checking with the user.\n\n5. **Apply + re-run**. After the user accepts the edit blocks, run the test command again. Iterate.\n\n6. **Stop conditions**:\n - All tests pass → report green, summarize what changed.\n - Same test still failing after 2 fix attempts on the same line → STOP. Tell the user \"I've tried twice, it's still failing — here's what I think is happening, want me to try a different angle?\". Don't loop indefinitely.\n - 3+ unrelated failures → fix one at a time, smallest first, so each pass narrows the surface.\n\nDon't:\n- Run \\`npm install\\` / \\`pip install\\` / \\`cargo update\\` without asking — those mutate lockfiles and have global effects.\n- Disable, skip, or delete failing tests to \"make it green\". If a test seems wrong, update its assertion with a one-sentence explanation, but never add \\`.skip\\` / \\`it.skip\\` / \\`@pytest.mark.skip\\`.\n- Modify the test runner config (vitest.config, jest.config, etc.) to silence failures.\n\nLead each turn with a one-line status: \"▸ running \\`npm test\\` ...\" → \"▸ 2 failures in tests/foo.test.ts — first is …\" → so the user always knows where you are without scrolling tool output.`;\n\nconst BUILTIN_SKILLS: readonly Skill[] = Object.freeze([\n Object.freeze<Skill>({\n name: \"explore\",\n description:\n \"Explore the codebase in an isolated subagent — wide-net read-only investigation that returns one distilled answer. Best for: 'find all places that...', 'how does X work across the project', 'survey the code for Y'.\",\n body: BUILTIN_EXPLORE_BODY,\n scope: \"builtin\",\n path: \"(builtin)\",\n runAs: \"subagent\",\n }),\n Object.freeze<Skill>({\n name: \"research\",\n description:\n \"Research a question by combining web search + code reading in an isolated subagent. Best for: 'is X feature supported by lib Y', 'what's the canonical way to do Z', 'compare our impl against the spec'.\",\n body: BUILTIN_RESEARCH_BODY,\n scope: \"builtin\",\n path: \"(builtin)\",\n runAs: \"subagent\",\n }),\n Object.freeze<Skill>({\n name: \"review\",\n description:\n \"Review the pending changes (current branch diff by default) in an isolated subagent — flags correctness, security, missing tests, hidden behavior changes; reports verdict + per-issue file:line. Read-only; the parent decides what to act on.\",\n body: BUILTIN_REVIEW_BODY,\n scope: \"builtin\",\n path: \"(builtin)\",\n runAs: \"subagent\",\n }),\n Object.freeze<Skill>({\n name: \"security-review\",\n description:\n \"Security-focused review of the current branch diff in an isolated subagent — flags injection/authz/secrets/deserialization/path-traversal/crypto issues, severity-tagged. Read-only. Use when shipping changes that touch auth, input parsing, file IO, or external requests.\",\n body: BUILTIN_SECURITY_REVIEW_BODY,\n scope: \"builtin\",\n path: \"(builtin)\",\n runAs: \"subagent\",\n }),\n Object.freeze<Skill>({\n name: \"test\",\n description:\n \"Run the project's test suite, diagnose failures, propose SEARCH/REPLACE fixes, re-run until green (or stop after 2 fix attempts on the same failure). Inlined — runs in the parent loop so you see the edit blocks and can /apply them. Detects npm/pnpm/yarn/pytest/go/cargo.\",\n body: BUILTIN_TEST_BODY,\n scope: \"builtin\",\n path: \"(builtin)\",\n runAs: \"inline\",\n }),\n]);\n"],"mappings":";;;AAEA,SAAS,YAAY,cAAc,gBAAgB;AACnD,SAAS,YAAY;AAEd,IAAM,sBAAsB;AAC5B,IAA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OAAO;AAAA,IACP,MAAM;AAAA,IACN,OAAO;AAAA,EACT,CAAC;AAAA,EACD,OAAO,OAAc;AAAA,IACnB,MAAM;AAAA,IACN,aACE;AAAA,IACF,MAAM;AAAA,IACN,OAAO;AAAA,IACP,MAAM;AAAA,IACN,OAAO;AAAA,EACT,CAAC;AACH,CAAC;","names":["existsSync","readFileSync","statSync","join","join","existsSync","statSync","readFileSync"]}
@@ -2,7 +2,7 @@
2
2
  import {
3
3
  MemoryStore,
4
4
  sanitizeMemoryName
5
- } from "./chunk-4D6TT2IB.js";
5
+ } from "./chunk-A63QT566.js";
6
6
  import {
7
7
  countTokens,
8
8
  estimateConversationTokens,
@@ -13,16 +13,15 @@ import {
13
13
  } from "./chunk-KMWKGPFZ.js";
14
14
  import {
15
15
  pauseGate
16
- } from "./chunk-S4GF3HPO.js";
16
+ } from "./chunk-LY352GTC.js";
17
17
  import {
18
- ESCALATION_CONTRACT,
19
18
  NEGATIVE_CLAIM_RULE,
20
19
  TUI_FORMATTING_RULES
21
- } from "./chunk-K6W64QVE.js";
20
+ } from "./chunk-XOIDSPMQ.js";
22
21
  import {
23
22
  formatHookOutcomeMessage,
24
23
  runHooks
25
- } from "./chunk-IPCPEZWQ.js";
24
+ } from "./chunk-LMNAMITH.js";
26
25
  import {
27
26
  ignoredByLayers,
28
27
  loadGitignoreAt,
@@ -30,18 +29,19 @@ import {
30
29
  } from "./chunk-5X7LZJDE.js";
31
30
  import {
32
31
  appendSessionMessage,
32
+ archiveSession,
33
33
  loadSessionMessages,
34
34
  loadSessionMeta,
35
35
  rewriteSession
36
- } from "./chunk-DFP4YSVM.js";
36
+ } from "./chunk-6CXT5JRM.js";
37
37
  import {
38
38
  t
39
- } from "./chunk-MLXUGPJE.js";
39
+ } from "./chunk-FYKZB6TX.js";
40
40
  import {
41
41
  DEFAULT_INDEX_EXCLUDES,
42
42
  webSearchEndpoint,
43
43
  webSearchEngine
44
- } from "./chunk-BHLHOS5Y.js";
44
+ } from "./chunk-BW2HWSYH.js";
45
45
  import {
46
46
  DEEPSEEK_CONTEXT_TOKENS,
47
47
  DEFAULT_CONTEXT_TOKENS,
@@ -309,6 +309,10 @@ var ToolRegistry = class {
309
309
  setResultAugmenter(fn) {
310
310
  this._resultAugmenter = fn;
311
311
  }
312
+ /** True when an augmenter is already wired — lets late-installing callers skip clobbering an earlier one. */
313
+ get hasResultAugmenter() {
314
+ return this._resultAugmenter !== null;
315
+ }
312
316
  register(def) {
313
317
  if (!def.name) throw new Error("tool requires a name");
314
318
  const internal = { ...def };
@@ -1375,6 +1379,7 @@ function signature(call) {
1375
1379
 
1376
1380
  // src/loop.ts
1377
1381
  var ESCALATION_MODEL = "deepseek-v4-pro";
1382
+ var PARENT_BUDGET_WARN_THRESHOLD = 5;
1378
1383
  var CacheFirstLoop = class {
1379
1384
  client;
1380
1385
  prefix;
@@ -1411,6 +1416,7 @@ var CacheFirstLoop = class {
1411
1416
  _turnFailures = new TurnFailureTracker();
1412
1417
  _turnSelfCorrected = false;
1413
1418
  _foldedThisTurn = false;
1419
+ _toolDispatchesThisStep = 0;
1414
1420
  context;
1415
1421
  /** Subscribe API so UI hooks can derive `running` from finally-guaranteed insertions. */
1416
1422
  get inflight() {
@@ -1465,6 +1471,23 @@ var CacheFirstLoop = class {
1465
1471
  stormThreshold: parsePositiveIntEnv(process.env.REASONIX_STORM_THRESHOLD),
1466
1472
  stormWindow: parsePositiveIntEnv(process.env.REASONIX_STORM_WINDOW)
1467
1473
  });
1474
+ if (!this.tools.hasResultAugmenter) {
1475
+ this.tools.setResultAugmenter((_name, _args, result) => {
1476
+ this._toolDispatchesThisStep++;
1477
+ const remaining = this.maxToolIters - this._toolDispatchesThisStep;
1478
+ if (remaining <= 0) {
1479
+ return `${result}
1480
+
1481
+ [budget: 0 of ${this.maxToolIters} tool calls left this turn \u2014 finalize NOW; the next iter forces a summary]`;
1482
+ }
1483
+ if (remaining <= PARENT_BUDGET_WARN_THRESHOLD) {
1484
+ return `${result}
1485
+
1486
+ [budget: ${remaining} of ${this.maxToolIters} tool calls left this turn \u2014 wrap up soon]`;
1487
+ }
1488
+ return result;
1489
+ });
1490
+ }
1468
1491
  this.sessionName = opts.session ?? null;
1469
1492
  if (this.sessionName) {
1470
1493
  const prior = loadSessionMessages(this.sessionName);
@@ -1535,19 +1558,21 @@ var CacheFirstLoop = class {
1535
1558
  }
1536
1559
  }
1537
1560
  }
1538
- /** "New chat" — drops messages but keeps session + immutable prefix (cache-first invariant). */
1561
+ /** "New chat" — drops in-memory messages, archives the on-disk transcript so it survives in Sessions, keeps sessionName so the prefix cache stays warm. */
1539
1562
  clearLog() {
1540
1563
  const dropped = this.log.length;
1541
1564
  this.log.compactInPlace([]);
1565
+ let archived = null;
1542
1566
  if (this.sessionName) {
1543
1567
  try {
1544
- rewriteSession(this.sessionName, []);
1568
+ archived = archiveSession(this.sessionName);
1569
+ if (archived === null) rewriteSession(this.sessionName, []);
1545
1570
  } catch {
1546
1571
  }
1547
1572
  }
1548
1573
  this.scratch.reset();
1549
1574
  this._inflight.clear();
1550
- return { dropped };
1575
+ return { dropped, archived };
1551
1576
  }
1552
1577
  configure(opts) {
1553
1578
  if (opts.model !== void 0) this.model = opts.model;
@@ -1716,6 +1741,7 @@ ${reason}`
1716
1741
  this._turnSelfCorrected = false;
1717
1742
  this._escalateThisTurn = false;
1718
1743
  this._foldedThisTurn = false;
1744
+ this._toolDispatchesThisStep = 0;
1719
1745
  let armedConsumed = false;
1720
1746
  if (this._proArmedForNextTurn) {
1721
1747
  this._escalateThisTurn = true;
@@ -3127,6 +3153,74 @@ Prefer \`list_directory\` for a single-level view, \`search_files\` to find spec
3127
3153
  return `moved ${displayRel4(rootDir, src)} \u2192 ${displayRel4(rootDir, dst)}`;
3128
3154
  }
3129
3155
  });
3156
+ registry.register({
3157
+ name: "delete_file",
3158
+ description: "Delete one file under the sandbox root. Refuses directories \u2014 use delete_directory for those. Errors if the path doesn't exist.",
3159
+ parameters: {
3160
+ type: "object",
3161
+ properties: { path: { type: "string" } },
3162
+ required: ["path"]
3163
+ },
3164
+ fn: async (args) => {
3165
+ const abs = safePath(args.path);
3166
+ const st = await fs4.lstat(abs);
3167
+ if (st.isDirectory()) {
3168
+ throw new Error(
3169
+ `delete_file: ${args.path} is a directory \u2014 use delete_directory to remove it`
3170
+ );
3171
+ }
3172
+ await fs4.unlink(abs);
3173
+ return `deleted ${displayRel4(rootDir, abs)}`;
3174
+ }
3175
+ });
3176
+ registry.register({
3177
+ name: "delete_directory",
3178
+ description: "Recursively delete a directory under the sandbox root. Pass `recursive:false` to refuse non-empty directories. Errors if the path doesn't exist.",
3179
+ parameters: {
3180
+ type: "object",
3181
+ properties: {
3182
+ path: { type: "string" },
3183
+ recursive: {
3184
+ type: "boolean",
3185
+ description: "When true (default) deletes the directory and all its contents. When false, only removes empty directories \u2014 non-empty refuses with an error."
3186
+ }
3187
+ },
3188
+ required: ["path"]
3189
+ },
3190
+ fn: async (args) => {
3191
+ const abs = safePath(args.path);
3192
+ const st = await fs4.lstat(abs);
3193
+ if (!st.isDirectory()) {
3194
+ throw new Error(`delete_directory: ${args.path} is a file \u2014 use delete_file to remove it`);
3195
+ }
3196
+ const recursive = args.recursive !== false;
3197
+ if (recursive) {
3198
+ await fs4.rm(abs, { recursive: true, force: false });
3199
+ } else {
3200
+ await fs4.rmdir(abs);
3201
+ }
3202
+ return `deleted ${displayRel4(rootDir, abs)}/${recursive ? " (recursive)" : ""}`;
3203
+ }
3204
+ });
3205
+ registry.register({
3206
+ name: "copy_file",
3207
+ description: "Copy a file or directory under the sandbox root. Both source and destination resolve under the sandbox. Parent directories of the destination are created as needed. Refuses to overwrite an existing destination \u2014 delete it first if you want to replace it.",
3208
+ parameters: {
3209
+ type: "object",
3210
+ properties: {
3211
+ source: { type: "string" },
3212
+ destination: { type: "string" }
3213
+ },
3214
+ required: ["source", "destination"]
3215
+ },
3216
+ fn: async (args) => {
3217
+ const src = safePath(args.source);
3218
+ const dst = safePath(args.destination);
3219
+ await fs4.mkdir(pathMod4.dirname(dst), { recursive: true });
3220
+ await fs4.cp(src, dst, { recursive: true, force: false, errorOnExist: true });
3221
+ return `copied ${displayRel4(rootDir, src)} \u2192 ${displayRel4(rootDir, dst)}`;
3222
+ }
3223
+ });
3130
3224
  return registry;
3131
3225
  }
3132
3226
 
@@ -3665,16 +3759,19 @@ async function searchMojeek(query, opts = {}) {
3665
3759
  signal: opts.signal,
3666
3760
  redirect: "follow"
3667
3761
  });
3668
- if (!resp.ok) throw new Error(`web_search ${resp.status}`);
3762
+ if (!resp.ok) throw new Error(t("webErrors.status", { status: resp.status }));
3669
3763
  const html = await resp.text();
3670
3764
  const results = parseMojeekResults(html).slice(0, topK);
3671
3765
  if (results.length === 0) {
3672
3766
  if (/no results found|did not match any documents/i.test(html)) return [];
3673
3767
  if (/captcha|verify you are human|access denied|forbidden/i.test(html)) {
3674
- throw new Error("web_search: Mojeek anti-bot page \u2014 rate-limited or blocked");
3768
+ throw new Error(t("webErrors.mojeekBlocked"));
3675
3769
  }
3676
3770
  throw new Error(
3677
- `web_search: 0 results but response doesn't look like a real empty page (${html.length} chars, first 120: ${html.slice(0, 120).replace(/\s+/g, " ")})`
3771
+ t("webErrors.mojeekNoResults", {
3772
+ chars: html.length,
3773
+ preview: html.slice(0, 120).replace(/\s+/g, " ")
3774
+ })
3678
3775
  );
3679
3776
  }
3680
3777
  return results;
@@ -3684,10 +3781,10 @@ function normalizeSearxngEndpoint(raw) {
3684
3781
  try {
3685
3782
  url = new URL(raw.includes("://") ? raw : `http://${raw}`);
3686
3783
  } catch {
3687
- throw new Error(`web_search: invalid SearXNG endpoint "${raw}"`);
3784
+ throw new Error(t("webErrors.invalidEndpoint", { endpoint: raw }));
3688
3785
  }
3689
3786
  if (url.protocol !== "http:" && url.protocol !== "https:") {
3690
- throw new Error(`web_search: SearXNG endpoint must be http(s), got ${url.protocol}`);
3787
+ throw new Error(t("webErrors.endpointMustBeHttp", { protocol: url.protocol }));
3691
3788
  }
3692
3789
  return url.origin;
3693
3790
  }
@@ -3707,19 +3804,17 @@ async function searchSearxng(query, opts = {}) {
3707
3804
  } catch (err) {
3708
3805
  if (err instanceof TypeError && err.message.includes("fetch")) {
3709
3806
  throw new Error(
3710
- `web_search: Cannot reach SearXNG server at ${opts.endpoint ?? "http://localhost:8080"}. Please install SearXNG (https://github.com/searxng/searxng) and start it (e.g. \`docker run -d -p 8080:8080 searxng/searxng\`), or switch to the default engine with /search-engine mojeek.`
3807
+ t("webErrors.cannotReach", { endpoint: opts.endpoint ?? "http://localhost:8080" })
3711
3808
  );
3712
3809
  }
3713
3810
  throw err;
3714
3811
  }
3715
- if (!resp.ok) throw new Error(`web_search ${resp.status}`);
3812
+ if (!resp.ok) throw new Error(t("webErrors.status", { status: resp.status }));
3716
3813
  const html = await resp.text();
3717
3814
  const results = parseSearxngHtmlResults(html).slice(0, topK);
3718
3815
  if (results.length === 0) {
3719
3816
  if (/no results found|did not match any documents/i.test(html)) return [];
3720
- throw new Error(
3721
- `web_search: 0 results but SearXNG response doesn't look like an empty results page (${html.length} chars)`
3722
- );
3817
+ throw new Error(t("webErrors.searxngNoResults", { chars: html.length }));
3723
3818
  }
3724
3819
  return results;
3725
3820
  }
@@ -3813,13 +3908,11 @@ async function webFetch(url, opts = {}) {
3813
3908
  clearTimeout(timer);
3814
3909
  opts.signal?.removeEventListener("abort", cancel);
3815
3910
  }
3816
- if (!resp.ok) throw new Error(`web_fetch ${resp.status} for ${url}`);
3911
+ if (!resp.ok) throw new Error(t("webErrors.fetchStatus", { status: resp.status, url }));
3817
3912
  const contentType = resp.headers.get("content-type") ?? "";
3818
3913
  const declaredLen = Number(resp.headers.get("content-length") ?? "");
3819
3914
  if (Number.isFinite(declaredLen) && declaredLen > FETCH_MAX_BYTES) {
3820
- throw new Error(
3821
- `web_fetch refused: content-length ${declaredLen} bytes exceeds ${FETCH_MAX_BYTES}-byte cap (${url})`
3822
- );
3915
+ throw new Error(t("webErrors.fetchTooLarge", { len: declaredLen, cap: FETCH_MAX_BYTES, url }));
3823
3916
  }
3824
3917
  const raw = await readBodyCapped(resp, FETCH_MAX_BYTES);
3825
3918
  const title = extractTitle(raw);
@@ -3846,9 +3939,7 @@ async function readBodyCapped(resp, maxBytes) {
3846
3939
  await reader.cancel();
3847
3940
  } catch {
3848
3941
  }
3849
- throw new Error(
3850
- `web_fetch refused: response body exceeded ${maxBytes}-byte cap (${total} bytes seen)`
3851
- );
3942
+ throw new Error(t("webErrors.fetchBodyTooLarge", { cap: maxBytes, seen: total }));
3852
3943
  }
3853
3944
  out += decoder.decode(value, { stream: true });
3854
3945
  }
@@ -3976,7 +4067,7 @@ function registerWebTools(registry, opts = {}) {
3976
4067
  },
3977
4068
  fn: async (args, ctx) => {
3978
4069
  if (!/^https?:\/\//i.test(args.url)) {
3979
- throw new Error("web_fetch: url must start with http:// or https://");
4070
+ throw new Error(t("webErrors.fetchInvalidUrl"));
3980
4071
  }
3981
4072
  const page = await webFetch(args.url, { maxChars: maxFetchChars, signal: ctx?.signal });
3982
4073
  const header = page.title ? `${page.title}
@@ -4597,7 +4688,7 @@ function nextRunId() {
4597
4688
  runIdCounter++;
4598
4689
  return `sub-${runIdCounter.toString(36)}`;
4599
4690
  }
4600
- var DEFAULT_SUBAGENT_SYSTEM = `You are a Reasonix subagent. The parent agent spawned you to handle one focused subtask, then return.
4691
+ var SUBAGENT_BASE_SYSTEM = `You are a Reasonix subagent. The parent agent spawned you to handle one focused subtask, then return.
4601
4692
 
4602
4693
  Rules:
4603
4694
  - Stay on the task you were given. Do not expand scope.
@@ -4607,8 +4698,6 @@ Rules:
4607
4698
 
4608
4699
  ${NEGATIVE_CLAIM_RULE}
4609
4700
 
4610
- ${ESCALATION_CONTRACT}
4611
-
4612
4701
  ${TUI_FORMATTING_RULES}`;
4613
4702
  var DEFAULT_MAX_RESULT_CHARS2 = 8e3;
4614
4703
  var DEFAULT_MAX_ITERS = 16;
@@ -5077,4 +5166,4 @@ export {
5077
5166
  snapshotBeforeEdits,
5078
5167
  restoreSnapshots
5079
5168
  };
5080
- //# sourceMappingURL=chunk-RNSZYYGB.js.map
5169
+ //# sourceMappingURL=chunk-YJKLNYCP.js.map