@withgateway/sdk 0.6.0 → 0.9.3

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 (150) hide show
  1. package/dist/agents/index.d.mts +581 -0
  2. package/dist/agents/index.d.ts +581 -0
  3. package/dist/agents/index.js +1473 -0
  4. package/dist/agents/index.js.map +1 -0
  5. package/dist/agents/index.mjs +1424 -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 +11611 -6845
  10. package/dist/cli.js.map +1 -1
  11. package/dist/cli.mjs +10090 -5325
  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 +371 -102
  16. package/dist/files/index.js.map +1 -1
  17. package/dist/files/index.mjs +371 -102
  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-LA-PMRJT.d.ts → index-DIN14Lhg.d.ts} +1 -1
  24. package/dist/{index-Di9nNqOY.d.mts → index-DuB-eQ0Z.d.mts} +1 -1
  25. package/dist/index.d.mts +7 -4
  26. package/dist/index.d.ts +7 -4
  27. package/dist/index.js +3177 -748
  28. package/dist/index.js.map +1 -1
  29. package/dist/index.mjs +2987 -590
  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/traces/index.d.mts +3 -1
  34. package/dist/traces/index.d.ts +3 -1
  35. package/dist/traces/index.js +371 -102
  36. package/dist/traces/index.js.map +1 -1
  37. package/dist/traces/index.mjs +371 -102
  38. package/dist/traces/index.mjs.map +1 -1
  39. package/dist/tracing/index.d.mts +3 -2
  40. package/dist/tracing/index.d.ts +3 -2
  41. package/dist/tracing/index.js +257 -16
  42. package/dist/tracing/index.js.map +1 -1
  43. package/dist/tracing/index.mjs +257 -16
  44. package/dist/tracing/index.mjs.map +1 -1
  45. package/dist/transport-CpRe7zgd.d.mts +123 -0
  46. package/dist/transport-CpRe7zgd.d.ts +123 -0
  47. package/dist/worlds/index.d.mts +1986 -1746
  48. package/dist/worlds/index.d.ts +1986 -1746
  49. package/dist/worlds/index.js +1470 -290
  50. package/dist/worlds/index.js.map +1 -1
  51. package/dist/worlds/index.mjs +1465 -286
  52. package/dist/worlds/index.mjs.map +1 -1
  53. package/package.json +6 -1
  54. package/runtime/gatewaysdk/environment/bundle_manifest.py +531 -0
  55. package/runtime/gatewaysdk/environment/factory_documents.py +670 -0
  56. package/runtime/gatewaysdk/environment/factory_rules.py +973 -0
  57. package/runtime/gatewaysdk/environment/factory_shapes.py +253 -0
  58. package/runtime/gatewaysdk/environment/factory_spine.py +1155 -0
  59. package/runtime/gatewaysdk/environment/factory_spine_shapes.py +480 -0
  60. package/runtime/gatewaysdk/environment/schema/__main__.py +2 -2
  61. package/runtime/gatewaysdk/environment/schema/_slack_fidelity.py +8 -23
  62. package/runtime/gatewaysdk/environment/schema/admission.py +61 -59
  63. package/runtime/gatewaysdk/environment/schema/api.py +3 -4
  64. package/runtime/gatewaysdk/environment/schema/assertions.py +7 -1
  65. package/runtime/gatewaysdk/environment/schema/bundle_runtime.py +1 -0
  66. package/runtime/gatewaysdk/environment/schema/call_log.py +20 -0
  67. package/runtime/gatewaysdk/environment/schema/cast.py +133 -67
  68. package/runtime/gatewaysdk/environment/schema/compiler.py +16 -17
  69. package/runtime/gatewaysdk/environment/schema/database/base.py +2 -2
  70. package/runtime/gatewaysdk/environment/schema/handler_errors.py +58 -4
  71. package/runtime/gatewaysdk/environment/schema/host.py +94 -12
  72. package/runtime/gatewaysdk/environment/schema/host_browser.py +48 -0
  73. package/runtime/gatewaysdk/environment/schema/host_control.py +35 -2
  74. package/runtime/gatewaysdk/environment/schema/host_handoff.py +4 -1
  75. package/runtime/gatewaysdk/environment/schema/host_loops.py +27 -4
  76. package/runtime/gatewaysdk/environment/schema/host_metrics.py +69 -0
  77. package/runtime/gatewaysdk/environment/schema/host_requests.py +35 -0
  78. package/runtime/gatewaysdk/environment/schema/host_session.py +20 -2
  79. package/runtime/gatewaysdk/environment/schema/host_surfaces.py +6 -0
  80. package/runtime/gatewaysdk/environment/schema/host_versions.py +100 -19
  81. package/runtime/gatewaysdk/environment/schema/host_workers.py +172 -50
  82. package/runtime/gatewaysdk/environment/schema/ingest.py +12 -3
  83. package/runtime/gatewaysdk/environment/schema/journal.py +7 -2
  84. package/runtime/gatewaysdk/environment/schema/local.py +32 -7
  85. package/runtime/gatewaysdk/environment/schema/mapping.py +1 -1
  86. package/runtime/gatewaysdk/environment/schema/measured_tests.py +187 -0
  87. package/runtime/gatewaysdk/environment/schema/page_checks.py +123 -0
  88. package/runtime/gatewaysdk/environment/schema/platform.py +80 -270
  89. package/runtime/gatewaysdk/environment/schema/platform_query.py +4 -3
  90. package/runtime/gatewaysdk/environment/schema/platform_templates.py +420 -0
  91. package/runtime/gatewaysdk/environment/schema/process_memory.py +76 -0
  92. package/runtime/gatewaysdk/environment/schema/redaction.py +13 -0
  93. package/runtime/gatewaysdk/environment/schema/request_ledger.py +4 -1
  94. package/runtime/gatewaysdk/environment/schema/run_parameters.py +25 -0
  95. package/runtime/gatewaysdk/environment/schema/runtime.py +57 -5
  96. package/runtime/gatewaysdk/environment/schema/scaffold.py +386 -219
  97. package/runtime/gatewaysdk/environment/schema/session_files.py +13 -2
  98. package/runtime/gatewaysdk/environment/schema/shape_catalog.py +493 -0
  99. package/runtime/gatewaysdk/environment/schema/shape_declarations.py +219 -0
  100. package/runtime/gatewaysdk/environment/schema/skill.py +1 -0
  101. package/runtime/gatewaysdk/environment/schema/skills/benchmarks-getting-started/SKILL.md +1 -1
  102. package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/SKILL.md +2 -2
  103. package/runtime/gatewaysdk/environment/schema/skills/factory-orchestrator/SKILL.md +147 -0
  104. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/ROWS.md +5 -1
  105. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/SKILL.md +8 -6
  106. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/SKILL.md +9 -9
  107. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/cli-mcp-map.md +33 -2
  108. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/gotchas.md +6 -6
  109. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/journal-checks.md +17 -2
  110. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/new-world-sandbox.md +1 -1
  111. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/shape-catalog.md +59 -0
  112. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/ui-map.md +3 -2
  113. package/runtime/gatewaysdk/environment/schema/slack.py +55 -10
  114. package/runtime/gatewaysdk/environment/schema/snapshot.py +28 -2
  115. package/runtime/gatewaysdk/environment/schema/tasks.py +25 -2
  116. package/runtime/gatewaysdk/environment/schema/template_record.py +131 -0
  117. package/runtime/gatewaysdk/environment/schema/tools_world.py +7 -5
  118. package/runtime/gatewaysdk/environment/schema/ui.py +54 -33
  119. package/runtime/gatewaysdk/environment/schema/ui_interactions.py +419 -0
  120. package/runtime/gatewaysdk/environment/schema/ui_recorder.js +895 -0
  121. package/runtime/gatewaysdk/environment/schema/ui_replay.py +366 -0
  122. package/runtime/gatewaysdk/environment/schema/ui_replay_record.LICENSE +25 -0
  123. package/runtime/gatewaysdk/environment/schema/ui_replay_record.js +109 -0
  124. package/runtime/gatewaysdk/environment/schema/validation.py +24 -1
  125. package/runtime/gatewaysdk/environment/schema/worker.py +12 -5
  126. package/runtime/gatewaysdk/environment/schema/worker_key.py +38 -0
  127. package/runtime/gatewaysdk/environment/schema/worker_peaks.py +38 -0
  128. package/runtime/gatewaysdk/environment/schema/worker_watch.py +50 -0
  129. package/runtime/gatewaysdk/environment/schema/workers.py +245 -69
  130. package/runtime/gatewaysdk/environment/schema/world_host.py +96 -73
  131. package/runtime/gatewaysdk/environment/schema/world_tests.py +3 -1
  132. package/runtime/gatewaysdk/environment/secret_values.py +1 -1
  133. package/runtime/gatewaysdk/environment/world.py +34 -43
  134. package/runtime/gatewaysdk/environment/world_session_contract.py +7 -34
  135. package/skills/benchmarks-getting-started/SKILL.md +1 -1
  136. package/skills/connector-schema-authoring/SKILL.md +2 -2
  137. package/skills/connector-schema-authoring/connector-worlds.md +3 -2
  138. package/skills/connector-schema-authoring/world-schema.md +36 -23
  139. package/skills/factory-orchestrator/SKILL.md +147 -0
  140. package/skills/world-data-ingestion/ROWS.md +5 -1
  141. package/skills/world-data-ingestion/SKILL.md +8 -6
  142. package/skills/worlds-getting-started/SKILL.md +9 -9
  143. package/skills/worlds-getting-started/references/cli-mcp-map.md +33 -2
  144. package/skills/worlds-getting-started/references/gotchas.md +6 -6
  145. package/skills/worlds-getting-started/references/journal-checks.md +17 -2
  146. package/skills/worlds-getting-started/references/new-world-sandbox.md +1 -1
  147. package/skills/worlds-getting-started/references/shape-catalog.md +59 -0
  148. package/skills/worlds-getting-started/references/ui-map.md +3 -2
  149. package/dist/media-BIApiPzS.d.mts +0 -102
  150. package/dist/media-BIApiPzS.d.ts +0 -102
@@ -35,13 +35,75 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
35
35
  ));
36
36
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
37
37
 
38
+ // src/worlds/personalToken.ts
39
+ var TOKEN_NOT_PERSONAL, TOKEN_NEEDS_PROJECT, TOKEN_NEEDS_HOST, TOKEN_OTHER_HOST, TOKEN_BESIDE_KEYS, PERSONAL, PROJECT, ENV_KEYS, PersonalTokenRefused, bare, PersonalToken;
40
+ var init_personalToken = __esm({
41
+ "src/worlds/personalToken.ts"() {
42
+ "use strict";
43
+ TOKEN_NOT_PERSONAL = "GATEWAY_TOKEN takes a personal access token: pat_ followed by letters and digits only.";
44
+ TOKEN_NEEDS_PROJECT = "GATEWAY_TOKEN acts in the project GATEWAY_PROJECT_ID names: set it to the official project's id (letters, digits, - and _).";
45
+ TOKEN_NEEDS_HOST = "GATEWAY_TOKEN goes only to the host GATEWAY_HOST names: set GATEWAY_HOST.";
46
+ 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.";
47
+ 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.";
48
+ PERSONAL = /^pat_[A-Za-z0-9]+$/;
49
+ PROJECT = /^[A-Za-z0-9_-]+$/;
50
+ ENV_KEYS = ["GATEWAY_PUBLIC_KEY", "GATEWAY_SECRET_KEY", "GATEWAY_API_KEY"];
51
+ PersonalTokenRefused = class extends Error {
52
+ };
53
+ bare = (host) => host.replace(/\/+$/, "");
54
+ PersonalToken = class _PersonalToken {
55
+ constructor(value, project, host) {
56
+ this.value = value;
57
+ this.project = project;
58
+ this.host = host;
59
+ }
60
+ value;
61
+ project;
62
+ host;
63
+ static fromEnv(env, request = {}) {
64
+ const value = env.GATEWAY_TOKEN;
65
+ if (!value) return null;
66
+ if (request.keys || ENV_KEYS.some((name) => env[name])) throw new PersonalTokenRefused(TOKEN_BESIDE_KEYS);
67
+ const host = bare(env.GATEWAY_HOST ?? "");
68
+ if (!host) throw new PersonalTokenRefused(TOKEN_NEEDS_HOST);
69
+ if (request.host && bare(request.host) !== host) throw new PersonalTokenRefused(TOKEN_OTHER_HOST);
70
+ if (!PERSONAL.test(value)) throw new PersonalTokenRefused(TOKEN_NOT_PERSONAL);
71
+ const project = env.GATEWAY_PROJECT_ID ?? "";
72
+ if (!PROJECT.test(project)) throw new PersonalTokenRefused(TOKEN_NEEDS_PROJECT);
73
+ return new _PersonalToken(value, project, host);
74
+ }
75
+ toJSON() {
76
+ return { project: this.project, host: this.host };
77
+ }
78
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
79
+ return `PersonalToken { project: ${this.project}, host: ${this.host} }`;
80
+ }
81
+ static scrubbed(env) {
82
+ return Object.fromEntries(Object.entries(env).filter(([key]) => key !== "GATEWAY_TOKEN"));
83
+ }
84
+ };
85
+ }
86
+ });
87
+
38
88
  // src/worlds/platformEndpoint.ts
39
89
  function platformEndpoint(options) {
90
+ if (options.token)
91
+ return {
92
+ host: (options.host ?? options.token.host).replace(/\/+$/, ""),
93
+ publicKey: options.publicKey ?? "",
94
+ secretKey: options.secretKey ?? "",
95
+ token: options.token
96
+ };
97
+ const token = PersonalToken.fromEnv(process.env, {
98
+ host: options.host,
99
+ keys: Boolean(options.publicKey || options.secretKey)
100
+ });
101
+ if (token) return { host: token.host, publicKey: "", secretKey: "", token };
102
+ const host = (options.host ?? process.env.GATEWAY_HOST ?? DEFAULT_HOST).replace(/\/+$/, "");
40
103
  const publicKey = options.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;
41
104
  const secretKey = options.secretKey ?? process.env.GATEWAY_SECRET_KEY;
42
105
  if (!publicKey || !secretKey) return null;
43
- const host = options.host ?? process.env.GATEWAY_HOST ?? DEFAULT_HOST;
44
- return { host: host.replace(/\/+$/, ""), publicKey, secretKey };
106
+ return { host, publicKey, secretKey };
45
107
  }
46
108
  function requirePlatformEndpoint(options) {
47
109
  const endpoint = platformEndpoint(options);
@@ -52,11 +114,74 @@ var DEFAULT_HOST, GATEWAY_KEYS_MISSING;
52
114
  var init_platformEndpoint = __esm({
53
115
  "src/worlds/platformEndpoint.ts"() {
54
116
  "use strict";
117
+ init_personalToken();
55
118
  DEFAULT_HOST = "https://withgateway.ai";
56
119
  GATEWAY_KEYS_MISSING = "Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY (or pass publicKey/secretKey).";
57
120
  }
58
121
  });
59
122
 
123
+ // src/worlds/apiError.ts
124
+ function edgeAnswer(text, status) {
125
+ if (status !== void 0 && status >= 500) return EDGE_ANSWERS[status] ?? EDGE_FAILURE;
126
+ return /^\s*</.test(text) ? EDGE_PAGE : null;
127
+ }
128
+ function parseErrorBody(text, status) {
129
+ const raw = { detail: text.slice(0, DETAIL_LIMIT), code: null };
130
+ let parsed;
131
+ try {
132
+ parsed = JSON.parse(text);
133
+ } catch {
134
+ return { detail: (edgeAnswer(text, status) ?? text).slice(0, DETAIL_LIMIT), code: null };
135
+ }
136
+ if (parsed === null || typeof parsed !== "object") return raw;
137
+ const { message, code, error } = parsed;
138
+ const stableCode = typeof code === "string" ? code : null;
139
+ if (typeof message !== "string") return { ...raw, code: stableCode };
140
+ const fields = invalidFields(error);
141
+ const said = fields ? `${message}: ${fields}` : message;
142
+ if (stableCode === null) return { detail: said.slice(0, DETAIL_LIMIT), code: null };
143
+ return {
144
+ detail: `${said} (${stableCode})`.slice(0, DETAIL_LIMIT),
145
+ code: stableCode
146
+ };
147
+ }
148
+ function invalidFields(error) {
149
+ const issues = Array.isArray(error) ? error : [];
150
+ return issues.filter(
151
+ (issue) => issue !== null && typeof issue === "object" && typeof issue.message === "string"
152
+ ).map((issue) => {
153
+ const path8 = Array.isArray(issue.path) ? issue.path.map(String).join(".") : "";
154
+ return path8 ? `${path8}: ${issue.message}` : issue.message;
155
+ }).join("; ");
156
+ }
157
+ var ApiError, DETAIL_LIMIT, EDGE_ANSWERS, EDGE_FAILURE, EDGE_PAGE;
158
+ var init_apiError = __esm({
159
+ "src/worlds/apiError.ts"() {
160
+ "use strict";
161
+ ApiError = class extends Error {
162
+ constructor(status, method, path8, text) {
163
+ const parsed = parseErrorBody(text, status);
164
+ super(`${method} ${path8} -> ${status}: ${parsed.detail}`);
165
+ this.status = status;
166
+ this.text = text;
167
+ this.name = "ApiError";
168
+ this.code = parsed.code;
169
+ }
170
+ status;
171
+ text;
172
+ code;
173
+ };
174
+ DETAIL_LIMIT = 600;
175
+ EDGE_ANSWERS = {
176
+ 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.",
177
+ 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.",
178
+ 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."
179
+ };
180
+ 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.";
181
+ 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.";
182
+ }
183
+ });
184
+
60
185
  // src/worlds/transport.ts
61
186
  function platformTimeoutMs(env = process.env) {
62
187
  const raw = env[PLATFORM_TIMEOUT_ENV];
@@ -65,10 +190,20 @@ function platformTimeoutMs(env = process.env) {
65
190
  if (Number.isInteger(value) && value > 0) return value;
66
191
  throw new Error(`${PLATFORM_TIMEOUT_ENV} must be a positive whole number of milliseconds, not \`${raw}\`.`);
67
192
  }
68
- var PLATFORM_TIMEOUT_ENV, PLATFORM_TIMEOUT_DEFAULT_MS, CHECK_HOST, RETRY, FETCH_LIMIT, CAUSES, UNKNOWN_CAUSE, TransportCause, UnreachableError, sleep, RetryPolicy, Attempt, PlatformTransport;
193
+ function platformAuthorization(endpoint, url) {
194
+ const { token } = endpoint;
195
+ if (!token)
196
+ return { authorization: "Basic " + Buffer.from(`${endpoint.publicKey}:${endpoint.secretKey}`).toString("base64") };
197
+ if (endpoint.publicKey || endpoint.secretKey) throw new PersonalTokenRefused(TOKEN_BESIDE_KEYS);
198
+ if (!url.startsWith(`${token.host}/`)) throw new PersonalTokenRefused(TOKEN_OTHER_HOST);
199
+ return { authorization: `Bearer ${token.value}`, "x-gateway-project": token.project };
200
+ }
201
+ var PLATFORM_TIMEOUT_ENV, PLATFORM_TIMEOUT_DEFAULT_MS, CHECK_HOST, RETRY, FETCH_LIMIT, CAUSES, UNKNOWN_CAUSE, TransportCause, UnreachableError, sleep, RetryPolicy, Attempt, PLATFORM_STREAM_IDLE_MS, REFUSAL_TEXT_LIMIT, KEYED_REDIRECTS, PlatformTransport, StreamWatch, PlatformStream;
69
202
  var init_transport = __esm({
70
203
  "src/worlds/transport.ts"() {
71
204
  "use strict";
205
+ init_apiError();
206
+ init_personalToken();
72
207
  PLATFORM_TIMEOUT_ENV = "GATEWAY_TIMEOUT_MS";
73
208
  PLATFORM_TIMEOUT_DEFAULT_MS = 12e4;
74
209
  CHECK_HOST = "Check GATEWAY_HOST (or --host) points at a running platform, then retry.";
@@ -108,6 +243,13 @@ var init_transport = __esm({
108
243
  `Retry; if the platform is slow, raise ${PLATFORM_TIMEOUT_ENV} (milliseconds per request).`
109
244
  );
110
245
  }
246
+ static idle(idleMs) {
247
+ return new _TransportCause(
248
+ `no data for ${idleMs / 1e3}s`,
249
+ null,
250
+ "The stream resumes from its last event; if it repeats, check the network between here and the platform."
251
+ );
252
+ }
111
253
  static of(error) {
112
254
  const cause = error instanceof Error && error.cause instanceof Error ? error.cause : void 0;
113
255
  const code = cause && "code" in cause && typeof cause.code === "string" ? cause.code : null;
@@ -183,45 +325,215 @@ var init_transport = __esm({
183
325
  throw this.error;
184
326
  }
185
327
  };
328
+ PLATFORM_STREAM_IDLE_MS = 6e4;
329
+ REFUSAL_TEXT_LIMIT = 64 * 1024;
330
+ KEYED_REDIRECTS = "manual";
186
331
  PlatformTransport = class {
332
+ #endpoint;
333
+ #timeoutMs;
187
334
  constructor(endpoint, timeoutMs = platformTimeoutMs()) {
188
- this.endpoint = endpoint;
189
- this.timeoutMs = timeoutMs;
335
+ this.#endpoint = endpoint;
336
+ this.#timeoutMs = timeoutMs;
190
337
  }
191
- endpoint;
192
- timeoutMs;
193
338
  /** A request that legitimately takes longer (a sandbox exec, a world create) waits its own budget; every other one waits the default. */
194
339
  budget(ownMs) {
195
- return Math.max(ownMs ?? 0, this.timeoutMs);
340
+ return Math.max(ownMs ?? 0, this.#timeoutMs);
196
341
  }
342
+ /** One request; the caller's `signal` aborts it in flight and throws the signal's reason, never an `UnreachableError`. */
197
343
  async send(method, route, body, opts = {}) {
198
344
  const timeoutMs = this.budget(opts.timeoutMs);
199
- return (opts.retry ?? RetryPolicy.NONE).run(() => this.once(method, route, body, timeoutMs));
345
+ return (opts.retry ?? RetryPolicy.NONE).run(() => this.once(method, route, body, timeoutMs, opts.signal));
346
+ }
347
+ /** `send`, then the 2xx body as JSON; any other answer throws `ApiError` with its status and stable `code`. */
348
+ async json(method, route, body, opts = {}) {
349
+ const reply = await this.send(method, route, body, opts);
350
+ if (!reply.ok) throw new ApiError(reply.status, method, route, reply.text);
351
+ return JSON.parse(reply.text);
352
+ }
353
+ /** 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. */
354
+ async stream(route, opts = {}) {
355
+ const watch = new StreamWatch(opts.signal, opts.idleMs ?? PLATFORM_STREAM_IDLE_MS, this.#endpoint.host, route);
356
+ const headers = this.headers(route, "text/event-stream", opts.after ? { "last-event-id": opts.after } : {});
357
+ try {
358
+ const response = await watch.within(
359
+ () => fetch(this.url(route), { method: "GET", headers, signal: watch.signal, redirect: KEYED_REDIRECTS })
360
+ );
361
+ return new PlatformStream(response, watch);
362
+ } catch (error) {
363
+ watch.close();
364
+ throw error;
365
+ }
366
+ }
367
+ url(route) {
368
+ return `${this.#endpoint.host}${route}`;
200
369
  }
201
- async once(method, route, body, timeoutMs) {
370
+ headers(route, accept, extra = {}) {
371
+ return {
372
+ "content-type": "application/json",
373
+ accept,
374
+ ...platformAuthorization(this.#endpoint, this.url(route)),
375
+ ...extra
376
+ };
377
+ }
378
+ async once(method, route, body, timeoutMs, caller) {
379
+ if (caller?.aborted) throw caller.reason;
202
380
  const payload = body === void 0 ? {} : { body: JSON.stringify(body) };
381
+ const headers = this.headers(route, "application/json");
203
382
  const controller = new AbortController();
204
383
  const timer = setTimeout(() => controller.abort(), timeoutMs);
384
+ const relay = () => controller.abort(caller?.reason);
385
+ caller?.addEventListener("abort", relay, { once: true });
205
386
  try {
206
- const res = await fetch(`${this.endpoint.host}${route}`, {
387
+ const res = await fetch(this.url(route), {
207
388
  method,
208
- headers: {
209
- "content-type": "application/json",
210
- accept: "application/json",
211
- authorization: "Basic " + Buffer.from(`${this.endpoint.publicKey}:${this.endpoint.secretKey}`).toString("base64")
212
- },
389
+ headers,
213
390
  ...payload,
214
- signal: controller.signal
391
+ signal: controller.signal,
392
+ redirect: KEYED_REDIRECTS
215
393
  });
216
394
  return { status: res.status, ok: res.ok, text: await res.text() };
217
395
  } catch (error) {
396
+ if (caller?.aborted) throw caller.reason;
218
397
  const cause = controller.signal.aborted ? TransportCause.timeout(timeoutMs) : TransportCause.of(error);
219
- throw new UnreachableError(this.endpoint.host, method, route, cause);
398
+ throw new UnreachableError(this.#endpoint.host, method, route, cause);
220
399
  } finally {
221
400
  clearTimeout(timer);
401
+ caller?.removeEventListener("abort", relay);
222
402
  }
223
403
  }
224
404
  };
405
+ StreamWatch = class {
406
+ constructor(caller, idleMs, host, route) {
407
+ this.idleMs = idleMs;
408
+ this.host = host;
409
+ this.route = route;
410
+ this.#caller = caller;
411
+ caller?.addEventListener("abort", this.#relay, { once: true });
412
+ if (caller?.aborted) this.#relay();
413
+ }
414
+ idleMs;
415
+ host;
416
+ route;
417
+ #controller = new AbortController();
418
+ #caller;
419
+ #relay = () => this.#controller.abort(this.#caller?.reason);
420
+ #idled = false;
421
+ get signal() {
422
+ return this.#controller.signal;
423
+ }
424
+ async within(wait) {
425
+ const timer = setTimeout(() => this.idle(), this.idleMs);
426
+ try {
427
+ return await wait();
428
+ } catch (error) {
429
+ throw this.failure(error);
430
+ } finally {
431
+ clearTimeout(timer);
432
+ }
433
+ }
434
+ close() {
435
+ this.#caller?.removeEventListener("abort", this.#relay);
436
+ this.#controller.abort();
437
+ }
438
+ idle() {
439
+ this.#idled = true;
440
+ this.#controller.abort();
441
+ }
442
+ failure(error) {
443
+ if (this.#caller?.aborted) return this.#caller.reason;
444
+ const cause = this.#idled ? TransportCause.idle(this.idleMs) : TransportCause.of(error);
445
+ return new UnreachableError(this.host, "GET", this.route, cause);
446
+ }
447
+ };
448
+ PlatformStream = class {
449
+ #response;
450
+ #watch;
451
+ constructor(response, watch) {
452
+ this.#response = response;
453
+ this.#watch = watch;
454
+ }
455
+ get status() {
456
+ return this.#response.status;
457
+ }
458
+ get ok() {
459
+ return this.#response.ok;
460
+ }
461
+ /** The body as text, for a refusal: at most the first 64 KiB of characters; closes the stream. */
462
+ async text() {
463
+ const decoder = new TextDecoder();
464
+ let text = "";
465
+ for await (const chunk of this.chunks()) {
466
+ text += decoder.decode(chunk, { stream: true });
467
+ if (text.length >= REFUSAL_TEXT_LIMIT) return text.slice(0, REFUSAL_TEXT_LIMIT);
468
+ }
469
+ return text + decoder.decode();
470
+ }
471
+ /** The body's bytes as they arrive; the idle budget runs only while waiting for the platform, never while the caller holds a chunk. */
472
+ async *chunks() {
473
+ const reader = this.#response.body?.getReader();
474
+ try {
475
+ for (; ; ) {
476
+ const next = reader ? await this.#watch.within(() => reader.read()) : { done: true };
477
+ if (next.done) return;
478
+ yield next.value;
479
+ }
480
+ } finally {
481
+ this.close();
482
+ }
483
+ }
484
+ close() {
485
+ this.#watch.close();
486
+ }
487
+ };
488
+ }
489
+ });
490
+
491
+ // src/worlds/credentialField.ts
492
+ function isCredentialField(described) {
493
+ const words = described.replace(SPACES, " ").replace(/^ | $/g, "");
494
+ return SECRET_FIELD.some((prefix) => words.startsWith(prefix)) || SECRET_KEY.test(words);
495
+ }
496
+ function redactActionArgs(action, args) {
497
+ const secretField = action === "browser_type" && SECRET_KEY.test(String(args.selector ?? ""));
498
+ return Object.fromEntries(
499
+ Object.entries(args).map(([key, value]) => [
500
+ key,
501
+ redactedArg(key, value, secretField)
502
+ ])
503
+ );
504
+ }
505
+ function redactedArg(key, value, secretField) {
506
+ if (value === null || value === void 0) return null;
507
+ if (typeof value === "boolean" || typeof value === "number") return value;
508
+ if (typeof value !== "string") return "[omitted]";
509
+ if (SECRET_KEY.test(key) || SECRET_VALUE.test(value) || secretField && key === "text")
510
+ return "[redacted]";
511
+ return value.length <= EVENT_MAX_STRING ? value : value.slice(0, EVENT_MAX_STRING) + "\u2026";
512
+ }
513
+ var SECRET_KEY, DESCRIBE_FIELD_JS, FIELD_VALUE_JS, SPACES, describeField, readFieldValue, readEditables, UNREADABLE, SECRET_FIELD, EVENT_MAX_STRING, SECRET_VALUE;
514
+ var init_credentialField = __esm({
515
+ "src/worlds/credentialField.ts"() {
516
+ "use strict";
517
+ SECRET_KEY = /pass(word|wd|code|phrase)|pass(?![a-z])|secret|token(?!s)|(api|private)[-_ ]?key|authorization|cookie|one[-_ ]?time[-_ ]?(code|password)|(verification|security|recovery|backup)[-_ ]?codes?|security[-_ ]?answers?|social[-_ ]?security|(card|account|routing)[-_ ]?(number|no\b)|cc-(number|csc|exp)|(^|[-_ #.\["'=(])(otp|totp|mfa|2fa|pin|cvv|cvc|ssn|iban)([-_ \]"'):.,*]|$)/i;
518
+ DESCRIBE_FIELD_JS = "(e) => { if (!e) return ''; if (e.tagName === 'IFRAME' || e.tagName === 'FRAME') return 'frame'; const root = e.getRootNode(); const byIds = (at) => (at.getAttribute('aria-labelledby') || '').split(/\\s+/).map((id) => (id && root.getElementById ? root.getElementById(id) : null)).map((label) => (label ? label.textContent : '')).join(' '); const labels = e.labels ? [...e.labels].map((label) => label.textContent) : []; const context = []; for (let at = e.parentElement; at; at = at.parentElement) { const legend = at.tagName === 'FIELDSET' ? at.querySelector('legend') : null; context.push(at.getAttribute('aria-label'), byIds(at), legend ? legend.textContent : ''); } const names = [e.getAttribute('aria-label'), byIds(e), ...labels, e.getAttribute('placeholder'), e.getAttribute('title'), ...context]; if (e.tagName === 'SELECT') return ['select', e.name, e.id, ...names].filter(Boolean).join(' '); if (!(e.tagName === 'INPUT' || e.tagName === 'TEXTAREA' || e.isContentEditable)) return 'opaque'; return [e.type, e.name, e.id, e.getAttribute('autocomplete'), ...names].filter(Boolean).join(' '); }";
519
+ FIELD_VALUE_JS = "(e) => { if (e.tagName === 'SELECT') return [...e.selectedOptions].map((o) => o.text).join('\\n'); if (e.tagName === 'INPUT' || e.tagName === 'TEXTAREA') return e.value; return e.isContentEditable ? e.innerText : null; }";
520
+ SPACES = /[ \t\n\r\f\v]+/g;
521
+ describeField = new Function(
522
+ "e",
523
+ `return (${DESCRIBE_FIELD_JS})(e);`
524
+ );
525
+ readFieldValue = new Function(
526
+ "e",
527
+ `return (${FIELD_VALUE_JS})(e);`
528
+ );
529
+ readEditables = new Function(
530
+ "elements",
531
+ `return elements.map((e) => [(${DESCRIBE_FIELD_JS})(e), (${FIELD_VALUE_JS})(e)]);`
532
+ );
533
+ UNREADABLE = "unreadable";
534
+ SECRET_FIELD = ["password", "frame", "opaque", UNREADABLE];
535
+ EVENT_MAX_STRING = 500;
536
+ SECRET_VALUE = /^((sk|pk|ghp|xox[abp])[-_][-_A-Za-z0-9]{8,}|AKIA[0-9A-Z]{12,}|Bearer [-_.A-Za-z0-9]{8,})/;
225
537
  }
226
538
  });
227
539
 
@@ -233,31 +545,28 @@ var init_browserReconnect = __esm({
233
545
  });
234
546
 
235
547
  // src/worlds/browser.ts
236
- function redactActionArgs(action, args) {
237
- const secretField = action === "browser_type" && SECRET_KEY.test(String(args.selector ?? ""));
238
- const out = {};
239
- for (const [key, value] of Object.entries(args)) {
240
- if (value === null || value === void 0) out[key] = null;
241
- else if (typeof value === "boolean" || typeof value === "number")
242
- out[key] = value;
243
- else if (typeof value === "string") {
244
- if (SECRET_KEY.test(key) || SECRET_VALUE.test(value) || secretField && key === "text")
245
- out[key] = "[redacted]";
246
- else
247
- out[key] = value.length <= EVENT_MAX_STRING ? value : value.slice(0, EVENT_MAX_STRING) + "\u2026";
248
- } else out[key] = "[omitted]";
249
- }
250
- return out;
251
- }
252
- var EVENT_MAX_STRING, SECRET_KEY, SECRET_VALUE;
253
548
  var init_browser = __esm({
254
549
  "src/worlds/browser.ts"() {
255
550
  "use strict";
256
- init_session2();
551
+ init_credentialField();
257
552
  init_browserReconnect();
258
- EVENT_MAX_STRING = 500;
259
- SECRET_KEY = /pass(word|wd)?|secret|token|api[-_]?key|authorization|cookie|(^|[-_ #.\["'=])(otp|pin|cvv|ssn)([-_ \]"']|$)/i;
260
- SECRET_VALUE = /^((sk|pk|ghp|xox[abp])[-_][-_A-Za-z0-9]{8,}|AKIA[0-9A-Z]{12,}|Bearer [-_.A-Za-z0-9]{8,})/;
553
+ }
554
+ });
555
+
556
+ // src/worlds/pageState.ts
557
+ var init_pageState = __esm({
558
+ "src/worlds/pageState.ts"() {
559
+ "use strict";
560
+ init_credentialField();
561
+ }
562
+ });
563
+
564
+ // src/worlds/browserTools.ts
565
+ var init_browserTools = __esm({
566
+ "src/worlds/browserTools.ts"() {
567
+ "use strict";
568
+ init_pageState();
569
+ init_session2();
261
570
  }
262
571
  });
263
572
 
@@ -401,13 +710,12 @@ function isNativePage(page) {
401
710
  const mouse = candidate?.mouse;
402
711
  return typeof candidate?.context === "function" && NATIVE_METHODS.every((m) => typeof mouse?.[m] === "function");
403
712
  }
404
- var FOCUSED_FIELD_JS, SECRET_FOCUS, DRAG_STEPS, PNG_SIGNATURE, NATIVE_METHODS, Screen;
713
+ var FOCUSED_FIELD_JS, DRAG_STEPS, PNG_SIGNATURE, NATIVE_METHODS, Screen;
405
714
  var init_screen = __esm({
406
715
  "src/worlds/nativeComputer/screen.ts"() {
407
716
  "use strict";
408
- init_browser();
409
- FOCUSED_FIELD_JS = "(() => { let e = document.activeElement; const inner = (el) => (el.shadowRoot && el.shadowRoot.activeElement) || (el.contentDocument && el.contentDocument.activeElement); while (e && inner(e)) e = inner(e); if (!e) return ''; if (e.tagName === 'IFRAME' || e.tagName === 'FRAME') return 'frame'; if (!(e.tagName === 'INPUT' || e.tagName === 'TEXTAREA' || e.isContentEditable)) return 'opaque'; return [e.type, e.name, e.id, e.getAttribute('autocomplete')].filter(Boolean).join(' '); })()";
410
- SECRET_FOCUS = ["password", "frame", "opaque"];
717
+ init_credentialField();
718
+ FOCUSED_FIELD_JS = `(() => { let e = document.activeElement; const inner = (el) => (el.shadowRoot && el.shadowRoot.activeElement) || (el.contentDocument && el.contentDocument.activeElement); while (e && inner(e)) e = inner(e); return (${DESCRIBE_FIELD_JS})(e); })()`;
411
719
  DRAG_STEPS = 5;
412
720
  PNG_SIGNATURE = Buffer.from([
413
721
  137,
@@ -498,7 +806,7 @@ var init_screen = __esm({
498
806
  } catch {
499
807
  return true;
500
808
  }
501
- return SECRET_FOCUS.some((prefix) => described.startsWith(prefix)) || SECRET_KEY.test(described);
809
+ return isCredentialField(described);
502
810
  }
503
811
  /** CDP renders a clip at the page's device pixel ratio as well as its
504
812
  * `scale` (a Retina host doubles it), so a capture of the wrong width
@@ -1628,6 +1936,7 @@ var init_session2 = __esm({
1628
1936
  import_node_crypto2 = require("crypto");
1629
1937
  init_worlds();
1630
1938
  init_browser();
1939
+ init_browserTools();
1631
1940
  init_nativeComputer();
1632
1941
  init_sessionContract();
1633
1942
  init_toolSchema();
@@ -1693,6 +2002,8 @@ var init_evals = __esm({
1693
2002
  "src/worlds/evals.ts"() {
1694
2003
  "use strict";
1695
2004
  init_worlds();
2005
+ init_personalToken();
2006
+ init_platformEndpoint();
1696
2007
  init_transport();
1697
2008
  }
1698
2009
  });
@@ -1748,6 +2059,7 @@ var init_taskTracing = __esm({
1748
2059
  "use strict";
1749
2060
  init_prerequisites();
1750
2061
  init_platformEndpoint();
2062
+ init_personalToken();
1751
2063
  }
1752
2064
  });
1753
2065
 
@@ -1785,6 +2097,7 @@ var init_setRun = __esm({
1785
2097
  "use strict";
1786
2098
  init_worlds();
1787
2099
  init_checkoutProvenance();
2100
+ init_evals();
1788
2101
  init_runSignals();
1789
2102
  init_taskRun();
1790
2103
  }
@@ -1972,6 +2285,7 @@ var init_ingest = __esm({
1972
2285
  path7 = __toESM(require("path"));
1973
2286
  init_worlds();
1974
2287
  init_platformEndpoint();
2288
+ init_personalToken();
1975
2289
  }
1976
2290
  });
1977
2291
 
@@ -1983,6 +2297,14 @@ var init_editSessions = __esm({
1983
2297
  }
1984
2298
  });
1985
2299
 
2300
+ // src/worlds/states.ts
2301
+ var init_states = __esm({
2302
+ "src/worlds/states.ts"() {
2303
+ "use strict";
2304
+ init_worlds();
2305
+ }
2306
+ });
2307
+
1986
2308
  // src/worlds/dryRun.ts
1987
2309
  var init_dryRun = __esm({
1988
2310
  "src/worlds/dryRun.ts"() {
@@ -1992,50 +2314,15 @@ var init_dryRun = __esm({
1992
2314
  });
1993
2315
 
1994
2316
  // src/worlds/index.ts
1995
- function edgeAnswer(text, status) {
1996
- if (status !== void 0 && status >= 500) return EDGE_ANSWERS[status] ?? EDGE_FAILURE;
1997
- return /^\s*</.test(text) ? EDGE_PAGE : null;
1998
- }
1999
- function parseErrorBody(text, status) {
2000
- const raw = { detail: text.slice(0, DETAIL_LIMIT), code: null };
2001
- let parsed;
2002
- try {
2003
- parsed = JSON.parse(text);
2004
- } catch {
2005
- return { detail: (edgeAnswer(text, status) ?? text).slice(0, DETAIL_LIMIT), code: null };
2006
- }
2007
- if (parsed === null || typeof parsed !== "object") return raw;
2008
- const { message, code, error } = parsed;
2009
- const stableCode = typeof code === "string" ? code : null;
2010
- if (typeof message !== "string") return { ...raw, code: stableCode };
2011
- const fields = invalidFields(error);
2012
- const said = fields ? `${message}: ${fields}` : message;
2013
- if (stableCode === null) return { detail: said.slice(0, DETAIL_LIMIT), code: null };
2014
- return {
2015
- detail: `${said} (${stableCode})`.slice(0, DETAIL_LIMIT),
2016
- code: stableCode
2017
- };
2018
- }
2019
- function invalidFields(error) {
2020
- const issues = Array.isArray(error) ? error : [];
2021
- return issues.filter(
2022
- (issue) => issue !== null && typeof issue === "object" && typeof issue.message === "string"
2023
- ).map((issue) => {
2024
- const path8 = Array.isArray(issue.path) ? issue.path.map(String).join(".") : "";
2025
- return path8 ? `${path8}: ${issue.message}` : issue.message;
2026
- }).join("; ");
2027
- }
2028
2317
  async function apiRequest(options, method, path8, body, init = {}) {
2029
- const reply = await new PlatformTransport(requirePlatformEndpoint(options)).send(method, path8, body, init);
2030
- if (!reply.ok) throw new ApiError(reply.status, method, path8, reply.text);
2031
- return JSON.parse(reply.text);
2318
+ return new PlatformTransport(requirePlatformEndpoint(options)).json(method, path8, body, init);
2032
2319
  }
2033
- var ApiError, DETAIL_LIMIT, EDGE_ANSWERS, EDGE_FAILURE, EDGE_PAGE;
2034
2320
  var init_worlds = __esm({
2035
2321
  "src/worlds/index.ts"() {
2036
2322
  "use strict";
2037
2323
  init_platformEndpoint();
2038
2324
  init_transport();
2325
+ init_apiError();
2039
2326
  init_transport();
2040
2327
  init_session2();
2041
2328
  init_grade();
@@ -2050,6 +2337,8 @@ var init_worlds = __esm({
2050
2337
  init_checkoutProvenance();
2051
2338
  init_evals();
2052
2339
  init_browser();
2340
+ init_browserTools();
2341
+ init_pageState();
2053
2342
  init_surfaceDescriptor();
2054
2343
  init_requestLog();
2055
2344
  init_requestLedger();
@@ -2066,29 +2355,9 @@ var init_worlds = __esm({
2066
2355
  init_ingest();
2067
2356
  init_sandbox();
2068
2357
  init_editSessions();
2358
+ init_states();
2069
2359
  init_dryRun();
2070
2360
  init_worldNotice();
2071
- ApiError = class extends Error {
2072
- constructor(status, method, path8, text) {
2073
- const parsed = parseErrorBody(text, status);
2074
- super(`${method} ${path8} -> ${status}: ${parsed.detail}`);
2075
- this.status = status;
2076
- this.text = text;
2077
- this.name = "ApiError";
2078
- this.code = parsed.code;
2079
- }
2080
- status;
2081
- text;
2082
- code;
2083
- };
2084
- DETAIL_LIMIT = 600;
2085
- EDGE_ANSWERS = {
2086
- 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.",
2087
- 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.",
2088
- 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."
2089
- };
2090
- 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.";
2091
- 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.";
2092
2361
  }
2093
2362
  });
2094
2363