@withgateway/sdk 0.4.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. package/dist/agents/index.d.mts +573 -0
  2. package/dist/agents/index.d.ts +573 -0
  3. package/dist/agents/index.js +1443 -0
  4. package/dist/agents/index.js.map +1 -0
  5. package/dist/agents/index.mjs +1394 -0
  6. package/dist/agents/index.mjs.map +1 -0
  7. package/dist/apiError-DHpfbmdx.d.mts +17 -0
  8. package/dist/apiError-DHpfbmdx.d.ts +17 -0
  9. package/dist/cli.js +5655 -1890
  10. package/dist/cli.js.map +1 -1
  11. package/dist/cli.mjs +5769 -2005
  12. package/dist/cli.mjs.map +1 -1
  13. package/dist/files/index.d.mts +3 -1
  14. package/dist/files/index.d.ts +3 -1
  15. package/dist/files/index.js +418 -120
  16. package/dist/files/index.js.map +1 -1
  17. package/dist/files/index.mjs +418 -120
  18. package/dist/files/index.mjs.map +1 -1
  19. package/dist/hooks/index.js +346 -136
  20. package/dist/hooks/index.js.map +1 -1
  21. package/dist/hooks/index.mjs +346 -136
  22. package/dist/hooks/index.mjs.map +1 -1
  23. package/dist/{index-DUHmS74p.d.ts → index-DIN14Lhg.d.ts} +27 -4
  24. package/dist/{index-mJhG3vZU.d.mts → index-DuB-eQ0Z.d.mts} +27 -4
  25. package/dist/index.d.mts +7 -4
  26. package/dist/index.d.ts +7 -4
  27. package/dist/index.js +2862 -438
  28. package/dist/index.js.map +1 -1
  29. package/dist/index.mjs +2820 -431
  30. package/dist/index.mjs.map +1 -1
  31. package/dist/media-CQUC7TkS.d.mts +39 -0
  32. package/dist/media-DQnBloaX.d.ts +39 -0
  33. package/dist/replay/index.d.mts +1 -1
  34. package/dist/replay/index.d.ts +1 -1
  35. package/dist/replay/index.js.map +1 -1
  36. package/dist/replay/index.mjs.map +1 -1
  37. package/dist/traces/index.d.mts +3 -1
  38. package/dist/traces/index.d.ts +3 -1
  39. package/dist/traces/index.js +418 -120
  40. package/dist/traces/index.js.map +1 -1
  41. package/dist/traces/index.mjs +418 -120
  42. package/dist/traces/index.mjs.map +1 -1
  43. package/dist/tracing/index.d.mts +3 -2
  44. package/dist/tracing/index.d.ts +3 -2
  45. package/dist/tracing/index.js +257 -16
  46. package/dist/tracing/index.js.map +1 -1
  47. package/dist/tracing/index.mjs +257 -16
  48. package/dist/tracing/index.mjs.map +1 -1
  49. package/dist/transport-CpRe7zgd.d.mts +123 -0
  50. package/dist/transport-CpRe7zgd.d.ts +123 -0
  51. package/dist/worlds/index.d.mts +2086 -1749
  52. package/dist/worlds/index.d.ts +2086 -1749
  53. package/dist/worlds/index.js +1471 -269
  54. package/dist/worlds/index.js.map +1 -1
  55. package/dist/worlds/index.mjs +1466 -265
  56. package/dist/worlds/index.mjs.map +1 -1
  57. package/package.json +6 -1
  58. package/runtime/gatewaysdk/environment/_bundle.py +4 -6
  59. package/runtime/gatewaysdk/environment/_world.py +24 -1
  60. package/runtime/gatewaysdk/environment/bundle_manifest.py +243 -0
  61. package/runtime/gatewaysdk/environment/runtime.py +45 -2
  62. package/runtime/gatewaysdk/environment/schema/__main__.py +2 -2
  63. package/runtime/gatewaysdk/environment/schema/_slack_fidelity.py +8 -23
  64. package/runtime/gatewaysdk/environment/schema/api.py +27 -7
  65. package/runtime/gatewaysdk/environment/schema/assertions.py +7 -1
  66. package/runtime/gatewaysdk/environment/schema/bundle_runtime.py +2 -0
  67. package/runtime/gatewaysdk/environment/schema/call_capture.py +13 -1
  68. package/runtime/gatewaysdk/environment/schema/call_log.py +66 -0
  69. package/runtime/gatewaysdk/environment/schema/call_redaction.py +6 -0
  70. package/runtime/gatewaysdk/environment/schema/compiler.py +4 -1
  71. package/runtime/gatewaysdk/environment/schema/conform.py +32 -8
  72. package/runtime/gatewaysdk/environment/schema/connector.py +5 -0
  73. package/runtime/gatewaysdk/environment/schema/connectors/custom/handlers.py +2 -1
  74. package/runtime/gatewaysdk/environment/schema/connectors/github/api/handlers.py +217 -58
  75. package/runtime/gatewaysdk/environment/schema/connectors/github/connector.toml +9 -19
  76. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_webhooks.json +10 -2
  77. package/runtime/gatewaysdk/environment/schema/connectors/github/tests/webhooks.json +47 -0
  78. package/runtime/gatewaysdk/environment/schema/connectors/github/world.json +21 -0
  79. package/runtime/gatewaysdk/environment/schema/connectors/jamf/api/handlers.py +185 -18
  80. package/runtime/gatewaysdk/environment/schema/connectors/jamf/connector.toml +29 -14
  81. package/runtime/gatewaysdk/environment/schema/connectors/jamf/provenance.json +43 -12
  82. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_webhooks.json +2 -2
  83. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scope.toml +4 -17
  84. package/runtime/gatewaysdk/environment/schema/connectors/jamf/tests/webhooks.json +107 -0
  85. package/runtime/gatewaysdk/environment/schema/connectors/jamf/vendor-openapi.json +1 -1
  86. package/runtime/gatewaysdk/environment/schema/connectors/linear/api/handlers.py +85 -1
  87. package/runtime/gatewaysdk/environment/schema/connectors/linear/connector.toml +19 -31
  88. package/runtime/gatewaysdk/environment/schema/connectors/linear/provenance.json +18 -8
  89. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/webhooks.json +19 -3
  90. package/runtime/gatewaysdk/environment/schema/connectors/linear/tests/test_webhooks.py +71 -0
  91. package/runtime/gatewaysdk/environment/schema/database/base.py +2 -2
  92. package/runtime/gatewaysdk/environment/schema/database/guard.py +2 -1
  93. package/runtime/gatewaysdk/environment/schema/handler_errors.py +27 -1
  94. package/runtime/gatewaysdk/environment/schema/host.py +74 -11
  95. package/runtime/gatewaysdk/environment/schema/host_browser.py +48 -0
  96. package/runtime/gatewaysdk/environment/schema/host_control.py +33 -2
  97. package/runtime/gatewaysdk/environment/schema/host_handoff.py +4 -1
  98. package/runtime/gatewaysdk/environment/schema/host_requests.py +14 -0
  99. package/runtime/gatewaysdk/environment/schema/host_session.py +13 -2
  100. package/runtime/gatewaysdk/environment/schema/host_surfaces.py +6 -0
  101. package/runtime/gatewaysdk/environment/schema/host_versions.py +96 -19
  102. package/runtime/gatewaysdk/environment/schema/journal.py +10 -4
  103. package/runtime/gatewaysdk/environment/schema/local.py +33 -7
  104. package/runtime/gatewaysdk/environment/schema/openapi_schemas.py +20 -5
  105. package/runtime/gatewaysdk/environment/schema/page_checks.py +123 -0
  106. package/runtime/gatewaysdk/environment/schema/platform.py +33 -480
  107. package/runtime/gatewaysdk/environment/schema/platform_templates.py +332 -0
  108. package/runtime/gatewaysdk/environment/schema/request_ledger.py +4 -1
  109. package/runtime/gatewaysdk/environment/schema/run_parameters.py +25 -0
  110. package/runtime/gatewaysdk/environment/schema/runtime.py +49 -4
  111. package/runtime/gatewaysdk/environment/schema/scaffold.py +369 -218
  112. package/runtime/gatewaysdk/environment/schema/session_files.py +13 -2
  113. package/runtime/gatewaysdk/environment/schema/skills/benchmarks-getting-started/SKILL.md +1 -1
  114. package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/CONNECTORS.md +3 -3
  115. package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/SKILL.md +20 -24
  116. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/SKILL.md +11 -11
  117. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/SKILL.md +9 -9
  118. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/cli-mcp-map.md +45 -12
  119. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/gotchas.md +40 -9
  120. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/journal-checks.md +17 -2
  121. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/new-world-sandbox.md +1 -1
  122. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/ui-map.md +3 -2
  123. package/runtime/gatewaysdk/environment/schema/slack.py +55 -10
  124. package/runtime/gatewaysdk/environment/schema/snapshot.py +30 -4
  125. package/runtime/gatewaysdk/environment/schema/tasks.py +25 -2
  126. package/runtime/gatewaysdk/environment/schema/template_record.py +131 -0
  127. package/runtime/gatewaysdk/environment/schema/tools_world.py +26 -5
  128. package/runtime/gatewaysdk/environment/schema/ui.py +54 -33
  129. package/runtime/gatewaysdk/environment/schema/ui_interactions.py +419 -0
  130. package/runtime/gatewaysdk/environment/schema/ui_recorder.js +895 -0
  131. package/runtime/gatewaysdk/environment/schema/ui_replay.py +366 -0
  132. package/runtime/gatewaysdk/environment/schema/ui_replay_record.LICENSE +25 -0
  133. package/runtime/gatewaysdk/environment/schema/ui_replay_record.js +109 -0
  134. package/runtime/gatewaysdk/environment/schema/validation.py +10 -1
  135. package/runtime/gatewaysdk/environment/schema/verbs.py +6 -0
  136. package/runtime/gatewaysdk/environment/schema/webhooks.py +687 -0
  137. package/runtime/gatewaysdk/environment/schema/worker.py +5 -1
  138. package/runtime/gatewaysdk/environment/schema/workers.py +8 -1
  139. package/runtime/gatewaysdk/environment/schema/world_host.py +64 -18
  140. package/runtime/gatewaysdk/environment/schema/world_tests.py +74 -0
  141. package/runtime/gatewaysdk/environment/secret_values.py +1 -1
  142. package/runtime/gatewaysdk/environment/world.py +34 -43
  143. package/runtime/gatewaysdk/environment/world_session_contract.py +7 -34
  144. package/skills/benchmarks-getting-started/SKILL.md +1 -1
  145. package/skills/connector-schema-authoring/CONNECTORS.md +3 -3
  146. package/skills/connector-schema-authoring/SKILL.md +20 -24
  147. package/skills/connector-schema-authoring/connector-worlds.md +155 -13
  148. package/skills/connector-schema-authoring/world-schema.md +36 -29
  149. package/skills/world-data-ingestion/SKILL.md +11 -11
  150. package/skills/worlds-getting-started/SKILL.md +9 -9
  151. package/skills/worlds-getting-started/references/cli-mcp-map.md +45 -12
  152. package/skills/worlds-getting-started/references/gotchas.md +40 -9
  153. package/skills/worlds-getting-started/references/journal-checks.md +17 -2
  154. package/skills/worlds-getting-started/references/new-world-sandbox.md +1 -1
  155. package/skills/worlds-getting-started/references/ui-map.md +3 -2
  156. package/dist/media-BIApiPzS.d.mts +0 -102
  157. package/dist/media-BIApiPzS.d.ts +0 -102
@@ -1,5 +1,6 @@
1
- export { I as IdentifyOptions, a as IdentitySpanProcessor, O as ObservationKind, b as ObserveClaudeOptions, c as ObserveOptions, S as SECRET_KEYS, d as SESSION_ID_ATTRIBUTE, e as SecretRedactingSpanProcessor, f as SessionSpanProcessor, g as SpanSecrets, T as TracingConfig, h as TracingHandle, j as TracingState, U as USER_ID_ATTRIBUTE, W as WORLD_SESSION_ID_ATTRIBUTE, k as flush, l as getAmbientSessionId, m as getCurrentWorldSessionId, i as identify, n as init, o as initIsolated, p as isGatewayConfigured, q as isInitialized, s as observe, t as observeAnthropic, u as observeClaude, v as observeOpenAI, w as resetAmbientUser, r as resolveUserId, x as shutdown, y as withSession, z as withWorldSession } from '../index-mJhG3vZU.mjs';
2
- export { M as MAX_MEDIA_BYTES, f as MediaField, g as MediaReference, h as MediaUploadError, i as MediaUploader } from '../media-BIApiPzS.mjs';
1
+ export { I as IdentifyOptions, a as IdentitySpanProcessor, O as ObservationKind, b as ObserveClaudeOptions, c as ObserveOptions, S as SECRET_KEYS, d as SESSION_ID_ATTRIBUTE, e as SecretRedactingSpanProcessor, f as SessionSpanProcessor, g as SpanSecrets, T as TracingConfig, h as TracingHandle, j as TracingState, U as USER_ID_ATTRIBUTE, W as WORLD_SESSION_ID_ATTRIBUTE, k as flush, l as getAmbientSessionId, m as getCurrentWorldSessionId, i as identify, n as init, o as initIsolated, p as isGatewayConfigured, q as isInitialized, s as observe, t as observeAnthropic, u as observeClaude, v as observeOpenAI, w as resetAmbientUser, r as resolveUserId, x as shutdown, y as withSession, z as withWorldSession } from '../index-DuB-eQ0Z.mjs';
2
+ export { M as MAX_MEDIA_BYTES, a as MediaField, b as MediaReference, c as MediaUploadError, d as MediaUploader } from '../media-CQUC7TkS.mjs';
3
3
  import '@opentelemetry/api';
4
4
  import '../scores/index.mjs';
5
5
  import '@opentelemetry/sdk-trace-base';
6
+ import '../transport-CpRe7zgd.mjs';
@@ -1,5 +1,6 @@
1
- export { I as IdentifyOptions, a as IdentitySpanProcessor, O as ObservationKind, b as ObserveClaudeOptions, c as ObserveOptions, S as SECRET_KEYS, d as SESSION_ID_ATTRIBUTE, e as SecretRedactingSpanProcessor, f as SessionSpanProcessor, g as SpanSecrets, T as TracingConfig, h as TracingHandle, j as TracingState, U as USER_ID_ATTRIBUTE, W as WORLD_SESSION_ID_ATTRIBUTE, k as flush, l as getAmbientSessionId, m as getCurrentWorldSessionId, i as identify, n as init, o as initIsolated, p as isGatewayConfigured, q as isInitialized, s as observe, t as observeAnthropic, u as observeClaude, v as observeOpenAI, w as resetAmbientUser, r as resolveUserId, x as shutdown, y as withSession, z as withWorldSession } from '../index-DUHmS74p.js';
2
- export { M as MAX_MEDIA_BYTES, f as MediaField, g as MediaReference, h as MediaUploadError, i as MediaUploader } from '../media-BIApiPzS.js';
1
+ export { I as IdentifyOptions, a as IdentitySpanProcessor, O as ObservationKind, b as ObserveClaudeOptions, c as ObserveOptions, S as SECRET_KEYS, d as SESSION_ID_ATTRIBUTE, e as SecretRedactingSpanProcessor, f as SessionSpanProcessor, g as SpanSecrets, T as TracingConfig, h as TracingHandle, j as TracingState, U as USER_ID_ATTRIBUTE, W as WORLD_SESSION_ID_ATTRIBUTE, k as flush, l as getAmbientSessionId, m as getCurrentWorldSessionId, i as identify, n as init, o as initIsolated, p as isGatewayConfigured, q as isInitialized, s as observe, t as observeAnthropic, u as observeClaude, v as observeOpenAI, w as resetAmbientUser, r as resolveUserId, x as shutdown, y as withSession, z as withWorldSession } from '../index-DIN14Lhg.js';
2
+ export { M as MAX_MEDIA_BYTES, a as MediaField, b as MediaReference, c as MediaUploadError, d as MediaUploader } from '../media-DQnBloaX.js';
3
3
  import '@opentelemetry/api';
4
4
  import '../scores/index.js';
5
5
  import '@opentelemetry/sdk-trace-base';
6
+ import '../transport-CpRe7zgd.js';
@@ -29,7 +29,7 @@ var require_package = __commonJS({
29
29
  "package.json"(exports2, module2) {
30
30
  module2.exports = {
31
31
  name: "@withgateway/sdk",
32
- version: "0.4.0",
32
+ version: "0.9.1",
33
33
  description: "Gateway SDK for TypeScript - A/B experiments, tracing, and observability",
34
34
  main: "./dist/index.js",
35
35
  module: "./dist/index.mjs",
@@ -110,6 +110,11 @@ var require_package = __commonJS({
110
110
  import: "./dist/hooks/index.mjs",
111
111
  require: "./dist/hooks/index.js"
112
112
  },
113
+ "./agents": {
114
+ types: "./dist/agents/index.d.ts",
115
+ import: "./dist/agents/index.mjs",
116
+ require: "./dist/agents/index.js"
117
+ },
113
118
  "./cli": {
114
119
  types: "./dist/cli.d.ts",
115
120
  import: "./dist/cli.mjs",
@@ -1766,6 +1771,106 @@ async function* observeClaude(stream, options) {
1766
1771
  // src/tracing/media.ts
1767
1772
  var import_node_crypto2 = require("crypto");
1768
1773
 
1774
+ // src/worlds/apiError.ts
1775
+ var ApiError = class extends Error {
1776
+ constructor(status, method, path, text) {
1777
+ const parsed = parseErrorBody(text, status);
1778
+ super(`${method} ${path} -> ${status}: ${parsed.detail}`);
1779
+ this.status = status;
1780
+ this.text = text;
1781
+ this.name = "ApiError";
1782
+ this.code = parsed.code;
1783
+ }
1784
+ status;
1785
+ text;
1786
+ code;
1787
+ };
1788
+ var DETAIL_LIMIT = 600;
1789
+ var EDGE_ANSWERS = {
1790
+ 502: "Bad Gateway from the load balancer in front of the platform, not the platform's answer: the web server dropped the connection or restarted mid-request. Retry; if it repeats, the platform is restarting or overloaded.",
1791
+ 503: "Service Unavailable from the load balancer in front of the platform, not the platform's answer: no web server was ready to take the request (a deploy or a restart). Retry in a minute.",
1792
+ 504: "Gateway Time-out from the load balancer in front of the platform, not the platform's answer: the request sent nothing back within the load balancer's idle timeout (60 s unless the deployment raises it: Helm ingress.idleTimeoutSeconds) and was cut there, though the platform may still be running it. Check what it changed before you retry."
1793
+ };
1794
+ var EDGE_FAILURE = "The platform failed without its JSON error body: a proxy in front of it answered, or the server stopped before its error handler ran. Retry; if it repeats, report the request and the time.";
1795
+ var EDGE_PAGE = "An HTML page answered instead of the platform's JSON: a proxy in front of the platform, or the configured host is not the platform.";
1796
+ function edgeAnswer(text, status) {
1797
+ if (status !== void 0 && status >= 500) return EDGE_ANSWERS[status] ?? EDGE_FAILURE;
1798
+ return /^\s*</.test(text) ? EDGE_PAGE : null;
1799
+ }
1800
+ function parseErrorBody(text, status) {
1801
+ const raw = { detail: text.slice(0, DETAIL_LIMIT), code: null };
1802
+ let parsed;
1803
+ try {
1804
+ parsed = JSON.parse(text);
1805
+ } catch {
1806
+ return { detail: (edgeAnswer(text, status) ?? text).slice(0, DETAIL_LIMIT), code: null };
1807
+ }
1808
+ if (parsed === null || typeof parsed !== "object") return raw;
1809
+ const { message, code, error } = parsed;
1810
+ const stableCode = typeof code === "string" ? code : null;
1811
+ if (typeof message !== "string") return { ...raw, code: stableCode };
1812
+ const fields = invalidFields(error);
1813
+ const said = fields ? `${message}: ${fields}` : message;
1814
+ if (stableCode === null) return { detail: said.slice(0, DETAIL_LIMIT), code: null };
1815
+ return {
1816
+ detail: `${said} (${stableCode})`.slice(0, DETAIL_LIMIT),
1817
+ code: stableCode
1818
+ };
1819
+ }
1820
+ function invalidFields(error) {
1821
+ const issues = Array.isArray(error) ? error : [];
1822
+ return issues.filter(
1823
+ (issue) => issue !== null && typeof issue === "object" && typeof issue.message === "string"
1824
+ ).map((issue) => {
1825
+ const path = Array.isArray(issue.path) ? issue.path.map(String).join(".") : "";
1826
+ return path ? `${path}: ${issue.message}` : issue.message;
1827
+ }).join("; ");
1828
+ }
1829
+
1830
+ // src/worlds/personalToken.ts
1831
+ var TOKEN_NOT_PERSONAL = "GATEWAY_TOKEN takes a personal access token: pat_ followed by letters and digits only.";
1832
+ var TOKEN_NEEDS_PROJECT = "GATEWAY_TOKEN acts in the project GATEWAY_PROJECT_ID names: set it to the official project's id (letters, digits, - and _).";
1833
+ var TOKEN_NEEDS_HOST = "GATEWAY_TOKEN goes only to the host GATEWAY_HOST names: set GATEWAY_HOST.";
1834
+ var TOKEN_OTHER_HOST = "GATEWAY_TOKEN goes only to the host GATEWAY_HOST names, and this call names another host: point the call at GATEWAY_HOST or unset GATEWAY_TOKEN.";
1835
+ var TOKEN_BESIDE_KEYS = "GATEWAY_TOKEN is set beside a project key (GATEWAY_PUBLIC_KEY, GATEWAY_SECRET_KEY, GATEWAY_API_KEY or a key passed in): unset one of them. Neither replaces the other.";
1836
+ var PERSONAL = /^pat_[A-Za-z0-9]+$/;
1837
+ var PROJECT = /^[A-Za-z0-9_-]+$/;
1838
+ var ENV_KEYS = ["GATEWAY_PUBLIC_KEY", "GATEWAY_SECRET_KEY", "GATEWAY_API_KEY"];
1839
+ var PersonalTokenRefused = class extends Error {
1840
+ };
1841
+ var bare = (host) => host.replace(/\/+$/, "");
1842
+ var PersonalToken = class _PersonalToken {
1843
+ constructor(value, project, host) {
1844
+ this.value = value;
1845
+ this.project = project;
1846
+ this.host = host;
1847
+ }
1848
+ value;
1849
+ project;
1850
+ host;
1851
+ static fromEnv(env, request = {}) {
1852
+ const value = env.GATEWAY_TOKEN;
1853
+ if (!value) return null;
1854
+ if (request.keys || ENV_KEYS.some((name) => env[name])) throw new PersonalTokenRefused(TOKEN_BESIDE_KEYS);
1855
+ const host = bare(env.GATEWAY_HOST ?? "");
1856
+ if (!host) throw new PersonalTokenRefused(TOKEN_NEEDS_HOST);
1857
+ if (request.host && bare(request.host) !== host) throw new PersonalTokenRefused(TOKEN_OTHER_HOST);
1858
+ if (!PERSONAL.test(value)) throw new PersonalTokenRefused(TOKEN_NOT_PERSONAL);
1859
+ const project = env.GATEWAY_PROJECT_ID ?? "";
1860
+ if (!PROJECT.test(project)) throw new PersonalTokenRefused(TOKEN_NEEDS_PROJECT);
1861
+ return new _PersonalToken(value, project, host);
1862
+ }
1863
+ toJSON() {
1864
+ return { project: this.project, host: this.host };
1865
+ }
1866
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
1867
+ return `PersonalToken { project: ${this.project}, host: ${this.host} }`;
1868
+ }
1869
+ static scrubbed(env) {
1870
+ return Object.fromEntries(Object.entries(env).filter(([key]) => key !== "GATEWAY_TOKEN"));
1871
+ }
1872
+ };
1873
+
1769
1874
  // src/worlds/transport.ts
1770
1875
  var PLATFORM_TIMEOUT_ENV = "GATEWAY_TIMEOUT_MS";
1771
1876
  var PLATFORM_TIMEOUT_DEFAULT_MS = 12e4;
@@ -1813,6 +1918,13 @@ var TransportCause = class _TransportCause {
1813
1918
  `Retry; if the platform is slow, raise ${PLATFORM_TIMEOUT_ENV} (milliseconds per request).`
1814
1919
  );
1815
1920
  }
1921
+ static idle(idleMs) {
1922
+ return new _TransportCause(
1923
+ `no data for ${idleMs / 1e3}s`,
1924
+ null,
1925
+ "The stream resumes from its last event; if it repeats, check the network between here and the platform."
1926
+ );
1927
+ }
1816
1928
  static of(error) {
1817
1929
  const cause = error instanceof Error && error.cause instanceof Error ? error.cause : void 0;
1818
1930
  const code = cause && "code" in cause && typeof cause.code === "string" ? cause.code : null;
@@ -1888,45 +2000,174 @@ var Attempt = class _Attempt {
1888
2000
  throw this.error;
1889
2001
  }
1890
2002
  };
2003
+ var PLATFORM_STREAM_IDLE_MS = 6e4;
2004
+ var REFUSAL_TEXT_LIMIT = 64 * 1024;
2005
+ var KEYED_REDIRECTS = "manual";
2006
+ function platformAuthorization(endpoint, url) {
2007
+ const { token } = endpoint;
2008
+ if (!token)
2009
+ return { authorization: "Basic " + Buffer.from(`${endpoint.publicKey}:${endpoint.secretKey}`).toString("base64") };
2010
+ if (endpoint.publicKey || endpoint.secretKey) throw new PersonalTokenRefused(TOKEN_BESIDE_KEYS);
2011
+ if (!url.startsWith(`${token.host}/`)) throw new PersonalTokenRefused(TOKEN_OTHER_HOST);
2012
+ return { authorization: `Bearer ${token.value}`, "x-gateway-project": token.project };
2013
+ }
1891
2014
  var PlatformTransport = class {
2015
+ #endpoint;
2016
+ #timeoutMs;
1892
2017
  constructor(endpoint, timeoutMs = platformTimeoutMs()) {
1893
- this.endpoint = endpoint;
1894
- this.timeoutMs = timeoutMs;
2018
+ this.#endpoint = endpoint;
2019
+ this.#timeoutMs = timeoutMs;
1895
2020
  }
1896
- endpoint;
1897
- timeoutMs;
1898
2021
  /** A request that legitimately takes longer (a sandbox exec, a world create) waits its own budget; every other one waits the default. */
1899
2022
  budget(ownMs) {
1900
- return Math.max(ownMs ?? 0, this.timeoutMs);
2023
+ return Math.max(ownMs ?? 0, this.#timeoutMs);
1901
2024
  }
2025
+ /** One request; the caller's `signal` aborts it in flight and throws the signal's reason, never an `UnreachableError`. */
1902
2026
  async send(method, route, body, opts = {}) {
1903
2027
  const timeoutMs = this.budget(opts.timeoutMs);
1904
- return (opts.retry ?? RetryPolicy.NONE).run(() => this.once(method, route, body, timeoutMs));
2028
+ return (opts.retry ?? RetryPolicy.NONE).run(() => this.once(method, route, body, timeoutMs, opts.signal));
2029
+ }
2030
+ /** `send`, then the 2xx body as JSON; any other answer throws `ApiError` with its status and stable `code`. */
2031
+ async json(method, route, body, opts = {}) {
2032
+ const reply = await this.send(method, route, body, opts);
2033
+ if (!reply.ok) throw new ApiError(reply.status, method, route, reply.text);
2034
+ return JSON.parse(reply.text);
2035
+ }
2036
+ /** The streaming twin of `send` for a `GET` event stream: nothing is buffered, `after` travels as `Last-Event-ID`, and each wait for the platform (the headers, every chunk) may last `idleMs` (default 60 s) instead of the request budget. */
2037
+ async stream(route, opts = {}) {
2038
+ const watch = new StreamWatch(opts.signal, opts.idleMs ?? PLATFORM_STREAM_IDLE_MS, this.#endpoint.host, route);
2039
+ const headers = this.headers(route, "text/event-stream", opts.after ? { "last-event-id": opts.after } : {});
2040
+ try {
2041
+ const response = await watch.within(
2042
+ () => fetch(this.url(route), { method: "GET", headers, signal: watch.signal, redirect: KEYED_REDIRECTS })
2043
+ );
2044
+ return new PlatformStream(response, watch);
2045
+ } catch (error) {
2046
+ watch.close();
2047
+ throw error;
2048
+ }
2049
+ }
2050
+ url(route) {
2051
+ return `${this.#endpoint.host}${route}`;
2052
+ }
2053
+ headers(route, accept, extra = {}) {
2054
+ return {
2055
+ "content-type": "application/json",
2056
+ accept,
2057
+ ...platformAuthorization(this.#endpoint, this.url(route)),
2058
+ ...extra
2059
+ };
1905
2060
  }
1906
- async once(method, route, body, timeoutMs) {
2061
+ async once(method, route, body, timeoutMs, caller) {
2062
+ if (caller?.aborted) throw caller.reason;
1907
2063
  const payload = body === void 0 ? {} : { body: JSON.stringify(body) };
2064
+ const headers = this.headers(route, "application/json");
1908
2065
  const controller = new AbortController();
1909
2066
  const timer = setTimeout(() => controller.abort(), timeoutMs);
2067
+ const relay = () => controller.abort(caller?.reason);
2068
+ caller?.addEventListener("abort", relay, { once: true });
1910
2069
  try {
1911
- const res = await fetch(`${this.endpoint.host}${route}`, {
2070
+ const res = await fetch(this.url(route), {
1912
2071
  method,
1913
- headers: {
1914
- "content-type": "application/json",
1915
- accept: "application/json",
1916
- authorization: "Basic " + Buffer.from(`${this.endpoint.publicKey}:${this.endpoint.secretKey}`).toString("base64")
1917
- },
2072
+ headers,
1918
2073
  ...payload,
1919
- signal: controller.signal
2074
+ signal: controller.signal,
2075
+ redirect: KEYED_REDIRECTS
1920
2076
  });
1921
2077
  return { status: res.status, ok: res.ok, text: await res.text() };
1922
2078
  } catch (error) {
2079
+ if (caller?.aborted) throw caller.reason;
1923
2080
  const cause = controller.signal.aborted ? TransportCause.timeout(timeoutMs) : TransportCause.of(error);
1924
- throw new UnreachableError(this.endpoint.host, method, route, cause);
2081
+ throw new UnreachableError(this.#endpoint.host, method, route, cause);
1925
2082
  } finally {
1926
2083
  clearTimeout(timer);
2084
+ caller?.removeEventListener("abort", relay);
1927
2085
  }
1928
2086
  }
1929
2087
  };
2088
+ var StreamWatch = class {
2089
+ constructor(caller, idleMs, host, route) {
2090
+ this.idleMs = idleMs;
2091
+ this.host = host;
2092
+ this.route = route;
2093
+ this.#caller = caller;
2094
+ caller?.addEventListener("abort", this.#relay, { once: true });
2095
+ if (caller?.aborted) this.#relay();
2096
+ }
2097
+ idleMs;
2098
+ host;
2099
+ route;
2100
+ #controller = new AbortController();
2101
+ #caller;
2102
+ #relay = () => this.#controller.abort(this.#caller?.reason);
2103
+ #idled = false;
2104
+ get signal() {
2105
+ return this.#controller.signal;
2106
+ }
2107
+ async within(wait) {
2108
+ const timer = setTimeout(() => this.idle(), this.idleMs);
2109
+ try {
2110
+ return await wait();
2111
+ } catch (error) {
2112
+ throw this.failure(error);
2113
+ } finally {
2114
+ clearTimeout(timer);
2115
+ }
2116
+ }
2117
+ close() {
2118
+ this.#caller?.removeEventListener("abort", this.#relay);
2119
+ this.#controller.abort();
2120
+ }
2121
+ idle() {
2122
+ this.#idled = true;
2123
+ this.#controller.abort();
2124
+ }
2125
+ failure(error) {
2126
+ if (this.#caller?.aborted) return this.#caller.reason;
2127
+ const cause = this.#idled ? TransportCause.idle(this.idleMs) : TransportCause.of(error);
2128
+ return new UnreachableError(this.host, "GET", this.route, cause);
2129
+ }
2130
+ };
2131
+ var PlatformStream = class {
2132
+ #response;
2133
+ #watch;
2134
+ constructor(response, watch) {
2135
+ this.#response = response;
2136
+ this.#watch = watch;
2137
+ }
2138
+ get status() {
2139
+ return this.#response.status;
2140
+ }
2141
+ get ok() {
2142
+ return this.#response.ok;
2143
+ }
2144
+ /** The body as text, for a refusal: at most the first 64 KiB of characters; closes the stream. */
2145
+ async text() {
2146
+ const decoder = new TextDecoder();
2147
+ let text = "";
2148
+ for await (const chunk of this.chunks()) {
2149
+ text += decoder.decode(chunk, { stream: true });
2150
+ if (text.length >= REFUSAL_TEXT_LIMIT) return text.slice(0, REFUSAL_TEXT_LIMIT);
2151
+ }
2152
+ return text + decoder.decode();
2153
+ }
2154
+ /** The body's bytes as they arrive; the idle budget runs only while waiting for the platform, never while the caller holds a chunk. */
2155
+ async *chunks() {
2156
+ const reader = this.#response.body?.getReader();
2157
+ try {
2158
+ for (; ; ) {
2159
+ const next = reader ? await this.#watch.within(() => reader.read()) : { done: true };
2160
+ if (next.done) return;
2161
+ yield next.value;
2162
+ }
2163
+ } finally {
2164
+ this.close();
2165
+ }
2166
+ }
2167
+ close() {
2168
+ this.#watch.close();
2169
+ }
2170
+ };
1930
2171
 
1931
2172
  // src/tracing/media.ts
1932
2173
  var MEDIA_PATH = "/api/public/media";