@withgateway/sdk 0.2.3 → 0.2.5

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 (62) hide show
  1. package/dist/cli.js +13267 -5869
  2. package/dist/cli.js.map +1 -1
  3. package/dist/cli.mjs +13272 -5874
  4. package/dist/cli.mjs.map +1 -1
  5. package/dist/files/index.js +83 -31
  6. package/dist/files/index.js.map +1 -1
  7. package/dist/files/index.mjs +79 -28
  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 +6698 -1606
  22. package/dist/index.js.map +1 -1
  23. package/dist/index.mjs +6793 -1713
  24. package/dist/index.mjs.map +1 -1
  25. package/dist/traces/index.js +72 -20
  26. package/dist/traces/index.js.map +1 -1
  27. package/dist/traces/index.mjs +68 -17
  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 +47 -3
  32. package/dist/tracing/index.js.map +1 -1
  33. package/dist/tracing/index.mjs +42 -2
  34. package/dist/tracing/index.mjs.map +1 -1
  35. package/dist/worlds/index.d.mts +390 -27
  36. package/dist/worlds/index.d.ts +390 -27
  37. package/dist/worlds/index.js +2291 -366
  38. package/dist/worlds/index.js.map +1 -1
  39. package/dist/worlds/index.mjs +2281 -356
  40. package/dist/worlds/index.mjs.map +1 -1
  41. package/package.json +7 -1
  42. package/runtime/gatewaysdk/environment/_bundle.py +14 -24
  43. package/runtime/gatewaysdk/environment/_materialize.py +3 -3
  44. package/runtime/gatewaysdk/environment/schema/api.py +153 -20
  45. package/runtime/gatewaysdk/environment/schema/compiler.py +14 -0
  46. package/runtime/gatewaysdk/environment/schema/data.py +21 -19
  47. package/runtime/gatewaysdk/environment/schema/grading.py +225 -0
  48. package/runtime/gatewaysdk/environment/schema/host.py +171 -535
  49. package/runtime/gatewaysdk/environment/schema/ingest.py +3 -11
  50. package/runtime/gatewaysdk/environment/schema/local.py +32 -126
  51. package/runtime/gatewaysdk/environment/schema/platform.py +14 -22
  52. package/runtime/gatewaysdk/environment/schema/proof.py +237 -0
  53. package/runtime/gatewaysdk/environment/schema/runtime.py +686 -0
  54. package/runtime/gatewaysdk/environment/schema/skill.py +1 -0
  55. package/runtime/gatewaysdk/environment/schema/skills/hooks-getting-started/SKILL.md +156 -0
  56. package/runtime/gatewaysdk/environment/schema/snapshot.py +6 -5
  57. package/runtime/gatewaysdk/environment/schema/tasks.py +12 -2
  58. package/runtime/gatewaysdk/environment/schema/tools_world.py +75 -23
  59. package/runtime/gatewaysdk/environment/schema/verbs.py +136 -0
  60. package/runtime/gatewaysdk/environment/schema/workers.py +44 -13
  61. package/runtime/gatewaysdk/environment/world.py +391 -0
  62. package/skills/hooks-getting-started/SKILL.md +156 -0
@@ -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, path10) {
42
45
  const base = ui.url.replace(/\/+$/, "");
43
- const rel = path8.startsWith("/") ? path8 : `/${path8}`;
46
+ const rel = path10.startsWith("/") ? path10 : `/${path10}`;
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,18 +600,19 @@ 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 ref = at === -1 ? "" : slugOrRef.slice(at + 1);
604
+ const state2 = await apiRequest(
600
605
  options,
601
606
  "POST",
602
607
  "/api/public/world-sessions",
603
608
  {
604
- ...opts.versionId ? { versionId: opts.versionId } : { slug },
609
+ ...opts.versionId ? { versionId: opts.versionId } : { slug, ...ref && { ref } },
605
610
  task,
606
611
  ...opts.reuseWarm === void 0 ? {} : { reuseWarm: opts.reuseWarm },
607
612
  ...opts.surfaces?.length ? { surfaces: opts.surfaces } : {}
608
613
  }
609
614
  );
610
- return new WorldSession(state.sessionId, state, options);
615
+ return new WorldSession(state2.sessionId, state2, options);
611
616
  }
612
617
  async function runSessions(opts) {
613
618
  const options = opts.options ?? {};
@@ -800,18 +805,18 @@ var init_session = __esm({
800
805
  }
801
806
  /** The reporter `browser()` uses; exposed for a page you drive yourself. */
802
807
  browserRecorder(agentId) {
803
- const path8 = `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/browser-events`;
808
+ const path10 = `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/browser-events`;
804
809
  const id = agentId ?? process.env.GATEWAY_AGENT_ID ?? `agent-${(0, import_node_crypto.randomUUID)().replace(/-/g, "").slice(0, 8)}`;
805
810
  return new BrowserActionRecorder(
806
811
  async (events) => {
807
- await apiRequest(this.options, "POST", path8, { events });
812
+ await apiRequest(this.options, "POST", path10, { events });
808
813
  },
809
814
  id,
810
815
  {
811
816
  // Continue this agent's timeline where the platform has it, so the
812
817
  // same id reopened later never re-numbers from zero.
813
818
  resumeFrom: async () => {
814
- const summary = await apiRequest(this.options, "GET", path8);
819
+ const summary = await apiRequest(this.options, "GET", path10);
815
820
  return summary.agents.find((a) => a.agentId === id)?.nextSeq ?? 0;
816
821
  }
817
822
  }
@@ -844,15 +849,15 @@ var init_session = __esm({
844
849
  async ready(opts = {}) {
845
850
  const deadline = Date.now() + (opts.timeoutMs ?? READY_TIMEOUT_MS);
846
851
  for (; ; ) {
847
- const state = await this.status();
848
- if (state.ready) return state;
849
- if (state.state === "FAILED" || state.state === "STOPPED")
852
+ const state2 = await this.status();
853
+ if (state2.ready) return state2;
854
+ if (state2.state === "FAILED" || state2.state === "STOPPED")
850
855
  throw new WorldSessionCallError(
851
- `World session ${state.state.toLowerCase()} before it was ready.`
856
+ `World session ${state2.state.toLowerCase()} before it was ready.`
852
857
  );
853
858
  if (Date.now() > deadline)
854
859
  throw new WorldSessionTimeout(
855
- `World session still ${state.state} after ${Math.round((opts.timeoutMs ?? READY_TIMEOUT_MS) / 1e3)}s.`
860
+ `World session still ${state2.state} after ${Math.round((opts.timeoutMs ?? READY_TIMEOUT_MS) / 1e3)}s.`
856
861
  );
857
862
  await sleep(READY_POLL_MS);
858
863
  }
@@ -928,10 +933,12 @@ var init_session = __esm({
928
933
  * A rubric grade is finalized by the platform's judge, not the container:
929
934
  * the platform answers the enqueue with `pending: true`, and this waits on
930
935
  * the judge's budget (15 min) instead of a call's. `timeoutMs` overrides
931
- * either. */
936
+ * either. `report` is the agent's own account of what it did and found,
937
+ * handed to the judge as its claim beside the evidence (the state and the
938
+ * calls); assertions and python graders ignore it. */
932
939
  async grade(opts = {}) {
933
940
  const raw = await this.exchange(
934
- { kind: "grade" },
941
+ opts.report !== void 0 ? { kind: "grade", report: opts.report } : { kind: "grade" },
935
942
  opts.timeoutMs
936
943
  );
937
944
  const record = raw && typeof raw === "object" ? raw : {};
@@ -981,156 +988,2085 @@ var init_session = __esm({
981
988
  async reset(opts = {}) {
982
989
  await this.exchange({ kind: "reset" }, opts.timeoutMs);
983
990
  }
984
- /** The session's call log, oldest first: every tool call, seed, reset,
985
- * grade with its result — the record of the episode. */
986
- async export() {
987
- const calls = [];
988
- let cursor;
989
- do {
990
- const params = new URLSearchParams({ limit: String(EXPORT_PAGE) });
991
- if (cursor) params.set("cursor", cursor);
992
- const page = await apiRequest(
993
- this.options,
994
- "GET",
995
- `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls?${params.toString()}`
991
+ /** The session's call log, oldest first: every tool call, seed, reset,
992
+ * grade with its result — the record of the episode. */
993
+ async export() {
994
+ const calls = [];
995
+ let cursor;
996
+ do {
997
+ const params = new URLSearchParams({ limit: String(EXPORT_PAGE) });
998
+ if (cursor) params.set("cursor", cursor);
999
+ const page = await apiRequest(
1000
+ this.options,
1001
+ "GET",
1002
+ `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls?${params.toString()}`
1003
+ );
1004
+ for (const call of page.calls) {
1005
+ calls.push({
1006
+ seq: Number(call.seq),
1007
+ kind: String(call.kind ?? "call"),
1008
+ tool: typeof call.tool === "string" ? call.tool : null,
1009
+ args: call.args ?? null,
1010
+ result: call.result ?? null,
1011
+ error: typeof call.error === "string" ? call.error : null,
1012
+ completedAt: typeof call.completedAt === "string" ? call.completedAt : null
1013
+ });
1014
+ }
1015
+ cursor = page.nextCursor ?? void 0;
1016
+ } while (cursor);
1017
+ return calls;
1018
+ }
1019
+ /**
1020
+ * Promote this session's inline task into a stored task of the project
1021
+ * (version 1, pinned to the session's world unless `world` says otherwise),
1022
+ * so a task written for one end user can be reused and its grades
1023
+ * compared. The session then records the new task's id. A session on a
1024
+ * bundled task has nothing to save; one on a stored task is already saved.
1025
+ */
1026
+ async saveTask(opts = {}) {
1027
+ const task = await apiRequest(
1028
+ this.options,
1029
+ "POST",
1030
+ `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/task`,
1031
+ {
1032
+ ...opts.name !== void 0 ? { name: opts.name } : {},
1033
+ ...opts.world !== void 0 ? { world: opts.world } : {},
1034
+ ...opts.message !== void 0 ? { message: opts.message } : {}
1035
+ }
1036
+ );
1037
+ this.current = {
1038
+ ...this.current,
1039
+ taskName: task.name,
1040
+ task: {
1041
+ ...this.taskInfo,
1042
+ source: "stored",
1043
+ name: task.name,
1044
+ id: task.id,
1045
+ version: task.version
1046
+ }
1047
+ };
1048
+ return task;
1049
+ }
1050
+ /**
1051
+ * End the session. `keepWarm` hands the container back to the pool instead
1052
+ * of tearing it down, so the next session for the same task starts warm —
1053
+ * the pooled instance still obeys the fleet's idle TTL and pinning.
1054
+ */
1055
+ async close(opts = {}) {
1056
+ return apiRequest(
1057
+ this.options,
1058
+ "DELETE",
1059
+ `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}`,
1060
+ { keepWarm: opts.keepWarm ?? false }
1061
+ );
1062
+ }
1063
+ };
1064
+ }
1065
+ });
1066
+
1067
+ // src/worlds/tasks.ts
1068
+ async function createTask(input, options = {}) {
1069
+ return apiRequest(
1070
+ options,
1071
+ "POST",
1072
+ TASKS,
1073
+ compact({
1074
+ spec: input.spec,
1075
+ name: input.name,
1076
+ world: input.world,
1077
+ message: input.message
1078
+ })
1079
+ );
1080
+ }
1081
+ async function updateTask(taskId, input, options = {}) {
1082
+ if (input.spec === void 0 && input.name === void 0 && input.world === void 0)
1083
+ throw new Error("updateTask: nothing to update \u2014 pass spec, name or world");
1084
+ return apiRequest(
1085
+ options,
1086
+ "PATCH",
1087
+ taskRoute(taskId),
1088
+ compact({
1089
+ spec: input.spec,
1090
+ name: input.name,
1091
+ world: input.world,
1092
+ message: input.message
1093
+ })
1094
+ );
1095
+ }
1096
+ async function listTasks(filter = {}, options = {}) {
1097
+ const params = new URLSearchParams();
1098
+ if (filter.world) params.set("world", filter.world);
1099
+ if (filter.page !== void 0) params.set("page", String(filter.page));
1100
+ if (filter.limit !== void 0) params.set("limit", String(filter.limit));
1101
+ for (const [key, value] of Object.entries(filter.metadata ?? {}))
1102
+ params.set(`metadata.${key}`, value);
1103
+ const query = params.toString();
1104
+ return apiRequest(
1105
+ options,
1106
+ "GET",
1107
+ query ? `${TASKS}?${query}` : TASKS
1108
+ );
1109
+ }
1110
+ async function getTask(taskId, opts = {}, options = {}) {
1111
+ const query = opts.version === void 0 ? "" : `?version=${String(opts.version)}`;
1112
+ return apiRequest(
1113
+ options,
1114
+ "GET",
1115
+ `${taskRoute(taskId)}${query}`
1116
+ );
1117
+ }
1118
+ async function deleteTask(taskId, options = {}) {
1119
+ return apiRequest(options, "DELETE", taskRoute(taskId));
1120
+ }
1121
+ async function validateTask(taskId, target = {}, options = {}) {
1122
+ return apiRequest(
1123
+ options,
1124
+ "POST",
1125
+ `${taskRoute(taskId)}/validate`,
1126
+ compact({
1127
+ version: target.version,
1128
+ slug: target.slug,
1129
+ versionId: target.versionId
1130
+ })
1131
+ );
1132
+ }
1133
+ var TASKS, taskRoute, compact;
1134
+ var init_tasks = __esm({
1135
+ "src/worlds/tasks.ts"() {
1136
+ "use strict";
1137
+ init_worlds();
1138
+ TASKS = "/api/public/world-tasks";
1139
+ taskRoute = (id) => `${TASKS}/${encodeURIComponent(id)}`;
1140
+ compact = (body) => Object.fromEntries(Object.entries(body).filter(([, v]) => v !== void 0));
1141
+ }
1142
+ });
1143
+
1144
+ // src/worlds/taskSessions.ts
1145
+ function aggregateTaskGrade(worlds) {
1146
+ const rewards = {};
1147
+ const ungraded = [];
1148
+ const graded = [];
1149
+ for (const [alias, grade] of Object.entries(worlds)) {
1150
+ if (typeof grade.reward === "number") {
1151
+ rewards[alias] = grade.reward;
1152
+ graded.push(grade.reward);
1153
+ } else ungraded.push(alias);
1154
+ for (const [key, value] of Object.entries(grade.rewards))
1155
+ rewards[`${alias}.${key}`] = value;
1156
+ }
1157
+ const reward = graded.length > 0 ? graded.reduce((a, b) => a + b, 0) / graded.length : null;
1158
+ return { reward, rewards, worlds, ungraded };
1159
+ }
1160
+ function fromResponse(answer, options) {
1161
+ const sessions = {};
1162
+ const worlds = {};
1163
+ for (const [alias, state2] of Object.entries(answer.sessions)) {
1164
+ sessions[alias] = new WorldSession(state2.sessionId, state2, options);
1165
+ worlds[alias] = { slug: state2.slug, ref: state2.ref };
1166
+ }
1167
+ return new TaskSessions(
1168
+ answer.taskId,
1169
+ answer.taskVersion,
1170
+ answer.name,
1171
+ answer.instruction,
1172
+ sessions,
1173
+ worlds,
1174
+ answer.hash ?? null
1175
+ );
1176
+ }
1177
+ async function openTask(ref, opts = {}) {
1178
+ const options = opts.options ?? {};
1179
+ const task = typeof ref === "string" ? {
1180
+ id: ref,
1181
+ ...opts.version !== void 0 ? { version: opts.version } : {}
1182
+ } : isTaskIdRef(ref) && opts.version !== void 0 ? { ...ref, version: opts.version } : ref;
1183
+ if (isTaskIdRef(task) ? !task.id : !task.instruction)
1184
+ throw new Error(
1185
+ "openTask needs a task: a stored task id, { id, version? } or a spec with worlds"
1186
+ );
1187
+ if (!isTaskIdRef(task) && !task.worlds)
1188
+ throw new Error(
1189
+ "openTask needs a spec that names its worlds; a single-world spec opens with openSession"
1190
+ );
1191
+ const answer = await apiRequest(
1192
+ options,
1193
+ "POST",
1194
+ TASK_SESSIONS,
1195
+ {
1196
+ task,
1197
+ ...opts.reuseWarm === void 0 ? {} : { reuseWarm: opts.reuseWarm },
1198
+ ...opts.surfaces?.length ? { surfaces: opts.surfaces } : {}
1199
+ }
1200
+ );
1201
+ return fromResponse(answer, options);
1202
+ }
1203
+ async function listTaskSessions(taskId, options = {}) {
1204
+ const answer = await apiRequest(options, "GET", `${TASK_SESSIONS}?taskId=${encodeURIComponent(taskId)}`);
1205
+ return answer.sessions;
1206
+ }
1207
+ async function attachTask(taskId, options = {}) {
1208
+ const live = await listTaskSessions(taskId, options);
1209
+ if (live.length === 0)
1210
+ throw new Error(
1211
+ `task ${taskId} has no live sessions; run \`task up\` first`
1212
+ );
1213
+ const byAlias = /* @__PURE__ */ new Map();
1214
+ for (const session of live) {
1215
+ const alias = session.alias ?? session.sessionId;
1216
+ byAlias.set(alias, [...byAlias.get(alias) ?? [], session]);
1217
+ }
1218
+ const doubled = [...byAlias.entries()].filter(([, rows]) => rows.length > 1);
1219
+ if (doubled.length > 0)
1220
+ throw new Error(
1221
+ `task ${taskId} has more than one live session for ${doubled.map(
1222
+ ([alias, rows]) => `'${alias}' (${rows.map((r) => r.sessionId).join(", ")})`
1223
+ ).join(", ")}; pass the manifest from \`task up\`, or close the extras`
1224
+ );
1225
+ return attachManifest(
1226
+ {
1227
+ taskId,
1228
+ taskVersion: live[0].taskVersion,
1229
+ name: null,
1230
+ instruction: null,
1231
+ sessions: Object.fromEntries(
1232
+ [...byAlias.entries()].map(([alias, [row]]) => [
1233
+ alias,
1234
+ {
1235
+ slug: row.slug ?? "",
1236
+ ref: null,
1237
+ versionId: row.versionId,
1238
+ sessionId: row.sessionId,
1239
+ ready: row.ready,
1240
+ state: row.state,
1241
+ surfaces: ["tools"]
1242
+ }
1243
+ ])
1244
+ )
1245
+ },
1246
+ options
1247
+ );
1248
+ }
1249
+ async function attachManifest(manifest, options = {}) {
1250
+ const entries = await Promise.all(
1251
+ Object.entries(manifest.sessions).map(
1252
+ async ([alias, entry]) => [alias, await attachSession(entry.sessionId, options)]
1253
+ )
1254
+ );
1255
+ const sessions = Object.fromEntries(entries);
1256
+ const instruction = manifest.instruction ?? entries[0]?.[1].instruction ?? null;
1257
+ return new TaskSessions(
1258
+ manifest.taskId,
1259
+ manifest.taskVersion,
1260
+ manifest.name,
1261
+ instruction,
1262
+ sessions,
1263
+ Object.fromEntries(
1264
+ Object.entries(manifest.sessions).map(([alias, entry]) => [
1265
+ alias,
1266
+ { slug: entry.slug, ref: entry.ref }
1267
+ ])
1268
+ )
1269
+ );
1270
+ }
1271
+ function isTaskManifest(value) {
1272
+ return typeof value === "object" && value !== null && !Array.isArray(value) && typeof value.sessions === "object" && value.sessions !== null && !("instruction" in value && "worlds" in value);
1273
+ }
1274
+ var TASK_SESSIONS, manifestSession, TaskSessions;
1275
+ var init_taskSessions = __esm({
1276
+ "src/worlds/taskSessions.ts"() {
1277
+ "use strict";
1278
+ init_worlds();
1279
+ init_browser();
1280
+ init_session();
1281
+ TASK_SESSIONS = "/api/public/world-task-sessions";
1282
+ manifestSession = (s, state2, world) => ({
1283
+ slug: world.slug,
1284
+ ref: world.ref,
1285
+ versionId: state2.versionId,
1286
+ sessionId: state2.sessionId,
1287
+ ready: state2.ready,
1288
+ state: state2.state,
1289
+ surfaces: surfaceKinds(s),
1290
+ ...s.api ? {
1291
+ api: { url: s.api.url, ...s.api.token ? { token: s.api.token } : {} }
1292
+ } : {},
1293
+ ...s.ui ? {
1294
+ ui: {
1295
+ url: s.ui.url,
1296
+ entry: uiEntryUrl(s.ui),
1297
+ apiPath: s.ui.apiPath ?? null
1298
+ }
1299
+ } : {},
1300
+ ...s.browser ? { browser: { wsUrl: s.browser.wsUrl, viewport: s.browser.viewport } } : {}
1301
+ });
1302
+ TaskSessions = class {
1303
+ constructor(taskId, taskVersion, name, instruction, sessions, worlds, hash = null) {
1304
+ this.taskId = taskId;
1305
+ this.taskVersion = taskVersion;
1306
+ this.name = name;
1307
+ this.instruction = instruction;
1308
+ this.sessions = sessions;
1309
+ this.worlds = worlds;
1310
+ this.hash = hash;
1311
+ }
1312
+ /** This alias's `{slug, ref}` as recorded at open/attach — the world a
1313
+ * `TaskRun` filing needs to name, without exposing the whole map. */
1314
+ worldRef(alias) {
1315
+ return this.worlds[alias] ?? { slug: "", ref: null };
1316
+ }
1317
+ /** The aliases, in the spec's order. */
1318
+ get aliases() {
1319
+ return Object.keys(this.sessions);
1320
+ }
1321
+ /** The alias's session, or a clear error naming the aliases there are. */
1322
+ session(alias) {
1323
+ const session = this.sessions[alias];
1324
+ if (!session)
1325
+ throw new Error(
1326
+ `task has no world '${alias}'; its worlds are ${this.aliases.join(", ")}`
1327
+ );
1328
+ return session;
1329
+ }
1330
+ async each(fn) {
1331
+ const entries = await Promise.all(
1332
+ Object.entries(this.sessions).map(
1333
+ async ([alias, session]) => [alias, await fn(session, alias)]
1334
+ )
1335
+ );
1336
+ return Object.fromEntries(entries);
1337
+ }
1338
+ /** Wait until every world answers ready. A world that never does throws
1339
+ * `WorldSessionTimeout` naming it; the others are left up. */
1340
+ async ready(opts = {}) {
1341
+ await this.each((session) => session.ready(opts));
1342
+ }
1343
+ /** Every world's current state, keyed by alias. */
1344
+ async status() {
1345
+ return this.each((session) => session.status());
1346
+ }
1347
+ /** The manifest: where every world answers, keyed by alias. */
1348
+ async manifest() {
1349
+ const sessions = await this.each(
1350
+ async (session, alias) => manifestSession(
1351
+ await session.surfaces(),
1352
+ {
1353
+ sessionId: session.sessionId,
1354
+ ready: session.isReady,
1355
+ state: (await session.status()).state,
1356
+ versionId: session.versionId
1357
+ },
1358
+ this.worlds[alias]
1359
+ )
1360
+ );
1361
+ return {
1362
+ taskId: this.taskId,
1363
+ taskVersion: this.taskVersion,
1364
+ name: this.name,
1365
+ instruction: this.instruction,
1366
+ sessions
1367
+ };
1368
+ }
1369
+ /** Grade every world and aggregate — see `TaskGrade`. One `report` (the
1370
+ * agent's own account of the whole investigation) goes to every world's
1371
+ * judge; a world graded by assertions or python ignores it. */
1372
+ async grade(opts = {}) {
1373
+ return aggregateTaskGrade(
1374
+ await this.each((session) => session.grade(opts))
1375
+ );
1376
+ }
1377
+ /** Every world's call log, keyed by alias. */
1378
+ async export() {
1379
+ return this.each((session) => session.export());
1380
+ }
1381
+ /** Close every world. Closes are attempted for all of them even when one
1382
+ * fails; the error then names every world that did not close. */
1383
+ async close(opts = {}) {
1384
+ const settled = await Promise.allSettled(
1385
+ Object.entries(this.sessions).map(
1386
+ async ([alias, session]) => [alias, await session.close(opts)]
1387
+ )
1388
+ );
1389
+ const failed = [];
1390
+ const closed = {};
1391
+ settled.forEach((result, i) => {
1392
+ const alias = this.aliases[i];
1393
+ if (result.status === "fulfilled") closed[alias] = result.value[1];
1394
+ else
1395
+ failed.push(
1396
+ `${alias}: ${result.reason instanceof Error ? result.reason.message : String(result.reason)}`
1397
+ );
1398
+ });
1399
+ if (failed.length > 0)
1400
+ throw new Error(
1401
+ `${failed.length} of ${this.aliases.length} worlds did not close \u2014 ${failed.join("; ")}`
1402
+ );
1403
+ return closed;
1404
+ }
1405
+ };
1406
+ }
1407
+ });
1408
+
1409
+ // src/worlds/evals.ts
1410
+ var EVALUATIONS, GatewayEvalsClient;
1411
+ var init_evals = __esm({
1412
+ "src/worlds/evals.ts"() {
1413
+ "use strict";
1414
+ init_worlds();
1415
+ EVALUATIONS = "/api/public/benchmark-containers/evaluations";
1416
+ GatewayEvalsClient = class {
1417
+ constructor(options = {}) {
1418
+ this.options = options;
1419
+ }
1420
+ /** Anchor a new evaluation to `versionId`; returns its id. */
1421
+ async createEvaluation(versionId, opts = {}) {
1422
+ const body = { versionId };
1423
+ if (opts.model !== void 0) body.model = opts.model;
1424
+ if (opts.rolloutsPerExample !== void 0)
1425
+ body.rolloutsPerExample = opts.rolloutsPerExample;
1426
+ if (opts.metadata !== void 0) body.metadata = opts.metadata;
1427
+ const answer = await apiRequest(
1428
+ this.options,
1429
+ "POST",
1430
+ EVALUATIONS,
1431
+ body
1432
+ );
1433
+ return answer.evaluationId;
1434
+ }
1435
+ /** Push one batch of samples; returns how many the platform inserted. */
1436
+ async pushSamples(evaluationId, samples) {
1437
+ const answer = await apiRequest(
1438
+ this.options,
1439
+ "POST",
1440
+ `${EVALUATIONS}/${encodeURIComponent(evaluationId)}/samples`,
1441
+ { samples }
1442
+ );
1443
+ return answer.inserted ?? samples.length;
1444
+ }
1445
+ /** Close the evaluation out; returns its final status. */
1446
+ async finalizeEvaluation(evaluationId, opts = {}) {
1447
+ const body = {
1448
+ status: opts.status ?? "COMPLETED"
1449
+ };
1450
+ if (opts.metrics !== void 0) body.metrics = opts.metrics;
1451
+ const answer = await apiRequest(
1452
+ this.options,
1453
+ "POST",
1454
+ `${EVALUATIONS}/${encodeURIComponent(evaluationId)}/finalize`,
1455
+ body
1456
+ );
1457
+ return answer.status;
1458
+ }
1459
+ };
1460
+ }
1461
+ });
1462
+
1463
+ // src/users/index.ts
1464
+ function parseEvent(payload) {
1465
+ return {
1466
+ id: String(payload.id ?? ""),
1467
+ userId: String(payload.userId ?? ""),
1468
+ event: String(payload.event ?? ""),
1469
+ value: typeof payload.value === "number" ? payload.value : null,
1470
+ metadata: payload.metadata && typeof payload.metadata === "object" && !Array.isArray(payload.metadata) ? payload.metadata : {},
1471
+ traceId: typeof payload.traceId === "string" ? payload.traceId : null,
1472
+ sessionId: typeof payload.sessionId === "string" ? payload.sessionId : null,
1473
+ createdAt: typeof payload.createdAt === "string" ? new Date(payload.createdAt) : /* @__PURE__ */ new Date(0)
1474
+ };
1475
+ }
1476
+ function parseProfile(payload) {
1477
+ return {
1478
+ userId: String(payload.userId ?? ""),
1479
+ displayName: typeof payload.displayName === "string" ? payload.displayName : null,
1480
+ email: typeof payload.email === "string" ? payload.email : null,
1481
+ attributes: parseAttributes(payload.attributes),
1482
+ notes: typeof payload.notes === "string" ? payload.notes : null
1483
+ };
1484
+ }
1485
+ function parseAttributes(value) {
1486
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
1487
+ const attributes = {};
1488
+ for (const [key, entry] of Object.entries(value)) {
1489
+ attributes[key] = String(entry);
1490
+ }
1491
+ return attributes;
1492
+ }
1493
+ function safeJson(value) {
1494
+ try {
1495
+ const parsed = JSON.parse(value);
1496
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
1497
+ } catch {
1498
+ return {};
1499
+ }
1500
+ }
1501
+ var UserProfileError, UsersClient, users;
1502
+ var init_users = __esm({
1503
+ "src/users/index.ts"() {
1504
+ "use strict";
1505
+ UserProfileError = class extends Error {
1506
+ constructor(message, options) {
1507
+ super(message);
1508
+ this.name = "UserProfileError";
1509
+ this.cause = options?.cause;
1510
+ }
1511
+ };
1512
+ UsersClient = class _UsersClient {
1513
+ host;
1514
+ publicKey;
1515
+ secretKey;
1516
+ timeoutSeconds;
1517
+ debug;
1518
+ constructor(config) {
1519
+ this.host = config.host.replace(/\/$/, "");
1520
+ this.publicKey = config.publicKey;
1521
+ this.secretKey = config.secretKey;
1522
+ this.timeoutSeconds = config.timeoutSeconds ?? 15;
1523
+ this.debug = config.debug ?? false;
1524
+ }
1525
+ /** Create a client from GATEWAY_HOST / GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY. */
1526
+ static fromEnv(config = {}) {
1527
+ const host = config.host ?? process.env.GATEWAY_HOST;
1528
+ const publicKey = config.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;
1529
+ const secretKey = config.secretKey ?? process.env.GATEWAY_SECRET_KEY;
1530
+ const missing = [
1531
+ ["host", host],
1532
+ ["publicKey", publicKey],
1533
+ ["secretKey", secretKey]
1534
+ ].filter(([, value]) => !value).map(([name]) => name);
1535
+ if (missing.length > 0) {
1536
+ throw new UserProfileError(
1537
+ `Missing Gateway user-profile configuration: ${missing.join(", ")}`
1538
+ );
1539
+ }
1540
+ return new _UsersClient({
1541
+ ...config,
1542
+ host,
1543
+ publicKey,
1544
+ secretKey
1545
+ });
1546
+ }
1547
+ /** Fetch a user's stored profile. */
1548
+ async get(userId) {
1549
+ return parseProfile(
1550
+ await this.requestJson(
1551
+ "GET",
1552
+ `/api/public/user-profiles/${encodeURIComponent(userId)}`
1553
+ )
1554
+ );
1555
+ }
1556
+ /**
1557
+ * Upsert a user's profile. `attributes` merge with the stored set unless
1558
+ * `merge: false` (which replaces it).
1559
+ */
1560
+ async update(userId, update = {}) {
1561
+ const body = {
1562
+ userId,
1563
+ attributes: update.attributes ?? {},
1564
+ mergeAttributes: update.merge ?? true,
1565
+ ...update.displayName !== void 0 ? { displayName: update.displayName } : {},
1566
+ ...update.email !== void 0 ? { email: update.email } : {},
1567
+ ...update.notes !== void 0 ? { notes: update.notes } : {}
1568
+ };
1569
+ return parseProfile(
1570
+ await this.requestJson("POST", "/api/public/user-profiles", body)
1571
+ );
1572
+ }
1573
+ /**
1574
+ * Record a VALUE EVENT for a user — the per-user ROI stream. `value` is
1575
+ * whatever the event is worth in your terms (minutes saved, revenue…);
1576
+ * Gateway sums it in the hours-saved/ROI rollups, and evals and task-set
1577
+ * replays can assert against the events. Link `traceId`/`sessionId` to tie
1578
+ * the event to the run that produced it.
1579
+ *
1580
+ * @example
1581
+ * ```ts
1582
+ * await client.trackEvent("user-123", "checkout_completed", {
1583
+ * value: 25,
1584
+ * metadata: { cartSize: 3 },
1585
+ * sessionId,
1586
+ * });
1587
+ * ```
1588
+ */
1589
+ async trackEvent(userId, event, options = {}) {
1590
+ const body = {
1591
+ userId,
1592
+ event,
1593
+ metadata: options.metadata ?? {},
1594
+ ...options.value !== void 0 ? { value: options.value } : {},
1595
+ ...options.traceId !== void 0 ? { traceId: options.traceId } : {},
1596
+ ...options.sessionId !== void 0 ? { sessionId: options.sessionId } : {}
1597
+ };
1598
+ return parseEvent(
1599
+ await this.requestJson("POST", "/api/public/user-events", body)
1600
+ );
1601
+ }
1602
+ /** List a project's user events, optionally filtered by user/event/time. */
1603
+ async listEvents(filter = {}) {
1604
+ const params = new URLSearchParams();
1605
+ if (filter.userId) params.set("userId", filter.userId);
1606
+ if (filter.event) params.set("event", filter.event);
1607
+ if (filter.fromTimestamp)
1608
+ params.set("fromTimestamp", filter.fromTimestamp.toISOString());
1609
+ if (filter.toTimestamp)
1610
+ params.set("toTimestamp", filter.toTimestamp.toISOString());
1611
+ if (filter.page) params.set("page", String(filter.page));
1612
+ if (filter.limit) params.set("limit", String(filter.limit));
1613
+ const qs = params.toString();
1614
+ const payload = await this.requestJson(
1615
+ "GET",
1616
+ `/api/public/user-events${qs ? `?${qs}` : ""}`
1617
+ );
1618
+ const rows = Array.isArray(payload.data) ? payload.data : [];
1619
+ const meta = payload.meta && typeof payload.meta === "object" ? payload.meta : {};
1620
+ return {
1621
+ data: rows.map((row) => parseEvent(row)),
1622
+ totalItems: Number(meta.totalItems ?? rows.length)
1623
+ };
1624
+ }
1625
+ async requestJson(method, path10, payload) {
1626
+ let response;
1627
+ try {
1628
+ response = await fetch(`${this.host}${path10}`, {
1629
+ method,
1630
+ headers: {
1631
+ Authorization: this.authHeader(),
1632
+ "Content-Type": "application/json"
1633
+ },
1634
+ ...payload ? { body: JSON.stringify(payload) } : {},
1635
+ signal: AbortSignal.timeout(this.timeoutSeconds * 1e3)
1636
+ });
1637
+ } catch (error) {
1638
+ throw new UserProfileError(
1639
+ `${method} ${path10} failed: ${error instanceof Error ? error.message : String(error)}`,
1640
+ { cause: error }
1641
+ );
1642
+ }
1643
+ const text2 = await response.text();
1644
+ if (!response.ok) {
1645
+ throw new UserProfileError(
1646
+ `${method} ${path10} failed (${response.status}): ${text2.slice(0, 500)}`
1647
+ );
1648
+ }
1649
+ this.log("%s %s -> %s", method, path10, response.status);
1650
+ return safeJson(text2);
1651
+ }
1652
+ authHeader() {
1653
+ return `Basic ${Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(
1654
+ "base64"
1655
+ )}`;
1656
+ }
1657
+ log(message, ...args) {
1658
+ if (this.debug) {
1659
+ console.log(`[gateway.users] ${message}`, ...args);
1660
+ }
1661
+ }
1662
+ };
1663
+ users = {
1664
+ fromEnv: UsersClient.fromEnv
1665
+ };
1666
+ }
1667
+ });
1668
+
1669
+ // src/tracing/identity.ts
1670
+ function resolveUserId() {
1671
+ const contextual = currentUserStorage.getStore();
1672
+ if (contextual) return contextual;
1673
+ const envUser = process.env.GATEWAY_USER_ID?.trim();
1674
+ return envUser ? envUser : void 0;
1675
+ }
1676
+ var import_async_hooks, import_api, USER_ID_ATTRIBUTE, currentUserStorage, IdentitySpanProcessor;
1677
+ var init_identity = __esm({
1678
+ "src/tracing/identity.ts"() {
1679
+ "use strict";
1680
+ import_async_hooks = require("async_hooks");
1681
+ import_api = require("@opentelemetry/api");
1682
+ init_users();
1683
+ USER_ID_ATTRIBUTE = "gateway.user.id";
1684
+ currentUserStorage = new import_async_hooks.AsyncLocalStorage();
1685
+ IdentitySpanProcessor = class {
1686
+ onStart(span, _parentContext) {
1687
+ const userId = resolveUserId();
1688
+ if (userId) {
1689
+ span.setAttribute(USER_ID_ATTRIBUTE, userId);
1690
+ }
1691
+ }
1692
+ onEnd(_span) {
1693
+ }
1694
+ async shutdown() {
1695
+ }
1696
+ async forceFlush() {
1697
+ }
1698
+ };
1699
+ }
1700
+ });
1701
+
1702
+ // src/tracing/session.ts
1703
+ var session_exports2 = {};
1704
+ __export(session_exports2, {
1705
+ SESSION_ID_ATTRIBUTE: () => SESSION_ID_ATTRIBUTE,
1706
+ SessionSpanProcessor: () => SessionSpanProcessor,
1707
+ getAmbientSessionId: () => getAmbientSessionId,
1708
+ withSession: () => withSession
1709
+ });
1710
+ function getAmbientSessionId() {
1711
+ return currentSessionStorage.getStore();
1712
+ }
1713
+ function withSession(sessionId, fn) {
1714
+ return new Promise((resolve6, reject) => {
1715
+ currentSessionStorage.run(sessionId, () => {
1716
+ Promise.resolve().then(fn).then(resolve6, reject);
1717
+ });
1718
+ });
1719
+ }
1720
+ var import_async_hooks2, SESSION_ID_ATTRIBUTE, currentSessionStorage, SessionSpanProcessor;
1721
+ var init_session2 = __esm({
1722
+ "src/tracing/session.ts"() {
1723
+ "use strict";
1724
+ import_async_hooks2 = require("async_hooks");
1725
+ SESSION_ID_ATTRIBUTE = "gateway.session.id";
1726
+ currentSessionStorage = new import_async_hooks2.AsyncLocalStorage();
1727
+ SessionSpanProcessor = class {
1728
+ onStart(span, _parentContext) {
1729
+ const sessionId = getAmbientSessionId();
1730
+ if (sessionId) {
1731
+ span.setAttribute(SESSION_ID_ATTRIBUTE, sessionId);
1732
+ }
1733
+ }
1734
+ onEnd(_span) {
1735
+ }
1736
+ async shutdown() {
1737
+ }
1738
+ async forceFlush() {
1739
+ }
1740
+ };
1741
+ }
1742
+ });
1743
+
1744
+ // src/scores/index.ts
1745
+ function currentTraceId() {
1746
+ try {
1747
+ const span = import_api2.trace.getActiveSpan();
1748
+ if (!span) return void 0;
1749
+ const ctx = span.spanContext();
1750
+ if (!ctx || !(0, import_api2.isSpanContextValid)(ctx)) return void 0;
1751
+ return ctx.traceId;
1752
+ } catch {
1753
+ return void 0;
1754
+ }
1755
+ }
1756
+ function coerceSignalValue(value) {
1757
+ if (typeof value === "boolean") {
1758
+ return { numericValue: value ? 1 : 0, inferredType: "BOOLEAN" };
1759
+ }
1760
+ return { numericValue: value, inferredType: "NUMERIC" };
1761
+ }
1762
+ async function success(name, value = true, options = {}) {
1763
+ let client;
1764
+ try {
1765
+ client = ScoresClient.fromEnv();
1766
+ } catch (error) {
1767
+ console.warn(`[gateway.scores] success '${name}' skipped`, error);
1768
+ return;
1769
+ }
1770
+ await client.success(name, value, options);
1771
+ }
1772
+ var import_api2, SUCCESS_SIGNAL_KEY, SUCCESS_METRIC_NAME_KEY, AGENT_ID_KEY, ScoreError, ScoresClient, scores;
1773
+ var init_scores = __esm({
1774
+ "src/scores/index.ts"() {
1775
+ "use strict";
1776
+ import_api2 = require("@opentelemetry/api");
1777
+ SUCCESS_SIGNAL_KEY = "gateway.success.signal";
1778
+ SUCCESS_METRIC_NAME_KEY = "gateway.success.metricName";
1779
+ AGENT_ID_KEY = "gateway.agent.id";
1780
+ ScoreError = class extends Error {
1781
+ constructor(message, options) {
1782
+ super(message);
1783
+ this.name = "ScoreError";
1784
+ this.cause = options?.cause;
1785
+ }
1786
+ };
1787
+ ScoresClient = class _ScoresClient {
1788
+ host;
1789
+ publicKey;
1790
+ secretKey;
1791
+ timeoutSeconds;
1792
+ debug;
1793
+ constructor(config) {
1794
+ this.host = config.host.replace(/\/$/, "");
1795
+ this.publicKey = config.publicKey;
1796
+ this.secretKey = config.secretKey;
1797
+ this.timeoutSeconds = config.timeoutSeconds ?? 15;
1798
+ this.debug = config.debug ?? false;
1799
+ }
1800
+ /** Create a client from GATEWAY_HOST / GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY. */
1801
+ static fromEnv(config = {}) {
1802
+ const host = config.host ?? process.env.GATEWAY_HOST;
1803
+ const publicKey = config.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;
1804
+ const secretKey = config.secretKey ?? process.env.GATEWAY_SECRET_KEY;
1805
+ const missing = [
1806
+ ["host", host],
1807
+ ["publicKey", publicKey],
1808
+ ["secretKey", secretKey]
1809
+ ].filter(([, value]) => !value).map(([name]) => name);
1810
+ if (missing.length > 0) {
1811
+ throw new ScoreError(
1812
+ `Missing Gateway scores configuration: ${missing.join(", ")}`
1813
+ );
1814
+ }
1815
+ return new _ScoresClient({
1816
+ ...config,
1817
+ host,
1818
+ publicKey,
1819
+ secretKey
1820
+ });
1821
+ }
1822
+ /**
1823
+ * Post a score, throwing {@link ScoreError} on any failure. Builds the exact
1824
+ * `POST /api/public/scores` body the Python SDK sends: exactly one of
1825
+ * `sessionId` / `traceId` (+ optional `observationId`) / `datasetRunId`.
1826
+ * When no target is provided, the active OTel trace id is used; if none is
1827
+ * available the call is a no-op (returns without posting), matching Python.
1828
+ */
1829
+ async postScore(name, value, options = {}) {
1830
+ const body = this.buildScoreBody(name, value, options);
1831
+ if (!body) {
1832
+ this.log(
1833
+ "score '%s' dropped: no sessionId, traceId or datasetRunId available",
1834
+ name
1835
+ );
1836
+ return;
1837
+ }
1838
+ await this.request("POST", "/api/public/scores", body);
1839
+ }
1840
+ /**
1841
+ * Build the score request body, or null when no target can be resolved.
1842
+ * Split out so it is unit-testable and shared by score()/success().
1843
+ */
1844
+ buildScoreBody(name, value, options = {}) {
1845
+ const traceId = options.traceId ?? currentTraceId();
1846
+ const target = {};
1847
+ if (options.sessionId) {
1848
+ target.sessionId = options.sessionId;
1849
+ } else if (options.datasetRunId) {
1850
+ target.datasetRunId = options.datasetRunId;
1851
+ } else if (traceId) {
1852
+ target.traceId = traceId;
1853
+ if (options.observationId) target.observationId = options.observationId;
1854
+ } else {
1855
+ return null;
1856
+ }
1857
+ const metadata = {
1858
+ source: "gatewaysdk",
1859
+ ...options.metadata ?? {}
1860
+ };
1861
+ return {
1862
+ name,
1863
+ value,
1864
+ dataType: options.dataType ?? "NUMERIC",
1865
+ environment: options.environment ?? "default",
1866
+ ...options.comment ? { comment: options.comment } : {},
1867
+ metadata,
1868
+ ...target
1869
+ };
1870
+ }
1871
+ /**
1872
+ * Post a score, FAIL-SOFT: warns and resolves on any failure so a broken
1873
+ * transport never throws into (or rejects out of) the caller.
1874
+ */
1875
+ async score(name, value, options = {}) {
1876
+ try {
1877
+ await this.postScore(name, value, options);
1878
+ } catch (error) {
1879
+ this.warn(`score '${name}' failed`, error);
1880
+ }
1881
+ }
1882
+ /**
1883
+ * Emit a SUCCESS SIGNAL that feeds a Gateway Success Metric — a score tagged
1884
+ * with `gateway.success.signal` + `gateway.success.metricName` (and the agent
1885
+ * identity when `agentId` is set). A boolean `value` records a 1/0 BOOLEAN
1886
+ * score (pass/fail); a number records a NUMERIC score. FAIL-SOFT.
1887
+ *
1888
+ * The metadata shape matches the Python SDK's `Run.success()` exactly, so the
1889
+ * platform's Success Metrics aggregation counts signals from either SDK
1890
+ * without change.
1891
+ *
1892
+ * @example
1893
+ * ```ts
1894
+ * await scores.success("resolved_ticket", true, { agentId: "support-triage", sessionId });
1895
+ * await scores.success("handle_time_s", 42, { agentId: "support-triage", sessionId });
1896
+ * ```
1897
+ */
1898
+ async success(name, value = true, options = {}) {
1899
+ const { numericValue, inferredType } = coerceSignalValue(value);
1900
+ const { agentId, metricName, metadata, dataType, ...rest } = options;
1901
+ const signalMetadata = {
1902
+ ...metadata ?? {},
1903
+ [SUCCESS_SIGNAL_KEY]: true,
1904
+ [SUCCESS_METRIC_NAME_KEY]: metricName ?? name,
1905
+ ...agentId ? { [AGENT_ID_KEY]: agentId } : {}
1906
+ };
1907
+ await this.score(name, numericValue, {
1908
+ ...rest,
1909
+ dataType: dataType ?? inferredType,
1910
+ metadata: signalMetadata
1911
+ });
1912
+ }
1913
+ async request(method, path10, payload) {
1914
+ let response;
1915
+ try {
1916
+ response = await fetch(`${this.host}${path10}`, {
1917
+ method,
1918
+ headers: {
1919
+ Authorization: this.authHeader(),
1920
+ "Content-Type": "application/json"
1921
+ },
1922
+ body: JSON.stringify(payload),
1923
+ signal: AbortSignal.timeout(this.timeoutSeconds * 1e3)
1924
+ });
1925
+ } catch (error) {
1926
+ throw new ScoreError(
1927
+ `${method} ${path10} failed: ${error instanceof Error ? error.message : String(error)}`,
1928
+ { cause: error }
1929
+ );
1930
+ }
1931
+ const text2 = await response.text();
1932
+ if (!response.ok) {
1933
+ throw new ScoreError(
1934
+ `${method} ${path10} failed (${response.status}): ${text2.slice(0, 500)}`
1935
+ );
1936
+ }
1937
+ this.log("%s %s -> %s", method, path10, response.status);
1938
+ }
1939
+ authHeader() {
1940
+ return `Basic ${Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(
1941
+ "base64"
1942
+ )}`;
1943
+ }
1944
+ log(message, ...args) {
1945
+ if (this.debug) {
1946
+ console.log(`[gateway.scores] ${message}`, ...args);
1947
+ }
1948
+ }
1949
+ warn(message, ...args) {
1950
+ console.warn(`[gateway.scores] ${message}`, ...args);
1951
+ }
1952
+ };
1953
+ scores = {
1954
+ fromEnv: ScoresClient.fromEnv,
1955
+ success
1956
+ };
1957
+ }
1958
+ });
1959
+
1960
+ // package.json
1961
+ var require_package = __commonJS({
1962
+ "package.json"(exports2, module2) {
1963
+ module2.exports = {
1964
+ name: "@withgateway/sdk",
1965
+ version: "0.2.5",
1966
+ description: "Gateway SDK for TypeScript - A/B experiments, tracing, and observability",
1967
+ main: "./dist/index.js",
1968
+ module: "./dist/index.mjs",
1969
+ types: "./dist/index.d.ts",
1970
+ exports: {
1971
+ ".": {
1972
+ types: "./dist/index.d.ts",
1973
+ import: "./dist/index.mjs",
1974
+ require: "./dist/index.js"
1975
+ },
1976
+ "./experiments": {
1977
+ types: "./dist/experiments/index.d.ts",
1978
+ import: "./dist/experiments/index.mjs",
1979
+ require: "./dist/experiments/index.js"
1980
+ },
1981
+ "./context": {
1982
+ types: "./dist/context/index.d.ts",
1983
+ import: "./dist/context/index.mjs",
1984
+ require: "./dist/context/index.js"
1985
+ },
1986
+ "./memory": {
1987
+ types: "./dist/memory/index.d.ts",
1988
+ import: "./dist/memory/index.mjs",
1989
+ require: "./dist/memory/index.js"
1990
+ },
1991
+ "./personas": {
1992
+ types: "./dist/personas/index.d.ts",
1993
+ import: "./dist/personas/index.mjs",
1994
+ require: "./dist/personas/index.js"
1995
+ },
1996
+ "./replay": {
1997
+ types: "./dist/replay/index.d.ts",
1998
+ import: "./dist/replay/index.mjs",
1999
+ require: "./dist/replay/index.js"
2000
+ },
2001
+ "./sessions": {
2002
+ types: "./dist/sessions/index.d.ts",
2003
+ import: "./dist/sessions/index.mjs",
2004
+ require: "./dist/sessions/index.js"
2005
+ },
2006
+ "./tracing": {
2007
+ types: "./dist/tracing/index.d.ts",
2008
+ import: "./dist/tracing/index.mjs",
2009
+ require: "./dist/tracing/index.js"
2010
+ },
2011
+ "./security": {
2012
+ types: "./dist/security/index.d.ts",
2013
+ import: "./dist/security/index.mjs",
2014
+ require: "./dist/security/index.js"
2015
+ },
2016
+ "./users": {
2017
+ types: "./dist/users/index.d.ts",
2018
+ import: "./dist/users/index.mjs",
2019
+ require: "./dist/users/index.js"
2020
+ },
2021
+ "./scores": {
2022
+ types: "./dist/scores/index.d.ts",
2023
+ import: "./dist/scores/index.mjs",
2024
+ require: "./dist/scores/index.js"
2025
+ },
2026
+ "./worlds": {
2027
+ types: "./dist/worlds/index.d.ts",
2028
+ import: "./dist/worlds/index.mjs",
2029
+ require: "./dist/worlds/index.js"
2030
+ },
2031
+ "./files": {
2032
+ types: "./dist/files/index.d.ts",
2033
+ import: "./dist/files/index.mjs",
2034
+ require: "./dist/files/index.js"
2035
+ },
2036
+ "./traces": {
2037
+ types: "./dist/traces/index.d.ts",
2038
+ import: "./dist/traces/index.mjs",
2039
+ require: "./dist/traces/index.js"
2040
+ },
2041
+ "./hooks": {
2042
+ types: "./dist/hooks/index.d.ts",
2043
+ import: "./dist/hooks/index.mjs",
2044
+ require: "./dist/hooks/index.js"
2045
+ },
2046
+ "./cli": {
2047
+ types: "./dist/cli.d.ts",
2048
+ import: "./dist/cli.mjs",
2049
+ require: "./dist/cli.js"
2050
+ }
2051
+ },
2052
+ files: [
2053
+ "dist",
2054
+ "skills",
2055
+ "runtime",
2056
+ "README.md"
2057
+ ],
2058
+ publishConfig: {
2059
+ access: "public"
2060
+ },
2061
+ scripts: {
2062
+ prebuild: "node scripts/copy-skills.mjs && node scripts/copy-runtime.mjs",
2063
+ build: "tsup",
2064
+ dev: "tsup --watch",
2065
+ typecheck: "tsc --noEmit",
2066
+ "typecheck:examples": "tsc -p tsconfig.examples.json --noEmit",
2067
+ test: "vitest",
2068
+ "test:run": "vitest run",
2069
+ "test:integration": "vitest run --config vitest.integration.config.ts",
2070
+ lint: "eslint src --ext .ts",
2071
+ clean: "rm -rf dist",
2072
+ example: "tsx examples/test-ab-experiment.ts",
2073
+ "test:crm": "tsx examples/test-crm-ab-experiment.ts",
2074
+ "test:crm:balanced": "tsx examples/test-crm-ab-experiment.ts --balanced",
2075
+ "test:crm:full": "tsx examples/test-crm-ab-experiment.ts --users 12 --all-tasks --concurrency 3"
2076
+ },
2077
+ keywords: [
2078
+ "gateway",
2079
+ "ab-testing",
2080
+ "experiments",
2081
+ "opentelemetry",
2082
+ "tracing",
2083
+ "observability",
2084
+ "llm"
2085
+ ],
2086
+ author: "Gateway Team",
2087
+ license: "MIT",
2088
+ engines: {
2089
+ node: ">=18.0.0"
2090
+ },
2091
+ peerDependencies: {
2092
+ "@opentelemetry/api": "^1.0.0",
2093
+ "@opentelemetry/exporter-trace-otlp-http": ">=0.50.0",
2094
+ "@opentelemetry/resources": ">=1.0.0",
2095
+ "@opentelemetry/sdk-trace-base": ">=1.0.0",
2096
+ "@opentelemetry/sdk-trace-node": ">=1.0.0",
2097
+ playwright: ">=1.40.0"
2098
+ },
2099
+ peerDependenciesMeta: {
2100
+ "@opentelemetry/api": {
2101
+ optional: true
2102
+ },
2103
+ "@opentelemetry/sdk-trace-base": {
2104
+ optional: true
2105
+ },
2106
+ "@opentelemetry/sdk-trace-node": {
2107
+ optional: true
2108
+ },
2109
+ "@opentelemetry/exporter-trace-otlp-http": {
2110
+ optional: true
2111
+ },
2112
+ "@opentelemetry/resources": {
2113
+ optional: true
2114
+ },
2115
+ playwright: {
2116
+ optional: true
2117
+ }
2118
+ },
2119
+ optionalDependencies: {
2120
+ "@arizeai/openinference-instrumentation-anthropic": "^0.1.15",
2121
+ "@arizeai/openinference-instrumentation-openai": "^4.1.5"
2122
+ },
2123
+ devDependencies: {
2124
+ "@anthropic-ai/sdk": "^0.79.0",
2125
+ "@opentelemetry/api": "^1.9.0",
2126
+ "@opentelemetry/exporter-trace-otlp-http": "^0.212.0",
2127
+ "@opentelemetry/resources": "^2.6.0",
2128
+ "@opentelemetry/sdk-trace-base": "^1.30.1",
2129
+ "@opentelemetry/sdk-trace-node": "^2.6.0",
2130
+ "@opentelemetry/semantic-conventions": "^1.40.0",
2131
+ "@types/node": "^20.0.0",
2132
+ openai: "^4.70.0",
2133
+ tsup: "^8.0.0",
2134
+ tsx: "^4.0.0",
2135
+ typescript: "^5.0.0",
2136
+ vitest: "^3.2.6"
2137
+ },
2138
+ overrides: {
2139
+ protobufjs: "^8.4.1",
2140
+ "vite@6": "^6.4.3",
2141
+ postcss: "^8.5.18",
2142
+ "picomatch@4": "^4.0.4"
2143
+ },
2144
+ pnpm: {
2145
+ overrides: {
2146
+ protobufjs: "^8.4.1",
2147
+ vitest: "^3.2.6",
2148
+ "vite@6": "^6.4.3",
2149
+ postcss: "^8.5.18",
2150
+ "picomatch@4": "^4.0.4"
2151
+ }
2152
+ },
2153
+ bin: {
2154
+ gateway: "./dist/cli.js"
2155
+ }
2156
+ };
2157
+ }
2158
+ });
2159
+
2160
+ // src/build/index.ts
2161
+ function canonicalJson(value) {
2162
+ if (value === null || typeof value !== "object") {
2163
+ return JSON.stringify(value);
2164
+ }
2165
+ if (Array.isArray(value)) {
2166
+ return `[${value.map(canonicalJson).join(",")}]`;
2167
+ }
2168
+ const entries = Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
2169
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(",")}}`;
2170
+ }
2171
+ function sha256(text2) {
2172
+ return `sha256:${(0, import_node_crypto2.createHash)("sha256").update(text2).digest("hex")}`;
2173
+ }
2174
+ function getRegisteredTools() {
2175
+ return [...registeredTools.values()].sort(
2176
+ (a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0
2177
+ );
2178
+ }
2179
+ function getRegisteredArtifacts() {
2180
+ return [...registeredArtifacts.values()].sort(
2181
+ (a, b) => `${a.kind}:${a.name}` < `${b.kind}:${b.name}` ? -1 : 1
2182
+ );
2183
+ }
2184
+ function getRegisteredSkills() {
2185
+ return Object.fromEntries(
2186
+ [...registeredSkills.entries()].sort(
2187
+ ([a], [b]) => a < b ? -1 : a > b ? 1 : 0
2188
+ )
2189
+ );
2190
+ }
2191
+ function getRegisteredPrompts() {
2192
+ return Object.fromEntries(
2193
+ [...registeredPrompts.entries()].sort(
2194
+ ([a], [b]) => a < b ? -1 : a > b ? 1 : 0
2195
+ )
2196
+ );
2197
+ }
2198
+ function sdkVersion() {
2199
+ try {
2200
+ const pkg = require_package();
2201
+ return `@withgateway/sdk@${pkg.version ?? "unknown"}`;
2202
+ } catch {
2203
+ return "@withgateway/sdk";
2204
+ }
2205
+ }
2206
+ function paasGitContext() {
2207
+ const env = process.env;
2208
+ if (env.VERCEL_GIT_COMMIT_SHA) {
2209
+ const isGithub = (env.VERCEL_GIT_PROVIDER ?? "github") === "github";
2210
+ return {
2211
+ provider: "vercel",
2212
+ sha: env.VERCEL_GIT_COMMIT_SHA,
2213
+ repo: isGithub && env.VERCEL_GIT_REPO_OWNER && env.VERCEL_GIT_REPO_SLUG ? `${env.VERCEL_GIT_REPO_OWNER}/${env.VERCEL_GIT_REPO_SLUG}` : void 0,
2214
+ branch: env.VERCEL_GIT_COMMIT_REF,
2215
+ login: env.VERCEL_GIT_COMMIT_AUTHOR_LOGIN
2216
+ };
2217
+ }
2218
+ if (env.RENDER_GIT_COMMIT) {
2219
+ return {
2220
+ provider: "render",
2221
+ sha: env.RENDER_GIT_COMMIT,
2222
+ repo: env.RENDER_GIT_REPO_SLUG,
2223
+ // already "owner/repo"
2224
+ branch: env.RENDER_GIT_BRANCH
2225
+ };
2226
+ }
2227
+ if (env.RAILWAY_GIT_COMMIT_SHA) {
2228
+ return {
2229
+ provider: "railway",
2230
+ sha: env.RAILWAY_GIT_COMMIT_SHA,
2231
+ repo: env.RAILWAY_GIT_REPO_OWNER && env.RAILWAY_GIT_REPO_NAME ? `${env.RAILWAY_GIT_REPO_OWNER}/${env.RAILWAY_GIT_REPO_NAME}` : void 0,
2232
+ branch: env.RAILWAY_GIT_BRANCH,
2233
+ login: env.RAILWAY_GIT_AUTHOR
2234
+ };
2235
+ }
2236
+ if (env.NETLIFY && env.COMMIT_REF) {
2237
+ const repoMatch = /github\.com[/:]([^/]+\/[^/.]+)/.exec(
2238
+ env.REPOSITORY_URL ?? ""
2239
+ );
2240
+ return {
2241
+ provider: "netlify",
2242
+ sha: env.COMMIT_REF,
2243
+ repo: repoMatch?.[1],
2244
+ branch: env.BRANCH
2245
+ };
2246
+ }
2247
+ const bareSha = env.HEROKU_SLUG_COMMIT ?? env.SOURCE_VERSION ?? env.GIT_COMMIT ?? env.COMMIT_SHA;
2248
+ if (bareSha) {
2249
+ return {
2250
+ provider: env.HEROKU_SLUG_COMMIT || env.SOURCE_VERSION ? "heroku" : "generic",
2251
+ sha: bareSha
2252
+ };
2253
+ }
2254
+ return null;
2255
+ }
2256
+ function codeRef() {
2257
+ const paas = paasGitContext();
2258
+ const sha = process.env.GATEWAY_COMMIT ?? process.env.GITHUB_SHA ?? process.env.CI_COMMIT_SHA ?? // GitLab
2259
+ process.env.CIRCLE_SHA1 ?? paas?.sha;
2260
+ if (!sha) return void 0;
2261
+ const repo = process.env.GITHUB_REPOSITORY ?? process.env.CI_PROJECT_PATH ?? paas?.repo;
2262
+ return repo ? `git:${repo}@${sha}` : `git:${sha}`;
2263
+ }
2264
+ function assembleManifest(agentId) {
2265
+ return {
2266
+ agentId,
2267
+ ...codeRef() ? { codeRef: codeRef() } : {},
2268
+ sdk: sdkVersion(),
2269
+ tools: getRegisteredTools(),
2270
+ prompts: getRegisteredPrompts(),
2271
+ skills: getRegisteredSkills(),
2272
+ artifacts: getRegisteredArtifacts()
2273
+ };
2274
+ }
2275
+ function computeBuildHash(manifest) {
2276
+ const identity = {
2277
+ ...manifest,
2278
+ tools: manifest.tools.map(({ source: _source, ...tool }) => tool),
2279
+ artifacts: manifest.artifacts.map(
2280
+ ({ source: _source, ...artifact }) => artifact
2281
+ )
2282
+ };
2283
+ return sha256(canonicalJson(identity));
2284
+ }
2285
+ function attributionFromEnv() {
2286
+ const attribution = { source: "runtime" };
2287
+ if (process.env.GITHUB_ACTIONS) attribution.source = "ci";
2288
+ if (process.env.GITHUB_ACTOR) attribution.githubLogin = process.env.GITHUB_ACTOR;
2289
+ const sha = process.env.GATEWAY_COMMIT ?? process.env.GITHUB_SHA;
2290
+ if (sha) attribution.commitSha = sha;
2291
+ if (process.env.GITHUB_REPOSITORY) attribution.repo = process.env.GITHUB_REPOSITORY;
2292
+ const branch = process.env.GITHUB_HEAD_REF ?? process.env.GITHUB_REF_NAME;
2293
+ if (branch) attribution.branch = branch;
2294
+ const paas = paasGitContext();
2295
+ if (paas) {
2296
+ if (attribution.source === "runtime") attribution.source = `paas:${paas.provider}`;
2297
+ if (!attribution.commitSha && paas.sha) attribution.commitSha = paas.sha;
2298
+ if (!attribution.repo && paas.repo) attribution.repo = paas.repo;
2299
+ if (!attribution.branch && paas.branch) attribution.branch = paas.branch;
2300
+ if (!attribution.githubLogin && paas.login) attribution.githubLogin = paas.login;
2301
+ }
2302
+ const ref = process.env.GITHUB_REF ?? "";
2303
+ const prMatch = /refs\/pull\/(\d+)\//.exec(ref);
2304
+ if (prMatch) attribution.prNumber = Number(prMatch[1]);
2305
+ if (process.env.GATEWAY_PR_TITLE) {
2306
+ attribution.prTitle = process.env.GATEWAY_PR_TITLE.slice(0, 300);
2307
+ }
2308
+ if (process.env.GATEWAY_PR_BODY) {
2309
+ attribution.prDescription = process.env.GATEWAY_PR_BODY.slice(0, 2e3);
2310
+ }
2311
+ if (attribution.repo && attribution.prNumber && !("prUrl" in attribution)) {
2312
+ attribution.prUrl = `https://github.com/${String(attribution.repo)}/pull/${String(attribution.prNumber)}`;
2313
+ }
2314
+ return attribution;
2315
+ }
2316
+ function trackActiveBuild(context) {
2317
+ activeBuilds.push(context);
2318
+ }
2319
+ async function registerBuild(params) {
2320
+ const auth = Buffer.from(`${params.publicKey}:${params.secretKey}`).toString(
2321
+ "base64"
2322
+ );
2323
+ const response = await fetch(
2324
+ `${params.host.replace(/\/$/, "")}/api/public/agent-builds`,
2325
+ {
2326
+ method: "POST",
2327
+ headers: {
2328
+ Authorization: `Basic ${auth}`,
2329
+ "Content-Type": "application/json"
2330
+ },
2331
+ body: JSON.stringify({
2332
+ agentId: params.agentId,
2333
+ buildHash: params.buildHash,
2334
+ ...params.version ? { semanticVer: params.version } : {},
2335
+ manifest: params.manifest,
2336
+ attribution: attributionFromEnv()
2337
+ }),
2338
+ signal: AbortSignal.timeout(15e3)
2339
+ }
2340
+ );
2341
+ if (!response.ok) {
2342
+ throw new Error(
2343
+ `build registration failed (${response.status}): ${(await response.text()).slice(0, 300)}`
2344
+ );
2345
+ }
2346
+ }
2347
+ var import_node_crypto2, registeredTools, registeredPrompts, registeredSkills, registeredArtifacts, activeBuilds;
2348
+ var init_build = __esm({
2349
+ "src/build/index.ts"() {
2350
+ "use strict";
2351
+ import_node_crypto2 = require("crypto");
2352
+ registeredTools = /* @__PURE__ */ new Map();
2353
+ registeredPrompts = /* @__PURE__ */ new Map();
2354
+ registeredSkills = /* @__PURE__ */ new Map();
2355
+ registeredArtifacts = /* @__PURE__ */ new Map();
2356
+ activeBuilds = [];
2357
+ }
2358
+ });
2359
+
2360
+ // src/tracing/init.ts
2361
+ var init_exports = {};
2362
+ __export(init_exports, {
2363
+ flush: () => flush,
2364
+ init: () => init,
2365
+ initIsolated: () => initIsolated,
2366
+ isGatewayConfigured: () => isGatewayConfigured,
2367
+ isInitialized: () => isInitialized,
2368
+ shutdown: () => shutdown
2369
+ });
2370
+ function getEnv(key) {
2371
+ const value = process.env[key];
2372
+ return value ? value : void 0;
2373
+ }
2374
+ function log(message, ...args) {
2375
+ if (state.debug) {
2376
+ console.log(`[gatewaysdk.tracing] ${message}`, ...args);
2377
+ }
2378
+ }
2379
+ function warn(message, ...args) {
2380
+ console.warn(`[gatewaysdk.tracing] ${message}`, ...args);
2381
+ }
2382
+ function buildProvider(config, logFn) {
2383
+ const host = config.host ?? getEnv(ENV_VARS.HOST);
2384
+ const publicKey = config.publicKey ?? getEnv(ENV_VARS.PUBLIC_KEY);
2385
+ const secretKey = config.secretKey ?? getEnv(ENV_VARS.SECRET_KEY);
2386
+ const endpoint = config.endpoint ?? getEnv(ENV_VARS.ENDPOINT) ?? (host ? `${host.replace(/\/$/, "")}${DEFAULT_OTLP_PATH}` : void 0);
2387
+ const missing = [];
2388
+ if (!host) missing.push("host (or GATEWAY_HOST env var)");
2389
+ if (!publicKey) missing.push("publicKey (or GATEWAY_PUBLIC_KEY env var)");
2390
+ if (!secretKey) missing.push("secretKey (or GATEWAY_SECRET_KEY env var)");
2391
+ if (missing.length > 0) {
2392
+ throw new Error(
2393
+ `Missing required Gateway configuration: ${missing.join(", ")}. Provide these values via init() parameters or environment variables.`
2394
+ );
2395
+ }
2396
+ let NodeTracerProvider;
2397
+ let BatchSpanProcessor;
2398
+ let OTLPTraceExporter;
2399
+ let createResource;
2400
+ let ATTR_SERVICE_NAME;
2401
+ try {
2402
+ const traceNode = require("@opentelemetry/sdk-trace-node");
2403
+ const traceBase = require("@opentelemetry/sdk-trace-base");
2404
+ const otlpHttp = require("@opentelemetry/exporter-trace-otlp-http");
2405
+ const resources = require("@opentelemetry/resources");
2406
+ NodeTracerProvider = traceNode.NodeTracerProvider;
2407
+ BatchSpanProcessor = traceBase.BatchSpanProcessor;
2408
+ OTLPTraceExporter = otlpHttp.OTLPTraceExporter;
2409
+ if (resources.Resource) {
2410
+ createResource = (attrs) => new resources.Resource(attrs);
2411
+ } else if (resources.resourceFromAttributes) {
2412
+ createResource = resources.resourceFromAttributes;
2413
+ } else {
2414
+ createResource = () => resources.defaultResource();
2415
+ }
2416
+ try {
2417
+ const semconv = require("@opentelemetry/semantic-conventions");
2418
+ ATTR_SERVICE_NAME = semconv.ATTR_SERVICE_NAME ?? semconv.SEMRESATTRS_SERVICE_NAME ?? "service.name";
2419
+ } catch {
2420
+ ATTR_SERVICE_NAME = "service.name";
2421
+ }
2422
+ } catch {
2423
+ throw new Error(
2424
+ "OpenTelemetry packages not found. Install them with:\nnpm install @opentelemetry/sdk-trace-node @opentelemetry/sdk-trace-base @opentelemetry/exporter-trace-otlp-http @opentelemetry/resources"
2425
+ );
2426
+ }
2427
+ const resourceAttrs = {
2428
+ [ATTR_SERVICE_NAME]: config.serviceName ?? "gatewaysdk-tracing"
2429
+ };
2430
+ if (config.environment) {
2431
+ resourceAttrs["gateway.environment"] = config.environment;
2432
+ }
2433
+ if (config.version) {
2434
+ resourceAttrs["gateway.version"] = config.version;
2435
+ }
2436
+ let buildInfo = null;
2437
+ if (config.agent) {
2438
+ const manifest = assembleManifest(config.agent);
2439
+ const buildHash = computeBuildHash(manifest);
2440
+ buildInfo = { manifest, buildHash };
2441
+ resourceAttrs["gateway.agent.id"] = config.agent;
2442
+ resourceAttrs["gateway.build.hash"] = buildHash;
2443
+ if (config.version) {
2444
+ resourceAttrs["gateway.agent.version"] = config.version;
2445
+ }
2446
+ logFn(
2447
+ "Agent build identity: %s @ %s (%d tools, %d prompts)",
2448
+ config.agent,
2449
+ buildHash.slice(0, 15),
2450
+ manifest.tools.length,
2451
+ Object.keys(manifest.prompts).length
2452
+ );
2453
+ }
2454
+ let isLocalhost = false;
2455
+ if (endpoint) {
2456
+ try {
2457
+ const parsed = new URL(endpoint);
2458
+ isLocalhost = parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1";
2459
+ } catch {
2460
+ isLocalhost = false;
2461
+ }
2462
+ }
2463
+ if (endpoint && !endpoint.startsWith("https://") && !isLocalhost) {
2464
+ throw new Error(
2465
+ `Refusing to send credentials over insecure HTTP to ${endpoint}. Use HTTPS or localhost for development.`
2466
+ );
2467
+ }
2468
+ const credentials = `${publicKey}:${secretKey}`;
2469
+ const encoded = Buffer.from(credentials).toString("base64");
2470
+ const authHeader = `Basic ${encoded}`;
2471
+ const exporter = new OTLPTraceExporter({
2472
+ url: endpoint,
2473
+ headers: {
2474
+ Authorization: authHeader
2475
+ }
2476
+ });
2477
+ logFn("Configured Gateway exporter: endpoint=%s", endpoint);
2478
+ const spanProcessors = [];
2479
+ if (config.customSpanProcessors) {
2480
+ for (const sp of config.customSpanProcessors) {
2481
+ spanProcessors.push(sp);
2482
+ logFn(
2483
+ "Added custom span processor: %s",
2484
+ sp.constructor?.name ?? "unknown"
2485
+ );
2486
+ }
2487
+ }
2488
+ spanProcessors.push(new IdentitySpanProcessor());
2489
+ spanProcessors.push(new SessionSpanProcessor());
2490
+ const batchConfig = {};
2491
+ if (config.batch?.maxQueueSize) {
2492
+ batchConfig.maxQueueSize = config.batch.maxQueueSize;
2493
+ }
2494
+ if (config.batch?.scheduledDelayMillis) {
2495
+ batchConfig.scheduledDelayMillis = config.batch.scheduledDelayMillis;
2496
+ }
2497
+ if (config.batch?.maxExportBatchSize) {
2498
+ batchConfig.maxExportBatchSize = config.batch.maxExportBatchSize;
2499
+ }
2500
+ spanProcessors.push(new BatchSpanProcessor(exporter, batchConfig));
2501
+ let provider = new NodeTracerProvider({
2502
+ resource: createResource(resourceAttrs)
2503
+ });
2504
+ if (typeof provider.addSpanProcessor === "function") {
2505
+ for (const sp of spanProcessors) {
2506
+ provider.addSpanProcessor(sp);
2507
+ }
2508
+ } else {
2509
+ provider = new NodeTracerProvider({
2510
+ resource: createResource(resourceAttrs),
2511
+ spanProcessors
2512
+ });
2513
+ }
2514
+ return {
2515
+ provider,
2516
+ buildInfo,
2517
+ connection: { host, publicKey, secretKey }
2518
+ };
2519
+ }
2520
+ function scheduleBuildRegistration(config, built) {
2521
+ if (!config.agent || !built.buildInfo || config.registerBuild === false) {
2522
+ return;
2523
+ }
2524
+ const { manifest, buildHash } = built.buildInfo;
2525
+ trackActiveBuild({
2526
+ host: built.connection.host,
2527
+ publicKey: built.connection.publicKey,
2528
+ secretKey: built.connection.secretKey,
2529
+ agentId: config.agent,
2530
+ version: config.version,
2531
+ lastRegisteredHash: buildHash
2532
+ });
2533
+ void registerBuild({
2534
+ host: built.connection.host,
2535
+ publicKey: built.connection.publicKey,
2536
+ secretKey: built.connection.secretKey,
2537
+ agentId: config.agent,
2538
+ version: config.version,
2539
+ manifest,
2540
+ buildHash
2541
+ }).catch((err) => {
2542
+ warn("Build registration failed (agent keeps running):", err);
2543
+ });
2544
+ }
2545
+ function init(config = {}) {
2546
+ if (state.initialized) {
2547
+ log("Tracing already initialized. Call shutdown() first to reinitialize.");
2548
+ return;
2549
+ }
2550
+ state.debug = config.debug ?? false;
2551
+ const built = buildProvider(config, log);
2552
+ const provider = built.provider;
2553
+ provider.register();
2554
+ scheduleBuildRegistration(config, built);
2555
+ state.provider = provider;
2556
+ state.initialized = true;
2557
+ log(
2558
+ "GatewaySDK tracing initialized successfully (service=%s)",
2559
+ config.serviceName ?? "gatewaysdk-tracing"
2560
+ );
2561
+ }
2562
+ function initIsolated(config = {}) {
2563
+ const debugLog = config.debug ? (message, ...args) => console.log(`[gatewaysdk.tracing:isolated] ${message}`, ...args) : () => {
2564
+ };
2565
+ const built = buildProvider(config, debugLog);
2566
+ const provider = built.provider;
2567
+ scheduleBuildRegistration(config, built);
2568
+ const tracer = provider.getTracer("@withgateway/sdk");
2569
+ const scores2 = new ScoresClient({
2570
+ host: built.connection.host,
2571
+ publicKey: built.connection.publicKey,
2572
+ secretKey: built.connection.secretKey,
2573
+ debug: config.debug ?? false
2574
+ });
2575
+ debugLog(
2576
+ "Isolated tracing provider created (service=%s)",
2577
+ config.serviceName ?? "gatewaysdk-tracing"
2578
+ );
2579
+ return {
2580
+ tracer,
2581
+ scores: scores2,
2582
+ async flush() {
2583
+ try {
2584
+ await provider.forceFlush();
2585
+ } catch (e) {
2586
+ warn("Error during isolated flush:", e);
2587
+ }
2588
+ },
2589
+ async shutdown() {
2590
+ try {
2591
+ await provider.shutdown();
2592
+ } catch (e) {
2593
+ warn("Error during isolated shutdown:", e);
2594
+ }
2595
+ }
2596
+ };
2597
+ }
2598
+ async function flush() {
2599
+ if (!state.provider) {
2600
+ log("No provider to flush");
2601
+ return;
2602
+ }
2603
+ try {
2604
+ await state.provider.forceFlush();
2605
+ log("Flush completed successfully");
2606
+ } catch (e) {
2607
+ warn("Error during flush:", e);
2608
+ }
2609
+ }
2610
+ async function shutdown() {
2611
+ if (!state.initialized || !state.provider) {
2612
+ log("Tracing not initialized, nothing to shutdown");
2613
+ return;
2614
+ }
2615
+ try {
2616
+ await state.provider.shutdown();
2617
+ log("Shutdown complete");
2618
+ } catch (e) {
2619
+ warn("Error during shutdown:", e);
2620
+ }
2621
+ state.provider = null;
2622
+ state.initialized = false;
2623
+ }
2624
+ function isInitialized() {
2625
+ return state.initialized;
2626
+ }
2627
+ function isGatewayConfigured() {
2628
+ const host = getEnv(ENV_VARS.HOST);
2629
+ const publicKey = getEnv(ENV_VARS.PUBLIC_KEY);
2630
+ const secretKey = getEnv(ENV_VARS.SECRET_KEY);
2631
+ return !!(host && publicKey && secretKey);
2632
+ }
2633
+ var ENV_VARS, DEFAULT_OTLP_PATH, state;
2634
+ var init_init = __esm({
2635
+ "src/tracing/init.ts"() {
2636
+ "use strict";
2637
+ init_identity();
2638
+ init_session2();
2639
+ init_scores();
2640
+ init_build();
2641
+ ENV_VARS = {
2642
+ HOST: "GATEWAY_HOST",
2643
+ PUBLIC_KEY: "GATEWAY_PUBLIC_KEY",
2644
+ SECRET_KEY: "GATEWAY_SECRET_KEY",
2645
+ ENDPOINT: "GATEWAY_OTLP_ENDPOINT"
2646
+ };
2647
+ DEFAULT_OTLP_PATH = "/api/public/otel/v1/traces";
2648
+ state = {
2649
+ initialized: false,
2650
+ provider: null
2651
+ };
2652
+ }
2653
+ });
2654
+
2655
+ // src/worlds/taskRun.ts
2656
+ function worldRef(live, alias) {
2657
+ const { slug, ref } = live.worldRef(alias);
2658
+ const session = live.sessions[alias];
2659
+ return {
2660
+ slug,
2661
+ ref,
2662
+ versionId: session.versionId,
2663
+ sessionId: session.sessionId
2664
+ };
2665
+ }
2666
+ async function fileTaskRun(live, runId, model, report, grade, agentError, traced, runDir, options) {
2667
+ const aliases = live.aliases;
2668
+ const anchor = aliases[0];
2669
+ const worldsMeta = Object.fromEntries(
2670
+ aliases.map((alias) => [alias, worldRef(live, alias)])
2671
+ );
2672
+ const evals = new GatewayEvalsClient(options);
2673
+ const evaluationId = await evals.createEvaluation(
2674
+ worldRef(live, anchor).versionId,
2675
+ {
2676
+ model,
2677
+ rolloutsPerExample: 1,
2678
+ metadata: {
2679
+ source: "worlds-task-run",
2680
+ task: {
2681
+ id: live.taskId,
2682
+ version: live.taskVersion,
2683
+ name: live.name,
2684
+ hash: live.hash
2685
+ },
2686
+ anchor,
2687
+ worlds: worldsMeta,
2688
+ runId
2689
+ }
2690
+ }
2691
+ );
2692
+ const reward = grade.reward;
2693
+ const sample = {
2694
+ exampleId: live.name ?? live.taskId ?? runId,
2695
+ task: live.name ?? live.taskId ?? runId,
2696
+ rolloutIndex: 0,
2697
+ prompt: live.instruction,
2698
+ completion: report,
2699
+ rewards: grade.rewards,
2700
+ info: {
2701
+ sessionId: runId,
2702
+ worlds: Object.fromEntries(
2703
+ aliases.map((alias) => [
2704
+ alias,
2705
+ {
2706
+ ...worldRef(live, alias),
2707
+ reward: grade.worlds[alias]?.reward ?? null
2708
+ }
2709
+ ])
2710
+ ),
2711
+ ungraded: grade.ungraded,
2712
+ traced,
2713
+ runDir,
2714
+ ...agentError ? { agentError } : {}
2715
+ }
2716
+ };
2717
+ if (typeof reward === "number") {
2718
+ sample.reward = reward;
2719
+ sample.score = reward;
2720
+ sample.correct = reward >= 1;
2721
+ }
2722
+ await evals.pushSamples(evaluationId, [sample]);
2723
+ await evals.finalizeEvaluation(evaluationId, {
2724
+ status: agentError ? "FAILED" : "COMPLETED",
2725
+ metrics: {
2726
+ ...typeof reward === "number" ? { avg_reward: reward } : {},
2727
+ reward,
2728
+ ...Object.fromEntries(
2729
+ Object.entries(grade.rewards).map(([k, v]) => [`rewards.${k}`, v])
2730
+ )
2731
+ }
2732
+ });
2733
+ return evaluationId;
2734
+ }
2735
+ function reportFromResult(result) {
2736
+ if (typeof result === "string") return { report: result, extra: {} };
2737
+ if (result && typeof result === "object") {
2738
+ const { report, ...extra } = result;
2739
+ return {
2740
+ report: report === void 0 || report === null ? null : typeof report === "string" ? report : String(report),
2741
+ extra
2742
+ };
2743
+ }
2744
+ if (result !== void 0 && result !== null)
2745
+ return { report: String(result), extra: {} };
2746
+ return { report: null, extra: {} };
2747
+ }
2748
+ async function runTask(ref, agent, opts) {
2749
+ const runId = `wtr-${(0, import_node_crypto3.randomBytes)(6).toString("hex")}`;
2750
+ const outDir = opts.outDir ?? "runs";
2751
+ const runDir = path.join(outDir, runId);
2752
+ fs.mkdirSync(runDir, { recursive: true });
2753
+ const options = opts.options ?? {};
2754
+ const live = await openTask(ref, {
2755
+ surfaces: opts.surfaces,
2756
+ reuseWarm: opts.reuseWarm,
2757
+ options
2758
+ });
2759
+ const started = Date.now();
2760
+ try {
2761
+ await live.ready();
2762
+ let traced = false;
2763
+ if (opts.trace !== false) {
2764
+ try {
2765
+ const { isGatewayConfigured: isGatewayConfigured2, init: init2 } = await Promise.resolve().then(() => (init_init(), init_exports));
2766
+ if (isGatewayConfigured2()) {
2767
+ init2();
2768
+ traced = true;
2769
+ }
2770
+ } catch {
2771
+ traced = false;
2772
+ }
2773
+ }
2774
+ const taskRun = new TaskRun(
2775
+ runId,
2776
+ live.instruction ?? "",
2777
+ opts.model,
2778
+ live.sessions,
2779
+ await live.manifest()
2780
+ );
2781
+ let agentError = null;
2782
+ let report = null;
2783
+ let extra = {};
2784
+ try {
2785
+ const invoke = () => agent(taskRun);
2786
+ const result = traced ? await (await Promise.resolve().then(() => (init_session2(), session_exports2))).withSession(runId, invoke) : await invoke();
2787
+ ({ report, extra } = reportFromResult(result));
2788
+ } catch (error) {
2789
+ const message = (error instanceof Error ? error.message : String(error)) || "Unknown error";
2790
+ agentError = message.slice(0, 2e3);
2791
+ }
2792
+ const grade = report !== null ? await live.grade({ report }) : await live.grade();
2793
+ fs.writeFileSync(
2794
+ path.join(runDir, "manifest.json"),
2795
+ JSON.stringify(taskRun.manifest, null, 2)
2796
+ );
2797
+ fs.writeFileSync(
2798
+ path.join(runDir, "grades.json"),
2799
+ JSON.stringify(grade, null, 2)
2800
+ );
2801
+ if (report) fs.writeFileSync(path.join(runDir, "report.md"), report);
2802
+ const summary = {
2803
+ runId,
2804
+ taskId: live.taskId,
2805
+ taskVersion: live.taskVersion,
2806
+ name: live.name,
2807
+ instruction: taskRun.instruction,
2808
+ model: opts.model,
2809
+ aliases: live.aliases,
2810
+ reward: grade.reward,
2811
+ rewards: grade.rewards,
2812
+ ungraded: grade.ungraded,
2813
+ agentError,
2814
+ report,
2815
+ traced,
2816
+ runDir,
2817
+ durationSeconds: Math.round((Date.now() - started) / 10) / 100,
2818
+ notes: taskRun.notes,
2819
+ filed: false,
2820
+ ...extra
2821
+ };
2822
+ if (opts.file !== false) {
2823
+ summary.evaluationId = await fileTaskRun(
2824
+ live,
2825
+ runId,
2826
+ opts.model,
2827
+ report,
2828
+ grade,
2829
+ agentError,
2830
+ traced,
2831
+ runDir,
2832
+ options
2833
+ );
2834
+ summary.filed = true;
2835
+ }
2836
+ fs.writeFileSync(
2837
+ path.join(runDir, "run.json"),
2838
+ JSON.stringify(summary, null, 2)
2839
+ );
2840
+ return summary;
2841
+ } finally {
2842
+ if (!opts.keepUp) {
2843
+ try {
2844
+ await live.close({ keepWarm: false });
2845
+ } catch {
2846
+ }
2847
+ }
2848
+ }
2849
+ }
2850
+ var import_node_crypto3, fs, path, TaskRun;
2851
+ var init_taskRun = __esm({
2852
+ "src/worlds/taskRun.ts"() {
2853
+ "use strict";
2854
+ import_node_crypto3 = require("crypto");
2855
+ fs = __toESM(require("fs"));
2856
+ path = __toESM(require("path"));
2857
+ init_browser();
2858
+ init_evals();
2859
+ init_session();
2860
+ init_taskSessions();
2861
+ TaskRun = class {
2862
+ constructor(runId, instruction, model, sessions, manifest) {
2863
+ this.runId = runId;
2864
+ this.instruction = instruction;
2865
+ this.model = model;
2866
+ this.sessions = sessions;
2867
+ this.manifest = manifest;
2868
+ }
2869
+ notes = {};
2870
+ /** The alias's session, or a clear error naming the aliases there are. */
2871
+ session(alias) {
2872
+ const session = this.sessions[alias];
2873
+ if (!session)
2874
+ throw new Error(
2875
+ `task run has no world '${alias}'; its worlds are ${Object.keys(this.sessions).join(", ")}`
2876
+ );
2877
+ return session;
2878
+ }
2879
+ /** `alias`'s HTTP API. Raises the same error the session itself would
2880
+ * when it was not opened with `surfaces: ["api"]`. */
2881
+ async api(alias) {
2882
+ const surfaces = await this.session(alias).surfaces();
2883
+ if (!surfaces.api)
2884
+ throw new WorldSurfaceUnavailable(
2885
+ "api",
2886
+ `open '${alias}' with surfaces: ['api']`
996
2887
  );
997
- for (const call of page.calls) {
998
- calls.push({
999
- seq: Number(call.seq),
1000
- kind: String(call.kind ?? "call"),
1001
- tool: typeof call.tool === "string" ? call.tool : null,
1002
- args: call.args ?? null,
1003
- result: call.result ?? null,
1004
- error: typeof call.error === "string" ? call.error : null,
1005
- completedAt: typeof call.completedAt === "string" ? call.completedAt : null
1006
- });
1007
- }
1008
- cursor = page.nextCursor ?? void 0;
1009
- } while (cursor);
1010
- return calls;
2888
+ return { url: surfaces.api.url, token: surfaces.api.token };
1011
2889
  }
1012
- /**
1013
- * Promote this session's inline task into a stored task of the project
1014
- * (version 1, pinned to the session's world unless `world` says otherwise),
1015
- * so a task written for one end user can be reused and its grades
1016
- * compared. The session then records the new task's id. A session on a
1017
- * bundled task has nothing to save; one on a stored task is already saved.
1018
- */
1019
- async saveTask(opts = {}) {
1020
- const task = await apiRequest(
1021
- this.options,
1022
- "POST",
1023
- `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/task`,
1024
- {
1025
- ...opts.name !== void 0 ? { name: opts.name } : {},
1026
- ...opts.world !== void 0 ? { world: opts.world } : {},
1027
- ...opts.message !== void 0 ? { message: opts.message } : {}
1028
- }
1029
- );
1030
- this.current = {
1031
- ...this.current,
1032
- taskName: task.name,
1033
- task: {
1034
- ...this.taskInfo,
1035
- source: "stored",
1036
- name: task.name,
1037
- id: task.id,
1038
- version: task.version
2890
+ /** Every world's tools merged into one toolkit, each name prefixed
2891
+ * `<alias>.<tool>` so a model can tell which world a call goes to. A
2892
+ * world that exposes no tools contributes nothing — there is nothing to
2893
+ * merge. */
2894
+ async toolkit() {
2895
+ const schemas = [];
2896
+ const impls = {};
2897
+ const specs = [];
2898
+ for (const [alias, session] of Object.entries(this.sessions)) {
2899
+ const kit = await session.toolkit();
2900
+ if (!kit.specs.length) continue;
2901
+ for (const spec of kit.specs) {
2902
+ const name = `${alias}.${spec.name}`;
2903
+ const prefixed = {
2904
+ name,
2905
+ signature: spec.signature,
2906
+ doc: spec.doc,
2907
+ inputSchema: spec.inputSchema
2908
+ };
2909
+ specs.push(prefixed);
2910
+ const schema = schemaFromSignature(prefixed);
2911
+ schema.function.name = name;
2912
+ schemas.push(schema);
2913
+ impls[name] = kit.impls[modelToolName(spec.name)];
1039
2914
  }
1040
- };
1041
- return task;
2915
+ }
2916
+ return { schemas, impls, specs };
1042
2917
  }
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
- );
2918
+ /** Log arbitrary notes into this run's `run.json` (merged; a later call
2919
+ * overrides a key an earlier one set). */
2920
+ record(notes) {
2921
+ Object.assign(this.notes, notes);
1055
2922
  }
1056
2923
  };
1057
2924
  }
1058
2925
  });
1059
2926
 
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
- );
1088
- }
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
1101
- );
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}`
1109
- );
1110
- }
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
- );
1125
- }
1126
- var TASKS, taskRoute, compact;
1127
- var init_tasks = __esm({
1128
- "src/worlds/tasks.ts"() {
2927
+ // src/worlds/worldDir.ts
2928
+ var import_node_crypto4, fs2, path2, WORLD_MANIFEST, API_BUNDLE_MANIFEST, BUNDLED_WORLD_PREFIX, CONNECTOR_SPEC, PYPROJECT, WORLD_SCHEMA_MARKERS, WORLD_ROOT_MARKERS, BROAD_ROOT_MARKERS, SKIPPED_DIRS, V1_DEP, V1_IMPORT, V1_TASKSET, HARBOR_TASK, skippedDir, byCodePoint, WorldDir;
2929
+ var init_worldDir = __esm({
2930
+ "src/worlds/worldDir.ts"() {
1129
2931
  "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));
2932
+ import_node_crypto4 = require("crypto");
2933
+ fs2 = __toESM(require("fs"));
2934
+ path2 = __toESM(require("path"));
2935
+ WORLD_MANIFEST = "gateway-env.toml";
2936
+ API_BUNDLE_MANIFEST = "gateway-api-world.toml";
2937
+ BUNDLED_WORLD_PREFIX = "server/world/";
2938
+ CONNECTOR_SPEC = "connector.toml";
2939
+ PYPROJECT = "pyproject.toml";
2940
+ WORLD_SCHEMA_MARKERS = ["schema/world.json", "schema/runtime.json", "schema/lock.json"];
2941
+ WORLD_ROOT_MARKERS = [CONNECTOR_SPEC, ...WORLD_SCHEMA_MARKERS];
2942
+ BROAD_ROOT_MARKERS = [WORLD_MANIFEST, API_BUNDLE_MANIFEST];
2943
+ SKIPPED_DIRS = /* @__PURE__ */ new Set(["dist", "build", "outputs", "__pycache__"]);
2944
+ V1_DEP = /["']verifiers\s*(?:\[[^\]]*\])?\s*(?:>=|~=|==|>)\s*(?:0\.(?:[2-9]\d*|[1-9]\d+)|[1-9]\d*)/;
2945
+ V1_IMPORT = /^\s*(?:from\s+verifiers\.v1\s+import\b|from\s+verifiers\s+import\s+v1\b|import\s+verifiers\.v1\b)/m;
2946
+ V1_TASKSET = /class\s+\w+\s*\(\s*(?:(?:vf|v1|verifiers(?:\.v1)?)\.)?Taskset\s*[,)]/;
2947
+ HARBOR_TASK = /^(?:tasks\/)?([^/]+)\/task\.toml$/;
2948
+ skippedDir = (name) => name.startsWith(".") || SKIPPED_DIRS.has(name) || name.endsWith(".egg-info");
2949
+ byCodePoint = (a, b) => Buffer.compare(Buffer.from(a, "utf-8"), Buffer.from(b, "utf-8"));
2950
+ WorldDir = class _WorldDir {
2951
+ constructor(dir, worldRoot) {
2952
+ this.dir = dir;
2953
+ this.worldRoot = worldRoot;
2954
+ }
2955
+ pathsMemo;
2956
+ static open(dir) {
2957
+ const present = (rel) => fs2.existsSync(path2.join(dir, rel));
2958
+ const bundled = present(API_BUNDLE_MANIFEST) && WORLD_ROOT_MARKERS.some((m) => present(BUNDLED_WORLD_PREFIX + m));
2959
+ return new _WorldDir(dir, bundled ? BUNDLED_WORLD_PREFIX : "");
2960
+ }
2961
+ // ── Files ──────────────────────────────────────────────────────────────
2962
+ has(rel) {
2963
+ return fs2.existsSync(path2.join(this.dir, rel));
2964
+ }
2965
+ text(rel) {
2966
+ try {
2967
+ return fs2.readFileSync(path2.join(this.dir, rel), "utf-8");
2968
+ } catch {
2969
+ return null;
2970
+ }
2971
+ }
2972
+ /** A path under the authored world's root. */
2973
+ worldPath(rel) {
2974
+ return this.worldRoot + rel;
2975
+ }
2976
+ /** Every regular file the archive rules keep (`_archive.py`: no hidden,
2977
+ * dist, build, outputs, pycache or egg-info directories), as sorted
2978
+ * relpaths. Root files enter only when a Gateway manifest widens the root
2979
+ * or they are README.md, pyproject.toml or Python. */
2980
+ get archivePaths() {
2981
+ if (this.pathsMemo) return this.pathsMemo;
2982
+ const broad = BROAD_ROOT_MARKERS.some((m) => this.has(m));
2983
+ const out = [];
2984
+ const walk = (rel) => {
2985
+ for (const entry of fs2.readdirSync(rel ? path2.join(this.dir, rel) : this.dir, { withFileTypes: true })) {
2986
+ const child = rel ? `${rel}/${entry.name}` : entry.name;
2987
+ if (entry.isDirectory()) {
2988
+ if (!skippedDir(entry.name)) walk(child);
2989
+ } else if (entry.isFile() && !entry.name.startsWith(".")) {
2990
+ const rootKept = broad || ["README.md", PYPROJECT].includes(entry.name) || entry.name.endsWith(".py");
2991
+ if (rel || rootKept) out.push(child);
2992
+ }
2993
+ }
2994
+ };
2995
+ walk("");
2996
+ return this.pathsMemo = out.sort(byCodePoint);
2997
+ }
2998
+ /** A root `.gitignore` is present: the Python SDK honours it when
2999
+ * collecting, this package does not reimplement gitignore. */
3000
+ get hasRootGitignore() {
3001
+ return this.has(".gitignore");
3002
+ }
3003
+ /** SHA-256 over `utf8("file:" + relpath)` + bytes per archive path in
3004
+ * sorted order: the version's identity, byte-compatible with
3005
+ * `_archive.compute_content_hash` and Prime Intellect. */
3006
+ get contentHash() {
3007
+ const hasher = (0, import_node_crypto4.createHash)("sha256");
3008
+ for (const rel of this.archivePaths) {
3009
+ hasher.update(Buffer.from(`file:${rel}`, "utf-8"));
3010
+ hasher.update(fs2.readFileSync(path2.join(this.dir, rel)));
3011
+ }
3012
+ return hasher.digest("hex");
3013
+ }
3014
+ // ── Markers ────────────────────────────────────────────────────────────
3015
+ get isApiBundle() {
3016
+ return this.has(API_BUNDLE_MANIFEST);
3017
+ }
3018
+ get hasManifest() {
3019
+ return this.has(this.worldPath(WORLD_MANIFEST));
3020
+ }
3021
+ get hasSchemaMarker() {
3022
+ return WORLD_SCHEMA_MARKERS.some((m) => this.has(this.worldPath(m)));
3023
+ }
3024
+ /** Harbor task dirs, relative to the tree: `tasks/<name>` when a `tasks/`
3025
+ * dir holds them, else the root `<name>` dirs. */
3026
+ taskDirs() {
3027
+ const names = /* @__PURE__ */ new Set();
3028
+ for (const rel of this.archivePaths) {
3029
+ const m = HARBOR_TASK.exec(rel);
3030
+ if (m) names.add(rel.startsWith("tasks/") ? `tasks/${m[1]}` : m[1]);
3031
+ }
3032
+ const under = [...names].filter((n) => n.startsWith("tasks/"));
3033
+ return (under.length ? under : [...names]).sort();
3034
+ }
3035
+ /** The Python package of a verifiers tree (`<pkg>/__init__.py` or
3036
+ * `src/<pkg>/__init__.py`), or null. */
3037
+ pythonPackage() {
3038
+ if (!this.has(PYPROJECT)) return null;
3039
+ for (const base of ["", "src/"]) {
3040
+ const init2 = this.archivePaths.find((rel) => {
3041
+ const m = /^([^/]+)\/__init__\.py$/.exec(rel.startsWith(base) ? rel.slice(base.length) : "");
3042
+ return m !== null && m[1] !== "tests";
3043
+ });
3044
+ if (init2) return { name: init2.slice(base.length).split("/")[0], init: init2 };
3045
+ }
3046
+ return null;
3047
+ }
3048
+ /** The package targets the `verifiers.v1` API: read from the root
3049
+ * pyproject and every archived Python module. */
3050
+ get isVerifiersV1() {
3051
+ for (const rel of this.archivePaths) {
3052
+ if (rel !== PYPROJECT && !rel.endsWith(".py")) continue;
3053
+ const text2 = this.text(rel);
3054
+ if (text2 === null) continue;
3055
+ if (rel === PYPROJECT ? V1_DEP.test(text2) : V1_IMPORT.test(text2) || text2.includes("__all__") && V1_TASKSET.test(text2))
3056
+ return true;
3057
+ }
3058
+ return false;
3059
+ }
3060
+ // ── The answer ─────────────────────────────────────────────────────────
3061
+ /** The runner's kind (`detect_env_kind`): api / mock-tools win over
3062
+ * everything, a harbor task tree next, then the verifiers API version. */
3063
+ get kind() {
3064
+ if (this.isApiBundle) return "api";
3065
+ if (this.has(WORLD_MANIFEST)) return "mock-tools";
3066
+ if (this.taskDirs().length) return "harbor";
3067
+ return this.isVerifiersV1 ? "verifiers-v1" : "verifiers";
3068
+ }
3069
+ };
1134
3070
  }
1135
3071
  });
1136
3072
 
@@ -1142,62 +3078,27 @@ __export(hub_exports, {
1142
3078
  collectArchiveRelPaths: () => collectArchiveRelPaths,
1143
3079
  computeContentHash: () => computeContentHash,
1144
3080
  createRef: () => createRef,
1145
- isIncludedInContentHash: () => isIncludedInContentHash,
1146
3081
  localTreeState: () => localTreeState,
1147
3082
  propose: () => propose,
1148
3083
  pull: () => pull,
1149
3084
  push: () => push,
3085
+ pushSlug: () => pushSlug,
1150
3086
  readLocalMeta: () => readLocalMeta,
1151
3087
  snapshotTreeHashes: () => snapshotTreeHashes,
1152
3088
  writeLocalMeta: () => writeLocalMeta
1153
3089
  });
1154
- function isExcludedDirComponent(component) {
1155
- return component.startsWith(".") || ROOT_EXCLUDED_DIRS.has(component) || component.endsWith(".egg-info");
1156
- }
1157
- function isIncludedInContentHash(relPath, includeAllRootFiles) {
1158
- const parts = relPath.split("/");
1159
- const name = parts[parts.length - 1];
1160
- const dirParts = parts.slice(0, -1);
1161
- if (name.startsWith(".")) return false;
1162
- if (parts.includes("__pycache__")) return false;
1163
- if (dirParts.length === 0) {
1164
- return includeAllRootFiles || name === "README.md" || name === "pyproject.toml" || BROAD_ROOT_MARKERS.includes(name) || name.endsWith(".py");
1165
- }
1166
- return !dirParts.some(isExcludedDirComponent);
1167
- }
1168
3090
  function collectArchiveRelPaths(dir) {
1169
- if (fs.existsSync(path.join(dir, ".gitignore"))) {
3091
+ const world = WorldDir.open(dir);
3092
+ if (world.hasRootGitignore) {
1170
3093
  throw new Error(
1171
3094
  "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
3095
  );
1173
3096
  }
1174
- const out = [];
1175
- const includeAllRootFiles = BROAD_ROOT_MARKERS.some(
1176
- (marker) => fs.existsSync(path.join(dir, marker))
1177
- );
1178
- 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))) {
1181
- const childRel = rel ? `${rel}/${entry.name}` : entry.name;
1182
- if (entry.isDirectory()) {
1183
- if (!isExcludedDirComponent(entry.name)) walk(childRel);
1184
- } else if (entry.isFile()) {
1185
- if (isIncludedInContentHash(childRel, includeAllRootFiles)) {
1186
- out.push(childRel);
1187
- }
1188
- }
1189
- }
1190
- };
1191
- walk("");
1192
- return out.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
3097
+ return world.archivePaths;
1193
3098
  }
1194
3099
  function computeContentHash(dir) {
1195
- const hasher = (0, import_node_crypto2.createHash)("sha256");
1196
- for (const relPath of collectArchiveRelPaths(dir)) {
1197
- hasher.update(Buffer.from(`file:${relPath}`, "utf-8"));
1198
- hasher.update(fs.readFileSync(path.join(dir, relPath)));
1199
- }
1200
- return hasher.digest("hex");
3100
+ collectArchiveRelPaths(dir);
3101
+ return WorldDir.open(dir).contentHash;
1201
3102
  }
1202
3103
  function octal(value, length) {
1203
3104
  return Buffer.from(value.toString(8).padStart(length - 1, "0") + "\0", "ascii");
@@ -1245,28 +3146,34 @@ function tarMember(name, payload) {
1245
3146
  function buildSourceTarball(dir) {
1246
3147
  const parts = [];
1247
3148
  for (const relPath of collectArchiveRelPaths(dir)) {
1248
- parts.push(...tarMember(relPath, fs.readFileSync(path.join(dir, relPath))));
3149
+ parts.push(...tarMember(relPath, fs3.readFileSync(path3.join(dir, relPath))));
1249
3150
  }
1250
3151
  parts.push(Buffer.alloc(1024));
1251
3152
  return (0, import_node_zlib.gzipSync)(Buffer.concat(parts), { level: 9 });
1252
3153
  }
1253
3154
  function readLocalMeta(dir) {
1254
3155
  try {
1255
- const raw = fs.readFileSync(path.join(dir, META_RELPATH), "utf-8");
3156
+ const raw = fs3.readFileSync(path3.join(dir, META_RELPATH), "utf-8");
1256
3157
  const parsed = JSON.parse(raw);
1257
3158
  return parsed && typeof parsed === "object" ? parsed : null;
1258
3159
  } catch {
1259
3160
  return null;
1260
3161
  }
1261
3162
  }
3163
+ function pushSlug(dir, explicit) {
3164
+ if (explicit) return explicit;
3165
+ const meta = readLocalMeta(dir);
3166
+ if (typeof meta?.slug === "string" && meta.slug) return meta.slug;
3167
+ return readPyproject(dir).name ?? path3.basename(path3.resolve(dir));
3168
+ }
1262
3169
  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));
3170
+ fs3.mkdirSync(path3.join(dir, ".gateway"), { recursive: true });
3171
+ fs3.writeFileSync(path3.join(dir, META_RELPATH), JSON.stringify(meta, null, 2));
1265
3172
  }
1266
3173
  function snapshotTreeHashes(dir) {
1267
3174
  const out = {};
1268
3175
  for (const relPath of collectArchiveRelPaths(dir)) {
1269
- out[relPath] = (0, import_node_crypto2.createHash)("sha256").update(fs.readFileSync(path.join(dir, relPath))).digest("hex");
3176
+ out[relPath] = (0, import_node_crypto5.createHash)("sha256").update(fs3.readFileSync(path3.join(dir, relPath))).digest("hex");
1270
3177
  }
1271
3178
  return out;
1272
3179
  }
@@ -1284,7 +3191,7 @@ function localTreeState(dir) {
1284
3191
  }
1285
3192
  function readPyproject(dir) {
1286
3193
  try {
1287
- const text2 = fs.readFileSync(path.join(dir, "pyproject.toml"), "utf-8");
3194
+ const text2 = fs3.readFileSync(path3.join(dir, "pyproject.toml"), "utf-8");
1288
3195
  const section = /\[project\]([\s\S]*?)(\n\[|$)/.exec(text2)?.[1] ?? "";
1289
3196
  const name = /\bname\s*=\s*"([^"]+)"/.exec(section)?.[1];
1290
3197
  const version = /\bversion\s*=\s*"([^"]+)"/.exec(section)?.[1];
@@ -1294,33 +3201,32 @@ function readPyproject(dir) {
1294
3201
  }
1295
3202
  }
1296
3203
  function readWorldContractVersion(dir) {
1297
- for (const rel of ["schema/world.json", path.join("server", "world", "schema", "world.json")]) {
1298
- try {
1299
- const parsed = JSON.parse(fs.readFileSync(path.join(dir, rel), "utf-8"));
1300
- const pkg = parsed["x-gateway"]?.package;
1301
- if (pkg?.version) return { name: pkg.id, version: pkg.version };
1302
- } catch {
1303
- }
3204
+ const world = WorldDir.open(dir);
3205
+ try {
3206
+ const parsed = JSON.parse(world.text(world.worldPath("schema/world.json")) ?? "");
3207
+ const pkg = parsed["x-gateway"]?.package;
3208
+ if (pkg?.version) return { name: pkg.id, version: pkg.version };
3209
+ } catch {
1304
3210
  }
1305
3211
  return {};
1306
3212
  }
1307
3213
  function buildFileManifest(dir) {
1308
3214
  const entries = [];
1309
3215
  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))) {
3216
+ const abs = rel ? path3.join(dir, rel) : dir;
3217
+ for (const entry of fs3.readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
1312
3218
  const childRel = rel ? `${rel}/${entry.name}` : entry.name;
1313
3219
  if (entry.isDirectory()) {
1314
3220
  if (!SKIP_DIRS.has(entry.name) && !entry.name.endsWith(".egg-info")) {
1315
3221
  walk(childRel);
1316
3222
  }
1317
3223
  } else if (entry.isFile()) {
1318
- const payload = fs.readFileSync(path.join(dir, childRel));
3224
+ const payload = fs3.readFileSync(path3.join(dir, childRel));
1319
3225
  entries.push({
1320
3226
  path: childRel,
1321
3227
  isDirectory: false,
1322
3228
  size: payload.length,
1323
- sha256: (0, import_node_crypto2.createHash)("sha256").update(payload).digest("hex")
3229
+ sha256: (0, import_node_crypto5.createHash)("sha256").update(payload).digest("hex")
1324
3230
  });
1325
3231
  }
1326
3232
  }
@@ -1343,7 +3249,7 @@ async function putObject(url, data, shaB64) {
1343
3249
  }
1344
3250
  async function push(dir, opts = {}) {
1345
3251
  const options = opts.options ?? {};
1346
- if (!fs.statSync(dir).isDirectory()) throw new Error(`Not a directory: ${dir}`);
3252
+ if (!fs3.statSync(dir).isDirectory()) throw new Error(`Not a directory: ${dir}`);
1347
3253
  const localMeta = readLocalMeta(dir) ?? {};
1348
3254
  const branch = opts.branch ?? localMeta.branch ?? DEFAULT_BRANCH;
1349
3255
  const baseVersionId = opts.baseVersionId ?? localMeta.versionId ?? null;
@@ -1351,18 +3257,18 @@ async function push(dir, opts = {}) {
1351
3257
  const pyproject = readPyproject(dir);
1352
3258
  const contractVersion = pyproject.version ? void 0 : readWorldContractVersion(dir).version;
1353
3259
  if (contractVersion) pyproject.version = contractVersion;
1354
- const slug = opts.slug ?? localMeta.slug ?? pyproject.name ?? path.basename(path.resolve(dir));
3260
+ const slug = opts.slug ?? localMeta.slug ?? pyproject.name ?? path3.basename(path3.resolve(dir));
3261
+ const metadata = {
3262
+ name: opts.name ?? pyproject.name ?? slug,
3263
+ ...opts.description !== void 0 ? { description: opts.description } : {},
3264
+ ...opts.tags !== void 0 ? { tags: opts.tags } : {},
3265
+ ...opts.visibility ? { visibility: opts.visibility } : {}
3266
+ };
1355
3267
  const resolve6 = await apiRequest(
1356
3268
  options,
1357
3269
  "POST",
1358
3270
  "/api/public/benchmark-containers/resolve",
1359
- {
1360
- slug,
1361
- name: opts.name ?? pyproject.name ?? slug,
1362
- ...opts.description ? { description: opts.description } : {},
1363
- ...opts.tags?.length ? { tags: opts.tags } : {},
1364
- ...opts.visibility ? { visibility: opts.visibility } : {}
1365
- }
3271
+ { slug, ...metadata }
1366
3272
  );
1367
3273
  const tarball = buildSourceTarball(dir);
1368
3274
  const bundleSha256 = sha256b64(tarball);
@@ -1386,7 +3292,7 @@ async function push(dir, opts = {}) {
1386
3292
  options,
1387
3293
  "POST",
1388
3294
  `/api/public/benchmark-containers/versions/${version.versionId}/finalize`,
1389
- { branch, baseVersionId, ...opts.force ? { force: true } : {} }
3295
+ { branch, baseVersionId, ...opts.force ? { force: true } : {}, ...metadata }
1390
3296
  );
1391
3297
  writeLocalMeta(dir, {
1392
3298
  ...localMeta,
@@ -1431,9 +3337,9 @@ function extractBundle(bundle, dir) {
1431
3337
  longName = null;
1432
3338
  if (typeflag !== "0" && typeflag !== "") continue;
1433
3339
  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);
3340
+ const target = path3.join(dir, name);
3341
+ fs3.mkdirSync(path3.dirname(target), { recursive: true });
3342
+ fs3.writeFileSync(target, body);
1437
3343
  written++;
1438
3344
  }
1439
3345
  return written;
@@ -1449,13 +3355,13 @@ async function pull(slugRef, target, options = {}) {
1449
3355
  if (!details.downloadUrl) {
1450
3356
  throw new Error(`${slug}@${ref} resolved but has no uploaded bundle`);
1451
3357
  }
1452
- let dir = target ?? path.join(process.cwd(), slug);
3358
+ let dir = target ?? path3.join(process.cwd(), slug);
1453
3359
  if (!target) {
1454
3360
  let i = 1;
1455
3361
  const base = dir;
1456
- while (fs.existsSync(dir)) dir = `${base}-${i++}`;
3362
+ while (fs3.existsSync(dir)) dir = `${base}-${i++}`;
1457
3363
  }
1458
- fs.mkdirSync(dir, { recursive: true });
3364
+ fs3.mkdirSync(dir, { recursive: true });
1459
3365
  const resp = await fetch(details.downloadUrl);
1460
3366
  if (!resp.ok) throw new Error(`bundle download -> ${resp.status}`);
1461
3367
  const bundle = Buffer.from(await resp.arrayBuffer());
@@ -1482,15 +3388,15 @@ async function propose(dir, opts) {
1482
3388
  if (!meta?.slug || !meta.baseFiles) {
1483
3389
  throw new Error("This dir has no pull/push base \u2014 run pull first, then edit, then propose.");
1484
3390
  }
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" };
3391
+ const state2 = localTreeState(dir);
3392
+ if (state2.clean) throw new Error("Nothing to propose \u2014 the tree matches its base.");
3393
+ const changes = state2.dirty.map((relPath) => {
3394
+ const abs = path3.join(dir, relPath);
3395
+ if (!fs3.existsSync(abs)) return { path: relPath, action: "delete" };
1490
3396
  return {
1491
3397
  path: relPath,
1492
3398
  action: "write",
1493
- newContent: fs.readFileSync(abs, "utf-8")
3399
+ newContent: fs3.readFileSync(abs, "utf-8")
1494
3400
  };
1495
3401
  });
1496
3402
  const res = await apiRequest(
@@ -1516,17 +3422,18 @@ async function createRef(slug, name, kind, versionId, options = {}) {
1516
3422
  ...versionId ? { versionId } : {}
1517
3423
  });
1518
3424
  }
1519
- var import_node_crypto2, import_node_zlib, fs, path, DEFAULT_BRANCH, META_RELPATH, SKIP_DIRS, ROOT_EXCLUDED_DIRS, BROAD_ROOT_MARKERS, sha256b64;
3425
+ var import_node_crypto5, import_node_zlib, fs3, path3, DEFAULT_BRANCH, META_RELPATH, SKIP_DIRS, sha256b64;
1520
3426
  var init_hub = __esm({
1521
3427
  "src/worlds/hub.ts"() {
1522
3428
  "use strict";
1523
- import_node_crypto2 = require("crypto");
3429
+ import_node_crypto5 = require("crypto");
1524
3430
  import_node_zlib = require("zlib");
1525
- fs = __toESM(require("fs"));
1526
- path = __toESM(require("path"));
3431
+ fs3 = __toESM(require("fs"));
3432
+ path3 = __toESM(require("path"));
1527
3433
  init_worlds();
3434
+ init_worldDir();
1528
3435
  DEFAULT_BRANCH = "main";
1529
- META_RELPATH = path.join(".gateway", ".env-metadata.json");
3436
+ META_RELPATH = path3.join(".gateway", ".env-metadata.json");
1530
3437
  SKIP_DIRS = /* @__PURE__ */ new Set([
1531
3438
  ".git",
1532
3439
  "__pycache__",
@@ -1537,9 +3444,7 @@ var init_hub = __esm({
1537
3444
  "build",
1538
3445
  "outputs"
1539
3446
  ]);
1540
- ROOT_EXCLUDED_DIRS = /* @__PURE__ */ new Set(["dist", "build", "outputs", "__pycache__"]);
1541
- BROAD_ROOT_MARKERS = ["gateway-env.toml", "gateway-api-world.toml"];
1542
- sha256b64 = (data) => (0, import_node_crypto2.createHash)("sha256").update(data).digest("base64");
3447
+ sha256b64 = (data) => (0, import_node_crypto5.createHash)("sha256").update(data).digest("base64");
1543
3448
  }
1544
3449
  });
1545
3450
 
@@ -1612,23 +3517,22 @@ async function validateWorld(dir, opts) {
1612
3517
  throw new Error(
1613
3518
  "No branch to validate on: pass --branch or run inside a git checkout / GitHub Actions."
1614
3519
  );
1615
- progress(`pushing ${dir} as ${opts.slug ?? "(pyproject name)"}@${branch}\u2026`);
3520
+ const slug = pushSlug(dir, opts.slug);
3521
+ progress(`pushing ${dir} as ${slug}@${branch}\u2026`);
1616
3522
  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
- }
3523
+ try {
3524
+ const tip = await apiRequest(
3525
+ options,
3526
+ "POST",
3527
+ "/api/public/benchmark-containers/resolve-version",
3528
+ { slug, ref: branch }
3529
+ );
3530
+ tipVersionId = tip.versionId ?? null;
3531
+ } catch {
3532
+ tipVersionId = null;
1629
3533
  }
1630
3534
  const pushed = await push(dir, {
1631
- slug: opts.slug,
3535
+ slug,
1632
3536
  branch,
1633
3537
  baseVersionId: tipVersionId,
1634
3538
  message: `PR validation push (${provenance.commit?.slice(0, 12) ?? "local"})`,
@@ -2056,15 +3960,15 @@ function applyTransforms(value, chain) {
2056
3960
  for (const step of steps) out = step(out);
2057
3961
  return out;
2058
3962
  }
2059
- var import_node_crypto3, WHITESPACE, WHITESPACE_EDGES, WHITESPACE_RUN, NOT_DIGIT, STRIP_PREFIX, trim, emailLocalPart, emailDomain, stripPrefix, hex, SIMPLE, TRANSFORMS, text;
3963
+ var import_node_crypto6, WHITESPACE, WHITESPACE_EDGES, WHITESPACE_RUN, NOT_DIGIT, STRIP_PREFIX, trim, emailLocalPart, emailDomain, stripPrefix, hex, SIMPLE, TRANSFORMS, text;
2060
3964
  var init_transforms = __esm({
2061
3965
  "src/worlds/transforms.ts"() {
2062
3966
  "use strict";
2063
- import_node_crypto3 = require("crypto");
3967
+ import_node_crypto6 = require("crypto");
2064
3968
  init_json();
2065
3969
  WHITESPACE = " \n\r\f\v";
2066
- WHITESPACE_EDGES = /^[ \t\n\r\f\v]+|[ \t\n\r\f\v]+$/g;
2067
- WHITESPACE_RUN = /[ \t\n\r\f\v]+/g;
3970
+ WHITESPACE_EDGES = new RegExp(`^[${WHITESPACE}]+|[${WHITESPACE}]+$`, "g");
3971
+ WHITESPACE_RUN = new RegExp(`[${WHITESPACE}]+`, "g");
2068
3972
  NOT_DIGIT = /[^0-9]/g;
2069
3973
  STRIP_PREFIX = "strip_prefix";
2070
3974
  trim = (value) => value.replace(WHITESPACE_EDGES, "");
@@ -2077,7 +3981,7 @@ var init_transforms = __esm({
2077
3981
  return at === -1 ? "" : value.slice(at + 1).toLowerCase();
2078
3982
  };
2079
3983
  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");
3984
+ hex = (algorithm, value) => (0, import_node_crypto6.createHash)(algorithm).update(value, "utf8").digest("hex");
2081
3985
  SIMPLE = {
2082
3986
  lower: (value) => value.toLowerCase(),
2083
3987
  upper: (value) => value.toUpperCase(),
@@ -2109,7 +4013,7 @@ function pyText(value) {
2109
4013
  return pyFloatRepr(value);
2110
4014
  }
2111
4015
  function hashForm(slug, plaintext) {
2112
- return "sha256:" + (0, import_node_crypto4.createHash)("sha256").update(`${slug}:${pyText(plaintext)}`, "utf8").digest("hex");
4016
+ return "sha256:" + (0, import_node_crypto7.createHash)("sha256").update(`${slug}:${pyText(plaintext)}`, "utf8").digest("hex");
2113
4017
  }
2114
4018
  function preserveForm(slug, plaintext) {
2115
4019
  const kind = typeof plaintext === "string" ? "str" : isInt(plaintext) ? "int" : "float";
@@ -2118,12 +4022,12 @@ function preserveForm(slug, plaintext) {
2118
4022
  }
2119
4023
  function shapeText(slug, text2, kind) {
2120
4024
  const seed = Buffer.from(`${slug}:${text2}`, "utf8");
2121
- let digest = (0, import_node_crypto4.createHash)("sha256").update(seed).digest();
4025
+ let digest = (0, import_node_crypto7.createHash)("sha256").update(seed).digest();
2122
4026
  let cursor = 0;
2123
4027
  const out = [];
2124
4028
  for (const char of text2) {
2125
4029
  if (cursor === digest.length) {
2126
- digest = (0, import_node_crypto4.createHash)("sha256").update(Buffer.concat([digest, seed])).digest();
4030
+ digest = (0, import_node_crypto7.createHash)("sha256").update(Buffer.concat([digest, seed])).digest();
2127
4031
  cursor = 0;
2128
4032
  }
2129
4033
  const byte = digest[cursor];
@@ -2160,11 +4064,11 @@ function storedForms(world, field, plaintext, transform) {
2160
4064
  if (policy !== null) return [roundForm(plaintext, world.redact.round[field])];
2161
4065
  return [plaintext];
2162
4066
  }
2163
- var import_node_crypto4, isInt;
4067
+ var import_node_crypto7, isInt;
2164
4068
  var init_redaction = __esm({
2165
4069
  "src/worlds/redaction.ts"() {
2166
4070
  "use strict";
2167
- import_node_crypto4 = require("crypto");
4071
+ import_node_crypto7 = require("crypto");
2168
4072
  init_json();
2169
4073
  init_transforms();
2170
4074
  isInt = (value) => typeof value === "number" && Number.isInteger(value);
@@ -2172,8 +4076,9 @@ var init_redaction = __esm({
2172
4076
  });
2173
4077
 
2174
4078
  // src/worlds/query.ts
2175
- function queryRowsSearch(entity, opts = {}) {
4079
+ function queryRowsSearch(entity, opts = {}, ref) {
2176
4080
  const search = new URLSearchParams();
4081
+ if (ref) search.set("ref", ref);
2177
4082
  search.set("entity", entity);
2178
4083
  if (opts.where && Object.keys(opts.where).length) search.set("where", JSON.stringify(opts.where));
2179
4084
  if (opts.limit !== void 0) search.set("limit", String(opts.limit));
@@ -2183,17 +4088,15 @@ function queryRowsSearch(entity, opts = {}) {
2183
4088
  if (opts.compare) search.set("compare", "true");
2184
4089
  return `?${search.toString()}`;
2185
4090
  }
2186
- async function queryRows(slug, entity, opts = {}, options = {}) {
2187
- if (slug.includes("@"))
2188
- throw new Error(
2189
- `queryRows reads a world's head version: pass the slug without @ref (got ${slug})`
2190
- );
4091
+ async function queryRows(slugRef, entity, opts = {}, options = {}) {
4092
+ const [slug, ref] = slugRef.split("@", 2);
4093
+ if (!slug || ref === "") throw new Error(`queryRows needs a slug, optionally slug@ref (got ${slugRef})`);
2191
4094
  if (!entity) throw new Error("queryRows needs an entity");
2192
4095
  if (opts.compare && !opts.across) throw new Error("queryRows: compare needs across");
2193
4096
  return apiRequest(
2194
4097
  options,
2195
4098
  "GET",
2196
- `/api/public/worlds/${encodeURIComponent(slug)}/data${queryRowsSearch(entity, opts)}`
4099
+ `/api/public/worlds/${encodeURIComponent(slug)}/data${queryRowsSearch(entity, opts, ref)}`
2197
4100
  );
2198
4101
  }
2199
4102
  var init_query = __esm({
@@ -2249,9 +4152,9 @@ var init_router = __esm({
2249
4152
  });
2250
4153
 
2251
4154
  // src/cli/config.ts
2252
- async function api(creds, method, route, body, init = {}) {
4155
+ async function api(creds, method, route, body, init2 = {}) {
2253
4156
  const controller = new AbortController();
2254
- const timer = setTimeout(() => controller.abort(), init.timeoutMs ?? 12e4);
4157
+ const timer = setTimeout(() => controller.abort(), init2.timeoutMs ?? 12e4);
2255
4158
  try {
2256
4159
  const res = await fetch(`${creds.host}${route}`, {
2257
4160
  method,
@@ -2270,13 +4173,13 @@ async function api(creds, method, route, body, init = {}) {
2270
4173
  clearTimeout(timer);
2271
4174
  }
2272
4175
  }
2273
- var fs2, os, path2, ApiError;
4176
+ var fs4, os, path4, ApiError;
2274
4177
  var init_config = __esm({
2275
4178
  "src/cli/config.ts"() {
2276
4179
  "use strict";
2277
- fs2 = __toESM(require("fs"));
4180
+ fs4 = __toESM(require("fs"));
2278
4181
  os = __toESM(require("os"));
2279
- path2 = __toESM(require("path"));
4182
+ path4 = __toESM(require("path"));
2280
4183
  init_router();
2281
4184
  ApiError = class extends CliError {
2282
4185
  constructor(status, method, route, text2) {
@@ -2305,16 +4208,16 @@ function runtimeRoot() {
2305
4208
  const candidates = [];
2306
4209
  if (process.env.GATEWAY_RUNTIME_PATH)
2307
4210
  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;
4211
+ const entry = process.argv[1] && fs5.existsSync(process.argv[1]) ? path5.dirname(fs5.realpathSync(process.argv[1])) : null;
2309
4212
  if (entry) {
2310
- candidates.push(path3.resolve(entry, "..", "runtime"));
2311
- candidates.push(path3.resolve(entry, "..", "..", "runtime"));
2312
- candidates.push(path3.resolve(entry, "..", "..", "sdk", "src"));
4213
+ candidates.push(path5.resolve(entry, "..", "runtime"));
4214
+ candidates.push(path5.resolve(entry, "..", "..", "runtime"));
4215
+ candidates.push(path5.resolve(entry, "..", "..", "sdk", "src"));
2313
4216
  }
2314
- candidates.push(path3.resolve(process.cwd(), "runtime"));
4217
+ candidates.push(path5.resolve(process.cwd(), "runtime"));
2315
4218
  for (const root of candidates)
2316
- if (fs3.existsSync(
2317
- path3.join(root, "gatewaysdk", "environment", "schema", "platform.py")
4219
+ if (fs5.existsSync(
4220
+ path5.join(root, "gatewaysdk", "environment", "schema", "platform.py")
2318
4221
  ))
2319
4222
  return root;
2320
4223
  return null;
@@ -2455,14 +4358,14 @@ async function localBridge(request, local, opts = {}) {
2455
4358
  child.stdin.end(input);
2456
4359
  });
2457
4360
  }
2458
- var import_node_child_process, fs3, net, path3, MIN_PYTHON, DIAGNOSTIC_TAIL, BRIDGE_BOOTSTRAP, pythonCache, pythonProbes, PYTHON_CANDIDATES, UV_FIND;
4361
+ var import_node_child_process, fs5, net, path5, MIN_PYTHON, DIAGNOSTIC_TAIL, BRIDGE_BOOTSTRAP, pythonCache, pythonProbes, PYTHON_CANDIDATES, UV_FIND;
2459
4362
  var init_local = __esm({
2460
4363
  "src/cli/runtime/local.ts"() {
2461
4364
  "use strict";
2462
4365
  import_node_child_process = require("child_process");
2463
- fs3 = __toESM(require("fs"));
4366
+ fs5 = __toESM(require("fs"));
2464
4367
  net = __toESM(require("net"));
2465
- path3 = __toESM(require("path"));
4368
+ path5 = __toESM(require("path"));
2466
4369
  init_router();
2467
4370
  init_config();
2468
4371
  MIN_PYTHON = [3, 11];
@@ -2490,12 +4393,12 @@ function isBuildOutput(relPath) {
2490
4393
  return BUILD_OUTPUT.test(relPath);
2491
4394
  }
2492
4395
  function readWorldFiles(dir, opts = {}) {
2493
- if (!fs4.existsSync(dir) || !fs4.statSync(dir).isDirectory())
4396
+ if (!fs6.existsSync(dir) || !fs6.statSync(dir).isDirectory())
2494
4397
  throw new CliError(`Not a directory: ${dir}`);
2495
4398
  const out = [];
2496
4399
  const walk = (rel) => {
2497
- const abs = rel ? path4.join(dir, rel) : dir;
2498
- const entries = fs4.readdirSync(abs, { withFileTypes: true });
4400
+ const abs = rel ? path6.join(dir, rel) : dir;
4401
+ const entries = fs6.readdirSync(abs, { withFileTypes: true });
2499
4402
  entries.sort((a, b) => a.name.localeCompare(b.name));
2500
4403
  for (const entry of entries) {
2501
4404
  const childRel = rel ? `${rel}/${entry.name}` : entry.name;
@@ -2505,7 +4408,7 @@ function readWorldFiles(dir, opts = {}) {
2505
4408
  if (!opts.buildOutputs && isBuildOutput(childRel)) continue;
2506
4409
  out.push({
2507
4410
  path: childRel,
2508
- content: fs4.readFileSync(path4.join(dir, childRel)).toString("base64")
4411
+ content: fs6.readFileSync(path6.join(dir, childRel)).toString("base64")
2509
4412
  });
2510
4413
  }
2511
4414
  }
@@ -2520,19 +4423,19 @@ function assertSafeRelPath(rel) {
2520
4423
  }
2521
4424
  function writeWorldFiles(dir, files, opts = {}) {
2522
4425
  for (const file of files) assertSafeRelPath(file.path);
2523
- if (opts.clean && fs4.existsSync(dir)) {
4426
+ if (opts.clean && fs6.existsSync(dir)) {
2524
4427
  const keep = new Set(files.map((f) => f.path));
2525
4428
  for (const existing of readWorldFiles(dir)) {
2526
- if (!keep.has(existing.path)) fs4.rmSync(path4.join(dir, existing.path));
4429
+ if (!keep.has(existing.path)) fs6.rmSync(path6.join(dir, existing.path));
2527
4430
  }
2528
4431
  pruneEmptyDirs(dir);
2529
4432
  }
2530
- fs4.mkdirSync(dir, { recursive: true });
4433
+ fs6.mkdirSync(dir, { recursive: true });
2531
4434
  const written = [];
2532
4435
  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"));
4436
+ const target = path6.join(dir, file.path);
4437
+ fs6.mkdirSync(path6.dirname(target), { recursive: true });
4438
+ fs6.writeFileSync(target, Buffer.from(file.content, "base64"));
2536
4439
  written.push(file.path);
2537
4440
  }
2538
4441
  return written;
@@ -2540,14 +4443,14 @@ function writeWorldFiles(dir, files, opts = {}) {
2540
4443
  function pruneEmptyDirs(root) {
2541
4444
  const walk = (abs) => {
2542
4445
  let empty = true;
2543
- for (const entry of fs4.readdirSync(abs, { withFileTypes: true })) {
2544
- const child = path4.join(abs, entry.name);
4446
+ for (const entry of fs6.readdirSync(abs, { withFileTypes: true })) {
4447
+ const child = path6.join(abs, entry.name);
2545
4448
  if (entry.isDirectory()) {
2546
4449
  if (SKIP_DIRS2.has(entry.name)) {
2547
4450
  empty = false;
2548
4451
  continue;
2549
4452
  }
2550
- if (walk(child)) fs4.rmdirSync(child);
4453
+ if (walk(child)) fs6.rmdirSync(child);
2551
4454
  else empty = false;
2552
4455
  } else empty = false;
2553
4456
  }
@@ -2611,12 +4514,12 @@ async function runtime(creds, request, opts = {}) {
2611
4514
  clearTimeout(timer);
2612
4515
  }
2613
4516
  }
2614
- var fs4, path4, SKIP_DIRS2, BUILD_OUTPUT, BridgeRejected;
4517
+ var fs6, path6, SKIP_DIRS2, BUILD_OUTPUT, BridgeRejected;
2615
4518
  var init_client = __esm({
2616
4519
  "src/cli/runtime/client.ts"() {
2617
4520
  "use strict";
2618
- fs4 = __toESM(require("fs"));
2619
- path4 = __toESM(require("path"));
4521
+ fs6 = __toESM(require("fs"));
4522
+ path6 = __toESM(require("path"));
2620
4523
  init_router();
2621
4524
  init_local();
2622
4525
  SKIP_DIRS2 = /* @__PURE__ */ new Set(["__pycache__", ".git", "node_modules", ".gateway"]);
@@ -2666,7 +4569,7 @@ function dropBuildOutputs(dir) {
2666
4569
  const dropped = [];
2667
4570
  for (const file of readWorldFiles(dir, { buildOutputs: true })) {
2668
4571
  if (!BUILD_OUTPUT2.test(file.path)) continue;
2669
- fs5.rmSync(path5.join(dir, file.path), { force: true });
4572
+ fs7.rmSync(path7.join(dir, file.path), { force: true });
2670
4573
  dropped.push(file.path);
2671
4574
  }
2672
4575
  return dropped;
@@ -2677,6 +4580,7 @@ async function checkLocalWorldData(dir, rows, creds, opts = {}) {
2677
4580
  files: readWorldFiles(dir),
2678
4581
  rows,
2679
4582
  mode: "append",
4583
+ dry_run: true,
2680
4584
  ...opts.redact && opts.redact !== "off" ? { redact: opts.redact } : {}
2681
4585
  });
2682
4586
  return {
@@ -2732,7 +4636,7 @@ async function queryLocalWorldDataAcross(dir, entity, where, opts) {
2732
4636
  const payload = await localBridge(
2733
4637
  {
2734
4638
  command: "query",
2735
- world: path5.resolve(dir),
4639
+ world: path7.resolve(dir),
2736
4640
  entity,
2737
4641
  across: true,
2738
4642
  ...opts.compare ? { compare: true } : {},
@@ -2779,12 +4683,12 @@ async function ingestLocalToolCalls(dir, records, opts, creds) {
2779
4683
  ...res.batch !== void 0 ? { batch: res.batch } : {}
2780
4684
  };
2781
4685
  }
2782
- var fs5, path5, BUILD_OUTPUT2;
4686
+ var fs7, path7, BUILD_OUTPUT2;
2783
4687
  var init_data = __esm({
2784
4688
  "src/cli/runtime/data.ts"() {
2785
4689
  "use strict";
2786
- fs5 = __toESM(require("fs"));
2787
- path5 = __toESM(require("path"));
4690
+ fs7 = __toESM(require("fs"));
4691
+ path7 = __toESM(require("path"));
2788
4692
  init_router();
2789
4693
  init_client();
2790
4694
  init_local();
@@ -2827,27 +4731,27 @@ function typescriptPrefix() {
2827
4731
  }
2828
4732
  }
2829
4733
  function command(script, wrapperDir) {
2830
- const suffix = path6.extname(script).toLowerCase();
4734
+ const suffix = path8.extname(script).toLowerCase();
2831
4735
  if (PYTHON_SUFFIXES.includes(suffix)) return { file: process.env.GATEWAY_PYTHON || "python3", args: ["-c", PY_WRAPPER, script] };
2832
4736
  if (NODE_SUFFIXES.includes(suffix)) {
2833
- const wrapper = path6.join(wrapperDir, "transform-wrapper.mjs");
2834
- fs6.writeFileSync(wrapper, NODE_WRAPPER);
4737
+ const wrapper = path8.join(wrapperDir, "transform-wrapper.mjs");
4738
+ fs8.writeFileSync(wrapper, NODE_WRAPPER);
2835
4739
  const flags = suffix === ".ts" || suffix === ".mts" ? typescriptPrefix() : [];
2836
4740
  return { file: process.env.GATEWAY_NODE || process.execPath, args: [...flags, wrapper, script] };
2837
4741
  }
2838
- throw new CliError(`${path6.basename(script)}: a transform script is .py, .ts, .mjs, .js or .cjs`, 1);
4742
+ throw new CliError(`${path8.basename(script)}: a transform script is .py, .ts, .mjs, .js or .cjs`, 1);
2839
4743
  }
2840
4744
  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);
4745
+ if (!fs8.existsSync(script) || !fs8.statSync(script).isFile()) throw new CliError(`no transform script at ${script}`, 1);
4746
+ const resolved = path8.resolve(script);
4747
+ const name = path8.basename(script);
2844
4748
  const timeoutMs = opts.timeoutMs ?? DEFAULT_TRANSFORM_TIMEOUT_MS;
2845
- const scratch = fs6.mkdtempSync(path6.join(os2.tmpdir(), "gateway-transform-"));
4749
+ const scratch = fs8.mkdtempSync(path8.join(os2.tmpdir(), "gateway-transform-"));
2846
4750
  try {
2847
4751
  const { file, args } = command(resolved, scratch);
2848
4752
  const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !SCRUBBED.test(key)));
2849
4753
  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"] });
4754
+ const child = (0, import_node_child_process2.spawn)(file, args, { cwd: path8.dirname(resolved), env, stdio: ["pipe", "pipe", "pipe"] });
2851
4755
  let stdout = "";
2852
4756
  let stderr = "";
2853
4757
  let timedOut = false;
@@ -2878,21 +4782,21 @@ async function runTransform(script, records, opts = {}) {
2878
4782
  }
2879
4783
  return { rows: checkRows(value, name), stderr: done.stderr };
2880
4784
  } finally {
2881
- fs6.rmSync(scratch, { recursive: true, force: true });
4785
+ fs8.rmSync(scratch, { recursive: true, force: true });
2882
4786
  }
2883
4787
  }
2884
4788
  async function transformRecords(transform, records, opts = {}) {
2885
4789
  if (typeof transform === "function") return { rows: checkRows(await transform(records), "transform(records)"), stderr: "" };
2886
4790
  return runTransform(transform, records, opts);
2887
4791
  }
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;
4792
+ var import_node_child_process2, fs8, os2, path8, import_node_module, import_meta, DEFAULT_TRANSFORM_TIMEOUT_MS, NODE_SUFFIXES, PYTHON_SUFFIXES, SCRUBBED, PY_WRAPPER, NODE_WRAPPER, isObject, tail;
2889
4793
  var init_transform = __esm({
2890
4794
  "src/cli/platform/worldData/transform.ts"() {
2891
4795
  "use strict";
2892
4796
  import_node_child_process2 = require("child_process");
2893
- fs6 = __toESM(require("fs"));
4797
+ fs8 = __toESM(require("fs"));
2894
4798
  os2 = __toESM(require("os"));
2895
- path6 = __toESM(require("path"));
4799
+ path8 = __toESM(require("path"));
2896
4800
  import_node_module = require("module");
2897
4801
  init_router();
2898
4802
  import_meta = {};
@@ -2976,11 +4880,16 @@ if (fn) {
2976
4880
  });
2977
4881
 
2978
4882
  // src/cli/platform/worldData/batches.ts
4883
+ function isSettled(status) {
4884
+ if (!TERMINAL_STATES.has(status.state)) return false;
4885
+ if (status.state !== "applied") return true;
4886
+ return status.dryRun === true || status.publish !== "now" || !status.snapshotId;
4887
+ }
2979
4888
  function uploadHeadersFor(gz) {
2980
4889
  return {
2981
4890
  "content-type": "application/gzip",
2982
4891
  "content-length": String(gz.length),
2983
- "x-amz-checksum-sha256": (0, import_node_crypto5.createHash)("sha256").update(gz).digest("base64")
4892
+ "x-amz-checksum-sha256": (0, import_node_crypto8.createHash)("sha256").update(gz).digest("base64")
2984
4893
  };
2985
4894
  }
2986
4895
  async function forEachLimited(items, limit, fn) {
@@ -3017,7 +4926,7 @@ async function waitForBatch(client, batchId, opts = {}) {
3017
4926
  opts.onPhase?.(phase);
3018
4927
  last = phase;
3019
4928
  }
3020
- if (TERMINAL_STATES.has(status.state)) return status;
4929
+ if (isSettled(status)) return status;
3021
4930
  await sleep2(delay);
3022
4931
  delay = Math.min(1e4, Math.round(delay * 1.5));
3023
4932
  }
@@ -3026,12 +4935,12 @@ function phaseLine(status) {
3026
4935
  const phase = status.progress?.phase;
3027
4936
  return phase ? `${status.state} (${phase})` : status.state;
3028
4937
  }
3029
- var import_node_crypto5, fs7, TERMINAL_STATES, sleepMs, WorldDataApi;
4938
+ var import_node_crypto8, fs9, TERMINAL_STATES, sleepMs, WorldDataApi;
3030
4939
  var init_batches = __esm({
3031
4940
  "src/cli/platform/worldData/batches.ts"() {
3032
4941
  "use strict";
3033
- import_node_crypto5 = require("crypto");
3034
- fs7 = __toESM(require("fs"));
4942
+ import_node_crypto8 = require("crypto");
4943
+ fs9 = __toESM(require("fs"));
3035
4944
  init_config();
3036
4945
  init_router();
3037
4946
  TERMINAL_STATES = /* @__PURE__ */ new Set(["applied", "refused", "published", "failed"]);
@@ -3121,7 +5030,7 @@ async function* buildChunks(rows, plan) {
3121
5030
  let rawBytes = 0;
3122
5031
  let ordinal = 0;
3123
5032
  let seen = 0;
3124
- const flush = () => {
5033
+ const flush2 = () => {
3125
5034
  const raw = Buffer.concat(lines);
3126
5035
  const built = finishChunk(ordinal++, raw, lines.length, plan.entity, seen - lines.length);
3127
5036
  lines = [];
@@ -3131,23 +5040,23 @@ async function* buildChunks(rows, plan) {
3131
5040
  for await (const row of rows) {
3132
5041
  const line = Buffer.from(chunkLine(row, plan.entity), "utf8");
3133
5042
  const full = lines.length > 0 && (plan.chunkRows !== null && lines.length >= plan.chunkRows || rawBytes + line.length > plan.chunkBytes);
3134
- if (full) yield flush();
5043
+ if (full) yield flush2();
3135
5044
  lines.push(line);
3136
5045
  rawBytes += line.length;
3137
5046
  seen++;
3138
5047
  }
3139
- if (lines.length) yield flush();
5048
+ if (lines.length) yield flush2();
3140
5049
  }
3141
5050
  function finishChunk(ordinal, raw, rows, entity, firstRow = 0) {
3142
5051
  const gz = gzipDeterministic(raw, { name: chunkName(ordinal) });
3143
5052
  return {
3144
5053
  ordinal,
3145
- digest: (0, import_node_crypto6.createHash)("sha256").update(gz).digest("hex"),
5054
+ digest: (0, import_node_crypto9.createHash)("sha256").update(gz).digest("hex"),
3146
5055
  bytes: gz.length,
3147
5056
  rows,
3148
5057
  entity,
3149
5058
  rawBytes: raw.length,
3150
- contentSha256: (0, import_node_crypto6.createHash)("sha256").update(raw).digest("hex"),
5059
+ contentSha256: (0, import_node_crypto9.createHash)("sha256").update(raw).digest("hex"),
3151
5060
  firstRow,
3152
5061
  gz
3153
5062
  };
@@ -3175,11 +5084,11 @@ function crc32(data) {
3175
5084
  for (let i = 0; i < data.length; i++) crc = table[(crc ^ data[i]) & 255] ^ crc >>> 8;
3176
5085
  return (crc ^ 4294967295) >>> 0;
3177
5086
  }
3178
- var import_node_crypto6, import_node_zlib2, DEFAULT_CHUNK_BYTES, GZIP_LEVEL, chunkName, table;
5087
+ var import_node_crypto9, import_node_zlib2, DEFAULT_CHUNK_BYTES, GZIP_LEVEL, chunkName, table;
3179
5088
  var init_chunker = __esm({
3180
5089
  "src/cli/platform/worldData/chunker.ts"() {
3181
5090
  "use strict";
3182
- import_node_crypto6 = require("crypto");
5091
+ import_node_crypto9 = require("crypto");
3183
5092
  import_node_zlib2 = require("zlib");
3184
5093
  init_json();
3185
5094
  DEFAULT_CHUNK_BYTES = 64 * 1024 * 1024;
@@ -3252,7 +5161,7 @@ function parseToolCallRecord(raw) {
3252
5161
  }
3253
5162
  function readToolCallRecords(paths) {
3254
5163
  const records = [];
3255
- for (const file of paths) records.push(...toolCallRecordsIn(fs8.readFileSync(file, "utf8"), file));
5164
+ for (const file of paths) records.push(...toolCallRecordsIn(fs10.readFileSync(file, "utf8"), file));
3256
5165
  return records;
3257
5166
  }
3258
5167
  function toolCallRecordsIn(text2, where) {
@@ -3288,7 +5197,7 @@ async function emit(sink, record) {
3288
5197
  return;
3289
5198
  }
3290
5199
  if (typeof sink === "string") {
3291
- fs8.appendFileSync(sink, JSON.stringify(record) + "\n");
5200
+ fs10.appendFileSync(sink, JSON.stringify(record) + "\n");
3292
5201
  return;
3293
5202
  }
3294
5203
  if (typeof sink === "function") {
@@ -3319,14 +5228,6 @@ function captureToolCalls(tools, sink, opts = {}) {
3319
5228
  }
3320
5229
  return wrapped;
3321
5230
  }
3322
- function jsonish(value) {
3323
- if (typeof value !== "string") return value;
3324
- try {
3325
- return JSON.parse(value);
3326
- } catch {
3327
- return value;
3328
- }
3329
- }
3330
5231
  function toolCallsFromObservations(observations, opts = {}) {
3331
5232
  const known = opts.tools ? new Set(opts.tools) : null;
3332
5233
  const sinceMs = opts.since ? Date.parse(opts.since) : NaN;
@@ -3353,10 +5254,9 @@ function toolCallsFromObservations(observations, opts = {}) {
3353
5254
  out.unknownTools[tool] = (out.unknownTools[tool] ?? 0) + 1;
3354
5255
  continue;
3355
5256
  }
3356
- const input = jsonish(observation.input);
3357
- const record = { tool, args: isObject2(input) ? input : {} };
5257
+ const record = { tool, args: isObject2(observation.input) ? observation.input : {} };
3358
5258
  if (observation.level === "ERROR") record.error = observation.statusMessage || "ERROR";
3359
- else record.result = jsonish(observation.output);
5259
+ else record.result = observation.output;
3360
5260
  if (at !== void 0) record.at = at;
3361
5261
  if (opts.session) record.session = opts.session;
3362
5262
  record.source = `trace:${observation.traceId ?? "?"}/${observation.id ?? "?"}`;
@@ -3377,7 +5277,7 @@ async function ingest(world, records, options = {}) {
3377
5277
  const mode = options.mode ?? "append";
3378
5278
  const dryRun = Boolean(options.dryRun);
3379
5279
  const creds = credentialsOf(options);
3380
- const local = fs8.existsSync(world) && fs8.statSync(world).isDirectory();
5280
+ const local = fs10.existsSync(world) && fs10.statSync(world).isDirectory();
3381
5281
  const map = options.map === void 0 ? void 0 : options.map;
3382
5282
  let rows = null;
3383
5283
  let stderr = "";
@@ -3393,9 +5293,9 @@ async function ingest(world, records, options = {}) {
3393
5293
  if (!creds) throw new Error("Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY (or pass publicKey/secretKey).");
3394
5294
  const { pull: pull2 } = await Promise.resolve().then(() => (init_hub(), hub_exports));
3395
5295
  const slug = world.split("@", 1)[0];
3396
- const scratch = fs8.mkdtempSync(path7.join(os3.tmpdir(), "gateway-ingest-"));
5296
+ const scratch = fs10.mkdtempSync(path9.join(os3.tmpdir(), "gateway-ingest-"));
3397
5297
  try {
3398
- const pulled = await pull2(world, path7.join(scratch, slug), options);
5298
+ const pulled = await pull2(world, path9.join(scratch, slug), options);
3399
5299
  let report;
3400
5300
  let projected;
3401
5301
  if (rows === null) {
@@ -3416,7 +5316,7 @@ async function ingest(world, records, options = {}) {
3416
5316
  if (status.entityCounts) report.entityCounts = status.entityCounts;
3417
5317
  return report;
3418
5318
  } finally {
3419
- fs8.rmSync(scratch, { recursive: true, force: true });
5319
+ fs10.rmSync(scratch, { recursive: true, force: true });
3420
5320
  }
3421
5321
  }
3422
5322
  async function ingestToolCalls(world, records, options = {}) {
@@ -3465,17 +5365,17 @@ async function sessionToolObservations(sessionId, options = {}) {
3465
5365
  `/api/public/sessions/${encodeURIComponent(sessionId)}?includeIO=true`
3466
5366
  );
3467
5367
  const out = [];
3468
- for (const trace of session.traces ?? [])
3469
- for (const observation of trace.observations ?? []) out.push({ traceId: trace.id ?? null, ...observation });
5368
+ for (const trace3 of session.traces ?? [])
5369
+ for (const observation of trace3.observations ?? []) out.push({ traceId: trace3.id ?? null, ...observation });
3470
5370
  return out;
3471
5371
  }
3472
- var fs8, os3, path7, isObject2, isoOf;
5372
+ var fs10, os3, path9, isObject2, isoOf;
3473
5373
  var init_ingest = __esm({
3474
5374
  "src/worlds/ingest.ts"() {
3475
5375
  "use strict";
3476
- fs8 = __toESM(require("fs"));
5376
+ fs10 = __toESM(require("fs"));
3477
5377
  os3 = __toESM(require("os"));
3478
- path7 = __toESM(require("path"));
5378
+ path9 = __toESM(require("path"));
3479
5379
  init_worlds();
3480
5380
  isObject2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3481
5381
  isoOf = (value) => value instanceof Date ? value.toISOString() : typeof value === "string" ? value : void 0;
@@ -3493,9 +5393,12 @@ __export(worlds_exports, {
3493
5393
  EVENT_BATCH_SIZE: () => EVENT_BATCH_SIZE,
3494
5394
  EVENT_FLUSH_INTERVAL_MS: () => EVENT_FLUSH_INTERVAL_MS,
3495
5395
  EVENT_MAX_RETRIES: () => EVENT_MAX_RETRIES,
5396
+ GatewayEvalsClient: () => GatewayEvalsClient,
3496
5397
  STRIP_PREFIX: () => STRIP_PREFIX,
3497
5398
  SURFACE_KINDS: () => SURFACE_KINDS,
3498
5399
  TRANSFORMS: () => TRANSFORMS,
5400
+ TaskRun: () => TaskRun,
5401
+ TaskSessions: () => TaskSessions,
3499
5402
  WHITESPACE: () => WHITESPACE,
3500
5403
  WorldBrowser: () => WorldBrowser,
3501
5404
  WorldSession: () => WorldSession,
@@ -3504,9 +5407,12 @@ __export(worlds_exports, {
3504
5407
  WorldSet: () => WorldSet,
3505
5408
  WorldSurfaceUnavailable: () => WorldSurfaceUnavailable,
3506
5409
  WorldTask: () => WorldTask,
5410
+ aggregateTaskGrade: () => aggregateTaskGrade,
3507
5411
  apiRequest: () => apiRequest,
3508
5412
  applyTransforms: () => applyTransforms,
5413
+ attachManifest: () => attachManifest,
3509
5414
  attachSession: () => attachSession,
5415
+ attachTask: () => attachTask,
3510
5416
  buildSourceTarball: () => buildSourceTarball,
3511
5417
  captureToolCalls: () => captureToolCalls,
3512
5418
  collectArchiveRelPaths: () => collectArchiveRelPaths,
@@ -3523,17 +5429,20 @@ __export(worlds_exports, {
3523
5429
  hashForm: () => hashForm,
3524
5430
  ingest: () => ingest,
3525
5431
  ingestToolCalls: () => ingestToolCalls,
3526
- isIncludedInContentHash: () => isIncludedInContentHash,
3527
5432
  isTaskIdRef: () => isTaskIdRef,
5433
+ isTaskManifest: () => isTaskManifest,
3528
5434
  isTaskSpec: () => isTaskSpec,
3529
5435
  listEnvSecretKeys: () => listEnvSecretKeys,
3530
5436
  listRunConfigs: () => listRunConfigs,
5437
+ listTaskSessions: () => listTaskSessions,
3531
5438
  listTasks: () => listTasks,
3532
5439
  localTreeState: () => localTreeState,
3533
5440
  migrateProjectWorlds: () => migrateProjectWorlds,
3534
5441
  migrateWorld: () => migrateWorld,
5442
+ modelToolName: () => modelToolName,
3535
5443
  openBrowser: () => openBrowser,
3536
5444
  openSession: () => openSession,
5445
+ openTask: () => openTask,
3537
5446
  openWorld: () => openWorld,
3538
5447
  parseToolCallRecord: () => parseToolCallRecord,
3539
5448
  parseTransform: () => parseTransform,
@@ -3542,6 +5451,7 @@ __export(worlds_exports, {
3542
5451
  propose: () => propose,
3543
5452
  pull: () => pull,
3544
5453
  push: () => push,
5454
+ pushSlug: () => pushSlug,
3545
5455
  pyText: () => pyText,
3546
5456
  queryRows: () => queryRows,
3547
5457
  queryRowsSearch: () => queryRowsSearch,
@@ -3552,6 +5462,7 @@ __export(worlds_exports, {
3552
5462
  resolveBrowserMode: () => resolveBrowserMode,
3553
5463
  roundForm: () => roundForm,
3554
5464
  runSessions: () => runSessions,
5465
+ runTask: () => runTask,
3555
5466
  schemaFromSignature: () => schemaFromSignature,
3556
5467
  sessionToolObservations: () => sessionToolObservations,
3557
5468
  setEnvSecret: () => setEnvSecret,
@@ -3584,9 +5495,9 @@ function resolveEnv(options) {
3584
5495
  }
3585
5496
  return { host: host.replace(/\/+$/, ""), publicKey, secretKey };
3586
5497
  }
3587
- async function apiRequest(options, method, path8, body) {
5498
+ async function apiRequest(options, method, path10, body) {
3588
5499
  const { host, publicKey, secretKey } = resolveEnv(options);
3589
- const res = await fetch(`${host}${path8}`, {
5500
+ const res = await fetch(`${host}${path10}`, {
3590
5501
  method,
3591
5502
  headers: {
3592
5503
  "content-type": "application/json",
@@ -3595,7 +5506,7 @@ async function apiRequest(options, method, path8, body) {
3595
5506
  ...body === void 0 ? {} : { body: JSON.stringify(body) }
3596
5507
  });
3597
5508
  const text2 = await res.text();
3598
- if (!res.ok) throw new ApiError2(res.status, method, path8, text2.slice(0, 400));
5509
+ if (!res.ok) throw new ApiError2(res.status, method, path10, text2.slice(0, 400));
3599
5510
  return JSON.parse(text2);
3600
5511
  }
3601
5512
  async function setEnvSecret(slug, key, value, options = {}) {
@@ -3752,6 +5663,9 @@ var init_worlds = __esm({
3752
5663
  "src/worlds/index.ts"() {
3753
5664
  init_session();
3754
5665
  init_tasks();
5666
+ init_taskSessions();
5667
+ init_taskRun();
5668
+ init_evals();
3755
5669
  init_browser();
3756
5670
  init_hub();
3757
5671
  init_validate();
@@ -3762,8 +5676,8 @@ var init_worlds = __esm({
3762
5676
  init_migrate();
3763
5677
  init_ingest();
3764
5678
  ApiError2 = class extends Error {
3765
- constructor(status, method, path8, body) {
3766
- super(`${method} ${path8} -> ${status}: ${body}`);
5679
+ constructor(status, method, path10, body) {
5680
+ super(`${method} ${path10} -> ${status}: ${body}`);
3767
5681
  this.status = status;
3768
5682
  this.name = "ApiError";
3769
5683
  }
@@ -3843,9 +5757,12 @@ init_worlds();
3843
5757
  EVENT_BATCH_SIZE,
3844
5758
  EVENT_FLUSH_INTERVAL_MS,
3845
5759
  EVENT_MAX_RETRIES,
5760
+ GatewayEvalsClient,
3846
5761
  STRIP_PREFIX,
3847
5762
  SURFACE_KINDS,
3848
5763
  TRANSFORMS,
5764
+ TaskRun,
5765
+ TaskSessions,
3849
5766
  WHITESPACE,
3850
5767
  WorldBrowser,
3851
5768
  WorldSession,
@@ -3854,9 +5771,12 @@ init_worlds();
3854
5771
  WorldSet,
3855
5772
  WorldSurfaceUnavailable,
3856
5773
  WorldTask,
5774
+ aggregateTaskGrade,
3857
5775
  apiRequest,
3858
5776
  applyTransforms,
5777
+ attachManifest,
3859
5778
  attachSession,
5779
+ attachTask,
3860
5780
  buildSourceTarball,
3861
5781
  captureToolCalls,
3862
5782
  collectArchiveRelPaths,
@@ -3873,17 +5793,20 @@ init_worlds();
3873
5793
  hashForm,
3874
5794
  ingest,
3875
5795
  ingestToolCalls,
3876
- isIncludedInContentHash,
3877
5796
  isTaskIdRef,
5797
+ isTaskManifest,
3878
5798
  isTaskSpec,
3879
5799
  listEnvSecretKeys,
3880
5800
  listRunConfigs,
5801
+ listTaskSessions,
3881
5802
  listTasks,
3882
5803
  localTreeState,
3883
5804
  migrateProjectWorlds,
3884
5805
  migrateWorld,
5806
+ modelToolName,
3885
5807
  openBrowser,
3886
5808
  openSession,
5809
+ openTask,
3887
5810
  openWorld,
3888
5811
  parseToolCallRecord,
3889
5812
  parseTransform,
@@ -3892,6 +5815,7 @@ init_worlds();
3892
5815
  propose,
3893
5816
  pull,
3894
5817
  push,
5818
+ pushSlug,
3895
5819
  pyText,
3896
5820
  queryRows,
3897
5821
  queryRowsSearch,
@@ -3902,6 +5826,7 @@ init_worlds();
3902
5826
  resolveBrowserMode,
3903
5827
  roundForm,
3904
5828
  runSessions,
5829
+ runTask,
3905
5830
  schemaFromSignature,
3906
5831
  sessionToolObservations,
3907
5832
  setEnvSecret,