sim 2.2.9-preview.214.1 → 2.2.9

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/runtime.js CHANGED
@@ -17379,16 +17379,106 @@ var V2_OPERATIONS = {
17379
17379
  }
17380
17380
  };
17381
17381
 
17382
+ // src/runtime/derive.ts
17383
+ var ACTION_SEGMENTS = new Set([
17384
+ "upsert",
17385
+ "query",
17386
+ "search",
17387
+ "export",
17388
+ "import",
17389
+ "deploy",
17390
+ "rollback"
17391
+ ]);
17392
+ function deriveCommandPath(operation) {
17393
+ const spec = V2_OPERATIONS[operation];
17394
+ const segments = spec.path.replace("/api/v2/", "").split("/");
17395
+ const resource = segments[0];
17396
+ const nouns = segments.slice(1).filter((segment) => !segment.startsWith("["));
17397
+ const last = nouns[nouns.length - 1];
17398
+ if (last && ACTION_SEGMENTS.has(last))
17399
+ return [resource, last];
17400
+ const isItem = spec.path.endsWith("]");
17401
+ const verb = spec.method === "GET" ? isItem ? "get" : "list" : spec.method === "POST" ? "create" : spec.method === "DELETE" ? "delete" : "update";
17402
+ return last ? [resource, last, verb] : [resource, verb];
17403
+ }
17404
+ function kebab(value) {
17405
+ return value.replace(/[A-Z]/g, (character) => `-${character.toLowerCase()}`);
17406
+ }
17407
+ function camel(flag) {
17408
+ return flag.replace(/-([a-z])/g, (_match, character) => character.toUpperCase());
17409
+ }
17410
+ function commandPath(command) {
17411
+ const names = [];
17412
+ for (let current = command;current?.parent; current = current.parent) {
17413
+ names.unshift(current.name());
17414
+ }
17415
+ return names;
17416
+ }
17417
+
17382
17418
  // src/runtime/called-operations.ts
17383
17419
  var CALLED_OPERATIONS = new WeakMap;
17384
17420
  var RUNS_OPERATION = new WeakMap;
17385
- function runsOperation(command, operation) {
17386
- RUNS_OPERATION.set(command, operation);
17387
- return command;
17421
+ class OperationClient {
17422
+ client;
17423
+ operations;
17424
+ caller;
17425
+ constructor(client, operations, caller) {
17426
+ this.client = client;
17427
+ this.operations = operations;
17428
+ this.caller = caller;
17429
+ }
17430
+ requireWorkspace(explicit, options) {
17431
+ return this.client.requireWorkspace(explicit, options);
17432
+ }
17433
+ async request(operation, { params, ...options } = {}) {
17434
+ return this.client.request(this.route(operation, params), {
17435
+ ...options,
17436
+ method: V2_OPERATIONS[operation].method
17437
+ });
17438
+ }
17439
+ async requestRaw(operation, { params, ...options } = {}) {
17440
+ return this.client.requestRaw(this.route(operation, params), {
17441
+ ...options,
17442
+ method: V2_OPERATIONS[operation].method
17443
+ });
17444
+ }
17445
+ async requestAllPages(operation, { params, ...options }) {
17446
+ return requestAllPages(this.client, this.route(operation, params), {
17447
+ ...options,
17448
+ method: V2_OPERATIONS[operation].method
17449
+ });
17450
+ }
17451
+ over(client) {
17452
+ return new OperationClient(client, this.operations, this.caller);
17453
+ }
17454
+ route(operation, params) {
17455
+ if (!this.operations.has(operation)) {
17456
+ throw new Error(`"${this.caller}" calls ${operation}, which it does not declare`);
17457
+ }
17458
+ return resolvePath(V2_OPERATIONS[operation].path, params);
17459
+ }
17460
+ }
17461
+ function caller(command) {
17462
+ return `sim ${commandPath(command).join(" ")}`;
17463
+ }
17464
+ function connect(command, expects = []) {
17465
+ const operations = new Set(CALLED_OPERATIONS.get(command));
17466
+ const missing = operations.size === 0 ? "what it calls" : expects.find((o) => !operations.has(o));
17467
+ if (missing) {
17468
+ throw new Error(`"${caller(command)}" calls the API without declaring ${missing}`);
17469
+ }
17470
+ const { client, profile } = clientFrom(command);
17471
+ return { client: new OperationClient(client, operations, caller(command)), profile };
17388
17472
  }
17389
- function callsOperations(command, operations) {
17473
+ function callsOperations(command, operations, { runs } = {}) {
17390
17474
  CALLED_OPERATIONS.set(command, operations);
17391
- return command;
17475
+ if (runs)
17476
+ RUNS_OPERATION.set(command, runs);
17477
+ return () => connect(command, operations);
17478
+ }
17479
+ function apiCommand(parent, name, operations, declaration = {}) {
17480
+ const command = parent.command(name);
17481
+ return [command, callsOperations(command, operations, declaration)];
17392
17482
  }
17393
17483
 
17394
17484
  // src/commands/auth.ts
@@ -17488,17 +17578,16 @@ function requireStoredAuthentication(profile) {
17488
17578
  return authProfile;
17489
17579
  }
17490
17580
  async function getWorkspaceById(client, workspaceId) {
17491
- const operation = V2_OPERATIONS.getWorkspace;
17492
- const response = await client.request(resolvePath(operation.path, { workspaceId }), { method: operation.method });
17581
+ const response = await client.request("getWorkspace", {
17582
+ params: { workspaceId }
17583
+ });
17493
17584
  return response.data;
17494
17585
  }
17495
17586
  async function chooseWorkspace(client) {
17496
17587
  if (!process.stdin.isTTY) {
17497
17588
  throw new SimApiError("No workspace provided. Pass --workspace <id> when creating a profile non-interactively.", 0);
17498
17589
  }
17499
- const operation = V2_OPERATIONS.listWorkspaces;
17500
- const workspaces = await requestAllPages(client, operation.path, {
17501
- method: operation.method,
17590
+ const workspaces = await client.requestAllPages("listWorkspaces", {
17502
17591
  query: { sortBy: "name", sortOrder: "asc" },
17503
17592
  pageSize: 100,
17504
17593
  limit: MAX_INTERACTIVE_WORKSPACES + 1
@@ -17527,9 +17616,11 @@ Available workspaces:`);
17527
17616
  }
17528
17617
  }
17529
17618
  function addProfileCommand() {
17530
- return new Command("add").description("Add a workspace profile that shares the active stored login").argument("<name>", "Name for the new profile").option("-w, --workspace <id>", "Existing workspace to use; omit for an interactive picker").action(async (profileName, _options, command) => {
17619
+ const add = new Command("add");
17620
+ const connectAdd = callsOperations(add, ["getWorkspace", "listWorkspaces"]);
17621
+ return add.description("Add a workspace profile that shares the active stored login").argument("<name>", "Name for the new profile").option("-w, --workspace <id>", "Existing workspace to use; omit for an interactive picker").action(async (profileName, _options, command) => {
17531
17622
  validateNewProfileName(profileName);
17532
- const { client, profile } = clientFrom(command);
17623
+ const { client, profile } = connectAdd();
17533
17624
  const authProfile = requireStoredAuthentication(profile);
17534
17625
  const credential = readStoredCredential(authProfile);
17535
17626
  const workspaceId = globalsOf(command).workspace;
@@ -17837,11 +17928,8 @@ async function verifyProfile(client, profile) {
17837
17928
  }
17838
17929
  let keyType = null;
17839
17930
  let authenticated = null;
17840
- const metaOperation = V2_OPERATIONS.getMeta;
17841
17931
  try {
17842
- const response = await client.request(metaOperation.path, {
17843
- method: metaOperation.method
17844
- });
17932
+ const response = await client.request("getMeta");
17845
17933
  const reportedKeyType = toRecord(toRecord(response).data).keyType;
17846
17934
  if (reportedKeyType === "personal" || reportedKeyType === "workspace" || reportedKeyType === "oauth_access_token") {
17847
17935
  keyType = reportedKeyType;
@@ -17869,9 +17957,10 @@ async function verifyProfile(client, profile) {
17869
17957
  detail: `no workspace to check against — run: sim configure --profile ${safeOneLine(profile.name)} --set-workspace <id>`
17870
17958
  };
17871
17959
  }
17872
- const operation = V2_OPERATIONS.getWorkspace;
17873
17960
  try {
17874
- const response = await client.request(resolvePath(operation.path, { workspaceId: profile.workspaceId }), { method: operation.method });
17961
+ const response = await client.request("getWorkspace", {
17962
+ params: { workspaceId: profile.workspaceId }
17963
+ });
17875
17964
  const { id, name, memberCount } = response.data;
17876
17965
  return {
17877
17966
  status: "verified",
@@ -17911,8 +18000,10 @@ function presentVerification(verification) {
17911
18000
  }
17912
18001
  }
17913
18002
  function whoamiCommand() {
17914
- const whoami = new Command("whoami").description("Show the resolved profile, where each setting came from, and whether it works").option("--no-verify", "Skip the API check and only print the resolved settings").action(async (options, command) => {
17915
- const { client, profile } = clientFrom(command);
18003
+ const whoami = new Command("whoami");
18004
+ const connectWhoami = callsOperations(whoami, ["getMeta", "getWorkspace"]);
18005
+ return whoami.description("Show the resolved profile, where each setting came from, and whether it works").option("--no-verify", "Skip the API check and only print the resolved settings").action(async (options) => {
18006
+ const { client, profile } = connectWhoami();
17916
18007
  const { sources } = profile;
17917
18008
  const authentication = presentAuthentication(sources.credential);
17918
18009
  const verification = options.verify ? await verifyProfile(client, profile) : {
@@ -17960,7 +18051,6 @@ function whoamiCommand() {
17960
18051
  if (exitCode !== 0)
17961
18052
  setSoftExitCode(exitCode);
17962
18053
  });
17963
- return callsOperations(whoami, ["getMeta", "getWorkspace"]);
17964
18054
  }
17965
18055
  var PROFILE_COLUMNS = [
17966
18056
  { header: "", value: (row) => row.active ? styles3().green("*") : " " },
@@ -19822,35 +19912,6 @@ var CLI_CONTRACT = {
19822
19912
  getFileUpload: { hidden: true }
19823
19913
  };
19824
19914
 
19825
- // src/runtime/derive.ts
19826
- var ACTION_SEGMENTS = new Set([
19827
- "upsert",
19828
- "query",
19829
- "search",
19830
- "export",
19831
- "import",
19832
- "deploy",
19833
- "rollback"
19834
- ]);
19835
- function deriveCommandPath(operation) {
19836
- const spec = V2_OPERATIONS[operation];
19837
- const segments = spec.path.replace("/api/v2/", "").split("/");
19838
- const resource = segments[0];
19839
- const nouns = segments.slice(1).filter((segment) => !segment.startsWith("["));
19840
- const last = nouns[nouns.length - 1];
19841
- if (last && ACTION_SEGMENTS.has(last))
19842
- return [resource, last];
19843
- const isItem = spec.path.endsWith("]");
19844
- const verb = spec.method === "GET" ? isItem ? "get" : "list" : spec.method === "POST" ? "create" : spec.method === "DELETE" ? "delete" : "update";
19845
- return last ? [resource, last, verb] : [resource, verb];
19846
- }
19847
- function kebab(value) {
19848
- return value.replace(/[A-Z]/g, (character) => `-${character.toLowerCase()}`);
19849
- }
19850
- function camel(flag) {
19851
- return flag.replace(/-([a-z])/g, (_match, character) => character.toUpperCase());
19852
- }
19853
-
19854
19915
  // src/output/truncation.ts
19855
19916
  var TRUNCATION_FLAG = /^truncated$|^[A-Za-z0-9]+Truncated$/;
19856
19917
  var NEGATED_TRUNCATION_FLAG = /^(?:not|un|non|never)Truncated$|(?:Not|Un|Non|Never)Truncated$/;
@@ -20252,7 +20313,6 @@ function assertWorkspaceOperationOutcome(report, timedOut = false) {
20252
20313
  }
20253
20314
  async function waitWorkspaceOperation(client, workspaceId, operationId, timeoutSeconds, initial) {
20254
20315
  const deadline = timeoutSeconds === 0 ? Number.POSITIVE_INFINITY : Date.now() + timeoutSeconds * 1000;
20255
- const path = resolvePath(V2_OPERATIONS.getWorkspaceOperation.path, { workspaceId, operationId });
20256
20316
  let report = initial;
20257
20317
  let delay = 1000;
20258
20318
  for (;; ) {
@@ -20267,7 +20327,8 @@ async function waitWorkspaceOperation(client, workspaceId, operationId, timeoutS
20267
20327
  throw new SimApiError("Waiting timed out before a status response; reconcile using the same operation ID", 0, "OPERATION_WAIT_TIMEOUT", { workspaceId, operationId }, 4);
20268
20328
  }
20269
20329
  try {
20270
- const nextReport = readWorkspaceOperation(await client.request(path, {
20330
+ const nextReport = readWorkspaceOperation(await client.request("getWorkspaceOperation", {
20331
+ params: { workspaceId, operationId },
20271
20332
  signal: Number.isFinite(remaining) ? AbortSignal.timeout(Math.max(1, Math.ceil(remaining))) : undefined
20272
20333
  }));
20273
20334
  if (nextReport.workspaceId !== workspaceId || nextReport.operationId !== operationId)
@@ -20295,9 +20356,10 @@ async function waitWorkspaceOperation(client, workspaceId, operationId, timeoutS
20295
20356
  }
20296
20357
  }
20297
20358
  function attachWorkspaceOperationWait(operations) {
20298
- operations.command("wait").argument("<operationId>", "Operation ID returned by import, fork, push, or pull").allowExcessArguments(false).description("Wait for copy and deployment readiness; exit 3 for configuration, 1 for failure, or 4 for timeout").option("--wait-timeout <seconds>", "Maximum total wait (default 3600; 0 waits indefinitely)").action(async (operationId, options, command) => {
20359
+ const [wait, connectWait] = apiCommand(operations, "wait", ["getWorkspaceOperation"]);
20360
+ wait.argument("<operationId>", "Operation ID returned by import, fork, push, or pull").allowExcessArguments(false).description("Wait for copy and deployment readiness; exit 3 for configuration, 1 for failure, or 4 for timeout").option("--wait-timeout <seconds>", "Maximum total wait (default 3600; 0 waits indefinitely)").action(async (operationId, options) => {
20299
20361
  const timeout = workspaceWaitTimeout(options.waitTimeout);
20300
- const { client, profile } = clientFrom(command);
20362
+ const { client, profile } = connectWait();
20301
20363
  const workspaceId = client.requireWorkspace();
20302
20364
  const result = await waitWorkspaceOperation(client, workspaceId, operationId, timeout);
20303
20365
  renderResult("getWorkspaceOperation", profile.output, result.report, CLI_CONTRACT.getWorkspaceOperation ?? {});
@@ -20645,7 +20707,7 @@ function boundedRequest(request) {
20645
20707
  async function buildRequest(operation, positional, flags, workspaceId) {
20646
20708
  const commandSpec = CLI_CONTRACT[operation] ?? {};
20647
20709
  const spec = V2_OPERATIONS[operation];
20648
- let path = spec.path;
20710
+ const params = {};
20649
20711
  let positionalIndex = 0;
20650
20712
  for (const param of spec.pathParams) {
20651
20713
  const pathFlag = commandSpec.pathFlags?.[param];
@@ -20662,7 +20724,7 @@ async function buildRequest(operation, positional, flags, workspaceId) {
20662
20724
  if (typeof value !== "string" || value.length === 0) {
20663
20725
  throw new SimApiError(pathFlag ? `--${flagName} cannot be empty` : `<${argumentName}> cannot be empty`, 0);
20664
20726
  }
20665
- path = path.replace(`[${param}]`, encodeURIComponent(value));
20727
+ params[param] = value;
20666
20728
  }
20667
20729
  const query = {};
20668
20730
  const body = {};
@@ -20735,7 +20797,7 @@ async function buildRequest(operation, positional, flags, workspaceId) {
20735
20797
  throw new SimApiError(`--${variant.name} must be a JSON ${variant.kind}`, 0);
20736
20798
  }
20737
20799
  return boundedRequest({
20738
- path,
20800
+ params,
20739
20801
  query,
20740
20802
  body: { ...body, [variant.property]: parsed },
20741
20803
  ...headerSlot
@@ -20749,14 +20811,14 @@ async function buildRequest(operation, positional, flags, workspaceId) {
20749
20811
  throw new SimApiError("--body must be a JSON object", 0);
20750
20812
  }
20751
20813
  return boundedRequest({
20752
- path,
20814
+ params,
20753
20815
  query,
20754
20816
  body: { ...body, ...parsed },
20755
20817
  ...headerSlot
20756
20818
  });
20757
20819
  }
20758
20820
  return boundedRequest({
20759
- path,
20821
+ params,
20760
20822
  query,
20761
20823
  body: spec.body ? body : undefined,
20762
20824
  ...headerSlot
@@ -21132,7 +21194,7 @@ async function executeOperation(operation, commandSpec, operationSpec, invocatio
21132
21194
  if (commandSpec.allWorkspaces && requestFlags.allWorkspaces && requestFlags.workspace) {
21133
21195
  throw new SimApiError("--all-workspaces cannot be combined with --workspace", 0);
21134
21196
  }
21135
- const { client, profile } = clientFrom(host);
21197
+ const { client, profile } = connect(host);
21136
21198
  const hasWorkspaceField = Boolean(operationSpec.query && PROFILE_INJECTED_FIELD in operationSpec.query || operationSpec.body && PROFILE_INJECTED_FIELD in operationSpec.body);
21137
21199
  const omitsWorkspace = commandSpec.allWorkspaces && requestFlags.allWorkspaces === true;
21138
21200
  const needsWorkspace = (hasWorkspaceField || commandSpec.profileWorkspacePath === true) && !omitsWorkspace;
@@ -21166,8 +21228,8 @@ async function executeOperation(operation, commandSpec, operationSpec, invocatio
21166
21228
  do {
21167
21229
  const pageSize = Math.min(DEFAULT_PAGE_SIZE, limit - rows.length);
21168
21230
  const pageLimit = "limit" in (operationSpec[paging] ?? {}) ? { limit: pageSize } : {};
21169
- const page = await client.request(request.path, {
21170
- method: operationSpec.method,
21231
+ const page = await client.request(operation, {
21232
+ params: request.params,
21171
21233
  headers: request.headers,
21172
21234
  query: paging === "query" ? { ...request.query, ...pageLimit, cursor } : request.query,
21173
21235
  body: paging === "body" ? { ...request.body ?? {}, ...pageLimit, ...cursor ? { cursor } : {} } : request.body
@@ -21190,8 +21252,8 @@ async function executeOperation(operation, commandSpec, operationSpec, invocatio
21190
21252
  }
21191
21253
  let result;
21192
21254
  try {
21193
- result = await client.request(request.path, {
21194
- method: operationSpec.method,
21255
+ result = await client.request(operation, {
21256
+ params: request.params,
21195
21257
  headers: request.headers,
21196
21258
  query: request.query,
21197
21259
  body: request.body
@@ -21346,7 +21408,7 @@ function argumentSyntax(command) {
21346
21408
  return argument.required ? `<${name}>` : `[${name}]`;
21347
21409
  }).join(" ");
21348
21410
  }
21349
- function commandPath(command) {
21411
+ function commandPath2(command) {
21350
21412
  const names = [];
21351
21413
  let current = command;
21352
21414
  while (current) {
@@ -21368,7 +21430,7 @@ function addParseErrorGuidance(command) {
21368
21430
  outputError(message, write);
21369
21431
  if (message.startsWith("error: missing required argument ")) {
21370
21432
  const syntax = argumentSyntax(command);
21371
- const example = syntax ? `${commandPath(command)} ${syntax}` : commandPath(command);
21433
+ const example = syntax ? `${commandPath2(command)} ${syntax}` : commandPath2(command);
21372
21434
  write(`Example: ${example}
21373
21435
  `);
21374
21436
  return;
@@ -21377,13 +21439,13 @@ function addParseErrorGuidance(command) {
21377
21439
  if (!token)
21378
21440
  return;
21379
21441
  if (looksLikeAnId(token) && command.registeredArguments.length > 0) {
21380
- write(`Example: ${commandPath(command)} -- ${token}
21442
+ write(`Example: ${commandPath2(command)} -- ${token}
21381
21443
  `);
21382
21444
  return;
21383
21445
  }
21384
21446
  const flags = command.options.filter((option) => !option.hidden).map((option) => option.flags);
21385
- write(flags.length > 0 ? `Options for ${commandPath(command)}: ${flags.join(", ")}
21386
- ` : `${commandPath(command)} takes no options.
21447
+ write(flags.length > 0 ? `Options for ${commandPath2(command)}: ${flags.join(", ")}
21448
+ ` : `${commandPath2(command)} takes no options.
21387
21449
  `);
21388
21450
  }
21389
21451
  });
@@ -21443,7 +21505,7 @@ function refuseHelpAfterUnknownCommand(program) {
21443
21505
  }
21444
21506
  function configureOperation(command, operation, spec) {
21445
21507
  const operationSpec = V2_OPERATIONS[operation];
21446
- runsOperation(command, operation);
21508
+ callsOperations(command, spec.workspaceOperation ? [operation, "getWorkspaceOperation"] : [operation], { runs: operation });
21447
21509
  command.allowExcessArguments(false);
21448
21510
  for (const alias of spec.aliases ?? [])
21449
21511
  command.alias(alias);
@@ -21670,12 +21732,9 @@ async function credentialValues(provider, raw) {
21670
21732
  }
21671
21733
  return values;
21672
21734
  }
21673
- async function createServiceAccount(command, providerId, options) {
21674
- const { client, profile } = clientFrom(command);
21735
+ async function createServiceAccount({ client, profile }, providerId, options) {
21675
21736
  const workspaceId = client.requireWorkspace();
21676
- const discovery = V2_OPERATIONS.listCredentialProviders;
21677
- const catalog = await client.request(discovery.path, {
21678
- method: discovery.method,
21737
+ const catalog = await client.request("listCredentialProviders", {
21679
21738
  query: { workspaceId }
21680
21739
  });
21681
21740
  const provider = serviceAccountProvider(catalog.data, providerId);
@@ -21683,9 +21742,7 @@ async function createServiceAccount(command, providerId, options) {
21683
21742
  throw new SimApiError(`--id is required for ${providerId}.`, 0);
21684
21743
  }
21685
21744
  const credentialFields = await credentialValues(provider, options.credentials);
21686
- const operation = V2_OPERATIONS.createServiceAccountCredential;
21687
- const response = await client.request(operation.path, {
21688
- method: operation.method,
21745
+ const response = await client.request("createServiceAccountCredential", {
21689
21746
  body: {
21690
21747
  workspaceId,
21691
21748
  type: "service_account",
@@ -21698,11 +21755,8 @@ async function createServiceAccount(command, providerId, options) {
21698
21755
  });
21699
21756
  renderResult("createServiceAccountCredential", profile.output, response.data, SERVICE_ACCOUNT_RESULT);
21700
21757
  }
21701
- async function createConnectionLink(command, body) {
21702
- const { client, profile } = clientFrom(command);
21703
- const operation = V2_OPERATIONS.createCredentialConnection;
21704
- const response = await client.request(operation.path, {
21705
- method: operation.method,
21758
+ async function createConnectionLink({ client, profile }, body) {
21759
+ const response = await client.request("createCredentialConnection", {
21706
21760
  body: {
21707
21761
  workspaceId: client.requireWorkspace(),
21708
21762
  ...body
@@ -21729,11 +21783,14 @@ function attachCredentialCommands(program) {
21729
21783
  if (!credentials)
21730
21784
  throw new Error("The generated credentials command group is missing");
21731
21785
  acceptNameOnUpdate(credentials);
21732
- const create = credentials.command("create").argument("<providerId>", "Service-account provider to create a credential for").description(describeOperation(V2_OPERATIONS.createServiceAccountCredential, "Create a service-account credential using its discovered provider schema")).requiredOption("--name <displayName>", "Name shown for the credential in Sim (required)").requiredOption("--credentials <json|@file>", "Provider credentials as JSON (or @path / @- to read a file or stdin) (required)").option("--description <description>", "Optional credential description").option("--id <credentialId>", "Client-generated credential ID when provider discovery requires it").action((providerId, options, command) => createServiceAccount(command, providerId, options));
21733
- callsOperations(create, ["listCredentialProviders", "createServiceAccountCredential"]);
21734
- runsOperation(create, "createServiceAccountCredential");
21735
- credentials.command("connect").argument("<providerId>", "OAuth provider to connect").description(describeOperation(V2_OPERATIONS.createCredentialConnection, "Create a short-lived link for connecting an OAuth provider")).requiredOption("--name <displayName>", "Name shown for the new credential in Sim (required)").action(async (providerId, options, command) => createConnectionLink(command, { providerId, displayName: options.name }));
21736
- credentials.command("reconnect").argument("<credentialId>", "Existing OAuth credential to re-authorize").description(describeOperation(V2_OPERATIONS.createCredentialConnection, "Create a short-lived link for reconnecting an OAuth credential")).action((credentialId, _options, command) => createConnectionLink(command, { credentialId }));
21786
+ const [create, connectCreate] = apiCommand(credentials, "create", ["listCredentialProviders", "createServiceAccountCredential"], { runs: "createServiceAccountCredential" });
21787
+ create.argument("<providerId>", "Service-account provider to create a credential for").description(describeOperation(V2_OPERATIONS.createServiceAccountCredential, "Create a service-account credential using its discovered provider schema")).requiredOption("--name <displayName>", "Name shown for the credential in Sim (required)").requiredOption("--credentials <json|@file>", "Provider credentials as JSON (or @path / @- to read a file or stdin) (required)").option("--description <description>", "Optional credential description").option("--id <credentialId>", "Client-generated credential ID when provider discovery requires it").action((providerId, options) => createServiceAccount(connectCreate(), providerId, options));
21788
+ const [connect, connectLink] = apiCommand(credentials, "connect", ["createCredentialConnection"]);
21789
+ connect.argument("<providerId>", "OAuth provider to connect").description(describeOperation(V2_OPERATIONS.createCredentialConnection, "Create a short-lived link for connecting an OAuth provider")).requiredOption("--name <displayName>", "Name shown for the new credential in Sim (required)").action(async (providerId, options) => createConnectionLink(connectLink(), { providerId, displayName: options.name }));
21790
+ const [reconnect, reconnectLink] = apiCommand(credentials, "reconnect", [
21791
+ "createCredentialConnection"
21792
+ ]);
21793
+ reconnect.argument("<credentialId>", "Existing OAuth credential to re-authorize").description(describeOperation(V2_OPERATIONS.createCredentialConnection, "Create a short-lived link for reconnecting an OAuth credential")).action((credentialId) => createConnectionLink(reconnectLink(), { credentialId }));
21737
21794
  }
21738
21795
 
21739
21796
  // src/http/ndjson.ts
@@ -21819,7 +21876,8 @@ function ignoreBrokenPipe(stream) {
21819
21876
  };
21820
21877
  }
21821
21878
  function attachChat(program) {
21822
- const chat = program.command("chat").description("Ask Sim and print the reply").argument("<message>", "What to ask Sim").allowExcessArguments(false).option("-c, --conversation <id>", "Continue the conversation with this ID").addHelpText("after", `
21879
+ const [chat, connectChat] = apiCommand(program, "chat", ["chat"]);
21880
+ chat.description("Ask Sim and print the reply").argument("<message>", "What to ask Sim").allowExcessArguments(false).option("-c, --conversation <id>", "Continue the conversation with this ID").addHelpText("after", `
21823
21881
  Each turn prints the reply on stdout and the conversation ID on stderr; pass
21824
21882
  that ID back with -c to continue the same conversation. With --output json or
21825
21883
  yaml the reply is not streamed — the finished result is printed as one
@@ -21829,17 +21887,16 @@ Examples:
21829
21887
  $ sim chat "What workflows do I have?"
21830
21888
  $ sim chat -c 3f2a… "Which of those run on a schedule?"
21831
21889
  $ sim --output json chat "Summarize yesterday's failed runs" | jq -r '.content'
21832
- `).action(async (message, options, command) => {
21890
+ `).action(async (message, options) => {
21833
21891
  if (message.trim() === "") {
21834
21892
  throw new SimApiError("<message> cannot be empty", 0);
21835
21893
  }
21836
21894
  if (options.conversation !== undefined && options.conversation.trim() === "") {
21837
21895
  throw new SimApiError("-c/--conversation cannot be empty — pass the conversation id printed on stderr after each turn", 0);
21838
21896
  }
21839
- const { client, profile } = clientFrom(command);
21897
+ const { client, profile } = connectChat();
21840
21898
  const workspaceId = client.requireWorkspace();
21841
- const response = await client.requestRaw(V2_OPERATIONS.chat.path, {
21842
- method: "POST",
21899
+ const response = await client.requestRaw("chat", {
21843
21900
  body: {
21844
21901
  workspaceId,
21845
21902
  message,
@@ -21885,7 +21942,6 @@ Examples:
21885
21942
  restorePipeHandling?.();
21886
21943
  }
21887
21944
  });
21888
- callsOperations(chat, ["chat"]);
21889
21945
  }
21890
21946
 
21891
21947
  // src/commands/protocol/files-get.ts
@@ -22066,16 +22122,16 @@ function isTerminalSafeContentType(contentType) {
22066
22122
  "image/svg+xml"
22067
22123
  ].includes(mediaType);
22068
22124
  }
22069
- async function downloadToOutput(command, operation, pathParams, options) {
22125
+ async function downloadToOutput(connectDownload, operation, params, options) {
22070
22126
  const target = options.outputFile;
22071
22127
  const writesToStdout = target === undefined || target === "-";
22072
22128
  if (writesToStdout && options.force) {
22073
22129
  throw new SimApiError("--force requires --output-file <path>", 0);
22074
22130
  }
22075
- const { client, profile } = clientFrom(command);
22131
+ const { client, profile } = connectDownload();
22076
22132
  const workspaceId = client.requireWorkspace();
22077
- const response = await client.requestRaw(resolvePath(operation.path, pathParams), {
22078
- method: operation.method,
22133
+ const response = await client.requestRaw(operation, {
22134
+ params,
22079
22135
  query: { workspaceId }
22080
22136
  });
22081
22137
  if (!response.body) {
@@ -22093,18 +22149,18 @@ async function downloadToOutput(command, operation, pathParams, options) {
22093
22149
  }
22094
22150
  const savedTarget = await saveToFile(response.body, target, Boolean(options.force));
22095
22151
  printProtocolResult(profile.output, {
22096
- id: pathParams.fileId,
22152
+ id: params.fileId,
22097
22153
  path: savedTarget,
22098
22154
  status: "saved"
22099
22155
  });
22100
22156
  }
22101
22157
  function attachFileGet(files) {
22102
- const get = files.command("get").argument("<fileId>", "File whose content to read").allowExcessArguments(false).description("Download a file’s content to stdout or a local file").option("-o, --output-file <path>", "Write content to a file instead of stdout").option("--force", "Overwrite --output-file if it already exists").action((fileId, options, command) => downloadToOutput(command, V2_OPERATIONS.downloadFile, { fileId }, options));
22103
- callsOperations(get, ["downloadFile"]);
22158
+ const [get, connectGet] = apiCommand(files, "get", ["downloadFile"]);
22159
+ get.argument("<fileId>", "File whose content to read").allowExcessArguments(false).description("Download a file’s content to stdout or a local file").option("-o, --output-file <path>", "Write content to a file instead of stdout").option("--force", "Overwrite --output-file if it already exists").action((fileId, options) => downloadToOutput(connectGet, "downloadFile", { fileId }, options));
22104
22160
  }
22105
22161
  function attachFileVersionDownload(versions) {
22106
- const download = versions.command("download").argument("<fileId>", "File identifier.").argument("<version>", "Version number.").allowExcessArguments(false).description("Download the content of one version of a file").option("-o, --output-file <path>", "Write content to a file instead of stdout").option("--force", "Overwrite --output-file if it already exists").action((fileId, version, options, command) => downloadToOutput(command, V2_OPERATIONS.downloadFileVersion, { fileId, version }, options));
22107
- callsOperations(download, ["downloadFileVersion"]);
22162
+ const [download, connectDownload] = apiCommand(versions, "download", ["downloadFileVersion"]);
22163
+ download.argument("<fileId>", "File identifier.").argument("<version>", "Version number.").allowExcessArguments(false).description("Download the content of one version of a file").option("-o, --output-file <path>", "Write content to a file instead of stdout").option("--force", "Overwrite --output-file if it already exists").action((fileId, version, options) => downloadToOutput(connectDownload, "downloadFileVersion", { fileId, version }, options));
22108
22164
  }
22109
22165
 
22110
22166
  // src/transfer/upload-session.ts
@@ -22230,8 +22286,8 @@ async function uploadParts(client, workspaceId, session, transfer, file) {
22230
22286
  for (let n = first;n < first + PART_URL_BATCH && n <= transfer.partCount; n++) {
22231
22287
  partNumbers.push(n);
22232
22288
  }
22233
- const signed = await client.request(`${session.basePath}/parts`, {
22234
- method: "POST",
22289
+ const signed = await client.request(session.operations.parts, {
22290
+ params: session.params,
22235
22291
  query: { workspaceId },
22236
22292
  headers: { "upload-token": session.uploadToken },
22237
22293
  body: { partNumbers }
@@ -22279,8 +22335,8 @@ async function finishUploadSession(client, workspaceId, session, path) {
22279
22335
  await streamed?.verifyComplete();
22280
22336
  await streamed?.close();
22281
22337
  await snapshot?.dispose().catch(() => {});
22282
- const completed = await client.request(`${session.basePath}/complete`, {
22283
- method: "POST",
22338
+ const completed = await client.request(session.operations.complete, {
22339
+ params: session.params,
22284
22340
  query: { workspaceId },
22285
22341
  headers: { "upload-token": session.uploadToken }
22286
22342
  });
@@ -22288,9 +22344,9 @@ async function finishUploadSession(client, workspaceId, session, path) {
22288
22344
  } catch (error) {
22289
22345
  await streamed?.close();
22290
22346
  const profile = embeddedProfile();
22291
- const cleanupClient = profile ? new SimClient({ ...profile, signal: AbortSignal.timeout(5000) }) : client;
22292
- await cleanupClient.request(session.basePath, {
22293
- method: "DELETE",
22347
+ const cleanupClient = profile ? client.over(new SimClient({ ...profile, signal: AbortSignal.timeout(5000) })) : client;
22348
+ await cleanupClient.request(session.operations.abort, {
22349
+ params: session.params,
22294
22350
  query: { workspaceId },
22295
22351
  headers: { "upload-token": session.uploadToken }
22296
22352
  }).catch(() => {
@@ -22305,12 +22361,17 @@ async function finishUploadSession(client, workspaceId, session, path) {
22305
22361
 
22306
22362
  // src/commands/protocol/files-upload.ts
22307
22363
  function attachFileUpload(files) {
22308
- files.command("upload").argument("<path>", "Local file to upload").allowExcessArguments(false).description("Upload a file to the workspace").option("--folder <path>", "Folder path as shown in the app; defaults to the root folder").option("--name <name>", "Store it under a different name").action(async (path, options, command) => {
22309
- const { client, profile } = clientFrom(command);
22364
+ const [upload, connectUpload] = apiCommand(files, "upload", [
22365
+ "createFileUpload",
22366
+ "createFileUploadPartUrls",
22367
+ "completeFileUpload",
22368
+ "abortFileUpload"
22369
+ ]);
22370
+ upload.argument("<path>", "Local file to upload").allowExcessArguments(false).description("Upload a file to the workspace").option("--folder <path>", "Folder path as shown in the app; defaults to the root folder").option("--name <name>", "Store it under a different name").action(async (path, options) => {
22371
+ const { client, profile } = connectUpload();
22310
22372
  const workspaceId = client.requireWorkspace();
22311
22373
  const { name, size } = await localFile(path, options.name);
22312
- const created = await client.request(V2_OPERATIONS.createFileUpload.path, {
22313
- method: "POST",
22374
+ const created = await client.request("createFileUpload", {
22314
22375
  body: {
22315
22376
  workspaceId,
22316
22377
  name,
@@ -22321,7 +22382,12 @@ function attachFileUpload(files) {
22321
22382
  });
22322
22383
  const { session, uploadToken, transfer } = created.data;
22323
22384
  const completed = await finishUploadSession(client, workspaceId, {
22324
- basePath: `/api/v2/files/uploads/${encodeURIComponent(session.id)}`,
22385
+ operations: {
22386
+ parts: "createFileUploadPartUrls",
22387
+ complete: "completeFileUpload",
22388
+ abort: "abortFileUpload"
22389
+ },
22390
+ params: { uploadId: session.id },
22325
22391
  uploadToken,
22326
22392
  transfer,
22327
22393
  size
@@ -22358,12 +22424,18 @@ var UPLOAD_RECIPES = [
22358
22424
  ];
22359
22425
  var LANGUAGE_TAG_HELP = "Document language tag: hyphen-separated letter and digit subtags, for example en or en-US";
22360
22426
  function attachKnowledgeDocumentUpload(documents) {
22361
- documents.command("upload").argument("<knowledgeBaseId>", "Knowledge base to upload into").argument("<path>", "Local file to upload").allowExcessArguments(false).description("Upload a document to a knowledge base").option("--name <name>", "Store it under a different name").option("--tag <value...>", "Document tags, in tag1 through tag7 order").addOption(new Option("--recipe <name>", "Document processing recipe").choices(UPLOAD_RECIPES)).option("--lang <code>", LANGUAGE_TAG_HELP).action(async (knowledgeBaseId, path, options, command) => {
22362
- const { client, profile } = clientFrom(command);
22427
+ const [upload, connectUpload] = apiCommand(documents, "upload", [
22428
+ "createKnowledgeDocumentUpload",
22429
+ "createKnowledgeDocumentUploadPartUrls",
22430
+ "completeKnowledgeDocumentUpload",
22431
+ "abortKnowledgeDocumentUpload"
22432
+ ]);
22433
+ upload.argument("<knowledgeBaseId>", "Knowledge base to upload into").argument("<path>", "Local file to upload").allowExcessArguments(false).description("Upload a document to a knowledge base").option("--name <name>", "Store it under a different name").option("--tag <value...>", "Document tags, in tag1 through tag7 order").addOption(new Option("--recipe <name>", "Document processing recipe").choices(UPLOAD_RECIPES)).option("--lang <code>", LANGUAGE_TAG_HELP).action(async (knowledgeBaseId, path, options) => {
22434
+ const { client, profile } = connectUpload();
22363
22435
  const workspaceId = client.requireWorkspace();
22364
22436
  const { name, size } = await localFile(path, options.name);
22365
- const created = await client.request(`/api/v2/knowledge/${encodeURIComponent(knowledgeBaseId)}/documents/uploads`, {
22366
- method: "POST",
22437
+ const created = await client.request("createKnowledgeDocumentUpload", {
22438
+ params: { knowledgeBaseId },
22367
22439
  body: {
22368
22440
  workspaceId,
22369
22441
  name,
@@ -22374,7 +22446,12 @@ function attachKnowledgeDocumentUpload(documents) {
22374
22446
  });
22375
22447
  const { session, uploadToken, transfer } = created.data;
22376
22448
  const completed = await finishUploadSession(client, workspaceId, {
22377
- basePath: `/api/v2/knowledge/${encodeURIComponent(knowledgeBaseId)}/documents/uploads/${encodeURIComponent(session.id)}`,
22449
+ operations: {
22450
+ parts: "createKnowledgeDocumentUploadPartUrls",
22451
+ complete: "completeKnowledgeDocumentUpload",
22452
+ abort: "abortKnowledgeDocumentUpload"
22453
+ },
22454
+ params: { knowledgeBaseId, uploadId: session.id },
22378
22455
  uploadToken,
22379
22456
  transfer,
22380
22457
  size
@@ -22413,16 +22490,16 @@ function safeBaseName(name) {
22413
22490
  return base && base !== "." && base !== ".." ? base : null;
22414
22491
  }
22415
22492
  function attachKnowledgeExport(knowledge) {
22416
- const exportCommand = knowledge.command("export").argument("<knowledgeBaseId>", "Knowledge base to export").allowExcessArguments(false).description("Export a knowledge base as a .simkb.zip bundle").option("-o, --output-file <path>", "Write the bundle to this path instead of the name the server suggests; pass - to stream it to stdout").option("--force", "Overwrite --output-file if it already exists").option("--no-vectors", "Leave chunk vectors out of the bundle, so an import re-embeds every chunk").action(async (knowledgeBaseId, options, command) => {
22493
+ const [exportCommand, connectExport] = apiCommand(knowledge, "export", ["exportKnowledgeBase"]);
22494
+ exportCommand.argument("<knowledgeBaseId>", "Knowledge base to export").allowExcessArguments(false).description("Export a knowledge base as a .simkb.zip bundle").option("-o, --output-file <path>", "Write the bundle to this path instead of the name the server suggests; pass - to stream it to stdout").option("--force", "Overwrite --output-file if it already exists").option("--no-vectors", "Leave chunk vectors out of the bundle, so an import re-embeds every chunk").action(async (knowledgeBaseId, options) => {
22417
22495
  const writesToStdout = options.outputFile === "-";
22418
22496
  if (writesToStdout && options.force) {
22419
22497
  throw new SimApiError("--force requires --output-file <path>", 0);
22420
22498
  }
22421
- const { client, profile } = clientFrom(command);
22499
+ const { client, profile } = connectExport();
22422
22500
  const workspaceId = client.requireWorkspace();
22423
- const operation = V2_OPERATIONS.exportKnowledgeBase;
22424
- const response = await client.requestRaw(resolvePath(operation.path, { knowledgeBaseId }), {
22425
- method: operation.method,
22501
+ const response = await client.requestRaw("exportKnowledgeBase", {
22502
+ params: { knowledgeBaseId },
22426
22503
  query: { workspaceId, vectors: options.vectors }
22427
22504
  });
22428
22505
  if (!response.body) {
@@ -22446,7 +22523,6 @@ function attachKnowledgeExport(knowledge) {
22446
22523
  vectors: options.vectors
22447
22524
  });
22448
22525
  });
22449
- callsOperations(exportCommand, ["exportKnowledgeBase"]);
22450
22526
  }
22451
22527
 
22452
22528
  // src/commands/protocol/logs-follow.ts
@@ -22605,12 +22681,12 @@ function remember(state, rows) {
22605
22681
  excess -= 1;
22606
22682
  }
22607
22683
  }
22608
- async function collectUnprinted(client, path, query, state, pageSize, maxPages) {
22684
+ async function collectUnprinted(client, query, state, pageSize, maxPages) {
22609
22685
  const rows = [];
22610
22686
  let cursor = null;
22611
22687
  let truncated = false;
22612
22688
  for (let page = 0;page < maxPages; page += 1) {
22613
- const response = await client.request(path, {
22689
+ const response = await client.request("listLogs", {
22614
22690
  query: { ...query, limit: pageSize, cursor }
22615
22691
  });
22616
22692
  const page_rows = response?.data ?? [];
@@ -22649,7 +22725,8 @@ function inSeconds(ms) {
22649
22725
  return Math.round(ms / 100) / 10;
22650
22726
  }
22651
22727
  function attachLogsFollow(logs) {
22652
- logs.command("follow").description("Watch runs live as they arrive, printing each new run once").option("--workflow <id>", "Only follow runs of this workflow (repeatable)", collect, []).option("--folder <path>", "Only follow runs of workflows in this folder (repeatable)", collect, []).option("--trigger <type>", "Only follow runs with this trigger type (repeatable)", collect, []).addOption(new Option("--level <level>", "Only follow runs at this severity").choices([
22728
+ const [follow, connectFollow] = apiCommand(logs, "follow", ["listLogs"]);
22729
+ follow.description("Watch runs live as they arrive, printing each new run once").option("--workflow <id>", "Only follow runs of this workflow (repeatable)", collect, []).option("--folder <path>", "Only follow runs of workflows in this folder (repeatable)", collect, []).option("--trigger <type>", "Only follow runs with this trigger type (repeatable)", collect, []).addOption(new Option("--level <level>", "Only follow runs at this severity").choices([
22653
22730
  ...V2_OPERATIONS.listLogs.query.level.values
22654
22731
  ])).addOption(new Option("--details <level>", "Response detail level; full names each run’s workflow").choices([...V2_OPERATIONS.listLogs.query.details.values]).default("full")).option("-n, --lines <count>", "Recent runs to print before watching", String(DEFAULT_BACKLOG)).option("--interval <seconds>", "Seconds between polls", String(DEFAULT_INTERVAL_SECONDS)).addHelpText("after", `
22655
22732
  Each run prints once, when it is first seen, so its status is the status it had
@@ -22663,11 +22740,10 @@ Examples:
22663
22740
  $ sim logs follow --level error
22664
22741
  $ sim logs follow --workflow 00000000-0000-4000-8000-000000000000 -n 0
22665
22742
  $ sim --output json logs follow | jq -r '.runId'
22666
- `).action(async (options, command) => {
22743
+ `).action(async (options) => {
22667
22744
  const lines = nonNegativeInteger(options.lines, "--lines");
22668
22745
  const delay = intervalMs(options.interval);
22669
- const { client, profile } = clientFrom(command);
22670
- const path = V2_OPERATIONS.listLogs.path;
22746
+ const { client, profile } = connectFollow();
22671
22747
  const query = {
22672
22748
  workspaceId: client.requireWorkspace(),
22673
22749
  workflowIds: options.workflow?.length ? options.workflow.join(",") : undefined,
@@ -22683,7 +22759,7 @@ Examples:
22683
22759
  const interrupt = watchForInterrupt();
22684
22760
  const state = { seen: new Map, floor: null };
22685
22761
  try {
22686
- const seed = await collectUnprinted(client, path, query, state, Math.max(lines, 1), 1);
22762
+ const seed = await collectUnprinted(client, query, state, Math.max(lines, 1), 1);
22687
22763
  remember(state, seed.rows);
22688
22764
  state.floor = seed.rows.at(-1)?.startedAt ?? null;
22689
22765
  if (seed.truncated && seed.rows.length < lines) {
@@ -22697,7 +22773,7 @@ Examples:
22697
22773
  break;
22698
22774
  let fresh;
22699
22775
  try {
22700
- fresh = await collectUnprinted(client, path, query, state, POLL_PAGE_SIZE, MAX_PAGES_PER_POLL);
22776
+ fresh = await collectUnprinted(client, query, state, POLL_PAGE_SIZE, MAX_PAGES_PER_POLL);
22701
22777
  } catch (error) {
22702
22778
  if (!isTransient(error))
22703
22779
  throw error;
@@ -22734,25 +22810,21 @@ var COLUMNS2 = [
22734
22810
  { header: "folder", value: (entry) => text(decodeFolderPath(entry.folderPath)) },
22735
22811
  { header: "updated", value: (entry) => timestamp2(entry.updatedAt) }
22736
22812
  ];
22737
- function operationPath(operation) {
22738
- return V2_OPERATIONS[operation].path;
22739
- }
22740
22813
  async function listResources(client, config, workspaceId, folderPath, search, limit) {
22741
22814
  const query = { workspaceId, folderPath, search, sortBy: "name", sortOrder: "asc" };
22742
- const path = operationPath(config.resources);
22743
22815
  const paginated = "cursor" in V2_OPERATIONS[config.resources].query;
22744
22816
  if (!paginated) {
22745
- const page = await client.request(path, { query });
22817
+ const page = await client.request(config.resources, { query });
22746
22818
  return page.data.slice(0, limit);
22747
22819
  }
22748
- return requestAllPages(client, path, {
22820
+ return client.requestAllPages(config.resources, {
22749
22821
  query,
22750
22822
  pageSize: DEFAULT_PAGE_SIZE,
22751
22823
  limit
22752
22824
  });
22753
22825
  }
22754
22826
  async function listFolders(client, operation, workspaceId, parentPath, search) {
22755
- const page = await client.request(operationPath(operation), {
22827
+ const page = await client.request(operation, {
22756
22828
  query: { workspaceId, parentPath, search, sortBy: "name", sortOrder: "asc" }
22757
22829
  });
22758
22830
  return page.data;
@@ -22777,14 +22849,15 @@ function entriesFor(config, folders, resources) {
22777
22849
  ].sort((left, right) => left.name.localeCompare(right.name) || left.kind.localeCompare(right.kind));
22778
22850
  }
22779
22851
  function attachResourceDirectoryCommands(group, config) {
22780
- group.command("ls").argument("[path]", "Folder path to list; defaults to the root folder").allowExcessArguments(false).description(`List ${config.kind} resources and child folders together`).option("--search <text>", "Filter folders and resources by name").addOption(new Option("--limit <n>", "Maximum combined items to return (0 for everything)").default("0")).action(async (path, options, command) => {
22852
+ const [ls, connectLs] = apiCommand(group, "ls", [config.resources, config.folders]);
22853
+ ls.argument("[path]", "Folder path to list; defaults to the root folder").allowExcessArguments(false).description(`List ${config.kind} resources and child folders together`).option("--search <text>", "Filter folders and resources by name").addOption(new Option("--limit <n>", "Maximum combined items to return (0 for everything)").default("0")).action(async (path, options) => {
22781
22854
  const rawLimit = Number(options.limit);
22782
22855
  if (!Number.isSafeInteger(rawLimit) || rawLimit < 0) {
22783
22856
  throw new SimApiError("--limit must be a whole number of 0 or more (0 for everything)", 0);
22784
22857
  }
22785
22858
  const limit = rawLimit === 0 ? Number.POSITIVE_INFINITY : rawLimit;
22786
22859
  const folderPath = encodeFolderPath(path ?? "/");
22787
- const { client, profile } = clientFrom(command);
22860
+ const { client, profile } = connectLs();
22788
22861
  const workspaceId = client.requireWorkspace();
22789
22862
  const [folders, resources] = await Promise.all([
22790
22863
  listFolders(client, config.folders, workspaceId, folderPath, options.search),
@@ -22794,11 +22867,10 @@ function attachResourceDirectoryCommands(group, config) {
22794
22867
  const shown = entries.slice(0, limit);
22795
22868
  printList(profile.output, shown, COLUMNS2);
22796
22869
  });
22797
- group.command("mkdir").argument("<path>", "Folder path to create; the leading / is optional").allowExcessArguments(false).description(`Create a ${config.kind} directory at a path`).action(async (path, _options, command) => {
22798
- const { client, profile } = clientFrom(command);
22799
- const operation = V2_OPERATIONS[config.createFolder];
22800
- const result = await client.request(operation.path, {
22801
- method: operation.method,
22870
+ const [mkdir, connectMkdir] = apiCommand(group, "mkdir", [config.createFolder]);
22871
+ mkdir.argument("<path>", "Folder path to create; the leading / is optional").allowExcessArguments(false).description(`Create a ${config.kind} directory at a path`).action(async (path) => {
22872
+ const { client, profile } = connectMkdir();
22873
+ const result = await client.request(config.createFolder, {
22802
22874
  body: { workspaceId: client.requireWorkspace(), path: encodeFolderPath(path) }
22803
22875
  });
22804
22876
  renderResult(config.createFolder, profile.output, result.data ?? result, {});
@@ -22847,7 +22919,10 @@ async function watchImport(client, workspaceId, job) {
22847
22919
  let reported = null;
22848
22920
  while (!IMPORT_SETTLED.has(current.status)) {
22849
22921
  await sleep2(IMPORT_POLL_MS);
22850
- const next = await client.request(`/api/v2/tables/imports/${encodeURIComponent(current.id)}`, { query: { workspaceId } });
22922
+ const next = await client.request("getTableImport", {
22923
+ params: { importId: current.id },
22924
+ query: { workspaceId }
22925
+ });
22851
22926
  current = next.data;
22852
22927
  const line = progressLine(current);
22853
22928
  if (hasProgressTerminal() && line !== reported) {
@@ -22877,8 +22952,15 @@ function validateTargetOptions(options) {
22877
22952
  return intoExisting;
22878
22953
  }
22879
22954
  function attachTableImport(tables) {
22880
- tables.command("import").argument("[path]", "Local CSV file to import; omit when using --file-id").allowExcessArguments(false).description("Import a CSV, into a new table by default").option("--name <name>", "Identifier for the new table: letters, numbers, and underscores; defaults to the sanitized file name").option("--table-id <id>", "Import into this existing table instead of creating one").addOption(new Option("--mode <append|replace>", "How to write into --table-id (default: append)").choices(["append", "replace"])).option("--folder <path>", "Folder path for the new table, as shown in the app").option("--file-id <id>", "Import a file already in the workspace instead of a local path").option("--mapping <json|@file>", "Column mapping (--table-id only)").option("--create-columns <json|@file>", "Columns to create (--table-id only)").option("--timezone <iana>", "Timezone for date parsing, e.g. America/New_York").option("-y, --yes", "Confirm this destructive operation (required with --mode replace)").option("--no-wait", "Return once the import is queued instead of watching it").action(async (path, options, command) => {
22881
- const { client, profile } = clientFrom(command);
22955
+ const [importCommand, connectImport] = apiCommand(tables, "import", [
22956
+ "createTableImport",
22957
+ "createTableImportPartUrls",
22958
+ "completeTableImport",
22959
+ "cancelTableImport",
22960
+ "getTableImport"
22961
+ ]);
22962
+ importCommand.argument("[path]", "Local CSV file to import; omit when using --file-id").allowExcessArguments(false).description("Import a CSV, into a new table by default").option("--name <name>", "Identifier for the new table: letters, numbers, and underscores; defaults to the sanitized file name").option("--table-id <id>", "Import into this existing table instead of creating one").addOption(new Option("--mode <append|replace>", "How to write into --table-id (default: append)").choices(["append", "replace"])).option("--folder <path>", "Folder path for the new table, as shown in the app").option("--file-id <id>", "Import a file already in the workspace instead of a local path").option("--mapping <json|@file>", "Column mapping (--table-id only)").option("--create-columns <json|@file>", "Columns to create (--table-id only)").option("--timezone <iana>", "Timezone for date parsing, e.g. America/New_York").option("-y, --yes", "Confirm this destructive operation (required with --mode replace)").option("--no-wait", "Return once the import is queued instead of watching it").action(async (path, options) => {
22963
+ const { client, profile } = connectImport();
22882
22964
  const workspaceId = client.requireWorkspace();
22883
22965
  if (Boolean(path) === Boolean(options.fileId)) {
22884
22966
  throw new SimApiError("Pass exactly one of <path> or --file-id <id>", 0);
@@ -22908,8 +22990,7 @@ function attachTableImport(tables) {
22908
22990
  ...options.folder !== undefined ? { folderPath: encodeFolderPath(options.folder) } : {}
22909
22991
  };
22910
22992
  }
22911
- const started = await client.request(V2_OPERATIONS.createTableImport.path, {
22912
- method: "POST",
22993
+ const started = await client.request("createTableImport", {
22913
22994
  body: {
22914
22995
  workspaceId,
22915
22996
  source,
@@ -22924,12 +23005,18 @@ function attachTableImport(tables) {
22924
23005
  if (!local || !started.data.uploadToken || !started.data.transfer) {
22925
23006
  throw new Error("Local table import did not return an upload transfer");
22926
23007
  }
22927
- job = await finishUploadSession(client, workspaceId, {
22928
- basePath: `/api/v2/tables/imports/${encodeURIComponent(job.id)}`,
23008
+ const completed = await finishUploadSession(client, workspaceId, {
23009
+ operations: {
23010
+ parts: "createTableImportPartUrls",
23011
+ complete: "completeTableImport",
23012
+ abort: "cancelTableImport"
23013
+ },
23014
+ params: { importId: job.id },
22929
23015
  uploadToken: started.data.uploadToken,
22930
23016
  transfer: started.data.transfer,
22931
23017
  size: local.size
22932
23018
  }, path);
23019
+ job = completed;
22933
23020
  }
22934
23021
  if (!options.wait) {
22935
23022
  printProtocolResult(profile.output, {
@@ -23047,13 +23134,13 @@ function withEmbeddedFileReferences(body) {
23047
23134
  }
23048
23135
  async function runWithResultStream(workflowId, command) {
23049
23136
  const flags = command.optsWithGlobals();
23050
- const { client, profile } = clientFrom(command);
23137
+ const { client, profile } = connect(command, ["executeWorkflow"]);
23051
23138
  const operation = V2_OPERATIONS.executeWorkflow;
23052
23139
  const commandSpec = CLI_CONTRACT.executeWorkflow ?? {};
23053
23140
  try {
23054
23141
  const request = await buildRequest("executeWorkflow", [workflowId], flags, profile.workspaceId);
23055
- const response = await client.requestRaw(request.path, {
23056
- method: operation.method,
23142
+ const response = await client.requestRaw("executeWorkflow", {
23143
+ params: request.params,
23057
23144
  query: request.query,
23058
23145
  body: withEmbeddedFileReferences(request.body),
23059
23146
  headers: { ...request.headers, accept: WORKFLOW_RESULT_STREAM_CONTENT_TYPE }
@@ -23191,11 +23278,11 @@ async function followRun(workflowId, command) {
23191
23278
  const includeThinking = flags.includeThinking === true;
23192
23279
  const includeToolCalls = flags.includeToolCalls === true;
23193
23280
  const negotiates = includeThinking || includeToolCalls;
23194
- const { client, profile } = clientFrom(command);
23281
+ const { client, profile } = connect(command, ["executeWorkflow"]);
23195
23282
  const operation = V2_OPERATIONS.executeWorkflow;
23196
23283
  const request = await buildRequest("executeWorkflow", [workflowId], flags, profile.workspaceId);
23197
- const response = await client.requestRaw(request.path, {
23198
- method: "POST",
23284
+ const response = await client.requestRaw("executeWorkflow", {
23285
+ params: request.params,
23199
23286
  query: request.query,
23200
23287
  body: {
23201
23288
  ...withEmbeddedFileReferences(request.body),
@@ -23271,10 +23358,7 @@ function normalizeBlockName(name) {
23271
23358
  return name.toLowerCase().replace(/\s+/g, "").replace(/\./g, "");
23272
23359
  }
23273
23360
  async function loadWorkflowBlocks(client, workflowId) {
23274
- const operation = V2_OPERATIONS.getWorkflowState;
23275
- const raw = await client.request(resolvePath(operation.path, { workflowId }), {
23276
- method: operation.method
23277
- });
23361
+ const raw = await client.request("getWorkflowState", { params: { workflowId } });
23278
23362
  const state = isRecordLike(raw) && isRecordLike(raw.data) ? raw.data : raw;
23279
23363
  const blocks = isRecordLike(state) && isRecordLike(state.blocks) ? Object.entries(state.blocks) : [];
23280
23364
  return blocks.map(([key, block]) => ({
@@ -23328,9 +23412,8 @@ function keyByTyped(payload, typedBy) {
23328
23412
  }
23329
23413
  return { ...payload, blockOutputs };
23330
23414
  }
23331
- async function readRunByName(runId, typed, command) {
23415
+ async function readRunByName(runId, typed, command, { client, profile }) {
23332
23416
  const flags = command.optsWithGlobals();
23333
- const { client, profile } = clientFrom(command);
23334
23417
  const operation = V2_OPERATIONS.getWorkflowRun;
23335
23418
  const spec = CLI_CONTRACT.getWorkflowRun ?? {};
23336
23419
  await buildRequest("getWorkflowRun", [runId], flags, profile.workspaceId);
@@ -23339,8 +23422,8 @@ async function readRunByName(runId, typed, command) {
23339
23422
  const request = await buildRequest("getWorkflowRun", [runId], { ...flags, selectOutput: selection.resolved }, profile.workspaceId);
23340
23423
  let result;
23341
23424
  try {
23342
- result = await client.request(request.path, {
23343
- method: operation.method,
23425
+ result = await client.request("getWorkflowRun", {
23426
+ params: request.params,
23344
23427
  headers: request.headers,
23345
23428
  query: request.query,
23346
23429
  body: request.body
@@ -23357,6 +23440,7 @@ function attachWorkflowRunGet(runs) {
23357
23440
  throw new Error("workflows runs get must be registered before block names can be attached to it");
23358
23441
  }
23359
23442
  const previous = held;
23443
+ const connectGet = callsOperations(get, ["getWorkflowRun", "getWorkflowState"]);
23360
23444
  get.action(async (runId, _options, command) => {
23361
23445
  const raw = command.optsWithGlobals().selectOutput;
23362
23446
  if (raw === undefined) {
@@ -23369,7 +23453,7 @@ function attachWorkflowRunGet(runs) {
23369
23453
  await previous(command.processedArgs);
23370
23454
  return;
23371
23455
  }
23372
- await readRunByName(runId, typed, command);
23456
+ await readRunByName(runId, typed, command, connectGet());
23373
23457
  });
23374
23458
  }
23375
23459
 
@@ -23451,18 +23535,18 @@ function runSpec() {
23451
23535
  return CLI_CONTRACT.getWorkflowRun ?? {};
23452
23536
  }
23453
23537
  function attachWorkflowRunWait(runs) {
23454
- runs.command("wait").argument("<runId>", V2_OPERATIONS.getWorkflowRun.pathParamDocs?.runId).allowExcessArguments(false).description("Wait for a run to reach a terminal state, then show it").addOption(new Option("--workflow <workflowId>", "Workflow ID (required)").makeOptionMandatory()).addOption(new Option(WAIT_TIMEOUT_FLAG, `Give up after this many seconds, or 0 to wait indefinitely (default: ${DEFAULT_WAIT_TIMEOUT_SECONDS}). Bounds the whole wait; SIM_TIMEOUT_SECONDS bounds one request`)).action(async (runId, options, command) => {
23538
+ const [wait, connectWait] = apiCommand(runs, "wait", ["getWorkflowRun"]);
23539
+ wait.argument("<runId>", V2_OPERATIONS.getWorkflowRun.pathParamDocs?.runId).allowExcessArguments(false).description("Wait for a run to reach a terminal state, then show it").addOption(new Option("--workflow <workflowId>", "Workflow ID (required)").makeOptionMandatory()).addOption(new Option(WAIT_TIMEOUT_FLAG, `Give up after this many seconds, or 0 to wait indefinitely (default: ${DEFAULT_WAIT_TIMEOUT_SECONDS}). Bounds the whole wait; SIM_TIMEOUT_SECONDS bounds one request`)).action(async (runId, options) => {
23455
23540
  const timeoutSeconds = options.waitTimeout === undefined ? DEFAULT_WAIT_TIMEOUT_SECONDS : parseWaitTimeout(options.waitTimeout);
23456
- const { client, profile } = clientFrom(command);
23457
- const operation = V2_OPERATIONS.getWorkflowRun;
23458
- const path = resolvePath(operation.path, { workflowId: options.workflow, runId });
23541
+ const { client, profile } = connectWait();
23542
+ const params = { workflowId: options.workflow, runId };
23459
23543
  const startedAt = Date.now();
23460
23544
  const deadline = timeoutSeconds === 0 ? Number.POSITIVE_INFINITY : startedAt + timeoutSeconds * 1000;
23461
23545
  const progress = waitProgress();
23462
23546
  let delayMs = FIRST_POLL_DELAY_MS;
23463
23547
  try {
23464
23548
  while (true) {
23465
- const raw = await client.request(path, { method: operation.method });
23549
+ const raw = await client.request("getWorkflowRun", { params });
23466
23550
  const snapshot = readRun(raw);
23467
23551
  const outcome = classify(snapshot);
23468
23552
  if (outcome) {
@@ -24814,17 +24898,16 @@ async function readSecretValue(options) {
24814
24898
  return exitCli(CANCELLED_EXIT_CODE);
24815
24899
  }
24816
24900
  }
24817
- async function setSecret(name, options, command, redactionSpellings) {
24901
+ async function setSecret(name, options, connectSet, redactionSpellings) {
24818
24902
  if (redactionSpellings.size > 1) {
24819
24903
  throw new SimApiError("Pass either --unredacted or --no-unredacted, not both: they are one setting, and commander keeps only whichever came last.", 0);
24820
24904
  }
24821
24905
  const description = validateWorkspaceOnlyFlag("description", options.description, options.scope);
24822
24906
  const unredacted = validateWorkspaceOnlyFlag("unredacted", options.unredacted, options.scope);
24823
24907
  const value = await readSecretValue(options);
24824
- const { client, profile } = clientFrom(command);
24825
- const operation = V2_OPERATIONS.setSecret;
24826
- const response = await client.request(resolvePath(operation.path, { name }), {
24827
- method: operation.method,
24908
+ const { client, profile } = connectSet();
24909
+ const response = await client.request("setSecret", {
24910
+ params: { name },
24828
24911
  body: {
24829
24912
  workspaceId: client.requireWorkspace(),
24830
24913
  scope: options.scope,
@@ -24840,7 +24923,8 @@ function attachSecretCommands(program) {
24840
24923
  if (!secrets)
24841
24924
  throw new Error("The generated secrets command group is missing");
24842
24925
  const redactionSpellings = new Set;
24843
- secrets.command("set").argument("<name>", "Secret name, as referenced in workflows").description(describeOperation(V2_OPERATIONS.setSecret, "Create or replace a named secret, such as an API key or environment variable")).addOption(new Option("--scope <scope>", "Secret ownership scope (required)").choices([...SECRET_SCOPES]).makeOptionMandatory()).option("--value <value|@file>", "Secret value. Passing it inline exposes it to shell history and process listings; @path reads it from a file and @- from stdin, verbatim — a trailing newline is part of the value, so write the file with printf rather than echo. Prefix a literal leading @ with a second one").option("--description <description>", "What the secret is for, shown to teammates; workspace scope only. Omit to leave an existing description unchanged").option("--unredacted", `${V2_OPERATIONS.setSecret.body.unredacted.describe} Pass --no-unredacted to restore redaction`).option("--no-unredacted", "Send --unredacted as false").on("option:unredacted", () => redactionSpellings.add("--unredacted")).on("option:no-unredacted", () => redactionSpellings.add("--no-unredacted")).action((name, options, command) => setSecret(name, options, command, redactionSpellings));
24926
+ const [set, connectSet] = apiCommand(secrets, "set", ["setSecret"]);
24927
+ set.argument("<name>", "Secret name, as referenced in workflows").description(describeOperation(V2_OPERATIONS.setSecret, "Create or replace a named secret, such as an API key or environment variable")).addOption(new Option("--scope <scope>", "Secret ownership scope (required)").choices([...SECRET_SCOPES]).makeOptionMandatory()).option("--value <value|@file>", "Secret value. Passing it inline exposes it to shell history and process listings; @path reads it from a file and @- from stdin, verbatim — a trailing newline is part of the value, so write the file with printf rather than echo. Prefix a literal leading @ with a second one").option("--description <description>", "What the secret is for, shown to teammates; workspace scope only. Omit to leave an existing description unchanged").option("--unredacted", `${V2_OPERATIONS.setSecret.body.unredacted.describe} Pass --no-unredacted to restore redaction`).option("--no-unredacted", "Send --unredacted as false").on("option:unredacted", () => redactionSpellings.add("--unredacted")).on("option:no-unredacted", () => redactionSpellings.add("--no-unredacted")).action((name, options) => setSecret(name, options, connectSet, redactionSpellings));
24844
24928
  }
24845
24929
 
24846
24930
  // src/telemetry/transport.ts
@@ -24901,13 +24985,6 @@ var FIRST_RUN_NOTICE = [
24901
24985
  ""
24902
24986
  ].join(`
24903
24987
  `);
24904
- function commandPath2(command) {
24905
- const names = [];
24906
- for (let current = command;current?.parent; current = current.parent) {
24907
- names.unshift(current.name());
24908
- }
24909
- return names;
24910
- }
24911
24988
  function typedFlags(command) {
24912
24989
  const flags = new Set;
24913
24990
  for (let current = command;current; current = current.parent) {
@@ -25016,7 +25093,7 @@ function createCommandTelemetry(options = {}) {
25016
25093
  return {
25017
25094
  observe(program) {
25018
25095
  program.hook("preAction", (_root, action) => {
25019
- const path = commandPath2(action);
25096
+ const path = commandPath(action);
25020
25097
  if (path[0] === EXCLUDED_ROOT_COMMAND || !isReportable({}))
25021
25098
  return;
25022
25099
  const state = loadTelemetryState();
@@ -25305,7 +25382,7 @@ function explainFailure(error, program) {
25305
25382
  if (error instanceof SimApiError) {
25306
25383
  let output = program.opts().output;
25307
25384
  try {
25308
- output = clientFrom(program).profile.output;
25385
+ output = profileFrom(program).output;
25309
25386
  } catch {}
25310
25387
  if (output === "json" || output === "yaml") {
25311
25388
  const payload = {