@carrieros/cli-staging 0.0.0-stage → 0.4.1

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 (137) 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 +26 -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 +78 -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 +160 -0
  27. package/dist/commands/update.js +285 -0
  28. package/dist/commands/upload.js +223 -0
  29. package/dist/commands/usage.js +229 -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 +364 -0
  34. package/dist/ide/tool-host.js +109 -0
  35. package/dist/main.js +132 -0
  36. package/dist/services/api.js +441 -0
  37. package/dist/services/auth-origin.js +20 -0
  38. package/dist/services/auto-update.js +221 -0
  39. package/dist/services/chat-stream.js +168 -0
  40. package/dist/services/checkpoints.js +278 -0
  41. package/dist/services/client-tools.js +356 -0
  42. package/dist/services/code-intel.js +243 -0
  43. package/dist/services/code-symbols.js +94 -0
  44. package/dist/services/coding-workflow.js +554 -0
  45. package/dist/services/command-coordinator.js +273 -0
  46. package/dist/services/command-policy.js +434 -0
  47. package/dist/services/config.js +384 -0
  48. package/dist/services/container-runner.js +254 -0
  49. package/dist/services/container-supervisor.js +38 -0
  50. package/dist/services/context.js +416 -0
  51. package/dist/services/device-auth.js +288 -0
  52. package/dist/services/diff.js +196 -0
  53. package/dist/services/env-policy.js +108 -0
  54. package/dist/services/execution-platform.js +30 -0
  55. package/dist/services/file-detect.js +104 -0
  56. package/dist/services/file-resolver.js +199 -0
  57. package/dist/services/file-upload.js +126 -0
  58. package/dist/services/folder-key.js +22 -0
  59. package/dist/services/git-tools.js +429 -0
  60. package/dist/services/glob-match.js +164 -0
  61. package/dist/services/helper-bin.js +85 -0
  62. package/dist/services/ignore-rules.js +189 -0
  63. package/dist/services/instruction-resolver.js +54 -0
  64. package/dist/services/job-helper.js +328 -0
  65. package/dist/services/local-files.js +639 -0
  66. package/dist/services/local-tools.js +937 -0
  67. package/dist/services/login-flow.js +156 -0
  68. package/dist/services/meta.js +42 -0
  69. package/dist/services/mutation-coordinator.js +327 -0
  70. package/dist/services/mutation-groups.js +309 -0
  71. package/dist/services/mutation-recovery.js +159 -0
  72. package/dist/services/mutations.js +679 -0
  73. package/dist/services/open-url.js +68 -0
  74. package/dist/services/output.js +62 -0
  75. package/dist/services/packaged-update.js +403 -0
  76. package/dist/services/packaged.js +39 -0
  77. package/dist/services/permission-mode.js +78 -0
  78. package/dist/services/process-runner.js +412 -0
  79. package/dist/services/project-context.js +298 -0
  80. package/dist/services/redaction.js +201 -0
  81. package/dist/services/result-reconciliation.js +49 -0
  82. package/dist/services/secure-store.js +217 -0
  83. package/dist/services/session-resolver.js +115 -0
  84. package/dist/services/sia.js +51 -0
  85. package/dist/services/spinner.js +40 -0
  86. package/dist/services/supported-runtime.js +59 -0
  87. package/dist/services/task-context.js +212 -0
  88. package/dist/services/task-snapshot.js +38 -0
  89. package/dist/services/tool-result-outbox.js +195 -0
  90. package/dist/services/update.js +730 -0
  91. package/dist/services/workspace-registry.js +310 -0
  92. package/dist/services/workspace.js +580 -0
  93. package/dist/shell/shell-chat.js +1622 -0
  94. package/dist/shell/shell-commands.js +411 -0
  95. package/dist/shell/shell-prompt.js +110 -0
  96. package/dist/shell/shell-renderer.js +51 -0
  97. package/dist/shell/shell-router.js +37 -0
  98. package/dist/shell/shell.js +414 -0
  99. package/dist/shell/task-context-view.js +40 -0
  100. package/dist/staging.js +5 -0
  101. package/dist/types/index.js +6 -0
  102. package/dist/ui/agent-cards.js +111 -0
  103. package/dist/ui/agent-presentation.js +131 -0
  104. package/dist/ui/approval.js +111 -0
  105. package/dist/ui/banner.js +56 -0
  106. package/dist/ui/btw-overlay.js +230 -0
  107. package/dist/ui/change-review.js +334 -0
  108. package/dist/ui/chat-renderer.js +463 -0
  109. package/dist/ui/code-block.js +52 -0
  110. package/dist/ui/color-picker.js +100 -0
  111. package/dist/ui/colors.js +55 -0
  112. package/dist/ui/command-details.js +11 -0
  113. package/dist/ui/command-filter.js +92 -0
  114. package/dist/ui/command-item.js +6 -0
  115. package/dist/ui/command-palette.js +383 -0
  116. package/dist/ui/command-registry.js +128 -0
  117. package/dist/ui/command-renderer.js +55 -0
  118. package/dist/ui/command-review.js +187 -0
  119. package/dist/ui/composer-layout.js +74 -0
  120. package/dist/ui/conversation.js +450 -0
  121. package/dist/ui/interrupt.js +35 -0
  122. package/dist/ui/live.js +141 -0
  123. package/dist/ui/logo.js +58 -0
  124. package/dist/ui/markdown.js +205 -0
  125. package/dist/ui/message.js +21 -0
  126. package/dist/ui/screen-prompt.js +181 -0
  127. package/dist/ui/screen.js +297 -0
  128. package/dist/ui/select.js +284 -0
  129. package/dist/ui/sia-qa.js +213 -0
  130. package/dist/ui/spinner.js +23 -0
  131. package/dist/ui/sticky-stream.js +64 -0
  132. package/dist/ui/task-context-card.js +99 -0
  133. package/dist/ui/text-prompt.js +74 -0
  134. package/dist/ui/theme.js +80 -0
  135. package/dist/ui/trust.js +88 -0
  136. package/dist/ui/ui.js +101 -0
  137. package/package.json +33 -4
@@ -0,0 +1,217 @@
1
+ import crypto from "node:crypto";
2
+ import { execFileSync } from "node:child_process";
3
+ import fs from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { damagedInstallMessage, findPrebuiltHelper } from "./helper-bin.js";
7
+ import { isPackaged } from "./packaged.js";
8
+ /**
9
+ * Credentials at rest, protected with Windows DPAPI.
10
+ *
11
+ * WHAT THIS IS FOR: keeping the access and refresh tokens out of plaintext in
12
+ * config.json — so a backup, a sync client, a support bundle, a screen share of
13
+ * the file, or anyone who copies it to another machine or account gets a blob
14
+ * that only this Windows user on this machine can open.
15
+ *
16
+ * WHAT THIS IS NOT: a boundary against code running as the same Windows user.
17
+ * DPAPI's CurrentUser scope decrypts for ANY process of that user, which
18
+ * includes project code the user approved through `run_command`. Such code can
19
+ * read this file and ask DPAPI to open it exactly as the CLI does. Nothing the
20
+ * CLI can do inside the user's own account changes that; the server-side
21
+ * protections (short-lived access tokens, refresh rotation with reuse detection,
22
+ * revocation) are what limit the damage of a stolen token. See
23
+ * docs/SECURITY-local-execution.md.
24
+ *
25
+ * The application-specific entropy below is not a secret — it is in this
26
+ * source. It only stops generic "decrypt every DPAPI blob" tools from opening
27
+ * these without knowing they belong to Carrier OS.
28
+ *
29
+ * MECHANISM: Node has no DPAPI binding, so a tiny helper does the call. It is
30
+ * compiled on first use with the .NET Framework C# compiler that ships with
31
+ * Windows, cached per source hash, and hash-checked before use — the same
32
+ * approach as the command-containment helper. Plaintext and blobs travel on
33
+ * stdin/stdout, never on the command line, where other processes could read
34
+ * them. When the Windows executable is packaged, this helper ships prebuilt.
35
+ */
36
+ export const SEALED_PREFIX = "dpapi:v1:";
37
+ export const DPAPI_SOURCE = String.raw `using System;
38
+ using System.Security.Cryptography;
39
+ using System.Text;
40
+
41
+ // cos-dpapi: protect/unprotect a payload for the CURRENT Windows user.
42
+ // Usage: cos-dpapi.exe protect|unprotect (base64 in on stdin, base64 out on stdout)
43
+ // Exit 0 = ok, 1 = the payload could not be processed, 2 = bad usage.
44
+ static class CosDpapi
45
+ {
46
+ static readonly byte[] Entropy = Encoding.UTF8.GetBytes("CarrierOS-CLI/credentials/v1");
47
+
48
+ static int Main(string[] args)
49
+ {
50
+ string mode = args.Length == 1 ? args[0] : "";
51
+ if (mode != "protect" && mode != "unprotect") { Console.Error.Write("usage"); return 2; }
52
+ try
53
+ {
54
+ byte[] input = Convert.FromBase64String(Console.In.ReadToEnd().Trim());
55
+ byte[] output = mode == "protect"
56
+ ? ProtectedData.Protect(input, Entropy, DataProtectionScope.CurrentUser)
57
+ : ProtectedData.Unprotect(input, Entropy, DataProtectionScope.CurrentUser);
58
+ Console.Out.Write(Convert.ToBase64String(output));
59
+ return 0;
60
+ }
61
+ catch (Exception e)
62
+ {
63
+ // The type only — never the payload.
64
+ Console.Error.Write(e.GetType().Name);
65
+ return 1;
66
+ }
67
+ }
68
+ }
69
+ `;
70
+ export class SealError extends Error {
71
+ code;
72
+ constructor(code, message) {
73
+ super(message);
74
+ this.code = code;
75
+ this.name = "SealError";
76
+ }
77
+ }
78
+ const sha256 = (data) => crypto.createHash("sha256").update(data).digest("hex");
79
+ function helperDir() {
80
+ const local = process.env.LOCALAPPDATA;
81
+ return local ? path.join(local, "CarrierOS", "bin") : path.join(os.homedir(), ".carrieros", "bin");
82
+ }
83
+ function findCompiler() {
84
+ const windir = process.env.SystemRoot || process.env.windir || "C:\\Windows";
85
+ for (const fw of ["Framework64", "Framework"]) {
86
+ const csc = path.join(windir, "Microsoft.NET", fw, "v4.0.30319", "csc.exe");
87
+ if (fs.existsSync(csc))
88
+ return csc;
89
+ }
90
+ return null;
91
+ }
92
+ let helperPath = null;
93
+ let helperFailed = false;
94
+ /** The verified helper, building it if needed; null when DPAPI is unavailable. */
95
+ function ensureHelper() {
96
+ if (process.platform !== "win32" || helperFailed)
97
+ return null;
98
+ // Prefer the prebuilt helper shipped with a packaged build.
99
+ const prebuilt = findPrebuiltHelper("cos-dpapi");
100
+ if (prebuilt) {
101
+ helperPath = prebuilt;
102
+ return prebuilt;
103
+ }
104
+ // A packaged build never compiles: no prebuilt helper means a damaged install,
105
+ // and sealingRequired() makes the config store refuse to write credentials.
106
+ if (isPackaged()) {
107
+ helperFailed = true;
108
+ return null;
109
+ }
110
+ const tag = sha256(DPAPI_SOURCE).slice(0, 16);
111
+ const dir = helperDir();
112
+ const exe = path.join(dir, `cos-dpapi-${tag}.exe`);
113
+ const stamp = `${exe}.sha256`;
114
+ if (helperPath === exe && fs.existsSync(exe))
115
+ return exe;
116
+ try {
117
+ if (fs.existsSync(exe) && fs.existsSync(stamp)) {
118
+ if (sha256(fs.readFileSync(exe)) === fs.readFileSync(stamp, "utf8").trim()) {
119
+ helperPath = exe;
120
+ return exe;
121
+ }
122
+ fs.rmSync(exe, { force: true });
123
+ fs.rmSync(stamp, { force: true });
124
+ }
125
+ const csc = findCompiler();
126
+ if (!csc) {
127
+ helperFailed = true;
128
+ return null;
129
+ }
130
+ fs.mkdirSync(dir, { recursive: true });
131
+ const nonce = crypto.randomBytes(6).toString("hex");
132
+ const src = path.join(dir, `cos-dpapi-${tag}-${nonce}.cs`);
133
+ const tmp = path.join(dir, `cos-dpapi-${tag}-${nonce}.exe`);
134
+ fs.writeFileSync(src, DPAPI_SOURCE, "utf8");
135
+ try {
136
+ execFileSync(csc, ["/nologo", "/target:exe", "/optimize+", "/reference:System.Security.dll", `/out:${tmp}`, src], { stdio: ["ignore", "pipe", "pipe"], windowsHide: true, timeout: 60_000 });
137
+ const hash = sha256(fs.readFileSync(tmp));
138
+ fs.renameSync(tmp, exe);
139
+ fs.writeFileSync(stamp, hash, "utf8");
140
+ }
141
+ finally {
142
+ fs.rmSync(src, { force: true });
143
+ fs.rmSync(tmp, { force: true });
144
+ }
145
+ helperPath = exe;
146
+ return exe;
147
+ }
148
+ catch {
149
+ helperFailed = true;
150
+ return null;
151
+ }
152
+ }
153
+ /**
154
+ * True when credentials MUST be sealed: the packaged Windows build ships its
155
+ * DPAPI helper, so its absence is a damaged installation, never a reason to
156
+ * write tokens in plaintext. A developer checkout keeps the documented
157
+ * fallback (plaintext at 0600 when no compiler exists).
158
+ */
159
+ export function sealingRequired() {
160
+ return process.platform === "win32" && isPackaged();
161
+ }
162
+ /** The error a packaged build raises instead of storing credentials unsealed. */
163
+ export function sealingUnavailableError() {
164
+ return new SealError("UNAVAILABLE", damagedInstallMessage("cos-dpapi.exe"));
165
+ }
166
+ /** Whether credentials can be protected on this machine. */
167
+ export function sealingAvailable() {
168
+ return ensureHelper() !== null;
169
+ }
170
+ export const isSealed = (value) => typeof value === "string" && value.startsWith(SEALED_PREFIX);
171
+ function runHelper(mode, base64) {
172
+ const exe = ensureHelper();
173
+ if (!exe)
174
+ throw new SealError("UNAVAILABLE", "Credential protection is not available on this machine.");
175
+ try {
176
+ return execFileSync(exe, [mode], {
177
+ input: base64,
178
+ encoding: "utf8",
179
+ stdio: ["pipe", "pipe", "pipe"],
180
+ windowsHide: true,
181
+ timeout: 15_000
182
+ }).trim();
183
+ }
184
+ catch {
185
+ throw new SealError("UNREADABLE", mode === "unprotect"
186
+ ? "Stored credentials could not be opened by this Windows account."
187
+ : "Credentials could not be protected.");
188
+ }
189
+ }
190
+ /**
191
+ * Plaintext by blob, so a process opens each credential once. Keyed by the
192
+ * sealed string itself: a rotated token is a new blob and a new entry.
193
+ */
194
+ const opened = new Map();
195
+ /** Protect a secret for the current Windows user. */
196
+ export function seal(plaintext) {
197
+ const blob = SEALED_PREFIX + runHelper("protect", Buffer.from(plaintext, "utf8").toString("base64"));
198
+ opened.set(blob, plaintext);
199
+ return blob;
200
+ }
201
+ /** Open a sealed secret. Throws SealError when it cannot be opened. */
202
+ export function unseal(blob) {
203
+ const hit = opened.get(blob);
204
+ if (hit !== undefined)
205
+ return hit;
206
+ if (!isSealed(blob))
207
+ throw new SealError("UNREADABLE", "Not a protected credential.");
208
+ const plaintext = Buffer.from(runHelper("unprotect", blob.slice(SEALED_PREFIX.length)), "base64").toString("utf8");
209
+ if (!plaintext)
210
+ throw new SealError("UNREADABLE", "Stored credentials could not be opened by this Windows account.");
211
+ opened.set(blob, plaintext);
212
+ return plaintext;
213
+ }
214
+ /** Test seam: forget opened blobs, so a test can prove a read really decrypts. */
215
+ export function forgetOpenedSecrets() {
216
+ opened.clear();
217
+ }
@@ -0,0 +1,115 @@
1
+ import { ApiError } from "./api.js";
2
+ import { resetPermissionMode, restorePermissionMode } from "./permission-mode.js";
3
+ import { withSpinner } from "./spinner.js";
4
+ /**
5
+ * The one place a session is looked up.
6
+ *
7
+ * `/sessions` prints an ordered list; every other session command then accepts
8
+ * the ordinal from that list ("2") as well as the raw id. Commands call
9
+ * `resolveSessionRef` and never do their own lookup, so the numbering can only
10
+ * ever mean one thing.
11
+ *
12
+ * The ordinal map is PERSISTED rather than held in memory: each standalone `cos`
13
+ * invocation is a separate process, so `cos sessions` followed by
14
+ * `cos session 2` would otherwise have nothing to resolve against.
15
+ */
16
+ /** A session id as the API issues them — anything else is treated as an ordinal. */
17
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
18
+ export function looksLikeSessionId(token) {
19
+ return UUID_RE.test(token.trim());
20
+ }
21
+ /** Thrown when a reference can't be turned into a session. Message is user-facing. */
22
+ export class SessionRefError extends Error {
23
+ hint;
24
+ constructor(message, hint) {
25
+ super(message);
26
+ this.hint = hint;
27
+ this.name = "SessionRefError";
28
+ }
29
+ }
30
+ /** Fetch a page of conversations and remember the order for ordinal lookups. */
31
+ export async function listSessions(ctx, client, opts = {}) {
32
+ const limit = Math.min(Math.max(opts.limit ?? 20, 1), 100);
33
+ const fetch = () => client.conversations({ limit });
34
+ const { conversations, pagination } = opts.spinner === false
35
+ ? await fetch()
36
+ : await withSpinner("Loading sessions…", fetch);
37
+ ctx.config.set("sessionOrdinals", conversations.map((cv) => cv.session_id));
38
+ return { conversations, total: pagination.total };
39
+ }
40
+ /** The ordinal map from the last listing, or an empty array if there isn't one. */
41
+ export function currentOrdinals(ctx) {
42
+ return ctx.config.get("sessionOrdinals") ?? [];
43
+ }
44
+ /** 1-based position of a session in the last listing, or null. */
45
+ export function ordinalOf(ctx, sessionId) {
46
+ const i = currentOrdinals(ctx).indexOf(sessionId);
47
+ return i === -1 ? null : i + 1;
48
+ }
49
+ /**
50
+ * Turn a user-supplied reference into a session id.
51
+ *
52
+ * Accepts, in order of precedence:
53
+ * - a full session id → returned as-is (scripting, and every pre-existing
54
+ * `session use <uuid>` / `history <uuid>` call site)
55
+ * - an ordinal from the last `/sessions` listing
56
+ *
57
+ * A stale ordinal triggers ONE refresh before giving up, so the common case —
58
+ * listing in one process and acting in another, or acting after a deletion —
59
+ * resolves silently instead of making the user re-run `/sessions` by hand.
60
+ */
61
+ export async function resolveSessionRef(ctx, client, ref) {
62
+ const token = ref.trim();
63
+ if (!token)
64
+ throw new SessionRefError("No session given.", "Run /sessions to see the list.");
65
+ if (looksLikeSessionId(token))
66
+ return token;
67
+ const n = Number(token);
68
+ if (!Number.isInteger(n) || n < 1) {
69
+ throw new SessionRefError(`"${token}" is not a session number or id.`, "Run /sessions to see the numbered list.");
70
+ }
71
+ const fromCache = currentOrdinals(ctx)[n - 1];
72
+ if (fromCache)
73
+ return fromCache;
74
+ // Nothing cached (or the list was shorter) — refresh once, then decide.
75
+ const { conversations } = await listSessions(ctx, client, { spinner: false });
76
+ const refreshed = conversations[n - 1]?.session_id;
77
+ if (refreshed)
78
+ return refreshed;
79
+ throw new SessionRefError(conversations.length === 0
80
+ ? `Session ${n} is no longer available.`
81
+ : `Session ${n} is no longer available. There ${conversations.length === 1 ? "is" : "are"} ${conversations.length}.`, "Run /sessions to refresh the list.");
82
+ }
83
+ /** Resolve a reference AND load the session, so callers get a verified title. */
84
+ export async function resolveSession(ctx, client, ref) {
85
+ const id = await resolveSessionRef(ctx, client, ref);
86
+ try {
87
+ const s = await client.session(id);
88
+ return { session_id: s.session_id, title: s.title, message_count: s.message_count };
89
+ }
90
+ catch (err) {
91
+ // A 404 here means the id resolved but the conversation is gone (deleted in
92
+ // another window, or no longer in this project) — say that, not "not found".
93
+ if (err instanceof ApiError && err.status === 404) {
94
+ throw new SessionRefError("That session is no longer available.", "Run /sessions to refresh the list.");
95
+ }
96
+ throw err;
97
+ }
98
+ }
99
+ /** Remember the active session and its title so the footer can name it. */
100
+ export function setActiveSession(ctx, id, title) {
101
+ ctx.config.set("sessionId", id);
102
+ ctx.noteSessionSelectionChanged();
103
+ if (title !== undefined)
104
+ ctx.config.set("sessionTitle", title);
105
+ // Resuming: the conversation's own permission mode. Approvals are never restored.
106
+ restorePermissionMode(ctx.config, id);
107
+ }
108
+ /** Forget the active session (a fresh conversation starts on the next message). */
109
+ export function clearActiveSession(ctx) {
110
+ ctx.config.set("sessionId", undefined);
111
+ ctx.config.set("sessionTitle", undefined);
112
+ ctx.noteSessionSelectionChanged();
113
+ // A new task never inherits Accept Edits authority or Plan state.
114
+ resetPermissionMode(ctx.config);
115
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * SIA answer merging — the CLI half of the website's lib/sia/answer-merger.ts.
3
+ *
4
+ * Clarification answers are not sent as a separate field: they are appended to
5
+ * the prompt itself, and the merged string is what /v1/chat stores as the user
6
+ * message. Both clients therefore have to agree on the marker EXACTLY. If this
7
+ * string drifts by one character, a conversation started in the CLI renders its
8
+ * raw marker on the website (and vice-versa), because the reader below is the
9
+ * only thing that splits the block back off for display.
10
+ */
11
+ /** Verbatim from the website. Do not "tidy" the whitespace. */
12
+ const SIA_MARKER = "\n\n[Clarification Context]\n";
13
+ /** snake_case key → "Snake Case", the label shown in the appended block. */
14
+ function formatKey(key) {
15
+ return key.replace(/_/g, " ").replace(/\b\w/g, (ch) => ch.toUpperCase());
16
+ }
17
+ /**
18
+ * Append the answers to the prompt. Returns the original untouched when nothing
19
+ * was answered, so a skipped Q&A is indistinguishable from SIA being off.
20
+ */
21
+ export function buildStructuredIntent(original, answers) {
22
+ const entries = Object.entries(answers).filter(([, v]) => v !== null && v !== undefined && v !== "");
23
+ if (entries.length === 0)
24
+ return original;
25
+ const lines = entries.map(([key, value]) => {
26
+ const display = typeof value === "boolean" ? (value ? "Yes" : "No") : String(value);
27
+ return `${formatKey(key)}: ${display}`;
28
+ });
29
+ return `${original}${SIA_MARKER}${lines.join("\n")}`;
30
+ }
31
+ /**
32
+ * Split a stored message back into the typed prompt and its clarification
33
+ * items, or null when there is no block. Used when replaying a transcript —
34
+ * including transcripts written by the website.
35
+ */
36
+ export function parseSiaContext(content) {
37
+ const idx = content.indexOf(SIA_MARKER);
38
+ if (idx === -1)
39
+ return null;
40
+ const displayPrompt = content.slice(0, idx).trim();
41
+ const items = content
42
+ .slice(idx + SIA_MARKER.length)
43
+ .trim()
44
+ .split("\n")
45
+ .filter((l) => l.includes(": "))
46
+ .map((l) => {
47
+ const at = l.indexOf(": ");
48
+ return { label: l.slice(0, at), value: l.slice(at + 2) };
49
+ });
50
+ return items.length > 0 ? { displayPrompt, items } : null;
51
+ }
@@ -0,0 +1,40 @@
1
+ import ora from "ora";
2
+ import { screenActive, screenTransient } from "../ui/screen.js";
3
+ const FRAMES = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏";
4
+ /**
5
+ * Run an async task under a spinner. The spinner is always stopped afterwards
6
+ * (success or throw) so it can never be left spinning on an error path. Inside
7
+ * the interactive shell the spinner renders as a transient line above the pinned
8
+ * composer (via the screen engine) instead of writing to stdout directly.
9
+ */
10
+ export async function withSpinner(text, fn) {
11
+ if (screenActive()) {
12
+ const state = { text };
13
+ let i = 0;
14
+ const paint = () => screenTransient([" " + FRAMES[i % FRAMES.length] + " " + state.text]);
15
+ paint();
16
+ const timer = setInterval(() => {
17
+ i++;
18
+ paint();
19
+ }, 80);
20
+ timer.unref?.();
21
+ try {
22
+ return await fn(state);
23
+ }
24
+ finally {
25
+ clearInterval(timer);
26
+ screenTransient([]); // clear the spinner line; real output follows via line()
27
+ }
28
+ }
29
+ // discardStdin:false — otherwise ora grabs/pauses stdin while spinning, which
30
+ // corrupts the interactive shell's readline and makes it exit after one turn.
31
+ const spinner = ora({ text, color: "cyan", discardStdin: false }).start();
32
+ try {
33
+ return await fn(spinner);
34
+ }
35
+ finally {
36
+ spinner.stop();
37
+ }
38
+ }
39
+ /** Small helper for the mocked "streaming" output. */
40
+ export const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
@@ -0,0 +1,59 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { executionPlatform } from "./execution-platform.js";
4
+ /** Supported administrator-installed Docker CLI locations. No PATH or executable override. */
5
+ export function supportedDockerPaths(platform) {
6
+ if (platform === "darwin")
7
+ return ["/Applications/Docker.app/Contents/Resources/bin/docker", "/opt/homebrew/bin/docker", "/usr/local/bin/docker"];
8
+ if (platform === "linux")
9
+ return ["/usr/bin/docker", "/usr/local/bin/docker"];
10
+ return [];
11
+ }
12
+ export function supportedDockerTarget(platform, target) {
13
+ if (platform === "linux")
14
+ return ["/usr/bin/docker", "/usr/local/bin/docker"].includes(target);
15
+ if (platform !== "darwin")
16
+ return false;
17
+ return target === "/Applications/Docker.app/Contents/Resources/bin/docker" ||
18
+ /^\/(opt\/homebrew|usr\/local)\/Cellar\/docker\/[0-9][A-Za-z0-9._-]*\/bin\/docker$/.test(target);
19
+ }
20
+ /** Installation and local administrators are trusted, as for the CLI itself.
21
+ * This rejects project wrappers/scripts, arbitrary paths and unsafe writable binaries;
22
+ * it is not package-signature attestation against a compromised administrator.
23
+ */
24
+ export function installedDocker() {
25
+ const platform = executionPlatform();
26
+ for (const candidate of supportedDockerPaths(platform)) {
27
+ try {
28
+ const target = fs.realpathSync(candidate);
29
+ if (!supportedDockerTarget(platform, target))
30
+ continue;
31
+ const info = fs.statSync(target);
32
+ if (!info.isFile() || (info.mode & 0o022) || ![0, process.getuid?.()].includes(info.uid))
33
+ continue;
34
+ fs.accessSync(target, fs.constants.X_OK);
35
+ let directory = path.dirname(target);
36
+ while (directory !== path.dirname(directory)) {
37
+ // Package-manager directories may be writable by the administrator group.
38
+ if (fs.statSync(directory).mode & 0o002)
39
+ throw new Error("world writable installation");
40
+ directory = path.dirname(directory);
41
+ }
42
+ const fd = fs.openSync(target, "r");
43
+ const header = Buffer.alloc(4);
44
+ try {
45
+ if (fs.readSync(fd, header, 0, 4, 0) !== 4)
46
+ continue;
47
+ }
48
+ finally {
49
+ fs.closeSync(fd);
50
+ }
51
+ const magic = header.toString("hex");
52
+ if (platform === "linux" ? magic !== "7f454c46" : !["cffaedfe", "feedfacf", "cafebabe", "bebafeca", "cafebabf", "bfbafeca"].includes(magic))
53
+ continue;
54
+ return target;
55
+ }
56
+ catch { /* Try only the next supported installation, never PATH. */ }
57
+ }
58
+ throw Object.assign(new Error("Install the supported Docker CLI using Docker Desktop/Homebrew on macOS or the system Docker Engine package on Linux. Arbitrary runtime executables are not supported."), { code: "ISOLATION_UNAVAILABLE" });
59
+ }