replicas-cli 0.3.435 → 0.3.436

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.cjs +277 -121
  2. package/package.json +1 -1
package/dist/index.cjs CHANGED
@@ -4958,7 +4958,7 @@ function isRef(value) {
4958
4958
  function cloneIssues(issues) {
4959
4959
  return issues.map((iss) => iss.path ? { ...iss, path: iss.path.slice() } : { ...iss });
4960
4960
  }
4961
- function isRecursive(inst, stack, resolve3) {
4961
+ function isRecursive(inst, stack, resolve4) {
4962
4962
  const cached2 = recursive.get(inst);
4963
4963
  if (cached2 !== void 0)
4964
4964
  return cached2 ? PROVEN : NONE;
@@ -4968,7 +4968,7 @@ function isRecursive(inst, stack, resolve3) {
4968
4968
  let result = NONE;
4969
4969
  const check2 = (child) => {
4970
4970
  if (result !== PROVEN && child?._zod) {
4971
- const answer = isRecursive(child, stack, resolve3);
4971
+ const answer = isRecursive(child, stack, resolve4);
4972
4972
  if (answer > result)
4973
4973
  result = answer;
4974
4974
  }
@@ -4979,7 +4979,7 @@ function isRecursive(inst, stack, resolve3) {
4979
4979
  const desc = Object.getOwnPropertyDescriptor(sh, key);
4980
4980
  if (spread && !desc.enumerable)
4981
4981
  continue;
4982
- const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve3) : NONE;
4982
+ const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve4) : NONE;
4983
4983
  if (child > answer)
4984
4984
  answer = child;
4985
4985
  }
@@ -5043,7 +5043,7 @@ function isRecursive(inst, stack, resolve3) {
5043
5043
  break;
5044
5044
  // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly
5045
5045
  case "lazy": {
5046
- const inner = def._cachedInner ?? (resolve3 ? inst._zod.innerType : void 0);
5046
+ const inner = def._cachedInner ?? (resolve4 ? inst._zod.innerType : void 0);
5047
5047
  merge2(inner ? isRecursive(inner, stack, false) : ASSUMED);
5048
5048
  break;
5049
5049
  }
@@ -23326,16 +23326,105 @@ var init_environment = __esm({
23326
23326
  }
23327
23327
  });
23328
23328
 
23329
+ // ../shared/src/environment-config.ts
23330
+ var variableNameSchema, mcpValueSchema, mcpValuesSchema, httpConfigSchema, replicasMcpDefinitionSchema, replicasEnvironmentConfigSchema;
23331
+ var init_environment_config = __esm({
23332
+ "../shared/src/environment-config.ts"() {
23333
+ "use strict";
23334
+ init_zod();
23335
+ init_environment();
23336
+ init_environment_setups();
23337
+ variableNameSchema = external_exports.string().regex(VARIABLE_KEY_RE, "must be a valid environment variable name");
23338
+ mcpValueSchema = external_exports.union([
23339
+ external_exports.string(),
23340
+ environmentMcpVariableReferenceSchema
23341
+ ]);
23342
+ mcpValuesSchema = external_exports.record(external_exports.string(), mcpValueSchema);
23343
+ httpConfigSchema = environmentMcpHttpConfigSchema.pick({ url: true, auth: true }).extend({
23344
+ headers: mcpValuesSchema.default({})
23345
+ }).strict();
23346
+ replicasMcpDefinitionSchema = external_exports.discriminatedUnion("transport", [
23347
+ external_exports.strictObject({
23348
+ transport: external_exports.literal("stdio"),
23349
+ config: environmentMcpStdioConfigSchema.pick({ command: true }).extend({
23350
+ args: environmentMcpStdioConfigSchema.shape.args.unwrap().default([]),
23351
+ env: external_exports.record(variableNameSchema, mcpValueSchema).default({})
23352
+ }).strict()
23353
+ }),
23354
+ external_exports.strictObject({ transport: external_exports.literal("http"), config: httpConfigSchema }),
23355
+ external_exports.strictObject({ transport: external_exports.literal("sse"), config: httpConfigSchema })
23356
+ ]).superRefine((definition, context) => {
23357
+ if (definition.transport === "stdio") return;
23358
+ const result = validateEnvironmentMcpAuthentication(definition.transport, definition.config);
23359
+ if (!result.ok) context.addIssue({ code: "custom", path: result.error.code === "transport" ? ["transport"] : ["config", result.error.code ?? "auth"], message: result.error.message });
23360
+ });
23361
+ replicasEnvironmentConfigSchema = external_exports.strictObject({
23362
+ systemPrompt: external_exports.string().optional(),
23363
+ warmHook: external_exports.string().optional(),
23364
+ startHook: external_exports.string().optional(),
23365
+ variables: external_exports.record(variableNameSchema, external_exports.string()).optional(),
23366
+ requiredSecrets: external_exports.array(variableNameSchema).optional(),
23367
+ mcps: external_exports.record(external_exports.string().regex(MCP_NAME_PATTERN, "must be 1\u201364 letters, digits, underscores or hyphens, starting with a letter or digit").refine((name) => !isReservedMcpName(name), "is reserved for Replicas"), replicasMcpDefinitionSchema).optional()
23368
+ }).superRefine((config3, context) => {
23369
+ const names = /* @__PURE__ */ new Set();
23370
+ for (const name of Object.keys(config3.mcps ?? {})) {
23371
+ const normalized = name.toLowerCase();
23372
+ if (names.has(normalized)) {
23373
+ context.addIssue({ code: "custom", path: ["mcps", name], message: "MCP names must be unique regardless of case" });
23374
+ }
23375
+ names.add(normalized);
23376
+ }
23377
+ for (const key of config3.requiredSecrets ?? []) {
23378
+ if (config3.variables && Object.hasOwn(config3.variables, key)) {
23379
+ context.addIssue({ code: "custom", path: ["requiredSecrets"], message: `"${key}" cannot also be declared as a non-secret variable` });
23380
+ }
23381
+ }
23382
+ });
23383
+ }
23384
+ });
23385
+
23329
23386
  // ../shared/src/routes/environment-config-source.ts
23330
- var previewEnvironmentConfigSourceRequestSchema, applyEnvironmentConfigSourceRequestSchema;
23387
+ var environmentConfigLocationSchema, sourceInput, previewEnvironmentConfigSourceRequestSchema, applyEnvironmentConfigSourceRequestSchema;
23331
23388
  var init_environment_config_source = __esm({
23332
23389
  "../shared/src/routes/environment-config-source.ts"() {
23333
23390
  "use strict";
23334
23391
  init_zod();
23335
- previewEnvironmentConfigSourceRequestSchema = external_exports.strictObject({ repository_id: external_exports.string().min(1).optional() });
23336
- applyEnvironmentConfigSourceRequestSchema = previewEnvironmentConfigSourceRequestSchema.extend({
23337
- commit_sha: external_exports.string().min(1),
23392
+ init_environment_config();
23393
+ environmentConfigLocationSchema = external_exports.union([
23394
+ external_exports.object({
23395
+ kind: external_exports.literal("git").default("git"),
23396
+ entrypoint_filename: external_exports.string().optional(),
23397
+ repository_id: external_exports.string(),
23398
+ repository_name: external_exports.string(),
23399
+ filename: external_exports.string(),
23400
+ commit_sha: external_exports.string(),
23401
+ source_url: external_exports.string(),
23402
+ file_sha: external_exports.undefined().optional()
23403
+ }),
23404
+ external_exports.object({
23405
+ kind: external_exports.literal("file"),
23406
+ repository_id: external_exports.null(),
23407
+ repository_name: external_exports.null(),
23408
+ filename: external_exports.string(),
23409
+ commit_sha: external_exports.null(),
23410
+ source_url: external_exports.null(),
23411
+ file_sha: external_exports.string()
23412
+ })
23413
+ ]);
23414
+ sourceInput = {
23415
+ repository_id: external_exports.string().min(1).optional(),
23416
+ file: external_exports.strictObject({ filename: external_exports.string().min(1).max(1024), environment: replicasEnvironmentConfigSchema }).optional()
23417
+ };
23418
+ previewEnvironmentConfigSourceRequestSchema = external_exports.strictObject(sourceInput).refine(
23419
+ (input2) => !input2.file || !input2.repository_id,
23420
+ { message: "Choose either a repository or a file" }
23421
+ );
23422
+ applyEnvironmentConfigSourceRequestSchema = external_exports.strictObject({
23423
+ ...sourceInput,
23424
+ commit_sha: external_exports.string().min(1).optional(),
23338
23425
  fingerprint: external_exports.string().min(1)
23426
+ }).refine((input2) => input2.file ? !input2.repository_id && !input2.commit_sha : !!input2.commit_sha, {
23427
+ message: "File configuration requires file contents; Git configuration requires a reviewed commit"
23339
23428
  });
23340
23429
  }
23341
23430
  });
@@ -23464,8 +23553,8 @@ var init_replicas_mcp = __esm({
23464
23553
  ...updateEnvironmentMcpRequestSchema.shape
23465
23554
  });
23466
23555
  createEnvironmentDeviceToolInputSchema = external_exports.object({ ...environmentMcpPath, ...createEnvironmentDeviceRequestSchema.shape });
23467
- previewEnvironmentConfigSourceToolInputSchema = external_exports.object({ ...environmentMcpPath, ...previewEnvironmentConfigSourceRequestSchema.shape });
23468
- applyEnvironmentConfigSourceToolInputSchema = external_exports.object({ ...environmentMcpPath, ...applyEnvironmentConfigSourceRequestSchema.shape });
23556
+ previewEnvironmentConfigSourceToolInputSchema = previewEnvironmentConfigSourceRequestSchema.safeExtend(environmentMcpPath);
23557
+ applyEnvironmentConfigSourceToolInputSchema = applyEnvironmentConfigSourceRequestSchema.safeExtend(environmentMcpPath);
23469
23558
  }
23470
23559
  });
23471
23560
 
@@ -38325,6 +38414,31 @@ var init_hook_config = __esm({
38325
38414
  });
38326
38415
 
38327
38416
  // ../shared/src/warm-hooks.ts
38417
+ function isRecord2(value) {
38418
+ return typeof value === "object" && value !== null;
38419
+ }
38420
+ function parseWarmHookConfig(value, filename = "replicas.json") {
38421
+ if (typeof value === "string") {
38422
+ return value;
38423
+ }
38424
+ if (!isRecord2(value)) {
38425
+ throw new Error(`Invalid ${filename}: "warmHook" must be a string or object`);
38426
+ }
38427
+ if (!Array.isArray(value.commands) || !value.commands.every((entry) => typeof entry === "string")) {
38428
+ throw new Error(`Invalid ${filename}: "warmHook.commands" must be an array of shell commands`);
38429
+ }
38430
+ if (value.timeout !== void 0 && (typeof value.timeout !== "number" || value.timeout <= 0)) {
38431
+ throw new Error(`Invalid ${filename}: "warmHook.timeout" must be a positive number`);
38432
+ }
38433
+ if (value.separate !== void 0 && typeof value.separate !== "boolean") {
38434
+ throw new Error(`Invalid ${filename}: "warmHook.separate" must be a boolean`);
38435
+ }
38436
+ return {
38437
+ commands: value.commands,
38438
+ timeout: value.timeout,
38439
+ separate: value.separate
38440
+ };
38441
+ }
38328
38442
  var DEFAULT_WARM_HOOK_TIMEOUT_MS, MAX_WARM_HOOK_TIMEOUT_MS, DEFAULT_START_HOOK_TIMEOUT_MS, HOOK_EXEC_MAX_BUFFER_BYTES;
38329
38443
  var init_warm_hooks = __esm({
38330
38444
  "../shared/src/warm-hooks.ts"() {
@@ -38337,69 +38451,90 @@ var init_warm_hooks = __esm({
38337
38451
  }
38338
38452
  });
38339
38453
 
38340
- // ../shared/src/environment-config.ts
38341
- var variableNameSchema, mcpValueSchema, mcpValuesSchema, httpConfigSchema, replicasMcpDefinitionSchema, replicasEnvironmentConfigSchema;
38342
- var init_environment_config = __esm({
38343
- "../shared/src/environment-config.ts"() {
38344
- "use strict";
38345
- init_zod();
38346
- init_environment();
38347
- init_environment_setups();
38348
- variableNameSchema = external_exports.string().regex(VARIABLE_KEY_RE, "must be a valid environment variable name");
38349
- mcpValueSchema = external_exports.union([
38350
- external_exports.string(),
38351
- environmentMcpVariableReferenceSchema
38352
- ]);
38353
- mcpValuesSchema = external_exports.record(external_exports.string(), mcpValueSchema);
38354
- httpConfigSchema = environmentMcpHttpConfigSchema.pick({ url: true, auth: true }).extend({
38355
- headers: mcpValuesSchema.default({})
38356
- }).strict();
38357
- replicasMcpDefinitionSchema = external_exports.discriminatedUnion("transport", [
38358
- external_exports.strictObject({
38359
- transport: external_exports.literal("stdio"),
38360
- config: environmentMcpStdioConfigSchema.pick({ command: true }).extend({
38361
- args: environmentMcpStdioConfigSchema.shape.args.unwrap().default([]),
38362
- env: external_exports.record(variableNameSchema, mcpValueSchema).default({})
38363
- }).strict()
38364
- }),
38365
- external_exports.strictObject({ transport: external_exports.literal("http"), config: httpConfigSchema }),
38366
- external_exports.strictObject({ transport: external_exports.literal("sse"), config: httpConfigSchema })
38367
- ]).superRefine((definition, context) => {
38368
- if (definition.transport === "stdio") return;
38369
- const result = validateEnvironmentMcpAuthentication(definition.transport, definition.config);
38370
- if (!result.ok) context.addIssue({ code: "custom", path: result.error.code === "transport" ? ["transport"] : ["config", result.error.code ?? "auth"], message: result.error.message });
38371
- });
38372
- replicasEnvironmentConfigSchema = external_exports.strictObject({
38373
- systemPrompt: external_exports.string().optional(),
38374
- warmHook: external_exports.string().optional(),
38375
- startHook: external_exports.string().optional(),
38376
- variables: external_exports.record(variableNameSchema, external_exports.string()).optional(),
38377
- requiredSecrets: external_exports.array(variableNameSchema).optional(),
38378
- mcps: external_exports.record(external_exports.string().regex(MCP_NAME_PATTERN, "must be 1\u201364 letters, digits, underscores or hyphens, starting with a letter or digit").refine((name) => !isReservedMcpName(name), "is reserved for Replicas"), replicasMcpDefinitionSchema).optional()
38379
- }).superRefine((config3, context) => {
38380
- const names = /* @__PURE__ */ new Set();
38381
- for (const name of Object.keys(config3.mcps ?? {})) {
38382
- const normalized = name.toLowerCase();
38383
- if (names.has(normalized)) {
38384
- context.addIssue({ code: "custom", path: ["mcps", name], message: "MCP names must be unique regardless of case" });
38385
- }
38386
- names.add(normalized);
38387
- }
38388
- for (const key of config3.requiredSecrets ?? []) {
38389
- if (config3.variables && Object.hasOwn(config3.variables, key)) {
38390
- context.addIssue({ code: "custom", path: ["requiredSecrets"], message: `"${key}" cannot also be declared as a non-secret variable` });
38391
- }
38392
- }
38393
- });
38394
- }
38395
- });
38396
-
38397
38454
  // ../shared/src/replicas-config.ts
38455
+ function isRecord3(value) {
38456
+ return typeof value === "object" && value !== null;
38457
+ }
38458
+ function parseReplicasConfig(value, filename = "replicas.json") {
38459
+ if (!isRecord3(value)) {
38460
+ throw new Error(`Invalid ${filename}: expected an object`);
38461
+ }
38462
+ const config3 = {};
38463
+ if ("infra" in value) {
38464
+ if (typeof value.infra !== "string" || !value.infra.trim()) {
38465
+ throw new Error(`Invalid ${filename}: "infra" must be a non-empty file path`);
38466
+ }
38467
+ if ("environment" in value) throw new Error(`Invalid ${filename}: use either "infra" or "environment", not both`);
38468
+ config3.infra = value.infra;
38469
+ }
38470
+ if ("organizationId" in value) {
38471
+ if (typeof value.organizationId !== "string") {
38472
+ throw new Error(`Invalid ${filename}: "organizationId" must be a string`);
38473
+ }
38474
+ config3.organizationId = value.organizationId;
38475
+ }
38476
+ if ("systemPrompt" in value) {
38477
+ if (typeof value.systemPrompt !== "string") {
38478
+ throw new Error(`Invalid ${filename}: "systemPrompt" must be a string`);
38479
+ }
38480
+ config3.systemPrompt = value.systemPrompt;
38481
+ }
38482
+ if ("startHook" in value) {
38483
+ if (!isRecord3(value.startHook)) {
38484
+ throw new Error(`Invalid ${filename}: "startHook" must be an object with "commands" array`);
38485
+ }
38486
+ const { commands, timeout, separate } = value.startHook;
38487
+ if (!Array.isArray(commands) || !commands.every((entry) => typeof entry === "string")) {
38488
+ throw new Error(`Invalid ${filename}: "startHook.commands" must be an array of shell commands`);
38489
+ }
38490
+ if (timeout !== void 0 && (typeof timeout !== "number" || timeout <= 0)) {
38491
+ throw new Error(`Invalid ${filename}: "startHook.timeout" must be a positive number`);
38492
+ }
38493
+ if (separate !== void 0 && typeof separate !== "boolean") {
38494
+ throw new Error(`Invalid ${filename}: "startHook.separate" must be a boolean`);
38495
+ }
38496
+ config3.startHook = { commands, timeout, separate };
38497
+ }
38498
+ if ("warmHook" in value) {
38499
+ config3.warmHook = parseWarmHookConfig(value.warmHook, filename);
38500
+ }
38501
+ if ("environment" in value) {
38502
+ const parsed = replicasEnvironmentConfigSchema.safeParse(value.environment);
38503
+ if (!parsed.success) {
38504
+ const issue2 = parsed.error.issues[0];
38505
+ throw new Error(`Invalid ${filename}: "environment${issue2.path.length ? `.${issue2.path.join(".")}` : ""}" ${issue2.message}`);
38506
+ }
38507
+ config3.environment = parsed.data;
38508
+ }
38509
+ return config3;
38510
+ }
38511
+ function parseReplicasConfigString(content, filename) {
38512
+ const isYaml = filename.endsWith(".yaml") || filename.endsWith(".yml");
38513
+ let parsed;
38514
+ if (isYaml) {
38515
+ parsed = (0, import_yaml2.parse)(content);
38516
+ } else {
38517
+ parsed = JSON.parse(content);
38518
+ }
38519
+ return parseReplicasConfig(parsed, filename);
38520
+ }
38521
+ async function resolveReplicasEnvironmentConfig(entrypoint, loadInfra) {
38522
+ let selected = entrypoint;
38523
+ if (entrypoint.config.infra) {
38524
+ const target = await loadInfra(entrypoint.config.infra);
38525
+ if (!target.ok) return target;
38526
+ selected = target.data;
38527
+ if (selected.config.infra) return createErrorResult({ message: `${selected.filename}: nested infra pointers are not supported; declare an "environment" section`, code: 400 });
38528
+ }
38529
+ if (!selected.config.environment) return createErrorResult({ message: `${selected.filename} needs an "environment" section before it can manage an environment`, code: 400 });
38530
+ return createSuccessResult({ filename: selected.filename, config: { ...entrypoint.config, environment: selected.config.environment } });
38531
+ }
38398
38532
  var import_yaml2, REPLICAS_CONFIG_FILENAMES;
38399
38533
  var init_replicas_config = __esm({
38400
38534
  "../shared/src/replicas-config.ts"() {
38401
38535
  "use strict";
38402
38536
  import_yaml2 = __toESM(require_dist());
38537
+ init_result();
38403
38538
  init_warm_hooks();
38404
38539
  init_environment_config();
38405
38540
  REPLICAS_CONFIG_FILENAMES = ["replicas.json", "replicas.yaml", "replicas.yml"];
@@ -38511,7 +38646,7 @@ var CLI_VERSION;
38511
38646
  var init_cli_version = __esm({
38512
38647
  "../shared/src/cli-version.ts"() {
38513
38648
  "use strict";
38514
- CLI_VERSION = "0.3.435";
38649
+ CLI_VERSION = "0.3.436";
38515
38650
  }
38516
38651
  });
38517
38652
 
@@ -48713,8 +48848,8 @@ var require_CronFileParser = __commonJS({
48713
48848
  */
48714
48849
  static async parseFile(filePath) {
48715
48850
  var _a3;
48716
- const { readFile } = await Promise.resolve().then(() => __importStar(require("fs/promises")));
48717
- const data = await readFile(filePath, "utf8");
48851
+ const { readFile: readFile2 } = await Promise.resolve().then(() => __importStar(require("fs/promises")));
48852
+ const data = await readFile2(filePath, "utf8");
48718
48853
  return __privateMethod(_a3 = _CronFileParser, _CronFileParser_static, parseContent_fn).call(_a3, data);
48719
48854
  }
48720
48855
  /**
@@ -50566,7 +50701,7 @@ async function apiKeyLoginCommand(key) {
50566
50701
  }
50567
50702
  async function loginCommand() {
50568
50703
  const state = generateState();
50569
- return new Promise((resolve3, reject) => {
50704
+ return new Promise((resolve4, reject) => {
50570
50705
  let authTimeout;
50571
50706
  let hasHandledCallback = false;
50572
50707
  let lastRedirectUrl = null;
@@ -50716,7 +50851,7 @@ async function loginCommand() {
50716
50851
  setImmediate(() => {
50717
50852
  server.closeAllConnections?.();
50718
50853
  server.close();
50719
- resolve3();
50854
+ resolve4();
50720
50855
  });
50721
50856
  } catch (error63) {
50722
50857
  const errorUrl = `${WEB_APP_URL}/cli-login/error?message=${encodeURIComponent("Failed to verify authentication.")}`;
@@ -50982,7 +51117,7 @@ async function waitForUser(params) {
50982
51117
  let value = params.initial;
50983
51118
  const deadline = Date.now() + timeoutMs;
50984
51119
  while (!params.settled(value) && Date.now() < deadline) {
50985
- await new Promise((resolve3) => setTimeout(resolve3, VARIABLE_REQUEST_WAIT.pollMs));
51120
+ await new Promise((resolve4) => setTimeout(resolve4, VARIABLE_REQUEST_WAIT.pollMs));
50986
51121
  value = await params.poll(true);
50987
51122
  }
50988
51123
  return params.settled(value) ? value : params.poll(false);
@@ -51017,7 +51152,7 @@ function buildSSHArgs(token, host, proxyCommand, localForward) {
51017
51152
  ];
51018
51153
  }
51019
51154
  async function connectSSH(token, host, proxyCommand, localForward) {
51020
- return new Promise((resolve3, reject) => {
51155
+ return new Promise((resolve4, reject) => {
51021
51156
  const ssh = (0, import_child_process.spawn)("ssh", buildSSHArgs(token, host, proxyCommand, localForward), {
51022
51157
  stdio: "inherit"
51023
51158
  });
@@ -51025,7 +51160,7 @@ async function connectSSH(token, host, proxyCommand, localForward) {
51025
51160
  if (localForward && code) {
51026
51161
  reject(new Error(`SSH tunnel exited with code ${code}`));
51027
51162
  } else {
51028
- resolve3();
51163
+ resolve4();
51029
51164
  }
51030
51165
  });
51031
51166
  ssh.on("error", reject);
@@ -51600,7 +51735,7 @@ async function exchangeCodeForTokens(code, codeVerifier) {
51600
51735
  };
51601
51736
  }
51602
51737
  function startCallbackServer(expectedState, codeVerifier, save) {
51603
- return new Promise((resolve3, reject) => {
51738
+ return new Promise((resolve4, reject) => {
51604
51739
  const server = import_http2.default.createServer(async (req, res) => {
51605
51740
  try {
51606
51741
  if (!req.url) {
@@ -51644,7 +51779,7 @@ function startCallbackServer(expectedState, codeVerifier, save) {
51644
51779
  res.writeHead(302, { "Location": completionUrl });
51645
51780
  res.end();
51646
51781
  server.close();
51647
- resolve3();
51782
+ resolve4();
51648
51783
  } catch (tokenError) {
51649
51784
  const errorMessage = encodeURIComponent(tokenError instanceof Error ? tokenError.message : "Unknown error");
51650
51785
  res.writeHead(302, { "Location": `${WEB_APP_URL2}/codex/oauth/error?message=${errorMessage}` });
@@ -51678,7 +51813,7 @@ async function runCodexOAuthFlow(totalSteps, save) {
51678
51813
  const state = generateState2();
51679
51814
  const authUrl = buildAuthorizationUrl(pkce.codeChallenge, state);
51680
51815
  const tokensPromise = startCallbackServer(state, pkce.codeVerifier, save);
51681
- await new Promise((resolve3) => setTimeout(resolve3, 500));
51816
+ await new Promise((resolve4) => setTimeout(resolve4, 500));
51682
51817
  renderAuthFlowStep(1, totalSteps, "Approve access in your browser");
51683
51818
  await openForApproval("auth.openai.com", authUrl);
51684
51819
  renderAuthFlowDetail("waiting for sign-in\u2026");
@@ -51862,10 +51997,10 @@ async function promptForAuthorizationCode() {
51862
51997
  process.stdin.setRawMode(false);
51863
51998
  process.stdin.resume();
51864
51999
  const rl = import_readline.default.createInterface({ input: process.stdin, output: process.stdout });
51865
- return new Promise((resolve3) => {
51866
- rl.on("close", () => resolve3(""));
52000
+ return new Promise((resolve4) => {
52001
+ rl.on("close", () => resolve4(""));
51867
52002
  rl.question(import_chalk15.default.gray(" Paste code here: "), (answer) => {
51868
- resolve3(answer.trim());
52003
+ resolve4(answer.trim());
51869
52004
  rl.close();
51870
52005
  });
51871
52006
  });
@@ -52035,7 +52170,7 @@ async function runMuseOAuthFlow(totalSteps) {
52035
52170
  const deadline = Date.now() + (typeof device.expires_in === "number" ? device.expires_in : 900) * 1e3;
52036
52171
  let intervalMs = Math.max(1, typeof device.interval === "number" ? device.interval : 5) * 1e3;
52037
52172
  while (Date.now() < deadline) {
52038
- await new Promise((resolve3) => setTimeout(resolve3, intervalMs));
52173
+ await new Promise((resolve4) => setTimeout(resolve4, intervalMs));
52039
52174
  const response = await post("/oidc/device/token/", new URLSearchParams({
52040
52175
  grant_type: "urn:ietf:params:oauth:grant-type:device_code",
52041
52176
  device_code: device.device_code,
@@ -55333,14 +55468,14 @@ function launchChrome() {
55333
55468
  }
55334
55469
  }
55335
55470
  });
55336
- const send = (method, params = {}, sessionId) => new Promise((resolve3, reject) => {
55471
+ const send = (method, params = {}, sessionId) => new Promise((resolve4, reject) => {
55337
55472
  if (exitError) return reject(exitError);
55338
55473
  const id = nextId++;
55339
55474
  const timer = setTimeout(() => {
55340
55475
  pending.delete(id);
55341
55476
  reject(new Error(`Chrome did not answer ${method} within ${COMMAND_TIMEOUT_MS / 1e3}s`));
55342
55477
  }, COMMAND_TIMEOUT_MS);
55343
- pending.set(id, { resolve: resolve3, reject, timer });
55478
+ pending.set(id, { resolve: resolve4, reject, timer });
55344
55479
  input2.write(`${JSON.stringify({ id, method, params, ...sessionId ? { sessionId } : {} })}\0`);
55345
55480
  });
55346
55481
  return {
@@ -55367,7 +55502,7 @@ function launchChrome() {
55367
55502
  // Callers exit the process right after, and Chrome's helper processes write into the profile until Chrome exits.
55368
55503
  async close() {
55369
55504
  if (child.exitCode === null && child.signalCode === null) {
55370
- const exited = new Promise((resolve3) => child.once("exit", resolve3));
55505
+ const exited = new Promise((resolve4) => child.once("exit", resolve4));
55371
55506
  const kill = setTimeout(() => child.kill("SIGKILL"), CLOSE_TIMEOUT_MS);
55372
55507
  send("Browser.close").catch(() => child.kill("SIGKILL"));
55373
55508
  await exited;
@@ -55423,21 +55558,21 @@ async function servePage(html) {
55423
55558
  response.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Content-Security-Policy": "sandbox allow-scripts" });
55424
55559
  response.end(html);
55425
55560
  });
55426
- await new Promise((resolve3) => server.listen(0, "127.0.0.1", resolve3));
55561
+ await new Promise((resolve4) => server.listen(0, "127.0.0.1", resolve4));
55427
55562
  const address = server.address();
55428
55563
  const origin = `http://127.0.0.1:${typeof address === "object" && address ? address.port : 0}`;
55429
55564
  return { server, pageUrl: `${origin}/page.html`, fontUrl: font ? `${origin}${VISUAL_FONT_PATH}` : void 0 };
55430
55565
  }
55431
55566
  function waitFor(page, method, timeoutMs) {
55432
- return new Promise((resolve3) => {
55567
+ return new Promise((resolve4) => {
55433
55568
  const stop = page.on(method, () => {
55434
55569
  clearTimeout(timer);
55435
55570
  stop();
55436
- resolve3(true);
55571
+ resolve4(true);
55437
55572
  });
55438
55573
  const timer = setTimeout(() => {
55439
55574
  stop();
55440
- resolve3(false);
55575
+ resolve4(false);
55441
55576
  }, timeoutMs);
55442
55577
  });
55443
55578
  }
@@ -55886,11 +56021,11 @@ var init_gpu2 = __esm({
55886
56021
  // src/commands/environment-config.ts
55887
56022
  function printSource({ source }) {
55888
56023
  if (!source) {
55889
- console.log("No Git configuration linked. Use replicas environment config link <env> --repository <name-or-id>.");
56024
+ console.log("No configuration source. Use replicas environment config apply <env> --file <path>, or config link with --repository.");
55890
56025
  return;
55891
56026
  }
55892
- console.log(`${source.repository_name}/${source.filename} @ ${source.commit_sha}`);
55893
- console.log(source.source_url);
56027
+ console.log(source.kind === "file" ? `${source.filename} @ ${source.file_sha}` : `${source.repository_name}/${source.filename} @ ${source.commit_sha}`);
56028
+ if (source.source_url) console.log(source.source_url);
55894
56029
  console.log(`Synced: ${source.synced_at}`);
55895
56030
  console.log(`Managed settings: ${source.managed.fields.join(", ") || "(none)"}`);
55896
56031
  console.log(`Managed variables: ${source.managed.variables.join(", ") || "(none)"}`);
@@ -55900,19 +56035,30 @@ function printSource({ source }) {
55900
56035
  if (source.last_error) console.log(import_chalk29.default.red(source.last_error));
55901
56036
  }
55902
56037
  function printPreview({ preview: preview2 }) {
55903
- console.log(`${preview2.repository_name}/${preview2.filename} @ ${preview2.commit_sha}`);
55904
- console.log(preview2.source_url);
55905
- if (!preview2.changes.length) console.log("No setting changes. Applying records this commit.");
56038
+ console.log(preview2.kind === "file" ? `${preview2.filename} @ ${preview2.file_sha}` : `${preview2.repository_name}/${preview2.filename} @ ${preview2.commit_sha}`);
56039
+ if (preview2.source_url) console.log(preview2.source_url);
56040
+ if (!preview2.changes.length) console.log("No setting changes. Applying records this configuration.");
55906
56041
  for (const change of preview2.changes) console.log(` ${change.operation}: ${change.kind} ${change.key}`);
55907
56042
  if (preview2.missing_secrets.length) console.log(import_chalk29.default.yellow(`Missing required secrets: ${preview2.missing_secrets.join(", ")}`));
55908
56043
  for (const blocker of preview2.blockers) console.log(import_chalk29.default.red(` Cannot apply: ${blocker}`));
55909
56044
  }
55910
- async function previewSource(id, repository) {
55911
- const [repositoryId] = repository ? await resolveRepositoryIds([repository]) : [];
55912
- return orgAuthenticatedFetch(`/v1/environments/${id}/config-source/preview`, {
55913
- method: "POST",
55914
- body: repositoryId ? { repository_id: repositoryId } : {}
55915
- });
56045
+ async function sourceInput2(options) {
56046
+ if (options.file && options.repository) throw new Error("Choose either --file or --repository");
56047
+ if (options.file) {
56048
+ const filename = options.file;
56049
+ const config3 = parseReplicasConfigString(await (0, import_promises2.readFile)(filename, "utf8"), filename);
56050
+ const result = await resolveReplicasEnvironmentConfig({ filename, config: config3 }, async (pointer) => {
56051
+ const target = (0, import_node_path3.resolve)((0, import_node_path3.dirname)(filename), pointer);
56052
+ return createSuccessResult({ filename: target, config: parseReplicasConfigString(await (0, import_promises2.readFile)(target, "utf8"), target) });
56053
+ });
56054
+ if (!result.ok) throw new Error(result.error.message);
56055
+ return { file: { filename: result.data.filename, environment: result.data.config.environment } };
56056
+ }
56057
+ const [repositoryId] = options.repository ? await resolveRepositoryIds([options.repository]) : [];
56058
+ return repositoryId ? { repository_id: repositoryId } : {};
56059
+ }
56060
+ async function previewSource(id, input2) {
56061
+ return orgAuthenticatedFetch(`/v1/environments/${id}/config-source/preview`, { method: "POST", body: input2 });
55916
56062
  }
55917
56063
  async function environmentConfigGetCommand(environment2) {
55918
56064
  ensureOrgApiAuthenticated();
@@ -55921,12 +56067,14 @@ async function environmentConfigGetCommand(environment2) {
55921
56067
  }
55922
56068
  async function environmentConfigPreviewCommand(environment2, options) {
55923
56069
  ensureOrgApiAuthenticated();
55924
- output2(await previewSource(await resolveEnvironmentId(environment2), options.repository), printPreview);
56070
+ const input2 = await sourceInput2(options);
56071
+ output2(await previewSource(await resolveEnvironmentId(environment2), input2), printPreview);
55925
56072
  }
55926
56073
  async function applySource(environment2, options, operation) {
55927
56074
  ensureOrgApiAuthenticated();
55928
56075
  const id = await resolveEnvironmentId(environment2);
55929
- const response = await previewSource(id, options.repository);
56076
+ const input2 = await sourceInput2(options);
56077
+ const response = await previewSource(id, input2);
55930
56078
  if (!isJsonMode()) printPreview(response);
55931
56079
  const { preview: preview2 } = response;
55932
56080
  if (preview2.blockers.length || preview2.missing_secrets.length) {
@@ -55939,9 +56087,13 @@ async function applySource(environment2, options, operation) {
55939
56087
  if (!isInteractive()) throw new Error("Preview the changes with replicas environment config preview, then pass --yes to apply without a terminal.");
55940
56088
  if (!await confirmAction(`${operation === "link" ? "Link and apply" : "Apply"} this configuration to ${environment2}?`)) return;
55941
56089
  }
55942
- const body = { repository_id: preview2.repository_id, commit_sha: preview2.commit_sha, fingerprint: preview2.fingerprint };
56090
+ if (options.file && JSON.stringify(await sourceInput2(options)) !== JSON.stringify(input2)) throw new Error("The configuration file changed after preview. Preview it again before applying");
56091
+ const body = { ...preview2.kind !== "file" ? { repository_id: preview2.repository_id, commit_sha: preview2.commit_sha } : input2, fingerprint: preview2.fingerprint };
55943
56092
  output2(await orgAuthenticatedFetch(`/v1/environments/${id}/config-source${operation === "sync" ? "/sync" : ""}`, { method: "POST", body }), printSource);
55944
56093
  }
56094
+ async function environmentConfigApplyCommand(environment2, options) {
56095
+ await applySource(environment2, options, "file");
56096
+ }
55945
56097
  async function environmentConfigLinkCommand(environment2, options) {
55946
56098
  await applySource(environment2, options, "link");
55947
56099
  }
@@ -55953,17 +56105,20 @@ async function environmentConfigDisconnectCommand(environment2, options) {
55953
56105
  const id = await resolveEnvironmentId(environment2);
55954
56106
  if (!options.yes) {
55955
56107
  if (!isInteractive()) throw new Error("Pass --yes to disconnect without a terminal. Current settings will be preserved.");
55956
- if (!await confirmAction(`Disconnect Git configuration for ${environment2}? Current settings will be preserved.`)) return;
56108
+ if (!await confirmAction(`Disconnect configuration source for ${environment2}? Current settings will be preserved.`)) return;
55957
56109
  }
55958
56110
  output2(await orgAuthenticatedFetch(`/v1/environments/${id}/config-source`, { method: "DELETE" }), () => {
55959
- console.log("Git configuration disconnected. Current settings preserved.");
56111
+ console.log("Configuration source disconnected. Current settings preserved.");
55960
56112
  });
55961
56113
  }
55962
- var import_chalk29;
56114
+ var import_chalk29, import_promises2, import_node_path3;
55963
56115
  var init_environment_config2 = __esm({
55964
56116
  "src/commands/environment-config.ts"() {
55965
56117
  "use strict";
55966
56118
  import_chalk29 = __toESM(require("chalk"));
56119
+ import_promises2 = require("fs/promises");
56120
+ import_node_path3 = require("path");
56121
+ init_src();
55967
56122
  init_api2();
55968
56123
  init_command_utils();
55969
56124
  init_output();
@@ -55979,18 +56134,18 @@ async function historyTranscriptCommand(name) {
55979
56134
  throw new Error(`Invalid session name '${name}'. Use the name from INDEX.md, e.g. 2026-01-31-<id>`);
55980
56135
  }
55981
56136
  const response = await agentRequest(`/v1/engine/history/transcripts/${session}`);
55982
- const dir = (0, import_node_path3.join)(HISTORY_ROOT, "transcripts");
56137
+ const dir = (0, import_node_path4.join)(HISTORY_ROOT, "transcripts");
55983
56138
  (0, import_node_fs3.mkdirSync)(dir, { recursive: true });
55984
- const file2 = (0, import_node_path3.join)(dir, `${session}.jsonl`);
56139
+ const file2 = (0, import_node_path4.join)(dir, `${session}.jsonl`);
55985
56140
  (0, import_node_fs3.writeFileSync)(file2, Buffer.from(await response.arrayBuffer()));
55986
56141
  output2({ path: file2 }, () => console.log(file2));
55987
56142
  }
55988
- var import_node_fs3, import_node_path3;
56143
+ var import_node_fs3, import_node_path4;
55989
56144
  var init_history = __esm({
55990
56145
  "src/commands/history.ts"() {
55991
56146
  "use strict";
55992
56147
  import_node_fs3 = require("fs");
55993
- import_node_path3 = require("path");
56148
+ import_node_path4 = require("path");
55994
56149
  init_src();
55995
56150
  init_agent_api();
55996
56151
  init_output();
@@ -56120,7 +56275,7 @@ function tailLines(content, lines) {
56120
56275
  return all.slice(-lines).join("\n").trim();
56121
56276
  }
56122
56277
  function statePath(name) {
56123
- return (0, import_node_path4.join)(SERVICES_DIR, `${name}.json`);
56278
+ return (0, import_node_path5.join)(SERVICES_DIR, `${name}.json`);
56124
56279
  }
56125
56280
  function isServiceState(value) {
56126
56281
  if (typeof value !== "object" || value === null) return false;
@@ -56190,8 +56345,8 @@ async function serviceStartCommand(name, commandParts, options) {
56190
56345
  await killServiceGroup(existing.pid);
56191
56346
  }
56192
56347
  (0, import_node_fs5.mkdirSync)(SERVICES_DIR, { recursive: true });
56193
- const cwd = (0, import_node_path4.resolve)(options.cwd ?? process.cwd());
56194
- const logFile = (0, import_node_path4.join)(SERVICES_DIR, `${name}.log`);
56348
+ const cwd = (0, import_node_path5.resolve)(options.cwd ?? process.cwd());
56349
+ const logFile = (0, import_node_path5.join)(SERVICES_DIR, `${name}.log`);
56195
56350
  const logFd = (0, import_node_fs5.openSync)(logFile, "a");
56196
56351
  (0, import_node_fs5.writeFileSync)(logFd, `
56197
56352
  === [replicas service] "${name}" started ${(/* @__PURE__ */ new Date()).toISOString()} in ${cwd}: ${command} ===
@@ -56277,7 +56432,7 @@ async function serviceLogsCommand(name, options) {
56277
56432
  console.log(logs || "(no log output yet)");
56278
56433
  });
56279
56434
  }
56280
- var import_chalk32, import_node_child_process3, import_node_fs5, import_node_os3, import_node_path4, SERVICES_DIR, NAME_PATTERN, LOG_KEEP_BYTES, LOG_TRIM_LOOP;
56435
+ var import_chalk32, import_node_child_process3, import_node_fs5, import_node_os3, import_node_path5, SERVICES_DIR, NAME_PATTERN, LOG_KEEP_BYTES, LOG_TRIM_LOOP;
56281
56436
  var init_service = __esm({
56282
56437
  "src/commands/service.ts"() {
56283
56438
  "use strict";
@@ -56285,10 +56440,10 @@ var init_service = __esm({
56285
56440
  import_node_child_process3 = require("child_process");
56286
56441
  import_node_fs5 = require("fs");
56287
56442
  import_node_os3 = require("os");
56288
- import_node_path4 = require("path");
56443
+ import_node_path5 = require("path");
56289
56444
  init_src();
56290
56445
  init_output();
56291
- SERVICES_DIR = (0, import_node_path4.join)((0, import_node_os3.homedir)(), ".replicas", "services");
56446
+ SERVICES_DIR = (0, import_node_path5.join)((0, import_node_os3.homedir)(), ".replicas", "services");
56292
56447
  NAME_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/;
56293
56448
  LOG_KEEP_BYTES = 5 * 1024 * 1024;
56294
56449
  LOG_TRIM_LOOP = `trim() { ${trimLogTailCommand('"$1"', 10 * 1024 * 1024, LOG_KEEP_BYTES)}; }
@@ -56384,17 +56539,17 @@ async function deviceConnectCommand() {
56384
56539
  const next = problem ?? `\u2713 ${device?.name}: ready for ${waiting.size} ${waiting.size === 1 ? "workspace" : "workspaces"}, forwarding to SSH on port ${port}`;
56385
56540
  if (next !== summary) console.log(problem ? import_chalk33.default.yellow(next) : import_chalk33.default.green(next));
56386
56541
  summary = next;
56387
- await (0, import_promises2.setTimeout)(POLL_INTERVAL_MS);
56542
+ await (0, import_promises3.setTimeout)(POLL_INTERVAL_MS);
56388
56543
  }
56389
56544
  }
56390
- var import_chalk33, import_node_child_process4, import_node_net, import_promises2, import_node_util, import_ws, POLL_INTERVAL_MS, HEARTBEAT_MS, MAX_RETRY_DELAY_MS, REMOTE_LOGIN_HINT;
56545
+ var import_chalk33, import_node_child_process4, import_node_net, import_promises3, import_node_util, import_ws, POLL_INTERVAL_MS, HEARTBEAT_MS, MAX_RETRY_DELAY_MS, REMOTE_LOGIN_HINT;
56391
56546
  var init_device = __esm({
56392
56547
  "src/commands/device.ts"() {
56393
56548
  "use strict";
56394
56549
  import_chalk33 = __toESM(require("chalk"));
56395
56550
  import_node_child_process4 = require("child_process");
56396
56551
  import_node_net = require("net");
56397
- import_promises2 = require("timers/promises");
56552
+ import_promises3 = require("timers/promises");
56398
56553
  import_node_util = require("util");
56399
56554
  import_ws = __toESM(require("ws"));
56400
56555
  init_src();
@@ -56719,7 +56874,8 @@ var init_src2 = __esm({
56719
56874
  environment.command("delete <id-or-name>").description("Delete an environment").option("-f, --force", "Skip confirmation prompt").action(run(environmentDeleteCommand));
56720
56875
  envConfig = environment.command("config").description("Link and sync environment configuration from Git");
56721
56876
  envConfig.command("get <env>").description("Show the linked configuration source and sync status").action(run(environmentConfigGetCommand));
56722
- envConfig.command("preview <env>").description("Preview committed configuration changes without applying them").option("-r, --repository <name-or-id>", "Repository containing the configuration").action(run(environmentConfigPreviewCommand));
56877
+ envConfig.command("preview <env>").description("Preview configuration changes from Git or a local file without applying them").option("--file <path>", "Read the environment block from a local JSON or YAML file").option("-r, --repository <name-or-id>", "Repository containing the configuration").action(run(environmentConfigPreviewCommand));
56878
+ envConfig.command("apply <env>").description("Preview and apply environment configuration from a local file").requiredOption("--file <path>", "Read the environment block from a local JSON or YAML file").option("-y, --yes", "Apply the preview without a confirmation prompt").action(run(environmentConfigApplyCommand));
56723
56879
  envConfig.command("link <env>").description("Preview, link, and apply configuration from a repository").option("-r, --repository <name-or-id>", "Repository containing the configuration").option("-y, --yes", "Apply the preview without a confirmation prompt").action(run(environmentConfigLinkCommand));
56724
56880
  envConfig.command("sync <env>").description("Preview and apply changes from the linked configuration").option("-y, --yes", "Apply the preview without a confirmation prompt").action(run(environmentConfigSyncCommand));
56725
56881
  envConfig.command("disconnect <env>").description("Disconnect Git configuration and preserve current settings").option("-y, --yes", "Disconnect without a confirmation prompt").action(run(environmentConfigDisconnectCommand));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "replicas-cli",
3
- "version": "0.3.435",
3
+ "version": "0.3.436",
4
4
  "description": "CLI for managing Replicas workspaces - SSH into cloud dev environments with automatic port forwarding",
5
5
  "main": "dist/index.cjs",
6
6
  "bin": {