@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
@@ -42,13 +42,77 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
42
42
  ));
43
43
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
44
44
 
45
+ // src/worlds/personalToken.ts
46
+ 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;
47
+ var init_personalToken = __esm({
48
+ "src/worlds/personalToken.ts"() {
49
+ "use strict";
50
+ TOKEN_NOT_PERSONAL = "GATEWAY_TOKEN takes a personal access token: pat_ followed by letters and digits only.";
51
+ TOKEN_NEEDS_PROJECT = "GATEWAY_TOKEN acts in the project GATEWAY_PROJECT_ID names: set it to the official project's id (letters, digits, - and _).";
52
+ TOKEN_NEEDS_HOST = "GATEWAY_TOKEN goes only to the host GATEWAY_HOST names: set GATEWAY_HOST.";
53
+ 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.";
54
+ 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.";
55
+ 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).";
56
+ TOKEN_KEYS_ONLY = "Task-run tracing exports with a project key pair (GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY), not GATEWAY_TOKEN.";
57
+ PERSONAL = /^pat_[A-Za-z0-9]+$/;
58
+ PROJECT = /^[A-Za-z0-9_-]+$/;
59
+ ENV_KEYS = ["GATEWAY_PUBLIC_KEY", "GATEWAY_SECRET_KEY", "GATEWAY_API_KEY"];
60
+ PersonalTokenRefused = class extends Error {
61
+ };
62
+ bare = (host) => host.replace(/\/+$/, "");
63
+ PersonalToken = class _PersonalToken {
64
+ constructor(value, project, host) {
65
+ this.value = value;
66
+ this.project = project;
67
+ this.host = host;
68
+ }
69
+ value;
70
+ project;
71
+ host;
72
+ static fromEnv(env, request = {}) {
73
+ const value = env.GATEWAY_TOKEN;
74
+ if (!value) return null;
75
+ if (request.keys || ENV_KEYS.some((name) => env[name])) throw new PersonalTokenRefused(TOKEN_BESIDE_KEYS);
76
+ const host = bare(env.GATEWAY_HOST ?? "");
77
+ if (!host) throw new PersonalTokenRefused(TOKEN_NEEDS_HOST);
78
+ if (request.host && bare(request.host) !== host) throw new PersonalTokenRefused(TOKEN_OTHER_HOST);
79
+ if (!PERSONAL.test(value)) throw new PersonalTokenRefused(TOKEN_NOT_PERSONAL);
80
+ const project = env.GATEWAY_PROJECT_ID ?? "";
81
+ if (!PROJECT.test(project)) throw new PersonalTokenRefused(TOKEN_NEEDS_PROJECT);
82
+ return new _PersonalToken(value, project, host);
83
+ }
84
+ toJSON() {
85
+ return { project: this.project, host: this.host };
86
+ }
87
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
88
+ return `PersonalToken { project: ${this.project}, host: ${this.host} }`;
89
+ }
90
+ static scrubbed(env) {
91
+ return Object.fromEntries(Object.entries(env).filter(([key]) => key !== "GATEWAY_TOKEN"));
92
+ }
93
+ };
94
+ }
95
+ });
96
+
45
97
  // src/worlds/platformEndpoint.ts
46
98
  function platformEndpoint(options) {
99
+ if (options.token)
100
+ return {
101
+ host: (options.host ?? options.token.host).replace(/\/+$/, ""),
102
+ publicKey: options.publicKey ?? "",
103
+ secretKey: options.secretKey ?? "",
104
+ token: options.token
105
+ };
106
+ const token = PersonalToken.fromEnv(process.env, {
107
+ host: options.host,
108
+ keys: Boolean(options.publicKey || options.secretKey)
109
+ });
110
+ if (token) return { host: token.host, publicKey: "", secretKey: "", token };
111
+ const host = (options.host ?? process.env.GATEWAY_HOST ?? DEFAULT_HOST).replace(/\/+$/, "");
47
112
  const publicKey = options.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;
48
113
  const secretKey = options.secretKey ?? process.env.GATEWAY_SECRET_KEY;
49
114
  if (!publicKey || !secretKey) return null;
50
- const host = options.host ?? process.env.GATEWAY_HOST ?? DEFAULT_HOST;
51
- return { host: host.replace(/\/+$/, ""), publicKey, secretKey };
115
+ return { host, publicKey, secretKey };
52
116
  }
53
117
  function requirePlatformEndpoint(options) {
54
118
  const endpoint = platformEndpoint(options);
@@ -59,11 +123,74 @@ var DEFAULT_HOST, GATEWAY_KEYS_MISSING;
59
123
  var init_platformEndpoint = __esm({
60
124
  "src/worlds/platformEndpoint.ts"() {
61
125
  "use strict";
126
+ init_personalToken();
62
127
  DEFAULT_HOST = "https://withgateway.ai";
63
128
  GATEWAY_KEYS_MISSING = "Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY (or pass publicKey/secretKey).";
64
129
  }
65
130
  });
66
131
 
132
+ // src/worlds/apiError.ts
133
+ function edgeAnswer(text2, status) {
134
+ if (status !== void 0 && status >= 500) return EDGE_ANSWERS[status] ?? EDGE_FAILURE;
135
+ return /^\s*</.test(text2) ? EDGE_PAGE : null;
136
+ }
137
+ function parseErrorBody(text2, status) {
138
+ const raw = { detail: text2.slice(0, DETAIL_LIMIT), code: null };
139
+ let parsed;
140
+ try {
141
+ parsed = JSON.parse(text2);
142
+ } catch {
143
+ return { detail: (edgeAnswer(text2, status) ?? text2).slice(0, DETAIL_LIMIT), code: null };
144
+ }
145
+ if (parsed === null || typeof parsed !== "object") return raw;
146
+ const { message, code, error } = parsed;
147
+ const stableCode = typeof code === "string" ? code : null;
148
+ if (typeof message !== "string") return { ...raw, code: stableCode };
149
+ const fields = invalidFields(error);
150
+ const said = fields ? `${message}: ${fields}` : message;
151
+ if (stableCode === null) return { detail: said.slice(0, DETAIL_LIMIT), code: null };
152
+ return {
153
+ detail: `${said} (${stableCode})`.slice(0, DETAIL_LIMIT),
154
+ code: stableCode
155
+ };
156
+ }
157
+ function invalidFields(error) {
158
+ const issues = Array.isArray(error) ? error : [];
159
+ return issues.filter(
160
+ (issue) => issue !== null && typeof issue === "object" && typeof issue.message === "string"
161
+ ).map((issue) => {
162
+ const path13 = Array.isArray(issue.path) ? issue.path.map(String).join(".") : "";
163
+ return path13 ? `${path13}: ${issue.message}` : issue.message;
164
+ }).join("; ");
165
+ }
166
+ var ApiError, DETAIL_LIMIT, EDGE_ANSWERS, EDGE_FAILURE, EDGE_PAGE;
167
+ var init_apiError = __esm({
168
+ "src/worlds/apiError.ts"() {
169
+ "use strict";
170
+ ApiError = class extends Error {
171
+ constructor(status, method, path13, text2) {
172
+ const parsed = parseErrorBody(text2, status);
173
+ super(`${method} ${path13} -> ${status}: ${parsed.detail}`);
174
+ this.status = status;
175
+ this.text = text2;
176
+ this.name = "ApiError";
177
+ this.code = parsed.code;
178
+ }
179
+ status;
180
+ text;
181
+ code;
182
+ };
183
+ DETAIL_LIMIT = 600;
184
+ EDGE_ANSWERS = {
185
+ 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.",
186
+ 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.",
187
+ 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."
188
+ };
189
+ 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.";
190
+ 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.";
191
+ }
192
+ });
193
+
67
194
  // src/worlds/transport.ts
68
195
  function platformTimeoutMs(env = process.env) {
69
196
  const raw = env[PLATFORM_TIMEOUT_ENV];
@@ -72,10 +199,20 @@ function platformTimeoutMs(env = process.env) {
72
199
  if (Number.isInteger(value) && value > 0) return value;
73
200
  throw new Error(`${PLATFORM_TIMEOUT_ENV} must be a positive whole number of milliseconds, not \`${raw}\`.`);
74
201
  }
75
- var PLATFORM_TIMEOUT_ENV, PLATFORM_TIMEOUT_DEFAULT_MS, CHECK_HOST, RETRY, FETCH_LIMIT, CAUSES, UNKNOWN_CAUSE, TransportCause, UnreachableError, sleep, RetryPolicy, Attempt, PlatformTransport;
202
+ function platformAuthorization(endpoint, url) {
203
+ const { token } = endpoint;
204
+ if (!token)
205
+ return { authorization: "Basic " + Buffer.from(`${endpoint.publicKey}:${endpoint.secretKey}`).toString("base64") };
206
+ if (endpoint.publicKey || endpoint.secretKey) throw new PersonalTokenRefused(TOKEN_BESIDE_KEYS);
207
+ if (!url.startsWith(`${token.host}/`)) throw new PersonalTokenRefused(TOKEN_OTHER_HOST);
208
+ return { authorization: `Bearer ${token.value}`, "x-gateway-project": token.project };
209
+ }
210
+ 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;
76
211
  var init_transport = __esm({
77
212
  "src/worlds/transport.ts"() {
78
213
  "use strict";
214
+ init_apiError();
215
+ init_personalToken();
79
216
  PLATFORM_TIMEOUT_ENV = "GATEWAY_TIMEOUT_MS";
80
217
  PLATFORM_TIMEOUT_DEFAULT_MS = 12e4;
81
218
  CHECK_HOST = "Check GATEWAY_HOST (or --host) points at a running platform, then retry.";
@@ -115,6 +252,13 @@ var init_transport = __esm({
115
252
  `Retry; if the platform is slow, raise ${PLATFORM_TIMEOUT_ENV} (milliseconds per request).`
116
253
  );
117
254
  }
255
+ static idle(idleMs) {
256
+ return new _TransportCause(
257
+ `no data for ${idleMs / 1e3}s`,
258
+ null,
259
+ "The stream resumes from its last event; if it repeats, check the network between here and the platform."
260
+ );
261
+ }
118
262
  static of(error) {
119
263
  const cause = error instanceof Error && error.cause instanceof Error ? error.cause : void 0;
120
264
  const code = cause && "code" in cause && typeof cause.code === "string" ? cause.code : null;
@@ -190,45 +334,277 @@ var init_transport = __esm({
190
334
  throw this.error;
191
335
  }
192
336
  };
337
+ PLATFORM_STREAM_IDLE_MS = 6e4;
338
+ REFUSAL_TEXT_LIMIT = 64 * 1024;
339
+ KEYED_REDIRECTS = "manual";
193
340
  PlatformTransport = class {
341
+ #endpoint;
342
+ #timeoutMs;
194
343
  constructor(endpoint, timeoutMs = platformTimeoutMs()) {
195
- this.endpoint = endpoint;
196
- this.timeoutMs = timeoutMs;
344
+ this.#endpoint = endpoint;
345
+ this.#timeoutMs = timeoutMs;
197
346
  }
198
- endpoint;
199
- timeoutMs;
200
347
  /** A request that legitimately takes longer (a sandbox exec, a world create) waits its own budget; every other one waits the default. */
201
348
  budget(ownMs) {
202
- return Math.max(ownMs ?? 0, this.timeoutMs);
349
+ return Math.max(ownMs ?? 0, this.#timeoutMs);
203
350
  }
351
+ /** One request; the caller's `signal` aborts it in flight and throws the signal's reason, never an `UnreachableError`. */
204
352
  async send(method, route2, body, opts = {}) {
205
353
  const timeoutMs = this.budget(opts.timeoutMs);
206
- return (opts.retry ?? RetryPolicy.NONE).run(() => this.once(method, route2, body, timeoutMs));
354
+ return (opts.retry ?? RetryPolicy.NONE).run(() => this.once(method, route2, body, timeoutMs, opts.signal));
355
+ }
356
+ /** `send`, then the 2xx body as JSON; any other answer throws `ApiError` with its status and stable `code`. */
357
+ async json(method, route2, body, opts = {}) {
358
+ const reply = await this.send(method, route2, body, opts);
359
+ if (!reply.ok) throw new ApiError(reply.status, method, route2, reply.text);
360
+ return JSON.parse(reply.text);
361
+ }
362
+ /** 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. */
363
+ async stream(route2, opts = {}) {
364
+ const watch = new StreamWatch(opts.signal, opts.idleMs ?? PLATFORM_STREAM_IDLE_MS, this.#endpoint.host, route2);
365
+ const headers = this.headers(route2, "text/event-stream", opts.after ? { "last-event-id": opts.after } : {});
366
+ try {
367
+ const response = await watch.within(
368
+ () => fetch(this.url(route2), { method: "GET", headers, signal: watch.signal, redirect: KEYED_REDIRECTS })
369
+ );
370
+ return new PlatformStream(response, watch);
371
+ } catch (error) {
372
+ watch.close();
373
+ throw error;
374
+ }
375
+ }
376
+ url(route2) {
377
+ return `${this.#endpoint.host}${route2}`;
207
378
  }
208
- async once(method, route2, body, timeoutMs) {
379
+ headers(route2, accept, extra = {}) {
380
+ return {
381
+ "content-type": "application/json",
382
+ accept,
383
+ ...platformAuthorization(this.#endpoint, this.url(route2)),
384
+ ...extra
385
+ };
386
+ }
387
+ async once(method, route2, body, timeoutMs, caller) {
388
+ if (caller?.aborted) throw caller.reason;
209
389
  const payload = body === void 0 ? {} : { body: JSON.stringify(body) };
390
+ const headers = this.headers(route2, "application/json");
210
391
  const controller = new AbortController();
211
392
  const timer = setTimeout(() => controller.abort(), timeoutMs);
393
+ const relay = () => controller.abort(caller?.reason);
394
+ caller?.addEventListener("abort", relay, { once: true });
212
395
  try {
213
- const res = await fetch(`${this.endpoint.host}${route2}`, {
396
+ const res = await fetch(this.url(route2), {
214
397
  method,
215
- headers: {
216
- "content-type": "application/json",
217
- accept: "application/json",
218
- authorization: "Basic " + Buffer.from(`${this.endpoint.publicKey}:${this.endpoint.secretKey}`).toString("base64")
219
- },
398
+ headers,
220
399
  ...payload,
221
- signal: controller.signal
400
+ signal: controller.signal,
401
+ redirect: KEYED_REDIRECTS
222
402
  });
223
403
  return { status: res.status, ok: res.ok, text: await res.text() };
224
404
  } catch (error) {
405
+ if (caller?.aborted) throw caller.reason;
225
406
  const cause = controller.signal.aborted ? TransportCause.timeout(timeoutMs) : TransportCause.of(error);
226
- throw new UnreachableError(this.endpoint.host, method, route2, cause);
407
+ throw new UnreachableError(this.#endpoint.host, method, route2, cause);
408
+ } finally {
409
+ clearTimeout(timer);
410
+ caller?.removeEventListener("abort", relay);
411
+ }
412
+ }
413
+ };
414
+ StreamWatch = class {
415
+ constructor(caller, idleMs, host, route2) {
416
+ this.idleMs = idleMs;
417
+ this.host = host;
418
+ this.route = route2;
419
+ this.#caller = caller;
420
+ caller?.addEventListener("abort", this.#relay, { once: true });
421
+ if (caller?.aborted) this.#relay();
422
+ }
423
+ idleMs;
424
+ host;
425
+ route;
426
+ #controller = new AbortController();
427
+ #caller;
428
+ #relay = () => this.#controller.abort(this.#caller?.reason);
429
+ #idled = false;
430
+ get signal() {
431
+ return this.#controller.signal;
432
+ }
433
+ async within(wait) {
434
+ const timer = setTimeout(() => this.idle(), this.idleMs);
435
+ try {
436
+ return await wait();
437
+ } catch (error) {
438
+ throw this.failure(error);
227
439
  } finally {
228
440
  clearTimeout(timer);
229
441
  }
230
442
  }
443
+ close() {
444
+ this.#caller?.removeEventListener("abort", this.#relay);
445
+ this.#controller.abort();
446
+ }
447
+ idle() {
448
+ this.#idled = true;
449
+ this.#controller.abort();
450
+ }
451
+ failure(error) {
452
+ if (this.#caller?.aborted) return this.#caller.reason;
453
+ const cause = this.#idled ? TransportCause.idle(this.idleMs) : TransportCause.of(error);
454
+ return new UnreachableError(this.host, "GET", this.route, cause);
455
+ }
456
+ };
457
+ PlatformStream = class {
458
+ #response;
459
+ #watch;
460
+ constructor(response, watch) {
461
+ this.#response = response;
462
+ this.#watch = watch;
463
+ }
464
+ get status() {
465
+ return this.#response.status;
466
+ }
467
+ get ok() {
468
+ return this.#response.ok;
469
+ }
470
+ /** The body as text, for a refusal: at most the first 64 KiB of characters; closes the stream. */
471
+ async text() {
472
+ const decoder = new TextDecoder();
473
+ let text2 = "";
474
+ for await (const chunk of this.chunks()) {
475
+ text2 += decoder.decode(chunk, { stream: true });
476
+ if (text2.length >= REFUSAL_TEXT_LIMIT) return text2.slice(0, REFUSAL_TEXT_LIMIT);
477
+ }
478
+ return text2 + decoder.decode();
479
+ }
480
+ /** The body's bytes as they arrive; the idle budget runs only while waiting for the platform, never while the caller holds a chunk. */
481
+ async *chunks() {
482
+ const reader = this.#response.body?.getReader();
483
+ try {
484
+ for (; ; ) {
485
+ const next = reader ? await this.#watch.within(() => reader.read()) : { done: true };
486
+ if (next.done) return;
487
+ yield next.value;
488
+ }
489
+ } finally {
490
+ this.close();
491
+ }
492
+ }
493
+ close() {
494
+ this.#watch.close();
495
+ }
496
+ };
497
+ }
498
+ });
499
+
500
+ // src/worlds/credentialField.ts
501
+ function isCredentialField(described) {
502
+ const words = described.replace(SPACES, " ").replace(/^ | $/g, "");
503
+ return SECRET_FIELD.some((prefix) => words.startsWith(prefix)) || SECRET_KEY.test(words);
504
+ }
505
+ function credentialTexts(pairs) {
506
+ return pairs.filter(([, text2]) => text2 !== null && text2 !== void 0).filter(([described]) => isCredentialField(String(described))).map(([, text2]) => String(text2));
507
+ }
508
+ function isTextField(described) {
509
+ return described !== "" && !NOT_TEXT.some((prefix) => described.startsWith(prefix));
510
+ }
511
+ function redactActionArgs(action, args) {
512
+ const secretField = action === "browser_type" && SECRET_KEY.test(String(args.selector ?? ""));
513
+ return Object.fromEntries(
514
+ Object.entries(args).map(([key, value]) => [
515
+ key,
516
+ redactedArg(key, value, secretField)
517
+ ])
518
+ );
519
+ }
520
+ function redactedArg(key, value, secretField) {
521
+ if (value === null || value === void 0) return null;
522
+ if (typeof value === "boolean" || typeof value === "number") return value;
523
+ if (typeof value !== "string") return "[omitted]";
524
+ if (SECRET_KEY.test(key) || SECRET_VALUE.test(value) || secretField && key === "text")
525
+ return "[redacted]";
526
+ return value.length <= EVENT_MAX_STRING ? value : value.slice(0, EVENT_MAX_STRING) + "\u2026";
527
+ }
528
+ 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;
529
+ var init_credentialField = __esm({
530
+ "src/worlds/credentialField.ts"() {
531
+ "use strict";
532
+ 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;
533
+ 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(' '); }";
534
+ 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; }";
535
+ 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])";
536
+ SHORTEST_WITHHELD = 4;
537
+ WITHHELD_TEXT = "[redacted]";
538
+ SPACES = /[ \t\n\r\f\v]+/g;
539
+ LINE_BREAK = /\r\n|\r|\n/;
540
+ TRIM = /^[ \t\n\r\f\v]+|[ \t\n\r\f\v]+$/g;
541
+ describeField = new Function(
542
+ "e",
543
+ `return (${DESCRIBE_FIELD_JS})(e);`
544
+ );
545
+ readFieldValue = new Function(
546
+ "e",
547
+ `return (${FIELD_VALUE_JS})(e);`
548
+ );
549
+ readEditables = new Function(
550
+ "elements",
551
+ `return elements.map((e) => [(${DESCRIBE_FIELD_JS})(e), (${FIELD_VALUE_JS})(e)]);`
552
+ );
553
+ UNREADABLE = "unreadable";
554
+ SECRET_FIELD = ["password", "frame", "opaque", UNREADABLE];
555
+ NOT_TEXT = ["opaque", "frame", "select"];
556
+ escapeRegExp = (text2) => text2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
557
+ urlForms = (text2) => {
558
+ let component;
559
+ try {
560
+ component = encodeURIComponent(text2);
561
+ } catch {
562
+ return [];
563
+ }
564
+ const form = component.replace(
565
+ /[!'()~]/g,
566
+ (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase()
567
+ ).replace(/%20/g, "+");
568
+ return [component, component.replace(/%20/g, "+"), form];
569
+ };
570
+ forms = (text2) => {
571
+ const written = [
572
+ text2,
573
+ text2.replace(SPACES, " "),
574
+ JSON.stringify(text2).slice(1, -1)
575
+ ];
576
+ return [
577
+ ...written,
578
+ ...written.map((form) => form.replaceAll("'", "''")),
579
+ ...urlForms(text2)
580
+ ];
231
581
  };
582
+ CredentialText = class {
583
+ pattern;
584
+ constructor(secrets) {
585
+ const texts = secrets.map((secret) => String(secret).replace(TRIM, ""));
586
+ const lines = texts.flatMap(
587
+ (text2) => text2.split(LINE_BREAK).map((line) => line.replace(TRIM, ""))
588
+ );
589
+ const whole = new Set(
590
+ [...texts, ...lines].filter(
591
+ (text2) => [...text2].length >= SHORTEST_WITHHELD
592
+ )
593
+ );
594
+ const withheld = [
595
+ ...new Set([...whole].flatMap((text2) => forms(text2)))
596
+ ].sort((a, b) => b.length - a.length);
597
+ this.pattern = withheld.length === 0 ? null : new RegExp(
598
+ `(?<![A-Za-z0-9])(?:${withheld.map(escapeRegExp).join("|")})(?![A-Za-z0-9])`,
599
+ "g"
600
+ );
601
+ }
602
+ withhold(text2) {
603
+ return this.pattern === null ? text2 : text2.replace(this.pattern, WITHHELD_TEXT);
604
+ }
605
+ };
606
+ EVENT_MAX_STRING = 500;
607
+ SECRET_VALUE = /^((sk|pk|ghp|xox[abp])[-_][-_A-Za-z0-9]{8,}|AKIA[0-9A-Z]{12,}|Bearer [-_.A-Za-z0-9]{8,})/;
232
608
  }
233
609
  });
234
610
 
@@ -245,6 +621,25 @@ function isBrowserGone(error) {
245
621
  if (PAGE_NETWORK_ERROR.test(message)) return false;
246
622
  return BROWSER_GONE_PATTERNS.some((p) => p.test(message));
247
623
  }
624
+ function scrubError(error, scrub) {
625
+ const seen = /* @__PURE__ */ new Set();
626
+ let at = error;
627
+ while (at instanceof Error && !seen.has(at)) {
628
+ seen.add(at);
629
+ at.message = scrub(at.message);
630
+ at.stack = at.stack && scrub(at.stack);
631
+ scrubOwnText(at, scrub);
632
+ at = at.cause;
633
+ }
634
+ }
635
+ function scrubOwnText(error, scrub) {
636
+ for (const key of Object.keys(error)) {
637
+ const value = error[key];
638
+ if (typeof value === "string") error[key] = scrub(value);
639
+ if (Array.isArray(value) && value.every((item) => typeof item === "string"))
640
+ error[key] = value.map((item) => scrub(item));
641
+ }
642
+ }
248
643
  function refusalIsTransient(error) {
249
644
  const { status, code } = error;
250
645
  if (typeof status !== "number") return true;
@@ -281,11 +676,17 @@ var init_browserReconnect = __esm({
281
676
  ].sort((a, b) => b.length - a.length);
282
677
  }
283
678
  scrub(text2) {
284
- const bare = this.secrets.reduce(
679
+ const bare2 = this.secrets.reduce(
285
680
  (out, secret) => out.split(secret).join(REDACTED),
286
681
  text2
287
682
  );
288
- return bare.replace(TOKEN_QUERY_VALUE, `$1${REDACTED}`);
683
+ return bare2.replace(TOKEN_QUERY_VALUE, `$1${REDACTED}`);
684
+ }
685
+ /** Scrub `error` and the errors it was raised from, in place: the message,
686
+ * the stack and every other own text property, Playwright's `log` call log
687
+ * included. */
688
+ scrubError(error) {
689
+ scrubError(error, (text2) => this.scrub(text2));
289
690
  }
290
691
  };
291
692
  BrowserReconnected = class extends Error {
@@ -437,22 +838,6 @@ function capabilityLabel(url) {
437
838
  }
438
839
  return CAPABILITY_HOST.exec(host)?.[1] ?? null;
439
840
  }
440
- function redactActionArgs(action, args) {
441
- const secretField = action === "browser_type" && SECRET_KEY.test(String(args.selector ?? ""));
442
- const out = {};
443
- for (const [key, value] of Object.entries(args)) {
444
- if (value === null || value === void 0) out[key] = null;
445
- else if (typeof value === "boolean" || typeof value === "number")
446
- out[key] = value;
447
- else if (typeof value === "string") {
448
- if (SECRET_KEY.test(key) || SECRET_VALUE.test(value) || secretField && key === "text")
449
- out[key] = "[redacted]";
450
- else
451
- out[key] = value.length <= EVENT_MAX_STRING ? value : value.slice(0, EVENT_MAX_STRING) + "\u2026";
452
- } else out[key] = "[omitted]";
453
- }
454
- return out;
455
- }
456
841
  async function loadPlaywright() {
457
842
  try {
458
843
  const name = "playwright";
@@ -514,62 +899,14 @@ async function openBrowser(surfaces, opts = {}) {
514
899
  scrubber
515
900
  );
516
901
  }
517
- function computerUseToolkit(browser, opts = {}) {
518
- const maxText = opts.maxText ?? 2e4;
519
- const observe = async (selector = "body") => {
520
- const text2 = await browser.text(selector);
521
- return {
522
- url: browser.url,
523
- title: await browser.title(),
524
- text: text2.slice(0, maxText),
525
- truncated: text2.length > maxText
526
- };
527
- };
528
- const impls = {
529
- browser_goto: async (a) => {
530
- await browser.goto(typeof a.path === "string" ? a.path : void 0);
531
- return observe();
532
- },
533
- browser_click: async (a) => {
534
- await browser.click(str(a.selector, ""));
535
- return observe();
536
- },
537
- browser_type: async (a) => {
538
- await browser.type(str(a.selector, ""), String(a.text ?? ""));
539
- return { ok: true, url: browser.url };
540
- },
541
- browser_press: async (a) => {
542
- await browser.press(str(a.key, "Enter"));
543
- return observe();
544
- },
545
- browser_scroll: async (a) => {
546
- await browser.scroll(typeof a.dy === "number" ? a.dy : 600);
547
- return { ok: true, url: browser.url };
548
- },
549
- browser_screenshot: async (a) => ({
550
- image_base64: await browser.screenshotBase64(a.full_page === true),
551
- url: browser.url
552
- }),
553
- browser_read: async (a) => observe(str(a.selector, "body")),
554
- browser_back: async () => {
555
- await browser.back();
556
- return observe();
557
- }
558
- };
559
- const specs = COMPUTER_USE_SPECS.map((s) => ({ ...s }));
560
- return {
561
- schemas: specs.map((spec) => schemaFromSignature(spec)),
562
- impls,
563
- specs
564
- };
565
- }
566
- 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;
902
+ 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;
567
903
  var init_browser = __esm({
568
904
  "src/worlds/browser.ts"() {
569
905
  "use strict";
570
- init_session2();
906
+ init_credentialField();
571
907
  init_browserReconnect();
572
908
  SURFACE_KINDS = ["tools", "api", "ui", "browser"];
909
+ FIELD_PROBE_TIMEOUT_MS = 2e3;
573
910
  PLATFORM_SESSION_HEADER = "X-World-Session";
574
911
  SESSION_AUTH_MODES = ["vendor", "open"];
575
912
  BROWSER_TIERS = ["standard", "premium"];
@@ -581,9 +918,6 @@ var init_browser = __esm({
581
918
  EVENT_FLUSH_INTERVAL_MS = 1e3;
582
919
  EVENT_MAX_RETRIES = 3;
583
920
  EVENT_SCREENSHOT_QUALITY = 60;
584
- EVENT_MAX_STRING = 500;
585
- SECRET_KEY = /pass(word|wd)?|secret|token|api[-_]?key|authorization|cookie|(^|[-_ #.\["'=])(otp|pin|cvv|ssn)([-_ \]"']|$)/i;
586
- SECRET_VALUE = /^((sk|pk|ghp|xox[abp])[-_][-_A-Za-z0-9]{8,}|AKIA[0-9A-Z]{12,}|Bearer [-_.A-Za-z0-9]{8,})/;
587
921
  WorldSurfaceUnavailable = class extends Error {
588
922
  constructor(surface, reason) {
589
923
  super(`World surface '${surface}' is unavailable: ${reason}`);
@@ -706,6 +1040,8 @@ var init_browser = __esm({
706
1040
  recorder;
707
1041
  reconnector;
708
1042
  scrubber;
1043
+ typed = [];
1044
+ typedText = new CredentialText([]);
709
1045
  current;
710
1046
  inflight = 0;
711
1047
  lastNetwork = Date.now();
@@ -719,10 +1055,20 @@ var init_browser = __esm({
719
1055
  get agentId() {
720
1056
  return this.recorder?.agentId ?? null;
721
1057
  }
722
- /** `text` with this session's credentials (UI token, browser address) removed. */
1058
+ /** `text` with this session's credentials (UI token, browser address) and
1059
+ * the credentials typed into it removed. */
723
1060
  scrub(text2) {
1061
+ return this.typedText.withhold(this.scrubber.scrub(text2));
1062
+ }
1063
+ /** `text` with this session's credentials removed and nothing else
1064
+ * changed: for text that is compared and never leaves the process. */
1065
+ scrubSession(text2) {
724
1066
  return this.scrubber.scrub(text2);
725
1067
  }
1068
+ /** Every credential typed into this browser by `type`. */
1069
+ get typedCredentials() {
1070
+ return [...this.typed];
1071
+ }
726
1072
  watchNetwork(page) {
727
1073
  page.on("request", () => {
728
1074
  this.inflight += 1;
@@ -766,7 +1112,7 @@ var init_browser = __esm({
766
1112
  async recover(reconnector, cause) {
767
1113
  const started = Date.now();
768
1114
  const message = cause instanceof Error ? cause.message : String(cause);
769
- const args = { cause: this.scrubber.scrub(message).slice(0, 200) };
1115
+ const args = { cause: this.scrub(message).slice(0, 200) };
770
1116
  let result;
771
1117
  try {
772
1118
  result = await reconnector.recover(cause, (c) => this.adopt(c));
@@ -801,7 +1147,9 @@ var init_browser = __esm({
801
1147
  }
802
1148
  /** Run one action and report it: the event carries what was asked,
803
1149
  * whether it worked, and the screen after — for failures too, so a
804
- * reviewer sees what the agent saw when the selector did not match. */
1150
+ * reviewer sees what the agent saw when the selector did not match. The
1151
+ * error it throws keeps no session credential and no credential typed into
1152
+ * this browser, which Playwright's call log would quote. */
805
1153
  async act(action, args, fn, onLoss = "report") {
806
1154
  const started = Date.now();
807
1155
  try {
@@ -809,6 +1157,7 @@ var init_browser = __esm({
809
1157
  await this.report(action, args, started, null);
810
1158
  return result;
811
1159
  } catch (error) {
1160
+ this.scrubError(error);
812
1161
  await this.report(action, args, started, error);
813
1162
  throw error;
814
1163
  }
@@ -817,7 +1166,7 @@ var init_browser = __esm({
817
1166
  async report(action, args, started, failure) {
818
1167
  const recorder = this.recorder;
819
1168
  if (!recorder) return;
820
- const error = failure === null ? null : this.scrubber.scrub(
1169
+ const error = failure === null ? null : this.scrub(
821
1170
  failure instanceof Error ? `${failure.name}: ${failure.message}` : String(failure)
822
1171
  ).slice(0, 4e3);
823
1172
  recorder.record({
@@ -830,7 +1179,7 @@ var init_browser = __esm({
830
1179
  Object.fromEntries(
831
1180
  Object.entries(args).map(([key, value]) => [
832
1181
  key,
833
- typeof value === "string" ? this.scrubber.scrub(value) : value
1182
+ typeof value === "string" ? this.scrub(value) : value
834
1183
  ])
835
1184
  )
836
1185
  ),
@@ -849,8 +1198,8 @@ var init_browser = __esm({
849
1198
  screenshot: null
850
1199
  };
851
1200
  try {
852
- out.url = this.scrubber.scrub(this.page.url());
853
- out.title = this.scrubber.scrub(await this.page.title());
1201
+ out.url = this.scrub(this.page.url());
1202
+ out.title = this.scrub(await this.page.title());
854
1203
  const jpeg = await this.page.screenshot({
855
1204
  type: "jpeg",
856
1205
  quality: EVENT_SCREENSHOT_QUALITY
@@ -887,7 +1236,7 @@ var init_browser = __esm({
887
1236
  async () => {
888
1237
  await this.page.goto(target, { waitUntil: "load" });
889
1238
  await this.settle();
890
- return this.page.url();
1239
+ return this.url;
891
1240
  },
892
1241
  // Navigating again lands on the same page: safe to replay.
893
1242
  "retry"
@@ -897,7 +1246,7 @@ var init_browser = __esm({
897
1246
  return this.act("browser_back", {}, async () => {
898
1247
  await this.page.goBack({ waitUntil: "load" });
899
1248
  await this.settle();
900
- return this.page.url();
1249
+ return this.url;
901
1250
  });
902
1251
  }
903
1252
  /** Wait for the page to finish reacting to an action. `load` alone is not
@@ -916,19 +1265,54 @@ var init_browser = __esm({
916
1265
  await this.page.waitForTimeout(SETTLE_POLL_MS);
917
1266
  }
918
1267
  }
919
- async click(selector) {
1268
+ async click(selector, opts = {}) {
920
1269
  await this.act("browser_click", { selector }, async () => {
921
- await this.page.click(selector);
1270
+ await this.page.click(selector, { timeout: opts.timeoutMs });
922
1271
  await this.settle();
923
1272
  });
924
1273
  }
925
- async type(selector, text2) {
1274
+ /** Replace the field's value with `text`. `opts.credential` is whether the
1275
+ * field takes one, when the caller already probed it; a credential is
1276
+ * withheld from the event and from any error. */
1277
+ async type(selector, text2, opts = {}) {
1278
+ const secret = opts.credential ?? await this.credentialField(selector);
1279
+ if (secret) this.typed.push(text2);
1280
+ this.typedText = new CredentialText(this.typed);
926
1281
  await this.act(
927
1282
  "browser_type",
928
- { selector, text: text2 },
929
- () => this.page.fill(selector, text2)
1283
+ { selector, text: secret ? "[redacted]" : text2 },
1284
+ () => this.page.fill(selector, text2, { timeout: opts.timeoutMs })
930
1285
  );
931
1286
  }
1287
+ /** `DESCRIBE_FIELD_JS` of the element `selector` finds, or `UNREADABLE`. */
1288
+ async describeField(selector) {
1289
+ try {
1290
+ const described = await this.page.locator(selector).evaluate(describeField, void 0, { timeout: FIELD_PROBE_TIMEOUT_MS });
1291
+ return String(described ?? "");
1292
+ } catch {
1293
+ return UNREADABLE;
1294
+ }
1295
+ }
1296
+ /** Whether the field `selector` finds takes a credential; one it cannot
1297
+ * read counts. */
1298
+ async credentialField(selector) {
1299
+ return isCredentialField(await this.describeField(selector));
1300
+ }
1301
+ /** What the field `selector` finds holds (`FIELD_VALUE_JS`), or null when
1302
+ * it cannot be read. */
1303
+ async fieldValue(selector) {
1304
+ try {
1305
+ const value = await this.page.locator(selector).evaluate(readFieldValue, void 0, { timeout: FIELD_PROBE_TIMEOUT_MS });
1306
+ return value === null || value === void 0 ? null : String(value);
1307
+ } catch {
1308
+ return null;
1309
+ }
1310
+ }
1311
+ /** Take this session's credentials out of `error` and the errors it came
1312
+ * from, in place. */
1313
+ scrubError(error) {
1314
+ scrubError(error, (text2) => this.scrub(text2));
1315
+ }
932
1316
  async press(key) {
933
1317
  await this.act("browser_press", { key }, async () => {
934
1318
  await this.page.keyboard.press(key);
@@ -951,14 +1335,39 @@ var init_browser = __esm({
951
1335
  async screenshotBase64(fullPage = false) {
952
1336
  return (await this.screenshot(fullPage)).toString("base64");
953
1337
  }
1338
+ /** The visible text of `selector`'s element, without what any field on the
1339
+ * page that takes a credential holds. */
954
1340
  async text(selector = "body") {
955
- return this.resilient(() => this.page.innerText(selector), "retry");
1341
+ const withheld = new CredentialText(await this.credentialTexts());
1342
+ return withheld.withhold(
1343
+ await this.resilient(() => this.page.innerText(selector), "retry")
1344
+ );
1345
+ }
1346
+ /** What each field on the page that takes a credential holds: an input's
1347
+ * or textarea's value, a select's chosen option, a contenteditable's text. */
1348
+ async credentialTexts() {
1349
+ return this.resilient(async () => {
1350
+ const pairs = await this.page.locator(FIELDS).evaluateAll(readEditables);
1351
+ return credentialTexts(pairs);
1352
+ }, "retry");
1353
+ }
1354
+ /** Wait until the element `selector` finds could be clicked, without
1355
+ * clicking it. */
1356
+ async actionable(selector) {
1357
+ await this.resilient(() => this.page.locator(selector).click({ trial: true }), "retry");
1358
+ }
1359
+ async ariaSnapshot() {
1360
+ return this.resilient(async () => {
1361
+ if (!this.page.ariaSnapshot)
1362
+ throw new TypeError("this Playwright has no page.ariaSnapshot");
1363
+ return this.page.ariaSnapshot({ mode: "ai" });
1364
+ }, "retry");
956
1365
  }
957
1366
  async html() {
958
1367
  return this.resilient(() => this.page.content(), "retry");
959
1368
  }
960
1369
  get url() {
961
- return this.page.url();
1370
+ return withoutUiToken(this.page.url());
962
1371
  }
963
1372
  async title() {
964
1373
  return this.resilient(() => this.page.title(), "retry");
@@ -971,21 +1380,504 @@ var init_browser = __esm({
971
1380
  }
972
1381
  }
973
1382
  };
1383
+ }
1384
+ });
1385
+
1386
+ // src/worlds/pageState.ts
1387
+ function selectorRef(selector) {
1388
+ if (selector.includes("aria-ref"))
1389
+ throw new PageStateError(
1390
+ "aria-ref selectors are not taken: pass ref=\u2026 from browser_snapshot"
1391
+ );
1392
+ return REF_SELECTOR.exec(selector.replace(/^ +| +$/g, ""))?.[1] ?? null;
1393
+ }
1394
+ 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;
1395
+ var init_pageState = __esm({
1396
+ "src/worlds/pageState.ts"() {
1397
+ "use strict";
1398
+ init_credentialField();
1399
+ DEFAULT_MAX_CHARS = 2e4;
1400
+ REF_ACT_TIMEOUT_MS = 2e3;
1401
+ STEADY_READS = 4;
1402
+ NEEDS_PLAYWRIGHT = "browser_snapshot needs Playwright 1.59 or newer (npm install playwright@latest)";
1403
+ 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)";
1404
+ LINE_KEY = /^ *- ('(?:[^']|'')*'|.*?)(:(?: .*)?)?$/s;
1405
+ ATTRIBUTES = /(?: \[[^[\]]*\])*$/;
1406
+ FOCUS = / \[active\]/g;
1407
+ STATES = / \[(?:checked(?:=mixed)?|expanded|pressed(?:=mixed)?|selected)\]/g;
1408
+ ROLE = /^[a-z]+/;
1409
+ REF = /\[ref=((?:f[0-9]+)?e[0-9]+)\]/g;
1410
+ REF_SELECTOR = /^ref=((?:f[0-9]+)?e[0-9]+)$/;
1411
+ EDITABLE_ROLES = /* @__PURE__ */ new Set([
1412
+ "textbox",
1413
+ "searchbox",
1414
+ "combobox",
1415
+ "spinbutton",
1416
+ "slider"
1417
+ ]);
1418
+ VALUE_KEYS = /* @__PURE__ */ new Set(["text", "/placeholder"]);
1419
+ WITHHELD = ": [redacted]";
1420
+ PageStateError = class extends Error {
1421
+ name = "PageStateError";
1422
+ };
1423
+ AriaLine = class _AriaLine {
1424
+ constructor(text2, indent, key = "", attributes = "", rest = "") {
1425
+ this.text = text2;
1426
+ this.indent = indent;
1427
+ this.key = key;
1428
+ this.attributes = attributes;
1429
+ this.rest = rest;
1430
+ }
1431
+ text;
1432
+ indent;
1433
+ key;
1434
+ attributes;
1435
+ rest;
1436
+ static parse(text2) {
1437
+ const indent = text2.length - text2.replace(/^ +/, "").length;
1438
+ const found = LINE_KEY.exec(text2);
1439
+ if (!found) return new _AriaLine(text2, indent);
1440
+ const key = found[1].startsWith("'") ? found[1].slice(1, -1).replaceAll("''", "'") : found[1];
1441
+ return new _AriaLine(
1442
+ text2,
1443
+ indent,
1444
+ key,
1445
+ ATTRIBUTES.exec(key)?.[0] ?? "",
1446
+ found[2] ?? ""
1447
+ );
1448
+ }
1449
+ static parseAll(aria) {
1450
+ return aria === "" ? [] : aria.split("\n").map((text2) => _AriaLine.parse(text2));
1451
+ }
1452
+ get refs() {
1453
+ return [...this.attributes.matchAll(REF)].map((ref) => ref[1]);
1454
+ }
1455
+ get disabled() {
1456
+ return this.attributes.includes("[disabled]");
1457
+ }
1458
+ get editable() {
1459
+ const role = ROLE.exec(this.key)?.[0];
1460
+ return role !== void 0 && EDITABLE_ROLES.has(role);
1461
+ }
1462
+ /** A value line: a field's text, or the placeholder it shows. */
1463
+ get value() {
1464
+ return VALUE_KEYS.has(this.key);
1465
+ }
1466
+ get states() {
1467
+ return this.attributes.match(STATES) ?? [];
1468
+ }
1469
+ get namedLikeCredential() {
1470
+ return SECRET_KEY.test(
1471
+ this.key.slice(0, this.key.length - this.attributes.length)
1472
+ );
1473
+ }
1474
+ /** Whether every value in and under this line is withheld. A field is,
1475
+ * when it is named like a credential or sits in something that is, has no
1476
+ * ref to probe, or `describe` reads it as a credential field. Any other
1477
+ * line is, when it is named like a credential and holds typed text (a
1478
+ * contenteditable), or has no ref to tell. */
1479
+ async credentialField(describe2, withinCredential) {
1480
+ if (this.editable)
1481
+ return this.credentialFieldInput(describe2, withinCredential);
1482
+ if (!this.namedLikeCredential) return false;
1483
+ if (this.refs.length === 0) return true;
1484
+ return isTextField(await describe2(this.refs[0]));
1485
+ }
1486
+ async credentialFieldInput(describe2, withinCredential) {
1487
+ if (withinCredential || this.namedLikeCredential) return true;
1488
+ if (this.refs.length === 0) return true;
1489
+ return isCredentialField(await describe2(this.refs[0]));
1490
+ }
1491
+ /** The line as shown: `withholding` applied to its text, while its refs and
1492
+ * states are still read from the attribute run Playwright wrote, so a
1493
+ * withheld name cannot join that run. */
1494
+ withheldBy(withhold) {
1495
+ return new _AriaLine(
1496
+ this.withholding(withhold),
1497
+ this.indent,
1498
+ this.key,
1499
+ this.attributes,
1500
+ this.rest
1501
+ );
1502
+ }
1503
+ /** The line with `withhold` applied to its name and value, its attribute
1504
+ * run (refs, states, levels) as Playwright wrote it. */
1505
+ withholding(withhold) {
1506
+ const at = this.attributes ? this.text.lastIndexOf(
1507
+ this.attributes,
1508
+ this.text.length - this.rest.length - this.attributes.length
1509
+ ) : -1;
1510
+ if (at < 0) return withhold(this.text);
1511
+ const end = at + this.attributes.length;
1512
+ return withhold(this.text.slice(0, at)) + this.attributes + withhold(this.text.slice(end));
1513
+ }
1514
+ /** The line with its own value replaced, keeping the key as Playwright
1515
+ * wrote it. */
1516
+ get withheld() {
1517
+ if (this.key === "/placeholder" || !this.rest.startsWith(": "))
1518
+ return this.text;
1519
+ return this.text.slice(0, this.text.length - this.rest.length) + WITHHELD;
1520
+ }
1521
+ };
1522
+ Touched = class _Touched {
1523
+ constructor(clicked = /* @__PURE__ */ new Map(), typed = /* @__PURE__ */ new Map()) {
1524
+ this.clicked = clicked;
1525
+ this.typed = typed;
1526
+ }
1527
+ clicked;
1528
+ typed;
1529
+ afterClick(ref, states) {
1530
+ return new _Touched(new Map([...this.clicked, [ref, states]]), this.typed);
1531
+ }
1532
+ afterTyping(ref, text2) {
1533
+ return new _Touched(this.clicked, new Map([...this.typed, [ref, text2]]));
1534
+ }
1535
+ /** The snapshot's lines as the page should now read them. */
1536
+ expected(lines) {
1537
+ return this.compared(lines, (line) => this.leftByClick(line));
1538
+ }
1539
+ /** A fresh read's lines, in the same form. */
1540
+ actual(lines) {
1541
+ return this.compared(lines, (line) => line.states);
1542
+ }
1543
+ compared(lines, states) {
1544
+ const out = [];
1545
+ let typedAt = null;
1546
+ for (const line of lines) {
1547
+ if (typedAt !== null && line.indent > typedAt && line.value) continue;
1548
+ typedAt = this.isTyped(line) ? line.indent : null;
1549
+ out.push(this.comparedLine(line, states(line)));
1550
+ }
1551
+ return out;
1552
+ }
1553
+ isTyped(line) {
1554
+ return line.refs.some((ref) => this.typed.has(ref));
1555
+ }
1556
+ clickedRef(line) {
1557
+ return line.refs.find((ref) => this.clicked.has(ref));
1558
+ }
1559
+ leftByClick(line) {
1560
+ const ref = this.clickedRef(line);
1561
+ return ref === void 0 ? line.states : this.clicked.get(ref);
1562
+ }
1563
+ comparedLine(line, states) {
1564
+ if (this.isTyped(line))
1565
+ return (" ".repeat(line.indent) + "- " + line.key).replace(FOCUS, "");
1566
+ if (this.clickedRef(line) !== void 0)
1567
+ return line.text.replace(FOCUS, "").replace(STATES, "") + states.join("");
1568
+ return line.text.replace(FOCUS, "");
1569
+ }
1570
+ };
1571
+ sameLines = (a, b) => a.length === b.length && a.every((line, at) => line === b[at]);
1572
+ deeper = (line, below) => below !== null && line.indent > below ? below : null;
1573
+ PageState = class _PageState {
1574
+ constructor(url, title, snapshot, refs, disabled, truncated, credentials = /* @__PURE__ */ new Set()) {
1575
+ this.url = url;
1576
+ this.title = title;
1577
+ this.snapshot = snapshot;
1578
+ this.refs = refs;
1579
+ this.disabled = disabled;
1580
+ this.truncated = truncated;
1581
+ this.credentials = credentials;
1582
+ }
1583
+ url;
1584
+ title;
1585
+ snapshot;
1586
+ refs;
1587
+ disabled;
1588
+ truncated;
1589
+ credentials;
1590
+ static parse(aria, opts) {
1591
+ return _PageState.ofLines(AriaLine.parseAll(aria), opts);
1592
+ }
1593
+ static ofLines(lines, opts) {
1594
+ const maxChars = opts.maxChars ?? DEFAULT_MAX_CHARS;
1595
+ const shown = [];
1596
+ let size = 0;
1597
+ for (const line of lines) {
1598
+ const width = [...line.text].length + 1;
1599
+ if (size + width > maxChars) break;
1600
+ size += width;
1601
+ shown.push(line);
1602
+ }
1603
+ return new _PageState(
1604
+ opts.url,
1605
+ opts.title,
1606
+ shown.map((line) => line.text).join("\n"),
1607
+ new Set(shown.flatMap((line) => line.refs)),
1608
+ new Set(
1609
+ shown.filter((line) => line.disabled).flatMap((line) => line.refs)
1610
+ ),
1611
+ shown.length < lines.length,
1612
+ opts.credentials ?? /* @__PURE__ */ new Set()
1613
+ );
1614
+ }
1615
+ /** `aria` with credential values withheld: every value in and under a
1616
+ * credential field (see `AriaLine.credentialField`; `describe` is
1617
+ * `DESCRIBE_FIELD_JS` of a ref's element), the placeholder aside, and the
1618
+ * value of any line named like a credential. Names, roles and refs stay. */
1619
+ static async redacted(aria, describe2) {
1620
+ const out = [];
1621
+ const withheld = [];
1622
+ let withheldBelow = null;
1623
+ let credentialBelow = null;
1624
+ for (const line of AriaLine.parseAll(aria)) {
1625
+ withheldBelow = deeper(line, withheldBelow);
1626
+ credentialBelow = deeper(line, credentialBelow);
1627
+ if (withheldBelow === null && await line.credentialField(describe2, credentialBelow !== null))
1628
+ withheldBelow = line.indent;
1629
+ if (credentialBelow === null && line.namedLikeCredential)
1630
+ credentialBelow = line.indent;
1631
+ const hidden = withheldBelow !== null || line.namedLikeCredential;
1632
+ out.push(hidden ? line.withheld : line.text);
1633
+ if (hidden) withheld.push(...line.refs);
1634
+ }
1635
+ return { snapshot: out.join("\n"), withheld: new Set(withheld) };
1636
+ }
1637
+ target(ref) {
1638
+ if (!this.refs.has(ref))
1639
+ throw new PageStateError(
1640
+ `ref=${ref} is not in the last browser_snapshot: take a new one`
1641
+ );
1642
+ if (this.disabled.has(ref))
1643
+ throw new PageStateError(`ref=${ref} is disabled`);
1644
+ return `aria-ref=${ref}`;
1645
+ }
1646
+ observation() {
1647
+ return {
1648
+ url: this.url,
1649
+ title: this.title,
1650
+ snapshot: this.snapshot,
1651
+ truncated: this.truncated
1652
+ };
1653
+ }
1654
+ };
1655
+ PageObserver = class {
1656
+ constructor(browser, maxChars = DEFAULT_MAX_CHARS) {
1657
+ this.browser = browser;
1658
+ this.maxChars = maxChars;
1659
+ }
1660
+ browser;
1661
+ maxChars;
1662
+ last = null;
1663
+ seen = [];
1664
+ seenUrl = "";
1665
+ touched = new Touched();
1666
+ turn = Promise.resolve();
1667
+ async snapshot() {
1668
+ return this.inTurn(() => this.takeSnapshot());
1669
+ }
1670
+ async click(selector) {
1671
+ return this.inTurn(() => this.clickOnce(selector));
1672
+ }
1673
+ async type(selector, text2) {
1674
+ return this.inTurn(() => this.typeOnce(selector, text2));
1675
+ }
1676
+ /** One call at a time, so a tool call a model made in parallel cannot act
1677
+ * between another's checks and its action. */
1678
+ inTurn(fn) {
1679
+ const run = this.turn.then(fn, fn);
1680
+ this.turn = run.catch(() => void 0);
1681
+ return run;
1682
+ }
1683
+ async takeSnapshot() {
1684
+ const aria = this.browser.scrubSession(await this.steady());
1685
+ const shown = await PageState.redacted(
1686
+ aria,
1687
+ (ref) => this.browser.describeField(`aria-ref=${ref}`)
1688
+ );
1689
+ const secrets = new CredentialText([
1690
+ ...await this.withheldValues(shown),
1691
+ ...await this.browser.credentialTexts(),
1692
+ ...this.browser.typedCredentials
1693
+ ]);
1694
+ const lines = AriaLine.parseAll(shown.snapshot).map(
1695
+ (line) => line.withheldBy((text2) => secrets.withhold(text2))
1696
+ );
1697
+ this.last = PageState.ofLines(lines, {
1698
+ url: this.url(),
1699
+ title: this.browser.scrub(await this.browser.title()),
1700
+ maxChars: this.maxChars,
1701
+ credentials: shown.withheld
1702
+ });
1703
+ this.seen = AriaLine.parseAll(aria);
1704
+ this.seenUrl = this.browser.scrubSession(this.browser.url);
1705
+ this.touched = new Touched();
1706
+ return this.last;
1707
+ }
1708
+ /** The values of the fields the redaction withheld: a page may repeat them
1709
+ * in another line's name (a row or cell named from its content, a label
1710
+ * that wraps the field). */
1711
+ async withheldValues(shown) {
1712
+ const refs = AriaLine.parseAll(shown.snapshot).filter((line) => line.editable).flatMap((line) => line.refs).filter((ref) => shown.withheld.has(ref));
1713
+ const values = [];
1714
+ for (const ref of refs)
1715
+ values.push(await this.browser.fieldValue(`aria-ref=${ref}`) ?? "");
1716
+ return values;
1717
+ }
1718
+ async clickOnce(selector) {
1719
+ const ref = selectorRef(selector);
1720
+ if (ref === null) return this.browser.click(selector);
1721
+ const [, target] = this.target(ref);
1722
+ await this.ready(target);
1723
+ await this.browser.click(target, { timeoutMs: REF_ACT_TIMEOUT_MS });
1724
+ const left = (await this.now()).find((line) => line.refs.includes(ref));
1725
+ if (left) this.touched = this.touched.afterClick(ref, left.states);
1726
+ }
1727
+ async typeOnce(selector, text2) {
1728
+ const ref = selectorRef(selector);
1729
+ if (ref === null) return this.browser.type(selector, text2);
1730
+ const [last, target] = this.target(ref);
1731
+ const credential = last.credentials.has(ref) || await this.browser.credentialField(target);
1732
+ await this.ready(target);
1733
+ await this.browser.type(target, text2, {
1734
+ timeoutMs: REF_ACT_TIMEOUT_MS,
1735
+ credential
1736
+ });
1737
+ this.touched = this.touched.afterTyping(ref, text2);
1738
+ }
1739
+ target(ref) {
1740
+ if (this.last === null)
1741
+ throw new PageStateError(
1742
+ "ref=\u2026 selectors come from browser_snapshot: take one first"
1743
+ );
1744
+ return [this.last, this.last.target(ref)];
1745
+ }
1746
+ async ready(target) {
1747
+ await this.still();
1748
+ await this.browser.actionable(target);
1749
+ await this.still();
1750
+ }
1751
+ /** A page still rendering when it is read would refuse the model's next
1752
+ * ref, so the snapshot it is shown is one that read the same before and
1753
+ * after the page settled again. */
1754
+ async steady() {
1755
+ const untouched = new Touched();
1756
+ let aria = await this.read();
1757
+ for (let read = 1; read < STEADY_READS; read++) {
1758
+ await this.browser.settle();
1759
+ const again = await this.read();
1760
+ if (sameLines(
1761
+ untouched.actual(AriaLine.parseAll(again)),
1762
+ untouched.actual(AriaLine.parseAll(aria))
1763
+ ))
1764
+ return again;
1765
+ aria = again;
1766
+ }
1767
+ return aria;
1768
+ }
1769
+ async read() {
1770
+ try {
1771
+ return await this.browser.ariaSnapshot();
1772
+ } catch (error) {
1773
+ if (error instanceof TypeError)
1774
+ throw new PageStateError(NEEDS_PLAYWRIGHT);
1775
+ throw error;
1776
+ }
1777
+ }
1778
+ url() {
1779
+ return this.browser.scrub(this.browser.url);
1780
+ }
1781
+ async now() {
1782
+ return AriaLine.parseAll(this.browser.scrubSession(await this.read()));
1783
+ }
1784
+ async still() {
1785
+ if (this.browser.scrubSession(this.browser.url) !== this.seenUrl || !sameLines(
1786
+ this.touched.actual(await this.now()),
1787
+ this.touched.expected(this.seen)
1788
+ ))
1789
+ throw new PageStateError(CHANGED);
1790
+ for (const [ref, text2] of this.touched.typed)
1791
+ if (await this.browser.fieldValue(`aria-ref=${ref}`) !== text2)
1792
+ throw new PageStateError(CHANGED);
1793
+ }
1794
+ };
1795
+ }
1796
+ });
1797
+
1798
+ // src/worlds/browserTools.ts
1799
+ function computerUseToolkit(browser, opts = {}) {
1800
+ const maxText = opts.maxText ?? DEFAULT_MAX_CHARS;
1801
+ const pages = new PageObserver(browser, maxText);
1802
+ const observe = async (selector = "body") => {
1803
+ const text2 = browser.scrub(await browser.text(selector));
1804
+ return {
1805
+ url: browser.scrub(browser.url),
1806
+ title: browser.scrub(await browser.title()),
1807
+ text: text2.slice(0, maxText),
1808
+ truncated: text2.length > maxText
1809
+ };
1810
+ };
1811
+ const impls = {
1812
+ browser_goto: async (a) => {
1813
+ await browser.goto(typeof a.path === "string" ? a.path : void 0);
1814
+ return observe();
1815
+ },
1816
+ browser_snapshot: async () => (await pages.snapshot()).observation(),
1817
+ browser_click: async (a) => {
1818
+ await pages.click(str(a.selector, ""));
1819
+ return observe();
1820
+ },
1821
+ browser_type: async (a) => {
1822
+ await pages.type(str(a.selector, ""), String(a.text ?? ""));
1823
+ return { ok: true, url: browser.scrub(browser.url) };
1824
+ },
1825
+ browser_press: async (a) => {
1826
+ await browser.press(str(a.key, "Enter"));
1827
+ return observe();
1828
+ },
1829
+ browser_scroll: async (a) => {
1830
+ await browser.scroll(typeof a.dy === "number" ? a.dy : 600);
1831
+ return { ok: true, url: browser.scrub(browser.url) };
1832
+ },
1833
+ browser_screenshot: async (a) => ({
1834
+ image_base64: await browser.screenshotBase64(a.full_page === true),
1835
+ url: browser.scrub(browser.url)
1836
+ }),
1837
+ browser_read: async (a) => observe(str(a.selector, "body")),
1838
+ browser_back: async () => {
1839
+ await browser.back();
1840
+ return observe();
1841
+ }
1842
+ };
1843
+ const specs = COMPUTER_USE_SPECS.map((s) => ({ ...s }));
1844
+ return {
1845
+ schemas: specs.map((spec) => schemaFromSignature(spec)),
1846
+ impls: Object.fromEntries(
1847
+ Object.entries(impls).map(([name, impl]) => [
1848
+ name,
1849
+ scrubbingErrors(browser, impl)
1850
+ ])
1851
+ ),
1852
+ specs
1853
+ };
1854
+ }
1855
+ var COMPUTER_USE_SPECS, scrubbingErrors, str;
1856
+ var init_browserTools = __esm({
1857
+ "src/worlds/browserTools.ts"() {
1858
+ "use strict";
1859
+ init_pageState();
1860
+ init_session2();
974
1861
  COMPUTER_USE_SPECS = [
975
1862
  {
976
1863
  name: "browser_goto",
977
1864
  signature: "browser_goto(path=None)",
978
1865
  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."
979
1866
  },
1867
+ {
1868
+ name: "browser_snapshot",
1869
+ signature: "browser_snapshot()",
1870
+ 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}."
1871
+ },
980
1872
  {
981
1873
  name: "browser_click",
982
1874
  signature: "browser_click(selector)",
983
- doc: "Click an element by Playwright selector (CSS, `text=Refund`, `role=button[name=Save]`). Returns the page text after the click."
1875
+ 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."
984
1876
  },
985
1877
  {
986
1878
  name: "browser_type",
987
1879
  signature: "browser_type(selector, text)",
988
- doc: "Replace the value of an input/textarea found by selector with `text`."
1880
+ doc: "Replace the value of an input/textarea, found by `ref=e3` or by selector, with `text`."
989
1881
  },
990
1882
  {
991
1883
  name: "browser_press",
@@ -1013,6 +1905,14 @@ var init_browser = __esm({
1013
1905
  doc: "Go back one page in history."
1014
1906
  }
1015
1907
  ];
1908
+ scrubbingErrors = (browser, impl) => async (args) => {
1909
+ try {
1910
+ return await impl(args);
1911
+ } catch (error) {
1912
+ browser.scrubError(error);
1913
+ throw error;
1914
+ }
1915
+ };
1016
1916
  str = (v, fallback) => typeof v === "string" && v.length > 0 ? v : fallback;
1017
1917
  }
1018
1918
  });
@@ -1157,13 +2057,12 @@ function isNativePage(page) {
1157
2057
  const mouse = candidate?.mouse;
1158
2058
  return typeof candidate?.context === "function" && NATIVE_METHODS.every((m) => typeof mouse?.[m] === "function");
1159
2059
  }
1160
- var FOCUSED_FIELD_JS, SECRET_FOCUS, DRAG_STEPS, PNG_SIGNATURE, NATIVE_METHODS, Screen;
2060
+ var FOCUSED_FIELD_JS, DRAG_STEPS, PNG_SIGNATURE, NATIVE_METHODS, Screen;
1161
2061
  var init_screen = __esm({
1162
2062
  "src/worlds/nativeComputer/screen.ts"() {
1163
2063
  "use strict";
1164
- init_browser();
1165
- 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(' '); })()";
1166
- SECRET_FOCUS = ["password", "frame", "opaque"];
2064
+ init_credentialField();
2065
+ 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); })()`;
1167
2066
  DRAG_STEPS = 5;
1168
2067
  PNG_SIGNATURE = Buffer.from([
1169
2068
  137,
@@ -1254,7 +2153,7 @@ var init_screen = __esm({
1254
2153
  } catch {
1255
2154
  return true;
1256
2155
  }
1257
- return SECRET_FOCUS.some((prefix) => described.startsWith(prefix)) || SECRET_KEY.test(described);
2156
+ return isCredentialField(described);
1258
2157
  }
1259
2158
  /** CDP renders a clip at the page's device pixel ratio as well as its
1260
2159
  * `scale` (a Retina host doubles it), so a capture of the wrong width
@@ -2432,7 +3331,7 @@ var init_requestLedger = __esm({
2432
3331
  "use strict";
2433
3332
  init_worlds();
2434
3333
  init_sessionContract();
2435
- WORLD_REQUEST_VIAS = ["api", "ui", "tool", "webhook"];
3334
+ WORLD_REQUEST_VIAS = ["api", "ui", "tool", "webhook", "page"];
2436
3335
  WorldRequestFilterError = class extends Error {
2437
3336
  };
2438
3337
  NOT_RECORDED = "This session's engine records no requests; only hosted World Host sessions do.";
@@ -2940,7 +3839,8 @@ async function openSession(slugOrRef, taskOrOpts = {}, positionalOpts = {}) {
2940
3839
  ...opts.reuseWarm === void 0 ? {} : { reuseWarm: opts.reuseWarm },
2941
3840
  ...opts.surfaces?.length ? { surfaces: opts.surfaces } : {},
2942
3841
  ...opts.browserTier === void 0 ? {} : { browserTier: opts.browserTier },
2943
- ...opts.auth === void 0 ? {} : { auth: opts.auth }
3842
+ ...opts.auth === void 0 ? {} : { auth: opts.auth },
3843
+ ...opts.worldState === void 0 ? {} : { worldState: opts.worldState }
2944
3844
  }
2945
3845
  );
2946
3846
  return new WorldSession(state2.sessionId, state2, options);
@@ -3028,6 +3928,7 @@ var init_session2 = __esm({
3028
3928
  import_node_crypto2 = require("crypto");
3029
3929
  init_worlds();
3030
3930
  init_browser();
3931
+ init_browserTools();
3031
3932
  init_nativeComputer();
3032
3933
  init_sessionContract();
3033
3934
  init_toolSchema();
@@ -3093,6 +3994,9 @@ var init_session2 = __esm({
3093
3994
  get versionId() {
3094
3995
  return this.current.versionId;
3095
3996
  }
3997
+ get worldState() {
3998
+ return this.current.worldState ?? null;
3999
+ }
3096
4000
  /** Whether the session answered ready as of the last state read (the open,
3097
4001
  * a `status()`, or the poll inside `ready()`); no request is made. */
3098
4002
  get isReady() {
@@ -3462,6 +4366,7 @@ var init_session2 = __esm({
3462
4366
  "surfaces",
3463
4367
  "browserTier",
3464
4368
  "auth",
4369
+ "worldState",
3465
4370
  "options"
3466
4371
  ]);
3467
4372
  isOpenSessionOptions = (value) => typeof value === "object" && value !== null && Object.keys(value).every((key) => OPEN_SESSION_OPTION_KEYS.has(key));
@@ -3705,7 +4610,8 @@ async function openTask(ref, opts = {}) {
3705
4610
  task,
3706
4611
  ...opts.reuseWarm === void 0 ? {} : { reuseWarm: opts.reuseWarm },
3707
4612
  ...opts.surfaces?.length ? { surfaces: opts.surfaces } : {},
3708
- ...opts.browserTier === void 0 ? {} : { browserTier: opts.browserTier }
4613
+ ...opts.browserTier === void 0 ? {} : { browserTier: opts.browserTier },
4614
+ ...opts.worldStates === void 0 ? {} : { worldStates: opts.worldStates }
3709
4615
  }
3710
4616
  );
3711
4617
  return fromResponse(answer, options);
@@ -3963,16 +4869,22 @@ var init_evals = __esm({
3963
4869
  "src/worlds/evals.ts"() {
3964
4870
  "use strict";
3965
4871
  init_worlds();
4872
+ init_personalToken();
4873
+ init_platformEndpoint();
3966
4874
  init_transport();
3967
4875
  EVALUATIONS = "/api/public/benchmark-containers/evaluations";
3968
- GatewayEvalsClient = class {
4876
+ GatewayEvalsClient = class _GatewayEvalsClient {
3969
4877
  constructor(options = {}, retry = RetryPolicy.FILING) {
3970
4878
  this.options = options;
3971
4879
  this.retry = retry;
4880
+ _GatewayEvalsClient.refuseToken(options);
3972
4881
  }
3973
4882
  options;
3974
4883
  retry;
3975
4884
  keyed = /* @__PURE__ */ new Set();
4885
+ static refuseToken(options) {
4886
+ if (platformEndpoint(options)?.token) throw new PersonalTokenRefused(TOKEN_FILING);
4887
+ }
3976
4888
  async createEvaluation(versionId, opts = {}) {
3977
4889
  const body = { versionId };
3978
4890
  if (opts.model !== void 0) body.model = opts.model;
@@ -5038,7 +5950,7 @@ var require_package = __commonJS({
5038
5950
  "package.json"(exports2, module2) {
5039
5951
  module2.exports = {
5040
5952
  name: "@withgateway/sdk",
5041
- version: "0.6.0",
5953
+ version: "0.9.1",
5042
5954
  description: "Gateway SDK for TypeScript - A/B experiments, tracing, and observability",
5043
5955
  main: "./dist/index.js",
5044
5956
  module: "./dist/index.mjs",
@@ -5119,6 +6031,11 @@ var require_package = __commonJS({
5119
6031
  import: "./dist/hooks/index.mjs",
5120
6032
  require: "./dist/hooks/index.js"
5121
6033
  },
6034
+ "./agents": {
6035
+ types: "./dist/agents/index.d.ts",
6036
+ import: "./dist/agents/index.mjs",
6037
+ require: "./dist/agents/index.js"
6038
+ },
5122
6039
  "./cli": {
5123
6040
  types: "./dist/cli.d.ts",
5124
6041
  import: "./dist/cli.mjs",
@@ -5727,6 +6644,7 @@ var init_taskTracing = __esm({
5727
6644
  "use strict";
5728
6645
  init_prerequisites();
5729
6646
  init_platformEndpoint();
6647
+ init_personalToken();
5730
6648
  HOST_WITH_AUTHORITY = /^[a-z][a-z0-9+.-]*:\/\/[^/\\?#@\s]+(\/|$)/i;
5731
6649
  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.";
5732
6650
  TaskTracing = class _TaskTracing {
@@ -5738,8 +6656,9 @@ var init_taskTracing = __esm({
5738
6656
  static target = null;
5739
6657
  async start(requested, options) {
5740
6658
  if (!requested) return false;
5741
- const endpoint = platformEndpoint(options);
6659
+ let endpoint = null;
5742
6660
  try {
6661
+ endpoint = platformEndpoint(options);
5743
6662
  await this.initOnce(_TaskTracing.config(endpoint));
5744
6663
  return true;
5745
6664
  } catch (error) {
@@ -5761,6 +6680,7 @@ var init_taskTracing = __esm({
5761
6680
  }
5762
6681
  static config(endpoint) {
5763
6682
  if (!endpoint) throw new Error(GATEWAY_KEYS_MISSING);
6683
+ if (endpoint.token) throw new Error(TOKEN_KEYS_ONLY);
5764
6684
  return { ...endpoint, endpoint: _TaskTracing.destination(endpoint) };
5765
6685
  }
5766
6686
  // B1: a saved login's keys go to their own host only. The redirect is compared as text, never parsed:
@@ -5791,7 +6711,9 @@ Pass --no-trace (trace: false) to run untraced without this warning.`
5791
6711
  static reason(error, endpoint) {
5792
6712
  if (OpenTelemetryMissing.explains(error)) return new OpenTelemetryMissing().message;
5793
6713
  const message = error instanceof Error ? error.message : String(error);
5794
- const keys = endpoint ? [endpoint.publicKey, endpoint.secretKey] : [];
6714
+ const keys = [endpoint?.publicKey, endpoint?.secretKey, endpoint?.token?.value].filter(
6715
+ (key) => Boolean(key)
6716
+ );
5795
6717
  return keys.reduce((text2, key) => text2.split(key).join("[redacted]"), message);
5796
6718
  }
5797
6719
  };
@@ -5836,13 +6758,15 @@ async function refuseUnreadTools(live) {
5836
6758
  }
5837
6759
  }
5838
6760
  async function runTask(ref, agent, opts) {
5839
- const runId = `wtr-${(0, import_node_crypto4.randomBytes)(6).toString("hex")}`;
5840
6761
  const options = opts.options ?? {};
6762
+ if (opts.file !== false) GatewayEvalsClient.refuseToken(options);
6763
+ const runId = `wtr-${(0, import_node_crypto4.randomBytes)(6).toString("hex")}`;
5841
6764
  const opening = new TaskOpening(
5842
6765
  openTask(ref, {
5843
6766
  surfaces: opts.surfaces,
5844
6767
  reuseWarm: opts.reuseWarm,
5845
6768
  browserTier: opts.browserTier,
6769
+ worldStates: opts.worldStates,
5846
6770
  options
5847
6771
  }).then(async (live) => {
5848
6772
  await refuseUnreadTools(live);
@@ -6124,6 +7048,7 @@ var init_checkoutProvenance = __esm({
6124
7048
  // src/worlds/setRun.ts
6125
7049
  async function runSet(datasetId, agent, opts) {
6126
7050
  const options = opts.options ?? {};
7051
+ GatewayEvalsClient.refuseToken(options);
6127
7052
  const git = opts.git === void 0 ? CheckoutProvenance.read() : opts.git;
6128
7053
  const opened = await apiRequest(options, "POST", SET_RUNS, {
6129
7054
  datasetId,
@@ -6139,6 +7064,7 @@ var init_setRun = __esm({
6139
7064
  "use strict";
6140
7065
  init_worlds();
6141
7066
  init_checkoutProvenance();
7067
+ init_evals();
6142
7068
  init_runSignals();
6143
7069
  init_taskRun();
6144
7070
  SET_RUNS = "/api/public/set-runs";
@@ -6523,7 +7449,7 @@ var init_checkoutTarget = __esm({
6523
7449
  });
6524
7450
 
6525
7451
  // src/worlds/worldDir.ts
6526
- var import_node_crypto5, fs3, path4, 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;
7452
+ var import_node_crypto5, fs3, path4, 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;
6527
7453
  var init_worldDir = __esm({
6528
7454
  "src/worlds/worldDir.ts"() {
6529
7455
  "use strict";
@@ -6532,13 +7458,14 @@ var init_worldDir = __esm({
6532
7458
  path4 = __toESM(require("path"));
6533
7459
  WORLD_MANIFEST = "gateway-env.toml";
6534
7460
  API_BUNDLE_MANIFEST = "gateway-api-world.toml";
7461
+ BUNDLE_MANIFEST = "gateway-bundle.toml";
6535
7462
  BUNDLED_WORLD_PREFIX = "server/world/";
6536
7463
  CONNECTOR_SPEC = "connector.toml";
6537
7464
  PYPROJECT = "pyproject.toml";
6538
7465
  BENCHMARK_CONFIG = "benchmark.json";
6539
7466
  WORLD_SCHEMA_MARKERS = ["schema/world.json", "schema/runtime.json", "schema/lock.json"];
6540
7467
  WORLD_ROOT_MARKERS = [CONNECTOR_SPEC, ...WORLD_SCHEMA_MARKERS];
6541
- BROAD_ROOT_MARKERS = [WORLD_MANIFEST, API_BUNDLE_MANIFEST, BENCHMARK_CONFIG];
7468
+ BROAD_ROOT_MARKERS = [WORLD_MANIFEST, API_BUNDLE_MANIFEST, BENCHMARK_CONFIG, BUNDLE_MANIFEST];
6542
7469
  SKIPPED_DIRS = /* @__PURE__ */ new Set(["dist", "build", "outputs", "__pycache__", "node_modules"]);
6543
7470
  V1_DEP = /["']verifiers\s*(?:\[[^\]]*\])?\s*(?:>=|~=|==|>)\s*(?:0\.(?:[2-9]\d*|[1-9]\d+)|[1-9]\d*)/;
6544
7471
  V1_IMPORT = /^\s*(?:from\s+verifiers\.v1\s+import\b|from\s+verifiers\s+import\s+v1\b|import\s+verifiers\.v1\b)/m;
@@ -6559,7 +7486,6 @@ var init_worldDir = __esm({
6559
7486
  const bundled = present(API_BUNDLE_MANIFEST) && WORLD_ROOT_MARKERS.some((m) => present(BUNDLED_WORLD_PREFIX + m));
6560
7487
  return new _WorldDir(dir, bundled ? BUNDLED_WORLD_PREFIX : "");
6561
7488
  }
6562
- // ── Files ──────────────────────────────────────────────────────────────
6563
7489
  has(rel) {
6564
7490
  return fs3.existsSync(path4.join(this.dir, rel));
6565
7491
  }
@@ -6570,15 +7496,9 @@ var init_worldDir = __esm({
6570
7496
  return null;
6571
7497
  }
6572
7498
  }
6573
- /** A path under the authored world's root. */
6574
7499
  worldPath(rel) {
6575
7500
  return this.worldRoot + rel;
6576
7501
  }
6577
- /** Every regular file the archive rules keep (`_archive.py`: no hidden,
6578
- * dist, build, outputs, pycache, node_modules or egg-info directories), as
6579
- * sorted relpaths. Root files enter only when a Gateway manifest or
6580
- * benchmark.json widens the root, or they are README.md, pyproject.toml or
6581
- * Python. */
6582
7502
  get archivePaths() {
6583
7503
  if (this.pathsMemo) return this.pathsMemo;
6584
7504
  const broad = BROAD_ROOT_MARKERS.some((m) => this.has(m));
@@ -6597,11 +7517,6 @@ var init_worldDir = __esm({
6597
7517
  walk("");
6598
7518
  return this.pathsMemo = out.sort(byCodePoint);
6599
7519
  }
6600
- /** What the archive rules leave out, collapsed to the entry that decided
6601
- * it: a pruned directory counts its files once, a dropped root file is
6602
- * named. Dot entries (`.git/`, `.gateway/`, `.gitignore`) are the one
6603
- * universal convention and stay unreported. `push` prints the rest so
6604
- * nothing disappears silently. */
6605
7520
  get exclusions() {
6606
7521
  const kept = new Set(this.archivePaths);
6607
7522
  const out = [];
@@ -6624,14 +7539,11 @@ var init_worldDir = __esm({
6624
7539
  }
6625
7540
  return out;
6626
7541
  }
6627
- /** A root `.gitignore` is present: the Python SDK honours it when
6628
- * collecting, this package does not reimplement gitignore. */
7542
+ /** The Python SDK honours a root `.gitignore` when collecting; this package does not reimplement gitignore. */
6629
7543
  get hasRootGitignore() {
6630
7544
  return this.has(".gitignore");
6631
7545
  }
6632
- /** SHA-256 over `utf8("file:" + relpath)` + bytes per archive path in
6633
- * sorted order: the version's identity, byte-compatible with
6634
- * `_archive.compute_content_hash` and Prime Intellect. */
7546
+ /** The version's identity, byte-compatible with the Python SDK's `compute_content_hash` and Prime Intellect's hub. */
6635
7547
  get contentHash() {
6636
7548
  const hasher = (0, import_node_crypto5.createHash)("sha256");
6637
7549
  for (const rel of this.archivePaths) {
@@ -6640,18 +7552,18 @@ var init_worldDir = __esm({
6640
7552
  }
6641
7553
  return hasher.digest("hex");
6642
7554
  }
6643
- // ── Markers ────────────────────────────────────────────────────────────
6644
7555
  get isApiBundle() {
6645
7556
  return this.has(API_BUNDLE_MANIFEST);
6646
7557
  }
7558
+ get isWorldBundle() {
7559
+ return this.has(BUNDLE_MANIFEST);
7560
+ }
6647
7561
  get hasManifest() {
6648
7562
  return this.has(this.worldPath(WORLD_MANIFEST));
6649
7563
  }
6650
7564
  get hasSchemaMarker() {
6651
7565
  return WORLD_SCHEMA_MARKERS.some((m) => this.has(this.worldPath(m)));
6652
7566
  }
6653
- /** Harbor task dirs, relative to the tree: `tasks/<name>` when a `tasks/`
6654
- * dir holds them, else the root `<name>` dirs. */
6655
7567
  taskDirs() {
6656
7568
  const names = /* @__PURE__ */ new Set();
6657
7569
  for (const rel of this.archivePaths) {
@@ -6661,8 +7573,6 @@ var init_worldDir = __esm({
6661
7573
  const under = [...names].filter((n) => n.startsWith("tasks/"));
6662
7574
  return (under.length ? under : [...names]).sort();
6663
7575
  }
6664
- /** The Python package of a verifiers tree (`<pkg>/__init__.py` or
6665
- * `src/<pkg>/__init__.py`), or null. */
6666
7576
  pythonPackage() {
6667
7577
  if (!this.has(PYPROJECT)) return null;
6668
7578
  for (const base of ["", "src/"]) {
@@ -6674,8 +7584,6 @@ var init_worldDir = __esm({
6674
7584
  }
6675
7585
  return null;
6676
7586
  }
6677
- /** The package targets the `verifiers.v1` API: read from the root
6678
- * pyproject and every archived Python module. */
6679
7587
  get isVerifiersV1() {
6680
7588
  for (const rel of this.archivePaths) {
6681
7589
  if (rel !== PYPROJECT && !rel.endsWith(".py")) continue;
@@ -6686,11 +7594,9 @@ var init_worldDir = __esm({
6686
7594
  }
6687
7595
  return false;
6688
7596
  }
6689
- // ── The answer ─────────────────────────────────────────────────────────
6690
- /** The runner's kind (`detect_env_kind`): api / mock-tools win over
6691
- * everything, a harbor task tree next, then the verifiers API version. */
6692
7597
  get kind() {
6693
7598
  if (this.isApiBundle) return "api";
7599
+ if (this.isWorldBundle) return "bundle";
6694
7600
  if (this.has(WORLD_MANIFEST)) return "mock-tools";
6695
7601
  if (this.taskDirs().length) return "harbor";
6696
7602
  return this.isVerifiersV1 ? "verifiers-v1" : "verifiers";
@@ -7028,8 +7934,7 @@ async function push(dir, opts = {}) {
7028
7934
  const metadata = {
7029
7935
  ...opts.name !== void 0 ? { name: opts.name } : {},
7030
7936
  ...opts.description !== void 0 ? { description: opts.description } : {},
7031
- ...opts.tags !== void 0 ? { tags: opts.tags } : {},
7032
- ...opts.visibility ? { visibility: opts.visibility } : {}
7937
+ ...opts.tags !== void 0 ? { tags: opts.tags } : {}
7033
7938
  };
7034
7939
  const resolve7 = await apiRequest(
7035
7940
  options,
@@ -7561,7 +8466,7 @@ var init_sandbox = __esm({
7561
8466
  /**
7562
8467
  * `{ slug, ref? }` opens a READY version; `{ new, from }` opens a sandbox on
7563
8468
  * a world that does not exist yet (409 `world_exists` if the slug is taken,
7564
- * 400 naming the shipped templates if `from` is unknown). Its first commit
8469
+ * 400 naming the official templates if `from` is unknown). Its first commit
7565
8470
  * creates the world on `main`.
7566
8471
  */
7567
8472
  open(target) {
@@ -8206,6 +9111,7 @@ var CliError;
8206
9111
  var init_router = __esm({
8207
9112
  "src/cli/router.ts"() {
8208
9113
  "use strict";
9114
+ init_personalToken();
8209
9115
  CliError = class extends Error {
8210
9116
  constructor(message, exitCode = 2) {
8211
9117
  super(message);
@@ -8217,12 +9123,52 @@ var init_router = __esm({
8217
9123
  });
8218
9124
 
8219
9125
  // src/cli/config.ts
9126
+ function configPath() {
9127
+ return path7.join(process.env.GATEWAY_CONFIG_DIR || path7.join(os.homedir(), ".gateway"), "config.json");
9128
+ }
9129
+ function readConfig() {
9130
+ let stored;
9131
+ try {
9132
+ stored = JSON.parse(fs6.readFileSync(configPath(), "utf8"));
9133
+ } catch {
9134
+ return {};
9135
+ }
9136
+ const record = stored ?? {};
9137
+ return Object.fromEntries(STORED_FIELDS.filter((f) => typeof record[f] === "string").map((f) => [f, record[f]]));
9138
+ }
9139
+ function personalToken(request = {}) {
9140
+ try {
9141
+ return PersonalToken.fromEnv(process.env, request);
9142
+ } catch (error) {
9143
+ if (error instanceof PersonalTokenRefused) throw new CliError(error.message);
9144
+ throw error;
9145
+ }
9146
+ }
9147
+ function resolveCredentials(hostFlag, secretKeyFlag) {
9148
+ const token = personalToken({ host: hostFlag || void 0, keys: Boolean(secretKeyFlag) });
9149
+ if (token) return { host: token.host, publicKey: "", secretKey: "", token };
9150
+ const stored = readConfig();
9151
+ const explicitHost = (hostFlag || process.env.GATEWAY_HOST || "").replace(/\/+$/, "");
9152
+ const host = explicitHost || (stored.host ?? "").replace(/\/+$/, "");
9153
+ if (!host)
9154
+ throw new CredentialsMissing(
9155
+ "Host not configured. Pass --host, set GATEWAY_HOST, or run `gateway auth login`."
9156
+ );
9157
+ const login = host === (stored.host ?? "").replace(/\/+$/, "") ? stored : {};
9158
+ const publicKey = process.env.GATEWAY_PUBLIC_KEY || login.public_key || "";
9159
+ const secretKey = secretKeyFlag || process.env.GATEWAY_SECRET_KEY || process.env.GATEWAY_API_KEY || login.api_key || "";
9160
+ if (!publicKey || !secretKey)
9161
+ throw new CredentialsMissing(
9162
+ "API key not configured. Set GATEWAY_PUBLIC_KEY and GATEWAY_SECRET_KEY, or run `gateway auth login`."
9163
+ );
9164
+ return { host, publicKey, secretKey };
9165
+ }
8220
9166
  async function api(creds, method, route2, body, init2 = {}) {
8221
9167
  const reply = await new PlatformTransport(creds).send(method, route2, body, init2);
8222
9168
  if (!reply.ok) throw new ApiError2(reply.status, method, route2, reply.text);
8223
9169
  return reply.text ? JSON.parse(reply.text) : {};
8224
9170
  }
8225
- var fs6, os, path7, ApiError2;
9171
+ var fs6, os, path7, STORED_FIELDS, CredentialsMissing, ApiError2;
8226
9172
  var init_config = __esm({
8227
9173
  "src/cli/config.ts"() {
8228
9174
  "use strict";
@@ -8231,7 +9177,11 @@ var init_config = __esm({
8231
9177
  path7 = __toESM(require("path"));
8232
9178
  init_router();
8233
9179
  init_worlds();
9180
+ init_personalToken();
8234
9181
  init_transport();
9182
+ STORED_FIELDS = ["host", "public_key", "api_key"];
9183
+ CredentialsMissing = class extends CliError {
9184
+ };
8235
9185
  ApiError2 = class extends CliError {
8236
9186
  constructor(status, method, route2, text2) {
8237
9187
  const body = parseErrorBody(text2, status);
@@ -8251,7 +9201,37 @@ var init_config = __esm({
8251
9201
  }
8252
9202
  });
8253
9203
 
9204
+ // src/worlds/isolatedPython.ts
9205
+ function isolatedPython(python, args, timeout) {
9206
+ return (0, import_node_child_process2.spawnSync)(python, ["-I", ...args], { encoding: "utf8", timeout, env: PersonalToken.scrubbed(process.env) });
9207
+ }
9208
+ var import_node_child_process2;
9209
+ var init_isolatedPython = __esm({
9210
+ "src/worlds/isolatedPython.ts"() {
9211
+ "use strict";
9212
+ import_node_child_process2 = require("child_process");
9213
+ init_personalToken();
9214
+ }
9215
+ });
9216
+
8254
9217
  // src/cli/runtime/local.ts
9218
+ var local_exports = {};
9219
+ __export(local_exports, {
9220
+ MIN_PYTHON_LABEL: () => MIN_PYTHON_LABEL,
9221
+ assertPortFree: () => assertPortFree,
9222
+ credentialsForRuntime: () => credentialsForRuntime,
9223
+ findPython: () => findPython,
9224
+ localBridge: () => localBridge,
9225
+ localModule: () => localModule,
9226
+ localPythonHasYaml: () => localPythonHasYaml,
9227
+ localRuntime: () => localRuntime,
9228
+ localRuntimeReason: () => localRuntimeReason,
9229
+ portOwner: () => portOwner,
9230
+ pythonAdvice: () => pythonAdvice,
9231
+ resetPythonCache: () => resetPythonCache,
9232
+ runtimeMode: () => runtimeMode,
9233
+ runtimeRoot: () => runtimeRoot
9234
+ });
8255
9235
  function forwardedEnv() {
8256
9236
  return Object.fromEntries(
8257
9237
  FORWARDED_ENV.flatMap((name) => {
@@ -8288,12 +9268,12 @@ function runtimeRoot() {
8288
9268
  return root;
8289
9269
  return null;
8290
9270
  }
9271
+ function resetPythonCache() {
9272
+ pythonCache = void 0;
9273
+ pythonProbes = [];
9274
+ }
8291
9275
  function probeVersion(name) {
8292
- const probe = (0, import_node_child_process2.spawnSync)(
8293
- name,
8294
- ["-c", "import sys;print(sys.version_info[0],sys.version_info[1])"],
8295
- { encoding: "utf8", timeout: 1e4 }
8296
- );
9276
+ const probe = isolatedPython(name, ["-c", "import sys;print(sys.version_info[0],sys.version_info[1])"], 1e4);
8297
9277
  if (probe.status !== 0) return null;
8298
9278
  const [major, minor] = probe.stdout.trim().split(/\s+/).map(Number);
8299
9279
  return Number.isInteger(major) && Number.isInteger(minor) ? `${major}.${minor}` : null;
@@ -8303,7 +9283,7 @@ function atLeastMinimum(version) {
8303
9283
  return major > MIN_PYTHON[0] || major === MIN_PYTHON[0] && minor >= MIN_PYTHON[1];
8304
9284
  }
8305
9285
  function uvPython() {
8306
- const found = (0, import_node_child_process2.spawnSync)("uv", UV_FIND, { encoding: "utf8", timeout: 1e4 });
9286
+ const found = (0, import_node_child_process3.spawnSync)("uv", UV_FIND, { encoding: "utf8", timeout: 1e4, env: PersonalToken.scrubbed(process.env) });
8307
9287
  if (found.status !== 0) return null;
8308
9288
  const line = found.stdout.trim().split(/\r?\n/)[0] ?? "";
8309
9289
  return line || null;
@@ -8362,12 +9342,12 @@ function localRuntime() {
8362
9342
  return { python, root };
8363
9343
  }
8364
9344
  function localPythonHasYaml(python) {
8365
- return (0, import_node_child_process2.spawnSync)(python, ["-c", "import yaml"], { timeout: 1e4 }).status === 0;
9345
+ return isolatedPython(python, ["-c", "import yaml"], 1e4).status === 0;
8366
9346
  }
8367
9347
  async function localBridge(request, local, opts = {}) {
8368
9348
  const input = JSON.stringify(request);
8369
9349
  return await new Promise((resolve7, reject) => {
8370
- const child = (0, import_node_child_process2.spawn)(
9350
+ const child = (0, import_node_child_process3.spawn)(
8371
9351
  local.python,
8372
9352
  ["-I", "-B", "-c", BRIDGE_BOOTSTRAP, local.root],
8373
9353
  {
@@ -8423,16 +9403,92 @@ async function localBridge(request, local, opts = {}) {
8423
9403
  child.stdin.end(input);
8424
9404
  });
8425
9405
  }
8426
- var import_node_child_process2, fs7, net, path8, MIN_PYTHON, MIN_PYTHON_LABEL, DIAGNOSTIC_TAIL, FORWARDED_ENV, BRIDGE_BOOTSTRAP, pythonCache, pythonProbes, PYTHON_CANDIDATES, UV_FIND;
9406
+ function portOwner(port) {
9407
+ const found = (0, import_node_child_process3.spawnSync)("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-Fpc"], {
9408
+ encoding: "utf8",
9409
+ timeout: 5e3
9410
+ });
9411
+ if (found.error || found.status !== 0) return null;
9412
+ let pid = null;
9413
+ let command2 = null;
9414
+ for (const line of found.stdout.split("\n")) {
9415
+ if (line.startsWith("p") && pid === null) pid = line.slice(1);
9416
+ else if (line.startsWith("c") && pid !== null && command2 === null) command2 = line.slice(1);
9417
+ }
9418
+ if (pid === null) return null;
9419
+ return `pid ${pid}${command2 ? ` (${command2})` : ""}`;
9420
+ }
9421
+ async function assertPortFree(port, host = "127.0.0.1") {
9422
+ const taken = await new Promise((resolve7) => {
9423
+ const probe = net.createServer();
9424
+ probe.once("error", () => resolve7(true));
9425
+ probe.listen(port, host, () => probe.close(() => resolve7(false)));
9426
+ });
9427
+ if (!taken) return;
9428
+ const owner = portOwner(port);
9429
+ throw new CliError(
9430
+ `port ${port} on ${host} is already in use${owner ? ` by ${owner}` : ""}; nothing was served there \u2014 pass another --port, or stop that server first`,
9431
+ 1
9432
+ );
9433
+ }
9434
+ async function localModule(argv, local, opts = {}) {
9435
+ return await new Promise((resolve7, reject) => {
9436
+ const child = (0, import_node_child_process3.spawn)(
9437
+ local.python,
9438
+ ["-B", "-c", MODULE_BOOTSTRAP, local.root, ...argv],
9439
+ {
9440
+ stdio: "inherit",
9441
+ cwd: opts.cwd,
9442
+ env: { ...PersonalToken.scrubbed(process.env), ...opts.env }
9443
+ }
9444
+ );
9445
+ const forward = (signal) => () => {
9446
+ if (child.exitCode === null && child.signalCode === null) child.kill(signal);
9447
+ };
9448
+ const handlers = [
9449
+ ["SIGINT", forward("SIGINT")],
9450
+ ["SIGTERM", forward("SIGTERM")],
9451
+ ["SIGHUP", forward("SIGHUP")]
9452
+ ];
9453
+ for (const [signal, handler] of handlers) process.on(signal, handler);
9454
+ const release = () => {
9455
+ for (const [signal, handler] of handlers) process.off(signal, handler);
9456
+ };
9457
+ child.on("error", (error) => {
9458
+ release();
9459
+ reject(
9460
+ new CliError(
9461
+ `local runtime could not start (${local.python}): ${error.message}`,
9462
+ 1
9463
+ )
9464
+ );
9465
+ });
9466
+ child.on("close", (code, signal) => {
9467
+ release();
9468
+ resolve7(code ?? (signal ? 130 : 1));
9469
+ });
9470
+ });
9471
+ }
9472
+ function credentialsForRuntime(hostFlag) {
9473
+ try {
9474
+ return resolveCredentials(hostFlag);
9475
+ } catch (error) {
9476
+ if (error instanceof CliError && localRuntime()) return null;
9477
+ throw error;
9478
+ }
9479
+ }
9480
+ var import_node_child_process3, fs7, net, path8, MIN_PYTHON, MIN_PYTHON_LABEL, DIAGNOSTIC_TAIL, FORWARDED_ENV, BRIDGE_BOOTSTRAP, MODULE_BOOTSTRAP, pythonCache, pythonProbes, PYTHON_CANDIDATES, UV_FIND;
8427
9481
  var init_local = __esm({
8428
9482
  "src/cli/runtime/local.ts"() {
8429
9483
  "use strict";
8430
- import_node_child_process2 = require("child_process");
9484
+ import_node_child_process3 = require("child_process");
8431
9485
  fs7 = __toESM(require("fs"));
8432
9486
  net = __toESM(require("net"));
8433
9487
  path8 = __toESM(require("path"));
8434
9488
  init_router();
8435
9489
  init_config();
9490
+ init_isolatedPython();
9491
+ init_personalToken();
8436
9492
  MIN_PYTHON = [3, 12];
8437
9493
  MIN_PYTHON_LABEL = MIN_PYTHON.join(".");
8438
9494
  DIAGNOSTIC_TAIL = 600;
@@ -8443,6 +9499,13 @@ package=types.ModuleType('gatewaysdk')
8443
9499
  package.__path__=[os.path.join(root,'gatewaysdk')]
8444
9500
  sys.modules['gatewaysdk']=package
8445
9501
  runpy.run_module('gatewaysdk.environment.schema.platform',run_name='__main__')`;
9502
+ MODULE_BOOTSTRAP = `import sys,runpy,types,os
9503
+ root=sys.argv[1]
9504
+ package=types.ModuleType('gatewaysdk')
9505
+ package.__path__=[os.path.join(root,'gatewaysdk')]
9506
+ sys.modules['gatewaysdk']=package
9507
+ sys.argv=['gateway worlds']+sys.argv[2:]
9508
+ runpy.run_module('gatewaysdk.environment.schema',run_name='__main__')`;
8446
9509
  pythonProbes = [];
8447
9510
  PYTHON_CANDIDATES = [
8448
9511
  "python3.13",
@@ -8938,7 +10001,7 @@ async function runTransform(script, records, opts = {}) {
8938
10001
  const { file, args } = command(resolved, scratch);
8939
10002
  const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !SCRUBBED.test(key)));
8940
10003
  const done = await new Promise((resolve7, reject) => {
8941
- const child = (0, import_node_child_process3.spawn)(file, args, { cwd: path11.dirname(resolved), env, stdio: ["pipe", "pipe", "pipe"] });
10004
+ const child = (0, import_node_child_process4.spawn)(file, args, { cwd: path11.dirname(resolved), env, stdio: ["pipe", "pipe", "pipe"] });
8942
10005
  let stdout = "";
8943
10006
  let stderr = "";
8944
10007
  let timedOut = false;
@@ -8976,11 +10039,11 @@ async function transformRecords(transform, records, opts = {}) {
8976
10039
  if (typeof transform === "function") return { rows: checkRows(await transform(records), "transform(records)"), stderr: "" };
8977
10040
  return runTransform(transform, records, opts);
8978
10041
  }
8979
- var import_node_child_process3, fs10, os2, path11, import_node_module, import_meta, DEFAULT_TRANSFORM_TIMEOUT_MS, NODE_SUFFIXES, PYTHON_SUFFIXES, SCRUBBED, PY_WRAPPER, NODE_WRAPPER, isObject, tail;
10042
+ var import_node_child_process4, fs10, os2, path11, import_node_module, import_meta, DEFAULT_TRANSFORM_TIMEOUT_MS, NODE_SUFFIXES, PYTHON_SUFFIXES, SCRUBBED, PY_WRAPPER, NODE_WRAPPER, isObject, tail;
8980
10043
  var init_transform = __esm({
8981
10044
  "src/cli/platform/worldData/transform.ts"() {
8982
10045
  "use strict";
8983
- import_node_child_process3 = require("child_process");
10046
+ import_node_child_process4 = require("child_process");
8984
10047
  fs10 = __toESM(require("fs"));
8985
10048
  os2 = __toESM(require("os"));
8986
10049
  path11 = __toESM(require("path"));
@@ -9551,14 +10614,23 @@ function toolCallsFromObservations(observations, opts = {}) {
9551
10614
  }
9552
10615
  return out;
9553
10616
  }
10617
+ async function runtimeEndpoint(options) {
10618
+ try {
10619
+ return platformEndpoint(options);
10620
+ } catch (error) {
10621
+ const { localRuntime: localRuntime2 } = await Promise.resolve().then(() => (init_local(), local_exports));
10622
+ if (error instanceof PersonalTokenRefused && localRuntime2()) return null;
10623
+ throw error;
10624
+ }
10625
+ }
9554
10626
  async function ingest(world, records, options = {}) {
9555
10627
  const { ingestLocalToolCalls: ingestLocalToolCalls2, importLocalWorldData: importLocalWorldData2, checkLocalWorldData: checkLocalWorldData2 } = await Promise.resolve().then(() => (init_data(), data_exports));
9556
10628
  if (options.transform !== void 0 && options.map !== void 0) throw new Error("records go through one of transform, map");
9557
10629
  const redact = options.redact ?? "off";
9558
10630
  const mode = options.mode ?? "append";
9559
10631
  const dryRun = Boolean(options.dryRun);
9560
- const creds = platformEndpoint(options);
9561
10632
  const local = fs12.existsSync(world) && fs12.statSync(world).isDirectory();
10633
+ const creds = local ? await runtimeEndpoint(options) : platformEndpoint(options);
9562
10634
  const map = options.map === void 0 ? void 0 : options.map;
9563
10635
  let rows = null;
9564
10636
  let stderr = "";
@@ -9659,6 +10731,7 @@ var init_ingest = __esm({
9659
10731
  path12 = __toESM(require("path"));
9660
10732
  init_worlds();
9661
10733
  init_platformEndpoint();
10734
+ init_personalToken();
9662
10735
  isObject2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
9663
10736
  isoOf = (value) => value instanceof Date ? value.toISOString() : typeof value === "string" ? value : void 0;
9664
10737
  }
@@ -9716,6 +10789,38 @@ var init_editSessions = __esm({
9716
10789
  }
9717
10790
  });
9718
10791
 
10792
+ // src/worlds/states.ts
10793
+ var WORLDS3, refQuery, WorldStateClient;
10794
+ var init_states = __esm({
10795
+ "src/worlds/states.ts"() {
10796
+ "use strict";
10797
+ init_worlds();
10798
+ WORLDS3 = "/api/public/worlds";
10799
+ refQuery = (ref) => ref ? `?${new URLSearchParams({ ref })}` : "";
10800
+ WorldStateClient = class {
10801
+ constructor(options = {}) {
10802
+ this.options = options;
10803
+ }
10804
+ options;
10805
+ list(slug) {
10806
+ return apiRequest(this.options, "GET", `${WORLDS3}/${encodeURIComponent(slug)}/states`);
10807
+ }
10808
+ show(slug, name, ref) {
10809
+ return apiRequest(this.options, "GET", `${WORLDS3}/${encodeURIComponent(slug)}/states/${encodeURIComponent(name)}` + refQuery(ref));
10810
+ }
10811
+ create(slug, input) {
10812
+ return apiRequest(this.options, "POST", `${WORLDS3}/${encodeURIComponent(slug)}/states`, input);
10813
+ }
10814
+ delete(slug, name) {
10815
+ return apiRequest(this.options, "DELETE", `${WORLDS3}/${encodeURIComponent(slug)}/states/${encodeURIComponent(name)}`);
10816
+ }
10817
+ pull(slug, name, ref) {
10818
+ return apiRequest(this.options, "GET", `${WORLDS3}/${encodeURIComponent(slug)}/states/${encodeURIComponent(name)}/pull` + refQuery(ref));
10819
+ }
10820
+ };
10821
+ }
10822
+ });
10823
+
9719
10824
  // src/worlds/dryRun.ts
9720
10825
  var DRY_RUN_KIND, DRY_RUN_AGENT, STATUS_WAIT_CAP_SECONDS, cid, HostedDryRunClient, DryRunOutcome;
9721
10826
  var init_dryRun = __esm({
@@ -9849,9 +10954,14 @@ __export(worlds_exports, {
9849
10954
  OpenAIComputer: () => OpenAIComputer,
9850
10955
  OpenAIPreviewComputer: () => OpenAIPreviewComputer,
9851
10956
  PLATFORM_SESSION_HEADER: () => PLATFORM_SESSION_HEADER,
10957
+ PLATFORM_STREAM_IDLE_MS: () => PLATFORM_STREAM_IDLE_MS,
9852
10958
  PLATFORM_TIMEOUT_DEFAULT_MS: () => PLATFORM_TIMEOUT_DEFAULT_MS,
9853
10959
  PLATFORM_TIMEOUT_ENV: () => PLATFORM_TIMEOUT_ENV,
10960
+ PageObserver: () => PageObserver,
10961
+ PageState: () => PageState,
10962
+ PageStateError: () => PageStateError,
9854
10963
  PendingSafetyChecks: () => PendingSafetyChecks,
10964
+ PlatformStream: () => PlatformStream,
9855
10965
  PlatformTransport: () => PlatformTransport,
9856
10966
  PushSlugConflict: () => PushSlugConflict,
9857
10967
  RECOVER_BUDGET_MS: () => RECOVER_BUDGET_MS,
@@ -9904,6 +11014,7 @@ __export(worlds_exports, {
9904
11014
  WorldSessionOpenFailed: () => WorldSessionOpenFailed,
9905
11015
  WorldSessionTimeout: () => WorldSessionTimeout,
9906
11016
  WorldSet: () => WorldSet,
11017
+ WorldStateClient: () => WorldStateClient,
9907
11018
  WorldSurfaceUnavailable: () => WorldSurfaceUnavailable,
9908
11019
  WorldTask: () => WorldTask,
9909
11020
  WorldToolsUnread: () => WorldToolsUnread,
@@ -9971,6 +11082,7 @@ __export(worlds_exports, {
9971
11082
  parseToolCallRecord: () => parseToolCallRecord,
9972
11083
  parseTransform: () => parseTransform,
9973
11084
  parseWorldTaskRefs: () => parseWorldTaskRefs,
11085
+ platformAuthorization: () => platformAuthorization,
9974
11086
  platformTimeoutMs: () => platformTimeoutMs,
9975
11087
  playwrightKey: () => playwrightKey,
9976
11088
  preserveForm: () => preserveForm,
@@ -9997,6 +11109,7 @@ __export(worlds_exports, {
9997
11109
  runSet: () => runSet,
9998
11110
  runTask: () => runTask,
9999
11111
  schemaFromSignature: () => schemaFromSignature,
11112
+ scrubError: () => scrubError,
10000
11113
  serializeCallBody: () => serializeCallBody,
10001
11114
  sessionToolObservations: () => sessionToolObservations,
10002
11115
  setEnvSecret: () => setEnvSecret,
@@ -10025,43 +11138,8 @@ __export(worlds_exports, {
10025
11138
  writeLocalMeta: () => writeLocalMeta
10026
11139
  });
10027
11140
  module.exports = __toCommonJS(worlds_exports);
10028
- function edgeAnswer(text2, status) {
10029
- if (status !== void 0 && status >= 500) return EDGE_ANSWERS[status] ?? EDGE_FAILURE;
10030
- return /^\s*</.test(text2) ? EDGE_PAGE : null;
10031
- }
10032
- function parseErrorBody(text2, status) {
10033
- const raw = { detail: text2.slice(0, DETAIL_LIMIT), code: null };
10034
- let parsed;
10035
- try {
10036
- parsed = JSON.parse(text2);
10037
- } catch {
10038
- return { detail: (edgeAnswer(text2, status) ?? text2).slice(0, DETAIL_LIMIT), code: null };
10039
- }
10040
- if (parsed === null || typeof parsed !== "object") return raw;
10041
- const { message, code, error } = parsed;
10042
- const stableCode = typeof code === "string" ? code : null;
10043
- if (typeof message !== "string") return { ...raw, code: stableCode };
10044
- const fields = invalidFields(error);
10045
- const said = fields ? `${message}: ${fields}` : message;
10046
- if (stableCode === null) return { detail: said.slice(0, DETAIL_LIMIT), code: null };
10047
- return {
10048
- detail: `${said} (${stableCode})`.slice(0, DETAIL_LIMIT),
10049
- code: stableCode
10050
- };
10051
- }
10052
- function invalidFields(error) {
10053
- const issues = Array.isArray(error) ? error : [];
10054
- return issues.filter(
10055
- (issue) => issue !== null && typeof issue === "object" && typeof issue.message === "string"
10056
- ).map((issue) => {
10057
- const path13 = Array.isArray(issue.path) ? issue.path.map(String).join(".") : "";
10058
- return path13 ? `${path13}: ${issue.message}` : issue.message;
10059
- }).join("; ");
10060
- }
10061
11141
  async function apiRequest(options, method, path13, body, init2 = {}) {
10062
- const reply = await new PlatformTransport(requirePlatformEndpoint(options)).send(method, path13, body, init2);
10063
- if (!reply.ok) throw new ApiError(reply.status, method, path13, reply.text);
10064
- return JSON.parse(reply.text);
11142
+ return new PlatformTransport(requirePlatformEndpoint(options)).json(method, path13, body, init2);
10065
11143
  }
10066
11144
  async function setEnvSecret(slug, key, value, options = {}) {
10067
11145
  return apiRequest(
@@ -10236,11 +11314,12 @@ async function resolveWorld(slugRef, slug, ref, pin, options) {
10236
11314
  }
10237
11315
  return world;
10238
11316
  }
10239
- var ApiError, DETAIL_LIMIT, EDGE_ANSWERS, EDGE_FAILURE, EDGE_PAGE, WorldTask, WorldSet;
11317
+ var WorldTask, WorldSet;
10240
11318
  var init_worlds = __esm({
10241
11319
  "src/worlds/index.ts"() {
10242
11320
  init_platformEndpoint();
10243
11321
  init_transport();
11322
+ init_apiError();
10244
11323
  init_transport();
10245
11324
  init_session2();
10246
11325
  init_grade();
@@ -10255,6 +11334,8 @@ var init_worlds = __esm({
10255
11334
  init_checkoutProvenance();
10256
11335
  init_evals();
10257
11336
  init_browser();
11337
+ init_browserTools();
11338
+ init_pageState();
10258
11339
  init_surfaceDescriptor();
10259
11340
  init_requestLog();
10260
11341
  init_requestLedger();
@@ -10271,29 +11352,9 @@ var init_worlds = __esm({
10271
11352
  init_ingest();
10272
11353
  init_sandbox();
10273
11354
  init_editSessions();
11355
+ init_states();
10274
11356
  init_dryRun();
10275
11357
  init_worldNotice();
10276
- ApiError = class extends Error {
10277
- constructor(status, method, path13, text2) {
10278
- const parsed = parseErrorBody(text2, status);
10279
- super(`${method} ${path13} -> ${status}: ${parsed.detail}`);
10280
- this.status = status;
10281
- this.text = text2;
10282
- this.name = "ApiError";
10283
- this.code = parsed.code;
10284
- }
10285
- status;
10286
- text;
10287
- code;
10288
- };
10289
- DETAIL_LIMIT = 600;
10290
- EDGE_ANSWERS = {
10291
- 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.",
10292
- 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.",
10293
- 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."
10294
- };
10295
- 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.";
10296
- 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.";
10297
11358
  WorldTask = class {
10298
11359
  constructor(world, name, variant) {
10299
11360
  this.world = world;
@@ -10403,9 +11464,14 @@ init_worlds();
10403
11464
  OpenAIComputer,
10404
11465
  OpenAIPreviewComputer,
10405
11466
  PLATFORM_SESSION_HEADER,
11467
+ PLATFORM_STREAM_IDLE_MS,
10406
11468
  PLATFORM_TIMEOUT_DEFAULT_MS,
10407
11469
  PLATFORM_TIMEOUT_ENV,
11470
+ PageObserver,
11471
+ PageState,
11472
+ PageStateError,
10408
11473
  PendingSafetyChecks,
11474
+ PlatformStream,
10409
11475
  PlatformTransport,
10410
11476
  PushSlugConflict,
10411
11477
  RECOVER_BUDGET_MS,
@@ -10458,6 +11524,7 @@ init_worlds();
10458
11524
  WorldSessionOpenFailed,
10459
11525
  WorldSessionTimeout,
10460
11526
  WorldSet,
11527
+ WorldStateClient,
10461
11528
  WorldSurfaceUnavailable,
10462
11529
  WorldTask,
10463
11530
  WorldToolsUnread,
@@ -10525,6 +11592,7 @@ init_worlds();
10525
11592
  parseToolCallRecord,
10526
11593
  parseTransform,
10527
11594
  parseWorldTaskRefs,
11595
+ platformAuthorization,
10528
11596
  platformTimeoutMs,
10529
11597
  playwrightKey,
10530
11598
  preserveForm,
@@ -10551,6 +11619,7 @@ init_worlds();
10551
11619
  runSet,
10552
11620
  runTask,
10553
11621
  schemaFromSignature,
11622
+ scrubError,
10554
11623
  serializeCallBody,
10555
11624
  sessionToolObservations,
10556
11625
  setEnvSecret,