setup-agent 0.0.8 → 0.1.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 (52) hide show
  1. package/README.md +31 -0
  2. package/dist/agents.d.ts +33 -0
  3. package/dist/agents.d.ts.map +1 -0
  4. package/dist/agents.js +221 -0
  5. package/dist/agents.js.map +1 -0
  6. package/dist/browser.d.ts +40 -0
  7. package/dist/browser.d.ts.map +1 -0
  8. package/dist/browser.js +91 -0
  9. package/dist/browser.js.map +1 -0
  10. package/dist/cli.d.ts +38 -49
  11. package/dist/cli.d.ts.map +1 -1
  12. package/dist/cli.js +89 -180
  13. package/dist/cli.js.map +1 -1
  14. package/dist/host.d.ts.map +1 -1
  15. package/dist/host.js +13 -0
  16. package/dist/host.js.map +1 -1
  17. package/dist/index.d.ts +1 -1
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +2 -2
  20. package/dist/needs.d.ts +62 -0
  21. package/dist/needs.d.ts.map +1 -0
  22. package/dist/needs.js +184 -0
  23. package/dist/needs.js.map +1 -0
  24. package/dist/protocol.d.ts +16 -0
  25. package/dist/protocol.d.ts.map +1 -1
  26. package/dist/protocol.js +8 -1
  27. package/dist/protocol.js.map +1 -1
  28. package/dist/sdk.d.ts +48 -0
  29. package/dist/sdk.d.ts.map +1 -0
  30. package/dist/sdk.js +97 -0
  31. package/dist/sdk.js.map +1 -0
  32. package/dist/stream.d.ts +93 -0
  33. package/dist/stream.d.ts.map +1 -0
  34. package/dist/stream.js +184 -0
  35. package/dist/stream.js.map +1 -0
  36. package/package.json +16 -2
  37. package/src/agents.test.ts +137 -0
  38. package/src/agents.ts +243 -0
  39. package/src/browser.test.ts +192 -0
  40. package/src/browser.ts +146 -0
  41. package/src/cli.test.ts +78 -0
  42. package/src/cli.ts +189 -258
  43. package/src/host.test.ts +25 -0
  44. package/src/host.ts +7 -0
  45. package/src/index.ts +1 -0
  46. package/src/needs.test.ts +180 -0
  47. package/src/needs.ts +273 -0
  48. package/src/protocol.ts +17 -0
  49. package/src/sdk.test.ts +111 -0
  50. package/src/sdk.ts +145 -0
  51. package/src/stream.test.ts +223 -0
  52. package/src/stream.ts +314 -0
package/dist/cli.js CHANGED
@@ -1,19 +1,26 @@
1
+ import { CODING_AGENTS, detectAgentKind, findCommand, isDirectInvocation, runCodingAgent } from "./agents.js";
2
+ import { OPTION_ICONS, currentPlan, isAgentPresent, isClosed, isLoopbackHostname, isOptionIcon, isValidModelAnswer, parseEntryPointOptions, stepProgress } from "./protocol.js";
3
+ import { answerNeed } from "./needs.js";
1
4
  import { connectCheckout } from "./client.js";
2
5
  import { INPUT_PRESETS, isPresetId, presetInput } from "./presets.js";
3
- import { AGENT_HEARTBEAT_MS, OPTION_ICONS, classifyChoiceAnswer, currentPlan, isAgentPresent, isClosed, isLoopbackHostname, isOptionIcon, isValidModelAnswer, parseEntryPointOptions, parseMultipleAnswer, stepProgress } from "./protocol.js";
4
- import { spawn } from "node:child_process";
5
- import { createHash, randomBytes } from "node:crypto";
6
+ import { answerFields, diffEvents, followSetup, shellWord } from "./stream.js";
6
7
  import { constants } from "node:fs";
8
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
9
+ import { createHash, randomBytes } from "node:crypto";
7
10
  import { chmod, lstat, mkdir, open, readFile, realpath, unlink } from "node:fs/promises";
8
11
  import { homedir, tmpdir, userInfo } from "node:os";
9
12
  import { createInterface } from "node:readline/promises";
10
- import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
11
13
  // src/cli.ts
14
+ const DEFAULT_COMMAND = "npx setup-agent";
12
15
  const HELP = `setup-agent <url> [command]
13
16
 
14
17
  Commands (the url always comes first):
15
18
  status Print the setup as JSON.
16
- stream Follow the setup: one JSON array of events per line.
19
+ stream [--setup-app-url <url>] [--no-open]
20
+ Follow the setup: one JSON array of events per line. With --setup-app-url, open the setup page when the setup waits on the user.
21
+ answer <input-id> <answer> [--note <text>] [--dismiss]
22
+ answer plan approve | answer plan revise --feedback <text> | answer finish close
23
+ Answer for the user what they told you in your own conversation, as an "input.needed" event's "answer" shows.
17
24
  log <text> Send a message to the user: a reply, something no question or step conveys, or one wrap-up when finished.
18
25
  ack <message-id> Acknowledge a user message.
19
26
  ask <prompt> [--placeholder <text>] [--optional] [--step <step-id>] [--wait]
@@ -64,51 +71,61 @@ const parseSetupUrl = (value) => {
64
71
  if (!SETUP_URL_PATTERN.test(href)) throw new Error("the setup URL has characters a setup URL does not use");
65
72
  return href;
66
73
  };
67
- /** `value` as one shell word, quoted only when it holds more than plain URL characters. */
68
- const shellWord = (value) => /^[A-Za-z0-9._~%/:@=+,-]+$/.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
69
- const agentInstructions = (setupUrl) => {
74
+ const EVENT_LIST = `"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", "setup.created" ({products})`;
75
+ const beginPlanHandoff = (cmd, url) => `Before planning, check the current setup 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:
76
+ ${cmd} ${url} wait start
77
+ 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}. If it returns {"ok":false,"status":"cancelled"}, the user ended this setup before planning: do not plan, tell the user you are connected and waiting for their next setup, and run "wait start" again. 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.`;
78
+ const agentStartedHandoff = ({ browserUrl, opened = true, streaming = false }) => streaming ? `You started this setup, and it is already planning: there is no Begin plan click to wait for. Check "status" before planning: if it is "planning" or "installing", go on with that phase. If the status 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.` : `You started this setup, and it is already planning: there is no Begin plan click to wait for. The browser asks the user to connect to you first; it shows your working directory once your stream is running. Check "status" before planning: if it is "planning" or "installing", go on with that phase. Tell the user in your own conversation, once: ${opened ? `"I opened the assistant-ui setup in your browser. I'll ask my questions there, and you can watch my progress and steer me from that page. If it didn't open, go to ${browserUrl} ."` : `"Open ${browserUrl} to follow the assistant-ui setup. I'll ask my questions there, and you can watch my progress and steer me from that page."`} If the status 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.`;
79
+ const streamSection = (cmd, url, streaming, noOpen) => streaming ? `The command that printed this is the stream. Keep it running in the background until the setup ends: the browser shows you as connected only while it runs, and it is how answers reach you. Each new line of its output is a JSON array of events: ${EVENT_LIST}, plus:
80
+ - "browser.opened" ({id, message}): setup opened the setup page in the user's browser for a question. Tell the user once, in your own conversation, that it waits there.
81
+ - "input.needed" ({id, message, question, options?, answer}): the user may not see the browser right now. Do what its message says: wait for "input.answered", or ask the user in your own conversation with that question and options, then run its "answer" command with their reply. Answered either way, the setup goes on.
82
+ If this command stops, start it again in the background with
83
+ ${cmd} ${url} stream${noOpen ? " --no-open" : ""}
84
+ The URL is the user's link to you from their browser, not one setup: it outlives this one, and their next setup arrives on the same stream.` : `First, start a persistent Monitor on
85
+ ${cmd} ${url} stream
86
+ 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 setup: it outlives this one, and their next setup arrives on the same stream. Each line is a JSON array of events: ${EVENT_LIST}.`;
87
+ const agentInstructions = (setupUrl, options = {}) => {
70
88
  const url = shellWord(setupUrl);
71
- return `You are the coding agent for a setup the user opened in their browser. The browser shows this setup 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.
89
+ const cmd = options.command ?? DEFAULT_COMMAND;
90
+ const started = options.startedByAgent;
91
+ const streaming = started?.streaming === true;
92
+ return `You are the coding agent for a setup ${started ? streaming ? started.opened === false ? "you started; setup opens no browser (--no-open), so the user follows it on the setup page if they open it, or answers you in your own conversation" : "you started; the user follows it in their browser, which setup opens when you ask the user something" : "you opened in the user's browser" : "the user opened in their browser"}. The browser shows this setup 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.
72
93
 
73
- First, start a persistent Monitor on
74
- npx setup-agent ${url} stream
75
- 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 setup: it outlives this one, 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", "setup.created" ({products}).
94
+ ${streamSection(cmd, url, streaming, started?.opened === false)}
76
95
 
77
- 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.
96
+ The user can message you at any time, including while a question is waiting. Read "message.created" events, acknowledge each with "${cmd} ${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.
78
97
 
79
98
  "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.
80
99
 
81
- Before planning, check the current setup 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:
82
- npx setup-agent ${url} wait start
83
- 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.
100
+ ${started ? agentStartedHandoff(started) : beginPlanHandoff(cmd, url)}
84
101
 
85
102
  The remaining phases are plan, then install.
86
103
 
87
104
  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:
88
- npx setup-agent ${url} ask "Which project should I install into?" --placeholder "An absolute path to the app" --wait
105
+ ${cmd} ${url} ask "Which project should I install into?" --placeholder "An absolute path to the app" --wait
89
106
  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 setup 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:
90
- npx setup-agent ${url} ask --preset framework
91
- npx setup-agent ${url} ask --preset llm-provider
92
- The setup's products are starting names and guide references. Explore each product's setup instructions, then discover and plan any other relevant products or dependencies the app needs. Read /catalog.md on the guide URL’s origin to find related products and fetch their setup guides. The starting list does not restrict the implementation or require adding another product to the list. Include relevant additions in the plan for approval.
107
+ ${cmd} ${url} ask --preset framework
108
+ ${cmd} ${url} ask --preset llm-provider
109
+ The setup's products are starting names and guide references. If the setup lists no products, first ask the user what to set up with a choice question whose options are slugs from https://www.assistant-ui.com/catalog.md, then fetch https://www.assistant-ui.com/install.md?items=<slugs> as the guide. Explore each product's setup instructions, then discover and plan any other relevant products or dependencies the app needs. Read /catalog.md on the guide URL’s origin to find related products and fetch their setup guides. The starting list does not restrict the implementation or require adding another product to the list. Include relevant additions in the plan for approval.
93
110
  When the setup puts an assistant in the app, ask how users should access it after discovering the actual app and before proposing the plan. Skip this question when no product's guide installs an assistant (a standalone library or service setup, for example). Use an entry-point question with only 1–3 sensible alternatives. Describe the actual app's pages, workflow and component placement, not generic placeholder copy. Recommend one clear fit when there is one; two options may use the same form factor in different places. Each option needs a stable id, label, contextual description and entryPoint {"formFactor":"modal"|"sidebar"|"full-page","placement":"where it appears","trigger":"how users open it or navigate to it","recommended":true?}. Write the JSON array for this app and send it with:
94
- npx setup-agent ${url} ask "Where should users access the assistant?" --entry-points '<JSON array>' --wait
111
+ ${cmd} ${url} ask "Where should users access the assistant?" --entry-points '<JSON array>' --wait
95
112
  Mark a clear fit with "recommended":true rather than --default, so the user makes the pick. When you ask it, do not submit the plan before the user picks an entry point. Respect the selected placement and trigger in the plan and implementation. Do not ask for a new-versus-existing app setting; discover the app from its files and ask only for an install path when needed.
96
113
  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.
97
114
  Then write the plan as markdown and submit it:
98
- npx setup-agent ${url} plan --file <path> --wait
115
+ ${cmd} ${url} plan --file <path> --wait
99
116
  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 setup refuses steps until then.
100
117
 
101
118
  2. Install. Declare the steps from your plan up front, in order:
102
- npx setup-agent ${url} add-step "<title>" --detail "<one line>"
119
+ ${cmd} ${url} add-step "<title>" --detail "<one line>"
103
120
  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.
104
121
  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
105
- npx setup-agent ${url} env <input-id> <ENV_VAR> --file .env.local
106
- 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.
122
+ ${cmd} ${url} env <input-id> <ENV_VAR> --file .env.local
123
+ 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. If "env" says the key was never deposited (the model question was answered from your conversation), ask the user to add the key to that file themselves. Never invent a key or a model name.
107
124
 
108
125
  When every product is installed and verified, run
109
- npx setup-agent ${url} done --summary "<one or two lines on what you installed and how to try it>" --preview http://localhost:<port>
126
+ ${cmd} ${url} done --summary "<one or two lines on what you installed and how to try it>" --preview http://localhost:<port>
110
127
  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 setup; 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 setup, 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 "setup.created" with its products. Run
111
- npx setup-agent ${url} wait start
128
+ ${cmd} ${url} wait start
112
129
  which returns once that setup begins, then run "status" for its products, guides and instructions and go through plan and install again. A "setup.created" event while you are still working means the user replaced this setup: drop what you were doing and start over the same way.
113
130
  `;
114
131
  };
@@ -145,47 +162,8 @@ const fail = (message) => {
145
162
  const print = (value) => {
146
163
  process.stdout.write(`${JSON.stringify(value)}\n`);
147
164
  };
148
- const AGENT_ENV = [
149
- ["claude", "CLAUDECODE"],
150
- ["codex", "CODEX_SANDBOX"],
151
- ["codex", "CODEX_SANDBOX_NETWORK_DISABLED"],
152
- ["cursor", "CURSOR_AGENT"],
153
- ["gemini", "GEMINI_CLI"]
154
- ];
155
- /** The coding agent this process runs under, from the variables each one exports to its shell. */
156
- const detectAgentKind = (env = process.env) => AGENT_ENV.find(([, variable]) => env[variable])?.[0];
157
- const LAUNCHERS = [
158
- {
159
- kind: "claude",
160
- name: "Claude Code",
161
- command: "claude",
162
- args: (prompt) => [prompt],
163
- install: "npm install -g @anthropic-ai/claude-code"
164
- },
165
- {
166
- kind: "codex",
167
- name: "Codex",
168
- command: "codex",
169
- args: (prompt) => [prompt],
170
- install: "npm install -g @openai/codex"
171
- },
172
- {
173
- kind: "cursor",
174
- name: "Cursor",
175
- command: "agent",
176
- args: (prompt) => [prompt],
177
- install: "curl https://cursor.com/install -fsS | bash"
178
- },
179
- {
180
- kind: "gemini",
181
- name: "Gemini CLI",
182
- command: "gemini",
183
- args: (prompt) => ["-i", prompt],
184
- install: "npm install -g @google/gemini-cli"
185
- }
186
- ];
187
- /** True when a person typed the command into a terminal rather than an agent running it from its shell. */
188
- const isDirectInvocation = (env = process.env, stdin = process.stdin, stdout = process.stdout) => detectAgentKind(env) === void 0 && stdin.isTTY === true && stdout.isTTY === true;
165
+ /** The agents `setup-agent <url>` can start itself, for a person who ran it in a terminal. */
166
+ const LAUNCHERS = CODING_AGENTS.filter((agent) => agent.launch !== void 0);
189
167
  const chooseLauncher = async () => {
190
168
  const rl = createInterface({
191
169
  input: process.stdin,
@@ -213,16 +191,9 @@ const launchAgent = async (url) => {
213
191
  const launcher = await chooseLauncher();
214
192
  const prompt = `Run \`npx setup-agent ${shellWord(url)}\` and follow the instructions it prints.`;
215
193
  process.stdout.write(`\nStarting ${launcher.name}...\n\n`);
216
- const child = spawn(launcher.command, launcher.args(prompt), { stdio: "inherit" });
217
- const code = await new Promise((resolve) => {
218
- child.on("error", (error) => {
219
- if (error.code === "ENOENT") process.stderr.write(`${launcher.name} is not installed. Install it with:\n ${launcher.install}\nthen run this command again.\n`);
220
- else process.stderr.write(`${error.message}\n`);
221
- resolve(1);
222
- });
223
- child.on("exit", (status) => resolve(status ?? 1));
224
- });
225
- process.exit(code);
194
+ const code = await runCodingAgent(launcher, prompt);
195
+ if (code === void 0) process.stderr.write(`${launcher.name} is not installed. Install it with:\n ${launcher.launch.install}\nthen run this command again.\n`);
196
+ process.exitCode = code ?? 1;
226
197
  };
227
198
  const requireState = (client) => client.state ?? fail("the setup has no state");
228
199
  const summary = (state) => {
@@ -251,99 +222,6 @@ const STEP_STATUSES = [
251
222
  "skipped",
252
223
  "blocked"
253
224
  ];
254
- 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.";
255
- const diffEvents = (before, after) => {
256
- const events = [];
257
- if (before.status === "waiting" && after.status === "planning") events.push({ event: "planning.started" });
258
- for (const entry of after.log) if (entry.role === "user" && entry.acknowledgedAt === void 0 && !before.log.some((previous) => previous.id === entry.id)) events.push({
259
- event: "message.created",
260
- messageId: entry.id,
261
- text: entry.text
262
- });
263
- for (const input of after.inputs) {
264
- if (before.inputs.find((candidate) => candidate.id === input.id)?.status === input.status) continue;
265
- if (input.status === "answered") {
266
- const answer = input.answer ?? "";
267
- events.push({
268
- event: "input.answered",
269
- inputId: input.id,
270
- prompt: input.prompt,
271
- ...answerFields(input, answer)
272
- });
273
- } else if (input.status === "dismissed" && after.status !== "cancelled") events.push({
274
- event: "input.dismissed",
275
- inputId: input.id,
276
- prompt: input.prompt
277
- });
278
- }
279
- for (const plan of after.plans) {
280
- if (before.plans.find((candidate) => candidate.revision === plan.revision)?.status === plan.status || plan.status === "proposed") continue;
281
- if (plan.status === "approved") events.push({
282
- event: "plan.approved",
283
- revision: plan.revision
284
- });
285
- else events.push({
286
- event: "plan.changes-requested",
287
- revision: plan.revision,
288
- feedback: plan.feedback ?? ""
289
- });
290
- }
291
- if (before.status !== "done" && after.status === "done") events.push({
292
- event: "finished",
293
- next: STAY_CONNECTED
294
- });
295
- if (before.status !== "cancelled" && after.status === "cancelled") events.push({
296
- event: "cancelled",
297
- next: STAY_CONNECTED
298
- });
299
- if (after.id !== null && after.id !== before.id) events.push({
300
- event: "setup.created",
301
- products: after.products.map((product) => product.slug)
302
- });
303
- return events;
304
- };
305
- const stream = async (client) => {
306
- let previous = requireState(client);
307
- let pending = diffEvents({
308
- ...previous,
309
- log: []
310
- }, previous);
311
- let timer = null;
312
- const flush = () => {
313
- timer = null;
314
- if (pending.length === 0) return;
315
- print(pending);
316
- pending = [];
317
- };
318
- client.subscribe(() => {
319
- const next = client.state;
320
- if (next === void 0) return;
321
- pending.push(...diffEvents(previous, next));
322
- previous = next;
323
- if (pending.length > 0 && timer === null) timer = setTimeout(flush, 200);
324
- });
325
- flush();
326
- const kind = detectAgentKind();
327
- await client.commands["agent/hello"]({
328
- cwd: process.cwd(),
329
- ...kind !== void 0 && { kind }
330
- });
331
- const heartbeat = setInterval(() => {
332
- client.commands["agent/heartbeat"]().catch(() => {});
333
- }, AGENT_HEARTBEAT_MS);
334
- const stop = () => {
335
- clearInterval(heartbeat);
336
- flush();
337
- client.commands["agent/bye"]().catch(() => {}).finally(() => {
338
- client.dispose();
339
- process.exit(0);
340
- });
341
- };
342
- process.on("SIGHUP", stop);
343
- process.on("SIGINT", stop);
344
- process.on("SIGTERM", stop);
345
- await new Promise(() => {});
346
- };
347
225
  /** Resolves once a setup is planning or installing, or once the one being waited on is cancelled; a setup already closed when the wait begins is over, so the wait is for the next one. */
348
226
  const waitForStart = (client) => new Promise((resolve) => {
349
227
  let previous;
@@ -622,18 +500,38 @@ const readRedeemKey = async (hash) => {
622
500
  continue;
623
501
  }
624
502
  };
625
- const answerFields = (input, answer) => ({
626
- answer: input.multiple && parseMultipleAnswer(answer) || answer,
627
- ...input.note !== void 0 && { note: input.note },
628
- ...input.kind === "choice" && classifyChoiceAnswer(input, answer) === "custom" && { custom: true }
629
- });
630
503
  const answered = (input) => ({
631
504
  ok: true,
632
505
  inputId: input.id,
633
506
  status: input.status,
634
507
  ...input.answer !== void 0 && answerFields(input, input.answer)
635
508
  });
636
- const main = async (argv) => {
509
+ const runStream = async (client, url, flags, options) => {
510
+ const setupAppUrl = options.browser?.setupAppUrl ?? flagText(flags, "setup-app-url");
511
+ const linkId = new URL(url).pathname.split("/").filter(Boolean).at(-1);
512
+ const stream = await followSetup(client, { ...setupAppUrl !== void 0 && linkId !== void 0 && { browser: {
513
+ setupAppUrl: parseSetupUrl(setupAppUrl),
514
+ linkId,
515
+ answerCommand: `${options.command ?? DEFAULT_COMMAND} ${shellWord(url)} answer`,
516
+ canOpen: (options.browser?.canOpen ?? true) && !flags.has("no-open")
517
+ } } });
518
+ const stop = () => {
519
+ stream.stop().finally(() => {
520
+ client.dispose();
521
+ process.exit(0);
522
+ });
523
+ };
524
+ process.on("SIGHUP", stop);
525
+ process.on("SIGINT", stop);
526
+ process.on("SIGTERM", stop);
527
+ await new Promise(() => {});
528
+ };
529
+ const main = (argv) => runSetupCommand(argv);
530
+ /**
531
+ * Runs one setup command (`<url> <command> ...`) the way `npx setup-agent`
532
+ * does, for a CLI that embeds setup as its own command.
533
+ */
534
+ const runSetupCommand = async (argv, options = {}) => {
637
535
  const { positional, flags } = parseArgs(argv);
638
536
  const [first, command = "intro", ...rest] = positional;
639
537
  if (flags.has("help") || flags.has("h") || first === void 0) {
@@ -654,7 +552,7 @@ const main = async (argv) => {
654
552
  case "intro": {
655
553
  const kind = detectAgentKind();
656
554
  await commands["agent/intro"]({ ...kind !== void 0 && { kind } }).catch(() => {});
657
- process.stdout.write(INSTRUCTIONS(url));
555
+ process.stdout.write(agentInstructions(url, { ...options.command !== void 0 && { command: options.command } }));
658
556
  process.stdout.write("\nCurrent setup:\n");
659
557
  print(summary(requireState(client)));
660
558
  break;
@@ -663,8 +561,19 @@ const main = async (argv) => {
663
561
  print(summary(requireState(client)));
664
562
  break;
665
563
  case "stream":
666
- await stream(client);
564
+ await runStream(client, url, flags, options);
667
565
  break;
566
+ case "answer": {
567
+ const id = rest[0] ?? fail("usage: answer <input-id|plan|finish> <answer> [--note <text>]");
568
+ const note = flagText(flags, "note");
569
+ const feedback = flagText(flags, "feedback");
570
+ print(await answerNeed(client, id, rest[1], {
571
+ ...note !== void 0 && { note },
572
+ ...feedback !== void 0 && { feedback },
573
+ ...flags.has("dismiss") && { dismiss: true }
574
+ }));
575
+ break;
576
+ }
668
577
  case "step": {
669
578
  const usage = "usage: step <step-id> <pending|active|done|skipped|blocked>";
670
579
  const stepId = rest[0] ?? fail(usage);
@@ -828,6 +737,6 @@ const main = async (argv) => {
828
737
  client.dispose();
829
738
  }
830
739
  };
831
- export { HELP, INSTRUCTIONS, agentInstructions, askSeed, detectAgentKind, diffEvents, isDirectInvocation, main, parseSetupUrl, upsertEnvLine, waitForStart, writeEnvSecret };
740
+ export { CODING_AGENTS, HELP, INSTRUCTIONS, agentInstructions, askSeed, detectAgentKind, diffEvents, findCommand, isDirectInvocation, main, parseSetupUrl, runCodingAgent, runSetupCommand, upsertEnvLine, waitForStart, writeEnvSecret };
832
741
 
833
742
  //# sourceMappingURL=cli.js.map