@standardagents/cli 0.45.2 → 0.45.3

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/index.js CHANGED
@@ -1,65 +1,64 @@
1
1
  #!/usr/bin/env node
2
2
  import { Command, Option } from 'commander';
3
- import path8 from 'path';
4
- import fs5 from 'fs';
3
+ import path9 from 'path';
4
+ import fs8 from 'fs';
5
5
  import { fileURLToPath, pathToFileURL } from 'url';
6
- import crypto from 'crypto';
6
+ import crypto2 from 'crypto';
7
7
  import os3 from 'os';
8
8
  import net from 'net';
9
- import readline from 'readline';
10
9
  import childProcess, { spawn, execFileSync, spawnSync } from 'child_process';
11
- import { FIRST_PARTY_PROVIDER_PACKAGES, renderPnpmWorkspaceYaml, AGENT_DEFINITIONS_AGENTS_MD, PROMPTS_AGENTS_MD, HANDLERS_AGENTS_MD, MODELS_AGENTS_MD, TOOLS_AGENTS_MD, HOOKS_AGENTS_MD, API_AGENTS_MD, renderAgentBuilderSupportFiles, ROOT_AGENTS_MD } from '@standardagents/agentbuilder-template';
10
+ import { FIRST_PARTY_PROVIDER_PACKAGES, renderPnpmWorkspaceYaml, AGENT_DOCS, renderAgentBuilderSupportFiles } from '@standardagents/agentbuilder-template';
12
11
  import chalk from 'chalk';
13
12
  import { parse, modify, applyEdits } from 'jsonc-parser';
14
13
  import { loadFile, writeFile } from 'magicast';
15
14
  import { addVitePlugin } from 'magicast/helpers';
16
15
  import { useState, useMemo } from 'react';
17
16
  import { render, renderToString, Box, Text, useApp, useInput } from 'ink';
18
- import { TextInput } from '@inkjs/ui';
19
- import { jsx, jsxs } from 'react/jsx-runtime';
17
+ import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
18
+ import readline from 'readline';
20
19
  import { copySkill } from '@standardagents/skill';
21
20
 
22
21
  function findPnpmWorkspaceRoot(startDir) {
23
22
  let currentDir = startDir;
24
23
  while (true) {
25
- if (fs5.existsSync(path8.join(currentDir, "pnpm-workspace.yaml"))) {
24
+ if (fs8.existsSync(path9.join(currentDir, "pnpm-workspace.yaml"))) {
26
25
  return currentDir;
27
26
  }
28
- const parentDir = path8.dirname(currentDir);
27
+ const parentDir = path9.dirname(currentDir);
29
28
  if (parentDir === currentDir) {
30
29
  return null;
31
30
  }
32
31
  currentDir = parentDir;
33
32
  }
34
33
  }
35
- function findStandardAgentsWorkspaceRoot(startDir = path8.dirname(fileURLToPath(import.meta.url))) {
34
+ function findStandardAgentsWorkspaceRoot(startDir = path9.dirname(fileURLToPath(import.meta.url))) {
36
35
  let currentDir = startDir;
37
36
  for (; ; ) {
38
37
  const workspaceRoot = findPnpmWorkspaceRoot(currentDir);
39
38
  if (!workspaceRoot) return null;
40
- const manifestPath = path8.join(workspaceRoot, "package.json");
39
+ const manifestPath = path9.join(workspaceRoot, "package.json");
41
40
  try {
42
- const manifest = JSON.parse(fs5.readFileSync(manifestPath, "utf8"));
41
+ const manifest = JSON.parse(fs8.readFileSync(manifestPath, "utf8"));
43
42
  if (manifest && typeof manifest === "object" && "name" in manifest && manifest.name === "standardagents") {
44
43
  return workspaceRoot;
45
44
  }
46
45
  } catch {
47
46
  }
48
- const parent = path8.dirname(workspaceRoot);
47
+ const parent = path9.dirname(workspaceRoot);
49
48
  if (parent === workspaceRoot) return null;
50
49
  currentDir = parent;
51
50
  }
52
51
  }
53
52
  function resolveStandardAgentsWorkspaceRoot(startDirs = [
54
- path8.dirname(fileURLToPath(import.meta.url)),
53
+ path9.dirname(fileURLToPath(import.meta.url)),
55
54
  process.cwd()
56
55
  ]) {
57
56
  const explicitRoot = process.env.STANDARDAGENTS_WORKSPACE_ROOT?.trim();
58
57
  if (explicitRoot) {
59
- const workspaceRoot = findStandardAgentsWorkspaceRoot(path8.resolve(explicitRoot));
58
+ const workspaceRoot = findStandardAgentsWorkspaceRoot(path9.resolve(explicitRoot));
60
59
  if (workspaceRoot) return workspaceRoot;
61
60
  throw new Error(
62
- `STANDARDAGENTS_WORKSPACE_ROOT=${path8.resolve(explicitRoot)} is not a Standard Agents workspace root`
61
+ `STANDARDAGENTS_WORKSPACE_ROOT=${path9.resolve(explicitRoot)} is not a Standard Agents workspace root`
63
62
  );
64
63
  }
65
64
  for (const startDir of startDirs) {
@@ -69,14 +68,14 @@ function resolveStandardAgentsWorkspaceRoot(startDirs = [
69
68
  return null;
70
69
  }
71
70
  function workspacePackageDir(workspaceRoot, packageName) {
72
- return path8.join(workspaceRoot, "packages", packageName.replace("@standardagents/", ""));
71
+ return path9.join(workspaceRoot, "packages", packageName.replace("@standardagents/", ""));
73
72
  }
74
73
  function validateWorkspacePackageDir(packageName, packageDir) {
75
- const dependencyPackageJsonPath = path8.join(packageDir, "package.json");
76
- if (!fs5.existsSync(dependencyPackageJsonPath)) {
74
+ const dependencyPackageJsonPath = path9.join(packageDir, "package.json");
75
+ if (!fs8.existsSync(dependencyPackageJsonPath)) {
77
76
  throw new Error(`Could not find workspace package for ${packageName} at ${packageDir}`);
78
77
  }
79
- const manifest = JSON.parse(fs5.readFileSync(dependencyPackageJsonPath, "utf8"));
78
+ const manifest = JSON.parse(fs8.readFileSync(dependencyPackageJsonPath, "utf8"));
80
79
  const name = manifest && typeof manifest === "object" && "name" in manifest ? manifest.name : void 0;
81
80
  if (name !== packageName) {
82
81
  throw new Error(`Expected ${packageDir} to contain ${packageName}, found ${String(name ?? "unknown package")}`);
@@ -102,6 +101,149 @@ function packageManagerEnv(base = process.env) {
102
101
  }
103
102
  return env;
104
103
  }
104
+ function writePrivateFileSync(filePath, content) {
105
+ const descriptor = fs8.openSync(filePath, "w", 384);
106
+ try {
107
+ fs8.fchmodSync(descriptor, 384);
108
+ fs8.writeFileSync(descriptor, content, "utf8");
109
+ } finally {
110
+ fs8.closeSync(descriptor);
111
+ }
112
+ }
113
+
114
+ // src/utils/dev-vars.ts
115
+ var DEV_VARS_FILENAME = ".dev.vars";
116
+ var ASSIGNMENT = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;
117
+ function effectiveValue(raw) {
118
+ let value = (raw ?? "").trim();
119
+ const quote = value[0];
120
+ const quoted = value.length >= 2 && (quote === '"' || quote === "'" || quote === "`") && value.endsWith(quote);
121
+ if (quoted) value = value.slice(1, -1);
122
+ if (quoted && quote === '"') value = value.replace(/\\n/g, "\n").replace(/\\r/g, "\r");
123
+ return value;
124
+ }
125
+ function assignmentSpan(match) {
126
+ const text = match[0];
127
+ const offset = match.index ?? 0;
128
+ const leading = text.length - text.trimStart().length;
129
+ const afterKey = text.indexOf(match[1], leading) + match[1].length;
130
+ const valueEnd = match[2] === void 0 ? afterKey + (/^\s*[=:]/.exec(text.slice(afterKey))?.[0].length ?? 0) : text.indexOf(match[2], afterKey) + match[2].length;
131
+ const lineEnd = text.indexOf("\n", valueEnd);
132
+ const end = text.slice(0, lineEnd === -1 ? text.length : lineEnd).trimEnd().length;
133
+ return { start: offset + leading, end: offset + end };
134
+ }
135
+ function assignments(content) {
136
+ const found = [];
137
+ for (const match of content.matchAll(ASSIGNMENT)) {
138
+ found.push({
139
+ key: match[1],
140
+ value: effectiveValue(match[2]),
141
+ ...assignmentSpan(match)
142
+ });
143
+ }
144
+ return found;
145
+ }
146
+ function readDevVar(content, key) {
147
+ let value;
148
+ for (const assignment of assignments(content)) {
149
+ if (assignment.key === key) value = assignment.value;
150
+ }
151
+ return value;
152
+ }
153
+ function removeDevVars(content, keys) {
154
+ let result = "";
155
+ let cursor = 0;
156
+ for (const assignment of assignments(content)) {
157
+ if (!keys.includes(assignment.key)) continue;
158
+ result += content.slice(cursor, assignment.start);
159
+ const terminator = /^\r?\n/.exec(content.slice(assignment.end));
160
+ cursor = assignment.end + (terminator ? terminator[0].length : 0);
161
+ }
162
+ return result + content.slice(cursor);
163
+ }
164
+ function serialize(value) {
165
+ if (!/[\s#'"`]/.test(value)) return value;
166
+ if (value.endsWith("\\")) return null;
167
+ if (!value.includes("'")) return `'${value}'`;
168
+ if (!value.includes("`")) return `\`${value}\``;
169
+ if (!value.includes('"') && !/\\[nr]/.test(value)) return `"${value}"`;
170
+ return null;
171
+ }
172
+ function isDevVarValueRepresentable(value) {
173
+ return serialize(value) !== null;
174
+ }
175
+ function setDevVar(content, key, value) {
176
+ const rest = removeDevVars(content, [key]);
177
+ const serialized = serialize(value);
178
+ if (serialized === null) {
179
+ throw new Error(`The value for ${key} cannot be written to .dev.vars without changing it.`);
180
+ }
181
+ const separator = rest.length === 0 || rest.endsWith("\n") ? "" : "\n";
182
+ return `${rest}${separator}${key}=${serialized}
183
+ `;
184
+ }
185
+ function collapseBlankLines(content) {
186
+ const outside = (text) => text.replace(/\n{3,}/g, "\n\n");
187
+ let result = "";
188
+ let cursor = 0;
189
+ for (const assignment of assignments(content)) {
190
+ result += outside(content.slice(cursor, assignment.start)) + content.slice(assignment.start, assignment.end);
191
+ cursor = assignment.end;
192
+ }
193
+ return (result + outside(content.slice(cursor))).replace(/^\n+/, "");
194
+ }
195
+ function readDevVarsFile(projectPath) {
196
+ const filePath = path9.join(projectPath, DEV_VARS_FILENAME);
197
+ return fs8.existsSync(filePath) ? fs8.readFileSync(filePath, "utf-8") : "";
198
+ }
199
+ function writeDevVarsFile(projectPath, content) {
200
+ const filePath = path9.join(projectPath, DEV_VARS_FILENAME);
201
+ writePrivateFileSync(filePath, content === "" || content.endsWith("\n") ? content : `${content}
202
+ `);
203
+ return filePath;
204
+ }
205
+
206
+ // src/utils/project-auth-env.ts
207
+ var PROJECT_AUTH_ENV_KEYS = [
208
+ "STANDARDAGENTS_ORG_ACCOUNT_ID",
209
+ "STANDARDAGENTS_ORG_USER_ID",
210
+ "STANDARDAGENTS_ORG_SLUG",
211
+ "STANDARDAGENTS_BOOTSTRAP_SESSION_COOKIE"
212
+ ];
213
+ var ADMIN_PASSWORD_KEY = "SUPER_ADMIN_PASSWORD";
214
+ var LEGACY_DEFAULT_ADMIN_PASSWORDS = /* @__PURE__ */ new Set(["password", "admin"]);
215
+ function hasLegacyDefaultAdminPassword(devVars) {
216
+ const password = readDevVar(devVars, ADMIN_PASSWORD_KEY);
217
+ return password !== void 0 && LEGACY_DEFAULT_ADMIN_PASSWORDS.has(password);
218
+ }
219
+ function withoutLegacyDefaultAdminPassword(devVars) {
220
+ return hasLegacyDefaultAdminPassword(devVars) ? removeDevVars(devVars, [ADMIN_PASSWORD_KEY]) : devVars;
221
+ }
222
+ function hasProjectApiKey(projectPath) {
223
+ return Boolean(readDevVar(readDevVarsFile(projectPath), "STANDARD_AGENTS_API_KEY")?.trim());
224
+ }
225
+ function replaceLegacyDefaultAdminPassword(projectPath) {
226
+ const devVars = readDevVarsFile(projectPath);
227
+ if (!hasLegacyDefaultAdminPassword(devVars)) return null;
228
+ const password = crypto2.randomBytes(18).toString("base64url");
229
+ writeDevVarsFile(projectPath, setDevVar(devVars, ADMIN_PASSWORD_KEY, password));
230
+ return password;
231
+ }
232
+ function syncProjectAuthEnv(projectPath, endpoint, state) {
233
+ let devVars = readDevVarsFile(projectPath);
234
+ if (endpoint.trim()) {
235
+ devVars = setDevVar(devVars, "PLATFORM_ENDPOINT", endpoint.trim());
236
+ }
237
+ devVars = setDevVar(devVars, "STANDARDAGENTS_ORG_ACCOUNT_ID", state.account.id);
238
+ devVars = setDevVar(devVars, "STANDARDAGENTS_ORG_USER_ID", state.user.id);
239
+ if (state.account.slug) {
240
+ devVars = setDevVar(devVars, "STANDARDAGENTS_ORG_SLUG", state.account.slug);
241
+ }
242
+ if (state.session_cookie) {
243
+ devVars = setDevVar(devVars, "STANDARDAGENTS_BOOTSTRAP_SESSION_COOKIE", state.session_cookie);
244
+ }
245
+ writeDevVarsFile(projectPath, devVars);
246
+ }
105
247
  var logger = {
106
248
  success: (message) => {
107
249
  console.log(chalk.green("\u2713"), message);
@@ -119,26 +261,15 @@ var logger = {
119
261
  console.log(message);
120
262
  }
121
263
  };
122
- function writePrivateFileSync(filePath, content) {
123
- const descriptor = fs5.openSync(filePath, "w", 384);
124
- try {
125
- fs5.fchmodSync(descriptor, 384);
126
- fs5.writeFileSync(descriptor, content, "utf8");
127
- } finally {
128
- fs5.closeSync(descriptor);
129
- }
130
- }
131
-
132
- // src/utils/bootstrap-state.ts
133
- var STATE_RELATIVE_PATH = path8.join(".agents", "bootstrap-session.json");
264
+ var STATE_RELATIVE_PATH = path9.join(".agents", "bootstrap-session.json");
134
265
  function getBootstrapStatePath(projectPath) {
135
- return path8.join(projectPath, STATE_RELATIVE_PATH);
266
+ return path9.join(projectPath, STATE_RELATIVE_PATH);
136
267
  }
137
268
  function loadBootstrapState(projectPath) {
138
269
  const statePath = getBootstrapStatePath(projectPath);
139
- if (!fs5.existsSync(statePath)) return null;
270
+ if (!fs8.existsSync(statePath)) return null;
140
271
  try {
141
- const parsed = JSON.parse(fs5.readFileSync(statePath, "utf-8"));
272
+ const parsed = JSON.parse(fs8.readFileSync(statePath, "utf-8"));
142
273
  if (parsed.version !== 1) return null;
143
274
  if (!parsed.endpoint || !parsed.user?.id || !parsed.account?.id) return null;
144
275
  if (parsed.session_cookie !== void 0 && typeof parsed.session_cookie !== "string") return null;
@@ -149,13 +280,13 @@ function loadBootstrapState(projectPath) {
149
280
  }
150
281
  function persistBootstrapState(projectPath, state) {
151
282
  const statePath = getBootstrapStatePath(projectPath);
152
- fs5.mkdirSync(path8.dirname(statePath), { recursive: true });
283
+ fs8.mkdirSync(path9.dirname(statePath), { recursive: true });
153
284
  writePrivateFileSync(statePath, JSON.stringify(state, null, 2) + "\n");
154
285
  }
155
286
  function clearBootstrapState(projectPath) {
156
287
  const statePath = getBootstrapStatePath(projectPath);
157
- if (fs5.existsSync(statePath)) {
158
- fs5.unlinkSync(statePath);
288
+ if (fs8.existsSync(statePath)) {
289
+ fs8.unlinkSync(statePath);
159
290
  }
160
291
  }
161
292
  function getWebSocketCtor() {
@@ -336,13 +467,13 @@ function getScaffoldStandardAgentsVersion() {
336
467
  if (process.env.STANDARDAGENTS_WORKSPACE === "1") {
337
468
  return workspacePackageLink("@standardagents/builder");
338
469
  }
339
- return "0.45.2";
470
+ return "0.45.3";
340
471
  }
341
472
  function findViteConfig(cwd) {
342
473
  const candidates = ["vite.config.ts", "vite.config.js", "vite.config.mts", "vite.config.mjs"];
343
474
  for (const candidate of candidates) {
344
- const configPath = path8.join(cwd, candidate);
345
- if (fs5.existsSync(configPath)) {
475
+ const configPath = path9.join(cwd, candidate);
476
+ if (fs8.existsSync(configPath)) {
346
477
  return configPath;
347
478
  }
348
479
  }
@@ -360,13 +491,13 @@ function setPackageDependency(packageJsonText, section, packageName, version) {
360
491
  return applyEdits(packageJsonText, edits);
361
492
  }
362
493
  function updatePackageDependencies(cwd, versions = {}) {
363
- const packageJsonPath = path8.join(cwd, "package.json");
364
- if (!fs5.existsSync(packageJsonPath)) {
494
+ const packageJsonPath = path9.join(cwd, "package.json");
495
+ if (!fs8.existsSync(packageJsonPath)) {
365
496
  logger.warning("No package.json found. Install @standardagents/builder manually.");
366
497
  return false;
367
498
  }
368
499
  try {
369
- const text = fs5.readFileSync(packageJsonPath, "utf-8");
500
+ const text = fs8.readFileSync(packageJsonPath, "utf-8");
370
501
  const pkg = JSON.parse(text);
371
502
  const desiredBuilderVersion = versions.standardAgents ?? getScaffoldStandardAgentsVersion();
372
503
  const builderSection = dependencySectionFor(pkg, "@standardagents/builder", "dependencies");
@@ -380,7 +511,7 @@ function updatePackageDependencies(cwd, versions = {}) {
380
511
  logger.info("package.json already has current Standard Agents dependencies");
381
512
  return true;
382
513
  }
383
- fs5.writeFileSync(packageJsonPath, `${result.trimEnd()}
514
+ fs8.writeFileSync(packageJsonPath, `${result.trimEnd()}
384
515
  `, "utf-8");
385
516
  logger.success("Updated package.json with current Standard Agents dependencies");
386
517
  return true;
@@ -392,10 +523,10 @@ function updatePackageDependencies(cwd, versions = {}) {
392
523
  async function modifyViteConfig(configPath, force) {
393
524
  try {
394
525
  const mod = await loadFile(configPath);
395
- const code = fs5.readFileSync(configPath, "utf-8");
526
+ const code = fs8.readFileSync(configPath, "utf-8");
396
527
  const hasAgentBuilder = code.includes("@standardagents/builder") || code.includes("builder()") || code.includes("agentbuilder()");
397
528
  if (hasAgentBuilder && !force) {
398
- logger.info("Vite config already includes builder plugin");
529
+ logger.info("Vite config already includes the Standard Agents Builder plugin");
399
530
  return true;
400
531
  }
401
532
  if (!hasAgentBuilder || force) {
@@ -404,7 +535,7 @@ async function modifyViteConfig(configPath, force) {
404
535
  imported: "builder",
405
536
  constructor: "builder"
406
537
  });
407
- logger.success("Added builder plugin to vite.config");
538
+ logger.success("Added the Standard Agents Builder plugin to vite.config");
408
539
  }
409
540
  await writeFile(mod, configPath);
410
541
  return true;
@@ -422,44 +553,34 @@ async function modifyViteConfig(configPath, force) {
422
553
  }
423
554
  function createDirectoriesAndDocs(cwd) {
424
555
  function writeAgentsDocWithClaudeSymlink(dirPath, doc, label) {
425
- const agentsDocPath = path8.join(dirPath, "AGENTS.md");
426
- const claudeDocPath = path8.join(dirPath, "CLAUDE.md");
427
- if (!fs5.existsSync(agentsDocPath)) {
428
- fs5.writeFileSync(agentsDocPath, doc, "utf-8");
556
+ const agentsDocPath = path9.join(dirPath, "AGENTS.md");
557
+ const claudeDocPath = path9.join(dirPath, "CLAUDE.md");
558
+ if (!fs8.existsSync(agentsDocPath)) {
559
+ fs8.writeFileSync(agentsDocPath, doc, "utf-8");
429
560
  logger.success(`Created ${label}/AGENTS.md`);
430
561
  }
431
- if (!fs5.existsSync(claudeDocPath)) {
432
- fs5.symlinkSync("AGENTS.md", claudeDocPath);
562
+ if (!fs8.existsSync(claudeDocPath)) {
563
+ fs8.symlinkSync("AGENTS.md", claudeDocPath);
433
564
  logger.success(`Created ${label}/CLAUDE.md symlink`);
434
565
  }
435
566
  }
436
- writeAgentsDocWithClaudeSymlink(cwd, ROOT_AGENTS_MD, ".");
437
- const directories = [
438
- { path: "agents/agents", doc: AGENT_DEFINITIONS_AGENTS_MD },
439
- { path: "agents/prompts", doc: PROMPTS_AGENTS_MD },
440
- { path: "agents/handlers", doc: HANDLERS_AGENTS_MD },
441
- { path: "agents/models", doc: MODELS_AGENTS_MD },
442
- { path: "agents/tools", doc: TOOLS_AGENTS_MD },
443
- { path: "agents/hooks", doc: HOOKS_AGENTS_MD },
444
- { path: "agents/api", doc: API_AGENTS_MD }
445
- ];
446
- for (const dir of directories) {
447
- const dirPath = path8.join(cwd, dir.path);
448
- if (!fs5.existsSync(dirPath)) {
449
- fs5.mkdirSync(dirPath, { recursive: true });
450
- logger.success(`Created ${dir.path}`);
567
+ for (const doc of AGENT_DOCS) {
568
+ const dirPath = path9.join(cwd, doc.directory);
569
+ if (!fs8.existsSync(dirPath)) {
570
+ fs8.mkdirSync(dirPath, { recursive: true });
571
+ logger.success(`Created ${doc.directory}`);
451
572
  }
452
- writeAgentsDocWithClaudeSymlink(dirPath, dir.doc, dir.path);
573
+ writeAgentsDocWithClaudeSymlink(dirPath, doc.content, doc.directory);
453
574
  }
454
575
  }
455
576
  function updateTsConfig(cwd) {
456
- const tsconfigPath = path8.join(cwd, "tsconfig.json");
457
- if (!fs5.existsSync(tsconfigPath)) {
577
+ const tsconfigPath = path9.join(cwd, "tsconfig.json");
578
+ if (!fs8.existsSync(tsconfigPath)) {
458
579
  logger.info("No tsconfig.json found, skipping TypeScript configuration");
459
580
  return;
460
581
  }
461
582
  try {
462
- const text = fs5.readFileSync(tsconfigPath, "utf-8");
583
+ const text = fs8.readFileSync(tsconfigPath, "utf-8");
463
584
  const config = parse(text);
464
585
  let result = text;
465
586
  const types = config.compilerOptions?.types || [];
@@ -480,7 +601,7 @@ function updateTsConfig(cwd) {
480
601
  result = applyEdits(result, edits);
481
602
  }
482
603
  if (newTypes.length > 0 || newIncludes.length > 0) {
483
- fs5.writeFileSync(tsconfigPath, result, "utf-8");
604
+ fs8.writeFileSync(tsconfigPath, result, "utf-8");
484
605
  logger.success("Updated tsconfig.json with Standard Agents types");
485
606
  } else {
486
607
  logger.info("tsconfig.json already configured");
@@ -506,21 +627,21 @@ function cleanupViteDefaults(cwd) {
506
627
  ];
507
628
  const dirsToRemove = ["src", "public", "worker"];
508
629
  for (const file of filesToRemove) {
509
- const filePath = path8.join(cwd, file);
510
- if (fs5.existsSync(filePath)) {
630
+ const filePath = path9.join(cwd, file);
631
+ if (fs8.existsSync(filePath)) {
511
632
  try {
512
- fs5.unlinkSync(filePath);
633
+ fs8.unlinkSync(filePath);
513
634
  } catch {
514
635
  }
515
636
  }
516
637
  }
517
638
  for (const dir of dirsToRemove) {
518
- const dirPath = path8.join(cwd, dir);
519
- if (fs5.existsSync(dirPath)) {
639
+ const dirPath = path9.join(cwd, dir);
640
+ if (fs8.existsSync(dirPath)) {
520
641
  try {
521
- const files = fs5.readdirSync(dirPath);
642
+ const files = fs8.readdirSync(dirPath);
522
643
  if (files.length === 0) {
523
- fs5.rmdirSync(dirPath);
644
+ fs8.rmdirSync(dirPath);
524
645
  }
525
646
  } catch {
526
647
  }
@@ -536,7 +657,7 @@ async function scaffold(options = {}) {
536
657
  if (viteConfigPath) {
537
658
  await modifyViteConfig(viteConfigPath, force);
538
659
  } else {
539
- logger.warning("No vite.config found. Please create one with the agentbuilder plugin.");
660
+ logger.warning("No vite.config found. Please create one with the Standard Agents Builder plugin.");
540
661
  }
541
662
  updatePackageDependencies(cwd, { standardAgents: options.standardAgents });
542
663
  createDirectoriesAndDocs(cwd);
@@ -563,19 +684,530 @@ async function scaffold(options = {}) {
563
684
  logger.log(" \u2514\u2500\u2500 api/ # Thread API endpoints");
564
685
  logger.log("");
565
686
  }
687
+
688
+ // src/utils/interrupt.ts
689
+ var SIGNAL_EXIT_CODES = { SIGINT: 130, SIGTERM: 143 };
690
+ function createInterruptScope(source = process, exit = (code) => process.exit(code)) {
691
+ const cleanups = [];
692
+ let listening = false;
693
+ let interrupted = false;
694
+ const setListening = (next) => {
695
+ if (next === listening) return;
696
+ listening = next;
697
+ for (const signal of ["SIGINT", "SIGTERM"]) {
698
+ if (next) source.on(signal, handle);
699
+ else source.off(signal, handle);
700
+ }
701
+ };
702
+ const handle = (signal) => {
703
+ if (interrupted) return;
704
+ interrupted = true;
705
+ void (async () => {
706
+ for (let cleanup = cleanups.pop(); cleanup; cleanup = cleanups.pop()) {
707
+ try {
708
+ await cleanup();
709
+ } catch {
710
+ }
711
+ }
712
+ exit(SIGNAL_EXIT_CODES[signal] ?? 130);
713
+ interrupted = false;
714
+ if (cleanups.length === 0) setListening(false);
715
+ })();
716
+ };
717
+ return {
718
+ onInterrupt(cleanup) {
719
+ cleanups.push(cleanup);
720
+ setListening(true);
721
+ return () => {
722
+ const index = cleanups.indexOf(cleanup);
723
+ if (index >= 0) cleanups.splice(index, 1);
724
+ if (cleanups.length === 0 && !interrupted) setListening(false);
725
+ };
726
+ },
727
+ isInterrupted: () => interrupted
728
+ };
729
+ }
730
+ var interrupts = createInterruptScope();
731
+ function parkUntilExit() {
732
+ return new Promise(() => {
733
+ });
734
+ }
735
+ var POLL_MS = 50;
736
+ function isAlive(pid) {
737
+ try {
738
+ process.kill(pid, 0);
739
+ return true;
740
+ } catch (error) {
741
+ return error !== null && typeof error === "object" && "code" in error && error.code === "EPERM";
742
+ }
743
+ }
744
+ function signalAll(pids, signal) {
745
+ for (const pid of pids) {
746
+ try {
747
+ process.kill(pid, signal);
748
+ } catch {
749
+ }
750
+ }
751
+ }
752
+ function readProcfsTable() {
753
+ let entries;
754
+ try {
755
+ entries = fs8.readdirSync("/proc");
756
+ } catch {
757
+ return null;
758
+ }
759
+ const parents = /* @__PURE__ */ new Map();
760
+ for (const entry of entries) {
761
+ if (!/^\d+$/.test(entry)) continue;
762
+ try {
763
+ const stat = fs8.readFileSync(`/proc/${entry}/stat`, "utf8");
764
+ const parent = Number.parseInt(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1], 10);
765
+ if (Number.isInteger(parent)) parents.set(Number(entry), parent);
766
+ } catch {
767
+ }
768
+ }
769
+ return parents.size > 0 ? parents : null;
770
+ }
771
+ function readPsTable() {
772
+ const table = spawnSync("ps", ["-A", "-o", "pid=,ppid="], { encoding: "utf8" });
773
+ if (table.error || table.status !== 0 || typeof table.stdout !== "string") return null;
774
+ const parents = /* @__PURE__ */ new Map();
775
+ for (const line of table.stdout.split("\n")) {
776
+ const [pid, parent] = line.trim().split(/\s+/).map((value) => Number.parseInt(value, 10));
777
+ if (Number.isInteger(pid) && Number.isInteger(parent)) parents.set(pid, parent);
778
+ }
779
+ return parents;
780
+ }
781
+ function readProcessTable() {
782
+ return readProcfsTable() ?? readPsTable();
783
+ }
784
+ function canStopProcessTrees() {
785
+ return process.platform === "win32" || readProcessTable() !== null;
786
+ }
787
+ function descendantPids(rootPid) {
788
+ const parents = readProcessTable();
789
+ if (!parents) return null;
790
+ const childrenByParent = /* @__PURE__ */ new Map();
791
+ for (const [pid, parent] of parents) {
792
+ childrenByParent.set(parent, [...childrenByParent.get(parent) ?? [], pid]);
793
+ }
794
+ const found = [];
795
+ for (const queue = [rootPid]; queue.length > 0; ) {
796
+ for (const child of childrenByParent.get(queue.shift() ?? -1) ?? []) {
797
+ found.push(child);
798
+ queue.push(child);
799
+ }
800
+ }
801
+ return found;
802
+ }
803
+ async function waitUntilGone(pids, timeoutMs) {
804
+ const deadline = Date.now() + timeoutMs;
805
+ while (pids.some(isAlive)) {
806
+ if (Date.now() >= deadline) return false;
807
+ await new Promise((resolve) => setTimeout(resolve, POLL_MS));
808
+ }
809
+ return true;
810
+ }
811
+ async function terminateProcessTree(child, options = {}) {
812
+ const pid = child.pid;
813
+ if (pid === void 0) return;
814
+ if (process.platform === "win32") {
815
+ spawnSync("taskkill", ["/pid", String(pid), "/T", "/F"], { stdio: "ignore" });
816
+ await waitUntilGone([pid], options.killWaitMs ?? 2e3);
817
+ return;
818
+ }
819
+ const pids = [pid, ...descendantPids(pid) ?? []];
820
+ signalAll(pids, "SIGTERM");
821
+ if (await waitUntilGone(pids, options.graceMs ?? 5e3)) return;
822
+ signalAll(pids.filter(isAlive), "SIGKILL");
823
+ await waitUntilGone(pids, options.killWaitMs ?? 2e3);
824
+ }
825
+ var CommandExitError = class extends Error {
826
+ constructor(exitCode, details = "") {
827
+ super(`Command failed with exit code ${exitCode}${details ? `
828
+ ${details}` : ""}`);
829
+ this.exitCode = exitCode;
830
+ this.name = "CommandExitError";
831
+ }
832
+ };
833
+ var ProcessControlUnavailableError = class extends Error {
834
+ constructor() {
835
+ super(
836
+ "Cannot list running processes on this system (no /proc and no working `ps`), so setup commands could not be stopped safely if interrupted."
837
+ );
838
+ this.name = "ProcessControlUnavailableError";
839
+ }
840
+ };
841
+ var INTERRUPT_SETTLE_MS = 250;
842
+ var INTERRUPT_EXIT_CODES = /* @__PURE__ */ new Set([130, 143]);
843
+ function appendOutputTail(existing, chunk, maxLength = 8e3) {
844
+ const combined = existing + chunk;
845
+ if (combined.length <= maxLength) return combined;
846
+ return combined.slice(combined.length - maxLength);
847
+ }
848
+ function runCommand(command, args, cwd, options = {}) {
849
+ if (!canStopProcessTrees()) {
850
+ return Promise.reject(new ProcessControlUnavailableError());
851
+ }
852
+ return new Promise((resolve, reject) => {
853
+ const quiet = options.quiet ?? false;
854
+ const child = spawn(command, args, {
855
+ cwd,
856
+ stdio: quiet ? ["ignore", "pipe", "pipe"] : "inherit",
857
+ shell: false,
858
+ // npx-inherited npm_config_allow_scripts fatals npm 12 project installs
859
+ // (EALLOWSCRIPTS); approvals live in the generated package.json instead.
860
+ env: packageManagerEnv()
861
+ });
862
+ const stopOnInterrupt = interrupts.onInterrupt(() => terminateProcessTree(child));
863
+ let outputTail = "";
864
+ if (quiet) {
865
+ child.stdout?.on("data", (chunk) => {
866
+ outputTail = appendOutputTail(outputTail, chunk.toString());
867
+ });
868
+ child.stderr?.on("data", (chunk) => {
869
+ outputTail = appendOutputTail(outputTail, chunk.toString());
870
+ });
871
+ }
872
+ const settle = (finish) => {
873
+ stopOnInterrupt();
874
+ if (!interrupts.isInterrupted()) finish();
875
+ };
876
+ child.on("close", (code, signal) => {
877
+ if (code === 0) {
878
+ settle(resolve);
879
+ return;
880
+ }
881
+ const fail = () => settle(() => reject(new CommandExitError(code, outputTail.trim())));
882
+ const diedFromInterrupt = signal === "SIGINT" || signal === "SIGTERM" || code !== null && INTERRUPT_EXIT_CODES.has(code);
883
+ if (diedFromInterrupt && !interrupts.isInterrupted()) {
884
+ setTimeout(fail, INTERRUPT_SETTLE_MS);
885
+ return;
886
+ }
887
+ fail();
888
+ });
889
+ child.on("error", (error) => settle(() => reject(error)));
890
+ });
891
+ }
892
+
893
+ // src/utils/wait-indicator.ts
894
+ var SPINNER_FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
895
+ var CLEAR_LINE = "\r\x1B[2K";
896
+ var CANCEL_HINT = "Press Ctrl-C to cancel.";
897
+ function formatDuration(ms) {
898
+ const totalSeconds = Math.max(0, Math.floor(ms / 1e3));
899
+ const minutes = Math.floor(totalSeconds / 60);
900
+ const seconds = totalSeconds % 60;
901
+ return minutes > 0 ? `${minutes}m ${String(seconds).padStart(2, "0")}s` : `${seconds}s`;
902
+ }
903
+ function startWaitIndicator(options) {
904
+ const stream = options.stream ?? process.stdout;
905
+ const log = options.log ?? ((message) => console.log(message));
906
+ const startedAt = Date.now();
907
+ if (!stream.isTTY) {
908
+ stream.write(
909
+ `${options.label}. This session expires in ${formatDuration(options.expiresAt - startedAt)}. ${CANCEL_HINT}
910
+ `
911
+ );
912
+ return { note: log, stop: () => {
913
+ } };
914
+ }
915
+ let frame = 0;
916
+ let stopped = false;
917
+ const render3 = () => {
918
+ const now = Date.now();
919
+ stream.write(
920
+ `${CLEAR_LINE}${SPINNER_FRAMES[frame]} ${options.label} (${formatDuration(now - startedAt)} elapsed, expires in ${formatDuration(options.expiresAt - now)}). ${CANCEL_HINT}`
921
+ );
922
+ frame = (frame + 1) % SPINNER_FRAMES.length;
923
+ };
924
+ render3();
925
+ const timer = setInterval(render3, 1e3);
926
+ return {
927
+ note(message) {
928
+ if (stopped) {
929
+ log(message);
930
+ return;
931
+ }
932
+ stream.write(CLEAR_LINE);
933
+ log(message);
934
+ render3();
935
+ },
936
+ stop() {
937
+ if (stopped) return;
938
+ stopped = true;
939
+ clearInterval(timer);
940
+ stream.write(CLEAR_LINE);
941
+ }
942
+ };
943
+ }
944
+ var INIT_COMMAND = "npx @standardagents/cli@latest init";
945
+ var ACCOUNT_STEP_LINES = [
946
+ "Init signs you in to your Standard Agents account in the browser (or creates one).",
947
+ "The account supplies inference for your agents, so no provider keys are needed."
948
+ ];
949
+ var SESSION_EXPIRED_MESSAGE = `The sign-in session expired before the browser steps were finished.
950
+ Start a new one: ${INIT_COMMAND}`;
951
+ var SESSION_CANCELLED_MESSAGE = `Sign-in was cancelled in the browser.
952
+ Start again when you are ready: ${INIT_COMMAND}`;
953
+ function isInteractiveTerminal(stdin = process.stdin, stdout = process.stdout) {
954
+ return Boolean(stdin.isTTY && stdout.isTTY);
955
+ }
956
+ function noTerminalFailure() {
957
+ return {
958
+ cause: "init needs an interactive terminal: it signs you in through your browser and then runs the dev server.",
959
+ next: [
960
+ `Run it in a terminal: ${INIT_COMMAND}`,
961
+ `To sign in from another device or a script, print the sign-in URL and wait for it: ${INIT_COMMAND} --no-open`
962
+ ]
963
+ };
964
+ }
965
+ function gitMissingFailure() {
966
+ return {
967
+ cause: "git is not installed or is not on your PATH. Init clones your project with git.",
968
+ next: [`Install git from https://git-scm.com/downloads, then run: ${INIT_COMMAND}`]
969
+ };
970
+ }
971
+ function processControlFailure() {
972
+ return {
973
+ cause: "init cannot list running processes on this system (no /proc and no working `ps`), so it could not stop its setup commands safely if interrupted.",
974
+ next: [`Install procps (for example: apt-get install -y procps), then run: ${INIT_COMMAND}`]
975
+ };
976
+ }
977
+ function directoryExistsFailure(name) {
978
+ return {
979
+ cause: `Directory "${name}" already exists here.`,
980
+ next: [`Choose another name: ${INIT_COMMAND} <another-name>`, "Or run the same command from a different directory."]
981
+ };
982
+ }
983
+ function resolveFreeDirectoryName(cwd, name) {
984
+ if (!fs8.existsSync(path9.join(cwd, name))) return name;
985
+ for (let suffix = 2; ; suffix += 1) {
986
+ const candidate = `${name}-${suffix}`;
987
+ if (!fs8.existsSync(path9.join(cwd, candidate))) return candidate;
988
+ }
989
+ }
990
+ function commandFailureCause(label, error) {
991
+ const code = error !== null && typeof error === "object" && "code" in error ? error.code : void 0;
992
+ if (code === "ENOENT") {
993
+ return `${label.split(" ")[0]} is not installed or is not on your PATH.`;
994
+ }
995
+ const exitCode = error !== null && typeof error === "object" && "exitCode" in error ? error.exitCode : void 0;
996
+ if (typeof exitCode === "number") {
997
+ return `${label} exited with code ${exitCode}. Its output is above.`;
998
+ }
999
+ return `${label} failed: ${error instanceof Error ? error.message : String(error)}`;
1000
+ }
1001
+ function setupCommandStep(dashboardUrl) {
1002
+ const where = dashboardUrl ? `the Standard Agents dashboard (${dashboardUrl})` : "the Standard Agents dashboard";
1003
+ return `Open the project's Overview page in ${where}, copy its setup command, and run it here.`;
1004
+ }
1005
+ function finishExistingProjectSteps(projectName, dashboardUrl) {
1006
+ return [
1007
+ `Your project "${projectName}" now exists in your account, so do not run init again.`,
1008
+ setupCommandStep(dashboardUrl)
1009
+ ];
1010
+ }
1011
+ function cloneFailure(params) {
1012
+ return {
1013
+ cause: `Could not clone "${params.projectName}": ${params.cause}`,
1014
+ next: [
1015
+ `Your project "${params.projectName}" now exists in your account, so do not run init again.`,
1016
+ `Fix the problem above. ${setupCommandStep(params.dashboardUrl)}`
1017
+ ]
1018
+ };
1019
+ }
1020
+ function configureFailure(params) {
1021
+ return {
1022
+ cause: `Could not finish configuring "${params.projectName}": ${params.cause}`,
1023
+ next: [
1024
+ `Your project "${params.projectName}" now exists in your account, so do not run init again.`,
1025
+ `Remove the "${params.directory}" directory. ${setupCommandStep(params.dashboardUrl)}`
1026
+ ]
1027
+ };
1028
+ }
1029
+ function resumeSteps(directory, installCommand, devCommand) {
1030
+ return [` cd ${directory}`, ` ${installCommand}`, ` ${devCommand}`];
1031
+ }
1032
+ function installFailure(params) {
1033
+ return {
1034
+ cause: `Could not install dependencies: ${params.cause}`,
1035
+ next: [
1036
+ `Your project is cloned and configured in "${params.directory}". Fix the problem above, then run:`,
1037
+ ...resumeSteps(params.directory, params.installCommand, params.devCommand)
1038
+ ]
1039
+ };
1040
+ }
1041
+
1042
+ // src/tui/local-init-wizard.ts
1043
+ var INIT_PACKAGE_MANAGERS = ["npm", "pnpm", "yarn", "bun"];
1044
+ var ENV_FIELDS = ["openrouter", "openai", "password"];
1045
+ var TEXT_STEPS = /* @__PURE__ */ new Set(["name", ...ENV_FIELDS]);
1046
+ function createLocalInitWizard(config) {
1047
+ let target = config.initialTarget;
1048
+ let chars = [];
1049
+ let cursor = 0;
1050
+ let afterCarriageReturn = false;
1051
+ let nameError = config.initialNameError;
1052
+ let fieldError;
1053
+ let packageManagerIndex = Math.max(0, INIT_PACKAGE_MANAGERS.indexOf(config.detectedPackageManager));
1054
+ let packageManagerChosen = false;
1055
+ const env = { openrouter: "", openai: "", password: "" };
1056
+ let outcome;
1057
+ const stepsFor = (resolved) => {
1058
+ const steps = [];
1059
+ if (resolved.existing) steps.push("confirm");
1060
+ if (!resolved.existing && !config.packageManager) steps.push("packageManager");
1061
+ if (resolved.collectEnv) steps.push(...ENV_FIELDS);
1062
+ return steps;
1063
+ };
1064
+ const finish = (resolved) => {
1065
+ outcome = {
1066
+ kind: "done",
1067
+ result: {
1068
+ projectName: resolved.projectName,
1069
+ packageManager: packageManagerChosen ? INIT_PACKAGE_MANAGERS[packageManagerIndex] : void 0,
1070
+ env: resolved.collectEnv ? {
1071
+ openrouterKey: env.openrouter,
1072
+ openaiKey: env.openai,
1073
+ adminPassword: env.password
1074
+ } : void 0
1075
+ }
1076
+ };
1077
+ };
1078
+ const setText = (value) => {
1079
+ chars = [...value];
1080
+ cursor = chars.length;
1081
+ };
1082
+ let step = "name";
1083
+ const advance = (resolved, after) => {
1084
+ const steps = stepsFor(resolved);
1085
+ const next = steps[after ? steps.indexOf(after) + 1 : 0];
1086
+ setText("");
1087
+ if (next) {
1088
+ step = next;
1089
+ } else {
1090
+ finish(resolved);
1091
+ }
1092
+ };
1093
+ if (target) advance(target);
1094
+ const submit = () => {
1095
+ if (step === "name") {
1096
+ const candidate = chars.join("").trim();
1097
+ if (!candidate) return;
1098
+ const resolution = config.resolveTarget(candidate);
1099
+ if (!resolution.ok) {
1100
+ nameError = resolution.message;
1101
+ setText("");
1102
+ return;
1103
+ }
1104
+ nameError = void 0;
1105
+ target = resolution.target;
1106
+ advance(target);
1107
+ return;
1108
+ }
1109
+ if (!target) return;
1110
+ if (step === "packageManager") {
1111
+ packageManagerChosen = true;
1112
+ } else if (step !== "confirm") {
1113
+ const value = chars.join("").trim();
1114
+ fieldError = config.validateEnvValue?.(value);
1115
+ if (fieldError) return;
1116
+ env[step] = value;
1117
+ }
1118
+ advance(target, step);
1119
+ };
1120
+ const movePackageManager = (offset) => {
1121
+ if (step !== "packageManager") return;
1122
+ const count = INIT_PACKAGE_MANAGERS.length;
1123
+ packageManagerIndex = (packageManagerIndex + offset + count) % count;
1124
+ };
1125
+ const editing = () => TEXT_STEPS.has(step);
1126
+ const erase = () => {
1127
+ if (!editing() || cursor === 0) return;
1128
+ chars.splice(cursor - 1, 1);
1129
+ cursor -= 1;
1130
+ };
1131
+ const moveCursor = (position) => {
1132
+ if (editing()) cursor = Math.min(chars.length, Math.max(0, position));
1133
+ };
1134
+ const applyCharacter = (char) => {
1135
+ const completesCrlf = char === "\n" && afterCarriageReturn;
1136
+ afterCarriageReturn = char === "\r";
1137
+ if (completesCrlf) return;
1138
+ if (char === "\r" || char === "\n") {
1139
+ submit();
1140
+ } else if (char === "") {
1141
+ outcome = { kind: "cancelled" };
1142
+ } else if (char === "\x7F" || char === "\b") {
1143
+ erase();
1144
+ } else if (step === "packageManager") {
1145
+ if (char === "k") movePackageManager(-1);
1146
+ if (char === "j") movePackageManager(1);
1147
+ } else if (editing() && char >= " ") {
1148
+ chars.splice(cursor, 0, char);
1149
+ cursor += 1;
1150
+ }
1151
+ };
1152
+ return {
1153
+ handleKey(input, key) {
1154
+ if (outcome) return;
1155
+ if (key.return) {
1156
+ applyCharacter("\r");
1157
+ return;
1158
+ }
1159
+ if (key.escape || key.ctrl && input === "c") {
1160
+ outcome = { kind: "cancelled" };
1161
+ } else if (key.upArrow) {
1162
+ movePackageManager(-1);
1163
+ } else if (key.downArrow) {
1164
+ movePackageManager(1);
1165
+ } else if (key.leftArrow) {
1166
+ moveCursor(cursor - 1);
1167
+ } else if (key.rightArrow) {
1168
+ moveCursor(cursor + 1);
1169
+ } else if (key.home) {
1170
+ moveCursor(0);
1171
+ } else if (key.end) {
1172
+ moveCursor(chars.length);
1173
+ } else if (key.backspace || key.delete) {
1174
+ erase();
1175
+ } else if (!key.ctrl && !key.meta) {
1176
+ for (const char of input) {
1177
+ if (outcome) return;
1178
+ applyCharacter(char);
1179
+ }
1180
+ return;
1181
+ }
1182
+ afterCarriageReturn = false;
1183
+ },
1184
+ snapshot() {
1185
+ return {
1186
+ step,
1187
+ text: chars.join(""),
1188
+ cursor,
1189
+ nameError,
1190
+ fieldError,
1191
+ target,
1192
+ packageManager: config.packageManager ?? INIT_PACKAGE_MANAGERS[packageManagerIndex],
1193
+ packageManagerChosen: packageManagerChosen || Boolean(config.packageManager),
1194
+ env: { ...env },
1195
+ collectEnv: target ? target.collectEnv : config.collectEnvByDefault,
1196
+ outcome
1197
+ };
1198
+ }
1199
+ };
1200
+ }
566
1201
  var STAGE_LABELS = {
567
1202
  project: "Project",
568
- auth: "Auth",
569
1203
  env: "Env",
570
1204
  scaffold: "Scaffold"
571
1205
  };
572
- var STANDARDAGENTS_FLOW = ["project", "auth", "scaffold"];
573
- var LOCAL_FLOW = ["project", "auth", "env", "scaffold"];
574
- function getInitProgressStages(authMode = "standardagents") {
575
- return authMode === "local" ? LOCAL_FLOW : STANDARDAGENTS_FLOW;
1206
+ function getInitProgressStages(collectEnv) {
1207
+ return collectEnv ? ["project", "env", "scaffold"] : ["project", "scaffold"];
576
1208
  }
577
- function getInitStepInfo(stage, authMode = "standardagents") {
578
- const flow = getInitProgressStages(authMode);
1209
+ function getInitStepInfo(stage, collectEnv) {
1210
+ const flow = getInitProgressStages(collectEnv);
579
1211
  const stepIndex = flow.indexOf(stage);
580
1212
  return {
581
1213
  step: stepIndex === -1 ? 1 : stepIndex + 1,
@@ -583,24 +1215,8 @@ function getInitStepInfo(stage, authMode = "standardagents") {
583
1215
  labels: flow.map((item) => STAGE_LABELS[item])
584
1216
  };
585
1217
  }
586
- var AUTH_SIDE_BY_SIDE_MIN_COLUMNS = 110;
587
- function shouldUseSideBySideAuthCards(columns) {
588
- return columns >= AUTH_SIDE_BY_SIDE_MIN_COLUMNS;
589
- }
590
- function clearInkScreen(stdout = process.stdout) {
591
- stdout.write("\x1B[2J\x1B[H");
592
- }
593
- async function settleStdinBeforePrompt(stdin = process.stdin) {
594
- if (!stdin.isTTY) return;
595
- stdin.pause();
596
- while (stdin.read() !== null) {
597
- }
598
- await new Promise((resolve) => setTimeout(resolve, 0));
599
- while (stdin.read() !== null) {
600
- }
601
- }
602
- function Stepper({ activeStage, authMode }) {
603
- const flow = getInitProgressStages(authMode);
1218
+ function Stepper({ activeStage, collectEnv }) {
1219
+ const flow = getInitProgressStages(collectEnv);
604
1220
  const activeIndex = flow.indexOf(activeStage);
605
1221
  return /* @__PURE__ */ jsx(Box, { flexDirection: "row", marginBottom: 1, children: flow.map((stage, index) => {
606
1222
  const label = STAGE_LABELS[stage];
@@ -619,42 +1235,31 @@ function Stepper({ activeStage, authMode }) {
619
1235
  }) });
620
1236
  }
621
1237
  function InitStepFrame(props) {
622
- const mode = props.authMode ?? "standardagents";
623
- const { step, total } = getInitStepInfo(props.stage, mode);
1238
+ const { step, total } = getInitStepInfo(props.stage, props.collectEnv);
624
1239
  const metadata = useMemo(() => {
625
1240
  const items = [];
626
1241
  if (props.projectName) {
627
1242
  items.push({ id: "project", label: "Project", value: props.projectName });
628
1243
  }
629
1244
  if (props.packageManager) {
630
- items.push({ id: "pm", label: "PM", value: props.packageManager });
631
- }
632
- if (props.authMode) {
633
- items.push({
634
- id: "mode",
635
- label: "Mode",
636
- value: props.authMode === "standardagents" ? "Standard Agents" : "Local"
637
- });
1245
+ items.push({ id: "pm", label: "Package manager", value: props.packageManager });
638
1246
  }
639
1247
  return items;
640
- }, [props.authMode, props.packageManager, props.projectName]);
1248
+ }, [props.packageManager, props.projectName]);
641
1249
  return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", paddingX: 1, children: [
642
1250
  /* @__PURE__ */ jsxs(Box, { borderStyle: "round", borderColor: "cyan", paddingX: 1, flexDirection: "column", children: [
643
1251
  /* @__PURE__ */ jsx(Text, { color: "cyanBright", bold: true, children: "Standard Agents CLI" }),
644
- /* @__PURE__ */ jsx(Text, { color: "gray", children: "Init Wizard" })
1252
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Project setup" })
645
1253
  ] }),
646
- /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(Stepper, { activeStage: props.stage, authMode: mode }) }),
647
- metadata.length > 0 && /* @__PURE__ */ jsx(Box, { marginBottom: 1, flexDirection: "row", children: metadata.map((item, index) => {
648
- const valueColor = item.id === "project" ? "whiteBright" : item.id === "pm" ? "magentaBright" : item.value === "Standard Agents" ? "greenBright" : "yellowBright";
649
- return /* @__PURE__ */ jsxs(Box, { flexDirection: "row", children: [
650
- /* @__PURE__ */ jsxs(Text, { color: "gray", children: [
651
- item.label,
652
- " "
653
- ] }),
654
- /* @__PURE__ */ jsx(Text, { color: valueColor, children: item.value }),
655
- index < metadata.length - 1 ? /* @__PURE__ */ jsx(Text, { color: "gray", children: " \u2022 " }) : null
656
- ] }, item.id);
657
- }) }),
1254
+ /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(Stepper, { activeStage: props.stage, collectEnv: props.collectEnv }) }),
1255
+ metadata.length > 0 && /* @__PURE__ */ jsx(Box, { marginBottom: 1, flexDirection: "row", children: metadata.map((item, index) => /* @__PURE__ */ jsxs(Box, { flexDirection: "row", children: [
1256
+ /* @__PURE__ */ jsxs(Text, { color: "gray", children: [
1257
+ item.label,
1258
+ " "
1259
+ ] }),
1260
+ /* @__PURE__ */ jsx(Text, { color: item.id === "project" ? "whiteBright" : "magentaBright", children: item.value }),
1261
+ index < metadata.length - 1 ? /* @__PURE__ */ jsx(Text, { color: "gray", children: " \u2022 " }) : null
1262
+ ] }, item.id)) }),
658
1263
  /* @__PURE__ */ jsxs(Text, { color: "whiteBright", bold: true, children: [
659
1264
  "Step ",
660
1265
  step,
@@ -666,485 +1271,212 @@ function InitStepFrame(props) {
666
1271
  props.subtitle ? /* @__PURE__ */ jsx(Text, { color: "gray", children: props.subtitle }) : null
667
1272
  ] });
668
1273
  }
669
- function OptionCard({
670
- option,
671
- selected,
672
- width
673
- }) {
674
- const borderColor = selected ? "cyan" : "gray";
675
- const titleColor = selected ? "cyanBright" : "whiteBright";
676
- const textColor = selected ? "whiteBright" : "gray";
677
- return /* @__PURE__ */ jsxs(
678
- Box,
679
- {
680
- width,
681
- borderStyle: "round",
682
- borderColor,
683
- flexDirection: "column",
684
- paddingX: 1,
685
- paddingY: 0,
686
- marginRight: 1,
687
- children: [
688
- /* @__PURE__ */ jsxs(Box, { children: [
689
- /* @__PURE__ */ jsx(Text, { color: titleColor, bold: true, children: option.label }),
690
- option.badge ? /* @__PURE__ */ jsx(Text, { color: selected ? "cyanBright" : "gray", children: ` ${option.badge}` }) : null
691
- ] }),
692
- option.description ? /* @__PURE__ */ jsx(Box, { marginTop: 0, children: /* @__PURE__ */ jsx(Text, { color: textColor, children: option.description }) }) : null,
693
- option.bullets?.map((line) => /* @__PURE__ */ jsxs(Text, { color: textColor, children: [
694
- "\u2022 ",
695
- line
696
- ] }, line))
697
- ]
698
- }
699
- );
700
- }
701
- function ProjectNamePrompt({ question, frame, onCancel, onSubmit }) {
702
- const { exit } = useApp();
703
- const label = question.trim().replace(/:$/, "");
704
- useInput((input, key) => {
705
- if (key.ctrl && input === "c") {
706
- process.exit(1);
707
- return;
708
- }
709
- if (key.escape) {
710
- onCancel();
711
- exit();
712
- return;
713
- }
714
- });
715
- return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
716
- /* @__PURE__ */ jsx(InitStepFrame, { ...frame }),
717
- /* @__PURE__ */ jsxs(Box, { flexDirection: "column", paddingX: 1, marginTop: 1, children: [
718
- /* @__PURE__ */ jsxs(Box, { borderStyle: "round", borderColor: "cyan", paddingX: 1, marginTop: 1, children: [
719
- /* @__PURE__ */ jsxs(Text, { color: "gray", children: [
720
- label,
721
- ": "
722
- ] }),
723
- /* @__PURE__ */ jsx(
724
- TextInput,
725
- {
726
- placeholder: "acme-agents",
727
- onSubmit: (nextValue) => {
728
- const trimmed = nextValue.trim();
729
- if (!trimmed) {
730
- return;
731
- }
732
- onSubmit(trimmed);
733
- exit();
734
- }
735
- }
736
- )
737
- ] }),
738
- /* @__PURE__ */ jsx(Text, { color: "gray", children: "Type to edit, Enter to continue." })
739
- ] })
740
- ] });
741
- }
742
- async function promptProjectNameWithInk(question, frame) {
743
- let resolved = null;
744
- let cancelled = false;
745
- await settleStdinBeforePrompt();
746
- clearInkScreen();
747
- const instance = render(
748
- /* @__PURE__ */ jsx(
749
- ProjectNamePrompt,
750
- {
751
- question,
752
- frame,
753
- onCancel: () => {
754
- cancelled = true;
755
- },
756
- onSubmit: (value) => {
757
- resolved = value;
758
- }
759
- }
760
- ),
761
- { exitOnCtrlC: false }
762
- );
763
- await instance.waitUntilExit();
764
- if (cancelled) return null;
765
- return resolved ?? "";
766
- }
767
- var LOCAL_ENV_FIELDS = [
768
- {
769
- id: "openrouter",
1274
+ var PACKAGE_MANAGER_DESCRIPTIONS = {
1275
+ npm: "Default Node package manager.",
1276
+ pnpm: "Fast, space-efficient monorepo manager.",
1277
+ yarn: "Classic workspace package manager.",
1278
+ bun: "Bun runtime package manager."
1279
+ };
1280
+ var ENV_FIELD_COPY = {
1281
+ openrouter: {
770
1282
  title: "OpenRouter API key",
771
1283
  description: "Optional. Needed for OpenRouter models.",
772
1284
  placeholder: "sk-or-v1-... (optional)"
773
1285
  },
774
- {
775
- id: "openai",
1286
+ openai: {
776
1287
  title: "OpenAI API key",
777
1288
  description: "Optional. Needed for OpenAI models.",
778
1289
  placeholder: "sk-... (optional)"
779
1290
  },
780
- {
781
- id: "password",
1291
+ password: {
782
1292
  title: "Temporary admin password",
783
- description: "Press Enter to use default: admin",
784
- placeholder: "admin"
1293
+ description: "Press Enter to generate a random password in .dev.vars.",
1294
+ placeholder: "random (press Enter)"
785
1295
  }
786
- ];
787
- function LocalEnvPrompt({ frame, onCancel, onSubmit }) {
788
- const { exit } = useApp();
789
- const [fieldIndex, setFieldIndex] = useState(0);
790
- const [draft, setDraft] = useState({
791
- openrouter: "",
792
- openai: "",
793
- password: ""
794
- });
795
- useInput((input, key) => {
796
- if (key.ctrl && input === "c") {
797
- process.exit(1);
798
- return;
799
- }
800
- if (key.escape) {
801
- onCancel();
802
- exit();
803
- return;
804
- }
805
- });
806
- const maskFieldValue = (fieldId, value) => {
807
- if (!value) return "";
808
- if (fieldId === "password") return "\u2022".repeat(value.length);
809
- return value;
810
- };
811
- return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
812
- /* @__PURE__ */ jsx(
813
- InitStepFrame,
814
- {
815
- stage: "env",
816
- title: "Environment setup",
817
- subtitle: "Add optional provider keys and local admin access.",
818
- projectName: frame.projectName,
819
- packageManager: frame.packageManager,
820
- authMode: frame.authMode
821
- }
822
- ),
823
- /* @__PURE__ */ jsx(Box, { marginTop: 1, paddingX: 1, flexDirection: "column", children: LOCAL_ENV_FIELDS.map((field, index) => {
824
- const isActive = index === fieldIndex;
825
- const isComplete = index < fieldIndex;
1296
+ };
1297
+ var MASK = "\u2022";
1298
+ function TextField({ state, placeholder, secret }) {
1299
+ const chars = [...state.text].map((char) => secret ? MASK : char);
1300
+ return /* @__PURE__ */ jsxs(Box, { borderStyle: "round", borderColor: "cyan", paddingX: 1, children: [
1301
+ /* @__PURE__ */ jsx(Text, { children: chars.slice(0, state.cursor).join("") }),
1302
+ /* @__PURE__ */ jsx(Text, { inverse: true, children: chars[state.cursor] ?? " " }),
1303
+ chars.length > 0 ? /* @__PURE__ */ jsx(Text, { children: chars.slice(state.cursor + 1).join("") }) : /* @__PURE__ */ jsx(Text, { color: "gray", children: placeholder })
1304
+ ] });
1305
+ }
1306
+ function WizardBody({ state, detected }) {
1307
+ if (state.step === "name") {
1308
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", paddingX: 1, marginTop: 1, children: [
1309
+ state.nameError ? /* @__PURE__ */ jsx(Text, { color: "yellow", children: state.nameError }) : null,
1310
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Project name" }),
1311
+ /* @__PURE__ */ jsx(TextField, { state, placeholder: "acme-agents" }),
1312
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Type a name. Press Enter to continue or Esc to cancel." })
1313
+ ] });
1314
+ }
1315
+ if (state.step === "confirm") {
1316
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", paddingX: 1, marginTop: 1, children: [
1317
+ /* @__PURE__ */ jsx(Text, { children: `"${state.target?.projectName ?? ""}" already holds a Standard Agents project.` }),
1318
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Setup will reinstall dependencies and refresh the scaffold files." }),
1319
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Existing values in .dev.vars will be kept." }),
1320
+ /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(Text, { color: "gray", children: "Press Enter to update this project or Esc to cancel." }) })
1321
+ ] });
1322
+ }
1323
+ if (state.step === "packageManager") {
1324
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", paddingX: 1, marginTop: 1, children: [
1325
+ INIT_PACKAGE_MANAGERS.map((name) => {
1326
+ const selected = name === state.packageManager;
1327
+ return /* @__PURE__ */ jsxs(Box, { children: [
1328
+ /* @__PURE__ */ jsxs(Text, { color: selected ? "black" : "white", backgroundColor: selected ? "cyan" : void 0, bold: selected, children: [
1329
+ selected ? "\u203A" : " ",
1330
+ " ",
1331
+ name,
1332
+ name === detected ? " (detected)" : ""
1333
+ ] }),
1334
+ /* @__PURE__ */ jsx(Text, { color: selected ? "cyan" : "gray", children: ` ${PACKAGE_MANAGER_DESCRIPTIONS[name]}` })
1335
+ ] }, name);
1336
+ }),
1337
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Use the arrow keys (or j/k). Press Enter to continue or Esc to cancel." })
1338
+ ] });
1339
+ }
1340
+ const activeIndex = ENV_FIELDS.indexOf(state.step);
1341
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", paddingX: 1, marginTop: 1, children: [
1342
+ ENV_FIELDS.map((field, index) => {
1343
+ const copy = ENV_FIELD_COPY[field];
1344
+ const isActive = index === activeIndex;
1345
+ const isComplete = index < activeIndex;
826
1346
  const marker = isComplete ? "\u2713" : isActive ? "\u203A" : "\xB7";
1347
+ const saved = state.env[field] ? MASK.repeat(8) : "";
827
1348
  return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [
828
1349
  /* @__PURE__ */ jsxs(Text, { color: isActive ? "cyanBright" : isComplete ? "greenBright" : "gray", bold: isActive, children: [
829
1350
  marker,
830
1351
  " ",
831
- field.title
1352
+ copy.title
832
1353
  ] }),
833
- /* @__PURE__ */ jsx(Text, { color: "gray", children: field.description }),
834
- isActive ? /* @__PURE__ */ jsx(Box, { borderStyle: "round", borderColor: "cyan", paddingX: 1, children: /* @__PURE__ */ jsx(
835
- TextInput,
836
- {
837
- defaultValue: draft[field.id],
838
- placeholder: field.placeholder,
839
- onSubmit: (nextValue) => {
840
- const trimmed = nextValue.trim();
841
- const nextDraft = { ...draft, [field.id]: trimmed };
842
- setDraft(nextDraft);
843
- if (fieldIndex < LOCAL_ENV_FIELDS.length - 1) {
844
- setFieldIndex(fieldIndex + 1);
845
- return;
846
- }
847
- onSubmit({
848
- openrouterKey: nextDraft.openrouter,
849
- openaiKey: nextDraft.openai,
850
- adminPassword: nextDraft.password || "admin"
851
- });
852
- exit();
853
- }
854
- },
855
- field.id
856
- ) }) : /* @__PURE__ */ jsx(Text, { color: isComplete ? "white" : "gray", children: maskFieldValue(field.id, draft[field.id]) || "(not set)" })
857
- ] }, field.id);
858
- }) }),
859
- /* @__PURE__ */ jsx(Box, { paddingX: 1, children: /* @__PURE__ */ jsx(Text, { color: "gray", children: "Press Enter to continue each field." }) })
1354
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: copy.description }),
1355
+ isActive ? /* @__PURE__ */ jsxs(Fragment, { children: [
1356
+ /* @__PURE__ */ jsx(TextField, { state, placeholder: copy.placeholder, secret: true }),
1357
+ state.fieldError ? /* @__PURE__ */ jsx(Text, { color: "yellow", children: state.fieldError }) : null
1358
+ ] }) : /* @__PURE__ */ jsx(Text, { color: isComplete ? "white" : "gray", children: saved || "(not set)" })
1359
+ ] }, field);
1360
+ }),
1361
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Keys for other providers can be added to .dev.vars later." }),
1362
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Press Enter to continue each field or Esc to cancel." })
860
1363
  ] });
861
1364
  }
862
- async function collectLocalEnvWithInk(frame) {
863
- let resolved = null;
864
- let cancelled = false;
865
- await settleStdinBeforePrompt();
866
- clearInkScreen();
867
- const instance = render(
1365
+ var ENV_FRAME = {
1366
+ stage: "env",
1367
+ title: "Environment setup",
1368
+ subtitle: "Add optional provider keys and local admin access."
1369
+ };
1370
+ var STEP_FRAMES = {
1371
+ name: { stage: "project", title: "Project", subtitle: "Choose the directory name for your new project." },
1372
+ confirm: { stage: "project", title: "Existing project", subtitle: "Confirm the update of this project." },
1373
+ packageManager: {
1374
+ stage: "project",
1375
+ title: "Package manager",
1376
+ subtitle: "Select the package manager for install and scaffold commands."
1377
+ },
1378
+ openrouter: ENV_FRAME,
1379
+ openai: ENV_FRAME,
1380
+ password: ENV_FRAME
1381
+ };
1382
+ function LocalInitWizardView({ wizard, detected }) {
1383
+ const { exit } = useApp();
1384
+ const [state, setState] = useState(() => wizard.snapshot());
1385
+ useInput((input, key) => {
1386
+ wizard.handleKey(input, key);
1387
+ const next = wizard.snapshot();
1388
+ setState(next);
1389
+ if (next.outcome) exit();
1390
+ });
1391
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
868
1392
  /* @__PURE__ */ jsx(
869
- LocalEnvPrompt,
1393
+ InitStepFrame,
870
1394
  {
871
- frame,
872
- onCancel: () => {
873
- cancelled = true;
874
- },
875
- onSubmit: (value) => {
876
- resolved = value;
877
- }
1395
+ ...STEP_FRAMES[state.step],
1396
+ projectName: state.target?.projectName,
1397
+ packageManager: state.packageManagerChosen ? state.packageManager : void 0,
1398
+ collectEnv: state.collectEnv
878
1399
  }
879
1400
  ),
880
- { exitOnCtrlC: false }
881
- );
1401
+ /* @__PURE__ */ jsx(WizardBody, { state, detected })
1402
+ ] });
1403
+ }
1404
+ async function runLocalInitWizardWithInk(config, terminal = { stdin: process.stdin, stdout: process.stdout }) {
1405
+ const wizard = createLocalInitWizard(config);
1406
+ const settled = wizard.snapshot().outcome;
1407
+ if (settled) return settled.kind === "done" ? settled.result : null;
1408
+ terminal.stdout.write("\x1B[2J\x1B[H");
1409
+ const instance = render(/* @__PURE__ */ jsx(LocalInitWizardView, { wizard, detected: config.detectedPackageManager }), {
1410
+ stdin: terminal.stdin,
1411
+ stdout: terminal.stdout,
1412
+ exitOnCtrlC: false
1413
+ });
882
1414
  await instance.waitUntilExit();
883
- if (cancelled) return null;
884
- return resolved;
1415
+ const outcome = wizard.snapshot().outcome;
1416
+ return outcome?.kind === "done" ? outcome.result : null;
885
1417
  }
886
1418
  function renderInitStepFrame(state) {
887
1419
  return renderToString(/* @__PURE__ */ jsx(InitStepFrame, { ...state }));
888
1420
  }
1421
+ var LOCAL_SIGN_IN_NOTES = [
1422
+ "Open the dev server URL. Sign in with username `admin` and the `SUPER_ADMIN_PASSWORD` value from `.dev.vars`.",
1423
+ "Open the gear menu, select Users, and create an account for yourself.",
1424
+ "Sign in with your own account, then remove `SUPER_ADMIN_PASSWORD` from `.dev.vars`.",
1425
+ "Add provider API keys to `.dev.vars` to use more model providers."
1426
+ ];
1427
+ var GENERATED_ADMIN_PASSWORD_NOTES = [
1428
+ "This project used a default admin password. It now has a random one.",
1429
+ "The password is saved as `SUPER_ADMIN_PASSWORD` in `.dev.vars`.",
1430
+ "Sign in with username `admin` and this password:"
1431
+ ];
889
1432
  function renderInitCompleteFrame(input) {
890
1433
  return renderToString(
891
1434
  /* @__PURE__ */ jsxs(Box, { flexDirection: "column", paddingX: 1, children: [
892
1435
  /* @__PURE__ */ jsxs(Box, { borderStyle: "round", borderColor: "green", paddingX: 1, flexDirection: "column", children: [
893
- /* @__PURE__ */ jsx(Text, { color: "greenBright", bold: true, children: "Init Complete" }),
1436
+ /* @__PURE__ */ jsx(Text, { color: "greenBright", bold: true, children: "Setup complete" }),
894
1437
  /* @__PURE__ */ jsx(Text, { color: "whiteBright", children: input.useExistingProject ? "Project updated successfully." : "Project created successfully." })
895
1438
  ] }),
896
1439
  /* @__PURE__ */ jsxs(Box, { marginTop: 1, flexDirection: "column", children: [
897
1440
  /* @__PURE__ */ jsx(Text, { color: "cyanBright", bold: true, children: "Next steps" }),
898
- !input.useExistingProject ? /* @__PURE__ */ jsx(Text, { color: "white", children: ` cd ${input.projectName}` }) : null,
1441
+ input.changeDirectory ? /* @__PURE__ */ jsx(Text, { color: "white", children: ` cd ${input.projectName}` }) : null,
899
1442
  /* @__PURE__ */ jsx(Text, { color: "white", children: ` ${input.nextCommand}` })
900
1443
  ] }),
901
- !input.bootstrapSession ? /* @__PURE__ */ jsxs(Box, { marginTop: 1, flexDirection: "column", children: [
902
- /* @__PURE__ */ jsx(Text, { color: "yellowBright", bold: true, children: "Local-only notes" }),
903
- /* @__PURE__ */ jsx(Text, { color: "gray", children: " 1. Sign in locally with username `admin` and your temporary `SUPER_ADMIN_PASSWORD`." }),
904
- /* @__PURE__ */ jsx(Text, { color: "gray", children: " 2. Create a standard user account for yourself." }),
905
- /* @__PURE__ */ jsx(Text, { color: "gray", children: " 3. Remove `SUPER_ADMIN_PASSWORD` from `.dev.vars` once setup is complete." })
1444
+ input.localSignIn ? /* @__PURE__ */ jsxs(Box, { marginTop: 1, flexDirection: "column", children: [
1445
+ /* @__PURE__ */ jsx(Text, { color: "yellowBright", bold: true, children: "Sign in" }),
1446
+ LOCAL_SIGN_IN_NOTES.map((note, index) => /* @__PURE__ */ jsx(Text, { color: "gray", children: ` ${index + 1}. ${note}` }, note))
1447
+ ] }) : null,
1448
+ input.generatedAdminPassword ? /* @__PURE__ */ jsxs(Box, { marginTop: 1, flexDirection: "column", children: [
1449
+ GENERATED_ADMIN_PASSWORD_NOTES.map((note) => /* @__PURE__ */ jsx(Text, { color: "yellow", children: note }, note)),
1450
+ /* @__PURE__ */ jsx(Text, { color: "whiteBright", children: ` ${input.generatedAdminPassword}` })
906
1451
  ] }) : null,
907
1452
  /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(Text, { color: "gray", children: "Docs: https://standardagents.ai/docs" }) })
908
1453
  ] })
909
1454
  );
910
1455
  }
911
- async function selectPackageManagerWithInk(detected, context = {}) {
912
- const options = [
913
- { value: "npm", label: "npm", description: "Default Node package manager.", badge: detected === "npm" ? "(detected)" : void 0 },
914
- { value: "pnpm", label: "pnpm", description: "Fast, space-efficient monorepo manager.", badge: detected === "pnpm" ? "(detected)" : void 0 },
915
- { value: "yarn", label: "yarn", description: "Classic workspace package manager.", badge: detected === "yarn" ? "(detected)" : void 0 },
916
- { value: "bun", label: "bun", description: "Bun runtime package manager.", badge: detected === "bun" ? "(detected)" : void 0 }
917
- ];
918
- function PackageManagerPrompt({
919
- onCancel,
920
- onSubmit
921
- }) {
922
- const { exit } = useApp();
923
- const [selectedIndex, setSelectedIndex] = useState(
924
- Math.max(0, options.findIndex((option) => option.value === detected))
925
- );
926
- const selectedPm = options[selectedIndex]?.value ?? detected;
927
- useInput((input, key) => {
928
- if (key.upArrow || input === "k") {
929
- setSelectedIndex((prev) => (prev - 1 + options.length) % options.length);
930
- return;
931
- }
932
- if (key.downArrow || input === "j") {
933
- setSelectedIndex((prev) => (prev + 1) % options.length);
934
- return;
935
- }
936
- if (key.return) {
937
- onSubmit(selectedPm);
938
- exit();
939
- return;
940
- }
941
- if (key.escape) {
942
- onCancel();
943
- exit();
944
- return;
945
- }
946
- if (key.ctrl && input === "c") {
947
- process.exit(1);
948
- }
949
- });
950
- return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
951
- /* @__PURE__ */ jsx(
952
- InitStepFrame,
953
- {
954
- stage: "project",
955
- title: "Creating project scaffold",
956
- subtitle: "Select package manager for install and scaffold commands.",
957
- projectName: context.projectName,
958
- packageManager: selectedPm,
959
- authMode: context.authMode
960
- }
961
- ),
962
- /* @__PURE__ */ jsx(Box, { marginTop: 1, flexDirection: "column", paddingX: 1, children: options.map((option, index) => {
963
- const selected = index === selectedIndex;
964
- return /* @__PURE__ */ jsxs(Box, { marginBottom: 0, children: [
965
- /* @__PURE__ */ jsxs(Text, { color: selected ? "black" : "white", backgroundColor: selected ? "cyan" : void 0, bold: selected, children: [
966
- selected ? "\u203A" : " ",
967
- " ",
968
- option.label,
969
- option.badge ? ` ${option.badge}` : ""
970
- ] }),
971
- option.description ? /* @__PURE__ */ jsx(Text, { color: selected ? "cyan" : "gray", children: ` ${option.description}` }) : null
972
- ] }, option.value);
973
- }) }),
974
- /* @__PURE__ */ jsx(Box, { paddingX: 1, children: /* @__PURE__ */ jsx(Text, { color: "gray", children: "Use arrows (or j/k), Enter to continue, Esc to return." }) })
975
- ] });
976
- }
977
- let resolved = null;
978
- let cancelled = false;
979
- await settleStdinBeforePrompt();
980
- clearInkScreen();
981
- const instance = render(
982
- /* @__PURE__ */ jsx(
983
- PackageManagerPrompt,
984
- {
985
- onCancel: () => {
986
- cancelled = true;
987
- },
988
- onSubmit: (value) => {
989
- resolved = value;
990
- }
991
- }
992
- ),
993
- { exitOnCtrlC: false }
994
- );
995
- await instance.waitUntilExit();
996
- if (cancelled) return null;
997
- return resolved;
998
- }
999
- function AuthModePrompt({ projectName, packageManager, onCancel, onSubmit }) {
1000
- const { exit } = useApp();
1001
- const options = [
1002
- {
1003
- value: "standardagents",
1004
- label: "Standard Agents",
1005
- bullets: ["Free account", "$2 starting credit", "Zero-config setup", "Production deployments"]
1006
- },
1007
- {
1008
- value: "local",
1009
- label: "Local",
1010
- bullets: ["Bring your own provider keys", "Manual setup required", "Local-only mode", "Account required for production"]
1011
- }
1012
- ];
1013
- const [selectedIndex, setSelectedIndex] = useState(0);
1014
- const selectedMode = options[selectedIndex]?.value ?? "standardagents";
1015
- const columns = process.stdout.columns ?? 120;
1016
- const horizontal = shouldUseSideBySideAuthCards(columns);
1017
- const cardWidth = horizontal ? Math.max(34, Math.floor((columns - 8) / options.length)) : Math.max(42, columns - 6);
1018
- useInput((input, key) => {
1019
- if (key.upArrow || input === "k" || key.leftArrow || input === "h") {
1020
- setSelectedIndex((prev) => (prev - 1 + options.length) % options.length);
1021
- return;
1022
- }
1023
- if (key.downArrow || input === "j" || key.rightArrow || input === "l") {
1024
- setSelectedIndex((prev) => (prev + 1) % options.length);
1025
- return;
1026
- }
1027
- if (key.return) {
1028
- onSubmit(selectedMode);
1029
- exit();
1030
- return;
1031
- }
1032
- if (key.escape) {
1033
- onCancel();
1034
- exit();
1035
- return;
1036
- }
1037
- if (key.ctrl && input === "c") {
1038
- process.exit(1);
1039
- }
1040
- });
1041
- return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
1042
- /* @__PURE__ */ jsx(
1043
- InitStepFrame,
1044
- {
1045
- stage: "auth",
1046
- title: "Account linking",
1047
- subtitle: "Choose how this project should be configured.",
1048
- projectName,
1049
- packageManager,
1050
- authMode: selectedMode
1051
- }
1052
- ),
1053
- /* @__PURE__ */ jsx(Box, { marginTop: 1, paddingX: 1, flexDirection: horizontal ? "row" : "column", children: options.map((option, index) => /* @__PURE__ */ jsx(Box, { marginBottom: horizontal ? 0 : 1, children: /* @__PURE__ */ jsx(OptionCard, { option, selected: index === selectedIndex, width: cardWidth }) }, option.value)) }),
1054
- /* @__PURE__ */ jsx(Box, { paddingX: 1, children: /* @__PURE__ */ jsx(Text, { color: "gray", children: "Use Left/Right (or h/l), Enter to continue, Esc to return." }) })
1055
- ] });
1056
- }
1057
- async function selectInitAuthModeWithInk(context = {}) {
1058
- let resolved = null;
1059
- let cancelled = false;
1060
- await settleStdinBeforePrompt();
1061
- clearInkScreen();
1062
- const instance = render(
1063
- /* @__PURE__ */ jsx(
1064
- AuthModePrompt,
1065
- {
1066
- projectName: context.projectName,
1067
- packageManager: context.packageManager,
1068
- onCancel: () => {
1069
- cancelled = true;
1070
- },
1071
- onSubmit: (value) => {
1072
- resolved = value;
1073
- }
1074
- }
1075
- ),
1076
- { exitOnCtrlC: false }
1077
- );
1078
- await instance.waitUntilExit();
1079
- if (cancelled) return null;
1080
- return resolved;
1081
- }
1082
1456
 
1083
1457
  // src/commands/init.ts
1084
1458
  var PlatformAuthWsTransportError = class extends Error {
1085
1459
  };
1086
- var DEFAULT_PLATFORM_ENDPOINT = "https://api.standardagents.ai";
1087
- var DEFAULT_ONBOARDING_URL = "https://platform.standardagents.ai/projects/new";
1088
- var KNOWN_PLATFORM_ONBOARDING_URLS = {
1089
- "https://api.standardagents.ai": DEFAULT_ONBOARDING_URL,
1090
- "https://platform.standardagents.ai": DEFAULT_ONBOARDING_URL
1091
- };
1092
- var INIT_TUI_ENV_VAR = "STANDARDAGENTS_INIT_TUI";
1093
- var GENERATED_STANDARD_AGENTS_PACKAGES = [
1094
- "@standardagents/builder",
1095
- "@standardagents/spec",
1096
- ...FIRST_PARTY_PROVIDER_PACKAGES
1097
- ];
1098
- var PACKAGE_MANAGERS = ["npm", "pnpm", "yarn", "bun"];
1099
- var MISSING_PLATFORM_PROJECT_NAME_MESSAGE = "The platform did not return a project name. Please run the init command again to start a new project setup.";
1100
- var LEGACY_BOOTSTRAP_RESPONSE_MESSAGE = "The platform returned an older onboarding response. Please run the init command again to start a new project setup.";
1101
- var INIT_WIZARD_RETURN_TO_HOME_EXIT_CODE = 90;
1102
- var InitWizardReturnToHomeError = class extends Error {
1460
+ var PlatformWaitAbortedError = class extends Error {
1103
1461
  constructor() {
1104
- super("Return to home");
1105
- this.name = "InitWizardReturnToHomeError";
1106
- }
1107
- };
1108
- function isInitWizardReturnToHomeError(error) {
1109
- return error instanceof InitWizardReturnToHomeError;
1110
- }
1111
- function exitOrThrowReturnToHome(options = {}) {
1112
- if (options.returnToHomeOnCancel) {
1113
- throw new InitWizardReturnToHomeError();
1114
- }
1115
- process.exit(INIT_WIZARD_RETURN_TO_HOME_EXIT_CODE);
1116
- }
1117
- async function prompt(question) {
1118
- if (process.stdin.isTTY && process.stdin.isRaw) {
1119
- process.stdin.setRawMode(false);
1120
- }
1121
- process.stdin.resume();
1122
- const rl = readline.createInterface({
1123
- input: process.stdin,
1124
- output: process.stdout
1125
- });
1126
- return new Promise((resolve) => {
1127
- let settled = false;
1128
- const finalize = (answer) => {
1129
- if (settled) return;
1130
- settled = true;
1131
- resolve(answer.trim());
1132
- };
1133
- rl.on("SIGINT", () => {
1134
- process.stdout.write("\n");
1135
- process.exit(130);
1136
- });
1137
- rl.once("close", () => {
1138
- if (!settled) {
1139
- finalize("");
1140
- }
1141
- });
1142
- rl.question(question, (answer) => {
1143
- finalize(answer);
1144
- rl.close();
1145
- });
1146
- });
1147
- }
1462
+ super("The wait for browser sign-in was interrupted.");
1463
+ this.name = "PlatformWaitAbortedError";
1464
+ }
1465
+ };
1466
+ var DEFAULT_PLATFORM_ENDPOINT = "https://api.standardagents.ai";
1467
+ var DEFAULT_ONBOARDING_URL = "https://platform.standardagents.ai/projects/new";
1468
+ var KNOWN_PLATFORM_ONBOARDING_URLS = {
1469
+ "https://api.standardagents.ai": DEFAULT_ONBOARDING_URL,
1470
+ "https://platform.standardagents.ai": DEFAULT_ONBOARDING_URL
1471
+ };
1472
+ var GENERATED_STANDARD_AGENTS_PACKAGES = [
1473
+ "@standardagents/builder",
1474
+ "@standardagents/spec",
1475
+ ...FIRST_PARTY_PROVIDER_PACKAGES
1476
+ ];
1477
+ var PACKAGE_MANAGERS = ["npm", "pnpm", "yarn", "bun"];
1478
+ var MISSING_PLATFORM_PROJECT_NAME_MESSAGE = "The platform did not return a project name. Please run the init command again to start a new project setup.";
1479
+ var LEGACY_BOOTSTRAP_RESPONSE_MESSAGE = "The platform returned an older onboarding response. Please run the init command again to start a new project setup.";
1148
1480
  function parseBootstrapCodeInput(raw) {
1149
1481
  const trimmed = raw.trim();
1150
1482
  if (!trimmed) return "";
@@ -1157,85 +1489,22 @@ function parseBootstrapCodeInput(raw) {
1157
1489
  function shouldSkipBrowserOpen(value) {
1158
1490
  return /^(none|false|0|off)$/i.test(value?.trim() ?? "");
1159
1491
  }
1492
+ function preferredBrowser() {
1493
+ return process.env.STANDARD_AGENTS_BROWSER?.trim() || process.env.BROWSER?.trim() || void 0;
1494
+ }
1160
1495
  function openUrl(url) {
1161
- const preferredBrowser = process.env.STANDARD_AGENTS_BROWSER?.trim() || process.env.BROWSER?.trim();
1162
- if (shouldSkipBrowserOpen(preferredBrowser)) {
1496
+ const browser = preferredBrowser();
1497
+ if (shouldSkipBrowserOpen(browser)) {
1163
1498
  return;
1164
1499
  }
1165
1500
  const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
1166
- const args = process.platform === "darwin" && preferredBrowser ? ["-a", preferredBrowser, url] : process.platform === "win32" ? ["/c", "start", "", url] : [url];
1501
+ const args = process.platform === "darwin" && browser ? ["-a", browser, url] : process.platform === "win32" ? ["/c", "start", "", url] : [url];
1167
1502
  const child = spawn(command, args, { stdio: "ignore", detached: true });
1168
1503
  child.on("error", () => {
1169
1504
  });
1170
1505
  child.unref();
1171
1506
  }
1172
- async function promptPassword(question) {
1173
- return new Promise((resolve) => {
1174
- const stdin = process.stdin;
1175
- const stdout = process.stdout;
1176
- stdout.write(question);
1177
- const wasRaw = stdin.isRaw;
1178
- if (stdin.isTTY) {
1179
- stdin.setRawMode(true);
1180
- }
1181
- stdin.resume();
1182
- stdin.setEncoding("utf8");
1183
- let password = "";
1184
- let settled = false;
1185
- const cleanup = () => {
1186
- if (stdin.isTTY) {
1187
- stdin.setRawMode(wasRaw ?? false);
1188
- }
1189
- stdin.pause();
1190
- stdin.removeListener("data", onData);
1191
- stdin.removeListener("end", onEndOrClose);
1192
- stdin.removeListener("close", onEndOrClose);
1193
- };
1194
- const finalize = (value) => {
1195
- if (settled) return;
1196
- settled = true;
1197
- cleanup();
1198
- resolve(value);
1199
- };
1200
- const onEndOrClose = () => {
1201
- stdout.write("\n");
1202
- finalize(password);
1203
- };
1204
- const onData = (char) => {
1205
- const c = char.toString();
1206
- switch (c) {
1207
- case "\n":
1208
- case "\r":
1209
- case "":
1210
- stdout.write("\n");
1211
- finalize(password);
1212
- break;
1213
- case "":
1214
- stdout.write("\n");
1215
- process.exit(1);
1216
- break;
1217
- case "\x7F":
1218
- // Backspace
1219
- case "\b":
1220
- if (password.length > 0) {
1221
- password = password.slice(0, -1);
1222
- stdout.clearLine(0);
1223
- stdout.cursorTo(0);
1224
- stdout.write(question + "*".repeat(password.length));
1225
- }
1226
- break;
1227
- default:
1228
- password += c;
1229
- stdout.write("*");
1230
- break;
1231
- }
1232
- };
1233
- stdin.on("data", onData);
1234
- stdin.once("end", onEndOrClose);
1235
- stdin.once("close", onEndOrClose);
1236
- });
1237
- }
1238
- var SPINNER_FRAMES = ["-", "\\", "|", "/"];
1507
+ var SPINNER_FRAMES2 = ["-", "\\", "|", "/"];
1239
1508
  async function withTuiSpinner(enabled, label, operation) {
1240
1509
  if (!enabled || !process.stdout.isTTY) {
1241
1510
  return operation();
@@ -1245,10 +1514,10 @@ async function withTuiSpinner(enabled, label, operation) {
1245
1514
  const renderFrame = (prefix) => {
1246
1515
  process.stdout.write(`\r${prefix} ${label}`);
1247
1516
  };
1248
- renderFrame(SPINNER_FRAMES[index]);
1517
+ renderFrame(SPINNER_FRAMES2[index]);
1249
1518
  const timer = setInterval(() => {
1250
- index = (index + 1) % SPINNER_FRAMES.length;
1251
- renderFrame(SPINNER_FRAMES[index]);
1519
+ index = (index + 1) % SPINNER_FRAMES2.length;
1520
+ renderFrame(SPINNER_FRAMES2[index]);
1252
1521
  }, 80);
1253
1522
  try {
1254
1523
  const result = await operation();
@@ -1263,47 +1532,6 @@ async function withTuiSpinner(enabled, label, operation) {
1263
1532
  throw error;
1264
1533
  }
1265
1534
  }
1266
- function appendOutputTail(existing, chunk, maxLength = 8e3) {
1267
- const combined = existing + chunk;
1268
- if (combined.length <= maxLength) return combined;
1269
- return combined.slice(combined.length - maxLength);
1270
- }
1271
- function runCommand(command, args, cwd, options = {}) {
1272
- return new Promise((resolve, reject) => {
1273
- const quiet = options.quiet ?? false;
1274
- const child = spawn(command, args, {
1275
- cwd,
1276
- stdio: quiet ? ["ignore", "pipe", "pipe"] : "inherit",
1277
- shell: false,
1278
- // npx-inherited npm_config_allow_scripts fatals npm 12 project installs
1279
- // (EALLOWSCRIPTS); approvals live in the generated package.json instead.
1280
- env: packageManagerEnv()
1281
- });
1282
- let outputTail = "";
1283
- if (quiet) {
1284
- child.stdout?.on("data", (chunk) => {
1285
- outputTail = appendOutputTail(outputTail, chunk.toString());
1286
- });
1287
- child.stderr?.on("data", (chunk) => {
1288
- outputTail = appendOutputTail(outputTail, chunk.toString());
1289
- });
1290
- }
1291
- child.on("close", (code) => {
1292
- if (code === 0) {
1293
- resolve();
1294
- } else {
1295
- const details = outputTail.trim();
1296
- if (details) {
1297
- reject(new Error(`Command failed with exit code ${code}
1298
- ${details}`));
1299
- return;
1300
- }
1301
- reject(new Error(`Command failed with exit code ${code}`));
1302
- }
1303
- });
1304
- child.on("error", reject);
1305
- });
1306
- }
1307
1535
  function devServerSpawnOptions(cwd) {
1308
1536
  return {
1309
1537
  cwd,
@@ -1371,16 +1599,16 @@ function normalizeProjectName(raw) {
1371
1599
  return toKebabCase(raw.trim());
1372
1600
  }
1373
1601
  function isNonEmptyDirectory(targetPath) {
1374
- if (!fs5.existsSync(targetPath)) return false;
1375
- const stat = fs5.statSync(targetPath);
1602
+ if (!fs8.existsSync(targetPath)) return false;
1603
+ const stat = fs8.statSync(targetPath);
1376
1604
  if (!stat.isDirectory()) return false;
1377
- return fs5.readdirSync(targetPath).length > 0;
1605
+ return fs8.readdirSync(targetPath).length > 0;
1378
1606
  }
1379
1607
  function hasBuilderDependency(targetPath) {
1380
- const packageJsonPath = path8.join(targetPath, "package.json");
1381
- if (!fs5.existsSync(packageJsonPath)) return false;
1608
+ const packageJsonPath = path9.join(targetPath, "package.json");
1609
+ if (!fs8.existsSync(packageJsonPath)) return false;
1382
1610
  try {
1383
- const pkg = JSON.parse(fs5.readFileSync(packageJsonPath, "utf-8"));
1611
+ const pkg = JSON.parse(fs8.readFileSync(packageJsonPath, "utf-8"));
1384
1612
  if (pkg === null || typeof pkg !== "object") return false;
1385
1613
  const dependencies = "dependencies" in pkg ? pkg.dependencies : void 0;
1386
1614
  const devDependencies = "devDependencies" in pkg ? pkg.devDependencies : void 0;
@@ -1392,78 +1620,65 @@ function hasBuilderDependency(targetPath) {
1392
1620
  }
1393
1621
  }
1394
1622
  function isStandardAgentsProjectDir(targetPath) {
1395
- const agentsDir = path8.join(targetPath, "agents");
1396
- if (!fs5.existsSync(agentsDir) || !fs5.statSync(agentsDir).isDirectory()) {
1623
+ const agentsDir = path9.join(targetPath, "agents");
1624
+ if (!fs8.existsSync(agentsDir) || !fs8.statSync(agentsDir).isDirectory()) {
1397
1625
  return false;
1398
1626
  }
1399
1627
  if (hasBuilderDependency(targetPath)) return true;
1400
- return fs5.existsSync(path8.join(targetPath, "vite.config.ts")) && fs5.existsSync(path8.join(targetPath, "tsconfig.json"));
1628
+ return fs8.existsSync(path9.join(targetPath, "vite.config.ts")) && fs8.existsSync(path9.join(targetPath, "tsconfig.json"));
1401
1629
  }
1402
- async function resolveProjectTarget(cwd, initialProjectName, options, promptProjectName = prompt) {
1403
- if (!initialProjectName && isStandardAgentsProjectDir(cwd)) {
1404
- const dirName = path8.basename(cwd) || "standard-agents";
1405
- const projectName = normalizeProjectName(dirName) || dirName;
1406
- const existingBootstrapState = loadBootstrapState(cwd);
1630
+ function resolveProjectTarget(cwd, candidate) {
1631
+ const requested = candidate?.trim() ?? "";
1632
+ if (!requested) {
1633
+ if (!isStandardAgentsProjectDir(cwd)) {
1634
+ return { ok: false, message: "Project name is required" };
1635
+ }
1636
+ const dirName = path9.basename(cwd) || "standard-agents";
1637
+ const existingBootstrapState2 = loadBootstrapState(cwd);
1407
1638
  return {
1408
- projectName,
1409
- projectPath: cwd,
1410
- existingBootstrapState,
1411
- resumeBootstrap: existingBootstrapState !== null,
1412
- useExistingProject: true
1639
+ ok: true,
1640
+ target: {
1641
+ projectName: normalizeProjectName(dirName) || dirName,
1642
+ projectPath: cwd,
1643
+ existingBootstrapState: existingBootstrapState2,
1644
+ resumeBootstrap: existingBootstrapState2 !== null,
1645
+ useExistingProject: true
1646
+ }
1413
1647
  };
1414
1648
  }
1415
- let candidate = initialProjectName?.trim() ?? "";
1416
- let hasPromptedOnce = false;
1417
- while (true) {
1418
- if (!candidate) {
1419
- if (options.yes) {
1420
- throw new Error("Project name is required");
1421
- }
1422
- candidate = (await promptProjectName(hasPromptedOnce ? "Project name (try another): " : "Project name: ")).trim();
1423
- hasPromptedOnce = true;
1424
- continue;
1425
- }
1426
- const projectName = normalizeProjectName(candidate);
1427
- if (!projectName) {
1428
- if (options.yes) {
1429
- throw new Error("Project name must include at least one letter or number");
1430
- }
1431
- logger.warning(`Project name "${candidate}" is invalid. Use letters and numbers.`);
1432
- candidate = "";
1433
- continue;
1434
- }
1435
- if (projectName !== candidate) {
1436
- logger.info(`Using project directory "${projectName}"`);
1437
- }
1438
- const projectPath = path8.join(cwd, projectName);
1439
- const exists = fs5.existsSync(projectPath);
1440
- if (exists && !fs5.statSync(projectPath).isDirectory()) {
1441
- if (options.yes) {
1442
- throw new Error(`Path "${projectName}" already exists and is not a directory`);
1443
- }
1444
- logger.warning(`Path "${projectName}" already exists and is not a directory.`);
1445
- candidate = "";
1446
- continue;
1447
- }
1448
- const existingBootstrapState = loadBootstrapState(projectPath);
1449
- const resumeBootstrap = exists && existingBootstrapState !== null;
1450
- const existingStandardAgentsProject = exists && isStandardAgentsProjectDir(projectPath);
1451
- if (!resumeBootstrap && !existingStandardAgentsProject && isNonEmptyDirectory(projectPath)) {
1452
- if (options.yes) {
1453
- throw new Error(`Directory "${projectName}" already exists and is not empty`);
1454
- }
1455
- logger.warning(`Directory "${projectName}" already exists and is not empty.`);
1456
- candidate = "";
1457
- continue;
1458
- }
1459
- return {
1649
+ const projectName = normalizeProjectName(requested);
1650
+ if (!projectName) {
1651
+ return { ok: false, message: "Project name must include at least one letter or number" };
1652
+ }
1653
+ const projectPath = path9.join(cwd, projectName);
1654
+ const exists = fs8.existsSync(projectPath);
1655
+ if (exists && !fs8.statSync(projectPath).isDirectory()) {
1656
+ return { ok: false, message: `Path "${projectName}" already exists and is not a directory` };
1657
+ }
1658
+ const existingBootstrapState = loadBootstrapState(projectPath);
1659
+ const resumeBootstrap = exists && existingBootstrapState !== null;
1660
+ const existingStandardAgentsProject = exists && isStandardAgentsProjectDir(projectPath);
1661
+ if (!resumeBootstrap && !existingStandardAgentsProject && isNonEmptyDirectory(projectPath)) {
1662
+ return { ok: false, message: `Directory "${projectName}" already exists and is not empty` };
1663
+ }
1664
+ return {
1665
+ ok: true,
1666
+ target: {
1460
1667
  projectName,
1461
1668
  projectPath,
1462
1669
  existingBootstrapState,
1463
1670
  resumeBootstrap,
1464
1671
  useExistingProject: resumeBootstrap || existingStandardAgentsProject
1465
- };
1466
- }
1672
+ }
1673
+ };
1674
+ }
1675
+ function detectLockfilePackageManager(projectPath) {
1676
+ const has = (file) => fs8.existsSync(path9.join(projectPath, file));
1677
+ if (has("pnpm-lock.yaml")) return "pnpm";
1678
+ if (has("yarn.lock")) return "yarn";
1679
+ if (has("bun.lockb") || has("bun.lock")) return "bun";
1680
+ if (has("package-lock.json")) return "npm";
1681
+ return void 0;
1467
1682
  }
1468
1683
  function detectPackageManager() {
1469
1684
  const userAgent = process.env.npm_config_user_agent;
@@ -1472,11 +1687,7 @@ function detectPackageManager() {
1472
1687
  if (userAgent.includes("yarn")) return "yarn";
1473
1688
  if (userAgent.includes("bun")) return "bun";
1474
1689
  }
1475
- if (fs5.existsSync("pnpm-lock.yaml")) return "pnpm";
1476
- if (fs5.existsSync("yarn.lock")) return "yarn";
1477
- if (fs5.existsSync("bun.lockb")) return "bun";
1478
- if (fs5.existsSync("package-lock.json")) return "npm";
1479
- return "npm";
1690
+ return detectLockfilePackageManager(process.cwd()) ?? "npm";
1480
1691
  }
1481
1692
  function resolvePackageManager(requested, detected) {
1482
1693
  if (!requested) return detected;
@@ -1486,13 +1697,6 @@ function resolvePackageManager(requested, detected) {
1486
1697
  }
1487
1698
  throw new Error("package-manager must be npm, pnpm, yarn, or bun");
1488
1699
  }
1489
- function isInitTuiEnabled(options = {}) {
1490
- if (options.yes) return false;
1491
- if (options.cli) return false;
1492
- if (!process.stdin.isTTY || !process.stdout.isTTY) return false;
1493
- if (process.env[INIT_TUI_ENV_VAR] === "0") return false;
1494
- return true;
1495
- }
1496
1700
  function clearTerminalScreen(stdout = process.stdout) {
1497
1701
  stdout.write("\x1B[2J\x1B[H");
1498
1702
  }
@@ -1520,9 +1724,8 @@ function silenceLoggerOutput(enabled) {
1520
1724
  logger.log = original.log;
1521
1725
  };
1522
1726
  }
1523
- function renderInitStepHeader(stage, title, subtitle, options = {}) {
1524
- const mode = options.authMode ?? "standardagents";
1525
- const { step, total, labels } = getInitStepInfo(stage, mode);
1727
+ function renderInitStepHeader(stage, title, subtitle, options) {
1728
+ const { step, total, labels } = getInitStepInfo(stage, options.collectEnv);
1526
1729
  const progress = labels.map((label, index) => {
1527
1730
  const markerIndex = index + 1;
1528
1731
  if (markerIndex < step) return `\u2713 ${label}`;
@@ -1538,7 +1741,7 @@ function renderInitStepHeader(stage, title, subtitle, options = {}) {
1538
1741
  subtitle,
1539
1742
  projectName: options.projectName,
1540
1743
  packageManager: options.packageManager,
1541
- authMode: options.authMode
1744
+ collectEnv: options.collectEnv
1542
1745
  })
1543
1746
  );
1544
1747
  return;
@@ -1546,103 +1749,11 @@ function renderInitStepHeader(stage, title, subtitle, options = {}) {
1546
1749
  logger.log("");
1547
1750
  logger.log(progress);
1548
1751
  logger.info(`Step ${step}/${total}: ${title}`);
1549
- if (subtitle) {
1550
- logger.log(subtitle);
1551
- }
1752
+ logger.log(subtitle);
1552
1753
  logger.log("");
1553
1754
  }
1554
- async function selectInitAuthMode(context = {}) {
1555
- if (!process.stdin.isTTY || !process.stdout.isTTY) {
1556
- const answer = (await prompt("Setup mode: [S]tandard Agents or [L]ocal? (default: Standard Agents): ")).toLowerCase();
1557
- if (answer === "l" || answer === "local") return "local";
1558
- return "standardagents";
1559
- }
1560
- const selection = await selectInitAuthModeWithInk(context);
1561
- if (!selection) {
1562
- throw new InitWizardReturnToHomeError();
1563
- }
1564
- return selection;
1565
- }
1566
- async function ensurePlatformAuth(options, quietLogs = false, context = {}) {
1567
- const logInfo = (message) => {
1568
- if (!quietLogs) logger.info(message);
1569
- };
1570
- const logWarning = (message) => {
1571
- if (!quietLogs) logger.warning(message);
1572
- };
1573
- const logSuccess = (message) => {
1574
- if (!quietLogs) logger.success(message);
1575
- };
1576
- const logLine = (message = "") => {
1577
- if (!quietLogs) logger.log(message);
1578
- };
1579
- if (options.bootstrap?.trim()) {
1580
- logInfo("Bootstrap code provided. Project will be connected during setup.");
1581
- return { connected: true, mode: "standardagents" };
1582
- }
1583
- if (options.yes) {
1584
- logInfo('Skipping platform auth in non-interactive mode. Run "agents login --bootstrap <code>" later to connect.');
1585
- return { connected: false, mode: "local" };
1586
- }
1587
- const authMode = await selectInitAuthMode(context);
1588
- if (authMode === "local") {
1589
- logInfo('Continuing in local-only mode. Run "agents login --bootstrap <code>" anytime to connect.');
1590
- return { connected: false, mode: "local" };
1591
- }
1592
- const endpoint = resolvePlatformEndpoint(options);
1593
- let authAppUrl = resolvePlatformAuthBrowserUrl(endpoint);
1594
- let sessionId = null;
1595
- logLine("");
1596
- logInfo("Starting Standard Agents account setup...");
1597
- logLine(`Platform API: ${endpoint}`);
1598
- try {
1599
- const started = await startCliAuthSession(endpoint);
1600
- sessionId = started.session_id;
1601
- authAppUrl = started.auth_url;
1602
- logLine(`Auth app: ${authAppUrl}`);
1603
- logLine("");
1604
- logLine("Complete login/signup in your browser. This window is waiting for realtime confirmation...");
1605
- if (process.stdin.isTTY) {
1606
- const opened = openBrowser(authAppUrl);
1607
- if (opened) {
1608
- logInfo("Opened browser for authentication.");
1609
- } else {
1610
- logWarning("Could not automatically open browser. Open the URL above manually.");
1611
- }
1612
- }
1613
- try {
1614
- const completion = await waitForCliAuthCompletion(started.ws_url, started.expires_at);
1615
- options.bootstrap = completion.bootstrapCode;
1616
- logSuccess("Authentication received from browser.");
1617
- return { connected: true, mode: "standardagents" };
1618
- } catch (error) {
1619
- const message = error instanceof Error ? error.message : "Realtime auth handoff failed";
1620
- logWarning(`${message} Switching to manual bootstrap command entry.`);
1621
- }
1622
- } catch (error) {
1623
- const message = error instanceof Error ? error.message : "Failed to start realtime auth session";
1624
- logWarning(`${message} Switching to manual bootstrap command entry.`);
1625
- logLine(`Auth app: ${authAppUrl}`);
1626
- }
1627
- logLine("");
1628
- const pasted = await prompt("Paste bootstrap code or full command (Enter to continue local-only): ");
1629
- const bootstrapCode = parseBootstrapCodeInput(pasted);
1630
- if (!bootstrapCode) {
1631
- if (sessionId) {
1632
- await cancelCliAuthSession(endpoint, sessionId);
1633
- }
1634
- logInfo("No bootstrap code provided. Continuing in local-only mode.");
1635
- return { connected: false, mode: "local" };
1636
- }
1637
- if (sessionId) {
1638
- await cancelCliAuthSession(endpoint, sessionId);
1639
- }
1640
- options.bootstrap = bootstrapCode;
1641
- logSuccess("Bootstrap code captured.");
1642
- return { connected: true, mode: "standardagents" };
1643
- }
1644
1755
  function getCliVersion() {
1645
- return "0.45.2";
1756
+ return "0.45.3";
1646
1757
  }
1647
1758
  function getSipVersion() {
1648
1759
  return "1.0.1";
@@ -1671,8 +1782,8 @@ function resolveStandardAgentsPackageSpecifier(packageName, packageSpecifier) {
1671
1782
  return packageSpecifier;
1672
1783
  }
1673
1784
  function rewriteStandardAgentsDependenciesForWorkspace(projectPath, workspaceRoot) {
1674
- const packageJsonPath = path8.join(projectPath, "package.json");
1675
- const packageJson = JSON.parse(fs5.readFileSync(packageJsonPath, "utf-8"));
1785
+ const packageJsonPath = path9.join(projectPath, "package.json");
1786
+ const packageJson = JSON.parse(fs8.readFileSync(packageJsonPath, "utf-8"));
1676
1787
  const dependencies = packageJson.dependencies ?? {};
1677
1788
  const linkedPackages = [];
1678
1789
  for (const packageName of GENERATED_STANDARD_AGENTS_PACKAGES) {
@@ -1684,7 +1795,7 @@ function rewriteStandardAgentsDependenciesForWorkspace(projectPath, workspaceRoo
1684
1795
  }
1685
1796
  if (linkedPackages.length > 0) {
1686
1797
  packageJson.dependencies = dependencies;
1687
- fs5.writeFileSync(packageJsonPath, `${JSON.stringify(packageJson, null, 2)}
1798
+ fs8.writeFileSync(packageJsonPath, `${JSON.stringify(packageJson, null, 2)}
1688
1799
  `, "utf-8");
1689
1800
  }
1690
1801
  return linkedPackages;
@@ -1705,7 +1816,7 @@ function preparePlatformProjectDependencies(projectPath, packageManager, options
1705
1816
  return linkedPackages;
1706
1817
  }
1707
1818
  function getPnpmWorkspaceCompatibilityArgs(packageManager, projectPath) {
1708
- if (packageManager !== "pnpm" || !fs5.existsSync(path8.join(projectPath, "pnpm-workspace.yaml"))) return [];
1819
+ if (packageManager !== "pnpm" || !fs8.existsSync(path9.join(projectPath, "pnpm-workspace.yaml"))) return [];
1709
1820
  try {
1710
1821
  childProcess.execFileSync("pnpm", ["config", "get", "registry"], {
1711
1822
  cwd: projectPath,
@@ -1723,8 +1834,8 @@ function getPnpmWorkspaceCompatibilityArgs(packageManager, projectPath) {
1723
1834
  }
1724
1835
  }
1725
1836
  function projectInstallArgs(packageManager, projectPath, command = "install", dependencies = [], options = {}) {
1726
- const hasProjectWorkspace = projectPath !== void 0 && fs5.existsSync(path8.join(projectPath, "pnpm-workspace.yaml"));
1727
- const inheritsWorkspace = !options.isolateFromParent && projectPath !== void 0 && findPnpmWorkspaceRoot(path8.dirname(projectPath)) !== null;
1837
+ const hasProjectWorkspace = projectPath !== void 0 && fs8.existsSync(path9.join(projectPath, "pnpm-workspace.yaml"));
1838
+ const inheritsWorkspace = !options.isolateFromParent && projectPath !== void 0 && findPnpmWorkspaceRoot(path9.dirname(projectPath)) !== null;
1728
1839
  const prefix = [];
1729
1840
  if (packageManager === "pnpm") {
1730
1841
  if (options.ignoreProjectWorkspace) prefix.push("--ignore-workspace");
@@ -1737,19 +1848,19 @@ function shellQuote(value) {
1737
1848
  return `"${value.replace(/(["\\$`])/g, "\\$1")}"`;
1738
1849
  }
1739
1850
  function findWorkspaceCommandRoot(projectPath) {
1740
- let current = path8.dirname(projectPath);
1851
+ let current = path9.dirname(projectPath);
1741
1852
  while (true) {
1742
- const packageJsonPath = path8.join(current, "package.json");
1743
- if (fs5.existsSync(packageJsonPath)) {
1853
+ const packageJsonPath = path9.join(current, "package.json");
1854
+ if (fs8.existsSync(packageJsonPath)) {
1744
1855
  try {
1745
- const packageJson = JSON.parse(fs5.readFileSync(packageJsonPath, "utf-8"));
1856
+ const packageJson = JSON.parse(fs8.readFileSync(packageJsonPath, "utf-8"));
1746
1857
  if (packageJson?.scripts && typeof packageJson.scripts["sandbox:hmr"] === "string") {
1747
1858
  return current;
1748
1859
  }
1749
1860
  } catch {
1750
1861
  }
1751
1862
  }
1752
- const parent = path8.dirname(current);
1863
+ const parent = path9.dirname(current);
1753
1864
  if (parent === current) {
1754
1865
  return null;
1755
1866
  }
@@ -1757,47 +1868,47 @@ function findWorkspaceCommandRoot(projectPath) {
1757
1868
  }
1758
1869
  }
1759
1870
  function linkWorkspaceProjectToolchain(projectPath, workspaceRoot) {
1760
- const packageJsonPath = path8.join(projectPath, "package.json");
1761
- const manifest = JSON.parse(fs5.readFileSync(packageJsonPath, "utf8"));
1871
+ const packageJsonPath = path9.join(projectPath, "package.json");
1872
+ const manifest = JSON.parse(fs8.readFileSync(packageJsonPath, "utf8"));
1762
1873
  for (const section of [manifest.dependencies, manifest.devDependencies]) {
1763
1874
  if (!section) continue;
1764
1875
  for (const name of ["vite", "typescript"]) {
1765
1876
  if (!(name in section)) continue;
1766
- const installedPath = path8.join(workspaceRoot, "node_modules", name);
1767
- if (!fs5.existsSync(path8.join(installedPath, "package.json"))) {
1877
+ const installedPath = path9.join(workspaceRoot, "node_modules", name);
1878
+ if (!fs8.existsSync(path9.join(installedPath, "package.json"))) {
1768
1879
  throw new Error(`Install the contributor workspace before linking ${name}`);
1769
1880
  }
1770
1881
  section[name] = `link:${installedPath}`;
1771
1882
  }
1772
1883
  }
1773
- fs5.writeFileSync(packageJsonPath, `${JSON.stringify(manifest, null, 2)}
1884
+ fs8.writeFileSync(packageJsonPath, `${JSON.stringify(manifest, null, 2)}
1774
1885
  `);
1775
1886
  }
1776
1887
  function configureWorkspaceProjectScripts(projectPath, projectName) {
1777
- const packageJsonPath = path8.join(projectPath, "package.json");
1778
- if (!fs5.existsSync(packageJsonPath)) return false;
1888
+ const packageJsonPath = path9.join(projectPath, "package.json");
1889
+ if (!fs8.existsSync(packageJsonPath)) return false;
1779
1890
  const workspaceRoot = findWorkspaceCommandRoot(projectPath);
1780
1891
  if (!workspaceRoot) return false;
1781
- const workspacePackageJsonPath = path8.join(workspaceRoot, "package.json");
1782
- const workspacePackageJson = JSON.parse(fs5.readFileSync(workspacePackageJsonPath, "utf-8"));
1783
- const packageJson = JSON.parse(fs5.readFileSync(packageJsonPath, "utf-8"));
1892
+ const workspacePackageJsonPath = path9.join(workspaceRoot, "package.json");
1893
+ const workspacePackageJson = JSON.parse(fs8.readFileSync(workspacePackageJsonPath, "utf-8"));
1894
+ const packageJson = JSON.parse(fs8.readFileSync(packageJsonPath, "utf-8"));
1784
1895
  const scripts = packageJson.scripts && typeof packageJson.scripts === "object" ? packageJson.scripts : {};
1785
- const relativeRoot = path8.relative(projectPath, workspaceRoot) || ".";
1896
+ const relativeRoot = path9.relative(projectPath, workspaceRoot) || ".";
1786
1897
  scripts["sandbox:hmr"] = `pnpm -C ${shellQuote(relativeRoot)} sandbox:hmr -- ${shellQuote(projectName)}`;
1787
1898
  if (workspacePackageJson?.scripts && typeof workspacePackageJson.scripts["cli:login:workspace"] === "string") {
1788
1899
  scripts["cli:login:workspace"] = `pnpm -C ${shellQuote(relativeRoot)} cli:login:workspace -- ${shellQuote(projectName)}`;
1789
1900
  }
1790
1901
  packageJson.scripts = scripts;
1791
- fs5.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2) + "\n", "utf-8");
1902
+ fs8.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2) + "\n", "utf-8");
1792
1903
  return true;
1793
1904
  }
1794
1905
  function resolvePostInitRunCommand(packageManager, projectPath, workspacePackages, pnpmCompatibilityArgs = []) {
1795
1906
  const command = packageManager === "pnpm" ? [packageManager, ...pnpmCompatibilityArgs].join(" ") : packageManager;
1796
1907
  if (workspacePackages) {
1797
- const packageJsonPath = path8.join(projectPath, "package.json");
1798
- if (fs5.existsSync(packageJsonPath)) {
1908
+ const packageJsonPath = path9.join(projectPath, "package.json");
1909
+ if (fs8.existsSync(packageJsonPath)) {
1799
1910
  try {
1800
- const packageJson = JSON.parse(fs5.readFileSync(packageJsonPath, "utf-8"));
1911
+ const packageJson = JSON.parse(fs8.readFileSync(packageJsonPath, "utf-8"));
1801
1912
  if (packageJson?.scripts && typeof packageJson.scripts["sandbox:hmr"] === "string") {
1802
1913
  return packageManager === "npm" ? "npm run sandbox:hmr" : `${command} sandbox:hmr`;
1803
1914
  }
@@ -1807,14 +1918,6 @@ function resolvePostInitRunCommand(packageManager, projectPath, workspacePackage
1807
1918
  }
1808
1919
  return packageManager === "npm" ? "npm run dev" : `${command} dev`;
1809
1920
  }
1810
- async function selectPackageManager(detected, context = {}) {
1811
- if (!process.stdin.isTTY || !process.stdout.isTTY) return detected;
1812
- const selection = await selectPackageManagerWithInk(detected, context);
1813
- if (!selection) {
1814
- throw new InitWizardReturnToHomeError();
1815
- }
1816
- return selection;
1817
- }
1818
1921
  function resolvePlatformEndpoint(options) {
1819
1922
  return options.endpoint || options.apiUrl || process.env.PLATFORM_ENDPOINT || DEFAULT_PLATFORM_ENDPOINT;
1820
1923
  }
@@ -1920,6 +2023,11 @@ async function prepareBootstrapSession(projectPath, options, fetchImpl = fetch)
1920
2023
  function normalizeApiUrl(input) {
1921
2024
  return (input || process.env.STANDARD_AGENTS_API_URL || process.env.PLATFORM_ENDPOINT || process.env.STANDARD_AGENTS_PLATFORM_URL || DEFAULT_PLATFORM_ENDPOINT).replace(/\/+$/, "");
1922
2025
  }
2026
+ function networkErrorCode(error) {
2027
+ const cause = error instanceof Error ? error.cause : void 0;
2028
+ const code = cause !== null && typeof cause === "object" && "code" in cause ? cause.code : void 0;
2029
+ return typeof code === "string" ? ` (${code})` : "";
2030
+ }
1923
2031
  async function startPlatformCliSession(params) {
1924
2032
  const body = {
1925
2033
  machine_name: os3.hostname(),
@@ -1938,12 +2046,16 @@ async function startPlatformCliSession(params) {
1938
2046
  });
1939
2047
  } catch (error) {
1940
2048
  throw new Error(
1941
- `Could not reach the Standard Agents platform at ${params.endpoint}: ${error instanceof Error ? error.message : String(error)}`
2049
+ `Could not reach the Standard Agents platform at ${params.endpoint}: ${error instanceof Error ? error.message : String(error)}${networkErrorCode(error)}
2050
+ Check your internet connection, then run: ${INIT_COMMAND}`
1942
2051
  );
1943
2052
  }
1944
2053
  if (!response.ok) {
1945
2054
  const bodyText = await response.text().catch(() => "");
1946
- throw new Error(`Platform auth failed to start (${response.status})${bodyText ? `: ${bodyText}` : ""}`);
2055
+ throw new Error(
2056
+ `The Standard Agents platform could not start sign-in (${response.status})${bodyText ? `: ${bodyText}` : ""}
2057
+ Wait a minute, then run: ${INIT_COMMAND}`
2058
+ );
1947
2059
  }
1948
2060
  return response.json();
1949
2061
  }
@@ -1979,8 +2091,8 @@ function gitCloneArgs(project, projectName) {
1979
2091
  return args;
1980
2092
  }
1981
2093
  function platformGitCredentialHelperCommand(cliEntry = process.argv[1] ?? "") {
1982
- if (process.env.STANDARDAGENTS_WORKSPACE === "1" && cliEntry && fs5.existsSync(cliEntry)) {
1983
- return `!node ${shellQuote(path8.resolve(cliEntry))} git-credential`;
2094
+ if (process.env.STANDARDAGENTS_WORKSPACE === "1" && cliEntry && fs8.existsSync(cliEntry)) {
2095
+ return `!node ${shellQuote(path9.resolve(cliEntry))} git-credential`;
1984
2096
  }
1985
2097
  if (process.env.STANDARD_AGENTS_GIT_HELPER?.trim()) {
1986
2098
  return process.env.STANDARD_AGENTS_GIT_HELPER.trim();
@@ -2001,19 +2113,28 @@ function isRetryablePlatformAuthStatus(status) {
2001
2113
  return status === 502 || status === 503 || status === 504;
2002
2114
  }
2003
2115
  async function readPlatformProjectStatus(statusUrl, options = {}) {
2116
+ const signal = options.signal;
2117
+ const throwIfAborted = () => {
2118
+ if (signal?.aborted) throw new PlatformWaitAbortedError();
2119
+ };
2120
+ throwIfAborted();
2004
2121
  let response;
2005
2122
  try {
2006
2123
  response = await fetch(statusUrl, {
2007
- headers: { Accept: "application/json" }
2124
+ headers: { Accept: "application/json" },
2125
+ signal
2008
2126
  });
2009
2127
  } catch {
2128
+ throwIfAborted();
2010
2129
  return null;
2011
2130
  }
2131
+ throwIfAborted();
2012
2132
  if (!response.ok) {
2013
2133
  if (isRetryablePlatformAuthStatus(response.status)) return null;
2014
2134
  throw new Error(`Platform auth status failed (${response.status})`);
2015
2135
  }
2016
2136
  const status = await response.json();
2137
+ throwIfAborted();
2017
2138
  if (status.progress?.message) {
2018
2139
  options.onProgress?.(status.progress);
2019
2140
  }
@@ -2024,10 +2145,10 @@ async function readPlatformProjectStatus(statusUrl, options = {}) {
2024
2145
  throw new Error(LEGACY_BOOTSTRAP_RESPONSE_MESSAGE);
2025
2146
  }
2026
2147
  if (status.status === "expired") {
2027
- throw new Error("Onboarding session expired. Run the init command again to start a new session.");
2148
+ throw new Error(SESSION_EXPIRED_MESSAGE);
2028
2149
  }
2029
2150
  if (status.status === "cancelled") {
2030
- throw new Error("Onboarding was cancelled in the browser. Run the init command again when you are ready.");
2151
+ throw new Error(SESSION_CANCELLED_MESSAGE);
2031
2152
  }
2032
2153
  return null;
2033
2154
  }
@@ -2036,6 +2157,10 @@ var PLATFORM_AUTH_SILENCE_LIMIT_MS = 75e3;
2036
2157
  var PLATFORM_AUTH_RECONNECT_DELAYS_MS = [1e3, 2e3, 5e3, 1e4];
2037
2158
  function waitForPlatformProjectWs(wsUrl, expiresAt, options = {}) {
2038
2159
  return new Promise((resolve, reject) => {
2160
+ if (options.signal?.aborted) {
2161
+ reject(new PlatformWaitAbortedError());
2162
+ return;
2163
+ }
2039
2164
  const WebSocketCtor = globalThis.WebSocket;
2040
2165
  if (!WebSocketCtor) {
2041
2166
  reject(new Error("This Node.js runtime does not provide WebSocket support. Use Node.js 22 or newer."));
@@ -2059,7 +2184,7 @@ function waitForPlatformProjectWs(wsUrl, expiresAt, options = {}) {
2059
2184
  settled = true;
2060
2185
  clearInterval(keepalive);
2061
2186
  socket.close();
2062
- reject(new Error("Timed out waiting for platform project creation"));
2187
+ reject(new Error(SESSION_EXPIRED_MESSAGE));
2063
2188
  }, Math.max(1e3, expiresAt - Date.now()));
2064
2189
  const settle = (fn) => {
2065
2190
  if (settled) return;
@@ -2069,6 +2194,9 @@ function waitForPlatformProjectWs(wsUrl, expiresAt, options = {}) {
2069
2194
  socket.close();
2070
2195
  fn();
2071
2196
  };
2197
+ options.signal?.addEventListener("abort", () => {
2198
+ settle(() => reject(new PlatformWaitAbortedError()));
2199
+ }, { once: true });
2072
2200
  socket.addEventListener("open", () => {
2073
2201
  try {
2074
2202
  socket.send(JSON.stringify({ type: "ready" }));
@@ -2121,7 +2249,7 @@ function waitForPlatformProjectWs(wsUrl, expiresAt, options = {}) {
2121
2249
  settle(() => resolve(project));
2122
2250
  } else if (message.type === "expired" || message.type === "cancelled") {
2123
2251
  settle(() => reject(new Error(
2124
- message.type === "expired" ? "Onboarding session expired. Run the init command again to start a new session." : "Onboarding was cancelled in the browser. Run the init command again when you are ready."
2252
+ message.type === "expired" ? SESSION_EXPIRED_MESSAGE : SESSION_CANCELLED_MESSAGE
2125
2253
  )));
2126
2254
  } else if (message.command || message.bootstrap_code) {
2127
2255
  settle(() => reject(new Error(LEGACY_BOOTSTRAP_RESPONSE_MESSAGE)));
@@ -2135,10 +2263,13 @@ function waitForPlatformProjectWs(wsUrl, expiresAt, options = {}) {
2135
2263
  });
2136
2264
  });
2137
2265
  }
2138
- async function waitForPlatformProject(session, onProgress) {
2266
+ async function waitForPlatformProject(session, onProgress, signal) {
2139
2267
  if (!session.ws_url) {
2140
2268
  throw new Error("Platform auth session provided no ws_url");
2141
2269
  }
2270
+ const throwIfAborted = () => {
2271
+ if (signal?.aborted) throw new PlatformWaitAbortedError();
2272
+ };
2142
2273
  let lastProgressKey = "";
2143
2274
  const reportProgress = (progress) => {
2144
2275
  const progressKey = `${progress.status}:${progress.message}:${progress.updated_at}`;
@@ -2149,52 +2280,48 @@ async function waitForPlatformProject(session, onProgress) {
2149
2280
  let statusReadDue = true;
2150
2281
  let failedAttempts = 0;
2151
2282
  while (Date.now() < session.expires_at) {
2283
+ throwIfAborted();
2152
2284
  try {
2153
- return await waitForPlatformProjectWs(session.ws_url, session.expires_at, {
2285
+ const project = await waitForPlatformProjectWs(session.ws_url, session.expires_at, {
2154
2286
  onProgress: reportProgress,
2155
2287
  onOpen: () => {
2156
2288
  statusReadDue = true;
2157
2289
  failedAttempts = 0;
2158
- }
2290
+ },
2291
+ signal
2159
2292
  });
2293
+ throwIfAborted();
2294
+ return project;
2160
2295
  } catch (error) {
2296
+ throwIfAborted();
2161
2297
  if (!(error instanceof PlatformAuthWsTransportError)) throw error;
2162
2298
  }
2163
2299
  if (statusReadDue && session.status_url && Date.now() < session.expires_at) {
2164
2300
  statusReadDue = false;
2165
- const project = await readPlatformProjectStatus(session.status_url, { onProgress: reportProgress });
2301
+ const project = await readPlatformProjectStatus(session.status_url, { onProgress: reportProgress, signal });
2166
2302
  if (project) return project;
2167
2303
  }
2168
2304
  const delay = PLATFORM_AUTH_RECONNECT_DELAYS_MS[Math.min(failedAttempts, PLATFORM_AUTH_RECONNECT_DELAYS_MS.length - 1)];
2169
2305
  failedAttempts += 1;
2170
2306
  await sleep(Math.min(delay, Math.max(0, session.expires_at - Date.now())));
2171
2307
  }
2172
- throw new Error("Timed out waiting for platform project creation");
2173
- }
2174
- function upsertEnvLine(lines, key, value) {
2175
- return [
2176
- ...lines.filter((line) => !line.startsWith(`${key}=`)),
2177
- `${key}=${value}`
2178
- ];
2179
- }
2180
- function hasEnvLine(lines, key) {
2181
- return lines.some((line) => line.startsWith(`${key}=`));
2308
+ throw new Error(SESSION_EXPIRED_MESSAGE);
2182
2309
  }
2183
2310
  function appendGitignoreEntries(projectPath, heading, entries) {
2184
- const gitignorePath = path8.join(projectPath, ".gitignore");
2185
- const gitignoreContent = fs5.existsSync(gitignorePath) ? fs5.readFileSync(gitignorePath, "utf-8") : "";
2311
+ const gitignorePath = path9.join(projectPath, ".gitignore");
2312
+ const gitignoreContent = fs8.existsSync(gitignorePath) ? fs8.readFileSync(gitignorePath, "utf-8") : "";
2186
2313
  const existingEntries = new Set(gitignoreContent.split(/\r?\n/));
2187
2314
  const missingEntries = entries.filter((entry) => !existingEntries.has(entry));
2188
2315
  if (missingEntries.length === 0) return;
2189
2316
  const prefix = gitignoreContent.length === 0 ? "" : gitignoreContent.endsWith("\n") ? "\n" : "\n\n";
2190
- fs5.appendFileSync(gitignorePath, `${prefix}${heading}
2317
+ fs8.appendFileSync(gitignorePath, `${prefix}${heading}
2191
2318
  ${missingEntries.join("\n")}
2192
2319
  `);
2193
2320
  }
2194
2321
  function writeLocalPnpmBuildPolicy(projectPath, packageManager, options = {}) {
2195
2322
  if (packageManager !== "pnpm") return false;
2196
- const policyPath = path8.join(projectPath, "pnpm-workspace.yaml");
2197
- if (fs5.existsSync(policyPath)) return false;
2323
+ const policyPath = path9.join(projectPath, "pnpm-workspace.yaml");
2324
+ if (fs8.existsSync(policyPath)) return false;
2198
2325
  const buildPolicySettings = [
2199
2326
  "onlyBuiltDependencies",
2200
2327
  "onlyBuiltDependenciesFile",
@@ -2205,20 +2332,20 @@ function writeLocalPnpmBuildPolicy(projectPath, packageManager, options = {}) {
2205
2332
  "ignoreDepScripts",
2206
2333
  "ignoreScripts"
2207
2334
  ];
2208
- const npmrcPath = path8.join(projectPath, ".npmrc");
2209
- if (fs5.existsSync(npmrcPath)) {
2210
- const hasBuildPolicy = fs5.readFileSync(npmrcPath, "utf8").split(/\r?\n/).some((line) => {
2335
+ const npmrcPath = path9.join(projectPath, ".npmrc");
2336
+ if (fs8.existsSync(npmrcPath)) {
2337
+ const hasBuildPolicy = fs8.readFileSync(npmrcPath, "utf8").split(/\r?\n/).some((line) => {
2211
2338
  const separator = line.indexOf("=");
2212
2339
  const name = (separator < 0 ? line : line.slice(0, separator)).trim().replace(/[-_[\]]/g, "").toLowerCase();
2213
2340
  return buildPolicySettings.some((setting) => setting.toLowerCase() === name);
2214
2341
  });
2215
2342
  if (hasBuildPolicy) return false;
2216
2343
  }
2217
- if (!options.isolateFromParent && findPnpmWorkspaceRoot(path8.dirname(projectPath))) return false;
2344
+ if (!options.isolateFromParent && findPnpmWorkspaceRoot(path9.dirname(projectPath))) return false;
2218
2345
  const ignoredBuildScripts = options.ignoredBuildScripts ?? [];
2219
2346
  const approvedBuildScripts = ["esbuild", "workerd"].filter((name) => !ignoredBuildScripts.includes(name));
2220
- const manifestPath = path8.join(projectPath, "package.json");
2221
- const manifest = JSON.parse(fs5.readFileSync(manifestPath, "utf8"));
2347
+ const manifestPath = path9.join(projectPath, "package.json");
2348
+ const manifest = JSON.parse(fs8.readFileSync(manifestPath, "utf8"));
2222
2349
  const existingPnpm = manifest.pnpm ?? {};
2223
2350
  if (buildPolicySettings.some((name) => Object.hasOwn(existingPnpm, name))) return false;
2224
2351
  manifest.pnpm = {
@@ -2226,9 +2353,9 @@ function writeLocalPnpmBuildPolicy(projectPath, packageManager, options = {}) {
2226
2353
  onlyBuiltDependencies: approvedBuildScripts,
2227
2354
  ...ignoredBuildScripts.length > 0 ? { ignoredBuiltDependencies: ignoredBuildScripts } : {}
2228
2355
  };
2229
- fs5.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}
2356
+ fs8.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}
2230
2357
  `);
2231
- fs5.writeFileSync(policyPath, renderPnpmWorkspaceYaml(approvedBuildScripts, ignoredBuildScripts));
2358
+ fs8.writeFileSync(policyPath, renderPnpmWorkspaceYaml(approvedBuildScripts, ignoredBuildScripts));
2232
2359
  return true;
2233
2360
  }
2234
2361
  function writeStandardAgentsSupportFiles(projectPath, params) {
@@ -2241,10 +2368,10 @@ function writeStandardAgentsSupportFiles(projectPath, params) {
2241
2368
  sip: getSipVersion()
2242
2369
  }
2243
2370
  })) {
2244
- const targetPath = path8.join(projectPath, supportFile.path);
2245
- if (fs5.existsSync(targetPath)) continue;
2246
- fs5.mkdirSync(path8.dirname(targetPath), { recursive: true });
2247
- fs5.writeFileSync(targetPath, supportFile.content, "utf-8");
2371
+ const targetPath = path9.join(projectPath, supportFile.path);
2372
+ if (fs8.existsSync(targetPath)) continue;
2373
+ fs8.mkdirSync(path9.dirname(targetPath), { recursive: true });
2374
+ fs8.writeFileSync(targetPath, supportFile.content, "utf-8");
2248
2375
  written.push(supportFile.path);
2249
2376
  }
2250
2377
  appendGitignoreEntries(projectPath, "# Standard Agents local dev state", [
@@ -2265,7 +2392,7 @@ function supportFiles(options = {}) {
2265
2392
  process.exit(1);
2266
2393
  }
2267
2394
  const cwd = process.cwd();
2268
- const projectName = normalizeProjectName(options.projectName ?? path8.basename(cwd)) || "standard-agents";
2395
+ const projectName = normalizeProjectName(options.projectName ?? path9.basename(cwd)) || "standard-agents";
2269
2396
  const written = writeStandardAgentsSupportFiles(cwd, {
2270
2397
  projectName,
2271
2398
  packageManager
@@ -2277,33 +2404,24 @@ function supportFiles(options = {}) {
2277
2404
  logger.success(`Wrote Standard Agents local support files: ${written.join(", ")}`);
2278
2405
  }
2279
2406
  function writeStandardAgentsEnv(projectPath, params) {
2280
- const envPath = path8.join(projectPath, ".dev.vars");
2281
- const existing = fs5.existsSync(envPath) ? fs5.readFileSync(envPath, "utf-8") : "";
2282
- let lines = existing.split(/\r?\n/).filter(
2283
- (line) => line.trim().length > 0 && !line.startsWith("STANDARD_AGENTS_API_KEY=") && !line.startsWith("PLATFORM_ENDPOINT=") && !line.startsWith("STANDARD_AGENTS_API_URL=")
2284
- );
2285
- const needsEncryptionKey = !hasEnvLine(lines, "ENCRYPTION_KEY");
2286
- const needsAdminPassword = !hasEnvLine(lines, "SUPER_ADMIN_PASSWORD");
2287
- if (needsEncryptionKey || needsAdminPassword) {
2288
- if (lines.length > 0) {
2289
- lines.push("");
2290
- }
2291
- lines.push("# Local admin access");
2292
- if (needsEncryptionKey) {
2293
- lines.push(`ENCRYPTION_KEY=${crypto.randomBytes(32).toString("hex")}`);
2294
- }
2295
- if (needsAdminPassword) {
2296
- lines.push("SUPER_ADMIN_PASSWORD=password");
2297
- }
2298
- }
2299
- if (lines.length > 0) {
2300
- lines.push("");
2301
- }
2302
- lines.push("# Standard Agents platform connection");
2303
- lines = upsertEnvLine(lines, "STANDARD_AGENTS_API_KEY", params.apiKey);
2304
- lines = upsertEnvLine(lines, "PLATFORM_ENDPOINT", params.platformEndpoint);
2305
- lines = upsertEnvLine(lines, "STANDARD_AGENTS_API_URL", params.platformEndpoint);
2306
- fs5.writeFileSync(envPath, lines.join("\n").replace(/\n{3,}/g, "\n\n").trim() + "\n", "utf-8");
2407
+ let devVars = removeDevVars(
2408
+ withoutLegacyDefaultAdminPassword(readDevVarsFile(projectPath)),
2409
+ ["STANDARD_AGENTS_API_KEY", "PLATFORM_ENDPOINT", "STANDARD_AGENTS_API_URL"]
2410
+ ).trimEnd();
2411
+ const section = (heading) => `${devVars}${devVars ? "\n\n" : ""}# ${heading}
2412
+ `;
2413
+ if (!readDevVar(devVars, "ENCRYPTION_KEY")) {
2414
+ devVars = setDevVar(
2415
+ section("Local session and data encryption"),
2416
+ "ENCRYPTION_KEY",
2417
+ crypto2.randomBytes(32).toString("hex")
2418
+ ).trimEnd();
2419
+ }
2420
+ devVars = section("Standard Agents platform connection");
2421
+ devVars = setDevVar(devVars, "STANDARD_AGENTS_API_KEY", params.apiKey);
2422
+ devVars = setDevVar(devVars, "PLATFORM_ENDPOINT", params.platformEndpoint);
2423
+ devVars = setDevVar(devVars, "STANDARD_AGENTS_API_URL", params.platformEndpoint);
2424
+ const envPath = writeDevVarsFile(projectPath, collapseBlankLines(devVars));
2307
2425
  appendGitignoreEntries(projectPath, "# Standard Agents local platform token", [".dev.vars"]);
2308
2426
  return envPath;
2309
2427
  }
@@ -2327,6 +2445,9 @@ async function resolveBootstrapProject(endpoint, code, fetchImpl = fetch) {
2327
2445
  const consumed = await exchangeBootstrapCode(endpoint, code, fetchImpl);
2328
2446
  const cookie = consumed.session_cookie;
2329
2447
  const projectId = consumed.project?.id ?? await findFirstProjectId(endpoint, cookie, fetchImpl);
2448
+ return requestCliHandoff(endpoint, projectId, cookie, fetchImpl);
2449
+ }
2450
+ async function requestCliHandoff(endpoint, projectId, cookie, fetchImpl = fetch) {
2330
2451
  const handoffResponse = await fetchImpl(`${endpoint}/projects/${encodeURIComponent(projectId)}/cli-handoff`, {
2331
2452
  method: "POST",
2332
2453
  headers: { Accept: "application/json", "Content-Type": "application/json", Cookie: cookie },
@@ -2342,6 +2463,88 @@ async function resolveBootstrapProject(endpoint, code, fetchImpl = fetch) {
2342
2463
  }
2343
2464
  return handoffBody.project;
2344
2465
  }
2466
+ function exitWithInitFailure(failure) {
2467
+ const [headline, ...detail] = failure.cause.split("\n");
2468
+ logger.error(headline);
2469
+ for (const line of [...detail, ...failure.next]) {
2470
+ logger.log(line);
2471
+ }
2472
+ process.exit(1);
2473
+ }
2474
+ function failureFromError(error) {
2475
+ const message = error instanceof Error ? error.message : String(error);
2476
+ return {
2477
+ cause: message,
2478
+ next: message.includes("\n") ? [] : [`Run the command again: ${INIT_COMMAND}`]
2479
+ };
2480
+ }
2481
+ function isGitInstalled() {
2482
+ const result = childProcess.spawnSync("git", ["--version"], { stdio: "ignore" });
2483
+ return !result.error && result.status === 0;
2484
+ }
2485
+ function browserOrigin(url) {
2486
+ try {
2487
+ return new URL(url).origin;
2488
+ } catch {
2489
+ return void 0;
2490
+ }
2491
+ }
2492
+ async function cancelPlatformSession(endpoint, sessionId) {
2493
+ await Promise.race([cancelCliAuthSession(endpoint, sessionId), sleep(3e3)]);
2494
+ }
2495
+ async function createProjectThroughBrowser(params) {
2496
+ for (const line of ACCOUNT_STEP_LINES) {
2497
+ logger.info(line);
2498
+ }
2499
+ let session;
2500
+ try {
2501
+ session = await startPlatformCliSession({
2502
+ endpoint: params.endpoint,
2503
+ projectName: params.projectName,
2504
+ packageManager: params.packageManager
2505
+ });
2506
+ } catch (error) {
2507
+ exitWithInitFailure(failureFromError(error));
2508
+ }
2509
+ logger.log("");
2510
+ logger.log(`Sign-in URL: ${session.auth_url}`);
2511
+ logger.log("");
2512
+ if (params.skipBrowserOpen) {
2513
+ logger.info("Open the sign-in URL in a browser to continue.");
2514
+ } else {
2515
+ openUrl(session.auth_url);
2516
+ logger.info("Opening your browser. If it does not open, use the sign-in URL above.");
2517
+ }
2518
+ const indicator = startWaitIndicator({
2519
+ label: "Waiting for you to finish in the browser",
2520
+ expiresAt: session.expires_at,
2521
+ log: logger.info
2522
+ });
2523
+ const waitAbort = new AbortController();
2524
+ const stopCancelOnInterrupt = interrupts.onInterrupt(async () => {
2525
+ waitAbort.abort();
2526
+ indicator.stop();
2527
+ await cancelPlatformSession(params.endpoint, session.session_id);
2528
+ logger.info(`Sign-in cancelled. Start again when you are ready: ${INIT_COMMAND}`);
2529
+ });
2530
+ let project;
2531
+ try {
2532
+ project = await waitForPlatformProject(
2533
+ session,
2534
+ (progress) => indicator.note(progress.message),
2535
+ waitAbort.signal
2536
+ );
2537
+ } catch (error) {
2538
+ if (interrupts.isInterrupted()) return parkUntilExit();
2539
+ indicator.stop();
2540
+ stopCancelOnInterrupt();
2541
+ exitWithInitFailure(failureFromError(error));
2542
+ }
2543
+ if (interrupts.isInterrupted()) return parkUntilExit();
2544
+ indicator.stop();
2545
+ stopCancelOnInterrupt();
2546
+ return { project, dashboardUrl: browserOrigin(session.auth_url) };
2547
+ }
2345
2548
  async function runPlatformInit(projectNameArg, options) {
2346
2549
  const cwd = process.cwd();
2347
2550
  let pm;
@@ -2352,81 +2555,137 @@ async function runPlatformInit(projectNameArg, options) {
2352
2555
  process.exit(1);
2353
2556
  }
2354
2557
  const requestedProjectName = projectNameArg?.trim() || void 0;
2355
- if (requestedProjectName && fs5.existsSync(path8.join(cwd, requestedProjectName))) {
2356
- logger.error(`Directory "${requestedProjectName}" already exists`);
2357
- process.exit(1);
2558
+ if (requestedProjectName && fs8.existsSync(path9.join(cwd, requestedProjectName))) {
2559
+ exitWithInitFailure(directoryExistsFailure(requestedProjectName));
2358
2560
  }
2359
2561
  const endpoint = normalizeApiUrl(options.apiUrl || options.endpoint);
2562
+ const bootstrapCode = options.bootstrap?.trim();
2563
+ const skipBrowserOpen = options.open === false || shouldSkipBrowserOpen(preferredBrowser());
2564
+ const waitsWithoutTerminal = skipBrowserOpen || process.env.STANDARD_AGENTS_NON_INTERACTIVE === "1";
2565
+ if (!bootstrapCode && !isInteractiveTerminal() && !waitsWithoutTerminal) {
2566
+ exitWithInitFailure(noTerminalFailure());
2567
+ }
2568
+ if (!isGitInstalled()) {
2569
+ exitWithInitFailure(gitMissingFailure());
2570
+ }
2571
+ if (!canStopProcessTrees()) {
2572
+ exitWithInitFailure(processControlFailure());
2573
+ }
2360
2574
  let project;
2361
- if (options.bootstrap?.trim()) {
2575
+ let dashboardUrl;
2576
+ if (bootstrapCode) {
2362
2577
  logger.info("Connecting to your Standard Agents instance...");
2363
2578
  try {
2364
- project = await resolveBootstrapProject(endpoint, options.bootstrap.trim());
2579
+ project = await resolveBootstrapProject(endpoint, bootstrapCode);
2365
2580
  } catch (error) {
2366
- logger.error(error instanceof Error ? error.message : String(error));
2367
- process.exit(1);
2581
+ exitWithInitFailure({ cause: error instanceof Error ? error.message : String(error), next: [] });
2368
2582
  }
2369
2583
  } else {
2370
- logger.info("Opening Standard Agents platform signup/login...");
2371
- let session;
2372
- try {
2373
- session = await startPlatformCliSession({
2374
- endpoint,
2375
- projectName: requestedProjectName,
2376
- packageManager: pm
2377
- });
2378
- } catch (error) {
2379
- logger.error(error instanceof Error ? error.message : String(error));
2380
- process.exit(1);
2381
- }
2382
- openUrl(session.auth_url);
2383
- logger.info("Finish the browser steps. I will stay here and continue automatically.");
2384
- project = await waitForPlatformProject(session, (progress) => {
2385
- logger.info(progress.message);
2386
- });
2584
+ ({ project, dashboardUrl } = await createProjectThroughBrowser({
2585
+ endpoint,
2586
+ projectName: requestedProjectName,
2587
+ packageManager: pm,
2588
+ skipBrowserOpen
2589
+ }));
2387
2590
  }
2388
- const projectName = resolvePlatformProjectDirectoryName(project, requestedProjectName);
2389
- const projectPackageManager = resolvePlatformProjectPackageManager(project.package_manager, pm);
2390
- const projectPath = path8.join(cwd, projectName);
2391
- if (fs5.existsSync(projectPath)) {
2392
- logger.error(`Directory "${projectName}" already exists`);
2393
- process.exit(1);
2591
+ let platformName;
2592
+ let projectPackageManager;
2593
+ try {
2594
+ platformName = resolvePlatformProjectDirectoryName(project, requestedProjectName);
2595
+ projectPackageManager = resolvePlatformProjectPackageManager(project.package_manager, pm);
2596
+ } catch (error) {
2597
+ exitWithInitFailure({ cause: error instanceof Error ? error.message : String(error), next: [] });
2394
2598
  }
2599
+ const projectName = resolveFreeDirectoryName(cwd, platformName);
2600
+ const projectPath = path9.join(cwd, projectName);
2601
+ const projectLabel = project.name || projectName;
2395
2602
  logger.success("Browser setup complete.");
2396
- logger.info(`Cloning ${cloneDisplayUrl(project)}...`);
2397
- await runCommand("git", gitCloneArgs(project, projectName), cwd);
2398
- if (project.git_extra_header && project.repo_html_url) {
2399
- await runCommand("git", ["remote", "set-url", "origin", project.repo_html_url], projectPath);
2400
- }
2401
- const supportFiles2 = writeStandardAgentsSupportFiles(projectPath, {
2402
- projectName: project.name || projectName,
2403
- packageManager: projectPackageManager
2404
- });
2405
- if (supportFiles2.length > 0) {
2406
- logger.success(`Wrote generated local support files: ${supportFiles2.join(", ")}.`);
2603
+ if (projectName !== platformName) {
2604
+ logger.warning(`Directory "${platformName}" already exists here, so the project will be cloned into "${projectName}".`);
2407
2605
  }
2408
- const envPath = writeStandardAgentsEnv(projectPath, {
2409
- apiKey: project.api_key,
2410
- platformEndpoint: endpoint
2606
+ logger.info(`Cloning ${cloneDisplayUrl(project)}...`);
2607
+ const stopRemoveOnInterrupt = interrupts.onInterrupt(() => {
2608
+ fs8.rmSync(projectPath, { recursive: true, force: true });
2609
+ logger.log("");
2610
+ logger.info(`Setup interrupted. Removed the partial "${projectName}" directory.`);
2611
+ for (const line of finishExistingProjectSteps(projectLabel, dashboardUrl)) {
2612
+ logger.log(line);
2613
+ }
2411
2614
  });
2412
- logger.success(`Wrote Standard Agents credentials to ${path8.relative(cwd, envPath)}.`);
2413
- if (project.git_extra_header) {
2414
- await configurePlatformGitCredentialHelper(projectPath);
2415
- logger.success("Configured git credentials for the platform repository.");
2615
+ try {
2616
+ await runCommand("git", gitCloneArgs(project, projectName), cwd);
2617
+ if (project.git_extra_header && project.repo_html_url) {
2618
+ await runCommand("git", ["remote", "set-url", "origin", project.repo_html_url], projectPath);
2619
+ }
2620
+ } catch (error) {
2621
+ stopRemoveOnInterrupt();
2622
+ exitWithInitFailure(cloneFailure({
2623
+ projectName: projectLabel,
2624
+ cause: commandFailureCause("git clone", error),
2625
+ dashboardUrl
2626
+ }));
2416
2627
  }
2417
- const linkedPackages = preparePlatformProjectDependencies(projectPath, projectPackageManager, options);
2418
- if (linkedPackages.length > 0) {
2419
- logger.info(`Workspace mode detected: linked ${linkedPackages.length} Standard Agents packages locally.`);
2628
+ let envPath;
2629
+ try {
2630
+ const supportFiles2 = writeStandardAgentsSupportFiles(projectPath, {
2631
+ projectName: projectLabel,
2632
+ packageManager: projectPackageManager
2633
+ });
2634
+ if (supportFiles2.length > 0) {
2635
+ logger.success(`Wrote generated local support files: ${supportFiles2.join(", ")}.`);
2636
+ }
2637
+ envPath = writeStandardAgentsEnv(projectPath, {
2638
+ apiKey: project.api_key,
2639
+ platformEndpoint: endpoint
2640
+ });
2641
+ logger.success(`Wrote Standard Agents credentials to ${path9.relative(cwd, envPath)}.`);
2642
+ if (project.git_extra_header) {
2643
+ await configurePlatformGitCredentialHelper(projectPath);
2644
+ logger.success("Configured git credentials for the platform repository.");
2645
+ }
2646
+ const linkedPackages = preparePlatformProjectDependencies(projectPath, projectPackageManager, options);
2647
+ if (linkedPackages.length > 0) {
2648
+ logger.info(`Workspace mode detected: linked ${linkedPackages.length} Standard Agents packages locally.`);
2649
+ }
2650
+ } catch (error) {
2651
+ stopRemoveOnInterrupt();
2652
+ exitWithInitFailure(configureFailure({
2653
+ projectName: projectLabel,
2654
+ directory: projectName,
2655
+ cause: commandFailureCause("Project configuration", error),
2656
+ dashboardUrl
2657
+ }));
2420
2658
  }
2659
+ stopRemoveOnInterrupt();
2421
2660
  logger.info(`Installing dependencies with ${projectPackageManager}...`);
2422
2661
  const pnpmCompatibilityArgs = getPnpmWorkspaceCompatibilityArgs(projectPackageManager, projectPath);
2423
2662
  const devHint = pnpmCompatibilityArgs.length > 0 ? resolvePostInitRunCommand(projectPackageManager, projectPath, false, pnpmCompatibilityArgs) : devCommandHint(projectPackageManager);
2424
- await runCommand(projectPackageManager, projectInstallArgs(projectPackageManager, projectPath, "install", [], {
2663
+ const installArgs = projectInstallArgs(projectPackageManager, projectPath, "install", [], {
2425
2664
  isolateFromParent: true,
2426
2665
  ignoreProjectWorkspace: pnpmCompatibilityArgs.length > 0
2427
- }), projectPath);
2666
+ });
2667
+ const installCommand = [projectPackageManager, ...installArgs].join(" ");
2668
+ const stopResumeHintOnInterrupt = interrupts.onInterrupt(() => {
2669
+ logger.log("");
2670
+ logger.info(`Setup interrupted. Your project is cloned and configured in "${projectName}". Finish with:`);
2671
+ for (const line of resumeSteps(projectName, installCommand, devHint)) {
2672
+ logger.log(line);
2673
+ }
2674
+ });
2675
+ try {
2676
+ await runCommand(projectPackageManager, installArgs, projectPath);
2677
+ } catch (error) {
2678
+ stopResumeHintOnInterrupt();
2679
+ exitWithInitFailure(installFailure({
2680
+ directory: projectName,
2681
+ cause: commandFailureCause(`${projectPackageManager} install`, error),
2682
+ installCommand,
2683
+ devCommand: devHint
2684
+ }));
2685
+ }
2686
+ stopResumeHintOnInterrupt();
2428
2687
  const repoUrl = project.repo_html_url ?? project.repo_clone_url;
2429
- const tokenLocation = path8.relative(cwd, envPath);
2688
+ const tokenLocation = path9.relative(cwd, envPath);
2430
2689
  if (options.dev === false) {
2431
2690
  logger.success("Your Standard Agents instance is ready.");
2432
2691
  logger.log(`Repository: ${repoUrl}`);
@@ -2467,13 +2726,19 @@ async function runPlatformInit(projectNameArg, options) {
2467
2726
  return;
2468
2727
  }
2469
2728
  if (startup.type === "ready" && startup.ready) {
2470
- openUrl(devUrl);
2729
+ if (!skipBrowserOpen) {
2730
+ openUrl(devUrl);
2731
+ }
2471
2732
  logger.success("Project is connected to Standard Agents.");
2472
2733
  logger.log(`Repository: ${repoUrl}`);
2473
2734
  logger.log(`Dev server: ${devUrl}`);
2474
2735
  logger.log(`Local token: ${tokenLocation}`);
2475
2736
  logger.log("");
2476
2737
  logger.log("The dev server is running in the foreground. Press Ctrl-C to stop it.");
2738
+ logger.log("");
2739
+ logger.log("To start it again later:");
2740
+ logger.log(` cd ${projectName}`);
2741
+ logger.log(` ${devHint}`);
2477
2742
  const exitCode2 = await devExit;
2478
2743
  if (exitCode2 !== null && exitCode2 !== 0) {
2479
2744
  logger.warning(`Dev server exited with code ${exitCode2}.`);
@@ -2505,6 +2770,82 @@ async function runPlatformInit(projectNameArg, options) {
2505
2770
  logger.warning(`Dev server exited with code ${exitCode}.`);
2506
2771
  }
2507
2772
  }
2773
+ var LOCAL_DEV_VARS_HEADER = [
2774
+ "# Standard Agents Environment Variables",
2775
+ "# This file contains secrets for local development only",
2776
+ "# Do not commit this file to version control",
2777
+ ""
2778
+ ].join("\n");
2779
+ var LOCAL_PROVIDER_KEY_HINTS = [
2780
+ "",
2781
+ "# AI provider API keys: uncomment and add your keys as needed",
2782
+ "# OPENROUTER_API_KEY=your-openrouter-key",
2783
+ "# OPENAI_API_KEY=your-openai-key",
2784
+ ""
2785
+ ].join("\n");
2786
+ var MANAGED_PROVIDER_KEY_HINTS = [
2787
+ "",
2788
+ "# Managed org mode",
2789
+ "# Model access, proxy routing, and credit are handled by your Standard Agents account.",
2790
+ "# Optional local overrides:",
2791
+ "# OPENROUTER_API_KEY=your-openrouter-key",
2792
+ "# OPENAI_API_KEY=your-openai-key",
2793
+ ""
2794
+ ].join("\n");
2795
+ function writeLocalDevVars(projectPath, input) {
2796
+ const devVarsPath = path9.join(projectPath, DEV_VARS_FILENAME);
2797
+ const existed = fs8.existsSync(devVarsPath);
2798
+ const existing = readDevVarsFile(projectPath);
2799
+ const wanted = [
2800
+ {
2801
+ heading: "Encryption key for secure data (auto-generated)",
2802
+ key: "ENCRYPTION_KEY",
2803
+ value: crypto2.randomBytes(32).toString("hex")
2804
+ }
2805
+ ];
2806
+ if (input.platformEndpoint) {
2807
+ wanted.push({
2808
+ heading: "Platform API endpoint for account, billing, and deploy integration",
2809
+ key: "PLATFORM_ENDPOINT",
2810
+ value: input.platformEndpoint
2811
+ });
2812
+ }
2813
+ if (!input.managed) {
2814
+ wanted.push({
2815
+ heading: "Temporary admin password for development access",
2816
+ key: "SUPER_ADMIN_PASSWORD",
2817
+ value: input.adminPassword
2818
+ });
2819
+ }
2820
+ if (input.openrouterKey) {
2821
+ wanted.push({ heading: "OpenRouter API key", key: "OPENROUTER_API_KEY", value: input.openrouterKey });
2822
+ }
2823
+ if (input.openaiKey) {
2824
+ wanted.push({ heading: "OpenAI API key", key: "OPENAI_API_KEY", value: input.openaiKey });
2825
+ }
2826
+ const missing = wanted.filter(({ key }) => !readDevVar(existing, key));
2827
+ if (existed && missing.length === 0) {
2828
+ fs8.chmodSync(devVarsPath, 384);
2829
+ } else {
2830
+ let devVars = existed ? existing : LOCAL_DEV_VARS_HEADER;
2831
+ for (const { heading, key, value } of missing) {
2832
+ const separator = devVars === "" || devVars.endsWith("\n") ? "" : "\n";
2833
+ devVars = setDevVar(`${devVars}${separator}
2834
+ # ${heading}
2835
+ `, key, value);
2836
+ }
2837
+ if (!existed) devVars += input.managed ? MANAGED_PROVIDER_KEY_HINTS : LOCAL_PROVIDER_KEY_HINTS;
2838
+ writeDevVarsFile(projectPath, devVars);
2839
+ }
2840
+ let generatedAdminPassword;
2841
+ if (input.bootstrapSession) {
2842
+ syncProjectAuthEnv(projectPath, input.platformEndpoint ?? "", input.bootstrapSession);
2843
+ if (!hasProjectApiKey(projectPath)) {
2844
+ generatedAdminPassword = replaceLegacyDefaultAdminPassword(projectPath) ?? void 0;
2845
+ }
2846
+ }
2847
+ return { status: existed ? "updated" : "created", ...generatedAdminPassword ? { generatedAdminPassword } : {} };
2848
+ }
2508
2849
  async function init(projectNameArg, options = {}) {
2509
2850
  if (!options.local) {
2510
2851
  await runPlatformInit(projectNameArg, options);
@@ -2513,9 +2854,12 @@ async function init(projectNameArg, options = {}) {
2513
2854
  const cwd = process.cwd();
2514
2855
  const detectedPm = detectPackageManager();
2515
2856
  const template = options.template || "vanilla-ts";
2516
- const initTuiMode = isInitTuiEnabled(options);
2517
- if (initTuiMode) {
2518
- clearTerminalScreen();
2857
+ const initTuiMode = !options.yes;
2858
+ if (initTuiMode && !(process.stdin.isTTY && process.stdout.isTTY)) {
2859
+ logger.error(
2860
+ "This setup needs an interactive terminal. Run it in a terminal, or pass --yes with a project name to skip the prompts."
2861
+ );
2862
+ process.exit(1);
2519
2863
  }
2520
2864
  const logInfo = (message) => {
2521
2865
  if (!initTuiMode) logger.info(message);
@@ -2526,84 +2870,70 @@ async function init(projectNameArg, options = {}) {
2526
2870
  const logSuccess = (message) => {
2527
2871
  if (!initTuiMode) logger.success(message);
2528
2872
  };
2529
- const logLine = (message = "") => {
2530
- if (!initTuiMode) logger.log(message);
2531
- };
2532
- let projectName = "";
2533
- let projectPath = "";
2534
- let existingBootstrapState = null;
2535
- let resumeBootstrap = false;
2536
- let useExistingProject = false;
2537
- const headerOptions = { tuiMode: initTuiMode };
2538
- const promptProjectName = async (question) => {
2539
- if (!initTuiMode) {
2540
- return prompt(question);
2541
- }
2542
- clearTerminalScreen();
2543
- const value = await promptProjectNameWithInk(question, {
2544
- stage: "project",
2545
- title: "Creating project scaffold",
2546
- subtitle: "Choose the directory name for your new project.",
2547
- projectName: headerOptions.projectName,
2548
- packageManager: headerOptions.packageManager,
2549
- authMode: headerOptions.authMode
2550
- });
2551
- if (value === null) {
2552
- throw new InitWizardReturnToHomeError();
2553
- }
2554
- return value;
2555
- };
2556
- try {
2557
- const target = await resolveProjectTarget(cwd, projectNameArg, options, promptProjectName);
2558
- projectName = target.projectName;
2559
- projectPath = target.projectPath;
2560
- existingBootstrapState = target.existingBootstrapState;
2561
- resumeBootstrap = target.resumeBootstrap;
2562
- useExistingProject = target.useExistingProject;
2563
- headerOptions.projectName = projectName;
2564
- } catch (error) {
2565
- if (isInitWizardReturnToHomeError(error)) {
2566
- exitOrThrowReturnToHome(options);
2567
- }
2568
- logger.error(error instanceof Error ? error.message : "Project name is required");
2569
- process.exit(1);
2570
- }
2571
- renderInitStepHeader(
2572
- "project",
2573
- useExistingProject ? "Inspecting existing project" : "Creating project scaffold",
2574
- useExistingProject ? `Using "${projectName}" in the current workspace.` : `Preparing "${projectName}" with template "${template}".`,
2575
- headerOptions
2576
- );
2577
- if (useExistingProject) {
2578
- logInfo(`Using existing Standard Agents project "${projectName}"...`);
2579
- } else {
2580
- logInfo("Creating a new Standard Agents project...");
2581
- }
2582
- let pm;
2873
+ let requestedPm;
2583
2874
  if (options.packageManager) {
2584
2875
  try {
2585
- pm = resolvePackageManager(options.packageManager, detectedPm);
2876
+ requestedPm = resolvePackageManager(options.packageManager, detectedPm);
2586
2877
  } catch (error) {
2587
2878
  logger.error(error instanceof Error ? error.message : String(error));
2588
2879
  process.exit(1);
2589
2880
  }
2590
- } else if (useExistingProject || options.yes) {
2591
- pm = detectedPm;
2881
+ }
2882
+ const providedBootstrap = options.bootstrap?.trim() ?? "";
2883
+ const needsLocalEnv = (candidate) => !providedBootstrap && candidate.existingBootstrapState === null && !fs8.existsSync(path9.join(candidate.projectPath, ".dev.vars"));
2884
+ const existingProjectPackageManager = (candidate) => candidate.useExistingProject ? detectLockfilePackageManager(candidate.projectPath) : void 0;
2885
+ const initialTarget = resolveProjectTarget(cwd, projectNameArg);
2886
+ let target;
2887
+ let pm;
2888
+ let localEnv;
2889
+ if (!initTuiMode) {
2890
+ if (!initialTarget.ok) {
2891
+ logger.error(initialTarget.message);
2892
+ process.exit(1);
2893
+ }
2894
+ target = initialTarget.target;
2895
+ pm = requestedPm ?? existingProjectPackageManager(target) ?? detectedPm;
2592
2896
  } else {
2593
- try {
2594
- pm = await selectPackageManager(detectedPm, {
2595
- projectName: headerOptions.projectName,
2596
- authMode: headerOptions.authMode
2597
- });
2598
- } catch (error) {
2599
- if (isInitWizardReturnToHomeError(error)) {
2600
- exitOrThrowReturnToHome(options);
2601
- }
2602
- throw error;
2897
+ let resolved = initialTarget.ok ? initialTarget.target : void 0;
2898
+ const toWizardTarget = (candidate) => ({
2899
+ projectName: candidate.projectName,
2900
+ existing: candidate.useExistingProject,
2901
+ collectEnv: needsLocalEnv(candidate)
2902
+ });
2903
+ const answers = await runLocalInitWizardWithInk({
2904
+ resolveTarget: (candidate) => {
2905
+ const resolution = resolveProjectTarget(cwd, candidate);
2906
+ if (!resolution.ok) return resolution;
2907
+ resolved = resolution.target;
2908
+ return { ok: true, target: toWizardTarget(resolution.target) };
2909
+ },
2910
+ initialTarget: resolved ? toWizardTarget(resolved) : void 0,
2911
+ initialNameError: !initialTarget.ok && projectNameArg?.trim() ? initialTarget.message : void 0,
2912
+ detectedPackageManager: detectedPm,
2913
+ packageManager: requestedPm,
2914
+ collectEnvByDefault: !providedBootstrap,
2915
+ validateEnvValue: (value) => isDevVarValueRepresentable(value) ? void 0 : "This value cannot be saved to .dev.vars unchanged. Use at most two of the ' \" ` characters and no trailing backslash."
2916
+ });
2917
+ if (!answers || !resolved) {
2918
+ logger.log("Setup cancelled. No changes were made.");
2919
+ process.exit(1);
2603
2920
  }
2604
- logLine("");
2921
+ target = resolved;
2922
+ pm = requestedPm ?? answers.packageManager ?? existingProjectPackageManager(target) ?? detectedPm;
2923
+ localEnv = answers.env;
2924
+ }
2925
+ const { projectName, projectPath, existingBootstrapState, resumeBootstrap, useExistingProject } = target;
2926
+ const headerOptions = {
2927
+ tuiMode: initTuiMode,
2928
+ projectName,
2929
+ packageManager: pm,
2930
+ collectEnv: localEnv !== void 0
2931
+ };
2932
+ if (useExistingProject) {
2933
+ logInfo(`Using existing Standard Agents project "${projectName}"...`);
2934
+ } else {
2935
+ logInfo("Creating a new Standard Agents project...");
2605
2936
  }
2606
- headerOptions.packageManager = pm;
2607
2937
  logInfo(`Using package manager: ${pm}`);
2608
2938
  let packageSpecifier = "";
2609
2939
  try {
@@ -2612,110 +2942,24 @@ async function init(projectNameArg, options = {}) {
2612
2942
  logger.error(error instanceof Error ? error.message : "Invalid package install mode");
2613
2943
  process.exit(1);
2614
2944
  }
2615
- const providedBootstrap = options.bootstrap?.trim() ?? "";
2616
- if (providedBootstrap) {
2617
- logInfo("Bootstrap code supplied.");
2618
- } else if (existingBootstrapState) {
2619
- logInfo("Found existing Standard Agents auth session for this project.");
2620
- } else {
2621
- logInfo("No Standard Agents CLI auth session found.");
2622
- }
2623
- logLine("");
2624
- const willShowAuthCardPrompt = initTuiMode && !existingBootstrapState && !providedBootstrap && !options.yes;
2625
- if (!willShowAuthCardPrompt) {
2626
- renderInitStepHeader(
2627
- "auth",
2628
- "Account linking",
2629
- existingBootstrapState ? "Reusing saved project auth session if compatible with endpoint." : "Choose Standard Agents or Local mode.",
2630
- headerOptions
2631
- );
2632
- }
2633
- let authResult = { connected: false, mode: "local" };
2634
- if (!existingBootstrapState) {
2635
- try {
2636
- authResult = await ensurePlatformAuth(options, initTuiMode, {
2637
- projectName: headerOptions.projectName,
2638
- packageManager: headerOptions.packageManager
2639
- });
2640
- } catch (error) {
2641
- if (isInitWizardReturnToHomeError(error)) {
2642
- exitOrThrowReturnToHome(options);
2643
- }
2644
- throw error;
2645
- }
2646
- } else {
2647
- authResult = { connected: true, mode: "standardagents" };
2648
- }
2649
- headerOptions.authMode = authResult.mode;
2650
- const bootstrapRequested = Boolean(options.bootstrap?.trim()) || existingBootstrapState !== null;
2651
- if (!bootstrapRequested && authResult.mode === "local") {
2652
- logInfo("Continuing in Local mode (no org link yet).");
2653
- }
2945
+ const bootstrapRequested = Boolean(providedBootstrap) || existingBootstrapState !== null;
2946
+ const isManagedOrgMode = bootstrapRequested;
2654
2947
  let bootstrapSession = null;
2655
- const isManagedOrgMode = authResult.mode === "standardagents";
2656
- if (!isManagedOrgMode) {
2657
- renderInitStepHeader(
2658
- "env",
2659
- "Environment setup",
2660
- "Collecting local credentials and writing .dev.vars.",
2661
- headerOptions
2662
- );
2663
- }
2664
- const encryptionKey = crypto.randomBytes(32).toString("hex");
2665
- let openrouterKey = "";
2666
- let openaiKey = "";
2667
- let adminPassword = "";
2668
- if (isManagedOrgMode) {
2669
- logInfo("Managed Standard Agents auth detected. Skipping local provider/admin prompts.");
2670
- } else if (!options.yes) {
2671
- if (initTuiMode) {
2672
- const localEnvInput = await collectLocalEnvWithInk({
2673
- projectName: headerOptions.projectName,
2674
- packageManager: headerOptions.packageManager,
2675
- authMode: headerOptions.authMode
2676
- });
2677
- if (!localEnvInput) {
2678
- exitOrThrowReturnToHome(options);
2679
- }
2680
- openrouterKey = localEnvInput.openrouterKey;
2681
- openaiKey = localEnvInput.openaiKey;
2682
- adminPassword = localEnvInput.adminPassword;
2683
- } else {
2684
- logLine("API keys are optional but required to use AI models.");
2685
- logLine("You can add them later by editing .dev.vars");
2686
- logLine("");
2687
- openrouterKey = await prompt("OpenRouter API key (optional, press Enter to skip): ");
2688
- openaiKey = await prompt("OpenAI API key (optional, press Enter to skip): ");
2689
- logLine("");
2690
- logLine("Set a temporary admin password for development access.");
2691
- logLine('Press Enter to use the default password "admin".');
2692
- logLine("");
2693
- while (true) {
2694
- adminPassword = await promptPassword("Temporary admin password: ");
2695
- if (!adminPassword) {
2696
- adminPassword = "admin";
2697
- break;
2698
- }
2699
- const confirmPassword = await promptPassword("Confirm password: ");
2700
- if (adminPassword === confirmPassword) {
2701
- break;
2702
- } else {
2703
- logWarning("Passwords do not match. Please try again.");
2704
- logLine("");
2705
- adminPassword = "";
2706
- }
2707
- }
2708
- }
2709
- }
2710
- if (!isManagedOrgMode && !adminPassword) {
2711
- adminPassword = "admin";
2712
- }
2948
+ const openrouterKey = localEnv?.openrouterKey ?? "";
2949
+ const openaiKey = localEnv?.openaiKey ?? "";
2950
+ const adminPassword = localEnv?.adminPassword || crypto2.randomBytes(18).toString("base64url");
2713
2951
  renderInitStepHeader(
2714
2952
  "scaffold",
2715
2953
  "Scaffold project",
2716
2954
  "Installing dependencies and applying Standard Agents project structure.",
2717
2955
  headerOptions
2718
2956
  );
2957
+ const stopRemoveOnInterrupt = !useExistingProject && !fs8.existsSync(projectPath) ? interrupts.onInterrupt(() => {
2958
+ fs8.rmSync(projectPath, { recursive: true, force: true });
2959
+ logger.log("");
2960
+ logger.info(`Setup interrupted. Removed the partial "${projectName}" directory.`);
2961
+ }) : () => {
2962
+ };
2719
2963
  if (!useExistingProject) {
2720
2964
  logInfo(`Running create-vite (${template})...`);
2721
2965
  try {
@@ -2747,15 +2991,15 @@ async function init(projectNameArg, options = {}) {
2747
2991
  );
2748
2992
  process.exit(1);
2749
2993
  }
2750
- const viteConfigPath = path8.join(projectPath, "vite.config.ts");
2751
- if (!fs5.existsSync(viteConfigPath)) {
2994
+ const viteConfigPath = path9.join(projectPath, "vite.config.ts");
2995
+ if (!fs8.existsSync(viteConfigPath)) {
2752
2996
  const viteConfigContent = `import { defineConfig } from 'vite'
2753
2997
 
2754
2998
  export default defineConfig({
2755
2999
  plugins: [],
2756
3000
  })
2757
3001
  `;
2758
- fs5.writeFileSync(viteConfigPath, viteConfigContent, "utf-8");
3002
+ fs8.writeFileSync(viteConfigPath, viteConfigContent, "utf-8");
2759
3003
  logSuccess("Created vite.config.ts");
2760
3004
  }
2761
3005
  } else if (resumeBootstrap) {
@@ -2763,13 +3007,13 @@ export default defineConfig({
2763
3007
  } else {
2764
3008
  logInfo(`Detected existing Standard Agents project in "${projectName}".`);
2765
3009
  }
2766
- const packageJsonPath = path8.join(projectPath, "package.json");
2767
- if (fs5.existsSync(packageJsonPath)) {
2768
- const packageJson = JSON.parse(fs5.readFileSync(packageJsonPath, "utf-8"));
3010
+ const packageJsonPath = path9.join(projectPath, "package.json");
3011
+ if (fs8.existsSync(packageJsonPath)) {
3012
+ const packageJson = JSON.parse(fs8.readFileSync(packageJsonPath, "utf-8"));
2769
3013
  const kebabName = toKebabCase(projectName);
2770
3014
  if (packageJson.name !== kebabName) {
2771
3015
  packageJson.name = kebabName;
2772
- fs5.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2) + "\n", "utf-8");
3016
+ fs8.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2) + "\n", "utf-8");
2773
3017
  }
2774
3018
  if (packageSpecifier === "workspace:*") {
2775
3019
  const workspaceRoot = resolveStandardAgentsWorkspaceRoot();
@@ -2802,7 +3046,7 @@ export default defineConfig({
2802
3046
  let projectPnpmCompatibilityArgs = [];
2803
3047
  try {
2804
3048
  const installBoundary = { isolateFromParent: packageSpecifier === "workspace:*" };
2805
- if (pm === "pnpm" && !installBoundary.isolateFromParent && !fs5.existsSync(path8.join(projectPath, "pnpm-workspace.yaml")) && findPnpmWorkspaceRoot(path8.dirname(projectPath))) {
3049
+ if (pm === "pnpm" && !installBoundary.isolateFromParent && !fs8.existsSync(path9.join(projectPath, "pnpm-workspace.yaml")) && findPnpmWorkspaceRoot(path9.dirname(projectPath))) {
2806
3050
  logInfo("The enclosing pnpm workspace controls esbuild and workerd build approvals.");
2807
3051
  }
2808
3052
  writeLocalPnpmBuildPolicy(projectPath, pm, {
@@ -2866,88 +3110,35 @@ export default defineConfig({
2866
3110
  process.exit(1);
2867
3111
  }
2868
3112
  logInfo("Writing environment configuration...");
2869
- const devVarsLines = [
2870
- "# Standard Agents Environment Variables",
2871
- "# This file contains secrets for local development only",
2872
- "# Do not commit this file to version control",
2873
- "",
2874
- "# Encryption key for secure data (auto-generated)",
2875
- `ENCRYPTION_KEY=${encryptionKey}`
2876
- ];
2877
- const resolvedPlatformEndpoint = resolvePlatformEndpoint(options);
2878
- if (isManagedOrgMode || options.endpoint || options.apiUrl || process.env.PLATFORM_ENDPOINT) {
2879
- devVarsLines.push(
2880
- "",
2881
- "# Platform API endpoint for account, billing, and deploy integration",
2882
- `PLATFORM_ENDPOINT=${resolvedPlatformEndpoint}`
2883
- );
2884
- }
2885
- if (!isManagedOrgMode) {
2886
- devVarsLines.push(
2887
- "",
2888
- "# Temporary admin password for development access",
2889
- `SUPER_ADMIN_PASSWORD=${adminPassword}`
2890
- );
2891
- }
2892
- if (bootstrapSession) {
2893
- devVarsLines.push(
2894
- "",
2895
- "# Bootstrap-authenticated org context",
2896
- `STANDARDAGENTS_ORG_ACCOUNT_ID=${bootstrapSession.account.id}`,
2897
- `STANDARDAGENTS_ORG_USER_ID=${bootstrapSession.user.id}`,
2898
- `STANDARDAGENTS_BOOTSTRAP_SESSION_COOKIE=${bootstrapSession.session_cookie}`
2899
- );
2900
- if (bootstrapSession.account.slug) {
2901
- devVarsLines.push(`STANDARDAGENTS_ORG_SLUG=${bootstrapSession.account.slug}`);
2902
- }
2903
- }
2904
- if (isManagedOrgMode) {
2905
- devVarsLines.push(
2906
- "",
2907
- "# Managed org mode",
2908
- "# Model access, proxy routing, and credit are handled by your Standard Agents account.",
2909
- "# Optional local overrides:",
2910
- "# OPENROUTER_API_KEY=your-openrouter-key",
2911
- "# OPENAI_API_KEY=your-openai-key"
2912
- );
2913
- } else {
2914
- devVarsLines.push(
2915
- "",
2916
- "# AI Provider API Keys",
2917
- "# Uncomment and add your keys as needed"
2918
- );
2919
- if (openrouterKey) {
2920
- devVarsLines.push(`OPENROUTER_API_KEY=${openrouterKey}`);
2921
- } else {
2922
- devVarsLines.push("# OPENROUTER_API_KEY=your-openrouter-key");
2923
- }
2924
- if (openaiKey) {
2925
- devVarsLines.push(`OPENAI_API_KEY=${openaiKey}`);
2926
- } else {
2927
- devVarsLines.push("# OPENAI_API_KEY=your-openai-key");
2928
- }
2929
- }
2930
- devVarsLines.push("");
2931
- const devVarsPath = path8.join(projectPath, ".dev.vars");
2932
- fs5.writeFileSync(devVarsPath, devVarsLines.join("\n"), "utf-8");
2933
- logSuccess("Created .dev.vars with encryption key");
2934
- const gitignorePath = path8.join(projectPath, ".gitignore");
2935
- if (fs5.existsSync(gitignorePath)) {
2936
- const gitignoreContent = fs5.readFileSync(gitignorePath, "utf-8");
3113
+ const devVarsResult = writeLocalDevVars(projectPath, {
3114
+ managed: isManagedOrgMode,
3115
+ platformEndpoint: isManagedOrgMode || options.endpoint || options.apiUrl || process.env.PLATFORM_ENDPOINT ? resolvePlatformEndpoint(options) : void 0,
3116
+ adminPassword,
3117
+ openrouterKey,
3118
+ openaiKey,
3119
+ bootstrapSession
3120
+ });
3121
+ logSuccess(devVarsResult.status === "created" ? "Created .dev.vars with encryption key" : "Kept existing .dev.vars values and added missing keys");
3122
+ const gitignorePath = path9.join(projectPath, ".gitignore");
3123
+ if (fs8.existsSync(gitignorePath)) {
3124
+ const gitignoreContent = fs8.readFileSync(gitignorePath, "utf-8");
2937
3125
  if (!gitignoreContent.includes(".dev.vars")) {
2938
- fs5.appendFileSync(gitignorePath, "\n# Local environment variables\n.dev.vars\n");
3126
+ fs8.appendFileSync(gitignorePath, "\n# Local environment variables\n.dev.vars\n");
2939
3127
  logSuccess("Added .dev.vars to .gitignore");
2940
3128
  }
2941
3129
  }
3130
+ stopRemoveOnInterrupt();
2942
3131
  const nextRunCommand = resolvePostInitRunCommand(pm, projectPath, packageSpecifier === "workspace:*", projectPnpmCompatibilityArgs);
2943
3132
  if (initTuiMode) {
2944
3133
  clearTerminalScreen();
2945
3134
  process.stdout.write(
2946
3135
  renderInitCompleteFrame({
2947
3136
  useExistingProject,
3137
+ changeDirectory: projectPath !== cwd,
2948
3138
  projectName,
2949
3139
  nextCommand: nextRunCommand,
2950
- bootstrapSession: Boolean(bootstrapSession)
3140
+ localSignIn: !isManagedOrgMode,
3141
+ generatedAdminPassword: devVarsResult.generatedAdminPassword
2951
3142
  })
2952
3143
  );
2953
3144
  return;
@@ -2957,57 +3148,71 @@ export default defineConfig({
2957
3148
  logger.log("");
2958
3149
  logger.log("Next steps:");
2959
3150
  logger.log("");
2960
- if (!useExistingProject) {
3151
+ if (projectPath !== cwd) {
2961
3152
  logger.log(` cd ${projectName}`);
2962
3153
  }
2963
3154
  logger.log(` ${nextRunCommand}`);
2964
3155
  logger.log("");
2965
- if (!bootstrapSession) {
2966
- logger.log("Local-only mode notes:");
2967
- logger.log(" 1. Sign in locally with username `admin` and your temporary `SUPER_ADMIN_PASSWORD`.");
2968
- logger.log(" 2. Create a standard user account for yourself.");
2969
- logger.log(" 3. Remove `SUPER_ADMIN_PASSWORD` from `.dev.vars` once setup is complete.");
3156
+ if (!isManagedOrgMode) {
3157
+ logger.log("Sign in:");
3158
+ LOCAL_SIGN_IN_NOTES.forEach((note, index) => {
3159
+ logger.log(` ${index + 1}. ${note}`);
3160
+ });
3161
+ logger.log("");
3162
+ }
3163
+ if (devVarsResult.generatedAdminPassword) {
3164
+ GENERATED_ADMIN_PASSWORD_NOTES.forEach((note) => logger.log(note));
3165
+ logger.log(` ${devVarsResult.generatedAdminPassword}`);
2970
3166
  logger.log("");
2971
3167
  }
2972
3168
  logger.log("For more information, visit: https://standardagents.ai/docs");
2973
3169
  }
2974
- var DEV_VARS_FILENAME = ".dev.vars";
2975
- var PROJECT_AUTH_ENV_KEYS = [
2976
- "STANDARDAGENTS_ORG_ACCOUNT_ID",
2977
- "STANDARDAGENTS_ORG_USER_ID",
2978
- "STANDARDAGENTS_ORG_SLUG",
2979
- "STANDARDAGENTS_BOOTSTRAP_SESSION_COOKIE"
2980
- ];
2981
- function upsertEnvLine2(lines, key, value) {
2982
- const nextLine = `${key}=${value}`;
2983
- const index = lines.findIndex((line) => line.startsWith(`${key}=`));
2984
- if (index >= 0) {
2985
- lines[index] = nextLine;
2986
- return;
2987
- }
2988
- lines.push(nextLine);
3170
+ function registerInitCommand(program2, action = init) {
3171
+ program2.command("init [project-name]").description(
3172
+ "Create a new Standard Agents project. Signs you in to your Standard Agents account in the browser; the account supplies inference."
3173
+ ).option("--no-open", "Print the sign-in URL without opening a browser").option("--no-dev", "Clone and configure the project without starting the dev server").option("--package-manager <manager>", "Package manager for the project: npm, pnpm, yarn, or bun").option("--api-url <url>", "Standard Agents platform API URL").addOption(new Option("--endpoint <url>", "Alias of --api-url").hideHelp()).addOption(new Option("-y, --yes", "Skip prompts in the local scaffold").hideHelp()).addOption(new Option("--local", "Use local project scaffolding").hideHelp()).addOption(new Option("--template <template>", "Vite template for the local scaffold").default("vanilla-ts").hideHelp()).addOption(new Option("--workspace", "Link local @standardagents packages with pnpm").hideHelp()).addOption(new Option("--bootstrap <code>", "Finish setup with a platform-issued setup code").hideHelp()).action(action);
2989
3174
  }
2990
- function syncProjectAuthEnv(projectPath, endpoint, state) {
2991
- const devVarsPath = path8.join(projectPath, DEV_VARS_FILENAME);
2992
- const existing = fs5.existsSync(devVarsPath) ? fs5.readFileSync(devVarsPath, "utf-8") : "";
2993
- const lines = existing ? existing.split("\n") : [];
2994
- if (endpoint.trim()) {
2995
- upsertEnvLine2(lines, "PLATFORM_ENDPOINT", endpoint.trim());
3175
+
3176
+ // src/utils/node-version.ts
3177
+ var SUPPORTED_DESCRIPTION = "Node.js 22 (22.12 or newer) and Node.js 24";
3178
+ var SWITCH_HINT = "Install a supported version (for example: nvm install 24), then run the command again.";
3179
+ function evaluateNodeVersion(rawVersion) {
3180
+ const version = rawVersion.trim().replace(/^v/, "");
3181
+ const [major, minor] = version.split(".").map((part) => Number.parseInt(part, 10));
3182
+ if (!Number.isInteger(major) || !Number.isInteger(minor)) {
3183
+ return {
3184
+ status: "untested",
3185
+ message: `Could not read the Node.js version. The Standard Agents CLI supports ${SUPPORTED_DESCRIPTION}.`
3186
+ };
2996
3187
  }
2997
- upsertEnvLine2(lines, "STANDARDAGENTS_ORG_ACCOUNT_ID", state.account.id);
2998
- upsertEnvLine2(lines, "STANDARDAGENTS_ORG_USER_ID", state.user.id);
2999
- if (state.account.slug) {
3000
- upsertEnvLine2(lines, "STANDARDAGENTS_ORG_SLUG", state.account.slug);
3188
+ if (major === 22 && minor >= 12 || major === 24) {
3189
+ return { status: "supported" };
3001
3190
  }
3002
- if (state.session_cookie) {
3003
- upsertEnvLine2(lines, "STANDARDAGENTS_BOOTSTRAP_SESSION_COOKIE", state.session_cookie);
3191
+ if (major <= 22) {
3192
+ return {
3193
+ status: "unsupported",
3194
+ message: `The Standard Agents CLI supports ${SUPPORTED_DESCRIPTION}. You are running Node.js ${version}.
3195
+ ${SWITCH_HINT}`
3196
+ };
3004
3197
  }
3005
- const normalized = lines.join("\n").replace(/\n*$/, "\n");
3006
- fs5.writeFileSync(devVarsPath, normalized, "utf-8");
3198
+ return {
3199
+ status: "untested",
3200
+ message: `The Standard Agents CLI supports ${SUPPORTED_DESCRIPTION}. Node.js ${version} is not tested. If a step fails, switch to Node.js 24 (for example: nvm install 24).`
3201
+ };
3007
3202
  }
3008
-
3009
- // src/commands/login.ts
3010
- async function prompt2(question) {
3203
+ function assertSupportedNodeVersion(rawVersion = process.versions.node, report = (message) => console.error(message), exit = (code) => process.exit(code)) {
3204
+ const check = evaluateNodeVersion(rawVersion);
3205
+ if (check.status === "supported" || !check.message) return;
3206
+ report(check.message);
3207
+ if (check.status === "unsupported") exit(1);
3208
+ }
3209
+ var LOGIN_COMMAND = "npx @standardagents/cli@latest login";
3210
+ function setupCodeHelp(reason) {
3211
+ return `${reason}
3212
+ Copy the setup command from your project's Overview page in the Standard Agents dashboard, or sign in through the browser from a terminal: ${LOGIN_COMMAND}
3213
+ With a code: ${LOGIN_COMMAND} --bootstrap <code>`;
3214
+ }
3215
+ async function prompt(question) {
3011
3216
  const rl = readline.createInterface({
3012
3217
  input: process.stdin,
3013
3218
  output: process.stdout
@@ -3019,12 +3224,31 @@ async function prompt2(question) {
3019
3224
  });
3020
3225
  });
3021
3226
  }
3227
+ async function ensureProjectSignIn(projectPath, endpoint, state, projectId, fetchImpl) {
3228
+ if (hasProjectApiKey(projectPath)) {
3229
+ return { accountSignIn: true };
3230
+ }
3231
+ if (projectId && state.session_cookie) {
3232
+ try {
3233
+ const project = await requestCliHandoff(endpoint, projectId, state.session_cookie, fetchImpl);
3234
+ writeStandardAgentsEnv(projectPath, { apiKey: project.api_key, platformEndpoint: endpoint });
3235
+ return { accountSignIn: true };
3236
+ } catch (error) {
3237
+ logger.warning(
3238
+ `Could not get a project key for account sign-in: ${error instanceof Error ? error.message : String(error)}`
3239
+ );
3240
+ }
3241
+ }
3242
+ const generatedAdminPassword = replaceLegacyDefaultAdminPassword(projectPath) ?? void 0;
3243
+ return { accountSignIn: false, ...generatedAdminPassword ? { generatedAdminPassword } : {} };
3244
+ }
3022
3245
  async function loginWithBootstrap(projectPath, options, fetchImpl = fetch) {
3023
3246
  const endpoint = resolvePlatformEndpoint({ endpoint: options.endpoint });
3024
3247
  const existing = loadBootstrapState(projectPath);
3025
3248
  if (existing && existing.endpoint === endpoint && existing.session_cookie && !options.bootstrap?.trim()) {
3026
3249
  syncProjectAuthEnv(projectPath, endpoint, existing);
3027
- return { state: existing, reused: true };
3250
+ const signIn2 = await ensureProjectSignIn(projectPath, endpoint, existing, void 0, fetchImpl);
3251
+ return { state: existing, reused: true, ...signIn2 };
3028
3252
  }
3029
3253
  const bootstrapCode = options.bootstrap?.trim();
3030
3254
  if (!bootstrapCode) {
@@ -3033,20 +3257,16 @@ async function loginWithBootstrap(projectPath, options, fetchImpl = fetch) {
3033
3257
  "Stored org session is missing credentials. Re-authenticate with: npx @standardagents/cli login --bootstrap <code>"
3034
3258
  );
3035
3259
  }
3036
- throw new Error("Bootstrap code required. Run: npx @standardagents/cli login --bootstrap <code>");
3260
+ throw new Error(setupCodeHelp("A setup code is required to link this project."));
3037
3261
  }
3038
- const state = await consumeBootstrapLogin({ ...options, endpoint, bootstrap: bootstrapCode }, fetchImpl);
3262
+ const consumed = await exchangeBootstrapCode(endpoint, bootstrapCode, fetchImpl);
3263
+ const state = bootstrapStateFromExchange(endpoint, consumed);
3039
3264
  persistBootstrapState(projectPath, state);
3040
3265
  syncProjectAuthEnv(projectPath, endpoint, state);
3041
- return { state, reused: false };
3266
+ const signIn = await ensureProjectSignIn(projectPath, endpoint, state, consumed.project?.id, fetchImpl);
3267
+ return { state, reused: false, ...signIn };
3042
3268
  }
3043
- async function consumeBootstrapLogin(options, fetchImpl = fetch) {
3044
- const endpoint = resolvePlatformEndpoint({ endpoint: options.endpoint });
3045
- const bootstrapCode = options.bootstrap?.trim();
3046
- if (!bootstrapCode) {
3047
- throw new Error("Bootstrap code required. Run: npx @standardagents/cli login --bootstrap <code>");
3048
- }
3049
- const consumed = await exchangeBootstrapCode(endpoint, bootstrapCode, fetchImpl);
3269
+ function bootstrapStateFromExchange(endpoint, consumed) {
3050
3270
  return {
3051
3271
  version: 1,
3052
3272
  endpoint,
@@ -3056,6 +3276,34 @@ async function consumeBootstrapLogin(options, fetchImpl = fetch) {
3056
3276
  account: consumed.account
3057
3277
  };
3058
3278
  }
3279
+ function reportProjectLogin({ state, reused, accountSignIn, generatedAdminPassword }) {
3280
+ logger.log("");
3281
+ if (reused) {
3282
+ logger.success("Already authenticated in this project.");
3283
+ } else {
3284
+ logger.success("Bootstrap login successful.");
3285
+ }
3286
+ logger.log(`Account: ${state.account.id}${state.account.slug ? ` (${state.account.slug})` : ""}`);
3287
+ logger.log(`User: ${state.user.email}`);
3288
+ if (accountSignIn) {
3289
+ logger.log("Local sign-in: your Standard Agents account.");
3290
+ } else if (generatedAdminPassword) {
3291
+ logger.log("");
3292
+ logger.warning("This project used a default admin password. It now has a random one.");
3293
+ logger.log("Local sign-in: username `admin` with this password.");
3294
+ logger.log(` ${generatedAdminPassword}`);
3295
+ logger.log("The password is saved as `SUPER_ADMIN_PASSWORD` in `.dev.vars`.");
3296
+ }
3297
+ logger.log("");
3298
+ }
3299
+ async function consumeBootstrapLogin(options, fetchImpl = fetch) {
3300
+ const endpoint = resolvePlatformEndpoint({ endpoint: options.endpoint });
3301
+ const bootstrapCode = options.bootstrap?.trim();
3302
+ if (!bootstrapCode) {
3303
+ throw new Error(setupCodeHelp("A setup code is required to link this project."));
3304
+ }
3305
+ return bootstrapStateFromExchange(endpoint, await exchangeBootstrapCode(endpoint, bootstrapCode, fetchImpl));
3306
+ }
3059
3307
  async function loginWithPlatform(options) {
3060
3308
  const endpoint = resolvePlatformEndpoint({ endpoint: options.endpoint });
3061
3309
  let authAppUrl = resolvePlatformAuthBrowserUrl(endpoint);
@@ -3087,7 +3335,7 @@ async function loginWithPlatform(options) {
3087
3335
  }
3088
3336
  }
3089
3337
  if (!process.stdin.isTTY) {
3090
- const message = "Non-interactive shell detected. Run: npx @standardagents/cli login --bootstrap <code>";
3338
+ const message = setupCodeHelp("Browser sign-in needs an interactive terminal.");
3091
3339
  if (options.exitOnError === false) {
3092
3340
  throw new Error(message);
3093
3341
  }
@@ -3098,19 +3346,10 @@ async function loginWithPlatform(options) {
3098
3346
  try {
3099
3347
  const completion = await waitForCliAuthCompletion(wsUrl, wsExpiresAt);
3100
3348
  const projectPath2 = process.cwd();
3101
- const { state: state2, reused: reused2 } = await loginWithBootstrap(
3349
+ reportProjectLogin(await loginWithBootstrap(
3102
3350
  projectPath2,
3103
3351
  { ...options, endpoint, bootstrap: completion.bootstrapCode }
3104
- );
3105
- logger.log("");
3106
- if (reused2) {
3107
- logger.success("Already authenticated in this project.");
3108
- } else {
3109
- logger.success("Bootstrap login successful.");
3110
- }
3111
- logger.log(`Account: ${state2.account.id}${state2.account.slug ? ` (${state2.account.slug})` : ""}`);
3112
- logger.log(`User: ${state2.user.email}`);
3113
- logger.log("");
3352
+ ));
3114
3353
  return;
3115
3354
  } catch (error) {
3116
3355
  const message = error instanceof Error ? error.message : "Realtime auth handoff failed";
@@ -3118,13 +3357,13 @@ async function loginWithPlatform(options) {
3118
3357
  }
3119
3358
  }
3120
3359
  logger.log("");
3121
- const input = await prompt2("Bootstrap code or command: ");
3360
+ const input = await prompt("Bootstrap code or command: ");
3122
3361
  const bootstrapCode = parseBootstrapCodeInput(input);
3123
3362
  if (!bootstrapCode) {
3124
3363
  if (sessionId) {
3125
3364
  await cancelCliAuthSession(endpoint, sessionId);
3126
3365
  }
3127
- const message = "No bootstrap code provided. Run: npx @standardagents/cli login --bootstrap <code>";
3366
+ const message = setupCodeHelp("No setup code was entered.");
3128
3367
  if (options.exitOnError === false) {
3129
3368
  throw new Error(message);
3130
3369
  }
@@ -3135,32 +3374,14 @@ async function loginWithPlatform(options) {
3135
3374
  await cancelCliAuthSession(endpoint, sessionId);
3136
3375
  }
3137
3376
  const projectPath = process.cwd();
3138
- const { state, reused } = await loginWithBootstrap(projectPath, { ...options, endpoint, bootstrap: bootstrapCode });
3139
- logger.log("");
3140
- if (reused) {
3141
- logger.success("Already authenticated in this project.");
3142
- } else {
3143
- logger.success("Bootstrap login successful.");
3144
- }
3145
- logger.log(`Account: ${state.account.id}${state.account.slug ? ` (${state.account.slug})` : ""}`);
3146
- logger.log(`User: ${state.user.email}`);
3147
- logger.log("");
3377
+ reportProjectLogin(await loginWithBootstrap(projectPath, { ...options, endpoint, bootstrap: bootstrapCode }));
3148
3378
  }
3149
3379
  async function login(options = {}) {
3150
3380
  const bootstrapCode = options.bootstrap?.trim();
3151
3381
  if (bootstrapCode) {
3152
3382
  const projectPath = process.cwd();
3153
3383
  try {
3154
- const { state, reused } = await loginWithBootstrap(projectPath, options);
3155
- logger.log("");
3156
- if (reused) {
3157
- logger.success("Already authenticated in this project.");
3158
- } else {
3159
- logger.success("Bootstrap login successful.");
3160
- }
3161
- logger.log(`Account: ${state.account.id}${state.account.slug ? ` (${state.account.slug})` : ""}`);
3162
- logger.log(`User: ${state.user.email}`);
3163
- logger.log("");
3384
+ reportProjectLogin(await loginWithBootstrap(projectPath, options));
3164
3385
  return;
3165
3386
  } catch (error) {
3166
3387
  const message = error instanceof Error ? error.message : "Login failed";
@@ -3177,17 +3398,17 @@ var KEYCHAIN_SERVICE = "standardagents-cli";
3177
3398
  function configDir() {
3178
3399
  if (process.platform === "win32") {
3179
3400
  const appData = process.env.APPDATA;
3180
- if (appData) return path8.join(appData, "standardagents");
3401
+ if (appData) return path9.join(appData, "standardagents");
3181
3402
  }
3182
3403
  const xdgConfig = process.env.XDG_CONFIG_HOME;
3183
- if (xdgConfig) return path8.join(xdgConfig, "standardagents");
3184
- return path8.join(os3.homedir(), ".config", "standardagents");
3404
+ if (xdgConfig) return path9.join(xdgConfig, "standardagents");
3405
+ return path9.join(os3.homedir(), ".config", "standardagents");
3185
3406
  }
3186
3407
  function stateFilePath() {
3187
- return path8.join(configDir(), "auth-state.json");
3408
+ return path9.join(configDir(), "auth-state.json");
3188
3409
  }
3189
3410
  function ensureStateDir() {
3190
- fs5.mkdirSync(path8.dirname(stateFilePath()), { recursive: true });
3411
+ fs8.mkdirSync(path9.dirname(stateFilePath()), { recursive: true });
3191
3412
  }
3192
3413
  function securityCommand(args) {
3193
3414
  const result = spawnSync("security", args, { encoding: "utf8" });
@@ -3230,11 +3451,11 @@ function readFromKeychain(orgId) {
3230
3451
  }
3231
3452
  function readCliAuthState() {
3232
3453
  const file = stateFilePath();
3233
- if (!fs5.existsSync(file)) {
3454
+ if (!fs8.existsSync(file)) {
3234
3455
  return { active_org_id: null, orgs: {} };
3235
3456
  }
3236
3457
  try {
3237
- const parsed = JSON.parse(fs5.readFileSync(file, "utf8"));
3458
+ const parsed = JSON.parse(fs8.readFileSync(file, "utf8"));
3238
3459
  return {
3239
3460
  active_org_id: parsed.active_org_id ?? null,
3240
3461
  orgs: parsed.orgs ?? {},
@@ -3379,18 +3600,18 @@ function stripOrgContextFromDevVars(content) {
3379
3600
  }
3380
3601
  function clearLocalOrgContext(projectPath) {
3381
3602
  const statePath = getBootstrapStatePath(projectPath);
3382
- const stateCleared = fs5.existsSync(statePath);
3603
+ const stateCleared = fs8.existsSync(statePath);
3383
3604
  clearBootstrapState(projectPath);
3384
- const devVarsPath = path8.join(projectPath, DEV_VARS_FILENAME2);
3385
- if (!fs5.existsSync(devVarsPath)) {
3605
+ const devVarsPath = path9.join(projectPath, DEV_VARS_FILENAME2);
3606
+ if (!fs8.existsSync(devVarsPath)) {
3386
3607
  return { stateCleared, envCleared: false };
3387
3608
  }
3388
- const content = fs5.readFileSync(devVarsPath, "utf-8");
3609
+ const content = fs8.readFileSync(devVarsPath, "utf-8");
3389
3610
  const stripped = stripOrgContextFromDevVars(content);
3390
3611
  if (!stripped.removed) {
3391
3612
  return { stateCleared, envCleared: false };
3392
3613
  }
3393
- fs5.writeFileSync(devVarsPath, stripped.updated, "utf-8");
3614
+ fs8.writeFileSync(devVarsPath, stripped.updated, "utf-8");
3394
3615
  return { stateCleared, envCleared: true };
3395
3616
  }
3396
3617
  function logLocalClearResult(result) {
@@ -3440,11 +3661,51 @@ async function logout(options = {}) {
3440
3661
  logger.success(`Logged out from org "${removed.org_slug}" (${removed.user_email}).`);
3441
3662
  logLocalClearResult(localResult);
3442
3663
  }
3664
+ var CHAT_DEV_HOST = "127.0.0.1";
3665
+ var CHAT_SCRIPTS = {
3666
+ vite: {
3667
+ dev: `vite --host ${CHAT_DEV_HOST}`,
3668
+ build: "vite build",
3669
+ preview: `vite preview --host ${CHAT_DEV_HOST}`
3670
+ },
3671
+ nextjs: {
3672
+ dev: `next dev --hostname ${CHAT_DEV_HOST}`,
3673
+ build: "next build",
3674
+ start: "next start"
3675
+ }
3676
+ };
3677
+ function renderChatViteConfig() {
3678
+ return `import { defineConfig, loadEnv } from 'vite'
3679
+ import react from '@vitejs/plugin-react'
3680
+ import tailwindcss from '@tailwindcss/vite'
3681
+
3682
+ export default defineConfig(({ mode }) => {
3683
+ const env = { ...loadEnv(mode, process.cwd(), ''), ...process.env }
3684
+ return {
3685
+ plugins: [
3686
+ react(),
3687
+ tailwindcss(),
3688
+ ],
3689
+ server: {
3690
+ host: '${CHAT_DEV_HOST}',
3691
+ proxy: {
3692
+ '/api': {
3693
+ target: env.VITE_AGENTBUILDER_URL || 'http://localhost:5173',
3694
+ ws: true,
3695
+ // Keep the browser's Host so the runtime sees a same-origin request.
3696
+ changeOrigin: false,
3697
+ },
3698
+ },
3699
+ },
3700
+ }
3701
+ })
3702
+ `;
3703
+ }
3443
3704
  function getReactPackageVersion() {
3444
3705
  try {
3445
- const __dirname = path8.dirname(fileURLToPath(import.meta.url));
3446
- const pkgPath = path8.resolve(__dirname, "../package.json");
3447
- const pkg = JSON.parse(fs5.readFileSync(pkgPath, "utf-8"));
3706
+ const __dirname = path9.dirname(fileURLToPath(import.meta.url));
3707
+ const pkgPath = path9.resolve(__dirname, "../package.json");
3708
+ const pkg = JSON.parse(fs8.readFileSync(pkgPath, "utf-8"));
3448
3709
  const version = pkg.version;
3449
3710
  const prereleaseMatch = version.match(/-([a-z]+)\./i);
3450
3711
  if (prereleaseMatch) {
@@ -3456,10 +3717,10 @@ function getReactPackageVersion() {
3456
3717
  }
3457
3718
  }
3458
3719
  function getChatSourceDir() {
3459
- const __dirname = path8.dirname(fileURLToPath(import.meta.url));
3460
- return path8.resolve(__dirname, "../chat");
3720
+ const __dirname = path9.dirname(fileURLToPath(import.meta.url));
3721
+ return path9.resolve(__dirname, "../chat");
3461
3722
  }
3462
- async function prompt3(question) {
3723
+ async function prompt2(question) {
3463
3724
  const rl = readline.createInterface({
3464
3725
  input: process.stdin,
3465
3726
  output: process.stdout
@@ -3498,13 +3759,13 @@ function detectPackageManager2() {
3498
3759
  if (userAgent.includes("yarn")) return "yarn";
3499
3760
  if (userAgent.includes("bun")) return "bun";
3500
3761
  }
3501
- if (fs5.existsSync("pnpm-lock.yaml")) return "pnpm";
3502
- if (fs5.existsSync("yarn.lock")) return "yarn";
3503
- if (fs5.existsSync("bun.lockb")) return "bun";
3504
- if (fs5.existsSync("package-lock.json")) return "npm";
3762
+ if (fs8.existsSync("pnpm-lock.yaml")) return "pnpm";
3763
+ if (fs8.existsSync("yarn.lock")) return "yarn";
3764
+ if (fs8.existsSync("bun.lockb")) return "bun";
3765
+ if (fs8.existsSync("package-lock.json")) return "npm";
3505
3766
  return "npm";
3506
3767
  }
3507
- async function selectPackageManager2(detected) {
3768
+ async function selectPackageManager(detected) {
3508
3769
  const options = ["npm", "pnpm", "yarn", "bun"];
3509
3770
  const detectedIndex = options.indexOf(detected);
3510
3771
  return new Promise((resolve) => {
@@ -3730,25 +3991,25 @@ minimumReleaseAgeExclude:
3730
3991
  `;
3731
3992
  }
3732
3993
  function copyDir(src, dest, skip = []) {
3733
- if (!fs5.existsSync(dest)) {
3734
- fs5.mkdirSync(dest, { recursive: true });
3994
+ if (!fs8.existsSync(dest)) {
3995
+ fs8.mkdirSync(dest, { recursive: true });
3735
3996
  }
3736
- const entries = fs5.readdirSync(src, { withFileTypes: true });
3997
+ const entries = fs8.readdirSync(src, { withFileTypes: true });
3737
3998
  for (const entry of entries) {
3738
3999
  if (skip.includes(entry.name) || /\.test\.tsx?$/.test(entry.name)) continue;
3739
- const srcPath = path8.join(src, entry.name);
3740
- const destPath = path8.join(dest, entry.name);
4000
+ const srcPath = path9.join(src, entry.name);
4001
+ const destPath = path9.join(dest, entry.name);
3741
4002
  if (entry.isDirectory()) {
3742
4003
  copyDir(srcPath, destPath, skip);
3743
4004
  } else {
3744
- fs5.copyFileSync(srcPath, destPath);
4005
+ fs8.copyFileSync(srcPath, destPath);
3745
4006
  }
3746
4007
  }
3747
4008
  }
3748
4009
  async function initChat(projectNameArg, options = {}) {
3749
4010
  const cwd = process.cwd();
3750
4011
  const chatSourceDir = getChatSourceDir();
3751
- if (!fs5.existsSync(chatSourceDir)) {
4012
+ if (!fs8.existsSync(chatSourceDir)) {
3752
4013
  logger.error("Chat source files not found. This CLI installation may be corrupted.");
3753
4014
  process.exit(1);
3754
4015
  }
@@ -3757,14 +4018,14 @@ async function initChat(projectNameArg, options = {}) {
3757
4018
  logger.log("");
3758
4019
  let projectName = projectNameArg;
3759
4020
  if (!projectName && !options.yes) {
3760
- projectName = await prompt3("Project name: ");
4021
+ projectName = await prompt2("Project name: ");
3761
4022
  }
3762
4023
  if (!projectName) {
3763
4024
  logger.error("Project name is required");
3764
4025
  process.exit(1);
3765
4026
  }
3766
- const projectPath = path8.join(cwd, projectName);
3767
- if (fs5.existsSync(projectPath)) {
4027
+ const projectPath = path9.join(cwd, projectName);
4028
+ if (fs8.existsSync(projectPath)) {
3768
4029
  logger.error(`Directory "${projectName}" already exists`);
3769
4030
  process.exit(1);
3770
4031
  }
@@ -3784,11 +4045,11 @@ async function initChat(projectNameArg, options = {}) {
3784
4045
  const detectedUrl = await detectAgentbuilderInstance();
3785
4046
  if (detectedUrl) {
3786
4047
  logger.success(`Found agentbuilder at ${detectedUrl}`);
3787
- const urlInput = await prompt3(`Agentbuilder dev server URL [${detectedUrl}]: `);
4048
+ const urlInput = await prompt2(`Standard Agents Builder dev server URL [${detectedUrl}]: `);
3788
4049
  serverUrl = urlInput || detectedUrl;
3789
4050
  } else {
3790
4051
  logger.log("\x1B[90mNo running agentbuilder instance found\x1B[0m");
3791
- const urlInput = await prompt3("Agentbuilder dev server URL [http://localhost:5173]: ");
4052
+ const urlInput = await prompt2("Standard Agents Builder dev server URL [http://localhost:5173]: ");
3792
4053
  serverUrl = urlInput || "http://localhost:5173";
3793
4054
  }
3794
4055
  if (!isValidUrl(serverUrl)) {
@@ -3801,13 +4062,13 @@ async function initChat(projectNameArg, options = {}) {
3801
4062
  if (options.yes) {
3802
4063
  pm = detectedPm;
3803
4064
  } else {
3804
- pm = await selectPackageManager2(detectedPm);
4065
+ pm = await selectPackageManager(detectedPm);
3805
4066
  logger.log("");
3806
4067
  }
3807
4068
  logger.log("");
3808
4069
  logger.info(`Creating ${framework === "vite" ? "Vite" : "Next.js"} project...`);
3809
4070
  logger.log("");
3810
- fs5.mkdirSync(projectPath, { recursive: true });
4071
+ fs8.mkdirSync(projectPath, { recursive: true });
3811
4072
  const reactVersion = getReactPackageVersion();
3812
4073
  if (framework === "vite") {
3813
4074
  await scaffoldVite(projectPath, chatSourceDir, projectName, serverUrl, reactVersion);
@@ -3844,7 +4105,7 @@ async function initChat(projectNameArg, options = {}) {
3844
4105
  devProcess.stdout?.on("data", (data) => {
3845
4106
  const text = data.toString();
3846
4107
  process.stdout.write(data);
3847
- const urlMatch = text.match(/Local:\s+(https?:\/\/localhost:\d+\/?)/);
4108
+ const urlMatch = text.match(/Local:\s+(https?:\/\/(?:localhost|127\.0\.0\.1):\d+\/?)/);
3848
4109
  if (urlMatch && !browserOpened) {
3849
4110
  openBrowser2(urlMatch[1]);
3850
4111
  }
@@ -3858,55 +4119,27 @@ async function initChat(projectNameArg, options = {}) {
3858
4119
  });
3859
4120
  }
3860
4121
  async function scaffoldVite(projectPath, chatSourceDir, projectName, serverUrl, reactVersion) {
3861
- copyDir(path8.join(chatSourceDir, "src"), path8.join(projectPath, "src"), []);
4122
+ copyDir(path9.join(chatSourceDir, "src"), path9.join(projectPath, "src"), []);
3862
4123
  logger.success("Copied src/");
3863
- const viteDir = path8.join(chatSourceDir, "vite");
3864
- let indexHtml = fs5.readFileSync(path8.join(viteDir, "index.html"), "utf-8");
4124
+ const viteDir = path9.join(chatSourceDir, "vite");
4125
+ let indexHtml = fs8.readFileSync(path9.join(viteDir, "index.html"), "utf-8");
3865
4126
  indexHtml = indexHtml.replace('src="/main.tsx"', 'src="/src/main.tsx"');
3866
- fs5.writeFileSync(path8.join(projectPath, "index.html"), indexHtml, "utf-8");
4127
+ fs8.writeFileSync(path9.join(projectPath, "index.html"), indexHtml, "utf-8");
3867
4128
  logger.success("Created index.html");
3868
- fs5.copyFileSync(path8.join(viteDir, "main.tsx"), path8.join(projectPath, "src", "main.tsx"));
4129
+ fs8.copyFileSync(path9.join(viteDir, "main.tsx"), path9.join(projectPath, "src", "main.tsx"));
3869
4130
  logger.success("Created src/main.tsx");
3870
- const viteConfig = `import { defineConfig, loadEnv } from 'vite'
3871
- import react from '@vitejs/plugin-react'
3872
- import tailwindcss from '@tailwindcss/vite'
3873
-
3874
- export default defineConfig(({ mode }) => {
3875
- const env = { ...loadEnv(mode, process.cwd(), ''), ...process.env }
3876
- return {
3877
- plugins: [
3878
- react(),
3879
- tailwindcss(),
3880
- ],
3881
- server: {
3882
- proxy: {
3883
- '/api': {
3884
- target: env.VITE_AGENTBUILDER_URL || 'http://localhost:5173',
3885
- ws: true,
3886
- // Keep the browser's Host so the runtime sees a same-origin request.
3887
- changeOrigin: false,
3888
- },
3889
- },
3890
- },
3891
- }
3892
- })
3893
- `;
3894
- fs5.writeFileSync(path8.join(projectPath, "vite.config.ts"), viteConfig, "utf-8");
4131
+ fs8.writeFileSync(path9.join(projectPath, "vite.config.ts"), renderChatViteConfig(), "utf-8");
3895
4132
  logger.success("Created vite.config.ts");
3896
- fs5.copyFileSync(path8.join(chatSourceDir, "tsconfig.json"), path8.join(projectPath, "tsconfig.json"));
3897
- const tsconfig = JSON.parse(fs5.readFileSync(path8.join(projectPath, "tsconfig.json"), "utf-8"));
4133
+ fs8.copyFileSync(path9.join(chatSourceDir, "tsconfig.json"), path9.join(projectPath, "tsconfig.json"));
4134
+ const tsconfig = JSON.parse(fs8.readFileSync(path9.join(projectPath, "tsconfig.json"), "utf-8"));
3898
4135
  tsconfig.include = ["src"];
3899
4136
  delete tsconfig.compilerOptions?.paths;
3900
- fs5.writeFileSync(path8.join(projectPath, "tsconfig.json"), JSON.stringify(tsconfig, null, 2) + "\n", "utf-8");
4137
+ fs8.writeFileSync(path9.join(projectPath, "tsconfig.json"), JSON.stringify(tsconfig, null, 2) + "\n", "utf-8");
3901
4138
  logger.success("Created tsconfig.json");
3902
- fs5.copyFileSync(path8.join(chatSourceDir, "package.json"), path8.join(projectPath, "package.json"));
3903
- const pkg = JSON.parse(fs5.readFileSync(path8.join(projectPath, "package.json"), "utf-8"));
4139
+ fs8.copyFileSync(path9.join(chatSourceDir, "package.json"), path9.join(projectPath, "package.json"));
4140
+ const pkg = JSON.parse(fs8.readFileSync(path9.join(projectPath, "package.json"), "utf-8"));
3904
4141
  pkg.name = projectName;
3905
- pkg.scripts = {
3906
- dev: "vite",
3907
- build: "vite build",
3908
- preview: "vite preview"
3909
- };
4142
+ pkg.scripts = { ...CHAT_SCRIPTS.vite };
3910
4143
  delete pkg.private;
3911
4144
  if (pkg.dependencies?.["@standardagents/react"]) {
3912
4145
  pkg.dependencies["@standardagents/react"] = reactVersion;
@@ -3915,36 +4148,36 @@ export default defineConfig(({ mode }) => {
3915
4148
  delete pkg.devDependencies?.["@tailwindcss/postcss"];
3916
4149
  delete pkg.devDependencies?.["postcss"];
3917
4150
  delete pkg.devDependencies?.["vitest"];
3918
- fs5.writeFileSync(path8.join(projectPath, "package.json"), JSON.stringify(applyChatBuildApprovals(pkg), null, 2) + "\n", "utf-8");
3919
- fs5.writeFileSync(path8.join(projectPath, "pnpm-workspace.yaml"), renderChatPnpmWorkspaceYaml(), "utf-8");
4151
+ fs8.writeFileSync(path9.join(projectPath, "package.json"), JSON.stringify(applyChatBuildApprovals(pkg), null, 2) + "\n", "utf-8");
4152
+ fs8.writeFileSync(path9.join(projectPath, "pnpm-workspace.yaml"), renderChatPnpmWorkspaceYaml(), "utf-8");
3920
4153
  logger.success("Created package.json");
3921
- const envContent = `# Agentbuilder connection
4154
+ const envContent = `# Standard Agents Builder connection
3922
4155
  VITE_AGENTBUILDER_URL=${serverUrl}
3923
4156
  `;
3924
- fs5.writeFileSync(path8.join(projectPath, ".env"), envContent, "utf-8");
4157
+ fs8.writeFileSync(path9.join(projectPath, ".env"), envContent, "utf-8");
3925
4158
  logger.success("Created .env");
3926
- fs5.writeFileSync(path8.join(projectPath, ".gitignore"), `node_modules
4159
+ fs8.writeFileSync(path9.join(projectPath, ".gitignore"), `node_modules
3927
4160
  dist
3928
4161
  .env
3929
4162
  `, "utf-8");
3930
4163
  logger.success("Created .gitignore");
3931
- let mainTsx = fs5.readFileSync(path8.join(projectPath, "src", "main.tsx"), "utf-8");
4164
+ let mainTsx = fs8.readFileSync(path9.join(projectPath, "src", "main.tsx"), "utf-8");
3932
4165
  mainTsx = mainTsx.replace(/from '\.\.\/src\//g, "from './").replace(/import '\.\.\/src\//g, "import './");
3933
- fs5.writeFileSync(path8.join(projectPath, "src", "main.tsx"), mainTsx, "utf-8");
3934
- if (fs5.existsSync(path8.join(viteDir, "favicon.svg"))) {
3935
- fs5.copyFileSync(path8.join(viteDir, "favicon.svg"), path8.join(projectPath, "favicon.svg"));
4166
+ fs8.writeFileSync(path9.join(projectPath, "src", "main.tsx"), mainTsx, "utf-8");
4167
+ if (fs8.existsSync(path9.join(viteDir, "favicon.svg"))) {
4168
+ fs8.copyFileSync(path9.join(viteDir, "favicon.svg"), path9.join(projectPath, "favicon.svg"));
3936
4169
  logger.success("Created favicon.svg");
3937
4170
  }
3938
4171
  }
3939
4172
  async function scaffoldNextjs(projectPath, chatSourceDir, projectName, serverUrl, reactVersion) {
3940
- copyDir(path8.join(chatSourceDir, "src"), path8.join(projectPath, "src"), []);
4173
+ copyDir(path9.join(chatSourceDir, "src"), path9.join(projectPath, "src"), []);
3941
4174
  logger.success("Copied src/");
3942
- const nextDir = path8.join(chatSourceDir, "next");
3943
- copyDir(path8.join(nextDir, "app"), path8.join(projectPath, "app"), []);
4175
+ const nextDir = path9.join(chatSourceDir, "next");
4176
+ copyDir(path9.join(nextDir, "app"), path9.join(projectPath, "app"), []);
3944
4177
  logger.success("Copied app/");
3945
- fs5.copyFileSync(path8.join(nextDir, "next.config.ts"), path8.join(projectPath, "next.config.ts"));
4178
+ fs8.copyFileSync(path9.join(nextDir, "next.config.ts"), path9.join(projectPath, "next.config.ts"));
3946
4179
  logger.success("Created next.config.ts");
3947
- fs5.copyFileSync(path8.join(nextDir, "postcss.config.mjs"), path8.join(projectPath, "postcss.config.mjs"));
4180
+ fs8.copyFileSync(path9.join(nextDir, "postcss.config.mjs"), path9.join(projectPath, "postcss.config.mjs"));
3948
4181
  logger.success("Created postcss.config.mjs");
3949
4182
  const tsconfig = {
3950
4183
  compilerOptions: {
@@ -3969,15 +4202,11 @@ async function scaffoldNextjs(projectPath, chatSourceDir, projectName, serverUrl
3969
4202
  include: ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
3970
4203
  exclude: ["node_modules"]
3971
4204
  };
3972
- fs5.writeFileSync(path8.join(projectPath, "tsconfig.json"), JSON.stringify(tsconfig, null, 2) + "\n", "utf-8");
4205
+ fs8.writeFileSync(path9.join(projectPath, "tsconfig.json"), JSON.stringify(tsconfig, null, 2) + "\n", "utf-8");
3973
4206
  logger.success("Created tsconfig.json");
3974
- const pkg = JSON.parse(fs5.readFileSync(path8.join(chatSourceDir, "package.json"), "utf-8"));
4207
+ const pkg = JSON.parse(fs8.readFileSync(path9.join(chatSourceDir, "package.json"), "utf-8"));
3975
4208
  pkg.name = projectName;
3976
- pkg.scripts = {
3977
- dev: "next dev",
3978
- build: "next build",
3979
- start: "next start"
3980
- };
4209
+ pkg.scripts = { ...CHAT_SCRIPTS.nextjs };
3981
4210
  delete pkg.private;
3982
4211
  if (pkg.dependencies?.["@standardagents/react"]) {
3983
4212
  pkg.dependencies["@standardagents/react"] = reactVersion;
@@ -3986,26 +4215,26 @@ async function scaffoldNextjs(projectPath, chatSourceDir, projectName, serverUrl
3986
4215
  delete pkg.devDependencies?.["@vitejs/plugin-react"];
3987
4216
  delete pkg.devDependencies?.["vite"];
3988
4217
  delete pkg.devDependencies?.["vitest"];
3989
- fs5.writeFileSync(path8.join(projectPath, "package.json"), JSON.stringify(applyChatBuildApprovals(pkg), null, 2) + "\n", "utf-8");
3990
- fs5.writeFileSync(path8.join(projectPath, "pnpm-workspace.yaml"), renderChatPnpmWorkspaceYaml(), "utf-8");
4218
+ fs8.writeFileSync(path9.join(projectPath, "package.json"), JSON.stringify(applyChatBuildApprovals(pkg), null, 2) + "\n", "utf-8");
4219
+ fs8.writeFileSync(path9.join(projectPath, "pnpm-workspace.yaml"), renderChatPnpmWorkspaceYaml(), "utf-8");
3991
4220
  logger.success("Created package.json");
3992
- const envContent = `# Agentbuilder connection
4221
+ const envContent = `# Standard Agents Builder connection
3993
4222
  NEXT_PUBLIC_AGENTBUILDER_URL=${serverUrl}
3994
4223
  `;
3995
- fs5.writeFileSync(path8.join(projectPath, ".env.local"), envContent, "utf-8");
4224
+ fs8.writeFileSync(path9.join(projectPath, ".env.local"), envContent, "utf-8");
3996
4225
  logger.success("Created .env.local");
3997
- fs5.writeFileSync(path8.join(projectPath, ".gitignore"), `node_modules
4226
+ fs8.writeFileSync(path9.join(projectPath, ".gitignore"), `node_modules
3998
4227
  .next
3999
4228
  out
4000
4229
  .env.local
4001
4230
  `, "utf-8");
4002
4231
  logger.success("Created .gitignore");
4003
- let layoutTsx = fs5.readFileSync(path8.join(projectPath, "app", "layout.tsx"), "utf-8");
4232
+ let layoutTsx = fs8.readFileSync(path9.join(projectPath, "app", "layout.tsx"), "utf-8");
4004
4233
  layoutTsx = layoutTsx.replace(/from '\.\.\/\.\.\/src\//g, "from '../src/");
4005
- fs5.writeFileSync(path8.join(projectPath, "app", "layout.tsx"), layoutTsx, "utf-8");
4006
- let pageTsx = fs5.readFileSync(path8.join(projectPath, "app", "page.tsx"), "utf-8");
4234
+ fs8.writeFileSync(path9.join(projectPath, "app", "layout.tsx"), layoutTsx, "utf-8");
4235
+ let pageTsx = fs8.readFileSync(path9.join(projectPath, "app", "page.tsx"), "utf-8");
4007
4236
  pageTsx = pageTsx.replace(/from '\.\.\/\.\.\/src\//g, "from '../src/");
4008
- fs5.writeFileSync(path8.join(projectPath, "app", "page.tsx"), pageTsx, "utf-8");
4237
+ fs8.writeFileSync(path9.join(projectPath, "app", "page.tsx"), pageTsx, "utf-8");
4009
4238
  }
4010
4239
  async function selectAgent(agents) {
4011
4240
  return new Promise((resolve) => {
@@ -4127,11 +4356,11 @@ async function selectItemModes(items, _agentName) {
4127
4356
  });
4128
4357
  }
4129
4358
  function isStandardAgentsProject() {
4130
- if (!fs5.existsSync("agents")) {
4359
+ if (!fs8.existsSync("agents")) {
4131
4360
  return false;
4132
4361
  }
4133
4362
  try {
4134
- const pkgJson = JSON.parse(fs5.readFileSync("package.json", "utf-8"));
4363
+ const pkgJson = JSON.parse(fs8.readFileSync("package.json", "utf-8"));
4135
4364
  const deps = { ...pkgJson.dependencies, ...pkgJson.devDependencies };
4136
4365
  return "@standardagents/builder" in deps;
4137
4366
  } catch {
@@ -4213,14 +4442,14 @@ async function pack(agentName, options) {
4213
4442
  sharedWith: agent.sharedWith
4214
4443
  });
4215
4444
  }
4216
- for (const prompt5 of analysis.constituents.prompts) {
4445
+ for (const prompt4 of analysis.constituents.prompts) {
4217
4446
  selectionItems.push({
4218
- name: prompt5.name,
4447
+ name: prompt4.name,
4219
4448
  type: "prompt",
4220
- filePath: prompt5.filePath,
4221
- mode: prompt5.sharedWith.length > 0 ? "copy" : "extract",
4222
- isShared: prompt5.sharedWith.length > 0,
4223
- sharedWith: prompt5.sharedWith
4449
+ filePath: prompt4.filePath,
4450
+ mode: prompt4.sharedWith.length > 0 ? "copy" : "extract",
4451
+ isShared: prompt4.sharedWith.length > 0,
4452
+ sharedWith: prompt4.sharedWith
4224
4453
  });
4225
4454
  }
4226
4455
  for (const tool of analysis.constituents.tools) {
@@ -4275,7 +4504,7 @@ async function pack(agentName, options) {
4275
4504
  }));
4276
4505
  console.log("");
4277
4506
  }
4278
- const outputDir = options.output || path8.join(rootDir, "agents", "packed");
4507
+ const outputDir = options.output || path9.join(rootDir, "agents", "packed");
4279
4508
  logger.info(`Packing to: ${outputDir}`);
4280
4509
  const result = await packingService.pack({
4281
4510
  agentName: selectedAgent,
@@ -4318,11 +4547,11 @@ function registerPackCommand(program2) {
4318
4547
  program2.command("pack [agent-name]").description("Pack an agent with all its dependencies").option("--output <dir>", "Output directory (default: agents/packed)").option("--npm", "Generate npm-ready package structure").option("--version <version>", "Package version (default: 1.0.0)").option("--no-remove", "Keep original files after packing").option("--no-interactive", "Skip interactive item mode selector").action(pack);
4319
4548
  }
4320
4549
  function isStandardAgentsProject2() {
4321
- if (!fs5.existsSync("agents")) {
4550
+ if (!fs8.existsSync("agents")) {
4322
4551
  return false;
4323
4552
  }
4324
4553
  try {
4325
- const pkgJson = JSON.parse(fs5.readFileSync("package.json", "utf-8"));
4554
+ const pkgJson = JSON.parse(fs8.readFileSync("package.json", "utf-8"));
4326
4555
  const deps = { ...pkgJson.dependencies, ...pkgJson.devDependencies };
4327
4556
  return "@standardagents/builder" in deps;
4328
4557
  } catch {
@@ -4383,7 +4612,7 @@ async function unpack(pkgIdentifier) {
4383
4612
  console.log("");
4384
4613
  logger.info("Created files:");
4385
4614
  for (const file of result.filesGenerated) {
4386
- const relPath = path8.relative(rootDir, file);
4615
+ const relPath = path9.relative(rootDir, file);
4387
4616
  console.log(` - ${relPath}`);
4388
4617
  }
4389
4618
  }
@@ -4493,8 +4722,8 @@ var PROJECT_SIGNAL_PATHS = [
4493
4722
  "vite.config.mjs"
4494
4723
  ];
4495
4724
  function hasProjectSignals(cwd) {
4496
- const hits = PROJECT_SIGNAL_PATHS.filter((signal) => fs5.existsSync(path8.join(cwd, signal))).length;
4497
- return hits >= 2 || fs5.existsSync(path8.join(cwd, ".agents"));
4725
+ const hits = PROJECT_SIGNAL_PATHS.filter((signal) => fs8.existsSync(path9.join(cwd, signal))).length;
4726
+ return hits >= 2 || fs8.existsSync(path9.join(cwd, ".agents"));
4498
4727
  }
4499
4728
  function detectCliDirectoryContext(cwd = process.cwd()) {
4500
4729
  if (!hasProjectSignals(cwd)) {
@@ -4614,7 +4843,7 @@ function HomeMenu({ contextLabel, actions, onSelect }) {
4614
4843
  });
4615
4844
  return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", paddingX: 1, children: [
4616
4845
  /* @__PURE__ */ jsxs(Box, { borderStyle: "double", borderColor: "cyan", paddingX: 1, flexDirection: "column", children: [
4617
- /* @__PURE__ */ jsx(Text, { color: "cyanBright", bold: true, children: "STANDARDAGENTS CLI" }),
4846
+ /* @__PURE__ */ jsx(Text, { color: "cyanBright", bold: true, children: "STANDARD AGENTS CLI" }),
4618
4847
  /* @__PURE__ */ jsx(Text, { color: "gray", children: "Command Center" })
4619
4848
  ] }),
4620
4849
  /* @__PURE__ */ jsx(Box, { marginTop: 1, flexDirection: "column", children: BRAND_LINES.map((line) => /* @__PURE__ */ jsx(Text, { color: "cyan", children: line }, line)) }),
@@ -4667,13 +4896,13 @@ async function runHomeTui(cwd = process.cwd()) {
4667
4896
  }
4668
4897
  var DEFAULT_SKILL_NAME = "agentbuilder";
4669
4898
  function resolveCodexHome(env = process.env, homeDir = os3.homedir()) {
4670
- return env.CODEX_HOME || path8.join(homeDir, ".codex");
4899
+ return env.CODEX_HOME || path9.join(homeDir, ".codex");
4671
4900
  }
4672
4901
  function resolveClaudeHome(homeDir = os3.homedir()) {
4673
- return path8.join(homeDir, ".claude");
4902
+ return path9.join(homeDir, ".claude");
4674
4903
  }
4675
4904
  function resolveAgentsHome(homeDir = os3.homedir()) {
4676
- return path8.join(homeDir, ".agents");
4905
+ return path9.join(homeDir, ".agents");
4677
4906
  }
4678
4907
  function normalizeTargetId(target) {
4679
4908
  if (target === "codex" || target === "agents") {
@@ -4686,12 +4915,12 @@ function expandHomePath(inputPath, homeDir = os3.homedir()) {
4686
4915
  return homeDir;
4687
4916
  }
4688
4917
  if (inputPath.startsWith("~/")) {
4689
- return path8.join(homeDir, inputPath.slice(2));
4918
+ return path9.join(homeDir, inputPath.slice(2));
4690
4919
  }
4691
4920
  return inputPath;
4692
4921
  }
4693
4922
  function buildInstallTargets(options = {}, env = process.env, homeDir = os3.homedir()) {
4694
- const customRoot = options.dir ? path8.resolve(expandHomePath(options.dir, homeDir)) : null;
4923
+ const customRoot = options.dir ? path9.resolve(expandHomePath(options.dir, homeDir)) : null;
4695
4924
  const agentsHome = resolveAgentsHome(homeDir);
4696
4925
  const claudeHome = resolveClaudeHome(homeDir);
4697
4926
  return [
@@ -4699,15 +4928,15 @@ function buildInstallTargets(options = {}, env = process.env, homeDir = os3.home
4699
4928
  id: "agents",
4700
4929
  label: "Codex and other coding agents",
4701
4930
  summary: "Agent Skills folder read by Codex, Cursor, Gemini CLI, GitHub Copilot, OpenCode, and others",
4702
- detected: fs5.existsSync(agentsHome) || fs5.existsSync(resolveCodexHome(env, homeDir)),
4703
- installPath: customRoot ?? path8.join(agentsHome, "skills")
4931
+ detected: fs8.existsSync(agentsHome) || fs8.existsSync(resolveCodexHome(env, homeDir)),
4932
+ installPath: customRoot ?? path9.join(agentsHome, "skills")
4704
4933
  },
4705
4934
  {
4706
4935
  id: "claude",
4707
4936
  label: "Claude Code",
4708
4937
  summary: "Agent Skills folder read by Claude Code",
4709
- detected: fs5.existsSync(claudeHome),
4710
- installPath: customRoot ?? path8.join(claudeHome, "skills")
4938
+ detected: fs8.existsSync(claudeHome),
4939
+ installPath: customRoot ?? path9.join(claudeHome, "skills")
4711
4940
  }
4712
4941
  ];
4713
4942
  }
@@ -4727,8 +4956,8 @@ function findSupersededInstalls(targetId, skillName = DEFAULT_SKILL_NAME, option
4727
4956
  if (options.dir) {
4728
4957
  return [];
4729
4958
  }
4730
- const superseded = normalizeTargetId(targetId) === "claude" ? path8.join(resolveClaudeHome(homeDir), "agents", `${skillName}.md`) : path8.join(resolveCodexHome(env, homeDir), "skills", skillName);
4731
- return fs5.existsSync(superseded) ? [superseded] : [];
4959
+ const superseded = normalizeTargetId(targetId) === "claude" ? path9.join(resolveClaudeHome(homeDir), "agents", `${skillName}.md`) : path9.join(resolveCodexHome(env, homeDir), "skills", skillName);
4960
+ return fs8.existsSync(superseded) ? [superseded] : [];
4732
4961
  }
4733
4962
  async function selectInstallTarget(targets) {
4734
4963
  return new Promise((resolve) => {
@@ -4737,7 +4966,7 @@ async function selectInstallTarget(targets) {
4737
4966
  let selectedIndex = 0;
4738
4967
  const render3 = (initial = false) => {
4739
4968
  const lines = [];
4740
- lines.push("Choose where to install the AgentBuilder skill:");
4969
+ lines.push("Choose where to install the Standard Agents Builder skill:");
4741
4970
  lines.push("");
4742
4971
  for (let i = 0; i < targets.length; i++) {
4743
4972
  const target = targets[i];
@@ -4792,8 +5021,8 @@ async function selectInstallTarget(targets) {
4792
5021
  }
4793
5022
  async function installBundledSkill(targetId, skillName = DEFAULT_SKILL_NAME, options = {}) {
4794
5023
  const target = resolveSelectedTarget(targetId, options);
4795
- const targetDir = path8.join(target.installPath, skillName);
4796
- if (fs5.existsSync(targetDir) && !options.force) {
5024
+ const targetDir = path9.join(target.installPath, skillName);
5025
+ if (fs8.existsSync(targetDir) && !options.force) {
4797
5026
  throw new Error(
4798
5027
  `Skill already exists at ${targetDir}. Re-run with --force to overwrite it.`
4799
5028
  );
@@ -4802,14 +5031,14 @@ async function installBundledSkill(targetId, skillName = DEFAULT_SKILL_NAME, opt
4802
5031
  overwrite: options.force ?? false
4803
5032
  });
4804
5033
  }
4805
- function isInteractiveTerminal() {
5034
+ function isInteractiveTerminal2() {
4806
5035
  return Boolean(process.stdin.isTTY && process.stdout.isTTY);
4807
5036
  }
4808
5037
  async function skill(options = {}) {
4809
5038
  try {
4810
- const selectedTarget = options.agent ? resolveSelectedTarget(options.agent, options) : isInteractiveTerminal() ? await selectInstallTarget(buildInstallTargets(options)) : resolveSelectedTarget("agents", options);
5039
+ const selectedTarget = options.agent ? resolveSelectedTarget(options.agent, options) : isInteractiveTerminal2() ? await selectInstallTarget(buildInstallTargets(options)) : resolveSelectedTarget("agents", options);
4811
5040
  logger.log("");
4812
- logger.info(`Installing AgentBuilder skill into ${selectedTarget.label}...`);
5041
+ logger.info(`Installing Standard Agents Builder skill into ${selectedTarget.label}...`);
4813
5042
  const installedPath = await installBundledSkill(
4814
5043
  selectedTarget.id,
4815
5044
  DEFAULT_SKILL_NAME,
@@ -4821,7 +5050,7 @@ async function skill(options = {}) {
4821
5050
  logger.log("");
4822
5051
  logger.log("Next steps:");
4823
5052
  logger.log(` Restart ${selectedTarget.id === "claude" ? "Claude Code" : "your coding agent"} if it is already running`);
4824
- logger.log(` Edit ${path8.join(installedPath, "SKILL.md")} to continue customizing the skill`);
5053
+ logger.log(` Edit ${path9.join(installedPath, "SKILL.md")} to continue customizing the skill`);
4825
5054
  for (const superseded of findSupersededInstalls(
4826
5055
  selectedTarget.id,
4827
5056
  DEFAULT_SKILL_NAME,
@@ -4949,24 +5178,24 @@ function parseEnvFile(content) {
4949
5178
  return result;
4950
5179
  }
4951
5180
  function findProjectRoot(startDir = process.cwd()) {
4952
- let currentDir = path8.resolve(startDir);
5181
+ let currentDir = path9.resolve(startDir);
4953
5182
  while (true) {
4954
- if (fs5.existsSync(path8.join(currentDir, "package.json"))) {
5183
+ if (fs8.existsSync(path9.join(currentDir, "package.json"))) {
4955
5184
  return currentDir;
4956
5185
  }
4957
- const parentDir = path8.dirname(currentDir);
5186
+ const parentDir = path9.dirname(currentDir);
4958
5187
  if (parentDir === currentDir) {
4959
- return path8.resolve(startDir);
5188
+ return path9.resolve(startDir);
4960
5189
  }
4961
5190
  currentDir = parentDir;
4962
5191
  }
4963
5192
  }
4964
5193
  function readProjectPackageJson(projectRoot) {
4965
- const packagePath = path8.join(projectRoot, "package.json");
4966
- if (!fs5.existsSync(packagePath)) {
5194
+ const packagePath = path9.join(projectRoot, "package.json");
5195
+ if (!fs8.existsSync(packagePath)) {
4967
5196
  return {};
4968
5197
  }
4969
- return JSON.parse(fs5.readFileSync(packagePath, "utf8"));
5198
+ return JSON.parse(fs8.readFileSync(packagePath, "utf8"));
4970
5199
  }
4971
5200
  function getDeclaredProviderPackages(projectRoot) {
4972
5201
  const pkg = readProjectPackageJson(projectRoot);
@@ -4983,23 +5212,23 @@ function resolvePackageEntry(packageName, projectRoot) {
4983
5212
  if (!packageDir) {
4984
5213
  return null;
4985
5214
  }
4986
- const packageJsonPath = path8.join(packageDir, "package.json");
5215
+ const packageJsonPath = path9.join(packageDir, "package.json");
4987
5216
  try {
4988
- const packageJson = JSON.parse(fs5.readFileSync(packageJsonPath, "utf8"));
5217
+ const packageJson = JSON.parse(fs8.readFileSync(packageJsonPath, "utf8"));
4989
5218
  const exportPath = resolvePackageExportPath(packageJson.exports) || packageJson.main || "index.js";
4990
- return path8.join(packageDir, exportPath);
5219
+ return path9.join(packageDir, exportPath);
4991
5220
  } catch {
4992
5221
  return null;
4993
5222
  }
4994
5223
  }
4995
5224
  function findInstalledPackageDir(packageName, projectRoot) {
4996
- let currentDir = path8.resolve(projectRoot);
5225
+ let currentDir = path9.resolve(projectRoot);
4997
5226
  while (true) {
4998
- const candidate = path8.join(currentDir, "node_modules", ...packageName.split("/"));
4999
- if (fs5.existsSync(candidate)) {
5227
+ const candidate = path9.join(currentDir, "node_modules", ...packageName.split("/"));
5228
+ if (fs8.existsSync(candidate)) {
5000
5229
  return candidate;
5001
5230
  }
5002
- const parentDir = path8.dirname(currentDir);
5231
+ const parentDir = path9.dirname(currentDir);
5003
5232
  if (parentDir === currentDir) {
5004
5233
  return null;
5005
5234
  }
@@ -5031,9 +5260,9 @@ function loadProjectEnv(projectRoot, processEnv = process.env) {
5031
5260
  const result = {};
5032
5261
  const envFiles = [".env", ".env.local", ".dev.vars", ".dev.vars.local"];
5033
5262
  for (const fileName of envFiles) {
5034
- const filePath = path8.join(projectRoot, fileName);
5035
- if (!fs5.existsSync(filePath)) continue;
5036
- Object.assign(result, parseEnvFile(fs5.readFileSync(filePath, "utf8")));
5263
+ const filePath = path9.join(projectRoot, fileName);
5264
+ if (!fs8.existsSync(filePath)) continue;
5265
+ Object.assign(result, parseEnvFile(fs8.readFileSync(filePath, "utf8")));
5037
5266
  }
5038
5267
  for (const [key, value] of Object.entries(processEnv)) {
5039
5268
  if (typeof value === "string") {
@@ -5284,6 +5513,17 @@ async function availableModels(options = {}) {
5284
5513
  writeError(message);
5285
5514
  }
5286
5515
  }
5516
+
5517
+ // src/utils/git-hosts.ts
5518
+ var STANDARD_AGENTS_GIT_HOSTS = [
5519
+ "git.standardagents.ai",
5520
+ "git.standardagentbuilder.com"
5521
+ ];
5522
+ function isStandardAgentsGitRequest(protocol, host) {
5523
+ return protocol.trim().toLowerCase() === "https" && STANDARD_AGENTS_GIT_HOSTS.includes(host.trim().toLowerCase());
5524
+ }
5525
+
5526
+ // src/commands/git-credential.ts
5287
5527
  var GIT_LOGIN_COMMAND = "npx @standardagents/cli@latest git-login";
5288
5528
  function parseKeyValueLines(input) {
5289
5529
  const result = {};
@@ -5296,11 +5536,11 @@ function parseKeyValueLines(input) {
5296
5536
  return result;
5297
5537
  }
5298
5538
  function findDotDevVars(startDir = process.cwd()) {
5299
- let current = path8.resolve(startDir);
5539
+ let current = path9.resolve(startDir);
5300
5540
  while (true) {
5301
- const candidate = path8.join(current, ".dev.vars");
5302
- if (fs5.existsSync(candidate)) return candidate;
5303
- const parent = path8.dirname(current);
5541
+ const candidate = path9.join(current, ".dev.vars");
5542
+ if (fs8.existsSync(candidate)) return candidate;
5543
+ const parent = path9.dirname(current);
5304
5544
  if (parent === current) return null;
5305
5545
  current = parent;
5306
5546
  }
@@ -5308,16 +5548,9 @@ function findDotDevVars(startDir = process.cwd()) {
5308
5548
  function normalizeEndpoint(value) {
5309
5549
  return value.replace(/\/+$/, "");
5310
5550
  }
5311
- function normalizeGitHost(host) {
5312
- return host.trim().toLowerCase().replace(/:\d+$/, "");
5313
- }
5314
- function isStandardAgentsGitHost(host) {
5315
- const normalized = normalizeGitHost(host);
5316
- return normalized === "standardagents.ai" || normalized.endsWith(".standardagents.ai") || normalized === "standardagentbuilder.com" || normalized.endsWith(".standardagentbuilder.com") || normalized === "artifacts.cloudflare.net" || normalized.endsWith(".artifacts.cloudflare.net") || normalized === "artifacts.cloudflare.com" || normalized.endsWith(".artifacts.cloudflare.com") || normalized === "git.cloudflare.com";
5317
- }
5318
5551
  function loadLocalConfig(options) {
5319
5552
  const envPath = findDotDevVars(options.startDir);
5320
- const fileVars = envPath ? parseKeyValueLines(fs5.readFileSync(envPath, "utf-8")) : {};
5553
+ const fileVars = envPath ? parseKeyValueLines(fs8.readFileSync(envPath, "utf-8")) : {};
5321
5554
  const endpoint = normalizeEndpoint(
5322
5555
  options.endpoint || process.env.STANDARD_AGENTS_API_URL || process.env.PLATFORM_ENDPOINT || fileVars.STANDARD_AGENTS_API_URL || fileVars.PLATFORM_ENDPOINT || ""
5323
5556
  );
@@ -5348,9 +5581,9 @@ function loadLocalConfig(options) {
5348
5581
  }
5349
5582
  function remoteFromCredentialRequest(request) {
5350
5583
  if (!request.protocol || !request.host) return null;
5351
- if (!isStandardAgentsGitHost(request.host)) return null;
5584
+ if (!isStandardAgentsGitRequest(request.protocol, request.host)) return null;
5352
5585
  const repoPath = request.path ? `/${request.path.replace(/^\/+/, "")}` : "";
5353
- return `${request.protocol}://${normalizeGitHost(request.host)}${repoPath}`;
5586
+ return `https://${request.host.trim().toLowerCase()}${repoPath}`;
5354
5587
  }
5355
5588
  async function readStdin() {
5356
5589
  const chunks = [];
@@ -5414,7 +5647,10 @@ password=${tokenSecret}
5414
5647
  `);
5415
5648
  }
5416
5649
  var DEFAULT_GIT_HELPER_COMMAND = "!npx -y @standardagents/cli@latest git-credential";
5417
- var STANDARD_AGENTS_GIT_CREDENTIAL_URL_PATTERNS = [
5650
+ var STANDARD_AGENTS_GIT_CREDENTIAL_URL_PATTERNS = STANDARD_AGENTS_GIT_HOSTS.map(
5651
+ (host) => `https://${host}`
5652
+ );
5653
+ var RETIRED_GIT_CREDENTIAL_URL_PATTERNS = [
5418
5654
  "https://standardagents.ai",
5419
5655
  "https://*.standardagents.ai",
5420
5656
  "https://standardagentbuilder.com",
@@ -5425,7 +5661,7 @@ var STANDARD_AGENTS_GIT_CREDENTIAL_URL_PATTERNS = [
5425
5661
  "https://*.artifacts.cloudflare.com",
5426
5662
  "https://git.cloudflare.com"
5427
5663
  ];
5428
- function prompt4(question) {
5664
+ function prompt3(question) {
5429
5665
  const rl = readline.createInterface({
5430
5666
  input: process.stdin,
5431
5667
  output: process.stdout
@@ -5485,6 +5721,16 @@ function configureStandardAgentsGitCredentials(options = {}) {
5485
5721
  runGit(["config", "--global", "--add", key, helperCommand], runner);
5486
5722
  helperAdded = true;
5487
5723
  }
5724
+ for (const pattern of RETIRED_GIT_CREDENTIAL_URL_PATTERNS) {
5725
+ const key = `credential.${pattern}.helper`;
5726
+ const existing = readGlobalConfigValues(runner, key) ?? [];
5727
+ if (!existing.some((value) => isStandardAgentsHelper(value, helperCommand))) continue;
5728
+ const kept = existing.filter((value) => value.trim() !== "" && !isStandardAgentsHelper(value, helperCommand));
5729
+ runGit(["config", "--global", "--unset-all", key], runner);
5730
+ for (const value of kept) {
5731
+ runGit(["config", "--global", "--add", key, value], runner);
5732
+ }
5733
+ }
5488
5734
  const generic = readGlobalConfigValues(runner, "credential.helper") ?? [];
5489
5735
  for (const value of new Set(generic.filter((entry) => isStandardAgentsHelper(entry, helperCommand)))) {
5490
5736
  runner(["config", "--global", "--unset-all", "--fixed-value", "credential.helper", value]);
@@ -5528,7 +5774,7 @@ async function completeBrowserGitLogin(options, endpoint) {
5528
5774
  if (!process.stdin.isTTY) {
5529
5775
  throw new Error("Non-interactive shell detected. Run: npx @standardagents/cli git-login --bootstrap <code>");
5530
5776
  }
5531
- const input = await prompt4("Bootstrap code or command: ");
5777
+ const input = await prompt3("Bootstrap code or command: ");
5532
5778
  const bootstrapCode = parseBootstrapCodeInput(input);
5533
5779
  if (!bootstrapCode) {
5534
5780
  if (sessionId) {
@@ -5603,14 +5849,14 @@ function resolveDiagConfig(options, env = process.env, fetchImpl) {
5603
5849
  const resolvedFetch = typeof fetchImpl === "function" ? fetchImpl : fetch;
5604
5850
  return { endpoint, token, json: Boolean(options.json), fetchImpl: resolvedFetch };
5605
5851
  }
5606
- async function apiGet(config, path15) {
5607
- return apiRequest(config, path15, "GET");
5852
+ async function apiGet(config, path16) {
5853
+ return apiRequest(config, path16, "GET");
5608
5854
  }
5609
- async function apiRequest(config, path15, method, body) {
5855
+ async function apiRequest(config, path16, method, body) {
5610
5856
  const headers = { Accept: "application/json" };
5611
5857
  if (config.token) headers.Authorization = `Bearer ${config.token}`;
5612
5858
  if (body !== void 0) headers["Content-Type"] = "application/json";
5613
- const response = await config.fetchImpl(`${config.endpoint}${path15}`, {
5859
+ const response = await config.fetchImpl(`${config.endpoint}${path16}`, {
5614
5860
  method,
5615
5861
  headers,
5616
5862
  body: body === void 0 ? void 0 : JSON.stringify(body)
@@ -5623,13 +5869,13 @@ async function apiRequest(config, path15, method, body) {
5623
5869
  if (parsed.error) detail = parsed.error;
5624
5870
  } catch {
5625
5871
  }
5626
- throw new Error(`${method} ${path15} \u2192 HTTP ${response.status}: ${detail}`);
5872
+ throw new Error(`${method} ${path16} \u2192 HTTP ${response.status}: ${detail}`);
5627
5873
  }
5628
5874
  try {
5629
5875
  return JSON.parse(text);
5630
5876
  } catch {
5631
5877
  throw new Error(
5632
- `${method} ${path15} returned non-JSON (is this an AgentBuilder instance URL?): ${text.slice(0, 120)}`
5878
+ `${method} ${path16} returned non-JSON (is this a Standard Agents Builder instance URL?): ${text.slice(0, 120)}`
5633
5879
  );
5634
5880
  }
5635
5881
  }
@@ -5996,9 +6242,9 @@ async function settleStdinForInitHandoff(stdin = process.stdin) {
5996
6242
  }
5997
6243
  }
5998
6244
  var program = new Command();
5999
- program.name("agents").description("CLI tool for Standard Agents / AgentBuilder").version("0.45.2");
6000
- program.command("init [project-name]").description("Create a new Standard Agents project").option("-y, --yes", "Skip prompts and use defaults").option("--local", "Use local project scaffolding instead of browser platform onboarding").option("--cli", "Use classic line-by-line CLI prompts instead of the TUI wizard").option("--api-url <url>", "Standard Agents platform API URL").option("--endpoint <url>", "Platform API endpoint for auth/bootstrap exchange").option("--package-manager <manager>", "Package manager for generated project: npm, pnpm, yarn, or bun").option("--template <template>", "Vite template to use", "vanilla-ts").option("--workspace", "Link local @standardagents packages with pnpm outside workspace membership").option("--no-dev", "Clone and configure the project without starting the dev server").addOption(new Option("--bootstrap <code>", "Exchange a web onboarding bootstrap code")).action(init);
6001
- program.command("login").description("Authenticate this machine (or use --bootstrap for project bootstrap auth)").option("--bootstrap <code>", "Bootstrap code from web onboarding").option("--endpoint <url>", "Platform API endpoint (default: https://api.standardagents.ai)").option("--no-open", "Do not auto-open browser URL").action(login);
6245
+ program.name("agents").description("CLI tool for Standard Agents Builder").version("0.45.3");
6246
+ registerInitCommand(program);
6247
+ program.command("login").description("Link this project to your Standard Agents account (opens the browser, or use --bootstrap)").option("--bootstrap <code>", "Setup code from the project Overview page in the Standard Agents dashboard").option("--endpoint <url>", "Platform API endpoint (default: https://api.standardagents.ai)").option("--no-open", "Do not auto-open browser URL").action(login);
6002
6248
  program.command("logout").description("Clear stored Standard Agents auth and local org-scoped project auth").option("--org <org-id-or-slug>", "Org ID or slug to logout (defaults to active org)").option("--endpoint <url>", "Platform API endpoint (default: https://api.standardagents.ai)").action(logout);
6003
6249
  program.command("scaffold").description("Add Standard Agents to an existing Vite project").option("--force", "Overwrite existing configuration").action(scaffold);
6004
6250
  program.command("init-chat [project-name]").description("Scaffold a frontend chat application").option("-y, --yes", "Skip prompts and use defaults").option("--framework <framework>", "Framework to use (vite or nextjs)").action(initChat);
@@ -6008,14 +6254,17 @@ program.command("deploy").description("Push the current branch to the Standard A
6008
6254
  program.command("git-credential <operation>").description("Git credential helper for Standard Agents platform repositories").option("--endpoint <url>", "Platform API endpoint").action(gitCredential);
6009
6255
  program.command("git-login").description("Authenticate Git for Standard Agents platform repositories").option("--bootstrap <code>", "Bootstrap code from web onboarding").option("--endpoint <url>", "Platform API endpoint (default: https://api.standardagents.ai)").option("--helper-command <command>", "Credential helper command to add to global git config").option("--no-config", "Store Git auth but do not update global git config").option("--no-open", "Do not auto-open browser URL").action(gitLogin);
6010
6256
  program.command("support-files").description("Write generated local support files for a Standard Agents platform repository").option("--project-name <name>", "Project name to use in the generated package manifest").option("--package-manager <manager>", "Package manager: npm, pnpm, yarn, or bun").action(supportFiles);
6011
- program.command("skill").description("Install the bundled AgentBuilder skill for your coding agent").option("--agent <target>", "Install target: agents (Codex and other coding agents) or claude").option("--dir <path>", "Install directory override for the selected target").option("--force", "Overwrite an existing installed skill").action(skill);
6257
+ program.command("skill").description("Install the bundled Standard Agents Builder skill for your coding agent").option("--agent <target>", "Install target: agents (Codex and other coding agents) or claude").option("--dir <path>", "Install directory override for the selected target").option("--force", "Overwrite an existing installed skill").action(skill);
6012
6258
  program.command("current-models").description("Print the live curated model guide from standardagentspec.com").option("--url <url>", "Override the models markdown URL").action(currentModels);
6013
6259
  program.command("available-models").description("List every available model for one configured provider in the current project").option("--provider <provider>", "Provider to query, for example cerebras or openai").action(availableModels);
6014
6260
  registerDiagCommand(program);
6015
6261
  async function run() {
6016
6262
  const userArgs = process.argv.slice(2);
6017
- const isInteractiveTerminal2 = Boolean(process.stdin.isTTY && process.stdout.isTTY);
6018
- if (userArgs.length === 0 && isInteractiveTerminal2) {
6263
+ if (userArgs[0] !== "git-credential") {
6264
+ assertSupportedNodeVersion();
6265
+ }
6266
+ const isInteractiveTerminal3 = Boolean(process.stdin.isTTY && process.stdout.isTTY);
6267
+ if (userArgs.length === 0 && isInteractiveTerminal3) {
6019
6268
  while (true) {
6020
6269
  const selection = await runHomeTui();
6021
6270
  if (!selection) return;
@@ -6023,15 +6272,10 @@ async function run() {
6023
6272
  await settleStdinForInitHandoff();
6024
6273
  process.stdout.write("\x1B[2J\x1B[H");
6025
6274
  try {
6026
- await init(void 0, { returnToHomeOnCancel: true });
6027
- } catch (error) {
6275
+ await init();
6276
+ } finally {
6028
6277
  restoreTuiTerminal();
6029
- if (isInitWizardReturnToHomeError(error)) {
6030
- continue;
6031
- }
6032
- throw error;
6033
6278
  }
6034
- restoreTuiTerminal();
6035
6279
  return;
6036
6280
  }
6037
6281
  await program.parseAsync(selection.argv, { from: "user" });