@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.
Files changed (86) hide show
  1. package/README.md +34 -13
  2. package/dist/commands/chat.js +3 -3
  3. package/dist/commands/context.js +40 -0
  4. package/dist/commands/doctor.js +27 -12
  5. package/dist/commands/logout.js +1 -0
  6. package/dist/commands/permissions.js +77 -0
  7. package/dist/commands/scope.js +9 -6
  8. package/dist/commands/sessions.js +5 -0
  9. package/dist/commands/settings.js +8 -1
  10. package/dist/commands/update.js +79 -9
  11. package/dist/commands/usage.js +5 -5
  12. package/dist/commands/whoami.js +12 -9
  13. package/dist/ide/editor-context.js +115 -12
  14. package/dist/ide/ide-session.js +274 -13
  15. package/dist/ide/tool-host.js +2 -2
  16. package/dist/main.js +0 -0
  17. package/dist/services/api.js +178 -12
  18. package/dist/services/auth-origin.js +20 -0
  19. package/dist/services/chat-stream.js +26 -3
  20. package/dist/services/checkpoints.js +176 -14
  21. package/dist/services/client-tools.js +113 -21
  22. package/dist/services/code-intel.js +243 -0
  23. package/dist/services/code-symbols.js +94 -0
  24. package/dist/services/coding-workflow.js +554 -0
  25. package/dist/services/command-coordinator.js +85 -12
  26. package/dist/services/command-policy.js +34 -4
  27. package/dist/services/config.js +67 -5
  28. package/dist/services/container-runner.js +254 -0
  29. package/dist/services/container-supervisor.js +38 -0
  30. package/dist/services/context.js +45 -17
  31. package/dist/services/device-auth.js +30 -5
  32. package/dist/services/execution-platform.js +30 -0
  33. package/dist/services/file-resolver.js +1 -1
  34. package/dist/services/folder-key.js +22 -0
  35. package/dist/services/git-tools.js +181 -0
  36. package/dist/services/helper-bin.js +56 -35
  37. package/dist/services/instruction-resolver.js +54 -0
  38. package/dist/services/job-helper.js +31 -10
  39. package/dist/services/local-files.js +148 -26
  40. package/dist/services/local-tools.js +540 -35
  41. package/dist/services/login-flow.js +43 -12
  42. package/dist/services/mutation-coordinator.js +186 -20
  43. package/dist/services/mutation-groups.js +309 -0
  44. package/dist/services/mutation-recovery.js +159 -0
  45. package/dist/services/mutations.js +264 -78
  46. package/dist/services/packaged-update.js +403 -0
  47. package/dist/services/packaged.js +15 -0
  48. package/dist/services/permission-mode.js +60 -0
  49. package/dist/services/process-runner.js +7 -1
  50. package/dist/services/project-context.js +4 -4
  51. package/dist/services/result-reconciliation.js +49 -0
  52. package/dist/services/secure-store.js +21 -1
  53. package/dist/services/session-resolver.js +5 -0
  54. package/dist/services/supported-runtime.js +59 -0
  55. package/dist/services/task-context.js +212 -0
  56. package/dist/services/task-snapshot.js +38 -0
  57. package/dist/services/tool-result-outbox.js +195 -0
  58. package/dist/services/update.js +37 -12
  59. package/dist/services/workspace-registry.js +4 -3
  60. package/dist/services/workspace.js +8 -1
  61. package/dist/shell/shell-chat.js +299 -32
  62. package/dist/shell/shell-commands.js +46 -4
  63. package/dist/shell/shell-prompt.js +21 -11
  64. package/dist/shell/shell-renderer.js +1 -1
  65. package/dist/shell/shell.js +69 -7
  66. package/dist/shell/task-context-view.js +40 -0
  67. package/dist/ui/agent-cards.js +111 -0
  68. package/dist/ui/agent-presentation.js +131 -0
  69. package/dist/ui/approval.js +46 -16
  70. package/dist/ui/banner.js +31 -87
  71. package/dist/ui/change-review.js +293 -46
  72. package/dist/ui/chat-renderer.js +6 -6
  73. package/dist/ui/colors.js +9 -9
  74. package/dist/ui/command-details.js +11 -0
  75. package/dist/ui/command-palette.js +27 -10
  76. package/dist/ui/command-registry.js +9 -2
  77. package/dist/ui/command-review.js +77 -28
  78. package/dist/ui/composer-layout.js +26 -20
  79. package/dist/ui/conversation.js +77 -25
  80. package/dist/ui/live.js +1 -1
  81. package/dist/ui/screen.js +19 -11
  82. package/dist/ui/select.js +6 -0
  83. package/dist/ui/task-context-card.js +99 -0
  84. package/dist/ui/trust.js +7 -12
  85. package/dist/ui/ui.js +23 -0
  86. package/package.json +8 -5
@@ -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
+ `;
@@ -1,6 +1,7 @@
1
1
  import { ApiClient, ApiError } from "./api.js";
2
2
  import { DEFAULT_API_URL, sameApiOrigin } from "./config.js";
3
3
  import { refreshCliSession } from "./device-auth.js";
4
+ import { assertCredentialOrigin } from "./auth-origin.js";
4
5
  /**
5
6
  * Thrown by requireAuth when no key is configured. Unlike a process.exit, this
6
7
  * can be caught — so the interactive shell can keep running after a failed
@@ -59,7 +60,8 @@ export class CommandContext {
59
60
  }
60
61
  /** A client built from current config (anonymous if not logged in). */
61
62
  client() {
62
- return new ApiClient(this.config.get("apiUrl") ?? DEFAULT_API_URL, this.authProvider());
63
+ const apiUrl = this.config.get("apiUrl") ?? DEFAULT_API_URL;
64
+ return new ApiClient(apiUrl, this.authProvider(apiUrl));
63
65
  }
64
66
  /**
65
67
  * The one refresh currently on the wire, shared by every request that needs it.
@@ -77,15 +79,31 @@ export class CommandContext {
77
79
  * new provider for every client, and the coordination has to span all of them.
78
80
  */
79
81
  refreshing = null;
80
- /**
81
- * The credential + silent-refresh strategy for every authenticated call.
82
- * Prefers the device-flow session; falls back to a legacy static key.
83
- */
84
- authProvider() {
82
+ /** Check configured and actual destinations before exposing saved credentials. */
83
+ validateCredentialOrigin(destination = this.config.get("apiUrl") ?? DEFAULT_API_URL) {
84
+ const auth = this.config.get("auth");
85
+ if (!auth?.accessToken && !auth?.refreshToken && !this.config.get("secretKey"))
86
+ return;
87
+ const issuer = auth?.accessToken || auth?.refreshToken ? auth.apiUrl : this.config.get("secretKeyApiUrl");
88
+ assertCredentialOrigin(issuer, this.config.get("apiUrl") ?? DEFAULT_API_URL);
89
+ assertCredentialOrigin(issuer, destination);
90
+ }
91
+ /** Credential + silent-refresh strategy, bound to the client's API base. */
92
+ authProvider(apiUrl = this.config.get("apiUrl") ?? DEFAULT_API_URL) {
85
93
  return {
86
- token: () => this.config.get("auth")?.accessToken ?? this.config.get("secretKey"),
87
- refresh: (failedToken) => {
88
- this.refreshing ??= this.renewSession(failedToken).finally(() => {
94
+ token: (destination = apiUrl) => {
95
+ this.validateCredentialOrigin(destination);
96
+ const auth = this.config.get("auth");
97
+ if (auth?.accessToken)
98
+ return auth.accessToken;
99
+ const key = this.config.get("secretKey");
100
+ if (key)
101
+ assertCredentialOrigin(this.config.get("secretKeyApiUrl"), destination);
102
+ return key;
103
+ },
104
+ refresh: async (failedToken) => {
105
+ this.validateCredentialOrigin(apiUrl);
106
+ this.refreshing ??= this.renewSession(apiUrl, failedToken).finally(() => {
89
107
  this.refreshing = null;
90
108
  });
91
109
  return this.refreshing;
@@ -102,16 +120,16 @@ export class CommandContext {
102
120
  * and presenting it trips the server's reuse detection — which revokes every
103
121
  * device on the account. Adopting the rotated pair avoids asking at all.
104
122
  */
105
- async renewSession(failedToken) {
123
+ async renewSession(apiUrl, failedToken) {
106
124
  this.config.reload();
107
125
  const auth = this.config.get("auth");
108
126
  if (!auth?.refreshToken)
109
127
  return undefined;
128
+ this.validateCredentialOrigin(apiUrl);
110
129
  // Someone already renewed since this request went out — just retry with it.
111
130
  if (failedToken && auth.accessToken && auth.accessToken !== failedToken) {
112
131
  return auth.accessToken;
113
132
  }
114
- const apiUrl = this.config.get("apiUrl") ?? DEFAULT_API_URL;
115
133
  const outcome = await refreshCliSession(apiUrl, auth.refreshToken);
116
134
  switch (outcome.kind) {
117
135
  case "ok": {
@@ -121,9 +139,8 @@ export class CommandContext {
121
139
  ...auth,
122
140
  accessToken: renewed.access_token,
123
141
  refreshToken: renewed.refresh_token,
124
- // A server that rotated this session is the server that owns it —
125
- // stamp sessions issued before the field existed.
126
- apiUrl: auth.apiUrl ?? apiUrl,
142
+ // Preserve the issuer that was validated before the exchange.
143
+ apiUrl: auth.apiUrl,
127
144
  workspace: renewed.workspace ?? auth.workspace,
128
145
  project: renewed.project ?? auth.project
129
146
  }
@@ -153,11 +170,15 @@ export class CommandContext {
153
170
  case "busy": {
154
171
  // A different process won the rotation; its tokens are about to land in
155
172
  // the shared config. Give it a moment to write them rather than guessing.
156
- const adopted = await this.awaitRotatedElsewhere(auth.refreshToken);
173
+ const adopted = await this.awaitRotatedElsewhere(auth.refreshToken, apiUrl);
157
174
  if (adopted)
158
175
  return adopted;
159
176
  throw new ApiError("SESSION_BUSY", "Your session is being renewed by another Carrier OS window. Try again in a moment.", 409);
160
177
  }
178
+ case "unsupported":
179
+ // Retrying cannot help: this API build has no route for the session.
180
+ throw new ApiError("SESSION_ENDPOINT_MISSING", `${apiUrl} can't renew Carrier OS sign-in sessions — it may be running an older API version. ` +
181
+ "Point Carrier OS at the API that signed you in, or run `cos logout` and sign in again.", 404);
161
182
  case "transient":
162
183
  // The session may be perfectly healthy — never sign someone out because
163
184
  // the API had a bad second.
@@ -165,11 +186,12 @@ export class CommandContext {
165
186
  }
166
187
  }
167
188
  /** Poll the shared config briefly for a refresh token rotated by another process. */
168
- async awaitRotatedElsewhere(spentRefreshToken) {
189
+ async awaitRotatedElsewhere(spentRefreshToken, apiUrl) {
169
190
  for (let attempt = 0; attempt < 10; attempt += 1) {
170
191
  await new Promise((r) => setTimeout(r, 100));
171
192
  this.config.reload();
172
193
  const auth = this.config.get("auth");
194
+ this.validateCredentialOrigin(apiUrl);
173
195
  if (auth?.refreshToken && auth.refreshToken !== spentRefreshToken && auth.accessToken) {
174
196
  return auth.accessToken;
175
197
  }
@@ -301,7 +323,10 @@ export class CommandContext {
301
323
  return "auto";
302
324
  if (stored === false)
303
325
  return "off";
304
- return stored === "off" ? "off" : "auto"; // unset -> auto, the default
326
+ // Unset is OFF, as the web composer's toggle is. Defaulting to auto put
327
+ // clarifying questions in front of every coding task ("should the subtotal
328
+ // include discounts?") before the agent had even read the repository.
329
+ return stored === "auto" ? "auto" : "off";
305
330
  }
306
331
  /** True when a turn should ask the backend whether clarification is needed. */
307
332
  get sia() {
@@ -318,6 +343,9 @@ export class CommandContext {
318
343
  * transient region.
319
344
  */
320
345
  mainTurnRunning = false;
346
+ /** Read-only Admin Panel Carrier Chat switch, refreshed by the shell. Null
347
+ * means it could not yet be verified; the send gate checks again. */
348
+ carrierMaintenance = null;
321
349
  /**
322
350
  * Credits this shell session's turns were actually debited, summed from the
323
351
  * server's per-turn `credits_spent`. Runtime-only: "this session" means this
@@ -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 {
@@ -130,6 +145,7 @@ async function envelopePost(url, body, headers) {
130
145
  ...(headers ?? {})
131
146
  },
132
147
  timeout: 30_000,
148
+ maxRedirects: 0,
133
149
  validateStatus: () => true
134
150
  });
135
151
  return { status: res.status, body: res.data };
@@ -170,13 +186,19 @@ async function pollOnce(authBase, deviceCode) {
170
186
  }
171
187
  /** Step 2 (loop) — poll until approved, denied, expired, or timed out. Calls
172
188
  * `onTick` between polls so the caller can animate a spinner. */
173
- export async function pollForToken(authBase, start, onTick) {
189
+ export async function pollForToken(authBase, start, onTick,
190
+ /** Stops polling: an approval that arrives after it is never used. */
191
+ signal) {
174
192
  let intervalMs = Math.max(1, start.interval || 5) * 1000;
175
193
  const deadline = Date.now() + Math.max(1, start.expires_in || 600) * 1000;
176
194
  while (Date.now() < deadline) {
177
195
  onTick?.();
178
196
  await sleep(intervalMs);
197
+ if (signal?.aborted)
198
+ throw new ApiError("SIGN_IN_CANCELLED", "Sign-in cancelled.");
179
199
  const outcome = await pollOnce(authBase, start.device_code);
200
+ if (signal?.aborted)
201
+ throw new ApiError("SIGN_IN_CANCELLED", "Sign-in cancelled.");
180
202
  switch (outcome.kind) {
181
203
  case "approved":
182
204
  return outcome.data;
@@ -198,7 +220,7 @@ export async function pollForToken(authBase, start, onTick) {
198
220
  /** Exchange a refresh token for a new session (rotation). Never clears anything
199
221
  * itself — the caller decides, from the outcome, whether the session is over. */
200
222
  export async function refreshCliSession(apiUrl, refreshToken) {
201
- const authBase = platformAuthBase(apiUrl);
223
+ const authBase = cliSessionAuthBase(apiUrl, refreshToken);
202
224
  const { status, body } = await envelopePost(`${authBase}/cli/refresh`, {
203
225
  refresh_token: refreshToken
204
226
  });
@@ -208,12 +230,14 @@ export async function refreshCliSession(apiUrl, refreshToken) {
208
230
  return { kind: "dead" };
209
231
  if (status === 409)
210
232
  return { kind: "busy" };
233
+ if (status === 404)
234
+ return { kind: "unsupported" };
211
235
  return { kind: "transient", status };
212
236
  }
213
237
  /** Best-effort server-side logout (revokes the refresh token). Never throws. */
214
238
  export async function logoutCliSession(apiUrl, refreshToken) {
215
239
  try {
216
- await envelopePost(`${platformAuthBase(apiUrl)}/cli/logout`, { refresh_token: refreshToken });
240
+ await envelopePost(`${cliSessionAuthBase(apiUrl, refreshToken)}/cli/logout`, { refresh_token: refreshToken });
217
241
  }
218
242
  catch {
219
243
  /* offline logout is fine — the local credentials are cleared regardless */
@@ -221,8 +245,8 @@ export async function logoutCliSession(apiUrl, refreshToken) {
221
245
  }
222
246
  // ── Authenticated /cli/* management (bearer access token, refresh-on-401) ─────
223
247
  async function authedRequest(apiUrl, method, path, provider, body, retry = true) {
224
- const url = `${platformAuthBase(apiUrl)}${path}`;
225
- const token = provider.token();
248
+ const token = provider.token(apiUrl);
249
+ const url = `${cliSessionAuthBase(apiUrl, token)}${path}`;
226
250
  const res = await axios.request({
227
251
  url,
228
252
  method,
@@ -232,6 +256,7 @@ async function authedRequest(apiUrl, method, path, provider, body, retry = true)
232
256
  ...(token ? { Authorization: `Bearer ${token}` } : {})
233
257
  },
234
258
  timeout: 30_000,
259
+ maxRedirects: 0,
235
260
  validateStatus: () => true
236
261
  });
237
262
  if (res.status === 401 && retry && provider.refresh) {
@@ -0,0 +1,30 @@
1
+ export function executionContract(value = process.platform) {
2
+ const windows = value === "win32";
3
+ const isolated = value === "darwin" || value === "linux";
4
+ const supported = windows || isolated;
5
+ return {
6
+ capability: windows ? "NATIVE_SECURE" : isolated ? "ISOLATED_RUNTIME_REQUIRED" : "UNSUPPORTED",
7
+ backend: windows ? "windows-job" : isolated ? "docker-engine-v1" : null,
8
+ guarantees: {
9
+ descendantTracking: windows ? "job-membership" : isolated ? "pid-namespace" : "unavailable",
10
+ descendantTermination: supported, orphanCleanup: supported, timeout: supported,
11
+ cancellation: supported, workingDirectoryContainment: supported,
12
+ environment: windows ? "filtered-host" : isolated ? "isolated-guest" : "unavailable",
13
+ commandRestrictions: supported
14
+ },
15
+ prerequisite: windows ? "Verified Windows Job Object helper; no breakaway. Native OS acceptance must be verified separately."
16
+ : isolated ? "Secure command execution requires the approved Docker Engine runtime because native process lifecycle guarantees are insufficient."
17
+ : `Secure command execution is unsupported on ${value}.`
18
+ };
19
+ }
20
+ export function executionPlatform(value = process.platform) {
21
+ if (executionContract(value).capability !== "UNSUPPORTED")
22
+ return value;
23
+ throw Object.assign(new Error(executionContract(value).prerequisite), { code: "UNSUPPORTED_PLATFORM" });
24
+ }
25
+ export function executionAdapter(platform) {
26
+ const contract = executionContract(platform);
27
+ if (contract.capability === "UNSUPPORTED")
28
+ executionPlatform(platform);
29
+ return contract.backend === "windows-job" ? "windows-job" : "isolated-container";
30
+ }
@@ -34,7 +34,7 @@ function tryExact(repo, rel, kind) {
34
34
  return null;
35
35
  if (kind === "directory" && !isDir)
36
36
  return null;
37
- const relOut = posix(path.relative(repo.root, abs));
37
+ const relOut = posix(path.relative(fs.realpathSync.native(repo.root), abs));
38
38
  if (!relOut || relOut.startsWith(".."))
39
39
  return null;
40
40
  if (isPathIgnored(relOut, repo.root))
@@ -0,0 +1,22 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ /**
4
+ * A folder's canonical identity for trust decisions: its real path (symlinks
5
+ * resolved — macOS /var is /private/var), case-folded on Windows. Trust is about
6
+ * a folder on disk, so two spellings of the same folder must agree and two
7
+ * different folders can never share a key. A path not on disk (yet) keeps its
8
+ * resolved spelling. The ONE comparison every trust check uses.
9
+ */
10
+ export function folderKey(dir) {
11
+ let resolved = path.resolve(dir);
12
+ try {
13
+ resolved = fs.realpathSync.native(resolved);
14
+ }
15
+ catch { /* not on disk: keep the spelling */ }
16
+ return process.platform === "win32" ? resolved.toLowerCase() : resolved;
17
+ }
18
+ /** Whether `dir` is one of `trusted` (entries saved under another spelling still count). */
19
+ export function isTrustedFolder(trusted, dir) {
20
+ const key = folderKey(dir);
21
+ return trusted.some((entry) => entry === key || folderKey(entry) === key);
22
+ }
@@ -246,3 +246,184 @@ export function gitDiff(root, scope = "working_tree") {
246
246
  }
247
247
  return { scope, files_changed: filesChanged, additions, deletions, diff, truncated };
248
248
  }
249
+ // ── History (read-only) ──────────────────────────────────────────────────────
250
+ // log, blame and show answer "when and why did this line change?" — the step a
251
+ // root-cause investigation takes after it has found the function. They are
252
+ // reads with the same hardening as status/diff. Revisions are validated to a
253
+ // closed grammar BEFORE they reach argv, so a model-supplied value can never be
254
+ // read by Git as an option, a ref expression with side effects, or a path; and
255
+ // every path follows a literal `--`. Patches are only ever produced for one
256
+ // path the caller already validated against the read rules (containment,
257
+ // ignore, sensitive names), so history cannot be used to read a credentials
258
+ // file that a current read_file would refuse.
259
+ /** Most commits one git_log returns. */
260
+ export const MAX_LOG_COMMITS = 50;
261
+ /** Most changed paths listed per commit. */
262
+ const MAX_LOG_FILES = 20;
263
+ /** Most lines one git_blame covers. */
264
+ export const MAX_BLAME_LINES = 200;
265
+ /** HEAD, HEAD~n, HEAD^…, or an abbreviated/full object id. Nothing else. */
266
+ const REVISION = /^(?:HEAD(?:~\d{1,4}|\^{1,4})?|[0-9a-fA-F]{4,64})$/;
267
+ export function isSafeRevision(rev) {
268
+ return REVISION.test(rev);
269
+ }
270
+ function requireRevision(rev) {
271
+ if (!isSafeRevision(rev)) {
272
+ throw new GitToolError("INVALID_REVISION", 'A revision must be HEAD, HEAD~n, HEAD^, or a commit hash (4–64 hex characters).');
273
+ }
274
+ return rev;
275
+ }
276
+ const HISTORY_GUARDS = ["--no-color", "--no-ext-diff", "--no-textconv"];
277
+ const FIELD = "\x1f";
278
+ const RECORD = "\x1e";
279
+ function noHistory(reason) {
280
+ return /does not have any commits|unknown revision|bad default revision|ambiguous argument 'HEAD'/i.test(reason ?? "");
281
+ }
282
+ function parseCommits(out, withFiles) {
283
+ const commits = [];
284
+ for (const raw of out.split(RECORD)) {
285
+ const record = raw.replace(/^\r?\n+/, "");
286
+ if (!record.trim())
287
+ continue;
288
+ const [header, ...rest] = record.split(/\r?\n/);
289
+ const [commit, short, author, date, subject] = header.split(FIELD);
290
+ if (!commit)
291
+ continue;
292
+ const entry = { commit, short, author, date, subject: subject ?? "" };
293
+ if (withFiles) {
294
+ const files = rest.map((l) => l.trim()).filter(Boolean);
295
+ entry.files = files.slice(0, MAX_LOG_FILES);
296
+ if (files.length > MAX_LOG_FILES)
297
+ entry.files_truncated = true;
298
+ }
299
+ commits.push(entry);
300
+ }
301
+ return commits;
302
+ }
303
+ /**
304
+ * Recent commits, optionally only those touching one validated path.
305
+ * Metadata and changed-path names only — never patches.
306
+ */
307
+ export function gitLog(root, opts = {}) {
308
+ const limit = Math.min(MAX_LOG_COMMITS, Math.max(1, Math.floor(opts.limit ?? 10)));
309
+ const args = [
310
+ "log",
311
+ ...HISTORY_GUARDS,
312
+ `--max-count=${limit + 1}`,
313
+ `--format=${RECORD}%H${FIELD}%h${FIELD}%an${FIELD}%aI${FIELD}%s`,
314
+ "--name-only"
315
+ ];
316
+ if (opts.path)
317
+ args.push("--follow", "--", opts.path);
318
+ const res = run(root, args, overridesFor(root));
319
+ if (!res.ok) {
320
+ if (noHistory(res.reason))
321
+ return { commits: [], truncated: false };
322
+ throw new GitToolError("GIT_FAILED", res.reason ?? "git log failed.");
323
+ }
324
+ const commits = parseCommits(res.out, true);
325
+ return { commits: commits.slice(0, limit), truncated: commits.length > limit };
326
+ }
327
+ /** Line-by-line authorship for a bounded range of one validated path. */
328
+ export function gitBlame(root, relPath, startLine, endLine) {
329
+ const start = Math.max(1, Math.floor(startLine));
330
+ const end = Math.max(start, Math.floor(endLine));
331
+ if (end - start + 1 > MAX_BLAME_LINES) {
332
+ throw new GitToolError("RANGE_TOO_LARGE", `Blame at most ${MAX_BLAME_LINES} lines at a time.`);
333
+ }
334
+ const res = run(root, ["blame", "--porcelain", "--no-textconv", "-L", `${start},${end}`, "--", relPath], overridesFor(root));
335
+ if (!res.ok) {
336
+ if (noHistory(res.reason) || /no such path .* in HEAD/i.test(res.reason ?? "")) {
337
+ throw new GitToolError("NO_HISTORY", `${relPath} has no committed history yet.`);
338
+ }
339
+ throw new GitToolError("GIT_FAILED", res.reason ?? "git blame failed.");
340
+ }
341
+ const meta = new Map();
342
+ const lines = [];
343
+ let current = null;
344
+ for (const raw of res.out.split("\n")) {
345
+ const head = raw.match(/^([0-9a-f]{40}) \d+ (\d+)(?: \d+)?$/);
346
+ if (head) {
347
+ current = { commit: head[1], final: Number(head[2]) };
348
+ if (!meta.has(head[1]))
349
+ meta.set(head[1], { author: "", time: null, summary: "" });
350
+ continue;
351
+ }
352
+ if (!current)
353
+ continue;
354
+ const m = meta.get(current.commit);
355
+ if (raw.startsWith("author "))
356
+ m.author = raw.slice(7);
357
+ else if (raw.startsWith("author-time "))
358
+ m.time = Number(raw.slice(12)) || null;
359
+ else if (raw.startsWith("summary "))
360
+ m.summary = raw.slice(8);
361
+ else if (raw.startsWith("\t")) {
362
+ const uncommitted = /^0+$/.test(current.commit);
363
+ lines.push({
364
+ line: current.final,
365
+ commit: uncommitted ? "uncommitted" : current.commit.slice(0, 12),
366
+ author: uncommitted ? "Not committed yet" : m.author,
367
+ date: uncommitted || m.time === null ? null : new Date(m.time * 1000).toISOString(),
368
+ summary: uncommitted ? "" : m.summary,
369
+ text: raw.slice(1).replace(/\r$/, ""),
370
+ uncommitted
371
+ });
372
+ current = null;
373
+ }
374
+ }
375
+ return { lines };
376
+ }
377
+ /** One commit: metadata and per-file counts; a bounded patch only for one validated path. */
378
+ export function gitShow(root, revision, relPath) {
379
+ const rev = requireRevision(revision);
380
+ const overrides = overridesFor(root);
381
+ const meta = run(root, ["show", "-s", ...HISTORY_GUARDS, `--format=%H${FIELD}%h${FIELD}%an${FIELD}%aI${FIELD}%s${FIELD}%b`, rev, "--"], overrides);
382
+ if (!meta.ok) {
383
+ if (noHistory(meta.reason) || /bad object|bad revision/i.test(meta.reason ?? "")) {
384
+ throw new GitToolError("UNKNOWN_REVISION", `No commit matches ${rev}.`);
385
+ }
386
+ throw new GitToolError("GIT_FAILED", meta.reason ?? "git show failed.");
387
+ }
388
+ const [commit, short, author, date, subject, ...body] = meta.out.replace(/\n+$/, "").split(FIELD);
389
+ const stat = run(root, ["show", ...HISTORY_GUARDS, "--numstat", "--format=", rev, "--"], overrides);
390
+ if (!stat.ok)
391
+ throw new GitToolError("GIT_FAILED", stat.reason ?? "git show failed.");
392
+ const files = [];
393
+ let filesTruncated = false;
394
+ for (const raw of stat.out.split(/\r?\n/)) {
395
+ if (!raw.trim())
396
+ continue;
397
+ if (files.length >= MAX_FILES) {
398
+ filesTruncated = true;
399
+ break;
400
+ }
401
+ const [add, del, ...name] = raw.split("\t");
402
+ files.push({ path: name.join("\t"), additions: add === "-" ? null : Number(add), deletions: del === "-" ? null : Number(del) });
403
+ }
404
+ const result = {
405
+ commit,
406
+ short,
407
+ author,
408
+ date,
409
+ subject: subject ?? "",
410
+ body: body.join(FIELD).trim().slice(0, 4000),
411
+ files_changed: files,
412
+ files_truncated: filesTruncated,
413
+ truncated: false
414
+ };
415
+ if (relPath) {
416
+ const patch = run(root, ["show", ...HISTORY_GUARDS, "--format=", rev, "--", relPath], overrides);
417
+ if (!patch.ok)
418
+ throw new GitToolError("GIT_FAILED", patch.reason ?? "git show failed.");
419
+ let diff = patch.out;
420
+ if (Buffer.byteLength(diff, "utf8") > MAX_DIFF_BYTES) {
421
+ diff = diff.slice(0, MAX_DIFF_BYTES);
422
+ diff = diff.slice(0, diff.lastIndexOf("\n") + 1) + "… [diff truncated]\n";
423
+ result.truncated = true;
424
+ }
425
+ result.path = relPath;
426
+ result.diff = diff;
427
+ }
428
+ return result;
429
+ }
@@ -1,53 +1,70 @@
1
1
  import crypto from "node:crypto";
2
2
  import fs from "node:fs";
3
3
  import path from "node:path";
4
- /**
5
- * Finding a PREBUILT native helper that ships with the CLI.
6
- *
7
- * The Job Object runner and the DPAPI credential helper are tiny C# programs.
8
- * In a developer checkout they are compiled on first use with the Windows
9
- * `csc.exe`; in the PACKAGED executable there is no compiler, no TypeScript
10
- * source and no npm — so the helpers are built ONCE at package time and shipped
11
- * as `.exe` files next to the CLI, each with a `.sha256` sidecar.
12
- *
13
- * This module locates such a prebuilt helper and verifies it before it is used.
14
- * The integrity check catches corruption and a stale or partial copy; it is NOT
15
- * a defence against other code running as the same Windows user (which could
16
- * replace the exe and its sidecar together) — the same honest limitation the
17
- * runtime-compiled path already documents. See docs/PACKAGING.md.
18
- *
19
- * Discovery order, none of which is a source path:
20
- * 1. COS_HELPER_DIR — an explicit override (packaging, tests).
21
- * 2. the directory of the running executable (where the packaged .exe ships
22
- * its helpers) and a `bin/` subfolder of it.
23
- */
4
+ import { isPackaged, PACKAGED_DOWNLOAD_URL } from "./packaged.js";
24
5
  export function sha256File(file) {
25
6
  return crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex");
26
7
  }
27
- function candidateDirs() {
28
- const dirs = [];
29
- if (process.env.COS_HELPER_DIR)
30
- dirs.push(process.env.COS_HELPER_DIR);
8
+ const HEX64 = /^[0-9a-f]{64}$/;
9
+ /**
10
+ * The baked helper hashes, or null when the build carries none or carries
11
+ * something malformed. Null is never "anything goes": in packaged mode it means
12
+ * no helper verifies, so the caller fails closed.
13
+ */
14
+ export function bakedHelperHashes(raw = typeof __HELPER_HASHES__ === "string" ? __HELPER_HASHES__ : undefined) {
15
+ if (typeof raw !== "string" || !raw)
16
+ return null;
31
17
  try {
32
- const exeDir = path.dirname(process.execPath);
33
- dirs.push(exeDir, path.join(exeDir, "bin"));
18
+ const parsed = JSON.parse(raw);
19
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
20
+ return null;
21
+ const out = {};
22
+ for (const [name, hash] of Object.entries(parsed)) {
23
+ if (!/^[A-Za-z0-9._-]+\.exe$/.test(name) || typeof hash !== "string" || !HEX64.test(hash))
24
+ return null;
25
+ out[name] = hash;
26
+ }
27
+ return Object.keys(out).length ? out : null;
34
28
  }
35
29
  catch {
36
- /* execPath unavailable — nothing to add */
30
+ return null;
37
31
  }
32
+ }
33
+ function devCandidateDirs(exeDir, env) {
34
+ const dirs = [];
35
+ if (env.COS_HELPER_DIR)
36
+ dirs.push(env.COS_HELPER_DIR);
37
+ dirs.push(exeDir, path.join(exeDir, "bin"));
38
38
  return dirs;
39
39
  }
40
40
  /**
41
- * The absolute path to a verified prebuilt `<baseName>.exe`, or null when none
42
- * is shipped (a developer checkout, where the caller falls back to compiling).
43
- * A file present but failing its sidecar hash is treated as absent — better to
44
- * rebuild than to run something that does not match what was shipped.
41
+ * The absolute path to a verified prebuilt `<baseName>.exe`, or null.
42
+ *
43
+ * Packaged: null means the installation is damaged — callers must fail closed.
44
+ * Development: null means "none shipped" — callers may compile from source.
45
45
  */
46
- export function findPrebuiltHelper(baseName) {
47
- if (process.platform !== "win32")
46
+ export function findPrebuiltHelper(baseName, opts = {}) {
47
+ const platform = opts.platform ?? process.platform;
48
+ if (platform !== "win32")
48
49
  return null;
49
- for (const dir of candidateDirs()) {
50
- const exe = path.join(dir, `${baseName}.exe`);
50
+ const packaged = opts.packaged ?? isPackaged();
51
+ const exeDir = opts.exeDir ?? path.dirname(process.execPath);
52
+ const file = `${baseName}.exe`;
53
+ if (packaged) {
54
+ const hashes = opts.hashes !== undefined ? opts.hashes : bakedHelperHashes();
55
+ const expected = hashes?.[file];
56
+ if (!expected)
57
+ return null;
58
+ const exe = path.join(exeDir, file);
59
+ try {
60
+ return fs.statSync(exe).isFile() && sha256File(exe) === expected ? exe : null;
61
+ }
62
+ catch {
63
+ return null;
64
+ }
65
+ }
66
+ for (const dir of devCandidateDirs(exeDir, opts.env ?? process.env)) {
67
+ const exe = path.join(dir, file);
51
68
  const stamp = `${exe}.sha256`;
52
69
  try {
53
70
  if (!fs.existsSync(exe) || !fs.existsSync(stamp))
@@ -62,3 +79,7 @@ export function findPrebuiltHelper(baseName) {
62
79
  }
63
80
  return null;
64
81
  }
82
+ /** The message every fail-closed packaged path shows. */
83
+ export function damagedInstallMessage(file) {
84
+ return `This Carrier OS installation is missing or has a damaged component (${file}). Reinstall Carrier OS from ${PACKAGED_DOWNLOAD_URL}.`;
85
+ }