@carrieros/cli 0.1.0 → 0.3.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 (104) hide show
  1. package/README.md +142 -57
  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 +102 -13
  7. package/dist/commands/context.js +160 -0
  8. package/dist/commands/doctor.js +53 -8
  9. package/dist/commands/files.js +84 -23
  10. package/dist/commands/help.js +3 -1
  11. package/dist/commands/history.js +88 -23
  12. package/dist/commands/login.js +44 -41
  13. package/dist/commands/logout.js +13 -4
  14. package/dist/commands/memory.js +162 -0
  15. package/dist/commands/mode-model.js +39 -3
  16. package/dist/commands/modes.js +4 -1
  17. package/dist/commands/project.js +106 -0
  18. package/dist/commands/repo.js +146 -0
  19. package/dist/commands/repos.js +61 -0
  20. package/dist/commands/review.js +92 -0
  21. package/dist/commands/scope.js +152 -0
  22. package/dist/commands/search.js +92 -0
  23. package/dist/commands/sessions.js +219 -65
  24. package/dist/commands/settings.js +87 -0
  25. package/dist/commands/update.js +159 -0
  26. package/dist/commands/upload.js +204 -31
  27. package/dist/commands/usage.js +212 -16
  28. package/dist/commands/whoami.js +2 -1
  29. package/dist/ide/editor-context.js +172 -0
  30. package/dist/ide/ide-session.js +94 -0
  31. package/dist/ide/tool-host.js +109 -0
  32. package/dist/main.js +30 -1
  33. package/dist/services/api.js +171 -13
  34. package/dist/services/chat-stream.js +145 -0
  35. package/dist/services/checkpoints.js +116 -0
  36. package/dist/services/client-tools.js +260 -0
  37. package/dist/services/command-coordinator.js +200 -0
  38. package/dist/services/command-policy.js +404 -0
  39. package/dist/services/config.js +249 -22
  40. package/dist/services/context.js +307 -6
  41. package/dist/services/device-auth.js +261 -0
  42. package/dist/services/diff.js +196 -0
  43. package/dist/services/env-policy.js +108 -0
  44. package/dist/services/file-detect.js +104 -0
  45. package/dist/services/file-resolver.js +199 -0
  46. package/dist/services/file-upload.js +126 -0
  47. package/dist/services/git-tools.js +248 -0
  48. package/dist/services/glob-match.js +164 -0
  49. package/dist/services/helper-bin.js +64 -0
  50. package/dist/services/ignore-rules.js +189 -0
  51. package/dist/services/job-helper.js +307 -0
  52. package/dist/services/local-files.js +517 -0
  53. package/dist/services/local-tools.js +432 -0
  54. package/dist/services/login-flow.js +120 -10
  55. package/dist/services/meta.js +3 -1
  56. package/dist/services/mutation-coordinator.js +161 -0
  57. package/dist/services/mutations.js +493 -0
  58. package/dist/services/open-url.js +68 -0
  59. package/dist/services/output.js +13 -5
  60. package/dist/services/packaged.js +24 -0
  61. package/dist/services/process-runner.js +406 -0
  62. package/dist/services/project-context.js +298 -0
  63. package/dist/services/redaction.js +201 -0
  64. package/dist/services/secure-store.js +197 -0
  65. package/dist/services/session-resolver.js +108 -0
  66. package/dist/services/sia.js +51 -0
  67. package/dist/services/spinner.js +23 -1
  68. package/dist/services/update.js +286 -0
  69. package/dist/services/workspace-registry.js +309 -0
  70. package/dist/services/workspace.js +573 -0
  71. package/dist/shell/shell-chat.js +1115 -59
  72. package/dist/shell/shell-commands.js +220 -19
  73. package/dist/shell/shell-prompt.js +89 -37
  74. package/dist/shell/shell-renderer.js +19 -38
  75. package/dist/shell/shell-router.js +19 -3
  76. package/dist/shell/shell.js +232 -44
  77. package/dist/types/index.js +3 -1
  78. package/dist/ui/approval.js +81 -0
  79. package/dist/ui/banner.js +55 -13
  80. package/dist/ui/btw-overlay.js +230 -0
  81. package/dist/ui/change-review.js +87 -0
  82. package/dist/ui/chat-renderer.js +223 -29
  83. package/dist/ui/color-picker.js +21 -0
  84. package/dist/ui/colors.js +9 -1
  85. package/dist/ui/command-filter.js +40 -5
  86. package/dist/ui/command-palette.js +122 -62
  87. package/dist/ui/command-registry.js +85 -11
  88. package/dist/ui/command-review.js +138 -0
  89. package/dist/ui/composer-layout.js +41 -0
  90. package/dist/ui/conversation.js +398 -0
  91. package/dist/ui/interrupt.js +35 -0
  92. package/dist/ui/live.js +18 -1
  93. package/dist/ui/markdown.js +63 -9
  94. package/dist/ui/message.js +14 -31
  95. package/dist/ui/screen-prompt.js +181 -0
  96. package/dist/ui/screen.js +289 -0
  97. package/dist/ui/select.js +193 -29
  98. package/dist/ui/sia-qa.js +213 -0
  99. package/dist/ui/text-prompt.js +74 -0
  100. package/dist/ui/theme.js +17 -0
  101. package/dist/ui/trust.js +93 -0
  102. package/dist/ui/ui.js +4 -1
  103. package/package.json +17 -6
  104. package/dist/ui/activity.js +0 -77
@@ -0,0 +1,432 @@
1
+ import path from "node:path";
2
+ import { LocalFileError, globFiles, isPathIgnored, listDirectory, readFile, resolveInside, searchFiles, workspaceRoot } from "./local-files.js";
3
+ import { RepositoryError, activeRepository, inWorkspaceMode, isWildcardSelector, listRepositories, repositoryTrust, resolveRepository } from "./workspace-registry.js";
4
+ import { GitToolError, gitDiff, gitStatus } from "./git-tools.js";
5
+ import { resolveWorkspaceFile } from "./file-resolver.js";
6
+ /**
7
+ * Tool descriptors, in the JSON-schema shape the engine already uses for
8
+ * PROJECT_TOOLS. Exported so a future protocol can advertise the client's
9
+ * capabilities without this list being retyped on the server, where it would
10
+ * immediately drift.
11
+ */
12
+ export const LOCAL_TOOL_DEFINITIONS = [
13
+ {
14
+ type: "function",
15
+ function: {
16
+ name: "read_file",
17
+ description: "Read one text file from the user's local project. Paths are relative to the project root.",
18
+ parameters: {
19
+ type: "object",
20
+ properties: {
21
+ path: { type: "string", description: "Project-relative path, e.g. src/auth.ts" }
22
+ },
23
+ required: ["path"]
24
+ }
25
+ }
26
+ },
27
+ {
28
+ type: "function",
29
+ function: {
30
+ name: "list_files",
31
+ description: "List files in the user's local project, optionally under a subdirectory or matching a glob.",
32
+ parameters: {
33
+ type: "object",
34
+ properties: {
35
+ path: { type: "string", description: "Subdirectory to list, relative to the project root" },
36
+ glob: { type: "string", description: "Glob such as **/*.ts" },
37
+ depth: { type: "number", description: "How deep to descend" }
38
+ }
39
+ }
40
+ }
41
+ },
42
+ {
43
+ type: "function",
44
+ function: {
45
+ name: "search_files",
46
+ description: "Search the user's local project for literal text. Not semantic search.",
47
+ parameters: {
48
+ type: "object",
49
+ properties: {
50
+ query: { type: "string", description: "Text to find" },
51
+ glob: { type: "string", description: "Restrict to files matching this glob" }
52
+ },
53
+ required: ["query"]
54
+ }
55
+ }
56
+ },
57
+ {
58
+ type: "function",
59
+ function: {
60
+ name: "git_status",
61
+ description: "Read the Git status of the user's local repository: branch, upstream, ahead/behind, and which " +
62
+ "files are staged, unstaged, untracked, renamed or deleted. Read-only. Prefer this over running " +
63
+ "`git status` as a command.",
64
+ parameters: {
65
+ type: "object",
66
+ properties: {}
67
+ }
68
+ }
69
+ },
70
+ {
71
+ type: "function",
72
+ function: {
73
+ name: "git_diff",
74
+ description: "Read the Git diff of the user's local repository, with a bounded patch and per-file line counts. " +
75
+ "Read-only. Prefer this over running `git diff` as a command. scope: working_tree (unstaged, the " +
76
+ "default), staged (index), or both (everything since HEAD).",
77
+ parameters: {
78
+ type: "object",
79
+ properties: {
80
+ scope: { type: "string", enum: ["working_tree", "staged", "both"], description: "Which changes to show." }
81
+ }
82
+ }
83
+ }
84
+ },
85
+ {
86
+ type: "function",
87
+ function: {
88
+ name: "resolve_local_file",
89
+ description: "Find which trusted repository a file or directory the user referenced belongs to, WITHOUT reading it. " +
90
+ "Use it when the user names a file/path in natural language and you do not already know its repository " +
91
+ "(e.g. \"read user.js\", \"open the hooks directory\"). Returns the repository and project-relative " +
92
+ "path to pass to read_file/search_files/edit_file, or a list of candidates when several match — then " +
93
+ "ask the user which one. It reads no file contents.",
94
+ parameters: {
95
+ type: "object",
96
+ properties: {
97
+ reference: { type: "string", description: "The file or directory the user referred to." },
98
+ kind: { type: "string", enum: ["file", "directory", "either"], description: "Restrict the match kind." }
99
+ },
100
+ required: ["reference"]
101
+ }
102
+ }
103
+ }
104
+ ];
105
+ export const LOCAL_TOOL_NAMES = LOCAL_TOOL_DEFINITIONS.map((t) => t.function.name);
106
+ /** Caps applied to whatever the caller asks for, so a request cannot set its own. */
107
+ const LIST_LIMIT = 500;
108
+ const SEARCH_LIMIT = 50;
109
+ /** Most bytes of one file a tool read returns; beyond this it reports truncated. */
110
+ export const TOOL_READ_BYTES = 256 * 1024;
111
+ /**
112
+ * Credential-shaped filenames that are never shared with the model, whether or
113
+ * not the project remembered to gitignore them. Conservative on purpose: these
114
+ * names almost never hold anything a question about the code needs.
115
+ */
116
+ const SENSITIVE_NAMES = [
117
+ /^\.env(\..+)?$/i,
118
+ /\.(pem|key|p12|pfx|keystore|jks)$/i,
119
+ /^id_(rsa|dsa|ecdsa|ed25519)(\.pub)?$/i,
120
+ /^\.(npmrc|pypirc|netrc|pgpass)$/i,
121
+ /^credentials(\.json)?$/i
122
+ ];
123
+ export function isSensitiveName(name) {
124
+ // `.env.example` and friends are documentation, not secrets.
125
+ if (/^\.env\.(example|sample|template|dist)$/i.test(name))
126
+ return false;
127
+ return SENSITIVE_NAMES.some((re) => re.test(name));
128
+ }
129
+ /** Lines as an editor shows them: a trailing newline does not start a new line. */
130
+ export function countLines(text) {
131
+ if (!text)
132
+ return 0;
133
+ const breaks = text.match(/\r\n|\r|\n/g)?.length ?? 0;
134
+ return /(\r\n|\r|\n)$/.test(text) ? breaks : breaks + 1;
135
+ }
136
+ function str(v) {
137
+ return typeof v === "string" && v.trim() ? v.trim() : undefined;
138
+ }
139
+ function num(v) {
140
+ return typeof v === "number" && Number.isFinite(v) ? v : undefined;
141
+ }
142
+ function fail(id, name, code, message) {
143
+ return { id, name, ok: false, error: { code, message } };
144
+ }
145
+ /**
146
+ * Execute one tool request.
147
+ *
148
+ * Never throws: a caller on the other end of a protocol needs a result it can
149
+ * correlate, and an exception that unwinds past the transport would strand the
150
+ * request id. Every failure comes back as `ok: false` with a code.
151
+ */
152
+ export function executeLocalTool(req) {
153
+ const id = typeof req?.id === "string" && req.id ? req.id : "unknown";
154
+ const name = typeof req?.name === "string" ? req.name : "";
155
+ const args = (req?.arguments ?? {});
156
+ if (!LOCAL_TOOL_NAMES.includes(name)) {
157
+ return fail(id, name, "UNKNOWN_TOOL", `No local tool named "${name}".`);
158
+ }
159
+ // Which repository this call is about. A NAME from the registry — never a
160
+ // path — so "../other-repo" cannot be smuggled in as a selector, and the
161
+ // path below is still resolved inside whichever root the name maps to.
162
+ const selector = args.repository;
163
+ const wildcard = isWildcardSelector(selector);
164
+ const wildcardOk = name === "list_files" || name === "search_files";
165
+ if (wildcard && !wildcardOk) {
166
+ return fail(id, name, "REPOSITORY_WILDCARD_NOT_ALLOWED", `${name} needs one repository; "*" is only for list_files and search_files.`);
167
+ }
168
+ let repo;
169
+ try {
170
+ repo = wildcard ? activeRepository() : resolveRepository(selector);
171
+ }
172
+ catch (err) {
173
+ if (err instanceof RepositoryError)
174
+ return fail(id, name, err.code, err.message);
175
+ throw err;
176
+ }
177
+ const root = repo.root;
178
+ // A content read of a NAMED (or active) repository must respect trust exactly
179
+ // as a wildcard read does. Without this, an explicit `repository` selector
180
+ // could reach an untrusted repository that git_status, git_diff and
181
+ // resolve_local_file already refuse. The wildcard branches filter with
182
+ // readableRepositories() themselves; here the single-target path reuses the
183
+ // same set, so the single-repository fallback (no repository trusted → the
184
+ // active one is still readable) is preserved and trust logic is not duplicated.
185
+ if (!wildcard && isContentReadTool(name) && !isReadableRepository(repo)) {
186
+ return fail(id, name, "REPOSITORY_NOT_TRUSTED", `${repo.name} is not a trusted repository. Ask the user to run /repo use ${repo.name} and confirm the trust prompt first.`);
187
+ }
188
+ try {
189
+ switch (name) {
190
+ case "read_file": {
191
+ const p = str(args.path);
192
+ if (!p)
193
+ return fail(id, name, "INVALID_ARGUMENTS", '"path" is required.');
194
+ // readFile does the containment and realpath checks; this layer does not
195
+ // re-implement them, it just refuses to bypass them. Capped lower than
196
+ // the display read: the result travels back to the server inside a JSON
197
+ // body, and a model gets nothing from a megabyte it cannot hold.
198
+ // A file no listing or search would surface is not readable by name
199
+ // either. This is what keeps a gitignored `.env` on the machine when the
200
+ // model — or a prompt in some README — asks for it directly.
201
+ const resolved = resolveInside(p, root);
202
+ const rel = path.relative(root, resolved);
203
+ if (isPathIgnored(rel, root)) {
204
+ return fail(id, name, "IGNORED_PATH", `${p} is excluded by the project's ignore rules.`);
205
+ }
206
+ if (isSensitiveName(path.basename(resolved))) {
207
+ return fail(id, name, "SENSITIVE_FILE", `${p} looks like a credentials file and is not shared.`);
208
+ }
209
+ const res = readFile({ path: p, maxBytes: TOOL_READ_BYTES, root });
210
+ return {
211
+ id,
212
+ name,
213
+ ok: true,
214
+ result: {
215
+ ...repositoryLabel(repo),
216
+ path: res.path,
217
+ content: res.text,
218
+ truncated: res.truncated,
219
+ size: res.size,
220
+ // Counted here, from the bytes on disk, because a model counting the
221
+ // lines of a long file by eye is exactly the kind of "roughly" this
222
+ // tool exists to replace. Omitted when the read was truncated — a
223
+ // count of the first N bytes would be a wrong answer, not a partial one.
224
+ ...(res.truncated ? {} : { line_count: countLines(res.text) })
225
+ }
226
+ };
227
+ }
228
+ case "list_files": {
229
+ const glob = str(args.glob);
230
+ const listOne = (handle) => {
231
+ if (glob) {
232
+ const res = globFiles({ pattern: glob, limit: LIST_LIMIT, root: handle.root });
233
+ return { files: res.paths.map((f) => ({ path: f })), truncated: res.truncated };
234
+ }
235
+ const res = listDirectory({
236
+ root: handle.root,
237
+ path: str(args.path),
238
+ depth: num(args.depth) ?? 3,
239
+ limit: LIST_LIMIT
240
+ });
241
+ return {
242
+ files: res.entries.filter((e) => e.type === "file").map((e) => ({ path: e.path, size: e.size })),
243
+ directories: res.entries.filter((e) => e.type === "dir").map((e) => e.path),
244
+ truncated: res.truncated
245
+ };
246
+ };
247
+ if (wildcard) {
248
+ const perRepo = readableRepositories().map((handle) => ({ ...repositoryLabel(handle), ...listOne(handle) }));
249
+ return { id, name, ok: true, result: { repositories: perRepo, truncated: perRepo.some((r) => r.truncated === true) } };
250
+ }
251
+ return { id, name, ok: true, result: { ...repositoryLabel(repo), ...listOne(repo) } };
252
+ }
253
+ case "search_files": {
254
+ const query = str(args.query);
255
+ if (!query)
256
+ return fail(id, name, "INVALID_ARGUMENTS", '"query" is required.');
257
+ // Each repository is searched on its own, under its own limits, and its
258
+ // matches are labelled — two files called src/auth.ts in two
259
+ // repositories must never arrive as one ambiguous list.
260
+ const searchOne = (handle) => {
261
+ const res = searchFiles({ query, glob: str(args.glob), limit: SEARCH_LIMIT, root: handle.root });
262
+ return {
263
+ // Search already skips ignored paths; a credentials file that is NOT
264
+ // gitignored would still show its matching line, so drop those.
265
+ matches: res.matches
266
+ .filter((m) => !isSensitiveName(path.basename(m.path)))
267
+ .map((m) => ({ path: m.path, line: m.line, snippet: m.text })),
268
+ truncated: res.truncated
269
+ };
270
+ };
271
+ if (wildcard) {
272
+ const perRepo = readableRepositories().map((handle) => ({ ...repositoryLabel(handle), ...searchOne(handle) }));
273
+ return { id, name, ok: true, result: { repositories: perRepo, truncated: perRepo.some((r) => r.truncated === true) } };
274
+ }
275
+ return { id, name, ok: true, result: { ...repositoryLabel(repo), ...searchOne(repo) } };
276
+ }
277
+ case "resolve_local_file": {
278
+ const reference = str(args.reference);
279
+ if (!reference)
280
+ return fail(id, name, "INVALID_ARGUMENTS", '"reference" is required.');
281
+ const kindArg = str(args.kind);
282
+ const kind = kindArg === "file" || kindArg === "directory" ? kindArg : "either";
283
+ const res = resolveWorkspaceFile({ reference, kind });
284
+ if (res.status === "resolved" && res.match) {
285
+ return {
286
+ id,
287
+ name,
288
+ ok: true,
289
+ result: {
290
+ status: "resolved",
291
+ repository: res.match.repositoryName,
292
+ path: res.match.relativePath,
293
+ is_directory: res.match.isDirectory,
294
+ match_type: res.match.matchType,
295
+ confidence: res.match.confidence
296
+ }
297
+ };
298
+ }
299
+ if (res.status === "ambiguous" && res.candidates) {
300
+ return {
301
+ id,
302
+ name,
303
+ ok: true,
304
+ result: {
305
+ status: "ambiguous",
306
+ candidates: res.candidates.map((c) => ({
307
+ repository: c.repositoryName,
308
+ path: c.relativePath,
309
+ is_directory: c.isDirectory,
310
+ match_type: c.matchType
311
+ }))
312
+ }
313
+ };
314
+ }
315
+ if (res.status === "not_found") {
316
+ return { id, name, ok: true, result: { status: "not_found", message: res.error?.message ?? "No match." } };
317
+ }
318
+ return fail(id, name, res.error?.code ?? "RESOLVE_FAILED", res.error?.message ?? "Could not resolve the reference.");
319
+ }
320
+ case "git_status": {
321
+ // A read, but of a whole repository's state — so it honours trust the
322
+ // same way a wildcard read does: an untrusted repository is not
323
+ // inspected, even when named explicitly.
324
+ if (repositoryTrust(repo) !== "trusted") {
325
+ return fail(id, name, "REPOSITORY_NOT_TRUSTED", `${repo.name} is not a trusted repository.`);
326
+ }
327
+ const s = gitStatus(root);
328
+ return {
329
+ id,
330
+ name,
331
+ ok: true,
332
+ result: {
333
+ ...repositoryLabel(repo),
334
+ branch: s.branch,
335
+ detached: s.detached,
336
+ head: s.head,
337
+ upstream: s.upstream,
338
+ ahead: s.ahead,
339
+ behind: s.behind,
340
+ clean: s.clean,
341
+ has_commits: s.hasCommits,
342
+ staged: s.staged,
343
+ unstaged: s.unstaged,
344
+ untracked: s.untracked,
345
+ renamed: s.renamed,
346
+ deleted: s.deleted,
347
+ truncated: s.truncated
348
+ }
349
+ };
350
+ }
351
+ case "git_diff": {
352
+ if (repositoryTrust(repo) !== "trusted") {
353
+ return fail(id, name, "REPOSITORY_NOT_TRUSTED", `${repo.name} is not a trusted repository.`);
354
+ }
355
+ const scopeArg = str(args.scope);
356
+ const scope = scopeArg === "staged" || scopeArg === "both" ? scopeArg : "working_tree";
357
+ const d = gitDiff(root, scope);
358
+ return {
359
+ id,
360
+ name,
361
+ ok: true,
362
+ result: {
363
+ ...repositoryLabel(repo),
364
+ scope: d.scope,
365
+ files_changed: d.files_changed,
366
+ additions: d.additions,
367
+ deletions: d.deletions,
368
+ diff: d.diff,
369
+ truncated: d.truncated
370
+ }
371
+ };
372
+ }
373
+ }
374
+ }
375
+ catch (err) {
376
+ if (err instanceof LocalFileError) {
377
+ return fail(id, name, err.code, err.message);
378
+ }
379
+ if (err instanceof GitToolError) {
380
+ return fail(id, name, err.code, err.message);
381
+ }
382
+ return fail(id, name, "TOOL_FAILED", err.message ?? "Tool failed.");
383
+ }
384
+ return fail(id, name, "UNKNOWN_TOOL", `No local tool named "${name}".`);
385
+ }
386
+ /** What a result says about where it came from; omitted in single-repo mode. */
387
+ function repositoryLabel(handle) {
388
+ return inWorkspaceMode() ? { repository: handle.name } : {};
389
+ }
390
+ /**
391
+ * The repositories a wildcard read may touch: registered AND trusted.
392
+ *
393
+ * Registering a workspace says a repository exists. Trust says the user allowed
394
+ * Carrier OS to read it. A fan-out read must respect the second, or "*" would
395
+ * become a way to read a repository the user never opened.
396
+ */
397
+ function readableRepositories() {
398
+ const all = listRepositories().filter((r) => repositoryTrust(r) === "trusted");
399
+ return all.length ? all : [activeRepository()];
400
+ }
401
+ /** The tools that read or search file CONTENT, and so must respect trust. */
402
+ function isContentReadTool(name) {
403
+ return name === "read_file" || name === "list_files" || name === "search_files";
404
+ }
405
+ /**
406
+ * Whether a single, named-or-active repository may be read/searched — the same
407
+ * trust rule the wildcard fan-out applies (`readableRepositories`), so a named
408
+ * or active target can never reach a repository "*" would skip. Reused rather
409
+ * than re-deriving trust, and it inherits the single-repository fallback.
410
+ */
411
+ function isReadableRepository(handle) {
412
+ return readableRepositories().some((r) => r.id === handle.id);
413
+ }
414
+ /**
415
+ * A one-line, content-free record of a tool call.
416
+ *
417
+ * Deliberately not an audit system — that belongs with the phase that can
418
+ * change files. What it does establish now is the shape: a stable id, the tool,
419
+ * and enough of the arguments to be meaningful. File CONTENT never appears
420
+ * here, so turning this into a real audit trail later cannot accidentally start
421
+ * logging source code or secrets.
422
+ */
423
+ export function describeToolCall(req) {
424
+ const args = (req.arguments ?? {});
425
+ const detail = str(args.path) ?? str(args.query) ?? str(args.glob) ?? "";
426
+ const repo = str(args.repository);
427
+ return `${req.id} ${req.name}${repo ? ` [${repo}]` : ""}${detail ? ` ${detail}` : ""}`;
428
+ }
429
+ /** The root every tool resolves against — exported for display, not for callers. */
430
+ export function toolBoundary() {
431
+ return workspaceRoot();
432
+ }
@@ -1,15 +1,125 @@
1
- import { ApiClient } from "./api.js";
1
+ import chalk from "chalk";
2
+ import { ApiError } from "./api.js";
3
+ import { DEFAULT_API_URL } from "./config.js";
4
+ import { deviceLabel, localAuthorizeDefault, openBrowser, platformAuthBase, pollForToken, startDeviceAuthorization, withPlatformOrigin } from "./device-auth.js";
5
+ import { info, line } from "./output.js";
6
+ import { sleep, withSpinner } from "./spinner.js";
7
+ import { c } from "../ui/colors.js";
2
8
  /**
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.
9
+ * The single source of truth for browser-based login (OAuth 2.0 Device
10
+ * Authorization). This module owns only the *presentation* of the login — the
11
+ * flow, polling, token, and refresh logic are unchanged and live in
12
+ * device-auth.ts. Shared by the `login` command and the shell's first-run.
7
13
  *
8
- * Throws ApiError on failure (invalid key, unreachable endpoint, …).
14
+ * Terminal choreography (Claude-Code style, minimal + fixed, no scroll flood):
15
+ * Opening your browser…
16
+ * ✓ Browser opened <verification url> Code XXXX-XXXX
17
+ * ⠋ Waiting for approval… (in-place spinner)
18
+ * ✓ Device authorized / Workspace / Project / Session / Authentication successful
9
19
  */
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 });
20
+ export async function deviceLogin(ctx, apiUrl) {
21
+ const authBase = platformAuthBase(apiUrl);
22
+ // Branding + intro first (shown for both `cos` first-run and `cos login`).
23
+ line();
24
+ line(" " + c.brand("Welcome to Carrier OS"));
25
+ line(" " + c.dim("Sign in with your Carrier OS account."));
26
+ line();
27
+ info("Opening your browser…");
28
+ const start = await startDeviceAuthorization(authBase, deviceLabel());
29
+ // Where the browser goes to authorize this request.
30
+ //
31
+ // The API decides the PATH — /cli/authorize on the main Carrier OS site — and
32
+ // the overrides below only ever swap the origin, so a local override cannot
33
+ // send the browser to a page that does not exist. Precedence: explicit config
34
+ // `platformUrl` → env CARRIEROS_PLATFORM_URL → a localhost guess when the API
35
+ // is local but pointed at a production site → otherwise trust the API.
36
+ const apiUri = start.verification_uri_complete || start.verification_uri;
37
+ const override = ctx.config.get("platformUrl") ||
38
+ process.env.CARRIEROS_PLATFORM_URL ||
39
+ localAuthorizeDefault(apiUrl, apiUri);
40
+ const openUrl = withPlatformOrigin(apiUri, override);
41
+ const opened = openBrowser(openUrl);
42
+ line();
43
+ line(" " + (opened ? chalk.green("✓") + " Browser opened." : chalk.yellow("!") + " Couldn't open your browser."));
44
+ line();
45
+ // Persistent fallback (Claude-style): always offer the URL to sign in manually.
46
+ line(" " + c.dim("Browser didn't open? Use the URL below to sign in:"));
47
+ line(" " + c.brand(openUrl));
48
+ line();
49
+ // Waiting state — a single in-place spinner (never scrolls). Polling is
50
+ // unchanged; the spinner just animates until it resolves or throws.
51
+ const tokens = await withSpinner(chalk.dim("Waiting for approval…"), () => pollForToken(authBase, start));
52
+ return renderAuthorized(ctx, tokens);
53
+ }
54
+ /** The success sequence — a short animated checklist, then persist + verify,
55
+ * ending on "Logged in as <email>" (the shell then pauses + shows the welcome). */
56
+ async function renderAuthorized(ctx, tokens) {
57
+ const ok = (msg) => line(" " + chalk.green("✓") + " " + msg);
58
+ line();
59
+ ok("Device authorized");
60
+ await sleep(150);
61
+ const scope = await persistSession(ctx, tokens);
62
+ ok("Session synchronized");
63
+ await sleep(130);
64
+ const email = scope.user?.email ?? tokens.account?.email;
65
+ if (email) {
66
+ line();
67
+ line(" Logged in as " + c.value(email));
68
+ }
69
+ return scope;
70
+ }
71
+ /** Save the issued tokens + a cached scope; land in Carrier Chat by default.
72
+ * (Unchanged behaviour — persistence + a verify to confirm the token works.) */
73
+ async function persistSession(ctx, tokens) {
74
+ ctx.config.update({
75
+ auth: {
76
+ accessToken: tokens.access_token,
77
+ refreshToken: tokens.refresh_token,
78
+ // Which server issued this session. Only its refusal ends the session.
79
+ apiUrl: ctx.config.get("apiUrl") ?? DEFAULT_API_URL,
80
+ account: tokens.account,
81
+ workspace: tokens.workspace ?? null,
82
+ project: tokens.project ?? null
83
+ }
84
+ });
85
+ ctx.config.set("chatType", "carrier");
86
+ let scope;
87
+ try {
88
+ scope = await ctx.client().verify();
89
+ }
90
+ catch {
91
+ scope = scopeFromTokens(tokens);
92
+ }
93
+ ctx.config.set("scope", scope);
14
94
  return scope;
15
95
  }
96
+ function scopeFromTokens(tokens) {
97
+ return {
98
+ apiKey: null,
99
+ workspace: tokens.workspace ?? { id: "", name: "—", slug: "" },
100
+ project: tokens.project ?? { id: "", name: "—", projectId: "", environment: "" },
101
+ user: tokens.account ? { id: tokens.account.id, email: tokens.account.email } : null
102
+ };
103
+ }
104
+ /** Render a single, minimal ✗ line for a failed login. Returns the category. */
105
+ export function renderLoginFailure(err, apiUrl) {
106
+ const code = err instanceof ApiError ? err.code : "other";
107
+ const fail = (msg) => line(" " + chalk.red("✗") + " " + msg);
108
+ line();
109
+ if (code === "ACCESS_DENIED") {
110
+ fail("Authorization cancelled in the browser.");
111
+ return "denied";
112
+ }
113
+ if (code === "EXPIRED_TOKEN" || code === "TIMEOUT") {
114
+ fail("Login timed out — the code expired before it was approved.");
115
+ return "expired";
116
+ }
117
+ if (code === "NETWORK_ERROR" || code.startsWith("HTTP_")) {
118
+ fail("Couldn't reach the server.");
119
+ if (apiUrl)
120
+ line(" " + c.dim(apiUrl));
121
+ return "network";
122
+ }
123
+ fail(err instanceof ApiError ? `${err.message} (${err.code})` : String(err?.message ?? err));
124
+ return "other";
125
+ }
@@ -1,7 +1,9 @@
1
1
  import { readFileSync } from "node:fs";
2
2
  import { fileURLToPath } from "node:url";
3
- /** Read the CLI's own version from package.json (works in dev and after build). */
3
+ /** The CLI's own version — from the baked constant when packaged, else package.json. */
4
4
  export function cliVersion() {
5
+ if (typeof __CLI_VERSION__ === "string" && __CLI_VERSION__)
6
+ return __CLI_VERSION__;
5
7
  try {
6
8
  const pkgUrl = new URL("../../package.json", import.meta.url);
7
9
  const pkg = JSON.parse(readFileSync(fileURLToPath(pkgUrl), "utf8"));