@mrrlin-dev/mcp 0.4.158 → 0.4.160

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/bin.cjs +892 -321
  2. package/package.json +1 -1
package/dist/bin.cjs CHANGED
@@ -21565,7 +21565,7 @@ __export(install_public_mcp_exports, {
21565
21565
  });
21566
21566
  async function pathExists5(target) {
21567
21567
  try {
21568
- await import_promises16.default.access(target);
21568
+ await import_promises17.default.access(target);
21569
21569
  return true;
21570
21570
  } catch {
21571
21571
  return false;
@@ -21573,8 +21573,8 @@ async function pathExists5(target) {
21573
21573
  }
21574
21574
  async function writeAtomic(targetPath, content) {
21575
21575
  const tempPath = `${targetPath}.${Date.now()}.tmp`;
21576
- await import_promises16.default.writeFile(tempPath, content, { mode: 384 });
21577
- await import_promises16.default.rename(tempPath, targetPath);
21576
+ await import_promises17.default.writeFile(tempPath, content, { mode: 384 });
21577
+ await import_promises17.default.rename(tempPath, targetPath);
21578
21578
  }
21579
21579
  function renderTomlBlock(serverId, expected) {
21580
21580
  let tomlStr = `
@@ -21597,7 +21597,7 @@ async function installPublicMcpServerToConfigs(serverId, expected) {
21597
21597
  const claudePath = import_node_path42.default.join(homeDir, ".claude.json");
21598
21598
  if (await pathExists5(claudePath)) {
21599
21599
  try {
21600
- const content = await import_promises16.default.readFile(claudePath, "utf8");
21600
+ const content = await import_promises17.default.readFile(claudePath, "utf8");
21601
21601
  const parsed = JSON.parse(content);
21602
21602
  if (!parsed.mcpServers) parsed.mcpServers = {};
21603
21603
  parsed.mcpServers[serverId] = expected;
@@ -21611,7 +21611,7 @@ async function installPublicMcpServerToConfigs(serverId, expected) {
21611
21611
  const codexPath = import_node_path42.default.join(homeDir, ".codex", "config.toml");
21612
21612
  if (await pathExists5(codexPath)) {
21613
21613
  try {
21614
- const content = await import_promises16.default.readFile(codexPath, "utf8");
21614
+ const content = await import_promises17.default.readFile(codexPath, "utf8");
21615
21615
  const parsed = toml4.parse(content);
21616
21616
  if (!parsed.mcp_servers?.[serverId]) {
21617
21617
  const appended = content.replace(/\n$/, "") + renderTomlBlock(serverId, expected);
@@ -21623,14 +21623,14 @@ async function installPublicMcpServerToConfigs(serverId, expected) {
21623
21623
  console.error(`Failed to inject MCP server into ${codexPath}`, e);
21624
21624
  }
21625
21625
  } else {
21626
- await import_promises16.default.mkdir(import_node_path42.default.dirname(codexPath), { recursive: true, mode: 448 }).catch(() => {
21626
+ await import_promises17.default.mkdir(import_node_path42.default.dirname(codexPath), { recursive: true, mode: 448 }).catch(() => {
21627
21627
  });
21628
21628
  await writeAtomic(codexPath, renderTomlBlock(serverId, expected).trim() + "\n");
21629
21629
  }
21630
21630
  const agyPath = import_node_path42.default.join(homeDir, ".gemini", "antigravity", "mcp_config.json");
21631
21631
  if (await pathExists5(agyPath)) {
21632
21632
  try {
21633
- const content = await import_promises16.default.readFile(agyPath, "utf8");
21633
+ const content = await import_promises17.default.readFile(agyPath, "utf8");
21634
21634
  const parsed = JSON.parse(content);
21635
21635
  if (!parsed.mcpServers) parsed.mcpServers = {};
21636
21636
  parsed.mcpServers[serverId] = expected;
@@ -21639,16 +21639,16 @@ async function installPublicMcpServerToConfigs(serverId, expected) {
21639
21639
  console.error(`Failed to inject MCP server into ${agyPath}`, e);
21640
21640
  }
21641
21641
  } else {
21642
- await import_promises16.default.mkdir(import_node_path42.default.dirname(agyPath), { recursive: true, mode: 448 }).catch(() => {
21642
+ await import_promises17.default.mkdir(import_node_path42.default.dirname(agyPath), { recursive: true, mode: 448 }).catch(() => {
21643
21643
  });
21644
21644
  await writeAtomic(agyPath, JSON.stringify({ mcpServers: { [serverId]: expected } }, null, 2) + "\n");
21645
21645
  }
21646
21646
  }
21647
- var import_promises16, import_node_os21, import_node_path42, toml4;
21647
+ var import_promises17, import_node_os21, import_node_path42, toml4;
21648
21648
  var init_install_public_mcp = __esm({
21649
21649
  "src/install-public-mcp.ts"() {
21650
21650
  "use strict";
21651
- import_promises16 = __toESM(require("node:fs/promises"), 1);
21651
+ import_promises17 = __toESM(require("node:fs/promises"), 1);
21652
21652
  import_node_os21 = __toESM(require("node:os"), 1);
21653
21653
  import_node_path42 = __toESM(require("node:path"), 1);
21654
21654
  toml4 = __toESM(require_toml(), 1);
@@ -22796,16 +22796,28 @@ async function installClaude(options) {
22796
22796
  }
22797
22797
 
22798
22798
  // src/install-agy.ts
22799
- var import_promises9 = __toESM(require("node:fs/promises"), 1);
22799
+ var import_promises10 = __toESM(require("node:fs/promises"), 1);
22800
22800
  var import_node_os13 = __toESM(require("node:os"), 1);
22801
22801
  var import_node_path24 = __toESM(require("node:path"), 1);
22802
22802
 
22803
22803
  // src/tools.ts
22804
22804
  var import_node_crypto15 = require("node:crypto");
22805
- var import_promises8 = require("node:fs/promises");
22805
+ var import_promises9 = require("node:fs/promises");
22806
22806
  var import_node_path23 = __toESM(require("node:path"), 1);
22807
22807
  var import_node_os12 = __toESM(require("node:os"), 1);
22808
22808
 
22809
+ // ../../packages/schemas/dist/canonical-json.js
22810
+ function canonicalJson(value) {
22811
+ if (value === null || typeof value !== "object") {
22812
+ return JSON.stringify(value) ?? "null";
22813
+ }
22814
+ if (Array.isArray(value)) {
22815
+ return `[${value.map((item) => canonicalJson(item === void 0 ? null : item)).join(",")}]`;
22816
+ }
22817
+ const entries = Object.entries(value).filter(([, item]) => item !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
22818
+ return `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${canonicalJson(item)}`).join(",")}}`;
22819
+ }
22820
+
22809
22821
  // ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js
22810
22822
  var external_exports = {};
22811
22823
  __export(external_exports, {
@@ -37610,7 +37622,19 @@ var openApiOperationIds = {
37610
37622
  finalizeCapabilityInvocation: "finalizeCapabilityInvocation",
37611
37623
  getCapabilityPermit: "getCapabilityPermit",
37612
37624
  getCapabilityInvocation: "getCapabilityInvocation",
37613
- reconcilePendingCapabilityInvocations: "reconcilePendingCapabilityInvocations"
37625
+ reconcilePendingCapabilityInvocations: "reconcilePendingCapabilityInvocations",
37626
+ mintIntegrationSetupTicket: "mintIntegrationSetupTicket",
37627
+ redeemIntegrationSetupTicket: "redeemIntegrationSetupTicket",
37628
+ listIntegrationBindings: "listIntegrationBindings",
37629
+ getIntegrationBinding: "getIntegrationBinding",
37630
+ upsertIntegrationBinding: "upsertIntegrationBinding",
37631
+ deleteIntegrationBinding: "deleteIntegrationBinding",
37632
+ preparePublishAttempt: "preparePublishAttempt",
37633
+ getPublishAttempt: "getPublishAttempt",
37634
+ claimPublishDispatch: "claimPublishDispatch",
37635
+ renewPublishLease: "renewPublishLease",
37636
+ recordPublishSubmission: "recordPublishSubmission",
37637
+ finalizePublishAttempt: "finalizePublishAttempt"
37614
37638
  };
37615
37639
 
37616
37640
  // ../../packages/schemas/dist/token-keys.js
@@ -38610,6 +38634,297 @@ var manualTaskClosureRequestSchema = external_exports.object({
38610
38634
  // ../../packages/schemas/dist/report-auth.js
38611
38635
  var encoder2 = new TextEncoder();
38612
38636
 
38637
+ // ../../packages/schemas/dist/integration-connections.js
38638
+ var IntegrationCatalogSourceSchema = external_exports.enum(["mcp_registry", "manual", "curated"]);
38639
+ var IntegrationCatalogPackageSchema = external_exports.object({
38640
+ registry: external_exports.enum(["npm", "pypi", "oci"]),
38641
+ name: external_exports.string().min(1),
38642
+ version: external_exports.string().min(1)
38643
+ });
38644
+ var IntegrationCatalogInputSchema = external_exports.object({
38645
+ name: external_exports.string().min(1),
38646
+ type: external_exports.enum(["string", "secret"]),
38647
+ description: external_exports.string().optional(),
38648
+ required: external_exports.boolean().default(true)
38649
+ });
38650
+ var IntegrationCatalogEntrySchema = external_exports.object({
38651
+ source: IntegrationCatalogSourceSchema,
38652
+ name: external_exports.string().min(1),
38653
+ version: external_exports.string().min(1),
38654
+ description: external_exports.string().optional(),
38655
+ homepage: external_exports.string().url().optional(),
38656
+ repository: external_exports.string().url().optional(),
38657
+ transports: external_exports.array(external_exports.enum(["streamable_http", "stdio"])).min(1),
38658
+ packages: external_exports.array(IntegrationCatalogPackageSchema).optional(),
38659
+ inputs: external_exports.array(IntegrationCatalogInputSchema).optional(),
38660
+ status: external_exports.enum(["active", "deprecated", "deleted"]).default("active"),
38661
+ fetchedAt: external_exports.string().datetime()
38662
+ });
38663
+ var IntegrationCatalogQuerySchema = external_exports.object({
38664
+ query: external_exports.string().min(3).optional(),
38665
+ cursor: external_exports.string().optional(),
38666
+ limit: external_exports.number().int().min(1).max(50).default(50)
38667
+ });
38668
+ var IntegrationCatalogResponseSchema = external_exports.object({
38669
+ entries: external_exports.array(IntegrationCatalogEntrySchema),
38670
+ nextCursor: external_exports.string().optional(),
38671
+ stale: external_exports.boolean().default(false),
38672
+ staleTimestamp: external_exports.string().datetime().optional()
38673
+ });
38674
+ var ConnectionTransportSchema = external_exports.enum(["streamable_http", "stdio"]);
38675
+ var ConnectionOriginSchema = external_exports.enum(["catalog", "manual", "native_import", "legacy"]);
38676
+ var ConnectionRecordSchema = external_exports.object({
38677
+ id: external_exports.string().uuid(),
38678
+ legacyServerId: external_exports.string().optional(),
38679
+ bridgeInstallationId: external_exports.string().min(1),
38680
+ transport: ConnectionTransportSchema,
38681
+ endpoint: external_exports.string().url().optional(),
38682
+ command: external_exports.string().optional(),
38683
+ args: external_exports.array(external_exports.string()).optional(),
38684
+ envKeys: external_exports.array(external_exports.string()).optional(),
38685
+ inputRefs: external_exports.record(external_exports.string(), external_exports.string()).optional(),
38686
+ origin: ConnectionOriginSchema,
38687
+ configRevision: external_exports.number().int().min(1).default(1),
38688
+ authorizationGeneration: external_exports.number().int().min(1).default(1),
38689
+ createdAt: external_exports.string().datetime(),
38690
+ updatedAt: external_exports.string().datetime()
38691
+ });
38692
+ var IntegrationConnectionBindingSchema = external_exports.object({
38693
+ projectSlug: external_exports.string().min(1),
38694
+ serverId: external_exports.string().min(1),
38695
+ connectionId: external_exports.string().uuid(),
38696
+ bridgeInstallationId: external_exports.string().min(1),
38697
+ configRevision: external_exports.number().int().min(1),
38698
+ authorizationGeneration: external_exports.number().int().min(1),
38699
+ configDigest: external_exports.string().regex(/^[0-9a-f]{64}$/),
38700
+ bindingRevision: external_exports.number().int().min(1).default(1),
38701
+ ownerActor: external_exports.string().min(1),
38702
+ createdAt: external_exports.string().datetime(),
38703
+ updatedAt: external_exports.string().datetime()
38704
+ });
38705
+ var IntegrationConnectionBindingListSchema = external_exports.array(IntegrationConnectionBindingSchema);
38706
+ var IntegrationSetupActionSchema = external_exports.enum([
38707
+ "configure",
38708
+ "import",
38709
+ "probe",
38710
+ "oauth_start",
38711
+ "disconnect",
38712
+ "export",
38713
+ "binding_commit",
38714
+ "vault_unlock",
38715
+ "vault_lock",
38716
+ "vault_rotate"
38717
+ ]);
38718
+ var IntegrationSetupTicketRequestSchema = external_exports.object({
38719
+ action: IntegrationSetupActionSchema,
38720
+ bridgeInstallationId: external_exports.string().min(1),
38721
+ requestDigest: external_exports.string().regex(/^[0-9a-f]{64}$/)
38722
+ });
38723
+ var IntegrationSetupTicketRecordSchema = external_exports.object({
38724
+ id: external_exports.string().uuid(),
38725
+ projectSlug: external_exports.string().min(1),
38726
+ ownerUserId: external_exports.string().min(1),
38727
+ bridgeInstallationId: external_exports.string().min(1),
38728
+ action: IntegrationSetupActionSchema,
38729
+ requestDigest: external_exports.string().regex(/^[0-9a-f]{64}$/),
38730
+ ticketHash: external_exports.string().regex(/^[0-9a-f]{64}$/),
38731
+ expiresAt: external_exports.string().datetime(),
38732
+ consumedAt: external_exports.string().datetime().nullable(),
38733
+ createdAt: external_exports.string().datetime()
38734
+ });
38735
+ var IntegrationSetupTicketIssuedSchema = external_exports.object({
38736
+ ticket: external_exports.string().regex(/^[0-9a-f]{64}$/),
38737
+ record: IntegrationSetupTicketRecordSchema
38738
+ });
38739
+ var UpsertConnectionBindingRequestSchema = external_exports.object({
38740
+ connectionId: external_exports.string().uuid(),
38741
+ bridgeInstallationId: external_exports.string().min(1),
38742
+ configRevision: external_exports.number().int().min(1),
38743
+ authorizationGeneration: external_exports.number().int().min(1),
38744
+ configDigest: external_exports.string().regex(/^[0-9a-f]{64}$/),
38745
+ expectedBindingRevision: external_exports.number().int().min(1).optional()
38746
+ });
38747
+ var IntegrationSetupTicketRedeemSchema = external_exports.object({
38748
+ ticket: external_exports.string().regex(/^[0-9a-f]{64}$/),
38749
+ action: IntegrationSetupActionSchema,
38750
+ requestDigest: external_exports.string().regex(/^[0-9a-f]{64}$/),
38751
+ signature: external_exports.string().min(1)
38752
+ });
38753
+ var IntegrationReadinessStateSchema = external_exports.enum([
38754
+ "unconfigured",
38755
+ "configured",
38756
+ "authorized",
38757
+ "needs_auth",
38758
+ "vault_locked",
38759
+ "probe_failed",
38760
+ "ready",
38761
+ "degraded",
38762
+ "disabled"
38763
+ ]);
38764
+ var IntegrationReadinessSchema = external_exports.object({
38765
+ serverId: external_exports.string().min(1),
38766
+ connectionId: external_exports.string().uuid().optional(),
38767
+ state: IntegrationReadinessStateSchema,
38768
+ configured: external_exports.boolean(),
38769
+ authorized: external_exports.boolean(),
38770
+ roleReady: external_exports.boolean(),
38771
+ projectGranted: external_exports.boolean(),
38772
+ lastCheckedAt: external_exports.string().datetime().optional(),
38773
+ lastError: external_exports.object({
38774
+ code: external_exports.string(),
38775
+ message: external_exports.string(),
38776
+ repairAction: external_exports.string().optional()
38777
+ }).optional()
38778
+ });
38779
+
38780
+ // ../../packages/schemas/dist/vercel-publishing.js
38781
+ var VercelEnvironmentSchema = external_exports.enum(["preview", "production"]);
38782
+ var VercelSourceModeSchema = external_exports.enum(["git_commit", "inline_manifest"]);
38783
+ var VercelTargetRefV1Schema = external_exports.object({
38784
+ provider: external_exports.literal("vercel"),
38785
+ profileVersion: external_exports.literal("vercel.v1"),
38786
+ bindingId: external_exports.string().uuid(),
38787
+ bindingRevision: external_exports.number().int().min(1),
38788
+ teamId: external_exports.string().min(1),
38789
+ projectId: external_exports.string().min(1),
38790
+ projectName: external_exports.string().optional(),
38791
+ environment: VercelEnvironmentSchema,
38792
+ rootDirectory: external_exports.string().optional(),
38793
+ buildSettingsDigest: external_exports.string().min(1),
38794
+ customDomain: external_exports.string().optional()
38795
+ });
38796
+ var VercelSourceFileEntrySchema = external_exports.object({
38797
+ path: external_exports.string().min(1),
38798
+ size: external_exports.number().int().min(0),
38799
+ sha256: external_exports.string().regex(/^[0-9a-f]{64}$/),
38800
+ encoding: external_exports.enum(["utf8", "base64"])
38801
+ });
38802
+ var VercelSourceManifestV1Schema = external_exports.object({
38803
+ mode: VercelSourceModeSchema,
38804
+ gitCommitSha: external_exports.string().regex(/^[0-9a-f]{40}$/).optional(),
38805
+ gitRepository: external_exports.string().optional(),
38806
+ files: external_exports.array(VercelSourceFileEntrySchema).optional(),
38807
+ totalBytes: external_exports.number().int().min(0),
38808
+ sourceDigest: external_exports.string().regex(/^[0-9a-f]{64}$/)
38809
+ });
38810
+ var VercelPreparedEnvelopeV1Schema = external_exports.object({
38811
+ project: external_exports.string().min(1),
38812
+ task: external_exports.string().min(1),
38813
+ run: external_exports.string().min(1),
38814
+ logicalOperationId: external_exports.string().min(1),
38815
+ operation: external_exports.enum(["publish_preview", "publish_release", "publish_observe"]),
38816
+ connectionBindingRevision: external_exports.number().int().min(1),
38817
+ authorizationGeneration: external_exports.number().int().min(1),
38818
+ routeRevision: external_exports.number().int().min(1),
38819
+ toolName: external_exports.string().min(1),
38820
+ toolSchemaDigest: external_exports.string().regex(/^[0-9a-f]{64}$/),
38821
+ adapterVersion: external_exports.string().min(1),
38822
+ teamId: external_exports.string().min(1),
38823
+ projectId: external_exports.string().min(1),
38824
+ environment: VercelEnvironmentSchema,
38825
+ targetFingerprint: external_exports.string().regex(/^[0-9a-f]{64}$/),
38826
+ sourceDigest: external_exports.string().regex(/^[0-9a-f]{64}$/),
38827
+ canonicalToolArgumentsDigest: external_exports.string().regex(/^[0-9a-f]{64}$/)
38828
+ });
38829
+ var PublishAttemptStatusSchema = external_exports.enum([
38830
+ "prepared",
38831
+ "dispatching",
38832
+ "submitted",
38833
+ "completed",
38834
+ "failed",
38835
+ "unknown"
38836
+ ]);
38837
+ var PublishAttemptRecordV1Schema = external_exports.object({
38838
+ id: external_exports.string().uuid().optional(),
38839
+ projectSlug: external_exports.string().min(1),
38840
+ runId: external_exports.string().min(1),
38841
+ environment: VercelEnvironmentSchema,
38842
+ logicalOperationId: external_exports.string().min(1),
38843
+ attemptNumber: external_exports.number().int().min(1),
38844
+ preparedEnvelopeDigest: external_exports.string().regex(/^[0-9a-f]{64}$/),
38845
+ preparedEnvelope: VercelPreparedEnvelopeV1Schema,
38846
+ status: PublishAttemptStatusSchema,
38847
+ leaseOwner: external_exports.string().nullable().optional(),
38848
+ leaseExpiresAt: external_exports.string().datetime().nullable().optional(),
38849
+ deploymentId: external_exports.string().nullable().optional(),
38850
+ publicUrl: external_exports.string().url().nullable().optional(),
38851
+ errorCode: external_exports.string().nullable().optional(),
38852
+ errorMessage: external_exports.string().nullable().optional(),
38853
+ invocationId: external_exports.string().uuid().nullable().optional(),
38854
+ evidenceDigest: external_exports.string().nullable().optional(),
38855
+ createdAt: external_exports.string().datetime(),
38856
+ updatedAt: external_exports.string().datetime()
38857
+ });
38858
+ var VercelPublishEvidenceV1Schema = external_exports.object({
38859
+ deploymentId: external_exports.string().min(1),
38860
+ url: external_exports.string().url(),
38861
+ sourceDigest: external_exports.string().regex(/^[0-9a-f]{64}$/),
38862
+ targetFingerprint: external_exports.string().regex(/^[0-9a-f]{64}$/),
38863
+ attemptDigest: external_exports.string().regex(/^[0-9a-f]{64}$/),
38864
+ permitId: external_exports.string().uuid(),
38865
+ verifierId: external_exports.string().min(1),
38866
+ verifiedAt: external_exports.string().datetime(),
38867
+ anonymousCheckPassed: external_exports.boolean(),
38868
+ markerDigest: external_exports.string().regex(/^[0-9a-f]{64}$/).optional()
38869
+ });
38870
+ var PreparePublishAttemptRequestSchema = external_exports.object({
38871
+ runId: external_exports.string().min(1),
38872
+ environment: VercelEnvironmentSchema,
38873
+ logicalOperationId: external_exports.string().min(1),
38874
+ preparedEnvelope: VercelPreparedEnvelopeV1Schema
38875
+ });
38876
+ var ClaimPublishDispatchRequestSchema = external_exports.object({
38877
+ runId: external_exports.string().min(1),
38878
+ environment: VercelEnvironmentSchema,
38879
+ logicalOperationId: external_exports.string().min(1),
38880
+ attemptNumber: external_exports.number().int().min(1),
38881
+ expectedEnvelopeDigest: external_exports.string().regex(/^[0-9a-f]{64}$/),
38882
+ leaseOwner: external_exports.string().min(1),
38883
+ leaseDurationSeconds: external_exports.number().int().min(1).default(60),
38884
+ invocationId: external_exports.string().uuid().optional()
38885
+ });
38886
+ var RenewPublishLeaseRequestSchema = external_exports.object({
38887
+ leaseOwner: external_exports.string().min(1),
38888
+ leaseDurationSeconds: external_exports.number().int().min(1).default(60)
38889
+ });
38890
+ var RecordPublishSubmissionRequestSchema = external_exports.object({
38891
+ leaseOwner: external_exports.string().min(1),
38892
+ deploymentId: external_exports.string().min(1)
38893
+ });
38894
+ var FinalizePublishAttemptRequestSchema = external_exports.object({
38895
+ status: external_exports.enum(["completed", "failed"]),
38896
+ publicUrl: external_exports.string().url().optional(),
38897
+ errorCode: external_exports.string().optional(),
38898
+ errorMessage: external_exports.string().optional(),
38899
+ evidenceDigest: external_exports.string().optional(),
38900
+ leaseOwner: external_exports.string().min(1)
38901
+ }).superRefine((data, ctx) => {
38902
+ if (data.status === "failed" && data.publicUrl !== void 0) {
38903
+ ctx.addIssue({
38904
+ code: external_exports.ZodIssueCode.custom,
38905
+ path: ["publicUrl"],
38906
+ message: "publicUrl cannot be specified when finalizing as failed"
38907
+ });
38908
+ }
38909
+ });
38910
+
38911
+ // ../../packages/schemas/dist/integration-tool-profiles.js
38912
+ var ProfileOperationClassSchema = external_exports.enum(["read", "mutation"]);
38913
+ var ToolProfileOperationSchema = external_exports.object({
38914
+ logicalOperationId: external_exports.string().min(1),
38915
+ wireToolName: external_exports.string().min(1),
38916
+ operationClass: ProfileOperationClassSchema,
38917
+ canonicalSchemaDigest: external_exports.string().regex(/^[0-9a-f]{64}$/),
38918
+ description: external_exports.string().optional()
38919
+ });
38920
+ var IntegrationToolProfileSchema = external_exports.object({
38921
+ profileId: external_exports.string().min(1),
38922
+ adapterVersion: external_exports.string().min(1),
38923
+ endpointAuthority: external_exports.string().min(1),
38924
+ allowedPathPrefix: external_exports.string().optional(),
38925
+ operations: external_exports.record(external_exports.string(), ToolProfileOperationSchema)
38926
+ });
38927
+
38613
38928
  // ../../packages/schemas/dist/index.js
38614
38929
  var mrrlinTaskStatusSchema = external_exports.enum([
38615
38930
  "backlog",
@@ -39804,6 +40119,7 @@ var mrrlinExecutionRunSchema = external_exports.object({
39804
40119
  claimedAt: external_exports.string().datetime().nullable(),
39805
40120
  codeExecution: external_exports.boolean(),
39806
40121
  createdAt: external_exports.string().datetime(),
40122
+ deployApprovalGeneration: external_exports.number().int().nonnegative().optional(),
39807
40123
  devEnvUrl: external_exports.string().min(1).nullable(),
39808
40124
  devRunUrl: external_exports.string().min(1).nullable(),
39809
40125
  devWorkflowId: external_exports.number().int().positive().nullable(),
@@ -40412,6 +40728,35 @@ var wakeDirectorResponseSchema = external_exports.object({
40412
40728
  var mrrlinInboxItemKindSchema = external_exports.enum(["proposal", "check_in", "question", "handoff", "info", "completed"]);
40413
40729
  var mrrlinInboxItemStatusSchema = external_exports.enum(["pending", "approved", "rejected", "acknowledged"]);
40414
40730
  var mrrlinInboxItemIdSchema = external_exports.string().regex(/^II-[A-Za-z0-9._-]+$/);
40731
+ var ROLLBACK_RECONCILIATION_INBOX_PREFIX = "II-ROLLBACK-RECONCILE-";
40732
+ var DEPLOY_APPROVAL_INBOX_PREFIX = "II-deploy-approve-";
40733
+ var DEPLOY_GRACE_INBOX_PREFIX = "II-grace-cancel-";
40734
+ var CAPABILITY_INVOCATION_IN_FLIGHT_MS = 5 * 6e4;
40735
+ function deployApprovalInboxBody(env, runId, taskId, legacyTitle, generation = 0) {
40736
+ const attempt = generation === 0 ? "" : `, attempt ${generation + 1}`;
40737
+ return `Ready to deploy to ${env}? (task ${taskId}${legacyTitle === void 0 ? "" : ` \u2014 ${legacyTitle}`}, run ${runId}${attempt})`;
40738
+ }
40739
+ function deployApprovalInboxOptions(env, legacy = false) {
40740
+ return [
40741
+ { label: "Approve", answer: "Approve", description: `Deploy to ${env}`, recommended: true },
40742
+ { label: "Reject", answer: "Reject", description: legacy ? "Do not deploy \u2014 hand it off to me" : "Stop this deployment" }
40743
+ ];
40744
+ }
40745
+ function matchesDeployApprovalInboxQuestion(item, env, runId, task, generation = 0) {
40746
+ if (item.kind !== "question" || item.origin !== "deploy-gate" || item.taskId !== task.id)
40747
+ return false;
40748
+ const legacy = generation === 0 && item.body === deployApprovalInboxBody(env, runId, task.id, task.title);
40749
+ if (!legacy && item.body !== deployApprovalInboxBody(env, runId, task.id, void 0, generation))
40750
+ return false;
40751
+ const options = mrrlinInboxQuestionOptionsSchema.safeParse(item.questionOptions);
40752
+ if (!options.success || options.data.length !== 2)
40753
+ return false;
40754
+ const expected = deployApprovalInboxOptions(env, legacy);
40755
+ return options.data.every((option, index) => {
40756
+ const match = expected[index];
40757
+ return match !== void 0 && option.label === match.label && option.answer === match.answer && option.description === match.description && Boolean(option.recommended) === Boolean(match.recommended);
40758
+ });
40759
+ }
40415
40760
  var mrrlinInboxItemActionPayloadSchema = external_exports.object({
40416
40761
  actor: external_exports.string().min(1),
40417
40762
  provider: external_exports.string().min(1),
@@ -40493,7 +40838,8 @@ var mrrlinInboxItemSchema = external_exports.object({
40493
40838
  reason: external_exports.string().nullable().optional(),
40494
40839
  status: mrrlinInboxItemStatusSchema,
40495
40840
  taskId: mrrlinTaskIdSchema.nullable(),
40496
- taskTitle: external_exports.string().nullable()
40841
+ taskTitle: external_exports.string().nullable(),
40842
+ verifiedOperatorDecision: external_exports.boolean().optional()
40497
40843
  }).superRefine((value, context) => {
40498
40844
  if (value.kind !== "question" && value.questionOptions !== null) {
40499
40845
  context.addIssue({
@@ -40514,6 +40860,7 @@ var mrrlinInboxItemCreateSchema = external_exports.object({
40514
40860
  payloadDigest: external_exports.string().min(1).nullable().optional(),
40515
40861
  planId: mrrlinPlanIdSchema.nullable().optional(),
40516
40862
  questionOptions: mrrlinInboxQuestionOptionsSchema.nullable().optional(),
40863
+ rollbackInvocationId: external_exports.string().min(1).optional(),
40517
40864
  taskId: mrrlinTaskIdSchema.nullable().optional()
40518
40865
  }).superRefine((value, context) => {
40519
40866
  if (value.kind !== "question" && value.questionOptions != null) {
@@ -40526,7 +40873,7 @@ var mrrlinInboxItemCreateSchema = external_exports.object({
40526
40873
  });
40527
40874
  var mrrlinInboxItemDecideSchema = external_exports.object({
40528
40875
  answer: external_exports.string().min(1).optional(),
40529
- decidedBy: external_exports.string().min(1),
40876
+ decidedBy: external_exports.string().min(1).optional(),
40530
40877
  expectedPayloadDigest: external_exports.string().min(1).optional(),
40531
40878
  reason: external_exports.string().min(1).optional(),
40532
40879
  verdict: external_exports.enum(["approved", "rejected", "acknowledged"])
@@ -40737,9 +41084,12 @@ var issueCapabilityPermitRequestSchema = external_exports.object({
40737
41084
  serverId: capabilityServerIdSchema,
40738
41085
  capability: capabilityNameSchema,
40739
41086
  toolName: capabilityToolNameSchema,
40740
- operationClass: external_exports.enum(["read", "reversible", "irreversible"]),
41087
+ operation: capabilityOperationNameSchema.optional(),
41088
+ operationClass: external_exports.enum(["read", "reversible", "irreversible"]).optional(),
41089
+ payload: external_exports.object({ operation: capabilityOperationNameSchema }).passthrough().optional(),
40741
41090
  payloadDigest: external_exports.string().min(1),
40742
- ttlMs: external_exports.number().int().positive().optional()
41091
+ ttlMs: external_exports.number().int().positive().optional(),
41092
+ inboxDecisionId: external_exports.string().optional()
40743
41093
  });
40744
41094
  var issueCapabilityPermitResponseSchema = external_exports.object({
40745
41095
  data: CapabilityPermitSchema
@@ -40786,7 +41136,11 @@ var capabilityUseCreateSchema = external_exports.object({
40786
41136
  outcome: capabilityUseOutcomeSchema
40787
41137
  });
40788
41138
  var deliveryResolutionResponseSchema = external_exports.object({
40789
- data: external_exports.object({ route: CapabilityRouteSchema, verdict: CapabilityGateVerdictSchema })
41139
+ data: external_exports.object({
41140
+ route: CapabilityRouteSchema,
41141
+ verdict: CapabilityGateVerdictSchema,
41142
+ gateRevision: external_exports.string().optional()
41143
+ })
40790
41144
  });
40791
41145
  function resolveProjectClientScope(project) {
40792
41146
  const trimmedClient = project.clientName?.trim();
@@ -41550,8 +41904,8 @@ function createMrrlinClient(config2) {
41550
41904
  try {
41551
41905
  const url2 = appendQuery(`${projectPath(projectSlug)}/artifact-kinds/${encodeURIComponent(artifactKind)}/delivery-resolution`, { taskProjectSlug, operation, taskId });
41552
41906
  const body = await request(url2, { method: "POST" });
41553
- const { route, verdict } = deliveryResolutionResponseSchema.parse(body).data;
41554
- return { ok: true, route, verdict };
41907
+ const { route, verdict, gateRevision } = deliveryResolutionResponseSchema.parse(body).data;
41908
+ return { ok: true, route, verdict, ...gateRevision ? { gateRevision } : {} };
41555
41909
  } catch (error51) {
41556
41910
  if (error51 instanceof MrrlinApiError) {
41557
41911
  const reason = CAPABILITY_ROUTE_RESOLUTION_REASON_BY_CODE[error51.code];
@@ -41626,8 +41980,12 @@ function createMrrlinClient(config2) {
41626
41980
  const body = await request(`${projectPath(projectSlug)}/execution-runs/${encodeURIComponent(runId)}`);
41627
41981
  return executionRunResponseSchema.parse(body).data;
41628
41982
  },
41629
- async updateExecutionRun(projectSlug, runId, patch) {
41630
- const body = await request(`${projectPath(projectSlug)}/execution-runs/${encodeURIComponent(runId)}`, {
41983
+ async updateExecutionRun(projectSlug, runId, patch, options) {
41984
+ const url2 = appendQuery(`${projectPath(projectSlug)}/execution-runs/${encodeURIComponent(runId)}`, {
41985
+ expectedStatus: options?.expectedStatus,
41986
+ expectedDeployApprovalGeneration: options?.expectedDeployApprovalGeneration?.toString()
41987
+ });
41988
+ const body = await request(url2, {
41631
41989
  body: JSON.stringify(patch),
41632
41990
  headers: { "content-type": "application/json" },
41633
41991
  method: "PATCH"
@@ -42267,6 +42625,100 @@ function createMrrlinClient(config2) {
42267
42625
  return null;
42268
42626
  throw error51;
42269
42627
  }
42628
+ },
42629
+ async mintIntegrationSetupTicket(projectSlug, input) {
42630
+ const body = await request(`${projectPath(projectSlug)}/integration-setup-tickets`, {
42631
+ method: "POST",
42632
+ headers: { "content-type": "application/json" },
42633
+ body: JSON.stringify(input)
42634
+ });
42635
+ return IntegrationSetupTicketIssuedSchema.parse(body);
42636
+ },
42637
+ async redeemIntegrationSetupTicket(projectSlug, input) {
42638
+ const body = await request(`${projectPath(projectSlug)}/integration-setup-tickets/redeem`, {
42639
+ method: "POST",
42640
+ headers: { "content-type": "application/json" },
42641
+ body: JSON.stringify(input)
42642
+ });
42643
+ return IntegrationSetupTicketRecordSchema.parse(body);
42644
+ },
42645
+ async listIntegrationBindings(projectSlug) {
42646
+ const body = await request(`${projectPath(projectSlug)}/integration-bindings`);
42647
+ return IntegrationConnectionBindingListSchema.parse(body);
42648
+ },
42649
+ async getIntegrationBinding(projectSlug, serverId) {
42650
+ try {
42651
+ const body = await request(`${projectPath(projectSlug)}/integration-bindings/${encodeURIComponent(serverId)}`);
42652
+ return IntegrationConnectionBindingSchema.parse(body);
42653
+ } catch (error51) {
42654
+ if (error51 instanceof MrrlinApiError && error51.status === 404)
42655
+ return null;
42656
+ throw error51;
42657
+ }
42658
+ },
42659
+ async upsertIntegrationBinding(projectSlug, serverId, input) {
42660
+ const body = await request(`${projectPath(projectSlug)}/integration-bindings/${encodeURIComponent(serverId)}`, {
42661
+ method: "PUT",
42662
+ headers: { "content-type": "application/json" },
42663
+ body: JSON.stringify(input)
42664
+ });
42665
+ return IntegrationConnectionBindingSchema.parse(body);
42666
+ },
42667
+ async deleteIntegrationBinding(projectSlug, serverId) {
42668
+ const body = await request(`${projectPath(projectSlug)}/integration-bindings/${encodeURIComponent(serverId)}`, {
42669
+ method: "DELETE"
42670
+ });
42671
+ return Boolean(body?.success ?? true);
42672
+ },
42673
+ async preparePublishAttempt(projectSlug, input) {
42674
+ const body = await request(`${projectPath(projectSlug)}/publish-attempts`, {
42675
+ method: "POST",
42676
+ headers: { "content-type": "application/json" },
42677
+ body: JSON.stringify(input)
42678
+ });
42679
+ return PublishAttemptRecordV1Schema.parse(body);
42680
+ },
42681
+ async getPublishAttempt(projectSlug, attemptId) {
42682
+ try {
42683
+ const body = await request(`${projectPath(projectSlug)}/publish-attempts/${encodeURIComponent(attemptId)}`);
42684
+ return PublishAttemptRecordV1Schema.parse(body);
42685
+ } catch (error51) {
42686
+ if (error51 instanceof MrrlinApiError && error51.status === 404)
42687
+ return null;
42688
+ throw error51;
42689
+ }
42690
+ },
42691
+ async claimPublishDispatch(projectSlug, attemptId, input) {
42692
+ const body = await request(`${projectPath(projectSlug)}/publish-attempts/${encodeURIComponent(attemptId)}/claim`, {
42693
+ method: "POST",
42694
+ headers: { "content-type": "application/json" },
42695
+ body: JSON.stringify(input)
42696
+ });
42697
+ return PublishAttemptRecordV1Schema.parse(body);
42698
+ },
42699
+ async renewPublishLease(projectSlug, attemptId, input) {
42700
+ const body = await request(`${projectPath(projectSlug)}/publish-attempts/${encodeURIComponent(attemptId)}/renew`, {
42701
+ method: "POST",
42702
+ headers: { "content-type": "application/json" },
42703
+ body: JSON.stringify(input)
42704
+ });
42705
+ return PublishAttemptRecordV1Schema.parse(body);
42706
+ },
42707
+ async recordPublishSubmission(projectSlug, attemptId, input) {
42708
+ const body = await request(`${projectPath(projectSlug)}/publish-attempts/${encodeURIComponent(attemptId)}/submit`, {
42709
+ method: "POST",
42710
+ headers: { "content-type": "application/json" },
42711
+ body: JSON.stringify(input)
42712
+ });
42713
+ return PublishAttemptRecordV1Schema.parse(body);
42714
+ },
42715
+ async finalizePublishAttempt(projectSlug, attemptId, input) {
42716
+ const body = await request(`${projectPath(projectSlug)}/publish-attempts/${encodeURIComponent(attemptId)}/finalize`, {
42717
+ method: "POST",
42718
+ headers: { "content-type": "application/json" },
42719
+ body: JSON.stringify(input)
42720
+ });
42721
+ return PublishAttemptRecordV1Schema.parse(body);
42270
42722
  }
42271
42723
  };
42272
42724
  }
@@ -49502,6 +49954,7 @@ function resolveStateDir(env = process.env) {
49502
49954
 
49503
49955
  // src/delivery/index.ts
49504
49956
  var import_node_crypto5 = __toESM(require("node:crypto"), 1);
49957
+ var import_promises6 = require("node:timers/promises");
49505
49958
 
49506
49959
  // src/delivery/wiki.ts
49507
49960
  async function deliverToWiki(client, projectSlug, payload) {
@@ -54215,13 +54668,13 @@ var StreamableHTTPClientTransport = class {
54215
54668
  this.onerror?.(new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`));
54216
54669
  return;
54217
54670
  }
54218
- const delay2 = this._getNextReconnectionDelay(attemptCount);
54671
+ const delay3 = this._getNextReconnectionDelay(attemptCount);
54219
54672
  this._reconnectionTimeout = setTimeout(() => {
54220
54673
  this._startOrAuthSse(options).catch((error51) => {
54221
54674
  this.onerror?.(new Error(`Failed to reconnect SSE stream: ${error51 instanceof Error ? error51.message : String(error51)}`));
54222
54675
  this._scheduleReconnection(options, attemptCount + 1);
54223
54676
  });
54224
- }, delay2);
54677
+ }, delay3);
54225
54678
  }
54226
54679
  _handleSseStream(stream, options, isReconnectable) {
54227
54680
  if (!stream) {
@@ -55116,10 +55569,20 @@ function getPublishProvider(name) {
55116
55569
  }
55117
55570
 
55118
55571
  // src/delivery/index.ts
55119
- async function deliverThroughCapability(client, input) {
55120
- if (resolveKindCapability(input.artifactKind) === null) {
55572
+ async function deliverThroughCapability(client, rawInput) {
55573
+ if (resolveKindCapability(rawInput.artifactKind) === null) {
55121
55574
  return { ok: false, reason: "blocked_kind" };
55122
55575
  }
55576
+ let input;
55577
+ try {
55578
+ input = {
55579
+ ...rawInput,
55580
+ payload: JSON.parse(JSON.stringify(rawInput.payload ?? null)),
55581
+ dispatchPayload: rawInput.payload
55582
+ };
55583
+ } catch {
55584
+ return { ok: false, reason: "delivery_failed", message: "Capability payload is not JSON serializable." };
55585
+ }
55123
55586
  const operation = isRecord3(input.payload) ? input.payload.operation : void 0;
55124
55587
  if (typeof operation !== "string") {
55125
55588
  return {
@@ -55143,7 +55606,7 @@ async function deliverThroughCapability(client, input) {
55143
55606
  if (!resolution.ok) {
55144
55607
  return { ok: false, reason: resolution.reason, message: resolution.message };
55145
55608
  }
55146
- const { route, verdict } = resolution;
55609
+ const { route, verdict, gateRevision } = resolution;
55147
55610
  const resolvedToolName = typeof route.operations[operation] === "string" ? route.operations[operation] : null;
55148
55611
  if (resolvedToolName === null) {
55149
55612
  return {
@@ -55156,13 +55619,13 @@ async function deliverThroughCapability(client, input) {
55156
55619
  return proceedToDestination(client, route, resolvedToolName, input);
55157
55620
  }
55158
55621
  if (verdict === "ask_once") {
55159
- return handleAskOnce(client, route, resolvedToolName, input);
55622
+ return handleAskOnce(client, route, resolvedToolName, input, gateRevision);
55160
55623
  }
55161
55624
  if (verdict === "window") {
55162
- return handleWindow(client, route, resolvedToolName, input);
55625
+ return handleWindow(client, route, resolvedToolName, input, gateRevision);
55163
55626
  }
55164
55627
  if (verdict === "approval") {
55165
- return handleApproval(client, route, resolvedToolName, input);
55628
+ return handleApproval(client, route, resolvedToolName, input, gateRevision);
55166
55629
  }
55167
55630
  await recordUse(client, route, resolvedToolName, input, "refused");
55168
55631
  return { ok: false, reason: "gate_refused" };
@@ -55176,7 +55639,14 @@ var RepoHostRouteUnavailableError = class extends Error {
55176
55639
  };
55177
55640
  var NoGrantForServerError = class extends RepoHostRouteUnavailableError {
55178
55641
  };
55179
- async function proceedToDestination(client, route, resolvedToolName, input, approvalItemId, boundPermitId) {
55642
+ var PERMIT_RETRY_DELAYS_MS = [25, 75];
55643
+ function isRetryablePermitError(error51) {
55644
+ if (error51 instanceof MrrlinApiError) {
55645
+ return error51.code === "CAPABILITY_PERMIT_RETRYABLE" || error51.code === "PERMIT_EXPIRED" || error51.status === 408 || error51.status === 504;
55646
+ }
55647
+ return error51 instanceof TypeError || error51 instanceof Error && (error51.name === "AbortError" || error51.name === "TimeoutError");
55648
+ }
55649
+ async function proceedToDestination(client, route, resolvedToolName, input, evidenceId) {
55180
55650
  const taskless = !input.taskId;
55181
55651
  if (taskless && !MRRLIN_API_CAPABILITIES.has(route.capability)) {
55182
55652
  await recordUse(client, route, resolvedToolName, input, "refused");
@@ -55197,32 +55667,36 @@ async function proceedToDestination(client, route, resolvedToolName, input, appr
55197
55667
  let invocationId;
55198
55668
  if (input.taskId && client.issueCapabilityPermit && client.redeemCapabilityPermit) {
55199
55669
  try {
55200
- const payloadDigest = import_node_crypto5.default.createHash("sha256").update(JSON.stringify(input.payload ?? null)).digest("hex");
55201
- const targetInvocationId = approvalItemId ? `inv_${approvalItemId}` : void 0;
55202
- let effectivePermitId = boundPermitId;
55203
- if (!effectivePermitId && targetInvocationId && client.getCapabilityInvocation) {
55670
+ const payloadDigest = digestCapabilityPayload(input.payload);
55671
+ const targetInvocationId = evidenceId ? `inv_${evidenceId}` : void 0;
55672
+ let redemption;
55673
+ for (let attempt = 0; ; attempt += 1) {
55204
55674
  try {
55205
- const existingInv = await client.getCapabilityInvocation(input.taskProjectSlug, targetInvocationId);
55206
- if (existingInv) effectivePermitId = existingInv.permitId;
55207
- } catch {
55675
+ const permit = await client.issueCapabilityPermit(input.taskProjectSlug, {
55676
+ projectSlug: input.taskProjectSlug,
55677
+ taskId: input.taskId,
55678
+ serverId: route.serverId,
55679
+ capability: route.capability,
55680
+ toolName: resolvedToolName,
55681
+ payload: input.payload,
55682
+ payloadDigest,
55683
+ inboxDecisionId: evidenceId
55684
+ });
55685
+ const permitId = permit.id;
55686
+ const idempotencyKey = evidenceId ? `deliver:approval:${evidenceId}` : `deliver:${input.taskProjectSlug}:${permitId}`;
55687
+ redemption = await client.redeemCapabilityPermit(input.taskProjectSlug, {
55688
+ permitId,
55689
+ idempotencyKey,
55690
+ payloadDigest,
55691
+ invocationId: targetInvocationId
55692
+ });
55693
+ break;
55694
+ } catch (error51) {
55695
+ const retryDelay = PERMIT_RETRY_DELAYS_MS[attempt];
55696
+ if (!evidenceId || !isRetryablePermitError(error51) || retryDelay === void 0) throw error51;
55697
+ await (0, import_promises6.setTimeout)(retryDelay);
55208
55698
  }
55209
55699
  }
55210
- const permitId = effectivePermitId ?? (await client.issueCapabilityPermit(input.taskProjectSlug, {
55211
- projectSlug: input.taskProjectSlug,
55212
- taskId: input.taskId,
55213
- serverId: route.serverId,
55214
- capability: route.capability,
55215
- toolName: resolvedToolName,
55216
- operationClass: resolveOperationClass(route, "reversible"),
55217
- payloadDigest
55218
- })).id;
55219
- const idempotencyKey = approvalItemId ? `deliver:approval:${approvalItemId}` : `deliver:${input.taskProjectSlug}:${permitId}`;
55220
- const redemption = await client.redeemCapabilityPermit(input.taskProjectSlug, {
55221
- permitId,
55222
- idempotencyKey,
55223
- payloadDigest,
55224
- invocationId: targetInvocationId
55225
- });
55226
55700
  invocationId = redemption.id;
55227
55701
  if (redemption.replayed) {
55228
55702
  if (redemption.status === "completed") {
@@ -55237,16 +55711,22 @@ async function proceedToDestination(client, route, resolvedToolName, input, appr
55237
55711
  message: errorMessage(redemption.error) ?? "Capability invocation previously failed"
55238
55712
  };
55239
55713
  }
55240
- await recordUse(client, route, resolvedToolName, input, "refused");
55714
+ const inFlight = evidenceId !== void 0 && redemption.status === "pending" && Date.now() - Date.parse(redemption.startedAt) < CAPABILITY_INVOCATION_IN_FLIGHT_MS;
55715
+ if (!inFlight) await recordUse(client, route, resolvedToolName, input, "refused");
55241
55716
  return {
55242
55717
  ok: false,
55243
55718
  reason: "operational_incident",
55244
- message: `Capability invocation ${redemption.id} is in status "${redemption.status}" (operational incident: no automatic redispatch)`
55719
+ invocationId: redemption.id,
55720
+ ...inFlight ? { code: "CAPABILITY_INVOCATION_IN_FLIGHT" } : {},
55721
+ message: `Capability invocation ${redemption.id} is in status "${redemption.status}" (operational incident: no automatic redispatch)${redemption.startedAt ? `. Started at ${redemption.startedAt}.` : "."}`
55245
55722
  };
55246
55723
  }
55247
55724
  } catch (permitError) {
55248
- await recordUse(client, route, resolvedToolName, input, "refused");
55249
55725
  const msg = errorMessage(permitError) ?? String(permitError);
55726
+ if (evidenceId && isRetryablePermitError(permitError)) {
55727
+ return { ok: false, reason: "transport_error", code: "CAPABILITY_PERMIT_RETRYABLE", message: msg };
55728
+ }
55729
+ await recordUse(client, route, resolvedToolName, input, "refused");
55250
55730
  const isNoGrant = msg.includes("GRANT_REQUIRED") || msg.includes("no active grant");
55251
55731
  return {
55252
55732
  ok: false,
@@ -55256,12 +55736,13 @@ async function proceedToDestination(client, route, resolvedToolName, input, appr
55256
55736
  }
55257
55737
  }
55258
55738
  try {
55739
+ await input.beforeDispatch?.();
55259
55740
  const result = await callDestination(
55260
55741
  client,
55261
55742
  input.taskProjectSlug,
55262
55743
  route,
55263
55744
  resolvedToolName,
55264
- input.payload,
55745
+ input.dispatchPayload,
55265
55746
  input.mcpConfigPath,
55266
55747
  input.bareFetch
55267
55748
  );
@@ -55313,16 +55794,30 @@ async function refuse(client, route, resolvedToolName, input) {
55313
55794
  await recordUse(client, route, resolvedToolName, input, "refused");
55314
55795
  return { ok: false, reason: "gate_refused" };
55315
55796
  }
55316
- async function handleAskOnce(client, route, resolvedToolName, input) {
55317
- const groupId = `capability:ask-once:${input.taskProjectSlug}:${route.serverId}`;
55797
+ async function handleAskOnce(client, route, resolvedToolName, input, gateRevision) {
55798
+ const grantGeneration = gateRevision?.split("-")[1] ?? "v2";
55799
+ const key = digestCapabilityPayload([input.taskProjectSlug, route.serverId, grantGeneration]);
55800
+ const groupId = `capability:ask-once:${key}`;
55318
55801
  try {
55319
55802
  await client.createInboxItem(input.taskProjectSlug, {
55320
- id: `II-capability-ask-once-${input.taskProjectSlug}-${route.serverId}`,
55803
+ id: `II-capability-ask-once-${key}`,
55321
55804
  kind: "question",
55322
55805
  origin: "capability",
55323
55806
  groupId,
55324
55807
  body: `The first write to ${route.serverId} (via ${resolvedToolName}) needs a one-time confirmation before it can proceed.`,
55325
- taskId: input.taskId
55808
+ taskId: input.taskId,
55809
+ questionOptions: [
55810
+ { label: "Allow writes", answer: "Allow writes", description: "Confirm the first write to this server." }
55811
+ ],
55812
+ actionPayload: input.taskId ? {
55813
+ actor: "agent",
55814
+ provider: "mcp",
55815
+ runId: input.runId ?? `ER-${input.taskId}`,
55816
+ serverId: route.serverId,
55817
+ toolName: resolvedToolName,
55818
+ capability: route.capability,
55819
+ capabilityPayload: input.payload
55820
+ } : void 0
55326
55821
  });
55327
55822
  } catch {
55328
55823
  }
@@ -55346,15 +55841,22 @@ async function alreadyConsumed(client, route, resolvedToolName, input, after) {
55346
55841
  return useAtMs > afterMs;
55347
55842
  });
55348
55843
  }
55349
- async function handleApproval(client, route, resolvedToolName, input) {
55350
- const scopeId = input.runId ?? input.taskId;
55844
+ async function handleApproval(client, route, resolvedToolName, input, gateRevision) {
55845
+ const scopeId = input.evidenceScope ?? input.runId ?? input.taskId;
55351
55846
  if (scopeId === null) {
55352
55847
  return refuse(client, route, resolvedToolName, input);
55353
55848
  }
55354
- const payloadDigest = import_node_crypto5.default.createHash("sha256").update(JSON.stringify(input.payload ?? null)).digest("hex");
55355
- const digestPrefix = payloadDigest.slice(0, 16);
55356
- const groupId = `capability:approval:${scopeId}:${route.serverId}:${resolvedToolName}:${digestPrefix}`;
55357
- const id = `II-capability-approval-${scopeId}-${route.serverId}-${resolvedToolName}-${digestPrefix}`;
55849
+ const payloadDigest = digestCapabilityPayload(input.payload);
55850
+ const evidenceKey = digestCapabilityPayload([
55851
+ scopeId,
55852
+ route.serverId,
55853
+ route.capability,
55854
+ resolvedToolName,
55855
+ gateRevision ?? "v2",
55856
+ payloadDigest
55857
+ ]);
55858
+ const groupId = `capability:approval:${evidenceKey}`;
55859
+ const id = `II-capability-approval-${evidenceKey}`;
55358
55860
  let items;
55359
55861
  try {
55360
55862
  items = await client.listInboxItems(input.taskProjectSlug, { groupId });
@@ -55396,35 +55898,39 @@ ${JSON.stringify(input.payload ?? {}, null, 2)}
55396
55898
  if (!existing.payloadDigest || existing.payloadDigest !== payloadDigest) {
55397
55899
  return refuse(client, route, resolvedToolName, input);
55398
55900
  }
55901
+ if (existing.status === "rejected") {
55902
+ return { ...await refuse(client, route, resolvedToolName, input), code: "CAPABILITY_AUTHORIZATION_REJECTED" };
55903
+ }
55399
55904
  const isApproved = existing.status === "approved";
55400
55905
  if (!isApproved) {
55401
55906
  return refuse(client, route, resolvedToolName, input);
55402
55907
  }
55403
- if (existing.decidedAt === null) {
55908
+ if (existing.decidedAt === null || !Number.isFinite(Date.parse(existing.decidedAt))) {
55404
55909
  return refuse(client, route, resolvedToolName, input);
55405
55910
  }
55406
- const invocationId = `inv_${existing.id}`;
55407
- let existingInv = null;
55408
- if (client.getCapabilityInvocation) {
55409
- try {
55410
- existingInv = await client.getCapabilityInvocation(input.taskProjectSlug, invocationId);
55411
- } catch {
55412
- }
55413
- }
55414
- if (!existingInv && await alreadyConsumed(client, route, resolvedToolName, input, existing.decidedAt)) {
55911
+ const invocation = await client.getCapabilityInvocation?.(input.taskProjectSlug, `inv_${existing.id}`).catch(() => null);
55912
+ if (!invocation && await alreadyConsumed(client, route, resolvedToolName, input, existing.decidedAt)) {
55415
55913
  return refuse(client, route, resolvedToolName, input);
55416
55914
  }
55417
- const boundPermitId = existingInv?.permitId ?? existing.actionPayload?.permitId;
55418
- return proceedToDestination(client, route, resolvedToolName, input, existing.id, boundPermitId);
55915
+ return proceedToDestination(client, route, resolvedToolName, input, existing.id);
55419
55916
  }
55420
- async function handleWindow(client, route, resolvedToolName, input) {
55917
+ async function handleWindow(client, route, resolvedToolName, input, gateRevision) {
55421
55918
  if (input.taskId === null) {
55422
55919
  return refuse(client, route, resolvedToolName, input);
55423
55920
  }
55424
55921
  const taskId = input.taskId;
55425
- const scopeId = input.runId ?? taskId;
55426
- const groupId = `capability:window:${scopeId}:${route.serverId}:${resolvedToolName}`;
55427
- const id = `II-capability-window-${scopeId}-${route.serverId}-${resolvedToolName}`;
55922
+ const scopeId = input.evidenceScope ?? input.runId ?? taskId;
55923
+ const payloadDigest = digestCapabilityPayload(input.payload);
55924
+ const evidenceKey = digestCapabilityPayload([
55925
+ scopeId,
55926
+ route.serverId,
55927
+ route.capability,
55928
+ resolvedToolName,
55929
+ gateRevision ?? "v2",
55930
+ payloadDigest
55931
+ ]);
55932
+ const groupId = `capability:window:${evidenceKey}`;
55933
+ const id = `II-capability-window-${evidenceKey}`;
55428
55934
  let items;
55429
55935
  try {
55430
55936
  items = await client.listInboxItems(input.taskProjectSlug, { groupId });
@@ -55440,7 +55946,19 @@ async function handleWindow(client, route, resolvedToolName, input) {
55440
55946
  origin: "capability",
55441
55947
  groupId,
55442
55948
  body: `Waiting for the ${resolvedToolName} window on ${route.serverId} to elapse.`,
55443
- taskId
55949
+ taskId,
55950
+ payloadDigest,
55951
+ actionPayload: {
55952
+ actor: "agent",
55953
+ provider: "mcp",
55954
+ runId: input.runId ?? `ER-${taskId}`,
55955
+ codeExecution: false,
55956
+ capabilityPayload: input.payload,
55957
+ serverId: route.serverId,
55958
+ toolName: resolvedToolName,
55959
+ scopeId,
55960
+ capability: route.capability
55961
+ }
55444
55962
  });
55445
55963
  } catch {
55446
55964
  }
@@ -55448,6 +55966,9 @@ async function handleWindow(client, route, resolvedToolName, input) {
55448
55966
  return refuse(client, route, resolvedToolName, input);
55449
55967
  }
55450
55968
  if (existing.status === "rejected") {
55969
+ return { ...await refuse(client, route, resolvedToolName, input), code: "CAPABILITY_AUTHORIZATION_REJECTED" };
55970
+ }
55971
+ if (existing.payloadDigest !== payloadDigest) {
55451
55972
  return refuse(client, route, resolvedToolName, input);
55452
55973
  }
55453
55974
  let task;
@@ -55456,17 +55977,18 @@ async function handleWindow(client, route, resolvedToolName, input) {
55456
55977
  } catch {
55457
55978
  return refuse(client, route, resolvedToolName, input);
55458
55979
  }
55459
- const elapsed = task.followUpAt !== null && Date.parse(task.followUpAt) <= Date.now();
55980
+ const elapsed = task.followUpAt !== null && Date.parse(task.followUpAt) <= Date.now() && Date.parse(existing.createdAt) + 5 * 60 * 1e3 <= Date.now();
55460
55981
  if (!elapsed) {
55461
55982
  return refuse(client, route, resolvedToolName, input);
55462
55983
  }
55463
- if (await alreadyConsumed(client, route, resolvedToolName, input, existing.createdAt)) {
55984
+ const invocation = await client.getCapabilityInvocation?.(input.taskProjectSlug, `inv_${existing.id}`).catch(() => null);
55985
+ if (!invocation && await alreadyConsumed(client, route, resolvedToolName, input, existing.createdAt)) {
55464
55986
  return refuse(client, route, resolvedToolName, input);
55465
55987
  }
55466
- const result = await proceedToDestination(client, route, resolvedToolName, input);
55988
+ const result = await proceedToDestination(client, route, resolvedToolName, input, existing.id);
55467
55989
  if (result.ok) {
55468
55990
  try {
55469
- await client.decideInboxItem(input.taskProjectSlug, existing.id, { verdict: "acknowledged", decidedBy: "system" });
55991
+ await client.decideInboxItem(input.taskProjectSlug, existing.id, { verdict: "acknowledged", answer: "Window elapsed.", decidedBy: "system" });
55470
55992
  } catch {
55471
55993
  }
55472
55994
  }
@@ -55536,6 +56058,7 @@ async function callDestination(client, projectSlug, route, resolvedToolName, pay
55536
56058
  throw new Error(`callDestination: no destination wired for capability "${route.capability}"`);
55537
56059
  }
55538
56060
  async function readPublishState(client, projectSlug, taskProjectSlug, payload, mcpConfigPath, taskId) {
56061
+ payload = JSON.parse(JSON.stringify(payload));
55539
56062
  const resolution = await client.resolveCapabilityRoute(projectSlug, "publish", taskProjectSlug);
55540
56063
  if (!resolution.ok) {
55541
56064
  throw new Error(`readPublishState: publish capability route unavailable: ${resolution.reason}`);
@@ -55553,14 +56076,14 @@ async function readPublishState(client, projectSlug, taskProjectSlug, payload, m
55553
56076
  if (!taskId) {
55554
56077
  throw new Error("TASK_ID_REQUIRED_FOR_CAPABILITY_PERMIT: Capability permit issuance requires an authoritative taskId");
55555
56078
  }
55556
- const payloadDigest = import_node_crypto5.default.createHash("sha256").update(JSON.stringify(payload ?? null)).digest("hex");
56079
+ const payloadDigest = digestCapabilityPayload(payload);
55557
56080
  const permit = await client.issueCapabilityPermit(taskProjectSlug, {
55558
56081
  projectSlug: taskProjectSlug,
55559
56082
  taskId,
55560
56083
  serverId: route.serverId,
55561
56084
  capability: route.capability,
55562
56085
  toolName: resolvedToolName,
55563
- operationClass: "read",
56086
+ payload,
55564
56087
  payloadDigest
55565
56088
  });
55566
56089
  const idempotencyKey = `publish-observe:${taskProjectSlug}:${permit.id}`;
@@ -55604,101 +56127,46 @@ async function readPublishState(client, projectSlug, taskProjectSlug, payload, m
55604
56127
  throw error51;
55605
56128
  }
55606
56129
  }
55607
- async function dispatchPublishOperation(client, projectSlug, taskProjectSlug, taskId, runId, payload, mcpConfigPath) {
55608
- const resolution = await client.resolveCapabilityRoute(projectSlug, "publish", taskProjectSlug);
55609
- if (!resolution.ok) {
55610
- throw new Error(`dispatchPublishOperation: publish capability route unavailable: ${resolution.reason}`);
55611
- }
55612
- const { route } = resolution;
55613
- const resolvedToolName = route.operations[payload.operation];
55614
- if (typeof resolvedToolName !== "string") {
55615
- throw new Error(`publish_${payload.operation}_unavailable`);
56130
+ var PublishAuthorizationPendingError = class extends Error {
56131
+ };
56132
+ var PublishInvocationIncidentError = class extends Error {
56133
+ constructor(message, invocationId) {
56134
+ super(message);
56135
+ this.invocationId = invocationId;
55616
56136
  }
55617
- const input = {
56137
+ };
56138
+ async function dispatchPublishOperation(client, projectSlug, taskProjectSlug, taskId, runId, payload, mcpConfigPath, beforeDispatch, purpose, approvalAttemptScope) {
56139
+ const delivery = await deliverThroughCapability(client, {
55618
56140
  projectSlug,
55619
56141
  taskProjectSlug,
55620
56142
  artifactKind: "page",
55621
56143
  taskId,
55622
56144
  runId,
55623
56145
  payload,
55624
- mcpConfigPath
55625
- };
55626
- const server = readMcpServerById(mcpConfigPath ?? defaultMcpConfigPath(), route.serverId);
55627
- if (server === null) {
55628
- const use = await recordUse(client, route, resolvedToolName, input, "refused");
55629
- throw Object.assign(new NoGrantForServerError(`no local MCP config for server "${route.serverId}"`), { use });
55630
- }
55631
- if (!client.issueCapabilityPermit || !client.redeemCapabilityPermit) {
55632
- const use = await recordUse(client, route, resolvedToolName, input, "refused");
55633
- throw Object.assign(new Error("Capability permit issuance and redemption client methods are required"), { use });
55634
- }
55635
- let invocationId;
55636
- try {
55637
- const payloadDigest = import_node_crypto5.default.createHash("sha256").update(JSON.stringify(payload ?? null)).digest("hex");
55638
- const permit = await client.issueCapabilityPermit(taskProjectSlug, {
55639
- projectSlug: taskProjectSlug,
55640
- taskId,
55641
- serverId: route.serverId,
55642
- capability: route.capability,
55643
- toolName: resolvedToolName,
55644
- operationClass: resolveOperationClass(route, payload.operation === "preview" ? "reversible" : "irreversible"),
55645
- payloadDigest
55646
- });
55647
- const idempotencyKey = `publish:${taskProjectSlug}:${permit.id}`;
55648
- const redemption = await client.redeemCapabilityPermit(taskProjectSlug, {
55649
- permitId: permit.id,
55650
- idempotencyKey,
55651
- payloadDigest
55652
- });
55653
- invocationId = redemption.id;
55654
- if (redemption.replayed) {
55655
- if (redemption.status === "completed") {
55656
- const use2 = await recordUse(client, route, resolvedToolName, input, "ok");
55657
- if (!isRecord3(redemption.result) || !("content" in redemption.result) || !("url" in redemption.result)) {
55658
- throw new Error("CAPABILITY_REPLAY_INVALID_RESULT: completed publish invocation has no object result");
55659
- }
55660
- return { content: redemption.result.content, url: typeof redemption.result.url === "string" ? redemption.result.url : null, use: use2 };
55661
- }
55662
- if (redemption.status === "failed") {
55663
- const use2 = await recordUse(client, route, resolvedToolName, input, "error");
55664
- const errMsg = errorMessage(redemption.error) ?? "Capability invocation previously failed";
55665
- throw Object.assign(new Error(`CAPABILITY_REPLAY_FAILED: ${errMsg}`), { use: use2 });
55666
- }
55667
- const use = await recordUse(client, route, resolvedToolName, input, "refused");
55668
- throw Object.assign(
55669
- new Error(`OPERATIONAL_INCIDENT: capability invocation ${redemption.id} is in status "${redemption.status}" and cannot be replayed as success`),
55670
- { use }
55671
- );
56146
+ mcpConfigPath,
56147
+ beforeDispatch,
56148
+ evidenceScope: purpose === "rollback" ? `${runId}-rollback` : approvalAttemptScope
56149
+ });
56150
+ if (!delivery.ok) {
56151
+ if (delivery.code === "DEPLOY_APPROVAL_STATE_CHANGED" || delivery.code === "CAPABILITY_PERMIT_RETRYABLE" || delivery.code === "CAPABILITY_INVOCATION_IN_FLIGHT" || delivery.reason === "gate_refused" && delivery.code !== "CAPABILITY_AUTHORIZATION_REJECTED") {
56152
+ throw new PublishAuthorizationPendingError(delivery.message ?? "Publish authorization is pending.");
55672
56153
  }
55673
- } catch (permitError) {
55674
- await recordUse(client, route, resolvedToolName, input, "refused");
55675
- throw permitError;
55676
- }
55677
- try {
55678
- const result = await deliverToPublish(server, resolvedToolName, payload);
55679
- if (invocationId && client.finalizeCapabilityInvocation) {
55680
- await client.finalizeCapabilityInvocation(taskProjectSlug, {
55681
- invocationId,
55682
- status: "completed",
55683
- result
55684
- }).catch(() => {
55685
- });
56154
+ if (delivery.reason === "no_grant") {
56155
+ throw new NoGrantForServerError(delivery.message ?? "No live publishing grant.");
55686
56156
  }
55687
- const use = await recordUse(client, route, resolvedToolName, input, "ok");
55688
- return { ...result, use };
55689
- } catch (error51) {
55690
- if (invocationId && client.finalizeCapabilityInvocation) {
55691
- await client.finalizeCapabilityInvocation(taskProjectSlug, {
55692
- invocationId,
55693
- status: "failed",
55694
- error: error51 instanceof Error ? error51.message : String(error51)
55695
- }).catch(() => {
55696
- });
56157
+ if (delivery.reason === "operational_incident" && delivery.invocationId) {
56158
+ throw new PublishInvocationIncidentError(delivery.message ?? "Publish invocation needs reconciliation.", delivery.invocationId);
55697
56159
  }
55698
- const outcome = error51 instanceof InvokeUnexpandedHeaderError ? "refused" : "error";
55699
- await recordUse(client, route, resolvedToolName, input, outcome);
55700
- throw error51;
56160
+ throw new Error(delivery.message ?? `Publish delivery failed: ${delivery.reason}`);
56161
+ }
56162
+ if (!isRecord3(delivery.result) || !("content" in delivery.result) || !("url" in delivery.result)) {
56163
+ throw new Error("Completed publish invocation has no publish result.");
55701
56164
  }
56165
+ return {
56166
+ content: delivery.result.content,
56167
+ url: typeof delivery.result.url === "string" ? delivery.result.url : null,
56168
+ use: delivery.use
56169
+ };
55702
56170
  }
55703
56171
  async function readPullRequestState(client, projectSlug, taskProjectSlug, pullRequestUrl, mcpConfigPath, taskId) {
55704
56172
  const resolution = await client.resolveCapabilityRoute(projectSlug, "repo_host", taskProjectSlug);
@@ -55722,14 +56190,14 @@ async function readPullRequestState(client, projectSlug, taskProjectSlug, pullRe
55722
56190
  operation: "pull_request_state",
55723
56191
  pullRequestUrl
55724
56192
  };
55725
- const payloadDigest = import_node_crypto5.default.createHash("sha256").update(JSON.stringify(payload ?? null)).digest("hex");
56193
+ const payloadDigest = digestCapabilityPayload(payload);
55726
56194
  const permit = await client.issueCapabilityPermit(taskProjectSlug, {
55727
56195
  projectSlug: taskProjectSlug,
55728
56196
  taskId,
55729
56197
  serverId: route.serverId,
55730
56198
  capability: route.capability,
55731
56199
  toolName: toolName2,
55732
- operationClass: "read",
56200
+ payload,
55733
56201
  payloadDigest
55734
56202
  });
55735
56203
  const idempotencyKey = `pr-state:${taskProjectSlug}:${permit.id}`;
@@ -55778,6 +56246,9 @@ async function readPullRequestState(client, projectSlug, taskProjectSlug, pullRe
55778
56246
  throw err;
55779
56247
  }
55780
56248
  }
56249
+ function digestCapabilityPayload(payload) {
56250
+ return import_node_crypto5.default.createHash("sha256").update(canonicalJson(payload)).digest("hex");
56251
+ }
55781
56252
  function isRecord3(value) {
55782
56253
  return typeof value === "object" && value !== null;
55783
56254
  }
@@ -55787,11 +56258,6 @@ function errorMessage(value) {
55787
56258
  if (isRecord3(value) && typeof value.message === "string") return value.message;
55788
56259
  return void 0;
55789
56260
  }
55790
- function resolveOperationClass(route, fallback) {
55791
- if (!isRecord3(route)) return fallback;
55792
- const operationClass = route.operationClass;
55793
- return operationClass === "read" || operationClass === "reversible" || operationClass === "irreversible" ? operationClass : fallback;
55794
- }
55795
56261
 
55796
56262
  // src/decision-consensus.ts
55797
56263
  var ANCHOR_TIMEOUT_MS = Number(process.env["MRRLIN_DECISION_TIMEOUT_MS"] ?? 9e4);
@@ -57527,12 +57993,12 @@ function createIntentCheckDescriptor() {
57527
57993
  var intentCheckDescriptor = createIntentCheckDescriptor();
57528
57994
 
57529
57995
  // src/evidence/assembler.ts
57530
- var import_promises7 = require("node:fs/promises");
57996
+ var import_promises8 = require("node:fs/promises");
57531
57997
  var import_node_path13 = require("node:path");
57532
57998
 
57533
57999
  // src/bridge-log.ts
57534
58000
  var import_node_fs7 = require("node:fs");
57535
- var import_promises6 = require("node:fs/promises");
58001
+ var import_promises7 = require("node:fs/promises");
57536
58002
  var import_node_path12 = require("node:path");
57537
58003
 
57538
58004
  // src/telemetry/projector.ts
@@ -57984,7 +58450,7 @@ async function findSessionDays(stateDir, sessionId) {
57984
58450
  const sessionsPath = (0, import_node_path12.join)(stateDir, "logs", ".sessions.json");
57985
58451
  let sessionsObj;
57986
58452
  try {
57987
- const parsed = JSON.parse(await (0, import_promises6.readFile)(sessionsPath, "utf8"));
58453
+ const parsed = JSON.parse(await (0, import_promises7.readFile)(sessionsPath, "utf8"));
57988
58454
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return [];
57989
58455
  sessionsObj = parsed;
57990
58456
  } catch {
@@ -58088,7 +58554,7 @@ function isRecord6(v) {
58088
58554
  async function readDayLines(stateDir, day, sessionId) {
58089
58555
  let raw;
58090
58556
  try {
58091
- raw = await (0, import_promises7.readFile)((0, import_node_path13.join)(stateDir, "logs", `bridge-${day}.jsonl`), "utf8");
58557
+ raw = await (0, import_promises8.readFile)((0, import_node_path13.join)(stateDir, "logs", `bridge-${day}.jsonl`), "utf8");
58092
58558
  } catch {
58093
58559
  return [];
58094
58560
  }
@@ -58162,7 +58628,7 @@ async function assembleEvidence(stateDir, sessionId, reportId, gateCtx) {
58162
58628
  }
58163
58629
  let windowPruned = false;
58164
58630
  try {
58165
- const raw = await (0, import_promises7.readFile)((0, import_node_path13.join)(stateDir, "logs", ".pruned.jsonl"), "utf8");
58631
+ const raw = await (0, import_promises8.readFile)((0, import_node_path13.join)(stateDir, "logs", ".pruned.jsonl"), "utf8");
58166
58632
  outer: for (const line of raw.split("\n")) {
58167
58633
  if (!line.trim()) continue;
58168
58634
  let rec;
@@ -61999,7 +62465,7 @@ function createMrrlinTools(options) {
61999
62465
  `Unsupported artifact extension '${extension2}'. Allowed: ${Object.keys(ARTIFACT_EXTENSION_TYPES).join(", ")}.`
62000
62466
  );
62001
62467
  }
62002
- const stats = await (0, import_promises8.stat)(filePath);
62468
+ const stats = await (0, import_promises9.stat)(filePath);
62003
62469
  if (stats.size > MRRLIN_ARTIFACT_FILE_MAX_BYTES) {
62004
62470
  throw new McpToolCodedError(
62005
62471
  "ARTIFACT_FILE_TOO_LARGE",
@@ -62012,7 +62478,7 @@ function createMrrlinTools(options) {
62012
62478
  "File is empty (0 bytes); write content before uploading."
62013
62479
  );
62014
62480
  }
62015
- const bytes3 = new Uint8Array(await (0, import_promises8.readFile)(filePath));
62481
+ const bytes3 = new Uint8Array(await (0, import_promises9.readFile)(filePath));
62016
62482
  if (bytes3.byteLength > MRRLIN_ARTIFACT_FILE_MAX_BYTES) {
62017
62483
  throw new McpToolCodedError(
62018
62484
  "ARTIFACT_FILE_TOO_LARGE",
@@ -62369,7 +62835,7 @@ function managedEntries2(options, distribution) {
62369
62835
  }
62370
62836
  async function pathExists4(target) {
62371
62837
  try {
62372
- await import_promises9.default.access(target);
62838
+ await import_promises10.default.access(target);
62373
62839
  return true;
62374
62840
  } catch {
62375
62841
  return false;
@@ -62380,18 +62846,18 @@ async function installAgy(options) {
62380
62846
  const configJsonPath = resolveConfigJsonPath(options);
62381
62847
  const distribution = await detectInstallDistribution3(options);
62382
62848
  const entries = managedEntries2(options, distribution);
62383
- await import_promises9.default.mkdir(import_node_path24.default.dirname(configPath), { recursive: true });
62384
- await import_promises9.default.mkdir(import_node_path24.default.dirname(configJsonPath), { recursive: true });
62849
+ await import_promises10.default.mkdir(import_node_path24.default.dirname(configPath), { recursive: true });
62850
+ await import_promises10.default.mkdir(import_node_path24.default.dirname(configJsonPath), { recursive: true });
62385
62851
  let action = "noop";
62386
62852
  const preservedEnvBlocks = [];
62387
62853
  if (!await pathExists4(configPath)) {
62388
62854
  const mcpServers = {};
62389
62855
  for (const entry of entries) mcpServers[entry.id] = entry.expected;
62390
- await import_promises9.default.writeFile(configPath, `${JSON.stringify({ mcpServers }, null, 2)}
62856
+ await import_promises10.default.writeFile(configPath, `${JSON.stringify({ mcpServers }, null, 2)}
62391
62857
  `, { mode: 384 });
62392
62858
  action = "created";
62393
62859
  } else {
62394
- const rawContent = await import_promises9.default.readFile(configPath, "utf8");
62860
+ const rawContent = await import_promises10.default.readFile(configPath, "utf8");
62395
62861
  let parsed;
62396
62862
  try {
62397
62863
  parsed = rawContent.trim() === "" ? {} : JSON.parse(rawContent);
@@ -62443,7 +62909,7 @@ async function installAgy(options) {
62443
62909
  }
62444
62910
  if (mutated) {
62445
62911
  parsed.mcpServers = mcpServers;
62446
- await import_promises9.default.writeFile(configPath, `${JSON.stringify(parsed, null, 2)}
62912
+ await import_promises10.default.writeFile(configPath, `${JSON.stringify(parsed, null, 2)}
62447
62913
  `, { mode: 384 });
62448
62914
  }
62449
62915
  }
@@ -62458,12 +62924,12 @@ async function installAgy(options) {
62458
62924
  }
62459
62925
  }
62460
62926
  };
62461
- await import_promises9.default.writeFile(configJsonPath, `${JSON.stringify(freshConfig, null, 2)}
62927
+ await import_promises10.default.writeFile(configJsonPath, `${JSON.stringify(freshConfig, null, 2)}
62462
62928
  `, { mode: 384 });
62463
62929
  grantsAction = "created";
62464
62930
  grantsAdded = targetGrants.length;
62465
62931
  } else {
62466
- const rawConfig = await import_promises9.default.readFile(configJsonPath, "utf8");
62932
+ const rawConfig = await import_promises10.default.readFile(configJsonPath, "utf8");
62467
62933
  let parsedConfig;
62468
62934
  try {
62469
62935
  parsedConfig = rawConfig.trim() === "" ? {} : JSON.parse(rawConfig);
@@ -62486,7 +62952,7 @@ async function installAgy(options) {
62486
62952
  permissionGrants.allow = mergedAllow;
62487
62953
  userSettings.globalPermissionGrants = permissionGrants;
62488
62954
  parsedConfig.userSettings = userSettings;
62489
- await import_promises9.default.writeFile(configJsonPath, `${JSON.stringify(parsedConfig, null, 2)}
62955
+ await import_promises10.default.writeFile(configJsonPath, `${JSON.stringify(parsedConfig, null, 2)}
62490
62956
  `, { mode: 384 });
62491
62957
  grantsAction = "updated";
62492
62958
  grantsAdded = newGrantsToAppend.length;
@@ -62496,7 +62962,7 @@ async function installAgy(options) {
62496
62962
  }
62497
62963
 
62498
62964
  // src/provider-readiness.ts
62499
- var import_promises10 = require("node:fs/promises");
62965
+ var import_promises11 = require("node:fs/promises");
62500
62966
  var import_node_fs17 = require("node:fs");
62501
62967
  var import_node_os14 = __toESM(require("node:os"), 1);
62502
62968
  var import_node_path25 = __toESM(require("node:path"), 1);
@@ -62667,7 +63133,7 @@ async function verifyProviderReadiness(provider, run3, opts = {}) {
62667
63133
  if (provider === "codex") {
62668
63134
  const authPath = import_node_path25.default.join(resolveCodexHome2(opts), "auth.json");
62669
63135
  try {
62670
- await (0, import_promises10.access)(authPath, import_node_fs17.constants.F_OK);
63136
+ await (0, import_promises11.access)(authPath, import_node_fs17.constants.F_OK);
62671
63137
  checks.auth = true;
62672
63138
  } catch {
62673
63139
  details.push(`auth: ${authPath} not found`);
@@ -62684,7 +63150,7 @@ async function verifyProviderReadiness(provider, run3, opts = {}) {
62684
63150
  if (provider === "codex") {
62685
63151
  const configPath = import_node_path25.default.join(resolveCodexHome2(opts), "config.toml");
62686
63152
  try {
62687
- const raw = await (0, import_promises10.readFile)(configPath, "utf8");
63153
+ const raw = await (0, import_promises11.readFile)(configPath, "utf8");
62688
63154
  const parsed = toml3.parse(raw);
62689
63155
  checks.mcpReachable = isExternalAgentsWrapper(parsed.mcp_servers?.["external-agents"]);
62690
63156
  } catch {
@@ -62694,7 +63160,7 @@ async function verifyProviderReadiness(provider, run3, opts = {}) {
62694
63160
  } else {
62695
63161
  const configPath = resolveClaudeConfigPath2(opts);
62696
63162
  try {
62697
- const raw = await (0, import_promises10.readFile)(configPath, "utf8");
63163
+ const raw = await (0, import_promises11.readFile)(configPath, "utf8");
62698
63164
  const parsed = raw.trim() === "" ? {} : JSON.parse(raw);
62699
63165
  checks.mcpReachable = isExternalAgentsWrapper(parsed.mcpServers?.["external-agents"]);
62700
63166
  } catch {
@@ -64126,7 +64592,7 @@ Do NOT derail the current task - if the operator has an in-flight question, answ
64126
64592
  }
64127
64593
 
64128
64594
  // src/_generated/version.ts
64129
- var PKG_VERSION = "0.4.158";
64595
+ var PKG_VERSION = "0.4.160";
64130
64596
 
64131
64597
  // src/bridge-allowed-origins.ts
64132
64598
  var DEFAULT_DIRECTOR_BRIDGE_ALLOWED_ORIGINS = [
@@ -65834,7 +66300,7 @@ function startSchedulerTickLoop(deps) {
65834
66300
  }
65835
66301
 
65836
66302
  // src/retention/pruner.ts
65837
- var import_promises11 = require("node:fs/promises");
66303
+ var import_promises12 = require("node:fs/promises");
65838
66304
  var import_node_path31 = __toESM(require("node:path"), 1);
65839
66305
  var LOG_DIR_MODE2 = 448;
65840
66306
  var LOG_FILE_MODE2 = 384;
@@ -65845,7 +66311,7 @@ async function prune(stateDir, bounds) {
65845
66311
  const logsDir = import_node_path31.default.join(stateDir, "logs");
65846
66312
  let entries;
65847
66313
  try {
65848
- entries = await (0, import_promises11.readdir)(logsDir);
66314
+ entries = await (0, import_promises12.readdir)(logsDir);
65849
66315
  } catch (err) {
65850
66316
  if (err?.code === "ENOENT") {
65851
66317
  await emitPruneLog(stateDir, [], {}, 0, null);
@@ -65859,7 +66325,7 @@ async function prune(stateDir, bounds) {
65859
66325
  const m = bridgeRe.exec(entry);
65860
66326
  if (!m?.[1]) continue;
65861
66327
  const fullPath = import_node_path31.default.join(logsDir, entry);
65862
- const s = await (0, import_promises11.stat)(fullPath);
66328
+ const s = await (0, import_promises12.stat)(fullPath);
65863
66329
  files.push({ day: m[1], size: s.size, fullPath });
65864
66330
  }
65865
66331
  files.sort((a, b) => a.day < b.day ? -1 : a.day > b.day ? 1 : 0);
@@ -65870,7 +66336,7 @@ async function prune(stateDir, bounds) {
65870
66336
  const telemetryDir = import_node_path31.default.join(stateDir, "telemetry");
65871
66337
  let telemetryEntries;
65872
66338
  try {
65873
- telemetryEntries = await (0, import_promises11.readdir)(telemetryDir);
66339
+ telemetryEntries = await (0, import_promises12.readdir)(telemetryDir);
65874
66340
  } catch (err) {
65875
66341
  if (err?.code === "ENOENT") return true;
65876
66342
  throw err;
@@ -65885,7 +66351,7 @@ async function prune(stateDir, bounds) {
65885
66351
  for (const slug of projectSlugs) {
65886
66352
  const markerPath = import_node_path31.default.join(telemetryDir, `.processed-${slug}-${day}`);
65887
66353
  try {
65888
- await (0, import_promises11.stat)(markerPath);
66354
+ await (0, import_promises12.stat)(markerPath);
65889
66355
  } catch (err) {
65890
66356
  if (err?.code === "ENOENT") return false;
65891
66357
  throw err;
@@ -65906,7 +66372,7 @@ async function prune(stateDir, bounds) {
65906
66372
  i += 1;
65907
66373
  continue;
65908
66374
  }
65909
- await (0, import_promises11.unlink)(candidate.fullPath);
66375
+ await (0, import_promises12.unlink)(candidate.fullPath);
65910
66376
  daysRemoved.push(candidate.day);
65911
66377
  reasonByDay[candidate.day] = "size";
65912
66378
  bytesRemoved += candidate.size;
@@ -65920,7 +66386,7 @@ async function prune(stateDir, bounds) {
65920
66386
  const fileDate = /* @__PURE__ */ new Date(`${info.day}T00:00:00Z`);
65921
66387
  const ageInDays = (now - fileDate.getTime()) / msPerDay;
65922
66388
  if (ageInDays > bounds.ageDays && !isProtected(info.day) && await isDaySafeToDelete(info.day)) {
65923
- await (0, import_promises11.unlink)(info.fullPath);
66389
+ await (0, import_promises12.unlink)(info.fullPath);
65924
66390
  daysRemoved.push(info.day);
65925
66391
  reasonByDay[info.day] = "age";
65926
66392
  bytesRemoved += info.size;
@@ -65937,7 +66403,7 @@ async function prune(stateDir, bounds) {
65937
66403
  let sessionsObj = {};
65938
66404
  let fileExists = true;
65939
66405
  try {
65940
- sessionsObj = JSON.parse(await (0, import_promises11.readFile)(sessionsPath, "utf8"));
66406
+ sessionsObj = JSON.parse(await (0, import_promises12.readFile)(sessionsPath, "utf8"));
65941
66407
  } catch (err) {
65942
66408
  if (err?.code === "ENOENT") {
65943
66409
  fileExists = false;
@@ -65948,8 +66414,8 @@ async function prune(stateDir, bounds) {
65948
66414
  if (fileExists) {
65949
66415
  for (const day of daysRemoved) Reflect.deleteProperty(sessionsObj, day);
65950
66416
  const tmpPath = `${sessionsPath}.tmp`;
65951
- await (0, import_promises11.writeFile)(tmpPath, JSON.stringify(sessionsObj), { mode: LOG_FILE_MODE2 });
65952
- await (0, import_promises11.rename)(tmpPath, sessionsPath);
66417
+ await (0, import_promises12.writeFile)(tmpPath, JSON.stringify(sessionsObj), { mode: LOG_FILE_MODE2 });
66418
+ await (0, import_promises12.rename)(tmpPath, sessionsPath);
65953
66419
  }
65954
66420
  }
65955
66421
  return { daysRemoved, reasonByDay, bytesRemoved, oldestDayRemaining, budgetOvershootBytes };
@@ -65957,15 +66423,15 @@ async function prune(stateDir, bounds) {
65957
66423
  async function emitPruneLog(stateDir, daysRemoved, reasonByDay, bytesRemoved, oldestDayRemaining) {
65958
66424
  const logsDir = import_node_path31.default.join(stateDir, "logs");
65959
66425
  const logPath = import_node_path31.default.join(logsDir, ".pruned.jsonl");
65960
- await (0, import_promises11.mkdir)(logsDir, { recursive: true, mode: LOG_DIR_MODE2 });
66426
+ await (0, import_promises12.mkdir)(logsDir, { recursive: true, mode: LOG_DIR_MODE2 });
65961
66427
  const record2 = { ts: Date.now(), dir: "logs", daysRemoved, reasonByDay, bytesRemoved, oldestDayRemaining };
65962
- await (0, import_promises11.appendFile)(logPath, `${JSON.stringify(record2)}
66428
+ await (0, import_promises12.appendFile)(logPath, `${JSON.stringify(record2)}
65963
66429
  `, { mode: LOG_FILE_MODE2 });
65964
66430
  }
65965
66431
 
65966
66432
  // src/telemetry/turn-aggregator.ts
65967
66433
  var import_node_crypto18 = require("node:crypto");
65968
- var import_promises12 = require("node:fs/promises");
66434
+ var import_promises13 = require("node:fs/promises");
65969
66435
  var import_node_path32 = require("node:path");
65970
66436
  var BRIDGE_FILE_RE = /^bridge-(\d{4}-\d{2}-\d{2})\.jsonl$/;
65971
66437
  var PLUMBING_COUNTER_KEY = {
@@ -65998,7 +66464,7 @@ async function foldClosedDays(stateDir, today) {
65998
66464
  const logsDir = (0, import_node_path32.join)(stateDir, "logs");
65999
66465
  let entries;
66000
66466
  try {
66001
- entries = await (0, import_promises12.readdir)(logsDir);
66467
+ entries = await (0, import_promises13.readdir)(logsDir);
66002
66468
  } catch {
66003
66469
  return;
66004
66470
  }
@@ -66007,7 +66473,7 @@ async function foldClosedDays(stateDir, today) {
66007
66473
  if (!m) continue;
66008
66474
  const day = m[1];
66009
66475
  if (day === today) continue;
66010
- const raw = await (0, import_promises12.readFile)((0, import_node_path32.join)(logsDir, entry), "utf8");
66476
+ const raw = await (0, import_promises13.readFile)((0, import_node_path32.join)(logsDir, entry), "utf8");
66011
66477
  const groups = /* @__PURE__ */ new Map();
66012
66478
  let groupCounter = 0;
66013
66479
  for (const line of raw.split("\n")) {
@@ -66119,15 +66585,15 @@ async function foldClosedDays(stateDir, today) {
66119
66585
  }
66120
66586
  if (rowsByProject.size === 0) continue;
66121
66587
  const telemetryDir = (0, import_node_path32.join)(stateDir, "telemetry");
66122
- await (0, import_promises12.mkdir)(telemetryDir, { recursive: true });
66588
+ await (0, import_promises13.mkdir)(telemetryDir, { recursive: true });
66123
66589
  for (const [slug, rows] of rowsByProject) {
66124
66590
  const finalPath = (0, import_node_path32.join)(telemetryDir, `rows-${slug}-${day}.jsonl`);
66125
66591
  const tmpPath = `${finalPath}.tmp-${process.pid}-${(0, import_node_crypto18.randomBytes)(6).toString("hex")}`;
66126
66592
  try {
66127
- await (0, import_promises12.writeFile)(tmpPath, rows.map((r) => JSON.stringify(r)).join("\n") + "\n", "utf8");
66128
- await (0, import_promises12.rename)(tmpPath, finalPath);
66593
+ await (0, import_promises13.writeFile)(tmpPath, rows.map((r) => JSON.stringify(r)).join("\n") + "\n", "utf8");
66594
+ await (0, import_promises13.rename)(tmpPath, finalPath);
66129
66595
  } finally {
66130
- await (0, import_promises12.unlink)(tmpPath).catch(() => {
66596
+ await (0, import_promises13.unlink)(tmpPath).catch(() => {
66131
66597
  });
66132
66598
  }
66133
66599
  }
@@ -66135,7 +66601,7 @@ async function foldClosedDays(stateDir, today) {
66135
66601
  }
66136
66602
 
66137
66603
  // src/telemetry/daily-uploader.ts
66138
- var import_promises13 = require("node:fs/promises");
66604
+ var import_promises14 = require("node:fs/promises");
66139
66605
  var import_node_path34 = require("node:path");
66140
66606
 
66141
66607
  // src/telemetry/installation-id.ts
@@ -66176,7 +66642,7 @@ async function uploadPendingDays(stateDir, client, bridgeHealth, gateCtx) {
66176
66642
  const telemetryDir = (0, import_node_path34.join)(stateDir, "telemetry");
66177
66643
  let files;
66178
66644
  try {
66179
- files = await (0, import_promises13.readdir)(telemetryDir);
66645
+ files = await (0, import_promises14.readdir)(telemetryDir);
66180
66646
  } catch (err) {
66181
66647
  if (err?.code === "ENOENT") return;
66182
66648
  throw err;
@@ -66199,14 +66665,14 @@ async function uploadPendingDays(stateDir, client, bridgeHealth, gateCtx) {
66199
66665
  const markerPath = (0, import_node_path34.join)(telemetryDir, `.processed-${projectSlug}-${day}`);
66200
66666
  if (rowsPath === null && day >= today) {
66201
66667
  try {
66202
- await (0, import_promises13.access)(markerPath);
66668
+ await (0, import_promises14.access)(markerPath);
66203
66669
  } catch {
66204
66670
  deferred.push({ projectSlug, day });
66205
66671
  }
66206
66672
  continue;
66207
66673
  }
66208
66674
  try {
66209
- await (0, import_promises13.access)(markerPath);
66675
+ await (0, import_promises14.access)(markerPath);
66210
66676
  } catch {
66211
66677
  pending.push({ projectSlug, day, rowsPath, markerPath });
66212
66678
  }
@@ -66219,7 +66685,7 @@ async function uploadPendingDays(stateDir, client, bridgeHealth, gateCtx) {
66219
66685
  const failurePath = (0, import_node_path34.join)(telemetryDir, `.failed-${cur.projectSlug}-${cur.day}.json`);
66220
66686
  let failureState = null;
66221
66687
  try {
66222
- const data = await (0, import_promises13.readFile)(failurePath, "utf8");
66688
+ const data = await (0, import_promises14.readFile)(failurePath, "utf8");
66223
66689
  failureState = JSON.parse(data);
66224
66690
  } catch {
66225
66691
  failureState = null;
@@ -66234,7 +66700,7 @@ async function uploadPendingDays(stateDir, client, bridgeHealth, gateCtx) {
66234
66700
  let raw = "";
66235
66701
  if (cur.rowsPath !== null) {
66236
66702
  try {
66237
- raw = await (0, import_promises13.readFile)(cur.rowsPath, "utf8");
66703
+ raw = await (0, import_promises14.readFile)(cur.rowsPath, "utf8");
66238
66704
  } catch (err) {
66239
66705
  console.error(`uploadPendingDays: failed to read ${cur.rowsPath}`, err);
66240
66706
  throw err;
@@ -66250,7 +66716,7 @@ async function uploadPendingDays(stateDir, client, bridgeHealth, gateCtx) {
66250
66716
  }
66251
66717
  const gateCalls = [];
66252
66718
  try {
66253
- const rawGate = await (0, import_promises13.readFile)((0, import_node_path34.join)(telemetryDir, gateFileName(cur.projectSlug, cur.day)), "utf8");
66719
+ const rawGate = await (0, import_promises14.readFile)((0, import_node_path34.join)(telemetryDir, gateFileName(cur.projectSlug, cur.day)), "utf8");
66254
66720
  for (const line of rawGate.split("\n")) {
66255
66721
  if (!line.trim()) continue;
66256
66722
  try {
@@ -66290,14 +66756,14 @@ async function uploadPendingDays(stateDir, client, bridgeHealth, gateCtx) {
66290
66756
  if (success2) {
66291
66757
  const tmpMarker = `${cur.markerPath}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;
66292
66758
  try {
66293
- await (0, import_promises13.writeFile)(tmpMarker, "");
66294
- await (0, import_promises13.rename)(tmpMarker, cur.markerPath);
66759
+ await (0, import_promises14.writeFile)(tmpMarker, "");
66760
+ await (0, import_promises14.rename)(tmpMarker, cur.markerPath);
66295
66761
  } catch (err) {
66296
66762
  console.error(`uploadPendingDays: failed to write marker for ${cur.projectSlug}/${cur.day}`, err);
66297
66763
  }
66298
66764
  if (failureState) {
66299
66765
  try {
66300
- await (0, import_promises13.unlink)(failurePath);
66766
+ await (0, import_promises14.unlink)(failurePath);
66301
66767
  console.log(`uploadPendingDays: partition ${cur.projectSlug}/${cur.day} recovered after ${failureState.failureCount + 1} consecutive failures`);
66302
66768
  } catch (err) {
66303
66769
  console.error(`uploadPendingDays: failed to remove failure state for ${cur.projectSlug}/${cur.day}`, err);
@@ -66325,8 +66791,8 @@ async function uploadPendingDays(stateDir, client, bridgeHealth, gateCtx) {
66325
66791
  };
66326
66792
  const tmpFailurePath = `${failurePath}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;
66327
66793
  try {
66328
- await (0, import_promises13.writeFile)(tmpFailurePath, JSON.stringify(newFailureState));
66329
- await (0, import_promises13.rename)(tmpFailurePath, failurePath);
66794
+ await (0, import_promises14.writeFile)(tmpFailurePath, JSON.stringify(newFailureState));
66795
+ await (0, import_promises14.rename)(tmpFailurePath, failurePath);
66330
66796
  } catch (writeErr) {
66331
66797
  console.error(`uploadPendingDays: failed to write failure state for ${cur.projectSlug}/${cur.day}`, writeErr);
66332
66798
  }
@@ -66801,6 +67267,7 @@ function outputProjectionDisabled(env = process.env) {
66801
67267
  }
66802
67268
 
66803
67269
  // src/deploy-gate.ts
67270
+ var ROLLBACK_INVOCATION_UNCONFIRMED = "rollback_invocation_unconfirmed";
66804
67271
  var DEFAULT_DEPLOY_POLL_BUDGET_SECONDS = 1200;
66805
67272
  var DEFAULT_PROD_GRACE_SECONDS = 900;
66806
67273
  function deployPollBudgetSeconds(env = process.env) {
@@ -66811,16 +67278,18 @@ function deployPollBudgetSeconds(env = process.env) {
66811
67278
  function isRealAttempt(payload) {
66812
67279
  return !payload || payload.phase === void 0 || payload.phase === null;
66813
67280
  }
66814
- function latestByEnv(artifacts, kind, env, opts = {}) {
66815
- const matches = artifacts.filter((a) => {
67281
+ function latestArtifactByEnv(artifacts, kind, env, opts = {}) {
67282
+ return artifacts.filter((a) => {
66816
67283
  if (a.kind !== kind) return false;
66817
67284
  const payload = a.payload;
66818
67285
  if (payload?.env !== env) return false;
66819
67286
  if (opts.realAttemptsOnly && !isRealAttempt(payload)) return false;
66820
67287
  return true;
66821
- });
66822
- const last = matches[matches.length - 1];
66823
- return last ? last.payload : null;
67288
+ }).at(-1);
67289
+ }
67290
+ function latestByEnv(artifacts, kind, env, opts = {}) {
67291
+ const artifact = latestArtifactByEnv(artifacts, kind, env, opts);
67292
+ return artifact ? artifact.payload : null;
66824
67293
  }
66825
67294
  function latestGraceRecord(artifacts) {
66826
67295
  const matches = artifacts.filter(
@@ -66868,11 +67337,12 @@ async function finishWithoutPublish(deps, projectSlug, run3) {
66868
67337
  });
66869
67338
  return { kind: "done" };
66870
67339
  }
66871
- function deployApprovalItemId(runId, env) {
66872
- return `II-deploy-approve-${env}-${runId}`;
67340
+ function deployApprovalItemId(runId, env, generation = 0) {
67341
+ const attempt = generation === 0 ? "" : `${generation}-`;
67342
+ return `${DEPLOY_APPROVAL_INBOX_PREFIX}${env}-${attempt}${runId}`;
66873
67343
  }
66874
67344
  function graceCancelItemId(runId) {
66875
- return `II-grace-cancel-${runId}`;
67345
+ return `${DEPLOY_GRACE_INBOX_PREFIX}${runId}`;
66876
67346
  }
66877
67347
  var APPROVE_ANSWER = "Approve";
66878
67348
  var REJECT_ANSWER = "Reject";
@@ -66912,8 +67382,7 @@ async function prodGraceSeconds(client, projectSlug) {
66912
67382
  }
66913
67383
  return DEFAULT_PROD_GRACE_SECONDS;
66914
67384
  }
66915
- async function resolveDeployApproval(deps, projectSlug, run3, task, env) {
66916
- const itemId = deployApprovalItemId(run3.id, env);
67385
+ async function resolveDeployApproval(deps, projectSlug, run3, task, env, itemId, priorVerification) {
66917
67386
  let item = null;
66918
67387
  try {
66919
67388
  item = await findInboxQuestion(deps.client, projectSlug, itemId);
@@ -66921,22 +67390,32 @@ async function resolveDeployApproval(deps, projectSlug, run3, task, env) {
66921
67390
  return "wait";
66922
67391
  }
66923
67392
  if (!item) {
66924
- await deps.client.createInboxItem(projectSlug, {
66925
- id: itemId,
66926
- kind: "question",
66927
- taskId: task.id,
66928
- body: `Ready to deploy to ${env}? (task ${task.id} \u2014 ${task.title}, run ${run3.id})`,
66929
- origin: "deploy-gate",
66930
- questionOptions: [
66931
- { label: APPROVE_ANSWER, answer: APPROVE_ANSWER, description: `Deploy to ${env}`, recommended: true },
66932
- { label: REJECT_ANSWER, answer: REJECT_ANSWER, description: "Do not deploy \u2014 hand it off to me" }
66933
- ]
66934
- }).catch(() => {
66935
- });
67393
+ try {
67394
+ await deps.client.createInboxItem(projectSlug, {
67395
+ id: itemId,
67396
+ kind: "question",
67397
+ taskId: task.id,
67398
+ body: deployApprovalInboxBody(env, run3.id, task.id, void 0, run3.deployApprovalGeneration),
67399
+ origin: "deploy-gate",
67400
+ questionOptions: deployApprovalInboxOptions(env)
67401
+ });
67402
+ } catch (error51) {
67403
+ if (error51 instanceof MrrlinApiError && error51.code === "INVALID_DEPLOY_APPROVAL") {
67404
+ const current2 = await deps.client.getExecutionRun(projectSlug, run3.id).catch(() => null);
67405
+ if (!current2 || current2.status !== `${env}_deploy` || (current2.deployApprovalGeneration ?? 0) !== (run3.deployApprovalGeneration ?? 0)) return "phase_changed";
67406
+ return "unverified";
67407
+ }
67408
+ }
66936
67409
  return "wait";
66937
67410
  }
66938
- if (item.status === "approved" || item.answer === APPROVE_ANSWER) return "dispatch";
66939
67411
  if (item.status === "rejected" || item.answer === REJECT_ANSWER) return "reject";
67412
+ if (!matchesDeployApprovalInboxQuestion(item, env, run3.id, task, run3.deployApprovalGeneration)) return "unverified";
67413
+ if (item.status !== "pending") {
67414
+ if (priorVerification && !(Date.parse(item.decidedAt ?? "") >= Date.parse(priorVerification.createdAt))) {
67415
+ return "unverified";
67416
+ }
67417
+ return item.status === "acknowledged" && item.answer === APPROVE_ANSWER && item.verifiedOperatorDecision === true ? "dispatch" : "unverified";
67418
+ }
66940
67419
  return "wait";
66941
67420
  }
66942
67421
  async function resolveProdGrace(deps, projectSlug, run3, task, artifacts) {
@@ -67003,22 +67482,34 @@ async function findLastGoodProdAttempt(client, projectSlug, task, currentRunId)
67003
67482
  }
67004
67483
  return null;
67005
67484
  }
67006
- async function tryProdAutoRevert(deps, projectSlug, run3, task) {
67485
+ function pendingProdRevert(artifacts) {
67486
+ const payload = artifacts.find(
67487
+ (artifact) => artifact.kind === "deploy_attempt" && artifact.payload?.phase === "revert_pending"
67488
+ )?.payload;
67489
+ if (payload && typeof payload.branch === "string" && typeof payload.workflowId === "number") {
67490
+ return { branch: payload.branch, workflowId: payload.workflowId };
67491
+ }
67492
+ return void 0;
67493
+ }
67494
+ async function tryProdAutoRevert(deps, projectSlug, run3, task, pending) {
67007
67495
  try {
67008
- const lastGood = await findLastGoodProdAttempt(deps.client, projectSlug, task, run3.id);
67496
+ const lastGood = pending ?? await findLastGoodProdAttempt(deps.client, projectSlug, task, run3.id);
67009
67497
  if (!lastGood) return null;
67010
- await deps.client.appendExecutionArtifact(projectSlug, run3.id, {
67011
- id: `EA-deploy-revert-${run3.id}`,
67012
- kind: "deploy_attempt",
67013
- payload: {
67014
- env: "prod",
67015
- phase: "revert",
67016
- workflowId: lastGood.workflowId,
67017
- branch: lastGood.branch,
67018
- dispatchedAt: deps.now().toISOString()
67019
- }
67020
- }).catch(() => {
67021
- });
67498
+ if (!pending) {
67499
+ await deps.client.appendExecutionArtifact(projectSlug, run3.id, {
67500
+ id: `EA-deploy-revert-pending-${run3.id}`,
67501
+ kind: "deploy_attempt",
67502
+ payload: { env: "prod", phase: "revert_pending", ...lastGood }
67503
+ });
67504
+ }
67505
+ if (await autonomyPaused(deps.client)) return "pending";
67506
+ const recordRevertDispatch = async () => {
67507
+ await deps.client.appendExecutionArtifact(projectSlug, run3.id, {
67508
+ id: `EA-deploy-revert-${run3.id}`,
67509
+ kind: "deploy_attempt",
67510
+ payload: { env: "prod", phase: "revert", ...lastGood, dispatchedAt: deps.now().toISOString() }
67511
+ });
67512
+ };
67022
67513
  const result = await (deps.dispatchPublishOperation ?? dispatchPublishOperation)(
67023
67514
  deps.client,
67024
67515
  projectSlug,
@@ -67026,16 +67517,55 @@ async function tryProdAutoRevert(deps, projectSlug, run3, task) {
67026
67517
  task.id,
67027
67518
  run3.id,
67028
67519
  { operation: "release", env: "prod", ref: lastGood.branch, workflowId: String(lastGood.workflowId) },
67029
- void 0
67520
+ void 0,
67521
+ recordRevertDispatch,
67522
+ "rollback"
67030
67523
  );
67031
67524
  if (result.url) {
67032
67525
  await deps.client.updateExecutionRun(projectSlug, run3.id, { prodPublishRef: result.url });
67033
67526
  }
67034
67527
  return lastGood;
67035
- } catch {
67528
+ } catch (error51) {
67529
+ if (error51 instanceof PublishAuthorizationPendingError) return "pending";
67530
+ if (error51 instanceof PublishInvocationIncidentError) return error51;
67036
67531
  return null;
67037
67532
  }
67038
67533
  }
67534
+ async function finishFailedVerification(deps, projectSlug, run3, task, env, pending) {
67535
+ if (env === "prod" && task.autonomyLevel === "auto") {
67536
+ const reverted = await tryProdAutoRevert(deps, projectSlug, run3, task, pending);
67537
+ if (reverted === "pending") return { kind: "noop", reason: "rollback_authorization_pending" };
67538
+ if (reverted instanceof PublishInvocationIncidentError) {
67539
+ const reason = `${ROLLBACK_INVOCATION_UNCONFIRMED}: ${reverted.message}`;
67540
+ const itemId = `${ROLLBACK_RECONCILIATION_INBOX_PREFIX}${run3.id}`;
67541
+ const item = await deps.client.createInboxItem(projectSlug, {
67542
+ id: itemId,
67543
+ kind: "question",
67544
+ origin: "deploy-gate",
67545
+ taskId: task.id,
67546
+ rollbackInvocationId: reverted.invocationId,
67547
+ body: "Verify the production rollback in the deployment provider"
67548
+ });
67549
+ if (item.id !== itemId || item.kind !== "question" || item.origin !== "deploy-gate" || item.taskId !== task.id || item.groupId !== `rollback-invocation:${reverted.invocationId}`) {
67550
+ throw new Error("Rollback reconciliation requires its own Inbox question.");
67551
+ }
67552
+ await deps.handoff(projectSlug, task, run3, reason);
67553
+ return { kind: "handoff", reason: ROLLBACK_INVOCATION_UNCONFIRMED };
67554
+ }
67555
+ if (reverted) {
67556
+ await postRunFeed(deps.client, projectSlug, run3.id, task.id, "reverted");
67557
+ await deps.handoff(
67558
+ projectSlug,
67559
+ task,
67560
+ run3,
67561
+ `verification_failed:prod (auto-rollback: prod rollback dispatched to ${reverted.branch})`
67562
+ );
67563
+ return { kind: "handoff", reason: "verification_failed:prod:reverted" };
67564
+ }
67565
+ }
67566
+ await deps.handoff(projectSlug, task, run3, `verification_failed:${env}`);
67567
+ return { kind: "handoff", reason: `verification_failed:${env}` };
67568
+ }
67039
67569
  function shouldEvaluateGuard(provider, guard) {
67040
67570
  if (provider.computableGuards.includes(guard)) {
67041
67571
  return true;
@@ -67110,6 +67640,10 @@ async function resolveWorkflowId(deps, projectSlug, run3, task, env) {
67110
67640
  }
67111
67641
  async function runDeployGateTick(deps, projectSlug, run3, task) {
67112
67642
  const artifacts = await deps.client.listExecutionArtifacts(projectSlug, run3.id);
67643
+ const pendingRevert = pendingProdRevert(artifacts);
67644
+ if (pendingRevert) {
67645
+ return finishFailedVerification(deps, projectSlug, run3, task, "prod", pendingRevert);
67646
+ }
67113
67647
  const publishRoute = await resolvePublishRouteState(deps.client, projectSlug).catch((error51) => {
67114
67648
  throw new Error(`publish route resolution failed: ${String(error51)}`);
67115
67649
  });
@@ -67148,12 +67682,39 @@ async function runDeployGateTick(deps, projectSlug, run3, task) {
67148
67682
  if (await autonomyPaused(deps.client)) {
67149
67683
  return { kind: "noop", reason: "autonomy_paused" };
67150
67684
  }
67685
+ let approvalItemId;
67151
67686
  if (task.autonomyLevel === "human_review") {
67152
- const approval = await resolveDeployApproval(deps, projectSlug, run3, task, env);
67687
+ if (env === "prod" && run3.status === "dev_deploy") {
67688
+ try {
67689
+ await deps.client.updateExecutionRun(projectSlug, run3.id, { status: "prod_deploy" }, {
67690
+ expectedStatus: "dev_deploy",
67691
+ expectedDeployApprovalGeneration: run3.deployApprovalGeneration ?? 0
67692
+ });
67693
+ } catch (error51) {
67694
+ if (error51 instanceof MrrlinApiError && error51.code === "EXECUTION_RUN_LEASE_LOST") {
67695
+ return { kind: "noop", reason: "deploy_phase_changed" };
67696
+ }
67697
+ throw error51;
67698
+ }
67699
+ }
67700
+ const priorVerification = env === "prod" && sequence.includes("dev") ? latestArtifactByEnv(artifacts, "verification", "dev") : void 0;
67701
+ approvalItemId = deployApprovalItemId(run3.id, env, run3.deployApprovalGeneration);
67702
+ const approval = await resolveDeployApproval(deps, projectSlug, run3, task, env, approvalItemId, priorVerification);
67703
+ if (approval === "phase_changed") return { kind: "noop", reason: "deploy_phase_changed" };
67153
67704
  if (approval === "reject") {
67154
67705
  await deps.handoff(projectSlug, task, run3, `deploy_rejected:${env}`);
67155
67706
  return { kind: "handoff", reason: `deploy_rejected:${env}` };
67156
67707
  }
67708
+ if (approval === "unverified") {
67709
+ const reason = `deploy_approval_unverified:${env}`;
67710
+ await deps.handoff(
67711
+ projectSlug,
67712
+ task,
67713
+ run3,
67714
+ `${reason}: Enable API authentication, sign in as an operator, and start a fresh run to approve when the deployment reaches ${env}.`
67715
+ );
67716
+ return { kind: "handoff", reason };
67717
+ }
67157
67718
  if (approval === "wait") return { kind: "noop", reason: `deploy_approval_pending:${env}` };
67158
67719
  } else if (env === "prod" && task.autonomyLevel === "auto" && task.autoDeploy === "prod") {
67159
67720
  const grace = await resolveProdGrace(deps, projectSlug, run3, task, artifacts);
@@ -67187,15 +67748,22 @@ async function runDeployGateTick(deps, projectSlug, run3, task) {
67187
67748
  await deps.handoff(projectSlug, task, run3, "run_branch_missing");
67188
67749
  return { kind: "handoff", reason: "run_branch_missing" };
67189
67750
  }
67190
- const dispatchedAt = deps.now().toISOString();
67191
- await deps.client.appendExecutionArtifact(projectSlug, run3.id, {
67192
- id: `EA-deploy-${env}-${attemptIndex(artifacts, env) + 1}`,
67193
- kind: "deploy_attempt",
67194
- payload: { env, workflowId, branch: run3.branch ?? "", dispatchedAt }
67195
- });
67196
- await deps.client.updateExecutionRun(projectSlug, run3.id, {
67197
- status: env === "dev" ? "dev_deploy" : "prod_deploy"
67198
- });
67751
+ const reserveDispatch = async () => {
67752
+ await deps.client.appendExecutionArtifact(projectSlug, run3.id, {
67753
+ id: `EA-deploy-${env}-${attemptIndex(artifacts, env) + 1}`,
67754
+ kind: "deploy_attempt",
67755
+ payload: {
67756
+ env,
67757
+ workflowId,
67758
+ branch: run3.branch ?? "",
67759
+ dispatchedAt: deps.now().toISOString(),
67760
+ ...approvalItemId === void 0 ? {} : { approvalItemId }
67761
+ }
67762
+ });
67763
+ if (approvalItemId === void 0) {
67764
+ await deps.client.updateExecutionRun(projectSlug, run3.id, { status: `${env}_deploy` });
67765
+ }
67766
+ };
67199
67767
  try {
67200
67768
  const operation = env === "dev" ? "preview" : "release";
67201
67769
  const result = await (deps.dispatchPublishOperation ?? dispatchPublishOperation)(
@@ -67205,7 +67773,10 @@ async function runDeployGateTick(deps, projectSlug, run3, task) {
67205
67773
  task.id,
67206
67774
  run3.id,
67207
67775
  { operation, env, ref: run3.branch, workflowId: String(workflowId) },
67208
- void 0
67776
+ void 0,
67777
+ reserveDispatch,
67778
+ void 0,
67779
+ run3.deployApprovalGeneration ? approvalItemId : void 0
67209
67780
  );
67210
67781
  if (result.url) {
67211
67782
  await deps.client.updateExecutionRun(
@@ -67215,6 +67786,12 @@ async function runDeployGateTick(deps, projectSlug, run3, task) {
67215
67786
  );
67216
67787
  }
67217
67788
  } catch (error51) {
67789
+ if (error51 instanceof PublishAuthorizationPendingError) {
67790
+ return { kind: "noop", reason: `publish_authorization_pending:${env}` };
67791
+ }
67792
+ if (error51 instanceof MrrlinApiError && error51.code === "DEPLOY_APPROVAL_STATE_CHANGED") {
67793
+ return { kind: "noop", reason: "deploy_phase_changed" };
67794
+ }
67218
67795
  if (String(error51).includes("publish_preview_unavailable")) {
67219
67796
  if (taskRequiresPage(task)) {
67220
67797
  await deps.handoff(projectSlug, task, run3, "publish_preview_unavailable:dev");
@@ -67374,21 +67951,7 @@ async function runDeployGateTick(deps, projectSlug, run3, task) {
67374
67951
  }
67375
67952
  });
67376
67953
  if (verdict.verdict === "fail") {
67377
- if (env === "prod" && task.autonomyLevel === "auto") {
67378
- const reverted = await tryProdAutoRevert(deps, projectSlug, run3, task);
67379
- if (reverted) {
67380
- await postRunFeed(deps.client, projectSlug, run3.id, task.id, "reverted");
67381
- await deps.handoff(
67382
- projectSlug,
67383
- task,
67384
- run3,
67385
- `verification_failed:prod (auto-rollback: prod rollback dispatched to ${reverted.branch})`
67386
- );
67387
- return { kind: "handoff", reason: "verification_failed:prod:reverted" };
67388
- }
67389
- }
67390
- await deps.handoff(projectSlug, task, run3, `verification_failed:${env}`);
67391
- return { kind: "handoff", reason: `verification_failed:${env}` };
67954
+ return finishFailedVerification(deps, projectSlug, run3, task, env);
67392
67955
  }
67393
67956
  await postRunFeed(
67394
67957
  deps.client,
@@ -70691,7 +71254,14 @@ function isRunRecoverableByThisBridge(run3, worktreeRoot) {
70691
71254
  return relative === "" || relative.length > 0 && !relative.startsWith("..") && !import_node_path35.default.isAbsolute(relative);
70692
71255
  }
70693
71256
  async function deployGateHandoff(deps, projectSlug, task, runId, reason, leaseId) {
70694
- await deps.client.updateExecutionRun(projectSlug, runId, { status: "failed", finishedAt: (/* @__PURE__ */ new Date()).toISOString(), leaseId: leaseId ?? void 0 }).catch(() => {
71257
+ const isRollbackReconciliation = reason.startsWith(`${ROLLBACK_INVOCATION_UNCONFIRMED}:`);
71258
+ const finishRun = deps.client.updateExecutionRun(projectSlug, runId, {
71259
+ status: "failed",
71260
+ finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
71261
+ leaseId: leaseId ?? void 0
71262
+ });
71263
+ if (isRollbackReconciliation) await finishRun;
71264
+ else await finishRun.catch(() => {
70695
71265
  });
70696
71266
  await deps.client.appendExecutionArtifact(projectSlug, runId, {
70697
71267
  id: newArtifactId(),
@@ -70705,6 +71275,7 @@ async function deployGateHandoff(deps, projectSlug, task, runId, reason, leaseId
70705
71275
  }
70706
71276
  }).catch(() => {
70707
71277
  });
71278
+ if (isRollbackReconciliation) return;
70708
71279
  await deps.client.createInboxItem(projectSlug, {
70709
71280
  id: `II-${import_node_crypto20.default.randomUUID()}`,
70710
71281
  kind: "handoff",
@@ -70901,7 +71472,7 @@ async function runAsyncBackstopSweep(deps, drive = (slug, jobId) => driveAsyncJo
70901
71472
 
70902
71473
  // src/bridge-artifacts.ts
70903
71474
  var import_node_fs23 = __toESM(require("node:fs"), 1);
70904
- var import_promises14 = __toESM(require("node:fs/promises"), 1);
71475
+ var import_promises15 = __toESM(require("node:fs/promises"), 1);
70905
71476
  var import_node_path36 = __toESM(require("node:path"), 1);
70906
71477
  var DEFAULT_MAX_ARTIFACTS_BYTES = 500 * 1024 * 1024;
70907
71478
  var DEFAULT_MAX_ARTIFACT_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
@@ -70927,9 +71498,9 @@ async function writeLocalArtifact(id, payload, baseStateDir) {
70927
71498
  ensureDir(artifactsDir);
70928
71499
  const filePath = safeArtifactPath(artifactsDir, id);
70929
71500
  const content = JSON.stringify(payload ?? {});
70930
- await import_promises14.default.writeFile(filePath, content, { mode: 384, encoding: "utf8" });
71501
+ await import_promises15.default.writeFile(filePath, content, { mode: 384, encoding: "utf8" });
70931
71502
  try {
70932
- await import_promises14.default.chmod(filePath, 384);
71503
+ await import_promises15.default.chmod(filePath, 384);
70933
71504
  } catch {
70934
71505
  }
70935
71506
  return filePath;
@@ -70938,7 +71509,7 @@ async function readLocalArtifact(id, baseStateDir) {
70938
71509
  const artifactsDir = resolveArtifactsDir(baseStateDir);
70939
71510
  try {
70940
71511
  const filePath = safeArtifactPath(artifactsDir, id);
70941
- const content = await import_promises14.default.readFile(filePath, "utf8");
71512
+ const content = await import_promises15.default.readFile(filePath, "utf8");
70942
71513
  return JSON.parse(content);
70943
71514
  } catch (err) {
70944
71515
  if (err?.code === "ENOENT") {
@@ -70953,7 +71524,7 @@ async function cleanArtifacts(baseStateDir, options) {
70953
71524
  const maxTotalBytes = options?.maxTotalBytes ?? DEFAULT_MAX_ARTIFACTS_BYTES;
70954
71525
  let entries = [];
70955
71526
  try {
70956
- entries = await import_promises14.default.readdir(artifactsDir);
71527
+ entries = await import_promises15.default.readdir(artifactsDir);
70957
71528
  } catch {
70958
71529
  return { deletedCount: 0, deletedBytes: 0 };
70959
71530
  }
@@ -70965,9 +71536,9 @@ async function cleanArtifacts(baseStateDir, options) {
70965
71536
  if (!name.endsWith(".json")) continue;
70966
71537
  const filePath = import_node_path36.default.join(artifactsDir, name);
70967
71538
  try {
70968
- const stat3 = await import_promises14.default.stat(filePath);
71539
+ const stat3 = await import_promises15.default.stat(filePath);
70969
71540
  if (now - stat3.mtimeMs > maxAgeMs) {
70970
- await import_promises14.default.unlink(filePath);
71541
+ await import_promises15.default.unlink(filePath);
70971
71542
  deletedCount++;
70972
71543
  deletedBytes += stat3.size;
70973
71544
  } else {
@@ -70982,7 +71553,7 @@ async function cleanArtifacts(baseStateDir, options) {
70982
71553
  for (const f of files) {
70983
71554
  if (currentTotalBytes <= maxTotalBytes) break;
70984
71555
  try {
70985
- await import_promises14.default.unlink(f.path);
71556
+ await import_promises15.default.unlink(f.path);
70986
71557
  deletedCount++;
70987
71558
  deletedBytes += f.size;
70988
71559
  currentTotalBytes -= f.size;
@@ -74411,9 +74982,9 @@ var RelayClient = class {
74411
74982
  this.socket = null;
74412
74983
  this.nextHeartbeatAt = Number.POSITIVE_INFINITY;
74413
74984
  if (this.stopped || this.register === null) return;
74414
- const delay2 = this.backoff[Math.min(this.backoffIndex, this.backoff.length - 1)] ?? 0;
74985
+ const delay3 = this.backoff[Math.min(this.backoffIndex, this.backoff.length - 1)] ?? 0;
74415
74986
  this.backoffIndex += 1;
74416
- this.reconnectAt = this.deps.now() + delay2;
74987
+ this.reconnectAt = this.deps.now() + delay3;
74417
74988
  }
74418
74989
  onMessage(data) {
74419
74990
  let frame;
@@ -75449,7 +76020,7 @@ var import_node_crypto22 = __toESM(require("node:crypto"), 1);
75449
76020
  var import_node_zlib = __toESM(require("node:zlib"), 1);
75450
76021
 
75451
76022
  // src/verification-egress-policy.ts
75452
- var import_promises15 = __toESM(require("node:dns/promises"), 1);
76023
+ var import_promises16 = __toESM(require("node:dns/promises"), 1);
75453
76024
  var MAX_REDIRECT_HOPS = 5;
75454
76025
  var MAX_RESPONSE_BYTES = 5 * 1024 * 1024;
75455
76026
  var MAX_DECOMPRESSED_BYTES = 10 * 1024 * 1024;
@@ -75726,7 +76297,7 @@ async function resolveAndPinAddress(hostname3, customResolver) {
75726
76297
  };
75727
76298
  }
75728
76299
  const allIps = [];
75729
- const resolver = customResolver ?? import_promises15.default;
76300
+ const resolver = customResolver ?? import_promises16.default;
75730
76301
  try {
75731
76302
  if (resolver.resolve4) {
75732
76303
  const aRecords = await resolver.resolve4(cleanHost);
@@ -82793,7 +83364,7 @@ function uninstallService(deps) {
82793
83364
  }
82794
83365
 
82795
83366
  // src/uninstall-codex.ts
82796
- var import_promises17 = __toESM(require("node:fs/promises"), 1);
83367
+ var import_promises18 = __toESM(require("node:fs/promises"), 1);
82797
83368
  var import_node_os24 = __toESM(require("node:os"), 1);
82798
83369
  var import_node_path45 = __toESM(require("node:path"), 1);
82799
83370
  var toml5 = __toESM(require_toml(), 1);
@@ -82805,7 +83376,7 @@ function resolveCodexHome3(options) {
82805
83376
  }
82806
83377
  async function pathExists6(target) {
82807
83378
  try {
82808
- await import_promises17.default.access(target);
83379
+ await import_promises18.default.access(target);
82809
83380
  return true;
82810
83381
  } catch {
82811
83382
  return false;
@@ -82819,8 +83390,8 @@ async function uninstallCodex(options = {}) {
82819
83390
  if (!await pathExists6(configPath)) {
82820
83391
  return { action: "missing", configPath, prompts: await removePrompts() };
82821
83392
  }
82822
- const realPath = await import_promises17.default.realpath(configPath).catch(() => configPath);
82823
- const existing = await import_promises17.default.readFile(realPath, "utf8");
83393
+ const realPath = await import_promises18.default.realpath(configPath).catch(() => configPath);
83394
+ const existing = await import_promises18.default.readFile(realPath, "utf8");
82824
83395
  let parsed = null;
82825
83396
  try {
82826
83397
  parsed = toml5.parse(existing);
@@ -82837,7 +83408,7 @@ async function uninstallCodex(options = {}) {
82837
83408
  return { action: "noop", configPath: realPath, prompts: await removePrompts() };
82838
83409
  }
82839
83410
  const stripped = existing.replace(MRRLIN_BLOCK_RE, (match) => match.startsWith("\n") ? "\n" : "").replace(/\n{3,}/g, "\n\n").replace(/^\n+/, "");
82840
- await import_promises17.default.writeFile(realPath, stripped, { mode: 384 });
83411
+ await import_promises18.default.writeFile(realPath, stripped, { mode: 384 });
82841
83412
  return { action: "removed", configPath: realPath, prompts: await removePrompts() };
82842
83413
  }
82843
83414
  async function uninstallPrompts(codexHome, names) {
@@ -82847,7 +83418,7 @@ async function uninstallPrompts(codexHome, names) {
82847
83418
  for (const name of names) {
82848
83419
  const promptPath = import_node_path45.default.join(promptsDir, `${name}.md`);
82849
83420
  try {
82850
- await import_promises17.default.unlink(promptPath);
83421
+ await import_promises18.default.unlink(promptPath);
82851
83422
  out.push({ name, action: "removed", promptPath });
82852
83423
  } catch (error51) {
82853
83424
  const code = error51?.code;
@@ -83327,7 +83898,7 @@ function removeBridgeLaunchAgent(deps) {
83327
83898
  }
83328
83899
 
83329
83900
  // src/extract/command.ts
83330
- var import_promises18 = require("node:fs/promises");
83901
+ var import_promises19 = require("node:fs/promises");
83331
83902
  var import_node_path48 = require("node:path");
83332
83903
  function parseArgs(args) {
83333
83904
  const map2 = /* @__PURE__ */ new Map();
@@ -83368,7 +83939,7 @@ Missing required flag(s): ${missing.join(
83368
83939
  const logPath = (0, import_node_path48.join)(deps.stateDir, "logs", `bridge-${day}.jsonl`);
83369
83940
  let raw;
83370
83941
  try {
83371
- raw = await (0, import_promises18.readFile)(logPath, "utf8");
83942
+ raw = await (0, import_promises19.readFile)(logPath, "utf8");
83372
83943
  } catch {
83373
83944
  continue;
83374
83945
  }
@@ -83402,7 +83973,7 @@ Missing required flag(s): ${missing.join(
83402
83973
  }
83403
83974
  const outputText = cappedLines.join("\n");
83404
83975
  if (outPath) {
83405
- await (0, import_promises18.writeFile)(outPath, outputText, "utf8");
83976
+ await (0, import_promises19.writeFile)(outPath, outputText, "utf8");
83406
83977
  return {
83407
83978
  ok: true,
83408
83979
  message: `Wrote extract to ${outPath}`,