@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
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
import { execFile, spawn } from "node:child_process";
|
|
2
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { StringDecoder } from "node:string_decoder";
|
|
6
|
+
import { promisify } from "node:util";
|
|
7
|
+
import { installedDocker } from "./supported-runtime.js";
|
|
8
|
+
import { executionContract } from "./execution-platform.js";
|
|
9
|
+
import { CONTAINER_SUPERVISOR } from "./container-supervisor.js";
|
|
10
|
+
import { FORCED_ENV, buildChildEnv } from "./env-policy.js";
|
|
11
|
+
import { isInside } from "./local-files.js";
|
|
12
|
+
import { HeadTailBuffer, MAX_TIMEOUT_MS, RunnerError, resolveCwd, validateArgs } from "./process-runner.js";
|
|
13
|
+
const exec = promisify(execFile);
|
|
14
|
+
const PROGRAMS = new Set(["node", "npm", "pnpm", "yarn", "git", "bun", "pytest", "go", "cargo"]);
|
|
15
|
+
export function runtimeHasRequiredIsolation(info) {
|
|
16
|
+
if (!info || typeof info !== "object")
|
|
17
|
+
return false;
|
|
18
|
+
const value = info;
|
|
19
|
+
return value.OSType === "linux" && Array.isArray(value.SecurityOptions) && value.SecurityOptions.some(option => typeof option === "string" && option.split(",").includes("name=seccomp") && option.split(",").includes("profile=builtin"));
|
|
20
|
+
}
|
|
21
|
+
/** Only explicit local runtime configuration. Never inherit a remote Docker context. */
|
|
22
|
+
export function containerRuntime(env = process.env) {
|
|
23
|
+
if (env.COS_COMMAND_DOCKER)
|
|
24
|
+
throw new RunnerError("INVALID_RUNTIME", "COS_COMMAND_DOCKER is no longer accepted. Remove it; the executor uses only a supported Docker CLI installation.");
|
|
25
|
+
if (env.COS_COMMAND_RUNTIME && env.COS_COMMAND_RUNTIME !== "docker-engine-v1")
|
|
26
|
+
throw new RunnerError("INVALID_RUNTIME", "Only docker-engine-v1 is supported.");
|
|
27
|
+
const socket = env.COS_COMMAND_DOCKER_SOCKET;
|
|
28
|
+
const image = env.COS_COMMAND_IMAGE;
|
|
29
|
+
if (!socket || !image) {
|
|
30
|
+
throw new RunnerError("ISOLATION_UNAVAILABLE", executionContract().prerequisite + " Configure COS_COMMAND_DOCKER_SOCKET and COS_COMMAND_IMAGE; nothing was run.");
|
|
31
|
+
}
|
|
32
|
+
if (!path.isAbsolute(socket) || !/^sha256:[a-f0-9]{64}$/.test(image)) {
|
|
33
|
+
throw new RunnerError("INVALID_RUNTIME", "The runtime requires an absolute local socket path and a local sha256 image ID.");
|
|
34
|
+
}
|
|
35
|
+
let executable;
|
|
36
|
+
try {
|
|
37
|
+
executable = installedDocker();
|
|
38
|
+
}
|
|
39
|
+
catch (error) {
|
|
40
|
+
throw new RunnerError("ISOLATION_UNAVAILABLE", error.message);
|
|
41
|
+
}
|
|
42
|
+
try {
|
|
43
|
+
if (!fs.statSync(executable).isFile() || !fs.statSync(socket).isSocket())
|
|
44
|
+
throw new Error();
|
|
45
|
+
fs.accessSync(executable, fs.constants.X_OK);
|
|
46
|
+
return { executable: fs.realpathSync(executable), socket: fs.realpathSync(socket), image };
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
throw new RunnerError("ISOLATION_UNAVAILABLE", "The configured local command runtime is unavailable.");
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/** Pure launch plan; project data cannot add mounts, privileges, a shell or a daemon endpoint. */
|
|
53
|
+
export function containerArguments(runtime, name, root, operationId) {
|
|
54
|
+
if (root.includes(",") || /[\r\n\0]/.test(root))
|
|
55
|
+
throw new RunnerError("INVALID_CWD", "This repository path cannot be safely mounted.");
|
|
56
|
+
// Daemon-owned removal survives CLI death; normal exit still verifies removal independently.
|
|
57
|
+
return ["--host", `unix://${runtime.socket}`, "run", "--rm", "--name", name,
|
|
58
|
+
"--label", "ai.carrieros.command=true",
|
|
59
|
+
...(operationId ? ["--label", `ai.carrieros.operation=${createHash("sha256").update(operationId).digest("hex")}`] : []),
|
|
60
|
+
"--pull=never", "--restart=no", "--init=false", "--read-only", "--network=none",
|
|
61
|
+
"--pids-limit=128", "--memory=1g", "--cpus=1",
|
|
62
|
+
"--cap-drop=ALL", "--cap-add=SETUID", "--cap-add=SETGID",
|
|
63
|
+
"--security-opt=no-new-privileges", "--user=0:0",
|
|
64
|
+
"--tmpfs=/tmp:rw,nosuid,nodev,size=128m", "--log-driver=none",
|
|
65
|
+
"--mount", `type=bind,source=${root},target=/workspace,bind-recursive=disabled`,
|
|
66
|
+
"-i", "--entrypoint=node", runtime.image, "-e", CONTAINER_SUPERVISOR];
|
|
67
|
+
}
|
|
68
|
+
/** A lost rm response is not proof of failure or success; query the daemon independently. */
|
|
69
|
+
export async function removeAndVerifyContainer(docker, name) {
|
|
70
|
+
try {
|
|
71
|
+
await docker(["rm", "--force", "--volumes", name]);
|
|
72
|
+
}
|
|
73
|
+
catch { /* ACK may be lost */ }
|
|
74
|
+
try {
|
|
75
|
+
return (await docker(["ps", "--all", "--quiet", "--filter", `name=^/${name}$`])).trim() === "";
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
return false;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
export async function verifyContainerRuntime(runtime) {
|
|
82
|
+
const query = async (args) => (await exec(runtime.executable, ["--host", `unix://${runtime.socket}`, ...args], {
|
|
83
|
+
env: { PATH: "/usr/bin:/bin", HOME: "/nonexistent", DOCKER_CONFIG: "/nonexistent" }, timeout: 10000, maxBuffer: 64 * 1024
|
|
84
|
+
})).stdout;
|
|
85
|
+
try {
|
|
86
|
+
const version = JSON.parse(await query(["version", "--format", "{{json .Server}}"]));
|
|
87
|
+
// bind-recursive=disabled requires modern Docker Engine; compatible wrappers are not supported.
|
|
88
|
+
if (!Array.isArray(version.Components) || !version.Components.some((c) => c.Name === "Engine") ||
|
|
89
|
+
!/^\d+\./.test(version.Version) || Number(version.Version.split(".")[0]) < 25)
|
|
90
|
+
throw new Error();
|
|
91
|
+
const info = JSON.parse(await query(["info", "--format", "{{json .}}"]));
|
|
92
|
+
if (!runtimeHasRequiredIsolation(info))
|
|
93
|
+
throw new Error();
|
|
94
|
+
if ((await query(["image", "inspect", runtime.image, "--format", "{{.Id}}"])).trim() !== runtime.image)
|
|
95
|
+
throw new Error();
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
throw new RunnerError("ISOLATION_UNAVAILABLE", "Secure command execution requires Docker Engine 25+ with Linux PID isolation, builtin seccomp and the configured local image. Start the approved runtime; no native fallback was used.");
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
function outcomeFrom(value) {
|
|
102
|
+
const data = JSON.parse(value);
|
|
103
|
+
if (!["exit", "timeout", "lease_lost", "start_failed", "not_installed"].includes(data.kind) ||
|
|
104
|
+
!(data.code === null || (Number.isInteger(data.code) && data.code >= 0 && data.code <= 255)) ||
|
|
105
|
+
!(data.signal === null || /^SIG[A-Z0-9]+$/.test(data.signal)))
|
|
106
|
+
throw new Error("invalid control result");
|
|
107
|
+
return data;
|
|
108
|
+
}
|
|
109
|
+
export async function runContainer(req) {
|
|
110
|
+
const args = validateArgs(req.args);
|
|
111
|
+
if (!PROGRAMS.has(req.program))
|
|
112
|
+
throw new RunnerError("PROGRAM_DENIED", "This program is not permitted by the isolated executor.");
|
|
113
|
+
if (!Number.isFinite(req.timeoutMs) || req.timeoutMs < 1 || req.timeoutMs > MAX_TIMEOUT_MS)
|
|
114
|
+
throw new RunnerError("INVALID_TIMEOUT", "Invalid command timeout.");
|
|
115
|
+
const cwd = resolveCwd(req.cwd, req.root);
|
|
116
|
+
// The same canonical form resolveCwd and the policy use, so cwd and arguments map consistently.
|
|
117
|
+
const root = fs.realpathSync.native(req.root);
|
|
118
|
+
const runtime = containerRuntime();
|
|
119
|
+
if (isInside(root, runtime.executable) || isInside(root, runtime.socket))
|
|
120
|
+
throw new RunnerError("INVALID_RUNTIME", "The runtime must be outside the repository.");
|
|
121
|
+
if (req.signal?.aborted)
|
|
122
|
+
throw new RunnerError("CANCELLED", "Cancelled before it started.");
|
|
123
|
+
const name = `cos-command-${randomUUID()}`;
|
|
124
|
+
const marker = `COS_CONTROL_${randomUUID()}:`;
|
|
125
|
+
const source = req.sourceEnv ?? process.env;
|
|
126
|
+
const filtered = buildChildEnv(source, root);
|
|
127
|
+
// Host HOME, PATH, config and credentials have no place in the guest.
|
|
128
|
+
const env = { ...FORCED_ENV, PATH: "/usr/local/bin:/usr/bin:/bin", HOME: "/tmp", TMPDIR: "/tmp" };
|
|
129
|
+
for (const key of ["LANG", "TZ"])
|
|
130
|
+
if (filtered.env[key])
|
|
131
|
+
env[key] = filtered.env[key];
|
|
132
|
+
const dropped = Object.keys(source).filter(key => source[key] !== undefined && !["LANG", "TZ"].includes(key)).sort();
|
|
133
|
+
const relative = path.relative(root, cwd).split(path.sep).join("/");
|
|
134
|
+
const guestCwd = relative ? `/workspace/${relative}` : "/workspace";
|
|
135
|
+
const mappedArgs = args.map(arg => {
|
|
136
|
+
if (!path.isAbsolute(arg))
|
|
137
|
+
return arg;
|
|
138
|
+
const real = fs.realpathSync.native(arg);
|
|
139
|
+
if (!isInside(root, real))
|
|
140
|
+
throw new RunnerError("OUTSIDE_WORKSPACE", "An absolute argument is outside the repository.");
|
|
141
|
+
return `/workspace/${path.relative(root, real).split(path.sep).join("/")}`;
|
|
142
|
+
});
|
|
143
|
+
// Docker client receives no user's registry/config/plugin environment.
|
|
144
|
+
const clientEnv = { PATH: "/usr/bin:/bin", HOME: "/nonexistent", DOCKER_CONFIG: "/nonexistent" };
|
|
145
|
+
const docker = async (argv) => (await exec(runtime.executable, ["--host", `unix://${runtime.socket}`, ...argv], {
|
|
146
|
+
env: clientEnv, timeout: 10000, maxBuffer: 64 * 1024
|
|
147
|
+
})).stdout;
|
|
148
|
+
// Revalidate at execution even if capability was checked before approval.
|
|
149
|
+
await verifyContainerRuntime(runtime);
|
|
150
|
+
if (req.signal?.aborted)
|
|
151
|
+
throw new RunnerError("CANCELLED", "Cancelled before it started.");
|
|
152
|
+
const started = Date.now();
|
|
153
|
+
const buffer = new HeadTailBuffer(req.headBytes ?? 16 * 1024, req.tailBytes ?? 44 * 1024);
|
|
154
|
+
const counts = { stdout: 0, stderr: 0 };
|
|
155
|
+
let outcome;
|
|
156
|
+
let controlInvalid = false;
|
|
157
|
+
let timedOut = false;
|
|
158
|
+
let cancelled = false;
|
|
159
|
+
let startError = false;
|
|
160
|
+
const child = spawn(runtime.executable, containerArguments(runtime, name, root, req.operationId), {
|
|
161
|
+
cwd: root, env: clientEnv, stdio: ["pipe", "pipe", "pipe"], shell: false
|
|
162
|
+
});
|
|
163
|
+
child.stdin.on("error", () => { });
|
|
164
|
+
const redactors = Object.fromEntries(["stdout", "stderr"].map(stream => [stream, req.redactor.stream(text => {
|
|
165
|
+
buffer.append(text);
|
|
166
|
+
req.onOutput?.(stream, text);
|
|
167
|
+
})]));
|
|
168
|
+
const outDecoder = new StringDecoder("utf8");
|
|
169
|
+
const errDecoder = new StringDecoder("utf8");
|
|
170
|
+
let errPending = "";
|
|
171
|
+
const errorText = (text, final = false) => {
|
|
172
|
+
errPending += text;
|
|
173
|
+
let at;
|
|
174
|
+
while ((at = errPending.indexOf("\n")) >= 0) {
|
|
175
|
+
const line = errPending.slice(0, at);
|
|
176
|
+
errPending = errPending.slice(at + 1);
|
|
177
|
+
if (line.startsWith(marker)) {
|
|
178
|
+
counts.stderr = Math.max(0, counts.stderr - Buffer.byteLength(line + "\n") - 1);
|
|
179
|
+
try {
|
|
180
|
+
if (outcome)
|
|
181
|
+
throw new Error();
|
|
182
|
+
outcome = outcomeFrom(line.slice(marker.length));
|
|
183
|
+
}
|
|
184
|
+
catch {
|
|
185
|
+
controlInvalid = true;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
else
|
|
189
|
+
redactors.stderr.write(line + "\n");
|
|
190
|
+
}
|
|
191
|
+
// Do not let a project grow an unbounded unterminated stderr line.
|
|
192
|
+
if (errPending.length > 8192) {
|
|
193
|
+
redactors.stderr.write(errPending.slice(0, -256));
|
|
194
|
+
errPending = errPending.slice(-256);
|
|
195
|
+
}
|
|
196
|
+
if (final) {
|
|
197
|
+
redactors.stderr.write(errPending);
|
|
198
|
+
errPending = "";
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
child.stdout.on("data", (chunk) => { counts.stdout += chunk.length; redactors.stdout.write(outDecoder.write(chunk)); });
|
|
202
|
+
child.stderr.on("data", (chunk) => { counts.stderr += chunk.length; errorText(errDecoder.write(chunk)); });
|
|
203
|
+
child.once("spawn", () => {
|
|
204
|
+
child.stdin.write(JSON.stringify({ program: req.program, args: mappedArgs, cwd: guestCwd, env,
|
|
205
|
+
uid: process.getuid?.() || 1000, gid: process.getgid?.() || 1000, timeoutMs: req.timeoutMs, marker }) + "\n");
|
|
206
|
+
req.onStart?.({ pid: child.pid, resolved: [req.program, ...args] });
|
|
207
|
+
});
|
|
208
|
+
const beat = setInterval(() => { if (!child.stdin.destroyed)
|
|
209
|
+
child.stdin.write("heartbeat\n"); }, 300);
|
|
210
|
+
const stop = () => { clearInterval(beat); child.stdin.end(); };
|
|
211
|
+
const abort = () => { cancelled = true; stop(); };
|
|
212
|
+
req.signal?.addEventListener("abort", abort, { once: true });
|
|
213
|
+
if (req.signal?.aborted)
|
|
214
|
+
abort();
|
|
215
|
+
const timer = setTimeout(() => { if (!cancelled) {
|
|
216
|
+
timedOut = true;
|
|
217
|
+
stop();
|
|
218
|
+
} }, req.timeoutMs);
|
|
219
|
+
// Transport cannot keep the host waiting forever. Cleanup is verified below.
|
|
220
|
+
const hardTimer = setTimeout(() => child.kill("SIGKILL"), req.timeoutMs + 15000);
|
|
221
|
+
await new Promise(resolve => {
|
|
222
|
+
child.once("error", () => { startError = true; resolve(); });
|
|
223
|
+
child.once("close", () => resolve());
|
|
224
|
+
});
|
|
225
|
+
clearInterval(beat);
|
|
226
|
+
clearTimeout(timer);
|
|
227
|
+
clearTimeout(hardTimer);
|
|
228
|
+
req.signal?.removeEventListener("abort", abort);
|
|
229
|
+
redactors.stdout.write(outDecoder.end());
|
|
230
|
+
errorText(errDecoder.end(), true);
|
|
231
|
+
redactors.stdout.end();
|
|
232
|
+
redactors.stderr.end();
|
|
233
|
+
const verified = await removeAndVerifyContainer(docker, name);
|
|
234
|
+
if (!verified)
|
|
235
|
+
throw new RunnerError("COMMAND_UNRESOLVED", "Isolated command cleanup could not be verified; the operation may remain active.");
|
|
236
|
+
if (!startError && outcome?.kind === "not_installed")
|
|
237
|
+
throw new RunnerError("PROGRAM_NOT_FOUND", `${req.program} is not installed in the command runtime image (COS_COMMAND_IMAGE). Use an image that includes it; nothing was run.`);
|
|
238
|
+
if (startError || outcome?.kind === "start_failed")
|
|
239
|
+
throw new RunnerError("START_FAILED", "The isolated project command could not be started.");
|
|
240
|
+
if (controlInvalid || (!outcome && !timedOut && !cancelled))
|
|
241
|
+
throw new RunnerError("COMMAND_UNRESOLVED", "The isolated command stopped without a verified execution result.");
|
|
242
|
+
timedOut ||= !cancelled && outcome?.kind === "timeout";
|
|
243
|
+
if (outcome?.kind === "lease_lost" && !timedOut && !cancelled)
|
|
244
|
+
throw new RunnerError("COMMAND_UNRESOLVED", "The isolated execution lease was lost; cleanup was verified but the command result is unknown.");
|
|
245
|
+
return {
|
|
246
|
+
exit_code: timedOut || cancelled ? null : outcome?.code ?? null,
|
|
247
|
+
signal: timedOut || cancelled ? "SIGKILL" : outcome?.signal ?? null,
|
|
248
|
+
timed_out: timedOut, cancelled: cancelled && !timedOut, tree_killed: timedOut || cancelled,
|
|
249
|
+
started_at: new Date(started).toISOString(), ended_at: new Date().toISOString(), duration_ms: Date.now() - started,
|
|
250
|
+
stdout_bytes: counts.stdout, stderr_bytes: counts.stderr, truncated: buffer.truncated,
|
|
251
|
+
output: buffer.text(), redaction_count: req.redactor.count, dropped_environment_names: dropped,
|
|
252
|
+
resolved_argv: [req.program, ...args], cwd
|
|
253
|
+
};
|
|
254
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Trusted PID 1 code, supplied by the CLI, never read from the repository.
|
|
3
|
+
* Project code runs under a different UID and cannot stop the heartbeat monitor.
|
|
4
|
+
* Exiting PID 1 tears down the PID namespace, including setsid/orphan descendants.
|
|
5
|
+
* The first input line is private control data, not inherited by project code.
|
|
6
|
+
*/
|
|
7
|
+
export const CONTAINER_SUPERVISOR = String.raw `
|
|
8
|
+
const {spawn}=require('node:child_process');
|
|
9
|
+
const readline=require('node:readline');
|
|
10
|
+
let request, child, finished=false, last=Date.now();
|
|
11
|
+
function finish(result) {
|
|
12
|
+
if(finished)return;
|
|
13
|
+
finished=true;
|
|
14
|
+
setTimeout(()=>process.exit(0),100);
|
|
15
|
+
if(request) process.stderr.write('\n'+request.marker+JSON.stringify(result)+'\n',()=>process.exit(0));
|
|
16
|
+
else process.exit(125);
|
|
17
|
+
}
|
|
18
|
+
const watchdog=setInterval(()=>{
|
|
19
|
+
if(Date.now()-last>2500) finish({kind:'lease_lost',code:null,signal:null});
|
|
20
|
+
},100);
|
|
21
|
+
const input=readline.createInterface({input:process.stdin});
|
|
22
|
+
input.on('line',line=>{
|
|
23
|
+
if(request) { if(line==='heartbeat')last=Date.now(); return; }
|
|
24
|
+
try {
|
|
25
|
+
request=JSON.parse(line);
|
|
26
|
+
if(!Number.isInteger(request.uid)||request.uid<=0||!Number.isInteger(request.gid)||request.gid<=0)throw Error();
|
|
27
|
+
last=Date.now();
|
|
28
|
+
setTimeout(()=>finish({kind:'timeout',code:null,signal:null}),request.timeoutMs);
|
|
29
|
+
child=spawn(request.program,request.args,{
|
|
30
|
+
cwd:request.cwd,env:request.env,uid:request.uid,gid:request.gid,
|
|
31
|
+
stdio:['ignore','inherit','inherit']
|
|
32
|
+
});
|
|
33
|
+
child.once('error',error=>finish({kind:error&&error.code==='ENOENT'?'not_installed':'start_failed',code:null,signal:null}));
|
|
34
|
+
child.once('exit',(code,signal)=>finish({kind:'exit',code,signal}));
|
|
35
|
+
} catch { finish({kind:'start_failed',code:null,signal:null}); }
|
|
36
|
+
});
|
|
37
|
+
input.on('close',()=>finish({kind:'lease_lost',code:null,signal:null}));
|
|
38
|
+
`;
|
package/dist/services/context.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
1
2
|
import { ApiClient, ApiError } from "./api.js";
|
|
2
3
|
import { DEFAULT_API_URL, sameApiOrigin } from "./config.js";
|
|
3
4
|
import { refreshCliSession } from "./device-auth.js";
|
|
5
|
+
import { assertCredentialOrigin } from "./auth-origin.js";
|
|
4
6
|
/**
|
|
5
7
|
* Thrown by requireAuth when no key is configured. Unlike a process.exit, this
|
|
6
8
|
* can be caught — so the interactive shell can keep running after a failed
|
|
@@ -19,8 +21,38 @@ export class AuthRequiredError extends Error {
|
|
|
19
21
|
*/
|
|
20
22
|
export class CommandContext {
|
|
21
23
|
config;
|
|
24
|
+
_sessionSelectionToken;
|
|
22
25
|
constructor(config) {
|
|
23
26
|
this.config = config;
|
|
27
|
+
this._sessionSelectionToken = config.get("sessionSelectionToken");
|
|
28
|
+
}
|
|
29
|
+
/** In-process generation for intentional changes to the shell's active chat. */
|
|
30
|
+
_sessionSelectionRevision = 0;
|
|
31
|
+
get sessionSelectionRevision() { return this._sessionSelectionRevision; }
|
|
32
|
+
get sessionSelectionToken() { return this._sessionSelectionToken; }
|
|
33
|
+
noteSessionSelectionChanged() {
|
|
34
|
+
this._sessionSelectionRevision += 1;
|
|
35
|
+
this._sessionSelectionToken = crypto.randomUUID();
|
|
36
|
+
this.config.set("sessionSelectionToken", this._sessionSelectionToken);
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Record the ID returned by a turn only if the user has not selected or
|
|
40
|
+
* cleared another conversation while that turn was running. Reload first so
|
|
41
|
+
* a separate CLI process changing the shared active conversation is respected.
|
|
42
|
+
*/
|
|
43
|
+
rememberTurnSession(id, expectedId, expectedRevision, expectedToken) {
|
|
44
|
+
this.config.reload();
|
|
45
|
+
const storedToken = this.config.get("sessionSelectionToken");
|
|
46
|
+
if (storedToken !== this._sessionSelectionToken) {
|
|
47
|
+
this._sessionSelectionToken = storedToken;
|
|
48
|
+
this._sessionSelectionRevision += 1;
|
|
49
|
+
}
|
|
50
|
+
if (this._sessionSelectionRevision !== expectedRevision || this._sessionSelectionToken !== expectedToken ||
|
|
51
|
+
storedToken !== expectedToken || this.config.get("sessionId") !== expectedId)
|
|
52
|
+
return false;
|
|
53
|
+
this.config.set("sessionId", id);
|
|
54
|
+
this.noteSessionSelectionChanged();
|
|
55
|
+
return true;
|
|
24
56
|
}
|
|
25
57
|
/** In-process mode override. The interactive shell always OPENS in the Carrier
|
|
26
58
|
* OS mode (the core persona) regardless of the persisted default; setting the
|
|
@@ -59,7 +91,8 @@ export class CommandContext {
|
|
|
59
91
|
}
|
|
60
92
|
/** A client built from current config (anonymous if not logged in). */
|
|
61
93
|
client() {
|
|
62
|
-
|
|
94
|
+
const apiUrl = this.config.get("apiUrl") ?? DEFAULT_API_URL;
|
|
95
|
+
return new ApiClient(apiUrl, this.authProvider(apiUrl));
|
|
63
96
|
}
|
|
64
97
|
/**
|
|
65
98
|
* The one refresh currently on the wire, shared by every request that needs it.
|
|
@@ -77,15 +110,31 @@ export class CommandContext {
|
|
|
77
110
|
* new provider for every client, and the coordination has to span all of them.
|
|
78
111
|
*/
|
|
79
112
|
refreshing = null;
|
|
80
|
-
/**
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
113
|
+
/** Check configured and actual destinations before exposing saved credentials. */
|
|
114
|
+
validateCredentialOrigin(destination = this.config.get("apiUrl") ?? DEFAULT_API_URL) {
|
|
115
|
+
const auth = this.config.get("auth");
|
|
116
|
+
if (!auth?.accessToken && !auth?.refreshToken && !this.config.get("secretKey"))
|
|
117
|
+
return;
|
|
118
|
+
const issuer = auth?.accessToken || auth?.refreshToken ? auth.apiUrl : this.config.get("secretKeyApiUrl");
|
|
119
|
+
assertCredentialOrigin(issuer, this.config.get("apiUrl") ?? DEFAULT_API_URL);
|
|
120
|
+
assertCredentialOrigin(issuer, destination);
|
|
121
|
+
}
|
|
122
|
+
/** Credential + silent-refresh strategy, bound to the client's API base. */
|
|
123
|
+
authProvider(apiUrl = this.config.get("apiUrl") ?? DEFAULT_API_URL) {
|
|
85
124
|
return {
|
|
86
|
-
token: (
|
|
87
|
-
|
|
88
|
-
|
|
125
|
+
token: (destination = apiUrl) => {
|
|
126
|
+
this.validateCredentialOrigin(destination);
|
|
127
|
+
const auth = this.config.get("auth");
|
|
128
|
+
if (auth?.accessToken)
|
|
129
|
+
return auth.accessToken;
|
|
130
|
+
const key = this.config.get("secretKey");
|
|
131
|
+
if (key)
|
|
132
|
+
assertCredentialOrigin(this.config.get("secretKeyApiUrl"), destination);
|
|
133
|
+
return key;
|
|
134
|
+
},
|
|
135
|
+
refresh: async (failedToken) => {
|
|
136
|
+
this.validateCredentialOrigin(apiUrl);
|
|
137
|
+
this.refreshing ??= this.renewSession(apiUrl, failedToken).finally(() => {
|
|
89
138
|
this.refreshing = null;
|
|
90
139
|
});
|
|
91
140
|
return this.refreshing;
|
|
@@ -102,16 +151,16 @@ export class CommandContext {
|
|
|
102
151
|
* and presenting it trips the server's reuse detection — which revokes every
|
|
103
152
|
* device on the account. Adopting the rotated pair avoids asking at all.
|
|
104
153
|
*/
|
|
105
|
-
async renewSession(failedToken) {
|
|
154
|
+
async renewSession(apiUrl, failedToken) {
|
|
106
155
|
this.config.reload();
|
|
107
156
|
const auth = this.config.get("auth");
|
|
108
157
|
if (!auth?.refreshToken)
|
|
109
158
|
return undefined;
|
|
159
|
+
this.validateCredentialOrigin(apiUrl);
|
|
110
160
|
// Someone already renewed since this request went out — just retry with it.
|
|
111
161
|
if (failedToken && auth.accessToken && auth.accessToken !== failedToken) {
|
|
112
162
|
return auth.accessToken;
|
|
113
163
|
}
|
|
114
|
-
const apiUrl = this.config.get("apiUrl") ?? DEFAULT_API_URL;
|
|
115
164
|
const outcome = await refreshCliSession(apiUrl, auth.refreshToken);
|
|
116
165
|
switch (outcome.kind) {
|
|
117
166
|
case "ok": {
|
|
@@ -121,9 +170,8 @@ export class CommandContext {
|
|
|
121
170
|
...auth,
|
|
122
171
|
accessToken: renewed.access_token,
|
|
123
172
|
refreshToken: renewed.refresh_token,
|
|
124
|
-
//
|
|
125
|
-
|
|
126
|
-
apiUrl: auth.apiUrl ?? apiUrl,
|
|
173
|
+
// Preserve the issuer that was validated before the exchange.
|
|
174
|
+
apiUrl: auth.apiUrl,
|
|
127
175
|
workspace: renewed.workspace ?? auth.workspace,
|
|
128
176
|
project: renewed.project ?? auth.project
|
|
129
177
|
}
|
|
@@ -141,23 +189,41 @@ export class CommandContext {
|
|
|
141
189
|
// or something the user does explicitly with `cos logout`. A refresh
|
|
142
190
|
// token the server has already revoked grants nothing, so leaving one on
|
|
143
191
|
// disk costs nothing either.
|
|
144
|
-
|
|
192
|
+
// Another CLI process may have rotated the refresh token after our
|
|
193
|
+
// preflight reload but before this server answered. Re-read before
|
|
194
|
+
// treating 401 as logout; adopt a newer pair instead of deleting it.
|
|
195
|
+
this.config.reload();
|
|
196
|
+
const latest = this.config.get("auth");
|
|
197
|
+
if (latest?.refreshToken && latest.refreshToken !== auth.refreshToken) {
|
|
198
|
+
this.validateCredentialOrigin(apiUrl);
|
|
199
|
+
return latest.accessToken;
|
|
200
|
+
}
|
|
201
|
+
// An explicit logout may also have happened while refresh was in flight.
|
|
202
|
+
// Do not clear again or erase a subsequent sign-in.
|
|
203
|
+
if (!latest?.refreshToken)
|
|
204
|
+
return undefined;
|
|
205
|
+
if (sameApiOrigin(latest.apiUrl, apiUrl)) {
|
|
206
|
+
this.noteSessionSelectionChanged();
|
|
145
207
|
this.config.clearAuth();
|
|
146
208
|
return undefined;
|
|
147
209
|
}
|
|
148
|
-
throw new ApiError("SESSION_NOT_RENEWABLE",
|
|
149
|
-
? `This session was issued by ${
|
|
150
|
-
`Point it back with \`cos login --url ${
|
|
210
|
+
throw new ApiError("SESSION_NOT_RENEWABLE", latest.apiUrl
|
|
211
|
+
? `This session was issued by ${latest.apiUrl}, but the CLI is pointed at ${apiUrl}. ` +
|
|
212
|
+
`Point it back with \`cos login --url ${latest.apiUrl}\`, or run \`cos logout\` to sign in here.`
|
|
151
213
|
: `${apiUrl} would not renew this session. If you signed out elsewhere or changed API URL, ` +
|
|
152
214
|
"run `cos logout` and sign in again.", 401);
|
|
153
215
|
case "busy": {
|
|
154
216
|
// A different process won the rotation; its tokens are about to land in
|
|
155
217
|
// the shared config. Give it a moment to write them rather than guessing.
|
|
156
|
-
const adopted = await this.awaitRotatedElsewhere(auth.refreshToken);
|
|
218
|
+
const adopted = await this.awaitRotatedElsewhere(auth.refreshToken, apiUrl);
|
|
157
219
|
if (adopted)
|
|
158
220
|
return adopted;
|
|
159
221
|
throw new ApiError("SESSION_BUSY", "Your session is being renewed by another Carrier OS window. Try again in a moment.", 409);
|
|
160
222
|
}
|
|
223
|
+
case "unsupported":
|
|
224
|
+
// Retrying cannot help: this API build has no route for the session.
|
|
225
|
+
throw new ApiError("SESSION_ENDPOINT_MISSING", `${apiUrl} can't renew Carrier OS sign-in sessions — it may be running an older API version. ` +
|
|
226
|
+
"Point Carrier OS at the API that signed you in, or run `cos logout` and sign in again.", 404);
|
|
161
227
|
case "transient":
|
|
162
228
|
// The session may be perfectly healthy — never sign someone out because
|
|
163
229
|
// the API had a bad second.
|
|
@@ -165,11 +231,12 @@ export class CommandContext {
|
|
|
165
231
|
}
|
|
166
232
|
}
|
|
167
233
|
/** Poll the shared config briefly for a refresh token rotated by another process. */
|
|
168
|
-
async awaitRotatedElsewhere(spentRefreshToken) {
|
|
234
|
+
async awaitRotatedElsewhere(spentRefreshToken, apiUrl) {
|
|
169
235
|
for (let attempt = 0; attempt < 10; attempt += 1) {
|
|
170
236
|
await new Promise((r) => setTimeout(r, 100));
|
|
171
237
|
this.config.reload();
|
|
172
238
|
const auth = this.config.get("auth");
|
|
239
|
+
this.validateCredentialOrigin(apiUrl);
|
|
173
240
|
if (auth?.refreshToken && auth.refreshToken !== spentRefreshToken && auth.accessToken) {
|
|
174
241
|
return auth.accessToken;
|
|
175
242
|
}
|
|
@@ -216,11 +283,10 @@ export class CommandContext {
|
|
|
216
283
|
setSessionMode(id) {
|
|
217
284
|
this.overrideMode = id;
|
|
218
285
|
}
|
|
219
|
-
/** Active chat experience:
|
|
220
|
-
*
|
|
221
|
-
* type survives across invocations; reset to carrier on login. */
|
|
286
|
+
/** Active chat experience: Standard by default. Persisted so an explicit
|
|
287
|
+
* choice survives across invocations; a fresh login starts in Standard. */
|
|
222
288
|
get chatType() {
|
|
223
|
-
return this.config.get("chatType") ?? "
|
|
289
|
+
return this.config.get("chatType") ?? "standard";
|
|
224
290
|
}
|
|
225
291
|
/** Switch chat type. Because a conversation's type is fixed at creation, this
|
|
226
292
|
* clears the active session so the NEXT message starts a fresh conversation of
|
|
@@ -228,6 +294,7 @@ export class CommandContext {
|
|
|
228
294
|
setChatType(type) {
|
|
229
295
|
this.config.set("chatType", type);
|
|
230
296
|
this.config.set("sessionId", undefined);
|
|
297
|
+
this.noteSessionSelectionChanged();
|
|
231
298
|
// Drop the session's mode override so the new chat type lands on its own
|
|
232
299
|
// default (carrier → General, standard → the saved mode or Auto) instead of
|
|
233
300
|
// inheriting a mode the user picked for the type they just left.
|
|
@@ -301,7 +368,10 @@ export class CommandContext {
|
|
|
301
368
|
return "auto";
|
|
302
369
|
if (stored === false)
|
|
303
370
|
return "off";
|
|
304
|
-
|
|
371
|
+
// Unset is OFF, as the web composer's toggle is. Defaulting to auto put
|
|
372
|
+
// clarifying questions in front of every coding task ("should the subtotal
|
|
373
|
+
// include discounts?") before the agent had even read the repository.
|
|
374
|
+
return stored === "auto" ? "auto" : "off";
|
|
305
375
|
}
|
|
306
376
|
/** True when a turn should ask the backend whether clarification is needed. */
|
|
307
377
|
get sia() {
|
|
@@ -318,6 +388,9 @@ export class CommandContext {
|
|
|
318
388
|
* transient region.
|
|
319
389
|
*/
|
|
320
390
|
mainTurnRunning = false;
|
|
391
|
+
/** Read-only Admin Panel Carrier Chat switch, refreshed by the shell. Null
|
|
392
|
+
* means it could not yet be verified; the send gate checks again. */
|
|
393
|
+
carrierMaintenance = null;
|
|
321
394
|
/**
|
|
322
395
|
* Credits this shell session's turns were actually debited, summed from the
|
|
323
396
|
* server's per-turn `credits_spent`. Runtime-only: "this session" means this
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import os from "node:os";
|
|
2
2
|
import axios, { isAxiosError } from "axios";
|
|
3
3
|
import { ApiError } from "./api.js";
|
|
4
|
-
import { cliVersion } from "./meta.js";
|
|
4
|
+
import { cliVersion, clientHeaders } from "./meta.js";
|
|
5
5
|
import { openUrl } from "./open-url.js";
|
|
6
6
|
import { sleep } from "./spinner.js";
|
|
7
7
|
/**
|
|
@@ -20,6 +20,21 @@ export function platformAuthBase(apiUrl) {
|
|
|
20
20
|
const origin = trimmed.replace(/\/v\d+$/i, ""); // drop a trailing /v1
|
|
21
21
|
return `${origin}/api/platform/auth`;
|
|
22
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
|
+
}
|
|
23
38
|
/** Is this URL pointing at the machine we are running on? */
|
|
24
39
|
function isLoopback(url) {
|
|
25
40
|
try {
|
|
@@ -127,9 +142,11 @@ async function envelopePost(url, body, headers) {
|
|
|
127
142
|
headers: {
|
|
128
143
|
"Content-Type": "application/json",
|
|
129
144
|
"User-Agent": cliUserAgent(),
|
|
145
|
+
...clientHeaders(),
|
|
130
146
|
...(headers ?? {})
|
|
131
147
|
},
|
|
132
148
|
timeout: 30_000,
|
|
149
|
+
maxRedirects: 0,
|
|
133
150
|
validateStatus: () => true
|
|
134
151
|
});
|
|
135
152
|
return { status: res.status, body: res.data };
|
|
@@ -170,13 +187,19 @@ async function pollOnce(authBase, deviceCode) {
|
|
|
170
187
|
}
|
|
171
188
|
/** Step 2 (loop) — poll until approved, denied, expired, or timed out. Calls
|
|
172
189
|
* `onTick` between polls so the caller can animate a spinner. */
|
|
173
|
-
export async function pollForToken(authBase, start, onTick
|
|
190
|
+
export async function pollForToken(authBase, start, onTick,
|
|
191
|
+
/** Stops polling: an approval that arrives after it is never used. */
|
|
192
|
+
signal) {
|
|
174
193
|
let intervalMs = Math.max(1, start.interval || 5) * 1000;
|
|
175
194
|
const deadline = Date.now() + Math.max(1, start.expires_in || 600) * 1000;
|
|
176
195
|
while (Date.now() < deadline) {
|
|
177
196
|
onTick?.();
|
|
178
197
|
await sleep(intervalMs);
|
|
198
|
+
if (signal?.aborted)
|
|
199
|
+
throw new ApiError("SIGN_IN_CANCELLED", "Sign-in cancelled.");
|
|
179
200
|
const outcome = await pollOnce(authBase, start.device_code);
|
|
201
|
+
if (signal?.aborted)
|
|
202
|
+
throw new ApiError("SIGN_IN_CANCELLED", "Sign-in cancelled.");
|
|
180
203
|
switch (outcome.kind) {
|
|
181
204
|
case "approved":
|
|
182
205
|
return outcome.data;
|
|
@@ -198,7 +221,7 @@ export async function pollForToken(authBase, start, onTick) {
|
|
|
198
221
|
/** Exchange a refresh token for a new session (rotation). Never clears anything
|
|
199
222
|
* itself — the caller decides, from the outcome, whether the session is over. */
|
|
200
223
|
export async function refreshCliSession(apiUrl, refreshToken) {
|
|
201
|
-
const authBase =
|
|
224
|
+
const authBase = cliSessionAuthBase(apiUrl, refreshToken);
|
|
202
225
|
const { status, body } = await envelopePost(`${authBase}/cli/refresh`, {
|
|
203
226
|
refresh_token: refreshToken
|
|
204
227
|
});
|
|
@@ -208,12 +231,14 @@ export async function refreshCliSession(apiUrl, refreshToken) {
|
|
|
208
231
|
return { kind: "dead" };
|
|
209
232
|
if (status === 409)
|
|
210
233
|
return { kind: "busy" };
|
|
234
|
+
if (status === 404)
|
|
235
|
+
return { kind: "unsupported" };
|
|
211
236
|
return { kind: "transient", status };
|
|
212
237
|
}
|
|
213
238
|
/** Best-effort server-side logout (revokes the refresh token). Never throws. */
|
|
214
239
|
export async function logoutCliSession(apiUrl, refreshToken) {
|
|
215
240
|
try {
|
|
216
|
-
await envelopePost(`${
|
|
241
|
+
await envelopePost(`${cliSessionAuthBase(apiUrl, refreshToken)}/cli/logout`, { refresh_token: refreshToken });
|
|
217
242
|
}
|
|
218
243
|
catch {
|
|
219
244
|
/* offline logout is fine — the local credentials are cleared regardless */
|
|
@@ -221,17 +246,19 @@ export async function logoutCliSession(apiUrl, refreshToken) {
|
|
|
221
246
|
}
|
|
222
247
|
// ── Authenticated /cli/* management (bearer access token, refresh-on-401) ─────
|
|
223
248
|
async function authedRequest(apiUrl, method, path, provider, body, retry = true) {
|
|
224
|
-
const
|
|
225
|
-
const
|
|
249
|
+
const token = provider.token(apiUrl);
|
|
250
|
+
const url = `${cliSessionAuthBase(apiUrl, token)}${path}`;
|
|
226
251
|
const res = await axios.request({
|
|
227
252
|
url,
|
|
228
253
|
method,
|
|
229
254
|
data: body,
|
|
230
255
|
headers: {
|
|
231
256
|
"Content-Type": "application/json",
|
|
257
|
+
...clientHeaders(),
|
|
232
258
|
...(token ? { Authorization: `Bearer ${token}` } : {})
|
|
233
259
|
},
|
|
234
260
|
timeout: 30_000,
|
|
261
|
+
maxRedirects: 0,
|
|
235
262
|
validateStatus: () => true
|
|
236
263
|
});
|
|
237
264
|
if (res.status === 401 && retry && provider.refresh) {
|