mcp-scraper 0.85.0 → 0.86.1

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.
@@ -43,7 +43,7 @@ import {
43
43
  setExtractJobTotal,
44
44
  settleExtractJob,
45
45
  terminalExtractJobStatus
46
- } from "./chunk-C7OKENCR.js";
46
+ } from "./chunk-KQWVJOVR.js";
47
47
  import {
48
48
  REQUIRED_LOCATION_STATE_CODES,
49
49
  importHostedCensusPlacesCsv,
@@ -105,7 +105,7 @@ import {
105
105
  probeNangoConnectionDirect,
106
106
  recordNangoConnectionCost,
107
107
  settleConnectedUsage
108
- } from "./chunk-W3SGF7GX.js";
108
+ } from "./chunk-WFGAR4BZ.js";
109
109
  import {
110
110
  ANALYTICS_ATTRIBUTION_MODELS,
111
111
  ANALYTICS_CONTENT_SORTS,
@@ -134,6 +134,7 @@ import {
134
134
  claimAnalyticsCrmImportRows,
135
135
  claimAnalyticsFormDeliveryJobs,
136
136
  completeAnalyticsCrmImportRow,
137
+ completeAnalyticsFormBridgeDelivery,
137
138
  completeAnalyticsFormDelivery,
138
139
  consumeAnalyticsSurveyInvite,
139
140
  createAnalyticsActivationDestination,
@@ -148,6 +149,7 @@ import {
148
149
  deferAnalyticsCrmImportRow,
149
150
  deferAnalyticsFormDelivery,
150
151
  deleteAnalyticsSite,
152
+ deterministicAnalyticsCrmEntityId,
151
153
  encryptAnalyticsRestricted,
152
154
  enrichAnalyticsExistingCrmIdentity,
153
155
  getAnalyticsActivationDestinationConnectionRef,
@@ -172,9 +174,8 @@ import {
172
174
  normalizeProviderReceipt,
173
175
  pollAnalyticsActivationDiagnostics,
174
176
  prepareAnalyticsLinkerIssue,
175
- queueAnalyticsFormDelivery,
177
+ queueAnalyticsFormBridgeTransaction,
176
178
  readImmutableConfirmedAttributionEvidence,
177
- recordAnalyticsFormSubmission,
178
179
  redeemAnalyticsLinkerRecord,
179
180
  refreshAnalyticsDailyRollupsIfDue,
180
181
  requireAnalyticsAccess,
@@ -193,7 +194,7 @@ import {
193
194
  upsertAnalyticsAdSpend,
194
195
  upsertAnalyticsHostGroup,
195
196
  verifyAnalyticsWebhookSignature
196
- } from "./chunk-TLRJV4SL.js";
197
+ } from "./chunk-X623GTBV.js";
197
198
  import {
198
199
  claimServiceConnectionAction,
199
200
  ensureServiceConnectionsSchema,
@@ -387,7 +388,7 @@ import {
387
388
  transcribeMediaUrl,
388
389
  transitionAnalyticsExperiment,
389
390
  validateAnalyticsRestResponseForRequest
390
- } from "./chunk-W4IY6CB4.js";
391
+ } from "./chunk-3H7QTJLV.js";
391
392
  import {
392
393
  auditImageUrls,
393
394
  auditImages,
@@ -458,7 +459,7 @@ import {
458
459
  tierChangeLeavesPrivateOffer,
459
460
  tierCreditsPerInterval,
460
461
  vendorCostUsdToMc
461
- } from "./chunk-X5HRAAQM.js";
462
+ } from "./chunk-NKRO2SUO.js";
462
463
  import {
463
464
  browserServiceApiKey,
464
465
  browserServiceProfileName,
@@ -508,7 +509,7 @@ import {
508
509
  } from "./chunk-GGZEC22A.js";
509
510
  import {
510
511
  PACKAGE_VERSION
511
- } from "./chunk-RHAOKXQK.js";
512
+ } from "./chunk-C4C4WUTV.js";
512
513
  import {
513
514
  CaptchaError,
514
515
  MapsSearchIncompletePageError,
@@ -3971,7 +3972,7 @@ async function generateOgImage(post) {
3971
3972
 
3972
3973
  // src/api/server.ts
3973
3974
  import { Resend as Resend3 } from "resend";
3974
- import { createHash as createHash103, randomUUID as randomUUID68 } from "crypto";
3975
+ import { createHash as createHash104, randomUUID as randomUUID69 } from "crypto";
3975
3976
 
3976
3977
  // src/api/kpo-extractor.ts
3977
3978
  import TurndownService from "turndown";
@@ -7321,7 +7322,7 @@ async function extractSite(opts) {
7321
7322
  }
7322
7323
 
7323
7324
  // src/api/server.ts
7324
- import { Hono as Hono48 } from "hono";
7325
+ import { Hono as Hono49 } from "hono";
7325
7326
  import { serve as serveInngest } from "inngest/hono";
7326
7327
 
7327
7328
  // src/inngest/client.ts
@@ -9763,7 +9764,7 @@ var siteExtractFn = inngest.createFunction(
9763
9764
  });
9764
9765
  }) : null;
9765
9766
  const finalized = await step.run("finalize", async () => {
9766
- const { assembleExtractArtifacts } = await import("./extract-bundle-NSMGHEG6.js");
9767
+ const { assembleExtractArtifacts } = await import("./extract-bundle-FALNLKYY.js");
9767
9768
  const current = await getExtractJob(jobId2);
9768
9769
  if (!current) throw new Error("extract job disappeared before finalization");
9769
9770
  const stored = await assembleExtractArtifacts(current, { branding, imageAudit });
@@ -21498,25 +21499,36 @@ async function recordPendingBrightDataRedditUsage(providerSessionId, telemetry)
21498
21499
  async function refreshFinalizedRedditProbeCosts() {
21499
21500
  const db = getDb();
21500
21501
  const probes = await db.execute({
21501
- sql: `SELECT v.probe_run_id, SUM(v.est_cost_usd) AS cost
21502
+ sql: `SELECT v.probe_run_id,
21503
+ SUM(CASE WHEN v.method = ? THEN v.est_cost_usd ELSE 0 END) AS cost,
21504
+ SUM(CASE WHEN v.method = ? THEN 1 ELSE 0 END) AS pending_count
21502
21505
  FROM vendor_usage_log v JOIN cost_probe_runs p ON p.id = v.probe_run_id
21503
- WHERE v.method = ? AND v.probe_run_id IS NOT NULL
21506
+ WHERE v.vendor = 'brightdata_browser_api' AND v.method IN (?, ?) AND v.probe_run_id IS NOT NULL
21504
21507
  GROUP BY v.probe_run_id
21505
- HAVING ABS(SUM(v.est_cost_usd) - MAX(p.vendor_cost_usd)) > 0.000000000001
21506
- OR MAX(CASE WHEN json_valid(p.notes) THEN json_extract(p.notes, '$.providerCostPending') ELSE 0 END) = 1
21508
+ HAVING ABS(SUM(CASE WHEN v.method = ? THEN v.est_cost_usd ELSE 0 END) - MAX(p.vendor_cost_usd)) > 0.000000000001
21509
+ OR MAX(CASE WHEN json_valid(p.notes) THEN COALESCE(json_extract(p.notes, '$.providerCostPending'), 0) ELSE 0 END)
21510
+ != CASE WHEN SUM(CASE WHEN v.method = ? THEN 1 ELSE 0 END) > 0 THEN 1 ELSE 0 END
21507
21511
  LIMIT 100`,
21508
- args: [REDDIT_COMPLETE_METHOD]
21512
+ args: [
21513
+ REDDIT_COMPLETE_METHOD,
21514
+ REDDIT_PENDING_METHOD,
21515
+ REDDIT_COMPLETE_METHOD,
21516
+ REDDIT_PENDING_METHOD,
21517
+ REDDIT_COMPLETE_METHOD,
21518
+ REDDIT_PENDING_METHOD
21519
+ ]
21509
21520
  });
21510
21521
  for (const probe of probes.rows) {
21511
21522
  const cost = Number(probe.cost ?? 0);
21523
+ const providerCostPending = Number(probe.pending_count ?? 0) > 0;
21512
21524
  await db.execute({
21513
21525
  sql: `UPDATE cost_probe_runs SET
21514
21526
  margin_usd_headless_starter = margin_usd_headless_starter - (? - vendor_cost_usd),
21515
21527
  margin_usd_headful_starter = margin_usd_headful_starter - (? - vendor_cost_usd),
21516
21528
  vendor_cost_usd = ?,
21517
- notes = CASE WHEN json_valid(notes) THEN json_set(notes, '$.providerCostPending', json('false')) ELSE notes END
21529
+ notes = CASE WHEN json_valid(notes) THEN json_set(notes, '$.providerCostPending', json(?)) ELSE notes END
21518
21530
  WHERE id = ?`,
21519
- args: [cost, cost, cost, probe.probe_run_id]
21531
+ args: [cost, cost, cost, providerCostPending ? "true" : "false", probe.probe_run_id]
21520
21532
  });
21521
21533
  }
21522
21534
  }
@@ -21724,39 +21736,77 @@ async function runBrightDataRedditThreadBackup(url2, requestedComments) {
21724
21736
 
21725
21737
  // src/reddit/thread-retrieval.ts
21726
21738
  async function retrieveRedditThread(kernelApiKey, input) {
21727
- let primaryFailure;
21728
- if (!kernelApiKey) primaryFailure = new Error("Kernel Reddit primary is not configured");
21729
- else {
21730
- try {
21731
- const primary = await runKernelRedditThread(kernelApiKey, input);
21732
- if (!isAcceptedRedditThread(primary.thread, input.maxComments)) {
21733
- throw new Error(`Kernel Reddit primary returned ${primary.thread.comments.length} comments below the ${redditThreadAcceptanceTarget(primary.thread, input.maxComments)} comment acceptance target`);
21739
+ const kernelFailures = [];
21740
+ let kernelAttempts = 0;
21741
+ if (!kernelApiKey) {
21742
+ kernelFailures.push("Kernel Reddit primary is not configured");
21743
+ } else {
21744
+ for (let attempt = 1; attempt <= 2; attempt += 1) {
21745
+ kernelAttempts = attempt;
21746
+ try {
21747
+ const primary = await runKernelRedditThread(kernelApiKey, input);
21748
+ if (!isAcceptedRedditThread(primary.thread, input.maxComments)) {
21749
+ throw new Error(`Kernel Reddit primary returned ${primary.thread.comments.length} comments below the ${redditThreadAcceptanceTarget(primary.thread, input.maxComments)} comment acceptance target`);
21750
+ }
21751
+ return {
21752
+ ...primary,
21753
+ diagnostics: {
21754
+ ...primary.diagnostics,
21755
+ fallbackUsed: false,
21756
+ retrievalProvider: "kernel",
21757
+ kernelAttempts,
21758
+ brightDataAttempts: 0,
21759
+ totalAttempts: kernelAttempts,
21760
+ kernelFailures
21761
+ }
21762
+ };
21763
+ } catch (error) {
21764
+ const message = sanitizeProviderLocalMessage(error instanceof Error ? error.message : String(error)) ?? "Kernel Reddit primary failed";
21765
+ kernelFailures.push(message);
21766
+ console.warn(JSON.stringify({
21767
+ event: "reddit_kernel_primary_rejected",
21768
+ attempt,
21769
+ max_attempts: 2,
21770
+ will_retry: attempt < 2,
21771
+ error: message,
21772
+ fallback: attempt === 2 ? "bright_data_browser_api" : null
21773
+ }));
21734
21774
  }
21775
+ }
21776
+ }
21777
+ const brightDataFailures = [];
21778
+ for (let attempt = 1; attempt <= 2; attempt += 1) {
21779
+ try {
21780
+ const backup = await runBrightDataRedditThreadBackup(input.url, Math.min(input.maxComments, 25));
21735
21781
  return {
21736
- ...primary,
21737
- diagnostics: { ...primary.diagnostics, fallbackUsed: false, retrievalProvider: "kernel" }
21782
+ ...backup,
21783
+ diagnostics: {
21784
+ ...backup.diagnostics,
21785
+ retrievalProvider: "bright_data_browser_api",
21786
+ primaryProvider: "kernel",
21787
+ primaryFailure: kernelFailures.at(-1) ?? "Kernel Reddit primary failed",
21788
+ kernelAttempts,
21789
+ brightDataAttempts: attempt,
21790
+ totalAttempts: kernelAttempts + attempt,
21791
+ kernelFailures,
21792
+ brightDataFailures
21793
+ }
21738
21794
  };
21739
21795
  } catch (error) {
21740
- primaryFailure = error instanceof Error ? error : new Error(String(error));
21796
+ const message = sanitizeProviderLocalMessage(error instanceof Error ? error.message : String(error)) ?? "Bright Data Reddit backup failed";
21797
+ brightDataFailures.push(message);
21798
+ console.warn(JSON.stringify({
21799
+ event: "reddit_bright_data_backup_rejected",
21800
+ attempt,
21801
+ max_attempts: 2,
21802
+ will_retry: attempt < 2,
21803
+ error: message
21804
+ }));
21741
21805
  }
21742
21806
  }
21743
- const primaryError = sanitizeProviderLocalMessage(primaryFailure.message) ?? "Kernel Reddit primary failed";
21744
- console.warn(JSON.stringify({ event: "reddit_kernel_primary_rejected", error: primaryError, fallback: "bright_data_browser_api" }));
21745
- try {
21746
- const backup = await runBrightDataRedditThreadBackup(input.url, Math.min(input.maxComments, 25));
21747
- return {
21748
- ...backup,
21749
- diagnostics: {
21750
- ...backup.diagnostics,
21751
- retrievalProvider: "bright_data_browser_api",
21752
- primaryProvider: "kernel",
21753
- primaryFailure: primaryError
21754
- }
21755
- };
21756
- } catch (backupError) {
21757
- const backupMessage = sanitizeProviderLocalMessage(backupError instanceof Error ? backupError.message : String(backupError)) ?? "Bright Data Reddit backup failed";
21758
- throw new Error(`Reddit retrieval failed: Kernel primary: ${primaryError}; Bright Data backup: ${backupMessage}`);
21759
- }
21807
+ throw new Error(
21808
+ `Reddit retrieval failed: Kernel attempts: ${kernelFailures.join(" | ")}; Bright Data attempts: ${brightDataFailures.join(" | ")}`
21809
+ );
21760
21810
  }
21761
21811
 
21762
21812
  // src/api/reddit-routes.ts
@@ -21826,7 +21876,7 @@ redditApp.post("/thread", createApiKeyAuth(), async (c) => {
21826
21876
  canonicalUrl: receipt4.canonicalUrl,
21827
21877
  oldRedditUrl: null,
21828
21878
  retrievalSource: "www_reddit",
21829
- attempts: receipt4.diagnostics.fallbackUsed ? 2 : 1,
21879
+ attempts: receipt4.diagnostics.totalAttempts ?? (receipt4.diagnostics.fallbackUsed ? 2 : 1),
21830
21880
  diagnostics: receipt4.diagnostics
21831
21881
  };
21832
21882
  const commentCount = Array.isArray(result3.comments) ? result3.comments.length : 0;
@@ -35418,17 +35468,17 @@ async function discoverAnalyticsCrmEffectiveProfile(input) {
35418
35468
  const publicProfile = getAnalyticsCrmProviderProfile(provider);
35419
35469
  const payload = provider === "highlevel" ? { locationId: input.discoveryContext?.locationId } : provider === "zoho" ? { module: input.discoveryContext?.zohoModules?.[0] ?? "Contacts" } : {};
35420
35470
  if (provider === "highlevel" && !safeString(payload.locationId, 128)) throw new Error("analytics_crm_highlevel_location_required");
35421
- const call = (actionPayload, suffix2) => input.dependencies.callAction({
35471
+ const call2 = (actionPayload, suffix2) => input.dependencies.callAction({
35422
35472
  connectionId: input.connectionId,
35423
35473
  action: ANALYTICS_CRM_NANGO_ACTIONS.discoverSchema,
35424
35474
  payload: actionPayload,
35425
35475
  idempotencyKey: stableId("crmdiscover", { provider, connectionId: input.connectionId, actionPayload, suffix: suffix2 })
35426
35476
  });
35427
- let raw = await call(payload);
35477
+ let raw = await call2(payload);
35428
35478
  if (provider === "zoho") {
35429
35479
  const modules = [...new Set(input.discoveryContext?.zohoModules ?? ["Contacts", "Deals"])];
35430
35480
  const results = [raw];
35431
- for (const module of modules.slice(1)) results.push(await call({ module }, module));
35481
+ for (const module of modules.slice(1)) results.push(await call2({ module }, module));
35432
35482
  raw = { moduleResults: results };
35433
35483
  }
35434
35484
  const normalized = normalizeProviderSchema(provider, raw);
@@ -39772,7 +39822,7 @@ loadChannels();
39772
39822
 
39773
39823
  // src/api/vault-routes.ts
39774
39824
  import { Hono as Hono30 } from "hono";
39775
- var VAULTS = ["People", "Organizations", "Deals", "Projects", "Tasks", "Communications", "Calendar"];
39825
+ var VAULTS = ["People", "Organizations", "CRM People", "CRM Organizations", "Deals", "Projects", "Tasks", "Communications", "Calendar"];
39776
39826
  var PROJECT_TYPES = ["codebase", "personal", "work", "client"];
39777
39827
  var PROJECT_KIND_BY_TYPE = {
39778
39828
  codebase: "codebase",
@@ -39856,6 +39906,8 @@ function normalizeRelationshipProps(vault, props) {
39856
39906
  }
39857
39907
  function defaultType(vault) {
39858
39908
  if (vault === "People" || vault === "Communications") return "unclassified";
39909
+ if (vault === "CRM People") return "person";
39910
+ if (vault === "CRM Organizations") return "organization";
39859
39911
  if (vault === "Organizations") return "organization";
39860
39912
  if (vault === "Deals") return "deal";
39861
39913
  if (vault === "Projects") return "project";
@@ -39864,7 +39916,7 @@ function defaultType(vault) {
39864
39916
  return "unclassified";
39865
39917
  }
39866
39918
  function defaultStatus(vault) {
39867
- if (vault === "People" || vault === "Organizations") return "active";
39919
+ if (vault === "People" || vault === "Organizations" || vault === "CRM People" || vault === "CRM Organizations") return "active";
39868
39920
  if (vault === "Deals") return "lead";
39869
39921
  if (vault === "Projects") return "active";
39870
39922
  if (vault === "Tasks") return "to_do";
@@ -39939,7 +39991,7 @@ async function mapWithConcurrency3(items, limit, map) {
39939
39991
  await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()));
39940
39992
  return values;
39941
39993
  }
39942
- async function readVault(vault, token7) {
39994
+ async function readLegacyVault(vault, token7) {
39943
39995
  const list = await readMemory("listTool", { vault }, token7);
39944
39996
  if (!list.ok) throw new Error(list.error ?? `unable to read ${vault}`);
39945
39997
  const noteRefs = (list.notes ?? []).slice(0, MAX_VAULT_RECORDS);
@@ -39952,6 +40004,28 @@ async function readVault(vault, token7) {
39952
40004
  if (failed && !failed.ok) throw new Error(failed.error ?? `unable to read ${vault} record`);
39953
40005
  return notes.filter((result3) => result3.ok && !!result3.note).map((result3) => workspaceRecord(vault, result3.note));
39954
40006
  }
40007
+ async function readVault(vault, token7) {
40008
+ const tool = vault === "People" ? "researchPersonSearchTool" : vault === "Organizations" ? "researchOrganizationSearchTool" : vault === "CRM People" ? "crmPersonSearchTool" : vault === "CRM Organizations" ? "crmOrganizationSearchTool" : null;
40009
+ if (!tool) return readLegacyVault(vault, token7);
40010
+ const result3 = await memoryCall(tool, { limit: MAX_VAULT_RECORDS }, token7);
40011
+ if (!result3.ok) throw new Error(result3.error ?? `unable to read ${vault}`);
40012
+ return (result3.items ?? []).map((item) => workspaceRecord(vault, {
40013
+ path: item.entityId,
40014
+ title: item.displayName,
40015
+ content: item.content,
40016
+ kind: vault.startsWith("CRM ") ? "crm" : "research",
40017
+ updatedAt: item.updatedAt,
40018
+ capturedAt: item.createdAt,
40019
+ revision: item.revision,
40020
+ props: {
40021
+ ...item.props,
40022
+ type: vault === "People" || vault === "CRM People" ? "person" : "organization",
40023
+ relationship_status: item.relationshipStatus,
40024
+ relationship_types: item.relationshipTypes,
40025
+ commercial_lifecycle: item.commercialLifecycle
40026
+ }
40027
+ }));
40028
+ }
39955
40029
  vaultApp.get("/api/workspace", async (c) => {
39956
40030
  const token7 = c.req.query("token");
39957
40031
  if (!validToken(token7)) return c.json({ ok: false, error: "missing or malformed Vault App link" }, 401);
@@ -39976,6 +40050,9 @@ vaultApp.post("/api/records", async (c) => {
39976
40050
  const content = typeof body3.content === "string" && body3.content.length <= 1e5 ? body3.content : "";
39977
40051
  const props = propsValue(body3.props) ?? {};
39978
40052
  if (!isVault(vault) || !path5 || !title) return c.json({ ok: false, error: "vault, path, and title are required" }, 400);
40053
+ if (["People", "Organizations", "CRM People", "CRM Organizations"].includes(vault)) {
40054
+ return c.json({ ok: false, error: "Governed Research and CRM records must be created through the native Research or CRM workflow." }, 409);
40055
+ }
39979
40056
  const normalizedProps = normalizeRelationshipProps(vault, props);
39980
40057
  const validationError2 = validateNewRecord(vault, normalizedProps);
39981
40058
  if (validationError2) return c.json({ ok: false, error: validationError2 }, 400);
@@ -45170,10 +45247,10 @@ function mergeArticleSections(left, right) {
45170
45247
  categories: uniqueStrings([...left.categories, ...right.categories]).slice(0, 50)
45171
45248
  };
45172
45249
  }
45173
- function mergeUniqueRecords(items, keyFor) {
45250
+ function mergeUniqueRecords(items, keyFor2) {
45174
45251
  const map = /* @__PURE__ */ new Map();
45175
45252
  for (const item of items) {
45176
- const key3 = keyFor(item).toLowerCase().replace(/\s+/g, " ").trim();
45253
+ const key3 = keyFor2(item).toLowerCase().replace(/\s+/g, " ").trim();
45177
45254
  map.set(key3, { ...map.get(key3), ...item });
45178
45255
  }
45179
45256
  return [...map.values()];
@@ -46637,10 +46714,11 @@ function previewAnalyticsManualImport(input) {
46637
46714
  continue;
46638
46715
  }
46639
46716
  identities.add(identityKey2);
46640
- const digest23 = createHash31("sha256").update(`${parsedInput.sourceSystem}:${stableIdentity}`).digest("hex").slice(0, 24);
46717
+ const digest23 = createHash31("sha256").update(`${parsedInput.sourceSystem}:${stableIdentity}`).digest("hex");
46718
+ const crmEntityId = `${digest23.slice(0, 8)}-${digest23.slice(8, 12)}-5${digest23.slice(13, 16)}-${(Number.parseInt(digest23.slice(16, 18), 16) & 63 | 128).toString(16)}${digest23.slice(18, 20)}-${digest23.slice(20, 32)}`;
46641
46719
  rows.push({
46642
46720
  row: rowNumber,
46643
- crmPersonRef: `People::Leads/person-${digest23}`,
46721
+ crmPersonRef: crmEntityId,
46644
46722
  ...displayName ? { displayName } : {},
46645
46723
  ...firstName ? { firstName } : {},
46646
46724
  ...lastName ? { lastName } : {},
@@ -48410,9 +48488,9 @@ function sanitizeNangoToolDescription(body3, tool) {
48410
48488
  true
48411
48489
  );
48412
48490
  }
48413
- let serializedBytes = Number.POSITIVE_INFINITY;
48491
+ let serializedBytes2 = Number.POSITIVE_INFINITY;
48414
48492
  try {
48415
- serializedBytes = Buffer.byteLength(JSON.stringify(rawTool), "utf8");
48493
+ serializedBytes2 = Buffer.byteLength(JSON.stringify(rawTool), "utf8");
48416
48494
  } catch {
48417
48495
  }
48418
48496
  const name = cleanString3(rawTool.name, 200);
@@ -48427,7 +48505,7 @@ function sanitizeNangoToolDescription(body3, tool) {
48427
48505
  const outputSchema = outputSchemaValue === void 0 ? void 0 : sanitizeToolSchema(outputSchemaValue);
48428
48506
  const blockedReasonValue = rawTool.blockedReason ?? rawTool.blocked_reason;
48429
48507
  const blockedReason = blockedReasonValue === null || blockedReasonValue === void 0 ? null : blockedReasonValue === "actions_disabled" || blockedReasonValue === "inactive_connection" || blockedReasonValue === "missing_permission" || blockedReasonValue === "missing_app_feature" || blockedReasonValue === "permission_policy_missing" || blockedReasonValue === "permission_verification_unavailable" ? blockedReasonValue : void 0;
48430
- if (serializedBytes > 256 * 1024 || !name || name !== tool || classification !== "read" && classification !== "action" || typeof rawTool.callable !== "boolean" || blockedReason === void 0 || transport !== "nango" && transport !== "remote_mcp" || !providerConfigKey || schemaSource !== "live_tools_list" || !upstreamSchemaHash || !/^[a-f0-9]{64}$/i.test(upstreamSchemaHash) || !fetchedAt || Number.isNaN(Date.parse(fetchedAt)) || !inputSchema || outputSchemaValue !== void 0 && !outputSchema) {
48508
+ if (serializedBytes2 > 256 * 1024 || !name || name !== tool || classification !== "read" && classification !== "action" || typeof rawTool.callable !== "boolean" || blockedReason === void 0 || transport !== "nango" && transport !== "remote_mcp" || !providerConfigKey || schemaSource !== "live_tools_list" || !upstreamSchemaHash || !/^[a-f0-9]{64}$/i.test(upstreamSchemaHash) || !fetchedAt || Number.isNaN(Date.parse(fetchedAt)) || !inputSchema || outputSchemaValue !== void 0 && !outputSchema) {
48431
48509
  throw new NangoControlError(
48432
48510
  "The connection service returned an invalid live tool description.",
48433
48511
  502,
@@ -48567,7 +48645,7 @@ async function callMainOwnedExportPage(identity, input) {
48567
48645
  });
48568
48646
  }
48569
48647
  if (connection.providerConfigKey === "google-mail" && input.dataset === "emails") {
48570
- const { GmailService: GmailService2 } = await import("./gmail-service-BTRAHGJS.js");
48648
+ const { GmailService: GmailService2 } = await import("./gmail-service-BUSU4BVX.js");
48571
48649
  const service = new GmailService2();
48572
48650
  const ownerId3 = createHash32("sha256").update(identity.toLowerCase()).digest("hex").slice(0, 24);
48573
48651
  const after = Math.floor(Date.parse(input.from) / 1e3);
@@ -51927,7 +52005,15 @@ var ANALYTICS_PRIVACY_FIELD_REGISTRY = Object.freeze([
51927
52005
  {
51928
52006
  dataClass: "pseudonymous_identity",
51929
52007
  purpose: "site_analytics",
51930
- fields: ["identity.value_hmac", "session.visitor_hmac", "session.session_hmac", "person.public_ref"],
52008
+ fields: [
52009
+ "identity.value_hmac",
52010
+ "identity.assignment_person_id",
52011
+ "identity.assignment_crm_entity_id",
52012
+ "identity.conflict_person_ids",
52013
+ "session.visitor_hmac",
52014
+ "session.session_hmac",
52015
+ "person.public_ref"
52016
+ ],
51931
52017
  storage: "pseudonymous",
51932
52018
  defaultRetentionDays: 395,
51933
52019
  readSurface: "privacy_export",
@@ -51981,7 +52067,14 @@ var ANALYTICS_PRIVACY_FIELD_REGISTRY = Object.freeze([
51981
52067
  {
51982
52068
  dataClass: "normalized_receipts",
51983
52069
  purpose: "necessary",
51984
- fields: ["ingestion.reason_codes", "webhook.signature_status", "activation.safe_error_category", "crm.safe_error_code"],
52070
+ fields: [
52071
+ "ingestion.reason_codes",
52072
+ "webhook.signature_status",
52073
+ "activation.safe_error_category",
52074
+ "crm.safe_error_code",
52075
+ "form_bridge.opaque_entity_id",
52076
+ "form_bridge.safe_error_code"
52077
+ ],
51985
52078
  storage: "ordinary",
51986
52079
  defaultRetentionDays: 30,
51987
52080
  readSurface: "privacy_export",
@@ -52062,7 +52155,7 @@ var ANALYTICS_PRIVACY_RELATION_REGISTRY = Object.freeze([
52062
52155
  `),
52063
52156
  ...relationPolicies("candidate_evidence", false, "expire", `analytics_runtime_rule_health`),
52064
52157
  ...relationPolicies("pseudonymous_identity", true, "delete", `
52065
- analytics_people analytics_identity_nodes analytics_identity_edges
52158
+ analytics_people analytics_identity_nodes analytics_identity_edges analytics_identity_assignments
52066
52159
  analytics_crm_person_mappings analytics_consent_current_state analytics_consent_receipts analytics_provider_customer_bindings
52067
52160
  `),
52068
52161
  ...relationPolicies("pseudonymous_identity", true, "retain_legal", `analytics_identity_tombstones`),
@@ -52083,12 +52176,13 @@ var ANALYTICS_PRIVACY_RELATION_REGISTRY = Object.freeze([
52083
52176
  analytics_connections analytics_webhook_receipts analytics_linker_tokens analytics_thorbit_connect_states
52084
52177
  `),
52085
52178
  ...relationPolicies("access_audit", true, "anonymize", `
52086
- analytics_identity_profile_access_audits
52179
+ analytics_identity_profile_access_audits analytics_identity_assignment_conflicts
52087
52180
  `),
52088
52181
  ...relationPolicies("normalized_receipts", true, "anonymize", `
52089
52182
  analytics_ingestion_receipts analytics_exports analytics_activation_destination_tests analytics_activation_delivery_attempts
52090
52183
  analytics_crm_provisioning_receipts analytics_crm_sync_receipts analytics_crm_outbound_attempts
52091
52184
  analytics_crm_outbound_receipts analytics_product_milestones analytics_identity_promotion_receipts
52185
+ analytics_form_bridge_receipts
52092
52186
  analytics_runtime_manifest_publications analytics_experiment_receipts
52093
52187
  analytics_revenue_setup_receipts
52094
52188
  `),
@@ -52563,6 +52657,14 @@ async function drainAnalyticsPrivacyLifecycle(input = {}) {
52563
52657
  WHERE id IN (SELECT id FROM analytics_identity_profile_access_audits a WHERE ${policyCutoff("a", "created_at")}
52564
52658
  AND (a.person_id IS NOT NULL OR a.subject_ref_hmac <> md5('retained-audit:'||a.id::text))
52565
52659
  ORDER BY a.created_at LIMIT $4) RETURNING id`);
52660
+ await run("identityAssignmentConflicts", "access_audit", `UPDATE analytics_identity_assignment_conflicts c
52661
+ SET identity_node_id=NULL,active_person_id=NULL,attempted_person_id=NULL,
52662
+ active_crm_entity_id=NULL,attempted_crm_entity_id=NULL,
52663
+ evidence_kind='retained_audit',resolved_at=COALESCE(c.resolved_at,$1)
52664
+ WHERE id IN (SELECT id FROM analytics_identity_assignment_conflicts c
52665
+ WHERE c.status <> 'pending' AND ${policyCutoff("c", "observed_at")}
52666
+ AND (c.identity_node_id IS NOT NULL OR c.active_person_id IS NOT NULL OR c.attempted_person_id IS NOT NULL)
52667
+ ORDER BY c.observed_at LIMIT $4) RETURNING id`);
52566
52668
  await run("webhookPayloads", "provider_secrets", `UPDATE analytics_webhook_receipts SET payload_ciphertext=NULL
52567
52669
  WHERE id IN (SELECT id FROM analytics_webhook_receipts WHERE payload_ciphertext IS NOT NULL AND payload_expires_at <= $1 AND $2::text IS NOT NULL AND $3::int > 0 ORDER BY payload_expires_at LIMIT $4) RETURNING id`);
52568
52670
  await run("linkerTokens", "provider_secrets", `DELETE FROM analytics_linker_tokens l WHERE id IN
@@ -52574,6 +52676,9 @@ async function drainAnalyticsPrivacyLifecycle(input = {}) {
52574
52676
  ORDER BY r.created_at LIMIT $4) RETURNING id`);
52575
52677
  await run("productMilestones", "normalized_receipts", `DELETE FROM analytics_product_milestones m WHERE id IN
52576
52678
  (SELECT id FROM analytics_product_milestones m WHERE ${policyCutoff("m", "occurred_at")} ORDER BY m.occurred_at LIMIT $4) RETURNING id`);
52679
+ await run("formBridgeReceipts", "normalized_receipts", `DELETE FROM analytics_form_bridge_receipts r WHERE id IN
52680
+ (SELECT r.id FROM analytics_form_bridge_receipts r JOIN analytics_form_submissions f ON f.id=r.submission_id
52681
+ WHERE ${joinedPolicyCutoff("r.occurred_at", "f.site_id")} ORDER BY r.occurred_at LIMIT $4) RETURNING id`);
52577
52682
  await run("crmSyncRuns", "delivery_jobs", `DELETE FROM analytics_crm_sync_runs r WHERE sync_id IN
52578
52683
  (SELECT sync_id FROM analytics_crm_sync_runs r WHERE r.state IN ('completed','degraded','cancelled','webhook_only')
52579
52684
  AND ${policyCutoff("r", "created_at")} ORDER BY r.created_at LIMIT $4) RETURNING sync_id`);
@@ -53497,6 +53602,7 @@ var FormSubmissionSchema = z43.object({
53497
53602
  medium: z43.string().trim().max(180).optional(),
53498
53603
  campaign: z43.string().trim().max(240).optional(),
53499
53604
  clickIds: z43.record(z43.string(), z43.string().trim().max(500)).optional(),
53605
+ idempotencyKey: z43.string().trim().min(8).max(200).optional(),
53500
53606
  placementUrl: z43.string().url().max(3e3),
53501
53607
  website: z43.string().max(0).optional()
53502
53608
  }).strict();
@@ -53805,7 +53911,7 @@ function renderPublicForm(form, placementUrl) {
53805
53911
  return `<label${field.type === "checkbox" ? ' class="check"' : ""}><span>${escapeHtml7(field.label)}${field.required ? " *" : ""}</span>${control}</label>`;
53806
53912
  }).join("");
53807
53913
  const brand = form.brand;
53808
- return `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><style>:root{font-family:ui-sans-serif,system-ui;color:${escapeHtml7(brand.textColor)};background:${escapeHtml7(brand.backgroundColor)}}*{box-sizing:border-box}body{margin:0;padding:18px}form{display:grid;gap:14px}label{display:grid;gap:6px;font-size:13px;font-weight:650}.check{grid-template-columns:auto 1fr;align-items:center}.check span{grid-column:2}.check input{grid-column:1;grid-row:1}input,textarea,select{width:100%;min-height:44px;padding:10px 12px;border:1px solid #ccd3df;border-radius:${brand.radius}px;background:white;color:inherit;font:inherit}textarea{min-height:110px;resize:vertical}button{min-height:46px;border:0;border-radius:${brand.radius}px;color:white;background:${escapeHtml7(brand.primaryColor)};font:inherit;font-weight:750;cursor:pointer}.consent{margin:0;color:#667085;font-size:11px;line-height:1.45}.notice{display:none;padding:12px;border-radius:${brand.radius}px;background:#edf8f2;color:#17613c}.hp{position:absolute!important;left:-9999px!important}</style></head><body><form id="mcp-form">${fields}<label class="hp">Website<input name="website" autocomplete="off" tabindex="-1"></label>${form.consent_text ? `<p class="consent">${escapeHtml7(form.consent_text)}</p>` : ""}<button>${escapeHtml7(form.submit_label)}</button><div class="notice" role="status"></div></form><script>(()=>{const form=document.querySelector('#mcp-form'),notice=form.querySelector('.notice'),q=new URLSearchParams(location.search);form.addEventListener('submit',async event=>{event.preventDefault();const button=form.querySelector('button');button.disabled=true;const raw=Object.fromEntries(new FormData(form).entries()),website=String(raw.website||''),clickIds={};delete raw.website;for(const k of ['fbclid','gclid','gbraid','wbraid','ttclid','rdt_cid','msclkid']){const v=q.get(k);if(v)clickIds[k]=v}try{const response=await fetch('/analytics/forms/${escapeHtml7(form.public_id)}/submissions',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({data:raw,website,placementUrl:${JSON.stringify(placementUrl)},visitorId:q.get('visitor')||undefined,sessionId:q.get('session')||undefined,source:q.get('source')||undefined,medium:q.get('medium')||undefined,campaign:q.get('campaign')||undefined,clickIds})});if(!response.ok)throw new Error('submit');notice.textContent=${JSON.stringify(form.success_message)};notice.style.display='block';form.reset();${form.redirect_url ? `setTimeout(()=>{top.location.href=${JSON.stringify(form.redirect_url)}},700);` : ""}}catch{notice.textContent='Your response could not be submitted. Please try again.';notice.style.display='block'}finally{button.disabled=false}})})()</script></body></html>`;
53914
+ return `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><style>:root{font-family:ui-sans-serif,system-ui;color:${escapeHtml7(brand.textColor)};background:${escapeHtml7(brand.backgroundColor)}}*{box-sizing:border-box}body{margin:0;padding:18px}form{display:grid;gap:14px}label{display:grid;gap:6px;font-size:13px;font-weight:650}.check{grid-template-columns:auto 1fr;align-items:center}.check span{grid-column:2}.check input{grid-column:1;grid-row:1}input,textarea,select{width:100%;min-height:44px;padding:10px 12px;border:1px solid #ccd3df;border-radius:${brand.radius}px;background:white;color:inherit;font:inherit}textarea{min-height:110px;resize:vertical}button{min-height:46px;border:0;border-radius:${brand.radius}px;color:white;background:${escapeHtml7(brand.primaryColor)};font:inherit;font-weight:750;cursor:pointer}.consent{margin:0;color:#667085;font-size:11px;line-height:1.45}.notice{display:none;padding:12px;border-radius:${brand.radius}px;background:#edf8f2;color:#17613c}.hp{position:absolute!important;left:-9999px!important}</style></head><body><form id="mcp-form">${fields}<label class="hp">Website<input name="website" autocomplete="off" tabindex="-1"></label>${form.consent_text ? `<p class="consent">${escapeHtml7(form.consent_text)}</p>` : ""}<button>${escapeHtml7(form.submit_label)}</button><div class="notice" role="status"></div></form><script>(()=>{const form=document.querySelector('#mcp-form'),notice=form.querySelector('.notice'),q=new URLSearchParams(location.search),id=()=>crypto.randomUUID?crypto.randomUUID():'form_'+Date.now().toString(36)+Math.random().toString(36).slice(2);let pendingKey=null;form.addEventListener('submit',async event=>{event.preventDefault();const button=form.querySelector('button');button.disabled=true;pendingKey=pendingKey||id();const raw=Object.fromEntries(new FormData(form).entries()),website=String(raw.website||''),clickIds={};delete raw.website;for(const k of ['fbclid','gclid','gbraid','wbraid','ttclid','rdt_cid','msclkid']){const v=q.get(k);if(v)clickIds[k]=v}try{const response=await fetch('/analytics/forms/${escapeHtml7(form.public_id)}/submissions',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({data:raw,website,idempotencyKey:pendingKey,placementUrl:${JSON.stringify(placementUrl)},visitorId:q.get('visitor')||undefined,sessionId:q.get('session')||undefined,source:q.get('source')||undefined,medium:q.get('medium')||undefined,campaign:q.get('campaign')||undefined,clickIds})});if(!response.ok)throw new Error('submit');pendingKey=null;notice.textContent=${JSON.stringify(form.success_message)};notice.style.display='block';form.reset();${form.redirect_url ? `setTimeout(()=>{top.location.href=${JSON.stringify(form.redirect_url)}},700);` : ""}}catch{notice.textContent='Your response could not be submitted. Please try again.';notice.style.display='block'}finally{button.disabled=false}})})()</script></body></html>`;
53809
53915
  }
53810
53916
  analyticsApp.get(
53811
53917
  "/health/live",
@@ -54212,163 +54318,64 @@ analyticsApp.post("/forms/:publicId/submissions", async (c) => {
54212
54318
  for (const field of allowed.values())
54213
54319
  if (field.required && (parsed.data.data[field.id] === void 0 || parsed.data.data[field.id] === ""))
54214
54320
  return c.json({ ok: false, error: `${field.label} is required.` }, 400);
54215
- const user = await getUserById(form.owner_user_id);
54216
- if (!user)
54217
- return c.json({ ok: false, error: "Form owner unavailable." }, 503);
54218
54321
  const data = parsed.data.data;
54219
54322
  const email = typeof data.email === "string" ? data.email.trim().toLowerCase() : "";
54220
54323
  const phone = typeof data.phone === "string" ? data.phone.trim() : "";
54221
54324
  const firstName = typeof data.first_name === "string" ? data.first_name.trim() : "";
54222
54325
  const lastName = typeof data.last_name === "string" ? data.last_name.trim() : "";
54223
- const fullName = [firstName, lastName].filter(Boolean).join(" ") || (typeof data.name === "string" ? data.name.trim() : "") || email || "Website lead";
54224
- const identitySeed = email || phone.replace(/\D/g, "") || randomUUID38();
54225
- const suffix2 = createHash43("sha256").update(identitySeed).digest("hex").slice(0, 12);
54226
- const path5 = `Leads/person-${suffix2}`;
54227
- const crmPersonRef = `People::${path5}`;
54228
- const { key: memoryKey, error: memoryKeyError } = await getOrCreateUserMemoryKey(user);
54229
- const existing = memoryKey ? await memoryCall("getTool", { vault: "People", path: path5 }, memoryKey) : { ok: false, error: memoryKeyError || "memory_credential_unavailable" };
54230
- const props = {
54231
- ...existing.note?.props ?? {},
54232
- type: "person",
54233
- status: "active",
54234
- person_name: fullName,
54235
- ...firstName ? { first_name: firstName } : {},
54236
- ...lastName ? { last_name: lastName } : {},
54237
- ...email ? { email } : {},
54238
- ...typeof data.phone === "string" && data.phone.trim() ? { phone: data.phone.trim(), text_phone: data.phone.trim() } : {},
54239
- ...typeof data.company === "string" && data.company.trim() ? { company: data.company.trim() } : {},
54240
- attribution_site_id: form.site_id,
54241
- attribution_form_id: form.id,
54242
- attribution_form_name: form.name,
54243
- attributed_source: parsed.data.source || "(direct)",
54244
- attributed_medium: parsed.data.medium || "(none)",
54245
- attributed_campaign: parsed.data.campaign || "(none)",
54246
- form_fields: data,
54247
- source_type: "analytics_form",
54248
- source_ref: `form:${form.public_id}`,
54249
- summary: `Website lead from ${form.name}`,
54250
- embedding_summary: `${fullName} submitted ${form.name}`,
54251
- related: [],
54252
- related_vault_notes: [],
54253
- embed: true,
54254
- embed_priority: "normal"
54255
- };
54256
- const crmPayload = {
54257
- vault: "People",
54258
- path: path5,
54259
- title: fullName,
54260
- content: existing.note?.content || `# ${fullName}
54261
-
54262
- ## Identity
54263
- Website lead captured through ${form.name}.
54264
-
54265
- ## Relationship
54266
- Attribution is linked to Site Analytics.
54267
-
54268
- ## Known Context
54269
- Submitted the published form.
54270
-
54271
- ## Interaction History
54272
- - ${(/* @__PURE__ */ new Date()).toISOString()}: Form submitted.
54273
-
54274
- ## Open Loops
54275
- - Review and follow up.`,
54276
- props,
54277
- ...existing.note ? { baseRevision: existing.note.revision } : {}
54278
- };
54279
- const saved = memoryKey ? await memoryCall(
54280
- "putTool",
54281
- crmPayload,
54282
- memoryKey
54283
- ) : { ok: false, error: memoryKeyError || "memory_credential_unavailable" };
54284
- const crmDeliveryStatus = saved.ok ? "delivered" : "pending";
54285
- const receipt4 = await recordAnalyticsFormSubmission({
54326
+ const fullName = [firstName, lastName].filter(Boolean).join(" ") || (typeof data.name === "string" ? data.name.trim() : "") || "Website visitor";
54327
+ const idempotencyKey4 = parsed.data.idempotencyKey ?? randomUUID38();
54328
+ const identitySeed = email || phone.replace(/\D/g, "") || parsed.data.visitorId || parsed.data.sessionId || idempotencyKey4;
54329
+ const crmEntityId = deterministicAnalyticsCrmEntityId(form.site_id, identitySeed);
54330
+ const observedAt = (/* @__PURE__ */ new Date()).toISOString();
54331
+ const bridge = await queueAnalyticsFormBridgeTransaction({
54286
54332
  form,
54333
+ ownerUserId: form.owner_user_id,
54334
+ idempotencyKey: idempotencyKey4,
54335
+ crmEntityId,
54287
54336
  visitorId: parsed.data.visitorId,
54288
54337
  sessionId: parsed.data.sessionId,
54289
- crmPersonRef,
54290
- crmDeliveryStatus,
54291
54338
  source: parsed.data.source,
54292
54339
  medium: parsed.data.medium,
54293
54340
  campaign: parsed.data.campaign,
54294
- clickIds: parsed.data.clickIds
54295
- });
54296
- const identityGraph = await linkAnalyticsFormIdentity({
54297
- submissionId: receipt4.submissionId,
54298
- siteId: form.site_id,
54299
- crmPersonRef,
54300
- visitorId: parsed.data.visitorId,
54301
- sessionId: parsed.data.sessionId,
54302
- email: email || void 0,
54303
- phone: phone || void 0,
54304
- displayName: [typeof data.first_name === "string" ? data.first_name : "", typeof data.last_name === "string" ? data.last_name : ""].filter(Boolean).join(" ") || void 0,
54305
- evidenceType: "first_party_form",
54306
- clickIds: parsed.data.clickIds
54307
- });
54308
- if (!saved.ok) {
54309
- await queueAnalyticsFormDelivery({
54310
- submissionId: receipt4.submissionId,
54311
- ownerUserId: form.owner_user_id,
54312
- payloadCiphertext: encryptMemoryKey(JSON.stringify(crmPayload)),
54313
- errorCode: memoryKey ? "memory_write_failed" : "memory_credential_unavailable"
54314
- });
54315
- }
54316
- const match = {
54317
- ...email ? { emailSha256: createHash43("sha256").update(email).digest("hex") } : {},
54318
- ...phone ? {
54319
- phoneSha256: createHash43("sha256").update(phone.replace(/\D/g, "")).digest("hex")
54320
- } : {}
54321
- };
54322
- const conversionOccurredAt = (/* @__PURE__ */ new Date()).toISOString();
54323
- const activationIdentity = await resolveAnalyticsConfirmedActivationIdentity(getAnalyticsPool(), {
54324
- siteId: form.site_id,
54325
- subjectRef: parsed.data.visitorId,
54326
- personId: identityGraph.personId
54327
- });
54328
- const conversion = await createAnalyticsConversion({
54329
- userId: form.owner_user_id,
54330
- siteId: form.site_id,
54331
- pixelId: form.pixel_id,
54332
- sessionId: parsed.data.sessionId,
54333
- sourceEventId: `form:${receipt4.submissionId}`,
54334
- conversionKind: "form_submitted",
54335
- occurredAt: conversionOccurredAt,
54336
- personId: activationIdentity.personId ?? void 0,
54337
- activationPayloadCiphertext: activationIdentity.activationEligible && activationIdentity.personId ? encryptAnalyticsRestricted(
54338
- JSON.stringify({
54339
- eventId: `form:${receipt4.submissionId}`,
54340
- eventName: "form_submitted",
54341
- eventTime: conversionOccurredAt,
54342
- actionSource: "website",
54343
- sourceUrl: parsed.data.placementUrl,
54344
- match,
54345
- clickIds: parsed.data.clickIds ?? {},
54346
- personId: activationIdentity.personId,
54347
- identityTier: "confirmed",
54348
- consent: { advertisingMeasurement: true },
54349
- attribution: {
54350
- source: parsed.data.source,
54351
- medium: parsed.data.medium,
54352
- campaign: parsed.data.campaign
54353
- }
54354
- }),
54355
- "activation-payload"
54356
- ) : void 0
54341
+ clickIds: parsed.data.clickIds,
54342
+ occurredAt: observedAt,
54343
+ payloadCiphertext: encryptMemoryKey(JSON.stringify({
54344
+ displayName: fullName,
54345
+ relationshipTypes: ["prospect"],
54346
+ email: email || void 0,
54347
+ phone: phone || void 0,
54348
+ organizationName: typeof data.company === "string" && data.company.trim() ? data.company.trim() : void 0,
54349
+ submittedFields: data,
54350
+ visitorId: parsed.data.visitorId,
54351
+ sessionId: parsed.data.sessionId,
54352
+ clickIds: parsed.data.clickIds ?? {},
54353
+ placementUrl: parsed.data.placementUrl,
54354
+ source: {
54355
+ kind: "xray_form",
54356
+ siteId: form.site_id,
54357
+ formId: form.id,
54358
+ observedAt
54359
+ }
54360
+ }))
54357
54361
  });
54358
54362
  return c.json(
54359
54363
  {
54360
54364
  ok: true,
54361
- submissionId: receipt4.submissionId,
54362
- crmDeliveryStatus,
54363
- attribution: {
54364
- personId: identityGraph.personId,
54365
- linkedSignals: identityGraph.linkedSignals
54365
+ submissionId: bridge.submissionId,
54366
+ crmDeliveryStatus: "pending",
54367
+ bridge: {
54368
+ runId: bridge.bridgeRunId,
54369
+ crmEntityId: bridge.crmEntityId,
54370
+ analyticsStatus: "delivered",
54371
+ crmStatus: "pending"
54366
54372
  },
54367
- activation: { queuedDestinations: conversion.queuedDestinations },
54373
+ conversion: { id: bridge.conversionId, status: "recorded" },
54374
+ activation: { status: "pending_identity_delivery" },
54368
54375
  message: form.success_message,
54369
54376
  redirectUrl: form.redirect_url
54370
54377
  },
54371
- saved.ok ? 201 : 202
54378
+ 202
54372
54379
  );
54373
54380
  });
54374
54381
  analyticsApp.get("/l/:shortCode", async (c) => {
@@ -56579,6 +56586,13 @@ analyticsApp.post("/sites/:siteId/identity-namespaces/:namespaceId/candidates/:a
56579
56586
  });
56580
56587
  return c.json({ ok: true, promotion }, 200, noStore);
56581
56588
  });
56589
+ analyticsApp.use("/sites/:siteId/crm/*", auth4, async (c) => c.json({
56590
+ ok: false,
56591
+ error: {
56592
+ code: "crm_provider_unavailable",
56593
+ message: "External CRM provider setup and synchronization are unavailable. Use the provider-neutral /crm workspace and GET /crm/connections."
56594
+ }
56595
+ }, 410));
56582
56596
  analyticsApp.get("/sites/:siteId/crm/capabilities", auth4, async (c) => {
56583
56597
  await requireSite(c);
56584
56598
  const providers = ANALYTICS_PUBLIC_CRM_PROVIDER_IDS.map((provider) => ({
@@ -57486,6 +57500,640 @@ analyticsApp.onError((error, c) => {
57486
57500
  );
57487
57501
  });
57488
57502
 
57503
+ // src/api/governed-relationship-routes.ts
57504
+ import { randomUUID as randomUUID39 } from "crypto";
57505
+ import { Hono as Hono37 } from "hono";
57506
+ import { z as z45 } from "zod";
57507
+
57508
+ // src/api/entity-domain-contract.ts
57509
+ var DOMAIN_VAULT_NAMES = Object.freeze({
57510
+ research_person: "People",
57511
+ research_organization: "Organizations",
57512
+ crm_person: "CRM People",
57513
+ crm_organization: "CRM Organizations"
57514
+ });
57515
+ var RESEARCH_FORBIDDEN_FIELDS = Object.freeze([
57516
+ "relationshipTypes",
57517
+ "relationship_types",
57518
+ "commercialLifecycle",
57519
+ "commercial_lifecycle",
57520
+ "relationshipStatus",
57521
+ "relationship_status",
57522
+ "ownerId",
57523
+ "owner_id",
57524
+ "consentState",
57525
+ "consent_state",
57526
+ "outreachState",
57527
+ "outreach_state",
57528
+ "pipelineId",
57529
+ "pipeline_id",
57530
+ "dealIds",
57531
+ "deal_ids",
57532
+ "taskIds",
57533
+ "task_ids",
57534
+ "nextTaskId",
57535
+ "next_task_id",
57536
+ "openDealValue",
57537
+ "open_deal_value"
57538
+ ]);
57539
+ var CRM_FORBIDDEN_FIELDS = Object.freeze([
57540
+ "claims",
57541
+ "citations",
57542
+ "sourceEvidence",
57543
+ "source_evidence",
57544
+ "researchRoles",
57545
+ "research_roles",
57546
+ "timePeriod",
57547
+ "time_period",
57548
+ "topics",
57549
+ "researchSummary",
57550
+ "research_summary"
57551
+ ]);
57552
+ var GovernedContractError = class extends Error {
57553
+ constructor(code, message, status = 422, details = {}) {
57554
+ super(message);
57555
+ this.code = code;
57556
+ this.status = status;
57557
+ this.details = details;
57558
+ this.name = "GovernedContractError";
57559
+ }
57560
+ code;
57561
+ status;
57562
+ details;
57563
+ };
57564
+ var EMAIL_ONLY = /^[^\s@]+@[^\s@]+\.[^\s@]+$/u;
57565
+ var VAULT_REFERENCE = /^(?:[A-Za-z][A-Za-z ]{1,80})::\S+/u;
57566
+ var FILE_EXTENSION = /\.(?:md|mdx|txt|json|csv|pdf|docx?|html?|ya?ml)$/iu;
57567
+ var WINDOWS_PATH = /^(?:[A-Za-z]:\\|\\\\)/u;
57568
+ var POSIX_PATH = /^(?:\.{0,2}\/|\/|~\/)/u;
57569
+ function displayNameIssue(value) {
57570
+ if (typeof value !== "string" || value.trim().length === 0) return "empty";
57571
+ const name = value.trim();
57572
+ if (EMAIL_ONLY.test(name)) return "email";
57573
+ if (VAULT_REFERENCE.test(name)) return "vault_reference";
57574
+ if (WINDOWS_PATH.test(name) || POSIX_PATH.test(name) || name.includes("/")) return "path";
57575
+ if (FILE_EXTENSION.test(name)) return "filename";
57576
+ return null;
57577
+ }
57578
+ function requireHumanDisplayName(value) {
57579
+ const issue = displayNameIssue(value);
57580
+ if (issue) {
57581
+ throw new GovernedContractError(
57582
+ issue === "empty" ? "entity_display_name_required" : "entity_display_name_invalid",
57583
+ issue === "empty" ? "A human display name is required." : `A ${issue.replace("_", " ")} may be retained as a locator, but cannot be the display name.`,
57584
+ 422,
57585
+ { issue }
57586
+ );
57587
+ }
57588
+ return value.trim();
57589
+ }
57590
+
57591
+ // src/api/crm-contract.ts
57592
+ var XRAY_ATTRIBUTION_MODELS = [
57593
+ "first_touch",
57594
+ "last_touch",
57595
+ "last_non_direct",
57596
+ "linear",
57597
+ "time_decay",
57598
+ "position_based",
57599
+ "custom_weighted"
57600
+ ];
57601
+ var DEFAULT_XRAY_ATTRIBUTION = Object.freeze({
57602
+ model: "position_based",
57603
+ firstWeight: 0.4,
57604
+ middleWeight: 0.2,
57605
+ lastWeight: 0.4
57606
+ });
57607
+
57608
+ // src/api/crm-import-service.ts
57609
+ import { z as z44 } from "zod";
57610
+ var MAX_IMPORT_BYTES = 20 * 1024 * 1024;
57611
+ var ImportRowSchema = z44.object({
57612
+ rowNumber: z44.number().int().min(1),
57613
+ domain: z44.enum(["crm_person", "crm_organization"]),
57614
+ values: z44.record(z44.string().min(1).max(120), z44.unknown())
57615
+ }).strict();
57616
+ var CrmImportPreviewSchema = z44.object({
57617
+ idempotencyKey: z44.string().min(8).max(200),
57618
+ ttlMinutes: z44.number().int().min(5).max(1440).default(60),
57619
+ mapping: z44.record(z44.string().min(1).max(120), z44.string().min(1).max(120)),
57620
+ rows: z44.array(ImportRowSchema).min(1).max(5e4)
57621
+ }).strict();
57622
+ var CrmImportApplySchema = z44.object({
57623
+ planHandle: z44.string().min(1).max(4096),
57624
+ digest: z44.string().regex(/^[a-f0-9]{64}$/iu),
57625
+ confirmationToken: z44.string().min(8).max(500),
57626
+ idempotencyKey: z44.string().min(8).max(200)
57627
+ }).strict();
57628
+ function serializedBytes(value) {
57629
+ return Buffer.byteLength(JSON.stringify(value), "utf8");
57630
+ }
57631
+ function parseCrmImportPreview(value) {
57632
+ if (serializedBytes(value) > MAX_IMPORT_BYTES) {
57633
+ return { ok: false, code: "crm_import_too_large", message: "The import exceeds the 20 MiB preview limit." };
57634
+ }
57635
+ const parsed = CrmImportPreviewSchema.safeParse(value);
57636
+ if (!parsed.success) {
57637
+ return { ok: false, code: "crm_import_invalid", message: "Import rows must use the strict CRM People or CRM Organizations preview contract." };
57638
+ }
57639
+ return { ok: true, input: parsed.data };
57640
+ }
57641
+ function parseCrmImportApply(value) {
57642
+ const parsed = CrmImportApplySchema.safeParse(value);
57643
+ if (!parsed.success) {
57644
+ return { ok: false, code: "crm_import_confirmation_invalid", message: "Import apply requires the exact preview handle, digest, confirmation token, and idempotency key." };
57645
+ }
57646
+ return { ok: true, input: parsed.data };
57647
+ }
57648
+
57649
+ // src/api/governed-relationship-routes.ts
57650
+ var UuidSchema = z45.string().uuid();
57651
+ var ObjectSchema = z45.enum(["people", "organizations"]);
57652
+ var QuerySchema = z45.object({
57653
+ query: z45.string().trim().max(300).optional(),
57654
+ cursor: z45.string().max(2e3).optional(),
57655
+ limit: z45.coerce.number().int().min(1).max(100).default(25)
57656
+ }).passthrough();
57657
+ var MutationSchema = z45.object({
57658
+ idempotencyKey: z45.string().min(8).max(200),
57659
+ baseRevision: z45.number().int().min(0)
57660
+ }).passthrough();
57661
+ var WorkPageSchema = z45.object({ cursor: z45.string().max(2048).optional(), limit: z45.coerce.number().int().min(1).max(100).default(25) }).passthrough();
57662
+ var DealQuerySchema = WorkPageSchema.extend({
57663
+ pipelineId: z45.string().uuid().optional(),
57664
+ stageId: z45.string().uuid().optional(),
57665
+ minValue: z45.coerce.number().nonnegative().optional(),
57666
+ maxValue: z45.coerce.number().nonnegative().optional()
57667
+ });
57668
+ var TaskQuerySchema = WorkPageSchema.extend({
57669
+ query: z45.string().trim().max(300).optional(),
57670
+ personEntityId: z45.string().uuid().optional(),
57671
+ organizationEntityId: z45.string().uuid().optional(),
57672
+ dealId: z45.string().uuid().optional(),
57673
+ due: z45.enum(["overdue", "today", "week", "unscheduled"]).optional(),
57674
+ ownerId: z45.string().trim().max(200).optional(),
57675
+ status: z45.enum(["todo", "in_progress", "blocked", "done", "cancelled"]).optional()
57676
+ });
57677
+ var PipelineMutationSchema = z45.object({
57678
+ pipelineId: z45.string().uuid().optional(),
57679
+ label: z45.string().trim().min(1).max(120),
57680
+ baseVersion: z45.number().int().min(0),
57681
+ isDefault: z45.boolean().default(false),
57682
+ stages: z45.array(z45.object({
57683
+ stageId: z45.string().uuid().optional(),
57684
+ label: z45.string().trim().min(1).max(120),
57685
+ outcome: z45.enum(["open", "won", "lost"]),
57686
+ probability: z45.number().min(0).max(1),
57687
+ requiredFields: z45.array(z45.string().trim().min(1).max(120)).max(100).default([]),
57688
+ allowedNextStageIds: z45.array(z45.string().uuid()).max(100).default([])
57689
+ }).strict()).min(2).max(100)
57690
+ }).strict();
57691
+ var researchTools = {
57692
+ people: { search: "researchPersonSearchTool", get: "researchPersonGetTool", write: "researchPersonCaptureTool" },
57693
+ organizations: { search: "researchOrganizationSearchTool", get: "researchOrganizationGetTool", write: "researchOrganizationCaptureTool" }
57694
+ };
57695
+ var crmTools = {
57696
+ people: { search: "crmPersonSearchTool", get: "crmPersonGetTool", write: "crmUpsertPersonTool" },
57697
+ organizations: { search: "crmOrganizationSearchTool", get: "crmOrganizationGetTool", write: "crmUpsertOrganizationTool" }
57698
+ };
57699
+ function safeFailure2(message, code = "relationship_unavailable") {
57700
+ return { ok: false, error: { code, message, requestId: randomUUID39(), retryable: code === "relationship_unavailable" } };
57701
+ }
57702
+ function resultStatus(result3) {
57703
+ const code = String(result3.code ?? "");
57704
+ if (/permission|owner_confirmation/iu.test(code)) return 403;
57705
+ if (/not_found/iu.test(code)) return 404;
57706
+ if (/conflict|digest_mismatch/iu.test(code)) return 409;
57707
+ if (/expired/iu.test(code)) return 410;
57708
+ if (/invalid|forbidden|mismatch|required/iu.test(code)) return 422;
57709
+ return 502;
57710
+ }
57711
+ async function keyFor(c) {
57712
+ const { key: key3, error } = await getOrCreateUserMemoryKey(c.get("user"));
57713
+ if (!key3) return c.json(safeFailure2(error ?? "Memory is unavailable."), 503);
57714
+ return key3;
57715
+ }
57716
+ async function call(c, tool, input, success = 200) {
57717
+ const key3 = await keyFor(c);
57718
+ if (typeof key3 !== "string") return key3;
57719
+ const result3 = await memoryCall(tool, input, key3);
57720
+ c.header("Cache-Control", "private, no-store");
57721
+ if (!result3.ok) {
57722
+ const status = resultStatus(result3);
57723
+ return c.json(safeFailure2(
57724
+ status === 502 ? "The governed relationship service is temporarily unavailable." : String(result3.message ?? result3.error ?? "The request was rejected."),
57725
+ typeof result3.code === "string" ? result3.code : "relationship_unavailable"
57726
+ ), status);
57727
+ }
57728
+ return c.json(result3, success);
57729
+ }
57730
+ async function readResult(c, tool, input) {
57731
+ const key3 = await keyFor(c);
57732
+ if (typeof key3 !== "string") return key3;
57733
+ const result3 = await memoryCall(tool, input, key3);
57734
+ c.header("Cache-Control", "private, no-store");
57735
+ if (!result3.ok) {
57736
+ const status = resultStatus(result3);
57737
+ return c.json(safeFailure2(status === 502 ? "The governed relationship service is temporarily unavailable." : String(result3.message ?? result3.error ?? "The request was rejected."), typeof result3.code === "string" ? result3.code : "relationship_unavailable"), status);
57738
+ }
57739
+ return result3;
57740
+ }
57741
+ function workItems(result3) {
57742
+ return (Array.isArray(result3.items) ? result3.items : []).filter((item) => Boolean(item && typeof item === "object" && typeof item.workId === "string"));
57743
+ }
57744
+ function pageInfo(result3) {
57745
+ const page3 = result3.pageInfo && typeof result3.pageInfo === "object" ? result3.pageInfo : {};
57746
+ return { endCursor: typeof page3.endCursor === "string" ? page3.endCursor : null, hasNextPage: page3.hasNextPage === true };
57747
+ }
57748
+ function stringProp(props, key3) {
57749
+ const value = props[key3];
57750
+ return typeof value === "string" && value.trim() ? value : null;
57751
+ }
57752
+ function numberProp(props, key3) {
57753
+ const value = props[key3];
57754
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
57755
+ }
57756
+ function dealView(item) {
57757
+ const fields = item.dealState?.fields ?? item.props;
57758
+ const partyId = stringProp(fields, "party") ?? item.entities[0]?.entityId ?? "";
57759
+ const party = item.entities.find((entity) => entity.entityId === partyId) ?? item.entities[0];
57760
+ return {
57761
+ dealId: item.workId,
57762
+ title: item.title,
57763
+ pipelineId: item.dealState?.pipelineId ?? stringProp(item.props, "pipeline_id") ?? "",
57764
+ stageId: item.dealState?.stageId ?? stringProp(item.props, "stage_id") ?? "",
57765
+ revision: item.revision,
57766
+ probability: item.dealState?.probability ?? numberProp(item.props, "probability") ?? 0,
57767
+ value: numberProp(item.props, "value"),
57768
+ currency: stringProp(item.props, "currency"),
57769
+ party: { entityId: party?.entityId ?? partyId, kind: party?.domain.endsWith("_organization") ? "organization" : "person", label: party?.displayName ?? partyId },
57770
+ enteredAt: stringProp(fields, "entered_at") ?? item.createdAt,
57771
+ lastActivityAt: stringProp(item.props, "last_activity_at"),
57772
+ nextTask: null,
57773
+ influencedSource: stringProp(item.props, "influenced_source") ? { label: stringProp(item.props, "influenced_source"), evidenceRef: stringProp(item.props, "influenced_evidence_ref") } : null,
57774
+ fields
57775
+ };
57776
+ }
57777
+ function taskView(item) {
57778
+ const person = item.entities.find((entity) => entity.domain === "crm_person");
57779
+ const organization = item.entities.find((entity) => entity.domain === "crm_organization");
57780
+ const dealId = stringProp(item.props, "deal_id");
57781
+ return {
57782
+ taskId: item.workId,
57783
+ title: item.title,
57784
+ status: stringProp(item.props, "status") ?? "todo",
57785
+ dueAt: stringProp(item.props, "due"),
57786
+ ownerId: stringProp(item.props, "owner_id"),
57787
+ canonicalHref: stringProp(item.props, "canonical_href"),
57788
+ person: person ? { entityId: person.entityId, label: person.displayName } : null,
57789
+ organization: organization ? { entityId: organization.entityId, label: organization.displayName } : null,
57790
+ deal: dealId ? { dealId, title: stringProp(item.props, "deal_title") ?? dealId } : null,
57791
+ sourceLabel: stringProp(item.props, "source_label") ?? "Canonical Tasks",
57792
+ updatedAt: item.updatedAt
57793
+ };
57794
+ }
57795
+ function parsedObject(c) {
57796
+ const parsed = ObjectSchema.safeParse(c.req.param("object"));
57797
+ return parsed.success ? parsed.data : null;
57798
+ }
57799
+ function stripRelationshipDeploymentQuery(query) {
57800
+ const publicQuery = { ...query };
57801
+ delete publicQuery.researchSubpath;
57802
+ delete publicQuery.crmSubpath;
57803
+ return publicQuery;
57804
+ }
57805
+ var researchApp = new Hono37();
57806
+ researchApp.use("*", createApiKeyAuth());
57807
+ for (const object2 of ["people", "organizations"]) {
57808
+ researchApp.get(`/${object2}`, async (c) => {
57809
+ const query = QuerySchema.safeParse(stripRelationshipDeploymentQuery(c.req.query()));
57810
+ if (!query.success) return c.json(safeFailure2("The Research filters are invalid.", "invalid_request"), 400);
57811
+ return call(c, researchTools[object2].search, query.data);
57812
+ });
57813
+ researchApp.post(`/${object2}`, async (c) => {
57814
+ const body3 = MutationSchema.safeParse(await c.req.json().catch(() => null));
57815
+ if (!body3.success) return c.json(safeFailure2("Research capture requires revision and idempotency.", "invalid_request"), 400);
57816
+ try {
57817
+ requireHumanDisplayName(body3.data.displayName);
57818
+ } catch (error) {
57819
+ return c.json(safeFailure2(error.message, "entity_display_name_invalid"), 422);
57820
+ }
57821
+ return call(c, researchTools[object2].write, body3.data, 201);
57822
+ });
57823
+ }
57824
+ researchApp.get("/:object/:entityId", async (c) => {
57825
+ const object2 = parsedObject(c);
57826
+ const entityId = UuidSchema.safeParse(c.req.param("entityId"));
57827
+ if (!object2 || !entityId.success) return c.json(safeFailure2("The Research record reference is invalid.", "invalid_request"), 400);
57828
+ return call(c, researchTools[object2].get, { entityId: entityId.data });
57829
+ });
57830
+ var crmApp = new Hono37();
57831
+ crmApp.use("*", createApiKeyAuth());
57832
+ crmApp.get("/summary", async (c) => {
57833
+ const generatedAt = (/* @__PURE__ */ new Date()).toISOString();
57834
+ const [activityResult, taskResult, dealResult, peopleResult, organizationResult] = await Promise.all([
57835
+ readResult(c, "crmWorkSearchTool", { objectKind: "activity", limit: 25 }),
57836
+ readResult(c, "crmWorkSearchTool", { objectKind: "task", limit: 100 }),
57837
+ readResult(c, "crmWorkSearchTool", { objectKind: "deal", limit: 100 }),
57838
+ readResult(c, "crmPersonSearchTool", { limit: 100 }),
57839
+ readResult(c, "crmOrganizationSearchTool", { limit: 100 })
57840
+ ]);
57841
+ const failed = [activityResult, taskResult, dealResult, peopleResult, organizationResult].find((result3) => result3 instanceof Response);
57842
+ if (failed instanceof Response) return failed;
57843
+ const activities = workItems(activityResult);
57844
+ const tasks = workItems(taskResult);
57845
+ const dealItems = workItems(dealResult);
57846
+ const deals = dealItems.map(dealView);
57847
+ const people = Array.isArray(peopleResult.items) ? peopleResult.items : [];
57848
+ const organizations = Array.isArray(organizationResult.items) ? organizationResult.items : [];
57849
+ const dueNow = Date.now();
57850
+ const recentActivity = Object.values(activities.reduce((groups, item) => {
57851
+ const occurredAt = stringProp(item.props, "occurred_at") ?? item.updatedAt;
57852
+ const date2 = occurredAt.slice(0, 10);
57853
+ groups[date2] ??= { date: date2, items: [] };
57854
+ const rawKind = stringProp(item.props, "activity_type") ?? "note";
57855
+ const kind = rawKind === "form_submission" ? "form" : rawKind === "calendar_event" ? "calendar" : rawKind === "conversion" ? "conversion" : "communication";
57856
+ groups[date2].items.push({ activityId: item.workId, kind, occurredAt, summary: item.title, sourceLabel: stringProp(item.props, "source_label") ?? "Native CRM", xrayEvidenceRef: stringProp(item.props, "xray_evidence_ref") });
57857
+ return groups;
57858
+ }, {}));
57859
+ return c.json({
57860
+ ok: true,
57861
+ kpis: [
57862
+ { key: "active_relationships", label: "Active relationships", value: people.length + organizations.length, unit: "count" },
57863
+ { key: "open_pipeline", label: "Open pipeline", value: dealItems.filter((deal) => deal.dealState?.outcome === "open").reduce((sum2, deal) => sum2 + (numberProp(deal.props, "value") ?? 0), 0), unit: "currency" },
57864
+ { key: "followups_due", label: "Follow-ups due", value: tasks.filter((task) => {
57865
+ const due = stringProp(task.props, "due");
57866
+ return Boolean(due && Date.parse(due) <= dueNow && !["done", "cancelled"].includes(stringProp(task.props, "status") ?? "todo"));
57867
+ }).length, unit: "count" },
57868
+ { key: "xray_revenue", label: "X-Ray revenue", value: 0, unit: "currency" }
57869
+ ],
57870
+ visuals: [
57871
+ { key: "source_revenue", model: DEFAULT_XRAY_ATTRIBUTION.model, evidenceClass: "observed", unit: "currency", rows: [] },
57872
+ { key: "pipeline_velocity", model: null, evidenceClass: null, unit: "days", rows: [] },
57873
+ { key: "lifecycle_movement", model: null, evidenceClass: null, unit: "count", rows: [] },
57874
+ { key: "data_health", model: null, evidenceClass: null, unit: "count", rows: [] }
57875
+ ],
57876
+ qualityCounts: {},
57877
+ recentActivity,
57878
+ activityPageInfo: pageInfo(activityResult),
57879
+ freshness: { generatedAt, sourceRevision: "memory-live", xrayObservedAt: null },
57880
+ xray: { state: "unavailable", reason: "No X-Ray site context was selected. CRM remains available." }
57881
+ });
57882
+ });
57883
+ for (const object2 of ["people", "organizations"]) {
57884
+ crmApp.get(`/${object2}`, async (c) => {
57885
+ const query = QuerySchema.safeParse(stripRelationshipDeploymentQuery(c.req.query()));
57886
+ if (!query.success) return c.json(safeFailure2("The CRM filters are invalid.", "invalid_request"), 400);
57887
+ return call(c, crmTools[object2].search, query.data);
57888
+ });
57889
+ crmApp.post(`/${object2}`, async (c) => {
57890
+ const body3 = MutationSchema.safeParse(await c.req.json().catch(() => null));
57891
+ if (!body3.success) return c.json(safeFailure2("CRM creation requires revision and idempotency.", "invalid_request"), 400);
57892
+ try {
57893
+ requireHumanDisplayName(body3.data.displayName);
57894
+ } catch (error) {
57895
+ return c.json(safeFailure2(error.message, "entity_display_name_invalid"), 422);
57896
+ }
57897
+ if (!Array.isArray(body3.data.relationshipTypes) || body3.data.relationshipTypes.length === 0) {
57898
+ return c.json(safeFailure2("At least one relationship type is required.", "crm_relationship_type_required"), 422);
57899
+ }
57900
+ return call(c, crmTools[object2].write, body3.data, 201);
57901
+ });
57902
+ }
57903
+ crmApp.get("/connections", (c) => {
57904
+ c.header("Cache-Control", "private, no-store");
57905
+ return c.json({
57906
+ ok: true,
57907
+ capabilities: [
57908
+ { capabilityId: "external_crm_sync", state: "unavailable", reason: "No external CRM provider has passed the release readiness contract.", providerMutationAvailable: false, publicTools: [] },
57909
+ { capabilityId: "payment_enrichment", state: "unproven", reason: "Stripe is not part of the native CRM release.", providerMutationAvailable: false, publicTools: [] }
57910
+ ],
57911
+ freshness: { generatedAt: (/* @__PURE__ */ new Date()).toISOString(), sourceRevision: "provider-neutral-v1", xrayObservedAt: null }
57912
+ });
57913
+ });
57914
+ crmApp.get("/deals", async (c) => {
57915
+ const query = DealQuerySchema.safeParse(c.req.query());
57916
+ if (!query.success || query.data.minValue != null && query.data.maxValue != null && query.data.minValue > query.data.maxValue) return c.json(safeFailure2("The deal filters are invalid.", "invalid_request"), 400);
57917
+ const result3 = await readResult(c, "crmWorkSearchTool", {
57918
+ objectKind: "deal",
57919
+ cursor: query.data.cursor,
57920
+ limit: query.data.limit,
57921
+ pipelineId: query.data.pipelineId,
57922
+ stageIds: query.data.stageId ? [query.data.stageId] : void 0,
57923
+ minValue: query.data.minValue,
57924
+ maxValue: query.data.maxValue
57925
+ });
57926
+ if (result3 instanceof Response) return result3;
57927
+ const pipelines = await readResult(c, "crmPipelineListTool", {});
57928
+ if (pipelines instanceof Response) return pipelines;
57929
+ return c.json({ ok: true, items: workItems(result3).map(dealView), pipelines: Array.isArray(pipelines.pipelines) ? pipelines.pipelines : [], pageInfo: pageInfo(result3), freshness: { generatedAt: (/* @__PURE__ */ new Date()).toISOString(), sourceRevision: "memory-live" } });
57930
+ });
57931
+ crmApp.get("/deals/:dealId", async (c) => {
57932
+ const dealId = UuidSchema.safeParse(c.req.param("dealId"));
57933
+ if (!dealId.success) return c.json(safeFailure2("The deal reference is invalid.", "invalid_request"), 400);
57934
+ const result3 = await readResult(c, "crmWorkSearchTool", { objectKind: "deal", workId: dealId.data, limit: 1 });
57935
+ if (result3 instanceof Response) return result3;
57936
+ const item = workItems(result3)[0];
57937
+ if (!item) return c.json(safeFailure2("The governed deal was not found.", "entity_not_found"), 404);
57938
+ const pipelines = await readResult(c, "crmPipelineListTool", {});
57939
+ if (pipelines instanceof Response) return pipelines;
57940
+ const pipeline = (Array.isArray(pipelines.pipelines) ? pipelines.pipelines : []).find((value) => Boolean(value && typeof value === "object" && value.pipelineId === item.dealState?.pipelineId));
57941
+ if (!pipeline) return c.json(safeFailure2("The governed pipeline for this deal was not found.", "pipeline_not_found"), 404);
57942
+ const partyId = stringProp(item.dealState?.fields ?? item.props, "party");
57943
+ const [activityResult, taskResult] = await Promise.all([
57944
+ readResult(c, "crmWorkSearchTool", { objectKind: "activity", ...partyId ? { entityId: partyId } : {}, limit: 100 }),
57945
+ readResult(c, "crmWorkSearchTool", { objectKind: "task", dealId: dealId.data, limit: 100 })
57946
+ ]);
57947
+ if (activityResult instanceof Response) return activityResult;
57948
+ if (taskResult instanceof Response) return taskResult;
57949
+ const activity = workItems(activityResult).map((activityItem) => ({
57950
+ activityId: activityItem.workId,
57951
+ occurredAt: stringProp(activityItem.props, "occurred_at") ?? activityItem.updatedAt,
57952
+ summary: activityItem.title,
57953
+ sourceLabel: stringProp(activityItem.props, "source_label") ?? "Native CRM"
57954
+ }));
57955
+ const tasks = workItems(taskResult).map(taskView).map((task) => ({ taskId: task.taskId, title: task.title, status: task.status, dueAt: task.dueAt, canonicalHref: task.canonicalHref }));
57956
+ return c.json({ ok: true, deal: dealView(item), pipeline, activity, tasks });
57957
+ });
57958
+ crmApp.get("/tasks", async (c) => {
57959
+ const query = TaskQuerySchema.safeParse(c.req.query());
57960
+ if (!query.success) return c.json(safeFailure2("The task filters are invalid.", "invalid_request"), 400);
57961
+ const now = /* @__PURE__ */ new Date();
57962
+ const startToday = new Date(now);
57963
+ startToday.setHours(0, 0, 0, 0);
57964
+ const endToday = new Date(startToday);
57965
+ endToday.setDate(endToday.getDate() + 1);
57966
+ const endWeek = new Date(startToday);
57967
+ endWeek.setDate(endWeek.getDate() + 7);
57968
+ const dueAfter = query.data.due === "today" || query.data.due === "week" ? startToday.toISOString() : void 0;
57969
+ const dueBefore = query.data.due === "overdue" ? startToday.toISOString() : query.data.due === "today" ? endToday.toISOString() : query.data.due === "week" ? endWeek.toISOString() : void 0;
57970
+ const entityIds = [query.data.personEntityId, query.data.organizationEntityId].filter((value) => Boolean(value));
57971
+ const result3 = await readResult(c, "crmWorkSearchTool", {
57972
+ objectKind: "task",
57973
+ cursor: query.data.cursor,
57974
+ limit: query.data.limit,
57975
+ query: query.data.query || void 0,
57976
+ entityIds: entityIds.length ? entityIds : void 0,
57977
+ dealId: query.data.dealId,
57978
+ taskOwnerId: query.data.ownerId || void 0,
57979
+ taskStatuses: query.data.status ? [query.data.status] : void 0,
57980
+ dueAfter,
57981
+ dueBefore,
57982
+ dueUnscheduled: query.data.due === "unscheduled" || void 0
57983
+ });
57984
+ if (result3 instanceof Response) return result3;
57985
+ return c.json({ ok: true, items: workItems(result3).map(taskView), pageInfo: pageInfo(result3), facets: {}, authority: "canonical_tasks", freshness: { generatedAt: (/* @__PURE__ */ new Date()).toISOString(), sourceRevision: "memory-live" } });
57986
+ });
57987
+ crmApp.get("/quality/:queue?", (c) => call(c, "crmQualityListTool", { ...c.req.param("queue") ? { queue: c.req.param("queue") } : {} }));
57988
+ crmApp.get("/audit", (c) => {
57989
+ c.header("Cache-Control", "private, no-store");
57990
+ return c.json({ ok: true, items: [], pageInfo: { endCursor: null, hasNextPage: false }, facets: {}, freshness: { generatedAt: (/* @__PURE__ */ new Date()).toISOString(), sourceRevision: "memory-live", xrayObservedAt: null } });
57991
+ });
57992
+ crmApp.get("/pipelines", async (c) => {
57993
+ const result3 = await readResult(c, "crmPipelineListTool", {});
57994
+ if (result3 instanceof Response) return result3;
57995
+ return c.json({ ...result3, freshness: { generatedAt: (/* @__PURE__ */ new Date()).toISOString(), sourceRevision: "memory-live", xrayObservedAt: null } });
57996
+ });
57997
+ crmApp.post("/pipelines", async (c) => {
57998
+ const body3 = PipelineMutationSchema.safeParse(await c.req.json().catch(() => null));
57999
+ if (!body3.success) return c.json(safeFailure2("The native CRM pipeline configuration is invalid.", "invalid_request"), 400);
58000
+ return call(c, "crmPipelineUpsertTool", body3.data, 201);
58001
+ });
58002
+ crmApp.get("/:object/:entityId", async (c) => {
58003
+ const object2 = parsedObject(c);
58004
+ const entityId = UuidSchema.safeParse(c.req.param("entityId"));
58005
+ if (!object2 || !entityId.success) return c.json(safeFailure2("The CRM record reference is invalid.", "invalid_request"), 400);
58006
+ return call(c, crmTools[object2].get, { entityId: entityId.data });
58007
+ });
58008
+ crmApp.patch("/:object/:entityId", async (c) => {
58009
+ const object2 = parsedObject(c);
58010
+ const entityId = UuidSchema.safeParse(c.req.param("entityId"));
58011
+ const body3 = MutationSchema.safeParse(await c.req.json().catch(() => null));
58012
+ if (!object2 || !entityId.success || !body3.success) return c.json(safeFailure2("The CRM update is invalid.", "invalid_request"), 400);
58013
+ return call(c, crmTools[object2].write, { ...body3.data, entityId: entityId.data });
58014
+ });
58015
+ crmApp.get("/people/:entityId/activity", async (c) => {
58016
+ const entityId = UuidSchema.safeParse(c.req.param("entityId"));
58017
+ if (!entityId.success) return c.json(safeFailure2("The CRM record reference is invalid.", "invalid_request"), 400);
58018
+ const query = WorkPageSchema.safeParse(c.req.query());
58019
+ if (!query.success) return c.json(safeFailure2("The CRM activity filters are invalid.", "invalid_request"), 400);
58020
+ const result3 = await readResult(c, "crmWorkSearchTool", { objectKind: "activity", entityId: entityId.data, cursor: query.data.cursor, limit: query.data.limit });
58021
+ if (result3 instanceof Response) return result3;
58022
+ return c.json({ ok: true, items: workItems(result3).map((item) => ({ activityId: item.workId, occurredAt: stringProp(item.props, "occurred_at") ?? item.updatedAt, summary: item.title, sourceLabel: stringProp(item.props, "source_label") ?? "Native CRM", content: item.content })), pageInfo: pageInfo(result3), facets: {}, freshness: { generatedAt: (/* @__PURE__ */ new Date()).toISOString(), sourceRevision: "memory-live" } });
58023
+ });
58024
+ crmApp.get("/people/:entityId/attribution", (c) => {
58025
+ const entityId = UuidSchema.safeParse(c.req.param("entityId"));
58026
+ if (!entityId.success) return c.json(safeFailure2("The CRM record reference is invalid.", "invalid_request"), 400);
58027
+ c.header("Cache-Control", "private, no-store");
58028
+ return c.json({ ok: true, entityId: entityId.data, selectedModel: DEFAULT_XRAY_ATTRIBUTION.model, availableModels: XRAY_ATTRIBUTION_MODELS, observed: [], reported: [], exactPaths: [], originalTouch: null, latestTouch: null, xray: { state: "unavailable", reason: "No stable X-Ray evidence is linked to this CRM record." } });
58029
+ });
58030
+ crmApp.post("/imports/preview", async (c) => {
58031
+ const body3 = parseCrmImportPreview(await c.req.json().catch(() => null));
58032
+ if (!body3.ok) return c.json(safeFailure2(body3.message, body3.code), body3.code === "crm_import_too_large" ? 413 : 400);
58033
+ return call(c, "crmImportPreviewTool", body3.input, 201);
58034
+ });
58035
+ crmApp.post("/imports/:importId/confirm", async (c) => {
58036
+ const importId = UuidSchema.safeParse(c.req.param("importId"));
58037
+ const body3 = parseCrmImportApply(await c.req.json().catch(() => null));
58038
+ if (!importId.success || !body3.ok) return c.json(safeFailure2(body3.ok ? "The import identifier is invalid." : body3.message, body3.ok ? "invalid_request" : body3.code), 400);
58039
+ return call(c, "crmImportApplyTool", { ...body3.input, importId: importId.data });
58040
+ });
58041
+ crmApp.get("/imports/:importId", (c) => c.json({ ok: false, error: { code: "import_status_use_receipt", message: "Use the immutable preview/apply receipt returned by the governed import.", requestId: randomUUID39(), retryable: false } }, 404));
58042
+ crmApp.post("/counterparts/preview", async (c) => {
58043
+ const body3 = MutationSchema.omit({ baseRevision: true }).safeParse(await c.req.json().catch(() => null));
58044
+ if (!body3.success) return c.json(safeFailure2("The counterpart preview is invalid.", "invalid_request"), 400);
58045
+ return call(c, "crmCounterpartPreviewTool", body3.data, 201);
58046
+ });
58047
+ crmApp.post("/counterparts/:planId/apply", async (c) => {
58048
+ const body3 = MutationSchema.omit({ baseRevision: true }).safeParse(await c.req.json().catch(() => null));
58049
+ if (!body3.success) return c.json(safeFailure2("The counterpart apply request is invalid.", "invalid_request"), 400);
58050
+ return call(c, "crmCounterpartApplyTool", { ...body3.data, planId: c.req.param("planId") });
58051
+ });
58052
+ crmApp.post("/merges/preview", async (c) => {
58053
+ const body3 = MutationSchema.omit({ baseRevision: true }).safeParse(await c.req.json().catch(() => null));
58054
+ if (!body3.success) return c.json(safeFailure2("The merge preview is invalid.", "invalid_request"), 400);
58055
+ return call(c, "crmMergePreviewTool", body3.data, 201);
58056
+ });
58057
+ crmApp.post("/merges/:mergeId/apply", (c) => c.json(safeFailure2("Merge apply is disabled until owner authorization Q-004 is recorded.", "crm_owner_confirmation_required"), 403));
58058
+ crmApp.post("/deals/:dealId/transitions", async (c) => {
58059
+ const body3 = MutationSchema.safeParse(await c.req.json().catch(() => null));
58060
+ if (!body3.success) return c.json(safeFailure2("The deal transition is invalid.", "invalid_request"), 400);
58061
+ return call(c, "crmDealTransitionTool", { ...body3.data, dealId: c.req.param("dealId") });
58062
+ });
58063
+
58064
+ // src/api/crm-bridge-service.ts
58065
+ import { createHash as createHash44 } from "crypto";
58066
+ var CrmBridgeError = class extends Error {
58067
+ constructor(code, message) {
58068
+ super(message);
58069
+ this.code = code;
58070
+ this.name = "CrmBridgeError";
58071
+ }
58072
+ code;
58073
+ };
58074
+ function stableChildId(parentId, suffix2) {
58075
+ const bytes2 = Buffer.from(createHash44("sha256").update(`${parentId}:${suffix2}`).digest().subarray(0, 16));
58076
+ bytes2[6] = bytes2[6] & 15 | 80;
58077
+ bytes2[8] = bytes2[8] & 63 | 128;
58078
+ const hex = bytes2.toString("hex");
58079
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
58080
+ }
58081
+ function validateCrmFormBridgePayload(payload) {
58082
+ if (!payload.bridgeRunId || !payload.crmEntityId)
58083
+ throw new CrmBridgeError("bridge_identity_required", "Bridge run and CRM entity IDs are required.");
58084
+ requireHumanDisplayName(payload.displayName);
58085
+ if (payload.relationshipTypes.length === 0)
58086
+ throw new CrmBridgeError("relationship_type_required", "A managed relationship type is required.");
58087
+ if (payload.source.kind !== "xray_form" || !payload.source.siteId || !payload.source.formId || !payload.source.submissionId)
58088
+ throw new CrmBridgeError("bridge_source_invalid", "The X-Ray form source receipt is incomplete.");
58089
+ return payload;
58090
+ }
58091
+ async function applyCrmFormBridge(rawPayload, writer) {
58092
+ const payload = validateCrmFormBridgePayload(rawPayload);
58093
+ const person = await writer.upsertPerson({
58094
+ entityId: payload.crmEntityId,
58095
+ idempotencyKey: `${payload.bridgeRunId}:person`,
58096
+ displayName: payload.displayName,
58097
+ relationshipTypes: [...payload.relationshipTypes],
58098
+ email: payload.email,
58099
+ phone: payload.phone,
58100
+ organizationName: payload.organizationName,
58101
+ source: payload.source
58102
+ });
58103
+ if (person.entityId !== payload.crmEntityId)
58104
+ throw new CrmBridgeError("crm_entity_identity_mismatch", "CRM returned a different entity identity.");
58105
+ const requestedCommunicationId = stableChildId(payload.bridgeRunId, "communication");
58106
+ const communication = await writer.appendCommunication({
58107
+ entityId: requestedCommunicationId,
58108
+ personEntityId: person.entityId,
58109
+ idempotencyKey: `${payload.bridgeRunId}:communication`,
58110
+ kind: "form_submission",
58111
+ occurredAt: payload.source.observedAt,
58112
+ submittedFields: payload.submittedFields,
58113
+ source: payload.source
58114
+ });
58115
+ let task = null;
58116
+ if (payload.followUp) {
58117
+ task = await writer.upsertTask({
58118
+ entityId: stableChildId(payload.bridgeRunId, "task"),
58119
+ personEntityId: person.entityId,
58120
+ communicationEntityId: communication.entityId,
58121
+ idempotencyKey: `${payload.bridgeRunId}:task`,
58122
+ title: payload.followUp.title,
58123
+ dueAt: payload.followUp.dueAt,
58124
+ source: payload.source
58125
+ });
58126
+ }
58127
+ return {
58128
+ crmEntityId: person.entityId,
58129
+ personReceiptId: person.receiptId,
58130
+ communicationEntityId: communication.entityId,
58131
+ communicationReceiptId: communication.receiptId,
58132
+ taskEntityId: task?.entityId ?? null,
58133
+ taskReceiptId: task?.receiptId ?? null
58134
+ };
58135
+ }
58136
+
57489
58137
  // src/api/analytics-delivery.ts
57490
58138
  function safeDeliveryError(error) {
57491
58139
  if (!error) return "memory_write_failed";
@@ -57494,7 +58142,37 @@ function safeDeliveryError(error) {
57494
58142
  if (error.includes("429")) return "memory_rate_limited";
57495
58143
  return "memory_write_failed";
57496
58144
  }
57497
- async function deliverPendingAnalyticsForms(limit = 10) {
58145
+ function memoryWriteReceipt(result3) {
58146
+ if (result3.ok !== true) throw new Error(typeof result3.error === "string" ? result3.error : "memory_write_failed");
58147
+ const record7 = result3.record && typeof result3.record === "object" ? result3.record : null;
58148
+ const receipt4 = result3.receipt && typeof result3.receipt === "object" ? result3.receipt : null;
58149
+ if (!record7 || typeof record7.entityId !== "string" || typeof record7.revision !== "number" || !receipt4 || typeof receipt4.receiptId !== "string") throw new Error("memory_write_receipt_invalid");
58150
+ return {
58151
+ entityId: record7.entityId,
58152
+ receiptId: receipt4.receiptId,
58153
+ revision: record7.revision
58154
+ };
58155
+ }
58156
+ function hostedMemoryCrmBridgeWriter(memoryKey) {
58157
+ return {
58158
+ async upsertPerson(input) {
58159
+ return memoryWriteReceipt(
58160
+ await memoryCall("crmUpsertPersonTool", input, memoryKey)
58161
+ );
58162
+ },
58163
+ async appendCommunication(input) {
58164
+ return memoryWriteReceipt(
58165
+ await memoryCall("crmAppendCommunicationTool", input, memoryKey)
58166
+ );
58167
+ },
58168
+ async upsertTask(input) {
58169
+ return memoryWriteReceipt(
58170
+ await memoryCall("crmUpsertTaskTool", input, memoryKey)
58171
+ );
58172
+ }
58173
+ };
58174
+ }
58175
+ async function deliverPendingAnalyticsForms(limit = 10, dependencies = {}) {
57498
58176
  const jobs = await claimAnalyticsFormDeliveryJobs(limit);
57499
58177
  let delivered = 0;
57500
58178
  let deferred = 0;
@@ -57515,12 +58193,62 @@ async function deliverPendingAnalyticsForms(limit = 10) {
57515
58193
  continue;
57516
58194
  }
57517
58195
  const { key: key3, error } = await getOrCreateUserMemoryKey(user);
57518
- const result3 = key3 ? await memoryCall("putTool", payload, key3) : { ok: false, error };
57519
- if (result3.ok) {
57520
- await completeAnalyticsFormDelivery(job.id, job.submissionId);
58196
+ if (!key3) {
58197
+ await deferAnalyticsFormDelivery(job.id, job.attempts, safeDeliveryError(error));
58198
+ deferred += 1;
58199
+ continue;
58200
+ }
58201
+ if (!job.bridgeRunId || !job.crmEntityId) {
58202
+ const result3 = await memoryCall("putTool", payload, key3);
58203
+ if (result3.ok) {
58204
+ await completeAnalyticsFormDelivery(job.id, job.submissionId);
58205
+ delivered += 1;
58206
+ } else {
58207
+ await deferAnalyticsFormDelivery(job.id, job.attempts, safeDeliveryError(result3.error));
58208
+ deferred += 1;
58209
+ }
58210
+ continue;
58211
+ }
58212
+ try {
58213
+ const source = payload.source && typeof payload.source === "object" ? payload.source : {};
58214
+ const bridgePayload = {
58215
+ ...payload,
58216
+ bridgeRunId: job.bridgeRunId,
58217
+ crmEntityId: job.crmEntityId,
58218
+ source: {
58219
+ ...source,
58220
+ kind: "xray_form",
58221
+ submissionId: job.submissionId
58222
+ }
58223
+ };
58224
+ const result3 = await applyCrmFormBridge(
58225
+ bridgePayload,
58226
+ (dependencies.createWriter ?? hostedMemoryCrmBridgeWriter)(key3)
58227
+ );
58228
+ await linkAnalyticsFormIdentity({
58229
+ submissionId: job.submissionId,
58230
+ siteId: bridgePayload.source.siteId,
58231
+ crmEntityId: result3.crmEntityId,
58232
+ visitorId: typeof payload.visitorId === "string" ? payload.visitorId : void 0,
58233
+ sessionId: typeof payload.sessionId === "string" ? payload.sessionId : void 0,
58234
+ email: bridgePayload.email,
58235
+ phone: bridgePayload.phone,
58236
+ displayName: bridgePayload.displayName,
58237
+ evidenceType: "first_party_form",
58238
+ clickIds: payload.clickIds && typeof payload.clickIds === "object" ? payload.clickIds : void 0
58239
+ });
58240
+ await completeAnalyticsFormBridgeDelivery({
58241
+ jobId: job.id,
58242
+ submissionId: job.submissionId,
58243
+ crmEntityId: result3.crmEntityId
58244
+ });
57521
58245
  delivered += 1;
57522
- } else {
57523
- await deferAnalyticsFormDelivery(job.id, job.attempts, safeDeliveryError(result3.error));
58246
+ } catch (bridgeError) {
58247
+ await deferAnalyticsFormDelivery(
58248
+ job.id,
58249
+ job.attempts,
58250
+ safeDeliveryError(bridgeError instanceof Error ? bridgeError.message : void 0)
58251
+ );
57524
58252
  deferred += 1;
57525
58253
  }
57526
58254
  }
@@ -57560,7 +58288,7 @@ async function deliverPendingAnalyticsCrmImports(limit = 10) {
57560
58288
  }
57561
58289
 
57562
58290
  // src/api/analytics-activation-dispatcher.ts
57563
- import { randomUUID as randomUUID39 } from "crypto";
58291
+ import { randomUUID as randomUUID40 } from "crypto";
57564
58292
  function parseAnalyticsActivationDestinationProviderConfig(platform, value) {
57565
58293
  if (!value || typeof value !== "object" || Array.isArray(value)) return null;
57566
58294
  const config = value;
@@ -57639,7 +58367,7 @@ async function claimAnalyticsActivationJobs(limit = 10) {
57639
58367
  }));
57640
58368
  }
57641
58369
  async function beginAttempt(job, stableEventId) {
57642
- const id2 = randomUUID39();
58370
+ const id2 = randomUUID40();
57643
58371
  const result3 = await getAnalyticsPool().query(
57644
58372
  `INSERT INTO analytics_activation_delivery_attempts(
57645
58373
  id, job_id, destination_id, mapping_version, attempt_number, provider_event_id, actor
@@ -58024,7 +58752,7 @@ async function pollPendingGoogleActivationDiagnostics(limit = 10, deadlineMs = D
58024
58752
  }
58025
58753
 
58026
58754
  // src/api/analytics-reconciliation.ts
58027
- import { createHash as createHash44, randomUUID as randomUUID40 } from "crypto";
58755
+ import { createHash as createHash45, randomUUID as randomUUID41 } from "crypto";
58028
58756
  var RECONCILIATION_INTERVAL_SECONDS = 15 * 60;
58029
58757
  var WEBHOOK_ONLY_RECHECK_SECONDS = 24 * 60 * 60;
58030
58758
  var LEASE_SECONDS = 90;
@@ -58048,7 +58776,7 @@ var defaultDependencies2 = {
58048
58776
  input: input.payload,
58049
58777
  classification: "read",
58050
58778
  operationKind: "sync",
58051
- requestId: randomUUID40()
58779
+ requestId: randomUUID41()
58052
58780
  });
58053
58781
  },
58054
58782
  async resolveMappedCrmPerson(input) {
@@ -58151,14 +58879,14 @@ function crmReadInput(provider, sourceAccountRef, cursorValue, now) {
58151
58879
  }
58152
58880
  }
58153
58881
  function crmOutcomeSourceEventId(outcome) {
58154
- const digest23 = createHash44("sha256").update(`${outcome.provider}:${outcome.sourceRecordId}:${outcome.updatedAt}:${outcome.tombstone}`).digest("hex").slice(0, 40);
58882
+ const digest23 = createHash45("sha256").update(`${outcome.provider}:${outcome.sourceRecordId}:${outcome.updatedAt}:${outcome.tombstone}`).digest("hex").slice(0, 40);
58155
58883
  return `crm:${outcome.provider}:${digest23}`;
58156
58884
  }
58157
58885
  function analyticsCrmOutcomeToExternalEvent(outcome, sourceAccountRef) {
58158
58886
  const sourceEventId = crmOutcomeSourceEventId(outcome);
58159
58887
  return {
58160
58888
  schemaVersion: 1,
58161
- eventId: `crm_${createHash44("sha256").update(sourceEventId).digest("hex").slice(0, 24)}`,
58889
+ eventId: `crm_${createHash45("sha256").update(sourceEventId).digest("hex").slice(0, 24)}`,
58162
58890
  sourceEventId,
58163
58891
  source: outcome.provider,
58164
58892
  sourceAccountRef,
@@ -58315,7 +59043,7 @@ async function ensureDueJobs() {
58315
59043
  await db.query(
58316
59044
  `INSERT INTO analytics_reconciliation_jobs(id, connection_id)
58317
59045
  VALUES ($1,$2) ON CONFLICT(connection_id) DO NOTHING`,
58318
- [randomUUID40(), connection.id]
59046
+ [randomUUID41(), connection.id]
58319
59047
  );
58320
59048
  }
58321
59049
  }
@@ -58458,7 +59186,7 @@ async function deferAnalyticsReconciliationJob(input) {
58458
59186
  connectionId: input.connectionId,
58459
59187
  safeErrorCode: errorCode2,
58460
59188
  nextRunAt: new Date(Date.now() + delaySeconds * 1e3).toISOString(),
58461
- receiptFingerprint: createHash44("sha256").update(`${input.jobId}:${input.attempts}:${errorCode2}`).digest("hex")
59189
+ receiptFingerprint: createHash45("sha256").update(`${input.jobId}:${input.attempts}:${errorCode2}`).digest("hex")
58462
59190
  });
58463
59191
  }
58464
59192
  }
@@ -58569,7 +59297,7 @@ async function reconcileAnalyticsConnection(job, dependencies = defaultDependenc
58569
59297
  deduplicated: duplicates,
58570
59298
  rejected: page3.rejected,
58571
59299
  hasMore: page3.hasMore,
58572
- receiptFingerprint: createHash44("sha256").update(`${job.id}:${JSON.stringify(page3.nextCursor)}:${replayed}:${duplicates}`).digest("hex"),
59300
+ receiptFingerprint: createHash45("sha256").update(`${job.id}:${JSON.stringify(page3.nextCursor)}:${replayed}:${duplicates}`).digest("hex"),
58573
59301
  scheduleConfigured: Boolean(scope.sync_id),
58574
59302
  scheduleIntervalSeconds: scope.sync_interval_seconds ?? null
58575
59303
  }
@@ -58606,7 +59334,7 @@ async function drainAnalyticsReconciliation(limit = 5, deadlineMs = Date.now() +
58606
59334
  }
58607
59335
 
58608
59336
  // src/api/analytics-scheduled-lanes.ts
58609
- import { randomUUID as randomUUID41 } from "crypto";
59337
+ import { randomUUID as randomUUID42 } from "crypto";
58610
59338
  var ANALYTICS_SCHEDULED_LANES = [
58611
59339
  { key: "rollup", intervalMinutes: 15, catchUpIntervals: 2, maxAttempts: 4 },
58612
59340
  { key: "form_delivery", intervalMinutes: 1, catchUpIntervals: 3, maxAttempts: 5 },
@@ -58653,7 +59381,7 @@ var PostgresAnalyticsScheduledOccurrenceStore = class {
58653
59381
  (id,lane_key,scheduled_for,status,attempt_count,max_attempts,next_attempt_at,created_at,updated_at)
58654
59382
  VALUES ($1,$2,$3,'pending',0,$4,$3,now(),now())
58655
59383
  ON CONFLICT (lane_key,scheduled_for) DO NOTHING`,
58656
- [randomUUID41(), definition.key, scheduledFor, definition.maxAttempts]
59384
+ [randomUUID42(), definition.key, scheduledFor, definition.maxAttempts]
58657
59385
  );
58658
59386
  inserted += Number(result3.rowCount ?? 0);
58659
59387
  }
@@ -58736,7 +59464,7 @@ var PostgresAnalyticsScheduledOccurrenceStore = class {
58736
59464
  async function runAnalyticsScheduledLanes(executors, options = {}) {
58737
59465
  const store = options.store ?? new PostgresAnalyticsScheduledOccurrenceStore();
58738
59466
  const now = options.now ?? (() => /* @__PURE__ */ new Date());
58739
- const owner5 = options.owner ?? `cron:${randomUUID41()}`;
59467
+ const owner5 = options.owner ?? `cron:${randomUUID42()}`;
58740
59468
  const leaseMs = options.leaseMs ?? 6e4;
58741
59469
  const maxClaims = options.maxClaims ?? 12;
58742
59470
  const firstNow = now();
@@ -58782,17 +59510,17 @@ async function runAnalyticsScheduledLanes(executors, options = {}) {
58782
59510
  }
58783
59511
 
58784
59512
  // src/api/scheduled-result-routes.ts
58785
- import { Hono as Hono37 } from "hono";
58786
- import { z as z44 } from "zod";
59513
+ import { Hono as Hono38 } from "hono";
59514
+ import { z as z46 } from "zod";
58787
59515
 
58788
59516
  // src/api/scheduled-artifact-owner.ts
58789
- import { createHash as createHash45 } from "crypto";
59517
+ import { createHash as createHash46 } from "crypto";
58790
59518
  function scheduledArtifactOwnerIdForApiKey(apiKey) {
58791
- return createHash45("sha256").update(apiKey).digest("hex").slice(0, 24);
59519
+ return createHash46("sha256").update(apiKey).digest("hex").slice(0, 24);
58792
59520
  }
58793
59521
 
58794
59522
  // src/api/scheduled-run-view-links.ts
58795
- import { createHash as createHash46, randomBytes as randomBytes6, randomUUID as randomUUID42 } from "crypto";
59523
+ import { createHash as createHash47, randomBytes as randomBytes6, randomUUID as randomUUID43 } from "crypto";
58796
59524
  var schemaReady3 = false;
58797
59525
  async function ensureScheduledRunViewLinksSchema() {
58798
59526
  if (schemaReady3) return;
@@ -58846,7 +59574,7 @@ async function ensureScheduledRunViewLinksSchema() {
58846
59574
  schemaReady3 = true;
58847
59575
  }
58848
59576
  function tokenHash2(token7) {
58849
- return createHash46("sha256").update(token7).digest("hex");
59577
+ return createHash47("sha256").update(token7).digest("hex");
58850
59578
  }
58851
59579
  function mapRow(row) {
58852
59580
  return {
@@ -58868,7 +59596,7 @@ async function createScheduledRunViewLink(input) {
58868
59596
  const now = input.now ?? /* @__PURE__ */ new Date();
58869
59597
  const token7 = randomBytes6(32).toString("base64url");
58870
59598
  const record7 = {
58871
- shareId: randomUUID42(),
59599
+ shareId: randomUUID43(),
58872
59600
  ownerId: input.ownerId,
58873
59601
  runId: input.runId,
58874
59602
  artifactId: input.artifactId,
@@ -58933,7 +59661,7 @@ async function revokeScheduledRunViewLink(ownerId3, runId, shareId, now = /* @__
58933
59661
  }
58934
59662
 
58935
59663
  // src/personal-authority/render.ts
58936
- import { createHash as createHash47 } from "crypto";
59664
+ import { createHash as createHash48 } from "crypto";
58937
59665
  function escapeHtml8(value) {
58938
59666
  return value.replace(/[&<>"']/g, (character) => ({
58939
59667
  "&": "&amp;",
@@ -58993,13 +59721,13 @@ ${section(flags.finalCta && Boolean(finalCta), `<section class="section cta" id=
58993
59721
  html,
58994
59722
  filename: `${input.name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "personal-authority"}.html`,
58995
59723
  bytes: bytes2,
58996
- sha256: createHash47("sha256").update(html).digest("hex"),
59724
+ sha256: createHash48("sha256").update(html).digest("hex"),
58997
59725
  generatedAt: generatedAtIso
58998
59726
  };
58999
59727
  }
59000
59728
 
59001
59729
  // src/personal-authority/render-v2.ts
59002
- import { createHash as createHash48 } from "crypto";
59730
+ import { createHash as createHash49 } from "crypto";
59003
59731
  var FONT_STACKS = Object.freeze({
59004
59732
  "editorial-serif": "Iowan Old Style, Baskerville, Times New Roman, serif",
59005
59733
  "modern-sans": "Avenir Next, Avenir, Helvetica Neue, Arial, sans-serif",
@@ -59103,13 +59831,13 @@ ${section2(flags.finalCta && Boolean(finalCta), `<section class="section cta" id
59103
59831
  html,
59104
59832
  filename: `${input.name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "personal-authority"}.html`,
59105
59833
  bytes: bytes2,
59106
- sha256: createHash48("sha256").update(html).digest("hex"),
59834
+ sha256: createHash49("sha256").update(html).digest("hex"),
59107
59835
  generatedAt: generatedAtIso
59108
59836
  };
59109
59837
  }
59110
59838
 
59111
59839
  // src/newsroom-publisher/render.ts
59112
- import { createHash as createHash49 } from "crypto";
59840
+ import { createHash as createHash50 } from "crypto";
59113
59841
  function escapeHtml10(value) {
59114
59842
  return value.replace(/[&<>"']/g, (character) => ({
59115
59843
  "&": "&amp;",
@@ -59215,13 +59943,13 @@ body{overflow-x:hidden}.lead-story__body,.lead-support__item,.story-card__body{m
59215
59943
  @media(max-width:620px){.desk-section__grid--panorama,.desk-section__grid--mosaic,.desk-section__grid--tiles{grid-template-columns:1fr}.story-card--panorama{display:block}.story-card--panorama h3,.story-card--mosaic-lead h3{font-size:34px}.story-card--mosaic-lead{grid-column:auto;grid-row:auto}.desk-section__grid--tiles>.story-card:nth-child(3n+2){margin-top:0}}
59216
59944
  </style></head><body data-theme="${escapeHtml10(config.theme)}" id="top" data-scheduled-renderer="newsroom_publisher_v1">${ticker}${masthead}${navigation}<main>${leadGrid}${latest}${sections}${newsletter}${pressRoom}${trustCenter}</main>${trustFooter}</body></html>`;
59217
59945
  const bytes2 = Buffer.byteLength(html);
59218
- const sha2564 = createHash49("sha256").update(html).digest("hex");
59946
+ const sha2564 = createHash50("sha256").update(html).digest("hex");
59219
59947
  const filename2 = `${brand.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "newsroom"}-news-site.html`;
59220
59948
  return { html, filename: filename2, bytes: bytes2, sha256: sha2564, generatedAt: generatedAtIso };
59221
59949
  }
59222
59950
 
59223
59951
  // src/blog-article/render.ts
59224
- import { createHash as createHash50 } from "crypto";
59952
+ import { createHash as createHash51 } from "crypto";
59225
59953
  function escapeHtml11(value) {
59226
59954
  return value.replace(
59227
59955
  /[&<>"']/g,
@@ -59309,7 +60037,7 @@ function renderBlogArticleV1(input, config, generatedAt) {
59309
60037
  :root{--ink:#10213d;--ink2:#1c355a;--blue:#2563eb;--blue2:#1749b6;--mint:#45d5aa;--paper:#f7f5f0;--line:#dce4ef;--card:#fff;--body:#475569;--serif:Iowan Old Style,Palatino Linotype,Palatino,Georgia,serif;--sans:Inter,Avenir Next,ui-sans-serif,system-ui,sans-serif}body[data-theme="slate"]{--ink:#1e293b;--ink2:#334155;--blue:#475569;--blue2:#1e293b;--mint:#94a3b8;--paper:#f8fafc}body[data-theme="forest"]{--ink:#12352e;--ink2:#23584c;--blue:#147d64;--blue2:#0c5b48;--mint:#79d8bd;--paper:#f4f8f3}*{box-sizing:border-box}html{scroll-behavior:smooth;background:var(--paper)}body{margin:0;color:#252a33;background:var(--paper);font-family:var(--sans);line-height:1.6}a{color:inherit}button{font:inherit}button:focus-visible,a:focus-visible{outline:3px solid var(--mint);outline-offset:3px}.progress{position:fixed;z-index:50;top:0;left:0;height:4px;width:0;background:var(--mint)}.hero{position:relative;overflow:hidden;color:#fff;background:var(--ink)}.hero:after{position:absolute;right:-110px;top:-150px;width:420px;height:420px;border:1px solid #ffffff1a;border-radius:50%;content:""}.hero-inner{position:relative;z-index:1;max-width:1240px;margin:auto;padding:58px 42px 126px}.breadcrumb{display:flex;gap:8px;margin-bottom:34px;color:#dbeafecc;font-size:14px}.eyebrow{display:block;color:var(--blue);font-size:12px;font-weight:800;letter-spacing:.16em;text-transform:uppercase}.hero .eyebrow{color:var(--mint)}h1,h2,h3,p{margin-top:0}.hero h1{max-width:1000px;margin:14px 0 24px;font:700 clamp(44px,6vw,78px)/.98 var(--serif);letter-spacing:-.035em}.hero .dek{max-width:780px;color:#dbeafe;font-size:20px}.contributors{margin-top:30px;color:#eff6ff;font-size:14px}.contributors a{font-weight:800}.meta{display:flex;flex-wrap:wrap;gap:12px;margin-top:6px;color:#dbeafecc}.layout{position:relative;z-index:2;display:grid;grid-template-columns:minmax(0,760px) 290px;gap:64px;max-width:1240px;margin:-78px auto 0;padding:0 42px 80px}.main{min-width:0}.takeaways{padding:38px 44px;border-radius:24px;background:#fff;box-shadow:0 24px 70px #10213d24}.takeaways h2{margin:5px 0 20px;font:700 32px/1.1 var(--serif);color:var(--ink)}.takeaways ul{display:grid;gap:16px;margin:0;padding:0;list-style:none}.takeaways li{position:relative;padding-left:26px;color:var(--body);font-size:17px}.takeaways li:before{position:absolute;left:2px;top:.7em;width:8px;height:8px;border-radius:50%;background:var(--blue);content:""}.intro{padding:40px 0 4px}.intro p,.article-section>p{margin-bottom:22px;color:var(--body);font:400 18px/1.75 var(--sans)}.article-section{scroll-margin-top:28px;padding-top:45px}.article-section h2,.faq h2{margin:6px 0 20px;color:var(--ink);font:700 38px/1.08 var(--serif);letter-spacing:-.02em}.article-section ul{display:grid;gap:10px;margin:22px 0;padding-left:24px;color:var(--body);font-size:17px}.article-section li::marker{color:var(--blue)}.callout{margin:34px 0;padding:24px 28px;border-left:4px solid var(--blue);border-radius:0 16px 16px 0;background:#fff}.callout span{color:var(--blue);font-size:11px;font-weight:800;letter-spacing:.13em;text-transform:uppercase}.callout h3{margin:5px 0 8px;color:var(--ink);font:700 24px/1.15 var(--serif)}.callout p{margin:0;color:var(--body)}.rail{padding-top:0}.sidebar-media{overflow:hidden;margin:0 0 18px;border:1px solid #dbeafe;border-radius:16px;background:#fff}.sidebar-media img,.sidebar-media svg{display:block;width:100%;aspect-ratio:16/9;object-fit:cover}.sidebar-media figcaption{padding:10px 13px;color:#64748b;font-size:11px}.disclosure{margin-bottom:28px;border-top:1px solid #dbeafe;border-bottom:1px solid #dbeafe}.disclosure button{display:flex;width:100%;align-items:center;justify-content:space-between;gap:14px;padding:15px 0;border:0;color:#64748b;background:transparent;text-align:left;font-size:12px;cursor:pointer}.disclosure button b{color:var(--blue);font-size:18px;transition:transform .2s}.disclosure button[aria-expanded="true"] b{transform:rotate(180deg)}.disclosure p{padding:0 0 16px;margin:0;color:#64748b;font-size:12px}.toc{position:sticky;top:30px;padding:22px;border:1px solid var(--line);border-radius:16px;background:#fff;box-shadow:0 2px 5px #10213d12}.toc header{display:flex;align-items:center;justify-content:space-between}.toc header strong{color:var(--ink);font:700 21px/1 var(--serif)}.toc header button{width:34px;height:34px;border:0;border-radius:50%;color:var(--blue);background:transparent;cursor:pointer}.toc nav{display:grid;margin-top:14px}.toc nav a{display:flex;align-items:flex-start;gap:11px;padding:8px 0;color:#64748b;text-decoration:none;font-size:13px;line-height:1.35}.toc nav i{width:8px;height:8px;margin-top:5px;border:2px solid #bfdbfe;border-radius:50%}.toc nav a[aria-current="location"]{color:var(--ink);font-weight:800}.toc nav a[aria-current="location"] i{border-color:var(--blue);background:var(--blue)}.back-top{width:100%;margin-top:18px;padding:16px 0 0;border:0;border-top:1px solid var(--line);color:var(--blue);background:transparent;text-align:right;font-size:13px;font-weight:800;cursor:pointer}.faq{scroll-margin-top:28px;padding-top:64px}.faq>div{border-top:1px solid var(--line);border-bottom:1px solid var(--line)}.faq article+article{border-top:1px solid var(--line)}.faq h3{margin:0}.faq h3 button{display:flex;width:100%;align-items:center;justify-content:space-between;gap:18px;padding:19px 0;border:0;color:var(--ink);background:transparent;text-align:left;font-weight:800;cursor:pointer}.faq h3 b{color:var(--blue);font-size:22px}.faq article>p{padding:0 0 20px;margin:0;color:var(--body);font-size:16px}.author-card{margin-top:64px;padding:32px 36px;border-radius:18px;background:#fff}.article-actions{display:flex;flex-wrap:wrap;justify-content:space-between;gap:14px}.article-actions button{display:inline-flex;min-height:46px;align-items:center;justify-content:center;gap:8px;padding:8px 18px;border:2px solid var(--blue);border-radius:999px;color:var(--ink);background:#fff;font-weight:800;cursor:pointer}.article-actions button:hover{color:#fff;background:var(--blue)}.action-status{min-height:20px;margin:8px 0 0;color:var(--blue);text-align:right;font-size:13px;font-weight:700}.author-grid{display:grid;grid-template-columns:auto 1fr auto;gap:22px;align-items:center;margin-top:24px}.author-portrait{width:88px;height:88px;border-radius:50%;object-fit:cover}.author-initials{display:grid;place-items:center;color:var(--ink);background:#fecdd3;font-size:22px;font-weight:900}.author-grid span{color:#64748b;font-size:13px}.author-grid h2{margin:2px 0;color:var(--ink);font:700 27px/1 var(--serif)}.author-grid h2 a{text-decoration:none}.author-grid p{margin:8px 0;color:#64748b;font-size:14px}.author-grid nav{display:flex;flex-wrap:wrap;gap:14px}.author-grid nav a{color:#64748b;font-size:12px}.author-more{display:inline-flex;min-height:48px;align-items:center;justify-content:center;padding:10px 24px;border:2px solid var(--blue);color:var(--blue);text-align:center;text-decoration:none;font-size:13px;font-weight:800}.author-bio{margin:24px 0 0!important;padding-top:20px;border-top:1px solid var(--line);color:var(--body);font-size:16px}dialog{width:min(720px,calc(100% - 30px));max-height:calc(100dvh - 30px);padding:0;border:0;border-radius:18px;color:var(--ink);background:#fff;box-shadow:0 24px 70px #10213d38}dialog::backdrop{background:#0f172a7a;backdrop-filter:blur(2px)}dialog>div{position:relative;padding:30px}dialog h2{margin:0 50px 2px 0;font:700 30px/1.1 var(--serif)}dialog>div>p{color:#64748b}.dialog-close{position:absolute;top:13px;right:13px;width:44px;height:44px;border:0;border-radius:50%;color:var(--blue);background:transparent;font-size:29px;cursor:pointer}dialog section{border-top:1px solid var(--line)}dialog section button{display:block;width:100%;padding:17px 5px;border:0;border-bottom:1px solid var(--line);color:var(--body);background:#fff;text-align:left;line-height:1.65;cursor:pointer}.citation-status{min-height:22px;margin:14px 0 0!important;color:var(--blue)!important;font-size:13px;font-weight:800}.generated{max-width:1156px;margin:-52px auto 50px;padding:0 42px;color:#94a3b8;font-size:11px}@media(max-width:900px){.layout{display:block}.rail{display:none}.hero-inner{padding-bottom:116px}}@media(max-width:620px){.hero-inner{padding:36px 20px 104px}.hero h1{font-size:46px}.hero .dek{font-size:17px}.layout{margin-top:-70px;padding:0 16px 54px}.takeaways{padding:28px 24px}.article-section h2,.faq h2{font-size:32px}.author-card{padding:24px}.article-actions{display:grid;justify-content:start}.author-grid{grid-template-columns:1fr;gap:12px}.author-more{width:100%}dialog>div{padding:24px}.generated{padding:0 20px}}
59310
60038
  </style></head><body data-theme="${escapeHtml11(config.theme)}" data-scheduled-renderer="blog_article_v1"><div class="progress" aria-hidden="true"></div><header class="hero"><div class="hero-inner"><nav class="breadcrumb" aria-label="Breadcrumb"><a href="${safeHref4(input.canonicalUrl)}">${escapeHtml11(input.category)}</a><span>/</span><span>Article</span></nav><span class="eyebrow">${escapeHtml11(input.eyebrow)}</span><h1>${escapeHtml11(input.title)}</h1>${input.dek ? `<p class="dek">${escapeHtml11(input.dek)}</p>` : ""}<div class="contributors">${contributorText}<div class="meta"><time datetime="${escapeHtml11(articleDate)}">Updated ${formatDate2(articleDate)}</time><span>\u2022</span><span>${input.readTimeMinutes} min read</span>${input.reviewer ? "<span>\u2022</span><strong>Expert reviewed</strong>" : ""}</div></div></div></header><main class="layout"><article class="main"><section class="takeaways"><span class="eyebrow">The short answer</span><h2>Key takeaways</h2><ul>${input.keyTakeaways.map((item) => `<li>${escapeHtml11(item)}</li>`).join("")}</ul></section><section class="intro">${input.introduction.map((paragraph) => `<p>${escapeHtml11(paragraph)}</p>`).join("")}</section>${sections}${faq}${author}</article><div class="rail">${media}${disclosure}${toc}</div></main>${config.showGeneratedAt ? `<p class="generated">Rendered ${formatDate2(generatedAtIso)} by MCP Scraper.</p>` : ""}${citationDialog}<script>(()=>{const citations=${jsonForScript(citationValues)};const canonical=${jsonForScript(input.canonicalUrl)};const title=${jsonForScript(input.title)};const progress=document.querySelector('.progress');const tocLinks=[...document.querySelectorAll('.toc nav a')];const targets=tocLinks.map(link=>document.querySelector(link.hash)).filter(Boolean);const update=()=>{const max=document.documentElement.scrollHeight-innerHeight;if(progress)progress.style.width=(max>0?scrollY/max*100:0)+'%';let active=targets[0]?.id;for(const target of targets){if(target.getBoundingClientRect().top<=innerHeight*.55)active=target.id}tocLinks.forEach(link=>link.toggleAttribute('aria-current',link.hash==='#'+active));tocLinks.forEach(link=>{if(link.hash==='#'+active)link.setAttribute('aria-current','location');else link.removeAttribute('aria-current')})};addEventListener('scroll',update,{passive:true});addEventListener('resize',update);update();document.querySelectorAll('.faq h3 button').forEach(button=>button.addEventListener('click',()=>{const panel=document.getElementById(button.getAttribute('aria-controls'));const open=button.getAttribute('aria-expanded')==='true';button.setAttribute('aria-expanded',String(!open));panel.hidden=open;button.querySelector('b').textContent=open?'+':'\u2212'}));const disclosure=document.querySelector('.disclosure button');disclosure?.addEventListener('click',()=>{const panel=document.getElementById(disclosure.getAttribute('aria-controls'));const open=disclosure.getAttribute('aria-expanded')==='true';disclosure.setAttribute('aria-expanded',String(!open));panel.hidden=open});const tocToggle=document.querySelector('.toc header button');tocToggle?.addEventListener('click',()=>{const nav=document.getElementById('toc-links');const open=tocToggle.getAttribute('aria-expanded')==='true';tocToggle.setAttribute('aria-expanded',String(!open));nav.hidden=open;tocToggle.textContent=open?'\u2304':'\u2303'});document.querySelector('.back-top')?.addEventListener('click',()=>scrollTo({top:0,behavior:'smooth'}));const copy=async text=>{try{await navigator.clipboard.writeText(text)}catch{const area=document.createElement('textarea');area.value=text;area.style.position='fixed';area.style.opacity='0';document.body.append(area);area.select();document.execCommand('copy');area.remove()}};const dialog=document.getElementById('citation-dialog');document.querySelector('[data-cite]')?.addEventListener('click',()=>dialog.showModal());document.querySelector('.dialog-close')?.addEventListener('click',()=>dialog.close());dialog?.addEventListener('click',event=>{if(event.target===dialog)dialog.close()});document.querySelectorAll('[data-citation]').forEach(button=>button.addEventListener('click',async()=>{const style=button.dataset.citation;await copy(citations[style]);document.querySelector('.citation-status').textContent=style+' citation copied to clipboard.'}));document.querySelector('[data-share]')?.addEventListener('click',async()=>{const status=document.querySelector('.action-status');if(navigator.share){try{await navigator.share({title,url:canonical});status.textContent='Sharing options opened.';return}catch(error){if(error.name==='AbortError')return}}await copy(canonical);status.textContent='Article link copied to clipboard.'})})()</script></body></html>`;
59311
60039
  const bytes2 = Buffer.byteLength(html);
59312
- const sha2564 = createHash50("sha256").update(html).digest("hex");
60040
+ const sha2564 = createHash51("sha256").update(html).digest("hex");
59313
60041
  return {
59314
60042
  html,
59315
60043
  filename: "blog-article.html",
@@ -59424,15 +60152,15 @@ var scheduledArtifactTemplatePresets = [
59424
60152
  ];
59425
60153
 
59426
60154
  // src/api/scheduled-result-routes.ts
59427
- var TemplateParamsSchema = z44.object({ templateId: z44.string().uuid() }).strict();
59428
- var RunParamsSchema = z44.object({ runId: z44.string().min(1).max(200) }).strict();
59429
- var ViewLinkParamsSchema = z44.object({
59430
- runId: z44.string().min(1).max(200),
59431
- shareId: z44.string().uuid()
60155
+ var TemplateParamsSchema = z46.object({ templateId: z46.string().uuid() }).strict();
60156
+ var RunParamsSchema = z46.object({ runId: z46.string().min(1).max(200) }).strict();
60157
+ var ViewLinkParamsSchema = z46.object({
60158
+ runId: z46.string().min(1).max(200),
60159
+ shareId: z46.string().uuid()
59432
60160
  }).strict();
59433
- var ArtifactTemplateListQuerySchema = z44.object({
59434
- status: z44.enum(["active", "archived", "all"]).default("active"),
59435
- query: z44.string().trim().min(1).max(120).optional(),
60161
+ var ArtifactTemplateListQuerySchema = z46.object({
60162
+ status: z46.enum(["active", "archived", "all"]).default("active"),
60163
+ query: z46.string().trim().min(1).max(120).optional(),
59436
60164
  presetKey: ArtifactTemplatePresetKeySchema.optional()
59437
60165
  }).strict();
59438
60166
  function apiError(error, errorCode2 = "invalid_request") {
@@ -59462,7 +60190,7 @@ function safeMemoryFailure(result3) {
59462
60190
  errorCode2 in messages ? errorCode2 : "internal_error"
59463
60191
  );
59464
60192
  }
59465
- var scheduledResultApp = new Hono37();
60193
+ var scheduledResultApp = new Hono38();
59466
60194
  scheduledResultApp.use("/artifact-templates", createApiKeyAuth());
59467
60195
  scheduledResultApp.use("/artifact-templates/*", createApiKeyAuth());
59468
60196
  scheduledResultApp.use("/schedule-runs", createApiKeyAuth());
@@ -59609,10 +60337,10 @@ scheduledResultApp.delete("/schedule-runs/:runId/view-links/:shareId", async (c)
59609
60337
  });
59610
60338
 
59611
60339
  // src/api/public-scheduled-result-routes.ts
59612
- import { Hono as Hono38 } from "hono";
60340
+ import { Hono as Hono39 } from "hono";
59613
60341
 
59614
60342
  // src/scheduled-artifacts/scheduled-run-artifact-store.ts
59615
- import { createHash as createHash51 } from "crypto";
60343
+ import { createHash as createHash52 } from "crypto";
59616
60344
  var SCHEDULED_RUN_ARTIFACT_PREFIX = "scheduled-run-artifacts/";
59617
60345
  var SCHEDULED_RUN_ARTIFACT_DOWNLOAD_TTL_MS = 15 * 60 * 1e3;
59618
60346
  var SCHEDULED_RUN_ARTIFACT_MAX_BYTES = 2e6;
@@ -59628,7 +60356,7 @@ function policy5() {
59628
60356
  };
59629
60357
  }
59630
60358
  function runStorageSegment(runId) {
59631
- return /^[a-zA-Z0-9_-]{1,160}$/.test(runId) ? runId : `run-${createHash51("sha256").update(runId).digest("hex").slice(0, 32)}`;
60359
+ return /^[a-zA-Z0-9_-]{1,160}$/.test(runId) ? runId : `run-${createHash52("sha256").update(runId).digest("hex").slice(0, 32)}`;
59632
60360
  }
59633
60361
  async function createScheduledRunArtifact(args) {
59634
60362
  if (args.rendered.bytes > SCHEDULED_RUN_ARTIFACT_MAX_BYTES) {
@@ -59671,7 +60399,7 @@ async function readScheduledRunArtifact(args) {
59671
60399
  }
59672
60400
 
59673
60401
  // src/api/public-scheduled-result-routes.ts
59674
- var publicScheduledResultApp = new Hono38();
60402
+ var publicScheduledResultApp = new Hono39();
59675
60403
  function allowedFrameAncestors() {
59676
60404
  const configured3 = (process.env.SCHEDULED_ARTIFACT_FRAME_ANCESTORS ?? "").split(",").map((value) => value.trim()).filter((value) => /^https?:\/\/[^/\s]+$/.test(value));
59677
60405
  const origins = configured3.length ? configured3 : ["https://mcpscraper.dev", "https://www.mcpscraper.dev"];
@@ -59732,8 +60460,8 @@ publicScheduledResultApp.get("/scheduled-run-view-links/:token/content", async (
59732
60460
  });
59733
60461
 
59734
60462
  // src/api/scheduled-artifact-internal-routes.ts
59735
- import { Hono as Hono39 } from "hono";
59736
- var scheduledArtifactInternalApp = new Hono39();
60463
+ import { Hono as Hono40 } from "hono";
60464
+ var scheduledArtifactInternalApp = new Hono40();
59737
60465
  function errorPayload(errorCode2, error, requestId) {
59738
60466
  return ApiErrorResponseSchema.parse({
59739
60467
  ok: false,
@@ -59820,19 +60548,19 @@ scheduledArtifactInternalApp.post("/render", async (c) => {
59820
60548
  });
59821
60549
 
59822
60550
  // src/api/personal-assistant-routes.ts
59823
- import { createHash as createHash59, randomUUID as randomUUID44 } from "crypto";
59824
- import { Hono as Hono41 } from "hono";
60551
+ import { createHash as createHash60, randomUUID as randomUUID45 } from "crypto";
60552
+ import { Hono as Hono42 } from "hono";
59825
60553
 
59826
60554
  // src/api/personal-assistant-schedule-readiness.ts
59827
- import { createHash as createHash52 } from "crypto";
59828
- import { z as z45 } from "zod";
59829
- var opaqueRef = z45.string().trim().regex(/^[a-z][a-z0-9_]*_[A-Za-z0-9_-]{3,128}$/);
59830
- var isoTimestamp2 = z45.iso.datetime({ offset: true });
59831
- var reasonCode = z45.string().regex(/^[a-z][a-z0-9_]{2,80}$/);
59832
- var ScheduleReadinessInputSchema = z45.object({
60555
+ import { createHash as createHash53 } from "crypto";
60556
+ import { z as z47 } from "zod";
60557
+ var opaqueRef = z47.string().trim().regex(/^[a-z][a-z0-9_]*_[A-Za-z0-9_-]{3,128}$/);
60558
+ var isoTimestamp2 = z47.iso.datetime({ offset: true });
60559
+ var reasonCode = z47.string().regex(/^[a-z][a-z0-9_]{2,80}$/);
60560
+ var ScheduleReadinessInputSchema = z47.object({
59833
60561
  draft: CanonicalScheduleDraftSchema,
59834
60562
  runtimeRef: opaqueRef.nullable(),
59835
- exactConnectionBindings: z45.array(ScheduleConnectionBindingSchema).max(100)
60563
+ exactConnectionBindings: z47.array(ScheduleConnectionBindingSchema).max(100)
59836
60564
  }).strict().superRefine((value, context) => {
59837
60565
  const connectionRefs = value.exactConnectionBindings.map((binding) => binding.connectionRef);
59838
60566
  if (new Set(connectionRefs).size !== connectionRefs.length) {
@@ -59845,26 +60573,26 @@ var ScheduleReadinessInputSchema = z45.object({
59845
60573
  context.addIssue({ code: "custom", path: ["runtimeRef"], message: "browser jobs require a registered runtime" });
59846
60574
  }
59847
60575
  });
59848
- var ScheduleReadinessFactSchema = z45.object({
59849
- key: z45.string().regex(/^[a-z][a-z0-9_.]{2,120}$/),
60576
+ var ScheduleReadinessFactSchema = z47.object({
60577
+ key: z47.string().regex(/^[a-z][a-z0-9_.]{2,120}$/),
59850
60578
  subjectRef: opaqueRef.nullable(),
59851
- state: z45.enum(["ready", "warning", "blocked"]),
60579
+ state: z47.enum(["ready", "warning", "blocked"]),
59852
60580
  reasonCode,
59853
- revision: z45.number().int().nonnegative().nullable(),
60581
+ revision: z47.number().int().nonnegative().nullable(),
59854
60582
  evidenceDigest: DigestSchema.nullable()
59855
60583
  }).strict();
59856
- var readinessIssue = z45.object({ code: reasonCode, subjectRef: opaqueRef.nullable() }).strict();
59857
- var ScheduleReadinessReceiptSchema = z45.object({
59858
- schemaVersion: z45.literal("assistant-schedule-readiness.v1"),
60584
+ var readinessIssue = z47.object({ code: reasonCode, subjectRef: opaqueRef.nullable() }).strict();
60585
+ var ScheduleReadinessReceiptSchema = z47.object({
60586
+ schemaVersion: z47.literal("assistant-schedule-readiness.v1"),
59859
60587
  scheduleRef: opaqueRef,
59860
- scheduleRevision: z45.number().int().positive(),
59861
- state: z45.enum(["ready", "blocked"]),
60588
+ scheduleRevision: z47.number().int().positive(),
60589
+ state: z47.enum(["ready", "blocked"]),
59862
60590
  planDigest: DigestSchema,
59863
60591
  grantSetDigest: DigestSchema,
59864
60592
  readinessDigest: DigestSchema,
59865
- facts: z45.array(ScheduleReadinessFactSchema).max(500),
59866
- blockers: z45.array(readinessIssue).max(200),
59867
- warnings: z45.array(readinessIssue).max(200),
60593
+ facts: z47.array(ScheduleReadinessFactSchema).max(500),
60594
+ blockers: z47.array(readinessIssue).max(200),
60595
+ warnings: z47.array(readinessIssue).max(200),
59868
60596
  evaluatedAt: isoTimestamp2
59869
60597
  }).strict();
59870
60598
  function resolveEffectiveBrowserGrant(raw) {
@@ -59897,7 +60625,7 @@ function canonicalJson2(value) {
59897
60625
  return JSON.stringify(value);
59898
60626
  }
59899
60627
  function digest2(value) {
59900
- return createHash52("sha256").update(canonicalJson2(value)).digest("hex");
60628
+ return createHash53("sha256").update(canonicalJson2(value)).digest("hex");
59901
60629
  }
59902
60630
  function validTimezone2(timezone) {
59903
60631
  try {
@@ -60158,7 +60886,7 @@ async function evaluateScheduleReadiness(rawInput, dependencies) {
60158
60886
  }
60159
60887
 
60160
60888
  // src/api/personal-assistant-command-builder.ts
60161
- import { createHash as createHash53 } from "crypto";
60889
+ import { createHash as createHash54 } from "crypto";
60162
60890
  function canonicalJson3(value) {
60163
60891
  return JSON.stringify(value, (_key, entry) => {
60164
60892
  if (!entry || typeof entry !== "object" || Array.isArray(entry)) return entry;
@@ -60166,7 +60894,7 @@ function canonicalJson3(value) {
60166
60894
  });
60167
60895
  }
60168
60896
  function digest3(value) {
60169
- return createHash53("sha256").update(canonicalJson3(value)).digest("hex");
60897
+ return createHash54("sha256").update(canonicalJson3(value)).digest("hex");
60170
60898
  }
60171
60899
  function explicitControlIntent(text3) {
60172
60900
  const normalized = text3.trim().toLowerCase();
@@ -60215,7 +60943,7 @@ async function buildPersonalAssistantCommand(context, input) {
60215
60943
  }
60216
60944
 
60217
60945
  // src/api/personal-assistant-consent-content.ts
60218
- import { createHash as createHash54 } from "crypto";
60946
+ import { createHash as createHash55 } from "crypto";
60219
60947
  var SUBMITTED_EVIDENCE = Object.freeze({
60220
60948
  evidenceVersion: "twilio-toll-free-submission.2026-08-28.v1",
60221
60949
  policyVersion: "2026-08-28.v1",
@@ -60278,7 +61006,7 @@ var ASSISTANT_ENROLLMENT_DISCLOSURE_TEXT = Object.freeze([
60278
61006
  ASSISTANT_CONSENT_CONTENT_V1.retentionDisclosure,
60279
61007
  ASSISTANT_CONSENT_CONTENT_V1.termsDisclosure
60280
61008
  ].join("\n\n"));
60281
- var ASSISTANT_ENROLLMENT_DISCLOSURE_DIGEST = createHash54("sha256").update(`${ASSISTANT_CONSENT_CONTENT_V1.policyVersion}\0${ASSISTANT_ENROLLMENT_DISCLOSURE_TEXT}`).digest("hex");
61009
+ var ASSISTANT_ENROLLMENT_DISCLOSURE_DIGEST = createHash55("sha256").update(`${ASSISTANT_CONSENT_CONTENT_V1.policyVersion}\0${ASSISTANT_ENROLLMENT_DISCLOSURE_TEXT}`).digest("hex");
60282
61010
  var ASSISTANT_ENROLLMENT_DISCLOSURE_PROJECTION = Object.freeze({
60283
61011
  policyVersion: ASSISTANT_CONSENT_CONTENT_V1.policyVersion,
60284
61012
  disclosureDigest: ASSISTANT_ENROLLMENT_DISCLOSURE_DIGEST,
@@ -60289,11 +61017,11 @@ var ASSISTANT_ENROLLMENT_DISCLOSURE_PROJECTION = Object.freeze({
60289
61017
  });
60290
61018
 
60291
61019
  // src/api/personal-assistant-lifecycle.ts
60292
- import { createHash as createHash56, randomUUID as randomUUID43 } from "crypto";
60293
- import { z as z46 } from "zod";
61020
+ import { createHash as createHash57, randomUUID as randomUUID44 } from "crypto";
61021
+ import { z as z48 } from "zod";
60294
61022
 
60295
61023
  // src/api/personal-assistant-db.ts
60296
- import { createHash as createHash55 } from "crypto";
61024
+ import { createHash as createHash56 } from "crypto";
60297
61025
  import { Pool } from "pg";
60298
61026
 
60299
61027
  // src/api/personal-assistant-schema.ts
@@ -60415,7 +61143,7 @@ function assistantDatabaseBindingFingerprint(value) {
60415
61143
  if (!database) {
60416
61144
  throw new AssistantDatabaseError("assistant_database_binding_invalid", "Personal Assistant database name is missing.");
60417
61145
  }
60418
- return createHash55("sha256").update(`${normalizedNeonHost(parsed.hostname)}\0${database}`).digest("hex");
61146
+ return createHash56("sha256").update(`${normalizedNeonHost(parsed.hostname)}\0${database}`).digest("hex");
60419
61147
  }
60420
61148
  function assistantDatabaseRole(value) {
60421
61149
  const role = decodeURIComponent(parseDatabaseUrl(value).username);
@@ -60557,10 +61285,10 @@ async function preflightAssistantRuntimeBinding() {
60557
61285
  }
60558
61286
 
60559
61287
  // src/api/personal-assistant-lifecycle.ts
60560
- var opaqueRef2 = z46.string().trim().regex(/^[a-z][A-Za-z0-9_-]{2,159}$/);
60561
- var digest4 = z46.string().regex(/^[a-f0-9]{64}$/);
60562
- var isoTimestamp3 = z46.string().datetime({ offset: true });
60563
- var AssistantLifecycleOperationSchema = z46.enum([
61288
+ var opaqueRef2 = z48.string().trim().regex(/^[a-z][A-Za-z0-9_-]{2,159}$/);
61289
+ var digest4 = z48.string().regex(/^[a-f0-9]{64}$/);
61290
+ var isoTimestamp3 = z48.string().datetime({ offset: true });
61291
+ var AssistantLifecycleOperationSchema = z48.enum([
60564
61292
  "export_data",
60565
61293
  "remove_recipient",
60566
61294
  "withdraw_consent",
@@ -60572,7 +61300,7 @@ var AssistantLifecycleOperationSchema = z46.enum([
60572
61300
  "detach_number",
60573
61301
  "release_number"
60574
61302
  ]);
60575
- var AssistantLifecycleTargetKindSchema = z46.enum([
61303
+ var AssistantLifecycleTargetKindSchema = z48.enum([
60576
61304
  "account",
60577
61305
  "recipient",
60578
61306
  "consent",
@@ -60607,24 +61335,24 @@ var ASSISTANT_LIFECYCLE_CONFIRMATION_PHRASES = Object.freeze({
60607
61335
  detach_number: "DETACH NUMBER",
60608
61336
  release_number: "RELEASE NUMBER"
60609
61337
  });
60610
- var AssistantLifecyclePreviewRequestSchema = z46.object({
61338
+ var AssistantLifecyclePreviewRequestSchema = z48.object({
60611
61339
  operation: AssistantLifecycleOperationSchema,
60612
- target: z46.object({ kind: AssistantLifecycleTargetKindSchema, targetRef: opaqueRef2 }).strict(),
60613
- reason: z46.string().trim().min(3).max(240).optional()
61340
+ target: z48.object({ kind: AssistantLifecycleTargetKindSchema, targetRef: opaqueRef2 }).strict(),
61341
+ reason: z48.string().trim().min(3).max(240).optional()
60614
61342
  }).strict().superRefine((value, context) => {
60615
61343
  if (TARGET_BY_OPERATION[value.operation] !== value.target.kind) {
60616
61344
  context.addIssue({ code: "custom", path: ["target", "kind"], message: "target kind does not match lifecycle operation" });
60617
61345
  }
60618
61346
  });
60619
- var AssistantLifecycleAffectedGroupSchema = z46.object({
60620
- count: z46.number().int().nonnegative().max(1e6),
60621
- refs: z46.array(opaqueRef2).max(50),
60622
- truncated: z46.boolean()
61347
+ var AssistantLifecycleAffectedGroupSchema = z48.object({
61348
+ count: z48.number().int().nonnegative().max(1e6),
61349
+ refs: z48.array(opaqueRef2).max(50),
61350
+ truncated: z48.boolean()
60623
61351
  }).strict().superRefine((value, context) => {
60624
61352
  if (value.refs.length > value.count) context.addIssue({ code: "custom", path: ["refs"], message: "references cannot exceed count" });
60625
61353
  if (!value.truncated && value.refs.length !== value.count) context.addIssue({ code: "custom", path: ["refs"], message: "complete impact groups must include every reference" });
60626
61354
  });
60627
- var AssistantLifecycleImpactSchema = z46.object({
61355
+ var AssistantLifecycleImpactSchema = z48.object({
60628
61356
  schedules: AssistantLifecycleAffectedGroupSchema,
60629
61357
  grants: AssistantLifecycleAffectedGroupSchema,
60630
61358
  conversations: AssistantLifecycleAffectedGroupSchema,
@@ -60634,21 +61362,21 @@ var AssistantLifecycleImpactSchema = z46.object({
60634
61362
  connections: AssistantLifecycleAffectedGroupSchema,
60635
61363
  numbers: AssistantLifecycleAffectedGroupSchema
60636
61364
  }).strict();
60637
- var AssistantLifecycleMinimumAuditSchema = z46.object({
60638
- category: z46.enum(["consent", "suppression", "approval", "receipt", "audit", "registration", "released_number"]),
60639
- reason: z46.string().trim().min(3).max(160),
61365
+ var AssistantLifecycleMinimumAuditSchema = z48.object({
61366
+ category: z48.enum(["consent", "suppression", "approval", "receipt", "audit", "registration", "released_number"]),
61367
+ reason: z48.string().trim().min(3).max(160),
60640
61368
  retainedUntil: isoTimestamp3.nullable()
60641
61369
  }).strict();
60642
- var AssistantLifecyclePreviewSchema = z46.object({
61370
+ var AssistantLifecyclePreviewSchema = z48.object({
60643
61371
  lifecycleRef: opaqueRef2,
60644
61372
  operation: AssistantLifecycleOperationSchema,
60645
- target: z46.object({ kind: AssistantLifecycleTargetKindSchema, targetRef: opaqueRef2 }).strict(),
60646
- state: z46.literal("awaiting_confirmation"),
61373
+ target: z48.object({ kind: AssistantLifecycleTargetKindSchema, targetRef: opaqueRef2 }).strict(),
61374
+ state: z48.literal("awaiting_confirmation"),
60647
61375
  previewDigest: digest4,
60648
- confirmationPhrase: z46.string().min(3).max(64),
60649
- irreversible: z46.boolean(),
61376
+ confirmationPhrase: z48.string().min(3).max(64),
61377
+ irreversible: z48.boolean(),
60650
61378
  impact: AssistantLifecycleImpactSchema,
60651
- minimumAudit: z46.array(AssistantLifecycleMinimumAuditSchema).min(1).max(10),
61379
+ minimumAudit: z48.array(AssistantLifecycleMinimumAuditSchema).min(1).max(10),
60652
61380
  createdAt: isoTimestamp3,
60653
61381
  expiresAt: isoTimestamp3
60654
61382
  }).strict().superRefine((value, context) => {
@@ -60659,30 +61387,30 @@ var AssistantLifecyclePreviewSchema = z46.object({
60659
61387
  context.addIssue({ code: "custom", path: ["expiresAt"], message: "preview must expire after creation" });
60660
61388
  }
60661
61389
  });
60662
- var AssistantLifecycleConfirmationSchema = z46.object({
61390
+ var AssistantLifecycleConfirmationSchema = z48.object({
60663
61391
  previewDigest: digest4,
60664
- confirmationPhrase: z46.string().min(3).max(64),
60665
- acknowledgeIrreversible: z46.boolean()
61392
+ confirmationPhrase: z48.string().min(3).max(64),
61393
+ acknowledgeIrreversible: z48.boolean()
60666
61394
  }).strict();
60667
- var AssistantLifecycleReconciliationItemSchema = z46.object({
61395
+ var AssistantLifecycleReconciliationItemSchema = z48.object({
60668
61396
  reconciliationRef: opaqueRef2,
60669
- kind: z46.enum(["provider_disconnect", "provider_number_detach", "provider_number_release", "artifact_purge", "memory_purge"]),
61397
+ kind: z48.enum(["provider_disconnect", "provider_number_detach", "provider_number_release", "artifact_purge", "memory_purge"]),
60670
61398
  targetRef: opaqueRef2,
60671
- state: z46.enum(["awaiting_provider", "pending_cleanup", "outcome_unknown"]),
60672
- retrySafety: z46.enum(["reconcile_first", "operator_only", "not_retryable"]),
60673
- nextAction: z46.string().trim().min(3).max(160)
61399
+ state: z48.enum(["awaiting_provider", "pending_cleanup", "outcome_unknown"]),
61400
+ retrySafety: z48.enum(["reconcile_first", "operator_only", "not_retryable"]),
61401
+ nextAction: z48.string().trim().min(3).max(160)
60674
61402
  }).strict();
60675
- var AssistantLifecycleReceiptSchema = z46.object({
61403
+ var AssistantLifecycleReceiptSchema = z48.object({
60676
61404
  lifecycleRef: opaqueRef2,
60677
61405
  operation: AssistantLifecycleOperationSchema,
60678
- target: z46.object({ kind: AssistantLifecycleTargetKindSchema, targetRef: opaqueRef2 }).strict(),
60679
- state: z46.enum(["completed", "reconciliation_required", "cancelled", "failed"]),
61406
+ target: z48.object({ kind: AssistantLifecycleTargetKindSchema, targetRef: opaqueRef2 }).strict(),
61407
+ state: z48.enum(["completed", "reconciliation_required", "cancelled", "failed"]),
60680
61408
  previewDigest: digest4,
60681
61409
  paused: AssistantLifecycleImpactSchema,
60682
- deleted: z46.object({ categories: z46.array(z46.string().regex(/^[a-z][a-z0-9_]{2,63}$/)).max(20), count: z46.number().int().nonnegative() }).strict(),
61410
+ deleted: z48.object({ categories: z48.array(z48.string().regex(/^[a-z][a-z0-9_]{2,63}$/)).max(20), count: z48.number().int().nonnegative() }).strict(),
60683
61411
  exportRef: opaqueRef2.nullable(),
60684
- minimumAudit: z46.array(AssistantLifecycleMinimumAuditSchema).min(1).max(10),
60685
- unresolved: z46.array(AssistantLifecycleReconciliationItemSchema).max(25),
61412
+ minimumAudit: z48.array(AssistantLifecycleMinimumAuditSchema).min(1).max(10),
61413
+ unresolved: z48.array(AssistantLifecycleReconciliationItemSchema).max(25),
60686
61414
  irreversibleAt: isoTimestamp3.nullable(),
60687
61415
  completedAt: isoTimestamp3
60688
61416
  }).strict().superRefine((value, context) => {
@@ -60703,7 +61431,7 @@ var AssistantLifecycleError = class extends Error {
60703
61431
  };
60704
61432
 
60705
61433
  // src/api/personal-assistant-service.ts
60706
- import { createHash as createHash57 } from "crypto";
61434
+ import { createHash as createHash58 } from "crypto";
60707
61435
  var PERSONAL_ASSISTANT_INTENT_ENVELOPE_VERSION = "assistant-intent-envelope.v1";
60708
61436
  var CONTROL_INTENTS = /* @__PURE__ */ new Set(["help", "status", "approve", "reject", "cancel"]);
60709
61437
  var EXPLICIT_TASK_INTENTS = /* @__PURE__ */ new Set([
@@ -60869,7 +61597,7 @@ function canonicalServiceJson(value) {
60869
61597
  });
60870
61598
  }
60871
61599
  function serviceDigest(value) {
60872
- return createHash57("sha256").update(canonicalServiceJson(value)).digest("hex");
61600
+ return createHash58("sha256").update(canonicalServiceJson(value)).digest("hex");
60873
61601
  }
60874
61602
  function serviceReceipt(idempotencyKey4, requestDigest2, occurredAt, state2, result3, error = null) {
60875
61603
  const receiptRef = `receipt_${serviceDigest({ idempotencyKey: idempotencyKey4, requestDigest: requestDigest2 }).slice(0, 32)}`;
@@ -62293,10 +63021,10 @@ function getPersonalAssistantService() {
62293
63021
 
62294
63022
  // src/api/twilio-webhook-routes.ts
62295
63023
  import twilio3 from "twilio";
62296
- import { Hono as Hono40 } from "hono";
63024
+ import { Hono as Hono41 } from "hono";
62297
63025
 
62298
63026
  // src/api/personal-assistant-observability.ts
62299
- import { createHash as createHash58 } from "crypto";
63027
+ import { createHash as createHash59 } from "crypto";
62300
63028
  var OPAQUE_TRACE_REF = /^trace_[A-Za-z0-9_-]{8,128}$/u;
62301
63029
  var KINDS = /* @__PURE__ */ new Set([
62302
63030
  "purchase_unknown",
@@ -62772,7 +63500,7 @@ function handlerForRuntime(runtime, kind) {
62772
63500
  return createTwilioWebhookHandler(kind === "inbound" ? { ...shared, handleInbound: runtime.inboundAdmissionService ? createTwilioInboundAdmissionHandler(runtime.inboundAdmissionService) : createTwilioInboundSmsHandler(runtime.messagingService) } : { ...shared, handleStatus: createTwilioDeliveryStatusHandler(runtime.messagingService) });
62773
63501
  }
62774
63502
  function buildTwilioWebhookApp(resolveRuntime) {
62775
- const app2 = new Hono40();
63503
+ const app2 = new Hono41();
62776
63504
  app2.get("/health", (c) => c.json({ ok: true, component: "twilio-webhook-boundary" }));
62777
63505
  for (const [path5, kind] of [["/inbound", "inbound"], ["/status", "status"]]) {
62778
63506
  app2.post(path5, async (c) => {
@@ -62993,7 +63721,7 @@ function payloadWithout(input, ...keys) {
62993
63721
  return Object.fromEntries(Object.entries(input).filter(([key3, value]) => !omitted.has(key3) && value !== void 0));
62994
63722
  }
62995
63723
  function personalAssistantMessagingServiceReviewDigest(review) {
62996
- return createHash59("sha256").update(JSON.stringify({
63724
+ return createHash60("sha256").update(JSON.stringify({
62997
63725
  schemaVersion: "assistant-messaging-service-review.v1",
62998
63726
  numberRef: review.numberRef,
62999
63727
  connectionRef: review.connectionRef,
@@ -63127,7 +63855,7 @@ function ownerCaller(c) {
63127
63855
  throw new OwnerRouteError("not_authenticated", "Authentication is required.", 401);
63128
63856
  }
63129
63857
  if (ownerUserId2 <= 0n) throw new OwnerRouteError("not_authenticated", "Authentication is required.", 401);
63130
- const subjectRef = `owner_${createHash59("sha256").update(ownerUserId2.toString()).digest("hex").slice(0, 24)}`;
63858
+ const subjectRef = `owner_${createHash60("sha256").update(ownerUserId2.toString()).digest("hex").slice(0, 24)}`;
63131
63859
  return { kind: "owner", surface: "rest", ownerUserId: ownerUserId2, subjectRef };
63132
63860
  }
63133
63861
  function enrollmentRequesterBinding(c, caller2) {
@@ -63179,10 +63907,10 @@ function publicError2(error, requestRef) {
63179
63907
  } } };
63180
63908
  }
63181
63909
  function buildPersonalAssistantOwnerRoutes(options) {
63182
- const app2 = new Hono41();
63910
+ const app2 = new Hono42();
63183
63911
  const now = options.now ?? (() => /* @__PURE__ */ new Date());
63184
- const nextRequestRef = options.requestRef ?? (() => `request_${randomUUID44().replaceAll("-", "")}`);
63185
- const route = (method, path5, mutating, call) => {
63912
+ const nextRequestRef = options.requestRef ?? (() => `request_${randomUUID45().replaceAll("-", "")}`);
63913
+ const route = (method, path5, mutating, call2) => {
63186
63914
  app2[method](path5, async (c) => {
63187
63915
  const requestRef = nextRequestRef();
63188
63916
  try {
@@ -63190,7 +63918,7 @@ function buildPersonalAssistantOwnerRoutes(options) {
63190
63918
  const input = mutating ? await jsonBody(c) : pageInput(c);
63191
63919
  input.idempotencyKey = requestIdentity(c, requestRef, mutating);
63192
63920
  const service = options.service();
63193
- const result3 = servicePayload(await call(service, caller2, input, c));
63921
+ const result3 = servicePayload(await call2(service, caller2, input, c));
63194
63922
  const body3 = { data: result3.data, ...result3.receipt ? { receipt: result3.receipt } : {}, meta: {
63195
63923
  request_ref: requestRef,
63196
63924
  projection_version: PERSONAL_ASSISTANT_OWNER_PROJECTION_VERSION,
@@ -63235,10 +63963,10 @@ function buildPersonalAssistantOwnerRoutes(options) {
63235
63963
  idempotencyKey: i.idempotencyKey,
63236
63964
  assistant: payloadWithout(i)
63237
63965
  }));
63238
- const contextRoute = (method, path5, mutating, names, call) => {
63966
+ const contextRoute = (method, path5, mutating, names, call2) => {
63239
63967
  route(method, path5, mutating, (service, caller2, input, context) => {
63240
63968
  for (const name of names) input[name] = opaqueRef3(context, name);
63241
- return call(service, caller2, input, context);
63969
+ return call2(service, caller2, input, context);
63242
63970
  });
63243
63971
  };
63244
63972
  contextRoute("get", "/lifecycle/:lifecycleRef", false, ["lifecycleRef"], (s, c, i) => s.getDataLifecycle(c, i));
@@ -63456,8 +64184,8 @@ function buildPersonalAssistantOwnerRoutes(options) {
63456
64184
  var personalAssistantOwnerApp = buildPersonalAssistantOwnerRoutes({ service: getPersonalAssistantService });
63457
64185
 
63458
64186
  // src/api/personal-assistant-browser-handoff-routes.ts
63459
- import { randomUUID as randomUUID45 } from "crypto";
63460
- import { Hono as Hono42 } from "hono";
64187
+ import { randomUUID as randomUUID46 } from "crypto";
64188
+ import { Hono as Hono43 } from "hono";
63461
64189
  var PERSONAL_ASSISTANT_BROWSER_HANDOFF_PROJECTION_VERSION = "assistant-browser-handoff.v1";
63462
64190
  var OPAQUE_REF2 = /^[a-z][a-z0-9]{1,31}_[A-Za-z0-9_-]{3,160}$/;
63463
64191
  var IDEMPOTENCY_KEY2 = /^[A-Za-z0-9._~:/+-]{8,240}$/;
@@ -63567,9 +64295,9 @@ function controlUrl(raw) {
63567
64295
  return url2;
63568
64296
  }
63569
64297
  function buildPersonalAssistantBrowserHandoffRoutes(options) {
63570
- const app2 = new Hono42();
64298
+ const app2 = new Hono43();
63571
64299
  const now = options.now ?? (() => /* @__PURE__ */ new Date());
63572
- const nextRequestRef = options.requestRef ?? (() => `request_${randomUUID45().replaceAll("-", "")}`);
64300
+ const nextRequestRef = options.requestRef ?? (() => `request_${randomUUID46().replaceAll("-", "")}`);
63573
64301
  const json = async (c, operation, created = false) => {
63574
64302
  const requestRef = nextRequestRef();
63575
64303
  try {
@@ -63657,8 +64385,8 @@ function buildPersonalAssistantBrowserHandoffRoutes(options) {
63657
64385
  }
63658
64386
 
63659
64387
  // src/api/personal-assistant-browser-profile-routes.ts
63660
- import { randomUUID as randomUUID46 } from "crypto";
63661
- import { Hono as Hono43 } from "hono";
64388
+ import { randomUUID as randomUUID47 } from "crypto";
64389
+ import { Hono as Hono44 } from "hono";
63662
64390
  var PERSONAL_ASSISTANT_BROWSER_PROFILE_PROJECTION_VERSION = "assistant-browser-profile.v1";
63663
64391
  var IDEMPOTENCY_KEY3 = /^[A-Za-z0-9._~:/+-]{8,240}$/;
63664
64392
  var OPAQUE_REF3 = /^[a-z][a-z0-9]{1,31}_[A-Za-z0-9_-]{3,160}$/;
@@ -63817,10 +64545,10 @@ function publicError4(error, requestRef) {
63817
64545
  };
63818
64546
  }
63819
64547
  function buildPersonalAssistantBrowserProfileRoutes(options) {
63820
- const app2 = new Hono43();
64548
+ const app2 = new Hono44();
63821
64549
  const now = options.now ?? (() => /* @__PURE__ */ new Date());
63822
64550
  const healthStaleAfterMs = options.healthStaleAfterMs ?? 15 * 6e4;
63823
- const requestRef = options.requestRef ?? (() => `request_${randomUUID46().replaceAll("-", "")}`);
64551
+ const requestRef = options.requestRef ?? (() => `request_${randomUUID47().replaceAll("-", "")}`);
63824
64552
  const respond = async (c, operation, created = false) => {
63825
64553
  const ref6 = requestRef();
63826
64554
  try {
@@ -63903,10 +64631,10 @@ function buildPersonalAssistantBrowserProfileRoutes(options) {
63903
64631
  }
63904
64632
 
63905
64633
  // src/api/personal-assistant-browser-production.ts
63906
- import { createHash as createHash63, randomUUID as randomUUID51 } from "crypto";
64634
+ import { createHash as createHash64, randomUUID as randomUUID52 } from "crypto";
63907
64635
 
63908
64636
  // src/api/personal-assistant-browser-handoff-store.ts
63909
- import { createHmac as createHmac12, randomUUID as randomUUID47 } from "crypto";
64637
+ import { createHmac as createHmac12, randomUUID as randomUUID48 } from "crypto";
63910
64638
  var BrowserHandoffStoreError = class extends Error {
63911
64639
  constructor(code, status) {
63912
64640
  super(code);
@@ -63994,14 +64722,14 @@ function createPostgresPersonalAssistantBrowserHandoffStore(options) {
63994
64722
  [row.owner_user_id, row.handoff_id, mode, now().toISOString()]
63995
64723
  );
63996
64724
  if (existing.rows[0]) return existing.rows[0].claim_ref;
63997
- const claimRef = `claim_${randomUUID47().replaceAll("-", "")}`;
64725
+ const claimRef = `claim_${randomUUID48().replaceAll("-", "")}`;
63998
64726
  const ceiling = Math.min(new Date(row.expires_at).getTime(), now().getTime() + (mode === "control" ? controlLifetimeMs : claimLifetimeMs));
63999
64727
  if (ceiling <= now().getTime()) throw new BrowserHandoffStoreError("handoff_expired", 409);
64000
64728
  await client2.query(
64001
64729
  `INSERT INTO assistant.browser_handoff_claims
64002
64730
  (owner_user_id,id,public_id,handoff_id,mode,state,claim_digest,expires_at,created_at)
64003
64731
  VALUES ($1,$2,$3,$4,$5,'available',$6,$7::timestamptz,$8::timestamptz)`,
64004
- [row.owner_user_id, randomUUID47(), claimRef, row.handoff_id, mode, claimDigest(claimRef), new Date(ceiling).toISOString(), now().toISOString()]
64732
+ [row.owner_user_id, randomUUID48(), claimRef, row.handoff_id, mode, claimDigest(claimRef), new Date(ceiling).toISOString(), now().toISOString()]
64005
64733
  );
64006
64734
  return claimRef;
64007
64735
  }
@@ -64023,7 +64751,7 @@ function createPostgresPersonalAssistantBrowserHandoffStore(options) {
64023
64751
  async function create(input) {
64024
64752
  return transaction2(async (client2) => {
64025
64753
  const owner5 = positiveOwner(input.ownerUserId);
64026
- const takeoverRef = `takeover_${randomUUID47().replaceAll("-", "")}`;
64754
+ const takeoverRef = `takeover_${randomUUID48().replaceAll("-", "")}`;
64027
64755
  const createdAt = now();
64028
64756
  const expiresAt = new Date(createdAt.getTime() + absoluteLifetimeMs);
64029
64757
  const inserted = await client2.query(
@@ -64038,7 +64766,7 @@ function createPostgresPersonalAssistantBrowserHandoffStore(options) {
64038
64766
  ) ${HANDOFF_SELECT} JOIN inserted ON inserted.id=handoff.id WHERE handoff.owner_user_id=$1`,
64039
64767
  [
64040
64768
  owner5,
64041
- randomUUID47(),
64769
+ randomUUID48(),
64042
64770
  takeoverRef,
64043
64771
  ref(input.profileRef, PROFILE_REF),
64044
64772
  ref(input.loginBindingRef, LOGIN_REF),
@@ -64197,7 +64925,7 @@ function createPostgresPersonalAssistantBrowserHandoffStore(options) {
64197
64925
  }
64198
64926
 
64199
64927
  // src/api/personal-assistant-browser-profile-store.ts
64200
- import { createHash as createHash60, createHmac as createHmac13, randomUUID as randomUUID48 } from "crypto";
64928
+ import { createHash as createHash61, createHmac as createHmac13, randomUUID as randomUUID49 } from "crypto";
64201
64929
  import { domainToASCII } from "url";
64202
64930
  var PersonalAssistantBrowserProfileStoreError = class extends Error {
64203
64931
  constructor(code, message = code, status = code.endsWith("revision_conflict") ? 409 : code.endsWith("input_rejected") ? 400 : 404) {
@@ -64239,7 +64967,7 @@ function iso2(value) {
64239
64967
  return value instanceof Date ? value.toISOString() : new Date(value).toISOString();
64240
64968
  }
64241
64969
  function newRef(prefix) {
64242
- return `${prefix}_${randomUUID48().replaceAll("-", "")}`;
64970
+ return `${prefix}_${randomUUID49().replaceAll("-", "")}`;
64243
64971
  }
64244
64972
  function deterministicRef(prefix, key3, identity) {
64245
64973
  return `${prefix}_${createHmac13("sha256", key3).update(`assistant.${prefix}\0${identity}`).digest("hex").slice(0, 32)}`;
@@ -64327,7 +65055,7 @@ function deriveBrowserProviderNamespaceDigest(keyInput, ownerUserId2, profileRef
64327
65055
  }
64328
65056
  function digestEvidence(value) {
64329
65057
  const canonical3 = JSON.stringify(value, (_key, entry) => entry && typeof entry === "object" && !Array.isArray(entry) ? Object.fromEntries(Object.entries(entry).sort(([a], [b]) => a.localeCompare(b))) : entry);
64330
- return createHash60("sha256").update(canonical3).digest("hex");
65058
+ return createHash61("sha256").update(canonical3).digest("hex");
64331
65059
  }
64332
65060
  function exactCapabilityList(value, allowed) {
64333
65061
  if (!Array.isArray(value)) return [];
@@ -64442,7 +65170,7 @@ function createPostgresPersonalAssistantBrowserProfileStore(options) {
64442
65170
  inserted.status,inserted.capability_summary,inserted.revision,inserted.last_verified_at,inserted.verification_digest,
64443
65171
  inserted.created_at,inserted.updated_at FROM inserted`, [
64444
65172
  owner5,
64445
- randomUUID48(),
65173
+ randomUUID49(),
64446
65174
  profileRef,
64447
65175
  input.assistantRef,
64448
65176
  label2,
@@ -64521,7 +65249,7 @@ function createPostgresPersonalAssistantBrowserProfileStore(options) {
64521
65249
  inserted.identity_label_masked,inserted.status,inserted.capability_summary,inserted.revision,inserted.last_verified_at,
64522
65250
  inserted.verification_digest,inserted.created_at,inserted.updated_at FROM inserted`, [
64523
65251
  owner5,
64524
- randomUUID48(),
65252
+ randomUUID49(),
64525
65253
  ref6,
64526
65254
  assertRef(input.profileRef, PROFILE_REF2, "profileRef"),
64527
65255
  canonicalizeBrowserDomain(input.canonicalDomain),
@@ -64620,7 +65348,7 @@ function createPostgresPersonalAssistantBrowserProfileStore(options) {
64620
65348
  verification.observed_status,verification.evidence_digest,verification.evidence_summary,verification.verified_at,
64621
65349
  verification.created_at FROM verification`, [
64622
65350
  owner5,
64623
- randomUUID48(),
65351
+ randomUUID49(),
64624
65352
  newRef("bpver"),
64625
65353
  profile.rows[0].id,
64626
65354
  bindingId,
@@ -64678,7 +65406,7 @@ function createPostgresPersonalAssistantBrowserProfileStore(options) {
64678
65406
  FROM assistant.assistants assistant WHERE assistant.owner_user_id=$1 AND assistant.public_id=$4 AND assistant.deleted_at IS NULL
64679
65407
  ON CONFLICT (owner_user_id,public_id) DO NOTHING`, [
64680
65408
  owner5,
64681
- randomUUID48(),
65409
+ randomUUID49(),
64682
65410
  profileRef,
64683
65411
  input.assistantRef,
64684
65412
  assertSafeText(input.displayLabel ?? "Imported browser profile", "displayLabel", 120),
@@ -64699,7 +65427,7 @@ function createPostgresPersonalAssistantBrowserProfileStore(options) {
64699
65427
  VALUES ($1,$2,$3,$4,$5,$6,$7,$8::jsonb,$9::timestamptz,$9::timestamptz)
64700
65428
  ON CONFLICT (owner_user_id,public_id) DO NOTHING`, [
64701
65429
  owner5,
64702
- randomUUID48(),
65430
+ randomUUID49(),
64703
65431
  bindingRef,
64704
65432
  existing.rows[0].id,
64705
65433
  domain,
@@ -64733,7 +65461,7 @@ function createPostgresPersonalAssistantBrowserProfileStore(options) {
64733
65461
  }
64734
65462
 
64735
65463
  // src/api/personal-assistant-idempotency-store.ts
64736
- import { createHash as createHash61, randomUUID as randomUUID49 } from "crypto";
65464
+ import { createHash as createHash62, randomUUID as randomUUID50 } from "crypto";
64737
65465
  var PersonalAssistantIdempotencyConflictError = class extends Error {
64738
65466
  code = "idempotency_conflict";
64739
65467
  status = 409;
@@ -64762,7 +65490,7 @@ function jsonValue(value) {
64762
65490
  return JSON.parse(serialized);
64763
65491
  }
64764
65492
  function resultDigest(value) {
64765
- return createHash61("sha256").update(canonicalJson4(value)).digest("hex");
65493
+ return createHash62("sha256").update(canonicalJson4(value)).digest("hex");
64766
65494
  }
64767
65495
  function timestamp3(value) {
64768
65496
  return value instanceof Date ? value.toISOString() : new Date(value).toISOString();
@@ -64774,7 +65502,7 @@ function createPostgresPersonalAssistantIdempotencyStore(options = {}) {
64774
65502
  return Object.freeze({
64775
65503
  async run(input, work) {
64776
65504
  const ownerUserId2 = input.ownerUserId.toString();
64777
- const id2 = randomUUID49();
65505
+ const id2 = randomUUID50();
64778
65506
  const claim = await transaction2(async (client2) => {
64779
65507
  const inserted = await client2.query(`
64780
65508
  INSERT INTO assistant.owner_request_idempotency (
@@ -64816,8 +65544,8 @@ function createPostgresPersonalAssistantIdempotencyStore(options = {}) {
64816
65544
  ) VALUES ($1, $2, $3, 'system', 'assistant.idempotency.completed', $4, $5, $6, $7::jsonb, $8::timestamptz)
64817
65545
  `, [
64818
65546
  ownerUserId2,
64819
- randomUUID49(),
64820
- `audit_${randomUUID49()}`,
65547
+ randomUUID50(),
65548
+ `audit_${randomUUID50()}`,
64821
65549
  input.action,
64822
65550
  input.idempotencyKey,
64823
65551
  input.requestDigest,
@@ -64845,7 +65573,7 @@ function createPostgresPersonalAssistantIdempotencyStore(options = {}) {
64845
65573
  }
64846
65574
 
64847
65575
  // src/api/personal-assistant-browser-account-cleanup.ts
64848
- import { createHash as createHash62, randomUUID as randomUUID50 } from "crypto";
65576
+ import { createHash as createHash63, randomUUID as randomUUID51 } from "crypto";
64849
65577
  function positiveOwner2(value) {
64850
65578
  if (typeof value !== "bigint" || value <= 0n) throw new TypeError("positive ownerUserId is required");
64851
65579
  return value.toString();
@@ -64904,10 +65632,10 @@ function createPersonalAssistantBrowserAccountCleanup(options) {
64904
65632
  };
64905
65633
  return Object.freeze({
64906
65634
  schemaVersion: "assistant-browser-account-cleanup.v1",
64907
- cleanupRef: `cleanup_${randomUUID50().replaceAll("-", "")}`,
65635
+ cleanupRef: `cleanup_${randomUUID51().replaceAll("-", "")}`,
64908
65636
  state: "confirmed",
64909
65637
  ...evidence,
64910
- evidenceDigest: createHash62("sha256").update(JSON.stringify(evidence)).digest("hex")
65638
+ evidenceDigest: createHash63("sha256").update(JSON.stringify(evidence)).digest("hex")
64911
65639
  });
64912
65640
  };
64913
65641
  }
@@ -64934,7 +65662,7 @@ var VERIFIED_BROWSER_CAPABILITIES = Object.freeze([
64934
65662
  "download"
64935
65663
  ]);
64936
65664
  function digest5(value) {
64937
- return createHash63("sha256").update(JSON.stringify(value, (_key, entry) => {
65665
+ return createHash64("sha256").update(JSON.stringify(value, (_key, entry) => {
64938
65666
  if (typeof entry === "bigint") return entry.toString();
64939
65667
  if (!entry || typeof entry !== "object" || Array.isArray(entry)) return entry;
64940
65668
  return Object.fromEntries(Object.entries(entry).sort(([a], [b]) => a.localeCompare(b)));
@@ -64966,13 +65694,13 @@ function handoffError(error) {
64966
65694
  }
64967
65695
  function receipt2(data, replayed, revision = 1) {
64968
65696
  return { data, receipt: {
64969
- receiptRef: `receipt_${randomUUID51().replaceAll("-", "")}`,
65697
+ receiptRef: `receipt_${randomUUID52().replaceAll("-", "")}`,
64970
65698
  state: replayed ? "reused" : "confirmed",
64971
65699
  revision
64972
65700
  } };
64973
65701
  }
64974
65702
  function handoffReceipt(data, replayed) {
64975
- return { data, receipt: { receiptRef: `receipt_${randomUUID51().replaceAll("-", "")}`, state: replayed ? "reused" : "confirmed" } };
65703
+ return { data, receipt: { receiptRef: `receipt_${randomUUID52().replaceAll("-", "")}`, state: replayed ? "reused" : "confirmed" } };
64976
65704
  }
64977
65705
  function loginHealth(status) {
64978
65706
  return status === "deleted" ? "revoked" : status;
@@ -65084,7 +65812,7 @@ function createPersonalAssistantBrowserProductionDependencies(options) {
65084
65812
  async createProfile(ownerUserId2, input) {
65085
65813
  try {
65086
65814
  const result3 = await run(ownerUserId2, "assistant.browser-profile.create", input.idempotencyKey, input, async () => {
65087
- const profileRef = `bprof_${randomUUID51().replaceAll("-", "")}`;
65815
+ const profileRef = `bprof_${randomUUID52().replaceAll("-", "")}`;
65088
65816
  const scope = { ownerRef: personalAssistantBrowserOwnerRef(ownerUserId2), profileRef };
65089
65817
  await runtime.ensureProfile(scope);
65090
65818
  try {
@@ -65147,7 +65875,7 @@ function createPersonalAssistantBrowserProductionDependencies(options) {
65147
65875
  const result3 = await run(ownerUserId2, "assistant.browser-login.begin", input.idempotencyKey, input, async () => {
65148
65876
  const profile = await profiles2.getProfile(ownerUserId2, input.profileRef);
65149
65877
  if (!profile) throw new PersonalAssistantBrowserProfileStoreError("browser_profile_not_found");
65150
- const loginBindingRef = `blogin_${randomUUID51().replaceAll("-", "")}`;
65878
+ const loginBindingRef = `blogin_${randomUUID52().replaceAll("-", "")}`;
65151
65879
  const session = await openLoginSetup(ownerUserId2, profile.profileRef, loginBindingRef, input.canonicalDomain);
65152
65880
  try {
65153
65881
  const binding = await profiles2.createLoginBinding({
@@ -65502,19 +66230,19 @@ var personalAssistantBrowserHandoffApp = buildPersonalAssistantBrowserHandoffRou
65502
66230
  });
65503
66231
 
65504
66232
  // src/api/personal-assistant-worker-composition.ts
65505
- import { Hono as Hono45 } from "hono";
66233
+ import { Hono as Hono46 } from "hono";
65506
66234
 
65507
66235
  // src/api/personal-assistant-worker-routes.ts
65508
- import { createHash as createHash64, createPublicKey, verify as verify2 } from "crypto";
65509
- import { Hono as Hono44 } from "hono";
65510
- import { z as z47 } from "zod";
66236
+ import { createHash as createHash65, createPublicKey, verify as verify2 } from "crypto";
66237
+ import { Hono as Hono45 } from "hono";
66238
+ import { z as z49 } from "zod";
65511
66239
  var PERSONAL_ASSISTANT_WORKER_API_PREFIX = "/api/private/v1/assistant-worker";
65512
66240
  var PERSONAL_ASSISTANT_WORKER_SIGNATURE_VERSION = "assistant-worker-signature.v1";
65513
66241
  var PERSONAL_ASSISTANT_WORKER_MAX_BODY_BYTES = 262144;
65514
66242
  var PERSONAL_ASSISTANT_WORKER_SIGNATURE_TTL_MS = 6e4;
65515
66243
  var PERSONAL_ASSISTANT_WORKER_IDENTITY_TTL_MS = 3e5;
65516
- var OPAQUE_REF4 = z47.string().regex(/^[a-z][a-z0-9]{1,31}_[A-Za-z0-9_-]{3,160}$/);
65517
- var ISO_TIME = z47.string().datetime({ offset: true });
66244
+ var OPAQUE_REF4 = z49.string().regex(/^[a-z][a-z0-9]{1,31}_[A-Za-z0-9_-]{3,160}$/);
66245
+ var ISO_TIME = z49.string().datetime({ offset: true });
65518
66246
  var FORBIDDEN_AUTHORITY_KEY2 = /^(?:owner(?:User)?Id|owner_user_id|caller|subjectRef|table|tableName|sql|query|statement)$/i;
65519
66247
  var PRIVATE_KEY2 = /(?:accessToken|refreshToken|authToken|accountSid|providerSid|privateKey|clientSecret|databaseUrl|signedUrl)/i;
65520
66248
  var AssistantWorkerRouteError = class extends Error {
@@ -65535,11 +66263,11 @@ function canonicalJson5(value) {
65535
66263
  return JSON.stringify(value);
65536
66264
  }
65537
66265
  function personalAssistantWorkerBodyDigest(rawBody) {
65538
- return createHash64("sha256").update(rawBody, "utf8").digest("hex");
66266
+ return createHash65("sha256").update(rawBody, "utf8").digest("hex");
65539
66267
  }
65540
66268
  function personalAssistantPlanDigest(plan) {
65541
66269
  const { planRef: _planRef, planDigest: _planDigest, immutable: _immutable, createdAt: _createdAt, ...proposal } = plan;
65542
- return createHash64("sha256").update(canonicalJson5(proposal)).digest("hex");
66270
+ return createHash65("sha256").update(canonicalJson5(proposal)).digest("hex");
65543
66271
  }
65544
66272
  function personalAssistantWorkerSigningPayload(input) {
65545
66273
  return [
@@ -65563,7 +66291,7 @@ function inspectWorkerInput(value) {
65563
66291
  }
65564
66292
  }
65565
66293
  function strictObject(shape) {
65566
- return z47.object(shape).strict();
66294
+ return z49.object(shape).strict();
65567
66295
  }
65568
66296
  var BindingSchema = {
65569
66297
  executionRef: OPAQUE_REF4,
@@ -65573,25 +66301,25 @@ var BindingSchema = {
65573
66301
  };
65574
66302
  var RegistrationSchema = strictObject({
65575
66303
  idempotencyKey: IdempotencyKeySchema,
65576
- runtimeVersion: z47.string().trim().min(1).max(80),
65577
- capabilities: z47.array(z47.string().regex(/^[a-z][a-z0-9_.-]{1,80}$/)).max(100)
66304
+ runtimeVersion: z49.string().trim().min(1).max(80),
66305
+ capabilities: z49.array(z49.string().regex(/^[a-z][a-z0-9_.-]{1,80}$/)).max(100)
65578
66306
  });
65579
66307
  var HealthSchema = strictObject({ idempotencyKey: IdempotencyKeySchema, heartbeat: WorkerHeartbeatSchema });
65580
66308
  var SignedWorkerClaimSchema = strictObject({
65581
- schemaVersion: z47.literal("assistant-worker-claim-envelope.v1"),
66309
+ schemaVersion: z49.literal("assistant-worker-claim-envelope.v1"),
65582
66310
  keyRef: OPAQUE_REF4,
65583
66311
  createdAt: ISO_TIME,
65584
66312
  bodyDigest: DigestSchema,
65585
66313
  body: WorkerClaimSchema,
65586
- signature: z47.string().regex(/^[A-Za-z0-9_-]{40,160}$/)
66314
+ signature: z49.string().regex(/^[A-Za-z0-9_-]{40,160}$/)
65587
66315
  });
65588
66316
  var WakeSchema = strictObject({ ...BindingSchema, idempotencyKey: IdempotencyKeySchema });
65589
66317
  var CycleSchema = strictObject({ ...BindingSchema, idempotencyKey: IdempotencyKeySchema, cycle: CycleCommandSchema });
65590
66318
  var PlanSchema = strictObject({ ...BindingSchema, idempotencyKey: IdempotencyKeySchema, plan: AssistantPlanSchema });
65591
66319
  var PolicyLeaseRequestSchema = strictObject({
65592
- schemaVersion: z47.literal("assistant-policy-lease-request.v1"),
66320
+ schemaVersion: z49.literal("assistant-policy-lease-request.v1"),
65593
66321
  requestRef: OPAQUE_REF4,
65594
- requestNonce: z47.string().regex(/^[A-Za-z0-9_-]{32,128}$/),
66322
+ requestNonce: z49.string().regex(/^[A-Za-z0-9_-]{32,128}$/),
65595
66323
  ownerRef: OPAQUE_REF4,
65596
66324
  workerRef: OPAQUE_REF4,
65597
66325
  cycleRef: OPAQUE_REF4,
@@ -65603,27 +66331,27 @@ var PolicyLeaseRequestSchema = strictObject({
65603
66331
  planDigest: DigestSchema,
65604
66332
  stepRef: OPAQUE_REF4,
65605
66333
  actionDigest: DigestSchema,
65606
- operation: z47.string().min(1).max(160),
66334
+ operation: z49.string().min(1).max(160),
65607
66335
  argumentDigest: DigestSchema,
65608
66336
  connectionRef: OPAQUE_REF4,
65609
66337
  profileRef: OPAQUE_REF4,
65610
66338
  audienceDigest: DigestSchema.nullable(),
65611
- estimatedSpend: z47.object({ currency: z47.string().regex(/^[A-Z]{3}$/), amountMinor: z47.number().int().nonnegative().safe() }).strict().nullable(),
65612
- requestedLeaseSeconds: z47.number().int().min(1).max(300)
66339
+ estimatedSpend: z49.object({ currency: z49.string().regex(/^[A-Z]{3}$/), amountMinor: z49.number().int().nonnegative().safe() }).strict().nullable(),
66340
+ requestedLeaseSeconds: z49.number().int().min(1).max(300)
65613
66341
  });
65614
66342
  var SignedPolicyLeaseRequestSchema = strictObject({
65615
- schemaVersion: z47.literal("assistant-signed-worker-request.v1"),
66343
+ schemaVersion: z49.literal("assistant-signed-worker-request.v1"),
65616
66344
  keyRef: OPAQUE_REF4,
65617
66345
  createdAt: ISO_TIME,
65618
66346
  expiresAt: ISO_TIME,
65619
66347
  bodyDigest: DigestSchema,
65620
66348
  body: PolicyLeaseRequestSchema,
65621
- signature: z47.string().regex(/^[A-Za-z0-9_-]{40,160}$/)
66349
+ signature: z49.string().regex(/^[A-Za-z0-9_-]{40,160}$/)
65622
66350
  }).superRefine((value, context) => {
65623
66351
  const lifetime = Date.parse(value.expiresAt) - Date.parse(value.createdAt);
65624
66352
  if (lifetime <= 0 || lifetime > 6e4) context.addIssue({ code: "custom", path: ["expiresAt"], message: "signed worker requests must expire within one minute" });
65625
66353
  });
65626
- var MoneySchema = z47.object({ currency: z47.string().regex(/^[A-Z]{3}$/), amountMinor: z47.number().int().nonnegative().safe() }).strict();
66354
+ var MoneySchema = z49.object({ currency: z49.string().regex(/^[A-Z]{3}$/), amountMinor: z49.number().int().nonnegative().safe() }).strict();
65627
66355
  var ApprovalSuspensionSchema = strictObject({
65628
66356
  ...BindingSchema,
65629
66357
  idempotencyKey: IdempotencyKeySchema,
@@ -65638,8 +66366,8 @@ var ApprovalSuspensionSchema = strictObject({
65638
66366
  spendLimit: MoneySchema.nullable(),
65639
66367
  occurrenceRef: OPAQUE_REF4.nullable(),
65640
66368
  expiresAt: ISO_TIME,
65641
- nextAction: z47.string().trim().min(1).max(500),
65642
- prompt: z47.object({ web: z47.string().trim().min(1).max(1e3), sms: z47.string().trim().min(1).max(480).nullable() }).strict()
66369
+ nextAction: z49.string().trim().min(1).max(500),
66370
+ prompt: z49.object({ web: z49.string().trim().min(1).max(1e3), sms: z49.string().trim().min(1).max(480).nullable() }).strict()
65643
66371
  });
65644
66372
  var DurableApprovalSuspensionSchema = strictObject({
65645
66373
  approvalRef: OPAQUE_REF4,
@@ -65654,9 +66382,9 @@ var DurableApprovalSuspensionSchema = strictObject({
65654
66382
  spendLimit: MoneySchema.nullable(),
65655
66383
  occurrenceRef: OPAQUE_REF4.nullable(),
65656
66384
  expiresAt: ISO_TIME,
65657
- nextAction: z47.string().trim().min(1).max(500),
66385
+ nextAction: z49.string().trim().min(1).max(500),
65658
66386
  approvalReceiptRef: OPAQUE_REF4,
65659
- promptReceiptRefs: z47.array(OPAQUE_REF4).min(1).max(2)
66387
+ promptReceiptRefs: z49.array(OPAQUE_REF4).min(1).max(2)
65660
66388
  });
65661
66389
  var ApprovalResumeSchema = strictObject({
65662
66390
  ...BindingSchema,
@@ -65672,12 +66400,12 @@ var SettlementSchema = strictObject({
65672
66400
  idempotencyKey: IdempotencyKeySchema,
65673
66401
  allocationRef: OPAQUE_REF4,
65674
66402
  actionReceiptRef: OPAQUE_REF4,
65675
- settledMinor: z47.number().int().nonnegative().safe(),
65676
- currency: z47.string().regex(/^[A-Z]{3}$/)
66403
+ settledMinor: z49.number().int().nonnegative().safe(),
66404
+ currency: z49.string().regex(/^[A-Z]{3}$/)
65677
66405
  });
65678
66406
  function publicWorkerError(error) {
65679
66407
  if (error instanceof AssistantWorkerRouteError) return { status: error.status, body: { error: { code: error.code, message: error.message } } };
65680
- if (error instanceof z47.ZodError || error instanceof TypeError) return { status: 400, body: { error: { code: "worker_validation_failed", message: "The worker request is invalid." } } };
66408
+ if (error instanceof z49.ZodError || error instanceof TypeError) return { status: 400, body: { error: { code: "worker_validation_failed", message: "The worker request is invalid." } } };
65681
66409
  return { status: 500, body: { error: { code: "worker_route_failed", message: "The worker request could not be completed." } } };
65682
66410
  }
65683
66411
  function identityKey(identity, nonce) {
@@ -65693,7 +66421,7 @@ function verifyPolicyEnvelope(identity, envelope, at) {
65693
66421
  if (Date.parse(envelope.expiresAt) <= at.getTime() || Math.abs(at.getTime() - Date.parse(envelope.createdAt)) > 6e4) {
65694
66422
  throw new AssistantWorkerRouteError("worker_policy_request_expired", "The policy request has expired.", 401);
65695
66423
  }
65696
- const expectedDigest = createHash64("sha256").update(canonicalJson5(envelope.body)).digest("hex");
66424
+ const expectedDigest = createHash65("sha256").update(canonicalJson5(envelope.body)).digest("hex");
65697
66425
  if (expectedDigest !== envelope.bodyDigest) throw new AssistantWorkerRouteError("worker_policy_digest_mismatch", "The policy request digest does not match.", 401);
65698
66426
  const { signature, ...unsigned } = envelope;
65699
66427
  let valid = false;
@@ -65711,7 +66439,7 @@ function verifyClaimEnvelope(identity, envelope, at) {
65711
66439
  if (Math.abs(at.getTime() - Date.parse(envelope.createdAt)) > PERSONAL_ASSISTANT_WORKER_SIGNATURE_TTL_MS) {
65712
66440
  throw new AssistantWorkerRouteError("worker_claim_expired", "The worker claim has expired.", 401);
65713
66441
  }
65714
- const expectedDigest = createHash64("sha256").update(canonicalJson5(envelope.body)).digest("hex");
66442
+ const expectedDigest = createHash65("sha256").update(canonicalJson5(envelope.body)).digest("hex");
65715
66443
  if (expectedDigest !== envelope.bodyDigest) throw new AssistantWorkerRouteError("worker_claim_digest_mismatch", "The claim digest does not match.", 401);
65716
66444
  const { signature, ...unsigned } = envelope;
65717
66445
  let valid = false;
@@ -65733,7 +66461,7 @@ function workerCaller(identity, executionRef) {
65733
66461
  };
65734
66462
  }
65735
66463
  function buildPersonalAssistantWorkerRoutes(options) {
65736
- const app2 = new Hono44();
66464
+ const app2 = new Hono45();
65737
66465
  const now = options.now ?? (() => /* @__PURE__ */ new Date());
65738
66466
  const maxClockSkewMs = options.maxClockSkewMs ?? PERSONAL_ASSISTANT_WORKER_SIGNATURE_TTL_MS;
65739
66467
  const maxIdentityLifetimeMs = options.maxIdentityLifetimeMs ?? PERSONAL_ASSISTANT_WORKER_IDENTITY_TTL_MS;
@@ -65789,7 +66517,7 @@ function buildPersonalAssistantWorkerRoutes(options) {
65789
66517
  return c.json(mapped.body, mapped.status);
65790
66518
  }
65791
66519
  });
65792
- const route = (path5, schema, binding, call, rawResponse = false) => {
66520
+ const route = (path5, schema, binding, call2, rawResponse = false) => {
65793
66521
  app2.post(path5, async (c) => {
65794
66522
  try {
65795
66523
  const identity = c.get("assistantWorker");
@@ -65817,7 +66545,7 @@ function buildPersonalAssistantWorkerRoutes(options) {
65817
66545
  throw new AssistantWorkerRouteError("worker_binding_rejected", "The worker execution binding was not found.", 404);
65818
66546
  }
65819
66547
  }
65820
- const data = await call(identity, parsed);
66548
+ const data = await call2(identity, parsed);
65821
66549
  return c.json(rawResponse ? data : { data, meta: { signature_version: PERSONAL_ASSISTANT_WORKER_SIGNATURE_VERSION } }, 200);
65822
66550
  } catch (error) {
65823
66551
  const mapped = publicWorkerError(error);
@@ -65993,7 +66721,7 @@ var configuredWorkerGraph = null;
65993
66721
  function configurePersonalAssistantWorkerProduction(dependencies) {
65994
66722
  if (configuredWorkerGraph) throw new PersonalAssistantWorkerCompositionError("Personal assistant worker routes are already configured.");
65995
66723
  const routes = buildPersonalAssistantWorkerRoutes(composePersonalAssistantWorkerProduction(dependencies).routeOptions);
65996
- const graph = new Hono45();
66724
+ const graph = new Hono46();
65997
66725
  graph.route(PERSONAL_ASSISTANT_WORKER_API_PREFIX, routes);
65998
66726
  configuredWorkerGraph = graph;
65999
66727
  }
@@ -66001,7 +66729,7 @@ function personalAssistantWorkerProductionReadiness() {
66001
66729
  return Object.freeze({ configured: configuredWorkerGraph !== null, durablePortsRequired: true });
66002
66730
  }
66003
66731
  var personalAssistantWorkerProductionApp = (() => {
66004
- const app2 = new Hono45();
66732
+ const app2 = new Hono46();
66005
66733
  app2.get("/ready", (c) => {
66006
66734
  const readiness2 = personalAssistantWorkerProductionReadiness();
66007
66735
  return c.json(readiness2, readiness2.configured ? 200 : 503);
@@ -66014,12 +66742,12 @@ var personalAssistantWorkerProductionApp = (() => {
66014
66742
  })();
66015
66743
 
66016
66744
  // src/api/personal-assistant-admin-routes.ts
66017
- import { createHash as createHash66, createPublicKey as createPublicKey2 } from "crypto";
66018
- import { Hono as Hono46 } from "hono";
66019
- import { z as z48 } from "zod";
66745
+ import { createHash as createHash67, createPublicKey as createPublicKey2 } from "crypto";
66746
+ import { Hono as Hono47 } from "hono";
66747
+ import { z as z50 } from "zod";
66020
66748
 
66021
66749
  // src/api/personal-assistant-kill-controls.ts
66022
- import { createHash as createHash65, randomUUID as randomUUID52 } from "crypto";
66750
+ import { createHash as createHash66, randomUUID as randomUUID53 } from "crypto";
66023
66751
  var PERSONAL_ASSISTANT_KILL_SCOPES = [
66024
66752
  "global",
66025
66753
  "outbound",
@@ -66047,7 +66775,7 @@ function canonicalJson6(value) {
66047
66775
  return JSON.stringify(value);
66048
66776
  }
66049
66777
  function digest6(value) {
66050
- return createHash65("sha256").update(canonicalJson6(value)).digest("hex");
66778
+ return createHash66("sha256").update(canonicalJson6(value)).digest("hex");
66051
66779
  }
66052
66780
  function validateTarget(target) {
66053
66781
  if (!PERSONAL_ASSISTANT_KILL_SCOPES.includes(target.scope)) throw new PersonalAssistantKillControlError("invalid_kill_control", "Invalid kill-control scope.", 400);
@@ -66167,7 +66895,7 @@ var PostgresPersonalAssistantKillControlStore = class {
66167
66895
  const active = input.action === "activate";
66168
66896
  if (state2.active === active) throw new PersonalAssistantKillControlError("kill_state_conflict", "Kill control is already in the requested state.", 409);
66169
66897
  const revision = Number(state2.revision) + 1;
66170
- const receiptRef = `kill_receipt_${randomUUID52().replaceAll("-", "")}`;
66898
+ const receiptRef = `kill_receipt_${randomUUID53().replaceAll("-", "")}`;
66171
66899
  await client2.query(`UPDATE assistant.kill_switch_controls SET revision = $3, active = $4, reason_code = $5, actor_ref = $6, updated_at = $7
66172
66900
  WHERE scope = $1 AND target_key = $2`, [input.target.scope, input.target.targetKey, revision, active, input.reasonCode, input.actorRef, input.occurredAt]);
66173
66901
  const inserted = await client2.query(
@@ -66245,11 +66973,11 @@ var PersonalAssistantAdminRouteError = class extends Error {
66245
66973
  code;
66246
66974
  status;
66247
66975
  };
66248
- var OPAQUE_REF6 = z48.string().regex(/^[a-z][a-z0-9]{1,31}_[A-Za-z0-9_-]{3,160}$/);
66249
- var DigestSchema2 = z48.string().regex(/^[a-f0-9]{64}$/);
66250
- var IdempotencyKeySchema2 = z48.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{2,199}$/);
66251
- var WorkerRegistrationSchema = z48.object({
66252
- schemaVersion: z48.literal("assistant-worker-registration-request.v1"),
66976
+ var OPAQUE_REF6 = z50.string().regex(/^[a-z][a-z0-9]{1,31}_[A-Za-z0-9_-]{3,160}$/);
66977
+ var DigestSchema2 = z50.string().regex(/^[a-f0-9]{64}$/);
66978
+ var IdempotencyKeySchema2 = z50.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{2,199}$/);
66979
+ var WorkerRegistrationSchema = z50.object({
66980
+ schemaVersion: z50.literal("assistant-worker-registration-request.v1"),
66253
66981
  idempotencyKey: IdempotencyKeySchema2,
66254
66982
  authorizedHostRef: OPAQUE_REF6,
66255
66983
  ownerRef: OPAQUE_REF6,
@@ -66257,34 +66985,34 @@ var WorkerRegistrationSchema = z48.object({
66257
66985
  workerRef: OPAQUE_REF6,
66258
66986
  deviceKeyId: OPAQUE_REF6,
66259
66987
  keyRef: OPAQUE_REF6,
66260
- algorithm: z48.literal("Ed25519"),
66261
- publicKeyPem: z48.string().min(80).max(2e3),
66988
+ algorithm: z50.literal("Ed25519"),
66989
+ publicKeyPem: z50.string().min(80).max(2e3),
66262
66990
  publicKeySha256: DigestSchema2,
66263
- runtimeVersion: z48.string().trim().min(1).max(120),
66264
- capabilities: z48.array(z48.enum([
66991
+ runtimeVersion: z50.string().trim().min(1).max(120),
66992
+ capabilities: z50.array(z50.enum([
66265
66993
  "assistant.claim",
66266
66994
  "assistant.health",
66267
66995
  "assistant.execute"
66268
66996
  ])).min(1).max(3).refine((values) => new Set(values).size === values.length),
66269
- expiresAt: z48.string().datetime({ offset: true })
66997
+ expiresAt: z50.string().datetime({ offset: true })
66270
66998
  }).strict();
66271
- var WorkerRevocationSchema = z48.object({
66272
- schemaVersion: z48.literal("assistant-worker-revocation-request.v1"),
66999
+ var WorkerRevocationSchema = z50.object({
67000
+ schemaVersion: z50.literal("assistant-worker-revocation-request.v1"),
66273
67001
  idempotencyKey: IdempotencyKeySchema2,
66274
67002
  authorizedHostRef: OPAQUE_REF6,
66275
67003
  ownerRef: OPAQUE_REF6,
66276
67004
  workerRef: OPAQUE_REF6,
66277
67005
  deviceKeyId: OPAQUE_REF6,
66278
67006
  keyRef: OPAQUE_REF6,
66279
- reasonCode: z48.string().regex(/^[a-z][a-z0-9_.-]{2,80}$/)
67007
+ reasonCode: z50.string().regex(/^[a-z][a-z0-9_.-]{2,80}$/)
66280
67008
  }).strict();
66281
- var KillMutationSchema = z48.object({
66282
- action: z48.enum(["activate", "deactivate"]),
66283
- scope: z48.enum(PERSONAL_ASSISTANT_KILL_SCOPES),
67009
+ var KillMutationSchema = z50.object({
67010
+ action: z50.enum(["activate", "deactivate"]),
67011
+ scope: z50.enum(PERSONAL_ASSISTANT_KILL_SCOPES),
66284
67012
  targetRef: OPAQUE_REF6.nullable(),
66285
67013
  idempotencyKey: IdempotencyKeySchema2,
66286
- reasonCode: z48.string().regex(/^[a-z][a-z0-9_.-]{2,80}$/),
66287
- expectedRevision: z48.number().int().nonnegative().safe()
67014
+ reasonCode: z50.string().regex(/^[a-z][a-z0-9_.-]{2,80}$/),
67015
+ expectedRevision: z50.number().int().nonnegative().safe()
66288
67016
  }).strict().superRefine((value, context) => {
66289
67017
  const targeted = ["owner", "assistant", "number"].includes(value.scope);
66290
67018
  if (targeted !== (value.targetRef !== null)) {
@@ -66315,7 +67043,7 @@ async function strictJson2(c, maxBodyBytes) {
66315
67043
  }
66316
67044
  }
66317
67045
  function derivedRef(prefix, ...identity) {
66318
- return `${prefix}_${createHash66("sha256").update(identity.join("\0")).digest("base64url").slice(0, 32)}`;
67046
+ return `${prefix}_${createHash67("sha256").update(identity.join("\0")).digest("base64url").slice(0, 32)}`;
66319
67047
  }
66320
67048
  function ownerUserId(target) {
66321
67049
  if (!/^[1-9][0-9]{0,18}$/.test(target.targetKey)) {
@@ -66343,7 +67071,7 @@ async function resolvedTarget(options, scope, targetRef) {
66343
67071
  return target;
66344
67072
  }
66345
67073
  function buildPersonalAssistantAdminRoutes(options) {
66346
- const app2 = new Hono46();
67074
+ const app2 = new Hono47();
66347
67075
  const now = options.now ?? (() => /* @__PURE__ */ new Date());
66348
67076
  const maxBodyBytes = options.maxBodyBytes ?? PERSONAL_ASSISTANT_ADMIN_MAX_BODY_BYTES;
66349
67077
  app2.onError((error, c) => {
@@ -66360,7 +67088,7 @@ function buildPersonalAssistantAdminRoutes(options) {
66360
67088
  });
66361
67089
  app2.get("/kill-switches", async (c) => {
66362
67090
  requireCapability(c.get("assistantAdmin"), "assistant.kill_switch.read");
66363
- const scope = z48.enum(PERSONAL_ASSISTANT_KILL_SCOPES).safeParse(c.req.query("scope"));
67091
+ const scope = z50.enum(PERSONAL_ASSISTANT_KILL_SCOPES).safeParse(c.req.query("scope"));
66364
67092
  const targetRaw = c.req.query("targetRef");
66365
67093
  const parsedTarget = targetRaw === void 0 || targetRaw === "" ? { success: true, data: null } : OPAQUE_REF6.safeParse(targetRaw);
66366
67094
  if (!scope.success) throw new PersonalAssistantAdminRouteError("invalid_kill_control", "Valid kill-control scope is required.", 400);
@@ -66401,7 +67129,7 @@ function buildPersonalAssistantAdminRoutes(options) {
66401
67129
  const identity = c.get("assistantAdmin");
66402
67130
  requireCapability(identity, "assistant.worker_registration.register");
66403
67131
  const parsed = WorkerRegistrationSchema.safeParse(await strictJson2(c, maxBodyBytes));
66404
- if (!parsed.success || Date.parse(parsed.data.expiresAt) <= now().getTime() || !/^-----BEGIN PUBLIC KEY-----\n[\s\S]+\n-----END PUBLIC KEY-----\n?$/.test(parsed.data.publicKeyPem) || /PRIVATE KEY|ENCRYPTED/.test(parsed.data.publicKeyPem) || createHash66("sha256").update(parsed.success ? parsed.data.publicKeyPem : "").digest("hex") !== (parsed.success ? parsed.data.publicKeySha256 : "")) {
67132
+ if (!parsed.success || Date.parse(parsed.data.expiresAt) <= now().getTime() || !/^-----BEGIN PUBLIC KEY-----\n[\s\S]+\n-----END PUBLIC KEY-----\n?$/.test(parsed.data.publicKeyPem) || /PRIVATE KEY|ENCRYPTED/.test(parsed.data.publicKeyPem) || createHash67("sha256").update(parsed.success ? parsed.data.publicKeyPem : "").digest("hex") !== (parsed.success ? parsed.data.publicKeySha256 : "")) {
66405
67133
  throw new PersonalAssistantAdminRouteError("invalid_worker_registration", "Invalid worker registration request.", 400);
66406
67134
  }
66407
67135
  try {
@@ -66484,7 +67212,7 @@ var configuredAdminGraph = null;
66484
67212
  function configurePersonalAssistantAdminProduction(options) {
66485
67213
  if (configuredAdminGraph) throw new PersonalAssistantAdminRouteError("assistant_admin_already_configured", "Assistant administrator routes are already configured.", 409);
66486
67214
  const routes = buildPersonalAssistantAdminRoutes(options);
66487
- const graph = new Hono46();
67215
+ const graph = new Hono47();
66488
67216
  graph.route(PERSONAL_ASSISTANT_ADMIN_API_PREFIX, routes);
66489
67217
  configuredAdminGraph = graph;
66490
67218
  }
@@ -66492,7 +67220,7 @@ function personalAssistantAdminReadiness() {
66492
67220
  return Object.freeze({ configured: configuredAdminGraph !== null, durablePortsRequired: true });
66493
67221
  }
66494
67222
  var personalAssistantAdminProductionApp = (() => {
66495
- const app2 = new Hono46();
67223
+ const app2 = new Hono47();
66496
67224
  app2.get("/ready", (c) => {
66497
67225
  const readiness2 = personalAssistantAdminReadiness();
66498
67226
  return c.json(readiness2, readiness2.configured ? 200 : 503);
@@ -66502,7 +67230,7 @@ var personalAssistantAdminProductionApp = (() => {
66502
67230
  })();
66503
67231
 
66504
67232
  // src/api/personal-assistant-cron-routes.ts
66505
- import { Hono as Hono47 } from "hono";
67233
+ import { Hono as Hono48 } from "hono";
66506
67234
  var PERSONAL_ASSISTANT_CRON_PREFIX = "/cron/assistant";
66507
67235
  var handlers = null;
66508
67236
  function configurePersonalAssistantCronProduction(next) {
@@ -66514,7 +67242,7 @@ function personalAssistantCronReadiness() {
66514
67242
  return Object.freeze({ configured: handlers !== null, durableReconciliationRequired: true });
66515
67243
  }
66516
67244
  var personalAssistantCronProductionApp = (() => {
66517
- const app2 = new Hono47();
67245
+ const app2 = new Hono48();
66518
67246
  app2.get("/ready", (c) => {
66519
67247
  const readiness2 = personalAssistantCronReadiness();
66520
67248
  return c.json(readiness2, readiness2.configured ? 200 : 503);
@@ -66527,24 +67255,24 @@ var personalAssistantCronProductionApp = (() => {
66527
67255
  })();
66528
67256
 
66529
67257
  // src/api/personal-assistant-production.ts
66530
- import { createHash as createHash96 } from "crypto";
67258
+ import { createHash as createHash97 } from "crypto";
66531
67259
 
66532
67260
  // src/api/personal-assistant-admin-production.ts
66533
- import { createHash as createHash70 } from "crypto";
67261
+ import { createHash as createHash71 } from "crypto";
66534
67262
 
66535
67263
  // src/api/personal-assistant-worker-store.ts
66536
- import { createHash as createHash69, randomUUID as randomUUID54 } from "crypto";
67264
+ import { createHash as createHash70, randomUUID as randomUUID55 } from "crypto";
66537
67265
 
66538
67266
  // src/api/personal-assistant-repository.ts
66539
- import { createHash as createHash68, randomBytes as randomBytes7, randomUUID as randomUUID53 } from "crypto";
67267
+ import { createHash as createHash69, randomBytes as randomBytes7, randomUUID as randomUUID54 } from "crypto";
66540
67268
 
66541
67269
  // src/api/personal-assistant-wake-packet.ts
66542
- import { createHash as createHash67 } from "crypto";
67270
+ import { createHash as createHash68 } from "crypto";
66543
67271
  function stableJson(value) {
66544
67272
  return JSON.stringify(value, (_key, entry) => !entry || typeof entry !== "object" || Array.isArray(entry) ? entry : Object.fromEntries(Object.entries(entry).sort(([a], [b]) => a.localeCompare(b))));
66545
67273
  }
66546
67274
  function stableDigest(value) {
66547
- return createHash67("sha256").update(stableJson(value)).digest("hex");
67275
+ return createHash68("sha256").update(stableJson(value)).digest("hex");
66548
67276
  }
66549
67277
  function deterministicWakePacketRef(snapshot) {
66550
67278
  return `wake_${stableDigest({ assistantRef: snapshot.assistantRef, commandRef: snapshot.commandRef, cycleRef: snapshot.cycleRef, executionRef: snapshot.executionRef, contextVersionRef: snapshot.contextVersion.contextVersionRef }).slice(0, 32)}`;
@@ -66597,10 +67325,10 @@ function canonicalJson7(value) {
66597
67325
  });
66598
67326
  }
66599
67327
  function digest7(value) {
66600
- return createHash68("sha256").update(canonicalJson7(value)).digest("hex");
67328
+ return createHash69("sha256").update(canonicalJson7(value)).digest("hex");
66601
67329
  }
66602
67330
  function deterministicRef2(prefix, identity) {
66603
- return `${prefix}_${createHash68("sha256").update(identity).digest("hex").slice(0, 32)}`;
67331
+ return `${prefix}_${createHash69("sha256").update(identity).digest("hex").slice(0, 32)}`;
66604
67332
  }
66605
67333
  function messageCursor(message) {
66606
67334
  return Buffer.from(JSON.stringify([message.occurredAt, message.messageRef])).toString("base64url");
@@ -66985,7 +67713,7 @@ function createPostgresPersonalAssistantRepositoryStore(options = {}) {
66985
67713
  const stored = AssistantCommandSchema.parse(existing.rows[0].payload);
66986
67714
  return { command: stored, receipt: receipt4, entity: stored };
66987
67715
  }
66988
- const commandId = randomUUID53();
67716
+ const commandId = randomUUID54();
66989
67717
  const inserted = await client2.query(`
66990
67718
  INSERT INTO assistant.commands (
66991
67719
  owner_user_id, id, public_id, assistant_id, conversation_id, command_type,
@@ -67027,7 +67755,7 @@ function createPostgresPersonalAssistantRepositoryStore(options = {}) {
67027
67755
  )
67028
67756
  `, [
67029
67757
  ownerUserId2.toString(),
67030
- randomUUID53(),
67758
+ randomUUID54(),
67031
67759
  receipt4.receiptRef,
67032
67760
  commandId,
67033
67761
  command.operation,
@@ -67096,7 +67824,7 @@ function createPostgresPersonalAssistantRepositoryStore(options = {}) {
67096
67824
  `, [ownerUserId2.toString(), row.id]);
67097
67825
  }
67098
67826
  const token7 = randomBytes7(32).toString("base64url");
67099
- const tokenHash5 = createHash68("sha256").update(token7).digest("hex");
67827
+ const tokenHash5 = createHash69("sha256").update(token7).digest("hex");
67100
67828
  const leaseRef = deterministicRef2("lease", `${input.executionRef}\0${input.workerRef}\0${input.now}`);
67101
67829
  const expiresAt = new Date(Date.parse(input.now) + input.leaseSeconds * 1e3).toISOString();
67102
67830
  await client2.query(`
@@ -67104,7 +67832,7 @@ function createPostgresPersonalAssistantRepositoryStore(options = {}) {
67104
67832
  owner_user_id, id, public_id, worker_id, execution_id, lease_token_hash,
67105
67833
  state, claimed_at, heartbeat_at, expires_at
67106
67834
  ) VALUES ($1, $2, $3, $4, $5, $6, 'active', $7, $7, $8)
67107
- `, [ownerUserId2.toString(), randomUUID53(), leaseRef, worker.rows[0].id, row.id, tokenHash5, input.now, expiresAt]);
67835
+ `, [ownerUserId2.toString(), randomUUID54(), leaseRef, worker.rows[0].id, row.id, tokenHash5, input.now, expiresAt]);
67108
67836
  await client2.query(`
67109
67837
  UPDATE assistant.executions
67110
67838
  SET state = 'claimed', claimed_by_worker_id = $3, claim_token_hash = $4,
@@ -67181,7 +67909,7 @@ function createPostgresPersonalAssistantRepositoryStore(options = {}) {
67181
67909
  RETURNING public_id
67182
67910
  `, [
67183
67911
  ownerUserId2.toString(),
67184
- randomUUID53(),
67912
+ randomUUID54(),
67185
67913
  grant.grantRef,
67186
67914
  grant.revision,
67187
67915
  grant.authorityClass,
@@ -67238,7 +67966,7 @@ function createPostgresPersonalAssistantRepositoryStore(options = {}) {
67238
67966
  RETURNING public_id
67239
67967
  `, [
67240
67968
  ownerUserId2.toString(),
67241
- randomUUID53(),
67969
+ randomUUID54(),
67242
67970
  approval.approvalRef,
67243
67971
  approval.requestedActionDigest,
67244
67972
  approval.approvedArgumentDigest,
@@ -67371,7 +68099,7 @@ function createPostgresPersonalAssistantRepositoryStore(options = {}) {
67371
68099
  RETURNING public_id
67372
68100
  `, [
67373
68101
  ownerUserId2.toString(),
67374
- randomUUID53(),
68102
+ randomUUID54(),
67375
68103
  input.conversationRef,
67376
68104
  input.participantDigest,
67377
68105
  input.occurredAt,
@@ -67419,7 +68147,7 @@ function createPostgresPersonalAssistantRepositoryStore(options = {}) {
67419
68147
  RETURNING public_id
67420
68148
  `, [
67421
68149
  ownerUserId2.toString(),
67422
- randomUUID53(),
68150
+ randomUUID54(),
67423
68151
  message.messageRef,
67424
68152
  message.direction,
67425
68153
  message.providerAccountRef,
@@ -67462,7 +68190,7 @@ function createPostgresPersonalAssistantRepositoryStore(options = {}) {
67462
68190
  provider_message_sid,provider_event_key,error_class,occurred_at
67463
68191
  `, [
67464
68192
  ownerUserId2.toString(),
67465
- randomUUID53(),
68193
+ randomUUID54(),
67466
68194
  event2.deliveryEventRef,
67467
68195
  event2.providerAccountRef,
67468
68196
  event2.providerMessageSid,
@@ -67511,7 +68239,7 @@ function createPostgresPersonalAssistantRepositoryStore(options = {}) {
67511
68239
  RETURNING public_id, byte_digest
67512
68240
  `, [
67513
68241
  ownerUserId2.toString(),
67514
- randomUUID53(),
68242
+ randomUUID54(),
67515
68243
  media.mediaRef,
67516
68244
  media.providerAccountRef,
67517
68245
  media.providerMediaSid,
@@ -67570,7 +68298,7 @@ function createPostgresPersonalAssistantRepositoryStore(options = {}) {
67570
68298
  RETURNING public_id,version,manifest_digest,created_at
67571
68299
  `, [
67572
68300
  ownerUserId2.toString(),
67573
- randomUUID53(),
68301
+ randomUUID54(),
67574
68302
  input.contextVersionRef,
67575
68303
  input.version,
67576
68304
  input.manifestDigest,
@@ -67599,7 +68327,7 @@ function createPostgresPersonalAssistantRepositoryStore(options = {}) {
67599
68327
  RETURNING public_id,state,opened_at,updated_at,closed_at
67600
68328
  `, [
67601
68329
  ownerUserId2.toString(),
67602
- randomUUID53(),
68330
+ randomUUID54(),
67603
68331
  cycle.cycleRef,
67604
68332
  cycle.state,
67605
68333
  cycle.openedAt,
@@ -67632,7 +68360,7 @@ function createPostgresPersonalAssistantRepositoryStore(options = {}) {
67632
68360
  FROM assistant.wake_cycles cycle WHERE cycle.owner_user_id = $1 AND cycle.public_id = $9
67633
68361
  `, [
67634
68362
  ownerUserId2.toString(),
67635
- randomUUID53(),
68363
+ randomUUID54(),
67636
68364
  transition.taskRef,
67637
68365
  title,
67638
68366
  transition.toState,
@@ -67666,7 +68394,7 @@ function createPostgresPersonalAssistantRepositoryStore(options = {}) {
67666
68394
  RETURNING public_id,state,attempt,retry_class,terminal_at
67667
68395
  `, [
67668
68396
  ownerUserId2.toString(),
67669
- randomUUID53(),
68397
+ randomUUID54(),
67670
68398
  execution.executionRef,
67671
68399
  execution.planDigest,
67672
68400
  execution.state,
@@ -67701,7 +68429,7 @@ function createPostgresPersonalAssistantRepositoryStore(options = {}) {
67701
68429
  RETURNING runtime_version,health,occurred_at
67702
68430
  `, [
67703
68431
  ownerUserId2.toString(),
67704
- randomUUID53(),
68432
+ randomUUID54(),
67705
68433
  relation.rows[0].worker_id,
67706
68434
  relation.rows[0].lease_id,
67707
68435
  heartbeat.sequence,
@@ -67786,7 +68514,7 @@ function createPostgresPersonalAssistantRepositoryStore(options = {}) {
67786
68514
  RETURNING id
67787
68515
  `, [
67788
68516
  ownerUserId2.toString(),
67789
- randomUUID53(),
68517
+ randomUUID54(),
67790
68518
  plan.planRef,
67791
68519
  plan.planDigest,
67792
68520
  JSON.stringify(plan),
@@ -67805,7 +68533,7 @@ function createPostgresPersonalAssistantRepositoryStore(options = {}) {
67805
68533
  ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9::jsonb,$10,$11,$12,$13,$14)
67806
68534
  `, [
67807
68535
  ownerUserId2.toString(),
67808
- randomUUID53(),
68536
+ randomUUID54(),
67809
68537
  step.stepRef,
67810
68538
  inserted.rows[0].id,
67811
68539
  step.position,
@@ -67845,7 +68573,7 @@ function createPostgresPersonalAssistantRepositoryStore(options = {}) {
67845
68573
  RETURNING required_digest,decision,reason_code
67846
68574
  `, [
67847
68575
  ownerUserId2.toString(),
67848
- randomUUID53(),
68576
+ randomUUID54(),
67849
68577
  barrier.barrierRef,
67850
68578
  barrier.barrierKind,
67851
68579
  barrier.decision,
@@ -67876,7 +68604,7 @@ function createPostgresPersonalAssistantRepositoryStore(options = {}) {
67876
68604
  RETURNING public_id,authorized_minor,state
67877
68605
  `, [
67878
68606
  ownerUserId2.toString(),
67879
- randomUUID53(),
68607
+ randomUUID54(),
67880
68608
  allocation.allocationRef,
67881
68609
  allocation.kind,
67882
68610
  allocation.idempotencyKey,
@@ -67990,7 +68718,7 @@ function createPostgresPersonalAssistantRepositoryStore(options = {}) {
67990
68718
  ON CONFLICT (owner_user_id, public_id) DO NOTHING
67991
68719
  `, [
67992
68720
  ownerUserId2.toString(),
67993
- randomUUID53(),
68721
+ randomUUID54(),
67994
68722
  contact.contactRef,
67995
68723
  contact.displayName,
67996
68724
  contact.phoneCiphertext,
@@ -68018,7 +68746,7 @@ function createPostgresPersonalAssistantRepositoryStore(options = {}) {
68018
68746
  ON CONFLICT (owner_user_id, public_id) DO NOTHING
68019
68747
  `, [
68020
68748
  ownerUserId2.toString(),
68021
- randomUUID53(),
68749
+ randomUUID54(),
68022
68750
  number.numberRef,
68023
68751
  number.providerAccountRef,
68024
68752
  number.providerNumberSid,
@@ -68050,7 +68778,7 @@ function createPostgresPersonalAssistantRepositoryStore(options = {}) {
68050
68778
  ON CONFLICT (owner_user_id, public_id) DO NOTHING
68051
68779
  `, [
68052
68780
  ownerUserId2.toString(),
68053
- randomUUID53(),
68781
+ randomUUID54(),
68054
68782
  conversation.conversationRef,
68055
68783
  conversation.participantDigest,
68056
68784
  conversation.occurredAt,
@@ -68072,7 +68800,7 @@ function createPostgresPersonalAssistantRepositoryStore(options = {}) {
68072
68800
  ON CONFLICT (owner_user_id, public_id) DO NOTHING
68073
68801
  `, [
68074
68802
  ownerUserId2.toString(),
68075
- randomUUID53(),
68803
+ randomUUID54(),
68076
68804
  message.messageRef,
68077
68805
  message.direction,
68078
68806
  message.providerAccountRef,
@@ -68101,7 +68829,7 @@ function createPostgresPersonalAssistantRepositoryStore(options = {}) {
68101
68829
  RETURNING id
68102
68830
  `, [
68103
68831
  ownerUserId2.toString(),
68104
- randomUUID53(),
68832
+ randomUUID54(),
68105
68833
  schedule.scheduleRef,
68106
68834
  schedule.sourceSystem,
68107
68835
  schedule.sourceRef,
@@ -68129,7 +68857,7 @@ function createPostgresPersonalAssistantRepositoryStore(options = {}) {
68129
68857
  ON CONFLICT (owner_user_id, public_id) DO NOTHING
68130
68858
  `, [
68131
68859
  ownerUserId2.toString(),
68132
- randomUUID53(),
68860
+ randomUUID54(),
68133
68861
  grant.grantRef,
68134
68862
  insertedSchedule.rows[0].id,
68135
68863
  grant.revision,
@@ -68155,7 +68883,7 @@ function createPostgresPersonalAssistantRepositoryStore(options = {}) {
68155
68883
  ON CONFLICT (owner_user_id, public_id) DO NOTHING
68156
68884
  `, [
68157
68885
  ownerUserId2.toString(),
68158
- randomUUID53(),
68886
+ randomUUID54(),
68159
68887
  run.occurrenceRef,
68160
68888
  run.sourceRef,
68161
68889
  run.occurrenceKey,
@@ -68214,7 +68942,7 @@ function createPostgresPersonalAssistantRepositoryStore(options = {}) {
68214
68942
  INSERT INTO assistant.audit_events (
68215
68943
  owner_user_id,id,public_id,actor_kind,event_type,correlation_id,evidence_digest,details,occurred_at
68216
68944
  ) VALUES ($1,$2,$3,'operator','legacy_import_applied',$3,$4,$5::jsonb,$6)
68217
- `, [ownerUserId2.toString(), randomUUID53(), input.importRef, applied.classificationDigest, JSON.stringify({ receipt: applied }), appliedAt]);
68945
+ `, [ownerUserId2.toString(), randomUUID54(), input.importRef, applied.classificationDigest, JSON.stringify({ receipt: applied }), appliedAt]);
68218
68946
  return applied;
68219
68947
  });
68220
68948
  }
@@ -68282,7 +69010,7 @@ async function appendPostgresReceipt(transaction2, ownerUserId2, receipt4, recei
68282
69010
  ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12::jsonb,$13,$14,$15)
68283
69011
  `, [
68284
69012
  ownerUserId2.toString(),
68285
- randomUUID53(),
69013
+ randomUUID54(),
68286
69014
  receipt4.receiptRef,
68287
69015
  relation.rows[0].command_id,
68288
69016
  relation.rows[0].execution_id,
@@ -68315,7 +69043,7 @@ async function insertPostgresConsentEvidence(queryable, ownerUserId2, evidence)
68315
69043
  RETURNING public_id
68316
69044
  `, [
68317
69045
  ownerUserId2.toString(),
68318
- randomUUID53(),
69046
+ randomUUID54(),
68319
69047
  evidence.consentRef,
68320
69048
  evidence.recipientHash,
68321
69049
  evidence.subjectKey,
@@ -68356,7 +69084,7 @@ async function insertPostgresSuppressionEvent(queryable, ownerUserId2, event2) {
68356
69084
  ON CONFLICT (owner_user_id, public_id) DO NOTHING RETURNING public_id
68357
69085
  `, [
68358
69086
  ownerUserId2.toString(),
68359
- randomUUID53(),
69087
+ randomUUID54(),
68360
69088
  event2.suppressionRef,
68361
69089
  event2.subjectKey,
68362
69090
  event2.transition,
@@ -68634,10 +69362,10 @@ var AssistantWorkerStoreError = class extends Error {
68634
69362
  };
68635
69363
  function hash(value) {
68636
69364
  const canonical3 = JSON.stringify(value, (_key, entry) => entry && typeof entry === "object" && !Array.isArray(entry) ? Object.fromEntries(Object.entries(entry).sort(([a], [b]) => a.localeCompare(b))) : entry);
68637
- return createHash69("sha256").update(canonical3).digest("hex");
69365
+ return createHash70("sha256").update(canonical3).digest("hex");
68638
69366
  }
68639
69367
  function ref2(prefix, identity) {
68640
- return `${prefix}_${createHash69("sha256").update(identity).digest("hex").slice(0, 32)}`;
69368
+ return `${prefix}_${createHash70("sha256").update(identity).digest("hex").slice(0, 32)}`;
68641
69369
  }
68642
69370
  function requiredString(input, key3) {
68643
69371
  const value = input[key3];
@@ -68688,7 +69416,7 @@ var PostgresAssistantWorkerIdentityRegistry = class {
68688
69416
  RETURNING owner_user_id::text,owner_ref,subject_ref,public_id AS worker_ref,device_key_id,key_ref,
68689
69417
  device_public_key,state,expires_at`, [
68690
69418
  input.ownerUserId.toString(),
68691
- randomUUID54(),
69419
+ randomUUID55(),
68692
69420
  input.workerRef,
68693
69421
  input.ownerRef,
68694
69422
  input.subjectRef,
@@ -68741,7 +69469,7 @@ var PostgresAssistantWorkerNonceLedger = class {
68741
69469
  INSERT INTO assistant.worker_nonces(owner_user_id,id,namespace,nonce_key,expires_at,consumed_at)
68742
69470
  SELECT owner_user_id,$1,$2,$3,$4,$5 FROM unique_candidate
68743
69471
  ON CONFLICT (owner_user_id,namespace,nonce_key) DO NOTHING RETURNING id`,
68744
- [randomUUID54(), input.namespace, input.key, input.expiresAt, now.toISOString(), workerRef]
69472
+ [randomUUID55(), input.namespace, input.key, input.expiresAt, now.toISOString(), workerRef]
68745
69473
  );
68746
69474
  return (result3.rowCount ?? result3.rows.length) === 1;
68747
69475
  }
@@ -69036,7 +69764,7 @@ var INTERNAL_CAPABILITIES = /* @__PURE__ */ new Set([
69036
69764
  "assistant.worker_registration.revoke"
69037
69765
  ]);
69038
69766
  function actorRef(issuer, subject) {
69039
- return `admin_actor_${createHash70("sha256").update(`${issuer}\0${subject}`).digest("base64url").slice(0, 32)}`;
69767
+ return `admin_actor_${createHash71("sha256").update(`${issuer}\0${subject}`).digest("base64url").slice(0, 32)}`;
69040
69768
  }
69041
69769
  var VerifiedPersonalAssistantAdminIdentityPort = class {
69042
69770
  constructor(verifier, configuration) {
@@ -69150,7 +69878,7 @@ function createPersonalAssistantAdminProductionDependencies(input) {
69150
69878
  }
69151
69879
 
69152
69880
  // src/api/personal-assistant-dispatcher.ts
69153
- import { createHash as createHash71, randomBytes as randomBytes8, randomUUID as randomUUID55 } from "crypto";
69881
+ import { createHash as createHash72, randomBytes as randomBytes8, randomUUID as randomUUID56 } from "crypto";
69154
69882
  var AssistantLeaseFenceError = class extends Error {
69155
69883
  code = "assistant_lease_fence_rejected";
69156
69884
  constructor() {
@@ -69164,7 +69892,7 @@ function canonical2(value) {
69164
69892
  return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key3, entry]) => [key3, canonical2(entry)]));
69165
69893
  }
69166
69894
  function digest8(value) {
69167
- return createHash71("sha256").update(JSON.stringify(canonical2(value))).digest("hex");
69895
+ return createHash72("sha256").update(JSON.stringify(canonical2(value))).digest("hex");
69168
69896
  }
69169
69897
  function ref3(prefix, identity) {
69170
69898
  return `${prefix}_${digest8(identity).slice(0, 32)}`;
@@ -69382,7 +70110,7 @@ function createPostgresPersonalAssistantDispatchStore(options = {}) {
69382
70110
  const cycleRef = deterministic ? null : ref3("cycle", commandRef);
69383
70111
  const executionRef = deterministic ? null : ref3("execution", commandRef);
69384
70112
  const occurrenceRef = input.occurrenceKey ? ref3("occurrence", `${ownerId3}\0${input.scheduleRef}\0${input.occurrenceKey}`) : null;
69385
- const commandId = randomUUID55();
70113
+ const commandId = randomUUID56();
69386
70114
  const commandPayload = {
69387
70115
  schemaVersion: "assistant-command.v1",
69388
70116
  commandRef,
@@ -69427,8 +70155,8 @@ function createPostgresPersonalAssistantDispatchStore(options = {}) {
69427
70155
  let cycleId = null;
69428
70156
  let executionId = null;
69429
70157
  if (!deterministic && cycleRef && executionRef) {
69430
- cycleId = randomUUID55();
69431
- executionId = randomUUID55();
70158
+ cycleId = randomUUID56();
70159
+ executionId = randomUUID56();
69432
70160
  await client2.query(
69433
70161
  `INSERT INTO assistant.wake_cycles
69434
70162
  (owner_user_id,id,public_id,assistant_id,command_id,context_version_id,state,opened_at,updated_at)
@@ -69450,7 +70178,7 @@ function createPostgresPersonalAssistantDispatchStore(options = {}) {
69450
70178
  ON CONFLICT (owner_user_id,schedule_ref,occurrence_key) DO UPDATE SET public_id=assistant.reminder_occurrences.public_id
69451
70179
  RETURNING public_id`, [
69452
70180
  ownerId3,
69453
- randomUUID55(),
70181
+ randomUUID56(),
69454
70182
  occurrenceRef,
69455
70183
  input.occurrenceKey,
69456
70184
  input.scheduledFor,
@@ -69479,7 +70207,7 @@ function createPostgresPersonalAssistantDispatchStore(options = {}) {
69479
70207
  VALUES ($1,$2,$3,$4,$5,'assistant.execution.status','response',$6,$7,$8,$9,$10::jsonb,$11,$12)`,
69480
70208
  [
69481
70209
  ownerId3,
69482
- randomUUID55(),
70210
+ randomUUID56(),
69483
70211
  receiptRef,
69484
70212
  commandId,
69485
70213
  executionId,
@@ -69540,7 +70268,7 @@ function createPostgresPersonalAssistantDispatchStore(options = {}) {
69540
70268
  (owner_user_id,id,public_id,worker_id,execution_id,lease_token_hash,state,claimed_at,heartbeat_at,expires_at)
69541
70269
  SELECT $1,$2,$3,$4,execution.id,$5,'active',$6,$6,$7 FROM assistant.executions execution
69542
70270
  WHERE execution.owner_user_id=$1 AND execution.public_id=$8`,
69543
- [ownerId3, randomUUID55(), leaseRef, worker.rows[0].id, tokenHash3(token7), at, expiresAt, row.execution_ref]
70271
+ [ownerId3, randomUUID56(), leaseRef, worker.rows[0].id, tokenHash3(token7), at, expiresAt, row.execution_ref]
69544
70272
  );
69545
70273
  await client2.query(
69546
70274
  `UPDATE assistant.executions SET state='claimed',claimed_by_worker_id=$3,claim_token_hash=$4,
@@ -69580,7 +70308,7 @@ function createPostgresPersonalAssistantDispatchStore(options = {}) {
69580
70308
  SELECT $1,$2,worker.id,lease.id,$3,$4,$5::jsonb,$6 FROM assistant.worker_registrations worker
69581
70309
  JOIN assistant.worker_leases lease ON lease.owner_user_id=worker.owner_user_id AND lease.worker_id=worker.id
69582
70310
  WHERE worker.owner_user_id=$1 AND worker.public_id=$7 AND lease.public_id=$8 AND lease.state='active'`,
69583
- [ownerId3, randomUUID55(), input.sequence, input.runtimeVersion, JSON.stringify(input.health), occurredAt, input.workerRef, input.leaseRef]
70311
+ [ownerId3, randomUUID56(), input.sequence, input.runtimeVersion, JSON.stringify(input.health), occurredAt, input.workerRef, input.leaseRef]
69584
70312
  );
69585
70313
  await client2.query(`UPDATE assistant.worker_leases SET heartbeat_at=$3,expires_at=$4
69586
70314
  WHERE owner_user_id=$1 AND public_id=$2 AND state='active'`, [ownerId3, input.leaseRef, occurredAt, expiresAt]);
@@ -69822,7 +70550,7 @@ function createPostgresAssistantReminderRuntimeStore(options = {}) {
69822
70550
  payload_digest,payload,parsed_intent,parsed_intent_digest,source,state,accepted_at,updated_at,terminal_at)
69823
70551
  SELECT $1,$2,$3,assistant.id,NULL,$4,'assistant-reminder-command.v1',$5,$6,$7::jsonb,NULL,NULL,'system','succeeded',$8,$8,$8
69824
70552
  FROM assistant.assistants assistant WHERE assistant.owner_user_id=$1 AND assistant.public_id=$9
69825
- RETURNING id`, [ownerId3, randomUUID55(), commandRef, command.kind, command.idempotencyKey, digest8(command), JSON.stringify(payload), at, assistantRef2]);
70553
+ RETURNING id`, [ownerId3, randomUUID56(), commandRef, command.kind, command.idempotencyKey, digest8(command), JSON.stringify(payload), at, assistantRef2]);
69826
70554
  if (!inserted.rows[0]) throw new Error("assistant_reminder_assistant_not_found");
69827
70555
  return inserted.rows[0].id;
69828
70556
  };
@@ -69872,7 +70600,7 @@ function createPostgresAssistantReminderRuntimeStore(options = {}) {
69872
70600
  FROM assistant.assistants assistant WHERE assistant.owner_user_id=$1 AND assistant.public_id=$12`,
69873
70601
  [
69874
70602
  ownerId3,
69875
- randomUUID55(),
70603
+ randomUUID56(),
69876
70604
  publicRef,
69877
70605
  commandRef,
69878
70606
  definition2.instruction,
@@ -69948,7 +70676,7 @@ function createPostgresAssistantReminderRuntimeStore(options = {}) {
69948
70676
  ON CONFLICT (owner_user_id,schedule_ref,occurrence_key) DO NOTHING RETURNING public_id`,
69949
70677
  [
69950
70678
  definition.ownerId,
69951
- randomUUID55(),
70679
+ randomUUID56(),
69952
70680
  occurrence.occurrenceRef,
69953
70681
  definition.assistantRef,
69954
70682
  definition.reminderRef,
@@ -70028,10 +70756,10 @@ function createPersonalAssistantReminderRuntime(options) {
70028
70756
  }
70029
70757
 
70030
70758
  // src/api/personal-assistant-reconcile-cron.ts
70031
- import { createHash as createHash73, timingSafeEqual as timingSafeEqual8 } from "crypto";
70759
+ import { createHash as createHash74, timingSafeEqual as timingSafeEqual8 } from "crypto";
70032
70760
 
70033
70761
  // src/api/personal-assistant-reconcile.ts
70034
- import { createHash as createHash72 } from "crypto";
70762
+ import { createHash as createHash73 } from "crypto";
70035
70763
  var PERSONAL_ASSISTANT_RECONCILIATION_LIMITS = Object.freeze({
70036
70764
  defaultBatchSize: 20,
70037
70765
  maxBatchSize: 50,
@@ -70053,7 +70781,7 @@ var PUBLIC_REF = /^[a-z][a-z0-9_]*_[A-Za-z0-9_-]{3,128}$/u;
70053
70781
  var DIGEST2 = /^[a-f0-9]{64}$/u;
70054
70782
  var PROVIDER_REF = /^[A-Za-z0-9:_-]{3,200}$/u;
70055
70783
  function hash2(value) {
70056
- return createHash72("sha256").update(value).digest("hex");
70784
+ return createHash73("sha256").update(value).digest("hex");
70057
70785
  }
70058
70786
  function validateCandidate(candidate) {
70059
70787
  if (!/^[1-9]\d*$/u.test(candidate.ownerUserId) || !PUBLIC_REF.test(candidate.candidateRef) || !/^trace_[A-Za-z0-9_-]{8,128}$/u.test(candidate.traceRef) || !PUBLIC_REF.test(candidate.claimToken) || !PROVIDER_REF.test(candidate.providerAccountRef) || !PROVIDER_REF.test(candidate.providerLocatorRef) || !DIGEST2.test(candidate.expectedDigest) || !Number.isFinite(Date.parse(candidate.stuckSince))) {
@@ -70175,8 +70903,8 @@ async function reconcilePersonalAssistantTransports(dependencies, options = {})
70175
70903
  // src/api/personal-assistant-reconcile-cron.ts
70176
70904
  function authorized(actual, expectedSecret) {
70177
70905
  if (!actual?.startsWith("Bearer ")) return false;
70178
- const actualDigest = createHash73("sha256").update(actual).digest();
70179
- const expectedDigest = createHash73("sha256").update(`Bearer ${expectedSecret}`).digest();
70906
+ const actualDigest = createHash74("sha256").update(actual).digest();
70907
+ const expectedDigest = createHash74("sha256").update(`Bearer ${expectedSecret}`).digest();
70180
70908
  return timingSafeEqual8(actualDigest, expectedDigest);
70181
70909
  }
70182
70910
  function createPersonalAssistantReconcileCronHandler(options) {
@@ -70238,7 +70966,7 @@ function createPersonalAssistantReminderCronHandler(options) {
70238
70966
  }
70239
70967
 
70240
70968
  // src/api/twilio-inbound-admission.ts
70241
- import { createHash as createHash74, randomBytes as randomBytes9 } from "crypto";
70969
+ import { createHash as createHash75, randomBytes as randomBytes9 } from "crypto";
70242
70970
  var ACCOUNT_SID = /^AC[0-9a-f]{32}$/iu;
70243
70971
  var MESSAGE_SID = /^(?:SM|MM)[0-9a-f]{32}$/iu;
70244
70972
  var MESSAGING_SERVICE_SID = /^MG[0-9a-f]{32}$/iu;
@@ -70260,10 +70988,10 @@ function canonicalJson8(value) {
70260
70988
  });
70261
70989
  }
70262
70990
  function digest9(value) {
70263
- return createHash74("sha256").update(canonicalJson8(value)).digest("hex");
70991
+ return createHash75("sha256").update(canonicalJson8(value)).digest("hex");
70264
70992
  }
70265
70993
  function stableRef(prefix, value) {
70266
- return `${prefix}_${createHash74("sha256").update(value).digest("hex").slice(0, 32)}`;
70994
+ return `${prefix}_${createHash75("sha256").update(value).digest("hex").slice(0, 32)}`;
70267
70995
  }
70268
70996
  function normalizeOptionalSid(value) {
70269
70997
  const normalized = value?.trim() || null;
@@ -70409,8 +71137,8 @@ function createTwilioInboundIngressCronHandler(options) {
70409
71137
  return async (request) => {
70410
71138
  if (request.method !== "GET") return Response.json({ error: "method_not_allowed" }, { status: 405, headers: { Allow: "GET" } });
70411
71139
  const actual = request.headers.get("authorization") ?? "";
70412
- const actualDigest = createHash74("sha256").update(actual).digest();
70413
- const expectedDigest = createHash74("sha256").update(expectedAuthorization).digest();
71140
+ const actualDigest = createHash75("sha256").update(actual).digest();
71141
+ const expectedDigest = createHash75("sha256").update(expectedAuthorization).digest();
70414
71142
  if (actualDigest.length !== expectedDigest.length || !actualDigest.equals(expectedDigest)) {
70415
71143
  return Response.json({ error: "unauthorized" }, { status: 401 });
70416
71144
  }
@@ -70452,7 +71180,7 @@ function createPersonalAssistantWorkerAndCronProduction(options) {
70452
71180
  }
70453
71181
 
70454
71182
  // src/api/personal-assistant-control-plane-store.ts
70455
- import { createHash as createHash75, randomUUID as randomUUID56 } from "crypto";
71183
+ import { createHash as createHash76, randomUUID as randomUUID57 } from "crypto";
70456
71184
  var REF = /^[a-z][A-Za-z0-9_-]{2,159}$/;
70457
71185
  var DIGEST4 = /^[a-f0-9]{64}$/;
70458
71186
  function record3(input) {
@@ -70475,7 +71203,7 @@ function ref4(value) {
70475
71203
  return value;
70476
71204
  }
70477
71205
  function newRef2(prefix) {
70478
- return `${prefix}_${randomUUID56().replaceAll("-", "")}`;
71206
+ return `${prefix}_${randomUUID57().replaceAll("-", "")}`;
70479
71207
  }
70480
71208
  function canonicalJson9(value) {
70481
71209
  return JSON.stringify(value, (_key, entry) => {
@@ -70484,7 +71212,7 @@ function canonicalJson9(value) {
70484
71212
  });
70485
71213
  }
70486
71214
  function digest10(value) {
70487
- return createHash75("sha256").update(canonicalJson9(value)).digest("hex");
71215
+ return createHash76("sha256").update(canonicalJson9(value)).digest("hex");
70488
71216
  }
70489
71217
  function normalizeE164(value) {
70490
71218
  const trimmed = value.trim();
@@ -70531,7 +71259,7 @@ async function audit(client2, owner5, operation, resourceRef, occurredAt) {
70531
71259
  `INSERT INTO assistant.audit_events (
70532
71260
  owner_user_id,id,public_id,actor_kind,event_type,operation,correlation_id,details,occurred_at
70533
71261
  ) VALUES ($1,$2,$3,'user','assistant.control_plane.mutation',$4,$5,$6::jsonb,$7::timestamptz)`,
70534
- [owner5, randomUUID56(), newRef2("audit"), operation, resourceRef, JSON.stringify({ resourceRef }), occurredAt]
71262
+ [owner5, randomUUID57(), newRef2("audit"), operation, resourceRef, JSON.stringify({ resourceRef }), occurredAt]
70535
71263
  );
70536
71264
  }
70537
71265
  var ASSISTANT_PROJECTION = `jsonb_build_object('assistantRef', assistant.public_id, 'state', assistant.status,
@@ -70612,7 +71340,7 @@ function createPostgresPersonalAssistantControlPlaneStore(options) {
70612
71340
  'assistantRef',public_id,'state',status,'displayName',name,'revision',revision,'createdAt',created_at,'updatedAt',updated_at) AS projection`,
70613
71341
  [
70614
71342
  ownerUserId2.toString(),
70615
- randomUUID56(),
71343
+ randomUUID57(),
70616
71344
  assistantRef2,
70617
71345
  text2(body3, "displayName", text2(body3, "name", "Personal Assistant")),
70618
71346
  optionalText3(body3, "timezone") ?? "UTC",
@@ -70666,7 +71394,7 @@ function createPostgresPersonalAssistantControlPlaneStore(options) {
70666
71394
  (owner_user_id,id,public_id,assistant_id,channel,address_ciphertext,address_hash,state,revision,created_at,updated_at)
70667
71395
  SELECT $1,$2,$3,assistant.id,$4,$5,$6,'active',1,$7,$7 FROM assistant.assistants assistant WHERE assistant.owner_user_id=$1 AND assistant.public_id=$8 AND assistant.deleted_at IS NULL
70668
71396
  RETURNING jsonb_build_object('bindingRef',public_id,'assistantRef',$8::text,'channelEndpointRef',public_id,'channel',channel,'state',state,'revision',revision) AS projection`,
70669
- [ownerUserId2.toString(), randomUUID56(), bindingRef, channel, protectedAddress?.ciphertext ?? null, protectedAddress?.digest ?? null, at, ref4(assistantRef2)]
71397
+ [ownerUserId2.toString(), randomUUID57(), bindingRef, channel, protectedAddress?.ciphertext ?? null, protectedAddress?.digest ?? null, at, ref4(assistantRef2)]
70670
71398
  );
70671
71399
  if (!result3.rows[0]) throw new Error("assistant_not_found");
70672
71400
  await audit(client2, ownerUserId2.toString(), "assistant.channel.bind", bindingRef, at);
@@ -70723,11 +71451,11 @@ function createPostgresPersonalAssistantControlPlaneStore(options) {
70723
71451
  const inserted = await client2.query(`INSERT INTO assistant.contacts(owner_user_id,id,public_id,display_name,relationship,phone_ciphertext,phone_hash,timezone,attributes,created_at,updated_at)
70724
71452
  VALUES($1,$2,$3,$4,$5,$6,$7,$8,'{}'::jsonb,$9,$9)
70725
71453
  ON CONFLICT(owner_user_id,phone_hash) WHERE phone_hash IS NOT NULL DO UPDATE SET updated_at=assistant.contacts.updated_at
70726
- RETURNING id,public_id`, [ownerUserId2.toString(), randomUUID56(), contactRef, optionalText3(body3, "displayName"), relationship, protectedAddress.ciphertext, protectedAddress.digest, optionalText3(body3, "timezone"), at]);
71454
+ RETURNING id,public_id`, [ownerUserId2.toString(), randomUUID57(), contactRef, optionalText3(body3, "displayName"), relationship, protectedAddress.ciphertext, protectedAddress.digest, optionalText3(body3, "timezone"), at]);
70727
71455
  const row = inserted.rows[0];
70728
71456
  if (!row) throw new Error("contact_create_failed");
70729
71457
  await client2.query(`INSERT INTO assistant.contact_delivery_endpoints(owner_user_id,id,public_id,endpoint_key,revision,contact_id,channel,address_ciphertext,address_hash,masked_display,state,created_at)
70730
- SELECT $1,$2,$3,$4,1,$5,'sms',$6,$7,$8,'unverified',$9 WHERE NOT EXISTS(SELECT 1 FROM (SELECT DISTINCT ON(endpoint_key) endpoint_key,contact_id,address_hash,state FROM assistant.contact_delivery_endpoints WHERE owner_user_id=$1 ORDER BY endpoint_key,revision DESC) effective WHERE effective.contact_id=$5 AND effective.address_hash=$7 AND effective.state<>'removed')`, [ownerUserId2.toString(), randomUUID56(), endpointRef, randomUUID56(), row.id, protectedAddress.ciphertext, protectedAddress.digest, maskedPhone(phone), at]);
71458
+ SELECT $1,$2,$3,$4,1,$5,'sms',$6,$7,$8,'unverified',$9 WHERE NOT EXISTS(SELECT 1 FROM (SELECT DISTINCT ON(endpoint_key) endpoint_key,contact_id,address_hash,state FROM assistant.contact_delivery_endpoints WHERE owner_user_id=$1 ORDER BY endpoint_key,revision DESC) effective WHERE effective.contact_id=$5 AND effective.address_hash=$7 AND effective.state<>'removed')`, [ownerUserId2.toString(), randomUUID57(), endpointRef, randomUUID57(), row.id, protectedAddress.ciphertext, protectedAddress.digest, maskedPhone(phone), at]);
70731
71459
  await audit(client2, ownerUserId2.toString(), "assistant.contact.create", row.public_id, at);
70732
71460
  const projected = await client2.query(`SELECT ${CONTACT_PROJECTION} AS projection FROM assistant.contacts contact WHERE contact.owner_user_id=$1 AND contact.public_id=$2`, [ownerUserId2.toString(), row.public_id]);
70733
71461
  return projected.rows[0].projection;
@@ -70752,7 +71480,7 @@ function createPostgresPersonalAssistantControlPlaneStore(options) {
70752
71480
  if (!DIGEST4.test(protectedAddress.digest)) throw new TypeError("protected address digest is invalid");
70753
71481
  return tx(async (client2) => {
70754
71482
  const result3 = await client2.query(`INSERT INTO assistant.contact_delivery_endpoints(owner_user_id,id,public_id,endpoint_key,revision,contact_id,channel,address_ciphertext,address_hash,masked_display,state,created_at)
70755
- SELECT $1,$2,$3,$4,1,contact.id,$5,$6,$7,$8,'unverified',$9 FROM assistant.contacts contact WHERE contact.owner_user_id=$1 AND contact.public_id=$10 AND contact.deleted_at IS NULL AND NOT EXISTS(SELECT 1 FROM (SELECT DISTINCT ON(endpoint_key) endpoint_key,address_hash,state FROM assistant.contact_delivery_endpoints WHERE owner_user_id=$1 ORDER BY endpoint_key,revision DESC) effective WHERE effective.address_hash=$7 AND effective.state<>'removed')`, [ownerUserId2.toString(), randomUUID56(), endpointRef, randomUUID56(), channel, protectedAddress.ciphertext, protectedAddress.digest, maskedPhone(phone), at, ref4(contactRef)]);
71483
+ SELECT $1,$2,$3,$4,1,contact.id,$5,$6,$7,$8,'unverified',$9 FROM assistant.contacts contact WHERE contact.owner_user_id=$1 AND contact.public_id=$10 AND contact.deleted_at IS NULL AND NOT EXISTS(SELECT 1 FROM (SELECT DISTINCT ON(endpoint_key) endpoint_key,address_hash,state FROM assistant.contact_delivery_endpoints WHERE owner_user_id=$1 ORDER BY endpoint_key,revision DESC) effective WHERE effective.address_hash=$7 AND effective.state<>'removed')`, [ownerUserId2.toString(), randomUUID57(), endpointRef, randomUUID57(), channel, protectedAddress.ciphertext, protectedAddress.digest, maskedPhone(phone), at, ref4(contactRef)]);
70756
71484
  if (!result3.rowCount) return null;
70757
71485
  await client2.query(`UPDATE assistant.contacts SET phone_ciphertext=COALESCE(phone_ciphertext,$3),phone_hash=COALESCE(phone_hash,$4),updated_at=$5 WHERE owner_user_id=$1 AND public_id=$2`, [ownerUserId2.toString(), contactRef, protectedAddress.ciphertext, protectedAddress.digest, at]);
70758
71486
  await audit(client2, ownerUserId2.toString(), "assistant.contact.delivery_endpoint.add", endpointRef, at);
@@ -70765,7 +71493,7 @@ function createPostgresPersonalAssistantControlPlaneStore(options) {
70765
71493
  if (!DIGEST4.test(protectedAddress.digest)) throw new TypeError("protected address digest is invalid");
70766
71494
  return tx(async (client2) => {
70767
71495
  const result3 = await client2.query(`INSERT INTO assistant.contact_delivery_endpoints(owner_user_id,id,public_id,endpoint_key,revision,contact_id,channel,address_ciphertext,address_hash,masked_display,state,created_at)
70768
- SELECT prior.owner_user_id,$4,$5,prior.endpoint_key,prior.revision+1,prior.contact_id,prior.channel,$6,$7,$8,'unverified',$9 FROM assistant.contact_delivery_endpoints prior JOIN assistant.contacts contact ON contact.owner_user_id=prior.owner_user_id AND contact.id=prior.contact_id WHERE prior.owner_user_id=$1 AND contact.public_id=$2 AND prior.public_id=$3 AND prior.state<>'removed' AND NOT EXISTS(SELECT 1 FROM (SELECT DISTINCT ON(endpoint_key) endpoint_key,address_hash,state FROM assistant.contact_delivery_endpoints WHERE owner_user_id=$1 ORDER BY endpoint_key,revision DESC) effective WHERE effective.address_hash=$7 AND effective.state<>'removed' AND effective.endpoint_key<>prior.endpoint_key)`, [ownerUserId2.toString(), ref4(contactRef), ref4(deliveryEndpointRef), randomUUID56(), nextRef, protectedAddress.ciphertext, protectedAddress.digest, maskedPhone(phone), at]);
71496
+ SELECT prior.owner_user_id,$4,$5,prior.endpoint_key,prior.revision+1,prior.contact_id,prior.channel,$6,$7,$8,'unverified',$9 FROM assistant.contact_delivery_endpoints prior JOIN assistant.contacts contact ON contact.owner_user_id=prior.owner_user_id AND contact.id=prior.contact_id WHERE prior.owner_user_id=$1 AND contact.public_id=$2 AND prior.public_id=$3 AND prior.state<>'removed' AND NOT EXISTS(SELECT 1 FROM (SELECT DISTINCT ON(endpoint_key) endpoint_key,address_hash,state FROM assistant.contact_delivery_endpoints WHERE owner_user_id=$1 ORDER BY endpoint_key,revision DESC) effective WHERE effective.address_hash=$7 AND effective.state<>'removed' AND effective.endpoint_key<>prior.endpoint_key)`, [ownerUserId2.toString(), ref4(contactRef), ref4(deliveryEndpointRef), randomUUID57(), nextRef, protectedAddress.ciphertext, protectedAddress.digest, maskedPhone(phone), at]);
70769
71497
  if (!result3.rowCount) return null;
70770
71498
  await client2.query(`UPDATE assistant.contacts SET phone_ciphertext=$3,phone_hash=$4,updated_at=$5 WHERE owner_user_id=$1 AND public_id=$2`, [ownerUserId2.toString(), contactRef, protectedAddress.ciphertext, protectedAddress.digest, at]);
70771
71499
  await audit(client2, ownerUserId2.toString(), "assistant.contact.delivery_endpoint.update", nextRef, at);
@@ -70777,7 +71505,7 @@ function createPostgresPersonalAssistantControlPlaneStore(options) {
70777
71505
  const body3 = record3(input), at = now().toISOString(), nextRef = newRef2("delivery");
70778
71506
  return tx(async (client2) => {
70779
71507
  const result3 = await client2.query(`INSERT INTO assistant.contact_delivery_endpoints(owner_user_id,id,public_id,endpoint_key,revision,contact_id,channel,address_ciphertext,address_hash,masked_display,state,reason_code,created_at)
70780
- SELECT prior.owner_user_id,$4,$5,prior.endpoint_key,prior.revision+1,prior.contact_id,prior.channel,prior.address_ciphertext,prior.address_hash,prior.masked_display,'removed',$6,$7 FROM assistant.contact_delivery_endpoints prior JOIN assistant.contacts contact ON contact.owner_user_id=prior.owner_user_id AND contact.id=prior.contact_id WHERE prior.owner_user_id=$1 AND contact.public_id=$2 AND prior.public_id=$3 AND prior.state<>'removed'`, [ownerUserId2.toString(), ref4(contactRef), ref4(deliveryEndpointRef), randomUUID56(), nextRef, optionalText3(body3, "reasonCode") ?? "owner_removed", at]);
71508
+ SELECT prior.owner_user_id,$4,$5,prior.endpoint_key,prior.revision+1,prior.contact_id,prior.channel,prior.address_ciphertext,prior.address_hash,prior.masked_display,'removed',$6,$7 FROM assistant.contact_delivery_endpoints prior JOIN assistant.contacts contact ON contact.owner_user_id=prior.owner_user_id AND contact.id=prior.contact_id WHERE prior.owner_user_id=$1 AND contact.public_id=$2 AND prior.public_id=$3 AND prior.state<>'removed'`, [ownerUserId2.toString(), ref4(contactRef), ref4(deliveryEndpointRef), randomUUID57(), nextRef, optionalText3(body3, "reasonCode") ?? "owner_removed", at]);
70781
71509
  if (!result3.rowCount) return null;
70782
71510
  await client2.query(`WITH effective AS(SELECT DISTINCT ON(endpoint_key) endpoint_key,contact_id,address_ciphertext,address_hash,state,revision FROM assistant.contact_delivery_endpoints WHERE owner_user_id=$1 ORDER BY endpoint_key,revision DESC),replacement AS(SELECT DISTINCT ON(contact_id) contact_id,address_ciphertext,address_hash FROM effective WHERE state<>'removed' ORDER BY contact_id,revision DESC) UPDATE assistant.contacts contact SET phone_ciphertext=replacement.address_ciphertext,phone_hash=replacement.address_hash,updated_at=$3 FROM replacement WHERE contact.owner_user_id=$1 AND contact.public_id=$2 AND replacement.contact_id=contact.id`, [ownerUserId2.toString(), contactRef, at]);
70783
71511
  await client2.query(`UPDATE assistant.contacts SET phone_ciphertext=NULL,phone_hash=NULL,updated_at=$3 WHERE owner_user_id=$1 AND public_id=$2 AND NOT EXISTS(SELECT 1 FROM (SELECT DISTINCT ON(endpoint_key) endpoint_key,contact_id,state FROM assistant.contact_delivery_endpoints WHERE owner_user_id=$1 ORDER BY endpoint_key,revision DESC) effective WHERE effective.contact_id=assistant.contacts.id AND effective.state<>'removed')`, [ownerUserId2.toString(), contactRef, at]);
@@ -70801,7 +71529,7 @@ function createPostgresPersonalAssistantControlPlaneStore(options) {
70801
71529
  const body3 = record3(input), contactRef = ref4(text2(body3, "contactRef")), consentRef = ref4(text2(body3, "consentRef")), at = now().toISOString();
70802
71530
  return tx(async (client2) => {
70803
71531
  const result3 = await client2.query(`INSERT INTO assistant.consent_evidence(owner_user_id,id,public_id,contact_id,sender_endpoint_id,recipient_hash,subject_key,message_class,transition,source,proof_digest,captured_at,withdrawn_at)
70804
- SELECT prior.owner_user_id,$3,$4,prior.contact_id,prior.sender_endpoint_id,prior.recipient_hash,prior.subject_key,prior.message_class,'withdrawn','internal_dnc',$5,$6,$6 FROM assistant.consent_evidence prior JOIN assistant.contacts contact ON contact.owner_user_id=prior.owner_user_id AND contact.id=prior.contact_id JOIN assistant.channel_endpoints endpoint ON endpoint.owner_user_id=prior.owner_user_id AND endpoint.id=prior.sender_endpoint_id WHERE prior.owner_user_id=$1 AND prior.public_id=$2 AND contact.public_id=$7 RETURNING public_id,(SELECT public_id FROM assistant.channel_endpoints WHERE owner_user_id=$1 AND id=sender_endpoint_id) sender_ref,subject_key,message_class,proof_digest`, [ownerUserId2.toString(), consentRef, randomUUID56(), newRef2("consent"), digest10({ consentRef, at }), at, contactRef]);
71532
+ SELECT prior.owner_user_id,$3,$4,prior.contact_id,prior.sender_endpoint_id,prior.recipient_hash,prior.subject_key,prior.message_class,'withdrawn','internal_dnc',$5,$6,$6 FROM assistant.consent_evidence prior JOIN assistant.contacts contact ON contact.owner_user_id=prior.owner_user_id AND contact.id=prior.contact_id JOIN assistant.channel_endpoints endpoint ON endpoint.owner_user_id=prior.owner_user_id AND endpoint.id=prior.sender_endpoint_id WHERE prior.owner_user_id=$1 AND prior.public_id=$2 AND contact.public_id=$7 RETURNING public_id,(SELECT public_id FROM assistant.channel_endpoints WHERE owner_user_id=$1 AND id=sender_endpoint_id) sender_ref,subject_key,message_class,proof_digest`, [ownerUserId2.toString(), consentRef, randomUUID57(), newRef2("consent"), digest10({ consentRef, at }), at, contactRef]);
70805
71533
  if (!result3.rows[0]) throw new Error("consent_not_found");
70806
71534
  await audit(client2, ownerUserId2.toString(), "assistant.consent.withdraw", consentRef, at);
70807
71535
  const row = result3.rows[0];
@@ -70811,7 +71539,7 @@ function createPostgresPersonalAssistantControlPlaneStore(options) {
70811
71539
  async createSchedule(ownerUserId2, assistantRef2, input) {
70812
71540
  const body3 = record3(input), scheduleRef = newRef2("schedule"), at = now().toISOString();
70813
71541
  return tx(async (client2) => {
70814
- const result3 = await client2.query(`INSERT INTO assistant.schedules(owner_user_id,id,public_id,assistant_id,source_system,source_ref,source_owner_ref,description,cadence,time_of_day,timezone,logical_vault,status,next_due_at,execution_mode,artifact_selection,source_payload_digest,revision,created_at,updated_at) SELECT $1,$2,$3,assistant.id,$4,$5,$6,$7,$8,$9,$10,$11,'active',$12,$13,$14::jsonb,$15,1,$16,$16 FROM assistant.assistants assistant WHERE assistant.owner_user_id=$1 AND assistant.public_id=$17 RETURNING jsonb_build_object('scheduleRef',public_id,'assistantRef',$17::text,'state',status,'timezone',timezone,'nextDueAt',next_due_at,'revision',revision) AS projection`, [ownerUserId2.toString(), randomUUID56(), scheduleRef, optionalText3(body3, "sourceSystem") ?? "assistant", optionalText3(body3, "sourceRef") ?? scheduleRef, optionalText3(body3, "sourceOwnerRef") ?? ownerUserId2.toString(), text2(body3, "description"), text2(body3, "cadence"), optionalText3(body3, "timeOfDay"), optionalText3(body3, "timezone") ?? "UTC", optionalText3(body3, "logicalVault") ?? "Personal Assistant", text2(body3, "nextDueAt"), optionalText3(body3, "executionMode") ?? "agent", JSON.stringify(body3.artifactSelection ?? { mode: "none" }), digest10(body3), at, ref4(assistantRef2)]);
71542
+ const result3 = await client2.query(`INSERT INTO assistant.schedules(owner_user_id,id,public_id,assistant_id,source_system,source_ref,source_owner_ref,description,cadence,time_of_day,timezone,logical_vault,status,next_due_at,execution_mode,artifact_selection,source_payload_digest,revision,created_at,updated_at) SELECT $1,$2,$3,assistant.id,$4,$5,$6,$7,$8,$9,$10,$11,'active',$12,$13,$14::jsonb,$15,1,$16,$16 FROM assistant.assistants assistant WHERE assistant.owner_user_id=$1 AND assistant.public_id=$17 RETURNING jsonb_build_object('scheduleRef',public_id,'assistantRef',$17::text,'state',status,'timezone',timezone,'nextDueAt',next_due_at,'revision',revision) AS projection`, [ownerUserId2.toString(), randomUUID57(), scheduleRef, optionalText3(body3, "sourceSystem") ?? "assistant", optionalText3(body3, "sourceRef") ?? scheduleRef, optionalText3(body3, "sourceOwnerRef") ?? ownerUserId2.toString(), text2(body3, "description"), text2(body3, "cadence"), optionalText3(body3, "timeOfDay"), optionalText3(body3, "timezone") ?? "UTC", optionalText3(body3, "logicalVault") ?? "Personal Assistant", text2(body3, "nextDueAt"), optionalText3(body3, "executionMode") ?? "agent", JSON.stringify(body3.artifactSelection ?? { mode: "none" }), digest10(body3), at, ref4(assistantRef2)]);
70815
71543
  if (!result3.rows[0]) throw new Error("assistant_not_found");
70816
71544
  await audit(client2, ownerUserId2.toString(), "assistant.schedule.create", scheduleRef, at);
70817
71545
  return result3.rows[0].projection;
@@ -70834,7 +71562,7 @@ function createPostgresPersonalAssistantControlPlaneStore(options) {
70834
71562
  async createReminder(ownerUserId2, assistantRef2, input) {
70835
71563
  const body3 = record3(input), reminderRef2 = newRef2("reminder"), at = now().toISOString(), scheduledFor = text2(body3, "scheduledFor");
70836
71564
  return tx(async (client2) => {
70837
- const result3 = await client2.query(`INSERT INTO assistant.reminder_occurrences(owner_user_id,id,public_id,assistant_id,schedule_id,schedule_ref,occurrence_key,instruction,scheduled_for,timezone,state,revision,created_at,updated_at) SELECT $1,$2,$3,assistant.id,schedule.id,COALESCE(schedule.public_id,$3),$4,$5,$6,$7,'materialized',1,$8,$8 FROM assistant.assistants assistant LEFT JOIN assistant.schedules schedule ON schedule.owner_user_id=assistant.owner_user_id AND schedule.public_id=$9 WHERE assistant.owner_user_id=$1 AND assistant.public_id=$10 RETURNING jsonb_build_object('reminderRef',public_id,'assistantRef',$10::text,'scheduleRef',CASE WHEN schedule_id IS NULL THEN NULL ELSE schedule_ref END,'state','scheduled','instruction',instruction,'scheduledFor',scheduled_for,'timezone',timezone,'revision',revision,'updatedAt',updated_at) AS projection`, [ownerUserId2.toString(), randomUUID56(), reminderRef2, optionalText3(body3, "occurrenceKey") ?? reminderRef2, text2(body3, "instruction"), scheduledFor, optionalText3(body3, "timezone") ?? "UTC", at, optionalText3(body3, "scheduleRef"), ref4(assistantRef2)]);
71565
+ const result3 = await client2.query(`INSERT INTO assistant.reminder_occurrences(owner_user_id,id,public_id,assistant_id,schedule_id,schedule_ref,occurrence_key,instruction,scheduled_for,timezone,state,revision,created_at,updated_at) SELECT $1,$2,$3,assistant.id,schedule.id,COALESCE(schedule.public_id,$3),$4,$5,$6,$7,'materialized',1,$8,$8 FROM assistant.assistants assistant LEFT JOIN assistant.schedules schedule ON schedule.owner_user_id=assistant.owner_user_id AND schedule.public_id=$9 WHERE assistant.owner_user_id=$1 AND assistant.public_id=$10 RETURNING jsonb_build_object('reminderRef',public_id,'assistantRef',$10::text,'scheduleRef',CASE WHEN schedule_id IS NULL THEN NULL ELSE schedule_ref END,'state','scheduled','instruction',instruction,'scheduledFor',scheduled_for,'timezone',timezone,'revision',revision,'updatedAt',updated_at) AS projection`, [ownerUserId2.toString(), randomUUID57(), reminderRef2, optionalText3(body3, "occurrenceKey") ?? reminderRef2, text2(body3, "instruction"), scheduledFor, optionalText3(body3, "timezone") ?? "UTC", at, optionalText3(body3, "scheduleRef"), ref4(assistantRef2)]);
70838
71566
  if (!result3.rows[0]) throw new Error("assistant_not_found");
70839
71567
  await audit(client2, ownerUserId2.toString(), "assistant.reminder.create", reminderRef2, at);
70840
71568
  return result3.rows[0].projection;
@@ -70858,7 +71586,7 @@ function createPostgresPersonalAssistantControlPlaneStore(options) {
70858
71586
  const body3 = record3(input), packetRef = newRef2("packet"), at = now().toISOString(), manifestDigest = text2(body3, "manifestDigest");
70859
71587
  if (!DIGEST4.test(manifestDigest)) throw new TypeError("manifestDigest is invalid");
70860
71588
  return tx(async (client2) => {
70861
- const result3 = await client2.query(`INSERT INTO assistant.context_packet_pointers(owner_user_id,id,public_id,assistant_id,context_version_id,memory_vault_ref,packet_ref,packet_revision,revision,manifest_digest,label,sensitivity,state,created_at,updated_at) SELECT $1,$2,$3,assistant.id,context.id,$4,$5,$6,1,$7,$8,$9,'active',$10,$10 FROM assistant.assistants assistant JOIN LATERAL(SELECT id FROM assistant.context_versions WHERE owner_user_id=assistant.owner_user_id AND assistant_id=assistant.id ORDER BY version DESC LIMIT 1) context ON true WHERE assistant.owner_user_id=$1 AND assistant.public_id=$11 RETURNING jsonb_build_object('packetRef',public_id,'assistantRef',$11::text,'revision',revision,'state',state,'manifestDigest',manifest_digest,'label',label,'updatedAt',updated_at) AS projection`, [ownerUserId2.toString(), randomUUID56(), packetRef, text2(body3, "memoryVaultRef"), text2(body3, "memoryPacketRef", packetRef), optionalText3(body3, "packetRevision") ?? "1", manifestDigest, text2(body3, "label"), optionalText3(body3, "sensitivity") ?? "standard", at, ref4(assistantRef2)]);
71589
+ const result3 = await client2.query(`INSERT INTO assistant.context_packet_pointers(owner_user_id,id,public_id,assistant_id,context_version_id,memory_vault_ref,packet_ref,packet_revision,revision,manifest_digest,label,sensitivity,state,created_at,updated_at) SELECT $1,$2,$3,assistant.id,context.id,$4,$5,$6,1,$7,$8,$9,'active',$10,$10 FROM assistant.assistants assistant JOIN LATERAL(SELECT id FROM assistant.context_versions WHERE owner_user_id=assistant.owner_user_id AND assistant_id=assistant.id ORDER BY version DESC LIMIT 1) context ON true WHERE assistant.owner_user_id=$1 AND assistant.public_id=$11 RETURNING jsonb_build_object('packetRef',public_id,'assistantRef',$11::text,'revision',revision,'state',state,'manifestDigest',manifest_digest,'label',label,'updatedAt',updated_at) AS projection`, [ownerUserId2.toString(), randomUUID57(), packetRef, text2(body3, "memoryVaultRef"), text2(body3, "memoryPacketRef", packetRef), optionalText3(body3, "packetRevision") ?? "1", manifestDigest, text2(body3, "label"), optionalText3(body3, "sensitivity") ?? "standard", at, ref4(assistantRef2)]);
70862
71590
  if (!result3.rows[0]) throw new Error("context_version_not_found");
70863
71591
  await audit(client2, ownerUserId2.toString(), "assistant.context.create", packetRef, at);
70864
71592
  return result3.rows[0].projection;
@@ -70913,7 +71641,7 @@ function createPostgresPersonalAssistantNumberPort(options) {
70913
71641
  }
70914
71642
 
70915
71643
  // src/api/personal-assistant-scheduling-store.ts
70916
- import { createHash as createHash76, randomUUID as randomUUID57 } from "crypto";
71644
+ import { createHash as createHash77, randomUUID as randomUUID58 } from "crypto";
70917
71645
  var PersonalAssistantSchedulingStoreError = class extends Error {
70918
71646
  constructor(code, message = code, status = code === "schedule_not_found" ? 404 : code === "schedule_activation_unavailable" ? 503 : 409) {
70919
71647
  super(message);
@@ -70929,7 +71657,7 @@ function owner3(ownerUserId2) {
70929
71657
  return ownerUserId2.toString();
70930
71658
  }
70931
71659
  function ref5(prefix) {
70932
- return `${prefix}_${randomUUID57().replaceAll("-", "")}`;
71660
+ return `${prefix}_${randomUUID58().replaceAll("-", "")}`;
70933
71661
  }
70934
71662
  function iso4(value) {
70935
71663
  return value instanceof Date ? value.toISOString() : new Date(value).toISOString();
@@ -70940,7 +71668,7 @@ function canonicalJson10(value) {
70940
71668
  return JSON.stringify(value);
70941
71669
  }
70942
71670
  function digest11(value) {
70943
- return createHash76("sha256").update(canonicalJson10(value)).digest("hex");
71671
+ return createHash77("sha256").update(canonicalJson10(value)).digest("hex");
70944
71672
  }
70945
71673
  function authorityClass(value) {
70946
71674
  if (value === "observe") return "observe";
@@ -71053,7 +71781,7 @@ function createPostgresPersonalAssistantSchedulingStore(options) {
71053
71781
  RETURNING id AS schedule_id,revision AS schedule_revision`,
71054
71782
  [
71055
71783
  ownerRef,
71056
- randomUUID57(),
71784
+ randomUUID58(),
71057
71785
  input.draft.scheduleRef,
71058
71786
  input.draft.instruction,
71059
71787
  scheduleCadence(input.draft),
@@ -71087,7 +71815,7 @@ function createPostgresPersonalAssistantSchedulingStore(options) {
71087
71815
  ) VALUES ($1,$2,$3,$4,$5,$6,$7::jsonb,$8,$9,$10::timestamptz,$11::timestamptz)`,
71088
71816
  [
71089
71817
  ownerRef,
71090
- randomUUID57(),
71818
+ randomUUID58(),
71091
71819
  ref5("schedrev"),
71092
71820
  schedule.rows[0].schedule_id,
71093
71821
  input.draft.revision,
@@ -71112,7 +71840,7 @@ function createPostgresPersonalAssistantSchedulingStore(options) {
71112
71840
  AND profile.deleted_at IS NULL AND login.deleted_at IS NULL`,
71113
71841
  [
71114
71842
  ownerRef,
71115
- randomUUID57(),
71843
+ randomUUID58(),
71116
71844
  ref5("sbgrant"),
71117
71845
  schedule.rows[0].schedule_id,
71118
71846
  input.draft.revision,
@@ -71182,7 +71910,7 @@ function createPostgresPersonalAssistantSchedulingStore(options) {
71182
71910
  RETURNING id`,
71183
71911
  [
71184
71912
  ownerRef,
71185
- randomUUID57(),
71913
+ randomUUID58(),
71186
71914
  ref5("sready"),
71187
71915
  row.schedule_id,
71188
71916
  row.revision,
@@ -71231,7 +71959,7 @@ function createPostgresPersonalAssistantSchedulingStore(options) {
71231
71959
  ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12::jsonb,$13::timestamptz)`,
71232
71960
  [
71233
71961
  ownerRef,
71234
- randomUUID57(),
71962
+ randomUUID58(),
71235
71963
  ref5("sactivate"),
71236
71964
  row.schedule_id,
71237
71965
  row.revision,
@@ -71384,7 +72112,7 @@ function assertNoRawTwilioSecretEnvironment(environment2 = process.env) {
71384
72112
  }
71385
72113
 
71386
72114
  // src/api/twilio-messaging-service.ts
71387
- import { createHash as createHash77 } from "crypto";
72115
+ import { createHash as createHash78 } from "crypto";
71388
72116
 
71389
72117
  // src/api/personal-assistant-policy.ts
71390
72118
  var AUTHORITY_RANK = {
@@ -71684,10 +72412,10 @@ function canonicalJson11(value) {
71684
72412
  });
71685
72413
  }
71686
72414
  function digest12(value) {
71687
- return createHash77("sha256").update(canonicalJson11(value)).digest("hex");
72415
+ return createHash78("sha256").update(canonicalJson11(value)).digest("hex");
71688
72416
  }
71689
72417
  function deterministicRef3(prefix, identity) {
71690
- return `${prefix}_${createHash77("sha256").update(identity).digest("hex").slice(0, 32)}`;
72418
+ return `${prefix}_${createHash78("sha256").update(identity).digest("hex").slice(0, 32)}`;
71691
72419
  }
71692
72420
  function isBoundedAuthorityRef(value) {
71693
72421
  return typeof value === "string" && value.length >= 3 && value.length <= 240 && !value.includes("\0");
@@ -71859,7 +72587,7 @@ function inboundIdentity(input, route) {
71859
72587
  };
71860
72588
  }
71861
72589
  function sha256Bytes(bytes2) {
71862
- return createHash77("sha256").update(bytes2).digest("hex");
72590
+ return createHash78("sha256").update(bytes2).digest("hex");
71863
72591
  }
71864
72592
  function startsWith(bytes2, signature) {
71865
72593
  return signature.every((value, index) => bytes2[index] === value);
@@ -73038,11 +73766,11 @@ function createTwilioMessagingService(dependencies = {}) {
73038
73766
  }
73039
73767
 
73040
73768
  // src/api/twilio-memory-media.ts
73041
- import { createHash as createHash78, randomUUID as randomUUID58 } from "crypto";
73769
+ import { createHash as createHash79, randomUUID as randomUUID59 } from "crypto";
73042
73770
  var IMAGE_TYPES = /* @__PURE__ */ new Set(["image/jpeg", "image/png", "image/gif", "image/webp"]);
73043
73771
  var FILE_TYPES = /* @__PURE__ */ new Set(["application/pdf", "text/plain"]);
73044
73772
  function digestBytes(bytes2) {
73045
- return createHash78("sha256").update(bytes2).digest("hex");
73773
+ return createHash79("sha256").update(bytes2).digest("hex");
73046
73774
  }
73047
73775
  function publicPointer(pointer) {
73048
73776
  return Object.freeze({
@@ -73126,7 +73854,7 @@ function createTwilioMemoryMedia(options) {
73126
73854
  return publicPointer(await options.pointers.put({
73127
73855
  ownerBindingRef: input.ownerBindingRef,
73128
73856
  mediaRef: input.mediaRef,
73129
- renewablePointerRef: `memory_asset_${createHash78("sha256").update(`${input.ownerBindingRef}\0${asset.assetId}`).digest("hex").slice(0, 32)}`,
73857
+ renewablePointerRef: `memory_asset_${createHash79("sha256").update(`${input.ownerBindingRef}\0${asset.assetId}`).digest("hex").slice(0, 32)}`,
73130
73858
  byteDigest: input.byteDigest,
73131
73859
  contentType: input.contentType,
73132
73860
  byteSize: input.bytes.byteLength,
@@ -73159,7 +73887,7 @@ function createTwilioMemoryMedia(options) {
73159
73887
  }
73160
73888
 
73161
73889
  // src/api/twilio-provider-facade.ts
73162
- import { createHash as createHash79 } from "crypto";
73890
+ import { createHash as createHash80 } from "crypto";
73163
73891
 
73164
73892
  // src/api/twilio-messaging-client.ts
73165
73893
  import twilio4 from "twilio";
@@ -73340,7 +74068,7 @@ function createTwilioMessagingClient(options) {
73340
74068
  if (!options.accountSid || !options.authToken) throw new Error("twilio_credentials_required");
73341
74069
  return createOfficialAdapter(options.accountSid, options.authToken, defaultDeadlineMs);
73342
74070
  })();
73343
- async function call(operation, work, deadlineMs) {
74071
+ async function call2(operation, work, deadlineMs) {
73344
74072
  const timeoutMs = boundedInteger(deadlineMs, defaultDeadlineMs, TWILIO_CLIENT_LIMITS.minDeadlineMs, TWILIO_CLIENT_LIMITS.maxDeadlineMs, "deadline_ms");
73345
74073
  let timer;
73346
74074
  try {
@@ -73372,7 +74100,7 @@ function createTwilioMessagingClient(options) {
73372
74100
  if (input.areaCode !== void 0 && (!Number.isInteger(input.areaCode) || input.areaCode < 100 || input.areaCode > 999)) throw new RangeError("area_code_out_of_bounds");
73373
74101
  if (input.contains !== void 0 && !/^[0-9A-Za-z*%+$]{2,16}$/.test(input.contains)) throw new TypeError("invalid_number_pattern");
73374
74102
  const bounds2 = listBounds(input.limit, input.pageSize, TWILIO_CLIENT_LIMITS.maxSearchResults);
73375
- const result3 = await call("number.search", () => adapter.searchAvailableNumbers({
74103
+ const result3 = await call2("number.search", () => adapter.searchAvailableNumbers({
73376
74104
  countryCode,
73377
74105
  type: input.type,
73378
74106
  ...bounds2,
@@ -73386,54 +74114,54 @@ function createTwilioMessagingClient(options) {
73386
74114
  },
73387
74115
  listIncomingNumbers: async (input = {}) => {
73388
74116
  const bounds2 = listBounds(input.limit, input.pageSize);
73389
- const result3 = await call("number.list", () => adapter.listIncomingNumbers(bounds2), input.deadlineMs);
74117
+ const result3 = await call2("number.list", () => adapter.listIncomingNumbers(bounds2), input.deadlineMs);
73390
74118
  return result3.slice(0, bounds2.limit).map(projectNumber);
73391
74119
  },
73392
- readIncomingNumber: async (sid, options2 = {}) => projectNumber(await call("number.read", () => adapter.fetchIncomingNumber(assertSid(sid, "number")), options2.deadlineMs)),
73393
- purchaseIncomingNumber: async (input) => projectNumber(await call("number.purchase", () => adapter.purchaseIncomingNumber({
74120
+ readIncomingNumber: async (sid, options2 = {}) => projectNumber(await call2("number.read", () => adapter.fetchIncomingNumber(assertSid(sid, "number")), options2.deadlineMs)),
74121
+ purchaseIncomingNumber: async (input) => projectNumber(await call2("number.purchase", () => adapter.purchaseIncomingNumber({
73394
74122
  phoneNumber: assertE164(input.phoneNumber, "phone_number"),
73395
74123
  ...input.friendlyName === void 0 ? {} : { friendlyName: boundedText2(input.friendlyName, TWILIO_CLIENT_LIMITS.maxFriendlyNameChars, "friendly_name") }
73396
74124
  }), input.deadlineMs)),
73397
- releaseIncomingNumber: async (sid, options2 = {}) => ({ released: await call("number.release", () => adapter.releaseIncomingNumber(assertSid(sid, "number")), options2.deadlineMs) }),
73398
- createMessagingService: async (input) => projectService(await call("messaging_service.create", () => adapter.createMessagingService({
74125
+ releaseIncomingNumber: async (sid, options2 = {}) => ({ released: await call2("number.release", () => adapter.releaseIncomingNumber(assertSid(sid, "number")), options2.deadlineMs) }),
74126
+ createMessagingService: async (input) => projectService(await call2("messaging_service.create", () => adapter.createMessagingService({
73399
74127
  friendlyName: boundedText2(input.friendlyName, TWILIO_CLIENT_LIMITS.maxFriendlyNameChars, "friendly_name"),
73400
74128
  ...input.inboundRequestUrl ? { inboundRequestUrl: assertHttpsUrl(input.inboundRequestUrl, "inbound_request_url") } : {},
73401
74129
  ...input.statusCallback ? { statusCallback: assertHttpsUrl(input.statusCallback, "status_callback") } : {}
73402
74130
  }), input.deadlineMs)),
73403
74131
  listMessagingServices: async (input = {}) => {
73404
74132
  const bounds2 = listBounds(input.limit, input.pageSize);
73405
- const result3 = await call("messaging_service.list", () => adapter.listMessagingServices(bounds2), input.deadlineMs);
74133
+ const result3 = await call2("messaging_service.list", () => adapter.listMessagingServices(bounds2), input.deadlineMs);
73406
74134
  return result3.slice(0, bounds2.limit).map(projectService);
73407
74135
  },
73408
- readMessagingService: async (sid, options2 = {}) => projectService(await call("messaging_service.read", () => adapter.fetchMessagingService(assertSid(sid, "service")), options2.deadlineMs)),
74136
+ readMessagingService: async (sid, options2 = {}) => projectService(await call2("messaging_service.read", () => adapter.fetchMessagingService(assertSid(sid, "service")), options2.deadlineMs)),
73409
74137
  updateMessagingService: async (sid, input) => {
73410
74138
  const patch = {};
73411
74139
  if (input.friendlyName !== void 0) patch.friendlyName = boundedText2(input.friendlyName, TWILIO_CLIENT_LIMITS.maxFriendlyNameChars, "friendly_name");
73412
74140
  if (input.inboundRequestUrl !== void 0) patch.inboundRequestUrl = assertHttpsUrl(input.inboundRequestUrl, "inbound_request_url");
73413
74141
  if (input.statusCallback !== void 0) patch.statusCallback = assertHttpsUrl(input.statusCallback, "status_callback");
73414
74142
  if (!Object.keys(patch).length) throw new TypeError("messaging_service_update_empty");
73415
- return projectService(await call("messaging_service.update", () => adapter.updateMessagingService(assertSid(sid, "service"), patch), input.deadlineMs));
74143
+ return projectService(await call2("messaging_service.update", () => adapter.updateMessagingService(assertSid(sid, "service"), patch), input.deadlineMs));
73416
74144
  },
73417
- deleteMessagingService: async (sid, options2 = {}) => ({ deleted: await call("messaging_service.delete", () => adapter.deleteMessagingService(assertSid(sid, "service")), options2.deadlineMs) }),
73418
- bindMessagingServiceSender: async (serviceSid, phoneNumberSid, options2 = {}) => pick2(await call("messaging_service.sender.bind", () => adapter.bindMessagingServiceSender(assertSid(serviceSid, "service"), { phoneNumberSid: assertSid(phoneNumberSid, "number") }), options2.deadlineMs), ["sid", "phoneNumberSid", "dateCreated"]),
74145
+ deleteMessagingService: async (sid, options2 = {}) => ({ deleted: await call2("messaging_service.delete", () => adapter.deleteMessagingService(assertSid(sid, "service")), options2.deadlineMs) }),
74146
+ bindMessagingServiceSender: async (serviceSid, phoneNumberSid, options2 = {}) => pick2(await call2("messaging_service.sender.bind", () => adapter.bindMessagingServiceSender(assertSid(serviceSid, "service"), { phoneNumberSid: assertSid(phoneNumberSid, "number") }), options2.deadlineMs), ["sid", "phoneNumberSid", "dateCreated"]),
73419
74147
  listMessagingServiceSenders: async (serviceSid, input = {}) => {
73420
74148
  const bounds2 = listBounds(input.limit, input.pageSize);
73421
- const result3 = await call("messaging_service.sender.list", () => adapter.listMessagingServiceSenders(assertSid(serviceSid, "service"), bounds2), input.deadlineMs);
74149
+ const result3 = await call2("messaging_service.sender.list", () => adapter.listMessagingServiceSenders(assertSid(serviceSid, "service"), bounds2), input.deadlineMs);
73422
74150
  return result3.slice(0, bounds2.limit).map((value) => pick2(value, ["sid", "phoneNumberSid", "dateCreated"]));
73423
74151
  },
73424
- unbindMessagingServiceSender: async (serviceSid, senderSid, options2 = {}) => ({ unbound: await call("messaging_service.sender.unbind", () => adapter.unbindMessagingServiceSender(assertSid(serviceSid, "service"), assertSid(senderSid, "sender")), options2.deadlineMs) }),
74152
+ unbindMessagingServiceSender: async (serviceSid, senderSid, options2 = {}) => ({ unbound: await call2("messaging_service.sender.unbind", () => adapter.unbindMessagingServiceSender(assertSid(serviceSid, "service"), assertSid(senderSid, "sender")), options2.deadlineMs) }),
73425
74153
  createRegulatoryBundle: async (input) => {
73426
74154
  const isoCountry = input.isoCountry.trim().toUpperCase();
73427
74155
  if (!/^[A-Z]{2}$/.test(isoCountry)) throw new TypeError("invalid_country_code");
73428
74156
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(input.email) || input.email.length > 254) throw new TypeError("invalid_contact_email");
73429
- return projectRegistration(await call("registration.bundle.create", () => adapter.createRegulatoryBundle({ friendlyName: boundedText2(input.friendlyName, TWILIO_CLIENT_LIMITS.maxFriendlyNameChars, "friendly_name"), email: input.email, endUserType: input.endUserType, isoCountry, numberType: boundedText2(input.numberType, 40, "number_type"), regulationSid: assertSid(input.regulationSid, "regulation") }), input.deadlineMs));
74157
+ return projectRegistration(await call2("registration.bundle.create", () => adapter.createRegulatoryBundle({ friendlyName: boundedText2(input.friendlyName, TWILIO_CLIENT_LIMITS.maxFriendlyNameChars, "friendly_name"), email: input.email, endUserType: input.endUserType, isoCountry, numberType: boundedText2(input.numberType, 40, "number_type"), regulationSid: assertSid(input.regulationSid, "regulation") }), input.deadlineMs));
73430
74158
  },
73431
74159
  listRegulatoryBundles: async (input = {}) => {
73432
74160
  const bounds2 = listBounds(input.limit, input.pageSize);
73433
- const result3 = await call("registration.bundle.list", () => adapter.listRegulatoryBundles({ ...bounds2, ...input.status ? { status: boundedText2(input.status, 40, "status") } : {} }), input.deadlineMs);
74161
+ const result3 = await call2("registration.bundle.list", () => adapter.listRegulatoryBundles({ ...bounds2, ...input.status ? { status: boundedText2(input.status, 40, "status") } : {} }), input.deadlineMs);
73434
74162
  return result3.slice(0, bounds2.limit).map(projectRegistration);
73435
74163
  },
73436
- readRegulatoryBundle: async (sid, options2 = {}) => projectRegistration(await call("registration.bundle.read", () => adapter.fetchRegulatoryBundle(assertSid(sid, "bundle")), options2.deadlineMs)),
74164
+ readRegulatoryBundle: async (sid, options2 = {}) => projectRegistration(await call2("registration.bundle.read", () => adapter.fetchRegulatoryBundle(assertSid(sid, "bundle")), options2.deadlineMs)),
73437
74165
  updateRegulatoryBundle: async (sid, input) => {
73438
74166
  const patch = {};
73439
74167
  if (input.friendlyName !== void 0) patch.friendlyName = boundedText2(input.friendlyName, TWILIO_CLIENT_LIMITS.maxFriendlyNameChars, "friendly_name");
@@ -73442,16 +74170,16 @@ function createTwilioMessagingClient(options) {
73442
74170
  patch.email = input.email;
73443
74171
  }
73444
74172
  if (!Object.keys(patch).length) throw new TypeError("registration_bundle_update_empty");
73445
- return projectRegistration(await call("registration.bundle.update", () => adapter.updateRegulatoryBundle(assertSid(sid, "bundle"), patch), input.deadlineMs));
74173
+ return projectRegistration(await call2("registration.bundle.update", () => adapter.updateRegulatoryBundle(assertSid(sid, "bundle"), patch), input.deadlineMs));
73446
74174
  },
73447
- submitRegulatoryBundle: async (sid, options2 = {}) => projectRegistration(await call("registration.bundle.submit", () => adapter.updateRegulatoryBundle(assertSid(sid, "bundle"), { status: "pending-review" }), options2.deadlineMs)),
73448
- bindRegulatoryItem: async (bundleSid, objectSid, options2 = {}) => pick2(await call("registration.item.bind", () => adapter.bindRegulatoryItem(assertSid(bundleSid, "bundle"), { objectSid: assertSid(objectSid, "regulatoryObject") }), options2.deadlineMs), ["sid", "objectSid", "bundleSid", "dateCreated"]),
74175
+ submitRegulatoryBundle: async (sid, options2 = {}) => projectRegistration(await call2("registration.bundle.submit", () => adapter.updateRegulatoryBundle(assertSid(sid, "bundle"), { status: "pending-review" }), options2.deadlineMs)),
74176
+ bindRegulatoryItem: async (bundleSid, objectSid, options2 = {}) => pick2(await call2("registration.item.bind", () => adapter.bindRegulatoryItem(assertSid(bundleSid, "bundle"), { objectSid: assertSid(objectSid, "regulatoryObject") }), options2.deadlineMs), ["sid", "objectSid", "bundleSid", "dateCreated"]),
73449
74177
  listRegulatoryItems: async (bundleSid, input = {}) => {
73450
74178
  const bounds2 = listBounds(input.limit, input.pageSize);
73451
- const result3 = await call("registration.item.list", () => adapter.listRegulatoryItems(assertSid(bundleSid, "bundle"), bounds2), input.deadlineMs);
74179
+ const result3 = await call2("registration.item.list", () => adapter.listRegulatoryItems(assertSid(bundleSid, "bundle"), bounds2), input.deadlineMs);
73452
74180
  return result3.slice(0, bounds2.limit).map((value) => pick2(value, ["sid", "objectSid", "bundleSid", "dateCreated"]));
73453
74181
  },
73454
- unbindRegulatoryItem: async (bundleSid, itemSid, options2 = {}) => ({ unbound: await call("registration.item.unbind", () => adapter.unbindRegulatoryItem(assertSid(bundleSid, "bundle"), assertSid(itemSid, "item")), options2.deadlineMs) }),
74182
+ unbindRegulatoryItem: async (bundleSid, itemSid, options2 = {}) => ({ unbound: await call2("registration.item.unbind", () => adapter.unbindRegulatoryItem(assertSid(bundleSid, "bundle"), assertSid(itemSid, "item")), options2.deadlineMs) }),
73455
74183
  createMessage: async (input) => {
73456
74184
  if (input.from === void 0 === (input.messagingServiceSid === void 0)) throw new TypeError("message_sender_requires_exactly_one_source");
73457
74185
  if (input.body === void 0 && (!input.mediaUrl || input.mediaUrl.length === 0)) throw new TypeError("message_content_required");
@@ -73466,21 +74194,21 @@ function createTwilioMessagingClient(options) {
73466
74194
  ...input.statusCallback ? { statusCallback: assertHttpsUrl(input.statusCallback, "status_callback") } : {},
73467
74195
  ...input.validityPeriod === void 0 ? {} : { validityPeriod: boundedInteger(input.validityPeriod, 36e3, 1, 36e3, "validity_period") }
73468
74196
  };
73469
- return projectMessage(await call("message.create", () => adapter.createMessage(request), input.deadlineMs));
74197
+ return projectMessage(await call2("message.create", () => adapter.createMessage(request), input.deadlineMs));
73470
74198
  },
73471
74199
  listMessages: async (input = {}) => {
73472
74200
  const bounds2 = listBounds(input.limit, input.pageSize);
73473
- const result3 = await call("message.list", () => adapter.listMessages(bounds2), input.deadlineMs);
74201
+ const result3 = await call2("message.list", () => adapter.listMessages(bounds2), input.deadlineMs);
73474
74202
  return result3.slice(0, bounds2.limit).map(projectMessage);
73475
74203
  },
73476
- readMessage: async (sid, options2 = {}) => projectMessage(await call("message.read", () => adapter.fetchMessage(assertSid(sid, "message")), options2.deadlineMs)),
73477
- cancelMessage: async (sid, options2 = {}) => projectMessage(await call("message.cancel", () => adapter.cancelMessage(assertSid(sid, "message")), options2.deadlineMs)),
74204
+ readMessage: async (sid, options2 = {}) => projectMessage(await call2("message.read", () => adapter.fetchMessage(assertSid(sid, "message")), options2.deadlineMs)),
74205
+ cancelMessage: async (sid, options2 = {}) => projectMessage(await call2("message.cancel", () => adapter.cancelMessage(assertSid(sid, "message")), options2.deadlineMs)),
73478
74206
  listMessageMedia: async (messageSid, input = {}) => {
73479
74207
  const bounds2 = listBounds(input.limit, input.pageSize, TWILIO_CLIENT_LIMITS.maxMediaUrls);
73480
- const result3 = await call("message.media.list", () => adapter.listMedia(assertSid(messageSid, "message"), bounds2), input.deadlineMs);
74208
+ const result3 = await call2("message.media.list", () => adapter.listMedia(assertSid(messageSid, "message"), bounds2), input.deadlineMs);
73481
74209
  return result3.slice(0, bounds2.limit).map(projectMedia);
73482
74210
  },
73483
- readMessageMedia: async (messageSid, mediaSid, options2 = {}) => projectMedia(await call("message.media.read", () => adapter.fetchMedia(assertSid(messageSid, "message"), assertSid(mediaSid, "media")), options2.deadlineMs))
74211
+ readMessageMedia: async (messageSid, mediaSid, options2 = {}) => projectMedia(await call2("message.media.read", () => adapter.fetchMedia(assertSid(messageSid, "message"), assertSid(mediaSid, "media")), options2.deadlineMs))
73484
74212
  });
73485
74213
  }
73486
74214
 
@@ -73494,7 +74222,7 @@ function validAuthority(input) {
73494
74222
  return /^[1-9]\d*$/u.test(input.ownerUserId) && PUBLIC_REF2.test(input.executionRef) && ACCOUNT_SID3.test(input.providerAccountRef) && PUBLIC_REF2.test(input.connectionRef) && /^[A-Za-z][A-Za-z0-9_.:-]{2,159}$/u.test(input.environmentRef);
73495
74223
  }
73496
74224
  function digest13(value) {
73497
- return createHash79("sha256").update(JSON.stringify(value, (_key, entry) => {
74225
+ return createHash80("sha256").update(JSON.stringify(value, (_key, entry) => {
73498
74226
  if (!entry || typeof entry !== "object" || Array.isArray(entry)) return entry;
73499
74227
  return Object.fromEntries(Object.entries(entry).sort(([a], [b]) => a.localeCompare(b)));
73500
74228
  })).digest("hex");
@@ -73683,7 +74411,7 @@ function createTwilioProduction(options) {
73683
74411
  }
73684
74412
 
73685
74413
  // src/runtime/personal-assistant-deployment-config.ts
73686
- import { createHash as createHash80 } from "crypto";
74414
+ import { createHash as createHash81 } from "crypto";
73687
74415
  import { readFileSync as readFileSync4 } from "fs";
73688
74416
  import { resolve as resolve2 } from "path";
73689
74417
  var REF_PATTERN = /^(?:[a-z][a-z0-9+.-]*:\/\/)?[A-Za-z0-9][A-Za-z0-9._:/-]{2,240}$/;
@@ -73719,7 +74447,7 @@ function databaseBinding(value) {
73719
74447
  const database = decodeURIComponent(parsed.pathname.replace(/^\//, ""));
73720
74448
  const role = decodeURIComponent(parsed.username);
73721
74449
  if (!database || !/^[a-z_][a-z0-9_]*$/.test(role)) return null;
73722
- return { fingerprint: createHash80("sha256").update(`${labels.join(".")}\0${database}`).digest("hex"), role };
74450
+ return { fingerprint: createHash81("sha256").update(`${labels.join(".")}\0${database}`).digest("hex"), role };
73723
74451
  } catch {
73724
74452
  return null;
73725
74453
  }
@@ -74181,8 +74909,8 @@ function createPersonalAssistantHostedConfigurationAdapter(input) {
74181
74909
  }
74182
74910
 
74183
74911
  // src/api/personal-assistant-authorization.ts
74184
- import { createHash as createHash81 } from "crypto";
74185
- import { z as z49 } from "zod";
74912
+ import { createHash as createHash82 } from "crypto";
74913
+ import { z as z51 } from "zod";
74186
74914
  var ABUSE_GATED_OPERATIONS = /* @__PURE__ */ new Set(["assistant.message.send", "assistant.bulk.send"]);
74187
74915
  var NORMALIZED_RECIPIENT_OPERATIONS = /* @__PURE__ */ new Set([
74188
74916
  "assistant.message.send",
@@ -74260,27 +74988,27 @@ var RepositoryBackedPersonalAssistantAuthorization = class {
74260
74988
  return result3;
74261
74989
  }
74262
74990
  };
74263
- var AuthorizationContextSchema = z49.object({
74264
- resourceRefs: z49.array(z49.string()).max(100),
74265
- contactRef: z49.string().optional(),
74266
- senderEndpointRef: z49.string().optional(),
74267
- numberRef: z49.string().optional(),
74268
- consentSubjectKey: z49.string().optional(),
74269
- messageClass: z49.enum(["administrative", "transactional", "conversational", "campaign", "compliance"]).optional(),
74270
- recipientHashes: z49.array(z49.string().regex(/^[a-f0-9]{64}$/)).max(1e4),
74271
- recipientCount: z49.number().int().nonnegative(),
74272
- segmentCount: z49.number().int().nonnegative(),
74273
- mediaCount: z49.number().int().nonnegative(),
74274
- byteCount: z49.number().int().nonnegative().safe(),
74275
- spendCurrency: z49.string().regex(/^[A-Z]{3}$/).optional(),
74276
- spendAmountMinor: z49.number().int().nonnegative().safe().optional(),
74277
- destinationCountry: z49.string().regex(/^[A-Z]{2}$/).optional(),
74278
- routingRef: z49.string().optional(),
74279
- audienceDigest: z49.string().regex(/^[a-f0-9]{64}$/).optional(),
74280
- occurrenceRef: z49.string().optional(),
74281
- currentPlanRevision: z49.number().int().positive().optional(),
74282
- validFrom: z49.string(),
74283
- expiresAt: z49.string()
74991
+ var AuthorizationContextSchema = z51.object({
74992
+ resourceRefs: z51.array(z51.string()).max(100),
74993
+ contactRef: z51.string().optional(),
74994
+ senderEndpointRef: z51.string().optional(),
74995
+ numberRef: z51.string().optional(),
74996
+ consentSubjectKey: z51.string().optional(),
74997
+ messageClass: z51.enum(["administrative", "transactional", "conversational", "campaign", "compliance"]).optional(),
74998
+ recipientHashes: z51.array(z51.string().regex(/^[a-f0-9]{64}$/)).max(1e4),
74999
+ recipientCount: z51.number().int().nonnegative(),
75000
+ segmentCount: z51.number().int().nonnegative(),
75001
+ mediaCount: z51.number().int().nonnegative(),
75002
+ byteCount: z51.number().int().nonnegative().safe(),
75003
+ spendCurrency: z51.string().regex(/^[A-Z]{3}$/).optional(),
75004
+ spendAmountMinor: z51.number().int().nonnegative().safe().optional(),
75005
+ destinationCountry: z51.string().regex(/^[A-Z]{2}$/).optional(),
75006
+ routingRef: z51.string().optional(),
75007
+ audienceDigest: z51.string().regex(/^[a-f0-9]{64}$/).optional(),
75008
+ occurrenceRef: z51.string().optional(),
75009
+ currentPlanRevision: z51.number().int().positive().optional(),
75010
+ validFrom: z51.string(),
75011
+ expiresAt: z51.string()
74284
75012
  }).strict().superRefine((value, context) => {
74285
75013
  if (value.spendCurrency === void 0 !== (value.spendAmountMinor === void 0)) {
74286
75014
  context.addIssue({ code: "custom", path: ["spendCurrency"], message: "spend currency and amount must be paired" });
@@ -74323,43 +75051,43 @@ var PostgresPersonalAssistantAuthorizationContextRepository = class {
74323
75051
  return parsed.success ? Object.freeze(parsed.data) : null;
74324
75052
  }
74325
75053
  };
74326
- var MoneySchema2 = z49.object({ currency: z49.string().regex(/^[A-Z]{3}$/), amountMinor: z49.number().int().nonnegative().safe() }).strict();
74327
- var DurablePolicyFactsSchema = z49.object({
74328
- requestedEffect: z49.string().optional(),
74329
- channel: z49.enum(["web", "sms", "mms", "cron", "system", "browser"]).optional(),
74330
- provider: z49.enum(["gmail", "calendar", "zoom", "twilio", "memory", "browser", "assistant"]).optional(),
74331
- accountRef: z49.string().optional(),
74332
- resourceRefs: z49.array(z49.string()).max(100).optional(),
74333
- requestedDomain: z49.string().optional(),
74334
- occurrenceRef: z49.string().optional(),
74335
- audienceDigest: z49.string().nullable().optional(),
74336
- operationCount: z49.number().int().nonnegative().optional(),
74337
- recipientCount: z49.number().int().nonnegative().optional(),
74338
- segmentCount: z49.number().int().nonnegative().optional(),
74339
- byteCount: z49.number().int().nonnegative().safe().optional(),
75054
+ var MoneySchema2 = z51.object({ currency: z51.string().regex(/^[A-Z]{3}$/), amountMinor: z51.number().int().nonnegative().safe() }).strict();
75055
+ var DurablePolicyFactsSchema = z51.object({
75056
+ requestedEffect: z51.string().optional(),
75057
+ channel: z51.enum(["web", "sms", "mms", "cron", "system", "browser"]).optional(),
75058
+ provider: z51.enum(["gmail", "calendar", "zoom", "twilio", "memory", "browser", "assistant"]).optional(),
75059
+ accountRef: z51.string().optional(),
75060
+ resourceRefs: z51.array(z51.string()).max(100).optional(),
75061
+ requestedDomain: z51.string().optional(),
75062
+ occurrenceRef: z51.string().optional(),
75063
+ audienceDigest: z51.string().nullable().optional(),
75064
+ operationCount: z51.number().int().nonnegative().optional(),
75065
+ recipientCount: z51.number().int().nonnegative().optional(),
75066
+ segmentCount: z51.number().int().nonnegative().optional(),
75067
+ byteCount: z51.number().int().nonnegative().safe().optional(),
74340
75068
  spend: MoneySchema2.nullable().optional(),
74341
- costBearing: z49.union([z49.boolean(), z49.literal("unknown")]).optional(),
74342
- actionDigest: z49.string().optional(),
74343
- argumentDigest: z49.string().optional(),
74344
- targetDigest: z49.string().nullable().optional(),
74345
- providerCapability: z49.enum(["available", "unavailable", "unknown"]).optional(),
74346
- actionSwitch: z49.enum(["enabled", "disabled", "unknown"]).optional(),
74347
- accountSwitch: z49.enum(["matched", "unbound", "mismatch", "trial", "unknown"]).optional(),
74348
- grants: z49.object({
74349
- assistant: z49.enum(["allow", "deny", "unknown", "not_applicable"]),
74350
- channel: z49.enum(["allow", "deny", "unknown", "not_applicable"]),
74351
- schedule: z49.enum(["allow", "deny", "unknown", "not_applicable"]),
74352
- conversation: z49.enum(["allow", "deny", "unknown", "not_applicable"])
75069
+ costBearing: z51.union([z51.boolean(), z51.literal("unknown")]).optional(),
75070
+ actionDigest: z51.string().optional(),
75071
+ argumentDigest: z51.string().optional(),
75072
+ targetDigest: z51.string().nullable().optional(),
75073
+ providerCapability: z51.enum(["available", "unavailable", "unknown"]).optional(),
75074
+ actionSwitch: z51.enum(["enabled", "disabled", "unknown"]).optional(),
75075
+ accountSwitch: z51.enum(["matched", "unbound", "mismatch", "trial", "unknown"]).optional(),
75076
+ grants: z51.object({
75077
+ assistant: z51.enum(["allow", "deny", "unknown", "not_applicable"]),
75078
+ channel: z51.enum(["allow", "deny", "unknown", "not_applicable"]),
75079
+ schedule: z51.enum(["allow", "deny", "unknown", "not_applicable"]),
75080
+ conversation: z51.enum(["allow", "deny", "unknown", "not_applicable"])
74353
75081
  }).strict().optional(),
74354
- quietHours: z49.enum(["clear", "active_defer", "timezone_unknown", "not_applicable", "unknown"]).optional(),
74355
- financialAuthorization: z49.enum(["authorized", "missing", "not_required", "unknown"]).optional(),
74356
- bulkConfirmation: z49.enum(["confirmed", "missing", "not_applicable"]).optional()
75082
+ quietHours: z51.enum(["clear", "active_defer", "timezone_unknown", "not_applicable", "unknown"]).optional(),
75083
+ financialAuthorization: z51.enum(["authorized", "missing", "not_required", "unknown"]).optional(),
75084
+ bulkConfirmation: z51.enum(["confirmed", "missing", "not_applicable"]).optional()
74357
75085
  }).strict();
74358
75086
  function canonicalJson12(value) {
74359
75087
  return JSON.stringify(value, (_key, entry) => entry && typeof entry === "object" && !Array.isArray(entry) ? Object.fromEntries(Object.entries(entry).sort(([a], [b]) => a.localeCompare(b))) : entry);
74360
75088
  }
74361
75089
  function factDigest(value) {
74362
- return createHash81("sha256").update(canonicalJson12(value)).digest("hex");
75090
+ return createHash82("sha256").update(canonicalJson12(value)).digest("hex");
74363
75091
  }
74364
75092
  var PostgresPersonalAssistantPolicyFactsRepository = class {
74365
75093
  constructor(db, contexts, now = () => /* @__PURE__ */ new Date()) {
@@ -74549,7 +75277,7 @@ var PostgresPersonalAssistantPolicyFactsRepository = class {
74549
75277
  };
74550
75278
 
74551
75279
  // src/api/personal-assistant-abuse-controls.ts
74552
- import { createHash as createHash82 } from "crypto";
75280
+ import { createHash as createHash83 } from "crypto";
74553
75281
  var EMPTY_STATE = () => ({
74554
75282
  version: 1,
74555
75283
  events: [],
@@ -74560,7 +75288,7 @@ var EMPTY_STATE = () => ({
74560
75288
  bulkIdentities: {}
74561
75289
  });
74562
75290
  function digest14(value) {
74563
- return createHash82("sha256").update(JSON.stringify(value)).digest("hex");
75291
+ return createHash83("sha256").update(JSON.stringify(value)).digest("hex");
74564
75292
  }
74565
75293
  function isDigest(value) {
74566
75294
  return typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
@@ -74820,10 +75548,10 @@ var PostgresPersonalAssistantAbuseStore = class {
74820
75548
  };
74821
75549
 
74822
75550
  // src/api/twilio-authority-billing-postgres.ts
74823
- import { createHash as createHash84, randomUUID as randomUUID59 } from "crypto";
75551
+ import { createHash as createHash85, randomUUID as randomUUID60 } from "crypto";
74824
75552
 
74825
75553
  // src/api/personal-assistant-billing.ts
74826
- import { createHash as createHash83 } from "crypto";
75554
+ import { createHash as createHash84 } from "crypto";
74827
75555
  var AssistantBillingError = class extends Error {
74828
75556
  constructor(code, message) {
74829
75557
  super(message);
@@ -74840,7 +75568,7 @@ function canonicalJson13(value) {
74840
75568
  });
74841
75569
  }
74842
75570
  function digest15(value) {
74843
- return createHash83("sha256").update(canonicalJson13(value)).digest("hex");
75571
+ return createHash84("sha256").update(canonicalJson13(value)).digest("hex");
74844
75572
  }
74845
75573
  function assertMoney(value, field) {
74846
75574
  if (!Number.isSafeInteger(value) || value < 0) throw new AssistantBillingError("billing_invalid_input", `${field} must be a non-negative safe integer.`);
@@ -74885,7 +75613,7 @@ function canonicalJson14(value) {
74885
75613
  });
74886
75614
  }
74887
75615
  function digest16(value) {
74888
- return createHash84("sha256").update(canonicalJson14(value)).digest("hex");
75616
+ return createHash85("sha256").update(canonicalJson14(value)).digest("hex");
74889
75617
  }
74890
75618
  function amountFor2(usage) {
74891
75619
  return usage.reduce((sum2, item) => sum2 + item.units * item.rateMinorPerUnit, 0);
@@ -74957,7 +75685,7 @@ function createPostgresAssistantBillingStore(options = {}) {
74957
75685
  FROM assistant.commands command WHERE command.owner_user_id=$1 AND command.public_id=$14
74958
75686
  RETURNING *, $14::text AS command_ref`, [
74959
75687
  input.ownerUserId.toString(),
74960
- randomUUID59(),
75688
+ randomUUID60(),
74961
75689
  input.billingRef,
74962
75690
  input.idempotencyKey,
74963
75691
  input.requestDigest,
@@ -74977,7 +75705,7 @@ function createPostgresAssistantBillingStore(options = {}) {
74977
75705
  SELECT $1,$2,billing.id,$3,$4,'authorize',$5,$6,$7 FROM assistant.billing_holds billing
74978
75706
  WHERE billing.owner_user_id=$1 AND billing.public_id=$8`, [
74979
75707
  input.ownerUserId.toString(),
74980
- randomUUID59(),
75708
+ randomUUID60(),
74981
75709
  `authorize:${input.idempotencyKey}`,
74982
75710
  inputDigest,
74983
75711
  input.requestDigest,
@@ -75043,7 +75771,7 @@ function createPostgresAssistantBillingStore(options = {}) {
75043
75771
  FROM assistant.billing_holds billing WHERE billing.owner_user_id=$1 AND billing.public_id=$9`,
75044
75772
  [
75045
75773
  input.ownerUserId.toString(),
75046
- randomUUID59(),
75774
+ randomUUID60(),
75047
75775
  input.eventKey,
75048
75776
  eventDigest,
75049
75777
  input.outcome,
@@ -75091,7 +75819,7 @@ function createPostgresAssistantBillingStore(options = {}) {
75091
75819
  FROM assistant.billing_holds billing WHERE billing.owner_user_id=$1 AND billing.public_id=$8`,
75092
75820
  [
75093
75821
  input.ownerUserId.toString(),
75094
- randomUUID59(),
75822
+ randomUUID60(),
75095
75823
  input.eventKey,
75096
75824
  eventDigest,
75097
75825
  input.evidenceDigest,
@@ -75120,7 +75848,7 @@ function createPostgresAssistantBillingStore(options = {}) {
75120
75848
  import {
75121
75849
  createCipheriv as createCipheriv3,
75122
75850
  createDecipheriv as createDecipheriv3,
75123
- createHash as createHash85,
75851
+ createHash as createHash86,
75124
75852
  createHmac as createHmac14,
75125
75853
  randomBytes as randomBytes10
75126
75854
  } from "crypto";
@@ -75178,7 +75906,7 @@ function canonicalContext(input) {
75178
75906
  });
75179
75907
  }
75180
75908
  function contextDigest(context) {
75181
- return createHash85("sha256").update(context, "utf8").digest("hex");
75909
+ return createHash86("sha256").update(context, "utf8").digest("hex");
75182
75910
  }
75183
75911
  function decodeBase64Url(value, expectedBytes) {
75184
75912
  if (!value || !BASE64URL.test(value)) throw new PersonalAssistantProtectedDataCryptoError("protected_data_envelope_invalid");
@@ -75367,8 +76095,8 @@ async function resolvePersonalAssistantProtectedDataCryptoFactory(options) {
75367
76095
  }
75368
76096
 
75369
76097
  // src/api/twilio-first-text-context-postgres.ts
75370
- import { createHash as createHash86 } from "crypto";
75371
- var digest17 = (value) => createHash86("sha256").update(value).digest("hex");
76098
+ import { createHash as createHash87 } from "crypto";
76099
+ var digest17 = (value) => createHash87("sha256").update(value).digest("hex");
75372
76100
  function createPostgresTwilioFirstTextDiagnosticContextResolver(options = {}) {
75373
76101
  const queryable = options.queryable ?? getAssistantPool();
75374
76102
  return async (input) => {
@@ -75413,10 +76141,10 @@ function createPostgresTwilioFirstTextDiagnosticContextResolver(options = {}) {
75413
76141
  }
75414
76142
 
75415
76143
  // src/api/twilio-first-text-diagnostic-postgres.ts
75416
- import { createHash as createHash88, randomBytes as randomBytes12, randomUUID as randomUUID60 } from "crypto";
76144
+ import { createHash as createHash89, randomBytes as randomBytes12, randomUUID as randomUUID61 } from "crypto";
75417
76145
 
75418
76146
  // src/api/twilio-first-text-diagnostic.ts
75419
- import { createHash as createHash87, randomBytes as randomBytes11 } from "crypto";
76147
+ import { createHash as createHash88, randomBytes as randomBytes11 } from "crypto";
75420
76148
  var TWILIO_FIRST_TEXT_BODY = ASSISTANT_CONSENT_CONTENT_V1.diagnosticMessage;
75421
76149
  var TwilioFirstTextDiagnosticError = class extends Error {
75422
76150
  constructor(code) {
@@ -75427,10 +76155,10 @@ var TwilioFirstTextDiagnosticError = class extends Error {
75427
76155
  code;
75428
76156
  };
75429
76157
  function digest18(value) {
75430
- return createHash87("sha256").update(JSON.stringify(value)).digest("hex");
76158
+ return createHash88("sha256").update(JSON.stringify(value)).digest("hex");
75431
76159
  }
75432
76160
  function stableRef2(prefix, identity) {
75433
- return `${prefix}_${createHash87("sha256").update(identity).digest("hex").slice(0, 32)}`;
76161
+ return `${prefix}_${createHash88("sha256").update(identity).digest("hex").slice(0, 32)}`;
75434
76162
  }
75435
76163
  function providerSid(result3) {
75436
76164
  const value = result3.receipt.providerMessageSid;
@@ -75542,14 +76270,14 @@ function createTwilioFirstTextDiagnosticService(dependencies) {
75542
76270
  var COLUMNS = `owner_user_id::text,public_id,idempotency_key,request_digest,policy_version,recipient_ref,sender_ref,
75543
76271
  state,mode,stages,provider_message_sid,inbound_event_ref,routing_receipt_ref,acknowledgement_receipt_ref,
75544
76272
  retry_eligible,failure_code,execution_token_digest,created_at,updated_at`;
75545
- var digest19 = (value) => createHash88("sha256").update(value).digest("hex");
76273
+ var digest19 = (value) => createHash89("sha256").update(value).digest("hex");
75546
76274
  var iso5 = (value) => new Date(value).toISOString();
75547
76275
  function receipt3(row) {
75548
76276
  return Object.freeze({
75549
76277
  diagnosticRef: row.public_id,
75550
76278
  ownerUserId: row.owner_user_id,
75551
76279
  idempotencyKey: row.idempotency_key,
75552
- executionRef: `execution_${createHash88("sha256").update(row.public_id).digest("hex").slice(0, 32)}`,
76280
+ executionRef: `execution_${createHash89("sha256").update(row.public_id).digest("hex").slice(0, 32)}`,
75553
76281
  requestDigest: row.request_digest,
75554
76282
  policyVersion: row.policy_version,
75555
76283
  recipientRef: row.recipient_ref,
@@ -75590,7 +76318,7 @@ function createPostgresTwilioFirstTextDiagnosticStore(options = {}) {
75590
76318
  ON CONFLICT (owner_user_id,idempotency_key) DO NOTHING RETURNING ${COLUMNS}`,
75591
76319
  [
75592
76320
  input.ownerUserId,
75593
- randomUUID60(),
76321
+ randomUUID61(),
75594
76322
  input.diagnosticRef,
75595
76323
  input.idempotencyKey,
75596
76324
  input.requestDigest,
@@ -75717,10 +76445,10 @@ function createTwilioInboundQuarantineClaimAuthorizer(options) {
75717
76445
  }
75718
76446
 
75719
76447
  // src/api/twilio-inbound-claim-control-plane-postgres.ts
75720
- import { createHash as createHash89, randomUUID as randomUUID61 } from "crypto";
75721
- var stableRef3 = (prefix, value) => `${prefix}_${createHash89("sha256").update(value).digest("hex").slice(0, 32)}`;
76448
+ import { createHash as createHash90, randomUUID as randomUUID62 } from "crypto";
76449
+ var stableRef3 = (prefix, value) => `${prefix}_${createHash90("sha256").update(value).digest("hex").slice(0, 32)}`;
75722
76450
  var stableUuid = (value) => {
75723
- const hex = createHash89("sha256").update(value).digest("hex").slice(0, 32).split("");
76451
+ const hex = createHash90("sha256").update(value).digest("hex").slice(0, 32).split("");
75724
76452
  hex[12] = "5";
75725
76453
  hex[16] = (Number.parseInt(hex[16], 16) & 3 | 8).toString(16);
75726
76454
  return `${hex.slice(0, 8).join("")}-${hex.slice(8, 12).join("")}-${hex.slice(12, 16).join("")}-${hex.slice(16, 20).join("")}-${hex.slice(20).join("")}`;
@@ -75771,7 +76499,7 @@ function createPostgresTwilioInboundClaimControlPlane(options) {
75771
76499
  (owner_user_id,id,public_id,endpoint_key,revision,contact_id,channel,address_ciphertext,address_hash,masked_display,state,reason_code,created_at)
75772
76500
  VALUES ($1::bigint,$2,$3,$4,1,$5,'sms',$6,$7,$8,'unverified','claimed_inbound_requires_enrollment',$9::timestamptz)
75773
76501
  ON CONFLICT (owner_user_id,public_id) DO NOTHING`,
75774
- [input.ownerUserId, randomUUID61(), endpointRef, endpointKey, contact.rows[0].id, sender.ciphertext, sender.digest, mask(input.sender), input.occurredAt]
76502
+ [input.ownerUserId, randomUUID62(), endpointRef, endpointKey, contact.rows[0].id, sender.ciphertext, sender.digest, mask(input.sender), input.occurredAt]
75775
76503
  );
75776
76504
  const route = number.rows[0];
75777
76505
  const conversationRef = stableRef3(
@@ -75802,12 +76530,12 @@ function createPostgresTwilioInboundClaimControlPlane(options) {
75802
76530
  }
75803
76531
 
75804
76532
  // src/api/twilio-inbound-envelope-postgres.ts
75805
- import { createHash as createHash91 } from "crypto";
76533
+ import { createHash as createHash92 } from "crypto";
75806
76534
 
75807
76535
  // src/api/twilio-inbound-admission-postgres.ts
75808
- import { createHash as createHash90, randomBytes as randomBytes13, randomUUID as randomUUID62 } from "crypto";
76536
+ import { createHash as createHash91, randomBytes as randomBytes13, randomUUID as randomUUID63 } from "crypto";
75809
76537
  function tokenHash4(value) {
75810
- return createHash90("sha256").update(value).digest("hex");
76538
+ return createHash91("sha256").update(value).digest("hex");
75811
76539
  }
75812
76540
  function rowToRecord(row) {
75813
76541
  return Object.freeze({
@@ -75852,7 +76580,7 @@ function createPostgresTwilioInboundAdmissionControl(options = {}) {
75852
76580
  DO UPDATE SET request_count=assistant.twilio_webhook_rate_buckets.request_count+1,updated_at=EXCLUDED.updated_at
75853
76581
  RETURNING request_count`, [
75854
76582
  input.ownerUserId,
75855
- randomUUID62(),
76583
+ randomUUID63(),
75856
76584
  input.providerAccountRef,
75857
76585
  input.scope,
75858
76586
  input.subjectKey,
@@ -75886,7 +76614,7 @@ function createPostgresTwilioInboundAdmissionStore(options = {}) {
75886
76614
  provider_message_sid,provider_messaging_service_sid,lane_key,routing_state,payload_digest,protected_envelope,state,attempt,admitted_at`,
75887
76615
  [
75888
76616
  input.ownerUserId,
75889
- randomUUID62(),
76617
+ randomUUID63(),
75890
76618
  input.ingressRef,
75891
76619
  input.ownerBindingRef,
75892
76620
  input.providerAccountRef,
@@ -75976,7 +76704,7 @@ function createPostgresTwilioInboundAdmissionStore(options = {}) {
75976
76704
 
75977
76705
  // src/api/twilio-inbound-envelope-postgres.ts
75978
76706
  function stableRef4(prefix, identity) {
75979
- return `${prefix}_${createHash91("sha256").update(identity).digest("hex").slice(0, 32)}`;
76707
+ return `${prefix}_${createHash92("sha256").update(identity).digest("hex").slice(0, 32)}`;
75980
76708
  }
75981
76709
  function parseStoredEnvelope(value) {
75982
76710
  let parsed;
@@ -76190,7 +76918,7 @@ function createPostgresTwilioInboundAdmissionRuntime(options) {
76190
76918
  }
76191
76919
 
76192
76920
  // src/api/twilio-inbound-quarantine-postgres.ts
76193
- import { randomUUID as randomUUID63 } from "crypto";
76921
+ import { randomUUID as randomUUID64 } from "crypto";
76194
76922
  function createPostgresTwilioInboundQuarantineAdmissionControl(options = {}) {
76195
76923
  const transaction2 = options.transaction ?? ((work) => withAssistantTransaction((client2) => work(client2)));
76196
76924
  const windowSeconds = options.windowSeconds ?? 60;
@@ -76270,7 +76998,7 @@ function createPostgresTwilioInboundQuarantineStore(options = {}) {
76270
76998
  ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,'pending',$11,$12::timestamptz,$13::timestamptz,$14::timestamptz,$14::timestamptz)
76271
76999
  ON CONFLICT DO NOTHING RETURNING ${COLUMNS2}`,
76272
77000
  [
76273
- randomUUID63(),
77001
+ randomUUID64(),
76274
77002
  input.quarantineRef,
76275
77003
  input.providerAccountDigest,
76276
77004
  input.providerMessageDigest,
@@ -76338,11 +77066,11 @@ function createPostgresTwilioInboundQuarantineStore(options = {}) {
76338
77066
  }
76339
77067
 
76340
77068
  // src/api/twilio-inbound-quarantine.ts
76341
- import { createHash as createHash92, createHmac as createHmac15, timingSafeEqual as timingSafeEqual10 } from "crypto";
77069
+ import { createHash as createHash93, createHmac as createHmac15, timingSafeEqual as timingSafeEqual10 } from "crypto";
76342
77070
  var DIGEST7 = /^[a-f0-9]{64}$/u;
76343
77071
  var OPAQUE2 = /^[A-Za-z][A-Za-z0-9_.:-]{2,199}$/u;
76344
77072
  function digest20(value) {
76345
- return createHash92("sha256").update(value).digest("hex");
77073
+ return createHash93("sha256").update(value).digest("hex");
76346
77074
  }
76347
77075
  function stableRef5(prefix, identity) {
76348
77076
  return `${prefix}_${digest20(identity).slice(0, 32)}`;
@@ -76657,10 +77385,10 @@ async function createPersonalAssistantTwilioTransportProduction(options) {
76657
77385
  }
76658
77386
 
76659
77387
  // src/api/twilio-number-production.ts
76660
- import { createHash as createHash94, randomUUID as randomUUID65 } from "crypto";
77388
+ import { createHash as createHash95, randomUUID as randomUUID66 } from "crypto";
76661
77389
 
76662
77390
  // src/api/twilio-number-repository.ts
76663
- import { createHash as createHash93, randomUUID as randomUUID64 } from "crypto";
77391
+ import { createHash as createHash94, randomUUID as randomUUID65 } from "crypto";
76664
77392
  var PUBLIC_REF3 = /^[a-z][a-z0-9_]*_[A-Za-z0-9_-]{3,128}$/;
76665
77393
  var DIGEST8 = /^[a-f0-9]{64}$/;
76666
77394
  var ACCOUNT_SID4 = /^AC[0-9a-f]{32}$/i;
@@ -76749,7 +77477,7 @@ function priceValue(value) {
76749
77477
  }), blocker: null });
76750
77478
  }
76751
77479
  function digest21(value) {
76752
- return createHash93("sha256").update(JSON.stringify(value, (_key, entry) => {
77480
+ return createHash94("sha256").update(JSON.stringify(value, (_key, entry) => {
76753
77481
  if (!entry || typeof entry !== "object" || Array.isArray(entry)) return entry;
76754
77482
  return Object.fromEntries(Object.entries(entry).sort(([a], [b]) => a.localeCompare(b)));
76755
77483
  })).digest("hex");
@@ -76876,7 +77604,7 @@ function createPostgresTwilioNumberOwnerRepository(options) {
76876
77604
  const ownerUserId2 = requireOwner(options.ownerUserId);
76877
77605
  const queryable = options.queryable ?? getAssistantPool();
76878
77606
  const transaction2 = options.transaction ?? ((work) => withAssistantTransaction((client2) => work(client2)));
76879
- const newId = options.newId ?? randomUUID64;
77607
+ const newId = options.newId ?? randomUUID65;
76880
77608
  const now = options.now ?? (() => /* @__PURE__ */ new Date());
76881
77609
  const snapshot = validateSnapshot(options.resourceSnapshot, ownerUserId2, now());
76882
77610
  async function numberRow(numberRef) {
@@ -77536,13 +78264,13 @@ function createPostgresTwilioNumberProductionAdapters(options) {
77536
78264
  }
77537
78265
  function twilioProviderAccountDigest(providerAccountRef) {
77538
78266
  if (!ACCOUNT_SID4.test(providerAccountRef)) throw new TwilioNumberRepositoryError("invalid_provider_account", "Twilio account assignment is invalid.", 400);
77539
- return createHash93("sha256").update(providerAccountRef).digest("hex");
78267
+ return createHash94("sha256").update(providerAccountRef).digest("hex");
77540
78268
  }
77541
78269
 
77542
78270
  // src/api/twilio-number-production.ts
77543
78271
  var DIGEST9 = /^[a-f0-9]{64}$/u;
77544
78272
  function hash3(value) {
77545
- return createHash94("sha256").update(typeof value === "string" ? value : JSON.stringify(value, (_key, entry) => {
78273
+ return createHash95("sha256").update(typeof value === "string" ? value : JSON.stringify(value, (_key, entry) => {
77546
78274
  if (!entry || typeof entry !== "object" || Array.isArray(entry)) return entry;
77547
78275
  return Object.fromEntries(Object.entries(entry).sort(([a], [b]) => a.localeCompare(b)));
77548
78276
  })).digest("hex");
@@ -77795,12 +78523,12 @@ function createPostgresTwilioNumberAuthorityAdapters(options) {
77795
78523
  WHERE approval.owner_user_id=$1 AND approval.state IN ('pending','approved') AND command.owner_user_id=approval.owner_user_id
77796
78524
  AND command.id=approval.command_id AND command.assistant_id=$2`, [ownerUserId2.toString(), row.assistant_id]);
77797
78525
  const authorityEpoch = hash3({ ownerUserId: ownerUserId2.toString(), numberRef: input.numberRef, releaseRef: input.releaseRef, occurredAt: input.occurredAt });
77798
- const auditRef = `audit_${randomUUID65().replace(/-/g, "")}`;
78526
+ const auditRef = `audit_${randomUUID66().replace(/-/g, "")}`;
77799
78527
  await client2.query(
77800
78528
  `INSERT INTO assistant.audit_events(owner_user_id,id,public_id,assistant_id,actor_kind,event_type,
77801
78529
  operation,decision,reason_code,correlation_id,evidence_digest,details,occurred_at)
77802
78530
  VALUES($1,$2,$3,$4,'system','twilio.number.release.freeze','twilio.number.release','allow','authority_invalidated',$5,$6,$7::jsonb,$8)`,
77803
- [ownerUserId2.toString(), randomUUID65(), auditRef, row.assistant_id, authorityEpoch, hash3(input.releaseRef), JSON.stringify({ numberRef: input.numberRef, releaseRef: input.releaseRef }), input.occurredAt]
78531
+ [ownerUserId2.toString(), randomUUID66(), auditRef, row.assistant_id, authorityEpoch, hash3(input.releaseRef), JSON.stringify({ numberRef: input.numberRef, releaseRef: input.releaseRef }), input.occurredAt]
77804
78532
  );
77805
78533
  return {
77806
78534
  authorityEpoch,
@@ -77955,7 +78683,7 @@ function createTwilioNumberProductionInterfaces(options) {
77955
78683
  }
77956
78684
 
77957
78685
  // src/api/twilio-number-service.ts
77958
- import { createHash as createHash95, randomUUID as randomUUID66 } from "crypto";
78686
+ import { createHash as createHash96, randomUUID as randomUUID67 } from "crypto";
77959
78687
  var DEFAULT_RESERVATION_TTL_MS = 5 * 60 * 1e3;
77960
78688
  var MIN_RESERVATION_TTL_MS = 60 * 1e3;
77961
78689
  var MAX_RESERVATION_TTL_MS = 10 * 60 * 1e3;
@@ -78091,7 +78819,7 @@ function canonicalJson15(value) {
78091
78819
  });
78092
78820
  }
78093
78821
  function digest22(value) {
78094
- return createHash95("sha256").update(canonicalJson15(value)).digest("hex");
78822
+ return createHash96("sha256").update(canonicalJson15(value)).digest("hex");
78095
78823
  }
78096
78824
  function requireIdempotencyKey(value) {
78097
78825
  if (typeof value !== "string" || !/^[A-Za-z0-9][A-Za-z0-9:._/-]{7,239}$/.test(value)) {
@@ -78212,7 +78940,7 @@ function publicReleaseReceipt(receipt4, replayed = receipt4.replayed) {
78212
78940
  }
78213
78941
  function createTwilioNumberService(dependencies = {}) {
78214
78942
  const now = dependencies.now ?? (() => /* @__PURE__ */ new Date());
78215
- const newId = dependencies.newId ?? randomUUID66;
78943
+ const newId = dependencies.newId ?? randomUUID67;
78216
78944
  const ttlMs = dependencies.reservationTtlMs ?? DEFAULT_RESERVATION_TTL_MS;
78217
78945
  if (!Number.isInteger(ttlMs) || ttlMs < MIN_RESERVATION_TTL_MS || ttlMs > MAX_RESERVATION_TTL_MS) {
78218
78946
  throw new TwilioNumberServiceError("invalid_configuration", "Number reservation lifetime must be from one through ten minutes.", 500);
@@ -79520,7 +80248,7 @@ function presence(env) {
79520
80248
  }
79521
80249
  function fingerprintDigest(env) {
79522
80250
  const value = env.PA_NEON_BINDING_FINGERPRINT?.trim();
79523
- return value ? createHash96("sha256").update("personal-assistant-binding-v1\0").update(value).digest("hex") : null;
80251
+ return value ? createHash97("sha256").update("personal-assistant-binding-v1\0").update(value).digest("hex") : null;
79524
80252
  }
79525
80253
  function missingHostedBindings(env) {
79526
80254
  return Object.entries(REQUIRED_HOSTED_BINDINGS).filter(([, variable]) => !env[variable]?.trim()).map(([name]) => `binding_${name}_missing`);
@@ -79753,7 +80481,7 @@ function shouldRunSiteExtractInBackground(input) {
79753
80481
  }
79754
80482
 
79755
80483
  // src/api/page-media-artifacts.ts
79756
- import { createHash as createHash97, randomBytes as randomBytes14 } from "crypto";
80484
+ import { createHash as createHash98, randomBytes as randomBytes14 } from "crypto";
79757
80485
  import { homedir as homedir4 } from "os";
79758
80486
  import { basename, extname, join as join9 } from "path";
79759
80487
  import pLimit6 from "p-limit";
@@ -79900,7 +80628,7 @@ async function fetchMedia(rawUrl, expectedType) {
79900
80628
  finalUrl: checked.parsed.href,
79901
80629
  width: dimensions?.width ?? null,
79902
80630
  height: dimensions?.height ?? null,
79903
- sha256: createHash97("sha256").update(bytes2).digest("hex")
80631
+ sha256: createHash98("sha256").update(bytes2).digest("hex")
79904
80632
  };
79905
80633
  }
79906
80634
  throw new Error("media_redirect_rejected");
@@ -80106,13 +80834,13 @@ async function reconcileSiteExtractSettlements(limit = 25) {
80106
80834
  }
80107
80835
 
80108
80836
  // src/api/page-diff.ts
80109
- import { createHash as createHash98 } from "crypto";
80837
+ import { createHash as createHash99 } from "crypto";
80110
80838
  import { diffLines } from "diff";
80111
80839
  var MAX_SNAPSHOT_CONTENT_CHARS = 25e4;
80112
80840
  var MAX_DIFF_HUNKS = 200;
80113
80841
  var MAX_DIFF_LINES_PER_RESPONSE = 2e3;
80114
80842
  function sha256Hex(value) {
80115
- return createHash98("sha256").update(value).digest("hex");
80843
+ return createHash99("sha256").update(value).digest("hex");
80116
80844
  }
80117
80845
  function truncateForStorage(value, maxChars = MAX_SNAPSHOT_CONTENT_CHARS) {
80118
80846
  if (value.length <= maxChars) return { value, truncated: false };
@@ -80226,10 +80954,10 @@ async function persistScrapeBody(user, opts) {
80226
80954
  }
80227
80955
 
80228
80956
  // src/api/scrape-image-sink.ts
80229
- import { createHash as createHash99 } from "crypto";
80957
+ import { createHash as createHash100 } from "crypto";
80230
80958
  var MAX_IMAGES_PER_SCRAPE = 25;
80231
80959
  function idempotencyKey3(userId, vault, input) {
80232
- return `scrape-image-${createHash99("sha256").update(`${userId}\0${vault}\0${input.sourceKind}\0${input.sourceUrl}\0${input.imageUrl ?? ""}\0${input.imageBase64 ?? ""}`).digest("hex")}`;
80960
+ return `scrape-image-${createHash100("sha256").update(`${userId}\0${vault}\0${input.sourceKind}\0${input.sourceUrl}\0${input.imageUrl ?? ""}\0${input.imageBase64 ?? ""}`).digest("hex")}`;
80233
80961
  }
80234
80962
  async function persistScrapeImagesToMemory(user, inputs, vault) {
80235
80963
  const selected = inputs.slice(0, MAX_IMAGES_PER_SCRAPE);
@@ -80701,7 +81429,7 @@ function inferredWaybackCapturedAt(content) {
80701
81429
  }
80702
81430
 
80703
81431
  // src/api/connection-memory-import.ts
80704
- import { createHash as createHash100 } from "crypto";
81432
+ import { createHash as createHash101 } from "crypto";
80705
81433
  var CONNECTION_MEMORY_IMPORT_MAX_ARGS_BYTES = 64 * 1024;
80706
81434
  var CONNECTION_MEMORY_IMPORT_MAX_RESULT_BYTES = 1e6;
80707
81435
  var CONNECTION_MEMORY_IMPORT_MAX_STRING_CHARS = 256e3;
@@ -80731,7 +81459,7 @@ function canonicalJson16(value) {
80731
81459
  return JSON.stringify(value);
80732
81460
  }
80733
81461
  function sha2562(value) {
80734
- return createHash100("sha256").update(value).digest("hex");
81462
+ return createHash101("sha256").update(value).digest("hex");
80735
81463
  }
80736
81464
  function sensitiveKey(key3) {
80737
81465
  const normalized = key3.toLowerCase().replace(/[^a-z0-9]/g, "");
@@ -81000,7 +81728,7 @@ async function cleanupExpiredScrapeBlobs(maxAgeMs = SCRAPE_BLOB_TTL_MS) {
81000
81728
  }
81001
81729
 
81002
81730
  // src/api/site-export-reader.ts
81003
- import { createHash as createHash101 } from "crypto";
81731
+ import { createHash as createHash102 } from "crypto";
81004
81732
  var SiteExportFormatUnavailableError = class extends Error {
81005
81733
  constructor(format) {
81006
81734
  super(`The ${format} representation was not retained for this export page.`);
@@ -81010,7 +81738,7 @@ var SiteExportFormatUnavailableError = class extends Error {
81010
81738
  format;
81011
81739
  };
81012
81740
  function sha2563(value) {
81013
- return createHash101("sha256").update(value).digest("hex");
81741
+ return createHash102("sha256").update(value).digest("hex");
81014
81742
  }
81015
81743
  function publicPageRecord(page3) {
81016
81744
  const { bodyMarkdown: _body, contentRef: _contentRef, discoveryLinks: _discovery, ...metadata } = page3;
@@ -81120,7 +81848,7 @@ async function readOwnedSiteExportImage(input) {
81120
81848
  }
81121
81849
 
81122
81850
  // src/api/search-console-table-export.ts
81123
- import { randomUUID as randomUUID67 } from "crypto";
81851
+ import { randomUUID as randomUUID68 } from "crypto";
81124
81852
  var SEARCH_CONSOLE_TABLE_EXPORT_MAX_ROWS = 5e4;
81125
81853
  var SEARCH_CONSOLE_TABLE_EXPORT_PAGE_SIZE = 2e3;
81126
81854
  var SEARCH_CONSOLE_TABLE_EXPORT_MAX_BYTES = 50 * 1024 * 1024;
@@ -81220,7 +81948,7 @@ async function exportSearchConsoleTableData(args) {
81220
81948
  offset += rows.length;
81221
81949
  if (stoppedForBytes || rows.length < limit || offset >= matchedRows) break;
81222
81950
  }
81223
- const exportId = randomUUID67();
81951
+ const exportId = randomUUID68();
81224
81952
  const artifact = await args.writeArtifact({
81225
81953
  ownerId: args.ownerId,
81226
81954
  exportId,
@@ -81575,7 +82303,7 @@ async function dbUsage(identity, plan) {
81575
82303
  }
81576
82304
 
81577
82305
  // src/api/resend-control.ts
81578
- import { createHash as createHash102 } from "crypto";
82306
+ import { createHash as createHash103 } from "crypto";
81579
82307
  var DEFAULT_CONNECTION_CONTROL_URL = "https://mcp-scraper-scheduler.vercel.app";
81580
82308
  var RESEND_PROVIDER_CONFIG_KEY = "resend";
81581
82309
  var RESEND_LOGO_URL = "https://cdn.resend.com/brand/resend-icon-black.svg";
@@ -81834,7 +82562,7 @@ async function callResendRead(identity, connectionId, tool, args) {
81834
82562
  return isRecord9(data) ? data.result ?? data : data;
81835
82563
  }
81836
82564
  async function callResendAction(identity, connectionId, tool, input, idempotencyKey4) {
81837
- const requestId = `main-resend-action:${createHash102("sha256").update(identity).update("\0").update(idempotencyKey4.trim()).digest("hex")}`;
82565
+ const requestId = `main-resend-action:${createHash103("sha256").update(identity).update("\0").update(idempotencyKey4.trim()).digest("hex")}`;
81838
82566
  const body3 = await controlRequest2("/api/internal/resend/actions/call", {
81839
82567
  method: "POST",
81840
82568
  headers: { "x-request-id": requestId },
@@ -81998,7 +82726,7 @@ var requirePaidSchedulingTier = createMiddleware5(async (c, next) => {
81998
82726
  if (!hasPaidSchedulingAccess(user)) return c.json(paidPlanRequiredPayload(), 403);
81999
82727
  return next();
82000
82728
  });
82001
- var app = new Hono48();
82729
+ var app = new Hono49();
82002
82730
  app.use("*", async (_c, next) => {
82003
82731
  await personalAssistantProductionStartup;
82004
82732
  return next();
@@ -83050,7 +83778,7 @@ app.post("/schedule-connections/actions/gmail/send-message", auth5, requireInteg
83050
83778
  }
83051
83779
  try {
83052
83780
  const result3 = await directGmailService.sendMessage({
83053
- ownerId: createHash103("sha256").update(user.api_key).digest("hex").slice(0, 24),
83781
+ ownerId: createHash104("sha256").update(user.api_key).digest("hex").slice(0, 24),
83054
83782
  providerIdentity: user.email,
83055
83783
  connectionId,
83056
83784
  to: body3.to,
@@ -83812,7 +84540,7 @@ app.post("/harvest", auth5, async (c) => {
83812
84540
  if (!harvestOk) return c.json(insufficientBalanceResponse(harvestBal, harvestCost), 402);
83813
84541
  jobId2 = await createJob(user.id, options.query, { ...options, billingHoldMc: harvestCost }, body3.callback_url);
83814
84542
  } else {
83815
- jobId2 = derivedJobId ?? randomUUID68();
84543
+ jobId2 = derivedJobId ?? randomUUID69();
83816
84544
  const billingDebitKey = `paa-harvest:${jobId2}:hold`;
83817
84545
  const description = `PAA harvest: ${options.query}`.slice(0, 500);
83818
84546
  const hold2 = await debitMcIdempotent(
@@ -85367,7 +86095,7 @@ app.get("/cron/tick", async (c) => {
85367
86095
  return c.json({ error: "Unauthorized" }, 401);
85368
86096
  }
85369
86097
  const startedAt = Date.now();
85370
- const { drainQueue } = await import("./worker-5A375BGN.js");
86098
+ const { drainQueue } = await import("./worker-OQSFSLNG.js");
85371
86099
  const budget = { maxJobs: 10, deadlineMs: startedAt + CRON_TICK_DRAIN_BUDGET_MS };
85372
86100
  const origin = `${new URL(c.req.url).protocol}//${new URL(c.req.url).host}`;
85373
86101
  const unfinished = [];
@@ -85491,8 +86219,8 @@ app.post("/api/internal/extract-refinalize/:id", async (c) => {
85491
86219
  finishExtractJob: finishExtractJob2,
85492
86220
  terminalExtractJobStatus: terminalExtractJobStatus2,
85493
86221
  extractJobLimitInfo: extractJobLimitInfo2
85494
- } = await import("./site-extract-repository-DWU52BRQ.js");
85495
- const { assembleExtractArtifacts } = await import("./extract-bundle-NSMGHEG6.js");
86222
+ } = await import("./site-extract-repository-S5FYNFDY.js");
86223
+ const { assembleExtractArtifacts } = await import("./extract-bundle-FALNLKYY.js");
85496
86224
  const existing = await getExtractJob2(jobId2);
85497
86225
  if (!existing) return c.json({ error: "job not found" }, 404);
85498
86226
  if (existing.status !== "failed") {
@@ -85519,7 +86247,7 @@ app.post("/api/internal/extract-refinalize/:id", async (c) => {
85519
86247
  if (!updated) return c.json({ error: "job state changed during re-finalization" }, 409);
85520
86248
  let settlement = "already_settled_or_refunded";
85521
86249
  if (job.billedMc == null && job.userId != null) {
85522
- const { settleExtractJob: settleExtractJob3, countSuccessfulPages: countSuccessfulPages2 } = await import("./site-extract-repository-DWU52BRQ.js");
86250
+ const { settleExtractJob: settleExtractJob3, countSuccessfulPages: countSuccessfulPages2 } = await import("./site-extract-repository-S5FYNFDY.js");
85523
86251
  const heldMc = Number(job.options.heldMc ?? 0);
85524
86252
  const successful = await countSuccessfulPages2(jobId2);
85525
86253
  const usedMc = Math.min(successful * MC_COSTS.page_scrape, heldMc);
@@ -85575,6 +86303,8 @@ app.route("/workshops", workshopRegistrationApp);
85575
86303
  app.route("/editorial-reading-room", editorialReadingRoomApp);
85576
86304
  app.route("/commons", commonsApp);
85577
86305
  app.route("/analytics", analyticsApp);
86306
+ app.route("/crm", crmApp);
86307
+ app.route("/research", researchApp);
85578
86308
  app.route("/", scheduledResultApp);
85579
86309
  app.route("/public", publicScheduledResultApp);
85580
86310
  app.route("/api/internal/scheduled-artifacts", scheduledArtifactInternalApp);