@withgateway/sdk 0.4.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. package/dist/agents/index.d.mts +573 -0
  2. package/dist/agents/index.d.ts +573 -0
  3. package/dist/agents/index.js +1443 -0
  4. package/dist/agents/index.js.map +1 -0
  5. package/dist/agents/index.mjs +1394 -0
  6. package/dist/agents/index.mjs.map +1 -0
  7. package/dist/apiError-DHpfbmdx.d.mts +17 -0
  8. package/dist/apiError-DHpfbmdx.d.ts +17 -0
  9. package/dist/cli.js +5655 -1890
  10. package/dist/cli.js.map +1 -1
  11. package/dist/cli.mjs +5769 -2005
  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 +418 -120
  16. package/dist/files/index.js.map +1 -1
  17. package/dist/files/index.mjs +418 -120
  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-DUHmS74p.d.ts → index-DIN14Lhg.d.ts} +27 -4
  24. package/dist/{index-mJhG3vZU.d.mts → index-DuB-eQ0Z.d.mts} +27 -4
  25. package/dist/index.d.mts +7 -4
  26. package/dist/index.d.ts +7 -4
  27. package/dist/index.js +2862 -438
  28. package/dist/index.js.map +1 -1
  29. package/dist/index.mjs +2820 -431
  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/replay/index.d.mts +1 -1
  34. package/dist/replay/index.d.ts +1 -1
  35. package/dist/replay/index.js.map +1 -1
  36. package/dist/replay/index.mjs.map +1 -1
  37. package/dist/traces/index.d.mts +3 -1
  38. package/dist/traces/index.d.ts +3 -1
  39. package/dist/traces/index.js +418 -120
  40. package/dist/traces/index.js.map +1 -1
  41. package/dist/traces/index.mjs +418 -120
  42. package/dist/traces/index.mjs.map +1 -1
  43. package/dist/tracing/index.d.mts +3 -2
  44. package/dist/tracing/index.d.ts +3 -2
  45. package/dist/tracing/index.js +257 -16
  46. package/dist/tracing/index.js.map +1 -1
  47. package/dist/tracing/index.mjs +257 -16
  48. package/dist/tracing/index.mjs.map +1 -1
  49. package/dist/transport-CpRe7zgd.d.mts +123 -0
  50. package/dist/transport-CpRe7zgd.d.ts +123 -0
  51. package/dist/worlds/index.d.mts +2086 -1749
  52. package/dist/worlds/index.d.ts +2086 -1749
  53. package/dist/worlds/index.js +1471 -269
  54. package/dist/worlds/index.js.map +1 -1
  55. package/dist/worlds/index.mjs +1466 -265
  56. package/dist/worlds/index.mjs.map +1 -1
  57. package/package.json +6 -1
  58. package/runtime/gatewaysdk/environment/_bundle.py +4 -6
  59. package/runtime/gatewaysdk/environment/_world.py +24 -1
  60. package/runtime/gatewaysdk/environment/bundle_manifest.py +243 -0
  61. package/runtime/gatewaysdk/environment/runtime.py +45 -2
  62. package/runtime/gatewaysdk/environment/schema/__main__.py +2 -2
  63. package/runtime/gatewaysdk/environment/schema/_slack_fidelity.py +8 -23
  64. package/runtime/gatewaysdk/environment/schema/api.py +27 -7
  65. package/runtime/gatewaysdk/environment/schema/assertions.py +7 -1
  66. package/runtime/gatewaysdk/environment/schema/bundle_runtime.py +2 -0
  67. package/runtime/gatewaysdk/environment/schema/call_capture.py +13 -1
  68. package/runtime/gatewaysdk/environment/schema/call_log.py +66 -0
  69. package/runtime/gatewaysdk/environment/schema/call_redaction.py +6 -0
  70. package/runtime/gatewaysdk/environment/schema/compiler.py +4 -1
  71. package/runtime/gatewaysdk/environment/schema/conform.py +32 -8
  72. package/runtime/gatewaysdk/environment/schema/connector.py +5 -0
  73. package/runtime/gatewaysdk/environment/schema/connectors/custom/handlers.py +2 -1
  74. package/runtime/gatewaysdk/environment/schema/connectors/github/api/handlers.py +217 -58
  75. package/runtime/gatewaysdk/environment/schema/connectors/github/connector.toml +9 -19
  76. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_webhooks.json +10 -2
  77. package/runtime/gatewaysdk/environment/schema/connectors/github/tests/webhooks.json +47 -0
  78. package/runtime/gatewaysdk/environment/schema/connectors/github/world.json +21 -0
  79. package/runtime/gatewaysdk/environment/schema/connectors/jamf/api/handlers.py +185 -18
  80. package/runtime/gatewaysdk/environment/schema/connectors/jamf/connector.toml +29 -14
  81. package/runtime/gatewaysdk/environment/schema/connectors/jamf/provenance.json +43 -12
  82. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_webhooks.json +2 -2
  83. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scope.toml +4 -17
  84. package/runtime/gatewaysdk/environment/schema/connectors/jamf/tests/webhooks.json +107 -0
  85. package/runtime/gatewaysdk/environment/schema/connectors/jamf/vendor-openapi.json +1 -1
  86. package/runtime/gatewaysdk/environment/schema/connectors/linear/api/handlers.py +85 -1
  87. package/runtime/gatewaysdk/environment/schema/connectors/linear/connector.toml +19 -31
  88. package/runtime/gatewaysdk/environment/schema/connectors/linear/provenance.json +18 -8
  89. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/webhooks.json +19 -3
  90. package/runtime/gatewaysdk/environment/schema/connectors/linear/tests/test_webhooks.py +71 -0
  91. package/runtime/gatewaysdk/environment/schema/database/base.py +2 -2
  92. package/runtime/gatewaysdk/environment/schema/database/guard.py +2 -1
  93. package/runtime/gatewaysdk/environment/schema/handler_errors.py +27 -1
  94. package/runtime/gatewaysdk/environment/schema/host.py +74 -11
  95. package/runtime/gatewaysdk/environment/schema/host_browser.py +48 -0
  96. package/runtime/gatewaysdk/environment/schema/host_control.py +33 -2
  97. package/runtime/gatewaysdk/environment/schema/host_handoff.py +4 -1
  98. package/runtime/gatewaysdk/environment/schema/host_requests.py +14 -0
  99. package/runtime/gatewaysdk/environment/schema/host_session.py +13 -2
  100. package/runtime/gatewaysdk/environment/schema/host_surfaces.py +6 -0
  101. package/runtime/gatewaysdk/environment/schema/host_versions.py +96 -19
  102. package/runtime/gatewaysdk/environment/schema/journal.py +10 -4
  103. package/runtime/gatewaysdk/environment/schema/local.py +33 -7
  104. package/runtime/gatewaysdk/environment/schema/openapi_schemas.py +20 -5
  105. package/runtime/gatewaysdk/environment/schema/page_checks.py +123 -0
  106. package/runtime/gatewaysdk/environment/schema/platform.py +33 -480
  107. package/runtime/gatewaysdk/environment/schema/platform_templates.py +332 -0
  108. package/runtime/gatewaysdk/environment/schema/request_ledger.py +4 -1
  109. package/runtime/gatewaysdk/environment/schema/run_parameters.py +25 -0
  110. package/runtime/gatewaysdk/environment/schema/runtime.py +49 -4
  111. package/runtime/gatewaysdk/environment/schema/scaffold.py +369 -218
  112. package/runtime/gatewaysdk/environment/schema/session_files.py +13 -2
  113. package/runtime/gatewaysdk/environment/schema/skills/benchmarks-getting-started/SKILL.md +1 -1
  114. package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/CONNECTORS.md +3 -3
  115. package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/SKILL.md +20 -24
  116. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/SKILL.md +11 -11
  117. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/SKILL.md +9 -9
  118. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/cli-mcp-map.md +45 -12
  119. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/gotchas.md +40 -9
  120. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/journal-checks.md +17 -2
  121. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/new-world-sandbox.md +1 -1
  122. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/ui-map.md +3 -2
  123. package/runtime/gatewaysdk/environment/schema/slack.py +55 -10
  124. package/runtime/gatewaysdk/environment/schema/snapshot.py +30 -4
  125. package/runtime/gatewaysdk/environment/schema/tasks.py +25 -2
  126. package/runtime/gatewaysdk/environment/schema/template_record.py +131 -0
  127. package/runtime/gatewaysdk/environment/schema/tools_world.py +26 -5
  128. package/runtime/gatewaysdk/environment/schema/ui.py +54 -33
  129. package/runtime/gatewaysdk/environment/schema/ui_interactions.py +419 -0
  130. package/runtime/gatewaysdk/environment/schema/ui_recorder.js +895 -0
  131. package/runtime/gatewaysdk/environment/schema/ui_replay.py +366 -0
  132. package/runtime/gatewaysdk/environment/schema/ui_replay_record.LICENSE +25 -0
  133. package/runtime/gatewaysdk/environment/schema/ui_replay_record.js +109 -0
  134. package/runtime/gatewaysdk/environment/schema/validation.py +10 -1
  135. package/runtime/gatewaysdk/environment/schema/verbs.py +6 -0
  136. package/runtime/gatewaysdk/environment/schema/webhooks.py +687 -0
  137. package/runtime/gatewaysdk/environment/schema/worker.py +5 -1
  138. package/runtime/gatewaysdk/environment/schema/workers.py +8 -1
  139. package/runtime/gatewaysdk/environment/schema/world_host.py +64 -18
  140. package/runtime/gatewaysdk/environment/schema/world_tests.py +74 -0
  141. package/runtime/gatewaysdk/environment/secret_values.py +1 -1
  142. package/runtime/gatewaysdk/environment/world.py +34 -43
  143. package/runtime/gatewaysdk/environment/world_session_contract.py +7 -34
  144. package/skills/benchmarks-getting-started/SKILL.md +1 -1
  145. package/skills/connector-schema-authoring/CONNECTORS.md +3 -3
  146. package/skills/connector-schema-authoring/SKILL.md +20 -24
  147. package/skills/connector-schema-authoring/connector-worlds.md +155 -13
  148. package/skills/connector-schema-authoring/world-schema.md +36 -29
  149. package/skills/world-data-ingestion/SKILL.md +11 -11
  150. package/skills/worlds-getting-started/SKILL.md +9 -9
  151. package/skills/worlds-getting-started/references/cli-mcp-map.md +45 -12
  152. package/skills/worlds-getting-started/references/gotchas.md +40 -9
  153. package/skills/worlds-getting-started/references/journal-checks.md +17 -2
  154. package/skills/worlds-getting-started/references/new-world-sandbox.md +1 -1
  155. package/skills/worlds-getting-started/references/ui-map.md +3 -2
  156. package/dist/media-BIApiPzS.d.mts +0 -102
  157. package/dist/media-BIApiPzS.d.ts +0 -102
@@ -28,13 +28,77 @@ var __export = (target, all) => {
28
28
  __defProp(target, name, { get: all[name], enumerable: true });
29
29
  };
30
30
 
31
+ // src/worlds/personalToken.ts
32
+ var TOKEN_NOT_PERSONAL, TOKEN_NEEDS_PROJECT, TOKEN_NEEDS_HOST, TOKEN_OTHER_HOST, TOKEN_BESIDE_KEYS, TOKEN_FILING, TOKEN_KEYS_ONLY, PERSONAL, PROJECT, ENV_KEYS, PersonalTokenRefused, bare, PersonalToken;
33
+ var init_personalToken = __esm({
34
+ "src/worlds/personalToken.ts"() {
35
+ "use strict";
36
+ TOKEN_NOT_PERSONAL = "GATEWAY_TOKEN takes a personal access token: pat_ followed by letters and digits only.";
37
+ TOKEN_NEEDS_PROJECT = "GATEWAY_TOKEN acts in the project GATEWAY_PROJECT_ID names: set it to the official project's id (letters, digits, - and _).";
38
+ TOKEN_NEEDS_HOST = "GATEWAY_TOKEN goes only to the host GATEWAY_HOST names: set GATEWAY_HOST.";
39
+ TOKEN_OTHER_HOST = "GATEWAY_TOKEN goes only to the host GATEWAY_HOST names, and this call names another host: point the call at GATEWAY_HOST or unset GATEWAY_TOKEN.";
40
+ TOKEN_BESIDE_KEYS = "GATEWAY_TOKEN is set beside a project key (GATEWAY_PUBLIC_KEY, GATEWAY_SECRET_KEY, GATEWAY_API_KEY or a key passed in): unset one of them. Neither replaces the other.";
41
+ TOKEN_FILING = "Filing an evaluation takes your project's key pair, not GATEWAY_TOKEN: unset it (an official world runs once copied into your own project).";
42
+ TOKEN_KEYS_ONLY = "Task-run tracing exports with a project key pair (GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY), not GATEWAY_TOKEN.";
43
+ PERSONAL = /^pat_[A-Za-z0-9]+$/;
44
+ PROJECT = /^[A-Za-z0-9_-]+$/;
45
+ ENV_KEYS = ["GATEWAY_PUBLIC_KEY", "GATEWAY_SECRET_KEY", "GATEWAY_API_KEY"];
46
+ PersonalTokenRefused = class extends Error {
47
+ };
48
+ bare = (host) => host.replace(/\/+$/, "");
49
+ PersonalToken = class _PersonalToken {
50
+ constructor(value, project, host) {
51
+ this.value = value;
52
+ this.project = project;
53
+ this.host = host;
54
+ }
55
+ value;
56
+ project;
57
+ host;
58
+ static fromEnv(env, request = {}) {
59
+ const value = env.GATEWAY_TOKEN;
60
+ if (!value) return null;
61
+ if (request.keys || ENV_KEYS.some((name) => env[name])) throw new PersonalTokenRefused(TOKEN_BESIDE_KEYS);
62
+ const host = bare(env.GATEWAY_HOST ?? "");
63
+ if (!host) throw new PersonalTokenRefused(TOKEN_NEEDS_HOST);
64
+ if (request.host && bare(request.host) !== host) throw new PersonalTokenRefused(TOKEN_OTHER_HOST);
65
+ if (!PERSONAL.test(value)) throw new PersonalTokenRefused(TOKEN_NOT_PERSONAL);
66
+ const project = env.GATEWAY_PROJECT_ID ?? "";
67
+ if (!PROJECT.test(project)) throw new PersonalTokenRefused(TOKEN_NEEDS_PROJECT);
68
+ return new _PersonalToken(value, project, host);
69
+ }
70
+ toJSON() {
71
+ return { project: this.project, host: this.host };
72
+ }
73
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
74
+ return `PersonalToken { project: ${this.project}, host: ${this.host} }`;
75
+ }
76
+ static scrubbed(env) {
77
+ return Object.fromEntries(Object.entries(env).filter(([key]) => key !== "GATEWAY_TOKEN"));
78
+ }
79
+ };
80
+ }
81
+ });
82
+
31
83
  // src/worlds/platformEndpoint.ts
32
84
  function platformEndpoint(options) {
85
+ if (options.token)
86
+ return {
87
+ host: (options.host ?? options.token.host).replace(/\/+$/, ""),
88
+ publicKey: options.publicKey ?? "",
89
+ secretKey: options.secretKey ?? "",
90
+ token: options.token
91
+ };
92
+ const token = PersonalToken.fromEnv(process.env, {
93
+ host: options.host,
94
+ keys: Boolean(options.publicKey || options.secretKey)
95
+ });
96
+ if (token) return { host: token.host, publicKey: "", secretKey: "", token };
97
+ const host = (options.host ?? process.env.GATEWAY_HOST ?? DEFAULT_HOST).replace(/\/+$/, "");
33
98
  const publicKey = options.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;
34
99
  const secretKey = options.secretKey ?? process.env.GATEWAY_SECRET_KEY;
35
100
  if (!publicKey || !secretKey) return null;
36
- const host = options.host ?? process.env.GATEWAY_HOST ?? DEFAULT_HOST;
37
- return { host: host.replace(/\/+$/, ""), publicKey, secretKey };
101
+ return { host, publicKey, secretKey };
38
102
  }
39
103
  function requirePlatformEndpoint(options) {
40
104
  const endpoint = platformEndpoint(options);
@@ -45,11 +109,74 @@ var DEFAULT_HOST, GATEWAY_KEYS_MISSING;
45
109
  var init_platformEndpoint = __esm({
46
110
  "src/worlds/platformEndpoint.ts"() {
47
111
  "use strict";
112
+ init_personalToken();
48
113
  DEFAULT_HOST = "https://withgateway.ai";
49
114
  GATEWAY_KEYS_MISSING = "Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY (or pass publicKey/secretKey).";
50
115
  }
51
116
  });
52
117
 
118
+ // src/worlds/apiError.ts
119
+ function edgeAnswer(text2, status) {
120
+ if (status !== void 0 && status >= 500) return EDGE_ANSWERS[status] ?? EDGE_FAILURE;
121
+ return /^\s*</.test(text2) ? EDGE_PAGE : null;
122
+ }
123
+ function parseErrorBody(text2, status) {
124
+ const raw = { detail: text2.slice(0, DETAIL_LIMIT), code: null };
125
+ let parsed;
126
+ try {
127
+ parsed = JSON.parse(text2);
128
+ } catch {
129
+ return { detail: (edgeAnswer(text2, status) ?? text2).slice(0, DETAIL_LIMIT), code: null };
130
+ }
131
+ if (parsed === null || typeof parsed !== "object") return raw;
132
+ const { message, code, error } = parsed;
133
+ const stableCode = typeof code === "string" ? code : null;
134
+ if (typeof message !== "string") return { ...raw, code: stableCode };
135
+ const fields = invalidFields(error);
136
+ const said = fields ? `${message}: ${fields}` : message;
137
+ if (stableCode === null) return { detail: said.slice(0, DETAIL_LIMIT), code: null };
138
+ return {
139
+ detail: `${said} (${stableCode})`.slice(0, DETAIL_LIMIT),
140
+ code: stableCode
141
+ };
142
+ }
143
+ function invalidFields(error) {
144
+ const issues = Array.isArray(error) ? error : [];
145
+ return issues.filter(
146
+ (issue) => issue !== null && typeof issue === "object" && typeof issue.message === "string"
147
+ ).map((issue) => {
148
+ const path13 = Array.isArray(issue.path) ? issue.path.map(String).join(".") : "";
149
+ return path13 ? `${path13}: ${issue.message}` : issue.message;
150
+ }).join("; ");
151
+ }
152
+ var ApiError, DETAIL_LIMIT, EDGE_ANSWERS, EDGE_FAILURE, EDGE_PAGE;
153
+ var init_apiError = __esm({
154
+ "src/worlds/apiError.ts"() {
155
+ "use strict";
156
+ ApiError = class extends Error {
157
+ constructor(status, method, path13, text2) {
158
+ const parsed = parseErrorBody(text2, status);
159
+ super(`${method} ${path13} -> ${status}: ${parsed.detail}`);
160
+ this.status = status;
161
+ this.text = text2;
162
+ this.name = "ApiError";
163
+ this.code = parsed.code;
164
+ }
165
+ status;
166
+ text;
167
+ code;
168
+ };
169
+ DETAIL_LIMIT = 600;
170
+ EDGE_ANSWERS = {
171
+ 502: "Bad Gateway from the load balancer in front of the platform, not the platform's answer: the web server dropped the connection or restarted mid-request. Retry; if it repeats, the platform is restarting or overloaded.",
172
+ 503: "Service Unavailable from the load balancer in front of the platform, not the platform's answer: no web server was ready to take the request (a deploy or a restart). Retry in a minute.",
173
+ 504: "Gateway Time-out from the load balancer in front of the platform, not the platform's answer: the request sent nothing back within the load balancer's idle timeout (60 s unless the deployment raises it: Helm ingress.idleTimeoutSeconds) and was cut there, though the platform may still be running it. Check what it changed before you retry."
174
+ };
175
+ EDGE_FAILURE = "The platform failed without its JSON error body: a proxy in front of it answered, or the server stopped before its error handler ran. Retry; if it repeats, report the request and the time.";
176
+ EDGE_PAGE = "An HTML page answered instead of the platform's JSON: a proxy in front of the platform, or the configured host is not the platform.";
177
+ }
178
+ });
179
+
53
180
  // src/worlds/transport.ts
54
181
  function platformTimeoutMs(env = process.env) {
55
182
  const raw = env[PLATFORM_TIMEOUT_ENV];
@@ -58,10 +185,20 @@ function platformTimeoutMs(env = process.env) {
58
185
  if (Number.isInteger(value) && value > 0) return value;
59
186
  throw new Error(`${PLATFORM_TIMEOUT_ENV} must be a positive whole number of milliseconds, not \`${raw}\`.`);
60
187
  }
61
- var PLATFORM_TIMEOUT_ENV, PLATFORM_TIMEOUT_DEFAULT_MS, CHECK_HOST, RETRY, FETCH_LIMIT, CAUSES, UNKNOWN_CAUSE, TransportCause, UnreachableError, sleep, RetryPolicy, Attempt, PlatformTransport;
188
+ function platformAuthorization(endpoint, url) {
189
+ const { token } = endpoint;
190
+ if (!token)
191
+ return { authorization: "Basic " + Buffer.from(`${endpoint.publicKey}:${endpoint.secretKey}`).toString("base64") };
192
+ if (endpoint.publicKey || endpoint.secretKey) throw new PersonalTokenRefused(TOKEN_BESIDE_KEYS);
193
+ if (!url.startsWith(`${token.host}/`)) throw new PersonalTokenRefused(TOKEN_OTHER_HOST);
194
+ return { authorization: `Bearer ${token.value}`, "x-gateway-project": token.project };
195
+ }
196
+ var PLATFORM_TIMEOUT_ENV, PLATFORM_TIMEOUT_DEFAULT_MS, CHECK_HOST, RETRY, FETCH_LIMIT, CAUSES, UNKNOWN_CAUSE, TransportCause, UnreachableError, sleep, RetryPolicy, Attempt, PLATFORM_STREAM_IDLE_MS, REFUSAL_TEXT_LIMIT, KEYED_REDIRECTS, PlatformTransport, StreamWatch, PlatformStream;
62
197
  var init_transport = __esm({
63
198
  "src/worlds/transport.ts"() {
64
199
  "use strict";
200
+ init_apiError();
201
+ init_personalToken();
65
202
  PLATFORM_TIMEOUT_ENV = "GATEWAY_TIMEOUT_MS";
66
203
  PLATFORM_TIMEOUT_DEFAULT_MS = 12e4;
67
204
  CHECK_HOST = "Check GATEWAY_HOST (or --host) points at a running platform, then retry.";
@@ -101,6 +238,13 @@ var init_transport = __esm({
101
238
  `Retry; if the platform is slow, raise ${PLATFORM_TIMEOUT_ENV} (milliseconds per request).`
102
239
  );
103
240
  }
241
+ static idle(idleMs) {
242
+ return new _TransportCause(
243
+ `no data for ${idleMs / 1e3}s`,
244
+ null,
245
+ "The stream resumes from its last event; if it repeats, check the network between here and the platform."
246
+ );
247
+ }
104
248
  static of(error) {
105
249
  const cause = error instanceof Error && error.cause instanceof Error ? error.cause : void 0;
106
250
  const code = cause && "code" in cause && typeof cause.code === "string" ? cause.code : null;
@@ -113,11 +257,11 @@ var init_transport = __esm({
113
257
  }
114
258
  };
115
259
  UnreachableError = class extends Error {
116
- constructor(host, method, route, failure) {
117
- super(`${method} ${route}: no answer from ${host}: ${failure.describe()}. ${failure.next}`);
260
+ constructor(host, method, route2, failure) {
261
+ super(`${method} ${route2}: no answer from ${host}: ${failure.describe()}. ${failure.next}`);
118
262
  this.host = host;
119
263
  this.method = method;
120
- this.route = route;
264
+ this.route = route2;
121
265
  this.failure = failure;
122
266
  this.name = "UnreachableError";
123
267
  }
@@ -176,45 +320,277 @@ var init_transport = __esm({
176
320
  throw this.error;
177
321
  }
178
322
  };
323
+ PLATFORM_STREAM_IDLE_MS = 6e4;
324
+ REFUSAL_TEXT_LIMIT = 64 * 1024;
325
+ KEYED_REDIRECTS = "manual";
179
326
  PlatformTransport = class {
327
+ #endpoint;
328
+ #timeoutMs;
180
329
  constructor(endpoint, timeoutMs = platformTimeoutMs()) {
181
- this.endpoint = endpoint;
182
- this.timeoutMs = timeoutMs;
330
+ this.#endpoint = endpoint;
331
+ this.#timeoutMs = timeoutMs;
183
332
  }
184
- endpoint;
185
- timeoutMs;
186
333
  /** A request that legitimately takes longer (a sandbox exec, a world create) waits its own budget; every other one waits the default. */
187
334
  budget(ownMs) {
188
- return Math.max(ownMs ?? 0, this.timeoutMs);
335
+ return Math.max(ownMs ?? 0, this.#timeoutMs);
189
336
  }
190
- async send(method, route, body, opts = {}) {
337
+ /** One request; the caller's `signal` aborts it in flight and throws the signal's reason, never an `UnreachableError`. */
338
+ async send(method, route2, body, opts = {}) {
191
339
  const timeoutMs = this.budget(opts.timeoutMs);
192
- return (opts.retry ?? RetryPolicy.NONE).run(() => this.once(method, route, body, timeoutMs));
340
+ return (opts.retry ?? RetryPolicy.NONE).run(() => this.once(method, route2, body, timeoutMs, opts.signal));
341
+ }
342
+ /** `send`, then the 2xx body as JSON; any other answer throws `ApiError` with its status and stable `code`. */
343
+ async json(method, route2, body, opts = {}) {
344
+ const reply = await this.send(method, route2, body, opts);
345
+ if (!reply.ok) throw new ApiError(reply.status, method, route2, reply.text);
346
+ return JSON.parse(reply.text);
347
+ }
348
+ /** The streaming twin of `send` for a `GET` event stream: nothing is buffered, `after` travels as `Last-Event-ID`, and each wait for the platform (the headers, every chunk) may last `idleMs` (default 60 s) instead of the request budget. */
349
+ async stream(route2, opts = {}) {
350
+ const watch = new StreamWatch(opts.signal, opts.idleMs ?? PLATFORM_STREAM_IDLE_MS, this.#endpoint.host, route2);
351
+ const headers = this.headers(route2, "text/event-stream", opts.after ? { "last-event-id": opts.after } : {});
352
+ try {
353
+ const response = await watch.within(
354
+ () => fetch(this.url(route2), { method: "GET", headers, signal: watch.signal, redirect: KEYED_REDIRECTS })
355
+ );
356
+ return new PlatformStream(response, watch);
357
+ } catch (error) {
358
+ watch.close();
359
+ throw error;
360
+ }
193
361
  }
194
- async once(method, route, body, timeoutMs) {
362
+ url(route2) {
363
+ return `${this.#endpoint.host}${route2}`;
364
+ }
365
+ headers(route2, accept, extra = {}) {
366
+ return {
367
+ "content-type": "application/json",
368
+ accept,
369
+ ...platformAuthorization(this.#endpoint, this.url(route2)),
370
+ ...extra
371
+ };
372
+ }
373
+ async once(method, route2, body, timeoutMs, caller) {
374
+ if (caller?.aborted) throw caller.reason;
195
375
  const payload = body === void 0 ? {} : { body: JSON.stringify(body) };
376
+ const headers = this.headers(route2, "application/json");
196
377
  const controller = new AbortController();
197
378
  const timer = setTimeout(() => controller.abort(), timeoutMs);
379
+ const relay = () => controller.abort(caller?.reason);
380
+ caller?.addEventListener("abort", relay, { once: true });
198
381
  try {
199
- const res = await fetch(`${this.endpoint.host}${route}`, {
382
+ const res = await fetch(this.url(route2), {
200
383
  method,
201
- headers: {
202
- "content-type": "application/json",
203
- accept: "application/json",
204
- authorization: "Basic " + Buffer.from(`${this.endpoint.publicKey}:${this.endpoint.secretKey}`).toString("base64")
205
- },
384
+ headers,
206
385
  ...payload,
207
- signal: controller.signal
386
+ signal: controller.signal,
387
+ redirect: KEYED_REDIRECTS
208
388
  });
209
389
  return { status: res.status, ok: res.ok, text: await res.text() };
210
390
  } catch (error) {
391
+ if (caller?.aborted) throw caller.reason;
211
392
  const cause = controller.signal.aborted ? TransportCause.timeout(timeoutMs) : TransportCause.of(error);
212
- throw new UnreachableError(this.endpoint.host, method, route, cause);
393
+ throw new UnreachableError(this.#endpoint.host, method, route2, cause);
213
394
  } finally {
214
395
  clearTimeout(timer);
396
+ caller?.removeEventListener("abort", relay);
397
+ }
398
+ }
399
+ };
400
+ StreamWatch = class {
401
+ constructor(caller, idleMs, host, route2) {
402
+ this.idleMs = idleMs;
403
+ this.host = host;
404
+ this.route = route2;
405
+ this.#caller = caller;
406
+ caller?.addEventListener("abort", this.#relay, { once: true });
407
+ if (caller?.aborted) this.#relay();
408
+ }
409
+ idleMs;
410
+ host;
411
+ route;
412
+ #controller = new AbortController();
413
+ #caller;
414
+ #relay = () => this.#controller.abort(this.#caller?.reason);
415
+ #idled = false;
416
+ get signal() {
417
+ return this.#controller.signal;
418
+ }
419
+ async within(wait) {
420
+ const timer = setTimeout(() => this.idle(), this.idleMs);
421
+ try {
422
+ return await wait();
423
+ } catch (error) {
424
+ throw this.failure(error);
425
+ } finally {
426
+ clearTimeout(timer);
427
+ }
428
+ }
429
+ close() {
430
+ this.#caller?.removeEventListener("abort", this.#relay);
431
+ this.#controller.abort();
432
+ }
433
+ idle() {
434
+ this.#idled = true;
435
+ this.#controller.abort();
436
+ }
437
+ failure(error) {
438
+ if (this.#caller?.aborted) return this.#caller.reason;
439
+ const cause = this.#idled ? TransportCause.idle(this.idleMs) : TransportCause.of(error);
440
+ return new UnreachableError(this.host, "GET", this.route, cause);
441
+ }
442
+ };
443
+ PlatformStream = class {
444
+ #response;
445
+ #watch;
446
+ constructor(response, watch) {
447
+ this.#response = response;
448
+ this.#watch = watch;
449
+ }
450
+ get status() {
451
+ return this.#response.status;
452
+ }
453
+ get ok() {
454
+ return this.#response.ok;
455
+ }
456
+ /** The body as text, for a refusal: at most the first 64 KiB of characters; closes the stream. */
457
+ async text() {
458
+ const decoder = new TextDecoder();
459
+ let text2 = "";
460
+ for await (const chunk of this.chunks()) {
461
+ text2 += decoder.decode(chunk, { stream: true });
462
+ if (text2.length >= REFUSAL_TEXT_LIMIT) return text2.slice(0, REFUSAL_TEXT_LIMIT);
215
463
  }
464
+ return text2 + decoder.decode();
465
+ }
466
+ /** The body's bytes as they arrive; the idle budget runs only while waiting for the platform, never while the caller holds a chunk. */
467
+ async *chunks() {
468
+ const reader = this.#response.body?.getReader();
469
+ try {
470
+ for (; ; ) {
471
+ const next = reader ? await this.#watch.within(() => reader.read()) : { done: true };
472
+ if (next.done) return;
473
+ yield next.value;
474
+ }
475
+ } finally {
476
+ this.close();
477
+ }
478
+ }
479
+ close() {
480
+ this.#watch.close();
481
+ }
482
+ };
483
+ }
484
+ });
485
+
486
+ // src/worlds/credentialField.ts
487
+ function isCredentialField(described) {
488
+ const words = described.replace(SPACES, " ").replace(/^ | $/g, "");
489
+ return SECRET_FIELD.some((prefix) => words.startsWith(prefix)) || SECRET_KEY.test(words);
490
+ }
491
+ function credentialTexts(pairs) {
492
+ return pairs.filter(([, text2]) => text2 !== null && text2 !== void 0).filter(([described]) => isCredentialField(String(described))).map(([, text2]) => String(text2));
493
+ }
494
+ function isTextField(described) {
495
+ return described !== "" && !NOT_TEXT.some((prefix) => described.startsWith(prefix));
496
+ }
497
+ function redactActionArgs(action, args) {
498
+ const secretField = action === "browser_type" && SECRET_KEY.test(String(args.selector ?? ""));
499
+ return Object.fromEntries(
500
+ Object.entries(args).map(([key, value]) => [
501
+ key,
502
+ redactedArg(key, value, secretField)
503
+ ])
504
+ );
505
+ }
506
+ function redactedArg(key, value, secretField) {
507
+ if (value === null || value === void 0) return null;
508
+ if (typeof value === "boolean" || typeof value === "number") return value;
509
+ if (typeof value !== "string") return "[omitted]";
510
+ if (SECRET_KEY.test(key) || SECRET_VALUE.test(value) || secretField && key === "text")
511
+ return "[redacted]";
512
+ return value.length <= EVENT_MAX_STRING ? value : value.slice(0, EVENT_MAX_STRING) + "\u2026";
513
+ }
514
+ var SECRET_KEY, DESCRIBE_FIELD_JS, FIELD_VALUE_JS, FIELDS, SHORTEST_WITHHELD, WITHHELD_TEXT, SPACES, LINE_BREAK, TRIM, describeField, readFieldValue, readEditables, UNREADABLE, SECRET_FIELD, NOT_TEXT, escapeRegExp, urlForms, forms, CredentialText, EVENT_MAX_STRING, SECRET_VALUE;
515
+ var init_credentialField = __esm({
516
+ "src/worlds/credentialField.ts"() {
517
+ "use strict";
518
+ SECRET_KEY = /pass(word|wd|code|phrase)|pass(?![a-z])|secret|token(?!s)|(api|private)[-_ ]?key|authorization|cookie|one[-_ ]?time[-_ ]?(code|password)|(verification|security|recovery|backup)[-_ ]?codes?|security[-_ ]?answers?|social[-_ ]?security|(card|account|routing)[-_ ]?(number|no\b)|cc-(number|csc|exp)|(^|[-_ #.\["'=(])(otp|totp|mfa|2fa|pin|cvv|cvc|ssn|iban)([-_ \]"'):.,*]|$)/i;
519
+ DESCRIBE_FIELD_JS = "(e) => { if (!e) return ''; if (e.tagName === 'IFRAME' || e.tagName === 'FRAME') return 'frame'; const root = e.getRootNode(); const byIds = (at) => (at.getAttribute('aria-labelledby') || '').split(/\\s+/).map((id) => (id && root.getElementById ? root.getElementById(id) : null)).map((label) => (label ? label.textContent : '')).join(' '); const labels = e.labels ? [...e.labels].map((label) => label.textContent) : []; const context = []; for (let at = e.parentElement; at; at = at.parentElement) { const legend = at.tagName === 'FIELDSET' ? at.querySelector('legend') : null; context.push(at.getAttribute('aria-label'), byIds(at), legend ? legend.textContent : ''); } const names = [e.getAttribute('aria-label'), byIds(e), ...labels, e.getAttribute('placeholder'), e.getAttribute('title'), ...context]; if (e.tagName === 'SELECT') return ['select', e.name, e.id, ...names].filter(Boolean).join(' '); if (!(e.tagName === 'INPUT' || e.tagName === 'TEXTAREA' || e.isContentEditable)) return 'opaque'; return [e.type, e.name, e.id, e.getAttribute('autocomplete'), ...names].filter(Boolean).join(' '); }";
520
+ FIELD_VALUE_JS = "(e) => { if (e.tagName === 'SELECT') return [...e.selectedOptions].map((o) => o.text).join('\\n'); if (e.tagName === 'INPUT' || e.tagName === 'TEXTAREA') return e.value; return e.isContentEditable ? e.innerText : null; }";
521
+ FIELDS = "input:not([type=button]):not([type=submit]):not([type=reset]):not([type=image]):not([type=checkbox]):not([type=radio]):not([type=file]), textarea, select, [contenteditable]:not([contenteditable=false])";
522
+ SHORTEST_WITHHELD = 4;
523
+ WITHHELD_TEXT = "[redacted]";
524
+ SPACES = /[ \t\n\r\f\v]+/g;
525
+ LINE_BREAK = /\r\n|\r|\n/;
526
+ TRIM = /^[ \t\n\r\f\v]+|[ \t\n\r\f\v]+$/g;
527
+ describeField = new Function(
528
+ "e",
529
+ `return (${DESCRIBE_FIELD_JS})(e);`
530
+ );
531
+ readFieldValue = new Function(
532
+ "e",
533
+ `return (${FIELD_VALUE_JS})(e);`
534
+ );
535
+ readEditables = new Function(
536
+ "elements",
537
+ `return elements.map((e) => [(${DESCRIBE_FIELD_JS})(e), (${FIELD_VALUE_JS})(e)]);`
538
+ );
539
+ UNREADABLE = "unreadable";
540
+ SECRET_FIELD = ["password", "frame", "opaque", UNREADABLE];
541
+ NOT_TEXT = ["opaque", "frame", "select"];
542
+ escapeRegExp = (text2) => text2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
543
+ urlForms = (text2) => {
544
+ let component;
545
+ try {
546
+ component = encodeURIComponent(text2);
547
+ } catch {
548
+ return [];
549
+ }
550
+ const form = component.replace(
551
+ /[!'()~]/g,
552
+ (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase()
553
+ ).replace(/%20/g, "+");
554
+ return [component, component.replace(/%20/g, "+"), form];
555
+ };
556
+ forms = (text2) => {
557
+ const written = [
558
+ text2,
559
+ text2.replace(SPACES, " "),
560
+ JSON.stringify(text2).slice(1, -1)
561
+ ];
562
+ return [
563
+ ...written,
564
+ ...written.map((form) => form.replaceAll("'", "''")),
565
+ ...urlForms(text2)
566
+ ];
567
+ };
568
+ CredentialText = class {
569
+ pattern;
570
+ constructor(secrets) {
571
+ const texts = secrets.map((secret) => String(secret).replace(TRIM, ""));
572
+ const lines = texts.flatMap(
573
+ (text2) => text2.split(LINE_BREAK).map((line) => line.replace(TRIM, ""))
574
+ );
575
+ const whole = new Set(
576
+ [...texts, ...lines].filter(
577
+ (text2) => [...text2].length >= SHORTEST_WITHHELD
578
+ )
579
+ );
580
+ const withheld = [
581
+ ...new Set([...whole].flatMap((text2) => forms(text2)))
582
+ ].sort((a, b) => b.length - a.length);
583
+ this.pattern = withheld.length === 0 ? null : new RegExp(
584
+ `(?<![A-Za-z0-9])(?:${withheld.map(escapeRegExp).join("|")})(?![A-Za-z0-9])`,
585
+ "g"
586
+ );
587
+ }
588
+ withhold(text2) {
589
+ return this.pattern === null ? text2 : text2.replace(this.pattern, WITHHELD_TEXT);
216
590
  }
217
591
  };
592
+ EVENT_MAX_STRING = 500;
593
+ SECRET_VALUE = /^((sk|pk|ghp|xox[abp])[-_][-_A-Za-z0-9]{8,}|AKIA[0-9A-Z]{12,}|Bearer [-_.A-Za-z0-9]{8,})/;
218
594
  }
219
595
  });
220
596
 
@@ -231,6 +607,25 @@ function isBrowserGone(error) {
231
607
  if (PAGE_NETWORK_ERROR.test(message)) return false;
232
608
  return BROWSER_GONE_PATTERNS.some((p) => p.test(message));
233
609
  }
610
+ function scrubError(error, scrub) {
611
+ const seen = /* @__PURE__ */ new Set();
612
+ let at = error;
613
+ while (at instanceof Error && !seen.has(at)) {
614
+ seen.add(at);
615
+ at.message = scrub(at.message);
616
+ at.stack = at.stack && scrub(at.stack);
617
+ scrubOwnText(at, scrub);
618
+ at = at.cause;
619
+ }
620
+ }
621
+ function scrubOwnText(error, scrub) {
622
+ for (const key of Object.keys(error)) {
623
+ const value = error[key];
624
+ if (typeof value === "string") error[key] = scrub(value);
625
+ if (Array.isArray(value) && value.every((item) => typeof item === "string"))
626
+ error[key] = value.map((item) => scrub(item));
627
+ }
628
+ }
234
629
  function refusalIsTransient(error) {
235
630
  const { status, code } = error;
236
631
  if (typeof status !== "number") return true;
@@ -267,11 +662,17 @@ var init_browserReconnect = __esm({
267
662
  ].sort((a, b) => b.length - a.length);
268
663
  }
269
664
  scrub(text2) {
270
- const bare = this.secrets.reduce(
665
+ const bare2 = this.secrets.reduce(
271
666
  (out, secret) => out.split(secret).join(REDACTED),
272
667
  text2
273
668
  );
274
- return bare.replace(TOKEN_QUERY_VALUE, `$1${REDACTED}`);
669
+ return bare2.replace(TOKEN_QUERY_VALUE, `$1${REDACTED}`);
670
+ }
671
+ /** Scrub `error` and the errors it was raised from, in place: the message,
672
+ * the stack and every other own text property, Playwright's `log` call log
673
+ * included. */
674
+ scrubError(error) {
675
+ scrubError(error, (text2) => this.scrub(text2));
275
676
  }
276
677
  };
277
678
  BrowserReconnected = class extends Error {
@@ -423,22 +824,6 @@ function capabilityLabel(url) {
423
824
  }
424
825
  return CAPABILITY_HOST.exec(host)?.[1] ?? null;
425
826
  }
426
- function redactActionArgs(action, args) {
427
- const secretField = action === "browser_type" && SECRET_KEY.test(String(args.selector ?? ""));
428
- const out = {};
429
- for (const [key, value] of Object.entries(args)) {
430
- if (value === null || value === void 0) out[key] = null;
431
- else if (typeof value === "boolean" || typeof value === "number")
432
- out[key] = value;
433
- else if (typeof value === "string") {
434
- if (SECRET_KEY.test(key) || SECRET_VALUE.test(value) || secretField && key === "text")
435
- out[key] = "[redacted]";
436
- else
437
- out[key] = value.length <= EVENT_MAX_STRING ? value : value.slice(0, EVENT_MAX_STRING) + "\u2026";
438
- } else out[key] = "[omitted]";
439
- }
440
- return out;
441
- }
442
827
  async function loadPlaywright() {
443
828
  try {
444
829
  const name = "playwright";
@@ -500,62 +885,14 @@ async function openBrowser(surfaces, opts = {}) {
500
885
  scrubber
501
886
  );
502
887
  }
503
- function computerUseToolkit(browser, opts = {}) {
504
- const maxText = opts.maxText ?? 2e4;
505
- const observe = async (selector = "body") => {
506
- const text2 = await browser.text(selector);
507
- return {
508
- url: browser.url,
509
- title: await browser.title(),
510
- text: text2.slice(0, maxText),
511
- truncated: text2.length > maxText
512
- };
513
- };
514
- const impls = {
515
- browser_goto: async (a) => {
516
- await browser.goto(typeof a.path === "string" ? a.path : void 0);
517
- return observe();
518
- },
519
- browser_click: async (a) => {
520
- await browser.click(str(a.selector, ""));
521
- return observe();
522
- },
523
- browser_type: async (a) => {
524
- await browser.type(str(a.selector, ""), String(a.text ?? ""));
525
- return { ok: true, url: browser.url };
526
- },
527
- browser_press: async (a) => {
528
- await browser.press(str(a.key, "Enter"));
529
- return observe();
530
- },
531
- browser_scroll: async (a) => {
532
- await browser.scroll(typeof a.dy === "number" ? a.dy : 600);
533
- return { ok: true, url: browser.url };
534
- },
535
- browser_screenshot: async (a) => ({
536
- image_base64: await browser.screenshotBase64(a.full_page === true),
537
- url: browser.url
538
- }),
539
- browser_read: async (a) => observe(str(a.selector, "body")),
540
- browser_back: async () => {
541
- await browser.back();
542
- return observe();
543
- }
544
- };
545
- const specs = COMPUTER_USE_SPECS.map((s) => ({ ...s }));
546
- return {
547
- schemas: specs.map((spec) => schemaFromSignature(spec)),
548
- impls,
549
- specs
550
- };
551
- }
552
- var SURFACE_KINDS, PLATFORM_SESSION_HEADER, SESSION_AUTH_MODES, BROWSER_TIERS, DEFAULT_VIEWPORT, SETTLE_TIMEOUT_MS, SETTLE_QUIET_MS, SETTLE_POLL_MS, EVENT_BATCH_SIZE, EVENT_FLUSH_INTERVAL_MS, EVENT_MAX_RETRIES, EVENT_SCREENSHOT_QUALITY, EVENT_MAX_STRING, SECRET_KEY, SECRET_VALUE, WorldSurfaceUnavailable, UI_TOKEN_QUERY, CAPABILITY_HOST, BrowserActionRecorder, WorldBrowser, COMPUTER_USE_SPECS, str;
888
+ var SURFACE_KINDS, FIELD_PROBE_TIMEOUT_MS, PLATFORM_SESSION_HEADER, SESSION_AUTH_MODES, BROWSER_TIERS, DEFAULT_VIEWPORT, SETTLE_TIMEOUT_MS, SETTLE_QUIET_MS, SETTLE_POLL_MS, EVENT_BATCH_SIZE, EVENT_FLUSH_INTERVAL_MS, EVENT_MAX_RETRIES, EVENT_SCREENSHOT_QUALITY, WorldSurfaceUnavailable, UI_TOKEN_QUERY, CAPABILITY_HOST, BrowserActionRecorder, WorldBrowser;
553
889
  var init_browser = __esm({
554
890
  "src/worlds/browser.ts"() {
555
891
  "use strict";
556
- init_session2();
892
+ init_credentialField();
557
893
  init_browserReconnect();
558
894
  SURFACE_KINDS = ["tools", "api", "ui", "browser"];
895
+ FIELD_PROBE_TIMEOUT_MS = 2e3;
559
896
  PLATFORM_SESSION_HEADER = "X-World-Session";
560
897
  SESSION_AUTH_MODES = ["vendor", "open"];
561
898
  BROWSER_TIERS = ["standard", "premium"];
@@ -567,9 +904,6 @@ var init_browser = __esm({
567
904
  EVENT_FLUSH_INTERVAL_MS = 1e3;
568
905
  EVENT_MAX_RETRIES = 3;
569
906
  EVENT_SCREENSHOT_QUALITY = 60;
570
- EVENT_MAX_STRING = 500;
571
- SECRET_KEY = /pass(word|wd)?|secret|token|api[-_]?key|authorization|cookie|(^|[-_ #.\["'=])(otp|pin|cvv|ssn)([-_ \]"']|$)/i;
572
- SECRET_VALUE = /^((sk|pk|ghp|xox[abp])[-_][-_A-Za-z0-9]{8,}|AKIA[0-9A-Z]{12,}|Bearer [-_.A-Za-z0-9]{8,})/;
573
907
  WorldSurfaceUnavailable = class extends Error {
574
908
  constructor(surface, reason) {
575
909
  super(`World surface '${surface}' is unavailable: ${reason}`);
@@ -692,6 +1026,8 @@ var init_browser = __esm({
692
1026
  recorder;
693
1027
  reconnector;
694
1028
  scrubber;
1029
+ typed = [];
1030
+ typedText = new CredentialText([]);
695
1031
  current;
696
1032
  inflight = 0;
697
1033
  lastNetwork = Date.now();
@@ -705,10 +1041,20 @@ var init_browser = __esm({
705
1041
  get agentId() {
706
1042
  return this.recorder?.agentId ?? null;
707
1043
  }
708
- /** `text` with this session's credentials (UI token, browser address) removed. */
1044
+ /** `text` with this session's credentials (UI token, browser address) and
1045
+ * the credentials typed into it removed. */
709
1046
  scrub(text2) {
1047
+ return this.typedText.withhold(this.scrubber.scrub(text2));
1048
+ }
1049
+ /** `text` with this session's credentials removed and nothing else
1050
+ * changed: for text that is compared and never leaves the process. */
1051
+ scrubSession(text2) {
710
1052
  return this.scrubber.scrub(text2);
711
1053
  }
1054
+ /** Every credential typed into this browser by `type`. */
1055
+ get typedCredentials() {
1056
+ return [...this.typed];
1057
+ }
712
1058
  watchNetwork(page) {
713
1059
  page.on("request", () => {
714
1060
  this.inflight += 1;
@@ -752,7 +1098,7 @@ var init_browser = __esm({
752
1098
  async recover(reconnector, cause) {
753
1099
  const started = Date.now();
754
1100
  const message = cause instanceof Error ? cause.message : String(cause);
755
- const args = { cause: this.scrubber.scrub(message).slice(0, 200) };
1101
+ const args = { cause: this.scrub(message).slice(0, 200) };
756
1102
  let result;
757
1103
  try {
758
1104
  result = await reconnector.recover(cause, (c) => this.adopt(c));
@@ -787,7 +1133,9 @@ var init_browser = __esm({
787
1133
  }
788
1134
  /** Run one action and report it: the event carries what was asked,
789
1135
  * whether it worked, and the screen after — for failures too, so a
790
- * reviewer sees what the agent saw when the selector did not match. */
1136
+ * reviewer sees what the agent saw when the selector did not match. The
1137
+ * error it throws keeps no session credential and no credential typed into
1138
+ * this browser, which Playwright's call log would quote. */
791
1139
  async act(action, args, fn, onLoss = "report") {
792
1140
  const started = Date.now();
793
1141
  try {
@@ -795,6 +1143,7 @@ var init_browser = __esm({
795
1143
  await this.report(action, args, started, null);
796
1144
  return result;
797
1145
  } catch (error) {
1146
+ this.scrubError(error);
798
1147
  await this.report(action, args, started, error);
799
1148
  throw error;
800
1149
  }
@@ -803,7 +1152,7 @@ var init_browser = __esm({
803
1152
  async report(action, args, started, failure) {
804
1153
  const recorder = this.recorder;
805
1154
  if (!recorder) return;
806
- const error = failure === null ? null : this.scrubber.scrub(
1155
+ const error = failure === null ? null : this.scrub(
807
1156
  failure instanceof Error ? `${failure.name}: ${failure.message}` : String(failure)
808
1157
  ).slice(0, 4e3);
809
1158
  recorder.record({
@@ -816,7 +1165,7 @@ var init_browser = __esm({
816
1165
  Object.fromEntries(
817
1166
  Object.entries(args).map(([key, value]) => [
818
1167
  key,
819
- typeof value === "string" ? this.scrubber.scrub(value) : value
1168
+ typeof value === "string" ? this.scrub(value) : value
820
1169
  ])
821
1170
  )
822
1171
  ),
@@ -835,8 +1184,8 @@ var init_browser = __esm({
835
1184
  screenshot: null
836
1185
  };
837
1186
  try {
838
- out.url = this.scrubber.scrub(this.page.url());
839
- out.title = this.scrubber.scrub(await this.page.title());
1187
+ out.url = this.scrub(this.page.url());
1188
+ out.title = this.scrub(await this.page.title());
840
1189
  const jpeg = await this.page.screenshot({
841
1190
  type: "jpeg",
842
1191
  quality: EVENT_SCREENSHOT_QUALITY
@@ -873,7 +1222,7 @@ var init_browser = __esm({
873
1222
  async () => {
874
1223
  await this.page.goto(target, { waitUntil: "load" });
875
1224
  await this.settle();
876
- return this.page.url();
1225
+ return this.url;
877
1226
  },
878
1227
  // Navigating again lands on the same page: safe to replay.
879
1228
  "retry"
@@ -883,7 +1232,7 @@ var init_browser = __esm({
883
1232
  return this.act("browser_back", {}, async () => {
884
1233
  await this.page.goBack({ waitUntil: "load" });
885
1234
  await this.settle();
886
- return this.page.url();
1235
+ return this.url;
887
1236
  });
888
1237
  }
889
1238
  /** Wait for the page to finish reacting to an action. `load` alone is not
@@ -902,19 +1251,54 @@ var init_browser = __esm({
902
1251
  await this.page.waitForTimeout(SETTLE_POLL_MS);
903
1252
  }
904
1253
  }
905
- async click(selector) {
1254
+ async click(selector, opts = {}) {
906
1255
  await this.act("browser_click", { selector }, async () => {
907
- await this.page.click(selector);
1256
+ await this.page.click(selector, { timeout: opts.timeoutMs });
908
1257
  await this.settle();
909
1258
  });
910
1259
  }
911
- async type(selector, text2) {
1260
+ /** Replace the field's value with `text`. `opts.credential` is whether the
1261
+ * field takes one, when the caller already probed it; a credential is
1262
+ * withheld from the event and from any error. */
1263
+ async type(selector, text2, opts = {}) {
1264
+ const secret = opts.credential ?? await this.credentialField(selector);
1265
+ if (secret) this.typed.push(text2);
1266
+ this.typedText = new CredentialText(this.typed);
912
1267
  await this.act(
913
1268
  "browser_type",
914
- { selector, text: text2 },
915
- () => this.page.fill(selector, text2)
1269
+ { selector, text: secret ? "[redacted]" : text2 },
1270
+ () => this.page.fill(selector, text2, { timeout: opts.timeoutMs })
916
1271
  );
917
1272
  }
1273
+ /** `DESCRIBE_FIELD_JS` of the element `selector` finds, or `UNREADABLE`. */
1274
+ async describeField(selector) {
1275
+ try {
1276
+ const described = await this.page.locator(selector).evaluate(describeField, void 0, { timeout: FIELD_PROBE_TIMEOUT_MS });
1277
+ return String(described ?? "");
1278
+ } catch {
1279
+ return UNREADABLE;
1280
+ }
1281
+ }
1282
+ /** Whether the field `selector` finds takes a credential; one it cannot
1283
+ * read counts. */
1284
+ async credentialField(selector) {
1285
+ return isCredentialField(await this.describeField(selector));
1286
+ }
1287
+ /** What the field `selector` finds holds (`FIELD_VALUE_JS`), or null when
1288
+ * it cannot be read. */
1289
+ async fieldValue(selector) {
1290
+ try {
1291
+ const value = await this.page.locator(selector).evaluate(readFieldValue, void 0, { timeout: FIELD_PROBE_TIMEOUT_MS });
1292
+ return value === null || value === void 0 ? null : String(value);
1293
+ } catch {
1294
+ return null;
1295
+ }
1296
+ }
1297
+ /** Take this session's credentials out of `error` and the errors it came
1298
+ * from, in place. */
1299
+ scrubError(error) {
1300
+ scrubError(error, (text2) => this.scrub(text2));
1301
+ }
918
1302
  async press(key) {
919
1303
  await this.act("browser_press", { key }, async () => {
920
1304
  await this.page.keyboard.press(key);
@@ -937,41 +1321,549 @@ var init_browser = __esm({
937
1321
  async screenshotBase64(fullPage = false) {
938
1322
  return (await this.screenshot(fullPage)).toString("base64");
939
1323
  }
1324
+ /** The visible text of `selector`'s element, without what any field on the
1325
+ * page that takes a credential holds. */
940
1326
  async text(selector = "body") {
941
- return this.resilient(() => this.page.innerText(selector), "retry");
1327
+ const withheld = new CredentialText(await this.credentialTexts());
1328
+ return withheld.withhold(
1329
+ await this.resilient(() => this.page.innerText(selector), "retry")
1330
+ );
1331
+ }
1332
+ /** What each field on the page that takes a credential holds: an input's
1333
+ * or textarea's value, a select's chosen option, a contenteditable's text. */
1334
+ async credentialTexts() {
1335
+ return this.resilient(async () => {
1336
+ const pairs = await this.page.locator(FIELDS).evaluateAll(readEditables);
1337
+ return credentialTexts(pairs);
1338
+ }, "retry");
1339
+ }
1340
+ /** Wait until the element `selector` finds could be clicked, without
1341
+ * clicking it. */
1342
+ async actionable(selector) {
1343
+ await this.resilient(() => this.page.locator(selector).click({ trial: true }), "retry");
1344
+ }
1345
+ async ariaSnapshot() {
1346
+ return this.resilient(async () => {
1347
+ if (!this.page.ariaSnapshot)
1348
+ throw new TypeError("this Playwright has no page.ariaSnapshot");
1349
+ return this.page.ariaSnapshot({ mode: "ai" });
1350
+ }, "retry");
942
1351
  }
943
1352
  async html() {
944
1353
  return this.resilient(() => this.page.content(), "retry");
945
1354
  }
946
1355
  get url() {
947
- return this.page.url();
1356
+ return withoutUiToken(this.page.url());
1357
+ }
1358
+ async title() {
1359
+ return this.resilient(() => this.page.title(), "retry");
1360
+ }
1361
+ async close() {
1362
+ try {
1363
+ await this.teardown();
1364
+ } finally {
1365
+ await this.recorder?.close();
1366
+ }
1367
+ }
1368
+ };
1369
+ }
1370
+ });
1371
+
1372
+ // src/worlds/pageState.ts
1373
+ function selectorRef(selector) {
1374
+ if (selector.includes("aria-ref"))
1375
+ throw new PageStateError(
1376
+ "aria-ref selectors are not taken: pass ref=\u2026 from browser_snapshot"
1377
+ );
1378
+ return REF_SELECTOR.exec(selector.replace(/^ +| +$/g, ""))?.[1] ?? null;
1379
+ }
1380
+ var DEFAULT_MAX_CHARS, REF_ACT_TIMEOUT_MS, STEADY_READS, NEEDS_PLAYWRIGHT, CHANGED, LINE_KEY, ATTRIBUTES, FOCUS, STATES, ROLE, REF, REF_SELECTOR, EDITABLE_ROLES, VALUE_KEYS, WITHHELD, PageStateError, AriaLine, Touched, sameLines, deeper, PageState, PageObserver;
1381
+ var init_pageState = __esm({
1382
+ "src/worlds/pageState.ts"() {
1383
+ "use strict";
1384
+ init_credentialField();
1385
+ DEFAULT_MAX_CHARS = 2e4;
1386
+ REF_ACT_TIMEOUT_MS = 2e3;
1387
+ STEADY_READS = 4;
1388
+ NEEDS_PLAYWRIGHT = "browser_snapshot needs Playwright 1.59 or newer (npm install playwright@latest)";
1389
+ CHANGED = "the page changed since the last browser_snapshot: take a new one (a page that never holds still can be driven with text= or CSS selectors)";
1390
+ LINE_KEY = /^ *- ('(?:[^']|'')*'|.*?)(:(?: .*)?)?$/s;
1391
+ ATTRIBUTES = /(?: \[[^[\]]*\])*$/;
1392
+ FOCUS = / \[active\]/g;
1393
+ STATES = / \[(?:checked(?:=mixed)?|expanded|pressed(?:=mixed)?|selected)\]/g;
1394
+ ROLE = /^[a-z]+/;
1395
+ REF = /\[ref=((?:f[0-9]+)?e[0-9]+)\]/g;
1396
+ REF_SELECTOR = /^ref=((?:f[0-9]+)?e[0-9]+)$/;
1397
+ EDITABLE_ROLES = /* @__PURE__ */ new Set([
1398
+ "textbox",
1399
+ "searchbox",
1400
+ "combobox",
1401
+ "spinbutton",
1402
+ "slider"
1403
+ ]);
1404
+ VALUE_KEYS = /* @__PURE__ */ new Set(["text", "/placeholder"]);
1405
+ WITHHELD = ": [redacted]";
1406
+ PageStateError = class extends Error {
1407
+ name = "PageStateError";
1408
+ };
1409
+ AriaLine = class _AriaLine {
1410
+ constructor(text2, indent, key = "", attributes = "", rest = "") {
1411
+ this.text = text2;
1412
+ this.indent = indent;
1413
+ this.key = key;
1414
+ this.attributes = attributes;
1415
+ this.rest = rest;
1416
+ }
1417
+ text;
1418
+ indent;
1419
+ key;
1420
+ attributes;
1421
+ rest;
1422
+ static parse(text2) {
1423
+ const indent = text2.length - text2.replace(/^ +/, "").length;
1424
+ const found = LINE_KEY.exec(text2);
1425
+ if (!found) return new _AriaLine(text2, indent);
1426
+ const key = found[1].startsWith("'") ? found[1].slice(1, -1).replaceAll("''", "'") : found[1];
1427
+ return new _AriaLine(
1428
+ text2,
1429
+ indent,
1430
+ key,
1431
+ ATTRIBUTES.exec(key)?.[0] ?? "",
1432
+ found[2] ?? ""
1433
+ );
1434
+ }
1435
+ static parseAll(aria) {
1436
+ return aria === "" ? [] : aria.split("\n").map((text2) => _AriaLine.parse(text2));
1437
+ }
1438
+ get refs() {
1439
+ return [...this.attributes.matchAll(REF)].map((ref) => ref[1]);
1440
+ }
1441
+ get disabled() {
1442
+ return this.attributes.includes("[disabled]");
1443
+ }
1444
+ get editable() {
1445
+ const role = ROLE.exec(this.key)?.[0];
1446
+ return role !== void 0 && EDITABLE_ROLES.has(role);
1447
+ }
1448
+ /** A value line: a field's text, or the placeholder it shows. */
1449
+ get value() {
1450
+ return VALUE_KEYS.has(this.key);
1451
+ }
1452
+ get states() {
1453
+ return this.attributes.match(STATES) ?? [];
1454
+ }
1455
+ get namedLikeCredential() {
1456
+ return SECRET_KEY.test(
1457
+ this.key.slice(0, this.key.length - this.attributes.length)
1458
+ );
1459
+ }
1460
+ /** Whether every value in and under this line is withheld. A field is,
1461
+ * when it is named like a credential or sits in something that is, has no
1462
+ * ref to probe, or `describe` reads it as a credential field. Any other
1463
+ * line is, when it is named like a credential and holds typed text (a
1464
+ * contenteditable), or has no ref to tell. */
1465
+ async credentialField(describe2, withinCredential) {
1466
+ if (this.editable)
1467
+ return this.credentialFieldInput(describe2, withinCredential);
1468
+ if (!this.namedLikeCredential) return false;
1469
+ if (this.refs.length === 0) return true;
1470
+ return isTextField(await describe2(this.refs[0]));
1471
+ }
1472
+ async credentialFieldInput(describe2, withinCredential) {
1473
+ if (withinCredential || this.namedLikeCredential) return true;
1474
+ if (this.refs.length === 0) return true;
1475
+ return isCredentialField(await describe2(this.refs[0]));
1476
+ }
1477
+ /** The line as shown: `withholding` applied to its text, while its refs and
1478
+ * states are still read from the attribute run Playwright wrote, so a
1479
+ * withheld name cannot join that run. */
1480
+ withheldBy(withhold) {
1481
+ return new _AriaLine(
1482
+ this.withholding(withhold),
1483
+ this.indent,
1484
+ this.key,
1485
+ this.attributes,
1486
+ this.rest
1487
+ );
1488
+ }
1489
+ /** The line with `withhold` applied to its name and value, its attribute
1490
+ * run (refs, states, levels) as Playwright wrote it. */
1491
+ withholding(withhold) {
1492
+ const at = this.attributes ? this.text.lastIndexOf(
1493
+ this.attributes,
1494
+ this.text.length - this.rest.length - this.attributes.length
1495
+ ) : -1;
1496
+ if (at < 0) return withhold(this.text);
1497
+ const end = at + this.attributes.length;
1498
+ return withhold(this.text.slice(0, at)) + this.attributes + withhold(this.text.slice(end));
1499
+ }
1500
+ /** The line with its own value replaced, keeping the key as Playwright
1501
+ * wrote it. */
1502
+ get withheld() {
1503
+ if (this.key === "/placeholder" || !this.rest.startsWith(": "))
1504
+ return this.text;
1505
+ return this.text.slice(0, this.text.length - this.rest.length) + WITHHELD;
1506
+ }
1507
+ };
1508
+ Touched = class _Touched {
1509
+ constructor(clicked = /* @__PURE__ */ new Map(), typed = /* @__PURE__ */ new Map()) {
1510
+ this.clicked = clicked;
1511
+ this.typed = typed;
1512
+ }
1513
+ clicked;
1514
+ typed;
1515
+ afterClick(ref, states) {
1516
+ return new _Touched(new Map([...this.clicked, [ref, states]]), this.typed);
1517
+ }
1518
+ afterTyping(ref, text2) {
1519
+ return new _Touched(this.clicked, new Map([...this.typed, [ref, text2]]));
1520
+ }
1521
+ /** The snapshot's lines as the page should now read them. */
1522
+ expected(lines) {
1523
+ return this.compared(lines, (line) => this.leftByClick(line));
1524
+ }
1525
+ /** A fresh read's lines, in the same form. */
1526
+ actual(lines) {
1527
+ return this.compared(lines, (line) => line.states);
1528
+ }
1529
+ compared(lines, states) {
1530
+ const out = [];
1531
+ let typedAt = null;
1532
+ for (const line of lines) {
1533
+ if (typedAt !== null && line.indent > typedAt && line.value) continue;
1534
+ typedAt = this.isTyped(line) ? line.indent : null;
1535
+ out.push(this.comparedLine(line, states(line)));
1536
+ }
1537
+ return out;
1538
+ }
1539
+ isTyped(line) {
1540
+ return line.refs.some((ref) => this.typed.has(ref));
1541
+ }
1542
+ clickedRef(line) {
1543
+ return line.refs.find((ref) => this.clicked.has(ref));
1544
+ }
1545
+ leftByClick(line) {
1546
+ const ref = this.clickedRef(line);
1547
+ return ref === void 0 ? line.states : this.clicked.get(ref);
1548
+ }
1549
+ comparedLine(line, states) {
1550
+ if (this.isTyped(line))
1551
+ return (" ".repeat(line.indent) + "- " + line.key).replace(FOCUS, "");
1552
+ if (this.clickedRef(line) !== void 0)
1553
+ return line.text.replace(FOCUS, "").replace(STATES, "") + states.join("");
1554
+ return line.text.replace(FOCUS, "");
1555
+ }
1556
+ };
1557
+ sameLines = (a, b) => a.length === b.length && a.every((line, at) => line === b[at]);
1558
+ deeper = (line, below) => below !== null && line.indent > below ? below : null;
1559
+ PageState = class _PageState {
1560
+ constructor(url, title, snapshot, refs, disabled, truncated, credentials = /* @__PURE__ */ new Set()) {
1561
+ this.url = url;
1562
+ this.title = title;
1563
+ this.snapshot = snapshot;
1564
+ this.refs = refs;
1565
+ this.disabled = disabled;
1566
+ this.truncated = truncated;
1567
+ this.credentials = credentials;
1568
+ }
1569
+ url;
1570
+ title;
1571
+ snapshot;
1572
+ refs;
1573
+ disabled;
1574
+ truncated;
1575
+ credentials;
1576
+ static parse(aria, opts) {
1577
+ return _PageState.ofLines(AriaLine.parseAll(aria), opts);
1578
+ }
1579
+ static ofLines(lines, opts) {
1580
+ const maxChars = opts.maxChars ?? DEFAULT_MAX_CHARS;
1581
+ const shown = [];
1582
+ let size = 0;
1583
+ for (const line of lines) {
1584
+ const width = [...line.text].length + 1;
1585
+ if (size + width > maxChars) break;
1586
+ size += width;
1587
+ shown.push(line);
1588
+ }
1589
+ return new _PageState(
1590
+ opts.url,
1591
+ opts.title,
1592
+ shown.map((line) => line.text).join("\n"),
1593
+ new Set(shown.flatMap((line) => line.refs)),
1594
+ new Set(
1595
+ shown.filter((line) => line.disabled).flatMap((line) => line.refs)
1596
+ ),
1597
+ shown.length < lines.length,
1598
+ opts.credentials ?? /* @__PURE__ */ new Set()
1599
+ );
1600
+ }
1601
+ /** `aria` with credential values withheld: every value in and under a
1602
+ * credential field (see `AriaLine.credentialField`; `describe` is
1603
+ * `DESCRIBE_FIELD_JS` of a ref's element), the placeholder aside, and the
1604
+ * value of any line named like a credential. Names, roles and refs stay. */
1605
+ static async redacted(aria, describe2) {
1606
+ const out = [];
1607
+ const withheld = [];
1608
+ let withheldBelow = null;
1609
+ let credentialBelow = null;
1610
+ for (const line of AriaLine.parseAll(aria)) {
1611
+ withheldBelow = deeper(line, withheldBelow);
1612
+ credentialBelow = deeper(line, credentialBelow);
1613
+ if (withheldBelow === null && await line.credentialField(describe2, credentialBelow !== null))
1614
+ withheldBelow = line.indent;
1615
+ if (credentialBelow === null && line.namedLikeCredential)
1616
+ credentialBelow = line.indent;
1617
+ const hidden = withheldBelow !== null || line.namedLikeCredential;
1618
+ out.push(hidden ? line.withheld : line.text);
1619
+ if (hidden) withheld.push(...line.refs);
1620
+ }
1621
+ return { snapshot: out.join("\n"), withheld: new Set(withheld) };
1622
+ }
1623
+ target(ref) {
1624
+ if (!this.refs.has(ref))
1625
+ throw new PageStateError(
1626
+ `ref=${ref} is not in the last browser_snapshot: take a new one`
1627
+ );
1628
+ if (this.disabled.has(ref))
1629
+ throw new PageStateError(`ref=${ref} is disabled`);
1630
+ return `aria-ref=${ref}`;
1631
+ }
1632
+ observation() {
1633
+ return {
1634
+ url: this.url,
1635
+ title: this.title,
1636
+ snapshot: this.snapshot,
1637
+ truncated: this.truncated
1638
+ };
1639
+ }
1640
+ };
1641
+ PageObserver = class {
1642
+ constructor(browser, maxChars = DEFAULT_MAX_CHARS) {
1643
+ this.browser = browser;
1644
+ this.maxChars = maxChars;
1645
+ }
1646
+ browser;
1647
+ maxChars;
1648
+ last = null;
1649
+ seen = [];
1650
+ seenUrl = "";
1651
+ touched = new Touched();
1652
+ turn = Promise.resolve();
1653
+ async snapshot() {
1654
+ return this.inTurn(() => this.takeSnapshot());
1655
+ }
1656
+ async click(selector) {
1657
+ return this.inTurn(() => this.clickOnce(selector));
1658
+ }
1659
+ async type(selector, text2) {
1660
+ return this.inTurn(() => this.typeOnce(selector, text2));
1661
+ }
1662
+ /** One call at a time, so a tool call a model made in parallel cannot act
1663
+ * between another's checks and its action. */
1664
+ inTurn(fn) {
1665
+ const run = this.turn.then(fn, fn);
1666
+ this.turn = run.catch(() => void 0);
1667
+ return run;
1668
+ }
1669
+ async takeSnapshot() {
1670
+ const aria = this.browser.scrubSession(await this.steady());
1671
+ const shown = await PageState.redacted(
1672
+ aria,
1673
+ (ref) => this.browser.describeField(`aria-ref=${ref}`)
1674
+ );
1675
+ const secrets = new CredentialText([
1676
+ ...await this.withheldValues(shown),
1677
+ ...await this.browser.credentialTexts(),
1678
+ ...this.browser.typedCredentials
1679
+ ]);
1680
+ const lines = AriaLine.parseAll(shown.snapshot).map(
1681
+ (line) => line.withheldBy((text2) => secrets.withhold(text2))
1682
+ );
1683
+ this.last = PageState.ofLines(lines, {
1684
+ url: this.url(),
1685
+ title: this.browser.scrub(await this.browser.title()),
1686
+ maxChars: this.maxChars,
1687
+ credentials: shown.withheld
1688
+ });
1689
+ this.seen = AriaLine.parseAll(aria);
1690
+ this.seenUrl = this.browser.scrubSession(this.browser.url);
1691
+ this.touched = new Touched();
1692
+ return this.last;
1693
+ }
1694
+ /** The values of the fields the redaction withheld: a page may repeat them
1695
+ * in another line's name (a row or cell named from its content, a label
1696
+ * that wraps the field). */
1697
+ async withheldValues(shown) {
1698
+ const refs = AriaLine.parseAll(shown.snapshot).filter((line) => line.editable).flatMap((line) => line.refs).filter((ref) => shown.withheld.has(ref));
1699
+ const values = [];
1700
+ for (const ref of refs)
1701
+ values.push(await this.browser.fieldValue(`aria-ref=${ref}`) ?? "");
1702
+ return values;
1703
+ }
1704
+ async clickOnce(selector) {
1705
+ const ref = selectorRef(selector);
1706
+ if (ref === null) return this.browser.click(selector);
1707
+ const [, target] = this.target(ref);
1708
+ await this.ready(target);
1709
+ await this.browser.click(target, { timeoutMs: REF_ACT_TIMEOUT_MS });
1710
+ const left = (await this.now()).find((line) => line.refs.includes(ref));
1711
+ if (left) this.touched = this.touched.afterClick(ref, left.states);
1712
+ }
1713
+ async typeOnce(selector, text2) {
1714
+ const ref = selectorRef(selector);
1715
+ if (ref === null) return this.browser.type(selector, text2);
1716
+ const [last, target] = this.target(ref);
1717
+ const credential = last.credentials.has(ref) || await this.browser.credentialField(target);
1718
+ await this.ready(target);
1719
+ await this.browser.type(target, text2, {
1720
+ timeoutMs: REF_ACT_TIMEOUT_MS,
1721
+ credential
1722
+ });
1723
+ this.touched = this.touched.afterTyping(ref, text2);
948
1724
  }
949
- async title() {
950
- return this.resilient(() => this.page.title(), "retry");
1725
+ target(ref) {
1726
+ if (this.last === null)
1727
+ throw new PageStateError(
1728
+ "ref=\u2026 selectors come from browser_snapshot: take one first"
1729
+ );
1730
+ return [this.last, this.last.target(ref)];
1731
+ }
1732
+ async ready(target) {
1733
+ await this.still();
1734
+ await this.browser.actionable(target);
1735
+ await this.still();
1736
+ }
1737
+ /** A page still rendering when it is read would refuse the model's next
1738
+ * ref, so the snapshot it is shown is one that read the same before and
1739
+ * after the page settled again. */
1740
+ async steady() {
1741
+ const untouched = new Touched();
1742
+ let aria = await this.read();
1743
+ for (let read = 1; read < STEADY_READS; read++) {
1744
+ await this.browser.settle();
1745
+ const again = await this.read();
1746
+ if (sameLines(
1747
+ untouched.actual(AriaLine.parseAll(again)),
1748
+ untouched.actual(AriaLine.parseAll(aria))
1749
+ ))
1750
+ return again;
1751
+ aria = again;
1752
+ }
1753
+ return aria;
951
1754
  }
952
- async close() {
1755
+ async read() {
953
1756
  try {
954
- await this.teardown();
955
- } finally {
956
- await this.recorder?.close();
1757
+ return await this.browser.ariaSnapshot();
1758
+ } catch (error) {
1759
+ if (error instanceof TypeError)
1760
+ throw new PageStateError(NEEDS_PLAYWRIGHT);
1761
+ throw error;
957
1762
  }
958
1763
  }
1764
+ url() {
1765
+ return this.browser.scrub(this.browser.url);
1766
+ }
1767
+ async now() {
1768
+ return AriaLine.parseAll(this.browser.scrubSession(await this.read()));
1769
+ }
1770
+ async still() {
1771
+ if (this.browser.scrubSession(this.browser.url) !== this.seenUrl || !sameLines(
1772
+ this.touched.actual(await this.now()),
1773
+ this.touched.expected(this.seen)
1774
+ ))
1775
+ throw new PageStateError(CHANGED);
1776
+ for (const [ref, text2] of this.touched.typed)
1777
+ if (await this.browser.fieldValue(`aria-ref=${ref}`) !== text2)
1778
+ throw new PageStateError(CHANGED);
1779
+ }
1780
+ };
1781
+ }
1782
+ });
1783
+
1784
+ // src/worlds/browserTools.ts
1785
+ function computerUseToolkit(browser, opts = {}) {
1786
+ const maxText = opts.maxText ?? DEFAULT_MAX_CHARS;
1787
+ const pages = new PageObserver(browser, maxText);
1788
+ const observe = async (selector = "body") => {
1789
+ const text2 = browser.scrub(await browser.text(selector));
1790
+ return {
1791
+ url: browser.scrub(browser.url),
1792
+ title: browser.scrub(await browser.title()),
1793
+ text: text2.slice(0, maxText),
1794
+ truncated: text2.length > maxText
959
1795
  };
1796
+ };
1797
+ const impls = {
1798
+ browser_goto: async (a) => {
1799
+ await browser.goto(typeof a.path === "string" ? a.path : void 0);
1800
+ return observe();
1801
+ },
1802
+ browser_snapshot: async () => (await pages.snapshot()).observation(),
1803
+ browser_click: async (a) => {
1804
+ await pages.click(str(a.selector, ""));
1805
+ return observe();
1806
+ },
1807
+ browser_type: async (a) => {
1808
+ await pages.type(str(a.selector, ""), String(a.text ?? ""));
1809
+ return { ok: true, url: browser.scrub(browser.url) };
1810
+ },
1811
+ browser_press: async (a) => {
1812
+ await browser.press(str(a.key, "Enter"));
1813
+ return observe();
1814
+ },
1815
+ browser_scroll: async (a) => {
1816
+ await browser.scroll(typeof a.dy === "number" ? a.dy : 600);
1817
+ return { ok: true, url: browser.scrub(browser.url) };
1818
+ },
1819
+ browser_screenshot: async (a) => ({
1820
+ image_base64: await browser.screenshotBase64(a.full_page === true),
1821
+ url: browser.scrub(browser.url)
1822
+ }),
1823
+ browser_read: async (a) => observe(str(a.selector, "body")),
1824
+ browser_back: async () => {
1825
+ await browser.back();
1826
+ return observe();
1827
+ }
1828
+ };
1829
+ const specs = COMPUTER_USE_SPECS.map((s) => ({ ...s }));
1830
+ return {
1831
+ schemas: specs.map((spec) => schemaFromSignature(spec)),
1832
+ impls: Object.fromEntries(
1833
+ Object.entries(impls).map(([name, impl]) => [
1834
+ name,
1835
+ scrubbingErrors(browser, impl)
1836
+ ])
1837
+ ),
1838
+ specs
1839
+ };
1840
+ }
1841
+ var COMPUTER_USE_SPECS, scrubbingErrors, str;
1842
+ var init_browserTools = __esm({
1843
+ "src/worlds/browserTools.ts"() {
1844
+ "use strict";
1845
+ init_pageState();
1846
+ init_session2();
960
1847
  COMPUTER_USE_SPECS = [
961
1848
  {
962
1849
  name: "browser_goto",
963
1850
  signature: "browser_goto(path=None)",
964
1851
  doc: "Open a page of the world's UI. `path` is a UI path like /customers, a full URL, or omitted for the entry page. Returns the URL and page text."
965
1852
  },
1853
+ {
1854
+ name: "browser_snapshot",
1855
+ signature: "browser_snapshot()",
1856
+ doc: "The page as an accessibility tree, one line per element with its role, name and [ref=e3]. To act on an element, pass `ref=e3` as the selector of browser_click or browser_type. Returns {url, title, snapshot, truncated}."
1857
+ },
966
1858
  {
967
1859
  name: "browser_click",
968
1860
  signature: "browser_click(selector)",
969
- doc: "Click an element by Playwright selector (CSS, `text=Refund`, `role=button[name=Save]`). Returns the page text after the click."
1861
+ doc: "Click an element by `ref=e3` from the last browser_snapshot, or by Playwright selector (CSS, `text=Refund`, `role=button[name=Save]`). Returns the page text after the click."
970
1862
  },
971
1863
  {
972
1864
  name: "browser_type",
973
1865
  signature: "browser_type(selector, text)",
974
- doc: "Replace the value of an input/textarea found by selector with `text`."
1866
+ doc: "Replace the value of an input/textarea, found by `ref=e3` or by selector, with `text`."
975
1867
  },
976
1868
  {
977
1869
  name: "browser_press",
@@ -999,6 +1891,14 @@ var init_browser = __esm({
999
1891
  doc: "Go back one page in history."
1000
1892
  }
1001
1893
  ];
1894
+ scrubbingErrors = (browser, impl) => async (args) => {
1895
+ try {
1896
+ return await impl(args);
1897
+ } catch (error) {
1898
+ browser.scrubError(error);
1899
+ throw error;
1900
+ }
1901
+ };
1002
1902
  str = (v, fallback) => typeof v === "string" && v.length > 0 ? v : fallback;
1003
1903
  }
1004
1904
  });
@@ -1143,13 +2043,12 @@ function isNativePage(page) {
1143
2043
  const mouse = candidate?.mouse;
1144
2044
  return typeof candidate?.context === "function" && NATIVE_METHODS.every((m) => typeof mouse?.[m] === "function");
1145
2045
  }
1146
- var FOCUSED_FIELD_JS, SECRET_FOCUS, DRAG_STEPS, PNG_SIGNATURE, NATIVE_METHODS, Screen;
2046
+ var FOCUSED_FIELD_JS, DRAG_STEPS, PNG_SIGNATURE, NATIVE_METHODS, Screen;
1147
2047
  var init_screen = __esm({
1148
2048
  "src/worlds/nativeComputer/screen.ts"() {
1149
2049
  "use strict";
1150
- init_browser();
1151
- FOCUSED_FIELD_JS = "(() => { let e = document.activeElement; const inner = (el) => (el.shadowRoot && el.shadowRoot.activeElement) || (el.contentDocument && el.contentDocument.activeElement); while (e && inner(e)) e = inner(e); if (!e) return ''; if (e.tagName === 'IFRAME' || e.tagName === 'FRAME') return 'frame'; if (!(e.tagName === 'INPUT' || e.tagName === 'TEXTAREA' || e.isContentEditable)) return 'opaque'; return [e.type, e.name, e.id, e.getAttribute('autocomplete')].filter(Boolean).join(' '); })()";
1152
- SECRET_FOCUS = ["password", "frame", "opaque"];
2050
+ init_credentialField();
2051
+ FOCUSED_FIELD_JS = `(() => { let e = document.activeElement; const inner = (el) => (el.shadowRoot && el.shadowRoot.activeElement) || (el.contentDocument && el.contentDocument.activeElement); while (e && inner(e)) e = inner(e); return (${DESCRIBE_FIELD_JS})(e); })()`;
1153
2052
  DRAG_STEPS = 5;
1154
2053
  PNG_SIGNATURE = Buffer.from([
1155
2054
  137,
@@ -1240,7 +2139,7 @@ var init_screen = __esm({
1240
2139
  } catch {
1241
2140
  return true;
1242
2141
  }
1243
- return SECRET_FOCUS.some((prefix) => described.startsWith(prefix)) || SECRET_KEY.test(described);
2142
+ return isCredentialField(described);
1244
2143
  }
1245
2144
  /** CDP renders a clip at the page's device pixel ratio as well as its
1246
2145
  * `scale` (a Retina host doubles it), so a capture of the wrong width
@@ -1471,11 +2370,11 @@ var init_media = __esm({
1471
2370
  status
1472
2371
  );
1473
2372
  }
1474
- async send(method, route, body) {
1475
- const reply = await this.transport.send(method, route, body);
2373
+ async send(method, route2, body) {
2374
+ const reply = await this.transport.send(method, route2, body);
1476
2375
  if (!reply.ok)
1477
2376
  throw new MediaUploadError(
1478
- `${method} ${route} -> ${reply.status}`,
2377
+ `${method} ${route2} -> ${reply.status}`,
1479
2378
  reply.status
1480
2379
  );
1481
2380
  return reply.text ? JSON.parse(reply.text) : {};
@@ -1828,7 +2727,7 @@ function click(button, count) {
1828
2727
  modifiers: modifierChord(raw.text)
1829
2728
  });
1830
2729
  }
1831
- var SCROLL_STEP_PX, NOT_EXECUTED, MAX_ERROR2, SCROLL_DIRECTIONS, MEMBERS, AnthropicComputer, AnthropicComputer20251124;
2730
+ var SCROLL_STEP_PX, NOT_EXECUTED, MAX_ERROR2, SCROLL_DIRECTIONS, IMAGE_PARTS, MEMBERS, AnthropicComputer, AnthropicComputer20251124;
1832
2731
  var init_anthropic = __esm({
1833
2732
  "src/worlds/nativeComputer/anthropic.ts"() {
1834
2733
  "use strict";
@@ -1844,6 +2743,14 @@ var init_anthropic = __esm({
1844
2743
  left: [-1, 0],
1845
2744
  right: [1, 0]
1846
2745
  };
2746
+ IMAGE_PARTS = {
2747
+ 6: (data) => ({ type: "image-data", data, mediaType: "image/png" }),
2748
+ 7: (data) => ({
2749
+ type: "file",
2750
+ mediaType: "image/png",
2751
+ data: { type: "data", data }
2752
+ })
2753
+ };
1847
2754
  MEMBERS = {
1848
2755
  screenshot: () => new ComputerAction("screenshot"),
1849
2756
  zoom: (raw) => new ComputerAction("zoom", {
@@ -1953,15 +2860,17 @@ var init_anthropic = __esm({
1953
2860
  ];
1954
2861
  return [{ type: "text", text: result.text ?? "OK" }];
1955
2862
  }
1956
- /** For `anthropic.tools.computerToolset_20260801({ ...computer.aiSdk() })`
1957
- * (or `computer_20251124` with the legacy kind): `execute` runs one action
1958
- * and returns `{ type: "image", data }` or text; `toModelOutput` turns that
1959
- * into the tool result. Calls run one at a time, and once a call fails the
2863
+ /** For `anthropic.tools.computerToolset_20260801(computer.aiSdk({ version: 7 }))`
2864
+ * (AI SDK 7 only), or `computer_20251124` with the legacy kind (AI SDK 6
2865
+ * and 7): `execute` runs one action and returns `{ type: "image", data }` or
2866
+ * text; `toModelOutput` turns that into the tool result in the part shape
2867
+ * of `options.version`. Calls run one at a time, and once a call fails the
1960
2868
  * rest of that step's calls answer as not executed. */
1961
- aiSdk() {
2869
+ aiSdk(options = {}) {
2870
+ const imagePart = _AnthropicComputer.imagePart(options);
1962
2871
  let failedStep;
1963
- const execute = (input, options) => this.serial(async () => {
1964
- const step = options?.messages?.length;
2872
+ const execute = (input, options2) => this.serial(async () => {
2873
+ const step = options2?.messages?.length;
1965
2874
  if (step !== void 0 && step === failedStep)
1966
2875
  throw new Error(NOT_EXECUTED);
1967
2876
  try {
@@ -1973,7 +2882,7 @@ var init_anthropic = __esm({
1973
2882
  });
1974
2883
  return {
1975
2884
  execute,
1976
- toModelOutput: ({ output }) => _AnthropicComputer.aiSdkModelOutput(output)
2885
+ toModelOutput: ({ output }) => _AnthropicComputer.modelOutput(output, imagePart)
1977
2886
  };
1978
2887
  }
1979
2888
  static aiSdkOutput(result) {
@@ -1981,16 +2890,26 @@ var init_anthropic = __esm({
1981
2890
  return { type: "image", data: result.image.toString("base64") };
1982
2891
  return result.text ?? "OK";
1983
2892
  }
1984
- /** `image-data` is what AI SDK 6's Anthropic provider turns into an image
1985
- * block; AI SDK 7 still accepts it (and converts it to a `file` part). */
1986
- static aiSdkModelOutput(output) {
2893
+ /** A screenshot as the image part of AI SDK `options.version`:
2894
+ * `image-data` for 6 (the default), `file` with `{ type: "data", data }`
2895
+ * for 7. */
2896
+ static aiSdkModelOutput(output, options = {}) {
2897
+ return _AnthropicComputer.modelOutput(
2898
+ output,
2899
+ _AnthropicComputer.imagePart(options)
2900
+ );
2901
+ }
2902
+ static imagePart({
2903
+ version = 6
2904
+ }) {
2905
+ if (Object.hasOwn(IMAGE_PARTS, version)) return IMAGE_PARTS[version];
2906
+ throw new Error(
2907
+ `unsupported AI SDK version ${version}; choose ${Object.keys(IMAGE_PARTS).join(" or ")}`
2908
+ );
2909
+ }
2910
+ static modelOutput(output, imagePart) {
1987
2911
  if (typeof output === "string") return { type: "text", value: output };
1988
- return {
1989
- type: "content",
1990
- value: [
1991
- { type: "image-data", data: output.data, mediaType: "image/png" }
1992
- ]
1993
- };
2912
+ return { type: "content", value: [imagePart(output.data)] };
1994
2913
  }
1995
2914
  envelope(block, content, isError = false) {
1996
2915
  return {
@@ -2398,7 +3317,7 @@ var init_requestLedger = __esm({
2398
3317
  "use strict";
2399
3318
  init_worlds();
2400
3319
  init_sessionContract();
2401
- WORLD_REQUEST_VIAS = ["api", "ui", "tool"];
3320
+ WORLD_REQUEST_VIAS = ["api", "ui", "tool", "webhook", "page"];
2402
3321
  WorldRequestFilterError = class extends Error {
2403
3322
  };
2404
3323
  NOT_RECORDED = "This session's engine records no requests; only hosted World Host sessions do.";
@@ -2907,7 +3826,8 @@ async function openSession(slugOrRef, taskOrOpts = {}, positionalOpts = {}) {
2907
3826
  ...opts.reuseWarm === void 0 ? {} : { reuseWarm: opts.reuseWarm },
2908
3827
  ...opts.surfaces?.length ? { surfaces: opts.surfaces } : {},
2909
3828
  ...opts.browserTier === void 0 ? {} : { browserTier: opts.browserTier },
2910
- ...opts.auth === void 0 ? {} : { auth: opts.auth }
3829
+ ...opts.auth === void 0 ? {} : { auth: opts.auth },
3830
+ ...opts.worldState === void 0 ? {} : { worldState: opts.worldState }
2911
3831
  }
2912
3832
  );
2913
3833
  return new WorldSession(state2.sessionId, state2, options);
@@ -2994,6 +3914,7 @@ var init_session2 = __esm({
2994
3914
  "use strict";
2995
3915
  init_worlds();
2996
3916
  init_browser();
3917
+ init_browserTools();
2997
3918
  init_nativeComputer();
2998
3919
  init_sessionContract();
2999
3920
  init_toolSchema();
@@ -3059,6 +3980,9 @@ var init_session2 = __esm({
3059
3980
  get versionId() {
3060
3981
  return this.current.versionId;
3061
3982
  }
3983
+ get worldState() {
3984
+ return this.current.worldState ?? null;
3985
+ }
3062
3986
  /** Whether the session answered ready as of the last state read (the open,
3063
3987
  * a `status()`, or the poll inside `ready()`); no request is made. */
3064
3988
  get isReady() {
@@ -3330,13 +4254,13 @@ var init_session2 = __esm({
3330
4254
  WorldRequestQuery.parse({ cursor: opts.cursor, limit: opts.limit ?? REQUEST_LOG_PAGE_MAX })
3331
4255
  );
3332
4256
  }
3333
- page(route, limit, cursor) {
4257
+ page(route2, limit, cursor) {
3334
4258
  const query = new URLSearchParams({ limit: String(limit) });
3335
4259
  if (cursor) query.set("cursor", cursor);
3336
4260
  return apiRequest(
3337
4261
  this.options,
3338
4262
  "GET",
3339
- `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/${route}?${query.toString()}`
4263
+ `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/${route2}?${query.toString()}`
3340
4264
  );
3341
4265
  }
3342
4266
  /** The session's call log, oldest first: every tool call, seed, reset,
@@ -3428,6 +4352,7 @@ var init_session2 = __esm({
3428
4352
  "surfaces",
3429
4353
  "browserTier",
3430
4354
  "auth",
4355
+ "worldState",
3431
4356
  "options"
3432
4357
  ]);
3433
4358
  isOpenSessionOptions = (value) => typeof value === "object" && value !== null && Object.keys(value).every((key) => OPEN_SESSION_OPTION_KEYS.has(key));
@@ -3671,7 +4596,8 @@ async function openTask(ref, opts = {}) {
3671
4596
  task,
3672
4597
  ...opts.reuseWarm === void 0 ? {} : { reuseWarm: opts.reuseWarm },
3673
4598
  ...opts.surfaces?.length ? { surfaces: opts.surfaces } : {},
3674
- ...opts.browserTier === void 0 ? {} : { browserTier: opts.browserTier }
4599
+ ...opts.browserTier === void 0 ? {} : { browserTier: opts.browserTier },
4600
+ ...opts.worldStates === void 0 ? {} : { worldStates: opts.worldStates }
3675
4601
  }
3676
4602
  );
3677
4603
  return fromResponse(answer, options);
@@ -3929,16 +4855,22 @@ var init_evals = __esm({
3929
4855
  "src/worlds/evals.ts"() {
3930
4856
  "use strict";
3931
4857
  init_worlds();
4858
+ init_personalToken();
4859
+ init_platformEndpoint();
3932
4860
  init_transport();
3933
4861
  EVALUATIONS = "/api/public/benchmark-containers/evaluations";
3934
- GatewayEvalsClient = class {
4862
+ GatewayEvalsClient = class _GatewayEvalsClient {
3935
4863
  constructor(options = {}, retry = RetryPolicy.FILING) {
3936
4864
  this.options = options;
3937
4865
  this.retry = retry;
4866
+ _GatewayEvalsClient.refuseToken(options);
3938
4867
  }
3939
4868
  options;
3940
4869
  retry;
3941
4870
  keyed = /* @__PURE__ */ new Set();
4871
+ static refuseToken(options) {
4872
+ if (platformEndpoint(options)?.token) throw new PersonalTokenRefused(TOKEN_FILING);
4873
+ }
3942
4874
  async createEvaluation(versionId, opts = {}) {
3943
4875
  const body = { versionId };
3944
4876
  if (opts.model !== void 0) body.model = opts.model;
@@ -5004,7 +5936,7 @@ var require_package = __commonJS({
5004
5936
  "package.json"(exports, module) {
5005
5937
  module.exports = {
5006
5938
  name: "@withgateway/sdk",
5007
- version: "0.4.0",
5939
+ version: "0.9.1",
5008
5940
  description: "Gateway SDK for TypeScript - A/B experiments, tracing, and observability",
5009
5941
  main: "./dist/index.js",
5010
5942
  module: "./dist/index.mjs",
@@ -5085,6 +6017,11 @@ var require_package = __commonJS({
5085
6017
  import: "./dist/hooks/index.mjs",
5086
6018
  require: "./dist/hooks/index.js"
5087
6019
  },
6020
+ "./agents": {
6021
+ types: "./dist/agents/index.d.ts",
6022
+ import: "./dist/agents/index.mjs",
6023
+ require: "./dist/agents/index.js"
6024
+ },
5088
6025
  "./cli": {
5089
6026
  types: "./dist/cli.d.ts",
5090
6027
  import: "./dist/cli.mjs",
@@ -5693,6 +6630,7 @@ var init_taskTracing = __esm({
5693
6630
  "use strict";
5694
6631
  init_prerequisites();
5695
6632
  init_platformEndpoint();
6633
+ init_personalToken();
5696
6634
  HOST_WITH_AUTHORITY = /^[a-z][a-z0-9+.-]*:\/\/[^/\\?#@\s]+(\/|$)/i;
5697
6635
  TRACING_HELD_ELSEWHERE = "Tracing in this process already sends spans to another destination or with other keys (an earlier run, or the agent's own tracing.init()), so this run's spans would not reach its own project.";
5698
6636
  TaskTracing = class _TaskTracing {
@@ -5704,8 +6642,9 @@ var init_taskTracing = __esm({
5704
6642
  static target = null;
5705
6643
  async start(requested, options) {
5706
6644
  if (!requested) return false;
5707
- const endpoint = platformEndpoint(options);
6645
+ let endpoint = null;
5708
6646
  try {
6647
+ endpoint = platformEndpoint(options);
5709
6648
  await this.initOnce(_TaskTracing.config(endpoint));
5710
6649
  return true;
5711
6650
  } catch (error) {
@@ -5727,6 +6666,7 @@ var init_taskTracing = __esm({
5727
6666
  }
5728
6667
  static config(endpoint) {
5729
6668
  if (!endpoint) throw new Error(GATEWAY_KEYS_MISSING);
6669
+ if (endpoint.token) throw new Error(TOKEN_KEYS_ONLY);
5730
6670
  return { ...endpoint, endpoint: _TaskTracing.destination(endpoint) };
5731
6671
  }
5732
6672
  // B1: a saved login's keys go to their own host only. The redirect is compared as text, never parsed:
@@ -5757,7 +6697,9 @@ Pass --no-trace (trace: false) to run untraced without this warning.`
5757
6697
  static reason(error, endpoint) {
5758
6698
  if (OpenTelemetryMissing.explains(error)) return new OpenTelemetryMissing().message;
5759
6699
  const message = error instanceof Error ? error.message : String(error);
5760
- const keys = endpoint ? [endpoint.publicKey, endpoint.secretKey] : [];
6700
+ const keys = [endpoint?.publicKey, endpoint?.secretKey, endpoint?.token?.value].filter(
6701
+ (key) => Boolean(key)
6702
+ );
5761
6703
  return keys.reduce((text2, key) => text2.split(key).join("[redacted]"), message);
5762
6704
  }
5763
6705
  };
@@ -5804,13 +6746,15 @@ async function refuseUnreadTools(live) {
5804
6746
  }
5805
6747
  }
5806
6748
  async function runTask(ref, agent, opts) {
5807
- const runId = `wtr-${randomBytes(6).toString("hex")}`;
5808
6749
  const options = opts.options ?? {};
6750
+ if (opts.file !== false) GatewayEvalsClient.refuseToken(options);
6751
+ const runId = `wtr-${randomBytes(6).toString("hex")}`;
5809
6752
  const opening = new TaskOpening(
5810
6753
  openTask(ref, {
5811
6754
  surfaces: opts.surfaces,
5812
6755
  reuseWarm: opts.reuseWarm,
5813
6756
  browserTier: opts.browserTier,
6757
+ worldStates: opts.worldStates,
5814
6758
  options
5815
6759
  }).then(async (live) => {
5816
6760
  await refuseUnreadTools(live);
@@ -6090,6 +7034,7 @@ var init_checkoutProvenance = __esm({
6090
7034
  // src/worlds/setRun.ts
6091
7035
  async function runSet(datasetId, agent, opts) {
6092
7036
  const options = opts.options ?? {};
7037
+ GatewayEvalsClient.refuseToken(options);
6093
7038
  const git = opts.git === void 0 ? CheckoutProvenance.read() : opts.git;
6094
7039
  const opened = await apiRequest(options, "POST", SET_RUNS, {
6095
7040
  datasetId,
@@ -6105,6 +7050,7 @@ var init_setRun = __esm({
6105
7050
  "use strict";
6106
7051
  init_worlds();
6107
7052
  init_checkoutProvenance();
7053
+ init_evals();
6108
7054
  init_runSignals();
6109
7055
  init_taskRun();
6110
7056
  SET_RUNS = "/api/public/set-runs";
@@ -6279,6 +7225,112 @@ var init_requestLog = __esm({
6279
7225
  }
6280
7226
  });
6281
7227
 
7228
+ // src/worlds/webhooks.ts
7229
+ async function listWebhooks(options, sessionId, page = {}) {
7230
+ const query = new URLSearchParams({
7231
+ after: String(page.after ?? 0),
7232
+ limit: String(page.limit ?? WORLD_WEBHOOK_PAGE_MAX),
7233
+ tail: String(page.tail ?? false)
7234
+ });
7235
+ if (page.epoch) query.set("epoch", page.epoch);
7236
+ return apiRequest(options, "GET", `${route(sessionId)}?${query.toString()}`);
7237
+ }
7238
+ var WORLD_WEBHOOK_PAGE_MAX, FORWARD_TIMEOUT_MS, ERROR_CHARS, route, WorldWebhookForwarder;
7239
+ var init_webhooks = __esm({
7240
+ "src/worlds/webhooks.ts"() {
7241
+ "use strict";
7242
+ init_worlds();
7243
+ WORLD_WEBHOOK_PAGE_MAX = 100;
7244
+ FORWARD_TIMEOUT_MS = 1e4;
7245
+ ERROR_CHARS = 500;
7246
+ route = (sessionId) => `/api/public/world-sessions/${encodeURIComponent(sessionId)}/webhooks`;
7247
+ WorldWebhookForwarder = class {
7248
+ constructor(options, sessionId, forwardTo, opts = {}) {
7249
+ this.options = options;
7250
+ this.sessionId = sessionId;
7251
+ this.forwardTo = forwardTo;
7252
+ this.send = opts.fetch ?? fetch;
7253
+ }
7254
+ options;
7255
+ sessionId;
7256
+ forwardTo;
7257
+ after = 0;
7258
+ epoch = null;
7259
+ answers = [];
7260
+ send;
7261
+ get cursor() {
7262
+ return this.after;
7263
+ }
7264
+ /** Where forwarding begins: the deliveries the session still holds (`replay`), or only those it sends from now. */
7265
+ async start(replay) {
7266
+ if (replay) return null;
7267
+ const page = await this.poll([], { tail: true, limit: 1 });
7268
+ this.follow(page);
7269
+ return page;
7270
+ }
7271
+ /** One poll: the answers held so far sent, the next page forwarded. A poll that fails keeps its answers for the next. */
7272
+ async round() {
7273
+ const page = await this.withAnswers((answers) => this.poll(answers));
7274
+ const forwarded = [];
7275
+ for (const delivery of page.deliveries) {
7276
+ const answer = await this.forward(delivery);
7277
+ this.answers.push(answer);
7278
+ forwarded.push({ delivery, answer });
7279
+ }
7280
+ this.follow(page);
7281
+ return { page, forwarded };
7282
+ }
7283
+ /** Sends the answers still held; the cursor stays, so a delivery this poll returns is forwarded by the next round. */
7284
+ async settle() {
7285
+ if (this.answers.length === 0) return 0;
7286
+ const page = await this.withAnswers((answers) => this.poll(answers, { limit: 1 }));
7287
+ return page.answered;
7288
+ }
7289
+ follow(page) {
7290
+ this.after = page.next;
7291
+ this.epoch = page.epoch;
7292
+ }
7293
+ async withAnswers(poll) {
7294
+ const answers = this.answers.splice(0, WORLD_WEBHOOK_PAGE_MAX);
7295
+ try {
7296
+ return await poll(answers);
7297
+ } catch (error) {
7298
+ this.answers.unshift(...answers);
7299
+ throw error;
7300
+ }
7301
+ }
7302
+ poll(answers, opts = {}) {
7303
+ return apiRequest(this.options, "POST", route(this.sessionId), {
7304
+ after: this.after,
7305
+ epoch: this.epoch,
7306
+ tail: opts.tail ?? false,
7307
+ limit: opts.limit ?? WORLD_WEBHOOK_PAGE_MAX,
7308
+ subscriptions: false,
7309
+ answers
7310
+ });
7311
+ }
7312
+ async forward(delivery) {
7313
+ const started = Date.now();
7314
+ try {
7315
+ const reply = await this.send(this.forwardTo, {
7316
+ method: "POST",
7317
+ headers: delivery.headers,
7318
+ body: delivery.payload,
7319
+ redirect: "manual",
7320
+ signal: AbortSignal.timeout(FORWARD_TIMEOUT_MS)
7321
+ });
7322
+ await reply.arrayBuffer().catch(() => void 0);
7323
+ if (reply.status < 100 || reply.status > 599) throw new Error("the receiver answered an invalid HTTP status");
7324
+ return { id: delivery.id, status: reply.status, durationMs: Date.now() - started, error: null };
7325
+ } catch (error) {
7326
+ const message = error instanceof Error ? error.message : String(error);
7327
+ return { id: delivery.id, status: 0, durationMs: Date.now() - started, error: message.slice(0, ERROR_CHARS) };
7328
+ }
7329
+ }
7330
+ };
7331
+ }
7332
+ });
7333
+
6282
7334
  // src/worlds/checkoutTarget.ts
6283
7335
  import * as fs2 from "fs";
6284
7336
  import * as path3 from "path";
@@ -6386,19 +7438,20 @@ var init_checkoutTarget = __esm({
6386
7438
  import { createHash as createHash3 } from "crypto";
6387
7439
  import * as fs3 from "fs";
6388
7440
  import * as path4 from "path";
6389
- var WORLD_MANIFEST, API_BUNDLE_MANIFEST, BUNDLED_WORLD_PREFIX, CONNECTOR_SPEC, PYPROJECT, BENCHMARK_CONFIG, WORLD_SCHEMA_MARKERS, WORLD_ROOT_MARKERS, BROAD_ROOT_MARKERS, SKIPPED_DIRS, V1_DEP, V1_IMPORT, V1_TASKSET, HARBOR_TASK, skippedDir, byCodePoint, WorldDir;
7441
+ var WORLD_MANIFEST, API_BUNDLE_MANIFEST, BUNDLE_MANIFEST, BUNDLED_WORLD_PREFIX, CONNECTOR_SPEC, PYPROJECT, BENCHMARK_CONFIG, WORLD_SCHEMA_MARKERS, WORLD_ROOT_MARKERS, BROAD_ROOT_MARKERS, SKIPPED_DIRS, V1_DEP, V1_IMPORT, V1_TASKSET, HARBOR_TASK, skippedDir, byCodePoint, WorldDir;
6390
7442
  var init_worldDir = __esm({
6391
7443
  "src/worlds/worldDir.ts"() {
6392
7444
  "use strict";
6393
7445
  WORLD_MANIFEST = "gateway-env.toml";
6394
7446
  API_BUNDLE_MANIFEST = "gateway-api-world.toml";
7447
+ BUNDLE_MANIFEST = "gateway-bundle.toml";
6395
7448
  BUNDLED_WORLD_PREFIX = "server/world/";
6396
7449
  CONNECTOR_SPEC = "connector.toml";
6397
7450
  PYPROJECT = "pyproject.toml";
6398
7451
  BENCHMARK_CONFIG = "benchmark.json";
6399
7452
  WORLD_SCHEMA_MARKERS = ["schema/world.json", "schema/runtime.json", "schema/lock.json"];
6400
7453
  WORLD_ROOT_MARKERS = [CONNECTOR_SPEC, ...WORLD_SCHEMA_MARKERS];
6401
- BROAD_ROOT_MARKERS = [WORLD_MANIFEST, API_BUNDLE_MANIFEST, BENCHMARK_CONFIG];
7454
+ BROAD_ROOT_MARKERS = [WORLD_MANIFEST, API_BUNDLE_MANIFEST, BENCHMARK_CONFIG, BUNDLE_MANIFEST];
6402
7455
  SKIPPED_DIRS = /* @__PURE__ */ new Set(["dist", "build", "outputs", "__pycache__", "node_modules"]);
6403
7456
  V1_DEP = /["']verifiers\s*(?:\[[^\]]*\])?\s*(?:>=|~=|==|>)\s*(?:0\.(?:[2-9]\d*|[1-9]\d+)|[1-9]\d*)/;
6404
7457
  V1_IMPORT = /^\s*(?:from\s+verifiers\.v1\s+import\b|from\s+verifiers\s+import\s+v1\b|import\s+verifiers\.v1\b)/m;
@@ -6419,7 +7472,6 @@ var init_worldDir = __esm({
6419
7472
  const bundled = present(API_BUNDLE_MANIFEST) && WORLD_ROOT_MARKERS.some((m) => present(BUNDLED_WORLD_PREFIX + m));
6420
7473
  return new _WorldDir(dir, bundled ? BUNDLED_WORLD_PREFIX : "");
6421
7474
  }
6422
- // ── Files ──────────────────────────────────────────────────────────────
6423
7475
  has(rel) {
6424
7476
  return fs3.existsSync(path4.join(this.dir, rel));
6425
7477
  }
@@ -6430,15 +7482,9 @@ var init_worldDir = __esm({
6430
7482
  return null;
6431
7483
  }
6432
7484
  }
6433
- /** A path under the authored world's root. */
6434
7485
  worldPath(rel) {
6435
7486
  return this.worldRoot + rel;
6436
7487
  }
6437
- /** Every regular file the archive rules keep (`_archive.py`: no hidden,
6438
- * dist, build, outputs, pycache, node_modules or egg-info directories), as
6439
- * sorted relpaths. Root files enter only when a Gateway manifest or
6440
- * benchmark.json widens the root, or they are README.md, pyproject.toml or
6441
- * Python. */
6442
7488
  get archivePaths() {
6443
7489
  if (this.pathsMemo) return this.pathsMemo;
6444
7490
  const broad = BROAD_ROOT_MARKERS.some((m) => this.has(m));
@@ -6457,11 +7503,6 @@ var init_worldDir = __esm({
6457
7503
  walk("");
6458
7504
  return this.pathsMemo = out.sort(byCodePoint);
6459
7505
  }
6460
- /** What the archive rules leave out, collapsed to the entry that decided
6461
- * it: a pruned directory counts its files once, a dropped root file is
6462
- * named. Dot entries (`.git/`, `.gateway/`, `.gitignore`) are the one
6463
- * universal convention and stay unreported. `push` prints the rest so
6464
- * nothing disappears silently. */
6465
7506
  get exclusions() {
6466
7507
  const kept = new Set(this.archivePaths);
6467
7508
  const out = [];
@@ -6484,14 +7525,11 @@ var init_worldDir = __esm({
6484
7525
  }
6485
7526
  return out;
6486
7527
  }
6487
- /** A root `.gitignore` is present: the Python SDK honours it when
6488
- * collecting, this package does not reimplement gitignore. */
7528
+ /** The Python SDK honours a root `.gitignore` when collecting; this package does not reimplement gitignore. */
6489
7529
  get hasRootGitignore() {
6490
7530
  return this.has(".gitignore");
6491
7531
  }
6492
- /** SHA-256 over `utf8("file:" + relpath)` + bytes per archive path in
6493
- * sorted order: the version's identity, byte-compatible with
6494
- * `_archive.compute_content_hash` and Prime Intellect. */
7532
+ /** The version's identity, byte-compatible with the Python SDK's `compute_content_hash` and Prime Intellect's hub. */
6495
7533
  get contentHash() {
6496
7534
  const hasher = createHash3("sha256");
6497
7535
  for (const rel of this.archivePaths) {
@@ -6500,18 +7538,18 @@ var init_worldDir = __esm({
6500
7538
  }
6501
7539
  return hasher.digest("hex");
6502
7540
  }
6503
- // ── Markers ────────────────────────────────────────────────────────────
6504
7541
  get isApiBundle() {
6505
7542
  return this.has(API_BUNDLE_MANIFEST);
6506
7543
  }
7544
+ get isWorldBundle() {
7545
+ return this.has(BUNDLE_MANIFEST);
7546
+ }
6507
7547
  get hasManifest() {
6508
7548
  return this.has(this.worldPath(WORLD_MANIFEST));
6509
7549
  }
6510
7550
  get hasSchemaMarker() {
6511
7551
  return WORLD_SCHEMA_MARKERS.some((m) => this.has(this.worldPath(m)));
6512
7552
  }
6513
- /** Harbor task dirs, relative to the tree: `tasks/<name>` when a `tasks/`
6514
- * dir holds them, else the root `<name>` dirs. */
6515
7553
  taskDirs() {
6516
7554
  const names = /* @__PURE__ */ new Set();
6517
7555
  for (const rel of this.archivePaths) {
@@ -6521,8 +7559,6 @@ var init_worldDir = __esm({
6521
7559
  const under = [...names].filter((n) => n.startsWith("tasks/"));
6522
7560
  return (under.length ? under : [...names]).sort();
6523
7561
  }
6524
- /** The Python package of a verifiers tree (`<pkg>/__init__.py` or
6525
- * `src/<pkg>/__init__.py`), or null. */
6526
7562
  pythonPackage() {
6527
7563
  if (!this.has(PYPROJECT)) return null;
6528
7564
  for (const base of ["", "src/"]) {
@@ -6534,8 +7570,6 @@ var init_worldDir = __esm({
6534
7570
  }
6535
7571
  return null;
6536
7572
  }
6537
- /** The package targets the `verifiers.v1` API: read from the root
6538
- * pyproject and every archived Python module. */
6539
7573
  get isVerifiersV1() {
6540
7574
  for (const rel of this.archivePaths) {
6541
7575
  if (rel !== PYPROJECT && !rel.endsWith(".py")) continue;
@@ -6546,11 +7580,9 @@ var init_worldDir = __esm({
6546
7580
  }
6547
7581
  return false;
6548
7582
  }
6549
- // ── The answer ─────────────────────────────────────────────────────────
6550
- /** The runner's kind (`detect_env_kind`): api / mock-tools win over
6551
- * everything, a harbor task tree next, then the verifiers API version. */
6552
7583
  get kind() {
6553
7584
  if (this.isApiBundle) return "api";
7585
+ if (this.isWorldBundle) return "bundle";
6554
7586
  if (this.has(WORLD_MANIFEST)) return "mock-tools";
6555
7587
  if (this.taskDirs().length) return "harbor";
6556
7588
  return this.isVerifiersV1 ? "verifiers-v1" : "verifiers";
@@ -6892,8 +7924,7 @@ async function push(dir, opts = {}) {
6892
7924
  const metadata = {
6893
7925
  ...opts.name !== void 0 ? { name: opts.name } : {},
6894
7926
  ...opts.description !== void 0 ? { description: opts.description } : {},
6895
- ...opts.tags !== void 0 ? { tags: opts.tags } : {},
6896
- ...opts.visibility ? { visibility: opts.visibility } : {}
7927
+ ...opts.tags !== void 0 ? { tags: opts.tags } : {}
6897
7928
  };
6898
7929
  const resolve7 = await apiRequest(
6899
7930
  options,
@@ -7421,7 +8452,7 @@ var init_sandbox = __esm({
7421
8452
  /**
7422
8453
  * `{ slug, ref? }` opens a READY version; `{ new, from }` opens a sandbox on
7423
8454
  * a world that does not exist yet (409 `world_exists` if the slug is taken,
7424
- * 400 naming the shipped templates if `from` is unknown). Its first commit
8455
+ * 400 naming the official templates if `from` is unknown). Its first commit
7425
8456
  * creates the world on `main`.
7426
8457
  */
7427
8458
  open(target) {
@@ -8066,6 +9097,7 @@ var CliError;
8066
9097
  var init_router = __esm({
8067
9098
  "src/cli/router.ts"() {
8068
9099
  "use strict";
9100
+ init_personalToken();
8069
9101
  CliError = class extends Error {
8070
9102
  constructor(message, exitCode = 2) {
8071
9103
  super(message);
@@ -8080,25 +9112,69 @@ var init_router = __esm({
8080
9112
  import * as fs6 from "fs";
8081
9113
  import * as os from "os";
8082
9114
  import * as path7 from "path";
8083
- async function api(creds, method, route, body, init2 = {}) {
8084
- const reply = await new PlatformTransport(creds).send(method, route, body, init2);
8085
- if (!reply.ok) throw new ApiError2(reply.status, method, route, reply.text);
9115
+ function configPath() {
9116
+ return path7.join(process.env.GATEWAY_CONFIG_DIR || path7.join(os.homedir(), ".gateway"), "config.json");
9117
+ }
9118
+ function readConfig() {
9119
+ let stored;
9120
+ try {
9121
+ stored = JSON.parse(fs6.readFileSync(configPath(), "utf8"));
9122
+ } catch {
9123
+ return {};
9124
+ }
9125
+ const record = stored ?? {};
9126
+ return Object.fromEntries(STORED_FIELDS.filter((f) => typeof record[f] === "string").map((f) => [f, record[f]]));
9127
+ }
9128
+ function personalToken(request = {}) {
9129
+ try {
9130
+ return PersonalToken.fromEnv(process.env, request);
9131
+ } catch (error) {
9132
+ if (error instanceof PersonalTokenRefused) throw new CliError(error.message);
9133
+ throw error;
9134
+ }
9135
+ }
9136
+ function resolveCredentials(hostFlag, secretKeyFlag) {
9137
+ const token = personalToken({ host: hostFlag || void 0, keys: Boolean(secretKeyFlag) });
9138
+ if (token) return { host: token.host, publicKey: "", secretKey: "", token };
9139
+ const stored = readConfig();
9140
+ const explicitHost = (hostFlag || process.env.GATEWAY_HOST || "").replace(/\/+$/, "");
9141
+ const host = explicitHost || (stored.host ?? "").replace(/\/+$/, "");
9142
+ if (!host)
9143
+ throw new CredentialsMissing(
9144
+ "Host not configured. Pass --host, set GATEWAY_HOST, or run `gateway auth login`."
9145
+ );
9146
+ const login = host === (stored.host ?? "").replace(/\/+$/, "") ? stored : {};
9147
+ const publicKey = process.env.GATEWAY_PUBLIC_KEY || login.public_key || "";
9148
+ const secretKey = secretKeyFlag || process.env.GATEWAY_SECRET_KEY || process.env.GATEWAY_API_KEY || login.api_key || "";
9149
+ if (!publicKey || !secretKey)
9150
+ throw new CredentialsMissing(
9151
+ "API key not configured. Set GATEWAY_PUBLIC_KEY and GATEWAY_SECRET_KEY, or run `gateway auth login`."
9152
+ );
9153
+ return { host, publicKey, secretKey };
9154
+ }
9155
+ async function api(creds, method, route2, body, init2 = {}) {
9156
+ const reply = await new PlatformTransport(creds).send(method, route2, body, init2);
9157
+ if (!reply.ok) throw new ApiError2(reply.status, method, route2, reply.text);
8086
9158
  return reply.text ? JSON.parse(reply.text) : {};
8087
9159
  }
8088
- var ApiError2;
9160
+ var STORED_FIELDS, CredentialsMissing, ApiError2;
8089
9161
  var init_config = __esm({
8090
9162
  "src/cli/config.ts"() {
8091
9163
  "use strict";
8092
9164
  init_router();
8093
9165
  init_worlds();
9166
+ init_personalToken();
8094
9167
  init_transport();
9168
+ STORED_FIELDS = ["host", "public_key", "api_key"];
9169
+ CredentialsMissing = class extends CliError {
9170
+ };
8095
9171
  ApiError2 = class extends CliError {
8096
- constructor(status, method, route, text2) {
9172
+ constructor(status, method, route2, text2) {
8097
9173
  const body = parseErrorBody(text2, status);
8098
- super(`${method} ${route} -> ${status}: ${body.detail}`, 1);
9174
+ super(`${method} ${route2} -> ${status}: ${body.detail}`, 1);
8099
9175
  this.status = status;
8100
9176
  this.method = method;
8101
- this.route = route;
9177
+ this.route = route2;
8102
9178
  this.text = text2;
8103
9179
  this.code = body.code;
8104
9180
  }
@@ -8111,8 +9187,37 @@ var init_config = __esm({
8111
9187
  }
8112
9188
  });
8113
9189
 
9190
+ // src/worlds/isolatedPython.ts
9191
+ import { spawnSync } from "child_process";
9192
+ function isolatedPython(python, args, timeout) {
9193
+ return spawnSync(python, ["-I", ...args], { encoding: "utf8", timeout, env: PersonalToken.scrubbed(process.env) });
9194
+ }
9195
+ var init_isolatedPython = __esm({
9196
+ "src/worlds/isolatedPython.ts"() {
9197
+ "use strict";
9198
+ init_personalToken();
9199
+ }
9200
+ });
9201
+
8114
9202
  // src/cli/runtime/local.ts
8115
- import { spawn, spawnSync } from "child_process";
9203
+ var local_exports = {};
9204
+ __export(local_exports, {
9205
+ MIN_PYTHON_LABEL: () => MIN_PYTHON_LABEL,
9206
+ assertPortFree: () => assertPortFree,
9207
+ credentialsForRuntime: () => credentialsForRuntime,
9208
+ findPython: () => findPython,
9209
+ localBridge: () => localBridge,
9210
+ localModule: () => localModule,
9211
+ localPythonHasYaml: () => localPythonHasYaml,
9212
+ localRuntime: () => localRuntime,
9213
+ localRuntimeReason: () => localRuntimeReason,
9214
+ portOwner: () => portOwner,
9215
+ pythonAdvice: () => pythonAdvice,
9216
+ resetPythonCache: () => resetPythonCache,
9217
+ runtimeMode: () => runtimeMode,
9218
+ runtimeRoot: () => runtimeRoot
9219
+ });
9220
+ import { spawn, spawnSync as spawnSync2 } from "child_process";
8116
9221
  import * as fs7 from "fs";
8117
9222
  import * as net from "net";
8118
9223
  import * as path8 from "path";
@@ -8152,12 +9257,12 @@ function runtimeRoot() {
8152
9257
  return root;
8153
9258
  return null;
8154
9259
  }
9260
+ function resetPythonCache() {
9261
+ pythonCache = void 0;
9262
+ pythonProbes = [];
9263
+ }
8155
9264
  function probeVersion(name) {
8156
- const probe = spawnSync(
8157
- name,
8158
- ["-c", "import sys;print(sys.version_info[0],sys.version_info[1])"],
8159
- { encoding: "utf8", timeout: 1e4 }
8160
- );
9265
+ const probe = isolatedPython(name, ["-c", "import sys;print(sys.version_info[0],sys.version_info[1])"], 1e4);
8161
9266
  if (probe.status !== 0) return null;
8162
9267
  const [major, minor] = probe.stdout.trim().split(/\s+/).map(Number);
8163
9268
  return Number.isInteger(major) && Number.isInteger(minor) ? `${major}.${minor}` : null;
@@ -8167,7 +9272,7 @@ function atLeastMinimum(version) {
8167
9272
  return major > MIN_PYTHON[0] || major === MIN_PYTHON[0] && minor >= MIN_PYTHON[1];
8168
9273
  }
8169
9274
  function uvPython() {
8170
- const found = spawnSync("uv", UV_FIND, { encoding: "utf8", timeout: 1e4 });
9275
+ const found = spawnSync2("uv", UV_FIND, { encoding: "utf8", timeout: 1e4, env: PersonalToken.scrubbed(process.env) });
8171
9276
  if (found.status !== 0) return null;
8172
9277
  const line = found.stdout.trim().split(/\r?\n/)[0] ?? "";
8173
9278
  return line || null;
@@ -8226,7 +9331,7 @@ function localRuntime() {
8226
9331
  return { python, root };
8227
9332
  }
8228
9333
  function localPythonHasYaml(python) {
8229
- return spawnSync(python, ["-c", "import yaml"], { timeout: 1e4 }).status === 0;
9334
+ return isolatedPython(python, ["-c", "import yaml"], 1e4).status === 0;
8230
9335
  }
8231
9336
  async function localBridge(request, local, opts = {}) {
8232
9337
  const input = JSON.stringify(request);
@@ -8287,12 +9392,88 @@ async function localBridge(request, local, opts = {}) {
8287
9392
  child.stdin.end(input);
8288
9393
  });
8289
9394
  }
8290
- var MIN_PYTHON, MIN_PYTHON_LABEL, DIAGNOSTIC_TAIL, FORWARDED_ENV, BRIDGE_BOOTSTRAP, pythonCache, pythonProbes, PYTHON_CANDIDATES, UV_FIND;
9395
+ function portOwner(port) {
9396
+ const found = spawnSync2("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-Fpc"], {
9397
+ encoding: "utf8",
9398
+ timeout: 5e3
9399
+ });
9400
+ if (found.error || found.status !== 0) return null;
9401
+ let pid = null;
9402
+ let command2 = null;
9403
+ for (const line of found.stdout.split("\n")) {
9404
+ if (line.startsWith("p") && pid === null) pid = line.slice(1);
9405
+ else if (line.startsWith("c") && pid !== null && command2 === null) command2 = line.slice(1);
9406
+ }
9407
+ if (pid === null) return null;
9408
+ return `pid ${pid}${command2 ? ` (${command2})` : ""}`;
9409
+ }
9410
+ async function assertPortFree(port, host = "127.0.0.1") {
9411
+ const taken = await new Promise((resolve7) => {
9412
+ const probe = net.createServer();
9413
+ probe.once("error", () => resolve7(true));
9414
+ probe.listen(port, host, () => probe.close(() => resolve7(false)));
9415
+ });
9416
+ if (!taken) return;
9417
+ const owner = portOwner(port);
9418
+ throw new CliError(
9419
+ `port ${port} on ${host} is already in use${owner ? ` by ${owner}` : ""}; nothing was served there \u2014 pass another --port, or stop that server first`,
9420
+ 1
9421
+ );
9422
+ }
9423
+ async function localModule(argv, local, opts = {}) {
9424
+ return await new Promise((resolve7, reject) => {
9425
+ const child = spawn(
9426
+ local.python,
9427
+ ["-B", "-c", MODULE_BOOTSTRAP, local.root, ...argv],
9428
+ {
9429
+ stdio: "inherit",
9430
+ cwd: opts.cwd,
9431
+ env: { ...PersonalToken.scrubbed(process.env), ...opts.env }
9432
+ }
9433
+ );
9434
+ const forward = (signal) => () => {
9435
+ if (child.exitCode === null && child.signalCode === null) child.kill(signal);
9436
+ };
9437
+ const handlers = [
9438
+ ["SIGINT", forward("SIGINT")],
9439
+ ["SIGTERM", forward("SIGTERM")],
9440
+ ["SIGHUP", forward("SIGHUP")]
9441
+ ];
9442
+ for (const [signal, handler] of handlers) process.on(signal, handler);
9443
+ const release = () => {
9444
+ for (const [signal, handler] of handlers) process.off(signal, handler);
9445
+ };
9446
+ child.on("error", (error) => {
9447
+ release();
9448
+ reject(
9449
+ new CliError(
9450
+ `local runtime could not start (${local.python}): ${error.message}`,
9451
+ 1
9452
+ )
9453
+ );
9454
+ });
9455
+ child.on("close", (code, signal) => {
9456
+ release();
9457
+ resolve7(code ?? (signal ? 130 : 1));
9458
+ });
9459
+ });
9460
+ }
9461
+ function credentialsForRuntime(hostFlag) {
9462
+ try {
9463
+ return resolveCredentials(hostFlag);
9464
+ } catch (error) {
9465
+ if (error instanceof CliError && localRuntime()) return null;
9466
+ throw error;
9467
+ }
9468
+ }
9469
+ var MIN_PYTHON, MIN_PYTHON_LABEL, DIAGNOSTIC_TAIL, FORWARDED_ENV, BRIDGE_BOOTSTRAP, MODULE_BOOTSTRAP, pythonCache, pythonProbes, PYTHON_CANDIDATES, UV_FIND;
8291
9470
  var init_local = __esm({
8292
9471
  "src/cli/runtime/local.ts"() {
8293
9472
  "use strict";
8294
9473
  init_router();
8295
9474
  init_config();
9475
+ init_isolatedPython();
9476
+ init_personalToken();
8296
9477
  MIN_PYTHON = [3, 12];
8297
9478
  MIN_PYTHON_LABEL = MIN_PYTHON.join(".");
8298
9479
  DIAGNOSTIC_TAIL = 600;
@@ -8303,6 +9484,13 @@ package=types.ModuleType('gatewaysdk')
8303
9484
  package.__path__=[os.path.join(root,'gatewaysdk')]
8304
9485
  sys.modules['gatewaysdk']=package
8305
9486
  runpy.run_module('gatewaysdk.environment.schema.platform',run_name='__main__')`;
9487
+ MODULE_BOOTSTRAP = `import sys,runpy,types,os
9488
+ root=sys.argv[1]
9489
+ package=types.ModuleType('gatewaysdk')
9490
+ package.__path__=[os.path.join(root,'gatewaysdk')]
9491
+ sys.modules['gatewaysdk']=package
9492
+ sys.argv=['gateway worlds']+sys.argv[2:]
9493
+ runpy.run_module('gatewaysdk.environment.schema',run_name='__main__')`;
8306
9494
  pythonProbes = [];
8307
9495
  PYTHON_CANDIDATES = [
8308
9496
  "python3.13",
@@ -8451,8 +9639,8 @@ async function runtime(creds, request, opts = {}) {
8451
9639
  throw new CliError(
8452
9640
  "This needs the schema runtime (the CLI bundles it) or platform credentials (`gateway auth login`). " + localRuntimeReason()
8453
9641
  );
8454
- const route = "/api/public/worlds/runtime";
8455
- const res = await new PlatformTransport(creds).send("POST", route, request, {
9642
+ const route2 = "/api/public/worlds/runtime";
9643
+ const res = await new PlatformTransport(creds).send("POST", route2, request, {
8456
9644
  timeoutMs: opts.timeoutMs ?? RUNTIME_TIMEOUT_MS
8457
9645
  });
8458
9646
  let payload = null;
@@ -8464,8 +9652,8 @@ async function runtime(creds, request, opts = {}) {
8464
9652
  const detail = detailFrom(payload);
8465
9653
  if (detail) throw new BridgeRejected(detail);
8466
9654
  if (!res.ok)
8467
- throw new CliError(`POST ${route} (${request.command}) -> ${res.status}: ${res.text.slice(0, 600)}`, 1);
8468
- if (payload === null) throw new CliError(`POST ${route} (${request.command}) returned non-JSON`, 1);
9655
+ throw new CliError(`POST ${route2} (${request.command}) -> ${res.status}: ${res.text.slice(0, 600)}`, 1);
9656
+ if (payload === null) throw new CliError(`POST ${route2} (${request.command}) returned non-JSON`, 1);
8469
9657
  return payload;
8470
9658
  }
8471
9659
  var MAX_WORLD_FILES, RUNTIME_TIMEOUT_MS, SKIP_DIRS, BridgeRejected, YAML_NAME, YAML_NEEDS_PYYAML, YAML_NOT_ON_PLATFORM, RuntimeRoute;
@@ -9412,14 +10600,23 @@ function toolCallsFromObservations(observations, opts = {}) {
9412
10600
  }
9413
10601
  return out;
9414
10602
  }
10603
+ async function runtimeEndpoint(options) {
10604
+ try {
10605
+ return platformEndpoint(options);
10606
+ } catch (error) {
10607
+ const { localRuntime: localRuntime2 } = await Promise.resolve().then(() => (init_local(), local_exports));
10608
+ if (error instanceof PersonalTokenRefused && localRuntime2()) return null;
10609
+ throw error;
10610
+ }
10611
+ }
9415
10612
  async function ingest(world, records, options = {}) {
9416
10613
  const { ingestLocalToolCalls: ingestLocalToolCalls2, importLocalWorldData: importLocalWorldData2, checkLocalWorldData: checkLocalWorldData2 } = await Promise.resolve().then(() => (init_data(), data_exports));
9417
10614
  if (options.transform !== void 0 && options.map !== void 0) throw new Error("records go through one of transform, map");
9418
10615
  const redact = options.redact ?? "off";
9419
10616
  const mode = options.mode ?? "append";
9420
10617
  const dryRun = Boolean(options.dryRun);
9421
- const creds = platformEndpoint(options);
9422
10618
  const local = fs12.existsSync(world) && fs12.statSync(world).isDirectory();
10619
+ const creds = local ? await runtimeEndpoint(options) : platformEndpoint(options);
9423
10620
  const map = options.map === void 0 ? void 0 : options.map;
9424
10621
  let rows = null;
9425
10622
  let stderr = "";
@@ -9517,6 +10714,7 @@ var init_ingest = __esm({
9517
10714
  "use strict";
9518
10715
  init_worlds();
9519
10716
  init_platformEndpoint();
10717
+ init_personalToken();
9520
10718
  isObject2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
9521
10719
  isoOf = (value) => value instanceof Date ? value.toISOString() : typeof value === "string" ? value : void 0;
9522
10720
  }
@@ -9574,6 +10772,38 @@ var init_editSessions = __esm({
9574
10772
  }
9575
10773
  });
9576
10774
 
10775
+ // src/worlds/states.ts
10776
+ var WORLDS3, refQuery, WorldStateClient;
10777
+ var init_states = __esm({
10778
+ "src/worlds/states.ts"() {
10779
+ "use strict";
10780
+ init_worlds();
10781
+ WORLDS3 = "/api/public/worlds";
10782
+ refQuery = (ref) => ref ? `?${new URLSearchParams({ ref })}` : "";
10783
+ WorldStateClient = class {
10784
+ constructor(options = {}) {
10785
+ this.options = options;
10786
+ }
10787
+ options;
10788
+ list(slug) {
10789
+ return apiRequest(this.options, "GET", `${WORLDS3}/${encodeURIComponent(slug)}/states`);
10790
+ }
10791
+ show(slug, name, ref) {
10792
+ return apiRequest(this.options, "GET", `${WORLDS3}/${encodeURIComponent(slug)}/states/${encodeURIComponent(name)}` + refQuery(ref));
10793
+ }
10794
+ create(slug, input) {
10795
+ return apiRequest(this.options, "POST", `${WORLDS3}/${encodeURIComponent(slug)}/states`, input);
10796
+ }
10797
+ delete(slug, name) {
10798
+ return apiRequest(this.options, "DELETE", `${WORLDS3}/${encodeURIComponent(slug)}/states/${encodeURIComponent(name)}`);
10799
+ }
10800
+ pull(slug, name, ref) {
10801
+ return apiRequest(this.options, "GET", `${WORLDS3}/${encodeURIComponent(slug)}/states/${encodeURIComponent(name)}/pull` + refQuery(ref));
10802
+ }
10803
+ };
10804
+ }
10805
+ });
10806
+
9577
10807
  // src/worlds/dryRun.ts
9578
10808
  var DRY_RUN_KIND, DRY_RUN_AGENT, STATUS_WAIT_CAP_SECONDS, cid, HostedDryRunClient, DryRunOutcome;
9579
10809
  var init_dryRun = __esm({
@@ -9707,9 +10937,14 @@ __export(worlds_exports, {
9707
10937
  OpenAIComputer: () => OpenAIComputer,
9708
10938
  OpenAIPreviewComputer: () => OpenAIPreviewComputer,
9709
10939
  PLATFORM_SESSION_HEADER: () => PLATFORM_SESSION_HEADER,
10940
+ PLATFORM_STREAM_IDLE_MS: () => PLATFORM_STREAM_IDLE_MS,
9710
10941
  PLATFORM_TIMEOUT_DEFAULT_MS: () => PLATFORM_TIMEOUT_DEFAULT_MS,
9711
10942
  PLATFORM_TIMEOUT_ENV: () => PLATFORM_TIMEOUT_ENV,
10943
+ PageObserver: () => PageObserver,
10944
+ PageState: () => PageState,
10945
+ PageStateError: () => PageStateError,
9712
10946
  PendingSafetyChecks: () => PendingSafetyChecks,
10947
+ PlatformStream: () => PlatformStream,
9713
10948
  PlatformTransport: () => PlatformTransport,
9714
10949
  PushSlugConflict: () => PushSlugConflict,
9715
10950
  RECOVER_BUDGET_MS: () => RECOVER_BUDGET_MS,
@@ -9746,6 +10981,7 @@ __export(worlds_exports, {
9746
10981
  VERIFIER_REWARD_PREFIX: () => VERIFIER_REWARD_PREFIX,
9747
10982
  WHITESPACE: () => WHITESPACE,
9748
10983
  WORLD_REQUEST_VIAS: () => WORLD_REQUEST_VIAS,
10984
+ WORLD_WEBHOOK_PAGE_MAX: () => WORLD_WEBHOOK_PAGE_MAX,
9749
10985
  WorldBrowser: () => WorldBrowser,
9750
10986
  WorldCallTooLarge: () => WorldCallTooLarge,
9751
10987
  WorldEditClient: () => WorldEditClient,
@@ -9761,9 +10997,11 @@ __export(worlds_exports, {
9761
10997
  WorldSessionOpenFailed: () => WorldSessionOpenFailed,
9762
10998
  WorldSessionTimeout: () => WorldSessionTimeout,
9763
10999
  WorldSet: () => WorldSet,
11000
+ WorldStateClient: () => WorldStateClient,
9764
11001
  WorldSurfaceUnavailable: () => WorldSurfaceUnavailable,
9765
11002
  WorldTask: () => WorldTask,
9766
11003
  WorldToolsUnread: () => WorldToolsUnread,
11004
+ WorldWebhookForwarder: () => WorldWebhookForwarder,
9767
11005
  WriteTreeFilter: () => WriteTreeFilter,
9768
11006
  aggregateTaskGrade: () => aggregateTaskGrade,
9769
11007
  apiRequest: () => apiRequest,
@@ -9811,6 +11049,7 @@ __export(worlds_exports, {
9811
11049
  listSessions: () => listSessions,
9812
11050
  listTaskSessions: () => listTaskSessions,
9813
11051
  listTasks: () => listTasks,
11052
+ listWebhooks: () => listWebhooks,
9814
11053
  localTreeState: () => localTreeState,
9815
11054
  messageOf: () => messageOf,
9816
11055
  migrateProjectWorlds: () => migrateProjectWorlds,
@@ -9826,6 +11065,7 @@ __export(worlds_exports, {
9826
11065
  parseToolCallRecord: () => parseToolCallRecord,
9827
11066
  parseTransform: () => parseTransform,
9828
11067
  parseWorldTaskRefs: () => parseWorldTaskRefs,
11068
+ platformAuthorization: () => platformAuthorization,
9829
11069
  platformTimeoutMs: () => platformTimeoutMs,
9830
11070
  playwrightKey: () => playwrightKey,
9831
11071
  preserveForm: () => preserveForm,
@@ -9852,6 +11092,7 @@ __export(worlds_exports, {
9852
11092
  runSet: () => runSet,
9853
11093
  runTask: () => runTask,
9854
11094
  schemaFromSignature: () => schemaFromSignature,
11095
+ scrubError: () => scrubError,
9855
11096
  serializeCallBody: () => serializeCallBody,
9856
11097
  sessionToolObservations: () => sessionToolObservations,
9857
11098
  setEnvSecret: () => setEnvSecret,
@@ -9879,43 +11120,8 @@ __export(worlds_exports, {
9879
11120
  worldRequestsUnrecorded: () => worldRequestsUnrecorded,
9880
11121
  writeLocalMeta: () => writeLocalMeta
9881
11122
  });
9882
- function edgeAnswer(text2, status) {
9883
- if (status !== void 0 && status >= 500) return EDGE_ANSWERS[status] ?? EDGE_FAILURE;
9884
- return /^\s*</.test(text2) ? EDGE_PAGE : null;
9885
- }
9886
- function parseErrorBody(text2, status) {
9887
- const raw = { detail: text2.slice(0, DETAIL_LIMIT), code: null };
9888
- let parsed;
9889
- try {
9890
- parsed = JSON.parse(text2);
9891
- } catch {
9892
- return { detail: (edgeAnswer(text2, status) ?? text2).slice(0, DETAIL_LIMIT), code: null };
9893
- }
9894
- if (parsed === null || typeof parsed !== "object") return raw;
9895
- const { message, code, error } = parsed;
9896
- const stableCode = typeof code === "string" ? code : null;
9897
- if (typeof message !== "string") return { ...raw, code: stableCode };
9898
- const fields = invalidFields(error);
9899
- const said = fields ? `${message}: ${fields}` : message;
9900
- if (stableCode === null) return { detail: said.slice(0, DETAIL_LIMIT), code: null };
9901
- return {
9902
- detail: `${said} (${stableCode})`.slice(0, DETAIL_LIMIT),
9903
- code: stableCode
9904
- };
9905
- }
9906
- function invalidFields(error) {
9907
- const issues = Array.isArray(error) ? error : [];
9908
- return issues.filter(
9909
- (issue) => issue !== null && typeof issue === "object" && typeof issue.message === "string"
9910
- ).map((issue) => {
9911
- const path13 = Array.isArray(issue.path) ? issue.path.map(String).join(".") : "";
9912
- return path13 ? `${path13}: ${issue.message}` : issue.message;
9913
- }).join("; ");
9914
- }
9915
11123
  async function apiRequest(options, method, path13, body, init2 = {}) {
9916
- const reply = await new PlatformTransport(requirePlatformEndpoint(options)).send(method, path13, body, init2);
9917
- if (!reply.ok) throw new ApiError(reply.status, method, path13, reply.text);
9918
- return JSON.parse(reply.text);
11124
+ return new PlatformTransport(requirePlatformEndpoint(options)).json(method, path13, body, init2);
9919
11125
  }
9920
11126
  async function setEnvSecret(slug, key, value, options = {}) {
9921
11127
  return apiRequest(
@@ -10090,11 +11296,12 @@ async function resolveWorld(slugRef, slug, ref, pin, options) {
10090
11296
  }
10091
11297
  return world;
10092
11298
  }
10093
- var ApiError, DETAIL_LIMIT, EDGE_ANSWERS, EDGE_FAILURE, EDGE_PAGE, WorldTask, WorldSet;
11299
+ var WorldTask, WorldSet;
10094
11300
  var init_worlds = __esm({
10095
11301
  "src/worlds/index.ts"() {
10096
11302
  init_platformEndpoint();
10097
11303
  init_transport();
11304
+ init_apiError();
10098
11305
  init_transport();
10099
11306
  init_session2();
10100
11307
  init_grade();
@@ -10109,9 +11316,12 @@ var init_worlds = __esm({
10109
11316
  init_checkoutProvenance();
10110
11317
  init_evals();
10111
11318
  init_browser();
11319
+ init_browserTools();
11320
+ init_pageState();
10112
11321
  init_surfaceDescriptor();
10113
11322
  init_requestLog();
10114
11323
  init_requestLedger();
11324
+ init_webhooks();
10115
11325
  init_browserReconnect();
10116
11326
  init_nativeComputer();
10117
11327
  init_hub();
@@ -10124,29 +11334,9 @@ var init_worlds = __esm({
10124
11334
  init_ingest();
10125
11335
  init_sandbox();
10126
11336
  init_editSessions();
11337
+ init_states();
10127
11338
  init_dryRun();
10128
11339
  init_worldNotice();
10129
- ApiError = class extends Error {
10130
- constructor(status, method, path13, text2) {
10131
- const parsed = parseErrorBody(text2, status);
10132
- super(`${method} ${path13} -> ${status}: ${parsed.detail}`);
10133
- this.status = status;
10134
- this.text = text2;
10135
- this.name = "ApiError";
10136
- this.code = parsed.code;
10137
- }
10138
- status;
10139
- text;
10140
- code;
10141
- };
10142
- DETAIL_LIMIT = 600;
10143
- EDGE_ANSWERS = {
10144
- 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.",
10145
- 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.",
10146
- 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."
10147
- };
10148
- 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.";
10149
- 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.";
10150
11340
  WorldTask = class {
10151
11341
  constructor(world, name, variant) {
10152
11342
  this.world = world;
@@ -10255,9 +11445,14 @@ export {
10255
11445
  OpenAIComputer,
10256
11446
  OpenAIPreviewComputer,
10257
11447
  PLATFORM_SESSION_HEADER,
11448
+ PLATFORM_STREAM_IDLE_MS,
10258
11449
  PLATFORM_TIMEOUT_DEFAULT_MS,
10259
11450
  PLATFORM_TIMEOUT_ENV,
11451
+ PageObserver,
11452
+ PageState,
11453
+ PageStateError,
10260
11454
  PendingSafetyChecks,
11455
+ PlatformStream,
10261
11456
  PlatformTransport,
10262
11457
  PushSlugConflict,
10263
11458
  RECOVER_BUDGET_MS,
@@ -10294,6 +11489,7 @@ export {
10294
11489
  VERIFIER_REWARD_PREFIX,
10295
11490
  WHITESPACE,
10296
11491
  WORLD_REQUEST_VIAS,
11492
+ WORLD_WEBHOOK_PAGE_MAX,
10297
11493
  WorldBrowser,
10298
11494
  WorldCallTooLarge,
10299
11495
  WorldEditClient,
@@ -10309,9 +11505,11 @@ export {
10309
11505
  WorldSessionOpenFailed,
10310
11506
  WorldSessionTimeout,
10311
11507
  WorldSet,
11508
+ WorldStateClient,
10312
11509
  WorldSurfaceUnavailable,
10313
11510
  WorldTask,
10314
11511
  WorldToolsUnread,
11512
+ WorldWebhookForwarder,
10315
11513
  WriteTreeFilter,
10316
11514
  aggregateTaskGrade,
10317
11515
  apiRequest,
@@ -10359,6 +11557,7 @@ export {
10359
11557
  listSessions,
10360
11558
  listTaskSessions,
10361
11559
  listTasks,
11560
+ listWebhooks,
10362
11561
  localTreeState,
10363
11562
  messageOf,
10364
11563
  migrateProjectWorlds,
@@ -10374,6 +11573,7 @@ export {
10374
11573
  parseToolCallRecord,
10375
11574
  parseTransform,
10376
11575
  parseWorldTaskRefs,
11576
+ platformAuthorization,
10377
11577
  platformTimeoutMs,
10378
11578
  playwrightKey,
10379
11579
  preserveForm,
@@ -10400,6 +11600,7 @@ export {
10400
11600
  runSet,
10401
11601
  runTask,
10402
11602
  schemaFromSignature,
11603
+ scrubError,
10403
11604
  serializeCallBody,
10404
11605
  sessionToolObservations,
10405
11606
  setEnvSecret,