@ashx-j/lunr 0.2.10 → 0.2.11

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 (64) hide show
  1. package/dist/builtin-extensions/lunr-cron.d.ts.map +1 -1
  2. package/dist/builtin-extensions/lunr-cron.js +6 -1
  3. package/dist/builtin-extensions/lunr-cron.js.map +1 -1
  4. package/dist/builtin-extensions/pi-subagents/src/extension/fanout-child.d.ts.map +1 -1
  5. package/dist/builtin-extensions/pi-subagents/src/extension/fanout-child.js +1 -1
  6. package/dist/builtin-extensions/pi-subagents/src/extension/fanout-child.js.map +1 -1
  7. package/dist/builtin-extensions/pi-subagents/src/extension/index.d.ts.map +1 -1
  8. package/dist/builtin-extensions/pi-subagents/src/extension/index.js +3 -4
  9. package/dist/builtin-extensions/pi-subagents/src/extension/index.js.map +1 -1
  10. package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.d.ts +2 -2
  11. package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.d.ts.map +1 -1
  12. package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.js +4 -4
  13. package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.js.map +1 -1
  14. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.d.ts.map +1 -1
  15. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.js +8 -7
  16. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.js.map +1 -1
  17. package/dist/builtin-extensions/pi-subagents/src/shared/types.d.ts +2 -1
  18. package/dist/builtin-extensions/pi-subagents/src/shared/types.d.ts.map +1 -1
  19. package/dist/builtin-extensions/pi-subagents/src/shared/types.js.map +1 -1
  20. package/dist/catalog/models.json +1 -1
  21. package/dist/catalog/providers/openrouter.json +1 -1
  22. package/dist/catalog/providers/xai.json +1 -1
  23. package/dist/catalog/publication.json +2 -2
  24. package/dist/core/agent-session.d.ts.map +1 -1
  25. package/dist/core/agent-session.js +2 -2
  26. package/dist/core/agent-session.js.map +1 -1
  27. package/dist/core/models-store.d.ts.map +1 -1
  28. package/dist/core/models-store.js +13 -1
  29. package/dist/core/models-store.js.map +1 -1
  30. package/dist/core/permissions.d.ts +9 -0
  31. package/dist/core/permissions.d.ts.map +1 -1
  32. package/dist/core/permissions.js +60 -20
  33. package/dist/core/permissions.js.map +1 -1
  34. package/dist/core/plan-mode.d.ts.map +1 -1
  35. package/dist/core/plan-mode.js +49 -7
  36. package/dist/core/plan-mode.js.map +1 -1
  37. package/dist/core/swarm.d.ts +17 -4
  38. package/dist/core/swarm.d.ts.map +1 -1
  39. package/dist/core/swarm.js +36 -4
  40. package/dist/core/swarm.js.map +1 -1
  41. package/dist/gateway/agent-bridge.d.ts +1 -1
  42. package/dist/gateway/agent-bridge.d.ts.map +1 -1
  43. package/dist/gateway/agent-bridge.js +11 -1
  44. package/dist/gateway/agent-bridge.js.map +1 -1
  45. package/dist/gateway/commands.d.ts.map +1 -1
  46. package/dist/gateway/commands.js +2 -1
  47. package/dist/gateway/commands.js.map +1 -1
  48. package/dist/gateway/cron.d.ts +4 -1
  49. package/dist/gateway/cron.d.ts.map +1 -1
  50. package/dist/gateway/cron.js +17 -8
  51. package/dist/gateway/cron.js.map +1 -1
  52. package/dist/gateway/router.d.ts +1 -1
  53. package/dist/gateway/router.d.ts.map +1 -1
  54. package/dist/gateway/router.js.map +1 -1
  55. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  56. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  57. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  58. package/examples/extensions/gondolin/package-lock.json +2 -2
  59. package/examples/extensions/gondolin/package.json +1 -1
  60. package/examples/extensions/sandbox/package-lock.json +2 -2
  61. package/examples/extensions/sandbox/package.json +1 -1
  62. package/examples/extensions/with-deps/package-lock.json +2 -2
  63. package/examples/extensions/with-deps/package.json +1 -1
  64. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"plan-mode.js","sourceRoot":"","sources":["../../src/core/plan-mode.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,+DAA+D;AAC/D,MAAM,CAAC,MAAM,kBAAkB,GAC9B,yRAAuR,CAAC;AAEzR,4EAA4E;AAC5E,MAAM,CAAC,MAAM,uBAAuB,GAAG,0DAAwD,CAAC;AAEhG,MAAM,aAAa,GAAG,IAAI,GAAG,CAAC;IAC7B,MAAM;IACN,OAAO;IACP,cAAc;IACd,iBAAiB;IACjB,YAAY;IACZ,eAAe;IACf,MAAM;CACN,CAAC,CAAC;AAEH,iGAAiG;AACjG,MAAM,gBAAgB,GAAG,IAAI,GAAG,CAAC;IAChC,IAAI;IACJ,IAAI;IACJ,KAAK;IACL,KAAK;IACL,MAAM;IACN,IAAI;IACJ,MAAM;IACN,KAAK;IACL,MAAM;IACN,QAAQ;IACR,MAAM;IACN,MAAM;IACN,IAAI;IACJ,MAAM;IACN,MAAM;IACN,MAAM;IACN,MAAM;IACN,MAAM;IACN,KAAK;IACL,MAAM;IACN,MAAM;IACN,GAAG;IACH,MAAM;IACN,OAAO;IACP,OAAO;IACP,SAAS;IACT,MAAM;IACN,MAAM;IACN,IAAI;IACJ,QAAQ;IACR,KAAK;IACL,MAAM;IACN,KAAK;IACL,KAAK;IACL,UAAU;IACV,OAAO;IACP,UAAU;IACV,QAAQ;IACR,OAAO;IACP,MAAM;IACN,KAAK;IACL,IAAI;IACJ,MAAM;IACN,KAAK;IACL,MAAM;IACN,MAAM;IACN,KAAK;CACL,CAAC,CAAC;AAEH,MAAM,wBAAwB,GAAG,IAAI,GAAG,CAAC;IACxC,KAAK;IACL,QAAQ;IACR,MAAM;IACN,MAAM;IACN,OAAO;IACP,QAAQ;IACR,OAAO;IACP,UAAU;IACV,QAAQ;IACR,SAAS;IACT,IAAI;IACJ,IAAI;IACJ,OAAO;IACP,aAAa;IACb,QAAQ;IACR,OAAO;IACP,OAAO;IACP,QAAQ;IACR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CAAC,KAAK,YAAY;QAAE,KAAK,EAAE,CAAC;IAC7C,MAAM,UAAU,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,WAAW,EAAE,CAAC;IAC9C,IAAI,CAAC,UAAU;QAAE,OAAO,KAAK,CAAC;IAC9B,IAAI,UAAU,CAAC,UAAU,CAAC,GAAG,CAAC;QAAE,OAAO,KAAK,CAAC,CAAC,yCAAyC;IAEvF,IAAI,wBAAwB,CAAC,GAAG,CAAC,UAAU,CAAC;QAAE,OAAO,IAAI,CAAC;IAC1D,IAAI,2BAA2B,CAAC,GAAG,CAAC,UAAU,CAAC,EAAE,CAAC;QACjD,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC;QACnC,OAAO,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,8BAA8B,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IACtF,CAAC;IACD,OAAO,KAAK,CAAC;AAAA,CACb;AAED,SAAS,UAAU,CAAC,KAAa,EAAU;IAC1C,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACnC,OAAO,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,IAAI,KAAK,CAAC;AAAA,CACxC","sourcesContent":["/**\n * lunr: plan permission mode — read-only tool-gating heuristics + system-prompt addendum.\n *\n * Plan is a first-class permission mode (`PermissionMode = \"plan\"`). `gateToolCall`\n * in permissions.ts applies `planModeBlockReason` when the session is in plan:\n * `edit`/`write` and mutating `bash` are hard-blocked; read tools stay open.\n * InteractiveMode installs `PLAN_MODE_ADDENDUM` via the shared system-prompt\n * append slot (same slot auto mode uses).\n *\n * Bash heuristic (conservative, blocklist-based — NOT a security boundary):\n * - any `>`/`>>` redirect outside quotes blocks the whole command;\n * - the command is split on `;`, `|`, `&` separators (outside quotes) and every segment's\n * leading command must be read-only:\n * - known mutating commands (rm, mv, cp, mkdir, sed -i, tee, …) are blocked;\n * - `git` is limited to read-only subcommands (status/log/diff/show/… plus flag-only\n * branch/tag/remote); mutating subcommands (add/commit/push/checkout/…) are blocked;\n * - package managers are limited to read-only subcommands (install/add/remove/… blocked);\n * - arbitrary runners (sudo, xargs, npx, sh -c …) are blocked.\n * Unknown-but-not-listed commands are ALLOWED (blocklist, not allowlist) — the model is\n * additionally steered by the system-prompt addendum. False positives are expected; the\n * user can run the command themselves or exit plan mode with /plan off.\n */\n\n/** Appended to the system prompt while plan mode is active. */\nexport const PLAN_MODE_ADDENDUM =\n\t\"You are in plan mode. Investigate read-only, then present your plan by calling the present_plan tool with a concise summary — the user approves or declines it in a dialog. Do not make changes until the plan is approved. The user can also exit plan mode manually with /plan off.\";\n\n/** Error returned to the model when a tool call is blocked by plan mode. */\nexport const PLAN_MODE_BLOCK_MESSAGE = \"Plan mode is active — propose a plan; no file changes.\";\n\nconst BLOCKED_TOOLS = new Set([\n\t\"edit\",\n\t\"write\",\n\t\"behavior_add\",\n\t\"behavior_remove\",\n\t\"memory_add\",\n\t\"memory_remove\",\n\t\"cron\",\n]);\n\n/** Small allowlist of read-only commands permitted in plan mode. Everything else is rejected. */\nconst ALLOWED_COMMANDS = new Set([\n\t\"ls\",\n\t\"ll\",\n\t\"cat\",\n\t\"tac\",\n\t\"grep\",\n\t\"rg\",\n\t\"find\",\n\t\"pwd\",\n\t\"echo\",\n\t\"printf\",\n\t\"head\",\n\t\"tail\",\n\t\"wc\",\n\t\"less\",\n\t\"more\",\n\t\"sort\",\n\t\"uniq\",\n\t\"diff\",\n\t\"cmp\",\n\t\"comm\",\n\t\"test\",\n\t\"[\",\n\t\"true\",\n\t\"false\",\n\t\"which\",\n\t\"whereis\",\n\t\"stat\",\n\t\"file\",\n\t\"id\",\n\t\"whoami\",\n\t\"who\",\n\t\"date\",\n\t\"cal\",\n\t\"env\",\n\t\"printenv\",\n\t\"uname\",\n\t\"hostname\",\n\t\"uptime\",\n\t\"nproc\",\n\t\"tput\",\n\t\"git\",\n\t\"gh\",\n\t\"node\",\n\t\"npm\",\n\t\"pnpm\",\n\t\"yarn\",\n\t\"bun\",\n]);\n\nconst MUTATING_GIT_SUBCOMMANDS = new Set([\n\t\"add\",\n\t\"commit\",\n\t\"push\",\n\t\"pull\",\n\t\"merge\",\n\t\"rebase\",\n\t\"reset\",\n\t\"checkout\",\n\t\"switch\",\n\t\"restore\",\n\t\"rm\",\n\t\"mv\",\n\t\"stash\",\n\t\"cherry-pick\",\n\t\"revert\",\n\t\"clean\",\n\t\"fetch\",\n\t\"config\",\n\t\"apply\",\n\t\"am\",\n\t\"init\",\n\t\"clone\",\n\t\"submodule\",\n\t\"worktree\",\n\t\"gc\",\n\t\"prune\",\n\t\"update-index\",\n]);\n\n// git subcommands that are read-only only when they carry no positional args or\n// mutating flags (`git branch` lists, `git branch foo` / `git branch -d foo` mutate).\nconst CONDITIONAL_GIT_SUBCOMMANDS = new Set([\"branch\", \"tag\", \"remote\"]);\nconst CONDITIONAL_GIT_MUTATING_FLAGS = new Set([\"-d\", \"-D\", \"-m\", \"-M\", \"-c\", \"-C\"]);\n\nconst PACKAGE_MANAGER_MUTATIONS: Record<string, Set<string>> = {\n\tnpm: new Set([\n\t\t\"install\",\n\t\t\"add\",\n\t\t\"remove\",\n\t\t\"uninstall\",\n\t\t\"update\",\n\t\t\"upgrade\",\n\t\t\"publish\",\n\t\t\"link\",\n\t\t\"unlink\",\n\t\t\"ci\",\n\t\t\"init\",\n\t]),\n\tpnpm: new Set([\"install\", \"add\", \"remove\", \"uninstall\", \"update\", \"upgrade\", \"publish\", \"link\", \"unlink\", \"init\"]),\n\tyarn: new Set([\"install\", \"add\", \"remove\", \"uninstall\", \"upgrade\", \"publish\", \"link\", \"unlink\", \"init\"]),\n\tbun: new Set([\"install\", \"add\", \"remove\", \"uninstall\", \"update\", \"upgrade\", \"publish\", \"link\", \"unlink\", \"init\"]),\n};\n\n// Almost every subcommand mutates the system.\nconst ALWAYS_MUTATING_MANAGERS = new Set([\n\t\"apt\",\n\t\"apt-get\",\n\t\"brew\",\n\t\"dnf\",\n\t\"yum\",\n\t\"pacman\",\n\t\"choco\",\n\t\"winget\",\n\t\"scoop\",\n]);\n\n/** Flags that cause an interpreter to execute code and are never allowed in plan mode. */\nconst EXECUTING_NODE_FLAGS = new Set([\n\t\"-e\",\n\t\"--eval\",\n\t\"-p\",\n\t\"--print\",\n\t\"-r\",\n\t\"--require\",\n\t\"--import\",\n\t\"-i\",\n\t\"--interactive\",\n]);\nconst EXECUTING_PYTHON_FLAGS = new Set([\"-c\", \"-m\", \"-i\", \"--interactive\"]);\n\n/** Apply-mode rewrite only. Default / omitted `dry_run` is preview and stays allowed. */\nexport function isCodeRewriteMutating(input: unknown): boolean {\n\treturn (input as { dry_run?: unknown } | undefined)?.dry_run === false;\n}\n\n/**\n * Returns the block reason when plan mode should block this tool call, else undefined.\n */\nexport function planModeBlockReason(toolName: string, input: unknown): string | undefined {\n\tif (BLOCKED_TOOLS.has(toolName)) {\n\t\treturn PLAN_MODE_BLOCK_MESSAGE;\n\t}\n\tif (toolName === \"code_rewrite\" && isCodeRewriteMutating(input)) {\n\t\treturn PLAN_MODE_BLOCK_MESSAGE;\n\t}\n\tif (toolName === \"bash\") {\n\t\tconst command = readBashCommand(input);\n\t\tif (command && isMutatingBashCommand(command)) {\n\t\t\treturn `${PLAN_MODE_BLOCK_MESSAGE} Blocked command: ${command}`;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction readBashCommand(input: unknown): string {\n\tconst command = (input as { command?: unknown } | undefined)?.command;\n\treturn typeof command === \"string\" ? command : \"\";\n}\n\n/**\n * Plan-mode bash allowlist. A command is mutating unless every segment is a\n * known read-only command used safely (no redirects, no command substitution,\n * no process substitution, no executing-interpreter flags).\n */\nexport function isMutatingBashCommand(command: string): boolean {\n\tif (!command.trim()) return false;\n\n\t// Any output redirect outside quotes can write a file.\n\tif (hasUnquotedRedirect(command)) return true;\n\n\t// Command substitution / process substitution / grouped redirect syntaxes\n\t// bypass a simple command-name check.\n\tif (hasShellSubstitution(command)) return true;\n\n\t// Every segment separated by ; | & && || must individually be read-only.\n\tfor (const segment of splitShellSegments(command)) {\n\t\tif (isMutatingSegment(segment)) return true;\n\t}\n\treturn false;\n}\n\nfunction hasUnquotedRedirect(command: string): boolean {\n\tlet quote: \"'\" | '\"' | undefined;\n\tlet escaped = false;\n\tfor (let i = 0; i < command.length; i++) {\n\t\tconst ch = command[i];\n\t\tif (escaped) {\n\t\t\tescaped = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"\\\\\" && quote !== \"'\") {\n\t\t\tescaped = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (quote) {\n\t\t\tif (ch === quote) quote = undefined;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"'\" || ch === '\"') {\n\t\t\tquote = ch;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \">\") return true;\n\t}\n\treturn false;\n}\n\nfunction splitShellSegments(command: string): string[] {\n\tconst segments: string[] = [];\n\tlet quote: \"'\" | '\"' | undefined;\n\tlet escaped = false;\n\tlet start = 0;\n\tfor (let i = 0; i < command.length; i++) {\n\t\tconst ch = command[i];\n\t\tconst next = command[i + 1];\n\t\tif (escaped) {\n\t\t\tescaped = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"\\\\\" && quote !== \"'\") {\n\t\t\tescaped = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (quote) {\n\t\t\tif (ch === quote) quote = undefined;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"'\" || ch === '\"') {\n\t\t\tquote = ch;\n\t\t\tcontinue;\n\t\t}\n\t\t// Combined operators && and || split as one boundary.\n\t\tif ((ch === \"&\" && next === \"&\") || (ch === \"|\" && next === \"|\")) {\n\t\t\tsegments.push(command.slice(start, i));\n\t\t\ti++;\n\t\t\tstart = i + 1;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \";\" || ch === \"|\" || ch === \"&\" || ch === \"\\n\") {\n\t\t\tsegments.push(command.slice(start, i));\n\t\t\tstart = i + 1;\n\t\t}\n\t}\n\tsegments.push(command.slice(start));\n\treturn segments.map((s) => s.trim()).filter((s) => s.length > 0);\n}\n\n/** True when the command contains command/process substitution outside quotes. */\nfunction hasShellSubstitution(command: string): boolean {\n\tlet quote: \"'\" | '\"' | undefined;\n\tlet escaped = false;\n\tfor (let i = 0; i < command.length; i++) {\n\t\tconst ch = command[i];\n\t\tif (escaped) {\n\t\t\tescaped = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"\\\\\" && quote !== \"'\") {\n\t\t\tescaped = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (quote) {\n\t\t\tif (ch === quote) quote = undefined;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"'\" || ch === '\"') {\n\t\t\tquote = ch;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"`\") return true;\n\t\tif (ch === \"$\" && command[i + 1] === \"(\") return true;\n\t\tif (ch === \"<\" && command[i + 1] === \"(\") return true;\n\t\tif (ch === \">\" && command[i + 1] === \"(\") return true;\n\t\tif (ch === \"&\" && command[i + 1] === \">\") return true;\n\t}\n\treturn false;\n}\n\nfunction isMutatingSegment(segment: string): boolean {\n\tlet tokens = segment.split(/\\s+/).filter((t) => t.length > 0);\n\t// Skip leading env assignments (FOO=bar cmd …) and command wrappers we can't see through.\n\twhile (tokens.length > 0 && /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[0])) {\n\t\ttokens = tokens.slice(1);\n\t}\n\tif (tokens.length === 0) return false;\n\n\tconst command = basenameOf(tokens[0]).toLowerCase();\n\tconst args = tokens.slice(1);\n\n\tif (ALWAYS_MUTATING_MANAGERS.has(command)) return true;\n\n\tif (command === \"sed\") {\n\t\treturn args.some((a) => a === \"-i\" || a.startsWith(\"-i\") || a.startsWith(\"--in-place\") || /^-[^-]*i/.test(a));\n\t}\n\tif (command === \"find\") {\n\t\treturn args.some((a) => [\"-delete\", \"-exec\", \"-execdir\", \"-ok\", \"-okdir\"].includes(a));\n\t}\n\tif (command === \"git\") {\n\t\treturn isMutatingGit(args);\n\t}\n\tif (command === \"gh\") {\n\t\t// Allow read-only views; block everything that changes remote state.\n\t\tconst sub = `${args[0] ?? \"\"} ${args[1] ?? \"\"}`;\n\t\treturn ![\n\t\t\t\"pr view\",\n\t\t\t\"pr list\",\n\t\t\t\"pr status\",\n\t\t\t\"issue view\",\n\t\t\t\"issue list\",\n\t\t\t\"issue status\",\n\t\t\t\"repo view\",\n\t\t\t\"release view\",\n\t\t\t\"release list\",\n\t\t\t\"run list\",\n\t\t\t\"run view\",\n\t\t\t\"status\",\n\t\t].includes(sub.trim());\n\t}\n\tif (command === \"sh\" || command === \"bash\" || command === \"zsh\" || command === \"dash\") {\n\t\t// `sh -c '…'` runs arbitrary code; bare `sh script` also executes. Block -c; allow\n\t\t// nothing else is too restrictive for `bash --version`, so allow flag-only invocations.\n\t\treturn args.some((a) => a === \"-c\" || a === \"-s\") || args.some((a) => !a.startsWith(\"-\"));\n\t}\n\n\tconst pkgMutations = PACKAGE_MANAGER_MUTATIONS[command];\n\tif (pkgMutations) {\n\t\tconst subcommand = args.find((a) => !a.startsWith(\"-\"))?.toLowerCase();\n\t\treturn subcommand !== undefined && pkgMutations.has(subcommand);\n\t}\n\n\t// Node / Python interpreters: flag-only, no executing flags, no positional scripts.\n\tif (command === \"node\") {\n\t\treturn args.some((a) => !a.startsWith(\"-\")) || args.some((a) => EXECUTING_NODE_FLAGS.has(a));\n\t}\n\tif (command === \"python\" || command === \"python3\") {\n\t\treturn args.some((a) => !a.startsWith(\"-\")) || args.some((a) => EXECUTING_PYTHON_FLAGS.has(a));\n\t}\n\n\t// Final gate: the command must be in the read-only allowlist.\n\treturn !ALLOWED_COMMANDS.has(command);\n}\n\nfunction isMutatingGit(args: string[]): boolean {\n\t// Skip global flags like --no-pager / -C <dir> / -c key=val crudely: find the first\n\t// token that doesn't start with \"-\" (imperfect for -C/-c values; conservative is fine).\n\tlet index = 0;\n\twhile (args[index] === \"--no-pager\") index++;\n\tconst subcommand = args[index]?.toLowerCase();\n\tif (!subcommand) return false;\n\tif (subcommand.startsWith(\"-\")) return false; // bare `git --version` etc. is read-only\n\n\tif (MUTATING_GIT_SUBCOMMANDS.has(subcommand)) return true;\n\tif (CONDITIONAL_GIT_SUBCOMMANDS.has(subcommand)) {\n\t\tconst rest = args.slice(index + 1);\n\t\treturn rest.some((a) => !a.startsWith(\"-\") || CONDITIONAL_GIT_MUTATING_FLAGS.has(a));\n\t}\n\treturn false;\n}\n\nfunction basenameOf(token: string): string {\n\tconst parts = token.split(/[\\\\/]/);\n\treturn parts[parts.length - 1] ?? token;\n}\n"]}
1
+ {"version":3,"file":"plan-mode.js","sourceRoot":"","sources":["../../src/core/plan-mode.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,+DAA+D;AAC/D,MAAM,CAAC,MAAM,kBAAkB,GAC9B,yRAAuR,CAAC;AAEzR,4EAA4E;AAC5E,MAAM,CAAC,MAAM,uBAAuB,GAAG,0DAAwD,CAAC;AAEhG,MAAM,aAAa,GAAG,IAAI,GAAG,CAAC;IAC7B,MAAM;IACN,OAAO;IACP,cAAc;IACd,iBAAiB;IACjB,YAAY;IACZ,eAAe;IACf,MAAM;CACN,CAAC,CAAC;AAEH,iGAAiG;AACjG,MAAM,gBAAgB,GAAG,IAAI,GAAG,CAAC;IAChC,IAAI;IACJ,IAAI;IACJ,KAAK;IACL,KAAK;IACL,MAAM;IACN,IAAI;IACJ,MAAM;IACN,KAAK;IACL,MAAM;IACN,QAAQ;IACR,MAAM;IACN,MAAM;IACN,IAAI;IACJ,MAAM;IACN,MAAM;IACN,MAAM;IACN,MAAM;IACN,MAAM;IACN,KAAK;IACL,MAAM;IACN,MAAM;IACN,GAAG;IACH,MAAM;IACN,OAAO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,CAAC,CAAC;IACnC,OAAO,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,IAAI,KAAK,CAAC;AAAA,CACxC","sourcesContent":["/**\n * lunr: plan permission mode — read-only tool-gating heuristics + system-prompt addendum.\n *\n * Plan is a first-class permission mode (`PermissionMode = \"plan\"`). `gateToolCall`\n * in permissions.ts applies `planModeBlockReason` when the session is in plan:\n * `edit`/`write` and mutating `bash` are hard-blocked; read tools stay open.\n * InteractiveMode installs `PLAN_MODE_ADDENDUM` via the shared system-prompt\n * append slot (same slot auto mode uses).\n *\n * Bash heuristic (conservative, blocklist-based — NOT a security boundary):\n * - any `>`/`>>` redirect outside quotes blocks the whole command;\n * - the command is split on `;`, `|`, `&` separators (outside quotes) and every segment's\n * leading command must be read-only:\n * - known mutating commands (rm, mv, cp, mkdir, sed -i, tee, …) are blocked;\n * - `git` is limited to read-only subcommands (status/log/diff/show/… plus flag-only\n * branch/tag/remote); mutating subcommands (add/commit/push/checkout/…) are blocked;\n * - package managers are limited to read-only subcommands (install/add/remove/… blocked);\n * - arbitrary runners (sudo, xargs, npx, sh -c …) are blocked.\n * Unknown-but-not-listed commands are ALLOWED (blocklist, not allowlist) — the model is\n * additionally steered by the system-prompt addendum. False positives are expected; the\n * user can run the command themselves or exit plan mode with /plan off.\n */\n\n/** Appended to the system prompt while plan mode is active. */\nexport const PLAN_MODE_ADDENDUM =\n\t\"You are in plan mode. Investigate read-only, then present your plan by calling the present_plan tool with a concise summary — the user approves or declines it in a dialog. Do not make changes until the plan is approved. The user can also exit plan mode manually with /plan off.\";\n\n/** Error returned to the model when a tool call is blocked by plan mode. */\nexport const PLAN_MODE_BLOCK_MESSAGE = \"Plan mode is active — propose a plan; no file changes.\";\n\nconst BLOCKED_TOOLS = new Set([\n\t\"edit\",\n\t\"write\",\n\t\"behavior_add\",\n\t\"behavior_remove\",\n\t\"memory_add\",\n\t\"memory_remove\",\n\t\"cron\",\n]);\n\n/** Small allowlist of read-only commands permitted in plan mode. Everything else is rejected. */\nconst ALLOWED_COMMANDS = new Set([\n\t\"ls\",\n\t\"ll\",\n\t\"cat\",\n\t\"tac\",\n\t\"grep\",\n\t\"rg\",\n\t\"find\",\n\t\"pwd\",\n\t\"echo\",\n\t\"printf\",\n\t\"head\",\n\t\"tail\",\n\t\"wc\",\n\t\"less\",\n\t\"more\",\n\t\"sort\",\n\t\"uniq\",\n\t\"diff\",\n\t\"cmp\",\n\t\"comm\",\n\t\"test\",\n\t\"[\",\n\t\"true\",\n\t\"false\",\n\t\"which\",\n\t\"whereis\",\n\t\"stat\",\n\t\"file\",\n\t\"id\",\n\t\"whoami\",\n\t\"who\",\n\t\"date\",\n\t\"cal\",\n\t\"env\",\n\t\"printenv\",\n\t\"uname\",\n\t\"hostname\",\n\t\"uptime\",\n\t\"nproc\",\n\t\"tput\",\n\t\"git\",\n\t\"gh\",\n\t\"node\",\n\t\"npm\",\n\t\"pnpm\",\n\t\"yarn\",\n\t\"bun\",\n]);\n\nconst MUTATING_GIT_SUBCOMMANDS = new Set([\n\t\"add\",\n\t\"commit\",\n\t\"push\",\n\t\"pull\",\n\t\"merge\",\n\t\"rebase\",\n\t\"reset\",\n\t\"checkout\",\n\t\"switch\",\n\t\"restore\",\n\t\"rm\",\n\t\"mv\",\n\t\"stash\",\n\t\"cherry-pick\",\n\t\"revert\",\n\t\"clean\",\n\t\"fetch\",\n\t\"config\",\n\t\"apply\",\n\t\"am\",\n\t\"init\",\n\t\"clone\",\n\t\"submodule\",\n\t\"worktree\",\n\t\"gc\",\n\t\"prune\",\n\t\"update-index\",\n]);\n\n// git subcommands that are read-only only when they carry no positional args or\n// mutating flags (`git branch` lists, `git branch foo` / `git branch -d foo` mutate).\nconst CONDITIONAL_GIT_SUBCOMMANDS = new Set([\"branch\", \"tag\", \"remote\"]);\nconst CONDITIONAL_GIT_MUTATING_FLAGS = new Set([\"-d\", \"-D\", \"-m\", \"-M\", \"-c\", \"-C\"]);\n\nconst PACKAGE_MANAGER_MUTATIONS: Record<string, Set<string>> = {\n\tnpm: new Set([\n\t\t\"install\",\n\t\t\"add\",\n\t\t\"remove\",\n\t\t\"uninstall\",\n\t\t\"update\",\n\t\t\"upgrade\",\n\t\t\"publish\",\n\t\t\"link\",\n\t\t\"unlink\",\n\t\t\"ci\",\n\t\t\"init\",\n\t]),\n\tpnpm: new Set([\"install\", \"add\", \"remove\", \"uninstall\", \"update\", \"upgrade\", \"publish\", \"link\", \"unlink\", \"init\"]),\n\tyarn: new Set([\"install\", \"add\", \"remove\", \"uninstall\", \"upgrade\", \"publish\", \"link\", \"unlink\", \"init\"]),\n\tbun: new Set([\"install\", \"add\", \"remove\", \"uninstall\", \"update\", \"upgrade\", \"publish\", \"link\", \"unlink\", \"init\"]),\n};\n\n// Almost every subcommand mutates the system.\nconst ALWAYS_MUTATING_MANAGERS = new Set([\n\t\"apt\",\n\t\"apt-get\",\n\t\"brew\",\n\t\"dnf\",\n\t\"yum\",\n\t\"pacman\",\n\t\"choco\",\n\t\"winget\",\n\t\"scoop\",\n]);\n\n/** Flags that cause an interpreter to execute code and are never allowed in plan mode. */\nconst EXECUTING_NODE_FLAGS = new Set([\n\t\"-e\",\n\t\"--eval\",\n\t\"-p\",\n\t\"--print\",\n\t\"-r\",\n\t\"--require\",\n\t\"--import\",\n\t\"-i\",\n\t\"--interactive\",\n]);\nconst EXECUTING_PYTHON_FLAGS = new Set([\"-c\", \"-m\", \"-i\", \"--interactive\"]);\n\n/** Apply-mode rewrite only. Default / omitted `dry_run` is preview and stays allowed. */\nexport function isCodeRewriteMutating(input: unknown): boolean {\n\treturn (input as { dry_run?: unknown } | undefined)?.dry_run === false;\n}\n\n/**\n * Returns the block reason when plan mode should block this tool call, else undefined.\n */\nexport function planModeBlockReason(toolName: string, input: unknown): string | undefined {\n\tif (BLOCKED_TOOLS.has(toolName)) {\n\t\treturn PLAN_MODE_BLOCK_MESSAGE;\n\t}\n\tif (toolName === \"code_rewrite\" && isCodeRewriteMutating(input)) {\n\t\treturn PLAN_MODE_BLOCK_MESSAGE;\n\t}\n\tif (toolName === \"bash\") {\n\t\tconst command = readBashCommand(input);\n\t\tif (command && isMutatingBashCommand(command)) {\n\t\t\treturn `${PLAN_MODE_BLOCK_MESSAGE} Blocked command: ${command}`;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction readBashCommand(input: unknown): string {\n\tconst command = (input as { command?: unknown } | undefined)?.command;\n\treturn typeof command === \"string\" ? command : \"\";\n}\n\n/**\n * Plan-mode bash allowlist. A command is mutating unless every segment is a\n * known read-only command used safely (no redirects, no command substitution,\n * no process substitution, no executing-interpreter flags).\n */\nexport function isMutatingBashCommand(command: string): boolean {\n\tif (!command.trim()) return false;\n\n\t// Any output redirect outside quotes can write a file.\n\tif (hasUnquotedRedirect(command)) return true;\n\n\t// Command substitution / process substitution / grouped redirect syntaxes\n\t// bypass a simple command-name check.\n\tif (hasShellSubstitution(command)) return true;\n\n\t// Every segment separated by ; | & && || must individually be read-only.\n\tfor (const segment of splitShellSegments(command)) {\n\t\tif (isMutatingSegment(segment)) return true;\n\t}\n\treturn false;\n}\n\nfunction hasUnquotedRedirect(command: string): boolean {\n\tlet quote: \"'\" | '\"' | undefined;\n\tlet escaped = false;\n\tfor (let i = 0; i < command.length; i++) {\n\t\tconst ch = command[i];\n\t\tif (escaped) {\n\t\t\tescaped = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"\\\\\" && quote !== \"'\") {\n\t\t\tescaped = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (quote) {\n\t\t\tif (ch === quote) quote = undefined;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"'\" || ch === '\"') {\n\t\t\tquote = ch;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \">\") return true;\n\t}\n\treturn false;\n}\n\nfunction splitShellSegments(command: string): string[] {\n\tconst segments: string[] = [];\n\tlet quote: \"'\" | '\"' | undefined;\n\tlet escaped = false;\n\tlet start = 0;\n\tfor (let i = 0; i < command.length; i++) {\n\t\tconst ch = command[i];\n\t\tconst next = command[i + 1];\n\t\tif (escaped) {\n\t\t\tescaped = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"\\\\\" && quote !== \"'\") {\n\t\t\tescaped = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (quote) {\n\t\t\tif (ch === quote) quote = undefined;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"'\" || ch === '\"') {\n\t\t\tquote = ch;\n\t\t\tcontinue;\n\t\t}\n\t\t// Combined operators && and || split as one boundary.\n\t\tif ((ch === \"&\" && next === \"&\") || (ch === \"|\" && next === \"|\")) {\n\t\t\tsegments.push(command.slice(start, i));\n\t\t\ti++;\n\t\t\tstart = i + 1;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \";\" || ch === \"|\" || ch === \"&\" || ch === \"\\n\") {\n\t\t\tsegments.push(command.slice(start, i));\n\t\t\tstart = i + 1;\n\t\t}\n\t}\n\tsegments.push(command.slice(start));\n\treturn segments.map((s) => s.trim()).filter((s) => s.length > 0);\n}\n\n/** True when the command contains command/process substitution outside quotes. */\nfunction hasShellSubstitution(command: string): boolean {\n\tlet quote: \"'\" | '\"' | undefined;\n\tlet escaped = false;\n\tfor (let i = 0; i < command.length; i++) {\n\t\tconst ch = command[i];\n\t\tif (escaped) {\n\t\t\tescaped = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"\\\\\" && quote !== \"'\") {\n\t\t\tescaped = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (quote) {\n\t\t\tif (ch === quote) quote = undefined;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"'\" || ch === '\"') {\n\t\t\tquote = ch;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"`\") return true;\n\t\tif (ch === \"$\" && command[i + 1] === \"(\") return true;\n\t\tif (ch === \"<\" && command[i + 1] === \"(\") return true;\n\t\tif (ch === \">\" && command[i + 1] === \"(\") return true;\n\t\tif (ch === \"&\" && command[i + 1] === \">\") return true;\n\t}\n\treturn false;\n}\n\nfunction isMutatingSegment(segment: string): boolean {\n\tlet tokens = segment.split(/\\s+/).filter((t) => t.length > 0);\n\t// Skip leading env assignments (FOO=bar cmd …) and command wrappers we can't see through.\n\twhile (tokens.length > 0 && /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[0])) {\n\t\ttokens = tokens.slice(1);\n\t}\n\tif (tokens.length === 0) return false;\n\n\tconst command = basenameOf(tokens[0]).toLowerCase();\n\tconst args = tokens.slice(1);\n\n\tif (ALWAYS_MUTATING_MANAGERS.has(command)) return true;\n\n\tif (command === \"sed\") {\n\t\treturn args.some((a) => a === \"-i\" || a.startsWith(\"-i\") || a.startsWith(\"--in-place\") || /^-[^-]*i/.test(a));\n\t}\n\tif (command === \"find\") {\n\t\treturn args.some((a) => [\"-delete\", \"-exec\", \"-execdir\", \"-ok\", \"-okdir\"].includes(a));\n\t}\n\tif (command === \"git\") {\n\t\treturn isMutatingGit(args);\n\t}\n\tif (command === \"gh\") {\n\t\t// Allow read-only views; block everything that changes remote state.\n\t\tconst sub = `${args[0] ?? \"\"} ${args[1] ?? \"\"}`;\n\t\treturn ![\n\t\t\t\"pr view\",\n\t\t\t\"pr list\",\n\t\t\t\"pr status\",\n\t\t\t\"issue view\",\n\t\t\t\"issue list\",\n\t\t\t\"issue status\",\n\t\t\t\"repo view\",\n\t\t\t\"release view\",\n\t\t\t\"release list\",\n\t\t\t\"run list\",\n\t\t\t\"run view\",\n\t\t\t\"status\",\n\t\t].includes(sub.trim());\n\t}\n\tif (command === \"sh\" || command === \"bash\" || command === \"zsh\" || command === \"dash\") {\n\t\t// `sh -c '…'` runs arbitrary code; bare `sh script` also executes. Block -c; allow\n\t\t// nothing else is too restrictive for `bash --version`, so allow flag-only invocations.\n\t\treturn args.some((a) => a === \"-c\" || a === \"-s\") || args.some((a) => !a.startsWith(\"-\"));\n\t}\n\n\tconst pkgMutations = PACKAGE_MANAGER_MUTATIONS[command];\n\tif (pkgMutations) {\n\t\tconst subcommand = args.find((a) => !a.startsWith(\"-\"))?.toLowerCase();\n\t\treturn subcommand !== undefined && pkgMutations.has(subcommand);\n\t}\n\n\t// Node / Python interpreters: flag-only, no executing flags, no positional scripts.\n\tif (command === \"node\") {\n\t\treturn args.some((a) => !a.startsWith(\"-\")) || args.some((a) => EXECUTING_NODE_FLAGS.has(a));\n\t}\n\tif (command === \"python\" || command === \"python3\") {\n\t\treturn args.some((a) => !a.startsWith(\"-\")) || args.some((a) => EXECUTING_PYTHON_FLAGS.has(a));\n\t}\n\n\t// Final gate: the command must be in the read-only allowlist.\n\treturn !ALLOWED_COMMANDS.has(command);\n}\n\n/** Global git options that take no value. Unknown leading flags are treated as mutating. */\nconst GIT_GLOBAL_FLAGS = new Set([\n\t\"--no-pager\",\n\t\"--paginate\",\n\t\"-p\",\n\t\"--version\",\n\t\"--help\",\n\t\"-h\",\n\t\"--bare\",\n\t\"--no-replace-objects\",\n\t\"--no-optional-locks\",\n\t\"--literal-pathspecs\",\n\t\"--glob-pathspecs\",\n\t\"--noglob-pathspecs\",\n\t\"--icase-pathspecs\",\n]);\n\n/** Walk past known `git` globals. Returns the subcommand index, or -1 to block. */\nfunction gitSubcommandIndex(args: string[]): number {\n\tlet index = 0;\n\twhile (index < args.length) {\n\t\tconst token = args[index];\n\t\tif (!token.startsWith(\"-\")) return index;\n\t\tif (token === \"--\") return index + 1;\n\t\tif (GIT_GLOBAL_FLAGS.has(token)) {\n\t\t\tindex++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (token === \"-C\" || token === \"-c\" || token === \"--git-dir\" || token === \"--work-tree\" || token === \"--namespace\") {\n\t\t\tif (args[index + 1] === undefined) return -1;\n\t\t\tindex += 2;\n\t\t\tcontinue;\n\t\t}\n\t\tif (\n\t\t\ttoken.startsWith(\"--git-dir=\") ||\n\t\t\ttoken.startsWith(\"--work-tree=\") ||\n\t\t\ttoken.startsWith(\"--namespace=\") ||\n\t\t\ttoken.startsWith(\"--config-env=\")\n\t\t) {\n\t\t\tindex++;\n\t\t\tcontinue;\n\t\t}\n\t\treturn -1;\n\t}\n\treturn index;\n}\n\nfunction isMutatingGit(args: string[]): boolean {\n\tconst index = gitSubcommandIndex(args);\n\tif (index < 0) return true;\n\tconst subcommand = args[index]?.toLowerCase();\n\tif (!subcommand) return false;\n\n\tif (MUTATING_GIT_SUBCOMMANDS.has(subcommand)) return true;\n\tif (CONDITIONAL_GIT_SUBCOMMANDS.has(subcommand)) {\n\t\tconst rest = args.slice(index + 1);\n\t\treturn rest.some((a) => !a.startsWith(\"-\") || CONDITIONAL_GIT_MUTATING_FLAGS.has(a));\n\t}\n\treturn false;\n}\n\nfunction basenameOf(token: string): string {\n\tconst parts = token.split(/[\\\\/]/);\n\treturn parts[parts.length - 1] ?? token;\n}\n"]}
@@ -9,10 +9,10 @@ export declare function buildSwarmPrompt(task: string): string;
9
9
  * lunR: agent-swarm auto-activation gate helpers.
10
10
  *
11
11
  * When the model launches more than SWARM_APPROVAL_THRESHOLD parallel subagents
12
- * in a single `subagent` tool call, that counts as an auto-activated agent swarm
13
- * and requires user approval in every permission mode except `auto` (see
14
- * core/permissions.ts). An explicit /swarm turn is pre-approved because the user
15
- * already asked for the swarm.
12
+ * in one `subagent` `tasks`/`chain.parallel` call, or that many same-turn SINGLE
13
+ * `subagent` calls, that counts as an auto-activated agent swarm and requires
14
+ * user approval in every permission mode except `auto` (see core/permissions.ts).
15
+ * An explicit /swarm turn is pre-approved because the user already asked for the swarm.
16
16
  */
17
17
  /** Parallel-subagent count above which the swarm approval gate engages. */
18
18
  export declare const SWARM_APPROVAL_THRESHOLD = 2;
@@ -23,6 +23,19 @@ export declare const SWARM_APPROVAL_THRESHOLD = 2;
23
23
  * Dynamic `expand` fan-out has no static count and is not gated.
24
24
  */
25
25
  export declare function effectiveSwarmCount(args: Record<string, unknown>): number;
26
+ interface AssistantMessageLike {
27
+ content?: ReadonlyArray<{
28
+ type?: string;
29
+ name?: string;
30
+ arguments?: unknown;
31
+ }>;
32
+ }
33
+ /**
34
+ * Parallel subagent count for the swarm gate. Uses this call's `tasks` / chain
35
+ * `parallel` blocks, plus every other same-turn SINGLE `subagent` call so three
36
+ * sibling singles still trip the >2 approval gate.
37
+ */
38
+ export declare function effectiveSwarmCountForTurn(args: Record<string, unknown>, assistantMessage?: AssistantMessageLike): number;
26
39
  interface BranchEntryLike {
27
40
  type: string;
28
41
  message?: {
@@ -1 +1 @@
1
- {"version":3,"file":"swarm.d.ts","sourceRoot":"","sources":["../../src/core/swarm.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CASrD;AAED;;;;;;;;GAQG;AAEH,2EAA2E;AAC3E,eAAO,MAAM,wBAAwB,IAAI,CAAC;AAO1C;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAczE;AAED,UAAU,eAAe;IACxB,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,CAAC,EAAE;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,OAAO,CAAA;KAAE,CAAC;CAC/C;AAaD;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,SAAS,eAAe,EAAE,GAAG,OAAO,CAO/E","sourcesContent":["/**\n * lunR: reusable swarm prompt builder.\n *\n * Moved out of interactive-mode so the gateway can decompose tasks across\n * parallel subagents the same way the TUI does.\n */\n\nexport function buildSwarmPrompt(task: string): string {\n\treturn `[SWARM MODE] Task: ${task}\nAct as an orchestrator. 1) Decompose into 3-8 independent subtasks. 2) Launch them\nin ONE parallel subagent call (async:false), picking an agent + model tier per\nsubtask (prefer scout for exploration, worker for implementation, reviewer for\nverification). 3) Synthesize the results and report. Rules: max 8 concurrent\nsubagents; no nested fan-out; if a subtask fails, retry once with the heavy tier\nbefore giving up on it; keep your final report under 100 lines with per-subtask\nstatus.`;\n}\n\n/**\n * lunR: agent-swarm auto-activation gate helpers.\n *\n * When the model launches more than SWARM_APPROVAL_THRESHOLD parallel subagents\n * in a single `subagent` tool call, that counts as an auto-activated agent swarm\n * and requires user approval in every permission mode except `auto` (see\n * core/permissions.ts). An explicit /swarm turn is pre-approved because the user\n * already asked for the swarm.\n */\n\n/** Parallel-subagent count above which the swarm approval gate engages. */\nexport const SWARM_APPROVAL_THRESHOLD = 2;\n\nfunction countEntry(item: unknown): number {\n\tconst count = item && typeof item === \"object\" ? (item as { count?: unknown }).count : undefined;\n\treturn typeof count === \"number\" && Number.isInteger(count) && count >= 1 ? count : 1;\n}\n\n/**\n * Effective number of parallel subagents a `subagent` tool call will launch:\n * the `tasks` array (with `count` multipliers) plus any `chain` step `parallel`\n * fan-out blocks. Sequential chain steps and single-agent calls count as 0.\n * Dynamic `expand` fan-out has no static count and is not gated.\n */\nexport function effectiveSwarmCount(args: Record<string, unknown>): number {\n\tlet total = 0;\n\tif (Array.isArray(args.tasks)) {\n\t\tfor (const task of args.tasks) total += countEntry(task);\n\t}\n\tif (Array.isArray(args.chain)) {\n\t\tfor (const step of args.chain) {\n\t\t\tconst parallel = step && typeof step === \"object\" ? (step as { parallel?: unknown }).parallel : undefined;\n\t\t\tif (Array.isArray(parallel)) {\n\t\t\t\tfor (const child of parallel) total += countEntry(child);\n\t\t\t}\n\t\t}\n\t}\n\treturn total;\n}\n\ninterface BranchEntryLike {\n\ttype: string;\n\tmessage?: { role?: string; content?: unknown };\n}\n\nfunction messageText(content: unknown): string {\n\tif (typeof content === \"string\") return content;\n\tif (Array.isArray(content)) {\n\t\treturn content\n\t\t\t.filter((c) => c && typeof c === \"object\" && (c as { type?: unknown }).type === \"text\")\n\t\t\t.map((c) => String((c as { text?: unknown }).text ?? \"\"))\n\t\t\t.join(\"\");\n\t}\n\treturn \"\";\n}\n\n/**\n * True when the current turn started from an explicit /swarm prompt (the most\n * recent user message carries the literal `[SWARM MODE]` prefix). Both the TUI\n * and the gateway inject the same buildSwarmPrompt text, so this works on both\n * surfaces without extra state.\n */\nexport function isExplicitSwarmTurn(branch: readonly BranchEntryLike[]): boolean {\n\tfor (let i = branch.length - 1; i >= 0; i--) {\n\t\tconst entry = branch[i];\n\t\tif (entry.type !== \"message\" || entry.message?.role !== \"user\") continue;\n\t\treturn messageText(entry.message.content).startsWith(\"[SWARM MODE]\");\n\t}\n\treturn false;\n}\n"]}
1
+ {"version":3,"file":"swarm.d.ts","sourceRoot":"","sources":["../../src/core/swarm.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CASrD;AAED;;;;;;;;GAQG;AAEH,2EAA2E;AAC3E,eAAO,MAAM,wBAAwB,IAAI,CAAC;AAe1C;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAczE;AAQD,UAAU,oBAAoB;IAC7B,OAAO,CAAC,EAAE,aAAa,CAAC;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,SAAS,CAAC,EAAE,OAAO,CAAA;KAAE,CAAC,CAAC;CAC/E;AAED;;;;GAIG;AACH,wBAAgB,0BAA0B,CACzC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC7B,gBAAgB,CAAC,EAAE,oBAAoB,GACrC,MAAM,CAYR;AAED,UAAU,eAAe;IACxB,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,CAAC,EAAE;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,OAAO,CAAA;KAAE,CAAC;CAC/C;AAaD;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,SAAS,eAAe,EAAE,GAAG,OAAO,CAO/E","sourcesContent":["/**\n * lunR: reusable swarm prompt builder.\n *\n * Moved out of interactive-mode so the gateway can decompose tasks across\n * parallel subagents the same way the TUI does.\n */\n\nexport function buildSwarmPrompt(task: string): string {\n\treturn `[SWARM MODE] Task: ${task}\nAct as an orchestrator. 1) Decompose into 3-8 independent subtasks. 2) Launch them\nin ONE parallel subagent call (async:false), picking an agent + model tier per\nsubtask (prefer scout for exploration, worker for implementation, reviewer for\nverification). 3) Synthesize the results and report. Rules: max 8 concurrent\nsubagents; no nested fan-out; if a subtask fails, retry once with the heavy tier\nbefore giving up on it; keep your final report under 100 lines with per-subtask\nstatus.`;\n}\n\n/**\n * lunR: agent-swarm auto-activation gate helpers.\n *\n * When the model launches more than SWARM_APPROVAL_THRESHOLD parallel subagents\n * in one `subagent` `tasks`/`chain.parallel` call, or that many same-turn SINGLE\n * `subagent` calls, that counts as an auto-activated agent swarm and requires\n * user approval in every permission mode except `auto` (see core/permissions.ts).\n * An explicit /swarm turn is pre-approved because the user already asked for the swarm.\n */\n\n/** Parallel-subagent count above which the swarm approval gate engages. */\nexport const SWARM_APPROVAL_THRESHOLD = 2;\n\nfunction countEntry(item: unknown): number {\n\tconst count = item && typeof item === \"object\" ? (item as { count?: unknown }).count : undefined;\n\treturn typeof count === \"number\" && Number.isInteger(count) && count >= 1 ? count : 1;\n}\n\nfunction isManagementCall(args: Record<string, unknown>): boolean {\n\treturn typeof args.action === \"string\" && args.action.length > 0;\n}\n\nfunction isAsyncDetached(args: Record<string, unknown>): boolean {\n\treturn args.async === true && args.clarify !== true;\n}\n\n/**\n * Effective number of parallel subagents a `subagent` tool call will launch:\n * the `tasks` array (with `count` multipliers) plus any `chain` step `parallel`\n * fan-out blocks. Sequential chain steps and single-agent calls count as 0.\n * Dynamic `expand` fan-out has no static count and is not gated.\n */\nexport function effectiveSwarmCount(args: Record<string, unknown>): number {\n\tlet total = 0;\n\tif (Array.isArray(args.tasks)) {\n\t\tfor (const task of args.tasks) total += countEntry(task);\n\t}\n\tif (Array.isArray(args.chain)) {\n\t\tfor (const step of args.chain) {\n\t\t\tconst parallel = step && typeof step === \"object\" ? (step as { parallel?: unknown }).parallel : undefined;\n\t\t\tif (Array.isArray(parallel)) {\n\t\t\t\tfor (const child of parallel) total += countEntry(child);\n\t\t\t}\n\t\t}\n\t}\n\treturn total;\n}\n\nfunction siblingSingleCount(args: Record<string, unknown>): number {\n\tif (isManagementCall(args) || isAsyncDetached(args)) return 0;\n\tif (Array.isArray(args.tasks) || Array.isArray(args.chain)) return 0;\n\treturn typeof args.agent === \"string\" && args.agent.length > 0 ? 1 : 0;\n}\n\ninterface AssistantMessageLike {\n\tcontent?: ReadonlyArray<{ type?: string; name?: string; arguments?: unknown }>;\n}\n\n/**\n * Parallel subagent count for the swarm gate. Uses this call's `tasks` / chain\n * `parallel` blocks, plus every other same-turn SINGLE `subagent` call so three\n * sibling singles still trip the >2 approval gate.\n */\nexport function effectiveSwarmCountForTurn(\n\targs: Record<string, unknown>,\n\tassistantMessage?: AssistantMessageLike,\n): number {\n\tconst own = effectiveSwarmCount(args);\n\tconst siblingSingles = (assistantMessage?.content ?? []).reduce((total, block) => {\n\t\tif (block.type !== \"toolCall\" || block.name !== \"subagent\") return total;\n\t\tconst siblingArgs =\n\t\t\tblock.arguments && typeof block.arguments === \"object\" && !Array.isArray(block.arguments)\n\t\t\t\t? (block.arguments as Record<string, unknown>)\n\t\t\t\t: undefined;\n\t\tif (!siblingArgs) return total;\n\t\treturn total + siblingSingleCount(siblingArgs);\n\t}, 0);\n\treturn Math.max(own, siblingSingles);\n}\n\ninterface BranchEntryLike {\n\ttype: string;\n\tmessage?: { role?: string; content?: unknown };\n}\n\nfunction messageText(content: unknown): string {\n\tif (typeof content === \"string\") return content;\n\tif (Array.isArray(content)) {\n\t\treturn content\n\t\t\t.filter((c) => c && typeof c === \"object\" && (c as { type?: unknown }).type === \"text\")\n\t\t\t.map((c) => String((c as { text?: unknown }).text ?? \"\"))\n\t\t\t.join(\"\");\n\t}\n\treturn \"\";\n}\n\n/**\n * True when the current turn started from an explicit /swarm prompt (the most\n * recent user message carries the literal `[SWARM MODE]` prefix). Both the TUI\n * and the gateway inject the same buildSwarmPrompt text, so this works on both\n * surfaces without extra state.\n */\nexport function isExplicitSwarmTurn(branch: readonly BranchEntryLike[]): boolean {\n\tfor (let i = branch.length - 1; i >= 0; i--) {\n\t\tconst entry = branch[i];\n\t\tif (entry.type !== \"message\" || entry.message?.role !== \"user\") continue;\n\t\treturn messageText(entry.message.content).startsWith(\"[SWARM MODE]\");\n\t}\n\treturn false;\n}\n"]}
@@ -18,10 +18,10 @@ status.`;
18
18
  * lunR: agent-swarm auto-activation gate helpers.
19
19
  *
20
20
  * When the model launches more than SWARM_APPROVAL_THRESHOLD parallel subagents
21
- * in a single `subagent` tool call, that counts as an auto-activated agent swarm
22
- * and requires user approval in every permission mode except `auto` (see
23
- * core/permissions.ts). An explicit /swarm turn is pre-approved because the user
24
- * already asked for the swarm.
21
+ * in one `subagent` `tasks`/`chain.parallel` call, or that many same-turn SINGLE
22
+ * `subagent` calls, that counts as an auto-activated agent swarm and requires
23
+ * user approval in every permission mode except `auto` (see core/permissions.ts).
24
+ * An explicit /swarm turn is pre-approved because the user already asked for the swarm.
25
25
  */
26
26
  /** Parallel-subagent count above which the swarm approval gate engages. */
27
27
  export const SWARM_APPROVAL_THRESHOLD = 2;
@@ -29,6 +29,12 @@ function countEntry(item) {
29
29
  const count = item && typeof item === "object" ? item.count : undefined;
30
30
  return typeof count === "number" && Number.isInteger(count) && count >= 1 ? count : 1;
31
31
  }
32
+ function isManagementCall(args) {
33
+ return typeof args.action === "string" && args.action.length > 0;
34
+ }
35
+ function isAsyncDetached(args) {
36
+ return args.async === true && args.clarify !== true;
37
+ }
32
38
  /**
33
39
  * Effective number of parallel subagents a `subagent` tool call will launch:
34
40
  * the `tasks` array (with `count` multipliers) plus any `chain` step `parallel`
@@ -52,6 +58,32 @@ export function effectiveSwarmCount(args) {
52
58
  }
53
59
  return total;
54
60
  }
61
+ function siblingSingleCount(args) {
62
+ if (isManagementCall(args) || isAsyncDetached(args))
63
+ return 0;
64
+ if (Array.isArray(args.tasks) || Array.isArray(args.chain))
65
+ return 0;
66
+ return typeof args.agent === "string" && args.agent.length > 0 ? 1 : 0;
67
+ }
68
+ /**
69
+ * Parallel subagent count for the swarm gate. Uses this call's `tasks` / chain
70
+ * `parallel` blocks, plus every other same-turn SINGLE `subagent` call so three
71
+ * sibling singles still trip the >2 approval gate.
72
+ */
73
+ export function effectiveSwarmCountForTurn(args, assistantMessage) {
74
+ const own = effectiveSwarmCount(args);
75
+ const siblingSingles = (assistantMessage?.content ?? []).reduce((total, block) => {
76
+ if (block.type !== "toolCall" || block.name !== "subagent")
77
+ return total;
78
+ const siblingArgs = block.arguments && typeof block.arguments === "object" && !Array.isArray(block.arguments)
79
+ ? block.arguments
80
+ : undefined;
81
+ if (!siblingArgs)
82
+ return total;
83
+ return total + siblingSingleCount(siblingArgs);
84
+ }, 0);
85
+ return Math.max(own, siblingSingles);
86
+ }
55
87
  function messageText(content) {
56
88
  if (typeof content === "string")
57
89
  return content;
@@ -1 +1 @@
1
- {"version":3,"file":"swarm.js","sourceRoot":"","sources":["../../src/core/swarm.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,MAAM,UAAU,gBAAgB,CAAC,IAAY,EAAU;IACtD,OAAO,sBAAsB,IAAI;;;;;;;QAO1B,CAAC;AAAA,CACR;AAED;;;;;;;;GAQG;AAEH,2EAA2E;AAC3E,MAAM,CAAC,MAAM,wBAAwB,GAAG,CAAC,CAAC;AAE1C,SAAS,UAAU,CAAC,IAAa,EAAU;IAC1C,MAAM,KAAK,GAAG,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAE,IAA4B,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;IACjG,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,KAAK,IAAI,CA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,CAAC,CAAC;aACxD,IAAI,CAAC,EAAE,CAAC,CAAC;IACZ,CAAC;IACD,OAAO,EAAE,CAAC;AAAA,CACV;AAED;;;;;GAKG;AACH,MAAM,UAAU,mBAAmB,CAAC,MAAkC,EAAW;IAChF,KAAK,IAAI,CAAC,GAAG,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC;QAC7C,MAAM,KAAK,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;QACxB,IAAI,KAAK,CAAC,IAAI,KAAK,SAAS,IAAI,KAAK,CAAC,OAAO,EAAE,IAAI,KAAK,MAAM;YAAE,SAAS;QACzE,OAAO,WAAW,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,UAAU,CAAC,cAAc,CAAC,CAAC;IACtE,CAAC;IACD,OAAO,KAAK,CAAC;AAAA,CACb","sourcesContent":["/**\n * lunR: reusable swarm prompt builder.\n *\n * Moved out of interactive-mode so the gateway can decompose tasks across\n * parallel subagents the same way the TUI does.\n */\n\nexport function buildSwarmPrompt(task: string): string {\n\treturn `[SWARM MODE] Task: ${task}\nAct as an orchestrator. 1) Decompose into 3-8 independent subtasks. 2) Launch them\nin ONE parallel subagent call (async:false), picking an agent + model tier per\nsubtask (prefer scout for exploration, worker for implementation, reviewer for\nverification). 3) Synthesize the results and report. Rules: max 8 concurrent\nsubagents; no nested fan-out; if a subtask fails, retry once with the heavy tier\nbefore giving up on it; keep your final report under 100 lines with per-subtask\nstatus.`;\n}\n\n/**\n * lunR: agent-swarm auto-activation gate helpers.\n *\n * When the model launches more than SWARM_APPROVAL_THRESHOLD parallel subagents\n * in a single `subagent` tool call, that counts as an auto-activated agent swarm\n * and requires user approval in every permission mode except `auto` (see\n * core/permissions.ts). An explicit /swarm turn is pre-approved because the user\n * already asked for the swarm.\n */\n\n/** Parallel-subagent count above which the swarm approval gate engages. */\nexport const SWARM_APPROVAL_THRESHOLD = 2;\n\nfunction countEntry(item: unknown): number {\n\tconst count = item && typeof item === \"object\" ? (item as { count?: unknown }).count : undefined;\n\treturn typeof count === \"number\" && Number.isInteger(count) && count >= 1 ? count : 1;\n}\n\n/**\n * Effective number of parallel subagents a `subagent` tool call will launch:\n * the `tasks` array (with `count` multipliers) plus any `chain` step `parallel`\n * fan-out blocks. Sequential chain steps and single-agent calls count as 0.\n * Dynamic `expand` fan-out has no static count and is not gated.\n */\nexport function effectiveSwarmCount(args: Record<string, unknown>): number {\n\tlet total = 0;\n\tif (Array.isArray(args.tasks)) {\n\t\tfor (const task of args.tasks) total += countEntry(task);\n\t}\n\tif (Array.isArray(args.chain)) {\n\t\tfor (const step of args.chain) {\n\t\t\tconst parallel = step && typeof step === \"object\" ? (step as { parallel?: unknown }).parallel : undefined;\n\t\t\tif (Array.isArray(parallel)) {\n\t\t\t\tfor (const child of parallel) total += countEntry(child);\n\t\t\t}\n\t\t}\n\t}\n\treturn total;\n}\n\ninterface BranchEntryLike {\n\ttype: string;\n\tmessage?: { role?: string; content?: unknown };\n}\n\nfunction messageText(content: unknown): string {\n\tif (typeof content === \"string\") return content;\n\tif (Array.isArray(content)) {\n\t\treturn content\n\t\t\t.filter((c) => c && typeof c === \"object\" && (c as { type?: unknown }).type === \"text\")\n\t\t\t.map((c) => String((c as { text?: unknown }).text ?? \"\"))\n\t\t\t.join(\"\");\n\t}\n\treturn \"\";\n}\n\n/**\n * True when the current turn started from an explicit /swarm prompt (the most\n * recent user message carries the literal `[SWARM MODE]` prefix). Both the TUI\n * and the gateway inject the same buildSwarmPrompt text, so this works on both\n * surfaces without extra state.\n */\nexport function isExplicitSwarmTurn(branch: readonly BranchEntryLike[]): boolean {\n\tfor (let i = branch.length - 1; i >= 0; i--) {\n\t\tconst entry = branch[i];\n\t\tif (entry.type !== \"message\" || entry.message?.role !== \"user\") continue;\n\t\treturn messageText(entry.message.content).startsWith(\"[SWARM MODE]\");\n\t}\n\treturn false;\n}\n"]}
1
+ {"version":3,"file":"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AAS;QACzE,OAAO,WAAW,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,UAAU,CAAC,cAAc,CAAC,CAAC;IACtE,CAAC;IACD,OAAO,KAAK,CAAC;AAAA,CACb","sourcesContent":["/**\n * lunR: reusable swarm prompt builder.\n *\n * Moved out of interactive-mode so the gateway can decompose tasks across\n * parallel subagents the same way the TUI does.\n */\n\nexport function buildSwarmPrompt(task: string): string {\n\treturn `[SWARM MODE] Task: ${task}\nAct as an orchestrator. 1) Decompose into 3-8 independent subtasks. 2) Launch them\nin ONE parallel subagent call (async:false), picking an agent + model tier per\nsubtask (prefer scout for exploration, worker for implementation, reviewer for\nverification). 3) Synthesize the results and report. Rules: max 8 concurrent\nsubagents; no nested fan-out; if a subtask fails, retry once with the heavy tier\nbefore giving up on it; keep your final report under 100 lines with per-subtask\nstatus.`;\n}\n\n/**\n * lunR: agent-swarm auto-activation gate helpers.\n *\n * When the model launches more than SWARM_APPROVAL_THRESHOLD parallel subagents\n * in one `subagent` `tasks`/`chain.parallel` call, or that many same-turn SINGLE\n * `subagent` calls, that counts as an auto-activated agent swarm and requires\n * user approval in every permission mode except `auto` (see core/permissions.ts).\n * An explicit /swarm turn is pre-approved because the user already asked for the swarm.\n */\n\n/** Parallel-subagent count above which the swarm approval gate engages. */\nexport const SWARM_APPROVAL_THRESHOLD = 2;\n\nfunction countEntry(item: unknown): number {\n\tconst count = item && typeof item === \"object\" ? (item as { count?: unknown }).count : undefined;\n\treturn typeof count === \"number\" && Number.isInteger(count) && count >= 1 ? count : 1;\n}\n\nfunction isManagementCall(args: Record<string, unknown>): boolean {\n\treturn typeof args.action === \"string\" && args.action.length > 0;\n}\n\nfunction isAsyncDetached(args: Record<string, unknown>): boolean {\n\treturn args.async === true && args.clarify !== true;\n}\n\n/**\n * Effective number of parallel subagents a `subagent` tool call will launch:\n * the `tasks` array (with `count` multipliers) plus any `chain` step `parallel`\n * fan-out blocks. Sequential chain steps and single-agent calls count as 0.\n * Dynamic `expand` fan-out has no static count and is not gated.\n */\nexport function effectiveSwarmCount(args: Record<string, unknown>): number {\n\tlet total = 0;\n\tif (Array.isArray(args.tasks)) {\n\t\tfor (const task of args.tasks) total += countEntry(task);\n\t}\n\tif (Array.isArray(args.chain)) {\n\t\tfor (const step of args.chain) {\n\t\t\tconst parallel = step && typeof step === \"object\" ? (step as { parallel?: unknown }).parallel : undefined;\n\t\t\tif (Array.isArray(parallel)) {\n\t\t\t\tfor (const child of parallel) total += countEntry(child);\n\t\t\t}\n\t\t}\n\t}\n\treturn total;\n}\n\nfunction siblingSingleCount(args: Record<string, unknown>): number {\n\tif (isManagementCall(args) || isAsyncDetached(args)) return 0;\n\tif (Array.isArray(args.tasks) || Array.isArray(args.chain)) return 0;\n\treturn typeof args.agent === \"string\" && args.agent.length > 0 ? 1 : 0;\n}\n\ninterface AssistantMessageLike {\n\tcontent?: ReadonlyArray<{ type?: string; name?: string; arguments?: unknown }>;\n}\n\n/**\n * Parallel subagent count for the swarm gate. Uses this call's `tasks` / chain\n * `parallel` blocks, plus every other same-turn SINGLE `subagent` call so three\n * sibling singles still trip the >2 approval gate.\n */\nexport function effectiveSwarmCountForTurn(\n\targs: Record<string, unknown>,\n\tassistantMessage?: AssistantMessageLike,\n): number {\n\tconst own = effectiveSwarmCount(args);\n\tconst siblingSingles = (assistantMessage?.content ?? []).reduce((total, block) => {\n\t\tif (block.type !== \"toolCall\" || block.name !== \"subagent\") return total;\n\t\tconst siblingArgs =\n\t\t\tblock.arguments && typeof block.arguments === \"object\" && !Array.isArray(block.arguments)\n\t\t\t\t? (block.arguments as Record<string, unknown>)\n\t\t\t\t: undefined;\n\t\tif (!siblingArgs) return total;\n\t\treturn total + siblingSingleCount(siblingArgs);\n\t}, 0);\n\treturn Math.max(own, siblingSingles);\n}\n\ninterface BranchEntryLike {\n\ttype: string;\n\tmessage?: { role?: string; content?: unknown };\n}\n\nfunction messageText(content: unknown): string {\n\tif (typeof content === \"string\") return content;\n\tif (Array.isArray(content)) {\n\t\treturn content\n\t\t\t.filter((c) => c && typeof c === \"object\" && (c as { type?: unknown }).type === \"text\")\n\t\t\t.map((c) => String((c as { text?: unknown }).text ?? \"\"))\n\t\t\t.join(\"\");\n\t}\n\treturn \"\";\n}\n\n/**\n * True when the current turn started from an explicit /swarm prompt (the most\n * recent user message carries the literal `[SWARM MODE]` prefix). Both the TUI\n * and the gateway inject the same buildSwarmPrompt text, so this works on both\n * surfaces without extra state.\n */\nexport function isExplicitSwarmTurn(branch: readonly BranchEntryLike[]): boolean {\n\tfor (let i = branch.length - 1; i >= 0; i--) {\n\t\tconst entry = branch[i];\n\t\tif (entry.type !== \"message\" || entry.message?.role !== \"user\") continue;\n\t\treturn messageText(entry.message.content).startsWith(\"[SWARM MODE]\");\n\t}\n\treturn false;\n}\n"]}
@@ -131,7 +131,7 @@ export declare class AgentBridge {
131
131
  /** Test/debug hook: how many redo targets are saved for a key. */
132
132
  getRedoStackLength(key: string): number;
133
133
  /** Drop the cached session (disposing it) and forget the store entry (/new, /reset). */
134
- reset(key: string): void;
134
+ reset(key: string): Promise<void>;
135
135
  getStatus(key: string): BridgeSessionStatus;
136
136
  private runPrompt;
137
137
  private drainQueue;
@@ -1 +1 @@
1
- {"version":3,"file":"agent-bridge.d.ts","sourceRoot":"","sources":["../../src/gateway/agent-bridge.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAGH,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACjF,OAAO,KAAK,EAAoB,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAC5E,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,8BAA8B,CAAC;AAC1D,OAAO,KAAK,EAAgB,iBAAiB,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AAC9F,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAEpE,OAAO,KAAK,EAAE,YAA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AO,CAAC,IAAI,CAAC,CAerC;IAED,kEAAkE;IAClE,kBAAkB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAEtC;IAED,wFAAwF;IACxF,KAAK,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CASvB;IAED,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,mBAAmB,CAO1C;YAGa,SAAS;YAiET,UAAU;YA2BV,WAAW;YAsBX,WAAW;IAkBzB,OAAO,CAAC,gBAAgB;IAyBxB,OAAO,CAAC,mBAAmB;IAI3B,OAAO,CAAC,mBAAmB;CAK3B","sourcesContent":["/**\n * lunR: gateway agent bridge.\n *\n * Owns the sessionKey → AgentSession mapping: an LRU cache (cap 20) over\n * live sessions, backed by store.ts so conversations survive daemon restarts\n * (a stored sessionFile is reopened via SessionManager.open, which\n * createAgentSession restores history from; a missing file starts fresh with\n * a one-line warning).\n *\n * New sessions replicate main.ts's headless wiring: SettingsManager +\n * DefaultResourceLoader with the builtin extension factories + the three\n * lunr bridges, then bindExtensions({ mode: \"print\" }) like print-mode.\n *\n * Busy guard: one turn per session at a time. Messages arriving mid-turn are\n * queued (cap 5, oldest dropped with a notice) and drained FIFO as a single\n * concatenated follow-up turn once the running turn ends; runTurn returns\n * the QUEUED sentinel for those, and the follow-up turn's result is\n * delivered via callbacks.onFollowUpResult.\n *\n * Streaming: subscribes to session events and converts cumulative\n * message_update snapshots into deltas for callbacks.onDelta.\n *\n * isGatewayTurn()/runDepth: incremented around every prompt() so Phase 4\n * (cron↔gateway delivery) and extensions can detect they run inside a\n * gateway turn and refuse self-scheduling. Every prompt() also runs inside\n * runWithOrigin(source, ...) (core/cron/origin-context) so tools executing\n * during the turn — e.g. the `cron` tool's create action — can read the chat\n * the message came from and stamp it as the job's delivery origin.\n */\n\nimport { existsSync } from \"node:fs\";\nimport type { AgentMessage, ThinkingLevel } from \"@ashx-j/lunr-agent\";\nimport type { AssistantMessage, ImageContent } from \"@ashx-j/lunr-ai\";\nimport type { Model } from \"@ashx-j/lunr-ai/compat\";\nimport type { AgentSession, AgentSessionEvent, SessionStats } from \"../core/agent-session.ts\";\nimport type { CompactionResult } from \"../core/compaction/index.ts\";\nimport { runWithOrigin } from \"../core/cron/origin-context.ts\";\nimport type { ContextUsage, ToolDefinition } from \"../core/extensions/types.ts\";\nimport type { ModelRuntime } from \"../core/model-runtime.ts\";\nimport { createPermissionContext, deletePermissionContext } from \"../core/permissions.ts\";\nimport type { ReadonlySessionManager, SessionManager, SessionMessageEntry } from \"../core/session-manager.ts\";\nimport { processImage } from \"../utils/image-process.ts\";\nimport { getSession, putSession, removeSession, touchSession } from \"./store.ts\";\nimport type { InboundAttachment, MessageEvent, SessionSource } from \"./types.ts\";\n\nfunction isUserMessageEntry(entry: { type: string }): entry is SessionMessageEntry {\n\treturn entry.type === \"message\";\n}\n\n/** runTurn resolves with this when the message was queued behind a running turn. */\nexport const QUEUED = \"__lunr_gateway_queued__\";\n\nconst CACHE_CAP = 20;\nconst QUEUE_CAP = 5;\n\nlet runDepth = 0;\n\n/** True while a gateway turn's prompt() is in flight. */\nexport function isGatewayTurn(): boolean {\n\treturn runDepth > 0;\n}\n\nexport function gatewayRunDepth(): number {\n\treturn runDepth;\n}\n\nexport interface TurnCallbacks {\n\t/** Assistant text delta during streaming (converted from cumulative snapshots). */\n\tonDelta?: (delta: string) => void;\n\t/** Final text of a drained-queue follow-up turn (deliver it like a normal reply). */\n\tonFollowUpResult?: (text: string) => void;\n\t/** Error from a drained-queue follow-up turn. */\n\tonError?: (message: string) => void;\n}\n\nexport interface BridgeSessionStatus {\n\tbusy: boolean;\n\tqueueDepth: number;\n\tcreatedAt?: string;\n}\n\n/**\n * Structural session shape the bridge needs — satisfied by AgentSession,\n * fakeable in tests. Expanded to support gateway slash commands.\n */\nexport interface BridgeSession {\n\tprompt(text: string, options?: { source?: \"extension\"; images?: ImageContent[] }): Promise<void>;\n\tabort(): Promise<void> | void;\n\tsubscribe(listener: (event: AgentSessionEvent) => void): () => void;\n\treadonly state: { messages: AgentMessage[] };\n\tdispose?(): void;\n\treadonly isStreaming: boolean;\n\treadonly isCompacting?: boolean;\n\treadonly model?: Model<any>;\n\treadonly modelRuntime: ModelRuntime;\n\treadonly thinkingLevel: ThinkingLevel;\n\treadonly messages: AgentMessage[];\n\treadonly systemPrompt: string;\n\treadonly sessionManager?: ReadonlySessionManager;\n\n\tgetActiveToolNames(): string[];\n\tgetToolDefinition(name: string): ToolDefinition | undefined;\n\tgetAvailableThinkingLevels(): ThinkingLevel[];\n\tsupportsThinking(): boolean;\n\tsetThinkingLevel(level: ThinkingLevel): void;\n\tsetModel(model: Model<any>): Promise<void>;\n\tcompact(customInstructions?: string): Promise<CompactionResult>;\n\tnavigateTree(\n\t\ttargetId: string,\n\t\toptions?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },\n\t): Promise<{ editorText?: string; editorImages?: ImageContent[]; cancelled: boolean; aborted?: boolean }>;\n\tgetContextUsage(): ContextUsage | undefined;\n\tgetSessionStats(): SessionStats;\n\tsetSessionName(name: string): void;\n}\n\nexport type SessionFactory = (key: string, reopen: { sessionFile: string } | undefined) => Promise<BridgeSession>;\n\ninterface CacheEntry {\n\tsession: BridgeSession;\n\tbusy: boolean;\n\tqueue: MessageEvent[];\n\tdropped: number;\n\tunsubscribe?: () => void;\n}\n\n/**\n * Default factory: headless session with the builtin extensions, mirroring\n * main.ts (minus TUI) + print-mode's bindExtensions.\n *\n * The heavy wiring is imported LAZILY: a static import of\n * builtin-extensions/index.ts here would pull the whole extension + TUI\n * graph into every consumer of this module (router tests, `gateway status`)\n * and trip the known ashxj-tui ↔ package-barrel cycle (see AGENTS.md\n * \"Barrel-import guard\"). Loading it on first session creation keeps module\n * import light and matches how main.ts loads it in the real CLI.\n */\nasync function defaultSessionFactory(key: string, reopen: { sessionFile: string } | undefined): Promise<AgentSession> {\n\tconst [\n\t\t{ loadAllBuiltinExtensions },\n\t\t{ getAgentDir },\n\t\t{ registerCustomizeBridge },\n\t\t{ reconcileBehaviorPreset, registerBehaviorPresetBridge },\n\t\t{ registerMemoryCapBridge },\n\t\t{ getModelTiersBridge, registerModelTierBridge },\n\t\t{ createAgentSessionFromServices, createAgentSessionServices },\n\t\t{ SessionManager },\n\t\t{ SettingsManager },\n\t] = await Promise.all([\n\t\timport(\"../builtin-extensions/index.ts\"),\n\t\timport(\"../config.ts\"),\n\t\timport(\"../core/customize.ts\"),\n\t\timport(\"../core/behavior-preset.ts\"),\n\t\timport(\"../core/memory-cap.ts\"),\n\t\timport(\"../core/model-tiers.ts\"),\n\t\timport(\"../core/agent-session-services.ts\"),\n\t\timport(\"../core/session-manager.ts\"),\n\t\timport(\"../core/settings-manager.ts\"),\n\t]);\n\tconst cwd = process.cwd();\n\tconst agentDir = getAgentDir();\n\tconst settingsManager = SettingsManager.create(cwd, agentDir, { projectTrusted: false });\n\t// Same bridges main.ts registers before extensions load.\n\tregisterModelTierBridge(settingsManager);\n\tregisterMemoryCapBridge(settingsManager);\n\tregisterBehaviorPresetBridge(settingsManager);\n\treconcileBehaviorPreset(settingsManager, agentDir);\n\tregisterCustomizeBridge(settingsManager);\n\n\tlet sessionManager: SessionManager;\n\tif (reopen && existsSync(reopen.sessionFile)) {\n\t\tsessionManager = SessionManager.open(reopen.sessionFile);\n\t} else {\n\t\tif (reopen) {\n\t\t\tconsole.warn(`[gateway] stored session file missing for ${key}; starting a fresh session`);\n\t\t}\n\t\tsessionManager = SessionManager.create(cwd);\n\t}\n\n\t// Services-first (mirrors main.ts): extension-registered providers (e.g.\n\t// ollama-cloud) must land in the shared ModelRuntime BEFORE session\n\t// creation — otherwise findInitialModel can't resolve the user's default\n\t// model and silently falls back to an arbitrary catalog provider (this\n\t// exact bug sent gateway turns to openrouter with no key → 401).\n\tconst services = await createAgentSessionServices({\n\t\tcwd,\n\t\tagentDir,\n\t\tsettingsManager,\n\t\tresourceLoaderOptions: { extensionFactories: await loadAllBuiltinExtensions() },\n\t});\n\tconst { session } = await createAgentSessionFromServices({ services, sessionManager });\n\tgetModelTiersBridge()?.setParentThinkingProvider(() => session.thinkingLevel);\n\tawait session.bindExtensions({\n\t\tmode: \"print\",\n\t\tonError: (err) => console.error(`[gateway] extension error (${err.extensionPath}): ${err.error}`),\n\t});\n\treturn session;\n}\n\n/** Final assistant text, print-mode style; throws on error/aborted stop. */\nfunction extractFinalText(session: BridgeSession): string {\n\tconst messages = session.state.messages;\n\tconst last = messages[messages.length - 1];\n\tif (last?.role !== \"assistant\") return \"\";\n\tconst assistant = last as AssistantMessage;\n\tif (assistant.stopReason === \"error\" || assistant.stopReason === \"aborted\") {\n\t\tthrow new Error(assistant.errorMessage || `Request ${assistant.stopReason}`);\n\t}\n\tlet text = \"\";\n\tfor (const content of assistant.content) {\n\t\tif (content.type === \"text\") text += content.text;\n\t}\n\treturn text;\n}\n\nexport class AgentBridge {\n\tprivate cap: number;\n\tprivate readonly sessionFactory: SessionFactory;\n\tprivate readonly cache = new Map<string, CacheEntry>();\n\tprivate readonly redoStack = new Map<string, string[]>();\n\tprivate readonly creating = new Map<string, Promise<CacheEntry>>();\n\n\tconstructor(options: { cacheCap?: number; sessionFactory?: SessionFactory } = {}) {\n\t\tthis.cap = options.cacheCap ?? CACHE_CAP;\n\t\tthis.sessionFactory = options.sessionFactory ?? defaultSessionFactory;\n\t}\n\n\t/**\n\t * Run one conversational turn. Resolves with the final assistant text, or\n\t * the QUEUED sentinel when the session was busy (router must not reply).\n\t */\n\tasync runTurn(key: string, event: MessageEvent, callbacks: TurnCallbacks = {}): Promise<string> {\n\t\tconst entry = await this.getOrCreate(key);\n\t\tif (entry.busy) {\n\t\t\tif (entry.queue.length >= QUEUE_CAP) {\n\t\t\t\tentry.queue.shift();\n\t\t\t\tentry.dropped++;\n\t\t\t}\n\t\t\tentry.queue.push(event);\n\t\t\treturn QUEUED;\n\t\t}\n\t\tentry.busy = true;\n\t\tlet result: string;\n\t\ttry {\n\t\t\tresult = await this.runPrompt(entry, event.text, callbacks, event.source, event.attachments);\n\t\t} catch (err) {\n\t\t\tentry.busy = false;\n\t\t\tthrow err;\n\t\t}\n\t\ttouchSession(key);\n\t\t// Drain queued messages as one follow-up turn, fire-and-forget. The busy\n\t\t// flag stays set until the queue is empty so turn ordering is strict;\n\t\t// the follow-up result arrives via callbacks.onFollowUpResult.\n\t\tvoid this.drainQueue(entry, callbacks).finally(() => {\n\t\t\tentry.busy = false;\n\t\t});\n\t\treturn result;\n\t}\n\n\tasync abort(key: string): Promise<void> {\n\t\tawait this.cache.get(key)?.session.abort();\n\t}\n\n\t/** Return the live session for a key, or null when none exists yet. */\n\tasync getSession(key: string): Promise<BridgeSession | null> {\n\t\tconst cached = this.cache.get(key);\n\t\tif (cached) return cached.session;\n\t\tif (!getSession(key)) return null;\n\t\treturn (await this.getOrCreate(key)).session;\n\t}\n\n\t/** Switch the chat to a different persisted session file. */\n\tasync switchSession(key: string, sessionFile: string): Promise<void> {\n\t\tconst entry = this.cache.get(key);\n\t\tif (entry?.busy) {\n\t\t\tthrow new Error(\"Session is busy — /stop first or wait\");\n\t\t}\n\t\tif (entry) {\n\t\t\tconst oldSessionId = entry.session.sessionManager?.getSessionId();\n\t\t\tentry.unsubscribe?.();\n\t\t\tthis.cache.delete(key);\n\t\t\tentry.session.dispose?.();\n\t\t\tif (oldSessionId) deletePermissionContext(oldSessionId);\n\t\t}\n\t\tremoveSession(key);\n\t\tthis.redoStack.delete(key);\n\n\t\tconst session = await this.sessionFactory(key, { sessionFile });\n\t\tconst newFile = session.sessionManager?.getSessionFile();\n\t\tconst newSessionId = session.sessionManager?.getSessionId();\n\t\tif (newFile) {\n\t\t\tputSession(key, { sessionId: newSessionId ?? key, sessionFile: newFile });\n\t\t}\n\t\tif (newSessionId) {\n\t\t\tcreatePermissionContext(newSessionId);\n\t\t}\n\t\tconst newEntry: CacheEntry = { session, busy: false, queue: [], dropped: 0 };\n\t\tthis.cache.set(key, newEntry);\n\t\tthis._enforceCacheCap(key);\n\t\tnewEntry.unsubscribe = this._subscribeToSession(key, newEntry);\n\t}\n\n\t/** Undo the last user turn and push the previous leaf onto the redo stack. */\n\tasync undo(key: string): Promise<{ userText: string }> {\n\t\tconst session = await this.getSession(key);\n\t\tif (!session) throw new Error(\"No session\");\n\t\tif (session.isStreaming) throw new Error(\"Wait for the current response to finish\");\n\t\tconst branch = session.sessionManager?.getBranch() ?? [];\n\t\tlet lastUserIndex = -1;\n\t\tfor (let i = branch.length - 1; i >= 0; i--) {\n\t\t\tconst entry = branch[i];\n\t\t\tif (isUserMessageEntry(entry) && entry.message.role === \"user\") {\n\t\t\t\tlastUserIndex = i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (lastUserIndex === -1) throw new Error(\"Nothing to undo\");\n\t\tconst lastUser = branch[lastUserIndex];\n\t\tif (!isUserMessageEntry(lastUser)) throw new Error(\"Nothing to undo\");\n\n\t\tconst leafId = session.sessionManager?.getLeafId() ?? null;\n\t\tlet targetId: string;\n\t\tif (lastUser.id === leafId) {\n\t\t\tif (!lastUser.parentId) throw new Error(\"Nothing to undo\");\n\t\t\ttargetId = lastUser.parentId;\n\t\t} else {\n\t\t\ttargetId = lastUser.id;\n\t\t}\n\n\t\tconst result = await session.navigateTree(targetId, {});\n\t\tif (result.cancelled) throw new Error(\"Navigation cancelled\");\n\n\t\tif (leafId) {\n\t\t\tconst stack = this.redoStack.get(key) ?? [];\n\t\t\tstack.push(leafId);\n\t\t\tthis.redoStack.set(key, stack);\n\t\t}\n\n\t\treturn { userText: extractUserText(lastUser.message) };\n\t}\n\n\t/** Redo to the leaf saved by the most recent undo. */\n\tasync redo(key: string): Promise<void> {\n\t\tconst session = await this.getSession(key);\n\t\tif (!session) throw new Error(\"No session\");\n\t\tif (session.isStreaming) throw new Error(\"Wait for the current response to finish\");\n\t\tconst stack = this.redoStack.get(key) ?? [];\n\t\tconst targetId = stack.pop();\n\t\tif (!targetId) throw new Error(\"Nothing to redo\");\n\t\tthis.redoStack.set(key, stack);\n\n\t\tconst result = await session.navigateTree(targetId, {});\n\t\tif (result.cancelled) {\n\t\t\tstack.push(targetId);\n\t\t\tthis.redoStack.set(key, stack);\n\t\t\tthrow new Error(\"Navigation cancelled\");\n\t\t}\n\t}\n\n\t/** Test/debug hook: how many redo targets are saved for a key. */\n\tgetRedoStackLength(key: string): number {\n\t\treturn this.redoStack.get(key)?.length ?? 0;\n\t}\n\n\t/** Drop the cached session (disposing it) and forget the store entry (/new, /reset). */\n\treset(key: string): void {\n\t\tconst entry = this.cache.get(key);\n\t\tif (entry) {\n\t\t\tentry.unsubscribe?.();\n\t\t\tthis.cache.delete(key);\n\t\t\tentry.session.dispose?.();\n\t\t}\n\t\tremoveSession(key);\n\t\tthis.redoStack.delete(key);\n\t}\n\n\tgetStatus(key: string): BridgeSessionStatus {\n\t\tconst entry = this.cache.get(key);\n\t\treturn {\n\t\t\tbusy: entry?.busy ?? false,\n\t\t\tqueueDepth: entry?.queue.length ?? 0,\n\t\t\tcreatedAt: getSession(key)?.createdAt,\n\t\t};\n\t}\n\n\t/** One prompt → final text. Increments runDepth; streams deltas when asked. */\n\tprivate async runPrompt(\n\t\tentry: CacheEntry,\n\t\ttext: string,\n\t\tcallbacks: TurnCallbacks,\n\t\tsource: SessionSource,\n\t\tattachments?: InboundAttachment[],\n\t): Promise<string> {\n\t\tconst { session } = entry;\n\t\tlet unsubscribe: (() => void) | undefined;\n\t\tif (callbacks.onDelta) {\n\t\t\tconst onDelta = callbacks.onDelta;\n\t\t\tlet streamedLen = 0;\n\t\t\tunsubscribe = session.subscribe((event: AgentSessionEvent) => {\n\t\t\t\tif (event.type !== \"message_update\") return;\n\t\t\t\tconst assistantEvent = event.assistantMessageEvent;\n\t\t\t\tif (assistantEvent.type !== \"text_delta\") return;\n\t\t\t\tlet full = \"\";\n\t\t\t\tfor (const content of assistantEvent.partial.content) {\n\t\t\t\t\tif (content.type === \"text\") full += content.text;\n\t\t\t\t}\n\t\t\t\tif (full.length < streamedLen) streamedLen = 0; // new assistant message (tool-call boundary)\n\t\t\t\tif (full.length > streamedLen) {\n\t\t\t\t\tonDelta(full.slice(streamedLen));\n\t\t\t\t\tstreamedLen = full.length;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\trunDepth++;\n\t\ttry {\n\t\t\t// lunr: convert inbound image attachments to ImageContent for the model.\n\t\t\t// processImage normalizes + resizes under the inline 4.5MB base64 limit;\n\t\t\t// failures become bracketed text notes so the model explains the gap.\n\t\t\tconst images: ImageContent[] = [];\n\t\t\tconst notes: string[] = [];\n\t\t\tfor (const attachment of attachments ?? []) {\n\t\t\t\tconst bytes = Buffer.from(attachment.data, \"base64\");\n\t\t\t\tconst processed = await processImage(new Uint8Array(bytes), attachment.mimeType);\n\t\t\t\tif (processed.ok) {\n\t\t\t\t\timages.push({ type: \"image\", data: processed.data, mimeType: processed.mimeType });\n\t\t\t\t\tfor (const hint of processed.hints) notes.push(hint);\n\t\t\t\t} else {\n\t\t\t\t\tnotes.push(processed.message);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst promptText = notes.length > 0 ? `${text}\\n\\n${notes.join(\" \")}` : text;\n\t\t\t// AsyncLocalStorage origin: tools executing during this turn (e.g. the\n\t\t\t// `cron` tool) can read the chat the message came from. Propagates\n\t\t\t// through the awaited prompt() call tree.\n\t\t\tawait runWithOrigin(\n\t\t\t\t{\n\t\t\t\t\tplatform: source.platform,\n\t\t\t\t\tchatId: source.chatId,\n\t\t\t\t\tthreadId: source.threadId,\n\t\t\t\t\tchatType: source.chatType,\n\t\t\t\t},\n\t\t\t\t() => session.prompt(promptText, { source: \"extension\", ...(images.length ? { images } : {}) }),\n\t\t\t);\n\t\t} finally {\n\t\t\trunDepth--;\n\t\t\tunsubscribe?.();\n\t\t}\n\t\treturn extractFinalText(session);\n\t}\n\n\t/** Drain the queue FIFO: all queued messages become one concatenated turn. */\n\tprivate async drainQueue(entry: CacheEntry, callbacks: TurnCallbacks): Promise<void> {\n\t\twhile (entry.queue.length > 0) {\n\t\t\tconst items = entry.queue.splice(0);\n\t\t\tconst parts = items.map((item) => item.text);\n\t\t\tconst attachments = items.flatMap((item) => item.attachments ?? []);\n\t\t\tif (entry.dropped > 0) {\n\t\t\t\tparts.unshift(`[gateway: ${entry.dropped} earlier message(s) were dropped — the queue was full]`);\n\t\t\t\tentry.dropped = 0;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\t// Follow-up turns are final-only: no streaming callbacks. The origin\n\t\t\t\t// is the chat of the latest queued message.\n\t\t\t\tconst text = await this.runPrompt(\n\t\t\t\t\tentry,\n\t\t\t\t\tparts.join(\"\\n\\n\"),\n\t\t\t\t\t{},\n\t\t\t\t\titems[items.length - 1].source,\n\t\t\t\t\tattachments,\n\t\t\t\t);\n\t\t\t\tcallbacks.onFollowUpResult?.(text);\n\t\t\t} catch (err) {\n\t\t\t\tcallbacks.onError?.(err instanceof Error ? err.message : String(err));\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async getOrCreate(key: string): Promise<CacheEntry> {\n\t\tconst cached = this.cache.get(key);\n\t\tif (cached) {\n\t\t\t// LRU refresh\n\t\t\tthis.cache.delete(key);\n\t\t\tthis.cache.set(key, cached);\n\t\t\treturn cached;\n\t\t}\n\t\t// Coalesce concurrent creation for the same key.\n\t\tlet pending = this.creating.get(key);\n\t\tif (!pending) {\n\t\t\tpending = this.createEntry(key);\n\t\t\tthis.creating.set(key, pending);\n\t\t\ttry {\n\t\t\t\tawait pending;\n\t\t\t} finally {\n\t\t\t\tthis.creating.delete(key);\n\t\t\t}\n\t\t}\n\t\treturn pending;\n\t}\n\n\tprivate async createEntry(key: string): Promise<CacheEntry> {\n\t\tconst stored = getSession(key);\n\t\tconst session = await this.sessionFactory(key, stored ? { sessionFile: stored.sessionFile } : undefined);\n\t\tconst sessionFile = session.sessionManager?.getSessionFile();\n\t\tconst sessionId = session.sessionManager?.getSessionId();\n\t\tif (sessionFile) {\n\t\t\tputSession(key, { sessionId: sessionId ?? key, sessionFile });\n\t\t}\n\t\tif (sessionId) {\n\t\t\tcreatePermissionContext(sessionId);\n\t\t}\n\t\tconst entry: CacheEntry = { session, busy: false, queue: [], dropped: 0, unsubscribe: undefined };\n\t\tthis.cache.set(key, entry);\n\t\tthis._enforceCacheCap(key);\n\t\tentry.unsubscribe = this._subscribeToSession(key, entry);\n\t\treturn entry;\n\t}\n\n\tprivate _enforceCacheCap(protectedKey?: string): void {\n\t\twhile (this.cache.size > this.cap) {\n\t\t\tlet oldestKey: string | undefined;\n\t\t\tlet oldest: CacheEntry | undefined;\n\t\t\tfor (const [key, entry] of this.cache) {\n\t\t\t\tif (key === protectedKey) continue;\n\t\t\t\tif (entry.busy) continue;\n\t\t\t\toldestKey = key;\n\t\t\t\toldest = entry;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (!oldest || !oldestKey) {\n\t\t\t\t// Every cached session is busy (or is the protected new entry);\n\t\t\t\t// grow the cap temporarily rather than killing an in-flight turn.\n\t\t\t\tthis.cap = this.cache.size;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\toldest.unsubscribe?.();\n\t\t\tthis.cache.delete(oldestKey);\n\t\t\toldest.session.dispose?.();\n\t\t\tconst evictedSessionId = oldest.session.sessionManager?.getSessionId();\n\t\t\tif (evictedSessionId) deletePermissionContext(evictedSessionId);\n\t\t}\n\t}\n\n\tprivate _subscribeToSession(key: string, entry: CacheEntry): () => void {\n\t\treturn entry.session.subscribe((event) => this._handleSessionEvent(key, event));\n\t}\n\n\tprivate _handleSessionEvent(key: string, event: AgentSessionEvent): void {\n\t\tif (event.type === \"message_start\" && event.message?.role === \"user\") {\n\t\t\tthis.redoStack.delete(key);\n\t\t}\n\t}\n}\n\nfunction extractUserText(message: AgentMessage): string {\n\tlet text = \"\";\n\tif (\"content\" in message && Array.isArray(message.content)) {\n\t\tfor (const block of message.content) {\n\t\t\tif (\n\t\t\t\tblock &&\n\t\t\t\ttypeof block === \"object\" &&\n\t\t\t\t\"type\" in block &&\n\t\t\t\tblock.type === \"text\" &&\n\t\t\t\t\"text\" in block &&\n\t\t\t\ttypeof block.text === \"string\"\n\t\t\t) {\n\t\t\t\ttext += block.text;\n\t\t\t}\n\t\t}\n\t}\n\treturn text;\n}\n"]}
1
+ {"version":3,"file":"agent-bridge.d.ts","sourceRoot":"","sources":["../../src/gateway/agent-bridge.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAGH,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACjF,OAAO,KAAK,EAAoB,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAC5E,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,8BAA8B,CAAC;AAC1D,OAAO,KAAK,EAAgB,iBAAiB,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AAC9F,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAEpE,OAAO,KAAK,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAChF,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AAE7D,OAAO,KAAK,EAAE,sBAAsB,EAAuC,MAAM,4BAA4B,CAAC;AAG9G,OAAO,KAAK,EAAqB,YAAY,EAAiB,MAAM,YAAY,CAAC;AAMjF,oFAAoF;AACpF,eAAO,MAAM,MAAM,4BAA4B,CAAC;AAOhD,yDAAyD;AACzD,wBAAgB,aAAa,IAAI,OAAO,CAEvC;AAED,wBAAgB,eAAe,IAAI,MAAM,CAExC;AAED,MAAM,WAAW,aAAa;IAC7B,mFAAmF;IACnF,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IAClC,qFAAqF;IACrF,gBAAgB,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IAC1C,iDAAiD;IACjD,OAAO,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAA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G/E;IAED;;;OAGG;IACG,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,YAAY,EAAE,SAAS,GAAE,aAAkB,GAAG,OAAO,CAAC,MAAM,CAAC,CA0B9F;IAEK,KAAK,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAEtC;IAED,uEAAuE;IACjE,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,GAAG,IAAI,CAAC,CAK3D;IAED,6DAA6D;IACvD,aAAa,CAAC,GAAG,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CA4BnE;IAED,8EAA8E;IACxE,IAAI,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;QAAE,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAC,CAoCrD;IAED,sDAAsD;IAChD,IAAI,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAerC;IAED,kEAAkE;IAClE,kBAAkB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAEtC;IAED,wFAAwF;IAClF,KAAK,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAkBtC;IAED,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,mBAAmB,CAO1C;YAGa,SAAS;YAiET,UAAU;YA2BV,WAAW;YAsBX,WAAW;IAkBzB,OAAO,CAAC,gBAAgB;IAyBxB,OAAO,CAAC,mBAAmB;IAI3B,OAAO,CAAC,mBAAmB;CAK3B","sourcesContent":["/**\n * lunR: gateway agent bridge.\n *\n * Owns the sessionKey → AgentSession mapping: an LRU cache (cap 20) over\n * live sessions, backed by store.ts so conversations survive daemon restarts\n * (a stored sessionFile is reopened via SessionManager.open, which\n * createAgentSession restores history from; a missing file starts fresh with\n * a one-line warning).\n *\n * New sessions replicate main.ts's headless wiring: SettingsManager +\n * DefaultResourceLoader with the builtin extension factories + the three\n * lunr bridges, then bindExtensions({ mode: \"print\" }) like print-mode.\n *\n * Busy guard: one turn per session at a time. Messages arriving mid-turn are\n * queued (cap 5, oldest dropped with a notice) and drained FIFO as a single\n * concatenated follow-up turn once the running turn ends; runTurn returns\n * the QUEUED sentinel for those, and the follow-up turn's result is\n * delivered via callbacks.onFollowUpResult.\n *\n * Streaming: subscribes to session events and converts cumulative\n * message_update snapshots into deltas for callbacks.onDelta.\n *\n * isGatewayTurn()/runDepth: incremented around every prompt() so Phase 4\n * (cron↔gateway delivery) and extensions can detect they run inside a\n * gateway turn and refuse self-scheduling. Every prompt() also runs inside\n * runWithOrigin(source, ...) (core/cron/origin-context) so tools executing\n * during the turn — e.g. the `cron` tool's create action — can read the chat\n * the message came from and stamp it as the job's delivery origin.\n */\n\nimport { existsSync } from \"node:fs\";\nimport type { AgentMessage, ThinkingLevel } from \"@ashx-j/lunr-agent\";\nimport type { AssistantMessage, ImageContent } from \"@ashx-j/lunr-ai\";\nimport type { Model } from \"@ashx-j/lunr-ai/compat\";\nimport type { AgentSession, AgentSessionEvent, SessionStats } from \"../core/agent-session.ts\";\nimport type { CompactionResult } from \"../core/compaction/index.ts\";\nimport { runWithOrigin } from \"../core/cron/origin-context.ts\";\nimport type { ContextUsage, ToolDefinition } from \"../core/extensions/types.ts\";\nimport type { ModelRuntime } from \"../core/model-runtime.ts\";\nimport { createPermissionContext, deletePermissionContext } from \"../core/permissions.ts\";\nimport type { ReadonlySessionManager, SessionManager, SessionMessageEntry } from \"../core/session-manager.ts\";\nimport { processImage } from \"../utils/image-process.ts\";\nimport { getSession, putSession, removeSession, touchSession } from \"./store.ts\";\nimport type { InboundAttachment, MessageEvent, SessionSource } from \"./types.ts\";\n\nfunction isUserMessageEntry(entry: { type: string }): entry is SessionMessageEntry {\n\treturn entry.type === \"message\";\n}\n\n/** runTurn resolves with this when the message was queued behind a running turn. */\nexport const QUEUED = \"__lunr_gateway_queued__\";\n\nconst CACHE_CAP = 20;\nconst QUEUE_CAP = 5;\n\nlet runDepth = 0;\n\n/** True while a gateway turn's prompt() is in flight. */\nexport function isGatewayTurn(): boolean {\n\treturn runDepth > 0;\n}\n\nexport function gatewayRunDepth(): number {\n\treturn runDepth;\n}\n\nexport interface TurnCallbacks {\n\t/** Assistant text delta during streaming (converted from cumulative snapshots). */\n\tonDelta?: (delta: string) => void;\n\t/** Final text of a drained-queue follow-up turn (deliver it like a normal reply). */\n\tonFollowUpResult?: (text: string) => void;\n\t/** Error from a drained-queue follow-up turn. */\n\tonError?: (message: string) => void;\n}\n\nexport interface BridgeSessionStatus {\n\tbusy: boolean;\n\tqueueDepth: number;\n\tcreatedAt?: string;\n}\n\n/**\n * Structural session shape the bridge needs — satisfied by AgentSession,\n * fakeable in tests. Expanded to support gateway slash commands.\n */\nexport interface BridgeSession {\n\tprompt(text: string, options?: { source?: \"extension\"; images?: ImageContent[] }): Promise<void>;\n\tabort(): Promise<void> | void;\n\tsubscribe(listener: (event: AgentSessionEvent) => void): () => void;\n\treadonly state: { messages: AgentMessage[] };\n\tdispose?(): void;\n\treadonly isStreaming: boolean;\n\treadonly isCompacting?: boolean;\n\treadonly model?: Model<any>;\n\treadonly modelRuntime: ModelRuntime;\n\treadonly thinkingLevel: ThinkingLevel;\n\treadonly messages: AgentMessage[];\n\treadonly systemPrompt: string;\n\treadonly sessionManager?: ReadonlySessionManager;\n\n\tgetActiveToolNames(): string[];\n\tgetToolDefinition(name: string): ToolDefinition | undefined;\n\tgetAvailableThinkingLevels(): ThinkingLevel[];\n\tsupportsThinking(): boolean;\n\tsetThinkingLevel(level: ThinkingLevel): void;\n\tsetModel(model: Model<any>): Promise<void>;\n\tcompact(customInstructions?: string): Promise<CompactionResult>;\n\tnavigateTree(\n\t\ttargetId: string,\n\t\toptions?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },\n\t): Promise<{ editorText?: string; editorImages?: ImageContent[]; cancelled: boolean; aborted?: boolean }>;\n\tgetContextUsage(): ContextUsage | undefined;\n\tgetSessionStats(): SessionStats;\n\tsetSessionName(name: string): void;\n}\n\nexport type SessionFactory = (key: string, reopen: { sessionFile: string } | undefined) => Promise<BridgeSession>;\n\ninterface CacheEntry {\n\tsession: BridgeSession;\n\tbusy: boolean;\n\tqueue: MessageEvent[];\n\tdropped: number;\n\tunsubscribe?: () => void;\n}\n\n/**\n * Default factory: headless session with the builtin extensions, mirroring\n * main.ts (minus TUI) + print-mode's bindExtensions.\n *\n * The heavy wiring is imported LAZILY: a static import of\n * builtin-extensions/index.ts here would pull the whole extension + TUI\n * graph into every consumer of this module (router tests, `gateway status`)\n * and trip the known ashxj-tui ↔ package-barrel cycle (see AGENTS.md\n * \"Barrel-import guard\"). Loading it on first session creation keeps module\n * import light and matches how main.ts loads it in the real CLI.\n */\nasync function defaultSessionFactory(key: string, reopen: { sessionFile: string } | undefined): Promise<AgentSession> {\n\tconst [\n\t\t{ loadAllBuiltinExtensions },\n\t\t{ getAgentDir },\n\t\t{ registerCustomizeBridge },\n\t\t{ reconcileBehaviorPreset, registerBehaviorPresetBridge },\n\t\t{ registerMemoryCapBridge },\n\t\t{ getModelTiersBridge, registerModelTierBridge },\n\t\t{ createAgentSessionFromServices, createAgentSessionServices },\n\t\t{ SessionManager },\n\t\t{ SettingsManager },\n\t] = await Promise.all([\n\t\timport(\"../builtin-extensions/index.ts\"),\n\t\timport(\"../config.ts\"),\n\t\timport(\"../core/customize.ts\"),\n\t\timport(\"../core/behavior-preset.ts\"),\n\t\timport(\"../core/memory-cap.ts\"),\n\t\timport(\"../core/model-tiers.ts\"),\n\t\timport(\"../core/agent-session-services.ts\"),\n\t\timport(\"../core/session-manager.ts\"),\n\t\timport(\"../core/settings-manager.ts\"),\n\t]);\n\tconst cwd = process.cwd();\n\tconst agentDir = getAgentDir();\n\tconst settingsManager = SettingsManager.create(cwd, agentDir, { projectTrusted: false });\n\t// Same bridges main.ts registers before extensions load.\n\tregisterModelTierBridge(settingsManager);\n\tregisterMemoryCapBridge(settingsManager);\n\tregisterBehaviorPresetBridge(settingsManager);\n\treconcileBehaviorPreset(settingsManager, agentDir);\n\tregisterCustomizeBridge(settingsManager);\n\n\tlet sessionManager: SessionManager;\n\tif (reopen && existsSync(reopen.sessionFile)) {\n\t\tsessionManager = SessionManager.open(reopen.sessionFile);\n\t} else {\n\t\tif (reopen) {\n\t\t\tconsole.warn(`[gateway] stored session file missing for ${key}; starting a fresh session`);\n\t\t}\n\t\tsessionManager = SessionManager.create(cwd);\n\t}\n\n\t// Services-first (mirrors main.ts): extension-registered providers (e.g.\n\t// ollama-cloud) must land in the shared ModelRuntime BEFORE session\n\t// creation — otherwise findInitialModel can't resolve the user's default\n\t// model and silently falls back to an arbitrary catalog provider (this\n\t// exact bug sent gateway turns to openrouter with no key → 401).\n\tconst services = await createAgentSessionServices({\n\t\tcwd,\n\t\tagentDir,\n\t\tsettingsManager,\n\t\tresourceLoaderOptions: { extensionFactories: await loadAllBuiltinExtensions() },\n\t});\n\tconst { session } = await createAgentSessionFromServices({ services, sessionManager });\n\tgetModelTiersBridge()?.setParentThinkingProvider(() => session.thinkingLevel);\n\tawait session.bindExtensions({\n\t\tmode: \"print\",\n\t\tonError: (err) => console.error(`[gateway] extension error (${err.extensionPath}): ${err.error}`),\n\t});\n\treturn session;\n}\n\n/** Final assistant text, print-mode style; throws on error/aborted stop. */\nfunction extractFinalText(session: BridgeSession): string {\n\tconst messages = session.state.messages;\n\tconst last = messages[messages.length - 1];\n\tif (last?.role !== \"assistant\") return \"\";\n\tconst assistant = last as AssistantMessage;\n\tif (assistant.stopReason === \"error\" || assistant.stopReason === \"aborted\") {\n\t\tthrow new Error(assistant.errorMessage || `Request ${assistant.stopReason}`);\n\t}\n\tlet text = \"\";\n\tfor (const content of assistant.content) {\n\t\tif (content.type === \"text\") text += content.text;\n\t}\n\treturn text;\n}\n\nexport class AgentBridge {\n\tprivate cap: number;\n\tprivate readonly sessionFactory: SessionFactory;\n\tprivate readonly cache = new Map<string, CacheEntry>();\n\tprivate readonly redoStack = new Map<string, string[]>();\n\tprivate readonly creating = new Map<string, Promise<CacheEntry>>();\n\n\tconstructor(options: { cacheCap?: number; sessionFactory?: SessionFactory } = {}) {\n\t\tthis.cap = options.cacheCap ?? CACHE_CAP;\n\t\tthis.sessionFactory = options.sessionFactory ?? defaultSessionFactory;\n\t}\n\n\t/**\n\t * Run one conversational turn. Resolves with the final assistant text, or\n\t * the QUEUED sentinel when the session was busy (router must not reply).\n\t */\n\tasync runTurn(key: string, event: MessageEvent, callbacks: TurnCallbacks = {}): Promise<string> {\n\t\tconst entry = await this.getOrCreate(key);\n\t\tif (entry.busy) {\n\t\t\tif (entry.queue.length >= QUEUE_CAP) {\n\t\t\t\tentry.queue.shift();\n\t\t\t\tentry.dropped++;\n\t\t\t}\n\t\t\tentry.queue.push(event);\n\t\t\treturn QUEUED;\n\t\t}\n\t\tentry.busy = true;\n\t\tlet result: string;\n\t\ttry {\n\t\t\tresult = await this.runPrompt(entry, event.text, callbacks, event.source, event.attachments);\n\t\t} catch (err) {\n\t\t\tentry.busy = false;\n\t\t\tthrow err;\n\t\t}\n\t\ttouchSession(key);\n\t\t// Drain queued messages as one follow-up turn, fire-and-forget. The busy\n\t\t// flag stays set until the queue is empty so turn ordering is strict;\n\t\t// the follow-up result arrives via callbacks.onFollowUpResult.\n\t\tvoid this.drainQueue(entry, callbacks).finally(() => {\n\t\t\tentry.busy = false;\n\t\t});\n\t\treturn result;\n\t}\n\n\tasync abort(key: string): Promise<void> {\n\t\tawait this.cache.get(key)?.session.abort();\n\t}\n\n\t/** Return the live session for a key, or null when none exists yet. */\n\tasync getSession(key: string): Promise<BridgeSession | null> {\n\t\tconst cached = this.cache.get(key);\n\t\tif (cached) return cached.session;\n\t\tif (!getSession(key)) return null;\n\t\treturn (await this.getOrCreate(key)).session;\n\t}\n\n\t/** Switch the chat to a different persisted session file. */\n\tasync switchSession(key: string, sessionFile: string): Promise<void> {\n\t\tconst entry = this.cache.get(key);\n\t\tif (entry?.busy) {\n\t\t\tthrow new Error(\"Session is busy — /stop first or wait\");\n\t\t}\n\t\tif (entry) {\n\t\t\tconst oldSessionId = entry.session.sessionManager?.getSessionId();\n\t\t\tentry.unsubscribe?.();\n\t\t\tthis.cache.delete(key);\n\t\t\tentry.session.dispose?.();\n\t\t\tif (oldSessionId) deletePermissionContext(oldSessionId);\n\t\t}\n\t\tremoveSession(key);\n\t\tthis.redoStack.delete(key);\n\n\t\tconst session = await this.sessionFactory(key, { sessionFile });\n\t\tconst newFile = session.sessionManager?.getSessionFile();\n\t\tconst newSessionId = session.sessionManager?.getSessionId();\n\t\tif (newFile) {\n\t\t\tputSession(key, { sessionId: newSessionId ?? key, sessionFile: newFile });\n\t\t}\n\t\tif (newSessionId) {\n\t\t\tcreatePermissionContext(newSessionId);\n\t\t}\n\t\tconst newEntry: CacheEntry = { session, busy: false, queue: [], dropped: 0 };\n\t\tthis.cache.set(key, newEntry);\n\t\tthis._enforceCacheCap(key);\n\t\tnewEntry.unsubscribe = this._subscribeToSession(key, newEntry);\n\t}\n\n\t/** Undo the last user turn and push the previous leaf onto the redo stack. */\n\tasync undo(key: string): Promise<{ userText: string }> {\n\t\tconst session = await this.getSession(key);\n\t\tif (!session) throw new Error(\"No session\");\n\t\tif (session.isStreaming) throw new Error(\"Wait for the current response to finish\");\n\t\tconst branch = session.sessionManager?.getBranch() ?? [];\n\t\tlet lastUserIndex = -1;\n\t\tfor (let i = branch.length - 1; i >= 0; i--) {\n\t\t\tconst entry = branch[i];\n\t\t\tif (isUserMessageEntry(entry) && entry.message.role === \"user\") {\n\t\t\t\tlastUserIndex = i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (lastUserIndex === -1) throw new Error(\"Nothing to undo\");\n\t\tconst lastUser = branch[lastUserIndex];\n\t\tif (!isUserMessageEntry(lastUser)) throw new Error(\"Nothing to undo\");\n\n\t\tconst leafId = session.sessionManager?.getLeafId() ?? null;\n\t\tlet targetId: string;\n\t\tif (lastUser.id === leafId) {\n\t\t\tif (!lastUser.parentId) throw new Error(\"Nothing to undo\");\n\t\t\ttargetId = lastUser.parentId;\n\t\t} else {\n\t\t\ttargetId = lastUser.id;\n\t\t}\n\n\t\tconst result = await session.navigateTree(targetId, {});\n\t\tif (result.cancelled) throw new Error(\"Navigation cancelled\");\n\n\t\tif (leafId) {\n\t\t\tconst stack = this.redoStack.get(key) ?? [];\n\t\t\tstack.push(leafId);\n\t\t\tthis.redoStack.set(key, stack);\n\t\t}\n\n\t\treturn { userText: extractUserText(lastUser.message) };\n\t}\n\n\t/** Redo to the leaf saved by the most recent undo. */\n\tasync redo(key: string): Promise<void> {\n\t\tconst session = await this.getSession(key);\n\t\tif (!session) throw new Error(\"No session\");\n\t\tif (session.isStreaming) throw new Error(\"Wait for the current response to finish\");\n\t\tconst stack = this.redoStack.get(key) ?? [];\n\t\tconst targetId = stack.pop();\n\t\tif (!targetId) throw new Error(\"Nothing to redo\");\n\t\tthis.redoStack.set(key, stack);\n\n\t\tconst result = await session.navigateTree(targetId, {});\n\t\tif (result.cancelled) {\n\t\t\tstack.push(targetId);\n\t\t\tthis.redoStack.set(key, stack);\n\t\t\tthrow new Error(\"Navigation cancelled\");\n\t\t}\n\t}\n\n\t/** Test/debug hook: how many redo targets are saved for a key. */\n\tgetRedoStackLength(key: string): number {\n\t\treturn this.redoStack.get(key)?.length ?? 0;\n\t}\n\n\t/** Drop the cached session (disposing it) and forget the store entry (/new, /reset). */\n\tasync reset(key: string): Promise<void> {\n\t\tconst entry = this.cache.get(key);\n\t\tif (entry) {\n\t\t\t// lunr: /new while busy must stop the live turn and drop queued follow-ups\n\t\t\t// before dispose, otherwise drainQueue can still fire on the torn-down entry.\n\t\t\tentry.queue.length = 0;\n\t\t\tentry.dropped = 0;\n\t\t\ttry {\n\t\t\t\tawait entry.session.abort();\n\t\t\t} catch {\n\t\t\t\t// best-effort; dispose still tears the session down\n\t\t\t}\n\t\t\tentry.unsubscribe?.();\n\t\t\tthis.cache.delete(key);\n\t\t\tentry.session.dispose?.();\n\t\t}\n\t\tremoveSession(key);\n\t\tthis.redoStack.delete(key);\n\t}\n\n\tgetStatus(key: string): BridgeSessionStatus {\n\t\tconst entry = this.cache.get(key);\n\t\treturn {\n\t\t\tbusy: entry?.busy ?? false,\n\t\t\tqueueDepth: entry?.queue.length ?? 0,\n\t\t\tcreatedAt: getSession(key)?.createdAt,\n\t\t};\n\t}\n\n\t/** One prompt → final text. Increments runDepth; streams deltas when asked. */\n\tprivate async runPrompt(\n\t\tentry: CacheEntry,\n\t\ttext: string,\n\t\tcallbacks: TurnCallbacks,\n\t\tsource: SessionSource,\n\t\tattachments?: InboundAttachment[],\n\t): Promise<string> {\n\t\tconst { session } = entry;\n\t\tlet unsubscribe: (() => void) | undefined;\n\t\tif (callbacks.onDelta) {\n\t\t\tconst onDelta = callbacks.onDelta;\n\t\t\tlet streamedLen = 0;\n\t\t\tunsubscribe = session.subscribe((event: AgentSessionEvent) => {\n\t\t\t\tif (event.type !== \"message_update\") return;\n\t\t\t\tconst assistantEvent = event.assistantMessageEvent;\n\t\t\t\tif (assistantEvent.type !== \"text_delta\") return;\n\t\t\t\tlet full = \"\";\n\t\t\t\tfor (const content of assistantEvent.partial.content) {\n\t\t\t\t\tif (content.type === \"text\") full += content.text;\n\t\t\t\t}\n\t\t\t\tif (full.length < streamedLen) streamedLen = 0; // new assistant message (tool-call boundary)\n\t\t\t\tif (full.length > streamedLen) {\n\t\t\t\t\tonDelta(full.slice(streamedLen));\n\t\t\t\t\tstreamedLen = full.length;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\trunDepth++;\n\t\ttry {\n\t\t\t// lunr: convert inbound image attachments to ImageContent for the model.\n\t\t\t// processImage normalizes + resizes under the inline 4.5MB base64 limit;\n\t\t\t// failures become bracketed text notes so the model explains the gap.\n\t\t\tconst images: ImageContent[] = [];\n\t\t\tconst notes: string[] = [];\n\t\t\tfor (const attachment of attachments ?? []) {\n\t\t\t\tconst bytes = Buffer.from(attachment.data, \"base64\");\n\t\t\t\tconst processed = await processImage(new Uint8Array(bytes), attachment.mimeType);\n\t\t\t\tif (processed.ok) {\n\t\t\t\t\timages.push({ type: \"image\", data: processed.data, mimeType: processed.mimeType });\n\t\t\t\t\tfor (const hint of processed.hints) notes.push(hint);\n\t\t\t\t} else {\n\t\t\t\t\tnotes.push(processed.message);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst promptText = notes.length > 0 ? `${text}\\n\\n${notes.join(\" \")}` : text;\n\t\t\t// AsyncLocalStorage origin: tools executing during this turn (e.g. the\n\t\t\t// `cron` tool) can read the chat the message came from. Propagates\n\t\t\t// through the awaited prompt() call tree.\n\t\t\tawait runWithOrigin(\n\t\t\t\t{\n\t\t\t\t\tplatform: source.platform,\n\t\t\t\t\tchatId: source.chatId,\n\t\t\t\t\tthreadId: source.threadId,\n\t\t\t\t\tchatType: source.chatType,\n\t\t\t\t},\n\t\t\t\t() => session.prompt(promptText, { source: \"extension\", ...(images.length ? { images } : {}) }),\n\t\t\t);\n\t\t} finally {\n\t\t\trunDepth--;\n\t\t\tunsubscribe?.();\n\t\t}\n\t\treturn extractFinalText(session);\n\t}\n\n\t/** Drain the queue FIFO: all queued messages become one concatenated turn. */\n\tprivate async drainQueue(entry: CacheEntry, callbacks: TurnCallbacks): Promise<void> {\n\t\twhile (entry.queue.length > 0) {\n\t\t\tconst items = entry.queue.splice(0);\n\t\t\tconst parts = items.map((item) => item.text);\n\t\t\tconst attachments = items.flatMap((item) => item.attachments ?? []);\n\t\t\tif (entry.dropped > 0) {\n\t\t\t\tparts.unshift(`[gateway: ${entry.dropped} earlier message(s) were dropped — the queue was full]`);\n\t\t\t\tentry.dropped = 0;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\t// Follow-up turns are final-only: no streaming callbacks. The origin\n\t\t\t\t// is the chat of the latest queued message.\n\t\t\t\tconst text = await this.runPrompt(\n\t\t\t\t\tentry,\n\t\t\t\t\tparts.join(\"\\n\\n\"),\n\t\t\t\t\t{},\n\t\t\t\t\titems[items.length - 1].source,\n\t\t\t\t\tattachments,\n\t\t\t\t);\n\t\t\t\tcallbacks.onFollowUpResult?.(text);\n\t\t\t} catch (err) {\n\t\t\t\tcallbacks.onError?.(err instanceof Error ? err.message : String(err));\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async getOrCreate(key: string): Promise<CacheEntry> {\n\t\tconst cached = this.cache.get(key);\n\t\tif (cached) {\n\t\t\t// LRU refresh\n\t\t\tthis.cache.delete(key);\n\t\t\tthis.cache.set(key, cached);\n\t\t\treturn cached;\n\t\t}\n\t\t// Coalesce concurrent creation for the same key.\n\t\tlet pending = this.creating.get(key);\n\t\tif (!pending) {\n\t\t\tpending = this.createEntry(key);\n\t\t\tthis.creating.set(key, pending);\n\t\t\ttry {\n\t\t\t\tawait pending;\n\t\t\t} finally {\n\t\t\t\tthis.creating.delete(key);\n\t\t\t}\n\t\t}\n\t\treturn pending;\n\t}\n\n\tprivate async createEntry(key: string): Promise<CacheEntry> {\n\t\tconst stored = getSession(key);\n\t\tconst session = await this.sessionFactory(key, stored ? { sessionFile: stored.sessionFile } : undefined);\n\t\tconst sessionFile = session.sessionManager?.getSessionFile();\n\t\tconst sessionId = session.sessionManager?.getSessionId();\n\t\tif (sessionFile) {\n\t\t\tputSession(key, { sessionId: sessionId ?? key, sessionFile });\n\t\t}\n\t\tif (sessionId) {\n\t\t\tcreatePermissionContext(sessionId);\n\t\t}\n\t\tconst entry: CacheEntry = { session, busy: false, queue: [], dropped: 0, unsubscribe: undefined };\n\t\tthis.cache.set(key, entry);\n\t\tthis._enforceCacheCap(key);\n\t\tentry.unsubscribe = this._subscribeToSession(key, entry);\n\t\treturn entry;\n\t}\n\n\tprivate _enforceCacheCap(protectedKey?: string): void {\n\t\twhile (this.cache.size > this.cap) {\n\t\t\tlet oldestKey: string | undefined;\n\t\t\tlet oldest: CacheEntry | undefined;\n\t\t\tfor (const [key, entry] of this.cache) {\n\t\t\t\tif (key === protectedKey) continue;\n\t\t\t\tif (entry.busy) continue;\n\t\t\t\toldestKey = key;\n\t\t\t\toldest = entry;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (!oldest || !oldestKey) {\n\t\t\t\t// Every cached session is busy (or is the protected new entry);\n\t\t\t\t// grow the cap temporarily rather than killing an in-flight turn.\n\t\t\t\tthis.cap = this.cache.size;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\toldest.unsubscribe?.();\n\t\t\tthis.cache.delete(oldestKey);\n\t\t\toldest.session.dispose?.();\n\t\t\tconst evictedSessionId = oldest.session.sessionManager?.getSessionId();\n\t\t\tif (evictedSessionId) deletePermissionContext(evictedSessionId);\n\t\t}\n\t}\n\n\tprivate _subscribeToSession(key: string, entry: CacheEntry): () => void {\n\t\treturn entry.session.subscribe((event) => this._handleSessionEvent(key, event));\n\t}\n\n\tprivate _handleSessionEvent(key: string, event: AgentSessionEvent): void {\n\t\tif (event.type === \"message_start\" && event.message?.role === \"user\") {\n\t\t\tthis.redoStack.delete(key);\n\t\t}\n\t}\n}\n\nfunction extractUserText(message: AgentMessage): string {\n\tlet text = \"\";\n\tif (\"content\" in message && Array.isArray(message.content)) {\n\t\tfor (const block of message.content) {\n\t\t\tif (\n\t\t\t\tblock &&\n\t\t\t\ttypeof block === \"object\" &&\n\t\t\t\t\"type\" in block &&\n\t\t\t\tblock.type === \"text\" &&\n\t\t\t\t\"text\" in block &&\n\t\t\t\ttypeof block.text === \"string\"\n\t\t\t) {\n\t\t\t\ttext += block.text;\n\t\t\t}\n\t\t}\n\t}\n\treturn text;\n}\n"]}
@@ -274,9 +274,19 @@ export class AgentBridge {
274
274
  return this.redoStack.get(key)?.length ?? 0;
275
275
  }
276
276
  /** Drop the cached session (disposing it) and forget the store entry (/new, /reset). */
277
- reset(key) {
277
+ async reset(key) {
278
278
  const entry = this.cache.get(key);
279
279
  if (entry) {
280
+ // lunr: /new while busy must stop the live turn and drop queued follow-ups
281
+ // before dispose, otherwise drainQueue can still fire on the torn-down entry.
282
+ entry.queue.length = 0;
283
+ entry.dropped = 0;
284
+ try {
285
+ await entry.session.abort();
286
+ }
287
+ catch {
288
+ // best-effort; dispose still tears the session down
289
+ }
280
290
  entry.unsubscribe?.();
281
291
  this.cache.delete(key);
282
292
  entry.session.dispose?.();