@carrieros/cli 0.2.0 → 0.4.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 (124) hide show
  1. package/README.md +170 -64
  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 +81 -15
  6. package/dist/commands/context.js +200 -0
  7. package/dist/commands/doctor.js +63 -3
  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/logout.js +1 -0
  13. package/dist/commands/memory.js +162 -0
  14. package/dist/commands/mode-model.js +39 -3
  15. package/dist/commands/modes.js +4 -1
  16. package/dist/commands/permissions.js +77 -0
  17. package/dist/commands/project.js +106 -0
  18. package/dist/commands/repo.js +146 -0
  19. package/dist/commands/repos.js +61 -0
  20. package/dist/commands/review.js +92 -0
  21. package/dist/commands/scope.js +9 -6
  22. package/dist/commands/search.js +92 -0
  23. package/dist/commands/sessions.js +224 -65
  24. package/dist/commands/settings.js +94 -0
  25. package/dist/commands/update.js +229 -0
  26. package/dist/commands/upload.js +204 -31
  27. package/dist/commands/usage.js +213 -17
  28. package/dist/commands/whoami.js +12 -9
  29. package/dist/ide/editor-context.js +275 -0
  30. package/dist/ide/ide-session.js +355 -0
  31. package/dist/ide/tool-host.js +109 -0
  32. package/dist/main.js +26 -1
  33. package/dist/services/api.js +315 -15
  34. package/dist/services/auth-origin.js +20 -0
  35. package/dist/services/chat-stream.js +168 -0
  36. package/dist/services/checkpoints.js +278 -0
  37. package/dist/services/client-tools.js +352 -0
  38. package/dist/services/code-intel.js +243 -0
  39. package/dist/services/code-symbols.js +94 -0
  40. package/dist/services/coding-workflow.js +554 -0
  41. package/dist/services/command-coordinator.js +273 -0
  42. package/dist/services/command-policy.js +434 -0
  43. package/dist/services/config.js +311 -24
  44. package/dist/services/container-runner.js +254 -0
  45. package/dist/services/container-supervisor.js +38 -0
  46. package/dist/services/context.js +296 -23
  47. package/dist/services/device-auth.js +72 -35
  48. package/dist/services/diff.js +196 -0
  49. package/dist/services/env-policy.js +108 -0
  50. package/dist/services/execution-platform.js +30 -0
  51. package/dist/services/file-detect.js +104 -0
  52. package/dist/services/file-resolver.js +199 -0
  53. package/dist/services/file-upload.js +126 -0
  54. package/dist/services/folder-key.js +22 -0
  55. package/dist/services/git-tools.js +429 -0
  56. package/dist/services/glob-match.js +164 -0
  57. package/dist/services/helper-bin.js +85 -0
  58. package/dist/services/ignore-rules.js +189 -0
  59. package/dist/services/instruction-resolver.js +54 -0
  60. package/dist/services/job-helper.js +328 -0
  61. package/dist/services/local-files.js +639 -0
  62. package/dist/services/local-tools.js +937 -0
  63. package/dist/services/login-flow.js +55 -17
  64. package/dist/services/meta.js +3 -1
  65. package/dist/services/mutation-coordinator.js +327 -0
  66. package/dist/services/mutation-groups.js +309 -0
  67. package/dist/services/mutation-recovery.js +159 -0
  68. package/dist/services/mutations.js +679 -0
  69. package/dist/services/open-url.js +68 -0
  70. package/dist/services/output.js +5 -2
  71. package/dist/services/packaged-update.js +403 -0
  72. package/dist/services/packaged.js +39 -0
  73. package/dist/services/permission-mode.js +60 -0
  74. package/dist/services/process-runner.js +412 -0
  75. package/dist/services/project-context.js +298 -0
  76. package/dist/services/redaction.js +201 -0
  77. package/dist/services/result-reconciliation.js +49 -0
  78. package/dist/services/secure-store.js +217 -0
  79. package/dist/services/session-resolver.js +113 -0
  80. package/dist/services/sia.js +51 -0
  81. package/dist/services/supported-runtime.js +59 -0
  82. package/dist/services/task-context.js +212 -0
  83. package/dist/services/task-snapshot.js +38 -0
  84. package/dist/services/tool-result-outbox.js +195 -0
  85. package/dist/services/update.js +311 -0
  86. package/dist/services/workspace-registry.js +310 -0
  87. package/dist/services/workspace.js +580 -0
  88. package/dist/shell/shell-chat.js +1297 -59
  89. package/dist/shell/shell-commands.js +243 -12
  90. package/dist/shell/shell-prompt.js +94 -11
  91. package/dist/shell/shell-renderer.js +8 -20
  92. package/dist/shell/shell-router.js +19 -3
  93. package/dist/shell/shell.js +252 -22
  94. package/dist/shell/task-context-view.js +40 -0
  95. package/dist/types/index.js +3 -1
  96. package/dist/ui/agent-cards.js +111 -0
  97. package/dist/ui/agent-presentation.js +131 -0
  98. package/dist/ui/approval.js +111 -0
  99. package/dist/ui/banner.js +31 -48
  100. package/dist/ui/btw-overlay.js +230 -0
  101. package/dist/ui/change-review.js +334 -0
  102. package/dist/ui/chat-renderer.js +207 -14
  103. package/dist/ui/colors.js +12 -8
  104. package/dist/ui/command-details.js +11 -0
  105. package/dist/ui/command-filter.js +26 -5
  106. package/dist/ui/command-palette.js +44 -14
  107. package/dist/ui/command-registry.js +92 -10
  108. package/dist/ui/command-review.js +187 -0
  109. package/dist/ui/composer-layout.js +48 -1
  110. package/dist/ui/conversation.js +450 -0
  111. package/dist/ui/interrupt.js +35 -0
  112. package/dist/ui/live.js +4 -2
  113. package/dist/ui/markdown.js +63 -9
  114. package/dist/ui/message.js +14 -31
  115. package/dist/ui/screen-prompt.js +181 -0
  116. package/dist/ui/screen.js +19 -11
  117. package/dist/ui/select.js +191 -29
  118. package/dist/ui/sia-qa.js +213 -0
  119. package/dist/ui/task-context-card.js +99 -0
  120. package/dist/ui/text-prompt.js +74 -0
  121. package/dist/ui/trust.js +88 -0
  122. package/dist/ui/ui.js +27 -1
  123. package/package.json +18 -4
  124. package/dist/ui/activity.js +0 -77
@@ -0,0 +1,213 @@
1
+ import { ApiError } from "../services/api.js";
2
+ import { buildStructuredIntent } from "../services/sia.js";
3
+ import { line } from "../services/output.js";
4
+ import { withSpinner } from "../services/spinner.js";
5
+ import { c } from "./colors.js";
6
+ import { pickFromList, SELECT_BACK } from "./select.js";
7
+ import { askTextInScreen, inScreen, pickInScreen } from "./screen-prompt.js";
8
+ import { askText } from "./text-prompt.js";
9
+ /**
10
+ * Inside the shell, prompts draw into the transcript so the banner and the
11
+ * conversation stay visible above them. Outside it (`cos chat`, a pipe) there
12
+ * is no screen engine, so the terminal-owning versions are used instead.
13
+ */
14
+ const ask = (opts) => inScreen() ? pickInScreen(opts) : pickFromList(opts);
15
+ /**
16
+ * SIA clarification — the terminal counterpart of the website's Q&A overlay.
17
+ *
18
+ * Before an ambiguous prompt is sent, the API is asked what it would need to
19
+ * know; the answers are appended to the prompt and THAT is what gets sent. The
20
+ * questions are a way to write a better prompt, not a separate request — see
21
+ * services/sia.ts for the merge format both clients share.
22
+ *
23
+ * Failures are non-blocking but NOT silent. If the API is unreachable or
24
+ * refuses, the original prompt still goes out — clarification must never be the
25
+ * reason a message can't be sent — but one dim line says so, because with SIA
26
+ * on by default a swallowed error is indistinguishable from the backend
27
+ * deciding no clarification was needed.
28
+ */
29
+ /** Sentinel values that can't collide with a real option value. */
30
+ const OTHER = "\u0000other";
31
+ const SKIP = "\u0000skip";
32
+ const unchanged = (prompt) => ({ prompt, cancelled: false });
33
+ /** Options for one question, plus the two escapes every question offers. */
34
+ function choicesFor(q) {
35
+ const base = q.type === "yn"
36
+ ? [
37
+ { value: "true", label: "Yes" },
38
+ { value: "false", label: "No" }
39
+ ]
40
+ : (q.options ?? []).map((o) => ({
41
+ value: o.value,
42
+ label: o.label,
43
+ description: o.description
44
+ }));
45
+ // No descriptions on these two: the labels already say it, and every
46
+ // description is a row taken from the answers that need one.
47
+ return [...base, { value: OTHER, label: "Other…" }, { value: SKIP, label: "Skip this question" }];
48
+ }
49
+ /** Word-wrap to `width` columns. */
50
+ function wrap(text, width) {
51
+ const w = Math.max(20, width);
52
+ const out = [];
53
+ let cur = "";
54
+ for (const word of text.trim().split(/\s+/).filter(Boolean)) {
55
+ if (cur && [...cur].length + 1 + [...word].length > w) {
56
+ out.push(cur);
57
+ cur = word;
58
+ }
59
+ else {
60
+ cur = cur ? `${cur} ${word}` : word;
61
+ }
62
+ }
63
+ if (cur)
64
+ out.push(cur);
65
+ return out.length ? out : [""];
66
+ }
67
+ /**
68
+ * The block above the options.
69
+ *
70
+ * It restates the prompt on EVERY question, which is not redundancy: a picker
71
+ * takes over the terminal from the shell's screen engine, so the banner and the
72
+ * echoed message are in a buffer the user cannot scroll back to while answering.
73
+ * Without this, the questions appear with no visible sign of what they are about.
74
+ */
75
+ /** Wrap, then hard-limit to `max` lines, marking the cut on the last one. */
76
+ function clampLines(text, width, max) {
77
+ const lines = wrap(text, width);
78
+ if (lines.length <= max)
79
+ return lines;
80
+ const shown = lines.slice(0, max);
81
+ shown[max - 1] = shown[max - 1].replace(/.{0,2}$/, "…");
82
+ return shown;
83
+ }
84
+ function siaHeader(prompt, q, index, total) {
85
+ return (width) => {
86
+ // Every row here is a row of your conversation pushed off screen, and the
87
+ // transcript only gets terminal-height minus the composer. So both blocks
88
+ // are capped: one line to recognise your own message, three for the
89
+ // question — the model pads these to 1-3 sentences and the ask is at the
90
+ // front. The options and their descriptions are what the rows are for.
91
+ const promptLine = clampLines(prompt, width - 2, 1);
92
+ return [
93
+ " " + c.brand("─".repeat(width)),
94
+ " " + c.dim("❯ ") + c.dim(promptLine[0]),
95
+ "",
96
+ " " + c.brand.bold(`Question ${index + 1} of ${total}`),
97
+ ...clampLines(q.text, width, 3).map((l) => " " + c.value(l))
98
+ ];
99
+ };
100
+ }
101
+ /** Index of the choice matching an already-given answer, so stepping back lands
102
+ * on what was picked last time rather than resetting to the top. */
103
+ function initialIndex(choices, previous) {
104
+ if (previous === undefined)
105
+ return 0;
106
+ const want = typeof previous === "boolean" ? String(previous) : previous;
107
+ const at = choices.findIndex((ch) => ch.value === want);
108
+ return at === -1 ? 0 : at;
109
+ }
110
+ /** Ask one question. null = cancelled, "back" = step to the previous question. */
111
+ async function askOne(prompt, q, index, total, previous, canGoBack) {
112
+ const heading = `Question ${index + 1} of ${total}`;
113
+ // An "open" question has nothing to pick from — go straight to free text.
114
+ // There is no list to press ← in, so it is the one step without back.
115
+ if (q.type === "open") {
116
+ const typed = inScreen()
117
+ ? await askTextInScreen(siaHeader(prompt, q, index, total), q.placeholder)
118
+ : await askText(`${heading} ${q.text}`, q.placeholder ?? "Enter to skip");
119
+ return { answer: typed };
120
+ }
121
+ const choices = choicesFor(q);
122
+ const picked = await ask({
123
+ title: heading,
124
+ header: siaHeader(prompt, q, index, total),
125
+ choices,
126
+ initial: initialIndex(choices, previous),
127
+ allowBack: canGoBack,
128
+ // "prev/next" rather than "question": it says you can move BOTH ways
129
+ // through the set, which the noun alone left you to guess.
130
+ backHint: "prev/next question",
131
+ // The descriptions ARE the decision here — a clipped one hides what's
132
+ // being chosen between.
133
+ stacked: true,
134
+ // Esc abandons the message, which "cancel" badly understates when the row
135
+ // above it says "Skip this question".
136
+ cancelHint: "discard message"
137
+ });
138
+ // Esc / Ctrl+C. The website treats Esc as "send it anyway", but in a terminal
139
+ // that gesture means abort — and sending a prompt someone tried to cancel
140
+ // spends real money. So it stops the turn, and "Skip this question" is the
141
+ // explicit way to move past one.
142
+ if (picked === null)
143
+ return null;
144
+ if (picked === SELECT_BACK)
145
+ return "back";
146
+ if (picked === SKIP)
147
+ return { answer: null };
148
+ if (picked === OTHER) {
149
+ const typed = inScreen()
150
+ ? await askTextInScreen(siaHeader(prompt, q, index, total), q.placeholder)
151
+ : await askText(q.text, q.placeholder ?? "Your answer");
152
+ return { answer: typed };
153
+ }
154
+ if (q.type === "yn")
155
+ return { answer: picked === "true" };
156
+ return { answer: picked };
157
+ }
158
+ /**
159
+ * Run the clarification pass for `message`.
160
+ *
161
+ * @param onLookup called when the API round-trip starts, so a caller with a
162
+ * pinned composer can clear its own status area first.
163
+ */
164
+ export async function clarifyIntent(client, message, onLookup) {
165
+ onLookup?.();
166
+ let questions;
167
+ try {
168
+ const res = await withSpinner(c.dim("Clarifying intent…"), () => client.siaQuestions(message));
169
+ if (res.skip || res.questions.length === 0)
170
+ return unchanged(message);
171
+ questions = res.questions;
172
+ }
173
+ catch (err) {
174
+ // Unreachable, unauthorized, rate-limited — none of it should block a chat,
175
+ // so the prompt still goes out unchanged.
176
+ //
177
+ // But it must not be SILENT. With SIA on by default, a swallowed failure is
178
+ // indistinguishable from the backend deciding no clarification was needed —
179
+ // so an expired token looks exactly like SIA working correctly, forever.
180
+ // One dim line is enough to tell the two apart.
181
+ line(" " +
182
+ c.dim("↳ SIA unavailable — sending as typed. ") +
183
+ c.dim(err instanceof ApiError ? "(" + err.code + ")" : ""));
184
+ return unchanged(message);
185
+ }
186
+ // No "a few questions first" banner: it would be written into the shell's
187
+ // transcript, which the picker is about to suspend — so it would be invisible
188
+ // during the Q&A and a stray line afterwards. The count lives in each
189
+ // question's own header instead.
190
+ //
191
+ // A cursor rather than a for-loop: ← steps back, and answers survive the
192
+ // round trip so revisiting a question shows what you already chose.
193
+ const answers = {};
194
+ let i = 0;
195
+ while (i < questions.length) {
196
+ const q = questions[i];
197
+ const result = await askOne(message, q, i, questions.length, answers[q.key], i > 0);
198
+ if (result === null)
199
+ return { prompt: message, cancelled: true };
200
+ if (result === "back") {
201
+ i -= 1;
202
+ continue;
203
+ }
204
+ // Skipping clears any earlier answer — otherwise going back to un-answer a
205
+ // question would silently keep the old value in the prompt.
206
+ if (result.answer === null)
207
+ delete answers[q.key];
208
+ else
209
+ answers[q.key] = result.answer;
210
+ i += 1;
211
+ }
212
+ return { prompt: buildStructuredIntent(message, answers), cancelled: false };
213
+ }
@@ -0,0 +1,99 @@
1
+ import { c } from "./colors.js";
2
+ import { MARGIN } from "./composer-layout.js";
3
+ import { INDENT, cardHeader, cardWidth } from "./agent-cards.js";
4
+ import { clip, stripControl, wrapText } from "./conversation.js";
5
+ /**
6
+ * Task Context presentation: a compact card when a conversation with earlier
7
+ * coding work is resumed, and one restored-context line when a coding turn
8
+ * starts in it. Never the whole context — the existing workflow cards remain
9
+ * the primary record of what happens in the turn.
10
+ */
11
+ const STATE_WORDS = { COMPLETED: "Completed", UNRESOLVED: "Unresolved" };
12
+ const RUN_WORDS = { passed: "passed", failed: "failed", not_approved: "not approved", not_run: "not run", cancelled: "cancelled", timed_out: "timed out", pending: "pending", unresolved: "unresolved", completed: "ran" };
13
+ const LABEL = 13;
14
+ /** `Label value`, with a long value wrapped under itself rather than clipped. */
15
+ function field(name, value) {
16
+ const room = Math.max(12, cardWidth() - LABEL - 2);
17
+ const pad = MARGIN + " ".repeat(LABEL + 2);
18
+ return wrapText(stripControl(value), room).map((part, i) => (i === 0 ? MARGIN + c.dim(name.padEnd(LABEL) + " ") : pad) + c.value(part));
19
+ }
20
+ /** Dim prose that wraps at the card width. */
21
+ const note = (text, prefix = INDENT) => wrapText(text, Math.max(12, cardWidth() - (prefix.length - INDENT.length))).map((l) => prefix + c.dim(l));
22
+ const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
23
+ function filesLine(ctx, state) {
24
+ const t = ctx.current;
25
+ const read = t.investigation.files.length + t.investigation.files_omitted;
26
+ const changed = state.filter((e) => e.status !== "unchanged").length;
27
+ const parts = [`${plural(read, "file")} read`];
28
+ if (t.changes.applied)
29
+ parts.push(`${t.changes.applied} changed by the task`);
30
+ if (changed)
31
+ parts.push(`${changed} changed on disk since`);
32
+ return parts.join(" · ");
33
+ }
34
+ function testsLine(ctx) {
35
+ const last = ctx.current.validation.runs.at(-1);
36
+ if (!last)
37
+ return "none run";
38
+ return `${last.command ?? "command"} ${RUN_WORDS[last.outcome] ?? last.outcome}`;
39
+ }
40
+ const relevantFiles = (ctx) => ctx.current.references ? ctx.current.references.items.length + ctx.current.references.omitted : ctx.current.investigation.files.length + ctx.current.investigation.files_omitted;
41
+ const previousChanges = (ctx) => ctx.current.changes.applied + ctx.earlier_tasks.reduce((n, e) => n + e.files_changed.length, 0);
42
+ /** "shop · main", and whether it is the repository the earlier work used. */
43
+ function repositoryLine(name, repo) {
44
+ const where = repo?.branch ? `${name} · ${repo.branch}` : name;
45
+ if (repo?.same_repository === false)
46
+ return `${where} — a different repository than the earlier work`;
47
+ return where;
48
+ }
49
+ /**
50
+ * Shown when the CLI starts (or resumes) into a conversation with earlier
51
+ * coding work. Small by design: what is being continued, and that the context
52
+ * — never an approval or an operation — was restored.
53
+ */
54
+ export function renderTaskContextCard(ctx, state = [], repo) {
55
+ const t = ctx.current;
56
+ const out = [...cardHeader("CONTINUING TASK")];
57
+ out.push(...field("Repository", repositoryLine(t.repository ?? repo?.name ?? "this repository", repo)));
58
+ out.push(...field("Previous task", t.title));
59
+ const status = STATE_WORDS[t.verified_state] ?? t.verified_state;
60
+ out.push(...field("Status", t.workflow_state && t.verified_state !== "COMPLETED" ? `${status} · workflow ${t.workflow_state}` : status));
61
+ out.push(...field("Files", filesLine(ctx, state)));
62
+ if (t.corrections_total)
63
+ out.push(...field("Corrections", String(t.corrections_total)));
64
+ out.push(...field("Tests", testsLine(ctx)));
65
+ if (t.pending_operations.length) {
66
+ out.push(...field("Unresolved", `${plural(t.pending_operations.length, "operation")} — never resumed; propose again to continue`));
67
+ }
68
+ if (ctx.earlier_tasks.length)
69
+ out.push(...field("Earlier", plural(ctx.earlier_tasks.length + ctx.earlier_tasks_omitted, "task")));
70
+ out.push(repo?.same_repository === false
71
+ ? MARGIN + c.warn("Context not reused: this is a different repository.")
72
+ : MARGIN + c.ok("Context restored ✓"));
73
+ out.push(...note("Context only: files are read again and every change needs new approval.", MARGIN));
74
+ return out;
75
+ }
76
+ /**
77
+ * A small note at the start of a coding turn in a conversation that has a Task
78
+ * Context — never the context itself. Previous changes counts the applied
79
+ * changes the platform recorded across this conversation's coding tasks.
80
+ */
81
+ export function renderTaskContextRestored(ctx, state = [], repository, repo) {
82
+ const t = ctx.current;
83
+ const changedOnDisk = state.filter((e) => e.status !== "unchanged").length;
84
+ const row = (name, value) => MARGIN + " " + c.dim(name.padEnd(18)) + c.value(clip(stripControl(value), Math.max(8, cardWidth() - 20)));
85
+ if (repo?.same_repository === false) {
86
+ return ["", MARGIN + c.warn("Previous task context not reused"), row("Repository", repo.branch ? `${repo.name} · ${repo.branch}` : repo.name),
87
+ ...note("This is a different repository than the earlier work, so this task starts fresh.", MARGIN + " ")];
88
+ }
89
+ return [
90
+ "",
91
+ MARGIN + c.title("Using previous task context"),
92
+ row("Repository", repositoryLine(t.repository ?? repository ?? "this repository", repo)),
93
+ row("Previous task", t.title),
94
+ row("Relevant files", String(relevantFiles(ctx))),
95
+ row("Previous changes", String(previousChanges(ctx))),
96
+ ...(changedOnDisk ? [row("Changed on disk", `${changedOnDisk} file${changedOnDisk === 1 ? "" : "s"} since then`)] : []),
97
+ ...note("Context only: files are read again and every change needs new approval.", MARGIN + " ")
98
+ ];
99
+ }
@@ -0,0 +1,74 @@
1
+ import * as readline from "node:readline";
2
+ import { c } from "./colors.js";
3
+ import { resumeScreen, screenActive, suspendScreen } from "./screen.js";
4
+ import { termWidth } from "./ui.js";
5
+ /** Word-wrap to `width` columns. */
6
+ function wrap(text, width) {
7
+ const w = Math.max(20, width);
8
+ const lines = [];
9
+ let cur = "";
10
+ for (const word of text.trim().split(/\s+/).filter(Boolean)) {
11
+ if (cur && [...cur].length + 1 + [...word].length > w) {
12
+ lines.push(cur);
13
+ cur = word;
14
+ }
15
+ else {
16
+ cur = cur ? `${cur} ${word}` : word;
17
+ }
18
+ }
19
+ if (cur)
20
+ lines.push(cur);
21
+ return lines.length ? lines : [""];
22
+ }
23
+ /**
24
+ * A one-line free-text prompt, for the places a list can't answer the question
25
+ * — SIA's "open" questions and the "Other…" escape on every other type.
26
+ *
27
+ * Deliberately NOT @inquirer: the picker next door avoids it because handing
28
+ * stdin back and forth froze the composer, and this has to interleave with the
29
+ * same pinned-composer engine. Cooked mode is restored for the duration so
30
+ * readline owns line editing (backspace, arrows, paste), then handed back.
31
+ *
32
+ * Resolves the trimmed answer, or null if it was empty or cancelled.
33
+ */
34
+ export function askText(label, placeholder) {
35
+ const stdin = process.stdin;
36
+ const stdout = process.stdout;
37
+ if (!stdin.isTTY)
38
+ return Promise.resolve(null);
39
+ return new Promise((resolve) => {
40
+ const suspended = screenActive();
41
+ if (suspended)
42
+ suspendScreen();
43
+ // The picker leaves keypress listeners and raw mode behind; readline needs
44
+ // neither, and a stale listener would eat the typed characters.
45
+ stdin.removeAllListeners("keypress");
46
+ const prevRaw = stdin.isRaw ?? false;
47
+ if (stdin.isTTY)
48
+ stdin.setRawMode(false);
49
+ stdin.resume();
50
+ // Wrap to the terminal, at word boundaries. A SIA question is a full
51
+ // sentence or three, and left raw the terminal breaks it mid-word.
52
+ const width = Math.min(termWidth() - 4, 92);
53
+ stdout.write("\n");
54
+ for (const l of wrap(label, width))
55
+ stdout.write(" " + c.title(l) + "\n");
56
+ if (placeholder)
57
+ stdout.write(" " + c.dim(placeholder) + "\n");
58
+ const rl = readline.createInterface({ input: stdin, output: stdout, terminal: true });
59
+ let settled = false;
60
+ const finish = (value) => {
61
+ if (settled)
62
+ return;
63
+ settled = true;
64
+ rl.close();
65
+ if (stdin.isTTY)
66
+ stdin.setRawMode(prevRaw);
67
+ if (suspended)
68
+ resumeScreen();
69
+ resolve(value);
70
+ };
71
+ rl.question(" " + c.brandFixed("❯ "), (answer) => finish(answer.trim() || null));
72
+ rl.on("SIGINT", () => finish(null));
73
+ });
74
+ }
@@ -0,0 +1,88 @@
1
+ import { folderKey, isTrustedFolder } from "../services/folder-key.js";
2
+ import { c } from "./colors.js";
3
+ import { pickFromList } from "./select.js";
4
+ /**
5
+ * Workspace trust — the safety check shown the first time the CLI is opened in
6
+ * a folder, before anything reads from it.
7
+ *
8
+ * This is not decoration. `detectLocalFiles` resolves a leading token in your
9
+ * message against the current directory and uploads any file it matches, and
10
+ * `cos upload` reads paths directly — so a bare filename can send a local file
11
+ * to the Carrier OS API. The answer is remembered per folder in the CLI config.
12
+ */
13
+ /** Trust keys are canonical folder identities — see services/folder-key.ts. */
14
+ const normalize = folderKey;
15
+ export function isTrusted(config, dir = process.cwd()) {
16
+ return isTrustedFolder(config.get("trustedFolders") ?? [], dir);
17
+ }
18
+ export function trustFolder(config, dir = process.cwd()) {
19
+ const key = normalize(dir);
20
+ const list = config.get("trustedFolders") ?? [];
21
+ if (list.includes(key))
22
+ return;
23
+ // Bounded so the config can't grow without limit; oldest entries drop first.
24
+ config.set("trustedFolders", [...list, key].slice(-200));
25
+ }
26
+ /** Plain-text word wrap. No ANSI here — color is applied per whole line below. */
27
+ function wrap(text, width) {
28
+ const w = Math.max(20, width);
29
+ const lines = [];
30
+ let cur = "";
31
+ for (const word of text.trim().split(/\s+/).filter(Boolean)) {
32
+ if (cur && cur.length + 1 + word.length > w) {
33
+ lines.push(cur);
34
+ cur = word;
35
+ }
36
+ else {
37
+ cur = cur ? `${cur} ${word}` : word;
38
+ }
39
+ }
40
+ if (cur)
41
+ lines.push(cur);
42
+ return lines;
43
+ }
44
+ /** Exported so the screen can be rendered without a TTY (preview / tests). */
45
+ export function workspaceTrustLines(dir, width) {
46
+ const body = (text) => wrap(text, width).map((l) => " " + c.value(l));
47
+ return [
48
+ " " + c.warn("─".repeat(width)),
49
+ " " + c.warn.bold("Accessing local repository:"),
50
+ "",
51
+ " " + c.title(dir),
52
+ "",
53
+ ...body("Quick safety check: Is this a project you created or one you trust? " +
54
+ "(Like your own code, a well-known open source project, or work from your team). " +
55
+ "If not, take a moment to review what's in this folder first."),
56
+ "",
57
+ ...body("Carrier OS can read referenced files in this repository and send their contents to Carrier OS using your signed-in user account and CLI device session. File changes and commands require their own approval."),
58
+ "",
59
+ ...body("Normal CLI login uses your CarrierOS account. No Developer Platform workspace, project or API key is required.")
60
+ ];
61
+ }
62
+ /**
63
+ * Ask once per folder. Returns false only when the user declines, which callers
64
+ * treat as "exit without doing anything".
65
+ *
66
+ * Non-TTY runs (pipes, CI) can't answer a prompt, so they proceed — the check
67
+ * is a guard for interactive use, not an authorization boundary.
68
+ */
69
+ export async function ensureWorkspaceTrust(config, dir = process.cwd()) {
70
+ if (!process.stdin.isTTY)
71
+ return true;
72
+ if (isTrusted(config, dir))
73
+ return true;
74
+ const choice = await pickFromList({
75
+ title: "",
76
+ header: (width) => workspaceTrustLines(dir, width),
77
+ choices: [
78
+ { value: "trust", label: "Yes, I trust this folder" },
79
+ { value: "exit", label: "No, exit" }
80
+ ],
81
+ initial: 0,
82
+ confirmOnNumber: true
83
+ });
84
+ if (choice !== "trust")
85
+ return false;
86
+ trustFolder(config, dir);
87
+ return true;
88
+ }
package/dist/ui/ui.js CHANGED
@@ -8,7 +8,10 @@ import { c } from "./colors.js";
8
8
  export const icon = {
9
9
  ok: c.ok("✓"),
10
10
  warn: c.warn("!"),
11
- info: c.info("i"),
11
+ // Informational lines are context, not status — a muted corner-down-right
12
+ // reads as "and then this happened" instead of competing with ✓ / ! / ✕ for
13
+ // attention. U+21B3 is in the base arrows block, so it renders everywhere.
14
+ info: c.dim("↳"),
12
15
  err: c.err("✕"),
13
16
  bullet: c.accent("•"),
14
17
  arrow: c.dim("›"),
@@ -19,6 +22,29 @@ export function termWidth(fallback = 80) {
19
22
  const w = process.stdout.columns;
20
23
  return w && w > 0 ? w : fallback;
21
24
  }
25
+ const UNITS = [[1e9, "B"], [1e6, "M"], [1e3, "K"]];
26
+ /**
27
+ * A large number the way dashboards show it: 12.47K, 1.25M — at most two
28
+ * decimals, trailing zeros dropped. Below 1,000, `small` formats it.
29
+ */
30
+ export function compactNumber(n, small) {
31
+ for (const [size, unit] of UNITS) {
32
+ // 999.996 rounds to 1,000.00 — that is "1K", not "1,000.00".
33
+ if (Math.abs(n) >= size * 0.999995)
34
+ return (n / size).toLocaleString("en-US", { maximumFractionDigits: 2 }) + unit;
35
+ }
36
+ return small(n);
37
+ }
38
+ /**
39
+ * A credit amount, everywhere credits appear: compact from 1,000 up (12.47K,
40
+ * 1.25M) and two decimals below it (23.67). A non-zero amount too small to
41
+ * show reads "<0.01" rather than a misleading "0.00".
42
+ */
43
+ export function formatCredits(n) {
44
+ if (n !== 0 && Math.abs(n) < 0.005)
45
+ return "<0.01";
46
+ return compactNumber(n, (v) => v.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 }));
47
+ }
22
48
  /** Visible length of a string, ignoring ANSI color codes. */
23
49
  export function visibleLen(s) {
24
50
  // eslint-disable-next-line no-control-regex
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@carrieros/cli",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "private": false,
5
5
  "description": "Carrier OS command-line interface — an interactive shell plus commands for the Carrier OS developer platform (chat, sessions, files, usage) over the public /v1 API.",
6
6
  "type": "module",
@@ -18,11 +18,21 @@
18
18
  "scripts": {
19
19
  "clean": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\"",
20
20
  "prebuild": "npm run clean",
21
- "build": "tsc -p tsconfig.json",
21
+ "build": "tsc -p tsconfig.json && node -e \"require('node:fs').chmodSync('dist/main.js', 0o755)\"",
22
22
  "dev": "tsx src/main.ts",
23
23
  "start": "node dist/main.js",
24
24
  "typecheck": "tsc --noEmit",
25
- "prepare": "npm run build"
25
+ "test": "npm run build && node --test \"test/*.test.mjs\"",
26
+ "prepack": "npm run build",
27
+ "test:pty": "npm run build && node test/acceptance/pty-selftest.mjs",
28
+ "test:execution": "npm run build && node scripts/validate-execution.mjs",
29
+ "test:acceptance": "npm run build && node test/acceptance/live-acceptance.mjs",
30
+ "build:helpers": "node scripts/build-helpers.mjs",
31
+ "bundle": "npm run build && node scripts/bundle.mjs",
32
+ "sea:blob": "node --experimental-sea-config sea-config.json",
33
+ "package:win": "node scripts/package-win.mjs",
34
+ "test:exe": "node test/acceptance/packaged-exe.mjs",
35
+ "rehash-helpers": "node scripts/rehash-helpers.mjs"
26
36
  },
27
37
  "keywords": [
28
38
  "carrieros",
@@ -54,10 +64,14 @@
54
64
  "chalk": "^5.3.0",
55
65
  "commander": "^12.1.0",
56
66
  "form-data": "^4.0.1",
57
- "ora": "^8.1.1"
67
+ "ora": "^8.1.1",
68
+ "string-width": "7.2.0"
58
69
  },
59
70
  "devDependencies": {
71
+ "@lydell/node-pty": "^1.2.0-beta.15",
60
72
  "@types/node": "^22.10.2",
73
+ "esbuild": "^0.28.2",
74
+ "postject": "1.0.0-alpha.6",
61
75
  "tsx": "^4.19.2",
62
76
  "typescript": "^5.7.2"
63
77
  }
@@ -1,77 +0,0 @@
1
- import { c } from "./colors.js";
2
- import { MARGIN } from "./composer-layout.js";
3
- /**
4
- * A live activity timeline — the "thinking" phase, Claude-style but TRUTHFUL to
5
- * the Carrier OS architecture. The CLI only talks to the public API, so steps
6
- * reflect what actually happens (understand the request → select the Carrier
7
- * mode → route to the API → wait for the model), never fabricated file/tool
8
- * actions.
9
- *
10
- * It renders into the composer's transient status region: completed steps dim to
11
- * a ●, and only the current step spins. The shell drives it by emitting phase
12
- * events (request_started → mode_selected → request_sent → waiting → done),
13
- * which map 1:1 to `step()` calls — new backend capabilities (search, files,
14
- * vision, agents…) plug in as extra steps without changing this renderer.
15
- */
16
- const FRAMES = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏";
17
- export function startActivity(live) {
18
- const steps = [];
19
- let frame = 0;
20
- const paint = () => {
21
- live.setStatus(steps.map((s, i) => {
22
- const active = !s.done && i === steps.length - 1;
23
- const marker = s.done
24
- ? c.dim("●")
25
- : active
26
- ? c.brand(FRAMES[frame % FRAMES.length])
27
- : c.dim("○");
28
- return MARGIN + marker + " " + c.dim(active ? `${s.label}…` : s.label);
29
- }));
30
- };
31
- const timer = setInterval(() => {
32
- frame++;
33
- paint();
34
- }, 90);
35
- timer.unref?.();
36
- return {
37
- step(label) {
38
- if (steps.length)
39
- steps[steps.length - 1].done = true;
40
- steps.push({ label, done: false });
41
- paint();
42
- },
43
- done() {
44
- for (const s of steps)
45
- s.done = true;
46
- paint();
47
- },
48
- stop() {
49
- clearInterval(timer);
50
- }
51
- };
52
- }
53
- /**
54
- * Truthful activity steps for a chat turn, flavored by the Carrier mode. The
55
- * FIRST steps are brief client-side phases; the LAST step is the one that spins
56
- * while genuinely awaiting the model's response.
57
- */
58
- export function chatActivitySteps(modeLabel) {
59
- const lower = modeLabel.toLowerCase();
60
- if (lower === "code" || lower === "debug") {
61
- return ["Detecting coding task", `Selecting ${modeLabel} mode`, "Routing to Carrier OS", "Generating solution"];
62
- }
63
- if (lower === "research") {
64
- return [
65
- "Understanding your request",
66
- `Selecting ${modeLabel} mode`,
67
- "Routing to Carrier OS",
68
- "Synthesizing response"
69
- ];
70
- }
71
- return [
72
- "Understanding your request",
73
- `Selecting ${modeLabel} mode`,
74
- "Routing to Carrier OS",
75
- "Waiting for the model"
76
- ];
77
- }