@withgateway/sdk 0.6.0 → 0.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/dist/agents/index.d.mts +581 -0
  2. package/dist/agents/index.d.ts +581 -0
  3. package/dist/agents/index.js +1473 -0
  4. package/dist/agents/index.js.map +1 -0
  5. package/dist/agents/index.mjs +1424 -0
  6. package/dist/agents/index.mjs.map +1 -0
  7. package/dist/apiError-DHpfbmdx.d.mts +17 -0
  8. package/dist/apiError-DHpfbmdx.d.ts +17 -0
  9. package/dist/cli.js +11611 -6845
  10. package/dist/cli.js.map +1 -1
  11. package/dist/cli.mjs +10090 -5325
  12. package/dist/cli.mjs.map +1 -1
  13. package/dist/files/index.d.mts +3 -1
  14. package/dist/files/index.d.ts +3 -1
  15. package/dist/files/index.js +371 -102
  16. package/dist/files/index.js.map +1 -1
  17. package/dist/files/index.mjs +371 -102
  18. package/dist/files/index.mjs.map +1 -1
  19. package/dist/hooks/index.js +346 -136
  20. package/dist/hooks/index.js.map +1 -1
  21. package/dist/hooks/index.mjs +346 -136
  22. package/dist/hooks/index.mjs.map +1 -1
  23. package/dist/{index-LA-PMRJT.d.ts → index-DIN14Lhg.d.ts} +1 -1
  24. package/dist/{index-Di9nNqOY.d.mts → index-DuB-eQ0Z.d.mts} +1 -1
  25. package/dist/index.d.mts +7 -4
  26. package/dist/index.d.ts +7 -4
  27. package/dist/index.js +3177 -748
  28. package/dist/index.js.map +1 -1
  29. package/dist/index.mjs +2987 -590
  30. package/dist/index.mjs.map +1 -1
  31. package/dist/media-CQUC7TkS.d.mts +39 -0
  32. package/dist/media-DQnBloaX.d.ts +39 -0
  33. package/dist/traces/index.d.mts +3 -1
  34. package/dist/traces/index.d.ts +3 -1
  35. package/dist/traces/index.js +371 -102
  36. package/dist/traces/index.js.map +1 -1
  37. package/dist/traces/index.mjs +371 -102
  38. package/dist/traces/index.mjs.map +1 -1
  39. package/dist/tracing/index.d.mts +3 -2
  40. package/dist/tracing/index.d.ts +3 -2
  41. package/dist/tracing/index.js +257 -16
  42. package/dist/tracing/index.js.map +1 -1
  43. package/dist/tracing/index.mjs +257 -16
  44. package/dist/tracing/index.mjs.map +1 -1
  45. package/dist/transport-CpRe7zgd.d.mts +123 -0
  46. package/dist/transport-CpRe7zgd.d.ts +123 -0
  47. package/dist/worlds/index.d.mts +1986 -1746
  48. package/dist/worlds/index.d.ts +1986 -1746
  49. package/dist/worlds/index.js +1470 -290
  50. package/dist/worlds/index.js.map +1 -1
  51. package/dist/worlds/index.mjs +1465 -286
  52. package/dist/worlds/index.mjs.map +1 -1
  53. package/package.json +6 -1
  54. package/runtime/gatewaysdk/environment/bundle_manifest.py +531 -0
  55. package/runtime/gatewaysdk/environment/factory_documents.py +670 -0
  56. package/runtime/gatewaysdk/environment/factory_rules.py +973 -0
  57. package/runtime/gatewaysdk/environment/factory_shapes.py +253 -0
  58. package/runtime/gatewaysdk/environment/factory_spine.py +1155 -0
  59. package/runtime/gatewaysdk/environment/factory_spine_shapes.py +480 -0
  60. package/runtime/gatewaysdk/environment/schema/__main__.py +2 -2
  61. package/runtime/gatewaysdk/environment/schema/_slack_fidelity.py +8 -23
  62. package/runtime/gatewaysdk/environment/schema/admission.py +61 -59
  63. package/runtime/gatewaysdk/environment/schema/api.py +3 -4
  64. package/runtime/gatewaysdk/environment/schema/assertions.py +7 -1
  65. package/runtime/gatewaysdk/environment/schema/bundle_runtime.py +1 -0
  66. package/runtime/gatewaysdk/environment/schema/call_log.py +20 -0
  67. package/runtime/gatewaysdk/environment/schema/cast.py +133 -67
  68. package/runtime/gatewaysdk/environment/schema/compiler.py +16 -17
  69. package/runtime/gatewaysdk/environment/schema/database/base.py +2 -2
  70. package/runtime/gatewaysdk/environment/schema/handler_errors.py +58 -4
  71. package/runtime/gatewaysdk/environment/schema/host.py +94 -12
  72. package/runtime/gatewaysdk/environment/schema/host_browser.py +48 -0
  73. package/runtime/gatewaysdk/environment/schema/host_control.py +35 -2
  74. package/runtime/gatewaysdk/environment/schema/host_handoff.py +4 -1
  75. package/runtime/gatewaysdk/environment/schema/host_loops.py +27 -4
  76. package/runtime/gatewaysdk/environment/schema/host_metrics.py +69 -0
  77. package/runtime/gatewaysdk/environment/schema/host_requests.py +35 -0
  78. package/runtime/gatewaysdk/environment/schema/host_session.py +20 -2
  79. package/runtime/gatewaysdk/environment/schema/host_surfaces.py +6 -0
  80. package/runtime/gatewaysdk/environment/schema/host_versions.py +100 -19
  81. package/runtime/gatewaysdk/environment/schema/host_workers.py +172 -50
  82. package/runtime/gatewaysdk/environment/schema/ingest.py +12 -3
  83. package/runtime/gatewaysdk/environment/schema/journal.py +7 -2
  84. package/runtime/gatewaysdk/environment/schema/local.py +32 -7
  85. package/runtime/gatewaysdk/environment/schema/mapping.py +1 -1
  86. package/runtime/gatewaysdk/environment/schema/measured_tests.py +187 -0
  87. package/runtime/gatewaysdk/environment/schema/page_checks.py +123 -0
  88. package/runtime/gatewaysdk/environment/schema/platform.py +80 -270
  89. package/runtime/gatewaysdk/environment/schema/platform_query.py +4 -3
  90. package/runtime/gatewaysdk/environment/schema/platform_templates.py +420 -0
  91. package/runtime/gatewaysdk/environment/schema/process_memory.py +76 -0
  92. package/runtime/gatewaysdk/environment/schema/redaction.py +13 -0
  93. package/runtime/gatewaysdk/environment/schema/request_ledger.py +4 -1
  94. package/runtime/gatewaysdk/environment/schema/run_parameters.py +25 -0
  95. package/runtime/gatewaysdk/environment/schema/runtime.py +57 -5
  96. package/runtime/gatewaysdk/environment/schema/scaffold.py +386 -219
  97. package/runtime/gatewaysdk/environment/schema/session_files.py +13 -2
  98. package/runtime/gatewaysdk/environment/schema/shape_catalog.py +493 -0
  99. package/runtime/gatewaysdk/environment/schema/shape_declarations.py +219 -0
  100. package/runtime/gatewaysdk/environment/schema/skill.py +1 -0
  101. package/runtime/gatewaysdk/environment/schema/skills/benchmarks-getting-started/SKILL.md +1 -1
  102. package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/SKILL.md +2 -2
  103. package/runtime/gatewaysdk/environment/schema/skills/factory-orchestrator/SKILL.md +147 -0
  104. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/ROWS.md +5 -1
  105. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/SKILL.md +8 -6
  106. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/SKILL.md +9 -9
  107. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/cli-mcp-map.md +33 -2
  108. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/gotchas.md +6 -6
  109. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/journal-checks.md +17 -2
  110. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/new-world-sandbox.md +1 -1
  111. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/shape-catalog.md +59 -0
  112. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/ui-map.md +3 -2
  113. package/runtime/gatewaysdk/environment/schema/slack.py +55 -10
  114. package/runtime/gatewaysdk/environment/schema/snapshot.py +28 -2
  115. package/runtime/gatewaysdk/environment/schema/tasks.py +25 -2
  116. package/runtime/gatewaysdk/environment/schema/template_record.py +131 -0
  117. package/runtime/gatewaysdk/environment/schema/tools_world.py +7 -5
  118. package/runtime/gatewaysdk/environment/schema/ui.py +54 -33
  119. package/runtime/gatewaysdk/environment/schema/ui_interactions.py +419 -0
  120. package/runtime/gatewaysdk/environment/schema/ui_recorder.js +895 -0
  121. package/runtime/gatewaysdk/environment/schema/ui_replay.py +366 -0
  122. package/runtime/gatewaysdk/environment/schema/ui_replay_record.LICENSE +25 -0
  123. package/runtime/gatewaysdk/environment/schema/ui_replay_record.js +109 -0
  124. package/runtime/gatewaysdk/environment/schema/validation.py +24 -1
  125. package/runtime/gatewaysdk/environment/schema/worker.py +12 -5
  126. package/runtime/gatewaysdk/environment/schema/worker_key.py +38 -0
  127. package/runtime/gatewaysdk/environment/schema/worker_peaks.py +38 -0
  128. package/runtime/gatewaysdk/environment/schema/worker_watch.py +50 -0
  129. package/runtime/gatewaysdk/environment/schema/workers.py +245 -69
  130. package/runtime/gatewaysdk/environment/schema/world_host.py +96 -73
  131. package/runtime/gatewaysdk/environment/schema/world_tests.py +3 -1
  132. package/runtime/gatewaysdk/environment/secret_values.py +1 -1
  133. package/runtime/gatewaysdk/environment/world.py +34 -43
  134. package/runtime/gatewaysdk/environment/world_session_contract.py +7 -34
  135. package/skills/benchmarks-getting-started/SKILL.md +1 -1
  136. package/skills/connector-schema-authoring/SKILL.md +2 -2
  137. package/skills/connector-schema-authoring/connector-worlds.md +3 -2
  138. package/skills/connector-schema-authoring/world-schema.md +36 -23
  139. package/skills/factory-orchestrator/SKILL.md +147 -0
  140. package/skills/world-data-ingestion/ROWS.md +5 -1
  141. package/skills/world-data-ingestion/SKILL.md +8 -6
  142. package/skills/worlds-getting-started/SKILL.md +9 -9
  143. package/skills/worlds-getting-started/references/cli-mcp-map.md +33 -2
  144. package/skills/worlds-getting-started/references/gotchas.md +6 -6
  145. package/skills/worlds-getting-started/references/journal-checks.md +17 -2
  146. package/skills/worlds-getting-started/references/new-world-sandbox.md +1 -1
  147. package/skills/worlds-getting-started/references/shape-catalog.md +59 -0
  148. package/skills/worlds-getting-started/references/ui-map.md +3 -2
  149. package/dist/media-BIApiPzS.d.mts +0 -102
  150. package/dist/media-BIApiPzS.d.ts +0 -102
@@ -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 path14 = Array.isArray(issue.path) ? issue.path.map(String).join(".") : "";
163
+ return path14 ? `${path14}: ${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, path14, text2) {
172
+ const parsed = parseErrorBody(text2, status);
173
+ super(`${method} ${path14} -> ${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
+ ];
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
+ }
231
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 {
@@ -405,9 +806,9 @@ function surfaceKinds(s) {
405
806
  if (s.browser) kinds.push("browser");
406
807
  return kinds;
407
808
  }
408
- function uiUrl(ui, path13) {
809
+ function uiUrl(ui, path14) {
409
810
  const base = ui.url.replace(/\/+$/, "");
410
- const rel = path13.startsWith("/") ? path13 : `/${path13}`;
811
+ const rel = path14.startsWith("/") ? path14 : `/${path14}`;
411
812
  if (!ui.token) return base + rel;
412
813
  const [beforeHash, hash] = splitHash(rel);
413
814
  const joiner = beforeHash.includes("?") ? "&" : "?";
@@ -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,41 +1335,549 @@ 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");
965
1374
  }
966
1375
  async close() {
967
1376
  try {
968
- await this.teardown();
969
- } finally {
970
- await this.recorder?.close();
1377
+ await this.teardown();
1378
+ } finally {
1379
+ await this.recorder?.close();
1380
+ }
1381
+ }
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;
971
1776
  }
972
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
973
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
@@ -1327,13 +2226,13 @@ var init_screen = __esm({
1327
2226
  });
1328
2227
  }
1329
2228
  async drag(action) {
1330
- const path13 = action.args.path ?? [];
1331
- if (path13.length < 2) throw new Error("a drag needs at least two points");
2229
+ const path14 = action.args.path ?? [];
2230
+ if (path14.length < 2) throw new Error("a drag needs at least two points");
1332
2231
  return this.held(action.args.modifiers ?? [], async () => {
1333
- await this.moveTo(path13[0]);
2232
+ await this.moveTo(path14[0]);
1334
2233
  await this.page.mouse.down({ button: "left" });
1335
2234
  try {
1336
- for (const point2 of path13.slice(1)) await this.moveTo(point2, DRAG_STEPS);
2235
+ for (const point2 of path14.slice(1)) await this.moveTo(point2, DRAG_STEPS);
1337
2236
  } finally {
1338
2237
  await this.page.mouse.up({ button: "left" });
1339
2238
  }
@@ -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() {
@@ -3162,17 +4066,17 @@ var init_session2 = __esm({
3162
4066
  }
3163
4067
  /** The reporter `browser()` uses; exposed for a page you drive yourself. */
3164
4068
  browserRecorder(agentId) {
3165
- const path13 = `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/browser-events`;
4069
+ const path14 = `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/browser-events`;
3166
4070
  const id = agentId ?? process.env.GATEWAY_AGENT_ID ?? `agent-${(0, import_node_crypto2.randomUUID)().replace(/-/g, "").slice(0, 8)}`;
3167
4071
  return new BrowserActionRecorder(
3168
4072
  async (events) => {
3169
- await apiRequest(this.options, "POST", path13, { events });
4073
+ await apiRequest(this.options, "POST", path14, { events });
3170
4074
  },
3171
4075
  id,
3172
4076
  {
3173
4077
  // Continue this agent's timeline where the platform has it, so a reopened id never re-numbers from zero.
3174
4078
  resumeFrom: async () => {
3175
- const summary = await apiRequest(this.options, "GET", path13);
4079
+ const summary = await apiRequest(this.options, "GET", path14);
3176
4080
  return summary.agents.find((a) => a.agentId === id)?.nextSeq ?? 0;
3177
4081
  }
3178
4082
  }
@@ -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;
@@ -4117,8 +5029,8 @@ var init_taskRunDir = __esm({
4117
5029
  path = __toESM(require("path"));
4118
5030
  init_browser();
4119
5031
  TaskRunDir = class {
4120
- constructor(path13) {
4121
- this.path = path13;
5032
+ constructor(path14) {
5033
+ this.path = path14;
4122
5034
  }
4123
5035
  path;
4124
5036
  writeManifest(manifest) {
@@ -4517,10 +5429,10 @@ var init_users = __esm({
4517
5429
  totalItems: Number(meta.totalItems ?? rows.length)
4518
5430
  };
4519
5431
  }
4520
- async requestJson(method, path13, payload) {
5432
+ async requestJson(method, path14, payload) {
4521
5433
  let response;
4522
5434
  try {
4523
- response = await fetch(`${this.host}${path13}`, {
5435
+ response = await fetch(`${this.host}${path14}`, {
4524
5436
  method,
4525
5437
  headers: {
4526
5438
  Authorization: this.authHeader(),
@@ -4531,17 +5443,17 @@ var init_users = __esm({
4531
5443
  });
4532
5444
  } catch (error) {
4533
5445
  throw new UserProfileError(
4534
- `${method} ${path13} failed: ${error instanceof Error ? error.message : String(error)}`,
5446
+ `${method} ${path14} failed: ${error instanceof Error ? error.message : String(error)}`,
4535
5447
  { cause: error }
4536
5448
  );
4537
5449
  }
4538
5450
  const text2 = await response.text();
4539
5451
  if (!response.ok) {
4540
5452
  throw new UserProfileError(
4541
- `${method} ${path13} failed (${response.status}): ${text2.slice(0, 500)}`
5453
+ `${method} ${path14} failed (${response.status}): ${text2.slice(0, 500)}`
4542
5454
  );
4543
5455
  }
4544
- this.log("%s %s -> %s", method, path13, response.status);
5456
+ this.log("%s %s -> %s", method, path14, response.status);
4545
5457
  return safeJson(text2);
4546
5458
  }
4547
5459
  authHeader() {
@@ -4986,10 +5898,10 @@ var init_scores = __esm({
4986
5898
  metadata: signalMetadata
4987
5899
  });
4988
5900
  }
4989
- async request(method, path13, payload) {
5901
+ async request(method, path14, payload) {
4990
5902
  let response;
4991
5903
  try {
4992
- response = await fetch(`${this.host}${path13}`, {
5904
+ response = await fetch(`${this.host}${path14}`, {
4993
5905
  method,
4994
5906
  headers: {
4995
5907
  Authorization: this.authHeader(),
@@ -5000,17 +5912,17 @@ var init_scores = __esm({
5000
5912
  });
5001
5913
  } catch (error) {
5002
5914
  throw new ScoreError(
5003
- `${method} ${path13} failed: ${error instanceof Error ? error.message : String(error)}`,
5915
+ `${method} ${path14} failed: ${error instanceof Error ? error.message : String(error)}`,
5004
5916
  { cause: error }
5005
5917
  );
5006
5918
  }
5007
5919
  const text2 = await response.text();
5008
5920
  if (!response.ok) {
5009
5921
  throw new ScoreError(
5010
- `${method} ${path13} failed (${response.status}): ${text2.slice(0, 500)}`
5922
+ `${method} ${path14} failed (${response.status}): ${text2.slice(0, 500)}`
5011
5923
  );
5012
5924
  }
5013
- this.log("%s %s -> %s", method, path13, response.status);
5925
+ this.log("%s %s -> %s", method, path14, response.status);
5014
5926
  }
5015
5927
  authHeader() {
5016
5928
  return `Basic ${Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(
@@ -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.3",
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,
@@ -7428,7 +8333,7 @@ function rebaseConflicts(error) {
7428
8333
  }
7429
8334
  const conflicts = body?.conflicts;
7430
8335
  if (!Array.isArray(conflicts)) return null;
7431
- return conflicts.filter(isConflictPath).map(({ path: path13, reason }) => ({ path: path13, reason }));
8336
+ return conflicts.filter(isConflictPath).map(({ path: path14, reason }) => ({ path: path14, reason }));
7432
8337
  }
7433
8338
  function isConflictPath(value) {
7434
8339
  const entry = value;
@@ -7553,15 +8458,15 @@ var init_sandbox = __esm({
7553
8458
  this.options = options;
7554
8459
  }
7555
8460
  options;
7556
- request(method, path13, body) {
7557
- return apiRequest(this.options, method, path13, body, {
8461
+ request(method, path14, body) {
8462
+ return apiRequest(this.options, method, path14, body, {
7558
8463
  timeoutMs: SANDBOX_REQUEST_TIMEOUT_MS
7559
8464
  });
7560
8465
  }
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) {
@@ -7684,13 +8589,16 @@ var init_sandbox = __esm({
7684
8589
  });
7685
8590
 
7686
8591
  // src/worlds/describe.ts
7687
- async function describeWorld(slugRef, options = {}) {
8592
+ async function describeWorld(slugRef, options = {}, entity) {
7688
8593
  const { slug, ref } = parseSlugRef(slugRef);
7689
- const query = ref === void 0 ? "" : `?ref=${encodeURIComponent(ref)}`;
8594
+ const query = new URLSearchParams();
8595
+ if (ref !== void 0) query.set("ref", ref);
8596
+ if (entity !== void 0) query.set("entity", entity);
8597
+ const search = query.toString() ? `?${query}` : "";
7690
8598
  return apiRequest(
7691
8599
  options,
7692
8600
  "GET",
7693
- `/api/public/worlds/${encodeURIComponent(slug)}${query}`
8601
+ `/api/public/worlds/${encodeURIComponent(slug)}${search}`
7694
8602
  );
7695
8603
  }
7696
8604
  var init_describe = __esm({
@@ -8206,6 +9114,7 @@ var CliError;
8206
9114
  var init_router = __esm({
8207
9115
  "src/cli/router.ts"() {
8208
9116
  "use strict";
9117
+ init_personalToken();
8209
9118
  CliError = class extends Error {
8210
9119
  constructor(message, exitCode = 2) {
8211
9120
  super(message);
@@ -8217,12 +9126,52 @@ var init_router = __esm({
8217
9126
  });
8218
9127
 
8219
9128
  // src/cli/config.ts
9129
+ function configPath() {
9130
+ return path7.join(process.env.GATEWAY_CONFIG_DIR || path7.join(os.homedir(), ".gateway"), "config.json");
9131
+ }
9132
+ function readConfig() {
9133
+ let stored;
9134
+ try {
9135
+ stored = JSON.parse(fs6.readFileSync(configPath(), "utf8"));
9136
+ } catch {
9137
+ return {};
9138
+ }
9139
+ const record = stored ?? {};
9140
+ return Object.fromEntries(STORED_FIELDS.filter((f) => typeof record[f] === "string").map((f) => [f, record[f]]));
9141
+ }
9142
+ function personalToken(request = {}) {
9143
+ try {
9144
+ return PersonalToken.fromEnv(process.env, request);
9145
+ } catch (error) {
9146
+ if (error instanceof PersonalTokenRefused) throw new CliError(error.message);
9147
+ throw error;
9148
+ }
9149
+ }
9150
+ function resolveCredentials(hostFlag, secretKeyFlag) {
9151
+ const token = personalToken({ host: hostFlag || void 0, keys: Boolean(secretKeyFlag) });
9152
+ if (token) return { host: token.host, publicKey: "", secretKey: "", token };
9153
+ const stored = readConfig();
9154
+ const explicitHost = (hostFlag || process.env.GATEWAY_HOST || "").replace(/\/+$/, "");
9155
+ const host = explicitHost || (stored.host ?? "").replace(/\/+$/, "");
9156
+ if (!host)
9157
+ throw new CredentialsMissing(
9158
+ "Host not configured. Pass --host, set GATEWAY_HOST, or run `gateway auth login`."
9159
+ );
9160
+ const login = host === (stored.host ?? "").replace(/\/+$/, "") ? stored : {};
9161
+ const publicKey = process.env.GATEWAY_PUBLIC_KEY || login.public_key || "";
9162
+ const secretKey = secretKeyFlag || process.env.GATEWAY_SECRET_KEY || process.env.GATEWAY_API_KEY || login.api_key || "";
9163
+ if (!publicKey || !secretKey)
9164
+ throw new CredentialsMissing(
9165
+ "API key not configured. Set GATEWAY_PUBLIC_KEY and GATEWAY_SECRET_KEY, or run `gateway auth login`."
9166
+ );
9167
+ return { host, publicKey, secretKey };
9168
+ }
8220
9169
  async function api(creds, method, route2, body, init2 = {}) {
8221
9170
  const reply = await new PlatformTransport(creds).send(method, route2, body, init2);
8222
9171
  if (!reply.ok) throw new ApiError2(reply.status, method, route2, reply.text);
8223
9172
  return reply.text ? JSON.parse(reply.text) : {};
8224
9173
  }
8225
- var fs6, os, path7, ApiError2;
9174
+ var fs6, os, path7, STORED_FIELDS, CredentialsMissing, ApiError2;
8226
9175
  var init_config = __esm({
8227
9176
  "src/cli/config.ts"() {
8228
9177
  "use strict";
@@ -8231,7 +9180,11 @@ var init_config = __esm({
8231
9180
  path7 = __toESM(require("path"));
8232
9181
  init_router();
8233
9182
  init_worlds();
9183
+ init_personalToken();
8234
9184
  init_transport();
9185
+ STORED_FIELDS = ["host", "public_key", "api_key"];
9186
+ CredentialsMissing = class extends CliError {
9187
+ };
8235
9188
  ApiError2 = class extends CliError {
8236
9189
  constructor(status, method, route2, text2) {
8237
9190
  const body = parseErrorBody(text2, status);
@@ -8251,7 +9204,37 @@ var init_config = __esm({
8251
9204
  }
8252
9205
  });
8253
9206
 
9207
+ // src/worlds/isolatedPython.ts
9208
+ function isolatedPython(python, args, timeout) {
9209
+ return (0, import_node_child_process2.spawnSync)(python, ["-I", ...args], { encoding: "utf8", timeout, env: PersonalToken.scrubbed(process.env) });
9210
+ }
9211
+ var import_node_child_process2;
9212
+ var init_isolatedPython = __esm({
9213
+ "src/worlds/isolatedPython.ts"() {
9214
+ "use strict";
9215
+ import_node_child_process2 = require("child_process");
9216
+ init_personalToken();
9217
+ }
9218
+ });
9219
+
8254
9220
  // src/cli/runtime/local.ts
9221
+ var local_exports = {};
9222
+ __export(local_exports, {
9223
+ MIN_PYTHON_LABEL: () => MIN_PYTHON_LABEL,
9224
+ assertPortFree: () => assertPortFree,
9225
+ credentialsForRuntime: () => credentialsForRuntime,
9226
+ findPython: () => findPython,
9227
+ localBridge: () => localBridge,
9228
+ localModule: () => localModule,
9229
+ localPythonHasYaml: () => localPythonHasYaml,
9230
+ localRuntime: () => localRuntime,
9231
+ localRuntimeReason: () => localRuntimeReason,
9232
+ portOwner: () => portOwner,
9233
+ pythonAdvice: () => pythonAdvice,
9234
+ resetPythonCache: () => resetPythonCache,
9235
+ runtimeMode: () => runtimeMode,
9236
+ runtimeRoot: () => runtimeRoot
9237
+ });
8255
9238
  function forwardedEnv() {
8256
9239
  return Object.fromEntries(
8257
9240
  FORWARDED_ENV.flatMap((name) => {
@@ -8288,12 +9271,12 @@ function runtimeRoot() {
8288
9271
  return root;
8289
9272
  return null;
8290
9273
  }
9274
+ function resetPythonCache() {
9275
+ pythonCache = void 0;
9276
+ pythonProbes = [];
9277
+ }
8291
9278
  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
- );
9279
+ const probe = isolatedPython(name, ["-c", "import sys;print(sys.version_info[0],sys.version_info[1])"], 1e4);
8297
9280
  if (probe.status !== 0) return null;
8298
9281
  const [major, minor] = probe.stdout.trim().split(/\s+/).map(Number);
8299
9282
  return Number.isInteger(major) && Number.isInteger(minor) ? `${major}.${minor}` : null;
@@ -8303,7 +9286,7 @@ function atLeastMinimum(version) {
8303
9286
  return major > MIN_PYTHON[0] || major === MIN_PYTHON[0] && minor >= MIN_PYTHON[1];
8304
9287
  }
8305
9288
  function uvPython() {
8306
- const found = (0, import_node_child_process2.spawnSync)("uv", UV_FIND, { encoding: "utf8", timeout: 1e4 });
9289
+ const found = (0, import_node_child_process3.spawnSync)("uv", UV_FIND, { encoding: "utf8", timeout: 1e4, env: PersonalToken.scrubbed(process.env) });
8307
9290
  if (found.status !== 0) return null;
8308
9291
  const line = found.stdout.trim().split(/\r?\n/)[0] ?? "";
8309
9292
  return line || null;
@@ -8362,12 +9345,12 @@ function localRuntime() {
8362
9345
  return { python, root };
8363
9346
  }
8364
9347
  function localPythonHasYaml(python) {
8365
- return (0, import_node_child_process2.spawnSync)(python, ["-c", "import yaml"], { timeout: 1e4 }).status === 0;
9348
+ return isolatedPython(python, ["-c", "import yaml"], 1e4).status === 0;
8366
9349
  }
8367
9350
  async function localBridge(request, local, opts = {}) {
8368
9351
  const input = JSON.stringify(request);
8369
9352
  return await new Promise((resolve7, reject) => {
8370
- const child = (0, import_node_child_process2.spawn)(
9353
+ const child = (0, import_node_child_process3.spawn)(
8371
9354
  local.python,
8372
9355
  ["-I", "-B", "-c", BRIDGE_BOOTSTRAP, local.root],
8373
9356
  {
@@ -8423,16 +9406,92 @@ async function localBridge(request, local, opts = {}) {
8423
9406
  child.stdin.end(input);
8424
9407
  });
8425
9408
  }
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;
9409
+ function portOwner(port) {
9410
+ const found = (0, import_node_child_process3.spawnSync)("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-Fpc"], {
9411
+ encoding: "utf8",
9412
+ timeout: 5e3
9413
+ });
9414
+ if (found.error || found.status !== 0) return null;
9415
+ let pid = null;
9416
+ let command2 = null;
9417
+ for (const line of found.stdout.split("\n")) {
9418
+ if (line.startsWith("p") && pid === null) pid = line.slice(1);
9419
+ else if (line.startsWith("c") && pid !== null && command2 === null) command2 = line.slice(1);
9420
+ }
9421
+ if (pid === null) return null;
9422
+ return `pid ${pid}${command2 ? ` (${command2})` : ""}`;
9423
+ }
9424
+ async function assertPortFree(port, host = "127.0.0.1") {
9425
+ const taken = await new Promise((resolve7) => {
9426
+ const probe = net.createServer();
9427
+ probe.once("error", () => resolve7(true));
9428
+ probe.listen(port, host, () => probe.close(() => resolve7(false)));
9429
+ });
9430
+ if (!taken) return;
9431
+ const owner = portOwner(port);
9432
+ throw new CliError(
9433
+ `port ${port} on ${host} is already in use${owner ? ` by ${owner}` : ""}; nothing was served there \u2014 pass another --port, or stop that server first`,
9434
+ 1
9435
+ );
9436
+ }
9437
+ async function localModule(argv, local, opts = {}) {
9438
+ return await new Promise((resolve7, reject) => {
9439
+ const child = (0, import_node_child_process3.spawn)(
9440
+ local.python,
9441
+ ["-B", "-c", MODULE_BOOTSTRAP, local.root, ...argv],
9442
+ {
9443
+ stdio: "inherit",
9444
+ cwd: opts.cwd,
9445
+ env: { ...PersonalToken.scrubbed(process.env), ...opts.env }
9446
+ }
9447
+ );
9448
+ const forward = (signal) => () => {
9449
+ if (child.exitCode === null && child.signalCode === null) child.kill(signal);
9450
+ };
9451
+ const handlers = [
9452
+ ["SIGINT", forward("SIGINT")],
9453
+ ["SIGTERM", forward("SIGTERM")],
9454
+ ["SIGHUP", forward("SIGHUP")]
9455
+ ];
9456
+ for (const [signal, handler] of handlers) process.on(signal, handler);
9457
+ const release = () => {
9458
+ for (const [signal, handler] of handlers) process.off(signal, handler);
9459
+ };
9460
+ child.on("error", (error) => {
9461
+ release();
9462
+ reject(
9463
+ new CliError(
9464
+ `local runtime could not start (${local.python}): ${error.message}`,
9465
+ 1
9466
+ )
9467
+ );
9468
+ });
9469
+ child.on("close", (code, signal) => {
9470
+ release();
9471
+ resolve7(code ?? (signal ? 130 : 1));
9472
+ });
9473
+ });
9474
+ }
9475
+ function credentialsForRuntime(hostFlag) {
9476
+ try {
9477
+ return resolveCredentials(hostFlag);
9478
+ } catch (error) {
9479
+ if (error instanceof CliError && localRuntime()) return null;
9480
+ throw error;
9481
+ }
9482
+ }
9483
+ 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
9484
  var init_local = __esm({
8428
9485
  "src/cli/runtime/local.ts"() {
8429
9486
  "use strict";
8430
- import_node_child_process2 = require("child_process");
9487
+ import_node_child_process3 = require("child_process");
8431
9488
  fs7 = __toESM(require("fs"));
8432
9489
  net = __toESM(require("net"));
8433
9490
  path8 = __toESM(require("path"));
8434
9491
  init_router();
8435
9492
  init_config();
9493
+ init_isolatedPython();
9494
+ init_personalToken();
8436
9495
  MIN_PYTHON = [3, 12];
8437
9496
  MIN_PYTHON_LABEL = MIN_PYTHON.join(".");
8438
9497
  DIAGNOSTIC_TAIL = 600;
@@ -8443,6 +9502,13 @@ package=types.ModuleType('gatewaysdk')
8443
9502
  package.__path__=[os.path.join(root,'gatewaysdk')]
8444
9503
  sys.modules['gatewaysdk']=package
8445
9504
  runpy.run_module('gatewaysdk.environment.schema.platform',run_name='__main__')`;
9505
+ MODULE_BOOTSTRAP = `import sys,runpy,types,os
9506
+ root=sys.argv[1]
9507
+ package=types.ModuleType('gatewaysdk')
9508
+ package.__path__=[os.path.join(root,'gatewaysdk')]
9509
+ sys.modules['gatewaysdk']=package
9510
+ sys.argv=['gateway worlds']+sys.argv[2:]
9511
+ runpy.run_module('gatewaysdk.environment.schema',run_name='__main__')`;
8446
9512
  pythonProbes = [];
8447
9513
  PYTHON_CANDIDATES = [
8448
9514
  "python3.13",
@@ -8455,8 +9521,8 @@ runpy.run_module('gatewaysdk.environment.schema.platform',run_name='__main__')`;
8455
9521
  });
8456
9522
 
8457
9523
  // src/worlds/databaseEngines.ts
8458
- function isWorldSnapshotOutput(path13) {
8459
- return SNAPSHOT_OUTPUTS.has(path13.slice(path13.lastIndexOf("/") + 1));
9524
+ function isWorldSnapshotOutput(path14) {
9525
+ return SNAPSHOT_OUTPUTS.has(path14.slice(path14.lastIndexOf("/") + 1));
8460
9526
  }
8461
9527
  var WORLD_DATABASE_ENGINES, DEFAULT_WORLD_DATABASE_ENGINE, WORLD_SNAPSHOT_FILE_PATH, WORLD_SNAPSHOT_SIDECAR_PATH, WORLD_SNAPSHOT_CONTENT_TYPE, SNAPSHOT_OUTPUTS;
8462
9528
  var init_databaseEngines = __esm({
@@ -8938,7 +10004,7 @@ async function runTransform(script, records, opts = {}) {
8938
10004
  const { file, args } = command(resolved, scratch);
8939
10005
  const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !SCRUBBED.test(key)));
8940
10006
  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"] });
10007
+ const child = (0, import_node_child_process4.spawn)(file, args, { cwd: path11.dirname(resolved), env, stdio: ["pipe", "pipe", "pipe"] });
8942
10008
  let stdout = "";
8943
10009
  let stderr = "";
8944
10010
  let timedOut = false;
@@ -8976,11 +10042,11 @@ async function transformRecords(transform, records, opts = {}) {
8976
10042
  if (typeof transform === "function") return { rows: checkRows(await transform(records), "transform(records)"), stderr: "" };
8977
10043
  return runTransform(transform, records, opts);
8978
10044
  }
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;
10045
+ 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
10046
  var init_transform = __esm({
8981
10047
  "src/cli/platform/worldData/transform.ts"() {
8982
10048
  "use strict";
8983
- import_node_child_process3 = require("child_process");
10049
+ import_node_child_process4 = require("child_process");
8984
10050
  fs10 = __toESM(require("fs"));
8985
10051
  os2 = __toESM(require("os"));
8986
10052
  path11 = __toESM(require("path"));
@@ -9066,6 +10132,80 @@ if (fn) {
9066
10132
  }
9067
10133
  });
9068
10134
 
10135
+ // src/cli/platform/worldData/manifest.ts
10136
+ function recordChunk(manifest, chunk) {
10137
+ manifest.chunks = [...manifest.chunks.filter((c) => c.ordinal !== chunk.ordinal), chunk].sort((a, b) => a.ordinal - b.ordinal);
10138
+ }
10139
+ function uploadedEntry(manifest, ordinal, digest) {
10140
+ return manifest.chunks.find((c) => c.ordinal === ordinal && c.digest === digest && c.uploaded) ?? null;
10141
+ }
10142
+ var fs11, path12, STEM, MANIFEST_DIR, stamp, sameInputs, ManifestShelf, IMPORT_MANIFESTS;
10143
+ var init_manifest = __esm({
10144
+ "src/cli/platform/worldData/manifest.ts"() {
10145
+ "use strict";
10146
+ fs11 = __toESM(require("fs"));
10147
+ path12 = __toESM(require("path"));
10148
+ init_router();
10149
+ STEM = /^[A-Za-z0-9_-]+$/;
10150
+ MANIFEST_DIR = path12.join(".gateway", "imports");
10151
+ stamp = () => (/* @__PURE__ */ new Date()).toISOString().replace(/\.\d{3}Z$/, "Z");
10152
+ sameInputs = (a, b) => a.length === b.length && a.every((x, i) => x === b[i]);
10153
+ ManifestShelf = class {
10154
+ constructor(dir, stem) {
10155
+ this.dir = dir;
10156
+ this.stem = stem;
10157
+ }
10158
+ dir;
10159
+ stem;
10160
+ dirIn(cwd = process.cwd()) {
10161
+ return path12.join(cwd, this.dir);
10162
+ }
10163
+ file(stem, cwd) {
10164
+ if (!STEM.test(stem)) throw new CliError(`Not a manifest name: ${stem}`);
10165
+ return path12.join(this.dirIn(cwd), `${stem}.json`);
10166
+ }
10167
+ // .gateway/ ignores itself so a manifest, which names hosts and inputs, never enters a repository.
10168
+ write(manifest, cwd = process.cwd()) {
10169
+ const file = this.file(this.stem(manifest), cwd);
10170
+ fs11.mkdirSync(path12.dirname(file), { recursive: true });
10171
+ const ignore = path12.join(cwd, ".gateway", ".gitignore");
10172
+ if (!fs11.existsSync(ignore)) fs11.writeFileSync(ignore, "*\n");
10173
+ manifest.updatedAt = stamp();
10174
+ const tmp = `${file}.tmp`;
10175
+ fs11.writeFileSync(tmp, JSON.stringify(manifest, null, 1) + "\n");
10176
+ fs11.renameSync(tmp, file);
10177
+ return file;
10178
+ }
10179
+ record(manifest, chunk, cwd = process.cwd()) {
10180
+ recordChunk(manifest, chunk);
10181
+ this.write(manifest, cwd);
10182
+ }
10183
+ read(stem, cwd = process.cwd()) {
10184
+ try {
10185
+ const parsed = JSON.parse(fs11.readFileSync(this.file(stem, cwd), "utf8"));
10186
+ return parsed && parsed.version === 1 && this.stem(parsed) === stem ? parsed : null;
10187
+ } catch {
10188
+ return null;
10189
+ }
10190
+ }
10191
+ list(cwd = process.cwd()) {
10192
+ const dir = this.dirIn(cwd);
10193
+ if (!fs11.existsSync(dir)) return [];
10194
+ const out = [];
10195
+ for (const name of fs11.readdirSync(dir)) {
10196
+ const manifest = name.endsWith(".json") ? this.read(name.slice(0, -5), cwd) : null;
10197
+ if (manifest) out.push(manifest);
10198
+ }
10199
+ return out.sort((a, b) => Number(a.updatedAt < b.updatedAt) - Number(a.updatedAt > b.updatedAt));
10200
+ }
10201
+ resumable(slug, inputs, cwd = process.cwd()) {
10202
+ return this.list(cwd).find((m) => !m.completed && m.slug === slug && sameInputs(m.inputs, inputs)) ?? null;
10203
+ }
10204
+ };
10205
+ IMPORT_MANIFESTS = new ManifestShelf(MANIFEST_DIR, (key) => key.batchId);
10206
+ }
10207
+ });
10208
+
9069
10209
  // src/cli/platform/worldData/batches.ts
9070
10210
  function isSettled(status) {
9071
10211
  if (!TERMINAL_STATES.has(status.state)) return false;
@@ -9128,14 +10268,16 @@ function phaseLine(status) {
9128
10268
  const phase = status.progress?.phase;
9129
10269
  return phase ? `${status.state} (${phase})` : status.state;
9130
10270
  }
9131
- var import_node_crypto10, fs11, TERMINAL_STATES, sleepMs, WorldDataApi;
10271
+ var import_node_crypto10, fs12, CHUNK_PARALLEL, TERMINAL_STATES, sleepMs, WorldDataApi, ChunkUploader;
9132
10272
  var init_batches = __esm({
9133
10273
  "src/cli/platform/worldData/batches.ts"() {
9134
10274
  "use strict";
9135
10275
  import_node_crypto10 = require("crypto");
9136
- fs11 = __toESM(require("fs"));
10276
+ fs12 = __toESM(require("fs"));
9137
10277
  init_config();
9138
10278
  init_router();
10279
+ init_manifest();
10280
+ CHUNK_PARALLEL = 4;
9139
10281
  TERMINAL_STATES = /* @__PURE__ */ new Set([
9140
10282
  "applied",
9141
10283
  "refused",
@@ -9162,13 +10304,7 @@ var init_batches = __esm({
9162
10304
  this.creds,
9163
10305
  "POST",
9164
10306
  `${this.base}/batches/${batchId}/chunks`,
9165
- {
9166
- ordinal: chunk.ordinal,
9167
- digest: chunk.digest,
9168
- bytes: chunk.bytes,
9169
- rows: chunk.rows,
9170
- ...chunk.entity ? { entity: chunk.entity } : {}
9171
- }
10307
+ chunk
9172
10308
  );
9173
10309
  }
9174
10310
  async stageDrive(batchId, chunk) {
@@ -9224,6 +10360,23 @@ var init_batches = __esm({
9224
10360
  message ? { message } : {}
9225
10361
  );
9226
10362
  }
10363
+ chunks(batchId) {
10364
+ return new ChunkUploader(
10365
+ {
10366
+ register: (chunk) => this.register(batchId, chunk),
10367
+ uploaded: (chunkId) => this.markUploaded(batchId, chunkId)
10368
+ },
10369
+ this.sleep
10370
+ );
10371
+ }
10372
+ };
10373
+ ChunkUploader = class {
10374
+ constructor(door, sleep4 = sleepMs) {
10375
+ this.door = door;
10376
+ this.sleep = sleep4;
10377
+ }
10378
+ door;
10379
+ sleep;
9227
10380
  async put(uploadUrl, gz, signed) {
9228
10381
  const headers = signed ?? uploadHeadersFor(gz);
9229
10382
  const delays = [500, 1500, 4e3];
@@ -9250,17 +10403,15 @@ var init_batches = __esm({
9250
10403
  await this.sleep(delays[attempt]);
9251
10404
  }
9252
10405
  }
9253
- async upload(batchId, chunk) {
9254
- const registered = await this.register(batchId, chunk);
9255
- if (!registered.uploaded) {
9256
- if (!registered.uploadUrl)
9257
- throw new CliError(
9258
- `the server registered chunk ${chunk.ordinal} without an upload URL`,
9259
- 1
9260
- );
9261
- await this.put(registered.uploadUrl, chunk.gz, registered.uploadHeaders);
9262
- await this.markUploaded(batchId, registered.chunkId);
9263
- }
10406
+ async upload(chunk) {
10407
+ const registered = await this.door.register({
10408
+ ordinal: chunk.ordinal,
10409
+ digest: chunk.digest,
10410
+ bytes: chunk.bytes,
10411
+ rows: chunk.rows,
10412
+ ...chunk.entity ? { entity: chunk.entity } : {}
10413
+ });
10414
+ if (!registered.uploaded) await this.send(chunk, registered);
9264
10415
  return {
9265
10416
  ordinal: chunk.ordinal,
9266
10417
  digest: chunk.digest,
@@ -9271,6 +10422,28 @@ var init_batches = __esm({
9271
10422
  uploaded: true
9272
10423
  };
9273
10424
  }
10425
+ async send(chunk, registered) {
10426
+ if (!registered.uploadUrl)
10427
+ throw new CliError(
10428
+ `the server registered chunk ${chunk.ordinal} without an upload URL`,
10429
+ 1
10430
+ );
10431
+ await this.put(registered.uploadUrl, chunk.gz, registered.uploadHeaders);
10432
+ await this.door.uploaded(registered.chunkId);
10433
+ }
10434
+ async uploadAll(chunks, kept, parallel, progress) {
10435
+ await forEachLimited(chunks, parallel, async (chunk) => {
10436
+ if (uploadedEntry(kept.manifest, chunk.ordinal, chunk.digest)) {
10437
+ progress(`chunk ${chunk.ordinal}: already uploaded (${chunk.rows} rows)`);
10438
+ return;
10439
+ }
10440
+ const entry = await this.upload(chunk);
10441
+ kept.shelf.record(kept.manifest, entry);
10442
+ progress(
10443
+ `chunk ${chunk.ordinal}: uploaded ${chunk.rows} rows, ${chunk.bytes} bytes (${entry.chunkId})`
10444
+ );
10445
+ });
10446
+ }
9274
10447
  };
9275
10448
  }
9276
10449
  });
@@ -9406,11 +10579,12 @@ async function pushRows(creds, slug, rows, opts = {}) {
9406
10579
  chunkRows: null,
9407
10580
  entity: null
9408
10581
  });
10582
+ const uploader = client.chunks(opened.batchId);
9409
10583
  await forEachLimited(
9410
10584
  chunks,
9411
- Math.max(1, opts.parallel ?? 4),
10585
+ Math.max(1, opts.parallel ?? CHUNK_PARALLEL),
9412
10586
  async (chunk) => {
9413
- await client.upload(opened.batchId, chunk);
10587
+ await uploader.upload(chunk);
9414
10588
  }
9415
10589
  );
9416
10590
  await client.complete(opened.batchId);
@@ -9448,7 +10622,7 @@ function parseToolCallRecord(raw) {
9448
10622
  }
9449
10623
  function readToolCallRecords(paths) {
9450
10624
  const records = [];
9451
- for (const file of paths) records.push(...toolCallRecordsIn(fs12.readFileSync(file, "utf8"), file));
10625
+ for (const file of paths) records.push(...toolCallRecordsIn(fs13.readFileSync(file, "utf8"), file));
9452
10626
  return records;
9453
10627
  }
9454
10628
  function toolCallRecordsIn(text2, where) {
@@ -9484,7 +10658,7 @@ async function emit(sink, record) {
9484
10658
  return;
9485
10659
  }
9486
10660
  if (typeof sink === "string") {
9487
- fs12.appendFileSync(sink, JSON.stringify(record) + "\n");
10661
+ fs13.appendFileSync(sink, JSON.stringify(record) + "\n");
9488
10662
  return;
9489
10663
  }
9490
10664
  if (typeof sink === "function") {
@@ -9551,14 +10725,23 @@ function toolCallsFromObservations(observations, opts = {}) {
9551
10725
  }
9552
10726
  return out;
9553
10727
  }
10728
+ async function runtimeEndpoint(options) {
10729
+ try {
10730
+ return platformEndpoint(options);
10731
+ } catch (error) {
10732
+ const { localRuntime: localRuntime2 } = await Promise.resolve().then(() => (init_local(), local_exports));
10733
+ if (error instanceof PersonalTokenRefused && localRuntime2()) return null;
10734
+ throw error;
10735
+ }
10736
+ }
9554
10737
  async function ingest(world, records, options = {}) {
9555
10738
  const { ingestLocalToolCalls: ingestLocalToolCalls2, importLocalWorldData: importLocalWorldData2, checkLocalWorldData: checkLocalWorldData2 } = await Promise.resolve().then(() => (init_data(), data_exports));
9556
10739
  if (options.transform !== void 0 && options.map !== void 0) throw new Error("records go through one of transform, map");
9557
10740
  const redact = options.redact ?? "off";
9558
10741
  const mode = options.mode ?? "append";
9559
10742
  const dryRun = Boolean(options.dryRun);
9560
- const creds = platformEndpoint(options);
9561
- const local = fs12.existsSync(world) && fs12.statSync(world).isDirectory();
10743
+ const local = fs13.existsSync(world) && fs13.statSync(world).isDirectory();
10744
+ const creds = local ? await runtimeEndpoint(options) : platformEndpoint(options);
9562
10745
  const map = options.map === void 0 ? void 0 : options.map;
9563
10746
  let rows = null;
9564
10747
  let stderr = "";
@@ -9574,9 +10757,9 @@ async function ingest(world, records, options = {}) {
9574
10757
  if (!creds) throw new Error(GATEWAY_KEYS_MISSING);
9575
10758
  const { pull: pull2 } = await Promise.resolve().then(() => (init_hub(), hub_exports));
9576
10759
  const slug = world.split("@", 1)[0];
9577
- const scratch = fs12.mkdtempSync(path12.join(os3.tmpdir(), "gateway-ingest-"));
10760
+ const scratch = fs13.mkdtempSync(path13.join(os3.tmpdir(), "gateway-ingest-"));
9578
10761
  try {
9579
- const pulled = await pull2(world, path12.join(scratch, slug), options);
10762
+ const pulled = await pull2(world, path13.join(scratch, slug), options);
9580
10763
  let report;
9581
10764
  let projected;
9582
10765
  if (rows === null) {
@@ -9597,7 +10780,7 @@ async function ingest(world, records, options = {}) {
9597
10780
  if (status.entityCounts) report.entityCounts = status.entityCounts;
9598
10781
  return report;
9599
10782
  } finally {
9600
- fs12.rmSync(scratch, { recursive: true, force: true });
10783
+ fs13.rmSync(scratch, { recursive: true, force: true });
9601
10784
  }
9602
10785
  }
9603
10786
  async function ingestToolCalls(world, records, options = {}) {
@@ -9650,15 +10833,16 @@ async function sessionToolObservations(sessionId, options = {}) {
9650
10833
  for (const observation of trace3.observations ?? []) out.push({ traceId: trace3.id ?? null, ...observation });
9651
10834
  return out;
9652
10835
  }
9653
- var fs12, os3, path12, isObject2, isoOf;
10836
+ var fs13, os3, path13, isObject2, isoOf;
9654
10837
  var init_ingest = __esm({
9655
10838
  "src/worlds/ingest.ts"() {
9656
10839
  "use strict";
9657
- fs12 = __toESM(require("fs"));
10840
+ fs13 = __toESM(require("fs"));
9658
10841
  os3 = __toESM(require("os"));
9659
- path12 = __toESM(require("path"));
10842
+ path13 = __toESM(require("path"));
9660
10843
  init_worlds();
9661
10844
  init_platformEndpoint();
10845
+ init_personalToken();
9662
10846
  isObject2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
9663
10847
  isoOf = (value) => value instanceof Date ? value.toISOString() : typeof value === "string" ? value : void 0;
9664
10848
  }
@@ -9716,6 +10900,38 @@ var init_editSessions = __esm({
9716
10900
  }
9717
10901
  });
9718
10902
 
10903
+ // src/worlds/states.ts
10904
+ var WORLDS3, refQuery, WorldStateClient;
10905
+ var init_states = __esm({
10906
+ "src/worlds/states.ts"() {
10907
+ "use strict";
10908
+ init_worlds();
10909
+ WORLDS3 = "/api/public/worlds";
10910
+ refQuery = (ref) => ref ? `?${new URLSearchParams({ ref })}` : "";
10911
+ WorldStateClient = class {
10912
+ constructor(options = {}) {
10913
+ this.options = options;
10914
+ }
10915
+ options;
10916
+ list(slug) {
10917
+ return apiRequest(this.options, "GET", `${WORLDS3}/${encodeURIComponent(slug)}/states`);
10918
+ }
10919
+ show(slug, name, ref) {
10920
+ return apiRequest(this.options, "GET", `${WORLDS3}/${encodeURIComponent(slug)}/states/${encodeURIComponent(name)}` + refQuery(ref));
10921
+ }
10922
+ create(slug, input) {
10923
+ return apiRequest(this.options, "POST", `${WORLDS3}/${encodeURIComponent(slug)}/states`, input);
10924
+ }
10925
+ delete(slug, name) {
10926
+ return apiRequest(this.options, "DELETE", `${WORLDS3}/${encodeURIComponent(slug)}/states/${encodeURIComponent(name)}`);
10927
+ }
10928
+ pull(slug, name, ref) {
10929
+ return apiRequest(this.options, "GET", `${WORLDS3}/${encodeURIComponent(slug)}/states/${encodeURIComponent(name)}/pull` + refQuery(ref));
10930
+ }
10931
+ };
10932
+ }
10933
+ });
10934
+
9719
10935
  // src/worlds/dryRun.ts
9720
10936
  var DRY_RUN_KIND, DRY_RUN_AGENT, STATUS_WAIT_CAP_SECONDS, cid, HostedDryRunClient, DryRunOutcome;
9721
10937
  var init_dryRun = __esm({
@@ -9849,9 +11065,14 @@ __export(worlds_exports, {
9849
11065
  OpenAIComputer: () => OpenAIComputer,
9850
11066
  OpenAIPreviewComputer: () => OpenAIPreviewComputer,
9851
11067
  PLATFORM_SESSION_HEADER: () => PLATFORM_SESSION_HEADER,
11068
+ PLATFORM_STREAM_IDLE_MS: () => PLATFORM_STREAM_IDLE_MS,
9852
11069
  PLATFORM_TIMEOUT_DEFAULT_MS: () => PLATFORM_TIMEOUT_DEFAULT_MS,
9853
11070
  PLATFORM_TIMEOUT_ENV: () => PLATFORM_TIMEOUT_ENV,
11071
+ PageObserver: () => PageObserver,
11072
+ PageState: () => PageState,
11073
+ PageStateError: () => PageStateError,
9854
11074
  PendingSafetyChecks: () => PendingSafetyChecks,
11075
+ PlatformStream: () => PlatformStream,
9855
11076
  PlatformTransport: () => PlatformTransport,
9856
11077
  PushSlugConflict: () => PushSlugConflict,
9857
11078
  RECOVER_BUDGET_MS: () => RECOVER_BUDGET_MS,
@@ -9904,6 +11125,7 @@ __export(worlds_exports, {
9904
11125
  WorldSessionOpenFailed: () => WorldSessionOpenFailed,
9905
11126
  WorldSessionTimeout: () => WorldSessionTimeout,
9906
11127
  WorldSet: () => WorldSet,
11128
+ WorldStateClient: () => WorldStateClient,
9907
11129
  WorldSurfaceUnavailable: () => WorldSurfaceUnavailable,
9908
11130
  WorldTask: () => WorldTask,
9909
11131
  WorldToolsUnread: () => WorldToolsUnread,
@@ -9971,6 +11193,7 @@ __export(worlds_exports, {
9971
11193
  parseToolCallRecord: () => parseToolCallRecord,
9972
11194
  parseTransform: () => parseTransform,
9973
11195
  parseWorldTaskRefs: () => parseWorldTaskRefs,
11196
+ platformAuthorization: () => platformAuthorization,
9974
11197
  platformTimeoutMs: () => platformTimeoutMs,
9975
11198
  playwrightKey: () => playwrightKey,
9976
11199
  preserveForm: () => preserveForm,
@@ -9997,6 +11220,7 @@ __export(worlds_exports, {
9997
11220
  runSet: () => runSet,
9998
11221
  runTask: () => runTask,
9999
11222
  schemaFromSignature: () => schemaFromSignature,
11223
+ scrubError: () => scrubError,
10000
11224
  serializeCallBody: () => serializeCallBody,
10001
11225
  sessionToolObservations: () => sessionToolObservations,
10002
11226
  setEnvSecret: () => setEnvSecret,
@@ -10025,43 +11249,8 @@ __export(worlds_exports, {
10025
11249
  writeLocalMeta: () => writeLocalMeta
10026
11250
  });
10027
11251
  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
- 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);
11252
+ async function apiRequest(options, method, path14, body, init2 = {}) {
11253
+ return new PlatformTransport(requirePlatformEndpoint(options)).json(method, path14, body, init2);
10065
11254
  }
10066
11255
  async function setEnvSecret(slug, key, value, options = {}) {
10067
11256
  return apiRequest(
@@ -10236,11 +11425,12 @@ async function resolveWorld(slugRef, slug, ref, pin, options) {
10236
11425
  }
10237
11426
  return world;
10238
11427
  }
10239
- var ApiError, DETAIL_LIMIT, EDGE_ANSWERS, EDGE_FAILURE, EDGE_PAGE, WorldTask, WorldSet;
11428
+ var WorldTask, WorldSet;
10240
11429
  var init_worlds = __esm({
10241
11430
  "src/worlds/index.ts"() {
10242
11431
  init_platformEndpoint();
10243
11432
  init_transport();
11433
+ init_apiError();
10244
11434
  init_transport();
10245
11435
  init_session2();
10246
11436
  init_grade();
@@ -10255,6 +11445,8 @@ var init_worlds = __esm({
10255
11445
  init_checkoutProvenance();
10256
11446
  init_evals();
10257
11447
  init_browser();
11448
+ init_browserTools();
11449
+ init_pageState();
10258
11450
  init_surfaceDescriptor();
10259
11451
  init_requestLog();
10260
11452
  init_requestLedger();
@@ -10271,29 +11463,9 @@ var init_worlds = __esm({
10271
11463
  init_ingest();
10272
11464
  init_sandbox();
10273
11465
  init_editSessions();
11466
+ init_states();
10274
11467
  init_dryRun();
10275
11468
  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
11469
  WorldTask = class {
10298
11470
  constructor(world, name, variant) {
10299
11471
  this.world = world;
@@ -10403,9 +11575,14 @@ init_worlds();
10403
11575
  OpenAIComputer,
10404
11576
  OpenAIPreviewComputer,
10405
11577
  PLATFORM_SESSION_HEADER,
11578
+ PLATFORM_STREAM_IDLE_MS,
10406
11579
  PLATFORM_TIMEOUT_DEFAULT_MS,
10407
11580
  PLATFORM_TIMEOUT_ENV,
11581
+ PageObserver,
11582
+ PageState,
11583
+ PageStateError,
10408
11584
  PendingSafetyChecks,
11585
+ PlatformStream,
10409
11586
  PlatformTransport,
10410
11587
  PushSlugConflict,
10411
11588
  RECOVER_BUDGET_MS,
@@ -10458,6 +11635,7 @@ init_worlds();
10458
11635
  WorldSessionOpenFailed,
10459
11636
  WorldSessionTimeout,
10460
11637
  WorldSet,
11638
+ WorldStateClient,
10461
11639
  WorldSurfaceUnavailable,
10462
11640
  WorldTask,
10463
11641
  WorldToolsUnread,
@@ -10525,6 +11703,7 @@ init_worlds();
10525
11703
  parseToolCallRecord,
10526
11704
  parseTransform,
10527
11705
  parseWorldTaskRefs,
11706
+ platformAuthorization,
10528
11707
  platformTimeoutMs,
10529
11708
  playwrightKey,
10530
11709
  preserveForm,
@@ -10551,6 +11730,7 @@ init_worlds();
10551
11730
  runSet,
10552
11731
  runTask,
10553
11732
  schemaFromSignature,
11733
+ scrubError,
10554
11734
  serializeCallBody,
10555
11735
  sessionToolObservations,
10556
11736
  setEnvSecret,