@withgateway/sdk 0.2.2 → 0.2.4

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 (52) hide show
  1. package/dist/cli.js +11992 -4572
  2. package/dist/cli.js.map +1 -1
  3. package/dist/cli.mjs +11998 -4578
  4. package/dist/cli.mjs.map +1 -1
  5. package/dist/files/index.js +71 -31
  6. package/dist/files/index.js.map +1 -1
  7. package/dist/files/index.mjs +59 -20
  8. package/dist/files/index.mjs.map +1 -1
  9. package/dist/hooks/index.d.mts +1 -0
  10. package/dist/hooks/index.d.ts +1 -0
  11. package/dist/hooks/index.js +4355 -0
  12. package/dist/hooks/index.js.map +1 -0
  13. package/dist/hooks/index.mjs +4243 -0
  14. package/dist/hooks/index.mjs.map +1 -0
  15. package/dist/{index-Dpo-t8iO.d.ts → index-1xnxt0Cc.d.ts} +58 -2
  16. package/dist/index-B0R3IgsV.d.mts +1279 -0
  17. package/dist/index-B0R3IgsV.d.ts +1279 -0
  18. package/dist/{index-B5HUQQDE.d.mts → index-C1wDEwH4.d.mts} +58 -2
  19. package/dist/index.d.mts +4 -3
  20. package/dist/index.d.ts +4 -3
  21. package/dist/index.js +6547 -1552
  22. package/dist/index.js.map +1 -1
  23. package/dist/index.mjs +6636 -1655
  24. package/dist/index.mjs.map +1 -1
  25. package/dist/traces/index.js +60 -20
  26. package/dist/traces/index.js.map +1 -1
  27. package/dist/traces/index.mjs +51 -12
  28. package/dist/traces/index.mjs.map +1 -1
  29. package/dist/tracing/index.d.mts +1 -1
  30. package/dist/tracing/index.d.ts +1 -1
  31. package/dist/tracing/index.js +46 -3
  32. package/dist/tracing/index.js.map +1 -1
  33. package/dist/tracing/index.mjs +41 -2
  34. package/dist/tracing/index.mjs.map +1 -1
  35. package/dist/worlds/index.d.mts +371 -6
  36. package/dist/worlds/index.d.ts +371 -6
  37. package/dist/worlds/index.js +2061 -235
  38. package/dist/worlds/index.js.map +1 -1
  39. package/dist/worlds/index.mjs +2050 -224
  40. package/dist/worlds/index.mjs.map +1 -1
  41. package/package.json +6 -1
  42. package/runtime/gatewaysdk/environment/_materialize.py +3 -3
  43. package/runtime/gatewaysdk/environment/schema/api.py +116 -2
  44. package/runtime/gatewaysdk/environment/schema/compiler.py +14 -0
  45. package/runtime/gatewaysdk/environment/schema/host.py +37 -11
  46. package/runtime/gatewaysdk/environment/schema/skills/hooks-getting-started/SKILL.md +154 -0
  47. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/SKILL.md +5 -5
  48. package/runtime/gatewaysdk/environment/schema/snapshot.py +6 -5
  49. package/runtime/gatewaysdk/environment/schema/tasks.py +12 -2
  50. package/runtime/gatewaysdk/environment/schema/workers.py +30 -13
  51. package/skills/hooks-getting-started/SKILL.md +154 -0
  52. package/skills/worlds-getting-started/SKILL.md +5 -5
@@ -8,6 +8,9 @@ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
8
  var __esm = (fn, res) => function __init() {
9
9
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
10
  };
11
+ var __commonJS = (cb, mod) => function __require() {
12
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
13
+ };
11
14
  var __export = (target, all) => {
12
15
  for (var name in all)
13
16
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -38,9 +41,9 @@ function surfaceKinds(s) {
38
41
  if (s.browser) kinds.push("browser");
39
42
  return kinds;
40
43
  }
41
- function uiUrl(ui, path8) {
44
+ function uiUrl(ui, path9) {
42
45
  const base = ui.url.replace(/\/+$/, "");
43
- const rel = path8.startsWith("/") ? path8 : `/${path8}`;
46
+ const rel = path9.startsWith("/") ? path9 : `/${path9}`;
44
47
  if (!ui.token) return base + rel;
45
48
  const [beforeHash, hash] = splitHash(rel);
46
49
  const joiner = beforeHash.includes("?") ? "&" : "?";
@@ -516,6 +519,7 @@ __export(session_exports, {
516
519
  attachSession: () => attachSession,
517
520
  isTaskIdRef: () => isTaskIdRef,
518
521
  isTaskSpec: () => isTaskSpec,
522
+ modelToolName: () => modelToolName,
519
523
  openSession: () => openSession,
520
524
  runSessions: () => runSessions,
521
525
  schemaFromSignature: () => schemaFromSignature,
@@ -573,12 +577,12 @@ function schemaFromSignature(spec) {
573
577
  };
574
578
  }
575
579
  async function attachSession(sessionId, options = {}) {
576
- const state = await apiRequest(
580
+ const state2 = await apiRequest(
577
581
  options,
578
582
  "GET",
579
583
  `/api/public/world-sessions/${encodeURIComponent(sessionId)}`
580
584
  );
581
- return new WorldSession(sessionId, state, options);
585
+ return new WorldSession(sessionId, state2, options);
582
586
  }
583
587
  async function openSession(slugOrRef, taskOrOpts, positionalOpts = {}) {
584
588
  const { task, ...opts } = typeof taskOrOpts === "object" && "task" in taskOrOpts ? taskOrOpts : { task: taskOrOpts, ...positionalOpts };
@@ -596,7 +600,7 @@ async function openSession(slugOrRef, taskOrOpts, positionalOpts = {}) {
596
600
  );
597
601
  const at = slugOrRef.indexOf("@");
598
602
  const slug = at === -1 ? slugOrRef : slugOrRef.slice(0, at);
599
- const state = await apiRequest(
603
+ const state2 = await apiRequest(
600
604
  options,
601
605
  "POST",
602
606
  "/api/public/world-sessions",
@@ -607,7 +611,7 @@ async function openSession(slugOrRef, taskOrOpts, positionalOpts = {}) {
607
611
  ...opts.surfaces?.length ? { surfaces: opts.surfaces } : {}
608
612
  }
609
613
  );
610
- return new WorldSession(state.sessionId, state, options);
614
+ return new WorldSession(state2.sessionId, state2, options);
611
615
  }
612
616
  async function runSessions(opts) {
613
617
  const options = opts.options ?? {};
@@ -800,18 +804,18 @@ var init_session = __esm({
800
804
  }
801
805
  /** The reporter `browser()` uses; exposed for a page you drive yourself. */
802
806
  browserRecorder(agentId) {
803
- const path8 = `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/browser-events`;
807
+ const path9 = `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/browser-events`;
804
808
  const id = agentId ?? process.env.GATEWAY_AGENT_ID ?? `agent-${(0, import_node_crypto.randomUUID)().replace(/-/g, "").slice(0, 8)}`;
805
809
  return new BrowserActionRecorder(
806
810
  async (events) => {
807
- await apiRequest(this.options, "POST", path8, { events });
811
+ await apiRequest(this.options, "POST", path9, { events });
808
812
  },
809
813
  id,
810
814
  {
811
815
  // Continue this agent's timeline where the platform has it, so the
812
816
  // same id reopened later never re-numbers from zero.
813
817
  resumeFrom: async () => {
814
- const summary = await apiRequest(this.options, "GET", path8);
818
+ const summary = await apiRequest(this.options, "GET", path9);
815
819
  return summary.agents.find((a) => a.agentId === id)?.nextSeq ?? 0;
816
820
  }
817
821
  }
@@ -844,15 +848,15 @@ var init_session = __esm({
844
848
  async ready(opts = {}) {
845
849
  const deadline = Date.now() + (opts.timeoutMs ?? READY_TIMEOUT_MS);
846
850
  for (; ; ) {
847
- const state = await this.status();
848
- if (state.ready) return state;
849
- if (state.state === "FAILED" || state.state === "STOPPED")
851
+ const state2 = await this.status();
852
+ if (state2.ready) return state2;
853
+ if (state2.state === "FAILED" || state2.state === "STOPPED")
850
854
  throw new WorldSessionCallError(
851
- `World session ${state.state.toLowerCase()} before it was ready.`
855
+ `World session ${state2.state.toLowerCase()} before it was ready.`
852
856
  );
853
857
  if (Date.now() > deadline)
854
858
  throw new WorldSessionTimeout(
855
- `World session still ${state.state} after ${Math.round((opts.timeoutMs ?? READY_TIMEOUT_MS) / 1e3)}s.`
859
+ `World session still ${state2.state} after ${Math.round((opts.timeoutMs ?? READY_TIMEOUT_MS) / 1e3)}s.`
856
860
  );
857
861
  await sleep(READY_POLL_MS);
858
862
  }
@@ -928,10 +932,12 @@ var init_session = __esm({
928
932
  * A rubric grade is finalized by the platform's judge, not the container:
929
933
  * the platform answers the enqueue with `pending: true`, and this waits on
930
934
  * the judge's budget (15 min) instead of a call's. `timeoutMs` overrides
931
- * either. */
935
+ * either. `report` is the agent's own account of what it did and found,
936
+ * handed to the judge as its claim beside the evidence (the state and the
937
+ * calls); assertions and python graders ignore it. */
932
938
  async grade(opts = {}) {
933
939
  const raw = await this.exchange(
934
- { kind: "grade" },
940
+ opts.report !== void 0 ? { kind: "grade", report: opts.report } : { kind: "grade" },
935
941
  opts.timeoutMs
936
942
  );
937
943
  const record = raw && typeof raw === "object" ? raw : {};
@@ -1040,97 +1046,1879 @@ var init_session = __esm({
1040
1046
  };
1041
1047
  return task;
1042
1048
  }
1043
- /**
1044
- * End the session. `keepWarm` hands the container back to the pool instead
1045
- * of tearing it down, so the next session for the same task starts warm —
1046
- * the pooled instance still obeys the fleet's idle TTL and pinning.
1047
- */
1048
- async close(opts = {}) {
1049
- return apiRequest(
1050
- this.options,
1051
- "DELETE",
1052
- `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}`,
1053
- { keepWarm: opts.keepWarm ?? false }
1054
- );
1049
+ /**
1050
+ * End the session. `keepWarm` hands the container back to the pool instead
1051
+ * of tearing it down, so the next session for the same task starts warm —
1052
+ * the pooled instance still obeys the fleet's idle TTL and pinning.
1053
+ */
1054
+ async close(opts = {}) {
1055
+ return apiRequest(
1056
+ this.options,
1057
+ "DELETE",
1058
+ `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}`,
1059
+ { keepWarm: opts.keepWarm ?? false }
1060
+ );
1061
+ }
1062
+ };
1063
+ }
1064
+ });
1065
+
1066
+ // src/worlds/tasks.ts
1067
+ async function createTask(input, options = {}) {
1068
+ return apiRequest(
1069
+ options,
1070
+ "POST",
1071
+ TASKS,
1072
+ compact({
1073
+ spec: input.spec,
1074
+ name: input.name,
1075
+ world: input.world,
1076
+ message: input.message
1077
+ })
1078
+ );
1079
+ }
1080
+ async function updateTask(taskId, input, options = {}) {
1081
+ if (input.spec === void 0 && input.name === void 0 && input.world === void 0)
1082
+ throw new Error("updateTask: nothing to update \u2014 pass spec, name or world");
1083
+ return apiRequest(
1084
+ options,
1085
+ "PATCH",
1086
+ taskRoute(taskId),
1087
+ compact({
1088
+ spec: input.spec,
1089
+ name: input.name,
1090
+ world: input.world,
1091
+ message: input.message
1092
+ })
1093
+ );
1094
+ }
1095
+ async function listTasks(filter = {}, options = {}) {
1096
+ const params = new URLSearchParams();
1097
+ if (filter.world) params.set("world", filter.world);
1098
+ if (filter.page !== void 0) params.set("page", String(filter.page));
1099
+ if (filter.limit !== void 0) params.set("limit", String(filter.limit));
1100
+ for (const [key, value] of Object.entries(filter.metadata ?? {}))
1101
+ params.set(`metadata.${key}`, value);
1102
+ const query = params.toString();
1103
+ return apiRequest(
1104
+ options,
1105
+ "GET",
1106
+ query ? `${TASKS}?${query}` : TASKS
1107
+ );
1108
+ }
1109
+ async function getTask(taskId, opts = {}, options = {}) {
1110
+ const query = opts.version === void 0 ? "" : `?version=${String(opts.version)}`;
1111
+ return apiRequest(
1112
+ options,
1113
+ "GET",
1114
+ `${taskRoute(taskId)}${query}`
1115
+ );
1116
+ }
1117
+ async function deleteTask(taskId, options = {}) {
1118
+ return apiRequest(options, "DELETE", taskRoute(taskId));
1119
+ }
1120
+ async function validateTask(taskId, target = {}, options = {}) {
1121
+ return apiRequest(
1122
+ options,
1123
+ "POST",
1124
+ `${taskRoute(taskId)}/validate`,
1125
+ compact({
1126
+ version: target.version,
1127
+ slug: target.slug,
1128
+ versionId: target.versionId
1129
+ })
1130
+ );
1131
+ }
1132
+ var TASKS, taskRoute, compact;
1133
+ var init_tasks = __esm({
1134
+ "src/worlds/tasks.ts"() {
1135
+ "use strict";
1136
+ init_worlds();
1137
+ TASKS = "/api/public/world-tasks";
1138
+ taskRoute = (id) => `${TASKS}/${encodeURIComponent(id)}`;
1139
+ compact = (body) => Object.fromEntries(Object.entries(body).filter(([, v]) => v !== void 0));
1140
+ }
1141
+ });
1142
+
1143
+ // src/worlds/taskSessions.ts
1144
+ function aggregateTaskGrade(worlds) {
1145
+ const rewards = {};
1146
+ const ungraded = [];
1147
+ const graded = [];
1148
+ for (const [alias, grade] of Object.entries(worlds)) {
1149
+ if (typeof grade.reward === "number") {
1150
+ rewards[alias] = grade.reward;
1151
+ graded.push(grade.reward);
1152
+ } else ungraded.push(alias);
1153
+ for (const [key, value] of Object.entries(grade.rewards))
1154
+ rewards[`${alias}.${key}`] = value;
1155
+ }
1156
+ const reward = graded.length > 0 ? graded.reduce((a, b) => a + b, 0) / graded.length : null;
1157
+ return { reward, rewards, worlds, ungraded };
1158
+ }
1159
+ function fromResponse(answer, options) {
1160
+ const sessions = {};
1161
+ const worlds = {};
1162
+ for (const [alias, state2] of Object.entries(answer.sessions)) {
1163
+ sessions[alias] = new WorldSession(state2.sessionId, state2, options);
1164
+ worlds[alias] = { slug: state2.slug, ref: state2.ref };
1165
+ }
1166
+ return new TaskSessions(
1167
+ answer.taskId,
1168
+ answer.taskVersion,
1169
+ answer.name,
1170
+ answer.instruction,
1171
+ sessions,
1172
+ worlds,
1173
+ answer.hash ?? null
1174
+ );
1175
+ }
1176
+ async function openTask(ref, opts = {}) {
1177
+ const options = opts.options ?? {};
1178
+ const task = typeof ref === "string" ? {
1179
+ id: ref,
1180
+ ...opts.version !== void 0 ? { version: opts.version } : {}
1181
+ } : isTaskIdRef(ref) && opts.version !== void 0 ? { ...ref, version: opts.version } : ref;
1182
+ if (isTaskIdRef(task) ? !task.id : !task.instruction)
1183
+ throw new Error(
1184
+ "openTask needs a task: a stored task id, { id, version? } or a spec with worlds"
1185
+ );
1186
+ if (!isTaskIdRef(task) && !task.worlds)
1187
+ throw new Error(
1188
+ "openTask needs a spec that names its worlds; a single-world spec opens with openSession"
1189
+ );
1190
+ const answer = await apiRequest(
1191
+ options,
1192
+ "POST",
1193
+ TASK_SESSIONS,
1194
+ {
1195
+ task,
1196
+ ...opts.reuseWarm === void 0 ? {} : { reuseWarm: opts.reuseWarm },
1197
+ ...opts.surfaces?.length ? { surfaces: opts.surfaces } : {}
1198
+ }
1199
+ );
1200
+ return fromResponse(answer, options);
1201
+ }
1202
+ async function listTaskSessions(taskId, options = {}) {
1203
+ const answer = await apiRequest(options, "GET", `${TASK_SESSIONS}?taskId=${encodeURIComponent(taskId)}`);
1204
+ return answer.sessions;
1205
+ }
1206
+ async function attachTask(taskId, options = {}) {
1207
+ const live = await listTaskSessions(taskId, options);
1208
+ if (live.length === 0)
1209
+ throw new Error(
1210
+ `task ${taskId} has no live sessions; run \`task up\` first`
1211
+ );
1212
+ const byAlias = /* @__PURE__ */ new Map();
1213
+ for (const session of live) {
1214
+ const alias = session.alias ?? session.sessionId;
1215
+ byAlias.set(alias, [...byAlias.get(alias) ?? [], session]);
1216
+ }
1217
+ const doubled = [...byAlias.entries()].filter(([, rows]) => rows.length > 1);
1218
+ if (doubled.length > 0)
1219
+ throw new Error(
1220
+ `task ${taskId} has more than one live session for ${doubled.map(
1221
+ ([alias, rows]) => `'${alias}' (${rows.map((r) => r.sessionId).join(", ")})`
1222
+ ).join(", ")}; pass the manifest from \`task up\`, or close the extras`
1223
+ );
1224
+ return attachManifest(
1225
+ {
1226
+ taskId,
1227
+ taskVersion: live[0].taskVersion,
1228
+ name: null,
1229
+ instruction: null,
1230
+ sessions: Object.fromEntries(
1231
+ [...byAlias.entries()].map(([alias, [row]]) => [
1232
+ alias,
1233
+ {
1234
+ slug: row.slug ?? "",
1235
+ ref: null,
1236
+ versionId: row.versionId,
1237
+ sessionId: row.sessionId,
1238
+ ready: row.ready,
1239
+ state: row.state,
1240
+ surfaces: ["tools"]
1241
+ }
1242
+ ])
1243
+ )
1244
+ },
1245
+ options
1246
+ );
1247
+ }
1248
+ async function attachManifest(manifest, options = {}) {
1249
+ const entries = await Promise.all(
1250
+ Object.entries(manifest.sessions).map(
1251
+ async ([alias, entry]) => [alias, await attachSession(entry.sessionId, options)]
1252
+ )
1253
+ );
1254
+ const sessions = Object.fromEntries(entries);
1255
+ const instruction = manifest.instruction ?? entries[0]?.[1].instruction ?? null;
1256
+ return new TaskSessions(
1257
+ manifest.taskId,
1258
+ manifest.taskVersion,
1259
+ manifest.name,
1260
+ instruction,
1261
+ sessions,
1262
+ Object.fromEntries(
1263
+ Object.entries(manifest.sessions).map(([alias, entry]) => [
1264
+ alias,
1265
+ { slug: entry.slug, ref: entry.ref }
1266
+ ])
1267
+ )
1268
+ );
1269
+ }
1270
+ function isTaskManifest(value) {
1271
+ return typeof value === "object" && value !== null && !Array.isArray(value) && typeof value.sessions === "object" && value.sessions !== null && !("instruction" in value && "worlds" in value);
1272
+ }
1273
+ var TASK_SESSIONS, manifestSession, TaskSessions;
1274
+ var init_taskSessions = __esm({
1275
+ "src/worlds/taskSessions.ts"() {
1276
+ "use strict";
1277
+ init_worlds();
1278
+ init_browser();
1279
+ init_session();
1280
+ TASK_SESSIONS = "/api/public/world-task-sessions";
1281
+ manifestSession = (s, state2, world) => ({
1282
+ slug: world.slug,
1283
+ ref: world.ref,
1284
+ versionId: state2.versionId,
1285
+ sessionId: state2.sessionId,
1286
+ ready: state2.ready,
1287
+ state: state2.state,
1288
+ surfaces: surfaceKinds(s),
1289
+ ...s.api ? {
1290
+ api: { url: s.api.url, ...s.api.token ? { token: s.api.token } : {} }
1291
+ } : {},
1292
+ ...s.ui ? {
1293
+ ui: {
1294
+ url: s.ui.url,
1295
+ entry: uiEntryUrl(s.ui),
1296
+ apiPath: s.ui.apiPath ?? null
1297
+ }
1298
+ } : {},
1299
+ ...s.browser ? { browser: { wsUrl: s.browser.wsUrl, viewport: s.browser.viewport } } : {}
1300
+ });
1301
+ TaskSessions = class {
1302
+ constructor(taskId, taskVersion, name, instruction, sessions, worlds, hash = null) {
1303
+ this.taskId = taskId;
1304
+ this.taskVersion = taskVersion;
1305
+ this.name = name;
1306
+ this.instruction = instruction;
1307
+ this.sessions = sessions;
1308
+ this.worlds = worlds;
1309
+ this.hash = hash;
1310
+ }
1311
+ /** This alias's `{slug, ref}` as recorded at open/attach — the world a
1312
+ * `TaskRun` filing needs to name, without exposing the whole map. */
1313
+ worldRef(alias) {
1314
+ return this.worlds[alias] ?? { slug: "", ref: null };
1315
+ }
1316
+ /** The aliases, in the spec's order. */
1317
+ get aliases() {
1318
+ return Object.keys(this.sessions);
1319
+ }
1320
+ /** The alias's session, or a clear error naming the aliases there are. */
1321
+ session(alias) {
1322
+ const session = this.sessions[alias];
1323
+ if (!session)
1324
+ throw new Error(
1325
+ `task has no world '${alias}'; its worlds are ${this.aliases.join(", ")}`
1326
+ );
1327
+ return session;
1328
+ }
1329
+ async each(fn) {
1330
+ const entries = await Promise.all(
1331
+ Object.entries(this.sessions).map(
1332
+ async ([alias, session]) => [alias, await fn(session, alias)]
1333
+ )
1334
+ );
1335
+ return Object.fromEntries(entries);
1336
+ }
1337
+ /** Wait until every world answers ready. A world that never does throws
1338
+ * `WorldSessionTimeout` naming it; the others are left up. */
1339
+ async ready(opts = {}) {
1340
+ await this.each((session) => session.ready(opts));
1341
+ }
1342
+ /** Every world's current state, keyed by alias. */
1343
+ async status() {
1344
+ return this.each((session) => session.status());
1345
+ }
1346
+ /** The manifest: where every world answers, keyed by alias. */
1347
+ async manifest() {
1348
+ const sessions = await this.each(
1349
+ async (session, alias) => manifestSession(
1350
+ await session.surfaces(),
1351
+ {
1352
+ sessionId: session.sessionId,
1353
+ ready: session.isReady,
1354
+ state: (await session.status()).state,
1355
+ versionId: session.versionId
1356
+ },
1357
+ this.worlds[alias]
1358
+ )
1359
+ );
1360
+ return {
1361
+ taskId: this.taskId,
1362
+ taskVersion: this.taskVersion,
1363
+ name: this.name,
1364
+ instruction: this.instruction,
1365
+ sessions
1366
+ };
1367
+ }
1368
+ /** Grade every world and aggregate — see `TaskGrade`. One `report` (the
1369
+ * agent's own account of the whole investigation) goes to every world's
1370
+ * judge; a world graded by assertions or python ignores it. */
1371
+ async grade(opts = {}) {
1372
+ return aggregateTaskGrade(
1373
+ await this.each((session) => session.grade(opts))
1374
+ );
1375
+ }
1376
+ /** Every world's call log, keyed by alias. */
1377
+ async export() {
1378
+ return this.each((session) => session.export());
1379
+ }
1380
+ /** Close every world. Closes are attempted for all of them even when one
1381
+ * fails; the error then names every world that did not close. */
1382
+ async close(opts = {}) {
1383
+ const settled = await Promise.allSettled(
1384
+ Object.entries(this.sessions).map(
1385
+ async ([alias, session]) => [alias, await session.close(opts)]
1386
+ )
1387
+ );
1388
+ const failed = [];
1389
+ const closed = {};
1390
+ settled.forEach((result, i) => {
1391
+ const alias = this.aliases[i];
1392
+ if (result.status === "fulfilled") closed[alias] = result.value[1];
1393
+ else
1394
+ failed.push(
1395
+ `${alias}: ${result.reason instanceof Error ? result.reason.message : String(result.reason)}`
1396
+ );
1397
+ });
1398
+ if (failed.length > 0)
1399
+ throw new Error(
1400
+ `${failed.length} of ${this.aliases.length} worlds did not close \u2014 ${failed.join("; ")}`
1401
+ );
1402
+ return closed;
1403
+ }
1404
+ };
1405
+ }
1406
+ });
1407
+
1408
+ // src/worlds/evals.ts
1409
+ var EVALUATIONS, GatewayEvalsClient;
1410
+ var init_evals = __esm({
1411
+ "src/worlds/evals.ts"() {
1412
+ "use strict";
1413
+ init_worlds();
1414
+ EVALUATIONS = "/api/public/benchmark-containers/evaluations";
1415
+ GatewayEvalsClient = class {
1416
+ constructor(options = {}) {
1417
+ this.options = options;
1418
+ }
1419
+ /** Anchor a new evaluation to `versionId`; returns its id. */
1420
+ async createEvaluation(versionId, opts = {}) {
1421
+ const body = { versionId };
1422
+ if (opts.model !== void 0) body.model = opts.model;
1423
+ if (opts.rolloutsPerExample !== void 0)
1424
+ body.rolloutsPerExample = opts.rolloutsPerExample;
1425
+ if (opts.metadata !== void 0) body.metadata = opts.metadata;
1426
+ const answer = await apiRequest(
1427
+ this.options,
1428
+ "POST",
1429
+ EVALUATIONS,
1430
+ body
1431
+ );
1432
+ return answer.evaluationId;
1433
+ }
1434
+ /** Push one batch of samples; returns how many the platform inserted. */
1435
+ async pushSamples(evaluationId, samples) {
1436
+ const answer = await apiRequest(
1437
+ this.options,
1438
+ "POST",
1439
+ `${EVALUATIONS}/${encodeURIComponent(evaluationId)}/samples`,
1440
+ { samples }
1441
+ );
1442
+ return answer.inserted ?? samples.length;
1443
+ }
1444
+ /** Close the evaluation out; returns its final status. */
1445
+ async finalizeEvaluation(evaluationId, opts = {}) {
1446
+ const body = {
1447
+ status: opts.status ?? "COMPLETED"
1448
+ };
1449
+ if (opts.metrics !== void 0) body.metrics = opts.metrics;
1450
+ const answer = await apiRequest(
1451
+ this.options,
1452
+ "POST",
1453
+ `${EVALUATIONS}/${encodeURIComponent(evaluationId)}/finalize`,
1454
+ body
1455
+ );
1456
+ return answer.status;
1457
+ }
1458
+ };
1459
+ }
1460
+ });
1461
+
1462
+ // src/users/index.ts
1463
+ function parseEvent(payload) {
1464
+ return {
1465
+ id: String(payload.id ?? ""),
1466
+ userId: String(payload.userId ?? ""),
1467
+ event: String(payload.event ?? ""),
1468
+ value: typeof payload.value === "number" ? payload.value : null,
1469
+ metadata: payload.metadata && typeof payload.metadata === "object" && !Array.isArray(payload.metadata) ? payload.metadata : {},
1470
+ traceId: typeof payload.traceId === "string" ? payload.traceId : null,
1471
+ sessionId: typeof payload.sessionId === "string" ? payload.sessionId : null,
1472
+ createdAt: typeof payload.createdAt === "string" ? new Date(payload.createdAt) : /* @__PURE__ */ new Date(0)
1473
+ };
1474
+ }
1475
+ function parseProfile(payload) {
1476
+ return {
1477
+ userId: String(payload.userId ?? ""),
1478
+ displayName: typeof payload.displayName === "string" ? payload.displayName : null,
1479
+ email: typeof payload.email === "string" ? payload.email : null,
1480
+ attributes: parseAttributes(payload.attributes),
1481
+ notes: typeof payload.notes === "string" ? payload.notes : null
1482
+ };
1483
+ }
1484
+ function parseAttributes(value) {
1485
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
1486
+ const attributes = {};
1487
+ for (const [key, entry] of Object.entries(value)) {
1488
+ attributes[key] = String(entry);
1489
+ }
1490
+ return attributes;
1491
+ }
1492
+ function safeJson(value) {
1493
+ try {
1494
+ const parsed = JSON.parse(value);
1495
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
1496
+ } catch {
1497
+ return {};
1498
+ }
1499
+ }
1500
+ var UserProfileError, UsersClient, users;
1501
+ var init_users = __esm({
1502
+ "src/users/index.ts"() {
1503
+ "use strict";
1504
+ UserProfileError = class extends Error {
1505
+ constructor(message, options) {
1506
+ super(message);
1507
+ this.name = "UserProfileError";
1508
+ this.cause = options?.cause;
1509
+ }
1510
+ };
1511
+ UsersClient = class _UsersClient {
1512
+ host;
1513
+ publicKey;
1514
+ secretKey;
1515
+ timeoutSeconds;
1516
+ debug;
1517
+ constructor(config) {
1518
+ this.host = config.host.replace(/\/$/, "");
1519
+ this.publicKey = config.publicKey;
1520
+ this.secretKey = config.secretKey;
1521
+ this.timeoutSeconds = config.timeoutSeconds ?? 15;
1522
+ this.debug = config.debug ?? false;
1523
+ }
1524
+ /** Create a client from GATEWAY_HOST / GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY. */
1525
+ static fromEnv(config = {}) {
1526
+ const host = config.host ?? process.env.GATEWAY_HOST;
1527
+ const publicKey = config.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;
1528
+ const secretKey = config.secretKey ?? process.env.GATEWAY_SECRET_KEY;
1529
+ const missing = [
1530
+ ["host", host],
1531
+ ["publicKey", publicKey],
1532
+ ["secretKey", secretKey]
1533
+ ].filter(([, value]) => !value).map(([name]) => name);
1534
+ if (missing.length > 0) {
1535
+ throw new UserProfileError(
1536
+ `Missing Gateway user-profile configuration: ${missing.join(", ")}`
1537
+ );
1538
+ }
1539
+ return new _UsersClient({
1540
+ ...config,
1541
+ host,
1542
+ publicKey,
1543
+ secretKey
1544
+ });
1545
+ }
1546
+ /** Fetch a user's stored profile. */
1547
+ async get(userId) {
1548
+ return parseProfile(
1549
+ await this.requestJson(
1550
+ "GET",
1551
+ `/api/public/user-profiles/${encodeURIComponent(userId)}`
1552
+ )
1553
+ );
1554
+ }
1555
+ /**
1556
+ * Upsert a user's profile. `attributes` merge with the stored set unless
1557
+ * `merge: false` (which replaces it).
1558
+ */
1559
+ async update(userId, update = {}) {
1560
+ const body = {
1561
+ userId,
1562
+ attributes: update.attributes ?? {},
1563
+ mergeAttributes: update.merge ?? true,
1564
+ ...update.displayName !== void 0 ? { displayName: update.displayName } : {},
1565
+ ...update.email !== void 0 ? { email: update.email } : {},
1566
+ ...update.notes !== void 0 ? { notes: update.notes } : {}
1567
+ };
1568
+ return parseProfile(
1569
+ await this.requestJson("POST", "/api/public/user-profiles", body)
1570
+ );
1571
+ }
1572
+ /**
1573
+ * Record a VALUE EVENT for a user — the per-user ROI stream. `value` is
1574
+ * whatever the event is worth in your terms (minutes saved, revenue…);
1575
+ * Gateway sums it in the hours-saved/ROI rollups, and evals and task-set
1576
+ * replays can assert against the events. Link `traceId`/`sessionId` to tie
1577
+ * the event to the run that produced it.
1578
+ *
1579
+ * @example
1580
+ * ```ts
1581
+ * await client.trackEvent("user-123", "checkout_completed", {
1582
+ * value: 25,
1583
+ * metadata: { cartSize: 3 },
1584
+ * sessionId,
1585
+ * });
1586
+ * ```
1587
+ */
1588
+ async trackEvent(userId, event, options = {}) {
1589
+ const body = {
1590
+ userId,
1591
+ event,
1592
+ metadata: options.metadata ?? {},
1593
+ ...options.value !== void 0 ? { value: options.value } : {},
1594
+ ...options.traceId !== void 0 ? { traceId: options.traceId } : {},
1595
+ ...options.sessionId !== void 0 ? { sessionId: options.sessionId } : {}
1596
+ };
1597
+ return parseEvent(
1598
+ await this.requestJson("POST", "/api/public/user-events", body)
1599
+ );
1600
+ }
1601
+ /** List a project's user events, optionally filtered by user/event/time. */
1602
+ async listEvents(filter = {}) {
1603
+ const params = new URLSearchParams();
1604
+ if (filter.userId) params.set("userId", filter.userId);
1605
+ if (filter.event) params.set("event", filter.event);
1606
+ if (filter.fromTimestamp)
1607
+ params.set("fromTimestamp", filter.fromTimestamp.toISOString());
1608
+ if (filter.toTimestamp)
1609
+ params.set("toTimestamp", filter.toTimestamp.toISOString());
1610
+ if (filter.page) params.set("page", String(filter.page));
1611
+ if (filter.limit) params.set("limit", String(filter.limit));
1612
+ const qs = params.toString();
1613
+ const payload = await this.requestJson(
1614
+ "GET",
1615
+ `/api/public/user-events${qs ? `?${qs}` : ""}`
1616
+ );
1617
+ const rows = Array.isArray(payload.data) ? payload.data : [];
1618
+ const meta = payload.meta && typeof payload.meta === "object" ? payload.meta : {};
1619
+ return {
1620
+ data: rows.map((row) => parseEvent(row)),
1621
+ totalItems: Number(meta.totalItems ?? rows.length)
1622
+ };
1623
+ }
1624
+ async requestJson(method, path9, payload) {
1625
+ let response;
1626
+ try {
1627
+ response = await fetch(`${this.host}${path9}`, {
1628
+ method,
1629
+ headers: {
1630
+ Authorization: this.authHeader(),
1631
+ "Content-Type": "application/json"
1632
+ },
1633
+ ...payload ? { body: JSON.stringify(payload) } : {},
1634
+ signal: AbortSignal.timeout(this.timeoutSeconds * 1e3)
1635
+ });
1636
+ } catch (error) {
1637
+ throw new UserProfileError(
1638
+ `${method} ${path9} failed: ${error instanceof Error ? error.message : String(error)}`,
1639
+ { cause: error }
1640
+ );
1641
+ }
1642
+ const text2 = await response.text();
1643
+ if (!response.ok) {
1644
+ throw new UserProfileError(
1645
+ `${method} ${path9} failed (${response.status}): ${text2.slice(0, 500)}`
1646
+ );
1647
+ }
1648
+ this.log("%s %s -> %s", method, path9, response.status);
1649
+ return safeJson(text2);
1650
+ }
1651
+ authHeader() {
1652
+ return `Basic ${Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(
1653
+ "base64"
1654
+ )}`;
1655
+ }
1656
+ log(message, ...args) {
1657
+ if (this.debug) {
1658
+ console.log(`[gateway.users] ${message}`, ...args);
1659
+ }
1660
+ }
1661
+ };
1662
+ users = {
1663
+ fromEnv: UsersClient.fromEnv
1664
+ };
1665
+ }
1666
+ });
1667
+
1668
+ // src/tracing/identity.ts
1669
+ function resolveUserId() {
1670
+ const contextual = currentUserStorage.getStore();
1671
+ if (contextual) return contextual;
1672
+ const envUser = process.env.GATEWAY_USER_ID?.trim();
1673
+ return envUser ? envUser : void 0;
1674
+ }
1675
+ var import_async_hooks, import_api, USER_ID_ATTRIBUTE, currentUserStorage, IdentitySpanProcessor;
1676
+ var init_identity = __esm({
1677
+ "src/tracing/identity.ts"() {
1678
+ "use strict";
1679
+ import_async_hooks = require("async_hooks");
1680
+ import_api = require("@opentelemetry/api");
1681
+ init_users();
1682
+ USER_ID_ATTRIBUTE = "gateway.user.id";
1683
+ currentUserStorage = new import_async_hooks.AsyncLocalStorage();
1684
+ IdentitySpanProcessor = class {
1685
+ onStart(span, _parentContext) {
1686
+ const userId = resolveUserId();
1687
+ if (userId) {
1688
+ span.setAttribute(USER_ID_ATTRIBUTE, userId);
1689
+ }
1690
+ }
1691
+ onEnd(_span) {
1692
+ }
1693
+ async shutdown() {
1694
+ }
1695
+ async forceFlush() {
1696
+ }
1697
+ };
1698
+ }
1699
+ });
1700
+
1701
+ // src/tracing/session.ts
1702
+ var session_exports2 = {};
1703
+ __export(session_exports2, {
1704
+ SESSION_ID_ATTRIBUTE: () => SESSION_ID_ATTRIBUTE,
1705
+ SessionSpanProcessor: () => SessionSpanProcessor,
1706
+ getAmbientSessionId: () => getAmbientSessionId,
1707
+ withSession: () => withSession
1708
+ });
1709
+ function getAmbientSessionId() {
1710
+ return currentSessionStorage.getStore();
1711
+ }
1712
+ function withSession(sessionId, fn) {
1713
+ return new Promise((resolve6, reject) => {
1714
+ currentSessionStorage.run(sessionId, () => {
1715
+ Promise.resolve().then(fn).then(resolve6, reject);
1716
+ });
1717
+ });
1718
+ }
1719
+ var import_async_hooks2, SESSION_ID_ATTRIBUTE, currentSessionStorage, SessionSpanProcessor;
1720
+ var init_session2 = __esm({
1721
+ "src/tracing/session.ts"() {
1722
+ "use strict";
1723
+ import_async_hooks2 = require("async_hooks");
1724
+ SESSION_ID_ATTRIBUTE = "gateway.session.id";
1725
+ currentSessionStorage = new import_async_hooks2.AsyncLocalStorage();
1726
+ SessionSpanProcessor = class {
1727
+ onStart(span, _parentContext) {
1728
+ const sessionId = getAmbientSessionId();
1729
+ if (sessionId) {
1730
+ span.setAttribute(SESSION_ID_ATTRIBUTE, sessionId);
1731
+ }
1732
+ }
1733
+ onEnd(_span) {
1734
+ }
1735
+ async shutdown() {
1736
+ }
1737
+ async forceFlush() {
1738
+ }
1739
+ };
1740
+ }
1741
+ });
1742
+
1743
+ // src/scores/index.ts
1744
+ function currentTraceId() {
1745
+ try {
1746
+ const span = import_api2.trace.getActiveSpan();
1747
+ if (!span) return void 0;
1748
+ const ctx = span.spanContext();
1749
+ if (!ctx || !(0, import_api2.isSpanContextValid)(ctx)) return void 0;
1750
+ return ctx.traceId;
1751
+ } catch {
1752
+ return void 0;
1753
+ }
1754
+ }
1755
+ function coerceSignalValue(value) {
1756
+ if (typeof value === "boolean") {
1757
+ return { numericValue: value ? 1 : 0, inferredType: "BOOLEAN" };
1758
+ }
1759
+ return { numericValue: value, inferredType: "NUMERIC" };
1760
+ }
1761
+ async function success(name, value = true, options = {}) {
1762
+ let client;
1763
+ try {
1764
+ client = ScoresClient.fromEnv();
1765
+ } catch (error) {
1766
+ console.warn(`[gateway.scores] success '${name}' skipped`, error);
1767
+ return;
1768
+ }
1769
+ await client.success(name, value, options);
1770
+ }
1771
+ var import_api2, SUCCESS_SIGNAL_KEY, SUCCESS_METRIC_NAME_KEY, AGENT_ID_KEY, ScoreError, ScoresClient, scores;
1772
+ var init_scores = __esm({
1773
+ "src/scores/index.ts"() {
1774
+ "use strict";
1775
+ import_api2 = require("@opentelemetry/api");
1776
+ SUCCESS_SIGNAL_KEY = "gateway.success.signal";
1777
+ SUCCESS_METRIC_NAME_KEY = "gateway.success.metricName";
1778
+ AGENT_ID_KEY = "gateway.agent.id";
1779
+ ScoreError = class extends Error {
1780
+ constructor(message, options) {
1781
+ super(message);
1782
+ this.name = "ScoreError";
1783
+ this.cause = options?.cause;
1784
+ }
1785
+ };
1786
+ ScoresClient = class _ScoresClient {
1787
+ host;
1788
+ publicKey;
1789
+ secretKey;
1790
+ timeoutSeconds;
1791
+ debug;
1792
+ constructor(config) {
1793
+ this.host = config.host.replace(/\/$/, "");
1794
+ this.publicKey = config.publicKey;
1795
+ this.secretKey = config.secretKey;
1796
+ this.timeoutSeconds = config.timeoutSeconds ?? 15;
1797
+ this.debug = config.debug ?? false;
1798
+ }
1799
+ /** Create a client from GATEWAY_HOST / GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY. */
1800
+ static fromEnv(config = {}) {
1801
+ const host = config.host ?? process.env.GATEWAY_HOST;
1802
+ const publicKey = config.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;
1803
+ const secretKey = config.secretKey ?? process.env.GATEWAY_SECRET_KEY;
1804
+ const missing = [
1805
+ ["host", host],
1806
+ ["publicKey", publicKey],
1807
+ ["secretKey", secretKey]
1808
+ ].filter(([, value]) => !value).map(([name]) => name);
1809
+ if (missing.length > 0) {
1810
+ throw new ScoreError(
1811
+ `Missing Gateway scores configuration: ${missing.join(", ")}`
1812
+ );
1813
+ }
1814
+ return new _ScoresClient({
1815
+ ...config,
1816
+ host,
1817
+ publicKey,
1818
+ secretKey
1819
+ });
1820
+ }
1821
+ /**
1822
+ * Post a score, throwing {@link ScoreError} on any failure. Builds the exact
1823
+ * `POST /api/public/scores` body the Python SDK sends: exactly one of
1824
+ * `sessionId` / `traceId` (+ optional `observationId`) / `datasetRunId`.
1825
+ * When no target is provided, the active OTel trace id is used; if none is
1826
+ * available the call is a no-op (returns without posting), matching Python.
1827
+ */
1828
+ async postScore(name, value, options = {}) {
1829
+ const body = this.buildScoreBody(name, value, options);
1830
+ if (!body) {
1831
+ this.log(
1832
+ "score '%s' dropped: no sessionId, traceId or datasetRunId available",
1833
+ name
1834
+ );
1835
+ return;
1836
+ }
1837
+ await this.request("POST", "/api/public/scores", body);
1838
+ }
1839
+ /**
1840
+ * Build the score request body, or null when no target can be resolved.
1841
+ * Split out so it is unit-testable and shared by score()/success().
1842
+ */
1843
+ buildScoreBody(name, value, options = {}) {
1844
+ const traceId = options.traceId ?? currentTraceId();
1845
+ const target = {};
1846
+ if (options.sessionId) {
1847
+ target.sessionId = options.sessionId;
1848
+ } else if (options.datasetRunId) {
1849
+ target.datasetRunId = options.datasetRunId;
1850
+ } else if (traceId) {
1851
+ target.traceId = traceId;
1852
+ if (options.observationId) target.observationId = options.observationId;
1853
+ } else {
1854
+ return null;
1855
+ }
1856
+ const metadata = {
1857
+ source: "gatewaysdk",
1858
+ ...options.metadata ?? {}
1859
+ };
1860
+ return {
1861
+ name,
1862
+ value,
1863
+ dataType: options.dataType ?? "NUMERIC",
1864
+ environment: options.environment ?? "default",
1865
+ ...options.comment ? { comment: options.comment } : {},
1866
+ metadata,
1867
+ ...target
1868
+ };
1869
+ }
1870
+ /**
1871
+ * Post a score, FAIL-SOFT: warns and resolves on any failure so a broken
1872
+ * transport never throws into (or rejects out of) the caller.
1873
+ */
1874
+ async score(name, value, options = {}) {
1875
+ try {
1876
+ await this.postScore(name, value, options);
1877
+ } catch (error) {
1878
+ this.warn(`score '${name}' failed`, error);
1879
+ }
1880
+ }
1881
+ /**
1882
+ * Emit a SUCCESS SIGNAL that feeds a Gateway Success Metric — a score tagged
1883
+ * with `gateway.success.signal` + `gateway.success.metricName` (and the agent
1884
+ * identity when `agentId` is set). A boolean `value` records a 1/0 BOOLEAN
1885
+ * score (pass/fail); a number records a NUMERIC score. FAIL-SOFT.
1886
+ *
1887
+ * The metadata shape matches the Python SDK's `Run.success()` exactly, so the
1888
+ * platform's Success Metrics aggregation counts signals from either SDK
1889
+ * without change.
1890
+ *
1891
+ * @example
1892
+ * ```ts
1893
+ * await scores.success("resolved_ticket", true, { agentId: "support-triage", sessionId });
1894
+ * await scores.success("handle_time_s", 42, { agentId: "support-triage", sessionId });
1895
+ * ```
1896
+ */
1897
+ async success(name, value = true, options = {}) {
1898
+ const { numericValue, inferredType } = coerceSignalValue(value);
1899
+ const { agentId, metricName, metadata, dataType, ...rest } = options;
1900
+ const signalMetadata = {
1901
+ ...metadata ?? {},
1902
+ [SUCCESS_SIGNAL_KEY]: true,
1903
+ [SUCCESS_METRIC_NAME_KEY]: metricName ?? name,
1904
+ ...agentId ? { [AGENT_ID_KEY]: agentId } : {}
1905
+ };
1906
+ await this.score(name, numericValue, {
1907
+ ...rest,
1908
+ dataType: dataType ?? inferredType,
1909
+ metadata: signalMetadata
1910
+ });
1911
+ }
1912
+ async request(method, path9, payload) {
1913
+ let response;
1914
+ try {
1915
+ response = await fetch(`${this.host}${path9}`, {
1916
+ method,
1917
+ headers: {
1918
+ Authorization: this.authHeader(),
1919
+ "Content-Type": "application/json"
1920
+ },
1921
+ body: JSON.stringify(payload),
1922
+ signal: AbortSignal.timeout(this.timeoutSeconds * 1e3)
1923
+ });
1924
+ } catch (error) {
1925
+ throw new ScoreError(
1926
+ `${method} ${path9} failed: ${error instanceof Error ? error.message : String(error)}`,
1927
+ { cause: error }
1928
+ );
1929
+ }
1930
+ const text2 = await response.text();
1931
+ if (!response.ok) {
1932
+ throw new ScoreError(
1933
+ `${method} ${path9} failed (${response.status}): ${text2.slice(0, 500)}`
1934
+ );
1935
+ }
1936
+ this.log("%s %s -> %s", method, path9, response.status);
1937
+ }
1938
+ authHeader() {
1939
+ return `Basic ${Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(
1940
+ "base64"
1941
+ )}`;
1942
+ }
1943
+ log(message, ...args) {
1944
+ if (this.debug) {
1945
+ console.log(`[gateway.scores] ${message}`, ...args);
1946
+ }
1947
+ }
1948
+ warn(message, ...args) {
1949
+ console.warn(`[gateway.scores] ${message}`, ...args);
1950
+ }
1951
+ };
1952
+ scores = {
1953
+ fromEnv: ScoresClient.fromEnv,
1954
+ success
1955
+ };
1956
+ }
1957
+ });
1958
+
1959
+ // package.json
1960
+ var require_package = __commonJS({
1961
+ "package.json"(exports2, module2) {
1962
+ module2.exports = {
1963
+ name: "@withgateway/sdk",
1964
+ version: "0.2.4",
1965
+ description: "Gateway SDK for TypeScript - A/B experiments, tracing, and observability",
1966
+ main: "./dist/index.js",
1967
+ module: "./dist/index.mjs",
1968
+ types: "./dist/index.d.ts",
1969
+ exports: {
1970
+ ".": {
1971
+ types: "./dist/index.d.ts",
1972
+ import: "./dist/index.mjs",
1973
+ require: "./dist/index.js"
1974
+ },
1975
+ "./experiments": {
1976
+ types: "./dist/experiments/index.d.ts",
1977
+ import: "./dist/experiments/index.mjs",
1978
+ require: "./dist/experiments/index.js"
1979
+ },
1980
+ "./context": {
1981
+ types: "./dist/context/index.d.ts",
1982
+ import: "./dist/context/index.mjs",
1983
+ require: "./dist/context/index.js"
1984
+ },
1985
+ "./memory": {
1986
+ types: "./dist/memory/index.d.ts",
1987
+ import: "./dist/memory/index.mjs",
1988
+ require: "./dist/memory/index.js"
1989
+ },
1990
+ "./personas": {
1991
+ types: "./dist/personas/index.d.ts",
1992
+ import: "./dist/personas/index.mjs",
1993
+ require: "./dist/personas/index.js"
1994
+ },
1995
+ "./replay": {
1996
+ types: "./dist/replay/index.d.ts",
1997
+ import: "./dist/replay/index.mjs",
1998
+ require: "./dist/replay/index.js"
1999
+ },
2000
+ "./sessions": {
2001
+ types: "./dist/sessions/index.d.ts",
2002
+ import: "./dist/sessions/index.mjs",
2003
+ require: "./dist/sessions/index.js"
2004
+ },
2005
+ "./tracing": {
2006
+ types: "./dist/tracing/index.d.ts",
2007
+ import: "./dist/tracing/index.mjs",
2008
+ require: "./dist/tracing/index.js"
2009
+ },
2010
+ "./security": {
2011
+ types: "./dist/security/index.d.ts",
2012
+ import: "./dist/security/index.mjs",
2013
+ require: "./dist/security/index.js"
2014
+ },
2015
+ "./users": {
2016
+ types: "./dist/users/index.d.ts",
2017
+ import: "./dist/users/index.mjs",
2018
+ require: "./dist/users/index.js"
2019
+ },
2020
+ "./scores": {
2021
+ types: "./dist/scores/index.d.ts",
2022
+ import: "./dist/scores/index.mjs",
2023
+ require: "./dist/scores/index.js"
2024
+ },
2025
+ "./worlds": {
2026
+ types: "./dist/worlds/index.d.ts",
2027
+ import: "./dist/worlds/index.mjs",
2028
+ require: "./dist/worlds/index.js"
2029
+ },
2030
+ "./files": {
2031
+ types: "./dist/files/index.d.ts",
2032
+ import: "./dist/files/index.mjs",
2033
+ require: "./dist/files/index.js"
2034
+ },
2035
+ "./traces": {
2036
+ types: "./dist/traces/index.d.ts",
2037
+ import: "./dist/traces/index.mjs",
2038
+ require: "./dist/traces/index.js"
2039
+ },
2040
+ "./hooks": {
2041
+ types: "./dist/hooks/index.d.ts",
2042
+ import: "./dist/hooks/index.mjs",
2043
+ require: "./dist/hooks/index.js"
2044
+ },
2045
+ "./cli": {
2046
+ types: "./dist/cli.d.ts",
2047
+ import: "./dist/cli.mjs",
2048
+ require: "./dist/cli.js"
2049
+ }
2050
+ },
2051
+ files: [
2052
+ "dist",
2053
+ "skills",
2054
+ "runtime",
2055
+ "README.md"
2056
+ ],
2057
+ publishConfig: {
2058
+ access: "public"
2059
+ },
2060
+ scripts: {
2061
+ prebuild: "node scripts/copy-skills.mjs && node scripts/copy-runtime.mjs",
2062
+ build: "tsup",
2063
+ dev: "tsup --watch",
2064
+ typecheck: "tsc --noEmit",
2065
+ "typecheck:examples": "tsc -p tsconfig.examples.json --noEmit",
2066
+ test: "vitest",
2067
+ "test:run": "vitest run",
2068
+ lint: "eslint src --ext .ts",
2069
+ clean: "rm -rf dist",
2070
+ example: "tsx examples/test-ab-experiment.ts",
2071
+ "test:crm": "tsx examples/test-crm-ab-experiment.ts",
2072
+ "test:crm:balanced": "tsx examples/test-crm-ab-experiment.ts --balanced",
2073
+ "test:crm:full": "tsx examples/test-crm-ab-experiment.ts --users 12 --all-tasks --concurrency 3"
2074
+ },
2075
+ keywords: [
2076
+ "gateway",
2077
+ "ab-testing",
2078
+ "experiments",
2079
+ "opentelemetry",
2080
+ "tracing",
2081
+ "observability",
2082
+ "llm"
2083
+ ],
2084
+ author: "Gateway Team",
2085
+ license: "MIT",
2086
+ engines: {
2087
+ node: ">=18.0.0"
2088
+ },
2089
+ peerDependencies: {
2090
+ "@opentelemetry/api": "^1.0.0",
2091
+ "@opentelemetry/exporter-trace-otlp-http": ">=0.50.0",
2092
+ "@opentelemetry/resources": ">=1.0.0",
2093
+ "@opentelemetry/sdk-trace-base": ">=1.0.0",
2094
+ "@opentelemetry/sdk-trace-node": ">=1.0.0",
2095
+ playwright: ">=1.40.0"
2096
+ },
2097
+ peerDependenciesMeta: {
2098
+ "@opentelemetry/api": {
2099
+ optional: true
2100
+ },
2101
+ "@opentelemetry/sdk-trace-base": {
2102
+ optional: true
2103
+ },
2104
+ "@opentelemetry/sdk-trace-node": {
2105
+ optional: true
2106
+ },
2107
+ "@opentelemetry/exporter-trace-otlp-http": {
2108
+ optional: true
2109
+ },
2110
+ "@opentelemetry/resources": {
2111
+ optional: true
2112
+ },
2113
+ playwright: {
2114
+ optional: true
2115
+ }
2116
+ },
2117
+ optionalDependencies: {
2118
+ "@arizeai/openinference-instrumentation-anthropic": "^0.1.15",
2119
+ "@arizeai/openinference-instrumentation-openai": "^4.1.5"
2120
+ },
2121
+ devDependencies: {
2122
+ "@anthropic-ai/sdk": "^0.79.0",
2123
+ "@opentelemetry/api": "^1.9.0",
2124
+ "@opentelemetry/exporter-trace-otlp-http": "^0.212.0",
2125
+ "@opentelemetry/resources": "^2.6.0",
2126
+ "@opentelemetry/sdk-trace-base": "^1.30.1",
2127
+ "@opentelemetry/sdk-trace-node": "^2.6.0",
2128
+ "@opentelemetry/semantic-conventions": "^1.40.0",
2129
+ "@types/node": "^20.0.0",
2130
+ openai: "^4.70.0",
2131
+ tsup: "^8.0.0",
2132
+ tsx: "^4.0.0",
2133
+ typescript: "^5.0.0",
2134
+ vitest: "^3.2.6"
2135
+ },
2136
+ overrides: {
2137
+ protobufjs: "^8.4.1",
2138
+ "vite@6": "^6.4.3",
2139
+ postcss: "^8.5.18",
2140
+ "picomatch@4": "^4.0.4"
2141
+ },
2142
+ pnpm: {
2143
+ overrides: {
2144
+ protobufjs: "^8.4.1",
2145
+ vitest: "^3.2.6",
2146
+ "vite@6": "^6.4.3",
2147
+ postcss: "^8.5.18",
2148
+ "picomatch@4": "^4.0.4"
2149
+ }
2150
+ },
2151
+ bin: {
2152
+ gateway: "./dist/cli.js"
2153
+ }
2154
+ };
2155
+ }
2156
+ });
2157
+
2158
+ // src/build/index.ts
2159
+ function canonicalJson(value) {
2160
+ if (value === null || typeof value !== "object") {
2161
+ return JSON.stringify(value);
2162
+ }
2163
+ if (Array.isArray(value)) {
2164
+ return `[${value.map(canonicalJson).join(",")}]`;
2165
+ }
2166
+ const entries = Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
2167
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(",")}}`;
2168
+ }
2169
+ function sha256(text2) {
2170
+ return `sha256:${(0, import_node_crypto2.createHash)("sha256").update(text2).digest("hex")}`;
2171
+ }
2172
+ function getRegisteredTools() {
2173
+ return [...registeredTools.values()].sort(
2174
+ (a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0
2175
+ );
2176
+ }
2177
+ function getRegisteredArtifacts() {
2178
+ return [...registeredArtifacts.values()].sort(
2179
+ (a, b) => `${a.kind}:${a.name}` < `${b.kind}:${b.name}` ? -1 : 1
2180
+ );
2181
+ }
2182
+ function getRegisteredSkills() {
2183
+ return Object.fromEntries(
2184
+ [...registeredSkills.entries()].sort(
2185
+ ([a], [b]) => a < b ? -1 : a > b ? 1 : 0
2186
+ )
2187
+ );
2188
+ }
2189
+ function getRegisteredPrompts() {
2190
+ return Object.fromEntries(
2191
+ [...registeredPrompts.entries()].sort(
2192
+ ([a], [b]) => a < b ? -1 : a > b ? 1 : 0
2193
+ )
2194
+ );
2195
+ }
2196
+ function sdkVersion() {
2197
+ try {
2198
+ const pkg = require_package();
2199
+ return `@withgateway/sdk@${pkg.version ?? "unknown"}`;
2200
+ } catch {
2201
+ return "@withgateway/sdk";
2202
+ }
2203
+ }
2204
+ function paasGitContext() {
2205
+ const env = process.env;
2206
+ if (env.VERCEL_GIT_COMMIT_SHA) {
2207
+ const isGithub = (env.VERCEL_GIT_PROVIDER ?? "github") === "github";
2208
+ return {
2209
+ provider: "vercel",
2210
+ sha: env.VERCEL_GIT_COMMIT_SHA,
2211
+ repo: isGithub && env.VERCEL_GIT_REPO_OWNER && env.VERCEL_GIT_REPO_SLUG ? `${env.VERCEL_GIT_REPO_OWNER}/${env.VERCEL_GIT_REPO_SLUG}` : void 0,
2212
+ branch: env.VERCEL_GIT_COMMIT_REF,
2213
+ login: env.VERCEL_GIT_COMMIT_AUTHOR_LOGIN
2214
+ };
2215
+ }
2216
+ if (env.RENDER_GIT_COMMIT) {
2217
+ return {
2218
+ provider: "render",
2219
+ sha: env.RENDER_GIT_COMMIT,
2220
+ repo: env.RENDER_GIT_REPO_SLUG,
2221
+ // already "owner/repo"
2222
+ branch: env.RENDER_GIT_BRANCH
2223
+ };
2224
+ }
2225
+ if (env.RAILWAY_GIT_COMMIT_SHA) {
2226
+ return {
2227
+ provider: "railway",
2228
+ sha: env.RAILWAY_GIT_COMMIT_SHA,
2229
+ repo: env.RAILWAY_GIT_REPO_OWNER && env.RAILWAY_GIT_REPO_NAME ? `${env.RAILWAY_GIT_REPO_OWNER}/${env.RAILWAY_GIT_REPO_NAME}` : void 0,
2230
+ branch: env.RAILWAY_GIT_BRANCH,
2231
+ login: env.RAILWAY_GIT_AUTHOR
2232
+ };
2233
+ }
2234
+ if (env.NETLIFY && env.COMMIT_REF) {
2235
+ const repoMatch = /github\.com[/:]([^/]+\/[^/.]+)/.exec(
2236
+ env.REPOSITORY_URL ?? ""
2237
+ );
2238
+ return {
2239
+ provider: "netlify",
2240
+ sha: env.COMMIT_REF,
2241
+ repo: repoMatch?.[1],
2242
+ branch: env.BRANCH
2243
+ };
2244
+ }
2245
+ const bareSha = env.HEROKU_SLUG_COMMIT ?? env.SOURCE_VERSION ?? env.GIT_COMMIT ?? env.COMMIT_SHA;
2246
+ if (bareSha) {
2247
+ return {
2248
+ provider: env.HEROKU_SLUG_COMMIT || env.SOURCE_VERSION ? "heroku" : "generic",
2249
+ sha: bareSha
2250
+ };
2251
+ }
2252
+ return null;
2253
+ }
2254
+ function codeRef() {
2255
+ const paas = paasGitContext();
2256
+ const sha = process.env.GATEWAY_COMMIT ?? process.env.GITHUB_SHA ?? process.env.CI_COMMIT_SHA ?? // GitLab
2257
+ process.env.CIRCLE_SHA1 ?? paas?.sha;
2258
+ if (!sha) return void 0;
2259
+ const repo = process.env.GITHUB_REPOSITORY ?? process.env.CI_PROJECT_PATH ?? paas?.repo;
2260
+ return repo ? `git:${repo}@${sha}` : `git:${sha}`;
2261
+ }
2262
+ function assembleManifest(agentId) {
2263
+ return {
2264
+ agentId,
2265
+ ...codeRef() ? { codeRef: codeRef() } : {},
2266
+ sdk: sdkVersion(),
2267
+ tools: getRegisteredTools(),
2268
+ prompts: getRegisteredPrompts(),
2269
+ skills: getRegisteredSkills(),
2270
+ artifacts: getRegisteredArtifacts()
2271
+ };
2272
+ }
2273
+ function computeBuildHash(manifest) {
2274
+ const identity = {
2275
+ ...manifest,
2276
+ tools: manifest.tools.map(({ source: _source, ...tool }) => tool),
2277
+ artifacts: manifest.artifacts.map(
2278
+ ({ source: _source, ...artifact }) => artifact
2279
+ )
2280
+ };
2281
+ return sha256(canonicalJson(identity));
2282
+ }
2283
+ function attributionFromEnv() {
2284
+ const attribution = { source: "runtime" };
2285
+ if (process.env.GITHUB_ACTIONS) attribution.source = "ci";
2286
+ if (process.env.GITHUB_ACTOR) attribution.githubLogin = process.env.GITHUB_ACTOR;
2287
+ const sha = process.env.GATEWAY_COMMIT ?? process.env.GITHUB_SHA;
2288
+ if (sha) attribution.commitSha = sha;
2289
+ if (process.env.GITHUB_REPOSITORY) attribution.repo = process.env.GITHUB_REPOSITORY;
2290
+ const branch = process.env.GITHUB_HEAD_REF ?? process.env.GITHUB_REF_NAME;
2291
+ if (branch) attribution.branch = branch;
2292
+ const paas = paasGitContext();
2293
+ if (paas) {
2294
+ if (attribution.source === "runtime") attribution.source = `paas:${paas.provider}`;
2295
+ if (!attribution.commitSha && paas.sha) attribution.commitSha = paas.sha;
2296
+ if (!attribution.repo && paas.repo) attribution.repo = paas.repo;
2297
+ if (!attribution.branch && paas.branch) attribution.branch = paas.branch;
2298
+ if (!attribution.githubLogin && paas.login) attribution.githubLogin = paas.login;
2299
+ }
2300
+ const ref = process.env.GITHUB_REF ?? "";
2301
+ const prMatch = /refs\/pull\/(\d+)\//.exec(ref);
2302
+ if (prMatch) attribution.prNumber = Number(prMatch[1]);
2303
+ if (process.env.GATEWAY_PR_TITLE) {
2304
+ attribution.prTitle = process.env.GATEWAY_PR_TITLE.slice(0, 300);
2305
+ }
2306
+ if (process.env.GATEWAY_PR_BODY) {
2307
+ attribution.prDescription = process.env.GATEWAY_PR_BODY.slice(0, 2e3);
2308
+ }
2309
+ if (attribution.repo && attribution.prNumber && !("prUrl" in attribution)) {
2310
+ attribution.prUrl = `https://github.com/${String(attribution.repo)}/pull/${String(attribution.prNumber)}`;
2311
+ }
2312
+ return attribution;
2313
+ }
2314
+ function trackActiveBuild(context) {
2315
+ activeBuilds.push(context);
2316
+ }
2317
+ async function registerBuild(params) {
2318
+ const auth = Buffer.from(`${params.publicKey}:${params.secretKey}`).toString(
2319
+ "base64"
2320
+ );
2321
+ const response = await fetch(
2322
+ `${params.host.replace(/\/$/, "")}/api/public/agent-builds`,
2323
+ {
2324
+ method: "POST",
2325
+ headers: {
2326
+ Authorization: `Basic ${auth}`,
2327
+ "Content-Type": "application/json"
2328
+ },
2329
+ body: JSON.stringify({
2330
+ agentId: params.agentId,
2331
+ buildHash: params.buildHash,
2332
+ ...params.version ? { semanticVer: params.version } : {},
2333
+ manifest: params.manifest,
2334
+ attribution: attributionFromEnv()
2335
+ }),
2336
+ signal: AbortSignal.timeout(15e3)
2337
+ }
2338
+ );
2339
+ if (!response.ok) {
2340
+ throw new Error(
2341
+ `build registration failed (${response.status}): ${(await response.text()).slice(0, 300)}`
2342
+ );
2343
+ }
2344
+ }
2345
+ var import_node_crypto2, registeredTools, registeredPrompts, registeredSkills, registeredArtifacts, activeBuilds;
2346
+ var init_build = __esm({
2347
+ "src/build/index.ts"() {
2348
+ "use strict";
2349
+ import_node_crypto2 = require("crypto");
2350
+ registeredTools = /* @__PURE__ */ new Map();
2351
+ registeredPrompts = /* @__PURE__ */ new Map();
2352
+ registeredSkills = /* @__PURE__ */ new Map();
2353
+ registeredArtifacts = /* @__PURE__ */ new Map();
2354
+ activeBuilds = [];
2355
+ }
2356
+ });
2357
+
2358
+ // src/tracing/init.ts
2359
+ var init_exports = {};
2360
+ __export(init_exports, {
2361
+ flush: () => flush,
2362
+ init: () => init,
2363
+ initIsolated: () => initIsolated,
2364
+ isGatewayConfigured: () => isGatewayConfigured,
2365
+ isInitialized: () => isInitialized,
2366
+ shutdown: () => shutdown
2367
+ });
2368
+ function getEnv(key) {
2369
+ const value = process.env[key];
2370
+ return value ? value : void 0;
2371
+ }
2372
+ function log(message, ...args) {
2373
+ if (state.debug) {
2374
+ console.log(`[gatewaysdk.tracing] ${message}`, ...args);
2375
+ }
2376
+ }
2377
+ function warn(message, ...args) {
2378
+ console.warn(`[gatewaysdk.tracing] ${message}`, ...args);
2379
+ }
2380
+ function buildProvider(config, logFn) {
2381
+ const host = config.host ?? getEnv(ENV_VARS.HOST);
2382
+ const publicKey = config.publicKey ?? getEnv(ENV_VARS.PUBLIC_KEY);
2383
+ const secretKey = config.secretKey ?? getEnv(ENV_VARS.SECRET_KEY);
2384
+ const endpoint = config.endpoint ?? getEnv(ENV_VARS.ENDPOINT) ?? (host ? `${host.replace(/\/$/, "")}${DEFAULT_OTLP_PATH}` : void 0);
2385
+ const missing = [];
2386
+ if (!host) missing.push("host (or GATEWAY_HOST env var)");
2387
+ if (!publicKey) missing.push("publicKey (or GATEWAY_PUBLIC_KEY env var)");
2388
+ if (!secretKey) missing.push("secretKey (or GATEWAY_SECRET_KEY env var)");
2389
+ if (missing.length > 0) {
2390
+ throw new Error(
2391
+ `Missing required Gateway configuration: ${missing.join(", ")}. Provide these values via init() parameters or environment variables.`
2392
+ );
2393
+ }
2394
+ let NodeTracerProvider;
2395
+ let BatchSpanProcessor;
2396
+ let OTLPTraceExporter;
2397
+ let createResource;
2398
+ let ATTR_SERVICE_NAME;
2399
+ try {
2400
+ const traceNode = require("@opentelemetry/sdk-trace-node");
2401
+ const traceBase = require("@opentelemetry/sdk-trace-base");
2402
+ const otlpHttp = require("@opentelemetry/exporter-trace-otlp-http");
2403
+ const resources = require("@opentelemetry/resources");
2404
+ NodeTracerProvider = traceNode.NodeTracerProvider;
2405
+ BatchSpanProcessor = traceBase.BatchSpanProcessor;
2406
+ OTLPTraceExporter = otlpHttp.OTLPTraceExporter;
2407
+ if (resources.Resource) {
2408
+ createResource = (attrs) => new resources.Resource(attrs);
2409
+ } else if (resources.resourceFromAttributes) {
2410
+ createResource = resources.resourceFromAttributes;
2411
+ } else {
2412
+ createResource = () => resources.defaultResource();
2413
+ }
2414
+ try {
2415
+ const semconv = require("@opentelemetry/semantic-conventions");
2416
+ ATTR_SERVICE_NAME = semconv.ATTR_SERVICE_NAME ?? semconv.SEMRESATTRS_SERVICE_NAME ?? "service.name";
2417
+ } catch {
2418
+ ATTR_SERVICE_NAME = "service.name";
2419
+ }
2420
+ } catch {
2421
+ throw new Error(
2422
+ "OpenTelemetry packages not found. Install them with:\nnpm install @opentelemetry/sdk-trace-node @opentelemetry/sdk-trace-base @opentelemetry/exporter-trace-otlp-http @opentelemetry/resources"
2423
+ );
2424
+ }
2425
+ const resourceAttrs = {
2426
+ [ATTR_SERVICE_NAME]: config.serviceName ?? "gatewaysdk-tracing"
2427
+ };
2428
+ if (config.environment) {
2429
+ resourceAttrs["gateway.environment"] = config.environment;
2430
+ }
2431
+ if (config.version) {
2432
+ resourceAttrs["gateway.version"] = config.version;
2433
+ }
2434
+ let buildInfo = null;
2435
+ if (config.agent) {
2436
+ const manifest = assembleManifest(config.agent);
2437
+ const buildHash = computeBuildHash(manifest);
2438
+ buildInfo = { manifest, buildHash };
2439
+ resourceAttrs["gateway.agent.id"] = config.agent;
2440
+ resourceAttrs["gateway.build.hash"] = buildHash;
2441
+ if (config.version) {
2442
+ resourceAttrs["gateway.agent.version"] = config.version;
2443
+ }
2444
+ logFn(
2445
+ "Agent build identity: %s @ %s (%d tools, %d prompts)",
2446
+ config.agent,
2447
+ buildHash.slice(0, 15),
2448
+ manifest.tools.length,
2449
+ Object.keys(manifest.prompts).length
2450
+ );
2451
+ }
2452
+ let isLocalhost = false;
2453
+ if (endpoint) {
2454
+ try {
2455
+ const parsed = new URL(endpoint);
2456
+ isLocalhost = parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1";
2457
+ } catch {
2458
+ isLocalhost = false;
2459
+ }
2460
+ }
2461
+ if (endpoint && !endpoint.startsWith("https://") && !isLocalhost) {
2462
+ throw new Error(
2463
+ `Refusing to send credentials over insecure HTTP to ${endpoint}. Use HTTPS or localhost for development.`
2464
+ );
2465
+ }
2466
+ const credentials = `${publicKey}:${secretKey}`;
2467
+ const encoded = Buffer.from(credentials).toString("base64");
2468
+ const authHeader = `Basic ${encoded}`;
2469
+ const exporter = new OTLPTraceExporter({
2470
+ url: endpoint,
2471
+ headers: {
2472
+ Authorization: authHeader
2473
+ }
2474
+ });
2475
+ logFn("Configured Gateway exporter: endpoint=%s", endpoint);
2476
+ const spanProcessors = [];
2477
+ if (config.customSpanProcessors) {
2478
+ for (const sp of config.customSpanProcessors) {
2479
+ spanProcessors.push(sp);
2480
+ logFn(
2481
+ "Added custom span processor: %s",
2482
+ sp.constructor?.name ?? "unknown"
2483
+ );
2484
+ }
2485
+ }
2486
+ spanProcessors.push(new IdentitySpanProcessor());
2487
+ spanProcessors.push(new SessionSpanProcessor());
2488
+ const batchConfig = {};
2489
+ if (config.batch?.maxQueueSize) {
2490
+ batchConfig.maxQueueSize = config.batch.maxQueueSize;
2491
+ }
2492
+ if (config.batch?.scheduledDelayMillis) {
2493
+ batchConfig.scheduledDelayMillis = config.batch.scheduledDelayMillis;
2494
+ }
2495
+ if (config.batch?.maxExportBatchSize) {
2496
+ batchConfig.maxExportBatchSize = config.batch.maxExportBatchSize;
2497
+ }
2498
+ spanProcessors.push(new BatchSpanProcessor(exporter, batchConfig));
2499
+ let provider = new NodeTracerProvider({
2500
+ resource: createResource(resourceAttrs)
2501
+ });
2502
+ if (typeof provider.addSpanProcessor === "function") {
2503
+ for (const sp of spanProcessors) {
2504
+ provider.addSpanProcessor(sp);
2505
+ }
2506
+ } else {
2507
+ provider = new NodeTracerProvider({
2508
+ resource: createResource(resourceAttrs),
2509
+ spanProcessors
2510
+ });
2511
+ }
2512
+ return {
2513
+ provider,
2514
+ buildInfo,
2515
+ connection: { host, publicKey, secretKey }
2516
+ };
2517
+ }
2518
+ function scheduleBuildRegistration(config, built) {
2519
+ if (!config.agent || !built.buildInfo || config.registerBuild === false) {
2520
+ return;
2521
+ }
2522
+ const { manifest, buildHash } = built.buildInfo;
2523
+ trackActiveBuild({
2524
+ host: built.connection.host,
2525
+ publicKey: built.connection.publicKey,
2526
+ secretKey: built.connection.secretKey,
2527
+ agentId: config.agent,
2528
+ version: config.version,
2529
+ lastRegisteredHash: buildHash
2530
+ });
2531
+ void registerBuild({
2532
+ host: built.connection.host,
2533
+ publicKey: built.connection.publicKey,
2534
+ secretKey: built.connection.secretKey,
2535
+ agentId: config.agent,
2536
+ version: config.version,
2537
+ manifest,
2538
+ buildHash
2539
+ }).catch((err) => {
2540
+ warn("Build registration failed (agent keeps running):", err);
2541
+ });
2542
+ }
2543
+ function init(config = {}) {
2544
+ if (state.initialized) {
2545
+ log("Tracing already initialized. Call shutdown() first to reinitialize.");
2546
+ return;
2547
+ }
2548
+ state.debug = config.debug ?? false;
2549
+ const built = buildProvider(config, log);
2550
+ const provider = built.provider;
2551
+ provider.register();
2552
+ scheduleBuildRegistration(config, built);
2553
+ state.provider = provider;
2554
+ state.initialized = true;
2555
+ log(
2556
+ "GatewaySDK tracing initialized successfully (service=%s)",
2557
+ config.serviceName ?? "gatewaysdk-tracing"
2558
+ );
2559
+ }
2560
+ function initIsolated(config = {}) {
2561
+ const debugLog = config.debug ? (message, ...args) => console.log(`[gatewaysdk.tracing:isolated] ${message}`, ...args) : () => {
2562
+ };
2563
+ const built = buildProvider(config, debugLog);
2564
+ const provider = built.provider;
2565
+ scheduleBuildRegistration(config, built);
2566
+ const tracer = provider.getTracer("@withgateway/sdk");
2567
+ const scores2 = new ScoresClient({
2568
+ host: built.connection.host,
2569
+ publicKey: built.connection.publicKey,
2570
+ secretKey: built.connection.secretKey,
2571
+ debug: config.debug ?? false
2572
+ });
2573
+ debugLog(
2574
+ "Isolated tracing provider created (service=%s)",
2575
+ config.serviceName ?? "gatewaysdk-tracing"
2576
+ );
2577
+ return {
2578
+ tracer,
2579
+ scores: scores2,
2580
+ async flush() {
2581
+ try {
2582
+ await provider.forceFlush();
2583
+ } catch (e) {
2584
+ warn("Error during isolated flush:", e);
2585
+ }
2586
+ },
2587
+ async shutdown() {
2588
+ try {
2589
+ await provider.shutdown();
2590
+ } catch (e) {
2591
+ warn("Error during isolated shutdown:", e);
1055
2592
  }
2593
+ }
2594
+ };
2595
+ }
2596
+ async function flush() {
2597
+ if (!state.provider) {
2598
+ log("No provider to flush");
2599
+ return;
2600
+ }
2601
+ try {
2602
+ await state.provider.forceFlush();
2603
+ log("Flush completed successfully");
2604
+ } catch (e) {
2605
+ warn("Error during flush:", e);
2606
+ }
2607
+ }
2608
+ async function shutdown() {
2609
+ if (!state.initialized || !state.provider) {
2610
+ log("Tracing not initialized, nothing to shutdown");
2611
+ return;
2612
+ }
2613
+ try {
2614
+ await state.provider.shutdown();
2615
+ log("Shutdown complete");
2616
+ } catch (e) {
2617
+ warn("Error during shutdown:", e);
2618
+ }
2619
+ state.provider = null;
2620
+ state.initialized = false;
2621
+ }
2622
+ function isInitialized() {
2623
+ return state.initialized;
2624
+ }
2625
+ function isGatewayConfigured() {
2626
+ const host = getEnv(ENV_VARS.HOST);
2627
+ const publicKey = getEnv(ENV_VARS.PUBLIC_KEY);
2628
+ const secretKey = getEnv(ENV_VARS.SECRET_KEY);
2629
+ return !!(host && publicKey && secretKey);
2630
+ }
2631
+ var ENV_VARS, DEFAULT_OTLP_PATH, state;
2632
+ var init_init = __esm({
2633
+ "src/tracing/init.ts"() {
2634
+ "use strict";
2635
+ init_identity();
2636
+ init_session2();
2637
+ init_scores();
2638
+ init_build();
2639
+ ENV_VARS = {
2640
+ HOST: "GATEWAY_HOST",
2641
+ PUBLIC_KEY: "GATEWAY_PUBLIC_KEY",
2642
+ SECRET_KEY: "GATEWAY_SECRET_KEY",
2643
+ ENDPOINT: "GATEWAY_OTLP_ENDPOINT"
2644
+ };
2645
+ DEFAULT_OTLP_PATH = "/api/public/otel/v1/traces";
2646
+ state = {
2647
+ initialized: false,
2648
+ provider: null
1056
2649
  };
1057
2650
  }
1058
2651
  });
1059
2652
 
1060
- // src/worlds/tasks.ts
1061
- async function createTask(input, options = {}) {
1062
- return apiRequest(
1063
- options,
1064
- "POST",
1065
- TASKS,
1066
- compact({
1067
- spec: input.spec,
1068
- name: input.name,
1069
- world: input.world,
1070
- message: input.message
1071
- })
1072
- );
1073
- }
1074
- async function updateTask(taskId, input, options = {}) {
1075
- if (input.spec === void 0 && input.name === void 0 && input.world === void 0)
1076
- throw new Error("updateTask: nothing to update \u2014 pass spec, name or world");
1077
- return apiRequest(
1078
- options,
1079
- "PATCH",
1080
- taskRoute(taskId),
1081
- compact({
1082
- spec: input.spec,
1083
- name: input.name,
1084
- world: input.world,
1085
- message: input.message
1086
- })
1087
- );
2653
+ // src/worlds/taskRun.ts
2654
+ function worldRef(live, alias) {
2655
+ const { slug, ref } = live.worldRef(alias);
2656
+ const session = live.sessions[alias];
2657
+ return {
2658
+ slug,
2659
+ ref,
2660
+ versionId: session.versionId,
2661
+ sessionId: session.sessionId
2662
+ };
1088
2663
  }
1089
- async function listTasks(filter = {}, options = {}) {
1090
- const params = new URLSearchParams();
1091
- if (filter.world) params.set("world", filter.world);
1092
- if (filter.page !== void 0) params.set("page", String(filter.page));
1093
- if (filter.limit !== void 0) params.set("limit", String(filter.limit));
1094
- for (const [key, value] of Object.entries(filter.metadata ?? {}))
1095
- params.set(`metadata.${key}`, value);
1096
- const query = params.toString();
1097
- return apiRequest(
1098
- options,
1099
- "GET",
1100
- query ? `${TASKS}?${query}` : TASKS
2664
+ async function fileTaskRun(live, runId, model, report, grade, agentError, traced, runDir, options) {
2665
+ const aliases = live.aliases;
2666
+ const anchor = aliases[0];
2667
+ const worldsMeta = Object.fromEntries(
2668
+ aliases.map((alias) => [alias, worldRef(live, alias)])
1101
2669
  );
1102
- }
1103
- async function getTask(taskId, opts = {}, options = {}) {
1104
- const query = opts.version === void 0 ? "" : `?version=${String(opts.version)}`;
1105
- return apiRequest(
1106
- options,
1107
- "GET",
1108
- `${taskRoute(taskId)}${query}`
2670
+ const evals = new GatewayEvalsClient(options);
2671
+ const evaluationId = await evals.createEvaluation(
2672
+ worldRef(live, anchor).versionId,
2673
+ {
2674
+ model,
2675
+ rolloutsPerExample: 1,
2676
+ metadata: {
2677
+ source: "worlds-task-run",
2678
+ task: {
2679
+ id: live.taskId,
2680
+ version: live.taskVersion,
2681
+ name: live.name,
2682
+ hash: live.hash
2683
+ },
2684
+ anchor,
2685
+ worlds: worldsMeta,
2686
+ runId
2687
+ }
2688
+ }
1109
2689
  );
2690
+ const reward = grade.reward;
2691
+ const sample = {
2692
+ exampleId: live.name ?? live.taskId ?? runId,
2693
+ task: live.name ?? live.taskId ?? runId,
2694
+ rolloutIndex: 0,
2695
+ prompt: live.instruction,
2696
+ completion: report,
2697
+ rewards: grade.rewards,
2698
+ info: {
2699
+ sessionId: runId,
2700
+ worlds: Object.fromEntries(
2701
+ aliases.map((alias) => [
2702
+ alias,
2703
+ {
2704
+ ...worldRef(live, alias),
2705
+ reward: grade.worlds[alias]?.reward ?? null
2706
+ }
2707
+ ])
2708
+ ),
2709
+ ungraded: grade.ungraded,
2710
+ traced,
2711
+ runDir,
2712
+ ...agentError ? { agentError } : {}
2713
+ }
2714
+ };
2715
+ if (typeof reward === "number") {
2716
+ sample.reward = reward;
2717
+ sample.score = reward;
2718
+ sample.correct = reward >= 1;
2719
+ }
2720
+ await evals.pushSamples(evaluationId, [sample]);
2721
+ await evals.finalizeEvaluation(evaluationId, {
2722
+ status: agentError ? "FAILED" : "COMPLETED",
2723
+ metrics: {
2724
+ ...typeof reward === "number" ? { avg_reward: reward } : {},
2725
+ reward,
2726
+ ...Object.fromEntries(
2727
+ Object.entries(grade.rewards).map(([k, v]) => [`rewards.${k}`, v])
2728
+ )
2729
+ }
2730
+ });
2731
+ return evaluationId;
1110
2732
  }
1111
- async function deleteTask(taskId, options = {}) {
1112
- return apiRequest(options, "DELETE", taskRoute(taskId));
1113
- }
1114
- async function validateTask(taskId, target = {}, options = {}) {
1115
- return apiRequest(
1116
- options,
1117
- "POST",
1118
- `${taskRoute(taskId)}/validate`,
1119
- compact({
1120
- version: target.version,
1121
- slug: target.slug,
1122
- versionId: target.versionId
1123
- })
1124
- );
2733
+ function reportFromResult(result) {
2734
+ if (typeof result === "string") return { report: result, extra: {} };
2735
+ if (result && typeof result === "object") {
2736
+ const { report, ...extra } = result;
2737
+ return {
2738
+ report: report === void 0 || report === null ? null : typeof report === "string" ? report : String(report),
2739
+ extra
2740
+ };
2741
+ }
2742
+ if (result !== void 0 && result !== null)
2743
+ return { report: String(result), extra: {} };
2744
+ return { report: null, extra: {} };
2745
+ }
2746
+ async function runTask(ref, agent, opts) {
2747
+ const runId = `wtr-${(0, import_node_crypto3.randomBytes)(6).toString("hex")}`;
2748
+ const outDir = opts.outDir ?? "runs";
2749
+ const runDir = path.join(outDir, runId);
2750
+ fs.mkdirSync(runDir, { recursive: true });
2751
+ const options = opts.options ?? {};
2752
+ const live = await openTask(ref, {
2753
+ surfaces: opts.surfaces,
2754
+ reuseWarm: opts.reuseWarm,
2755
+ options
2756
+ });
2757
+ const started = Date.now();
2758
+ try {
2759
+ await live.ready();
2760
+ let traced = false;
2761
+ if (opts.trace !== false) {
2762
+ try {
2763
+ const { isGatewayConfigured: isGatewayConfigured2, init: init2 } = await Promise.resolve().then(() => (init_init(), init_exports));
2764
+ if (isGatewayConfigured2()) {
2765
+ init2();
2766
+ traced = true;
2767
+ }
2768
+ } catch {
2769
+ traced = false;
2770
+ }
2771
+ }
2772
+ const taskRun = new TaskRun(
2773
+ runId,
2774
+ live.instruction ?? "",
2775
+ opts.model,
2776
+ live.sessions,
2777
+ await live.manifest()
2778
+ );
2779
+ let agentError = null;
2780
+ let report = null;
2781
+ let extra = {};
2782
+ try {
2783
+ const invoke = () => agent(taskRun);
2784
+ const result = traced ? await (await Promise.resolve().then(() => (init_session2(), session_exports2))).withSession(runId, invoke) : await invoke();
2785
+ ({ report, extra } = reportFromResult(result));
2786
+ } catch (error) {
2787
+ const message = (error instanceof Error ? error.message : String(error)) || "Unknown error";
2788
+ agentError = message.slice(0, 2e3);
2789
+ }
2790
+ const grade = report !== null ? await live.grade({ report }) : await live.grade();
2791
+ fs.writeFileSync(
2792
+ path.join(runDir, "manifest.json"),
2793
+ JSON.stringify(taskRun.manifest, null, 2)
2794
+ );
2795
+ fs.writeFileSync(
2796
+ path.join(runDir, "grades.json"),
2797
+ JSON.stringify(grade, null, 2)
2798
+ );
2799
+ if (report) fs.writeFileSync(path.join(runDir, "report.md"), report);
2800
+ const summary = {
2801
+ runId,
2802
+ taskId: live.taskId,
2803
+ taskVersion: live.taskVersion,
2804
+ name: live.name,
2805
+ instruction: taskRun.instruction,
2806
+ model: opts.model,
2807
+ aliases: live.aliases,
2808
+ reward: grade.reward,
2809
+ rewards: grade.rewards,
2810
+ ungraded: grade.ungraded,
2811
+ agentError,
2812
+ report,
2813
+ traced,
2814
+ runDir,
2815
+ durationSeconds: Math.round((Date.now() - started) / 10) / 100,
2816
+ notes: taskRun.notes,
2817
+ filed: false,
2818
+ ...extra
2819
+ };
2820
+ if (opts.file !== false) {
2821
+ summary.evaluationId = await fileTaskRun(
2822
+ live,
2823
+ runId,
2824
+ opts.model,
2825
+ report,
2826
+ grade,
2827
+ agentError,
2828
+ traced,
2829
+ runDir,
2830
+ options
2831
+ );
2832
+ summary.filed = true;
2833
+ }
2834
+ fs.writeFileSync(
2835
+ path.join(runDir, "run.json"),
2836
+ JSON.stringify(summary, null, 2)
2837
+ );
2838
+ return summary;
2839
+ } finally {
2840
+ if (!opts.keepUp) {
2841
+ try {
2842
+ await live.close({ keepWarm: false });
2843
+ } catch {
2844
+ }
2845
+ }
2846
+ }
1125
2847
  }
1126
- var TASKS, taskRoute, compact;
1127
- var init_tasks = __esm({
1128
- "src/worlds/tasks.ts"() {
2848
+ var import_node_crypto3, fs, path, TaskRun;
2849
+ var init_taskRun = __esm({
2850
+ "src/worlds/taskRun.ts"() {
1129
2851
  "use strict";
1130
- init_worlds();
1131
- TASKS = "/api/public/world-tasks";
1132
- taskRoute = (id) => `${TASKS}/${encodeURIComponent(id)}`;
1133
- compact = (body) => Object.fromEntries(Object.entries(body).filter(([, v]) => v !== void 0));
2852
+ import_node_crypto3 = require("crypto");
2853
+ fs = __toESM(require("fs"));
2854
+ path = __toESM(require("path"));
2855
+ init_browser();
2856
+ init_evals();
2857
+ init_session();
2858
+ init_taskSessions();
2859
+ TaskRun = class {
2860
+ constructor(runId, instruction, model, sessions, manifest) {
2861
+ this.runId = runId;
2862
+ this.instruction = instruction;
2863
+ this.model = model;
2864
+ this.sessions = sessions;
2865
+ this.manifest = manifest;
2866
+ }
2867
+ notes = {};
2868
+ /** The alias's session, or a clear error naming the aliases there are. */
2869
+ session(alias) {
2870
+ const session = this.sessions[alias];
2871
+ if (!session)
2872
+ throw new Error(
2873
+ `task run has no world '${alias}'; its worlds are ${Object.keys(this.sessions).join(", ")}`
2874
+ );
2875
+ return session;
2876
+ }
2877
+ /** `alias`'s HTTP API. Raises the same error the session itself would
2878
+ * when it was not opened with `surfaces: ["api"]`. */
2879
+ async api(alias) {
2880
+ const surfaces = await this.session(alias).surfaces();
2881
+ if (!surfaces.api)
2882
+ throw new WorldSurfaceUnavailable(
2883
+ "api",
2884
+ `open '${alias}' with surfaces: ['api']`
2885
+ );
2886
+ return { url: surfaces.api.url, token: surfaces.api.token };
2887
+ }
2888
+ /** Every world's tools merged into one toolkit, each name prefixed
2889
+ * `<alias>.<tool>` so a model can tell which world a call goes to. A
2890
+ * world that exposes no tools contributes nothing — there is nothing to
2891
+ * merge. */
2892
+ async toolkit() {
2893
+ const schemas = [];
2894
+ const impls = {};
2895
+ const specs = [];
2896
+ for (const [alias, session] of Object.entries(this.sessions)) {
2897
+ const kit = await session.toolkit();
2898
+ if (!kit.specs.length) continue;
2899
+ for (const spec of kit.specs) {
2900
+ const name = `${alias}.${spec.name}`;
2901
+ const prefixed = {
2902
+ name,
2903
+ signature: spec.signature,
2904
+ doc: spec.doc,
2905
+ inputSchema: spec.inputSchema
2906
+ };
2907
+ specs.push(prefixed);
2908
+ const schema = schemaFromSignature(prefixed);
2909
+ schema.function.name = name;
2910
+ schemas.push(schema);
2911
+ impls[name] = kit.impls[modelToolName(spec.name)];
2912
+ }
2913
+ }
2914
+ return { schemas, impls, specs };
2915
+ }
2916
+ /** Log arbitrary notes into this run's `run.json` (merged; a later call
2917
+ * overrides a key an earlier one set). */
2918
+ record(notes) {
2919
+ Object.assign(this.notes, notes);
2920
+ }
2921
+ };
1134
2922
  }
1135
2923
  });
1136
2924
 
@@ -1147,6 +2935,7 @@ __export(hub_exports, {
1147
2935
  propose: () => propose,
1148
2936
  pull: () => pull,
1149
2937
  push: () => push,
2938
+ pushSlug: () => pushSlug,
1150
2939
  readLocalMeta: () => readLocalMeta,
1151
2940
  snapshotTreeHashes: () => snapshotTreeHashes,
1152
2941
  writeLocalMeta: () => writeLocalMeta
@@ -1166,18 +2955,18 @@ function isIncludedInContentHash(relPath, includeAllRootFiles) {
1166
2955
  return !dirParts.some(isExcludedDirComponent);
1167
2956
  }
1168
2957
  function collectArchiveRelPaths(dir) {
1169
- if (fs.existsSync(path.join(dir, ".gitignore"))) {
2958
+ if (fs2.existsSync(path2.join(dir, ".gitignore"))) {
1170
2959
  throw new Error(
1171
2960
  "This bundle has a root .gitignore, which the Python CLI honors via gitignore_parser. Reimplementing that imperfectly here would silently produce a different content hash, so the TS CLI refuses. Remove the .gitignore (or bake its effect into the tree) and retry."
1172
2961
  );
1173
2962
  }
1174
2963
  const out = [];
1175
2964
  const includeAllRootFiles = BROAD_ROOT_MARKERS.some(
1176
- (marker) => fs.existsSync(path.join(dir, marker))
2965
+ (marker) => fs2.existsSync(path2.join(dir, marker))
1177
2966
  );
1178
2967
  const walk = (rel) => {
1179
- const abs = rel ? path.join(dir, rel) : dir;
1180
- for (const entry of fs.readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
2968
+ const abs = rel ? path2.join(dir, rel) : dir;
2969
+ for (const entry of fs2.readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
1181
2970
  const childRel = rel ? `${rel}/${entry.name}` : entry.name;
1182
2971
  if (entry.isDirectory()) {
1183
2972
  if (!isExcludedDirComponent(entry.name)) walk(childRel);
@@ -1192,10 +2981,10 @@ function collectArchiveRelPaths(dir) {
1192
2981
  return out.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
1193
2982
  }
1194
2983
  function computeContentHash(dir) {
1195
- const hasher = (0, import_node_crypto2.createHash)("sha256");
2984
+ const hasher = (0, import_node_crypto4.createHash)("sha256");
1196
2985
  for (const relPath of collectArchiveRelPaths(dir)) {
1197
2986
  hasher.update(Buffer.from(`file:${relPath}`, "utf-8"));
1198
- hasher.update(fs.readFileSync(path.join(dir, relPath)));
2987
+ hasher.update(fs2.readFileSync(path2.join(dir, relPath)));
1199
2988
  }
1200
2989
  return hasher.digest("hex");
1201
2990
  }
@@ -1245,28 +3034,34 @@ function tarMember(name, payload) {
1245
3034
  function buildSourceTarball(dir) {
1246
3035
  const parts = [];
1247
3036
  for (const relPath of collectArchiveRelPaths(dir)) {
1248
- parts.push(...tarMember(relPath, fs.readFileSync(path.join(dir, relPath))));
3037
+ parts.push(...tarMember(relPath, fs2.readFileSync(path2.join(dir, relPath))));
1249
3038
  }
1250
3039
  parts.push(Buffer.alloc(1024));
1251
3040
  return (0, import_node_zlib.gzipSync)(Buffer.concat(parts), { level: 9 });
1252
3041
  }
1253
3042
  function readLocalMeta(dir) {
1254
3043
  try {
1255
- const raw = fs.readFileSync(path.join(dir, META_RELPATH), "utf-8");
3044
+ const raw = fs2.readFileSync(path2.join(dir, META_RELPATH), "utf-8");
1256
3045
  const parsed = JSON.parse(raw);
1257
3046
  return parsed && typeof parsed === "object" ? parsed : null;
1258
3047
  } catch {
1259
3048
  return null;
1260
3049
  }
1261
3050
  }
3051
+ function pushSlug(dir, explicit) {
3052
+ if (explicit) return explicit;
3053
+ const meta = readLocalMeta(dir);
3054
+ if (typeof meta?.slug === "string" && meta.slug) return meta.slug;
3055
+ return readPyproject(dir).name ?? path2.basename(path2.resolve(dir));
3056
+ }
1262
3057
  function writeLocalMeta(dir, meta) {
1263
- fs.mkdirSync(path.join(dir, ".gateway"), { recursive: true });
1264
- fs.writeFileSync(path.join(dir, META_RELPATH), JSON.stringify(meta, null, 2));
3058
+ fs2.mkdirSync(path2.join(dir, ".gateway"), { recursive: true });
3059
+ fs2.writeFileSync(path2.join(dir, META_RELPATH), JSON.stringify(meta, null, 2));
1265
3060
  }
1266
3061
  function snapshotTreeHashes(dir) {
1267
3062
  const out = {};
1268
3063
  for (const relPath of collectArchiveRelPaths(dir)) {
1269
- out[relPath] = (0, import_node_crypto2.createHash)("sha256").update(fs.readFileSync(path.join(dir, relPath))).digest("hex");
3064
+ out[relPath] = (0, import_node_crypto4.createHash)("sha256").update(fs2.readFileSync(path2.join(dir, relPath))).digest("hex");
1270
3065
  }
1271
3066
  return out;
1272
3067
  }
@@ -1284,7 +3079,7 @@ function localTreeState(dir) {
1284
3079
  }
1285
3080
  function readPyproject(dir) {
1286
3081
  try {
1287
- const text2 = fs.readFileSync(path.join(dir, "pyproject.toml"), "utf-8");
3082
+ const text2 = fs2.readFileSync(path2.join(dir, "pyproject.toml"), "utf-8");
1288
3083
  const section = /\[project\]([\s\S]*?)(\n\[|$)/.exec(text2)?.[1] ?? "";
1289
3084
  const name = /\bname\s*=\s*"([^"]+)"/.exec(section)?.[1];
1290
3085
  const version = /\bversion\s*=\s*"([^"]+)"/.exec(section)?.[1];
@@ -1294,9 +3089,9 @@ function readPyproject(dir) {
1294
3089
  }
1295
3090
  }
1296
3091
  function readWorldContractVersion(dir) {
1297
- for (const rel of ["schema/world.json", path.join("server", "world", "schema", "world.json")]) {
3092
+ for (const rel of ["schema/world.json", path2.join("server", "world", "schema", "world.json")]) {
1298
3093
  try {
1299
- const parsed = JSON.parse(fs.readFileSync(path.join(dir, rel), "utf-8"));
3094
+ const parsed = JSON.parse(fs2.readFileSync(path2.join(dir, rel), "utf-8"));
1300
3095
  const pkg = parsed["x-gateway"]?.package;
1301
3096
  if (pkg?.version) return { name: pkg.id, version: pkg.version };
1302
3097
  } catch {
@@ -1307,20 +3102,20 @@ function readWorldContractVersion(dir) {
1307
3102
  function buildFileManifest(dir) {
1308
3103
  const entries = [];
1309
3104
  const walk = (rel) => {
1310
- const abs = rel ? path.join(dir, rel) : dir;
1311
- for (const entry of fs.readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
3105
+ const abs = rel ? path2.join(dir, rel) : dir;
3106
+ for (const entry of fs2.readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
1312
3107
  const childRel = rel ? `${rel}/${entry.name}` : entry.name;
1313
3108
  if (entry.isDirectory()) {
1314
3109
  if (!SKIP_DIRS.has(entry.name) && !entry.name.endsWith(".egg-info")) {
1315
3110
  walk(childRel);
1316
3111
  }
1317
3112
  } else if (entry.isFile()) {
1318
- const payload = fs.readFileSync(path.join(dir, childRel));
3113
+ const payload = fs2.readFileSync(path2.join(dir, childRel));
1319
3114
  entries.push({
1320
3115
  path: childRel,
1321
3116
  isDirectory: false,
1322
3117
  size: payload.length,
1323
- sha256: (0, import_node_crypto2.createHash)("sha256").update(payload).digest("hex")
3118
+ sha256: (0, import_node_crypto4.createHash)("sha256").update(payload).digest("hex")
1324
3119
  });
1325
3120
  }
1326
3121
  }
@@ -1343,7 +3138,7 @@ async function putObject(url, data, shaB64) {
1343
3138
  }
1344
3139
  async function push(dir, opts = {}) {
1345
3140
  const options = opts.options ?? {};
1346
- if (!fs.statSync(dir).isDirectory()) throw new Error(`Not a directory: ${dir}`);
3141
+ if (!fs2.statSync(dir).isDirectory()) throw new Error(`Not a directory: ${dir}`);
1347
3142
  const localMeta = readLocalMeta(dir) ?? {};
1348
3143
  const branch = opts.branch ?? localMeta.branch ?? DEFAULT_BRANCH;
1349
3144
  const baseVersionId = opts.baseVersionId ?? localMeta.versionId ?? null;
@@ -1351,7 +3146,7 @@ async function push(dir, opts = {}) {
1351
3146
  const pyproject = readPyproject(dir);
1352
3147
  const contractVersion = pyproject.version ? void 0 : readWorldContractVersion(dir).version;
1353
3148
  if (contractVersion) pyproject.version = contractVersion;
1354
- const slug = opts.slug ?? pyproject.name ?? path.basename(path.resolve(dir));
3149
+ const slug = opts.slug ?? localMeta.slug ?? pyproject.name ?? path2.basename(path2.resolve(dir));
1355
3150
  const resolve6 = await apiRequest(
1356
3151
  options,
1357
3152
  "POST",
@@ -1431,9 +3226,9 @@ function extractBundle(bundle, dir) {
1431
3226
  longName = null;
1432
3227
  if (typeflag !== "0" && typeflag !== "") continue;
1433
3228
  if (name.startsWith("/") || name.split("/").includes("..")) continue;
1434
- const target = path.join(dir, name);
1435
- fs.mkdirSync(path.dirname(target), { recursive: true });
1436
- fs.writeFileSync(target, body);
3229
+ const target = path2.join(dir, name);
3230
+ fs2.mkdirSync(path2.dirname(target), { recursive: true });
3231
+ fs2.writeFileSync(target, body);
1437
3232
  written++;
1438
3233
  }
1439
3234
  return written;
@@ -1449,13 +3244,13 @@ async function pull(slugRef, target, options = {}) {
1449
3244
  if (!details.downloadUrl) {
1450
3245
  throw new Error(`${slug}@${ref} resolved but has no uploaded bundle`);
1451
3246
  }
1452
- let dir = target ?? path.join(process.cwd(), slug);
3247
+ let dir = target ?? path2.join(process.cwd(), slug);
1453
3248
  if (!target) {
1454
3249
  let i = 1;
1455
3250
  const base = dir;
1456
- while (fs.existsSync(dir)) dir = `${base}-${i++}`;
3251
+ while (fs2.existsSync(dir)) dir = `${base}-${i++}`;
1457
3252
  }
1458
- fs.mkdirSync(dir, { recursive: true });
3253
+ fs2.mkdirSync(dir, { recursive: true });
1459
3254
  const resp = await fetch(details.downloadUrl);
1460
3255
  if (!resp.ok) throw new Error(`bundle download -> ${resp.status}`);
1461
3256
  const bundle = Buffer.from(await resp.arrayBuffer());
@@ -1482,15 +3277,15 @@ async function propose(dir, opts) {
1482
3277
  if (!meta?.slug || !meta.baseFiles) {
1483
3278
  throw new Error("This dir has no pull/push base \u2014 run pull first, then edit, then propose.");
1484
3279
  }
1485
- const state = localTreeState(dir);
1486
- if (state.clean) throw new Error("Nothing to propose \u2014 the tree matches its base.");
1487
- const changes = state.dirty.map((relPath) => {
1488
- const abs = path.join(dir, relPath);
1489
- if (!fs.existsSync(abs)) return { path: relPath, action: "delete" };
3280
+ const state2 = localTreeState(dir);
3281
+ if (state2.clean) throw new Error("Nothing to propose \u2014 the tree matches its base.");
3282
+ const changes = state2.dirty.map((relPath) => {
3283
+ const abs = path2.join(dir, relPath);
3284
+ if (!fs2.existsSync(abs)) return { path: relPath, action: "delete" };
1490
3285
  return {
1491
3286
  path: relPath,
1492
3287
  action: "write",
1493
- newContent: fs.readFileSync(abs, "utf-8")
3288
+ newContent: fs2.readFileSync(abs, "utf-8")
1494
3289
  };
1495
3290
  });
1496
3291
  const res = await apiRequest(
@@ -1516,17 +3311,17 @@ async function createRef(slug, name, kind, versionId, options = {}) {
1516
3311
  ...versionId ? { versionId } : {}
1517
3312
  });
1518
3313
  }
1519
- var import_node_crypto2, import_node_zlib, fs, path, DEFAULT_BRANCH, META_RELPATH, SKIP_DIRS, ROOT_EXCLUDED_DIRS, BROAD_ROOT_MARKERS, sha256b64;
3314
+ var import_node_crypto4, import_node_zlib, fs2, path2, DEFAULT_BRANCH, META_RELPATH, SKIP_DIRS, ROOT_EXCLUDED_DIRS, BROAD_ROOT_MARKERS, sha256b64;
1520
3315
  var init_hub = __esm({
1521
3316
  "src/worlds/hub.ts"() {
1522
3317
  "use strict";
1523
- import_node_crypto2 = require("crypto");
3318
+ import_node_crypto4 = require("crypto");
1524
3319
  import_node_zlib = require("zlib");
1525
- fs = __toESM(require("fs"));
1526
- path = __toESM(require("path"));
3320
+ fs2 = __toESM(require("fs"));
3321
+ path2 = __toESM(require("path"));
1527
3322
  init_worlds();
1528
3323
  DEFAULT_BRANCH = "main";
1529
- META_RELPATH = path.join(".gateway", ".env-metadata.json");
3324
+ META_RELPATH = path2.join(".gateway", ".env-metadata.json");
1530
3325
  SKIP_DIRS = /* @__PURE__ */ new Set([
1531
3326
  ".git",
1532
3327
  "__pycache__",
@@ -1539,7 +3334,7 @@ var init_hub = __esm({
1539
3334
  ]);
1540
3335
  ROOT_EXCLUDED_DIRS = /* @__PURE__ */ new Set(["dist", "build", "outputs", "__pycache__"]);
1541
3336
  BROAD_ROOT_MARKERS = ["gateway-env.toml", "gateway-api-world.toml"];
1542
- sha256b64 = (data) => (0, import_node_crypto2.createHash)("sha256").update(data).digest("base64");
3337
+ sha256b64 = (data) => (0, import_node_crypto4.createHash)("sha256").update(data).digest("base64");
1543
3338
  }
1544
3339
  });
1545
3340
 
@@ -1612,23 +3407,22 @@ async function validateWorld(dir, opts) {
1612
3407
  throw new Error(
1613
3408
  "No branch to validate on: pass --branch or run inside a git checkout / GitHub Actions."
1614
3409
  );
1615
- progress(`pushing ${dir} as ${opts.slug ?? "(pyproject name)"}@${branch}\u2026`);
3410
+ const slug = pushSlug(dir, opts.slug);
3411
+ progress(`pushing ${dir} as ${slug}@${branch}\u2026`);
1616
3412
  let tipVersionId = null;
1617
- if (opts.slug) {
1618
- try {
1619
- const tip = await apiRequest(
1620
- options,
1621
- "POST",
1622
- "/api/public/benchmark-containers/resolve-version",
1623
- { slug: opts.slug, ref: branch }
1624
- );
1625
- tipVersionId = tip.versionId ?? null;
1626
- } catch {
1627
- tipVersionId = null;
1628
- }
3413
+ try {
3414
+ const tip = await apiRequest(
3415
+ options,
3416
+ "POST",
3417
+ "/api/public/benchmark-containers/resolve-version",
3418
+ { slug, ref: branch }
3419
+ );
3420
+ tipVersionId = tip.versionId ?? null;
3421
+ } catch {
3422
+ tipVersionId = null;
1629
3423
  }
1630
3424
  const pushed = await push(dir, {
1631
- slug: opts.slug,
3425
+ slug,
1632
3426
  branch,
1633
3427
  baseVersionId: tipVersionId,
1634
3428
  message: `PR validation push (${provenance.commit?.slice(0, 12) ?? "local"})`,
@@ -2056,11 +3850,11 @@ function applyTransforms(value, chain) {
2056
3850
  for (const step of steps) out = step(out);
2057
3851
  return out;
2058
3852
  }
2059
- var import_node_crypto3, WHITESPACE, WHITESPACE_EDGES, WHITESPACE_RUN, NOT_DIGIT, STRIP_PREFIX, trim, emailLocalPart, emailDomain, stripPrefix, hex, SIMPLE, TRANSFORMS, text;
3853
+ var import_node_crypto5, WHITESPACE, WHITESPACE_EDGES, WHITESPACE_RUN, NOT_DIGIT, STRIP_PREFIX, trim, emailLocalPart, emailDomain, stripPrefix, hex, SIMPLE, TRANSFORMS, text;
2060
3854
  var init_transforms = __esm({
2061
3855
  "src/worlds/transforms.ts"() {
2062
3856
  "use strict";
2063
- import_node_crypto3 = require("crypto");
3857
+ import_node_crypto5 = require("crypto");
2064
3858
  init_json();
2065
3859
  WHITESPACE = " \n\r\f\v";
2066
3860
  WHITESPACE_EDGES = /^[ \t\n\r\f\v]+|[ \t\n\r\f\v]+$/g;
@@ -2077,7 +3871,7 @@ var init_transforms = __esm({
2077
3871
  return at === -1 ? "" : value.slice(at + 1).toLowerCase();
2078
3872
  };
2079
3873
  stripPrefix = (prefix) => (value) => value.startsWith(prefix) ? value.slice(prefix.length) : value;
2080
- hex = (algorithm, value) => (0, import_node_crypto3.createHash)(algorithm).update(value, "utf8").digest("hex");
3874
+ hex = (algorithm, value) => (0, import_node_crypto5.createHash)(algorithm).update(value, "utf8").digest("hex");
2081
3875
  SIMPLE = {
2082
3876
  lower: (value) => value.toLowerCase(),
2083
3877
  upper: (value) => value.toUpperCase(),
@@ -2109,7 +3903,7 @@ function pyText(value) {
2109
3903
  return pyFloatRepr(value);
2110
3904
  }
2111
3905
  function hashForm(slug, plaintext) {
2112
- return "sha256:" + (0, import_node_crypto4.createHash)("sha256").update(`${slug}:${pyText(plaintext)}`, "utf8").digest("hex");
3906
+ return "sha256:" + (0, import_node_crypto6.createHash)("sha256").update(`${slug}:${pyText(plaintext)}`, "utf8").digest("hex");
2113
3907
  }
2114
3908
  function preserveForm(slug, plaintext) {
2115
3909
  const kind = typeof plaintext === "string" ? "str" : isInt(plaintext) ? "int" : "float";
@@ -2118,12 +3912,12 @@ function preserveForm(slug, plaintext) {
2118
3912
  }
2119
3913
  function shapeText(slug, text2, kind) {
2120
3914
  const seed = Buffer.from(`${slug}:${text2}`, "utf8");
2121
- let digest = (0, import_node_crypto4.createHash)("sha256").update(seed).digest();
3915
+ let digest = (0, import_node_crypto6.createHash)("sha256").update(seed).digest();
2122
3916
  let cursor = 0;
2123
3917
  const out = [];
2124
3918
  for (const char of text2) {
2125
3919
  if (cursor === digest.length) {
2126
- digest = (0, import_node_crypto4.createHash)("sha256").update(Buffer.concat([digest, seed])).digest();
3920
+ digest = (0, import_node_crypto6.createHash)("sha256").update(Buffer.concat([digest, seed])).digest();
2127
3921
  cursor = 0;
2128
3922
  }
2129
3923
  const byte = digest[cursor];
@@ -2160,11 +3954,11 @@ function storedForms(world, field, plaintext, transform) {
2160
3954
  if (policy !== null) return [roundForm(plaintext, world.redact.round[field])];
2161
3955
  return [plaintext];
2162
3956
  }
2163
- var import_node_crypto4, isInt;
3957
+ var import_node_crypto6, isInt;
2164
3958
  var init_redaction = __esm({
2165
3959
  "src/worlds/redaction.ts"() {
2166
3960
  "use strict";
2167
- import_node_crypto4 = require("crypto");
3961
+ import_node_crypto6 = require("crypto");
2168
3962
  init_json();
2169
3963
  init_transforms();
2170
3964
  isInt = (value) => typeof value === "number" && Number.isInteger(value);
@@ -2249,9 +4043,9 @@ var init_router = __esm({
2249
4043
  });
2250
4044
 
2251
4045
  // src/cli/config.ts
2252
- async function api(creds, method, route, body, init = {}) {
4046
+ async function api(creds, method, route, body, init2 = {}) {
2253
4047
  const controller = new AbortController();
2254
- const timer = setTimeout(() => controller.abort(), init.timeoutMs ?? 12e4);
4048
+ const timer = setTimeout(() => controller.abort(), init2.timeoutMs ?? 12e4);
2255
4049
  try {
2256
4050
  const res = await fetch(`${creds.host}${route}`, {
2257
4051
  method,
@@ -2270,13 +4064,13 @@ async function api(creds, method, route, body, init = {}) {
2270
4064
  clearTimeout(timer);
2271
4065
  }
2272
4066
  }
2273
- var fs2, os, path2, ApiError;
4067
+ var fs3, os, path3, ApiError;
2274
4068
  var init_config = __esm({
2275
4069
  "src/cli/config.ts"() {
2276
4070
  "use strict";
2277
- fs2 = __toESM(require("fs"));
4071
+ fs3 = __toESM(require("fs"));
2278
4072
  os = __toESM(require("os"));
2279
- path2 = __toESM(require("path"));
4073
+ path3 = __toESM(require("path"));
2280
4074
  init_router();
2281
4075
  ApiError = class extends CliError {
2282
4076
  constructor(status, method, route, text2) {
@@ -2305,16 +4099,16 @@ function runtimeRoot() {
2305
4099
  const candidates = [];
2306
4100
  if (process.env.GATEWAY_RUNTIME_PATH)
2307
4101
  candidates.push(process.env.GATEWAY_RUNTIME_PATH);
2308
- const entry = process.argv[1] && fs3.existsSync(process.argv[1]) ? path3.dirname(fs3.realpathSync(process.argv[1])) : null;
4102
+ const entry = process.argv[1] && fs4.existsSync(process.argv[1]) ? path4.dirname(fs4.realpathSync(process.argv[1])) : null;
2309
4103
  if (entry) {
2310
- candidates.push(path3.resolve(entry, "..", "runtime"));
2311
- candidates.push(path3.resolve(entry, "..", "..", "runtime"));
2312
- candidates.push(path3.resolve(entry, "..", "..", "sdk", "src"));
4104
+ candidates.push(path4.resolve(entry, "..", "runtime"));
4105
+ candidates.push(path4.resolve(entry, "..", "..", "runtime"));
4106
+ candidates.push(path4.resolve(entry, "..", "..", "sdk", "src"));
2313
4107
  }
2314
- candidates.push(path3.resolve(process.cwd(), "runtime"));
4108
+ candidates.push(path4.resolve(process.cwd(), "runtime"));
2315
4109
  for (const root of candidates)
2316
- if (fs3.existsSync(
2317
- path3.join(root, "gatewaysdk", "environment", "schema", "platform.py")
4110
+ if (fs4.existsSync(
4111
+ path4.join(root, "gatewaysdk", "environment", "schema", "platform.py")
2318
4112
  ))
2319
4113
  return root;
2320
4114
  return null;
@@ -2455,14 +4249,14 @@ async function localBridge(request, local, opts = {}) {
2455
4249
  child.stdin.end(input);
2456
4250
  });
2457
4251
  }
2458
- var import_node_child_process, fs3, net, path3, MIN_PYTHON, DIAGNOSTIC_TAIL, BRIDGE_BOOTSTRAP, pythonCache, pythonProbes, PYTHON_CANDIDATES, UV_FIND;
4252
+ var import_node_child_process, fs4, net, path4, MIN_PYTHON, DIAGNOSTIC_TAIL, BRIDGE_BOOTSTRAP, pythonCache, pythonProbes, PYTHON_CANDIDATES, UV_FIND;
2459
4253
  var init_local = __esm({
2460
4254
  "src/cli/runtime/local.ts"() {
2461
4255
  "use strict";
2462
4256
  import_node_child_process = require("child_process");
2463
- fs3 = __toESM(require("fs"));
4257
+ fs4 = __toESM(require("fs"));
2464
4258
  net = __toESM(require("net"));
2465
- path3 = __toESM(require("path"));
4259
+ path4 = __toESM(require("path"));
2466
4260
  init_router();
2467
4261
  init_config();
2468
4262
  MIN_PYTHON = [3, 11];
@@ -2490,12 +4284,12 @@ function isBuildOutput(relPath) {
2490
4284
  return BUILD_OUTPUT.test(relPath);
2491
4285
  }
2492
4286
  function readWorldFiles(dir, opts = {}) {
2493
- if (!fs4.existsSync(dir) || !fs4.statSync(dir).isDirectory())
4287
+ if (!fs5.existsSync(dir) || !fs5.statSync(dir).isDirectory())
2494
4288
  throw new CliError(`Not a directory: ${dir}`);
2495
4289
  const out = [];
2496
4290
  const walk = (rel) => {
2497
- const abs = rel ? path4.join(dir, rel) : dir;
2498
- const entries = fs4.readdirSync(abs, { withFileTypes: true });
4291
+ const abs = rel ? path5.join(dir, rel) : dir;
4292
+ const entries = fs5.readdirSync(abs, { withFileTypes: true });
2499
4293
  entries.sort((a, b) => a.name.localeCompare(b.name));
2500
4294
  for (const entry of entries) {
2501
4295
  const childRel = rel ? `${rel}/${entry.name}` : entry.name;
@@ -2505,7 +4299,7 @@ function readWorldFiles(dir, opts = {}) {
2505
4299
  if (!opts.buildOutputs && isBuildOutput(childRel)) continue;
2506
4300
  out.push({
2507
4301
  path: childRel,
2508
- content: fs4.readFileSync(path4.join(dir, childRel)).toString("base64")
4302
+ content: fs5.readFileSync(path5.join(dir, childRel)).toString("base64")
2509
4303
  });
2510
4304
  }
2511
4305
  }
@@ -2520,19 +4314,19 @@ function assertSafeRelPath(rel) {
2520
4314
  }
2521
4315
  function writeWorldFiles(dir, files, opts = {}) {
2522
4316
  for (const file of files) assertSafeRelPath(file.path);
2523
- if (opts.clean && fs4.existsSync(dir)) {
4317
+ if (opts.clean && fs5.existsSync(dir)) {
2524
4318
  const keep = new Set(files.map((f) => f.path));
2525
4319
  for (const existing of readWorldFiles(dir)) {
2526
- if (!keep.has(existing.path)) fs4.rmSync(path4.join(dir, existing.path));
4320
+ if (!keep.has(existing.path)) fs5.rmSync(path5.join(dir, existing.path));
2527
4321
  }
2528
4322
  pruneEmptyDirs(dir);
2529
4323
  }
2530
- fs4.mkdirSync(dir, { recursive: true });
4324
+ fs5.mkdirSync(dir, { recursive: true });
2531
4325
  const written = [];
2532
4326
  for (const file of files) {
2533
- const target = path4.join(dir, file.path);
2534
- fs4.mkdirSync(path4.dirname(target), { recursive: true });
2535
- fs4.writeFileSync(target, Buffer.from(file.content, "base64"));
4327
+ const target = path5.join(dir, file.path);
4328
+ fs5.mkdirSync(path5.dirname(target), { recursive: true });
4329
+ fs5.writeFileSync(target, Buffer.from(file.content, "base64"));
2536
4330
  written.push(file.path);
2537
4331
  }
2538
4332
  return written;
@@ -2540,14 +4334,14 @@ function writeWorldFiles(dir, files, opts = {}) {
2540
4334
  function pruneEmptyDirs(root) {
2541
4335
  const walk = (abs) => {
2542
4336
  let empty = true;
2543
- for (const entry of fs4.readdirSync(abs, { withFileTypes: true })) {
2544
- const child = path4.join(abs, entry.name);
4337
+ for (const entry of fs5.readdirSync(abs, { withFileTypes: true })) {
4338
+ const child = path5.join(abs, entry.name);
2545
4339
  if (entry.isDirectory()) {
2546
4340
  if (SKIP_DIRS2.has(entry.name)) {
2547
4341
  empty = false;
2548
4342
  continue;
2549
4343
  }
2550
- if (walk(child)) fs4.rmdirSync(child);
4344
+ if (walk(child)) fs5.rmdirSync(child);
2551
4345
  else empty = false;
2552
4346
  } else empty = false;
2553
4347
  }
@@ -2611,12 +4405,12 @@ async function runtime(creds, request, opts = {}) {
2611
4405
  clearTimeout(timer);
2612
4406
  }
2613
4407
  }
2614
- var fs4, path4, SKIP_DIRS2, BUILD_OUTPUT, BridgeRejected;
4408
+ var fs5, path5, SKIP_DIRS2, BUILD_OUTPUT, BridgeRejected;
2615
4409
  var init_client = __esm({
2616
4410
  "src/cli/runtime/client.ts"() {
2617
4411
  "use strict";
2618
- fs4 = __toESM(require("fs"));
2619
- path4 = __toESM(require("path"));
4412
+ fs5 = __toESM(require("fs"));
4413
+ path5 = __toESM(require("path"));
2620
4414
  init_router();
2621
4415
  init_local();
2622
4416
  SKIP_DIRS2 = /* @__PURE__ */ new Set(["__pycache__", ".git", "node_modules", ".gateway"]);
@@ -2666,7 +4460,7 @@ function dropBuildOutputs(dir) {
2666
4460
  const dropped = [];
2667
4461
  for (const file of readWorldFiles(dir, { buildOutputs: true })) {
2668
4462
  if (!BUILD_OUTPUT2.test(file.path)) continue;
2669
- fs5.rmSync(path5.join(dir, file.path), { force: true });
4463
+ fs6.rmSync(path6.join(dir, file.path), { force: true });
2670
4464
  dropped.push(file.path);
2671
4465
  }
2672
4466
  return dropped;
@@ -2732,7 +4526,7 @@ async function queryLocalWorldDataAcross(dir, entity, where, opts) {
2732
4526
  const payload = await localBridge(
2733
4527
  {
2734
4528
  command: "query",
2735
- world: path5.resolve(dir),
4529
+ world: path6.resolve(dir),
2736
4530
  entity,
2737
4531
  across: true,
2738
4532
  ...opts.compare ? { compare: true } : {},
@@ -2779,12 +4573,12 @@ async function ingestLocalToolCalls(dir, records, opts, creds) {
2779
4573
  ...res.batch !== void 0 ? { batch: res.batch } : {}
2780
4574
  };
2781
4575
  }
2782
- var fs5, path5, BUILD_OUTPUT2;
4576
+ var fs6, path6, BUILD_OUTPUT2;
2783
4577
  var init_data = __esm({
2784
4578
  "src/cli/runtime/data.ts"() {
2785
4579
  "use strict";
2786
- fs5 = __toESM(require("fs"));
2787
- path5 = __toESM(require("path"));
4580
+ fs6 = __toESM(require("fs"));
4581
+ path6 = __toESM(require("path"));
2788
4582
  init_router();
2789
4583
  init_client();
2790
4584
  init_local();
@@ -2827,27 +4621,27 @@ function typescriptPrefix() {
2827
4621
  }
2828
4622
  }
2829
4623
  function command(script, wrapperDir) {
2830
- const suffix = path6.extname(script).toLowerCase();
4624
+ const suffix = path7.extname(script).toLowerCase();
2831
4625
  if (PYTHON_SUFFIXES.includes(suffix)) return { file: process.env.GATEWAY_PYTHON || "python3", args: ["-c", PY_WRAPPER, script] };
2832
4626
  if (NODE_SUFFIXES.includes(suffix)) {
2833
- const wrapper = path6.join(wrapperDir, "transform-wrapper.mjs");
2834
- fs6.writeFileSync(wrapper, NODE_WRAPPER);
4627
+ const wrapper = path7.join(wrapperDir, "transform-wrapper.mjs");
4628
+ fs7.writeFileSync(wrapper, NODE_WRAPPER);
2835
4629
  const flags = suffix === ".ts" || suffix === ".mts" ? typescriptPrefix() : [];
2836
4630
  return { file: process.env.GATEWAY_NODE || process.execPath, args: [...flags, wrapper, script] };
2837
4631
  }
2838
- throw new CliError(`${path6.basename(script)}: a transform script is .py, .ts, .mjs, .js or .cjs`, 1);
4632
+ throw new CliError(`${path7.basename(script)}: a transform script is .py, .ts, .mjs, .js or .cjs`, 1);
2839
4633
  }
2840
4634
  async function runTransform(script, records, opts = {}) {
2841
- if (!fs6.existsSync(script) || !fs6.statSync(script).isFile()) throw new CliError(`no transform script at ${script}`, 1);
2842
- const resolved = path6.resolve(script);
2843
- const name = path6.basename(script);
4635
+ if (!fs7.existsSync(script) || !fs7.statSync(script).isFile()) throw new CliError(`no transform script at ${script}`, 1);
4636
+ const resolved = path7.resolve(script);
4637
+ const name = path7.basename(script);
2844
4638
  const timeoutMs = opts.timeoutMs ?? DEFAULT_TRANSFORM_TIMEOUT_MS;
2845
- const scratch = fs6.mkdtempSync(path6.join(os2.tmpdir(), "gateway-transform-"));
4639
+ const scratch = fs7.mkdtempSync(path7.join(os2.tmpdir(), "gateway-transform-"));
2846
4640
  try {
2847
4641
  const { file, args } = command(resolved, scratch);
2848
4642
  const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !SCRUBBED.test(key)));
2849
4643
  const done = await new Promise((resolve6, reject) => {
2850
- const child = (0, import_node_child_process2.spawn)(file, args, { cwd: path6.dirname(resolved), env, stdio: ["pipe", "pipe", "pipe"] });
4644
+ const child = (0, import_node_child_process2.spawn)(file, args, { cwd: path7.dirname(resolved), env, stdio: ["pipe", "pipe", "pipe"] });
2851
4645
  let stdout = "";
2852
4646
  let stderr = "";
2853
4647
  let timedOut = false;
@@ -2878,21 +4672,21 @@ async function runTransform(script, records, opts = {}) {
2878
4672
  }
2879
4673
  return { rows: checkRows(value, name), stderr: done.stderr };
2880
4674
  } finally {
2881
- fs6.rmSync(scratch, { recursive: true, force: true });
4675
+ fs7.rmSync(scratch, { recursive: true, force: true });
2882
4676
  }
2883
4677
  }
2884
4678
  async function transformRecords(transform, records, opts = {}) {
2885
4679
  if (typeof transform === "function") return { rows: checkRows(await transform(records), "transform(records)"), stderr: "" };
2886
4680
  return runTransform(transform, records, opts);
2887
4681
  }
2888
- var import_node_child_process2, fs6, os2, path6, import_node_module, import_meta, DEFAULT_TRANSFORM_TIMEOUT_MS, NODE_SUFFIXES, PYTHON_SUFFIXES, SCRUBBED, PY_WRAPPER, NODE_WRAPPER, isObject, tail;
4682
+ var import_node_child_process2, fs7, os2, path7, import_node_module, import_meta, DEFAULT_TRANSFORM_TIMEOUT_MS, NODE_SUFFIXES, PYTHON_SUFFIXES, SCRUBBED, PY_WRAPPER, NODE_WRAPPER, isObject, tail;
2889
4683
  var init_transform = __esm({
2890
4684
  "src/cli/platform/worldData/transform.ts"() {
2891
4685
  "use strict";
2892
4686
  import_node_child_process2 = require("child_process");
2893
- fs6 = __toESM(require("fs"));
4687
+ fs7 = __toESM(require("fs"));
2894
4688
  os2 = __toESM(require("os"));
2895
- path6 = __toESM(require("path"));
4689
+ path7 = __toESM(require("path"));
2896
4690
  import_node_module = require("module");
2897
4691
  init_router();
2898
4692
  import_meta = {};
@@ -2980,7 +4774,7 @@ function uploadHeadersFor(gz) {
2980
4774
  return {
2981
4775
  "content-type": "application/gzip",
2982
4776
  "content-length": String(gz.length),
2983
- "x-amz-checksum-sha256": (0, import_node_crypto5.createHash)("sha256").update(gz).digest("base64")
4777
+ "x-amz-checksum-sha256": (0, import_node_crypto7.createHash)("sha256").update(gz).digest("base64")
2984
4778
  };
2985
4779
  }
2986
4780
  async function forEachLimited(items, limit, fn) {
@@ -3026,12 +4820,12 @@ function phaseLine(status) {
3026
4820
  const phase = status.progress?.phase;
3027
4821
  return phase ? `${status.state} (${phase})` : status.state;
3028
4822
  }
3029
- var import_node_crypto5, fs7, TERMINAL_STATES, sleepMs, WorldDataApi;
4823
+ var import_node_crypto7, fs8, TERMINAL_STATES, sleepMs, WorldDataApi;
3030
4824
  var init_batches = __esm({
3031
4825
  "src/cli/platform/worldData/batches.ts"() {
3032
4826
  "use strict";
3033
- import_node_crypto5 = require("crypto");
3034
- fs7 = __toESM(require("fs"));
4827
+ import_node_crypto7 = require("crypto");
4828
+ fs8 = __toESM(require("fs"));
3035
4829
  init_config();
3036
4830
  init_router();
3037
4831
  TERMINAL_STATES = /* @__PURE__ */ new Set(["applied", "refused", "published", "failed"]);
@@ -3121,7 +4915,7 @@ async function* buildChunks(rows, plan) {
3121
4915
  let rawBytes = 0;
3122
4916
  let ordinal = 0;
3123
4917
  let seen = 0;
3124
- const flush = () => {
4918
+ const flush2 = () => {
3125
4919
  const raw = Buffer.concat(lines);
3126
4920
  const built = finishChunk(ordinal++, raw, lines.length, plan.entity, seen - lines.length);
3127
4921
  lines = [];
@@ -3131,23 +4925,23 @@ async function* buildChunks(rows, plan) {
3131
4925
  for await (const row of rows) {
3132
4926
  const line = Buffer.from(chunkLine(row, plan.entity), "utf8");
3133
4927
  const full = lines.length > 0 && (plan.chunkRows !== null && lines.length >= plan.chunkRows || rawBytes + line.length > plan.chunkBytes);
3134
- if (full) yield flush();
4928
+ if (full) yield flush2();
3135
4929
  lines.push(line);
3136
4930
  rawBytes += line.length;
3137
4931
  seen++;
3138
4932
  }
3139
- if (lines.length) yield flush();
4933
+ if (lines.length) yield flush2();
3140
4934
  }
3141
4935
  function finishChunk(ordinal, raw, rows, entity, firstRow = 0) {
3142
4936
  const gz = gzipDeterministic(raw, { name: chunkName(ordinal) });
3143
4937
  return {
3144
4938
  ordinal,
3145
- digest: (0, import_node_crypto6.createHash)("sha256").update(gz).digest("hex"),
4939
+ digest: (0, import_node_crypto8.createHash)("sha256").update(gz).digest("hex"),
3146
4940
  bytes: gz.length,
3147
4941
  rows,
3148
4942
  entity,
3149
4943
  rawBytes: raw.length,
3150
- contentSha256: (0, import_node_crypto6.createHash)("sha256").update(raw).digest("hex"),
4944
+ contentSha256: (0, import_node_crypto8.createHash)("sha256").update(raw).digest("hex"),
3151
4945
  firstRow,
3152
4946
  gz
3153
4947
  };
@@ -3175,11 +4969,11 @@ function crc32(data) {
3175
4969
  for (let i = 0; i < data.length; i++) crc = table[(crc ^ data[i]) & 255] ^ crc >>> 8;
3176
4970
  return (crc ^ 4294967295) >>> 0;
3177
4971
  }
3178
- var import_node_crypto6, import_node_zlib2, DEFAULT_CHUNK_BYTES, GZIP_LEVEL, chunkName, table;
4972
+ var import_node_crypto8, import_node_zlib2, DEFAULT_CHUNK_BYTES, GZIP_LEVEL, chunkName, table;
3179
4973
  var init_chunker = __esm({
3180
4974
  "src/cli/platform/worldData/chunker.ts"() {
3181
4975
  "use strict";
3182
- import_node_crypto6 = require("crypto");
4976
+ import_node_crypto8 = require("crypto");
3183
4977
  import_node_zlib2 = require("zlib");
3184
4978
  init_json();
3185
4979
  DEFAULT_CHUNK_BYTES = 64 * 1024 * 1024;
@@ -3252,7 +5046,7 @@ function parseToolCallRecord(raw) {
3252
5046
  }
3253
5047
  function readToolCallRecords(paths) {
3254
5048
  const records = [];
3255
- for (const file of paths) records.push(...toolCallRecordsIn(fs8.readFileSync(file, "utf8"), file));
5049
+ for (const file of paths) records.push(...toolCallRecordsIn(fs9.readFileSync(file, "utf8"), file));
3256
5050
  return records;
3257
5051
  }
3258
5052
  function toolCallRecordsIn(text2, where) {
@@ -3288,7 +5082,7 @@ async function emit(sink, record) {
3288
5082
  return;
3289
5083
  }
3290
5084
  if (typeof sink === "string") {
3291
- fs8.appendFileSync(sink, JSON.stringify(record) + "\n");
5085
+ fs9.appendFileSync(sink, JSON.stringify(record) + "\n");
3292
5086
  return;
3293
5087
  }
3294
5088
  if (typeof sink === "function") {
@@ -3377,7 +5171,7 @@ async function ingest(world, records, options = {}) {
3377
5171
  const mode = options.mode ?? "append";
3378
5172
  const dryRun = Boolean(options.dryRun);
3379
5173
  const creds = credentialsOf(options);
3380
- const local = fs8.existsSync(world) && fs8.statSync(world).isDirectory();
5174
+ const local = fs9.existsSync(world) && fs9.statSync(world).isDirectory();
3381
5175
  const map = options.map === void 0 ? void 0 : options.map;
3382
5176
  let rows = null;
3383
5177
  let stderr = "";
@@ -3393,9 +5187,9 @@ async function ingest(world, records, options = {}) {
3393
5187
  if (!creds) throw new Error("Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY (or pass publicKey/secretKey).");
3394
5188
  const { pull: pull2 } = await Promise.resolve().then(() => (init_hub(), hub_exports));
3395
5189
  const slug = world.split("@", 1)[0];
3396
- const scratch = fs8.mkdtempSync(path7.join(os3.tmpdir(), "gateway-ingest-"));
5190
+ const scratch = fs9.mkdtempSync(path8.join(os3.tmpdir(), "gateway-ingest-"));
3397
5191
  try {
3398
- const pulled = await pull2(world, path7.join(scratch, slug), options);
5192
+ const pulled = await pull2(world, path8.join(scratch, slug), options);
3399
5193
  let report;
3400
5194
  let projected;
3401
5195
  if (rows === null) {
@@ -3416,7 +5210,7 @@ async function ingest(world, records, options = {}) {
3416
5210
  if (status.entityCounts) report.entityCounts = status.entityCounts;
3417
5211
  return report;
3418
5212
  } finally {
3419
- fs8.rmSync(scratch, { recursive: true, force: true });
5213
+ fs9.rmSync(scratch, { recursive: true, force: true });
3420
5214
  }
3421
5215
  }
3422
5216
  async function ingestToolCalls(world, records, options = {}) {
@@ -3465,17 +5259,17 @@ async function sessionToolObservations(sessionId, options = {}) {
3465
5259
  `/api/public/sessions/${encodeURIComponent(sessionId)}?includeIO=true`
3466
5260
  );
3467
5261
  const out = [];
3468
- for (const trace of session.traces ?? [])
3469
- for (const observation of trace.observations ?? []) out.push({ traceId: trace.id ?? null, ...observation });
5262
+ for (const trace3 of session.traces ?? [])
5263
+ for (const observation of trace3.observations ?? []) out.push({ traceId: trace3.id ?? null, ...observation });
3470
5264
  return out;
3471
5265
  }
3472
- var fs8, os3, path7, isObject2, isoOf;
5266
+ var fs9, os3, path8, isObject2, isoOf;
3473
5267
  var init_ingest = __esm({
3474
5268
  "src/worlds/ingest.ts"() {
3475
5269
  "use strict";
3476
- fs8 = __toESM(require("fs"));
5270
+ fs9 = __toESM(require("fs"));
3477
5271
  os3 = __toESM(require("os"));
3478
- path7 = __toESM(require("path"));
5272
+ path8 = __toESM(require("path"));
3479
5273
  init_worlds();
3480
5274
  isObject2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3481
5275
  isoOf = (value) => value instanceof Date ? value.toISOString() : typeof value === "string" ? value : void 0;
@@ -3485,6 +5279,7 @@ var init_ingest = __esm({
3485
5279
  // src/worlds/index.ts
3486
5280
  var worlds_exports = {};
3487
5281
  __export(worlds_exports, {
5282
+ ApiError: () => ApiError2,
3488
5283
  BrowserActionRecorder: () => BrowserActionRecorder,
3489
5284
  COMPUTER_USE_SPECS: () => COMPUTER_USE_SPECS,
3490
5285
  DEFAULT_BRANCH: () => DEFAULT_BRANCH,
@@ -3492,9 +5287,12 @@ __export(worlds_exports, {
3492
5287
  EVENT_BATCH_SIZE: () => EVENT_BATCH_SIZE,
3493
5288
  EVENT_FLUSH_INTERVAL_MS: () => EVENT_FLUSH_INTERVAL_MS,
3494
5289
  EVENT_MAX_RETRIES: () => EVENT_MAX_RETRIES,
5290
+ GatewayEvalsClient: () => GatewayEvalsClient,
3495
5291
  STRIP_PREFIX: () => STRIP_PREFIX,
3496
5292
  SURFACE_KINDS: () => SURFACE_KINDS,
3497
5293
  TRANSFORMS: () => TRANSFORMS,
5294
+ TaskRun: () => TaskRun,
5295
+ TaskSessions: () => TaskSessions,
3498
5296
  WHITESPACE: () => WHITESPACE,
3499
5297
  WorldBrowser: () => WorldBrowser,
3500
5298
  WorldSession: () => WorldSession,
@@ -3503,9 +5301,12 @@ __export(worlds_exports, {
3503
5301
  WorldSet: () => WorldSet,
3504
5302
  WorldSurfaceUnavailable: () => WorldSurfaceUnavailable,
3505
5303
  WorldTask: () => WorldTask,
5304
+ aggregateTaskGrade: () => aggregateTaskGrade,
3506
5305
  apiRequest: () => apiRequest,
3507
5306
  applyTransforms: () => applyTransforms,
5307
+ attachManifest: () => attachManifest,
3508
5308
  attachSession: () => attachSession,
5309
+ attachTask: () => attachTask,
3509
5310
  buildSourceTarball: () => buildSourceTarball,
3510
5311
  captureToolCalls: () => captureToolCalls,
3511
5312
  collectArchiveRelPaths: () => collectArchiveRelPaths,
@@ -3524,15 +5325,19 @@ __export(worlds_exports, {
3524
5325
  ingestToolCalls: () => ingestToolCalls,
3525
5326
  isIncludedInContentHash: () => isIncludedInContentHash,
3526
5327
  isTaskIdRef: () => isTaskIdRef,
5328
+ isTaskManifest: () => isTaskManifest,
3527
5329
  isTaskSpec: () => isTaskSpec,
3528
5330
  listEnvSecretKeys: () => listEnvSecretKeys,
3529
5331
  listRunConfigs: () => listRunConfigs,
5332
+ listTaskSessions: () => listTaskSessions,
3530
5333
  listTasks: () => listTasks,
3531
5334
  localTreeState: () => localTreeState,
3532
5335
  migrateProjectWorlds: () => migrateProjectWorlds,
3533
5336
  migrateWorld: () => migrateWorld,
5337
+ modelToolName: () => modelToolName,
3534
5338
  openBrowser: () => openBrowser,
3535
5339
  openSession: () => openSession,
5340
+ openTask: () => openTask,
3536
5341
  openWorld: () => openWorld,
3537
5342
  parseToolCallRecord: () => parseToolCallRecord,
3538
5343
  parseTransform: () => parseTransform,
@@ -3541,6 +5346,7 @@ __export(worlds_exports, {
3541
5346
  propose: () => propose,
3542
5347
  pull: () => pull,
3543
5348
  push: () => push,
5349
+ pushSlug: () => pushSlug,
3544
5350
  pyText: () => pyText,
3545
5351
  queryRows: () => queryRows,
3546
5352
  queryRowsSearch: () => queryRowsSearch,
@@ -3551,6 +5357,7 @@ __export(worlds_exports, {
3551
5357
  resolveBrowserMode: () => resolveBrowserMode,
3552
5358
  roundForm: () => roundForm,
3553
5359
  runSessions: () => runSessions,
5360
+ runTask: () => runTask,
3554
5361
  schemaFromSignature: () => schemaFromSignature,
3555
5362
  sessionToolObservations: () => sessionToolObservations,
3556
5363
  setEnvSecret: () => setEnvSecret,
@@ -3583,9 +5390,9 @@ function resolveEnv(options) {
3583
5390
  }
3584
5391
  return { host: host.replace(/\/+$/, ""), publicKey, secretKey };
3585
5392
  }
3586
- async function apiRequest(options, method, path8, body) {
5393
+ async function apiRequest(options, method, path9, body) {
3587
5394
  const { host, publicKey, secretKey } = resolveEnv(options);
3588
- const res = await fetch(`${host}${path8}`, {
5395
+ const res = await fetch(`${host}${path9}`, {
3589
5396
  method,
3590
5397
  headers: {
3591
5398
  "content-type": "application/json",
@@ -3594,11 +5401,7 @@ async function apiRequest(options, method, path8, body) {
3594
5401
  ...body === void 0 ? {} : { body: JSON.stringify(body) }
3595
5402
  });
3596
5403
  const text2 = await res.text();
3597
- if (!res.ok) {
3598
- throw new Error(
3599
- `${method} ${path8} -> ${res.status}: ${text2.slice(0, 400)}`
3600
- );
3601
- }
5404
+ if (!res.ok) throw new ApiError2(res.status, method, path9, text2.slice(0, 400));
3602
5405
  return JSON.parse(text2);
3603
5406
  }
3604
5407
  async function setEnvSecret(slug, key, value, options = {}) {
@@ -3750,11 +5553,14 @@ async function openWorld(slugRef, options = {}) {
3750
5553
  }
3751
5554
  return world;
3752
5555
  }
3753
- var WorldTask, WorldSet;
5556
+ var ApiError2, WorldTask, WorldSet;
3754
5557
  var init_worlds = __esm({
3755
5558
  "src/worlds/index.ts"() {
3756
5559
  init_session();
3757
5560
  init_tasks();
5561
+ init_taskSessions();
5562
+ init_taskRun();
5563
+ init_evals();
3758
5564
  init_browser();
3759
5565
  init_hub();
3760
5566
  init_validate();
@@ -3764,6 +5570,13 @@ var init_worlds = __esm({
3764
5570
  init_query();
3765
5571
  init_migrate();
3766
5572
  init_ingest();
5573
+ ApiError2 = class extends Error {
5574
+ constructor(status, method, path9, body) {
5575
+ super(`${method} ${path9} -> ${status}: ${body}`);
5576
+ this.status = status;
5577
+ this.name = "ApiError";
5578
+ }
5579
+ };
3767
5580
  WorldTask = class {
3768
5581
  constructor(world, name, variant) {
3769
5582
  this.world = world;
@@ -3831,6 +5644,7 @@ var init_worlds = __esm({
3831
5644
  init_worlds();
3832
5645
  // Annotate the CommonJS export names for ESM import in node:
3833
5646
  0 && (module.exports = {
5647
+ ApiError,
3834
5648
  BrowserActionRecorder,
3835
5649
  COMPUTER_USE_SPECS,
3836
5650
  DEFAULT_BRANCH,
@@ -3838,9 +5652,12 @@ init_worlds();
3838
5652
  EVENT_BATCH_SIZE,
3839
5653
  EVENT_FLUSH_INTERVAL_MS,
3840
5654
  EVENT_MAX_RETRIES,
5655
+ GatewayEvalsClient,
3841
5656
  STRIP_PREFIX,
3842
5657
  SURFACE_KINDS,
3843
5658
  TRANSFORMS,
5659
+ TaskRun,
5660
+ TaskSessions,
3844
5661
  WHITESPACE,
3845
5662
  WorldBrowser,
3846
5663
  WorldSession,
@@ -3849,9 +5666,12 @@ init_worlds();
3849
5666
  WorldSet,
3850
5667
  WorldSurfaceUnavailable,
3851
5668
  WorldTask,
5669
+ aggregateTaskGrade,
3852
5670
  apiRequest,
3853
5671
  applyTransforms,
5672
+ attachManifest,
3854
5673
  attachSession,
5674
+ attachTask,
3855
5675
  buildSourceTarball,
3856
5676
  captureToolCalls,
3857
5677
  collectArchiveRelPaths,
@@ -3870,15 +5690,19 @@ init_worlds();
3870
5690
  ingestToolCalls,
3871
5691
  isIncludedInContentHash,
3872
5692
  isTaskIdRef,
5693
+ isTaskManifest,
3873
5694
  isTaskSpec,
3874
5695
  listEnvSecretKeys,
3875
5696
  listRunConfigs,
5697
+ listTaskSessions,
3876
5698
  listTasks,
3877
5699
  localTreeState,
3878
5700
  migrateProjectWorlds,
3879
5701
  migrateWorld,
5702
+ modelToolName,
3880
5703
  openBrowser,
3881
5704
  openSession,
5705
+ openTask,
3882
5706
  openWorld,
3883
5707
  parseToolCallRecord,
3884
5708
  parseTransform,
@@ -3887,6 +5711,7 @@ init_worlds();
3887
5711
  propose,
3888
5712
  pull,
3889
5713
  push,
5714
+ pushSlug,
3890
5715
  pyText,
3891
5716
  queryRows,
3892
5717
  queryRowsSearch,
@@ -3897,6 +5722,7 @@ init_worlds();
3897
5722
  resolveBrowserMode,
3898
5723
  roundForm,
3899
5724
  runSessions,
5725
+ runTask,
3900
5726
  schemaFromSignature,
3901
5727
  sessionToolObservations,
3902
5728
  setEnvSecret,