@carrieros/cli 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +305 -0
- package/dist/commands/chat.js +93 -0
- package/dist/commands/doctor.js +54 -0
- package/dist/commands/files.js +33 -0
- package/dist/commands/help.js +35 -0
- package/dist/commands/history.js +47 -0
- package/dist/commands/login.js +59 -0
- package/dist/commands/logout.js +15 -0
- package/dist/commands/mode-model.js +28 -0
- package/dist/commands/models.js +28 -0
- package/dist/commands/modes.js +27 -0
- package/dist/commands/sessions.js +123 -0
- package/dist/commands/upload.js +50 -0
- package/dist/commands/usage.js +31 -0
- package/dist/commands/version.js +28 -0
- package/dist/commands/whoami.js +40 -0
- package/dist/main.js +94 -0
- package/dist/services/api.js +115 -0
- package/dist/services/config.js +72 -0
- package/dist/services/context.js +42 -0
- package/dist/services/login-flow.js +15 -0
- package/dist/services/meta.js +13 -0
- package/dist/services/output.js +54 -0
- package/dist/services/spinner.js +18 -0
- package/dist/shell/shell-chat.js +280 -0
- package/dist/shell/shell-commands.js +168 -0
- package/dist/shell/shell-prompt.js +48 -0
- package/dist/shell/shell-renderer.js +70 -0
- package/dist/shell/shell-router.js +21 -0
- package/dist/shell/shell.js +139 -0
- package/dist/types/index.js +4 -0
- package/dist/ui/activity.js +77 -0
- package/dist/ui/banner.js +70 -0
- package/dist/ui/chat-renderer.js +269 -0
- package/dist/ui/code-block.js +52 -0
- package/dist/ui/color-picker.js +79 -0
- package/dist/ui/colors.js +47 -0
- package/dist/ui/command-filter.js +57 -0
- package/dist/ui/command-item.js +6 -0
- package/dist/ui/command-palette.js +306 -0
- package/dist/ui/command-registry.js +47 -0
- package/dist/ui/command-renderer.js +55 -0
- package/dist/ui/composer-layout.js +27 -0
- package/dist/ui/live.js +124 -0
- package/dist/ui/logo.js +58 -0
- package/dist/ui/markdown.js +151 -0
- package/dist/ui/message.js +38 -0
- package/dist/ui/select.js +114 -0
- package/dist/ui/spinner.js +23 -0
- package/dist/ui/sticky-stream.js +64 -0
- package/dist/ui/theme.js +63 -0
- package/dist/ui/ui.js +75 -0
- package/package.json +64 -0
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import chalk from "chalk";
|
|
2
|
+
import { heading, line } from "../services/output.js";
|
|
3
|
+
import { withSpinner } from "../services/spinner.js";
|
|
4
|
+
/**
|
|
5
|
+
* `cos models` — list the provider models a developer may request via the
|
|
6
|
+
* chat `model` override (GET /v1/models/chat). See `cos modes` for the
|
|
7
|
+
* Carrier behavior modes.
|
|
8
|
+
*/
|
|
9
|
+
export function registerModels(program, ctx) {
|
|
10
|
+
program
|
|
11
|
+
.command("models")
|
|
12
|
+
.description("List provider models available for the chat model override")
|
|
13
|
+
.action(async () => {
|
|
14
|
+
const client = ctx.requireAuth();
|
|
15
|
+
const models = await withSpinner("Loading models…", () => client.chatModels());
|
|
16
|
+
const active = ctx.config.get("model") ?? "";
|
|
17
|
+
heading(`Provider models (${models.length})`);
|
|
18
|
+
line(` ${active === "" ? chalk.green("►") : " "} ${chalk.bold("Auto (mode default)")}`);
|
|
19
|
+
for (const m of models) {
|
|
20
|
+
const on = m.id === active;
|
|
21
|
+
const label = on ? chalk.bold(m.label) : m.label;
|
|
22
|
+
line(` ${on ? chalk.green("►") : " "} ${label.padEnd(28)} ${chalk.dim(m.id)}`);
|
|
23
|
+
}
|
|
24
|
+
line();
|
|
25
|
+
line(chalk.dim(" Use one with `cos chat --model <id>`, or /model in chat."));
|
|
26
|
+
line();
|
|
27
|
+
});
|
|
28
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import chalk from "chalk";
|
|
2
|
+
import { capitalize, heading, line } from "../services/output.js";
|
|
3
|
+
import { withSpinner } from "../services/spinner.js";
|
|
4
|
+
/**
|
|
5
|
+
* `cos modes` — list the Carrier behavior modes from GET /v1/models
|
|
6
|
+
* (general, reasoning, code, research, …). Each mode maps to a default provider
|
|
7
|
+
* model server-side; use `cos models` to see/override the provider model.
|
|
8
|
+
*/
|
|
9
|
+
export function registerModes(program, ctx) {
|
|
10
|
+
program
|
|
11
|
+
.command("modes")
|
|
12
|
+
.description("List Carrier modes (behavior presets)")
|
|
13
|
+
.action(async () => {
|
|
14
|
+
const client = ctx.requireAuth();
|
|
15
|
+
const modes = await withSpinner("Loading modes…", () => client.models());
|
|
16
|
+
const active = ctx.mode;
|
|
17
|
+
heading(`Carrier modes (${modes.length})`);
|
|
18
|
+
for (const m of modes) {
|
|
19
|
+
const marker = m.id === active ? chalk.green("►") : " ";
|
|
20
|
+
const name = m.id === active ? chalk.bold(capitalize(m.name)) : capitalize(m.name);
|
|
21
|
+
line(` ${marker} ${name.padEnd(12)} ${chalk.dim(m.description)}`);
|
|
22
|
+
}
|
|
23
|
+
line();
|
|
24
|
+
line(chalk.dim(" Set a default with `cos chat --mode <id>`, or /mode in chat."));
|
|
25
|
+
line();
|
|
26
|
+
});
|
|
27
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { ApiError } from "../services/api.js";
|
|
2
|
+
import { errorLine, info, line, success, timeAgo } from "../services/output.js";
|
|
3
|
+
import { withSpinner } from "../services/spinner.js";
|
|
4
|
+
import { c } from "../ui/colors.js";
|
|
5
|
+
import { pickFromList } from "../ui/select.js";
|
|
6
|
+
import { emptyState, icon, sectionHeader } from "../ui/ui.js";
|
|
7
|
+
/**
|
|
8
|
+
* Session management, all backed by GET /v1/conversations, GET /v1/sessions/:id
|
|
9
|
+
* and DELETE /v1/sessions/:id:
|
|
10
|
+
* cos sessions list conversations
|
|
11
|
+
* cos session use [id] switch active session (prompts if no id)
|
|
12
|
+
* cos session delete <id> delete a session
|
|
13
|
+
* cos clear start a new session (drops the local pointer)
|
|
14
|
+
*/
|
|
15
|
+
export function registerSessions(program, ctx) {
|
|
16
|
+
program
|
|
17
|
+
.command("sessions")
|
|
18
|
+
.description("List conversations in the current project")
|
|
19
|
+
.option("-n, --limit <n>", "how many to show", "20")
|
|
20
|
+
.action(async (opts) => {
|
|
21
|
+
const client = ctx.requireAuth();
|
|
22
|
+
const limit = clampLimit(opts.limit);
|
|
23
|
+
const { conversations, pagination } = await withSpinner("Loading sessions…", () => client.conversations({ limit }));
|
|
24
|
+
renderList(conversations, ctx.config.get("sessionId"), pagination.total);
|
|
25
|
+
});
|
|
26
|
+
const session = program.command("session").description("Inspect or switch the active session");
|
|
27
|
+
session
|
|
28
|
+
.command("use")
|
|
29
|
+
.description("Switch the active session")
|
|
30
|
+
.argument("[id]", "session id (prompts from the list if omitted)")
|
|
31
|
+
.action(async (id) => {
|
|
32
|
+
const client = ctx.requireAuth();
|
|
33
|
+
let target = id;
|
|
34
|
+
if (!target) {
|
|
35
|
+
const { conversations } = await withSpinner("Loading sessions…", () => client.conversations({ limit: 25 }));
|
|
36
|
+
if (conversations.length === 0) {
|
|
37
|
+
for (const l of emptyState("No conversations yet.", "Start chatting to create one.")) {
|
|
38
|
+
line(l);
|
|
39
|
+
}
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
const activeId = ctx.config.get("sessionId");
|
|
43
|
+
const chosen = await pickFromList({
|
|
44
|
+
title: "Select a session",
|
|
45
|
+
description: "Switch the active conversation.",
|
|
46
|
+
initial: Math.max(0, conversations.findIndex((cv) => cv.session_id === activeId)),
|
|
47
|
+
choices: conversations.map((cv) => ({
|
|
48
|
+
value: cv.session_id,
|
|
49
|
+
label: cv.title,
|
|
50
|
+
description: `${cv.message_count} msgs · ${timeAgo(cv.last_activity)}`,
|
|
51
|
+
current: cv.session_id === activeId
|
|
52
|
+
}))
|
|
53
|
+
});
|
|
54
|
+
if (chosen == null)
|
|
55
|
+
return; // Esc / Ctrl+C — leave the session unchanged
|
|
56
|
+
target = chosen;
|
|
57
|
+
}
|
|
58
|
+
try {
|
|
59
|
+
const info_ = await withSpinner("Opening…", () => client.session(target));
|
|
60
|
+
ctx.config.set("sessionId", info_.session_id);
|
|
61
|
+
success(`Switched to “${info_.title}”.`);
|
|
62
|
+
}
|
|
63
|
+
catch (err) {
|
|
64
|
+
errorLine(err instanceof ApiError ? `${err.message} (${err.code})` : err.message);
|
|
65
|
+
process.exitCode = 1;
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
session
|
|
69
|
+
.command("current")
|
|
70
|
+
.description("Show the active session id")
|
|
71
|
+
.action(() => {
|
|
72
|
+
const sid = ctx.config.get("sessionId");
|
|
73
|
+
info(sid ? `Current session: ${sid}` : "No active session (a new one starts on your next message).");
|
|
74
|
+
});
|
|
75
|
+
session
|
|
76
|
+
.command("delete")
|
|
77
|
+
.description("Delete a session")
|
|
78
|
+
.argument("<id>", "session id")
|
|
79
|
+
.action(async (id) => {
|
|
80
|
+
const client = ctx.requireAuth();
|
|
81
|
+
try {
|
|
82
|
+
await withSpinner("Deleting…", () => client.deleteSession(id));
|
|
83
|
+
if (ctx.config.get("sessionId") === id)
|
|
84
|
+
ctx.config.set("sessionId", undefined);
|
|
85
|
+
success("Session deleted.");
|
|
86
|
+
}
|
|
87
|
+
catch (err) {
|
|
88
|
+
errorLine(err instanceof ApiError ? `${err.message} (${err.code})` : err.message);
|
|
89
|
+
process.exitCode = 1;
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
program
|
|
93
|
+
.command("clear")
|
|
94
|
+
.description("Start a new session (forgets the active one locally)")
|
|
95
|
+
.action(() => {
|
|
96
|
+
ctx.config.set("sessionId", undefined);
|
|
97
|
+
success("Cleared. Your next message starts a fresh session.");
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
function clampLimit(raw) {
|
|
101
|
+
const n = parseInt(raw, 10);
|
|
102
|
+
if (Number.isNaN(n))
|
|
103
|
+
return 20;
|
|
104
|
+
return Math.min(Math.max(n, 1), 100);
|
|
105
|
+
}
|
|
106
|
+
function renderList(items, activeId, total) {
|
|
107
|
+
if (items.length === 0) {
|
|
108
|
+
for (const l of emptyState("No conversations yet.", "Start chatting to create one."))
|
|
109
|
+
line(l);
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
line();
|
|
113
|
+
line(sectionHeader(`Sessions (${items.length} of ${total})`));
|
|
114
|
+
const w = Math.max(0, ...items.map((s) => [...s.title].length));
|
|
115
|
+
for (const s of items) {
|
|
116
|
+
const active = s.session_id === activeId;
|
|
117
|
+
const marker = active ? icon.active : " ";
|
|
118
|
+
const title = (active ? c.brand : c.value)(s.title.padEnd(w));
|
|
119
|
+
const meta = c.dim(`${s.message_count} msgs · ${timeAgo(s.last_activity)} · ${s.session_id.slice(0, 8)}`);
|
|
120
|
+
line(` ${marker} ${title} ${meta}`);
|
|
121
|
+
}
|
|
122
|
+
line();
|
|
123
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { ApiError } from "../services/api.js";
|
|
4
|
+
import { errorLine, info, kv, line, success } from "../services/output.js";
|
|
5
|
+
import { withSpinner } from "../services/spinner.js";
|
|
6
|
+
/**
|
|
7
|
+
* `cos upload <file>` — upload a file (POST /v1/files) and immediately
|
|
8
|
+
* kick off indexing (POST /v1/files/:id/process). The file id is remembered
|
|
9
|
+
* locally so `cos files` can list it and `chat` can reference it later.
|
|
10
|
+
*/
|
|
11
|
+
export function registerUpload(program, ctx) {
|
|
12
|
+
program
|
|
13
|
+
.command("upload")
|
|
14
|
+
.description("Upload a file and start processing it")
|
|
15
|
+
.argument("<file>", "path to the file to upload")
|
|
16
|
+
.option("--no-process", "upload only; skip the processing/indexing step")
|
|
17
|
+
.action(async (file, opts) => {
|
|
18
|
+
const client = ctx.requireAuth();
|
|
19
|
+
const filePath = path.resolve(file);
|
|
20
|
+
if (!fs.existsSync(filePath) || !fs.statSync(filePath).isFile()) {
|
|
21
|
+
errorLine(`No such file: ${filePath}`);
|
|
22
|
+
process.exitCode = 1;
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
try {
|
|
26
|
+
const uploaded = await withSpinner(`Uploading ${path.basename(filePath)}…`, () => client.uploadFile(filePath));
|
|
27
|
+
success("Uploaded.");
|
|
28
|
+
kv("File id", uploaded.file_id);
|
|
29
|
+
kv("Name", uploaded.filename);
|
|
30
|
+
kv("Type", uploaded.file_type);
|
|
31
|
+
kv("Size", `${(uploaded.file_size / 1024).toFixed(1)} KB`);
|
|
32
|
+
ctx.config.addUpload({
|
|
33
|
+
file_id: uploaded.file_id,
|
|
34
|
+
filename: uploaded.filename,
|
|
35
|
+
file_type: uploaded.file_type,
|
|
36
|
+
uploaded_at: new Date().toISOString()
|
|
37
|
+
});
|
|
38
|
+
if (opts.process) {
|
|
39
|
+
const processed = await withSpinner("Processing…", () => client.processFile(uploaded.file_id));
|
|
40
|
+
kv("Status", processed.status);
|
|
41
|
+
info("Processing runs in the background; the file is usable once indexed.");
|
|
42
|
+
}
|
|
43
|
+
line();
|
|
44
|
+
}
|
|
45
|
+
catch (err) {
|
|
46
|
+
errorLine(err instanceof ApiError ? `${err.message} (${err.code})` : err.message);
|
|
47
|
+
process.exitCode = 1;
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import chalk from "chalk";
|
|
2
|
+
import { heading, kv, line } from "../services/output.js";
|
|
3
|
+
import { withSpinner } from "../services/spinner.js";
|
|
4
|
+
/**
|
|
5
|
+
* `cos usage` — requests, tokens and estimated cost for the current
|
|
6
|
+
* project, with today / this-month breakdowns, from GET /v1/usage.
|
|
7
|
+
*/
|
|
8
|
+
export function registerUsage(program, ctx) {
|
|
9
|
+
program
|
|
10
|
+
.command("usage")
|
|
11
|
+
.description("Show requests, tokens and estimated cost for this project")
|
|
12
|
+
.action(async () => {
|
|
13
|
+
const client = ctx.requireAuth();
|
|
14
|
+
const usage = await withSpinner("Loading usage…", () => client.usage());
|
|
15
|
+
heading(`Usage · project ${usage.project_id}`);
|
|
16
|
+
kv("Requests", String(usage.requests));
|
|
17
|
+
kv("Successful", chalk.green(String(usage.successful_requests)));
|
|
18
|
+
kv("Failed", usage.failed_requests > 0 ? chalk.red(String(usage.failed_requests)) : "0");
|
|
19
|
+
kv("Tokens", usage.tokens_used.toLocaleString());
|
|
20
|
+
kv("Est. cost", usage.estimated_cost);
|
|
21
|
+
period("Today", usage.daily_usage);
|
|
22
|
+
period("This month", usage.monthly_usage);
|
|
23
|
+
line();
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
function period(label, p) {
|
|
27
|
+
heading(label);
|
|
28
|
+
kv("Requests", String(p.requests));
|
|
29
|
+
kv("Tokens", p.tokens_used.toLocaleString());
|
|
30
|
+
kv("Est. cost", p.estimated_cost);
|
|
31
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import chalk from "chalk";
|
|
2
|
+
import { cliVersion } from "../services/meta.js";
|
|
3
|
+
import { kv, line } from "../services/output.js";
|
|
4
|
+
/**
|
|
5
|
+
* `cos version` — CLI version (from package.json) + best-effort live API
|
|
6
|
+
* version. Prints:
|
|
7
|
+
* Carrier OS CLI 0.1.0
|
|
8
|
+
* API Version v1
|
|
9
|
+
* Endpoint http://localhost:5000/v1
|
|
10
|
+
*/
|
|
11
|
+
export function registerVersion(program, ctx) {
|
|
12
|
+
program
|
|
13
|
+
.command("version")
|
|
14
|
+
.description("Print the CLI and API versions")
|
|
15
|
+
.action(async () => {
|
|
16
|
+
line();
|
|
17
|
+
line(` ${chalk.bold.white("Carrier OS CLI")} ${cliVersion()}`);
|
|
18
|
+
try {
|
|
19
|
+
const health = await ctx.client().health();
|
|
20
|
+
kv("API Version", health.version);
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
kv("API Version", chalk.dim("unreachable"));
|
|
24
|
+
}
|
|
25
|
+
kv("Endpoint", ctx.config.get("apiUrl") ?? "—");
|
|
26
|
+
line();
|
|
27
|
+
});
|
|
28
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { ApiError } from "../services/api.js";
|
|
2
|
+
import { heading, kv, line, warn } from "../services/output.js";
|
|
3
|
+
import { withSpinner } from "../services/spinner.js";
|
|
4
|
+
/**
|
|
5
|
+
* `cos whoami` — show the identity behind the stored key. Re-verifies
|
|
6
|
+
* against the API for freshness, falling back to the cached scope if offline.
|
|
7
|
+
*/
|
|
8
|
+
export function registerWhoami(program, ctx) {
|
|
9
|
+
program
|
|
10
|
+
.command("whoami")
|
|
11
|
+
.description("Show the workspace, project and account for the current key")
|
|
12
|
+
.action(async () => {
|
|
13
|
+
const client = ctx.requireAuth();
|
|
14
|
+
try {
|
|
15
|
+
const scope = await withSpinner("Checking…", () => client.verify());
|
|
16
|
+
ctx.config.set("scope", scope);
|
|
17
|
+
render(scope, false);
|
|
18
|
+
}
|
|
19
|
+
catch (err) {
|
|
20
|
+
const cached = ctx.config.get("scope");
|
|
21
|
+
if (cached) {
|
|
22
|
+
warn(`Could not reach the API (${err instanceof ApiError ? err.code : "error"}); showing cached details.`);
|
|
23
|
+
render(cached, true);
|
|
24
|
+
}
|
|
25
|
+
else {
|
|
26
|
+
throw err;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
function render(scope, cached) {
|
|
32
|
+
heading(cached ? "Account (cached)" : "Account");
|
|
33
|
+
kv("Workspace", `${scope.workspace.name} (${scope.workspace.slug})`);
|
|
34
|
+
kv("Project", scope.project.name);
|
|
35
|
+
kv("Environment", scope.project.environment);
|
|
36
|
+
kv("Key", `${scope.apiKey.name} · ${scope.apiKey.type}`);
|
|
37
|
+
if (scope.user)
|
|
38
|
+
kv("Account", scope.user.email);
|
|
39
|
+
line();
|
|
40
|
+
}
|
package/dist/main.js
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { Command, CommanderError } from "commander";
|
|
3
|
+
import { registerChat } from "./commands/chat.js";
|
|
4
|
+
import { registerDoctor } from "./commands/doctor.js";
|
|
5
|
+
import { registerFiles } from "./commands/files.js";
|
|
6
|
+
import { registerHelp } from "./commands/help.js";
|
|
7
|
+
import { registerHistory } from "./commands/history.js";
|
|
8
|
+
import { registerLogin } from "./commands/login.js";
|
|
9
|
+
import { registerLogout } from "./commands/logout.js";
|
|
10
|
+
import { registerModels } from "./commands/models.js";
|
|
11
|
+
import { registerModes } from "./commands/modes.js";
|
|
12
|
+
import { registerModeModel } from "./commands/mode-model.js";
|
|
13
|
+
import { registerSessions } from "./commands/sessions.js";
|
|
14
|
+
import { registerUpload } from "./commands/upload.js";
|
|
15
|
+
import { registerUsage } from "./commands/usage.js";
|
|
16
|
+
import { registerVersion } from "./commands/version.js";
|
|
17
|
+
import { registerWhoami } from "./commands/whoami.js";
|
|
18
|
+
import { ApiError } from "./services/api.js";
|
|
19
|
+
import { ConfigStore } from "./services/config.js";
|
|
20
|
+
import { AuthRequiredError, CommandContext } from "./services/context.js";
|
|
21
|
+
import { cliVersion } from "./services/meta.js";
|
|
22
|
+
import { errorLine } from "./services/output.js";
|
|
23
|
+
import { runShell } from "./shell/shell.js";
|
|
24
|
+
import { loadAccent } from "./ui/theme.js";
|
|
25
|
+
async function main() {
|
|
26
|
+
const ctx = new CommandContext(new ConfigStore());
|
|
27
|
+
// Restore the saved accent color before anything renders.
|
|
28
|
+
loadAccent(ctx.config.get("theme")?.accent);
|
|
29
|
+
const program = new Command();
|
|
30
|
+
program
|
|
31
|
+
.name("cos")
|
|
32
|
+
.description("Carrier OS command-line interface")
|
|
33
|
+
.version(cliVersion(), "-v, --version", "print the CLI version")
|
|
34
|
+
.configureHelp({ sortSubcommands: true })
|
|
35
|
+
.showHelpAfterError("(run `cos --help` for a list of commands)")
|
|
36
|
+
// Throw instead of calling process.exit, so the shell can re-invoke commands
|
|
37
|
+
// via program.parseAsync and survive parse errors.
|
|
38
|
+
.exitOverride();
|
|
39
|
+
// Phase A — auth & diagnostics
|
|
40
|
+
registerLogin(program, ctx);
|
|
41
|
+
registerLogout(program, ctx);
|
|
42
|
+
registerWhoami(program, ctx);
|
|
43
|
+
registerVersion(program, ctx);
|
|
44
|
+
registerDoctor(program, ctx);
|
|
45
|
+
// Phase B — chat, sessions, history
|
|
46
|
+
registerChat(program, ctx);
|
|
47
|
+
registerSessions(program, ctx);
|
|
48
|
+
registerHistory(program, ctx);
|
|
49
|
+
// Phase C — files, usage, models, modes, guide
|
|
50
|
+
registerUpload(program, ctx);
|
|
51
|
+
registerFiles(program, ctx);
|
|
52
|
+
registerUsage(program, ctx);
|
|
53
|
+
registerModels(program, ctx);
|
|
54
|
+
registerModes(program, ctx);
|
|
55
|
+
registerModeModel(program, ctx);
|
|
56
|
+
registerHelp(program, ctx);
|
|
57
|
+
// Explicit `cos shell` also opens it (hidden; not a default command, so
|
|
58
|
+
// unknown commands still error instead of silently launching the shell).
|
|
59
|
+
program
|
|
60
|
+
.command("shell", { hidden: true })
|
|
61
|
+
.description("Interactive Carrier OS shell (default when run with no command)")
|
|
62
|
+
.action(async () => {
|
|
63
|
+
await runShell(ctx, program);
|
|
64
|
+
});
|
|
65
|
+
// No command at all → the interactive shell. Any provided command is parsed
|
|
66
|
+
// normally (so `cos bogus` errors rather than opening the shell).
|
|
67
|
+
if (process.argv.slice(2).length === 0) {
|
|
68
|
+
await runShell(ctx, program);
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
await program.parseAsync(process.argv);
|
|
72
|
+
}
|
|
73
|
+
main().catch((err) => {
|
|
74
|
+
// @inquirer throws this when the user hits Ctrl+C at a prompt — clean exit.
|
|
75
|
+
if (err instanceof Error && err.name === "ExitPromptError") {
|
|
76
|
+
process.exit(0);
|
|
77
|
+
}
|
|
78
|
+
// Commander with exitOverride throws for --help/--version/parse errors; it has
|
|
79
|
+
// already printed whatever it needed to.
|
|
80
|
+
if (err instanceof CommanderError) {
|
|
81
|
+
process.exit(err.exitCode);
|
|
82
|
+
}
|
|
83
|
+
if (err instanceof AuthRequiredError) {
|
|
84
|
+
errorLine(err.message);
|
|
85
|
+
process.exit(1);
|
|
86
|
+
}
|
|
87
|
+
if (err instanceof ApiError) {
|
|
88
|
+
errorLine(`${err.message} (${err.code})`);
|
|
89
|
+
}
|
|
90
|
+
else {
|
|
91
|
+
errorLine(err instanceof Error ? err.message : String(err));
|
|
92
|
+
}
|
|
93
|
+
process.exit(1);
|
|
94
|
+
});
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import axios, { isAxiosError } from "axios";
|
|
4
|
+
import FormData from "form-data";
|
|
5
|
+
/** A typed, envelope-aware error surfaced by the API client. */
|
|
6
|
+
export class ApiError extends Error {
|
|
7
|
+
code;
|
|
8
|
+
status;
|
|
9
|
+
constructor(code, message, status) {
|
|
10
|
+
super(message);
|
|
11
|
+
this.code = code;
|
|
12
|
+
this.status = status;
|
|
13
|
+
this.name = "ApiError";
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* ApiClient — the ONLY place the CLI talks HTTP. Each method maps 1:1 to a
|
|
18
|
+
* public /v1 endpoint and returns the already-unwrapped `data` payload, or
|
|
19
|
+
* throws an ApiError carrying the server's `{code,message}`. No business logic
|
|
20
|
+
* lives here; it is a thin, strongly-typed transport over the public contract.
|
|
21
|
+
*/
|
|
22
|
+
export class ApiClient {
|
|
23
|
+
baseUrl;
|
|
24
|
+
http;
|
|
25
|
+
constructor(baseUrl, secretKey) {
|
|
26
|
+
this.baseUrl = baseUrl;
|
|
27
|
+
this.http = axios.create({
|
|
28
|
+
baseURL: baseUrl,
|
|
29
|
+
timeout: 60_000,
|
|
30
|
+
headers: secretKey ? { Authorization: `Bearer ${secretKey}` } : {}
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
async request(config) {
|
|
34
|
+
try {
|
|
35
|
+
const res = await this.http.request(config);
|
|
36
|
+
const body = res.data;
|
|
37
|
+
if (body?.success && body.data !== undefined)
|
|
38
|
+
return body.data;
|
|
39
|
+
throw new ApiError(body?.error?.code ?? "REQUEST_FAILED", body?.error?.message ?? "Request failed.", res.status);
|
|
40
|
+
}
|
|
41
|
+
catch (err) {
|
|
42
|
+
if (err instanceof ApiError)
|
|
43
|
+
throw err;
|
|
44
|
+
if (isAxiosError(err)) {
|
|
45
|
+
const status = err.response?.status;
|
|
46
|
+
const body = err.response?.data;
|
|
47
|
+
// Standard envelope error from the API.
|
|
48
|
+
if (body?.error?.code || body?.error?.message) {
|
|
49
|
+
throw new ApiError(body.error.code || "REQUEST_FAILED", body.error.message || `Request failed (HTTP ${status}).`, status);
|
|
50
|
+
}
|
|
51
|
+
// Couldn't connect at all.
|
|
52
|
+
if (["ECONNREFUSED", "ENOTFOUND", "ECONNABORTED", "ETIMEDOUT"].includes(err.code ?? "")) {
|
|
53
|
+
throw new ApiError("NETWORK_ERROR", `Could not reach the API at ${this.baseUrl}.`, 0);
|
|
54
|
+
}
|
|
55
|
+
// Reached a server, but it didn't speak our envelope (wrong URL, proxy,
|
|
56
|
+
// gateway page, …). Never surface an empty message.
|
|
57
|
+
throw new ApiError(status ? `HTTP_${status}` : "REQUEST_FAILED", err.message || (status ? `Request failed (HTTP ${status}).` : "Request failed."), status);
|
|
58
|
+
}
|
|
59
|
+
throw new ApiError("UNKNOWN", err instanceof Error ? err.message : String(err));
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
// ── Auth / meta ─────────────────────────────────────────────────────────────
|
|
63
|
+
health() {
|
|
64
|
+
return this.request({ method: "GET", url: "/health" });
|
|
65
|
+
}
|
|
66
|
+
verify() {
|
|
67
|
+
return this.request({ method: "POST", url: "/auth/verify" });
|
|
68
|
+
}
|
|
69
|
+
models() {
|
|
70
|
+
return this.request({ method: "GET", url: "/models" });
|
|
71
|
+
}
|
|
72
|
+
chatModels() {
|
|
73
|
+
return this.request({ method: "GET", url: "/models/chat" });
|
|
74
|
+
}
|
|
75
|
+
// ── Chat ────────────────────────────────────────────────────────────────────
|
|
76
|
+
chat(body) {
|
|
77
|
+
return this.request({ method: "POST", url: "/chat", data: body });
|
|
78
|
+
}
|
|
79
|
+
// ── Sessions / conversations ─────────────────────────────────────────────────
|
|
80
|
+
conversations(params) {
|
|
81
|
+
return this.request({ method: "GET", url: "/conversations", params });
|
|
82
|
+
}
|
|
83
|
+
session(id) {
|
|
84
|
+
return this.request({ method: "GET", url: `/sessions/${id}` });
|
|
85
|
+
}
|
|
86
|
+
sessionMessages(id) {
|
|
87
|
+
return this.request({ method: "GET", url: `/sessions/${id}/messages` });
|
|
88
|
+
}
|
|
89
|
+
createSession(title) {
|
|
90
|
+
return this.request({ method: "POST", url: "/sessions", data: { title } });
|
|
91
|
+
}
|
|
92
|
+
deleteSession(id) {
|
|
93
|
+
return this.request({ method: "DELETE", url: `/sessions/${id}` });
|
|
94
|
+
}
|
|
95
|
+
// ── Usage ────────────────────────────────────────────────────────────────────
|
|
96
|
+
usage() {
|
|
97
|
+
return this.request({ method: "GET", url: "/usage" });
|
|
98
|
+
}
|
|
99
|
+
// ── Files ────────────────────────────────────────────────────────────────────
|
|
100
|
+
async uploadFile(filePath) {
|
|
101
|
+
const form = new FormData();
|
|
102
|
+
form.append("file", fs.createReadStream(filePath), path.basename(filePath));
|
|
103
|
+
return this.request({
|
|
104
|
+
method: "POST",
|
|
105
|
+
url: "/files",
|
|
106
|
+
data: form,
|
|
107
|
+
headers: form.getHeaders(),
|
|
108
|
+
maxContentLength: Infinity,
|
|
109
|
+
maxBodyLength: Infinity
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
processFile(fileId) {
|
|
113
|
+
return this.request({ method: "POST", url: `/files/${fileId}/process` });
|
|
114
|
+
}
|
|
115
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
/** Production default; override at login with `--url` or via CARRIEROS_API_URL. */
|
|
5
|
+
export const DEFAULT_API_URL = process.env.CARRIEROS_API_URL || "https://api.carrieros.ai/v1";
|
|
6
|
+
/**
|
|
7
|
+
* ConfigStore — the single owner of on-disk CLI state. Everything the CLI
|
|
8
|
+
* persists (API key, active session, cached scope, recent uploads) lives in one
|
|
9
|
+
* JSON file so the rest of the app never touches the filesystem directly.
|
|
10
|
+
*
|
|
11
|
+
* Windows-first: `%APPDATA%/CarrierOS/config.json`; falls back to
|
|
12
|
+
* `~/.carrieros/config.json` on other platforms.
|
|
13
|
+
*/
|
|
14
|
+
export class ConfigStore {
|
|
15
|
+
dir;
|
|
16
|
+
file;
|
|
17
|
+
data;
|
|
18
|
+
constructor() {
|
|
19
|
+
this.dir = ConfigStore.resolveDir();
|
|
20
|
+
this.file = path.join(this.dir, "config.json");
|
|
21
|
+
this.data = this.read();
|
|
22
|
+
}
|
|
23
|
+
static resolveDir() {
|
|
24
|
+
const appData = process.env.APPDATA;
|
|
25
|
+
if (appData)
|
|
26
|
+
return path.join(appData, "CarrierOS");
|
|
27
|
+
return path.join(os.homedir(), ".carrieros");
|
|
28
|
+
}
|
|
29
|
+
read() {
|
|
30
|
+
try {
|
|
31
|
+
const parsed = JSON.parse(fs.readFileSync(this.file, "utf8"));
|
|
32
|
+
return { apiUrl: DEFAULT_API_URL, ...parsed };
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return { apiUrl: DEFAULT_API_URL };
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
write() {
|
|
39
|
+
fs.mkdirSync(this.dir, { recursive: true });
|
|
40
|
+
// 0o600 = owner-only; a no-op on Windows ACLs but correct on POSIX.
|
|
41
|
+
fs.writeFileSync(this.file, JSON.stringify(this.data, null, 2), { mode: 0o600 });
|
|
42
|
+
}
|
|
43
|
+
get all() {
|
|
44
|
+
return this.data;
|
|
45
|
+
}
|
|
46
|
+
get(key) {
|
|
47
|
+
return this.data[key];
|
|
48
|
+
}
|
|
49
|
+
set(key, value) {
|
|
50
|
+
this.data[key] = value;
|
|
51
|
+
this.write();
|
|
52
|
+
}
|
|
53
|
+
update(patch) {
|
|
54
|
+
this.data = { ...this.data, ...patch };
|
|
55
|
+
this.write();
|
|
56
|
+
}
|
|
57
|
+
get isAuthenticated() {
|
|
58
|
+
return Boolean(this.data.secretKey);
|
|
59
|
+
}
|
|
60
|
+
/** Wipe credentials + derived state on logout (keeps apiUrl). */
|
|
61
|
+
clearAuth() {
|
|
62
|
+
delete this.data.secretKey;
|
|
63
|
+
delete this.data.sessionId;
|
|
64
|
+
delete this.data.scope;
|
|
65
|
+
this.write();
|
|
66
|
+
}
|
|
67
|
+
addUpload(record) {
|
|
68
|
+
const list = this.data.uploads ?? [];
|
|
69
|
+
this.data.uploads = [record, ...list].slice(0, 25);
|
|
70
|
+
this.write();
|
|
71
|
+
}
|
|
72
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { ApiClient } from "./api.js";
|
|
2
|
+
import { DEFAULT_API_URL } from "./config.js";
|
|
3
|
+
/**
|
|
4
|
+
* Thrown by requireAuth when no key is configured. Unlike a process.exit, this
|
|
5
|
+
* can be caught — so the interactive shell can keep running after a failed
|
|
6
|
+
* command, while standalone commands still turn it into a clean exit(1).
|
|
7
|
+
*/
|
|
8
|
+
export class AuthRequiredError extends Error {
|
|
9
|
+
constructor(message = "You are not logged in. Run `cos login` first.") {
|
|
10
|
+
super(message);
|
|
11
|
+
this.name = "AuthRequiredError";
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* CommandContext is the single dependency every command receives. Commands
|
|
16
|
+
* depend on this abstraction (not on axios/fs directly), which keeps them thin
|
|
17
|
+
* and testable and satisfies the dependency-inversion principle.
|
|
18
|
+
*/
|
|
19
|
+
export class CommandContext {
|
|
20
|
+
config;
|
|
21
|
+
constructor(config) {
|
|
22
|
+
this.config = config;
|
|
23
|
+
}
|
|
24
|
+
/** A client built from current config (anonymous if not logged in). */
|
|
25
|
+
client() {
|
|
26
|
+
return new ApiClient(this.config.get("apiUrl") ?? DEFAULT_API_URL, this.config.get("secretKey"));
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* A client guaranteed to carry a key, or a clean exit with guidance. Use this
|
|
30
|
+
* in every command that hits an authenticated endpoint.
|
|
31
|
+
*/
|
|
32
|
+
requireAuth() {
|
|
33
|
+
if (!this.config.isAuthenticated) {
|
|
34
|
+
throw new AuthRequiredError();
|
|
35
|
+
}
|
|
36
|
+
return this.client();
|
|
37
|
+
}
|
|
38
|
+
/** Default Carrier mode for chat (persisted, falls back to "general"). */
|
|
39
|
+
get mode() {
|
|
40
|
+
return this.config.get("mode") ?? "general";
|
|
41
|
+
}
|
|
42
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { ApiClient } from "./api.js";
|
|
2
|
+
/**
|
|
3
|
+
* The single source of truth for API-key login: verify the key against
|
|
4
|
+
* POST /v1/auth/verify and, on success, persist it (and its scope). Shared by
|
|
5
|
+
* the `login` command and the interactive shell's first-run flow so there is
|
|
6
|
+
* exactly one authentication path.
|
|
7
|
+
*
|
|
8
|
+
* Throws ApiError on failure (invalid key, unreachable endpoint, …).
|
|
9
|
+
*/
|
|
10
|
+
export async function verifyAndSaveKey(ctx, apiUrl, key) {
|
|
11
|
+
const client = new ApiClient(apiUrl, key);
|
|
12
|
+
const scope = await client.verify();
|
|
13
|
+
ctx.config.update({ secretKey: key, scope });
|
|
14
|
+
return scope;
|
|
15
|
+
}
|