@carrieros/cli-staging 0.0.0-stage → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -2
- package/dist/commands/attach.js +45 -0
- package/dist/commands/auth.js +60 -0
- package/dist/commands/btw.js +78 -0
- package/dist/commands/changes.js +167 -0
- package/dist/commands/chat.js +182 -0
- package/dist/commands/context.js +200 -0
- package/dist/commands/doctor.js +119 -0
- package/dist/commands/files.js +94 -0
- package/dist/commands/help.js +37 -0
- package/dist/commands/history.js +112 -0
- package/dist/commands/login.js +62 -0
- package/dist/commands/logout.js +25 -0
- package/dist/commands/memory.js +162 -0
- package/dist/commands/mode-model.js +64 -0
- package/dist/commands/models.js +28 -0
- package/dist/commands/modes.js +30 -0
- package/dist/commands/permissions.js +77 -0
- package/dist/commands/project.js +106 -0
- package/dist/commands/repo.js +146 -0
- package/dist/commands/repos.js +61 -0
- package/dist/commands/review.js +92 -0
- package/dist/commands/scope.js +155 -0
- package/dist/commands/search.js +92 -0
- package/dist/commands/sessions.js +282 -0
- package/dist/commands/settings.js +100 -0
- package/dist/commands/update.js +229 -0
- package/dist/commands/upload.js +223 -0
- package/dist/commands/usage.js +227 -0
- package/dist/commands/version.js +26 -0
- package/dist/commands/whoami.js +44 -0
- package/dist/ide/editor-context.js +275 -0
- package/dist/ide/ide-session.js +360 -0
- package/dist/ide/tool-host.js +109 -0
- package/dist/main.js +126 -0
- package/dist/services/api.js +439 -0
- package/dist/services/auth-origin.js +20 -0
- package/dist/services/chat-stream.js +168 -0
- package/dist/services/checkpoints.js +278 -0
- package/dist/services/client-tools.js +356 -0
- package/dist/services/code-intel.js +243 -0
- package/dist/services/code-symbols.js +94 -0
- package/dist/services/coding-workflow.js +554 -0
- package/dist/services/command-coordinator.js +273 -0
- package/dist/services/command-policy.js +434 -0
- package/dist/services/config.js +383 -0
- package/dist/services/container-runner.js +254 -0
- package/dist/services/container-supervisor.js +38 -0
- package/dist/services/context.js +371 -0
- package/dist/services/device-auth.js +286 -0
- package/dist/services/diff.js +196 -0
- package/dist/services/env-policy.js +108 -0
- package/dist/services/execution-platform.js +30 -0
- package/dist/services/file-detect.js +104 -0
- package/dist/services/file-resolver.js +199 -0
- package/dist/services/file-upload.js +126 -0
- package/dist/services/folder-key.js +22 -0
- package/dist/services/git-tools.js +429 -0
- package/dist/services/glob-match.js +164 -0
- package/dist/services/helper-bin.js +85 -0
- package/dist/services/ignore-rules.js +189 -0
- package/dist/services/instruction-resolver.js +54 -0
- package/dist/services/job-helper.js +328 -0
- package/dist/services/local-files.js +639 -0
- package/dist/services/local-tools.js +937 -0
- package/dist/services/login-flow.js +156 -0
- package/dist/services/meta.js +15 -0
- package/dist/services/mutation-coordinator.js +327 -0
- package/dist/services/mutation-groups.js +309 -0
- package/dist/services/mutation-recovery.js +159 -0
- package/dist/services/mutations.js +679 -0
- package/dist/services/open-url.js +68 -0
- package/dist/services/output.js +62 -0
- package/dist/services/packaged-update.js +403 -0
- package/dist/services/packaged.js +39 -0
- package/dist/services/permission-mode.js +78 -0
- package/dist/services/process-runner.js +412 -0
- package/dist/services/project-context.js +298 -0
- package/dist/services/redaction.js +201 -0
- package/dist/services/result-reconciliation.js +49 -0
- package/dist/services/secure-store.js +217 -0
- package/dist/services/session-resolver.js +113 -0
- package/dist/services/sia.js +51 -0
- package/dist/services/spinner.js +40 -0
- package/dist/services/supported-runtime.js +59 -0
- package/dist/services/task-context.js +212 -0
- package/dist/services/task-snapshot.js +38 -0
- package/dist/services/tool-result-outbox.js +195 -0
- package/dist/services/update.js +311 -0
- package/dist/services/workspace-registry.js +310 -0
- package/dist/services/workspace.js +580 -0
- package/dist/shell/shell-chat.js +1619 -0
- package/dist/shell/shell-commands.js +411 -0
- package/dist/shell/shell-prompt.js +110 -0
- package/dist/shell/shell-renderer.js +51 -0
- package/dist/shell/shell-router.js +37 -0
- package/dist/shell/shell.js +389 -0
- package/dist/shell/task-context-view.js +40 -0
- package/dist/staging.js +5 -0
- package/dist/types/index.js +6 -0
- package/dist/ui/agent-cards.js +111 -0
- package/dist/ui/agent-presentation.js +131 -0
- package/dist/ui/approval.js +111 -0
- package/dist/ui/banner.js +56 -0
- package/dist/ui/btw-overlay.js +230 -0
- package/dist/ui/change-review.js +334 -0
- package/dist/ui/chat-renderer.js +463 -0
- package/dist/ui/code-block.js +52 -0
- package/dist/ui/color-picker.js +100 -0
- package/dist/ui/colors.js +55 -0
- package/dist/ui/command-details.js +11 -0
- package/dist/ui/command-filter.js +92 -0
- package/dist/ui/command-item.js +6 -0
- package/dist/ui/command-palette.js +383 -0
- package/dist/ui/command-registry.js +128 -0
- package/dist/ui/command-renderer.js +55 -0
- package/dist/ui/command-review.js +187 -0
- package/dist/ui/composer-layout.js +74 -0
- package/dist/ui/conversation.js +450 -0
- package/dist/ui/interrupt.js +35 -0
- package/dist/ui/live.js +141 -0
- package/dist/ui/logo.js +58 -0
- package/dist/ui/markdown.js +205 -0
- package/dist/ui/message.js +21 -0
- package/dist/ui/screen-prompt.js +181 -0
- package/dist/ui/screen.js +297 -0
- package/dist/ui/select.js +284 -0
- package/dist/ui/sia-qa.js +213 -0
- package/dist/ui/spinner.js +23 -0
- package/dist/ui/sticky-stream.js +64 -0
- package/dist/ui/task-context-card.js +99 -0
- package/dist/ui/text-prompt.js +74 -0
- package/dist/ui/theme.js +80 -0
- package/dist/ui/trust.js +88 -0
- package/dist/ui/ui.js +101 -0
- package/package.json +33 -4
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
import { ApiClient, ApiError } from "./api.js";
|
|
2
|
+
import { DEFAULT_API_URL, sameApiOrigin } from "./config.js";
|
|
3
|
+
import { refreshCliSession } from "./device-auth.js";
|
|
4
|
+
import { assertCredentialOrigin } from "./auth-origin.js";
|
|
5
|
+
/**
|
|
6
|
+
* Thrown by requireAuth when no key is configured. Unlike a process.exit, this
|
|
7
|
+
* can be caught — so the interactive shell can keep running after a failed
|
|
8
|
+
* command, while standalone commands still turn it into a clean exit(1).
|
|
9
|
+
*/
|
|
10
|
+
export class AuthRequiredError extends Error {
|
|
11
|
+
constructor(message = "You are not logged in. Run `cos login` first.") {
|
|
12
|
+
super(message);
|
|
13
|
+
this.name = "AuthRequiredError";
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* CommandContext is the single dependency every command receives. Commands
|
|
18
|
+
* depend on this abstraction (not on axios/fs directly), which keeps them thin
|
|
19
|
+
* and testable and satisfies the dependency-inversion principle.
|
|
20
|
+
*/
|
|
21
|
+
export class CommandContext {
|
|
22
|
+
config;
|
|
23
|
+
constructor(config) {
|
|
24
|
+
this.config = config;
|
|
25
|
+
}
|
|
26
|
+
/** In-process mode override. The interactive shell always OPENS in the Carrier
|
|
27
|
+
* OS mode (the core persona) regardless of the persisted default; setting the
|
|
28
|
+
* mode mid-session updates this. It is never written to disk, so standalone
|
|
29
|
+
* commands keep using the persisted `mode`. */
|
|
30
|
+
overrideMode;
|
|
31
|
+
/** True while running inside the interactive `cos` shell (vs a one-shot
|
|
32
|
+
* standalone command). Commands use this to decide between interactive
|
|
33
|
+
* prompts (shell) and finish-and-return "next steps" output (standalone). */
|
|
34
|
+
_inShell = false;
|
|
35
|
+
get inShell() {
|
|
36
|
+
return this._inShell;
|
|
37
|
+
}
|
|
38
|
+
setInShell(v) {
|
|
39
|
+
this._inShell = v;
|
|
40
|
+
}
|
|
41
|
+
/** File ids attached to chat messages, sent as `file_ids` on /v1/chat so the
|
|
42
|
+
* model can read the file. PERSISTED in config (not just in-process) so a file
|
|
43
|
+
* uploaded via a standalone `cos upload` is still attached when the shell opens
|
|
44
|
+
* in a separate process. Populated by upload (auto-attach) and `/attach`,
|
|
45
|
+
* cleared by `/detach` or logout. */
|
|
46
|
+
get attachedFileIds() {
|
|
47
|
+
return this.config.get("attachedFileIds") ?? [];
|
|
48
|
+
}
|
|
49
|
+
/** Attach a file id (deduped) so it rides along on subsequent messages. */
|
|
50
|
+
attachFile(fileId) {
|
|
51
|
+
if (!fileId)
|
|
52
|
+
return;
|
|
53
|
+
const list = this.attachedFileIds;
|
|
54
|
+
if (!list.includes(fileId))
|
|
55
|
+
this.config.set("attachedFileIds", [...list, fileId]);
|
|
56
|
+
}
|
|
57
|
+
/** Drop all attachments (an explicit /detach or logout). */
|
|
58
|
+
clearAttachments() {
|
|
59
|
+
this.config.set("attachedFileIds", []);
|
|
60
|
+
}
|
|
61
|
+
/** A client built from current config (anonymous if not logged in). */
|
|
62
|
+
client() {
|
|
63
|
+
const apiUrl = this.config.get("apiUrl") ?? DEFAULT_API_URL;
|
|
64
|
+
return new ApiClient(apiUrl, this.authProvider(apiUrl));
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* The one refresh currently on the wire, shared by every request that needs it.
|
|
68
|
+
*
|
|
69
|
+
* Refresh tokens are single-use. The shell opens by loading models and modes
|
|
70
|
+
* in parallel, so when the stored access token has expired both requests get
|
|
71
|
+
* a 401 in the same instant — and each used to run its own refresh with the
|
|
72
|
+
* same token. The server let exactly one rotate and answered the other 409;
|
|
73
|
+
* the CLI read that 409 as a dead session and deleted the credentials the
|
|
74
|
+
* winner had just saved. The first message still went through on the fresh
|
|
75
|
+
* token held in memory, and the second found nothing on disk: "You're not
|
|
76
|
+
* signed in".
|
|
77
|
+
*
|
|
78
|
+
* Lives on the context rather than the provider because `client()` builds a
|
|
79
|
+
* new provider for every client, and the coordination has to span all of them.
|
|
80
|
+
*/
|
|
81
|
+
refreshing = null;
|
|
82
|
+
/** Check configured and actual destinations before exposing saved credentials. */
|
|
83
|
+
validateCredentialOrigin(destination = this.config.get("apiUrl") ?? DEFAULT_API_URL) {
|
|
84
|
+
const auth = this.config.get("auth");
|
|
85
|
+
if (!auth?.accessToken && !auth?.refreshToken && !this.config.get("secretKey"))
|
|
86
|
+
return;
|
|
87
|
+
const issuer = auth?.accessToken || auth?.refreshToken ? auth.apiUrl : this.config.get("secretKeyApiUrl");
|
|
88
|
+
assertCredentialOrigin(issuer, this.config.get("apiUrl") ?? DEFAULT_API_URL);
|
|
89
|
+
assertCredentialOrigin(issuer, destination);
|
|
90
|
+
}
|
|
91
|
+
/** Credential + silent-refresh strategy, bound to the client's API base. */
|
|
92
|
+
authProvider(apiUrl = this.config.get("apiUrl") ?? DEFAULT_API_URL) {
|
|
93
|
+
return {
|
|
94
|
+
token: (destination = apiUrl) => {
|
|
95
|
+
this.validateCredentialOrigin(destination);
|
|
96
|
+
const auth = this.config.get("auth");
|
|
97
|
+
if (auth?.accessToken)
|
|
98
|
+
return auth.accessToken;
|
|
99
|
+
const key = this.config.get("secretKey");
|
|
100
|
+
if (key)
|
|
101
|
+
assertCredentialOrigin(this.config.get("secretKeyApiUrl"), destination);
|
|
102
|
+
return key;
|
|
103
|
+
},
|
|
104
|
+
refresh: async (failedToken) => {
|
|
105
|
+
this.validateCredentialOrigin(apiUrl);
|
|
106
|
+
this.refreshing ??= this.renewSession(apiUrl, failedToken).finally(() => {
|
|
107
|
+
this.refreshing = null;
|
|
108
|
+
});
|
|
109
|
+
return this.refreshing;
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Renew the session, and clear local credentials ONLY when the server says it
|
|
115
|
+
* is finished.
|
|
116
|
+
*
|
|
117
|
+
* Before spending the refresh token this re-reads config from disk: another
|
|
118
|
+
* `cos` process (a second terminal, a standalone command alongside the shell)
|
|
119
|
+
* may already have rotated it, in which case the token held in memory is spent
|
|
120
|
+
* and presenting it trips the server's reuse detection — which revokes every
|
|
121
|
+
* device on the account. Adopting the rotated pair avoids asking at all.
|
|
122
|
+
*/
|
|
123
|
+
async renewSession(apiUrl, failedToken) {
|
|
124
|
+
this.config.reload();
|
|
125
|
+
const auth = this.config.get("auth");
|
|
126
|
+
if (!auth?.refreshToken)
|
|
127
|
+
return undefined;
|
|
128
|
+
this.validateCredentialOrigin(apiUrl);
|
|
129
|
+
// Someone already renewed since this request went out — just retry with it.
|
|
130
|
+
if (failedToken && auth.accessToken && auth.accessToken !== failedToken) {
|
|
131
|
+
return auth.accessToken;
|
|
132
|
+
}
|
|
133
|
+
const outcome = await refreshCliSession(apiUrl, auth.refreshToken);
|
|
134
|
+
switch (outcome.kind) {
|
|
135
|
+
case "ok": {
|
|
136
|
+
const renewed = outcome.data;
|
|
137
|
+
this.config.update({
|
|
138
|
+
auth: {
|
|
139
|
+
...auth,
|
|
140
|
+
accessToken: renewed.access_token,
|
|
141
|
+
refreshToken: renewed.refresh_token,
|
|
142
|
+
// Preserve the issuer that was validated before the exchange.
|
|
143
|
+
apiUrl: auth.apiUrl,
|
|
144
|
+
workspace: renewed.workspace ?? auth.workspace,
|
|
145
|
+
project: renewed.project ?? auth.project
|
|
146
|
+
}
|
|
147
|
+
});
|
|
148
|
+
return renewed.access_token;
|
|
149
|
+
}
|
|
150
|
+
case "dead":
|
|
151
|
+
// "This session is finished" is only true when it comes from the server
|
|
152
|
+
// that ISSUED the session. Pointing the CLI at a different API (a local
|
|
153
|
+
// dev server, a mistyped --url) gets the very same 401 from a server
|
|
154
|
+
// that has simply never heard of it — and acting on that is
|
|
155
|
+
// unrecoverable, because the refresh token exists nowhere else.
|
|
156
|
+
//
|
|
157
|
+
// Signing out is therefore something the CLI does only when it is sure,
|
|
158
|
+
// or something the user does explicitly with `cos logout`. A refresh
|
|
159
|
+
// token the server has already revoked grants nothing, so leaving one on
|
|
160
|
+
// disk costs nothing either.
|
|
161
|
+
if (sameApiOrigin(auth.apiUrl, apiUrl)) {
|
|
162
|
+
this.config.clearAuth();
|
|
163
|
+
return undefined;
|
|
164
|
+
}
|
|
165
|
+
throw new ApiError("SESSION_NOT_RENEWABLE", auth.apiUrl
|
|
166
|
+
? `This session was issued by ${auth.apiUrl}, but the CLI is pointed at ${apiUrl}. ` +
|
|
167
|
+
`Point it back with \`cos login --url ${auth.apiUrl}\`, or run \`cos logout\` to sign in here.`
|
|
168
|
+
: `${apiUrl} would not renew this session. If you signed out elsewhere or changed API URL, ` +
|
|
169
|
+
"run `cos logout` and sign in again.", 401);
|
|
170
|
+
case "busy": {
|
|
171
|
+
// A different process won the rotation; its tokens are about to land in
|
|
172
|
+
// the shared config. Give it a moment to write them rather than guessing.
|
|
173
|
+
const adopted = await this.awaitRotatedElsewhere(auth.refreshToken, apiUrl);
|
|
174
|
+
if (adopted)
|
|
175
|
+
return adopted;
|
|
176
|
+
throw new ApiError("SESSION_BUSY", "Your session is being renewed by another Carrier OS window. Try again in a moment.", 409);
|
|
177
|
+
}
|
|
178
|
+
case "unsupported":
|
|
179
|
+
// Retrying cannot help: this API build has no route for the session.
|
|
180
|
+
throw new ApiError("SESSION_ENDPOINT_MISSING", `${apiUrl} can't renew Carrier OS sign-in sessions — it may be running an older API version. ` +
|
|
181
|
+
"Point Carrier OS at the API that signed you in, or run `cos logout` and sign in again.", 404);
|
|
182
|
+
case "transient":
|
|
183
|
+
// The session may be perfectly healthy — never sign someone out because
|
|
184
|
+
// the API had a bad second.
|
|
185
|
+
throw new ApiError("REFRESH_UNAVAILABLE", "Couldn't renew your session right now. Try again in a moment.", outcome.status || 503);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
/** Poll the shared config briefly for a refresh token rotated by another process. */
|
|
189
|
+
async awaitRotatedElsewhere(spentRefreshToken, apiUrl) {
|
|
190
|
+
for (let attempt = 0; attempt < 10; attempt += 1) {
|
|
191
|
+
await new Promise((r) => setTimeout(r, 100));
|
|
192
|
+
this.config.reload();
|
|
193
|
+
const auth = this.config.get("auth");
|
|
194
|
+
this.validateCredentialOrigin(apiUrl);
|
|
195
|
+
if (auth?.refreshToken && auth.refreshToken !== spentRefreshToken && auth.accessToken) {
|
|
196
|
+
return auth.accessToken;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
return undefined;
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* A client guaranteed to carry a key, or a clean exit with guidance. Use this
|
|
203
|
+
* in every command that hits an authenticated endpoint.
|
|
204
|
+
*/
|
|
205
|
+
requireAuth() {
|
|
206
|
+
if (!this.config.isAuthenticated) {
|
|
207
|
+
// Say WHY when we know: credentials that exist but cannot be opened by
|
|
208
|
+
// this Windows account (copied from another machine or user, or damaged)
|
|
209
|
+
// are a different situation from never having signed in.
|
|
210
|
+
throw new AuthRequiredError(this.config.credentialError
|
|
211
|
+
? `${this.config.credentialError} Run \`cos login\` to sign in again.`
|
|
212
|
+
: undefined);
|
|
213
|
+
}
|
|
214
|
+
return this.client();
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* Active Carrier mode. Mode belongs to the CHAT TYPE, not the session:
|
|
218
|
+
*
|
|
219
|
+
* carrier → always "general". Carrier Chat runs one mode, so this is
|
|
220
|
+
* derived rather than stored — nothing chosen in Standard can
|
|
221
|
+
* leak in, and nothing chosen here can leak back out.
|
|
222
|
+
* standard → the session override, else the persisted default, else "auto"
|
|
223
|
+
* (Standard is the only place Auto routing applies).
|
|
224
|
+
*
|
|
225
|
+
* Deriving it is what keeps a Carrier→Standard switch from stranding you in
|
|
226
|
+
* General: there is no carrier mode to carry over in the first place.
|
|
227
|
+
*/
|
|
228
|
+
get mode() {
|
|
229
|
+
if (this.chatType === "carrier")
|
|
230
|
+
return "general";
|
|
231
|
+
return this.overrideMode ?? this.config.get("mode") ?? "auto";
|
|
232
|
+
}
|
|
233
|
+
/** True when the active chat type lets the user choose a mode at all. */
|
|
234
|
+
get modeIsSelectable() {
|
|
235
|
+
return this.chatType !== "carrier";
|
|
236
|
+
}
|
|
237
|
+
/** Set the mode for this process only (interactive shell), without persisting. */
|
|
238
|
+
setSessionMode(id) {
|
|
239
|
+
this.overrideMode = id;
|
|
240
|
+
}
|
|
241
|
+
/** Active chat experience: "carrier" (flagship Carrier Chat) by default — you
|
|
242
|
+
* always land in Carrier Chat, matching the web app. Persisted so a chosen
|
|
243
|
+
* type survives across invocations; reset to carrier on login. */
|
|
244
|
+
get chatType() {
|
|
245
|
+
return this.config.get("chatType") ?? "carrier";
|
|
246
|
+
}
|
|
247
|
+
/** Switch chat type. Because a conversation's type is fixed at creation, this
|
|
248
|
+
* clears the active session so the NEXT message starts a fresh conversation of
|
|
249
|
+
* the new type. */
|
|
250
|
+
setChatType(type) {
|
|
251
|
+
this.config.set("chatType", type);
|
|
252
|
+
this.config.set("sessionId", undefined);
|
|
253
|
+
// Drop the session's mode override so the new chat type lands on its own
|
|
254
|
+
// default (carrier → General, standard → the saved mode or Auto) instead of
|
|
255
|
+
// inheriting a mode the user picked for the type they just left.
|
|
256
|
+
this.overrideMode = undefined;
|
|
257
|
+
}
|
|
258
|
+
/** Persisted web-search preference. `undefined` means "not chosen here" — the
|
|
259
|
+
* API then falls back to the workspace's admin toggle, which is what the web
|
|
260
|
+
* app does. `/websearch on|off` persists a choice that wins over that. */
|
|
261
|
+
get webSearch() {
|
|
262
|
+
return this.config.get("webSearch");
|
|
263
|
+
}
|
|
264
|
+
setWebSearch(on) {
|
|
265
|
+
this.config.set("webSearch", on);
|
|
266
|
+
}
|
|
267
|
+
/** One-shot arm from a bare `/websearch`: search the NEXT message, then go
|
|
268
|
+
* back to whatever the persisted preference was. Deliberately in-process —
|
|
269
|
+
* an armed turn that never got sent shouldn't survive into a new session. */
|
|
270
|
+
armed = false;
|
|
271
|
+
get webSearchArmed() {
|
|
272
|
+
return this.armed;
|
|
273
|
+
}
|
|
274
|
+
armWebSearch() {
|
|
275
|
+
this.armed = true;
|
|
276
|
+
}
|
|
277
|
+
disarmWebSearch() {
|
|
278
|
+
this.armed = false;
|
|
279
|
+
}
|
|
280
|
+
/** What to send as `web_search` on the next turn: forced on while armed,
|
|
281
|
+
* otherwise the persisted preference (undefined = follow the workspace). */
|
|
282
|
+
get effectiveWebSearch() {
|
|
283
|
+
return this.armed ? true : this.webSearch;
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* Fast mode — Llama via Groq instead of the selected model.
|
|
287
|
+
*
|
|
288
|
+
* STANDARD CHAT ONLY, mirroring the web's `isRestrictedType`: it forces
|
|
289
|
+
* fastMode off for `carrier`/`temp` conversations even when one has the flag
|
|
290
|
+
* stored. Deriving it here rather than clearing the setting means switching
|
|
291
|
+
* Carrier → Standard restores whatever the user last chose, instead of
|
|
292
|
+
* silently losing it on every round trip.
|
|
293
|
+
*/
|
|
294
|
+
get fast() {
|
|
295
|
+
if (this.chatType !== "standard")
|
|
296
|
+
return false;
|
|
297
|
+
return this.config.get("fast") === true;
|
|
298
|
+
}
|
|
299
|
+
setFast(on) {
|
|
300
|
+
this.config.set("fast", on);
|
|
301
|
+
}
|
|
302
|
+
/** High Power (HIPWR) — the 4-pass refinement pipeline. Persisted, but the
|
|
303
|
+
* server still treats it as opt-in per request and admin-gated. */
|
|
304
|
+
get highPower() {
|
|
305
|
+
return this.config.get("highPower") === true;
|
|
306
|
+
}
|
|
307
|
+
setHighPower(on) {
|
|
308
|
+
this.config.set("highPower", on);
|
|
309
|
+
}
|
|
310
|
+
/** SIA clarification — ask before sending, rather than guessing at an
|
|
311
|
+
* ambiguous prompt. Off by default, like the web composer's toggle. */
|
|
312
|
+
get siaMode() {
|
|
313
|
+
// STANDARD CHAT ONLY, derived the same way `fast` is: Carrier Chat runs its
|
|
314
|
+
// own behaviour layer and the web shows no SIA control there. Deriving
|
|
315
|
+
// rather than clearing means a Carrier -> Standard switch restores whatever
|
|
316
|
+
// the user last chose instead of silently losing it.
|
|
317
|
+
if (this.chatType !== "standard")
|
|
318
|
+
return "off";
|
|
319
|
+
const stored = this.config.get("sia");
|
|
320
|
+
// Legacy booleans from before the mode existed: true meant "consult the
|
|
321
|
+
// backend", which is exactly what auto does now.
|
|
322
|
+
if (stored === true)
|
|
323
|
+
return "auto";
|
|
324
|
+
if (stored === false)
|
|
325
|
+
return "off";
|
|
326
|
+
// Unset is OFF, as the web composer's toggle is. Defaulting to auto put
|
|
327
|
+
// clarifying questions in front of every coding task ("should the subtotal
|
|
328
|
+
// include discounts?") before the agent had even read the repository.
|
|
329
|
+
return stored === "auto" ? "auto" : "off";
|
|
330
|
+
}
|
|
331
|
+
/** True when a turn should ask the backend whether clarification is needed. */
|
|
332
|
+
get sia() {
|
|
333
|
+
return this.siaMode === "auto";
|
|
334
|
+
}
|
|
335
|
+
setSiaMode(mode) {
|
|
336
|
+
this.config.set("sia", mode);
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* True while a main chat turn is rendering in the background.
|
|
340
|
+
*
|
|
341
|
+
* Runtime-only (never persisted): the shell sets it when it detaches a turn
|
|
342
|
+
* so commands that share the terminal — `/btw` — can tell who owns the
|
|
343
|
+
* transient region.
|
|
344
|
+
*/
|
|
345
|
+
mainTurnRunning = false;
|
|
346
|
+
/** Read-only Admin Panel Carrier Chat switch, refreshed by the shell. Null
|
|
347
|
+
* means it could not yet be verified; the send gate checks again. */
|
|
348
|
+
carrierMaintenance = null;
|
|
349
|
+
/**
|
|
350
|
+
* Credits this shell session's turns were actually debited, summed from the
|
|
351
|
+
* server's per-turn `credits_spent`. Runtime-only: "this session" means this
|
|
352
|
+
* process. Background context maintenance is billed separately on the server
|
|
353
|
+
* and is not a turn, so it is not in here — `/usage` reports it.
|
|
354
|
+
*/
|
|
355
|
+
sessionCreditsSpent = 0;
|
|
356
|
+
/** Whether any turn this session reported its spend (older APIs do not). */
|
|
357
|
+
sessionSpendKnown = false;
|
|
358
|
+
/** Citations from the most recent turn that returned any, so /sources and
|
|
359
|
+
* /open can act on them after the answer has scrolled away. */
|
|
360
|
+
lastSearch = null;
|
|
361
|
+
recordSearch(sources) {
|
|
362
|
+
if (sources.length > 0)
|
|
363
|
+
this.lastSearch = { sources, at: Date.now() };
|
|
364
|
+
}
|
|
365
|
+
get lastSources() {
|
|
366
|
+
return this.lastSearch?.sources ?? [];
|
|
367
|
+
}
|
|
368
|
+
get lastSearchAt() {
|
|
369
|
+
return this.lastSearch?.at ?? null;
|
|
370
|
+
}
|
|
371
|
+
}
|
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
import os from "node:os";
|
|
2
|
+
import axios, { isAxiosError } from "axios";
|
|
3
|
+
import { ApiError } from "./api.js";
|
|
4
|
+
import { cliVersion } from "./meta.js";
|
|
5
|
+
import { openUrl } from "./open-url.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
|
+
/** Dedicated user-owned CLI auth endpoints; existing sessions retain their issuer. */
|
|
24
|
+
export function userCliAuthBase(apiUrl) {
|
|
25
|
+
return platformAuthBase(apiUrl).replace(/\/platform\/auth$/, "/cli/auth");
|
|
26
|
+
}
|
|
27
|
+
/** Unverified claims select an endpoint only; the server authenticates the token.
|
|
28
|
+
* Both choices stay on the configured, origin-validated API. */
|
|
29
|
+
export function cliSessionAuthBase(apiUrl, token) {
|
|
30
|
+
try {
|
|
31
|
+
const claims = JSON.parse(Buffer.from((token ?? "").split(".")[1], "base64url").toString("utf8"));
|
|
32
|
+
if (claims.realm === "carrier-cli")
|
|
33
|
+
return userCliAuthBase(apiUrl);
|
|
34
|
+
}
|
|
35
|
+
catch { /* legacy and opaque credentials retain their original endpoint */ }
|
|
36
|
+
return platformAuthBase(apiUrl);
|
|
37
|
+
}
|
|
38
|
+
/** Is this URL pointing at the machine we are running on? */
|
|
39
|
+
function isLoopback(url) {
|
|
40
|
+
try {
|
|
41
|
+
const host = new URL(url).hostname;
|
|
42
|
+
return host === "localhost" || host === "127.0.0.1" || host === "::1";
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Local authorization-site default (dev convenience).
|
|
50
|
+
*
|
|
51
|
+
* The browser step happens on the MAIN Carrier OS site now, so against a local
|
|
52
|
+
* API this opens the local main site (:3000) rather than the production URL the
|
|
53
|
+
* API returns when CLI_AUTHORIZE_URL / FRONTEND_URL aren't set.
|
|
54
|
+
*
|
|
55
|
+
* It deliberately stands down when the API already returned a loopback URL: an
|
|
56
|
+
* API that IS configured knows where its authorization page lives — possibly on
|
|
57
|
+
* a different port than this guess — and overriding it would send the browser
|
|
58
|
+
* somewhere with no such page. The guess only covers a local API that handed
|
|
59
|
+
* back a production URL.
|
|
60
|
+
*
|
|
61
|
+
* Override with CARRIEROS_PLATFORM_URL or `--platform`.
|
|
62
|
+
*/
|
|
63
|
+
export function localAuthorizeDefault(apiUrl, verificationUri) {
|
|
64
|
+
if (verificationUri && isLoopback(verificationUri))
|
|
65
|
+
return undefined;
|
|
66
|
+
return isLoopback(apiUrl) ? "http://localhost:3000" : undefined;
|
|
67
|
+
}
|
|
68
|
+
/** Swap the origin (scheme + host) of a URL, preserving its path + query. Lets
|
|
69
|
+
* the CLI point the browser at a local platform during development without the
|
|
70
|
+
* API's PLATFORM_FRONTEND_URL being set. Returns the input unchanged on error
|
|
71
|
+
* or when no override is given. */
|
|
72
|
+
export function withPlatformOrigin(url, override) {
|
|
73
|
+
if (!override)
|
|
74
|
+
return url;
|
|
75
|
+
try {
|
|
76
|
+
const u = new URL(url);
|
|
77
|
+
const o = new URL(override);
|
|
78
|
+
u.protocol = o.protocol;
|
|
79
|
+
u.host = o.host;
|
|
80
|
+
return u.toString();
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
return url;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
/** A friendly device label so the developer can recognise this machine in the
|
|
87
|
+
* Devices list (e.g. "cos on DESKTOP-ABC (win32)"). */
|
|
88
|
+
export function deviceLabel() {
|
|
89
|
+
const host = os.hostname?.() || "unknown-host";
|
|
90
|
+
return `cos on ${host} (${process.platform})`;
|
|
91
|
+
}
|
|
92
|
+
const osName = () => {
|
|
93
|
+
switch (process.platform) {
|
|
94
|
+
case "win32":
|
|
95
|
+
return "Windows";
|
|
96
|
+
case "darwin":
|
|
97
|
+
return "macOS";
|
|
98
|
+
case "linux":
|
|
99
|
+
return "Linux";
|
|
100
|
+
default:
|
|
101
|
+
return process.platform;
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
/** Best-effort terminal/host identification for the approval page. */
|
|
105
|
+
const clientName = () => {
|
|
106
|
+
if (process.env.TERM_PROGRAM === "vscode")
|
|
107
|
+
return "VS Code Terminal";
|
|
108
|
+
if (process.env.WT_SESSION)
|
|
109
|
+
return "Windows Terminal";
|
|
110
|
+
if (process.env.TERM_PROGRAM === "Apple_Terminal")
|
|
111
|
+
return "Apple Terminal";
|
|
112
|
+
if (process.env.TERM_PROGRAM)
|
|
113
|
+
return `${process.env.TERM_PROGRAM} Terminal`;
|
|
114
|
+
return "Terminal";
|
|
115
|
+
};
|
|
116
|
+
/** The User-Agent the CLI presents so the browser approval page can show a
|
|
117
|
+
* human "OS · client" instead of a raw HTTP library string. Parsed on the
|
|
118
|
+
* platform by the same `CarrierOS-CLI/<v> (<os>; <client>)` shape. */
|
|
119
|
+
export function cliUserAgent() {
|
|
120
|
+
return `CarrierOS-CLI/${cliVersion()} (${osName()}; ${clientName()})`;
|
|
121
|
+
}
|
|
122
|
+
/** Open a URL in the user's default browser, cross-platform, with no extra deps.
|
|
123
|
+
* Best-effort: if it fails the caller still shows the URL to open manually.
|
|
124
|
+
*
|
|
125
|
+
* Goes through the same checked, shell-free opener as every other link: the
|
|
126
|
+
* URL comes from the server, and a `cmd /c start` here would let a `&` in it
|
|
127
|
+
* run a second command. */
|
|
128
|
+
export function openBrowser(url) {
|
|
129
|
+
try {
|
|
130
|
+
openUrl(url);
|
|
131
|
+
return true;
|
|
132
|
+
}
|
|
133
|
+
catch {
|
|
134
|
+
return false;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
/** A bare axios call to the platform-auth base that returns the parsed envelope
|
|
138
|
+
* WITHOUT throwing on 4xx — so the poll loop can read RFC 8628 error codes. */
|
|
139
|
+
async function envelopePost(url, body, headers) {
|
|
140
|
+
try {
|
|
141
|
+
const res = await axios.post(url, body, {
|
|
142
|
+
headers: {
|
|
143
|
+
"Content-Type": "application/json",
|
|
144
|
+
"User-Agent": cliUserAgent(),
|
|
145
|
+
...(headers ?? {})
|
|
146
|
+
},
|
|
147
|
+
timeout: 30_000,
|
|
148
|
+
maxRedirects: 0,
|
|
149
|
+
validateStatus: () => true
|
|
150
|
+
});
|
|
151
|
+
return { status: res.status, body: res.data };
|
|
152
|
+
}
|
|
153
|
+
catch (err) {
|
|
154
|
+
if (isAxiosError(err) && ["ECONNREFUSED", "ENOTFOUND", "ETIMEDOUT", "ECONNABORTED"].includes(err.code ?? "")) {
|
|
155
|
+
throw new ApiError("NETWORK_ERROR", `Could not reach the API at ${url}.`, 0);
|
|
156
|
+
}
|
|
157
|
+
throw new ApiError("REQUEST_FAILED", err instanceof Error ? err.message : String(err));
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
/** Step 1 — ask the server to start a device authorization. */
|
|
161
|
+
export async function startDeviceAuthorization(authBase, label) {
|
|
162
|
+
const { body } = await envelopePost(`${authBase}/device/code`, { label });
|
|
163
|
+
if (body?.success && body.data)
|
|
164
|
+
return body.data;
|
|
165
|
+
throw new ApiError(body?.error?.code ?? "DEVICE_START_FAILED", body?.error?.message ?? "Could not start login.");
|
|
166
|
+
}
|
|
167
|
+
/** Step 2 — one poll of the token endpoint. */
|
|
168
|
+
async function pollOnce(authBase, deviceCode) {
|
|
169
|
+
const { body } = await envelopePost(`${authBase}/device/token`, {
|
|
170
|
+
device_code: deviceCode
|
|
171
|
+
});
|
|
172
|
+
if (body?.success && body.data)
|
|
173
|
+
return { kind: "approved", data: body.data };
|
|
174
|
+
switch (body?.error?.code) {
|
|
175
|
+
case "AUTHORIZATION_PENDING":
|
|
176
|
+
return { kind: "pending" };
|
|
177
|
+
case "SLOW_DOWN":
|
|
178
|
+
return { kind: "slow_down" };
|
|
179
|
+
case "ACCESS_DENIED":
|
|
180
|
+
return { kind: "denied" };
|
|
181
|
+
case "EXPIRED_TOKEN":
|
|
182
|
+
return { kind: "expired" };
|
|
183
|
+
default:
|
|
184
|
+
return { kind: "error", message: body?.error?.message ?? "Authorization failed." };
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
/** Step 2 (loop) — poll until approved, denied, expired, or timed out. Calls
|
|
188
|
+
* `onTick` between polls so the caller can animate a spinner. */
|
|
189
|
+
export async function pollForToken(authBase, start, onTick,
|
|
190
|
+
/** Stops polling: an approval that arrives after it is never used. */
|
|
191
|
+
signal) {
|
|
192
|
+
let intervalMs = Math.max(1, start.interval || 5) * 1000;
|
|
193
|
+
const deadline = Date.now() + Math.max(1, start.expires_in || 600) * 1000;
|
|
194
|
+
while (Date.now() < deadline) {
|
|
195
|
+
onTick?.();
|
|
196
|
+
await sleep(intervalMs);
|
|
197
|
+
if (signal?.aborted)
|
|
198
|
+
throw new ApiError("SIGN_IN_CANCELLED", "Sign-in cancelled.");
|
|
199
|
+
const outcome = await pollOnce(authBase, start.device_code);
|
|
200
|
+
if (signal?.aborted)
|
|
201
|
+
throw new ApiError("SIGN_IN_CANCELLED", "Sign-in cancelled.");
|
|
202
|
+
switch (outcome.kind) {
|
|
203
|
+
case "approved":
|
|
204
|
+
return outcome.data;
|
|
205
|
+
case "pending":
|
|
206
|
+
break;
|
|
207
|
+
case "slow_down":
|
|
208
|
+
intervalMs += 5_000; // back off per RFC 8628
|
|
209
|
+
break;
|
|
210
|
+
case "denied":
|
|
211
|
+
throw new ApiError("ACCESS_DENIED", "Authorization was cancelled in the browser.");
|
|
212
|
+
case "expired":
|
|
213
|
+
throw new ApiError("EXPIRED_TOKEN", "The code expired before it was approved. Run `cos login` again.");
|
|
214
|
+
case "error":
|
|
215
|
+
throw new ApiError("AUTH_FAILED", outcome.message);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
throw new ApiError("TIMEOUT", "Timed out waiting for approval. Run `cos login` again.");
|
|
219
|
+
}
|
|
220
|
+
/** Exchange a refresh token for a new session (rotation). Never clears anything
|
|
221
|
+
* itself — the caller decides, from the outcome, whether the session is over. */
|
|
222
|
+
export async function refreshCliSession(apiUrl, refreshToken) {
|
|
223
|
+
const authBase = cliSessionAuthBase(apiUrl, refreshToken);
|
|
224
|
+
const { status, body } = await envelopePost(`${authBase}/cli/refresh`, {
|
|
225
|
+
refresh_token: refreshToken
|
|
226
|
+
});
|
|
227
|
+
if (body?.success && body.data)
|
|
228
|
+
return { kind: "ok", data: body.data };
|
|
229
|
+
if (status === 401)
|
|
230
|
+
return { kind: "dead" };
|
|
231
|
+
if (status === 409)
|
|
232
|
+
return { kind: "busy" };
|
|
233
|
+
if (status === 404)
|
|
234
|
+
return { kind: "unsupported" };
|
|
235
|
+
return { kind: "transient", status };
|
|
236
|
+
}
|
|
237
|
+
/** Best-effort server-side logout (revokes the refresh token). Never throws. */
|
|
238
|
+
export async function logoutCliSession(apiUrl, refreshToken) {
|
|
239
|
+
try {
|
|
240
|
+
await envelopePost(`${cliSessionAuthBase(apiUrl, refreshToken)}/cli/logout`, { refresh_token: refreshToken });
|
|
241
|
+
}
|
|
242
|
+
catch {
|
|
243
|
+
/* offline logout is fine — the local credentials are cleared regardless */
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
// ── Authenticated /cli/* management (bearer access token, refresh-on-401) ─────
|
|
247
|
+
async function authedRequest(apiUrl, method, path, provider, body, retry = true) {
|
|
248
|
+
const token = provider.token(apiUrl);
|
|
249
|
+
const url = `${cliSessionAuthBase(apiUrl, token)}${path}`;
|
|
250
|
+
const res = await axios.request({
|
|
251
|
+
url,
|
|
252
|
+
method,
|
|
253
|
+
data: body,
|
|
254
|
+
headers: {
|
|
255
|
+
"Content-Type": "application/json",
|
|
256
|
+
...(token ? { Authorization: `Bearer ${token}` } : {})
|
|
257
|
+
},
|
|
258
|
+
timeout: 30_000,
|
|
259
|
+
maxRedirects: 0,
|
|
260
|
+
validateStatus: () => true
|
|
261
|
+
});
|
|
262
|
+
if (res.status === 401 && retry && provider.refresh) {
|
|
263
|
+
const renewed = await provider.refresh(token);
|
|
264
|
+
if (renewed)
|
|
265
|
+
return authedRequest(apiUrl, method, path, provider, body, false);
|
|
266
|
+
}
|
|
267
|
+
const env = res.data;
|
|
268
|
+
if (env?.success && env.data !== undefined)
|
|
269
|
+
return env.data;
|
|
270
|
+
throw new ApiError(env?.error?.code ?? "REQUEST_FAILED", env?.error?.message ?? "Request failed.", res.status);
|
|
271
|
+
}
|
|
272
|
+
export function listCliWorkspaces(apiUrl, provider) {
|
|
273
|
+
return authedRequest(apiUrl, "get", "/cli/workspaces", provider);
|
|
274
|
+
}
|
|
275
|
+
export function listCliProjects(apiUrl, provider, workspaceId) {
|
|
276
|
+
return authedRequest(apiUrl, "get", `/cli/workspaces/${workspaceId}/projects`, provider);
|
|
277
|
+
}
|
|
278
|
+
export function setCliScope(apiUrl, provider, workspaceId, projectId) {
|
|
279
|
+
return authedRequest(apiUrl, "post", "/cli/scope", provider, {
|
|
280
|
+
workspace_id: workspaceId,
|
|
281
|
+
project_id: projectId
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
export function getCliContext(apiUrl, provider) {
|
|
285
|
+
return authedRequest(apiUrl, "get", "/cli/context", provider);
|
|
286
|
+
}
|