@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,100 @@
1
+ import { COMMANDS_OPT_IN_ENV, localCommandsState } from "../services/client-tools.js";
2
+ import { getPermissionMode } from "../services/permission-mode.js";
3
+ import { errorLine, line } from "../services/output.js";
4
+ import { c } from "../ui/colors.js";
5
+ import { sectionHeader } from "../ui/ui.js";
6
+ import { executionAdapter, executionPlatform } from "../services/execution-platform.js";
7
+ /**
8
+ * `cos settings` — the CLI's persisted behaviour settings, in one place.
9
+ *
10
+ * /settings show them
11
+ * /settings commands on|off allow or stop local commands (run_command)
12
+ *
13
+ * Most settings already have their own toggle (/fast, /hipwr, /sia, /websearch)
14
+ * and keep it; this command lists them together and owns the one setting that
15
+ * had no home: whether the model may propose commands in Manual/Accept Edits.
16
+ * Selecting Auto also opts in for that session; an explicit `commands off`
17
+ * remains a hard stop.
18
+ */
19
+ export function registerSettings(program, ctx) {
20
+ program
21
+ .command("settings")
22
+ .argument("[setting]", 'the setting to change, e.g. "commands"')
23
+ .argument("[value]", "on or off")
24
+ .description("Show or change CLI settings (e.g. settings commands on)")
25
+ .action((setting, value) => {
26
+ runSettings(ctx, [setting, value].filter(Boolean).join(" "));
27
+ });
28
+ }
29
+ const ON = new Set(["on", "yes", "true", "enable", "enabled"]);
30
+ const OFF = new Set(["off", "no", "false", "disable", "disabled"]);
31
+ export function runSettings(ctx, argStr) {
32
+ const [name = "", value = ""] = argStr.trim().toLowerCase().split(/\s+/);
33
+ if (!name)
34
+ return showSettings(ctx);
35
+ if (name !== "commands" && name !== "local-commands") {
36
+ errorLine(`Unknown setting "${name}". Try: /settings commands on|off`);
37
+ return;
38
+ }
39
+ if (!ON.has(value) && !OFF.has(value)) {
40
+ errorLine("Use /settings commands on or /settings commands off.");
41
+ return;
42
+ }
43
+ const enable = ON.has(value);
44
+ ctx.config.set("localCommandsEnabled", enable);
45
+ line();
46
+ if (enable) {
47
+ line(" " + c.ok("✓") + " " + c.value("Local commands enabled."));
48
+ // Said plainly at the moment it is switched on: what a command can do.
49
+ const notice = executionAdapter(executionPlatform()) === "windows-job" ? LOCAL_COMMANDS_NOTICE : [
50
+ ...LOCAL_COMMANDS_NOTICE.slice(0, 3),
51
+ "Approved project code runs in a configured isolated Linux container.",
52
+ "Only the selected repository is mounted; network access is disabled.",
53
+ LOCAL_COMMANDS_NOTICE[LOCAL_COMMANDS_NOTICE.length - 1]
54
+ ];
55
+ for (const l of notice)
56
+ line(" " + c.dim(l));
57
+ }
58
+ else {
59
+ line(" " + c.ok("✓") + " " + c.value("Local commands disabled.") + " " + c.dim("The model can still read, search and propose file changes."));
60
+ }
61
+ line();
62
+ }
63
+ /**
64
+ * What enabling local commands means, in the user's terms. Shown when it is
65
+ * switched on — not buried in documentation — because it is the one decision
66
+ * here that lets project code run.
67
+ */
68
+ export const LOCAL_COMMANDS_NOTICE = [
69
+ "Manual/Accept Edits may now propose local commands such as npm test or git status.",
70
+ "Manual asks before each command; Auto opts in and runs locally allowed commands without an individual prompt.",
71
+ "Commands only run in a trusted repository and remain subject to the allowlist,",
72
+ "runtime containment and cancellation checks (no shells, network tools or git writes).",
73
+ "Approved project code runs as your Windows account: it can read what you can",
74
+ "read, and may open other applications through Windows file associations.",
75
+ "Turn it off again with /settings commands off."
76
+ ];
77
+ function showSettings(ctx) {
78
+ const state = localCommandsState(ctx, undefined, getPermissionMode(ctx.config) === "auto");
79
+ const row = (label, value, note = "") => line(" " + c.label(label.padEnd(16)) + value + (note ? " " + c.dim(note) : ""));
80
+ line();
81
+ line(sectionHeader("Settings"));
82
+ line();
83
+ row("Local commands", state.enabled ? c.ok("enabled") : c.dim("disabled"), state.source === "env"
84
+ ? `via ${COMMANDS_OPT_IN_ENV}=1`
85
+ : state.source === "auto"
86
+ ? "enabled by Auto for this session"
87
+ : state.enabled
88
+ ? "/settings commands off to stop"
89
+ : "/settings commands on to allow");
90
+ if (state.enabled && state.blockedBy)
91
+ row("", c.warn("not active"), state.blockedBy);
92
+ row("Mode", c.value(ctx.mode));
93
+ row("Model", c.value(ctx.config.get("model") || "mode default"));
94
+ row("Fast", ctx.fast ? c.ok("on") : c.dim("off"), "/fast");
95
+ row("High Power", ctx.highPower ? c.ok("on") : c.dim("off"), "/hipwr");
96
+ row("Clarification", c.value(ctx.siaMode), "/sia");
97
+ const web = ctx.webSearch;
98
+ row("Web search", web === undefined ? c.dim("workspace default") : web ? c.ok("on") : c.dim("off"), "/websearch");
99
+ line();
100
+ }
@@ -0,0 +1,229 @@
1
+ import { line } from "../services/output.js";
2
+ import { withSpinner } from "../services/spinner.js";
3
+ import { isPackaged, isSignedRelease, PACKAGED_DOWNLOAD_URL } from "../services/packaged.js";
4
+ import { checkInstallerSignature, checkPackagedUpdate, downloadVerified, launchInstaller, updatesDir, UpdateError } from "../services/packaged-update.js";
5
+ import { checkForUpdate, installLatest, isLinkedInstallation, PACKAGE_NAME, verifyInstallation } from "../services/update.js";
6
+ import { c } from "../ui/colors.js";
7
+ import { pickFromList } from "../ui/select.js";
8
+ /**
9
+ * `/update` and `cos update` — check for, and install, a newer CLI.
10
+ *
11
+ * Bare `/update` NEVER mutates the installation; `/update install` is the only
12
+ * path that changes anything, and only after an explicit confirmation. The
13
+ * process is never restarted: npm swaps files under a running Node, and
14
+ * re-execing through the shim while the old process still holds handles is how
15
+ * partial installs happen. The user is told to restart instead.
16
+ *
17
+ * This file owns every message. services/update.ts owns the logic, so the shell
18
+ * command and the standalone command cannot drift apart.
19
+ */
20
+ const MANUAL = "npm install -g " + PACKAGE_NAME + "@latest";
21
+ function heading() {
22
+ line();
23
+ line(" " + c.title("Carrier OS CLI"));
24
+ line();
25
+ }
26
+ function versions(current, latest) {
27
+ line(" " + c.dim("Current version: ") + c.value(current));
28
+ line(" " + c.dim("Latest version: ") + c.value(latest));
29
+ line();
30
+ }
31
+ function renderTerminalState(state) {
32
+ if (state.kind === "current") {
33
+ line();
34
+ line(" " + c.ok("✓") + " " + c.value("Carrier OS CLI is already up to date (v" + state.current + ")"));
35
+ line();
36
+ return;
37
+ }
38
+ if (state.kind === "ahead") {
39
+ heading();
40
+ versions(state.current, state.latest);
41
+ line(" " + c.ok("✓") + " " + c.value("You are running a newer version than npm's latest."));
42
+ line(" " + c.dim("Nothing to do — this will not downgrade."));
43
+ line();
44
+ return;
45
+ }
46
+ if (state.kind === "no-npm") {
47
+ heading();
48
+ line(" " + c.err("✗") + " " + c.value("Unable to check for updates."));
49
+ line();
50
+ line(" " + c.dim("npm was not found on this system."));
51
+ line(" " + c.dim("Update manually with:"));
52
+ line(" " + c.cmd(MANUAL));
53
+ line();
54
+ return;
55
+ }
56
+ // unreachable
57
+ heading();
58
+ line(" " + c.err("✗") + " " + c.value("Could not check for the latest version."));
59
+ line();
60
+ line(" " + c.dim("Your current version: ") + c.value(state.current));
61
+ line(" " + c.dim(state.detail));
62
+ line();
63
+ }
64
+ /**
65
+ * `/update` and `cos update` — the entire user-facing surface.
66
+ *
67
+ * One command: check, and if something newer exists, offer to install it. The
68
+ * check/install split exists only as functions in services/update.ts — exposing
69
+ * it as subcommands would make the user choose between two things that are
70
+ * really one intention.
71
+ *
72
+ * Nothing is installed without an explicit Yes, and the process is never
73
+ * restarted: npm swaps files under a running Node, and re-execing through the
74
+ * shim while the old process still holds handles is how partial installs occur.
75
+ */
76
+ export async function runUpdate(opts = {}) {
77
+ // The packaged executable has no npm to update through. Point at the download
78
+ // rather than running an npm command that cannot exist in that environment.
79
+ if (isPackaged()) {
80
+ await runPackagedUpdate(opts.assumeYes === true);
81
+ return;
82
+ }
83
+ const state = await withSpinner(c.dim("Checking for updates…"), async () => checkForUpdate());
84
+ // Up to date, ahead of the registry, npm missing, or unreachable — each says
85
+ // everything it needs to, including how to update by hand.
86
+ if (state.kind !== "available") {
87
+ renderTerminalState(state);
88
+ return;
89
+ }
90
+ // MANDATORY GUARD, before anything can write. `npm i -g` against a linked
91
+ // install replaces the symlink, silently detaching a developer's checkout.
92
+ if (isLinkedInstallation()) {
93
+ heading();
94
+ versions(state.current, state.latest);
95
+ line(" " + c.warn("⚠") + " " + c.value("Running from a linked development checkout."));
96
+ line();
97
+ line(" " + c.dim("Automatic update is disabled here — it would replace the link."));
98
+ line(" " + c.dim("Install a published version from npm before using /update."));
99
+ line();
100
+ return;
101
+ }
102
+ heading();
103
+ versions(state.current, state.latest);
104
+ line(" " + c.value("A new version is available."));
105
+ line();
106
+ const answer = opts.assumeYes ? "yes" : await pickFromList({
107
+ title: "Update now?",
108
+ description: "Runs " + MANUAL,
109
+ choices: [
110
+ { value: "yes", label: "Yes", description: "Install v" + state.latest + " now" },
111
+ { value: "no", label: "No", description: "Stay on v" + state.current }
112
+ ],
113
+ initial: 0,
114
+ confirmOnNumber: true
115
+ });
116
+ // Esc resolves null — a dismissed prompt must never install anything.
117
+ if (answer !== "yes") {
118
+ line(" " + c.dim("Update cancelled."));
119
+ line();
120
+ return;
121
+ }
122
+ const result = await withSpinner(c.dim("Updating Carrier OS CLI…"), async () => installLatest());
123
+ if (!result.ok) {
124
+ line();
125
+ line(" " + c.err("✗") + " " + c.value("Update failed."));
126
+ line();
127
+ line(" " + c.dim("Carrier OS CLI remains at v") + c.value(state.current) + c.dim("."));
128
+ if (result.permission) {
129
+ line(" " + c.dim("This looks like a permissions problem — try an elevated terminal,"));
130
+ line(" " + c.dim("or run: ") + c.cmd(MANUAL));
131
+ }
132
+ if (result.detail) {
133
+ line();
134
+ for (const l of result.detail.split("\n").slice(0, 6))
135
+ line(" " + c.dim(l));
136
+ }
137
+ line();
138
+ return;
139
+ }
140
+ // Trust the disk, not this process: our own package.json was read at startup
141
+ // and the old modules stay loaded, so cliVersion() cannot see the swap.
142
+ const installed = verifyInstallation() ?? state.latest;
143
+ line();
144
+ line(" " + c.ok("✓") + " " + c.value("Carrier OS CLI updated successfully."));
145
+ line(" " + c.dim(state.current) + c.dim(" → ") + c.value(installed));
146
+ line();
147
+ line(" " + c.dim("Restart Carrier OS CLI to use the new version."));
148
+ line();
149
+ }
150
+ /**
151
+ * The packaged (installer) update: check the release manifest, then — only
152
+ * after an explicit Yes — download, verify the checksum (and the signature on
153
+ * a signed build), hand the installer this PID and exit. The installer waits
154
+ * for this process to end before replacing cos.exe, so nothing is swapped
155
+ * underneath a running CLI. Every failure leaves the current version intact.
156
+ */
157
+ async function runPackagedUpdate(assumeYes) {
158
+ const state = await withSpinner(c.dim("Checking for updates…"), () => checkPackagedUpdate());
159
+ if (state.kind === "current") {
160
+ renderTerminalState({ kind: "current", current: state.current, latest: state.latest });
161
+ return;
162
+ }
163
+ if (state.kind === "ahead") {
164
+ heading();
165
+ versions(state.current, state.latest);
166
+ line(" " + c.ok("✓") + " " + c.value("You are running a newer version than the latest release."));
167
+ line(" " + c.dim("Nothing to do — this will not downgrade."));
168
+ line();
169
+ return;
170
+ }
171
+ if (state.kind === "unreachable") {
172
+ heading();
173
+ line(" " + c.err("✗") + " " + c.value("Could not check for the latest version."));
174
+ line();
175
+ line(" " + c.dim("Your current version: ") + c.value(state.current));
176
+ line(" " + c.dim(state.detail));
177
+ line(" " + c.dim("You can also download the installer from ") + c.value(PACKAGED_DOWNLOAD_URL) + c.dim("."));
178
+ line();
179
+ return;
180
+ }
181
+ const artifact = state.manifest.artifacts["win-x64-setup"];
182
+ heading();
183
+ versions(state.current, state.latest);
184
+ line(" " + c.value("A new version is available."));
185
+ line();
186
+ const answer = assumeYes ? "yes" : await pickFromList({
187
+ title: "Update now?",
188
+ description: `Downloads ${artifact.file} (${(artifact.size / 1024 / 1024).toFixed(1)} MB), verifies it, then installs it`,
189
+ choices: [
190
+ { value: "yes", label: "Yes", description: "Install v" + state.latest + " — Carrier OS closes while it updates" },
191
+ { value: "no", label: "No", description: "Stay on v" + state.current }
192
+ ],
193
+ initial: 0,
194
+ confirmOnNumber: true
195
+ });
196
+ if (answer !== "yes") {
197
+ line(" " + c.dim("Update cancelled."));
198
+ line();
199
+ return;
200
+ }
201
+ try {
202
+ const installer = await withSpinner(c.dim("Downloading and verifying…"), () => downloadVerified(artifact, updatesDir()));
203
+ const sig = checkInstallerSignature(installer, artifact, isSignedRelease());
204
+ const log = await launchInstaller(installer);
205
+ line();
206
+ line(" " + c.ok("✓") + " " + c.value(`Verified v${state.latest}`) + c.dim(sig.verified ? " (checksum + signature)" : " (checksum)"));
207
+ line(" " + c.dim("Installing now. Carrier OS will close; open a new terminal when it finishes."));
208
+ line(" " + c.dim("Installer log: ") + c.value(log));
209
+ line();
210
+ // The installer is waiting for this PID. Exit now so it can replace cos.exe.
211
+ process.exit(0);
212
+ }
213
+ catch (err) {
214
+ line();
215
+ line(" " + c.err("✗") + " " + c.value("Update failed."));
216
+ line(" " + c.dim(err instanceof UpdateError ? err.message : String(err?.message ?? err)));
217
+ line(" " + c.dim("Carrier OS CLI remains at v") + c.value(state.current) + c.dim("."));
218
+ line();
219
+ }
220
+ }
221
+ export function registerUpdate(program, _ctx) {
222
+ program
223
+ .command("update")
224
+ .description("Check for and install the latest Carrier OS CLI version")
225
+ .option("-y, --yes", "install an available update without asking (for scripts)")
226
+ .action(async (opts) => {
227
+ await runUpdate({ assumeYes: opts.yes === true });
228
+ });
229
+ }
@@ -0,0 +1,223 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { attachedFilenames, ensureUploaded, uploadAndAttach, UploadError } from "../services/file-upload.js";
4
+ import { errorLine, info, line, success } from "../services/output.js";
5
+ import { withSpinner } from "../services/spinner.js";
6
+ import { c } from "../ui/colors.js";
7
+ import { pickFromList } from "../ui/select.js";
8
+ import { ensureWorkspaceTrust } from "../ui/trust.js";
9
+ /** Expand file args — literal paths pass through; `*`/`?` are globbed locally. */
10
+ function expandFiles(patterns) {
11
+ const out = [];
12
+ for (const p of patterns) {
13
+ const base = path.basename(p);
14
+ if (/[*?]/.test(base)) {
15
+ const dir = path.resolve(path.dirname(p));
16
+ const rx = new RegExp("^" +
17
+ base
18
+ .replace(/[.+^${}()|[\]\\]/g, "\\$&")
19
+ .replace(/\*/g, ".*")
20
+ .replace(/\?/g, ".") +
21
+ "$", "i");
22
+ try {
23
+ for (const name of fs.readdirSync(dir)) {
24
+ const full = path.join(dir, name);
25
+ if (rx.test(name) && fs.statSync(full).isFile())
26
+ out.push(full);
27
+ }
28
+ }
29
+ catch {
30
+ /* directory missing */
31
+ }
32
+ }
33
+ else {
34
+ out.push(path.resolve(p));
35
+ }
36
+ }
37
+ return [...new Set(out)];
38
+ }
39
+ function reportError(err) {
40
+ errorLine(err instanceof UploadError ? err.message : err.message);
41
+ }
42
+ /** "Attached files (N)" list. */
43
+ function printAttachedList(ctx) {
44
+ const names = attachedFilenames(ctx);
45
+ if (names.length === 0)
46
+ return;
47
+ line();
48
+ line(" " + c.dim(`Attached files (${names.length})`));
49
+ for (const n of names)
50
+ line(" " + c.dim("• ") + c.value(n));
51
+ }
52
+ /** Next-command suggestions after a standalone upload. */
53
+ function printTry(multiple) {
54
+ line();
55
+ line(" " + c.dim("Try:"));
56
+ line(' ' + c.cmd('cos chat "Summarize this file"'));
57
+ if (multiple)
58
+ line(' ' + c.cmd('cos chat "Compare the attached files"'));
59
+ line(" " + c.cmd("cos") + c.dim(" (open interactive mode)"));
60
+ line();
61
+ }
62
+ /** Yes/No confirm (default Yes, 1→Yes / 2→No, Esc cancels → false). */
63
+ async function confirmAttach(question) {
64
+ const chosen = await pickFromList({
65
+ title: question,
66
+ choices: [
67
+ { value: "yes", label: "Yes" },
68
+ { value: "no", label: "No" }
69
+ ],
70
+ initial: 0,
71
+ confirmOnNumber: true
72
+ });
73
+ return chosen === "yes";
74
+ }
75
+ /** Standalone single-file flow: upload/find, then confirm attach (Case A/B/C). */
76
+ async function standaloneSingle(ctx, client, filePath, opts) {
77
+ const r = await ensureUploaded(ctx, client, filePath, {
78
+ onUploading: () => {
79
+ line();
80
+ line(" " + c.dim("Uploading…"));
81
+ },
82
+ onUploaded: (n) => success(`Uploaded ${n}`),
83
+ onProcessing: () => {
84
+ line();
85
+ line(" " + c.dim("Processing in background…"));
86
+ },
87
+ process: opts.process
88
+ });
89
+ // Case A — already uploaded AND attached.
90
+ if (r.status === "existing" && r.wasAttached) {
91
+ line();
92
+ success(`${r.filename} is already attached to this conversation.`);
93
+ line();
94
+ line(" " + c.dim("Ready to use."));
95
+ printAttachedList(ctx);
96
+ printTry(attachedFilenames(ctx).length > 1);
97
+ return;
98
+ }
99
+ // Case B — previously uploaded, not attached.
100
+ if (r.status === "existing" && !r.wasAttached) {
101
+ line();
102
+ success(`Found existing upload: ${r.filename}`);
103
+ line();
104
+ const yes = await confirmAttach("Attach it to this conversation?");
105
+ line();
106
+ if (yes) {
107
+ ctx.attachFile(r.fileId);
108
+ success(`Attached ${r.filename}`);
109
+ line();
110
+ line(" " + c.dim("Ready to chat about it."));
111
+ }
112
+ else {
113
+ info("Nothing changed.");
114
+ }
115
+ return;
116
+ }
117
+ // Case C — a brand-new upload (Uploading/Processing already printed).
118
+ line();
119
+ const yes = await confirmAttach("Attach this file to the current conversation?");
120
+ line();
121
+ if (yes) {
122
+ ctx.attachFile(r.fileId);
123
+ success(`Attached ${r.filename}`);
124
+ line();
125
+ line(" " + c.dim("Ready to chat about it."));
126
+ printTry(false);
127
+ }
128
+ else {
129
+ success("Upload complete.");
130
+ line();
131
+ line(" " + c.dim("The file is saved to your uploads. Attach it anytime with:"));
132
+ line(" " + c.cmd(`cos attach "${r.filename}"`));
133
+ line();
134
+ }
135
+ }
136
+ /**
137
+ * `cos upload <files...>` / `/upload` — upload one or more files and index each.
138
+ * Thin client: `ensureUploaded` does the /v1/files + /process calls; this owns the
139
+ * UX. It NEVER starts a chat or summarizes.
140
+ *
141
+ * • Inside the shell → upload + auto-attach + "Ready." (you're already chatting).
142
+ * • Standalone (single file) → upload, then confirm whether to attach.
143
+ * • Standalone (multiple) → upload + attach all, then show next steps.
144
+ */
145
+ export function registerUpload(program, ctx) {
146
+ program
147
+ .command("upload")
148
+ .description("Upload one or more files and start processing them")
149
+ .argument("<files...>", "path(s) to upload — multiple files and * globs are supported")
150
+ .option("--no-process", "upload only; skip the processing/indexing step")
151
+ .action(async (files, opts) => {
152
+ // Standalone runs reach the disk without having passed the shell's
153
+ // startup check, so gate them here too. In-shell is already trusted.
154
+ if (!ctx.inShell && !(await ensureWorkspaceTrust(ctx.config))) {
155
+ process.exitCode = 1;
156
+ return;
157
+ }
158
+ const client = ctx.requireAuth();
159
+ const paths = expandFiles(files);
160
+ if (paths.length === 0) {
161
+ errorLine("Couldn't find that file. Check the path and try again.");
162
+ process.exitCode = 1;
163
+ return;
164
+ }
165
+ // ── Interactive shell: upload + auto-attach, no prompts ──────────────────
166
+ if (ctx.inShell) {
167
+ let ok = 0;
168
+ for (const fp of paths) {
169
+ try {
170
+ const r = await withSpinner(`Uploading ${path.basename(fp)}…`, () => uploadAndAttach(ctx, client, fp, { process: opts.process }));
171
+ line();
172
+ if (r.status === "uploaded")
173
+ success(`Uploaded ${r.filename}`);
174
+ success(r.wasAttached ? `${r.filename} already attached` : `Attached ${r.filename}`);
175
+ ok += 1;
176
+ }
177
+ catch (err) {
178
+ reportError(err);
179
+ }
180
+ }
181
+ if (ok > 0) {
182
+ line();
183
+ info("Ready.");
184
+ line();
185
+ }
186
+ if (ok < paths.length)
187
+ process.exitCode = 1;
188
+ return;
189
+ }
190
+ // ── Standalone, single file: confirm attach (Case A/B/C) ─────────────────
191
+ if (paths.length === 1) {
192
+ try {
193
+ await standaloneSingle(ctx, client, paths[0], opts);
194
+ }
195
+ catch (err) {
196
+ reportError(err);
197
+ process.exitCode = 1;
198
+ }
199
+ return;
200
+ }
201
+ // ── Standalone, multiple files: upload + attach all, then next steps ─────
202
+ let ok = 0;
203
+ for (const fp of paths) {
204
+ try {
205
+ const r = await withSpinner(`Uploading ${path.basename(fp)}…`, () => uploadAndAttach(ctx, client, fp, { process: opts.process }));
206
+ line();
207
+ success(r.status === "uploaded" ? `Uploaded ${r.filename}` : `${r.filename} (already uploaded)`);
208
+ ok += 1;
209
+ }
210
+ catch (err) {
211
+ reportError(err);
212
+ }
213
+ }
214
+ if (ok > 0) {
215
+ line();
216
+ info(`Attached ${ok} file${ok > 1 ? "s" : ""} to this conversation.`);
217
+ printAttachedList(ctx);
218
+ printTry(ok > 1);
219
+ }
220
+ if (ok < paths.length)
221
+ process.exitCode = 1;
222
+ });
223
+ }