@ouro.bot/cli 0.1.0-alpha.26 → 0.1.0-alpha.260

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