@carrieros/cli 0.2.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 (124) hide show
  1. package/README.md +170 -64
  2. package/dist/commands/attach.js +45 -0
  3. package/dist/commands/btw.js +78 -0
  4. package/dist/commands/changes.js +167 -0
  5. package/dist/commands/chat.js +81 -15
  6. package/dist/commands/context.js +200 -0
  7. package/dist/commands/doctor.js +63 -3
  8. package/dist/commands/files.js +84 -23
  9. package/dist/commands/help.js +1 -0
  10. package/dist/commands/history.js +88 -23
  11. package/dist/commands/login.js +31 -7
  12. package/dist/commands/logout.js +1 -0
  13. package/dist/commands/memory.js +162 -0
  14. package/dist/commands/mode-model.js +39 -3
  15. package/dist/commands/modes.js +4 -1
  16. package/dist/commands/permissions.js +77 -0
  17. package/dist/commands/project.js +106 -0
  18. package/dist/commands/repo.js +146 -0
  19. package/dist/commands/repos.js +61 -0
  20. package/dist/commands/review.js +92 -0
  21. package/dist/commands/scope.js +9 -6
  22. package/dist/commands/search.js +92 -0
  23. package/dist/commands/sessions.js +224 -65
  24. package/dist/commands/settings.js +94 -0
  25. package/dist/commands/update.js +229 -0
  26. package/dist/commands/upload.js +204 -31
  27. package/dist/commands/usage.js +213 -17
  28. package/dist/commands/whoami.js +12 -9
  29. package/dist/ide/editor-context.js +275 -0
  30. package/dist/ide/ide-session.js +355 -0
  31. package/dist/ide/tool-host.js +109 -0
  32. package/dist/main.js +26 -1
  33. package/dist/services/api.js +315 -15
  34. package/dist/services/auth-origin.js +20 -0
  35. package/dist/services/chat-stream.js +168 -0
  36. package/dist/services/checkpoints.js +278 -0
  37. package/dist/services/client-tools.js +352 -0
  38. package/dist/services/code-intel.js +243 -0
  39. package/dist/services/code-symbols.js +94 -0
  40. package/dist/services/coding-workflow.js +554 -0
  41. package/dist/services/command-coordinator.js +273 -0
  42. package/dist/services/command-policy.js +434 -0
  43. package/dist/services/config.js +311 -24
  44. package/dist/services/container-runner.js +254 -0
  45. package/dist/services/container-supervisor.js +38 -0
  46. package/dist/services/context.js +296 -23
  47. package/dist/services/device-auth.js +72 -35
  48. package/dist/services/diff.js +196 -0
  49. package/dist/services/env-policy.js +108 -0
  50. package/dist/services/execution-platform.js +30 -0
  51. package/dist/services/file-detect.js +104 -0
  52. package/dist/services/file-resolver.js +199 -0
  53. package/dist/services/file-upload.js +126 -0
  54. package/dist/services/folder-key.js +22 -0
  55. package/dist/services/git-tools.js +429 -0
  56. package/dist/services/glob-match.js +164 -0
  57. package/dist/services/helper-bin.js +85 -0
  58. package/dist/services/ignore-rules.js +189 -0
  59. package/dist/services/instruction-resolver.js +54 -0
  60. package/dist/services/job-helper.js +328 -0
  61. package/dist/services/local-files.js +639 -0
  62. package/dist/services/local-tools.js +937 -0
  63. package/dist/services/login-flow.js +55 -17
  64. package/dist/services/meta.js +3 -1
  65. package/dist/services/mutation-coordinator.js +327 -0
  66. package/dist/services/mutation-groups.js +309 -0
  67. package/dist/services/mutation-recovery.js +159 -0
  68. package/dist/services/mutations.js +679 -0
  69. package/dist/services/open-url.js +68 -0
  70. package/dist/services/output.js +5 -2
  71. package/dist/services/packaged-update.js +403 -0
  72. package/dist/services/packaged.js +39 -0
  73. package/dist/services/permission-mode.js +60 -0
  74. package/dist/services/process-runner.js +412 -0
  75. package/dist/services/project-context.js +298 -0
  76. package/dist/services/redaction.js +201 -0
  77. package/dist/services/result-reconciliation.js +49 -0
  78. package/dist/services/secure-store.js +217 -0
  79. package/dist/services/session-resolver.js +113 -0
  80. package/dist/services/sia.js +51 -0
  81. package/dist/services/supported-runtime.js +59 -0
  82. package/dist/services/task-context.js +212 -0
  83. package/dist/services/task-snapshot.js +38 -0
  84. package/dist/services/tool-result-outbox.js +195 -0
  85. package/dist/services/update.js +311 -0
  86. package/dist/services/workspace-registry.js +310 -0
  87. package/dist/services/workspace.js +580 -0
  88. package/dist/shell/shell-chat.js +1297 -59
  89. package/dist/shell/shell-commands.js +243 -12
  90. package/dist/shell/shell-prompt.js +94 -11
  91. package/dist/shell/shell-renderer.js +8 -20
  92. package/dist/shell/shell-router.js +19 -3
  93. package/dist/shell/shell.js +252 -22
  94. package/dist/shell/task-context-view.js +40 -0
  95. package/dist/types/index.js +3 -1
  96. package/dist/ui/agent-cards.js +111 -0
  97. package/dist/ui/agent-presentation.js +131 -0
  98. package/dist/ui/approval.js +111 -0
  99. package/dist/ui/banner.js +31 -48
  100. package/dist/ui/btw-overlay.js +230 -0
  101. package/dist/ui/change-review.js +334 -0
  102. package/dist/ui/chat-renderer.js +207 -14
  103. package/dist/ui/colors.js +12 -8
  104. package/dist/ui/command-details.js +11 -0
  105. package/dist/ui/command-filter.js +26 -5
  106. package/dist/ui/command-palette.js +44 -14
  107. package/dist/ui/command-registry.js +92 -10
  108. package/dist/ui/command-review.js +187 -0
  109. package/dist/ui/composer-layout.js +48 -1
  110. package/dist/ui/conversation.js +450 -0
  111. package/dist/ui/interrupt.js +35 -0
  112. package/dist/ui/live.js +4 -2
  113. package/dist/ui/markdown.js +63 -9
  114. package/dist/ui/message.js +14 -31
  115. package/dist/ui/screen-prompt.js +181 -0
  116. package/dist/ui/screen.js +19 -11
  117. package/dist/ui/select.js +191 -29
  118. package/dist/ui/sia-qa.js +213 -0
  119. package/dist/ui/task-context-card.js +99 -0
  120. package/dist/ui/text-prompt.js +74 -0
  121. package/dist/ui/trust.js +88 -0
  122. package/dist/ui/ui.js +27 -1
  123. package/package.json +18 -4
  124. package/dist/ui/activity.js +0 -77
@@ -0,0 +1,126 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { ApiError } from "./api.js";
4
+ const SUPPORTED = "PDF, DOCX, TXT, CSV, JSON, Markdown, Images";
5
+ /** A friendly, already-formatted, user-facing upload error. */
6
+ export class UploadError extends Error {
7
+ constructor(message) {
8
+ super(message);
9
+ this.name = "UploadError";
10
+ }
11
+ }
12
+ /** A short human file-type label from the extension (e.g. "PDF", "CSV"). */
13
+ export function fileTypeLabel(name) {
14
+ const ext = path.extname(name).replace(".", "").toUpperCase();
15
+ return ext || "FILE";
16
+ }
17
+ /** Human size — "812 KB" / "2.3 MB". */
18
+ export function formatSize(bytes) {
19
+ if (bytes >= 1024 * 1024)
20
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
21
+ return `${Math.max(1, Math.round(bytes / 1024))} KB`;
22
+ }
23
+ /** Reuse an already-uploaded, unchanged local file (same path + size + mtime). */
24
+ function findDuplicate(ctx, absPath, size, mtime) {
25
+ const uploads = ctx.config.get("uploads") ?? [];
26
+ const hit = uploads.find((u) => u.local_path === absPath && u.size === size && u.mtime === mtime);
27
+ return hit?.file_id ?? null;
28
+ }
29
+ /** Filenames for the currently-attached file ids (for the footer / listings). */
30
+ export function attachedFilenames(ctx) {
31
+ const uploads = ctx.config.get("uploads") ?? [];
32
+ return ctx.attachedFileIds.map((id) => uploads.find((u) => u.file_id === id)?.filename ?? id);
33
+ }
34
+ /**
35
+ * Upload a local file (POST /v1/files) and, unless disabled, kick off indexing
36
+ * (POST /v1/files/:id/process). Reuses the existing file_id if the same unchanged
37
+ * file was already uploaded from this machine (no re-upload). Does NOT attach —
38
+ * the caller decides that (the shell auto-attaches; standalone asks). Throws
39
+ * UploadError with a friendly, ready-to-print message on any failure.
40
+ *
41
+ * Thin client only: no parsing, no indexing — the backend owns all of that.
42
+ */
43
+ export async function ensureUploaded(ctx, client, filePath, hooks = {}) {
44
+ const absPath = path.resolve(filePath);
45
+ const name = path.basename(absPath);
46
+ let stat;
47
+ try {
48
+ stat = fs.statSync(absPath);
49
+ }
50
+ catch {
51
+ throw new UploadError(`Couldn't find that file.\n Check the path and try again: ${filePath}`);
52
+ }
53
+ if (stat.isDirectory()) {
54
+ throw new UploadError(`That's a folder, not a file: ${filePath}`);
55
+ }
56
+ // Dedup — reuse the existing upload for the same unchanged file.
57
+ const dupId = findDuplicate(ctx, absPath, stat.size, Math.floor(stat.mtimeMs));
58
+ if (dupId) {
59
+ return {
60
+ fileId: dupId,
61
+ filename: name,
62
+ bytes: stat.size,
63
+ status: "existing",
64
+ wasAttached: ctx.attachedFileIds.includes(dupId)
65
+ };
66
+ }
67
+ hooks.onUploading?.();
68
+ let uploaded;
69
+ try {
70
+ uploaded = await client.uploadFile(absPath);
71
+ }
72
+ catch (err) {
73
+ throw new UploadError(friendlyUploadError(err));
74
+ }
75
+ ctx.config.addUpload({
76
+ file_id: uploaded.file_id,
77
+ filename: uploaded.filename,
78
+ file_type: uploaded.file_type,
79
+ uploaded_at: new Date().toISOString(),
80
+ local_path: absPath,
81
+ size: stat.size,
82
+ mtime: Math.floor(stat.mtimeMs)
83
+ });
84
+ hooks.onUploaded?.(uploaded.filename);
85
+ if (hooks.process !== false) {
86
+ hooks.onProcessing?.();
87
+ try {
88
+ await client.processFile(uploaded.file_id);
89
+ }
90
+ catch {
91
+ // Indexing is best-effort — the file is still usable once ready.
92
+ }
93
+ }
94
+ return {
95
+ fileId: uploaded.file_id,
96
+ filename: uploaded.filename,
97
+ bytes: stat.size,
98
+ status: "uploaded",
99
+ wasAttached: false
100
+ };
101
+ }
102
+ /** ensureUploaded + attach (the shell/auto flow — attaching is expected there). */
103
+ export async function uploadAndAttach(ctx, client, filePath, hooks = {}) {
104
+ const r = await ensureUploaded(ctx, client, filePath, hooks);
105
+ ctx.attachFile(r.fileId);
106
+ return r;
107
+ }
108
+ /** Map an API/local error to a friendly, actionable message. */
109
+ export function friendlyUploadError(err) {
110
+ if (err instanceof ApiError) {
111
+ switch (err.code) {
112
+ case "UNSUPPORTED_FILE_TYPE":
113
+ return `Carrier OS can't upload this file type.\n Supported: ${SUPPORTED}`;
114
+ case "FILE_TOO_LARGE":
115
+ return "This file exceeds the 25 MB upload limit.";
116
+ case "NO_ACCOUNT":
117
+ return "This account can't upload files — try `cos login` again.";
118
+ default:
119
+ return err.message || "Upload failed.";
120
+ }
121
+ }
122
+ if (err?.code === "ENOENT") {
123
+ return "Couldn't find that file. Check the path and try again.";
124
+ }
125
+ return err?.message || "Upload failed.";
126
+ }
@@ -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
+ }
@@ -0,0 +1,429 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { HARDENED_GIT_OPTIONS, hardenedGitEnv, neutralizingOverrides } from "./workspace.js";
3
+ /**
4
+ * Read-only Git for the developer tools `git_status` and `git_diff`.
5
+ *
6
+ * These are READS, like read_file — not commands. They never need
7
+ * `run_command` enabled, never prompt for approval, and never mutate. What they
8
+ * do need is the same hardening every Git call in this CLI uses, because a
9
+ * repository's own `.git/config` is attacker-controlled: cloning or unzipping a
10
+ * project is enough to plant a `filter`, an `fsmonitor` hook or an external
11
+ * diff driver that Git would otherwise run while reading the tree.
12
+ *
13
+ * So every call here goes through the shared hardening — global `-c` overrides,
14
+ * the per-repository program-key neutralization, and the no-prompt/no-lock
15
+ * environment — with argv arrays and no shell, exactly as workspace.ts does.
16
+ * The containment boundary is unchanged; this module only adds two read shapes
17
+ * on top of it. The caller resolves WHICH repository (name → trusted handle →
18
+ * root) before anything here runs; `root` is always a repository root.
19
+ */
20
+ const GIT_TIMEOUT_MS = 10_000;
21
+ /** A diff a person cannot read on a terminal is not one a model should hold either. */
22
+ const MAX_DIFF_BYTES = 120 * 1024;
23
+ /** Enough file entries to describe a change set; more is noise. */
24
+ const MAX_FILES = 1000;
25
+ export class GitToolError extends Error {
26
+ code;
27
+ constructor(code, message) {
28
+ super(message);
29
+ this.code = code;
30
+ this.name = "GitToolError";
31
+ }
32
+ }
33
+ /**
34
+ * One hardened Git invocation. `diffSafe` adds the per-command diff guards
35
+ * (`--no-ext-diff`, `--no-textconv`, `--no-color`) that `status` rejects but
36
+ * `diff` needs, so a diff never runs a repository-chosen textconv program.
37
+ */
38
+ function run(root, args, overrides) {
39
+ try {
40
+ const out = execFileSync("git", [...HARDENED_GIT_OPTIONS, ...overrides, ...args], {
41
+ cwd: root,
42
+ timeout: GIT_TIMEOUT_MS,
43
+ windowsHide: true,
44
+ encoding: "utf8",
45
+ env: hardenedGitEnv(),
46
+ stdio: ["ignore", "pipe", "pipe"],
47
+ maxBuffer: 16 * 1024 * 1024
48
+ });
49
+ return { ok: true, out: String(out) };
50
+ }
51
+ catch (err) {
52
+ const e = err;
53
+ const stderr = e.stderr ? String(e.stderr).trim() : "";
54
+ const reason = e.code === "ENOENT"
55
+ ? "Git is not installed."
56
+ : e.code === "ETIMEDOUT"
57
+ ? "Git timed out."
58
+ : (stderr.split(/\r?\n/).find((l) => l.trim()) ?? e.message ?? "Git failed.").replace(/^fatal:\s*/i, "");
59
+ return { ok: false, out: "", code: e.status, reason };
60
+ }
61
+ }
62
+ /**
63
+ * The program-key overrides for this repository, or throw.
64
+ *
65
+ * Throwing rather than proceeding is the safe default the descriptor uses too:
66
+ * if we cannot read the config to know which filter/diff-driver names to
67
+ * neutralize, we do not run the calls that would honour them.
68
+ */
69
+ function overridesFor(root) {
70
+ const overrides = neutralizingOverrides(root);
71
+ if (overrides === null) {
72
+ throw new GitToolError("GIT_UNAVAILABLE", "The repository's Git configuration could not be read safely.");
73
+ }
74
+ return overrides;
75
+ }
76
+ /**
77
+ * `git status --porcelain=v2 --branch`, parsed into structured state.
78
+ *
79
+ * porcelain v2 is stable and machine-first: each entry names its staged (X) and
80
+ * unstaged (Y) state, so "modified but not added" and "staged" are
81
+ * distinguishable — which the next phase's review needs. Submodules are ignored
82
+ * (each has its own config these overrides never saw).
83
+ */
84
+ export function gitStatus(root) {
85
+ const res = run(root, ["status", "--porcelain=v2", "--branch", "--ignore-submodules=all"], overridesFor(root));
86
+ if (!res.ok)
87
+ throw new GitToolError("GIT_FAILED", res.reason ?? "git status failed.");
88
+ const s = {
89
+ branch: null,
90
+ detached: false,
91
+ head: null,
92
+ upstream: null,
93
+ ahead: 0,
94
+ behind: 0,
95
+ clean: true,
96
+ hasCommits: false,
97
+ staged: [],
98
+ unstaged: [],
99
+ untracked: [],
100
+ renamed: [],
101
+ deleted: [],
102
+ truncated: false
103
+ };
104
+ let changes = 0;
105
+ let oid = null;
106
+ const push = (list, value) => {
107
+ if (list.length < MAX_FILES)
108
+ list.push(value);
109
+ else
110
+ s.truncated = true;
111
+ };
112
+ for (const raw of res.out.split(/\r?\n/)) {
113
+ if (!raw)
114
+ continue;
115
+ if (raw.startsWith("#")) {
116
+ const m = raw.match(/^# branch\.(oid|head|upstream|ab) (.+)$/);
117
+ if (!m)
118
+ continue;
119
+ if (m[1] === "oid") {
120
+ oid = m[2].trim();
121
+ s.hasCommits = oid !== "(initial)";
122
+ }
123
+ else if (m[1] === "head") {
124
+ const head = m[2].trim();
125
+ if (head === "(detached)")
126
+ s.detached = true;
127
+ else
128
+ s.branch = head;
129
+ }
130
+ else if (m[1] === "upstream")
131
+ s.upstream = m[2].trim();
132
+ else if (m[1] === "ab") {
133
+ const ab = m[2].match(/\+(\d+)\s+-(\d+)/);
134
+ if (ab) {
135
+ s.ahead = Number(ab[1]);
136
+ s.behind = Number(ab[2]);
137
+ }
138
+ }
139
+ continue;
140
+ }
141
+ // ? untracked
142
+ if (raw.startsWith("? ")) {
143
+ push(s.untracked, raw.slice(2));
144
+ changes += 1;
145
+ continue;
146
+ }
147
+ // 1 <XY> ... <path> changed (X = staged state, Y = unstaged state)
148
+ if (raw.startsWith("1 ")) {
149
+ const xy = raw.split(" ")[1] ?? "..";
150
+ const file = fieldAfter(raw, 8);
151
+ if (xy[0] !== ".")
152
+ push(s.staged, file);
153
+ if (xy[1] !== ".")
154
+ push(s.unstaged, file);
155
+ if (xy.includes("D"))
156
+ push(s.deleted, file);
157
+ changes += 1;
158
+ continue;
159
+ }
160
+ // 2 <XY> ... <path>\t<origPath> renamed/copied
161
+ if (raw.startsWith("2 ")) {
162
+ const xy = raw.split(" ")[1] ?? "..";
163
+ const tail = fieldAfter(raw, 9);
164
+ const [to, from] = tail.split("\t");
165
+ s.renamed.length < MAX_FILES ? s.renamed.push({ from: from ?? "", to: to ?? "" }) : (s.truncated = true);
166
+ if (xy[0] !== ".")
167
+ push(s.staged, to ?? "");
168
+ changes += 1;
169
+ continue;
170
+ }
171
+ // u ... unmerged (a conflict is a change)
172
+ if (raw.startsWith("u ")) {
173
+ push(s.unstaged, fieldAfter(raw, 10));
174
+ changes += 1;
175
+ }
176
+ }
177
+ // A detached HEAD has no branch name; the short commit is what identifies it.
178
+ if (s.detached && oid && s.hasCommits)
179
+ s.head = oid.slice(0, 7);
180
+ s.clean = changes === 0;
181
+ return s;
182
+ }
183
+ /**
184
+ * The Nth space-separated field to end of line — porcelain v2 paths are the
185
+ * last field and may contain spaces, so everything from field N on is the path.
186
+ */
187
+ function fieldAfter(line, n) {
188
+ let i = 0;
189
+ let field = 0;
190
+ while (field < n && i < line.length) {
191
+ if (line[i] === " ")
192
+ field += 1;
193
+ i += 1;
194
+ }
195
+ return line.slice(i);
196
+ }
197
+ /** The diff args for a scope. `both` is staged + unstaged, i.e. against HEAD. */
198
+ function diffArgs(scope) {
199
+ const guards = ["--no-color", "--no-ext-diff", "--no-textconv"];
200
+ if (scope === "staged")
201
+ return ["diff", "--cached", ...guards];
202
+ if (scope === "both")
203
+ return ["diff", "HEAD", ...guards];
204
+ return ["diff", ...guards];
205
+ }
206
+ /**
207
+ * A bounded, hardened diff for one repository.
208
+ *
209
+ * Counts come from `--numstat` (cheap, parseable); the patch text is captured
210
+ * separately and trimmed to MAX_DIFF_BYTES so a huge change set cannot swamp a
211
+ * turn. No approval, no mutation — it is a read.
212
+ */
213
+ export function gitDiff(root, scope = "working_tree") {
214
+ const overrides = overridesFor(root);
215
+ const stat = run(root, [...diffArgs(scope), "--numstat"], overrides);
216
+ if (!stat.ok) {
217
+ // A fresh repository has no HEAD, so `diff HEAD`/`both` cannot resolve one.
218
+ if (scope === "both" && /ambiguous argument 'HEAD'|unknown revision/i.test(stat.reason ?? "")) {
219
+ return gitDiff(root, "staged");
220
+ }
221
+ throw new GitToolError("GIT_FAILED", stat.reason ?? "git diff failed.");
222
+ }
223
+ let filesChanged = 0;
224
+ let additions = 0;
225
+ let deletions = 0;
226
+ for (const raw of stat.out.split(/\r?\n/)) {
227
+ if (!raw.trim())
228
+ continue;
229
+ filesChanged += 1;
230
+ const [add, del] = raw.split("\t");
231
+ if (add !== "-")
232
+ additions += Number(add) || 0;
233
+ if (del !== "-")
234
+ deletions += Number(del) || 0;
235
+ }
236
+ const patch = run(root, diffArgs(scope), overrides);
237
+ if (!patch.ok)
238
+ throw new GitToolError("GIT_FAILED", patch.reason ?? "git diff failed.");
239
+ let diff = patch.out;
240
+ let truncated = false;
241
+ if (Buffer.byteLength(diff, "utf8") > MAX_DIFF_BYTES) {
242
+ diff = diff.slice(0, MAX_DIFF_BYTES);
243
+ // Do not end mid-line — drop the partial last line.
244
+ diff = diff.slice(0, diff.lastIndexOf("\n") + 1) + "… [diff truncated]\n";
245
+ truncated = true;
246
+ }
247
+ return { scope, files_changed: filesChanged, additions, deletions, diff, truncated };
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
+ }