@uru-intelligence/cli 0.5.1 → 0.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/uru.mjs CHANGED
@@ -993,16 +993,11 @@ var RETIRED_FROZEN_GEM_DATASET_TOOL_NAMES = Object.freeze([
993
993
  "UPDATE_DATASET",
994
994
  "DATASET_UPDATE",
995
995
  "LIST_DATASET_ROWS",
996
- "DATASET_QUERY",
997
996
  "GET_DATASET",
998
- "DATASET_GET",
999
997
  "UPSERT_DATASET_ROWS",
1000
998
  "DELETE_DATASET_ROWS",
1001
999
  "RESTORE_DATASET_ROWS",
1002
- "DATASET_ROWS",
1003
- "DATASET_SQL",
1004
- "DATASET_SQL_READ",
1005
- "DATASET_SQL_WRITE"
1000
+ "DATASET_SQL_READ"
1006
1001
  ]);
1007
1002
  var DATASET_TOOL_NAMES = new Map([
1008
1003
  ["CREATE_DATASET", "dataset_manage"],
@@ -1010,15 +1005,11 @@ var DATASET_TOOL_NAMES = new Map([
1010
1005
  ["UPDATE_DATASET", "dataset_manage"],
1011
1006
  ["DATASET_UPDATE", "dataset_manage"],
1012
1007
  ["LIST_DATASET_ROWS", "dataset_query"],
1013
- ["DATASET_QUERY", "dataset_query"],
1014
1008
  ["GET_DATASET", "dataset_get"],
1015
- ["DATASET_GET", "dataset_get"],
1016
1009
  ["UPSERT_DATASET_ROWS", "dataset_rows"],
1017
1010
  ["DELETE_DATASET_ROWS", "dataset_rows"],
1018
1011
  ["RESTORE_DATASET_ROWS", "dataset_rows"],
1019
- ["DATASET_ROWS", "dataset_rows"],
1020
- ["DATASET_SQL_READ", "dataset_sql"],
1021
- ["DATASET_SQL_WRITE", "dataset_sql_write"]
1012
+ ["DATASET_SQL_READ", "dataset_sql"]
1022
1013
  ]);
1023
1014
  var DATASET_ROW_OPERATIONS = new Map([
1024
1015
  ["UPSERT_DATASET_ROWS", "upsert"],
@@ -3061,7 +3052,7 @@ function spec(id, summary, auth, workspace, safety, outputModes, cancellation =
3061
3052
  // package.json
3062
3053
  var package_default = {
3063
3054
  name: "@uru-intelligence/cli",
3064
- version: "0.5.1",
3055
+ version: "0.5.3",
3065
3056
  private: false,
3066
3057
  description: "Uru full-platform command line interface",
3067
3058
  repository: {
@@ -3141,6 +3132,9 @@ class CliError extends Error {
3141
3132
  suggestedCommand;
3142
3133
  errorId;
3143
3134
  httpStatus;
3135
+ retryable;
3136
+ tip;
3137
+ details;
3144
3138
  constructor(message, options = {}) {
3145
3139
  super(message, options.cause === undefined ? undefined : { cause: options.cause });
3146
3140
  this.name = "CliError";
@@ -3158,8 +3152,32 @@ class CliError extends Error {
3158
3152
  if (options.httpStatus !== undefined) {
3159
3153
  this.httpStatus = options.httpStatus;
3160
3154
  }
3155
+ if (options.retryable === true) {
3156
+ this.retryable = true;
3157
+ }
3158
+ if (options.tip !== undefined) {
3159
+ this.tip = options.tip;
3160
+ }
3161
+ if (options.details !== undefined) {
3162
+ this.details = options.details;
3163
+ }
3161
3164
  }
3162
3165
  }
3166
+ function refineCliError(error, refinement) {
3167
+ const tip = refinement.tip ?? error.tip;
3168
+ return new CliError(refinement.message ?? error.message, {
3169
+ code: error.exitCode,
3170
+ errorCode: error.errorCode,
3171
+ cause: error,
3172
+ ...error.errorId === undefined ? {} : { errorId: error.errorId },
3173
+ ...error.httpStatus === undefined ? {} : { httpStatus: error.httpStatus },
3174
+ ...error.confirmationRequired === true ? { confirmationRequired: true } : {},
3175
+ ...error.suggestedCommand === undefined ? {} : { suggestedCommand: error.suggestedCommand },
3176
+ ...error.retryable === true ? { retryable: true } : {},
3177
+ ...error.details === undefined ? {} : { details: error.details },
3178
+ ...tip === undefined ? {} : { tip }
3179
+ });
3180
+ }
3163
3181
  function defaultCliErrorCode(exitCode) {
3164
3182
  switch (exitCode) {
3165
3183
  case ExitCode.Cancelled:
@@ -3310,7 +3328,83 @@ function applyValueFlag(flags, flag, value) {
3310
3328
 
3311
3329
  // src/auth-commands.ts
3312
3330
  import { readFile } from "node:fs/promises";
3331
+
3332
+ // src/oauth-callback.ts
3313
3333
  import { createServer } from "node:http";
3334
+ var OAUTH_CALLBACK_PATH = "/oauth/callback";
3335
+ async function listenForOAuthCallback(args) {
3336
+ args.signal.throwIfAborted();
3337
+ const server = createServer();
3338
+ const completion = Promise.withResolvers();
3339
+ completion.promise.catch(() => {
3340
+ return;
3341
+ });
3342
+ let settled = false;
3343
+ const close = () => {
3344
+ clearTimeout(timeout);
3345
+ args.signal.removeEventListener("abort", cancel);
3346
+ server.close();
3347
+ server.closeAllConnections();
3348
+ };
3349
+ const fail = (error) => {
3350
+ if (settled)
3351
+ return;
3352
+ settled = true;
3353
+ close();
3354
+ completion.reject(error);
3355
+ };
3356
+ const cancel = () => fail(new CliError("Cancelled.", { code: ExitCode.Cancelled }));
3357
+ const timeout = setTimeout(() => fail(new CliError("OAuth login timed out waiting for browser callback.", { code: ExitCode.AuthRequired, errorCode: "oauth_callback_timeout" })), 5 * 60 * 1000);
3358
+ args.signal.addEventListener("abort", cancel, { once: true });
3359
+ server.on("request", (request, response) => {
3360
+ const url = new URL(request.url ?? "/", `http://${args.host}`);
3361
+ response.setHeader("Cache-Control", "no-store");
3362
+ if (request.method !== "GET" || url.pathname !== OAUTH_CALLBACK_PATH) {
3363
+ response.writeHead(404).end("Not found");
3364
+ return;
3365
+ }
3366
+ if (url.searchParams.get("state") !== args.state || !url.searchParams.has("code") && !url.searchParams.has("error")) {
3367
+ response.writeHead(400).end("Invalid sign-in response. Return to the sign-in window.");
3368
+ return;
3369
+ }
3370
+ response.setHeader("content-type", "text/html; charset=utf-8");
3371
+ response.end('<!doctype html><meta charset="utf-8"><title>Uru CLI sign-in</title><h1>Sign-in response received</h1><p>Return to your terminal to check whether sign-in completed. You can close this window.</p>');
3372
+ if (!settled) {
3373
+ settled = true;
3374
+ clearTimeout(timeout);
3375
+ args.signal.removeEventListener("abort", cancel);
3376
+ server.close();
3377
+ completion.resolve(url.toString());
3378
+ }
3379
+ });
3380
+ server.on("error", (cause) => fail(new CliError("Could not start OAuth callback server.", {
3381
+ code: ExitCode.AuthRequired,
3382
+ errorCode: "oauth_callback_server_failed",
3383
+ cause
3384
+ })));
3385
+ try {
3386
+ await new Promise((resolve, reject) => {
3387
+ server.once("error", reject);
3388
+ server.listen(args.port, args.host, resolve);
3389
+ });
3390
+ args.signal.throwIfAborted();
3391
+ const address = server.address();
3392
+ if (address === null || typeof address === "string") {
3393
+ throw new CliError("Could not determine OAuth callback port.");
3394
+ }
3395
+ return { port: address.port, result: completion.promise, close };
3396
+ } catch (cause) {
3397
+ close();
3398
+ if (args.signal.aborted) {
3399
+ throw new CliError("Cancelled.", { code: ExitCode.Cancelled });
3400
+ }
3401
+ throw new CliError("Could not start OAuth callback server.", {
3402
+ code: ExitCode.AuthRequired,
3403
+ errorCode: "oauth_callback_server_failed",
3404
+ cause
3405
+ });
3406
+ }
3407
+ }
3314
3408
 
3315
3409
  // ../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/core/core.js
3316
3410
  var _a;
@@ -9728,7 +9822,7 @@ var zArtifactProjectFileUpdateRequest = object({
9728
9822
  content: string2().nullish(),
9729
9823
  contentBase64: string2().nullish(),
9730
9824
  createIfMissing: boolean2().optional().default(false),
9731
- path: string2().min(1).max(1024)
9825
+ path: string2().min(1).max(240)
9732
9826
  });
9733
9827
  var zArtifactRenderEventRequest = object({
9734
9828
  dependencyNames: array(string2()).nullish(),
@@ -14563,17 +14657,17 @@ var zThreadFileView = object({
14563
14657
  "quarantined",
14564
14658
  "failed"
14565
14659
  ]),
14566
- bytes: int().nullish(),
14660
+ bytes: int().nullable(),
14567
14661
  createdAtMs: int(),
14568
14662
  fileId: uuid2(),
14569
14663
  filename: string2(),
14570
14664
  folder: _enum(["uploads", "outputs"]),
14571
14665
  kind: _enum(["file", "image", "audio", "video"]),
14572
- mime: string2().nullish(),
14666
+ mime: string2().nullable(),
14573
14667
  modelAccess: _enum(["direct", "sandbox_only"]),
14574
14668
  previewUrl: string2().nullable(),
14575
14669
  threadId: uuid2(),
14576
- url: string2().nullish()
14670
+ url: string2().nullable()
14577
14671
  });
14578
14672
  var zThreadFileListResponse = object({
14579
14673
  files: array(zThreadFileView),
@@ -14933,10 +15027,7 @@ var zThreadShareLink = object({
14933
15027
  snapshotLeafMessageId: string2().nullable(),
14934
15028
  threadId: string2()
14935
15029
  });
14936
- var zThreadShareListResponse = object({
14937
- links: array(zThreadShareLink)
14938
- });
14939
- var zThreadShareMintResponse = object({
15030
+ var zThreadShareEnsureResponse = object({
14940
15031
  link: zThreadShareLink,
14941
15032
  token: string2(),
14942
15033
  url: string2().nullable()
@@ -15282,6 +15373,8 @@ var zThreadMessagesListResponse = object({
15282
15373
  siblings: record(string2(), array(string2()))
15283
15374
  });
15284
15375
  var zThreadShareSnapshot = object({
15376
+ files: array(zThreadFileView),
15377
+ generatedAt: string2(),
15285
15378
  messages: array(zThreadExportMessage),
15286
15379
  schema: _enum(["uru.thread-share"]),
15287
15380
  sharedAt: string2(),
@@ -16323,7 +16416,9 @@ var zGetUserDetailApiAdminUsageUsersUserIdGetResponse = record(string2(), unknow
16323
16416
  var zAdminListUsersApiAdminUsersGetQuery = object({
16324
16417
  limit: int().gte(1).lte(100).optional().default(50),
16325
16418
  offset: int().gte(0).nullish().default(0),
16326
- search: string2().max(200).optional()
16419
+ search: string2().max(200).optional(),
16420
+ status: _enum(["active", "deactivated"]).optional(),
16421
+ workspaces: _enum(["one", "many"]).optional()
16327
16422
  });
16328
16423
  var zAdminGetUserApiAdminUsersUserIdGetPath = object({
16329
16424
  userId: string2()
@@ -17537,6 +17632,7 @@ var zAuthorizeRequestApiOauthAuthorizeRequestGetQuery = object({
17537
17632
  var zAuthorizeRequestApiOauthAuthorizeRequestGetResponse = object({
17538
17633
  client_id: string2(),
17539
17634
  client_name: string2(),
17635
+ redirectUri: url(),
17540
17636
  resource: url(),
17541
17637
  scope: string2(),
17542
17638
  workspace_id: string2().nullable(),
@@ -17886,7 +17982,7 @@ var zGetArtifactProjectFileContentApiPlatformArtifactsArtifactSlugProjectFilesCo
17886
17982
  artifactSlug: string2()
17887
17983
  });
17888
17984
  var zGetArtifactProjectFileContentApiPlatformArtifactsArtifactSlugProjectFilesContentGetQuery = object({
17889
- path: string2().min(1).max(1024)
17985
+ path: string2().min(1).max(240)
17890
17986
  });
17891
17987
  var zGetArtifactProjectFileContentApiPlatformArtifactsArtifactSlugProjectFilesContentGetResponse = object({
17892
17988
  artifactId: string2(),
@@ -19196,6 +19292,7 @@ var zDatasetListRowsResponse = object({
19196
19292
  limit: int(),
19197
19293
  nextCursor: string2().nullish(),
19198
19294
  offset: int(),
19295
+ revision: string2().regex(/^(0|[1-9][0-9]{0,19})$/).optional(),
19199
19296
  rows: array(object({
19200
19297
  createdAt: string2().optional(),
19201
19298
  deleted: boolean2().optional(),
@@ -19220,6 +19317,7 @@ var zDatasetListRowsResponse = object({
19220
19317
  total: int().nullable()
19221
19318
  });
19222
19319
  var zDatasetUpsertRowsBody = object({
19320
+ expectedDatasetRevision: string2().regex(/^(0|[1-9][0-9]{0,19})$/).optional(),
19223
19321
  idempotencyKey: string2().min(1).max(128).optional(),
19224
19322
  rows: array(record(string2(), union([
19225
19323
  string2(),
@@ -19244,6 +19342,8 @@ var zDatasetUpsertRowsResponse = object({
19244
19342
  updatedIds: array(string2().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/))
19245
19343
  });
19246
19344
  var zDatasetDeleteRowsBody = object({
19345
+ expectedDatasetRevision: string2().regex(/^(0|[1-9][0-9]{0,19})$/).optional(),
19346
+ idempotencyKey: string2().min(1).max(128).optional(),
19247
19347
  rowIds: array(string2().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/)).max(1000).optional().default([])
19248
19348
  });
19249
19349
  var zDatasetDeleteRowsPath = object({
@@ -19321,6 +19421,8 @@ var zDatasetSubmitRowsMutationResponse = object({
19321
19421
  ])
19322
19422
  });
19323
19423
  var zDatasetRestoreRowsBody = object({
19424
+ expectedDatasetRevision: string2().regex(/^(0|[1-9][0-9]{0,19})$/).optional(),
19425
+ idempotencyKey: string2().min(1).max(128).optional(),
19324
19426
  rowIds: array(string2().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/)).max(1000).optional().default([])
19325
19427
  });
19326
19428
  var zDatasetRestoreRowsPath = object({
@@ -20588,10 +20690,7 @@ var zThreadSandboxListPath = object({
20588
20690
  var zThreadSandboxListQuery = object({
20589
20691
  path: string2().max(512).optional()
20590
20692
  });
20591
- var zThreadShareListPath = object({
20592
- threadId: uuid2()
20593
- });
20594
- var zThreadShareMintPath = object({
20693
+ var zThreadShareEnsurePath = object({
20595
20694
  threadId: uuid2()
20596
20695
  });
20597
20696
  var zThreadShareRevokePath = object({
@@ -21216,6 +21315,9 @@ function toolTransportError(body, requestBody) {
21216
21315
  const structured = {
21217
21316
  ...error2.errorCode === undefined ? {} : { errorCode: error2.errorCode },
21218
21317
  ...error2.errorId === undefined ? {} : { errorId: error2.errorId },
21318
+ ...error2.details === undefined ? {} : { details: error2.details },
21319
+ ...error2.tip === undefined ? {} : { tip: error2.tip },
21320
+ ...isTransientFailure(status, body) ? { retryable: true } : {},
21219
21321
  httpStatus: status
21220
21322
  };
21221
21323
  if (status === 409) {
@@ -21447,13 +21549,28 @@ function apiError(status, payload, requestBody) {
21447
21549
  "error_code"
21448
21550
  ]);
21449
21551
  const errorId = pickStringFromJsonValue(envelope, ["errorId", "error_id"]);
21552
+ const serverDetails = isRecord(envelope) ? envelope["details"] : undefined;
21553
+ const tip = serverTip(envelope);
21450
21554
  return new CliError(message, {
21555
+ ...tip === undefined ? {} : { tip: stripTerminalControl(redactValues(tip, redactions)) },
21451
21556
  code: status === 401 ? ExitCode.AuthRequired : ExitCode.Failure,
21452
21557
  errorCode: backendCode ?? (status === 401 ? "auth_required" : status === 403 ? "permission_denied" : "api_request_failed"),
21453
21558
  httpStatus: status,
21454
- ...errorId === undefined ? {} : { errorId }
21559
+ ...errorId === undefined ? {} : { errorId },
21560
+ ...isTransientFailure(status, payload) ? { retryable: true } : {},
21561
+ ...serverDetails !== undefined && isJsonObject(serverDetails) ? { details: serverDetails } : {}
21455
21562
  });
21456
21563
  }
21564
+ function isTransientFailure(status, payload) {
21565
+ if (status === 429 || status === 503) {
21566
+ return true;
21567
+ }
21568
+ if (!isRecord(payload)) {
21569
+ return false;
21570
+ }
21571
+ const nested = payload["error"];
21572
+ return payload["retryable"] === true || isRecord(nested) && nested["retryable"] === true;
21573
+ }
21457
21574
  function pickStringFromJsonValue(value, keys) {
21458
21575
  return isRecord(value) ? pickString(value, keys) : undefined;
21459
21576
  }
@@ -21491,16 +21608,23 @@ function errorDetails(payload) {
21491
21608
  if (code !== undefined) {
21492
21609
  details.push(`Code: ${code}`);
21493
21610
  }
21494
- const tip = pickString(payload, ["tip"]);
21495
- if (tip !== undefined) {
21496
- details.push(`Tip: ${tip}`);
21497
- }
21498
21611
  const nested = payload["details"];
21499
21612
  if (isJsonObject(nested)) {
21500
21613
  details.push(...errorDetails(nested));
21501
21614
  }
21502
21615
  return [...new Set(details)];
21503
21616
  }
21617
+ function serverTip(payload) {
21618
+ if (!isRecord(payload)) {
21619
+ return;
21620
+ }
21621
+ const tip = pickString(payload, ["tip"]);
21622
+ if (tip !== undefined) {
21623
+ return tip;
21624
+ }
21625
+ const nested = payload["details"];
21626
+ return isJsonObject(nested) ? serverTip(nested) : undefined;
21627
+ }
21504
21628
  function collectSensitiveValues(value) {
21505
21629
  if (value === undefined || value === null) {
21506
21630
  return [];
@@ -21578,6 +21702,7 @@ function normalizeTool(value) {
21578
21702
 
21579
21703
  // src/oauth.ts
21580
21704
  import { createHash, randomBytes } from "node:crypto";
21705
+ import { setTimeout as sleepTimer } from "node:timers/promises";
21581
21706
  var DEFAULT_PKCE_VERIFIER_BYTES = 32;
21582
21707
  var DEFAULT_STATE_BYTES = 24;
21583
21708
  var OAUTH_DEVICE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
@@ -21625,7 +21750,7 @@ function buildAuthorizationUrl(args) {
21625
21750
  }
21626
21751
  return url2.toString();
21627
21752
  }
21628
- function parseOAuthCallbackUrl(callbackUrl, expectedState) {
21753
+ function parseOAuthCallbackUrl(callbackUrl, expectedState, expectedIssuer, issuerRequired = false) {
21629
21754
  const url2 = new URL(callbackUrl);
21630
21755
  const state = url2.searchParams.get("state") ?? "";
21631
21756
  if (state === "" || state !== expectedState) {
@@ -21634,6 +21759,13 @@ function parseOAuthCallbackUrl(callbackUrl, expectedState) {
21634
21759
  errorCode: "oauth_state_mismatch"
21635
21760
  });
21636
21761
  }
21762
+ const issuers = url2.searchParams.getAll("iss");
21763
+ if (issuerRequired && issuers.length === 0 || issuers.length > 1 || issuers.length === 1 && issuers[0] !== expectedIssuer) {
21764
+ throw new CliError("OAuth callback issuer did not match the sign-in server.", {
21765
+ code: ExitCode.AuthRequired,
21766
+ errorCode: "oauth_issuer_mismatch"
21767
+ });
21768
+ }
21637
21769
  const error2 = url2.searchParams.get("error");
21638
21770
  if (error2 !== null && error2 !== "") {
21639
21771
  throw new CliError("OAuth authorization failed. Start sign-in again and approve access.", { code: ExitCode.AuthRequired, errorCode: "oauth_authorization_failed" });
@@ -21670,6 +21802,24 @@ async function resolveOAuthClientMetadata(args) {
21670
21802
  scope: optionalStringField(response, "scope") ?? "mcp offline_access"
21671
21803
  };
21672
21804
  }
21805
+ async function discoverOAuthIssuer(args) {
21806
+ const expectedIssuer = normalizeApiUrl(args.apiUrl);
21807
+ const metadata = await fetchOAuthGet({
21808
+ apiUrl: args.apiUrl,
21809
+ path: "/.well-known/oauth-authorization-server",
21810
+ ...args.fetch === undefined ? {} : { fetch: args.fetch }
21811
+ });
21812
+ if (!isRecord(metadata) || metadata["issuer"] !== expectedIssuer) {
21813
+ throw new CliError("OAuth discovery issuer did not match the sign-in server.", {
21814
+ code: ExitCode.AuthRequired,
21815
+ errorCode: "oauth_issuer_mismatch"
21816
+ });
21817
+ }
21818
+ return {
21819
+ issuer: expectedIssuer,
21820
+ issuerRequired: metadata["authorization_response_iss_parameter_supported"] === true
21821
+ };
21822
+ }
21673
21823
  async function discoverOAuthResource(args) {
21674
21824
  const response = await fetchOAuthGet({
21675
21825
  apiUrl: args.apiUrl,
@@ -21759,8 +21909,9 @@ async function startDeviceAuthorization(args) {
21759
21909
  }
21760
21910
  async function pollDeviceToken(args) {
21761
21911
  let intervalSeconds = Math.max(1, args.intervalSeconds);
21762
- const sleep = args.sleep ?? defaultSleep;
21912
+ const sleep = args.sleep ?? ((milliseconds) => sleepTimer(milliseconds, undefined, { signal: args.signal }));
21763
21913
  for (let attempt = 0;attempt < args.maxPolls; attempt += 1) {
21914
+ args.signal?.throwIfAborted();
21764
21915
  if (attempt > 0) {
21765
21916
  await sleep(intervalSeconds * 1000);
21766
21917
  }
@@ -21789,6 +21940,7 @@ async function pollDeviceToken(args) {
21789
21940
  errorCode: "oauth_device_failed"
21790
21941
  });
21791
21942
  }
21943
+ args.signal?.throwIfAborted();
21792
21944
  return toOAuthTokenResponse(zOAuthTokenResponse.parse(response));
21793
21945
  }
21794
21946
  throw new CliError("OAuth device login timed out before authorization completed.", {
@@ -21800,6 +21952,7 @@ async function fetchOAuthJson(args) {
21800
21952
  const fetchImpl = args.fetch ?? fetch;
21801
21953
  const response = await fetchImpl(oauthEndpoint(args.apiUrl, args.path), {
21802
21954
  method: "POST",
21955
+ signal: AbortSignal.timeout(30000),
21803
21956
  headers: {
21804
21957
  Accept: "application/json",
21805
21958
  "Content-Type": "application/json",
@@ -21820,6 +21973,7 @@ async function fetchOAuthGet(args) {
21820
21973
  const fetchImpl = args.fetch ?? fetch;
21821
21974
  const response = await fetchImpl(oauthEndpoint(args.apiUrl, args.path), {
21822
21975
  method: "GET",
21976
+ signal: AbortSignal.timeout(30000),
21823
21977
  headers: { Accept: "application/json" }
21824
21978
  });
21825
21979
  const payload = parseJsonResponse(await response.text());
@@ -21838,6 +21992,7 @@ async function fetchOAuthForm(args) {
21838
21992
  const fetchImpl = args.fetch ?? fetch;
21839
21993
  const response = await fetchImpl(oauthEndpoint(args.apiUrl, args.path), {
21840
21994
  method: "POST",
21995
+ signal: AbortSignal.timeout(30000),
21841
21996
  headers: {
21842
21997
  Accept: "application/json",
21843
21998
  "Content-Type": "application/x-www-form-urlencoded"
@@ -21985,9 +22140,6 @@ function errorMessage2(payload) {
21985
22140
  return;
21986
22141
  }
21987
22142
  }
21988
- function defaultSleep(milliseconds) {
21989
- return new Promise((resolve) => setTimeout(resolve, milliseconds));
21990
- }
21991
22143
 
21992
22144
  // src/visual.ts
21993
22145
  var PLAIN_VISUAL = { rich: false, width: 80 };
@@ -22349,6 +22501,7 @@ No generated CLI operations are registered for family ${family}.
22349
22501
  Generated ${family} operations:
22350
22502
  ${operations}
22351
22503
 
22504
+ Send the fields exactly as \`uru ${command} <operation> --get-schema\` prints them.
22352
22505
  Run \`uru operations run <operation-id> --params-json|--args-json '{...}'\` for the fully
22353
22506
  qualified operation form.
22354
22507
  `;
@@ -22866,8 +23019,6 @@ function objectPayload(value) {
22866
23019
  }
22867
23020
 
22868
23021
  // src/auth-commands.ts
22869
- var OAUTH_CALLBACK_PATH = "/oauth/callback";
22870
- var OAUTH_CALLBACK_TIMEOUT_MS = 5 * 60 * 1000;
22871
23022
  var DEVICE_MAX_POLLS = 120;
22872
23023
  var CIMD_CALLBACK_PORT = 8765;
22873
23024
  async function resolveStoredToken(options) {
@@ -23046,7 +23197,7 @@ async function validateSessionToken(ctx, token) {
23046
23197
  apiUrl: ctx.apiUrl,
23047
23198
  token,
23048
23199
  ...workspaceId === undefined ? {} : { workspaceId },
23049
- ...ctx.fetch !== undefined ? { fetch: ctx.fetch } : {}
23200
+ fetch: loginFetch(ctx)
23050
23201
  });
23051
23202
  return loginClient.validateToken();
23052
23203
  }
@@ -23081,7 +23232,7 @@ function canCompleteBrowserLogin(ctx) {
23081
23232
  async function loginWithDeviceCode(ctx) {
23082
23233
  const resource = await discoverOAuthResource({
23083
23234
  apiUrl: ctx.apiUrl,
23084
- ...ctx.fetch === undefined ? {} : { fetch: ctx.fetch }
23235
+ fetch: loginFetch(ctx)
23085
23236
  });
23086
23237
  const clientMetadata = await resolveOAuthClientMetadata({
23087
23238
  apiUrl: ctx.apiUrl,
@@ -23090,14 +23241,14 @@ async function loginWithDeviceCode(ctx) {
23090
23241
  port: CIMD_CALLBACK_PORT,
23091
23242
  path: OAUTH_CALLBACK_PATH
23092
23243
  }),
23093
- ...ctx.fetch !== undefined ? { fetch: ctx.fetch } : {}
23244
+ fetch: loginFetch(ctx)
23094
23245
  });
23095
23246
  const authorization = await startDeviceAuthorization({
23096
23247
  apiUrl: ctx.apiUrl,
23097
23248
  clientId: clientMetadata.clientId,
23098
23249
  scope: clientMetadata.scope,
23099
23250
  resource,
23100
- ...ctx.fetch !== undefined ? { fetch: ctx.fetch } : {}
23251
+ fetch: loginFetch(ctx)
23101
23252
  });
23102
23253
  const complete = authorization.verificationUriComplete ?? authorization.verificationUri;
23103
23254
  await maybeCopyLoginUrl(ctx, complete);
@@ -23110,8 +23261,9 @@ async function loginWithDeviceCode(ctx) {
23110
23261
  clientId: clientMetadata.clientId,
23111
23262
  deviceCode: authorization.deviceCode,
23112
23263
  intervalSeconds: authorization.interval,
23264
+ signal: ctx.abortSignal,
23113
23265
  maxPolls: Math.min(DEVICE_MAX_POLLS, Math.ceil(authorization.expiresIn / Math.max(1, authorization.interval))),
23114
- ...ctx.fetch !== undefined ? { fetch: ctx.fetch } : {}
23266
+ fetch: loginFetch(ctx)
23115
23267
  });
23116
23268
  return exchangeOAuthTokenForSession(ctx, token, clientMetadata.clientId, resource);
23117
23269
  }
@@ -23120,14 +23272,17 @@ async function loginWithBrowser(ctx) {
23120
23272
  if (ctx.callbackPort !== undefined && ctx.callbackPort !== CIMD_CALLBACK_PORT) {
23121
23273
  throw new CliError(`Uru CLI requires callback port ${CIMD_CALLBACK_PORT} for OAuth Client ID Metadata.`);
23122
23274
  }
23123
- const callback = await waitForOAuthCallback({
23275
+ const state = generateOAuthState();
23276
+ const callback = await listenForOAuthCallback({
23124
23277
  host: callbackHost,
23125
- port: CIMD_CALLBACK_PORT
23278
+ port: CIMD_CALLBACK_PORT,
23279
+ state,
23280
+ signal: ctx.abortSignal
23126
23281
  });
23127
23282
  try {
23128
23283
  const resource = await discoverOAuthResource({
23129
23284
  apiUrl: ctx.apiUrl,
23130
- ...ctx.fetch === undefined ? {} : { fetch: ctx.fetch }
23285
+ fetch: loginFetch(ctx)
23131
23286
  });
23132
23287
  const redirectUri = buildLoopbackRedirectUri({
23133
23288
  host: callbackHost,
@@ -23137,10 +23292,10 @@ async function loginWithBrowser(ctx) {
23137
23292
  const clientMetadata = await resolveOAuthClientMetadata({
23138
23293
  apiUrl: ctx.apiUrl,
23139
23294
  redirectUri,
23140
- ...ctx.fetch !== undefined ? { fetch: ctx.fetch } : {}
23295
+ fetch: loginFetch(ctx)
23141
23296
  });
23297
+ const issuer = await discoverOAuthIssuer({ apiUrl: ctx.apiUrl, fetch: loginFetch(ctx) });
23142
23298
  const pkce = generatePkcePair();
23143
- const state = generateOAuthState();
23144
23299
  const authorizationUrl = buildAuthorizationUrl({
23145
23300
  authorizationEndpoint: `${normalizeApiUrl(ctx.apiUrl)}/oauth/authorize`,
23146
23301
  clientId: clientMetadata.clientId,
@@ -23160,7 +23315,7 @@ async function loginWithBrowser(ctx) {
23160
23315
  `);
23161
23316
  }
23162
23317
  const callbackUrl = await callback.result;
23163
- const authorization = parseOAuthCallbackUrl(callbackUrl, state);
23318
+ const authorization = parseOAuthCallbackUrl(callbackUrl, state, issuer.issuer, issuer.issuerRequired);
23164
23319
  const token = await exchangeAuthorizationCode({
23165
23320
  apiUrl: ctx.apiUrl,
23166
23321
  clientId: clientMetadata.clientId,
@@ -23168,7 +23323,7 @@ async function loginWithBrowser(ctx) {
23168
23323
  redirectUri,
23169
23324
  codeVerifier: pkce.verifier,
23170
23325
  resource,
23171
- ...ctx.fetch !== undefined ? { fetch: ctx.fetch } : {}
23326
+ fetch: loginFetch(ctx)
23172
23327
  });
23173
23328
  return exchangeOAuthTokenForSession(ctx, token, clientMetadata.clientId, resource);
23174
23329
  } finally {
@@ -23181,7 +23336,7 @@ async function exchangeOAuthTokenForSession(ctx, token, clientId, resource) {
23181
23336
  apiUrl: ctx.apiUrl,
23182
23337
  oauthAccessToken: token.accessToken,
23183
23338
  ...ctx.workspace !== undefined ? { workspaceId: ctx.workspace } : {},
23184
- ...ctx.fetch !== undefined ? { fetch: ctx.fetch } : {}
23339
+ fetch: loginFetch(ctx)
23185
23340
  });
23186
23341
  if (session.oauthResource !== resource) {
23187
23342
  throw new CliError("CLI session OAuth resource did not match discovery.", {
@@ -23270,61 +23425,14 @@ async function maybeCopyLoginUrl(ctx, url2) {
23270
23425
  ctx.io.stderr.write(`Copied login URL to clipboard.
23271
23426
  `);
23272
23427
  }
23273
- async function waitForOAuthCallback(args) {
23274
- const server = createServer();
23275
- const result = new Promise((resolve, reject) => {
23276
- const timeout = setTimeout(() => {
23277
- server.close();
23278
- reject(new CliError("OAuth login timed out waiting for browser callback.", {
23279
- code: ExitCode.AuthRequired,
23280
- errorCode: "oauth_callback_timeout"
23281
- }));
23282
- }, OAUTH_CALLBACK_TIMEOUT_MS);
23283
- server.on("request", (request, response) => {
23284
- handleOAuthCallbackRequest(request, response, {
23285
- host: args.host,
23286
- onComplete: (callbackUrl) => {
23287
- clearTimeout(timeout);
23288
- server.close();
23289
- resolve(callbackUrl);
23290
- }
23291
- });
23292
- });
23293
- server.on("error", (error2) => {
23294
- clearTimeout(timeout);
23295
- reject(new CliError("Could not start OAuth callback server.", {
23296
- code: ExitCode.AuthRequired,
23297
- errorCode: "oauth_callback_server_failed",
23298
- cause: error2
23299
- }));
23300
- });
23301
- });
23302
- await new Promise((resolve, reject) => {
23303
- server.listen(args.port ?? 0, args.host, resolve);
23304
- server.once("error", reject);
23428
+ function loginFetch(ctx) {
23429
+ return (input, init) => (ctx.fetch ?? fetch)(input, {
23430
+ ...init,
23431
+ signal: AbortSignal.any([
23432
+ ctx.abortSignal,
23433
+ init?.signal ?? AbortSignal.timeout(30000)
23434
+ ])
23305
23435
  });
23306
- const address = server.address();
23307
- if (address === null || typeof address === "string") {
23308
- server.close();
23309
- throw new CliError("Could not determine OAuth callback port.", {
23310
- code: ExitCode.AuthRequired,
23311
- errorCode: "oauth_callback_server_failed"
23312
- });
23313
- }
23314
- return { port: address.port, result, close: () => server.close() };
23315
- }
23316
- function handleOAuthCallbackRequest(request, response, args) {
23317
- const requestUrl = request.url ?? "/";
23318
- const parsed = new URL(requestUrl, `http://${args.host}`);
23319
- if (parsed.pathname !== OAUTH_CALLBACK_PATH) {
23320
- response.statusCode = 404;
23321
- response.end("Not found");
23322
- return;
23323
- }
23324
- response.statusCode = 200;
23325
- response.setHeader("content-type", "text/html; charset=utf-8");
23326
- response.end('<!doctype html><meta charset="utf-8"><title>Uru CLI login</title><body><h1>Uru CLI login complete</h1><p>You can close this window and return to your terminal.</p></body>');
23327
- args.onComplete(`http://${args.host}${requestUrl}`);
23328
23436
  }
23329
23437
 
23330
23438
  // src/cli-helpers.ts
@@ -23593,6 +23701,103 @@ function nonEmptyString(value) {
23593
23701
 
23594
23702
  // src/cli-runtime.ts
23595
23703
  import { dirname } from "node:path";
23704
+
23705
+ // src/tool-failure-guidance.ts
23706
+ async function explainToolFailure(input) {
23707
+ const { error: error2, operation, params } = input;
23708
+ if (error2.errorCode === "invalid_tool_arguments") {
23709
+ const lines = invalidArgumentLines(operation, params, error2.details, await input.loadInputSchema());
23710
+ return refineCliError(error2, {
23711
+ ...lines.length === 0 ? {} : { message: `${error2.message} ${lines.join(" ")}` },
23712
+ tip: `Run \`uru operations inspect ${operation.id}\` to read this operation's exact input schema, then send its field names unchanged.`
23713
+ });
23714
+ }
23715
+ if (error2.retryable === true) {
23716
+ return error2.tip === undefined ? refineCliError(error2, { tip: retryTip(operation, params) }) : error2;
23717
+ }
23718
+ return error2;
23719
+ }
23720
+ function retryTip(operation, params) {
23721
+ if (operation.safety === "read") {
23722
+ return "This failure is temporary. This operation only reads, so it is safe to run the same command again. Wait a few seconds first.";
23723
+ }
23724
+ const key = params["idempotency_key"];
23725
+ if (typeof key === "string" && key !== "") {
23726
+ return `This failure is temporary. Run the same command again with the same idempotency_key (${JSON.stringify(key)}): the server uses the key to apply the change only once, so the retry cannot apply it twice.`;
23727
+ }
23728
+ return `This failure is temporary. The change may already have applied. This write carried no idempotency_key, so a retry could apply it twice. If \`uru operations inspect ${operation.id}\` lists idempotency_key, add one to --params-json and reuse it on every retry. If it does not, check the current state before you retry.`;
23729
+ }
23730
+ function invalidArgumentLines(operation, params, details, schema) {
23731
+ const fields = operationFields(schema);
23732
+ const lines = [];
23733
+ if (fields !== undefined) {
23734
+ const missing = fields.required.filter((name) => name !== "op" && !Object.hasOwn(params, name));
23735
+ const unknown2 = Object.keys(params).filter((name) => name !== "op" && !fields.properties.has(name));
23736
+ if (missing.length > 0) {
23737
+ lines.push(`Missing required fields: ${missing.join(", ")}.`);
23738
+ }
23739
+ if (unknown2.length > 0) {
23740
+ lines.push(`Fields not in this operation's input schema: ${unknown2.join(", ")}.`);
23741
+ }
23742
+ }
23743
+ const pathLine = mismatchPathLine(details, fields);
23744
+ if (pathLine !== undefined) {
23745
+ lines.push(pathLine);
23746
+ }
23747
+ return lines.length > 0 ? lines : serverReportLines(operation, details);
23748
+ }
23749
+ function operationFields(schema) {
23750
+ const properties = schema?.["properties"];
23751
+ if (schema === undefined || !isSchemaObject2(properties)) {
23752
+ return;
23753
+ }
23754
+ const required3 = schema["required"];
23755
+ return {
23756
+ properties: new Set(Object.keys(properties)),
23757
+ required: Array.isArray(required3) ? required3.filter((name) => typeof name === "string") : []
23758
+ };
23759
+ }
23760
+ function mismatchPathLine(details, fields) {
23761
+ const path = stringDetail(details, "first_mismatch_path");
23762
+ const keyword = stringDetail(details, "first_mismatch_keyword");
23763
+ if (path === undefined || path === "" || path === "/" || keyword === undefined) {
23764
+ return;
23765
+ }
23766
+ const topField = path.split("/")[1];
23767
+ if (fields !== undefined && (topField === undefined || !fields.properties.has(topField))) {
23768
+ return;
23769
+ }
23770
+ const property = stringDetail(details, "first_mismatch_property");
23771
+ return keyword === "required" && property !== undefined ? `Field ${path} is missing required field "${property}".` : `Field ${path} failed the schema rule "${keyword}".`;
23772
+ }
23773
+ function serverReportLines(operation, details) {
23774
+ const lines = [];
23775
+ const path = stringDetail(details, "first_mismatch_path");
23776
+ const property = stringDetail(details, "first_mismatch_property");
23777
+ if ((path === "/" || path === "") && stringDetail(details, "first_mismatch_keyword") === "required" && property !== undefined) {
23778
+ lines.push(`First failing field: ${property} (required).`);
23779
+ } else {
23780
+ const pathLine = mismatchPathLine(details, undefined);
23781
+ if (pathLine !== undefined) {
23782
+ lines.push(pathLine);
23783
+ }
23784
+ }
23785
+ const missing = details?.["missing_required"];
23786
+ const missingNames = Array.isArray(missing) ? missing.filter((name) => typeof name === "string") : [];
23787
+ if (missingNames.length > 0) {
23788
+ lines.push(operation.backendOp === undefined ? `Required fields the server found missing: ${missingNames.join(", ")}.` : `Required fields the server found missing, across every operation of ${operation.backendToolName}: ${missingNames.join(", ")}.`);
23789
+ }
23790
+ return lines;
23791
+ }
23792
+ function stringDetail(details, key) {
23793
+ const value = details?.[key];
23794
+ return typeof value === "string" ? value : undefined;
23795
+ }
23796
+ function isSchemaObject2(value) {
23797
+ return typeof value === "object" && value !== null && !Array.isArray(value);
23798
+ }
23799
+
23800
+ // src/cli-runtime.ts
23596
23801
  function cliStateHome(ctx) {
23597
23802
  return dirname(ctx.store.path);
23598
23803
  }
@@ -23624,6 +23829,38 @@ async function emitGemTool(ctx, operationId, params, options = {}) {
23624
23829
  return emitTool(ctx, operationId, params, options);
23625
23830
  }
23626
23831
  async function emitTool(ctx, operationId, params, options = {}) {
23832
+ try {
23833
+ return await emitToolOutput(ctx, operationId, params, options);
23834
+ } catch (error2) {
23835
+ throw await explainOperationFailure(ctx, operationId, params, error2);
23836
+ }
23837
+ }
23838
+ async function explainOperationFailure(ctx, operationId, params, error2) {
23839
+ const operation = getPlatformOperation(operationId);
23840
+ if (!(error2 instanceof CliError) || operation === undefined) {
23841
+ return error2;
23842
+ }
23843
+ return explainToolFailure({
23844
+ error: error2,
23845
+ operation,
23846
+ params,
23847
+ loadInputSchema: () => narrowedOperationInputSchema(ctx, operation)
23848
+ });
23849
+ }
23850
+ async function narrowedOperationInputSchema(ctx, operation) {
23851
+ if (getCliNativeOperationContract(operation.id) !== undefined) {
23852
+ return;
23853
+ }
23854
+ let rawSchema;
23855
+ try {
23856
+ rawSchema = await client(ctx).getToolSchema(operation.backendToolName);
23857
+ } catch {
23858
+ return;
23859
+ }
23860
+ const inputSchema = isJsonObject2(rawSchema) ? rawSchema["inputSchema"] : undefined;
23861
+ return isJsonObject2(inputSchema) ? narrowToolInputSchemaToOperation(inputSchema, operation.backendOp) : undefined;
23862
+ }
23863
+ async function emitToolOutput(ctx, operationId, params, options) {
23627
23864
  if (ctx.outputFormat === "stream-json" && options.streamStart !== undefined) {
23628
23865
  writeStreamJson(ctx.io, "started", options.streamStart);
23629
23866
  writeStreamJson(ctx.io, "phase", {
@@ -23905,11 +24142,15 @@ function assertToolResultSuccess(value) {
23905
24142
  ].filter((detail) => detail !== undefined);
23906
24143
  const tip = stringField2(value, ["tip"]);
23907
24144
  const errorId = stringField2(value, ["errorId", "error_id"]);
23908
- throw new CliError(`${message}${details.length === 0 ? "" : ` ${details.join(" ")}`}${tip === undefined ? "" : ` ${tip}`}`, {
24145
+ const serverDetails = value["details"] ?? value["errorDetails"];
24146
+ throw new CliError(`${message}${details.length === 0 ? "" : ` ${details.join(" ")}`}`, {
24147
+ ...tip === undefined ? {} : { tip },
23909
24148
  code: httpStatus === 409 ? ExitCode.Conflict : httpStatus === 401 || httpStatus === 403 ? ExitCode.AuthRequired : ExitCode.Failure,
23910
24149
  ...errorCode === undefined ? {} : { errorCode },
23911
24150
  ...errorId === undefined ? {} : { errorId },
23912
- ...httpStatus === undefined ? {} : { httpStatus }
24151
+ ...httpStatus === undefined ? {} : { httpStatus },
24152
+ ...isTransientFailure(httpStatus ?? 0, value) ? { retryable: true } : {},
24153
+ ...isJsonObject2(serverDetails) ? { details: serverDetails } : {}
23913
24154
  });
23914
24155
  }
23915
24156
  function isToolResultEnvelope(value) {
@@ -24607,19 +24848,18 @@ async function dispatchOperations(ctx, sub, args) {
24607
24848
  return;
24608
24849
  }
24609
24850
  if (sub === "inspect") {
24610
- const operationId = requireCommandValue(args[0], "Usage: uru operations inspect <operation-id>");
24611
- const operation = getPlatformOperation(operationId);
24612
- if (operation === undefined) {
24613
- throw new CliError(`Unknown operation: ${operationId}. Run \`uru operations ls\`.`);
24614
- }
24851
+ const reference = requireCommandValue(args[0], "Usage: uru operations inspect <operation-id>");
24852
+ const operation = resolveOperationReference(reference, "inspect", undefined);
24615
24853
  const { contract, text } = await operationContractForInspect(ctx, operation);
24616
24854
  emitValue(ctx, contract, text);
24617
24855
  return;
24618
24856
  }
24619
24857
  if (sub === "run") {
24858
+ const reference = requireCommandValue(args[0], "Usage: uru operations run <operation-id> --params-json '{...}'");
24859
+ const params = await paramsJson(args.slice(1), ["operations", "run"], paramsJsonOptions(ctx));
24860
+ const operation = resolveOperationReference(reference, "run", params);
24620
24861
  await withWorkspace(ctx);
24621
- const operationId = requireCommandValue(args[0], "Usage: uru operations run <operation-id> --params-json '{...}'");
24622
- await emitTool(ctx, operationId, await paramsJson(args.slice(1), ["operations", "run"], paramsJsonOptions(ctx)));
24862
+ await emitTool(ctx, operation.id, params);
24623
24863
  return;
24624
24864
  }
24625
24865
  throw new CliError("Usage: uru operations ls [--family <family>] | inspect <operation-id> | run <operation-id> --params-json {...}");
@@ -24636,43 +24876,31 @@ async function dispatchRegistryFamily(ctx, family, sub, args) {
24636
24876
  emitValue(ctx, contract, text);
24637
24877
  return;
24638
24878
  }
24639
- await emitTool(ctx, operation.id, adaptRegistryFamilyParams(await paramsJson(args, commandPath, paramsJsonOptions(ctx))));
24640
- }
24641
- function adaptRegistryFamilyParams(params) {
24642
- const adapted = {};
24643
- for (const [key, value] of Object.entries(params)) {
24644
- const protocolKey = canonicalCliFieldToToolProtocol(key);
24645
- if (Object.hasOwn(adapted, protocolKey)) {
24646
- throw new CliError(`--params-json contains ambiguous aliases for ${protocolKey}. Use canonical camelCase CLI fields only.`);
24647
- }
24648
- adapted[protocolKey] = value;
24649
- }
24650
- return adapted;
24651
- }
24652
- var REGISTRY_FAMILY_SNAKE_CASE_ALIASES = new Set([
24653
- "automation_id",
24654
- "dataset_ids",
24655
- "idempotency_key",
24656
- "item_id",
24657
- "label_id",
24658
- "label_value",
24659
- "max_results",
24660
- "source_id",
24661
- "connection_id",
24662
- "target_folder_id",
24663
- "drive_id",
24664
- "file_ids",
24665
- "folder_ids",
24666
- "sync_interval_minutes"
24667
- ]);
24668
- function canonicalCliFieldToToolProtocol(key) {
24669
- if (REGISTRY_FAMILY_SNAKE_CASE_ALIASES.has(key)) {
24670
- return key;
24879
+ await emitTool(ctx, operation.id, await paramsJson(args, commandPath, paramsJsonOptions(ctx)));
24880
+ }
24881
+ function resolveOperationReference(reference, verb, params) {
24882
+ const byId = getPlatformOperation(reference);
24883
+ if (byId !== undefined) {
24884
+ return byId;
24885
+ }
24886
+ const toolName = reference.trim().toLowerCase();
24887
+ const candidates = platformOperationsForSurface("cli").filter((operation) => operation.backendToolName.toLowerCase() === toolName);
24888
+ const [first] = candidates;
24889
+ if (first === undefined) {
24890
+ throw new CliError(`Unknown operation: ${reference}. Run \`uru operations ls\`.`);
24891
+ }
24892
+ const rawOp = params?.["op"];
24893
+ const op2 = typeof rawOp === "string" ? rawOp.trim().toLowerCase() : undefined;
24894
+ const [match, ...others] = candidates.filter((operation) => operation.backendOp === undefined ? op2 === undefined : operation.backendOp.toLowerCase() === op2);
24895
+ if (match !== undefined && others.length === 0) {
24896
+ return match;
24671
24897
  }
24672
- if (!/^[a-z][A-Za-z0-9]*$/u.test(key)) {
24673
- throw new CliError(`--params-json field ${JSON.stringify(key)} is not canonical camelCase. Registry-family commands accept canonical CLI fields and adapt them at the tool-protocol boundary.`);
24898
+ if (op2 === undefined && candidates.length === 1) {
24899
+ return first;
24674
24900
  }
24675
- return key.replace(/[A-Z]/g, (character) => `_${character.toLowerCase()}`);
24901
+ const listed = candidates.map((operation) => operation.backendOp === undefined ? operation.id : `${operation.id} (op=${operation.backendOp})`).join(", ");
24902
+ const next = verb === "run" ? `Pass one of those ops in --params-json, or use the operation id: \`uru operations run ${first.id} --params-json '{...}'\`.` : `Inspect one by its operation id: \`uru operations inspect ${first.id}\`.`;
24903
+ throw new CliError(`${reference} is a tool name, not an operation id${op2 === undefined ? "" : `, and op=${op2} is not one of its operations`}. Its operations: ${listed}. ${next}`);
24676
24904
  }
24677
24905
  async function dispatchLibrary(ctx, sub, args) {
24678
24906
  if (sub === "ls") {
@@ -24813,14 +25041,14 @@ async function dispatchLibrarySource(ctx, verb, args) {
24813
25041
  return;
24814
25042
  }
24815
25043
  if (normalizedVerb === "create") {
24816
- const params = adaptRegistryFamilyParams(await paramsJson(args, ["library", "source", "create"], paramsJsonOptions(ctx)));
25044
+ const params = await paramsJson(args, ["library", "source", "create"], paramsJsonOptions(ctx));
24817
25045
  await emitTool(ctx, "library.sources_create", params);
24818
25046
  return;
24819
25047
  }
24820
25048
  if (normalizedVerb === "edit") {
24821
25049
  const flags = parseLocalFlags(args, ["library", "source", "edit"]);
24822
25050
  const sourceId = requireCommandValue(flags.positionals[0], "Usage: uru library source edit <source-id> --params-json '{...}'");
24823
- const params = adaptRegistryFamilyParams(await paramsJson(args, ["library", "source", "edit"], paramsJsonOptions(ctx)));
25051
+ const params = await paramsJson(args, ["library", "source", "edit"], paramsJsonOptions(ctx));
24824
25052
  params["source_id"] = sourceId;
24825
25053
  await emitTool(ctx, "library.sources_edit", params);
24826
25054
  return;
@@ -24844,7 +25072,7 @@ async function dispatchLibrarySource(ctx, verb, args) {
24844
25072
  if (normalizedVerb === "reconnect") {
24845
25073
  const flags = parseLocalFlags(args, ["library", "source", "reconnect"]);
24846
25074
  const sourceId = requireCommandValue(flags.positionals[0], "Usage: uru library source reconnect <source-id> --params-json '{...}'");
24847
- const params = adaptRegistryFamilyParams(await paramsJson(args, ["library", "source", "reconnect"], paramsJsonOptions(ctx)));
25075
+ const params = await paramsJson(args, ["library", "source", "reconnect"], paramsJsonOptions(ctx));
24848
25076
  params["source_id"] = sourceId;
24849
25077
  await emitTool(ctx, "library.sources_reconnect", params);
24850
25078
  return;
@@ -25059,7 +25287,7 @@ async function dispatchDatasets(ctx, sub, args) {
25059
25287
  return;
25060
25288
  }
25061
25289
  if (sub === "create" || sub === "update" || sub === "rows" || sub === "restore" || sub === "sql" || sub === "sql-write") {
25062
- const params = adaptRegistryFamilyParams(await paramsJson(args, ["datasets", sub], paramsJsonOptions(ctx)));
25290
+ const params = await paramsJson(args, ["datasets", sub], paramsJsonOptions(ctx));
25063
25291
  let operationId;
25064
25292
  if (sub === "rows") {
25065
25293
  const rowOperation = params["op"];
@@ -25116,7 +25344,7 @@ async function dispatchDatasetCommand(ctx, sub, args) {
25116
25344
  if (sub === "query") {
25117
25345
  const explicitParams = flags.values["--params-json"];
25118
25346
  if (explicitParams !== undefined) {
25119
- const params2 = adaptRegistryFamilyParams(parseParamsJson(await readParamsJsonSource(explicitParams, paramsJsonOptions(ctx)), "--params-json"));
25347
+ const params2 = parseParamsJson(await readParamsJsonSource(explicitParams, paramsJsonOptions(ctx)), "--params-json");
25120
25348
  params2["dataset_id"] ??= datasetId;
25121
25349
  await emitTool(ctx, "dataset.query", params2);
25122
25350
  return;
@@ -25215,7 +25443,7 @@ async function dispatchDatasetSourceCommand(ctx, verb, args) {
25215
25443
  if (normalizedVerb === "put" || normalizedVerb === "test") {
25216
25444
  const flags = parseLocalFlags(args, ["datasets", "source", normalizedVerb]);
25217
25445
  const datasetId = requireCommandValue(flags.positionals[0], `Usage: uru datasets source ${normalizedVerb} <dataset-id> --params-json '{...}'`);
25218
- const params = adaptRegistryFamilyParams(await paramsJson(args, ["datasets", "source", normalizedVerb], paramsJsonOptions(ctx)));
25446
+ const params = await paramsJson(args, ["datasets", "source", normalizedVerb], paramsJsonOptions(ctx));
25219
25447
  params["dataset_id"] ??= datasetId;
25220
25448
  await emitTool(ctx, normalizedVerb === "put" ? "dataset.external_source_put" : "dataset.external_source_test", params);
25221
25449
  return;
@@ -25236,7 +25464,7 @@ async function dispatchDatasetSourceCommand(ctx, verb, args) {
25236
25464
  const flags = parseLocalFlags(args, ["datasets", "source", "sync"]);
25237
25465
  const datasetId = requireCommandValue(flags.positionals[0], "Usage: uru datasets source sync|run-now <dataset-id> [--params-json '{...}']");
25238
25466
  const explicitParams = flags.values["--params-json"];
25239
- const params = explicitParams === undefined ? {} : adaptRegistryFamilyParams(parseParamsJson(await readParamsJsonSource(explicitParams, paramsJsonOptions(ctx)), "--params-json"));
25467
+ const params = explicitParams === undefined ? {} : parseParamsJson(await readParamsJsonSource(explicitParams, paramsJsonOptions(ctx)), "--params-json");
25240
25468
  params["dataset_id"] = datasetId;
25241
25469
  params["idempotency_key"] ??= flags.values["--idempotency-key"] ?? randomUUID();
25242
25470
  if (params["expected_dataset_revision"] === undefined || params["expected_schema_revision"] === undefined) {
@@ -25755,7 +25983,7 @@ async function dispatchDistributionLinkCreate(ctx, args) {
25755
25983
  }
25756
25984
  function distributionParams(flags) {
25757
25985
  const raw = flags.values["--params-json"];
25758
- return raw === undefined ? {} : adaptRegistryFamilyParams(parseParamsJson(raw, "--params-json"));
25986
+ return raw === undefined ? {} : parseParamsJson(raw, "--params-json");
25759
25987
  }
25760
25988
 
25761
25989
  // src/mcp-commands.ts
@@ -31893,13 +32121,15 @@ function sourceSensitiveTip(errorCode, source) {
31893
32121
  return source === "explicit" ? "This token was supplied for this invocation, so `uru login` cannot replace it. The server refused the token itself: check that it is still valid and that it may act in the workspace this command targets." : "Run `uru login`, pass `--token`, or set `URU_TOKEN` before retrying.";
31894
32122
  }
31895
32123
  function cliErrorJson(error2, source = "stored") {
31896
- const tip = tipForErrorCode(error2.errorCode, source);
32124
+ const tip = tipForError(error2, source);
31897
32125
  return {
31898
32126
  error: error2.message,
31899
32127
  code: error2.errorCode,
31900
32128
  exitCode: error2.exitCode,
31901
32129
  ...error2.errorId === undefined ? {} : { errorId: error2.errorId },
31902
32130
  ...error2.httpStatus === undefined ? {} : { httpStatus: error2.httpStatus },
32131
+ ...error2.retryable === true ? { retryable: true } : {},
32132
+ ...error2.details === undefined ? {} : { details: error2.details },
31903
32133
  ...tip === undefined ? {} : { tip },
31904
32134
  docs: `${CLI_DOCS_URL}#${error2.errorCode}`,
31905
32135
  ...error2.confirmationRequired === true ? { confirmationRequired: true } : {},
@@ -31910,7 +32140,7 @@ function formatCliError(error2, source = "stored") {
31910
32140
  const lines = [
31911
32141
  `Error [${error2.errorCode}]: ${stripTerminalControl(error2.message)}`
31912
32142
  ];
31913
- const tip = tipForErrorCode(error2.errorCode, source);
32143
+ const tip = tipForError(error2, source);
31914
32144
  if (tip !== undefined) {
31915
32145
  lines.push(`Tip: ${tip}`);
31916
32146
  }
@@ -31919,8 +32149,9 @@ function formatCliError(error2, source = "stored") {
31919
32149
  `)}
31920
32150
  `;
31921
32151
  }
31922
- function tipForErrorCode(errorCode, source) {
31923
- return sourceSensitiveTip(errorCode, source) ?? ERROR_TIPS[errorCode];
32152
+ var RETRYABLE_TIP = "This failure is temporary. A read is safe to run again as it is. Retry a write only with the same idempotency_key, so the change cannot apply twice.";
32153
+ function tipForError(error2, source) {
32154
+ return sourceSensitiveTip(error2.errorCode, source) ?? error2.tip ?? (error2.retryable === true ? RETRYABLE_TIP : undefined) ?? ERROR_TIPS[error2.errorCode];
31924
32155
  }
31925
32156
 
31926
32157
  // src/terminal.ts
@@ -32186,6 +32417,10 @@ function throwIfCancelled(signal) {
32186
32417
  throw new CliError("Cancelled.", { code: ExitCode.Cancelled, cause: reason });
32187
32418
  }
32188
32419
  async function dispatchWithImplicitLogin(ctx, command, linkedProject) {
32420
+ if (command[0] === "login") {
32421
+ await dispatchCliCommand(ctx, command, linkedProject);
32422
+ return;
32423
+ }
32189
32424
  let activeCtx = ctx;
32190
32425
  let recoveredFromSessionRevoked = false;
32191
32426
  for (;; ) {