replicas-cli 0.3.434 → 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 +289 -122
  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
  }
@@ -22414,7 +22414,7 @@ function codexTurnFromEvent(event) {
22414
22414
  const { turnId, status, error: error62 } = event.payload;
22415
22415
  return typeof turnId === "string" && typeof status === "string" ? { turnId, status, ...typeof error62 === "string" ? { error: error62 } : {} } : null;
22416
22416
  }
22417
- var MERGED_MESSAGE_SEPARATOR, updateChatDisplayNameRequestSchema, createChatRequestSchema, spawnSubagentRequestSchema, messageSubagentRequestSchema, waitSubagentRequestSchema, subagentResponseSchema, integrationErrorNotificationTargetSchema, sendChatMessageRequestSchema, CODEX_ITEM_FIELD_CHECKS, sendChatMessageResponseSchema, interruptChatRequestSchema, respondToolInputRequestSchema;
22417
+ var MERGED_MESSAGE_SEPARATOR, engineStatusSnapshotSchema, updateChatDisplayNameRequestSchema, createChatRequestSchema, spawnSubagentRequestSchema, messageSubagentRequestSchema, waitSubagentRequestSchema, subagentResponseSchema, integrationErrorNotificationTargetSchema, sendChatMessageRequestSchema, CODEX_ITEM_FIELD_CHECKS, sendChatMessageResponseSchema, interruptChatRequestSchema, respondToolInputRequestSchema;
22418
22418
  var init_v1 = __esm({
22419
22419
  "../shared/src/engine/v1.ts"() {
22420
22420
  "use strict";
@@ -22427,6 +22427,17 @@ var init_v1 = __esm({
22427
22427
  init_type_guards();
22428
22428
  init_zod();
22429
22429
  MERGED_MESSAGE_SEPARATOR = "\n\n<!-- replicas:merged -->\n\n";
22430
+ engineStatusSnapshotSchema = external_exports.object({
22431
+ uptimeSeconds: external_exports.number(),
22432
+ hasActiveSSHSessions: external_exports.boolean(),
22433
+ activeSseClients: external_exports.number(),
22434
+ chatsTotal: external_exports.number(),
22435
+ chatsProcessing: external_exports.number(),
22436
+ chatsWithActiveTurn: external_exports.number().optional(),
22437
+ reposTotal: external_exports.number(),
22438
+ hooksRunning: external_exports.boolean(),
22439
+ desktopReady: external_exports.boolean().optional()
22440
+ });
22430
22441
  updateChatDisplayNameRequestSchema = external_exports.object({
22431
22442
  displayName: external_exports.string().trim().min(1).max(100)
22432
22443
  });
@@ -23315,16 +23326,105 @@ var init_environment = __esm({
23315
23326
  }
23316
23327
  });
23317
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
+
23318
23386
  // ../shared/src/routes/environment-config-source.ts
23319
- var previewEnvironmentConfigSourceRequestSchema, applyEnvironmentConfigSourceRequestSchema;
23387
+ var environmentConfigLocationSchema, sourceInput, previewEnvironmentConfigSourceRequestSchema, applyEnvironmentConfigSourceRequestSchema;
23320
23388
  var init_environment_config_source = __esm({
23321
23389
  "../shared/src/routes/environment-config-source.ts"() {
23322
23390
  "use strict";
23323
23391
  init_zod();
23324
- previewEnvironmentConfigSourceRequestSchema = external_exports.strictObject({ repository_id: external_exports.string().min(1).optional() });
23325
- applyEnvironmentConfigSourceRequestSchema = previewEnvironmentConfigSourceRequestSchema.extend({
23326
- 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(),
23327
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"
23328
23428
  });
23329
23429
  }
23330
23430
  });
@@ -23453,8 +23553,8 @@ var init_replicas_mcp = __esm({
23453
23553
  ...updateEnvironmentMcpRequestSchema.shape
23454
23554
  });
23455
23555
  createEnvironmentDeviceToolInputSchema = external_exports.object({ ...environmentMcpPath, ...createEnvironmentDeviceRequestSchema.shape });
23456
- previewEnvironmentConfigSourceToolInputSchema = external_exports.object({ ...environmentMcpPath, ...previewEnvironmentConfigSourceRequestSchema.shape });
23457
- applyEnvironmentConfigSourceToolInputSchema = external_exports.object({ ...environmentMcpPath, ...applyEnvironmentConfigSourceRequestSchema.shape });
23556
+ previewEnvironmentConfigSourceToolInputSchema = previewEnvironmentConfigSourceRequestSchema.safeExtend(environmentMcpPath);
23557
+ applyEnvironmentConfigSourceToolInputSchema = applyEnvironmentConfigSourceRequestSchema.safeExtend(environmentMcpPath);
23458
23558
  }
23459
23559
  });
23460
23560
 
@@ -38314,6 +38414,31 @@ var init_hook_config = __esm({
38314
38414
  });
38315
38415
 
38316
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
+ }
38317
38442
  var DEFAULT_WARM_HOOK_TIMEOUT_MS, MAX_WARM_HOOK_TIMEOUT_MS, DEFAULT_START_HOOK_TIMEOUT_MS, HOOK_EXEC_MAX_BUFFER_BYTES;
38318
38443
  var init_warm_hooks = __esm({
38319
38444
  "../shared/src/warm-hooks.ts"() {
@@ -38326,69 +38451,90 @@ var init_warm_hooks = __esm({
38326
38451
  }
38327
38452
  });
38328
38453
 
38329
- // ../shared/src/environment-config.ts
38330
- var variableNameSchema, mcpValueSchema, mcpValuesSchema, httpConfigSchema, replicasMcpDefinitionSchema, replicasEnvironmentConfigSchema;
38331
- var init_environment_config = __esm({
38332
- "../shared/src/environment-config.ts"() {
38333
- "use strict";
38334
- init_zod();
38335
- init_environment();
38336
- init_environment_setups();
38337
- variableNameSchema = external_exports.string().regex(VARIABLE_KEY_RE, "must be a valid environment variable name");
38338
- mcpValueSchema = external_exports.union([
38339
- external_exports.string(),
38340
- environmentMcpVariableReferenceSchema
38341
- ]);
38342
- mcpValuesSchema = external_exports.record(external_exports.string(), mcpValueSchema);
38343
- httpConfigSchema = environmentMcpHttpConfigSchema.pick({ url: true, auth: true }).extend({
38344
- headers: mcpValuesSchema.default({})
38345
- }).strict();
38346
- replicasMcpDefinitionSchema = external_exports.discriminatedUnion("transport", [
38347
- external_exports.strictObject({
38348
- transport: external_exports.literal("stdio"),
38349
- config: environmentMcpStdioConfigSchema.pick({ command: true }).extend({
38350
- args: environmentMcpStdioConfigSchema.shape.args.unwrap().default([]),
38351
- env: external_exports.record(variableNameSchema, mcpValueSchema).default({})
38352
- }).strict()
38353
- }),
38354
- external_exports.strictObject({ transport: external_exports.literal("http"), config: httpConfigSchema }),
38355
- external_exports.strictObject({ transport: external_exports.literal("sse"), config: httpConfigSchema })
38356
- ]).superRefine((definition, context) => {
38357
- if (definition.transport === "stdio") return;
38358
- const result = validateEnvironmentMcpAuthentication(definition.transport, definition.config);
38359
- if (!result.ok) context.addIssue({ code: "custom", path: result.error.code === "transport" ? ["transport"] : ["config", result.error.code ?? "auth"], message: result.error.message });
38360
- });
38361
- replicasEnvironmentConfigSchema = external_exports.strictObject({
38362
- systemPrompt: external_exports.string().optional(),
38363
- warmHook: external_exports.string().optional(),
38364
- startHook: external_exports.string().optional(),
38365
- variables: external_exports.record(variableNameSchema, external_exports.string()).optional(),
38366
- requiredSecrets: external_exports.array(variableNameSchema).optional(),
38367
- 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()
38368
- }).superRefine((config3, context) => {
38369
- const names = /* @__PURE__ */ new Set();
38370
- for (const name of Object.keys(config3.mcps ?? {})) {
38371
- const normalized = name.toLowerCase();
38372
- if (names.has(normalized)) {
38373
- context.addIssue({ code: "custom", path: ["mcps", name], message: "MCP names must be unique regardless of case" });
38374
- }
38375
- names.add(normalized);
38376
- }
38377
- for (const key of config3.requiredSecrets ?? []) {
38378
- if (config3.variables && Object.hasOwn(config3.variables, key)) {
38379
- context.addIssue({ code: "custom", path: ["requiredSecrets"], message: `"${key}" cannot also be declared as a non-secret variable` });
38380
- }
38381
- }
38382
- });
38383
- }
38384
- });
38385
-
38386
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
+ }
38387
38532
  var import_yaml2, REPLICAS_CONFIG_FILENAMES;
38388
38533
  var init_replicas_config = __esm({
38389
38534
  "../shared/src/replicas-config.ts"() {
38390
38535
  "use strict";
38391
38536
  import_yaml2 = __toESM(require_dist());
38537
+ init_result();
38392
38538
  init_warm_hooks();
38393
38539
  init_environment_config();
38394
38540
  REPLICAS_CONFIG_FILENAMES = ["replicas.json", "replicas.yaml", "replicas.yml"];
@@ -38500,7 +38646,7 @@ var CLI_VERSION;
38500
38646
  var init_cli_version = __esm({
38501
38647
  "../shared/src/cli-version.ts"() {
38502
38648
  "use strict";
38503
- CLI_VERSION = "0.3.434";
38649
+ CLI_VERSION = "0.3.436";
38504
38650
  }
38505
38651
  });
38506
38652
 
@@ -48702,8 +48848,8 @@ var require_CronFileParser = __commonJS({
48702
48848
  */
48703
48849
  static async parseFile(filePath) {
48704
48850
  var _a3;
48705
- const { readFile } = await Promise.resolve().then(() => __importStar(require("fs/promises")));
48706
- 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");
48707
48853
  return __privateMethod(_a3 = _CronFileParser, _CronFileParser_static, parseContent_fn).call(_a3, data);
48708
48854
  }
48709
48855
  /**
@@ -50555,7 +50701,7 @@ async function apiKeyLoginCommand(key) {
50555
50701
  }
50556
50702
  async function loginCommand() {
50557
50703
  const state = generateState();
50558
- return new Promise((resolve3, reject) => {
50704
+ return new Promise((resolve4, reject) => {
50559
50705
  let authTimeout;
50560
50706
  let hasHandledCallback = false;
50561
50707
  let lastRedirectUrl = null;
@@ -50705,7 +50851,7 @@ async function loginCommand() {
50705
50851
  setImmediate(() => {
50706
50852
  server.closeAllConnections?.();
50707
50853
  server.close();
50708
- resolve3();
50854
+ resolve4();
50709
50855
  });
50710
50856
  } catch (error63) {
50711
50857
  const errorUrl = `${WEB_APP_URL}/cli-login/error?message=${encodeURIComponent("Failed to verify authentication.")}`;
@@ -50971,7 +51117,7 @@ async function waitForUser(params) {
50971
51117
  let value = params.initial;
50972
51118
  const deadline = Date.now() + timeoutMs;
50973
51119
  while (!params.settled(value) && Date.now() < deadline) {
50974
- await new Promise((resolve3) => setTimeout(resolve3, VARIABLE_REQUEST_WAIT.pollMs));
51120
+ await new Promise((resolve4) => setTimeout(resolve4, VARIABLE_REQUEST_WAIT.pollMs));
50975
51121
  value = await params.poll(true);
50976
51122
  }
50977
51123
  return params.settled(value) ? value : params.poll(false);
@@ -51006,7 +51152,7 @@ function buildSSHArgs(token, host, proxyCommand, localForward) {
51006
51152
  ];
51007
51153
  }
51008
51154
  async function connectSSH(token, host, proxyCommand, localForward) {
51009
- return new Promise((resolve3, reject) => {
51155
+ return new Promise((resolve4, reject) => {
51010
51156
  const ssh = (0, import_child_process.spawn)("ssh", buildSSHArgs(token, host, proxyCommand, localForward), {
51011
51157
  stdio: "inherit"
51012
51158
  });
@@ -51014,7 +51160,7 @@ async function connectSSH(token, host, proxyCommand, localForward) {
51014
51160
  if (localForward && code) {
51015
51161
  reject(new Error(`SSH tunnel exited with code ${code}`));
51016
51162
  } else {
51017
- resolve3();
51163
+ resolve4();
51018
51164
  }
51019
51165
  });
51020
51166
  ssh.on("error", reject);
@@ -51589,7 +51735,7 @@ async function exchangeCodeForTokens(code, codeVerifier) {
51589
51735
  };
51590
51736
  }
51591
51737
  function startCallbackServer(expectedState, codeVerifier, save) {
51592
- return new Promise((resolve3, reject) => {
51738
+ return new Promise((resolve4, reject) => {
51593
51739
  const server = import_http2.default.createServer(async (req, res) => {
51594
51740
  try {
51595
51741
  if (!req.url) {
@@ -51633,7 +51779,7 @@ function startCallbackServer(expectedState, codeVerifier, save) {
51633
51779
  res.writeHead(302, { "Location": completionUrl });
51634
51780
  res.end();
51635
51781
  server.close();
51636
- resolve3();
51782
+ resolve4();
51637
51783
  } catch (tokenError) {
51638
51784
  const errorMessage = encodeURIComponent(tokenError instanceof Error ? tokenError.message : "Unknown error");
51639
51785
  res.writeHead(302, { "Location": `${WEB_APP_URL2}/codex/oauth/error?message=${errorMessage}` });
@@ -51667,7 +51813,7 @@ async function runCodexOAuthFlow(totalSteps, save) {
51667
51813
  const state = generateState2();
51668
51814
  const authUrl = buildAuthorizationUrl(pkce.codeChallenge, state);
51669
51815
  const tokensPromise = startCallbackServer(state, pkce.codeVerifier, save);
51670
- await new Promise((resolve3) => setTimeout(resolve3, 500));
51816
+ await new Promise((resolve4) => setTimeout(resolve4, 500));
51671
51817
  renderAuthFlowStep(1, totalSteps, "Approve access in your browser");
51672
51818
  await openForApproval("auth.openai.com", authUrl);
51673
51819
  renderAuthFlowDetail("waiting for sign-in\u2026");
@@ -51851,10 +51997,10 @@ async function promptForAuthorizationCode() {
51851
51997
  process.stdin.setRawMode(false);
51852
51998
  process.stdin.resume();
51853
51999
  const rl = import_readline.default.createInterface({ input: process.stdin, output: process.stdout });
51854
- return new Promise((resolve3) => {
51855
- rl.on("close", () => resolve3(""));
52000
+ return new Promise((resolve4) => {
52001
+ rl.on("close", () => resolve4(""));
51856
52002
  rl.question(import_chalk15.default.gray(" Paste code here: "), (answer) => {
51857
- resolve3(answer.trim());
52003
+ resolve4(answer.trim());
51858
52004
  rl.close();
51859
52005
  });
51860
52006
  });
@@ -52024,7 +52170,7 @@ async function runMuseOAuthFlow(totalSteps) {
52024
52170
  const deadline = Date.now() + (typeof device.expires_in === "number" ? device.expires_in : 900) * 1e3;
52025
52171
  let intervalMs = Math.max(1, typeof device.interval === "number" ? device.interval : 5) * 1e3;
52026
52172
  while (Date.now() < deadline) {
52027
- await new Promise((resolve3) => setTimeout(resolve3, intervalMs));
52173
+ await new Promise((resolve4) => setTimeout(resolve4, intervalMs));
52028
52174
  const response = await post("/oidc/device/token/", new URLSearchParams({
52029
52175
  grant_type: "urn:ietf:params:oauth:grant-type:device_code",
52030
52176
  device_code: device.device_code,
@@ -55322,14 +55468,14 @@ function launchChrome() {
55322
55468
  }
55323
55469
  }
55324
55470
  });
55325
- const send = (method, params = {}, sessionId) => new Promise((resolve3, reject) => {
55471
+ const send = (method, params = {}, sessionId) => new Promise((resolve4, reject) => {
55326
55472
  if (exitError) return reject(exitError);
55327
55473
  const id = nextId++;
55328
55474
  const timer = setTimeout(() => {
55329
55475
  pending.delete(id);
55330
55476
  reject(new Error(`Chrome did not answer ${method} within ${COMMAND_TIMEOUT_MS / 1e3}s`));
55331
55477
  }, COMMAND_TIMEOUT_MS);
55332
- pending.set(id, { resolve: resolve3, reject, timer });
55478
+ pending.set(id, { resolve: resolve4, reject, timer });
55333
55479
  input2.write(`${JSON.stringify({ id, method, params, ...sessionId ? { sessionId } : {} })}\0`);
55334
55480
  });
55335
55481
  return {
@@ -55356,7 +55502,7 @@ function launchChrome() {
55356
55502
  // Callers exit the process right after, and Chrome's helper processes write into the profile until Chrome exits.
55357
55503
  async close() {
55358
55504
  if (child.exitCode === null && child.signalCode === null) {
55359
- const exited = new Promise((resolve3) => child.once("exit", resolve3));
55505
+ const exited = new Promise((resolve4) => child.once("exit", resolve4));
55360
55506
  const kill = setTimeout(() => child.kill("SIGKILL"), CLOSE_TIMEOUT_MS);
55361
55507
  send("Browser.close").catch(() => child.kill("SIGKILL"));
55362
55508
  await exited;
@@ -55412,21 +55558,21 @@ async function servePage(html) {
55412
55558
  response.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Content-Security-Policy": "sandbox allow-scripts" });
55413
55559
  response.end(html);
55414
55560
  });
55415
- 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));
55416
55562
  const address = server.address();
55417
55563
  const origin = `http://127.0.0.1:${typeof address === "object" && address ? address.port : 0}`;
55418
55564
  return { server, pageUrl: `${origin}/page.html`, fontUrl: font ? `${origin}${VISUAL_FONT_PATH}` : void 0 };
55419
55565
  }
55420
55566
  function waitFor(page, method, timeoutMs) {
55421
- return new Promise((resolve3) => {
55567
+ return new Promise((resolve4) => {
55422
55568
  const stop = page.on(method, () => {
55423
55569
  clearTimeout(timer);
55424
55570
  stop();
55425
- resolve3(true);
55571
+ resolve4(true);
55426
55572
  });
55427
55573
  const timer = setTimeout(() => {
55428
55574
  stop();
55429
- resolve3(false);
55575
+ resolve4(false);
55430
55576
  }, timeoutMs);
55431
55577
  });
55432
55578
  }
@@ -55875,11 +56021,11 @@ var init_gpu2 = __esm({
55875
56021
  // src/commands/environment-config.ts
55876
56022
  function printSource({ source }) {
55877
56023
  if (!source) {
55878
- 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.");
55879
56025
  return;
55880
56026
  }
55881
- console.log(`${source.repository_name}/${source.filename} @ ${source.commit_sha}`);
55882
- 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);
55883
56029
  console.log(`Synced: ${source.synced_at}`);
55884
56030
  console.log(`Managed settings: ${source.managed.fields.join(", ") || "(none)"}`);
55885
56031
  console.log(`Managed variables: ${source.managed.variables.join(", ") || "(none)"}`);
@@ -55889,19 +56035,30 @@ function printSource({ source }) {
55889
56035
  if (source.last_error) console.log(import_chalk29.default.red(source.last_error));
55890
56036
  }
55891
56037
  function printPreview({ preview: preview2 }) {
55892
- console.log(`${preview2.repository_name}/${preview2.filename} @ ${preview2.commit_sha}`);
55893
- console.log(preview2.source_url);
55894
- 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.");
55895
56041
  for (const change of preview2.changes) console.log(` ${change.operation}: ${change.kind} ${change.key}`);
55896
56042
  if (preview2.missing_secrets.length) console.log(import_chalk29.default.yellow(`Missing required secrets: ${preview2.missing_secrets.join(", ")}`));
55897
56043
  for (const blocker of preview2.blockers) console.log(import_chalk29.default.red(` Cannot apply: ${blocker}`));
55898
56044
  }
55899
- async function previewSource(id, repository) {
55900
- const [repositoryId] = repository ? await resolveRepositoryIds([repository]) : [];
55901
- return orgAuthenticatedFetch(`/v1/environments/${id}/config-source/preview`, {
55902
- method: "POST",
55903
- body: repositoryId ? { repository_id: repositoryId } : {}
55904
- });
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 });
55905
56062
  }
55906
56063
  async function environmentConfigGetCommand(environment2) {
55907
56064
  ensureOrgApiAuthenticated();
@@ -55910,12 +56067,14 @@ async function environmentConfigGetCommand(environment2) {
55910
56067
  }
55911
56068
  async function environmentConfigPreviewCommand(environment2, options) {
55912
56069
  ensureOrgApiAuthenticated();
55913
- output2(await previewSource(await resolveEnvironmentId(environment2), options.repository), printPreview);
56070
+ const input2 = await sourceInput2(options);
56071
+ output2(await previewSource(await resolveEnvironmentId(environment2), input2), printPreview);
55914
56072
  }
55915
56073
  async function applySource(environment2, options, operation) {
55916
56074
  ensureOrgApiAuthenticated();
55917
56075
  const id = await resolveEnvironmentId(environment2);
55918
- const response = await previewSource(id, options.repository);
56076
+ const input2 = await sourceInput2(options);
56077
+ const response = await previewSource(id, input2);
55919
56078
  if (!isJsonMode()) printPreview(response);
55920
56079
  const { preview: preview2 } = response;
55921
56080
  if (preview2.blockers.length || preview2.missing_secrets.length) {
@@ -55928,9 +56087,13 @@ async function applySource(environment2, options, operation) {
55928
56087
  if (!isInteractive()) throw new Error("Preview the changes with replicas environment config preview, then pass --yes to apply without a terminal.");
55929
56088
  if (!await confirmAction(`${operation === "link" ? "Link and apply" : "Apply"} this configuration to ${environment2}?`)) return;
55930
56089
  }
55931
- 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 };
55932
56092
  output2(await orgAuthenticatedFetch(`/v1/environments/${id}/config-source${operation === "sync" ? "/sync" : ""}`, { method: "POST", body }), printSource);
55933
56093
  }
56094
+ async function environmentConfigApplyCommand(environment2, options) {
56095
+ await applySource(environment2, options, "file");
56096
+ }
55934
56097
  async function environmentConfigLinkCommand(environment2, options) {
55935
56098
  await applySource(environment2, options, "link");
55936
56099
  }
@@ -55942,17 +56105,20 @@ async function environmentConfigDisconnectCommand(environment2, options) {
55942
56105
  const id = await resolveEnvironmentId(environment2);
55943
56106
  if (!options.yes) {
55944
56107
  if (!isInteractive()) throw new Error("Pass --yes to disconnect without a terminal. Current settings will be preserved.");
55945
- 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;
55946
56109
  }
55947
56110
  output2(await orgAuthenticatedFetch(`/v1/environments/${id}/config-source`, { method: "DELETE" }), () => {
55948
- console.log("Git configuration disconnected. Current settings preserved.");
56111
+ console.log("Configuration source disconnected. Current settings preserved.");
55949
56112
  });
55950
56113
  }
55951
- var import_chalk29;
56114
+ var import_chalk29, import_promises2, import_node_path3;
55952
56115
  var init_environment_config2 = __esm({
55953
56116
  "src/commands/environment-config.ts"() {
55954
56117
  "use strict";
55955
56118
  import_chalk29 = __toESM(require("chalk"));
56119
+ import_promises2 = require("fs/promises");
56120
+ import_node_path3 = require("path");
56121
+ init_src();
55956
56122
  init_api2();
55957
56123
  init_command_utils();
55958
56124
  init_output();
@@ -55968,18 +56134,18 @@ async function historyTranscriptCommand(name) {
55968
56134
  throw new Error(`Invalid session name '${name}'. Use the name from INDEX.md, e.g. 2026-01-31-<id>`);
55969
56135
  }
55970
56136
  const response = await agentRequest(`/v1/engine/history/transcripts/${session}`);
55971
- const dir = (0, import_node_path3.join)(HISTORY_ROOT, "transcripts");
56137
+ const dir = (0, import_node_path4.join)(HISTORY_ROOT, "transcripts");
55972
56138
  (0, import_node_fs3.mkdirSync)(dir, { recursive: true });
55973
- const file2 = (0, import_node_path3.join)(dir, `${session}.jsonl`);
56139
+ const file2 = (0, import_node_path4.join)(dir, `${session}.jsonl`);
55974
56140
  (0, import_node_fs3.writeFileSync)(file2, Buffer.from(await response.arrayBuffer()));
55975
56141
  output2({ path: file2 }, () => console.log(file2));
55976
56142
  }
55977
- var import_node_fs3, import_node_path3;
56143
+ var import_node_fs3, import_node_path4;
55978
56144
  var init_history = __esm({
55979
56145
  "src/commands/history.ts"() {
55980
56146
  "use strict";
55981
56147
  import_node_fs3 = require("fs");
55982
- import_node_path3 = require("path");
56148
+ import_node_path4 = require("path");
55983
56149
  init_src();
55984
56150
  init_agent_api();
55985
56151
  init_output();
@@ -56109,7 +56275,7 @@ function tailLines(content, lines) {
56109
56275
  return all.slice(-lines).join("\n").trim();
56110
56276
  }
56111
56277
  function statePath(name) {
56112
- return (0, import_node_path4.join)(SERVICES_DIR, `${name}.json`);
56278
+ return (0, import_node_path5.join)(SERVICES_DIR, `${name}.json`);
56113
56279
  }
56114
56280
  function isServiceState(value) {
56115
56281
  if (typeof value !== "object" || value === null) return false;
@@ -56179,8 +56345,8 @@ async function serviceStartCommand(name, commandParts, options) {
56179
56345
  await killServiceGroup(existing.pid);
56180
56346
  }
56181
56347
  (0, import_node_fs5.mkdirSync)(SERVICES_DIR, { recursive: true });
56182
- const cwd = (0, import_node_path4.resolve)(options.cwd ?? process.cwd());
56183
- 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`);
56184
56350
  const logFd = (0, import_node_fs5.openSync)(logFile, "a");
56185
56351
  (0, import_node_fs5.writeFileSync)(logFd, `
56186
56352
  === [replicas service] "${name}" started ${(/* @__PURE__ */ new Date()).toISOString()} in ${cwd}: ${command} ===
@@ -56266,7 +56432,7 @@ async function serviceLogsCommand(name, options) {
56266
56432
  console.log(logs || "(no log output yet)");
56267
56433
  });
56268
56434
  }
56269
- 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;
56270
56436
  var init_service = __esm({
56271
56437
  "src/commands/service.ts"() {
56272
56438
  "use strict";
@@ -56274,10 +56440,10 @@ var init_service = __esm({
56274
56440
  import_node_child_process3 = require("child_process");
56275
56441
  import_node_fs5 = require("fs");
56276
56442
  import_node_os3 = require("os");
56277
- import_node_path4 = require("path");
56443
+ import_node_path5 = require("path");
56278
56444
  init_src();
56279
56445
  init_output();
56280
- 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");
56281
56447
  NAME_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/;
56282
56448
  LOG_KEEP_BYTES = 5 * 1024 * 1024;
56283
56449
  LOG_TRIM_LOOP = `trim() { ${trimLogTailCommand('"$1"', 10 * 1024 * 1024, LOG_KEEP_BYTES)}; }
@@ -56373,17 +56539,17 @@ async function deviceConnectCommand() {
56373
56539
  const next = problem ?? `\u2713 ${device?.name}: ready for ${waiting.size} ${waiting.size === 1 ? "workspace" : "workspaces"}, forwarding to SSH on port ${port}`;
56374
56540
  if (next !== summary) console.log(problem ? import_chalk33.default.yellow(next) : import_chalk33.default.green(next));
56375
56541
  summary = next;
56376
- await (0, import_promises2.setTimeout)(POLL_INTERVAL_MS);
56542
+ await (0, import_promises3.setTimeout)(POLL_INTERVAL_MS);
56377
56543
  }
56378
56544
  }
56379
- 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;
56380
56546
  var init_device = __esm({
56381
56547
  "src/commands/device.ts"() {
56382
56548
  "use strict";
56383
56549
  import_chalk33 = __toESM(require("chalk"));
56384
56550
  import_node_child_process4 = require("child_process");
56385
56551
  import_node_net = require("net");
56386
- import_promises2 = require("timers/promises");
56552
+ import_promises3 = require("timers/promises");
56387
56553
  import_node_util = require("util");
56388
56554
  import_ws = __toESM(require("ws"));
56389
56555
  init_src();
@@ -56708,7 +56874,8 @@ var init_src2 = __esm({
56708
56874
  environment.command("delete <id-or-name>").description("Delete an environment").option("-f, --force", "Skip confirmation prompt").action(run(environmentDeleteCommand));
56709
56875
  envConfig = environment.command("config").description("Link and sync environment configuration from Git");
56710
56876
  envConfig.command("get <env>").description("Show the linked configuration source and sync status").action(run(environmentConfigGetCommand));
56711
- 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));
56712
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));
56713
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));
56714
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.434",
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": {