@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.mjs CHANGED
@@ -2236,7 +2236,7 @@ async function push(dir, opts = {}) {
2236
2236
  const pyproject = readPyproject(dir);
2237
2237
  const contractVersion = pyproject.version ? void 0 : readWorldContractVersion(dir).version;
2238
2238
  if (contractVersion) pyproject.version = contractVersion;
2239
- const slug = opts.slug ?? pyproject.name ?? path4.basename(path4.resolve(dir));
2239
+ const slug = opts.slug ?? localMeta.slug ?? pyproject.name ?? path4.basename(path4.resolve(dir));
2240
2240
  const resolve22 = await apiRequest(
2241
2241
  options,
2242
2242
  "POST",
@@ -4014,6 +4014,7 @@ var init_ingest = __esm({
4014
4014
  // src/worlds/index.ts
4015
4015
  var worlds_exports = {};
4016
4016
  __export(worlds_exports, {
4017
+ ApiError: () => ApiError2,
4017
4018
  BrowserActionRecorder: () => BrowserActionRecorder,
4018
4019
  COMPUTER_USE_SPECS: () => COMPUTER_USE_SPECS,
4019
4020
  DEFAULT_BRANCH: () => DEFAULT_BRANCH,
@@ -4122,11 +4123,7 @@ async function apiRequest(options, method, path30, body) {
4122
4123
  ...body === void 0 ? {} : { body: JSON.stringify(body) }
4123
4124
  });
4124
4125
  const text2 = await res.text();
4125
- if (!res.ok) {
4126
- throw new Error(
4127
- `${method} ${path30} -> ${res.status}: ${text2.slice(0, 400)}`
4128
- );
4129
- }
4126
+ if (!res.ok) throw new ApiError2(res.status, method, path30, text2.slice(0, 400));
4130
4127
  return JSON.parse(text2);
4131
4128
  }
4132
4129
  async function setEnvSecret(slug, key, value, options = {}) {
@@ -4278,7 +4275,7 @@ async function openWorld(slugRef, options = {}) {
4278
4275
  }
4279
4276
  return world;
4280
4277
  }
4281
- var WorldTask, WorldSet;
4278
+ var ApiError2, WorldTask, WorldSet;
4282
4279
  var init_worlds = __esm({
4283
4280
  "src/worlds/index.ts"() {
4284
4281
  "use strict";
@@ -4293,6 +4290,13 @@ var init_worlds = __esm({
4293
4290
  init_query();
4294
4291
  init_migrate();
4295
4292
  init_ingest();
4293
+ ApiError2 = class extends Error {
4294
+ constructor(status, method, path30, body) {
4295
+ super(`${method} ${path30} -> ${status}: ${body}`);
4296
+ this.status = status;
4297
+ this.name = "ApiError";
4298
+ }
4299
+ };
4296
4300
  WorldTask = class {
4297
4301
  constructor(world, name, variant) {
4298
4302
  this.world = world;
@@ -11390,6 +11394,14 @@ init_router();
11390
11394
  init_worlds();
11391
11395
  init_shared();
11392
11396
  import * as fs30 from "fs";
11397
+ async function findTaskByName(name, options) {
11398
+ for (let page = 1; ; page++) {
11399
+ const batch = await listTasks({ page, limit: 100 }, options);
11400
+ const hit = batch.tasks.find((task) => task.name === name);
11401
+ if (hit) return hit;
11402
+ if (page >= batch.meta.totalPages) return null;
11403
+ }
11404
+ }
11393
11405
  var WORLD_FLAG = {
11394
11406
  name: "world",
11395
11407
  short: "w",
@@ -11461,20 +11473,42 @@ function registerTaskCommands(root) {
11461
11473
  },
11462
11474
  WORLD_FLAG,
11463
11475
  MESSAGE_FLAG2,
11476
+ {
11477
+ name: "replace",
11478
+ help: "A task by this name already exists: store the spec as its next version instead of refusing (409).",
11479
+ boolean: true
11480
+ },
11464
11481
  HOST_FLAG
11465
11482
  ],
11466
11483
  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.",
11467
11484
  run: async (args, ctx) => {
11468
11485
  const spec = readTaskSpec(args.positionals[0], "spec");
11469
- const created = await createTask(
11470
- {
11471
- spec,
11472
- name: arg.str(args, "name"),
11473
- world: arg.str(args, "world"),
11474
- message: arg.str(args, "message")
11475
- },
11476
- worldsOptions(credentials(args))
11477
- );
11486
+ const options = worldsOptions(credentials(args));
11487
+ const input = {
11488
+ spec,
11489
+ name: arg.str(args, "name"),
11490
+ world: arg.str(args, "world"),
11491
+ message: arg.str(args, "message")
11492
+ };
11493
+ let created;
11494
+ try {
11495
+ created = await createTask(input, options);
11496
+ } catch (error) {
11497
+ if (!arg.bool(args, "replace") || !(error instanceof ApiError2) || error.status !== 409) throw error;
11498
+ const name = input.name ?? spec.name;
11499
+ const existing = name ? await findTaskByName(name, options) : null;
11500
+ if (!existing) throw error;
11501
+ created = await updateTask(
11502
+ existing.id,
11503
+ {
11504
+ spec,
11505
+ message: input.message,
11506
+ ...input.world === void 0 ? {} : { world: input.world }
11507
+ },
11508
+ options
11509
+ );
11510
+ ctx.stderr(`task '${name}' exists (${existing.id}); stored the spec as version ${String(created.version)}`);
11511
+ }
11478
11512
  printDeprecations(ctx, created.deprecations);
11479
11513
  printJson(ctx, created);
11480
11514
  }
@@ -12809,10 +12843,10 @@ init_config();
12809
12843
  init_worlds();
12810
12844
  init_session();
12811
12845
  init_hub();
12812
- init_validate();
12813
12846
  import * as fs34 from "fs";
12814
12847
  import * as path25 from "path";
12815
12848
  import { pathToFileURL } from "url";
12849
+ init_validate();
12816
12850
  var HOST_FLAG4 = {
12817
12851
  name: "host",
12818
12852
  help: "Platform host (default: GATEWAY_HOST or the saved login).",
@@ -13038,7 +13072,19 @@ function registerRunCommands2(worlds) {
13038
13072
  }
13039
13073
  return report.ok ? 0 : 1;
13040
13074
  }
13041
- const pushed = await push(dir, { branch, force: true, message, options });
13075
+ const packaged = isConnectorWorld(dir) ? await packageApiBundle(dir, args, ctx) : null;
13076
+ const pushed = await push(packaged ?? dir, {
13077
+ ...packaged ? { slug: meta.slug ?? path25.basename(dir) } : {},
13078
+ branch,
13079
+ force: true,
13080
+ message,
13081
+ options
13082
+ });
13083
+ if (packaged) {
13084
+ const carried = readLocalMeta(packaged);
13085
+ if (carried) writeLocalMeta(dir, carried);
13086
+ fs34.rmSync(packaged, { recursive: true, force: true });
13087
+ }
13042
13088
  ctx.stderr(`pushed ${pushed.slug}@${branch} (${pushed.contentHash.slice(0, 8)})`);
13043
13089
  const agent = await loadAgent(agentFile);
13044
13090
  const world = await openWorld(`${pushed.slug}@${branch}`, options);
@@ -13388,6 +13434,8 @@ function registerTestCommand(worlds) {
13388
13434
 
13389
13435
  // src/cli/runtime/call.ts
13390
13436
  init_router();
13437
+ init_session();
13438
+ init_shared();
13391
13439
  init_local();
13392
13440
  init_client();
13393
13441
  import * as fs37 from "fs";
@@ -13436,6 +13484,43 @@ async function sessionVerb(base, verb, body) {
13436
13484
  }
13437
13485
  return { status: response.status, body: parsed };
13438
13486
  }
13487
+ function isRouteAnswer(value) {
13488
+ return typeof value === "object" && value !== null && typeof value.status === "number" && "body" in value;
13489
+ }
13490
+ async function callHosted(sessionId, tool, args, wants, options) {
13491
+ const live = await attachSession(sessionId, options);
13492
+ const report = {
13493
+ status: "ok",
13494
+ tools: (await live.toolkit()).specs.map((spec) => spec.name),
13495
+ result: { status: 0, body: null }
13496
+ };
13497
+ if (wants.seed) {
13498
+ const { rows, mode } = wants.seed;
13499
+ if (!rows || typeof rows !== "object" || Array.isArray(rows))
13500
+ throw new CliError("--seed on a hosted session is the host's shape: {rows: {entity: [row, ...]}, mode?: append|replace}");
13501
+ if (mode !== void 0 && mode !== "append" && mode !== "replace")
13502
+ throw new CliError("--seed mode must be append or replace");
13503
+ const seeded = await live.seed(rows, mode ? { mode } : {});
13504
+ report.seed = seeded;
13505
+ }
13506
+ try {
13507
+ const answer = await live.call(tool, args);
13508
+ report.result = isRouteAnswer(answer) ? answer : { status: 200, body: answer };
13509
+ } catch (error) {
13510
+ if (!(error instanceof WorldSessionCallError)) throw error;
13511
+ report.result = { status: 500, body: { error: error.message } };
13512
+ }
13513
+ if (wants.state) report.state = await live.state();
13514
+ if (wants.grade) report.grade = await live.grade();
13515
+ if (wants.close) {
13516
+ await live.close();
13517
+ report.closed = true;
13518
+ }
13519
+ return settleStatus(report);
13520
+ }
13521
+ function looksLikeSessionId(target) {
13522
+ return !target.includes("/") && !target.startsWith(".") && !fs37.existsSync(target);
13523
+ }
13439
13524
  async function callServed(base, tool, args, wants) {
13440
13525
  const url = base.replace(/\/+$/, "");
13441
13526
  const tools = await sessionVerb(url, "tools");
@@ -13466,11 +13551,11 @@ async function callServed(base, tool, args, wants) {
13466
13551
  function registerCallCommand(worlds) {
13467
13552
  worlds.command({
13468
13553
  name: "call",
13469
- help: "Call one tool on a world directory here, or on a served session by URL; a dependency's tool as alias.tool.",
13554
+ 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.",
13470
13555
  positionals: [
13471
13556
  {
13472
13557
  name: "path",
13473
- help: "World directory (a schema world with gateway-env.toml), or the url of a running `worlds serve` session."
13558
+ 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`)."
13474
13559
  },
13475
13560
  { name: "tool", help: "Tool name; a dependency's tool as <alias>.<tool>." }
13476
13561
  ],
@@ -13484,9 +13569,10 @@ function registerCallCommand(worlds) {
13484
13569
  },
13485
13570
  { name: "state", help: "Print the world's state after the call.", boolean: true },
13486
13571
  { name: "grade", help: "Run the verifiers after the call and print the scores.", boolean: true },
13487
- { name: "close", help: "On a served session (url): end it after the call; `worlds serve` returns.", boolean: true }
13572
+ { name: "close", help: "On a served session (url) or a hosted one (id): end it after the call.", boolean: true },
13573
+ HOST_FLAG
13488
13574
  ],
13489
- 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',
13575
+ 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',
13490
13576
  run: async (args, ctx) => {
13491
13577
  const [target, tool] = args.positionals;
13492
13578
  if (SERVED_URL.test(target)) {
@@ -13504,7 +13590,28 @@ function registerCallCommand(worlds) {
13504
13590
  ctx.stdout(JSON.stringify(report2, null, 2));
13505
13591
  return report2.result.status >= 200 && report2.result.status < 300 ? 0 : 1;
13506
13592
  }
13507
- if (arg.bool(args, "close")) throw new CliError("--close ends a served session; pass its url instead of a directory");
13593
+ if (looksLikeSessionId(target)) {
13594
+ for (const flag of ["task", "scenario"])
13595
+ if (arg.str(args, flag) !== void 0)
13596
+ throw new CliError(`--${flag} belongs to \`gateway worlds session open\`; session ${target} already has its own`);
13597
+ const stdin2 = args.flags.args === "-" || args.flags.seed === "-" ? await ctx.stdin() : "";
13598
+ const seedRaw2 = arg.str(args, "seed");
13599
+ const report2 = await callHosted(
13600
+ target,
13601
+ tool,
13602
+ parseArgs2(arg.str(args, "args"), stdin2),
13603
+ {
13604
+ ...seedRaw2 === void 0 ? {} : { seed: parseArgs2(seedRaw2, stdin2) },
13605
+ state: arg.bool(args, "state"),
13606
+ grade: arg.bool(args, "grade"),
13607
+ close: arg.bool(args, "close")
13608
+ },
13609
+ worldsOptions(credentials(args))
13610
+ );
13611
+ ctx.stdout(JSON.stringify(report2, null, 2));
13612
+ return report2.result.status >= 200 && report2.result.status < 300 ? 0 : 1;
13613
+ }
13614
+ if (arg.bool(args, "close")) throw new CliError("--close ends a served or hosted session; pass its url or id instead of a directory");
13508
13615
  const dir = path28.resolve(target);
13509
13616
  if (!fs37.existsSync(dir) || !fs37.statSync(dir).isDirectory()) throw new CliError(`Not a directory: ${dir}`, 1);
13510
13617
  const local = localRuntime();