@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
@@ -28,13 +28,77 @@ var __export = (target, all) => {
28
28
  __defProp(target, name, { get: all[name], enumerable: true });
29
29
  };
30
30
 
31
+ // src/worlds/personalToken.ts
32
+ var TOKEN_NOT_PERSONAL, TOKEN_NEEDS_PROJECT, TOKEN_NEEDS_HOST, TOKEN_OTHER_HOST, TOKEN_BESIDE_KEYS, TOKEN_FILING, TOKEN_KEYS_ONLY, PERSONAL, PROJECT, ENV_KEYS, PersonalTokenRefused, bare, PersonalToken;
33
+ var init_personalToken = __esm({
34
+ "src/worlds/personalToken.ts"() {
35
+ "use strict";
36
+ TOKEN_NOT_PERSONAL = "GATEWAY_TOKEN takes a personal access token: pat_ followed by letters and digits only.";
37
+ TOKEN_NEEDS_PROJECT = "GATEWAY_TOKEN acts in the project GATEWAY_PROJECT_ID names: set it to the official project's id (letters, digits, - and _).";
38
+ TOKEN_NEEDS_HOST = "GATEWAY_TOKEN goes only to the host GATEWAY_HOST names: set GATEWAY_HOST.";
39
+ 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.";
40
+ 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.";
41
+ TOKEN_FILING = "Filing an evaluation takes your project's key pair, not GATEWAY_TOKEN: unset it (an official world runs once copied into your own project).";
42
+ TOKEN_KEYS_ONLY = "Task-run tracing exports with a project key pair (GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY), not GATEWAY_TOKEN.";
43
+ PERSONAL = /^pat_[A-Za-z0-9]+$/;
44
+ PROJECT = /^[A-Za-z0-9_-]+$/;
45
+ ENV_KEYS = ["GATEWAY_PUBLIC_KEY", "GATEWAY_SECRET_KEY", "GATEWAY_API_KEY"];
46
+ PersonalTokenRefused = class extends Error {
47
+ };
48
+ bare = (host) => host.replace(/\/+$/, "");
49
+ PersonalToken = class _PersonalToken {
50
+ constructor(value, project, host) {
51
+ this.value = value;
52
+ this.project = project;
53
+ this.host = host;
54
+ }
55
+ value;
56
+ project;
57
+ host;
58
+ static fromEnv(env, request = {}) {
59
+ const value = env.GATEWAY_TOKEN;
60
+ if (!value) return null;
61
+ if (request.keys || ENV_KEYS.some((name) => env[name])) throw new PersonalTokenRefused(TOKEN_BESIDE_KEYS);
62
+ const host = bare(env.GATEWAY_HOST ?? "");
63
+ if (!host) throw new PersonalTokenRefused(TOKEN_NEEDS_HOST);
64
+ if (request.host && bare(request.host) !== host) throw new PersonalTokenRefused(TOKEN_OTHER_HOST);
65
+ if (!PERSONAL.test(value)) throw new PersonalTokenRefused(TOKEN_NOT_PERSONAL);
66
+ const project = env.GATEWAY_PROJECT_ID ?? "";
67
+ if (!PROJECT.test(project)) throw new PersonalTokenRefused(TOKEN_NEEDS_PROJECT);
68
+ return new _PersonalToken(value, project, host);
69
+ }
70
+ toJSON() {
71
+ return { project: this.project, host: this.host };
72
+ }
73
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
74
+ return `PersonalToken { project: ${this.project}, host: ${this.host} }`;
75
+ }
76
+ static scrubbed(env) {
77
+ return Object.fromEntries(Object.entries(env).filter(([key]) => key !== "GATEWAY_TOKEN"));
78
+ }
79
+ };
80
+ }
81
+ });
82
+
31
83
  // src/worlds/platformEndpoint.ts
32
84
  function platformEndpoint(options) {
85
+ if (options.token)
86
+ return {
87
+ host: (options.host ?? options.token.host).replace(/\/+$/, ""),
88
+ publicKey: options.publicKey ?? "",
89
+ secretKey: options.secretKey ?? "",
90
+ token: options.token
91
+ };
92
+ const token = PersonalToken.fromEnv(process.env, {
93
+ host: options.host,
94
+ keys: Boolean(options.publicKey || options.secretKey)
95
+ });
96
+ if (token) return { host: token.host, publicKey: "", secretKey: "", token };
97
+ const host = (options.host ?? process.env.GATEWAY_HOST ?? DEFAULT_HOST).replace(/\/+$/, "");
33
98
  const publicKey = options.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;
34
99
  const secretKey = options.secretKey ?? process.env.GATEWAY_SECRET_KEY;
35
100
  if (!publicKey || !secretKey) return null;
36
- const host = options.host ?? process.env.GATEWAY_HOST ?? DEFAULT_HOST;
37
- return { host: host.replace(/\/+$/, ""), publicKey, secretKey };
101
+ return { host, publicKey, secretKey };
38
102
  }
39
103
  function requirePlatformEndpoint(options) {
40
104
  const endpoint = platformEndpoint(options);
@@ -45,11 +109,74 @@ var DEFAULT_HOST, GATEWAY_KEYS_MISSING;
45
109
  var init_platformEndpoint = __esm({
46
110
  "src/worlds/platformEndpoint.ts"() {
47
111
  "use strict";
112
+ init_personalToken();
48
113
  DEFAULT_HOST = "https://withgateway.ai";
49
114
  GATEWAY_KEYS_MISSING = "Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY (or pass publicKey/secretKey).";
50
115
  }
51
116
  });
52
117
 
118
+ // src/worlds/apiError.ts
119
+ function edgeAnswer(text2, status) {
120
+ if (status !== void 0 && status >= 500) return EDGE_ANSWERS[status] ?? EDGE_FAILURE;
121
+ return /^\s*</.test(text2) ? EDGE_PAGE : null;
122
+ }
123
+ function parseErrorBody(text2, status) {
124
+ const raw = { detail: text2.slice(0, DETAIL_LIMIT), code: null };
125
+ let parsed;
126
+ try {
127
+ parsed = JSON.parse(text2);
128
+ } catch {
129
+ return { detail: (edgeAnswer(text2, status) ?? text2).slice(0, DETAIL_LIMIT), code: null };
130
+ }
131
+ if (parsed === null || typeof parsed !== "object") return raw;
132
+ const { message, code, error } = parsed;
133
+ const stableCode = typeof code === "string" ? code : null;
134
+ if (typeof message !== "string") return { ...raw, code: stableCode };
135
+ const fields = invalidFields(error);
136
+ const said = fields ? `${message}: ${fields}` : message;
137
+ if (stableCode === null) return { detail: said.slice(0, DETAIL_LIMIT), code: null };
138
+ return {
139
+ detail: `${said} (${stableCode})`.slice(0, DETAIL_LIMIT),
140
+ code: stableCode
141
+ };
142
+ }
143
+ function invalidFields(error) {
144
+ const issues = Array.isArray(error) ? error : [];
145
+ return issues.filter(
146
+ (issue) => issue !== null && typeof issue === "object" && typeof issue.message === "string"
147
+ ).map((issue) => {
148
+ const path13 = Array.isArray(issue.path) ? issue.path.map(String).join(".") : "";
149
+ return path13 ? `${path13}: ${issue.message}` : issue.message;
150
+ }).join("; ");
151
+ }
152
+ var ApiError, DETAIL_LIMIT, EDGE_ANSWERS, EDGE_FAILURE, EDGE_PAGE;
153
+ var init_apiError = __esm({
154
+ "src/worlds/apiError.ts"() {
155
+ "use strict";
156
+ ApiError = class extends Error {
157
+ constructor(status, method, path13, text2) {
158
+ const parsed = parseErrorBody(text2, status);
159
+ super(`${method} ${path13} -> ${status}: ${parsed.detail}`);
160
+ this.status = status;
161
+ this.text = text2;
162
+ this.name = "ApiError";
163
+ this.code = parsed.code;
164
+ }
165
+ status;
166
+ text;
167
+ code;
168
+ };
169
+ DETAIL_LIMIT = 600;
170
+ EDGE_ANSWERS = {
171
+ 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.",
172
+ 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.",
173
+ 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."
174
+ };
175
+ 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.";
176
+ 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.";
177
+ }
178
+ });
179
+
53
180
  // src/worlds/transport.ts
54
181
  function platformTimeoutMs(env = process.env) {
55
182
  const raw = env[PLATFORM_TIMEOUT_ENV];
@@ -58,10 +185,20 @@ function platformTimeoutMs(env = process.env) {
58
185
  if (Number.isInteger(value) && value > 0) return value;
59
186
  throw new Error(`${PLATFORM_TIMEOUT_ENV} must be a positive whole number of milliseconds, not \`${raw}\`.`);
60
187
  }
61
- var PLATFORM_TIMEOUT_ENV, PLATFORM_TIMEOUT_DEFAULT_MS, CHECK_HOST, RETRY, FETCH_LIMIT, CAUSES, UNKNOWN_CAUSE, TransportCause, UnreachableError, sleep, RetryPolicy, Attempt, PlatformTransport;
188
+ function platformAuthorization(endpoint, url) {
189
+ const { token } = endpoint;
190
+ if (!token)
191
+ return { authorization: "Basic " + Buffer.from(`${endpoint.publicKey}:${endpoint.secretKey}`).toString("base64") };
192
+ if (endpoint.publicKey || endpoint.secretKey) throw new PersonalTokenRefused(TOKEN_BESIDE_KEYS);
193
+ if (!url.startsWith(`${token.host}/`)) throw new PersonalTokenRefused(TOKEN_OTHER_HOST);
194
+ return { authorization: `Bearer ${token.value}`, "x-gateway-project": token.project };
195
+ }
196
+ 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;
62
197
  var init_transport = __esm({
63
198
  "src/worlds/transport.ts"() {
64
199
  "use strict";
200
+ init_apiError();
201
+ init_personalToken();
65
202
  PLATFORM_TIMEOUT_ENV = "GATEWAY_TIMEOUT_MS";
66
203
  PLATFORM_TIMEOUT_DEFAULT_MS = 12e4;
67
204
  CHECK_HOST = "Check GATEWAY_HOST (or --host) points at a running platform, then retry.";
@@ -101,6 +238,13 @@ var init_transport = __esm({
101
238
  `Retry; if the platform is slow, raise ${PLATFORM_TIMEOUT_ENV} (milliseconds per request).`
102
239
  );
103
240
  }
241
+ static idle(idleMs) {
242
+ return new _TransportCause(
243
+ `no data for ${idleMs / 1e3}s`,
244
+ null,
245
+ "The stream resumes from its last event; if it repeats, check the network between here and the platform."
246
+ );
247
+ }
104
248
  static of(error) {
105
249
  const cause = error instanceof Error && error.cause instanceof Error ? error.cause : void 0;
106
250
  const code = cause && "code" in cause && typeof cause.code === "string" ? cause.code : null;
@@ -176,45 +320,277 @@ var init_transport = __esm({
176
320
  throw this.error;
177
321
  }
178
322
  };
323
+ PLATFORM_STREAM_IDLE_MS = 6e4;
324
+ REFUSAL_TEXT_LIMIT = 64 * 1024;
325
+ KEYED_REDIRECTS = "manual";
179
326
  PlatformTransport = class {
327
+ #endpoint;
328
+ #timeoutMs;
180
329
  constructor(endpoint, timeoutMs = platformTimeoutMs()) {
181
- this.endpoint = endpoint;
182
- this.timeoutMs = timeoutMs;
330
+ this.#endpoint = endpoint;
331
+ this.#timeoutMs = timeoutMs;
183
332
  }
184
- endpoint;
185
- timeoutMs;
186
333
  /** A request that legitimately takes longer (a sandbox exec, a world create) waits its own budget; every other one waits the default. */
187
334
  budget(ownMs) {
188
- return Math.max(ownMs ?? 0, this.timeoutMs);
335
+ return Math.max(ownMs ?? 0, this.#timeoutMs);
189
336
  }
337
+ /** One request; the caller's `signal` aborts it in flight and throws the signal's reason, never an `UnreachableError`. */
190
338
  async send(method, route2, body, opts = {}) {
191
339
  const timeoutMs = this.budget(opts.timeoutMs);
192
- return (opts.retry ?? RetryPolicy.NONE).run(() => this.once(method, route2, body, timeoutMs));
340
+ return (opts.retry ?? RetryPolicy.NONE).run(() => this.once(method, route2, body, timeoutMs, opts.signal));
341
+ }
342
+ /** `send`, then the 2xx body as JSON; any other answer throws `ApiError` with its status and stable `code`. */
343
+ async json(method, route2, body, opts = {}) {
344
+ const reply = await this.send(method, route2, body, opts);
345
+ if (!reply.ok) throw new ApiError(reply.status, method, route2, reply.text);
346
+ return JSON.parse(reply.text);
347
+ }
348
+ /** 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. */
349
+ async stream(route2, opts = {}) {
350
+ const watch = new StreamWatch(opts.signal, opts.idleMs ?? PLATFORM_STREAM_IDLE_MS, this.#endpoint.host, route2);
351
+ const headers = this.headers(route2, "text/event-stream", opts.after ? { "last-event-id": opts.after } : {});
352
+ try {
353
+ const response = await watch.within(
354
+ () => fetch(this.url(route2), { method: "GET", headers, signal: watch.signal, redirect: KEYED_REDIRECTS })
355
+ );
356
+ return new PlatformStream(response, watch);
357
+ } catch (error) {
358
+ watch.close();
359
+ throw error;
360
+ }
361
+ }
362
+ url(route2) {
363
+ return `${this.#endpoint.host}${route2}`;
193
364
  }
194
- async once(method, route2, body, timeoutMs) {
365
+ headers(route2, accept, extra = {}) {
366
+ return {
367
+ "content-type": "application/json",
368
+ accept,
369
+ ...platformAuthorization(this.#endpoint, this.url(route2)),
370
+ ...extra
371
+ };
372
+ }
373
+ async once(method, route2, body, timeoutMs, caller) {
374
+ if (caller?.aborted) throw caller.reason;
195
375
  const payload = body === void 0 ? {} : { body: JSON.stringify(body) };
376
+ const headers = this.headers(route2, "application/json");
196
377
  const controller = new AbortController();
197
378
  const timer = setTimeout(() => controller.abort(), timeoutMs);
379
+ const relay = () => controller.abort(caller?.reason);
380
+ caller?.addEventListener("abort", relay, { once: true });
198
381
  try {
199
- const res = await fetch(`${this.endpoint.host}${route2}`, {
382
+ const res = await fetch(this.url(route2), {
200
383
  method,
201
- headers: {
202
- "content-type": "application/json",
203
- accept: "application/json",
204
- authorization: "Basic " + Buffer.from(`${this.endpoint.publicKey}:${this.endpoint.secretKey}`).toString("base64")
205
- },
384
+ headers,
206
385
  ...payload,
207
- signal: controller.signal
386
+ signal: controller.signal,
387
+ redirect: KEYED_REDIRECTS
208
388
  });
209
389
  return { status: res.status, ok: res.ok, text: await res.text() };
210
390
  } catch (error) {
391
+ if (caller?.aborted) throw caller.reason;
211
392
  const cause = controller.signal.aborted ? TransportCause.timeout(timeoutMs) : TransportCause.of(error);
212
- throw new UnreachableError(this.endpoint.host, method, route2, cause);
393
+ throw new UnreachableError(this.#endpoint.host, method, route2, cause);
213
394
  } finally {
214
395
  clearTimeout(timer);
396
+ caller?.removeEventListener("abort", relay);
215
397
  }
216
398
  }
217
399
  };
400
+ StreamWatch = class {
401
+ constructor(caller, idleMs, host, route2) {
402
+ this.idleMs = idleMs;
403
+ this.host = host;
404
+ this.route = route2;
405
+ this.#caller = caller;
406
+ caller?.addEventListener("abort", this.#relay, { once: true });
407
+ if (caller?.aborted) this.#relay();
408
+ }
409
+ idleMs;
410
+ host;
411
+ route;
412
+ #controller = new AbortController();
413
+ #caller;
414
+ #relay = () => this.#controller.abort(this.#caller?.reason);
415
+ #idled = false;
416
+ get signal() {
417
+ return this.#controller.signal;
418
+ }
419
+ async within(wait) {
420
+ const timer = setTimeout(() => this.idle(), this.idleMs);
421
+ try {
422
+ return await wait();
423
+ } catch (error) {
424
+ throw this.failure(error);
425
+ } finally {
426
+ clearTimeout(timer);
427
+ }
428
+ }
429
+ close() {
430
+ this.#caller?.removeEventListener("abort", this.#relay);
431
+ this.#controller.abort();
432
+ }
433
+ idle() {
434
+ this.#idled = true;
435
+ this.#controller.abort();
436
+ }
437
+ failure(error) {
438
+ if (this.#caller?.aborted) return this.#caller.reason;
439
+ const cause = this.#idled ? TransportCause.idle(this.idleMs) : TransportCause.of(error);
440
+ return new UnreachableError(this.host, "GET", this.route, cause);
441
+ }
442
+ };
443
+ PlatformStream = class {
444
+ #response;
445
+ #watch;
446
+ constructor(response, watch) {
447
+ this.#response = response;
448
+ this.#watch = watch;
449
+ }
450
+ get status() {
451
+ return this.#response.status;
452
+ }
453
+ get ok() {
454
+ return this.#response.ok;
455
+ }
456
+ /** The body as text, for a refusal: at most the first 64 KiB of characters; closes the stream. */
457
+ async text() {
458
+ const decoder = new TextDecoder();
459
+ let text2 = "";
460
+ for await (const chunk of this.chunks()) {
461
+ text2 += decoder.decode(chunk, { stream: true });
462
+ if (text2.length >= REFUSAL_TEXT_LIMIT) return text2.slice(0, REFUSAL_TEXT_LIMIT);
463
+ }
464
+ return text2 + decoder.decode();
465
+ }
466
+ /** The body's bytes as they arrive; the idle budget runs only while waiting for the platform, never while the caller holds a chunk. */
467
+ async *chunks() {
468
+ const reader = this.#response.body?.getReader();
469
+ try {
470
+ for (; ; ) {
471
+ const next = reader ? await this.#watch.within(() => reader.read()) : { done: true };
472
+ if (next.done) return;
473
+ yield next.value;
474
+ }
475
+ } finally {
476
+ this.close();
477
+ }
478
+ }
479
+ close() {
480
+ this.#watch.close();
481
+ }
482
+ };
483
+ }
484
+ });
485
+
486
+ // src/worlds/credentialField.ts
487
+ function isCredentialField(described) {
488
+ const words = described.replace(SPACES, " ").replace(/^ | $/g, "");
489
+ return SECRET_FIELD.some((prefix) => words.startsWith(prefix)) || SECRET_KEY.test(words);
490
+ }
491
+ function credentialTexts(pairs) {
492
+ return pairs.filter(([, text2]) => text2 !== null && text2 !== void 0).filter(([described]) => isCredentialField(String(described))).map(([, text2]) => String(text2));
493
+ }
494
+ function isTextField(described) {
495
+ return described !== "" && !NOT_TEXT.some((prefix) => described.startsWith(prefix));
496
+ }
497
+ function redactActionArgs(action, args) {
498
+ const secretField = action === "browser_type" && SECRET_KEY.test(String(args.selector ?? ""));
499
+ return Object.fromEntries(
500
+ Object.entries(args).map(([key, value]) => [
501
+ key,
502
+ redactedArg(key, value, secretField)
503
+ ])
504
+ );
505
+ }
506
+ function redactedArg(key, value, secretField) {
507
+ if (value === null || value === void 0) return null;
508
+ if (typeof value === "boolean" || typeof value === "number") return value;
509
+ if (typeof value !== "string") return "[omitted]";
510
+ if (SECRET_KEY.test(key) || SECRET_VALUE.test(value) || secretField && key === "text")
511
+ return "[redacted]";
512
+ return value.length <= EVENT_MAX_STRING ? value : value.slice(0, EVENT_MAX_STRING) + "\u2026";
513
+ }
514
+ var SECRET_KEY, DESCRIBE_FIELD_JS, FIELD_VALUE_JS, FIELDS, SHORTEST_WITHHELD, WITHHELD_TEXT, SPACES, LINE_BREAK, TRIM, describeField, readFieldValue, readEditables, UNREADABLE, SECRET_FIELD, NOT_TEXT, escapeRegExp, urlForms, forms, CredentialText, EVENT_MAX_STRING, SECRET_VALUE;
515
+ var init_credentialField = __esm({
516
+ "src/worlds/credentialField.ts"() {
517
+ "use strict";
518
+ 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;
519
+ 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(' '); }";
520
+ 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; }";
521
+ FIELDS = "input:not([type=button]):not([type=submit]):not([type=reset]):not([type=image]):not([type=checkbox]):not([type=radio]):not([type=file]), textarea, select, [contenteditable]:not([contenteditable=false])";
522
+ SHORTEST_WITHHELD = 4;
523
+ WITHHELD_TEXT = "[redacted]";
524
+ SPACES = /[ \t\n\r\f\v]+/g;
525
+ LINE_BREAK = /\r\n|\r|\n/;
526
+ TRIM = /^[ \t\n\r\f\v]+|[ \t\n\r\f\v]+$/g;
527
+ describeField = new Function(
528
+ "e",
529
+ `return (${DESCRIBE_FIELD_JS})(e);`
530
+ );
531
+ readFieldValue = new Function(
532
+ "e",
533
+ `return (${FIELD_VALUE_JS})(e);`
534
+ );
535
+ readEditables = new Function(
536
+ "elements",
537
+ `return elements.map((e) => [(${DESCRIBE_FIELD_JS})(e), (${FIELD_VALUE_JS})(e)]);`
538
+ );
539
+ UNREADABLE = "unreadable";
540
+ SECRET_FIELD = ["password", "frame", "opaque", UNREADABLE];
541
+ NOT_TEXT = ["opaque", "frame", "select"];
542
+ escapeRegExp = (text2) => text2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
543
+ urlForms = (text2) => {
544
+ let component;
545
+ try {
546
+ component = encodeURIComponent(text2);
547
+ } catch {
548
+ return [];
549
+ }
550
+ const form = component.replace(
551
+ /[!'()~]/g,
552
+ (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase()
553
+ ).replace(/%20/g, "+");
554
+ return [component, component.replace(/%20/g, "+"), form];
555
+ };
556
+ forms = (text2) => {
557
+ const written = [
558
+ text2,
559
+ text2.replace(SPACES, " "),
560
+ JSON.stringify(text2).slice(1, -1)
561
+ ];
562
+ return [
563
+ ...written,
564
+ ...written.map((form) => form.replaceAll("'", "''")),
565
+ ...urlForms(text2)
566
+ ];
567
+ };
568
+ CredentialText = class {
569
+ pattern;
570
+ constructor(secrets) {
571
+ const texts = secrets.map((secret) => String(secret).replace(TRIM, ""));
572
+ const lines = texts.flatMap(
573
+ (text2) => text2.split(LINE_BREAK).map((line) => line.replace(TRIM, ""))
574
+ );
575
+ const whole = new Set(
576
+ [...texts, ...lines].filter(
577
+ (text2) => [...text2].length >= SHORTEST_WITHHELD
578
+ )
579
+ );
580
+ const withheld = [
581
+ ...new Set([...whole].flatMap((text2) => forms(text2)))
582
+ ].sort((a, b) => b.length - a.length);
583
+ this.pattern = withheld.length === 0 ? null : new RegExp(
584
+ `(?<![A-Za-z0-9])(?:${withheld.map(escapeRegExp).join("|")})(?![A-Za-z0-9])`,
585
+ "g"
586
+ );
587
+ }
588
+ withhold(text2) {
589
+ return this.pattern === null ? text2 : text2.replace(this.pattern, WITHHELD_TEXT);
590
+ }
591
+ };
592
+ EVENT_MAX_STRING = 500;
593
+ SECRET_VALUE = /^((sk|pk|ghp|xox[abp])[-_][-_A-Za-z0-9]{8,}|AKIA[0-9A-Z]{12,}|Bearer [-_.A-Za-z0-9]{8,})/;
218
594
  }
219
595
  });
220
596
 
@@ -231,6 +607,25 @@ function isBrowserGone(error) {
231
607
  if (PAGE_NETWORK_ERROR.test(message)) return false;
232
608
  return BROWSER_GONE_PATTERNS.some((p) => p.test(message));
233
609
  }
610
+ function scrubError(error, scrub) {
611
+ const seen = /* @__PURE__ */ new Set();
612
+ let at = error;
613
+ while (at instanceof Error && !seen.has(at)) {
614
+ seen.add(at);
615
+ at.message = scrub(at.message);
616
+ at.stack = at.stack && scrub(at.stack);
617
+ scrubOwnText(at, scrub);
618
+ at = at.cause;
619
+ }
620
+ }
621
+ function scrubOwnText(error, scrub) {
622
+ for (const key of Object.keys(error)) {
623
+ const value = error[key];
624
+ if (typeof value === "string") error[key] = scrub(value);
625
+ if (Array.isArray(value) && value.every((item) => typeof item === "string"))
626
+ error[key] = value.map((item) => scrub(item));
627
+ }
628
+ }
234
629
  function refusalIsTransient(error) {
235
630
  const { status, code } = error;
236
631
  if (typeof status !== "number") return true;
@@ -267,11 +662,17 @@ var init_browserReconnect = __esm({
267
662
  ].sort((a, b) => b.length - a.length);
268
663
  }
269
664
  scrub(text2) {
270
- const bare = this.secrets.reduce(
665
+ const bare2 = this.secrets.reduce(
271
666
  (out, secret) => out.split(secret).join(REDACTED),
272
667
  text2
273
668
  );
274
- return bare.replace(TOKEN_QUERY_VALUE, `$1${REDACTED}`);
669
+ return bare2.replace(TOKEN_QUERY_VALUE, `$1${REDACTED}`);
670
+ }
671
+ /** Scrub `error` and the errors it was raised from, in place: the message,
672
+ * the stack and every other own text property, Playwright's `log` call log
673
+ * included. */
674
+ scrubError(error) {
675
+ scrubError(error, (text2) => this.scrub(text2));
275
676
  }
276
677
  };
277
678
  BrowserReconnected = class extends Error {
@@ -423,22 +824,6 @@ function capabilityLabel(url) {
423
824
  }
424
825
  return CAPABILITY_HOST.exec(host)?.[1] ?? null;
425
826
  }
426
- function redactActionArgs(action, args) {
427
- const secretField = action === "browser_type" && SECRET_KEY.test(String(args.selector ?? ""));
428
- const out = {};
429
- for (const [key, value] of Object.entries(args)) {
430
- if (value === null || value === void 0) out[key] = null;
431
- else if (typeof value === "boolean" || typeof value === "number")
432
- out[key] = value;
433
- else if (typeof value === "string") {
434
- if (SECRET_KEY.test(key) || SECRET_VALUE.test(value) || secretField && key === "text")
435
- out[key] = "[redacted]";
436
- else
437
- out[key] = value.length <= EVENT_MAX_STRING ? value : value.slice(0, EVENT_MAX_STRING) + "\u2026";
438
- } else out[key] = "[omitted]";
439
- }
440
- return out;
441
- }
442
827
  async function loadPlaywright() {
443
828
  try {
444
829
  const name = "playwright";
@@ -500,62 +885,14 @@ async function openBrowser(surfaces, opts = {}) {
500
885
  scrubber
501
886
  );
502
887
  }
503
- function computerUseToolkit(browser, opts = {}) {
504
- const maxText = opts.maxText ?? 2e4;
505
- const observe = async (selector = "body") => {
506
- const text2 = await browser.text(selector);
507
- return {
508
- url: browser.url,
509
- title: await browser.title(),
510
- text: text2.slice(0, maxText),
511
- truncated: text2.length > maxText
512
- };
513
- };
514
- const impls = {
515
- browser_goto: async (a) => {
516
- await browser.goto(typeof a.path === "string" ? a.path : void 0);
517
- return observe();
518
- },
519
- browser_click: async (a) => {
520
- await browser.click(str(a.selector, ""));
521
- return observe();
522
- },
523
- browser_type: async (a) => {
524
- await browser.type(str(a.selector, ""), String(a.text ?? ""));
525
- return { ok: true, url: browser.url };
526
- },
527
- browser_press: async (a) => {
528
- await browser.press(str(a.key, "Enter"));
529
- return observe();
530
- },
531
- browser_scroll: async (a) => {
532
- await browser.scroll(typeof a.dy === "number" ? a.dy : 600);
533
- return { ok: true, url: browser.url };
534
- },
535
- browser_screenshot: async (a) => ({
536
- image_base64: await browser.screenshotBase64(a.full_page === true),
537
- url: browser.url
538
- }),
539
- browser_read: async (a) => observe(str(a.selector, "body")),
540
- browser_back: async () => {
541
- await browser.back();
542
- return observe();
543
- }
544
- };
545
- const specs = COMPUTER_USE_SPECS.map((s) => ({ ...s }));
546
- return {
547
- schemas: specs.map((spec) => schemaFromSignature(spec)),
548
- impls,
549
- specs
550
- };
551
- }
552
- var SURFACE_KINDS, PLATFORM_SESSION_HEADER, SESSION_AUTH_MODES, BROWSER_TIERS, DEFAULT_VIEWPORT, SETTLE_TIMEOUT_MS, SETTLE_QUIET_MS, SETTLE_POLL_MS, EVENT_BATCH_SIZE, EVENT_FLUSH_INTERVAL_MS, EVENT_MAX_RETRIES, EVENT_SCREENSHOT_QUALITY, EVENT_MAX_STRING, SECRET_KEY, SECRET_VALUE, WorldSurfaceUnavailable, UI_TOKEN_QUERY, CAPABILITY_HOST, BrowserActionRecorder, WorldBrowser, COMPUTER_USE_SPECS, str;
888
+ var SURFACE_KINDS, FIELD_PROBE_TIMEOUT_MS, PLATFORM_SESSION_HEADER, SESSION_AUTH_MODES, BROWSER_TIERS, DEFAULT_VIEWPORT, SETTLE_TIMEOUT_MS, SETTLE_QUIET_MS, SETTLE_POLL_MS, EVENT_BATCH_SIZE, EVENT_FLUSH_INTERVAL_MS, EVENT_MAX_RETRIES, EVENT_SCREENSHOT_QUALITY, WorldSurfaceUnavailable, UI_TOKEN_QUERY, CAPABILITY_HOST, BrowserActionRecorder, WorldBrowser;
553
889
  var init_browser = __esm({
554
890
  "src/worlds/browser.ts"() {
555
891
  "use strict";
556
- init_session2();
892
+ init_credentialField();
557
893
  init_browserReconnect();
558
894
  SURFACE_KINDS = ["tools", "api", "ui", "browser"];
895
+ FIELD_PROBE_TIMEOUT_MS = 2e3;
559
896
  PLATFORM_SESSION_HEADER = "X-World-Session";
560
897
  SESSION_AUTH_MODES = ["vendor", "open"];
561
898
  BROWSER_TIERS = ["standard", "premium"];
@@ -567,9 +904,6 @@ var init_browser = __esm({
567
904
  EVENT_FLUSH_INTERVAL_MS = 1e3;
568
905
  EVENT_MAX_RETRIES = 3;
569
906
  EVENT_SCREENSHOT_QUALITY = 60;
570
- EVENT_MAX_STRING = 500;
571
- SECRET_KEY = /pass(word|wd)?|secret|token|api[-_]?key|authorization|cookie|(^|[-_ #.\["'=])(otp|pin|cvv|ssn)([-_ \]"']|$)/i;
572
- SECRET_VALUE = /^((sk|pk|ghp|xox[abp])[-_][-_A-Za-z0-9]{8,}|AKIA[0-9A-Z]{12,}|Bearer [-_.A-Za-z0-9]{8,})/;
573
907
  WorldSurfaceUnavailable = class extends Error {
574
908
  constructor(surface, reason) {
575
909
  super(`World surface '${surface}' is unavailable: ${reason}`);
@@ -692,6 +1026,8 @@ var init_browser = __esm({
692
1026
  recorder;
693
1027
  reconnector;
694
1028
  scrubber;
1029
+ typed = [];
1030
+ typedText = new CredentialText([]);
695
1031
  current;
696
1032
  inflight = 0;
697
1033
  lastNetwork = Date.now();
@@ -705,10 +1041,20 @@ var init_browser = __esm({
705
1041
  get agentId() {
706
1042
  return this.recorder?.agentId ?? null;
707
1043
  }
708
- /** `text` with this session's credentials (UI token, browser address) removed. */
1044
+ /** `text` with this session's credentials (UI token, browser address) and
1045
+ * the credentials typed into it removed. */
709
1046
  scrub(text2) {
1047
+ return this.typedText.withhold(this.scrubber.scrub(text2));
1048
+ }
1049
+ /** `text` with this session's credentials removed and nothing else
1050
+ * changed: for text that is compared and never leaves the process. */
1051
+ scrubSession(text2) {
710
1052
  return this.scrubber.scrub(text2);
711
1053
  }
1054
+ /** Every credential typed into this browser by `type`. */
1055
+ get typedCredentials() {
1056
+ return [...this.typed];
1057
+ }
712
1058
  watchNetwork(page) {
713
1059
  page.on("request", () => {
714
1060
  this.inflight += 1;
@@ -752,7 +1098,7 @@ var init_browser = __esm({
752
1098
  async recover(reconnector, cause) {
753
1099
  const started = Date.now();
754
1100
  const message = cause instanceof Error ? cause.message : String(cause);
755
- const args = { cause: this.scrubber.scrub(message).slice(0, 200) };
1101
+ const args = { cause: this.scrub(message).slice(0, 200) };
756
1102
  let result;
757
1103
  try {
758
1104
  result = await reconnector.recover(cause, (c) => this.adopt(c));
@@ -787,7 +1133,9 @@ var init_browser = __esm({
787
1133
  }
788
1134
  /** Run one action and report it: the event carries what was asked,
789
1135
  * whether it worked, and the screen after — for failures too, so a
790
- * reviewer sees what the agent saw when the selector did not match. */
1136
+ * reviewer sees what the agent saw when the selector did not match. The
1137
+ * error it throws keeps no session credential and no credential typed into
1138
+ * this browser, which Playwright's call log would quote. */
791
1139
  async act(action, args, fn, onLoss = "report") {
792
1140
  const started = Date.now();
793
1141
  try {
@@ -795,6 +1143,7 @@ var init_browser = __esm({
795
1143
  await this.report(action, args, started, null);
796
1144
  return result;
797
1145
  } catch (error) {
1146
+ this.scrubError(error);
798
1147
  await this.report(action, args, started, error);
799
1148
  throw error;
800
1149
  }
@@ -803,7 +1152,7 @@ var init_browser = __esm({
803
1152
  async report(action, args, started, failure) {
804
1153
  const recorder = this.recorder;
805
1154
  if (!recorder) return;
806
- const error = failure === null ? null : this.scrubber.scrub(
1155
+ const error = failure === null ? null : this.scrub(
807
1156
  failure instanceof Error ? `${failure.name}: ${failure.message}` : String(failure)
808
1157
  ).slice(0, 4e3);
809
1158
  recorder.record({
@@ -816,7 +1165,7 @@ var init_browser = __esm({
816
1165
  Object.fromEntries(
817
1166
  Object.entries(args).map(([key, value]) => [
818
1167
  key,
819
- typeof value === "string" ? this.scrubber.scrub(value) : value
1168
+ typeof value === "string" ? this.scrub(value) : value
820
1169
  ])
821
1170
  )
822
1171
  ),
@@ -835,8 +1184,8 @@ var init_browser = __esm({
835
1184
  screenshot: null
836
1185
  };
837
1186
  try {
838
- out.url = this.scrubber.scrub(this.page.url());
839
- out.title = this.scrubber.scrub(await this.page.title());
1187
+ out.url = this.scrub(this.page.url());
1188
+ out.title = this.scrub(await this.page.title());
840
1189
  const jpeg = await this.page.screenshot({
841
1190
  type: "jpeg",
842
1191
  quality: EVENT_SCREENSHOT_QUALITY
@@ -873,7 +1222,7 @@ var init_browser = __esm({
873
1222
  async () => {
874
1223
  await this.page.goto(target, { waitUntil: "load" });
875
1224
  await this.settle();
876
- return this.page.url();
1225
+ return this.url;
877
1226
  },
878
1227
  // Navigating again lands on the same page: safe to replay.
879
1228
  "retry"
@@ -883,7 +1232,7 @@ var init_browser = __esm({
883
1232
  return this.act("browser_back", {}, async () => {
884
1233
  await this.page.goBack({ waitUntil: "load" });
885
1234
  await this.settle();
886
- return this.page.url();
1235
+ return this.url;
887
1236
  });
888
1237
  }
889
1238
  /** Wait for the page to finish reacting to an action. `load` alone is not
@@ -902,19 +1251,54 @@ var init_browser = __esm({
902
1251
  await this.page.waitForTimeout(SETTLE_POLL_MS);
903
1252
  }
904
1253
  }
905
- async click(selector) {
1254
+ async click(selector, opts = {}) {
906
1255
  await this.act("browser_click", { selector }, async () => {
907
- await this.page.click(selector);
1256
+ await this.page.click(selector, { timeout: opts.timeoutMs });
908
1257
  await this.settle();
909
1258
  });
910
1259
  }
911
- async type(selector, text2) {
1260
+ /** Replace the field's value with `text`. `opts.credential` is whether the
1261
+ * field takes one, when the caller already probed it; a credential is
1262
+ * withheld from the event and from any error. */
1263
+ async type(selector, text2, opts = {}) {
1264
+ const secret = opts.credential ?? await this.credentialField(selector);
1265
+ if (secret) this.typed.push(text2);
1266
+ this.typedText = new CredentialText(this.typed);
912
1267
  await this.act(
913
1268
  "browser_type",
914
- { selector, text: text2 },
915
- () => this.page.fill(selector, text2)
1269
+ { selector, text: secret ? "[redacted]" : text2 },
1270
+ () => this.page.fill(selector, text2, { timeout: opts.timeoutMs })
916
1271
  );
917
1272
  }
1273
+ /** `DESCRIBE_FIELD_JS` of the element `selector` finds, or `UNREADABLE`. */
1274
+ async describeField(selector) {
1275
+ try {
1276
+ const described = await this.page.locator(selector).evaluate(describeField, void 0, { timeout: FIELD_PROBE_TIMEOUT_MS });
1277
+ return String(described ?? "");
1278
+ } catch {
1279
+ return UNREADABLE;
1280
+ }
1281
+ }
1282
+ /** Whether the field `selector` finds takes a credential; one it cannot
1283
+ * read counts. */
1284
+ async credentialField(selector) {
1285
+ return isCredentialField(await this.describeField(selector));
1286
+ }
1287
+ /** What the field `selector` finds holds (`FIELD_VALUE_JS`), or null when
1288
+ * it cannot be read. */
1289
+ async fieldValue(selector) {
1290
+ try {
1291
+ const value = await this.page.locator(selector).evaluate(readFieldValue, void 0, { timeout: FIELD_PROBE_TIMEOUT_MS });
1292
+ return value === null || value === void 0 ? null : String(value);
1293
+ } catch {
1294
+ return null;
1295
+ }
1296
+ }
1297
+ /** Take this session's credentials out of `error` and the errors it came
1298
+ * from, in place. */
1299
+ scrubError(error) {
1300
+ scrubError(error, (text2) => this.scrub(text2));
1301
+ }
918
1302
  async press(key) {
919
1303
  await this.act("browser_press", { key }, async () => {
920
1304
  await this.page.keyboard.press(key);
@@ -937,14 +1321,39 @@ var init_browser = __esm({
937
1321
  async screenshotBase64(fullPage = false) {
938
1322
  return (await this.screenshot(fullPage)).toString("base64");
939
1323
  }
1324
+ /** The visible text of `selector`'s element, without what any field on the
1325
+ * page that takes a credential holds. */
940
1326
  async text(selector = "body") {
941
- return this.resilient(() => this.page.innerText(selector), "retry");
1327
+ const withheld = new CredentialText(await this.credentialTexts());
1328
+ return withheld.withhold(
1329
+ await this.resilient(() => this.page.innerText(selector), "retry")
1330
+ );
1331
+ }
1332
+ /** What each field on the page that takes a credential holds: an input's
1333
+ * or textarea's value, a select's chosen option, a contenteditable's text. */
1334
+ async credentialTexts() {
1335
+ return this.resilient(async () => {
1336
+ const pairs = await this.page.locator(FIELDS).evaluateAll(readEditables);
1337
+ return credentialTexts(pairs);
1338
+ }, "retry");
1339
+ }
1340
+ /** Wait until the element `selector` finds could be clicked, without
1341
+ * clicking it. */
1342
+ async actionable(selector) {
1343
+ await this.resilient(() => this.page.locator(selector).click({ trial: true }), "retry");
1344
+ }
1345
+ async ariaSnapshot() {
1346
+ return this.resilient(async () => {
1347
+ if (!this.page.ariaSnapshot)
1348
+ throw new TypeError("this Playwright has no page.ariaSnapshot");
1349
+ return this.page.ariaSnapshot({ mode: "ai" });
1350
+ }, "retry");
942
1351
  }
943
1352
  async html() {
944
1353
  return this.resilient(() => this.page.content(), "retry");
945
1354
  }
946
1355
  get url() {
947
- return this.page.url();
1356
+ return withoutUiToken(this.page.url());
948
1357
  }
949
1358
  async title() {
950
1359
  return this.resilient(() => this.page.title(), "retry");
@@ -957,21 +1366,504 @@ var init_browser = __esm({
957
1366
  }
958
1367
  }
959
1368
  };
1369
+ }
1370
+ });
1371
+
1372
+ // src/worlds/pageState.ts
1373
+ function selectorRef(selector) {
1374
+ if (selector.includes("aria-ref"))
1375
+ throw new PageStateError(
1376
+ "aria-ref selectors are not taken: pass ref=\u2026 from browser_snapshot"
1377
+ );
1378
+ return REF_SELECTOR.exec(selector.replace(/^ +| +$/g, ""))?.[1] ?? null;
1379
+ }
1380
+ var DEFAULT_MAX_CHARS, REF_ACT_TIMEOUT_MS, STEADY_READS, NEEDS_PLAYWRIGHT, CHANGED, LINE_KEY, ATTRIBUTES, FOCUS, STATES, ROLE, REF, REF_SELECTOR, EDITABLE_ROLES, VALUE_KEYS, WITHHELD, PageStateError, AriaLine, Touched, sameLines, deeper, PageState, PageObserver;
1381
+ var init_pageState = __esm({
1382
+ "src/worlds/pageState.ts"() {
1383
+ "use strict";
1384
+ init_credentialField();
1385
+ DEFAULT_MAX_CHARS = 2e4;
1386
+ REF_ACT_TIMEOUT_MS = 2e3;
1387
+ STEADY_READS = 4;
1388
+ NEEDS_PLAYWRIGHT = "browser_snapshot needs Playwright 1.59 or newer (npm install playwright@latest)";
1389
+ CHANGED = "the page changed since the last browser_snapshot: take a new one (a page that never holds still can be driven with text= or CSS selectors)";
1390
+ LINE_KEY = /^ *- ('(?:[^']|'')*'|.*?)(:(?: .*)?)?$/s;
1391
+ ATTRIBUTES = /(?: \[[^[\]]*\])*$/;
1392
+ FOCUS = / \[active\]/g;
1393
+ STATES = / \[(?:checked(?:=mixed)?|expanded|pressed(?:=mixed)?|selected)\]/g;
1394
+ ROLE = /^[a-z]+/;
1395
+ REF = /\[ref=((?:f[0-9]+)?e[0-9]+)\]/g;
1396
+ REF_SELECTOR = /^ref=((?:f[0-9]+)?e[0-9]+)$/;
1397
+ EDITABLE_ROLES = /* @__PURE__ */ new Set([
1398
+ "textbox",
1399
+ "searchbox",
1400
+ "combobox",
1401
+ "spinbutton",
1402
+ "slider"
1403
+ ]);
1404
+ VALUE_KEYS = /* @__PURE__ */ new Set(["text", "/placeholder"]);
1405
+ WITHHELD = ": [redacted]";
1406
+ PageStateError = class extends Error {
1407
+ name = "PageStateError";
1408
+ };
1409
+ AriaLine = class _AriaLine {
1410
+ constructor(text2, indent, key = "", attributes = "", rest = "") {
1411
+ this.text = text2;
1412
+ this.indent = indent;
1413
+ this.key = key;
1414
+ this.attributes = attributes;
1415
+ this.rest = rest;
1416
+ }
1417
+ text;
1418
+ indent;
1419
+ key;
1420
+ attributes;
1421
+ rest;
1422
+ static parse(text2) {
1423
+ const indent = text2.length - text2.replace(/^ +/, "").length;
1424
+ const found = LINE_KEY.exec(text2);
1425
+ if (!found) return new _AriaLine(text2, indent);
1426
+ const key = found[1].startsWith("'") ? found[1].slice(1, -1).replaceAll("''", "'") : found[1];
1427
+ return new _AriaLine(
1428
+ text2,
1429
+ indent,
1430
+ key,
1431
+ ATTRIBUTES.exec(key)?.[0] ?? "",
1432
+ found[2] ?? ""
1433
+ );
1434
+ }
1435
+ static parseAll(aria) {
1436
+ return aria === "" ? [] : aria.split("\n").map((text2) => _AriaLine.parse(text2));
1437
+ }
1438
+ get refs() {
1439
+ return [...this.attributes.matchAll(REF)].map((ref) => ref[1]);
1440
+ }
1441
+ get disabled() {
1442
+ return this.attributes.includes("[disabled]");
1443
+ }
1444
+ get editable() {
1445
+ const role = ROLE.exec(this.key)?.[0];
1446
+ return role !== void 0 && EDITABLE_ROLES.has(role);
1447
+ }
1448
+ /** A value line: a field's text, or the placeholder it shows. */
1449
+ get value() {
1450
+ return VALUE_KEYS.has(this.key);
1451
+ }
1452
+ get states() {
1453
+ return this.attributes.match(STATES) ?? [];
1454
+ }
1455
+ get namedLikeCredential() {
1456
+ return SECRET_KEY.test(
1457
+ this.key.slice(0, this.key.length - this.attributes.length)
1458
+ );
1459
+ }
1460
+ /** Whether every value in and under this line is withheld. A field is,
1461
+ * when it is named like a credential or sits in something that is, has no
1462
+ * ref to probe, or `describe` reads it as a credential field. Any other
1463
+ * line is, when it is named like a credential and holds typed text (a
1464
+ * contenteditable), or has no ref to tell. */
1465
+ async credentialField(describe2, withinCredential) {
1466
+ if (this.editable)
1467
+ return this.credentialFieldInput(describe2, withinCredential);
1468
+ if (!this.namedLikeCredential) return false;
1469
+ if (this.refs.length === 0) return true;
1470
+ return isTextField(await describe2(this.refs[0]));
1471
+ }
1472
+ async credentialFieldInput(describe2, withinCredential) {
1473
+ if (withinCredential || this.namedLikeCredential) return true;
1474
+ if (this.refs.length === 0) return true;
1475
+ return isCredentialField(await describe2(this.refs[0]));
1476
+ }
1477
+ /** The line as shown: `withholding` applied to its text, while its refs and
1478
+ * states are still read from the attribute run Playwright wrote, so a
1479
+ * withheld name cannot join that run. */
1480
+ withheldBy(withhold) {
1481
+ return new _AriaLine(
1482
+ this.withholding(withhold),
1483
+ this.indent,
1484
+ this.key,
1485
+ this.attributes,
1486
+ this.rest
1487
+ );
1488
+ }
1489
+ /** The line with `withhold` applied to its name and value, its attribute
1490
+ * run (refs, states, levels) as Playwright wrote it. */
1491
+ withholding(withhold) {
1492
+ const at = this.attributes ? this.text.lastIndexOf(
1493
+ this.attributes,
1494
+ this.text.length - this.rest.length - this.attributes.length
1495
+ ) : -1;
1496
+ if (at < 0) return withhold(this.text);
1497
+ const end = at + this.attributes.length;
1498
+ return withhold(this.text.slice(0, at)) + this.attributes + withhold(this.text.slice(end));
1499
+ }
1500
+ /** The line with its own value replaced, keeping the key as Playwright
1501
+ * wrote it. */
1502
+ get withheld() {
1503
+ if (this.key === "/placeholder" || !this.rest.startsWith(": "))
1504
+ return this.text;
1505
+ return this.text.slice(0, this.text.length - this.rest.length) + WITHHELD;
1506
+ }
1507
+ };
1508
+ Touched = class _Touched {
1509
+ constructor(clicked = /* @__PURE__ */ new Map(), typed = /* @__PURE__ */ new Map()) {
1510
+ this.clicked = clicked;
1511
+ this.typed = typed;
1512
+ }
1513
+ clicked;
1514
+ typed;
1515
+ afterClick(ref, states) {
1516
+ return new _Touched(new Map([...this.clicked, [ref, states]]), this.typed);
1517
+ }
1518
+ afterTyping(ref, text2) {
1519
+ return new _Touched(this.clicked, new Map([...this.typed, [ref, text2]]));
1520
+ }
1521
+ /** The snapshot's lines as the page should now read them. */
1522
+ expected(lines) {
1523
+ return this.compared(lines, (line) => this.leftByClick(line));
1524
+ }
1525
+ /** A fresh read's lines, in the same form. */
1526
+ actual(lines) {
1527
+ return this.compared(lines, (line) => line.states);
1528
+ }
1529
+ compared(lines, states) {
1530
+ const out = [];
1531
+ let typedAt = null;
1532
+ for (const line of lines) {
1533
+ if (typedAt !== null && line.indent > typedAt && line.value) continue;
1534
+ typedAt = this.isTyped(line) ? line.indent : null;
1535
+ out.push(this.comparedLine(line, states(line)));
1536
+ }
1537
+ return out;
1538
+ }
1539
+ isTyped(line) {
1540
+ return line.refs.some((ref) => this.typed.has(ref));
1541
+ }
1542
+ clickedRef(line) {
1543
+ return line.refs.find((ref) => this.clicked.has(ref));
1544
+ }
1545
+ leftByClick(line) {
1546
+ const ref = this.clickedRef(line);
1547
+ return ref === void 0 ? line.states : this.clicked.get(ref);
1548
+ }
1549
+ comparedLine(line, states) {
1550
+ if (this.isTyped(line))
1551
+ return (" ".repeat(line.indent) + "- " + line.key).replace(FOCUS, "");
1552
+ if (this.clickedRef(line) !== void 0)
1553
+ return line.text.replace(FOCUS, "").replace(STATES, "") + states.join("");
1554
+ return line.text.replace(FOCUS, "");
1555
+ }
1556
+ };
1557
+ sameLines = (a, b) => a.length === b.length && a.every((line, at) => line === b[at]);
1558
+ deeper = (line, below) => below !== null && line.indent > below ? below : null;
1559
+ PageState = class _PageState {
1560
+ constructor(url, title, snapshot, refs, disabled, truncated, credentials = /* @__PURE__ */ new Set()) {
1561
+ this.url = url;
1562
+ this.title = title;
1563
+ this.snapshot = snapshot;
1564
+ this.refs = refs;
1565
+ this.disabled = disabled;
1566
+ this.truncated = truncated;
1567
+ this.credentials = credentials;
1568
+ }
1569
+ url;
1570
+ title;
1571
+ snapshot;
1572
+ refs;
1573
+ disabled;
1574
+ truncated;
1575
+ credentials;
1576
+ static parse(aria, opts) {
1577
+ return _PageState.ofLines(AriaLine.parseAll(aria), opts);
1578
+ }
1579
+ static ofLines(lines, opts) {
1580
+ const maxChars = opts.maxChars ?? DEFAULT_MAX_CHARS;
1581
+ const shown = [];
1582
+ let size = 0;
1583
+ for (const line of lines) {
1584
+ const width = [...line.text].length + 1;
1585
+ if (size + width > maxChars) break;
1586
+ size += width;
1587
+ shown.push(line);
1588
+ }
1589
+ return new _PageState(
1590
+ opts.url,
1591
+ opts.title,
1592
+ shown.map((line) => line.text).join("\n"),
1593
+ new Set(shown.flatMap((line) => line.refs)),
1594
+ new Set(
1595
+ shown.filter((line) => line.disabled).flatMap((line) => line.refs)
1596
+ ),
1597
+ shown.length < lines.length,
1598
+ opts.credentials ?? /* @__PURE__ */ new Set()
1599
+ );
1600
+ }
1601
+ /** `aria` with credential values withheld: every value in and under a
1602
+ * credential field (see `AriaLine.credentialField`; `describe` is
1603
+ * `DESCRIBE_FIELD_JS` of a ref's element), the placeholder aside, and the
1604
+ * value of any line named like a credential. Names, roles and refs stay. */
1605
+ static async redacted(aria, describe2) {
1606
+ const out = [];
1607
+ const withheld = [];
1608
+ let withheldBelow = null;
1609
+ let credentialBelow = null;
1610
+ for (const line of AriaLine.parseAll(aria)) {
1611
+ withheldBelow = deeper(line, withheldBelow);
1612
+ credentialBelow = deeper(line, credentialBelow);
1613
+ if (withheldBelow === null && await line.credentialField(describe2, credentialBelow !== null))
1614
+ withheldBelow = line.indent;
1615
+ if (credentialBelow === null && line.namedLikeCredential)
1616
+ credentialBelow = line.indent;
1617
+ const hidden = withheldBelow !== null || line.namedLikeCredential;
1618
+ out.push(hidden ? line.withheld : line.text);
1619
+ if (hidden) withheld.push(...line.refs);
1620
+ }
1621
+ return { snapshot: out.join("\n"), withheld: new Set(withheld) };
1622
+ }
1623
+ target(ref) {
1624
+ if (!this.refs.has(ref))
1625
+ throw new PageStateError(
1626
+ `ref=${ref} is not in the last browser_snapshot: take a new one`
1627
+ );
1628
+ if (this.disabled.has(ref))
1629
+ throw new PageStateError(`ref=${ref} is disabled`);
1630
+ return `aria-ref=${ref}`;
1631
+ }
1632
+ observation() {
1633
+ return {
1634
+ url: this.url,
1635
+ title: this.title,
1636
+ snapshot: this.snapshot,
1637
+ truncated: this.truncated
1638
+ };
1639
+ }
1640
+ };
1641
+ PageObserver = class {
1642
+ constructor(browser, maxChars = DEFAULT_MAX_CHARS) {
1643
+ this.browser = browser;
1644
+ this.maxChars = maxChars;
1645
+ }
1646
+ browser;
1647
+ maxChars;
1648
+ last = null;
1649
+ seen = [];
1650
+ seenUrl = "";
1651
+ touched = new Touched();
1652
+ turn = Promise.resolve();
1653
+ async snapshot() {
1654
+ return this.inTurn(() => this.takeSnapshot());
1655
+ }
1656
+ async click(selector) {
1657
+ return this.inTurn(() => this.clickOnce(selector));
1658
+ }
1659
+ async type(selector, text2) {
1660
+ return this.inTurn(() => this.typeOnce(selector, text2));
1661
+ }
1662
+ /** One call at a time, so a tool call a model made in parallel cannot act
1663
+ * between another's checks and its action. */
1664
+ inTurn(fn) {
1665
+ const run = this.turn.then(fn, fn);
1666
+ this.turn = run.catch(() => void 0);
1667
+ return run;
1668
+ }
1669
+ async takeSnapshot() {
1670
+ const aria = this.browser.scrubSession(await this.steady());
1671
+ const shown = await PageState.redacted(
1672
+ aria,
1673
+ (ref) => this.browser.describeField(`aria-ref=${ref}`)
1674
+ );
1675
+ const secrets = new CredentialText([
1676
+ ...await this.withheldValues(shown),
1677
+ ...await this.browser.credentialTexts(),
1678
+ ...this.browser.typedCredentials
1679
+ ]);
1680
+ const lines = AriaLine.parseAll(shown.snapshot).map(
1681
+ (line) => line.withheldBy((text2) => secrets.withhold(text2))
1682
+ );
1683
+ this.last = PageState.ofLines(lines, {
1684
+ url: this.url(),
1685
+ title: this.browser.scrub(await this.browser.title()),
1686
+ maxChars: this.maxChars,
1687
+ credentials: shown.withheld
1688
+ });
1689
+ this.seen = AriaLine.parseAll(aria);
1690
+ this.seenUrl = this.browser.scrubSession(this.browser.url);
1691
+ this.touched = new Touched();
1692
+ return this.last;
1693
+ }
1694
+ /** The values of the fields the redaction withheld: a page may repeat them
1695
+ * in another line's name (a row or cell named from its content, a label
1696
+ * that wraps the field). */
1697
+ async withheldValues(shown) {
1698
+ const refs = AriaLine.parseAll(shown.snapshot).filter((line) => line.editable).flatMap((line) => line.refs).filter((ref) => shown.withheld.has(ref));
1699
+ const values = [];
1700
+ for (const ref of refs)
1701
+ values.push(await this.browser.fieldValue(`aria-ref=${ref}`) ?? "");
1702
+ return values;
1703
+ }
1704
+ async clickOnce(selector) {
1705
+ const ref = selectorRef(selector);
1706
+ if (ref === null) return this.browser.click(selector);
1707
+ const [, target] = this.target(ref);
1708
+ await this.ready(target);
1709
+ await this.browser.click(target, { timeoutMs: REF_ACT_TIMEOUT_MS });
1710
+ const left = (await this.now()).find((line) => line.refs.includes(ref));
1711
+ if (left) this.touched = this.touched.afterClick(ref, left.states);
1712
+ }
1713
+ async typeOnce(selector, text2) {
1714
+ const ref = selectorRef(selector);
1715
+ if (ref === null) return this.browser.type(selector, text2);
1716
+ const [last, target] = this.target(ref);
1717
+ const credential = last.credentials.has(ref) || await this.browser.credentialField(target);
1718
+ await this.ready(target);
1719
+ await this.browser.type(target, text2, {
1720
+ timeoutMs: REF_ACT_TIMEOUT_MS,
1721
+ credential
1722
+ });
1723
+ this.touched = this.touched.afterTyping(ref, text2);
1724
+ }
1725
+ target(ref) {
1726
+ if (this.last === null)
1727
+ throw new PageStateError(
1728
+ "ref=\u2026 selectors come from browser_snapshot: take one first"
1729
+ );
1730
+ return [this.last, this.last.target(ref)];
1731
+ }
1732
+ async ready(target) {
1733
+ await this.still();
1734
+ await this.browser.actionable(target);
1735
+ await this.still();
1736
+ }
1737
+ /** A page still rendering when it is read would refuse the model's next
1738
+ * ref, so the snapshot it is shown is one that read the same before and
1739
+ * after the page settled again. */
1740
+ async steady() {
1741
+ const untouched = new Touched();
1742
+ let aria = await this.read();
1743
+ for (let read = 1; read < STEADY_READS; read++) {
1744
+ await this.browser.settle();
1745
+ const again = await this.read();
1746
+ if (sameLines(
1747
+ untouched.actual(AriaLine.parseAll(again)),
1748
+ untouched.actual(AriaLine.parseAll(aria))
1749
+ ))
1750
+ return again;
1751
+ aria = again;
1752
+ }
1753
+ return aria;
1754
+ }
1755
+ async read() {
1756
+ try {
1757
+ return await this.browser.ariaSnapshot();
1758
+ } catch (error) {
1759
+ if (error instanceof TypeError)
1760
+ throw new PageStateError(NEEDS_PLAYWRIGHT);
1761
+ throw error;
1762
+ }
1763
+ }
1764
+ url() {
1765
+ return this.browser.scrub(this.browser.url);
1766
+ }
1767
+ async now() {
1768
+ return AriaLine.parseAll(this.browser.scrubSession(await this.read()));
1769
+ }
1770
+ async still() {
1771
+ if (this.browser.scrubSession(this.browser.url) !== this.seenUrl || !sameLines(
1772
+ this.touched.actual(await this.now()),
1773
+ this.touched.expected(this.seen)
1774
+ ))
1775
+ throw new PageStateError(CHANGED);
1776
+ for (const [ref, text2] of this.touched.typed)
1777
+ if (await this.browser.fieldValue(`aria-ref=${ref}`) !== text2)
1778
+ throw new PageStateError(CHANGED);
1779
+ }
1780
+ };
1781
+ }
1782
+ });
1783
+
1784
+ // src/worlds/browserTools.ts
1785
+ function computerUseToolkit(browser, opts = {}) {
1786
+ const maxText = opts.maxText ?? DEFAULT_MAX_CHARS;
1787
+ const pages = new PageObserver(browser, maxText);
1788
+ const observe = async (selector = "body") => {
1789
+ const text2 = browser.scrub(await browser.text(selector));
1790
+ return {
1791
+ url: browser.scrub(browser.url),
1792
+ title: browser.scrub(await browser.title()),
1793
+ text: text2.slice(0, maxText),
1794
+ truncated: text2.length > maxText
1795
+ };
1796
+ };
1797
+ const impls = {
1798
+ browser_goto: async (a) => {
1799
+ await browser.goto(typeof a.path === "string" ? a.path : void 0);
1800
+ return observe();
1801
+ },
1802
+ browser_snapshot: async () => (await pages.snapshot()).observation(),
1803
+ browser_click: async (a) => {
1804
+ await pages.click(str(a.selector, ""));
1805
+ return observe();
1806
+ },
1807
+ browser_type: async (a) => {
1808
+ await pages.type(str(a.selector, ""), String(a.text ?? ""));
1809
+ return { ok: true, url: browser.scrub(browser.url) };
1810
+ },
1811
+ browser_press: async (a) => {
1812
+ await browser.press(str(a.key, "Enter"));
1813
+ return observe();
1814
+ },
1815
+ browser_scroll: async (a) => {
1816
+ await browser.scroll(typeof a.dy === "number" ? a.dy : 600);
1817
+ return { ok: true, url: browser.scrub(browser.url) };
1818
+ },
1819
+ browser_screenshot: async (a) => ({
1820
+ image_base64: await browser.screenshotBase64(a.full_page === true),
1821
+ url: browser.scrub(browser.url)
1822
+ }),
1823
+ browser_read: async (a) => observe(str(a.selector, "body")),
1824
+ browser_back: async () => {
1825
+ await browser.back();
1826
+ return observe();
1827
+ }
1828
+ };
1829
+ const specs = COMPUTER_USE_SPECS.map((s) => ({ ...s }));
1830
+ return {
1831
+ schemas: specs.map((spec) => schemaFromSignature(spec)),
1832
+ impls: Object.fromEntries(
1833
+ Object.entries(impls).map(([name, impl]) => [
1834
+ name,
1835
+ scrubbingErrors(browser, impl)
1836
+ ])
1837
+ ),
1838
+ specs
1839
+ };
1840
+ }
1841
+ var COMPUTER_USE_SPECS, scrubbingErrors, str;
1842
+ var init_browserTools = __esm({
1843
+ "src/worlds/browserTools.ts"() {
1844
+ "use strict";
1845
+ init_pageState();
1846
+ init_session2();
960
1847
  COMPUTER_USE_SPECS = [
961
1848
  {
962
1849
  name: "browser_goto",
963
1850
  signature: "browser_goto(path=None)",
964
1851
  doc: "Open a page of the world's UI. `path` is a UI path like /customers, a full URL, or omitted for the entry page. Returns the URL and page text."
965
1852
  },
1853
+ {
1854
+ name: "browser_snapshot",
1855
+ signature: "browser_snapshot()",
1856
+ doc: "The page as an accessibility tree, one line per element with its role, name and [ref=e3]. To act on an element, pass `ref=e3` as the selector of browser_click or browser_type. Returns {url, title, snapshot, truncated}."
1857
+ },
966
1858
  {
967
1859
  name: "browser_click",
968
1860
  signature: "browser_click(selector)",
969
- doc: "Click an element by Playwright selector (CSS, `text=Refund`, `role=button[name=Save]`). Returns the page text after the click."
1861
+ doc: "Click an element by `ref=e3` from the last browser_snapshot, or by Playwright selector (CSS, `text=Refund`, `role=button[name=Save]`). Returns the page text after the click."
970
1862
  },
971
1863
  {
972
1864
  name: "browser_type",
973
1865
  signature: "browser_type(selector, text)",
974
- doc: "Replace the value of an input/textarea found by selector with `text`."
1866
+ doc: "Replace the value of an input/textarea, found by `ref=e3` or by selector, with `text`."
975
1867
  },
976
1868
  {
977
1869
  name: "browser_press",
@@ -999,6 +1891,14 @@ var init_browser = __esm({
999
1891
  doc: "Go back one page in history."
1000
1892
  }
1001
1893
  ];
1894
+ scrubbingErrors = (browser, impl) => async (args) => {
1895
+ try {
1896
+ return await impl(args);
1897
+ } catch (error) {
1898
+ browser.scrubError(error);
1899
+ throw error;
1900
+ }
1901
+ };
1002
1902
  str = (v, fallback) => typeof v === "string" && v.length > 0 ? v : fallback;
1003
1903
  }
1004
1904
  });
@@ -1143,13 +2043,12 @@ function isNativePage(page) {
1143
2043
  const mouse = candidate?.mouse;
1144
2044
  return typeof candidate?.context === "function" && NATIVE_METHODS.every((m) => typeof mouse?.[m] === "function");
1145
2045
  }
1146
- var FOCUSED_FIELD_JS, SECRET_FOCUS, DRAG_STEPS, PNG_SIGNATURE, NATIVE_METHODS, Screen;
2046
+ var FOCUSED_FIELD_JS, DRAG_STEPS, PNG_SIGNATURE, NATIVE_METHODS, Screen;
1147
2047
  var init_screen = __esm({
1148
2048
  "src/worlds/nativeComputer/screen.ts"() {
1149
2049
  "use strict";
1150
- init_browser();
1151
- 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(' '); })()";
1152
- SECRET_FOCUS = ["password", "frame", "opaque"];
2050
+ init_credentialField();
2051
+ 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); })()`;
1153
2052
  DRAG_STEPS = 5;
1154
2053
  PNG_SIGNATURE = Buffer.from([
1155
2054
  137,
@@ -1240,7 +2139,7 @@ var init_screen = __esm({
1240
2139
  } catch {
1241
2140
  return true;
1242
2141
  }
1243
- return SECRET_FOCUS.some((prefix) => described.startsWith(prefix)) || SECRET_KEY.test(described);
2142
+ return isCredentialField(described);
1244
2143
  }
1245
2144
  /** CDP renders a clip at the page's device pixel ratio as well as its
1246
2145
  * `scale` (a Retina host doubles it), so a capture of the wrong width
@@ -2418,7 +3317,7 @@ var init_requestLedger = __esm({
2418
3317
  "use strict";
2419
3318
  init_worlds();
2420
3319
  init_sessionContract();
2421
- WORLD_REQUEST_VIAS = ["api", "ui", "tool", "webhook"];
3320
+ WORLD_REQUEST_VIAS = ["api", "ui", "tool", "webhook", "page"];
2422
3321
  WorldRequestFilterError = class extends Error {
2423
3322
  };
2424
3323
  NOT_RECORDED = "This session's engine records no requests; only hosted World Host sessions do.";
@@ -2927,7 +3826,8 @@ async function openSession(slugOrRef, taskOrOpts = {}, positionalOpts = {}) {
2927
3826
  ...opts.reuseWarm === void 0 ? {} : { reuseWarm: opts.reuseWarm },
2928
3827
  ...opts.surfaces?.length ? { surfaces: opts.surfaces } : {},
2929
3828
  ...opts.browserTier === void 0 ? {} : { browserTier: opts.browserTier },
2930
- ...opts.auth === void 0 ? {} : { auth: opts.auth }
3829
+ ...opts.auth === void 0 ? {} : { auth: opts.auth },
3830
+ ...opts.worldState === void 0 ? {} : { worldState: opts.worldState }
2931
3831
  }
2932
3832
  );
2933
3833
  return new WorldSession(state2.sessionId, state2, options);
@@ -3014,6 +3914,7 @@ var init_session2 = __esm({
3014
3914
  "use strict";
3015
3915
  init_worlds();
3016
3916
  init_browser();
3917
+ init_browserTools();
3017
3918
  init_nativeComputer();
3018
3919
  init_sessionContract();
3019
3920
  init_toolSchema();
@@ -3079,6 +3980,9 @@ var init_session2 = __esm({
3079
3980
  get versionId() {
3080
3981
  return this.current.versionId;
3081
3982
  }
3983
+ get worldState() {
3984
+ return this.current.worldState ?? null;
3985
+ }
3082
3986
  /** Whether the session answered ready as of the last state read (the open,
3083
3987
  * a `status()`, or the poll inside `ready()`); no request is made. */
3084
3988
  get isReady() {
@@ -3448,6 +4352,7 @@ var init_session2 = __esm({
3448
4352
  "surfaces",
3449
4353
  "browserTier",
3450
4354
  "auth",
4355
+ "worldState",
3451
4356
  "options"
3452
4357
  ]);
3453
4358
  isOpenSessionOptions = (value) => typeof value === "object" && value !== null && Object.keys(value).every((key) => OPEN_SESSION_OPTION_KEYS.has(key));
@@ -3691,7 +4596,8 @@ async function openTask(ref, opts = {}) {
3691
4596
  task,
3692
4597
  ...opts.reuseWarm === void 0 ? {} : { reuseWarm: opts.reuseWarm },
3693
4598
  ...opts.surfaces?.length ? { surfaces: opts.surfaces } : {},
3694
- ...opts.browserTier === void 0 ? {} : { browserTier: opts.browserTier }
4599
+ ...opts.browserTier === void 0 ? {} : { browserTier: opts.browserTier },
4600
+ ...opts.worldStates === void 0 ? {} : { worldStates: opts.worldStates }
3695
4601
  }
3696
4602
  );
3697
4603
  return fromResponse(answer, options);
@@ -3949,16 +4855,22 @@ var init_evals = __esm({
3949
4855
  "src/worlds/evals.ts"() {
3950
4856
  "use strict";
3951
4857
  init_worlds();
4858
+ init_personalToken();
4859
+ init_platformEndpoint();
3952
4860
  init_transport();
3953
4861
  EVALUATIONS = "/api/public/benchmark-containers/evaluations";
3954
- GatewayEvalsClient = class {
4862
+ GatewayEvalsClient = class _GatewayEvalsClient {
3955
4863
  constructor(options = {}, retry = RetryPolicy.FILING) {
3956
4864
  this.options = options;
3957
4865
  this.retry = retry;
4866
+ _GatewayEvalsClient.refuseToken(options);
3958
4867
  }
3959
4868
  options;
3960
4869
  retry;
3961
4870
  keyed = /* @__PURE__ */ new Set();
4871
+ static refuseToken(options) {
4872
+ if (platformEndpoint(options)?.token) throw new PersonalTokenRefused(TOKEN_FILING);
4873
+ }
3962
4874
  async createEvaluation(versionId, opts = {}) {
3963
4875
  const body = { versionId };
3964
4876
  if (opts.model !== void 0) body.model = opts.model;
@@ -5024,7 +5936,7 @@ var require_package = __commonJS({
5024
5936
  "package.json"(exports, module) {
5025
5937
  module.exports = {
5026
5938
  name: "@withgateway/sdk",
5027
- version: "0.6.0",
5939
+ version: "0.9.1",
5028
5940
  description: "Gateway SDK for TypeScript - A/B experiments, tracing, and observability",
5029
5941
  main: "./dist/index.js",
5030
5942
  module: "./dist/index.mjs",
@@ -5105,6 +6017,11 @@ var require_package = __commonJS({
5105
6017
  import: "./dist/hooks/index.mjs",
5106
6018
  require: "./dist/hooks/index.js"
5107
6019
  },
6020
+ "./agents": {
6021
+ types: "./dist/agents/index.d.ts",
6022
+ import: "./dist/agents/index.mjs",
6023
+ require: "./dist/agents/index.js"
6024
+ },
5108
6025
  "./cli": {
5109
6026
  types: "./dist/cli.d.ts",
5110
6027
  import: "./dist/cli.mjs",
@@ -5713,6 +6630,7 @@ var init_taskTracing = __esm({
5713
6630
  "use strict";
5714
6631
  init_prerequisites();
5715
6632
  init_platformEndpoint();
6633
+ init_personalToken();
5716
6634
  HOST_WITH_AUTHORITY = /^[a-z][a-z0-9+.-]*:\/\/[^/\\?#@\s]+(\/|$)/i;
5717
6635
  TRACING_HELD_ELSEWHERE = "Tracing in this process already sends spans to another destination or with other keys (an earlier run, or the agent's own tracing.init()), so this run's spans would not reach its own project.";
5718
6636
  TaskTracing = class _TaskTracing {
@@ -5724,8 +6642,9 @@ var init_taskTracing = __esm({
5724
6642
  static target = null;
5725
6643
  async start(requested, options) {
5726
6644
  if (!requested) return false;
5727
- const endpoint = platformEndpoint(options);
6645
+ let endpoint = null;
5728
6646
  try {
6647
+ endpoint = platformEndpoint(options);
5729
6648
  await this.initOnce(_TaskTracing.config(endpoint));
5730
6649
  return true;
5731
6650
  } catch (error) {
@@ -5747,6 +6666,7 @@ var init_taskTracing = __esm({
5747
6666
  }
5748
6667
  static config(endpoint) {
5749
6668
  if (!endpoint) throw new Error(GATEWAY_KEYS_MISSING);
6669
+ if (endpoint.token) throw new Error(TOKEN_KEYS_ONLY);
5750
6670
  return { ...endpoint, endpoint: _TaskTracing.destination(endpoint) };
5751
6671
  }
5752
6672
  // B1: a saved login's keys go to their own host only. The redirect is compared as text, never parsed:
@@ -5777,7 +6697,9 @@ Pass --no-trace (trace: false) to run untraced without this warning.`
5777
6697
  static reason(error, endpoint) {
5778
6698
  if (OpenTelemetryMissing.explains(error)) return new OpenTelemetryMissing().message;
5779
6699
  const message = error instanceof Error ? error.message : String(error);
5780
- const keys = endpoint ? [endpoint.publicKey, endpoint.secretKey] : [];
6700
+ const keys = [endpoint?.publicKey, endpoint?.secretKey, endpoint?.token?.value].filter(
6701
+ (key) => Boolean(key)
6702
+ );
5781
6703
  return keys.reduce((text2, key) => text2.split(key).join("[redacted]"), message);
5782
6704
  }
5783
6705
  };
@@ -5824,13 +6746,15 @@ async function refuseUnreadTools(live) {
5824
6746
  }
5825
6747
  }
5826
6748
  async function runTask(ref, agent, opts) {
5827
- const runId = `wtr-${randomBytes(6).toString("hex")}`;
5828
6749
  const options = opts.options ?? {};
6750
+ if (opts.file !== false) GatewayEvalsClient.refuseToken(options);
6751
+ const runId = `wtr-${randomBytes(6).toString("hex")}`;
5829
6752
  const opening = new TaskOpening(
5830
6753
  openTask(ref, {
5831
6754
  surfaces: opts.surfaces,
5832
6755
  reuseWarm: opts.reuseWarm,
5833
6756
  browserTier: opts.browserTier,
6757
+ worldStates: opts.worldStates,
5834
6758
  options
5835
6759
  }).then(async (live) => {
5836
6760
  await refuseUnreadTools(live);
@@ -6110,6 +7034,7 @@ var init_checkoutProvenance = __esm({
6110
7034
  // src/worlds/setRun.ts
6111
7035
  async function runSet(datasetId, agent, opts) {
6112
7036
  const options = opts.options ?? {};
7037
+ GatewayEvalsClient.refuseToken(options);
6113
7038
  const git = opts.git === void 0 ? CheckoutProvenance.read() : opts.git;
6114
7039
  const opened = await apiRequest(options, "POST", SET_RUNS, {
6115
7040
  datasetId,
@@ -6125,6 +7050,7 @@ var init_setRun = __esm({
6125
7050
  "use strict";
6126
7051
  init_worlds();
6127
7052
  init_checkoutProvenance();
7053
+ init_evals();
6128
7054
  init_runSignals();
6129
7055
  init_taskRun();
6130
7056
  SET_RUNS = "/api/public/set-runs";
@@ -6512,19 +7438,20 @@ var init_checkoutTarget = __esm({
6512
7438
  import { createHash as createHash3 } from "crypto";
6513
7439
  import * as fs3 from "fs";
6514
7440
  import * as path4 from "path";
6515
- var WORLD_MANIFEST, API_BUNDLE_MANIFEST, BUNDLED_WORLD_PREFIX, CONNECTOR_SPEC, PYPROJECT, BENCHMARK_CONFIG, WORLD_SCHEMA_MARKERS, WORLD_ROOT_MARKERS, BROAD_ROOT_MARKERS, SKIPPED_DIRS, V1_DEP, V1_IMPORT, V1_TASKSET, HARBOR_TASK, skippedDir, byCodePoint, WorldDir;
7441
+ var WORLD_MANIFEST, API_BUNDLE_MANIFEST, BUNDLE_MANIFEST, BUNDLED_WORLD_PREFIX, CONNECTOR_SPEC, PYPROJECT, BENCHMARK_CONFIG, WORLD_SCHEMA_MARKERS, WORLD_ROOT_MARKERS, BROAD_ROOT_MARKERS, SKIPPED_DIRS, V1_DEP, V1_IMPORT, V1_TASKSET, HARBOR_TASK, skippedDir, byCodePoint, WorldDir;
6516
7442
  var init_worldDir = __esm({
6517
7443
  "src/worlds/worldDir.ts"() {
6518
7444
  "use strict";
6519
7445
  WORLD_MANIFEST = "gateway-env.toml";
6520
7446
  API_BUNDLE_MANIFEST = "gateway-api-world.toml";
7447
+ BUNDLE_MANIFEST = "gateway-bundle.toml";
6521
7448
  BUNDLED_WORLD_PREFIX = "server/world/";
6522
7449
  CONNECTOR_SPEC = "connector.toml";
6523
7450
  PYPROJECT = "pyproject.toml";
6524
7451
  BENCHMARK_CONFIG = "benchmark.json";
6525
7452
  WORLD_SCHEMA_MARKERS = ["schema/world.json", "schema/runtime.json", "schema/lock.json"];
6526
7453
  WORLD_ROOT_MARKERS = [CONNECTOR_SPEC, ...WORLD_SCHEMA_MARKERS];
6527
- BROAD_ROOT_MARKERS = [WORLD_MANIFEST, API_BUNDLE_MANIFEST, BENCHMARK_CONFIG];
7454
+ BROAD_ROOT_MARKERS = [WORLD_MANIFEST, API_BUNDLE_MANIFEST, BENCHMARK_CONFIG, BUNDLE_MANIFEST];
6528
7455
  SKIPPED_DIRS = /* @__PURE__ */ new Set(["dist", "build", "outputs", "__pycache__", "node_modules"]);
6529
7456
  V1_DEP = /["']verifiers\s*(?:\[[^\]]*\])?\s*(?:>=|~=|==|>)\s*(?:0\.(?:[2-9]\d*|[1-9]\d+)|[1-9]\d*)/;
6530
7457
  V1_IMPORT = /^\s*(?:from\s+verifiers\.v1\s+import\b|from\s+verifiers\s+import\s+v1\b|import\s+verifiers\.v1\b)/m;
@@ -6545,7 +7472,6 @@ var init_worldDir = __esm({
6545
7472
  const bundled = present(API_BUNDLE_MANIFEST) && WORLD_ROOT_MARKERS.some((m) => present(BUNDLED_WORLD_PREFIX + m));
6546
7473
  return new _WorldDir(dir, bundled ? BUNDLED_WORLD_PREFIX : "");
6547
7474
  }
6548
- // ── Files ──────────────────────────────────────────────────────────────
6549
7475
  has(rel) {
6550
7476
  return fs3.existsSync(path4.join(this.dir, rel));
6551
7477
  }
@@ -6556,15 +7482,9 @@ var init_worldDir = __esm({
6556
7482
  return null;
6557
7483
  }
6558
7484
  }
6559
- /** A path under the authored world's root. */
6560
7485
  worldPath(rel) {
6561
7486
  return this.worldRoot + rel;
6562
7487
  }
6563
- /** Every regular file the archive rules keep (`_archive.py`: no hidden,
6564
- * dist, build, outputs, pycache, node_modules or egg-info directories), as
6565
- * sorted relpaths. Root files enter only when a Gateway manifest or
6566
- * benchmark.json widens the root, or they are README.md, pyproject.toml or
6567
- * Python. */
6568
7488
  get archivePaths() {
6569
7489
  if (this.pathsMemo) return this.pathsMemo;
6570
7490
  const broad = BROAD_ROOT_MARKERS.some((m) => this.has(m));
@@ -6583,11 +7503,6 @@ var init_worldDir = __esm({
6583
7503
  walk("");
6584
7504
  return this.pathsMemo = out.sort(byCodePoint);
6585
7505
  }
6586
- /** What the archive rules leave out, collapsed to the entry that decided
6587
- * it: a pruned directory counts its files once, a dropped root file is
6588
- * named. Dot entries (`.git/`, `.gateway/`, `.gitignore`) are the one
6589
- * universal convention and stay unreported. `push` prints the rest so
6590
- * nothing disappears silently. */
6591
7506
  get exclusions() {
6592
7507
  const kept = new Set(this.archivePaths);
6593
7508
  const out = [];
@@ -6610,14 +7525,11 @@ var init_worldDir = __esm({
6610
7525
  }
6611
7526
  return out;
6612
7527
  }
6613
- /** A root `.gitignore` is present: the Python SDK honours it when
6614
- * collecting, this package does not reimplement gitignore. */
7528
+ /** The Python SDK honours a root `.gitignore` when collecting; this package does not reimplement gitignore. */
6615
7529
  get hasRootGitignore() {
6616
7530
  return this.has(".gitignore");
6617
7531
  }
6618
- /** SHA-256 over `utf8("file:" + relpath)` + bytes per archive path in
6619
- * sorted order: the version's identity, byte-compatible with
6620
- * `_archive.compute_content_hash` and Prime Intellect. */
7532
+ /** The version's identity, byte-compatible with the Python SDK's `compute_content_hash` and Prime Intellect's hub. */
6621
7533
  get contentHash() {
6622
7534
  const hasher = createHash3("sha256");
6623
7535
  for (const rel of this.archivePaths) {
@@ -6626,18 +7538,18 @@ var init_worldDir = __esm({
6626
7538
  }
6627
7539
  return hasher.digest("hex");
6628
7540
  }
6629
- // ── Markers ────────────────────────────────────────────────────────────
6630
7541
  get isApiBundle() {
6631
7542
  return this.has(API_BUNDLE_MANIFEST);
6632
7543
  }
7544
+ get isWorldBundle() {
7545
+ return this.has(BUNDLE_MANIFEST);
7546
+ }
6633
7547
  get hasManifest() {
6634
7548
  return this.has(this.worldPath(WORLD_MANIFEST));
6635
7549
  }
6636
7550
  get hasSchemaMarker() {
6637
7551
  return WORLD_SCHEMA_MARKERS.some((m) => this.has(this.worldPath(m)));
6638
7552
  }
6639
- /** Harbor task dirs, relative to the tree: `tasks/<name>` when a `tasks/`
6640
- * dir holds them, else the root `<name>` dirs. */
6641
7553
  taskDirs() {
6642
7554
  const names = /* @__PURE__ */ new Set();
6643
7555
  for (const rel of this.archivePaths) {
@@ -6647,8 +7559,6 @@ var init_worldDir = __esm({
6647
7559
  const under = [...names].filter((n) => n.startsWith("tasks/"));
6648
7560
  return (under.length ? under : [...names]).sort();
6649
7561
  }
6650
- /** The Python package of a verifiers tree (`<pkg>/__init__.py` or
6651
- * `src/<pkg>/__init__.py`), or null. */
6652
7562
  pythonPackage() {
6653
7563
  if (!this.has(PYPROJECT)) return null;
6654
7564
  for (const base of ["", "src/"]) {
@@ -6660,8 +7570,6 @@ var init_worldDir = __esm({
6660
7570
  }
6661
7571
  return null;
6662
7572
  }
6663
- /** The package targets the `verifiers.v1` API: read from the root
6664
- * pyproject and every archived Python module. */
6665
7573
  get isVerifiersV1() {
6666
7574
  for (const rel of this.archivePaths) {
6667
7575
  if (rel !== PYPROJECT && !rel.endsWith(".py")) continue;
@@ -6672,11 +7580,9 @@ var init_worldDir = __esm({
6672
7580
  }
6673
7581
  return false;
6674
7582
  }
6675
- // ── The answer ─────────────────────────────────────────────────────────
6676
- /** The runner's kind (`detect_env_kind`): api / mock-tools win over
6677
- * everything, a harbor task tree next, then the verifiers API version. */
6678
7583
  get kind() {
6679
7584
  if (this.isApiBundle) return "api";
7585
+ if (this.isWorldBundle) return "bundle";
6680
7586
  if (this.has(WORLD_MANIFEST)) return "mock-tools";
6681
7587
  if (this.taskDirs().length) return "harbor";
6682
7588
  return this.isVerifiersV1 ? "verifiers-v1" : "verifiers";
@@ -7018,8 +7924,7 @@ async function push(dir, opts = {}) {
7018
7924
  const metadata = {
7019
7925
  ...opts.name !== void 0 ? { name: opts.name } : {},
7020
7926
  ...opts.description !== void 0 ? { description: opts.description } : {},
7021
- ...opts.tags !== void 0 ? { tags: opts.tags } : {},
7022
- ...opts.visibility ? { visibility: opts.visibility } : {}
7927
+ ...opts.tags !== void 0 ? { tags: opts.tags } : {}
7023
7928
  };
7024
7929
  const resolve7 = await apiRequest(
7025
7930
  options,
@@ -7547,7 +8452,7 @@ var init_sandbox = __esm({
7547
8452
  /**
7548
8453
  * `{ slug, ref? }` opens a READY version; `{ new, from }` opens a sandbox on
7549
8454
  * a world that does not exist yet (409 `world_exists` if the slug is taken,
7550
- * 400 naming the shipped templates if `from` is unknown). Its first commit
8455
+ * 400 naming the official templates if `from` is unknown). Its first commit
7551
8456
  * creates the world on `main`.
7552
8457
  */
7553
8458
  open(target) {
@@ -8192,6 +9097,7 @@ var CliError;
8192
9097
  var init_router = __esm({
8193
9098
  "src/cli/router.ts"() {
8194
9099
  "use strict";
9100
+ init_personalToken();
8195
9101
  CliError = class extends Error {
8196
9102
  constructor(message, exitCode = 2) {
8197
9103
  super(message);
@@ -8206,18 +9112,62 @@ var init_router = __esm({
8206
9112
  import * as fs6 from "fs";
8207
9113
  import * as os from "os";
8208
9114
  import * as path7 from "path";
9115
+ function configPath() {
9116
+ return path7.join(process.env.GATEWAY_CONFIG_DIR || path7.join(os.homedir(), ".gateway"), "config.json");
9117
+ }
9118
+ function readConfig() {
9119
+ let stored;
9120
+ try {
9121
+ stored = JSON.parse(fs6.readFileSync(configPath(), "utf8"));
9122
+ } catch {
9123
+ return {};
9124
+ }
9125
+ const record = stored ?? {};
9126
+ return Object.fromEntries(STORED_FIELDS.filter((f) => typeof record[f] === "string").map((f) => [f, record[f]]));
9127
+ }
9128
+ function personalToken(request = {}) {
9129
+ try {
9130
+ return PersonalToken.fromEnv(process.env, request);
9131
+ } catch (error) {
9132
+ if (error instanceof PersonalTokenRefused) throw new CliError(error.message);
9133
+ throw error;
9134
+ }
9135
+ }
9136
+ function resolveCredentials(hostFlag, secretKeyFlag) {
9137
+ const token = personalToken({ host: hostFlag || void 0, keys: Boolean(secretKeyFlag) });
9138
+ if (token) return { host: token.host, publicKey: "", secretKey: "", token };
9139
+ const stored = readConfig();
9140
+ const explicitHost = (hostFlag || process.env.GATEWAY_HOST || "").replace(/\/+$/, "");
9141
+ const host = explicitHost || (stored.host ?? "").replace(/\/+$/, "");
9142
+ if (!host)
9143
+ throw new CredentialsMissing(
9144
+ "Host not configured. Pass --host, set GATEWAY_HOST, or run `gateway auth login`."
9145
+ );
9146
+ const login = host === (stored.host ?? "").replace(/\/+$/, "") ? stored : {};
9147
+ const publicKey = process.env.GATEWAY_PUBLIC_KEY || login.public_key || "";
9148
+ const secretKey = secretKeyFlag || process.env.GATEWAY_SECRET_KEY || process.env.GATEWAY_API_KEY || login.api_key || "";
9149
+ if (!publicKey || !secretKey)
9150
+ throw new CredentialsMissing(
9151
+ "API key not configured. Set GATEWAY_PUBLIC_KEY and GATEWAY_SECRET_KEY, or run `gateway auth login`."
9152
+ );
9153
+ return { host, publicKey, secretKey };
9154
+ }
8209
9155
  async function api(creds, method, route2, body, init2 = {}) {
8210
9156
  const reply = await new PlatformTransport(creds).send(method, route2, body, init2);
8211
9157
  if (!reply.ok) throw new ApiError2(reply.status, method, route2, reply.text);
8212
9158
  return reply.text ? JSON.parse(reply.text) : {};
8213
9159
  }
8214
- var ApiError2;
9160
+ var STORED_FIELDS, CredentialsMissing, ApiError2;
8215
9161
  var init_config = __esm({
8216
9162
  "src/cli/config.ts"() {
8217
9163
  "use strict";
8218
9164
  init_router();
8219
9165
  init_worlds();
9166
+ init_personalToken();
8220
9167
  init_transport();
9168
+ STORED_FIELDS = ["host", "public_key", "api_key"];
9169
+ CredentialsMissing = class extends CliError {
9170
+ };
8221
9171
  ApiError2 = class extends CliError {
8222
9172
  constructor(status, method, route2, text2) {
8223
9173
  const body = parseErrorBody(text2, status);
@@ -8237,8 +9187,37 @@ var init_config = __esm({
8237
9187
  }
8238
9188
  });
8239
9189
 
9190
+ // src/worlds/isolatedPython.ts
9191
+ import { spawnSync } from "child_process";
9192
+ function isolatedPython(python, args, timeout) {
9193
+ return spawnSync(python, ["-I", ...args], { encoding: "utf8", timeout, env: PersonalToken.scrubbed(process.env) });
9194
+ }
9195
+ var init_isolatedPython = __esm({
9196
+ "src/worlds/isolatedPython.ts"() {
9197
+ "use strict";
9198
+ init_personalToken();
9199
+ }
9200
+ });
9201
+
8240
9202
  // src/cli/runtime/local.ts
8241
- import { spawn, spawnSync } from "child_process";
9203
+ var local_exports = {};
9204
+ __export(local_exports, {
9205
+ MIN_PYTHON_LABEL: () => MIN_PYTHON_LABEL,
9206
+ assertPortFree: () => assertPortFree,
9207
+ credentialsForRuntime: () => credentialsForRuntime,
9208
+ findPython: () => findPython,
9209
+ localBridge: () => localBridge,
9210
+ localModule: () => localModule,
9211
+ localPythonHasYaml: () => localPythonHasYaml,
9212
+ localRuntime: () => localRuntime,
9213
+ localRuntimeReason: () => localRuntimeReason,
9214
+ portOwner: () => portOwner,
9215
+ pythonAdvice: () => pythonAdvice,
9216
+ resetPythonCache: () => resetPythonCache,
9217
+ runtimeMode: () => runtimeMode,
9218
+ runtimeRoot: () => runtimeRoot
9219
+ });
9220
+ import { spawn, spawnSync as spawnSync2 } from "child_process";
8242
9221
  import * as fs7 from "fs";
8243
9222
  import * as net from "net";
8244
9223
  import * as path8 from "path";
@@ -8278,12 +9257,12 @@ function runtimeRoot() {
8278
9257
  return root;
8279
9258
  return null;
8280
9259
  }
9260
+ function resetPythonCache() {
9261
+ pythonCache = void 0;
9262
+ pythonProbes = [];
9263
+ }
8281
9264
  function probeVersion(name) {
8282
- const probe = spawnSync(
8283
- name,
8284
- ["-c", "import sys;print(sys.version_info[0],sys.version_info[1])"],
8285
- { encoding: "utf8", timeout: 1e4 }
8286
- );
9265
+ const probe = isolatedPython(name, ["-c", "import sys;print(sys.version_info[0],sys.version_info[1])"], 1e4);
8287
9266
  if (probe.status !== 0) return null;
8288
9267
  const [major, minor] = probe.stdout.trim().split(/\s+/).map(Number);
8289
9268
  return Number.isInteger(major) && Number.isInteger(minor) ? `${major}.${minor}` : null;
@@ -8293,7 +9272,7 @@ function atLeastMinimum(version) {
8293
9272
  return major > MIN_PYTHON[0] || major === MIN_PYTHON[0] && minor >= MIN_PYTHON[1];
8294
9273
  }
8295
9274
  function uvPython() {
8296
- const found = spawnSync("uv", UV_FIND, { encoding: "utf8", timeout: 1e4 });
9275
+ const found = spawnSync2("uv", UV_FIND, { encoding: "utf8", timeout: 1e4, env: PersonalToken.scrubbed(process.env) });
8297
9276
  if (found.status !== 0) return null;
8298
9277
  const line = found.stdout.trim().split(/\r?\n/)[0] ?? "";
8299
9278
  return line || null;
@@ -8352,7 +9331,7 @@ function localRuntime() {
8352
9331
  return { python, root };
8353
9332
  }
8354
9333
  function localPythonHasYaml(python) {
8355
- return spawnSync(python, ["-c", "import yaml"], { timeout: 1e4 }).status === 0;
9334
+ return isolatedPython(python, ["-c", "import yaml"], 1e4).status === 0;
8356
9335
  }
8357
9336
  async function localBridge(request, local, opts = {}) {
8358
9337
  const input = JSON.stringify(request);
@@ -8413,12 +9392,88 @@ async function localBridge(request, local, opts = {}) {
8413
9392
  child.stdin.end(input);
8414
9393
  });
8415
9394
  }
8416
- var MIN_PYTHON, MIN_PYTHON_LABEL, DIAGNOSTIC_TAIL, FORWARDED_ENV, BRIDGE_BOOTSTRAP, pythonCache, pythonProbes, PYTHON_CANDIDATES, UV_FIND;
9395
+ function portOwner(port) {
9396
+ const found = spawnSync2("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-Fpc"], {
9397
+ encoding: "utf8",
9398
+ timeout: 5e3
9399
+ });
9400
+ if (found.error || found.status !== 0) return null;
9401
+ let pid = null;
9402
+ let command2 = null;
9403
+ for (const line of found.stdout.split("\n")) {
9404
+ if (line.startsWith("p") && pid === null) pid = line.slice(1);
9405
+ else if (line.startsWith("c") && pid !== null && command2 === null) command2 = line.slice(1);
9406
+ }
9407
+ if (pid === null) return null;
9408
+ return `pid ${pid}${command2 ? ` (${command2})` : ""}`;
9409
+ }
9410
+ async function assertPortFree(port, host = "127.0.0.1") {
9411
+ const taken = await new Promise((resolve7) => {
9412
+ const probe = net.createServer();
9413
+ probe.once("error", () => resolve7(true));
9414
+ probe.listen(port, host, () => probe.close(() => resolve7(false)));
9415
+ });
9416
+ if (!taken) return;
9417
+ const owner = portOwner(port);
9418
+ throw new CliError(
9419
+ `port ${port} on ${host} is already in use${owner ? ` by ${owner}` : ""}; nothing was served there \u2014 pass another --port, or stop that server first`,
9420
+ 1
9421
+ );
9422
+ }
9423
+ async function localModule(argv, local, opts = {}) {
9424
+ return await new Promise((resolve7, reject) => {
9425
+ const child = spawn(
9426
+ local.python,
9427
+ ["-B", "-c", MODULE_BOOTSTRAP, local.root, ...argv],
9428
+ {
9429
+ stdio: "inherit",
9430
+ cwd: opts.cwd,
9431
+ env: { ...PersonalToken.scrubbed(process.env), ...opts.env }
9432
+ }
9433
+ );
9434
+ const forward = (signal) => () => {
9435
+ if (child.exitCode === null && child.signalCode === null) child.kill(signal);
9436
+ };
9437
+ const handlers = [
9438
+ ["SIGINT", forward("SIGINT")],
9439
+ ["SIGTERM", forward("SIGTERM")],
9440
+ ["SIGHUP", forward("SIGHUP")]
9441
+ ];
9442
+ for (const [signal, handler] of handlers) process.on(signal, handler);
9443
+ const release = () => {
9444
+ for (const [signal, handler] of handlers) process.off(signal, handler);
9445
+ };
9446
+ child.on("error", (error) => {
9447
+ release();
9448
+ reject(
9449
+ new CliError(
9450
+ `local runtime could not start (${local.python}): ${error.message}`,
9451
+ 1
9452
+ )
9453
+ );
9454
+ });
9455
+ child.on("close", (code, signal) => {
9456
+ release();
9457
+ resolve7(code ?? (signal ? 130 : 1));
9458
+ });
9459
+ });
9460
+ }
9461
+ function credentialsForRuntime(hostFlag) {
9462
+ try {
9463
+ return resolveCredentials(hostFlag);
9464
+ } catch (error) {
9465
+ if (error instanceof CliError && localRuntime()) return null;
9466
+ throw error;
9467
+ }
9468
+ }
9469
+ var MIN_PYTHON, MIN_PYTHON_LABEL, DIAGNOSTIC_TAIL, FORWARDED_ENV, BRIDGE_BOOTSTRAP, MODULE_BOOTSTRAP, pythonCache, pythonProbes, PYTHON_CANDIDATES, UV_FIND;
8417
9470
  var init_local = __esm({
8418
9471
  "src/cli/runtime/local.ts"() {
8419
9472
  "use strict";
8420
9473
  init_router();
8421
9474
  init_config();
9475
+ init_isolatedPython();
9476
+ init_personalToken();
8422
9477
  MIN_PYTHON = [3, 12];
8423
9478
  MIN_PYTHON_LABEL = MIN_PYTHON.join(".");
8424
9479
  DIAGNOSTIC_TAIL = 600;
@@ -8429,6 +9484,13 @@ package=types.ModuleType('gatewaysdk')
8429
9484
  package.__path__=[os.path.join(root,'gatewaysdk')]
8430
9485
  sys.modules['gatewaysdk']=package
8431
9486
  runpy.run_module('gatewaysdk.environment.schema.platform',run_name='__main__')`;
9487
+ MODULE_BOOTSTRAP = `import sys,runpy,types,os
9488
+ root=sys.argv[1]
9489
+ package=types.ModuleType('gatewaysdk')
9490
+ package.__path__=[os.path.join(root,'gatewaysdk')]
9491
+ sys.modules['gatewaysdk']=package
9492
+ sys.argv=['gateway worlds']+sys.argv[2:]
9493
+ runpy.run_module('gatewaysdk.environment.schema',run_name='__main__')`;
8432
9494
  pythonProbes = [];
8433
9495
  PYTHON_CANDIDATES = [
8434
9496
  "python3.13",
@@ -9538,14 +10600,23 @@ function toolCallsFromObservations(observations, opts = {}) {
9538
10600
  }
9539
10601
  return out;
9540
10602
  }
10603
+ async function runtimeEndpoint(options) {
10604
+ try {
10605
+ return platformEndpoint(options);
10606
+ } catch (error) {
10607
+ const { localRuntime: localRuntime2 } = await Promise.resolve().then(() => (init_local(), local_exports));
10608
+ if (error instanceof PersonalTokenRefused && localRuntime2()) return null;
10609
+ throw error;
10610
+ }
10611
+ }
9541
10612
  async function ingest(world, records, options = {}) {
9542
10613
  const { ingestLocalToolCalls: ingestLocalToolCalls2, importLocalWorldData: importLocalWorldData2, checkLocalWorldData: checkLocalWorldData2 } = await Promise.resolve().then(() => (init_data(), data_exports));
9543
10614
  if (options.transform !== void 0 && options.map !== void 0) throw new Error("records go through one of transform, map");
9544
10615
  const redact = options.redact ?? "off";
9545
10616
  const mode = options.mode ?? "append";
9546
10617
  const dryRun = Boolean(options.dryRun);
9547
- const creds = platformEndpoint(options);
9548
10618
  const local = fs12.existsSync(world) && fs12.statSync(world).isDirectory();
10619
+ const creds = local ? await runtimeEndpoint(options) : platformEndpoint(options);
9549
10620
  const map = options.map === void 0 ? void 0 : options.map;
9550
10621
  let rows = null;
9551
10622
  let stderr = "";
@@ -9643,6 +10714,7 @@ var init_ingest = __esm({
9643
10714
  "use strict";
9644
10715
  init_worlds();
9645
10716
  init_platformEndpoint();
10717
+ init_personalToken();
9646
10718
  isObject2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
9647
10719
  isoOf = (value) => value instanceof Date ? value.toISOString() : typeof value === "string" ? value : void 0;
9648
10720
  }
@@ -9700,6 +10772,38 @@ var init_editSessions = __esm({
9700
10772
  }
9701
10773
  });
9702
10774
 
10775
+ // src/worlds/states.ts
10776
+ var WORLDS3, refQuery, WorldStateClient;
10777
+ var init_states = __esm({
10778
+ "src/worlds/states.ts"() {
10779
+ "use strict";
10780
+ init_worlds();
10781
+ WORLDS3 = "/api/public/worlds";
10782
+ refQuery = (ref) => ref ? `?${new URLSearchParams({ ref })}` : "";
10783
+ WorldStateClient = class {
10784
+ constructor(options = {}) {
10785
+ this.options = options;
10786
+ }
10787
+ options;
10788
+ list(slug) {
10789
+ return apiRequest(this.options, "GET", `${WORLDS3}/${encodeURIComponent(slug)}/states`);
10790
+ }
10791
+ show(slug, name, ref) {
10792
+ return apiRequest(this.options, "GET", `${WORLDS3}/${encodeURIComponent(slug)}/states/${encodeURIComponent(name)}` + refQuery(ref));
10793
+ }
10794
+ create(slug, input) {
10795
+ return apiRequest(this.options, "POST", `${WORLDS3}/${encodeURIComponent(slug)}/states`, input);
10796
+ }
10797
+ delete(slug, name) {
10798
+ return apiRequest(this.options, "DELETE", `${WORLDS3}/${encodeURIComponent(slug)}/states/${encodeURIComponent(name)}`);
10799
+ }
10800
+ pull(slug, name, ref) {
10801
+ return apiRequest(this.options, "GET", `${WORLDS3}/${encodeURIComponent(slug)}/states/${encodeURIComponent(name)}/pull` + refQuery(ref));
10802
+ }
10803
+ };
10804
+ }
10805
+ });
10806
+
9703
10807
  // src/worlds/dryRun.ts
9704
10808
  var DRY_RUN_KIND, DRY_RUN_AGENT, STATUS_WAIT_CAP_SECONDS, cid, HostedDryRunClient, DryRunOutcome;
9705
10809
  var init_dryRun = __esm({
@@ -9833,9 +10937,14 @@ __export(worlds_exports, {
9833
10937
  OpenAIComputer: () => OpenAIComputer,
9834
10938
  OpenAIPreviewComputer: () => OpenAIPreviewComputer,
9835
10939
  PLATFORM_SESSION_HEADER: () => PLATFORM_SESSION_HEADER,
10940
+ PLATFORM_STREAM_IDLE_MS: () => PLATFORM_STREAM_IDLE_MS,
9836
10941
  PLATFORM_TIMEOUT_DEFAULT_MS: () => PLATFORM_TIMEOUT_DEFAULT_MS,
9837
10942
  PLATFORM_TIMEOUT_ENV: () => PLATFORM_TIMEOUT_ENV,
10943
+ PageObserver: () => PageObserver,
10944
+ PageState: () => PageState,
10945
+ PageStateError: () => PageStateError,
9838
10946
  PendingSafetyChecks: () => PendingSafetyChecks,
10947
+ PlatformStream: () => PlatformStream,
9839
10948
  PlatformTransport: () => PlatformTransport,
9840
10949
  PushSlugConflict: () => PushSlugConflict,
9841
10950
  RECOVER_BUDGET_MS: () => RECOVER_BUDGET_MS,
@@ -9888,6 +10997,7 @@ __export(worlds_exports, {
9888
10997
  WorldSessionOpenFailed: () => WorldSessionOpenFailed,
9889
10998
  WorldSessionTimeout: () => WorldSessionTimeout,
9890
10999
  WorldSet: () => WorldSet,
11000
+ WorldStateClient: () => WorldStateClient,
9891
11001
  WorldSurfaceUnavailable: () => WorldSurfaceUnavailable,
9892
11002
  WorldTask: () => WorldTask,
9893
11003
  WorldToolsUnread: () => WorldToolsUnread,
@@ -9955,6 +11065,7 @@ __export(worlds_exports, {
9955
11065
  parseToolCallRecord: () => parseToolCallRecord,
9956
11066
  parseTransform: () => parseTransform,
9957
11067
  parseWorldTaskRefs: () => parseWorldTaskRefs,
11068
+ platformAuthorization: () => platformAuthorization,
9958
11069
  platformTimeoutMs: () => platformTimeoutMs,
9959
11070
  playwrightKey: () => playwrightKey,
9960
11071
  preserveForm: () => preserveForm,
@@ -9981,6 +11092,7 @@ __export(worlds_exports, {
9981
11092
  runSet: () => runSet,
9982
11093
  runTask: () => runTask,
9983
11094
  schemaFromSignature: () => schemaFromSignature,
11095
+ scrubError: () => scrubError,
9984
11096
  serializeCallBody: () => serializeCallBody,
9985
11097
  sessionToolObservations: () => sessionToolObservations,
9986
11098
  setEnvSecret: () => setEnvSecret,
@@ -10008,43 +11120,8 @@ __export(worlds_exports, {
10008
11120
  worldRequestsUnrecorded: () => worldRequestsUnrecorded,
10009
11121
  writeLocalMeta: () => writeLocalMeta
10010
11122
  });
10011
- function edgeAnswer(text2, status) {
10012
- if (status !== void 0 && status >= 500) return EDGE_ANSWERS[status] ?? EDGE_FAILURE;
10013
- return /^\s*</.test(text2) ? EDGE_PAGE : null;
10014
- }
10015
- function parseErrorBody(text2, status) {
10016
- const raw = { detail: text2.slice(0, DETAIL_LIMIT), code: null };
10017
- let parsed;
10018
- try {
10019
- parsed = JSON.parse(text2);
10020
- } catch {
10021
- return { detail: (edgeAnswer(text2, status) ?? text2).slice(0, DETAIL_LIMIT), code: null };
10022
- }
10023
- if (parsed === null || typeof parsed !== "object") return raw;
10024
- const { message, code, error } = parsed;
10025
- const stableCode = typeof code === "string" ? code : null;
10026
- if (typeof message !== "string") return { ...raw, code: stableCode };
10027
- const fields = invalidFields(error);
10028
- const said = fields ? `${message}: ${fields}` : message;
10029
- if (stableCode === null) return { detail: said.slice(0, DETAIL_LIMIT), code: null };
10030
- return {
10031
- detail: `${said} (${stableCode})`.slice(0, DETAIL_LIMIT),
10032
- code: stableCode
10033
- };
10034
- }
10035
- function invalidFields(error) {
10036
- const issues = Array.isArray(error) ? error : [];
10037
- return issues.filter(
10038
- (issue) => issue !== null && typeof issue === "object" && typeof issue.message === "string"
10039
- ).map((issue) => {
10040
- const path13 = Array.isArray(issue.path) ? issue.path.map(String).join(".") : "";
10041
- return path13 ? `${path13}: ${issue.message}` : issue.message;
10042
- }).join("; ");
10043
- }
10044
11123
  async function apiRequest(options, method, path13, body, init2 = {}) {
10045
- const reply = await new PlatformTransport(requirePlatformEndpoint(options)).send(method, path13, body, init2);
10046
- if (!reply.ok) throw new ApiError(reply.status, method, path13, reply.text);
10047
- return JSON.parse(reply.text);
11124
+ return new PlatformTransport(requirePlatformEndpoint(options)).json(method, path13, body, init2);
10048
11125
  }
10049
11126
  async function setEnvSecret(slug, key, value, options = {}) {
10050
11127
  return apiRequest(
@@ -10219,11 +11296,12 @@ async function resolveWorld(slugRef, slug, ref, pin, options) {
10219
11296
  }
10220
11297
  return world;
10221
11298
  }
10222
- var ApiError, DETAIL_LIMIT, EDGE_ANSWERS, EDGE_FAILURE, EDGE_PAGE, WorldTask, WorldSet;
11299
+ var WorldTask, WorldSet;
10223
11300
  var init_worlds = __esm({
10224
11301
  "src/worlds/index.ts"() {
10225
11302
  init_platformEndpoint();
10226
11303
  init_transport();
11304
+ init_apiError();
10227
11305
  init_transport();
10228
11306
  init_session2();
10229
11307
  init_grade();
@@ -10238,6 +11316,8 @@ var init_worlds = __esm({
10238
11316
  init_checkoutProvenance();
10239
11317
  init_evals();
10240
11318
  init_browser();
11319
+ init_browserTools();
11320
+ init_pageState();
10241
11321
  init_surfaceDescriptor();
10242
11322
  init_requestLog();
10243
11323
  init_requestLedger();
@@ -10254,29 +11334,9 @@ var init_worlds = __esm({
10254
11334
  init_ingest();
10255
11335
  init_sandbox();
10256
11336
  init_editSessions();
11337
+ init_states();
10257
11338
  init_dryRun();
10258
11339
  init_worldNotice();
10259
- ApiError = class extends Error {
10260
- constructor(status, method, path13, text2) {
10261
- const parsed = parseErrorBody(text2, status);
10262
- super(`${method} ${path13} -> ${status}: ${parsed.detail}`);
10263
- this.status = status;
10264
- this.text = text2;
10265
- this.name = "ApiError";
10266
- this.code = parsed.code;
10267
- }
10268
- status;
10269
- text;
10270
- code;
10271
- };
10272
- DETAIL_LIMIT = 600;
10273
- EDGE_ANSWERS = {
10274
- 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.",
10275
- 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.",
10276
- 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."
10277
- };
10278
- 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.";
10279
- 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.";
10280
11340
  WorldTask = class {
10281
11341
  constructor(world, name, variant) {
10282
11342
  this.world = world;
@@ -10385,9 +11445,14 @@ export {
10385
11445
  OpenAIComputer,
10386
11446
  OpenAIPreviewComputer,
10387
11447
  PLATFORM_SESSION_HEADER,
11448
+ PLATFORM_STREAM_IDLE_MS,
10388
11449
  PLATFORM_TIMEOUT_DEFAULT_MS,
10389
11450
  PLATFORM_TIMEOUT_ENV,
11451
+ PageObserver,
11452
+ PageState,
11453
+ PageStateError,
10390
11454
  PendingSafetyChecks,
11455
+ PlatformStream,
10391
11456
  PlatformTransport,
10392
11457
  PushSlugConflict,
10393
11458
  RECOVER_BUDGET_MS,
@@ -10440,6 +11505,7 @@ export {
10440
11505
  WorldSessionOpenFailed,
10441
11506
  WorldSessionTimeout,
10442
11507
  WorldSet,
11508
+ WorldStateClient,
10443
11509
  WorldSurfaceUnavailable,
10444
11510
  WorldTask,
10445
11511
  WorldToolsUnread,
@@ -10507,6 +11573,7 @@ export {
10507
11573
  parseToolCallRecord,
10508
11574
  parseTransform,
10509
11575
  parseWorldTaskRefs,
11576
+ platformAuthorization,
10510
11577
  platformTimeoutMs,
10511
11578
  playwrightKey,
10512
11579
  preserveForm,
@@ -10533,6 +11600,7 @@ export {
10533
11600
  runSet,
10534
11601
  runTask,
10535
11602
  schemaFromSignature,
11603
+ scrubError,
10536
11604
  serializeCallBody,
10537
11605
  sessionToolObservations,
10538
11606
  setEnvSecret,