@withgateway/sdk 0.6.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 (119) 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 +5019 -1599
  10. package/dist/cli.js.map +1 -1
  11. package/dist/cli.mjs +5003 -1584
  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 +2689 -401
  28. package/dist/index.js.map +1 -1
  29. package/dist/index.mjs +2650 -394
  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 +1983 -1745
  48. package/dist/worlds/index.d.ts +1983 -1745
  49. package/dist/worlds/index.js +1295 -226
  50. package/dist/worlds/index.js.map +1 -1
  51. package/dist/worlds/index.mjs +1290 -222
  52. package/dist/worlds/index.mjs.map +1 -1
  53. package/package.json +6 -1
  54. package/runtime/gatewaysdk/environment/bundle_manifest.py +243 -0
  55. package/runtime/gatewaysdk/environment/schema/__main__.py +2 -2
  56. package/runtime/gatewaysdk/environment/schema/_slack_fidelity.py +8 -23
  57. package/runtime/gatewaysdk/environment/schema/api.py +3 -4
  58. package/runtime/gatewaysdk/environment/schema/assertions.py +7 -1
  59. package/runtime/gatewaysdk/environment/schema/bundle_runtime.py +1 -0
  60. package/runtime/gatewaysdk/environment/schema/call_log.py +20 -0
  61. package/runtime/gatewaysdk/environment/schema/database/base.py +2 -2
  62. package/runtime/gatewaysdk/environment/schema/host.py +74 -11
  63. package/runtime/gatewaysdk/environment/schema/host_browser.py +48 -0
  64. package/runtime/gatewaysdk/environment/schema/host_control.py +33 -2
  65. package/runtime/gatewaysdk/environment/schema/host_handoff.py +4 -1
  66. package/runtime/gatewaysdk/environment/schema/host_requests.py +14 -0
  67. package/runtime/gatewaysdk/environment/schema/host_session.py +13 -2
  68. package/runtime/gatewaysdk/environment/schema/host_surfaces.py +6 -0
  69. package/runtime/gatewaysdk/environment/schema/host_versions.py +96 -19
  70. package/runtime/gatewaysdk/environment/schema/journal.py +7 -2
  71. package/runtime/gatewaysdk/environment/schema/local.py +32 -7
  72. package/runtime/gatewaysdk/environment/schema/page_checks.py +123 -0
  73. package/runtime/gatewaysdk/environment/schema/platform.py +23 -267
  74. package/runtime/gatewaysdk/environment/schema/platform_templates.py +332 -0
  75. package/runtime/gatewaysdk/environment/schema/request_ledger.py +4 -1
  76. package/runtime/gatewaysdk/environment/schema/run_parameters.py +25 -0
  77. package/runtime/gatewaysdk/environment/schema/runtime.py +43 -5
  78. package/runtime/gatewaysdk/environment/schema/scaffold.py +367 -217
  79. package/runtime/gatewaysdk/environment/schema/session_files.py +13 -2
  80. package/runtime/gatewaysdk/environment/schema/skills/benchmarks-getting-started/SKILL.md +1 -1
  81. package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/SKILL.md +1 -2
  82. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/SKILL.md +4 -2
  83. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/SKILL.md +7 -7
  84. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/cli-mcp-map.md +32 -2
  85. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/gotchas.md +6 -6
  86. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/journal-checks.md +17 -2
  87. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/new-world-sandbox.md +1 -1
  88. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/ui-map.md +3 -2
  89. package/runtime/gatewaysdk/environment/schema/slack.py +55 -10
  90. package/runtime/gatewaysdk/environment/schema/snapshot.py +28 -2
  91. package/runtime/gatewaysdk/environment/schema/tasks.py +25 -2
  92. package/runtime/gatewaysdk/environment/schema/template_record.py +131 -0
  93. package/runtime/gatewaysdk/environment/schema/tools_world.py +7 -5
  94. package/runtime/gatewaysdk/environment/schema/ui.py +54 -33
  95. package/runtime/gatewaysdk/environment/schema/ui_interactions.py +419 -0
  96. package/runtime/gatewaysdk/environment/schema/ui_recorder.js +895 -0
  97. package/runtime/gatewaysdk/environment/schema/ui_replay.py +366 -0
  98. package/runtime/gatewaysdk/environment/schema/ui_replay_record.LICENSE +25 -0
  99. package/runtime/gatewaysdk/environment/schema/ui_replay_record.js +109 -0
  100. package/runtime/gatewaysdk/environment/schema/validation.py +10 -1
  101. package/runtime/gatewaysdk/environment/schema/worker.py +5 -1
  102. package/runtime/gatewaysdk/environment/schema/workers.py +8 -1
  103. package/runtime/gatewaysdk/environment/schema/world_host.py +44 -15
  104. package/runtime/gatewaysdk/environment/secret_values.py +1 -1
  105. package/runtime/gatewaysdk/environment/world.py +34 -43
  106. package/runtime/gatewaysdk/environment/world_session_contract.py +7 -34
  107. package/skills/benchmarks-getting-started/SKILL.md +1 -1
  108. package/skills/connector-schema-authoring/SKILL.md +1 -2
  109. package/skills/connector-schema-authoring/connector-worlds.md +2 -2
  110. package/skills/connector-schema-authoring/world-schema.md +29 -23
  111. package/skills/world-data-ingestion/SKILL.md +4 -2
  112. package/skills/worlds-getting-started/SKILL.md +7 -7
  113. package/skills/worlds-getting-started/references/cli-mcp-map.md +32 -2
  114. package/skills/worlds-getting-started/references/gotchas.md +6 -6
  115. package/skills/worlds-getting-started/references/journal-checks.md +17 -2
  116. package/skills/worlds-getting-started/references/new-world-sandbox.md +1 -1
  117. package/skills/worlds-getting-started/references/ui-map.md +3 -2
  118. package/dist/media-BIApiPzS.d.mts +0 -102
  119. package/dist/media-BIApiPzS.d.ts +0 -102
@@ -16,13 +16,75 @@ var __esm = (fn, res, err) => function __init() {
16
16
  }
17
17
  };
18
18
 
19
+ // src/worlds/personalToken.ts
20
+ var TOKEN_NOT_PERSONAL, TOKEN_NEEDS_PROJECT, TOKEN_NEEDS_HOST, TOKEN_OTHER_HOST, TOKEN_BESIDE_KEYS, PERSONAL, PROJECT, ENV_KEYS, PersonalTokenRefused, bare, PersonalToken;
21
+ var init_personalToken = __esm({
22
+ "src/worlds/personalToken.ts"() {
23
+ "use strict";
24
+ TOKEN_NOT_PERSONAL = "GATEWAY_TOKEN takes a personal access token: pat_ followed by letters and digits only.";
25
+ TOKEN_NEEDS_PROJECT = "GATEWAY_TOKEN acts in the project GATEWAY_PROJECT_ID names: set it to the official project's id (letters, digits, - and _).";
26
+ TOKEN_NEEDS_HOST = "GATEWAY_TOKEN goes only to the host GATEWAY_HOST names: set GATEWAY_HOST.";
27
+ 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.";
28
+ 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.";
29
+ PERSONAL = /^pat_[A-Za-z0-9]+$/;
30
+ PROJECT = /^[A-Za-z0-9_-]+$/;
31
+ ENV_KEYS = ["GATEWAY_PUBLIC_KEY", "GATEWAY_SECRET_KEY", "GATEWAY_API_KEY"];
32
+ PersonalTokenRefused = class extends Error {
33
+ };
34
+ bare = (host) => host.replace(/\/+$/, "");
35
+ PersonalToken = class _PersonalToken {
36
+ constructor(value, project, host) {
37
+ this.value = value;
38
+ this.project = project;
39
+ this.host = host;
40
+ }
41
+ value;
42
+ project;
43
+ host;
44
+ static fromEnv(env, request = {}) {
45
+ const value = env.GATEWAY_TOKEN;
46
+ if (!value) return null;
47
+ if (request.keys || ENV_KEYS.some((name) => env[name])) throw new PersonalTokenRefused(TOKEN_BESIDE_KEYS);
48
+ const host = bare(env.GATEWAY_HOST ?? "");
49
+ if (!host) throw new PersonalTokenRefused(TOKEN_NEEDS_HOST);
50
+ if (request.host && bare(request.host) !== host) throw new PersonalTokenRefused(TOKEN_OTHER_HOST);
51
+ if (!PERSONAL.test(value)) throw new PersonalTokenRefused(TOKEN_NOT_PERSONAL);
52
+ const project = env.GATEWAY_PROJECT_ID ?? "";
53
+ if (!PROJECT.test(project)) throw new PersonalTokenRefused(TOKEN_NEEDS_PROJECT);
54
+ return new _PersonalToken(value, project, host);
55
+ }
56
+ toJSON() {
57
+ return { project: this.project, host: this.host };
58
+ }
59
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
60
+ return `PersonalToken { project: ${this.project}, host: ${this.host} }`;
61
+ }
62
+ static scrubbed(env) {
63
+ return Object.fromEntries(Object.entries(env).filter(([key]) => key !== "GATEWAY_TOKEN"));
64
+ }
65
+ };
66
+ }
67
+ });
68
+
19
69
  // src/worlds/platformEndpoint.ts
20
70
  function platformEndpoint(options) {
71
+ if (options.token)
72
+ return {
73
+ host: (options.host ?? options.token.host).replace(/\/+$/, ""),
74
+ publicKey: options.publicKey ?? "",
75
+ secretKey: options.secretKey ?? "",
76
+ token: options.token
77
+ };
78
+ const token = PersonalToken.fromEnv(process.env, {
79
+ host: options.host,
80
+ keys: Boolean(options.publicKey || options.secretKey)
81
+ });
82
+ if (token) return { host: token.host, publicKey: "", secretKey: "", token };
83
+ const host = (options.host ?? process.env.GATEWAY_HOST ?? DEFAULT_HOST).replace(/\/+$/, "");
21
84
  const publicKey = options.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;
22
85
  const secretKey = options.secretKey ?? process.env.GATEWAY_SECRET_KEY;
23
86
  if (!publicKey || !secretKey) return null;
24
- const host = options.host ?? process.env.GATEWAY_HOST ?? DEFAULT_HOST;
25
- return { host: host.replace(/\/+$/, ""), publicKey, secretKey };
87
+ return { host, publicKey, secretKey };
26
88
  }
27
89
  function requirePlatformEndpoint(options) {
28
90
  const endpoint = platformEndpoint(options);
@@ -33,11 +95,74 @@ var DEFAULT_HOST, GATEWAY_KEYS_MISSING;
33
95
  var init_platformEndpoint = __esm({
34
96
  "src/worlds/platformEndpoint.ts"() {
35
97
  "use strict";
98
+ init_personalToken();
36
99
  DEFAULT_HOST = "https://withgateway.ai";
37
100
  GATEWAY_KEYS_MISSING = "Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY (or pass publicKey/secretKey).";
38
101
  }
39
102
  });
40
103
 
104
+ // src/worlds/apiError.ts
105
+ function edgeAnswer(text, status) {
106
+ if (status !== void 0 && status >= 500) return EDGE_ANSWERS[status] ?? EDGE_FAILURE;
107
+ return /^\s*</.test(text) ? EDGE_PAGE : null;
108
+ }
109
+ function parseErrorBody(text, status) {
110
+ const raw = { detail: text.slice(0, DETAIL_LIMIT), code: null };
111
+ let parsed;
112
+ try {
113
+ parsed = JSON.parse(text);
114
+ } catch {
115
+ return { detail: (edgeAnswer(text, status) ?? text).slice(0, DETAIL_LIMIT), code: null };
116
+ }
117
+ if (parsed === null || typeof parsed !== "object") return raw;
118
+ const { message, code, error } = parsed;
119
+ const stableCode = typeof code === "string" ? code : null;
120
+ if (typeof message !== "string") return { ...raw, code: stableCode };
121
+ const fields = invalidFields(error);
122
+ const said = fields ? `${message}: ${fields}` : message;
123
+ if (stableCode === null) return { detail: said.slice(0, DETAIL_LIMIT), code: null };
124
+ return {
125
+ detail: `${said} (${stableCode})`.slice(0, DETAIL_LIMIT),
126
+ code: stableCode
127
+ };
128
+ }
129
+ function invalidFields(error) {
130
+ const issues = Array.isArray(error) ? error : [];
131
+ return issues.filter(
132
+ (issue) => issue !== null && typeof issue === "object" && typeof issue.message === "string"
133
+ ).map((issue) => {
134
+ const path9 = Array.isArray(issue.path) ? issue.path.map(String).join(".") : "";
135
+ return path9 ? `${path9}: ${issue.message}` : issue.message;
136
+ }).join("; ");
137
+ }
138
+ var ApiError, DETAIL_LIMIT, EDGE_ANSWERS, EDGE_FAILURE, EDGE_PAGE;
139
+ var init_apiError = __esm({
140
+ "src/worlds/apiError.ts"() {
141
+ "use strict";
142
+ ApiError = class extends Error {
143
+ constructor(status, method, path9, text) {
144
+ const parsed = parseErrorBody(text, status);
145
+ super(`${method} ${path9} -> ${status}: ${parsed.detail}`);
146
+ this.status = status;
147
+ this.text = text;
148
+ this.name = "ApiError";
149
+ this.code = parsed.code;
150
+ }
151
+ status;
152
+ text;
153
+ code;
154
+ };
155
+ DETAIL_LIMIT = 600;
156
+ EDGE_ANSWERS = {
157
+ 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.",
158
+ 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.",
159
+ 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."
160
+ };
161
+ 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.";
162
+ 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.";
163
+ }
164
+ });
165
+
41
166
  // src/worlds/transport.ts
42
167
  function platformTimeoutMs(env = process.env) {
43
168
  const raw = env[PLATFORM_TIMEOUT_ENV];
@@ -46,10 +171,20 @@ function platformTimeoutMs(env = process.env) {
46
171
  if (Number.isInteger(value) && value > 0) return value;
47
172
  throw new Error(`${PLATFORM_TIMEOUT_ENV} must be a positive whole number of milliseconds, not \`${raw}\`.`);
48
173
  }
49
- var PLATFORM_TIMEOUT_ENV, PLATFORM_TIMEOUT_DEFAULT_MS, CHECK_HOST, RETRY, FETCH_LIMIT, CAUSES, UNKNOWN_CAUSE, TransportCause, UnreachableError, sleep, RetryPolicy, Attempt, PlatformTransport;
174
+ function platformAuthorization(endpoint, url) {
175
+ const { token } = endpoint;
176
+ if (!token)
177
+ return { authorization: "Basic " + Buffer.from(`${endpoint.publicKey}:${endpoint.secretKey}`).toString("base64") };
178
+ if (endpoint.publicKey || endpoint.secretKey) throw new PersonalTokenRefused(TOKEN_BESIDE_KEYS);
179
+ if (!url.startsWith(`${token.host}/`)) throw new PersonalTokenRefused(TOKEN_OTHER_HOST);
180
+ return { authorization: `Bearer ${token.value}`, "x-gateway-project": token.project };
181
+ }
182
+ 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;
50
183
  var init_transport = __esm({
51
184
  "src/worlds/transport.ts"() {
52
185
  "use strict";
186
+ init_apiError();
187
+ init_personalToken();
53
188
  PLATFORM_TIMEOUT_ENV = "GATEWAY_TIMEOUT_MS";
54
189
  PLATFORM_TIMEOUT_DEFAULT_MS = 12e4;
55
190
  CHECK_HOST = "Check GATEWAY_HOST (or --host) points at a running platform, then retry.";
@@ -89,6 +224,13 @@ var init_transport = __esm({
89
224
  `Retry; if the platform is slow, raise ${PLATFORM_TIMEOUT_ENV} (milliseconds per request).`
90
225
  );
91
226
  }
227
+ static idle(idleMs) {
228
+ return new _TransportCause(
229
+ `no data for ${idleMs / 1e3}s`,
230
+ null,
231
+ "The stream resumes from its last event; if it repeats, check the network between here and the platform."
232
+ );
233
+ }
92
234
  static of(error) {
93
235
  const cause = error instanceof Error && error.cause instanceof Error ? error.cause : void 0;
94
236
  const code = cause && "code" in cause && typeof cause.code === "string" ? cause.code : null;
@@ -164,45 +306,215 @@ var init_transport = __esm({
164
306
  throw this.error;
165
307
  }
166
308
  };
309
+ PLATFORM_STREAM_IDLE_MS = 6e4;
310
+ REFUSAL_TEXT_LIMIT = 64 * 1024;
311
+ KEYED_REDIRECTS = "manual";
167
312
  PlatformTransport = class {
313
+ #endpoint;
314
+ #timeoutMs;
168
315
  constructor(endpoint, timeoutMs = platformTimeoutMs()) {
169
- this.endpoint = endpoint;
170
- this.timeoutMs = timeoutMs;
316
+ this.#endpoint = endpoint;
317
+ this.#timeoutMs = timeoutMs;
171
318
  }
172
- endpoint;
173
- timeoutMs;
174
319
  /** A request that legitimately takes longer (a sandbox exec, a world create) waits its own budget; every other one waits the default. */
175
320
  budget(ownMs) {
176
- return Math.max(ownMs ?? 0, this.timeoutMs);
321
+ return Math.max(ownMs ?? 0, this.#timeoutMs);
177
322
  }
323
+ /** One request; the caller's `signal` aborts it in flight and throws the signal's reason, never an `UnreachableError`. */
178
324
  async send(method, route, body, opts = {}) {
179
325
  const timeoutMs = this.budget(opts.timeoutMs);
180
- return (opts.retry ?? RetryPolicy.NONE).run(() => this.once(method, route, body, timeoutMs));
326
+ return (opts.retry ?? RetryPolicy.NONE).run(() => this.once(method, route, body, timeoutMs, opts.signal));
327
+ }
328
+ /** `send`, then the 2xx body as JSON; any other answer throws `ApiError` with its status and stable `code`. */
329
+ async json(method, route, body, opts = {}) {
330
+ const reply = await this.send(method, route, body, opts);
331
+ if (!reply.ok) throw new ApiError(reply.status, method, route, reply.text);
332
+ return JSON.parse(reply.text);
333
+ }
334
+ /** 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. */
335
+ async stream(route, opts = {}) {
336
+ const watch = new StreamWatch(opts.signal, opts.idleMs ?? PLATFORM_STREAM_IDLE_MS, this.#endpoint.host, route);
337
+ const headers = this.headers(route, "text/event-stream", opts.after ? { "last-event-id": opts.after } : {});
338
+ try {
339
+ const response = await watch.within(
340
+ () => fetch(this.url(route), { method: "GET", headers, signal: watch.signal, redirect: KEYED_REDIRECTS })
341
+ );
342
+ return new PlatformStream(response, watch);
343
+ } catch (error) {
344
+ watch.close();
345
+ throw error;
346
+ }
347
+ }
348
+ url(route) {
349
+ return `${this.#endpoint.host}${route}`;
181
350
  }
182
- async once(method, route, body, timeoutMs) {
351
+ headers(route, accept, extra = {}) {
352
+ return {
353
+ "content-type": "application/json",
354
+ accept,
355
+ ...platformAuthorization(this.#endpoint, this.url(route)),
356
+ ...extra
357
+ };
358
+ }
359
+ async once(method, route, body, timeoutMs, caller) {
360
+ if (caller?.aborted) throw caller.reason;
183
361
  const payload = body === void 0 ? {} : { body: JSON.stringify(body) };
362
+ const headers = this.headers(route, "application/json");
184
363
  const controller = new AbortController();
185
364
  const timer = setTimeout(() => controller.abort(), timeoutMs);
365
+ const relay = () => controller.abort(caller?.reason);
366
+ caller?.addEventListener("abort", relay, { once: true });
186
367
  try {
187
- const res = await fetch(`${this.endpoint.host}${route}`, {
368
+ const res = await fetch(this.url(route), {
188
369
  method,
189
- headers: {
190
- "content-type": "application/json",
191
- accept: "application/json",
192
- authorization: "Basic " + Buffer.from(`${this.endpoint.publicKey}:${this.endpoint.secretKey}`).toString("base64")
193
- },
370
+ headers,
194
371
  ...payload,
195
- signal: controller.signal
372
+ signal: controller.signal,
373
+ redirect: KEYED_REDIRECTS
196
374
  });
197
375
  return { status: res.status, ok: res.ok, text: await res.text() };
198
376
  } catch (error) {
377
+ if (caller?.aborted) throw caller.reason;
199
378
  const cause = controller.signal.aborted ? TransportCause.timeout(timeoutMs) : TransportCause.of(error);
200
- throw new UnreachableError(this.endpoint.host, method, route, cause);
379
+ throw new UnreachableError(this.#endpoint.host, method, route, cause);
201
380
  } finally {
202
381
  clearTimeout(timer);
382
+ caller?.removeEventListener("abort", relay);
203
383
  }
204
384
  }
205
385
  };
386
+ StreamWatch = class {
387
+ constructor(caller, idleMs, host, route) {
388
+ this.idleMs = idleMs;
389
+ this.host = host;
390
+ this.route = route;
391
+ this.#caller = caller;
392
+ caller?.addEventListener("abort", this.#relay, { once: true });
393
+ if (caller?.aborted) this.#relay();
394
+ }
395
+ idleMs;
396
+ host;
397
+ route;
398
+ #controller = new AbortController();
399
+ #caller;
400
+ #relay = () => this.#controller.abort(this.#caller?.reason);
401
+ #idled = false;
402
+ get signal() {
403
+ return this.#controller.signal;
404
+ }
405
+ async within(wait) {
406
+ const timer = setTimeout(() => this.idle(), this.idleMs);
407
+ try {
408
+ return await wait();
409
+ } catch (error) {
410
+ throw this.failure(error);
411
+ } finally {
412
+ clearTimeout(timer);
413
+ }
414
+ }
415
+ close() {
416
+ this.#caller?.removeEventListener("abort", this.#relay);
417
+ this.#controller.abort();
418
+ }
419
+ idle() {
420
+ this.#idled = true;
421
+ this.#controller.abort();
422
+ }
423
+ failure(error) {
424
+ if (this.#caller?.aborted) return this.#caller.reason;
425
+ const cause = this.#idled ? TransportCause.idle(this.idleMs) : TransportCause.of(error);
426
+ return new UnreachableError(this.host, "GET", this.route, cause);
427
+ }
428
+ };
429
+ PlatformStream = class {
430
+ #response;
431
+ #watch;
432
+ constructor(response, watch) {
433
+ this.#response = response;
434
+ this.#watch = watch;
435
+ }
436
+ get status() {
437
+ return this.#response.status;
438
+ }
439
+ get ok() {
440
+ return this.#response.ok;
441
+ }
442
+ /** The body as text, for a refusal: at most the first 64 KiB of characters; closes the stream. */
443
+ async text() {
444
+ const decoder = new TextDecoder();
445
+ let text = "";
446
+ for await (const chunk of this.chunks()) {
447
+ text += decoder.decode(chunk, { stream: true });
448
+ if (text.length >= REFUSAL_TEXT_LIMIT) return text.slice(0, REFUSAL_TEXT_LIMIT);
449
+ }
450
+ return text + decoder.decode();
451
+ }
452
+ /** The body's bytes as they arrive; the idle budget runs only while waiting for the platform, never while the caller holds a chunk. */
453
+ async *chunks() {
454
+ const reader = this.#response.body?.getReader();
455
+ try {
456
+ for (; ; ) {
457
+ const next = reader ? await this.#watch.within(() => reader.read()) : { done: true };
458
+ if (next.done) return;
459
+ yield next.value;
460
+ }
461
+ } finally {
462
+ this.close();
463
+ }
464
+ }
465
+ close() {
466
+ this.#watch.close();
467
+ }
468
+ };
469
+ }
470
+ });
471
+
472
+ // src/worlds/credentialField.ts
473
+ function isCredentialField(described) {
474
+ const words = described.replace(SPACES, " ").replace(/^ | $/g, "");
475
+ return SECRET_FIELD.some((prefix) => words.startsWith(prefix)) || SECRET_KEY.test(words);
476
+ }
477
+ function redactActionArgs(action, args) {
478
+ const secretField = action === "browser_type" && SECRET_KEY.test(String(args.selector ?? ""));
479
+ return Object.fromEntries(
480
+ Object.entries(args).map(([key, value]) => [
481
+ key,
482
+ redactedArg(key, value, secretField)
483
+ ])
484
+ );
485
+ }
486
+ function redactedArg(key, value, secretField) {
487
+ if (value === null || value === void 0) return null;
488
+ if (typeof value === "boolean" || typeof value === "number") return value;
489
+ if (typeof value !== "string") return "[omitted]";
490
+ if (SECRET_KEY.test(key) || SECRET_VALUE.test(value) || secretField && key === "text")
491
+ return "[redacted]";
492
+ return value.length <= EVENT_MAX_STRING ? value : value.slice(0, EVENT_MAX_STRING) + "\u2026";
493
+ }
494
+ var SECRET_KEY, DESCRIBE_FIELD_JS, FIELD_VALUE_JS, SPACES, describeField, readFieldValue, readEditables, UNREADABLE, SECRET_FIELD, EVENT_MAX_STRING, SECRET_VALUE;
495
+ var init_credentialField = __esm({
496
+ "src/worlds/credentialField.ts"() {
497
+ "use strict";
498
+ 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;
499
+ 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(' '); }";
500
+ 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; }";
501
+ SPACES = /[ \t\n\r\f\v]+/g;
502
+ describeField = new Function(
503
+ "e",
504
+ `return (${DESCRIBE_FIELD_JS})(e);`
505
+ );
506
+ readFieldValue = new Function(
507
+ "e",
508
+ `return (${FIELD_VALUE_JS})(e);`
509
+ );
510
+ readEditables = new Function(
511
+ "elements",
512
+ `return elements.map((e) => [(${DESCRIBE_FIELD_JS})(e), (${FIELD_VALUE_JS})(e)]);`
513
+ );
514
+ UNREADABLE = "unreadable";
515
+ SECRET_FIELD = ["password", "frame", "opaque", UNREADABLE];
516
+ EVENT_MAX_STRING = 500;
517
+ SECRET_VALUE = /^((sk|pk|ghp|xox[abp])[-_][-_A-Za-z0-9]{8,}|AKIA[0-9A-Z]{12,}|Bearer [-_.A-Za-z0-9]{8,})/;
206
518
  }
207
519
  });
208
520
 
@@ -214,31 +526,28 @@ var init_browserReconnect = __esm({
214
526
  });
215
527
 
216
528
  // src/worlds/browser.ts
217
- function redactActionArgs(action, args) {
218
- const secretField = action === "browser_type" && SECRET_KEY.test(String(args.selector ?? ""));
219
- const out = {};
220
- for (const [key, value] of Object.entries(args)) {
221
- if (value === null || value === void 0) out[key] = null;
222
- else if (typeof value === "boolean" || typeof value === "number")
223
- out[key] = value;
224
- else if (typeof value === "string") {
225
- if (SECRET_KEY.test(key) || SECRET_VALUE.test(value) || secretField && key === "text")
226
- out[key] = "[redacted]";
227
- else
228
- out[key] = value.length <= EVENT_MAX_STRING ? value : value.slice(0, EVENT_MAX_STRING) + "\u2026";
229
- } else out[key] = "[omitted]";
230
- }
231
- return out;
232
- }
233
- var EVENT_MAX_STRING, SECRET_KEY, SECRET_VALUE;
234
529
  var init_browser = __esm({
235
530
  "src/worlds/browser.ts"() {
236
531
  "use strict";
237
- init_session2();
532
+ init_credentialField();
238
533
  init_browserReconnect();
239
- EVENT_MAX_STRING = 500;
240
- SECRET_KEY = /pass(word|wd)?|secret|token|api[-_]?key|authorization|cookie|(^|[-_ #.\["'=])(otp|pin|cvv|ssn)([-_ \]"']|$)/i;
241
- SECRET_VALUE = /^((sk|pk|ghp|xox[abp])[-_][-_A-Za-z0-9]{8,}|AKIA[0-9A-Z]{12,}|Bearer [-_.A-Za-z0-9]{8,})/;
534
+ }
535
+ });
536
+
537
+ // src/worlds/pageState.ts
538
+ var init_pageState = __esm({
539
+ "src/worlds/pageState.ts"() {
540
+ "use strict";
541
+ init_credentialField();
542
+ }
543
+ });
544
+
545
+ // src/worlds/browserTools.ts
546
+ var init_browserTools = __esm({
547
+ "src/worlds/browserTools.ts"() {
548
+ "use strict";
549
+ init_pageState();
550
+ init_session2();
242
551
  }
243
552
  });
244
553
 
@@ -382,13 +691,12 @@ function isNativePage(page) {
382
691
  const mouse = candidate?.mouse;
383
692
  return typeof candidate?.context === "function" && NATIVE_METHODS.every((m) => typeof mouse?.[m] === "function");
384
693
  }
385
- var FOCUSED_FIELD_JS, SECRET_FOCUS, DRAG_STEPS, PNG_SIGNATURE, NATIVE_METHODS, Screen;
694
+ var FOCUSED_FIELD_JS, DRAG_STEPS, PNG_SIGNATURE, NATIVE_METHODS, Screen;
386
695
  var init_screen = __esm({
387
696
  "src/worlds/nativeComputer/screen.ts"() {
388
697
  "use strict";
389
- init_browser();
390
- 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(' '); })()";
391
- SECRET_FOCUS = ["password", "frame", "opaque"];
698
+ init_credentialField();
699
+ 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); })()`;
392
700
  DRAG_STEPS = 5;
393
701
  PNG_SIGNATURE = Buffer.from([
394
702
  137,
@@ -479,7 +787,7 @@ var init_screen = __esm({
479
787
  } catch {
480
788
  return true;
481
789
  }
482
- return SECRET_FOCUS.some((prefix) => described.startsWith(prefix)) || SECRET_KEY.test(described);
790
+ return isCredentialField(described);
483
791
  }
484
792
  /** CDP renders a clip at the page's device pixel ratio as well as its
485
793
  * `scale` (a Retina host doubles it), so a capture of the wrong width
@@ -1609,6 +1917,7 @@ var init_session2 = __esm({
1609
1917
  "use strict";
1610
1918
  init_worlds();
1611
1919
  init_browser();
1920
+ init_browserTools();
1612
1921
  init_nativeComputer();
1613
1922
  init_sessionContract();
1614
1923
  init_toolSchema();
@@ -1674,6 +1983,8 @@ var init_evals = __esm({
1674
1983
  "src/worlds/evals.ts"() {
1675
1984
  "use strict";
1676
1985
  init_worlds();
1986
+ init_personalToken();
1987
+ init_platformEndpoint();
1677
1988
  init_transport();
1678
1989
  }
1679
1990
  });
@@ -1727,6 +2038,7 @@ var init_taskTracing = __esm({
1727
2038
  "use strict";
1728
2039
  init_prerequisites();
1729
2040
  init_platformEndpoint();
2041
+ init_personalToken();
1730
2042
  }
1731
2043
  });
1732
2044
 
@@ -1762,6 +2074,7 @@ var init_setRun = __esm({
1762
2074
  "use strict";
1763
2075
  init_worlds();
1764
2076
  init_checkoutProvenance();
2077
+ init_evals();
1765
2078
  init_runSignals();
1766
2079
  init_taskRun();
1767
2080
  }
@@ -1945,6 +2258,7 @@ var init_ingest = __esm({
1945
2258
  "use strict";
1946
2259
  init_worlds();
1947
2260
  init_platformEndpoint();
2261
+ init_personalToken();
1948
2262
  }
1949
2263
  });
1950
2264
 
@@ -1956,6 +2270,14 @@ var init_editSessions = __esm({
1956
2270
  }
1957
2271
  });
1958
2272
 
2273
+ // src/worlds/states.ts
2274
+ var init_states = __esm({
2275
+ "src/worlds/states.ts"() {
2276
+ "use strict";
2277
+ init_worlds();
2278
+ }
2279
+ });
2280
+
1959
2281
  // src/worlds/dryRun.ts
1960
2282
  var init_dryRun = __esm({
1961
2283
  "src/worlds/dryRun.ts"() {
@@ -1965,50 +2287,15 @@ var init_dryRun = __esm({
1965
2287
  });
1966
2288
 
1967
2289
  // src/worlds/index.ts
1968
- function edgeAnswer(text, status) {
1969
- if (status !== void 0 && status >= 500) return EDGE_ANSWERS[status] ?? EDGE_FAILURE;
1970
- return /^\s*</.test(text) ? EDGE_PAGE : null;
1971
- }
1972
- function parseErrorBody(text, status) {
1973
- const raw = { detail: text.slice(0, DETAIL_LIMIT), code: null };
1974
- let parsed;
1975
- try {
1976
- parsed = JSON.parse(text);
1977
- } catch {
1978
- return { detail: (edgeAnswer(text, status) ?? text).slice(0, DETAIL_LIMIT), code: null };
1979
- }
1980
- if (parsed === null || typeof parsed !== "object") return raw;
1981
- const { message, code, error } = parsed;
1982
- const stableCode = typeof code === "string" ? code : null;
1983
- if (typeof message !== "string") return { ...raw, code: stableCode };
1984
- const fields = invalidFields(error);
1985
- const said = fields ? `${message}: ${fields}` : message;
1986
- if (stableCode === null) return { detail: said.slice(0, DETAIL_LIMIT), code: null };
1987
- return {
1988
- detail: `${said} (${stableCode})`.slice(0, DETAIL_LIMIT),
1989
- code: stableCode
1990
- };
1991
- }
1992
- function invalidFields(error) {
1993
- const issues = Array.isArray(error) ? error : [];
1994
- return issues.filter(
1995
- (issue) => issue !== null && typeof issue === "object" && typeof issue.message === "string"
1996
- ).map((issue) => {
1997
- const path9 = Array.isArray(issue.path) ? issue.path.map(String).join(".") : "";
1998
- return path9 ? `${path9}: ${issue.message}` : issue.message;
1999
- }).join("; ");
2000
- }
2001
2290
  async function apiRequest(options, method, path9, body, init = {}) {
2002
- const reply = await new PlatformTransport(requirePlatformEndpoint(options)).send(method, path9, body, init);
2003
- if (!reply.ok) throw new ApiError(reply.status, method, path9, reply.text);
2004
- return JSON.parse(reply.text);
2291
+ return new PlatformTransport(requirePlatformEndpoint(options)).json(method, path9, body, init);
2005
2292
  }
2006
- var ApiError, DETAIL_LIMIT, EDGE_ANSWERS, EDGE_FAILURE, EDGE_PAGE;
2007
2293
  var init_worlds = __esm({
2008
2294
  "src/worlds/index.ts"() {
2009
2295
  "use strict";
2010
2296
  init_platformEndpoint();
2011
2297
  init_transport();
2298
+ init_apiError();
2012
2299
  init_transport();
2013
2300
  init_session2();
2014
2301
  init_grade();
@@ -2023,6 +2310,8 @@ var init_worlds = __esm({
2023
2310
  init_checkoutProvenance();
2024
2311
  init_evals();
2025
2312
  init_browser();
2313
+ init_browserTools();
2314
+ init_pageState();
2026
2315
  init_surfaceDescriptor();
2027
2316
  init_requestLog();
2028
2317
  init_requestLedger();
@@ -2039,29 +2328,9 @@ var init_worlds = __esm({
2039
2328
  init_ingest();
2040
2329
  init_sandbox();
2041
2330
  init_editSessions();
2331
+ init_states();
2042
2332
  init_dryRun();
2043
2333
  init_worldNotice();
2044
- ApiError = class extends Error {
2045
- constructor(status, method, path9, text) {
2046
- const parsed = parseErrorBody(text, status);
2047
- super(`${method} ${path9} -> ${status}: ${parsed.detail}`);
2048
- this.status = status;
2049
- this.text = text;
2050
- this.name = "ApiError";
2051
- this.code = parsed.code;
2052
- }
2053
- status;
2054
- text;
2055
- code;
2056
- };
2057
- DETAIL_LIMIT = 600;
2058
- EDGE_ANSWERS = {
2059
- 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.",
2060
- 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.",
2061
- 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."
2062
- };
2063
- 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.";
2064
- 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.";
2065
2334
  }
2066
2335
  });
2067
2336