setup-agent 0.0.9 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +31 -0
- package/dist/browser.d.ts +40 -0
- package/dist/browser.d.ts.map +1 -0
- package/dist/browser.js +91 -0
- package/dist/browser.js.map +1 -0
- package/dist/cli.d.ts +23 -39
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +77 -125
- package/dist/cli.js.map +1 -1
- package/dist/host.d.ts.map +1 -1
- package/dist/host.js +13 -0
- package/dist/host.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/needs.d.ts +62 -0
- package/dist/needs.d.ts.map +1 -0
- package/dist/needs.js +184 -0
- package/dist/needs.js.map +1 -0
- package/dist/presets.js +1 -1
- package/dist/presets.js.map +1 -1
- package/dist/protocol.d.ts +16 -0
- package/dist/protocol.d.ts.map +1 -1
- package/dist/protocol.js +8 -1
- package/dist/protocol.js.map +1 -1
- package/dist/sdk.d.ts +48 -0
- package/dist/sdk.d.ts.map +1 -0
- package/dist/sdk.js +97 -0
- package/dist/sdk.js.map +1 -0
- package/dist/stream.d.ts +93 -0
- package/dist/stream.d.ts.map +1 -0
- package/dist/stream.js +184 -0
- package/dist/stream.js.map +1 -0
- package/package.json +5 -1
- package/src/browser.test.ts +192 -0
- package/src/browser.ts +146 -0
- package/src/cli.test.ts +57 -1
- package/src/cli.ts +134 -186
- package/src/host.test.ts +25 -0
- package/src/host.ts +7 -0
- package/src/index.ts +1 -0
- package/src/needs.test.ts +180 -0
- package/src/needs.ts +273 -0
- package/src/presets.ts +1 -1
- package/src/protocol.ts +17 -0
- package/src/sdk.test.ts +111 -0
- package/src/sdk.ts +145 -0
- package/src/stream.test.ts +223 -0
- package/src/stream.ts +314 -0
package/src/browser.ts
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { needKey, pendingNeeds } from "./needs";
|
|
2
|
+
import type { SetupNeed } from "./needs";
|
|
3
|
+
import { BROWSER_HEARTBEAT_MS, BROWSER_PRESENCE_MS } from "./protocol";
|
|
4
|
+
import type { Checkout } from "./protocol";
|
|
5
|
+
|
|
6
|
+
/** Within this long of opening a tab, setup never opens another. */
|
|
7
|
+
export const BROWSER_REOPEN_GUARD_MS = 30_000;
|
|
8
|
+
/** A page silent this long after it was present counts as closed; one heartbeat gap is not enough. */
|
|
9
|
+
export const BROWSER_CLOSE_GRACE_MS = BROWSER_HEARTBEAT_MS + 1_000;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Why the agent should ask the user itself:
|
|
13
|
+
* - recently-opened: a tab was opened moments ago, or opened and never joined;
|
|
14
|
+
* - browser-closed: the user closed the setup tab (and it may not reopen yet);
|
|
15
|
+
* - no-browser: setup may not open a browser (`--no-open`).
|
|
16
|
+
*/
|
|
17
|
+
export type AskReason = "recently-opened" | "browser-closed" | "no-browser";
|
|
18
|
+
|
|
19
|
+
export type BrowserGateAction =
|
|
20
|
+
| { type: "open"; url: string; need: SetupNeed }
|
|
21
|
+
| { type: "ask"; reason: AskReason; need: SetupNeed; openedAgoMs?: number };
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Decides when setup opens the user's browser: only once the setup waits on
|
|
25
|
+
* the user, never while a joined tab is present, never twice within the
|
|
26
|
+
* guard window, and again for a later need once a joined tab went away.
|
|
27
|
+
* Presence is measured on this machine's clock from when each heartbeat
|
|
28
|
+
* arrived, so a skewed server clock does not matter.
|
|
29
|
+
*/
|
|
30
|
+
export const createBrowserGate = ({
|
|
31
|
+
url,
|
|
32
|
+
canOpen = true,
|
|
33
|
+
now = Date.now,
|
|
34
|
+
}: {
|
|
35
|
+
/** The setup page for a state; `undefined` when there is none to open. */
|
|
36
|
+
url: (state: Checkout.State) => string | undefined;
|
|
37
|
+
/** False for `--no-open`: the agent is told to ask instead. */
|
|
38
|
+
canOpen?: boolean;
|
|
39
|
+
now?: () => number;
|
|
40
|
+
}) => {
|
|
41
|
+
const handled = new Set<string>();
|
|
42
|
+
/** Needs the agent was already told to ask about. */
|
|
43
|
+
const told = new Set<string>();
|
|
44
|
+
let openedAt: number | undefined;
|
|
45
|
+
let joinedSinceOpen = false;
|
|
46
|
+
let lastBeat: number | null | undefined;
|
|
47
|
+
let beatArrivedAt: number | undefined;
|
|
48
|
+
let present = false;
|
|
49
|
+
let absentSince: number | undefined;
|
|
50
|
+
let closedReported = true;
|
|
51
|
+
let joinTimeoutReported = true;
|
|
52
|
+
|
|
53
|
+
const trackPresence = (browser: Checkout.State["browser"]) => {
|
|
54
|
+
if (browser === undefined) return;
|
|
55
|
+
const time = now();
|
|
56
|
+
if (browser.lastSeenAt !== lastBeat) {
|
|
57
|
+
// Every beat, the first one included, counts from when it arrived here.
|
|
58
|
+
beatArrivedAt = browser.lastSeenAt === null ? undefined : time;
|
|
59
|
+
lastBeat = browser.lastSeenAt;
|
|
60
|
+
}
|
|
61
|
+
if (
|
|
62
|
+
browser.connected &&
|
|
63
|
+
beatArrivedAt !== undefined &&
|
|
64
|
+
time - beatArrivedAt < BROWSER_PRESENCE_MS
|
|
65
|
+
) {
|
|
66
|
+
present = joinedSinceOpen = true;
|
|
67
|
+
absentSince = undefined;
|
|
68
|
+
closedReported = false;
|
|
69
|
+
} else if (present || absentSince !== undefined) {
|
|
70
|
+
// A page that went quiet left when its last beat expired, not when this noticed.
|
|
71
|
+
absentSince ??=
|
|
72
|
+
browser.connected && beatArrivedAt !== undefined
|
|
73
|
+
? Math.min(time, beatArrivedAt + BROWSER_PRESENCE_MS)
|
|
74
|
+
: time;
|
|
75
|
+
present = false;
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
return {
|
|
80
|
+
update: (state: Checkout.State): BrowserGateAction[] => {
|
|
81
|
+
trackPresence(state.browser);
|
|
82
|
+
const time = now();
|
|
83
|
+
const needs = pendingNeeds(state);
|
|
84
|
+
const keys = new Set(needs.map(needKey));
|
|
85
|
+
for (const key of handled) if (!keys.has(key)) handled.delete(key);
|
|
86
|
+
for (const key of told) if (!keys.has(key)) told.delete(key);
|
|
87
|
+
// Present, or gone too briefly to call it closed.
|
|
88
|
+
const looksPresent =
|
|
89
|
+
present ||
|
|
90
|
+
(absentSince !== undefined &&
|
|
91
|
+
time - absentSince < BROWSER_CLOSE_GRACE_MS);
|
|
92
|
+
const closed = !looksPresent && absentSince !== undefined;
|
|
93
|
+
const ask = (need: SetupNeed, reason: AskReason): BrowserGateAction => {
|
|
94
|
+
told.add(needKey(need));
|
|
95
|
+
return {
|
|
96
|
+
type: "ask",
|
|
97
|
+
reason,
|
|
98
|
+
need,
|
|
99
|
+
...(reason === "recently-opened" && {
|
|
100
|
+
openedAgoMs: time - openedAt!,
|
|
101
|
+
}),
|
|
102
|
+
};
|
|
103
|
+
};
|
|
104
|
+
const actions: BrowserGateAction[] = [];
|
|
105
|
+
if (closed && !closedReported) {
|
|
106
|
+
// The tab closed while the user had something to answer there.
|
|
107
|
+
closedReported = true;
|
|
108
|
+
for (const need of needs)
|
|
109
|
+
if (handled.has(needKey(need)))
|
|
110
|
+
actions.push(ask(need, "browser-closed"));
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
if (
|
|
114
|
+
!joinTimeoutReported &&
|
|
115
|
+
!joinedSinceOpen &&
|
|
116
|
+
time - openedAt! >= BROWSER_REOPEN_GUARD_MS
|
|
117
|
+
) {
|
|
118
|
+
// The opened tab never joined: it did not open, or the user left it.
|
|
119
|
+
joinTimeoutReported = true;
|
|
120
|
+
for (const need of needs)
|
|
121
|
+
if (handled.has(needKey(need)) && !told.has(needKey(need)))
|
|
122
|
+
actions.push(ask(need, "recently-opened"));
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const fresh = needs.filter((need) => !handled.has(needKey(need)));
|
|
126
|
+
for (const need of fresh) handled.add(needKey(need));
|
|
127
|
+
if (fresh.length === 0 || looksPresent) return actions;
|
|
128
|
+
const target = canOpen ? url(state) : undefined;
|
|
129
|
+
if (target === undefined)
|
|
130
|
+
return [...actions, ...fresh.map((need) => ask(need, "no-browser"))];
|
|
131
|
+
if (
|
|
132
|
+
openedAt === undefined ||
|
|
133
|
+
(time - openedAt >= BROWSER_REOPEN_GUARD_MS && joinedSinceOpen)
|
|
134
|
+
) {
|
|
135
|
+
openedAt = time;
|
|
136
|
+
joinedSinceOpen = false;
|
|
137
|
+
joinTimeoutReported = false;
|
|
138
|
+
// One tab shows every waiting question.
|
|
139
|
+
return [...actions, { type: "open", url: target, need: fresh[0]! }];
|
|
140
|
+
}
|
|
141
|
+
const reason =
|
|
142
|
+
closed && joinedSinceOpen ? "browser-closed" : "recently-opened";
|
|
143
|
+
return [...actions, ...fresh.map((need) => ask(need, reason))];
|
|
144
|
+
},
|
|
145
|
+
};
|
|
146
|
+
};
|
package/src/cli.test.ts
CHANGED
|
@@ -604,7 +604,7 @@ describe("begin planning", () => {
|
|
|
604
604
|
describe("agent instructions", () => {
|
|
605
605
|
it("goes straight to planning for a setup the agent started", () => {
|
|
606
606
|
const browserUrl =
|
|
607
|
-
"https://
|
|
607
|
+
"https://setup.assistant-ui.com/#link=abc12345&setup=def67890";
|
|
608
608
|
const started = agentInstructions("https://setup.test/abc12345", {
|
|
609
609
|
startedByAgent: { browserUrl },
|
|
610
610
|
});
|
|
@@ -1221,3 +1221,59 @@ describe("model key handoff", () => {
|
|
|
1221
1221
|
},
|
|
1222
1222
|
);
|
|
1223
1223
|
});
|
|
1224
|
+
|
|
1225
|
+
describe("answer", () => {
|
|
1226
|
+
it("answers an input for the user from the agent's side", async () => {
|
|
1227
|
+
const state: Checkout.State = {
|
|
1228
|
+
...initialCheckoutState(),
|
|
1229
|
+
id: "setup-a",
|
|
1230
|
+
createdAt: 1,
|
|
1231
|
+
status: "planning",
|
|
1232
|
+
inputs: [
|
|
1233
|
+
{
|
|
1234
|
+
id: "q1",
|
|
1235
|
+
phase: "planning",
|
|
1236
|
+
kind: "text",
|
|
1237
|
+
prompt: "Where?",
|
|
1238
|
+
optional: false,
|
|
1239
|
+
status: "open",
|
|
1240
|
+
createdAt: 2,
|
|
1241
|
+
},
|
|
1242
|
+
],
|
|
1243
|
+
};
|
|
1244
|
+
const answer = vi.fn(async () => {});
|
|
1245
|
+
connectCheckoutMock.mockResolvedValue({
|
|
1246
|
+
state,
|
|
1247
|
+
commands: { "checkout/answer": answer },
|
|
1248
|
+
dispose: vi.fn(),
|
|
1249
|
+
} as unknown as Awaited<ReturnType<typeof connectCheckout>>);
|
|
1250
|
+
const stdout = vi.spyOn(process.stdout, "write").mockReturnValue(true);
|
|
1251
|
+
onTestFinished(() => {
|
|
1252
|
+
stdout.mockRestore();
|
|
1253
|
+
connectCheckoutMock.mockReset();
|
|
1254
|
+
});
|
|
1255
|
+
await main([
|
|
1256
|
+
"https://checkout.test/session",
|
|
1257
|
+
"answer",
|
|
1258
|
+
"q1",
|
|
1259
|
+
"apps/web",
|
|
1260
|
+
"--note",
|
|
1261
|
+
"said in chat",
|
|
1262
|
+
]);
|
|
1263
|
+
expect(answer).toHaveBeenCalledWith({
|
|
1264
|
+
inputId: "q1",
|
|
1265
|
+
answer: "apps/web",
|
|
1266
|
+
note: "said in chat",
|
|
1267
|
+
});
|
|
1268
|
+
expect(stdout).toHaveBeenCalledWith(
|
|
1269
|
+
`${JSON.stringify({ ok: true, id: "q1", status: "answered" })}\n`,
|
|
1270
|
+
);
|
|
1271
|
+
});
|
|
1272
|
+
});
|
|
1273
|
+
|
|
1274
|
+
describe("help", () => {
|
|
1275
|
+
it("documents answer in the help", () => {
|
|
1276
|
+
expect(HELP).toContain("answer <input-id> <answer>");
|
|
1277
|
+
expect(HELP).toContain("--setup-app-url");
|
|
1278
|
+
});
|
|
1279
|
+
});
|
package/src/cli.ts
CHANGED
|
@@ -23,9 +23,7 @@ import { homedir, tmpdir, userInfo } from "node:os";
|
|
|
23
23
|
import { createInterface } from "node:readline/promises";
|
|
24
24
|
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
25
25
|
import {
|
|
26
|
-
AGENT_HEARTBEAT_MS,
|
|
27
26
|
OPTION_ICONS,
|
|
28
|
-
classifyChoiceAnswer,
|
|
29
27
|
currentPlan,
|
|
30
28
|
isAgentPresent,
|
|
31
29
|
isClosed,
|
|
@@ -33,16 +31,25 @@ import {
|
|
|
33
31
|
isOptionIcon,
|
|
34
32
|
isValidModelAnswer,
|
|
35
33
|
parseEntryPointOptions,
|
|
36
|
-
parseMultipleAnswer,
|
|
37
34
|
stepProgress,
|
|
38
35
|
} from "./protocol";
|
|
39
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";
|
|
40
43
|
|
|
41
44
|
export const HELP = `setup-agent <url> [command]
|
|
42
45
|
|
|
43
46
|
Commands (the url always comes first):
|
|
44
47
|
status Print the setup as JSON.
|
|
45
|
-
stream
|
|
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.
|
|
46
53
|
log <text> Send a message to the user: a reply, something no question or step conveys, or one wrap-up when finished.
|
|
47
54
|
ack <message-id> Acknowledge a user message.
|
|
48
55
|
ask <prompt> [--placeholder <text>] [--optional] [--step <step-id>] [--wait]
|
|
@@ -113,85 +120,107 @@ export const parseSetupUrl = (value: string): string => {
|
|
|
113
120
|
return href;
|
|
114
121
|
};
|
|
115
122
|
|
|
116
|
-
/** `value` as one shell word, quoted only when it holds more than plain URL characters. */
|
|
117
|
-
const shellWord = (value: string) =>
|
|
118
|
-
/^[A-Za-z0-9._~%/:@=+,-]+$/.test(value)
|
|
119
|
-
? value
|
|
120
|
-
: `'${value.replaceAll("'", `'\\''`)}'`;
|
|
121
|
-
|
|
122
123
|
export type AgentInstructionsOptions = {
|
|
124
|
+
/** How the agent invokes the setup commands, before the URL; `npx setup-agent` by default. */
|
|
125
|
+
command?: string;
|
|
123
126
|
/**
|
|
124
127
|
* The agent started this setup with `assistant-ui setup`, which already
|
|
125
|
-
* began planning
|
|
126
|
-
* no Begin plan click to wait for.
|
|
128
|
+
* began planning; there is no Begin plan click to wait for.
|
|
127
129
|
*/
|
|
128
130
|
startedByAgent?: {
|
|
129
131
|
browserUrl: string;
|
|
130
132
|
/** False when the browser was not opened for the user; the agent then hands them the link. */
|
|
131
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;
|
|
132
139
|
};
|
|
133
140
|
};
|
|
134
141
|
|
|
135
|
-
const
|
|
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})`;
|
|
143
|
+
|
|
144
|
+
const beginPlanHandoff = (cmd: string, url: string) =>
|
|
136
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:
|
|
137
|
-
|
|
146
|
+
${cmd} ${url} wait start
|
|
138
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.`;
|
|
139
148
|
|
|
140
149
|
const agentStartedHandoff = ({
|
|
141
150
|
browserUrl,
|
|
142
151
|
opened = true,
|
|
152
|
+
streaming = false,
|
|
143
153
|
}: NonNullable<AgentInstructionsOptions["startedByAgent"]>) =>
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
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}.`;
|
|
149
178
|
|
|
150
179
|
export const agentInstructions = (
|
|
151
180
|
setupUrl: string,
|
|
152
181
|
options: AgentInstructionsOptions = {},
|
|
153
182
|
) => {
|
|
154
183
|
const url = shellWord(setupUrl);
|
|
184
|
+
const cmd = options.command ?? DEFAULT_COMMAND;
|
|
155
185
|
const started = options.startedByAgent;
|
|
156
|
-
|
|
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.
|
|
157
188
|
|
|
158
|
-
|
|
159
|
-
npx setup-agent ${url} stream
|
|
160
|
-
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)}
|
|
161
190
|
|
|
162
|
-
The user can message you at any time, including while a question is waiting. Read "message.created" events, acknowledge each with "
|
|
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.
|
|
163
192
|
|
|
164
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.
|
|
165
194
|
|
|
166
|
-
${started ? agentStartedHandoff(started) : beginPlanHandoff(url)}
|
|
195
|
+
${started ? agentStartedHandoff(started) : beginPlanHandoff(cmd, url)}
|
|
167
196
|
|
|
168
197
|
The remaining phases are plan, then install.
|
|
169
198
|
|
|
170
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:
|
|
171
|
-
|
|
200
|
+
${cmd} ${url} ask "Which project should I install into?" --placeholder "An absolute path to the app" --wait
|
|
172
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:
|
|
173
|
-
|
|
174
|
-
|
|
202
|
+
${cmd} ${url} ask --preset framework
|
|
203
|
+
${cmd} ${url} ask --preset llm-provider
|
|
175
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.
|
|
176
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:
|
|
177
|
-
|
|
206
|
+
${cmd} ${url} ask "Where should users access the assistant?" --entry-points '<JSON array>' --wait
|
|
178
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.
|
|
179
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.
|
|
180
209
|
Then write the plan as markdown and submit it:
|
|
181
|
-
|
|
210
|
+
${cmd} ${url} plan --file <path> --wait
|
|
182
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.
|
|
183
212
|
|
|
184
213
|
2. Install. Declare the steps from your plan up front, in order:
|
|
185
|
-
|
|
214
|
+
${cmd} ${url} add-step "<title>" --detail "<one line>"
|
|
186
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.
|
|
187
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
|
|
188
|
-
|
|
189
|
-
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.
|
|
190
219
|
|
|
191
220
|
When every product is installed and verified, run
|
|
192
|
-
|
|
221
|
+
${cmd} ${url} done --summary "<one or two lines on what you installed and how to try it>" --preview http://localhost:<port>
|
|
193
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
|
|
194
|
-
|
|
223
|
+
${cmd} ${url} wait start
|
|
195
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.
|
|
196
225
|
`;
|
|
197
226
|
};
|
|
@@ -331,145 +360,6 @@ const STEP_STATUSES: readonly Checkout.StepStatus[] = [
|
|
|
331
360
|
"blocked",
|
|
332
361
|
];
|
|
333
362
|
|
|
334
|
-
type StreamEvent =
|
|
335
|
-
| { event: "planning.started" }
|
|
336
|
-
| { event: "message.created"; messageId: string; text: string }
|
|
337
|
-
| {
|
|
338
|
-
event: "input.answered";
|
|
339
|
-
inputId: string;
|
|
340
|
-
prompt: string;
|
|
341
|
-
/** The entries of a multiple choice answer, else the answer text. */
|
|
342
|
-
answer: string | string[];
|
|
343
|
-
note?: string;
|
|
344
|
-
/** True when a choice answer is, or a multiple one contains, the user's own text rather than an option. */
|
|
345
|
-
custom?: true;
|
|
346
|
-
}
|
|
347
|
-
| { event: "input.dismissed"; inputId: string; prompt: string }
|
|
348
|
-
| { event: "plan.approved"; revision: number }
|
|
349
|
-
| { event: "plan.changes-requested"; revision: number; feedback: string }
|
|
350
|
-
| { event: "finished"; next: string }
|
|
351
|
-
| { event: "cancelled"; next: string }
|
|
352
|
-
| { event: "setup.created"; products: string[] };
|
|
353
|
-
|
|
354
|
-
const STAY_CONNECTED =
|
|
355
|
-
"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.";
|
|
356
|
-
|
|
357
|
-
export const diffEvents = (
|
|
358
|
-
before: Checkout.State,
|
|
359
|
-
after: Checkout.State,
|
|
360
|
-
): StreamEvent[] => {
|
|
361
|
-
const events: StreamEvent[] = [];
|
|
362
|
-
if (before.status === "waiting" && after.status === "planning") {
|
|
363
|
-
events.push({ event: "planning.started" });
|
|
364
|
-
}
|
|
365
|
-
for (const entry of after.log) {
|
|
366
|
-
if (
|
|
367
|
-
entry.role === "user" &&
|
|
368
|
-
entry.acknowledgedAt === undefined &&
|
|
369
|
-
!before.log.some((previous) => previous.id === entry.id)
|
|
370
|
-
) {
|
|
371
|
-
events.push({
|
|
372
|
-
event: "message.created",
|
|
373
|
-
messageId: entry.id,
|
|
374
|
-
text: entry.text,
|
|
375
|
-
});
|
|
376
|
-
}
|
|
377
|
-
}
|
|
378
|
-
for (const input of after.inputs) {
|
|
379
|
-
const previous = before.inputs.find(
|
|
380
|
-
(candidate) => candidate.id === input.id,
|
|
381
|
-
);
|
|
382
|
-
if (previous?.status === input.status) continue;
|
|
383
|
-
if (input.status === "answered") {
|
|
384
|
-
const answer = input.answer ?? "";
|
|
385
|
-
events.push({
|
|
386
|
-
event: "input.answered",
|
|
387
|
-
inputId: input.id,
|
|
388
|
-
prompt: input.prompt,
|
|
389
|
-
...answerFields(input, answer),
|
|
390
|
-
});
|
|
391
|
-
} else if (input.status === "dismissed" && after.status !== "cancelled") {
|
|
392
|
-
events.push({
|
|
393
|
-
event: "input.dismissed",
|
|
394
|
-
inputId: input.id,
|
|
395
|
-
prompt: input.prompt,
|
|
396
|
-
});
|
|
397
|
-
}
|
|
398
|
-
}
|
|
399
|
-
for (const plan of after.plans) {
|
|
400
|
-
const previous = before.plans.find(
|
|
401
|
-
(candidate) => candidate.revision === plan.revision,
|
|
402
|
-
);
|
|
403
|
-
if (previous?.status === plan.status || plan.status === "proposed") {
|
|
404
|
-
continue;
|
|
405
|
-
}
|
|
406
|
-
if (plan.status === "approved") {
|
|
407
|
-
events.push({ event: "plan.approved", revision: plan.revision });
|
|
408
|
-
} else {
|
|
409
|
-
events.push({
|
|
410
|
-
event: "plan.changes-requested",
|
|
411
|
-
revision: plan.revision,
|
|
412
|
-
feedback: plan.feedback ?? "",
|
|
413
|
-
});
|
|
414
|
-
}
|
|
415
|
-
}
|
|
416
|
-
if (before.status !== "done" && after.status === "done") {
|
|
417
|
-
events.push({ event: "finished", next: STAY_CONNECTED });
|
|
418
|
-
}
|
|
419
|
-
if (before.status !== "cancelled" && after.status === "cancelled") {
|
|
420
|
-
events.push({ event: "cancelled", next: STAY_CONNECTED });
|
|
421
|
-
}
|
|
422
|
-
if (after.id !== null && after.id !== before.id) {
|
|
423
|
-
events.push({
|
|
424
|
-
event: "setup.created",
|
|
425
|
-
products: after.products.map((product) => product.slug),
|
|
426
|
-
});
|
|
427
|
-
}
|
|
428
|
-
return events;
|
|
429
|
-
};
|
|
430
|
-
|
|
431
|
-
const stream = async (client: CheckoutClient) => {
|
|
432
|
-
let previous = requireState(client);
|
|
433
|
-
let pending: StreamEvent[] = diffEvents({ ...previous, log: [] }, previous);
|
|
434
|
-
let timer: ReturnType<typeof setTimeout> | null = null;
|
|
435
|
-
const flush = () => {
|
|
436
|
-
timer = null;
|
|
437
|
-
if (pending.length === 0) return;
|
|
438
|
-
print(pending);
|
|
439
|
-
pending = [];
|
|
440
|
-
};
|
|
441
|
-
client.subscribe(() => {
|
|
442
|
-
const next = client.state;
|
|
443
|
-
if (next === undefined) return;
|
|
444
|
-
pending.push(...diffEvents(previous, next));
|
|
445
|
-
previous = next;
|
|
446
|
-
if (pending.length > 0 && timer === null) timer = setTimeout(flush, 200);
|
|
447
|
-
});
|
|
448
|
-
flush();
|
|
449
|
-
const kind = detectAgentKind();
|
|
450
|
-
await client.commands["agent/hello"]({
|
|
451
|
-
cwd: process.cwd(),
|
|
452
|
-
...(kind !== undefined && { kind }),
|
|
453
|
-
});
|
|
454
|
-
const heartbeat = setInterval(() => {
|
|
455
|
-
void client.commands["agent/heartbeat"]().catch(() => {});
|
|
456
|
-
}, AGENT_HEARTBEAT_MS);
|
|
457
|
-
const stop = () => {
|
|
458
|
-
clearInterval(heartbeat);
|
|
459
|
-
flush();
|
|
460
|
-
void client.commands["agent/bye"]()
|
|
461
|
-
.catch(() => {})
|
|
462
|
-
.finally(() => {
|
|
463
|
-
client.dispose();
|
|
464
|
-
process.exit(0);
|
|
465
|
-
});
|
|
466
|
-
};
|
|
467
|
-
process.on("SIGHUP", stop);
|
|
468
|
-
process.on("SIGINT", stop);
|
|
469
|
-
process.on("SIGTERM", stop);
|
|
470
|
-
await new Promise(() => {});
|
|
471
|
-
};
|
|
472
|
-
|
|
473
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. */
|
|
474
364
|
export const waitForStart = (
|
|
475
365
|
client: Pick<CheckoutClient, "state" | "subscribe">,
|
|
@@ -876,15 +766,6 @@ const readRedeemKey = async (hash: string) => {
|
|
|
876
766
|
return undefined;
|
|
877
767
|
};
|
|
878
768
|
|
|
879
|
-
const answerFields = (input: Checkout.Input, answer: string) => ({
|
|
880
|
-
answer: (input.multiple && parseMultipleAnswer(answer)) || answer,
|
|
881
|
-
...(input.note !== undefined && { note: input.note }),
|
|
882
|
-
...(input.kind === "choice" &&
|
|
883
|
-
classifyChoiceAnswer(input, answer) === "custom" && {
|
|
884
|
-
custom: true as const,
|
|
885
|
-
}),
|
|
886
|
-
});
|
|
887
|
-
|
|
888
769
|
const answered = (input: Checkout.Input) => ({
|
|
889
770
|
ok: true,
|
|
890
771
|
inputId: input.id,
|
|
@@ -892,7 +773,55 @@ const answered = (input: Checkout.Input) => ({
|
|
|
892
773
|
...(input.answer !== undefined && answerFields(input, input.answer)),
|
|
893
774
|
});
|
|
894
775
|
|
|
895
|
-
export
|
|
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
|
+
) => {
|
|
896
825
|
const { positional, flags } = parseArgs(argv);
|
|
897
826
|
const [first, command = "intro", ...rest] = positional;
|
|
898
827
|
if (flags.has("help") || flags.has("h") || first === undefined) {
|
|
@@ -919,7 +848,11 @@ export const main = async (argv: readonly string[]) => {
|
|
|
919
848
|
await commands["agent/intro"]({
|
|
920
849
|
...(kind !== undefined && { kind }),
|
|
921
850
|
}).catch(() => {});
|
|
922
|
-
process.stdout.write(
|
|
851
|
+
process.stdout.write(
|
|
852
|
+
agentInstructions(url, {
|
|
853
|
+
...(options.command !== undefined && { command: options.command }),
|
|
854
|
+
}),
|
|
855
|
+
);
|
|
923
856
|
process.stdout.write("\nCurrent setup:\n");
|
|
924
857
|
print(summary(requireState(client)));
|
|
925
858
|
break;
|
|
@@ -929,7 +862,22 @@ export const main = async (argv: readonly string[]) => {
|
|
|
929
862
|
break;
|
|
930
863
|
}
|
|
931
864
|
case "stream": {
|
|
932
|
-
await
|
|
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
|
+
);
|
|
933
881
|
break;
|
|
934
882
|
}
|
|
935
883
|
case "step": {
|