setup-agent 0.0.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.
package/dist/cli.js ADDED
@@ -0,0 +1,636 @@
1
+ import { connectCheckout } from "./client.js";
2
+ import { INPUT_PRESETS, isPresetId, presetInput } from "./presets.js";
3
+ import { AGENT_HEARTBEAT_MS, OPTION_ICONS, classifyChoiceAnswer, currentPlan, isAgentPresent, isClosed, isOptionIcon, parseModelAnswer, parseMultipleAnswer, stepProgress } from "./protocol.js";
4
+ import { spawn } from "node:child_process";
5
+ import { readFile, writeFile } from "node:fs/promises";
6
+ import { createInterface } from "node:readline/promises";
7
+ import { resolve } from "node:path";
8
+ //#region src/cli.ts
9
+ const HELP = `setup-agent <url> [command]
10
+
11
+ Commands (the url always comes first):
12
+ status Print the checkout as JSON.
13
+ stream Follow the checkout: one JSON array of events per line.
14
+ log <text> Send a message to the user: a reply, something no question or step conveys, or one wrap-up when finished.
15
+ ack <message-id> Acknowledge a user message.
16
+ ask <prompt> [--placeholder <text>] [--optional] [--step <step-id>] [--wait]
17
+ Ask the user for a line of text.
18
+ ask [prompt] --preset <framework|llm-provider|project> [--only <id,id>] [--choices <id=description,...>] [--default <id>] [--optional] [--step <step-id>] [--wait]
19
+ Ask a standard question. --only restricts the options (one id locks it in); --default preselects one.
20
+ "framework" answers "<framework>:<language>"; "llm-provider" answers JSON with provider, model and reasoningEffort; the key itself arrives through "env".
21
+ "project" lists the React projects you found as --choices "<path>=<what it is>,..." ahead of "New project"; it answers a path, or "new:<next|vite|react-router|tanstack-start|expo>".
22
+ ask <prompt> --choices <id,id,...> --icons <id=icon,...> [--single] [--default <id>] [--optional] [--step <step-id>] [--wait]
23
+ Ask the user to pick from your own options; they may also type their own answer.
24
+ The user checks any number of options and the answer is a JSON array of option ids (their own text is one entry).
25
+ --single is for options that exclude each other (one framework, one model, yes or no); the answer is then one id.
26
+ --icons is required and names an icon for every option, from: ${OPTION_ICONS.join(", ")}.
27
+ ask <prompt> --product <slug> [--wait]
28
+ Propose adding a product to this checkout, such as one another product needs first. Answers "added"; the product and its guide then appear in "status".
29
+ wait start Block until the user clicks Begin plan in their browser; after a finished or cancelled checkout, until the next one begins.
30
+ wait <input-id> Block until the user answers or dismisses an input. A multi-select answer prints as an array.
31
+ plan (<markdown> | --file <path>) [--wait]
32
+ Propose the plan for the user to approve. --wait blocks until they decide.
33
+ wait plan Block until the user approves the plan or asks for changes.
34
+ env <input-id> <ENV_VAR> [--file <path>]
35
+ Write the API key behind an answered llm-provider input to an env file (default .env.local) as ENV_VAR=<key>, without printing it.
36
+ add-step <title> [--detail <text>] [--product <slug>] [--active]
37
+ Declare a step of the install (after the plan is approved). Prints its id.
38
+ step <step-id> <status> [--note <text>]
39
+ Set a step to pending|active|done|skipped|blocked.
40
+ done [--summary <text>] [--preview <url>]
41
+ Mark every remaining step done and propose closing; the user closes it.
42
+ `;
43
+ const INSTRUCTIONS = (url) => `You are the coding agent for a checkout the user opened in their browser. The browser shows this checkout live; every command below updates it. The user watches the browser, not this terminal: once setup begins, send questions through "ask" so the user can answer in their browser.
44
+
45
+ First, start a persistent Monitor on
46
+ npx setup-agent ${url} stream
47
+ and keep it running: the browser shows you as connected only while it runs, and it is how answers reach you. The URL is the user's link to you from their browser, not one checkout: it outlives this setup, and their next setup arrives on the same stream. Each line is a JSON array of events: "planning.started", "input.answered" ({inputId, answer, note?}; answer is an array for a choice question not asked with --single), "input.dismissed", "plan.approved", "plan.changes-requested" ({feedback}), "message.created" ({messageId, text}), "finished", "cancelled", "checkout.created" ({products}).
48
+
49
+ The user can message you at any time, including while a question is waiting. Read "message.created" events, acknowledge each with "npx setup-agent ${url} ack <message-id>", and reply using "log" with what you will do. Pending messages are replayed when the stream starts and listed in "status". A message is not an answer or plan approval; keep those decisions explicit.
50
+
51
+ "log" is a message to the user, and the user reads every one: send it only to reply to their message, to tell them something no question or step conveys (a blocker, a deviation from the plan, a decision you made for them), or once as a wrap-up when the install is finished. Findings go in the plan, progress in step notes, questions in "ask"; do not narrate.
52
+
53
+ Before planning, check the current checkout status. If it is "waiting", tell the user in your own conversation: "I'm connected. Go back to your browser and click Begin plan. You can watch my progress, answer questions, and steer me there." Then run:
54
+ npx setup-agent ${url} wait start
55
+ Keep the stream running while you wait. Do not inspect the project, fetch guides, ask setup questions, or propose a plan until this command returns {"ok":true}. Only the user in the browser should start planning; never invoke the browser's start command yourself. "planning.started" also arrives on the stream. If the status is already "planning" or "installing", resume that phase without asking the user to begin again. If it is "done" or "cancelled", that setup is over: tell the user you are connected and waiting for their next setup, and run "wait start", which returns once the next one begins.
56
+
57
+ The remaining phases are plan, then install.
58
+
59
+ 1. Plan. Investigate only; change nothing yet. If the current directory is not an app to install into (a monorepo root, an empty folder, a library), ask where to install first:
60
+ npx setup-agent ${url} ask "Which project should I install into?" --placeholder "An absolute path, or a path for a new Next.js app" --wait
61
+ Read the project: its app framework and package manager, the agent framework and model provider it already uses, where components live, any existing chat route. Fetch each product's "guide" URL from the checkout below; it is the install reference. Ask for what the project does not decide, using the standard questions so the browser can render them well:
62
+ npx setup-agent ${url} ask --preset framework
63
+ npx setup-agent ${url} ask --preset llm-provider
64
+ If a product's guide needs another product the project does not have yet (most need assistant-ui installed and rendering a thread), do not stop and do not install it on the side. Propose adding it to this checkout:
65
+ npx setup-agent ${url} ask "assistant-ui is not installed in this project yet. Add it to this setup?" --product assistant-ui --wait
66
+ On "added", run "status", fetch the new product's guide, and install it first in your plan. If the user dismisses it, follow what the guide says about the missing product.
67
+ Skip a preset the code already answers (a chat route on the AI SDK, a provider key in .env.local) and log why. Ask everything at once, keep investigating, and block with "wait <input-id>" only when nothing else can proceed. A framework answer is "<framework>:<language>", for example "ai-sdk:typescript". A model answer is JSON {"provider","model","reasoningEffort"?}. An answer may carry a "note" from the user; follow it. A choice answer that matches none of the options is the user's own text.
68
+ Then write the plan as markdown and submit it:
69
+ npx setup-agent ${url} plan --file <path> --wait
70
+ Use these headings, each with bullets: "## What I found" (facts as \`- **Label:** value\`: app framework, package manager, agent framework, model provider and model, where components live), "## What I will install" (packages and files, one per bullet), "## Steps" (a numbered list, one line each), and "## Open questions" only if any remain. Keep it under 30 lines; no preamble. "plan --wait" prints {"decision":"approve"} or {"decision":"revise","feedback":"..."}. On revise, address the feedback (ask again if you need to) and submit a new plan; repeat until approved. Do not change the project before approval: the checkout refuses steps until then.
71
+
72
+ 2. Install. Declare the steps from your plan up front, in order:
73
+ npx setup-agent ${url} add-step "<title>" --detail "<one line>"
74
+ which prints the step id. Then work through them: "step <id> active" before, "step <id> done --note '<one line on what you did>'" after; "skipped" when the step is already satisfied, "blocked" when you cannot continue, saying why in --note. Add steps as the work reveals them. Ask when you need another decision or value (--choices for a pick, plain for text; --optional when you can proceed without an answer; --wait only when the answer is the very next thing you need). A choice question is multi-select: the user checks any number of your options, and the answer is an array of the ids they checked, plus their own text as an entry when they typed one. Pass --single only when the options exclude each other (one framework, one model, yes or no); the answer is then one id. Every option must carry an icon, given as --icons "<id>=<icon>,..." with the closest name from this pack: ${OPTION_ICONS.join(", ")}. A question without an icon for each option is refused. Open inputs the user has not answered are listed under "inputs" in "status"; check them before asking again.
75
+ The API key behind a model answer is not in the answer and you never see it: pick the variable name the provider's SDK reads (OPENAI_API_KEY, ANTHROPIC_API_KEY, ...) and run
76
+ npx setup-agent ${url} env <input-id> <ENV_VAR> --file .env.local
77
+ which writes ENV_VAR=<key> into that file. Use the answer's model in the chat route and map reasoningEffort onto the provider's setting when it is set. Never invent a key or a model name.
78
+
79
+ When every product is installed and verified, run
80
+ npx setup-agent ${url} done --summary "<one or two lines on what you installed and how to try it>" --preview http://localhost:<port>
81
+ Before that, start the project's dev server in the background when the project has one, check that the page you changed loads, and pass the address as --preview (the page itself when it is not the root); leave the server running so the user can try the result. Omit --preview when there is nothing to open. This proposes closing the checkout; only the user closes it. Do not stop the stream or exit: stay idle on it, because the user may follow up with a "message.created" event. Handle it, then run "done" again. The stream prints "finished" once the user closes the checkout, and "cancelled" if they end it early. Keep the stream running after either: the user's next setup starts on this same URL and arrives as "checkout.created" with its products. Run
82
+ npx setup-agent ${url} wait start
83
+ which returns once that setup begins, then run "status" for its products, guides and instructions and go through plan and install again. A "checkout.created" event while you are still working means the user replaced this setup: drop what you were doing and start over the same way.
84
+ `;
85
+ const parseArgs = (argv) => {
86
+ const positional = [];
87
+ const flags = /* @__PURE__ */ new Map();
88
+ for (let i = 0; i < argv.length; i++) {
89
+ const arg = argv[i];
90
+ if (!arg.startsWith("--")) {
91
+ positional.push(arg);
92
+ continue;
93
+ }
94
+ const name = arg.slice(2);
95
+ const next = argv[i + 1];
96
+ if (next !== void 0 && !next.startsWith("--")) {
97
+ flags.set(name, next);
98
+ i++;
99
+ } else flags.set(name, true);
100
+ }
101
+ return {
102
+ positional,
103
+ flags
104
+ };
105
+ };
106
+ const flagText = (flags, name) => {
107
+ const value = flags.get(name);
108
+ return typeof value === "string" ? value : void 0;
109
+ };
110
+ const fail = (message) => {
111
+ process.stderr.write(`setup-agent: ${message}\n`);
112
+ return process.exit(1);
113
+ };
114
+ const print = (value) => {
115
+ process.stdout.write(`${JSON.stringify(value)}\n`);
116
+ };
117
+ const AGENT_ENV = [
118
+ ["claude", "CLAUDECODE"],
119
+ ["codex", "CODEX_SANDBOX"],
120
+ ["codex", "CODEX_SANDBOX_NETWORK_DISABLED"],
121
+ ["cursor", "CURSOR_AGENT"],
122
+ ["gemini", "GEMINI_CLI"]
123
+ ];
124
+ /** The coding agent this process runs under, from the variables each one exports to its shell. */
125
+ const detectAgentKind = (env = process.env) => AGENT_ENV.find(([, variable]) => env[variable])?.[0];
126
+ const LAUNCHERS = [
127
+ {
128
+ kind: "claude",
129
+ name: "Claude Code",
130
+ command: "claude",
131
+ args: (prompt) => [prompt],
132
+ install: "npm install -g @anthropic-ai/claude-code"
133
+ },
134
+ {
135
+ kind: "codex",
136
+ name: "Codex",
137
+ command: "codex",
138
+ args: (prompt) => [prompt],
139
+ install: "npm install -g @openai/codex"
140
+ },
141
+ {
142
+ kind: "cursor",
143
+ name: "Cursor",
144
+ command: "agent",
145
+ args: (prompt) => [prompt],
146
+ install: "curl https://cursor.com/install -fsS | bash"
147
+ },
148
+ {
149
+ kind: "gemini",
150
+ name: "Gemini CLI",
151
+ command: "gemini",
152
+ args: (prompt) => ["-i", prompt],
153
+ install: "npm install -g @google/gemini-cli"
154
+ }
155
+ ];
156
+ /** True when a person typed the command into a terminal rather than an agent running it from its shell. */
157
+ const isDirectInvocation = (env = process.env, stdin = process.stdin, stdout = process.stdout) => detectAgentKind(env) === void 0 && stdin.isTTY === true && stdout.isTTY === true;
158
+ const chooseLauncher = async () => {
159
+ const rl = createInterface({
160
+ input: process.stdin,
161
+ output: process.stdout
162
+ });
163
+ try {
164
+ process.stdout.write("This command is meant for a coding agent, and none is running here.\nStart one to do the install:\n");
165
+ LAUNCHERS.forEach((launcher, index) => {
166
+ process.stdout.write(` ${index + 1}. ${launcher.name}\n`);
167
+ });
168
+ while (true) {
169
+ const answer = (await rl.question("Choose [1]: ").catch(() => process.exit(1))).trim();
170
+ if (answer === "") return LAUNCHERS[0];
171
+ const byNumber = LAUNCHERS[Number(answer) - 1];
172
+ if (byNumber) return byNumber;
173
+ const byName = LAUNCHERS.find((launcher) => launcher.kind === answer.toLowerCase() || launcher.name.toLowerCase() === answer.toLowerCase());
174
+ if (byName) return byName;
175
+ process.stdout.write("Enter a number from the list.\n");
176
+ }
177
+ } finally {
178
+ rl.close();
179
+ }
180
+ };
181
+ const launchAgent = async (url) => {
182
+ const launcher = await chooseLauncher();
183
+ const prompt = `Run \`npx setup-agent ${url}\` and follow the instructions it prints.`;
184
+ process.stdout.write(`\nStarting ${launcher.name}...\n\n`);
185
+ const child = spawn(launcher.command, launcher.args(prompt), { stdio: "inherit" });
186
+ const code = await new Promise((resolve) => {
187
+ child.on("error", (error) => {
188
+ if (error.code === "ENOENT") process.stderr.write(`${launcher.name} is not installed. Install it with:\n ${launcher.install}\nthen run this command again.\n`);
189
+ else process.stderr.write(`${error.message}\n`);
190
+ resolve(1);
191
+ });
192
+ child.on("exit", (status) => resolve(status ?? 1));
193
+ });
194
+ process.exit(code);
195
+ };
196
+ const requireState = (client) => client.state ?? fail("the checkout has no state");
197
+ const summary = (state) => {
198
+ const plan = currentPlan(state);
199
+ return {
200
+ status: state.status,
201
+ agentConnected: isAgentPresent(state),
202
+ products: state.products,
203
+ instructions: state.instructions,
204
+ plan: plan === void 0 ? null : {
205
+ revision: plan.revision,
206
+ status: plan.status,
207
+ ...plan.feedback !== void 0 && { feedback: plan.feedback }
208
+ },
209
+ progress: stepProgress(state),
210
+ steps: state.steps,
211
+ inputs: state.inputs,
212
+ log: state.log.slice(-20),
213
+ pendingMessages: state.log.filter((entry) => entry.role === "user" && entry.acknowledgedAt === void 0)
214
+ };
215
+ };
216
+ const STEP_STATUSES = [
217
+ "pending",
218
+ "active",
219
+ "done",
220
+ "skipped",
221
+ "blocked"
222
+ ];
223
+ const STAY_CONNECTED = "This setup is over, not your connection. Keep the stream running, tell the user you are connected and waiting for their next setup, and run wait start.";
224
+ const diffEvents = (before, after) => {
225
+ const events = [];
226
+ if (before.status === "waiting" && after.status === "planning") events.push({ event: "planning.started" });
227
+ for (const entry of after.log) if (entry.role === "user" && entry.acknowledgedAt === void 0 && !before.log.some((previous) => previous.id === entry.id)) events.push({
228
+ event: "message.created",
229
+ messageId: entry.id,
230
+ text: entry.text
231
+ });
232
+ for (const input of after.inputs) {
233
+ if (before.inputs.find((candidate) => candidate.id === input.id)?.status === input.status) continue;
234
+ if (input.status === "answered") {
235
+ const answer = input.answer ?? "";
236
+ events.push({
237
+ event: "input.answered",
238
+ inputId: input.id,
239
+ prompt: input.prompt,
240
+ ...answerFields(input, answer)
241
+ });
242
+ } else if (input.status === "dismissed" && after.status !== "cancelled") events.push({
243
+ event: "input.dismissed",
244
+ inputId: input.id,
245
+ prompt: input.prompt
246
+ });
247
+ }
248
+ for (const plan of after.plans) {
249
+ if (before.plans.find((candidate) => candidate.revision === plan.revision)?.status === plan.status || plan.status === "proposed") continue;
250
+ if (plan.status === "approved") events.push({
251
+ event: "plan.approved",
252
+ revision: plan.revision
253
+ });
254
+ else events.push({
255
+ event: "plan.changes-requested",
256
+ revision: plan.revision,
257
+ feedback: plan.feedback ?? ""
258
+ });
259
+ }
260
+ if (before.status !== "done" && after.status === "done") events.push({
261
+ event: "finished",
262
+ next: STAY_CONNECTED
263
+ });
264
+ if (before.status !== "cancelled" && after.status === "cancelled") events.push({
265
+ event: "cancelled",
266
+ next: STAY_CONNECTED
267
+ });
268
+ if (after.id !== null && after.id !== before.id) events.push({
269
+ event: "checkout.created",
270
+ products: after.products.map((product) => product.slug)
271
+ });
272
+ return events;
273
+ };
274
+ const stream = async (client) => {
275
+ let previous = requireState(client);
276
+ let pending = diffEvents({
277
+ ...previous,
278
+ log: []
279
+ }, previous);
280
+ let timer = null;
281
+ const flush = () => {
282
+ timer = null;
283
+ if (pending.length === 0) return;
284
+ print(pending);
285
+ pending = [];
286
+ };
287
+ client.subscribe(() => {
288
+ const next = client.state;
289
+ if (next === void 0) return;
290
+ pending.push(...diffEvents(previous, next));
291
+ previous = next;
292
+ if (pending.length > 0 && timer === null) timer = setTimeout(flush, 200);
293
+ });
294
+ flush();
295
+ const kind = detectAgentKind();
296
+ await client.commands["agent/hello"]({
297
+ cwd: process.cwd(),
298
+ ...kind !== void 0 && { kind }
299
+ });
300
+ const heartbeat = setInterval(() => {
301
+ client.commands["agent/heartbeat"]().catch(() => {});
302
+ }, AGENT_HEARTBEAT_MS);
303
+ const stop = () => {
304
+ clearInterval(heartbeat);
305
+ flush();
306
+ client.commands["agent/bye"]().catch(() => {}).finally(() => {
307
+ client.dispose();
308
+ process.exit(0);
309
+ });
310
+ };
311
+ process.on("SIGHUP", stop);
312
+ process.on("SIGINT", stop);
313
+ process.on("SIGTERM", stop);
314
+ await new Promise(() => {});
315
+ };
316
+ /** Resolves once a checkout is planning or installing, or once the one being waited on is cancelled; a checkout already closed when the wait begins is over, so the wait is for the next one. */
317
+ const waitForStart = (client) => new Promise((resolve) => {
318
+ let previous;
319
+ const check = () => {
320
+ const state = client.state;
321
+ if (state === void 0) return;
322
+ const started = state.status === "planning" || state.status === "installing";
323
+ const ended = isClosed(state) && previous === "waiting";
324
+ previous = state.status;
325
+ if (!started && !ended) return;
326
+ unsubscribe();
327
+ resolve(state.status);
328
+ };
329
+ const unsubscribe = client.subscribe(check);
330
+ check();
331
+ });
332
+ const waitForInput = (client, inputId) => new Promise((resolve) => {
333
+ const check = () => {
334
+ const state = client.state;
335
+ const input = state?.inputs.find((candidate) => candidate.id === inputId);
336
+ if (!input) return;
337
+ if (input.status !== "open" || state?.status === "cancelled") {
338
+ unsubscribe();
339
+ resolve(input);
340
+ }
341
+ };
342
+ const unsubscribe = client.subscribe(check);
343
+ check();
344
+ });
345
+ const waitForPlan = (client, revision) => new Promise((resolve) => {
346
+ const check = () => {
347
+ const state = client.state;
348
+ const plan = state?.plans.find((candidate) => candidate.revision === revision);
349
+ if (plan === void 0 || plan.status !== "proposed" || state?.status === "cancelled") {
350
+ unsubscribe();
351
+ resolve(plan);
352
+ }
353
+ };
354
+ const unsubscribe = client.subscribe(check);
355
+ check();
356
+ });
357
+ const decided = (plan, state) => {
358
+ if (state.status === "cancelled") return {
359
+ ok: false,
360
+ status: "cancelled"
361
+ };
362
+ if (plan === void 0) return fail("the plan disappeared");
363
+ return plan.status === "approved" ? {
364
+ ok: true,
365
+ decision: "approve",
366
+ revision: plan.revision
367
+ } : {
368
+ ok: true,
369
+ decision: "revise",
370
+ revision: plan.revision,
371
+ feedback: plan.feedback ?? ""
372
+ };
373
+ };
374
+ const splitList = (value) => value?.split(",").map((entry) => entry.trim()).filter(Boolean);
375
+ const askSeed = (rest, flags) => {
376
+ const stepId = flagText(flags, "step");
377
+ const optional = flags.has("optional");
378
+ const fallback = flagText(flags, "default");
379
+ const preset = flagText(flags, "preset");
380
+ if (preset !== void 0) {
381
+ if (!isPresetId(preset)) return fail(`unknown preset "${preset}"; use ${Object.keys(INPUT_PRESETS).join(" or ")}`);
382
+ const only = splitList(flagText(flags, "only"));
383
+ const found = splitList(flagText(flags, "choices"))?.map((entry) => {
384
+ const [id = "", ...description] = entry.split("=");
385
+ return description.length === 0 ? { id } : {
386
+ id,
387
+ description: description.join("=")
388
+ };
389
+ });
390
+ try {
391
+ const seed = presetInput(preset, {
392
+ ...only !== void 0 && { only },
393
+ ...found !== void 0 && { found },
394
+ ...fallback !== void 0 && { default: fallback },
395
+ optional,
396
+ ...stepId !== void 0 && { stepId }
397
+ });
398
+ return rest[0] === void 0 ? seed : {
399
+ ...seed,
400
+ prompt: rest[0]
401
+ };
402
+ } catch (error) {
403
+ return fail(error instanceof Error ? error.message : String(error));
404
+ }
405
+ }
406
+ const prompt = rest[0] ?? fail("usage: ask <prompt>");
407
+ const product = flagText(flags, "product");
408
+ if (product !== void 0) return {
409
+ kind: "product",
410
+ prompt,
411
+ product,
412
+ optional,
413
+ ...stepId !== void 0 && { stepId }
414
+ };
415
+ const choices = splitList(flagText(flags, "choices"));
416
+ if (choices !== void 0) {
417
+ if (flags.has("single") && flags.has("multiple")) return fail("--single and --multiple exclude each other");
418
+ const icons = /* @__PURE__ */ new Map();
419
+ for (const entry of splitList(flagText(flags, "icons")) ?? []) {
420
+ const [id = "", icon = ""] = entry.split("=", 2);
421
+ if (!choices.includes(id)) return fail(`no choice "${id}" to put an icon on`);
422
+ if (!isOptionIcon(icon)) return fail(`unknown icon "${icon}"; pick one of ${OPTION_ICONS.join(", ")}`);
423
+ icons.set(id, icon);
424
+ }
425
+ const missing = choices.filter((id) => !icons.has(id));
426
+ if (missing.length > 0) return fail(`every option needs an icon; ${missing.map((id) => `"${id}"`).join(", ")} ${missing.length === 1 ? "has" : "have"} none. Pass --icons "${choices.map((id) => `${id}=<icon>`).join(",")}" with icons from: ${OPTION_ICONS.join(", ")}`);
427
+ return {
428
+ kind: "choice",
429
+ prompt,
430
+ options: choices.map((id) => ({
431
+ id,
432
+ label: id,
433
+ icon: icons.get(id)
434
+ })),
435
+ ...!flags.has("single") && { multiple: true },
436
+ ...fallback !== void 0 && { default: fallback },
437
+ optional,
438
+ ...stepId !== void 0 && { stepId }
439
+ };
440
+ }
441
+ const placeholder = flagText(flags, "placeholder");
442
+ return {
443
+ prompt,
444
+ ...placeholder !== void 0 && { placeholder },
445
+ optional,
446
+ ...stepId !== void 0 && { stepId }
447
+ };
448
+ };
449
+ /** Sets `key=value` in dotenv text, replacing an existing line for the key. */
450
+ const upsertEnvLine = (content, key, value) => {
451
+ const line = `${key}=${value}`;
452
+ const lines = content === "" ? [] : content.replace(/\n$/, "").split("\n");
453
+ const index = lines.findIndex((entry) => new RegExp(`^(export\\s+)?${key}\\s*=`).test(entry));
454
+ if (index === -1) lines.push(line);
455
+ else lines[index] = line;
456
+ return `${lines.join("\n")}\n`;
457
+ };
458
+ const answerFields = (input, answer) => ({
459
+ answer: input.multiple && parseMultipleAnswer(answer) || answer,
460
+ ...input.note !== void 0 && { note: input.note },
461
+ ...input.kind === "choice" && classifyChoiceAnswer(input, answer) === "custom" && { custom: true }
462
+ });
463
+ const answered = (input) => ({
464
+ ok: true,
465
+ inputId: input.id,
466
+ status: input.status,
467
+ ...input.answer !== void 0 && answerFields(input, input.answer)
468
+ });
469
+ const main = async (argv) => {
470
+ const { positional, flags } = parseArgs(argv);
471
+ const [first, command = "intro", ...rest] = positional;
472
+ if (flags.has("help") || flags.has("h") || first === void 0) {
473
+ process.stdout.write(HELP);
474
+ return process.exit(first === void 0 ? 1 : 0);
475
+ }
476
+ const url = first;
477
+ if (command === "intro" && isDirectInvocation()) return launchAgent(url);
478
+ const client = await connectCheckout(url).catch((error) => fail(error instanceof Error ? error.message : String(error)));
479
+ const commands = client.commands;
480
+ try {
481
+ switch (command) {
482
+ case "intro": {
483
+ const kind = detectAgentKind();
484
+ await commands["agent/intro"]({ ...kind !== void 0 && { kind } }).catch(() => {});
485
+ process.stdout.write(INSTRUCTIONS(url));
486
+ process.stdout.write("\nCurrent checkout:\n");
487
+ print(summary(requireState(client)));
488
+ break;
489
+ }
490
+ case "status":
491
+ print(summary(requireState(client)));
492
+ break;
493
+ case "stream":
494
+ await stream(client);
495
+ break;
496
+ case "step": {
497
+ const usage = "usage: step <step-id> <pending|active|done|skipped|blocked>";
498
+ const stepId = rest[0] ?? fail(usage);
499
+ const status = rest[1];
500
+ if (!STEP_STATUSES.includes(status)) fail(usage);
501
+ const note = flagText(flags, "note");
502
+ await commands["agent/step"]({
503
+ stepId,
504
+ status,
505
+ ...note !== void 0 && { note }
506
+ });
507
+ print({
508
+ ok: true,
509
+ stepId,
510
+ status
511
+ });
512
+ break;
513
+ }
514
+ case "add-step": {
515
+ const title = rest[0] ?? fail("usage: add-step <title>");
516
+ const detail = flagText(flags, "detail");
517
+ const product = flagText(flags, "product");
518
+ const result = await commands["agent/add-step"]({
519
+ title,
520
+ ...detail !== void 0 && { detail },
521
+ ...product !== void 0 && { product },
522
+ ...flags.has("active") && { active: true }
523
+ });
524
+ print({
525
+ ok: true,
526
+ ...result
527
+ });
528
+ break;
529
+ }
530
+ case "plan": {
531
+ const file = flagText(flags, "file");
532
+ const markdown = file !== void 0 ? await readFile(resolve(file), "utf8").catch(() => fail(`could not read ${file}`)) : rest[0] ?? fail("usage: plan <markdown> | plan --file <path>");
533
+ const { revision } = await commands["agent/plan"]({ markdown });
534
+ if (!flags.has("wait")) {
535
+ print({
536
+ ok: true,
537
+ revision
538
+ });
539
+ break;
540
+ }
541
+ const plan = await waitForPlan(client, revision);
542
+ print(decided(plan, requireState(client)));
543
+ break;
544
+ }
545
+ case "ask": {
546
+ const { inputId } = await commands["agent/ask"](askSeed(rest, flags));
547
+ if (!flags.has("wait")) {
548
+ print({
549
+ ok: true,
550
+ inputId
551
+ });
552
+ break;
553
+ }
554
+ print(await waitForInput(client, inputId).then(answered));
555
+ break;
556
+ }
557
+ case "wait": {
558
+ const target = rest[0] ?? fail("usage: wait start | wait <input-id> | wait plan");
559
+ const state = requireState(client);
560
+ if (target === "start") {
561
+ const status = await waitForStart(client);
562
+ print({
563
+ ok: status === "planning" || status === "installing",
564
+ status
565
+ });
566
+ break;
567
+ }
568
+ if (target === "plan") {
569
+ const plan = currentPlan(state) ?? fail("no plan has been proposed");
570
+ print(decided(await waitForPlan(client, plan.revision), requireState(client)));
571
+ break;
572
+ }
573
+ if (!state.inputs.some((input) => input.id === target)) fail(`no input "${target}"`);
574
+ print(await waitForInput(client, target).then(answered));
575
+ break;
576
+ }
577
+ case "env": {
578
+ const usage = "usage: env <input-id> <ENV_VAR> [--file <path>]";
579
+ const inputId = rest[0] ?? fail(usage);
580
+ const envKey = rest[1] ?? fail(usage);
581
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(envKey)) fail(`"${envKey}" is not an environment variable name`);
582
+ const input = requireState(client).inputs.find((candidate) => candidate.id === inputId) ?? fail(`no input "${inputId}"`);
583
+ if (input.status !== "answered") fail(`input "${inputId}" is ${input.status}`);
584
+ if (parseModelAnswer(input.answer ?? "") === void 0) fail(`input "${inputId}" is not an llm-provider answer`);
585
+ const file = resolve(flagText(flags, "file") ?? ".env.local");
586
+ const response = await fetch(`${url.replace(/\/$/, "")}/secret/${encodeURIComponent(inputId)}`);
587
+ if (response.status === 404) fail(`the key for "${inputId}" was already taken or never deposited`);
588
+ if (!response.ok) fail(`could not fetch the key: ${response.status}`);
589
+ const value = await response.text();
590
+ const current = await readFile(file, "utf8").catch(() => "");
591
+ await writeFile(file, upsertEnvLine(current, envKey, value));
592
+ print({
593
+ ok: true,
594
+ envKey,
595
+ file
596
+ });
597
+ break;
598
+ }
599
+ case "ack": {
600
+ const messageId = rest[0] ?? fail("usage: ack <message-id>");
601
+ await commands["agent/ack"]({ messageId });
602
+ print({ ok: true });
603
+ break;
604
+ }
605
+ case "log": {
606
+ const text = rest[0] ?? fail("usage: log <text>");
607
+ await commands["agent/log"]({ text });
608
+ print({ ok: true });
609
+ break;
610
+ }
611
+ case "done": {
612
+ const summary = flagText(flags, "summary");
613
+ const preview = flagText(flags, "preview");
614
+ await commands["agent/done"]({
615
+ ...summary !== void 0 && { summary },
616
+ ...preview !== void 0 && { preview }
617
+ });
618
+ print({
619
+ ok: true,
620
+ status: "proposed",
621
+ next: "Keep the stream running and stay idle. The user closes the checkout or sends a follow-up message."
622
+ });
623
+ break;
624
+ }
625
+ default: fail(`unknown command "${command}"\n\n${HELP}`);
626
+ }
627
+ } catch (error) {
628
+ fail(error instanceof Error ? error.message : String(error));
629
+ } finally {
630
+ client.dispose();
631
+ }
632
+ };
633
+ //#endregion
634
+ export { askSeed, detectAgentKind, diffEvents, isDirectInvocation, main, upsertEnvLine, waitForStart };
635
+
636
+ //# sourceMappingURL=cli.js.map