@le-space/core 0.4.4 → 0.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/index.d.ts +40 -2
  2. package/index.js +1108 -901
  3. package/package.json +11 -3
package/index.js CHANGED
@@ -5,7 +5,7 @@ var DEFAULT_ALEPH_CHANNEL = "TEST";
5
5
 
6
6
  // src/manifests.ts
7
7
  var ITEM_HASH_RE = /^[a-fA-F0-9]{64}$/;
8
- var DEFAULT_ALEPH_API_HOST = "https://api2.aleph.im";
8
+ var DEFAULT_ALEPH_API_HOST = "https://api.aleph.im";
9
9
  var DEFAULT_IPFS_GATEWAY_BASE_URL = "https://ipfs.aleph.cloud/ipfs/";
10
10
  function isValidDateString(value) {
11
11
  return value.trim().length > 0 && !Number.isNaN(new Date(value).getTime());
@@ -757,480 +757,498 @@ async function broadcastAlephMessage(message, options) {
757
757
  throw new Error("Broadcast failed: retry budget exhausted");
758
758
  }
759
759
 
760
- // src/forget.ts
761
- function asOptionalReason(value) {
762
- return typeof value === "string" && value.trim() ? value.trim() : void 0;
763
- }
764
- async function createUnsignedForgetMessage(args) {
765
- const content = {
766
- address: args.sender,
767
- time: args.now ?? Date.now() / 1e3,
768
- hashes: [...new Set((args.hashes ?? []).filter(Boolean))],
769
- aggregates: [...new Set((args.aggregates ?? []).filter(Boolean))],
770
- reason: asOptionalReason(args.reason)
771
- };
772
- if (content.hashes.length === 0 && content.aggregates.length === 0) {
773
- throw new Error("FORGET message requires at least one hash or aggregate key.");
774
- }
775
- const itemContent = JSON.stringify(content);
776
- const itemHash = await args.hasher(itemContent);
777
- return {
778
- sender: args.sender,
779
- chain: "ETH",
780
- type: "FORGET",
781
- item_hash: itemHash,
782
- item_type: "inline",
783
- item_content: itemContent,
784
- time: args.now ?? Date.now() / 1e3,
785
- channel: args.channel ?? DEFAULT_ALEPH_CHANNEL
786
- };
787
- }
788
- async function forgetAlephMessages(args) {
789
- args.onProgress?.({
790
- stage: "building-delete-message",
791
- label: "Building delete message",
792
- progress: 18,
793
- status: "info",
794
- itemHash: null,
795
- detail: [...new Set((args.hashes ?? []).filter(Boolean))].join(", ") || null,
796
- error: null,
797
- timestamp: Date.now()
798
- });
799
- const unsignedMessage = await createUnsignedForgetMessage({
800
- sender: args.sender,
801
- hashes: args.hashes,
802
- aggregates: args.aggregates,
803
- reason: args.reason,
804
- hasher: args.hasher,
805
- channel: args.channel,
806
- now: args.now
807
- });
808
- args.onProgress?.({
809
- stage: "signing-delete-message",
810
- label: "Waiting for delete signature",
811
- progress: 42,
812
- status: "info",
813
- itemHash: unsignedMessage.item_hash,
814
- detail: unsignedMessage.item_hash,
815
- error: null,
816
- timestamp: Date.now()
817
- });
818
- const message = await signAlephMessage(unsignedMessage, args.signer);
819
- args.onProgress?.({
820
- stage: "broadcasting-delete",
821
- label: "Broadcasting delete to Aleph",
822
- progress: 68,
823
- status: "warning",
824
- itemHash: message.item_hash,
825
- detail: message.item_hash,
826
- error: null,
827
- timestamp: Date.now()
828
- });
829
- const { response, httpStatus } = await broadcastAlephMessage(message, {
830
- apiHost: args.apiHost,
831
- sync: args.sync,
832
- fetch: args.fetch
833
- });
834
- const status = normalizeBroadcastStatus(httpStatus, response?.message_status);
835
- args.onProgress?.({
836
- stage: status === "rejected" ? "error" : "delete-completed",
837
- label: status === "rejected" ? "Delete rejected by Aleph" : "Delete submitted to Aleph",
838
- progress: 100,
839
- status: status === "rejected" ? "error" : "success",
840
- itemHash: message.item_hash,
841
- detail: status === "rejected" ? String(response?.details ?? "Aleph rejected this delete request.") : null,
842
- error: status === "rejected" ? String(response?.details ?? "Aleph rejected this delete request.") : null,
843
- timestamp: Date.now()
844
- });
845
- return {
846
- sender: args.sender,
847
- itemHash: message.item_hash,
848
- response,
849
- httpStatus,
850
- status
851
- };
852
- }
853
- async function cleanupFailedDeployment(args) {
854
- try {
855
- return await forgetAlephMessages({
856
- sender: args.sender,
857
- hashes: [args.instanceItemHash],
858
- reason: args.reason ?? "Discard failed deployment attempt",
859
- signer: args.signer,
860
- hasher: args.hasher,
861
- fetch: args.fetch,
862
- channel: args.channel,
863
- apiHost: args.apiHost
864
- });
865
- } catch (error) {
866
- return {
867
- error: error instanceof Error ? error.message : String(error)
868
- };
869
- }
870
- }
871
-
872
- // src/retention.ts
873
- var SUCCESSFUL_DEPLOYMENTS_AGGREGATE_KEY = "uc-go-peer-successful-deployments";
760
+ // src/runtime.ts
761
+ var DEFAULT_SCHEDULER_ALLOCATION_URL = "https://scheduler.api.aleph.cloud/api/v0/allocation";
762
+ var DEFAULT_TWO_N_SIX_HASH_URL = "https://api.2n6.me/api/hash";
874
763
  function asString3(value) {
875
764
  return typeof value === "string" && value.trim() ? value.trim() : null;
876
765
  }
877
- function normalizeRetentionRecord(record) {
878
- if (!record || typeof record !== "object" || Array.isArray(record)) return null;
879
- const candidate = record;
880
- const instanceItemHash = asString3(candidate.instance_item_hash);
881
- if (!instanceItemHash) return null;
882
- return {
883
- instance_item_hash: instanceItemHash,
884
- rootfs_item_hash: asString3(candidate.rootfs_item_hash) ?? "",
885
- site_item_hash: asString3(candidate.site_item_hash) ?? "",
886
- rootfs_cid: asString3(candidate.rootfs_cid) ?? "",
887
- site_url: asString3(candidate.site_url) ?? "",
888
- relay_peer_id: asString3(candidate.relay_peer_id) ?? "",
889
- rootfs_version: asString3(candidate.rootfs_version) ?? "",
890
- deployed_at: asString3(candidate.deployed_at) ?? (/* @__PURE__ */ new Date()).toISOString(),
891
- vm_name: asString3(candidate.vm_name) ?? ""
892
- };
893
- }
894
- function normalizeRetentionLedger(value) {
895
- if (Array.isArray(value)) {
896
- return value.map(normalizeRetentionRecord).filter((entry) => entry != null);
897
- }
898
- if (value && typeof value === "object" && Array.isArray(value.deployments)) {
899
- return value.deployments.map(normalizeRetentionRecord).filter((entry) => entry != null);
900
- }
901
- return [];
902
- }
903
- function retentionRecordId(record) {
904
- return [record.instance_item_hash, record.rootfs_item_hash, record.site_item_hash].join(":");
766
+ function asNumber2(value) {
767
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
905
768
  }
906
- function hashesFromRetentionRecord(record) {
907
- return [record.instance_item_hash, record.rootfs_item_hash, record.site_item_hash].filter(Boolean);
769
+ function normalizeIpv6(value) {
770
+ if (typeof value !== "string") return null;
771
+ const normalized = value.trim().toLowerCase();
772
+ if (!normalized) return null;
773
+ const zoneIndex = normalized.indexOf("%");
774
+ return zoneIndex >= 0 ? normalized.slice(0, zoneIndex) : normalized;
908
775
  }
909
- function uniqueHashes(hashes) {
910
- return [...new Set(hashes.filter(Boolean))];
776
+ function isLikelyGlobalIpv6(value) {
777
+ const normalized = normalizeIpv6(value);
778
+ if (!normalized || normalized === "::" || normalized === "::1") return false;
779
+ const firstHextetText = normalized.split(":", 1)[0];
780
+ if (!firstHextetText) return false;
781
+ const firstHextet = Number.parseInt(firstHextetText, 16);
782
+ if (!Number.isFinite(firstHextet)) return false;
783
+ if ((firstHextet & 65024) === 64512) return false;
784
+ if ((firstHextet & 65472) === 65152) return false;
785
+ if ((firstHextet & 65280) === 65280) return false;
786
+ if ((firstHextet & 65472) === 65216) return false;
787
+ return true;
911
788
  }
912
- function dependentHashesFromRetentionRecord(record) {
913
- return [record.rootfs_item_hash, record.site_item_hash].filter(Boolean);
789
+ function findCrnByHash(crns, crnHash) {
790
+ return crns.find((crn) => crn.hash === crnHash) ?? null;
914
791
  }
915
- function splitForgetStages(args) {
916
- const instanceForgetHashes = uniqueHashes(args.prunedRecords.map((record) => record.instance_item_hash)).filter(
917
- (hash) => !args.retainedHashes.has(hash)
792
+ async function fetchSchedulerAllocation(itemHash, options) {
793
+ const response = await options.fetch(
794
+ `${options.schedulerAllocationUrl ?? DEFAULT_SCHEDULER_ALLOCATION_URL}/${itemHash}`,
795
+ { cache: "no-cache" }
918
796
  );
919
- const dependentForgetHashes = uniqueHashes([
920
- ...args.prunedRecords.flatMap(dependentHashesFromRetentionRecord),
921
- ...args.extraForgetHashes
922
- ]).filter((hash) => !args.retainedHashes.has(hash) && !instanceForgetHashes.includes(hash));
923
- return {
924
- instanceForgetHashes,
925
- dependentForgetHashes,
926
- orderedForgetHashes: [...instanceForgetHashes, ...dependentForgetHashes]
927
- };
928
- }
929
- async function fetchAggregateKey(args) {
930
- const requestUrl = new URL(`/api/v0/aggregates/${args.address}.json`, args.apiHost ?? "https://api2.aleph.im");
931
- requestUrl.searchParams.set("keys", args.key);
932
- const response = await args.fetch(requestUrl.toString(), { cache: "no-cache" });
933
- if (response.status === 404) return {};
797
+ if (response.status === 404) return null;
934
798
  if (!response.ok) {
935
- throw new Error(`Aggregate request failed for key ${args.key}: ${response.status}`);
799
+ throw new Error(`Scheduler allocation request failed: ${response.status}`);
936
800
  }
937
801
  const payload = await response.json();
938
- return payload?.data?.[args.key] ?? {};
939
- }
940
- async function createUnsignedAggregateMessage(args) {
941
- const itemContent = JSON.stringify(args.content);
942
- const itemHash = await args.hasher(itemContent);
802
+ const node = payload?.node;
943
803
  return {
944
- sender: args.sender,
945
- chain: "ETH",
946
- type: "AGGREGATE",
947
- item_hash: itemHash,
948
- item_type: "inline",
949
- item_content: itemContent,
950
- time: args.now ?? Date.now() / 1e3,
951
- channel: args.channel ?? DEFAULT_ALEPH_CHANNEL
804
+ source: "scheduler",
805
+ crnHash: asString3(node?.node_id),
806
+ crnUrl: asString3(node?.url),
807
+ node: node ? {
808
+ node_id: asString3(node.node_id) ?? void 0,
809
+ url: asString3(node.url) ?? void 0,
810
+ ipv6: asString3(node.ipv6),
811
+ supports_ipv6: typeof node.supports_ipv6 === "boolean" ? node.supports_ipv6 : void 0
812
+ } : null,
813
+ vmIpv6: asString3(payload?.vm_ipv6),
814
+ period: payload?.period ? {
815
+ start_timestamp: asString3(payload.period.start_timestamp) ?? void 0,
816
+ duration_seconds: asNumber2(payload.period.duration_seconds) ?? void 0
817
+ } : null
952
818
  };
953
819
  }
954
- async function publishAggregateKey(args) {
955
- const aggregateContent = {
956
- address: args.sender,
957
- key: args.key,
958
- content: args.content,
959
- time: args.now ?? Date.now() / 1e3
960
- };
961
- const unsignedMessage = await createUnsignedAggregateMessage({
962
- sender: args.sender,
963
- content: aggregateContent,
964
- hasher: args.hasher,
965
- channel: args.channel,
966
- now: args.now
967
- });
968
- const message = await signAlephMessage(unsignedMessage, args.signer);
969
- const { response, httpStatus } = await broadcastAlephMessage(message, {
970
- apiHost: args.apiHost,
971
- sync: true,
972
- fetch: args.fetch
973
- });
820
+ async function fetch2n6WebAccessUrl(itemHash, options) {
821
+ const response = await options.fetch(
822
+ `${options.twoN6HashUrl ?? DEFAULT_TWO_N_SIX_HASH_URL}/${itemHash}`,
823
+ { cache: "no-cache" }
824
+ );
825
+ if (!response.ok) return null;
826
+ const payload = await response.json();
974
827
  return {
975
- itemHash: message.item_hash,
976
- status: normalizeBroadcastStatus(httpStatus, response?.message_status),
977
- response,
978
- httpStatus
828
+ url: normalizeProxyUrl(payload?.url ?? payload?.subdomain),
829
+ active: typeof payload?.active === "boolean" ? payload.active : null,
830
+ subdomain: asString3(payload?.subdomain)
979
831
  };
980
832
  }
981
- async function fetchMessageStatus(args) {
982
- const requestUrl = new URL(`/api/v0/messages/${args.hash}`, args.apiHost ?? "https://api2.aleph.im");
983
- const response = await args.fetch(requestUrl.toString(), { cache: "no-cache" });
984
- if (response.status === 404) return "missing";
985
- if (!response.ok) return "unknown";
986
- const payload = await response.json();
987
- return asString3(payload?.status) ?? "unknown";
988
- }
989
- async function classifyForgetHashes(args) {
990
- const statuses = {};
991
- for (const hash of args.hashes) {
992
- statuses[hash] = await fetchMessageStatus({
993
- hash,
994
- fetch: args.fetch,
995
- apiHost: args.apiHost
996
- });
833
+ async function fetchCrnExecutionMap(crnUrl, options) {
834
+ const normalizedCrnUrl = String(crnUrl).replace(/\/+$/, "");
835
+ for (const [version, suffix] of [
836
+ ["v2", "/v2/about/executions/list"],
837
+ ["v1", "/about/executions/list"]
838
+ ]) {
839
+ const requestUrl = `${normalizedCrnUrl}${suffix}`;
840
+ const response = await options.fetch(requestUrl, {
841
+ cache: "no-cache"
842
+ });
843
+ if (response.ok) {
844
+ const payload = await response.json();
845
+ return {
846
+ version,
847
+ payload: payload && typeof payload === "object" ? payload : null,
848
+ requestUrl
849
+ };
850
+ }
851
+ if (response.status !== 404) {
852
+ return {
853
+ version,
854
+ payload: null,
855
+ requestUrl
856
+ };
857
+ }
997
858
  }
998
- const forgottenHashes = args.hashes.filter((hash) => statuses[hash] === "forgotten");
999
- const outstandingForgetHashes = args.hashes.filter((hash) => statuses[hash] !== "forgotten");
1000
859
  return {
1001
- forgottenHashes,
1002
- outstandingForgetHashes,
1003
- statuses
860
+ version: "v2",
861
+ payload: null,
862
+ requestUrl: `${normalizedCrnUrl}/v2/about/executions/list`
1004
863
  };
1005
864
  }
1006
- async function executeForgetStage(args) {
1007
- const stageHashes = uniqueHashes(args.hashes);
1008
- let forgetResult = null;
1009
- const followUpForgetResults = [];
1010
- if (stageHashes.length === 0) {
865
+ function describeRuntimeAvailability(runtime) {
866
+ const execution = runtime.execution ?? null;
867
+ const mappedPorts = runtime.mappedPorts ?? {};
868
+ const hostIpv4 = runtime.hostIpv4 ?? null;
869
+ const ipv6 = runtime.ipv6 ?? null;
870
+ const executionGuestIpv6 = execution?.networking?.ipv6_ip ?? null;
871
+ const proxyUrl = runtime.proxyUrl ?? null;
872
+ const schedulerSource = runtime.allocation?.source ?? null;
873
+ const webAccessActive = runtime.webAccess?.active ?? null;
874
+ const mappedPortCount = Object.keys(mappedPorts).length;
875
+ if (hostIpv4 && mappedPortCount > 0 && runtime.requirePublicGuestIpv6ForProxy === true && proxyUrl && executionGuestIpv6 && !isLikelyGlobalIpv6(executionGuestIpv6)) {
1011
876
  return {
1012
- hashes: stageHashes,
1013
- forgottenHashes: [],
1014
- outstandingForgetHashes: [],
1015
- statuses: {},
1016
- forgetResult,
1017
- followUpForgetResults
877
+ state: "execution-invalid-public-ipv6",
878
+ reason: `The CRN exposed runtime networking, but the guest IPv6 (${executionGuestIpv6}) is not globally routable. Proxy-backed HTTPS activation cannot succeed until the CRN reports a public guest IPv6.`,
879
+ schedulerSource,
880
+ executionSeen: Boolean(execution),
881
+ webAccessActive,
882
+ mappedPortCount,
883
+ proxyUrl
1018
884
  };
1019
885
  }
1020
- let classified = await classifyForgetHashes({
1021
- hashes: stageHashes,
1022
- fetch: args.fetch,
1023
- apiHost: args.apiHost
886
+ if (hostIpv4 && mappedPortCount > 0) {
887
+ return {
888
+ state: "ready",
889
+ reason: null,
890
+ schedulerSource,
891
+ executionSeen: Boolean(execution),
892
+ webAccessActive,
893
+ mappedPortCount,
894
+ proxyUrl
895
+ };
896
+ }
897
+ if (!execution && proxyUrl && webAccessActive === false) {
898
+ return {
899
+ state: "proxy-reserved-inactive",
900
+ reason: "Aleph reserved a proxy URL for the VM, but it is still inactive and the selected CRN has not exposed execution networking yet.",
901
+ schedulerSource,
902
+ executionSeen: false,
903
+ webAccessActive,
904
+ mappedPortCount,
905
+ proxyUrl
906
+ };
907
+ }
908
+ if (!execution && schedulerSource === "manual") {
909
+ return {
910
+ state: "crn-execution-missing",
911
+ reason: "The deployment is pinned to a specific CRN, but that CRN is not exposing this VM in its execution list yet.",
912
+ schedulerSource,
913
+ executionSeen: false,
914
+ webAccessActive,
915
+ mappedPortCount,
916
+ proxyUrl
917
+ };
918
+ }
919
+ if (execution && !hostIpv4) {
920
+ return {
921
+ state: "execution-missing-host-ipv4",
922
+ reason: "The CRN exposed an execution record, but it does not include a public host IPv4 yet.",
923
+ schedulerSource,
924
+ executionSeen: true,
925
+ webAccessActive,
926
+ mappedPortCount,
927
+ proxyUrl
928
+ };
929
+ }
930
+ if (execution && mappedPortCount === 0) {
931
+ return {
932
+ state: "execution-missing-port-mappings",
933
+ reason: "The CRN exposed an execution record, but mapped ports are still empty.",
934
+ schedulerSource,
935
+ executionSeen: true,
936
+ webAccessActive,
937
+ mappedPortCount,
938
+ proxyUrl
939
+ };
940
+ }
941
+ return {
942
+ state: "runtime-pending",
943
+ reason: "Aleph has not exposed enough runtime networking details yet.",
944
+ schedulerSource,
945
+ executionSeen: Boolean(execution),
946
+ webAccessActive,
947
+ mappedPortCount,
948
+ proxyUrl
949
+ };
950
+ }
951
+ async function fetchVmRuntime(args) {
952
+ const crns = args.crns ?? await fetchCrns({
953
+ url: args.crnListUrl ?? DEFAULT_CRN_LIST_URL,
954
+ fetch: args.fetch
1024
955
  });
1025
- if (classified.outstandingForgetHashes.length > 0) {
1026
- forgetResult = await forgetAlephMessages({
1027
- sender: args.sender,
1028
- hashes: classified.outstandingForgetHashes,
1029
- reason: args.reason,
1030
- signer: args.signer,
1031
- hasher: args.hasher,
1032
- fetch: args.fetch,
1033
- channel: args.channel,
1034
- apiHost: args.apiHost,
1035
- now: args.now
1036
- });
1037
- classified = await classifyForgetHashes({
1038
- hashes: stageHashes,
1039
- fetch: args.fetch,
1040
- apiHost: args.apiHost
956
+ const schedulerAllocation = await fetchSchedulerAllocation(args.itemHash, {
957
+ fetch: args.fetch,
958
+ schedulerAllocationUrl: args.schedulerAllocationUrl
959
+ }).catch(() => null);
960
+ const selectedCrn = args.crnHash ? findCrnByHash(crns, args.crnHash) : null;
961
+ const allocation = schedulerAllocation ?? (selectedCrn ? {
962
+ source: "manual",
963
+ crnHash: selectedCrn.hash,
964
+ crnUrl: selectedCrn.address,
965
+ node: { url: selectedCrn.address },
966
+ vmIpv6: null,
967
+ period: null
968
+ } : null);
969
+ const webAccess = await fetch2n6WebAccessUrl(args.itemHash, {
970
+ fetch: args.fetch,
971
+ twoN6HashUrl: args.twoN6HashUrl
972
+ }).catch(() => null);
973
+ const webAccessUrl = webAccess?.url ?? null;
974
+ let execution = null;
975
+ let executionLookupBlocked = false;
976
+ if (allocation?.crnUrl) {
977
+ const executionLookup = await fetchCrnExecutionMap(allocation.crnUrl, {
978
+ fetch: args.fetch
1041
979
  });
1042
- if (classified.outstandingForgetHashes.length > 0) {
1043
- for (const hash of classified.outstandingForgetHashes) {
1044
- const result = await forgetAlephMessages({
1045
- sender: args.sender,
1046
- hashes: [hash],
1047
- reason: args.reason,
1048
- signer: args.signer,
1049
- hasher: args.hasher,
1050
- fetch: args.fetch,
1051
- channel: args.channel,
1052
- apiHost: args.apiHost,
1053
- now: args.now
1054
- });
1055
- followUpForgetResults.push({ hash, result });
980
+ const executionPayload = executionLookup.payload?.[args.itemHash];
981
+ if (executionPayload && typeof executionPayload === "object") {
982
+ execution = normalizeExecution(executionPayload, allocation.crnUrl);
983
+ if (!execution.networking.proxy_url && webAccessUrl) {
984
+ execution.networking.proxy_url = webAccessUrl;
1056
985
  }
1057
- classified = await classifyForgetHashes({
1058
- hashes: stageHashes,
1059
- fetch: args.fetch,
1060
- apiHost: args.apiHost
1061
- });
986
+ } else if (executionLookup.payload == null) {
987
+ executionLookupBlocked = true;
1062
988
  }
1063
989
  }
990
+ const hostIpv4 = execution?.networking?.host_ipv4 ?? execution?.networking?.ipv4 ?? null;
991
+ const ipv6 = execution?.networking?.ipv6_ip ?? execution?.networking?.ipv6 ?? allocation?.vmIpv6 ?? null;
992
+ const mappedPorts = execution?.networking?.mapped_ports ?? {};
993
+ const sshPort = mappedPorts?.["22"]?.host ?? null;
994
+ const proxyUrl = execution?.networking?.proxy_url ?? webAccessUrl ?? null;
995
+ const diagnostics = describeRuntimeAvailability({
996
+ allocation,
997
+ execution,
998
+ webAccess,
999
+ hostIpv4,
1000
+ ipv6,
1001
+ proxyUrl,
1002
+ mappedPorts,
1003
+ requirePublicGuestIpv6ForProxy: args.requirePublicGuestIpv6ForProxy
1004
+ });
1064
1005
  return {
1065
- hashes: stageHashes,
1066
- forgottenHashes: classified.forgottenHashes,
1067
- outstandingForgetHashes: classified.outstandingForgetHashes,
1068
- statuses: classified.statuses,
1069
- forgetResult,
1070
- followUpForgetResults
1006
+ allocation,
1007
+ execution,
1008
+ webAccess,
1009
+ webAccessUrl,
1010
+ hostIpv4,
1011
+ ipv6,
1012
+ proxyUrl,
1013
+ mappedPorts,
1014
+ diagnostics,
1015
+ sshCommand: hostIpv4 && sshPort ? `ssh root@${hostIpv4} -p ${sshPort}` : ipv6 ? `ssh root@${ipv6}` : null,
1016
+ selectedCrn,
1017
+ executionLookupBlocked
1071
1018
  };
1072
1019
  }
1073
- async function retainSuccessfulDeployments(args) {
1074
- const keepCount = Math.max(0, Number.parseInt(String(args.keepCount ?? 0), 10) || 0);
1075
- const aggregateKey = asString3(args.aggregateKey) ?? SUCCESSFUL_DEPLOYMENTS_AGGREGATE_KEY;
1076
- const currentRecord = normalizeRetentionRecord(args.currentRecord);
1077
- if (!currentRecord) {
1078
- throw new Error("retainSuccessfulDeployments requires a current deployment record with instance_item_hash.");
1020
+ async function waitForVmRuntime(args) {
1021
+ const attempts = Math.max(1, Number(args.attempts ?? 20));
1022
+ const delayMs = Math.max(0, Number(args.delayMs ?? 4e3));
1023
+ const sleep2 = args.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
1024
+ let lastRuntime = await fetchVmRuntime(args);
1025
+ args.onAttempt?.(lastRuntime, 1, attempts);
1026
+ for (let attempt = 0; attempt < attempts - 1; attempt += 1) {
1027
+ if (lastRuntime.diagnostics?.state === "ready" || lastRuntime.diagnostics?.state === "execution-invalid-public-ipv6") {
1028
+ return lastRuntime;
1029
+ }
1030
+ await sleep2(delayMs);
1031
+ lastRuntime = await fetchVmRuntime(args);
1032
+ args.onAttempt?.(lastRuntime, attempt + 2, attempts);
1079
1033
  }
1080
- const existingValue = await fetchAggregateKey({
1081
- address: args.sender,
1082
- key: aggregateKey,
1083
- fetch: args.fetch,
1084
- apiHost: args.apiHost
1085
- });
1086
- const existingRecords = normalizeRetentionLedger(existingValue);
1087
- const mergedRecords = [currentRecord, ...existingRecords];
1088
- const uniqueRecords = [];
1089
- const seenIds = /* @__PURE__ */ new Set();
1090
- for (const record of mergedRecords) {
1091
- const id = retentionRecordId(record);
1092
- if (seenIds.has(id)) continue;
1093
- seenIds.add(id);
1094
- uniqueRecords.push(record);
1034
+ if (lastRuntime.diagnostics) {
1035
+ lastRuntime.diagnostics.timedOut = true;
1095
1036
  }
1096
- const retainedRecords = keepCount > 0 ? uniqueRecords.slice(0, keepCount) : [];
1097
- const prunedRecords = keepCount > 0 ? uniqueRecords.slice(keepCount) : uniqueRecords;
1098
- const retainedHashes = new Set(retainedRecords.flatMap(hashesFromRetentionRecord));
1099
- const extraForgetHashes = uniqueHashes(args.extraForgetHashes ?? []);
1100
- const { instanceForgetHashes, dependentForgetHashes, orderedForgetHashes } = splitForgetStages({
1101
- prunedRecords,
1102
- extraForgetHashes,
1103
- retainedHashes
1104
- });
1105
- const forgetHashes = orderedForgetHashes;
1106
- const aggregateContent = {
1107
- keep: keepCount,
1108
- updated_at: (/* @__PURE__ */ new Date()).toISOString(),
1109
- deployments: retainedRecords
1037
+ return lastRuntime;
1038
+ }
1039
+
1040
+ // src/crn-control.ts
1041
+ function bytesToHex(bytes) {
1042
+ return Array.from(bytes).map((byte) => byte.toString(16).padStart(2, "0")).join("");
1043
+ }
1044
+ function utf8Hex(value) {
1045
+ return bytesToHex(new TextEncoder().encode(value));
1046
+ }
1047
+ function normalizeHexSignature(signature) {
1048
+ return signature.startsWith("0x") ? signature : `0x${signature}`;
1049
+ }
1050
+ function asString4(value) {
1051
+ return typeof value === "string" && value.trim() ? value.trim() : null;
1052
+ }
1053
+ function trimTrailingSlashes(value) {
1054
+ return value.replace(/\/+$/u, "");
1055
+ }
1056
+ function isoTimestampWithMicros(date = /* @__PURE__ */ new Date()) {
1057
+ return date.toISOString().replace(/\.(\d{3})Z$/u, ".$1000Z");
1058
+ }
1059
+ async function generateEphemeralKeyPair() {
1060
+ return globalThis.crypto.subtle.generateKey(
1061
+ {
1062
+ name: "ECDSA",
1063
+ namedCurve: "P-256"
1064
+ },
1065
+ true,
1066
+ ["sign", "verify"]
1067
+ );
1068
+ }
1069
+ async function exportP256PublicJwk(publicKey) {
1070
+ const jwk = await globalThis.crypto.subtle.exportKey("jwk", publicKey);
1071
+ return {
1072
+ kty: String(jwk.kty ?? "EC"),
1073
+ crv: String(jwk.crv ?? "P-256"),
1074
+ x: String(jwk.x ?? ""),
1075
+ y: String(jwk.y ?? "")
1110
1076
  };
1111
- const aggregatePublication = await publishAggregateKey({
1077
+ }
1078
+ async function buildSignedPubKeyHeader(args) {
1079
+ const payload = {
1080
+ pubkey: await exportP256PublicJwk(args.publicKey),
1081
+ alg: "ECDSA",
1082
+ domain: args.domain,
1083
+ address: args.sender,
1084
+ expires: isoTimestampWithMicros(new Date(Date.now() + 24 * 60 * 60 * 1e3)),
1085
+ chain: "ETH"
1086
+ };
1087
+ const payloadJson = JSON.stringify(payload);
1088
+ const signature = normalizeHexSignature(await args.signer(args.sender, payloadJson));
1089
+ return JSON.stringify({
1112
1090
  sender: args.sender,
1113
- key: aggregateKey,
1114
- content: aggregateContent,
1115
- signer: args.signer,
1116
- hasher: args.hasher,
1091
+ payload: utf8Hex(payloadJson),
1092
+ signature,
1093
+ content: {
1094
+ domain: args.domain
1095
+ }
1096
+ });
1097
+ }
1098
+ async function buildSignedOperationHeader(args) {
1099
+ const payload = {
1100
+ time: isoTimestampWithMicros(),
1101
+ method: args.method,
1102
+ path: args.path,
1103
+ domain: args.domain
1104
+ };
1105
+ const payloadJson = JSON.stringify(payload);
1106
+ const signature = new Uint8Array(
1107
+ await globalThis.crypto.subtle.sign(
1108
+ {
1109
+ name: "ECDSA",
1110
+ hash: "SHA-256"
1111
+ },
1112
+ args.privateKey,
1113
+ new TextEncoder().encode(payloadJson)
1114
+ )
1115
+ );
1116
+ return JSON.stringify({
1117
+ payload: utf8Hex(payloadJson),
1118
+ signature: bytesToHex(signature)
1119
+ });
1120
+ }
1121
+ async function fetchInstanceNodeHash(args) {
1122
+ const envelope = await fetchMessageEnvelope(args.instanceHash, {
1117
1123
  fetch: args.fetch,
1118
- channel: args.channel,
1119
- apiHost: args.apiHost,
1120
- now: args.now
1124
+ apiHost: args.apiHost
1121
1125
  });
1122
- const forgetReason = args.reason ?? `Prune successful deployments beyond retention limit ${keepCount}`;
1123
- const forgetStageResults = [];
1124
- let forgottenHashes = [];
1125
- let outstandingForgetHashes = [];
1126
- let forgetStatuses = {};
1127
- let forgetResult = null;
1128
- const followUpForgetResults = [];
1129
- if (instanceForgetHashes.length > 0) {
1130
- const instanceStage = await executeForgetStage({
1131
- sender: args.sender,
1132
- hashes: instanceForgetHashes,
1133
- reason: forgetReason,
1134
- signer: args.signer,
1135
- hasher: args.hasher,
1136
- fetch: args.fetch,
1137
- channel: args.channel,
1138
- apiHost: args.apiHost,
1139
- now: args.now
1140
- });
1141
- forgetStageResults.push({ stage: "instances", ...instanceStage });
1142
- forgottenHashes.push(...instanceStage.forgottenHashes);
1143
- outstandingForgetHashes.push(...instanceStage.outstandingForgetHashes);
1144
- forgetStatuses = { ...forgetStatuses, ...instanceStage.statuses };
1145
- if (!forgetResult && instanceStage.forgetResult) {
1146
- forgetResult = instanceStage.forgetResult;
1147
- }
1148
- followUpForgetResults.push(...instanceStage.followUpForgetResults);
1126
+ const payload = envelope;
1127
+ return asString4(payload?.content?.requirements?.node?.node_hash) ?? asString4(payload?.message?.content?.requirements?.node?.node_hash) ?? null;
1128
+ }
1129
+ async function resolveInstanceCrn(args) {
1130
+ const providedCrnUrl = asString4(args.crnUrl);
1131
+ if (providedCrnUrl) {
1132
+ return {
1133
+ crnUrl: trimTrailingSlashes(providedCrnUrl),
1134
+ crnHash: asString4(args.crnHash),
1135
+ source: "provided"
1136
+ };
1149
1137
  }
1150
- if (dependentForgetHashes.length > 0) {
1151
- if (outstandingForgetHashes.length === 0) {
1152
- const dependentStage = await executeForgetStage({
1153
- sender: args.sender,
1154
- hashes: dependentForgetHashes,
1155
- reason: forgetReason,
1156
- signer: args.signer,
1157
- hasher: args.hasher,
1158
- fetch: args.fetch,
1159
- channel: args.channel,
1160
- apiHost: args.apiHost,
1161
- now: args.now
1162
- });
1163
- forgetStageResults.push({ stage: "dependents", ...dependentStage });
1164
- forgottenHashes.push(...dependentStage.forgottenHashes);
1165
- outstandingForgetHashes.push(...dependentStage.outstandingForgetHashes);
1166
- forgetStatuses = { ...forgetStatuses, ...dependentStage.statuses };
1167
- if (!forgetResult && dependentStage.forgetResult) {
1168
- forgetResult = dependentStage.forgetResult;
1169
- }
1170
- followUpForgetResults.push(...dependentStage.followUpForgetResults);
1171
- } else {
1172
- const dependentStageStatus = await classifyForgetHashes({
1173
- hashes: dependentForgetHashes,
1174
- fetch: args.fetch,
1175
- apiHost: args.apiHost
1176
- });
1177
- forgetStageResults.push({
1178
- stage: "dependents",
1179
- hashes: dependentForgetHashes,
1180
- skipped: true,
1181
- skippedReason: "Waiting for instance forget stage to complete before pruning dependent store items.",
1182
- forgottenHashes: dependentStageStatus.forgottenHashes,
1183
- outstandingForgetHashes: dependentStageStatus.outstandingForgetHashes,
1184
- statuses: dependentStageStatus.statuses,
1185
- forgetResult: null,
1186
- followUpForgetResults: []
1187
- });
1188
- forgottenHashes.push(...dependentStageStatus.forgottenHashes);
1189
- outstandingForgetHashes.push(...dependentStageStatus.outstandingForgetHashes);
1190
- forgetStatuses = { ...forgetStatuses, ...dependentStageStatus.statuses };
1138
+ const allocation = await fetchSchedulerAllocation(args.instanceHash, {
1139
+ fetch: args.fetch,
1140
+ schedulerAllocationUrl: args.schedulerAllocationUrl ?? DEFAULT_SCHEDULER_ALLOCATION_URL
1141
+ }).catch(() => null);
1142
+ if (allocation?.crnUrl) {
1143
+ return {
1144
+ crnUrl: trimTrailingSlashes(allocation.crnUrl),
1145
+ crnHash: asString4(allocation.crnHash),
1146
+ source: "scheduler"
1147
+ };
1148
+ }
1149
+ const manualCrnHash = asString4(args.crnHash) ?? await fetchInstanceNodeHash({
1150
+ instanceHash: args.instanceHash,
1151
+ fetch: args.fetch,
1152
+ apiHost: args.apiHost ?? DEFAULT_ALEPH_API_HOST
1153
+ }).catch(() => null);
1154
+ if (manualCrnHash) {
1155
+ const crns = await fetchCrns({
1156
+ url: args.crnListUrl ?? DEFAULT_CRN_LIST_URL,
1157
+ fetch: args.fetch
1158
+ }).catch(() => []);
1159
+ const matchingCrn = crns.find((candidate) => candidate.hash === manualCrnHash);
1160
+ if (matchingCrn?.address) {
1161
+ return {
1162
+ crnUrl: trimTrailingSlashes(matchingCrn.address),
1163
+ crnHash: manualCrnHash,
1164
+ source: "manual"
1165
+ };
1191
1166
  }
1192
1167
  }
1193
- forgottenHashes = uniqueHashes(forgottenHashes);
1194
- outstandingForgetHashes = uniqueHashes(outstandingForgetHashes);
1195
1168
  return {
1196
- sender: args.sender,
1197
- aggregateKey,
1198
- keepCount,
1199
- aggregatePublication,
1200
- retainedRecords,
1201
- prunedRecords,
1202
- forgetHashes,
1203
- forgottenHashes,
1204
- outstandingForgetHashes,
1205
- forgetStatuses,
1206
- forgetResult,
1207
- followUpForgetResults,
1208
- forgetStageResults
1169
+ crnUrl: null,
1170
+ crnHash: manualCrnHash,
1171
+ source: "missing"
1209
1172
  };
1210
1173
  }
1174
+ async function eraseInstanceOnCrn(args) {
1175
+ const resolution = await resolveInstanceCrn({
1176
+ instanceHash: args.instanceHash,
1177
+ fetch: args.fetch,
1178
+ apiHost: args.apiHost,
1179
+ crnUrl: args.crnUrl,
1180
+ crnHash: args.crnHash,
1181
+ crnListUrl: args.crnListUrl,
1182
+ schedulerAllocationUrl: args.schedulerAllocationUrl
1183
+ });
1184
+ if (!resolution.crnUrl) {
1185
+ return {
1186
+ ...resolution,
1187
+ status: "skipped"
1188
+ };
1189
+ }
1190
+ const crnUrl = new URL(resolution.crnUrl);
1191
+ const domain = crnUrl.host;
1192
+ const path = `/control/machine/${args.instanceHash}/erase`;
1193
+ const { privateKey, publicKey } = await generateEphemeralKeyPair();
1194
+ const signedPubKeyHeader = await buildSignedPubKeyHeader({
1195
+ sender: args.sender,
1196
+ signer: args.signer,
1197
+ domain,
1198
+ publicKey
1199
+ });
1200
+ const signedOperationHeader = await buildSignedOperationHeader({
1201
+ privateKey,
1202
+ domain,
1203
+ method: "POST",
1204
+ path
1205
+ });
1206
+ const response = await args.fetch(`${trimTrailingSlashes(resolution.crnUrl)}${path}`, {
1207
+ method: "POST",
1208
+ headers: {
1209
+ "X-SignedPubKey": signedPubKeyHeader,
1210
+ "X-SignedOperation": signedOperationHeader
1211
+ }
1212
+ });
1213
+ if (response.status === 404) {
1214
+ return {
1215
+ ...resolution,
1216
+ status: "missing"
1217
+ };
1218
+ }
1219
+ if (response.ok) {
1220
+ return {
1221
+ ...resolution,
1222
+ status: "erased"
1223
+ };
1224
+ }
1225
+ const errorBody = await response.json().then((payload) => JSON.stringify(payload)).catch(() => "");
1226
+ throw new Error(
1227
+ `CRN erase failed for ${args.instanceHash} on ${resolution.crnUrl}: ${response.status}${errorBody ? ` ${errorBody}` : ""}`
1228
+ );
1229
+ }
1211
1230
 
1212
- // src/aggregate-publication.ts
1213
- function createPortForwardAggregateContent(args) {
1214
- const existingPorts = normalizeExistingPortForwardEntry(args.existingAggregate?.[args.instanceItemHash]);
1215
- const mergedPorts = mergePortFlagMaps(existingPorts, requestedPortFlags(args.requestedPorts));
1216
- return {
1231
+ // src/forget.ts
1232
+ function asOptionalReason(value) {
1233
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
1234
+ }
1235
+ async function createUnsignedForgetMessage(args) {
1236
+ const content = {
1217
1237
  address: args.sender,
1218
- key: "port-forwarding",
1219
- content: {
1220
- [args.instanceItemHash]: {
1221
- ports: mergedPorts
1222
- }
1223
- },
1224
- time: args.now ?? Date.now() / 1e3
1238
+ time: args.now ?? Date.now() / 1e3,
1239
+ hashes: [...new Set((args.hashes ?? []).filter(Boolean))],
1240
+ aggregates: [...new Set((args.aggregates ?? []).filter(Boolean))],
1241
+ reason: asOptionalReason(args.reason)
1225
1242
  };
1226
- }
1227
- async function createUnsignedAggregateMessage2(args) {
1228
- const itemContent = JSON.stringify(args.content);
1243
+ if (content.hashes.length === 0 && content.aggregates.length === 0) {
1244
+ throw new Error("FORGET message requires at least one hash or aggregate key.");
1245
+ }
1246
+ const itemContent = JSON.stringify(content);
1229
1247
  const itemHash = await args.hasher(itemContent);
1230
1248
  return {
1231
1249
  sender: args.sender,
1232
1250
  chain: "ETH",
1233
- type: "AGGREGATE",
1251
+ type: "FORGET",
1234
1252
  item_hash: itemHash,
1235
1253
  item_type: "inline",
1236
1254
  item_content: itemContent,
@@ -1238,169 +1256,165 @@ async function createUnsignedAggregateMessage2(args) {
1238
1256
  channel: args.channel ?? DEFAULT_ALEPH_CHANNEL
1239
1257
  };
1240
1258
  }
1241
- async function ensureInstancePortForwards(args) {
1242
- const requestedPorts = requiredInstancePortForwards(args.manifest);
1243
- const aggregate = await fetchPortForwardAggregate(args.sender, {
1244
- apiHost: args.apiHost,
1245
- fetch: args.fetch
1246
- });
1247
- const content = createPortForwardAggregateContent({
1248
- sender: args.sender,
1249
- instanceItemHash: args.instanceItemHash,
1250
- requestedPorts,
1251
- existingAggregate: aggregate
1259
+ async function forgetAlephMessages(args) {
1260
+ args.onProgress?.({
1261
+ stage: "building-delete-message",
1262
+ label: "Building delete message",
1263
+ progress: 18,
1264
+ status: "info",
1265
+ itemHash: null,
1266
+ detail: [...new Set((args.hashes ?? []).filter(Boolean))].join(", ") || null,
1267
+ error: null,
1268
+ timestamp: Date.now()
1252
1269
  });
1253
- const unsignedMessage = await createUnsignedAggregateMessage2({
1270
+ const unsignedMessage = await createUnsignedForgetMessage({
1254
1271
  sender: args.sender,
1255
- content,
1272
+ hashes: args.hashes,
1273
+ aggregates: args.aggregates,
1274
+ reason: args.reason,
1256
1275
  hasher: args.hasher,
1257
- channel: args.channel
1258
- });
1259
- const message = await signAlephMessage(unsignedMessage, args.signer);
1260
- const { response, httpStatus } = await broadcastAlephMessage(message, {
1261
- apiHost: args.apiHost,
1262
- sync: args.sync,
1263
- fetch: args.fetch
1276
+ channel: args.channel,
1277
+ now: args.now
1278
+ });
1279
+ args.onProgress?.({
1280
+ stage: "signing-delete-message",
1281
+ label: "Waiting for delete signature",
1282
+ progress: 42,
1283
+ status: "info",
1284
+ itemHash: unsignedMessage.item_hash,
1285
+ detail: unsignedMessage.item_hash,
1286
+ error: null,
1287
+ timestamp: Date.now()
1288
+ });
1289
+ const message = await signAlephMessage(unsignedMessage, args.signer);
1290
+ args.onProgress?.({
1291
+ stage: "broadcasting-delete",
1292
+ label: "Broadcasting delete to Aleph",
1293
+ progress: 68,
1294
+ status: "warning",
1295
+ itemHash: message.item_hash,
1296
+ detail: message.item_hash,
1297
+ error: null,
1298
+ timestamp: Date.now()
1299
+ });
1300
+ const { response, httpStatus } = await broadcastAlephMessage(message, {
1301
+ apiHost: args.apiHost,
1302
+ sync: args.sync,
1303
+ fetch: args.fetch
1304
+ });
1305
+ const status = normalizeBroadcastStatus(httpStatus, response?.message_status);
1306
+ args.onProgress?.({
1307
+ stage: status === "rejected" ? "error" : "delete-completed",
1308
+ label: status === "rejected" ? "Delete rejected by Aleph" : "Delete submitted to Aleph",
1309
+ progress: 100,
1310
+ status: status === "rejected" ? "error" : "success",
1311
+ itemHash: message.item_hash,
1312
+ detail: status === "rejected" ? String(response?.details ?? "Aleph rejected this delete request.") : null,
1313
+ error: status === "rejected" ? String(response?.details ?? "Aleph rejected this delete request.") : null,
1314
+ timestamp: Date.now()
1264
1315
  });
1265
- const aggregateStatus = normalizeBroadcastStatus(httpStatus, response.message_status);
1266
- if (aggregateStatus === "rejected") {
1267
- throw new Error(`Port-forward aggregate was rejected by Aleph: ${JSON.stringify(response.details ?? response)}`);
1268
- }
1269
1316
  return {
1270
- aggregateItemHash: message.item_hash,
1271
- aggregateStatus,
1272
- requestedPorts
1317
+ sender: args.sender,
1318
+ itemHash: message.item_hash,
1319
+ response,
1320
+ httpStatus,
1321
+ status
1273
1322
  };
1274
1323
  }
1275
-
1276
- // src/instance-deployment.ts
1277
- var SSH_PUBLIC_KEY_PATTERN = /^(ssh-rsa|ssh-ed25519|ecdsa-sha2-nistp256|ecdsa-sha2-nistp384|ecdsa-sha2-nistp521|sk-ssh-ed25519@openssh\.com|sk-ecdsa-sha2-nistp256@openssh\.com)\s+[A-Za-z0-9+/]+={0,3}(?:\s+.+)?$/;
1278
- function toFiniteNumber(value) {
1279
- if (typeof value === "number") return value;
1280
- if (typeof value === "string" && value.trim()) return Number(value);
1281
- return Number.NaN;
1282
- }
1283
- function normalizeSshPublicKey(value) {
1284
- return value.split(/\r?\n/g).map((line) => line.trim()).filter(Boolean).join(" ").replace(/\s+/g, " ").trim();
1285
- }
1286
- function isValidSshPublicKey(value) {
1287
- return SSH_PUBLIC_KEY_PATTERN.test(normalizeSshPublicKey(value));
1288
- }
1289
- function createDeploymentToken() {
1290
- const randomUuid = globalThis.crypto?.randomUUID?.();
1291
- if (typeof randomUuid === "string" && randomUuid.trim()) {
1292
- return randomUuid;
1324
+ async function cleanupFailedDeployment(args) {
1325
+ try {
1326
+ return await forgetAlephMessages({
1327
+ sender: args.sender,
1328
+ hashes: [args.instanceItemHash],
1329
+ reason: args.reason ?? "Discard failed deployment attempt",
1330
+ signer: args.signer,
1331
+ hasher: args.hasher,
1332
+ fetch: args.fetch,
1333
+ channel: args.channel,
1334
+ apiHost: args.apiHost
1335
+ });
1336
+ } catch (error) {
1337
+ return {
1338
+ error: error instanceof Error ? error.message : String(error)
1339
+ };
1293
1340
  }
1294
- return `deploy-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;
1295
1341
  }
1296
- function appendDeploymentTokenToSshPublicKey(sshPublicKey, ownerAddress, deploymentToken) {
1297
- const normalized = normalizeSshPublicKey(sshPublicKey);
1298
- if (!normalized) return normalized;
1299
- const [algorithm = "", key = ""] = normalized.split(/\s+/, 3);
1300
- const owner = ownerAddress.trim();
1301
- const token = deploymentToken.trim();
1302
- if (!algorithm || !key || !owner || !token) {
1303
- return normalized;
1304
- }
1305
- return `${algorithm} ${key} aleph-bootstrap-config:${owner}:${token}`;
1342
+
1343
+ // src/retention.ts
1344
+ var SUCCESSFUL_DEPLOYMENTS_AGGREGATE_KEY = "uc-go-peer-successful-deployments";
1345
+ function asString5(value) {
1346
+ return typeof value === "string" && value.trim() ? value.trim() : null;
1306
1347
  }
1307
- function createReleaseMetadata(name, rootfsVersion, deployer = "shared-aleph-tooling") {
1348
+ function normalizeRetentionRecord(record) {
1349
+ if (!record || typeof record !== "object" || Array.isArray(record)) return null;
1350
+ const candidate = record;
1351
+ const instanceItemHash = asString5(candidate.instance_item_hash);
1352
+ if (!instanceItemHash) return null;
1308
1353
  return {
1309
- name,
1310
- rootfs_version: rootfsVersion,
1311
- deployer
1354
+ instance_item_hash: instanceItemHash,
1355
+ rootfs_item_hash: asString5(candidate.rootfs_item_hash) ?? "",
1356
+ site_item_hash: asString5(candidate.site_item_hash) ?? "",
1357
+ rootfs_cid: asString5(candidate.rootfs_cid) ?? "",
1358
+ site_url: asString5(candidate.site_url) ?? "",
1359
+ relay_peer_id: asString5(candidate.relay_peer_id) ?? "",
1360
+ rootfs_version: asString5(candidate.rootfs_version) ?? "",
1361
+ deployed_at: asString5(candidate.deployed_at) ?? (/* @__PURE__ */ new Date()).toISOString(),
1362
+ vm_name: asString5(candidate.vm_name) ?? ""
1312
1363
  };
1313
1364
  }
1314
- function selectedTier(pricing, tierId) {
1315
- return pricing?.tiers.find((tier) => tier.id === tierId) ?? null;
1365
+ function normalizeRetentionLedger(value) {
1366
+ if (Array.isArray(value)) {
1367
+ return value.map(normalizeRetentionRecord).filter((entry) => entry != null);
1368
+ }
1369
+ if (value && typeof value === "object" && Array.isArray(value.deployments)) {
1370
+ return value.deployments.map(normalizeRetentionRecord).filter((entry) => entry != null);
1371
+ }
1372
+ return [];
1316
1373
  }
1317
- function tierSpec(pricing, tier) {
1318
- return {
1319
- vcpus: pricing.compute_unit.vcpus * tier.compute_units,
1320
- memoryMiB: pricing.compute_unit.memory_mib * tier.compute_units,
1321
- diskMiB: pricing.compute_unit.disk_mib * tier.compute_units
1322
- };
1374
+ function retentionRecordId(record) {
1375
+ return [record.instance_item_hash, record.rootfs_item_hash, record.site_item_hash].join(":");
1323
1376
  }
1324
- function buildPaymentQuote(tier, pricing, balance) {
1325
- const computeUnitPrice = pricing.price.compute_unit;
1326
- if (!computeUnitPrice) return null;
1327
- const unitPrice = toFiniteNumber(computeUnitPrice.credit);
1328
- if (!Number.isFinite(unitPrice)) return null;
1329
- return {
1330
- required: unitPrice * tier.compute_units,
1331
- available: Number(balance.credit_balance ?? 0),
1332
- computeUnits: tier.compute_units,
1333
- unitPrice,
1334
- label: "credits"
1335
- };
1377
+ function hashesFromRetentionRecord(record) {
1378
+ return [record.instance_item_hash, record.rootfs_item_hash, record.site_item_hash].filter(Boolean);
1336
1379
  }
1337
- function quoteRequiredBudgetUnits(quote) {
1338
- if (!quote) return 0n;
1339
- return BigInt(Math.ceil(quote.required * 1e18));
1380
+ function uniqueHashes(hashes) {
1381
+ return [...new Set(hashes.filter(Boolean))];
1340
1382
  }
1341
- function describeRejectedInstanceBroadcast(response) {
1342
- const balanceMessage = extractInsufficientBalanceMessage(response.details);
1343
- if (balanceMessage) {
1344
- return `Aleph rejected this deployment due to ${balanceMessage}.`;
1345
- }
1346
- const errorCode = typeof response.error_code === "number" ? response.error_code : null;
1347
- return `Aleph rejected this deployment${errorCode ? ` (error ${errorCode})` : ""}.`;
1383
+ function dependentHashesFromRetentionRecord(record) {
1384
+ return [record.rootfs_item_hash, record.site_item_hash].filter(Boolean);
1348
1385
  }
1349
- function createInstanceContent(args) {
1350
- const sshKey = normalizeSshPublicKey(args.sshPublicKey);
1351
- if (!sshKey) {
1352
- throw new Error("An SSH public key is required.");
1353
- }
1354
- if (!isValidSshPublicKey(sshKey)) {
1355
- throw new Error("SSH public key must be a single valid .pub line.");
1356
- }
1357
- if (!args.rootfsItemHash || !/^[a-fA-F0-9]{64}$/.test(args.rootfsItemHash)) {
1358
- throw new Error("rootfsItemHash must be a 64-character Aleph item hash.");
1359
- }
1386
+ function splitForgetStages(args) {
1387
+ const instanceForgetHashes = uniqueHashes(args.prunedRecords.map((record) => record.instance_item_hash)).filter(
1388
+ (hash) => !args.retainedHashes.has(hash)
1389
+ );
1390
+ const dependentForgetHashes = uniqueHashes([
1391
+ ...args.prunedRecords.flatMap(dependentHashesFromRetentionRecord),
1392
+ ...args.extraForgetHashes
1393
+ ]).filter((hash) => !args.retainedHashes.has(hash) && !instanceForgetHashes.includes(hash));
1360
1394
  return {
1361
- address: args.address,
1362
- time: args.now ?? Date.now() / 1e3,
1363
- allow_amend: false,
1364
- metadata: createReleaseMetadata(args.name.trim(), args.rootfsVersion ?? "custom-rootfs", args.deployer),
1365
- authorized_keys: [sshKey],
1366
- environment: {
1367
- internet: true,
1368
- aleph_api: true,
1369
- hypervisor: "qemu",
1370
- reproducible: false,
1371
- shared_cache: false
1372
- },
1373
- resources: {
1374
- vcpus: Number(args.vcpus),
1375
- memory: Number(args.memoryMiB),
1376
- seconds: Number(args.seconds ?? 30)
1377
- },
1378
- payment: {
1379
- type: "credit"
1380
- },
1381
- requirements: args.crnHash ? {
1382
- node: {
1383
- node_hash: args.crnHash
1384
- }
1385
- } : void 0,
1386
- volumes: [],
1387
- rootfs: {
1388
- parent: {
1389
- ref: args.rootfsItemHash,
1390
- use_latest: true
1391
- },
1392
- persistence: "host",
1393
- size_mib: Number(args.rootfsSizeMiB)
1394
- }
1395
+ instanceForgetHashes,
1396
+ dependentForgetHashes,
1397
+ orderedForgetHashes: [...instanceForgetHashes, ...dependentForgetHashes]
1395
1398
  };
1396
1399
  }
1397
- async function createUnsignedInstanceMessage(args) {
1400
+ async function fetchAggregateKey(args) {
1401
+ const requestUrl = new URL(`/api/v0/aggregates/${args.address}.json`, args.apiHost ?? "https://api.aleph.im");
1402
+ requestUrl.searchParams.set("keys", args.key);
1403
+ const response = await args.fetch(requestUrl.toString(), { cache: "no-cache" });
1404
+ if (response.status === 404) return {};
1405
+ if (!response.ok) {
1406
+ throw new Error(`Aggregate request failed for key ${args.key}: ${response.status}`);
1407
+ }
1408
+ const payload = await response.json();
1409
+ return payload?.data?.[args.key] ?? {};
1410
+ }
1411
+ async function createUnsignedAggregateMessage(args) {
1398
1412
  const itemContent = JSON.stringify(args.content);
1399
1413
  const itemHash = await args.hasher(itemContent);
1400
1414
  return {
1401
1415
  sender: args.sender,
1402
1416
  chain: "ETH",
1403
- type: "INSTANCE",
1417
+ type: "AGGREGATE",
1404
1418
  item_hash: itemHash,
1405
1419
  item_type: "inline",
1406
1420
  item_content: itemContent,
@@ -1408,375 +1422,566 @@ async function createUnsignedInstanceMessage(args) {
1408
1422
  channel: args.channel ?? DEFAULT_ALEPH_CHANNEL
1409
1423
  };
1410
1424
  }
1411
- async function createDeploymentIntent(args) {
1412
- const intent = {
1413
- ownerAddress: args.sender,
1414
- messageTime: args.unsignedMessage.time,
1415
- itemHash: args.unsignedMessage.item_hash,
1416
- paymentType: args.content.payment.type,
1417
- rootfsRef: args.content.rootfs.parent.ref,
1418
- rootfsSizeMiB: args.content.rootfs.size_mib,
1419
- computeUnits: args.computeUnits,
1420
- vcpus: args.content.resources.vcpus,
1421
- memoryMiB: args.content.resources.memory,
1422
- crnHash: args.content.requirements?.node?.node_hash ?? null,
1423
- channel: args.unsignedMessage.channel,
1424
- expiresAt: args.expiresAt,
1425
- maxCost: args.maxCost
1425
+ async function publishAggregateKey(args) {
1426
+ const aggregateContent = {
1427
+ address: args.sender,
1428
+ key: args.key,
1429
+ content: args.content,
1430
+ time: args.now ?? Date.now() / 1e3
1426
1431
  };
1427
- return {
1428
- intent,
1429
- intentHash: await args.hasher(JSON.stringify(intent))
1430
- };
1431
- }
1432
- async function deployInstance(args) {
1433
- args.onProgress?.({
1434
- stage: "building-message",
1435
- label: "Building deployment message",
1436
- progress: 32,
1437
- status: "info",
1438
- detail: args.content.metadata?.name ?? null,
1439
- itemHash: null,
1440
- error: null,
1441
- timestamp: Date.now()
1442
- });
1443
- const unsignedMessage = await createUnsignedInstanceMessage({
1444
- sender: args.sender,
1445
- content: args.content,
1446
- hasher: args.hasher,
1447
- channel: args.channel,
1448
- now: args.now
1449
- });
1450
- args.onProgress?.({
1451
- stage: "signing-message",
1452
- label: "Waiting for MetaMask signature",
1453
- progress: 48,
1454
- status: "info",
1455
- detail: unsignedMessage.item_hash,
1456
- itemHash: unsignedMessage.item_hash,
1457
- error: null,
1458
- timestamp: Date.now()
1459
- });
1460
- const signature = await args.signer(unsignedMessage.sender, [unsignedMessage.chain, unsignedMessage.sender, unsignedMessage.type, unsignedMessage.item_hash].join("\n"));
1461
- const message = {
1462
- ...unsignedMessage,
1463
- signature: signature.startsWith("0x") ? signature : `0x${signature}`
1464
- };
1465
- args.onProgress?.({
1466
- stage: "broadcasting",
1467
- label: "Broadcasting to Aleph",
1468
- progress: 64,
1469
- status: "info",
1470
- detail: message.item_hash,
1471
- itemHash: message.item_hash,
1472
- error: null,
1473
- timestamp: Date.now()
1474
- });
1475
- const { response, httpStatus } = await broadcastAlephMessage(message, {
1476
- apiHost: args.apiHost,
1477
- sync: args.sync,
1478
- fetch: args.fetch
1479
- });
1480
- const status = httpStatus === 202 ? "pending" : typeof response.message_status === "string" ? response.message_status : "unknown";
1481
- args.onProgress?.({
1482
- stage: status === "processed" ? "deployment-confirmed" : status === "rejected" ? "deployment-rejected" : "waiting-for-aleph",
1483
- label: status === "processed" ? "Deployment accepted by Aleph" : status === "rejected" ? "Deployment rejected by Aleph" : "Deployment submitted to Aleph",
1484
- progress: status === "processed" ? 88 : status === "rejected" ? 100 : 78,
1485
- status: status === "processed" ? "success" : status === "rejected" ? "error" : "warning",
1486
- detail: status === "rejected" ? describeRejectedInstanceBroadcast(response) : null,
1487
- itemHash: message.item_hash,
1488
- error: status === "rejected" ? describeRejectedInstanceBroadcast(response) : null,
1489
- timestamp: Date.now()
1490
- });
1432
+ const unsignedMessage = await createUnsignedAggregateMessage({
1433
+ sender: args.sender,
1434
+ content: aggregateContent,
1435
+ hasher: args.hasher,
1436
+ channel: args.channel,
1437
+ now: args.now
1438
+ });
1439
+ const message = await signAlephMessage(unsignedMessage, args.signer);
1440
+ const { response, httpStatus } = await broadcastAlephMessage(message, {
1441
+ apiHost: args.apiHost,
1442
+ sync: true,
1443
+ fetch: args.fetch
1444
+ });
1491
1445
  return {
1492
1446
  itemHash: message.item_hash,
1493
- httpStatus,
1494
- status,
1495
- message,
1447
+ status: normalizeBroadcastStatus(httpStatus, response?.message_status),
1496
1448
  response,
1497
- rejectionReason: status === "rejected" ? describeRejectedInstanceBroadcast(response) : null
1449
+ httpStatus
1498
1450
  };
1499
1451
  }
1500
-
1501
- // src/runtime.ts
1502
- var DEFAULT_SCHEDULER_ALLOCATION_URL = "https://scheduler.api.aleph.cloud/api/v0/allocation";
1503
- var DEFAULT_TWO_N_SIX_HASH_URL = "https://api.2n6.me/api/hash";
1504
- function asString4(value) {
1505
- return typeof value === "string" && value.trim() ? value.trim() : null;
1506
- }
1507
- function asNumber2(value) {
1508
- return typeof value === "number" && Number.isFinite(value) ? value : null;
1509
- }
1510
- function normalizeIpv6(value) {
1511
- if (typeof value !== "string") return null;
1512
- const normalized = value.trim().toLowerCase();
1513
- if (!normalized) return null;
1514
- const zoneIndex = normalized.indexOf("%");
1515
- return zoneIndex >= 0 ? normalized.slice(0, zoneIndex) : normalized;
1516
- }
1517
- function isLikelyGlobalIpv6(value) {
1518
- const normalized = normalizeIpv6(value);
1519
- if (!normalized || normalized === "::" || normalized === "::1") return false;
1520
- const firstHextetText = normalized.split(":", 1)[0];
1521
- if (!firstHextetText) return false;
1522
- const firstHextet = Number.parseInt(firstHextetText, 16);
1523
- if (!Number.isFinite(firstHextet)) return false;
1524
- if ((firstHextet & 65024) === 64512) return false;
1525
- if ((firstHextet & 65472) === 65152) return false;
1526
- if ((firstHextet & 65280) === 65280) return false;
1527
- if ((firstHextet & 65472) === 65216) return false;
1528
- return true;
1529
- }
1530
- function findCrnByHash(crns, crnHash) {
1531
- return crns.find((crn) => crn.hash === crnHash) ?? null;
1532
- }
1533
- async function fetchSchedulerAllocation(itemHash, options) {
1534
- const response = await options.fetch(
1535
- `${options.schedulerAllocationUrl ?? DEFAULT_SCHEDULER_ALLOCATION_URL}/${itemHash}`,
1536
- { cache: "no-cache" }
1537
- );
1538
- if (response.status === 404) return null;
1539
- if (!response.ok) {
1540
- throw new Error(`Scheduler allocation request failed: ${response.status}`);
1541
- }
1452
+ async function fetchMessageStatus(args) {
1453
+ const requestUrl = new URL(`/api/v0/messages/${args.hash}`, args.apiHost ?? "https://api.aleph.im");
1454
+ const response = await args.fetch(requestUrl.toString(), { cache: "no-cache" });
1455
+ if (response.status === 404) return "missing";
1456
+ if (!response.ok) return "unknown";
1542
1457
  const payload = await response.json();
1543
- const node = payload?.node;
1544
- return {
1545
- source: "scheduler",
1546
- crnHash: asString4(node?.node_id),
1547
- crnUrl: asString4(node?.url),
1548
- node: node ? {
1549
- node_id: asString4(node.node_id) ?? void 0,
1550
- url: asString4(node.url) ?? void 0,
1551
- ipv6: asString4(node.ipv6),
1552
- supports_ipv6: typeof node.supports_ipv6 === "boolean" ? node.supports_ipv6 : void 0
1553
- } : null,
1554
- vmIpv6: asString4(payload?.vm_ipv6),
1555
- period: payload?.period ? {
1556
- start_timestamp: asString4(payload.period.start_timestamp) ?? void 0,
1557
- duration_seconds: asNumber2(payload.period.duration_seconds) ?? void 0
1558
- } : null
1559
- };
1458
+ return asString5(payload?.status) ?? "unknown";
1560
1459
  }
1561
- async function fetch2n6WebAccessUrl(itemHash, options) {
1562
- const response = await options.fetch(
1563
- `${options.twoN6HashUrl ?? DEFAULT_TWO_N_SIX_HASH_URL}/${itemHash}`,
1564
- { cache: "no-cache" }
1565
- );
1566
- if (!response.ok) return null;
1567
- const payload = await response.json();
1460
+ async function classifyForgetHashes(args) {
1461
+ const statuses = {};
1462
+ for (const hash of args.hashes) {
1463
+ statuses[hash] = await fetchMessageStatus({
1464
+ hash,
1465
+ fetch: args.fetch,
1466
+ apiHost: args.apiHost
1467
+ });
1468
+ }
1469
+ const forgottenHashes = args.hashes.filter((hash) => statuses[hash] === "forgotten");
1470
+ const outstandingForgetHashes = args.hashes.filter((hash) => statuses[hash] !== "forgotten");
1568
1471
  return {
1569
- url: normalizeProxyUrl(payload?.url ?? payload?.subdomain),
1570
- active: typeof payload?.active === "boolean" ? payload.active : null,
1571
- subdomain: asString4(payload?.subdomain)
1472
+ forgottenHashes,
1473
+ outstandingForgetHashes,
1474
+ statuses
1572
1475
  };
1573
1476
  }
1574
- async function fetchCrnExecutionMap(crnUrl, options) {
1575
- const normalizedCrnUrl = String(crnUrl).replace(/\/+$/, "");
1576
- for (const [version, suffix] of [
1577
- ["v2", "/v2/about/executions/list"],
1578
- ["v1", "/about/executions/list"]
1579
- ]) {
1580
- const requestUrl = `${normalizedCrnUrl}${suffix}`;
1581
- const response = await options.fetch(requestUrl, {
1582
- cache: "no-cache"
1477
+ async function executeForgetStage(args) {
1478
+ const stageHashes = uniqueHashes(args.hashes);
1479
+ let forgetResult = null;
1480
+ const followUpForgetResults = [];
1481
+ if (stageHashes.length === 0) {
1482
+ return {
1483
+ hashes: stageHashes,
1484
+ forgottenHashes: [],
1485
+ outstandingForgetHashes: [],
1486
+ statuses: {},
1487
+ forgetResult,
1488
+ followUpForgetResults
1489
+ };
1490
+ }
1491
+ let classified = await classifyForgetHashes({
1492
+ hashes: stageHashes,
1493
+ fetch: args.fetch,
1494
+ apiHost: args.apiHost
1495
+ });
1496
+ if (classified.outstandingForgetHashes.length > 0) {
1497
+ forgetResult = await forgetAlephMessages({
1498
+ sender: args.sender,
1499
+ hashes: classified.outstandingForgetHashes,
1500
+ reason: args.reason,
1501
+ signer: args.signer,
1502
+ hasher: args.hasher,
1503
+ fetch: args.fetch,
1504
+ channel: args.channel,
1505
+ apiHost: args.apiHost,
1506
+ now: args.now
1583
1507
  });
1584
- if (response.ok) {
1585
- const payload = await response.json();
1586
- return {
1587
- version,
1588
- payload: payload && typeof payload === "object" ? payload : null,
1589
- requestUrl
1590
- };
1591
- }
1592
- if (response.status !== 404) {
1593
- return {
1594
- version,
1595
- payload: null,
1596
- requestUrl
1597
- };
1508
+ classified = await classifyForgetHashes({
1509
+ hashes: stageHashes,
1510
+ fetch: args.fetch,
1511
+ apiHost: args.apiHost
1512
+ });
1513
+ if (classified.outstandingForgetHashes.length > 0) {
1514
+ for (const hash of classified.outstandingForgetHashes) {
1515
+ const result = await forgetAlephMessages({
1516
+ sender: args.sender,
1517
+ hashes: [hash],
1518
+ reason: args.reason,
1519
+ signer: args.signer,
1520
+ hasher: args.hasher,
1521
+ fetch: args.fetch,
1522
+ channel: args.channel,
1523
+ apiHost: args.apiHost,
1524
+ now: args.now
1525
+ });
1526
+ followUpForgetResults.push({ hash, result });
1527
+ }
1528
+ classified = await classifyForgetHashes({
1529
+ hashes: stageHashes,
1530
+ fetch: args.fetch,
1531
+ apiHost: args.apiHost
1532
+ });
1598
1533
  }
1599
1534
  }
1600
1535
  return {
1601
- version: "v2",
1602
- payload: null,
1603
- requestUrl: `${normalizedCrnUrl}/v2/about/executions/list`
1536
+ hashes: stageHashes,
1537
+ forgottenHashes: classified.forgottenHashes,
1538
+ outstandingForgetHashes: classified.outstandingForgetHashes,
1539
+ statuses: classified.statuses,
1540
+ forgetResult,
1541
+ followUpForgetResults
1604
1542
  };
1605
1543
  }
1606
- function describeRuntimeAvailability(runtime) {
1607
- const execution = runtime.execution ?? null;
1608
- const mappedPorts = runtime.mappedPorts ?? {};
1609
- const hostIpv4 = runtime.hostIpv4 ?? null;
1610
- const ipv6 = runtime.ipv6 ?? null;
1611
- const executionGuestIpv6 = execution?.networking?.ipv6_ip ?? null;
1612
- const proxyUrl = runtime.proxyUrl ?? null;
1613
- const schedulerSource = runtime.allocation?.source ?? null;
1614
- const webAccessActive = runtime.webAccess?.active ?? null;
1615
- const mappedPortCount = Object.keys(mappedPorts).length;
1616
- if (hostIpv4 && mappedPortCount > 0 && runtime.requirePublicGuestIpv6ForProxy === true && proxyUrl && executionGuestIpv6 && !isLikelyGlobalIpv6(executionGuestIpv6)) {
1617
- return {
1618
- state: "execution-invalid-public-ipv6",
1619
- reason: `The CRN exposed runtime networking, but the guest IPv6 (${executionGuestIpv6}) is not globally routable. Proxy-backed HTTPS activation cannot succeed until the CRN reports a public guest IPv6.`,
1620
- schedulerSource,
1621
- executionSeen: Boolean(execution),
1622
- webAccessActive,
1623
- mappedPortCount,
1624
- proxyUrl
1625
- };
1544
+ async function retainSuccessfulDeployments(args) {
1545
+ const keepCount = Math.max(0, Number.parseInt(String(args.keepCount ?? 0), 10) || 0);
1546
+ const aggregateKey = asString5(args.aggregateKey) ?? SUCCESSFUL_DEPLOYMENTS_AGGREGATE_KEY;
1547
+ const currentRecord = normalizeRetentionRecord(args.currentRecord);
1548
+ if (!currentRecord) {
1549
+ throw new Error("retainSuccessfulDeployments requires a current deployment record with instance_item_hash.");
1626
1550
  }
1627
- if (hostIpv4 && mappedPortCount > 0) {
1628
- return {
1629
- state: "ready",
1630
- reason: null,
1631
- schedulerSource,
1632
- executionSeen: Boolean(execution),
1633
- webAccessActive,
1634
- mappedPortCount,
1635
- proxyUrl
1636
- };
1551
+ const existingValue = await fetchAggregateKey({
1552
+ address: args.sender,
1553
+ key: aggregateKey,
1554
+ fetch: args.fetch,
1555
+ apiHost: args.apiHost
1556
+ });
1557
+ const existingRecords = normalizeRetentionLedger(existingValue);
1558
+ const mergedRecords = [currentRecord, ...existingRecords];
1559
+ const uniqueRecords = [];
1560
+ const seenIds = /* @__PURE__ */ new Set();
1561
+ for (const record of mergedRecords) {
1562
+ const id = retentionRecordId(record);
1563
+ if (seenIds.has(id)) continue;
1564
+ seenIds.add(id);
1565
+ uniqueRecords.push(record);
1637
1566
  }
1638
- if (!execution && proxyUrl && webAccessActive === false) {
1639
- return {
1640
- state: "proxy-reserved-inactive",
1641
- reason: "Aleph reserved a proxy URL for the VM, but it is still inactive and the selected CRN has not exposed execution networking yet.",
1642
- schedulerSource,
1643
- executionSeen: false,
1644
- webAccessActive,
1645
- mappedPortCount,
1646
- proxyUrl
1647
- };
1567
+ const retainedRecords = keepCount > 0 ? uniqueRecords.slice(0, keepCount) : [];
1568
+ const prunedRecords = keepCount > 0 ? uniqueRecords.slice(keepCount) : uniqueRecords;
1569
+ const retainedHashes = new Set(retainedRecords.flatMap(hashesFromRetentionRecord));
1570
+ const extraForgetHashes = uniqueHashes(args.extraForgetHashes ?? []);
1571
+ const { instanceForgetHashes, dependentForgetHashes, orderedForgetHashes } = splitForgetStages({
1572
+ prunedRecords,
1573
+ extraForgetHashes,
1574
+ retainedHashes
1575
+ });
1576
+ const forgetHashes = orderedForgetHashes;
1577
+ const aggregateContent = {
1578
+ keep: keepCount,
1579
+ updated_at: (/* @__PURE__ */ new Date()).toISOString(),
1580
+ deployments: retainedRecords
1581
+ };
1582
+ const aggregatePublication = await publishAggregateKey({
1583
+ sender: args.sender,
1584
+ key: aggregateKey,
1585
+ content: aggregateContent,
1586
+ signer: args.signer,
1587
+ hasher: args.hasher,
1588
+ fetch: args.fetch,
1589
+ channel: args.channel,
1590
+ apiHost: args.apiHost,
1591
+ now: args.now
1592
+ });
1593
+ const forgetReason = args.reason ?? `Prune successful deployments beyond retention limit ${keepCount}`;
1594
+ const forgetStageResults = [];
1595
+ let forgottenHashes = [];
1596
+ let outstandingForgetHashes = [];
1597
+ let forgetStatuses = {};
1598
+ let forgetResult = null;
1599
+ const followUpForgetResults = [];
1600
+ if (instanceForgetHashes.length > 0) {
1601
+ const eraseResults = await Promise.all(
1602
+ instanceForgetHashes.map(async (hash) => ({
1603
+ hash,
1604
+ ...await eraseInstanceOnCrn({
1605
+ sender: args.sender,
1606
+ signer: args.signer,
1607
+ instanceHash: hash,
1608
+ fetch: args.fetch,
1609
+ apiHost: args.apiHost,
1610
+ crnListUrl: args.crnListUrl,
1611
+ schedulerAllocationUrl: args.schedulerAllocationUrl
1612
+ })
1613
+ }))
1614
+ );
1615
+ const instanceStage = await executeForgetStage({
1616
+ sender: args.sender,
1617
+ hashes: instanceForgetHashes,
1618
+ reason: forgetReason,
1619
+ signer: args.signer,
1620
+ hasher: args.hasher,
1621
+ fetch: args.fetch,
1622
+ channel: args.channel,
1623
+ apiHost: args.apiHost,
1624
+ now: args.now
1625
+ });
1626
+ forgetStageResults.push({ stage: "instances", eraseResults, ...instanceStage });
1627
+ forgottenHashes.push(...instanceStage.forgottenHashes);
1628
+ outstandingForgetHashes.push(...instanceStage.outstandingForgetHashes);
1629
+ forgetStatuses = { ...forgetStatuses, ...instanceStage.statuses };
1630
+ if (!forgetResult && instanceStage.forgetResult) {
1631
+ forgetResult = instanceStage.forgetResult;
1632
+ }
1633
+ followUpForgetResults.push(...instanceStage.followUpForgetResults);
1648
1634
  }
1649
- if (!execution && schedulerSource === "manual") {
1650
- return {
1651
- state: "crn-execution-missing",
1652
- reason: "The deployment is pinned to a specific CRN, but that CRN is not exposing this VM in its execution list yet.",
1653
- schedulerSource,
1654
- executionSeen: false,
1655
- webAccessActive,
1656
- mappedPortCount,
1657
- proxyUrl
1658
- };
1635
+ if (dependentForgetHashes.length > 0) {
1636
+ if (outstandingForgetHashes.length === 0) {
1637
+ const dependentStage = await executeForgetStage({
1638
+ sender: args.sender,
1639
+ hashes: dependentForgetHashes,
1640
+ reason: forgetReason,
1641
+ signer: args.signer,
1642
+ hasher: args.hasher,
1643
+ fetch: args.fetch,
1644
+ channel: args.channel,
1645
+ apiHost: args.apiHost,
1646
+ now: args.now
1647
+ });
1648
+ forgetStageResults.push({ stage: "dependents", ...dependentStage });
1649
+ forgottenHashes.push(...dependentStage.forgottenHashes);
1650
+ outstandingForgetHashes.push(...dependentStage.outstandingForgetHashes);
1651
+ forgetStatuses = { ...forgetStatuses, ...dependentStage.statuses };
1652
+ if (!forgetResult && dependentStage.forgetResult) {
1653
+ forgetResult = dependentStage.forgetResult;
1654
+ }
1655
+ followUpForgetResults.push(...dependentStage.followUpForgetResults);
1656
+ } else {
1657
+ const dependentStageStatus = await classifyForgetHashes({
1658
+ hashes: dependentForgetHashes,
1659
+ fetch: args.fetch,
1660
+ apiHost: args.apiHost
1661
+ });
1662
+ forgetStageResults.push({
1663
+ stage: "dependents",
1664
+ hashes: dependentForgetHashes,
1665
+ skipped: true,
1666
+ skippedReason: "Waiting for instance forget stage to complete before pruning dependent store items.",
1667
+ forgottenHashes: dependentStageStatus.forgottenHashes,
1668
+ outstandingForgetHashes: dependentStageStatus.outstandingForgetHashes,
1669
+ statuses: dependentStageStatus.statuses,
1670
+ forgetResult: null,
1671
+ followUpForgetResults: []
1672
+ });
1673
+ forgottenHashes.push(...dependentStageStatus.forgottenHashes);
1674
+ outstandingForgetHashes.push(...dependentStageStatus.outstandingForgetHashes);
1675
+ forgetStatuses = { ...forgetStatuses, ...dependentStageStatus.statuses };
1676
+ }
1677
+ }
1678
+ forgottenHashes = uniqueHashes(forgottenHashes);
1679
+ outstandingForgetHashes = uniqueHashes(outstandingForgetHashes);
1680
+ return {
1681
+ sender: args.sender,
1682
+ aggregateKey,
1683
+ keepCount,
1684
+ aggregatePublication,
1685
+ retainedRecords,
1686
+ prunedRecords,
1687
+ forgetHashes,
1688
+ forgottenHashes,
1689
+ outstandingForgetHashes,
1690
+ forgetStatuses,
1691
+ forgetResult,
1692
+ followUpForgetResults,
1693
+ forgetStageResults
1694
+ };
1695
+ }
1696
+
1697
+ // src/aggregate-publication.ts
1698
+ function createPortForwardAggregateContent(args) {
1699
+ const existingPorts = normalizeExistingPortForwardEntry(args.existingAggregate?.[args.instanceItemHash]);
1700
+ const mergedPorts = mergePortFlagMaps(existingPorts, requestedPortFlags(args.requestedPorts));
1701
+ return {
1702
+ address: args.sender,
1703
+ key: "port-forwarding",
1704
+ content: {
1705
+ [args.instanceItemHash]: {
1706
+ ports: mergedPorts
1707
+ }
1708
+ },
1709
+ time: args.now ?? Date.now() / 1e3
1710
+ };
1711
+ }
1712
+ async function createUnsignedAggregateMessage2(args) {
1713
+ const itemContent = JSON.stringify(args.content);
1714
+ const itemHash = await args.hasher(itemContent);
1715
+ return {
1716
+ sender: args.sender,
1717
+ chain: "ETH",
1718
+ type: "AGGREGATE",
1719
+ item_hash: itemHash,
1720
+ item_type: "inline",
1721
+ item_content: itemContent,
1722
+ time: args.now ?? Date.now() / 1e3,
1723
+ channel: args.channel ?? DEFAULT_ALEPH_CHANNEL
1724
+ };
1725
+ }
1726
+ async function ensureInstancePortForwards(args) {
1727
+ const requestedPorts = requiredInstancePortForwards(args.manifest);
1728
+ const aggregate = await fetchPortForwardAggregate(args.sender, {
1729
+ apiHost: args.apiHost,
1730
+ fetch: args.fetch
1731
+ });
1732
+ const content = createPortForwardAggregateContent({
1733
+ sender: args.sender,
1734
+ instanceItemHash: args.instanceItemHash,
1735
+ requestedPorts,
1736
+ existingAggregate: aggregate
1737
+ });
1738
+ const unsignedMessage = await createUnsignedAggregateMessage2({
1739
+ sender: args.sender,
1740
+ content,
1741
+ hasher: args.hasher,
1742
+ channel: args.channel
1743
+ });
1744
+ const message = await signAlephMessage(unsignedMessage, args.signer);
1745
+ const { response, httpStatus } = await broadcastAlephMessage(message, {
1746
+ apiHost: args.apiHost,
1747
+ sync: args.sync,
1748
+ fetch: args.fetch
1749
+ });
1750
+ const aggregateStatus = normalizeBroadcastStatus(httpStatus, response.message_status);
1751
+ if (aggregateStatus === "rejected") {
1752
+ throw new Error(`Port-forward aggregate was rejected by Aleph: ${JSON.stringify(response.details ?? response)}`);
1753
+ }
1754
+ return {
1755
+ aggregateItemHash: message.item_hash,
1756
+ aggregateStatus,
1757
+ requestedPorts
1758
+ };
1759
+ }
1760
+
1761
+ // src/instance-deployment.ts
1762
+ var SSH_PUBLIC_KEY_PATTERN = /^(ssh-rsa|ssh-ed25519|ecdsa-sha2-nistp256|ecdsa-sha2-nistp384|ecdsa-sha2-nistp521|sk-ssh-ed25519@openssh\.com|sk-ecdsa-sha2-nistp256@openssh\.com)\s+[A-Za-z0-9+/]+={0,3}(?:\s+.+)?$/;
1763
+ function toFiniteNumber(value) {
1764
+ if (typeof value === "number") return value;
1765
+ if (typeof value === "string" && value.trim()) return Number(value);
1766
+ return Number.NaN;
1767
+ }
1768
+ function normalizeSshPublicKey(value) {
1769
+ return value.split(/\r?\n/g).map((line) => line.trim()).filter(Boolean).join(" ").replace(/\s+/g, " ").trim();
1770
+ }
1771
+ function isValidSshPublicKey(value) {
1772
+ return SSH_PUBLIC_KEY_PATTERN.test(normalizeSshPublicKey(value));
1773
+ }
1774
+ function createDeploymentToken() {
1775
+ const randomUuid = globalThis.crypto?.randomUUID?.();
1776
+ if (typeof randomUuid === "string" && randomUuid.trim()) {
1777
+ return randomUuid;
1778
+ }
1779
+ return `deploy-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;
1780
+ }
1781
+ function appendDeploymentTokenToSshPublicKey(sshPublicKey, ownerAddress, deploymentToken) {
1782
+ const normalized = normalizeSshPublicKey(sshPublicKey);
1783
+ if (!normalized) return normalized;
1784
+ const [algorithm = "", key = ""] = normalized.split(/\s+/, 3);
1785
+ const owner = ownerAddress.trim();
1786
+ const token = deploymentToken.trim();
1787
+ if (!algorithm || !key || !owner || !token) {
1788
+ return normalized;
1789
+ }
1790
+ return `${algorithm} ${key} aleph-bootstrap-config:${owner}:${token}`;
1791
+ }
1792
+ function createReleaseMetadata(name, rootfsVersion, deployer = "shared-aleph-tooling") {
1793
+ return {
1794
+ name,
1795
+ rootfs_version: rootfsVersion,
1796
+ deployer
1797
+ };
1798
+ }
1799
+ function selectedTier(pricing, tierId) {
1800
+ return pricing?.tiers.find((tier) => tier.id === tierId) ?? null;
1801
+ }
1802
+ function tierSpec(pricing, tier) {
1803
+ return {
1804
+ vcpus: pricing.compute_unit.vcpus * tier.compute_units,
1805
+ memoryMiB: pricing.compute_unit.memory_mib * tier.compute_units,
1806
+ diskMiB: pricing.compute_unit.disk_mib * tier.compute_units
1807
+ };
1808
+ }
1809
+ function buildPaymentQuote(tier, pricing, balance) {
1810
+ const computeUnitPrice = pricing.price.compute_unit;
1811
+ if (!computeUnitPrice) return null;
1812
+ const unitPrice = toFiniteNumber(computeUnitPrice.credit);
1813
+ if (!Number.isFinite(unitPrice)) return null;
1814
+ return {
1815
+ required: unitPrice * tier.compute_units,
1816
+ available: Number(balance.credit_balance ?? 0),
1817
+ computeUnits: tier.compute_units,
1818
+ unitPrice,
1819
+ label: "credits"
1820
+ };
1821
+ }
1822
+ function quoteRequiredBudgetUnits(quote) {
1823
+ if (!quote) return 0n;
1824
+ return BigInt(Math.ceil(quote.required * 1e18));
1825
+ }
1826
+ function describeRejectedInstanceBroadcast(response) {
1827
+ const balanceMessage = extractInsufficientBalanceMessage(response.details);
1828
+ if (balanceMessage) {
1829
+ return `Aleph rejected this deployment due to ${balanceMessage}.`;
1659
1830
  }
1660
- if (execution && !hostIpv4) {
1661
- return {
1662
- state: "execution-missing-host-ipv4",
1663
- reason: "The CRN exposed an execution record, but it does not include a public host IPv4 yet.",
1664
- schedulerSource,
1665
- executionSeen: true,
1666
- webAccessActive,
1667
- mappedPortCount,
1668
- proxyUrl
1669
- };
1831
+ const errorCode = typeof response.error_code === "number" ? response.error_code : null;
1832
+ return `Aleph rejected this deployment${errorCode ? ` (error ${errorCode})` : ""}.`;
1833
+ }
1834
+ function createInstanceContent(args) {
1835
+ const sshKey = normalizeSshPublicKey(args.sshPublicKey);
1836
+ if (!sshKey) {
1837
+ throw new Error("An SSH public key is required.");
1670
1838
  }
1671
- if (execution && mappedPortCount === 0) {
1672
- return {
1673
- state: "execution-missing-port-mappings",
1674
- reason: "The CRN exposed an execution record, but mapped ports are still empty.",
1675
- schedulerSource,
1676
- executionSeen: true,
1677
- webAccessActive,
1678
- mappedPortCount,
1679
- proxyUrl
1680
- };
1839
+ if (!isValidSshPublicKey(sshKey)) {
1840
+ throw new Error("SSH public key must be a single valid .pub line.");
1841
+ }
1842
+ if (!args.rootfsItemHash || !/^[a-fA-F0-9]{64}$/.test(args.rootfsItemHash)) {
1843
+ throw new Error("rootfsItemHash must be a 64-character Aleph item hash.");
1681
1844
  }
1682
1845
  return {
1683
- state: "runtime-pending",
1684
- reason: "Aleph has not exposed enough runtime networking details yet.",
1685
- schedulerSource,
1686
- executionSeen: Boolean(execution),
1687
- webAccessActive,
1688
- mappedPortCount,
1689
- proxyUrl
1846
+ address: args.address,
1847
+ time: args.now ?? Date.now() / 1e3,
1848
+ allow_amend: false,
1849
+ metadata: createReleaseMetadata(args.name.trim(), args.rootfsVersion ?? "custom-rootfs", args.deployer),
1850
+ authorized_keys: [sshKey],
1851
+ environment: {
1852
+ internet: true,
1853
+ aleph_api: true,
1854
+ hypervisor: "qemu",
1855
+ reproducible: false,
1856
+ shared_cache: false
1857
+ },
1858
+ resources: {
1859
+ vcpus: Number(args.vcpus),
1860
+ memory: Number(args.memoryMiB),
1861
+ seconds: Number(args.seconds ?? 30)
1862
+ },
1863
+ payment: {
1864
+ type: "credit"
1865
+ },
1866
+ requirements: args.crnHash ? {
1867
+ node: {
1868
+ node_hash: args.crnHash
1869
+ }
1870
+ } : void 0,
1871
+ volumes: [],
1872
+ rootfs: {
1873
+ parent: {
1874
+ ref: args.rootfsItemHash,
1875
+ use_latest: true
1876
+ },
1877
+ persistence: "host",
1878
+ size_mib: Number(args.rootfsSizeMiB)
1879
+ }
1690
1880
  };
1691
1881
  }
1692
- async function fetchVmRuntime(args) {
1693
- const crns = args.crns ?? await fetchCrns({
1694
- url: args.crnListUrl ?? DEFAULT_CRN_LIST_URL,
1882
+ async function createUnsignedInstanceMessage(args) {
1883
+ const itemContent = JSON.stringify(args.content);
1884
+ const itemHash = await args.hasher(itemContent);
1885
+ return {
1886
+ sender: args.sender,
1887
+ chain: "ETH",
1888
+ type: "INSTANCE",
1889
+ item_hash: itemHash,
1890
+ item_type: "inline",
1891
+ item_content: itemContent,
1892
+ time: args.now ?? Date.now() / 1e3,
1893
+ channel: args.channel ?? DEFAULT_ALEPH_CHANNEL
1894
+ };
1895
+ }
1896
+ async function createDeploymentIntent(args) {
1897
+ const intent = {
1898
+ ownerAddress: args.sender,
1899
+ messageTime: args.unsignedMessage.time,
1900
+ itemHash: args.unsignedMessage.item_hash,
1901
+ paymentType: args.content.payment.type,
1902
+ rootfsRef: args.content.rootfs.parent.ref,
1903
+ rootfsSizeMiB: args.content.rootfs.size_mib,
1904
+ computeUnits: args.computeUnits,
1905
+ vcpus: args.content.resources.vcpus,
1906
+ memoryMiB: args.content.resources.memory,
1907
+ crnHash: args.content.requirements?.node?.node_hash ?? null,
1908
+ channel: args.unsignedMessage.channel,
1909
+ expiresAt: args.expiresAt,
1910
+ maxCost: args.maxCost
1911
+ };
1912
+ return {
1913
+ intent,
1914
+ intentHash: await args.hasher(JSON.stringify(intent))
1915
+ };
1916
+ }
1917
+ async function deployInstance(args) {
1918
+ args.onProgress?.({
1919
+ stage: "building-message",
1920
+ label: "Building deployment message",
1921
+ progress: 32,
1922
+ status: "info",
1923
+ detail: args.content.metadata?.name ?? null,
1924
+ itemHash: null,
1925
+ error: null,
1926
+ timestamp: Date.now()
1927
+ });
1928
+ const unsignedMessage = await createUnsignedInstanceMessage({
1929
+ sender: args.sender,
1930
+ content: args.content,
1931
+ hasher: args.hasher,
1932
+ channel: args.channel,
1933
+ now: args.now
1934
+ });
1935
+ args.onProgress?.({
1936
+ stage: "signing-message",
1937
+ label: "Waiting for MetaMask signature",
1938
+ progress: 48,
1939
+ status: "info",
1940
+ detail: unsignedMessage.item_hash,
1941
+ itemHash: unsignedMessage.item_hash,
1942
+ error: null,
1943
+ timestamp: Date.now()
1944
+ });
1945
+ const signature = await args.signer(unsignedMessage.sender, [unsignedMessage.chain, unsignedMessage.sender, unsignedMessage.type, unsignedMessage.item_hash].join("\n"));
1946
+ const message = {
1947
+ ...unsignedMessage,
1948
+ signature: signature.startsWith("0x") ? signature : `0x${signature}`
1949
+ };
1950
+ args.onProgress?.({
1951
+ stage: "broadcasting",
1952
+ label: "Broadcasting to Aleph",
1953
+ progress: 64,
1954
+ status: "info",
1955
+ detail: message.item_hash,
1956
+ itemHash: message.item_hash,
1957
+ error: null,
1958
+ timestamp: Date.now()
1959
+ });
1960
+ const { response, httpStatus } = await broadcastAlephMessage(message, {
1961
+ apiHost: args.apiHost,
1962
+ sync: args.sync,
1695
1963
  fetch: args.fetch
1696
1964
  });
1697
- const schedulerAllocation = await fetchSchedulerAllocation(args.itemHash, {
1698
- fetch: args.fetch,
1699
- schedulerAllocationUrl: args.schedulerAllocationUrl
1700
- }).catch(() => null);
1701
- const selectedCrn = args.crnHash ? findCrnByHash(crns, args.crnHash) : null;
1702
- const allocation = schedulerAllocation ?? (selectedCrn ? {
1703
- source: "manual",
1704
- crnHash: selectedCrn.hash,
1705
- crnUrl: selectedCrn.address,
1706
- node: { url: selectedCrn.address },
1707
- vmIpv6: null,
1708
- period: null
1709
- } : null);
1710
- const webAccess = await fetch2n6WebAccessUrl(args.itemHash, {
1711
- fetch: args.fetch,
1712
- twoN6HashUrl: args.twoN6HashUrl
1713
- }).catch(() => null);
1714
- const webAccessUrl = webAccess?.url ?? null;
1715
- let execution = null;
1716
- let executionLookupBlocked = false;
1717
- if (allocation?.crnUrl) {
1718
- const executionLookup = await fetchCrnExecutionMap(allocation.crnUrl, {
1719
- fetch: args.fetch
1720
- });
1721
- const executionPayload = executionLookup.payload?.[args.itemHash];
1722
- if (executionPayload && typeof executionPayload === "object") {
1723
- execution = normalizeExecution(executionPayload, allocation.crnUrl);
1724
- if (!execution.networking.proxy_url && webAccessUrl) {
1725
- execution.networking.proxy_url = webAccessUrl;
1726
- }
1727
- } else if (executionLookup.payload == null) {
1728
- executionLookupBlocked = true;
1729
- }
1730
- }
1731
- const hostIpv4 = execution?.networking?.host_ipv4 ?? execution?.networking?.ipv4 ?? null;
1732
- const ipv6 = execution?.networking?.ipv6_ip ?? execution?.networking?.ipv6 ?? allocation?.vmIpv6 ?? null;
1733
- const mappedPorts = execution?.networking?.mapped_ports ?? {};
1734
- const sshPort = mappedPorts?.["22"]?.host ?? null;
1735
- const proxyUrl = execution?.networking?.proxy_url ?? webAccessUrl ?? null;
1736
- const diagnostics = describeRuntimeAvailability({
1737
- allocation,
1738
- execution,
1739
- webAccess,
1740
- hostIpv4,
1741
- ipv6,
1742
- proxyUrl,
1743
- mappedPorts,
1744
- requirePublicGuestIpv6ForProxy: args.requirePublicGuestIpv6ForProxy
1965
+ const status = httpStatus === 202 ? "pending" : typeof response.message_status === "string" ? response.message_status : "unknown";
1966
+ args.onProgress?.({
1967
+ stage: status === "processed" ? "deployment-confirmed" : status === "rejected" ? "deployment-rejected" : "waiting-for-aleph",
1968
+ label: status === "processed" ? "Deployment accepted by Aleph" : status === "rejected" ? "Deployment rejected by Aleph" : "Deployment submitted to Aleph",
1969
+ progress: status === "processed" ? 88 : status === "rejected" ? 100 : 78,
1970
+ status: status === "processed" ? "success" : status === "rejected" ? "error" : "warning",
1971
+ detail: status === "rejected" ? describeRejectedInstanceBroadcast(response) : null,
1972
+ itemHash: message.item_hash,
1973
+ error: status === "rejected" ? describeRejectedInstanceBroadcast(response) : null,
1974
+ timestamp: Date.now()
1745
1975
  });
1746
1976
  return {
1747
- allocation,
1748
- execution,
1749
- webAccess,
1750
- webAccessUrl,
1751
- hostIpv4,
1752
- ipv6,
1753
- proxyUrl,
1754
- mappedPorts,
1755
- diagnostics,
1756
- sshCommand: hostIpv4 && sshPort ? `ssh root@${hostIpv4} -p ${sshPort}` : ipv6 ? `ssh root@${ipv6}` : null,
1757
- selectedCrn,
1758
- executionLookupBlocked
1977
+ itemHash: message.item_hash,
1978
+ httpStatus,
1979
+ status,
1980
+ message,
1981
+ response,
1982
+ rejectionReason: status === "rejected" ? describeRejectedInstanceBroadcast(response) : null
1759
1983
  };
1760
1984
  }
1761
- async function waitForVmRuntime(args) {
1762
- const attempts = Math.max(1, Number(args.attempts ?? 20));
1763
- const delayMs = Math.max(0, Number(args.delayMs ?? 4e3));
1764
- const sleep2 = args.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
1765
- let lastRuntime = await fetchVmRuntime(args);
1766
- args.onAttempt?.(lastRuntime, 1, attempts);
1767
- for (let attempt = 0; attempt < attempts - 1; attempt += 1) {
1768
- if (lastRuntime.diagnostics?.state === "ready" || lastRuntime.diagnostics?.state === "execution-invalid-public-ipv6") {
1769
- return lastRuntime;
1770
- }
1771
- await sleep2(delayMs);
1772
- lastRuntime = await fetchVmRuntime(args);
1773
- args.onAttempt?.(lastRuntime, attempt + 2, attempts);
1774
- }
1775
- if (lastRuntime.diagnostics) {
1776
- lastRuntime.diagnostics.timedOut = true;
1777
- }
1778
- return lastRuntime;
1779
- }
1780
1985
 
1781
1986
  // src/guest.ts
1782
1987
  function proxyHostnameFromUrl(value) {
@@ -2127,7 +2332,7 @@ async function verifyUcGoPeerReachability(args) {
2127
2332
  }
2128
2333
 
2129
2334
  // ../aleph-bootstrap/src/index.ts
2130
- var DEFAULT_ALEPH_API_HOST2 = "https://api2.aleph.im";
2335
+ var DEFAULT_ALEPH_API_HOST2 = "https://api.aleph.im";
2131
2336
  var DEFAULT_ALEPH_BOOTSTRAP_CHANNEL = "simple-todo";
2132
2337
  var DEFAULT_ALEPH_BOOTSTRAP_REF = "simple-todo-bootstrap";
2133
2338
  var DEFAULT_ALEPH_BOOTSTRAP_POST_TYPE = "relay-bootstrap";
@@ -2816,7 +3021,7 @@ async function listStaleVmBootstrapConfigAggregateMessageHashes(args) {
2816
3021
  const requestUrl = new URL("/api/v0/messages.json", args.apiHost ?? DEFAULT_ALEPH_API_HOST);
2817
3022
  requestUrl.searchParams.set("msgType", "AGGREGATE");
2818
3023
  requestUrl.searchParams.set("addresses", address);
2819
- requestUrl.searchParams.set("message_statuses", "processed,pending,rejected,removing");
3024
+ requestUrl.searchParams.set("message_statuses", "processed,pending,rejected");
2820
3025
  requestUrl.searchParams.set("pagination", String(pagination));
2821
3026
  requestUrl.searchParams.set("page", String(page));
2822
3027
  requestUrl.searchParams.set("sortOrder", "-1");
@@ -3011,7 +3216,7 @@ async function fetchOwnerInstances(address, options) {
3011
3216
  const url = new URL("/api/v0/messages.json", options.apiHost ?? DEFAULT_ALEPH_API_HOST);
3012
3217
  url.searchParams.set("msgTypes", "INSTANCE");
3013
3218
  url.searchParams.set("addresses", address);
3014
- url.searchParams.set("message_statuses", "processed,pending,rejected,removing");
3219
+ url.searchParams.set("message_statuses", "processed,pending,rejected");
3015
3220
  url.searchParams.set("pagination", "100");
3016
3221
  url.searchParams.set("page", "1");
3017
3222
  url.searchParams.set("sortOrder", "-1");
@@ -3207,6 +3412,7 @@ export {
3207
3412
  describeRuntimeAvailability,
3208
3413
  enrichCrnsWithGeo,
3209
3414
  ensureInstancePortForwards,
3415
+ eraseInstanceOnCrn,
3210
3416
  extractInsufficientBalanceMessage,
3211
3417
  extractProxyUrl,
3212
3418
  extractReferenceHashes,
@@ -3254,6 +3460,7 @@ export {
3254
3460
  reconcileOwnerRelayBootstrapRegistrations,
3255
3461
  requestedPortFlags,
3256
3462
  requiredInstancePortForwards,
3463
+ resolveInstanceCrn,
3257
3464
  resolveRootfsReference,
3258
3465
  retainSuccessfulDeployments,
3259
3466
  selectPreferredCrn,