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/src/cli.ts CHANGED
@@ -1,7 +1,13 @@
1
+ import {
2
+ CODING_AGENTS,
3
+ detectAgentKind,
4
+ isDirectInvocation,
5
+ runCodingAgent,
6
+ } from "./agents";
7
+ import type { CodingAgent } from "./agents";
1
8
  import { connectCheckout } from "./client";
2
9
  import type { CheckoutClient } from "./client";
3
10
  import { INPUT_PRESETS, isPresetId, presetInput } from "./presets";
4
- import { spawn } from "node:child_process";
5
11
  import { createHash, randomBytes } from "node:crypto";
6
12
  import { constants } from "node:fs";
7
13
  import {
@@ -17,9 +23,7 @@ import { homedir, tmpdir, userInfo } from "node:os";
17
23
  import { createInterface } from "node:readline/promises";
18
24
  import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
19
25
  import {
20
- AGENT_HEARTBEAT_MS,
21
26
  OPTION_ICONS,
22
- classifyChoiceAnswer,
23
27
  currentPlan,
24
28
  isAgentPresent,
25
29
  isClosed,
@@ -27,16 +31,25 @@ import {
27
31
  isOptionIcon,
28
32
  isValidModelAnswer,
29
33
  parseEntryPointOptions,
30
- parseMultipleAnswer,
31
34
  stepProgress,
32
35
  } from "./protocol";
33
36
  import type { Checkout } from "./protocol";
37
+ import { answerNeed } from "./needs";
38
+ import { answerFields, followSetup, shellWord } from "./stream";
39
+
40
+ export { diffEvents } from "./stream";
41
+
42
+ const DEFAULT_COMMAND = "npx setup-agent";
34
43
 
35
44
  export const HELP = `setup-agent <url> [command]
36
45
 
37
46
  Commands (the url always comes first):
38
47
  status Print the setup as JSON.
39
- stream Follow the setup: one JSON array of events per line.
48
+ stream [--setup-app-url <url>] [--no-open]
49
+ 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.
50
+ answer <input-id> <answer> [--note <text>] [--dismiss]
51
+ answer plan approve | answer plan revise --feedback <text> | answer finish close
52
+ Answer for the user what they told you in your own conversation, as an "input.needed" event's "answer" shows.
40
53
  log <text> Send a message to the user: a reply, something no question or step conveys, or one wrap-up when finished.
41
54
  ack <message-id> Acknowledge a user message.
42
55
  ask <prompt> [--placeholder <text>] [--optional] [--step <step-id>] [--wait]
@@ -107,55 +120,107 @@ export const parseSetupUrl = (value: string): string => {
107
120
  return href;
108
121
  };
109
122
 
110
- /** `value` as one shell word, quoted only when it holds more than plain URL characters. */
111
- const shellWord = (value: string) =>
112
- /^[A-Za-z0-9._~%/:@=+,-]+$/.test(value)
113
- ? value
114
- : `'${value.replaceAll("'", `'\\''`)}'`;
123
+ export type AgentInstructionsOptions = {
124
+ /** How the agent invokes the setup commands, before the URL; `npx setup-agent` by default. */
125
+ command?: string;
126
+ /**
127
+ * The agent started this setup with `assistant-ui setup`, which already
128
+ * began planning; there is no Begin plan click to wait for.
129
+ */
130
+ startedByAgent?: {
131
+ browserUrl: string;
132
+ /** False when the browser was not opened for the user; the agent then hands them the link. */
133
+ opened?: boolean;
134
+ /**
135
+ * The command that printed this briefing is the stream: it keeps running
136
+ * and opens the browser only when the setup waits on the user.
137
+ */
138
+ streaming?: boolean;
139
+ };
140
+ };
141
+
142
+ 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})`;
115
143
 
116
- export const agentInstructions = (setupUrl: string) => {
144
+ const beginPlanHandoff = (cmd: string, url: string) =>
145
+ `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:
146
+ ${cmd} ${url} wait start
147
+ 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.`;
148
+
149
+ const agentStartedHandoff = ({
150
+ browserUrl,
151
+ opened = true,
152
+ streaming = false,
153
+ }: NonNullable<AgentInstructionsOptions["startedByAgent"]>) =>
154
+ streaming
155
+ ? `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.`
156
+ : `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: ${
157
+ opened
158
+ ? `"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} ."`
159
+ : `"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."`
160
+ } 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.`;
161
+
162
+ const streamSection = (
163
+ cmd: string,
164
+ url: string,
165
+ streaming: boolean,
166
+ noOpen: boolean,
167
+ ) =>
168
+ streaming
169
+ ? `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:
170
+ - "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.
171
+ - "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.
172
+ If this command stops, start it again in the background with
173
+ ${cmd} ${url} stream${noOpen ? " --no-open" : ""}
174
+ 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.`
175
+ : `First, start a persistent Monitor on
176
+ ${cmd} ${url} stream
177
+ 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}.`;
178
+
179
+ export const agentInstructions = (
180
+ setupUrl: string,
181
+ options: AgentInstructionsOptions = {},
182
+ ) => {
117
183
  const url = shellWord(setupUrl);
118
- 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.
184
+ const cmd = options.command ?? DEFAULT_COMMAND;
185
+ const started = options.startedByAgent;
186
+ const streaming = started?.streaming === true;
187
+ 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.
119
188
 
120
- First, start a persistent Monitor on
121
- npx setup-agent ${url} stream
122
- 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}).
189
+ ${streamSection(cmd, url, streaming, started?.opened === false)}
123
190
 
124
- 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.
191
+ 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.
125
192
 
126
193
  "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.
127
194
 
128
- 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:
129
- npx setup-agent ${url} wait start
130
- 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.
195
+ ${started ? agentStartedHandoff(started) : beginPlanHandoff(cmd, url)}
131
196
 
132
197
  The remaining phases are plan, then install.
133
198
 
134
199
  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:
135
- npx setup-agent ${url} ask "Which project should I install into?" --placeholder "An absolute path to the app" --wait
200
+ ${cmd} ${url} ask "Which project should I install into?" --placeholder "An absolute path to the app" --wait
136
201
  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:
137
- npx setup-agent ${url} ask --preset framework
138
- npx setup-agent ${url} ask --preset llm-provider
139
- 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.
202
+ ${cmd} ${url} ask --preset framework
203
+ ${cmd} ${url} ask --preset llm-provider
204
+ 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.
140
205
  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:
141
- npx setup-agent ${url} ask "Where should users access the assistant?" --entry-points '<JSON array>' --wait
206
+ ${cmd} ${url} ask "Where should users access the assistant?" --entry-points '<JSON array>' --wait
142
207
  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.
143
208
  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.
144
209
  Then write the plan as markdown and submit it:
145
- npx setup-agent ${url} plan --file <path> --wait
210
+ ${cmd} ${url} plan --file <path> --wait
146
211
  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.
147
212
 
148
213
  2. Install. Declare the steps from your plan up front, in order:
149
- npx setup-agent ${url} add-step "<title>" --detail "<one line>"
214
+ ${cmd} ${url} add-step "<title>" --detail "<one line>"
150
215
  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.
151
216
  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
152
- npx setup-agent ${url} env <input-id> <ENV_VAR> --file .env.local
153
- 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.
217
+ ${cmd} ${url} env <input-id> <ENV_VAR> --file .env.local
218
+ 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.
154
219
 
155
220
  When every product is installed and verified, run
156
- npx setup-agent ${url} done --summary "<one or two lines on what you installed and how to try it>" --preview http://localhost:<port>
221
+ ${cmd} ${url} done --summary "<one or two lines on what you installed and how to try it>" --preview http://localhost:<port>
157
222
  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
158
- npx setup-agent ${url} wait start
223
+ ${cmd} ${url} wait start
159
224
  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.
160
225
  `;
161
226
  };
@@ -185,6 +250,15 @@ const parseArgs = (argv: readonly string[]): Parsed => {
185
250
  return { positional, flags };
186
251
  };
187
252
 
253
+ export {
254
+ CODING_AGENTS,
255
+ detectAgentKind,
256
+ findCommand,
257
+ isDirectInvocation,
258
+ runCodingAgent,
259
+ } from "./agents";
260
+ export type { CodingAgent } from "./agents";
261
+
188
262
  const flagText = (flags: Parsed["flags"], name: string) => {
189
263
  const value = flags.get(name);
190
264
  return typeof value === "string" ? value : undefined;
@@ -199,66 +273,13 @@ const print = (value: unknown) => {
199
273
  process.stdout.write(`${JSON.stringify(value)}\n`);
200
274
  };
201
275
 
202
- const AGENT_ENV: readonly [kind: string, variable: string][] = [
203
- ["claude", "CLAUDECODE"],
204
- ["codex", "CODEX_SANDBOX"],
205
- ["codex", "CODEX_SANDBOX_NETWORK_DISABLED"],
206
- ["cursor", "CURSOR_AGENT"],
207
- ["gemini", "GEMINI_CLI"],
208
- ];
209
-
210
- /** The coding agent this process runs under, from the variables each one exports to its shell. */
211
- export const detectAgentKind = (env: NodeJS.ProcessEnv = process.env) =>
212
- AGENT_ENV.find(([, variable]) => env[variable])?.[0];
213
-
214
- type Launcher = {
215
- kind: string;
216
- name: string;
217
- command: string;
218
- args: (prompt: string) => string[];
219
- install: string;
220
- };
221
-
222
- const LAUNCHERS: Launcher[] = [
223
- {
224
- kind: "claude",
225
- name: "Claude Code",
226
- command: "claude",
227
- args: (prompt) => [prompt],
228
- install: "npm install -g @anthropic-ai/claude-code",
229
- },
230
- {
231
- kind: "codex",
232
- name: "Codex",
233
- command: "codex",
234
- args: (prompt) => [prompt],
235
- install: "npm install -g @openai/codex",
236
- },
237
- {
238
- kind: "cursor",
239
- name: "Cursor",
240
- command: "agent",
241
- args: (prompt) => [prompt],
242
- install: "curl https://cursor.com/install -fsS | bash",
243
- },
244
- {
245
- kind: "gemini",
246
- name: "Gemini CLI",
247
- command: "gemini",
248
- args: (prompt) => ["-i", prompt],
249
- install: "npm install -g @google/gemini-cli",
250
- },
251
- ];
252
-
253
- /** True when a person typed the command into a terminal rather than an agent running it from its shell. */
254
- export const isDirectInvocation = (
255
- env: NodeJS.ProcessEnv = process.env,
256
- stdin: { isTTY?: boolean | undefined } = process.stdin,
257
- stdout: { isTTY?: boolean | undefined } = process.stdout,
258
- ) =>
259
- detectAgentKind(env) === undefined &&
260
- stdin.isTTY === true &&
261
- stdout.isTTY === true;
276
+ /** The agents `setup-agent <url>` can start itself, for a person who ran it in a terminal. */
277
+ const LAUNCHERS = CODING_AGENTS.filter(
278
+ (
279
+ agent,
280
+ ): agent is CodingAgent & { launch: NonNullable<CodingAgent["launch"]> } =>
281
+ agent.launch !== undefined,
282
+ );
262
283
 
263
284
  const chooseLauncher = async () => {
264
285
  const rl = createInterface({ input: process.stdin, output: process.stdout });
@@ -293,23 +314,14 @@ const launchAgent = async (url: string) => {
293
314
  const launcher = await chooseLauncher();
294
315
  const prompt = `Run \`npx setup-agent ${shellWord(url)}\` and follow the instructions it prints.`;
295
316
  process.stdout.write(`\nStarting ${launcher.name}...\n\n`);
296
- const child = spawn(launcher.command, launcher.args(prompt), {
297
- stdio: "inherit",
298
- });
299
- const code = await new Promise<number>((resolve) => {
300
- child.on("error", (error: NodeJS.ErrnoException) => {
301
- if (error.code === "ENOENT") {
302
- process.stderr.write(
303
- `${launcher.name} is not installed. Install it with:\n ${launcher.install}\nthen run this command again.\n`,
304
- );
305
- } else {
306
- process.stderr.write(`${error.message}\n`);
307
- }
308
- resolve(1);
309
- });
310
- child.on("exit", (status) => resolve(status ?? 1));
311
- });
312
- process.exit(code);
317
+ const code = await runCodingAgent(launcher, prompt);
318
+ if (code === undefined) {
319
+ process.stderr.write(
320
+ `${launcher.name} is not installed. Install it with:\n ${launcher.launch.install}\nthen run this command again.\n`,
321
+ );
322
+ }
323
+ // Exit once stdout and stderr have drained.
324
+ process.exitCode = code ?? 1;
313
325
  };
314
326
 
315
327
  const requireState = (client: CheckoutClient): Checkout.State =>
@@ -348,145 +360,6 @@ const STEP_STATUSES: readonly Checkout.StepStatus[] = [
348
360
  "blocked",
349
361
  ];
350
362
 
351
- type StreamEvent =
352
- | { event: "planning.started" }
353
- | { event: "message.created"; messageId: string; text: string }
354
- | {
355
- event: "input.answered";
356
- inputId: string;
357
- prompt: string;
358
- /** The entries of a multiple choice answer, else the answer text. */
359
- answer: string | string[];
360
- note?: string;
361
- /** True when a choice answer is, or a multiple one contains, the user's own text rather than an option. */
362
- custom?: true;
363
- }
364
- | { event: "input.dismissed"; inputId: string; prompt: string }
365
- | { event: "plan.approved"; revision: number }
366
- | { event: "plan.changes-requested"; revision: number; feedback: string }
367
- | { event: "finished"; next: string }
368
- | { event: "cancelled"; next: string }
369
- | { event: "setup.created"; products: string[] };
370
-
371
- const STAY_CONNECTED =
372
- "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.";
373
-
374
- export const diffEvents = (
375
- before: Checkout.State,
376
- after: Checkout.State,
377
- ): StreamEvent[] => {
378
- const events: StreamEvent[] = [];
379
- if (before.status === "waiting" && after.status === "planning") {
380
- events.push({ event: "planning.started" });
381
- }
382
- for (const entry of after.log) {
383
- if (
384
- entry.role === "user" &&
385
- entry.acknowledgedAt === undefined &&
386
- !before.log.some((previous) => previous.id === entry.id)
387
- ) {
388
- events.push({
389
- event: "message.created",
390
- messageId: entry.id,
391
- text: entry.text,
392
- });
393
- }
394
- }
395
- for (const input of after.inputs) {
396
- const previous = before.inputs.find(
397
- (candidate) => candidate.id === input.id,
398
- );
399
- if (previous?.status === input.status) continue;
400
- if (input.status === "answered") {
401
- const answer = input.answer ?? "";
402
- events.push({
403
- event: "input.answered",
404
- inputId: input.id,
405
- prompt: input.prompt,
406
- ...answerFields(input, answer),
407
- });
408
- } else if (input.status === "dismissed" && after.status !== "cancelled") {
409
- events.push({
410
- event: "input.dismissed",
411
- inputId: input.id,
412
- prompt: input.prompt,
413
- });
414
- }
415
- }
416
- for (const plan of after.plans) {
417
- const previous = before.plans.find(
418
- (candidate) => candidate.revision === plan.revision,
419
- );
420
- if (previous?.status === plan.status || plan.status === "proposed") {
421
- continue;
422
- }
423
- if (plan.status === "approved") {
424
- events.push({ event: "plan.approved", revision: plan.revision });
425
- } else {
426
- events.push({
427
- event: "plan.changes-requested",
428
- revision: plan.revision,
429
- feedback: plan.feedback ?? "",
430
- });
431
- }
432
- }
433
- if (before.status !== "done" && after.status === "done") {
434
- events.push({ event: "finished", next: STAY_CONNECTED });
435
- }
436
- if (before.status !== "cancelled" && after.status === "cancelled") {
437
- events.push({ event: "cancelled", next: STAY_CONNECTED });
438
- }
439
- if (after.id !== null && after.id !== before.id) {
440
- events.push({
441
- event: "setup.created",
442
- products: after.products.map((product) => product.slug),
443
- });
444
- }
445
- return events;
446
- };
447
-
448
- const stream = async (client: CheckoutClient) => {
449
- let previous = requireState(client);
450
- let pending: StreamEvent[] = diffEvents({ ...previous, log: [] }, previous);
451
- let timer: ReturnType<typeof setTimeout> | null = null;
452
- const flush = () => {
453
- timer = null;
454
- if (pending.length === 0) return;
455
- print(pending);
456
- pending = [];
457
- };
458
- client.subscribe(() => {
459
- const next = client.state;
460
- if (next === undefined) return;
461
- pending.push(...diffEvents(previous, next));
462
- previous = next;
463
- if (pending.length > 0 && timer === null) timer = setTimeout(flush, 200);
464
- });
465
- flush();
466
- const kind = detectAgentKind();
467
- await client.commands["agent/hello"]({
468
- cwd: process.cwd(),
469
- ...(kind !== undefined && { kind }),
470
- });
471
- const heartbeat = setInterval(() => {
472
- void client.commands["agent/heartbeat"]().catch(() => {});
473
- }, AGENT_HEARTBEAT_MS);
474
- const stop = () => {
475
- clearInterval(heartbeat);
476
- flush();
477
- void client.commands["agent/bye"]()
478
- .catch(() => {})
479
- .finally(() => {
480
- client.dispose();
481
- process.exit(0);
482
- });
483
- };
484
- process.on("SIGHUP", stop);
485
- process.on("SIGINT", stop);
486
- process.on("SIGTERM", stop);
487
- await new Promise(() => {});
488
- };
489
-
490
363
  /** 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. */
491
364
  export const waitForStart = (
492
365
  client: Pick<CheckoutClient, "state" | "subscribe">,
@@ -893,15 +766,6 @@ const readRedeemKey = async (hash: string) => {
893
766
  return undefined;
894
767
  };
895
768
 
896
- const answerFields = (input: Checkout.Input, answer: string) => ({
897
- answer: (input.multiple && parseMultipleAnswer(answer)) || answer,
898
- ...(input.note !== undefined && { note: input.note }),
899
- ...(input.kind === "choice" &&
900
- classifyChoiceAnswer(input, answer) === "custom" && {
901
- custom: true as const,
902
- }),
903
- });
904
-
905
769
  const answered = (input: Checkout.Input) => ({
906
770
  ok: true,
907
771
  inputId: input.id,
@@ -909,7 +773,55 @@ const answered = (input: Checkout.Input) => ({
909
773
  ...(input.answer !== undefined && answerFields(input, input.answer)),
910
774
  });
911
775
 
912
- export const main = async (argv: readonly string[]) => {
776
+ export type RunSetupCommandOptions = {
777
+ /** How the agent invokes these commands, before the URL; `npx setup-agent` by default. */
778
+ command?: string;
779
+ /** Lets "stream" open the setup page when the setup waits on the user, as `--setup-app-url` does. */
780
+ browser?: { setupAppUrl: string; canOpen?: boolean };
781
+ };
782
+
783
+ const runStream = async (
784
+ client: CheckoutClient,
785
+ url: string,
786
+ flags: Parsed["flags"],
787
+ options: RunSetupCommandOptions,
788
+ ) => {
789
+ const setupAppUrl =
790
+ options.browser?.setupAppUrl ?? flagText(flags, "setup-app-url");
791
+ const linkId = new URL(url).pathname.split("/").filter(Boolean).at(-1);
792
+ const stream = await followSetup(client, {
793
+ ...(setupAppUrl !== undefined &&
794
+ linkId !== undefined && {
795
+ browser: {
796
+ setupAppUrl: parseSetupUrl(setupAppUrl),
797
+ linkId,
798
+ answerCommand: `${options.command ?? DEFAULT_COMMAND} ${shellWord(url)} answer`,
799
+ canOpen: (options.browser?.canOpen ?? true) && !flags.has("no-open"),
800
+ },
801
+ }),
802
+ });
803
+ const stop = () => {
804
+ void stream.stop().finally(() => {
805
+ client.dispose();
806
+ process.exit(0);
807
+ });
808
+ };
809
+ process.on("SIGHUP", stop);
810
+ process.on("SIGINT", stop);
811
+ process.on("SIGTERM", stop);
812
+ await new Promise(() => {});
813
+ };
814
+
815
+ export const main = (argv: readonly string[]) => runSetupCommand(argv);
816
+
817
+ /**
818
+ * Runs one setup command (`<url> <command> ...`) the way `npx setup-agent`
819
+ * does, for a CLI that embeds setup as its own command.
820
+ */
821
+ export const runSetupCommand = async (
822
+ argv: readonly string[],
823
+ options: RunSetupCommandOptions = {},
824
+ ) => {
913
825
  const { positional, flags } = parseArgs(argv);
914
826
  const [first, command = "intro", ...rest] = positional;
915
827
  if (flags.has("help") || flags.has("h") || first === undefined) {
@@ -936,7 +848,11 @@ export const main = async (argv: readonly string[]) => {
936
848
  await commands["agent/intro"]({
937
849
  ...(kind !== undefined && { kind }),
938
850
  }).catch(() => {});
939
- process.stdout.write(INSTRUCTIONS(url));
851
+ process.stdout.write(
852
+ agentInstructions(url, {
853
+ ...(options.command !== undefined && { command: options.command }),
854
+ }),
855
+ );
940
856
  process.stdout.write("\nCurrent setup:\n");
941
857
  print(summary(requireState(client)));
942
858
  break;
@@ -946,7 +862,22 @@ export const main = async (argv: readonly string[]) => {
946
862
  break;
947
863
  }
948
864
  case "stream": {
949
- await stream(client);
865
+ await runStream(client, url, flags, options);
866
+ break;
867
+ }
868
+ case "answer": {
869
+ const id =
870
+ rest[0] ??
871
+ fail("usage: answer <input-id|plan|finish> <answer> [--note <text>]");
872
+ const note = flagText(flags, "note");
873
+ const feedback = flagText(flags, "feedback");
874
+ print(
875
+ await answerNeed(client, id, rest[1], {
876
+ ...(note !== undefined && { note }),
877
+ ...(feedback !== undefined && { feedback }),
878
+ ...(flags.has("dismiss") && { dismiss: true }),
879
+ }),
880
+ );
950
881
  break;
951
882
  }
952
883
  case "step": {
package/src/host.test.ts CHANGED
@@ -57,6 +57,31 @@ const approvedHost = async () => {
57
57
  };
58
58
 
59
59
  describe("CheckoutHost", () => {
60
+ it("tracks the setup page's presence apart from the agent's", async () => {
61
+ const host = mount();
62
+ expect(host.state.browser).toEqual({ lastSeenAt: null, connected: false });
63
+ await host.commands["checkout/create"](seed);
64
+ await host.commands["browser/heartbeat"]();
65
+ expect(host.state.browser).toEqual({
66
+ lastSeenAt: expect.any(Number),
67
+ connected: true,
68
+ });
69
+ expect(isAgentPresent(host.state)).toBe(false);
70
+ await host.commands["browser/bye"]();
71
+ expect(host.state.browser!.connected).toBe(false);
72
+ });
73
+
74
+ it("restores a snapshot from before browser presence with the page absent", () => {
75
+ const { browser: _, ...old } = {
76
+ ...initialCheckoutState(),
77
+ id: "c1",
78
+ createdAt: 1,
79
+ };
80
+ const host = mount(old);
81
+ expect(host.state.browser).toEqual({ lastSeenAt: null, connected: false });
82
+ expect(host.state.id).toBe("c1");
83
+ });
84
+
60
85
  it("creates the products once, with no steps or questions", async () => {
61
86
  const host = mount();
62
87
  await host.commands["checkout/create"](seed);
package/src/host.ts CHANGED
@@ -32,6 +32,7 @@ const useCheckoutHost = (restored: unknown) => {
32
32
  ...initial,
33
33
  ...snapshot,
34
34
  agent: { ...initial.agent, ...snapshot.agent },
35
+ browser: { ...initial.browser!, ...snapshot.browser },
35
36
  };
36
37
  });
37
38
 
@@ -401,6 +402,12 @@ const useCheckoutHost = (restored: unknown) => {
401
402
  "agent/bye": () => {
402
403
  state.agent.connected = false;
403
404
  },
405
+ "browser/heartbeat": () => {
406
+ state.browser = { lastSeenAt: Date.now(), connected: true };
407
+ },
408
+ "browser/bye": () => {
409
+ if (state.browser) state.browser.connected = false;
410
+ },
404
411
  "agent/plan": ({ markdown }) => {
405
412
  requireStarted();
406
413
  touchAgent();
package/src/index.ts CHANGED
@@ -2,6 +2,7 @@ export type { Checkout, OptionIcon } from "./protocol";
2
2
  export {
3
3
  AGENT_HEARTBEAT_MS,
4
4
  AGENT_PRESENCE_MS,
5
+ BROWSER_HEARTBEAT_MS,
5
6
  OPTION_ICONS,
6
7
  classifyChoiceAnswer,
7
8
  currentPlan,