setup-agent 0.0.2 → 0.0.4

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AgentbaseAI Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,9 +1,9 @@
1
1
  # setup-agent
2
2
 
3
- One checkout, shared live between the browser that opened it and the coding agent installing its products. The state is a Statewire host (`setup-agent/host`) served from a Cloudflare Durable Object (`apps/checkout-worker`); the CLI (`npx setup-agent <url>`) is a thin Statewire client the agent drives from its shell.
3
+ One setup, shared live between the browser that opened it and the coding agent installing its products. The state is a Statewire host (`setup-agent/host`) served from a Cloudflare Durable Object (`apps/checkout-worker`); the CLI (`npx setup-agent <url>`) is a thin Statewire client the agent drives from its shell.
4
4
 
5
5
  ```sh
6
- npx setup-agent <url> # instructions plus the current checkout
6
+ npx setup-agent <url> # instructions plus the current setup
7
7
  npx setup-agent <url> stream # one JSON array of events per line; run it under a Monitor
8
8
  npx setup-agent <url> wait start # wait for the user to click Begin plan in their browser
9
9
  npx setup-agent <url> log "Sure, I will keep the existing chat route" # a reply, or something no question or step conveys
@@ -21,13 +21,13 @@ npx setup-agent <url> done --summary "installed the thread and a chat route" --p
21
21
 
22
22
  ## Phases
23
23
 
24
- A checkout opens `waiting` with its products and nothing else: no steps, no questions. After connecting, the agent tells the user to return to their browser and click **Begin plan**. It keeps the stream running and blocks on `wait start`. The browser sends `checkout/begin-plan`, moving the checkout to `planning` and emitting `planning.started` on the stream. Questions and plan submissions are refused while waiting. When a product needs another one the project lacks, the agent proposes it with `ask "<why>" --product <slug>`; the browser, which owns the catalog, accepts with `checkout/add-product` (the product and its guide join `products`, the input answers `added`) or dismisses the input. In `planning`, the agent investigates the project, asks what the code does not decide, and proposes a markdown plan with `plan` carrying its findings. `log` is for replying to the user and for what no question or step conveys. The user approves the plan or asks for changes with feedback; every revision is kept. Approval moves the checkout to `installing`, where the agent declares its own steps with `add-step` and works through them with `step`. `add-step` and `step` are refused before approval. `done` marks the remaining steps done and proposes closing, with an optional `--summary` and an optional `--preview <url>` naming a dev server the agent left running; a preview must be an http(s) URL on localhost, and the browser offers to open it. `done` does not close. The browser shows the proposal with a close action that sends `checkout/finish`, and the stream prints `finished`. Until then the agent stays idle on the stream, because the user may send a follow-up message; after handling one it runs `done` again to renew the proposal.
24
+ A setup opens `waiting` with its products and nothing else: no steps, no questions. After connecting, the agent tells the user to return to their browser and click **Begin plan**. It keeps the stream running and blocks on `wait start`, which prints `{"ok":true,"status":"planning"}` once planning begins, or `{"ok":false,"status":"cancelled"}` when the user ends the setup first. The browser sends `checkout/begin-plan`, moving the setup to `planning` and emitting `planning.started` on the stream. Questions and plan submissions are refused while waiting. When a product needs another one the project lacks, the agent proposes it with `ask "<why>" --product <slug>`; the browser, which owns the catalog, accepts with `checkout/add-product` (the product and its guide join `products`, the input answers `added`) or dismisses the input. In `planning`, the agent investigates the project, asks what the code does not decide, and proposes a markdown plan with `plan` carrying its findings. `log` is for replying to the user and for what no question or step conveys. The user approves the plan or asks for changes with feedback; every revision is kept. Approval moves the setup to `installing`, where the agent declares its own steps with `add-step` and works through them with `step`. `add-step` and `step` are refused before approval. `done` marks the remaining steps done and proposes closing, with an optional `--summary` and an optional `--preview <url>` naming a dev server the agent left running; a preview must be an http(s) URL on localhost, and the browser offers to open it. `done` does not close. The browser shows the proposal with a close action that sends `checkout/finish`, and the stream prints `finished`. Until then the agent stays idle on the stream, because the user may send a follow-up message; after handling one it runs `done` again to renew the proposal.
25
25
 
26
- The URL is the browser's link to its agent, not one checkout. A finished or cancelled checkout stays on the link, and the browser's next setup replaces it with a new `checkout/create` carrying a new `id`: the plans, steps, inputs and log start over, the agent's presence carries across when it is still connected, and the stream prints `checkout.created` with the new products. The agent keeps the stream running after `finished` or `cancelled` and blocks on `wait start`, which returns once the next checkout begins planning; a checkout already closed when the wait begins is skipped rather than reported.
26
+ The URL is the browser's link to its agent, not one setup. A finished or cancelled setup stays on the link, and the browser's next setup replaces it with a new `checkout/create` carrying a new `id`: the plans, steps, inputs and log start over, the agent's presence carries across when it is still connected, and the stream prints `setup.created` with the new products. The agent keeps the stream running after `finished` or `cancelled` and blocks on `wait start`, which returns once the next setup begins planning; a setup already closed when the wait begins is skipped rather than reported.
27
27
 
28
28
  ## Inputs
29
29
 
30
- Every input is `text`, `choice` or `model`. A choice carries `options` (`id`, `label`, `description`, `icon`, `variants`), an optional `default` and a `help` note the browser renders as a "help me choose" disclosure. The answer is the option id, `<option>:<variant>` when the option has variants (`langgraph:python`), or the user's own text when none of the options fit; the stream marks that answer `custom`. An agent's own choice is multi-select unless asked with `--single`: the user checks any number of options (none may have variants), and the answer is a JSON array of those entries, which `wait` and the stream print as an array and `status` holds as text. `--single` is for options that exclude each other (one framework, one model, yes or no) and answers one id. Every one of the agent's own options must carry an `icon` from the pack `OPTION_ICONS` exports (`--icons "slack=message,email=mail"`); the CLI refuses the question otherwise. A preset option carries a brand mark instead. Every answer may carry a `note` from the user. A model input lists providers as its options; the browser collects the provider, its API key, the model and an optional reasoning effort, and the answer is that object as JSON (`{"provider","model","reasoningEffort"?}`); the API key is deposited separately and only ever reaches the env file the agent names through `env`.
30
+ Every input is `text`, `choice` or `model`. A choice carries `options` (`id`, `label`, `description`, `icon`, `variants`), an optional `default` and a `help` note the browser renders as a "help me choose" disclosure. Option ids are unique, and neither option nor variant ids may contain `:`. The answer is the option id, `<option>:<variant>` when the option has variants (`langgraph:python`), or the user's own text when none of the options fit (including any text with more than one `:`); the stream marks that answer `custom`. An agent's own choice is multi-select unless asked with `--single`: the user checks any number of options (none may have variants), and the answer is a JSON array of those entries, which `wait` and the stream print as an array and `status` holds as text. `--single` is for options that exclude each other (one framework, one model, yes or no) and answers one id. Every one of the agent's own options must carry an `icon` from the pack `OPTION_ICONS` exports (`--icons "slack=message,email=mail"`); the CLI refuses the question otherwise. A preset option carries a brand mark instead. Every answer may carry a `note` from the user. A model input lists providers as its options; the browser collects the provider, its API key, the model and an optional reasoning effort, and the answer is that object as JSON (`{"provider","model","reasoningEffort"?}`); the API key is deposited separately and only ever reaches the env file the agent names through `env`.
31
31
 
32
32
  Three standard choices ship as presets (`setup-agent` exports `INPUT_PRESETS` and `presetInput`), so the browser and the CLI agree on their options and brand marks:
33
33
 
@@ -35,4 +35,8 @@ Three standard choices ship as presets (`setup-agent` exports `INPUT_PRESETS` an
35
35
  - `llm-provider`: OpenAI, Anthropic, Google Gemini, OpenRouter, xAI, Mistral, DeepSeek, Groq, Fireworks AI; defaults to OpenAI. Rendered as the model picker (provider, key, model, reasoning effort).
36
36
  - `project`: the React projects the agent found, passed as `--choices "apps/web=Next.js,apps/admin"`, ahead of a fixed "New project" option whose second pick is the meta framework. Answers a path, or `new:<next|vite|react-router|tanstack-start|expo>`.
37
37
 
38
- `--only` restricts a preset to some of its options (a single id locks the choice in) and `--default` preselects one.
38
+ `--only` restricts a preset to some of its options and leaves out `--choices` (a single id locks the choice in) and `--default` preselects one.
39
+
40
+ ## Workspace
41
+
42
+ The package lives in `packages/setup-agent`; its Cloudflare worker lives in `apps/checkout-worker`. Build the worker dependencies with `pnpm turbo build --filter="checkout-worker^..."`, then run `pnpm --filter checkout-worker dev`. The worker consumes the published `@statewire/cloudflare` adapter.
package/dist/cli.d.ts CHANGED
@@ -1,64 +1,70 @@
1
- /// <reference types="node" />
2
- import { Checkout } from "./protocol.js";
3
- import { CheckoutClient } from "./client.js";
4
- //#region src/cli.d.ts
1
+ import type { CheckoutClient } from "./client.js";
2
+ import type { Checkout } from "./protocol.js";
3
+ export declare const HELP: string;
4
+ export declare const INSTRUCTIONS: (url: string) => string;
5
5
  type Parsed = {
6
- positional: string[];
7
- flags: Map<string, string | true>;
6
+ positional: string[];
7
+ flags: Map<string, string | true>;
8
8
  };
9
9
  /** The coding agent this process runs under, from the variables each one exports to its shell. */
10
- declare const detectAgentKind: (env?: NodeJS.ProcessEnv) => string | undefined;
10
+ export declare const detectAgentKind: (env?: NodeJS.ProcessEnv) => string | undefined;
11
11
  /** True when a person typed the command into a terminal rather than an agent running it from its shell. */
12
- declare const isDirectInvocation: (env?: NodeJS.ProcessEnv, stdin?: {
13
- isTTY?: boolean | undefined;
12
+ export declare const isDirectInvocation: (env?: NodeJS.ProcessEnv, stdin?: {
13
+ isTTY?: boolean | undefined;
14
14
  }, stdout?: {
15
- isTTY?: boolean | undefined;
15
+ isTTY?: boolean | undefined;
16
16
  }) => boolean;
17
17
  type StreamEvent = {
18
- event: "planning.started";
18
+ event: "planning.started";
19
19
  } | {
20
- event: "message.created";
21
- messageId: string;
22
- text: string;
20
+ event: "message.created";
21
+ messageId: string;
22
+ text: string;
23
23
  } | {
24
- event: "input.answered";
25
- inputId: string;
26
- prompt: string;
27
- /** The entries of a multiple choice answer, else the answer text. */
28
- answer: string | string[];
29
- note?: string;
30
- /** True when a choice answer is, or a multiple one contains, the user's own text rather than an option. */
31
- custom?: true;
24
+ event: "input.answered";
25
+ inputId: string;
26
+ prompt: string;
27
+ /** The entries of a multiple choice answer, else the answer text. */
28
+ answer: string | string[];
29
+ note?: string;
30
+ /** True when a choice answer is, or a multiple one contains, the user's own text rather than an option. */
31
+ custom?: true;
32
32
  } | {
33
- event: "input.dismissed";
34
- inputId: string;
35
- prompt: string;
33
+ event: "input.dismissed";
34
+ inputId: string;
35
+ prompt: string;
36
36
  } | {
37
- event: "plan.approved";
38
- revision: number;
37
+ event: "plan.approved";
38
+ revision: number;
39
39
  } | {
40
- event: "plan.changes-requested";
41
- revision: number;
42
- feedback: string;
40
+ event: "plan.changes-requested";
41
+ revision: number;
42
+ feedback: string;
43
43
  } | {
44
- event: "finished";
45
- next: string;
44
+ event: "finished";
45
+ next: string;
46
46
  } | {
47
- event: "cancelled";
48
- next: string;
47
+ event: "cancelled";
48
+ next: string;
49
49
  } | {
50
- event: "checkout.created";
51
- products: string[];
50
+ event: "setup.created";
51
+ products: string[];
52
52
  };
53
- declare const diffEvents: (before: Checkout.State, after: Checkout.State) => StreamEvent[];
54
- /** 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. */
55
- declare const waitForStart: (client: Pick<CheckoutClient, "state" | "subscribe">) => Promise<Checkout.Status>;
56
- declare const askSeed: (rest: readonly string[], flags: Parsed["flags"]) => Checkout.InputSeed & {
57
- stepId?: string;
53
+ export declare const diffEvents: (before: Checkout.State, after: Checkout.State) => StreamEvent[];
54
+ /** 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. */
55
+ export declare const waitForStart: (client: Pick<CheckoutClient, "state" | "subscribe">) => Promise<Checkout.Status>;
56
+ export declare const askSeed: (rest: readonly string[], flags: Parsed["flags"]) => Checkout.InputSeed & {
57
+ stepId?: string;
58
58
  };
59
59
  /** Sets `key=value` in dotenv text, replacing an existing line for the key. */
60
- declare const upsertEnvLine: (content: string, key: string, value: string) => string;
61
- declare const main: (argv: readonly string[]) => Promise<undefined>;
62
- //#endregion
63
- export { askSeed, detectAgentKind, diffEvents, isDirectInvocation, main, upsertEnvLine, waitForStart };
60
+ export declare const upsertEnvLine: (content: string, key: string, value: string) => string;
61
+ /**
62
+ * Write the secret `take` returns to `file` under `key`, leaving the file
63
+ * owner-only. The file is opened before `take` runs, because taking the
64
+ * secret consumes it and an unwritable destination must fail while it is
65
+ * still deposited; it is read after, so lines written meanwhile survive.
66
+ */
67
+ export declare const writeEnvSecret: (file: string, key: string, take: () => Promise<string>) => Promise<void>;
68
+ export declare const main: (argv: readonly string[]) => Promise<undefined>;
69
+ export {};
64
70
  //# sourceMappingURL=cli.d.ts.map
package/dist/cli.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.d.ts","names":[],"sources":["../src/cli.ts"],"mappings":";;;KAsGK;EAAW;EAAsB,OAAO;;;cA8ChC,kBAAmB,MAAK,OAAO;;cA2C/B,qBACX,MAAK,OAAO,YACZ;EAAS;GACT;EAAU;;KA8FP;EACC;;EACA;EAA0B;EAAmB;;EAE7C;EACA;EACA;;EAEA;EACA;;EAEA;;EAEA;EAA0B;EAAiB;;EAC3C;EAAwB;;EACxB;EAAiC;EAAkB;;EACnD;EAAmB;;EACnB;EAAoB;;EACpB;EAA2B;;cAKpB,aACX,QAAQ,SAAS,OACjB,OAAO,SAAS,UACf;;cAkHU,eACX,QAAQ,KAAK,2CAAsC,QAAA,SAAA;cAyExC,UACX,yBACA,OAAO,oBACN,SAAS;EAAc;;;cAoFb,gBAAiB,iBAAiB,aAAa;cA2B/C,OAAc,4BAAuB"}
1
+ {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,oBAAiB;AAkB/C,OAAO,KAAK,EAAE,QAAQ,EAAE,sBAAmB;AAE3C,eAAO,MAAM,IAAI,QAiChB,CAAC;AAEF,eAAO,MAAM,YAAY,GACvB,KAAK,MAAM,WA0CZ,CAAC;AAEF,KAAK,MAAM,GAAG;IAAE,UAAU,EAAE,MAAM,EAAE,CAAC;IAAC,KAAK,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC,CAAA;CAAE,CAAC;AA6C1E,kGAAkG;AAClG,eAAO,MAAM,eAAe,GAAI,MAAK,MAAM,CAAC,UAAwB,uBACd,CAAC;AAyCvD,2GAA2G;AAC3G,eAAO,MAAM,kBAAkB,GAC7B,MAAK,MAAM,CAAC,UAAwB,EACpC,QAAO;IAAE,KAAK,CAAC,EAAE,OAAO,GAAG,SAAS,CAAA;CAAkB,EACtD,SAAQ;IAAE,KAAK,CAAC,EAAE,OAAO,GAAG,SAAS,CAAA;CAAmB,YAInC,CAAC;AA0FxB,KAAK,WAAW,GACZ;IAAE,KAAK,EAAE,kBAAkB,CAAA;CAAE,GAC7B;IAAE,KAAK,EAAE,iBAAiB,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAC7D;IACE,KAAK,EAAE,gBAAgB,CAAC;IACxB,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,qEAAqE;IACrE,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IAC1B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,2GAA2G;IAC3G,MAAM,CAAC,EAAE,IAAI,CAAC;CACf,GACD;IAAE,KAAK,EAAE,iBAAiB,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GAC7D;IAAE,KAAK,EAAE,eAAe,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,GAC5C;IAAE,KAAK,EAAE,wBAAwB,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,GACvE;IAAE,KAAK,EAAE,UAAU,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GACnC;IAAE,KAAK,EAAE,WAAW,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GACpC;IAAE,KAAK,EAAE,eAAe,CAAC;IAAC,QAAQ,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC;AAKnD,eAAO,MAAM,UAAU,GACrB,QAAQ,QAAQ,CAAC,KAAK,EACtB,OAAO,QAAQ,CAAC,KAAK,KACpB,WAAW,EAqEb,CAAC;AA4CF,2LAA2L;AAC3L,eAAO,MAAM,YAAY,GACvB,QAAQ,IAAI,CAAC,cAAc,EAAE,OAAO,GAAG,WAAW,CAAC,6BAiBjD,CAAC;AAwDL,eAAO,MAAM,OAAO,GAClB,MAAM,SAAS,MAAM,EAAE,EACvB,OAAO,MAAM,CAAC,OAAO,CAAC,KACrB,QAAQ,CAAC,SAAS,GAAG;IAAE,MAAM,CAAC,EAAE,MAAM,CAAA;CAiFxC,CAAC;AAQF,+EAA+E;AAC/E,eAAO,MAAM,aAAa,GAAI,SAAS,MAAM,EAAE,KAAK,MAAM,EAAE,OAAO,MAAM,WAWxE,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,cAAc,GACzB,MAAM,MAAM,EACZ,KAAK,MAAM,EACX,MAAM,MAAM,OAAO,CAAC,MAAM,CAAC,kBAa5B,CAAC;AAkBF,eAAO,MAAM,IAAI,GAAU,MAAM,SAAS,MAAM,EAAE,uBA+LjD,CAAC"}
package/dist/cli.js CHANGED
@@ -1,22 +1,22 @@
1
1
  import { connectCheckout } from "./client.js";
2
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";
3
+ import { AGENT_HEARTBEAT_MS, OPTION_ICONS, classifyChoiceAnswer, currentPlan, isAgentPresent, isClosed, isOptionIcon, isValidModelAnswer, parseMultipleAnswer, stepProgress } from "./protocol.js";
4
4
  import { spawn } from "node:child_process";
5
- import { readFile, writeFile } from "node:fs/promises";
5
+ import { open, readFile } from "node:fs/promises";
6
6
  import { createInterface } from "node:readline/promises";
7
7
  import { resolve } from "node:path";
8
8
  //#region src/cli.ts
9
9
  const HELP = `setup-agent <url> [command]
10
10
 
11
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.
12
+ status Print the setup as JSON.
13
+ stream Follow the setup: one JSON array of events per line.
14
14
  log <text> Send a message to the user: a reply, something no question or step conveys, or one wrap-up when finished.
15
15
  ack <message-id> Acknowledge a user message.
16
16
  ask <prompt> [--placeholder <text>] [--optional] [--step <step-id>] [--wait]
17
17
  Ask the user for a line of text.
18
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.
19
+ Ask a standard question. --only restricts the options and leaves out --choices (one id locks it in); --default preselects one.
20
20
  "framework" answers "<framework>:<language>"; "llm-provider" answers JSON with provider, model and reasoningEffort; the key itself arrives through "env".
21
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
22
  ask <prompt> --choices <id,id,...> --icons <id=icon,...> [--single] [--default <id>] [--optional] [--step <step-id>] [--wait]
@@ -25,8 +25,8 @@ Commands (the url always comes first):
25
25
  --single is for options that exclude each other (one framework, one model, yes or no); the answer is then one id.
26
26
  --icons is required and names an icon for every option, from: ${OPTION_ICONS.join(", ")}.
27
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.
28
+ Propose adding a product to this setup, 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 setup, until the next one begins.
30
30
  wait <input-id> Block until the user answers or dismisses an input. A multi-select answer prints as an array.
31
31
  plan (<markdown> | --file <path>) [--wait]
32
32
  Propose the plan for the user to approve. --wait blocks until they decide.
@@ -40,17 +40,17 @@ Commands (the url always comes first):
40
40
  done [--summary <text>] [--preview <url>]
41
41
  Mark every remaining step done and propose closing; the user closes it.
42
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.
43
+ const INSTRUCTIONS = (url) => `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.
44
44
 
45
45
  First, start a persistent Monitor on
46
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}).
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 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}).
48
48
 
49
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
50
 
51
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
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:
53
+ 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:
54
54
  npx setup-agent ${url} wait start
55
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
56
 
@@ -58,16 +58,16 @@ The remaining phases are plan, then install.
58
58
 
59
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
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:
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 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:
62
62
  npx setup-agent ${url} ask --preset framework
63
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:
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 setup:
65
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
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
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
68
  Then write the plan as markdown and submit it:
69
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.
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 setup refuses steps until then.
71
71
 
72
72
  2. Install. Declare the steps from your plan up front, in order:
73
73
  npx setup-agent ${url} add-step "<title>" --detail "<one line>"
@@ -78,9 +78,9 @@ which writes ENV_VAR=<key> into that file. Use the answer's model in the chat ro
78
78
 
79
79
  When every product is installed and verified, run
80
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
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 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
82
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.
83
+ 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.
84
84
  `;
85
85
  const parseArgs = (argv) => {
86
86
  const positional = [];
@@ -193,7 +193,7 @@ const launchAgent = async (url) => {
193
193
  });
194
194
  process.exit(code);
195
195
  };
196
- const requireState = (client) => client.state ?? fail("the checkout has no state");
196
+ const requireState = (client) => client.state ?? fail("the setup has no state");
197
197
  const summary = (state) => {
198
198
  const plan = currentPlan(state);
199
199
  return {
@@ -266,7 +266,7 @@ const diffEvents = (before, after) => {
266
266
  next: STAY_CONNECTED
267
267
  });
268
268
  if (after.id !== null && after.id !== before.id) events.push({
269
- event: "checkout.created",
269
+ event: "setup.created",
270
270
  products: after.products.map((product) => product.slug)
271
271
  });
272
272
  return events;
@@ -313,7 +313,7 @@ const stream = async (client) => {
313
313
  process.on("SIGTERM", stop);
314
314
  await new Promise(() => {});
315
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. */
316
+ /** 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. */
317
317
  const waitForStart = (client) => new Promise((resolve) => {
318
318
  let previous;
319
319
  const check = () => {
@@ -446,15 +446,38 @@ const askSeed = (rest, flags) => {
446
446
  ...stepId !== void 0 && { stepId }
447
447
  };
448
448
  };
449
+ const assertEnvKey = (key) => {
450
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) throw new Error(`"${key}" is not an environment variable name`);
451
+ };
449
452
  /** Sets `key=value` in dotenv text, replacing an existing line for the key. */
450
453
  const upsertEnvLine = (content, key, value) => {
454
+ assertEnvKey(key);
451
455
  const line = `${key}=${value}`;
452
456
  const lines = content === "" ? [] : content.replace(/\n$/, "").split("\n");
453
- const index = lines.findIndex((entry) => new RegExp(`^(export\\s+)?${key}\\s*=`).test(entry));
457
+ const index = lines.findIndex((entry) => /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(entry)?.[1] === key);
454
458
  if (index === -1) lines.push(line);
455
459
  else lines[index] = line;
456
460
  return `${lines.join("\n")}\n`;
457
461
  };
462
+ /**
463
+ * Write the secret `take` returns to `file` under `key`, leaving the file
464
+ * owner-only. The file is opened before `take` runs, because taking the
465
+ * secret consumes it and an unwritable destination must fail while it is
466
+ * still deposited; it is read after, so lines written meanwhile survive.
467
+ */
468
+ const writeEnvSecret = async (file, key, take) => {
469
+ assertEnvKey(key);
470
+ const handle = await open(file, "a+", 384);
471
+ try {
472
+ await handle.chmod(384);
473
+ const value = await take();
474
+ const current = await handle.readFile("utf8");
475
+ await handle.truncate(0);
476
+ await handle.writeFile(upsertEnvLine(current, key, value));
477
+ } finally {
478
+ await handle.close();
479
+ }
480
+ };
458
481
  const answerFields = (input, answer) => ({
459
482
  answer: input.multiple && parseMultipleAnswer(answer) || answer,
460
483
  ...input.note !== void 0 && { note: input.note },
@@ -483,7 +506,7 @@ const main = async (argv) => {
483
506
  const kind = detectAgentKind();
484
507
  await commands["agent/intro"]({ ...kind !== void 0 && { kind } }).catch(() => {});
485
508
  process.stdout.write(INSTRUCTIONS(url));
486
- process.stdout.write("\nCurrent checkout:\n");
509
+ process.stdout.write("\nCurrent setup:\n");
487
510
  print(summary(requireState(client)));
488
511
  break;
489
512
  }
@@ -579,16 +602,19 @@ const main = async (argv) => {
579
602
  const inputId = rest[0] ?? fail(usage);
580
603
  const envKey = rest[1] ?? fail(usage);
581
604
  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}"`);
605
+ const state = requireState(client);
606
+ const input = state.inputs.find((candidate) => candidate.id === inputId) ?? fail(`no input "${inputId}"`);
607
+ const setupId = state.id ?? fail("the setup has not been created yet");
608
+ if (isClosed(state)) fail("the setup is not open");
583
609
  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`);
610
+ if (input.kind !== "model" || !isValidModelAnswer(input, input.answer ?? "")) fail(`input "${inputId}" is not an llm-provider answer`);
585
611
  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));
612
+ await writeEnvSecret(file, envKey, async () => {
613
+ const response = await fetch(`${url.replace(/\/$/, "")}/secret/${encodeURIComponent(inputId)}?setup=${encodeURIComponent(setupId)}`);
614
+ if (response.status === 404) fail(`the key for "${inputId}" was already taken or never deposited`);
615
+ if (!response.ok) fail(`could not fetch the key: ${response.status}`);
616
+ return response.text();
617
+ });
592
618
  print({
593
619
  ok: true,
594
620
  envKey,
@@ -618,7 +644,7 @@ const main = async (argv) => {
618
644
  print({
619
645
  ok: true,
620
646
  status: "proposed",
621
- next: "Keep the stream running and stay idle. The user closes the checkout or sends a follow-up message."
647
+ next: "Keep the stream running and stay idle. The user closes the setup or sends a follow-up message."
622
648
  });
623
649
  break;
624
650
  }
@@ -631,6 +657,6 @@ const main = async (argv) => {
631
657
  }
632
658
  };
633
659
  //#endregion
634
- export { askSeed, detectAgentKind, diffEvents, isDirectInvocation, main, upsertEnvLine, waitForStart };
660
+ export { HELP, INSTRUCTIONS, askSeed, detectAgentKind, diffEvents, isDirectInvocation, main, upsertEnvLine, waitForStart, writeEnvSecret };
635
661
 
636
662
  //# sourceMappingURL=cli.js.map