@preplabsai/rovara-code 0.5.20 → 0.5.22

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 +662 -1086
  2. package/package.json +1 -1
@@ -25797,6 +25797,9 @@ var init_routes = __esm({
25797
25797
  { method: "GET", path: "/v1/dev/tasks/{taskId}/readers", requires: "tasks:share" },
25798
25798
  { method: "PUT", path: "/v1/dev/tasks/{taskId}/readers/{developerId}", requires: "tasks:share" },
25799
25799
  { method: "DELETE", path: "/v1/dev/tasks/{taskId}/readers/{developerId}", requires: "tasks:share" },
25800
+ // #1673: switch a shared task between view only and continue (`rovara admin task share-mode`): a live owner or admin of the task's company, or the project's administrator there.
25801
+ // Full access only, like the other company admin rows; anyone else gets a missing task's answer.
25802
+ { method: "POST", path: "/v1/dev/tasks/{taskId}/share-mode", requires: "full" },
25800
25803
  // Decisions: approve a plan or request changes; decide on the pull-request feedback proposal.
25801
25804
  { method: "POST", path: "/v1/dev/tasks/{taskId}/workflow/decision", requires: "decisions:decide" },
25802
25805
  { method: "POST", path: "/v1/dev/tasks/{taskId}/workflow/feedback-decision", requires: "decisions:decide" },
@@ -52426,7 +52429,7 @@ var init_e2e_view_node = __esm({
52426
52429
  });
52427
52430
 
52428
52431
  // packages/contracts/dist/plan-quality.js
52429
- var PLAN_QUALITY_CODES, PLAN_QUALITY_LINTS, PLAN_QUALITY_TARGET_REASONS, FindingIds, PlanQualityFindingSchema, TARGET_REASON_SENTENCES;
52432
+ var PLAN_QUALITY_CODES, PLAN_QUALITY_LINTS, PLAN_QUALITY_TARGET_REASONS, FindingIds, PlanQualityFindingSchema, UPDATE_SETUP, TARGET_REASON_SENTENCES;
52430
52433
  var init_plan_quality = __esm({
52431
52434
  "packages/contracts/dist/plan-quality.js"() {
52432
52435
  "use strict";
@@ -52505,14 +52508,15 @@ var init_plan_quality = __esm({
52505
52508
  /** For the planner's next prompt: one line from plan IDs and fixed text. */
52506
52509
  plannerLine: external_exports.string().min(1).max(1e3)
52507
52510
  }).strict();
52511
+ UPDATE_SETUP = "A company owner or admin can fix this on the project's Browser testing page. Then close and restart the task.";
52508
52512
  TARGET_REASON_SENTENCES = {
52509
- "runtime-unavailable": "its runtime is not set up for this project revision. Run project setup-approve, then close and restart the task.",
52510
- "no-launch-recipe": "the project has no recipe that starts it. Run project setup-approve, then close and restart the task.",
52511
- "needs-project-contract": "its test accounts are not described by a project contract. Run project setup-approve, then close and restart the task.",
52513
+ "runtime-unavailable": `its runtime is not set up for this project revision. ${UPDATE_SETUP}`,
52514
+ "no-launch-recipe": `the project has no recipe that starts it. ${UPDATE_SETUP}`,
52515
+ "needs-project-contract": `its test accounts are not described by a project contract. ${UPDATE_SETUP}`,
52512
52516
  "runtime-not-ready": "its runtime is not ready now. Wait for the runtime to be qualified, then close and restart the task.",
52513
52517
  "no-source-identity": "its application has no package or project file that names it. Add one, then close and restart the task.",
52514
- "no-account-definition": "no usable test account is registered for it. Run project setup-approve, then close and restart the task.",
52515
- "not-offered": "this project revision does not offer it. Run project setup-approve, then close and restart the task.",
52518
+ "no-account-definition": `no usable test account is registered for it. ${UPDATE_SETUP}`,
52519
+ "not-offered": `this project revision does not offer it. ${UPDATE_SETUP}`,
52516
52520
  // BROWSER-SKIP-HONESTY: the whole sentence is the fixed words (one table: browser-runner-words.ts), so it is said the same way on every surface.
52517
52521
  "no-browser-runner": BROWSER_RUNNER_WORDS.planWillNotRun
52518
52522
  };
@@ -64900,7 +64904,7 @@ var init_plugin_points = __esm({
64900
64904
  }).strict();
64901
64905
  PluginConfigSchema = external_exports.object({
64902
64906
  version: external_exports.literal(PLUGIN_CONFIG_VERSION),
64903
- /** The company Code runs as (decision 45.6). Absent: the implicit company. It has the shape of an organization id (`org_` and 20 characters), because plug-in calls carry it as their scope (`HostScope`). */
64907
+ /** The company Code runs as (decision 45.6). Loading a config that names none is refused (#1650). It has the shape of an organization id (`org_` and 20 characters), because plug-in calls carry it as their scope (`HostScope`). */
64904
64908
  companyId: external_exports.string().regex(/^org_[0-9a-z]{20}$/, "a company id looks like org_ and 20 lower-case letters or digits (the same shape a hosted install uses; code-host and tracker calls are scoped by it)").optional(),
64905
64909
  /**
64906
64910
  * Port lane L11 (laptop only, owner-set): a worker may be given the owner's own code-host token even when that token reaches every repository its owner can (a classic token, the GitHub CLI's).
@@ -100357,7 +100361,7 @@ var require_dist_cjs16 = __commonJS({
100357
100361
  var { setCredentialFeature: setCredentialFeature2 } = (init_client3(), __toCommonJS(client_exports2));
100358
100362
  var { CredentialsProviderError: CredentialsProviderError2, parseKnownFiles: parseKnownFiles2, getProfileName: getProfileName2 } = (init_config2(), __toCommonJS(config_exports));
100359
100363
  var { HttpRequest: HttpRequest2 } = (init_protocols(), __toCommonJS(protocols_exports));
100360
- var { createHash: createHash39, createPrivateKey, createPublicKey: createPublicKey2, sign: sign3 } = __require("node:crypto");
100364
+ var { createHash: createHash37, createPrivateKey, createPublicKey: createPublicKey2, sign: sign3 } = __require("node:crypto");
100361
100365
  var { promises } = __require("node:fs");
100362
100366
  var { homedir: homedir6 } = __require("node:os");
100363
100367
  var { dirname: dirname13, join: join34 } = __require("node:path");
@@ -100528,7 +100532,7 @@ var require_dist_cjs16 = __commonJS({
100528
100532
  getTokenFilePath() {
100529
100533
  const directory = process.env.AWS_LOGIN_CACHE_DIRECTORY ?? join34(homedir6(), ".aws", "login", "cache");
100530
100534
  const loginSessionBytes = Buffer.from(this.loginSession, "utf8");
100531
- const loginSessionSha256 = createHash39("sha256").update(loginSessionBytes).digest("hex");
100535
+ const loginSessionSha256 = createHash37("sha256").update(loginSessionBytes).digest("hex");
100532
100536
  return join34(directory, `${loginSessionSha256}.json`);
100533
100537
  }
100534
100538
  derToRawSignature(derSignature) {
@@ -295331,7 +295335,7 @@ var require_dist_cjs42 = __commonJS({
295331
295335
  return async () => handler(this.clientCommand);
295332
295336
  }
295333
295337
  };
295334
- var PutCommand4 = class extends DynamoDBDocumentClientCommand {
295338
+ var PutCommand3 = class extends DynamoDBDocumentClientCommand {
295335
295339
  input;
295336
295340
  inputKeyNodes = {
295337
295341
  Item: ALL_VALUES,
@@ -295715,7 +295719,7 @@ var require_dist_cjs42 = __commonJS({
295715
295719
  }
295716
295720
  }
295717
295721
  put(args, optionsOrCb, cb) {
295718
- const command5 = new PutCommand4(args);
295722
+ const command5 = new PutCommand3(args);
295719
295723
  if (typeof optionsOrCb === "function") {
295720
295724
  this.send(command5, optionsOrCb);
295721
295725
  } else if (typeof cb === "function") {
@@ -295816,7 +295820,7 @@ var require_dist_cjs42 = __commonJS({
295816
295820
  exports.ExecuteStatementCommand = ExecuteStatementCommand;
295817
295821
  exports.ExecuteTransactionCommand = ExecuteTransactionCommand;
295818
295822
  exports.GetCommand = GetCommand8;
295819
- exports.PutCommand = PutCommand4;
295823
+ exports.PutCommand = PutCommand3;
295820
295824
  exports.QueryCommand = QueryCommand6;
295821
295825
  exports.ScanCommand = ScanCommand2;
295822
295826
  exports.SearchVectorsCommand = SearchVectorsCommand;
@@ -339656,7 +339660,7 @@ var init_application_build_source = __esm({
339656
339660
  });
339657
339661
 
339658
339662
  // packages/verifier/dist/rovara-http-engine-descriptor.js
339659
- import { createHash as createHash34 } from "node:crypto";
339663
+ import { createHash as createHash32 } from "node:crypto";
339660
339664
  var ROVARA_HTTP_ENGINE_ASSERTION_FIXTURE, ROVARA_HTTP_ENGINE_DESCRIPTOR, ROVARA_HTTP_ENGINE_DIGEST;
339661
339665
  var init_rovara_http_engine_descriptor = __esm({
339662
339666
  "packages/verifier/dist/rovara-http-engine-descriptor.js"() {
@@ -339670,7 +339674,7 @@ var init_rovara_http_engine_descriptor = __esm({
339670
339674
  platform: "api",
339671
339675
  capabilities: Object.freeze([ROVARA_HTTP_ENGINE_ASSERTION_FIXTURE])
339672
339676
  });
339673
- ROVARA_HTTP_ENGINE_DIGEST = createHash34("sha256").update(canonicalJson(ROVARA_HTTP_ENGINE_DESCRIPTOR)).digest("hex");
339677
+ ROVARA_HTTP_ENGINE_DIGEST = createHash32("sha256").update(canonicalJson(ROVARA_HTTP_ENGINE_DESCRIPTOR)).digest("hex");
339674
339678
  }
339675
339679
  });
339676
339680
 
@@ -340462,7 +340466,7 @@ var init_evidence_paths = __esm({
340462
340466
  });
340463
340467
 
340464
340468
  // packages/verifier/dist/application-result-adapter.js
340465
- import { createHash as createHash35 } from "node:crypto";
340469
+ import { createHash as createHash33 } from "node:crypto";
340466
340470
  function e2eApplicationSupervisorEvidenceEntryMax(caseCount) {
340467
340471
  if (!Number.isSafeInteger(caseCount) || caseCount < 1 || caseCount > 64)
340468
340472
  throw new TypeError("supervisor proof case count is outside the admitted bound");
@@ -340955,7 +340959,7 @@ var init_application_result_adapter = __esm({
340955
340959
  if (field4.byteLength > E2E_REPORT_MAX_BYTES || field4.bytesBase64.length !== Math.ceil(field4.byteLength / 3) * 4)
340956
340960
  throw new Error();
340957
340961
  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)
340962
+ if (decoded.toString("base64") !== field4.bytesBase64 || decoded.byteLength !== field4.byteLength || createHash33("sha256").update(decoded).digest("hex") !== field4.sha256)
340959
340963
  throw new Error();
340960
340964
  } catch {
340961
340965
  context.addIssue({ code: "custom", path: ["shards"], message: "private shard bytes are not canonical base64 with the declared size and digest" });
@@ -340979,7 +340983,7 @@ var init_application_result_adapter = __esm({
340979
340983
  if (proof.ref.byteLength > 26214400 || proof.bytesBase64.length !== expectedLength || proof.bytesBase64.length > 35e6)
340980
340984
  throw new Error();
340981
340985
  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))
340986
+ if (bytes5.toString("base64") !== proof.bytesBase64 || bytes5.byteLength !== proof.ref.byteLength || createHash33("sha256").update(bytes5).digest("hex") !== proof.ref.sha256 || proofIds.has(proof.ref.artifactId))
340983
340987
  throw new Error();
340984
340988
  proofIds.add(proof.ref.artifactId);
340985
340989
  proofBytes += bytes5.byteLength;
@@ -341078,7 +341082,7 @@ var init_application_result_adapter = __esm({
341078
341082
  if (new Set(originRows.map((item) => item.componentId)).size !== originRows.length || originRows.some((item) => !sourceDerivedMocks.some((spec) => spec.componentId === item.componentId))) {
341079
341083
  context.addIssue({ code: "custom", path: ["mockOrigins"], message: "mock origins must name each approved mock component at most once" });
341080
341084
  }
341081
- if (createHash35("sha256").update(canonicalJson(sourceDerivedMocks)).digest("hex") !== oracle.binding.mockManifestDigest) {
341085
+ if (createHash33("sha256").update(canonicalJson(sourceDerivedMocks)).digest("hex") !== oracle.binding.mockManifestDigest) {
341082
341086
  context.addIssue({ code: "custom", path: ["expectedMocksByCase"], message: "case mock expectations do not reproduce the admitted mock manifest digest" });
341083
341087
  }
341084
341088
  const componentsByTarget = /* @__PURE__ */ new Map();
@@ -341394,7 +341398,7 @@ var init_install_qualification = __esm({
341394
341398
  });
341395
341399
 
341396
341400
  // packages/verifier/dist/executor/host-registry.js
341397
- import { createHash as createHash36 } from "node:crypto";
341401
+ import { createHash as createHash34 } from "node:crypto";
341398
341402
  var E2E_EXECUTOR_HOST_ENTRY_POINT_ID, E2E_EXECUTOR_HOST_ENTRY_SOURCE, E2E_EXECUTOR_HOST_DESCRIPTOR, registrySchema;
341399
341403
  var init_host_registry = __esm({
341400
341404
  "packages/verifier/dist/executor/host-registry.js"() {
@@ -341405,7 +341409,7 @@ var init_host_registry = __esm({
341405
341409
  `;
341406
341410
  E2E_EXECUTOR_HOST_DESCRIPTOR = Object.freeze({
341407
341411
  entryPointId: E2E_EXECUTOR_HOST_ENTRY_POINT_ID,
341408
- entryPointManifestDigest: createHash36("sha256").update(E2E_EXECUTOR_HOST_ENTRY_SOURCE).digest("hex")
341412
+ entryPointManifestDigest: createHash34("sha256").update(E2E_EXECUTOR_HOST_ENTRY_SOURCE).digest("hex")
341409
341413
  });
341410
341414
  registrySchema = external_exports.object({
341411
341415
  schemaVersion: external_exports.literal("application-cli-host-registry/v1"),
@@ -341556,7 +341560,7 @@ var init_fake_core = __esm({
341556
341560
  });
341557
341561
 
341558
341562
  // packages/verifier/dist/executor/mock-server.js
341559
- import { createHash as createHash37 } from "node:crypto";
341563
+ import { createHash as createHash35 } from "node:crypto";
341560
341564
  function sortKeys2(value) {
341561
341565
  if (Array.isArray(value))
341562
341566
  return value.map(sortKeys2);
@@ -341575,7 +341579,7 @@ var init_mock_server = __esm({
341575
341579
  "use strict";
341576
341580
  init_fake_core();
341577
341581
  MOCK_UNMOCKED_STATUS = 599;
341578
- sha3 = (value) => createHash37("sha256").update(value, "utf8").digest("hex");
341582
+ sha3 = (value) => createHash35("sha256").update(value, "utf8").digest("hex");
341579
341583
  mockResponseDigest = (response) => sha3(canonicalJson2({ status: response.status, body: response.body }));
341580
341584
  MOCK_UNMOCKED_RESPONSE_DIGEST = mockResponseDigest({ status: MOCK_UNMOCKED_STATUS, body: { error: "rovara-unmocked" } });
341581
341585
  }
@@ -358901,26 +358905,19 @@ function cliRuntimeBinding(deploymentMode, options) {
358901
358905
  }
358902
358906
  }
358903
358907
  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
358908
  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"}`, {
358909
+ if (options.runtimeBinding !== void 0) {
358910
+ WorkspaceDeploymentModeSchema.parse(options.runtimeBinding.deploymentMode);
358911
+ Ec2RuntimeBindingSchema.parse(options.runtimeBinding);
358912
+ }
358913
+ const response = await fetchImplementation(`${options.controlPlaneUrl.replace(/\/$/, "")}/v1/dev/projects`, {
358911
358914
  method: "POST",
358912
358915
  headers: {
358913
358916
  authorization: `Bearer ${options.accessToken}`,
358914
358917
  "content-type": "application/json"
358915
358918
  },
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
- })
358919
+ // Asks the control plane to check each connector with its vendor.
358920
+ body: JSON.stringify({ definition, ...options.runtimeBinding === void 0 ? {} : { runtimeBinding: options.runtimeBinding }, preflight: true })
358924
358921
  });
358925
358922
  const { ok: ok2, status, body } = await readJsonResponse(response);
358926
358923
  if (!ok2) {
@@ -358933,53 +358930,492 @@ async function registerProject(options, fetchImplementation = fetch) {
358933
358930
  return body;
358934
358931
  }
358935
358932
 
358936
- // packages/cli/src/admin/slack.ts
358933
+ // packages/cli/src/admin/project-access.ts
358934
+ init_dist2();
358935
+
358936
+ // packages/cli/src/company/people.ts
358937
358937
  init_dist2();
358938
- async function bindSlackChannel(input2, fetchImplementation = fetch) {
358939
- return sendBindingRequest(input2, "PUT", fetchImplementation, JSON.stringify({ projectName: input2.projectName }));
358938
+ import { randomUUID as randomUUID3 } from "node:crypto";
358939
+
358940
+ // packages/cli/src/session/app-request.ts
358941
+ init_dist2();
358942
+
358943
+ // packages/cli/src/output.ts
358944
+ init_dist2();
358945
+
358946
+ // packages/cli/src/stopped.ts
358947
+ init_dist2();
358948
+ var StoppedByOperator = class extends Error {
358949
+ exitCode = 130;
358950
+ constructor(message) {
358951
+ super(message);
358952
+ this.name = "StoppedByOperator";
358953
+ }
358954
+ };
358955
+ function isCtrlCAtPrompt(error64) {
358956
+ for (let current = error64, depth = 0; current instanceof Error && depth < 10; current = current.cause, depth += 1) {
358957
+ if (current.name === "AbortError" && /Ctrl\+C/.test(current.message)) return true;
358958
+ if (current instanceof AgentXError && current.code === "CONFIG_INVALID" && current.message.replace(/^CONFIG_INVALID: /, "") === "cancelled") return true;
358959
+ }
358960
+ return false;
358940
358961
  }
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`);
358962
+
358963
+ // packages/cli/src/output.ts
358964
+ function formatSuccess(data, json3) {
358965
+ if (json3) return `${JSON.stringify({ ok: true, data })}
358966
+ `;
358967
+ return typeof data === "string" ? `${data}
358968
+ ` : `${JSON.stringify(data, null, 2)}
358969
+ `;
358970
+ }
358971
+ var ReportedFailure = class extends Error {
358972
+ constructor(failureCode, message, exitCode = 1) {
358973
+ super(message);
358974
+ this.failureCode = failureCode;
358975
+ this.exitCode = exitCode;
358976
+ this.name = "ReportedFailure";
358977
+ }
358978
+ failureCode;
358979
+ exitCode;
358980
+ };
358981
+ function formatError2(error64, json3) {
358982
+ if (error64 instanceof StoppedByOperator) {
358983
+ return { text: json3 ? `${JSON.stringify({ ok: false, error: { code: "STOPPED", message: error64.message } })}
358984
+ ` : `${error64.message}
358985
+ `, exitCode: error64.exitCode };
358986
+ }
358987
+ if (error64 instanceof ReportedFailure) {
358988
+ return { text: json3 ? `${JSON.stringify({ ok: false, error: { code: error64.failureCode, message: error64.message } })}
358989
+ ` : `${error64.message}
358990
+ `, exitCode: error64.exitCode };
358991
+ }
358992
+ 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" };
358993
+ const text11 = json3 ? `${JSON.stringify({ ok: false, error: normalized })}
358994
+ ` : `AgentX error [${normalized.code}]: ${normalized.message}
358995
+ `;
358996
+ return {
358997
+ text: text11,
358998
+ exitCode: normalized.code === "INTERNAL_ERROR" ? 1 : exitCodeForError(normalized.code)
358999
+ };
358944
359000
  }
358945
- async function unbindSlackChannel(input2, fetchImplementation = fetch) {
358946
- return sendBindingRequest(input2, "DELETE", fetchImplementation);
359001
+ function exitCodeForError(code2) {
359002
+ if (code2 === "CONFIG_INVALID" || code2 === "PROJECT_REVISION_MISMATCH") return 2;
359003
+ if (code2 === "AUTH_REQUIRED") return 3;
359004
+ if (code2 === "FORBIDDEN" || code2 === "NOT_FOUND" || code2 === "CALLBACK_FORBIDDEN") return 4;
359005
+ if (code2 === "WORKSPACE_NOT_READY" || code2 === "WORKSPACE_BUSY") return 5;
359006
+ if (code2 === "RUNTIME_UNAVAILABLE" || code2 === "OPERATION_INTERRUPTED" || code2 === "STALE_FENCE") return 6;
359007
+ return 7;
358947
359008
  }
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 }
359009
+ function plainMessage(error64) {
359010
+ if (error64 instanceof AgentXError) return stripCodePrefix(error64.message, error64.code);
359011
+ return error64 instanceof Error ? error64.message : String(error64);
359012
+ }
359013
+ function stripCodePrefix(message, code2) {
359014
+ const prefix2 = `${code2}: `;
359015
+ return message.startsWith(prefix2) ? message.slice(prefix2.length) : message;
359016
+ }
359017
+
359018
+ // packages/cli/src/developer/session.ts
359019
+ init_dist2();
359020
+ init_dist2();
359021
+ import { chmod as chmod2, mkdir as mkdir3, open as open3, readFile as readFile6, rm as rm2, stat as stat2 } from "node:fs/promises";
359022
+ import { randomUUID as randomUUID2 } from "node:crypto";
359023
+ import { join as join7 } from "node:path";
359024
+
359025
+ // packages/cli/src/developer/config.ts
359026
+ init_dist2();
359027
+ init_dist2();
359028
+ var import_yaml = __toESM(require_dist4(), 1);
359029
+ init_zod();
359030
+ import { chmod, mkdir as mkdir2, open as open2, readFile as readFile5, rename, rm } from "node:fs/promises";
359031
+ import { join as join6 } from "node:path";
359032
+ 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();
359033
+ var ConfigSchema = external_exports.object({ schemaVersion: external_exports.literal(1), default: EnvironmentNameSchema.optional(), environments: external_exports.record(EnvironmentNameSchema, EntrySchema) }).strict();
359034
+ var developerConfigPath = (home) => join6(home, ".agentx", "developer.yaml");
359035
+ var developerTokenKey = (issuer) => tokenStoreKey({ issuer, clientId: AGENTX_CLI_CLIENT_ID, audience: DEVELOPER_TOKEN_AUDIENCE });
359036
+ async function readDeveloperConfig(home) {
359037
+ let text11;
359038
+ try {
359039
+ text11 = await readFile5(developerConfigPath(home), "utf8");
359040
+ } catch (error64) {
359041
+ if (error64.code === "ENOENT") return { environments: {} };
359042
+ throw error64;
359043
+ }
359044
+ let document;
359045
+ try {
359046
+ document = import_yaml.default.parse(text11);
359047
+ } catch {
359048
+ document = void 0;
359049
+ }
359050
+ const parsed = ConfigSchema.safeParse(document);
359051
+ if (!parsed.success) throw agentXError("CONFIG_INVALID", `${developerConfigPath(home)} is invalid; delete it and run agentx login <url> again`);
359052
+ return { environments: parsed.data.environments };
359053
+ }
359054
+ async function write(home, config5) {
359055
+ const path6 = developerConfigPath(home);
359056
+ await mkdir2(join6(home, ".agentx"), { recursive: true, mode: 448 });
359057
+ await chmod(join6(home, ".agentx"), 448);
359058
+ const temp = `${path6}.${process.pid}.tmp`;
359059
+ const handle = await open2(temp, "w", 384);
359060
+ try {
359061
+ await handle.writeFile(import_yaml.default.stringify({ schemaVersion: 1, ...config5 }));
359062
+ } finally {
359063
+ await handle.close();
359064
+ }
359065
+ try {
359066
+ await rename(temp, path6);
359067
+ } catch (error64) {
359068
+ await rm(temp, { force: true });
359069
+ throw error64;
359070
+ }
359071
+ }
359072
+ async function saveDeveloperEnvironment(home, env3, entry) {
359073
+ const config5 = await readDeveloperConfig(home);
359074
+ await write(home, { environments: { ...config5.environments, [env3]: EntrySchema.parse(entry) } });
359075
+ }
359076
+ async function removeDeveloperEnvironment(home, env3) {
359077
+ const config5 = await readDeveloperConfig(home);
359078
+ const { [env3]: _removed, ...rest } = config5.environments;
359079
+ await write(home, { environments: rest });
359080
+ }
359081
+ async function forgetDeveloperSignIn(home, env3, tokenStore) {
359082
+ const entry = (await readDeveloperConfig(home)).environments[env3];
359083
+ if (entry === void 0) return false;
359084
+ await tokenStore.delete(developerTokenKey(entry.issuer));
359085
+ await removeDeveloperEnvironment(home, env3);
359086
+ return true;
359087
+ }
359088
+ async function resolveDeveloperEnvironment(home, env3) {
359089
+ const config5 = await readDeveloperConfig(home);
359090
+ const name3 = env3 ?? DEFAULT_ENVIRONMENT;
359091
+ const entry = config5.environments[name3];
359092
+ if (entry === void 0) {
359093
+ const others = Object.keys(config5.environments).sort();
359094
+ const signIn = `run npx ${CLI_PACKAGE_NAME} login <your AgentX URL>`;
359095
+ const next = others.length === 0 ? signIn : `it is signed in to ${others.join(", ")}: add --env ${others.length === 1 ? others[0] : "<name>"}, or ${signIn}`;
359096
+ throw agentXError("AUTH_REQUIRED", `this computer is not signed in to AgentX environment ${name3}; ${next}`);
359097
+ }
359098
+ return { env: name3, entry };
359099
+ }
359100
+
359101
+ // packages/cli/src/developer/session.ts
359102
+ var EARLY_MS = 6e4;
359103
+ var STALE_LOCK_MS = 3e4;
359104
+ var LOCK_POLL_MS = 50;
359105
+ function serverReason(value, fallback2) {
359106
+ return typeof value === "string" ? sanitizeServerText(value) : fallback2;
359107
+ }
359108
+ async function withRefreshLock(deps, env3, work) {
359109
+ const dir = join7(deps.home, ".agentx", "locks");
359110
+ await mkdir3(dir, { recursive: true, mode: 448 });
359111
+ await chmod2(dir, 448);
359112
+ const path6 = join7(dir, `developer-${env3}.lock`);
359113
+ const owner = `${process.pid}:${randomUUID2()}`;
359114
+ const sleep4 = deps.sleep ?? ((ms) => new Promise((resolve17) => setTimeout(resolve17, ms)));
359115
+ const deadline = Date.now() + (deps.lockWaitMs ?? 15e3);
359116
+ for (; ; ) {
359117
+ try {
359118
+ const handle = await open3(path6, "wx", 384);
359119
+ try {
359120
+ await handle.writeFile(owner);
359121
+ } finally {
359122
+ await handle.close();
359123
+ }
359124
+ break;
359125
+ } catch (error64) {
359126
+ if (error64.code !== "EEXIST") throw error64;
359127
+ const age = await stat2(path6).then((info) => Date.now() - info.mtimeMs, () => 0);
359128
+ if (age > STALE_LOCK_MS) {
359129
+ await rm2(path6, { force: true });
359130
+ continue;
359131
+ }
359132
+ if (Date.now() > deadline) throw agentXError("RUNTIME_UNAVAILABLE", `another agentx process is refreshing your sign-in to ${env3}; try again in a moment`);
359133
+ await sleep4(LOCK_POLL_MS);
358960
359134
  }
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
359135
  }
358967
- if (parsedBody === void 0) throw agentXError("RUNTIME_UNAVAILABLE", "control plane returned an invalid response");
358968
- return parsedBody;
359136
+ try {
359137
+ return await work();
359138
+ } finally {
359139
+ const holder = await readFile6(path6, "utf8").catch(() => void 0);
359140
+ if (holder === owner) await rm2(path6, { force: true });
359141
+ }
359142
+ }
359143
+ async function developerAccessToken(deps, env3, options = {}) {
359144
+ const now = deps.now ?? Date.now;
359145
+ const resolved2 = await resolveDeveloperEnvironment(deps.home, env3);
359146
+ const key = developerTokenKey(resolved2.entry.issuer);
359147
+ const signIn = `run npx ${CLI_PACKAGE_NAME} login ${resolved2.entry.url}`;
359148
+ const fresh = (tokens) => tokens.expiresAt - EARLY_MS > now();
359149
+ const stored = await deps.tokenStore.get(key);
359150
+ if (stored === void 0) throw agentXError("AUTH_REQUIRED", `this computer is not signed in to AgentX environment ${resolved2.env}; ${signIn}`);
359151
+ if (options.force !== true && fresh(stored)) return { ...resolved2, accessToken: stored.accessToken };
359152
+ return withRefreshLock(deps, resolved2.env, async () => {
359153
+ const current = await deps.tokenStore.get(key);
359154
+ const replaced = options.force !== true || current?.accessToken !== stored.accessToken;
359155
+ if (current !== void 0 && fresh(current) && replaced) return { ...resolved2, accessToken: current.accessToken };
359156
+ if (current?.refreshToken === void 0) throw agentXError("AUTH_REQUIRED", `your AgentX sign-in for ${resolved2.env} has ended; ${signIn}`);
359157
+ let response;
359158
+ try {
359159
+ response = await deps.fetch(resolved2.entry.tokenEndpoint, {
359160
+ method: "POST",
359161
+ headers: { "content-type": "application/x-www-form-urlencoded" },
359162
+ body: new URLSearchParams({ grant_type: "refresh_token", client_id: AGENTX_CLI_CLIENT_ID, refresh_token: current.refreshToken }).toString(),
359163
+ signal: AbortSignal.timeout(15e3)
359164
+ });
359165
+ } catch {
359166
+ throw agentXError("RUNTIME_UNAVAILABLE", `could not reach AgentX at ${resolved2.entry.url}; check your connection and try again`);
359167
+ }
359168
+ const body = await response.json().catch(() => ({}));
359169
+ const fields = typeof body === "object" && body !== null ? body : {};
359170
+ const reason2 = serverReason(fields.error_description, "no reason given");
359171
+ if (response.status === 400 && fields.error === "invalid_grant") {
359172
+ await deps.tokenStore.delete(key);
359173
+ throw agentXError("AUTH_REQUIRED", `your AgentX sign-in for ${resolved2.env} has ended (${reason2}); ${signIn}`);
359174
+ }
359175
+ 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"));
359176
+ if (!response.ok) throw agentXError("RUNTIME_UNAVAILABLE", `AgentX could not refresh your sign-in (HTTP ${response.status}); try again`);
359177
+ const parsed = DeveloperTokenResponseSchema.safeParse(body);
359178
+ if (!parsed.success) throw agentXError("RUNTIME_UNAVAILABLE", "AgentX answered the refresh with something unexpected; try again");
359179
+ await deps.tokenStore.set(key, { accessToken: parsed.data.access_token, refreshToken: parsed.data.refresh_token, expiresAt: now() + parsed.data.expires_in * 1e3 });
359180
+ return { ...resolved2, accessToken: parsed.data.access_token };
359181
+ });
359182
+ }
359183
+
359184
+ // packages/cli/src/session/app-request.ts
359185
+ var UNSAFE = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Cs}\p{Co}͏ᅟᅠ⠀ㅤᅠ]/gu;
359186
+ var marker = (character) => `[U+${(character.codePointAt(0) ?? 0).toString(16).toUpperCase().padStart(4, "0")}]`;
359187
+ var MAX_SHOWN = 500;
359188
+ function terminalSafe(value) {
359189
+ const characters = [...String(value).replace(/[\r\n\t]+/g, " ")];
359190
+ const shown2 = characters.length > MAX_SHOWN ? characters.slice(0, MAX_SHOWN) : characters;
359191
+ return shown2.join("").replace(UNSAFE, marker) + (characters.length > MAX_SHOWN ? "...[truncated]" : "");
359192
+ }
359193
+ function jsonSafe(value) {
359194
+ if (typeof value === "string") return value.replace(UNSAFE, (character) => character === "\n" || character === "\r" || character === " " ? character : marker(character));
359195
+ if (Array.isArray(value)) return value.map(jsonSafe);
359196
+ if (value !== null && typeof value === "object") {
359197
+ return Object.fromEntries(Object.entries(value).map(([key, child]) => [jsonSafe(key), jsonSafe(child)]));
359198
+ }
359199
+ return value;
359200
+ }
359201
+ var clean = (text11) => terminalSafe(text11.replace(/agx[rc]_[A-Za-z0-9_-]+/g, "[hidden]"));
359202
+ async function appRequest(deps, env3, path6, options = {}) {
359203
+ const session = await developerAccessToken(deps, env3);
359204
+ let response;
359205
+ try {
359206
+ response = await deps.fetch(`${session.entry.url}${path6}`, {
359207
+ method: options.method ?? "GET",
359208
+ headers: { ...options.headers, authorization: `Bearer ${session.accessToken}`, ...options.body === void 0 ? {} : { "content-type": "application/json" } },
359209
+ ...options.body === void 0 ? {} : { body: JSON.stringify(options.body) },
359210
+ signal: AbortSignal.timeout(3e4)
359211
+ });
359212
+ } catch {
359213
+ throw agentXError("RUNTIME_UNAVAILABLE", `could not reach AgentX at ${session.entry.url}; check your connection and try again`);
359214
+ }
359215
+ const value = await response.json().catch(() => void 0);
359216
+ 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}`);
359217
+ if (!response.ok) {
359218
+ const error64 = typeof value === "object" && value !== null ? value.error : void 0;
359219
+ const message = typeof error64?.message === "string" ? clean(error64.message).trim() : "";
359220
+ if (message === "") throw agentXError("RUNTIME_UNAVAILABLE", `AgentX answered HTTP ${response.status}; try again`);
359221
+ const code2 = AgentXErrorCodeSchema.safeParse(error64?.code);
359222
+ throw new ReportedFailure(code2.success ? code2.data : "REFUSED", message, response.status === 409 || !code2.success ? 1 : exitCodeForError(code2.data));
359223
+ }
359224
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
359225
+ throw agentXError("RUNTIME_UNAVAILABLE", `AgentX answered with something unexpected; try again, or upgrade: npx ${CLI_PACKAGE_NAME}@latest whoami`);
359226
+ }
359227
+ return { env: session.env, url: session.entry.url, status: response.status, body: value };
359228
+ }
359229
+ var result = (answer2, data, text11) => ({ env: answer2.env, url: answer2.url, data: jsonSafe(data), text: text11 });
359230
+ var seg = (id12) => {
359231
+ if (id12 === "." || id12 === "..") throw agentXError("CONFIG_INVALID", "an ID cannot be . or ..");
359232
+ return encodeURIComponent(id12);
359233
+ };
359234
+ var str = (value, fallback2 = "") => typeof value === "string" || typeof value === "number" ? clean(String(value)) : fallback2;
359235
+ var list2 = (value) => Array.isArray(value) ? value.filter((entry) => typeof entry === "object" && entry !== null) : [];
359236
+ var DEVELOPER_ID = /^[a-f0-9]{64}$/;
359237
+ async function developerRef(_deps, _env, who2) {
359238
+ const id12 = who2.trim().toLowerCase();
359239
+ 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");
359240
+ return { developerId: id12, name: `developer ${id12.slice(0, 8)}` };
358969
359241
  }
358970
359242
 
358971
- // packages/cli/src/admin/task-share-mode.ts
358972
- import { randomUUID as randomUUID2 } from "node:crypto";
358973
- async function setTaskShareMode(input2, fetchImplementation = fetch) {
358974
- const response = await fetchImplementation(
358975
- `${input2.controlPlaneUrl.replace(/\/$/, "")}/v1/admin/tasks/${encodeURIComponent(input2.taskId)}/share-mode`,
358976
- {
358977
- method: "POST",
358978
- headers: { authorization: `Bearer ${input2.accessToken}`, "content-type": "application/json" },
358979
- body: JSON.stringify({ requestId: input2.requestId ?? randomUUID2(), shareMode: input2.mode })
359243
+ // packages/cli/src/company/people.ts
359244
+ var MEMBERS_PATH = "/v1/dev/company/members";
359245
+ var MAX_PAGES = 50;
359246
+ var ROLES = ["member", "admin", "owner"];
359247
+ var ROLE_WORDS = { owner: "owner", admin: "administrator", member: "member" };
359248
+ var METHOD_WORDS = { slack: "Slack", oidc: "company sign-in", github: "GitHub" };
359249
+ var pad = (value) => String(value).padStart(2, "0");
359250
+ function localTime(iso7) {
359251
+ const at = new Date(iso7);
359252
+ if (Number.isNaN(at.getTime())) return terminalSafe(iso7);
359253
+ return `${at.getFullYear()}-${pad(at.getMonth() + 1)}-${pad(at.getDate())} ${pad(at.getHours())}:${pad(at.getMinutes())}`;
359254
+ }
359255
+ var day = (iso7) => localTime(iso7).slice(0, 10);
359256
+ var asMember = (value) => {
359257
+ if (typeof value !== "object" || value === null) return void 0;
359258
+ const row2 = value;
359259
+ if (typeof row2.personId !== "string" || typeof row2.role !== "string" || typeof row2.joinedAt !== "string") return void 0;
359260
+ return {
359261
+ personId: row2.personId,
359262
+ role: row2.role,
359263
+ joinedAt: row2.joinedAt,
359264
+ ...typeof row2.name === "string" ? { name: row2.name } : {},
359265
+ ...typeof row2.email === "string" ? { email: row2.email } : {},
359266
+ ...typeof row2.signsInWith === "string" ? { signsInWith: row2.signsInWith } : {},
359267
+ ...typeof row2.revokedAt === "string" ? { revokedAt: row2.revokedAt } : {}
359268
+ };
359269
+ };
359270
+ async function allMembers(deps, env3) {
359271
+ const members2 = [];
359272
+ let cursor2;
359273
+ let answer2;
359274
+ for (let page = 0; page < MAX_PAGES; page += 1) {
359275
+ answer2 = await appRequest(deps, env3, `${MEMBERS_PATH}?limit=100${cursor2 === void 0 ? "" : `&cursor=${encodeURIComponent(cursor2)}`}`);
359276
+ const rows = Array.isArray(answer2.body.members) ? answer2.body.members : [];
359277
+ for (const row2 of rows) {
359278
+ const member2 = asMember(row2);
359279
+ if (member2 !== void 0) members2.push(member2);
358980
359280
  }
359281
+ cursor2 = answer2.body.more === true && typeof answer2.body.cursor === "string" ? answer2.body.cursor : void 0;
359282
+ if (cursor2 === void 0) break;
359283
+ }
359284
+ return { env: answer2.env, url: answer2.url, members: members2, more: cursor2 !== void 0 };
359285
+ }
359286
+ var who = (member2) => {
359287
+ const name3 = member2.name === void 0 ? void 0 : terminalSafe(member2.name);
359288
+ const email4 = member2.email === void 0 ? void 0 : terminalSafe(member2.email);
359289
+ return name3 !== void 0 && email4 !== void 0 ? `${name3} (${email4})` : name3 ?? email4 ?? `person ${member2.personId.slice(0, 12)}`;
359290
+ };
359291
+ function findMember(members2, typed) {
359292
+ const live = members2.filter((member2) => member2.revokedAt === void 0);
359293
+ const key = typed.trim();
359294
+ const lower = key.toLowerCase();
359295
+ const byId = live.filter((member2) => member2.personId === lower);
359296
+ const byEmail = live.filter((member2) => member2.email?.toLowerCase() === lower);
359297
+ const byName = live.filter((member2) => member2.name?.toLowerCase() === lower);
359298
+ const found = byId.length > 0 ? byId : byEmail.length > 0 ? byEmail : byName;
359299
+ if (found.length === 1) return found[0];
359300
+ 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)`);
359301
+ throw agentXError("NOT_FOUND", `no member of your company is ${terminalSafe(key)}; rovara company members lists who is in it`);
359302
+ }
359303
+ async function companyMember(deps, env3, typed) {
359304
+ const member2 = findMember((await allMembers(deps, env3)).members, typed);
359305
+ return { member: member2, who: who(member2) };
359306
+ }
359307
+ async function companyName(deps, env3) {
359308
+ const details = await appRequest(deps, env3, COMPANY_DETAILS_PATH);
359309
+ 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) };
359310
+ }
359311
+ function memberLine(member2) {
359312
+ const parts2 = [` ${who(member2)}`, ROLE_WORDS[member2.role] ?? terminalSafe(member2.role)];
359313
+ if (member2.signsInWith !== void 0) parts2.push(`signs in with ${METHOD_WORDS[member2.signsInWith] ?? terminalSafe(member2.signsInWith)}`);
359314
+ parts2.push(`joined ${day(member2.joinedAt)}`);
359315
+ if (member2.revokedAt !== void 0) parts2.push(`removed ${day(member2.revokedAt)}`);
359316
+ return parts2.join(", ");
359317
+ }
359318
+ async function companyMembers(deps, env3, options) {
359319
+ const listed3 = await allMembers(deps, env3);
359320
+ const shown2 = options.all ? listed3.members : listed3.members.filter((member2) => member2.revokedAt === void 0);
359321
+ const lines = shown2.length === 0 ? ["Your company has no members to show."] : [`${shown2.length} ${shown2.length === 1 ? "member" : "members"}:`, ...shown2.map(memberLine)];
359322
+ if (listed3.more) lines.push(`More members are not shown (the first ${MAX_PAGES * 100}).`);
359323
+ return result(listed3, { members: shown2, more: listed3.more }, `${lines.join("\n")}
359324
+ `);
359325
+ }
359326
+ var declined = (env3, url2) => result({ env: env3, url: url2 }, { applied: false }, "Nothing changed.\n");
359327
+ async function companyRole(deps, env3, typed, role, io) {
359328
+ if (!ROLES.includes(role)) throw agentXError("CONFIG_INVALID", "the role is member, admin or owner");
359329
+ const listed3 = await allMembers(deps, env3);
359330
+ const member2 = findMember(listed3.members, typed);
359331
+ if (member2.role === role) return result(listed3, { applied: false, personId: member2.personId, role }, `${who(member2)} is already ${ROLE_WORDS[role]}.
359332
+ `);
359333
+ const company = await companyName(deps, env3);
359334
+ io.tell(`This changes ${who(member2)}'s role in ${company.name} from ${ROLE_WORDS[member2.role] ?? terminalSafe(member2.role)} to ${ROLE_WORDS[role]}.`);
359335
+ if (!await io.confirm("Apply this change?")) return declined(listed3.env, listed3.url);
359336
+ const answer2 = await appRequest(deps, env3, `${MEMBERS_PATH}/${seg(member2.personId)}/role`, { method: "PUT", body: { role } });
359337
+ return result(answer2, { applied: true, personId: member2.personId, role }, `${who(member2)}'s role in ${company.name} is now ${ROLE_WORDS[role]}.
359338
+ `);
359339
+ }
359340
+ var count4 = (value, one, many) => {
359341
+ const n3 = typeof value === "number" ? value : 0;
359342
+ return `${n3} ${n3 === 1 ? one : many}`;
359343
+ };
359344
+ var names = (value) => Array.isArray(value) ? value.filter((item) => typeof item === "string").map(terminalSafe) : [];
359345
+ var objectOf = (value) => typeof value === "object" && value !== null ? value : {};
359346
+ function removalLines(member2, company, preview, to) {
359347
+ const handOver = objectOf(preview.handOver);
359348
+ const owned = names(preview.ownedProjects), granted = names(preview.projectGrants);
359349
+ 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.`];
359350
+ if (granted.length > 0) lines.push(` Project access they lose: ${granted.join(", ")}.`);
359351
+ 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")}.`);
359352
+ 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.`);
359353
+ if (typeof preview.awaitingTheirDecision === "number" && preview.awaitingTheirDecision > 0) lines.push(` ${count4(preview.awaitingTheirDecision, "task is", "tasks are")} waiting on their decision.`);
359354
+ return lines;
359355
+ }
359356
+ async function companyRemove(deps, env3, typed, options, io) {
359357
+ const listed3 = await allMembers(deps, env3);
359358
+ const member2 = findMember(listed3.members, typed);
359359
+ const successor = options.to === void 0 ? void 0 : findMember(listed3.members, options.to);
359360
+ const preview = (await appRequest(deps, env3, `${MEMBERS_PATH}/${seg(member2.personId)}/removal-preview${successor === void 0 ? "" : `?successorId=${seg(successor.personId)}`}`)).body;
359361
+ if (preview.mayRemove === false) throw agentXError("FORBIDDEN", member2.role === "owner" ? "only an owner can remove an owner" : "you cannot remove this member");
359362
+ const company = await companyName(deps, env3);
359363
+ const named4 = objectOf(preview.successor).name;
359364
+ const to = typeof named4 === "string" ? terminalSafe(named4) : successor !== void 0 ? who(successor) : "you";
359365
+ for (const line21 of removalLines(member2, company.name, preview, to)) io.tell(line21);
359366
+ if (!await io.confirm("Apply this change?")) return declined(listed3.env, listed3.url);
359367
+ const answer2 = await appRequest(deps, env3, `${MEMBERS_PATH}/${seg(member2.personId)}/removal`, {
359368
+ method: "POST",
359369
+ body: { requestId: randomUUID3(), expectedRole: str(preview.role), ...successor === void 0 ? {} : { successorId: successor.personId } }
359370
+ });
359371
+ const moved = objectOf(answer2.body.moved);
359372
+ return result(
359373
+ answer2,
359374
+ { applied: true, personId: member2.personId, ...answer2.body },
359375
+ `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")}.
359376
+ `
358981
359377
  );
358982
- return adminResponseBody(response);
359378
+ }
359379
+
359380
+ // packages/cli/src/admin/project-access.ts
359381
+ var DEVELOPER_ID2 = /^[a-f0-9]{64}$/;
359382
+ async function personNamed(deps, env3, typed) {
359383
+ const value = typed.trim();
359384
+ if (DEVELOPER_ID2.test(value.toLowerCase())) return { ref: value.toLowerCase(), who: `developer ${value.slice(0, 12).toLowerCase()}` };
359385
+ if (SlackUserIdSchema.safeParse(value).success) return { ref: value, who: `Slack user ${value}` };
359386
+ const { member: member2, who: who2 } = await companyMember(deps, env3, value);
359387
+ return { ref: member2.personId, who: who2 };
359388
+ }
359389
+ var OUTCOME_TEXT = {
359390
+ granted: (who2, project3) => `${who2} can now hand tasks to ${project3}.`,
359391
+ already_member: (who2, project3) => `${who2} already had access to ${project3}; nothing changed.`,
359392
+ revoked: (who2, project3) => `${who2} no longer has access to ${project3}.`,
359393
+ not_member: (who2, project3) => `${who2} had no access to ${project3} to take away; nothing changed.`
359394
+ };
359395
+ async function projectAccessChange(deps, env3, input2, io) {
359396
+ const session = await developerAccessToken(deps, env3);
359397
+ const signedIn = { env: session.env, url: session.entry.url };
359398
+ const person4 = await personNamed(deps, env3, input2.developer);
359399
+ 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.`);
359400
+ if (!await io.confirm("Apply this change?")) return result(signedIn, { applied: false }, "Nothing changed.\n");
359401
+ const answer2 = await appRequest(deps, env3, `/v1/dev/client/projects/${seg(input2.project)}/members/${seg(person4.ref)}`, { method: input2.action === "grant" ? "PUT" : "DELETE" });
359402
+ const outcome = str(answer2.body.outcome);
359403
+ const text11 = OUTCOME_TEXT[outcome]?.(person4.who, input2.project) ?? `The project's members changed (${outcome}).`;
359404
+ return result(answer2, { applied: true, project: input2.project, developerId: str(answer2.body.developerId), outcome }, `${text11}
359405
+ `);
359406
+ }
359407
+
359408
+ // packages/cli/src/admin/task-share-mode.ts
359409
+ import { randomUUID as randomUUID4 } from "node:crypto";
359410
+ async function setTaskShareMode(deps, env3, input2) {
359411
+ const answer2 = await appRequest(deps, env3, `/v1/dev/tasks/${seg(input2.taskId)}/share-mode`, {
359412
+ method: "POST",
359413
+ body: { requestId: input2.requestId ?? randomUUID4(), shareMode: input2.mode }
359414
+ });
359415
+ const share = answer2.body.task?.share;
359416
+ const text11 = share?.mode === "continue" ? "is open to the channel (continue)" : input2.mode === "continue" ? "stays view only: its project does not allow continue" : "is view only";
359417
+ return result(answer2, { task: answer2.body.task }, `Task ${input2.taskId} ${text11}.
359418
+ `);
358983
359419
  }
358984
359420
 
358985
359421
  // packages/cli/src/admin/cancel.ts
@@ -359000,10 +359436,10 @@ async function cancelWorkspaceTask(input2, fetchImplementation = fetch) {
359000
359436
 
359001
359437
  // packages/cli/src/admin/changes.ts
359002
359438
  init_dist2();
359003
- import { randomUUID as randomUUID3 } from "node:crypto";
359439
+ import { randomUUID as randomUUID5 } from "node:crypto";
359004
359440
  import { createInterface as createInterface2 } from "node:readline";
359005
359441
  var PAGE_LIMIT = "100";
359006
- var MAX_PAGES = 1e4;
359442
+ var MAX_PAGES2 = 1e4;
359007
359443
  var CHECK_STEP = "run agentx admin changes --since 1h to see how it ended";
359008
359444
  function plain2(text11) {
359009
359445
  let out = "";
@@ -359043,9 +359479,9 @@ function viewOf(value, unreadable) {
359043
359479
  return parsed.data.change;
359044
359480
  }
359045
359481
  async function runCliChange(input2, fetchImplementation = fetch) {
359046
- const traceId = randomUUID3();
359482
+ const traceId = randomUUID5();
359047
359483
  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"),
359484
+ await send(input2, traceId, "POST", "/v1/admin/changes", { requestId: (input2.newId ?? randomUUID5)(), change: input2.change, client: { cliVersion: input2.cliVersion }, methods: ["cli"] }, fetchImplementation, "plan"),
359049
359485
  "AgentX answered with a change this version of the CLI cannot read; nothing was applied. Upgrade the CLI, then ask again"
359050
359486
  );
359051
359487
  const changeId = planned.changeId;
@@ -359093,7 +359529,7 @@ async function runCliChange(input2, fetchImplementation = fetch) {
359093
359529
  throw agentXError("RUNTIME_UNAVAILABLE", `AgentX answered change ${changeId} as ${plain2(applied.status)}, which this CLI does not read as applied; ${CHECK_STEP}`);
359094
359530
  }
359095
359531
  async function recordConfigChange(input2, fetchImplementation = fetch) {
359096
- const traceId = randomUUID3();
359532
+ const traceId = randomUUID5();
359097
359533
  const request = { requestId: input2.requestId, change: input2.change, client: { cliVersion: input2.cliVersion }, ...input2.requestedAt === void 0 ? {} : { requestedAt: input2.requestedAt }, answeredAt: input2.answeredAt };
359098
359534
  const body = await send(input2, traceId, "POST", "/v1/admin/changes/config", request, fetchImplementation, "record");
359099
359535
  const parsed = RecordedChangeResponseWireSchema.safeParse(body);
@@ -359143,14 +359579,14 @@ function kindText(record4) {
359143
359579
  return record4.kind === "set_config" && typeof key === "string" ? `set_config ${key}` : record4.kind;
359144
359580
  }
359145
359581
  async function exportChanges(input2, fetchImplementation = fetch) {
359146
- const traceId = randomUUID3();
359582
+ const traceId = randomUUID5();
359147
359583
  const seen = /* @__PURE__ */ new Set();
359148
359584
  let cursor2;
359149
359585
  let exported = 0;
359150
359586
  let pages = 0;
359151
359587
  do {
359152
359588
  pages += 1;
359153
- if (pages > MAX_PAGES) throw agentXError("RUNTIME_UNAVAILABLE", "change record export did not finish after 10000 pages; try a narrower --since");
359589
+ if (pages > MAX_PAGES2) throw agentXError("RUNTIME_UNAVAILABLE", "change record export did not finish after 10000 pages; try a narrower --since");
359154
359590
  const query = new URLSearchParams({ since: input2.since, limit: PAGE_LIMIT, ...cursor2 === void 0 ? {} : { cursor: cursor2 } });
359155
359591
  const body = await send(input2, traceId, "GET", `/v1/admin/changes?${query.toString()}`, void 0, fetchImplementation, "list");
359156
359592
  const page = AdminChangesResponseWireSchema.safeParse(body);
@@ -359262,7 +359698,7 @@ init_dist2();
359262
359698
  var DURATION = /^(\d{1,4})([mhd])$/;
359263
359699
  var UNIT_MS = { m: 6e4, h: 36e5, d: 864e5 };
359264
359700
  var RETENTION_MS = 30 * UNIT_MS.d;
359265
- var MAX_PAGES2 = 1e4;
359701
+ var MAX_PAGES3 = 1e4;
359266
359702
  function parseSince(value, now = Date.now(), noun = "turn records") {
359267
359703
  const match = DURATION.exec(value.trim());
359268
359704
  if (!match) throw agentXError("CONFIG_INVALID", "--since must be a duration such as 30m, 12h or 7d");
@@ -359280,7 +359716,7 @@ async function exportTurns(input2, fetchImplementation = fetch) {
359280
359716
  let pages = 0;
359281
359717
  do {
359282
359718
  pages += 1;
359283
- if (pages > MAX_PAGES2) throw agentXError("RUNTIME_UNAVAILABLE", "turn record export did not finish after 10000 pages; try a narrower --since");
359719
+ if (pages > MAX_PAGES3) throw agentXError("RUNTIME_UNAVAILABLE", "turn record export did not finish after 10000 pages; try a narrower --since");
359284
359720
  const url2 = new URL(`${input2.controlPlaneUrl.replace(/\/$/, "")}/v1/admin/turns`);
359285
359721
  url2.searchParams.set("since", input2.since);
359286
359722
  if (cursor2 !== void 0) url2.searchParams.set("cursor", cursor2);
@@ -359308,8 +359744,8 @@ async function exportTurns(input2, fetchImplementation = fetch) {
359308
359744
 
359309
359745
  // packages/cli/src/config.ts
359310
359746
  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";
359747
+ var import_yaml2 = __toESM(require_dist4(), 1);
359748
+ import { readFile as readFile7, realpath as realpath2, stat as stat3 } from "node:fs/promises";
359313
359749
  import { isAbsolute as isAbsolute2, relative, resolve as resolve3, sep as sep2 } from "node:path";
359314
359750
  var MAX_CONFIG_BYTES = 1048576;
359315
359751
  async function loadProjectConfig(options) {
@@ -359322,11 +359758,11 @@ async function loadProjectConfig(options) {
359322
359758
  );
359323
359759
  });
359324
359760
  assertContained(configDirectory, canonicalPath);
359325
- const metadata = await stat2(canonicalPath);
359761
+ const metadata = await stat3(canonicalPath);
359326
359762
  if (!metadata.isFile() || metadata.size > MAX_CONFIG_BYTES) {
359327
359763
  throw agentXError("CONFIG_INVALID", "project configuration must be a regular file no larger than 1 MiB");
359328
359764
  }
359329
- const document = import_yaml.default.parseDocument(await readFile5(canonicalPath, "utf8"), { uniqueKeys: true });
359765
+ const document = import_yaml2.default.parseDocument(await readFile7(canonicalPath, "utf8"), { uniqueKeys: true });
359330
359766
  if (document.errors.length > 0) {
359331
359767
  throw agentXError("CONFIG_INVALID", document.errors[0]?.message ?? "project YAML is invalid");
359332
359768
  }
@@ -359380,172 +359816,6 @@ function isNodeError(error64) {
359380
359816
 
359381
359817
  // packages/cli/src/developer/commands.ts
359382
359818
  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
359819
  async function developerGet(deps, env3, path6, schema) {
359550
359820
  return developerRequest(deps, env3, path6, schema);
359551
359821
  }
@@ -359909,147 +360179,8 @@ async function developerLogin(options) {
359909
360179
  // packages/cli/src/developer/sign-ins.ts
359910
360180
  init_dist2();
359911
360181
  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
360182
  var SIGN_INS_PATH = "/v1/dev/me/sign-ins";
360052
- var METHOD_WORDS = { slack: "Slack", oidc: "your company sign-in", github: "GitHub" };
360183
+ var METHOD_WORDS2 = { slack: "Slack", oidc: "your company sign-in", github: "GitHub" };
360053
360184
  var LINKABLE = ["slack", "github"];
360054
360185
  var ENDED = {
360055
360186
  cancelled: "the sign-in was cancelled on the provider's page; nothing was connected",
@@ -360059,12 +360190,12 @@ var ENDED = {
360059
360190
  async function signInsList(deps, env3) {
360060
360191
  const answer2 = await appRequest(deps, env3, SIGN_INS_PATH);
360061
360192
  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)})` : ""}`);
360193
+ 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
360194
  const missing = LINKABLE.filter((method) => !rows.some((row2) => row2.method === method));
360064
360195
  return result(answer2, { signIns: rows }, [
360065
360196
  `You sign in to AgentX environment ${answer2.env} with:`,
360066
360197
  ...lines,
360067
- ...missing.length === 0 ? [] : [`To connect ${missing.map((method) => METHOD_WORDS[method]).join(" or ")} too: rovara signins link ${missing.join("|")}`]
360198
+ ...missing.length === 0 ? [] : [`To connect ${missing.map((method) => METHOD_WORDS2[method]).join(" or ")} too: rovara signins link ${missing.join("|")}`]
360068
360199
  ].join("\n") + "\n");
360069
360200
  }
360070
360201
  async function linkCallback(state3, timeoutMs) {
@@ -360112,15 +360243,15 @@ async function signInsLink(deps, env3, method, options) {
360112
360243
  const linkId = typeof started.body.linkId === "string" ? started.body.linkId : "";
360113
360244
  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
360245
  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}`);
360246
+ options.write(`Opening your browser to sign in with ${METHOD_WORDS2[method]}. If it does not open, open this link: ${authorizeUrl}`);
360116
360247
  await (options.openBrowser ?? openSystemBrowser)(authorizeUrl).catch(() => void 0);
360117
360248
  } else {
360118
- options.write(`Open this link in a browser on this computer and sign in with ${METHOD_WORDS[method]}: ${authorizeUrl}`);
360249
+ options.write(`Open this link in a browser on this computer and sign in with ${METHOD_WORDS2[method]}: ${authorizeUrl}`);
360119
360250
  }
360120
360251
  const back = await callback.answer;
360121
360252
  if (back.linkId !== linkId) throw agentXError("AUTH_REQUIRED", ENDED.failed);
360122
360253
  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.
360254
+ 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
360255
  `);
360125
360256
  } finally {
360126
360257
  callback.close();
@@ -361177,7 +361308,7 @@ init_dist2();
361177
361308
 
361178
361309
  // packages/cli/src/session/commands.ts
361179
361310
  init_dist2();
361180
- import { randomUUID as randomUUID5 } from "node:crypto";
361311
+ import { randomUUID as randomUUID6 } from "node:crypto";
361181
361312
  var TEXT_MAX = 1e4;
361182
361313
  var SAFE_URL = /^https?:\/\/[A-Za-z0-9._~:/?#@!$&'()*+,;=%[\]-]+$/;
361183
361314
  var PAGE_TOKEN_PATH = /^\/s\/[A-Za-z0-9_-]{43}(?:\/|$)/;
@@ -361265,7 +361396,7 @@ ${linkOf(answer2.url, id12)}
361265
361396
  async function sessionSay(deps, env3, id12, kind, text11) {
361266
361397
  if (text11.trim() === "") throw agentXError("CONFIG_INVALID", `give the ${kind === "comment" ? "comment" : "message"} as text`);
361267
361398
  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 } });
361399
+ const answer2 = await appRequest(deps, env3, sessionPath(id12, "/messages"), { method: "POST", body: { requestId: randomUUID6(), kind, text: text11 } });
361269
361400
  const delivery = answer2.body.delivery ?? {};
361270
361401
  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
361402
  return result(answer2, answer2.body, `${fate}
@@ -361273,7 +361404,7 @@ ${linkOf(answer2.url, id12)}
361273
361404
  `);
361274
361405
  }
361275
361406
  async function taskStop(deps, env3, taskId) {
361276
- const answer2 = await appRequest(deps, env3, `/v1/dev/tasks/${seg(taskId)}/cancel`, { method: "POST", body: { requestId: randomUUID5() } });
361407
+ const answer2 = await appRequest(deps, env3, `/v1/dev/tasks/${seg(taskId)}/cancel`, { method: "POST", body: { requestId: randomUUID6() } });
361277
361408
  const task = answer2.body.task;
361278
361409
  if (task === void 0 || typeof task !== "object") throw agentXError("RUNTIME_UNAVAILABLE", UNEXPECTED);
361279
361410
  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 +361413,7 @@ async function taskStop(deps, env3, taskId) {
361282
361413
  }
361283
361414
  async function sessionControl(deps, env3, id12, action) {
361284
361415
  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() } });
361416
+ const answer2 = await appRequest(deps, env3, sessionPath(id12, `/${action}`), { method: "POST", body: { requestId: randomUUID6() } });
361286
361417
  const view2 = answer2.body.session ?? {};
361287
361418
  const fresh = typeof view2.sessionId === "string" && view2.sessionId !== id12;
361288
361419
  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 +361421,7 @@ async function sessionControl(deps, env3, id12, action) {
361290
361421
  `);
361291
361422
  }
361292
361423
  async function sessionTakeOver(deps, env3, id12) {
361293
- const answer2 = await appRequest(deps, env3, sessionPath(id12, "/take-over"), { method: "POST", body: { requestId: randomUUID5() } });
361424
+ const answer2 = await appRequest(deps, env3, sessionPath(id12, "/take-over"), { method: "POST", body: { requestId: randomUUID6() } });
361294
361425
  if (answer2.status !== 202) throw agentXError("RUNTIME_UNAVAILABLE", UNEXPECTED);
361295
361426
  return confirmationOf(answer2);
361296
361427
  }
@@ -361315,7 +361446,7 @@ async function sessionShare(deps, env3, id12, input2) {
361315
361446
  principal = { kind: "member", developerId: member2.developerId };
361316
361447
  who2 = clean(member2.name);
361317
361448
  }
361318
- const answer2 = await appRequest(deps, env3, sessionPath(id12, "/shares"), { method: "PUT", body: { requestId: randomUUID5(), principal, level } });
361449
+ const answer2 = await appRequest(deps, env3, sessionPath(id12, "/shares"), { method: "PUT", body: { requestId: randomUUID6(), principal, level } });
361319
361450
  if (answer2.status === 202 || answer2.body.status === "NEEDS_CONFIRMATION") return confirmationOf(answer2);
361320
361451
  if (answer2.body.share === void 0) throw agentXError("RUNTIME_UNAVAILABLE", UNEXPECTED);
361321
361452
  return result(answer2, answer2.body, `Shared with ${who2} (${LEVEL_WORDS[level]}).
@@ -361333,7 +361464,7 @@ async function sessionStart(deps, env3, input2) {
361333
361464
  const answer2 = await appRequest(deps, env3, "/v1/dev/tasks", {
361334
361465
  method: "POST",
361335
361466
  body: {
361336
- requestId: randomUUID5(),
361467
+ requestId: randomUUID6(),
361337
361468
  project: project3,
361338
361469
  instructions: instructions2,
361339
361470
  client: "agentx-cli",
@@ -361408,7 +361539,7 @@ async function sessionAnswer(deps, env3, ref, input2) {
361408
361539
  const option = question.options.find((candidate) => candidate.id.toLowerCase() === said || candidate.label.trim().toLowerCase() === said);
361409
361540
  return option === void 0 ? { questionId: question.id, text: answer2 } : { questionId: question.id, optionId: option.id };
361410
361541
  });
361411
- const sent = await appRequest(deps, env3, sessionPath(id12, "/answers"), { method: "POST", body: { requestId: randomUUID5(), round, answers } });
361542
+ const sent = await appRequest(deps, env3, sessionPath(id12, "/answers"), { method: "POST", body: { requestId: randomUUID6(), round, answers } });
361412
361543
  const after = sent.body.session ?? {};
361413
361544
  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
361545
  `);
@@ -361561,141 +361692,6 @@ function registerSessionCommands(program2, context) {
361561
361692
  // packages/cli/src/company/commands.ts
361562
361693
  init_dist2();
361563
361694
 
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
361695
  // packages/cli/src/company/invites.ts
361700
361696
  init_dist2();
361701
361697
  init_zod();
@@ -361849,15 +361845,6 @@ function registerPeopleCommands(company, context, print) {
361849
361845
  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
361846
  }
361851
361847
 
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
361848
  // packages/cli/src/deployment.ts
361862
361849
  init_dist2();
361863
361850
  var import_yaml3 = __toESM(require_dist4(), 1);
@@ -368106,7 +368093,7 @@ init_dist2();
368106
368093
  import { realpathSync } from "node:fs";
368107
368094
 
368108
368095
  // packages/cli/src/version.ts
368109
- var RELEASE_VERSION = true ? "0.5.20" : void 0;
368096
+ var RELEASE_VERSION = true ? "0.5.22" : void 0;
368110
368097
  var CLI_VERSION = RELEASE_VERSION ?? "0.1.0";
368111
368098
  function isPrereleaseVersion(version3) {
368112
368099
  return /^\d+\.\d+\.\d+-/.test(version3);
@@ -374312,23 +374299,14 @@ var Membership = external_exports.object({
374312
374299
  });
374313
374300
  var membershipKey = (personId) => ({ pk: `COMPANY_MEMBER#${personId}`, sk: "COMPANY" });
374314
374301
 
374315
- // packages/broker/dist/aws/lambda.js
374316
- init_dist2();
374317
- import { createHash as createHash28 } from "node:crypto";
374318
- function ownerKeyForSubject(issuer, subject) {
374319
- if (!subject || subject.length > 512)
374320
- throw agentXError("CONFIG_INVALID", "owner subject is invalid");
374321
- return createHash28("sha256").update(issuer).update("\0").update(subject).digest("hex");
374322
- }
374323
-
374324
374302
  // packages/broker/dist/developer/store.js
374325
374303
  var import_lib_dynamodb2 = __toESM(require_dist_cjs42(), 1);
374326
374304
  init_dist2();
374327
374305
 
374328
374306
  // packages/broker/dist/developer/tokens.js
374329
- import { createHash as createHash29, createPublicKey, randomBytes as randomBytes10, randomUUID as randomUUID10, timingSafeEqual as timingSafeEqual3 } from "node:crypto";
374307
+ import { createHash as createHash28, createPublicKey, randomBytes as randomBytes10, randomUUID as randomUUID10, timingSafeEqual as timingSafeEqual3 } from "node:crypto";
374330
374308
  function sha256Hex3(value) {
374331
- return createHash29("sha256").update(value).digest("hex");
374309
+ return createHash28("sha256").update(value).digest("hex");
374332
374310
  }
374333
374311
 
374334
374312
  // packages/broker/dist/developer/store.js
@@ -374492,7 +374470,7 @@ var CompanySignInStore = class {
374492
374470
  if (!OrgIdSchema.safeParse(companyId).success)
374493
374471
  return false;
374494
374472
  if (companyId === IMPLICIT_COMPANY_ID)
374495
- return true;
374473
+ return false;
374496
374474
  const found = CompanyRecord.safeParse(await this.read(companyKey(companyId)));
374497
374475
  return found.success && found.data.companyId === companyId;
374498
374476
  }
@@ -374535,26 +374513,19 @@ var CompanySignInStore = class {
374535
374513
  return this.memberResult(existing, input2.companyId);
374536
374514
  if (!await this.companyExists(input2.companyId))
374537
374515
  return refused();
374538
- let legacy = false;
374539
- if (input2.companyId === IMPLICIT_COMPANY_ID) {
374540
- const developer = external_exports.object({ entityType: external_exports.literal("DEVELOPER"), provider: external_exports.enum(["slack", "oidc"]), issuer: external_exports.string().min(1), subject: external_exports.string().min(1), revoked: external_exports.literal(false), firstSignInAt: external_exports.iso.datetime(), companyless: external_exports.unknown().optional(), mergedInto: external_exports.unknown().optional() }).safeParse(await this.read({ pk: `DEVELOPER#${input2.personId}`, sk: "META" }));
374541
- legacy = developer.success && developer.data.companyless === void 0 && developer.data.mergedInto === void 0 && ownerKeyForSubject(developer.data.issuer, developer.data.subject) === input2.personId;
374542
- }
374543
374516
  const key = input2.email === void 0 || !CompanyEmail.safeParse(input2.email).success ? void 0 : preapprovalKey(input2.companyId, input2.email);
374544
- const approval = !legacy && key !== void 0 ? CompanyPreapproval.safeParse(await this.read(key)) : void 0;
374545
- if (!legacy && (!approval?.success || approval.data.status !== "live" || approval.data.expiresAt <= this.seconds()))
374517
+ const approval = key === void 0 ? void 0 : CompanyPreapproval.safeParse(await this.read(key));
374518
+ if (key === void 0 || !approval?.success || approval.data.status !== "live" || approval.data.expiresAt <= this.seconds())
374546
374519
  return refused();
374547
- const member2 = { entityType: "COMPANY_MEMBERSHIP", personId: input2.personId, companyId: input2.companyId, role: legacy ? "member" : approval.data.role, joinedAt: this.iso(), joinedVia: legacy ? "legacy" : "preapproval" };
374548
- const writes = [{ Put: { TableName: this.input.tableName, Item: { ...membershipKey(input2.personId), ...member2 }, ConditionExpression: "attribute_not_exists(pk)" } }, this.memberMirror(member2)];
374549
- if (!legacy)
374550
- writes.push({ Update: {
374551
- TableName: this.input.tableName,
374552
- Key: key,
374553
- UpdateExpression: "SET #status = :used, usedBy = :person, usedAt = :at",
374554
- ConditionExpression: "#status = :live AND expiresAt > :now AND expiresAt = :expires AND #role = :role AND createdAt = :created",
374555
- ExpressionAttributeNames: { "#status": "status", "#role": "role" },
374556
- ExpressionAttributeValues: { ":used": "used", ":person": input2.personId, ":at": this.iso(), ":live": "live", ":now": this.seconds(), ":expires": approval.data.expiresAt, ":role": approval.data.role, ":created": approval.data.createdAt }
374557
- } });
374520
+ const member2 = { entityType: "COMPANY_MEMBERSHIP", personId: input2.personId, companyId: input2.companyId, role: approval.data.role, joinedAt: this.iso(), joinedVia: "preapproval" };
374521
+ const writes = [{ Put: { TableName: this.input.tableName, Item: { ...membershipKey(input2.personId), ...member2 }, ConditionExpression: "attribute_not_exists(pk)" } }, this.memberMirror(member2), { Update: {
374522
+ TableName: this.input.tableName,
374523
+ Key: key,
374524
+ UpdateExpression: "SET #status = :used, usedBy = :person, usedAt = :at",
374525
+ ConditionExpression: "#status = :live AND expiresAt > :now AND expiresAt = :expires AND #role = :role AND createdAt = :created",
374526
+ ExpressionAttributeNames: { "#status": "status", "#role": "role" },
374527
+ ExpressionAttributeValues: { ":used": "used", ":person": input2.personId, ":at": this.iso(), ":live": "live", ":now": this.seconds(), ":expires": approval.data.expiresAt, ":role": approval.data.role, ":created": approval.data.createdAt }
374528
+ } }];
374558
374529
  try {
374559
374530
  await this.input.documentClient.send(new import_lib_dynamodb3.TransactWriteCommand({ TransactItems: writes }));
374560
374531
  } catch (error64) {
@@ -374563,7 +374534,7 @@ var CompanySignInStore = class {
374563
374534
  const won = await this.membership(input2.personId);
374564
374535
  return won === void 0 ? refused() : this.memberResult(won, input2.companyId);
374565
374536
  }
374566
- return { ok: true, membership: member2, ...legacy ? {} : { viaPreapproval: true } };
374537
+ return { ok: true, membership: member2, viaPreapproval: true };
374567
374538
  } catch (error64) {
374568
374539
  return isUnreadableMembershipRow(error64) ? refused() : { ok: false, reason: "not_invited", readFailed: true };
374569
374540
  }
@@ -375214,7 +375185,6 @@ var READ_TOKEN_REUSE_MS = 5 * 6e4;
375214
375185
 
375215
375186
  // packages/broker/dist/aws/github-credentials.js
375216
375187
  var bindingKey = (installationId) => ({ pk: `GITHUB_INSTALLATION#${installationId}`, sk: "BINDING" });
375217
- var backfillKey = { pk: "GITHUB_INSTALLATION_BINDING", sk: "BACKFILL" };
375218
375188
  var installationIdSchema = external_exports.number().int().positive().max(Number.MAX_SAFE_INTEGER);
375219
375189
  var bindingText = external_exports.string().min(1).max(256);
375220
375190
  var installationSchema = external_exports.object({ installationId: installationIdSchema, accountLogin: bindingText });
@@ -375228,7 +375198,6 @@ var bindingSchema = installationSchema.extend({
375228
375198
  stateAt: external_exports.iso.datetime().optional(),
375229
375199
  accountType: external_exports.enum(["User", "Organization"]).optional()
375230
375200
  });
375231
- var markerSchema = external_exports.object({ pk: external_exports.literal("GITHUB_INSTALLATION_BINDING"), sk: external_exports.literal("BACKFILL") }).strict();
375232
375201
  var companyInstallationKey = (companyId, installationId) => ({ pk: `ORG#${companyId}#GITHUB_INSTALLATIONS`, sk: `INSTALLATION#${installationId}` });
375233
375202
  var companyInstallationRow = (companyId, row2) => ({
375234
375203
  ...companyInstallationKey(companyId, row2.installationId),
@@ -375274,6 +375243,10 @@ var LIFECYCLE_TRANSITIONS = {
375274
375243
  };
375275
375244
  var DELIVERY = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
375276
375245
  var stateOf = (row2) => row2.state ?? "active";
375246
+ var unboundCondition = {
375247
+ ConditionExpression: "attribute_not_exists(pk) OR companyId = :placeholder",
375248
+ ExpressionAttributeValues: { ":placeholder": IMPLICIT_COMPANY_ID }
375249
+ };
375277
375250
  function sameBinding(row2) {
375278
375251
  return {
375279
375252
  ConditionExpression: `companyId = :company AND boundAt = :boundAt AND ${row2.state === void 0 ? "attribute_not_exists(#state)" : "#state = :read"}`,
@@ -375315,13 +375288,6 @@ var GithubInstallationBindings = class _GithubInstallationBindings {
375315
375288
  throw githubBindingRefusal();
375316
375289
  }
375317
375290
  }
375318
- async marker(send3) {
375319
- const response = await send3(new import_lib_dynamodb5.GetCommand({ TableName: this.tableName, Key: backfillKey, ConsistentRead: true }));
375320
- if (response.Item === void 0)
375321
- return false;
375322
- markerSchema.parse(response.Item);
375323
- return true;
375324
- }
375325
375291
  async binding(send3, installationId) {
375326
375292
  const response = await send3(new import_lib_dynamodb5.GetCommand({ TableName: this.tableName, Key: bindingKey(installationId), ConsistentRead: true }));
375327
375293
  if (response.Item === void 0)
@@ -375329,46 +375295,26 @@ var GithubInstallationBindings = class _GithubInstallationBindings {
375329
375295
  const row2 = bindingSchema.parse(response.Item);
375330
375296
  if (row2.installationId !== installationId)
375331
375297
  throw githubBindingRefusal();
375332
- return row2;
375298
+ return row2.companyId === IMPLICIT_COMPANY_ID ? void 0 : row2;
375333
375299
  }
375334
- async ownerOf(installationId) {
375335
- return this.run(async (send3) => {
375336
- installationIdSchema.parse(installationId);
375337
- const row2 = await this.binding(send3, installationId);
375338
- if (row2 !== void 0)
375339
- return row2.companyId;
375340
- return await this.marker(send3) ? void 0 : IMPLICIT_COMPANY_ID;
375341
- });
375342
- }
375343
- /** A list shares the backfill marker and the store's total command/byte/time budget. */
375300
+ /** Each installation's owner (#1650: no binding is nobody's), within the store's total command/byte/time budget. */
375344
375301
  async ownersOf(installationIds) {
375345
375302
  return this.run(async (send3) => {
375346
375303
  const ids2 = external_exports.array(installationIdSchema).max(100).parse(installationIds);
375347
- let marker2;
375348
375304
  const owners = [];
375349
- for (const id12 of ids2) {
375350
- const row2 = await this.binding(send3, id12);
375351
- if (row2 !== void 0)
375352
- owners.push(row2.companyId);
375353
- else {
375354
- marker2 ??= this.marker(send3);
375355
- owners.push(await marker2 ? void 0 : IMPLICIT_COMPANY_ID);
375356
- }
375357
- }
375305
+ for (const id12 of ids2)
375306
+ owners.push((await this.binding(send3, id12))?.companyId);
375358
375307
  return owners;
375359
375308
  });
375360
375309
  }
375361
- /**
375362
- * The owner and state of an installation: its binding's, or (no binding) the implicit company's before backfill and nobody's after. `bound` says whether a binding row names the owner: an
375363
- * implicit owner (no row) is the install's old single company, which only the legacy webhook path serves (webhook lane W0).
375364
- */
375310
+ /** The owner and state of an installation: its binding's, or (#1650: no binding) nobody's. `bound` says whether a binding row names the owner. */
375365
375311
  async ownerAndState(installationId) {
375366
375312
  return this.run(async (send3) => {
375367
375313
  installationIdSchema.parse(installationId);
375368
375314
  const row2 = await this.binding(send3, installationId);
375369
375315
  if (row2 !== void 0)
375370
375316
  return { owner: row2.companyId, state: stateOf(row2), bound: true };
375371
- return { owner: await this.marker(send3) ? void 0 : IMPLICIT_COMPANY_ID, state: "active", bound: false };
375317
+ return { owner: void 0, state: "active", bound: false };
375372
375318
  });
375373
375319
  }
375374
375320
  /**
@@ -375453,7 +375399,7 @@ var GithubInstallationBindings = class _GithubInstallationBindings {
375453
375399
  }
375454
375400
  /**
375455
375401
  * DEC 254zc(1): GitHub's signed webhook says repositories left this installation (`installation_repositories` removed: reason "removed") or moved to another owner (`repository`
375456
- * transferred: reason "transferred"). The company is the installation's, found by the installation id alone (its binding; before the backfill marker, the implicit company), so one
375402
+ * transferred: reason "transferred"). The company is the installation's, found by the installation id alone (its binding), so one
375457
375403
  * company's event never marks another's. Each name gets one mark in the company's own partition; a "removed" never replaces a "transferred" (the more exact word stays). When the
375458
375404
  * event names the installation's account (`accountLogin`) it must be the binding's, else nothing is written (a body signed for another event, replayed). An unbound installation
375459
375405
  * writes nothing. More than REPOSITORY_MOVES_MAX names refuses the whole delivery.
@@ -375493,7 +375439,7 @@ var GithubInstallationBindings = class _GithubInstallationBindings {
375493
375439
  return { outcome: "cleared", companyId: owner.companyId, count: fullNames.length };
375494
375440
  });
375495
375441
  }
375496
- /** The company a repository event writes for: the installation's binding (its account must match the event's, when the event names one), else the implicit company before the backfill marker. */
375442
+ /** The company a repository event writes for: the installation's binding (its account must match the event's, when the event names one). #1650: unbound writes nothing. */
375497
375443
  async repositoryOwner(send3, installationId, deliveryId, accountLogin, names2) {
375498
375444
  installationIdSchema.parse(installationId);
375499
375445
  if (accountLogin !== void 0)
@@ -375501,14 +375447,14 @@ var GithubInstallationBindings = class _GithubInstallationBindings {
375501
375447
  if (!DELIVERY.test(deliveryId) || names2 > REPOSITORY_MOVES_MAX)
375502
375448
  throw githubBindingRefusal();
375503
375449
  const row2 = await this.binding(send3, installationId);
375504
- if (row2 !== void 0)
375505
- return accountLogin !== void 0 && accountLogin.toLowerCase() !== row2.accountLogin.toLowerCase() ? "unchanged" : { companyId: row2.companyId };
375506
- return await this.marker(send3) ? "unbound" : { companyId: IMPLICIT_COMPANY_ID };
375450
+ if (row2 === void 0)
375451
+ return "unbound";
375452
+ return accountLogin !== void 0 && accountLogin.toLowerCase() !== row2.accountLogin.toLowerCase() ? "unchanged" : { companyId: row2.companyId };
375507
375453
  }
375508
375454
  /**
375509
375455
  * Guided onboarding PR 3: a company owner unbinds the company's installation (the route checked the role and that no project uses it). One conditional
375510
- * transaction on exactly the binding that was read: the binding and the company's list row go, an audit row naming the person stays (with the claim audits, history is kept),
375511
- * and the backfill marker must exist (before it, an unbound installation would read as the implicit company's). Another company's, or none: not_found, nothing written.
375456
+ * transaction on exactly the binding that was read: the binding and the company's list row go, an audit row naming the person stays (with the claim audits, history is kept).
375457
+ * Another company's, or none: not_found, nothing written.
375512
375458
  */
375513
375459
  async disconnect(companyId, installationId, personId) {
375514
375460
  return this.run(async (send3) => {
@@ -375523,7 +375469,6 @@ var GithubInstallationBindings = class _GithubInstallationBindings {
375523
375469
  const auditKey = { pk: `GITHUB_INSTALLATION#${installationId}`, sk: `AUDIT#DISCONNECT#${at}#${personId}` };
375524
375470
  try {
375525
375471
  await send3(new import_lib_dynamodb5.TransactWriteCommand({ TransactItems: [
375526
- { ConditionCheck: { TableName: this.tableName, Key: backfillKey, ConditionExpression: "attribute_exists(pk)" } },
375527
375472
  { Delete: { TableName: this.tableName, Key: bindingKey(installationId), ...fence } },
375528
375473
  { Delete: { TableName: this.tableName, Key: companyInstallationKey(companyId, installationId) } },
375529
375474
  { Put: { TableName: this.tableName, Item: {
@@ -375551,18 +375496,8 @@ var GithubInstallationBindings = class _GithubInstallationBindings {
375551
375496
  return { outcome: "disconnected", accountLogin: row2.accountLogin, ...row2.accountType === void 0 ? {} : { accountType: row2.accountType } };
375552
375497
  });
375553
375498
  }
375554
- async claim(companyId, installationId, accountLogin, by) {
375555
- return this.run(async (send3) => {
375556
- OrgIdSchema.parse(companyId);
375557
- installationSchema.parse({ installationId, accountLogin });
375558
- bindingText.parse(by);
375559
- if (!await this.marker(send3) && companyId !== IMPLICIT_COMPANY_ID)
375560
- throw githubBindingRefusal();
375561
- await this.put(send3, companyId, installationId, accountLogin, by);
375562
- });
375563
- }
375564
- /** Only the direct operator event calls this; the conditional transaction is the
375565
- * claim and its durable audit record. Replays, including same-company, refuse. */
375499
+ /** The direct operator event and the install's connections step call this; the conditional transaction is the
375500
+ * claim and its durable audit record. Replays, including same-company, refuse. #1650: a binding to the built-in placeholder is replaced, as no binding. */
375566
375501
  async claimOperator(companyId, installation) {
375567
375502
  return this.run(async (send3) => {
375568
375503
  OrgIdSchema.parse(companyId);
@@ -375576,7 +375511,7 @@ var GithubInstallationBindings = class _GithubInstallationBindings {
375576
375511
  companyId,
375577
375512
  boundAt: at,
375578
375513
  boundBy: "operator-lambda"
375579
- }, ConditionExpression: "attribute_not_exists(pk)" } },
375514
+ }, ...unboundCondition } },
375580
375515
  { Put: { TableName: this.tableName, Item: {
375581
375516
  pk: `GITHUB_INSTALLATION#${installation.installationId}`,
375582
375517
  sk: "AUDIT#CLAIM",
@@ -375592,8 +375527,7 @@ var GithubInstallationBindings = class _GithubInstallationBindings {
375592
375527
  }
375593
375528
  /**
375594
375529
  * Guided onboarding PR 1: a company owner or admin binds an installation they proved they control (the route checked that against GitHub first).
375595
- * First binder wins with one conditional transaction: the binding (absent), its audit row naming the person, the company's list row, and the
375596
- * backfill marker (present: before backfill every unbound installation is the implicit company's, so the person path never binds then).
375530
+ * First binder wins with one conditional transaction: the binding (absent, or #1650 the built-in placeholder's), its audit row naming the person, and the company's list row.
375597
375531
  * Already this company's: nothing is overwritten (the company's list row is put back if it is missing, only while that binding still stands). Another company's: "taken", nothing written.
375598
375532
  * Guided onboarding PR 3: this company's binding that GitHub said is uninstalled or suspended is reconnected by the claim alone (`reconnected`): its state moves to what the
375599
375533
  * person's GitHub check saw (active, or suspended if GitHub still says so), conditionally on what was read, with an audit row naming the person. A webhook never re-activates
@@ -375653,8 +375587,6 @@ var GithubInstallationBindings = class _GithubInstallationBindings {
375653
375587
  }
375654
375588
  return "reconnected";
375655
375589
  }
375656
- if (!await this.marker(send3))
375657
- return companyId === IMPLICIT_COMPANY_ID ? "already_bound" : "taken";
375658
375590
  return void 0;
375659
375591
  };
375660
375592
  const before = await decide2();
@@ -375663,7 +375595,6 @@ var GithubInstallationBindings = class _GithubInstallationBindings {
375663
375595
  const at = new Date(this.clock()).toISOString();
375664
375596
  try {
375665
375597
  await send3(new import_lib_dynamodb5.TransactWriteCommand({ TransactItems: [
375666
- { ConditionCheck: { TableName: this.tableName, Key: backfillKey, ConditionExpression: "attribute_exists(pk)" } },
375667
375598
  { Put: { TableName: this.tableName, Item: {
375668
375599
  ...bindingKey(installation.installationId),
375669
375600
  ...fields,
@@ -375672,7 +375603,7 @@ var GithubInstallationBindings = class _GithubInstallationBindings {
375672
375603
  boundAt: at,
375673
375604
  boundBy: personId,
375674
375605
  ...target3 === "active" ? {} : { state: target3, stateAt: at }
375675
- }, ConditionExpression: "attribute_not_exists(pk)" } },
375606
+ }, ...unboundCondition } },
375676
375607
  { Put: { TableName: this.tableName, Item: {
375677
375608
  pk: `GITHUB_INSTALLATION#${installation.installationId}`,
375678
375609
  sk: `AUDIT#CLAIM#${at}#${personId}`,
@@ -375731,106 +375662,6 @@ var GithubInstallationBindings = class _GithubInstallationBindings {
375731
375662
  return listed3;
375732
375663
  });
375733
375664
  }
375734
- /** Each operator invocation reads one page and writes at most 25 bindings. The
375735
- * durable page number prevents a forged/skipped continuation from sealing early. */
375736
- async backfillPage(list3, page = 1) {
375737
- const progressKey = { pk: "GITHUB_INSTALLATION_BINDING", sk: "PROGRESS" };
375738
- const expected = await this.run(async (send3) => {
375739
- external_exports.number().int().positive().max(1e6).parse(page);
375740
- if (await this.marker(send3))
375741
- return void 0;
375742
- const saved = await send3(new import_lib_dynamodb5.GetCommand({ TableName: this.tableName, Key: progressKey, ConsistentRead: true }));
375743
- return saved.Item === void 0 ? 1 : external_exports.object({ page: external_exports.number().int().positive().max(1e6) }).parse(saved.Item).page;
375744
- });
375745
- if (expected === void 0)
375746
- return { more: false };
375747
- if (page !== expected)
375748
- throw githubBindingRefusal();
375749
- let input2;
375750
- try {
375751
- const value = await list3(page);
375752
- if (Buffer.byteLength(JSON.stringify(value) ?? "") > 1e6)
375753
- throw githubBindingRefusal();
375754
- input2 = external_exports.object({ installations: external_exports.array(installationSchema).max(25), more: external_exports.boolean() }).strict().parse(value);
375755
- if (new Set(input2.installations.map((row2) => row2.installationId)).size !== input2.installations.length)
375756
- throw githubBindingRefusal();
375757
- } catch {
375758
- throw githubBindingRefusal();
375759
- }
375760
- return this.run(async (send3) => {
375761
- for (const installation of input2.installations) {
375762
- if (await this.binding(send3, installation.installationId) === void 0) {
375763
- try {
375764
- await this.put(send3, IMPLICIT_COMPANY_ID, installation.installationId, installation.accountLogin, "operator-backfill");
375765
- } catch {
375766
- if (await this.binding(send3, installation.installationId) === void 0)
375767
- throw githubBindingRefusal();
375768
- }
375769
- }
375770
- }
375771
- await send3(new import_lib_dynamodb5.TransactWriteCommand({ TransactItems: [
375772
- { Put: {
375773
- TableName: this.tableName,
375774
- Item: { ...progressKey, page: page + 1 },
375775
- ConditionExpression: page === 1 ? "attribute_not_exists(pk)" : "#page = :page",
375776
- ...page === 1 ? {} : { ExpressionAttributeNames: { "#page": "page" }, ExpressionAttributeValues: { ":page": page } }
375777
- } },
375778
- ...input2.more ? [] : [{ Put: { TableName: this.tableName, Item: backfillKey, ConditionExpression: "attribute_not_exists(pk)" } }]
375779
- ] }));
375780
- return input2.more ? { more: true, continuation: page + 1 } : { more: false };
375781
- });
375782
- }
375783
- async put(send3, companyId, installationId, accountLogin, by) {
375784
- const existing = await this.binding(send3, installationId);
375785
- if (existing !== void 0) {
375786
- if (existing.companyId !== companyId)
375787
- throw githubBindingRefusal();
375788
- return;
375789
- }
375790
- try {
375791
- await send3(new import_lib_dynamodb5.PutCommand({
375792
- TableName: this.tableName,
375793
- Item: {
375794
- ...bindingKey(installationId),
375795
- entityType: "GITHUB_INSTALLATION_BINDING",
375796
- installationId,
375797
- companyId,
375798
- accountLogin,
375799
- boundAt: new Date(this.clock()).toISOString(),
375800
- boundBy: by
375801
- },
375802
- ConditionExpression: "attribute_not_exists(pk)"
375803
- }));
375804
- } catch (error64) {
375805
- if (!isConditional(error64) || (await this.binding(send3, installationId))?.companyId !== companyId)
375806
- throw githubBindingRefusal();
375807
- }
375808
- }
375809
- async backfill(listInstallations) {
375810
- return this.run(async (send3, check4) => {
375811
- if (await this.marker(send3))
375812
- return { more: false };
375813
- const input2 = await listInstallations();
375814
- check4();
375815
- if (!Array.isArray(input2))
375816
- throw githubBindingRefusal();
375817
- if (input2.length > 100)
375818
- return { more: true };
375819
- const installations2 = external_exports.array(installationSchema).max(100).parse(input2);
375820
- if (new Set(installations2.map((row2) => row2.installationId)).size !== installations2.length)
375821
- throw githubBindingRefusal();
375822
- for (const installation of installations2)
375823
- await this.put(send3, IMPLICIT_COMPANY_ID, installation.installationId, installation.accountLogin, "operator-backfill");
375824
- check4();
375825
- try {
375826
- await send3(new import_lib_dynamodb5.PutCommand({ TableName: this.tableName, Item: backfillKey, ConditionExpression: "attribute_not_exists(pk)" }));
375827
- } catch (error64) {
375828
- if (!isConditional(error64) || !await this.marker(send3))
375829
- throw githubBindingRefusal();
375830
- }
375831
- return { more: false };
375832
- });
375833
- }
375834
375665
  };
375835
375666
  var listedInstallationsSchema = external_exports.array(installationSchema.extend({
375836
375667
  accountType: external_exports.enum(["User", "Organization"]),
@@ -375868,8 +375699,6 @@ var bindingRow = external_exports.object({
375868
375699
  boundAt: external_exports.iso.datetime(),
375869
375700
  boundBy: external_exports.union([operator, person3])
375870
375701
  }).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
375702
  var teamKey = (teamId) => ({ pk: `SLACK_TEAM#${teamId}`, sk: "BINDING" });
375874
375703
  var companyWorkspaceKey = (companyId, teamId) => ({ pk: `ORG#${companyId}#SLACK_WORKSPACES`, sk: `TEAM#${teamId}` });
375875
375704
  function parseBinding(value) {
@@ -375902,7 +375731,6 @@ function indexTransaction(tableName, row2, create) {
375902
375731
  }
375903
375732
  function createSlackWorkspaceBindings(deps) {
375904
375733
  const now = deps.now ?? Date.now;
375905
- const legacy = slackWorkspaceTeam(deps.legacyTeamId) ? deps.legacyTeamId : void 0;
375906
375734
  const operation2 = (body) => {
375907
375735
  const started = now();
375908
375736
  let commands5 = 0;
@@ -375911,8 +375739,6 @@ function createSlackWorkspaceBindings(deps) {
375911
375739
  if (commands5 > 8 || bytes5 > 65536 || now() - started > 1e4)
375912
375740
  throw new SlackWorkspaceRefused();
375913
375741
  };
375914
- if (deps.legacyTeamId !== void 0 && deps.legacyTeamId !== "" && legacy === void 0)
375915
- return Promise.reject(new SlackWorkspaceRefused());
375916
375742
  return body(async (command5) => {
375917
375743
  commands5++;
375918
375744
  check4();
@@ -375930,14 +375756,6 @@ function createSlackWorkspaceBindings(deps) {
375930
375756
  throw new SlackWorkspaceRefused();
375931
375757
  return response.Item;
375932
375758
  };
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
375759
  const storedBinding = async (send3, team) => {
375942
375760
  const row2 = await read(send3, teamKey(team));
375943
375761
  if (row2 === void 0)
@@ -375971,9 +375789,7 @@ function createSlackWorkspaceBindings(deps) {
375971
375789
  if (!slackWorkspaceTeam(team))
375972
375790
  throw new SlackWorkspaceRefused();
375973
375791
  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;
375792
+ return company === void 0 || company === IMPLICIT_COMPANY_ID ? void 0 : company;
375977
375793
  });
375978
375794
  return {
375979
375795
  companyOf: companyOf2,
@@ -375985,31 +375801,13 @@ function createSlackWorkspaceBindings(deps) {
375985
375801
  },
375986
375802
  channelCompanyOf: (where) => where !== null && typeof where === "object" && where.channel === "slack" ? companyOf2(where.tenant) : void 0,
375987
375803
  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)
375804
+ if (!OrgIdSchema.safeParse(company).success || company === IMPLICIT_COMPANY_ID || !slackWorkspaceTeam(team) || !operator.safeParse(by).success)
375991
375805
  throw new SlackWorkspaceRefused();
375992
375806
  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
375807
  })
376007
375808
  };
376008
375809
  }
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
- ]);
375810
+ 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
375811
  var cursorSchema = external_exports.object({ pk: external_exports.string().min(1).max(2048), sk: external_exports.string().min(1).max(1024) }).strict();
376014
375812
  var pageSchema = external_exports.object({
376015
375813
  Items: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).optional(),
@@ -376045,12 +375843,13 @@ async function linkInstallConnections(deps, input2) {
376045
375843
  }
376046
375844
  async function claimInstallation(deps, companyId, installation, apply, into) {
376047
375845
  into.found++;
376048
- const binding = await get2(deps, { pk: `GITHUB_INSTALLATION#${installation.installationId}`, sk: "BINDING" });
375846
+ const stored = await get2(deps, { pk: `GITHUB_INSTALLATION#${installation.installationId}`, sk: "BINDING" });
375847
+ const binding = stored?.["companyId"] === IMPLICIT_COMPANY_ID ? void 0 : stored;
376049
375848
  if (binding !== void 0) {
376050
375849
  into[binding["companyId"] === companyId ? "existing" : "conflicts"]++;
376051
375850
  return;
376052
375851
  }
376053
- if (await get2(deps, { pk: `GITHUB_INSTALLATION#${installation.installationId}`, sk: "AUDIT#CLAIM" }) !== void 0) {
375852
+ if (stored === void 0 && await get2(deps, { pk: `GITHUB_INSTALLATION#${installation.installationId}`, sk: "AUDIT#CLAIM" }) !== void 0) {
376054
375853
  into.conflicts++;
376055
375854
  return;
376056
375855
  }
@@ -376073,7 +375872,6 @@ async function bindWorkspace(deps, companyId, teamId, apply) {
376073
375872
  if (!apply)
376074
375873
  return "bound";
376075
375874
  const bindings = createSlackWorkspaceBindings({ client: deps.documentClient, tableName: deps.tableName, ...deps.now === void 0 ? {} : { now: deps.now } });
376076
- await bindings.backfill();
376077
375875
  await bindings.bind(companyId, teamId, BY);
376078
375876
  return "bound";
376079
375877
  }
@@ -376474,7 +376272,7 @@ function vendorApi(fetchImplementation) {
376474
376272
 
376475
376273
  // packages/cli/src/setup/project-files.ts
376476
376274
  init_dist2();
376477
- import { createHash as createHash30 } from "node:crypto";
376275
+ import { createHash as createHash29 } from "node:crypto";
376478
376276
  var API2 = "https://api.github.com";
376479
376277
  var SETUP_TIMEOUT = 900;
376480
376278
  var TEST_TIMEOUT = 1800;
@@ -376589,11 +376387,11 @@ function githubRepositoryApi(fetchImplementation) {
376589
376387
  if (normalizedBase64.length > encodedLimit || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(normalizedBase64)) throw agentXError("RUNTIME_UNAVAILABLE", `GitHub returned incomplete or mismatched immutable source bytes for ${path6}`);
376590
376388
  const bytes5 = Buffer.from(normalizedBase64, "base64");
376591
376389
  if (bytes5.byteLength !== entry.size) throw agentXError("RUNTIME_UNAVAILABLE", `GitHub source byte count did not match the immutable tree for ${path6}`);
376592
- const gitObjectSha = createHash30("sha1").update(Buffer.from(`blob ${bytes5.byteLength}\0`)).update(bytes5).digest("hex");
376390
+ const gitObjectSha = createHash29("sha1").update(Buffer.from(`blob ${bytes5.byteLength}\0`)).update(bytes5).digest("hex");
376593
376391
  if (gitObjectSha !== entry.sha) throw agentXError("RUNTIME_UNAVAILABLE", `GitHub source bytes did not match the immutable Git blob identity for ${path6}`);
376594
376392
  totalBytes += bytes5.byteLength;
376595
376393
  if (totalBytes > MAX_SNAPSHOT_TOTAL_BYTES) throw agentXError("RUNTIME_UNAVAILABLE", "requested source snapshot exceeds the total byte limit");
376596
- sources.push({ path: path6, sha256: createHash30("sha256").update(bytes5).digest("hex"), bytes: bytes5, kind: "blob" });
376394
+ sources.push({ path: path6, sha256: createHash29("sha256").update(bytes5).digest("hex"), bytes: bytes5, kind: "blob" });
376597
376395
  }
376598
376396
  const candidate = createCandidateManifest([{ repositoryId: fullName, commitSha, treeSha }]);
376599
376397
  return { candidate, commitSha, treeSha, treeComplete: true, treePaths: [...treePaths], sources };
@@ -377147,6 +376945,28 @@ async function installations(context) {
377147
376945
  // packages/cli/src/init/finish-steps.ts
377148
376946
  init_answer_schemas();
377149
376947
 
376948
+ // packages/cli/src/admin/slack.ts
376949
+ init_dist2();
376950
+ async function bindCompanyChannel(input2, fetchImplementation = fetch) {
376951
+ const projectName = AgentXNameSchema.parse(input2.projectName);
376952
+ return sendBindingRequest(input2, `/v1/dev/company/slack/projects/${projectName}/bindings`, fetchImplementation);
376953
+ }
376954
+ async function sendBindingRequest(input2, base2, fetchImplementation) {
376955
+ const teamId = SlackTeamIdSchema.parse(input2.teamId);
376956
+ const channelId = SlackChannelIdSchema.parse(input2.channelId);
376957
+ const response = await fetchImplementation(`${input2.controlPlaneUrl.replace(/\/$/, "")}${base2}/${teamId}/${channelId}`, {
376958
+ method: "PUT",
376959
+ headers: { authorization: `Bearer ${input2.accessToken}` }
376960
+ });
376961
+ const { ok: ok2, status, body } = await readJsonResponse(response);
376962
+ if (!ok2) {
376963
+ const message = body === void 0 ? `HTTP ${status}` : serverError(body).message ?? `HTTP ${status}`;
376964
+ throw agentXError("RUNTIME_UNAVAILABLE", `Slack channel binding failed: ${message}`);
376965
+ }
376966
+ if (body === void 0) throw agentXError("RUNTIME_UNAVAILABLE", "control plane returned an invalid response");
376967
+ return body;
376968
+ }
376969
+
377150
376970
  // packages/cli/src/setup/connectors/asana.ts
377151
376971
  init_dist2();
377152
376972
  init_answer_schemas();
@@ -377159,13 +376979,12 @@ import { stat as stat6 } from "node:fs/promises";
377159
376979
  var import_yaml5 = __toESM(require_dist4(), 1);
377160
376980
  init_dist2();
377161
376981
  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
376982
  import { join as join18 } from "node:path";
377164
376983
  import { isDeepStrictEqual as isDeepStrictEqual3 } from "node:util";
377165
376984
 
377166
376985
  // packages/cli/src/loop/enrollment-cli.ts
377167
376986
  init_dist2();
377168
- import { createHash as createHash32 } from "node:crypto";
376987
+ import { createHash as createHash31 } from "node:crypto";
377169
376988
  import { realpath as realpath5 } from "node:fs/promises";
377170
376989
  import { arch, hostname as hostname3 } from "node:os";
377171
376990
  import { isDeepStrictEqual as isDeepStrictEqual2 } from "node:util";
@@ -377419,7 +377238,7 @@ ${body}` }) });
377419
377238
  init_zod();
377420
377239
  init_dist2();
377421
377240
  import { randomUUID as randomUUID12 } from "node:crypto";
377422
- import { createHash as createHash31 } from "node:crypto";
377241
+ import { createHash as createHash30 } from "node:crypto";
377423
377242
  var ShaSchema = external_exports.string().regex(/^[a-f0-9]{40}$/u);
377424
377243
  var DigestSchema5 = external_exports.string().regex(/^[a-f0-9]{64}$/u);
377425
377244
  var RepoSlugSchema = external_exports.string().regex(/^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/u, "owner/name");
@@ -377482,7 +377301,7 @@ var NativeTaskEvidenceReceiptSchema = external_exports.object({
377482
377301
  const proofDigest = receipt4.proofDigest;
377483
377302
  delete semantic.importedAt;
377484
377303
  delete semantic.proofDigest;
377485
- const expected = createHash31("sha256").update(canonicalJson(semantic)).digest("hex");
377304
+ const expected = createHash30("sha256").update(canonicalJson(semantic)).digest("hex");
377486
377305
  if (expected !== proofDigest) context.addIssue({ code: "custom", path: ["proofDigest"], message: "native evidence receipt digest does not match its bound fields" });
377487
377306
  });
377488
377307
  var RegisteredPendingSourceSchema = external_exports.object({
@@ -377663,7 +377482,7 @@ function importNativeTaskEvidence(input2) {
377663
377482
  const progress = workflow.e2e;
377664
377483
  const qualified = progress?.qualifiedRound;
377665
377484
  if (progress?.required !== true || qualified === void 0 || workflow.verification?.candidateDigest !== manifest.digest || workflow.e2e?.currentRoundId !== qualified.roundId || workflow.e2e.currentGroupRunIds.length !== qualified.groupRunIds.length || workflow.e2e.currentGroupRunIds.some((id12, index) => id12 !== qualified.groupRunIds[index]) || qualified.candidateDigest !== input2.join.candidateDigest || progress.contractDigest !== input2.join.contractDigest || progress.policyDigest !== input2.join.policyDigest || progress.executionPlanDigest !== input2.join.planDigest || qualified.contractDigest !== input2.join.contractDigest || qualified.policyDigest !== input2.join.policyDigest || qualified.executionPlanDigest !== input2.join.planDigest || qualified.roundId !== input2.join.roundId) return hold("e2e_round_binding_mismatch");
377666
- const expectedEvidenceSetDigest = createHash31("sha256").update(canonicalJson({
377485
+ const expectedEvidenceSetDigest = createHash30("sha256").update(canonicalJson({
377667
377486
  domain: "agentx-e2e-publication-context/v1",
377668
377487
  taskId: task.taskId,
377669
377488
  candidateDigest: input2.join.candidateDigest,
@@ -377702,7 +377521,7 @@ function importNativeTaskEvidence(input2) {
377702
377521
  return hold("approved_graph_missing_or_changed");
377703
377522
  }
377704
377523
  if (graph !== void 0 && (graph.artifactDigest !== plan.sha256 || graph.workflowRevision !== approval.workflowRevision || graph.actorId !== approval.actorId || graph.graphDigest !== approval.workBreakdownDigest)) return hold("approved_graph_mismatch");
377705
- const approvalDigest = createHash31("sha256").update(canonicalJson({
377524
+ const approvalDigest = createHash30("sha256").update(canonicalJson({
377706
377525
  artifactDigest: plan.sha256,
377707
377526
  workflowRevision: approval.workflowRevision,
377708
377527
  actorId: approval.actorId,
@@ -377741,7 +377560,7 @@ function importNativeTaskEvidence(input2) {
377741
377560
  approvalDigest,
377742
377561
  ...graph === void 0 ? {} : { graphDigest: graph.graphDigest }
377743
377562
  };
377744
- const proofDigest = createHash31("sha256").update(canonicalJson(semantic)).digest("hex");
377563
+ const proofDigest = createHash30("sha256").update(canonicalJson(semantic)).digest("hex");
377745
377564
  return NativeTaskEvidenceReceiptSchema.parse({ ...semantic, importedAt: input2.now.toISOString(), proofDigest });
377746
377565
  }
377747
377566
  function sameNativeTaskEvidenceReceipt(left, right) {
@@ -378384,7 +378203,7 @@ async function recordRegisteredLoopEnrollment(input2) {
378384
378203
  return { recorded: false, reasonCode: "source_identity_unavailable" };
378385
378204
  }
378386
378205
  const checkoutPath = cwd;
378387
- const sourceBindingRef = `cli-source:v1:${createHash32("sha256").update(JSON.stringify([
378206
+ const sourceBindingRef = `cli-source:v1:${createHash31("sha256").update(JSON.stringify([
378388
378207
  parsed.registeredBy,
378389
378208
  namespace,
378390
378209
  projectDefinition.name,
@@ -378690,7 +378509,7 @@ async function writeProjectFile(configDir, definition, register) {
378690
378509
  }
378691
378510
  var LocalSaveAfterRegistrationError = class extends AgentXError {
378692
378511
  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);
378512
+ 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
378513
  this.projectName = projectName;
378695
378514
  this.revision = revision3;
378696
378515
  }
@@ -378707,22 +378526,10 @@ async function registerRevision(request) {
378707
378526
  const input2 = { ...request, definition: modelChecked.definition };
378708
378527
  const foundation = environmentStackName(input2.env, "foundation");
378709
378528
  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);
378529
+ const result4 = await registerProject({ controlPlaneUrl: input2.session.controlPlaneUrl, accessToken: input2.session.accessToken, definition: input2.definition, runtimeBinding }, input2.services.fetch);
378530
+ const registeredDefinition = withSavedCredentialRefs(input2.definition, result4);
378719
378531
  const preflight = RegistrationPreflightSchema.safeParse(result4.preflight);
378720
378532
  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
378533
  if (input2.services.loopHome !== void 0) {
378727
378534
  try {
378728
378535
  const enrollment = await recordRegisteredLoopEnrollment({ home: input2.services.loopHome, env: input2.env, controlPlaneUrl: input2.session.controlPlaneUrl, definition: registeredDefinition, response: result4 });
@@ -378734,11 +378541,6 @@ async function registerRevision(request) {
378734
378541
  let file2;
378735
378542
  try {
378736
378543
  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
378544
  } catch (error64) {
378743
378545
  const raw = typeof error64.code === "string" ? error64.code : error64 instanceof Error ? error64.name : "";
378744
378546
  const cause = /^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(raw) ? raw : "unknown error";
@@ -378821,114 +378623,6 @@ async function existingProject(configDir, name3) {
378821
378623
  }
378822
378624
  }
378823
378625
  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
378626
  function differences(existing, wanted) {
378933
378627
  const repository = existing.repositories[0];
378934
378628
  const typed = (line21, timeout) => line21.trim() === "" ? [] : [parseCommandLine(line21, repository?.path ?? ".", timeout)];
@@ -378938,85 +378632,6 @@ function differences(existing, wanted) {
378938
378632
  if (wanted.testCommand !== void 0 && !isDeepStrictEqual3(typed(wanted.testCommand, TEST_TIMEOUT), existing.readiness)) found.push("test command");
378939
378633
  return found;
378940
378634
  }
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
378635
  async function addProject(input2) {
379021
378636
  const { prompter, flags } = input2;
379022
378637
  const configDir = input2.services.configDir;
@@ -379081,7 +378696,7 @@ async function addProject(input2) {
379081
378696
  readiness,
379082
378697
  orchestratorInstructions: DEFAULT_INSTRUCTIONS
379083
378698
  });
379084
- const registered = await registerRevision({ env: input2.env, session: input2.session, definition, services: input2.services, registerPath: "/v1/dev/projects" });
378699
+ const registered = await registerRevision({ env: input2.env, session: input2.session, definition, services: input2.services });
379085
378700
  input2.write(`Registered project ${name3}, revision 1, on EC2 workers. Its file is ${registered.file}.`);
379086
378701
  for (const warning2 of registered.warnings) input2.write(`Warning: ${warning2}`);
379087
378702
  return { name: name3, revision: 1, file: registered.file };
@@ -379128,8 +378743,7 @@ async function addConnectorRevision(input2) {
379128
378743
  const current = await loadProjectFile({ projectName: input2.projectName, configDir: input2.services.configDir, rerun: input2.rerun });
379129
378744
  const others = (current.integrations?.connectors ?? []).filter((entry) => entry.name !== input2.connector.name);
379130
378745
  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 } });
378746
+ const registered = await registerRevision({ env: input2.env, session: input2.session, definition, services: input2.services });
379133
378747
  const report = registered.preflight.find((entry) => entry.name === input2.connector.name);
379134
378748
  for (const warning2 of registered.warnings) input2.write(`Warning: ${warning2}`);
379135
378749
  if (report === void 0) {
@@ -379241,7 +378855,7 @@ async function addAsana(input2) {
379241
378855
  input2.write(`The bot user sees the Asana project ${project3.name}.`);
379242
378856
  const { revision: revision3 } = await addConnectorRevision({
379243
378857
  env: input2.env,
379244
- session: input2.session,
378858
+ session: input2.person,
379245
378859
  projectName: input2.projectName,
379246
378860
  write: input2.write,
379247
378861
  services: input2.services,
@@ -379323,7 +378937,7 @@ async function addJira(input2) {
379323
378937
  await registerCredential({ ...input2.session, ref: "jira", type: "static-secret", secretName }, input2.services.fetch);
379324
378938
  const { revision: revision3 } = await addConnectorRevision({
379325
378939
  env: input2.env,
379326
- session: input2.session,
378940
+ session: input2.person,
379327
378941
  projectName: input2.projectName,
379328
378942
  write: input2.write,
379329
378943
  services: input2.services,
@@ -379372,7 +378986,7 @@ async function addLinear(input2) {
379372
378986
  await registerCredential({ ...input2.session, ref: "linear", type: "static-secret", secretName }, input2.services.fetch);
379373
378987
  const { revision: revision3 } = await addConnectorRevision({
379374
378988
  env: input2.env,
379375
- session: input2.session,
378989
+ session: input2.person,
379376
378990
  projectName: input2.projectName,
379377
378991
  write: input2.write,
379378
378992
  services: input2.services,
@@ -381320,7 +380934,6 @@ function firstProjectStep() {
381320
380934
  async run(context, progress) {
381321
380935
  let project3 = progress.current().project;
381322
380936
  if (project3 === void 0) return { status: "done", note: NO_FIRST_PROJECT_NOTE };
381323
- const session = await context.adminSession();
381324
380937
  context.surface?.card(projectCard({ name: project3.name, revision: project3.revision }));
381325
380938
  if (project3.channelId === void 0) {
381326
380939
  const slack = progress.current().slack;
@@ -381329,8 +380942,9 @@ function firstProjectStep() {
381329
380942
  let bound2;
381330
380943
  try {
381331
380944
  const projectName = project3.name;
380945
+ const person4 = await context.personSession();
381332
380946
  bound2 = await addChannel({
381333
- bind: (channelId) => bindSlackChannel({ ...session, teamId: slack.teamId, channelId, projectName }, context.setup.fetch),
380947
+ bind: (channelId) => bindCompanyChannel({ ...person4, teamId: slack.teamId, channelId, projectName }, context.setup.fetch),
381334
380948
  botToken: await readSlackBotToken(context.secrets, context.env),
381335
380949
  teamId: slack.teamId,
381336
380950
  botUserId: slack.botUserId,
@@ -381383,8 +380997,9 @@ function connectorsStep() {
381383
380997
  if (done.has(type)) continue;
381384
380998
  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
380999
  if (!yes) continue;
381000
+ const person4 = await context.personSession();
381386
381001
  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 };
381002
+ 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
381003
  const result4 = type === "linear" ? await addLinear(base2) : type === "jira" ? await addJira(base2) : await addAsana(base2);
381389
381004
  const { warning: warning2 } = result4;
381390
381005
  const current = progress.current();
@@ -384126,6 +383741,10 @@ async function init(options, deps, services, session) {
384126
383741
  ...adminClaim === void 0 ? {} : { adminClaim }
384127
383742
  });
384128
383743
  };
383744
+ const personSession = async () => {
383745
+ const signedIn = await developerAccessToken({ home: services.home, tokenStore: setup.tokenStore, fetch: fetchImplementation }, env3);
383746
+ return { controlPlaneUrl: signedIn.entry.url, accessToken: signedIn.accessToken };
383747
+ };
384129
383748
  let deployment;
384130
383749
  const context = {
384131
383750
  env: env3,
@@ -384181,6 +383800,7 @@ async function init(options, deps, services, session) {
384181
383800
  runPrerequisites: () => runPrerequisites(),
384182
383801
  setup,
384183
383802
  adminSession,
383803
+ personSession,
384184
383804
  flags: options.finishFlags,
384185
383805
  cliInvocation: session.invocation,
384186
383806
  ...options.cloud === void 0 ? {} : { setupPageUrl: options.cloud.url, githubWaitMs: CLOUD_GITHUB_WAIT_MS }
@@ -384998,7 +384618,7 @@ ${toolLines2(offered)}`);
384998
384618
  await storeKey?.();
384999
384619
  const { revision: revision3 } = await addConnectorRevision({
385000
384620
  env: input2.env,
385001
- session: input2.session,
384621
+ session: input2.person,
385002
384622
  projectName: input2.projectName,
385003
384623
  write: input2.write,
385004
384624
  services: input2.services,
@@ -385201,6 +384821,10 @@ function projectOption(command5, what) {
385201
384821
  if (!AgentXNameSchema.safeParse(project3).success) throw agentXError("CONFIG_INVALID", `--project ${project3} is not a project name; use lower-case letters, digits and hyphens`);
385202
384822
  return project3;
385203
384823
  }
384824
+ async function openConnectorRun(context, command5) {
384825
+ const person4 = (await context.openPerson(command5)).session;
384826
+ return { ...await context.open(command5), person: person4 };
384827
+ }
385204
384828
  function registerSetupCommands(program2, context) {
385205
384829
  const project3 = program2.command("project").description("AgentX projects");
385206
384830
  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 +384843,6 @@ function registerSetupCommands(program2, context) {
385219
384843
  repositoryAccess: { settingsUrl: access10.settingsUrl, ...wait2 === void 0 ? {} : { wait: wait2 } }
385220
384844
  });
385221
384845
  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
384846
  `);
385230
384847
  });
385231
384848
  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 +384912,37 @@ function registerSetupCommands(program2, context) {
385295
384912
  const connectorAdd = connector.command("add").description("add a connector to a project");
385296
384913
  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
384914
  const projectName = projectOption(command5, "the project to connect Linear to");
385298
- const run2 = await context.open(command5);
384915
+ const run2 = await openConnectorRun(context, command5);
385299
384916
  const flags = definedEntries({
385300
384917
  linearTeam: options.linearTeam,
385301
384918
  linearKey: secretSource(options.linearKeyFile, options.linearKeyEnv)
385302
384919
  });
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 });
384920
+ 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
384921
  run2.print(result4, `Linear connected to ${projectName} (revision ${result4.revision})
385305
384922
  `);
385306
384923
  });
385307
384924
  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
384925
  const projectName = projectOption(command5, "the project to connect Jira to");
385309
- const run2 = await context.open(command5);
384926
+ const run2 = await openConnectorRun(context, command5);
385310
384927
  const flags = definedEntries({
385311
384928
  jiraSite: options.jiraSite,
385312
384929
  jiraProject: options.jiraProject,
385313
384930
  jiraToken: secretSource(options.jiraTokenFile, options.jiraTokenEnv)
385314
384931
  });
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 });
384932
+ 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
384933
  run2.print(result4, `Jira connected to ${projectName} (revision ${result4.revision})${result4.warning === void 0 ? "" : ", with the warning above"}
385317
384934
  `);
385318
384935
  });
385319
384936
  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
384937
  const projectName = projectOption(command5, "the project to connect Asana to");
385321
- const run2 = await context.open(command5);
384938
+ const run2 = await openConnectorRun(context, command5);
385322
384939
  const flags = definedEntries({
385323
384940
  asanaClientId: options.asanaClientId,
385324
384941
  asanaClientSecret: secretSource(options.asanaClientSecretFile, options.asanaClientSecretEnv),
385325
384942
  asanaBotEmail: options.asanaBotEmail,
385326
384943
  asanaProject: options.asanaProject
385327
384944
  });
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 });
384945
+ 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
384946
  run2.print(result4, `Asana connected to ${projectName} (revision ${result4.revision})
385330
384947
  `);
385331
384948
  });
@@ -385333,7 +384950,7 @@ function registerSetupCommands(program2, context) {
385333
384950
  const projectName = projectOption(command5, "the project to connect the MCP server to");
385334
384951
  const authKind = options.auth === "key" || options.auth === "oauth" ? options.auth : void 0;
385335
384952
  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);
384953
+ const run2 = await openConnectorRun(context, command5);
385337
384954
  const flags = definedEntries({
385338
384955
  endpoint: options.endpoint,
385339
384956
  name: options.name,
@@ -385352,7 +384969,7 @@ function registerSetupCommands(program2, context) {
385352
384969
  acknowledgeUnscopedWrites: options.acknowledgeUnscopedWrites,
385353
384970
  configFile: options.configFile
385354
384971
  });
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 });
384972
+ 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
384973
  run2.print(result4, `${result4.name} connected to ${projectName} with ${result4.tools} tools (revision ${result4.revision})
385357
384974
  `);
385358
384975
  });
@@ -388995,7 +388612,7 @@ function parseComment(body) {
388995
388612
  }
388996
388613
 
388997
388614
  // packages/cli/src/loop/exit-checks.ts
388998
- import { createHash as createHash38 } from "node:crypto";
388615
+ import { createHash as createHash36 } from "node:crypto";
388999
388616
  import { readFile as readFile25 } from "node:fs/promises";
389000
388617
  import { join as join27 } from "node:path";
389001
388618
 
@@ -389489,7 +389106,7 @@ async function readArtifact(worktree, issue2, artifact2) {
389489
389106
  return readFile25(join27(worktree, artifactPath(issue2, artifact2)), "utf8").catch(() => void 0);
389490
389107
  }
389491
389108
  function artifactDigest(text11) {
389492
- return createHash38("sha256").update(text11).digest("hex");
389109
+ return createHash36("sha256").update(text11).digest("hex");
389493
389110
  }
389494
389111
  function missingSections(text11, required4) {
389495
389112
  const sections2 = /* @__PURE__ */ new Map();
@@ -391481,7 +391098,7 @@ function createCliProgram(dependencies = {}) {
391481
391098
  return stored !== void 0 && stored.expiresAt > Date.now() ? stored : void 0;
391482
391099
  }
391483
391100
  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", `
391101
+ 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
391102
  ${ROOT_HELP_DOCS_LINES.join("\n")}`);
391486
391103
  program2.hook("preAction", (_program, actionCommand) => {
391487
391104
  const { env: env3 } = actionCommand.optsWithGlobals();
@@ -391681,16 +391298,8 @@ ${ROOT_HELP_DOCS_LINES.join("\n")}`);
391681
391298
  });
391682
391299
  const admin = program2.command("admin").description("administrator workflows");
391683
391300
  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) => {
391301
+ 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
391302
  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
391303
  const parsedDefinition = await projectFromFile(options.file, globals.allowLoopback);
391695
391304
  const modelChecked = await checkModelsForRegistration({
391696
391305
  definition: parsedDefinition,
@@ -391700,23 +391309,13 @@ ${ROOT_HELP_DOCS_LINES.join("\n")}`);
391700
391309
  acceptUncheckedModel: globals.acceptUncheckedModel
391701
391310
  });
391702
391311
  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
- }
391312
+ const signedIn = await developerAccessToken(developerSession(), developerEnv(command5));
391313
+ const result4 = await registerProject({ controlPlaneUrl: signedIn.entry.url, accessToken: signedIn.accessToken, definition }, services.fetchImplementation);
391715
391314
  try {
391716
391315
  const enrollment = await recordRegisteredLoopEnrollment({
391717
391316
  home,
391718
391317
  env: globals.env,
391719
- controlPlaneUrl: settings.controlPlaneUrl,
391318
+ controlPlaneUrl: signedIn.entry.url,
391720
391319
  definition,
391721
391320
  response: result4,
391722
391321
  ...dependencies.loop?.exec === void 0 ? {} : { exec: dependencies.loop.exec }
@@ -391771,7 +391370,7 @@ ${ROOT_HELP_DOCS_LINES.join("\n")}`);
391771
391370
  return (question) => askToApply(question, { input: stdin, output: output2, signals: process });
391772
391371
  };
391773
391372
  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) => {
391373
+ 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
391374
  const globals = globalOptions2(command5);
391776
391375
  const projectName = options.project ?? globals.project;
391777
391376
  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 +391378,22 @@ ${ROOT_HELP_DOCS_LINES.join("\n")}`);
391779
391378
  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
391379
  const developer = options.developer?.trim();
391781
391380
  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");
391381
+ 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
391382
  }
391784
391383
  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");
391384
+ 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
391385
  }
391787
391386
  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) => {
391387
+ const answer2 = await projectAccessChange(
391388
+ developerSession(),
391389
+ developerEnv(command5),
391390
+ { action, project: project3.data, developer },
391391
+ { tell: (line21) => {
391797
391392
  services.stderr.write(`${line21}
391798
391393
  `);
391799
- }
391800
- }, services.fetchImplementation);
391801
- services.stdout.write(formatSuccess({ outcome: result4.outcome, changeId: result4.change.changeId }, globals.json));
391394
+ }, confirm }
391395
+ );
391396
+ services.stdout.write(globals.json ? formatSuccess({ env: answer2.env, url: answer2.url, ...answer2.data }, true) : answer2.text);
391802
391397
  });
391803
391398
  }
391804
391399
  async function applySignInClient(command5, clientId, build2, secret, options) {
@@ -391929,12 +391524,6 @@ ${list3.invites.length === 0 ? "No invite codes.\n" : `${list3.invites.map(descr
391929
391524
  services.stdout.write(formatSuccess({ outcome: result4.outcome, changeId: result4.change.changeId, selfServe: state3 === "on" ? "open" : "closed" }, globals.json));
391930
391525
  });
391931
391526
  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
391527
  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
391528
  const globals = globalOptions2(command5);
391940
391529
  const { settings, accessToken } = await authenticate(globals, services.tokenStore);
@@ -391947,18 +391536,6 @@ ${list3.invites.length === 0 ? "No invite codes.\n" : `${list3.invites.map(descr
391947
391536
  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
391537
  services.stdout.write(formatSuccess(globals.json ? result4 : plain5, globals.json));
391949
391538
  });
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
391539
  const adminCredential = admin.command("credential").description("register connector credentials stored in Secrets Manager under agentx/connectors/ or agentx/<env>/connectors/");
391963
391540
  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
391541
  const globals = globalOptions2(command5);
@@ -392072,9 +391649,8 @@ ${url2}
392072
391649
  throw agentXError("CONFIG_INVALID", "--task must be a task ID, such as 44444444-4444-4444-8444-444444444444; agentx admin turns export shows task IDs");
392073
391650
  }
392074
391651
  const globals = globalOptions2(command5);
392075
- const { settings, accessToken } = await authenticate(globals, services.tokenStore);
392076
- const result4 = await setTaskShareMode({ controlPlaneUrl: settings.controlPlaneUrl, accessToken, taskId: options.task, mode: options.mode }, services.fetchImplementation);
392077
- services.stdout.write(formatSuccess(result4, globals.json));
391652
+ const answer2 = await setTaskShareMode(developerSession(), developerEnv(command5), { taskId: options.task, mode: options.mode });
391653
+ services.stdout.write(globals.json ? formatSuccess({ env: answer2.env, url: answer2.url, ...answer2.data }, true) : answer2.text);
392078
391654
  });
392079
391655
  admin.command("changes").description("list admin change records (kept 30 days): who asked, the change, how it was confirmed and how it ended; --json writes JSON Lines").requiredOption("--since <duration>", "how far back, such as 30m, 12h or 7d (at most 30d)").action(async (options, command5) => {
392080
391656
  const globals = globalOptions2(command5);