@withgateway/sdk 0.2.2 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -2245,7 +2245,7 @@ async function push(dir, opts = {}) {
2245
2245
  const pyproject = readPyproject(dir);
2246
2246
  const contractVersion = pyproject.version ? void 0 : readWorldContractVersion(dir).version;
2247
2247
  if (contractVersion) pyproject.version = contractVersion;
2248
- const slug = opts.slug ?? pyproject.name ?? path4.basename(path4.resolve(dir));
2248
+ const slug = opts.slug ?? localMeta.slug ?? pyproject.name ?? path4.basename(path4.resolve(dir));
2249
2249
  const resolve22 = await apiRequest(
2250
2250
  options,
2251
2251
  "POST",
@@ -4028,6 +4028,7 @@ var init_ingest = __esm({
4028
4028
  // src/worlds/index.ts
4029
4029
  var worlds_exports = {};
4030
4030
  __export(worlds_exports, {
4031
+ ApiError: () => ApiError2,
4031
4032
  BrowserActionRecorder: () => BrowserActionRecorder,
4032
4033
  COMPUTER_USE_SPECS: () => COMPUTER_USE_SPECS,
4033
4034
  DEFAULT_BRANCH: () => DEFAULT_BRANCH,
@@ -4136,11 +4137,7 @@ async function apiRequest(options, method, path30, body) {
4136
4137
  ...body === void 0 ? {} : { body: JSON.stringify(body) }
4137
4138
  });
4138
4139
  const text2 = await res.text();
4139
- if (!res.ok) {
4140
- throw new Error(
4141
- `${method} ${path30} -> ${res.status}: ${text2.slice(0, 400)}`
4142
- );
4143
- }
4140
+ if (!res.ok) throw new ApiError2(res.status, method, path30, text2.slice(0, 400));
4144
4141
  return JSON.parse(text2);
4145
4142
  }
4146
4143
  async function setEnvSecret(slug, key, value, options = {}) {
@@ -4292,7 +4289,7 @@ async function openWorld(slugRef, options = {}) {
4292
4289
  }
4293
4290
  return world;
4294
4291
  }
4295
- var WorldTask, WorldSet;
4292
+ var ApiError2, WorldTask, WorldSet;
4296
4293
  var init_worlds = __esm({
4297
4294
  "src/worlds/index.ts"() {
4298
4295
  "use strict";
@@ -4307,6 +4304,13 @@ var init_worlds = __esm({
4307
4304
  init_query();
4308
4305
  init_migrate();
4309
4306
  init_ingest();
4307
+ ApiError2 = class extends Error {
4308
+ constructor(status, method, path30, body) {
4309
+ super(`${method} ${path30} -> ${status}: ${body}`);
4310
+ this.status = status;
4311
+ this.name = "ApiError";
4312
+ }
4313
+ };
4310
4314
  WorldTask = class {
4311
4315
  constructor(world, name, variant) {
4312
4316
  this.world = world;
@@ -11404,6 +11408,14 @@ init_config();
11404
11408
  init_router();
11405
11409
  init_worlds();
11406
11410
  init_shared();
11411
+ async function findTaskByName(name, options) {
11412
+ for (let page = 1; ; page++) {
11413
+ const batch = await listTasks({ page, limit: 100 }, options);
11414
+ const hit = batch.tasks.find((task) => task.name === name);
11415
+ if (hit) return hit;
11416
+ if (page >= batch.meta.totalPages) return null;
11417
+ }
11418
+ }
11407
11419
  var WORLD_FLAG = {
11408
11420
  name: "world",
11409
11421
  short: "w",
@@ -11475,20 +11487,42 @@ function registerTaskCommands(root) {
11475
11487
  },
11476
11488
  WORLD_FLAG,
11477
11489
  MESSAGE_FLAG2,
11490
+ {
11491
+ name: "replace",
11492
+ help: "A task by this name already exists: store the spec as its next version instead of refusing (409).",
11493
+ boolean: true
11494
+ },
11478
11495
  HOST_FLAG
11479
11496
  ],
11480
11497
  notes: "The same spec `worlds session open --task-file` takes, kept as a project resource so sessions open on it by id\n(`session open --task-id <id>`) and grades attribute to the task and its version. --world pins it to one world\nand checks the seed and grader entities against that world's contract.",
11481
11498
  run: async (args, ctx) => {
11482
11499
  const spec = readTaskSpec(args.positionals[0], "spec");
11483
- const created = await createTask(
11484
- {
11485
- spec,
11486
- name: arg.str(args, "name"),
11487
- world: arg.str(args, "world"),
11488
- message: arg.str(args, "message")
11489
- },
11490
- worldsOptions(credentials(args))
11491
- );
11500
+ const options = worldsOptions(credentials(args));
11501
+ const input = {
11502
+ spec,
11503
+ name: arg.str(args, "name"),
11504
+ world: arg.str(args, "world"),
11505
+ message: arg.str(args, "message")
11506
+ };
11507
+ let created;
11508
+ try {
11509
+ created = await createTask(input, options);
11510
+ } catch (error) {
11511
+ if (!arg.bool(args, "replace") || !(error instanceof ApiError2) || error.status !== 409) throw error;
11512
+ const name = input.name ?? spec.name;
11513
+ const existing = name ? await findTaskByName(name, options) : null;
11514
+ if (!existing) throw error;
11515
+ created = await updateTask(
11516
+ existing.id,
11517
+ {
11518
+ spec,
11519
+ message: input.message,
11520
+ ...input.world === void 0 ? {} : { world: input.world }
11521
+ },
11522
+ options
11523
+ );
11524
+ ctx.stderr(`task '${name}' exists (${existing.id}); stored the spec as version ${String(created.version)}`);
11525
+ }
11492
11526
  printDeprecations(ctx, created.deprecations);
11493
11527
  printJson(ctx, created);
11494
11528
  }
@@ -13052,7 +13086,19 @@ function registerRunCommands2(worlds) {
13052
13086
  }
13053
13087
  return report.ok ? 0 : 1;
13054
13088
  }
13055
- const pushed = await push(dir, { branch, force: true, message, options });
13089
+ const packaged = isConnectorWorld(dir) ? await packageApiBundle(dir, args, ctx) : null;
13090
+ const pushed = await push(packaged ?? dir, {
13091
+ ...packaged ? { slug: meta.slug ?? path25.basename(dir) } : {},
13092
+ branch,
13093
+ force: true,
13094
+ message,
13095
+ options
13096
+ });
13097
+ if (packaged) {
13098
+ const carried = readLocalMeta(packaged);
13099
+ if (carried) writeLocalMeta(dir, carried);
13100
+ fs34.rmSync(packaged, { recursive: true, force: true });
13101
+ }
13056
13102
  ctx.stderr(`pushed ${pushed.slug}@${branch} (${pushed.contentHash.slice(0, 8)})`);
13057
13103
  const agent = await loadAgent(agentFile);
13058
13104
  const world = await openWorld(`${pushed.slug}@${branch}`, options);
@@ -13404,6 +13450,8 @@ function registerTestCommand(worlds) {
13404
13450
  var fs37 = __toESM(require("fs"));
13405
13451
  var path28 = __toESM(require("path"));
13406
13452
  init_router();
13453
+ init_session();
13454
+ init_shared();
13407
13455
  init_local();
13408
13456
  init_client();
13409
13457
  function parseArgs2(raw, stdin) {
@@ -13450,6 +13498,43 @@ async function sessionVerb(base, verb, body) {
13450
13498
  }
13451
13499
  return { status: response.status, body: parsed };
13452
13500
  }
13501
+ function isRouteAnswer(value) {
13502
+ return typeof value === "object" && value !== null && typeof value.status === "number" && "body" in value;
13503
+ }
13504
+ async function callHosted(sessionId, tool, args, wants, options) {
13505
+ const live = await attachSession(sessionId, options);
13506
+ const report = {
13507
+ status: "ok",
13508
+ tools: (await live.toolkit()).specs.map((spec) => spec.name),
13509
+ result: { status: 0, body: null }
13510
+ };
13511
+ if (wants.seed) {
13512
+ const { rows, mode } = wants.seed;
13513
+ if (!rows || typeof rows !== "object" || Array.isArray(rows))
13514
+ throw new CliError("--seed on a hosted session is the host's shape: {rows: {entity: [row, ...]}, mode?: append|replace}");
13515
+ if (mode !== void 0 && mode !== "append" && mode !== "replace")
13516
+ throw new CliError("--seed mode must be append or replace");
13517
+ const seeded = await live.seed(rows, mode ? { mode } : {});
13518
+ report.seed = seeded;
13519
+ }
13520
+ try {
13521
+ const answer = await live.call(tool, args);
13522
+ report.result = isRouteAnswer(answer) ? answer : { status: 200, body: answer };
13523
+ } catch (error) {
13524
+ if (!(error instanceof WorldSessionCallError)) throw error;
13525
+ report.result = { status: 500, body: { error: error.message } };
13526
+ }
13527
+ if (wants.state) report.state = await live.state();
13528
+ if (wants.grade) report.grade = await live.grade();
13529
+ if (wants.close) {
13530
+ await live.close();
13531
+ report.closed = true;
13532
+ }
13533
+ return settleStatus(report);
13534
+ }
13535
+ function looksLikeSessionId(target) {
13536
+ return !target.includes("/") && !target.startsWith(".") && !fs37.existsSync(target);
13537
+ }
13453
13538
  async function callServed(base, tool, args, wants) {
13454
13539
  const url = base.replace(/\/+$/, "");
13455
13540
  const tools = await sessionVerb(url, "tools");
@@ -13480,11 +13565,11 @@ async function callServed(base, tool, args, wants) {
13480
13565
  function registerCallCommand(worlds) {
13481
13566
  worlds.command({
13482
13567
  name: "call",
13483
- help: "Call one tool on a world directory here, or on a served session by URL; a dependency's tool as alias.tool.",
13568
+ help: "Call one tool on a world directory here, on a served session by url, or on a hosted session by id; a dependency's tool as alias.tool.",
13484
13569
  positionals: [
13485
13570
  {
13486
13571
  name: "path",
13487
- help: "World directory (a schema world with gateway-env.toml), or the url of a running `worlds serve` session."
13572
+ help: "World directory (a schema world with gateway-env.toml), the url of a running `worlds serve` session, or the id of a hosted session (`worlds session open`)."
13488
13573
  },
13489
13574
  { name: "tool", help: "Tool name; a dependency's tool as <alias>.<tool>." }
13490
13575
  ],
@@ -13498,9 +13583,10 @@ function registerCallCommand(worlds) {
13498
13583
  },
13499
13584
  { name: "state", help: "Print the world's state after the call.", boolean: true },
13500
13585
  { name: "grade", help: "Run the verifiers after the call and print the scores.", boolean: true },
13501
- { name: "close", help: "On a served session (url): end it after the call; `worlds serve` returns.", boolean: true }
13586
+ { name: "close", help: "On a served session (url) or a hosted one (id): end it after the call.", boolean: true },
13587
+ HOST_FLAG
13502
13588
  ],
13503
- notes: 'The world is opened in place, so `[dependencies]` entries with a `path` open beside it and their tools\nanswer as alias.tool; a pin without a path is refused here (add path = "../<dir>"). The world\'s handlers\nrun on this machine through the bundled runtime (a python3 >= 3.11); the platform never runs them for you.\nExit 0 when the tool answered 2xx, 1 otherwise: a refused call (unknown tool, arguments off the schema, a\ntool outside --task\'s allow-list) prints the refusal; a 500 is the handler raising, its error in the body.\nWith a url (the `url` `gateway worlds serve <dir> --task <id>` prints) the call goes to THAT session over\nPOST /__session/call, so state carries from call to call, --state/--grade read it, and --close ends it;\n--task and --scenario belong to the serve. This is the outside-agent path: any HTTP client does the same.\nExamples:\n gateway worlds call ./whatsapp list_conversations\n gateway worlds call ./whatsapp send_message --args \'{"conversation_id": "c1", "body": "hi"}\' --state\n gateway worlds call ./whatsapp slack.post_message --args @msg.json --task escalate --grade\n gateway worlds call http://127.0.0.1:8080 send_message --args \'{"conversation_id": "c1", "body": "hi"}\'\n gateway worlds call http://127.0.0.1:8080 slack.post_message --args @msg.json --grade --close',
13589
+ notes: 'The world is opened in place, so `[dependencies]` entries with a `path` open beside it and their tools\nanswer as alias.tool; a pin without a path is refused here (add path = "../<dir>"). The world\'s handlers\nrun on this machine through the bundled runtime (a python3 >= 3.11); the platform never runs them for you.\nExit 0 when the tool answered 2xx, 1 otherwise: a refused call (unknown tool, arguments off the schema, a\ntool outside --task\'s allow-list) prints the refusal; a 500 is the handler raising, its error in the body.\nWith a url (the `url` `gateway worlds serve <dir> --task <id>` prints) the call goes to THAT session over\nPOST /__session/call, so state carries from call to call, --state/--grade read it, and --close ends it;\n--task and --scenario belong to the serve. This is the outside-agent path: any HTTP client does the same.\nWith a session id (the `sessionId` `gateway worlds session open` prints) the call goes through the platform to\nthat hosted session: the World Host\'s api url takes the session\'s own bearer and serves no /__session verbs, so\nthis is the way to act on a hosted session from the CLI; --seed/--state/--grade/--close work the same.\nExamples:\n gateway worlds call ./whatsapp list_conversations\n gateway worlds call ./whatsapp send_message --args \'{"conversation_id": "c1", "body": "hi"}\' --state\n gateway worlds call ./whatsapp slack.post_message --args @msg.json --task escalate --grade\n gateway worlds call http://127.0.0.1:8080 send_message --args \'{"conversation_id": "c1", "body": "hi"}\'\n gateway worlds call http://127.0.0.1:8080 slack.post_message --args @msg.json --grade --close',
13504
13590
  run: async (args, ctx) => {
13505
13591
  const [target, tool] = args.positionals;
13506
13592
  if (SERVED_URL.test(target)) {
@@ -13518,7 +13604,28 @@ function registerCallCommand(worlds) {
13518
13604
  ctx.stdout(JSON.stringify(report2, null, 2));
13519
13605
  return report2.result.status >= 200 && report2.result.status < 300 ? 0 : 1;
13520
13606
  }
13521
- if (arg.bool(args, "close")) throw new CliError("--close ends a served session; pass its url instead of a directory");
13607
+ if (looksLikeSessionId(target)) {
13608
+ for (const flag of ["task", "scenario"])
13609
+ if (arg.str(args, flag) !== void 0)
13610
+ throw new CliError(`--${flag} belongs to \`gateway worlds session open\`; session ${target} already has its own`);
13611
+ const stdin2 = args.flags.args === "-" || args.flags.seed === "-" ? await ctx.stdin() : "";
13612
+ const seedRaw2 = arg.str(args, "seed");
13613
+ const report2 = await callHosted(
13614
+ target,
13615
+ tool,
13616
+ parseArgs2(arg.str(args, "args"), stdin2),
13617
+ {
13618
+ ...seedRaw2 === void 0 ? {} : { seed: parseArgs2(seedRaw2, stdin2) },
13619
+ state: arg.bool(args, "state"),
13620
+ grade: arg.bool(args, "grade"),
13621
+ close: arg.bool(args, "close")
13622
+ },
13623
+ worldsOptions(credentials(args))
13624
+ );
13625
+ ctx.stdout(JSON.stringify(report2, null, 2));
13626
+ return report2.result.status >= 200 && report2.result.status < 300 ? 0 : 1;
13627
+ }
13628
+ if (arg.bool(args, "close")) throw new CliError("--close ends a served or hosted session; pass its url or id instead of a directory");
13522
13629
  const dir = path28.resolve(target);
13523
13630
  if (!fs37.existsSync(dir) || !fs37.statSync(dir).isDirectory()) throw new CliError(`Not a directory: ${dir}`, 1);
13524
13631
  const local = localRuntime();