@ouro.bot/cli 0.1.0-alpha.3 → 0.1.0-alpha.300

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 (289) hide show
  1. package/README.md +188 -190
  2. package/SerpentGuide.ouro/agent.json +82 -0
  3. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/SOUL.md +6 -3
  4. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/monty.md +2 -2
  5. package/SerpentGuide.ouro/psyche/identities/python.md +31 -0
  6. package/assets/ouroboros.png +0 -0
  7. package/changelog.json +1888 -0
  8. package/dist/arc/attention-types.js +8 -0
  9. package/dist/arc/cares.js +140 -0
  10. package/dist/arc/episodes.js +117 -0
  11. package/dist/arc/intentions.js +133 -0
  12. package/dist/arc/json-store.js +117 -0
  13. package/dist/arc/obligations.js +237 -0
  14. package/dist/arc/packets.js +203 -0
  15. package/dist/arc/presence.js +185 -0
  16. package/dist/heart/active-work.js +832 -0
  17. package/dist/heart/agent-entry.js +37 -2
  18. package/dist/heart/attachments/image-normalize.js +194 -0
  19. package/dist/heart/attachments/materialize.js +230 -0
  20. package/dist/heart/attachments/render.js +29 -0
  21. package/dist/heart/attachments/store.js +103 -0
  22. package/dist/heart/attachments/types.js +138 -0
  23. package/dist/heart/auth/auth-flow.js +456 -0
  24. package/dist/heart/bridges/manager.js +358 -0
  25. package/dist/heart/bridges/state-machine.js +135 -0
  26. package/dist/heart/bridges/store.js +123 -0
  27. package/dist/heart/bundle-state.js +168 -0
  28. package/dist/heart/commitments.js +111 -0
  29. package/dist/heart/config-registry.js +304 -0
  30. package/dist/heart/config.js +123 -28
  31. package/dist/heart/core.js +738 -191
  32. package/dist/heart/cross-chat-delivery.js +131 -0
  33. package/dist/heart/daemon/agent-config-check.js +149 -0
  34. package/dist/heart/daemon/agent-discovery.js +157 -0
  35. package/dist/heart/daemon/agent-service.js +360 -0
  36. package/dist/heart/daemon/cadence.js +70 -0
  37. package/dist/heart/daemon/cli-defaults.js +574 -0
  38. package/dist/heart/daemon/cli-exec.js +1945 -0
  39. package/dist/heart/daemon/cli-parse.js +808 -0
  40. package/dist/heart/daemon/cli-render.js +503 -0
  41. package/dist/heart/daemon/cli-types.js +8 -0
  42. package/dist/heart/daemon/daemon-cli.js +29 -673
  43. package/dist/heart/daemon/daemon-entry.js +259 -8
  44. package/dist/heart/daemon/daemon-health.js +136 -0
  45. package/dist/heart/daemon/daemon-runtime-sync.js +231 -0
  46. package/dist/heart/daemon/daemon-tombstone.js +236 -0
  47. package/dist/heart/daemon/daemon.js +745 -18
  48. package/dist/heart/daemon/health-monitor.js +38 -0
  49. package/dist/heart/daemon/hooks/agent-config-v2.js +33 -0
  50. package/dist/heart/daemon/hooks/bundle-meta.js +206 -0
  51. package/dist/heart/daemon/inner-status.js +89 -0
  52. package/dist/heart/daemon/launchd.js +171 -0
  53. package/dist/heart/daemon/log-tailer.js +82 -12
  54. package/dist/heart/daemon/logs-prune.js +105 -0
  55. package/dist/heart/daemon/message-router.js +17 -8
  56. package/dist/heart/daemon/os-cron-deps.js +134 -0
  57. package/dist/heart/daemon/ouro-bot-entry.js +1 -1
  58. package/dist/heart/daemon/process-manager.js +181 -1
  59. package/dist/heart/daemon/pulse.js +463 -0
  60. package/dist/heart/daemon/run-hooks.js +39 -0
  61. package/dist/heart/daemon/runtime-logging.js +70 -15
  62. package/dist/heart/daemon/runtime-metadata.js +219 -0
  63. package/dist/heart/daemon/runtime-mode.js +67 -0
  64. package/dist/heart/daemon/safe-mode.js +161 -0
  65. package/dist/heart/daemon/sense-manager.js +335 -0
  66. package/dist/heart/daemon/session-id-resolver.js +131 -0
  67. package/dist/heart/daemon/skill-management-installer.js +94 -0
  68. package/dist/heart/daemon/socket-client.js +307 -0
  69. package/dist/heart/daemon/task-scheduler.js +3 -25
  70. package/dist/heart/daemon/thoughts.js +510 -0
  71. package/dist/heart/delegation.js +62 -0
  72. package/dist/heart/habits/habit-migration.js +181 -0
  73. package/dist/heart/habits/habit-parser.js +140 -0
  74. package/dist/heart/habits/habit-scheduler.js +371 -0
  75. package/dist/heart/hatch/hatch-animation.js +35 -0
  76. package/dist/heart/{daemon → hatch}/hatch-flow.js +31 -130
  77. package/dist/heart/{daemon → hatch}/hatch-specialist.js +7 -2
  78. package/dist/heart/hatch/specialist-orchestrator.js +129 -0
  79. package/dist/heart/hatch/specialist-prompt.js +101 -0
  80. package/dist/heart/hatch/specialist-tools.js +283 -0
  81. package/dist/heart/identity.js +241 -54
  82. package/dist/heart/kicks.js +2 -20
  83. package/dist/heart/mcp/mcp-server.js +653 -0
  84. package/dist/heart/migrate-config.js +127 -0
  85. package/dist/heart/model-capabilities.js +59 -0
  86. package/dist/heart/outlook/outlook-http.js +439 -0
  87. package/dist/heart/outlook/outlook-read.js +1618 -0
  88. package/dist/heart/outlook/outlook-render.js +1032 -0
  89. package/dist/heart/outlook/outlook-types.js +7 -0
  90. package/dist/heart/outlook/outlook-view.js +194 -0
  91. package/dist/heart/progress-story.js +42 -0
  92. package/dist/heart/provider-failover.js +88 -0
  93. package/dist/heart/provider-ping.js +162 -0
  94. package/dist/heart/providers/anthropic-token.js +163 -0
  95. package/dist/heart/providers/anthropic.js +181 -41
  96. package/dist/heart/providers/azure.js +98 -11
  97. package/dist/heart/providers/error-classification.js +63 -0
  98. package/dist/heart/providers/github-copilot.js +136 -0
  99. package/dist/heart/providers/minimax-vlm.js +189 -0
  100. package/dist/heart/providers/minimax.js +23 -5
  101. package/dist/heart/providers/openai-codex.js +33 -22
  102. package/dist/heart/sense-truth.js +61 -0
  103. package/dist/heart/session-activity.js +172 -0
  104. package/dist/heart/session-recall.js +216 -0
  105. package/dist/heart/start-of-turn-packet.js +339 -0
  106. package/dist/heart/streaming.js +120 -33
  107. package/dist/heart/sync.js +332 -0
  108. package/dist/heart/target-resolution.js +127 -0
  109. package/dist/heart/tempo.js +93 -0
  110. package/dist/heart/temporal-view.js +41 -0
  111. package/dist/heart/tool-activity-callbacks.js +36 -0
  112. package/dist/heart/tool-description.js +135 -0
  113. package/dist/heart/tool-friction.js +55 -0
  114. package/dist/heart/tool-loop.js +200 -0
  115. package/dist/heart/turn-context.js +358 -0
  116. package/dist/heart/turn-coordinator.js +28 -0
  117. package/dist/heart/versioning/ouro-bot-global-installer.js +128 -0
  118. package/dist/heart/{daemon → versioning}/ouro-bot-wrapper.js +5 -4
  119. package/dist/heart/versioning/ouro-path-installer.js +221 -0
  120. package/dist/heart/{daemon → versioning}/ouro-uti.js +11 -2
  121. package/dist/heart/versioning/ouro-version-manager.js +295 -0
  122. package/dist/heart/versioning/staged-restart.js +146 -0
  123. package/dist/heart/versioning/update-checker.js +113 -0
  124. package/dist/heart/versioning/update-hooks.js +142 -0
  125. package/dist/heart/versioning/wrapper-publish-guard.js +86 -0
  126. package/dist/mind/associative-recall.js +135 -66
  127. package/dist/mind/bundle-manifest.js +77 -1
  128. package/dist/mind/context.js +125 -14
  129. package/dist/mind/diary-integrity.js +60 -0
  130. package/dist/mind/{memory.js → diary.js} +84 -96
  131. package/dist/mind/embedding-provider.js +60 -0
  132. package/dist/mind/file-state.js +179 -0
  133. package/dist/mind/first-impressions.js +16 -2
  134. package/dist/mind/friends/channel.js +64 -0
  135. package/dist/mind/friends/group-context.js +144 -0
  136. package/dist/mind/friends/resolver.js +37 -0
  137. package/dist/mind/friends/store-file.js +58 -3
  138. package/dist/mind/friends/trust-explanation.js +74 -0
  139. package/dist/mind/friends/types.js +9 -1
  140. package/dist/mind/journal-index.js +161 -0
  141. package/dist/mind/obligation-steering.js +221 -0
  142. package/dist/mind/pending.js +76 -9
  143. package/dist/mind/phrases.js +1 -0
  144. package/dist/mind/prompt.js +1011 -107
  145. package/dist/mind/scrutiny.js +173 -0
  146. package/dist/mind/token-estimate.js +8 -12
  147. package/dist/nerves/cli-logging.js +22 -3
  148. package/dist/nerves/coverage/audit.js +1 -1
  149. package/dist/nerves/coverage/file-completeness.js +59 -5
  150. package/dist/nerves/coverage/run-artifacts.js +1 -1
  151. package/dist/nerves/event-buffer.js +111 -0
  152. package/dist/nerves/index.js +224 -4
  153. package/dist/nerves/observation.js +20 -0
  154. package/dist/nerves/redact.js +79 -0
  155. package/dist/nerves/runtime.js +5 -1
  156. package/dist/outlook-ui/assets/index-Ck8agNeO.js +61 -0
  157. package/dist/outlook-ui/assets/index-LwChZTgL.css +1 -0
  158. package/dist/outlook-ui/index.html +15 -0
  159. package/dist/repertoire/ado-client.js +17 -56
  160. package/dist/repertoire/ado-semantic.js +11 -10
  161. package/dist/repertoire/api-client.js +97 -0
  162. package/dist/repertoire/bitwarden-store.js +319 -0
  163. package/dist/repertoire/bundle-templates.js +72 -0
  164. package/dist/repertoire/bw-installer.js +79 -0
  165. package/dist/repertoire/coding/codex-jsonl.js +64 -0
  166. package/dist/repertoire/coding/context-pack.js +330 -0
  167. package/dist/repertoire/coding/feedback.js +301 -0
  168. package/dist/repertoire/coding/index.js +4 -1
  169. package/dist/repertoire/coding/manager.js +220 -13
  170. package/dist/repertoire/coding/spawner.js +58 -12
  171. package/dist/repertoire/coding/tools.js +209 -7
  172. package/dist/repertoire/commerce-errors.js +109 -0
  173. package/dist/repertoire/commerce-self-test.js +156 -0
  174. package/dist/repertoire/credential-access.js +527 -0
  175. package/dist/repertoire/data/ado-endpoints.json +188 -0
  176. package/dist/repertoire/duffel-client.js +185 -0
  177. package/dist/repertoire/github-client.js +14 -55
  178. package/dist/repertoire/graph-client.js +11 -52
  179. package/dist/repertoire/guardrails.js +375 -0
  180. package/dist/repertoire/mcp-client.js +255 -0
  181. package/dist/repertoire/mcp-manager.js +305 -0
  182. package/dist/repertoire/mcp-tools.js +63 -0
  183. package/dist/repertoire/shell-sessions.js +133 -0
  184. package/dist/repertoire/skills.js +14 -23
  185. package/dist/repertoire/stripe-client.js +131 -0
  186. package/dist/repertoire/tasks/board.js +43 -5
  187. package/dist/repertoire/tasks/fix.js +182 -0
  188. package/dist/repertoire/tasks/index.js +28 -10
  189. package/dist/repertoire/tasks/lifecycle.js +2 -2
  190. package/dist/repertoire/tasks/parser.js +3 -2
  191. package/dist/repertoire/tasks/scanner.js +194 -37
  192. package/dist/repertoire/tasks/transitions.js +11 -28
  193. package/dist/repertoire/tool-results.js +29 -0
  194. package/dist/repertoire/tools-attachments.js +316 -0
  195. package/dist/repertoire/tools-base.js +45 -707
  196. package/dist/repertoire/tools-bluebubbles.js +94 -0
  197. package/dist/repertoire/tools-bridge.js +141 -0
  198. package/dist/repertoire/tools-bundle.js +984 -0
  199. package/dist/repertoire/tools-config.js +185 -0
  200. package/dist/repertoire/tools-continuity.js +248 -0
  201. package/dist/repertoire/tools-credential.js +182 -0
  202. package/dist/repertoire/tools-files.js +342 -0
  203. package/dist/repertoire/tools-flight.js +224 -0
  204. package/dist/repertoire/tools-flow.js +105 -0
  205. package/dist/repertoire/tools-github.js +1 -7
  206. package/dist/repertoire/tools-memory.js +374 -0
  207. package/dist/repertoire/tools-session.js +739 -0
  208. package/dist/repertoire/tools-shell.js +120 -0
  209. package/dist/repertoire/tools-stripe.js +180 -0
  210. package/dist/repertoire/tools-surface.js +243 -0
  211. package/dist/repertoire/tools-teams.js +64 -61
  212. package/dist/repertoire/tools-travel.js +125 -0
  213. package/dist/repertoire/tools-user-profile.js +144 -0
  214. package/dist/repertoire/tools-vault.js +110 -0
  215. package/dist/repertoire/tools.js +149 -98
  216. package/dist/repertoire/travel-api-client.js +360 -0
  217. package/dist/repertoire/user-profile.js +118 -0
  218. package/dist/repertoire/vault-setup.js +241 -0
  219. package/dist/scripts/claude-code-hook.js +41 -0
  220. package/dist/scripts/claude-code-stop-hook.js +47 -0
  221. package/dist/senses/attention-queue.js +116 -0
  222. package/dist/senses/bluebubbles/attachment-cache.js +53 -0
  223. package/dist/senses/bluebubbles/attachment-download.js +137 -0
  224. package/dist/senses/bluebubbles/client.js +568 -0
  225. package/dist/senses/bluebubbles/entry.js +13 -0
  226. package/dist/senses/bluebubbles/inbound-log.js +113 -0
  227. package/dist/senses/bluebubbles/index.js +1427 -0
  228. package/dist/senses/bluebubbles/media.js +390 -0
  229. package/dist/senses/bluebubbles/model.js +282 -0
  230. package/dist/senses/bluebubbles/mutation-log.js +116 -0
  231. package/dist/senses/bluebubbles/replay.js +129 -0
  232. package/dist/senses/bluebubbles/runtime-state.js +109 -0
  233. package/dist/senses/bluebubbles/session-cleanup.js +72 -0
  234. package/dist/senses/cli/bracketed-paste.js +82 -0
  235. package/dist/senses/cli/image-paste.js +287 -0
  236. package/dist/senses/cli/image-ref-navigation.js +75 -0
  237. package/dist/senses/cli/ink-app.js +156 -0
  238. package/dist/senses/cli/inline-diff.js +64 -0
  239. package/dist/senses/cli/input-keys.js +174 -0
  240. package/dist/senses/cli/kill-ring.js +86 -0
  241. package/dist/senses/cli/message-list.js +51 -0
  242. package/dist/senses/cli/ouro-tui.js +595 -0
  243. package/dist/senses/cli/spinner-imperative.js +135 -0
  244. package/dist/senses/cli/spinner.js +101 -0
  245. package/dist/senses/cli/status-line.js +60 -0
  246. package/dist/senses/cli/streaming-markdown.js +526 -0
  247. package/dist/senses/cli/tool-display.js +83 -0
  248. package/dist/senses/cli/tool-render.js +85 -0
  249. package/dist/senses/cli/tui-store.js +240 -0
  250. package/dist/senses/cli/virtual-list.js +35 -0
  251. package/dist/senses/cli-entry.js +1 -1
  252. package/dist/senses/cli-layout.js +187 -0
  253. package/dist/senses/cli.js +772 -264
  254. package/dist/senses/commands.js +65 -1
  255. package/dist/senses/continuity.js +94 -0
  256. package/dist/senses/habit-turn-message.js +108 -0
  257. package/dist/senses/inner-dialog-worker.js +112 -19
  258. package/dist/senses/inner-dialog.js +633 -86
  259. package/dist/senses/pipeline.js +560 -0
  260. package/dist/senses/shared-turn.js +195 -0
  261. package/dist/senses/surface-tool.js +68 -0
  262. package/dist/senses/teams.js +814 -196
  263. package/dist/senses/trust-gate.js +112 -2
  264. package/package.json +25 -9
  265. package/skills/agent-commerce.md +106 -0
  266. package/skills/browser-navigation.md +110 -0
  267. package/skills/commerce-setup-guide.md +116 -0
  268. package/skills/commerce-setup.md +84 -0
  269. package/skills/configure-dev-tools.md +81 -0
  270. package/skills/travel-planning.md +138 -0
  271. package/AdoptionSpecialist.ouro/agent.json +0 -20
  272. package/AdoptionSpecialist.ouro/psyche/identities/python.md +0 -1
  273. package/dist/heart/daemon/subagent-installer.js +0 -125
  274. package/dist/inner-worker-entry.js +0 -4
  275. package/subagents/README.md +0 -73
  276. package/subagents/work-doer.md +0 -233
  277. package/subagents/work-merger.md +0 -624
  278. package/subagents/work-planner.md +0 -373
  279. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/basilisk.md +0 -0
  280. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jafar.md +0 -0
  281. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jormungandr.md +0 -0
  282. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/kaa.md +0 -0
  283. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/medusa.md +0 -0
  284. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/nagini.md +0 -0
  285. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/ouroboros.md +0 -0
  286. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/quetzalcoatl.md +0 -0
  287. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/sir-hiss.md +0 -0
  288. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-serpent.md +0 -0
  289. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-snake.md +0 -0
@@ -33,11 +33,20 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.MarkdownStreamer = exports.InputController = exports.Spinner = void 0;
36
+ exports.InputQueue = exports.MarkdownStreamer = exports.InputController = exports.Spinner = exports.StreamingWordWrapper = exports.wrapCliText = exports.formatEchoedInputSummary = void 0;
37
+ exports.formatPendingPrefix = formatPendingPrefix;
38
+ exports.getCliContinuityIngressTexts = getCliContinuityIngressTexts;
39
+ exports.formatTimeAgo = formatTimeAgo;
40
+ exports.writeCliAsyncAssistantMessage = writeCliAsyncAssistantMessage;
41
+ exports.pauseActiveSpinner = pauseActiveSpinner;
42
+ exports.resumeActiveSpinner = resumeActiveSpinner;
43
+ exports.setActiveSpinner = setActiveSpinner;
37
44
  exports.handleSigint = handleSigint;
38
45
  exports.addHistory = addHistory;
39
46
  exports.renderMarkdown = renderMarkdown;
40
47
  exports.createCliCallbacks = createCliCallbacks;
48
+ exports.createDebouncedLines = createDebouncedLines;
49
+ exports.runCliSession = runCliSession;
41
50
  exports.main = main;
42
51
  const readline = __importStar(require("readline"));
43
52
  const os = __importStar(require("os"));
@@ -49,9 +58,9 @@ const format_1 = require("../mind/format");
49
58
  const config_1 = require("../heart/config");
50
59
  const context_1 = require("../mind/context");
51
60
  const pending_1 = require("../mind/pending");
52
- const prompt_refresh_1 = require("../mind/prompt-refresh");
53
61
  const commands_1 = require("./commands");
54
62
  const identity_1 = require("../heart/identity");
63
+ const mcp_manager_1 = require("../repertoire/mcp-manager");
55
64
  const nerves_1 = require("../nerves");
56
65
  const store_file_1 = require("../mind/friends/store-file");
57
66
  const resolver_1 = require("../mind/friends/resolver");
@@ -59,59 +68,78 @@ const tokens_1 = require("../mind/friends/tokens");
59
68
  const cli_logging_1 = require("../nerves/cli-logging");
60
69
  const runtime_1 = require("../nerves/runtime");
61
70
  const trust_gate_1 = require("./trust-gate");
71
+ const pipeline_1 = require("./pipeline");
72
+ const channel_1 = require("../mind/friends/channel");
62
73
  const session_lock_1 = require("./session-lock");
63
- // spinner that only touches stderr, cleans up after itself
64
- // exported for direct testability (stop-without-start branch)
65
- class Spinner {
66
- frames = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
67
- i = 0;
68
- iv = null;
69
- piv = null;
70
- msg = "";
71
- phrases = null;
72
- lastPhrase = "";
73
- constructor(m = "working", phrases) {
74
- this.msg = m;
75
- if (phrases && phrases.length > 0)
76
- this.phrases = phrases;
77
- }
78
- start() {
79
- process.stderr.write("\r\x1b[K");
80
- this.spin();
81
- this.iv = setInterval(() => this.spin(), 80);
82
- if (this.phrases) {
83
- this.piv = setInterval(() => this.rotatePhrase(), 1500);
84
- }
85
- }
86
- spin() {
87
- process.stderr.write(`\r${this.frames[this.i]} ${this.msg}... `);
88
- this.i = (this.i + 1) % this.frames.length;
89
- }
90
- rotatePhrase() {
91
- const next = (0, phrases_1.pickPhrase)(this.phrases, this.lastPhrase);
92
- this.lastPhrase = next;
93
- this.msg = next;
94
- }
95
- stop(ok) {
96
- if (this.iv) {
97
- clearInterval(this.iv);
98
- this.iv = null;
99
- }
100
- if (this.piv) {
101
- clearInterval(this.piv);
102
- this.piv = null;
103
- }
104
- process.stderr.write("\r\x1b[K");
105
- /* v8 ignore next -- ok parameter currently unused by callers @preserve */
106
- if (ok)
107
- process.stderr.write(`\x1b[32m\u2713\x1b[0m ${ok}\n`);
108
- }
109
- fail(msg) {
110
- this.stop();
111
- process.stderr.write(`\x1b[31m\u2717\x1b[0m ${msg}\n`);
74
+ const update_hooks_1 = require("../heart/versioning/update-hooks");
75
+ const bundle_meta_1 = require("../heart/daemon/hooks/bundle-meta");
76
+ const agent_config_v2_1 = require("../heart/daemon/hooks/agent-config-v2");
77
+ const bundle_manifest_1 = require("../mind/bundle-manifest");
78
+ const cli_layout_1 = require("./cli-layout");
79
+ const image_paste_1 = require("./cli/image-paste");
80
+ const spinner_imperative_1 = require("./cli/spinner-imperative");
81
+ const tool_display_1 = require("./cli/tool-display");
82
+ var cli_layout_2 = require("./cli-layout");
83
+ Object.defineProperty(exports, "formatEchoedInputSummary", { enumerable: true, get: function () { return cli_layout_2.formatEchoedInputSummary; } });
84
+ Object.defineProperty(exports, "wrapCliText", { enumerable: true, get: function () { return cli_layout_2.wrapCliText; } });
85
+ Object.defineProperty(exports, "StreamingWordWrapper", { enumerable: true, get: function () { return cli_layout_2.StreamingWordWrapper; } });
86
+ /**
87
+ * Format pending messages as content-prefix strings for injection into
88
+ * the next user message. Self-messages (from === agentName) become
89
+ * `[inner thought: {content}]`, inter-agent messages become
90
+ * `[message from {name}: {content}]`.
91
+ */
92
+ function formatPendingPrefix(messages, agentName) {
93
+ return messages
94
+ .map((msg) => msg.from === agentName
95
+ ? `[inner thought: ${msg.content}]`
96
+ : `[message from ${msg.from}: ${msg.content}]`)
97
+ .join("\n");
98
+ }
99
+ function getCliContinuityIngressTexts(input) {
100
+ const trimmed = input.trim();
101
+ return trimmed ? [trimmed] : [];
102
+ }
103
+ /* v8 ignore start -- cosmetic time formatting @preserve */
104
+ function formatTimeAgo(date) {
105
+ const seconds = Math.floor((Date.now() - date.getTime()) / 1000);
106
+ if (seconds < 60)
107
+ return "just now";
108
+ const minutes = Math.floor(seconds / 60);
109
+ if (minutes < 60)
110
+ return `${minutes}m ago`;
111
+ const hours = Math.floor(minutes / 60);
112
+ if (hours < 24)
113
+ return `${hours}h ago`;
114
+ const days = Math.floor(hours / 24);
115
+ return `${days}d ago`;
116
+ }
117
+ const CLI_PROMPT = "\x1b[36m) \x1b[0m";
118
+ function writeCliAsyncAssistantMessage(rl, message, stdout = process.stdout) {
119
+ const rlInt = rl;
120
+ const currentLine = rlInt.line ?? "";
121
+ const currentCursor = rlInt.cursor ?? currentLine.length;
122
+ stdout.write("\r\x1b[K");
123
+ stdout.write(`${renderMarkdown(message)}\n`);
124
+ stdout.write(CLI_PROMPT);
125
+ if (!currentLine)
126
+ return;
127
+ stdout.write(currentLine);
128
+ if (currentCursor < currentLine.length) {
129
+ readline.cursorTo(process.stdout, 2 + currentCursor);
112
130
  }
113
131
  }
114
- exports.Spinner = Spinner;
132
+ // Module-level active spinner for log coordination.
133
+ // The terminal log sink calls these to avoid interleaving with spinner output.
134
+ let _activeSpinner = null;
135
+ /* v8 ignore start -- spinner coordination: exercised at runtime, not unit-testable without real terminal @preserve */
136
+ function pauseActiveSpinner() { _activeSpinner?.pause(); }
137
+ function resumeActiveSpinner() { _activeSpinner?.resume(); }
138
+ /* v8 ignore stop */
139
+ function setActiveSpinner(s) { _activeSpinner = s; }
140
+ // Re-export ImperativeSpinner as Spinner for backward compatibility
141
+ var spinner_imperative_2 = require("./cli/spinner-imperative");
142
+ Object.defineProperty(exports, "Spinner", { enumerable: true, get: function () { return spinner_imperative_2.ImperativeSpinner; } });
115
143
  // Input controller: pauses readline during model/tool execution.
116
144
  // Does NOT touch raw mode — readline with terminal:true manages raw mode
117
145
  // internally. Touching it causes ^C to be echoed by the terminal driver.
@@ -279,41 +307,54 @@ function createCliCallbacks() {
279
307
  meta: {},
280
308
  });
281
309
  let currentSpinner = null;
282
- let hadReasoning = false;
310
+ function setSpinner(s) { currentSpinner = s; setActiveSpinner(s); }
283
311
  let hadToolRun = false;
284
312
  let textDirty = false; // true when text/reasoning was written without a trailing newline
285
313
  const streamer = new MarkdownStreamer();
314
+ const wrapper = new cli_layout_1.StreamingWordWrapper();
286
315
  return {
287
316
  onModelStart: () => {
288
317
  currentSpinner?.stop();
289
- currentSpinner = null;
290
- hadReasoning = false;
318
+ setSpinner(null);
291
319
  textDirty = false;
292
320
  streamer.reset();
321
+ wrapper.reset();
293
322
  const phrases = (0, phrases_1.getPhrases)();
294
323
  const pool = hadToolRun ? phrases.followup : phrases.thinking;
295
324
  const first = (0, phrases_1.pickPhrase)(pool);
296
- currentSpinner = new Spinner(first, pool);
325
+ setSpinner(new spinner_imperative_1.ImperativeSpinner(first, pool));
297
326
  currentSpinner.start();
298
327
  },
299
328
  onModelStreamStart: () => {
300
- currentSpinner?.stop();
301
- currentSpinner = null;
329
+ // No-op: content callbacks (onTextChunk, onReasoningChunk) handle
330
+ // stopping the spinner. onModelStreamStart fires too early and
331
+ // doesn't fire at all for settle tool streaming.
332
+ },
333
+ onClearText: () => {
334
+ streamer.reset();
335
+ wrapper.reset();
302
336
  },
303
337
  onTextChunk: (text) => {
304
- if (hadReasoning) {
305
- process.stdout.write("\n\n");
306
- hadReasoning = false;
338
+ // Stop spinner if still running — settle streaming and Anthropic
339
+ // tool-only responses bypass onModelStreamStart, so the spinner would
340
+ // otherwise keep running (and its \r writes overwrite response text).
341
+ if (currentSpinner) {
342
+ currentSpinner.stop();
343
+ setSpinner(null);
307
344
  }
308
345
  const rendered = streamer.push(text);
309
- if (rendered)
310
- process.stdout.write(rendered);
346
+ /* v8 ignore start -- wrapper integration: tested via cli.test.ts onTextChunk tests @preserve */
347
+ if (rendered) {
348
+ const wrapped = wrapper.push(rendered);
349
+ if (wrapped)
350
+ process.stdout.write(wrapped);
351
+ }
352
+ /* v8 ignore stop */
311
353
  textDirty = text.length > 0 && !text.endsWith("\n");
312
354
  },
313
- onReasoningChunk: (text) => {
314
- hadReasoning = true;
315
- process.stdout.write(`\x1b[2m${text}\x1b[0m`);
316
- textDirty = text.length > 0 && !text.endsWith("\n");
355
+ onReasoningChunk: (_text) => {
356
+ // Keep reasoning private in the CLI surface. The spinner continues to
357
+ // represent active thinking until actual tool or answer output arrives.
317
358
  },
318
359
  onToolStart: (_name, _args) => {
319
360
  // Stop the model-start spinner: when the model returns only tool calls
@@ -328,31 +369,29 @@ function createCliCallbacks() {
328
369
  }
329
370
  const toolPhrases = (0, phrases_1.getPhrases)().tool;
330
371
  const first = (0, phrases_1.pickPhrase)(toolPhrases);
331
- currentSpinner = new Spinner(first, toolPhrases);
372
+ setSpinner(new spinner_imperative_1.ImperativeSpinner(first, toolPhrases));
332
373
  currentSpinner.start();
333
374
  hadToolRun = true;
334
375
  },
335
376
  onToolEnd: (name, argSummary, success) => {
336
377
  currentSpinner?.stop();
337
- currentSpinner = null;
338
- const msg = (0, format_1.formatToolResult)(name, argSummary, success);
339
- const color = success ? "\x1b[32m" : "\x1b[31m";
340
- process.stderr.write(`${color}${msg}\x1b[0m\n`);
378
+ setSpinner(null);
379
+ (0, tool_display_1.writeToolEnd)(name, argSummary, success);
341
380
  },
342
381
  onError: (error, severity) => {
343
382
  if (severity === "transient") {
344
383
  currentSpinner?.fail(error.message);
345
- currentSpinner = null;
384
+ setSpinner(null);
346
385
  }
347
386
  else {
348
387
  currentSpinner?.stop();
349
- currentSpinner = null;
388
+ setSpinner(null);
350
389
  process.stderr.write(`\x1b[31m${(0, format_1.formatError)(error)}\x1b[0m\n`);
351
390
  }
352
391
  },
353
392
  onKick: () => {
354
393
  currentSpinner?.stop();
355
- currentSpinner = null;
394
+ setSpinner(null);
356
395
  if (textDirty) {
357
396
  process.stdout.write("\n");
358
397
  textDirty = false;
@@ -361,27 +400,561 @@ function createCliCallbacks() {
361
400
  },
362
401
  flushMarkdown: () => {
363
402
  currentSpinner?.stop();
364
- currentSpinner = null;
403
+ setSpinner(null);
404
+ /* v8 ignore start -- wrapper flush: tested via cli.test.ts flushMarkdown tests @preserve */
365
405
  const remaining = streamer.flush();
366
- if (remaining)
367
- process.stdout.write(remaining);
406
+ if (remaining) {
407
+ const wrapped = wrapper.push(remaining);
408
+ if (wrapped)
409
+ process.stdout.write(wrapped);
410
+ }
411
+ const tail = wrapper.flush();
412
+ if (tail)
413
+ process.stdout.write(tail);
414
+ /* v8 ignore stop */
415
+ },
416
+ };
417
+ }
418
+ // Debounced line iterator: collects rapid-fire lines (paste) into a single input.
419
+ // When the debounce timeout wins the race, the pending iter.next() is saved
420
+ // and reused in the next iteration to prevent it from silently consuming input.
421
+ async function* createDebouncedLines(source, debounceMs) {
422
+ if (debounceMs <= 0) {
423
+ yield* source;
424
+ return;
425
+ }
426
+ const iter = source[Symbol.asyncIterator]();
427
+ let pending = null;
428
+ while (true) {
429
+ const first = pending ? await pending : await iter.next();
430
+ pending = null;
431
+ if (first.done)
432
+ break;
433
+ const lines = [first.value];
434
+ let more = true;
435
+ while (more) {
436
+ const nextPromise = iter.next();
437
+ const raced = await Promise.race([
438
+ nextPromise.then((r) => ({ kind: "line", result: r })),
439
+ new Promise((r) => setTimeout(() => r({ kind: "timeout" }), debounceMs)),
440
+ ]);
441
+ if (raced.kind === "timeout") {
442
+ pending = nextPromise;
443
+ more = false;
444
+ }
445
+ else if (raced.result.done) {
446
+ more = false;
447
+ }
448
+ else {
449
+ lines.push(raced.result.value);
450
+ }
451
+ }
452
+ yield lines.join("\n");
453
+ }
454
+ }
455
+ /**
456
+ * Async queue that bridges push-based Ink input to pull-based async iteration.
457
+ * Input from Ink's onSubmit callback is pushed; the business logic loop awaits via for-await.
458
+ */
459
+ class InputQueue {
460
+ queue = [];
461
+ resolve = null;
462
+ done = false;
463
+ push(input) {
464
+ if (this.done)
465
+ return;
466
+ if (this.resolve) {
467
+ const r = this.resolve;
468
+ this.resolve = null;
469
+ r({ value: input, done: false });
470
+ }
471
+ else {
472
+ this.queue.push(input);
473
+ }
474
+ }
475
+ close() {
476
+ this.done = true;
477
+ if (this.resolve) {
478
+ const r = this.resolve;
479
+ this.resolve = null;
480
+ r({ value: undefined, done: true });
481
+ }
482
+ }
483
+ /** Drain all buffered items, leaving any pending async awaiter untouched. */
484
+ drainAll() {
485
+ const items = [...this.queue];
486
+ this.queue = [];
487
+ return items;
488
+ }
489
+ [Symbol.asyncIterator]() {
490
+ return {
491
+ next: () => {
492
+ if (this.queue.length > 0) {
493
+ return Promise.resolve({ value: this.queue.shift(), done: false });
494
+ }
495
+ if (this.done) {
496
+ return Promise.resolve({ value: undefined, done: true });
497
+ }
498
+ return new Promise((resolve) => {
499
+ this.resolve = resolve;
500
+ });
501
+ },
502
+ };
503
+ }
504
+ }
505
+ exports.InputQueue = InputQueue;
506
+ async function runCliSession(options) {
507
+ /* v8 ignore start -- integration: runCliSession is interactive, tested via E2E @preserve */
508
+ const registry = (0, commands_1.createCommandRegistry)();
509
+ if (!options.disableCommands) {
510
+ (0, commands_1.registerDefaultCommands)(registry);
511
+ }
512
+ const messages = options.messages
513
+ ?? [{ role: "system", content: await (0, prompt_1.buildSystem)("cli") }];
514
+ // ─── Rendering: TUI (Ink + Static) for TTY, imperative for tests/pipes ───
515
+ const useTui = !options._testInputSource && process.stdin.isTTY === true;
516
+ let currentAbort = null;
517
+ let closed = false;
518
+ // eslint-disable-next-line prefer-const -- set by onImageMap callback during input
519
+ let pendingImages = null;
520
+ let cliCallbacks;
521
+ let tuiStore = null;
522
+ let inkRef = null;
523
+ const inputQueue = useTui ? new InputQueue() : null;
524
+ let rl = null;
525
+ if (useTui) {
526
+ try {
527
+ const [ink, React, tuiMod, storeMod] = await Promise.all([
528
+ Promise.resolve().then(() => __importStar(require("ink"))),
529
+ Promise.resolve().then(() => __importStar(require("react"))),
530
+ Promise.resolve().then(() => __importStar(require("./cli/ouro-tui"))),
531
+ Promise.resolve().then(() => __importStar(require("./cli/tui-store"))),
532
+ ]);
533
+ const { OuroTui } = tuiMod;
534
+ const { TuiStore, createTuiCallbacks } = storeMod;
535
+ tuiStore = new TuiStore();
536
+ cliCallbacks = createTuiCallbacks(tuiStore);
537
+ // Seed input history from previous session (for up/down arrows) — NOT display
538
+ const prevUserMsgs = messages
539
+ .filter((msg) => msg.role === "user" && typeof msg.content === "string")
540
+ .map(msg => msg.content);
541
+ tuiStore.seedHistory(prevUserMsgs);
542
+ // Show session resume context: last 2 exchanges as normal messages
543
+ if (messages.length > 1) {
544
+ const userAssistantMsgs = messages.filter((m) => (m.role === "user" || m.role === "assistant") && typeof m.content === "string" && m.content.trim().length > 0);
545
+ // Extract last 2 exchanges (up to 4 messages)
546
+ const lastExchanges = [];
547
+ for (let i = userAssistantMsgs.length - 1; i >= 0 && lastExchanges.length < 4; i--) {
548
+ lastExchanges.unshift({ role: userAssistantMsgs[i].role, content: userAssistantMsgs[i].content });
549
+ }
550
+ tuiStore.addResumeMessages(lastExchanges);
551
+ }
552
+ // Compute resumeInfo for header banner
553
+ const resumeInfo = messages.length > 1
554
+ ? {
555
+ messageCount: messages.filter(m => m.role === "user" || m.role === "assistant").length,
556
+ timeAgo: options.lastActivityAt ? formatTimeAgo(new Date(options.lastActivityAt)) : "unknown",
557
+ }
558
+ : undefined;
559
+ // Ctrl-C state machine (Claude Code behavior):
560
+ // During generation: abort current request
561
+ // Idle with text: clear input
562
+ // Idle empty (first): warn
563
+ // Idle empty (second): exit
564
+ let ctrlCWarned = false;
565
+ let ctrlCTimer = null;
566
+ const handleCtrlC = (hasInput) => {
567
+ if (currentAbort) {
568
+ currentAbort.abort();
569
+ ctrlCWarned = false;
570
+ return "abort";
571
+ }
572
+ if (hasInput) {
573
+ ctrlCWarned = false;
574
+ return "clear";
575
+ }
576
+ if (ctrlCWarned) {
577
+ ctrlCWarned = false;
578
+ if (ctrlCTimer) {
579
+ clearTimeout(ctrlCTimer);
580
+ ctrlCTimer = null;
581
+ }
582
+ closed = true;
583
+ inputQueue.close();
584
+ return "exit";
585
+ }
586
+ ctrlCWarned = true;
587
+ // Reset after 2 seconds — must press twice within window
588
+ ctrlCTimer = setTimeout(() => { ctrlCWarned = false; }, 2000);
589
+ return "warn";
590
+ };
591
+ // TUI root: subscribes to store, passes props to OuroTui
592
+ // Elapsed timer is local React state (no store.notify overhead)
593
+ const storeRef = tuiStore;
594
+ function TuiRoot() {
595
+ const [, forceUpdate] = React.useState(0);
596
+ const [elapsed, setElapsed] = React.useState(0);
597
+ React.useEffect(() => storeRef.subscribe(() => {
598
+ forceUpdate((n) => n + 1);
599
+ // Reset ctrlC warning on any state change (new turn, etc.)
600
+ }), []);
601
+ React.useEffect(() => {
602
+ const iv = setInterval(() => setElapsed(storeRef.getElapsed()), 1000);
603
+ return () => clearInterval(iv);
604
+ }, []);
605
+ return React.createElement(OuroTui, {
606
+ agentName: options.agentName,
607
+ model: (0, identity_1.loadAgentConfig)().humanFacing?.model ?? "",
608
+ completedMessages: storeRef.completedMessages,
609
+ inputHistory: storeRef.inputHistory,
610
+ queuedInputs: storeRef.queuedInputs,
611
+ live: storeRef.live,
612
+ elapsedSeconds: elapsed,
613
+ contextPercent: 0,
614
+ onSubmit: (text) => { ctrlCWarned = false; inputQueue.push(text); storeRef.enqueueInput(text); },
615
+ onCtrlC: handleCtrlC,
616
+ onPopQueue: () => { const items = storeRef.popAllQueuedForEditing(); inputQueue.drainAll(); return items; },
617
+ headerShown: storeRef.headerShown,
618
+ cwd: process.cwd().replace(process.env.HOME ?? "", "~"),
619
+ resumeInfo,
620
+ onImageMap: (images) => { pendingImages = images; },
621
+ onHistoryAdd: (text) => { storeRef.addToHistoryOnly(text); },
622
+ });
623
+ }
624
+ inkRef = ink.render(React.createElement(TuiRoot), { exitOnCtrlC: false, patchConsole: false });
625
+ }
626
+ catch (err) {
627
+ // Ink failed to load (CJS compat, missing deps, etc.) — fall through to imperative
628
+ (0, runtime_1.emitNervesEvent)({
629
+ component: "senses",
630
+ event: "senses.tui_fallback",
631
+ message: `TUI failed to load, falling back to imperative: ${err instanceof Error ? err.message : String(err)}`,
632
+ meta: {},
633
+ });
634
+ }
635
+ }
636
+ // Fallback to imperative callbacks if TUI didn't initialize
637
+ if (!tuiStore) {
638
+ cliCallbacks = createCliCallbacks();
639
+ if (options.banner !== false) {
640
+ const bannerText = typeof options.banner === "string"
641
+ ? options.banner
642
+ : `${options.agentName} (type /commands for help)`;
643
+ // eslint-disable-next-line no-console -- terminal UX: startup banner
644
+ console.log(`\n${bannerText}\n`);
645
+ }
646
+ }
647
+ // Display helpers: route to TUI store or imperative stderr/stdout
648
+ const display = {
649
+ error: (msg) => {
650
+ if (tuiStore)
651
+ tuiStore.setError(msg);
652
+ else
653
+ process.stderr.write(`\x1b[31m${msg}\x1b[0m\n`);
654
+ },
655
+ warn: (msg) => {
656
+ if (tuiStore)
657
+ tuiStore.setError(msg); // TUI shows warnings as errors (amber color handled in component)
658
+ else
659
+ process.stderr.write(`\x1b[33m${msg}\x1b[0m\n`);
660
+ },
661
+ text: (msg) => {
662
+ if (tuiStore)
663
+ tuiStore.appendText(msg);
664
+ else
665
+ process.stdout.write(`${msg}\n`);
666
+ },
667
+ suppressInput: () => {
668
+ if (tuiStore)
669
+ tuiStore.suppressInput();
670
+ },
671
+ restoreInput: () => {
672
+ if (tuiStore)
673
+ tuiStore.restoreInput();
368
674
  },
369
675
  };
676
+ const effectiveToolContext = {
677
+ signin: options.toolContext?.signin ?? (async () => undefined),
678
+ ...options.toolContext,
679
+ codingFeedback: {
680
+ send: async (message) => {
681
+ const assistantMessage = {
682
+ role: "assistant",
683
+ content: message,
684
+ };
685
+ messages.push(assistantMessage);
686
+ await options.onAsyncAssistantMessage?.(messages, assistantMessage);
687
+ display.text(message);
688
+ await options.toolContext?.codingFeedback?.send(message);
689
+ },
690
+ },
691
+ };
692
+ // exitOnToolCall machinery: wrap execTool to detect target tool
693
+ let exitToolResult;
694
+ let exitToolFired = false;
695
+ const resolvedExecTool = options.execTool;
696
+ const wrappedExecTool = options.exitOnToolCall && resolvedExecTool
697
+ ? async (name, args, ctx) => {
698
+ const result = await resolvedExecTool(name, args, ctx);
699
+ if (name === options.exitOnToolCall) {
700
+ exitToolResult = result;
701
+ exitToolFired = true;
702
+ currentAbort?.abort();
703
+ }
704
+ return result;
705
+ }
706
+ : resolvedExecTool;
707
+ // Resolve toolChoiceRequired: use explicit option if set, else fall back to toggle
708
+ const getEffectiveToolChoiceRequired = () => options.toolChoiceRequired !== undefined ? options.toolChoiceRequired : (0, commands_1.getToolChoiceRequired)();
709
+ (0, runtime_1.emitNervesEvent)({
710
+ component: "senses",
711
+ event: "senses.cli_session_start",
712
+ message: "runCliSession started",
713
+ meta: { agentName: options.agentName, hasExitOnToolCall: !!options.exitOnToolCall },
714
+ });
715
+ let exitReason = "user_quit";
716
+ // Auto-first-turn: process the last user message immediately so the agent
717
+ // speaks first (e.g. specialist greeting). Only triggers when explicitly opted in.
718
+ if (options.autoFirstTurn && messages.length > 0 && messages[messages.length - 1]?.role === "user") {
719
+ currentAbort = new AbortController();
720
+ const traceId = (0, nerves_1.createTraceId)();
721
+ display.suppressInput();
722
+ let result;
723
+ try {
724
+ result = await (0, core_1.runAgent)(messages, cliCallbacks, options.skipSystemPromptRefresh ? undefined : "cli", currentAbort.signal, {
725
+ toolChoiceRequired: getEffectiveToolChoiceRequired(),
726
+ traceId,
727
+ tools: options.tools,
728
+ execTool: wrappedExecTool,
729
+ toolContext: effectiveToolContext,
730
+ });
731
+ }
732
+ catch (err) {
733
+ if (!(err instanceof DOMException && err.name === "AbortError")) {
734
+ display.error(err instanceof Error ? err.message : String(err));
735
+ }
736
+ }
737
+ cliCallbacks.flushMarkdown();
738
+ display.restoreInput();
739
+ currentAbort = null;
740
+ if (exitToolFired) {
741
+ exitReason = "tool_exit";
742
+ closed = true;
743
+ }
744
+ else {
745
+ const lastMsg = messages[messages.length - 1];
746
+ if (lastMsg?.role === "assistant" && !(typeof lastMsg.content === "string" ? lastMsg.content : "").trim()) {
747
+ display.warn("(empty response)");
748
+ }
749
+ if (options.onTurnEnd) {
750
+ await options.onTurnEnd(messages, result ?? { usage: undefined });
751
+ }
752
+ }
753
+ }
754
+ try {
755
+ // Input source: TUI queue for Ink, test source for tests, readline fallback
756
+ let inputSource;
757
+ let inputCtrl = null;
758
+ if (tuiStore && inputQueue) {
759
+ // TUI path: input comes from Ink's onSubmit → InputQueue
760
+ inputSource = inputQueue;
761
+ }
762
+ else if (options._testInputSource) {
763
+ inputSource = options._testInputSource;
764
+ }
765
+ else {
766
+ // Imperative fallback: readline
767
+ const isTTY = process.stdin.isTTY === true;
768
+ rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: isTTY });
769
+ inputCtrl = new InputController(rl);
770
+ inputSource = rl;
771
+ process.stdout.write(CLI_PROMPT);
772
+ }
773
+ for await (const input of inputSource) {
774
+ if (closed)
775
+ break;
776
+ if (!input.trim())
777
+ continue;
778
+ // Remove from TUI queue display as the agent picks up this message
779
+ tuiStore?.dequeueInput(input);
780
+ // Optional input gate (e.g. trust gate in main)
781
+ if (options.onInput) {
782
+ const gate = options.onInput(input);
783
+ if (!gate.allowed) {
784
+ if (gate.reply) {
785
+ display.text(gate.reply);
786
+ }
787
+ if (closed)
788
+ break;
789
+ continue;
790
+ }
791
+ }
792
+ // Check for slash commands (legacy path only — pipeline handles commands for runTurn path)
793
+ if (!options.runTurn) {
794
+ const parsed = (0, commands_1.parseSlashCommand)(input);
795
+ if (parsed) {
796
+ const dispatchResult = registry.dispatch(parsed.command, { channel: "cli" });
797
+ if (dispatchResult.handled && dispatchResult.result) {
798
+ if (dispatchResult.result.action === "exit") {
799
+ break;
800
+ }
801
+ else if (dispatchResult.result.action === "new") {
802
+ messages.length = 0;
803
+ messages.push({ role: "system", content: await (0, prompt_1.buildSystem)("cli") });
804
+ await options.onNewSession?.();
805
+ // eslint-disable-next-line no-console -- terminal UX: session cleared
806
+ console.log("session cleared");
807
+ continue;
808
+ }
809
+ else if (dispatchResult.result.action === "response") {
810
+ display.text(dispatchResult.result.message || "");
811
+ continue;
812
+ }
813
+ }
814
+ }
815
+ }
816
+ // Track user message in TUI for display
817
+ if (tuiStore)
818
+ tuiStore.addUserMessage(input);
819
+ currentAbort = new AbortController();
820
+ if (tuiStore)
821
+ tuiStore.suppressInput();
822
+ inputCtrl?.suppress(() => { currentAbort?.abort(); });
823
+ // Resolve pending image content before the turn executes
824
+ let contentParts = null;
825
+ const currentImages = pendingImages;
826
+ if (currentImages && currentImages.size > 0) {
827
+ contentParts = await (0, image_paste_1.resolveImageContent)(input, currentImages);
828
+ pendingImages = null;
829
+ }
830
+ let result;
831
+ try {
832
+ if (options.runTurn) {
833
+ // Pipeline-based turn: the runTurn callback handles user message assembly,
834
+ // pending drain, trust gate, runAgent, postTurn, and token accumulation.
835
+ result = await options.runTurn(messages, input, cliCallbacks, currentAbort.signal, effectiveToolContext, contentParts ?? undefined);
836
+ // Handle pipeline-intercepted commands with loop-control side effects
837
+ if (result?.turnOutcome === "command") {
838
+ if (result.commandAction === "exit") {
839
+ break;
840
+ }
841
+ else if (result.commandAction === "new") {
842
+ messages.length = 0;
843
+ messages.push({ role: "system", content: await (0, prompt_1.buildSystem)("cli") });
844
+ await options.onNewSession?.();
845
+ // eslint-disable-next-line no-console -- terminal UX: session cleared
846
+ console.log("session cleared");
847
+ continue;
848
+ }
849
+ // For "response" commands: the pipeline already emitted the response via onTextChunk
850
+ cliCallbacks.flushMarkdown();
851
+ continue;
852
+ }
853
+ }
854
+ else {
855
+ // Legacy path: inline runAgent (used by serpent guide and tests)
856
+ const prefix = options.getContentPrefix?.();
857
+ const userContent = contentParts
858
+ ? contentParts
859
+ : (prefix ? `${prefix}\n\n${input}` : input);
860
+ messages.push({ role: "user", content: userContent });
861
+ const traceId = (0, nerves_1.createTraceId)();
862
+ result = await (0, core_1.runAgent)(messages, cliCallbacks, options.skipSystemPromptRefresh ? undefined : "cli", currentAbort.signal, {
863
+ toolChoiceRequired: getEffectiveToolChoiceRequired(),
864
+ traceId,
865
+ tools: options.tools,
866
+ execTool: wrappedExecTool,
867
+ toolContext: effectiveToolContext,
868
+ });
869
+ }
870
+ }
871
+ catch (err) {
872
+ if (!(err instanceof DOMException && err.name === "AbortError")) {
873
+ display.error(err instanceof Error ? err.message : String(err));
874
+ }
875
+ }
876
+ cliCallbacks.flushMarkdown();
877
+ if (!tuiStore)
878
+ process.stdout.write("\n"); // ensure response ends with newline before prompt (imperative only)
879
+ if (tuiStore)
880
+ tuiStore.restoreInput();
881
+ inputCtrl?.restore();
882
+ currentAbort = null;
883
+ // Check if exit tool was fired during this turn
884
+ if (exitToolFired) {
885
+ exitReason = "tool_exit";
886
+ break;
887
+ }
888
+ // Safety net: never silently swallow an empty response
889
+ const lastMsg = messages[messages.length - 1];
890
+ if (lastMsg?.role === "assistant" && !(typeof lastMsg.content === "string" ? lastMsg.content : "").trim()) {
891
+ display.warn("(empty response)");
892
+ }
893
+ // Post-turn hook (session persistence, pending drain, prompt refresh, etc.)
894
+ if (options.onTurnEnd) {
895
+ await options.onTurnEnd(messages, result ?? { usage: undefined });
896
+ }
897
+ if (closed)
898
+ break;
899
+ }
900
+ }
901
+ finally {
902
+ rl?.close();
903
+ if (inkRef) {
904
+ // Suppress React "state update on unmounted component" warnings during cleanup.
905
+ // Ink's useInput hook fires after unmount — this is harmless but noisy.
906
+ // This also covers the SerpentGuide exitOnToolCall path, which aborts the
907
+ // current request and breaks out of the loop into this finally block.
908
+ // eslint-disable-next-line no-console -- intentional console.warn/error override for cleanup
909
+ const origWarn = console.warn;
910
+ const origError = console.error; // eslint-disable-line no-console
911
+ // eslint-disable-next-line no-console -- suppress React unmount warnings
912
+ console.warn = (...args) => { if (typeof args[0] === "string" && args[0].includes("Can't perform a React state update"))
913
+ return; origWarn.apply(console, args); };
914
+ // eslint-disable-next-line no-console -- suppress React unmount warnings
915
+ console.error = (...args) => { if (typeof args[0] === "string" && args[0].includes("Can't perform a React state update"))
916
+ return; origError.apply(console, args); };
917
+ inkRef.unmount();
918
+ setTimeout(() => { console.warn = origWarn; console.error = origError; }, 100); // eslint-disable-line no-console
919
+ }
920
+ if (options.banner !== false) {
921
+ // eslint-disable-next-line no-console -- terminal UX: goodbye
922
+ console.log("bye");
923
+ }
924
+ }
925
+ /* v8 ignore stop */
926
+ return { exitReason, toolResult: exitToolResult };
370
927
  }
371
928
  async function main(agentName, options) {
372
929
  if (agentName)
373
930
  (0, identity_1.setAgentName)(agentName);
374
931
  const pasteDebounceMs = options?.pasteDebounceMs ?? 50;
932
+ // Safety net: process-level SIGINT handler ensures Ctrl+C always exits,
933
+ // even when Ink's event loop is blocked by expensive renders.
934
+ /* v8 ignore start -- process signal handler @preserve */
935
+ let sigintCount = 0;
936
+ const sigintHandler = () => {
937
+ sigintCount++;
938
+ if (sigintCount >= 2)
939
+ process.exit(1);
940
+ };
941
+ if (!options?._testInputSource) {
942
+ process.on("SIGINT", sigintHandler);
943
+ }
944
+ /* v8 ignore stop */
945
+ // Register spinner hooks so log output clears the spinner before printing
946
+ (0, nerves_1.registerSpinnerHooks)(pauseActiveSpinner, resumeActiveSpinner);
947
+ // Fallback: apply pending updates for daemon-less direct CLI usage
948
+ (0, update_hooks_1.registerUpdateHook)(bundle_meta_1.bundleMetaHook);
949
+ (0, update_hooks_1.registerUpdateHook)(agent_config_v2_1.agentConfigV2Hook);
950
+ await (0, update_hooks_1.applyPendingUpdates)((0, identity_1.getAgentBundlesRoot)(), (0, bundle_manifest_1.getPackageVersion)());
375
951
  // Fail fast if provider is misconfigured (triggers human-readable error + exit)
376
- (0, core_1.getProvider)();
377
- const registry = (0, commands_1.createCommandRegistry)();
378
- (0, commands_1.registerDefaultCommands)(registry);
952
+ (0, core_1.getProvider)("human");
379
953
  // Resolve context kernel (identity + channel) for CLI
380
954
  const friendsPath = path.join((0, identity_1.getAgentRoot)(), "friends");
381
955
  const friendStore = new store_file_1.FileFriendStore(friendsPath);
382
956
  const username = os.userInfo().username;
383
- const hostname = os.hostname();
384
- const localExternalId = `${username}@${hostname}`;
957
+ const localExternalId = username;
385
958
  const resolver = new resolver_1.FriendResolver(friendStore, {
386
959
  provider: "local",
387
960
  externalId: localExternalId,
@@ -389,13 +962,6 @@ async function main(agentName, options) {
389
962
  channel: "cli",
390
963
  });
391
964
  const resolvedContext = await resolver.resolve();
392
- const cliToolContext = {
393
- /* v8 ignore next -- CLI has no OAuth sign-in; this no-op satisfies the interface @preserve */
394
- signin: async () => undefined,
395
- context: resolvedContext,
396
- friendStore,
397
- summarize: (0, core_1.createSummarize)(),
398
- };
399
965
  const friendId = resolvedContext.friend.id;
400
966
  const agentConfig = (0, identity_1.loadAgentConfig)();
401
967
  (0, cli_logging_1.configureCliRuntimeLogger)(friendId, {
@@ -418,187 +984,129 @@ async function main(agentName, options) {
418
984
  }
419
985
  // Load existing session or start fresh
420
986
  const existing = (0, context_1.loadSession)(sessPath);
421
- const messages = existing?.messages && existing.messages.length > 0
987
+ let sessionState = existing?.state;
988
+ const mcpManager = await (0, mcp_manager_1.getSharedMcpManager)() ?? undefined;
989
+ const sessionMessages = existing?.messages && existing.messages.length > 0
422
990
  ? existing.messages
423
- : [{ role: "system", content: await (0, prompt_1.buildSystem)("cli", undefined, resolvedContext) }];
424
- // Pending queue drain: inject pending messages as harness-context + assistant-content pairs
425
- const pendingDir = (0, pending_1.getPendingDir)((0, identity_1.getAgentName)(), friendId, "cli", "session");
426
- const drainToMessages = () => {
427
- const pending = (0, pending_1.drainPending)(pendingDir);
428
- if (pending.length === 0)
429
- return 0;
430
- for (const msg of pending) {
431
- messages.push({ role: "user", name: "harness", content: `[proactive message from ${msg.from}]` });
432
- messages.push({ role: "assistant", content: msg.content });
433
- }
434
- return pending.length;
435
- };
436
- // Startup drain: deliver offline messages
437
- const startupCount = drainToMessages();
438
- if (startupCount > 0) {
439
- (0, context_1.saveSession)(sessPath, messages);
440
- }
441
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: true });
442
- const ctrl = new InputController(rl);
443
- let currentAbort = null;
444
- const history = [];
445
- let closed = false;
446
- rl.on("close", () => { closed = true; });
447
- // eslint-disable-next-line no-console -- terminal UX: startup banner
448
- console.log(`\n${(0, identity_1.getAgentName)()} (type /commands for help)\n`);
449
- const cliCallbacks = createCliCallbacks();
450
- process.stdout.write("\x1b[36m> \x1b[0m");
451
- // Ctrl-C at the input prompt: clear line or warn/exit
452
- // readline with terminal:true catches Ctrl-C in raw mode (no ^C echo)
453
- rl.on("SIGINT", () => {
454
- const rlInt = rl;
455
- const currentLine = rlInt.line || "";
456
- const result = handleSigint(rl, currentLine);
457
- if (result === "clear") {
458
- rlInt.line = "";
459
- rlInt.cursor = 0;
460
- process.stdout.write("\r\x1b[K\x1b[36m> \x1b[0m");
461
- }
462
- else if (result === "warn") {
463
- rlInt.line = "";
464
- rlInt.cursor = 0;
465
- process.stdout.write("\r\x1b[K");
466
- process.stderr.write("press Ctrl-C again to exit\n");
467
- process.stdout.write("\x1b[36m> \x1b[0m");
468
- }
469
- else {
470
- rl.close();
471
- }
472
- });
473
- // Debounced line iterator: collects rapid-fire lines (paste) into a single input
474
- async function* debouncedLines(source) {
475
- if (pasteDebounceMs <= 0) {
476
- yield* source;
477
- return;
478
- }
479
- const iter = source[Symbol.asyncIterator]();
480
- while (true) {
481
- const first = await iter.next();
482
- if (first.done)
483
- break;
484
- // Collect any lines that arrive within the debounce window (paste detection)
485
- const lines = [first.value];
486
- let more = true;
487
- while (more) {
488
- const raced = await Promise.race([
489
- iter.next().then((r) => ({ kind: "line", result: r })),
490
- new Promise((r) => setTimeout(() => r({ kind: "timeout" }), pasteDebounceMs)),
491
- ]);
492
- if (raced.kind === "timeout") {
493
- more = false;
494
- }
495
- else if (raced.result.done) {
496
- more = false;
497
- }
498
- else {
499
- lines.push(raced.result.value);
500
- }
501
- }
502
- yield lines.join("\n");
503
- }
504
- }
991
+ : [{ role: "system", content: await (0, prompt_1.buildSystem)("cli", {}, resolvedContext) }];
992
+ // Repair any orphaned tool calls from a crash mid-turn
993
+ (0, core_1.repairOrphanedToolCalls)(sessionMessages);
994
+ // Per-turn pipeline input: CLI capabilities and pending dir
995
+ const cliCapabilities = (0, channel_1.getChannelCapabilities)("cli");
996
+ const currentAgentName = (0, identity_1.getAgentName)();
997
+ const pendingDir = (0, pending_1.getPendingDir)(currentAgentName, friendId, "cli", "session");
998
+ const summarize = (0, core_1.createSummarize)("human");
999
+ const cliFailoverState = { pending: null };
505
1000
  try {
506
- for await (const input of debouncedLines(rl)) {
507
- if (closed)
508
- break;
509
- if (!input.trim()) {
510
- process.stdout.write("\x1b[36m> \x1b[0m");
511
- continue;
512
- }
513
- const trustGate = (0, trust_gate_1.enforceTrustGate)({
514
- friend: resolvedContext.friend,
515
- provider: "local",
516
- externalId: localExternalId,
517
- channel: "cli",
518
- });
519
- if (!trustGate.allowed) {
520
- if (trustGate.reason === "stranger_first_reply") {
521
- process.stdout.write(`${trustGate.autoReply}\n`);
1001
+ await runCliSession({
1002
+ agentName: currentAgentName,
1003
+ pasteDebounceMs,
1004
+ messages: sessionMessages,
1005
+ lastActivityAt: sessionState?.lastFriendActivityAt,
1006
+ _testInputSource: options?._testInputSource,
1007
+ onAsyncAssistantMessage: async (messages, _assistantMessage) => {
1008
+ (0, context_1.postTurn)(messages, sessPath, undefined, undefined, sessionState);
1009
+ },
1010
+ runTurn: async (messages, userInput, callbacks, signal, toolContext, userContent) => {
1011
+ // Run the full per-turn pipeline: resolve -> gate -> session -> drain -> runAgent -> postTurn -> tokens
1012
+ // User message passed via input.messages so the pipeline can prepend pending messages to it.
1013
+ const failoverState = cliFailoverState;
1014
+ // Capture terminal errors instead of displaying immediately — the failover
1015
+ // message replaces the raw error if failover triggers successfully.
1016
+ let capturedTerminalError = null;
1017
+ /* v8 ignore start -- failover-aware callback wrapper: tested via pipeline integration @preserve */
1018
+ const failoverAwareCallbacks = {
1019
+ ...callbacks,
1020
+ // Save session after each tool result for crash recovery
1021
+ onToolResult: (turnMessages) => {
1022
+ (0, context_1.postTurn)(turnMessages, sessPath, undefined, undefined, sessionState);
1023
+ },
1024
+ onError: (error, severity) => {
1025
+ if (severity === "terminal" && failoverState) {
1026
+ capturedTerminalError = error;
1027
+ callbacks.onError(new Error(""), "transient");
1028
+ return;
1029
+ }
1030
+ callbacks.onError(error, severity);
1031
+ },
1032
+ };
1033
+ /* v8 ignore stop */
1034
+ const result = await (0, pipeline_1.handleInboundTurn)({
1035
+ channel: "cli",
1036
+ sessionKey: "session",
1037
+ capabilities: cliCapabilities,
1038
+ messages: [{ role: "user", content: userContent ?? userInput }],
1039
+ continuityIngressTexts: getCliContinuityIngressTexts(userInput),
1040
+ callbacks: failoverAwareCallbacks,
1041
+ friendResolver: { resolve: () => Promise.resolve(resolvedContext) },
1042
+ sessionLoader: {
1043
+ loadOrCreate: () => Promise.resolve({
1044
+ messages,
1045
+ sessionPath: sessPath,
1046
+ state: sessionState,
1047
+ }),
1048
+ },
1049
+ pendingDir,
1050
+ friendStore,
1051
+ provider: "local",
1052
+ externalId: localExternalId,
1053
+ enforceTrustGate: trust_gate_1.enforceTrustGate,
1054
+ drainPending: pending_1.drainPending,
1055
+ drainDeferredReturns: (deferredFriendId) => (0, pending_1.drainDeferredReturns)(currentAgentName, deferredFriendId),
1056
+ runAgent: (msgs, cb, channel, sig, opts) => (0, core_1.runAgent)(msgs, cb, channel, sig, {
1057
+ ...opts,
1058
+ toolContext: {
1059
+ /* v8 ignore next -- default no-op signin; pipeline provides the real one @preserve */
1060
+ signin: async () => undefined,
1061
+ ...opts?.toolContext,
1062
+ summarize,
1063
+ },
1064
+ }),
1065
+ postTurn: (turnMessages, sessionPathArg, usage, hooks, state) => {
1066
+ (0, context_1.postTurn)(turnMessages, sessionPathArg, usage, hooks, state);
1067
+ sessionState = state;
1068
+ },
1069
+ accumulateFriendTokens: tokens_1.accumulateFriendTokens,
1070
+ signal,
1071
+ runAgentOptions: {
1072
+ toolChoiceRequired: (0, commands_1.getToolChoiceRequired)(),
1073
+ traceId: (0, nerves_1.createTraceId)(),
1074
+ mcpManager,
1075
+ toolContext,
1076
+ },
1077
+ failoverState,
1078
+ });
1079
+ /* v8 ignore start -- failover display: tested via pipeline integration tests @preserve */
1080
+ if (result.failoverMessage) {
1081
+ // Failover handled it — show the actionable message instead of the raw error
1082
+ process.stdout.write(`\x1b[33m${result.failoverMessage}\x1b[0m\n`);
522
1083
  }
523
- if (closed)
524
- break;
525
- process.stdout.write("\x1b[36m> \x1b[0m");
526
- continue;
527
- }
528
- // Check for slash commands
529
- const parsed = (0, commands_1.parseSlashCommand)(input);
530
- if (parsed) {
531
- const dispatchResult = registry.dispatch(parsed.command, { channel: "cli" });
532
- if (dispatchResult.handled && dispatchResult.result) {
533
- if (dispatchResult.result.action === "exit") {
534
- break;
535
- }
536
- else if (dispatchResult.result.action === "new") {
537
- messages.length = 0;
538
- messages.push({ role: "system", content: await (0, prompt_1.buildSystem)("cli") });
539
- (0, context_1.deleteSession)(sessPath);
540
- // eslint-disable-next-line no-console -- terminal UX: session cleared
541
- console.log("session cleared");
542
- process.stdout.write("\x1b[36m> \x1b[0m");
543
- continue;
544
- }
545
- else if (dispatchResult.result.action === "response") {
546
- // eslint-disable-next-line no-console -- terminal UX: command dispatch result
547
- console.log(dispatchResult.result.message || "");
548
- process.stdout.write("\x1b[36m> \x1b[0m");
549
- continue;
1084
+ else if (capturedTerminalError) {
1085
+ // Failover didn't trigger (no failoverState, or sequence failed) — show the raw error
1086
+ process.stderr.write(`\x1b[31m${(0, format_1.formatError)(capturedTerminalError)}\x1b[0m\n`);
1087
+ }
1088
+ /* v8 ignore stop */
1089
+ // Handle gate rejection: display auto-reply if present
1090
+ if (!result.gateResult.allowed) {
1091
+ if ("autoReply" in result.gateResult && result.gateResult.autoReply) {
1092
+ process.stdout.write(`${result.gateResult.autoReply}\n`);
550
1093
  }
551
1094
  }
552
- }
553
- // Re-style the echoed input lines (readline terminal:true echoes each line)
554
- // For multiline paste, each line was echoed separately — erase them all
555
- const cols = process.stdout.columns || 80;
556
- const inputLines = input.split("\n");
557
- let echoRows = 0;
558
- for (const line of inputLines) {
559
- echoRows += Math.ceil((2 + line.length) / cols); // "> " prefix + line content
560
- }
561
- process.stdout.write(`\x1b[${echoRows}A\x1b[K` + `\x1b[1m> ${inputLines[0]}${inputLines.length > 1 ? ` (+${inputLines.length - 1} lines)` : ""}\x1b[0m\n\n`);
562
- messages.push({ role: "user", content: input });
563
- addHistory(history, input);
564
- currentAbort = new AbortController();
565
- const traceId = (0, nerves_1.createTraceId)();
566
- ctrl.suppress(() => currentAbort.abort());
567
- let result;
568
- try {
569
- result = await (0, core_1.runAgent)(messages, cliCallbacks, "cli", currentAbort.signal, {
570
- toolChoiceRequired: (0, commands_1.getToolChoiceRequired)(),
571
- toolContext: cliToolContext,
572
- traceId,
573
- });
574
- }
575
- catch {
576
- // AbortError — silently return to prompt
577
- }
578
- cliCallbacks.flushMarkdown();
579
- ctrl.restore();
580
- currentAbort = null;
581
- // Safety net: never silently swallow an empty response
582
- const lastMsg = messages[messages.length - 1];
583
- if (lastMsg?.role === "assistant" && !(typeof lastMsg.content === "string" ? lastMsg.content : "").trim()) {
584
- process.stderr.write("\x1b[33m(empty response)\x1b[0m\n");
585
- }
586
- process.stdout.write("\n\n");
587
- (0, context_1.postTurn)(messages, sessPath, result?.usage);
588
- await (0, tokens_1.accumulateFriendTokens)(friendStore, resolvedContext.friend.id, result?.usage);
589
- // Post-turn: drain any pending messages that arrived during runAgent
590
- drainToMessages();
591
- // Post-turn: refresh system prompt so active sessions metadata is current
592
- await (0, prompt_refresh_1.refreshSystemPrompt)(messages, "cli", undefined, resolvedContext);
593
- if (closed)
594
- break;
595
- process.stdout.write("\x1b[36m> \x1b[0m");
596
- }
1095
+ return { usage: result.usage, turnOutcome: result.turnOutcome, commandAction: result.commandAction };
1096
+ },
1097
+ onNewSession: () => {
1098
+ (0, context_1.deleteSession)(sessPath);
1099
+ },
1100
+ });
597
1101
  }
598
1102
  finally {
599
1103
  sessionLock?.release();
600
- rl.close();
601
- // eslint-disable-next-line no-console -- terminal UX: goodbye
602
- console.log("bye");
603
1104
  }
1105
+ // Force exit: lingering handles (Ink cleanup timers, MCP connections) keep the
1106
+ // event loop alive after the interactive session ends. This is safe because all
1107
+ // session persistence has already completed in the finally block above.
1108
+ /* v8 ignore next -- process.exit not callable in vitest @preserve */
1109
+ if (!options?._testInputSource)
1110
+ process.exit(0);
604
1111
  }
1112
+ // CI trigger