@carrieros/cli 0.3.0 → 0.4.1
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 +89 -15
- package/dist/commands/chat.js +6 -6
- package/dist/commands/context.js +40 -0
- package/dist/commands/doctor.js +34 -14
- package/dist/commands/logout.js +2 -0
- package/dist/commands/permissions.js +78 -0
- package/dist/commands/scope.js +9 -6
- package/dist/commands/sessions.js +5 -0
- package/dist/commands/settings.js +83 -10
- package/dist/commands/update.js +177 -51
- package/dist/commands/usage.js +10 -8
- package/dist/commands/version.js +1 -3
- package/dist/commands/whoami.js +12 -9
- package/dist/ide/editor-context.js +115 -12
- package/dist/ide/ide-session.js +288 -18
- package/dist/ide/tool-host.js +6 -6
- package/dist/main.js +10 -1
- package/dist/services/api.js +183 -15
- package/dist/services/auth-origin.js +20 -0
- package/dist/services/auto-update.js +221 -0
- package/dist/services/chat-stream.js +26 -3
- package/dist/services/checkpoints.js +176 -14
- package/dist/services/client-tools.js +123 -27
- 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 +85 -12
- package/dist/services/command-policy.js +34 -4
- package/dist/services/config.js +96 -11
- package/dist/services/container-runner.js +254 -0
- package/dist/services/container-supervisor.js +38 -0
- package/dist/services/context.js +98 -25
- package/dist/services/device-auth.js +33 -6
- package/dist/services/execution-platform.js +30 -0
- package/dist/services/file-resolver.js +1 -1
- package/dist/services/folder-key.js +22 -0
- package/dist/services/git-tools.js +181 -0
- package/dist/services/helper-bin.js +56 -35
- package/dist/services/instruction-resolver.js +54 -0
- package/dist/services/job-helper.js +31 -10
- package/dist/services/local-files.js +148 -26
- package/dist/services/local-tools.js +540 -35
- package/dist/services/login-flow.js +44 -13
- package/dist/services/meta.js +27 -0
- package/dist/services/mutation-coordinator.js +186 -20
- package/dist/services/mutation-groups.js +309 -0
- package/dist/services/mutation-recovery.js +159 -0
- package/dist/services/mutations.js +264 -78
- package/dist/services/packaged-update.js +403 -0
- package/dist/services/packaged.js +15 -0
- package/dist/services/permission-mode.js +78 -0
- package/dist/services/process-runner.js +7 -1
- package/dist/services/project-context.js +4 -4
- package/dist/services/result-reconciliation.js +49 -0
- package/dist/services/secure-store.js +21 -1
- package/dist/services/session-resolver.js +7 -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 +457 -13
- package/dist/services/workspace-registry.js +4 -3
- package/dist/services/workspace.js +8 -1
- package/dist/shell/shell-chat.js +320 -34
- package/dist/shell/shell-commands.js +47 -5
- package/dist/shell/shell-prompt.js +21 -11
- package/dist/shell/shell-renderer.js +1 -1
- package/dist/shell/shell.js +107 -20
- package/dist/shell/task-context-view.js +40 -0
- package/dist/ui/agent-cards.js +111 -0
- package/dist/ui/agent-presentation.js +131 -0
- package/dist/ui/approval.js +46 -16
- package/dist/ui/banner.js +31 -87
- package/dist/ui/change-review.js +293 -46
- package/dist/ui/chat-renderer.js +6 -6
- package/dist/ui/colors.js +9 -9
- package/dist/ui/command-details.js +11 -0
- package/dist/ui/command-palette.js +27 -10
- package/dist/ui/command-registry.js +11 -4
- package/dist/ui/command-review.js +77 -28
- package/dist/ui/composer-layout.js +26 -20
- package/dist/ui/conversation.js +77 -25
- package/dist/ui/live.js +1 -1
- package/dist/ui/screen.js +19 -11
- package/dist/ui/select.js +6 -0
- package/dist/ui/task-context-card.js +99 -0
- package/dist/ui/trust.js +7 -12
- package/dist/ui/ui.js +23 -0
- package/package.json +9 -5
|
@@ -1,8 +1,12 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { APPROVAL_TIMEOUT_MS } from "./mutations.js";
|
|
1
3
|
import { PolicyError, evaluateCommand } from "./command-policy.js";
|
|
2
4
|
import { JobHelperError } from "./job-helper.js";
|
|
3
5
|
import { RunnerError, runProcess } from "./process-runner.js";
|
|
4
6
|
import { Redactor, projectEnvSecrets } from "./redaction.js";
|
|
5
7
|
import { neutralizingOverrides } from "./workspace.js";
|
|
8
|
+
import { containerRuntime, verifyContainerRuntime } from "./container-runner.js";
|
|
9
|
+
import { executionAdapter, executionPlatform, executionContract } from "./execution-platform.js";
|
|
6
10
|
import { RepositoryError, activeRepository, isWildcardSelector, listRepositories, resolveOperableRepository } from "./workspace-registry.js";
|
|
7
11
|
/**
|
|
8
12
|
* One turn's proposed local commands: check → ask → run → answer.
|
|
@@ -67,17 +71,28 @@ export function createCommandCoordinator(opts) {
|
|
|
67
71
|
const { ui } = opts;
|
|
68
72
|
let chain = Promise.resolve();
|
|
69
73
|
let declined = false;
|
|
70
|
-
|
|
74
|
+
// One answer per call. Transport owns retrying it; a later error must never
|
|
75
|
+
// send a second, contradictory result for a command that already ran.
|
|
76
|
+
const answered = new Set();
|
|
77
|
+
const submitOnce = (result) => {
|
|
78
|
+
if (answered.has(result.tool_call_id))
|
|
79
|
+
return Promise.resolve();
|
|
80
|
+
answered.add(result.tool_call_id);
|
|
81
|
+
return opts.submit(result);
|
|
82
|
+
};
|
|
83
|
+
const seen = new Set();
|
|
84
|
+
const fail = (call, started, code, message) => submitOnce({ tool_call_id: call.tool_call_id, ok: false, error: { code, message }, duration_ms: Date.now() - started });
|
|
71
85
|
async function process(call) {
|
|
86
|
+
const boundCall = structuredClone(call);
|
|
72
87
|
const started = Date.now();
|
|
73
88
|
const args = (call.arguments ?? {});
|
|
74
89
|
const reason = typeof args.reason === "string" ? args.reason.slice(0, 300) : "";
|
|
75
90
|
if (declined) {
|
|
76
|
-
await fail(
|
|
91
|
+
await fail(boundCall, started, "COMMAND_REJECTED", "The user already declined a command in this turn. Nothing ran; ask how to proceed.");
|
|
77
92
|
return;
|
|
78
93
|
}
|
|
79
94
|
if (opts.signal.aborted) {
|
|
80
|
-
await fail(
|
|
95
|
+
await fail(boundCall, started, "COMMAND_CANCELLED", "The turn was stopped. Nothing ran.");
|
|
81
96
|
return;
|
|
82
97
|
}
|
|
83
98
|
// 1. Which repository, then policy — both before anyone is asked. A command
|
|
@@ -92,18 +107,20 @@ export function createCommandCoordinator(opts) {
|
|
|
92
107
|
catch (err) {
|
|
93
108
|
const e = errorCodeOf(err);
|
|
94
109
|
ui.finished({ decision: null, errorCode: e.code, message: e.message });
|
|
95
|
-
await fail(
|
|
110
|
+
await fail(boundCall, started, e.code, e.message);
|
|
96
111
|
return;
|
|
97
112
|
}
|
|
98
113
|
let decision;
|
|
114
|
+
let policyFingerprint;
|
|
99
115
|
try {
|
|
100
116
|
const { reason: _r, repository: _repo, ...proposal } = args;
|
|
101
117
|
decision = evaluateCommand(proposal, root);
|
|
118
|
+
policyFingerprint = JSON.stringify(decision);
|
|
102
119
|
}
|
|
103
120
|
catch (err) {
|
|
104
121
|
const e = errorCodeOf(err);
|
|
105
122
|
ui.finished({ decision: null, errorCode: e.code, message: e.message });
|
|
106
|
-
await fail(
|
|
123
|
+
await fail(boundCall, started, e.code, e.message);
|
|
107
124
|
return;
|
|
108
125
|
}
|
|
109
126
|
// Git reads file content through repository-configured programs; neutralize
|
|
@@ -113,15 +130,45 @@ export function createCommandCoordinator(opts) {
|
|
|
113
130
|
if (!overrides) {
|
|
114
131
|
const message = "The repository's Git configuration could not be read safely, so the command was not run.";
|
|
115
132
|
ui.finished({ decision, errorCode: "COMMAND_DENIED", message });
|
|
116
|
-
await fail(
|
|
133
|
+
await fail(boundCall, started, "COMMAND_DENIED", message);
|
|
117
134
|
return;
|
|
118
135
|
}
|
|
119
136
|
const sub = decision.effectiveArgs.indexOf(decision.args[0]);
|
|
120
137
|
decision = { ...decision, effectiveArgs: [...decision.effectiveArgs.slice(0, sub), ...overrides, ...decision.effectiveArgs.slice(sub)] };
|
|
121
138
|
}
|
|
139
|
+
// Capability is checked before asking for approval, and again by runProcess.
|
|
140
|
+
try {
|
|
141
|
+
if (executionAdapter(executionPlatform()) === "isolated-container") {
|
|
142
|
+
await verifyContainerRuntime(containerRuntime());
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
catch (err) {
|
|
146
|
+
const e = errorCodeOf(err);
|
|
147
|
+
ui.finished({ decision, errorCode: e.code, message: e.message });
|
|
148
|
+
await fail(boundCall, started, e.code, e.message);
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
122
151
|
// 2. Approval, then 3. run — both while holding the terminal.
|
|
123
152
|
await opts.withTerminal(async () => {
|
|
124
|
-
|
|
153
|
+
if (opts.signal.aborted) {
|
|
154
|
+
await fail(boundCall, started, "COMMAND_CANCELLED", "The turn was stopped before command review. Nothing ran.");
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
if (executionAdapter(executionPlatform()) === "isolated-container") {
|
|
158
|
+
decision = { ...decision, notes: [
|
|
159
|
+
...decision.notes.filter(note => !note.includes("Windows account")),
|
|
160
|
+
"Runs in an isolated Linux container with only this repository mounted. Network access is disabled; host tools and credentials are not inherited."
|
|
161
|
+
] };
|
|
162
|
+
}
|
|
163
|
+
const scope = opts.recoveryScope?.();
|
|
164
|
+
const fingerprint = () => createHash("sha256").update(JSON.stringify({ call, decision, root, repository: repository?.id, workflow: opts.approvalContext?.() })).digest("hex");
|
|
165
|
+
const reviewed = fingerprint();
|
|
166
|
+
const deadline = Date.now() + Math.min(APPROVAL_TIMEOUT_MS, call.timeout_ms ?? APPROVAL_TIMEOUT_MS);
|
|
167
|
+
const answer = await ui.review(decision, reason, repository?.name, boundCall.tool_call_id);
|
|
168
|
+
if (opts.signal.aborted) {
|
|
169
|
+
await fail(boundCall, started, "COMMAND_CANCELLED", "The turn was stopped during command review. Nothing ran.");
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
125
172
|
if (answer !== "approve") {
|
|
126
173
|
declined = true;
|
|
127
174
|
const code = answer === "timeout" ? "APPROVAL_TIMEOUT" : answer === "cancel" ? "COMMAND_CANCELLED" : "COMMAND_REJECTED";
|
|
@@ -131,11 +178,27 @@ export function createCommandCoordinator(opts) {
|
|
|
131
178
|
? "The user stopped the turn. Nothing ran."
|
|
132
179
|
: "The user rejected the command. Nothing ran.";
|
|
133
180
|
ui.finished({ decision, errorCode: code, message });
|
|
134
|
-
await fail(
|
|
181
|
+
await fail(boundCall, started, code, message);
|
|
135
182
|
if (answer === "cancel")
|
|
136
183
|
ui.cancelTurn();
|
|
137
184
|
return;
|
|
138
185
|
}
|
|
186
|
+
const { reason: _reason, repository: _selector, ...currentProposal } = args;
|
|
187
|
+
let unchanged = false;
|
|
188
|
+
try {
|
|
189
|
+
unchanged = Date.now() < deadline && scope === opts.recoveryScope?.() && fingerprint() === reviewed &&
|
|
190
|
+
commandRepository(args.repository, opts.root).id === repository?.id &&
|
|
191
|
+
JSON.stringify(evaluateCommand(currentProposal, root)) === policyFingerprint;
|
|
192
|
+
}
|
|
193
|
+
catch {
|
|
194
|
+
unchanged = false;
|
|
195
|
+
}
|
|
196
|
+
if (!unchanged) {
|
|
197
|
+
declined = true;
|
|
198
|
+
ui.finished({ decision, errorCode: "APPROVAL_INVALIDATED", message: "Command, script, scope or deadline changed during review. Request fresh approval." });
|
|
199
|
+
await fail(boundCall, started, "APPROVAL_INVALIDATED", "Command, script, scope or deadline changed during review. Nothing ran.");
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
139
202
|
let result;
|
|
140
203
|
try {
|
|
141
204
|
const redactor = new Redactor([...projectEnvSecrets(root), ...(opts.cliSecrets ?? [])]);
|
|
@@ -145,6 +208,7 @@ export function createCommandCoordinator(opts) {
|
|
|
145
208
|
cwd: decision.cwdAbsolute,
|
|
146
209
|
root,
|
|
147
210
|
timeoutMs: decision.timeoutMs,
|
|
211
|
+
operationId: boundCall.tool_call_id,
|
|
148
212
|
signal: opts.signal,
|
|
149
213
|
redactor,
|
|
150
214
|
onStart: () => ui.started(decision),
|
|
@@ -154,7 +218,7 @@ export function createCommandCoordinator(opts) {
|
|
|
154
218
|
catch (err) {
|
|
155
219
|
const e = errorCodeOf(err);
|
|
156
220
|
ui.finished({ decision, errorCode: e.code, message: e.message });
|
|
157
|
-
await fail(
|
|
221
|
+
await fail(boundCall, started, e.code, e.message);
|
|
158
222
|
return;
|
|
159
223
|
}
|
|
160
224
|
ui.finished({ decision, result });
|
|
@@ -176,6 +240,7 @@ export function createCommandCoordinator(opts) {
|
|
|
176
240
|
started_at: result.started_at,
|
|
177
241
|
ended_at: result.ended_at,
|
|
178
242
|
duration_ms: result.duration_ms,
|
|
243
|
+
execution_backend: executionContract().backend,
|
|
179
244
|
stdout_bytes: result.stdout_bytes,
|
|
180
245
|
stderr_bytes: result.stderr_bytes,
|
|
181
246
|
truncated: result.truncated,
|
|
@@ -184,16 +249,24 @@ export function createCommandCoordinator(opts) {
|
|
|
184
249
|
...(decision.script ? { script: { name: decision.script.name, text: decision.script.text.slice(0, 500) } } : {}),
|
|
185
250
|
output: result.output
|
|
186
251
|
});
|
|
187
|
-
await
|
|
252
|
+
await submitOnce({ tool_call_id: boundCall.tool_call_id, ok: true, result: payload, duration_ms: Date.now() - started });
|
|
188
253
|
});
|
|
189
254
|
}
|
|
190
255
|
return {
|
|
191
256
|
handle(call) {
|
|
257
|
+
// A repeated id is the same call: it is reviewed and run at most once.
|
|
258
|
+
if (seen.has(call.tool_call_id))
|
|
259
|
+
return Promise.resolve();
|
|
260
|
+
seen.add(call.tool_call_id);
|
|
261
|
+
const identity = structuredClone(call);
|
|
192
262
|
const next = chain.then(() => process(call)).catch(async (err) => {
|
|
263
|
+
// Already answered (e.g. its delivery failed): surface that, never a second result.
|
|
264
|
+
if (answered.has(identity.tool_call_id))
|
|
265
|
+
throw err;
|
|
193
266
|
// A bug here must still answer the call, never leave the turn waiting.
|
|
194
|
-
await fail(
|
|
267
|
+
await fail(identity, Date.now(), "START_FAILED", err?.message ?? "The command could not be processed.").catch(() => undefined);
|
|
195
268
|
});
|
|
196
|
-
chain = next;
|
|
269
|
+
chain = next.catch(() => undefined);
|
|
197
270
|
return next;
|
|
198
271
|
}
|
|
199
272
|
};
|
|
@@ -2,6 +2,7 @@ import fs from "node:fs";
|
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { isInside } from "./local-files.js";
|
|
4
4
|
import { MAX_TIMEOUT_MS, RunnerError, resolveCwd } from "./process-runner.js";
|
|
5
|
+
import { GIT_NO_HOOKS_PATH } from "./workspace.js";
|
|
5
6
|
export class PolicyError extends Error {
|
|
6
7
|
code;
|
|
7
8
|
constructor(code, message) {
|
|
@@ -44,7 +45,6 @@ const KNOWN_DANGEROUS = {
|
|
|
44
45
|
ruby: "an interpreter",
|
|
45
46
|
perl: "an interpreter",
|
|
46
47
|
deno: "an interpreter",
|
|
47
|
-
bun: "an interpreter",
|
|
48
48
|
npx: "a remote package runner",
|
|
49
49
|
curl: "a network tool",
|
|
50
50
|
wget: "a network tool",
|
|
@@ -128,7 +128,7 @@ function timeoutFor(tier, requested) {
|
|
|
128
128
|
}
|
|
129
129
|
// ── git ──────────────────────────────────────────────────────────────────────
|
|
130
130
|
/** Global hardening, placed before the subcommand. */
|
|
131
|
-
const GIT_GLOBAL = ["--no-pager", "-c", "core.fsmonitor=false", "-c",
|
|
131
|
+
const GIT_GLOBAL = ["--no-pager", "-c", "core.fsmonitor=false", "-c", `core.hooksPath=${GIT_NO_HOOKS_PATH}`, "-c", "diff.external="];
|
|
132
132
|
/** Never allowed in any git invocation: each reads or writes outside the command's intent. */
|
|
133
133
|
const GIT_FORBIDDEN = /^(-c|-C|--git-dir|--work-tree|--exec-path|--namespace|--super-prefix|--config-env|--output|--ext-diff|--textconv|--no-index|--upload-pack|--receive-pack|--open-files-in-pager|-O)(=|$)/;
|
|
134
134
|
const GIT_FLAGS = {
|
|
@@ -226,7 +226,8 @@ function nearestPackageJson(cwdAbs, root) {
|
|
|
226
226
|
catch {
|
|
227
227
|
/* none or unreadable here */
|
|
228
228
|
}
|
|
229
|
-
|
|
229
|
+
// The platform's own path comparison (case-insensitive only on Windows), as isInside.
|
|
230
|
+
if (path.relative(path.resolve(root), path.resolve(dir)) === "")
|
|
230
231
|
return null;
|
|
231
232
|
const parent = path.dirname(dir);
|
|
232
233
|
if (parent === dir || !isInside(root, parent))
|
|
@@ -378,6 +379,8 @@ export function evaluateCommand(proposal, root) {
|
|
|
378
379
|
}
|
|
379
380
|
throw err;
|
|
380
381
|
}
|
|
382
|
+
// resolveCwd returns a real path; compare positional paths against the same root.
|
|
383
|
+
root = fs.realpathSync.native(root);
|
|
381
384
|
const cwdRelative = path.relative(fs.realpathSync.native(root), cwdAbsolute).split(path.sep).join("/") || ".";
|
|
382
385
|
let partial;
|
|
383
386
|
switch (name) {
|
|
@@ -392,8 +395,35 @@ export function evaluateCommand(proposal, root) {
|
|
|
392
395
|
case "yarn":
|
|
393
396
|
partial = evaluatePackageManager(name, args, cwdAbsolute, root);
|
|
394
397
|
break;
|
|
398
|
+
case "bun":
|
|
399
|
+
case "pytest":
|
|
400
|
+
case "go":
|
|
401
|
+
case "cargo": {
|
|
402
|
+
const version = args.length === 1 && args[0] === (name === "go" ? "version" : "--version");
|
|
403
|
+
const expected = name === "pytest" ? [] : name === "go" ? ["test", "./..."] : ["test"];
|
|
404
|
+
// No eval, arbitrary scripts, flags, install/publish or external paths.
|
|
405
|
+
if (!version && JSON.stringify(args) !== JSON.stringify(expected))
|
|
406
|
+
return deny(`${name} may only run its project tests or its version query.`);
|
|
407
|
+
const markers = name === "go" ? ["go.mod"] : name === "cargo" ? ["Cargo.toml"] : name === "bun" ? ["package.json"] : ["pyproject.toml", "pytest.ini", "setup.cfg", "setup.py"];
|
|
408
|
+
if (!version && !markers.some(file => {
|
|
409
|
+
// Same canonical form as root (realpathSync.native): 8.3, subst and mapped
|
|
410
|
+
// drives resolve alike, and a marker that links out still fails.
|
|
411
|
+
try {
|
|
412
|
+
const real = fs.realpathSync.native(path.join(cwdAbsolute, file));
|
|
413
|
+
return isInside(root, real) && fs.statSync(real).isFile();
|
|
414
|
+
}
|
|
415
|
+
catch {
|
|
416
|
+
return false;
|
|
417
|
+
}
|
|
418
|
+
}))
|
|
419
|
+
return deny(`${name} requires project configuration in the selected working directory.`);
|
|
420
|
+
partial = { tier: version ? "R0" : "R1", program: name, args, effectiveArgs: args,
|
|
421
|
+
network: version ? "none-expected" : "project-code-may-use-network",
|
|
422
|
+
notes: version ? [] : ["Runs project tests, including project-defined configuration and plugins."] };
|
|
423
|
+
break;
|
|
424
|
+
}
|
|
395
425
|
default:
|
|
396
|
-
return deny(`${program} is not in the allowed command set (git, node, npm, pnpm, yarn).`);
|
|
426
|
+
return deny(`${program} is not in the allowed command set (git, node, npm, pnpm, yarn, bun, pytest, go, cargo).`);
|
|
397
427
|
}
|
|
398
428
|
const notes = partial.tier === "R0" ? partial.notes : [...partial.notes, PROJECT_CODE_NOTE];
|
|
399
429
|
return { ...partial, notes, cwdRelative, cwdAbsolute, timeoutMs: timeoutFor(partial.tier, proposal.timeout_ms) };
|
package/dist/services/config.js
CHANGED
|
@@ -2,7 +2,7 @@ import crypto from "node:crypto";
|
|
|
2
2
|
import fs from "node:fs";
|
|
3
3
|
import os from "node:os";
|
|
4
4
|
import path from "node:path";
|
|
5
|
-
import { SealError, isSealed, seal, sealingAvailable, unseal } from "./secure-store.js";
|
|
5
|
+
import { SealError, isSealed, seal, sealingAvailable, sealingRequired, sealingUnavailableError, unseal } from "./secure-store.js";
|
|
6
6
|
/**
|
|
7
7
|
* A URL is safe to send credentials to only over HTTPS, or over HTTP to a
|
|
8
8
|
* loopback host (local dev). Anything else (a plain-HTTP remote host) would send
|
|
@@ -40,10 +40,13 @@ export function sameApiOrigin(a, b) {
|
|
|
40
40
|
if (!a || !b)
|
|
41
41
|
return false;
|
|
42
42
|
try {
|
|
43
|
-
|
|
43
|
+
const left = new URL(a);
|
|
44
|
+
const right = new URL(b);
|
|
45
|
+
return ["http:", "https:"].includes(left.protocol) &&
|
|
46
|
+
["http:", "https:"].includes(right.protocol) && left.origin === right.origin;
|
|
44
47
|
}
|
|
45
48
|
catch {
|
|
46
|
-
return
|
|
49
|
+
return false;
|
|
47
50
|
}
|
|
48
51
|
}
|
|
49
52
|
/**
|
|
@@ -64,11 +67,52 @@ export function sameApiOrigin(a, b) {
|
|
|
64
67
|
* removed only when a caller asks for it to be removed, which is why logout
|
|
65
68
|
* still works and why nothing else can take `auth` with it.
|
|
66
69
|
*/
|
|
70
|
+
export class ConfigReadError extends Error {
|
|
71
|
+
code = "CONFIG_UNREADABLE";
|
|
72
|
+
constructor() {
|
|
73
|
+
super("Saved configuration is unreadable or invalid. No configuration was overwritten. Back up config.json, then repair it or explicitly move it aside before restarting.");
|
|
74
|
+
this.name = "ConfigReadError";
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/** Reject malformed known fields; preserve unknown fields for forward compatibility. */
|
|
78
|
+
function validateConfig(value) {
|
|
79
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
80
|
+
throw new ConfigReadError();
|
|
81
|
+
const data = value;
|
|
82
|
+
const strings = ["apiUrl", "platformUrl", "secretKey", "secretKeyApiUrl", "sessionId", "sessionSelectionToken", "sessionTitle", "mode", "model", "latestCliVersion"];
|
|
83
|
+
const booleans = ["webSearch", "fast", "highPower", "localCommandsEnabled", "projectContextPending"];
|
|
84
|
+
const arrays = ["sessionOrdinals", "memoryArtifactIds", "attachedFileIds", "trustedFolders"];
|
|
85
|
+
for (const key of strings)
|
|
86
|
+
if (data[key] !== undefined && typeof data[key] !== "string")
|
|
87
|
+
throw new ConfigReadError();
|
|
88
|
+
for (const key of booleans)
|
|
89
|
+
if (data[key] !== undefined && typeof data[key] !== "boolean")
|
|
90
|
+
throw new ConfigReadError();
|
|
91
|
+
for (const key of arrays)
|
|
92
|
+
if (data[key] !== undefined && (!Array.isArray(data[key]) || !data[key].every(v => typeof v === "string")))
|
|
93
|
+
throw new ConfigReadError();
|
|
94
|
+
for (const key of ["updateCheckAt", "updateCheckErrorAt"])
|
|
95
|
+
if (data[key] !== undefined && (typeof data[key] !== "number" || !Number.isFinite(data[key])))
|
|
96
|
+
throw new ConfigReadError();
|
|
97
|
+
if (data.chatType !== undefined && !["carrier", "standard"].includes(data.chatType))
|
|
98
|
+
throw new ConfigReadError();
|
|
99
|
+
if (data.sia !== undefined && typeof data.sia !== "boolean" && !["auto", "off"].includes(data.sia))
|
|
100
|
+
throw new ConfigReadError();
|
|
101
|
+
for (const key of ["auth", "scope", "theme"])
|
|
102
|
+
if (data[key] !== undefined && (!data[key] || typeof data[key] !== "object" || Array.isArray(data[key])))
|
|
103
|
+
throw new ConfigReadError();
|
|
104
|
+
if (data.theme && typeof data.theme.accent !== "string")
|
|
105
|
+
throw new ConfigReadError();
|
|
106
|
+
if (data.uploads !== undefined && !Array.isArray(data.uploads))
|
|
107
|
+
throw new ConfigReadError();
|
|
108
|
+
// Credential contents and issuer policy remain the existing auth layer's job.
|
|
109
|
+
}
|
|
67
110
|
export class ConfigStore {
|
|
68
111
|
dir;
|
|
69
112
|
file;
|
|
70
113
|
/** The config with credentials OPENED — what every caller reads. */
|
|
71
114
|
data;
|
|
115
|
+
options;
|
|
72
116
|
/**
|
|
73
117
|
* Why stored credentials could not be opened, when they could not: another
|
|
74
118
|
* Windows account, another machine, or a damaged blob. The CLI then behaves
|
|
@@ -76,9 +120,13 @@ export class ConfigStore {
|
|
|
76
120
|
* `cos login` is the recovery and nothing is lost by trying.
|
|
77
121
|
*/
|
|
78
122
|
credentialError = null;
|
|
79
|
-
constructor() {
|
|
123
|
+
constructor(options = {}) {
|
|
124
|
+
this.options = options;
|
|
80
125
|
this.dir = ConfigStore.resolveDir();
|
|
81
|
-
|
|
126
|
+
const fileName = options.fileName ?? "config.json";
|
|
127
|
+
if (path.basename(fileName) !== fileName || !fileName.endsWith(".json"))
|
|
128
|
+
throw new Error("Config filename must be a JSON file name.");
|
|
129
|
+
this.file = path.join(this.dir, fileName);
|
|
82
130
|
this.data = this.reveal(this.read());
|
|
83
131
|
this.protectPlaintextCredentials();
|
|
84
132
|
}
|
|
@@ -115,6 +163,12 @@ export class ConfigStore {
|
|
|
115
163
|
*/
|
|
116
164
|
conceal(patch) {
|
|
117
165
|
const canSeal = (v) => typeof v === "string" && v.length > 0 && !isSealed(v);
|
|
166
|
+
const carriesSecret = (patch.auth && (canSeal(patch.auth.accessToken) || canSeal(patch.auth.refreshToken))) || canSeal(patch.secretKey);
|
|
167
|
+
// The packaged build fails closed: a missing DPAPI helper is a damaged
|
|
168
|
+
// install, and writing the tokens in plaintext would silently drop the
|
|
169
|
+
// protection the user was promised. Nothing is written; login reports why.
|
|
170
|
+
if (carriesSecret && sealingRequired() && !sealingAvailable())
|
|
171
|
+
throw sealingUnavailableError();
|
|
118
172
|
const out = { ...patch };
|
|
119
173
|
if (patch.auth && (canSeal(patch.auth.accessToken) || canSeal(patch.auth.refreshToken))) {
|
|
120
174
|
if (sealingAvailable()) {
|
|
@@ -168,17 +222,40 @@ export class ConfigStore {
|
|
|
168
222
|
}
|
|
169
223
|
static resolveDir() {
|
|
170
224
|
const appData = process.env.APPDATA;
|
|
225
|
+
const profile = process.env.CARRIEROS_CLI_PROFILE === "staging" ? "staging" : undefined;
|
|
171
226
|
if (appData)
|
|
172
|
-
return path.join(appData, "CarrierOS");
|
|
173
|
-
return path.join(os.homedir(), ".carrieros");
|
|
227
|
+
return path.join(appData, "CarrierOS", ...(profile ? [profile] : []));
|
|
228
|
+
return path.join(os.homedir(), ".carrieros", ...(profile ? [profile] : []));
|
|
174
229
|
}
|
|
175
230
|
read() {
|
|
231
|
+
const defaults = {
|
|
232
|
+
apiUrl: this.options.fixedApiUrl ?? this.options.defaultApiUrl ?? DEFAULT_API_URL,
|
|
233
|
+
...(this.options.fixedPlatformUrl || this.options.defaultPlatformUrl
|
|
234
|
+
? { platformUrl: this.options.fixedPlatformUrl ?? this.options.defaultPlatformUrl }
|
|
235
|
+
: {})
|
|
236
|
+
};
|
|
237
|
+
let source;
|
|
238
|
+
try {
|
|
239
|
+
source = fs.readFileSync(this.file, "utf8");
|
|
240
|
+
}
|
|
241
|
+
catch (err) {
|
|
242
|
+
if (err.code === "ENOENT")
|
|
243
|
+
return defaults;
|
|
244
|
+
throw new ConfigReadError();
|
|
245
|
+
}
|
|
176
246
|
try {
|
|
177
|
-
const parsed = JSON.parse(
|
|
178
|
-
|
|
247
|
+
const parsed = JSON.parse(source);
|
|
248
|
+
validateConfig(parsed);
|
|
249
|
+
return {
|
|
250
|
+
...defaults,
|
|
251
|
+
...parsed,
|
|
252
|
+
...(this.options.fixedApiUrl ? { apiUrl: this.options.fixedApiUrl } : {}),
|
|
253
|
+
...(this.options.fixedPlatformUrl ? { platformUrl: this.options.fixedPlatformUrl } : {})
|
|
254
|
+
};
|
|
179
255
|
}
|
|
180
256
|
catch {
|
|
181
|
-
|
|
257
|
+
// Never include the parser error: its source excerpt can contain tokens.
|
|
258
|
+
throw new ConfigReadError();
|
|
182
259
|
}
|
|
183
260
|
}
|
|
184
261
|
/**
|
|
@@ -191,9 +268,15 @@ export class ConfigStore {
|
|
|
191
268
|
commit(patch, remove = []) {
|
|
192
269
|
// Merge in DISK form: what is already there stays sealed, and the patch is
|
|
193
270
|
// sealed before it joins it. Plaintext credentials never reach the file.
|
|
194
|
-
const merged = {
|
|
271
|
+
const merged = {
|
|
272
|
+
...this.read(),
|
|
273
|
+
...this.conceal(patch),
|
|
274
|
+
...(this.options.fixedApiUrl ? { apiUrl: this.options.fixedApiUrl } : {}),
|
|
275
|
+
...(this.options.fixedPlatformUrl ? { platformUrl: this.options.fixedPlatformUrl } : {})
|
|
276
|
+
};
|
|
195
277
|
for (const key of remove)
|
|
196
278
|
delete merged[key];
|
|
279
|
+
validateConfig(merged);
|
|
197
280
|
this.write(merged);
|
|
198
281
|
this.data = this.reveal(merged);
|
|
199
282
|
}
|
|
@@ -282,7 +365,9 @@ export class ConfigStore {
|
|
|
282
365
|
this.commit({}, [
|
|
283
366
|
"auth",
|
|
284
367
|
"secretKey",
|
|
368
|
+
"secretKeyApiUrl",
|
|
285
369
|
"sessionId",
|
|
370
|
+
"sessionSelectionToken",
|
|
286
371
|
"sessionTitle",
|
|
287
372
|
"sessionOrdinals",
|
|
288
373
|
"memoryArtifactIds",
|