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/index.js CHANGED
@@ -17330,16 +17330,106 @@ var V2_OPERATIONS = {
17330
17330
  }
17331
17331
  };
17332
17332
 
17333
+ // src/runtime/derive.ts
17334
+ var ACTION_SEGMENTS = new Set([
17335
+ "upsert",
17336
+ "query",
17337
+ "search",
17338
+ "export",
17339
+ "import",
17340
+ "deploy",
17341
+ "rollback"
17342
+ ]);
17343
+ function deriveCommandPath(operation) {
17344
+ const spec = V2_OPERATIONS[operation];
17345
+ const segments = spec.path.replace("/api/v2/", "").split("/");
17346
+ const resource = segments[0];
17347
+ const nouns = segments.slice(1).filter((segment) => !segment.startsWith("["));
17348
+ const last = nouns[nouns.length - 1];
17349
+ if (last && ACTION_SEGMENTS.has(last))
17350
+ return [resource, last];
17351
+ const isItem = spec.path.endsWith("]");
17352
+ const verb = spec.method === "GET" ? isItem ? "get" : "list" : spec.method === "POST" ? "create" : spec.method === "DELETE" ? "delete" : "update";
17353
+ return last ? [resource, last, verb] : [resource, verb];
17354
+ }
17355
+ function kebab(value) {
17356
+ return value.replace(/[A-Z]/g, (character) => `-${character.toLowerCase()}`);
17357
+ }
17358
+ function camel(flag) {
17359
+ return flag.replace(/-([a-z])/g, (_match, character) => character.toUpperCase());
17360
+ }
17361
+ function commandPath(command) {
17362
+ const names = [];
17363
+ for (let current = command;current?.parent; current = current.parent) {
17364
+ names.unshift(current.name());
17365
+ }
17366
+ return names;
17367
+ }
17368
+
17333
17369
  // src/runtime/called-operations.ts
17334
17370
  var CALLED_OPERATIONS = new WeakMap;
17335
17371
  var RUNS_OPERATION = new WeakMap;
17336
- function runsOperation(command, operation) {
17337
- RUNS_OPERATION.set(command, operation);
17338
- return command;
17372
+ class OperationClient {
17373
+ client;
17374
+ operations;
17375
+ caller;
17376
+ constructor(client, operations, caller) {
17377
+ this.client = client;
17378
+ this.operations = operations;
17379
+ this.caller = caller;
17380
+ }
17381
+ requireWorkspace(explicit, options) {
17382
+ return this.client.requireWorkspace(explicit, options);
17383
+ }
17384
+ async request(operation, { params, ...options } = {}) {
17385
+ return this.client.request(this.route(operation, params), {
17386
+ ...options,
17387
+ method: V2_OPERATIONS[operation].method
17388
+ });
17389
+ }
17390
+ async requestRaw(operation, { params, ...options } = {}) {
17391
+ return this.client.requestRaw(this.route(operation, params), {
17392
+ ...options,
17393
+ method: V2_OPERATIONS[operation].method
17394
+ });
17395
+ }
17396
+ async requestAllPages(operation, { params, ...options }) {
17397
+ return requestAllPages(this.client, this.route(operation, params), {
17398
+ ...options,
17399
+ method: V2_OPERATIONS[operation].method
17400
+ });
17401
+ }
17402
+ over(client) {
17403
+ return new OperationClient(client, this.operations, this.caller);
17404
+ }
17405
+ route(operation, params) {
17406
+ if (!this.operations.has(operation)) {
17407
+ throw new Error(`"${this.caller}" calls ${operation}, which it does not declare`);
17408
+ }
17409
+ return resolvePath(V2_OPERATIONS[operation].path, params);
17410
+ }
17411
+ }
17412
+ function caller(command) {
17413
+ return `sim ${commandPath(command).join(" ")}`;
17414
+ }
17415
+ function connect(command, expects = []) {
17416
+ const operations = new Set(CALLED_OPERATIONS.get(command));
17417
+ const missing = operations.size === 0 ? "what it calls" : expects.find((o) => !operations.has(o));
17418
+ if (missing) {
17419
+ throw new Error(`"${caller(command)}" calls the API without declaring ${missing}`);
17420
+ }
17421
+ const { client, profile } = clientFrom(command);
17422
+ return { client: new OperationClient(client, operations, caller(command)), profile };
17339
17423
  }
17340
- function callsOperations(command, operations) {
17424
+ function callsOperations(command, operations, { runs } = {}) {
17341
17425
  CALLED_OPERATIONS.set(command, operations);
17342
- return command;
17426
+ if (runs)
17427
+ RUNS_OPERATION.set(command, runs);
17428
+ return () => connect(command, operations);
17429
+ }
17430
+ function apiCommand(parent, name, operations, declaration = {}) {
17431
+ const command = parent.command(name);
17432
+ return [command, callsOperations(command, operations, declaration)];
17343
17433
  }
17344
17434
 
17345
17435
  // src/commands/auth.ts
@@ -17439,17 +17529,16 @@ function requireStoredAuthentication(profile) {
17439
17529
  return authProfile;
17440
17530
  }
17441
17531
  async function getWorkspaceById(client, workspaceId) {
17442
- const operation = V2_OPERATIONS.getWorkspace;
17443
- const response = await client.request(resolvePath(operation.path, { workspaceId }), { method: operation.method });
17532
+ const response = await client.request("getWorkspace", {
17533
+ params: { workspaceId }
17534
+ });
17444
17535
  return response.data;
17445
17536
  }
17446
17537
  async function chooseWorkspace(client) {
17447
17538
  if (!process.stdin.isTTY) {
17448
17539
  throw new SimApiError("No workspace provided. Pass --workspace <id> when creating a profile non-interactively.", 0);
17449
17540
  }
17450
- const operation = V2_OPERATIONS.listWorkspaces;
17451
- const workspaces = await requestAllPages(client, operation.path, {
17452
- method: operation.method,
17541
+ const workspaces = await client.requestAllPages("listWorkspaces", {
17453
17542
  query: { sortBy: "name", sortOrder: "asc" },
17454
17543
  pageSize: 100,
17455
17544
  limit: MAX_INTERACTIVE_WORKSPACES + 1
@@ -17478,9 +17567,11 @@ Available workspaces:`);
17478
17567
  }
17479
17568
  }
17480
17569
  function addProfileCommand() {
17481
- 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) => {
17570
+ const add = new Command("add");
17571
+ const connectAdd = callsOperations(add, ["getWorkspace", "listWorkspaces"]);
17572
+ 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) => {
17482
17573
  validateNewProfileName(profileName);
17483
- const { client, profile } = clientFrom(command);
17574
+ const { client, profile } = connectAdd();
17484
17575
  const authProfile = requireStoredAuthentication(profile);
17485
17576
  const credential = readStoredCredential(authProfile);
17486
17577
  const workspaceId = globalsOf(command).workspace;
@@ -17788,11 +17879,8 @@ async function verifyProfile(client, profile) {
17788
17879
  }
17789
17880
  let keyType = null;
17790
17881
  let authenticated = null;
17791
- const metaOperation = V2_OPERATIONS.getMeta;
17792
17882
  try {
17793
- const response = await client.request(metaOperation.path, {
17794
- method: metaOperation.method
17795
- });
17883
+ const response = await client.request("getMeta");
17796
17884
  const reportedKeyType = toRecord(toRecord(response).data).keyType;
17797
17885
  if (reportedKeyType === "personal" || reportedKeyType === "workspace" || reportedKeyType === "oauth_access_token") {
17798
17886
  keyType = reportedKeyType;
@@ -17820,9 +17908,10 @@ async function verifyProfile(client, profile) {
17820
17908
  detail: `no workspace to check against — run: sim configure --profile ${safeOneLine(profile.name)} --set-workspace <id>`
17821
17909
  };
17822
17910
  }
17823
- const operation = V2_OPERATIONS.getWorkspace;
17824
17911
  try {
17825
- const response = await client.request(resolvePath(operation.path, { workspaceId: profile.workspaceId }), { method: operation.method });
17912
+ const response = await client.request("getWorkspace", {
17913
+ params: { workspaceId: profile.workspaceId }
17914
+ });
17826
17915
  const { id, name, memberCount } = response.data;
17827
17916
  return {
17828
17917
  status: "verified",
@@ -17862,8 +17951,10 @@ function presentVerification(verification) {
17862
17951
  }
17863
17952
  }
17864
17953
  function whoamiCommand() {
17865
- 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) => {
17866
- const { client, profile } = clientFrom(command);
17954
+ const whoami = new Command("whoami");
17955
+ const connectWhoami = callsOperations(whoami, ["getMeta", "getWorkspace"]);
17956
+ 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) => {
17957
+ const { client, profile } = connectWhoami();
17867
17958
  const { sources } = profile;
17868
17959
  const authentication = presentAuthentication(sources.credential);
17869
17960
  const verification = options.verify ? await verifyProfile(client, profile) : {
@@ -17911,7 +18002,6 @@ function whoamiCommand() {
17911
18002
  if (exitCode !== 0)
17912
18003
  setSoftExitCode(exitCode);
17913
18004
  });
17914
- return callsOperations(whoami, ["getMeta", "getWorkspace"]);
17915
18005
  }
17916
18006
  var PROFILE_COLUMNS = [
17917
18007
  { header: "", value: (row) => row.active ? styles3().green("*") : " " },
@@ -19773,35 +19863,6 @@ var CLI_CONTRACT = {
19773
19863
  getFileUpload: { hidden: true }
19774
19864
  };
19775
19865
 
19776
- // src/runtime/derive.ts
19777
- var ACTION_SEGMENTS = new Set([
19778
- "upsert",
19779
- "query",
19780
- "search",
19781
- "export",
19782
- "import",
19783
- "deploy",
19784
- "rollback"
19785
- ]);
19786
- function deriveCommandPath(operation) {
19787
- const spec = V2_OPERATIONS[operation];
19788
- const segments = spec.path.replace("/api/v2/", "").split("/");
19789
- const resource = segments[0];
19790
- const nouns = segments.slice(1).filter((segment) => !segment.startsWith("["));
19791
- const last = nouns[nouns.length - 1];
19792
- if (last && ACTION_SEGMENTS.has(last))
19793
- return [resource, last];
19794
- const isItem = spec.path.endsWith("]");
19795
- const verb = spec.method === "GET" ? isItem ? "get" : "list" : spec.method === "POST" ? "create" : spec.method === "DELETE" ? "delete" : "update";
19796
- return last ? [resource, last, verb] : [resource, verb];
19797
- }
19798
- function kebab(value) {
19799
- return value.replace(/[A-Z]/g, (character) => `-${character.toLowerCase()}`);
19800
- }
19801
- function camel(flag) {
19802
- return flag.replace(/-([a-z])/g, (_match, character) => character.toUpperCase());
19803
- }
19804
-
19805
19866
  // src/output/truncation.ts
19806
19867
  var TRUNCATION_FLAG = /^truncated$|^[A-Za-z0-9]+Truncated$/;
19807
19868
  var NEGATED_TRUNCATION_FLAG = /^(?:not|un|non|never)Truncated$|(?:Not|Un|Non|Never)Truncated$/;
@@ -20203,7 +20264,6 @@ function assertWorkspaceOperationOutcome(report, timedOut = false) {
20203
20264
  }
20204
20265
  async function waitWorkspaceOperation(client, workspaceId, operationId, timeoutSeconds, initial) {
20205
20266
  const deadline = timeoutSeconds === 0 ? Number.POSITIVE_INFINITY : Date.now() + timeoutSeconds * 1000;
20206
- const path = resolvePath(V2_OPERATIONS.getWorkspaceOperation.path, { workspaceId, operationId });
20207
20267
  let report = initial;
20208
20268
  let delay = 1000;
20209
20269
  for (;; ) {
@@ -20218,7 +20278,8 @@ async function waitWorkspaceOperation(client, workspaceId, operationId, timeoutS
20218
20278
  throw new SimApiError("Waiting timed out before a status response; reconcile using the same operation ID", 0, "OPERATION_WAIT_TIMEOUT", { workspaceId, operationId }, 4);
20219
20279
  }
20220
20280
  try {
20221
- const nextReport = readWorkspaceOperation(await client.request(path, {
20281
+ const nextReport = readWorkspaceOperation(await client.request("getWorkspaceOperation", {
20282
+ params: { workspaceId, operationId },
20222
20283
  signal: Number.isFinite(remaining) ? AbortSignal.timeout(Math.max(1, Math.ceil(remaining))) : undefined
20223
20284
  }));
20224
20285
  if (nextReport.workspaceId !== workspaceId || nextReport.operationId !== operationId)
@@ -20246,9 +20307,10 @@ async function waitWorkspaceOperation(client, workspaceId, operationId, timeoutS
20246
20307
  }
20247
20308
  }
20248
20309
  function attachWorkspaceOperationWait(operations) {
20249
- 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) => {
20310
+ const [wait, connectWait] = apiCommand(operations, "wait", ["getWorkspaceOperation"]);
20311
+ 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) => {
20250
20312
  const timeout = workspaceWaitTimeout(options.waitTimeout);
20251
- const { client, profile } = clientFrom(command);
20313
+ const { client, profile } = connectWait();
20252
20314
  const workspaceId = client.requireWorkspace();
20253
20315
  const result = await waitWorkspaceOperation(client, workspaceId, operationId, timeout);
20254
20316
  renderResult("getWorkspaceOperation", profile.output, result.report, CLI_CONTRACT.getWorkspaceOperation ?? {});
@@ -20596,7 +20658,7 @@ function boundedRequest(request) {
20596
20658
  async function buildRequest(operation, positional, flags, workspaceId) {
20597
20659
  const commandSpec = CLI_CONTRACT[operation] ?? {};
20598
20660
  const spec = V2_OPERATIONS[operation];
20599
- let path = spec.path;
20661
+ const params = {};
20600
20662
  let positionalIndex = 0;
20601
20663
  for (const param of spec.pathParams) {
20602
20664
  const pathFlag = commandSpec.pathFlags?.[param];
@@ -20613,7 +20675,7 @@ async function buildRequest(operation, positional, flags, workspaceId) {
20613
20675
  if (typeof value !== "string" || value.length === 0) {
20614
20676
  throw new SimApiError(pathFlag ? `--${flagName} cannot be empty` : `<${argumentName}> cannot be empty`, 0);
20615
20677
  }
20616
- path = path.replace(`[${param}]`, encodeURIComponent(value));
20678
+ params[param] = value;
20617
20679
  }
20618
20680
  const query = {};
20619
20681
  const body = {};
@@ -20686,7 +20748,7 @@ async function buildRequest(operation, positional, flags, workspaceId) {
20686
20748
  throw new SimApiError(`--${variant.name} must be a JSON ${variant.kind}`, 0);
20687
20749
  }
20688
20750
  return boundedRequest({
20689
- path,
20751
+ params,
20690
20752
  query,
20691
20753
  body: { ...body, [variant.property]: parsed },
20692
20754
  ...headerSlot
@@ -20700,14 +20762,14 @@ async function buildRequest(operation, positional, flags, workspaceId) {
20700
20762
  throw new SimApiError("--body must be a JSON object", 0);
20701
20763
  }
20702
20764
  return boundedRequest({
20703
- path,
20765
+ params,
20704
20766
  query,
20705
20767
  body: { ...body, ...parsed },
20706
20768
  ...headerSlot
20707
20769
  });
20708
20770
  }
20709
20771
  return boundedRequest({
20710
- path,
20772
+ params,
20711
20773
  query,
20712
20774
  body: spec.body ? body : undefined,
20713
20775
  ...headerSlot
@@ -21083,7 +21145,7 @@ async function executeOperation(operation, commandSpec, operationSpec, invocatio
21083
21145
  if (commandSpec.allWorkspaces && requestFlags.allWorkspaces && requestFlags.workspace) {
21084
21146
  throw new SimApiError("--all-workspaces cannot be combined with --workspace", 0);
21085
21147
  }
21086
- const { client, profile } = clientFrom(host);
21148
+ const { client, profile } = connect(host);
21087
21149
  const hasWorkspaceField = Boolean(operationSpec.query && PROFILE_INJECTED_FIELD in operationSpec.query || operationSpec.body && PROFILE_INJECTED_FIELD in operationSpec.body);
21088
21150
  const omitsWorkspace = commandSpec.allWorkspaces && requestFlags.allWorkspaces === true;
21089
21151
  const needsWorkspace = (hasWorkspaceField || commandSpec.profileWorkspacePath === true) && !omitsWorkspace;
@@ -21117,8 +21179,8 @@ async function executeOperation(operation, commandSpec, operationSpec, invocatio
21117
21179
  do {
21118
21180
  const pageSize = Math.min(DEFAULT_PAGE_SIZE, limit - rows.length);
21119
21181
  const pageLimit = "limit" in (operationSpec[paging] ?? {}) ? { limit: pageSize } : {};
21120
- const page = await client.request(request.path, {
21121
- method: operationSpec.method,
21182
+ const page = await client.request(operation, {
21183
+ params: request.params,
21122
21184
  headers: request.headers,
21123
21185
  query: paging === "query" ? { ...request.query, ...pageLimit, cursor } : request.query,
21124
21186
  body: paging === "body" ? { ...request.body ?? {}, ...pageLimit, ...cursor ? { cursor } : {} } : request.body
@@ -21141,8 +21203,8 @@ async function executeOperation(operation, commandSpec, operationSpec, invocatio
21141
21203
  }
21142
21204
  let result;
21143
21205
  try {
21144
- result = await client.request(request.path, {
21145
- method: operationSpec.method,
21206
+ result = await client.request(operation, {
21207
+ params: request.params,
21146
21208
  headers: request.headers,
21147
21209
  query: request.query,
21148
21210
  body: request.body
@@ -21297,7 +21359,7 @@ function argumentSyntax(command) {
21297
21359
  return argument.required ? `<${name}>` : `[${name}]`;
21298
21360
  }).join(" ");
21299
21361
  }
21300
- function commandPath(command) {
21362
+ function commandPath2(command) {
21301
21363
  const names = [];
21302
21364
  let current = command;
21303
21365
  while (current) {
@@ -21319,7 +21381,7 @@ function addParseErrorGuidance(command) {
21319
21381
  outputError(message, write);
21320
21382
  if (message.startsWith("error: missing required argument ")) {
21321
21383
  const syntax = argumentSyntax(command);
21322
- const example = syntax ? `${commandPath(command)} ${syntax}` : commandPath(command);
21384
+ const example = syntax ? `${commandPath2(command)} ${syntax}` : commandPath2(command);
21323
21385
  write(`Example: ${example}
21324
21386
  `);
21325
21387
  return;
@@ -21328,13 +21390,13 @@ function addParseErrorGuidance(command) {
21328
21390
  if (!token)
21329
21391
  return;
21330
21392
  if (looksLikeAnId(token) && command.registeredArguments.length > 0) {
21331
- write(`Example: ${commandPath(command)} -- ${token}
21393
+ write(`Example: ${commandPath2(command)} -- ${token}
21332
21394
  `);
21333
21395
  return;
21334
21396
  }
21335
21397
  const flags = command.options.filter((option) => !option.hidden).map((option) => option.flags);
21336
- write(flags.length > 0 ? `Options for ${commandPath(command)}: ${flags.join(", ")}
21337
- ` : `${commandPath(command)} takes no options.
21398
+ write(flags.length > 0 ? `Options for ${commandPath2(command)}: ${flags.join(", ")}
21399
+ ` : `${commandPath2(command)} takes no options.
21338
21400
  `);
21339
21401
  }
21340
21402
  });
@@ -21394,7 +21456,7 @@ function refuseHelpAfterUnknownCommand(program) {
21394
21456
  }
21395
21457
  function configureOperation(command, operation, spec) {
21396
21458
  const operationSpec = V2_OPERATIONS[operation];
21397
- runsOperation(command, operation);
21459
+ callsOperations(command, spec.workspaceOperation ? [operation, "getWorkspaceOperation"] : [operation], { runs: operation });
21398
21460
  command.allowExcessArguments(false);
21399
21461
  for (const alias of spec.aliases ?? [])
21400
21462
  command.alias(alias);
@@ -21621,12 +21683,9 @@ async function credentialValues(provider, raw) {
21621
21683
  }
21622
21684
  return values;
21623
21685
  }
21624
- async function createServiceAccount(command, providerId, options) {
21625
- const { client, profile } = clientFrom(command);
21686
+ async function createServiceAccount({ client, profile }, providerId, options) {
21626
21687
  const workspaceId = client.requireWorkspace();
21627
- const discovery = V2_OPERATIONS.listCredentialProviders;
21628
- const catalog = await client.request(discovery.path, {
21629
- method: discovery.method,
21688
+ const catalog = await client.request("listCredentialProviders", {
21630
21689
  query: { workspaceId }
21631
21690
  });
21632
21691
  const provider = serviceAccountProvider(catalog.data, providerId);
@@ -21634,9 +21693,7 @@ async function createServiceAccount(command, providerId, options) {
21634
21693
  throw new SimApiError(`--id is required for ${providerId}.`, 0);
21635
21694
  }
21636
21695
  const credentialFields = await credentialValues(provider, options.credentials);
21637
- const operation = V2_OPERATIONS.createServiceAccountCredential;
21638
- const response = await client.request(operation.path, {
21639
- method: operation.method,
21696
+ const response = await client.request("createServiceAccountCredential", {
21640
21697
  body: {
21641
21698
  workspaceId,
21642
21699
  type: "service_account",
@@ -21649,11 +21706,8 @@ async function createServiceAccount(command, providerId, options) {
21649
21706
  });
21650
21707
  renderResult("createServiceAccountCredential", profile.output, response.data, SERVICE_ACCOUNT_RESULT);
21651
21708
  }
21652
- async function createConnectionLink(command, body) {
21653
- const { client, profile } = clientFrom(command);
21654
- const operation = V2_OPERATIONS.createCredentialConnection;
21655
- const response = await client.request(operation.path, {
21656
- method: operation.method,
21709
+ async function createConnectionLink({ client, profile }, body) {
21710
+ const response = await client.request("createCredentialConnection", {
21657
21711
  body: {
21658
21712
  workspaceId: client.requireWorkspace(),
21659
21713
  ...body
@@ -21680,11 +21734,14 @@ function attachCredentialCommands(program) {
21680
21734
  if (!credentials)
21681
21735
  throw new Error("The generated credentials command group is missing");
21682
21736
  acceptNameOnUpdate(credentials);
21683
- 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));
21684
- callsOperations(create, ["listCredentialProviders", "createServiceAccountCredential"]);
21685
- runsOperation(create, "createServiceAccountCredential");
21686
- 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 }));
21687
- 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 }));
21737
+ const [create, connectCreate] = apiCommand(credentials, "create", ["listCredentialProviders", "createServiceAccountCredential"], { runs: "createServiceAccountCredential" });
21738
+ 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));
21739
+ const [connect, connectLink] = apiCommand(credentials, "connect", ["createCredentialConnection"]);
21740
+ 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 }));
21741
+ const [reconnect, reconnectLink] = apiCommand(credentials, "reconnect", [
21742
+ "createCredentialConnection"
21743
+ ]);
21744
+ 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 }));
21688
21745
  }
21689
21746
 
21690
21747
  // src/http/ndjson.ts
@@ -21770,7 +21827,8 @@ function ignoreBrokenPipe(stream) {
21770
21827
  };
21771
21828
  }
21772
21829
  function attachChat(program) {
21773
- 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", `
21830
+ const [chat, connectChat] = apiCommand(program, "chat", ["chat"]);
21831
+ 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", `
21774
21832
  Each turn prints the reply on stdout and the conversation ID on stderr; pass
21775
21833
  that ID back with -c to continue the same conversation. With --output json or
21776
21834
  yaml the reply is not streamed — the finished result is printed as one
@@ -21780,17 +21838,16 @@ Examples:
21780
21838
  $ sim chat "What workflows do I have?"
21781
21839
  $ sim chat -c 3f2a… "Which of those run on a schedule?"
21782
21840
  $ sim --output json chat "Summarize yesterday's failed runs" | jq -r '.content'
21783
- `).action(async (message, options, command) => {
21841
+ `).action(async (message, options) => {
21784
21842
  if (message.trim() === "") {
21785
21843
  throw new SimApiError("<message> cannot be empty", 0);
21786
21844
  }
21787
21845
  if (options.conversation !== undefined && options.conversation.trim() === "") {
21788
21846
  throw new SimApiError("-c/--conversation cannot be empty — pass the conversation id printed on stderr after each turn", 0);
21789
21847
  }
21790
- const { client, profile } = clientFrom(command);
21848
+ const { client, profile } = connectChat();
21791
21849
  const workspaceId = client.requireWorkspace();
21792
- const response = await client.requestRaw(V2_OPERATIONS.chat.path, {
21793
- method: "POST",
21850
+ const response = await client.requestRaw("chat", {
21794
21851
  body: {
21795
21852
  workspaceId,
21796
21853
  message,
@@ -21836,7 +21893,6 @@ Examples:
21836
21893
  restorePipeHandling?.();
21837
21894
  }
21838
21895
  });
21839
- callsOperations(chat, ["chat"]);
21840
21896
  }
21841
21897
 
21842
21898
  // src/commands/protocol/files-get.ts
@@ -22017,16 +22073,16 @@ function isTerminalSafeContentType(contentType) {
22017
22073
  "image/svg+xml"
22018
22074
  ].includes(mediaType);
22019
22075
  }
22020
- async function downloadToOutput(command, operation, pathParams, options) {
22076
+ async function downloadToOutput(connectDownload, operation, params, options) {
22021
22077
  const target = options.outputFile;
22022
22078
  const writesToStdout = target === undefined || target === "-";
22023
22079
  if (writesToStdout && options.force) {
22024
22080
  throw new SimApiError("--force requires --output-file <path>", 0);
22025
22081
  }
22026
- const { client, profile } = clientFrom(command);
22082
+ const { client, profile } = connectDownload();
22027
22083
  const workspaceId = client.requireWorkspace();
22028
- const response = await client.requestRaw(resolvePath(operation.path, pathParams), {
22029
- method: operation.method,
22084
+ const response = await client.requestRaw(operation, {
22085
+ params,
22030
22086
  query: { workspaceId }
22031
22087
  });
22032
22088
  if (!response.body) {
@@ -22044,18 +22100,18 @@ async function downloadToOutput(command, operation, pathParams, options) {
22044
22100
  }
22045
22101
  const savedTarget = await saveToFile(response.body, target, Boolean(options.force));
22046
22102
  printProtocolResult(profile.output, {
22047
- id: pathParams.fileId,
22103
+ id: params.fileId,
22048
22104
  path: savedTarget,
22049
22105
  status: "saved"
22050
22106
  });
22051
22107
  }
22052
22108
  function attachFileGet(files) {
22053
- 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));
22054
- callsOperations(get, ["downloadFile"]);
22109
+ const [get, connectGet] = apiCommand(files, "get", ["downloadFile"]);
22110
+ 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));
22055
22111
  }
22056
22112
  function attachFileVersionDownload(versions) {
22057
- 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));
22058
- callsOperations(download, ["downloadFileVersion"]);
22113
+ const [download, connectDownload] = apiCommand(versions, "download", ["downloadFileVersion"]);
22114
+ 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));
22059
22115
  }
22060
22116
 
22061
22117
  // src/transfer/upload-session.ts
@@ -22181,8 +22237,8 @@ async function uploadParts(client, workspaceId, session, transfer, file) {
22181
22237
  for (let n = first;n < first + PART_URL_BATCH && n <= transfer.partCount; n++) {
22182
22238
  partNumbers.push(n);
22183
22239
  }
22184
- const signed = await client.request(`${session.basePath}/parts`, {
22185
- method: "POST",
22240
+ const signed = await client.request(session.operations.parts, {
22241
+ params: session.params,
22186
22242
  query: { workspaceId },
22187
22243
  headers: { "upload-token": session.uploadToken },
22188
22244
  body: { partNumbers }
@@ -22230,8 +22286,8 @@ async function finishUploadSession(client, workspaceId, session, path) {
22230
22286
  await streamed?.verifyComplete();
22231
22287
  await streamed?.close();
22232
22288
  await snapshot?.dispose().catch(() => {});
22233
- const completed = await client.request(`${session.basePath}/complete`, {
22234
- method: "POST",
22289
+ const completed = await client.request(session.operations.complete, {
22290
+ params: session.params,
22235
22291
  query: { workspaceId },
22236
22292
  headers: { "upload-token": session.uploadToken }
22237
22293
  });
@@ -22239,9 +22295,9 @@ async function finishUploadSession(client, workspaceId, session, path) {
22239
22295
  } catch (error) {
22240
22296
  await streamed?.close();
22241
22297
  const profile = embeddedProfile();
22242
- const cleanupClient = profile ? new SimClient({ ...profile, signal: AbortSignal.timeout(5000) }) : client;
22243
- await cleanupClient.request(session.basePath, {
22244
- method: "DELETE",
22298
+ const cleanupClient = profile ? client.over(new SimClient({ ...profile, signal: AbortSignal.timeout(5000) })) : client;
22299
+ await cleanupClient.request(session.operations.abort, {
22300
+ params: session.params,
22245
22301
  query: { workspaceId },
22246
22302
  headers: { "upload-token": session.uploadToken }
22247
22303
  }).catch(() => {
@@ -22256,12 +22312,17 @@ async function finishUploadSession(client, workspaceId, session, path) {
22256
22312
 
22257
22313
  // src/commands/protocol/files-upload.ts
22258
22314
  function attachFileUpload(files) {
22259
- 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) => {
22260
- const { client, profile } = clientFrom(command);
22315
+ const [upload, connectUpload] = apiCommand(files, "upload", [
22316
+ "createFileUpload",
22317
+ "createFileUploadPartUrls",
22318
+ "completeFileUpload",
22319
+ "abortFileUpload"
22320
+ ]);
22321
+ 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) => {
22322
+ const { client, profile } = connectUpload();
22261
22323
  const workspaceId = client.requireWorkspace();
22262
22324
  const { name, size } = await localFile(path, options.name);
22263
- const created = await client.request(V2_OPERATIONS.createFileUpload.path, {
22264
- method: "POST",
22325
+ const created = await client.request("createFileUpload", {
22265
22326
  body: {
22266
22327
  workspaceId,
22267
22328
  name,
@@ -22272,7 +22333,12 @@ function attachFileUpload(files) {
22272
22333
  });
22273
22334
  const { session, uploadToken, transfer } = created.data;
22274
22335
  const completed = await finishUploadSession(client, workspaceId, {
22275
- basePath: `/api/v2/files/uploads/${encodeURIComponent(session.id)}`,
22336
+ operations: {
22337
+ parts: "createFileUploadPartUrls",
22338
+ complete: "completeFileUpload",
22339
+ abort: "abortFileUpload"
22340
+ },
22341
+ params: { uploadId: session.id },
22276
22342
  uploadToken,
22277
22343
  transfer,
22278
22344
  size
@@ -22309,12 +22375,18 @@ var UPLOAD_RECIPES = [
22309
22375
  ];
22310
22376
  var LANGUAGE_TAG_HELP = "Document language tag: hyphen-separated letter and digit subtags, for example en or en-US";
22311
22377
  function attachKnowledgeDocumentUpload(documents) {
22312
- 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) => {
22313
- const { client, profile } = clientFrom(command);
22378
+ const [upload, connectUpload] = apiCommand(documents, "upload", [
22379
+ "createKnowledgeDocumentUpload",
22380
+ "createKnowledgeDocumentUploadPartUrls",
22381
+ "completeKnowledgeDocumentUpload",
22382
+ "abortKnowledgeDocumentUpload"
22383
+ ]);
22384
+ 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) => {
22385
+ const { client, profile } = connectUpload();
22314
22386
  const workspaceId = client.requireWorkspace();
22315
22387
  const { name, size } = await localFile(path, options.name);
22316
- const created = await client.request(`/api/v2/knowledge/${encodeURIComponent(knowledgeBaseId)}/documents/uploads`, {
22317
- method: "POST",
22388
+ const created = await client.request("createKnowledgeDocumentUpload", {
22389
+ params: { knowledgeBaseId },
22318
22390
  body: {
22319
22391
  workspaceId,
22320
22392
  name,
@@ -22325,7 +22397,12 @@ function attachKnowledgeDocumentUpload(documents) {
22325
22397
  });
22326
22398
  const { session, uploadToken, transfer } = created.data;
22327
22399
  const completed = await finishUploadSession(client, workspaceId, {
22328
- basePath: `/api/v2/knowledge/${encodeURIComponent(knowledgeBaseId)}/documents/uploads/${encodeURIComponent(session.id)}`,
22400
+ operations: {
22401
+ parts: "createKnowledgeDocumentUploadPartUrls",
22402
+ complete: "completeKnowledgeDocumentUpload",
22403
+ abort: "abortKnowledgeDocumentUpload"
22404
+ },
22405
+ params: { knowledgeBaseId, uploadId: session.id },
22329
22406
  uploadToken,
22330
22407
  transfer,
22331
22408
  size
@@ -22364,16 +22441,16 @@ function safeBaseName(name) {
22364
22441
  return base && base !== "." && base !== ".." ? base : null;
22365
22442
  }
22366
22443
  function attachKnowledgeExport(knowledge) {
22367
- 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) => {
22444
+ const [exportCommand, connectExport] = apiCommand(knowledge, "export", ["exportKnowledgeBase"]);
22445
+ 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) => {
22368
22446
  const writesToStdout = options.outputFile === "-";
22369
22447
  if (writesToStdout && options.force) {
22370
22448
  throw new SimApiError("--force requires --output-file <path>", 0);
22371
22449
  }
22372
- const { client, profile } = clientFrom(command);
22450
+ const { client, profile } = connectExport();
22373
22451
  const workspaceId = client.requireWorkspace();
22374
- const operation = V2_OPERATIONS.exportKnowledgeBase;
22375
- const response = await client.requestRaw(resolvePath(operation.path, { knowledgeBaseId }), {
22376
- method: operation.method,
22452
+ const response = await client.requestRaw("exportKnowledgeBase", {
22453
+ params: { knowledgeBaseId },
22377
22454
  query: { workspaceId, vectors: options.vectors }
22378
22455
  });
22379
22456
  if (!response.body) {
@@ -22397,7 +22474,6 @@ function attachKnowledgeExport(knowledge) {
22397
22474
  vectors: options.vectors
22398
22475
  });
22399
22476
  });
22400
- callsOperations(exportCommand, ["exportKnowledgeBase"]);
22401
22477
  }
22402
22478
 
22403
22479
  // src/commands/protocol/logs-follow.ts
@@ -22556,12 +22632,12 @@ function remember(state, rows) {
22556
22632
  excess -= 1;
22557
22633
  }
22558
22634
  }
22559
- async function collectUnprinted(client, path, query, state, pageSize, maxPages) {
22635
+ async function collectUnprinted(client, query, state, pageSize, maxPages) {
22560
22636
  const rows = [];
22561
22637
  let cursor = null;
22562
22638
  let truncated = false;
22563
22639
  for (let page = 0;page < maxPages; page += 1) {
22564
- const response = await client.request(path, {
22640
+ const response = await client.request("listLogs", {
22565
22641
  query: { ...query, limit: pageSize, cursor }
22566
22642
  });
22567
22643
  const page_rows = response?.data ?? [];
@@ -22600,7 +22676,8 @@ function inSeconds(ms) {
22600
22676
  return Math.round(ms / 100) / 10;
22601
22677
  }
22602
22678
  function attachLogsFollow(logs) {
22603
- 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([
22679
+ const [follow, connectFollow] = apiCommand(logs, "follow", ["listLogs"]);
22680
+ 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([
22604
22681
  ...V2_OPERATIONS.listLogs.query.level.values
22605
22682
  ])).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", `
22606
22683
  Each run prints once, when it is first seen, so its status is the status it had
@@ -22614,11 +22691,10 @@ Examples:
22614
22691
  $ sim logs follow --level error
22615
22692
  $ sim logs follow --workflow 00000000-0000-4000-8000-000000000000 -n 0
22616
22693
  $ sim --output json logs follow | jq -r '.runId'
22617
- `).action(async (options, command) => {
22694
+ `).action(async (options) => {
22618
22695
  const lines = nonNegativeInteger(options.lines, "--lines");
22619
22696
  const delay = intervalMs(options.interval);
22620
- const { client, profile } = clientFrom(command);
22621
- const path = V2_OPERATIONS.listLogs.path;
22697
+ const { client, profile } = connectFollow();
22622
22698
  const query = {
22623
22699
  workspaceId: client.requireWorkspace(),
22624
22700
  workflowIds: options.workflow?.length ? options.workflow.join(",") : undefined,
@@ -22634,7 +22710,7 @@ Examples:
22634
22710
  const interrupt = watchForInterrupt();
22635
22711
  const state = { seen: new Map, floor: null };
22636
22712
  try {
22637
- const seed = await collectUnprinted(client, path, query, state, Math.max(lines, 1), 1);
22713
+ const seed = await collectUnprinted(client, query, state, Math.max(lines, 1), 1);
22638
22714
  remember(state, seed.rows);
22639
22715
  state.floor = seed.rows.at(-1)?.startedAt ?? null;
22640
22716
  if (seed.truncated && seed.rows.length < lines) {
@@ -22648,7 +22724,7 @@ Examples:
22648
22724
  break;
22649
22725
  let fresh;
22650
22726
  try {
22651
- fresh = await collectUnprinted(client, path, query, state, POLL_PAGE_SIZE, MAX_PAGES_PER_POLL);
22727
+ fresh = await collectUnprinted(client, query, state, POLL_PAGE_SIZE, MAX_PAGES_PER_POLL);
22652
22728
  } catch (error) {
22653
22729
  if (!isTransient(error))
22654
22730
  throw error;
@@ -22685,25 +22761,21 @@ var COLUMNS2 = [
22685
22761
  { header: "folder", value: (entry) => text(decodeFolderPath(entry.folderPath)) },
22686
22762
  { header: "updated", value: (entry) => timestamp2(entry.updatedAt) }
22687
22763
  ];
22688
- function operationPath(operation) {
22689
- return V2_OPERATIONS[operation].path;
22690
- }
22691
22764
  async function listResources(client, config, workspaceId, folderPath, search, limit) {
22692
22765
  const query = { workspaceId, folderPath, search, sortBy: "name", sortOrder: "asc" };
22693
- const path = operationPath(config.resources);
22694
22766
  const paginated = "cursor" in V2_OPERATIONS[config.resources].query;
22695
22767
  if (!paginated) {
22696
- const page = await client.request(path, { query });
22768
+ const page = await client.request(config.resources, { query });
22697
22769
  return page.data.slice(0, limit);
22698
22770
  }
22699
- return requestAllPages(client, path, {
22771
+ return client.requestAllPages(config.resources, {
22700
22772
  query,
22701
22773
  pageSize: DEFAULT_PAGE_SIZE,
22702
22774
  limit
22703
22775
  });
22704
22776
  }
22705
22777
  async function listFolders(client, operation, workspaceId, parentPath, search) {
22706
- const page = await client.request(operationPath(operation), {
22778
+ const page = await client.request(operation, {
22707
22779
  query: { workspaceId, parentPath, search, sortBy: "name", sortOrder: "asc" }
22708
22780
  });
22709
22781
  return page.data;
@@ -22728,14 +22800,15 @@ function entriesFor(config, folders, resources) {
22728
22800
  ].sort((left, right) => left.name.localeCompare(right.name) || left.kind.localeCompare(right.kind));
22729
22801
  }
22730
22802
  function attachResourceDirectoryCommands(group, config) {
22731
- 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) => {
22803
+ const [ls, connectLs] = apiCommand(group, "ls", [config.resources, config.folders]);
22804
+ 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) => {
22732
22805
  const rawLimit = Number(options.limit);
22733
22806
  if (!Number.isSafeInteger(rawLimit) || rawLimit < 0) {
22734
22807
  throw new SimApiError("--limit must be a whole number of 0 or more (0 for everything)", 0);
22735
22808
  }
22736
22809
  const limit = rawLimit === 0 ? Number.POSITIVE_INFINITY : rawLimit;
22737
22810
  const folderPath = encodeFolderPath(path ?? "/");
22738
- const { client, profile } = clientFrom(command);
22811
+ const { client, profile } = connectLs();
22739
22812
  const workspaceId = client.requireWorkspace();
22740
22813
  const [folders, resources] = await Promise.all([
22741
22814
  listFolders(client, config.folders, workspaceId, folderPath, options.search),
@@ -22745,11 +22818,10 @@ function attachResourceDirectoryCommands(group, config) {
22745
22818
  const shown = entries.slice(0, limit);
22746
22819
  printList(profile.output, shown, COLUMNS2);
22747
22820
  });
22748
- 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) => {
22749
- const { client, profile } = clientFrom(command);
22750
- const operation = V2_OPERATIONS[config.createFolder];
22751
- const result = await client.request(operation.path, {
22752
- method: operation.method,
22821
+ const [mkdir, connectMkdir] = apiCommand(group, "mkdir", [config.createFolder]);
22822
+ 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) => {
22823
+ const { client, profile } = connectMkdir();
22824
+ const result = await client.request(config.createFolder, {
22753
22825
  body: { workspaceId: client.requireWorkspace(), path: encodeFolderPath(path) }
22754
22826
  });
22755
22827
  renderResult(config.createFolder, profile.output, result.data ?? result, {});
@@ -22798,7 +22870,10 @@ async function watchImport(client, workspaceId, job) {
22798
22870
  let reported = null;
22799
22871
  while (!IMPORT_SETTLED.has(current.status)) {
22800
22872
  await sleep2(IMPORT_POLL_MS);
22801
- const next = await client.request(`/api/v2/tables/imports/${encodeURIComponent(current.id)}`, { query: { workspaceId } });
22873
+ const next = await client.request("getTableImport", {
22874
+ params: { importId: current.id },
22875
+ query: { workspaceId }
22876
+ });
22802
22877
  current = next.data;
22803
22878
  const line = progressLine(current);
22804
22879
  if (hasProgressTerminal() && line !== reported) {
@@ -22828,8 +22903,15 @@ function validateTargetOptions(options) {
22828
22903
  return intoExisting;
22829
22904
  }
22830
22905
  function attachTableImport(tables) {
22831
- 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) => {
22832
- const { client, profile } = clientFrom(command);
22906
+ const [importCommand, connectImport] = apiCommand(tables, "import", [
22907
+ "createTableImport",
22908
+ "createTableImportPartUrls",
22909
+ "completeTableImport",
22910
+ "cancelTableImport",
22911
+ "getTableImport"
22912
+ ]);
22913
+ 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) => {
22914
+ const { client, profile } = connectImport();
22833
22915
  const workspaceId = client.requireWorkspace();
22834
22916
  if (Boolean(path) === Boolean(options.fileId)) {
22835
22917
  throw new SimApiError("Pass exactly one of <path> or --file-id <id>", 0);
@@ -22859,8 +22941,7 @@ function attachTableImport(tables) {
22859
22941
  ...options.folder !== undefined ? { folderPath: encodeFolderPath(options.folder) } : {}
22860
22942
  };
22861
22943
  }
22862
- const started = await client.request(V2_OPERATIONS.createTableImport.path, {
22863
- method: "POST",
22944
+ const started = await client.request("createTableImport", {
22864
22945
  body: {
22865
22946
  workspaceId,
22866
22947
  source,
@@ -22875,12 +22956,18 @@ function attachTableImport(tables) {
22875
22956
  if (!local || !started.data.uploadToken || !started.data.transfer) {
22876
22957
  throw new Error("Local table import did not return an upload transfer");
22877
22958
  }
22878
- job = await finishUploadSession(client, workspaceId, {
22879
- basePath: `/api/v2/tables/imports/${encodeURIComponent(job.id)}`,
22959
+ const completed = await finishUploadSession(client, workspaceId, {
22960
+ operations: {
22961
+ parts: "createTableImportPartUrls",
22962
+ complete: "completeTableImport",
22963
+ abort: "cancelTableImport"
22964
+ },
22965
+ params: { importId: job.id },
22880
22966
  uploadToken: started.data.uploadToken,
22881
22967
  transfer: started.data.transfer,
22882
22968
  size: local.size
22883
22969
  }, path);
22970
+ job = completed;
22884
22971
  }
22885
22972
  if (!options.wait) {
22886
22973
  printProtocolResult(profile.output, {
@@ -22998,13 +23085,13 @@ function withEmbeddedFileReferences(body) {
22998
23085
  }
22999
23086
  async function runWithResultStream(workflowId, command) {
23000
23087
  const flags = command.optsWithGlobals();
23001
- const { client, profile } = clientFrom(command);
23088
+ const { client, profile } = connect(command, ["executeWorkflow"]);
23002
23089
  const operation = V2_OPERATIONS.executeWorkflow;
23003
23090
  const commandSpec = CLI_CONTRACT.executeWorkflow ?? {};
23004
23091
  try {
23005
23092
  const request = await buildRequest("executeWorkflow", [workflowId], flags, profile.workspaceId);
23006
- const response = await client.requestRaw(request.path, {
23007
- method: operation.method,
23093
+ const response = await client.requestRaw("executeWorkflow", {
23094
+ params: request.params,
23008
23095
  query: request.query,
23009
23096
  body: withEmbeddedFileReferences(request.body),
23010
23097
  headers: { ...request.headers, accept: WORKFLOW_RESULT_STREAM_CONTENT_TYPE }
@@ -23142,11 +23229,11 @@ async function followRun(workflowId, command) {
23142
23229
  const includeThinking = flags.includeThinking === true;
23143
23230
  const includeToolCalls = flags.includeToolCalls === true;
23144
23231
  const negotiates = includeThinking || includeToolCalls;
23145
- const { client, profile } = clientFrom(command);
23232
+ const { client, profile } = connect(command, ["executeWorkflow"]);
23146
23233
  const operation = V2_OPERATIONS.executeWorkflow;
23147
23234
  const request = await buildRequest("executeWorkflow", [workflowId], flags, profile.workspaceId);
23148
- const response = await client.requestRaw(request.path, {
23149
- method: "POST",
23235
+ const response = await client.requestRaw("executeWorkflow", {
23236
+ params: request.params,
23150
23237
  query: request.query,
23151
23238
  body: {
23152
23239
  ...withEmbeddedFileReferences(request.body),
@@ -23222,10 +23309,7 @@ function normalizeBlockName(name) {
23222
23309
  return name.toLowerCase().replace(/\s+/g, "").replace(/\./g, "");
23223
23310
  }
23224
23311
  async function loadWorkflowBlocks(client, workflowId) {
23225
- const operation = V2_OPERATIONS.getWorkflowState;
23226
- const raw = await client.request(resolvePath(operation.path, { workflowId }), {
23227
- method: operation.method
23228
- });
23312
+ const raw = await client.request("getWorkflowState", { params: { workflowId } });
23229
23313
  const state = isRecordLike(raw) && isRecordLike(raw.data) ? raw.data : raw;
23230
23314
  const blocks = isRecordLike(state) && isRecordLike(state.blocks) ? Object.entries(state.blocks) : [];
23231
23315
  return blocks.map(([key, block]) => ({
@@ -23279,9 +23363,8 @@ function keyByTyped(payload, typedBy) {
23279
23363
  }
23280
23364
  return { ...payload, blockOutputs };
23281
23365
  }
23282
- async function readRunByName(runId, typed, command) {
23366
+ async function readRunByName(runId, typed, command, { client, profile }) {
23283
23367
  const flags = command.optsWithGlobals();
23284
- const { client, profile } = clientFrom(command);
23285
23368
  const operation = V2_OPERATIONS.getWorkflowRun;
23286
23369
  const spec = CLI_CONTRACT.getWorkflowRun ?? {};
23287
23370
  await buildRequest("getWorkflowRun", [runId], flags, profile.workspaceId);
@@ -23290,8 +23373,8 @@ async function readRunByName(runId, typed, command) {
23290
23373
  const request = await buildRequest("getWorkflowRun", [runId], { ...flags, selectOutput: selection.resolved }, profile.workspaceId);
23291
23374
  let result;
23292
23375
  try {
23293
- result = await client.request(request.path, {
23294
- method: operation.method,
23376
+ result = await client.request("getWorkflowRun", {
23377
+ params: request.params,
23295
23378
  headers: request.headers,
23296
23379
  query: request.query,
23297
23380
  body: request.body
@@ -23308,6 +23391,7 @@ function attachWorkflowRunGet(runs) {
23308
23391
  throw new Error("workflows runs get must be registered before block names can be attached to it");
23309
23392
  }
23310
23393
  const previous = held;
23394
+ const connectGet = callsOperations(get, ["getWorkflowRun", "getWorkflowState"]);
23311
23395
  get.action(async (runId, _options, command) => {
23312
23396
  const raw = command.optsWithGlobals().selectOutput;
23313
23397
  if (raw === undefined) {
@@ -23320,7 +23404,7 @@ function attachWorkflowRunGet(runs) {
23320
23404
  await previous(command.processedArgs);
23321
23405
  return;
23322
23406
  }
23323
- await readRunByName(runId, typed, command);
23407
+ await readRunByName(runId, typed, command, connectGet());
23324
23408
  });
23325
23409
  }
23326
23410
 
@@ -23402,18 +23486,18 @@ function runSpec() {
23402
23486
  return CLI_CONTRACT.getWorkflowRun ?? {};
23403
23487
  }
23404
23488
  function attachWorkflowRunWait(runs) {
23405
- 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) => {
23489
+ const [wait, connectWait] = apiCommand(runs, "wait", ["getWorkflowRun"]);
23490
+ 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) => {
23406
23491
  const timeoutSeconds = options.waitTimeout === undefined ? DEFAULT_WAIT_TIMEOUT_SECONDS : parseWaitTimeout(options.waitTimeout);
23407
- const { client, profile } = clientFrom(command);
23408
- const operation = V2_OPERATIONS.getWorkflowRun;
23409
- const path = resolvePath(operation.path, { workflowId: options.workflow, runId });
23492
+ const { client, profile } = connectWait();
23493
+ const params = { workflowId: options.workflow, runId };
23410
23494
  const startedAt = Date.now();
23411
23495
  const deadline = timeoutSeconds === 0 ? Number.POSITIVE_INFINITY : startedAt + timeoutSeconds * 1000;
23412
23496
  const progress = waitProgress();
23413
23497
  let delayMs = FIRST_POLL_DELAY_MS;
23414
23498
  try {
23415
23499
  while (true) {
23416
- const raw = await client.request(path, { method: operation.method });
23500
+ const raw = await client.request("getWorkflowRun", { params });
23417
23501
  const snapshot = readRun(raw);
23418
23502
  const outcome = classify(snapshot);
23419
23503
  if (outcome) {
@@ -24765,17 +24849,16 @@ async function readSecretValue(options) {
24765
24849
  return exitCli(CANCELLED_EXIT_CODE);
24766
24850
  }
24767
24851
  }
24768
- async function setSecret(name, options, command, redactionSpellings) {
24852
+ async function setSecret(name, options, connectSet, redactionSpellings) {
24769
24853
  if (redactionSpellings.size > 1) {
24770
24854
  throw new SimApiError("Pass either --unredacted or --no-unredacted, not both: they are one setting, and commander keeps only whichever came last.", 0);
24771
24855
  }
24772
24856
  const description = validateWorkspaceOnlyFlag("description", options.description, options.scope);
24773
24857
  const unredacted = validateWorkspaceOnlyFlag("unredacted", options.unredacted, options.scope);
24774
24858
  const value = await readSecretValue(options);
24775
- const { client, profile } = clientFrom(command);
24776
- const operation = V2_OPERATIONS.setSecret;
24777
- const response = await client.request(resolvePath(operation.path, { name }), {
24778
- method: operation.method,
24859
+ const { client, profile } = connectSet();
24860
+ const response = await client.request("setSecret", {
24861
+ params: { name },
24779
24862
  body: {
24780
24863
  workspaceId: client.requireWorkspace(),
24781
24864
  scope: options.scope,
@@ -24791,7 +24874,8 @@ function attachSecretCommands(program) {
24791
24874
  if (!secrets)
24792
24875
  throw new Error("The generated secrets command group is missing");
24793
24876
  const redactionSpellings = new Set;
24794
- 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));
24877
+ const [set, connectSet] = apiCommand(secrets, "set", ["setSecret"]);
24878
+ 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));
24795
24879
  }
24796
24880
 
24797
24881
  // src/telemetry/transport.ts
@@ -24852,13 +24936,6 @@ var FIRST_RUN_NOTICE = [
24852
24936
  ""
24853
24937
  ].join(`
24854
24938
  `);
24855
- function commandPath2(command) {
24856
- const names = [];
24857
- for (let current = command;current?.parent; current = current.parent) {
24858
- names.unshift(current.name());
24859
- }
24860
- return names;
24861
- }
24862
24939
  function typedFlags(command) {
24863
24940
  const flags = new Set;
24864
24941
  for (let current = command;current; current = current.parent) {
@@ -24967,7 +25044,7 @@ function createCommandTelemetry(options = {}) {
24967
25044
  return {
24968
25045
  observe(program) {
24969
25046
  program.hook("preAction", (_root, action) => {
24970
- const path = commandPath2(action);
25047
+ const path = commandPath(action);
24971
25048
  if (path[0] === EXCLUDED_ROOT_COMMAND || !isReportable({}))
24972
25049
  return;
24973
25050
  const state = loadTelemetryState();
@@ -25145,7 +25222,7 @@ function explainFailure(error, program) {
25145
25222
  if (error instanceof SimApiError) {
25146
25223
  let output = program.opts().output;
25147
25224
  try {
25148
- output = clientFrom(program).profile.output;
25225
+ output = profileFrom(program).output;
25149
25226
  } catch {}
25150
25227
  if (output === "json" || output === "yaml") {
25151
25228
  const payload = {