@mrrlin-dev/mcp 0.4.236 → 0.4.247

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 +1114 -80
  2. package/package.json +1 -1
package/dist/bin.cjs CHANGED
@@ -17448,6 +17448,7 @@ var init_operationIds = __esm({
17448
17448
  beginColdWorkV2: "beginColdWorkV2",
17449
17449
  parkColdWork: "parkColdWork",
17450
17450
  restartReconciledColdWork: "restartReconciledColdWork",
17451
+ closeParkedColdWork: "closeParkedColdWork",
17451
17452
  registerDrainSupervision: "registerDrainSupervision",
17452
17453
  relayDrainStatement: "relayDrainStatement",
17453
17454
  beginColdWorkV3: "beginColdWorkV3",
@@ -17521,6 +17522,7 @@ var init_operationIds = __esm({
17521
17522
  answerIntentClarification: "answerIntentClarification",
17522
17523
  confirmIntentProposal: "confirmIntentProposal",
17523
17524
  refreshIntentProposal: "refreshIntentProposal",
17525
+ declineIntentProposal: "declineIntentProposal",
17524
17526
  getIntentConfirmation: "getIntentConfirmation",
17525
17527
  resolveAccount: "resolveAccount",
17526
17528
  linkAccountIdentity: "linkAccountIdentity",
@@ -18378,7 +18380,7 @@ var init_task_notes = __esm({
18378
18380
  });
18379
18381
 
18380
18382
  // ../../packages/schemas/dist/intent.js
18381
- var taskImpactSchema, autonomyLevelSchema, autoDeploySchema, mrrlinOperatorTranscriptMessageSchema, mrrlinOperatorTranscriptAppendSchema, mrrlinOperatorTranscriptListSchema, operatorTranscriptMessageResponseSchema, operatorTranscriptListResponseSchema, mrrlinIntentProposalStateSchema, mrrlinIntentProposalSchema, mrrlinIntentProposalCreateSchema, intentProposalResponseSchema, intentProposalMaybeResponseSchema, mrrlinIntentClarificationStateSchema, mrrlinIntentClarificationSchema, mrrlinIntentClarificationRecordSchema, mrrlinIntentClarificationAnswerSchema, intentClarificationResponseSchema, mrrlinIntentConfirmRequestSchema, mrrlinIntentConfirmResponseSchema, intentConfirmResultResponseSchema, mrrlinIntentRefreshRequestSchema, mrrlinIntentRefreshOutcomeSchema, mrrlinIntentRefreshResponseSchema, intentRefreshResultResponseSchema, mrrlinIntentConfirmationSchema, intentConfirmationMaybeResponseSchema, intentProposalListResponseSchema;
18383
+ var taskImpactSchema, autonomyLevelSchema, autoDeploySchema, mrrlinOperatorTranscriptMessageSchema, mrrlinOperatorTranscriptAppendSchema, mrrlinOperatorTranscriptListSchema, operatorTranscriptMessageResponseSchema, operatorTranscriptListResponseSchema, mrrlinIntentProposalStateSchema, mrrlinIntentProposalSchema, mrrlinIntentProposalCreateSchema, intentProposalResponseSchema, intentProposalMaybeResponseSchema, mrrlinIntentClarificationStateSchema, mrrlinIntentClarificationSchema, mrrlinIntentClarificationRecordSchema, mrrlinIntentClarificationAnswerSchema, intentClarificationResponseSchema, mrrlinIntentConfirmRequestSchema, mrrlinIntentConfirmResponseSchema, intentConfirmResultResponseSchema, mrrlinIntentRefreshRequestSchema, mrrlinIntentRefreshOutcomeSchema, mrrlinIntentRefreshResponseSchema, intentRefreshResultResponseSchema, mrrlinIntentDeclineRequestSchema, mrrlinIntentDeclineResponseSchema, intentDeclineResultResponseSchema, mrrlinIntentConfirmationSchema, intentConfirmationMaybeResponseSchema, intentProposalListStateSchema, intentProposalListResponseSchema;
18382
18384
  var init_intent = __esm({
18383
18385
  "../../packages/schemas/dist/intent.js"() {
18384
18386
  "use strict";
@@ -18537,6 +18539,28 @@ var init_intent = __esm({
18537
18539
  intentRefreshResultResponseSchema = external_exports.object({
18538
18540
  data: mrrlinIntentRefreshResponseSchema
18539
18541
  });
18542
+ mrrlinIntentDeclineRequestSchema = external_exports.object({
18543
+ expectedVersion: external_exports.number().int().min(1)
18544
+ }).strict();
18545
+ mrrlinIntentDeclineResponseSchema = external_exports.discriminatedUnion("ok", [
18546
+ external_exports.object({
18547
+ ok: external_exports.literal(true),
18548
+ already_declined: external_exports.boolean(),
18549
+ proposal_id: external_exports.string().uuid(),
18550
+ proposal_version: external_exports.number().int(),
18551
+ state: external_exports.literal("rejected")
18552
+ }),
18553
+ external_exports.object({
18554
+ ok: external_exports.literal(false),
18555
+ code: external_exports.string(),
18556
+ message: external_exports.string(),
18557
+ current_state: external_exports.string().optional(),
18558
+ current_version: external_exports.number().int().optional()
18559
+ })
18560
+ ]);
18561
+ intentDeclineResultResponseSchema = external_exports.object({
18562
+ data: mrrlinIntentDeclineResponseSchema
18563
+ });
18540
18564
  mrrlinIntentConfirmationSchema = external_exports.object({
18541
18565
  id: external_exports.string().uuid(),
18542
18566
  projectSlug: external_exports.string().min(1),
@@ -18553,6 +18577,7 @@ var init_intent = __esm({
18553
18577
  intentConfirmationMaybeResponseSchema = external_exports.object({
18554
18578
  data: mrrlinIntentConfirmationSchema.nullable()
18555
18579
  });
18580
+ intentProposalListStateSchema = external_exports.enum(["actionable", "declined"]);
18556
18581
  intentProposalListResponseSchema = external_exports.object({
18557
18582
  data: external_exports.array(mrrlinIntentProposalSchema)
18558
18583
  });
@@ -19347,6 +19372,13 @@ var init_integration_connections = __esm({
19347
19372
  authorizationGeneration: external_exports.number().int().min(1),
19348
19373
  configDigest: external_exports.string().regex(/^[0-9a-f]{64}$/),
19349
19374
  bindingRevision: external_exports.number().int().min(1).default(1),
19375
+ publisherTarget: external_exports.object({
19376
+ targetId: external_exports.string().min(1).max(128),
19377
+ endpoint: external_exports.string().url(),
19378
+ publicOrigin: external_exports.string().url(),
19379
+ rootDirectory: external_exports.string().optional(),
19380
+ buildSettingsDigest: external_exports.string().regex(/^[0-9a-f]{64}$/).optional()
19381
+ }).strict().optional(),
19350
19382
  ownerActor: external_exports.string().min(1),
19351
19383
  createdAt: external_exports.string().datetime(),
19352
19384
  updatedAt: external_exports.string().datetime()
@@ -19535,7 +19567,9 @@ var init_publisher_profiles = __esm({
19535
19567
  endpoint: external_exports.string().url().refine(isHttpsOrLoopbackTestUrl, { message: "Endpoint must use https: (http: permitted only on loopback in test mode)" }),
19536
19568
  targetId: external_exports.string().min(1).max(128),
19537
19569
  publicOrigin: external_exports.string().url().refine(isHttpsOrLoopbackTestUrl, { message: "Public origin must use https: (http: permitted only on loopback in test mode)" }),
19538
- rootDirectory: external_exports.string().optional(),
19570
+ // Omit rather than send "": the target fingerprint treats "" as absent but the
19571
+ // dispatch fence compares the stored jsonb, so "" would drift at dispatch.
19572
+ rootDirectory: external_exports.string().min(1).optional(),
19539
19573
  buildSettingsDigest: external_exports.string().regex(/^[0-9a-f]{64}$/).optional(),
19540
19574
  configRevision: external_exports.number().int().min(1).default(1),
19541
19575
  authorizationGeneration: external_exports.number().int().min(1).default(1),
@@ -19648,6 +19682,9 @@ var init_vercel_publishing = __esm({
19648
19682
  invocationId: external_exports.string().min(1).nullable().optional(),
19649
19683
  evidenceDigest: external_exports.string().nullable().optional(),
19650
19684
  dispatchCount: external_exports.number().int().min(0).default(0).optional(),
19685
+ /** The operation id the bridge actually dispatched (sent to the publisher, stamped into the live
19686
+ * marker). Absent on older rows and older APIs; closure then falls back to the marker-only check. */
19687
+ dispatchedOperationId: external_exports.string().min(1).nullable().optional(),
19651
19688
  createdAt: external_exports.string().datetime(),
19652
19689
  updatedAt: external_exports.string().datetime()
19653
19690
  });
@@ -19712,7 +19749,10 @@ var init_vercel_publishing = __esm({
19712
19749
  errorMessage: external_exports.string().min(1)
19713
19750
  });
19714
19751
  CommitPublishDispatchRequestSchema = external_exports.object({
19715
- leaseOwner: external_exports.string().min(1)
19752
+ leaseOwner: external_exports.string().min(1),
19753
+ /** The operation id this dispatch sends to the publisher. Optional so an older bridge still commits;
19754
+ * the row then keeps it null and closure falls back to the marker-only check. */
19755
+ operationId: external_exports.string().min(1).optional()
19716
19756
  });
19717
19757
  }
19718
19758
  });
@@ -53092,7 +53132,7 @@ var require_snapshot_recorder = __commonJS({
53092
53132
  "../../node_modules/.pnpm/undici@7.30.2/node_modules/undici/lib/mock/snapshot-recorder.js"(exports2, module2) {
53093
53133
  "use strict";
53094
53134
  var { writeFile: writeFile7, readFile: readFile10, mkdir: mkdir4 } = require("node:fs/promises");
53095
- var { dirname: dirname3, resolve: resolve4 } = require("node:path");
53135
+ var { dirname: dirname4, resolve: resolve4 } = require("node:path");
53096
53136
  var { setTimeout: setTimeout2, clearTimeout: clearTimeout2 } = require("node:timers");
53097
53137
  var { InvalidArgumentError, UndiciError } = require_errors2();
53098
53138
  var { hashId, isUrlExcludedFactory, normalizeHeaders: normalizeHeaders2, createHeaderFilters } = require_snapshot_utils();
@@ -53323,7 +53363,7 @@ var require_snapshot_recorder = __commonJS({
53323
53363
  throw new InvalidArgumentError("Snapshot path is required");
53324
53364
  }
53325
53365
  const resolvedPath = resolve4(path42);
53326
- await mkdir4(dirname3(resolvedPath), { recursive: true });
53366
+ await mkdir4(dirname4(resolvedPath), { recursive: true });
53327
53367
  const data = Array.from(this.#snapshots.entries()).map(([hash3, snapshot]) => ({
53328
53368
  hash: hash3,
53329
53369
  snapshot
@@ -78724,6 +78764,14 @@ function createMrrlinClient(config2) {
78724
78764
  });
78725
78765
  return body?.data?.applied === true;
78726
78766
  },
78767
+ async closeParkedColdWork(projectSlug, runId, attemptId) {
78768
+ const body = await request(`${projectPath(projectSlug)}/execution-runs/${encodeURIComponent(runId)}/close-parked-cold-work`, {
78769
+ method: "POST",
78770
+ headers: { "content-type": "application/json" },
78771
+ body: JSON.stringify({ attemptId })
78772
+ });
78773
+ return body?.data?.applied === true;
78774
+ },
78727
78775
  async publishExecutorThread(projectSlug, taskId, input) {
78728
78776
  try {
78729
78777
  const body = await request(`${projectPath(projectSlug)}/tasks/${encodeURIComponent(taskId)}/publish-executor-thread`, {
@@ -79072,8 +79120,9 @@ function createMrrlinClient(config2) {
79072
79120
  });
79073
79121
  return intentProposalResponseSchema.parse(body).data;
79074
79122
  },
79075
- async listIntentProposals(projectSlug) {
79076
- const body = await request(`${projectPath(projectSlug)}/intent/proposals`);
79123
+ async listIntentProposals(projectSlug, options) {
79124
+ const query = options?.state ? `?state=${encodeURIComponent(options.state)}` : "";
79125
+ const body = await request(`${projectPath(projectSlug)}/intent/proposals${query}`);
79077
79126
  return intentProposalListResponseSchema.parse(body).data;
79078
79127
  },
79079
79128
  async getIntentProposal(projectSlug, proposalId, version2) {
@@ -79144,6 +79193,27 @@ function createMrrlinClient(config2) {
79144
79193
  throw error51;
79145
79194
  }
79146
79195
  },
79196
+ async declineIntentProposal(projectSlug, proposalId, input) {
79197
+ try {
79198
+ const body = await request(`${projectPath(projectSlug)}/intent/proposals/${encodeURIComponent(proposalId)}/decline`, {
79199
+ method: "POST",
79200
+ headers: { "content-type": "application/json" },
79201
+ body: JSON.stringify(input)
79202
+ });
79203
+ return intentDeclineResultResponseSchema.parse(body).data;
79204
+ } catch (error51) {
79205
+ if (error51 instanceof MrrlinApiError && (error51.status === 404 || error51.status === 409)) {
79206
+ try {
79207
+ const parsed = JSON.parse(error51.responseBody);
79208
+ const refusal = mrrlinIntentDeclineResponseSchema.safeParse(parsed?.data);
79209
+ if (refusal.success && !refusal.data.ok)
79210
+ return refusal.data;
79211
+ } catch {
79212
+ }
79213
+ }
79214
+ throw error51;
79215
+ }
79216
+ },
79147
79217
  async getIntentConfirmation(projectSlug, proposalId, version2) {
79148
79218
  try {
79149
79219
  const body = await request(`${projectPath(projectSlug)}/intent/confirmations/${encodeURIComponent(proposalId)}/${encodeURIComponent(String(version2))}`);
@@ -79378,6 +79448,14 @@ function createMrrlinClient(config2) {
79378
79448
  });
79379
79449
  return Boolean(body?.success ?? true);
79380
79450
  },
79451
+ async enrollManagedPublisher(projectSlug, input) {
79452
+ const body = await request(`${projectPath(projectSlug)}/managed-publisher`, {
79453
+ method: "PUT",
79454
+ headers: { "content-type": "application/json" },
79455
+ body: JSON.stringify(input)
79456
+ });
79457
+ return EnrollManagedPublisherResponseSchema.parse(body);
79458
+ },
79381
79459
  async listIntegrationCatalog(options = {}) {
79382
79460
  const params = new URLSearchParams();
79383
79461
  const q = options.query ?? options.q;
@@ -82360,6 +82438,10 @@ function computeSetupRequestDigest(action, params) {
82360
82438
  const canonical = JSON.stringify(canonicalizeValue(params));
82361
82439
  return (0, import_node_crypto6.createHash)("sha256").update(`${action}:${canonical}`).digest("hex");
82362
82440
  }
82441
+ function computeToolSchemaDigest(schema) {
82442
+ const normalized = typeof schema === "string" ? schema : JSON.stringify(canonicalizeValue(schema));
82443
+ return (0, import_node_crypto6.createHash)("sha256").update(normalized).digest("hex");
82444
+ }
82363
82445
  function computePreparedEnvelopeDigest(envelope) {
82364
82446
  if ("profileId" in envelope && envelope.profileId === "publisher.mcp.v1") {
82365
82447
  const canonical2 = {
@@ -88204,6 +88286,15 @@ async function executeHttpRequest(targetUrl, init, signal, allowLocal = false, m
88204
88286
  function createSafeFetch(options) {
88205
88287
  return (url2, init) => safeFetch(url2, init, options);
88206
88288
  }
88289
+ function stampFinalUrl(response, finalUrl) {
88290
+ if (!response.url) {
88291
+ try {
88292
+ Object.defineProperty(response, "url", { value: finalUrl, configurable: true });
88293
+ } catch {
88294
+ }
88295
+ }
88296
+ return response;
88297
+ }
88207
88298
  async function safeFetch(inputUrl, init, policy) {
88208
88299
  const allowLocal = process.env.NODE_ENV !== "production" && (policy?.allowLocalEndpoints ?? false);
88209
88300
  const maxRedirects = policy?.maxRedirects ?? DEFAULT_MAX_REDIRECTS;
@@ -88263,7 +88354,7 @@ async function safeFetch(inputUrl, init, policy) {
88263
88354
  } else {
88264
88355
  cleanup();
88265
88356
  }
88266
- return response;
88357
+ return stampFinalUrl(response, currentUrl);
88267
88358
  }
88268
88359
  try {
88269
88360
  await response.body?.cancel();
@@ -88316,7 +88407,7 @@ async function safeFetch(inputUrl, init, policy) {
88316
88407
  } else {
88317
88408
  cleanup();
88318
88409
  }
88319
- return response;
88410
+ return stampFinalUrl(response, currentUrl);
88320
88411
  } catch (fetchErr) {
88321
88412
  cleanup();
88322
88413
  throw fetchErr;
@@ -89327,12 +89418,33 @@ var LocalConnectionStore = class _LocalConnectionStore {
89327
89418
  const connectionId = existing?.id ?? input.id ?? import_node_crypto7.default.randomUUID();
89328
89419
  let configRevision = existing ? existing.configRevision : 1;
89329
89420
  let authorizationGeneration = existing ? existing.authorizationGeneration : input.authorizationGeneration ?? 1;
89421
+ let publisherSecretRevisionAdvanced = false;
89330
89422
  const inputRefs = existing?.inputRefs ? { ...existing.inputRefs } : {};
89331
89423
  if (input.secretValues && Object.keys(input.secretValues).length > 0) {
89332
89424
  if (!this.isVaultUnlocked()) {
89333
89425
  throw new VaultLockedError();
89334
89426
  }
89335
89427
  const vaultSecrets = await this.readDecryptedSecrets();
89428
+ const isPublisher = (input.legacyServerId ?? existing?.legacyServerId) === "publisher.mcp.v1";
89429
+ const publisherSecretsChanged = existing && isPublisher && Object.entries(input.secretValues).some(([slot, value]) => {
89430
+ const ref = inputRefs[slot];
89431
+ return !ref || vaultSecrets[ref] !== value;
89432
+ });
89433
+ if (existing && publisherSecretsChanged) {
89434
+ configRevision += 1;
89435
+ authorizationGeneration += 1;
89436
+ publisherSecretRevisionAdvanced = true;
89437
+ const invalidated = ConnectionRecordSchema.parse({
89438
+ ...existing,
89439
+ configRevision,
89440
+ authorizationGeneration,
89441
+ updatedAt: now
89442
+ });
89443
+ writeProtectedJsonAtomic(this.getConnectionsPath(), {
89444
+ version: "v1",
89445
+ connections: [...existingList.filter((c) => c.id !== connectionId), invalidated]
89446
+ }, true);
89447
+ }
89336
89448
  for (const [slotName, secretValue] of Object.entries(input.secretValues)) {
89337
89449
  let ref = inputRefs[slotName];
89338
89450
  if (!ref) {
@@ -89352,7 +89464,7 @@ var LocalConnectionStore = class _LocalConnectionStore {
89352
89464
  const existingSlotKeys = Object.keys(existing.inputRefs ?? {}).sort();
89353
89465
  const newSlotKeys = Object.keys(inputRefs).sort();
89354
89466
  const secretSlotsChanged = JSON.stringify(existingSlotKeys) !== JSON.stringify(newSlotKeys);
89355
- if (endpointChanged || commandChanged || argsChanged || envKeysChanged || originChanged || secretSlotsChanged) {
89467
+ if (!publisherSecretRevisionAdvanced && (endpointChanged || commandChanged || argsChanged || envKeysChanged || originChanged || secretSlotsChanged)) {
89356
89468
  configRevision += 1;
89357
89469
  authorizationGeneration += 1;
89358
89470
  }
@@ -89431,29 +89543,31 @@ var LocalConnectionStore = class _LocalConnectionStore {
89431
89543
  });
89432
89544
  }
89433
89545
  async resolveConnection(connectionId) {
89434
- const conn = this.getConnection(connectionId);
89435
- if (!conn) {
89436
- throw new Error(`Connection not found: ${connectionId}`);
89437
- }
89438
- if (!conn.inputRefs || Object.keys(conn.inputRefs).length === 0) {
89439
- return { connection: conn, secrets: {} };
89440
- }
89441
- if (!this.isVaultUnlocked()) {
89442
- throw new VaultLockedError();
89443
- }
89444
- const decryptedMap = await this.readDecryptedSecrets();
89445
- const resolvedSecrets = {};
89446
- for (const [slotName, ref] of Object.entries(conn.inputRefs)) {
89447
- const val = decryptedMap[ref];
89448
- if (val === void 0) {
89449
- throw new MissingSecretError(slotName);
89546
+ return withStoreLock(this.integrationsDir, async () => {
89547
+ const conn = this.getConnection(connectionId);
89548
+ if (!conn) {
89549
+ throw new Error(`Connection not found: ${connectionId}`);
89450
89550
  }
89451
- resolvedSecrets[slotName] = val;
89452
- }
89453
- return {
89454
- connection: conn,
89455
- secrets: resolvedSecrets
89456
- };
89551
+ if (!conn.inputRefs || Object.keys(conn.inputRefs).length === 0) {
89552
+ return { connection: conn, secrets: {} };
89553
+ }
89554
+ if (!this.isVaultUnlocked()) {
89555
+ throw new VaultLockedError();
89556
+ }
89557
+ const decryptedMap = await this.readDecryptedSecrets();
89558
+ const resolvedSecrets = {};
89559
+ for (const [slotName, ref] of Object.entries(conn.inputRefs)) {
89560
+ const val = decryptedMap[ref];
89561
+ if (val === void 0) {
89562
+ throw new MissingSecretError(slotName);
89563
+ }
89564
+ resolvedSecrets[slotName] = val;
89565
+ }
89566
+ return {
89567
+ connection: conn,
89568
+ secrets: resolvedSecrets
89569
+ };
89570
+ });
89457
89571
  }
89458
89572
  async advanceAuthorizationGeneration(connectionId) {
89459
89573
  return withStoreLock(this.integrationsDir, async () => {
@@ -91984,7 +92098,6 @@ var VercelAdapter = class {
91984
92098
  const wireToolName = "get_deployment";
91985
92099
  const wireArguments = {
91986
92100
  teamId: target.teamId,
91987
- id: params.deploymentId,
91988
92101
  idOrUrl: params.deploymentId
91989
92102
  };
91990
92103
  const canonicalToolArgumentsDigest = (0, import_node_crypto10.createHash)("sha256").update(JSON.stringify(canonicalizeValue(wireArguments))).digest("hex");
@@ -92626,6 +92739,26 @@ var HttpMcpClient = class {
92626
92739
  const result = await this.rpc("tools/list", {});
92627
92740
  return result?.tools ?? [];
92628
92741
  }
92742
+ /** Read every advertised tool page for security-sensitive contract checks. */
92743
+ async listAllTools() {
92744
+ const tools = [];
92745
+ const seen = /* @__PURE__ */ new Set();
92746
+ let cursor;
92747
+ for (let page = 0; page < 32; page++) {
92748
+ const result = await this.rpc("tools/list", cursor ? { cursor } : {});
92749
+ if (!result || !Array.isArray(result.tools)) {
92750
+ throw new Error("Invalid paginated tools/list response");
92751
+ }
92752
+ tools.push(...result.tools);
92753
+ if (result.nextCursor === void 0) return tools;
92754
+ if (typeof result.nextCursor !== "string" || !result.nextCursor || seen.has(result.nextCursor)) {
92755
+ throw new Error("Invalid or repeated tools/list cursor");
92756
+ }
92757
+ seen.add(result.nextCursor);
92758
+ cursor = result.nextCursor;
92759
+ }
92760
+ throw new Error("Too many tools/list pages");
92761
+ }
92629
92762
  async callTool(name, args) {
92630
92763
  const result = await this.rpc("tools/call", { name, arguments: args });
92631
92764
  return result;
@@ -93221,6 +93354,89 @@ function scopePublisherServer(server, toolName2) {
93221
93354
  headers
93222
93355
  };
93223
93356
  }
93357
+ async function preflightPublisherServer(server) {
93358
+ if (server.transport !== "http" || !server.url || !server.headers || server.authProvider) {
93359
+ throw new PublisherContractError("Publisher requires an HTTP endpoint and two role-specific bearer tokens");
93360
+ }
93361
+ const headers = server.headers;
93362
+ const releaseToken = headers.releaseToken ?? headers.release_token ?? headers.RELEASE_TOKEN;
93363
+ const observeToken = headers.observeToken ?? headers.observe_token ?? headers.OBSERVE_TOKEN;
93364
+ if (!releaseToken || !observeToken) {
93365
+ throw new PublisherContractError("Publisher requires both release and observe bearer tokens");
93366
+ }
93367
+ validatePublisherUrl(server.url, "Target endpoint");
93368
+ await preflightPublisherSchemas(server.url, { releaseToken, observeToken }, {
93369
+ allowLocalEndpoints: process.env.NODE_ENV === "test" || process.env.MRRLIN_ALLOW_LOCAL_ENDPOINTS === "1"
93370
+ });
93371
+ }
93372
+ async function preflightPublisherSchemas(endpoint, credentials, options) {
93373
+ if (credentials.releaseToken === credentials.observeToken) {
93374
+ throw new PublisherContractError("Identical token values rejected: release and observe credentials must be distinct");
93375
+ }
93376
+ const allowLocal = options?.allowLocalEndpoints ?? false;
93377
+ const releaseClient = new HttpMcpClient(
93378
+ endpoint,
93379
+ { Authorization: `Bearer ${credentials.releaseToken}` },
93380
+ allowLocal
93381
+ );
93382
+ try {
93383
+ await releaseClient.initialize();
93384
+ const tools = await releaseClient.listAllTools();
93385
+ const releaseTools = tools.filter((t) => t?.name === PUBLISHER_MCP_V1_TOOLS.release);
93386
+ if (releaseTools.length !== 1) {
93387
+ throw new PublisherContractError(
93388
+ `Release credential must expose exactly one required tool "${PUBLISHER_MCP_V1_TOOLS.release}"`
93389
+ );
93390
+ }
93391
+ if (tools.some((t) => t.name === PUBLISHER_MCP_V1_TOOLS.observe)) {
93392
+ throw new PublisherContractError(
93393
+ `Role isolation violation: Release credential must not expose observe tool "${PUBLISHER_MCP_V1_TOOLS.observe}"`
93394
+ );
93395
+ }
93396
+ const digest = computeToolSchemaDigest(releaseTools[0]?.inputSchema);
93397
+ if (digest !== PUBLISHER_RELEASE_V1_SCHEMA_DIGEST) {
93398
+ throw new PublisherContractError(
93399
+ `Schema drift detected for "${PUBLISHER_MCP_V1_TOOLS.release}": expected digest "${PUBLISHER_RELEASE_V1_SCHEMA_DIGEST}", got "${digest}"`
93400
+ );
93401
+ }
93402
+ } finally {
93403
+ await releaseClient.close().catch(() => {
93404
+ });
93405
+ }
93406
+ const observeClient = new HttpMcpClient(
93407
+ endpoint,
93408
+ { Authorization: `Bearer ${credentials.observeToken}` },
93409
+ allowLocal
93410
+ );
93411
+ try {
93412
+ await observeClient.initialize();
93413
+ const tools = await observeClient.listAllTools();
93414
+ const observeTools = tools.filter((t) => t?.name === PUBLISHER_MCP_V1_TOOLS.observe);
93415
+ if (observeTools.length !== 1) {
93416
+ throw new PublisherContractError(
93417
+ `Observe credential must expose exactly one required tool "${PUBLISHER_MCP_V1_TOOLS.observe}"`
93418
+ );
93419
+ }
93420
+ if (tools.some((t) => t.name === PUBLISHER_MCP_V1_TOOLS.release)) {
93421
+ throw new PublisherContractError(
93422
+ `Role isolation violation: Observe credential must not expose release tool "${PUBLISHER_MCP_V1_TOOLS.release}"`
93423
+ );
93424
+ }
93425
+ const digest = computeToolSchemaDigest(observeTools[0]?.inputSchema);
93426
+ if (digest !== PUBLISHER_OBSERVE_V1_SCHEMA_DIGEST) {
93427
+ throw new PublisherContractError(
93428
+ `Schema drift detected for "${PUBLISHER_MCP_V1_TOOLS.observe}": expected digest "${PUBLISHER_OBSERVE_V1_SCHEMA_DIGEST}", got "${digest}"`
93429
+ );
93430
+ }
93431
+ } finally {
93432
+ await observeClient.close().catch(() => {
93433
+ });
93434
+ }
93435
+ return {
93436
+ releaseDigest: PUBLISHER_RELEASE_V1_SCHEMA_DIGEST,
93437
+ observeDigest: PUBLISHER_OBSERVE_V1_SCHEMA_DIGEST
93438
+ };
93439
+ }
93224
93440
  var publisherMcpAdapter = new PublisherMcpAdapter();
93225
93441
  registerPublisherAdapter(publisherMcpAdapter);
93226
93442
 
@@ -93421,8 +93637,7 @@ function assertPublisherEndpoint(serverUrl, profileAuthority, envelope) {
93421
93637
  if (profileAuthority !== "custom") throw new Error("profile mismatch");
93422
93638
  const expected = new URL(envelope.target.endpoint);
93423
93639
  if (actual.href !== expected.href) throw new Error("endpoint drift");
93424
- const localFixture = (actual.hostname === "127.0.0.1" || actual.hostname === "localhost") && (process.env.NODE_ENV === "test" || process.env.MRRLIN_ALLOW_LOCAL_ENDPOINTS === "1");
93425
- if (!localFixture) throw new Error("custom target enrollment cannot be verified");
93640
+ validatePublisherUrl(actual.href, "Publisher endpoint");
93426
93641
  } else {
93427
93642
  if (profileAuthority === "custom") throw new Error("profile mismatch");
93428
93643
  const local = (actual.hostname === "127.0.0.1" || actual.hostname === "localhost") && (process.env.NODE_ENV === "test" || process.env.MRRLIN_ALLOW_LOCAL_ENDPOINTS === "1");
@@ -93440,6 +93655,21 @@ var PublishAttemptController = class _PublishAttemptController {
93440
93655
  this.context = context;
93441
93656
  }
93442
93657
  static inFlightDispatches = /* @__PURE__ */ new Set();
93658
+ /** The operation id this attempt is bound to — the same one sent to the publisher and stamped
93659
+ * into the published marker. Read by the produced_url evidence write (S6). */
93660
+ get boundOperationId() {
93661
+ return this.context.operationId;
93662
+ }
93663
+ /** The source digest of the approved prepared envelope this attempt dispatches. */
93664
+ get boundSourceDigest() {
93665
+ return this.context.preparedEnvelope.sourceDigest;
93666
+ }
93667
+ /** Version of the digest scheme behind `boundSourceDigest`. Both V1 envelope schemas carry the
93668
+ * v1 manifest digest and no version field; an envelope that names its own version wins. */
93669
+ get boundSourceDigestVersion() {
93670
+ const declared = this.context.preparedEnvelope.sourceDigestVersion;
93671
+ return typeof declared === "string" && declared.length > 0 ? declared : "v1";
93672
+ }
93443
93673
  /**
93444
93674
  * Prepares the attempt row in the database (or retrieves existing row).
93445
93675
  */
@@ -93612,6 +93842,9 @@ var PublishAttemptController = class _PublishAttemptController {
93612
93842
  );
93613
93843
  }
93614
93844
  await this.verifyAuthority(server, approvedEnvelope, payload.operation, payload.profileId);
93845
+ if ("profileId" in approvedEnvelope && approvedEnvelope.profileId === "publisher.mcp.v1") {
93846
+ await preflightPublisherServer(server);
93847
+ }
93615
93848
  if (current2.dispatchCount && current2.dispatchCount > 0) {
93616
93849
  throw new PublishLeaseFencingError(
93617
93850
  `Single-use dispatch commitment already consumed for attempt ${attemptId} (dispatchCount=${current2.dispatchCount}). Re-dispatch is prohibited; status must be reconciled.`
@@ -93623,7 +93856,8 @@ var PublishAttemptController = class _PublishAttemptController {
93623
93856
  );
93624
93857
  }
93625
93858
  const comm = await this.client.commitPublishDispatch(this.context.projectSlug, attemptId, {
93626
- leaseOwner: this.context.leaseOwner
93859
+ leaseOwner: this.context.leaseOwner,
93860
+ operationId: this.context.operationId
93627
93861
  });
93628
93862
  if (!comm) {
93629
93863
  throw new PublishLeaseFencingError(
@@ -93892,6 +94126,12 @@ var PublishAttemptController = class _PublishAttemptController {
93892
94126
  `AUTHORITY_DRIFT: Live authorization generation (${liveBinding.authorizationGeneration}) does not match approved envelope authorization generation (${approvedEnvelope.authorizationGeneration})`
93893
94127
  );
93894
94128
  }
94129
+ if ("target" in approvedEnvelope && (!liveBinding.publisherTarget || computeTargetFingerprint(liveBinding.publisherTarget) !== computeTargetFingerprint(approvedEnvelope.target))) {
94130
+ throw new PublishLeaseFencingError("AUTHORITY_DRIFT: Publisher target differs from owner enrollment");
94131
+ }
94132
+ if ("target" in approvedEnvelope && server.authorizationGeneration !== liveBinding.authorizationGeneration) {
94133
+ throw new PublishLeaseFencingError("AUTHORITY_DRIFT: Local publisher authorization generation changed");
94134
+ }
93895
94135
  if (server.connectionId && liveBinding.connectionId !== server.connectionId) {
93896
94136
  throw new PublishLeaseFencingError(
93897
94137
  `AUTHORITY_DRIFT: Live binding connectionId (${liveBinding.connectionId}) does not match server connectionId (${server.connectionId})`
@@ -94180,10 +94420,12 @@ async function resolveDeliveryServer(serverId, opts) {
94180
94420
  return null;
94181
94421
  }
94182
94422
  if (resolved.kind === "managed") {
94423
+ let managedConnection = resolved.connection;
94183
94424
  let secrets = {};
94184
94425
  if (resolved.connection.inputRefs && Object.keys(resolved.connection.inputRefs).length > 0 && store.isVaultUnlocked()) {
94185
94426
  try {
94186
94427
  const secretObj = await store.resolveConnection(resolved.connection.id);
94428
+ managedConnection = secretObj.connection;
94187
94429
  secrets = secretObj.secrets;
94188
94430
  } catch {
94189
94431
  }
@@ -94191,11 +94433,11 @@ async function resolveDeliveryServer(serverId, opts) {
94191
94433
  let authProvider;
94192
94434
  if (store.isVaultUnlocked()) {
94193
94435
  try {
94194
- const authGen = resolved.connection.authorizationGeneration ?? 1;
94195
- const mapping = await store.getOAuthResourceMapping(resolved.connection.id, authGen);
94196
- if (mapping?.resource && resolved.connection.endpoint) {
94436
+ const authGen = managedConnection.authorizationGeneration ?? 1;
94437
+ const mapping = await store.getOAuthResourceMapping(managedConnection.id, authGen);
94438
+ if (mapping?.resource && managedConnection.endpoint) {
94197
94439
  try {
94198
- const endpointOrigin = new URL(resolved.connection.endpoint).origin;
94440
+ const endpointOrigin = new URL(managedConnection.endpoint).origin;
94199
94441
  const resourceOrigin = new URL(mapping.resource).origin;
94200
94442
  if (endpointOrigin !== resourceOrigin) {
94201
94443
  throw new AuthorizationGenerationMismatchError(
@@ -94207,15 +94449,15 @@ async function resolveDeliveryServer(serverId, opts) {
94207
94449
  }
94208
94450
  }
94209
94451
  const tokens2 = await store.getOAuthTokens({
94210
- connectionId: resolved.connection.id,
94452
+ connectionId: managedConnection.id,
94211
94453
  authorizationGeneration: authGen,
94212
94454
  issuer: mapping?.issuer,
94213
94455
  resource: mapping?.resource
94214
94456
  });
94215
94457
  let isServerHostLocal = false;
94216
- if (resolved.connection.endpoint) {
94458
+ if (managedConnection.endpoint) {
94217
94459
  try {
94218
- const parsedEndpoint = new URL(resolved.connection.endpoint);
94460
+ const parsedEndpoint = new URL(managedConnection.endpoint);
94219
94461
  isServerHostLocal = parsedEndpoint.hostname === "localhost" || parsedEndpoint.hostname === "127.0.0.1" || parsedEndpoint.hostname === "::1" || parsedEndpoint.hostname === "[::1]";
94220
94462
  } catch {
94221
94463
  }
@@ -94224,7 +94466,7 @@ async function resolveDeliveryServer(serverId, opts) {
94224
94466
  if (tokens2) {
94225
94467
  authProvider = new MrrlinOAuthClientProvider({
94226
94468
  store,
94227
- connectionId: resolved.connection.id,
94469
+ connectionId: managedConnection.id,
94228
94470
  authorizationGeneration: authGen,
94229
94471
  redirectUrl: "http://127.0.0.1/integrations/oauth/callback",
94230
94472
  expectedIssuer: mapping?.issuer,
@@ -94236,35 +94478,35 @@ async function resolveDeliveryServer(serverId, opts) {
94236
94478
  if (err instanceof AuthorizationGenerationMismatchError) throw err;
94237
94479
  }
94238
94480
  }
94239
- const configDigest = resolved.connection.configDigest ?? computeConnectionConfigDigest({
94240
- transport: resolved.connection.transport,
94241
- endpoint: resolved.connection.endpoint,
94242
- command: resolved.connection.command,
94243
- args: resolved.connection.args,
94244
- envKeys: resolved.connection.envKeys,
94245
- inputRefKeys: Object.keys(resolved.connection.inputRefs ?? {})
94481
+ const configDigest = managedConnection.configDigest ?? computeConnectionConfigDigest({
94482
+ transport: managedConnection.transport,
94483
+ endpoint: managedConnection.endpoint,
94484
+ command: managedConnection.command,
94485
+ args: managedConnection.args,
94486
+ envKeys: managedConnection.envKeys,
94487
+ inputRefKeys: Object.keys(managedConnection.inputRefs ?? {})
94246
94488
  });
94247
- if (resolved.connection.transport === "streamable_http") {
94489
+ if (managedConnection.transport === "streamable_http") {
94248
94490
  return {
94249
- id: resolved.connection.legacyServerId ?? resolved.connection.id,
94491
+ id: managedConnection.legacyServerId ?? managedConnection.id,
94250
94492
  transport: "http",
94251
- url: resolved.connection.endpoint ?? "",
94493
+ url: managedConnection.endpoint ?? "",
94252
94494
  headers: secrets,
94253
94495
  authProvider,
94254
- connectionId: resolved.connection.id,
94255
- authorizationGeneration: resolved.connection.authorizationGeneration,
94496
+ connectionId: managedConnection.id,
94497
+ authorizationGeneration: managedConnection.authorizationGeneration,
94256
94498
  configDigest
94257
94499
  };
94258
94500
  }
94259
94501
  return {
94260
- id: resolved.connection.legacyServerId ?? resolved.connection.id,
94502
+ id: managedConnection.legacyServerId ?? managedConnection.id,
94261
94503
  transport: "stdio",
94262
- command: resolved.connection.command ?? "",
94263
- args: resolved.connection.args ?? [],
94504
+ command: managedConnection.command ?? "",
94505
+ args: managedConnection.args ?? [],
94264
94506
  env: secrets,
94265
94507
  authProvider,
94266
- connectionId: resolved.connection.id,
94267
- authorizationGeneration: resolved.connection.authorizationGeneration,
94508
+ connectionId: managedConnection.id,
94509
+ authorizationGeneration: managedConnection.authorizationGeneration,
94268
94510
  configDigest
94269
94511
  };
94270
94512
  }
@@ -94877,10 +95119,15 @@ async function callDestination(client, projectSlug, route, resolvedToolName, pay
94877
95119
  }
94878
95120
  }
94879
95121
  }
94880
- return deliverToPublish(server, resolvedToolName, publishPayload, {
95122
+ const delivered = await deliverToPublish(server, resolvedToolName, publishPayload, {
94881
95123
  controller,
94882
95124
  attemptId: attId
94883
95125
  });
95126
+ await recordManagedPublishEvidence(client, projectSlug, runId, controller, attId, delivered, {
95127
+ operation: typeof operation === "string" ? operation : "",
95128
+ environment: publishPayload.environment
95129
+ });
95130
+ return delivered;
94884
95131
  }
94885
95132
  return deliverToPublish(server, resolvedToolName, publishPayload, {
94886
95133
  controller: attemptController,
@@ -95113,6 +95360,38 @@ async function readPullRequestState(client, projectSlug, taskProjectSlug, pullRe
95113
95360
  throw err;
95114
95361
  }
95115
95362
  }
95363
+ async function recordManagedPublishEvidence(client, projectSlug, runId, controller, attemptId, delivered, publish) {
95364
+ if (!runId || !controller) return;
95365
+ if (!isReleasePublish(publish)) return;
95366
+ const url2 = delivered.normalized?.url ?? null;
95367
+ if (delivered.normalized?.status !== "success" || !url2 || url2 !== delivered.url) return;
95368
+ const operationId = controller.boundOperationId;
95369
+ const sourceDigest = controller.boundSourceDigest;
95370
+ if (!operationId || !sourceDigest) return;
95371
+ const id = `EA-pu-m-${import_node_crypto12.default.createHash("sha256").update(`${runId}
95372
+ ${operationId}
95373
+ ${url2}`).digest("hex").slice(0, 16)}`;
95374
+ try {
95375
+ await client.appendExecutionArtifact(projectSlug, runId, {
95376
+ id,
95377
+ kind: "produced_url",
95378
+ payload: {
95379
+ url: url2,
95380
+ label: "managed_publish",
95381
+ operationId,
95382
+ sourceDigest,
95383
+ sourceDigestVersion: controller.boundSourceDigestVersion,
95384
+ ...attemptId ? { publishAttemptId: attemptId } : {}
95385
+ }
95386
+ });
95387
+ } catch (error51) {
95388
+ console.error(`[mrrlin] produced_url evidence write failed for run ${runId}: ${errorMessage(error51) ?? String(error51)}`);
95389
+ }
95390
+ }
95391
+ function isReleasePublish(publish) {
95392
+ if (publish.environment !== "production") return false;
95393
+ return publish.operation === "release" || publish.operation === "publish_release" || publish.operation === "observe" || publish.operation === "publish_observe";
95394
+ }
95116
95395
  function digestCapabilityPayload(payload) {
95117
95396
  if (payload && typeof payload === "object" && "envelope" in payload) {
95118
95397
  const { envelope: _env, ...rest } = payload;
@@ -96433,7 +96712,7 @@ function buildDraftSpecPrompt(task, constitution, deployTarget = null) {
96433
96712
  `id: ${task.id}`,
96434
96713
  `title: ${task.title}`,
96435
96714
  `type: ${task.type ?? "task"}`,
96436
- `domains: ${(task.domains ?? ["code"]).join(", ")}`,
96715
+ `domains: ${task.domains?.length ? task.domains.join(", ") : "none (not a code task)"}`,
96437
96716
  `impact: ${task.impact ?? ""}`,
96438
96717
  `category: ${task.category ?? ""} / ${task.subcategory ?? ""}`,
96439
96718
  `tags: ${(task.tags ?? []).join(", ")}`,
@@ -99604,6 +99883,56 @@ function unfinishedRunWorktrees(runs) {
99604
99883
  }
99605
99884
  return keep;
99606
99885
  }
99886
+ function gitCommonDir(checkout) {
99887
+ const dotGit = (0, import_node_path24.join)(checkout, ".git");
99888
+ try {
99889
+ if ((0, import_node_fs18.lstatSync)(dotGit).isDirectory()) return dotGit;
99890
+ const match2 = /^gitdir: (.+)$/m.exec((0, import_node_fs18.readFileSync)(dotGit, "utf8"));
99891
+ if (!match2?.[1]) return null;
99892
+ const gitdir = (0, import_node_path24.resolve)(checkout, match2[1].trim());
99893
+ try {
99894
+ return (0, import_node_path24.resolve)(gitdir, (0, import_node_fs18.readFileSync)((0, import_node_path24.join)(gitdir, "commondir"), "utf8").trim());
99895
+ } catch {
99896
+ return gitdir;
99897
+ }
99898
+ } catch {
99899
+ return null;
99900
+ }
99901
+ }
99902
+ function pruneOwnedStaleRegistrations(checkout, ownedPrefixes) {
99903
+ const commonDir = gitCommonDir(checkout);
99904
+ if (!commonDir) return [];
99905
+ const admin = (0, import_node_path24.join)(commonDir, "worktrees");
99906
+ let ids;
99907
+ try {
99908
+ ids = (0, import_node_fs18.readdirSync)(admin);
99909
+ } catch {
99910
+ return [];
99911
+ }
99912
+ const fold = (path42) => process.platform === "win32" ? (0, import_node_path24.normalize)(path42).toLowerCase() : (0, import_node_path24.normalize)(path42);
99913
+ const prefixes = ownedPrefixes.map(fold);
99914
+ const pruned = [];
99915
+ for (const id of ids) {
99916
+ const entry = (0, import_node_path24.join)(admin, id);
99917
+ if ((0, import_node_fs18.existsSync)((0, import_node_path24.join)(entry, "locked"))) continue;
99918
+ let target;
99919
+ try {
99920
+ target = (0, import_node_fs18.readFileSync)((0, import_node_path24.join)(entry, "gitdir"), "utf8").trim();
99921
+ } catch {
99922
+ continue;
99923
+ }
99924
+ if (!(0, import_node_path24.isAbsolute)(target) || (0, import_node_path24.basename)(target) !== ".git" || /[\x00-\x1f\x7f]/.test(target)) continue;
99925
+ const worktree = (0, import_node_path24.dirname)(target);
99926
+ if (!prefixes.some((prefix) => fold(worktree).startsWith(prefix))) continue;
99927
+ if ((0, import_node_fs18.existsSync)(target) || (0, import_node_fs18.existsSync)(worktree)) continue;
99928
+ try {
99929
+ (0, import_node_fs18.rmSync)(entry, { recursive: true, force: true });
99930
+ pruned.push(worktree);
99931
+ } catch {
99932
+ }
99933
+ }
99934
+ return pruned;
99935
+ }
99607
99936
  async function sweepOrphanWorktrees(opts, runGit2 = git2) {
99608
99937
  const reaped = [];
99609
99938
  const hooksDir = prepareDisabledGitHooksDir(opts.locksDir, `sweep:${opts.slug}`);
@@ -99661,6 +99990,8 @@ async function sweepOrphanWorktrees(opts, runGit2 = git2) {
99661
99990
  }
99662
99991
  }
99663
99992
  }
99993
+ const rawPrefix = (0, import_node_path24.normalize)(opts.worktreeRoot) + import_node_path24.sep + opts.slug + import_node_path24.sep;
99994
+ reaped.push(...pruneOwnedStaleRegistrations(opts.checkout, [ownedPrefix, rawPrefix]));
99664
99995
  });
99665
99996
  });
99666
99997
  } finally {
@@ -102458,6 +102789,12 @@ function createMrrlinTools(options) {
102458
102789
  "A local_apply landing record is written only by the bridge when it lands a run. Read the landing with get_execution_run (localLanding) instead."
102459
102790
  );
102460
102791
  }
102792
+ if (input.kind === "produced_url") {
102793
+ throw new McpToolCodedError(
102794
+ "PRODUCED_URL_RESERVED",
102795
+ "A produced_url artifact is written only by record_produced_url. Call record_produced_url with the page's URL instead."
102796
+ );
102797
+ }
102461
102798
  return await c.appendExecutionArtifact(projectSlug, runId, input);
102462
102799
  }
102463
102800
  ),
@@ -106502,7 +106839,7 @@ Do NOT derail the current task - if the operator has an in-flight question, answ
106502
106839
  }
106503
106840
 
106504
106841
  // src/_generated/version.ts
106505
- var PKG_VERSION = "0.4.236";
106842
+ var PKG_VERSION = "0.4.247";
106506
106843
 
106507
106844
  // src/bridge-allowed-origins.ts
106508
106845
  var DEFAULT_DIRECTOR_BRIDGE_ALLOWED_ORIGINS = [
@@ -110686,7 +111023,627 @@ init_dist2();
110686
111023
  init_dist();
110687
111024
 
110688
111025
  // src/delivery/public-url-verifier.ts
111026
+ var DEFAULT_VERIFIER_TIMEOUT_MS = 1e4;
111027
+ var DEFAULT_VERIFIER_MAX_REDIRECTS = 3;
110689
111028
  var DEFAULT_VERIFIER_MAX_BYTES = 2 * 1024 * 1024;
111029
+ function isProtectedStatus(status) {
111030
+ return status === 401 || status === 403;
111031
+ }
111032
+ function isDnsOrUnreachableError(err) {
111033
+ if (!err) return false;
111034
+ if (err?.name === "TimeoutError") return true;
111035
+ const msg = err instanceof Error ? err.message : String(err);
111036
+ const lower = msg.toLowerCase();
111037
+ return lower.includes("failed to resolve hostname") || lower.includes("enotfound") || lower.includes("eai_again") || lower.includes("econnrefused") || lower.includes("econnreset") || lower.includes("etimedout") || lower.includes("timed out") || lower.includes("getaddrinfo") || lower.includes("dns") || lower.includes("unresolvable") || err instanceof NetworkPolicyViolationError && lower.includes("resolve");
111038
+ }
111039
+ var LOGIN_PATH_SEGMENTS = /* @__PURE__ */ new Set([
111040
+ "login",
111041
+ "log-in",
111042
+ "signin",
111043
+ "sign-in",
111044
+ "auth",
111045
+ "sso",
111046
+ "oauth",
111047
+ "authorize"
111048
+ ]);
111049
+ function looksLikeLoginPage(input) {
111050
+ const { requestedUrl, finalUrl, body } = input;
111051
+ if (finalUrl) {
111052
+ try {
111053
+ const requested = new URL(requestedUrl);
111054
+ const final = new URL(finalUrl);
111055
+ const redirected = requested.origin !== final.origin || requested.pathname !== final.pathname;
111056
+ if (redirected) {
111057
+ const path42 = final.pathname.toLowerCase();
111058
+ if (path42.split("/").filter(Boolean).some((segment) => LOGIN_PATH_SEGMENTS.has(segment))) return true;
111059
+ if (path42.includes("protection_bypass") || final.searchParams.has("protection_bypass")) return true;
111060
+ }
111061
+ } catch {
111062
+ }
111063
+ }
111064
+ if (body) {
111065
+ const asksForPassword = /<input\b[^>]*\btype\s*=\s*["']?password\b/i.test(body);
111066
+ const title = /<title[^>]*>([\s\S]*?)<\/title>/i.exec(body)?.[1] ?? "";
111067
+ const signInTitle = /\b(log[\s-]?in|sign[\s-]?in|authenticate|authentication required)\b/i.test(title);
111068
+ if (asksForPassword && signInTitle) return true;
111069
+ }
111070
+ return false;
111071
+ }
111072
+ function finalResponseUrl(response) {
111073
+ return typeof response.url === "string" ? response.url : "";
111074
+ }
111075
+ async function readBodyPrefix(response, maxBytes = 64 * 1024) {
111076
+ const reader = response.body?.getReader();
111077
+ if (!reader) return "";
111078
+ const chunks = [];
111079
+ let total = 0;
111080
+ try {
111081
+ while (total < maxBytes) {
111082
+ const { done, value } = await reader.read();
111083
+ if (done || !value) break;
111084
+ chunks.push(Buffer.from(value));
111085
+ total += value.byteLength;
111086
+ }
111087
+ } catch {
111088
+ } finally {
111089
+ await reader.cancel().catch(() => {
111090
+ });
111091
+ }
111092
+ return Buffer.concat(chunks).subarray(0, maxBytes).toString("utf8");
111093
+ }
111094
+ function isTransientVerificationFailure(result) {
111095
+ if (result.transient === true) return true;
111096
+ if (result.outcome === "dns_pending") return true;
111097
+ return typeof result.httpStatus === "number" && result.httpStatus >= 500 && (result.outcome === "marker_missing" || result.outcome === "landing_page_error" || result.outcome === "verification_failed");
111098
+ }
111099
+ function readMarkerDigestVersion(rawContent) {
111100
+ try {
111101
+ const parsed = JSON.parse(rawContent);
111102
+ if (parsed === null || typeof parsed !== "object") return null;
111103
+ const version2 = parsed.sourceDigestVersion;
111104
+ if (version2 === void 0) return "v1";
111105
+ return typeof version2 === "string" && version2.length > 0 ? version2 : null;
111106
+ } catch {
111107
+ return null;
111108
+ }
111109
+ }
111110
+ function cleanBaseUrl(rawUrl) {
111111
+ const trimmed = rawUrl.trim();
111112
+ const withProtocol = trimmed.startsWith("http://") || trimmed.startsWith("https://") ? trimmed : `https://${trimmed}`;
111113
+ return withProtocol.replace(/\/+$/, "");
111114
+ }
111115
+ async function verifyPublicUrl(options) {
111116
+ const {
111117
+ publicUrl,
111118
+ expectedOperationId,
111119
+ expectedSourceDigest,
111120
+ expectedSourceDigestVersion,
111121
+ markerPath = PUBLISH_SOURCE_LIMITS.RESERVED_MARKER_PATH,
111122
+ customDomain,
111123
+ allowLocalEndpoints = process.env.NODE_ENV === "test" && process.env.MRRLIN_ALLOW_LOCAL_ENDPOINTS === "1",
111124
+ timeoutMs = DEFAULT_VERIFIER_TIMEOUT_MS,
111125
+ maxRedirects = DEFAULT_VERIFIER_MAX_REDIRECTS,
111126
+ maxResponseBytes = DEFAULT_VERIFIER_MAX_BYTES,
111127
+ fetchFn = safeFetch
111128
+ } = options;
111129
+ if (!publicUrl || typeof publicUrl !== "string") {
111130
+ return {
111131
+ verified: false,
111132
+ publicUrl: String(publicUrl),
111133
+ outcome: "verification_failed",
111134
+ reason: "Candidate public URL must be a non-empty string"
111135
+ };
111136
+ }
111137
+ const normalizedPublicBase = cleanBaseUrl(publicUrl);
111138
+ const cleanMarkerPath = markerPath.replace(/^\/+/, "");
111139
+ const markerUrl = `${normalizedPublicBase}/${cleanMarkerPath}`;
111140
+ const landingUrl = `${normalizedPublicBase}/`;
111141
+ const policy = {
111142
+ allowLocalEndpoints,
111143
+ timeoutMs,
111144
+ maxRedirects,
111145
+ maxResponseBytes
111146
+ };
111147
+ let markerResponse;
111148
+ try {
111149
+ markerResponse = await fetchFn(
111150
+ markerUrl,
111151
+ {
111152
+ method: "GET",
111153
+ headers: {
111154
+ accept: "application/json, text/plain",
111155
+ "user-agent": "Mrrlin-Public-Verifier/1.0"
111156
+ }
111157
+ },
111158
+ policy
111159
+ );
111160
+ } catch (err) {
111161
+ if (err instanceof NetworkPolicyViolationError) {
111162
+ return {
111163
+ verified: false,
111164
+ publicUrl: normalizedPublicBase,
111165
+ outcome: "network_policy_violation",
111166
+ reason: `Network policy rejected verification request: ${err.message}`,
111167
+ ...isDnsOrUnreachableError(err) ? { transient: true } : {}
111168
+ };
111169
+ }
111170
+ return {
111171
+ verified: false,
111172
+ publicUrl: normalizedPublicBase,
111173
+ outcome: "verification_failed",
111174
+ reason: `Failed to reach verification marker endpoint: ${err instanceof Error ? err.message : String(err)}`,
111175
+ ...isDnsOrUnreachableError(err) ? { transient: true } : {}
111176
+ };
111177
+ }
111178
+ if (isProtectedStatus(markerResponse.status)) {
111179
+ return {
111180
+ verified: false,
111181
+ publicUrl: normalizedPublicBase,
111182
+ outcome: "protected_preview",
111183
+ reason: `Verification marker is protected by an authentication wall (HTTP ${markerResponse.status})`,
111184
+ httpStatus: markerResponse.status
111185
+ };
111186
+ }
111187
+ if (markerResponse.status !== 200) {
111188
+ return {
111189
+ verified: false,
111190
+ publicUrl: normalizedPublicBase,
111191
+ outcome: "marker_missing",
111192
+ reason: `Verification marker request returned non-200 status (HTTP ${markerResponse.status})`,
111193
+ httpStatus: markerResponse.status
111194
+ };
111195
+ }
111196
+ let markerBody;
111197
+ try {
111198
+ markerBody = await readBoundedResponseBody(markerResponse, maxResponseBytes);
111199
+ } catch (err) {
111200
+ return {
111201
+ verified: false,
111202
+ publicUrl: normalizedPublicBase,
111203
+ outcome: "verification_failed",
111204
+ reason: `Failed to read marker response body within bounds: ${err instanceof Error ? err.message : String(err)}`
111205
+ };
111206
+ }
111207
+ if (expectedSourceDigestVersion !== void 0) {
111208
+ const markerVersion = readMarkerDigestVersion(markerBody);
111209
+ if (markerVersion !== expectedSourceDigestVersion) {
111210
+ return {
111211
+ verified: false,
111212
+ publicUrl: normalizedPublicBase,
111213
+ outcome: "digest_version_mismatch",
111214
+ reason: `Verification marker uses source digest version "${markerVersion ?? "unreadable"}", expected "${expectedSourceDigestVersion}"`,
111215
+ httpStatus: markerResponse.status
111216
+ };
111217
+ }
111218
+ }
111219
+ const markerValid = verifyPublishMarker(markerBody, {
111220
+ operationId: expectedOperationId,
111221
+ sourceDigest: expectedSourceDigest
111222
+ });
111223
+ if (!markerValid) {
111224
+ return {
111225
+ verified: false,
111226
+ publicUrl: normalizedPublicBase,
111227
+ outcome: "marker_mismatch",
111228
+ reason: "Verification marker content does not match expected operationId and sourceDigest (PUB-009)",
111229
+ httpStatus: markerResponse.status
111230
+ };
111231
+ }
111232
+ let landingResponse;
111233
+ try {
111234
+ landingResponse = await fetchFn(
111235
+ landingUrl,
111236
+ {
111237
+ method: "GET",
111238
+ headers: {
111239
+ accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
111240
+ "user-agent": "Mrrlin-Public-Verifier/1.0"
111241
+ }
111242
+ },
111243
+ policy
111244
+ );
111245
+ } catch (err) {
111246
+ if (err instanceof NetworkPolicyViolationError) {
111247
+ return {
111248
+ verified: false,
111249
+ publicUrl: normalizedPublicBase,
111250
+ outcome: "network_policy_violation",
111251
+ reason: `Network policy rejected landing page request: ${err.message}`,
111252
+ ...isDnsOrUnreachableError(err) ? { transient: true } : {}
111253
+ };
111254
+ }
111255
+ return {
111256
+ verified: false,
111257
+ publicUrl: normalizedPublicBase,
111258
+ outcome: "verification_failed",
111259
+ reason: `Failed to reach landing page: ${err instanceof Error ? err.message : String(err)}`,
111260
+ ...isDnsOrUnreachableError(err) ? { transient: true } : {}
111261
+ };
111262
+ }
111263
+ if (isProtectedStatus(landingResponse.status)) {
111264
+ await landingResponse.body?.cancel().catch(() => {
111265
+ });
111266
+ return {
111267
+ verified: false,
111268
+ publicUrl: normalizedPublicBase,
111269
+ outcome: "protected_preview",
111270
+ reason: `Landing page is protected by authentication or preview gate (HTTP ${landingResponse.status})`,
111271
+ httpStatus: landingResponse.status
111272
+ };
111273
+ }
111274
+ if (landingResponse.status >= 400) {
111275
+ await landingResponse.body?.cancel().catch(() => {
111276
+ });
111277
+ return {
111278
+ verified: false,
111279
+ publicUrl: normalizedPublicBase,
111280
+ outcome: "landing_page_error",
111281
+ reason: `Landing page returned HTTP ${landingResponse.status}`,
111282
+ httpStatus: landingResponse.status
111283
+ };
111284
+ }
111285
+ const landingBody = await readBodyPrefix(landingResponse);
111286
+ if (looksLikeLoginPage({ requestedUrl: landingUrl, finalUrl: finalResponseUrl(landingResponse), body: landingBody })) {
111287
+ return {
111288
+ verified: false,
111289
+ publicUrl: normalizedPublicBase,
111290
+ outcome: "protected_preview",
111291
+ reason: `Landing page ends on a sign-in page${finalResponseUrl(landingResponse) ? ` (${finalResponseUrl(landingResponse)})` : ""}, so it is not public`,
111292
+ httpStatus: landingResponse.status
111293
+ };
111294
+ }
111295
+ let customDomainVerified = false;
111296
+ if (customDomain && customDomain.trim().length > 0) {
111297
+ const normalizedDomain = customDomain.trim().toLowerCase().replace(/^https?:\/\//, "").replace(/\/+$/, "");
111298
+ const customDomainMarkerUrl = `https://${normalizedDomain}/${cleanMarkerPath}`;
111299
+ let domainResponse;
111300
+ try {
111301
+ domainResponse = await fetchFn(
111302
+ customDomainMarkerUrl,
111303
+ {
111304
+ method: "GET",
111305
+ headers: {
111306
+ accept: "application/json, text/plain",
111307
+ "user-agent": "Mrrlin-Public-Verifier/1.0"
111308
+ }
111309
+ },
111310
+ policy
111311
+ );
111312
+ } catch (err) {
111313
+ const msg = err instanceof Error ? err.message : String(err);
111314
+ if (isDnsOrUnreachableError(err)) {
111315
+ return {
111316
+ verified: false,
111317
+ publicUrl: normalizedPublicBase,
111318
+ outcome: "dns_pending",
111319
+ reason: `Custom domain "${normalizedDomain}" DNS is propagating or unresolvable (PUB-010): ${msg}`
111320
+ };
111321
+ }
111322
+ return {
111323
+ verified: false,
111324
+ publicUrl: normalizedPublicBase,
111325
+ outcome: "verification_failed",
111326
+ reason: `Custom domain verification failed: ${msg}`
111327
+ };
111328
+ }
111329
+ if (isProtectedStatus(domainResponse.status)) {
111330
+ return {
111331
+ verified: false,
111332
+ publicUrl: normalizedPublicBase,
111333
+ outcome: "protected_preview",
111334
+ reason: `Custom domain "${normalizedDomain}" is protected by authentication (HTTP ${domainResponse.status})`,
111335
+ httpStatus: domainResponse.status
111336
+ };
111337
+ }
111338
+ if (domainResponse.status !== 200) {
111339
+ return {
111340
+ verified: false,
111341
+ publicUrl: normalizedPublicBase,
111342
+ outcome: "verification_failed",
111343
+ reason: `Custom domain "${normalizedDomain}" returned non-200 status (HTTP ${domainResponse.status})`,
111344
+ httpStatus: domainResponse.status
111345
+ };
111346
+ }
111347
+ let domainMarkerBody;
111348
+ try {
111349
+ domainMarkerBody = await readBoundedResponseBody(domainResponse, maxResponseBytes);
111350
+ } catch (err) {
111351
+ return {
111352
+ verified: false,
111353
+ publicUrl: normalizedPublicBase,
111354
+ outcome: "verification_failed",
111355
+ reason: `Failed to read custom domain marker body: ${err instanceof Error ? err.message : String(err)}`
111356
+ };
111357
+ }
111358
+ const domainMarkerValid = verifyPublishMarker(domainMarkerBody, {
111359
+ operationId: expectedOperationId,
111360
+ sourceDigest: expectedSourceDigest
111361
+ });
111362
+ if (!domainMarkerValid) {
111363
+ return {
111364
+ verified: false,
111365
+ publicUrl: normalizedPublicBase,
111366
+ outcome: "verification_failed",
111367
+ reason: `Custom domain "${normalizedDomain}" points to older or mismatched content (PUB-010)`
111368
+ };
111369
+ }
111370
+ customDomainVerified = true;
111371
+ }
111372
+ return {
111373
+ verified: true,
111374
+ publicUrl: normalizedPublicBase,
111375
+ customDomainVerified: customDomain ? customDomainVerified : void 0,
111376
+ marker: {
111377
+ operationId: expectedOperationId,
111378
+ sourceDigest: expectedSourceDigest
111379
+ },
111380
+ verifiedAt: (/* @__PURE__ */ new Date()).toISOString(),
111381
+ landingPageStatusCode: landingResponse.status
111382
+ };
111383
+ }
111384
+
111385
+ // src/delivery/page-publication-evidence.ts
111386
+ var MANAGED_PUBLISHER_SERVER_ID = "publisher.mcp.v1";
111387
+ var SUPPORTED_SOURCE_DIGEST_VERSIONS = /* @__PURE__ */ new Set(["v1"]);
111388
+ var DEFAULT_LIVENESS_TIMEOUT_MS = 1e4;
111389
+ var DEFAULT_PUBLICATION_RETRY = { attempts: 3, delaysMs: [2e3, 6e3] };
111390
+ var DEFAULT_PUBLICATION_DEADLINE_MS = 3e4;
111391
+ function nonEmptyString(value) {
111392
+ return typeof value === "string" && value.length > 0 ? value : null;
111393
+ }
111394
+ function defaultAllowLocal() {
111395
+ return process.env.NODE_ENV === "test" && process.env.MRRLIN_ALLOW_LOCAL_ENDPOINTS === "1";
111396
+ }
111397
+ var realSleep = (ms) => new Promise((resolve4) => setTimeout(resolve4, ms));
111398
+ async function withTransientRetry(check2, retry, remainingMs) {
111399
+ const attempts = Math.max(1, Math.min(retry?.attempts ?? DEFAULT_PUBLICATION_RETRY.attempts, 5));
111400
+ const delays = retry?.delaysMs ?? DEFAULT_PUBLICATION_RETRY.delaysMs;
111401
+ const sleep = retry?.sleep ?? realSleep;
111402
+ let result = await check2();
111403
+ let tried = 1;
111404
+ for (let attempt = 2; attempt <= attempts && !result.ok && result.transient; attempt += 1) {
111405
+ const delay6 = delays[Math.min(attempt - 2, delays.length - 1)] ?? 0;
111406
+ if (delay6 >= remainingMs()) break;
111407
+ await sleep(delay6);
111408
+ result = await check2();
111409
+ tried += 1;
111410
+ }
111411
+ if (!result.ok && result.transient && tried > 1) {
111412
+ return { ...result, reason: `${result.reason} (still failing after ${tried} attempts)` };
111413
+ }
111414
+ return result;
111415
+ }
111416
+ async function withinDeadline(work, remainingMs, onTimeout) {
111417
+ if (remainingMs <= 0) return onTimeout();
111418
+ let timer;
111419
+ const timeout = new Promise((resolve4) => {
111420
+ timer = setTimeout(() => resolve4(onTimeout()), remainingMs);
111421
+ });
111422
+ try {
111423
+ return await Promise.race([work, timeout]);
111424
+ } finally {
111425
+ clearTimeout(timer);
111426
+ }
111427
+ }
111428
+ async function verifyUrlLive(url2, options = {}) {
111429
+ const fetchFn = options.fetchFn ?? safeFetch;
111430
+ let response;
111431
+ try {
111432
+ response = await fetchFn(
111433
+ url2,
111434
+ { method: "GET", headers: { accept: "text/html,*/*;q=0.8", "user-agent": "Mrrlin-Public-Verifier/1.0" } },
111435
+ {
111436
+ allowLocalEndpoints: options.allowLocalEndpoints ?? defaultAllowLocal(),
111437
+ timeoutMs: options.timeoutMs ?? DEFAULT_LIVENESS_TIMEOUT_MS,
111438
+ maxRedirects: 3
111439
+ }
111440
+ );
111441
+ } catch (error51) {
111442
+ const transient = isDnsOrUnreachableError(error51);
111443
+ if (error51 instanceof NetworkPolicyViolationError) {
111444
+ return { live: false, reason: `network policy refused ${url2}: ${error51.message}`, transient };
111445
+ }
111446
+ return { live: false, reason: `${url2} is unreachable: ${error51 instanceof Error ? error51.message : String(error51)}`, transient };
111447
+ }
111448
+ if (response.status === 401 || response.status === 403) {
111449
+ await response.body?.cancel().catch(() => {
111450
+ });
111451
+ return { live: false, reason: `${url2} is behind an authentication wall (HTTP ${response.status})`, transient: false };
111452
+ }
111453
+ if (response.status >= 400) {
111454
+ await response.body?.cancel().catch(() => {
111455
+ });
111456
+ return { live: false, reason: `${url2} answered HTTP ${response.status}`, transient: response.status >= 500 };
111457
+ }
111458
+ const finalUrl = finalResponseUrl(response);
111459
+ const body = await readBodyPrefix(response);
111460
+ if (looksLikeLoginPage({ requestedUrl: url2, finalUrl, body })) {
111461
+ return {
111462
+ live: false,
111463
+ reason: `${url2} is behind an authentication wall (it ends on a sign-in page${finalUrl && finalUrl !== url2 ? `: ${finalUrl}` : ""})`,
111464
+ transient: false
111465
+ };
111466
+ }
111467
+ return { live: true };
111468
+ }
111469
+ async function checkPublishAttemptBinding(options, url2, attemptId, sourceDigest, operationId) {
111470
+ let attempt;
111471
+ try {
111472
+ attempt = await options.resolvePublishAttempt(attemptId);
111473
+ } catch (error51) {
111474
+ return {
111475
+ ok: false,
111476
+ transient: false,
111477
+ reason: `publication_evidence_missing: publish attempt ${attemptId} for ${url2} could not be read: ${error51 instanceof Error ? error51.message : String(error51)}`
111478
+ };
111479
+ }
111480
+ if (!attempt) {
111481
+ return { ok: false, transient: false, reason: `publication_evidence_unbound: ${url2} names publish attempt ${attemptId}, which does not exist in this project` };
111482
+ }
111483
+ if (attempt.projectSlug !== options.projectSlug || attempt.runId !== options.runId) {
111484
+ return { ok: false, transient: false, reason: `publication_evidence_unbound: publish attempt ${attemptId} belongs to another run, not ${options.runId}` };
111485
+ }
111486
+ if (attempt.status === "failed") {
111487
+ return { ok: false, transient: false, reason: `publication_evidence_unbound: publish attempt ${attemptId} failed, so it cannot prove ${url2}` };
111488
+ }
111489
+ if (attempt.preparedEnvelope?.sourceDigest !== sourceDigest) {
111490
+ return { ok: false, transient: false, reason: `publication_evidence_unbound: ${url2} claims a source digest that publish attempt ${attemptId} did not publish` };
111491
+ }
111492
+ const dispatchedOperationId = nonEmptyString(attempt.dispatchedOperationId);
111493
+ if (dispatchedOperationId !== null && dispatchedOperationId !== operationId) {
111494
+ return { ok: false, transient: false, reason: `publication_evidence_unbound: ${url2} claims operation ${operationId}, but publish attempt ${attemptId} dispatched ${dispatchedOperationId}` };
111495
+ }
111496
+ return { ok: true };
111497
+ }
111498
+ async function verifyPagePublicationEvidence(options) {
111499
+ const startedAt = Date.now();
111500
+ const deadlineMs = options.deadlineMs ?? DEFAULT_PUBLICATION_DEADLINE_MS;
111501
+ const remainingMs = () => deadlineMs - (Date.now() - startedAt);
111502
+ const produced = options.artifacts.map((artifact, index) => ({ artifact, index })).filter(({ artifact }) => artifact.kind === "produced_url").sort((a, b) => {
111503
+ const ac = a.artifact.createdAt ?? "";
111504
+ const bc = b.artifact.createdAt ?? "";
111505
+ return ac && bc && ac !== bc ? ac < bc ? -1 : 1 : a.index - b.index;
111506
+ }).map(({ artifact }) => artifact);
111507
+ if (produced.length === 0) {
111508
+ return {
111509
+ ok: false,
111510
+ reason: "publication_evidence_missing: the page outcome has no produced URL, so nothing proves the page is public"
111511
+ };
111512
+ }
111513
+ let publisher;
111514
+ try {
111515
+ publisher = await options.resolvePublisherTarget();
111516
+ } catch (error51) {
111517
+ return {
111518
+ ok: false,
111519
+ reason: `publication_evidence_missing: the publisher binding could not be read: ${error51 instanceof Error ? error51.message : String(error51)}`
111520
+ };
111521
+ }
111522
+ let publicOrigin = null;
111523
+ try {
111524
+ publicOrigin = publisher?.publicOrigin ? new URL(publisher.publicOrigin).origin : null;
111525
+ } catch {
111526
+ publicOrigin = null;
111527
+ }
111528
+ const isManaged = (artifact) => {
111529
+ const payload = artifact.payload ?? {};
111530
+ return ["operationId", "sourceDigest", "sourceDigestVersion", "publishAttemptId"].some((key) => nonEmptyString(payload[key]) !== null);
111531
+ };
111532
+ const primary = produced.find(isManaged) ?? produced[0];
111533
+ if (!primary) {
111534
+ return { ok: false, reason: "publication_evidence_missing: the page outcome has no produced URL" };
111535
+ }
111536
+ if (publisher && !isManaged(primary)) {
111537
+ const url2 = nonEmptyString((primary.payload ?? {}).url) ?? "(no url)";
111538
+ return {
111539
+ ok: false,
111540
+ reason: `publication_evidence_unmanaged: this project publishes through ${MANAGED_PUBLISHER_SERVER_ID}, so a page closes only on a managed publish; ${url2} was recorded by hand and carries no publish evidence`
111541
+ };
111542
+ }
111543
+ const checkOne = async (artifact, retryTransient) => {
111544
+ const retry = retryTransient ? options.retry : { ...options.retry, attempts: 1 };
111545
+ const fetchTimeoutMs = () => Math.max(1, Math.min(options.timeoutMs ?? DEFAULT_LIVENESS_TIMEOUT_MS, remainingMs()));
111546
+ const payload = artifact.payload ?? {};
111547
+ const rawUrl = nonEmptyString(payload.url);
111548
+ let parsedUrl = null;
111549
+ try {
111550
+ if (rawUrl && rawUrl.startsWith("/") && !rawUrl.startsWith("//")) {
111551
+ parsedUrl = publicOrigin ? new URL(rawUrl, publicOrigin) : null;
111552
+ } else {
111553
+ parsedUrl = rawUrl ? new URL(rawUrl) : null;
111554
+ }
111555
+ } catch {
111556
+ parsedUrl = null;
111557
+ }
111558
+ if (!rawUrl || !parsedUrl || parsedUrl.protocol !== "http:" && parsedUrl.protocol !== "https:") {
111559
+ return {
111560
+ ok: false,
111561
+ url: rawUrl ?? "(no url)",
111562
+ reason: `publication_evidence_missing: produced URL artifact ${artifact.id} is not an absolute http(s) URL` + (rawUrl?.startsWith("/") ? " and there is no publisher public origin to resolve it against" : "")
111563
+ };
111564
+ }
111565
+ const url2 = parsedUrl.toString();
111566
+ if (!isManaged(artifact)) {
111567
+ const liveness = await withTransientRetry(async () => {
111568
+ const live = await verifyUrlLive(url2, { ...options, timeoutMs: fetchTimeoutMs() });
111569
+ return live.live ? { ok: true } : { ok: false, reason: live.reason, transient: live.transient };
111570
+ }, retry, remainingMs);
111571
+ if (!liveness.ok) return { ok: false, url: url2, reason: `public_url_not_verified: ${liveness.reason}` };
111572
+ return { ok: true, verified: { artifactId: artifact.id, url: url2, mode: "liveness" } };
111573
+ }
111574
+ const operationId = nonEmptyString(payload.operationId);
111575
+ const sourceDigest = nonEmptyString(payload.sourceDigest);
111576
+ const sourceDigestVersion = nonEmptyString(payload.sourceDigestVersion);
111577
+ const publishAttemptId = nonEmptyString(payload.publishAttemptId);
111578
+ if (!operationId || !sourceDigest || !sourceDigestVersion || !publishAttemptId) {
111579
+ return {
111580
+ ok: false,
111581
+ url: url2,
111582
+ reason: `publication_evidence_missing: produced URL ${url2} carries incomplete publish evidence (operationId, sourceDigest, sourceDigestVersion and publishAttemptId are all required)`
111583
+ };
111584
+ }
111585
+ if (!SUPPORTED_SOURCE_DIGEST_VERSIONS.has(sourceDigestVersion)) {
111586
+ return {
111587
+ ok: false,
111588
+ url: url2,
111589
+ reason: `publication_evidence_missing: produced URL ${url2} uses source digest version "${sourceDigestVersion}", which this closure cannot compare`
111590
+ };
111591
+ }
111592
+ if (!publicOrigin) {
111593
+ return {
111594
+ ok: false,
111595
+ url: url2,
111596
+ reason: `publication_evidence_missing: no ${MANAGED_PUBLISHER_SERVER_ID} binding with a public origin to check ${url2} against`
111597
+ };
111598
+ }
111599
+ if (parsedUrl.origin !== publicOrigin) {
111600
+ return {
111601
+ ok: false,
111602
+ url: url2,
111603
+ reason: `public_url_outside_origin: ${url2} is not inside the publisher's public origin ${publicOrigin}`
111604
+ };
111605
+ }
111606
+ const binding = await checkPublishAttemptBinding(options, url2, publishAttemptId, sourceDigest, operationId);
111607
+ if (!binding.ok) return { ok: false, url: url2, reason: binding.reason };
111608
+ const result = await withTransientRetry(async () => {
111609
+ const verified2 = await verifyPublicUrl({
111610
+ publicUrl: url2,
111611
+ expectedOperationId: operationId,
111612
+ expectedSourceDigest: sourceDigest,
111613
+ expectedSourceDigestVersion: sourceDigestVersion,
111614
+ allowLocalEndpoints: options.allowLocalEndpoints,
111615
+ ...options.fetchFn ? { fetchFn: options.fetchFn } : {},
111616
+ timeoutMs: fetchTimeoutMs()
111617
+ });
111618
+ if (verified2.verified) return { ok: true };
111619
+ const reason = verified2.outcome === "digest_version_mismatch" ? `publication_evidence_missing: ${verified2.reason}` : `public_url_not_verified: ${verified2.outcome}: ${verified2.reason}`;
111620
+ return { ok: false, reason, transient: isTransientVerificationFailure(verified2) };
111621
+ }, retry, remainingMs);
111622
+ if (!result.ok) return { ok: false, url: url2, reason: result.reason };
111623
+ return { ok: true, verified: { artifactId: artifact.id, url: url2, mode: "managed" } };
111624
+ };
111625
+ const deadlineReason = `public_url_not_verified: the publication check ran out of its ${Math.round(deadlineMs / 1e3)}s budget`;
111626
+ const primaryResult = await withinDeadline(checkOne(primary, true), remainingMs(), () => ({
111627
+ ok: false,
111628
+ url: "",
111629
+ reason: deadlineReason
111630
+ }));
111631
+ if (!primaryResult.ok) return { ok: false, reason: primaryResult.reason };
111632
+ const verified = [primaryResult.verified];
111633
+ const secondaryFailures = [];
111634
+ for (const artifact of produced) {
111635
+ if (artifact === primary) continue;
111636
+ const rawUrl = nonEmptyString((artifact.payload ?? {}).url) ?? "(no url)";
111637
+ const secondary = await withinDeadline(checkOne(artifact, false), remainingMs(), () => ({
111638
+ ok: false,
111639
+ url: rawUrl,
111640
+ reason: `${deadlineReason}; not checked in time`
111641
+ }));
111642
+ if (secondary.ok) verified.push(secondary.verified);
111643
+ else secondaryFailures.push({ artifactId: artifact.id, url: secondary.url, reason: secondary.reason });
111644
+ }
111645
+ return { ok: true, primary: primaryResult.verified, verified, secondaryFailures };
111646
+ }
110690
111647
 
110691
111648
  // src/prompts/task-notes-contract.ts
110692
111649
  init_dist();
@@ -112957,7 +113914,7 @@ async function driveClaimedRun(deps, projectSlug, runId, claimed, leaseId) {
112957
113914
  );
112958
113915
  return;
112959
113916
  }
112960
- const runDomains = Array.isArray(task.domains) ? task.domains : [task.domains ?? "code"];
113917
+ const runDomains = Array.isArray(task.domains) ? task.domains : [];
112961
113918
  const hasCodeDomain = runDomains.some((d) => typeof d === "string" && d.trim().toLowerCase() === "code");
112962
113919
  const isPureCode = runDomains.length === 1 && hasCodeDomain;
112963
113920
  const requires = task.declaredOutcome?.requires ?? [];
@@ -112989,11 +113946,12 @@ async function driveClaimedRun(deps, projectSlug, runId, claimed, leaseId) {
112989
113946
  const isCodeRun = isPureCode || hasCodeDomain && needsCodeChange && claimed.codeExecution === true && claimed.executionRouteIntent === "code" && !!runApproval;
112990
113947
  const verifyLegacyPureScope = async () => {
112991
113948
  const current2 = await deps.client.getTask(projectSlug, task.id);
112992
- const domains = current2.domains ?? ["code"];
113949
+ const domains = current2.domains ?? [];
112993
113950
  return current2.codeScopeApprovalRequired !== true && domains.length === 1 && domains[0] === "code";
112994
113951
  };
112995
113952
  if (!isCodeRun) {
112996
- const runDomain = runDomains.find((d) => typeof d === "string" && d.trim().toLowerCase() !== "code") ?? runDomains[0] ?? "code";
113953
+ const runDomain = runDomains.find((d) => typeof d === "string" && d.trim().toLowerCase() !== "code") ?? runDomains[0] ?? // No domain: author the result with the general content producer.
113954
+ "content";
112997
113955
  let providerId = claimed.agentSeat;
112998
113956
  if (providerId == null) {
112999
113957
  const seat = await mintResolvedSeat(resolveProvider(process.env, getSelectedProvider()));
@@ -114380,7 +115338,7 @@ function buildDeliverableAuthorPrompt(task, specMarkdown, project, journalMarkdo
114380
115338
  `--- TASK ---`,
114381
115339
  `id: ${task.id}`,
114382
115340
  `title: ${task.title}`,
114383
- `domains: ${(task.domains ?? ["code"]).join(", ")}`,
115341
+ `domains: ${task.domains?.length ? task.domains.join(", ") : "none (not a code task)"}`,
114384
115342
  ``,
114385
115343
  `notes:`,
114386
115344
  task.notes ?? "(none)",
@@ -114711,22 +115669,56 @@ async function driveNonCodeRun(deps, projectSlug, runId, leaseId, task, domain2,
114711
115669
  }
114712
115670
  const awaitsResultConfirmation = rawProject.awaitsResultConfirmation === true;
114713
115671
  const isPageOutcome = task.declaredOutcome?.requires?.includes("page") === true;
114714
- const hasPublicationEvidence = isPageOutcome && parsedResult.outcome === "completed" && !awaitsResultConfirmation && !deps.signingProvider && (await deps.client.listExecutionArtifacts(projectSlug, runId).catch(() => [])).some((artifact) => artifact.kind === "produced_url");
114715
- if (hasPublicationEvidence) {
114716
- await failRun(
114717
- deps,
115672
+ const verifyPagePublication = async (artifacts) => {
115673
+ const evidence = await verifyPagePublicationEvidence({
115674
+ artifacts,
114718
115675
  projectSlug,
114719
- task,
114720
115676
  runId,
114721
- leaseId,
114722
- `receipt_signing_unavailable: task ${task.id} produced publication evidence, but closure signing provider is unavailable (PUB-011)`,
114723
- "receipt_signing_unavailable"
114724
- );
114725
- return;
115677
+ resolvePublisherTarget: async () => {
115678
+ const target = (await deps.client.getIntegrationBinding(projectSlug, MANAGED_PUBLISHER_SERVER_ID))?.publisherTarget;
115679
+ return target ? { publicOrigin: target.publicOrigin ?? null } : null;
115680
+ },
115681
+ // Read-only: binds managed evidence to this run's own publish attempt (anti-forgery).
115682
+ resolvePublishAttempt: (attemptId) => deps.client.getPublishAttempt(projectSlug, attemptId),
115683
+ ...deps.publicationFetch ? { fetchFn: deps.publicationFetch } : {},
115684
+ ...deps.publicationRetrySleep ? { retry: { sleep: deps.publicationRetrySleep } } : {}
115685
+ });
115686
+ if (evidence.ok && evidence.secondaryFailures.length > 0) {
115687
+ const lines2 = evidence.secondaryFailures.map((failure) => `- ${failure.url}: ${failure.reason}`).join("\n");
115688
+ console.error(`[mrrlin] run ${runId}: ${evidence.secondaryFailures.length} secondary produced URL(s) failed the public check`);
115689
+ try {
115690
+ await deps.client.appendTaskEvent(projectSlug, task.id, {
115691
+ kind: "note",
115692
+ body: `The page's main link ${evidence.primary.url} is live, but ${evidence.secondaryFailures.length === 1 ? "another link this run recorded is" : "other links this run recorded are"} not:
115693
+ ${lines2}`
115694
+ });
115695
+ } catch {
115696
+ }
115697
+ }
115698
+ return evidence;
115699
+ };
115700
+ if (isPageOutcome && parsedResult.outcome === "completed" && !awaitsResultConfirmation && !deps.signingProvider) {
115701
+ const artifacts = await deps.client.listExecutionArtifacts(projectSlug, runId).catch(() => []);
115702
+ if (artifacts.some((artifact) => artifact.kind === "produced_url")) {
115703
+ const evidence = await verifyPagePublication(artifacts);
115704
+ deps.activeLease?.progress();
115705
+ if (!evidence.ok) {
115706
+ await failRun(deps, projectSlug, task, runId, leaseId, evidence.reason);
115707
+ return;
115708
+ }
115709
+ }
114726
115710
  }
114727
115711
  if (deps.signingProvider && (parsedResult.outcome === "negative_result" || parsedResult.outcome === "completed" && !awaitsResultConfirmation)) {
115712
+ const existingArtifacts = isPageOutcome ? await deps.client.listExecutionArtifacts(projectSlug, runId).catch(() => []) : [];
115713
+ if (isPageOutcome && parsedResult.outcome === "completed") {
115714
+ const evidence = await verifyPagePublication(existingArtifacts);
115715
+ deps.activeLease?.progress();
115716
+ if (!evidence.ok) {
115717
+ await failRun(deps, projectSlug, task, runId, leaseId, evidence.reason);
115718
+ return;
115719
+ }
115720
+ }
114728
115721
  try {
114729
- const existingArtifacts = isPageOutcome ? await deps.client.listExecutionArtifacts(projectSlug, runId).catch(() => []) : [];
114730
115722
  const urlArtifacts = existingArtifacts.filter((a) => a.kind === "produced_url").map((a) => ({
114731
115723
  artifactId: a.id,
114732
115724
  storageVersion: "1",
@@ -124007,6 +124999,22 @@ async function runExternalAgentsPruneAtStartup(deps) {
124007
124999
 
124008
125000
  // src/director-bridge.ts
124009
125001
  var JSON_GPT_MODEL_REF_RE = /"(?:slug|model)"\s*:\s*"(gpt-[a-z0-9.-]+)"/gi;
125002
+ var DECLINED_PROPOSALS_MAX = 5;
125003
+ var DECLINED_PROPOSAL_TITLE_MAX = 120;
125004
+ var DECLINED_PROPOSALS_TIMEOUT_MS = 1500;
125005
+ function toDeclinedProposalContext(proposals) {
125006
+ return proposals.slice(0, DECLINED_PROPOSALS_MAX).map((proposal) => {
125007
+ const intent = proposal.resolvedIntent ?? {};
125008
+ const rawTitle = typeof intent.title === "string" && intent.title.trim() ? intent.title.trim() : "Untitled";
125009
+ const title = rawTitle.length > DECLINED_PROPOSAL_TITLE_MAX ? `${rawTitle.slice(0, DECLINED_PROPOSAL_TITLE_MAX - 1)}\u2026` : rawTitle;
125010
+ return {
125011
+ proposalId: proposal.proposalId,
125012
+ kind: intent.kind === "plan" ? "plan" : "task",
125013
+ title,
125014
+ declinedAt: proposal.updatedAt ?? ""
125015
+ };
125016
+ });
125017
+ }
124010
125018
  var COMPACT_REQUEST_HISTORY_MAX_ITEMS = 500;
124011
125019
  function isValidChatHistoryMessage(value) {
124012
125020
  if (!value || typeof value !== "object") return false;
@@ -124362,7 +125370,7 @@ function buildThreadStartParams(msg, config2, desiredModel) {
124362
125370
  "- Apply this format ONLY to Specs/{id} pages; do not retro-fit it onto other wiki page types.",
124363
125371
  "- With each spec, set the task's `declaredOutcome` via `update_task` yourself; approval needs it.",
124364
125372
  '- Spec consensus runs ASYNCHRONOUSLY. Call `run_spec_consensus` for a `Specs/{id}` page; it returns IMMEDIATELY. On `already_converged`, the spec is already marked ready \u2014 proceed straight to `create_execution_run`; do NOT call `mark_spec_ready` and do NOT re-run consensus. On `queued` or `already_running`, tell the user it was launched and END your turn \u2014 do NOT poll or call it again; the result arrives in the inbox (an `info` item on CONVERGED, a `handoff` item if it was blocked/failed). When a `handoff` says it was blocked, address the recorded issues in the spec (any edit re-arms the gate) and call `run_spec_consensus` once more. For a NON-code task (domain seo/marketing/content, ADR 0020): the low-risk lanes `seo`, `marketing`, and `content` proceed to `create_execution_run` after consensus converges, using the same flow as code tasks. When the review agrees, tell the operator "the reviewers agreed on the spec" and proceed to create_execution_run. When it does not, tell them the reviewers could not agree and that there is a decision question in the inbox. Never say "consensus", "converged", or "CONVERGED" to the operator; those are internal words.',
124365
- "- When creating a task, classify and supply the `domain` field explicitly based on the nature of the work: pass `domain:'code'` for software engineering work, `domain:'seo'` for SEO/optimization, `domain:'marketing'` for marketing/growth, or `domain:'content'` for content creation/writing \u2014 the same way you select category/subcategory. A follow-up task spawned with `parentTaskId` inherits its parent's domain automatically and requires no explicit domain.",
125373
+ "- Classify every task you create via `domains`: `['code']` for software changes, else `['seo']`, `['marketing']` or `['content']` (a `parentTaskId` follow-up inherits its parent's). Code is never the default. Reclassify as you learn: when a task turns out to need code changes, update_task its `domains` to include `code`; when it does not, switch them to the fitting non-code domain.",
124366
125374
  '- When a task needs a browser (login flows, UI verification/clicks, scraping), pass `prerequisites:[{mcp:"mrrlin-browser",reason:"..."}]` to `create_execution_run`. If that run later fails into a handoff, the operator gets a one-click "Launch browser & resume" that brings up the dedicated browser as the turn starts.',
124367
125375
  "- When you actually drive a browser (calling `browser_navigate`, `browser_click`, `browser_snapshot`, `browser_type`, etc.), invoke those tools from the **`mrrlin-browser`** MCP server ONLY. Do NOT use tools from any other browser MCP (`playwright`, `chrome-devtools`, `puppeteer`, etc.) even if they are also connected on this operator's box \u2014 those use a shared/default Playwright profile that is fragile across runs. Only `mrrlin-browser` uses this project's dedicated Chromium + persistent operator profile (`~/.mrrlin/browser/profile`). If your host exposes multiple browser MCPs with overlapping tool names, prefer the `mrrlin-browser` server unconditionally.",
124368
125376
  "- One browser session is shared by every concurrent chat on this operator's box (a code run drives its task's own copy) \u2014 a deliberate tradeoff, so a second user is expected, not exceptional. If a `mrrlin-browser` call fails with `Browser is already in use for ...`, that means another one of the operator's own chats or tasks is driving the browser RIGHT NOW. Do not present this as a broken tool or a mysterious error: tell the operator plainly that the browser is busy with another task, ask them to wait for it to finish (or close it), and offer to retry shortly. Never retry-loop this silently.",
@@ -125962,6 +126970,23 @@ function createBridgeMessageHandler(deps) {
125962
126970
  } catch {
125963
126971
  }
125964
126972
  }
126973
+ let declinedProposals;
126974
+ if (deps.listDeclinedProposals && contextProjectSlug) {
126975
+ let timer;
126976
+ try {
126977
+ const declined = await Promise.race([
126978
+ deps.listDeclinedProposals(contextProjectSlug),
126979
+ new Promise((_, reject) => {
126980
+ timer = setTimeout(() => reject(new Error("declined proposals timed out")), DECLINED_PROPOSALS_TIMEOUT_MS);
126981
+ })
126982
+ ]);
126983
+ const mapped = toDeclinedProposalContext(declined);
126984
+ declinedProposals = mapped.length ? mapped : void 0;
126985
+ } catch {
126986
+ } finally {
126987
+ if (timer) clearTimeout(timer);
126988
+ }
126989
+ }
125965
126990
  if (!contextProjectSlug) {
125966
126991
  sendForSpan({
125967
126992
  type: "error",
@@ -126033,6 +127058,7 @@ function createBridgeMessageHandler(deps) {
126033
127058
  ...msg.context,
126034
127059
  project: projectContext,
126035
127060
  answeredQuestions,
127061
+ declinedProposals,
126036
127062
  openQuestions: presentedLedger.shown.length ? presentedLedger.shown : void 0,
126037
127063
  clarifications: msg.context?.clarifications ?? (presentedLedger.shown.some((i) => i.id) ? presentedLedger.shown.map(({ id, round, ordinal, question, status, answer, actor }) => ({
126038
127064
  id,
@@ -127392,6 +128418,7 @@ async function startBridge(startupDeps, agentSecret, startupRollback) {
127392
128418
  }
127393
128419
  },
127394
128420
  listAnsweredQuestions: (projectSlug, taskId) => client.listInboxItems(projectSlug, { status: "acknowledged", kind: "question", taskId }),
128421
+ listDeclinedProposals: (projectSlug) => client.listIntentProposals(projectSlug, { state: "declined" }),
127395
128422
  snapshotProjectObjects: async (projectSlug, opts) => {
127396
128423
  const signal = opts?.signal;
127397
128424
  if (signal?.aborted) throw new Error("snapshot aborted");
@@ -128067,6 +129094,8 @@ function renderContextPrefix(context) {
128067
129094
  if (answeredQuestions) payload.answeredQuestions = answeredQuestions;
128068
129095
  const openQuestions = context?.openQuestions?.length ? context.openQuestions : void 0;
128069
129096
  if (openQuestions) payload.openQuestions = openQuestions;
129097
+ const declinedProposals = context?.declinedProposals?.length ? context.declinedProposals.slice(0, DECLINED_PROPOSALS_MAX) : void 0;
129098
+ if (declinedProposals) payload.declinedProposals = declinedProposals;
128070
129099
  if (context?.activeProposal) payload.activeProposal = context.activeProposal;
128071
129100
  if (context?.clarifications?.length) payload.clarifications = context.clarifications;
128072
129101
  const keys = Object.keys(payload);
@@ -128078,6 +129107,11 @@ function renderContextPrefix(context) {
128078
129107
  `[ACTIVE PROPOSAL] Proposal ID: ${context.activeProposal.id} (version ${context.activeProposal.version}). Work is created only by the operator confirming a proposal in the chat; propose new work with propose_task. create_plan, and create_task for an already-confirmed proposal, need its proposalId, proposalVersion, and proposalDigest.`
128079
129108
  );
128080
129109
  }
129110
+ if (declinedProposals) {
129111
+ parts.push(
129112
+ "[DECLINED PROPOSALS] `declinedProposals` lists proposals the operator declined (\xABNot now\xBB). Do not propose the same work again unless the operator asks for it again; if it still matters, ask what should change instead."
129113
+ );
129114
+ }
128081
129115
  if (context?.clarifications?.length) {
128082
129116
  parts.push(
128083
129117
  "[DURABLE CLARIFICATIONS] Prior clarification decisions with stable IDs and states: answered or rejected items MUST NOT be re-asked. You may ask at most 3 questions per round. After 3 unresolved clarification rounds, escalation is triggered and no work can be created."