@preplabsai/rovara-code 0.5.20 → 0.5.21

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/bin/agentx-cli.mjs +592 -863
  2. package/package.json +1 -1
@@ -100357,7 +100357,7 @@ var require_dist_cjs16 = __commonJS({
100357
100357
  var { setCredentialFeature: setCredentialFeature2 } = (init_client3(), __toCommonJS(client_exports2));
100358
100358
  var { CredentialsProviderError: CredentialsProviderError2, parseKnownFiles: parseKnownFiles2, getProfileName: getProfileName2 } = (init_config2(), __toCommonJS(config_exports));
100359
100359
  var { HttpRequest: HttpRequest2 } = (init_protocols(), __toCommonJS(protocols_exports));
100360
- var { createHash: createHash39, createPrivateKey, createPublicKey: createPublicKey2, sign: sign3 } = __require("node:crypto");
100360
+ var { createHash: createHash38, createPrivateKey, createPublicKey: createPublicKey2, sign: sign3 } = __require("node:crypto");
100361
100361
  var { promises } = __require("node:fs");
100362
100362
  var { homedir: homedir6 } = __require("node:os");
100363
100363
  var { dirname: dirname13, join: join34 } = __require("node:path");
@@ -100528,7 +100528,7 @@ var require_dist_cjs16 = __commonJS({
100528
100528
  getTokenFilePath() {
100529
100529
  const directory = process.env.AWS_LOGIN_CACHE_DIRECTORY ?? join34(homedir6(), ".aws", "login", "cache");
100530
100530
  const loginSessionBytes = Buffer.from(this.loginSession, "utf8");
100531
- const loginSessionSha256 = createHash39("sha256").update(loginSessionBytes).digest("hex");
100531
+ const loginSessionSha256 = createHash38("sha256").update(loginSessionBytes).digest("hex");
100532
100532
  return join34(directory, `${loginSessionSha256}.json`);
100533
100533
  }
100534
100534
  derToRawSignature(derSignature) {
@@ -295331,7 +295331,7 @@ var require_dist_cjs42 = __commonJS({
295331
295331
  return async () => handler(this.clientCommand);
295332
295332
  }
295333
295333
  };
295334
- var PutCommand4 = class extends DynamoDBDocumentClientCommand {
295334
+ var PutCommand3 = class extends DynamoDBDocumentClientCommand {
295335
295335
  input;
295336
295336
  inputKeyNodes = {
295337
295337
  Item: ALL_VALUES,
@@ -295715,7 +295715,7 @@ var require_dist_cjs42 = __commonJS({
295715
295715
  }
295716
295716
  }
295717
295717
  put(args, optionsOrCb, cb) {
295718
- const command5 = new PutCommand4(args);
295718
+ const command5 = new PutCommand3(args);
295719
295719
  if (typeof optionsOrCb === "function") {
295720
295720
  this.send(command5, optionsOrCb);
295721
295721
  } else if (typeof cb === "function") {
@@ -295816,7 +295816,7 @@ var require_dist_cjs42 = __commonJS({
295816
295816
  exports.ExecuteStatementCommand = ExecuteStatementCommand;
295817
295817
  exports.ExecuteTransactionCommand = ExecuteTransactionCommand;
295818
295818
  exports.GetCommand = GetCommand8;
295819
- exports.PutCommand = PutCommand4;
295819
+ exports.PutCommand = PutCommand3;
295820
295820
  exports.QueryCommand = QueryCommand6;
295821
295821
  exports.ScanCommand = ScanCommand2;
295822
295822
  exports.SearchVectorsCommand = SearchVectorsCommand;
@@ -339656,7 +339656,7 @@ var init_application_build_source = __esm({
339656
339656
  });
339657
339657
 
339658
339658
  // packages/verifier/dist/rovara-http-engine-descriptor.js
339659
- import { createHash as createHash34 } from "node:crypto";
339659
+ import { createHash as createHash33 } from "node:crypto";
339660
339660
  var ROVARA_HTTP_ENGINE_ASSERTION_FIXTURE, ROVARA_HTTP_ENGINE_DESCRIPTOR, ROVARA_HTTP_ENGINE_DIGEST;
339661
339661
  var init_rovara_http_engine_descriptor = __esm({
339662
339662
  "packages/verifier/dist/rovara-http-engine-descriptor.js"() {
@@ -339670,7 +339670,7 @@ var init_rovara_http_engine_descriptor = __esm({
339670
339670
  platform: "api",
339671
339671
  capabilities: Object.freeze([ROVARA_HTTP_ENGINE_ASSERTION_FIXTURE])
339672
339672
  });
339673
- ROVARA_HTTP_ENGINE_DIGEST = createHash34("sha256").update(canonicalJson(ROVARA_HTTP_ENGINE_DESCRIPTOR)).digest("hex");
339673
+ ROVARA_HTTP_ENGINE_DIGEST = createHash33("sha256").update(canonicalJson(ROVARA_HTTP_ENGINE_DESCRIPTOR)).digest("hex");
339674
339674
  }
339675
339675
  });
339676
339676
 
@@ -340462,7 +340462,7 @@ var init_evidence_paths = __esm({
340462
340462
  });
340463
340463
 
340464
340464
  // packages/verifier/dist/application-result-adapter.js
340465
- import { createHash as createHash35 } from "node:crypto";
340465
+ import { createHash as createHash34 } from "node:crypto";
340466
340466
  function e2eApplicationSupervisorEvidenceEntryMax(caseCount) {
340467
340467
  if (!Number.isSafeInteger(caseCount) || caseCount < 1 || caseCount > 64)
340468
340468
  throw new TypeError("supervisor proof case count is outside the admitted bound");
@@ -340955,7 +340955,7 @@ var init_application_result_adapter = __esm({
340955
340955
  if (field4.byteLength > E2E_REPORT_MAX_BYTES || field4.bytesBase64.length !== Math.ceil(field4.byteLength / 3) * 4)
340956
340956
  throw new Error();
340957
340957
  const decoded = Buffer.from(field4.bytesBase64, "base64");
340958
- if (decoded.toString("base64") !== field4.bytesBase64 || decoded.byteLength !== field4.byteLength || createHash35("sha256").update(decoded).digest("hex") !== field4.sha256)
340958
+ if (decoded.toString("base64") !== field4.bytesBase64 || decoded.byteLength !== field4.byteLength || createHash34("sha256").update(decoded).digest("hex") !== field4.sha256)
340959
340959
  throw new Error();
340960
340960
  } catch {
340961
340961
  context.addIssue({ code: "custom", path: ["shards"], message: "private shard bytes are not canonical base64 with the declared size and digest" });
@@ -340979,7 +340979,7 @@ var init_application_result_adapter = __esm({
340979
340979
  if (proof.ref.byteLength > 26214400 || proof.bytesBase64.length !== expectedLength || proof.bytesBase64.length > 35e6)
340980
340980
  throw new Error();
340981
340981
  const bytes5 = Buffer.from(proof.bytesBase64, "base64");
340982
- if (bytes5.toString("base64") !== proof.bytesBase64 || bytes5.byteLength !== proof.ref.byteLength || createHash35("sha256").update(bytes5).digest("hex") !== proof.ref.sha256 || proofIds.has(proof.ref.artifactId))
340982
+ if (bytes5.toString("base64") !== proof.bytesBase64 || bytes5.byteLength !== proof.ref.byteLength || createHash34("sha256").update(bytes5).digest("hex") !== proof.ref.sha256 || proofIds.has(proof.ref.artifactId))
340983
340983
  throw new Error();
340984
340984
  proofIds.add(proof.ref.artifactId);
340985
340985
  proofBytes += bytes5.byteLength;
@@ -341078,7 +341078,7 @@ var init_application_result_adapter = __esm({
341078
341078
  if (new Set(originRows.map((item) => item.componentId)).size !== originRows.length || originRows.some((item) => !sourceDerivedMocks.some((spec) => spec.componentId === item.componentId))) {
341079
341079
  context.addIssue({ code: "custom", path: ["mockOrigins"], message: "mock origins must name each approved mock component at most once" });
341080
341080
  }
341081
- if (createHash35("sha256").update(canonicalJson(sourceDerivedMocks)).digest("hex") !== oracle.binding.mockManifestDigest) {
341081
+ if (createHash34("sha256").update(canonicalJson(sourceDerivedMocks)).digest("hex") !== oracle.binding.mockManifestDigest) {
341082
341082
  context.addIssue({ code: "custom", path: ["expectedMocksByCase"], message: "case mock expectations do not reproduce the admitted mock manifest digest" });
341083
341083
  }
341084
341084
  const componentsByTarget = /* @__PURE__ */ new Map();
@@ -341394,7 +341394,7 @@ var init_install_qualification = __esm({
341394
341394
  });
341395
341395
 
341396
341396
  // packages/verifier/dist/executor/host-registry.js
341397
- import { createHash as createHash36 } from "node:crypto";
341397
+ import { createHash as createHash35 } from "node:crypto";
341398
341398
  var E2E_EXECUTOR_HOST_ENTRY_POINT_ID, E2E_EXECUTOR_HOST_ENTRY_SOURCE, E2E_EXECUTOR_HOST_DESCRIPTOR, registrySchema;
341399
341399
  var init_host_registry = __esm({
341400
341400
  "packages/verifier/dist/executor/host-registry.js"() {
@@ -341405,7 +341405,7 @@ var init_host_registry = __esm({
341405
341405
  `;
341406
341406
  E2E_EXECUTOR_HOST_DESCRIPTOR = Object.freeze({
341407
341407
  entryPointId: E2E_EXECUTOR_HOST_ENTRY_POINT_ID,
341408
- entryPointManifestDigest: createHash36("sha256").update(E2E_EXECUTOR_HOST_ENTRY_SOURCE).digest("hex")
341408
+ entryPointManifestDigest: createHash35("sha256").update(E2E_EXECUTOR_HOST_ENTRY_SOURCE).digest("hex")
341409
341409
  });
341410
341410
  registrySchema = external_exports.object({
341411
341411
  schemaVersion: external_exports.literal("application-cli-host-registry/v1"),
@@ -341556,7 +341556,7 @@ var init_fake_core = __esm({
341556
341556
  });
341557
341557
 
341558
341558
  // packages/verifier/dist/executor/mock-server.js
341559
- import { createHash as createHash37 } from "node:crypto";
341559
+ import { createHash as createHash36 } from "node:crypto";
341560
341560
  function sortKeys2(value) {
341561
341561
  if (Array.isArray(value))
341562
341562
  return value.map(sortKeys2);
@@ -341575,7 +341575,7 @@ var init_mock_server = __esm({
341575
341575
  "use strict";
341576
341576
  init_fake_core();
341577
341577
  MOCK_UNMOCKED_STATUS = 599;
341578
- sha3 = (value) => createHash37("sha256").update(value, "utf8").digest("hex");
341578
+ sha3 = (value) => createHash36("sha256").update(value, "utf8").digest("hex");
341579
341579
  mockResponseDigest = (response) => sha3(canonicalJson2({ status: response.status, body: response.body }));
341580
341580
  MOCK_UNMOCKED_RESPONSE_DIGEST = mockResponseDigest({ status: MOCK_UNMOCKED_STATUS, body: { error: "rovara-unmocked" } });
341581
341581
  }
@@ -358901,26 +358901,19 @@ function cliRuntimeBinding(deploymentMode, options) {
358901
358901
  }
358902
358902
  }
358903
358903
  async function registerProject(options, fetchImplementation = fetch) {
358904
- if (options.takeOwnership !== void 0 && options.takeOwnership.reason.trim() === "") {
358905
- throw agentXError("CONFIG_INVALID", "--take-ownership needs --ownership-reason <why>; the takeover is recorded with who took the project over, when, and why");
358906
- }
358907
358904
  const definition = ProjectDefinitionSchema.parse(options.definition);
358908
- WorkspaceDeploymentModeSchema.parse(options.runtimeBinding.deploymentMode);
358909
- Ec2RuntimeBindingSchema.parse(options.runtimeBinding);
358910
- const response = await fetchImplementation(`${options.controlPlaneUrl.replace(/\/$/, "")}${options.path ?? "/v1/admin/projects"}`, {
358905
+ if (options.runtimeBinding !== void 0) {
358906
+ WorkspaceDeploymentModeSchema.parse(options.runtimeBinding.deploymentMode);
358907
+ Ec2RuntimeBindingSchema.parse(options.runtimeBinding);
358908
+ }
358909
+ const response = await fetchImplementation(`${options.controlPlaneUrl.replace(/\/$/, "")}/v1/dev/projects`, {
358911
358910
  method: "POST",
358912
358911
  headers: {
358913
358912
  authorization: `Bearer ${options.accessToken}`,
358914
358913
  "content-type": "application/json"
358915
358914
  },
358916
- // Asks the control plane to check each connector with its vendor; older control planes ignore it.
358917
- body: JSON.stringify({
358918
- definition,
358919
- runtimeBinding: options.runtimeBinding,
358920
- preflight: true,
358921
- ...options.setupApproval === void 0 ? {} : { setupApproval: options.setupApproval },
358922
- ...options.takeOwnership === void 0 ? {} : { takeOwnership: true, takeOwnershipReason: options.takeOwnership.reason.trim() }
358923
- })
358915
+ // Asks the control plane to check each connector with its vendor.
358916
+ body: JSON.stringify({ definition, ...options.runtimeBinding === void 0 ? {} : { runtimeBinding: options.runtimeBinding }, preflight: true })
358924
358917
  });
358925
358918
  const { ok: ok2, status, body } = await readJsonResponse(response);
358926
358919
  if (!ok2) {
@@ -358933,50 +358926,490 @@ async function registerProject(options, fetchImplementation = fetch) {
358933
358926
  return body;
358934
358927
  }
358935
358928
 
358936
- // packages/cli/src/admin/slack.ts
358929
+ // packages/cli/src/admin/project-access.ts
358937
358930
  init_dist2();
358938
- async function bindSlackChannel(input2, fetchImplementation = fetch) {
358939
- return sendBindingRequest(input2, "PUT", fetchImplementation, JSON.stringify({ projectName: input2.projectName }));
358931
+
358932
+ // packages/cli/src/company/people.ts
358933
+ init_dist2();
358934
+ import { randomUUID as randomUUID3 } from "node:crypto";
358935
+
358936
+ // packages/cli/src/session/app-request.ts
358937
+ init_dist2();
358938
+
358939
+ // packages/cli/src/output.ts
358940
+ init_dist2();
358941
+
358942
+ // packages/cli/src/stopped.ts
358943
+ init_dist2();
358944
+ var StoppedByOperator = class extends Error {
358945
+ exitCode = 130;
358946
+ constructor(message) {
358947
+ super(message);
358948
+ this.name = "StoppedByOperator";
358949
+ }
358950
+ };
358951
+ function isCtrlCAtPrompt(error64) {
358952
+ for (let current = error64, depth = 0; current instanceof Error && depth < 10; current = current.cause, depth += 1) {
358953
+ if (current.name === "AbortError" && /Ctrl\+C/.test(current.message)) return true;
358954
+ if (current instanceof AgentXError && current.code === "CONFIG_INVALID" && current.message.replace(/^CONFIG_INVALID: /, "") === "cancelled") return true;
358955
+ }
358956
+ return false;
358940
358957
  }
358941
- async function bindCompanyChannel(input2, fetchImplementation = fetch) {
358942
- const projectName = AgentXNameSchema.parse(input2.projectName);
358943
- return sendBindingRequest(input2, "PUT", fetchImplementation, void 0, `/v1/dev/company/slack/projects/${projectName}/bindings`);
358958
+
358959
+ // packages/cli/src/output.ts
358960
+ function formatSuccess(data, json3) {
358961
+ if (json3) return `${JSON.stringify({ ok: true, data })}
358962
+ `;
358963
+ return typeof data === "string" ? `${data}
358964
+ ` : `${JSON.stringify(data, null, 2)}
358965
+ `;
358944
358966
  }
358945
- async function unbindSlackChannel(input2, fetchImplementation = fetch) {
358946
- return sendBindingRequest(input2, "DELETE", fetchImplementation);
358967
+ var ReportedFailure = class extends Error {
358968
+ constructor(failureCode, message, exitCode = 1) {
358969
+ super(message);
358970
+ this.failureCode = failureCode;
358971
+ this.exitCode = exitCode;
358972
+ this.name = "ReportedFailure";
358973
+ }
358974
+ failureCode;
358975
+ exitCode;
358976
+ };
358977
+ function formatError2(error64, json3) {
358978
+ if (error64 instanceof StoppedByOperator) {
358979
+ return { text: json3 ? `${JSON.stringify({ ok: false, error: { code: "STOPPED", message: error64.message } })}
358980
+ ` : `${error64.message}
358981
+ `, exitCode: error64.exitCode };
358982
+ }
358983
+ if (error64 instanceof ReportedFailure) {
358984
+ return { text: json3 ? `${JSON.stringify({ ok: false, error: { code: error64.failureCode, message: error64.message } })}
358985
+ ` : `${error64.message}
358986
+ `, exitCode: error64.exitCode };
358987
+ }
358988
+ const normalized = error64 instanceof AgentXError ? { code: error64.code, message: stripCodePrefix(error64.message, error64.code) } : { code: "INTERNAL_ERROR", message: error64 instanceof Error ? error64.message : "unexpected error" };
358989
+ const text11 = json3 ? `${JSON.stringify({ ok: false, error: normalized })}
358990
+ ` : `AgentX error [${normalized.code}]: ${normalized.message}
358991
+ `;
358992
+ return {
358993
+ text: text11,
358994
+ exitCode: normalized.code === "INTERNAL_ERROR" ? 1 : exitCodeForError(normalized.code)
358995
+ };
358947
358996
  }
358948
- async function sendBindingRequest(input2, method, fetchImplementation, body, base2 = "/v1/admin/slack/bindings") {
358949
- const teamId = SlackTeamIdSchema.parse(input2.teamId);
358950
- const channelId = SlackChannelIdSchema.parse(input2.channelId);
358951
- const response = await fetchImplementation(
358952
- `${input2.controlPlaneUrl.replace(/\/$/, "")}${base2}/${teamId}/${channelId}`,
358953
- {
358954
- method,
358955
- headers: {
358956
- authorization: `Bearer ${input2.accessToken}`,
358957
- ...body === void 0 ? {} : { "content-type": "application/json" }
358958
- },
358959
- ...body === void 0 ? {} : { body }
358997
+ function exitCodeForError(code2) {
358998
+ if (code2 === "CONFIG_INVALID" || code2 === "PROJECT_REVISION_MISMATCH") return 2;
358999
+ if (code2 === "AUTH_REQUIRED") return 3;
359000
+ if (code2 === "FORBIDDEN" || code2 === "NOT_FOUND" || code2 === "CALLBACK_FORBIDDEN") return 4;
359001
+ if (code2 === "WORKSPACE_NOT_READY" || code2 === "WORKSPACE_BUSY") return 5;
359002
+ if (code2 === "RUNTIME_UNAVAILABLE" || code2 === "OPERATION_INTERRUPTED" || code2 === "STALE_FENCE") return 6;
359003
+ return 7;
359004
+ }
359005
+ function plainMessage(error64) {
359006
+ if (error64 instanceof AgentXError) return stripCodePrefix(error64.message, error64.code);
359007
+ return error64 instanceof Error ? error64.message : String(error64);
359008
+ }
359009
+ function stripCodePrefix(message, code2) {
359010
+ const prefix2 = `${code2}: `;
359011
+ return message.startsWith(prefix2) ? message.slice(prefix2.length) : message;
359012
+ }
359013
+
359014
+ // packages/cli/src/developer/session.ts
359015
+ init_dist2();
359016
+ init_dist2();
359017
+ import { chmod as chmod2, mkdir as mkdir3, open as open3, readFile as readFile6, rm as rm2, stat as stat2 } from "node:fs/promises";
359018
+ import { randomUUID as randomUUID2 } from "node:crypto";
359019
+ import { join as join7 } from "node:path";
359020
+
359021
+ // packages/cli/src/developer/config.ts
359022
+ init_dist2();
359023
+ init_dist2();
359024
+ var import_yaml = __toESM(require_dist4(), 1);
359025
+ init_zod();
359026
+ import { chmod, mkdir as mkdir2, open as open2, readFile as readFile5, rename, rm } from "node:fs/promises";
359027
+ import { join as join6 } from "node:path";
359028
+ var EntrySchema = external_exports.object({ url: external_exports.string().url(), issuer: external_exports.string().url(), tokenEndpoint: external_exports.string().url(), revocationEndpoint: external_exports.string().url() }).strict();
359029
+ var ConfigSchema = external_exports.object({ schemaVersion: external_exports.literal(1), default: EnvironmentNameSchema.optional(), environments: external_exports.record(EnvironmentNameSchema, EntrySchema) }).strict();
359030
+ var developerConfigPath = (home) => join6(home, ".agentx", "developer.yaml");
359031
+ var developerTokenKey = (issuer) => tokenStoreKey({ issuer, clientId: AGENTX_CLI_CLIENT_ID, audience: DEVELOPER_TOKEN_AUDIENCE });
359032
+ async function readDeveloperConfig(home) {
359033
+ let text11;
359034
+ try {
359035
+ text11 = await readFile5(developerConfigPath(home), "utf8");
359036
+ } catch (error64) {
359037
+ if (error64.code === "ENOENT") return { environments: {} };
359038
+ throw error64;
359039
+ }
359040
+ let document;
359041
+ try {
359042
+ document = import_yaml.default.parse(text11);
359043
+ } catch {
359044
+ document = void 0;
359045
+ }
359046
+ const parsed = ConfigSchema.safeParse(document);
359047
+ if (!parsed.success) throw agentXError("CONFIG_INVALID", `${developerConfigPath(home)} is invalid; delete it and run agentx login <url> again`);
359048
+ return { environments: parsed.data.environments };
359049
+ }
359050
+ async function write(home, config5) {
359051
+ const path6 = developerConfigPath(home);
359052
+ await mkdir2(join6(home, ".agentx"), { recursive: true, mode: 448 });
359053
+ await chmod(join6(home, ".agentx"), 448);
359054
+ const temp = `${path6}.${process.pid}.tmp`;
359055
+ const handle = await open2(temp, "w", 384);
359056
+ try {
359057
+ await handle.writeFile(import_yaml.default.stringify({ schemaVersion: 1, ...config5 }));
359058
+ } finally {
359059
+ await handle.close();
359060
+ }
359061
+ try {
359062
+ await rename(temp, path6);
359063
+ } catch (error64) {
359064
+ await rm(temp, { force: true });
359065
+ throw error64;
359066
+ }
359067
+ }
359068
+ async function saveDeveloperEnvironment(home, env3, entry) {
359069
+ const config5 = await readDeveloperConfig(home);
359070
+ await write(home, { environments: { ...config5.environments, [env3]: EntrySchema.parse(entry) } });
359071
+ }
359072
+ async function removeDeveloperEnvironment(home, env3) {
359073
+ const config5 = await readDeveloperConfig(home);
359074
+ const { [env3]: _removed, ...rest } = config5.environments;
359075
+ await write(home, { environments: rest });
359076
+ }
359077
+ async function forgetDeveloperSignIn(home, env3, tokenStore) {
359078
+ const entry = (await readDeveloperConfig(home)).environments[env3];
359079
+ if (entry === void 0) return false;
359080
+ await tokenStore.delete(developerTokenKey(entry.issuer));
359081
+ await removeDeveloperEnvironment(home, env3);
359082
+ return true;
359083
+ }
359084
+ async function resolveDeveloperEnvironment(home, env3) {
359085
+ const config5 = await readDeveloperConfig(home);
359086
+ const name3 = env3 ?? DEFAULT_ENVIRONMENT;
359087
+ const entry = config5.environments[name3];
359088
+ if (entry === void 0) {
359089
+ const others = Object.keys(config5.environments).sort();
359090
+ const signIn = `run npx ${CLI_PACKAGE_NAME} login <your AgentX URL>`;
359091
+ const next = others.length === 0 ? signIn : `it is signed in to ${others.join(", ")}: add --env ${others.length === 1 ? others[0] : "<name>"}, or ${signIn}`;
359092
+ throw agentXError("AUTH_REQUIRED", `this computer is not signed in to AgentX environment ${name3}; ${next}`);
359093
+ }
359094
+ return { env: name3, entry };
359095
+ }
359096
+
359097
+ // packages/cli/src/developer/session.ts
359098
+ var EARLY_MS = 6e4;
359099
+ var STALE_LOCK_MS = 3e4;
359100
+ var LOCK_POLL_MS = 50;
359101
+ function serverReason(value, fallback2) {
359102
+ return typeof value === "string" ? sanitizeServerText(value) : fallback2;
359103
+ }
359104
+ async function withRefreshLock(deps, env3, work) {
359105
+ const dir = join7(deps.home, ".agentx", "locks");
359106
+ await mkdir3(dir, { recursive: true, mode: 448 });
359107
+ await chmod2(dir, 448);
359108
+ const path6 = join7(dir, `developer-${env3}.lock`);
359109
+ const owner = `${process.pid}:${randomUUID2()}`;
359110
+ const sleep4 = deps.sleep ?? ((ms) => new Promise((resolve17) => setTimeout(resolve17, ms)));
359111
+ const deadline = Date.now() + (deps.lockWaitMs ?? 15e3);
359112
+ for (; ; ) {
359113
+ try {
359114
+ const handle = await open3(path6, "wx", 384);
359115
+ try {
359116
+ await handle.writeFile(owner);
359117
+ } finally {
359118
+ await handle.close();
359119
+ }
359120
+ break;
359121
+ } catch (error64) {
359122
+ if (error64.code !== "EEXIST") throw error64;
359123
+ const age = await stat2(path6).then((info) => Date.now() - info.mtimeMs, () => 0);
359124
+ if (age > STALE_LOCK_MS) {
359125
+ await rm2(path6, { force: true });
359126
+ continue;
359127
+ }
359128
+ if (Date.now() > deadline) throw agentXError("RUNTIME_UNAVAILABLE", `another agentx process is refreshing your sign-in to ${env3}; try again in a moment`);
359129
+ await sleep4(LOCK_POLL_MS);
358960
359130
  }
358961
- );
358962
- const { ok: ok2, status, body: parsedBody } = await readJsonResponse(response);
358963
- if (!ok2) {
358964
- const message = parsedBody === void 0 ? `HTTP ${status}` : serverError(parsedBody).message ?? `HTTP ${status}`;
358965
- throw agentXError("RUNTIME_UNAVAILABLE", `Slack channel ${method === "PUT" ? "binding" : "unbinding"} failed: ${message}`);
358966
359131
  }
358967
- if (parsedBody === void 0) throw agentXError("RUNTIME_UNAVAILABLE", "control plane returned an invalid response");
358968
- return parsedBody;
359132
+ try {
359133
+ return await work();
359134
+ } finally {
359135
+ const holder = await readFile6(path6, "utf8").catch(() => void 0);
359136
+ if (holder === owner) await rm2(path6, { force: true });
359137
+ }
359138
+ }
359139
+ async function developerAccessToken(deps, env3, options = {}) {
359140
+ const now = deps.now ?? Date.now;
359141
+ const resolved2 = await resolveDeveloperEnvironment(deps.home, env3);
359142
+ const key = developerTokenKey(resolved2.entry.issuer);
359143
+ const signIn = `run npx ${CLI_PACKAGE_NAME} login ${resolved2.entry.url}`;
359144
+ const fresh = (tokens) => tokens.expiresAt - EARLY_MS > now();
359145
+ const stored = await deps.tokenStore.get(key);
359146
+ if (stored === void 0) throw agentXError("AUTH_REQUIRED", `this computer is not signed in to AgentX environment ${resolved2.env}; ${signIn}`);
359147
+ if (options.force !== true && fresh(stored)) return { ...resolved2, accessToken: stored.accessToken };
359148
+ return withRefreshLock(deps, resolved2.env, async () => {
359149
+ const current = await deps.tokenStore.get(key);
359150
+ const replaced = options.force !== true || current?.accessToken !== stored.accessToken;
359151
+ if (current !== void 0 && fresh(current) && replaced) return { ...resolved2, accessToken: current.accessToken };
359152
+ if (current?.refreshToken === void 0) throw agentXError("AUTH_REQUIRED", `your AgentX sign-in for ${resolved2.env} has ended; ${signIn}`);
359153
+ let response;
359154
+ try {
359155
+ response = await deps.fetch(resolved2.entry.tokenEndpoint, {
359156
+ method: "POST",
359157
+ headers: { "content-type": "application/x-www-form-urlencoded" },
359158
+ body: new URLSearchParams({ grant_type: "refresh_token", client_id: AGENTX_CLI_CLIENT_ID, refresh_token: current.refreshToken }).toString(),
359159
+ signal: AbortSignal.timeout(15e3)
359160
+ });
359161
+ } catch {
359162
+ throw agentXError("RUNTIME_UNAVAILABLE", `could not reach AgentX at ${resolved2.entry.url}; check your connection and try again`);
359163
+ }
359164
+ const body = await response.json().catch(() => ({}));
359165
+ const fields = typeof body === "object" && body !== null ? body : {};
359166
+ const reason2 = serverReason(fields.error_description, "no reason given");
359167
+ if (response.status === 400 && fields.error === "invalid_grant") {
359168
+ await deps.tokenStore.delete(key);
359169
+ throw agentXError("AUTH_REQUIRED", `your AgentX sign-in for ${resolved2.env} has ended (${reason2}); ${signIn}`);
359170
+ }
359171
+ if (response.status === 503) throw agentXError("RUNTIME_UNAVAILABLE", serverReason(fields.error_description, "AgentX could not refresh your sign-in just now; try again in a moment"));
359172
+ if (!response.ok) throw agentXError("RUNTIME_UNAVAILABLE", `AgentX could not refresh your sign-in (HTTP ${response.status}); try again`);
359173
+ const parsed = DeveloperTokenResponseSchema.safeParse(body);
359174
+ if (!parsed.success) throw agentXError("RUNTIME_UNAVAILABLE", "AgentX answered the refresh with something unexpected; try again");
359175
+ await deps.tokenStore.set(key, { accessToken: parsed.data.access_token, refreshToken: parsed.data.refresh_token, expiresAt: now() + parsed.data.expires_in * 1e3 });
359176
+ return { ...resolved2, accessToken: parsed.data.access_token };
359177
+ });
359178
+ }
359179
+
359180
+ // packages/cli/src/session/app-request.ts
359181
+ var UNSAFE = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Cs}\p{Co}͏ᅟᅠ⠀ㅤᅠ]/gu;
359182
+ var marker = (character) => `[U+${(character.codePointAt(0) ?? 0).toString(16).toUpperCase().padStart(4, "0")}]`;
359183
+ var MAX_SHOWN = 500;
359184
+ function terminalSafe(value) {
359185
+ const characters = [...String(value).replace(/[\r\n\t]+/g, " ")];
359186
+ const shown2 = characters.length > MAX_SHOWN ? characters.slice(0, MAX_SHOWN) : characters;
359187
+ return shown2.join("").replace(UNSAFE, marker) + (characters.length > MAX_SHOWN ? "...[truncated]" : "");
359188
+ }
359189
+ function jsonSafe(value) {
359190
+ if (typeof value === "string") return value.replace(UNSAFE, (character) => character === "\n" || character === "\r" || character === " " ? character : marker(character));
359191
+ if (Array.isArray(value)) return value.map(jsonSafe);
359192
+ if (value !== null && typeof value === "object") {
359193
+ return Object.fromEntries(Object.entries(value).map(([key, child]) => [jsonSafe(key), jsonSafe(child)]));
359194
+ }
359195
+ return value;
359196
+ }
359197
+ var clean = (text11) => terminalSafe(text11.replace(/agx[rc]_[A-Za-z0-9_-]+/g, "[hidden]"));
359198
+ async function appRequest(deps, env3, path6, options = {}) {
359199
+ const session = await developerAccessToken(deps, env3);
359200
+ let response;
359201
+ try {
359202
+ response = await deps.fetch(`${session.entry.url}${path6}`, {
359203
+ method: options.method ?? "GET",
359204
+ headers: { ...options.headers, authorization: `Bearer ${session.accessToken}`, ...options.body === void 0 ? {} : { "content-type": "application/json" } },
359205
+ ...options.body === void 0 ? {} : { body: JSON.stringify(options.body) },
359206
+ signal: AbortSignal.timeout(3e4)
359207
+ });
359208
+ } catch {
359209
+ throw agentXError("RUNTIME_UNAVAILABLE", `could not reach AgentX at ${session.entry.url}; check your connection and try again`);
359210
+ }
359211
+ const value = await response.json().catch(() => void 0);
359212
+ if (response.status === 401) throw agentXError("AUTH_REQUIRED", `your AgentX sign-in for ${session.env} has ended; run npx ${CLI_PACKAGE_NAME} login ${session.entry.url}`);
359213
+ if (!response.ok) {
359214
+ const error64 = typeof value === "object" && value !== null ? value.error : void 0;
359215
+ const message = typeof error64?.message === "string" ? clean(error64.message).trim() : "";
359216
+ if (message === "") throw agentXError("RUNTIME_UNAVAILABLE", `AgentX answered HTTP ${response.status}; try again`);
359217
+ const code2 = AgentXErrorCodeSchema.safeParse(error64?.code);
359218
+ throw new ReportedFailure(code2.success ? code2.data : "REFUSED", message, response.status === 409 || !code2.success ? 1 : exitCodeForError(code2.data));
359219
+ }
359220
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
359221
+ throw agentXError("RUNTIME_UNAVAILABLE", `AgentX answered with something unexpected; try again, or upgrade: npx ${CLI_PACKAGE_NAME}@latest whoami`);
359222
+ }
359223
+ return { env: session.env, url: session.entry.url, status: response.status, body: value };
359224
+ }
359225
+ var result = (answer2, data, text11) => ({ env: answer2.env, url: answer2.url, data: jsonSafe(data), text: text11 });
359226
+ var seg = (id12) => {
359227
+ if (id12 === "." || id12 === "..") throw agentXError("CONFIG_INVALID", "an ID cannot be . or ..");
359228
+ return encodeURIComponent(id12);
359229
+ };
359230
+ var str = (value, fallback2 = "") => typeof value === "string" || typeof value === "number" ? clean(String(value)) : fallback2;
359231
+ var list2 = (value) => Array.isArray(value) ? value.filter((entry) => typeof entry === "object" && entry !== null) : [];
359232
+ var DEVELOPER_ID = /^[a-f0-9]{64}$/;
359233
+ async function developerRef(_deps, _env, who2) {
359234
+ const id12 = who2.trim().toLowerCase();
359235
+ if (!DEVELOPER_ID.test(id12)) throw agentXError("CONFIG_INVALID", "--with takes a person's developer ID (64 hexadecimal characters), project:<name>, or company; Code has no member directory to look an email up in");
359236
+ return { developerId: id12, name: `developer ${id12.slice(0, 8)}` };
359237
+ }
359238
+
359239
+ // packages/cli/src/company/people.ts
359240
+ var MEMBERS_PATH = "/v1/dev/company/members";
359241
+ var MAX_PAGES = 50;
359242
+ var ROLES = ["member", "admin", "owner"];
359243
+ var ROLE_WORDS = { owner: "owner", admin: "administrator", member: "member" };
359244
+ var METHOD_WORDS = { slack: "Slack", oidc: "company sign-in", github: "GitHub" };
359245
+ var pad = (value) => String(value).padStart(2, "0");
359246
+ function localTime(iso7) {
359247
+ const at = new Date(iso7);
359248
+ if (Number.isNaN(at.getTime())) return terminalSafe(iso7);
359249
+ return `${at.getFullYear()}-${pad(at.getMonth() + 1)}-${pad(at.getDate())} ${pad(at.getHours())}:${pad(at.getMinutes())}`;
359250
+ }
359251
+ var day = (iso7) => localTime(iso7).slice(0, 10);
359252
+ var asMember = (value) => {
359253
+ if (typeof value !== "object" || value === null) return void 0;
359254
+ const row2 = value;
359255
+ if (typeof row2.personId !== "string" || typeof row2.role !== "string" || typeof row2.joinedAt !== "string") return void 0;
359256
+ return {
359257
+ personId: row2.personId,
359258
+ role: row2.role,
359259
+ joinedAt: row2.joinedAt,
359260
+ ...typeof row2.name === "string" ? { name: row2.name } : {},
359261
+ ...typeof row2.email === "string" ? { email: row2.email } : {},
359262
+ ...typeof row2.signsInWith === "string" ? { signsInWith: row2.signsInWith } : {},
359263
+ ...typeof row2.revokedAt === "string" ? { revokedAt: row2.revokedAt } : {}
359264
+ };
359265
+ };
359266
+ async function allMembers(deps, env3) {
359267
+ const members2 = [];
359268
+ let cursor2;
359269
+ let answer2;
359270
+ for (let page = 0; page < MAX_PAGES; page += 1) {
359271
+ answer2 = await appRequest(deps, env3, `${MEMBERS_PATH}?limit=100${cursor2 === void 0 ? "" : `&cursor=${encodeURIComponent(cursor2)}`}`);
359272
+ const rows = Array.isArray(answer2.body.members) ? answer2.body.members : [];
359273
+ for (const row2 of rows) {
359274
+ const member2 = asMember(row2);
359275
+ if (member2 !== void 0) members2.push(member2);
359276
+ }
359277
+ cursor2 = answer2.body.more === true && typeof answer2.body.cursor === "string" ? answer2.body.cursor : void 0;
359278
+ if (cursor2 === void 0) break;
359279
+ }
359280
+ return { env: answer2.env, url: answer2.url, members: members2, more: cursor2 !== void 0 };
359281
+ }
359282
+ var who = (member2) => {
359283
+ const name3 = member2.name === void 0 ? void 0 : terminalSafe(member2.name);
359284
+ const email4 = member2.email === void 0 ? void 0 : terminalSafe(member2.email);
359285
+ return name3 !== void 0 && email4 !== void 0 ? `${name3} (${email4})` : name3 ?? email4 ?? `person ${member2.personId.slice(0, 12)}`;
359286
+ };
359287
+ function findMember(members2, typed) {
359288
+ const live = members2.filter((member2) => member2.revokedAt === void 0);
359289
+ const key = typed.trim();
359290
+ const lower = key.toLowerCase();
359291
+ const byId = live.filter((member2) => member2.personId === lower);
359292
+ const byEmail = live.filter((member2) => member2.email?.toLowerCase() === lower);
359293
+ const byName = live.filter((member2) => member2.name?.toLowerCase() === lower);
359294
+ const found = byId.length > 0 ? byId : byEmail.length > 0 ? byEmail : byName;
359295
+ if (found.length === 1) return found[0];
359296
+ if (found.length > 1) throw agentXError("CONFIG_INVALID", `${found.length} members are called ${terminalSafe(key)}; name them by email instead (rovara company members shows each one's)`);
359297
+ throw agentXError("NOT_FOUND", `no member of your company is ${terminalSafe(key)}; rovara company members lists who is in it`);
359298
+ }
359299
+ async function companyMember(deps, env3, typed) {
359300
+ const member2 = findMember((await allMembers(deps, env3)).members, typed);
359301
+ return { member: member2, who: who(member2) };
359302
+ }
359303
+ async function companyName(deps, env3) {
359304
+ const details = await appRequest(deps, env3, COMPANY_DETAILS_PATH);
359305
+ return { env: details.env, url: details.url, name: details.body.name === null || details.body.name === void 0 ? "your company" : str(details.body.name), companyId: str(details.body.companyId) };
359306
+ }
359307
+ function memberLine(member2) {
359308
+ const parts2 = [` ${who(member2)}`, ROLE_WORDS[member2.role] ?? terminalSafe(member2.role)];
359309
+ if (member2.signsInWith !== void 0) parts2.push(`signs in with ${METHOD_WORDS[member2.signsInWith] ?? terminalSafe(member2.signsInWith)}`);
359310
+ parts2.push(`joined ${day(member2.joinedAt)}`);
359311
+ if (member2.revokedAt !== void 0) parts2.push(`removed ${day(member2.revokedAt)}`);
359312
+ return parts2.join(", ");
359313
+ }
359314
+ async function companyMembers(deps, env3, options) {
359315
+ const listed3 = await allMembers(deps, env3);
359316
+ const shown2 = options.all ? listed3.members : listed3.members.filter((member2) => member2.revokedAt === void 0);
359317
+ const lines = shown2.length === 0 ? ["Your company has no members to show."] : [`${shown2.length} ${shown2.length === 1 ? "member" : "members"}:`, ...shown2.map(memberLine)];
359318
+ if (listed3.more) lines.push(`More members are not shown (the first ${MAX_PAGES * 100}).`);
359319
+ return result(listed3, { members: shown2, more: listed3.more }, `${lines.join("\n")}
359320
+ `);
359321
+ }
359322
+ var declined = (env3, url2) => result({ env: env3, url: url2 }, { applied: false }, "Nothing changed.\n");
359323
+ async function companyRole(deps, env3, typed, role, io) {
359324
+ if (!ROLES.includes(role)) throw agentXError("CONFIG_INVALID", "the role is member, admin or owner");
359325
+ const listed3 = await allMembers(deps, env3);
359326
+ const member2 = findMember(listed3.members, typed);
359327
+ if (member2.role === role) return result(listed3, { applied: false, personId: member2.personId, role }, `${who(member2)} is already ${ROLE_WORDS[role]}.
359328
+ `);
359329
+ const company = await companyName(deps, env3);
359330
+ io.tell(`This changes ${who(member2)}'s role in ${company.name} from ${ROLE_WORDS[member2.role] ?? terminalSafe(member2.role)} to ${ROLE_WORDS[role]}.`);
359331
+ if (!await io.confirm("Apply this change?")) return declined(listed3.env, listed3.url);
359332
+ const answer2 = await appRequest(deps, env3, `${MEMBERS_PATH}/${seg(member2.personId)}/role`, { method: "PUT", body: { role } });
359333
+ return result(answer2, { applied: true, personId: member2.personId, role }, `${who(member2)}'s role in ${company.name} is now ${ROLE_WORDS[role]}.
359334
+ `);
359335
+ }
359336
+ var count4 = (value, one, many) => {
359337
+ const n3 = typeof value === "number" ? value : 0;
359338
+ return `${n3} ${n3 === 1 ? one : many}`;
359339
+ };
359340
+ var names = (value) => Array.isArray(value) ? value.filter((item) => typeof item === "string").map(terminalSafe) : [];
359341
+ var objectOf = (value) => typeof value === "object" && value !== null ? value : {};
359342
+ function removalLines(member2, company, preview, to) {
359343
+ const handOver = objectOf(preview.handOver);
359344
+ const owned = names(preview.ownedProjects), granted = names(preview.projectGrants);
359345
+ const lines = [`This removes ${who(member2)} (${ROLE_WORDS[str(preview.role)] ?? terminalSafe(str(preview.role))}) from ${company}: their sign-ins end and their access to ${company}'s projects is taken away.`];
359346
+ if (granted.length > 0) lines.push(` Project access they lose: ${granted.join(", ")}.`);
359347
+ lines.push(` ${to} takes over ${count4(handOver.agents, "agent", "agents")}, ${count4(handOver.chains, "chain", "chains")}, ${count4(handOver.projects, "project", "projects")}${owned.length > 0 ? ` (${owned.join(", ")})` : ""} and ${count4(handOver.tasks, "open task", "open tasks")}.`);
359348
+ if (typeof handOver.tasksLeft === "number" && handOver.tasksLeft > 0) lines.push(` ${count4(handOver.tasksLeft, "open task", "open tasks")} cannot be handed over and will stay without an owner.`);
359349
+ if (typeof preview.awaitingTheirDecision === "number" && preview.awaitingTheirDecision > 0) lines.push(` ${count4(preview.awaitingTheirDecision, "task is", "tasks are")} waiting on their decision.`);
359350
+ return lines;
359351
+ }
359352
+ async function companyRemove(deps, env3, typed, options, io) {
359353
+ const listed3 = await allMembers(deps, env3);
359354
+ const member2 = findMember(listed3.members, typed);
359355
+ const successor = options.to === void 0 ? void 0 : findMember(listed3.members, options.to);
359356
+ const preview = (await appRequest(deps, env3, `${MEMBERS_PATH}/${seg(member2.personId)}/removal-preview${successor === void 0 ? "" : `?successorId=${seg(successor.personId)}`}`)).body;
359357
+ if (preview.mayRemove === false) throw agentXError("FORBIDDEN", member2.role === "owner" ? "only an owner can remove an owner" : "you cannot remove this member");
359358
+ const company = await companyName(deps, env3);
359359
+ const named4 = objectOf(preview.successor).name;
359360
+ const to = typeof named4 === "string" ? terminalSafe(named4) : successor !== void 0 ? who(successor) : "you";
359361
+ for (const line21 of removalLines(member2, company.name, preview, to)) io.tell(line21);
359362
+ if (!await io.confirm("Apply this change?")) return declined(listed3.env, listed3.url);
359363
+ const answer2 = await appRequest(deps, env3, `${MEMBERS_PATH}/${seg(member2.personId)}/removal`, {
359364
+ method: "POST",
359365
+ body: { requestId: randomUUID3(), expectedRole: str(preview.role), ...successor === void 0 ? {} : { successorId: successor.personId } }
359366
+ });
359367
+ const moved = objectOf(answer2.body.moved);
359368
+ return result(
359369
+ answer2,
359370
+ { applied: true, personId: member2.personId, ...answer2.body },
359371
+ `Removed ${who(member2)} from ${company.name}. ${to === "you" ? "You took" : `${to} took`} over ${count4(moved.agents, "agent", "agents")}, ${count4(moved.chains, "chain", "chains")}, ${count4(moved.projects, "project", "projects")} and ${count4(moved.tasks, "open task", "open tasks")}.
359372
+ `
359373
+ );
359374
+ }
359375
+
359376
+ // packages/cli/src/admin/project-access.ts
359377
+ var DEVELOPER_ID2 = /^[a-f0-9]{64}$/;
359378
+ async function personNamed(deps, env3, typed) {
359379
+ const value = typed.trim();
359380
+ if (DEVELOPER_ID2.test(value.toLowerCase())) return { ref: value.toLowerCase(), who: `developer ${value.slice(0, 12).toLowerCase()}` };
359381
+ if (SlackUserIdSchema.safeParse(value).success) return { ref: value, who: `Slack user ${value}` };
359382
+ const { member: member2, who: who2 } = await companyMember(deps, env3, value);
359383
+ return { ref: member2.personId, who: who2 };
359384
+ }
359385
+ var OUTCOME_TEXT = {
359386
+ granted: (who2, project3) => `${who2} can now hand tasks to ${project3}.`,
359387
+ already_member: (who2, project3) => `${who2} already had access to ${project3}; nothing changed.`,
359388
+ revoked: (who2, project3) => `${who2} no longer has access to ${project3}.`,
359389
+ not_member: (who2, project3) => `${who2} had no access to ${project3} to take away; nothing changed.`
359390
+ };
359391
+ async function projectAccessChange(deps, env3, input2, io) {
359392
+ const session = await developerAccessToken(deps, env3);
359393
+ const signedIn = { env: session.env, url: session.entry.url };
359394
+ const person4 = await personNamed(deps, env3, input2.developer);
359395
+ io.tell(input2.action === "grant" ? `This gives ${person4.who} access to project ${input2.project}: they can hand it tasks from an AI tool.` : `This takes ${person4.who}'s access to project ${input2.project} away.`);
359396
+ if (!await io.confirm("Apply this change?")) return result(signedIn, { applied: false }, "Nothing changed.\n");
359397
+ const answer2 = await appRequest(deps, env3, `/v1/dev/client/projects/${seg(input2.project)}/members/${seg(person4.ref)}`, { method: input2.action === "grant" ? "PUT" : "DELETE" });
359398
+ const outcome = str(answer2.body.outcome);
359399
+ const text11 = OUTCOME_TEXT[outcome]?.(person4.who, input2.project) ?? `The project's members changed (${outcome}).`;
359400
+ return result(answer2, { applied: true, project: input2.project, developerId: str(answer2.body.developerId), outcome }, `${text11}
359401
+ `);
358969
359402
  }
358970
359403
 
358971
359404
  // packages/cli/src/admin/task-share-mode.ts
358972
- import { randomUUID as randomUUID2 } from "node:crypto";
359405
+ import { randomUUID as randomUUID4 } from "node:crypto";
358973
359406
  async function setTaskShareMode(input2, fetchImplementation = fetch) {
358974
359407
  const response = await fetchImplementation(
358975
359408
  `${input2.controlPlaneUrl.replace(/\/$/, "")}/v1/admin/tasks/${encodeURIComponent(input2.taskId)}/share-mode`,
358976
359409
  {
358977
359410
  method: "POST",
358978
359411
  headers: { authorization: `Bearer ${input2.accessToken}`, "content-type": "application/json" },
358979
- body: JSON.stringify({ requestId: input2.requestId ?? randomUUID2(), shareMode: input2.mode })
359412
+ body: JSON.stringify({ requestId: input2.requestId ?? randomUUID4(), shareMode: input2.mode })
358980
359413
  }
358981
359414
  );
358982
359415
  return adminResponseBody(response);
@@ -359000,10 +359433,10 @@ async function cancelWorkspaceTask(input2, fetchImplementation = fetch) {
359000
359433
 
359001
359434
  // packages/cli/src/admin/changes.ts
359002
359435
  init_dist2();
359003
- import { randomUUID as randomUUID3 } from "node:crypto";
359436
+ import { randomUUID as randomUUID5 } from "node:crypto";
359004
359437
  import { createInterface as createInterface2 } from "node:readline";
359005
359438
  var PAGE_LIMIT = "100";
359006
- var MAX_PAGES = 1e4;
359439
+ var MAX_PAGES2 = 1e4;
359007
359440
  var CHECK_STEP = "run agentx admin changes --since 1h to see how it ended";
359008
359441
  function plain2(text11) {
359009
359442
  let out = "";
@@ -359043,9 +359476,9 @@ function viewOf(value, unreadable) {
359043
359476
  return parsed.data.change;
359044
359477
  }
359045
359478
  async function runCliChange(input2, fetchImplementation = fetch) {
359046
- const traceId = randomUUID3();
359479
+ const traceId = randomUUID5();
359047
359480
  const planned = viewOf(
359048
- await send(input2, traceId, "POST", "/v1/admin/changes", { requestId: (input2.newId ?? randomUUID3)(), change: input2.change, client: { cliVersion: input2.cliVersion }, methods: ["cli"] }, fetchImplementation, "plan"),
359481
+ await send(input2, traceId, "POST", "/v1/admin/changes", { requestId: (input2.newId ?? randomUUID5)(), change: input2.change, client: { cliVersion: input2.cliVersion }, methods: ["cli"] }, fetchImplementation, "plan"),
359049
359482
  "AgentX answered with a change this version of the CLI cannot read; nothing was applied. Upgrade the CLI, then ask again"
359050
359483
  );
359051
359484
  const changeId = planned.changeId;
@@ -359093,7 +359526,7 @@ async function runCliChange(input2, fetchImplementation = fetch) {
359093
359526
  throw agentXError("RUNTIME_UNAVAILABLE", `AgentX answered change ${changeId} as ${plain2(applied.status)}, which this CLI does not read as applied; ${CHECK_STEP}`);
359094
359527
  }
359095
359528
  async function recordConfigChange(input2, fetchImplementation = fetch) {
359096
- const traceId = randomUUID3();
359529
+ const traceId = randomUUID5();
359097
359530
  const request = { requestId: input2.requestId, change: input2.change, client: { cliVersion: input2.cliVersion }, ...input2.requestedAt === void 0 ? {} : { requestedAt: input2.requestedAt }, answeredAt: input2.answeredAt };
359098
359531
  const body = await send(input2, traceId, "POST", "/v1/admin/changes/config", request, fetchImplementation, "record");
359099
359532
  const parsed = RecordedChangeResponseWireSchema.safeParse(body);
@@ -359143,14 +359576,14 @@ function kindText(record4) {
359143
359576
  return record4.kind === "set_config" && typeof key === "string" ? `set_config ${key}` : record4.kind;
359144
359577
  }
359145
359578
  async function exportChanges(input2, fetchImplementation = fetch) {
359146
- const traceId = randomUUID3();
359579
+ const traceId = randomUUID5();
359147
359580
  const seen = /* @__PURE__ */ new Set();
359148
359581
  let cursor2;
359149
359582
  let exported = 0;
359150
359583
  let pages = 0;
359151
359584
  do {
359152
359585
  pages += 1;
359153
- if (pages > MAX_PAGES) throw agentXError("RUNTIME_UNAVAILABLE", "change record export did not finish after 10000 pages; try a narrower --since");
359586
+ if (pages > MAX_PAGES2) throw agentXError("RUNTIME_UNAVAILABLE", "change record export did not finish after 10000 pages; try a narrower --since");
359154
359587
  const query = new URLSearchParams({ since: input2.since, limit: PAGE_LIMIT, ...cursor2 === void 0 ? {} : { cursor: cursor2 } });
359155
359588
  const body = await send(input2, traceId, "GET", `/v1/admin/changes?${query.toString()}`, void 0, fetchImplementation, "list");
359156
359589
  const page = AdminChangesResponseWireSchema.safeParse(body);
@@ -359262,7 +359695,7 @@ init_dist2();
359262
359695
  var DURATION = /^(\d{1,4})([mhd])$/;
359263
359696
  var UNIT_MS = { m: 6e4, h: 36e5, d: 864e5 };
359264
359697
  var RETENTION_MS = 30 * UNIT_MS.d;
359265
- var MAX_PAGES2 = 1e4;
359698
+ var MAX_PAGES3 = 1e4;
359266
359699
  function parseSince(value, now = Date.now(), noun = "turn records") {
359267
359700
  const match = DURATION.exec(value.trim());
359268
359701
  if (!match) throw agentXError("CONFIG_INVALID", "--since must be a duration such as 30m, 12h or 7d");
@@ -359280,7 +359713,7 @@ async function exportTurns(input2, fetchImplementation = fetch) {
359280
359713
  let pages = 0;
359281
359714
  do {
359282
359715
  pages += 1;
359283
- if (pages > MAX_PAGES2) throw agentXError("RUNTIME_UNAVAILABLE", "turn record export did not finish after 10000 pages; try a narrower --since");
359716
+ if (pages > MAX_PAGES3) throw agentXError("RUNTIME_UNAVAILABLE", "turn record export did not finish after 10000 pages; try a narrower --since");
359284
359717
  const url2 = new URL(`${input2.controlPlaneUrl.replace(/\/$/, "")}/v1/admin/turns`);
359285
359718
  url2.searchParams.set("since", input2.since);
359286
359719
  if (cursor2 !== void 0) url2.searchParams.set("cursor", cursor2);
@@ -359308,8 +359741,8 @@ async function exportTurns(input2, fetchImplementation = fetch) {
359308
359741
 
359309
359742
  // packages/cli/src/config.ts
359310
359743
  init_dist2();
359311
- var import_yaml = __toESM(require_dist4(), 1);
359312
- import { readFile as readFile5, realpath as realpath2, stat as stat2 } from "node:fs/promises";
359744
+ var import_yaml2 = __toESM(require_dist4(), 1);
359745
+ import { readFile as readFile7, realpath as realpath2, stat as stat3 } from "node:fs/promises";
359313
359746
  import { isAbsolute as isAbsolute2, relative, resolve as resolve3, sep as sep2 } from "node:path";
359314
359747
  var MAX_CONFIG_BYTES = 1048576;
359315
359748
  async function loadProjectConfig(options) {
@@ -359322,11 +359755,11 @@ async function loadProjectConfig(options) {
359322
359755
  );
359323
359756
  });
359324
359757
  assertContained(configDirectory, canonicalPath);
359325
- const metadata = await stat2(canonicalPath);
359758
+ const metadata = await stat3(canonicalPath);
359326
359759
  if (!metadata.isFile() || metadata.size > MAX_CONFIG_BYTES) {
359327
359760
  throw agentXError("CONFIG_INVALID", "project configuration must be a regular file no larger than 1 MiB");
359328
359761
  }
359329
- const document = import_yaml.default.parseDocument(await readFile5(canonicalPath, "utf8"), { uniqueKeys: true });
359762
+ const document = import_yaml2.default.parseDocument(await readFile7(canonicalPath, "utf8"), { uniqueKeys: true });
359330
359763
  if (document.errors.length > 0) {
359331
359764
  throw agentXError("CONFIG_INVALID", document.errors[0]?.message ?? "project YAML is invalid");
359332
359765
  }
@@ -359380,172 +359813,6 @@ function isNodeError(error64) {
359380
359813
 
359381
359814
  // packages/cli/src/developer/commands.ts
359382
359815
  init_dist2();
359383
-
359384
- // packages/cli/src/developer/config.ts
359385
- init_dist2();
359386
- init_dist2();
359387
- var import_yaml2 = __toESM(require_dist4(), 1);
359388
- init_zod();
359389
- import { chmod, mkdir as mkdir2, open as open2, readFile as readFile6, rename, rm } from "node:fs/promises";
359390
- import { join as join6 } from "node:path";
359391
- var EntrySchema = external_exports.object({ url: external_exports.string().url(), issuer: external_exports.string().url(), tokenEndpoint: external_exports.string().url(), revocationEndpoint: external_exports.string().url() }).strict();
359392
- var ConfigSchema = external_exports.object({ schemaVersion: external_exports.literal(1), default: EnvironmentNameSchema.optional(), environments: external_exports.record(EnvironmentNameSchema, EntrySchema) }).strict();
359393
- var developerConfigPath = (home) => join6(home, ".agentx", "developer.yaml");
359394
- var developerTokenKey = (issuer) => tokenStoreKey({ issuer, clientId: AGENTX_CLI_CLIENT_ID, audience: DEVELOPER_TOKEN_AUDIENCE });
359395
- async function readDeveloperConfig(home) {
359396
- let text11;
359397
- try {
359398
- text11 = await readFile6(developerConfigPath(home), "utf8");
359399
- } catch (error64) {
359400
- if (error64.code === "ENOENT") return { environments: {} };
359401
- throw error64;
359402
- }
359403
- let document;
359404
- try {
359405
- document = import_yaml2.default.parse(text11);
359406
- } catch {
359407
- document = void 0;
359408
- }
359409
- const parsed = ConfigSchema.safeParse(document);
359410
- if (!parsed.success) throw agentXError("CONFIG_INVALID", `${developerConfigPath(home)} is invalid; delete it and run agentx login <url> again`);
359411
- return { environments: parsed.data.environments };
359412
- }
359413
- async function write(home, config5) {
359414
- const path6 = developerConfigPath(home);
359415
- await mkdir2(join6(home, ".agentx"), { recursive: true, mode: 448 });
359416
- await chmod(join6(home, ".agentx"), 448);
359417
- const temp = `${path6}.${process.pid}.tmp`;
359418
- const handle = await open2(temp, "w", 384);
359419
- try {
359420
- await handle.writeFile(import_yaml2.default.stringify({ schemaVersion: 1, ...config5 }));
359421
- } finally {
359422
- await handle.close();
359423
- }
359424
- try {
359425
- await rename(temp, path6);
359426
- } catch (error64) {
359427
- await rm(temp, { force: true });
359428
- throw error64;
359429
- }
359430
- }
359431
- async function saveDeveloperEnvironment(home, env3, entry) {
359432
- const config5 = await readDeveloperConfig(home);
359433
- await write(home, { environments: { ...config5.environments, [env3]: EntrySchema.parse(entry) } });
359434
- }
359435
- async function removeDeveloperEnvironment(home, env3) {
359436
- const config5 = await readDeveloperConfig(home);
359437
- const { [env3]: _removed, ...rest } = config5.environments;
359438
- await write(home, { environments: rest });
359439
- }
359440
- async function forgetDeveloperSignIn(home, env3, tokenStore) {
359441
- const entry = (await readDeveloperConfig(home)).environments[env3];
359442
- if (entry === void 0) return false;
359443
- await tokenStore.delete(developerTokenKey(entry.issuer));
359444
- await removeDeveloperEnvironment(home, env3);
359445
- return true;
359446
- }
359447
- async function resolveDeveloperEnvironment(home, env3) {
359448
- const config5 = await readDeveloperConfig(home);
359449
- const name3 = env3 ?? DEFAULT_ENVIRONMENT;
359450
- const entry = config5.environments[name3];
359451
- if (entry === void 0) {
359452
- const others = Object.keys(config5.environments).sort();
359453
- const signIn = `run npx ${CLI_PACKAGE_NAME} login <your AgentX URL>`;
359454
- const next = others.length === 0 ? signIn : `it is signed in to ${others.join(", ")}: add --env ${others.length === 1 ? others[0] : "<name>"}, or ${signIn}`;
359455
- throw agentXError("AUTH_REQUIRED", `this computer is not signed in to AgentX environment ${name3}; ${next}`);
359456
- }
359457
- return { env: name3, entry };
359458
- }
359459
-
359460
- // packages/cli/src/developer/session.ts
359461
- init_dist2();
359462
- init_dist2();
359463
- import { chmod as chmod2, mkdir as mkdir3, open as open3, readFile as readFile7, rm as rm2, stat as stat3 } from "node:fs/promises";
359464
- import { randomUUID as randomUUID4 } from "node:crypto";
359465
- import { join as join7 } from "node:path";
359466
- var EARLY_MS = 6e4;
359467
- var STALE_LOCK_MS = 3e4;
359468
- var LOCK_POLL_MS = 50;
359469
- function serverReason(value, fallback2) {
359470
- return typeof value === "string" ? sanitizeServerText(value) : fallback2;
359471
- }
359472
- async function withRefreshLock(deps, env3, work) {
359473
- const dir = join7(deps.home, ".agentx", "locks");
359474
- await mkdir3(dir, { recursive: true, mode: 448 });
359475
- await chmod2(dir, 448);
359476
- const path6 = join7(dir, `developer-${env3}.lock`);
359477
- const owner = `${process.pid}:${randomUUID4()}`;
359478
- const sleep4 = deps.sleep ?? ((ms) => new Promise((resolve17) => setTimeout(resolve17, ms)));
359479
- const deadline = Date.now() + (deps.lockWaitMs ?? 15e3);
359480
- for (; ; ) {
359481
- try {
359482
- const handle = await open3(path6, "wx", 384);
359483
- try {
359484
- await handle.writeFile(owner);
359485
- } finally {
359486
- await handle.close();
359487
- }
359488
- break;
359489
- } catch (error64) {
359490
- if (error64.code !== "EEXIST") throw error64;
359491
- const age = await stat3(path6).then((info) => Date.now() - info.mtimeMs, () => 0);
359492
- if (age > STALE_LOCK_MS) {
359493
- await rm2(path6, { force: true });
359494
- continue;
359495
- }
359496
- if (Date.now() > deadline) throw agentXError("RUNTIME_UNAVAILABLE", `another agentx process is refreshing your sign-in to ${env3}; try again in a moment`);
359497
- await sleep4(LOCK_POLL_MS);
359498
- }
359499
- }
359500
- try {
359501
- return await work();
359502
- } finally {
359503
- const holder = await readFile7(path6, "utf8").catch(() => void 0);
359504
- if (holder === owner) await rm2(path6, { force: true });
359505
- }
359506
- }
359507
- async function developerAccessToken(deps, env3, options = {}) {
359508
- const now = deps.now ?? Date.now;
359509
- const resolved2 = await resolveDeveloperEnvironment(deps.home, env3);
359510
- const key = developerTokenKey(resolved2.entry.issuer);
359511
- const signIn = `run npx ${CLI_PACKAGE_NAME} login ${resolved2.entry.url}`;
359512
- const fresh = (tokens) => tokens.expiresAt - EARLY_MS > now();
359513
- const stored = await deps.tokenStore.get(key);
359514
- if (stored === void 0) throw agentXError("AUTH_REQUIRED", `this computer is not signed in to AgentX environment ${resolved2.env}; ${signIn}`);
359515
- if (options.force !== true && fresh(stored)) return { ...resolved2, accessToken: stored.accessToken };
359516
- return withRefreshLock(deps, resolved2.env, async () => {
359517
- const current = await deps.tokenStore.get(key);
359518
- const replaced = options.force !== true || current?.accessToken !== stored.accessToken;
359519
- if (current !== void 0 && fresh(current) && replaced) return { ...resolved2, accessToken: current.accessToken };
359520
- if (current?.refreshToken === void 0) throw agentXError("AUTH_REQUIRED", `your AgentX sign-in for ${resolved2.env} has ended; ${signIn}`);
359521
- let response;
359522
- try {
359523
- response = await deps.fetch(resolved2.entry.tokenEndpoint, {
359524
- method: "POST",
359525
- headers: { "content-type": "application/x-www-form-urlencoded" },
359526
- body: new URLSearchParams({ grant_type: "refresh_token", client_id: AGENTX_CLI_CLIENT_ID, refresh_token: current.refreshToken }).toString(),
359527
- signal: AbortSignal.timeout(15e3)
359528
- });
359529
- } catch {
359530
- throw agentXError("RUNTIME_UNAVAILABLE", `could not reach AgentX at ${resolved2.entry.url}; check your connection and try again`);
359531
- }
359532
- const body = await response.json().catch(() => ({}));
359533
- const fields = typeof body === "object" && body !== null ? body : {};
359534
- const reason2 = serverReason(fields.error_description, "no reason given");
359535
- if (response.status === 400 && fields.error === "invalid_grant") {
359536
- await deps.tokenStore.delete(key);
359537
- throw agentXError("AUTH_REQUIRED", `your AgentX sign-in for ${resolved2.env} has ended (${reason2}); ${signIn}`);
359538
- }
359539
- if (response.status === 503) throw agentXError("RUNTIME_UNAVAILABLE", serverReason(fields.error_description, "AgentX could not refresh your sign-in just now; try again in a moment"));
359540
- if (!response.ok) throw agentXError("RUNTIME_UNAVAILABLE", `AgentX could not refresh your sign-in (HTTP ${response.status}); try again`);
359541
- const parsed = DeveloperTokenResponseSchema.safeParse(body);
359542
- if (!parsed.success) throw agentXError("RUNTIME_UNAVAILABLE", "AgentX answered the refresh with something unexpected; try again");
359543
- await deps.tokenStore.set(key, { accessToken: parsed.data.access_token, refreshToken: parsed.data.refresh_token, expiresAt: now() + parsed.data.expires_in * 1e3 });
359544
- return { ...resolved2, accessToken: parsed.data.access_token };
359545
- });
359546
- }
359547
-
359548
- // packages/cli/src/developer/commands.ts
359549
359816
  async function developerGet(deps, env3, path6, schema) {
359550
359817
  return developerRequest(deps, env3, path6, schema);
359551
359818
  }
@@ -359909,147 +360176,8 @@ async function developerLogin(options) {
359909
360176
  // packages/cli/src/developer/sign-ins.ts
359910
360177
  init_dist2();
359911
360178
  import { createServer as createServer4 } from "node:http";
359912
-
359913
- // packages/cli/src/session/app-request.ts
359914
- init_dist2();
359915
-
359916
- // packages/cli/src/output.ts
359917
- init_dist2();
359918
-
359919
- // packages/cli/src/stopped.ts
359920
- init_dist2();
359921
- var StoppedByOperator = class extends Error {
359922
- exitCode = 130;
359923
- constructor(message) {
359924
- super(message);
359925
- this.name = "StoppedByOperator";
359926
- }
359927
- };
359928
- function isCtrlCAtPrompt(error64) {
359929
- for (let current = error64, depth = 0; current instanceof Error && depth < 10; current = current.cause, depth += 1) {
359930
- if (current.name === "AbortError" && /Ctrl\+C/.test(current.message)) return true;
359931
- if (current instanceof AgentXError && current.code === "CONFIG_INVALID" && current.message.replace(/^CONFIG_INVALID: /, "") === "cancelled") return true;
359932
- }
359933
- return false;
359934
- }
359935
-
359936
- // packages/cli/src/output.ts
359937
- function formatSuccess(data, json3) {
359938
- if (json3) return `${JSON.stringify({ ok: true, data })}
359939
- `;
359940
- return typeof data === "string" ? `${data}
359941
- ` : `${JSON.stringify(data, null, 2)}
359942
- `;
359943
- }
359944
- var ReportedFailure = class extends Error {
359945
- constructor(failureCode, message, exitCode = 1) {
359946
- super(message);
359947
- this.failureCode = failureCode;
359948
- this.exitCode = exitCode;
359949
- this.name = "ReportedFailure";
359950
- }
359951
- failureCode;
359952
- exitCode;
359953
- };
359954
- function formatError2(error64, json3) {
359955
- if (error64 instanceof StoppedByOperator) {
359956
- return { text: json3 ? `${JSON.stringify({ ok: false, error: { code: "STOPPED", message: error64.message } })}
359957
- ` : `${error64.message}
359958
- `, exitCode: error64.exitCode };
359959
- }
359960
- if (error64 instanceof ReportedFailure) {
359961
- return { text: json3 ? `${JSON.stringify({ ok: false, error: { code: error64.failureCode, message: error64.message } })}
359962
- ` : `${error64.message}
359963
- `, exitCode: error64.exitCode };
359964
- }
359965
- const normalized = error64 instanceof AgentXError ? { code: error64.code, message: stripCodePrefix(error64.message, error64.code) } : { code: "INTERNAL_ERROR", message: error64 instanceof Error ? error64.message : "unexpected error" };
359966
- const text11 = json3 ? `${JSON.stringify({ ok: false, error: normalized })}
359967
- ` : `AgentX error [${normalized.code}]: ${normalized.message}
359968
- `;
359969
- return {
359970
- text: text11,
359971
- exitCode: normalized.code === "INTERNAL_ERROR" ? 1 : exitCodeForError(normalized.code)
359972
- };
359973
- }
359974
- function exitCodeForError(code2) {
359975
- if (code2 === "CONFIG_INVALID" || code2 === "PROJECT_REVISION_MISMATCH") return 2;
359976
- if (code2 === "AUTH_REQUIRED") return 3;
359977
- if (code2 === "FORBIDDEN" || code2 === "NOT_FOUND" || code2 === "CALLBACK_FORBIDDEN") return 4;
359978
- if (code2 === "WORKSPACE_NOT_READY" || code2 === "WORKSPACE_BUSY") return 5;
359979
- if (code2 === "RUNTIME_UNAVAILABLE" || code2 === "OPERATION_INTERRUPTED" || code2 === "STALE_FENCE") return 6;
359980
- return 7;
359981
- }
359982
- function plainMessage(error64) {
359983
- if (error64 instanceof AgentXError) return stripCodePrefix(error64.message, error64.code);
359984
- return error64 instanceof Error ? error64.message : String(error64);
359985
- }
359986
- function stripCodePrefix(message, code2) {
359987
- const prefix2 = `${code2}: `;
359988
- return message.startsWith(prefix2) ? message.slice(prefix2.length) : message;
359989
- }
359990
-
359991
- // packages/cli/src/session/app-request.ts
359992
- var UNSAFE = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Cs}\p{Co}͏ᅟᅠ⠀ㅤᅠ]/gu;
359993
- var marker = (character) => `[U+${(character.codePointAt(0) ?? 0).toString(16).toUpperCase().padStart(4, "0")}]`;
359994
- var MAX_SHOWN = 500;
359995
- function terminalSafe(value) {
359996
- const characters = [...String(value).replace(/[\r\n\t]+/g, " ")];
359997
- const shown2 = characters.length > MAX_SHOWN ? characters.slice(0, MAX_SHOWN) : characters;
359998
- return shown2.join("").replace(UNSAFE, marker) + (characters.length > MAX_SHOWN ? "...[truncated]" : "");
359999
- }
360000
- function jsonSafe(value) {
360001
- if (typeof value === "string") return value.replace(UNSAFE, (character) => character === "\n" || character === "\r" || character === " " ? character : marker(character));
360002
- if (Array.isArray(value)) return value.map(jsonSafe);
360003
- if (value !== null && typeof value === "object") {
360004
- return Object.fromEntries(Object.entries(value).map(([key, child]) => [jsonSafe(key), jsonSafe(child)]));
360005
- }
360006
- return value;
360007
- }
360008
- var clean = (text11) => terminalSafe(text11.replace(/agx[rc]_[A-Za-z0-9_-]+/g, "[hidden]"));
360009
- async function appRequest(deps, env3, path6, options = {}) {
360010
- const session = await developerAccessToken(deps, env3);
360011
- let response;
360012
- try {
360013
- response = await deps.fetch(`${session.entry.url}${path6}`, {
360014
- method: options.method ?? "GET",
360015
- headers: { ...options.headers, authorization: `Bearer ${session.accessToken}`, ...options.body === void 0 ? {} : { "content-type": "application/json" } },
360016
- ...options.body === void 0 ? {} : { body: JSON.stringify(options.body) },
360017
- signal: AbortSignal.timeout(3e4)
360018
- });
360019
- } catch {
360020
- throw agentXError("RUNTIME_UNAVAILABLE", `could not reach AgentX at ${session.entry.url}; check your connection and try again`);
360021
- }
360022
- const value = await response.json().catch(() => void 0);
360023
- if (response.status === 401) throw agentXError("AUTH_REQUIRED", `your AgentX sign-in for ${session.env} has ended; run npx ${CLI_PACKAGE_NAME} login ${session.entry.url}`);
360024
- if (!response.ok) {
360025
- const error64 = typeof value === "object" && value !== null ? value.error : void 0;
360026
- const message = typeof error64?.message === "string" ? clean(error64.message).trim() : "";
360027
- if (message === "") throw agentXError("RUNTIME_UNAVAILABLE", `AgentX answered HTTP ${response.status}; try again`);
360028
- const code2 = AgentXErrorCodeSchema.safeParse(error64?.code);
360029
- throw new ReportedFailure(code2.success ? code2.data : "REFUSED", message, response.status === 409 || !code2.success ? 1 : exitCodeForError(code2.data));
360030
- }
360031
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
360032
- throw agentXError("RUNTIME_UNAVAILABLE", `AgentX answered with something unexpected; try again, or upgrade: npx ${CLI_PACKAGE_NAME}@latest whoami`);
360033
- }
360034
- return { env: session.env, url: session.entry.url, status: response.status, body: value };
360035
- }
360036
- var result = (answer2, data, text11) => ({ env: answer2.env, url: answer2.url, data: jsonSafe(data), text: text11 });
360037
- var seg = (id12) => {
360038
- if (id12 === "." || id12 === "..") throw agentXError("CONFIG_INVALID", "an ID cannot be . or ..");
360039
- return encodeURIComponent(id12);
360040
- };
360041
- var str = (value, fallback2 = "") => typeof value === "string" || typeof value === "number" ? clean(String(value)) : fallback2;
360042
- var list2 = (value) => Array.isArray(value) ? value.filter((entry) => typeof entry === "object" && entry !== null) : [];
360043
- var DEVELOPER_ID = /^[a-f0-9]{64}$/;
360044
- async function developerRef(_deps, _env, who2) {
360045
- const id12 = who2.trim().toLowerCase();
360046
- if (!DEVELOPER_ID.test(id12)) throw agentXError("CONFIG_INVALID", "--with takes a person's developer ID (64 hexadecimal characters), project:<name>, or company; Code has no member directory to look an email up in");
360047
- return { developerId: id12, name: `developer ${id12.slice(0, 8)}` };
360048
- }
360049
-
360050
- // packages/cli/src/developer/sign-ins.ts
360051
360179
  var SIGN_INS_PATH = "/v1/dev/me/sign-ins";
360052
- var METHOD_WORDS = { slack: "Slack", oidc: "your company sign-in", github: "GitHub" };
360180
+ var METHOD_WORDS2 = { slack: "Slack", oidc: "your company sign-in", github: "GitHub" };
360053
360181
  var LINKABLE = ["slack", "github"];
360054
360182
  var ENDED = {
360055
360183
  cancelled: "the sign-in was cancelled on the provider's page; nothing was connected",
@@ -360059,12 +360187,12 @@ var ENDED = {
360059
360187
  async function signInsList(deps, env3) {
360060
360188
  const answer2 = await appRequest(deps, env3, SIGN_INS_PATH);
360061
360189
  const rows = (Array.isArray(answer2.body.signIns) ? answer2.body.signIns : []).filter((row2) => typeof row2 === "object" && row2 !== null);
360062
- const lines = rows.map((row2) => ` ${METHOD_WORDS[str(row2.method)] ?? str(row2.method)}${row2.primary === true ? " (the first way you signed in; it can't be removed)" : typeof row2.linkedAt === "string" ? ` (connected ${row2.linkedAt.slice(0, 10)})` : ""}`);
360190
+ const lines = rows.map((row2) => ` ${METHOD_WORDS2[str(row2.method)] ?? str(row2.method)}${row2.primary === true ? " (the first way you signed in; it can't be removed)" : typeof row2.linkedAt === "string" ? ` (connected ${row2.linkedAt.slice(0, 10)})` : ""}`);
360063
360191
  const missing = LINKABLE.filter((method) => !rows.some((row2) => row2.method === method));
360064
360192
  return result(answer2, { signIns: rows }, [
360065
360193
  `You sign in to AgentX environment ${answer2.env} with:`,
360066
360194
  ...lines,
360067
- ...missing.length === 0 ? [] : [`To connect ${missing.map((method) => METHOD_WORDS[method]).join(" or ")} too: rovara signins link ${missing.join("|")}`]
360195
+ ...missing.length === 0 ? [] : [`To connect ${missing.map((method) => METHOD_WORDS2[method]).join(" or ")} too: rovara signins link ${missing.join("|")}`]
360068
360196
  ].join("\n") + "\n");
360069
360197
  }
360070
360198
  async function linkCallback(state3, timeoutMs) {
@@ -360112,15 +360240,15 @@ async function signInsLink(deps, env3, method, options) {
360112
360240
  const linkId = typeof started.body.linkId === "string" ? started.body.linkId : "";
360113
360241
  if (!/^https:\/\/[^\s]+$/u.test(authorizeUrl) || !/^lnk_[A-Za-z0-9_-]{43}$/u.test(linkId)) throw agentXError("RUNTIME_UNAVAILABLE", "AgentX answered with something unexpected; try again");
360114
360242
  if (options.browser) {
360115
- options.write(`Opening your browser to sign in with ${METHOD_WORDS[method]}. If it does not open, open this link: ${authorizeUrl}`);
360243
+ options.write(`Opening your browser to sign in with ${METHOD_WORDS2[method]}. If it does not open, open this link: ${authorizeUrl}`);
360116
360244
  await (options.openBrowser ?? openSystemBrowser)(authorizeUrl).catch(() => void 0);
360117
360245
  } else {
360118
- options.write(`Open this link in a browser on this computer and sign in with ${METHOD_WORDS[method]}: ${authorizeUrl}`);
360246
+ options.write(`Open this link in a browser on this computer and sign in with ${METHOD_WORDS2[method]}: ${authorizeUrl}`);
360119
360247
  }
360120
360248
  const back = await callback.answer;
360121
360249
  if (back.linkId !== linkId) throw agentXError("AUTH_REQUIRED", ENDED.failed);
360122
360250
  const finished = await appRequest(deps, env3, `${SIGN_INS_PATH}/link/finish`, { method: "POST", body: { linkId, linkCode: back.linkCode, verifier: pkce.verifier } });
360123
- return result(finished, { method }, `Connected ${METHOD_WORDS[method]} to your account. You can now sign in to AgentX environment ${finished.env} with it too.
360251
+ return result(finished, { method }, `Connected ${METHOD_WORDS2[method]} to your account. You can now sign in to AgentX environment ${finished.env} with it too.
360124
360252
  `);
360125
360253
  } finally {
360126
360254
  callback.close();
@@ -361177,7 +361305,7 @@ init_dist2();
361177
361305
 
361178
361306
  // packages/cli/src/session/commands.ts
361179
361307
  init_dist2();
361180
- import { randomUUID as randomUUID5 } from "node:crypto";
361308
+ import { randomUUID as randomUUID6 } from "node:crypto";
361181
361309
  var TEXT_MAX = 1e4;
361182
361310
  var SAFE_URL = /^https?:\/\/[A-Za-z0-9._~:/?#@!$&'()*+,;=%[\]-]+$/;
361183
361311
  var PAGE_TOKEN_PATH = /^\/s\/[A-Za-z0-9_-]{43}(?:\/|$)/;
@@ -361265,7 +361393,7 @@ ${linkOf(answer2.url, id12)}
361265
361393
  async function sessionSay(deps, env3, id12, kind, text11) {
361266
361394
  if (text11.trim() === "") throw agentXError("CONFIG_INVALID", `give the ${kind === "comment" ? "comment" : "message"} as text`);
361267
361395
  if ([...text11].length > TEXT_MAX) throw agentXError("CONFIG_INVALID", `the text is longer than ${TEXT_MAX.toLocaleString("en-US")} characters`);
361268
- const answer2 = await appRequest(deps, env3, sessionPath(id12, "/messages"), { method: "POST", body: { requestId: randomUUID5(), kind, text: text11 } });
361396
+ const answer2 = await appRequest(deps, env3, sessionPath(id12, "/messages"), { method: "POST", body: { requestId: randomUUID6(), kind, text: text11 } });
361269
361397
  const delivery = answer2.body.delivery ?? {};
361270
361398
  const fate = kind === "comment" ? "Commented." : delivery.state === "queued" ? "Queued: the agent reads your message at its next step." : delivery.state === "delivered" ? "Delivered to the agent." : delivery.state === "not_delivered" ? `Not delivered${delivery.reason === void 0 ? "" : `: ${str(delivery.reason)}`}.` : "Sent to the agent.";
361271
361399
  return result(answer2, answer2.body, `${fate}
@@ -361273,7 +361401,7 @@ ${linkOf(answer2.url, id12)}
361273
361401
  `);
361274
361402
  }
361275
361403
  async function taskStop(deps, env3, taskId) {
361276
- const answer2 = await appRequest(deps, env3, `/v1/dev/tasks/${seg(taskId)}/cancel`, { method: "POST", body: { requestId: randomUUID5() } });
361404
+ const answer2 = await appRequest(deps, env3, `/v1/dev/tasks/${seg(taskId)}/cancel`, { method: "POST", body: { requestId: randomUUID6() } });
361277
361405
  const task = answer2.body.task;
361278
361406
  if (task === void 0 || typeof task !== "object") throw agentXError("RUNTIME_UNAVAILABLE", UNEXPECTED);
361279
361407
  const lines = ["Stop requested.", `${str(task.title, "(no title)")}`, ` task ${taskId}${typeof task.project === "string" ? ` on ${str(task.project)}` : ""}${typeof task.status === "string" ? `; ${str(task.status.toLowerCase())}` : ""}`];
@@ -361282,7 +361410,7 @@ async function taskStop(deps, env3, taskId) {
361282
361410
  }
361283
361411
  async function sessionControl(deps, env3, id12, action) {
361284
361412
  if (action === "stop" && !SessionIdSchema.safeParse(id12).success && TASK_ID.test(id12)) return await taskStop(deps, env3, id12);
361285
- const answer2 = await appRequest(deps, env3, sessionPath(id12, `/${action}`), { method: "POST", body: { requestId: randomUUID5() } });
361413
+ const answer2 = await appRequest(deps, env3, sessionPath(id12, `/${action}`), { method: "POST", body: { requestId: randomUUID6() } });
361286
361414
  const view2 = answer2.body.session ?? {};
361287
361415
  const fresh = typeof view2.sessionId === "string" && view2.sessionId !== id12;
361288
361416
  const first = action === "stop" ? answer2.body.stop === "NOTHING_RUNNING" ? typeof answer2.body.message === "string" && answer2.body.message !== "" ? answer2.body.message : "Nothing was running to stop." : "Stop requested." : fresh ? "Started a new session." : "Retrying.";
@@ -361290,7 +361418,7 @@ async function sessionControl(deps, env3, id12, action) {
361290
361418
  `);
361291
361419
  }
361292
361420
  async function sessionTakeOver(deps, env3, id12) {
361293
- const answer2 = await appRequest(deps, env3, sessionPath(id12, "/take-over"), { method: "POST", body: { requestId: randomUUID5() } });
361421
+ const answer2 = await appRequest(deps, env3, sessionPath(id12, "/take-over"), { method: "POST", body: { requestId: randomUUID6() } });
361294
361422
  if (answer2.status !== 202) throw agentXError("RUNTIME_UNAVAILABLE", UNEXPECTED);
361295
361423
  return confirmationOf(answer2);
361296
361424
  }
@@ -361315,7 +361443,7 @@ async function sessionShare(deps, env3, id12, input2) {
361315
361443
  principal = { kind: "member", developerId: member2.developerId };
361316
361444
  who2 = clean(member2.name);
361317
361445
  }
361318
- const answer2 = await appRequest(deps, env3, sessionPath(id12, "/shares"), { method: "PUT", body: { requestId: randomUUID5(), principal, level } });
361446
+ const answer2 = await appRequest(deps, env3, sessionPath(id12, "/shares"), { method: "PUT", body: { requestId: randomUUID6(), principal, level } });
361319
361447
  if (answer2.status === 202 || answer2.body.status === "NEEDS_CONFIRMATION") return confirmationOf(answer2);
361320
361448
  if (answer2.body.share === void 0) throw agentXError("RUNTIME_UNAVAILABLE", UNEXPECTED);
361321
361449
  return result(answer2, answer2.body, `Shared with ${who2} (${LEVEL_WORDS[level]}).
@@ -361333,7 +361461,7 @@ async function sessionStart(deps, env3, input2) {
361333
361461
  const answer2 = await appRequest(deps, env3, "/v1/dev/tasks", {
361334
361462
  method: "POST",
361335
361463
  body: {
361336
- requestId: randomUUID5(),
361464
+ requestId: randomUUID6(),
361337
361465
  project: project3,
361338
361466
  instructions: instructions2,
361339
361467
  client: "agentx-cli",
@@ -361408,7 +361536,7 @@ async function sessionAnswer(deps, env3, ref, input2) {
361408
361536
  const option = question.options.find((candidate) => candidate.id.toLowerCase() === said || candidate.label.trim().toLowerCase() === said);
361409
361537
  return option === void 0 ? { questionId: question.id, text: answer2 } : { questionId: question.id, optionId: option.id };
361410
361538
  });
361411
- const sent = await appRequest(deps, env3, sessionPath(id12, "/answers"), { method: "POST", body: { requestId: randomUUID5(), round, answers } });
361539
+ const sent = await appRequest(deps, env3, sessionPath(id12, "/answers"), { method: "POST", body: { requestId: randomUUID6(), round, answers } });
361412
361540
  const after = sent.body.session ?? {};
361413
361541
  return result(sent, sent.body, `${[`Answered. Rovara is planning again with your ${plural2(answers.length, "answer", "answers")}.`, linkOf(sent.url, id12, after.link ?? view2.link)].join("\n")}
361414
361542
  `);
@@ -361561,141 +361689,6 @@ function registerSessionCommands(program2, context) {
361561
361689
  // packages/cli/src/company/commands.ts
361562
361690
  init_dist2();
361563
361691
 
361564
- // packages/cli/src/company/people.ts
361565
- init_dist2();
361566
- import { randomUUID as randomUUID6 } from "node:crypto";
361567
- var MEMBERS_PATH = "/v1/dev/company/members";
361568
- var MAX_PAGES3 = 50;
361569
- var ROLES = ["member", "admin", "owner"];
361570
- var ROLE_WORDS = { owner: "owner", admin: "administrator", member: "member" };
361571
- var METHOD_WORDS2 = { slack: "Slack", oidc: "company sign-in", github: "GitHub" };
361572
- var pad = (value) => String(value).padStart(2, "0");
361573
- function localTime(iso7) {
361574
- const at = new Date(iso7);
361575
- if (Number.isNaN(at.getTime())) return terminalSafe(iso7);
361576
- return `${at.getFullYear()}-${pad(at.getMonth() + 1)}-${pad(at.getDate())} ${pad(at.getHours())}:${pad(at.getMinutes())}`;
361577
- }
361578
- var day = (iso7) => localTime(iso7).slice(0, 10);
361579
- var asMember = (value) => {
361580
- if (typeof value !== "object" || value === null) return void 0;
361581
- const row2 = value;
361582
- if (typeof row2.personId !== "string" || typeof row2.role !== "string" || typeof row2.joinedAt !== "string") return void 0;
361583
- return {
361584
- personId: row2.personId,
361585
- role: row2.role,
361586
- joinedAt: row2.joinedAt,
361587
- ...typeof row2.name === "string" ? { name: row2.name } : {},
361588
- ...typeof row2.email === "string" ? { email: row2.email } : {},
361589
- ...typeof row2.signsInWith === "string" ? { signsInWith: row2.signsInWith } : {},
361590
- ...typeof row2.revokedAt === "string" ? { revokedAt: row2.revokedAt } : {}
361591
- };
361592
- };
361593
- async function allMembers(deps, env3) {
361594
- const members2 = [];
361595
- let cursor2;
361596
- let answer2;
361597
- for (let page = 0; page < MAX_PAGES3; page += 1) {
361598
- answer2 = await appRequest(deps, env3, `${MEMBERS_PATH}?limit=100${cursor2 === void 0 ? "" : `&cursor=${encodeURIComponent(cursor2)}`}`);
361599
- const rows = Array.isArray(answer2.body.members) ? answer2.body.members : [];
361600
- for (const row2 of rows) {
361601
- const member2 = asMember(row2);
361602
- if (member2 !== void 0) members2.push(member2);
361603
- }
361604
- cursor2 = answer2.body.more === true && typeof answer2.body.cursor === "string" ? answer2.body.cursor : void 0;
361605
- if (cursor2 === void 0) break;
361606
- }
361607
- return { env: answer2.env, url: answer2.url, members: members2, more: cursor2 !== void 0 };
361608
- }
361609
- var who = (member2) => {
361610
- const name3 = member2.name === void 0 ? void 0 : terminalSafe(member2.name);
361611
- const email4 = member2.email === void 0 ? void 0 : terminalSafe(member2.email);
361612
- return name3 !== void 0 && email4 !== void 0 ? `${name3} (${email4})` : name3 ?? email4 ?? `person ${member2.personId.slice(0, 12)}`;
361613
- };
361614
- function findMember(members2, typed) {
361615
- const live = members2.filter((member2) => member2.revokedAt === void 0);
361616
- const key = typed.trim();
361617
- const lower = key.toLowerCase();
361618
- const byId = live.filter((member2) => member2.personId === lower);
361619
- const byEmail = live.filter((member2) => member2.email?.toLowerCase() === lower);
361620
- const byName = live.filter((member2) => member2.name?.toLowerCase() === lower);
361621
- const found = byId.length > 0 ? byId : byEmail.length > 0 ? byEmail : byName;
361622
- if (found.length === 1) return found[0];
361623
- if (found.length > 1) throw agentXError("CONFIG_INVALID", `${found.length} members are called ${terminalSafe(key)}; name them by email instead (rovara company members shows each one's)`);
361624
- throw agentXError("NOT_FOUND", `no member of your company is ${terminalSafe(key)}; rovara company members lists who is in it`);
361625
- }
361626
- async function companyName(deps, env3) {
361627
- const details = await appRequest(deps, env3, COMPANY_DETAILS_PATH);
361628
- return { env: details.env, url: details.url, name: details.body.name === null || details.body.name === void 0 ? "your company" : str(details.body.name), companyId: str(details.body.companyId) };
361629
- }
361630
- function memberLine(member2) {
361631
- const parts2 = [` ${who(member2)}`, ROLE_WORDS[member2.role] ?? terminalSafe(member2.role)];
361632
- if (member2.signsInWith !== void 0) parts2.push(`signs in with ${METHOD_WORDS2[member2.signsInWith] ?? terminalSafe(member2.signsInWith)}`);
361633
- parts2.push(`joined ${day(member2.joinedAt)}`);
361634
- if (member2.revokedAt !== void 0) parts2.push(`removed ${day(member2.revokedAt)}`);
361635
- return parts2.join(", ");
361636
- }
361637
- async function companyMembers(deps, env3, options) {
361638
- const listed3 = await allMembers(deps, env3);
361639
- const shown2 = options.all ? listed3.members : listed3.members.filter((member2) => member2.revokedAt === void 0);
361640
- const lines = shown2.length === 0 ? ["Your company has no members to show."] : [`${shown2.length} ${shown2.length === 1 ? "member" : "members"}:`, ...shown2.map(memberLine)];
361641
- if (listed3.more) lines.push(`More members are not shown (the first ${MAX_PAGES3 * 100}).`);
361642
- return result(listed3, { members: shown2, more: listed3.more }, `${lines.join("\n")}
361643
- `);
361644
- }
361645
- var declined = (env3, url2) => result({ env: env3, url: url2 }, { applied: false }, "Nothing changed.\n");
361646
- async function companyRole(deps, env3, typed, role, io) {
361647
- if (!ROLES.includes(role)) throw agentXError("CONFIG_INVALID", "the role is member, admin or owner");
361648
- const listed3 = await allMembers(deps, env3);
361649
- const member2 = findMember(listed3.members, typed);
361650
- if (member2.role === role) return result(listed3, { applied: false, personId: member2.personId, role }, `${who(member2)} is already ${ROLE_WORDS[role]}.
361651
- `);
361652
- const company = await companyName(deps, env3);
361653
- io.tell(`This changes ${who(member2)}'s role in ${company.name} from ${ROLE_WORDS[member2.role] ?? terminalSafe(member2.role)} to ${ROLE_WORDS[role]}.`);
361654
- if (!await io.confirm("Apply this change?")) return declined(listed3.env, listed3.url);
361655
- const answer2 = await appRequest(deps, env3, `${MEMBERS_PATH}/${seg(member2.personId)}/role`, { method: "PUT", body: { role } });
361656
- return result(answer2, { applied: true, personId: member2.personId, role }, `${who(member2)}'s role in ${company.name} is now ${ROLE_WORDS[role]}.
361657
- `);
361658
- }
361659
- var count4 = (value, one, many) => {
361660
- const n3 = typeof value === "number" ? value : 0;
361661
- return `${n3} ${n3 === 1 ? one : many}`;
361662
- };
361663
- var names = (value) => Array.isArray(value) ? value.filter((item) => typeof item === "string").map(terminalSafe) : [];
361664
- var objectOf = (value) => typeof value === "object" && value !== null ? value : {};
361665
- function removalLines(member2, company, preview, to) {
361666
- const handOver = objectOf(preview.handOver);
361667
- const owned = names(preview.ownedProjects), granted = names(preview.projectGrants);
361668
- const lines = [`This removes ${who(member2)} (${ROLE_WORDS[str(preview.role)] ?? terminalSafe(str(preview.role))}) from ${company}: their sign-ins end and their access to ${company}'s projects is taken away.`];
361669
- if (granted.length > 0) lines.push(` Project access they lose: ${granted.join(", ")}.`);
361670
- lines.push(` ${to} takes over ${count4(handOver.agents, "agent", "agents")}, ${count4(handOver.chains, "chain", "chains")}, ${count4(handOver.projects, "project", "projects")}${owned.length > 0 ? ` (${owned.join(", ")})` : ""} and ${count4(handOver.tasks, "open task", "open tasks")}.`);
361671
- if (typeof handOver.tasksLeft === "number" && handOver.tasksLeft > 0) lines.push(` ${count4(handOver.tasksLeft, "open task", "open tasks")} cannot be handed over and will stay without an owner.`);
361672
- if (typeof preview.awaitingTheirDecision === "number" && preview.awaitingTheirDecision > 0) lines.push(` ${count4(preview.awaitingTheirDecision, "task is", "tasks are")} waiting on their decision.`);
361673
- return lines;
361674
- }
361675
- async function companyRemove(deps, env3, typed, options, io) {
361676
- const listed3 = await allMembers(deps, env3);
361677
- const member2 = findMember(listed3.members, typed);
361678
- const successor = options.to === void 0 ? void 0 : findMember(listed3.members, options.to);
361679
- const preview = (await appRequest(deps, env3, `${MEMBERS_PATH}/${seg(member2.personId)}/removal-preview${successor === void 0 ? "" : `?successorId=${seg(successor.personId)}`}`)).body;
361680
- if (preview.mayRemove === false) throw agentXError("FORBIDDEN", member2.role === "owner" ? "only an owner can remove an owner" : "you cannot remove this member");
361681
- const company = await companyName(deps, env3);
361682
- const named4 = objectOf(preview.successor).name;
361683
- const to = typeof named4 === "string" ? terminalSafe(named4) : successor !== void 0 ? who(successor) : "you";
361684
- for (const line21 of removalLines(member2, company.name, preview, to)) io.tell(line21);
361685
- if (!await io.confirm("Apply this change?")) return declined(listed3.env, listed3.url);
361686
- const answer2 = await appRequest(deps, env3, `${MEMBERS_PATH}/${seg(member2.personId)}/removal`, {
361687
- method: "POST",
361688
- body: { requestId: randomUUID6(), expectedRole: str(preview.role), ...successor === void 0 ? {} : { successorId: successor.personId } }
361689
- });
361690
- const moved = objectOf(answer2.body.moved);
361691
- return result(
361692
- answer2,
361693
- { applied: true, personId: member2.personId, ...answer2.body },
361694
- `Removed ${who(member2)} from ${company.name}. ${to === "you" ? "You took" : `${to} took`} over ${count4(moved.agents, "agent", "agents")}, ${count4(moved.chains, "chain", "chains")}, ${count4(moved.projects, "project", "projects")} and ${count4(moved.tasks, "open task", "open tasks")}.
361695
- `
361696
- );
361697
- }
361698
-
361699
361692
  // packages/cli/src/company/invites.ts
361700
361693
  init_dist2();
361701
361694
  init_zod();
@@ -361849,15 +361842,6 @@ function registerPeopleCommands(company, context, print) {
361849
361842
  company.command("remove").description("remove a member from your company and hand what they own to you (or --to someone else); shows what moves and asks first").argument("<member>", "the member's email, name or person id").option("--to <member>", "the member who takes over their agents, chains, projects and open tasks (default: you)").option("--yes", "make the change without asking", false).action(async (member2, options, command5) => print(command5, await companyRemove(session(), context.developerEnv(command5), member2, options.to === void 0 ? {} : { to: options.to }, io(options.yes))));
361850
361843
  }
361851
361844
 
361852
- // packages/cli/src/admin/workspaces.ts
361853
- init_dist2();
361854
- async function listAdminWorkspaces(input2, fetchImplementation = fetch) {
361855
- const response = await fetchImplementation(`${input2.controlPlaneUrl.replace(/\/$/, "")}/v1/admin/workspaces`, { method: "GET", headers: { authorization: `Bearer ${input2.accessToken}` } });
361856
- const parsed = AdminWorkspacesResponseSchema.safeParse(await adminResponseBody(response));
361857
- if (!parsed.success) throw agentXError("RUNTIME_UNAVAILABLE", "control plane returned an invalid workspace list");
361858
- return parsed.data;
361859
- }
361860
-
361861
361845
  // packages/cli/src/deployment.ts
361862
361846
  init_dist2();
361863
361847
  var import_yaml3 = __toESM(require_dist4(), 1);
@@ -368106,7 +368090,7 @@ init_dist2();
368106
368090
  import { realpathSync } from "node:fs";
368107
368091
 
368108
368092
  // packages/cli/src/version.ts
368109
- var RELEASE_VERSION = true ? "0.5.20" : void 0;
368093
+ var RELEASE_VERSION = true ? "0.5.21" : void 0;
368110
368094
  var CLI_VERSION = RELEASE_VERSION ?? "0.1.0";
368111
368095
  function isPrereleaseVersion(version3) {
368112
368096
  return /^\d+\.\d+\.\d+-/.test(version3);
@@ -375868,8 +375852,6 @@ var bindingRow = external_exports.object({
375868
375852
  boundAt: external_exports.iso.datetime(),
375869
375853
  boundBy: external_exports.union([operator, person3])
375870
375854
  }).strict();
375871
- var markerKey = { pk: "SLACK_WORKSPACE_BINDING", sk: "BACKFILL" };
375872
- var markerRow = external_exports.object({ pk: external_exports.literal("SLACK_WORKSPACE_BINDING"), sk: external_exports.literal("BACKFILL") }).strict();
375873
375855
  var teamKey = (teamId) => ({ pk: `SLACK_TEAM#${teamId}`, sk: "BINDING" });
375874
375856
  var companyWorkspaceKey = (companyId, teamId) => ({ pk: `ORG#${companyId}#SLACK_WORKSPACES`, sk: `TEAM#${teamId}` });
375875
375857
  function parseBinding(value) {
@@ -375902,7 +375884,6 @@ function indexTransaction(tableName, row2, create) {
375902
375884
  }
375903
375885
  function createSlackWorkspaceBindings(deps) {
375904
375886
  const now = deps.now ?? Date.now;
375905
- const legacy = slackWorkspaceTeam(deps.legacyTeamId) ? deps.legacyTeamId : void 0;
375906
375887
  const operation2 = (body) => {
375907
375888
  const started = now();
375908
375889
  let commands5 = 0;
@@ -375911,8 +375892,6 @@ function createSlackWorkspaceBindings(deps) {
375911
375892
  if (commands5 > 8 || bytes5 > 65536 || now() - started > 1e4)
375912
375893
  throw new SlackWorkspaceRefused();
375913
375894
  };
375914
- if (deps.legacyTeamId !== void 0 && deps.legacyTeamId !== "" && legacy === void 0)
375915
- return Promise.reject(new SlackWorkspaceRefused());
375916
375895
  return body(async (command5) => {
375917
375896
  commands5++;
375918
375897
  check4();
@@ -375930,14 +375909,6 @@ function createSlackWorkspaceBindings(deps) {
375930
375909
  throw new SlackWorkspaceRefused();
375931
375910
  return response.Item;
375932
375911
  };
375933
- const complete = async (send3) => {
375934
- const row2 = await read(send3, markerKey);
375935
- if (row2 === void 0)
375936
- return false;
375937
- if (!markerRow.safeParse(row2).success)
375938
- throw new SlackWorkspaceRefused();
375939
- return true;
375940
- };
375941
375912
  const storedBinding = async (send3, team) => {
375942
375913
  const row2 = await read(send3, teamKey(team));
375943
375914
  if (row2 === void 0)
@@ -375971,9 +375942,7 @@ function createSlackWorkspaceBindings(deps) {
375971
375942
  if (!slackWorkspaceTeam(team))
375972
375943
  throw new SlackWorkspaceRefused();
375973
375944
  const company = (await storedBinding(send3, team))?.companyId;
375974
- if (company !== void 0)
375975
- return company;
375976
- return !await complete(send3) && team === legacy ? IMPLICIT_COMPANY_ID : void 0;
375945
+ return company === void 0 || company === IMPLICIT_COMPANY_ID ? void 0 : company;
375977
375946
  });
375978
375947
  return {
375979
375948
  companyOf: companyOf2,
@@ -375985,31 +375954,13 @@ function createSlackWorkspaceBindings(deps) {
375985
375954
  },
375986
375955
  channelCompanyOf: (where) => where !== null && typeof where === "object" && where.channel === "slack" ? companyOf2(where.tenant) : void 0,
375987
375956
  bind: (company, team, by) => operation2(async (send3) => {
375988
- if (!OrgIdSchema.safeParse(company).success || !slackWorkspaceTeam(team) || !operator.safeParse(by).success)
375989
- throw new SlackWorkspaceRefused();
375990
- if (!await complete(send3) && company !== IMPLICIT_COMPANY_ID)
375957
+ if (!OrgIdSchema.safeParse(company).success || company === IMPLICIT_COMPANY_ID || !slackWorkspaceTeam(team) || !operator.safeParse(by).success)
375991
375958
  throw new SlackWorkspaceRefused();
375992
375959
  await claim2(send3, company, team, by);
375993
- }),
375994
- backfill: () => operation2(async (send3) => {
375995
- if (await complete(send3))
375996
- return { teamsRead: 0 };
375997
- if (legacy !== void 0)
375998
- await claim2(send3, IMPLICIT_COMPANY_ID, legacy, "backfill");
375999
- try {
376000
- await send3(new import_lib_dynamodb6.PutCommand({ TableName: deps.tableName, Item: markerKey, ConditionExpression: "attribute_not_exists(pk)" }));
376001
- } catch (error64) {
376002
- if (!(error64 instanceof Error) || error64.name !== "ConditionalCheckFailedException" || !await complete(send3))
376003
- throw new SlackWorkspaceRefused();
376004
- }
376005
- return { teamsRead: legacy === void 0 ? 0 : 1 };
376006
375960
  })
376007
375961
  };
376008
375962
  }
376009
- var SlackWorkspaceOperatorEventSchema = external_exports.discriminatedUnion("source", [
376010
- external_exports.object({ source: external_exports.literal("agentx.slack-workspace-bind"), teamId: external_exports.string().max(32).refine(slackWorkspaceTeam), companyId: OrgIdSchema, by: operator }).strict(),
376011
- external_exports.object({ source: external_exports.literal("agentx.slack-workspace-backfill") }).strict()
376012
- ]);
375963
+ var SlackWorkspaceOperatorEventSchema = external_exports.object({ source: external_exports.literal("agentx.slack-workspace-bind"), teamId: external_exports.string().max(32).refine(slackWorkspaceTeam), companyId: OrgIdSchema, by: operator }).strict();
376013
375964
  var cursorSchema = external_exports.object({ pk: external_exports.string().min(1).max(2048), sk: external_exports.string().min(1).max(1024) }).strict();
376014
375965
  var pageSchema = external_exports.object({
376015
375966
  Items: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).optional(),
@@ -376073,7 +376024,6 @@ async function bindWorkspace(deps, companyId, teamId, apply) {
376073
376024
  if (!apply)
376074
376025
  return "bound";
376075
376026
  const bindings = createSlackWorkspaceBindings({ client: deps.documentClient, tableName: deps.tableName, ...deps.now === void 0 ? {} : { now: deps.now } });
376076
- await bindings.backfill();
376077
376027
  await bindings.bind(companyId, teamId, BY);
376078
376028
  return "bound";
376079
376029
  }
@@ -377147,6 +377097,28 @@ async function installations(context) {
377147
377097
  // packages/cli/src/init/finish-steps.ts
377148
377098
  init_answer_schemas();
377149
377099
 
377100
+ // packages/cli/src/admin/slack.ts
377101
+ init_dist2();
377102
+ async function bindCompanyChannel(input2, fetchImplementation = fetch) {
377103
+ const projectName = AgentXNameSchema.parse(input2.projectName);
377104
+ return sendBindingRequest(input2, `/v1/dev/company/slack/projects/${projectName}/bindings`, fetchImplementation);
377105
+ }
377106
+ async function sendBindingRequest(input2, base2, fetchImplementation) {
377107
+ const teamId = SlackTeamIdSchema.parse(input2.teamId);
377108
+ const channelId = SlackChannelIdSchema.parse(input2.channelId);
377109
+ const response = await fetchImplementation(`${input2.controlPlaneUrl.replace(/\/$/, "")}${base2}/${teamId}/${channelId}`, {
377110
+ method: "PUT",
377111
+ headers: { authorization: `Bearer ${input2.accessToken}` }
377112
+ });
377113
+ const { ok: ok2, status, body } = await readJsonResponse(response);
377114
+ if (!ok2) {
377115
+ const message = body === void 0 ? `HTTP ${status}` : serverError(body).message ?? `HTTP ${status}`;
377116
+ throw agentXError("RUNTIME_UNAVAILABLE", `Slack channel binding failed: ${message}`);
377117
+ }
377118
+ if (body === void 0) throw agentXError("RUNTIME_UNAVAILABLE", "control plane returned an invalid response");
377119
+ return body;
377120
+ }
377121
+
377150
377122
  // packages/cli/src/setup/connectors/asana.ts
377151
377123
  init_dist2();
377152
377124
  init_answer_schemas();
@@ -377159,7 +377131,6 @@ import { stat as stat6 } from "node:fs/promises";
377159
377131
  var import_yaml5 = __toESM(require_dist4(), 1);
377160
377132
  init_dist2();
377161
377133
  import { access as access4, mkdir as mkdir8, readdir as readdir4, readFile as readFile20, writeFile as writeFile6 } from "node:fs/promises";
377162
- import { createHash as createHash33 } from "node:crypto";
377163
377134
  import { join as join18 } from "node:path";
377164
377135
  import { isDeepStrictEqual as isDeepStrictEqual3 } from "node:util";
377165
377136
 
@@ -378690,7 +378661,7 @@ async function writeProjectFile(configDir, definition, register) {
378690
378661
  }
378691
378662
  var LocalSaveAfterRegistrationError = class extends AgentXError {
378692
378663
  constructor(projectName, revision3, file2, cause) {
378693
- super("CONFIG_INVALID", `revision ${revision3} of ${projectName} IS registered with the control plane; only the local file ${file2} (or the stored setup decision beside it) could not be updated (${cause}); do not register again. Fix the problem (permissions or disk space), then bring that file up to date: copy the registered settings into it and set its revision to ${revision3}, before the next project command`, 400);
378664
+ super("CONFIG_INVALID", `revision ${revision3} of ${projectName} IS registered with the control plane; only the local file ${file2} could not be updated (${cause}); do not register again. Fix the problem (permissions or disk space), then bring that file up to date: copy the registered settings into it and set its revision to ${revision3}, before the next project command`, 400);
378694
378665
  this.projectName = projectName;
378695
378666
  this.revision = revision3;
378696
378667
  }
@@ -378707,22 +378678,10 @@ async function registerRevision(request) {
378707
378678
  const input2 = { ...request, definition: modelChecked.definition };
378708
378679
  const foundation = environmentStackName(input2.env, "foundation");
378709
378680
  const runtimeBinding = ec2Binding(await input2.services.stackOutputs(foundation), foundation);
378710
- const result4 = await registerProject({
378711
- controlPlaneUrl: input2.session.controlPlaneUrl,
378712
- accessToken: input2.session.accessToken,
378713
- definition: input2.definition,
378714
- runtimeBinding,
378715
- ...input2.setupApproval === void 0 ? {} : { setupApproval: input2.setupApproval },
378716
- ...input2.registerPath === void 0 ? {} : { path: input2.registerPath }
378717
- }, input2.services.fetch);
378718
- const registeredDefinition = input2.registerPath === void 0 ? input2.definition : withSavedCredentialRefs(input2.definition, result4);
378681
+ const result4 = await registerProject({ controlPlaneUrl: input2.session.controlPlaneUrl, accessToken: input2.session.accessToken, definition: input2.definition, runtimeBinding }, input2.services.fetch);
378682
+ const registeredDefinition = withSavedCredentialRefs(input2.definition, result4);
378719
378683
  const preflight = RegistrationPreflightSchema.safeParse(result4.preflight);
378720
378684
  const warnings = [...modelChecked.warnings, ...Array.isArray(result4.warnings) ? result4.warnings.filter((entry) => typeof entry === "string") : []];
378721
- if (input2.setupApproval?.decision === "approve" && input2.definition.e2e !== void 0) {
378722
- if (result4.setupRuntime === "QUEUED") warnings.push("E2E testing setup was queued; project registration is complete, but testing is not ready.");
378723
- else if (result4.setupRuntime === "UNAVAILABLE") warnings.push("E2E testing setup is unavailable; project registration is complete, but testing is not ready.");
378724
- else warnings.push("E2E testing setup status is unknown; project registration is complete, but testing is not ready.");
378725
- }
378726
378685
  if (input2.services.loopHome !== void 0) {
378727
378686
  try {
378728
378687
  const enrollment = await recordRegisteredLoopEnrollment({ home: input2.services.loopHome, env: input2.env, controlPlaneUrl: input2.session.controlPlaneUrl, definition: registeredDefinition, response: result4 });
@@ -378734,11 +378693,6 @@ async function registerRevision(request) {
378734
378693
  let file2;
378735
378694
  try {
378736
378695
  file2 = await writeProjectFile(input2.services.configDir, registeredDefinition, { env: input2.env, binding: runtimeBinding });
378737
- if (input2.setupApproval !== void 0) {
378738
- const policy = input2.setupPolicy ?? input2.definition.e2e;
378739
- if (policy === void 0) throw agentXError("CONFIG_INVALID", "a stored setup decision cannot be saved without its source-backed E2E policy");
378740
- await writeStoredSetupDecision({ configDir: input2.services.configDir, env: input2.env, session: input2.session, definition: input2.definition, policy, decision: input2.setupApproval });
378741
- }
378742
378696
  } catch (error64) {
378743
378697
  const raw = typeof error64.code === "string" ? error64.code : error64 instanceof Error ? error64.name : "";
378744
378698
  const cause = /^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(raw) ? raw : "unknown error";
@@ -378821,114 +378775,6 @@ async function existingProject(configDir, name3) {
378821
378775
  }
378822
378776
  }
378823
378777
  var cloneUrlOf = (fullName) => `https://github.com/${fullName}.git`.toLowerCase();
378824
- function setupDecisionPath(configDir, projectName) {
378825
- return `${projectFilePath(configDir, projectName)}.setup-approval.json`;
378826
- }
378827
- function normalizedControlPlaneUrl(value) {
378828
- try {
378829
- const url2 = new URL(value);
378830
- if (url2.protocol !== "https:" && url2.protocol !== "http:" || url2.username || url2.password || url2.search || url2.hash) throw new Error("invalid control-plane URL");
378831
- return url2.href.replace(/\/$/, "");
378832
- } catch {
378833
- throw agentXError("CONFIG_INVALID", "the setup decision cannot be bound to an invalid control-plane URL");
378834
- }
378835
- }
378836
- function policyDigest(value) {
378837
- return createHash33("sha256").update(canonicalJson(E2EPolicySchema.parse(value)), "utf8").digest("hex");
378838
- }
378839
- function setupDecisionRecord(input2) {
378840
- const repositoryUrl = input2.definition.repositories[0]?.url;
378841
- if (repositoryUrl === void 0 || !/^[a-f0-9]{64}$/.test(input2.decision.proposalSha256) || input2.decision.proposalRef.length > 512 || !input2.decision.proposalRef.startsWith("project-setup-proposals/") || input2.decision.decision !== "approve" && input2.decision.decision !== "decline") {
378842
- throw agentXError("CONFIG_INVALID", "the stored setup decision is missing its project or source proposal binding");
378843
- }
378844
- return {
378845
- schemaVersion: 1,
378846
- env: input2.env,
378847
- controlPlaneUrl: normalizedControlPlaneUrl(input2.session.controlPlaneUrl),
378848
- projectName: input2.definition.name,
378849
- repositoryUrl: repositoryUrl.toLowerCase().replace(/\/$/, ""),
378850
- policySha256: policyDigest(input2.policy),
378851
- setupApproval: input2.decision
378852
- };
378853
- }
378854
- async function writeStoredSetupDecision(input2) {
378855
- await mkdir8(input2.configDir, { recursive: true, mode: 448 });
378856
- await writeFile6(setupDecisionPath(input2.configDir, input2.definition.name), `${JSON.stringify(setupDecisionRecord(input2), null, 2)}
378857
- `, { mode: 384 });
378858
- }
378859
- async function setupDecisionForRevision(input2) {
378860
- const path6 = setupDecisionPath(input2.configDir, input2.definition.name);
378861
- let raw;
378862
- try {
378863
- raw = await readFile20(path6, "utf8");
378864
- } catch (error64) {
378865
- if (error64.code === "ENOENT") {
378866
- if (input2.definition.e2e !== void 0) throw agentXError("CONFIG_INVALID", `project ${input2.definition.name} has E2E policy but no local source-backed setup decision; obtain a fresh owner setup decision before registering a revision`);
378867
- return void 0;
378868
- }
378869
- throw agentXError("CONFIG_INVALID", `the local setup decision for ${input2.definition.name} cannot be read; obtain a fresh owner setup decision before registering a revision`);
378870
- }
378871
- if (Buffer.byteLength(raw, "utf8") > 16 * 1024) throw agentXError("CONFIG_INVALID", `the local setup decision for ${input2.definition.name} is too large; obtain a fresh owner setup decision`);
378872
- let parsed;
378873
- try {
378874
- parsed = JSON.parse(raw);
378875
- } catch {
378876
- parsed = void 0;
378877
- }
378878
- if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) throw agentXError("CONFIG_INVALID", `the local setup decision for ${input2.definition.name} is invalid; obtain a fresh owner setup decision`);
378879
- const record4 = parsed;
378880
- const decision = record4.setupApproval;
378881
- if (Object.keys(record4).sort().join(",") !== "controlPlaneUrl,env,policySha256,projectName,repositoryUrl,schemaVersion,setupApproval" || record4.schemaVersion !== 1 || typeof record4.env !== "string" || typeof record4.controlPlaneUrl !== "string" || typeof record4.projectName !== "string" || typeof record4.repositoryUrl !== "string" || typeof record4.policySha256 !== "string" || !/^[a-f0-9]{64}$/.test(record4.policySha256) || decision === null || typeof decision !== "object" || Array.isArray(decision)) {
378882
- throw agentXError("CONFIG_INVALID", `the local setup decision for ${input2.definition.name} is invalid; obtain a fresh owner setup decision`);
378883
- }
378884
- const storedDecision = decision;
378885
- if (Object.keys(storedDecision).sort().join(",") !== "decision,proposalRef,proposalSha256" || typeof storedDecision.proposalRef !== "string" || storedDecision.proposalRef.length > 512 || typeof storedDecision.proposalSha256 !== "string" || !/^[a-f0-9]{64}$/.test(storedDecision.proposalSha256) || storedDecision.decision !== "approve" && storedDecision.decision !== "decline") {
378886
- throw agentXError("CONFIG_INVALID", `the local setup decision for ${input2.definition.name} is invalid; obtain a fresh owner setup decision`);
378887
- }
378888
- if (input2.definition.e2e === void 0 && storedDecision.decision === "decline") return void 0;
378889
- const repositoryUrl = input2.definition.repositories[0]?.url.toLowerCase().replace(/\/$/, "");
378890
- let matches2 = record4.env === input2.env && record4.controlPlaneUrl === normalizedControlPlaneUrl(input2.session.controlPlaneUrl) && record4.projectName === input2.definition.name && record4.repositoryUrl === repositoryUrl;
378891
- matches2 &&= input2.definition.e2e !== void 0 && storedDecision.decision === "approve" && record4.policySha256 === policyDigest(input2.definition.e2e);
378892
- if (!matches2) throw agentXError("CONFIG_INVALID", `the saved setup decision for ${input2.definition.name} no longer matches its project, environment, control plane, repository, or E2E policy; obtain a fresh owner setup decision before registering a revision`);
378893
- return { proposalRef: storedDecision.proposalRef, proposalSha256: storedDecision.proposalSha256, decision: storedDecision.decision };
378894
- }
378895
- async function setupRequest(session, fetchImplementation, path6, body, timeoutMs) {
378896
- const response = await fetchImplementation(`${session.controlPlaneUrl.replace(/\/$/, "")}${path6}`, {
378897
- method: "POST",
378898
- headers: { authorization: `Bearer ${session.accessToken}`, "content-type": "application/json" },
378899
- body: JSON.stringify(body),
378900
- ...timeoutMs === void 0 ? {} : { signal: AbortSignal.timeout(timeoutMs) }
378901
- });
378902
- const { ok: ok2, status, body: result4 } = await readJsonResponse(response);
378903
- if (!ok2) {
378904
- const { code: code2, message } = serverError(result4);
378905
- const parsedCode = AgentXErrorCodeSchema.safeParse(code2);
378906
- const fallback2 = status >= 500 ? "RUNTIME_UNAVAILABLE" : "CONFIG_INVALID";
378907
- const responseCode = status === 401 ? "AUTH_REQUIRED" : status === 403 ? "FORBIDDEN" : parsedCode.success ? parsedCode.data : fallback2;
378908
- throw agentXError(responseCode, `${path6} failed with HTTP ${status}${message ? `: ${message}` : ""}`);
378909
- }
378910
- if (result4 === void 0 || result4 === null || typeof result4 !== "object" || Array.isArray(result4)) throw agentXError("CONFIG_INVALID", `${path6} returned a malformed successful response`);
378911
- return result4;
378912
- }
378913
- function validateSetupProposalResponse(value) {
378914
- const proposal = E2ESetupProposalSchema.parse(value.proposal);
378915
- const policy = E2EPolicySchema.parse(value.policy);
378916
- if (typeof value.proposalRef !== "string" || !/^project-setup-proposals\/[a-f0-9]{64}\/[a-f0-9]{64}\.json$/.test(value.proposalRef) || typeof value.proposalSha256 !== "string" || !/^[a-f0-9]{64}$/.test(value.proposalSha256) || value.proposalRef !== `project-setup-proposals/${value.proposalRef.split("/")[1]}/${value.proposalSha256}.json` || value.candidateDigest !== proposal.candidateDigest || policy.targets.length !== proposal.targets.length || proposal.targets.some((target3) => !policy.targets.some((configured) => JSON.stringify(configured) === JSON.stringify(target3)))) {
378917
- throw agentXError("RUNTIME_UNAVAILABLE", "control plane returned an unbound source-backed setup proposal");
378918
- }
378919
- const sentence = typeof value.aiNavigation === "string" ? value.aiNavigation.replace(/[\p{Cc}\p{Cf}]+/gu, " ").trim().slice(0, 400) : "";
378920
- if (policy.modelRouteRevision !== null && sentence === "") throw agentXError("RUNTIME_UNAVAILABLE", "control plane pinned an AI navigation route without saying which");
378921
- const untested = typeof value.aiNavigationUntested === "object" && value.aiNavigationUntested !== null ? value.aiNavigationUntested : void 0;
378922
- const untestedNote = untested !== void 0 && typeof untested.modelId === "string" && /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,199}$/.test(untested.modelId) && typeof untested.sentence === "string" ? { modelId: untested.modelId, sentence: untested.sentence.replace(/[\p{Cc}\p{Cf}]+/gu, " ").trim().slice(0, 600) } : null;
378923
- return {
378924
- proposal,
378925
- policy,
378926
- proposalRef: value.proposalRef,
378927
- proposalSha256: value.proposalSha256,
378928
- aiNavigation: policy.modelRouteRevision === null || sentence === "" ? null : sentence,
378929
- aiNavigationUntested: policy.modelRouteRevision === null ? untestedNote : null
378930
- };
378931
- }
378932
378778
  function differences(existing, wanted) {
378933
378779
  const repository = existing.repositories[0];
378934
378780
  const typed = (line21, timeout) => line21.trim() === "" ? [] : [parseCommandLine(line21, repository?.path ?? ".", timeout)];
@@ -378938,85 +378784,6 @@ function differences(existing, wanted) {
378938
378784
  if (wanted.testCommand !== void 0 && !isDeepStrictEqual3(typed(wanted.testCommand, TEST_TIMEOUT), existing.readiness)) found.push("test command");
378939
378785
  return found;
378940
378786
  }
378941
- async function confirmSetupPlan(input2) {
378942
- const { proposal } = input2;
378943
- const targetSummary = proposal.targets.map((target3) => target3.kind + ":" + target3.targetId).join(", ") || "no targets detected (no usable package.json found; browser and API checks need a Node 22 app, see docs/e2e-onboarding.md, Supported stacks)";
378944
- const mockSummary = proposal.missingInputs.filter((item) => item.disposition === "mock-substitutable").map((item) => item.kind).join(", ") || "none detected";
378945
- const blockerSummary = proposal.missingInputs.filter((item) => item.disposition === "blocking").map((item) => item.reason).join("; ") || "none";
378946
- input2.write(proposal.missingInputs.length === 0 ? "Detected source-backed E2E setup." : "Detected source-backed E2E setup with unresolved inputs: " + blockerSummary);
378947
- const untestedSummary = input2.aiNavigationUntested === void 0 || input2.aiNavigationUntested === null ? void 0 : `${input2.aiNavigationUntested.sentence}. Run \`agentx${input2.env === void 0 ? "" : ` --env ${input2.env}`} project model-check test --model ${input2.aiNavigationUntested.modelId}\``;
378948
- const aiNavigationSummary = input2.aiNavigation ?? untestedSummary ?? "AI navigation steps will not run: this installation has no usable model route for them (it needs a configured model provider with its key), so only deterministic checks run";
378949
- input2.write(aiNavigationSummary);
378950
- const commandSummary = "setup: " + input2.setup.map(commandLine2).join("; ") + "; readiness: " + input2.readiness.map(commandLine2).join("; ");
378951
- return input2.prompter.confirm("Use this project setup plan? (" + commandSummary + "; targets: " + targetSummary + "; mock substitutions: " + mockSummary + "; unresolved inputs: " + blockerSummary + "; " + aiNavigationSummary + ")", { defaultValue: true });
378952
- }
378953
- async function recordSetupDecision(input2) {
378954
- const { trusted, decision } = input2;
378955
- const approval = await setupRequest(input2.session, input2.fetch, "/v1/admin/projects/setup-approvals", {
378956
- projectName: input2.projectName,
378957
- proposalRef: trusted.proposalRef,
378958
- proposalSha256: trusted.proposalSha256,
378959
- decision
378960
- });
378961
- if (approval.proposalRef !== trusted.proposalRef || approval.proposalSha256 !== trusted.proposalSha256 || approval.decision !== decision) {
378962
- throw agentXError("RUNTIME_UNAVAILABLE", "control plane returned a mismatched immutable setup decision");
378963
- }
378964
- return { proposalRef: trusted.proposalRef, proposalSha256: trusted.proposalSha256, decision };
378965
- }
378966
- async function registeredHead(input2) {
378967
- const unreadable = (reason2) => agentXError("RUNTIME_UNAVAILABLE", `could not read the registered revision of ${input2.name}; nothing was approved or registered${reason2}. Run the command again when the control plane answers`);
378968
- let listing;
378969
- try {
378970
- const response = await input2.fetch(`${input2.session.controlPlaneUrl.replace(/\/$/, "")}/v1/admin/projects`, { headers: { authorization: `Bearer ${input2.session.accessToken}` }, signal: AbortSignal.timeout(3e4) });
378971
- const { ok: ok2, status, body } = await readJsonResponse(response);
378972
- if (!ok2) throw unreadable(` (HTTP ${status})`);
378973
- listing = AdminProjectsResponseSchema.safeParse(body);
378974
- } catch (error64) {
378975
- if (error64 instanceof AgentXError) throw error64;
378976
- throw unreadable("");
378977
- }
378978
- if (!listing.success) throw unreadable(" (the answer was not a project list)");
378979
- const found = listing.data.projects.find((project3) => project3.name === input2.name);
378980
- if (found === void 0) throw agentXError("CONFIG_INVALID", `${input2.name} is not registered with this control plane (check --env), so there is no revision to build on; nothing was approved or registered. Register it with agentx project add first`);
378981
- return { revision: found.latestRevision };
378982
- }
378983
- async function reapproveProjectSetup(input2) {
378984
- const name3 = input2.projectName;
378985
- if (!/^[a-z][a-z0-9-]{0,62}$/.test(name3)) throw agentXError("CONFIG_INVALID", `--project-name ${JSON.stringify(name3)} is not valid; a project name is 1 to 63 lowercase letters, digits and hyphens, starting with a letter`);
378986
- const configDir = input2.services.configDir;
378987
- const existing = await existingProject(configDir, name3);
378988
- const file2 = projectFilePath(configDir, name3);
378989
- if (existing === void 0) throw agentXError("CONFIG_INVALID", `project ${name3} is not registered from this machine (no ${file2}); register it with agentx project add first`);
378990
- const repository = existing.repositories[0];
378991
- if (repository === void 0) throw agentXError("CONFIG_INVALID", `project ${name3} has no repository to propose its setup from`);
378992
- const head = await registeredHead({ session: input2.session, fetch: input2.services.fetch, name: name3 });
378993
- if (head.revision !== existing.revision) {
378994
- throw agentXError("CONFIG_INVALID", `revision ${head.revision} is registered for ${name3}, but the local file ${file2} says revision ${existing.revision}, so it may not hold the registered settings; nothing was approved or registered. There is no command that fetches a registered revision: copy the registered settings into that file and set its revision to ${head.revision} (the operator who registered revision ${head.revision} has them), then run this again`);
378995
- }
378996
- const trusted = validateSetupProposalResponse(await setupRequest(input2.session, input2.services.fetch, "/v1/admin/projects/setup-proposals", {
378997
- repositoryUrl: repository.url,
378998
- ref: repository.defaultBranch
378999
- }, 65e3));
379000
- const accepted = await confirmSetupPlan({ prompter: input2.prompter, write: input2.write, proposal: trusted.proposal, aiNavigation: trusted.aiNavigation, env: input2.env, aiNavigationUntested: trusted.aiNavigationUntested, setup: existing.setup, readiness: existing.readiness });
379001
- const setupApproval = await recordSetupDecision({ session: input2.session, fetch: input2.services.fetch, projectName: name3, trusted, decision: accepted ? "approve" : "decline" });
379002
- if (!accepted) {
379003
- input2.write(`Declined the setup of ${name3}; the decision is recorded and revision ${head.revision} stays as it is.`);
379004
- return { name: name3, revision: head.revision, file: file2, decision: "decline", modelRouteRevision: null };
379005
- }
379006
- const definition = ProjectDefinitionSchema.parse({ ...existing, revision: head.revision + 1, e2e: trusted.policy });
379007
- let registered;
379008
- try {
379009
- registered = await registerRevision({ env: input2.env, session: input2.session, definition, services: input2.services, setupApproval, setupPolicy: trusted.policy });
379010
- } catch (error64) {
379011
- if (error64 instanceof LocalSaveAfterRegistrationError) throw error64;
379012
- const code2 = error64 instanceof AgentXError ? error64.code : "RUNTIME_UNAVAILABLE";
379013
- const cause = error64 instanceof AgentXError ? error64.message : "an unexpected error";
379014
- throw agentXError(code2, `your approval of the setup proposal is recorded, but revision ${definition.revision} of ${name3} was NOT registered, so no revision carries it and tasks keep running on revision ${head.revision} (${cause}). Run agentx --env ${input2.env} project setup-approve --project-name ${name3} again; it proposes and asks again, and registers the revision`);
379015
- }
379016
- input2.write(`Approved the setup of ${name3} and registered revision ${definition.revision}${trusted.policy.modelRouteRevision === null ? "" : `, pinning AI navigation route revision ${trusted.policy.modelRouteRevision}`}. Its file is ${registered.file}.`);
379017
- for (const warning2 of registered.warnings) input2.write(`Warning: ${warning2}`);
379018
- return { name: name3, revision: definition.revision, file: registered.file, decision: "approve", modelRouteRevision: trusted.policy.modelRouteRevision };
379019
- }
379020
378787
  async function addProject(input2) {
379021
378788
  const { prompter, flags } = input2;
379022
378789
  const configDir = input2.services.configDir;
@@ -379081,7 +378848,7 @@ async function addProject(input2) {
379081
378848
  readiness,
379082
378849
  orchestratorInstructions: DEFAULT_INSTRUCTIONS
379083
378850
  });
379084
- const registered = await registerRevision({ env: input2.env, session: input2.session, definition, services: input2.services, registerPath: "/v1/dev/projects" });
378851
+ const registered = await registerRevision({ env: input2.env, session: input2.session, definition, services: input2.services });
379085
378852
  input2.write(`Registered project ${name3}, revision 1, on EC2 workers. Its file is ${registered.file}.`);
379086
378853
  for (const warning2 of registered.warnings) input2.write(`Warning: ${warning2}`);
379087
378854
  return { name: name3, revision: 1, file: registered.file };
@@ -379128,8 +378895,7 @@ async function addConnectorRevision(input2) {
379128
378895
  const current = await loadProjectFile({ projectName: input2.projectName, configDir: input2.services.configDir, rerun: input2.rerun });
379129
378896
  const others = (current.integrations?.connectors ?? []).filter((entry) => entry.name !== input2.connector.name);
379130
378897
  const definition = { ...current, revision: current.revision + 1, integrations: { ...current.integrations, connectors: [...others, input2.connector] } };
379131
- const setupApproval = await setupDecisionForRevision({ configDir: input2.services.configDir, env: input2.env, session: input2.session, definition });
379132
- const registered = await registerRevision({ env: input2.env, session: input2.session, definition, services: input2.services, ...setupApproval === void 0 ? {} : { setupApproval } });
378898
+ const registered = await registerRevision({ env: input2.env, session: input2.session, definition, services: input2.services });
379133
378899
  const report = registered.preflight.find((entry) => entry.name === input2.connector.name);
379134
378900
  for (const warning2 of registered.warnings) input2.write(`Warning: ${warning2}`);
379135
378901
  if (report === void 0) {
@@ -379241,7 +379007,7 @@ async function addAsana(input2) {
379241
379007
  input2.write(`The bot user sees the Asana project ${project3.name}.`);
379242
379008
  const { revision: revision3 } = await addConnectorRevision({
379243
379009
  env: input2.env,
379244
- session: input2.session,
379010
+ session: input2.person,
379245
379011
  projectName: input2.projectName,
379246
379012
  write: input2.write,
379247
379013
  services: input2.services,
@@ -379323,7 +379089,7 @@ async function addJira(input2) {
379323
379089
  await registerCredential({ ...input2.session, ref: "jira", type: "static-secret", secretName }, input2.services.fetch);
379324
379090
  const { revision: revision3 } = await addConnectorRevision({
379325
379091
  env: input2.env,
379326
- session: input2.session,
379092
+ session: input2.person,
379327
379093
  projectName: input2.projectName,
379328
379094
  write: input2.write,
379329
379095
  services: input2.services,
@@ -379372,7 +379138,7 @@ async function addLinear(input2) {
379372
379138
  await registerCredential({ ...input2.session, ref: "linear", type: "static-secret", secretName }, input2.services.fetch);
379373
379139
  const { revision: revision3 } = await addConnectorRevision({
379374
379140
  env: input2.env,
379375
- session: input2.session,
379141
+ session: input2.person,
379376
379142
  projectName: input2.projectName,
379377
379143
  write: input2.write,
379378
379144
  services: input2.services,
@@ -381320,7 +381086,6 @@ function firstProjectStep() {
381320
381086
  async run(context, progress) {
381321
381087
  let project3 = progress.current().project;
381322
381088
  if (project3 === void 0) return { status: "done", note: NO_FIRST_PROJECT_NOTE };
381323
- const session = await context.adminSession();
381324
381089
  context.surface?.card(projectCard({ name: project3.name, revision: project3.revision }));
381325
381090
  if (project3.channelId === void 0) {
381326
381091
  const slack = progress.current().slack;
@@ -381329,8 +381094,9 @@ function firstProjectStep() {
381329
381094
  let bound2;
381330
381095
  try {
381331
381096
  const projectName = project3.name;
381097
+ const person4 = await context.personSession();
381332
381098
  bound2 = await addChannel({
381333
- bind: (channelId) => bindSlackChannel({ ...session, teamId: slack.teamId, channelId, projectName }, context.setup.fetch),
381099
+ bind: (channelId) => bindCompanyChannel({ ...person4, teamId: slack.teamId, channelId, projectName }, context.setup.fetch),
381334
381100
  botToken: await readSlackBotToken(context.secrets, context.env),
381335
381101
  teamId: slack.teamId,
381336
381102
  botUserId: slack.botUserId,
@@ -381383,8 +381149,9 @@ function connectorsStep() {
381383
381149
  if (done.has(type)) continue;
381384
381150
  const yes = wanted !== void 0 ? wanted.has(type) : await context.prompter.confirm(`Connect ${CONNECTOR_LABELS[type]} to ${project3.name} now? (You can add it later with agentx connector add ${type})`, { defaultValue: false });
381385
381151
  if (!yes) continue;
381152
+ const person4 = await context.personSession();
381386
381153
  const session = await context.adminSession();
381387
- const base2 = { env: context.env, rerun: `agentx --env ${context.env} init`, session, projectName: project3.name, secrets: context.secrets, prompter: context.prompter, processEnv: context.processEnv, write: context.write, services: context.setup, flags: context.flags };
381154
+ const base2 = { env: context.env, rerun: `agentx --env ${context.env} init`, session, person: person4, projectName: project3.name, secrets: context.secrets, prompter: context.prompter, processEnv: context.processEnv, write: context.write, services: context.setup, flags: context.flags };
381388
381155
  const result4 = type === "linear" ? await addLinear(base2) : type === "jira" ? await addJira(base2) : await addAsana(base2);
381389
381156
  const { warning: warning2 } = result4;
381390
381157
  const current = progress.current();
@@ -384126,6 +383893,10 @@ async function init(options, deps, services, session) {
384126
383893
  ...adminClaim === void 0 ? {} : { adminClaim }
384127
383894
  });
384128
383895
  };
383896
+ const personSession = async () => {
383897
+ const signedIn = await developerAccessToken({ home: services.home, tokenStore: setup.tokenStore, fetch: fetchImplementation }, env3);
383898
+ return { controlPlaneUrl: signedIn.entry.url, accessToken: signedIn.accessToken };
383899
+ };
384129
383900
  let deployment;
384130
383901
  const context = {
384131
383902
  env: env3,
@@ -384181,6 +383952,7 @@ async function init(options, deps, services, session) {
384181
383952
  runPrerequisites: () => runPrerequisites(),
384182
383953
  setup,
384183
383954
  adminSession,
383955
+ personSession,
384184
383956
  flags: options.finishFlags,
384185
383957
  cliInvocation: session.invocation,
384186
383958
  ...options.cloud === void 0 ? {} : { setupPageUrl: options.cloud.url, githubWaitMs: CLOUD_GITHUB_WAIT_MS }
@@ -384998,7 +384770,7 @@ ${toolLines2(offered)}`);
384998
384770
  await storeKey?.();
384999
384771
  const { revision: revision3 } = await addConnectorRevision({
385000
384772
  env: input2.env,
385001
- session: input2.session,
384773
+ session: input2.person,
385002
384774
  projectName: input2.projectName,
385003
384775
  write: input2.write,
385004
384776
  services: input2.services,
@@ -385201,6 +384973,10 @@ function projectOption(command5, what) {
385201
384973
  if (!AgentXNameSchema.safeParse(project3).success) throw agentXError("CONFIG_INVALID", `--project ${project3} is not a project name; use lower-case letters, digits and hyphens`);
385202
384974
  return project3;
385203
384975
  }
384976
+ async function openConnectorRun(context, command5) {
384977
+ const person4 = (await context.openPerson(command5)).session;
384978
+ return { ...await context.open(command5), person: person4 };
384979
+ }
385204
384980
  function registerSetupCommands(program2, context) {
385205
384981
  const project3 = program2.command("project").description("AgentX projects");
385206
384982
  withRegion(project3.command("add").description("register a new project from a repository the GitHub App sees, on EC2 workers")).option("--repository <owner/name>", "the repository").option("--project-name <name>", "the project's name (default: the repository's)").option("--setup-command <command>", 'the setup command, or "" for none').option("--test-command <command>", 'the test command, or "" for none').option("--no-browser", "when the GitHub App cannot see the repository yet, print the page where it is added instead of opening it").action(async (options, command5) => {
@@ -385219,13 +384995,6 @@ function registerSetupCommands(program2, context) {
385219
384995
  repositoryAccess: { settingsUrl: access10.settingsUrl, ...wait2 === void 0 ? {} : { wait: wait2 } }
385220
384996
  });
385221
384997
  run2.print(result4, `Registered project ${result4.name} (revision ${result4.revision}); file ${result4.file}
385222
- `);
385223
- });
385224
- withRegion(project3.command("setup-approve").description("propose the setup of a project registered from this machine again and approve or decline it (pins the installation's AI navigation route when approved)")).requiredOption("--project-name <name>", "the registered project's name").action(async (options, command5) => {
385225
- const run2 = await context.open(command5);
385226
- const result4 = await reapproveProjectSetup({ env: run2.env, session: run2.session, prompter: run2.prompter, write: run2.write, services: run2.services, projectName: options.projectName });
385227
- run2.print(result4, result4.decision === "approve" ? `Approved the setup of ${result4.name}; revision ${result4.revision}${result4.modelRouteRevision === null ? ", no AI navigation route" : `, AI navigation route ${result4.modelRouteRevision}`}; file ${result4.file}
385228
- ` : `Declined the setup of ${result4.name}; revision ${result4.revision} unchanged
385229
384998
  `);
385230
384999
  });
385231
385000
  const modelCheck = project3.command("model-check").description("check which AI navigation models this account can use, and prove one with a driving test");
@@ -385295,37 +385064,37 @@ function registerSetupCommands(program2, context) {
385295
385064
  const connectorAdd = connector.command("add").description("add a connector to a project");
385296
385065
  withRegion(connectorAdd.command("linear")).description("add Linear to a project: guide, key, test read, team, new revision").option("--linear-key-file <path>", "file holding the Linear API key").option("--linear-key-env <NAME>", "environment variable holding the Linear API key").option("--linear-team <id or key>", "the team the project may use").action(async (options, command5) => {
385297
385066
  const projectName = projectOption(command5, "the project to connect Linear to");
385298
- const run2 = await context.open(command5);
385067
+ const run2 = await openConnectorRun(context, command5);
385299
385068
  const flags = definedEntries({
385300
385069
  linearTeam: options.linearTeam,
385301
385070
  linearKey: secretSource(options.linearKeyFile, options.linearKeyEnv)
385302
385071
  });
385303
- const result4 = await addLinear({ env: run2.env, session: run2.session, projectName, secrets: run2.secrets, prompter: run2.prompter, processEnv: process.env, write: run2.write, services: run2.services, flags });
385072
+ const result4 = await addLinear({ env: run2.env, session: run2.session, person: run2.person, projectName, secrets: run2.secrets, prompter: run2.prompter, processEnv: process.env, write: run2.write, services: run2.services, flags });
385304
385073
  run2.print(result4, `Linear connected to ${projectName} (revision ${result4.revision})
385305
385074
  `);
385306
385075
  });
385307
385076
  withRegion(connectorAdd.command("jira")).description("add Jira to a project: guide, service account token, project check, new revision").option("--jira-site <site>", "the <site> in <site>.atlassian.net").option("--jira-project <key>", "the Jira project key").option("--jira-token-file <path>", "file holding the API token").option("--jira-token-env <NAME>", "environment variable holding the API token").action(async (options, command5) => {
385308
385077
  const projectName = projectOption(command5, "the project to connect Jira to");
385309
- const run2 = await context.open(command5);
385078
+ const run2 = await openConnectorRun(context, command5);
385310
385079
  const flags = definedEntries({
385311
385080
  jiraSite: options.jiraSite,
385312
385081
  jiraProject: options.jiraProject,
385313
385082
  jiraToken: secretSource(options.jiraTokenFile, options.jiraTokenEnv)
385314
385083
  });
385315
- const result4 = await addJira({ env: run2.env, session: run2.session, projectName, secrets: run2.secrets, prompter: run2.prompter, processEnv: process.env, write: run2.write, services: run2.services, flags });
385084
+ const result4 = await addJira({ env: run2.env, session: run2.session, person: run2.person, projectName, secrets: run2.secrets, prompter: run2.prompter, processEnv: process.env, write: run2.write, services: run2.services, flags });
385316
385085
  run2.print(result4, `Jira connected to ${projectName} (revision ${result4.revision})${result4.warning === void 0 ? "" : ", with the warning above"}
385317
385086
  `);
385318
385087
  });
385319
385088
  withRegion(connectorAdd.command("asana")).description("add Asana to a project: guide, app client, the bot user's sign-in (no browser opened here), project check, new revision").option("--asana-client-id <id>", "the Asana MCP app's Client ID").option("--asana-client-secret-file <path>", "file holding the app's Client secret").option("--asana-client-secret-env <NAME>", "environment variable holding the app's Client secret").option("--asana-bot-email <email>", "the bot user's email; a sign-in by any other account is refused").option("--asana-project <gid>", "the Asana project's GID").action(async (options, command5) => {
385320
385089
  const projectName = projectOption(command5, "the project to connect Asana to");
385321
- const run2 = await context.open(command5);
385090
+ const run2 = await openConnectorRun(context, command5);
385322
385091
  const flags = definedEntries({
385323
385092
  asanaClientId: options.asanaClientId,
385324
385093
  asanaClientSecret: secretSource(options.asanaClientSecretFile, options.asanaClientSecretEnv),
385325
385094
  asanaBotEmail: options.asanaBotEmail,
385326
385095
  asanaProject: options.asanaProject
385327
385096
  });
385328
- const result4 = await addAsana({ env: run2.env, session: run2.session, projectName, secrets: run2.secrets, prompter: run2.prompter, processEnv: process.env, write: run2.write, services: run2.services, flags });
385097
+ const result4 = await addAsana({ env: run2.env, session: run2.session, person: run2.person, projectName, secrets: run2.secrets, prompter: run2.prompter, processEnv: process.env, write: run2.write, services: run2.services, flags });
385329
385098
  run2.print(result4, `Asana connected to ${projectName} (revision ${result4.revision})
385330
385099
  `);
385331
385100
  });
@@ -385333,7 +385102,7 @@ function registerSetupCommands(program2, context) {
385333
385102
  const projectName = projectOption(command5, "the project to connect the MCP server to");
385334
385103
  const authKind = options.auth === "key" || options.auth === "oauth" ? options.auth : void 0;
385335
385104
  if (options.auth !== void 0 && authKind === void 0) throw agentXError("CONFIG_INVALID", `--auth ${options.auth} must be key or oauth`);
385336
- const run2 = await context.open(command5);
385105
+ const run2 = await openConnectorRun(context, command5);
385337
385106
  const flags = definedEntries({
385338
385107
  endpoint: options.endpoint,
385339
385108
  name: options.name,
@@ -385352,7 +385121,7 @@ function registerSetupCommands(program2, context) {
385352
385121
  acknowledgeUnscopedWrites: options.acknowledgeUnscopedWrites,
385353
385122
  configFile: options.configFile
385354
385123
  });
385355
- const result4 = await addMcp({ env: run2.env, session: run2.session, projectName, secrets: run2.secrets, prompter: run2.prompter, processEnv: process.env, write: run2.write, services: run2.services, flags });
385124
+ const result4 = await addMcp({ env: run2.env, session: run2.session, person: run2.person, projectName, secrets: run2.secrets, prompter: run2.prompter, processEnv: process.env, write: run2.write, services: run2.services, flags });
385356
385125
  run2.print(result4, `${result4.name} connected to ${projectName} with ${result4.tools} tools (revision ${result4.revision})
385357
385126
  `);
385358
385127
  });
@@ -388995,7 +388764,7 @@ function parseComment(body) {
388995
388764
  }
388996
388765
 
388997
388766
  // packages/cli/src/loop/exit-checks.ts
388998
- import { createHash as createHash38 } from "node:crypto";
388767
+ import { createHash as createHash37 } from "node:crypto";
388999
388768
  import { readFile as readFile25 } from "node:fs/promises";
389000
388769
  import { join as join27 } from "node:path";
389001
388770
 
@@ -389489,7 +389258,7 @@ async function readArtifact(worktree, issue2, artifact2) {
389489
389258
  return readFile25(join27(worktree, artifactPath(issue2, artifact2)), "utf8").catch(() => void 0);
389490
389259
  }
389491
389260
  function artifactDigest(text11) {
389492
- return createHash38("sha256").update(text11).digest("hex");
389261
+ return createHash37("sha256").update(text11).digest("hex");
389493
389262
  }
389494
389263
  function missingSections(text11, required4) {
389495
389264
  const sections2 = /* @__PURE__ */ new Map();
@@ -391481,7 +391250,7 @@ function createCliProgram(dependencies = {}) {
391481
391250
  return stored !== void 0 && stored.expiresAt > Date.now() ? stored : void 0;
391482
391251
  }
391483
391252
  const developerSession = () => ({ home, tokenStore: services.tokenStore, fetch: services.fetchImplementation });
391484
- const program2 = new Command2().name(CLI_COMMAND_NAME).description("Rovara Code: sign in, deploy and administer your coding-agent workspace; hand off tasks from your coding tool or Slack").version(CLI_VERSION).option("--project <project-name>", "select a locally configured AgentX project").option("--config-dir <directory>", "project configuration directory", join33(homedir5(), ".agentx/projects")).option("--deployment-file <path>", "AgentX deployment settings; defaults to this environment's local cache, or, for production, ~/.agentx/deployment.yaml").option("--env <name>", "AgentX environment", DEFAULT_ENVIRONMENT).option("--allow-loopback", "allow loopback HTTP endpoints for local testing only", false).option("--accept-unchecked-model <reason>", "register a project whose default model failed its check anyway (project add, setup-approve, connector add, admin project register); the reason is recorded with the revision").option("--json", "emit stable machine-readable output", false).addHelpText("after", `
391253
+ const program2 = new Command2().name(CLI_COMMAND_NAME).description("Rovara Code: sign in, deploy and administer your coding-agent workspace; hand off tasks from your coding tool or Slack").version(CLI_VERSION).option("--project <project-name>", "select a locally configured AgentX project").option("--config-dir <directory>", "project configuration directory", join33(homedir5(), ".agentx/projects")).option("--deployment-file <path>", "AgentX deployment settings; defaults to this environment's local cache, or, for production, ~/.agentx/deployment.yaml").option("--env <name>", "AgentX environment", DEFAULT_ENVIRONMENT).option("--allow-loopback", "allow loopback HTTP endpoints for local testing only", false).option("--accept-unchecked-model <reason>", "register a project whose default model failed its check anyway (project add, connector add, admin project register); the reason is recorded with the revision").option("--json", "emit stable machine-readable output", false).addHelpText("after", `
391485
391254
  ${ROOT_HELP_DOCS_LINES.join("\n")}`);
391486
391255
  program2.hook("preAction", (_program, actionCommand) => {
391487
391256
  const { env: env3 } = actionCommand.optsWithGlobals();
@@ -391681,16 +391450,8 @@ ${ROOT_HELP_DOCS_LINES.join("\n")}`);
391681
391450
  });
391682
391451
  const admin = program2.command("admin").description("administrator workflows");
391683
391452
  const adminProject = admin.command("project").description("administer registered projects");
391684
- adminProject.command("register").description("register an immutable project revision and trusted runtime binding").requiredOption("--file <path>", "project YAML file").option("--deployment-mode <mode>", "ec2-ebs", "ec2-ebs").option("--launch-template-id <id>", "EC2 worker launch template (ec2-ebs), the foundation's Ec2WorkerLaunchTemplateId").option("--subnets <pairs>", "availabilityZone=subnetId pairs, comma-separated (ec2-ebs), the foundation's Ec2WorkerSubnets").option("--volume-size-gib <size>", "workspace volume size in GiB (ec2-ebs)", "20").option("--volume-type <type>", "workspace volume type (ec2-ebs)", "gp3").option("--take-ownership", "register a revision of an existing project you do not administer, becoming its administrator; needs --ownership-reason and is recorded").option("--ownership-reason <why>", "why you are taking the project over (with --take-ownership); recorded with your identity and the time").option("--region <region>", "AWS region of the environment, to read its settings for the project models' check; defaults to your AWS configuration").action(async (options, command5) => {
391453
+ adminProject.command("register").description("register a project revision from its YAML file, as you (signed in with rovara login), in your company; it runs on this install's own EC2 workers").requiredOption("--file <path>", "project YAML file").addOption(new Option2("--deployment-mode <mode>").hideHelp()).addOption(new Option2("--launch-template-id <id>").hideHelp()).addOption(new Option2("--subnets <pairs>").hideHelp()).addOption(new Option2("--volume-size-gib <size>").hideHelp()).addOption(new Option2("--volume-type <type>").hideHelp()).option("--region <region>", "AWS region of the environment, to read its settings for the project models' check; defaults to your AWS configuration").action(async (options, command5) => {
391685
391454
  const globals = globalOptions2(command5);
391686
- if (options.takeOwnership === true && (options.ownershipReason === void 0 || options.ownershipReason.trim() === "")) {
391687
- throw agentXError("CONFIG_INVALID", "--take-ownership needs --ownership-reason <why>; the takeover is recorded with who took the project over, when, and why");
391688
- }
391689
- if (options.takeOwnership !== true && options.ownershipReason !== void 0) {
391690
- throw agentXError("CONFIG_INVALID", "--ownership-reason only goes with --take-ownership; add it only if you mean to take the project over");
391691
- }
391692
- const deploymentMode = WorkspaceDeploymentModeSchema.parse(options.deploymentMode);
391693
- const runtimeBinding = cliRuntimeBinding(deploymentMode, options);
391694
391455
  const parsedDefinition = await projectFromFile(options.file, globals.allowLoopback);
391695
391456
  const modelChecked = await checkModelsForRegistration({
391696
391457
  definition: parsedDefinition,
@@ -391700,23 +391461,13 @@ ${ROOT_HELP_DOCS_LINES.join("\n")}`);
391700
391461
  acceptUncheckedModel: globals.acceptUncheckedModel
391701
391462
  });
391702
391463
  const definition = modelChecked.definition;
391703
- const { settings, accessToken } = await authenticate(globals, services.tokenStore);
391704
- const result4 = await registerProject({
391705
- controlPlaneUrl: settings.controlPlaneUrl,
391706
- accessToken,
391707
- definition,
391708
- runtimeBinding,
391709
- ...options.takeOwnership === true ? { takeOwnership: { reason: options.ownershipReason } } : {}
391710
- }, services.fetchImplementation);
391711
- if (result4?.ownershipTakenOver === true) {
391712
- services.stderr.write(`Warning: you took over project ${definition.name}: you are now one of its administrators, and the takeover is recorded with your identity, the time and your reason.
391713
- `);
391714
- }
391464
+ const signedIn = await developerAccessToken(developerSession(), developerEnv(command5));
391465
+ const result4 = await registerProject({ controlPlaneUrl: signedIn.entry.url, accessToken: signedIn.accessToken, definition }, services.fetchImplementation);
391715
391466
  try {
391716
391467
  const enrollment = await recordRegisteredLoopEnrollment({
391717
391468
  home,
391718
391469
  env: globals.env,
391719
- controlPlaneUrl: settings.controlPlaneUrl,
391470
+ controlPlaneUrl: signedIn.entry.url,
391720
391471
  definition,
391721
391472
  response: result4,
391722
391473
  ...dependencies.loop?.exec === void 0 ? {} : { exec: dependencies.loop.exec }
@@ -391771,7 +391522,7 @@ ${ROOT_HELP_DOCS_LINES.join("\n")}`);
391771
391522
  return (question) => askToApply(question, { input: stdin, output: output2, signals: process });
391772
391523
  };
391773
391524
  for (const action of ["grant", "revoke"]) {
391774
- adminProject.command(action).description(action === "grant" ? "let a developer hand tasks to a project from an AI tool: shows the change and asks first" : "remove a developer's granted access to a project: shows the change and asks first").option("--project <name>", "the project's name (required)").option("--developer <who>", "a Slack user ID such as U0123456789, the email they signed in with, or a developer ID (required)").option("--yes", "apply without asking; the change is still printed", false).action(async (options, command5) => {
391525
+ adminProject.command(action).description(action === "grant" ? "let a person hand tasks to a project from an AI tool, as you (signed in with rovara login): shows the change and asks first" : "take a person's access to a project away, as you (signed in with rovara login): shows the change and asks first").option("--project <name>", "the project's name (required)").option("--developer <who>", "a Slack user ID such as U0123456789, a developer ID, or the email or name of someone in your company (required)").option("--yes", "apply without asking; the change is still printed", false).action(async (options, command5) => {
391775
391526
  const globals = globalOptions2(command5);
391776
391527
  const projectName = options.project ?? globals.project;
391777
391528
  if (projectName === void 0) throw agentXError("CONFIG_INVALID", `--project is required: name the project, such as agentx admin project ${action} --project payments --developer U0123456789`);
@@ -391779,26 +391530,22 @@ ${ROOT_HELP_DOCS_LINES.join("\n")}`);
391779
391530
  if (!project3.success) throw agentXError("CONFIG_INVALID", "--project must be a project name: a lowercase letter, then up to 62 lowercase letters, digits or hyphens");
391780
391531
  const developer = options.developer?.trim();
391781
391532
  if (developer === void 0 || developer === "") {
391782
- throw agentXError("CONFIG_INVALID", "--developer is required: a Slack user ID such as U0123456789, the email they signed in to AgentX with, or a developer ID");
391533
+ throw agentXError("CONFIG_INVALID", "--developer is required: a Slack user ID such as U0123456789, a developer ID, or the email or name of someone in your company");
391783
391534
  }
391784
391535
  if (developer.length > 254) {
391785
- throw agentXError("CONFIG_INVALID", "--developer must be at most 254 characters; name them by Slack user ID, the email they signed in with, or developer ID");
391536
+ throw agentXError("CONFIG_INVALID", "--developer must be at most 254 characters; name them by Slack user ID, developer ID, or the email they signed in with");
391786
391537
  }
391787
391538
  const confirm = changeConfirmer(options.yes);
391788
- const { settings, accessToken } = await authenticate(globals, services.tokenStore);
391789
- const result4 = await runCliChange({
391790
- controlPlaneUrl: settings.controlPlaneUrl,
391791
- accessToken,
391792
- cliVersion: CLI_VERSION,
391793
- change: { kind: action === "grant" ? "grant_project_access" : "revoke_project_access", project: project3.data, developer },
391794
- // The effect is already printed above the prompt.
391795
- confirm: () => confirm("Apply this change?"),
391796
- write: (line21) => {
391539
+ const answer2 = await projectAccessChange(
391540
+ developerSession(),
391541
+ developerEnv(command5),
391542
+ { action, project: project3.data, developer },
391543
+ { tell: (line21) => {
391797
391544
  services.stderr.write(`${line21}
391798
391545
  `);
391799
- }
391800
- }, services.fetchImplementation);
391801
- services.stdout.write(formatSuccess({ outcome: result4.outcome, changeId: result4.change.changeId }, globals.json));
391546
+ }, confirm }
391547
+ );
391548
+ services.stdout.write(globals.json ? formatSuccess({ env: answer2.env, url: answer2.url, ...answer2.data }, true) : answer2.text);
391802
391549
  });
391803
391550
  }
391804
391551
  async function applySignInClient(command5, clientId, build2, secret, options) {
@@ -391929,12 +391676,6 @@ ${list3.invites.length === 0 ? "No invite codes.\n" : `${list3.invites.map(descr
391929
391676
  services.stdout.write(formatSuccess({ outcome: result4.outcome, changeId: result4.change.changeId, selfServe: state3 === "on" ? "open" : "closed" }, globals.json));
391930
391677
  });
391931
391678
  const adminWorkspace = admin.command("workspace").description("administer AgentX workspaces");
391932
- adminWorkspace.command("list").description("list workspaces with their Slack or developer owner identity and available name").action(async (_options, command5) => {
391933
- const globals = globalOptions2(command5);
391934
- const { settings, accessToken } = await authenticate(globals, services.tokenStore);
391935
- const result4 = await listAdminWorkspaces({ controlPlaneUrl: settings.controlPlaneUrl, accessToken }, services.fetchImplementation);
391936
- services.stdout.write(formatSuccess(result4, globals.json));
391937
- });
391938
391679
  adminWorkspace.command("cancel").description("cancel the workspace's running coding task (its conversation keeps what finished before), or stop a project's setup check that is stuck: its workspace is closed and its machine released").requiredOption("--workspace <workspace-id>", "workspace whose task to cancel").action(async (options, command5) => {
391939
391680
  const globals = globalOptions2(command5);
391940
391681
  const { settings, accessToken } = await authenticate(globals, services.tokenStore);
@@ -391947,18 +391688,6 @@ ${list3.invites.length === 0 ? "No invite codes.\n" : `${list3.invites.map(descr
391947
391688
  const plain5 = finished === "CANCELLED" ? "The task was already cancelled." : typeof finished === "string" ? `The task had already finished as ${finished}, so nothing was cancelled.` : result4;
391948
391689
  services.stdout.write(formatSuccess(globals.json ? result4 : plain5, globals.json));
391949
391690
  });
391950
- const adminSlack = admin.command("slack").description("unbind Slack channels from projects");
391951
- adminSlack.command("unbind").description("remove a Slack channel binding; existing thread workspaces are kept").requiredOption("--team <team-id>", "Slack team ID").requiredOption("--channel <channel-id>", "Slack channel ID").action(async (options, command5) => {
391952
- const globals = globalOptions2(command5);
391953
- const { settings, accessToken } = await authenticate(globals, services.tokenStore);
391954
- const result4 = await unbindSlackChannel({
391955
- controlPlaneUrl: settings.controlPlaneUrl,
391956
- accessToken,
391957
- teamId: options.team,
391958
- channelId: options.channel
391959
- }, services.fetchImplementation);
391960
- services.stdout.write(formatSuccess(result4, globals.json));
391961
- });
391962
391691
  const adminCredential = admin.command("credential").description("register connector credentials stored in Secrets Manager under agentx/connectors/ or agentx/<env>/connectors/");
391963
391692
  adminCredential.command("register").description("register or replace a credential reference; the secret must already exist").requiredOption("--ref <reference>", "credential reference used by connectors' credentialRef").requiredOption("--type <type>", "static-secret, oauth-client-credentials or oauth-refresh-token").requiredOption("--secret <name>", "Secrets Manager secret name, agentx/connectors/<name> or agentx/<env>/connectors/<name>").option("--host <host>", "the one MCP host this credential may be sent to, such as mcp.sentry.dev; required by a generic mcp connector").option("--token-url <url>", "an OAuth credential's token endpoint, for a generic mcp connector").option("--resource <url>", "the RFC 8707 resource an OAuth credential's tokens are for, for a generic mcp connector").action(async (options, command5) => {
391964
391693
  const globals = globalOptions2(command5);