@ultrst-armada/kloks 2.2.6 → 2.2.8

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 (50) hide show
  1. package/.krusbl-release-attestation.json +3 -3
  2. package/package.json +1 -1
  3. package/packages/backend/dist/auth/OidcBffEnv.d.ts +14 -12
  4. package/packages/backend/dist/auth/OidcBffEnv.test.d.ts +1 -0
  5. package/packages/backend/dist/auth/index.js +1 -1
  6. package/packages/backend/dist/{chunk-5SKQBVYU.js → chunk-AMI5MY6E.js} +2 -2
  7. package/packages/backend/dist/{chunk-4LRMJIJ4.js → chunk-FFQJ4USX.js} +1 -1
  8. package/packages/backend/dist/chunk-G6FLQJS6.js +496 -0
  9. package/packages/backend/dist/{chunk-4NTZRTRY.js → chunk-GIUAFRAA.js} +1 -1
  10. package/packages/backend/dist/{chunk-OJCSPAFE.js → chunk-GZTZ376X.js} +1 -1
  11. package/packages/backend/dist/{chunk-4BCTI7BL.js → chunk-LAKCKX3I.js} +1 -1
  12. package/packages/backend/dist/{chunk-YTJTF7LS.js → chunk-LPM5E2A2.js} +2 -2
  13. package/packages/backend/dist/{chunk-5S5CDQXD.js → chunk-MQ6AHJ6X.js} +2 -2
  14. package/packages/backend/dist/{chunk-SEKPSCWP.js → chunk-NR7OXPB3.js} +69 -21
  15. package/packages/backend/dist/{chunk-2DVRZKOK.js → chunk-QZDTABQX.js} +2 -2
  16. package/packages/backend/dist/{chunk-3V5B2BOP.js → chunk-RHW75K46.js} +1 -1
  17. package/packages/backend/dist/{chunk-FGZA6PDX.js → chunk-U5VPYALB.js} +4 -4
  18. package/packages/backend/dist/chunk-UI7AYFAU.js +364 -0
  19. package/packages/backend/dist/{client-S4R4MZ6K.js → client-R5FY5AP7.js} +2 -2
  20. package/packages/backend/dist/index.js +38 -12
  21. package/packages/backend/dist/krnl-services.js +2 -2
  22. package/packages/backend/dist/node.js +33 -33
  23. package/packages/backend/dist/provider-services/compute-routing.d.ts +65 -0
  24. package/packages/backend/dist/provider-services/compute-routing.test.d.ts +1 -0
  25. package/packages/backend/dist/provider-services/fly-machines.d.ts +52 -0
  26. package/packages/backend/dist/provider-services/fly-machines.test.d.ts +1 -0
  27. package/packages/backend/dist/provider-services/free-compute.d.ts +5 -0
  28. package/packages/backend/dist/provider-services/free-compute.test.d.ts +1 -0
  29. package/packages/backend/dist/provider-services/google/cloud-run.js +1 -1
  30. package/packages/backend/dist/provider-services/google/cloud-shell.js +1 -1
  31. package/packages/backend/dist/provider-services/google/cloud-storage.js +1 -1
  32. package/packages/backend/dist/provider-services/google/drive.js +1 -1
  33. package/packages/backend/dist/provider-services/google/gemini.js +3 -3
  34. package/packages/backend/dist/provider-services/google/index.js +3 -3
  35. package/packages/backend/dist/provider-services/google/vertex-ai.js +1 -1
  36. package/packages/backend/dist/provider-services/index.d.ts +3 -0
  37. package/packages/backend/dist/provider-services/index.js +39 -13
  38. package/packages/backend/dist/provider-services/node.js +11 -11
  39. package/packages/backend/dist/provider-services/storage/dropbox.js +4 -4
  40. package/packages/backend/dist/provider-services/storage/github.js +4 -4
  41. package/packages/backend/dist/provider-services/storage/node.js +7 -7
  42. package/packages/backend/dist/provider-services/storage.js +6 -6
  43. package/packages/backend/dist/provider-services/types.d.ts +16 -2
  44. package/packages/state-graph/dist/browser.js +25 -25
  45. package/packages/state-graph/dist/index.js +25 -25
  46. package/packages/state-graph/dist/spatial/index.js +1 -1
  47. package/packages/backend/dist/chunk-FFYTCLFC.js +0 -93
  48. package/packages/backend/dist/chunk-LN274IE5.js +0 -414
  49. package/packages/backend/dist/{chunk-5CZUAEAD.js → chunk-R4B3KPHY.js} +5 -5
  50. package/packages/state-graph/dist/{chunk-YUJC367F.js → chunk-7N2LLBUW.js} +7 -7
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  createProviderClient
3
- } from "./chunk-5S5CDQXD.js";
3
+ } from "./chunk-MQ6AHJ6X.js";
4
4
 
5
5
  // src/provider-services/operations.ts
6
6
  async function cfGet(connection, path, transport = fetch) {
@@ -3,10 +3,10 @@ import {
3
3
  } from "./chunk-O25T5KCE.js";
4
4
  import {
5
5
  createDropboxStorageService
6
- } from "./chunk-2DVRZKOK.js";
6
+ } from "./chunk-QZDTABQX.js";
7
7
  import {
8
8
  createGitHubStorageService
9
- } from "./chunk-4LRMJIJ4.js";
9
+ } from "./chunk-FFQJ4USX.js";
10
10
  import {
11
11
  createGoogleDriveStorageService
12
12
  } from "./chunk-CTBVXX5C.js";
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  getProviderService,
3
3
  resolveProviderServiceId
4
- } from "./chunk-LN274IE5.js";
4
+ } from "./chunk-G6FLQJS6.js";
5
5
 
6
6
  // src/provider-services/client.ts
7
7
  import { resolveTrustedApiUrl } from "@dinilmusick/gutts/urls/safety";
@@ -48,7 +48,7 @@ function createProviderClient(connection, transport = fetch) {
48
48
  signal: AbortSignal.timeout(options.timeoutMs ?? 1e4)
49
49
  });
50
50
  if (!response.ok) throw new Error("Provider " + id + " returned HTTP " + response.status);
51
- const data = await response.json();
51
+ const data = response.status === 204 || response.status === 205 ? null : await response.json();
52
52
  return { data, status: response.status, headers: response.headers };
53
53
  }
54
54
  return { providerId: id, request };
@@ -314,34 +314,82 @@ function createOAuthBff(config) {
314
314
  import { neon } from "@neondatabase/serverless";
315
315
  import { DEFAULT_LUTH_URL } from "@dinilmusick/gutts/auth";
316
316
  function createCanonicalApplicationOAuthBff(request, env, applicationId) {
317
- if (!/^[a-z0-9][a-z0-9_-]{0,119}$/.test(applicationId)) throw new Error("INVALID_APP_ID");
318
- const origin = String(env.APP_URL || "").trim();
319
- const clientId = String(env.LUTH_OAUTH_CLIENT_ID || "").trim();
320
- const clientSecret = String(env.LUTH_OAUTH_CLIENT_SECRET || "").trim();
321
- const secret = String(env.LUTH_OAUTH_BFF_SECRET || "");
322
- const dbUrl = String(env.SYSTEM_DATABASE_URL || env.SYSTEM_DATABASE_URL_2 || env.SYSTEM_DATABASE_URL_3 || "");
323
- if (!origin || !clientId || !clientSecret || secret.length < 32 || !dbUrl) {
324
- throw new Error("CANONICAL_APP_AUTH_NOT_PROVISIONED");
317
+ if (!/^[a-z0-9][a-z0-9_-]{0,119}$/.test(applicationId)) {
318
+ throw new Error("INVALID_APP_ID");
325
319
  }
320
+ const origin = String(env.APP_URL || "").trim();
321
+ const candidates = [
322
+ env.SYSTEM_DATABASE_URL,
323
+ env.SYSTEM_DATABASE_URL_2,
324
+ env.SYSTEM_DATABASE_URL_3
325
+ ].filter((value) => typeof value === "string" && !!value.trim()).map((value) => value.trim());
326
+ if (!origin || !candidates.length) throw new Error("CANONICAL_APP_AUTH_NOT_PROVISIONED");
326
327
  const verifiedOrigin = new URL(origin);
327
328
  if (verifiedOrigin.origin !== origin.replace(/\/$/, "") || !["http:", "https:"].includes(verifiedOrigin.protocol) || new URL(request.url).origin !== verifiedOrigin.origin) {
328
329
  throw new Error("APPLICATION_ORIGIN_MISMATCH");
329
330
  }
330
- const sql = neon(dbUrl);
331
- return createOAuthBff({
332
- appId: applicationId,
333
- issuer: DEFAULT_LUTH_URL.replace(/\/$/, "") + "/api/auth",
334
- clientId,
335
- clientSecret,
336
- redirectUri: verifiedOrigin.origin + "/api/auth/oidc/callback",
337
- encryptionSecret: secret,
338
- database: {
339
- async query(statement, values) {
340
- const rows = await sql(statement, [...values]);
341
- return { rows: [...rows] };
331
+ async function resolve(current) {
332
+ if (new URL(current.url).origin !== verifiedOrigin.origin) {
333
+ throw new Error("APPLICATION_ORIGIN_MISMATCH");
334
+ }
335
+ const settingsKey = applicationId + "|" + verifiedOrigin.origin;
336
+ const statement = `
337
+ SELECT c."clientId" AS client_id,
338
+ cred.credentials #> ARRAY['applicationOAuth', $3::text] AS settings
339
+ FROM public."ultrst-apps" a
340
+ JOIN public.luth_ecosystems e ON e.id = a.ecosystem_id
341
+ JOIN public.luth_auth_origins o
342
+ ON o.app_id = a.app_id AND o.ecosystem_id = a.ecosystem_id
343
+ JOIN public."oauthClient" c
344
+ ON c.metadata->>'appId' = a.app_id
345
+ AND c.metadata->>'origin' = o.origin
346
+ JOIN public."ultrst-credentials" cred ON cred.id = 'system'
347
+ WHERE a.app_id = $1 AND a.status = 'active' AND e.status = 'active'
348
+ AND o.origin = $2 AND o.enabled = true
349
+ AND COALESCE(c.disabled, false) = false
350
+ LIMIT 2
351
+ `;
352
+ let lastError;
353
+ for (const dbUrl of candidates) {
354
+ const sql = neon(dbUrl);
355
+ let rows;
356
+ try {
357
+ rows = [...await sql(statement, [applicationId, verifiedOrigin.origin, settingsKey])];
358
+ } catch (error) {
359
+ lastError = error;
360
+ continue;
342
361
  }
362
+ if (rows.length !== 1) throw new Error("CANONICAL_APP_AUTH_NOT_PROVISIONED");
363
+ const raw = rows[0].settings;
364
+ const credential = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
365
+ if (typeof credential.clientId !== "string" || typeof credential.clientSecret !== "string" || typeof credential.bffSecret !== "string" || credential.bffSecret.length < 32 || credential.clientId !== rows[0].client_id || !credential.clientSecret) {
366
+ throw new Error("CANONICAL_APP_AUTH_NOT_PROVISIONED");
367
+ }
368
+ return createOAuthBff({
369
+ appId: applicationId,
370
+ issuer: DEFAULT_LUTH_URL.replace(/\/$/, "") + "/api/auth",
371
+ clientId: credential.clientId,
372
+ clientSecret: credential.clientSecret,
373
+ redirectUri: verifiedOrigin.origin + "/api/auth/oidc/callback",
374
+ encryptionSecret: credential.bffSecret,
375
+ database: {
376
+ async query(query, values) {
377
+ const result = await sql(query, [...values]);
378
+ return { rows: [...result] };
379
+ }
380
+ }
381
+ });
343
382
  }
344
- });
383
+ throw new Error(lastError ? "SYSTEM_DATABASE_UNAVAILABLE" : "CANONICAL_APP_AUTH_NOT_PROVISIONED");
384
+ }
385
+ return {
386
+ handle: async (current) => (await resolve(current)).handle(current),
387
+ getSession: async (current) => (await resolve(current)).getSession(current),
388
+ start: async (current) => (await resolve(current)).start(current),
389
+ callback: async (current) => (await resolve(current)).callback(current),
390
+ session: async (current) => (await resolve(current)).session(current),
391
+ signOut: async (current) => (await resolve(current)).signOut(current)
392
+ };
345
393
  }
346
394
 
347
395
  export {
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  continueDropboxFolder,
3
3
  listDropboxFolder
4
- } from "./chunk-5SKQBVYU.js";
4
+ } from "./chunk-AMI5MY6E.js";
5
5
  import {
6
6
  normalizeStoragePath
7
7
  } from "./chunk-HJE4CVKY.js";
@@ -59,7 +59,7 @@ function createDropboxStorageService(connection, transport = fetch) {
59
59
  async delete(path) {
60
60
  const target = toDropboxPath(path);
61
61
  if (!target) throw new Error("Refusing to delete the Dropbox root");
62
- const { createProviderClient } = await import("./client-S4R4MZ6K.js");
62
+ const { createProviderClient } = await import("./client-R5FY5AP7.js");
63
63
  await createProviderClient(connection, transport).request({
64
64
  path: "/2/files/delete_v2",
65
65
  method: "POST",
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  createProviderClient
3
- } from "./chunk-5S5CDQXD.js";
3
+ } from "./chunk-MQ6AHJ6X.js";
4
4
 
5
5
  // src/provider-services/cloudflare.ts
6
6
  var QUERY = `query WorkersToday($account: string, $start: string, $end: string) {
@@ -1,11 +1,11 @@
1
1
  import {
2
2
  fetchCloudflareCapacity,
3
3
  fetchVercelCapacity
4
- } from "./chunk-3V5B2BOP.js";
4
+ } from "./chunk-RHW75K46.js";
5
5
  import {
6
6
  getGeminiQuotaStatus,
7
7
  listGeminiModels
8
- } from "./chunk-4NTZRTRY.js";
8
+ } from "./chunk-GIUAFRAA.js";
9
9
  import {
10
10
  getGoogleAccountProfile,
11
11
  listCloudflareAccounts,
@@ -13,7 +13,7 @@ import {
13
13
  listCloudflareWorkers,
14
14
  listVercelDeployments,
15
15
  listVercelProjects
16
- } from "./chunk-4BCTI7BL.js";
16
+ } from "./chunk-LAKCKX3I.js";
17
17
  import {
18
18
  continueDropboxFolder,
19
19
  listDropboxFolder,
@@ -21,7 +21,7 @@ import {
21
21
  listGitHubRepositoryContents,
22
22
  listGitLabProjects,
23
23
  listGitLabRepositoryTree
24
- } from "./chunk-5SKQBVYU.js";
24
+ } from "./chunk-AMI5MY6E.js";
25
25
  import {
26
26
  b2ListBuckets,
27
27
  b2ListFileNames
@@ -0,0 +1,364 @@
1
+ import {
2
+ createProviderClient
3
+ } from "./chunk-MQ6AHJ6X.js";
4
+
5
+ // src/provider-services/capacity.ts
6
+ function calculateProviderCapacity(snapshot, now = /* @__PURE__ */ new Date(), maxAgeMs = 10 * 6e4) {
7
+ const checkedAt = now.toISOString();
8
+ const unknown = (reason) => ({ status: "unknown", weight: 0, percentRemaining: null, bottleneck: null, reason, checkedAt });
9
+ const timestamp = Date.parse(snapshot.capturedAt);
10
+ if (!Number.isFinite(timestamp) || now.getTime() < timestamp - 3e4 || now.getTime() - timestamp > maxAgeMs) return unknown("Telemetry is stale or undated");
11
+ if (snapshot.error || snapshot.coverage === "unavailable") {
12
+ return unknown(snapshot.error || "Provider quota telemetry unavailable");
13
+ }
14
+ const enforced = snapshot.metrics.filter((m) => m.enforceable);
15
+ if (!enforced.length) return unknown("No provider-confirmed renewable quota windows");
16
+ if (snapshot.coverage !== "complete") return unknown("Required quota coverage is incomplete");
17
+ let bottleneck = null;
18
+ let minimum = 1;
19
+ for (const metric of enforced) {
20
+ if (metric.source !== "provider" || !validQuota(metric) || !metric.resetAt || Date.parse(metric.resetAt) <= now.getTime()) {
21
+ return unknown("Quota metric missing, estimated, or outside its reset window: " + metric.id);
22
+ }
23
+ const remaining = Math.max(0, Math.min(1, (metric.limit - metric.used) / metric.limit));
24
+ if (!bottleneck || remaining < minimum) {
25
+ minimum = remaining;
26
+ bottleneck = metric;
27
+ }
28
+ }
29
+ const status = minimum === 0 ? "exhausted" : "eligible";
30
+ return {
31
+ status,
32
+ weight: status === "eligible" ? Number(minimum.toFixed(4)) : 0,
33
+ percentRemaining: Math.round(minimum * 100),
34
+ bottleneck: bottleneck?.id ?? null,
35
+ reason: status === "eligible" ? "Provider-measured quota remaining" : "A required quota is exhausted",
36
+ checkedAt
37
+ };
38
+ }
39
+ function validQuota(metric) {
40
+ return metric.used !== null && metric.limit !== null && Number.isFinite(metric.used) && Number.isFinite(metric.limit) && metric.used >= 0 && metric.limit > 0 && typeof metric.resetAt === "string" && Number.isFinite(Date.parse(metric.resetAt));
41
+ }
42
+
43
+ // src/provider-services/compute-operations.ts
44
+ function connectionFor(input, expected) {
45
+ if (input.providerId !== expected) throw new Error("Credential/provider mismatch");
46
+ return input;
47
+ }
48
+ function requiredProject(input, name, pattern) {
49
+ if (!pattern.test(input)) throw new Error("Invalid " + name);
50
+ return input;
51
+ }
52
+ async function getRailwayAccount(connection, transport = fetch) {
53
+ const client = createProviderClient(connectionFor(connection, "railway"), transport);
54
+ const { data } = await client.request({
55
+ path: "/graphql/v2",
56
+ method: "POST",
57
+ body: { query: "query FrnesIdentity { me { name email } }" }
58
+ });
59
+ if (data.errors?.length || !data.data?.me || typeof data.data.me !== "object" || !(typeof data.data.me.email === "string" && data.data.me.email.trim() || typeof data.data.me.name === "string" && data.data.me.name.trim()))
60
+ throw new Error("Railway account token could not be authorized");
61
+ return data.data.me;
62
+ }
63
+ async function listFlyApps(connection, transport = fetch) {
64
+ const client = createProviderClient(connectionFor(connection, "fly"), transport);
65
+ const { data } = await client.request({ path: "/v1/apps" });
66
+ if (!Array.isArray(data?.apps) || data.apps.some((item) => typeof item.name !== "string" || !item.name))
67
+ throw new Error("Invalid Fly Machines app listing");
68
+ return data.apps;
69
+ }
70
+ async function listRenderServices(connection, transport = fetch) {
71
+ const client = createProviderClient(connectionFor(connection, "render"), transport);
72
+ const { data } = await client.request({ path: "/v1/services", query: { limit: 20 } });
73
+ if (!Array.isArray(data) || data.some((item) => typeof item.service?.id !== "string" || !item.service.id || typeof item.service.name !== "string" || !item.service.name))
74
+ throw new Error("Invalid Render services response");
75
+ return data;
76
+ }
77
+ async function listGoogleCloudRunServices(connection, project, region, transport = fetch) {
78
+ connectionFor(connection, "google-cloud-run");
79
+ const projectId = requiredProject(project, "Google project ID", /^[a-z][a-z0-9-]{4,61}[a-z0-9]$/);
80
+ const location = requiredProject(region, "Google Cloud location", /^[a-z][a-z0-9-]{1,40}$/);
81
+ const { data } = await createProviderClient(connection, transport).request({ path: `/v2/projects/${projectId}/locations/${location}/services` });
82
+ if (!data || data.services !== void 0 && (!Array.isArray(data.services) || data.services.some((item) => typeof item.name !== "string" || !item.name)))
83
+ throw new Error("Invalid Cloud Run service listing");
84
+ return data.services || [];
85
+ }
86
+
87
+ // src/provider-services/compute-routing.ts
88
+ var COMPUTE_PROFILE_PRESETS = Object.freeze({
89
+ low: Object.freeze({ cpuVcpus: 1, memoryGiB: 1 }),
90
+ medium: Object.freeze({ cpuVcpus: 2, memoryGiB: 4 }),
91
+ high: Object.freeze({ cpuVcpus: 4, memoryGiB: 8 }),
92
+ ultra: Object.freeze({ cpuVcpus: 8, memoryGiB: 16 })
93
+ });
94
+ function validateComputeSpec(value) {
95
+ if (!value || typeof value !== "object" || Array.isArray(value))
96
+ throw new Error("Compute spec must be an object");
97
+ const positive = (value2, name, min, max) => {
98
+ if (typeof value2 !== "number" || !Number.isFinite(value2) || value2 < min || value2 > max)
99
+ throw new Error("Invalid compute requirement: " + name);
100
+ return value2;
101
+ };
102
+ const cpuVcpus = positive(value.cpuVcpus, "cpuVcpus", 0.1, 4096);
103
+ const memoryGiB = positive(value.memoryGiB, "memoryGiB", 0.125, 65536);
104
+ const gpuCount = value.gpuCount === void 0 ? 0 : positive(value.gpuCount, "gpuCount", 0, 64);
105
+ if (!Number.isInteger(gpuCount)) throw new Error("GPU count must be an integer");
106
+ const gpuMemoryGiB = value.gpuMemoryGiB === void 0 ? 0 : positive(value.gpuMemoryGiB, "gpuMemoryGiB", 0, 4096);
107
+ if (gpuCount === 0 && gpuMemoryGiB > 0) throw new Error("GPU memory requires a GPU");
108
+ const diskGiB = value.diskGiB === void 0 ? 0 : positive(value.diskGiB, "diskGiB", 0, 1048576);
109
+ const workload = value.workload;
110
+ if (workload !== void 0 && !["vm", "container", "function", "gpu", "sandbox"].includes(workload))
111
+ throw new Error("Unsupported compute workload");
112
+ return { cpuVcpus, memoryGiB, gpuCount, gpuMemoryGiB, diskGiB, ...workload ? { workload } : {} };
113
+ }
114
+ function resolveComputeSpec(profile, custom) {
115
+ if (profile === "custom") {
116
+ if (!custom) throw new Error("Custom compute profile requires a specification");
117
+ return validateComputeSpec(custom);
118
+ }
119
+ if (!Object.prototype.hasOwnProperty.call(COMPUTE_PROFILE_PRESETS, profile))
120
+ throw new Error("Unknown compute profile");
121
+ return validateComputeSpec(COMPUTE_PROFILE_PRESETS[profile]);
122
+ }
123
+ function fit(required, available) {
124
+ let resource;
125
+ try {
126
+ resource = validateComputeSpec(available);
127
+ } catch {
128
+ return 0;
129
+ }
130
+ if (required.workload && resource.workload !== required.workload) return 0;
131
+ if (resource.cpuVcpus < required.cpuVcpus || resource.memoryGiB < required.memoryGiB || (resource.gpuCount ?? 0) < (required.gpuCount ?? 0) || (resource.gpuMemoryGiB ?? 0) < (required.gpuMemoryGiB ?? 0) || (resource.diskGiB ?? 0) < (required.diskGiB ?? 0)) return 0;
132
+ const cpuFit = required.cpuVcpus / resource.cpuVcpus;
133
+ const memFit = required.memoryGiB / resource.memoryGiB;
134
+ const gpuFit = !required.gpuCount && resource.gpuCount ? 0.5 : required.gpuCount ? required.gpuCount / (resource.gpuCount || 1) : 1;
135
+ return Math.max(0.01, Math.min(1, (cpuFit + memFit + gpuFit) / 3));
136
+ }
137
+ function rankComputeRoutes(request, resources, now = /* @__PURE__ */ new Date()) {
138
+ if (!request.ownerUserId?.trim() || !request.workspaceId?.trim())
139
+ throw new Error("An authenticated user and workspace are required");
140
+ if (!["exclude", "user-weight"].includes(request.missingUsage))
141
+ throw new Error("Missing-usage policy must be explicit");
142
+ if (request.exhaustedUsage !== void 0 && !["exclude", "user-weight"].includes(request.exhaustedUsage))
143
+ throw new Error("Invalid exhausted-quota policy");
144
+ if (request.allowAccountIds && (!Array.isArray(request.allowAccountIds) || request.allowAccountIds.some((id) => typeof id !== "string" || !id)))
145
+ throw new Error("Invalid account allowlist");
146
+ const requested = resolveComputeSpec(request.profile, request.customSpec);
147
+ const permittedIds = request.allowAccountIds && new Set(request.allowAccountIds);
148
+ const candidates = [];
149
+ const rejected = [];
150
+ const seen = /* @__PURE__ */ new Set();
151
+ for (const account of resources) {
152
+ if (account.ownerUserId !== request.ownerUserId || account.workspaceId !== request.workspaceId) continue;
153
+ if (permittedIds && !permittedIds.has(account.accountId)) continue;
154
+ const tag = { providerId: account.providerId, accountId: account.accountId, resourceId: account.resourceId };
155
+ const reject = (reason) => {
156
+ rejected.push({ ...tag, reason });
157
+ };
158
+ if (!account.providerId || !account.accountId || !account.resourceId || !account.enabled || !account.executable) {
159
+ reject("Provider runtime not available");
160
+ continue;
161
+ }
162
+ const key = [account.providerId, account.accountId, account.resourceId].join("\0");
163
+ if (seen.has(key)) {
164
+ reject("Duplicate resource");
165
+ continue;
166
+ }
167
+ seen.add(key);
168
+ const fitScore = fit(requested, account.capabilities);
169
+ if (!fitScore) {
170
+ reject("Compute capabilities below requested profile");
171
+ continue;
172
+ }
173
+ if (!Number.isFinite(account.preferenceWeight) || account.preferenceWeight < 0 || account.preferenceWeight > 100) {
174
+ reject("Invalid user account weight");
175
+ continue;
176
+ }
177
+ if (account.preferenceWeight === 0) {
178
+ reject("Disabled by user account weight");
179
+ continue;
180
+ }
181
+ let remainingFraction = null;
182
+ let exhaustedManualOverride = false;
183
+ let weightSource = "user-weight";
184
+ if (account.usage && account.usage.accountId === account.accountId && account.usage.providerId === account.providerId) {
185
+ const decision = calculateProviderCapacity(account.usage, now);
186
+ if (decision.status === "exhausted") {
187
+ if (request.exhaustedUsage !== "user-weight") {
188
+ reject("Provider-measured quota exhausted");
189
+ continue;
190
+ }
191
+ exhaustedManualOverride = true;
192
+ }
193
+ if (decision.status === "eligible") {
194
+ remainingFraction = decision.weight;
195
+ weightSource = "verified-usage";
196
+ }
197
+ }
198
+ if (remainingFraction === null && request.missingUsage === "exclude" && !exhaustedManualOverride) {
199
+ reject("Verified quota measurement unavailable");
200
+ continue;
201
+ }
202
+ const rawWeight = fitScore * account.preferenceWeight * (remainingFraction ?? 1);
203
+ if (!Number.isFinite(rawWeight) || rawWeight <= 0) {
204
+ reject("Account has no routing weight");
205
+ continue;
206
+ }
207
+ candidates.push({ ...tag, capabilityFit: fitScore, remainingFraction, weightSource, rawWeight, probability: 0 });
208
+ }
209
+ const sum = candidates.reduce((total, item) => total + item.rawWeight, 0);
210
+ const ranked = candidates.map(({ rawWeight, ...item }) => ({ ...item, probability: rawWeight / sum })).sort((a, b) => b.probability - a.probability || a.providerId.localeCompare(b.providerId) || a.accountId.localeCompare(b.accountId) || a.resourceId.localeCompare(b.resourceId));
211
+ return { requested, candidates: ranked, rejected };
212
+ }
213
+ function selectComputeRoute(ranking, selectionUnit) {
214
+ if (!Number.isFinite(selectionUnit) || selectionUnit < 0 || selectionUnit >= 1)
215
+ throw new Error("Selection unit must be between 0 inclusive and 1 exclusive");
216
+ let accumulated = 0;
217
+ for (const candidate of ranking.candidates) {
218
+ accumulated += candidate.probability;
219
+ if (selectionUnit < accumulated) return candidate;
220
+ }
221
+ return ranking.candidates.at(-1) ?? null;
222
+ }
223
+
224
+ // src/provider-services/fly-machines.ts
225
+ import { resolveTrustedApiUrl } from "@dinilmusick/gutts/urls/safety";
226
+ function flyConnection(connection) {
227
+ if (connection.providerId !== "fly") throw new Error("Fly machine credentials must belong to Fly");
228
+ return connection;
229
+ }
230
+ function identifier(value, label) {
231
+ if (typeof value !== "string" || !/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,62}$/.test(value))
232
+ throw new Error("Invalid Fly " + label);
233
+ return value;
234
+ }
235
+ function appPath(app) {
236
+ return "/v1/apps/" + identifier(app, "app name") + "/machines";
237
+ }
238
+ function machinePath(app, id) {
239
+ return appPath(app) + "/" + identifier(id, "machine ID");
240
+ }
241
+ function mapMachine(input, app) {
242
+ if (!input || typeof input !== "object") throw new Error("Invalid Fly Machine payload");
243
+ const data = input;
244
+ const guest = data.config?.guest;
245
+ if (typeof data.id !== "string" || !data.id || typeof data.state !== "string" || !data.state || !guest || !Number.isInteger(guest.cpus) || guest.cpus < 1 || guest.cpus > 4096 || !Number.isFinite(guest.memory_mb) || guest.memory_mb < 128 || guest.gpus !== void 0 && (!Number.isInteger(guest.gpus) || guest.gpus < 0))
246
+ throw new Error("Fly Machine configuration is incomplete");
247
+ return {
248
+ id: data.id,
249
+ app,
250
+ name: typeof data.name === "string" ? data.name : null,
251
+ state: data.state,
252
+ region: typeof data.region === "string" ? data.region : null,
253
+ cpuVcpus: guest.cpus,
254
+ memoryGiB: guest.memory_mb / 1024,
255
+ gpuCount: guest.gpus ?? 0
256
+ };
257
+ }
258
+ async function listFlyMachines(connection, app, transport = fetch) {
259
+ const { data } = await createProviderClient(flyConnection(connection), transport).request({ path: appPath(app) });
260
+ if (!Array.isArray(data)) throw new Error("Fly Machines inventory was not an array");
261
+ return data.map((item) => mapMachine(item, app));
262
+ }
263
+ async function getFlyMachine(connection, app, id, transport = fetch) {
264
+ const { data } = await createProviderClient(flyConnection(connection), transport).request({ path: machinePath(app, id) });
265
+ return mapMachine(data, app);
266
+ }
267
+ async function createFlyMachine(connection, input, transport = fetch) {
268
+ const path = appPath(input.app);
269
+ identifier(input.name, "machine name");
270
+ if (!/^[a-z]{3}$/.test(input.region) || !/^[A-Za-z0-9._/@:-]{3,240}$/.test(input.image) || !["shared", "performance"].includes(input.cpuKind) || !Number.isInteger(input.cpuVcpus) || input.cpuVcpus < 1 || input.cpuVcpus > 64 || !Number.isInteger(input.memoryMiB) || input.memoryMiB < 256 || input.memoryMiB > 262144)
271
+ throw new Error("Invalid Fly Machine resources or image");
272
+ const body = { name: input.name, region: input.region, config: {
273
+ image: input.image,
274
+ guest: {
275
+ cpu_kind: input.cpuKind,
276
+ cpus: input.cpuVcpus,
277
+ memory_mb: input.memoryMiB
278
+ }
279
+ } };
280
+ const { data } = await createProviderClient(flyConnection(connection), transport).request({ path, method: "POST", body });
281
+ return mapMachine(data, input.app);
282
+ }
283
+ async function mutateFlyMachine(connection, app, id, operation, transport = fetch) {
284
+ if (!["start", "stop", "delete"].includes(operation)) throw new Error("Invalid Fly operation");
285
+ const path = machinePath(app, id) + (operation === "delete" ? "" : "/" + operation);
286
+ await createProviderClient(flyConnection(connection), transport).request({
287
+ path,
288
+ method: operation === "delete" ? "DELETE" : "POST"
289
+ });
290
+ return { accepted: true, app, id, operation };
291
+ }
292
+ async function invokeFlyMachineHttp(input, transport = fetch) {
293
+ const app = identifier(input.app, "app name");
294
+ const machineId = identifier(input.machineId, "machine ID");
295
+ if (typeof input.path !== "string" || input.path.length > 512 || !input.path.startsWith("/") || input.path.startsWith("//") || !/^[\x20-\x7e]*$/.test(input.path))
296
+ throw new Error("Invalid Fly application path");
297
+ if (!["GET", "POST"].includes(input.method) || input.method === "GET" && input.payload !== void 0)
298
+ throw new Error("Invalid Fly HTTP method or request");
299
+ if (input.appAuthorization !== void 0 && (typeof input.appAuthorization !== "string" || input.appAuthorization.length > 4096 || /[\r\n]/.test(input.appAuthorization)))
300
+ throw new Error("Invalid application authorization");
301
+ const payload = input.payload === void 0 ? void 0 : JSON.stringify(input.payload);
302
+ if (payload !== void 0 && new TextEncoder().encode(payload).byteLength > 131072)
303
+ throw new Error("Fly request exceeds the allowed size");
304
+ const target = resolveTrustedApiUrl("https://" + app + ".fly.dev", input.path);
305
+ const headers = {
306
+ Accept: "application/json",
307
+ "Fly-Force-Instance-Id": machineId,
308
+ ...payload === void 0 ? {} : { "Content-Type": "application/json" },
309
+ ...input.appAuthorization ? { Authorization: input.appAuthorization } : {}
310
+ };
311
+ const response = await transport(target.toString(), {
312
+ method: input.method,
313
+ headers,
314
+ body: payload,
315
+ redirect: "error",
316
+ signal: AbortSignal.timeout(15e3)
317
+ });
318
+ const limit = 131072;
319
+ const reader = response.body?.getReader();
320
+ if (!reader) return { status: response.status, contentType: response.headers.get("content-type") || "", body: "" };
321
+ const chunks = [];
322
+ let size = 0;
323
+ try {
324
+ for (; ; ) {
325
+ const part = await reader.read();
326
+ if (part.done) break;
327
+ size += part.value.byteLength;
328
+ if (size > limit) throw new Error("Fly response exceeds the allowed size");
329
+ chunks.push(part.value);
330
+ }
331
+ } finally {
332
+ if (size > limit) await reader.cancel().catch(() => void 0);
333
+ reader.releaseLock();
334
+ }
335
+ const bytes = new Uint8Array(size);
336
+ let position = 0;
337
+ for (const chunk of chunks) {
338
+ bytes.set(chunk, position);
339
+ position += chunk.byteLength;
340
+ }
341
+ return {
342
+ status: response.status,
343
+ contentType: response.headers.get("content-type") || "",
344
+ body: new TextDecoder("utf-8", { fatal: true }).decode(bytes)
345
+ };
346
+ }
347
+
348
+ export {
349
+ calculateProviderCapacity,
350
+ getRailwayAccount,
351
+ listFlyApps,
352
+ listRenderServices,
353
+ listGoogleCloudRunServices,
354
+ COMPUTE_PROFILE_PRESETS,
355
+ validateComputeSpec,
356
+ resolveComputeSpec,
357
+ rankComputeRoutes,
358
+ selectComputeRoute,
359
+ listFlyMachines,
360
+ getFlyMachine,
361
+ createFlyMachine,
362
+ mutateFlyMachine,
363
+ invokeFlyMachineHttp
364
+ };
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  createProviderClient
3
- } from "./chunk-5S5CDQXD.js";
4
- import "./chunk-LN274IE5.js";
3
+ } from "./chunk-MQ6AHJ6X.js";
4
+ import "./chunk-G6FLQJS6.js";
5
5
  export {
6
6
  createProviderClient
7
7
  };