@carrieros/cli 0.1.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 (53) hide show
  1. package/README.md +305 -0
  2. package/dist/commands/chat.js +93 -0
  3. package/dist/commands/doctor.js +54 -0
  4. package/dist/commands/files.js +33 -0
  5. package/dist/commands/help.js +35 -0
  6. package/dist/commands/history.js +47 -0
  7. package/dist/commands/login.js +59 -0
  8. package/dist/commands/logout.js +15 -0
  9. package/dist/commands/mode-model.js +28 -0
  10. package/dist/commands/models.js +28 -0
  11. package/dist/commands/modes.js +27 -0
  12. package/dist/commands/sessions.js +123 -0
  13. package/dist/commands/upload.js +50 -0
  14. package/dist/commands/usage.js +31 -0
  15. package/dist/commands/version.js +28 -0
  16. package/dist/commands/whoami.js +40 -0
  17. package/dist/main.js +94 -0
  18. package/dist/services/api.js +115 -0
  19. package/dist/services/config.js +72 -0
  20. package/dist/services/context.js +42 -0
  21. package/dist/services/login-flow.js +15 -0
  22. package/dist/services/meta.js +13 -0
  23. package/dist/services/output.js +54 -0
  24. package/dist/services/spinner.js +18 -0
  25. package/dist/shell/shell-chat.js +280 -0
  26. package/dist/shell/shell-commands.js +168 -0
  27. package/dist/shell/shell-prompt.js +48 -0
  28. package/dist/shell/shell-renderer.js +70 -0
  29. package/dist/shell/shell-router.js +21 -0
  30. package/dist/shell/shell.js +139 -0
  31. package/dist/types/index.js +4 -0
  32. package/dist/ui/activity.js +77 -0
  33. package/dist/ui/banner.js +70 -0
  34. package/dist/ui/chat-renderer.js +269 -0
  35. package/dist/ui/code-block.js +52 -0
  36. package/dist/ui/color-picker.js +79 -0
  37. package/dist/ui/colors.js +47 -0
  38. package/dist/ui/command-filter.js +57 -0
  39. package/dist/ui/command-item.js +6 -0
  40. package/dist/ui/command-palette.js +306 -0
  41. package/dist/ui/command-registry.js +47 -0
  42. package/dist/ui/command-renderer.js +55 -0
  43. package/dist/ui/composer-layout.js +27 -0
  44. package/dist/ui/live.js +124 -0
  45. package/dist/ui/logo.js +58 -0
  46. package/dist/ui/markdown.js +151 -0
  47. package/dist/ui/message.js +38 -0
  48. package/dist/ui/select.js +114 -0
  49. package/dist/ui/spinner.js +23 -0
  50. package/dist/ui/sticky-stream.js +64 -0
  51. package/dist/ui/theme.js +63 -0
  52. package/dist/ui/ui.js +75 -0
  53. package/package.json +64 -0
@@ -0,0 +1,13 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { fileURLToPath } from "node:url";
3
+ /** Read the CLI's own version from package.json (works in dev and after build). */
4
+ export function cliVersion() {
5
+ try {
6
+ const pkgUrl = new URL("../../package.json", import.meta.url);
7
+ const pkg = JSON.parse(readFileSync(fileURLToPath(pkgUrl), "utf8"));
8
+ return pkg.version ?? "0.0.0";
9
+ }
10
+ catch {
11
+ return "0.0.0";
12
+ }
13
+ }
@@ -0,0 +1,54 @@
1
+ import { c } from "../ui/colors.js";
2
+ import { icon } from "../ui/ui.js";
3
+ /** Status glyphs (consistent icon set — never emojis). */
4
+ export const glyph = {
5
+ ok: icon.ok,
6
+ warn: icon.warn,
7
+ err: icon.err
8
+ };
9
+ export const line = (msg = "") => {
10
+ process.stdout.write(msg + "\n");
11
+ };
12
+ export const success = (msg) => line(`${icon.ok} ${msg}`);
13
+ export const warn = (msg) => line(`${icon.warn} ${msg}`);
14
+ export const info = (msg) => line(`${icon.info} ${msg}`);
15
+ export const errorLine = (msg) => line(`${icon.err} ${msg}`);
16
+ export const heading = (text) => line("\n" + c.title(text));
17
+ /** Left-aligned label + value, dim label. Used across whoami / usage / doctor. */
18
+ export function kv(label, value, width = 14) {
19
+ line(` ${c.label(label.padEnd(width))}${value}`);
20
+ }
21
+ /** The focused-chat header (used by `cos chat`). */
22
+ export function printBanner(scope, mode, modelLabel) {
23
+ line();
24
+ line(c.wordmark(" Carrier OS CLI"));
25
+ line(c.dim(" Ready."));
26
+ line();
27
+ kv("Workspace", scope?.workspace.name ?? c.dim("—"));
28
+ kv("Project", scope?.project.name ?? c.dim("—"));
29
+ kv("Mode", capitalize(mode));
30
+ kv("Model", modelLabel);
31
+ line();
32
+ line(c.dim(" Type your message, or /help for commands. Ctrl+C to exit."));
33
+ line();
34
+ }
35
+ export function capitalize(s) {
36
+ return s ? s.charAt(0).toUpperCase() + s.slice(1) : s;
37
+ }
38
+ /** Compact, dependency-free relative-time formatter for lists. */
39
+ export function timeAgo(iso) {
40
+ const then = new Date(iso).getTime();
41
+ if (Number.isNaN(then))
42
+ return "—";
43
+ const secs = Math.max(0, Math.floor((Date.now() - then) / 1000));
44
+ if (secs < 60)
45
+ return `${secs}s ago`;
46
+ const mins = Math.floor(secs / 60);
47
+ if (mins < 60)
48
+ return `${mins}m ago`;
49
+ const hrs = Math.floor(mins / 60);
50
+ if (hrs < 24)
51
+ return `${hrs}h ago`;
52
+ const days = Math.floor(hrs / 24);
53
+ return `${days}d ago`;
54
+ }
@@ -0,0 +1,18 @@
1
+ import ora from "ora";
2
+ /**
3
+ * Run an async task under a spinner. The spinner is always stopped afterwards
4
+ * (success or throw) so it can never be left spinning on an error path.
5
+ */
6
+ export async function withSpinner(text, fn) {
7
+ // discardStdin:false — otherwise ora grabs/pauses stdin while spinning, which
8
+ // corrupts the interactive shell's readline and makes it exit after one turn.
9
+ const spinner = ora({ text, color: "cyan", discardStdin: false }).start();
10
+ try {
11
+ return await fn(spinner);
12
+ }
13
+ finally {
14
+ spinner.stop();
15
+ }
16
+ }
17
+ /** Small helper for the mocked "streaming" output. */
18
+ export const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
@@ -0,0 +1,280 @@
1
+ import chalk from "chalk";
2
+ import { ApiError } from "../services/api.js";
3
+ import { capitalize, errorLine, info, line } from "../services/output.js";
4
+ import { sleep, withSpinner } from "../services/spinner.js";
5
+ import { chatActivitySteps, startActivity } from "../ui/activity.js";
6
+ import { renderComplete, renderCompleteSticky, renderError, renderUserMessage, startThinking, streamAssistant, streamAssistantSticky } from "../ui/chat-renderer.js";
7
+ import { startLiveComposer } from "../ui/live.js";
8
+ import { startStickyStream } from "../ui/sticky-stream.js";
9
+ import { pickFromList } from "../ui/select.js";
10
+ // Shared by the `chat` command REPL and the interactive shell so chat, mode and
11
+ // model logic lives in exactly one place (no duplicated business logic).
12
+ export const AUTO_LABEL = "Auto (mode default)";
13
+ // Process-lifetime caches — the mode/model lists are stable per run.
14
+ let modeCache = null;
15
+ let modelCache = null;
16
+ export async function loadModes(client) {
17
+ return (modeCache ??= await client.models());
18
+ }
19
+ export async function loadModels(client) {
20
+ return (modelCache ??= await client.chatModels());
21
+ }
22
+ export function currentModelId(ctx) {
23
+ return ctx.config.get("model") ?? "";
24
+ }
25
+ /** Short label for the prompt/banner ("Auto" or e.g. "GPT-5.5"). */
26
+ export function modelLabelShort(ctx) {
27
+ const id = currentModelId(ctx);
28
+ if (!id)
29
+ return "Auto";
30
+ return modelCache?.find((m) => m.id === id)?.label ?? id;
31
+ }
32
+ function reportError(err) {
33
+ errorLine(err instanceof ApiError ? `${err.message} (${err.code})` : err.message);
34
+ }
35
+ /**
36
+ * Send one chat turn using the config's current mode + model, and render it.
37
+ * When `opts.footer` is supplied (the interactive shell), the input bar stays
38
+ * pinned at the bottom and the response streams above it; otherwise (the plain
39
+ * `chat` REPL) output just prints inline.
40
+ */
41
+ export async function chatTurn(ctx, client, message, opts = {}) {
42
+ const useLiveBar = opts.footer !== undefined && process.stdout.isTTY;
43
+ if (useLiveBar) {
44
+ await chatTurnLive(ctx, client, message, opts.footer ?? "");
45
+ return;
46
+ }
47
+ const mode = ctx.mode;
48
+ const model = currentModelId(ctx);
49
+ renderUserMessage(message);
50
+ const started = Date.now();
51
+ const spinner = startThinking();
52
+ try {
53
+ const sessionId = ctx.config.get("sessionId");
54
+ const result = await client.chat({
55
+ mode,
56
+ message,
57
+ session_id: sessionId,
58
+ model: model || undefined
59
+ });
60
+ spinner.stop();
61
+ // Persist the session so the conversation continues across turns/invocations.
62
+ if (result.session_id && result.session_id !== sessionId) {
63
+ ctx.config.set("sessionId", result.session_id);
64
+ }
65
+ await streamAssistant(result.response);
66
+ renderComplete((Date.now() - started) / 1000);
67
+ }
68
+ catch (err) {
69
+ spinner.stop();
70
+ if (err instanceof ApiError) {
71
+ const hint = err.code === "INVALID_API_KEY" || err.code === "NO_ACCOUNT" ? "/login" : undefined;
72
+ renderError(err.message, `Error code: ${err.code}`, hint);
73
+ }
74
+ else {
75
+ renderError("Something went wrong", err.message);
76
+ }
77
+ }
78
+ }
79
+ /**
80
+ * chatTurn with the sticky bottom input bar + an activity timeline. The turn
81
+ * emits phase "events" (request_started → mode_selected → request_sent →
82
+ * waiting → done) as `activity.step()` calls; the real API request is fired up
83
+ * front so the timeline overlays the genuine wait (adding no latency), then the
84
+ * timeline collapses and the answer streams in word-by-word.
85
+ */
86
+ async function chatTurnLive(ctx, client, message, footer) {
87
+ const mode = ctx.mode;
88
+ const model = currentModelId(ctx);
89
+ const sessionId = ctx.config.get("sessionId");
90
+ renderUserMessage(message);
91
+ const live = startLiveComposer(footer);
92
+ const activity = startActivity(live);
93
+ const started = Date.now();
94
+ // request_started + request_sent: fire the real call immediately, then the
95
+ // brief client-side steps play over the actual wait. Settle it eagerly so a
96
+ // rejection during the steps is never an unhandled rejection.
97
+ const settled = client
98
+ .chat({ mode, message, session_id: sessionId, model: model || undefined })
99
+ .then((r) => ({ ok: true, r }))
100
+ .catch((e) => ({ ok: false, e }));
101
+ try {
102
+ const steps = chatActivitySteps(capitalize(mode));
103
+ for (let i = 0; i < steps.length - 1; i++) {
104
+ activity.step(steps[i]); // request_started → mode_selected → request_sent
105
+ await sleep(190);
106
+ }
107
+ activity.step(steps[steps.length - 1]); // waiting — spins over the real await
108
+ const outcome = await settled;
109
+ activity.done();
110
+ activity.stop();
111
+ live.stop(); // hand the composer region over to the sticky scroll-region stream
112
+ if (!outcome.ok)
113
+ throw outcome.e;
114
+ const result = outcome.r;
115
+ if (result.session_id && result.session_id !== sessionId) {
116
+ ctx.config.set("sessionId", result.session_id);
117
+ }
118
+ // Stream the answer above a PINNED input bar via a scroll region — the bar
119
+ // stays visible AND never repaints (flicker-free).
120
+ const sticky = startStickyStream(footer);
121
+ try {
122
+ await streamAssistantSticky(sticky, result.response); // first_token → stream → complete
123
+ renderCompleteSticky(sticky, (Date.now() - started) / 1000);
124
+ }
125
+ finally {
126
+ sticky.stop(); // restore the terminal; the reader redraws its bar in place
127
+ }
128
+ }
129
+ catch (err) {
130
+ activity.stop();
131
+ live.stop();
132
+ if (err instanceof ApiError) {
133
+ const hint = err.code === "INVALID_API_KEY" || err.code === "NO_ACCOUNT" ? "/login" : undefined;
134
+ renderError(err.message, `Error code: ${err.code}`, hint);
135
+ }
136
+ else {
137
+ renderError("Something went wrong", err.message);
138
+ }
139
+ }
140
+ }
141
+ // ── Carrier modes (behavior) ──────────────────────────────────────────────────
142
+ export async function showModes(ctx, client) {
143
+ try {
144
+ const modes = await withSpinner(chalk.dim("Loading modes…"), () => loadModes(client));
145
+ const active = ctx.mode;
146
+ line();
147
+ line(chalk.dim(" Carrier modes (behavior):"));
148
+ for (const m of modes) {
149
+ const on = m.id === active;
150
+ const name = on ? chalk.bold(capitalize(m.name)) : capitalize(m.name);
151
+ line(` ${on ? chalk.green("►") : " "} ${name.padEnd(12)} ${chalk.dim(m.description)}`);
152
+ }
153
+ line();
154
+ }
155
+ catch (err) {
156
+ reportError(err);
157
+ }
158
+ }
159
+ export async function setMode(ctx, client, arg) {
160
+ const id = arg.trim().toLowerCase();
161
+ if (!id) {
162
+ await pickMode(ctx, client);
163
+ return;
164
+ }
165
+ try {
166
+ const modes = await loadModes(client);
167
+ if (!modes.some((m) => m.id === id)) {
168
+ errorLine(`Unknown mode "${id}". Type /modes to see the options.`);
169
+ return;
170
+ }
171
+ ctx.config.set("mode", id);
172
+ info(`Mode changed to ${capitalize(id)} (applies to your next message).`);
173
+ }
174
+ catch (err) {
175
+ reportError(err);
176
+ }
177
+ }
178
+ /** Arrow-key picker for the Carrier mode (↑/↓ + Enter; Esc/Ctrl+C cancels). */
179
+ export async function pickMode(ctx, client) {
180
+ let modes;
181
+ try {
182
+ modes = await withSpinner(chalk.dim("Loading modes…"), () => loadModes(client));
183
+ }
184
+ catch (err) {
185
+ reportError(err);
186
+ return;
187
+ }
188
+ const chosen = await pickFromList({
189
+ title: "Select a Carrier mode",
190
+ description: "Changes how Carrier responds. Applies to your next message.",
191
+ initial: Math.max(0, modes.findIndex((m) => m.id === ctx.mode)),
192
+ choices: modes.map((m) => ({
193
+ value: m.id,
194
+ label: capitalize(m.name),
195
+ description: m.description,
196
+ current: m.id === ctx.mode
197
+ }))
198
+ });
199
+ if (chosen == null)
200
+ return; // Esc / Ctrl+C — leave the mode unchanged
201
+ ctx.config.set("mode", chosen);
202
+ info(`Mode changed to ${capitalize(chosen)} (applies to your next message).`);
203
+ }
204
+ // ── Provider models (the LLM behind a turn) ───────────────────────────────────
205
+ export async function showModels(ctx, client) {
206
+ try {
207
+ const models = await withSpinner(chalk.dim("Loading models…"), () => loadModels(client));
208
+ const active = currentModelId(ctx);
209
+ line();
210
+ line(chalk.dim(" Provider models:"));
211
+ const autoOn = active === "";
212
+ line(` ${autoOn ? chalk.green("►") : " "} ${(autoOn ? chalk.bold(AUTO_LABEL) : AUTO_LABEL).padEnd(28)}`);
213
+ for (const m of models) {
214
+ const on = m.id === active;
215
+ const label = on ? chalk.bold(m.label) : m.label;
216
+ line(` ${on ? chalk.green("►") : " "} ${label.padEnd(28)} ${chalk.dim(m.id)}`);
217
+ }
218
+ line();
219
+ }
220
+ catch (err) {
221
+ reportError(err);
222
+ }
223
+ }
224
+ export async function setModel(ctx, client, arg) {
225
+ const id = arg.trim().toLowerCase();
226
+ if (!id) {
227
+ await pickModel(ctx, client);
228
+ return;
229
+ }
230
+ if (id === "auto" || id === "default") {
231
+ ctx.config.set("model", "");
232
+ info(`Model set to ${AUTO_LABEL}.`);
233
+ return;
234
+ }
235
+ try {
236
+ const models = await loadModels(client);
237
+ const match = models.find((m) => m.id === id);
238
+ if (!match) {
239
+ errorLine(`Unknown model "${id}". Type /models to see the options.`);
240
+ return;
241
+ }
242
+ ctx.config.set("model", match.id);
243
+ info(`Model changed to ${match.label} (applies to your next message).`);
244
+ }
245
+ catch (err) {
246
+ reportError(err);
247
+ }
248
+ }
249
+ /** Arrow-key picker for the provider model (Auto + each model; Esc/Ctrl+C cancels). */
250
+ export async function pickModel(ctx, client) {
251
+ let models;
252
+ try {
253
+ models = await withSpinner(chalk.dim("Loading models…"), () => loadModels(client));
254
+ }
255
+ catch (err) {
256
+ reportError(err);
257
+ return;
258
+ }
259
+ const current = currentModelId(ctx);
260
+ const choices = [
261
+ {
262
+ value: "",
263
+ label: AUTO_LABEL,
264
+ description: "Use the current mode's default model",
265
+ current: current === ""
266
+ },
267
+ ...models.map((m) => ({ value: m.id, label: m.label, description: m.id, current: m.id === current }))
268
+ ];
269
+ const chosen = await pickFromList({
270
+ title: "Select a model",
271
+ description: "Switch the model for this and future messages.",
272
+ initial: Math.max(0, choices.findIndex((ch) => ch.current)),
273
+ choices
274
+ });
275
+ if (chosen == null)
276
+ return; // Esc / Ctrl+C — leave the model unchanged
277
+ ctx.config.set("model", chosen);
278
+ const label = chosen ? (models.find((m) => m.id === chosen)?.label ?? chosen) : AUTO_LABEL;
279
+ info(`Model changed to ${label} (applies to your next message).`);
280
+ }
@@ -0,0 +1,168 @@
1
+ import { CommanderError } from "commander";
2
+ import { ApiError } from "../services/api.js";
3
+ import { AuthRequiredError } from "../services/context.js";
4
+ import { errorLine, info } from "../services/output.js";
5
+ import { COMMANDS } from "../ui/command-item.js";
6
+ import { pickColor } from "../ui/color-picker.js";
7
+ import { pickFromList } from "../ui/select.js";
8
+ import { isThemeColor, setAccent, THEME_ORDER } from "../ui/theme.js";
9
+ import { chatTurn, pickMode, pickModel, setMode, setModel } from "./shell-chat.js";
10
+ import { buildFooter } from "./shell-prompt.js";
11
+ import { printShellHelp } from "./shell-renderer.js";
12
+ const STAY = { exit: false };
13
+ /**
14
+ * Invoke an existing command through the SAME Commander program, so the shell
15
+ * reuses each command's real implementation instead of duplicating it. Errors
16
+ * are caught (rather than exiting the process) so the shell survives them.
17
+ */
18
+ async function route(program, argv) {
19
+ try {
20
+ await program.parseAsync(argv, { from: "user" });
21
+ }
22
+ catch (err) {
23
+ if (err instanceof AuthRequiredError)
24
+ errorLine(err.message);
25
+ else if (err instanceof ApiError)
26
+ errorLine(`${err.message} (${err.code})`);
27
+ else if (err instanceof CommanderError) {
28
+ /* Commander already printed its message; keep the shell alive. */
29
+ }
30
+ else
31
+ errorLine(err.message);
32
+ }
33
+ finally {
34
+ // A routed command may set a non-zero exit code on error — don't let it
35
+ // leak out of the long-lived shell process.
36
+ process.exitCode = 0;
37
+ }
38
+ }
39
+ /** Handle a `/…` line. Returns { exit } to tell the loop whether to stop. */
40
+ export async function handleSlash(ctx, program, client, input) {
41
+ const body = input.slice(1); // drop the leading '/'
42
+ const parts = body.split(/\s+/).filter(Boolean);
43
+ const cmd = (parts[0] ?? "").toLowerCase();
44
+ const rest = parts.slice(1);
45
+ const argStr = body.slice((parts[0] ?? "").length).trim();
46
+ switch (cmd) {
47
+ case "exit":
48
+ case "quit":
49
+ return { exit: true };
50
+ case "help":
51
+ // In a TTY, /help is an arrow-navigable menu (Enter runs the picked
52
+ // command); piped/non-interactive falls back to the static list.
53
+ if (!process.stdin.isTTY) {
54
+ printShellHelp();
55
+ return STAY;
56
+ }
57
+ return runHelpMenu(ctx, program, client);
58
+ // Accent theme (also /theme). `/color <name>` applies directly; bare
59
+ // `/color` opens the inline selector. Applied on Enter and persisted.
60
+ case "color":
61
+ case "theme": {
62
+ const arg = argStr.trim().toLowerCase();
63
+ if (arg) {
64
+ if (isThemeColor(arg)) {
65
+ setAccent(arg);
66
+ ctx.config.set("theme", { accent: arg });
67
+ info(`Accent color set to ${arg}.`);
68
+ }
69
+ else {
70
+ errorLine(`Unknown color "${arg}". Try: ${THEME_ORDER.join(", ")}.`);
71
+ }
72
+ return STAY;
73
+ }
74
+ const chosen = await pickColor();
75
+ if (chosen) {
76
+ ctx.config.set("theme", { accent: chosen });
77
+ info(`Accent color set to ${chosen}.`);
78
+ }
79
+ return STAY;
80
+ }
81
+ // In the shell you're already chatting — /chat <text> sends a message, and
82
+ // bare /chat just reminds you that typing directly is enough.
83
+ case "chat":
84
+ if (argStr)
85
+ await chatTurn(ctx, client, argStr, { footer: buildFooter(ctx) });
86
+ else
87
+ info("You're in the shell — just type your message to chat.");
88
+ return STAY;
89
+ // ── Chat behavior — handled here so the prompt reflects it immediately ────
90
+ case "modes":
91
+ await pickMode(ctx, client);
92
+ return STAY;
93
+ case "models":
94
+ await pickModel(ctx, client);
95
+ return STAY;
96
+ case "mode":
97
+ await setMode(ctx, client, argStr);
98
+ return STAY;
99
+ case "model":
100
+ await setModel(ctx, client, argStr);
101
+ return STAY;
102
+ case "new":
103
+ case "clear":
104
+ ctx.config.set("sessionId", undefined);
105
+ info("Started a new session.");
106
+ return STAY;
107
+ // ── Routed to the existing command implementations ───────────────────────
108
+ case "whoami":
109
+ await route(program, ["whoami"]);
110
+ return STAY;
111
+ case "doctor":
112
+ await route(program, ["doctor"]);
113
+ return STAY;
114
+ case "usage":
115
+ await route(program, ["usage"]);
116
+ return STAY;
117
+ case "files":
118
+ await route(program, ["files"]);
119
+ return STAY;
120
+ case "version":
121
+ await route(program, ["version"]);
122
+ return STAY;
123
+ case "logout":
124
+ await route(program, ["logout"]);
125
+ return STAY;
126
+ case "login":
127
+ await route(program, ["login", ...rest]);
128
+ return STAY;
129
+ case "sessions":
130
+ await route(program, ["sessions", ...rest]);
131
+ return STAY;
132
+ case "history":
133
+ await route(program, ["history", ...rest]);
134
+ return STAY;
135
+ case "upload":
136
+ if (rest.length === 0) {
137
+ errorLine("Usage: /upload <file>");
138
+ return STAY;
139
+ }
140
+ await route(program, ["upload", ...rest]);
141
+ return STAY;
142
+ case "session":
143
+ if (rest.length === 0) {
144
+ errorLine("Usage: /session use [id] | /session delete <id>");
145
+ return STAY;
146
+ }
147
+ await route(program, ["session", ...rest]);
148
+ return STAY;
149
+ default:
150
+ errorLine(`Unknown command: /${cmd}. Type /help for the list.`);
151
+ return STAY;
152
+ }
153
+ }
154
+ /** Interactive /help: browse every command with ↑/↓ and run the chosen one. */
155
+ async function runHelpMenu(ctx, program, client) {
156
+ const chosen = await pickFromList({
157
+ title: "Commands",
158
+ description: "Type a message to chat, or pick a command to run.",
159
+ choices: COMMANDS.map((entry) => ({
160
+ value: entry.name,
161
+ label: entry.name,
162
+ description: entry.desc
163
+ }))
164
+ });
165
+ if (chosen == null || chosen === "/help")
166
+ return STAY; // Esc, or avoid reopening
167
+ return handleSlash(ctx, program, client, chosen);
168
+ }
@@ -0,0 +1,48 @@
1
+ import { capitalize } from "../services/output.js";
2
+ import { c } from "../ui/colors.js";
3
+ import { modelLabelShort } from "./shell-chat.js";
4
+ /** The green caret the shell prompt uses (non-TTY fallback). */
5
+ export const CARET = c.brand("❯") + " ";
6
+ /**
7
+ * The dim status footer shown directly beneath the input box, Claude-style:
8
+ * ‖ Test CLI · Project A · Code mode · Auto / for commands
9
+ * Workspace/project fade to dim; the active mode (cyan) and model (yellow) keep
10
+ * a subtle accent so they read at a glance. Hidden while the palette is open.
11
+ */
12
+ export function buildFooter(ctx) {
13
+ const scope = ctx.config.get("scope");
14
+ let ws = scope?.workspace.name ?? "—";
15
+ let proj = scope?.project.name ?? "—";
16
+ const mode = capitalize(ctx.mode);
17
+ const model = modelLabelShort(ctx);
18
+ const w = process.stdout.columns && process.stdout.columns > 0 ? process.stdout.columns : 80;
19
+ const trunc = (str, max) => (str.length > max ? str.slice(0, max - 1) + "…" : str);
20
+ const rawPrefix = " ‖ ";
21
+ const rawModeModel = ` · ${mode} mode · ${model}`;
22
+ const rawHint = ` / for commands`;
23
+ const fullMax = w - rawPrefix.length - rawModeModel.length - rawHint.length - 3;
24
+ let hintStr = c.dim(" / ") + c.dim("for commands");
25
+ if (fullMax < ws.length + proj.length) {
26
+ hintStr = "";
27
+ const noHintMax = w - rawPrefix.length - rawModeModel.length - 3;
28
+ if (noHintMax < ws.length + proj.length) {
29
+ if (noHintMax > 8) {
30
+ const half = Math.floor(noHintMax / 2);
31
+ ws = trunc(ws, half);
32
+ proj = trunc(proj, noHintMax - ws.length);
33
+ }
34
+ else {
35
+ ws = "";
36
+ proj = "";
37
+ }
38
+ }
39
+ }
40
+ const dot = c.dim(" · ");
41
+ let context = "";
42
+ if (ws || proj) {
43
+ context += c.dim(ws) + dot + c.dim(proj) + dot;
44
+ }
45
+ context += c.accent(mode) + c.dim(" mode") + dot + c.file(model);
46
+ const finalStr = " " + c.dim("‖ ") + context + hintStr;
47
+ return finalStr;
48
+ }
@@ -0,0 +1,70 @@
1
+ import chalk from "chalk";
2
+ import { kv, line } from "../services/output.js";
3
+ import { renderBrandmark } from "../ui/banner.js";
4
+ import { c } from "../ui/colors.js";
5
+ import { twoCol } from "../ui/ui.js";
6
+ /** First-run welcome shown when no API key is configured — branded. */
7
+ export function printWelcome() {
8
+ line();
9
+ for (const l of renderBrandmark())
10
+ line(l);
11
+ line();
12
+ line(" " + c.brand("Welcome to Carrier OS"));
13
+ line();
14
+ line(" No API key configured.");
15
+ line();
16
+ line(" Paste your Carrier API Secret Key");
17
+ line(chalk.dim(" (or type /exit)"));
18
+ line();
19
+ }
20
+ /** Confirmation after a successful first-run login. */
21
+ export function printAuthSuccess(scope) {
22
+ line();
23
+ line(`${chalk.green("✓")} ${chalk.bold("Authentication Successful")}`);
24
+ line();
25
+ if (scope.user)
26
+ kv("Developer", scope.user.email);
27
+ kv("Workspace", scope.workspace.name);
28
+ kv("Project", scope.project.name);
29
+ line();
30
+ line(chalk.dim(" Configuration saved."));
31
+ line();
32
+ line(chalk.bold(" Ready."));
33
+ line();
34
+ }
35
+ export function printShellHelp() {
36
+ // A single flat list — no category sections — with white command names.
37
+ const rows = [
38
+ ["/mode <id>", "switch Carrier mode · /modes to pick"],
39
+ ["/model <id>", "set provider model · /models to pick · /model auto"],
40
+ ["/clear", "start a fresh session"],
41
+ ["/sessions", "list conversations"],
42
+ ["/session use [id]", "switch session"],
43
+ ["/session delete <id>", "delete a session"],
44
+ ["/history [id]", "print a transcript"],
45
+ ["/upload <file>", "upload + process a file"],
46
+ ["/files", "list your uploads"],
47
+ ["/whoami", "workspace / project / account"],
48
+ ["/doctor", "diagnostics"],
49
+ ["/usage", "requests, tokens, cost"],
50
+ ["/login · /logout", "sign in / out"],
51
+ ["/version", "CLI + API versions"],
52
+ ["/help", "show this help"],
53
+ ["/exit", "leave the shell · or Ctrl+D"]
54
+ ];
55
+ line();
56
+ line(" " + c.dim("Type a message to chat, or run a slash command:"));
57
+ line();
58
+ for (const l of twoCol(rows, c.value, c.dim))
59
+ line(l);
60
+ line();
61
+ line(" " +
62
+ c.dim("Keys ") +
63
+ c.key("↑↓") +
64
+ c.dim(" history ") +
65
+ c.key("Tab") +
66
+ c.dim(" complete ") +
67
+ c.key("Ctrl+C") +
68
+ c.dim(" twice to exit"));
69
+ line();
70
+ }
@@ -0,0 +1,21 @@
1
+ import { chatTurn } from "./shell-chat.js";
2
+ import { handleSlash } from "./shell-commands.js";
3
+ import { buildFooter } from "./shell-prompt.js";
4
+ /**
5
+ * Route one line of shell input: a `/…` line goes to the slash-command handler;
6
+ * anything else is a chat message sent through the shared chat turn.
7
+ */
8
+ export async function dispatchLine(ctx, program, client, input) {
9
+ // Forgive users who type the binary name inside the shell, e.g.
10
+ // "cos models" → treat it as the "/models" command.
11
+ const prefixed = input.match(/^(?:cos|carrieros)\s+(.+)$/i);
12
+ if (prefixed) {
13
+ const rest = prefixed[1].trim();
14
+ return handleSlash(ctx, program, client, rest.startsWith("/") ? rest : `/${rest}`);
15
+ }
16
+ if (input.startsWith("/")) {
17
+ return handleSlash(ctx, program, client, input);
18
+ }
19
+ await chatTurn(ctx, client, input, { footer: buildFooter(ctx) });
20
+ return { exit: false };
21
+ }