@carrieros/cli 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +34 -13
- package/dist/commands/chat.js +3 -3
- package/dist/commands/context.js +40 -0
- package/dist/commands/doctor.js +27 -12
- package/dist/commands/logout.js +1 -0
- package/dist/commands/permissions.js +77 -0
- package/dist/commands/scope.js +9 -6
- package/dist/commands/sessions.js +5 -0
- package/dist/commands/settings.js +8 -1
- package/dist/commands/update.js +79 -9
- package/dist/commands/usage.js +5 -5
- package/dist/commands/whoami.js +12 -9
- package/dist/ide/editor-context.js +115 -12
- package/dist/ide/ide-session.js +274 -13
- package/dist/ide/tool-host.js +2 -2
- package/dist/main.js +0 -0
- package/dist/services/api.js +178 -12
- package/dist/services/auth-origin.js +20 -0
- package/dist/services/chat-stream.js +26 -3
- package/dist/services/checkpoints.js +176 -14
- package/dist/services/client-tools.js +113 -21
- 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 +67 -5
- package/dist/services/container-runner.js +254 -0
- package/dist/services/container-supervisor.js +38 -0
- package/dist/services/context.js +45 -17
- package/dist/services/device-auth.js +30 -5
- 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 +43 -12
- 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 +60 -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 +5 -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 +37 -12
- package/dist/services/workspace-registry.js +4 -3
- package/dist/services/workspace.js +8 -1
- package/dist/shell/shell-chat.js +299 -32
- package/dist/shell/shell-commands.js +46 -4
- package/dist/shell/shell-prompt.js +21 -11
- package/dist/shell/shell-renderer.js +1 -1
- package/dist/shell/shell.js +69 -7
- 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 +9 -2
- 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 +8 -5
|
@@ -0,0 +1,403 @@
|
|
|
1
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
2
|
+
import crypto from "node:crypto";
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { cliVersion } from "./meta.js";
|
|
7
|
+
import { RELEASE_MANIFEST_URL } from "./packaged.js";
|
|
8
|
+
import { compareVersions, isVersionLike } from "./update.js";
|
|
9
|
+
/**
|
|
10
|
+
* Self-update for the packaged Windows build (cos.exe installed by the Inno
|
|
11
|
+
* Setup installer). The npm path in update.ts is untouched.
|
|
12
|
+
*
|
|
13
|
+
* The trust chain, in order — each step refuses rather than guesses:
|
|
14
|
+
*
|
|
15
|
+
* 1. The release manifest comes from RELEASE_MANIFEST_URL over HTTPS. Its
|
|
16
|
+
* artifact URL must be on the SAME origin, so a manifest can never point
|
|
17
|
+
* an update at another host.
|
|
18
|
+
* 2. The version must be well-formed and newer than this one (no downgrade).
|
|
19
|
+
* 3. The installer is streamed to `<name>.partial` under the user's updates
|
|
20
|
+
* directory, hashed as it arrives, and capped at the manifest's size. It is
|
|
21
|
+
* renamed to its final name only when size AND sha256 match — so an
|
|
22
|
+
* interrupted or corrupted download never leaves a runnable file.
|
|
23
|
+
* 4. A signed release build additionally requires a valid Authenticode
|
|
24
|
+
* signature whose signer matches the running cos.exe's own signer, and it
|
|
25
|
+
* refuses an installer the manifest marks unsigned.
|
|
26
|
+
* 5. Replacement is done by the installer, never by this process: it is
|
|
27
|
+
* started detached with this PID, waits for cos.exe to exit, then
|
|
28
|
+
* installs over the existing copy. Inno Setup rolls back an install that
|
|
29
|
+
* fails part-way, so a failed update leaves the old version in place.
|
|
30
|
+
*
|
|
31
|
+
* Nothing here deletes or rewrites configuration: config and credentials live
|
|
32
|
+
* in %APPDATA%\CarrierOS, outside the install directory the installer owns.
|
|
33
|
+
*/
|
|
34
|
+
export const MAX_MANIFEST_BYTES = 64 * 1024;
|
|
35
|
+
export const MAX_INSTALLER_BYTES = 512 * 1024 * 1024;
|
|
36
|
+
const MANIFEST_TIMEOUT_MS = 15_000;
|
|
37
|
+
const DOWNLOAD_IDLE_TIMEOUT_MS = 60_000;
|
|
38
|
+
export class UpdateError extends Error {
|
|
39
|
+
code;
|
|
40
|
+
constructor(code, message) {
|
|
41
|
+
super(message);
|
|
42
|
+
this.code = code;
|
|
43
|
+
this.name = "UpdateError";
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
const LOOPBACK = new Set(["127.0.0.1", "localhost", "[::1]", "::1"]);
|
|
47
|
+
/**
|
|
48
|
+
* The manifest URL: the baked HTTPS constant, or COS_UPDATE_MANIFEST_URL for
|
|
49
|
+
* a staging channel or the acceptance harness. An override must itself be
|
|
50
|
+
* HTTPS, or plain HTTP on loopback only (a local test server).
|
|
51
|
+
*/
|
|
52
|
+
export function manifestUrl(env = process.env) {
|
|
53
|
+
const raw = env.COS_UPDATE_MANIFEST_URL?.trim();
|
|
54
|
+
if (!raw)
|
|
55
|
+
return RELEASE_MANIFEST_URL;
|
|
56
|
+
let u;
|
|
57
|
+
try {
|
|
58
|
+
u = new URL(raw);
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
throw new UpdateError("BAD_URL", "COS_UPDATE_MANIFEST_URL is not a valid URL.");
|
|
62
|
+
}
|
|
63
|
+
if (u.protocol === "https:" || (u.protocol === "http:" && LOOPBACK.has(u.hostname)))
|
|
64
|
+
return u.toString();
|
|
65
|
+
throw new UpdateError("BAD_URL", "COS_UPDATE_MANIFEST_URL must be https:// (or http:// on localhost).");
|
|
66
|
+
}
|
|
67
|
+
/** Deterministic artifact names; the manifest must agree with them. */
|
|
68
|
+
export function artifactFileName(key, version, signed) {
|
|
69
|
+
const suffix = signed ? "" : "-UNSIGNED";
|
|
70
|
+
return key === "win-x64-setup"
|
|
71
|
+
? `CarrierOS-Setup-${version}-x64${suffix}.exe`
|
|
72
|
+
: `cos-${version}-win-x64${suffix}.zip`;
|
|
73
|
+
}
|
|
74
|
+
function isObject(v) {
|
|
75
|
+
return !!v && typeof v === "object" && !Array.isArray(v);
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Validate a release manifest fetched from `fromUrl`. Throws BAD_MANIFEST with
|
|
79
|
+
* the first problem found; returns a manifest whose every field was checked.
|
|
80
|
+
*/
|
|
81
|
+
export function parseReleaseManifest(raw, fromUrl) {
|
|
82
|
+
const bad = (why) => {
|
|
83
|
+
throw new UpdateError("BAD_MANIFEST", `The release manifest is invalid: ${why}.`);
|
|
84
|
+
};
|
|
85
|
+
if (!isObject(raw))
|
|
86
|
+
return bad("not an object");
|
|
87
|
+
if (raw.schema !== 1)
|
|
88
|
+
bad("unsupported schema");
|
|
89
|
+
if (raw.product !== "carrieros-cli")
|
|
90
|
+
bad("wrong product");
|
|
91
|
+
const version = typeof raw.version === "string" ? raw.version.trim() : "";
|
|
92
|
+
if (!isVersionLike(version))
|
|
93
|
+
bad("malformed version");
|
|
94
|
+
if (!isObject(raw.artifacts))
|
|
95
|
+
return bad("no artifacts");
|
|
96
|
+
const origin = new URL(fromUrl).origin;
|
|
97
|
+
const artifacts = {};
|
|
98
|
+
for (const key of ["win-x64-setup", "win-x64-zip"]) {
|
|
99
|
+
const a = raw.artifacts[key];
|
|
100
|
+
if (a === undefined)
|
|
101
|
+
continue;
|
|
102
|
+
if (!isObject(a))
|
|
103
|
+
bad(`${key} is not an object`);
|
|
104
|
+
const art = a;
|
|
105
|
+
const signed = art.signed === true;
|
|
106
|
+
if (art.file !== artifactFileName(key, version, signed))
|
|
107
|
+
bad(`${key} file name does not match its version`);
|
|
108
|
+
if (typeof art.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(art.sha256))
|
|
109
|
+
bad(`${key} sha256 is malformed`);
|
|
110
|
+
if (typeof art.size !== "number" || !Number.isInteger(art.size) || art.size <= 0 || art.size > MAX_INSTALLER_BYTES) {
|
|
111
|
+
bad(`${key} size is out of range`);
|
|
112
|
+
}
|
|
113
|
+
let url;
|
|
114
|
+
try {
|
|
115
|
+
url = new URL(String(art.url), fromUrl);
|
|
116
|
+
}
|
|
117
|
+
catch {
|
|
118
|
+
return bad(`${key} url is malformed`);
|
|
119
|
+
}
|
|
120
|
+
if (url.origin !== origin)
|
|
121
|
+
bad(`${key} is not hosted on the manifest's own site`);
|
|
122
|
+
if (url.protocol !== "https:" && !(url.protocol === "http:" && LOOPBACK.has(url.hostname)))
|
|
123
|
+
bad(`${key} is not HTTPS`);
|
|
124
|
+
artifacts[key] = {
|
|
125
|
+
file: art.file,
|
|
126
|
+
url: url.toString(),
|
|
127
|
+
sha256: art.sha256,
|
|
128
|
+
size: art.size,
|
|
129
|
+
signed
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
if (!artifacts["win-x64-setup"])
|
|
133
|
+
bad("no Windows installer");
|
|
134
|
+
return {
|
|
135
|
+
schema: 1,
|
|
136
|
+
product: "carrieros-cli",
|
|
137
|
+
version,
|
|
138
|
+
released: typeof raw.released === "string" ? raw.released : undefined,
|
|
139
|
+
notes: typeof raw.notes === "string" ? raw.notes.slice(0, 2000) : undefined,
|
|
140
|
+
artifacts
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
async function readCapped(res, cap) {
|
|
144
|
+
const declared = Number(res.headers.get("content-length") || 0);
|
|
145
|
+
if (declared > cap)
|
|
146
|
+
throw new UpdateError("BAD_MANIFEST", "The release manifest is too large.");
|
|
147
|
+
const buf = Buffer.from(await res.arrayBuffer());
|
|
148
|
+
if (buf.length > cap)
|
|
149
|
+
throw new UpdateError("BAD_MANIFEST", "The release manifest is too large.");
|
|
150
|
+
return buf;
|
|
151
|
+
}
|
|
152
|
+
export async function fetchReleaseManifest(url = manifestUrl(), fetchImpl = fetch) {
|
|
153
|
+
let res;
|
|
154
|
+
try {
|
|
155
|
+
res = await fetchImpl(url, {
|
|
156
|
+
redirect: "error",
|
|
157
|
+
signal: AbortSignal.timeout(MANIFEST_TIMEOUT_MS),
|
|
158
|
+
headers: { accept: "application/json", "cache-control": "no-cache" }
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
catch (err) {
|
|
162
|
+
throw new UpdateError("UNREACHABLE", `Could not reach the update server (${err.message}).`);
|
|
163
|
+
}
|
|
164
|
+
if (!res.ok)
|
|
165
|
+
throw new UpdateError("UNREACHABLE", `The update server answered HTTP ${res.status}.`);
|
|
166
|
+
const body = await readCapped(res, MAX_MANIFEST_BYTES);
|
|
167
|
+
let json;
|
|
168
|
+
try {
|
|
169
|
+
json = JSON.parse(body.toString("utf8"));
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
throw new UpdateError("BAD_MANIFEST", "The release manifest is not valid JSON.");
|
|
173
|
+
}
|
|
174
|
+
return parseReleaseManifest(json, url);
|
|
175
|
+
}
|
|
176
|
+
export async function checkPackagedUpdate(current = cliVersion(), fetchImpl = fetch, env = process.env) {
|
|
177
|
+
let manifest;
|
|
178
|
+
try {
|
|
179
|
+
manifest = await fetchReleaseManifest(manifestUrl(env), fetchImpl);
|
|
180
|
+
}
|
|
181
|
+
catch (err) {
|
|
182
|
+
return { kind: "unreachable", current, detail: err.message };
|
|
183
|
+
}
|
|
184
|
+
const cmp = compareVersions(current, manifest.version);
|
|
185
|
+
if (cmp === 0)
|
|
186
|
+
return { kind: "current", current, latest: manifest.version };
|
|
187
|
+
if (cmp > 0)
|
|
188
|
+
return { kind: "ahead", current, latest: manifest.version };
|
|
189
|
+
return { kind: "available", current, latest: manifest.version, manifest };
|
|
190
|
+
}
|
|
191
|
+
/** Per-user download directory; never the install directory. */
|
|
192
|
+
export function updatesDir(env = process.env) {
|
|
193
|
+
return env.LOCALAPPDATA
|
|
194
|
+
? path.join(env.LOCALAPPDATA, "CarrierOS", "updates")
|
|
195
|
+
: path.join(os.homedir(), ".carrieros", "updates");
|
|
196
|
+
}
|
|
197
|
+
export function sha256OfFile(file) {
|
|
198
|
+
return crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex");
|
|
199
|
+
}
|
|
200
|
+
/** Remove leftovers from interrupted or superseded downloads. */
|
|
201
|
+
export function cleanupDownloads(dir, keep) {
|
|
202
|
+
let names;
|
|
203
|
+
try {
|
|
204
|
+
names = fs.readdirSync(dir);
|
|
205
|
+
}
|
|
206
|
+
catch {
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
for (const name of names) {
|
|
210
|
+
if (name === keep)
|
|
211
|
+
continue;
|
|
212
|
+
if (/^CarrierOS-Setup-.*\.exe(\.partial)?$/.test(name)) {
|
|
213
|
+
try {
|
|
214
|
+
fs.rmSync(path.join(dir, name), { force: true });
|
|
215
|
+
}
|
|
216
|
+
catch {
|
|
217
|
+
/* in use or already gone */
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* Download `artifact` into `dir` and verify it. Returns the path of a file
|
|
224
|
+
* whose size and sha256 match the manifest; anything else throws and leaves no
|
|
225
|
+
* file behind under the final name.
|
|
226
|
+
*/
|
|
227
|
+
export async function downloadVerified(artifact, dir, opts = {}) {
|
|
228
|
+
const fetchImpl = opts.fetchImpl ?? fetch;
|
|
229
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
230
|
+
const final = path.join(dir, artifact.file);
|
|
231
|
+
cleanupDownloads(dir, artifact.file);
|
|
232
|
+
// A complete, verified copy from an earlier attempt is reused.
|
|
233
|
+
try {
|
|
234
|
+
if (fs.statSync(final).size === artifact.size && sha256OfFile(final) === artifact.sha256)
|
|
235
|
+
return final;
|
|
236
|
+
fs.rmSync(final, { force: true });
|
|
237
|
+
}
|
|
238
|
+
catch {
|
|
239
|
+
/* not there */
|
|
240
|
+
}
|
|
241
|
+
const partial = `${final}.partial`;
|
|
242
|
+
const idle = new AbortController();
|
|
243
|
+
let idleTimer;
|
|
244
|
+
const touch = () => {
|
|
245
|
+
if (idleTimer)
|
|
246
|
+
clearTimeout(idleTimer);
|
|
247
|
+
idleTimer = setTimeout(() => idle.abort(), DOWNLOAD_IDLE_TIMEOUT_MS);
|
|
248
|
+
};
|
|
249
|
+
const signal = opts.signal ? AbortSignal.any([opts.signal, idle.signal]) : idle.signal;
|
|
250
|
+
const hash = crypto.createHash("sha256");
|
|
251
|
+
let received = 0;
|
|
252
|
+
let fd = null;
|
|
253
|
+
try {
|
|
254
|
+
touch();
|
|
255
|
+
let res;
|
|
256
|
+
try {
|
|
257
|
+
res = await fetchImpl(artifact.url, { redirect: "error", signal });
|
|
258
|
+
}
|
|
259
|
+
catch (err) {
|
|
260
|
+
throw opts.signal?.aborted
|
|
261
|
+
? new UpdateError("CANCELLED", "Update cancelled.")
|
|
262
|
+
: new UpdateError("DOWNLOAD_FAILED", `Download failed (${err.message}).`);
|
|
263
|
+
}
|
|
264
|
+
if (!res.ok || !res.body)
|
|
265
|
+
throw new UpdateError("DOWNLOAD_FAILED", `Download failed (HTTP ${res.status}).`);
|
|
266
|
+
fd = fs.openSync(partial, "w", 0o600);
|
|
267
|
+
const reader = res.body.getReader();
|
|
268
|
+
for (;;) {
|
|
269
|
+
let chunk;
|
|
270
|
+
try {
|
|
271
|
+
chunk = await reader.read();
|
|
272
|
+
}
|
|
273
|
+
catch (err) {
|
|
274
|
+
throw opts.signal?.aborted
|
|
275
|
+
? new UpdateError("CANCELLED", "Update cancelled.")
|
|
276
|
+
: new UpdateError("DOWNLOAD_FAILED", `Download interrupted (${err.message}).`);
|
|
277
|
+
}
|
|
278
|
+
if (chunk.done || !chunk.value)
|
|
279
|
+
break;
|
|
280
|
+
touch();
|
|
281
|
+
received += chunk.value.length;
|
|
282
|
+
if (received > artifact.size) {
|
|
283
|
+
await reader.cancel().catch(() => undefined);
|
|
284
|
+
throw new UpdateError("SIZE_MISMATCH", "The download is larger than the release manifest declares.");
|
|
285
|
+
}
|
|
286
|
+
hash.update(chunk.value);
|
|
287
|
+
fs.writeSync(fd, chunk.value);
|
|
288
|
+
opts.onProgress?.(received, artifact.size);
|
|
289
|
+
}
|
|
290
|
+
fs.fsyncSync(fd);
|
|
291
|
+
fs.closeSync(fd);
|
|
292
|
+
fd = null;
|
|
293
|
+
if (received !== artifact.size) {
|
|
294
|
+
throw new UpdateError("SIZE_MISMATCH", "The download is incomplete.");
|
|
295
|
+
}
|
|
296
|
+
if (hash.digest("hex") !== artifact.sha256) {
|
|
297
|
+
throw new UpdateError("CHECKSUM_MISMATCH", "The download does not match the published checksum.");
|
|
298
|
+
}
|
|
299
|
+
fs.renameSync(partial, final);
|
|
300
|
+
return final;
|
|
301
|
+
}
|
|
302
|
+
finally {
|
|
303
|
+
if (idleTimer)
|
|
304
|
+
clearTimeout(idleTimer);
|
|
305
|
+
if (fd !== null) {
|
|
306
|
+
try {
|
|
307
|
+
fs.closeSync(fd);
|
|
308
|
+
}
|
|
309
|
+
catch {
|
|
310
|
+
/* already closed */
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
fs.rmSync(partial, { force: true });
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
const POWERSHELL = () => path.join(process.env.SystemRoot || "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
|
|
317
|
+
/**
|
|
318
|
+
* Authenticode status of a file, via PowerShell's Get-AuthenticodeSignature.
|
|
319
|
+
* The path travels in an environment variable, never in the command text.
|
|
320
|
+
*/
|
|
321
|
+
export function authenticodeSignature(file) {
|
|
322
|
+
if (process.platform !== "win32")
|
|
323
|
+
return { status: "UnsupportedPlatform", subject: null };
|
|
324
|
+
const script = "$s = Get-AuthenticodeSignature -LiteralPath $env:COS_SIGNED_FILE; " +
|
|
325
|
+
"[Console]::Out.Write(($s.Status.ToString()) + \"`n\" + ($(if ($s.SignerCertificate) { $s.SignerCertificate.Subject } else { '' })))";
|
|
326
|
+
const res = spawnSync(POWERSHELL(), ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", script], {
|
|
327
|
+
env: { ...process.env, COS_SIGNED_FILE: file },
|
|
328
|
+
encoding: "utf8",
|
|
329
|
+
windowsHide: true,
|
|
330
|
+
timeout: 30_000
|
|
331
|
+
});
|
|
332
|
+
if (res.status !== 0)
|
|
333
|
+
return { status: "VerificationFailed", subject: null };
|
|
334
|
+
const [status = "Unknown", subject = ""] = String(res.stdout || "").split("\n");
|
|
335
|
+
return { status: status.trim(), subject: subject.trim() || null };
|
|
336
|
+
}
|
|
337
|
+
/**
|
|
338
|
+
* The signature gate. A signed build requires a valid signature from the same
|
|
339
|
+
* publisher as itself; an unsigned build (development, pre-certificate)
|
|
340
|
+
* accepts what the checksum already verified, and says so.
|
|
341
|
+
*/
|
|
342
|
+
export function checkInstallerSignature(installer, artifact, signedBuild, inspect = authenticodeSignature, self = process.execPath) {
|
|
343
|
+
if (!signedBuild)
|
|
344
|
+
return { verified: false };
|
|
345
|
+
if (!artifact.signed) {
|
|
346
|
+
throw new UpdateError("UNSIGNED", "This update is not signed, and a signed installation only accepts signed updates.");
|
|
347
|
+
}
|
|
348
|
+
const got = inspect(installer);
|
|
349
|
+
const mine = inspect(self);
|
|
350
|
+
if (got.status !== "Valid" || !got.subject) {
|
|
351
|
+
throw new UpdateError("SIGNATURE_INVALID", `The update's signature is not valid (${got.status}).`);
|
|
352
|
+
}
|
|
353
|
+
if (!mine.subject || got.subject !== mine.subject) {
|
|
354
|
+
throw new UpdateError("SIGNATURE_INVALID", "The update is signed by a different publisher than this installation.");
|
|
355
|
+
}
|
|
356
|
+
return { verified: true };
|
|
357
|
+
}
|
|
358
|
+
/** Arguments for a silent, in-place upgrade that waits for this process. */
|
|
359
|
+
export function installerArgs(pid, logFile) {
|
|
360
|
+
return ["/VERYSILENT", "/SUPPRESSMSGBOXES", "/NORESTART", "/SP-", `/WAITPID=${pid}`, `/LOG=${logFile}`];
|
|
361
|
+
}
|
|
362
|
+
/**
|
|
363
|
+
* Start the verified installer detached. It waits for `pid` to exit (the
|
|
364
|
+
* installer's [Code] section) before touching cos.exe, so the caller must exit
|
|
365
|
+
* promptly after this resolves. Resolution confirms process creation, not
|
|
366
|
+
* completion of the installation.
|
|
367
|
+
*/
|
|
368
|
+
export async function launchInstaller(installer, pid = process.pid) {
|
|
369
|
+
const logFile = path.join(path.dirname(installer), `install-${Date.now()}.log`);
|
|
370
|
+
try {
|
|
371
|
+
await new Promise((resolve, reject) => {
|
|
372
|
+
const child = spawn(installer, installerArgs(pid, logFile), {
|
|
373
|
+
detached: true,
|
|
374
|
+
stdio: "ignore",
|
|
375
|
+
windowsHide: true
|
|
376
|
+
});
|
|
377
|
+
child.once("error", reject);
|
|
378
|
+
child.once("spawn", () => {
|
|
379
|
+
child.unref();
|
|
380
|
+
resolve();
|
|
381
|
+
});
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
catch (err) {
|
|
385
|
+
throw new UpdateError("LAUNCH_FAILED", `The installer could not be started (${err.message}).`);
|
|
386
|
+
}
|
|
387
|
+
return logFile;
|
|
388
|
+
}
|
|
389
|
+
/**
|
|
390
|
+
* The packaged twin of refreshUpdateCache: same cache keys, so the banner's
|
|
391
|
+
* "Update available" notice works unchanged. Asynchronous (fetch), so unlike
|
|
392
|
+
* the npm check it never blocks the shell. Failures are recorded, never shown.
|
|
393
|
+
*/
|
|
394
|
+
export async function refreshPackagedUpdateCache(cache, now = Date.now()) {
|
|
395
|
+
try {
|
|
396
|
+
const manifest = await fetchReleaseManifest();
|
|
397
|
+
cache.set("latestCliVersion", manifest.version);
|
|
398
|
+
cache.set("updateCheckAt", now);
|
|
399
|
+
}
|
|
400
|
+
catch {
|
|
401
|
+
cache.set("updateCheckErrorAt", now);
|
|
402
|
+
}
|
|
403
|
+
}
|
|
@@ -22,3 +22,18 @@ export function isPackaged() {
|
|
|
22
22
|
}
|
|
23
23
|
/** Where to point someone at a new packaged build (no npm involved). */
|
|
24
24
|
export const PACKAGED_DOWNLOAD_URL = "https://carrieros.ai/cli";
|
|
25
|
+
/**
|
|
26
|
+
* The release manifest the packaged updater reads. HTTPS on the Carrier OS
|
|
27
|
+
* site: the download page and the update channel are one place, so an
|
|
28
|
+
* installer a person downloads by hand and one `cos update` fetches are the
|
|
29
|
+
* same artifact with the same checksum.
|
|
30
|
+
*/
|
|
31
|
+
export const RELEASE_MANIFEST_URL = "https://carrieros.ai/cli/release.json";
|
|
32
|
+
/**
|
|
33
|
+
* True for a signed release build. A signed build only ever updates to a
|
|
34
|
+
* signed installer — an update must never quietly downgrade the trust a user
|
|
35
|
+
* installed with.
|
|
36
|
+
*/
|
|
37
|
+
export function isSignedRelease() {
|
|
38
|
+
return typeof __RELEASE_SIGNED__ === "boolean" && __RELEASE_SIGNED__;
|
|
39
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
export const PERMISSION_MODES = ["manual", "plan", "accept_edits", "auto"];
|
|
2
|
+
const LABELS = { manual: "Manual", plan: "Plan", accept_edits: "Accept Edits", auto: "Auto" };
|
|
3
|
+
const EXPLAIN = {
|
|
4
|
+
manual: "Every file change and every command asks for your approval.",
|
|
5
|
+
plan: "Investigate and plan only. No file changes or commands are available.",
|
|
6
|
+
accept_edits: "File changes can be applied without individual approval. Commands still require approval.",
|
|
7
|
+
auto: "File changes and test commands run without asking. A command that writes files or installs packages still asks."
|
|
8
|
+
};
|
|
9
|
+
/** Sessions whose mode is remembered for resume; older entries are dropped. */
|
|
10
|
+
const REMEMBERED = 50;
|
|
11
|
+
export const permissionModeLabel = (m) => LABELS[m];
|
|
12
|
+
export const permissionModeExplanation = (m) => EXPLAIN[m];
|
|
13
|
+
/** "accept-edits", "Accept Edits", "accept_edits", "acceptedits" → accept_edits; unknown → undefined. */
|
|
14
|
+
export function parsePermissionMode(value) {
|
|
15
|
+
const v = typeof value === "string" ? value.trim().toLowerCase().replace(/[\s-]+/g, "_") : "";
|
|
16
|
+
if (v === "acceptedits")
|
|
17
|
+
return "accept_edits";
|
|
18
|
+
return PERMISSION_MODES.includes(v) ? v : undefined;
|
|
19
|
+
}
|
|
20
|
+
/** The current mode; anything unreadable is MANUAL (fail closed). */
|
|
21
|
+
export function getPermissionMode(config) {
|
|
22
|
+
return parsePermissionMode(config.get("permissionMode")) ?? "manual";
|
|
23
|
+
}
|
|
24
|
+
/** Change the mode for this session (and remember it for resuming the active conversation). */
|
|
25
|
+
export function setPermissionMode(config, mode) {
|
|
26
|
+
config.set("permissionMode", mode);
|
|
27
|
+
rememberPermissionMode(config);
|
|
28
|
+
}
|
|
29
|
+
/** Record the current mode against the active conversation — called when a turn learns its session id. */
|
|
30
|
+
export function rememberPermissionMode(config) {
|
|
31
|
+
const sessionId = config.get("sessionId");
|
|
32
|
+
if (!sessionId)
|
|
33
|
+
return;
|
|
34
|
+
const saved = { ...(config.get("permissionModes") ?? {}) };
|
|
35
|
+
delete saved[sessionId];
|
|
36
|
+
saved[sessionId] = getPermissionMode(config);
|
|
37
|
+
const keys = Object.keys(saved);
|
|
38
|
+
for (const k of keys.slice(0, Math.max(0, keys.length - REMEMBERED)))
|
|
39
|
+
delete saved[k];
|
|
40
|
+
config.set("permissionModes", saved);
|
|
41
|
+
}
|
|
42
|
+
/** A new task: back to MANUAL. */
|
|
43
|
+
export function resetPermissionMode(config) {
|
|
44
|
+
config.set("permissionMode", "manual");
|
|
45
|
+
}
|
|
46
|
+
/** Resuming a conversation: the mode it was last used with, or MANUAL. */
|
|
47
|
+
export function restorePermissionMode(config, sessionId) {
|
|
48
|
+
const mode = parsePermissionMode((config.get("permissionModes") ?? {})[sessionId]) ?? "manual";
|
|
49
|
+
config.set("permissionMode", mode);
|
|
50
|
+
return mode;
|
|
51
|
+
}
|
|
52
|
+
/** What a mode allows, as the turn's tool policy. */
|
|
53
|
+
export function permissionPolicy(mode) {
|
|
54
|
+
return {
|
|
55
|
+
changeTools: mode !== "plan",
|
|
56
|
+
commands: mode !== "plan",
|
|
57
|
+
approveEditsByPolicy: mode === "accept_edits" || mode === "auto",
|
|
58
|
+
approveCommandByPolicy: (tier) => mode === "auto" && (tier === "R0" || tier === "R1")
|
|
59
|
+
};
|
|
60
|
+
}
|
|
@@ -5,8 +5,12 @@ import { StringDecoder } from "node:string_decoder";
|
|
|
5
5
|
import { buildChildEnv } from "./env-policy.js";
|
|
6
6
|
import { JOB_HELPER_FAILURE_EXIT, JobHelperError, ensureJobHelper } from "./job-helper.js";
|
|
7
7
|
import { isInside } from "./local-files.js";
|
|
8
|
+
import { executionAdapter, executionPlatform } from "./execution-platform.js";
|
|
9
|
+
import { runContainer } from "./container-runner.js";
|
|
8
10
|
/**
|
|
9
11
|
* Runs ONE local program, contained, bounded and redacted.
|
|
12
|
+
* Windows uses the Job Object implementation below. macOS/Linux dispatch to
|
|
13
|
+
* the isolated container adapter; neither has an unrestricted host fallback.
|
|
10
14
|
*
|
|
11
15
|
* This is the only way a command proposed by a model may ever reach the
|
|
12
16
|
* machine, and it is deliberately unaware of models, approval or policy — the
|
|
@@ -83,7 +87,7 @@ export function resolveCwd(cwd, root) {
|
|
|
83
87
|
if (typeof cwd !== "string" || !cwd.trim())
|
|
84
88
|
throw new RunnerError("INVALID_CWD", "A working directory is required.");
|
|
85
89
|
const raw = cwd.trim();
|
|
86
|
-
if (raw.includes("\0") || raw.startsWith("\\\\") || raw.split(/[\\/]+/).includes("..")) {
|
|
90
|
+
if (raw.includes("\0") || raw.startsWith("\\\\") || (/^[A-Za-z]:/.test(raw) && !path.isAbsolute(raw)) || raw.split(/[\\/]+/).includes("..")) {
|
|
87
91
|
throw new RunnerError("OUTSIDE_WORKSPACE", "The working directory must stay inside the project.");
|
|
88
92
|
}
|
|
89
93
|
const realRoot = fs.realpathSync.native(root);
|
|
@@ -282,6 +286,8 @@ function installExitHook() {
|
|
|
282
286
|
});
|
|
283
287
|
}
|
|
284
288
|
export async function runProcess(req) {
|
|
289
|
+
if (executionAdapter(executionPlatform()) === "isolated-container")
|
|
290
|
+
return runContainer(req);
|
|
285
291
|
const args = validateArgs(req.args);
|
|
286
292
|
if (!Number.isFinite(req.timeoutMs) || req.timeoutMs < 1 || req.timeoutMs > MAX_TIMEOUT_MS) {
|
|
287
293
|
throw new RunnerError("INVALID_TIMEOUT", `timeout must be between 1 ms and ${MAX_TIMEOUT_MS} ms.`);
|
|
@@ -3,6 +3,7 @@ import path from "node:path";
|
|
|
3
3
|
import { LocalFileError, categorize, formatSize, readFile, walkRepository, workspaceRoot } from "./local-files.js";
|
|
4
4
|
import { branchLabel, describeRepository, refreshWorkspace, statusLabel } from "./workspace.js";
|
|
5
5
|
import { activeRepository, inWorkspaceMode, listRepositories } from "./workspace-registry.js";
|
|
6
|
+
import { INSTRUCTION_FILE_NAMES, instructionPathsForDirectories } from "./instruction-resolver.js";
|
|
6
7
|
/**
|
|
7
8
|
* What Carrier OS can be told about the project WITHOUT being sent the project.
|
|
8
9
|
*
|
|
@@ -33,7 +34,7 @@ const MAX_BRIEF_CHARS = 8000;
|
|
|
33
34
|
* real convention but they raise a scoping question (which directory is a rule
|
|
34
35
|
* in force for?) that belongs with the phase that can actually act on them.
|
|
35
36
|
*/
|
|
36
|
-
const INSTRUCTION_FILES =
|
|
37
|
+
const INSTRUCTION_FILES = INSTRUCTION_FILE_NAMES;
|
|
37
38
|
/** Root-level markers worth naming. Presence only — contents are never read. */
|
|
38
39
|
const NOTABLE_ROOT_FILES = [
|
|
39
40
|
"package.json",
|
|
@@ -67,9 +68,9 @@ function typeId(name) {
|
|
|
67
68
|
*/
|
|
68
69
|
export function discoverInstructions(root = workspaceRoot()) {
|
|
69
70
|
const found = [];
|
|
70
|
-
for (const name of
|
|
71
|
+
for (const name of instructionPathsForDirectories(root, ["."])) {
|
|
71
72
|
try {
|
|
72
|
-
const res = readFile({ path: name, maxBytes: MAX_INSTRUCTION_BYTES });
|
|
73
|
+
const res = readFile({ path: name, maxBytes: MAX_INSTRUCTION_BYTES, root });
|
|
73
74
|
if (!res.text.trim())
|
|
74
75
|
continue;
|
|
75
76
|
found.push({
|
|
@@ -86,7 +87,6 @@ export function discoverInstructions(root = workspaceRoot()) {
|
|
|
86
87
|
throw err;
|
|
87
88
|
}
|
|
88
89
|
}
|
|
89
|
-
void root;
|
|
90
90
|
return found;
|
|
91
91
|
}
|
|
92
92
|
// ── Build ────────────────────────────────────────────────────────────────────
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { readJournal, recoveryReceipts, updateRecoveryReceipt } from './checkpoints.js';
|
|
2
|
+
import { listRepositories, repositoryTrust } from './workspace-registry.js';
|
|
3
|
+
import { appliedResult } from './mutations.js';
|
|
4
|
+
/** Reconstruct metadata only from independently verified execution evidence.
|
|
5
|
+
* No filesystem mutation, model call, or guessed success from bytes alone. */
|
|
6
|
+
export function reconstructMutationResults(scope, reports, groups) {
|
|
7
|
+
const replay = [];
|
|
8
|
+
for (const repo of listRepositories().slice(0, 20)) {
|
|
9
|
+
if (repositoryTrust(repo) !== 'trusted')
|
|
10
|
+
continue;
|
|
11
|
+
for (const r of recoveryReceipts(repo.root).receipts) {
|
|
12
|
+
if (r.scope !== scope || r.repository_id !== repo.id || r.result || r.delivery !== 'none')
|
|
13
|
+
continue;
|
|
14
|
+
const report = reports.find(p => p.operationId === r.operation_id && p.repositoryId === repo.id);
|
|
15
|
+
if (!report || report.classification === 'unresolved')
|
|
16
|
+
continue;
|
|
17
|
+
const group = r.group_id ? groups.find(g => g.groupId === r.group_id) : undefined;
|
|
18
|
+
if (r.group_id && (!group || !['COMPLETED', 'ROLLED_BACK', 'FAILED'].includes(group.state)))
|
|
19
|
+
continue;
|
|
20
|
+
const entry = readJournal(repo.root).find(e => e.operation_id === r.operation_id);
|
|
21
|
+
let payload;
|
|
22
|
+
if (r.phase === 'verified' && r.journal_persisted && report.journalStatus === 'EXECUTED' &&
|
|
23
|
+
entry && report.classification !== 'not_applied' && (!group || group.state === 'COMPLETED')) {
|
|
24
|
+
payload = { tool_call_id: r.operation_id, ok: true, result: appliedResult({
|
|
25
|
+
operationId: r.operation_id, repositoryId: r.repository_id, repositoryName: r.repository_name,
|
|
26
|
+
checkpointId: r.checkpoint_id, name: r.action, rel: r.path,
|
|
27
|
+
beforeExists: r.before_exists, afterExists: r.after_exists, beforeSha: r.before_sha, afterSha: r.after_sha,
|
|
28
|
+
beforeBytes: entry.before_bytes, afterBytes: entry.after_bytes, added: entry.added, removed: entry.removed,
|
|
29
|
+
reverts: entry.reverts,
|
|
30
|
+
// Exactly what the original result carried: present only when the journal recorded it.
|
|
31
|
+
...(entry.reviewed_diff && typeof entry.reviewed_diff === 'object' && !Array.isArray(entry.reviewed_diff) ? { review: entry.reviewed_diff } : {}),
|
|
32
|
+
}) };
|
|
33
|
+
}
|
|
34
|
+
else if (report.classification === 'not_applied' && r.phase === 'rolled_back' && report.journalStatus === 'ROLLED_BACK') {
|
|
35
|
+
payload = { tool_call_id: r.operation_id, ok: false, error: { code: 'ROLLED_BACK', message: 'Recovery verified that the approved change was rolled back.' } };
|
|
36
|
+
}
|
|
37
|
+
else if (group && ['ROLLED_BACK', 'FAILED'].includes(group.state) && report.classification === 'not_applied' &&
|
|
38
|
+
group.members?.some(m => m.operation_id === r.operation_id && ['NOT_STARTED', 'FAILED', 'NOT_APPLIED'].includes(m.state))) {
|
|
39
|
+
payload = { tool_call_id: r.operation_id, ok: false, error: { code: 'NOT_APPLIED', message: 'Recovery verified no applied change remains from this group member.' } };
|
|
40
|
+
}
|
|
41
|
+
if (!payload)
|
|
42
|
+
continue;
|
|
43
|
+
// Persist the exact reconstructed payload before it can enter transport.
|
|
44
|
+
updateRecoveryReceipt(repo.root, r.checkpoint_id, { result: payload, delivery: 'ready' });
|
|
45
|
+
replay.push({ payload, createdAt: Date.parse(r.created_at) });
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return replay;
|
|
49
|
+
}
|
|
@@ -3,7 +3,8 @@ import { execFileSync } from "node:child_process";
|
|
|
3
3
|
import fs from "node:fs";
|
|
4
4
|
import os from "node:os";
|
|
5
5
|
import path from "node:path";
|
|
6
|
-
import { findPrebuiltHelper } from "./helper-bin.js";
|
|
6
|
+
import { damagedInstallMessage, findPrebuiltHelper } from "./helper-bin.js";
|
|
7
|
+
import { isPackaged } from "./packaged.js";
|
|
7
8
|
/**
|
|
8
9
|
* Credentials at rest, protected with Windows DPAPI.
|
|
9
10
|
*
|
|
@@ -100,6 +101,12 @@ function ensureHelper() {
|
|
|
100
101
|
helperPath = prebuilt;
|
|
101
102
|
return prebuilt;
|
|
102
103
|
}
|
|
104
|
+
// A packaged build never compiles: no prebuilt helper means a damaged install,
|
|
105
|
+
// and sealingRequired() makes the config store refuse to write credentials.
|
|
106
|
+
if (isPackaged()) {
|
|
107
|
+
helperFailed = true;
|
|
108
|
+
return null;
|
|
109
|
+
}
|
|
103
110
|
const tag = sha256(DPAPI_SOURCE).slice(0, 16);
|
|
104
111
|
const dir = helperDir();
|
|
105
112
|
const exe = path.join(dir, `cos-dpapi-${tag}.exe`);
|
|
@@ -143,6 +150,19 @@ function ensureHelper() {
|
|
|
143
150
|
return null;
|
|
144
151
|
}
|
|
145
152
|
}
|
|
153
|
+
/**
|
|
154
|
+
* True when credentials MUST be sealed: the packaged Windows build ships its
|
|
155
|
+
* DPAPI helper, so its absence is a damaged installation, never a reason to
|
|
156
|
+
* write tokens in plaintext. A developer checkout keeps the documented
|
|
157
|
+
* fallback (plaintext at 0600 when no compiler exists).
|
|
158
|
+
*/
|
|
159
|
+
export function sealingRequired() {
|
|
160
|
+
return process.platform === "win32" && isPackaged();
|
|
161
|
+
}
|
|
162
|
+
/** The error a packaged build raises instead of storing credentials unsealed. */
|
|
163
|
+
export function sealingUnavailableError() {
|
|
164
|
+
return new SealError("UNAVAILABLE", damagedInstallMessage("cos-dpapi.exe"));
|
|
165
|
+
}
|
|
146
166
|
/** Whether credentials can be protected on this machine. */
|
|
147
167
|
export function sealingAvailable() {
|
|
148
168
|
return ensureHelper() !== null;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { ApiError } from "./api.js";
|
|
2
|
+
import { resetPermissionMode, restorePermissionMode } from "./permission-mode.js";
|
|
2
3
|
import { withSpinner } from "./spinner.js";
|
|
3
4
|
/**
|
|
4
5
|
* The one place a session is looked up.
|
|
@@ -100,9 +101,13 @@ export function setActiveSession(ctx, id, title) {
|
|
|
100
101
|
ctx.config.set("sessionId", id);
|
|
101
102
|
if (title !== undefined)
|
|
102
103
|
ctx.config.set("sessionTitle", title);
|
|
104
|
+
// Resuming: the conversation's own permission mode. Approvals are never restored.
|
|
105
|
+
restorePermissionMode(ctx.config, id);
|
|
103
106
|
}
|
|
104
107
|
/** Forget the active session (a fresh conversation starts on the next message). */
|
|
105
108
|
export function clearActiveSession(ctx) {
|
|
106
109
|
ctx.config.set("sessionId", undefined);
|
|
107
110
|
ctx.config.set("sessionTitle", undefined);
|
|
111
|
+
// A new task never inherits Accept Edits authority or Plan state.
|
|
112
|
+
resetPermissionMode(ctx.config);
|
|
108
113
|
}
|