@agent-native/core 0.237.2 → 0.237.3-nightly-20261203005849
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/builder-import.d.ts +32 -0
- package/dist/cli/builder-import.js +270 -0
- package/dist/cli/builder-sign-in.d.ts +11 -0
- package/dist/cli/builder-sign-in.js +100 -0
- package/dist/cli/code-agent-runs.d.ts +7 -0
- package/dist/cli/code-agent-runs.js +41 -7
- package/dist/cli/index.js +25 -4
- package/dist/cli/skills-content/turn-into-app-skill.d.ts +1 -1
- package/dist/cli/skills-content/turn-into-app-skill.js +14 -0
- package/dist/cli/telemetry-routing.d.ts +5 -0
- package/dist/cli/telemetry-routing.js +16 -0
- package/dist/client/generation-stream/streaming-frame.d.ts +1 -0
- package/dist/client/generation-stream/streaming-frame.js +1 -1
- package/dist/client/use-chat-models.js +4 -1
- package/dist/framework-package-versions.json +7 -7
- package/dist/framework-tools.js +1 -0
- package/dist/notifications/actions/archive-notification.d.ts +7 -0
- package/dist/notifications/actions/archive-notification.js +29 -0
- package/dist/notifications/actions.js +2 -2
- package/dist/notifications/routes.d.ts +2 -2
- package/dist/onboarding/default-steps.js +9 -30
- package/dist/onboarding/types.d.ts +2 -0
- package/dist/org/handlers.js +2 -1
- package/dist/org/index.d.ts +2 -2
- package/dist/org/migrations.d.ts +1 -1
- package/dist/provider-api/actions/custom-provider-registration.d.ts +9 -9
- package/dist/provider-api/actions/provider-api.d.ts +8 -8
- package/dist/resources/handlers.d.ts +3 -3
- package/dist/secrets/routes.d.ts +2 -2
- package/dist/server/action-discovery.js +4 -0
- package/dist/server/agent-engine-api-key-route.d.ts +2 -2
- package/dist/server/builder-oauth.d.ts +12 -0
- package/dist/server/builder-oauth.js +6 -0
- package/dist/server/first-touch-route.d.ts +1 -1
- package/dist/templates/default/.agents/skills/notifications/SKILL.md +2 -0
- package/dist/templates/workspace-core/.agents/skills/turn-into-app/references/local-run-and-deploy.md +14 -0
- package/dist/triggers/actions.js +3 -0
- package/docs/content/notifications.mdx +4 -0
- package/package.json +3 -3
- package/src/templates/default/.agents/skills/notifications/SKILL.md +2 -0
- package/src/templates/workspace-core/.agents/skills/turn-into-app/references/local-run-and-deploy.md +14 -0
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { BuilderSignIn } from "./builder-sign-in.js";
|
|
2
|
+
/** Builder's own cap on an import ZIP (`PROJECT_IMPORT_MAX_BYTES`). */
|
|
3
|
+
export declare const BUILDER_IMPORT_MAX_BYTES: number;
|
|
4
|
+
type Fetch = typeof fetch;
|
|
5
|
+
export interface BuilderAuth {
|
|
6
|
+
token: string;
|
|
7
|
+
via: "sign-in" | "token";
|
|
8
|
+
}
|
|
9
|
+
export interface BuilderImportOptions {
|
|
10
|
+
dir: string;
|
|
11
|
+
name: string;
|
|
12
|
+
spaceId: string;
|
|
13
|
+
/** Start from the agent-native starter and port the app into it; Builder only offers Publish then. */
|
|
14
|
+
convert: boolean;
|
|
15
|
+
dryRun: boolean;
|
|
16
|
+
}
|
|
17
|
+
export interface BuilderImportResult {
|
|
18
|
+
projectId: string;
|
|
19
|
+
url: string;
|
|
20
|
+
}
|
|
21
|
+
export declare function parseBuilderImportArgs(args: string[], env?: NodeJS.ProcessEnv, cwd?: string): BuilderImportOptions;
|
|
22
|
+
/** The app's files, relative to `dir`, as the import ZIP holds them. */
|
|
23
|
+
export declare function listImportFiles(dir: string): string[];
|
|
24
|
+
export declare function zipImportFiles(dir: string, files: string[]): Promise<Uint8Array>;
|
|
25
|
+
/**
|
|
26
|
+
* Sends a ZIP to Builder the way its "Import project → Upload a ZIP" page
|
|
27
|
+
* does: start an upload, stream the bytes through Builder's upload proxy, then
|
|
28
|
+
* create the project from the upload.
|
|
29
|
+
*/
|
|
30
|
+
export declare function importZipToBuilder(opts: Pick<BuilderImportOptions, "name" | "spaceId" | "convert">, credential: BuilderAuth, zip: Uint8Array, fileName: string, fetchImpl?: Fetch): Promise<BuilderImportResult>;
|
|
31
|
+
export declare function runBuilderImport(args: string[], env?: NodeJS.ProcessEnv, fetchImpl?: Fetch, signIn?: () => Promise<BuilderSignIn>): Promise<BuilderImportResult | undefined>;
|
|
32
|
+
export {};
|
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { parseArgs } from "node:util";
|
|
5
|
+
import JSZip from "jszip";
|
|
6
|
+
/** Builder's own cap on an import ZIP (`PROJECT_IMPORT_MAX_BYTES`). */
|
|
7
|
+
export const BUILDER_IMPORT_MAX_BYTES = 250 * 1024 * 1024;
|
|
8
|
+
const BUILDER_API_HOST = "https://api.builder.io";
|
|
9
|
+
const TOKEN_ENV = "BUILDER_PERSONAL_ACCESS_TOKEN";
|
|
10
|
+
const SPACE_ENV = "BUILDER_SPACE_ID";
|
|
11
|
+
const REFUSAL_HINTS = [
|
|
12
|
+
[
|
|
13
|
+
"not enabled",
|
|
14
|
+
"Builder hasn't turned on project import for this account yet.",
|
|
15
|
+
],
|
|
16
|
+
[
|
|
17
|
+
"Invalid or inactive",
|
|
18
|
+
"Builder doesn't know this token, or it was revoked or has expired: make a new one under Account settings → Access.",
|
|
19
|
+
],
|
|
20
|
+
["lacks required scope", "The token needs write scope."],
|
|
21
|
+
[
|
|
22
|
+
"not authorized for this space",
|
|
23
|
+
"Allow this space on the token, or check the --space value.",
|
|
24
|
+
],
|
|
25
|
+
[
|
|
26
|
+
"does not match spaceId",
|
|
27
|
+
"The space picked on Builder's sign-in page isn't the --space one: run it again and pick that space, or leave out --space.",
|
|
28
|
+
],
|
|
29
|
+
];
|
|
30
|
+
const FALLBACK_SKIPPED_DIRS = new Set([
|
|
31
|
+
".agent-native",
|
|
32
|
+
".deploy-tmp",
|
|
33
|
+
".generated",
|
|
34
|
+
".git",
|
|
35
|
+
".netlify",
|
|
36
|
+
".output",
|
|
37
|
+
".react-router",
|
|
38
|
+
".tmp",
|
|
39
|
+
".vercel",
|
|
40
|
+
"build",
|
|
41
|
+
"data",
|
|
42
|
+
"dist",
|
|
43
|
+
"node_modules",
|
|
44
|
+
]);
|
|
45
|
+
function isSentFile(rel) {
|
|
46
|
+
const parts = rel.split("/");
|
|
47
|
+
const base = parts[parts.length - 1] ?? "";
|
|
48
|
+
if (parts.includes("node_modules") || parts.includes(".git"))
|
|
49
|
+
return false;
|
|
50
|
+
return !(base === ".env" ||
|
|
51
|
+
(base.startsWith(".env.") && base !== ".env.example"));
|
|
52
|
+
}
|
|
53
|
+
export function parseBuilderImportArgs(args, env = process.env, cwd = process.cwd()) {
|
|
54
|
+
const { values, positionals } = parseArgs({
|
|
55
|
+
args,
|
|
56
|
+
options: {
|
|
57
|
+
name: { type: "string" },
|
|
58
|
+
space: { type: "string" },
|
|
59
|
+
"as-is": { type: "boolean" },
|
|
60
|
+
"dry-run": { type: "boolean" },
|
|
61
|
+
},
|
|
62
|
+
allowPositionals: true,
|
|
63
|
+
});
|
|
64
|
+
if (positionals.length > 1)
|
|
65
|
+
throw new Error("Give one app folder");
|
|
66
|
+
const dir = path.resolve(cwd, positionals[0] ?? ".");
|
|
67
|
+
if (!fs.existsSync(path.join(dir, "package.json"))) {
|
|
68
|
+
throw new Error(`${dir} has no package.json; run this from the app's folder`);
|
|
69
|
+
}
|
|
70
|
+
const dryRun = values["dry-run"] === true;
|
|
71
|
+
const spaceId = values.space ?? env[SPACE_ENV];
|
|
72
|
+
if (!spaceId && env[TOKEN_ENV] && !dryRun) {
|
|
73
|
+
throw new Error(`With ${TOKEN_ENV} set, pass --space <space id> or set ${SPACE_ENV}: the space's Public API Key, from Builder's Account settings. Or unset ${TOKEN_ENV} to sign in to Builder and pick the space there.`);
|
|
74
|
+
}
|
|
75
|
+
return {
|
|
76
|
+
dir,
|
|
77
|
+
name: values.name ?? path.basename(dir),
|
|
78
|
+
spaceId: spaceId ?? "",
|
|
79
|
+
convert: values["as-is"] !== true,
|
|
80
|
+
dryRun,
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
/** The app's files, relative to `dir`, as the import ZIP holds them. */
|
|
84
|
+
export function listImportFiles(dir) {
|
|
85
|
+
let files;
|
|
86
|
+
try {
|
|
87
|
+
files = execFileSync("git", [
|
|
88
|
+
"ls-files",
|
|
89
|
+
"-z",
|
|
90
|
+
"--cached",
|
|
91
|
+
"--others",
|
|
92
|
+
"--exclude-standard",
|
|
93
|
+
"--",
|
|
94
|
+
".",
|
|
95
|
+
], { cwd: dir, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] })
|
|
96
|
+
.split("\0")
|
|
97
|
+
.filter(Boolean)
|
|
98
|
+
.filter((rel) => fs
|
|
99
|
+
.lstatSync(path.join(dir, rel), { throwIfNoEntry: false })
|
|
100
|
+
?.isFile() === true);
|
|
101
|
+
}
|
|
102
|
+
catch {
|
|
103
|
+
files = [];
|
|
104
|
+
const walk = (rel) => {
|
|
105
|
+
for (const entry of fs.readdirSync(path.join(dir, rel), {
|
|
106
|
+
withFileTypes: true,
|
|
107
|
+
})) {
|
|
108
|
+
const child = rel ? `${rel}/${entry.name}` : entry.name;
|
|
109
|
+
if (entry.isDirectory()) {
|
|
110
|
+
if (!FALLBACK_SKIPPED_DIRS.has(entry.name))
|
|
111
|
+
walk(child);
|
|
112
|
+
}
|
|
113
|
+
else if (entry.isFile()) {
|
|
114
|
+
files.push(child);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
walk("");
|
|
119
|
+
}
|
|
120
|
+
return files.filter(isSentFile).sort();
|
|
121
|
+
}
|
|
122
|
+
export async function zipImportFiles(dir, files) {
|
|
123
|
+
const zip = new JSZip();
|
|
124
|
+
for (const rel of files)
|
|
125
|
+
zip.file(rel, fs.readFileSync(path.join(dir, rel)));
|
|
126
|
+
return zip.generateAsync({
|
|
127
|
+
type: "uint8array",
|
|
128
|
+
compression: "DEFLATE",
|
|
129
|
+
compressionOptions: { level: 6 },
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
async function refusal(step, response, via) {
|
|
133
|
+
const text = (await response.text()).trim();
|
|
134
|
+
const said = text && response.headers.get("content-type")?.includes("json")
|
|
135
|
+
? errorText(JSON.parse(text))
|
|
136
|
+
: text.slice(0, 300);
|
|
137
|
+
let hint = "";
|
|
138
|
+
if (response.status === 401 || response.status === 403) {
|
|
139
|
+
const known = REFUSAL_HINTS.find(([text]) => said.includes(text));
|
|
140
|
+
const fallback = via === "sign-in"
|
|
141
|
+
? `Run the command again to sign in afresh, or send it with a personal access token: set ${TOKEN_ENV} and pass --space.`
|
|
142
|
+
: `Check that ${TOKEN_ENV} is a personal access token with write scope, allowed for this space.`;
|
|
143
|
+
hint = ` ${known?.[1] ?? fallback}`;
|
|
144
|
+
}
|
|
145
|
+
return new Error(`${step} failed (${response.status})${said ? `: ${said}` : ""}.${hint}`);
|
|
146
|
+
}
|
|
147
|
+
function errorText(body) {
|
|
148
|
+
if (typeof body !== "object" || body === null)
|
|
149
|
+
return "";
|
|
150
|
+
if ("message" in body && typeof body.message === "string")
|
|
151
|
+
return body.message;
|
|
152
|
+
if ("error" in body && typeof body.error === "string")
|
|
153
|
+
return body.error;
|
|
154
|
+
return "";
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Sends a ZIP to Builder the way its "Import project → Upload a ZIP" page
|
|
158
|
+
* does: start an upload, stream the bytes through Builder's upload proxy, then
|
|
159
|
+
* create the project from the upload.
|
|
160
|
+
*/
|
|
161
|
+
export async function importZipToBuilder(opts, credential, zip, fileName, fetchImpl = fetch) {
|
|
162
|
+
const api = (route) => opts.spaceId
|
|
163
|
+
? `${BUILDER_API_HOST}${route}?apiKey=${encodeURIComponent(opts.spaceId)}`
|
|
164
|
+
: `${BUILDER_API_HOST}${route}`;
|
|
165
|
+
const auth = { Authorization: `Bearer ${credential.token}` };
|
|
166
|
+
const refused = (step, response) => refusal(step, response, credential.via);
|
|
167
|
+
const start = await fetchImpl(api("/projects/imports/upload/start"), {
|
|
168
|
+
method: "POST",
|
|
169
|
+
headers: { ...auth, "Content-Type": "application/json" },
|
|
170
|
+
body: JSON.stringify({ fileName, size: zip.byteLength }),
|
|
171
|
+
});
|
|
172
|
+
if (!start.ok)
|
|
173
|
+
throw await refused("Starting the upload", start);
|
|
174
|
+
const { uploadUrl, uploadToken } = (await start.json());
|
|
175
|
+
const session = await fetchImpl(uploadUrl, {
|
|
176
|
+
method: "POST",
|
|
177
|
+
headers: {
|
|
178
|
+
"x-goog-resumable": "start",
|
|
179
|
+
"x-goog-content-length-range": `0,${zip.byteLength}`,
|
|
180
|
+
"Content-Type": "application/zip",
|
|
181
|
+
},
|
|
182
|
+
});
|
|
183
|
+
const sessionUri = session.headers.get("Location");
|
|
184
|
+
if (!session.ok || !sessionUri)
|
|
185
|
+
throw await refused("Opening the upload", session);
|
|
186
|
+
const put = await fetchImpl(sessionUri, {
|
|
187
|
+
method: "PUT",
|
|
188
|
+
headers: {
|
|
189
|
+
"Content-Range": `bytes 0-${zip.byteLength - 1}/${zip.byteLength}`,
|
|
190
|
+
},
|
|
191
|
+
body: zip,
|
|
192
|
+
});
|
|
193
|
+
if (put.status !== 200 && put.status !== 201)
|
|
194
|
+
throw await refused("Uploading the ZIP", put);
|
|
195
|
+
const created = await fetchImpl(api("/projects/create"), {
|
|
196
|
+
method: "POST",
|
|
197
|
+
headers: { ...auth, "Content-Type": "application/json" },
|
|
198
|
+
body: JSON.stringify({
|
|
199
|
+
name: opts.name,
|
|
200
|
+
source: {
|
|
201
|
+
kind: "upload",
|
|
202
|
+
uploadToken,
|
|
203
|
+
origin: "upload",
|
|
204
|
+
convertToAgentNative: opts.convert,
|
|
205
|
+
},
|
|
206
|
+
}),
|
|
207
|
+
});
|
|
208
|
+
if (!created.ok)
|
|
209
|
+
throw await refused("Creating the project", created);
|
|
210
|
+
const result = (await created.json());
|
|
211
|
+
const projectId = result.project?.id;
|
|
212
|
+
if (!projectId)
|
|
213
|
+
throw new Error("Builder created the project but returned no project id");
|
|
214
|
+
return {
|
|
215
|
+
projectId,
|
|
216
|
+
url: result.browserUrl ??
|
|
217
|
+
`https://builder.io/app/projects/${projectId}/${result.branch?.name ?? "main"}`,
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
async function signInWithBrowser() {
|
|
221
|
+
const { signInToBuilder } = await import("./builder-sign-in.js");
|
|
222
|
+
return signInToBuilder();
|
|
223
|
+
}
|
|
224
|
+
export async function runBuilderImport(args, env = process.env, fetchImpl = fetch, signIn = signInWithBrowser) {
|
|
225
|
+
const opts = parseBuilderImportArgs(args, env);
|
|
226
|
+
const files = listImportFiles(opts.dir);
|
|
227
|
+
if (files.length === 0)
|
|
228
|
+
throw new Error(`No files to send from ${opts.dir}`);
|
|
229
|
+
const zip = await zipImportFiles(opts.dir, files);
|
|
230
|
+
const mb = (zip.byteLength / 1024 / 1024).toFixed(1);
|
|
231
|
+
if (zip.byteLength > BUILDER_IMPORT_MAX_BYTES) {
|
|
232
|
+
throw new Error(`The ZIP is ${mb} MB; Builder takes up to 250 MB`);
|
|
233
|
+
}
|
|
234
|
+
if (opts.dryRun) {
|
|
235
|
+
for (const rel of files)
|
|
236
|
+
console.log(rel);
|
|
237
|
+
console.log(`\n${files.length} files, ${mb} MB zipped. Nothing was sent (--dry-run).`);
|
|
238
|
+
return undefined;
|
|
239
|
+
}
|
|
240
|
+
const token = env[TOKEN_ENV];
|
|
241
|
+
let session;
|
|
242
|
+
let credential;
|
|
243
|
+
if (token) {
|
|
244
|
+
credential = { token, via: "token" };
|
|
245
|
+
}
|
|
246
|
+
else {
|
|
247
|
+
session = await signIn();
|
|
248
|
+
credential = { token: session.token, via: "sign-in" };
|
|
249
|
+
}
|
|
250
|
+
let result;
|
|
251
|
+
try {
|
|
252
|
+
console.log(`Sending ${files.length} files (${mb} MB) to Builder...`);
|
|
253
|
+
result = await importZipToBuilder(opts, credential, zip, `${opts.name}.zip`, fetchImpl);
|
|
254
|
+
}
|
|
255
|
+
finally {
|
|
256
|
+
if (session) {
|
|
257
|
+
try {
|
|
258
|
+
await session.revoke();
|
|
259
|
+
}
|
|
260
|
+
catch (error) {
|
|
261
|
+
console.warn(`Couldn't revoke the Builder sign-in (${error instanceof Error ? error.message : String(error)}); it expires on its own.`);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
console.log(`\nBuilder project: ${result.url}`);
|
|
266
|
+
console.log(opts.convert
|
|
267
|
+
? "Builder's agent now moves the app onto its agent-native starter, which takes a few minutes and uses Builder credits. Publish is in the project once it finishes, on plans that include hosting."
|
|
268
|
+
: "Imported as-is: the app runs in Builder as it is, without Publish.");
|
|
269
|
+
return result;
|
|
270
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export interface BuilderSignIn {
|
|
2
|
+
token: string;
|
|
3
|
+
revoke: () => Promise<void>;
|
|
4
|
+
}
|
|
5
|
+
export interface BuilderSignInOptions {
|
|
6
|
+
openUrl?: (url: string) => void;
|
|
7
|
+
log?: (message: string) => void;
|
|
8
|
+
fetchImpl?: typeof fetch;
|
|
9
|
+
timeoutMs?: number;
|
|
10
|
+
}
|
|
11
|
+
export declare function signInToBuilder(options?: BuilderSignInOptions): Promise<BuilderSignIn>;
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import http from "node:http";
|
|
3
|
+
import { exchangeBuilderOAuthSignIn, startBuilderOAuthSignIn, } from "../server/builder-oauth.js";
|
|
4
|
+
import { openUrlInBrowser } from "./open-url.js";
|
|
5
|
+
const SIGN_IN_TIMEOUT_MS = 5 * 60 * 1000;
|
|
6
|
+
function page(res, status, text) {
|
|
7
|
+
res.writeHead(status, { "Content-Type": "text/plain; charset=utf-8" });
|
|
8
|
+
res.end(text);
|
|
9
|
+
}
|
|
10
|
+
function waitForCallback(server, state, timeoutMs) {
|
|
11
|
+
return new Promise((resolve, reject) => {
|
|
12
|
+
const timer = setTimeout(() => {
|
|
13
|
+
reject(new Error(`Builder's sign-in didn't come back within ${Math.round(timeoutMs / 60_000)} minutes. Run the command again to sign in.`));
|
|
14
|
+
}, timeoutMs);
|
|
15
|
+
server.once("close", () => clearTimeout(timer));
|
|
16
|
+
server.on("request", (req, res) => {
|
|
17
|
+
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
18
|
+
if (url.pathname !== "/callback") {
|
|
19
|
+
page(res, 404, "Not found.");
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
if (url.searchParams.get("state") !== state) {
|
|
23
|
+
page(res, 400, "This sign-in page is out of date. Go back to the terminal.");
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
clearTimeout(timer);
|
|
27
|
+
const error = url.searchParams.get("error");
|
|
28
|
+
const code = url.searchParams.get("code");
|
|
29
|
+
if (error || !code) {
|
|
30
|
+
page(res, 200, "Builder sign-in didn't finish. You can close this tab.");
|
|
31
|
+
const description = url.searchParams.get("error_description");
|
|
32
|
+
reject(new Error(`Builder sign-in didn't finish (${error ?? "no code returned"}${description ? `: ${description}` : ""}).`));
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
page(res, 200, "Signed in to Builder. You can close this tab and go back to the terminal.");
|
|
36
|
+
const iss = url.searchParams.get("iss");
|
|
37
|
+
resolve(iss ? { code, iss } : { code });
|
|
38
|
+
});
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
async function revokeToken(endpoint, clientId, token, hint, fetchImpl) {
|
|
42
|
+
const response = await fetchImpl(endpoint, {
|
|
43
|
+
method: "POST",
|
|
44
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
45
|
+
body: new URLSearchParams({
|
|
46
|
+
token,
|
|
47
|
+
token_type_hint: hint,
|
|
48
|
+
client_id: clientId,
|
|
49
|
+
}),
|
|
50
|
+
});
|
|
51
|
+
await response.body?.cancel();
|
|
52
|
+
if (!response.ok) {
|
|
53
|
+
throw new Error(`Builder refused to revoke the sign-in (${response.status})`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
async function revokeSignIn(credentials, fetchImpl) {
|
|
57
|
+
const metadata = credentials.discoveryState?.authorizationServerMetadata;
|
|
58
|
+
const endpoint = metadata?.revocation_endpoint;
|
|
59
|
+
if (!endpoint) {
|
|
60
|
+
throw new Error("Builder's sign-in offers no way to revoke it");
|
|
61
|
+
}
|
|
62
|
+
const clientId = credentials.clientInformation.client_id;
|
|
63
|
+
const { refresh_token: refreshToken, access_token: accessToken } = credentials.tokens;
|
|
64
|
+
if (refreshToken) {
|
|
65
|
+
await revokeToken(endpoint, clientId, refreshToken, "refresh_token", fetchImpl);
|
|
66
|
+
}
|
|
67
|
+
await revokeToken(endpoint, clientId, accessToken, "access_token", fetchImpl);
|
|
68
|
+
}
|
|
69
|
+
export async function signInToBuilder(options = {}) {
|
|
70
|
+
const log = options.log ?? console.log;
|
|
71
|
+
const state = randomBytes(16).toString("base64url");
|
|
72
|
+
const server = http.createServer();
|
|
73
|
+
await new Promise((resolve, reject) => {
|
|
74
|
+
server.once("error", reject);
|
|
75
|
+
server.listen(0, "127.0.0.1", () => resolve());
|
|
76
|
+
});
|
|
77
|
+
try {
|
|
78
|
+
const { port } = server.address();
|
|
79
|
+
const started = await startBuilderOAuthSignIn({
|
|
80
|
+
redirectUri: `http://127.0.0.1:${port}/callback`,
|
|
81
|
+
state,
|
|
82
|
+
});
|
|
83
|
+
const callback = waitForCallback(server, state, options.timeoutMs ?? SIGN_IN_TIMEOUT_MS);
|
|
84
|
+
log(`Sign in to Builder in your browser, pick the space to send the app to, and click Authorize:\n${started.authorizationUrl}\n`);
|
|
85
|
+
(options.openUrl ?? openUrlInBrowser)(started.authorizationUrl);
|
|
86
|
+
const { code, iss } = await callback;
|
|
87
|
+
const credentials = await exchangeBuilderOAuthSignIn({
|
|
88
|
+
code,
|
|
89
|
+
...(iss ? { iss } : {}),
|
|
90
|
+
pending: started.pending,
|
|
91
|
+
});
|
|
92
|
+
return {
|
|
93
|
+
token: credentials.tokens.access_token,
|
|
94
|
+
revoke: () => revokeSignIn(credentials, options.fetchImpl ?? fetch),
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
finally {
|
|
98
|
+
server.close();
|
|
99
|
+
}
|
|
100
|
+
}
|
|
@@ -90,6 +90,13 @@ export interface QueueCodeAgentFollowUpInput {
|
|
|
90
90
|
createdAt?: string;
|
|
91
91
|
attachments?: AgentPromptAttachment[];
|
|
92
92
|
}
|
|
93
|
+
export declare class CodeAgentStoreUnwritableError extends Error {
|
|
94
|
+
readonly directory: string;
|
|
95
|
+
readonly code: string;
|
|
96
|
+
readonly name = "CodeAgentStoreUnwritableError";
|
|
97
|
+
readonly envVar = "AGENT_NATIVE_CODE_AGENTS_HOME";
|
|
98
|
+
constructor(directory: string, code: string, cause: Error);
|
|
99
|
+
}
|
|
93
100
|
export declare function codeAgentStoreRoot(): string;
|
|
94
101
|
export declare function codeAgentRunsDir(): string;
|
|
95
102
|
export declare function codeAgentRunArtifactsDir(runId: string): string;
|
|
@@ -10,6 +10,37 @@ export const CODE_AGENT_PERMISSION_MODES = [
|
|
|
10
10
|
"full-auto",
|
|
11
11
|
];
|
|
12
12
|
const STORE_ENV = "AGENT_NATIVE_CODE_AGENTS_HOME";
|
|
13
|
+
const STORE_PERMISSION_CODES = new Set(["EACCES", "EPERM", "EROFS"]);
|
|
14
|
+
export class CodeAgentStoreUnwritableError extends Error {
|
|
15
|
+
directory;
|
|
16
|
+
code;
|
|
17
|
+
name = "CodeAgentStoreUnwritableError";
|
|
18
|
+
envVar = STORE_ENV;
|
|
19
|
+
constructor(directory, code, cause) {
|
|
20
|
+
super(`Cannot write Code agent run records for ${directory}: ${cause.message}. Check that the process has access to it, or set ${STORE_ENV} to a writable directory.`, { cause });
|
|
21
|
+
this.directory = directory;
|
|
22
|
+
this.code = code;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
function isStorePermissionError(error) {
|
|
26
|
+
if (!(error instanceof Error))
|
|
27
|
+
return false;
|
|
28
|
+
const { code, syscall } = error;
|
|
29
|
+
return (typeof syscall === "string" &&
|
|
30
|
+
typeof code === "string" &&
|
|
31
|
+
STORE_PERMISSION_CODES.has(code));
|
|
32
|
+
}
|
|
33
|
+
function withRunStoreDiagnostics(directory, action) {
|
|
34
|
+
try {
|
|
35
|
+
return action();
|
|
36
|
+
}
|
|
37
|
+
catch (error) {
|
|
38
|
+
if (isStorePermissionError(error)) {
|
|
39
|
+
throw new CodeAgentStoreUnwritableError(directory, error.code, error);
|
|
40
|
+
}
|
|
41
|
+
throw error;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
13
44
|
export function codeAgentStoreRoot() {
|
|
14
45
|
return path.resolve(process.env[STORE_ENV] ??
|
|
15
46
|
path.join(os.homedir(), ".agent-native", "code-agents"));
|
|
@@ -43,12 +74,12 @@ export function readCodeAgentCommandAllowlist() {
|
|
|
43
74
|
}
|
|
44
75
|
export function addCodeAgentCommandToAllowlist(command) {
|
|
45
76
|
const filePath = codeAgentCommandAllowlistPath();
|
|
46
|
-
withFileLockSync(filePath, () => {
|
|
77
|
+
withRunStoreDiagnostics(path.dirname(filePath), () => withFileLockSync(filePath, () => {
|
|
47
78
|
const current = readCodeAgentCommandAllowlist();
|
|
48
79
|
if (current.includes(command))
|
|
49
80
|
return;
|
|
50
81
|
writeJsonFileAtomically(filePath, [...current, command], { mode: 0o600 });
|
|
51
|
-
});
|
|
82
|
+
}));
|
|
52
83
|
}
|
|
53
84
|
export function isCodeAgentCommandAllowed(command) {
|
|
54
85
|
return readCodeAgentCommandAllowlist().includes(command);
|
|
@@ -88,13 +119,14 @@ export function normalizeCodeAgentPermissionMode(value) {
|
|
|
88
119
|
}
|
|
89
120
|
export function writeCodeAgentRunRecord(record) {
|
|
90
121
|
const filePath = codeAgentRunRecordPath(record.id);
|
|
91
|
-
withFileLockSync(filePath, () => writeJsonFileAtomically(filePath, record));
|
|
122
|
+
withRunStoreDiagnostics(path.dirname(filePath), () => withFileLockSync(filePath, () => writeJsonFileAtomically(filePath, record)));
|
|
92
123
|
}
|
|
93
124
|
export function getCodeAgentRunRecord(runId) {
|
|
94
125
|
return readRunFile(codeAgentRunRecordPath(runId));
|
|
95
126
|
}
|
|
96
127
|
export function updateCodeAgentRunRecord(runId, updates) {
|
|
97
|
-
|
|
128
|
+
const filePath = codeAgentRunRecordPath(runId);
|
|
129
|
+
return withRunStoreDiagnostics(path.dirname(filePath), () => updateJsonFileAtomically(filePath, readRunValue, (record) => {
|
|
98
130
|
if (!record)
|
|
99
131
|
return null;
|
|
100
132
|
const patch = typeof updates === "function" ? updates(record) : updates;
|
|
@@ -107,7 +139,7 @@ export function updateCodeAgentRunRecord(runId, updates) {
|
|
|
107
139
|
},
|
|
108
140
|
updatedAt: patch.updatedAt ?? new Date().toISOString(),
|
|
109
141
|
};
|
|
110
|
-
});
|
|
142
|
+
}));
|
|
111
143
|
}
|
|
112
144
|
export function listCodeAgentRunRecords(goalId) {
|
|
113
145
|
const dir = codeAgentRunsDir();
|
|
@@ -143,7 +175,8 @@ export function appendCodeAgentTranscriptEvent(input) {
|
|
|
143
175
|
metadata: input.metadata,
|
|
144
176
|
...(input.signal ? { signal: input.signal } : {}),
|
|
145
177
|
};
|
|
146
|
-
const
|
|
178
|
+
const transcriptPath = codeAgentRunTranscriptPath(input.runId);
|
|
179
|
+
const persisted = withRunStoreDiagnostics(path.dirname(transcriptPath), () => appendUniqueJsonLineAtomically(transcriptPath, event, readTranscriptValue));
|
|
147
180
|
touchCodeAgentRunRecord(input.runId, createdAt);
|
|
148
181
|
return persisted.value;
|
|
149
182
|
}
|
|
@@ -229,7 +262,8 @@ function readPendingFollowUps(value) {
|
|
|
229
262
|
.filter((item) => Boolean(item));
|
|
230
263
|
}
|
|
231
264
|
function touchCodeAgentRunRecord(runId, updatedAt) {
|
|
232
|
-
|
|
265
|
+
const filePath = codeAgentRunRecordPath(runId);
|
|
266
|
+
withRunStoreDiagnostics(path.dirname(filePath), () => updateJsonFileAtomically(filePath, readRunValue, (record) => record ? { ...record, updatedAt } : null));
|
|
233
267
|
}
|
|
234
268
|
function readRunFile(filePath) {
|
|
235
269
|
try {
|
package/dist/cli/index.js
CHANGED
|
@@ -15,7 +15,7 @@ import { resolveDeployPostBuildInvocation } from "./deploy-build.js";
|
|
|
15
15
|
import { cliSpawnOptions, runDevServer, WORKSPACE_DEPLOY_BUILD_ENV, } from "./process.js";
|
|
16
16
|
import { findBinUpwards, findReactRouterInvocation, } from "./react-router-command.js";
|
|
17
17
|
import { captureSentryException as captureOptionalSentryException, flushSentryTelemetry, setCliSentryVersion, } from "./sentry-telemetry.js";
|
|
18
|
-
import { shouldTrackCliRun, telemetryCommandName, } from "./telemetry-routing.js";
|
|
18
|
+
import { classifyCliImportError, shouldTrackCliRun, telemetryCommandName, } from "./telemetry-routing.js";
|
|
19
19
|
import { createCliTelemetry } from "./telemetry.js";
|
|
20
20
|
import { getTemplate } from "./templates-meta.js";
|
|
21
21
|
let _version = "unknown";
|
|
@@ -138,20 +138,24 @@ process.on("unhandledRejection", (reason) => {
|
|
|
138
138
|
});
|
|
139
139
|
function handleScaffoldImportError(err) {
|
|
140
140
|
const msg = err?.message ?? String(err);
|
|
141
|
+
const classification = classifyCliImportError(err);
|
|
141
142
|
const looksLikeCorruptCache = err?.code === "ERR_MODULE_NOT_FOUND" ||
|
|
142
143
|
err?.code === "MODULE_NOT_FOUND" ||
|
|
143
144
|
err?.code === "ENOENT" ||
|
|
144
145
|
/Cannot find module|tarball|integrity|EINTEGRITY|corrupt|truncated/i.test(msg);
|
|
145
|
-
if (
|
|
146
|
+
if (classification.kind === "run-store") {
|
|
147
|
+
console.error(`\n ${msg}\n`);
|
|
148
|
+
}
|
|
149
|
+
else if (looksLikeCorruptCache) {
|
|
146
150
|
console.error(`\n Failed to load the scaffolder. This usually means an earlier\n \`npx\` run was interrupted and left a corrupt cache.\n\n Clear the npx cache and try again:\n rm -rf ~/.npm/_npx\n npx @agent-native/core@latest create\n\n Original error: ${msg}\n`);
|
|
147
151
|
}
|
|
148
152
|
else {
|
|
149
153
|
console.error(`\n Failed to load the scaffolder: ${msg}\n`);
|
|
150
154
|
}
|
|
151
|
-
trackCli(
|
|
155
|
+
trackCli(classification.event, { error: err });
|
|
152
156
|
captureCliException(err, {
|
|
153
157
|
handled: false,
|
|
154
|
-
tags: { source:
|
|
158
|
+
tags: { source: classification.source },
|
|
155
159
|
});
|
|
156
160
|
reportToSentryAndExit(1, err);
|
|
157
161
|
}
|
|
@@ -918,6 +922,15 @@ switch (command) {
|
|
|
918
922
|
});
|
|
919
923
|
break;
|
|
920
924
|
}
|
|
925
|
+
case "builder-import": {
|
|
926
|
+
import("./builder-import.js")
|
|
927
|
+
.then((m) => m.runBuilderImport(args))
|
|
928
|
+
.catch((err) => {
|
|
929
|
+
console.error("Builder import failed:", err?.message ?? err);
|
|
930
|
+
process.exit(1);
|
|
931
|
+
});
|
|
932
|
+
break;
|
|
933
|
+
}
|
|
921
934
|
case "amplify-stream": {
|
|
922
935
|
import("./amplify-stream.js")
|
|
923
936
|
.then((m) => m.runAmplifyStream(args))
|
|
@@ -1104,6 +1117,14 @@ Usage:
|
|
|
1104
1117
|
agent-native netlify-deploy Zip workspace functions deterministically and
|
|
1105
1118
|
run 'netlify deploy', so unchanged functions
|
|
1106
1119
|
are not re-uploaded
|
|
1120
|
+
agent-native builder-import [dir]
|
|
1121
|
+
ZIP an app (git-ignored files and .env left
|
|
1122
|
+
out) and create a Builder project from it.
|
|
1123
|
+
Signs in to Builder in the browser, or uses
|
|
1124
|
+
BUILDER_PERSONAL_ACCESS_TOKEN with --space
|
|
1125
|
+
<id>. --as-is skips the port to the
|
|
1126
|
+
agent-native starter (no Publish); --dry-run
|
|
1127
|
+
lists what would be sent.
|
|
1107
1128
|
agent-native amplify-stream Build a Nitro streaming Lambda and connect it
|
|
1108
1129
|
to an AWS Amplify branch
|
|
1109
1130
|
agent-native setup-agents Create symlinks for all agent tools
|