@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.
- package/README.md +142 -57
- 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 +102 -13
- package/dist/commands/context.js +160 -0
- package/dist/commands/doctor.js +53 -8
- package/dist/commands/files.js +84 -23
- package/dist/commands/help.js +3 -1
- package/dist/commands/history.js +88 -23
- package/dist/commands/login.js +44 -41
- package/dist/commands/logout.js +13 -4
- package/dist/commands/memory.js +162 -0
- package/dist/commands/mode-model.js +39 -3
- package/dist/commands/modes.js +4 -1
- 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 +152 -0
- package/dist/commands/search.js +92 -0
- package/dist/commands/sessions.js +219 -65
- package/dist/commands/settings.js +87 -0
- package/dist/commands/update.js +159 -0
- package/dist/commands/upload.js +204 -31
- package/dist/commands/usage.js +212 -16
- package/dist/commands/whoami.js +2 -1
- package/dist/ide/editor-context.js +172 -0
- package/dist/ide/ide-session.js +94 -0
- package/dist/ide/tool-host.js +109 -0
- package/dist/main.js +30 -1
- package/dist/services/api.js +171 -13
- package/dist/services/chat-stream.js +145 -0
- package/dist/services/checkpoints.js +116 -0
- package/dist/services/client-tools.js +260 -0
- package/dist/services/command-coordinator.js +200 -0
- package/dist/services/command-policy.js +404 -0
- package/dist/services/config.js +249 -22
- package/dist/services/context.js +307 -6
- package/dist/services/device-auth.js +261 -0
- package/dist/services/diff.js +196 -0
- package/dist/services/env-policy.js +108 -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/git-tools.js +248 -0
- package/dist/services/glob-match.js +164 -0
- package/dist/services/helper-bin.js +64 -0
- package/dist/services/ignore-rules.js +189 -0
- package/dist/services/job-helper.js +307 -0
- package/dist/services/local-files.js +517 -0
- package/dist/services/local-tools.js +432 -0
- package/dist/services/login-flow.js +120 -10
- package/dist/services/meta.js +3 -1
- package/dist/services/mutation-coordinator.js +161 -0
- package/dist/services/mutations.js +493 -0
- package/dist/services/open-url.js +68 -0
- package/dist/services/output.js +13 -5
- package/dist/services/packaged.js +24 -0
- package/dist/services/process-runner.js +406 -0
- package/dist/services/project-context.js +298 -0
- package/dist/services/redaction.js +201 -0
- package/dist/services/secure-store.js +197 -0
- package/dist/services/session-resolver.js +108 -0
- package/dist/services/sia.js +51 -0
- package/dist/services/spinner.js +23 -1
- package/dist/services/update.js +286 -0
- package/dist/services/workspace-registry.js +309 -0
- package/dist/services/workspace.js +573 -0
- package/dist/shell/shell-chat.js +1115 -59
- package/dist/shell/shell-commands.js +220 -19
- package/dist/shell/shell-prompt.js +89 -37
- package/dist/shell/shell-renderer.js +19 -38
- package/dist/shell/shell-router.js +19 -3
- package/dist/shell/shell.js +232 -44
- package/dist/types/index.js +3 -1
- package/dist/ui/approval.js +81 -0
- package/dist/ui/banner.js +55 -13
- package/dist/ui/btw-overlay.js +230 -0
- package/dist/ui/change-review.js +87 -0
- package/dist/ui/chat-renderer.js +223 -29
- package/dist/ui/color-picker.js +21 -0
- package/dist/ui/colors.js +9 -1
- package/dist/ui/command-filter.js +40 -5
- package/dist/ui/command-palette.js +122 -62
- package/dist/ui/command-registry.js +85 -11
- package/dist/ui/command-review.js +138 -0
- package/dist/ui/composer-layout.js +41 -0
- package/dist/ui/conversation.js +398 -0
- package/dist/ui/interrupt.js +35 -0
- package/dist/ui/live.js +18 -1
- package/dist/ui/markdown.js +63 -9
- package/dist/ui/message.js +14 -31
- package/dist/ui/screen-prompt.js +181 -0
- package/dist/ui/screen.js +289 -0
- package/dist/ui/select.js +193 -29
- package/dist/ui/sia-qa.js +213 -0
- package/dist/ui/text-prompt.js +74 -0
- package/dist/ui/theme.js +17 -0
- package/dist/ui/trust.js +93 -0
- package/dist/ui/ui.js +4 -1
- package/package.json +17 -6
- package/dist/ui/activity.js +0 -77
package/dist/services/config.js
CHANGED
|
@@ -1,24 +1,170 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
1
2
|
import fs from "node:fs";
|
|
2
3
|
import os from "node:os";
|
|
3
4
|
import path from "node:path";
|
|
4
|
-
|
|
5
|
-
|
|
5
|
+
import { SealError, isSealed, seal, sealingAvailable, unseal } from "./secure-store.js";
|
|
6
|
+
/**
|
|
7
|
+
* A URL is safe to send credentials to only over HTTPS, or over HTTP to a
|
|
8
|
+
* loopback host (local dev). Anything else (a plain-HTTP remote host) would send
|
|
9
|
+
* bearer/refresh tokens in cleartext — reject it so a mistaken or hostile
|
|
10
|
+
* `--url` / env override can't exfiltrate credentials.
|
|
11
|
+
*/
|
|
12
|
+
export function isSafeUrl(u) {
|
|
13
|
+
try {
|
|
14
|
+
const x = new URL(u);
|
|
15
|
+
if (x.protocol === "https:")
|
|
16
|
+
return true;
|
|
17
|
+
const loopback = ["localhost", "127.0.0.1", "::1", "[::1]", "0.0.0.0"];
|
|
18
|
+
return x.protocol === "http:" && loopback.includes(x.hostname);
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
return false;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
/** Production default; override at login with `--url` or via CARRIEROS_API_URL.
|
|
25
|
+
* An unsafe (plain-HTTP remote) env override is ignored in favour of the
|
|
26
|
+
* secure default rather than silently leaking tokens. */
|
|
27
|
+
const ENV_API_URL = (process.env.CARRIEROS_API_URL || "").trim();
|
|
28
|
+
export const DEFAULT_API_URL = ENV_API_URL && isSafeUrl(ENV_API_URL) ? ENV_API_URL : "https://api.carrieros.ai/v1";
|
|
29
|
+
/**
|
|
30
|
+
* Do two API base URLs point at the same server?
|
|
31
|
+
*
|
|
32
|
+
* Compared by ORIGIN (scheme + host + port), so `https://api.carrieros.ai/v1`
|
|
33
|
+
* and `https://api.carrieros.ai/v2` are the same server while
|
|
34
|
+
* `http://localhost:5000/v1` is not. Used to decide whether a rejection came
|
|
35
|
+
* from the server that issued the session — the only one whose "no" means the
|
|
36
|
+
* session is over. An unknown value on either side is NOT a match: not knowing
|
|
37
|
+
* who issued a session is a reason to leave it alone, not to delete it.
|
|
38
|
+
*/
|
|
39
|
+
export function sameApiOrigin(a, b) {
|
|
40
|
+
if (!a || !b)
|
|
41
|
+
return false;
|
|
42
|
+
try {
|
|
43
|
+
return new URL(a).origin === new URL(b).origin;
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
return a === b;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
6
49
|
/**
|
|
7
50
|
* ConfigStore — the single owner of on-disk CLI state. Everything the CLI
|
|
8
|
-
* persists (
|
|
9
|
-
* JSON file so the rest of the app never touches the filesystem directly.
|
|
51
|
+
* persists (credentials, active session, cached scope, recent uploads) lives in
|
|
52
|
+
* one JSON file so the rest of the app never touches the filesystem directly.
|
|
10
53
|
*
|
|
11
54
|
* Windows-first: `%APPDATA%/CarrierOS/config.json`; falls back to
|
|
12
55
|
* `~/.carrieros/config.json` on other platforms.
|
|
56
|
+
*
|
|
57
|
+
* WRITES ARE MERGES, NOT SNAPSHOTS. A `cos` process can live for hours (the
|
|
58
|
+
* shell) while another one signs in, and the in-memory copy it loaded at
|
|
59
|
+
* startup does not know about that. Writing that copy back — which is what
|
|
60
|
+
* saving a theme, a model, a session id or an update check used to do — served
|
|
61
|
+
* the whole file from a stale snapshot and silently deleted the credentials the
|
|
62
|
+
* other process had just written. Every write now re-reads the file, applies
|
|
63
|
+
* only what THIS call changes, and replaces the file atomically. A field is
|
|
64
|
+
* removed only when a caller asks for it to be removed, which is why logout
|
|
65
|
+
* still works and why nothing else can take `auth` with it.
|
|
13
66
|
*/
|
|
14
67
|
export class ConfigStore {
|
|
15
68
|
dir;
|
|
16
69
|
file;
|
|
70
|
+
/** The config with credentials OPENED — what every caller reads. */
|
|
17
71
|
data;
|
|
72
|
+
/**
|
|
73
|
+
* Why stored credentials could not be opened, when they could not: another
|
|
74
|
+
* Windows account, another machine, or a damaged blob. The CLI then behaves
|
|
75
|
+
* as signed out — it never crashes over it, and never deletes the blob, so
|
|
76
|
+
* `cos login` is the recovery and nothing is lost by trying.
|
|
77
|
+
*/
|
|
78
|
+
credentialError = null;
|
|
18
79
|
constructor() {
|
|
19
80
|
this.dir = ConfigStore.resolveDir();
|
|
20
81
|
this.file = path.join(this.dir, "config.json");
|
|
21
|
-
this.data = this.read();
|
|
82
|
+
this.data = this.reveal(this.read());
|
|
83
|
+
this.protectPlaintextCredentials();
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Credentials written before protection existed are still plaintext on disk.
|
|
87
|
+
* Seal them in place the first time a build that can protect them runs.
|
|
88
|
+
* Best-effort: a failure leaves the file exactly as it was.
|
|
89
|
+
*/
|
|
90
|
+
protectPlaintextCredentials() {
|
|
91
|
+
const raw = this.read();
|
|
92
|
+
const plaintext = (typeof raw.auth?.accessToken === "string" && !isSealed(raw.auth.accessToken)) ||
|
|
93
|
+
(typeof raw.auth?.refreshToken === "string" && !isSealed(raw.auth.refreshToken)) ||
|
|
94
|
+
(typeof raw.secretKey === "string" && !isSealed(raw.secretKey));
|
|
95
|
+
if (!plaintext || !sealingAvailable())
|
|
96
|
+
return;
|
|
97
|
+
try {
|
|
98
|
+
this.commit({
|
|
99
|
+
...(raw.auth ? { auth: this.data.auth } : {}),
|
|
100
|
+
...(typeof raw.secretKey === "string" ? { secretKey: this.data.secretKey } : {})
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
/* leave the file as it was */
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Seal the credential fields of a patch before it is written.
|
|
109
|
+
*
|
|
110
|
+
* Only these three are secrets; everything else in the file — the account
|
|
111
|
+
* email, the workspace, the issuing API — stays readable, so the prompt and
|
|
112
|
+
* an offline `whoami` never need to open anything. Where protection is not
|
|
113
|
+
* available (not Windows, or no C# compiler) the value is written as before:
|
|
114
|
+
* refusing to sign someone in would be worse, and the risk is documented.
|
|
115
|
+
*/
|
|
116
|
+
conceal(patch) {
|
|
117
|
+
const canSeal = (v) => typeof v === "string" && v.length > 0 && !isSealed(v);
|
|
118
|
+
const out = { ...patch };
|
|
119
|
+
if (patch.auth && (canSeal(patch.auth.accessToken) || canSeal(patch.auth.refreshToken))) {
|
|
120
|
+
if (sealingAvailable()) {
|
|
121
|
+
out.auth = {
|
|
122
|
+
...patch.auth,
|
|
123
|
+
accessToken: canSeal(patch.auth.accessToken) ? seal(patch.auth.accessToken) : patch.auth.accessToken,
|
|
124
|
+
refreshToken: canSeal(patch.auth.refreshToken) ? seal(patch.auth.refreshToken) : patch.auth.refreshToken
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
if (canSeal(patch.secretKey) && sealingAvailable())
|
|
129
|
+
out.secretKey = seal(patch.secretKey);
|
|
130
|
+
return out;
|
|
131
|
+
}
|
|
132
|
+
/** Open the credential fields of what is on disk, for the in-memory view. */
|
|
133
|
+
reveal(raw) {
|
|
134
|
+
const out = { ...raw };
|
|
135
|
+
const open = (v) => {
|
|
136
|
+
if (typeof v !== "string")
|
|
137
|
+
return undefined;
|
|
138
|
+
if (!isSealed(v))
|
|
139
|
+
return v;
|
|
140
|
+
try {
|
|
141
|
+
return unseal(v);
|
|
142
|
+
}
|
|
143
|
+
catch (err) {
|
|
144
|
+
this.credentialError =
|
|
145
|
+
err instanceof SealError ? err.message : "Stored credentials could not be opened.";
|
|
146
|
+
return undefined;
|
|
147
|
+
}
|
|
148
|
+
};
|
|
149
|
+
this.credentialError = null;
|
|
150
|
+
if (raw.auth) {
|
|
151
|
+
const accessToken = open(raw.auth.accessToken);
|
|
152
|
+
const refreshToken = open(raw.auth.refreshToken);
|
|
153
|
+
// A session is both halves or neither: half a session would sign the
|
|
154
|
+
// user in and then fail on the first refresh.
|
|
155
|
+
out.auth =
|
|
156
|
+
accessToken && refreshToken
|
|
157
|
+
? { ...raw.auth, accessToken, refreshToken }
|
|
158
|
+
: undefined;
|
|
159
|
+
}
|
|
160
|
+
if (raw.secretKey !== undefined) {
|
|
161
|
+
const key = open(raw.secretKey);
|
|
162
|
+
if (key)
|
|
163
|
+
out.secretKey = key;
|
|
164
|
+
else
|
|
165
|
+
delete out.secretKey;
|
|
166
|
+
}
|
|
167
|
+
return out;
|
|
22
168
|
}
|
|
23
169
|
static resolveDir() {
|
|
24
170
|
const appData = process.env.APPDATA;
|
|
@@ -35,10 +181,60 @@ export class ConfigStore {
|
|
|
35
181
|
return { apiUrl: DEFAULT_API_URL };
|
|
36
182
|
}
|
|
37
183
|
}
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
184
|
+
/**
|
|
185
|
+
* Apply a change on top of what is on disk NOW.
|
|
186
|
+
*
|
|
187
|
+
* `remove` is the only way a key leaves the file. Everything the caller did
|
|
188
|
+
* not mention survives, whoever wrote it and whenever — which is the property
|
|
189
|
+
* that keeps a session alive through an unrelated save from an older process.
|
|
190
|
+
*/
|
|
191
|
+
commit(patch, remove = []) {
|
|
192
|
+
// Merge in DISK form: what is already there stays sealed, and the patch is
|
|
193
|
+
// sealed before it joins it. Plaintext credentials never reach the file.
|
|
194
|
+
const merged = { ...this.read(), ...this.conceal(patch) };
|
|
195
|
+
for (const key of remove)
|
|
196
|
+
delete merged[key];
|
|
197
|
+
this.write(merged);
|
|
198
|
+
this.data = this.reveal(merged);
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Replace the file atomically: write a sibling temp file, then rename over
|
|
202
|
+
* the target. A crash or a full disk mid-write leaves the previous config
|
|
203
|
+
* intact instead of a truncated file that reads as "logged out".
|
|
204
|
+
*/
|
|
205
|
+
write(data) {
|
|
206
|
+
fs.mkdirSync(this.dir, { recursive: true, mode: 0o700 });
|
|
207
|
+
const tmp = `${this.file}.${process.pid}.${crypto.randomBytes(4).toString("hex")}.tmp`;
|
|
208
|
+
try {
|
|
209
|
+
// `mode` on writeFileSync only applies when the file is CREATED — so a
|
|
210
|
+
// pre-existing file with looser perms would keep them. chmod after the
|
|
211
|
+
// write (and on the dir) to guarantee owner-only tokens. POSIX-only; a
|
|
212
|
+
// no-op on Windows ACLs, hence best-effort.
|
|
213
|
+
fs.writeFileSync(tmp, JSON.stringify(data, null, 2), { mode: 0o600 });
|
|
214
|
+
try {
|
|
215
|
+
fs.chmodSync(tmp, 0o600);
|
|
216
|
+
}
|
|
217
|
+
catch {
|
|
218
|
+
/* Windows / restricted FS — best effort */
|
|
219
|
+
}
|
|
220
|
+
fs.renameSync(tmp, this.file);
|
|
221
|
+
}
|
|
222
|
+
catch (err) {
|
|
223
|
+
try {
|
|
224
|
+
fs.unlinkSync(tmp);
|
|
225
|
+
}
|
|
226
|
+
catch {
|
|
227
|
+
/* already gone */
|
|
228
|
+
}
|
|
229
|
+
throw err;
|
|
230
|
+
}
|
|
231
|
+
try {
|
|
232
|
+
fs.chmodSync(this.file, 0o600);
|
|
233
|
+
fs.chmodSync(this.dir, 0o700);
|
|
234
|
+
}
|
|
235
|
+
catch {
|
|
236
|
+
/* Windows / restricted FS — best effort */
|
|
237
|
+
}
|
|
42
238
|
}
|
|
43
239
|
get all() {
|
|
44
240
|
return this.data;
|
|
@@ -47,26 +243,57 @@ export class ConfigStore {
|
|
|
47
243
|
return this.data[key];
|
|
48
244
|
}
|
|
49
245
|
set(key, value) {
|
|
50
|
-
this.
|
|
51
|
-
|
|
246
|
+
// `undefined` is how several callers say "forget this" (e.g. sessionId);
|
|
247
|
+
// it is removed from the file rather than written as a null.
|
|
248
|
+
if (value === undefined)
|
|
249
|
+
this.commit({}, [key]);
|
|
250
|
+
else
|
|
251
|
+
this.commit({ [key]: value });
|
|
52
252
|
}
|
|
53
253
|
update(patch) {
|
|
54
|
-
this.
|
|
55
|
-
|
|
254
|
+
this.commit(patch);
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Re-read the file, discarding the in-memory copy.
|
|
258
|
+
*
|
|
259
|
+
* Every write already goes straight to disk, so the only thing this can pick
|
|
260
|
+
* up is a change made by ANOTHER `cos` process — which is exactly the case
|
|
261
|
+
* token refresh needs: if a second terminal rotated the session, this process
|
|
262
|
+
* is holding a spent refresh token, and presenting it would look to the server
|
|
263
|
+
* like token theft.
|
|
264
|
+
*/
|
|
265
|
+
reload() {
|
|
266
|
+
this.data = this.reveal(this.read());
|
|
56
267
|
}
|
|
57
268
|
get isAuthenticated() {
|
|
58
|
-
|
|
269
|
+
// Device-flow session is the primary credential; a legacy key still counts.
|
|
270
|
+
return Boolean(this.data.auth?.accessToken || this.data.secretKey);
|
|
59
271
|
}
|
|
60
|
-
/**
|
|
272
|
+
/**
|
|
273
|
+
* Wipe credentials + derived state on logout (keeps apiUrl).
|
|
274
|
+
*
|
|
275
|
+
* The ONE place `auth` is removed. Everything else merges, so signing out is
|
|
276
|
+
* something a user asks for rather than something a save can do by accident.
|
|
277
|
+
* Title and ordinals are CACHES OF sessionId: dropping the id without them
|
|
278
|
+
* left the footer naming a conversation the CLI was no longer in, and
|
|
279
|
+
* `/memory 2` resolving against a stale numbering from a previous account.
|
|
280
|
+
*/
|
|
61
281
|
clearAuth() {
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
282
|
+
this.commit({}, [
|
|
283
|
+
"auth",
|
|
284
|
+
"secretKey",
|
|
285
|
+
"sessionId",
|
|
286
|
+
"sessionTitle",
|
|
287
|
+
"sessionOrdinals",
|
|
288
|
+
"memoryArtifactIds",
|
|
289
|
+
"scope",
|
|
290
|
+
"attachedFileIds"
|
|
291
|
+
]);
|
|
66
292
|
}
|
|
67
293
|
addUpload(record) {
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
this.
|
|
294
|
+
// Read-modify-write against the file, so an upload recorded by another
|
|
295
|
+
// process is not dropped by this one.
|
|
296
|
+
const list = this.read().uploads ?? [];
|
|
297
|
+
this.commit({ uploads: [record, ...list].slice(0, 25) });
|
|
71
298
|
}
|
|
72
299
|
}
|
package/dist/services/context.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { ApiClient } from "./api.js";
|
|
2
|
-
import { DEFAULT_API_URL } from "./config.js";
|
|
1
|
+
import { ApiClient, ApiError } from "./api.js";
|
|
2
|
+
import { DEFAULT_API_URL, sameApiOrigin } from "./config.js";
|
|
3
|
+
import { refreshCliSession } from "./device-auth.js";
|
|
3
4
|
/**
|
|
4
5
|
* Thrown by requireAuth when no key is configured. Unlike a process.exit, this
|
|
5
6
|
* can be caught — so the interactive shell can keep running after a failed
|
|
@@ -21,9 +22,159 @@ export class CommandContext {
|
|
|
21
22
|
constructor(config) {
|
|
22
23
|
this.config = config;
|
|
23
24
|
}
|
|
25
|
+
/** In-process mode override. The interactive shell always OPENS in the Carrier
|
|
26
|
+
* OS mode (the core persona) regardless of the persisted default; setting the
|
|
27
|
+
* mode mid-session updates this. It is never written to disk, so standalone
|
|
28
|
+
* commands keep using the persisted `mode`. */
|
|
29
|
+
overrideMode;
|
|
30
|
+
/** True while running inside the interactive `cos` shell (vs a one-shot
|
|
31
|
+
* standalone command). Commands use this to decide between interactive
|
|
32
|
+
* prompts (shell) and finish-and-return "next steps" output (standalone). */
|
|
33
|
+
_inShell = false;
|
|
34
|
+
get inShell() {
|
|
35
|
+
return this._inShell;
|
|
36
|
+
}
|
|
37
|
+
setInShell(v) {
|
|
38
|
+
this._inShell = v;
|
|
39
|
+
}
|
|
40
|
+
/** File ids attached to chat messages, sent as `file_ids` on /v1/chat so the
|
|
41
|
+
* model can read the file. PERSISTED in config (not just in-process) so a file
|
|
42
|
+
* uploaded via a standalone `cos upload` is still attached when the shell opens
|
|
43
|
+
* in a separate process. Populated by upload (auto-attach) and `/attach`,
|
|
44
|
+
* cleared by `/detach` or logout. */
|
|
45
|
+
get attachedFileIds() {
|
|
46
|
+
return this.config.get("attachedFileIds") ?? [];
|
|
47
|
+
}
|
|
48
|
+
/** Attach a file id (deduped) so it rides along on subsequent messages. */
|
|
49
|
+
attachFile(fileId) {
|
|
50
|
+
if (!fileId)
|
|
51
|
+
return;
|
|
52
|
+
const list = this.attachedFileIds;
|
|
53
|
+
if (!list.includes(fileId))
|
|
54
|
+
this.config.set("attachedFileIds", [...list, fileId]);
|
|
55
|
+
}
|
|
56
|
+
/** Drop all attachments (an explicit /detach or logout). */
|
|
57
|
+
clearAttachments() {
|
|
58
|
+
this.config.set("attachedFileIds", []);
|
|
59
|
+
}
|
|
24
60
|
/** A client built from current config (anonymous if not logged in). */
|
|
25
61
|
client() {
|
|
26
|
-
return new ApiClient(this.config.get("apiUrl") ?? DEFAULT_API_URL, this.
|
|
62
|
+
return new ApiClient(this.config.get("apiUrl") ?? DEFAULT_API_URL, this.authProvider());
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* The one refresh currently on the wire, shared by every request that needs it.
|
|
66
|
+
*
|
|
67
|
+
* Refresh tokens are single-use. The shell opens by loading models and modes
|
|
68
|
+
* in parallel, so when the stored access token has expired both requests get
|
|
69
|
+
* a 401 in the same instant — and each used to run its own refresh with the
|
|
70
|
+
* same token. The server let exactly one rotate and answered the other 409;
|
|
71
|
+
* the CLI read that 409 as a dead session and deleted the credentials the
|
|
72
|
+
* winner had just saved. The first message still went through on the fresh
|
|
73
|
+
* token held in memory, and the second found nothing on disk: "You're not
|
|
74
|
+
* signed in".
|
|
75
|
+
*
|
|
76
|
+
* Lives on the context rather than the provider because `client()` builds a
|
|
77
|
+
* new provider for every client, and the coordination has to span all of them.
|
|
78
|
+
*/
|
|
79
|
+
refreshing = null;
|
|
80
|
+
/**
|
|
81
|
+
* The credential + silent-refresh strategy for every authenticated call.
|
|
82
|
+
* Prefers the device-flow session; falls back to a legacy static key.
|
|
83
|
+
*/
|
|
84
|
+
authProvider() {
|
|
85
|
+
return {
|
|
86
|
+
token: () => this.config.get("auth")?.accessToken ?? this.config.get("secretKey"),
|
|
87
|
+
refresh: (failedToken) => {
|
|
88
|
+
this.refreshing ??= this.renewSession(failedToken).finally(() => {
|
|
89
|
+
this.refreshing = null;
|
|
90
|
+
});
|
|
91
|
+
return this.refreshing;
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Renew the session, and clear local credentials ONLY when the server says it
|
|
97
|
+
* is finished.
|
|
98
|
+
*
|
|
99
|
+
* Before spending the refresh token this re-reads config from disk: another
|
|
100
|
+
* `cos` process (a second terminal, a standalone command alongside the shell)
|
|
101
|
+
* may already have rotated it, in which case the token held in memory is spent
|
|
102
|
+
* and presenting it trips the server's reuse detection — which revokes every
|
|
103
|
+
* device on the account. Adopting the rotated pair avoids asking at all.
|
|
104
|
+
*/
|
|
105
|
+
async renewSession(failedToken) {
|
|
106
|
+
this.config.reload();
|
|
107
|
+
const auth = this.config.get("auth");
|
|
108
|
+
if (!auth?.refreshToken)
|
|
109
|
+
return undefined;
|
|
110
|
+
// Someone already renewed since this request went out — just retry with it.
|
|
111
|
+
if (failedToken && auth.accessToken && auth.accessToken !== failedToken) {
|
|
112
|
+
return auth.accessToken;
|
|
113
|
+
}
|
|
114
|
+
const apiUrl = this.config.get("apiUrl") ?? DEFAULT_API_URL;
|
|
115
|
+
const outcome = await refreshCliSession(apiUrl, auth.refreshToken);
|
|
116
|
+
switch (outcome.kind) {
|
|
117
|
+
case "ok": {
|
|
118
|
+
const renewed = outcome.data;
|
|
119
|
+
this.config.update({
|
|
120
|
+
auth: {
|
|
121
|
+
...auth,
|
|
122
|
+
accessToken: renewed.access_token,
|
|
123
|
+
refreshToken: renewed.refresh_token,
|
|
124
|
+
// A server that rotated this session is the server that owns it —
|
|
125
|
+
// stamp sessions issued before the field existed.
|
|
126
|
+
apiUrl: auth.apiUrl ?? apiUrl,
|
|
127
|
+
workspace: renewed.workspace ?? auth.workspace,
|
|
128
|
+
project: renewed.project ?? auth.project
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
return renewed.access_token;
|
|
132
|
+
}
|
|
133
|
+
case "dead":
|
|
134
|
+
// "This session is finished" is only true when it comes from the server
|
|
135
|
+
// that ISSUED the session. Pointing the CLI at a different API (a local
|
|
136
|
+
// dev server, a mistyped --url) gets the very same 401 from a server
|
|
137
|
+
// that has simply never heard of it — and acting on that is
|
|
138
|
+
// unrecoverable, because the refresh token exists nowhere else.
|
|
139
|
+
//
|
|
140
|
+
// Signing out is therefore something the CLI does only when it is sure,
|
|
141
|
+
// or something the user does explicitly with `cos logout`. A refresh
|
|
142
|
+
// token the server has already revoked grants nothing, so leaving one on
|
|
143
|
+
// disk costs nothing either.
|
|
144
|
+
if (sameApiOrigin(auth.apiUrl, apiUrl)) {
|
|
145
|
+
this.config.clearAuth();
|
|
146
|
+
return undefined;
|
|
147
|
+
}
|
|
148
|
+
throw new ApiError("SESSION_NOT_RENEWABLE", auth.apiUrl
|
|
149
|
+
? `This session was issued by ${auth.apiUrl}, but the CLI is pointed at ${apiUrl}. ` +
|
|
150
|
+
`Point it back with \`cos login --url ${auth.apiUrl}\`, or run \`cos logout\` to sign in here.`
|
|
151
|
+
: `${apiUrl} would not renew this session. If you signed out elsewhere or changed API URL, ` +
|
|
152
|
+
"run `cos logout` and sign in again.", 401);
|
|
153
|
+
case "busy": {
|
|
154
|
+
// A different process won the rotation; its tokens are about to land in
|
|
155
|
+
// the shared config. Give it a moment to write them rather than guessing.
|
|
156
|
+
const adopted = await this.awaitRotatedElsewhere(auth.refreshToken);
|
|
157
|
+
if (adopted)
|
|
158
|
+
return adopted;
|
|
159
|
+
throw new ApiError("SESSION_BUSY", "Your session is being renewed by another Carrier OS window. Try again in a moment.", 409);
|
|
160
|
+
}
|
|
161
|
+
case "transient":
|
|
162
|
+
// The session may be perfectly healthy — never sign someone out because
|
|
163
|
+
// the API had a bad second.
|
|
164
|
+
throw new ApiError("REFRESH_UNAVAILABLE", "Couldn't renew your session right now. Try again in a moment.", outcome.status || 503);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
/** Poll the shared config briefly for a refresh token rotated by another process. */
|
|
168
|
+
async awaitRotatedElsewhere(spentRefreshToken) {
|
|
169
|
+
for (let attempt = 0; attempt < 10; attempt += 1) {
|
|
170
|
+
await new Promise((r) => setTimeout(r, 100));
|
|
171
|
+
this.config.reload();
|
|
172
|
+
const auth = this.config.get("auth");
|
|
173
|
+
if (auth?.refreshToken && auth.refreshToken !== spentRefreshToken && auth.accessToken) {
|
|
174
|
+
return auth.accessToken;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
return undefined;
|
|
27
178
|
}
|
|
28
179
|
/**
|
|
29
180
|
* A client guaranteed to carry a key, or a clean exit with guidance. Use this
|
|
@@ -31,12 +182,162 @@ export class CommandContext {
|
|
|
31
182
|
*/
|
|
32
183
|
requireAuth() {
|
|
33
184
|
if (!this.config.isAuthenticated) {
|
|
34
|
-
|
|
185
|
+
// Say WHY when we know: credentials that exist but cannot be opened by
|
|
186
|
+
// this Windows account (copied from another machine or user, or damaged)
|
|
187
|
+
// are a different situation from never having signed in.
|
|
188
|
+
throw new AuthRequiredError(this.config.credentialError
|
|
189
|
+
? `${this.config.credentialError} Run \`cos login\` to sign in again.`
|
|
190
|
+
: undefined);
|
|
35
191
|
}
|
|
36
192
|
return this.client();
|
|
37
193
|
}
|
|
38
|
-
/**
|
|
194
|
+
/**
|
|
195
|
+
* Active Carrier mode. Mode belongs to the CHAT TYPE, not the session:
|
|
196
|
+
*
|
|
197
|
+
* carrier → always "general". Carrier Chat runs one mode, so this is
|
|
198
|
+
* derived rather than stored — nothing chosen in Standard can
|
|
199
|
+
* leak in, and nothing chosen here can leak back out.
|
|
200
|
+
* standard → the session override, else the persisted default, else "auto"
|
|
201
|
+
* (Standard is the only place Auto routing applies).
|
|
202
|
+
*
|
|
203
|
+
* Deriving it is what keeps a Carrier→Standard switch from stranding you in
|
|
204
|
+
* General: there is no carrier mode to carry over in the first place.
|
|
205
|
+
*/
|
|
39
206
|
get mode() {
|
|
40
|
-
|
|
207
|
+
if (this.chatType === "carrier")
|
|
208
|
+
return "general";
|
|
209
|
+
return this.overrideMode ?? this.config.get("mode") ?? "auto";
|
|
210
|
+
}
|
|
211
|
+
/** True when the active chat type lets the user choose a mode at all. */
|
|
212
|
+
get modeIsSelectable() {
|
|
213
|
+
return this.chatType !== "carrier";
|
|
214
|
+
}
|
|
215
|
+
/** Set the mode for this process only (interactive shell), without persisting. */
|
|
216
|
+
setSessionMode(id) {
|
|
217
|
+
this.overrideMode = id;
|
|
218
|
+
}
|
|
219
|
+
/** Active chat experience: "carrier" (flagship Carrier Chat) by default — you
|
|
220
|
+
* always land in Carrier Chat, matching the web app. Persisted so a chosen
|
|
221
|
+
* type survives across invocations; reset to carrier on login. */
|
|
222
|
+
get chatType() {
|
|
223
|
+
return this.config.get("chatType") ?? "carrier";
|
|
224
|
+
}
|
|
225
|
+
/** Switch chat type. Because a conversation's type is fixed at creation, this
|
|
226
|
+
* clears the active session so the NEXT message starts a fresh conversation of
|
|
227
|
+
* the new type. */
|
|
228
|
+
setChatType(type) {
|
|
229
|
+
this.config.set("chatType", type);
|
|
230
|
+
this.config.set("sessionId", undefined);
|
|
231
|
+
// Drop the session's mode override so the new chat type lands on its own
|
|
232
|
+
// default (carrier → General, standard → the saved mode or Auto) instead of
|
|
233
|
+
// inheriting a mode the user picked for the type they just left.
|
|
234
|
+
this.overrideMode = undefined;
|
|
235
|
+
}
|
|
236
|
+
/** Persisted web-search preference. `undefined` means "not chosen here" — the
|
|
237
|
+
* API then falls back to the workspace's admin toggle, which is what the web
|
|
238
|
+
* app does. `/websearch on|off` persists a choice that wins over that. */
|
|
239
|
+
get webSearch() {
|
|
240
|
+
return this.config.get("webSearch");
|
|
241
|
+
}
|
|
242
|
+
setWebSearch(on) {
|
|
243
|
+
this.config.set("webSearch", on);
|
|
244
|
+
}
|
|
245
|
+
/** One-shot arm from a bare `/websearch`: search the NEXT message, then go
|
|
246
|
+
* back to whatever the persisted preference was. Deliberately in-process —
|
|
247
|
+
* an armed turn that never got sent shouldn't survive into a new session. */
|
|
248
|
+
armed = false;
|
|
249
|
+
get webSearchArmed() {
|
|
250
|
+
return this.armed;
|
|
251
|
+
}
|
|
252
|
+
armWebSearch() {
|
|
253
|
+
this.armed = true;
|
|
254
|
+
}
|
|
255
|
+
disarmWebSearch() {
|
|
256
|
+
this.armed = false;
|
|
257
|
+
}
|
|
258
|
+
/** What to send as `web_search` on the next turn: forced on while armed,
|
|
259
|
+
* otherwise the persisted preference (undefined = follow the workspace). */
|
|
260
|
+
get effectiveWebSearch() {
|
|
261
|
+
return this.armed ? true : this.webSearch;
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Fast mode — Llama via Groq instead of the selected model.
|
|
265
|
+
*
|
|
266
|
+
* STANDARD CHAT ONLY, mirroring the web's `isRestrictedType`: it forces
|
|
267
|
+
* fastMode off for `carrier`/`temp` conversations even when one has the flag
|
|
268
|
+
* stored. Deriving it here rather than clearing the setting means switching
|
|
269
|
+
* Carrier → Standard restores whatever the user last chose, instead of
|
|
270
|
+
* silently losing it on every round trip.
|
|
271
|
+
*/
|
|
272
|
+
get fast() {
|
|
273
|
+
if (this.chatType !== "standard")
|
|
274
|
+
return false;
|
|
275
|
+
return this.config.get("fast") === true;
|
|
276
|
+
}
|
|
277
|
+
setFast(on) {
|
|
278
|
+
this.config.set("fast", on);
|
|
279
|
+
}
|
|
280
|
+
/** High Power (HIPWR) — the 4-pass refinement pipeline. Persisted, but the
|
|
281
|
+
* server still treats it as opt-in per request and admin-gated. */
|
|
282
|
+
get highPower() {
|
|
283
|
+
return this.config.get("highPower") === true;
|
|
284
|
+
}
|
|
285
|
+
setHighPower(on) {
|
|
286
|
+
this.config.set("highPower", on);
|
|
287
|
+
}
|
|
288
|
+
/** SIA clarification — ask before sending, rather than guessing at an
|
|
289
|
+
* ambiguous prompt. Off by default, like the web composer's toggle. */
|
|
290
|
+
get siaMode() {
|
|
291
|
+
// STANDARD CHAT ONLY, derived the same way `fast` is: Carrier Chat runs its
|
|
292
|
+
// own behaviour layer and the web shows no SIA control there. Deriving
|
|
293
|
+
// rather than clearing means a Carrier -> Standard switch restores whatever
|
|
294
|
+
// the user last chose instead of silently losing it.
|
|
295
|
+
if (this.chatType !== "standard")
|
|
296
|
+
return "off";
|
|
297
|
+
const stored = this.config.get("sia");
|
|
298
|
+
// Legacy booleans from before the mode existed: true meant "consult the
|
|
299
|
+
// backend", which is exactly what auto does now.
|
|
300
|
+
if (stored === true)
|
|
301
|
+
return "auto";
|
|
302
|
+
if (stored === false)
|
|
303
|
+
return "off";
|
|
304
|
+
return stored === "off" ? "off" : "auto"; // unset -> auto, the default
|
|
305
|
+
}
|
|
306
|
+
/** True when a turn should ask the backend whether clarification is needed. */
|
|
307
|
+
get sia() {
|
|
308
|
+
return this.siaMode === "auto";
|
|
309
|
+
}
|
|
310
|
+
setSiaMode(mode) {
|
|
311
|
+
this.config.set("sia", mode);
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* True while a main chat turn is rendering in the background.
|
|
315
|
+
*
|
|
316
|
+
* Runtime-only (never persisted): the shell sets it when it detaches a turn
|
|
317
|
+
* so commands that share the terminal — `/btw` — can tell who owns the
|
|
318
|
+
* transient region.
|
|
319
|
+
*/
|
|
320
|
+
mainTurnRunning = false;
|
|
321
|
+
/**
|
|
322
|
+
* Credits this shell session's turns were actually debited, summed from the
|
|
323
|
+
* server's per-turn `credits_spent`. Runtime-only: "this session" means this
|
|
324
|
+
* process. Background context maintenance is billed separately on the server
|
|
325
|
+
* and is not a turn, so it is not in here — `/usage` reports it.
|
|
326
|
+
*/
|
|
327
|
+
sessionCreditsSpent = 0;
|
|
328
|
+
/** Whether any turn this session reported its spend (older APIs do not). */
|
|
329
|
+
sessionSpendKnown = false;
|
|
330
|
+
/** Citations from the most recent turn that returned any, so /sources and
|
|
331
|
+
* /open can act on them after the answer has scrolled away. */
|
|
332
|
+
lastSearch = null;
|
|
333
|
+
recordSearch(sources) {
|
|
334
|
+
if (sources.length > 0)
|
|
335
|
+
this.lastSearch = { sources, at: Date.now() };
|
|
336
|
+
}
|
|
337
|
+
get lastSources() {
|
|
338
|
+
return this.lastSearch?.sources ?? [];
|
|
339
|
+
}
|
|
340
|
+
get lastSearchAt() {
|
|
341
|
+
return this.lastSearch?.at ?? null;
|
|
41
342
|
}
|
|
42
343
|
}
|