@carrieros/cli-staging 0.0.0-stage → 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 (136) hide show
  1. package/README.md +6 -2
  2. package/dist/commands/attach.js +45 -0
  3. package/dist/commands/auth.js +60 -0
  4. package/dist/commands/btw.js +78 -0
  5. package/dist/commands/changes.js +167 -0
  6. package/dist/commands/chat.js +182 -0
  7. package/dist/commands/context.js +200 -0
  8. package/dist/commands/doctor.js +119 -0
  9. package/dist/commands/files.js +94 -0
  10. package/dist/commands/help.js +37 -0
  11. package/dist/commands/history.js +112 -0
  12. package/dist/commands/login.js +62 -0
  13. package/dist/commands/logout.js +25 -0
  14. package/dist/commands/memory.js +162 -0
  15. package/dist/commands/mode-model.js +64 -0
  16. package/dist/commands/models.js +28 -0
  17. package/dist/commands/modes.js +30 -0
  18. package/dist/commands/permissions.js +77 -0
  19. package/dist/commands/project.js +106 -0
  20. package/dist/commands/repo.js +146 -0
  21. package/dist/commands/repos.js +61 -0
  22. package/dist/commands/review.js +92 -0
  23. package/dist/commands/scope.js +155 -0
  24. package/dist/commands/search.js +92 -0
  25. package/dist/commands/sessions.js +282 -0
  26. package/dist/commands/settings.js +100 -0
  27. package/dist/commands/update.js +229 -0
  28. package/dist/commands/upload.js +223 -0
  29. package/dist/commands/usage.js +227 -0
  30. package/dist/commands/version.js +26 -0
  31. package/dist/commands/whoami.js +44 -0
  32. package/dist/ide/editor-context.js +275 -0
  33. package/dist/ide/ide-session.js +360 -0
  34. package/dist/ide/tool-host.js +109 -0
  35. package/dist/main.js +126 -0
  36. package/dist/services/api.js +439 -0
  37. package/dist/services/auth-origin.js +20 -0
  38. package/dist/services/chat-stream.js +168 -0
  39. package/dist/services/checkpoints.js +278 -0
  40. package/dist/services/client-tools.js +356 -0
  41. package/dist/services/code-intel.js +243 -0
  42. package/dist/services/code-symbols.js +94 -0
  43. package/dist/services/coding-workflow.js +554 -0
  44. package/dist/services/command-coordinator.js +273 -0
  45. package/dist/services/command-policy.js +434 -0
  46. package/dist/services/config.js +383 -0
  47. package/dist/services/container-runner.js +254 -0
  48. package/dist/services/container-supervisor.js +38 -0
  49. package/dist/services/context.js +371 -0
  50. package/dist/services/device-auth.js +286 -0
  51. package/dist/services/diff.js +196 -0
  52. package/dist/services/env-policy.js +108 -0
  53. package/dist/services/execution-platform.js +30 -0
  54. package/dist/services/file-detect.js +104 -0
  55. package/dist/services/file-resolver.js +199 -0
  56. package/dist/services/file-upload.js +126 -0
  57. package/dist/services/folder-key.js +22 -0
  58. package/dist/services/git-tools.js +429 -0
  59. package/dist/services/glob-match.js +164 -0
  60. package/dist/services/helper-bin.js +85 -0
  61. package/dist/services/ignore-rules.js +189 -0
  62. package/dist/services/instruction-resolver.js +54 -0
  63. package/dist/services/job-helper.js +328 -0
  64. package/dist/services/local-files.js +639 -0
  65. package/dist/services/local-tools.js +937 -0
  66. package/dist/services/login-flow.js +156 -0
  67. package/dist/services/meta.js +15 -0
  68. package/dist/services/mutation-coordinator.js +327 -0
  69. package/dist/services/mutation-groups.js +309 -0
  70. package/dist/services/mutation-recovery.js +159 -0
  71. package/dist/services/mutations.js +679 -0
  72. package/dist/services/open-url.js +68 -0
  73. package/dist/services/output.js +62 -0
  74. package/dist/services/packaged-update.js +403 -0
  75. package/dist/services/packaged.js +39 -0
  76. package/dist/services/permission-mode.js +78 -0
  77. package/dist/services/process-runner.js +412 -0
  78. package/dist/services/project-context.js +298 -0
  79. package/dist/services/redaction.js +201 -0
  80. package/dist/services/result-reconciliation.js +49 -0
  81. package/dist/services/secure-store.js +217 -0
  82. package/dist/services/session-resolver.js +113 -0
  83. package/dist/services/sia.js +51 -0
  84. package/dist/services/spinner.js +40 -0
  85. package/dist/services/supported-runtime.js +59 -0
  86. package/dist/services/task-context.js +212 -0
  87. package/dist/services/task-snapshot.js +38 -0
  88. package/dist/services/tool-result-outbox.js +195 -0
  89. package/dist/services/update.js +311 -0
  90. package/dist/services/workspace-registry.js +310 -0
  91. package/dist/services/workspace.js +580 -0
  92. package/dist/shell/shell-chat.js +1619 -0
  93. package/dist/shell/shell-commands.js +411 -0
  94. package/dist/shell/shell-prompt.js +110 -0
  95. package/dist/shell/shell-renderer.js +51 -0
  96. package/dist/shell/shell-router.js +37 -0
  97. package/dist/shell/shell.js +389 -0
  98. package/dist/shell/task-context-view.js +40 -0
  99. package/dist/staging.js +5 -0
  100. package/dist/types/index.js +6 -0
  101. package/dist/ui/agent-cards.js +111 -0
  102. package/dist/ui/agent-presentation.js +131 -0
  103. package/dist/ui/approval.js +111 -0
  104. package/dist/ui/banner.js +56 -0
  105. package/dist/ui/btw-overlay.js +230 -0
  106. package/dist/ui/change-review.js +334 -0
  107. package/dist/ui/chat-renderer.js +463 -0
  108. package/dist/ui/code-block.js +52 -0
  109. package/dist/ui/color-picker.js +100 -0
  110. package/dist/ui/colors.js +55 -0
  111. package/dist/ui/command-details.js +11 -0
  112. package/dist/ui/command-filter.js +92 -0
  113. package/dist/ui/command-item.js +6 -0
  114. package/dist/ui/command-palette.js +383 -0
  115. package/dist/ui/command-registry.js +128 -0
  116. package/dist/ui/command-renderer.js +55 -0
  117. package/dist/ui/command-review.js +187 -0
  118. package/dist/ui/composer-layout.js +74 -0
  119. package/dist/ui/conversation.js +450 -0
  120. package/dist/ui/interrupt.js +35 -0
  121. package/dist/ui/live.js +141 -0
  122. package/dist/ui/logo.js +58 -0
  123. package/dist/ui/markdown.js +205 -0
  124. package/dist/ui/message.js +21 -0
  125. package/dist/ui/screen-prompt.js +181 -0
  126. package/dist/ui/screen.js +297 -0
  127. package/dist/ui/select.js +284 -0
  128. package/dist/ui/sia-qa.js +213 -0
  129. package/dist/ui/spinner.js +23 -0
  130. package/dist/ui/sticky-stream.js +64 -0
  131. package/dist/ui/task-context-card.js +99 -0
  132. package/dist/ui/text-prompt.js +74 -0
  133. package/dist/ui/theme.js +80 -0
  134. package/dist/ui/trust.js +88 -0
  135. package/dist/ui/ui.js +101 -0
  136. package/package.json +33 -4
@@ -0,0 +1,131 @@
1
+ import path from 'node:path';
2
+ import { c } from './colors.js';
3
+ import { MARGIN, contentWidth } from './composer-layout.js';
4
+ import { clip, stripControl, wrapText } from './conversation.js';
5
+ import { INDENT, cardField, cardHeader, cardWidth } from './agent-cards.js';
6
+ import { displayCommand } from '../services/command-policy.js';
7
+ export const ACTIVITY = {
8
+ IDLE: 'Ready', THINKING: 'Thinking', INSPECTING: 'Inspecting repository', SEARCHING: 'Searching repository', READING: 'Reading files', PLANNING: 'Creating plan', PROPOSAL_READY: 'Change proposed', WAITING_FOR_MUTATION_APPROVAL: 'Waiting for change approval', APPLYING: 'Applying changes', VALIDATION_PENDING: 'Validation pending', WAITING_FOR_COMMAND_APPROVAL: 'Waiting for command approval', RUNNING_COMMAND: 'Running command', ANALYZING_FAILURE: 'Analyzing failure', CORRECTION_PROPOSED: 'Correction proposed', WAITING_FOR_CORRECTION_APPROVAL: 'Waiting for correction approval', RETESTING: 'Retesting', COMPLETED: 'Completed', FAILED: 'Failed', CANCELLED: 'Cancelled', UNRESOLVED: 'Unresolved'
9
+ };
10
+ export function workflowActivity(snapshot) {
11
+ const state = String(snapshot.state), correction = Number(snapshot.corrections) > 0;
12
+ if (state === 'COMPLETED')
13
+ return 'Validation passed · awaiting completion';
14
+ if (state === 'READING')
15
+ return correction ? 'Preparing correction' : 'Preparing changes';
16
+ if (state === 'APPLYING' || state === 'REAPPLYING') {
17
+ const validation = snapshot.validation;
18
+ if (validation?.some(v => v.status === 'PENDING_REVIEW'))
19
+ return correction ? 'Retest required' : 'Validation pending';
20
+ return correction ? 'Applying correction' : 'Applying changes';
21
+ }
22
+ const names = { TASK_RECEIVED: 'Thinking', INSPECTING: 'Inspecting repository', PLANNING: 'Creating plan', CAPABILITY_CHECK: 'Checking execution capability', READING: correction ? 'Preparing correction' : 'Preparing changes', PROPOSING: 'Change proposed', AWAITING_APPROVAL: 'Waiting for change approval', APPLYING: correction ? 'Applying correction' : 'Applying changes', TESTING: 'Running validation', ANALYZING_FAILURE: 'Analyzing failure', CORRECTIVE_PROPOSAL: 'Correction proposed', CORRECTIVE_APPROVAL: 'Waiting for correction approval', REAPPLYING: 'Applying correction', RETESTING: 'Retesting', COMPLETED: 'Completed', FAILED: 'Failed', CANCELLED: 'Cancelled', UNRESOLVED: 'Unresolved' };
23
+ return names[state] ?? 'Thinking';
24
+ }
25
+ const commandLabel = (t) => typeof t.program === 'string' ? `${displayCommand(t.program, Array.isArray(t.args) ? t.args.map(String) : [])}${t.cwd && t.cwd !== '.' ? ` · ${t.cwd}` : ''}` : '';
26
+ /** The recorded analysis text, from the workflow's own "Failure analysis (…): …" line. */
27
+ export function analysisExplanation(lines) {
28
+ const m = /^Failure analysis \(([^)]+)\):\s*([\s\S]*)$/.exec(stripControl(lines.join(' ')));
29
+ return { classification: m?.[1] ?? 'recorded', explanation: m?.[2] ?? stripControl(lines.join(' ')) };
30
+ }
31
+ /**
32
+ * The PLAN card: the workflow's own structured plan (snapshot.plan), not a copy.
33
+ * "Root cause" appears only where the workflow recorded one — the failure
34
+ * analysis behind a corrective plan. An initial plan has no such field, so it
35
+ * shows the planned expected behavior instead of inventing a cause.
36
+ */
37
+ export function renderAgentPlan(snapshot, opts = {}) {
38
+ const plan = snapshot.plan;
39
+ if (!plan)
40
+ return [];
41
+ const corrective = Number(snapshot.corrections) > 0;
42
+ const rows = [...cardHeader(corrective ? 'CORRECTIVE PLAN' : 'PLAN', c.title)];
43
+ rows.push(...cardField('Task', clip(stripControl(plan.summary), 240)));
44
+ const inv = plan.investigation;
45
+ if (corrective && opts.rootCause)
46
+ rows.push(...cardField('Root cause', clip(stripControl(opts.rootCause), 240)));
47
+ else if (inv) {
48
+ // The investigation the workflow verified, symptom first: where it shows, why, where to change.
49
+ rows.push(...cardField('Symptom', clip(stripControl(inv.symptom), 200), c.dim));
50
+ rows.push(...cardField('Path', inv.execution_path.slice(0, 8).map(s => s.symbol ? `${s.path} · ${s.symbol}` : s.path), c.file));
51
+ rows.push(...cardField('Root cause', clip(stripControl(inv.root_cause), 240)));
52
+ rows.push(...cardField('Change at', `${inv.change_location.path}${inv.change_location.symbol ? ` · ${inv.change_location.symbol}` : ''}`, c.file));
53
+ if (inv.evidence?.length)
54
+ rows.push(...cardField('Evidence', inv.evidence.slice(0, 4).map(e => clip(stripControl(`${e.path}${e.lines ? `:${e.lines}` : ''} — ${e.note}`), 160)), c.dim));
55
+ if (inv.ruled_out?.length)
56
+ rows.push(...cardField('Ruled out', inv.ruled_out.slice(0, 4).map(r => clip(stripControl(`${r.path} — ${r.reason}`), 160)), c.dim));
57
+ }
58
+ else if (plan.expected)
59
+ rows.push(...cardField('Expected', clip(stripControl(plan.expected), 200), c.dim));
60
+ rows.push(...cardField('Files', plan.files.slice(0, 8).map(f => f.path), c.file));
61
+ if (plan.files.length > 8)
62
+ rows.push(INDENT + c.dim(`+${plan.files.length - 8} more planned files`));
63
+ rows.push(...cardField('Validation', plan.tests.slice(0, 3).map(t => commandLabel(t)).filter(Boolean)));
64
+ if (plan.risks)
65
+ rows.push(...cardField('Risk', clip(stripControl(plan.risks), 160), c.dim));
66
+ rows.push('');
67
+ return rows;
68
+ }
69
+ /**
70
+ * The analysis the workflow recorded after a failed validation — classification
71
+ * and the stated evidence, as recorded by coding_workflow(analyze). It is the
72
+ * tool's input, shown as an operational record, not hidden reasoning.
73
+ */
74
+ export function renderFailureAnalysis(lines) {
75
+ const { classification, explanation } = analysisExplanation(lines);
76
+ const out = ['', MARGIN + c.title('Analyzing failure…'), MARGIN + ' ' + c.ok('✓ ') + c.value('Failure evidence captured') + c.dim(` · ${classification}`)];
77
+ for (const line of wrapText(explanation, cardWidth() - 2))
78
+ out.push(INDENT + ' ' + c.dim(line));
79
+ out.push(MARGIN + c.dim('Fresh reads and a new plan come next; any correction needs its own approval.'), '');
80
+ return out;
81
+ }
82
+ /** Called only after the shell's existing interrupt/acknowledged-finish guard. */
83
+ export function renderAgentOutcome(snapshot, ctx = {}) {
84
+ if (!snapshot.plan)
85
+ return [];
86
+ const plan = snapshot.plan;
87
+ const state = String(snapshot.state), files = Array.isArray(snapshot.files) ? snapshot.files.map(String) : [];
88
+ const validation = (snapshot.validation ?? []);
89
+ const corrections = Number(snapshot.corrections) || 0;
90
+ const applied = ctx.applied ?? [];
91
+ // A person's "no" is a decision, not a failure (the workflow still records
92
+ // FAILED), and an invalidated change is a safety stop. Each already has its
93
+ // own card at the moment it happened (CHANGE REJECTED / CHANGE INVALIDATED),
94
+ // so the turn ends there — no second card, and never "Failed".
95
+ if (ctx.declined && applied.length === 0)
96
+ return [];
97
+ const changed = files.length ? files : [...new Set(applied.map(a => a.rel))];
98
+ const commands = validation.map(t => commandLabel(t) + (t.status ? ` — ${t.status === 'PASSED' ? 'passed' : t.status === 'FAILED' ? 'failed' : 'not completed'}` : '')).filter(Boolean);
99
+ if (state === 'COMPLETED') {
100
+ // The validation counts arrive as "3 passed · 0 failed"; one fact per line.
101
+ const counts = (ctx.validationCounts ?? '').split(' · ').filter(Boolean);
102
+ const changes = `${changed.length} file${changed.length === 1 ? '' : 's'} modified${applied.length > changed.length ? ` · ${applied.length} approved changes` : ''}`;
103
+ return [...cardHeader('✓ COMPLETED', c.ok),
104
+ ...cardField('Task', clip(stripControl(ctx.task ?? plan.summary), 200)),
105
+ ...cardField('Changes', changes),
106
+ ...cardField('Validation', [...validation.map(commandLabel).filter(Boolean), ...counts]),
107
+ ...cardField('Corrections', String(corrections)),
108
+ ...cardField('Files modified', changed.slice(0, 8), c.file),
109
+ ...(changed.length > 8 ? [INDENT + c.dim(`+${changed.length - 8} more`)] : []),
110
+ ...cardField('Operation IDs', applied.map(a => a.operationId), c.dim),
111
+ '', MARGIN + c.ok('✓ ') + c.value(validation.length && validation.every(v => v.status === 'PASSED') ? 'The issue has been fixed and verified.' : 'The task completed.'), ''];
112
+ }
113
+ const title = state === 'CANCELLED' ? '⊘ CANCELLED' : state === 'FAILED' ? '✗ FAILED' : '! UNRESOLVED';
114
+ const reason = state === 'CANCELLED' ? 'The turn stopped. Review retained changes before continuing.' : state === 'FAILED' ? 'The workflow stopped. Review the step above, then start a new task.' : 'Required validation or acknowledgment is incomplete. Nothing resumes automatically.';
115
+ return [...cardHeader(title, state === 'CANCELLED' ? c.warn : c.err), ...wrapText(reason, cardWidth()).map(l => MARGIN + c.dim(l)),
116
+ ...cardField('Applied', applied.map(a => `${a.rel} · +${a.added} −${a.removed} · ${a.operationId}`), c.file),
117
+ ...cardField('Validation', commands), ''];
118
+ }
119
+ export function toolActivity(name, args, root) {
120
+ // A search is named by what it looks for; its directory only narrows it.
121
+ if (name === 'search_files' && typeof args.query === 'string')
122
+ return clip(`Searching ${stripControl(args.query)}${typeof args.path === 'string' && args.path ? ` in ${stripControl(args.path)}` : ''}`, contentWidth() - 6);
123
+ if (name === 'find_symbol' && typeof args.name === 'string')
124
+ return clip(`Finding definition ${stripControl(args.name)}`, contentWidth() - 6);
125
+ if (name === 'find_references' && typeof args.name === 'string')
126
+ return clip(`Finding usages ${stripControl(args.name)}`, contentWidth() - 6);
127
+ const raw = String(args.path ?? args.query ?? args.pattern ?? args.reference ?? args.revision ?? '');
128
+ const value = path.isAbsolute(raw) && !path.relative(root, raw).startsWith('..') ? path.relative(root, raw) : raw;
129
+ const labels = { read_file: 'Reading', search_files: 'Searching', list_files: 'Inspecting repository', find_files: 'Finding files', git_log: 'Reading history', git_blame: 'Reading blame', git_show: 'Reading commit', git_status: 'Inspecting repository', git_diff: 'Inspecting changes', resolve_local_file: 'Finding file', code_outline: 'Outlining', coding_workflow: args.action === 'analyze' ? 'Analyzing failure' : args.action === 'plan' ? 'Creating plan' : 'Checking workflow', run_command: 'Preparing command', edit_file: 'Preparing change', write_file: 'Preparing change', create_file: 'Preparing change', delete_file: 'Preparing deletion', revert_change: 'Preparing revert' };
130
+ return clip(`${labels[name] ?? 'Inspecting'}${value ? ' ' + stripControl(value) : ''}`, contentWidth() - 6);
131
+ }
@@ -0,0 +1,111 @@
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("Type y + Enter to approve · empty 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("y + Enter approves · Enter/") + c.key("n") + c.dim(" declines · ") + c.key("Ctrl+C") + c.dim(" stops · ") + c.dim(countdown(msLeft));
25
+ const room = contentWidth() - 6;
26
+ if (contentWidth() < 70)
27
+ return [
28
+ MARGIN + c.title(question),
29
+ MARGIN + c.dim("y + Enter approves"),
30
+ MARGIN + c.dim("Enter/n declines"),
31
+ MARGIN + c.dim(`Ctrl+C stops · ${countdown(msLeft)}`)
32
+ ];
33
+ return [
34
+ MARGIN + " " + c.warn("?") + " " + c.title(question) + " " + c.dim("(y/N)"),
35
+ MARGIN + " " + (visibleWidth(hint) <= room ? hint : short)
36
+ ];
37
+ }
38
+ export function askApproval(opts) {
39
+ return new Promise((resolve) => {
40
+ const deadline = Date.now() + opts.timeoutMs;
41
+ let done = false;
42
+ let candidate = false;
43
+ let confirming = false;
44
+ const paint = () => screenTransient(approvalFrame(opts.question, deadline - Date.now()));
45
+ const finish = (value) => {
46
+ if (done)
47
+ return;
48
+ done = true;
49
+ clearInterval(timer);
50
+ process.stdout.removeListener("resize", paint);
51
+ opts.signal?.removeEventListener?.("abort", onAbort);
52
+ setImmediate(() => {
53
+ release();
54
+ screenTransient([]);
55
+ resolve(value);
56
+ });
57
+ };
58
+ function onAbort() {
59
+ finish("cancel");
60
+ }
61
+ const onKey = (str, key) => {
62
+ if (done || (!key && !str))
63
+ return;
64
+ if (Date.now() >= deadline)
65
+ return finish("timeout");
66
+ if (opts.signal?.aborted)
67
+ return finish("cancel");
68
+ if (key?.ctrl && (key.name === "c" || key.name === "d"))
69
+ return finish("cancel");
70
+ // Never interpret a prefix of text/paste as consent. Drain this input
71
+ // burst before resolving so trailing characters cannot approve another
72
+ // prompt. No input text is retained or rendered.
73
+ if (confirming)
74
+ return finish("reject");
75
+ if (key?.ctrl || key?.meta)
76
+ return finish("reject");
77
+ if (!candidate && ["up", "down", "left", "right", "home"].includes(key?.name ?? ""))
78
+ return;
79
+ if (!candidate && key?.name === "pageup")
80
+ return screenScrollPage(1);
81
+ if (!candidate && key?.name === "pagedown")
82
+ return screenScrollPage(-1);
83
+ if (!candidate && key?.name === "end")
84
+ return screenScrollToBottom();
85
+ if ((str === "y" || str === "Y") && !candidate) {
86
+ candidate = true;
87
+ return;
88
+ }
89
+ if ((key?.name === "return" || key?.name === "enter") && candidate) {
90
+ confirming = true;
91
+ setImmediate(() => finish(Date.now() >= deadline ? "timeout" : opts.signal?.aborted ? "cancel" : "approve"));
92
+ return;
93
+ }
94
+ finish("reject");
95
+ };
96
+ const release = captureKeys(onKey);
97
+ const timer = setInterval(() => {
98
+ if (Date.now() >= deadline)
99
+ finish("timeout");
100
+ else
101
+ paint();
102
+ }, 1000);
103
+ timer.unref?.();
104
+ if (opts.signal?.aborted)
105
+ return finish("cancel");
106
+ opts.signal?.addEventListener?.("abort", onAbort, { once: true });
107
+ process.stdout.on("resize", paint);
108
+ screenScrollToBottom();
109
+ paint();
110
+ });
111
+ }
@@ -0,0 +1,56 @@
1
+ import chalk from "chalk";
2
+ import { line } from "../services/output.js";
3
+ import { branchLabel, getWorkspace } from "../services/workspace.js";
4
+ import { modeLabelShort, modelLabelShort } from "../shell/shell-chat.js";
5
+ import { c } from "./colors.js";
6
+ import { clip } from "./conversation.js";
7
+ import { contentWidth, MARGIN } from "./composer-layout.js";
8
+ import { WORDMARK } from "./logo.js";
9
+ import { BRAND_HEX } from "./theme.js";
10
+ function hexToRgb(h) {
11
+ const n = parseInt(h.slice(1), 16);
12
+ return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
13
+ }
14
+ function lerpHex(a, b, t) {
15
+ const [ar, ag, ab] = hexToRgb(a);
16
+ const [br, bg, bb] = hexToRgb(b);
17
+ const mix = (x, y) => Math.round(x + (y - x) * t);
18
+ return "#" + [mix(ar, br), mix(ag, bg), mix(ab, bb)].map((v) => v.toString(16).padStart(2, "0")).join("");
19
+ }
20
+ /** The CARRIER OS block wordmark with a brand-green → lighter gradient, or a
21
+ * one-line mark when the terminal is too narrow for it. */
22
+ export function renderBrandmark() {
23
+ const rows = WORDMARK.split("\n");
24
+ const width = Math.max(1, ...rows.map((l) => [...l].length));
25
+ if ((process.stdout.columns ?? 80) < MARGIN.length + width + 2)
26
+ return [MARGIN + c.title("CarrierOS")];
27
+ const to = lerpHex(BRAND_HEX, "#ffffff", 0.5);
28
+ return rows.map((row) => MARGIN + [...row].map((ch, i) => (ch === " " ? ch : chalk.hex(lerpHex(BRAND_HEX, to, i / width))(ch))).join(""));
29
+ }
30
+ export function renderWelcomeBanner(ctx, opts = {}) {
31
+ try {
32
+ const ws = getWorkspace();
33
+ const branch = branchLabel(ws.repository);
34
+ // Where the agent will work, stated plainly before the first prompt: the
35
+ // signed-in state (a stored credential; the server checks it on use), the
36
+ // repository this folder resolves to, and its branch.
37
+ const row = (label, value) => MARGIN + c.dim(label.padEnd(12)) + c.value(clip(value, Math.max(8, contentWidth() - 12 - MARGIN.length)));
38
+ line("");
39
+ for (const l of renderBrandmark())
40
+ line(l);
41
+ line("");
42
+ line(MARGIN + c.ok("Authenticated ✓"));
43
+ line(row("Repository", ws.project.name));
44
+ if (branch)
45
+ line(row("Branch", branch));
46
+ line(row("Model", modelLabelShort(ctx)));
47
+ line(row("Mode", modeLabelShort(ctx)));
48
+ for (const notice of opts.notices ?? [])
49
+ line(MARGIN + clip(notice, contentWidth()));
50
+ line(MARGIN + c.dim("Describe a bug or a change in plain words · /help for commands"));
51
+ line("");
52
+ }
53
+ catch {
54
+ line(MARGIN + c.title("CarrierOS"));
55
+ }
56
+ }
@@ -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
+ }