@carrieros/cli 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/README.md +142 -57
  2. package/dist/commands/attach.js +45 -0
  3. package/dist/commands/btw.js +78 -0
  4. package/dist/commands/changes.js +167 -0
  5. package/dist/commands/chat.js +80 -14
  6. package/dist/commands/context.js +160 -0
  7. package/dist/commands/doctor.js +46 -1
  8. package/dist/commands/files.js +84 -23
  9. package/dist/commands/help.js +1 -0
  10. package/dist/commands/history.js +88 -23
  11. package/dist/commands/login.js +31 -7
  12. package/dist/commands/memory.js +162 -0
  13. package/dist/commands/mode-model.js +39 -3
  14. package/dist/commands/modes.js +4 -1
  15. package/dist/commands/project.js +106 -0
  16. package/dist/commands/repo.js +146 -0
  17. package/dist/commands/repos.js +61 -0
  18. package/dist/commands/review.js +92 -0
  19. package/dist/commands/search.js +92 -0
  20. package/dist/commands/sessions.js +219 -65
  21. package/dist/commands/settings.js +87 -0
  22. package/dist/commands/update.js +159 -0
  23. package/dist/commands/upload.js +204 -31
  24. package/dist/commands/usage.js +212 -16
  25. package/dist/ide/editor-context.js +172 -0
  26. package/dist/ide/ide-session.js +94 -0
  27. package/dist/ide/tool-host.js +109 -0
  28. package/dist/main.js +26 -1
  29. package/dist/services/api.js +140 -6
  30. package/dist/services/chat-stream.js +145 -0
  31. package/dist/services/checkpoints.js +116 -0
  32. package/dist/services/client-tools.js +260 -0
  33. package/dist/services/command-coordinator.js +200 -0
  34. package/dist/services/command-policy.js +404 -0
  35. package/dist/services/config.js +247 -22
  36. package/dist/services/context.js +265 -20
  37. package/dist/services/device-auth.js +42 -30
  38. package/dist/services/diff.js +196 -0
  39. package/dist/services/env-policy.js +108 -0
  40. package/dist/services/file-detect.js +104 -0
  41. package/dist/services/file-resolver.js +199 -0
  42. package/dist/services/file-upload.js +126 -0
  43. package/dist/services/git-tools.js +248 -0
  44. package/dist/services/glob-match.js +164 -0
  45. package/dist/services/helper-bin.js +64 -0
  46. package/dist/services/ignore-rules.js +189 -0
  47. package/dist/services/job-helper.js +307 -0
  48. package/dist/services/local-files.js +517 -0
  49. package/dist/services/local-tools.js +432 -0
  50. package/dist/services/login-flow.js +15 -8
  51. package/dist/services/meta.js +3 -1
  52. package/dist/services/mutation-coordinator.js +161 -0
  53. package/dist/services/mutations.js +493 -0
  54. package/dist/services/open-url.js +68 -0
  55. package/dist/services/output.js +5 -2
  56. package/dist/services/packaged.js +24 -0
  57. package/dist/services/process-runner.js +406 -0
  58. package/dist/services/project-context.js +298 -0
  59. package/dist/services/redaction.js +201 -0
  60. package/dist/services/secure-store.js +197 -0
  61. package/dist/services/session-resolver.js +108 -0
  62. package/dist/services/sia.js +51 -0
  63. package/dist/services/update.js +286 -0
  64. package/dist/services/workspace-registry.js +309 -0
  65. package/dist/services/workspace.js +573 -0
  66. package/dist/shell/shell-chat.js +1028 -57
  67. package/dist/shell/shell-commands.js +200 -11
  68. package/dist/shell/shell-prompt.js +81 -8
  69. package/dist/shell/shell-renderer.js +7 -19
  70. package/dist/shell/shell-router.js +19 -3
  71. package/dist/shell/shell.js +185 -17
  72. package/dist/types/index.js +3 -1
  73. package/dist/ui/approval.js +81 -0
  74. package/dist/ui/banner.js +39 -0
  75. package/dist/ui/btw-overlay.js +230 -0
  76. package/dist/ui/change-review.js +87 -0
  77. package/dist/ui/chat-renderer.js +206 -13
  78. package/dist/ui/colors.js +4 -0
  79. package/dist/ui/command-filter.js +26 -5
  80. package/dist/ui/command-palette.js +17 -4
  81. package/dist/ui/command-registry.js +84 -9
  82. package/dist/ui/command-review.js +138 -0
  83. package/dist/ui/composer-layout.js +41 -0
  84. package/dist/ui/conversation.js +398 -0
  85. package/dist/ui/interrupt.js +35 -0
  86. package/dist/ui/live.js +3 -1
  87. package/dist/ui/markdown.js +63 -9
  88. package/dist/ui/message.js +14 -31
  89. package/dist/ui/screen-prompt.js +181 -0
  90. package/dist/ui/screen.js +1 -1
  91. package/dist/ui/select.js +185 -29
  92. package/dist/ui/sia-qa.js +213 -0
  93. package/dist/ui/text-prompt.js +74 -0
  94. package/dist/ui/trust.js +93 -0
  95. package/dist/ui/ui.js +4 -1
  96. package/package.json +13 -2
  97. package/dist/ui/activity.js +0 -77
@@ -7,10 +7,14 @@ import { renderWelcomeBanner } from "../ui/banner.js";
7
7
  import { renderExit } from "../ui/chat-renderer.js";
8
8
  import { c } from "../ui/colors.js";
9
9
  import { readCommand } from "../ui/command-palette.js";
10
+ import { setCommandScope } from "../ui/command-item.js";
10
11
  import { startScreen, stopScreen, screenScrollToBottom } from "../ui/screen.js";
11
- import { loadModels, loadModes } from "./shell-chat.js";
12
+ import { ensureWorkspaceTrust } from "../ui/trust.js";
13
+ import { activeRepository, inWorkspaceMode, listRepositories } from "../services/workspace-registry.js";
14
+ import { cachedUpdateNotice, refreshUpdateCache, shouldRefreshCheck } from "../services/update.js";
15
+ import { chatTypeLabel, loadModels, loadModes } from "./shell-chat.js";
12
16
  import { CARET, buildFooter } from "./shell-prompt.js";
13
- import { dispatchLine } from "./shell-router.js";
17
+ import { dispatchLine, isMainTurn } from "./shell-router.js";
14
18
  import { printWelcome, renderWelcomeBack } from "./shell-renderer.js";
15
19
  /**
16
20
  * The interactive Carrier OS shell — the default experience when you run
@@ -19,6 +23,12 @@ import { printWelcome, renderWelcomeBack } from "./shell-renderer.js";
19
23
  * through the same Commander program, so no logic is duplicated.
20
24
  */
21
25
  export async function runShell(ctx, program) {
26
+ // Safety check before anything touches the working directory — the shell
27
+ // uploads local files you reference by path. Asked once per repository: in a
28
+ // multi-repository workspace the folder holding them is NOT what gets
29
+ // trusted, because trusting it must never imply trusting its children.
30
+ if (!(await ensureWorkspaceTrust(ctx.config, activeRepository().root)))
31
+ return;
22
32
  // Returning users see the branded banner once; a fresh login already showed
23
33
  // the branding + scope in the welcome / auth-success screens, so we don't
24
34
  // repeat it after logging in.
@@ -29,10 +39,13 @@ export async function runShell(ctx, program) {
29
39
  return; // user chose /exit or Ctrl+C
30
40
  }
31
41
  const client = ctx.requireAuth();
32
- // The interactive shell always OPENS in the Carrier OS mode (the core persona)
33
- // — Carrier Chat by default, not the last standalone mode. Switch any time with
34
- // /mode; that applies for the session. The persisted default is left untouched.
35
- ctx.setSessionMode("general");
42
+ // Mark that we're inside the interactive shell — commands (e.g. upload) use
43
+ // this to prompt interactively here vs. print finish-and-return output when
44
+ // run standalone (cos upload).
45
+ ctx.setInShell(true);
46
+ // Mode is derived from the chat type (see CommandContext.mode): Carrier Chat
47
+ // always opens in General, Standard opens on its saved mode or Auto. Forcing
48
+ // General here would override that and strand Standard users in General.
36
49
  // Preload the mode + model lists so the prompt/banner can show friendly labels
37
50
  // (e.g. the "Carrier OS" mode name rather than the raw id).
38
51
  await Promise.all([loadModels(client).catch(() => []), loadModes(client).catch(() => [])]);
@@ -40,18 +53,39 @@ export async function runShell(ctx, program) {
40
53
  // transcript its own scrolling region above it (Claude-style). From here, all
41
54
  // output flows into the transcript via the screen engine.
42
55
  startScreen();
43
- if (returning) {
44
- // Branded startup banner (rendered once). Notices can be passed here later —
45
- // e.g. renderWelcomeBanner(ctx, { notices: ["Update available: v0.2.0"] }).
46
- renderWelcomeBanner(ctx);
47
- }
48
- else {
49
- // Just logged in — go straight to the shell with a slim hint (the prompt
50
- // already shows workspace / project / mode / model).
51
- line();
52
- line(" " + c.dim("Type ") + c.key("/help") + c.dim(" for available commands."));
56
+ // Branded startup banner (rendered once) — ALWAYS the first thing in the
57
+ // transcript, for returning users and fresh logins alike, so the lockup is
58
+ // always one scroll up from the composer (Claude-style). It can't be inherited
59
+ // from the onboarding screens: those were drawn on the real terminal, and
60
+ // startScreen() has since switched to the alternate buffer, which hides them.
61
+ // Update notice comes from the PREVIOUS check — reading the cache is a
62
+ // property lookup, so the banner is never waiting on npm.
63
+ const notice = cachedUpdateNotice(ctx.config);
64
+ renderWelcomeBanner(ctx, notice ? { notices: [notice] } : undefined);
65
+ if (inWorkspaceMode()) {
66
+ line(" " +
67
+ c.dim("Workspace with ") +
68
+ c.value(String(listRepositories().length)) +
69
+ c.dim(" repositories · active: ") +
70
+ c.value(activeRepository().name) +
71
+ c.dim(" · ") +
72
+ c.cmd("/repos") +
73
+ c.dim(" to switch"));
53
74
  }
54
75
  line();
76
+ // Refresh for NEXT launch, once a day, after the shell is already usable.
77
+ // setImmediate keeps the blocking npm call off the startup path; a failure is
78
+ // recorded and never shown.
79
+ if (shouldRefreshCheck(ctx.config)) {
80
+ setImmediate(() => {
81
+ try {
82
+ refreshUpdateCache(ctx.config);
83
+ }
84
+ catch {
85
+ /* never let an update check affect the session */
86
+ }
87
+ });
88
+ }
55
89
  // Interactive loop driven by the composer/reader. Each iteration reads one
56
90
  // line (with the slash palette overlay, the dim status footer, and a
57
91
  // placeholder inside the box), then dispatches it. Enter in the palette only
@@ -59,6 +93,57 @@ export async function runShell(ctx, program) {
59
93
  const history = [];
60
94
  let sigintArmed = false;
61
95
  let conversationStarted = false; // only the first empty session shows the full welcome
96
+ /**
97
+ * The main turn runs in the BACKGROUND so the composer keeps reading.
98
+ *
99
+ * Only one may be in flight — a second `/v1/chat` would be a second
100
+ * conversation turn, which is not what "let me type while it answers" means.
101
+ * Commands stay awaited as before; they are fast and sequential, and awaiting
102
+ * a `/btw` does not block the main turn because that is already detached.
103
+ */
104
+ let mainTask = null;
105
+ let mainAbort = null;
106
+ const mainRunning = () => mainTask !== null;
107
+ /**
108
+ * One message typed while a turn is still answering.
109
+ *
110
+ * A modern coding agent lets you line up the next thing to say instead of
111
+ * refusing it. Exactly one is held — the next turn is a real conversation
112
+ * turn, and stacking several would queue a pile of them behind an approval
113
+ * nobody is watching. It runs when the current turn finishes, and is dropped
114
+ * if that turn is cancelled (there is nothing to run it after).
115
+ */
116
+ let queued = null;
117
+ /**
118
+ * Start a main turn detached, and — when it finishes — drain any message the
119
+ * user queued while it ran. Recursive on purpose: the drained turn can itself
120
+ * have a message queued behind it.
121
+ */
122
+ const startMainTurn = (msg) => {
123
+ mainAbort = new AbortController();
124
+ ctx.mainTurnRunning = true;
125
+ const task = dispatchLine(ctx, program, client, msg, mainAbort.signal)
126
+ .catch(() => undefined)
127
+ .finally(() => {
128
+ if (mainTask === task) {
129
+ mainTask = null;
130
+ mainAbort = null;
131
+ ctx.mainTurnRunning = false;
132
+ if (queued !== null) {
133
+ const next = queued;
134
+ queued = null;
135
+ line(" " + c.dim("↳ Running the message you queued."));
136
+ startMainTurn(next);
137
+ }
138
+ }
139
+ });
140
+ mainTask = task;
141
+ };
142
+ /** Cancel the running turn, if any. In its own closure so the type of
143
+ * mainAbort is not narrowed away at the call sites. */
144
+ const cancelMainTurn = () => {
145
+ mainAbort?.abort();
146
+ };
62
147
  // Leaving the shell: restore cooked mode + a visible cursor (the reader keeps
63
148
  // raw mode on for the session), then print the farewell.
64
149
  const leave = () => {
@@ -73,12 +158,53 @@ export async function runShell(ctx, program) {
73
158
  // One Ctrl+C swaps the status footer for a dim "again to exit" hint beneath
74
159
  // the bar (no separate info line); a second Ctrl+C quits.
75
160
  const footer = sigintArmed ? " " + c.dim("Press Ctrl-C again to exit") : buildFooter(ctx);
161
+ // Keep the palette in step with the chat type — /switch mid-session must
162
+ // add or remove the commands that only apply to one experience (e.g. /fast
163
+ // is Standard-only), the same way the web shows or hides its toggles.
164
+ setCommandScope(ctx.chatType);
76
165
  const res = await readCommand(CARET, history, footer, placeholder);
77
166
  if (res.type === "exit") {
78
167
  leave();
79
168
  return;
80
169
  }
170
+ // ←/→ switch chat type. No confirmation: the outgoing conversation is NOT
171
+ // deleted — setChatType only drops the local pointer to it, and the thread
172
+ // stays on the server. So the note says how to get back rather than asking
173
+ // permission to leave.
174
+ if (res.type === "switch") {
175
+ const target = res.dir === "left" ? "carrier" : "standard";
176
+ if (ctx.chatType === target)
177
+ continue; // already there — nothing to say
178
+ // Refused mid-turn: the in-flight reply belongs to the OUTGOING
179
+ // conversation, and clearing the pointer now would file its session id
180
+ // against the chat type you just left.
181
+ if (mainRunning()) {
182
+ line();
183
+ line(" " + c.warn("!") + " " + c.dim("Finish the current response before switching."));
184
+ line();
185
+ continue;
186
+ }
187
+ const leaving = describeCurrentSession(ctx);
188
+ ctx.setChatType(target);
189
+ conversationStarted = false; // a fresh conversation starts on the next message
190
+ line();
191
+ line(" " + c.dim("Switched to ") + c.value(chatTypeLabel(target)) + c.dim("."));
192
+ if (leaving)
193
+ line(" " + c.dim(leaving));
194
+ line();
195
+ continue;
196
+ }
81
197
  if (res.type === "sigint") {
198
+ // Ctrl+C with a turn in flight cancels the TURN, not the CLI — the same
199
+ // meaning it had when the turn owned stdin. Only an idle Ctrl+C arms the
200
+ // exit, so a mistaken keystroke mid-answer can never drop the shell.
201
+ if (mainRunning()) {
202
+ // Cancelling the running turn also drops whatever was queued behind it —
203
+ // there is nothing for it to run after now.
204
+ queued = null;
205
+ cancelMainTurn();
206
+ continue;
207
+ }
82
208
  if (sigintArmed) {
83
209
  leave();
84
210
  return;
@@ -89,7 +215,7 @@ export async function runShell(ctx, program) {
89
215
  sigintArmed = false;
90
216
  let message = res.value.trim();
91
217
  if (!message)
92
- continue;
218
+ continue; // never auto-act on an empty prompt
93
219
  history.push(message);
94
220
  // Submitting always re-follows the newest output (in case they'd scrolled up).
95
221
  screenScrollToBottom();
@@ -102,13 +228,55 @@ export async function runShell(ctx, program) {
102
228
  conversationStarted = false;
103
229
  else if (!message.startsWith("/"))
104
230
  conversationStarted = true;
231
+ // A main turn while one is already running is QUEUED, not refused — one at a
232
+ // time, so the pending one is next when the current turn finishes. A quick
233
+ // side question (/btw) is still the way to ask without waiting.
234
+ if (isMainTurn(message) && mainRunning()) {
235
+ if (queued !== null) {
236
+ line();
237
+ line(" " + c.warn("!") + " " + c.dim("A message is already queued — it runs next. Send this once it starts."));
238
+ line();
239
+ }
240
+ else {
241
+ queued = message;
242
+ line(" " + c.dim("⏎ Queued — runs after the current response. Ctrl+C cancels both."));
243
+ }
244
+ continue;
245
+ }
246
+ // Main turns are detached so the composer keeps reading; the drain of a
247
+ // queued message is handled in startMainTurn's finally.
248
+ if (isMainTurn(message)) {
249
+ startMainTurn(message);
250
+ continue;
251
+ }
105
252
  const { exit } = await dispatchLine(ctx, program, client, message);
106
253
  if (exit) {
254
+ // Let an in-flight turn go rather than leaving it writing into a
255
+ // torn-down screen.
256
+ cancelMainTurn();
107
257
  leave();
108
258
  return;
109
259
  }
110
260
  }
111
261
  }
262
+ /**
263
+ * "Your Carrier conversation "…" is saved — /session 3 to return.", or null when
264
+ * there is nothing to go back to.
265
+ *
266
+ * The ordinal comes from the list `/sessions` last printed, which is what the
267
+ * user would actually type; without it the message names the conversation but
268
+ * points at /sessions instead of inventing a number.
269
+ */
270
+ function describeCurrentSession(ctx) {
271
+ const id = ctx.config.get("sessionId");
272
+ if (!id)
273
+ return null;
274
+ const title = ctx.config.get("sessionTitle");
275
+ const named = title ? `"${title}"` : "conversation";
276
+ const ordinal = (ctx.config.get("sessionOrdinals") ?? []).indexOf(id) + 1;
277
+ const back = ordinal > 0 ? `/session ${ordinal} to return` : "/sessions to return";
278
+ return `Your ${chatTypeLabel(ctx.chatType)} ${named} is saved — ${back}.`;
279
+ }
112
280
  /** First empty session — the welcome placeholder doubles as the input area. */
113
281
  const WELCOME_PLACEHOLDER = "What can I help you build today?";
114
282
  /** Once the conversation is underway — a compact, unobtrusive prompt. */
@@ -1,4 +1,6 @@
1
1
  // Public /v1 API contract — mirrors the shapes returned by api.carrieros.ai's
2
2
  // `src/routes/v1/*`. The CLI is a pure consumer: it never reimplements any of
3
3
  // this logic, it only types the JSON it receives.
4
- export {};
4
+ export function isMemoryMarker(m) {
5
+ return m.role === "marker";
6
+ }
@@ -0,0 +1,81 @@
1
+ import { c } from "./colors.js";
2
+ import { MARGIN, contentWidth, visibleWidth } from "./composer-layout.js";
3
+ import { captureKeys } from "./screen-prompt.js";
4
+ import { screenScrollPage, screenScrollToBottom, screenTransient } from "./screen.js";
5
+ /** Remaining time as m:ss, for the auto-reject hint. */
6
+ function countdown(msLeft) {
7
+ const left = Math.max(0, Math.ceil(msLeft / 1000));
8
+ return `${Math.floor(left / 60)}:${String(left % 60).padStart(2, "0")}`;
9
+ }
10
+ /**
11
+ * The exact lines the prompt shows. Pure, so the layout can be tested.
12
+ *
13
+ * One line to answer, one dim line saying what the keys do and when it gives
14
+ * up. `(y/N)` is the convention for "anything but y means no", which is exactly
15
+ * the policy underneath.
16
+ */
17
+ export function approvalFrame(question, msLeft) {
18
+ const hint = c.dim("Enter or ") +
19
+ c.key("n") +
20
+ c.dim(" declines · ") +
21
+ c.key("Ctrl+C") +
22
+ c.dim(" stops the turn · declines on its own in ") +
23
+ c.dim(countdown(msLeft));
24
+ const short = c.dim("Enter/") + c.key("n") + c.dim(" declines · ") + c.key("Ctrl+C") + c.dim(" stops · ") + c.dim(countdown(msLeft));
25
+ const room = contentWidth() - 6;
26
+ return [
27
+ MARGIN + " " + c.warn("?") + " " + c.title(question) + " " + c.dim("(y/N)"),
28
+ MARGIN + " " + (visibleWidth(hint) <= room ? hint : short)
29
+ ];
30
+ }
31
+ export function askApproval(opts) {
32
+ return new Promise((resolve) => {
33
+ const deadline = Date.now() + opts.timeoutMs;
34
+ let done = false;
35
+ const paint = () => screenTransient(approvalFrame(opts.question, deadline - Date.now()));
36
+ const finish = (value) => {
37
+ if (done)
38
+ return;
39
+ done = true;
40
+ clearInterval(timer);
41
+ opts.signal?.removeEventListener?.("abort", onAbort);
42
+ release();
43
+ screenTransient([]);
44
+ resolve(value);
45
+ };
46
+ function onAbort() {
47
+ finish("cancel");
48
+ }
49
+ const onKey = (str, key) => {
50
+ if (!key && !str)
51
+ return;
52
+ if (key?.ctrl && (key.name === "c" || key.name === "d"))
53
+ return finish("cancel");
54
+ if (key?.name === "pageup")
55
+ return screenScrollPage(-1);
56
+ if (key?.name === "pagedown")
57
+ return screenScrollPage(1);
58
+ if (key?.name === "end")
59
+ return screenScrollToBottom();
60
+ if (str === "y" || str === "Y")
61
+ return finish("approve");
62
+ if (str === "n" || str === "N" || key?.name === "escape")
63
+ return finish("reject");
64
+ if (key?.name === "return" || key?.name === "enter")
65
+ return finish("reject");
66
+ };
67
+ const release = captureKeys(onKey);
68
+ const timer = setInterval(() => {
69
+ if (Date.now() >= deadline)
70
+ finish("timeout");
71
+ else
72
+ paint();
73
+ }, 1000);
74
+ timer.unref?.();
75
+ if (opts.signal?.aborted)
76
+ return finish("cancel");
77
+ opts.signal?.addEventListener?.("abort", onAbort, { once: true });
78
+ screenScrollToBottom();
79
+ paint();
80
+ });
81
+ }
package/dist/ui/banner.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import chalk from "chalk";
2
2
  import { line } from "../services/output.js";
3
+ import { branchLabel, fitPath, getWorkspace, statusLabel } from "../services/workspace.js";
3
4
  import { modeLabelShort, modelLabelShort } from "../shell/shell-chat.js";
4
5
  import { c } from "./colors.js";
5
6
  import { WORDMARK } from "./logo.js";
@@ -48,9 +49,47 @@ export function renderBrandmark() {
48
49
  function kvLine(label, value) {
49
50
  return MARGIN + c.label(label.padEnd(LABEL_WIDTH)) + c.value(value);
50
51
  }
52
+ /**
53
+ * Where you are, in three lines: the project, its Git state, and the path.
54
+ *
55
+ * This is the first thing the CLI has ever known about the local machine, and
56
+ * the banner is where it belongs — it answers "what am I pointed at?" before
57
+ * the first prompt, rather than making someone run a command to find out.
58
+ *
59
+ * Failure is silent by design. A machine without Git, or a folder Git refuses
60
+ * to read, still gets a Workspace and a Path; only the Git line changes. The
61
+ * caller already wraps this, but the shell must open regardless.
62
+ */
63
+ function workspaceLines() {
64
+ const ws = getWorkspace();
65
+ const repo = ws.repository;
66
+ const out = [kvLine("Workspace", ws.project.name)];
67
+ if (repo.state === "detected") {
68
+ const branch = branchLabel(repo) ?? "unknown";
69
+ const status = statusLabel(repo);
70
+ // "Clean" adds nothing at a glance — the absence of a count already says
71
+ // it. Only a dirty tree, or an unknown one, is worth the extra words.
72
+ const suffix = status && status !== "Clean" ? ` ${c.dim("·")} ${status}` : "";
73
+ out.push(kvLine("Git", branch) + suffix);
74
+ }
75
+ else if (repo.state === "unavailable") {
76
+ out.push(kvLine("Git", "Unavailable"));
77
+ }
78
+ else {
79
+ out.push(kvLine("Git", "Not detected"));
80
+ }
81
+ // Budget: margin + label column + a little slack, so a deep path shortens
82
+ // instead of wrapping the banner onto a second line.
83
+ const width = Math.max(24, (process.stdout.columns ?? 80) - MARGIN.length - LABEL_WIDTH - 2);
84
+ out.push(kvLine("Path", fitPath(ws.cwd, width)));
85
+ out.push("");
86
+ return out;
87
+ }
51
88
  export function renderWelcomeBanner(ctx, opts = {}) {
52
89
  try {
53
90
  const out = ["", ...renderBrandmark(), ""];
91
+ for (const l of workspaceLines())
92
+ out.push(l);
54
93
  out.push(kvLine("Mode", modeLabelShort(ctx)));
55
94
  out.push(kvLine("Model", modelLabelShort(ctx)));
56
95
  out.push("");
@@ -0,0 +1,230 @@
1
+ import * as readline from "node:readline";
2
+ import { line } from "../services/output.js";
3
+ import { sleep } from "../services/spinner.js";
4
+ import { c } from "./colors.js";
5
+ import { renderMarkdown } from "./markdown.js";
6
+ import { resumeScreen, screenActive, screenCommitTransient, screenTransient, suspendScreen } from "./screen.js";
7
+ import { termWidth } from "./ui.js";
8
+ /**
9
+ * The "By the way" overlay — a temporary panel for a side answer.
10
+ *
11
+ * Deliberately NOT a transcript message. The answer was never persisted
12
+ * server-side, so printing it into the conversation would be the one place the
13
+ * CLI lied about what happened. It is drawn in the transient region, dismissed
14
+ * by a keypress, and leaves nothing behind.
15
+ */
16
+ const MAX_ROWS = 14;
17
+ /** SGR runs plus OSC strings — an OSC payload occupies no columns. */
18
+ const ANSI = /\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b\[[0-9;]*m/g;
19
+ /** Truncate to `max` visible columns, closing any open colour run. */
20
+ function clipAnsi(s, max) {
21
+ let out = "";
22
+ let seen = 0;
23
+ let i = 0;
24
+ while (i < s.length && seen < max) {
25
+ if (s[i] === "\x1b") {
26
+ ANSI.lastIndex = i;
27
+ const m = ANSI.exec(s);
28
+ if (m && m.index === i) {
29
+ out += m[0];
30
+ i += m[0].length;
31
+ continue;
32
+ }
33
+ }
34
+ out += s[i];
35
+ seen += 1;
36
+ i += 1;
37
+ }
38
+ return out + "\x1b[0m";
39
+ }
40
+ function wrap(text, width) {
41
+ const w = Math.max(20, width);
42
+ const out = [];
43
+ for (const paragraph of text.split(/\n/)) {
44
+ if (!paragraph.trim()) {
45
+ out.push("");
46
+ continue;
47
+ }
48
+ let cur = "";
49
+ for (const word of paragraph.trim().split(/\s+/)) {
50
+ if (cur && [...cur].length + 1 + [...word].length > w) {
51
+ out.push(cur);
52
+ cur = word;
53
+ }
54
+ else {
55
+ cur = cur ? `${cur} ${word}` : word;
56
+ }
57
+ }
58
+ if (cur)
59
+ out.push(cur);
60
+ }
61
+ return out.length ? out : [""];
62
+ }
63
+ /**
64
+ * The answer as a bordered block, with the body rendered through the SAME
65
+ * markdown renderer the main response uses — so headings, bold and inline code
66
+ * are themed identically instead of showing raw `**asterisks**`.
67
+ *
68
+ * Nothing is truncated. An earlier version capped the body at 14 rows with an
69
+ * ellipsis, which quietly threw away most of a long answer AND defeated the
70
+ * "too tall for a panel" check, since the panel could never measure tall.
71
+ * A left rule marks it as an aside; the transcript scrolls, so length is fine.
72
+ */
73
+ export function btwAnswerLines(answer, note) {
74
+ // Interior width. The body is rendered to exactly this, so a wrapped line can
75
+ // never push past the right border.
76
+ const box = Math.max(32, Math.min(termWidth() - 4, 92));
77
+ const inner = box - 4; // "│ " … " │"
78
+ const title = " By the way ";
79
+ const top = "┌─" + title + "─".repeat(Math.max(1, box - title.length - 3)) + "┐";
80
+ const bottom = "└" + "─".repeat(box - 2) + "┘";
81
+ /** One boxed row, padded on the VISIBLE width so colour codes don't skew it. */
82
+ const row = (styled) => {
83
+ const visible = [...styled.replace(ANSI, "")].length;
84
+ const body = visible > inner ? clipAnsi(styled, inner) : styled;
85
+ const padTo = Math.max(0, inner - Math.min(visible, inner));
86
+ return " " + c.magic("│") + " " + body + " ".repeat(padTo) + " " + c.magic("│");
87
+ };
88
+ const footer = "Not added to your conversation." + (note ? ` ${note}` : "");
89
+ return [
90
+ "",
91
+ " " + c.magic(top),
92
+ ...renderMarkdown(answer, inner).map(row),
93
+ row(""),
94
+ row(c.dim(footer)),
95
+ " " + c.magic(bottom),
96
+ ""
97
+ ];
98
+ }
99
+ /** Delay between revealed rows. Fast enough not to be a wait, slow enough to
100
+ * read as the answer arriving rather than a repaint. */
101
+ const REVEAL_MS = 26;
102
+ /**
103
+ * Build the box a row at a time in the transient region, then promote the whole
104
+ * thing to permanent transcript.
105
+ *
106
+ * Line-by-line rather than word-by-word: the box has to be closed on every
107
+ * frame, and a partially-drawn row inside a border reads as corruption. The
108
+ * screen engine diffs frames, so each step repaints only the new row.
109
+ */
110
+ async function revealAnswer(lines) {
111
+ for (let i = 1; i <= lines.length; i++) {
112
+ screenTransient(lines.slice(0, i));
113
+ await sleep(REVEAL_MS);
114
+ }
115
+ // Already on screen where it will stay — promoting is invisible.
116
+ screenCommitTransient();
117
+ }
118
+ /** Build the bordered panel. Exported so it can be rendered without a TTY. */
119
+ export function btwPanelLines(panel, width, opts = {}) {
120
+ // Columns between the borders, including the one space of padding each side.
121
+ const inner = Math.max(28, Math.min(width, 92) - 4);
122
+ const text = inner - 2; // room actually available to content
123
+ const title = " By the way ";
124
+ const top = "┌─" + title + "─".repeat(Math.max(1, inner - title.length - 1)) + "┐";
125
+ const bottom = "└" + "─".repeat(inner) + "┘";
126
+ /** One body row. `plain` is the same text without colour — the only reliable
127
+ * way to know how many columns it occupies. */
128
+ const row = (styled, plain) => c.magic("│") + " " + styled + " ".repeat(Math.max(0, text - [...plain].length)) + " " + c.magic("│");
129
+ const body = [];
130
+ if (panel.answer === null) {
131
+ const message = panel.error ?? "Unable to answer this side question.";
132
+ for (const l of wrap(message, text - 2)) {
133
+ body.push(row(c.err("✗ ") + c.value(l), "✗ " + l));
134
+ }
135
+ body.push(row("", ""));
136
+ const footer = "Your conversation was not affected.";
137
+ body.push(row(c.dim(footer), footer));
138
+ }
139
+ else {
140
+ const lines = wrap(panel.answer, text);
141
+ // Long answers are clipped rather than allowed to fill the screen — this is
142
+ // an aside, and the transcript behind it has to stay visible.
143
+ const shown = lines.slice(0, MAX_ROWS);
144
+ if (lines.length > MAX_ROWS)
145
+ shown[MAX_ROWS - 1] = shown[MAX_ROWS - 1].slice(0, -1) + "…";
146
+ for (const l of shown)
147
+ body.push(row(c.value(l), l));
148
+ body.push(row("", ""));
149
+ const footer = "Not added to your conversation.";
150
+ body.push(row(c.dim(footer), footer));
151
+ }
152
+ if (panel.note)
153
+ body.push(row(c.dim(panel.note), panel.note));
154
+ return [
155
+ "",
156
+ " " + c.magic(top),
157
+ ...body.map((l) => " " + l),
158
+ " " + c.magic(bottom),
159
+ ...(opts.dismissible === false ? [] : [" " + c.dim("Esc / Enter / Space to close")]),
160
+ ""
161
+ ];
162
+ }
163
+ /**
164
+ * Show the panel and wait for a dismissal key.
165
+ *
166
+ * Resolves once dismissed. Any key closes it — Esc, Enter and Space are simply
167
+ * the ones advertised — because a panel you cannot get rid of is worse than one
168
+ * that closes too eagerly.
169
+ */
170
+ export function showBtwPanel(panel, opts = {}) {
171
+ const stdin = process.stdin;
172
+ // A reveal needs the transient region, and during a main turn the turn owns
173
+ // it — two writers there is the flicker we already fixed once. So the answer
174
+ // builds progressively only when nothing else is rendering.
175
+ if (panel.answer !== null && !opts.commit && screenActive()) {
176
+ return revealAnswer(btwAnswerLines(panel.answer, panel.note));
177
+ }
178
+ // ANSWERS go to the transcript, always.
179
+ //
180
+ // A panel cannot scroll, so any answer longer than the terminal would have to
181
+ // be truncated — and these are real explanations now, not one-liners. The
182
+ // transcript scrolls (PgUp/PgDn, End) and renders markdown, so the whole
183
+ // answer survives and reads like the main response.
184
+ //
185
+ // Routed through line(), NOT process.stdout: with the screen engine running,
186
+ // a raw write lands wherever the cursor happens to be and corrupts the frame.
187
+ if (panel.answer !== null) {
188
+ for (const l of btwAnswerLines(panel.answer, panel.note))
189
+ line(l);
190
+ return Promise.resolve();
191
+ }
192
+ // ERRORS stay a small box — short, and worth a beat of attention.
193
+ if (opts.commit || !stdin.isTTY) {
194
+ for (const l of btwPanelLines(panel, termWidth(), { dismissible: false }))
195
+ line(l);
196
+ return Promise.resolve();
197
+ }
198
+ return new Promise((resolve) => {
199
+ const onScreen = screenActive();
200
+ const lines = () => btwPanelLines(panel, termWidth());
201
+ if (onScreen) {
202
+ screenTransient(lines());
203
+ }
204
+ else {
205
+ suspendScreen();
206
+ for (const l of lines())
207
+ process.stdout.write(l + "\n");
208
+ }
209
+ const previous = stdin.listeners("keypress");
210
+ stdin.removeAllListeners("keypress");
211
+ readline.emitKeypressEvents(stdin);
212
+ const prevRaw = stdin.isRaw ?? false;
213
+ if (stdin.isTTY)
214
+ stdin.setRawMode(true);
215
+ stdin.resume();
216
+ const onKey = () => {
217
+ stdin.removeListener("keypress", onKey);
218
+ if (stdin.isTTY)
219
+ stdin.setRawMode(prevRaw);
220
+ for (const l of previous)
221
+ stdin.on("keypress", l);
222
+ if (onScreen)
223
+ screenTransient([]);
224
+ else
225
+ resumeScreen();
226
+ resolve();
227
+ };
228
+ stdin.on("keypress", onKey);
229
+ });
230
+ }