@carrieros/cli-staging 0.0.0-stage → 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 (136) hide show
  1. package/README.md +6 -2
  2. package/dist/commands/attach.js +45 -0
  3. package/dist/commands/auth.js +60 -0
  4. package/dist/commands/btw.js +78 -0
  5. package/dist/commands/changes.js +167 -0
  6. package/dist/commands/chat.js +182 -0
  7. package/dist/commands/context.js +200 -0
  8. package/dist/commands/doctor.js +119 -0
  9. package/dist/commands/files.js +94 -0
  10. package/dist/commands/help.js +37 -0
  11. package/dist/commands/history.js +112 -0
  12. package/dist/commands/login.js +62 -0
  13. package/dist/commands/logout.js +25 -0
  14. package/dist/commands/memory.js +162 -0
  15. package/dist/commands/mode-model.js +64 -0
  16. package/dist/commands/models.js +28 -0
  17. package/dist/commands/modes.js +30 -0
  18. package/dist/commands/permissions.js +77 -0
  19. package/dist/commands/project.js +106 -0
  20. package/dist/commands/repo.js +146 -0
  21. package/dist/commands/repos.js +61 -0
  22. package/dist/commands/review.js +92 -0
  23. package/dist/commands/scope.js +155 -0
  24. package/dist/commands/search.js +92 -0
  25. package/dist/commands/sessions.js +282 -0
  26. package/dist/commands/settings.js +100 -0
  27. package/dist/commands/update.js +229 -0
  28. package/dist/commands/upload.js +223 -0
  29. package/dist/commands/usage.js +227 -0
  30. package/dist/commands/version.js +26 -0
  31. package/dist/commands/whoami.js +44 -0
  32. package/dist/ide/editor-context.js +275 -0
  33. package/dist/ide/ide-session.js +360 -0
  34. package/dist/ide/tool-host.js +109 -0
  35. package/dist/main.js +126 -0
  36. package/dist/services/api.js +439 -0
  37. package/dist/services/auth-origin.js +20 -0
  38. package/dist/services/chat-stream.js +168 -0
  39. package/dist/services/checkpoints.js +278 -0
  40. package/dist/services/client-tools.js +356 -0
  41. package/dist/services/code-intel.js +243 -0
  42. package/dist/services/code-symbols.js +94 -0
  43. package/dist/services/coding-workflow.js +554 -0
  44. package/dist/services/command-coordinator.js +273 -0
  45. package/dist/services/command-policy.js +434 -0
  46. package/dist/services/config.js +383 -0
  47. package/dist/services/container-runner.js +254 -0
  48. package/dist/services/container-supervisor.js +38 -0
  49. package/dist/services/context.js +371 -0
  50. package/dist/services/device-auth.js +286 -0
  51. package/dist/services/diff.js +196 -0
  52. package/dist/services/env-policy.js +108 -0
  53. package/dist/services/execution-platform.js +30 -0
  54. package/dist/services/file-detect.js +104 -0
  55. package/dist/services/file-resolver.js +199 -0
  56. package/dist/services/file-upload.js +126 -0
  57. package/dist/services/folder-key.js +22 -0
  58. package/dist/services/git-tools.js +429 -0
  59. package/dist/services/glob-match.js +164 -0
  60. package/dist/services/helper-bin.js +85 -0
  61. package/dist/services/ignore-rules.js +189 -0
  62. package/dist/services/instruction-resolver.js +54 -0
  63. package/dist/services/job-helper.js +328 -0
  64. package/dist/services/local-files.js +639 -0
  65. package/dist/services/local-tools.js +937 -0
  66. package/dist/services/login-flow.js +156 -0
  67. package/dist/services/meta.js +15 -0
  68. package/dist/services/mutation-coordinator.js +327 -0
  69. package/dist/services/mutation-groups.js +309 -0
  70. package/dist/services/mutation-recovery.js +159 -0
  71. package/dist/services/mutations.js +679 -0
  72. package/dist/services/open-url.js +68 -0
  73. package/dist/services/output.js +62 -0
  74. package/dist/services/packaged-update.js +403 -0
  75. package/dist/services/packaged.js +39 -0
  76. package/dist/services/permission-mode.js +78 -0
  77. package/dist/services/process-runner.js +412 -0
  78. package/dist/services/project-context.js +298 -0
  79. package/dist/services/redaction.js +201 -0
  80. package/dist/services/result-reconciliation.js +49 -0
  81. package/dist/services/secure-store.js +217 -0
  82. package/dist/services/session-resolver.js +113 -0
  83. package/dist/services/sia.js +51 -0
  84. package/dist/services/spinner.js +40 -0
  85. package/dist/services/supported-runtime.js +59 -0
  86. package/dist/services/task-context.js +212 -0
  87. package/dist/services/task-snapshot.js +38 -0
  88. package/dist/services/tool-result-outbox.js +195 -0
  89. package/dist/services/update.js +311 -0
  90. package/dist/services/workspace-registry.js +310 -0
  91. package/dist/services/workspace.js +580 -0
  92. package/dist/shell/shell-chat.js +1619 -0
  93. package/dist/shell/shell-commands.js +411 -0
  94. package/dist/shell/shell-prompt.js +110 -0
  95. package/dist/shell/shell-renderer.js +51 -0
  96. package/dist/shell/shell-router.js +37 -0
  97. package/dist/shell/shell.js +389 -0
  98. package/dist/shell/task-context-view.js +40 -0
  99. package/dist/staging.js +5 -0
  100. package/dist/types/index.js +6 -0
  101. package/dist/ui/agent-cards.js +111 -0
  102. package/dist/ui/agent-presentation.js +131 -0
  103. package/dist/ui/approval.js +111 -0
  104. package/dist/ui/banner.js +56 -0
  105. package/dist/ui/btw-overlay.js +230 -0
  106. package/dist/ui/change-review.js +334 -0
  107. package/dist/ui/chat-renderer.js +463 -0
  108. package/dist/ui/code-block.js +52 -0
  109. package/dist/ui/color-picker.js +100 -0
  110. package/dist/ui/colors.js +55 -0
  111. package/dist/ui/command-details.js +11 -0
  112. package/dist/ui/command-filter.js +92 -0
  113. package/dist/ui/command-item.js +6 -0
  114. package/dist/ui/command-palette.js +383 -0
  115. package/dist/ui/command-registry.js +128 -0
  116. package/dist/ui/command-renderer.js +55 -0
  117. package/dist/ui/command-review.js +187 -0
  118. package/dist/ui/composer-layout.js +74 -0
  119. package/dist/ui/conversation.js +450 -0
  120. package/dist/ui/interrupt.js +35 -0
  121. package/dist/ui/live.js +141 -0
  122. package/dist/ui/logo.js +58 -0
  123. package/dist/ui/markdown.js +205 -0
  124. package/dist/ui/message.js +21 -0
  125. package/dist/ui/screen-prompt.js +181 -0
  126. package/dist/ui/screen.js +297 -0
  127. package/dist/ui/select.js +284 -0
  128. package/dist/ui/sia-qa.js +213 -0
  129. package/dist/ui/spinner.js +23 -0
  130. package/dist/ui/sticky-stream.js +64 -0
  131. package/dist/ui/task-context-card.js +99 -0
  132. package/dist/ui/text-prompt.js +74 -0
  133. package/dist/ui/theme.js +80 -0
  134. package/dist/ui/trust.js +88 -0
  135. package/dist/ui/ui.js +101 -0
  136. package/package.json +33 -4
@@ -0,0 +1,311 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { cliVersion } from "./meta.js";
6
+ /**
7
+ * CLI update management over npm — the CLI's only distribution channel.
8
+ *
9
+ * Pure logic: version resolution, comparison, the linked-checkout guard and the
10
+ * install call. Nothing here prints; commands/update.ts owns every message, so
11
+ * the shell command and `cos update` render identically from one source.
12
+ *
13
+ * Deliberately NOT here: downloading anything, restarting the process, hot
14
+ * reloading, or writing into the installed package. npm performs the
15
+ * replacement; this only asks it to.
16
+ */
17
+ /** The only package this will ever install. Never built from user input. */
18
+ export const PACKAGE_NAME = "@carrieros/cli";
19
+ /** npm is invoked by name with an argument array, never through a shell, so no
20
+ * version string can be interpolated into a command line. */
21
+ const NPM_BIN = process.platform === "win32" ? "npm.cmd" : "npm";
22
+ /**
23
+ * Windows needs `shell: true` to launch npm at all — since the CVE-2024-27980
24
+ * hardening, Node refuses to spawn a .cmd directly and returns EINVAL. That is
25
+ * safe HERE only because every argument this file passes is a compile-time
26
+ * constant: no version string, path or user input is ever interpolated into a
27
+ * command line. Keep it that way.
28
+ */
29
+ const SPAWN_SHELL = process.platform === "win32";
30
+ /**
31
+ * Run npm and hand back the raw result.
32
+ *
33
+ * On Windows the command goes through a shell as ONE string: passing an args
34
+ * array alongside `shell: true` triggers Node's DEP0190 warning (args are
35
+ * concatenated, not escaped) and that warning would print into the user's
36
+ * terminal. Every argument here is a compile-time constant, so concatenation is
37
+ * safe — but that is exactly why nothing dynamic may ever be added to `args`.
38
+ */
39
+ function runNpm(args, timeout) {
40
+ const opts = { encoding: "utf8", timeout, windowsHide: true };
41
+ return SPAWN_SHELL
42
+ ? spawnSync([NPM_BIN, ...args].join(" "), { ...opts, shell: true })
43
+ : spawnSync(NPM_BIN, args, opts);
44
+ }
45
+ const VIEW_TIMEOUT_MS = 20000;
46
+ const INSTALL_TIMEOUT_MS = 180000;
47
+ export function getCurrentVersion() {
48
+ return cliVersion();
49
+ }
50
+ /**
51
+ * Compare semver numerically.
52
+ *
53
+ * Lexical comparison gets 0.10.0 vs 0.9.0 wrong — the case that appears the
54
+ * moment a project passes its ninth minor. Prereleases sort BELOW their release
55
+ * (1.0.0-rc.1 < 1.0.0). Numeric prerelease identifiers compare numerically and
56
+ * sort below nonnumeric identifiers. Build metadata does not affect precedence.
57
+ */
58
+ export function compareVersions(a, b) {
59
+ const parse = (v) => {
60
+ const normalized = String(v).trim().replace(/^v/, "");
61
+ if (!isVersionLike(normalized))
62
+ throw new Error(`Invalid version: ${v}`);
63
+ const version = normalized.split("+", 1)[0];
64
+ const dash = version.indexOf("-");
65
+ const core = dash === -1 ? version : version.slice(0, dash);
66
+ return {
67
+ nums: core.split(".").map((n) => BigInt(n)),
68
+ pre: dash === -1 ? [] : version.slice(dash + 1).split(".")
69
+ };
70
+ };
71
+ const x = parse(a);
72
+ const y = parse(b);
73
+ for (let i = 0; i < 3; i++) {
74
+ if (x.nums[i] !== y.nums[i])
75
+ return x.nums[i] < y.nums[i] ? -1 : 1;
76
+ }
77
+ if (!x.pre.length && !y.pre.length)
78
+ return 0;
79
+ if (!x.pre.length)
80
+ return 1;
81
+ if (!y.pre.length)
82
+ return -1;
83
+ for (let i = 0; i < Math.max(x.pre.length, y.pre.length); i++) {
84
+ const left = x.pre[i];
85
+ const right = y.pre[i];
86
+ if (left === undefined)
87
+ return -1;
88
+ if (right === undefined)
89
+ return 1;
90
+ if (left === right)
91
+ continue;
92
+ const leftNumeric = /^\d+$/.test(left);
93
+ const rightNumeric = /^\d+$/.test(right);
94
+ if (leftNumeric && rightNumeric)
95
+ return BigInt(left) < BigInt(right) ? -1 : 1;
96
+ if (leftNumeric !== rightNumeric)
97
+ return leftNumeric ? -1 : 1;
98
+ return left < right ? -1 : 1;
99
+ }
100
+ return 0;
101
+ }
102
+ /** Guards every version that reaches a comparison or a message. */
103
+ export function isVersionLike(v) {
104
+ if (typeof v !== "string")
105
+ return false;
106
+ const match = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/.exec(v.trim());
107
+ return !!match && (!match[4] || match[4].split(".").every((id) => !/^\d+$/.test(id) || id === "0" || !id.startsWith("0")));
108
+ }
109
+ export function getLatestVersion() {
110
+ let res;
111
+ try {
112
+ res = runNpm(["view", PACKAGE_NAME, "version", "--json"], VIEW_TIMEOUT_MS);
113
+ }
114
+ catch (err) {
115
+ return { ok: false, reason: "failed", detail: err.message };
116
+ }
117
+ // ENOENT means npm is missing from PATH — a different problem from a
118
+ // registry failure, and it needs different advice.
119
+ if (res.error && res.error.code === "ENOENT") {
120
+ return { ok: false, reason: "no-npm", detail: "npm was not found on this system." };
121
+ }
122
+ if (res.error)
123
+ return { ok: false, reason: "failed", detail: res.error.message };
124
+ if (res.status !== 0) {
125
+ const first = String(res.stderr || res.stdout || "").trim().split("\n")[0];
126
+ return { ok: false, reason: "failed", detail: first || "npm exited with code " + res.status };
127
+ }
128
+ // --json yields a quoted string for one version, a bare string under some
129
+ // configs, and an array when several match. Accept all three.
130
+ const raw = String(res.stdout || "").trim();
131
+ let parsed = raw;
132
+ try {
133
+ parsed = JSON.parse(raw);
134
+ }
135
+ catch {
136
+ parsed = raw.replace(/^"|"$/g, "");
137
+ }
138
+ if (Array.isArray(parsed))
139
+ parsed = parsed[parsed.length - 1];
140
+ const version = typeof parsed === "string" ? parsed.trim() : "";
141
+ if (!isVersionLike(version)) {
142
+ return { ok: false, reason: "failed", detail: "Unexpected npm output: " + raw.slice(0, 80) };
143
+ }
144
+ return { ok: true, version };
145
+ }
146
+ export function checkForUpdate() {
147
+ const current = getCurrentVersion();
148
+ const latest = getLatestVersion();
149
+ if (!latest.ok) {
150
+ return latest.reason === "no-npm"
151
+ ? { kind: "no-npm", current }
152
+ : { kind: "unreachable", current, detail: latest.detail };
153
+ }
154
+ const cmp = compareVersions(current, latest.version);
155
+ if (cmp === 0)
156
+ return { kind: "current", current, latest: latest.version };
157
+ return cmp < 0
158
+ ? { kind: "available", current, latest: latest.version }
159
+ : { kind: "ahead", current, latest: latest.version };
160
+ }
161
+ /** Absolute path of the package this process runs from. */
162
+ export function packageRoot() {
163
+ try {
164
+ return path.resolve(fileURLToPath(new URL("../..", import.meta.url)));
165
+ }
166
+ catch {
167
+ return null;
168
+ }
169
+ }
170
+ function npmGlobalRoot() {
171
+ try {
172
+ const res = runNpm(["root", "-g"], VIEW_TIMEOUT_MS);
173
+ if (res.status !== 0)
174
+ return null;
175
+ const out = String(res.stdout || "").trim();
176
+ return out ? path.resolve(out) : null;
177
+ }
178
+ catch {
179
+ return null;
180
+ }
181
+ }
182
+ /** Windows paths differ only in case, so containment compares case-folded. */
183
+ function isInside(parent, child) {
184
+ const rel = path.relative(parent.toLowerCase(), child.toLowerCase());
185
+ return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
186
+ }
187
+ /**
188
+ * True when the global package is a link to a working copy (npm link).
189
+ *
190
+ * MANDATORY GUARD: `npm i -g` against a linked install replaces the symlink and
191
+ * the developer silently loses the link to their checkout. Two independent
192
+ * signals, either conclusive:
193
+ * 1. the global package path is itself a symlink;
194
+ * 2. this process runs from outside the global npm root, so updating the
195
+ * global copy would not change what is executing anyway.
196
+ */
197
+ export function isLinkedInstallation() {
198
+ const globalRoot = npmGlobalRoot();
199
+ if (!globalRoot)
200
+ return false;
201
+ const installed = path.join(globalRoot, ...PACKAGE_NAME.split("/"));
202
+ try {
203
+ if (fs.lstatSync(installed).isSymbolicLink())
204
+ return true;
205
+ }
206
+ catch {
207
+ /* not installed globally — fall through to the location check */
208
+ }
209
+ const here = packageRoot();
210
+ return here ? !isInside(globalRoot, here) : false;
211
+ }
212
+ /**
213
+ * Install the latest published version.
214
+ *
215
+ * `install @latest`, never `npm update`: the intent is "give me the published
216
+ * latest", and update obeys semver ranges instead.
217
+ */
218
+ export function installLatest() {
219
+ let res;
220
+ try {
221
+ res = runNpm(["install", "-g", PACKAGE_NAME + "@latest"], INSTALL_TIMEOUT_MS);
222
+ }
223
+ catch (err) {
224
+ return { ok: false, detail: err.message, permission: false };
225
+ }
226
+ if (res.error) {
227
+ const code = res.error.code;
228
+ return {
229
+ ok: false,
230
+ detail: code === "ENOENT" ? "npm was not found on this system." : res.error.message,
231
+ permission: false
232
+ };
233
+ }
234
+ const output = (String(res.stdout || "") + "\n" + String(res.stderr || "")).trim();
235
+ if (res.status === 0)
236
+ return { ok: true, detail: output, permission: false };
237
+ return {
238
+ ok: false,
239
+ detail: lastMeaningfulLines(output) || "npm exited with code " + res.status,
240
+ permission: /EACCES|EPERM|permission denied|Access is denied/i.test(output)
241
+ };
242
+ }
243
+ /**
244
+ * What is on disk now.
245
+ *
246
+ * The running process cannot answer this — its own package.json is already read
247
+ * and the old modules stay loaded — so this reads the freshly installed
248
+ * package.json from the global root rather than trusting cliVersion().
249
+ */
250
+ export function verifyInstallation() {
251
+ const globalRoot = npmGlobalRoot();
252
+ if (!globalRoot)
253
+ return null;
254
+ try {
255
+ const pkg = path.join(globalRoot, ...PACKAGE_NAME.split("/"), "package.json");
256
+ const parsed = JSON.parse(fs.readFileSync(pkg, "utf8"));
257
+ return isVersionLike(parsed.version) ? parsed.version : null;
258
+ }
259
+ catch {
260
+ return null;
261
+ }
262
+ }
263
+ /** The last few actionable lines of npm output — enough to act on, not a wall. */
264
+ function lastMeaningfulLines(output, max = 6) {
265
+ return output
266
+ .split(/\r?\n/)
267
+ .map((l) => l.trim())
268
+ .filter((l) => l && !/^npm (notice|warn) /i.test(l))
269
+ .slice(-max)
270
+ .join("\n");
271
+ }
272
+ // ── Startup notice ───────────────────────────────────────────────────────────
273
+ // The banner renders once, and rewriting it later would mean mutating the
274
+ // screen engine mid-frame. So the notice is built from the PREVIOUS check and a
275
+ // fresh one runs afterwards, off the startup path — a new release is announced
276
+ // on the next launch, and startup is never delayed or failed by npm.
277
+ /** How long a cached result stays good. */
278
+ const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
279
+ /** Notice line for the banner, or null when current / unknown. */
280
+ export function cachedUpdateNotice(cache) {
281
+ const latest = cache.get("latestCliVersion");
282
+ if (!isVersionLike(latest))
283
+ return null;
284
+ return compareVersions(getCurrentVersion(), latest) < 0
285
+ ? "Update available: v" + latest + " — run /update to upgrade."
286
+ : null;
287
+ }
288
+ /** True when the cached result is stale enough to re-check. */
289
+ export function shouldRefreshCheck(cache, now = Date.now()) {
290
+ const ok = cache.get("updateCheckAt") ?? 0;
291
+ const failed = cache.get("updateCheckErrorAt") ?? 0;
292
+ // A failure also starts the clock, so an offline machine retries once a day
293
+ // instead of shelling out to npm on every launch.
294
+ return now - Math.max(ok, failed) >= CHECK_INTERVAL_MS;
295
+ }
296
+ /**
297
+ * Refresh the cache. Call AFTER the shell is up — spawnSync blocks, so this
298
+ * must never sit between the user and their prompt.
299
+ */
300
+ export function refreshUpdateCache(cache, now = Date.now()) {
301
+ const latest = getLatestVersion();
302
+ if (latest.ok) {
303
+ cache.set("latestCliVersion", latest.version);
304
+ cache.set("updateCheckAt", now);
305
+ }
306
+ else {
307
+ // Recorded, never shown: a background check that fails is not the user's
308
+ // problem, and surfacing it every launch would be noise.
309
+ cache.set("updateCheckErrorAt", now);
310
+ }
311
+ }
@@ -0,0 +1,310 @@
1
+ import { isTrustedFolder } from "./folder-key.js";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { describeRepository, getCurrentDirectory, getWorkspace } from "./workspace.js";
5
+ export class RepositoryError extends Error {
6
+ code;
7
+ constructor(code, message) {
8
+ super(message);
9
+ this.code = code;
10
+ this.name = "RepositoryError";
11
+ }
12
+ }
13
+ /** Selector syntax: a name from the registry. No separators, no traversal. */
14
+ const SELECTOR = /^[A-Za-z0-9][A-Za-z0-9._@+-]{0,63}$/;
15
+ /** How many direct children are worth stat-ing for a `.git` entry. */
16
+ const MAX_SCAN_ENTRIES = 200;
17
+ /**
18
+ * Containment test, duplicated from local-files on purpose: that module asks
19
+ * the registry which repository is active, so the registry must not import it
20
+ * back. Four lines is a cheaper price than a module cycle.
21
+ */
22
+ function isInsideRoot(root, candidate) {
23
+ const norm = (p) => (process.platform === "win32" ? path.resolve(p).toLowerCase() : path.resolve(p));
24
+ const r = norm(root);
25
+ const c = norm(candidate);
26
+ return c === r || c.startsWith(r.endsWith(path.sep) ? r : r + path.sep);
27
+ }
28
+ function isGitRoot(dir) {
29
+ try {
30
+ return fs.existsSync(path.join(dir, ".git"));
31
+ }
32
+ catch {
33
+ return false;
34
+ }
35
+ }
36
+ /** A selector-safe id for a folder name: lowercase, no separators. */
37
+ export function repositoryId(name) {
38
+ const id = name
39
+ .trim()
40
+ .toLowerCase()
41
+ .replace(/[^a-z0-9._@+-]+/g, "-")
42
+ .replace(/^-+|-+$/g, "")
43
+ .slice(0, 64);
44
+ return id || "repository";
45
+ }
46
+ function handleFor(root) {
47
+ const abs = path.resolve(root);
48
+ const name = path.basename(abs) || abs;
49
+ return { id: repositoryId(name), name, root: abs, git: isGitRoot(abs) };
50
+ }
51
+ /**
52
+ * Direct child repositories of `dir`, sorted by name.
53
+ *
54
+ * Direct children only, and only real Git roots. No deep scan: a recursive
55
+ * search would wander into `node_modules`, vendored trees and anything a
56
+ * repository happens to contain, and "what is in my workspace" is a question
57
+ * about the folder you opened, not about everything under it.
58
+ */
59
+ export function discoverChildRepositories(dir) {
60
+ let entries;
61
+ try {
62
+ entries = fs.readdirSync(dir, { withFileTypes: true });
63
+ }
64
+ catch {
65
+ return [];
66
+ }
67
+ const found = [];
68
+ for (const entry of entries.slice(0, MAX_SCAN_ENTRIES)) {
69
+ // Symlinked directories are not followed — the same rule the walker uses.
70
+ if (!entry.isDirectory() || entry.isSymbolicLink())
71
+ continue;
72
+ if (entry.name.startsWith("."))
73
+ continue;
74
+ const child = path.join(dir, entry.name);
75
+ if (isGitRoot(child))
76
+ found.push(handleFor(child));
77
+ }
78
+ return found.sort((a, b) => a.name.localeCompare(b.name));
79
+ }
80
+ /**
81
+ * Decide the mode for a launch directory.
82
+ *
83
+ * Workspace mode needs BOTH conditions from the design: the launch directory is
84
+ * not itself a repository, and it holds at least two. Anything else — inside a
85
+ * repository, a plain folder, a folder with a single repository in it — keeps
86
+ * the single-root behaviour the CLI has always had.
87
+ */
88
+ function build(cwd) {
89
+ const ws = getWorkspace();
90
+ if (ws.repository.state === "detected" && ws.repository.root) {
91
+ const active = handleFor(ws.repository.root);
92
+ return { mode: "single", workspaceRoot: null, repositories: [active], activeId: active.id };
93
+ }
94
+ const children = discoverChildRepositories(cwd);
95
+ if (children.length >= 2) {
96
+ // Deterministic default: the first repository by name. Explicit selection
97
+ // (`/repo use`) is how you get anything else — guessing from mtimes would
98
+ // make the same command mean different things on different days.
99
+ return { mode: "workspace", workspaceRoot: path.resolve(cwd), repositories: children, activeId: children[0].id };
100
+ }
101
+ const active = handleFor(cwd);
102
+ return { mode: "single", workspaceRoot: null, repositories: [active], activeId: active.id };
103
+ }
104
+ let registry = null;
105
+ let config = null;
106
+ /**
107
+ * An EXPLICIT set of repository roots, or null for cwd-based discovery.
108
+ *
109
+ * Set by a host that already knows its repositories — a VS Code multi-root
110
+ * workspace, whose `workspaceFolders` ARE the repositories. When set, the
111
+ * registry scans nothing: exactly these folders become the repositories. The
112
+ * CLI never sets it, so its cwd discovery is unchanged.
113
+ */
114
+ let explicitRoots = null;
115
+ const detailCache = new Map();
116
+ /** Give the registry access to trust state. Called once at startup. */
117
+ export function attachConfig(store) {
118
+ config = store;
119
+ }
120
+ /**
121
+ * Register an EXPLICIT set of repository roots — the folders VS Code reports for
122
+ * a multi-root workspace. Nothing is scanned or auto-discovered: each folder,
123
+ * exactly as supplied, becomes one repository contained to its own root. Trust
124
+ * (`repositoryTrust`), containment (`resolveInside`/realpath) and selector rules
125
+ * are all unchanged — this only chooses WHICH roots exist. `activeRoot` (a folder
126
+ * or a file path within one) picks the active repository; it defaults to the
127
+ * first. Passing no usable root reverts to cwd discovery.
128
+ */
129
+ export function setWorkspaceRoots(roots, activeRoot) {
130
+ const unique = [];
131
+ const seen = new Set();
132
+ for (const r of roots ?? []) {
133
+ if (typeof r !== "string" || !r.trim())
134
+ continue;
135
+ const abs = path.resolve(r);
136
+ const key = process.platform === "win32" ? abs.toLowerCase() : abs;
137
+ if (seen.has(key))
138
+ continue;
139
+ seen.add(key);
140
+ unique.push(abs);
141
+ }
142
+ explicitRoots = unique.length ? unique : null;
143
+ registry = explicitRoots ? buildFromRoots(explicitRoots, activeRoot) : build(getCurrentDirectory());
144
+ detailCache.clear();
145
+ return registry;
146
+ }
147
+ /** Revert to cwd-based discovery (the CLI default); forget any explicit roots. */
148
+ export function clearWorkspaceRoots() {
149
+ explicitRoots = null;
150
+ registry = null;
151
+ detailCache.clear();
152
+ }
153
+ /** Build a registry from an explicit list of roots (no scanning). */
154
+ function buildFromRoots(roots, activeRoot) {
155
+ if (roots.length === 0)
156
+ return build(getCurrentDirectory());
157
+ const handles = [];
158
+ const ids = new Set();
159
+ for (const root of roots) {
160
+ const handle = handleFor(root);
161
+ // Two folders can share a basename; keep the first stable id, exactly as
162
+ // the selector lookup would resolve it.
163
+ if (ids.has(handle.id))
164
+ continue;
165
+ ids.add(handle.id);
166
+ handles.push(handle);
167
+ }
168
+ const mode = handles.length >= 2 ? "workspace" : "single";
169
+ let activeId = handles[0].id;
170
+ if (activeRoot) {
171
+ const abs = path.resolve(activeRoot);
172
+ // Deepest containing root wins, so a file inside a nested repo picks it.
173
+ const containing = handles
174
+ .filter((h) => isInsideRoot(h.root, abs))
175
+ .sort((a, b) => b.root.length - a.root.length)[0];
176
+ if (containing)
177
+ activeId = containing.id;
178
+ }
179
+ // No single workspaceRoot for a multi-root set — there is no common parent,
180
+ // and it is display-only anyway.
181
+ return { mode, workspaceRoot: null, repositories: handles, activeId };
182
+ }
183
+ export function getRegistry() {
184
+ if (!registry)
185
+ registry = explicitRoots ? buildFromRoots(explicitRoots) : build(getCurrentDirectory());
186
+ return registry;
187
+ }
188
+ /** Re-scan (after a `/repo use` that should see a newly cloned sibling, say). */
189
+ export function refreshRegistry() {
190
+ const previous = registry?.activeId;
191
+ registry = explicitRoots ? buildFromRoots(explicitRoots) : build(getCurrentDirectory());
192
+ detailCache.clear();
193
+ if (previous && registry.repositories.some((r) => r.id === previous))
194
+ registry.activeId = previous;
195
+ return registry;
196
+ }
197
+ export function inWorkspaceMode() {
198
+ return getRegistry().mode === "workspace";
199
+ }
200
+ export function listRepositories() {
201
+ return [...getRegistry().repositories];
202
+ }
203
+ export function activeRepository() {
204
+ const reg = getRegistry();
205
+ return reg.repositories.find((r) => r.id === reg.activeId) ?? reg.repositories[0];
206
+ }
207
+ /** True for the one selector that means "every repository". */
208
+ export function isWildcardSelector(selector) {
209
+ return selector === "*";
210
+ }
211
+ /**
212
+ * Turn a model- or user-supplied selector into a repository.
213
+ *
214
+ * The selector is matched against the registry by id or name. It is never
215
+ * treated as a path: `../other`, `C:\x`, `a/b` and `..` all fail the selector
216
+ * pattern before any lookup happens, so there is no way to reach a directory
217
+ * that is not a registered repository.
218
+ */
219
+ export function resolveRepository(selector) {
220
+ if (selector === undefined || selector === null || selector === "")
221
+ return activeRepository();
222
+ if (typeof selector !== "string") {
223
+ throw new RepositoryError("INVALID_REPOSITORY", "A repository must be named as a string.");
224
+ }
225
+ const raw = selector.trim();
226
+ if (isWildcardSelector(raw)) {
227
+ throw new RepositoryError("REPOSITORY_WILDCARD_NOT_ALLOWED", 'Only list_files and search_files accept repository "*".');
228
+ }
229
+ if (!SELECTOR.test(raw)) {
230
+ throw new RepositoryError("INVALID_REPOSITORY", `"${raw.slice(0, 40)}" is not a repository name. Name a repository from this workspace, not a path.`);
231
+ }
232
+ const wanted = raw.toLowerCase();
233
+ const found = getRegistry().repositories.find((r) => r.id === wanted || r.name.toLowerCase() === wanted);
234
+ if (!found) {
235
+ const names = listRepositories()
236
+ .map((r) => r.name)
237
+ .join(", ");
238
+ throw new RepositoryError("UNKNOWN_REPOSITORY", `No repository named "${raw}" in this workspace. Available: ${names}.`);
239
+ }
240
+ return found;
241
+ }
242
+ /** Select the active repository. Same resolution rules as everything else. */
243
+ export function setActiveRepository(selector) {
244
+ const handle = resolveRepository(selector);
245
+ getRegistry().activeId = handle.id;
246
+ return handle;
247
+ }
248
+ /** The repository a path belongs to, or null when it is outside all of them. */
249
+ export function repositoryForPath(absolutePath) {
250
+ const abs = path.resolve(absolutePath);
251
+ // Deepest root wins, so a repository nested inside another claims its files.
252
+ return ([...listRepositories()]
253
+ .filter((r) => isInsideRoot(r.root, abs))
254
+ .sort((a, b) => b.root.length - a.root.length)[0] ?? null);
255
+ }
256
+ /** Trust is per repository: registering a workspace grants nothing. */
257
+ export function repositoryTrust(handle) {
258
+ // The same canonical comparison as the trust prompt (ui/trust.ts), so a
259
+ // folder trusted under one spelling is the same folder here.
260
+ return isTrustedFolder(config?.get("trustedFolders") ?? [], handle.root) ? "trusted" : "untrusted";
261
+ }
262
+ /**
263
+ * Resolve a repository that an operation may ACT on — a change or a command.
264
+ *
265
+ * Two rules beyond plain resolution, and both are the point of this function:
266
+ *
267
+ * • the wildcard is refused, because "every repository" is not something a
268
+ * person can approve or a runner can contain; and
269
+ * • the repository must be TRUSTED in its own right. Trust is the moment the
270
+ * user said Carrier OS may touch this code, and it is granted per
271
+ * repository. A model naming a sibling must not be a way around the prompt
272
+ * the user would have seen if they had opened it.
273
+ *
274
+ * It deliberately does NOT require the repository to be active: an explicitly
275
+ * named, registered, trusted repository is a legitimate target, and the user
276
+ * still approves the individual operation with that name in front of them.
277
+ */
278
+ export function resolveOperableRepository(selector) {
279
+ const handle = resolveRepository(selector);
280
+ if (repositoryTrust(handle) !== "trusted") {
281
+ throw new RepositoryError("REPOSITORY_NOT_TRUSTED", `${handle.name} is not a trusted repository. Ask the user to run /repo use ${handle.name} and confirm the trust prompt first.`);
282
+ }
283
+ return handle;
284
+ }
285
+ /** Branch, status, project type and trust — read lazily, cached per process. */
286
+ export function repositoryDetails(handle, refresh = false) {
287
+ const cached = detailCache.get(handle.root);
288
+ if (cached && !refresh)
289
+ return { ...cached, trust: repositoryTrust(handle) };
290
+ const described = describeRepository(handle.root);
291
+ const details = {
292
+ branch: described.branch,
293
+ status: described.status,
294
+ projectType: described.projectType,
295
+ projectLabel: described.projectLabel,
296
+ trust: repositoryTrust(handle)
297
+ };
298
+ detailCache.set(handle.root, details);
299
+ return details;
300
+ }
301
+ /** Details already known, without spawning Git. For the footer. */
302
+ export function peekRepositoryDetails(handle) {
303
+ const cached = detailCache.get(handle.root);
304
+ return cached ? { ...cached, trust: repositoryTrust(handle) } : null;
305
+ }
306
+ /** Test seam: forget the discovered registry (used when cwd changes in tests). */
307
+ export function resetRegistry() {
308
+ registry = null;
309
+ detailCache.clear();
310
+ }