@tangle-network/agent-app 0.60.131 → 0.60.133

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 (58) hide show
  1. package/dist/app-auth/index.js +3 -3
  2. package/dist/assistant/index.js +10 -10
  3. package/dist/billing/index.js +1 -1
  4. package/dist/chat-react/index.js +2 -2
  5. package/dist/chat-routes/index.js +11 -11
  6. package/dist/chat-routes/turn-routes.d.ts +6 -2
  7. package/dist/chat-store/index.js +3 -3
  8. package/dist/{chunk-JZUSVGRJ.js → chunk-2GP6JOWE.js} +15 -2
  9. package/dist/chunk-2GP6JOWE.js.map +1 -0
  10. package/dist/chunk-4JUEOVQS.js +134 -0
  11. package/dist/chunk-4JUEOVQS.js.map +1 -0
  12. package/dist/{chunk-5S5ANZBS.js → chunk-HZGKPWVA.js} +6 -6
  13. package/dist/{chunk-NRG2YHGY.js → chunk-IMTU5LCF.js} +1 -1
  14. package/dist/{chunk-XPP653RG.js → chunk-JEM4BKR4.js} +10 -10
  15. package/dist/{chunk-JGLK5RDK.js → chunk-JIXM57JM.js} +28 -14
  16. package/dist/{chunk-JGLK5RDK.js.map → chunk-JIXM57JM.js.map} +1 -1
  17. package/dist/{chunk-4DEI6QC5.js → chunk-NNNAC3DV.js} +4 -4
  18. package/dist/{chunk-GU7OZFU7.js → chunk-VXWEJ7F2.js} +4 -4
  19. package/dist/{chunk-ZGUXI5SI.js → chunk-XNKLQG26.js} +5 -5
  20. package/dist/{chunk-LJDMPYGA.js → chunk-YJHE73TF.js} +8 -2
  21. package/dist/chunk-YJHE73TF.js.map +1 -0
  22. package/dist/design-canvas-react/index.js +4 -4
  23. package/dist/design-canvas-react/lazy.js +1 -1
  24. package/dist/journeys/index.js +11 -5
  25. package/dist/journeys/index.js.map +1 -1
  26. package/dist/journeys/send.d.ts +10 -0
  27. package/dist/platform/delegated-keys.d.ts +226 -0
  28. package/dist/platform/index.d.ts +1 -0
  29. package/dist/platform/index.js +315 -0
  30. package/dist/platform/index.js.map +1 -1
  31. package/dist/preset-cloudflare/index.js +1 -1
  32. package/dist/public-consultation/index.d.ts +1 -1
  33. package/dist/public-consultation/index.js +5 -5
  34. package/dist/rollout/cli.d.ts +25 -0
  35. package/dist/rollout/cli.js +121 -0
  36. package/dist/rollout/cli.js.map +1 -0
  37. package/dist/rollout/d1.d.ts +62 -0
  38. package/dist/rollout/d1.js +89 -0
  39. package/dist/rollout/d1.js.map +1 -0
  40. package/dist/rollout/index.d.ts +116 -0
  41. package/dist/rollout/index.js +19 -0
  42. package/dist/rollout/index.js.map +1 -0
  43. package/dist/sandbox/index.js +1 -1
  44. package/dist/sandbox/sandbox-exec-tool.d.ts +5 -3
  45. package/dist/sandbox/sandbox-run-tool.d.ts +12 -5
  46. package/dist/stream/index.js +2 -2
  47. package/dist/studio-react/index.js +2 -2
  48. package/dist/web-react/index.js +16 -16
  49. package/dist/workspace-react/index.js +5 -5
  50. package/package.json +12 -1
  51. package/dist/chunk-JZUSVGRJ.js.map +0 -1
  52. package/dist/chunk-LJDMPYGA.js.map +0 -1
  53. /package/dist/{chunk-5S5ANZBS.js.map → chunk-HZGKPWVA.js.map} +0 -0
  54. /package/dist/{chunk-NRG2YHGY.js.map → chunk-IMTU5LCF.js.map} +0 -0
  55. /package/dist/{chunk-XPP653RG.js.map → chunk-JEM4BKR4.js.map} +0 -0
  56. /package/dist/{chunk-4DEI6QC5.js.map → chunk-NNNAC3DV.js.map} +0 -0
  57. /package/dist/{chunk-GU7OZFU7.js.map → chunk-VXWEJ7F2.js.map} +0 -0
  58. /package/dist/{chunk-ZGUXI5SI.js.map → chunk-XNKLQG26.js.map} +0 -0
@@ -704,9 +704,321 @@ function createPlatformAgentSpend(options) {
704
704
  }
705
705
  };
706
706
  }
707
+
708
+ // src/platform/delegated-keys.ts
709
+ var REQUEST_TIMEOUT_MS2 = 1e4;
710
+ var KEY_PREFIX = "sk-tan-";
711
+ var AUTO_PREFIX = "auto:";
712
+ var PRODUCT_QUALIFIED = /* @__PURE__ */ new Set(["router", "sandbox"]);
713
+ function canonicalDelegatedKeyName(input) {
714
+ const logical = input.name.startsWith(AUTO_PREFIX) ? input.name.slice(AUTO_PREFIX.length) : input.name;
715
+ if (!PRODUCT_QUALIFIED.has(input.product)) return `${AUTO_PREFIX}${logical}`;
716
+ if (logical.startsWith(`${input.serviceName}:${input.product}:`)) return `${AUTO_PREFIX}${logical}`;
717
+ const withoutService = logical.startsWith(`${input.serviceName}:`) ? logical.slice(input.serviceName.length + 1) : logical;
718
+ return `${AUTO_PREFIX}${input.serviceName}:${input.product}:${withoutService}`;
719
+ }
720
+ function refusal2(status, code) {
721
+ if (code === "INSUFFICIENT_BALANCE") {
722
+ return { status: 402, code: "delegated_key.payment_required", message: "The payer's Tangle account has no credit." };
723
+ }
724
+ if (code === "KEY_BUDGET_EXHAUSTED" || code === "KEY_BUDGET_EXCEEDED" || code === "PRODUCT_BUDGET_EXCEEDED") {
725
+ return { status: 402, code: "delegated_key.budget_exhausted", message: "The payer's key has spent the budget it allows." };
726
+ }
727
+ if (code === "EMAIL_VERIFICATION_REQUIRED") {
728
+ return { status: 403, code: "delegated_key.owner_unverified", message: "The payer must verify their Tangle email." };
729
+ }
730
+ if (status >= 500 || status === 429 || code === "PLATFORM_BUSY") {
731
+ return { status: 503, code: "delegated_key.unavailable", message: "Platform could not answer; retry." };
732
+ }
733
+ return { status: 403, code: "delegated_key.refused", message: "Platform refused to delegate this key." };
734
+ }
735
+ var failure = (status, code, message, extra = {}) => ({ succeeded: false, error: { status, code, message, ...extra } });
736
+ var record2 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : null;
737
+ function sameSet(granted, requested) {
738
+ if (!Array.isArray(granted) || granted.some((model) => typeof model !== "string")) return false;
739
+ const a = [...new Set(granted)].sort();
740
+ const b = [...new Set(requested)].sort();
741
+ return granted.length === a.length && a.length === b.length && a.every((model, index) => model === b[index]);
742
+ }
743
+ function childProblem(data, request, name, serviceName, nowMs) {
744
+ const key = data.key;
745
+ const id = data.id;
746
+ if (typeof id !== "string" || !id) return "no key id";
747
+ if (typeof key !== "string" || !key.startsWith(KEY_PREFIX) || key.length <= KEY_PREFIX.length) return "not an sk-tan child key";
748
+ if (key === request.sourceKey) return "the source key itself";
749
+ if (typeof data.prefix === "string" && !key.startsWith(data.prefix)) return "a key that does not match its prefix";
750
+ if (data.name !== name) return "a different name";
751
+ if (data.product !== request.product) return "a different product";
752
+ if (data.provisionedByService !== serviceName) return "a different provisioner";
753
+ if (data.scopes !== null && !(Array.isArray(data.scopes) && data.scopes.length === 0)) return "control-plane scopes";
754
+ if (request.allowedModels && !sameSet(data.allowedModels, request.allowedModels)) return "a different model set";
755
+ const budget = request.budget;
756
+ if (budget && "usd" in budget && !(typeof data.budgetUsd === "number" && data.budgetUsd <= budget.usd)) return "a budget larger than requested";
757
+ if (budget?.monthlyUsd !== void 0 && !(typeof data.monthlyBudgetUsd === "number" && data.monthlyBudgetUsd <= budget.monthlyUsd)) {
758
+ return "a monthly budget larger than requested";
759
+ }
760
+ const attribution = record2(data.attribution);
761
+ if (!attribution) return "no attribution";
762
+ if (attribution.version !== 1 || attribution.targetService !== request.product) return "attribution for another target";
763
+ if (request.expect?.originAppId !== void 0 && (attribution.originAppId ?? null) !== request.expect.originAppId) {
764
+ return "attribution from another app";
765
+ }
766
+ const parent = attribution.delegatedFromKeyId;
767
+ if (typeof parent !== "string" || !parent || parent === id) return "attribution without its parent key";
768
+ if (request.expect?.sourceKeyId !== void 0 && parent !== request.expect.sourceKeyId) return "attribution for another source key";
769
+ if (attribution.payerType !== "user") return "attribution to a non-user payer";
770
+ if (request.expect?.payerId !== void 0 && attribution.payerId !== request.expect.payerId) return "attribution to another payer";
771
+ if ((attribution.resourceType ?? null) !== (request.resource?.type ?? null) || (attribution.resourceId ?? null) !== (request.resource?.id ?? null)) {
772
+ return "attribution for another resource";
773
+ }
774
+ const expiresAt = typeof attribution.expiresAt === "string" ? Date.parse(attribution.expiresAt) : NaN;
775
+ if (!Number.isFinite(expiresAt) || expiresAt <= nowMs || expiresAt > request.expiresAt.getTime()) return "an expiry in the past or past the request";
776
+ return null;
777
+ }
778
+ function createPlatformDelegatedKeyClient(options) {
779
+ const fetchImpl = options.fetch ?? fetch;
780
+ const now = options.now ?? Date.now;
781
+ const base = options.platformUrl.replace(/\/+$/, "");
782
+ const serviceToken = () => typeof options.serviceToken === "function" ? options.serviceToken() : options.serviceToken;
783
+ async function call(path, init) {
784
+ try {
785
+ const response = await fetchImpl(`${base}${path}`, {
786
+ method: init.method,
787
+ headers: {
788
+ authorization: `Bearer ${init.bearer}`,
789
+ ...init.service ? { "x-service-name": options.serviceName } : {},
790
+ ...init.body === void 0 ? {} : { "content-type": "application/json" }
791
+ },
792
+ ...init.body === void 0 ? {} : { body: JSON.stringify(init.body) },
793
+ redirect: "manual",
794
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS2)
795
+ });
796
+ return { status: response.status, body: record2(await response.json().catch(() => null)) };
797
+ } catch {
798
+ return null;
799
+ }
800
+ }
801
+ const client = {
802
+ async delegate(request) {
803
+ if (!request.sourceKey.startsWith(KEY_PREFIX)) return failure(400, "delegated_key.invalid_request", "The source must be a linked sk-tan- key.");
804
+ if (request.expiresAt.getTime() <= now()) return failure(400, "delegated_key.invalid_request", "The expiry must be in the future.");
805
+ const name = canonicalDelegatedKeyName({ serviceName: options.serviceName, product: request.product, name: request.name });
806
+ const budget = request.budget;
807
+ const result = await call("/v1/keys/delegate", {
808
+ method: "POST",
809
+ bearer: serviceToken(),
810
+ service: true,
811
+ body: {
812
+ sourceKey: request.sourceKey,
813
+ name,
814
+ product: request.product,
815
+ ...request.resource ? { resourceType: request.resource.type, resourceId: request.resource.id } : {},
816
+ ...budget && "usd" in budget ? { budgetUsd: budget.usd } : {},
817
+ ...budget && "spendThrough" in budget ? { spendThrough: true } : {},
818
+ ...budget?.monthlyUsd !== void 0 ? { monthlyBudgetUsd: budget.monthlyUsd } : {},
819
+ ...request.allowedModels ? { allowedModels: [...new Set(request.allowedModels)] } : {},
820
+ ...request.rpmLimit !== void 0 ? { rpmLimit: request.rpmLimit } : {},
821
+ // Omitted, Platform copies the source's scopes onto the child; a product key carries none.
822
+ scopes: [],
823
+ expiresAt: request.expiresAt.toISOString()
824
+ }
825
+ });
826
+ if (!result) return { succeeded: false, error: refusal2(503, null) };
827
+ const data = record2(result.body?.data);
828
+ if (result.status !== 201 || result.body?.success !== true || !data) {
829
+ return { succeeded: false, error: refusal2(result.status, record2(result.body?.error)?.code) };
830
+ }
831
+ const problem = childProblem(data, request, name, options.serviceName, now());
832
+ if (problem) {
833
+ const id = typeof data.id === "string" && data.id ? data.id : null;
834
+ const owner = request.expect?.payerId ? {
835
+ userId: request.expect.payerId,
836
+ name,
837
+ product: request.product,
838
+ ...request.expect.sourceKeyId ? { sourceKeyId: request.expect.sourceKeyId } : {}
839
+ } : void 0;
840
+ const revoked = id ? await client.revoke({ sourceKey: request.sourceKey, keyId: id, ...owner ? { slot: owner } : {} }) : null;
841
+ return failure(
842
+ 502,
843
+ "delegated_key.response_invalid",
844
+ `Platform returned ${problem}.`,
845
+ id && !revoked?.succeeded ? { unrevokedKeyId: id } : {}
846
+ );
847
+ }
848
+ const attribution = record2(data.attribution);
849
+ return { succeeded: true, value: {
850
+ key: data.key,
851
+ id: data.id,
852
+ name,
853
+ product: request.product,
854
+ expiresAt: new Date(attribution.expiresAt),
855
+ allowedModels: request.allowedModels ? [...new Set(request.allowedModels)] : null,
856
+ budgetUsd: typeof data.budgetUsd === "number" ? data.budgetUsd : null
857
+ } };
858
+ },
859
+ async verify({ keyId, product }) {
860
+ const result = await call("/v1/keys/verify-by-id", {
861
+ method: "POST",
862
+ bearer: serviceToken(),
863
+ service: true,
864
+ body: { keyId, expectedProduct: product }
865
+ });
866
+ if (!result || result.status >= 500 || result.status === 429) return { succeeded: false, error: refusal2(503, null) };
867
+ const body2 = result.body;
868
+ if (result.status !== 200 || typeof body2?.valid !== "boolean" || body2.valid && body2.keyId !== keyId) {
869
+ return failure(502, "delegated_key.response_invalid", "Platform returned no verification verdict for this key.");
870
+ }
871
+ const number = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
872
+ return { succeeded: true, value: {
873
+ valid: body2.valid,
874
+ ...typeof body2.invalidReason === "string" ? { invalidReason: body2.invalidReason } : {},
875
+ ...number(body2.budgetUsd) !== void 0 ? { budgetUsd: number(body2.budgetUsd) } : {},
876
+ ...number(body2.budgetRemaining) !== void 0 ? { budgetRemaining: number(body2.budgetRemaining) } : {},
877
+ ...typeof body2.expiresAt === "string" ? { expiresAt: body2.expiresAt } : {}
878
+ } };
879
+ },
880
+ async revoke({ sourceKey, keyId, slot }) {
881
+ const result = await call(`/v1/keys/${encodeURIComponent(keyId)}`, { method: "DELETE", bearer: sourceKey, service: false });
882
+ if (!result) return { succeeded: false, error: refusal2(503, null) };
883
+ if (result.status === 404 || result.status >= 200 && result.status < 300 && result.body?.success === true) {
884
+ return { succeeded: true, value: null };
885
+ }
886
+ if (result.status === 403 && slot) {
887
+ let name = slot.name;
888
+ let product = slot.product;
889
+ if (!name || !product) {
890
+ const row = await call(`/v1/keys/${encodeURIComponent(keyId)}`, { method: "GET", bearer: sourceKey, service: false });
891
+ const data = record2(row?.body?.data);
892
+ if (row?.status === 404) return { succeeded: true, value: null };
893
+ if (!row || row.status !== 200 || typeof data?.name !== "string" || typeof data.product !== "string") {
894
+ return { succeeded: false, error: refusal2(row?.status ?? 503, null) };
895
+ }
896
+ if (data.revokedAt) return { succeeded: true, value: null };
897
+ name = data.name;
898
+ product = data.product;
899
+ }
900
+ const retired = await call("/v1/keys/auto-provisioned/revoke-slot", {
901
+ method: "POST",
902
+ bearer: serviceToken(),
903
+ service: true,
904
+ body: {
905
+ userId: slot.userId,
906
+ name,
907
+ product,
908
+ childKeyId: keyId,
909
+ ...slot.sourceKeyId ? { sourceKeyId: slot.sourceKeyId } : {}
910
+ }
911
+ });
912
+ if (!retired) return { succeeded: false, error: refusal2(503, null) };
913
+ if (retired.status >= 200 && retired.status < 300 && retired.body?.success === true) return { succeeded: true, value: null };
914
+ return { succeeded: false, error: refusal2(retired.status, record2(retired.body?.error)?.code) };
915
+ }
916
+ return { succeeded: false, error: refusal2(result.status, record2(result.body?.error)?.code) };
917
+ },
918
+ async listChildren({ sourceKey, name, product }) {
919
+ const canonical = canonicalDelegatedKeyName({ serviceName: options.serviceName, product, name });
920
+ const result = await call("/v1/keys", { method: "GET", bearer: sourceKey, service: false });
921
+ if (!result) return { succeeded: false, error: refusal2(503, null) };
922
+ const rows = result.body?.data;
923
+ if (result.status !== 200 || result.body?.success !== true || !Array.isArray(rows)) {
924
+ return { succeeded: false, error: refusal2(result.status, record2(result.body?.error)?.code) };
925
+ }
926
+ return { succeeded: true, value: rows.flatMap((row) => {
927
+ const value = record2(row);
928
+ return value && typeof value.id === "string" && value.name === canonical && value.product === product && !value.revokedAt ? [{ id: value.id }] : [];
929
+ }) };
930
+ }
931
+ };
932
+ return client;
933
+ }
934
+ var DelegatedKeyMissingError = class extends Error {
935
+ status = 404;
936
+ code = "not_found";
937
+ constructor(keyId) {
938
+ super(`Platform no longer accepts key ${keyId}`);
939
+ this.name = "DelegatedKeyMissingError";
940
+ }
941
+ };
942
+ var DelegatedKeyRefusalError = class extends Error {
943
+ constructor(refusal3) {
944
+ super(refusal3.message);
945
+ this.refusal = refusal3;
946
+ this.name = "DelegatedKeyRefusalError";
947
+ }
948
+ refusal;
949
+ };
950
+ var GONE_REASONS = /* @__PURE__ */ new Set([
951
+ "key_not_found",
952
+ "key_revoked",
953
+ "key_expired",
954
+ "key_lineage_revoked",
955
+ "parent_key_not_found",
956
+ "parent_key_revoked",
957
+ "parent_key_expired",
958
+ "parent_key_lineage_revoked",
959
+ "ancestor_key_not_found",
960
+ "ancestor_key_revoked",
961
+ "ancestor_key_expired",
962
+ "ancestor_key_lineage_revoked"
963
+ ]);
964
+ var SPENT_REASONS = /* @__PURE__ */ new Set(["budget_exhausted", "monthly_budget_exhausted"]);
965
+ function createDelegatedKeyProvisioner(input) {
966
+ const product = input.product;
967
+ const slotOwner = input.payerId ? { userId: input.payerId, ...input.expect?.sourceKeyId ? { sourceKeyId: input.expect.sourceKeyId } : {} } : void 0;
968
+ return {
969
+ async createKey(create) {
970
+ const minted = await input.client.delegate({
971
+ sourceKey: input.sourceKey,
972
+ name: create.name,
973
+ product,
974
+ ...input.resource ? { resource: input.resource } : {},
975
+ ...input.allowedModels ? { allowedModels: input.allowedModels } : {},
976
+ budget: { usd: create.budgetUsd, ...input.monthlyBudgetUsd !== void 0 ? { monthlyUsd: input.monthlyBudgetUsd } : {} },
977
+ ...input.rpmLimit !== void 0 ? { rpmLimit: input.rpmLimit } : {},
978
+ expiresAt: new Date(create.expiresAt),
979
+ ...input.expect ? { expect: input.expect } : {}
980
+ });
981
+ if (!minted.succeeded) throw new DelegatedKeyRefusalError(minted.error);
982
+ return { id: minted.value.id, key: minted.value.key, budgetUsd: minted.value.budgetUsd, expiresAt: minted.value.expiresAt.toISOString() };
983
+ },
984
+ async getKey(id) {
985
+ const verdict = await input.client.verify({ keyId: id, product });
986
+ if (!verdict.succeeded) throw new DelegatedKeyRefusalError(verdict.error);
987
+ const v = verdict.value;
988
+ if (v.valid) {
989
+ return {
990
+ ...v.budgetUsd !== void 0 ? { budgetUsd: v.budgetUsd } : {},
991
+ ...v.budgetUsd !== void 0 && v.budgetRemaining !== void 0 ? { budgetSpent: Math.max(0, v.budgetUsd - v.budgetRemaining) } : {},
992
+ ...v.expiresAt ? { expiresAt: v.expiresAt } : {}
993
+ };
994
+ }
995
+ if (v.invalidReason && GONE_REASONS.has(v.invalidReason)) throw new DelegatedKeyMissingError(id);
996
+ if (v.invalidReason && SPENT_REASONS.has(v.invalidReason)) {
997
+ return { budgetUsd: v.budgetUsd ?? 0, budgetSpent: v.budgetUsd ?? 0, ...v.expiresAt ? { expiresAt: v.expiresAt } : {} };
998
+ }
999
+ throw new DelegatedKeyRefusalError({
1000
+ status: 403,
1001
+ code: "delegated_key.refused",
1002
+ message: `Platform refused the key for now (${v.invalidReason ?? "no reason"}).`
1003
+ });
1004
+ },
1005
+ async revokeKey(id) {
1006
+ const revoked = await input.client.revoke({ sourceKey: input.sourceKey, keyId: id, ...slotOwner ? { slot: slotOwner } : {} });
1007
+ if (!revoked.succeeded) throw new DelegatedKeyRefusalError(revoked.error);
1008
+ return null;
1009
+ },
1010
+ async findCreatedKeys(find) {
1011
+ const listed = await input.client.listChildren({ sourceKey: input.sourceKey, name: find.name, product: find.product });
1012
+ if (!listed.succeeded) throw new DelegatedKeyRefusalError(listed.error);
1013
+ return listed.value;
1014
+ }
1015
+ };
1016
+ }
707
1017
  export {
708
1018
  DEFAULT_SEAT_BILLING_ENABLED_ENV_VAR,
709
1019
  DEFAULT_TANGLE_TIER_POLICY,
1020
+ DelegatedKeyMissingError,
1021
+ DelegatedKeyRefusalError,
710
1022
  FREE_TIER_SPEND_CAP_USD,
711
1023
  PLATFORM_AGENT_KEY_PROVISIONER,
712
1024
  PLATFORM_KEY_PREFIX,
@@ -717,15 +1029,18 @@ export {
717
1029
  TangleSsoUserCreateError,
718
1030
  agentOperatorScopes,
719
1031
  assertBillableBalance,
1032
+ canonicalDelegatedKeyName,
720
1033
  createAdminGuard,
721
1034
  createApiKeyRequestAuth,
722
1035
  createAuthGuard,
723
1036
  createBetterAuthSessionCookieMinter,
724
1037
  createD1TangleIdentityStore,
1038
+ createDelegatedKeyProvisioner,
725
1039
  createHubSettingsRoutes,
726
1040
  createPlatformAgentKeyVerifier,
727
1041
  createPlatformAgentSpend,
728
1042
  createPlatformBillingHttp,
1043
+ createPlatformDelegatedKeyClient,
729
1044
  createSignedSsoState,
730
1045
  createTanglePlatformBillingClient,
731
1046
  createTangleSsoHandlers,