@carrieros/cli 0.1.0 → 0.2.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.
- package/dist/commands/auth.js +60 -0
- package/dist/commands/chat.js +27 -4
- package/dist/commands/doctor.js +7 -7
- package/dist/commands/help.js +2 -1
- package/dist/commands/login.js +19 -40
- package/dist/commands/logout.js +13 -4
- package/dist/commands/scope.js +152 -0
- package/dist/commands/whoami.js +2 -1
- package/dist/main.js +4 -0
- package/dist/services/api.js +33 -9
- package/dist/services/config.js +3 -1
- package/dist/services/context.js +59 -3
- package/dist/services/device-auth.js +249 -0
- package/dist/services/login-flow.js +113 -10
- package/dist/services/output.js +8 -3
- package/dist/services/spinner.js +23 -1
- package/dist/shell/shell-chat.js +102 -17
- package/dist/shell/shell-commands.js +21 -9
- package/dist/shell/shell-prompt.js +17 -38
- package/dist/shell/shell-renderer.js +14 -21
- package/dist/shell/shell.js +52 -32
- package/dist/ui/banner.js +16 -13
- package/dist/ui/chat-renderer.js +17 -16
- package/dist/ui/color-picker.js +21 -0
- package/dist/ui/colors.js +5 -1
- package/dist/ui/command-filter.js +15 -1
- package/dist/ui/command-palette.js +107 -60
- package/dist/ui/command-registry.js +4 -5
- package/dist/ui/live.js +15 -0
- package/dist/ui/screen.js +289 -0
- package/dist/ui/select.js +8 -0
- package/dist/ui/theme.js +17 -0
- package/package.json +5 -5
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import axios, { isAxiosError } from "axios";
|
|
4
|
+
import { ApiError } from "./api.js";
|
|
5
|
+
import { cliVersion } from "./meta.js";
|
|
6
|
+
import { sleep } from "./spinner.js";
|
|
7
|
+
/**
|
|
8
|
+
* device-auth — the transport for the OAuth 2.0 Device Authorization (RFC 8628)
|
|
9
|
+
* flow that backs the browser-based `cos login`. These are low-level primitives
|
|
10
|
+
* (start / poll / refresh / logout / manage scope); the user-facing orchestration
|
|
11
|
+
* and printing live in login-flow.ts.
|
|
12
|
+
*
|
|
13
|
+
* The device + CLI endpoints live under `/api/platform/auth`, NOT under `/v1`,
|
|
14
|
+
* so we derive that base from the configured API URL.
|
|
15
|
+
*/
|
|
16
|
+
/** Derive `<origin>/api/platform/auth` from an API base like
|
|
17
|
+
* `https://api.carrieros.ai/v1` or `http://localhost:5000/v1`. */
|
|
18
|
+
export function platformAuthBase(apiUrl) {
|
|
19
|
+
const trimmed = apiUrl.replace(/\/+$/, "");
|
|
20
|
+
const origin = trimmed.replace(/\/v\d+$/i, ""); // drop a trailing /v1
|
|
21
|
+
return `${origin}/api/platform/auth`;
|
|
22
|
+
}
|
|
23
|
+
/** Local platform default (dev convenience): when the API is on localhost, the
|
|
24
|
+
* browser step should open the local platform (typically :3002) rather than the
|
|
25
|
+
* production URL the API returns when PLATFORM_FRONTEND_URL isn't set. Override
|
|
26
|
+
* the port with CARRIEROS_PLATFORM_URL. Returns undefined for non-local APIs. */
|
|
27
|
+
export function localPlatformDefault(apiUrl) {
|
|
28
|
+
try {
|
|
29
|
+
const host = new URL(apiUrl).hostname;
|
|
30
|
+
if (host === "localhost" || host === "127.0.0.1" || host === "::1") {
|
|
31
|
+
return "http://localhost:3002";
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
/* not a parseable URL — no local default */
|
|
36
|
+
}
|
|
37
|
+
return undefined;
|
|
38
|
+
}
|
|
39
|
+
/** Swap the origin (scheme + host) of a URL, preserving its path + query. Lets
|
|
40
|
+
* the CLI point the browser at a local platform during development without the
|
|
41
|
+
* API's PLATFORM_FRONTEND_URL being set. Returns the input unchanged on error
|
|
42
|
+
* or when no override is given. */
|
|
43
|
+
export function withPlatformOrigin(url, override) {
|
|
44
|
+
if (!override)
|
|
45
|
+
return url;
|
|
46
|
+
try {
|
|
47
|
+
const u = new URL(url);
|
|
48
|
+
const o = new URL(override);
|
|
49
|
+
u.protocol = o.protocol;
|
|
50
|
+
u.host = o.host;
|
|
51
|
+
return u.toString();
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
return url;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
/** A friendly device label so the developer can recognise this machine in the
|
|
58
|
+
* Devices list (e.g. "cos on DESKTOP-ABC (win32)"). */
|
|
59
|
+
export function deviceLabel() {
|
|
60
|
+
const host = os.hostname?.() || "unknown-host";
|
|
61
|
+
return `cos on ${host} (${process.platform})`;
|
|
62
|
+
}
|
|
63
|
+
const osName = () => {
|
|
64
|
+
switch (process.platform) {
|
|
65
|
+
case "win32":
|
|
66
|
+
return "Windows";
|
|
67
|
+
case "darwin":
|
|
68
|
+
return "macOS";
|
|
69
|
+
case "linux":
|
|
70
|
+
return "Linux";
|
|
71
|
+
default:
|
|
72
|
+
return process.platform;
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
/** Best-effort terminal/host identification for the approval page. */
|
|
76
|
+
const clientName = () => {
|
|
77
|
+
if (process.env.TERM_PROGRAM === "vscode")
|
|
78
|
+
return "VS Code Terminal";
|
|
79
|
+
if (process.env.WT_SESSION)
|
|
80
|
+
return "Windows Terminal";
|
|
81
|
+
if (process.env.TERM_PROGRAM === "Apple_Terminal")
|
|
82
|
+
return "Apple Terminal";
|
|
83
|
+
if (process.env.TERM_PROGRAM)
|
|
84
|
+
return `${process.env.TERM_PROGRAM} Terminal`;
|
|
85
|
+
return "Terminal";
|
|
86
|
+
};
|
|
87
|
+
/** The User-Agent the CLI presents so the browser approval page can show a
|
|
88
|
+
* human "OS · client" instead of a raw HTTP library string. Parsed on the
|
|
89
|
+
* platform by the same `CarrierOS-CLI/<v> (<os>; <client>)` shape. */
|
|
90
|
+
export function cliUserAgent() {
|
|
91
|
+
return `CarrierOS-CLI/${cliVersion()} (${osName()}; ${clientName()})`;
|
|
92
|
+
}
|
|
93
|
+
/** Open a URL in the user's default browser, cross-platform, with no extra deps.
|
|
94
|
+
* Best-effort: if it fails the caller still shows the URL to open manually. */
|
|
95
|
+
export function openBrowser(url) {
|
|
96
|
+
try {
|
|
97
|
+
if (process.platform === "win32") {
|
|
98
|
+
// `start` is a cmd builtin; the empty "" is the window title (avoids the
|
|
99
|
+
// URL being consumed as the title when it contains spaces/&).
|
|
100
|
+
spawn("cmd", ["/c", "start", "", url], { stdio: "ignore", detached: true }).unref();
|
|
101
|
+
}
|
|
102
|
+
else if (process.platform === "darwin") {
|
|
103
|
+
spawn("open", [url], { stdio: "ignore", detached: true }).unref();
|
|
104
|
+
}
|
|
105
|
+
else {
|
|
106
|
+
spawn("xdg-open", [url], { stdio: "ignore", detached: true }).unref();
|
|
107
|
+
}
|
|
108
|
+
return true;
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
return false;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
/** A bare axios call to the platform-auth base that returns the parsed envelope
|
|
115
|
+
* WITHOUT throwing on 4xx — so the poll loop can read RFC 8628 error codes. */
|
|
116
|
+
async function envelopePost(url, body, headers) {
|
|
117
|
+
try {
|
|
118
|
+
const res = await axios.post(url, body, {
|
|
119
|
+
headers: {
|
|
120
|
+
"Content-Type": "application/json",
|
|
121
|
+
"User-Agent": cliUserAgent(),
|
|
122
|
+
...(headers ?? {})
|
|
123
|
+
},
|
|
124
|
+
timeout: 30_000,
|
|
125
|
+
validateStatus: () => true
|
|
126
|
+
});
|
|
127
|
+
return { status: res.status, body: res.data };
|
|
128
|
+
}
|
|
129
|
+
catch (err) {
|
|
130
|
+
if (isAxiosError(err) && ["ECONNREFUSED", "ENOTFOUND", "ETIMEDOUT", "ECONNABORTED"].includes(err.code ?? "")) {
|
|
131
|
+
throw new ApiError("NETWORK_ERROR", `Could not reach the API at ${url}.`, 0);
|
|
132
|
+
}
|
|
133
|
+
throw new ApiError("REQUEST_FAILED", err instanceof Error ? err.message : String(err));
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
/** Step 1 — ask the server to start a device authorization. */
|
|
137
|
+
export async function startDeviceAuthorization(authBase, label) {
|
|
138
|
+
const { body } = await envelopePost(`${authBase}/device/code`, { label });
|
|
139
|
+
if (body?.success && body.data)
|
|
140
|
+
return body.data;
|
|
141
|
+
throw new ApiError(body?.error?.code ?? "DEVICE_START_FAILED", body?.error?.message ?? "Could not start login.");
|
|
142
|
+
}
|
|
143
|
+
/** Step 2 — one poll of the token endpoint. */
|
|
144
|
+
async function pollOnce(authBase, deviceCode) {
|
|
145
|
+
const { body } = await envelopePost(`${authBase}/device/token`, {
|
|
146
|
+
device_code: deviceCode
|
|
147
|
+
});
|
|
148
|
+
if (body?.success && body.data)
|
|
149
|
+
return { kind: "approved", data: body.data };
|
|
150
|
+
switch (body?.error?.code) {
|
|
151
|
+
case "AUTHORIZATION_PENDING":
|
|
152
|
+
return { kind: "pending" };
|
|
153
|
+
case "SLOW_DOWN":
|
|
154
|
+
return { kind: "slow_down" };
|
|
155
|
+
case "ACCESS_DENIED":
|
|
156
|
+
return { kind: "denied" };
|
|
157
|
+
case "EXPIRED_TOKEN":
|
|
158
|
+
return { kind: "expired" };
|
|
159
|
+
default:
|
|
160
|
+
return { kind: "error", message: body?.error?.message ?? "Authorization failed." };
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
/** Step 2 (loop) — poll until approved, denied, expired, or timed out. Calls
|
|
164
|
+
* `onTick` between polls so the caller can animate a spinner. */
|
|
165
|
+
export async function pollForToken(authBase, start, onTick) {
|
|
166
|
+
let intervalMs = Math.max(1, start.interval || 5) * 1000;
|
|
167
|
+
const deadline = Date.now() + Math.max(1, start.expires_in || 600) * 1000;
|
|
168
|
+
while (Date.now() < deadline) {
|
|
169
|
+
onTick?.();
|
|
170
|
+
await sleep(intervalMs);
|
|
171
|
+
const outcome = await pollOnce(authBase, start.device_code);
|
|
172
|
+
switch (outcome.kind) {
|
|
173
|
+
case "approved":
|
|
174
|
+
return outcome.data;
|
|
175
|
+
case "pending":
|
|
176
|
+
break;
|
|
177
|
+
case "slow_down":
|
|
178
|
+
intervalMs += 5_000; // back off per RFC 8628
|
|
179
|
+
break;
|
|
180
|
+
case "denied":
|
|
181
|
+
throw new ApiError("ACCESS_DENIED", "Authorization was cancelled in the browser.");
|
|
182
|
+
case "expired":
|
|
183
|
+
throw new ApiError("EXPIRED_TOKEN", "The code expired before it was approved. Run `cos login` again.");
|
|
184
|
+
case "error":
|
|
185
|
+
throw new ApiError("AUTH_FAILED", outcome.message);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
throw new ApiError("TIMEOUT", "Timed out waiting for approval. Run `cos login` again.");
|
|
189
|
+
}
|
|
190
|
+
/** Silently exchange a refresh token for a new session (rotation). Returns null
|
|
191
|
+
* if the session is no longer valid (caller should clear + re-login). */
|
|
192
|
+
export async function refreshCliSession(apiUrl, refreshToken) {
|
|
193
|
+
const authBase = platformAuthBase(apiUrl);
|
|
194
|
+
const { body } = await envelopePost(`${authBase}/cli/refresh`, {
|
|
195
|
+
refresh_token: refreshToken
|
|
196
|
+
});
|
|
197
|
+
if (body?.success && body.data)
|
|
198
|
+
return body.data;
|
|
199
|
+
return null;
|
|
200
|
+
}
|
|
201
|
+
/** Best-effort server-side logout (revokes the refresh token). Never throws. */
|
|
202
|
+
export async function logoutCliSession(apiUrl, refreshToken) {
|
|
203
|
+
try {
|
|
204
|
+
await envelopePost(`${platformAuthBase(apiUrl)}/cli/logout`, { refresh_token: refreshToken });
|
|
205
|
+
}
|
|
206
|
+
catch {
|
|
207
|
+
/* offline logout is fine — the local credentials are cleared regardless */
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
// ── Authenticated /cli/* management (bearer access token, refresh-on-401) ─────
|
|
211
|
+
async function authedRequest(apiUrl, method, path, provider, body, retry = true) {
|
|
212
|
+
const url = `${platformAuthBase(apiUrl)}${path}`;
|
|
213
|
+
const token = provider.token();
|
|
214
|
+
const res = await axios.request({
|
|
215
|
+
url,
|
|
216
|
+
method,
|
|
217
|
+
data: body,
|
|
218
|
+
headers: {
|
|
219
|
+
"Content-Type": "application/json",
|
|
220
|
+
...(token ? { Authorization: `Bearer ${token}` } : {})
|
|
221
|
+
},
|
|
222
|
+
timeout: 30_000,
|
|
223
|
+
validateStatus: () => true
|
|
224
|
+
});
|
|
225
|
+
if (res.status === 401 && retry && provider.refresh) {
|
|
226
|
+
const renewed = await provider.refresh();
|
|
227
|
+
if (renewed)
|
|
228
|
+
return authedRequest(apiUrl, method, path, provider, body, false);
|
|
229
|
+
}
|
|
230
|
+
const env = res.data;
|
|
231
|
+
if (env?.success && env.data !== undefined)
|
|
232
|
+
return env.data;
|
|
233
|
+
throw new ApiError(env?.error?.code ?? "REQUEST_FAILED", env?.error?.message ?? "Request failed.", res.status);
|
|
234
|
+
}
|
|
235
|
+
export function listCliWorkspaces(apiUrl, provider) {
|
|
236
|
+
return authedRequest(apiUrl, "get", "/cli/workspaces", provider);
|
|
237
|
+
}
|
|
238
|
+
export function listCliProjects(apiUrl, provider, workspaceId) {
|
|
239
|
+
return authedRequest(apiUrl, "get", `/cli/workspaces/${workspaceId}/projects`, provider);
|
|
240
|
+
}
|
|
241
|
+
export function setCliScope(apiUrl, provider, workspaceId, projectId) {
|
|
242
|
+
return authedRequest(apiUrl, "post", "/cli/scope", provider, {
|
|
243
|
+
workspace_id: workspaceId,
|
|
244
|
+
project_id: projectId
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
export function getCliContext(apiUrl, provider) {
|
|
248
|
+
return authedRequest(apiUrl, "get", "/cli/context", provider);
|
|
249
|
+
}
|
|
@@ -1,15 +1,118 @@
|
|
|
1
|
-
import
|
|
1
|
+
import chalk from "chalk";
|
|
2
|
+
import { ApiError } from "./api.js";
|
|
3
|
+
import { deviceLabel, localPlatformDefault, openBrowser, platformAuthBase, pollForToken, startDeviceAuthorization, withPlatformOrigin } from "./device-auth.js";
|
|
4
|
+
import { info, line } from "./output.js";
|
|
5
|
+
import { sleep, withSpinner } from "./spinner.js";
|
|
6
|
+
import { c } from "../ui/colors.js";
|
|
2
7
|
/**
|
|
3
|
-
* The single source of truth for
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
8
|
+
* The single source of truth for browser-based login (OAuth 2.0 Device
|
|
9
|
+
* Authorization). This module owns only the *presentation* of the login — the
|
|
10
|
+
* flow, polling, token, and refresh logic are unchanged and live in
|
|
11
|
+
* device-auth.ts. Shared by the `login` command and the shell's first-run.
|
|
7
12
|
*
|
|
8
|
-
*
|
|
13
|
+
* Terminal choreography (Claude-Code style, minimal + fixed, no scroll flood):
|
|
14
|
+
* Opening your browser…
|
|
15
|
+
* ✓ Browser opened <verification url> Code XXXX-XXXX
|
|
16
|
+
* ⠋ Waiting for approval… (in-place spinner)
|
|
17
|
+
* ✓ Device authorized / Workspace / Project / Session / Authentication successful
|
|
9
18
|
*/
|
|
10
|
-
export async function
|
|
11
|
-
const
|
|
12
|
-
|
|
13
|
-
|
|
19
|
+
export async function deviceLogin(ctx, apiUrl) {
|
|
20
|
+
const authBase = platformAuthBase(apiUrl);
|
|
21
|
+
// Branding + intro first (shown for both `cos` first-run and `cos login`).
|
|
22
|
+
line();
|
|
23
|
+
line(" " + c.brand("Welcome to Carrier OS"));
|
|
24
|
+
line(" " + c.dim("Sign in with your Carrier OS Developer account."));
|
|
25
|
+
line();
|
|
26
|
+
info("Opening your browser…");
|
|
27
|
+
const start = await startDeviceAuthorization(authBase, deviceLabel());
|
|
28
|
+
// Resolve the platform origin for the browser step. Precedence: explicit
|
|
29
|
+
// config `platformUrl` → env CARRIEROS_PLATFORM_URL → a localhost default when
|
|
30
|
+
// the API itself is local (so `cos` "just works" against a local stack) →
|
|
31
|
+
// otherwise trust the URL the API returned.
|
|
32
|
+
const override = ctx.config.get("platformUrl") ||
|
|
33
|
+
process.env.CARRIEROS_PLATFORM_URL ||
|
|
34
|
+
localPlatformDefault(apiUrl);
|
|
35
|
+
const openUrl = withPlatformOrigin(start.verification_uri_complete || start.verification_uri, override);
|
|
36
|
+
const opened = openBrowser(openUrl);
|
|
37
|
+
line();
|
|
38
|
+
line(" " + (opened ? chalk.green("✓") + " Browser opened." : chalk.yellow("!") + " Couldn't open your browser."));
|
|
39
|
+
line();
|
|
40
|
+
// Persistent fallback (Claude-style): always offer the URL to sign in manually.
|
|
41
|
+
line(" " + c.dim("Browser didn't open? Use the URL below to sign in:"));
|
|
42
|
+
line(" " + c.brand(openUrl));
|
|
43
|
+
line();
|
|
44
|
+
// Waiting state — a single in-place spinner (never scrolls). Polling is
|
|
45
|
+
// unchanged; the spinner just animates until it resolves or throws.
|
|
46
|
+
const tokens = await withSpinner(chalk.dim("Waiting for approval…"), () => pollForToken(authBase, start));
|
|
47
|
+
return renderAuthorized(ctx, tokens);
|
|
48
|
+
}
|
|
49
|
+
/** The success sequence — a short animated checklist, then persist + verify,
|
|
50
|
+
* ending on "Logged in as <email>" (the shell then pauses + shows the welcome). */
|
|
51
|
+
async function renderAuthorized(ctx, tokens) {
|
|
52
|
+
const ok = (msg) => line(" " + chalk.green("✓") + " " + msg);
|
|
53
|
+
line();
|
|
54
|
+
ok("Device authorized");
|
|
55
|
+
await sleep(150);
|
|
56
|
+
const scope = await persistSession(ctx, tokens);
|
|
57
|
+
ok("Session synchronized");
|
|
58
|
+
await sleep(130);
|
|
59
|
+
const email = scope.user?.email ?? tokens.account?.email;
|
|
60
|
+
if (email) {
|
|
61
|
+
line();
|
|
62
|
+
line(" Logged in as " + c.value(email));
|
|
63
|
+
}
|
|
64
|
+
return scope;
|
|
65
|
+
}
|
|
66
|
+
/** Save the issued tokens + a cached scope; land in Carrier Chat by default.
|
|
67
|
+
* (Unchanged behaviour — persistence + a verify to confirm the token works.) */
|
|
68
|
+
async function persistSession(ctx, tokens) {
|
|
69
|
+
ctx.config.update({
|
|
70
|
+
auth: {
|
|
71
|
+
accessToken: tokens.access_token,
|
|
72
|
+
refreshToken: tokens.refresh_token,
|
|
73
|
+
account: tokens.account,
|
|
74
|
+
workspace: tokens.workspace ?? null,
|
|
75
|
+
project: tokens.project ?? null
|
|
76
|
+
}
|
|
77
|
+
});
|
|
78
|
+
ctx.config.set("chatType", "carrier");
|
|
79
|
+
let scope;
|
|
80
|
+
try {
|
|
81
|
+
scope = await ctx.client().verify();
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
scope = scopeFromTokens(tokens);
|
|
85
|
+
}
|
|
86
|
+
ctx.config.set("scope", scope);
|
|
14
87
|
return scope;
|
|
15
88
|
}
|
|
89
|
+
function scopeFromTokens(tokens) {
|
|
90
|
+
return {
|
|
91
|
+
apiKey: null,
|
|
92
|
+
workspace: tokens.workspace ?? { id: "", name: "—", slug: "" },
|
|
93
|
+
project: tokens.project ?? { id: "", name: "—", projectId: "", environment: "" },
|
|
94
|
+
user: tokens.account ? { id: tokens.account.id, email: tokens.account.email } : null
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
/** Render a single, minimal ✗ line for a failed login. Returns the category. */
|
|
98
|
+
export function renderLoginFailure(err, apiUrl) {
|
|
99
|
+
const code = err instanceof ApiError ? err.code : "other";
|
|
100
|
+
const fail = (msg) => line(" " + chalk.red("✗") + " " + msg);
|
|
101
|
+
line();
|
|
102
|
+
if (code === "ACCESS_DENIED") {
|
|
103
|
+
fail("Authorization cancelled in the browser.");
|
|
104
|
+
return "denied";
|
|
105
|
+
}
|
|
106
|
+
if (code === "EXPIRED_TOKEN" || code === "TIMEOUT") {
|
|
107
|
+
fail("Login timed out — the code expired before it was approved.");
|
|
108
|
+
return "expired";
|
|
109
|
+
}
|
|
110
|
+
if (code === "NETWORK_ERROR" || code.startsWith("HTTP_")) {
|
|
111
|
+
fail("Couldn't reach the server.");
|
|
112
|
+
if (apiUrl)
|
|
113
|
+
line(" " + c.dim(apiUrl));
|
|
114
|
+
return "network";
|
|
115
|
+
}
|
|
116
|
+
fail(err instanceof ApiError ? `${err.message} (${err.code})` : String(err?.message ?? err));
|
|
117
|
+
return "other";
|
|
118
|
+
}
|
package/dist/services/output.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { c } from "../ui/colors.js";
|
|
2
|
+
import { screenActive, screenPrint } from "../ui/screen.js";
|
|
2
3
|
import { icon } from "../ui/ui.js";
|
|
3
4
|
/** Status glyphs (consistent icon set — never emojis). */
|
|
4
5
|
export const glyph = {
|
|
@@ -7,6 +8,12 @@ export const glyph = {
|
|
|
7
8
|
err: icon.err
|
|
8
9
|
};
|
|
9
10
|
export const line = (msg = "") => {
|
|
11
|
+
// In the interactive shell the screen owns the terminal: route transcript
|
|
12
|
+
// output through it (so it lands above the pinned composer, not over it).
|
|
13
|
+
if (screenActive()) {
|
|
14
|
+
screenPrint(msg.length ? msg.split("\n") : [""]);
|
|
15
|
+
return;
|
|
16
|
+
}
|
|
10
17
|
process.stdout.write(msg + "\n");
|
|
11
18
|
};
|
|
12
19
|
export const success = (msg) => line(`${icon.ok} ${msg}`);
|
|
@@ -19,13 +26,11 @@ export function kv(label, value, width = 14) {
|
|
|
19
26
|
line(` ${c.label(label.padEnd(width))}${value}`);
|
|
20
27
|
}
|
|
21
28
|
/** The focused-chat header (used by `cos chat`). */
|
|
22
|
-
export function printBanner(
|
|
29
|
+
export function printBanner(_scope, mode, modelLabel) {
|
|
23
30
|
line();
|
|
24
31
|
line(c.wordmark(" Carrier OS CLI"));
|
|
25
32
|
line(c.dim(" Ready."));
|
|
26
33
|
line();
|
|
27
|
-
kv("Workspace", scope?.workspace.name ?? c.dim("—"));
|
|
28
|
-
kv("Project", scope?.project.name ?? c.dim("—"));
|
|
29
34
|
kv("Mode", capitalize(mode));
|
|
30
35
|
kv("Model", modelLabel);
|
|
31
36
|
line();
|
package/dist/services/spinner.js
CHANGED
|
@@ -1,9 +1,31 @@
|
|
|
1
1
|
import ora from "ora";
|
|
2
|
+
import { screenActive, screenTransient } from "../ui/screen.js";
|
|
3
|
+
const FRAMES = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏";
|
|
2
4
|
/**
|
|
3
5
|
* 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.
|
|
6
|
+
* (success or throw) so it can never be left spinning on an error path. Inside
|
|
7
|
+
* the interactive shell the spinner renders as a transient line above the pinned
|
|
8
|
+
* composer (via the screen engine) instead of writing to stdout directly.
|
|
5
9
|
*/
|
|
6
10
|
export async function withSpinner(text, fn) {
|
|
11
|
+
if (screenActive()) {
|
|
12
|
+
const state = { text };
|
|
13
|
+
let i = 0;
|
|
14
|
+
const paint = () => screenTransient([" " + FRAMES[i % FRAMES.length] + " " + state.text]);
|
|
15
|
+
paint();
|
|
16
|
+
const timer = setInterval(() => {
|
|
17
|
+
i++;
|
|
18
|
+
paint();
|
|
19
|
+
}, 80);
|
|
20
|
+
timer.unref?.();
|
|
21
|
+
try {
|
|
22
|
+
return await fn(state);
|
|
23
|
+
}
|
|
24
|
+
finally {
|
|
25
|
+
clearInterval(timer);
|
|
26
|
+
screenTransient([]); // clear the spinner line; real output follows via line()
|
|
27
|
+
}
|
|
28
|
+
}
|
|
7
29
|
// discardStdin:false — otherwise ora grabs/pauses stdin while spinning, which
|
|
8
30
|
// corrupts the interactive shell's readline and makes it exit after one turn.
|
|
9
31
|
const spinner = ora({ text, color: "cyan", discardStdin: false }).start();
|
package/dist/shell/shell-chat.js
CHANGED
|
@@ -3,9 +3,8 @@ import { ApiError } from "../services/api.js";
|
|
|
3
3
|
import { capitalize, errorLine, info, line } from "../services/output.js";
|
|
4
4
|
import { sleep, withSpinner } from "../services/spinner.js";
|
|
5
5
|
import { chatActivitySteps, startActivity } from "../ui/activity.js";
|
|
6
|
-
import { renderComplete,
|
|
6
|
+
import { renderComplete, renderCompleteLive, renderError, renderUserMessage, startThinking, streamAssistant, streamAssistantLive } from "../ui/chat-renderer.js";
|
|
7
7
|
import { startLiveComposer } from "../ui/live.js";
|
|
8
|
-
import { startStickyStream } from "../ui/sticky-stream.js";
|
|
9
8
|
import { pickFromList } from "../ui/select.js";
|
|
10
9
|
// Shared by the `chat` command REPL and the interactive shell so chat, mode and
|
|
11
10
|
// model logic lives in exactly one place (no duplicated business logic).
|
|
@@ -29,6 +28,12 @@ export function modelLabelShort(ctx) {
|
|
|
29
28
|
return "Auto";
|
|
30
29
|
return modelCache?.find((m) => m.id === id)?.label ?? id;
|
|
31
30
|
}
|
|
31
|
+
/** Friendly label for the active Carrier mode — its display name (e.g. "Carrier
|
|
32
|
+
* OS"), not the raw id. Falls back to a capitalized id until modes are loaded. */
|
|
33
|
+
export function modeLabelShort(ctx) {
|
|
34
|
+
const id = ctx.mode;
|
|
35
|
+
return modeCache?.find((m) => m.id === id)?.name ?? capitalize(id);
|
|
36
|
+
}
|
|
32
37
|
function reportError(err) {
|
|
33
38
|
errorLine(err instanceof ApiError ? `${err.message} (${err.code})` : err.message);
|
|
34
39
|
}
|
|
@@ -55,7 +60,8 @@ export async function chatTurn(ctx, client, message, opts = {}) {
|
|
|
55
60
|
mode,
|
|
56
61
|
message,
|
|
57
62
|
session_id: sessionId,
|
|
58
|
-
model: model || undefined
|
|
63
|
+
model: model || undefined,
|
|
64
|
+
chat_type: ctx.chatType
|
|
59
65
|
});
|
|
60
66
|
spinner.stop();
|
|
61
67
|
// Persist the session so the conversation continues across turns/invocations.
|
|
@@ -95,7 +101,7 @@ async function chatTurnLive(ctx, client, message, footer) {
|
|
|
95
101
|
// brief client-side steps play over the actual wait. Settle it eagerly so a
|
|
96
102
|
// rejection during the steps is never an unhandled rejection.
|
|
97
103
|
const settled = client
|
|
98
|
-
.chat({ mode, message, session_id: sessionId, model: model || undefined })
|
|
104
|
+
.chat({ mode, message, session_id: sessionId, model: model || undefined, chat_type: ctx.chatType })
|
|
99
105
|
.then((r) => ({ ok: true, r }))
|
|
100
106
|
.catch((e) => ({ ok: false, e }));
|
|
101
107
|
try {
|
|
@@ -108,23 +114,19 @@ async function chatTurnLive(ctx, client, message, footer) {
|
|
|
108
114
|
const outcome = await settled;
|
|
109
115
|
activity.done();
|
|
110
116
|
activity.stop();
|
|
111
|
-
live.
|
|
117
|
+
live.setStatus([]); // collapse the activity checklist before the answer
|
|
112
118
|
if (!outcome.ok)
|
|
113
119
|
throw outcome.e;
|
|
114
120
|
const result = outcome.r;
|
|
115
121
|
if (result.session_id && result.session_id !== sessionId) {
|
|
116
122
|
ctx.config.set("sessionId", result.session_id);
|
|
117
123
|
}
|
|
118
|
-
// Stream the answer
|
|
119
|
-
//
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
}
|
|
125
|
-
finally {
|
|
126
|
-
sticky.stop(); // restore the terminal; the reader redraws its bar in place
|
|
127
|
-
}
|
|
124
|
+
// Stream the answer in the SAME pinned composer so the reply sits directly
|
|
125
|
+
// beneath the user's message (contiguous — no gap), with the input bar
|
|
126
|
+
// staying visible the whole time. Finished lines commit above the bar.
|
|
127
|
+
await streamAssistantLive(live, result.response); // header → stream → each line locked
|
|
128
|
+
renderCompleteLive(live, (Date.now() - started) / 1000);
|
|
129
|
+
live.stop();
|
|
128
130
|
}
|
|
129
131
|
catch (err) {
|
|
130
132
|
activity.stop();
|
|
@@ -138,6 +140,85 @@ async function chatTurnLive(ctx, client, message, footer) {
|
|
|
138
140
|
}
|
|
139
141
|
}
|
|
140
142
|
}
|
|
143
|
+
// ── Chat type (Carrier Chat vs Standard) ──────────────────────────────────────
|
|
144
|
+
// Orthogonal to modes: modes tune HOW Carrier responds; chat type picks WHICH
|
|
145
|
+
// chat experience — the flagship Carrier Chat (app-instructions + carrier
|
|
146
|
+
// behaviour layer, same engine/128k-context/memory as the web app) or a plain
|
|
147
|
+
// standard chat.
|
|
148
|
+
export function chatTypeLabel(type) {
|
|
149
|
+
return type === "carrier" ? "Carrier Chat" : "Standard chat";
|
|
150
|
+
}
|
|
151
|
+
/** Short label for the prompt/banner. */
|
|
152
|
+
export function chatTypeLabelShort(ctx) {
|
|
153
|
+
return chatTypeLabel(ctx.chatType);
|
|
154
|
+
}
|
|
155
|
+
/** `/chat` — no arg shows the current type; `/chat carrier|standard` switches. */
|
|
156
|
+
export function setChatType(ctx, arg) {
|
|
157
|
+
const raw = arg.trim().toLowerCase();
|
|
158
|
+
if (!raw) {
|
|
159
|
+
line();
|
|
160
|
+
line(chalk.dim(" Chat type:"));
|
|
161
|
+
for (const t of ["carrier", "standard"]) {
|
|
162
|
+
const on = t === ctx.chatType;
|
|
163
|
+
const label = on ? chalk.bold(chatTypeLabel(t)) : chatTypeLabel(t);
|
|
164
|
+
const desc = t === "carrier"
|
|
165
|
+
? "Flagship Carrier OS chat — full persona, 128k context, memory."
|
|
166
|
+
: "Plain chat — Carrier persona without the app-instruction layer.";
|
|
167
|
+
line(` ${on ? chalk.green("►") : " "} ${label.padEnd(15)} ${chalk.dim(desc)}`);
|
|
168
|
+
}
|
|
169
|
+
line();
|
|
170
|
+
line(chalk.dim(" Switch with /chat carrier or /chat standard."));
|
|
171
|
+
line();
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
const next = raw === "carrier" || raw === "carrieros"
|
|
175
|
+
? "carrier"
|
|
176
|
+
: raw === "standard" || raw === "plain" || raw === "normal"
|
|
177
|
+
? "standard"
|
|
178
|
+
: null;
|
|
179
|
+
if (next === null) {
|
|
180
|
+
errorLine(`Unknown chat type "${arg.trim()}". Use /chat carrier or /chat standard.`);
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
if (next === ctx.chatType) {
|
|
184
|
+
info(`Already in ${chatTypeLabel(next)}.`);
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
ctx.setChatType(next); // clears the session — the next message starts fresh
|
|
188
|
+
info(`Switched to ${chatTypeLabel(next)}. A new conversation starts on your next message.`);
|
|
189
|
+
}
|
|
190
|
+
/** Arrow-key picker to switch chat type (Carrier ⇄ Standard). `/switch`. */
|
|
191
|
+
export async function pickChatType(ctx) {
|
|
192
|
+
const choices = [
|
|
193
|
+
{
|
|
194
|
+
value: "carrier",
|
|
195
|
+
label: chatTypeLabel("carrier"),
|
|
196
|
+
description: "Flagship Carrier OS chat — full persona, 128k context, memory.",
|
|
197
|
+
current: ctx.chatType === "carrier"
|
|
198
|
+
},
|
|
199
|
+
{
|
|
200
|
+
value: "standard",
|
|
201
|
+
label: chatTypeLabel("standard"),
|
|
202
|
+
description: "Plain chat — Carrier persona without the app-instruction layer.",
|
|
203
|
+
current: ctx.chatType === "standard"
|
|
204
|
+
}
|
|
205
|
+
];
|
|
206
|
+
const chosen = await pickFromList({
|
|
207
|
+
title: "Switch chat",
|
|
208
|
+
description: "Pick your chat experience. Switching starts a new conversation.",
|
|
209
|
+
initial: Math.max(0, choices.findIndex((ch) => ch.current)),
|
|
210
|
+
choices
|
|
211
|
+
});
|
|
212
|
+
if (chosen == null)
|
|
213
|
+
return; // Esc / Ctrl+C — leave it unchanged
|
|
214
|
+
const next = chosen;
|
|
215
|
+
if (next === ctx.chatType) {
|
|
216
|
+
info(`Already in ${chatTypeLabel(next)}.`);
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
ctx.setChatType(next);
|
|
220
|
+
info(`Switched to ${chatTypeLabel(next)}. A new conversation starts on your next message.`);
|
|
221
|
+
}
|
|
141
222
|
// ── Carrier modes (behavior) ──────────────────────────────────────────────────
|
|
142
223
|
export async function showModes(ctx, client) {
|
|
143
224
|
try {
|
|
@@ -169,7 +250,9 @@ export async function setMode(ctx, client, arg) {
|
|
|
169
250
|
return;
|
|
170
251
|
}
|
|
171
252
|
ctx.config.set("mode", id);
|
|
172
|
-
|
|
253
|
+
ctx.setSessionMode(id); // reflect immediately in the shell (over the session default)
|
|
254
|
+
const name = modes.find((m) => m.id === id)?.name ?? capitalize(id);
|
|
255
|
+
info(`Mode changed to ${name} (applies to your next message).`);
|
|
173
256
|
}
|
|
174
257
|
catch (err) {
|
|
175
258
|
reportError(err);
|
|
@@ -199,7 +282,9 @@ export async function pickMode(ctx, client) {
|
|
|
199
282
|
if (chosen == null)
|
|
200
283
|
return; // Esc / Ctrl+C — leave the mode unchanged
|
|
201
284
|
ctx.config.set("mode", chosen);
|
|
202
|
-
|
|
285
|
+
ctx.setSessionMode(chosen); // reflect immediately in the shell (over the session default)
|
|
286
|
+
const name = modes.find((m) => m.id === chosen)?.name ?? capitalize(chosen);
|
|
287
|
+
info(`Mode changed to ${name} (applies to your next message).`);
|
|
203
288
|
}
|
|
204
289
|
// ── Provider models (the LLM behind a turn) ───────────────────────────────────
|
|
205
290
|
export async function showModels(ctx, client) {
|