@uru-intelligence/cli 0.5.7 → 0.5.8

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
@@ -17,7 +17,7 @@ var __export = (target, all) => {
17
17
 
18
18
  // src/cli.ts
19
19
  import { spawn as spawn3 } from "node:child_process";
20
- import { homedir as homedir3 } from "node:os";
20
+ import { homedir as homedir4 } from "node:os";
21
21
 
22
22
  // ../../packages/api-client/src/generated/cli-remote-contracts.gen.ts
23
23
  var cliRemoteOperationContracts = [
@@ -2424,6 +2424,7 @@ function gemPathSpecs() {
2424
2424
  pathSpec(["gems", "share", "create"], "gems", [optional("gem")], [
2425
2425
  valueFlag("--name"),
2426
2426
  valueFlag("--people"),
2427
+ booleanFlag("--no-notify"),
2427
2428
  booleanFlag("--anyone"),
2428
2429
  booleanFlag("--no-anyone"),
2429
2430
  booleanFlag("--organization"),
@@ -2465,7 +2466,12 @@ function gemPathSpecs() {
2465
2466
  valueFlag("--idempotency-key"),
2466
2467
  ...gemRefFlags
2467
2468
  ]),
2468
- pathSpec(["gems", "share", "add-people"], "gems", [required("share"), optional("gem")], [...gemRefFlags, valueFlag("--people"), valueFlag("--idempotency-key")]),
2469
+ pathSpec(["gems", "share", "add-people"], "gems", [required("share"), optional("gem")], [
2470
+ ...gemRefFlags,
2471
+ valueFlag("--people"),
2472
+ booleanFlag("--no-notify"),
2473
+ valueFlag("--idempotency-key")
2474
+ ]),
2469
2475
  pathSpec(["gems", "share", "remove-person"], "gems", [required("share"), required("recipient"), optional("gem")], [...gemRefFlags, booleanFlag("--yes"), valueFlag("--idempotency-key")]),
2470
2476
  pathSpec(["gems", "share", "consents"], "gems", [required("share"), optional("gem")], [
2471
2477
  ...gemRefFlags,
@@ -3132,7 +3138,7 @@ function spec(id, summary, auth, workspace, safety, outputModes, cancellation =
3132
3138
  // package.json
3133
3139
  var package_default = {
3134
3140
  name: "@uru-intelligence/cli",
3135
- version: "0.5.7",
3141
+ version: "0.5.8",
3136
3142
  private: false,
3137
3143
  description: "Uru full-platform command line interface",
3138
3144
  repository: {
@@ -3160,10 +3166,8 @@ var package_default = {
3160
3166
  lint: "node ../../scripts/run-with-repo-node.mjs oxlint --type-aware --deny-warnings -c ../../oxlint.config.mts .",
3161
3167
  "lint:fix": "node ../../scripts/run-with-repo-node.mjs oxlint --type-aware --deny-warnings -c ../../oxlint.config.mts --fix .",
3162
3168
  "type-check": "tsc --noEmit",
3163
- test: "bun test",
3164
- "test:unit": "bun test",
3165
- "test:safety": "node ../../scripts/ci/run-named-test-files.mjs bun test --files test/certified-tarball-inspection.test.ts test/command-spec.test.ts test/cli-auth-help.test.ts test/cli-distribution.test.ts test/cli-gem-lifecycle.test.ts test/cli-hardening.test.ts test/cli-login-cancellation.test.ts test/cli-login-noninteractive.test.ts test/cli-login-rejection.test.ts test/cli-mcp-auth-ux.test.ts test/cli-oauth-lifecycle.test.ts test/cli-oauth-offline.test.ts test/cli-openapi-contract.test.ts test/cli-token-env-run.test.ts test/cli-token-env.test.ts test/cli-tools-approve.test.ts test/cli-update-check.test.ts test/cli-update-notifier.test.ts test/cli-whoami-honesty.test.ts test/cli-workspace-organizations.test.ts test/credentials.test.ts test/held-idempotency-keys.test.ts test/oauth-callback.test.ts test/oauth-credential.test.ts test/oauth.test.ts test/publish-immutable-cli.test.ts test/stricli-compatibility.test.ts test/terminal-safety.test.ts",
3166
- ci: "bun run lint && bun run type-check && bun run test:unit && bun run docs:check && bun run changelog:check && bun run build && bun run smoke:package && bun run smoke:binaries",
3169
+ "test:safety": "node ../../scripts/ci/run-named-test-files.mjs bun test --files test/certified-tarball-inspection.test.ts test/command-spec.test.ts test/cli-auth-help.test.ts test/cli-distribution.test.ts test/cli-gem-lifecycle.test.ts test/cli-hardening.test.ts test/cli-login-cancellation.test.ts test/cli-login-noninteractive.test.ts test/cli-login-rejection.test.ts test/cli-mcp-auth-ux.test.ts test/cli-oauth-lifecycle.test.ts test/cli-oauth-offline.test.ts test/cli-openapi-contract.test.ts test/cli-token-env-run.test.ts test/cli-token-env.test.ts test/cli-tools-approve.test.ts test/cli-update-check.test.ts test/cli-update-notifier.test.ts test/cli-whoami-honesty.test.ts test/cli-workspace-organizations.test.ts test/credentials.test.ts test/held-idempotency-keys.test.ts test/oauth-callback.test.ts test/oauth-credential.test.ts test/oauth.test.ts test/publish-immutable-cli.test.ts test/stricli-compatibility.test.ts test/terminal-safety.test.ts test/cli-automations-wait.test.ts test/cli-connector-auth-status.test.ts test/cli-connector-oauth.test.ts test/cli-doctor.test.ts test/cli-gem-capabilities.test.ts test/cli-gem-logs-follow.test.ts test/cli-gem-source-remote-degrade.test.ts test/cli-gem-v2-commands.test.ts test/cli-platform-tools.test.ts test/cli-source-sync-push.test.ts test/cli-source-sync.part2.test.ts test/cli-source-sync.test.ts test/cli-tools-catalog.test.ts test/cli.test.ts test/client.test.ts test/config.test.ts test/gem-result.test.ts test/library.test.ts test/staging-smoke.test.ts test/platform-operations-tool-call-lookup.test.ts test/cli-gem-bindings.test.ts",
3170
+ ci: "bun run lint && bun run type-check && bun run test:safety && bun run docs:check && bun run changelog:check && bun run build && bun run smoke:package && bun run smoke:binaries",
3167
3171
  build: "node scripts/build.mjs && bun run check:dist-company-names",
3168
3172
  "check:dist-company-names": "bun ../../scripts/check-cli-dist-company-names.ts",
3169
3173
  prepack: "bun run build",
@@ -3410,6 +3414,7 @@ function applyValueFlag(flags, flag, value) {
3410
3414
 
3411
3415
  // src/auth-commands.ts
3412
3416
  import { readFile } from "node:fs/promises";
3417
+ import { dirname as dirname3 } from "node:path";
3413
3418
 
3414
3419
  // src/oauth-callback.ts
3415
3420
  import { createServer } from "node:http";
@@ -3488,6 +3493,9 @@ async function listenForOAuthCallback(args) {
3488
3493
  }
3489
3494
  }
3490
3495
 
3496
+ // src/cli-runtime.ts
3497
+ import { dirname } from "node:path";
3498
+
3491
3499
  // ../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/core/core.js
3492
3500
  var _a;
3493
3501
  function $constructor(name, initializer, params) {
@@ -12587,7 +12595,8 @@ var zGemShareAudienceRequest = strictObject({
12587
12595
  });
12588
12596
  var zGemShareCaller = strictObject({
12589
12597
  canManage: boolean2(),
12590
- isOwner: boolean2()
12598
+ isOwner: boolean2(),
12599
+ peopleSearch: _enum(["organization", "workspace"]).nullable()
12591
12600
  });
12592
12601
  var zGemShareCapability = strictObject({
12593
12602
  blockedReason: _enum(["adopted_connection", "no_personal_owner"]).nullable(),
@@ -12651,10 +12660,14 @@ var zGemShareOwner = strictObject({
12651
12660
  isYou: boolean2(),
12652
12661
  name: string2().nullable()
12653
12662
  });
12663
+ var zGemSharePeopleResponse = strictObject({
12664
+ people: array(zGemShareAudiencePerson)
12665
+ });
12654
12666
  var zGemSharePerson = strictObject({
12655
12667
  email: string2().min(3).max(320)
12656
12668
  });
12657
12669
  var zAddGemShareRecipientsRequest = strictObject({
12670
+ notify: boolean2().optional(),
12658
12671
  people: array(zGemSharePerson).min(1).max(100)
12659
12672
  });
12660
12673
  var zCreateGemShareRequest = strictObject({
@@ -12665,6 +12678,7 @@ var zCreateGemShareRequest = strictObject({
12665
12678
  kind: _enum(["editor", "viewer"]).optional(),
12666
12679
  message: string2().max(2000).nullish(),
12667
12680
  name: string2().min(1).max(200),
12681
+ notify: boolean2().optional(),
12668
12682
  notifyOnOpen: _enum(["all_views", "first_view_only", "off"]).optional(),
12669
12683
  people: array(zGemSharePerson).max(100).optional(),
12670
12684
  version: object({
@@ -12716,6 +12730,7 @@ var zGemShare = strictObject({
12716
12730
  expiresAt: string2().nullable(),
12717
12731
  gate: zGemShareGate,
12718
12732
  gemId: string2(),
12733
+ generalAccessCount: int(),
12719
12734
  hasNamedRecipients: boolean2(),
12720
12735
  id: string2(),
12721
12736
  kind: _enum(["editor", "viewer"]),
@@ -12766,6 +12781,12 @@ var zGemShareDetail = strictObject({
12766
12781
  });
12767
12782
  var zGemShareAddRecipientsResponse = strictObject({
12768
12783
  added: array(zGemShareRecipient),
12784
+ emailed: array(string2()),
12785
+ gemId: string2(),
12786
+ share: zGemShareDetail
12787
+ });
12788
+ var zGemShareCreateResponse = strictObject({
12789
+ emailed: array(string2()),
12769
12790
  gemId: string2(),
12770
12791
  share: zGemShareDetail
12771
12792
  });
@@ -13793,6 +13814,7 @@ var zLibraryShareRequest = object({
13793
13814
  automationPackageConfirmationToken: string2().min(16).nullish(),
13794
13815
  expiresAt: exports_iso.datetime({ offset: true }).nullish(),
13795
13816
  message: string2().nullish(),
13817
+ notify: boolean2().optional().default(true),
13796
13818
  recipients: array(zLibraryShareRecipientRequest).optional(),
13797
13819
  shareMode: string2().regex(/^(reference|copy)$/).optional().default("reference"),
13798
13820
  shareScope: string2().regex(/^(specific_users|workspace)$/).optional().default("specific_users")
@@ -15326,6 +15348,7 @@ var zShareContentRequest = object({
15326
15348
  contentType: zContentTypeInput,
15327
15349
  description: string2().nullish(),
15328
15350
  expiresAt: exports_iso.datetime({ offset: true }).nullish(),
15351
+ notify: boolean2().optional().default(true),
15329
15352
  recipientUserIds: array(uuid2()).nullish(),
15330
15353
  recipients: array(zRecipientSpec).nullish(),
15331
15354
  replaceExistingRecipients: boolean2().optional().default(false),
@@ -17991,6 +18014,7 @@ var zSharedContentResponse = object({
17991
18014
  contentType: zModulesSharingModelsContentType,
17992
18015
  createdAt: exports_iso.datetime({ offset: true }),
17993
18016
  description: string2().nullable(),
18017
+ emailedUserIds: array(uuid2()).optional(),
17994
18018
  expiresAt: exports_iso.datetime({ offset: true }).nullable(),
17995
18019
  id: uuid2(),
17996
18020
  metadata: record(string2(), unknown()),
@@ -21495,6 +21519,13 @@ var zCreateGemShareHeaders = object({
21495
21519
  var zCreateGemSharePath = object({
21496
21520
  gemRef: string2().min(1)
21497
21521
  });
21522
+ var zSearchGemSharePeoplePath = object({
21523
+ gemRef: string2().min(1)
21524
+ });
21525
+ var zSearchGemSharePeopleQuery = object({
21526
+ query: string2().min(2).max(200),
21527
+ limit: int().gte(1).lte(50).optional().default(20)
21528
+ });
21498
21529
  var zListGemVersionsPath = object({
21499
21530
  gemRef: string2().min(1)
21500
21531
  });
@@ -23808,447 +23839,6 @@ function normalizeTool(value) {
23808
23839
  }
23809
23840
  return [tool];
23810
23841
  }
23811
-
23812
- // src/oauth.ts
23813
- import { createHash, randomBytes } from "node:crypto";
23814
- import { setTimeout as sleepTimer } from "node:timers/promises";
23815
- var DEFAULT_PKCE_VERIFIER_BYTES = 32;
23816
- var DEFAULT_STATE_BYTES = 24;
23817
- var OAUTH_DEVICE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
23818
- var DEVICE_POLL_SLOW_DOWN_SECONDS = 5;
23819
- function generatePkcePair() {
23820
- const verifier = tokenUrlSafe(DEFAULT_PKCE_VERIFIER_BYTES);
23821
- return {
23822
- verifier,
23823
- challenge: pkceChallengeS256(verifier),
23824
- method: "S256"
23825
- };
23826
- }
23827
- function generateOAuthState() {
23828
- return tokenUrlSafe(DEFAULT_STATE_BYTES);
23829
- }
23830
- function pkceChallengeS256(verifier) {
23831
- if (!isValidPkceVerifier(verifier)) {
23832
- throw new CliError("PKCE code verifier must be 43-128 RFC7636 unreserved characters.");
23833
- }
23834
- return createHash("sha256").update(verifier).digest("base64url");
23835
- }
23836
- function buildLoopbackRedirectUri(args) {
23837
- const host = args.host.trim();
23838
- if (host === "") {
23839
- throw new CliError("Callback host cannot be empty.");
23840
- }
23841
- if (!Number.isInteger(args.port) || args.port < 1 || args.port > 65535) {
23842
- throw new CliError("Callback port must be between 1 and 65535.");
23843
- }
23844
- const path = args.path ?? "/oauth/callback";
23845
- const normalizedPath = path.startsWith("/") ? path : `/${path}`;
23846
- return `http://${host}:${args.port}${normalizedPath}`;
23847
- }
23848
- function buildAuthorizationUrl(args) {
23849
- const url2 = new URL(args.authorizationEndpoint);
23850
- url2.searchParams.set("response_type", "code");
23851
- url2.searchParams.set("client_id", args.clientId);
23852
- url2.searchParams.set("redirect_uri", args.redirectUri);
23853
- url2.searchParams.set("scope", args.scope);
23854
- url2.searchParams.set("state", args.state);
23855
- url2.searchParams.set("code_challenge", args.codeChallenge);
23856
- url2.searchParams.set("code_challenge_method", "S256");
23857
- if (args.resource !== undefined && args.resource.trim() !== "") {
23858
- url2.searchParams.set("resource", args.resource);
23859
- }
23860
- return url2.toString();
23861
- }
23862
- function parseOAuthCallbackUrl(callbackUrl, expectedState, expectedIssuer, issuerRequired = false) {
23863
- const url2 = new URL(callbackUrl);
23864
- const state = url2.searchParams.get("state") ?? "";
23865
- if (state === "" || state !== expectedState) {
23866
- throw new CliError("OAuth callback state did not match.", {
23867
- code: ExitCode.AuthRequired,
23868
- errorCode: "oauth_state_mismatch"
23869
- });
23870
- }
23871
- const issuers = url2.searchParams.getAll("iss");
23872
- if (issuerRequired && issuers.length === 0 || issuers.length > 1 || issuers.length === 1 && issuers[0] !== expectedIssuer) {
23873
- throw new CliError("OAuth callback issuer did not match the sign-in server.", {
23874
- code: ExitCode.AuthRequired,
23875
- errorCode: "oauth_issuer_mismatch"
23876
- });
23877
- }
23878
- const error2 = url2.searchParams.get("error");
23879
- if (error2 !== null && error2 !== "") {
23880
- throw new CliError("OAuth authorization failed. Start sign-in again and approve access.", { code: ExitCode.AuthRequired, errorCode: "oauth_authorization_failed" });
23881
- }
23882
- const code = url2.searchParams.get("code") ?? "";
23883
- if (code === "") {
23884
- throw new CliError("OAuth callback did not include an authorization code.", {
23885
- code: ExitCode.AuthRequired,
23886
- errorCode: "oauth_missing_code"
23887
- });
23888
- }
23889
- return { code, state };
23890
- }
23891
- async function resolveOAuthClientMetadata(args) {
23892
- const clientId = `${normalizeApiUrl(args.apiUrl)}/oauth/client-metadata/uru-cli.json`;
23893
- const response = await fetchOAuthGet({
23894
- apiUrl: args.apiUrl,
23895
- path: "/oauth/client-metadata/uru-cli.json",
23896
- ...args.fetch === undefined ? {} : { fetch: args.fetch }
23897
- });
23898
- if (!isRecord(response)) {
23899
- throw new CliError("Unexpected OAuth Client ID Metadata Document.");
23900
- }
23901
- const declaredClientId = stringField(response, "client_id");
23902
- if (declaredClientId !== clientId) {
23903
- throw new CliError("OAuth Client ID Metadata Document did not match its URL.");
23904
- }
23905
- const redirectUris = response["redirect_uris"];
23906
- if (!Array.isArray(redirectUris) || !redirectUris.some((value) => value === args.redirectUri)) {
23907
- throw new CliError("OAuth Client ID Metadata Document did not allow this callback.");
23908
- }
23909
- return {
23910
- clientId: declaredClientId,
23911
- scope: optionalStringField(response, "scope") ?? "mcp offline_access"
23912
- };
23913
- }
23914
- async function discoverOAuthIssuer(args) {
23915
- const expectedIssuer = normalizeApiUrl(args.apiUrl);
23916
- const metadata = await fetchOAuthGet({
23917
- apiUrl: args.apiUrl,
23918
- path: "/.well-known/oauth-authorization-server",
23919
- ...args.fetch === undefined ? {} : { fetch: args.fetch }
23920
- });
23921
- if (!isRecord(metadata) || metadata["issuer"] !== expectedIssuer) {
23922
- throw new CliError("OAuth discovery issuer did not match the sign-in server.", {
23923
- code: ExitCode.AuthRequired,
23924
- errorCode: "oauth_issuer_mismatch"
23925
- });
23926
- }
23927
- return {
23928
- issuer: expectedIssuer,
23929
- issuerRequired: metadata["authorization_response_iss_parameter_supported"] === true
23930
- };
23931
- }
23932
- async function discoverOAuthResource(args) {
23933
- const response = await fetchOAuthGet({
23934
- apiUrl: args.apiUrl,
23935
- path: "/.well-known/oauth-protected-resource",
23936
- ...args.fetch === undefined ? {} : { fetch: args.fetch }
23937
- });
23938
- if (!isRecord(response)) {
23939
- throw new CliError("Unexpected OAuth protected-resource metadata response.");
23940
- }
23941
- const resource = stringField(response, "resource");
23942
- assertHttpUrl(resource, "OAuth protected resource");
23943
- return resource;
23944
- }
23945
- async function exchangeAuthorizationCode(args) {
23946
- const body = new URLSearchParams;
23947
- body.set("grant_type", "authorization_code");
23948
- body.set("client_id", args.clientId);
23949
- body.set("code", args.code);
23950
- body.set("redirect_uri", args.redirectUri);
23951
- body.set("code_verifier", args.codeVerifier);
23952
- if (args.resource !== undefined && args.resource.trim() !== "") {
23953
- body.set("resource", args.resource);
23954
- }
23955
- const response = await fetchOAuthForm({
23956
- apiUrl: args.apiUrl,
23957
- path: "/oauth/token",
23958
- body,
23959
- ...args.fetch === undefined ? {} : { fetch: args.fetch }
23960
- });
23961
- return toOAuthTokenResponse(zOAuthTokenResponse.parse(response));
23962
- }
23963
- async function refreshOAuthToken(args) {
23964
- const body = new URLSearchParams;
23965
- body.set("grant_type", "refresh_token");
23966
- body.set("client_id", args.clientId);
23967
- body.set("refresh_token", args.refreshToken);
23968
- body.set("resource", args.resource);
23969
- const response = await fetchOAuthForm({
23970
- apiUrl: args.apiUrl,
23971
- path: "/oauth/token",
23972
- body,
23973
- rejectedGrantErrorCode: "oauth_refresh_invalid",
23974
- ...args.fetch === undefined ? {} : { fetch: args.fetch }
23975
- });
23976
- return toOAuthTokenResponse(zOAuthTokenResponse.parse(response));
23977
- }
23978
- async function revokeOAuthToken(args) {
23979
- const body = new URLSearchParams;
23980
- body.set("token", args.token);
23981
- body.set("token_type_hint", "refresh_token");
23982
- body.set("client_id", args.clientId);
23983
- await fetchOAuthForm({
23984
- apiUrl: args.apiUrl,
23985
- path: "/oauth/revoke",
23986
- body,
23987
- ...args.fetch === undefined ? {} : { fetch: args.fetch }
23988
- });
23989
- }
23990
- async function exchangeOAuthForCliSession(args) {
23991
- const body = {};
23992
- if (args.workspaceId !== undefined && args.workspaceId.trim() !== "") {
23993
- body["workspace_id"] = args.workspaceId;
23994
- }
23995
- const response = await fetchOAuthJson({
23996
- apiUrl: args.apiUrl,
23997
- path: "/api/oauth/cli-session",
23998
- body,
23999
- authorization: `Bearer ${args.oauthAccessToken}`,
24000
- ...args.fetch === undefined ? {} : { fetch: args.fetch }
24001
- });
24002
- return toCliSessionResponse(zCliSessionResponse.parse(response));
24003
- }
24004
- async function startDeviceAuthorization(args) {
24005
- const body = new URLSearchParams;
24006
- body.set("client_id", args.clientId);
24007
- body.set("scope", args.scope);
24008
- if (args.resource !== undefined && args.resource.trim() !== "") {
24009
- body.set("resource", args.resource);
24010
- }
24011
- const response = await fetchOAuthForm({
24012
- apiUrl: args.apiUrl,
24013
- path: "/oauth/device/code",
24014
- body,
24015
- ...args.fetch === undefined ? {} : { fetch: args.fetch }
24016
- });
24017
- return toDeviceAuthorization(zDeviceAuthorizationResponse.parse(response));
24018
- }
24019
- async function pollDeviceToken(args) {
24020
- let intervalSeconds = Math.max(1, args.intervalSeconds);
24021
- const sleep = args.sleep ?? ((milliseconds) => sleepTimer(milliseconds, undefined, { signal: args.signal }));
24022
- for (let attempt = 0;attempt < args.maxPolls; attempt += 1) {
24023
- args.signal?.throwIfAborted();
24024
- if (attempt > 0) {
24025
- await sleep(intervalSeconds * 1000);
24026
- }
24027
- const body = new URLSearchParams;
24028
- body.set("grant_type", OAUTH_DEVICE_GRANT_TYPE);
24029
- body.set("client_id", args.clientId);
24030
- body.set("device_code", args.deviceCode);
24031
- const response = await fetchOAuthForm({
24032
- apiUrl: args.apiUrl,
24033
- path: "/oauth/token",
24034
- body,
24035
- allowOAuthError: true,
24036
- ...args.fetch === undefined ? {} : { fetch: args.fetch }
24037
- });
24038
- if (isRecord(response) && typeof response["error"] === "string") {
24039
- const error2 = response["error"];
24040
- if (error2 === "authorization_pending") {
24041
- continue;
24042
- }
24043
- if (error2 === "slow_down") {
24044
- intervalSeconds += DEVICE_POLL_SLOW_DOWN_SECONDS;
24045
- continue;
24046
- }
24047
- throw new CliError(`OAuth device login failed: ${error2}`, {
24048
- code: ExitCode.AuthRequired,
24049
- errorCode: "oauth_device_failed"
24050
- });
24051
- }
24052
- args.signal?.throwIfAborted();
24053
- return toOAuthTokenResponse(zOAuthTokenResponse.parse(response));
24054
- }
24055
- throw new CliError("OAuth device login timed out before authorization completed.", {
24056
- code: ExitCode.AuthRequired,
24057
- errorCode: "oauth_device_timeout"
24058
- });
24059
- }
24060
- async function fetchOAuthJson(args) {
24061
- const fetchImpl = args.fetch ?? fetch;
24062
- const response = await fetchImpl(oauthEndpoint(args.apiUrl, args.path), {
24063
- method: "POST",
24064
- signal: AbortSignal.timeout(30000),
24065
- headers: {
24066
- Accept: "application/json",
24067
- "Content-Type": "application/json",
24068
- ...args.authorization === undefined ? {} : { Authorization: args.authorization }
24069
- },
24070
- body: JSON.stringify(args.body)
24071
- });
24072
- const payload = parseJsonResponse(await response.text());
24073
- if (!response.ok) {
24074
- throw new CliError(errorMessage2(payload) ?? `OAuth request failed: HTTP ${response.status}`, {
24075
- code: response.status === 401 || response.status === 403 || response.status === 409 ? ExitCode.AuthRequired : ExitCode.Failure,
24076
- errorCode: "oauth_request_failed"
24077
- });
24078
- }
24079
- return payload;
24080
- }
24081
- async function fetchOAuthGet(args) {
24082
- const fetchImpl = args.fetch ?? fetch;
24083
- const response = await fetchImpl(oauthEndpoint(args.apiUrl, args.path), {
24084
- method: "GET",
24085
- signal: AbortSignal.timeout(30000),
24086
- headers: { Accept: "application/json" }
24087
- });
24088
- const payload = parseJsonResponse(await response.text());
24089
- if (!response.ok) {
24090
- throw oauthHttpError(response.status, payload);
24091
- }
24092
- return payload;
24093
- }
24094
- function tokenUrlSafe(byteLength) {
24095
- return randomBytes(byteLength).toString("base64url");
24096
- }
24097
- function isValidPkceVerifier(verifier) {
24098
- return /^[A-Za-z0-9._~-]{43,128}$/.test(verifier);
24099
- }
24100
- async function fetchOAuthForm(args) {
24101
- const fetchImpl = args.fetch ?? fetch;
24102
- const response = await fetchImpl(oauthEndpoint(args.apiUrl, args.path), {
24103
- method: "POST",
24104
- signal: AbortSignal.timeout(30000),
24105
- headers: {
24106
- Accept: "application/json",
24107
- "Content-Type": "application/x-www-form-urlencoded"
24108
- },
24109
- body: args.body.toString()
24110
- });
24111
- const payload = parseJsonResponse(await response.text());
24112
- if (!response.ok && !(args.allowOAuthError === true && isOAuthError(payload))) {
24113
- throw oauthHttpError(response.status, payload, args.rejectedGrantErrorCode);
24114
- }
24115
- return payload;
24116
- }
24117
- function oauthEndpoint(apiUrl, path) {
24118
- let endpoint;
24119
- try {
24120
- endpoint = new URL(normalizeApiUrl(apiUrl));
24121
- } catch (error2) {
24122
- throw invalidOAuthApiUrl(error2);
24123
- }
24124
- if (endpoint.username !== "" || endpoint.password !== "" || endpoint.search !== "" || endpoint.hash !== "" || endpoint.protocol !== "https:" && !(endpoint.protocol === "http:" && isLoopbackHostname(endpoint.hostname))) {
24125
- throw invalidOAuthApiUrl();
24126
- }
24127
- endpoint.pathname = `${endpoint.pathname.replace(/\/$/u, "")}${path}`;
24128
- return endpoint;
24129
- }
24130
- function isLoopbackHostname(hostname) {
24131
- return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]";
24132
- }
24133
- function invalidOAuthApiUrl(cause) {
24134
- return new CliError("OAuth API URL must use HTTPS, except for a local loopback server.", {
24135
- code: ExitCode.AuthRequired,
24136
- errorCode: "oauth_invalid_api_url",
24137
- ...cause === undefined ? {} : { cause }
24138
- });
24139
- }
24140
- function parseJsonResponse(text) {
24141
- if (text.trim() === "") {
24142
- return null;
24143
- }
24144
- const parsed = JSON.parse(text);
24145
- if (!isJsonValue2(parsed)) {
24146
- throw new CliError("OAuth endpoint returned non-JSON data.", {
24147
- errorCode: "oauth_invalid_response"
24148
- });
24149
- }
24150
- return parsed;
24151
- }
24152
- function isJsonValue2(value) {
24153
- if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
24154
- return true;
24155
- }
24156
- if (Array.isArray(value)) {
24157
- return value.every(isJsonValue2);
24158
- }
24159
- if (isRecord(value)) {
24160
- return Object.values(value).every(isJsonValue2);
24161
- }
24162
- return false;
24163
- }
24164
- function isOAuthError(value) {
24165
- return isRecord(value) && typeof value["error"] === "string";
24166
- }
24167
- function toCliSessionResponse(response) {
24168
- return {
24169
- accessToken: response.access_token,
24170
- tokenType: response.token_type,
24171
- expiresIn: response.expires_in,
24172
- oauthResource: response.oauth_resource,
24173
- ...response.workspace_id.trim() === "" ? {} : { workspaceId: response.workspace_id }
24174
- };
24175
- }
24176
- function toDeviceAuthorization(response) {
24177
- return {
24178
- deviceCode: response.device_code,
24179
- userCode: response.user_code,
24180
- verificationUri: response.verification_uri,
24181
- verificationUriComplete: response.verification_uri_complete,
24182
- expiresIn: response.expires_in,
24183
- interval: response.interval
24184
- };
24185
- }
24186
- function toOAuthTokenResponse(response) {
24187
- return {
24188
- accessToken: response.access_token,
24189
- tokenType: response.token_type,
24190
- expiresIn: response.expires_in,
24191
- refreshToken: response.refresh_token,
24192
- scope: response.scope
24193
- };
24194
- }
24195
- function oauthHttpError(status, payload, rejectedGrantErrorCode) {
24196
- const oauthError = isRecord(payload) && typeof payload["error"] === "string" ? payload["error"] : null;
24197
- const authRequired = status === 400 || status === 401 || status === 403 || status === 409;
24198
- const grantRejected = rejectedGrantErrorCode !== undefined && (oauthError === "invalid_grant" || oauthError === "invalid_target" || oauthError === "invalid_client");
24199
- return new CliError(errorMessage2(payload) ?? `OAuth request failed: HTTP ${status}`, {
24200
- code: authRequired ? ExitCode.AuthRequired : ExitCode.Failure,
24201
- errorCode: grantRejected ? rejectedGrantErrorCode : "oauth_request_failed"
24202
- });
24203
- }
24204
- function assertHttpUrl(value, label) {
24205
- let url2;
24206
- try {
24207
- url2 = new URL(value);
24208
- } catch (error2) {
24209
- throw new CliError(`${label} is not a valid URL.`, {
24210
- errorCode: "oauth_invalid_response",
24211
- cause: error2
24212
- });
24213
- }
24214
- const loopbackHostname = url2.hostname === "localhost" || url2.hostname === "127.0.0.1" || url2.hostname === "[::1]";
24215
- if (url2.protocol !== "https:" && !(url2.protocol === "http:" && loopbackHostname)) {
24216
- throw new CliError(`${label} must use HTTPS except on loopback.`, {
24217
- errorCode: "oauth_invalid_response"
24218
- });
24219
- }
24220
- }
24221
- function stringField(value, key) {
24222
- const field = value[key];
24223
- if (typeof field !== "string" || field.trim() === "") {
24224
- throw new CliError(`OAuth response missing ${key}.`);
24225
- }
24226
- return field;
24227
- }
24228
- function optionalStringField(value, key) {
24229
- const field = value[key];
24230
- return typeof field === "string" && field.trim() !== "" ? field : undefined;
24231
- }
24232
- function errorMessage2(payload) {
24233
- if (!isRecord(payload)) {
24234
- return;
24235
- }
24236
- const error2 = payload["error"];
24237
- switch (error2) {
24238
- case "access_denied":
24239
- return "Authorization was denied. Start sign-in again.";
24240
- case "invalid_grant":
24241
- return "Authorization expired or was revoked. Sign in again.";
24242
- case "invalid_client":
24243
- return "The sign-in client is not accepted by the server.";
24244
- case "expired_token":
24245
- return "The sign-in request expired. Start sign-in again.";
24246
- case "temporarily_unavailable":
24247
- return "The sign-in service is temporarily unavailable.";
24248
- default:
24249
- return;
24250
- }
24251
- }
24252
23842
  // ../../packages/types/src/platform/workspace.ts
24253
23843
  var PERSONAL_ORGANIZATION_GROUP_LABEL = "Personal";
24254
23844
  function groupWorkspacesByOrganizationOrder(rows, keyOf) {
@@ -24880,11 +24470,11 @@ Release flag. A Release never changes a share. Embedded Gems can be shared
24880
24470
  without a Release.
24881
24471
  `,
24882
24472
  "gems share": `Usage: uru gems share list [library/name.gem]
24883
- uru gems share create [library/name.gem] --name <name> [--people <email,email>] [--anyone|--no-anyone|--organization|--workspaces <id,id>] [--gate none|passcode|email_otp] [--passcode <code>] [--email-allowlist <email,email>] [--expires-at <iso>] [--notify-on-open off|first_view_only|all_views] [--message <text>] [--pin --version <version>] [--idempotency-key <key>] [--verify]
24884
- uru gems share create [library/name.gem] --name <name> --role editor --people <email,email> [--consent kind:id,...] [--message <text>] [--idempotency-key <key>]
24473
+ uru gems share create [library/name.gem] --name <name> [--people <email,email>] [--no-notify] [--anyone|--no-anyone|--organization|--workspaces <id,id>] [--gate none|passcode|email_otp] [--passcode <code>] [--email-allowlist <email,email>] [--expires-at <iso>] [--notify-on-open off|first_view_only|all_views] [--message <text>] [--pin --version <version>] [--idempotency-key <key>] [--verify]
24474
+ uru gems share create [library/name.gem] --name <name> --role editor --people <email,email> [--no-notify] [--consent kind:id,...] [--message <text>] [--idempotency-key <key>]
24885
24475
  uru gems share get|analytics [library/name.gem] <share>
24886
24476
  uru gems share update [library/name.gem] <share> [--name <name>] [--version <version> | --latest] [--rollback --yes] [--gate <gate>] [--expires-at <iso>] [--notify-on-open <mode>] [--anyone|--no-anyone|--organization|--workspaces <id,id>] [--confirm-link-off] [--search-indexing-disabled]
24887
- uru gems share add-people [library/name.gem] <share> --people <email,email>
24477
+ uru gems share add-people [library/name.gem] <share> --people <email,email> [--no-notify]
24888
24478
  uru gems share remove-person [library/name.gem] <share> <recipient> --yes
24889
24479
  uru gems share consents [library/name.gem] <share> [--grant kind:id,...] [--revoke kind:id,...]
24890
24480
  uru gems share revoke [library/name.gem] <share>
@@ -24897,6 +24487,11 @@ serves each newer Version once it is ready, and needs no Version named. Add
24897
24487
  --pin --version <version> to keep it on one Version instead. --version on its
24898
24488
  own is refused on create, because a following share would not serve it.
24899
24489
 
24490
+ Each person you name on create or add-people gets an email that says you
24491
+ shared the Gem with them. --no-notify sends no email: the person is still
24492
+ added and still gets the Uru inbox card. The output names every address the
24493
+ email was queued for. A person who turned sharing email off gets none.
24494
+
24900
24495
  General access is one level at a time. --anyone gives the share an anyone URL.
24901
24496
  --organization lets every owner, admin and member of the Gem workspace's
24902
24497
  organization open it after they sign in. --workspaces <id,id> lets the members
@@ -25265,142 +24860,1544 @@ function objectPayload(value) {
25265
24860
  return { value };
25266
24861
  }
25267
24862
 
25268
- // src/auth-commands.ts
25269
- var DEVICE_MAX_POLLS = 120;
25270
- var CIMD_CALLBACK_PORT = 8765;
25271
- async function resolveStoredToken(options) {
25272
- const keychainValue = await options.credentialStore.readToken(options.apiUrl);
25273
- const source = keychainValue === undefined ? "config" : "keychain";
25274
- const storedValue = keychainValue ?? (options.config.insecureStorage === true ? options.config.token : undefined);
25275
- if (storedValue === undefined) {
24863
+ // src/tool-failure-guidance.ts
24864
+ async function explainToolFailure(input) {
24865
+ const { error: error2, operation, params } = input;
24866
+ if (error2.errorCode === "invalid_tool_arguments") {
24867
+ const lines = invalidArgumentLines(operation, params, error2.details, await input.loadInputSchema());
24868
+ return refineCliError(error2, {
24869
+ ...lines.length === 0 ? {} : { message: `${error2.message} ${lines.join(" ")}` },
24870
+ tip: `Run \`uru operations inspect ${operation.id}\` to read this operation's exact input schema, then send its field names unchanged.`
24871
+ });
24872
+ }
24873
+ if (error2.retryable === true) {
24874
+ return error2.tip === undefined ? refineCliError(error2, { tip: retryTip(operation, params) }) : error2;
24875
+ }
24876
+ return error2;
24877
+ }
24878
+ function retryTip(operation, params) {
24879
+ if (operation.safety === "read") {
24880
+ return "This failure is temporary. This operation only reads, so it is safe to run the same command again. Wait a few seconds first.";
24881
+ }
24882
+ const key = params["idempotency_key"];
24883
+ if (typeof key === "string" && key !== "") {
24884
+ 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.`;
24885
+ }
24886
+ 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.`;
24887
+ }
24888
+ function invalidArgumentLines(operation, params, details, schema) {
24889
+ const fields = operationFields(schema);
24890
+ const lines = [];
24891
+ if (fields !== undefined) {
24892
+ const missing = fields.required.filter((name) => name !== "op" && !Object.hasOwn(params, name));
24893
+ const unknown2 = Object.keys(params).filter((name) => name !== "op" && !fields.properties.has(name));
24894
+ if (missing.length > 0) {
24895
+ lines.push(`Missing required fields: ${missing.join(", ")}.`);
24896
+ }
24897
+ if (unknown2.length > 0) {
24898
+ lines.push(`Fields not in this operation's input schema: ${unknown2.join(", ")}.`);
24899
+ }
24900
+ }
24901
+ const pathLine = mismatchPathLine(details, fields);
24902
+ if (pathLine !== undefined) {
24903
+ lines.push(pathLine);
24904
+ }
24905
+ return lines.length > 0 ? lines : serverReportLines(operation, details);
24906
+ }
24907
+ function operationFields(schema) {
24908
+ const properties = schema?.["properties"];
24909
+ if (schema === undefined || !isSchemaObject2(properties)) {
25276
24910
  return;
25277
24911
  }
25278
- let credential;
24912
+ const required3 = schema["required"];
24913
+ return {
24914
+ properties: new Set(Object.keys(properties)),
24915
+ required: Array.isArray(required3) ? required3.filter((name) => typeof name === "string") : []
24916
+ };
24917
+ }
24918
+ function mismatchPathLine(details, fields) {
24919
+ const path = stringDetail(details, "first_mismatch_path");
24920
+ const keyword = stringDetail(details, "first_mismatch_keyword");
24921
+ if (path === undefined || path === "" || path === "/" || keyword === undefined) {
24922
+ return;
24923
+ }
24924
+ const topField = path.split("/")[1];
24925
+ if (fields !== undefined && (topField === undefined || !fields.properties.has(topField))) {
24926
+ return;
24927
+ }
24928
+ const property = stringDetail(details, "first_mismatch_property");
24929
+ return keyword === "required" && property !== undefined ? `Field ${path} is missing required field "${property}".` : `Field ${path} failed the schema rule "${keyword}".`;
24930
+ }
24931
+ function serverReportLines(operation, details) {
24932
+ const lines = [];
24933
+ const path = stringDetail(details, "first_mismatch_path");
24934
+ const property = stringDetail(details, "first_mismatch_property");
24935
+ if ((path === "/" || path === "") && stringDetail(details, "first_mismatch_keyword") === "required" && property !== undefined) {
24936
+ lines.push(`First failing field: ${property} (required).`);
24937
+ } else {
24938
+ const pathLine = mismatchPathLine(details, undefined);
24939
+ if (pathLine !== undefined) {
24940
+ lines.push(pathLine);
24941
+ }
24942
+ }
24943
+ const missing = details?.["missing_required"];
24944
+ const missingNames = Array.isArray(missing) ? missing.filter((name) => typeof name === "string") : [];
24945
+ if (missingNames.length > 0) {
24946
+ 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(", ")}.`);
24947
+ }
24948
+ return lines;
24949
+ }
24950
+ function stringDetail(details, key) {
24951
+ const value = details?.[key];
24952
+ return typeof value === "string" ? value : undefined;
24953
+ }
24954
+ function isSchemaObject2(value) {
24955
+ return typeof value === "object" && value !== null && !Array.isArray(value);
24956
+ }
24957
+
24958
+ // src/cli-runtime.ts
24959
+ function cliStateHome(ctx) {
24960
+ return dirname(ctx.store.path);
24961
+ }
24962
+ async function withWorkspace(ctx) {
24963
+ if (ctx.workspace !== undefined && ctx.workspace.trim() !== "") {
24964
+ return;
24965
+ }
24966
+ const identity = await client(ctx).validateToken();
24967
+ if (identity.workspaceSelectionRequired) {
24968
+ throw new CliError(`${identity.workspaceSelectionMessage ?? "Workspace selection required"} Run \`uru switch <workspace-id>\`, \`uru link --workspace <workspace-id>\`, or pass --workspace.`, { code: ExitCode.AuthRequired });
24969
+ }
24970
+ }
24971
+ function client(ctx) {
24972
+ return new UruApiClient({
24973
+ apiUrl: ctx.apiUrl,
24974
+ ...ctx.token !== undefined ? { token: ctx.token } : {},
24975
+ ...ctx.workspace !== undefined ? { workspaceId: ctx.workspace } : {},
24976
+ ...ctx.fetch !== undefined ? { fetch: ctx.fetch } : {},
24977
+ signal: ctx.abortSignal
24978
+ });
24979
+ }
24980
+ function assertWorkspaceAvailable(identity, workspaceId) {
24981
+ if (identity.workspaceId === workspaceId || identity.workspaces.some((workspace2) => workspace2.id === workspaceId)) {
24982
+ return;
24983
+ }
24984
+ throw new CliError(`Workspace ${workspaceId} is not available for the current token. Run \`uru switch\` to list available workspaces.`);
24985
+ }
24986
+ async function emitGemTool(ctx, operationId, params, options = {}) {
24987
+ return emitTool(ctx, operationId, params, options);
24988
+ }
24989
+ async function emitTool(ctx, operationId, params, options = {}) {
25279
24990
  try {
25280
- credential = parseStoredCliOAuthCredential(storedValue);
24991
+ return await emitToolOutput(ctx, operationId, params, options);
25281
24992
  } catch (error2) {
25282
- if (options.recoverInvalidCredential === true) {
25283
- return;
25284
- }
25285
- throw error2;
24993
+ throw await explainOperationFailure(ctx, operationId, params, error2);
25286
24994
  }
25287
- if (credential === null) {
25288
- return storedValue;
24995
+ }
24996
+ async function explainOperationFailure(ctx, operationId, params, error2) {
24997
+ const operation = getPlatformOperation(operationId);
24998
+ if (!(error2 instanceof CliError) || operation === undefined) {
24999
+ return error2;
25289
25000
  }
25290
- if (!cliOAuthCredentialNeedsRefresh(credential, Date.now(), {
25291
- ...options.forceRefresh === undefined ? {} : { forceRefresh: options.forceRefresh }
25292
- })) {
25293
- return credential.sessionAccessToken;
25001
+ return explainToolFailure({
25002
+ error: error2,
25003
+ operation,
25004
+ params,
25005
+ loadInputSchema: () => narrowedOperationInputSchema(ctx, operation)
25006
+ });
25007
+ }
25008
+ async function narrowedOperationInputSchema(ctx, operation) {
25009
+ if (getCliNativeOperationContract(operation.id) !== undefined) {
25010
+ return;
25294
25011
  }
25012
+ let rawSchema;
25295
25013
  try {
25296
- const refreshed = await refreshOAuthToken({
25297
- apiUrl: options.apiUrl,
25298
- clientId: credential.oauthClientId,
25299
- refreshToken: credential.oauthRefreshToken,
25300
- resource: credential.oauthResource,
25301
- ...options.fetch === undefined ? {} : { fetch: options.fetch }
25014
+ rawSchema = await client(ctx).getToolSchema(operation.backendToolName);
25015
+ } catch {
25016
+ return;
25017
+ }
25018
+ const inputSchema = isJsonObject2(rawSchema) ? rawSchema["inputSchema"] : undefined;
25019
+ return isJsonObject2(inputSchema) ? narrowToolInputSchemaToOperation(inputSchema, operation.backendOp) : undefined;
25020
+ }
25021
+ async function emitToolOutput(ctx, operationId, params, options) {
25022
+ if (ctx.outputFormat === "stream-json" && options.streamStart !== undefined) {
25023
+ writeStreamJson(ctx.io, "started", options.streamStart);
25024
+ writeStreamJson(ctx.io, "phase", {
25025
+ operation: options.streamStart["operation"] ?? operationId,
25026
+ phase: "requesting"
25302
25027
  });
25303
- const rotatedRefreshToken = requireRefreshToken(refreshed);
25304
- await persistResolvedCredential(options, source, serializeStoredCliOAuthCredential({
25305
- ...credential,
25306
- oauthRefreshToken: rotatedRefreshToken
25307
- }));
25308
- const session = await exchangeOAuthForCliSession({
25309
- apiUrl: options.apiUrl,
25310
- oauthAccessToken: refreshed.accessToken,
25311
- ...options.workspaceId === undefined ? {} : { workspaceId: options.workspaceId },
25312
- ...options.fetch === undefined ? {} : { fetch: options.fetch }
25028
+ const streamed = await executeOperationStream(ctx, operationId, params, (event) => {
25029
+ writeStreamJsonEvent(ctx.io, event);
25313
25030
  });
25314
- if (session.oauthResource !== credential.oauthResource) {
25315
- throw new CliError("Refreshed CLI session OAuth resource did not match the stored credential.", {
25316
- code: ExitCode.AuthRequired,
25317
- errorCode: "oauth_resource_mismatch"
25318
- });
25031
+ if (streamed.streamed) {
25032
+ return null;
25319
25033
  }
25320
- const nextCredential = createStoredCliOAuthCredential({
25321
- sessionAccessToken: session.accessToken,
25322
- sessionExpiresIn: session.expiresIn,
25323
- oauthRefreshToken: rotatedRefreshToken,
25324
- oauthClientId: credential.oauthClientId,
25325
- oauthResource: session.oauthResource,
25326
- ...session.workspaceId === undefined ? {} : { workspaceId: session.workspaceId }
25034
+ const payload2 = toolOutputPayload(streamed.payload ?? null);
25035
+ const output2 = options.transform?.(payload2) ?? payload2;
25036
+ writeStreamJson(ctx.io, "result", output2);
25037
+ writeStreamJson(ctx.io, "done", {
25038
+ operation: options.streamStart["operation"] ?? operationId
25327
25039
  });
25328
- await persistResolvedCredential(options, source, serializeStoredCliOAuthCredential(nextCredential));
25329
- return nextCredential.sessionAccessToken;
25330
- } catch (error2) {
25331
- if (!isStoredRefreshRejected(error2)) {
25332
- throw error2;
25040
+ return payload2;
25041
+ }
25042
+ const result = await executeOperation(ctx, operationId, params);
25043
+ const payload = toolOutputPayload(result);
25044
+ const output = options.transform?.(payload) ?? payload;
25045
+ if (ctx.outputFormat === "stream-json") {
25046
+ writeStreamJson(ctx.io, "result", output);
25047
+ if (options.streamStart !== undefined) {
25048
+ writeStreamJson(ctx.io, "done", {
25049
+ operation: options.streamStart["operation"] ?? operationId
25050
+ });
25051
+ }
25052
+ } else if (ctx.json) {
25053
+ writeJson(ctx.io, output);
25054
+ } else {
25055
+ writeText(ctx.io, options.textExtractor?.(output) ?? JSON.stringify(output, null, 2));
25056
+ }
25057
+ return payload;
25058
+ }
25059
+ async function executeOperationStream(ctx, operationId, params, onEvent) {
25060
+ const operation = getPlatformOperation(operationId);
25061
+ if (operation === undefined) {
25062
+ throw new CliError(`Unknown operation registry id: ${operationId}`);
25063
+ }
25064
+ requireOperationConfirmation(ctx, operation, params);
25065
+ const nativeResult = await executeCliNativeOperation(ctx, operationId, params);
25066
+ if (nativeResult !== undefined) {
25067
+ return { streamed: false, payload: nativeResult };
25068
+ }
25069
+ const toolParams = { ...params };
25070
+ if (operation.backendOp !== undefined) {
25071
+ toolParams["op"] = operation.backendOp;
25072
+ }
25073
+ const streamed = isGemOperation(operation.backendToolName) ? await client(ctx).streamGemTool(operation.backendToolName, toolParams, operation.backendOp ?? operationId, onEvent) : await client(ctx).streamTool(operation.backendToolName, toolParams, onEvent, operationId);
25074
+ if (streamed.streamed) {
25075
+ return streamed;
25076
+ }
25077
+ const payload = streamed.payload ?? null;
25078
+ return { streamed: false, payload };
25079
+ }
25080
+ async function executeOperation(ctx, operationId, params) {
25081
+ const operation = getPlatformOperation(operationId);
25082
+ if (operation === undefined) {
25083
+ throw new CliError(`Unknown operation registry id: ${operationId}`);
25084
+ }
25085
+ requireOperationConfirmation(ctx, operation, params);
25086
+ const nativeResult = await executeCliNativeOperation(ctx, operationId, params);
25087
+ if (nativeResult !== undefined) {
25088
+ return nativeResult;
25089
+ }
25090
+ const toolParams = { ...params };
25091
+ if (operation.backendOp !== undefined) {
25092
+ toolParams["op"] = operation.backendOp;
25093
+ }
25094
+ const result = isGemOperation(operation.backendToolName) ? await client(ctx).runGemTool(operation.backendToolName, toolParams, operation.backendOp ?? operationId) : await client(ctx).runTool(operation.backendToolName, toolParams, operationId);
25095
+ return result;
25096
+ }
25097
+ async function executeCliNativeOperation(ctx, operationId, params) {
25098
+ const contract = getCliNativeOperationContract(operationId);
25099
+ if (contract === undefined)
25100
+ return;
25101
+ switch (contract.kind) {
25102
+ case "list_platform_tools":
25103
+ requireExactKeys(operationId, params, []);
25104
+ return client(ctx).listTools().then(toJsonValue);
25105
+ case "get_platform_tool_schema": {
25106
+ requireExactKeys(operationId, params, ["tool_name"]);
25107
+ return client(ctx).getToolSchema(requireStringParam(params, "tool_name"));
25108
+ }
25109
+ case "execute_platform_tool": {
25110
+ requireExactKeys(operationId, params, ["tool_name", "parameters"]);
25111
+ const parameters = params["parameters"];
25112
+ if (!isJsonObject2(parameters)) {
25113
+ throw new CliError(`${operationId} parameters must be an object.`);
25114
+ }
25115
+ return client(ctx).runTool(requireStringParam(params, "tool_name"), parameters);
25333
25116
  }
25334
- await clearResolvedCredential(options, source);
25117
+ }
25118
+ }
25119
+ function requireExactKeys(operationId, params, expected) {
25120
+ const expectedKeys = new Set(expected);
25121
+ const unexpected = Object.keys(params).filter((key) => !expectedKeys.has(key));
25122
+ const missing = expected.filter((key) => !Object.hasOwn(params, key));
25123
+ if (unexpected.length === 0 && missing.length === 0)
25335
25124
  return;
25125
+ throw new CliError(`${operationId} parameters do not match its operation contract.`);
25126
+ }
25127
+ function requireStringParam(params, key) {
25128
+ const value = params[key];
25129
+ if (typeof value !== "string" || value.trim() === "") {
25130
+ throw new CliError(`${key} must be a non-empty string.`);
25336
25131
  }
25132
+ return value;
25337
25133
  }
25338
- async function resolveMcpCallBearer(ctx, mcpUrl) {
25339
- if (ctx.token === undefined) {
25340
- throw new CliError("Authentication required. Run `uru login` first.", {
25341
- code: ExitCode.AuthRequired
25342
- });
25134
+ function toJsonValue(value) {
25135
+ if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
25136
+ return value;
25343
25137
  }
25344
- if (ctx.tokenIsExplicit || ctx.token.startsWith("uru_")) {
25345
- return { token: ctx.token, expiresAtMs: null };
25138
+ if (Array.isArray(value))
25139
+ return value.map(toJsonValue);
25140
+ if (isUnknownRecord(value)) {
25141
+ return Object.fromEntries(Object.entries(value).map(([key, member]) => [key, toJsonValue(member)]));
25346
25142
  }
25347
- const currentConfig = await ctx.store.read();
25348
- const options = {
25349
- credentialStore: ctx.credentialStore,
25350
- store: ctx.store,
25351
- apiUrl: ctx.apiUrl,
25352
- config: currentConfig,
25353
- ...ctx.workspace === undefined ? {} : { workspaceId: ctx.workspace },
25354
- ...ctx.fetch === undefined ? {} : { fetch: ctx.fetch }
25143
+ throw new CliError("Platform tool command returned a non-JSON value.");
25144
+ }
25145
+ function isUnknownRecord(value) {
25146
+ return typeof value === "object" && value !== null && !Array.isArray(value);
25147
+ }
25148
+ function requireOperationConfirmation(ctx, operation, params) {
25149
+ if (operation === undefined) {
25150
+ throw new CliError("Unknown platform operation. Refusing to execute without a registered safety policy.");
25151
+ }
25152
+ if (ctx.yes || !operationRequiresExplicitConfirmation(operation, params)) {
25153
+ return;
25154
+ }
25155
+ if (operation.id === "library.rm" && params["permanent"] === true) {
25156
+ throw confirmationRequiredError(ctx, "Permanent Library deletion cannot be undone. Re-run with --yes to confirm.");
25157
+ }
25158
+ throw confirmationRequiredError(ctx, `${operation.id} is destructive. Re-run with --yes to confirm.`);
25159
+ }
25160
+ function confirmationRequiredError(ctx, message) {
25161
+ throw new CliError(message, {
25162
+ errorCode: "confirmation_required",
25163
+ confirmationRequired: true,
25164
+ suggestedCommand: suggestCommandWithYes(ctx.argv)
25165
+ });
25166
+ }
25167
+ var SECRET_VALUE_FLAGS = new Set(["--token", "--api-key"]);
25168
+ function suggestCommandWithYes(argv) {
25169
+ const sanitized = stripSecretFlagValues(argv);
25170
+ const withYes = sanitized.includes("--yes") ? sanitized : [...sanitized, "--yes"];
25171
+ return `uru ${withYes.map(shellQuoteArg).join(" ")}`;
25172
+ }
25173
+ function stripSecretFlagValues(argv) {
25174
+ const out = [];
25175
+ for (let i = 0;i < argv.length; i += 1) {
25176
+ const arg = argv[i];
25177
+ if (arg === undefined) {
25178
+ continue;
25179
+ }
25180
+ const equals = arg.indexOf("=");
25181
+ if (equals !== -1 && SECRET_VALUE_FLAGS.has(arg.slice(0, equals))) {
25182
+ out.push(`${arg.slice(0, equals)}=[redacted]`);
25183
+ continue;
25184
+ }
25185
+ if (SECRET_VALUE_FLAGS.has(arg)) {
25186
+ out.push(arg);
25187
+ const next = argv[i + 1];
25188
+ if (next !== undefined && !next.startsWith("--")) {
25189
+ out.push("[redacted]");
25190
+ i += 1;
25191
+ }
25192
+ continue;
25193
+ }
25194
+ out.push(arg);
25195
+ }
25196
+ return out;
25197
+ }
25198
+ function shellQuoteArg(arg) {
25199
+ if (/^[A-Za-z0-9_./:@%+=,-]+$/.test(arg)) {
25200
+ return arg;
25201
+ }
25202
+ return `'${arg.replace(/'/g, "'\\''")}'`;
25203
+ }
25204
+ function emit(ctx, value, text) {
25205
+ emitValue(ctx, value, text);
25206
+ }
25207
+ function emitValue(ctx, value, text) {
25208
+ if (ctx.outputFormat === "stream-json") {
25209
+ writeStreamJson(ctx.io, "result", value);
25210
+ return;
25211
+ }
25212
+ if (ctx.json) {
25213
+ writeJson(ctx.io, value);
25214
+ return;
25215
+ }
25216
+ writeText(ctx.io, text ?? (typeof value === "string" ? value : JSON.stringify(value, null, 2)));
25217
+ }
25218
+ function delegatedPayload(value) {
25219
+ if (isJsonObject2(value) && isJsonObject2(value["payload"])) {
25220
+ return value["payload"];
25221
+ }
25222
+ return value;
25223
+ }
25224
+ function gemPathFromArgs(flags, linkedProject) {
25225
+ return flags.values["--path"] ?? flags.values["--gem"] ?? flags.positionals.find((value) => value.startsWith("library/")) ?? linkedProject.libraryPath ?? linkedProject.gemId ?? (() => {
25226
+ throw new CliError("Gem path required. Pass library/<name>.gem or run `uru link --path library/<name>.gem`.");
25227
+ })();
25228
+ }
25229
+ function tokenGemRefParams(flags, linkedProject, options = {}) {
25230
+ const explicitPath = flags.values["--path"];
25231
+ if (explicitPath !== undefined) {
25232
+ return { path: explicitPath };
25233
+ }
25234
+ const explicitGem = flags.values["--gem"];
25235
+ if (explicitGem !== undefined) {
25236
+ return explicitGem.startsWith("library/") ? { path: explicitGem } : { gem_id: explicitGem };
25237
+ }
25238
+ const positional = flags.positionals[0];
25239
+ if (positional !== undefined) {
25240
+ return positional.startsWith("library/") ? { path: positional } : { gem_id: positional };
25241
+ }
25242
+ if (linkedProject.libraryPath !== undefined) {
25243
+ return { path: linkedProject.libraryPath };
25244
+ }
25245
+ if (linkedProject.gemId !== undefined) {
25246
+ return { gem_id: linkedProject.gemId };
25247
+ }
25248
+ if (options.required === true) {
25249
+ throw new CliError(options.usage ?? "Gem reference required. Pass library/<name>.gem, --path, --gem, or run `uru link`.");
25250
+ }
25251
+ return {};
25252
+ }
25253
+ function shiftPositionals(flags, count) {
25254
+ return {
25255
+ values: flags.values,
25256
+ booleans: flags.booleans,
25257
+ positionals: flags.positionals.slice(count)
25355
25258
  };
25356
- const keychainValue = await ctx.credentialStore.readToken(ctx.apiUrl);
25357
- const source = keychainValue === undefined ? "config" : "keychain";
25358
- const storedValue = keychainValue ?? (currentConfig.insecureStorage === true ? currentConfig.token : undefined);
25359
- const credential = storedValue === undefined ? null : parseStoredCliOAuthCredential(storedValue);
25360
- if (storedValue === undefined || credential === null) {
25361
- throw new CliError("The saved CLI login has no MCP grant. Run `uru login` again.", {
25362
- code: ExitCode.AuthRequired,
25363
- errorCode: "auth_required"
25364
- });
25259
+ }
25260
+ function stringField(record2, keys) {
25261
+ for (const key of keys) {
25262
+ const value = record2[key];
25263
+ if (typeof value === "string" && value.trim() !== "") {
25264
+ return value.trim();
25265
+ }
25365
25266
  }
25366
- if (credential.sessionAccessToken !== ctx.token) {
25367
- throw new CliError("The saved CLI sign-in changed. Retry the command.", {
25368
- code: ExitCode.AuthRequired,
25369
- errorCode: "auth_required"
25370
- });
25267
+ return;
25268
+ }
25269
+ function isGemOperation(toolName) {
25270
+ return toolName === "gem_control_plane" || toolName === "gem_query";
25271
+ }
25272
+ function toolOutputPayload(value) {
25273
+ return unwrapToolResult(value);
25274
+ }
25275
+ function isJsonObject2(value) {
25276
+ return value !== null && typeof value === "object" && !Array.isArray(value);
25277
+ }
25278
+ function unwrapToolResult(value) {
25279
+ assertToolResultSuccess(value);
25280
+ if (isJsonObject2(value) && Object.hasOwn(value, "result") && (isToolResultEnvelope2(value) || isJsonObject2(value["result"]))) {
25281
+ return value["result"] ?? value;
25371
25282
  }
25372
- if (credential.oauthResource !== mcpUrl) {
25373
- throw new CliError("The saved MCP grant is for a different proxy URL.", {
25374
- code: ExitCode.AuthRequired,
25375
- errorCode: "oauth_resource_mismatch"
25376
- });
25283
+ return value;
25284
+ }
25285
+ function assertToolResultSuccess(value) {
25286
+ if (!isJsonObject2(value) || !isToolResultEnvelope2(value)) {
25287
+ return;
25377
25288
  }
25378
- try {
25379
- const refreshed = await refreshOAuthToken({
25380
- apiUrl: ctx.apiUrl,
25381
- clientId: credential.oauthClientId,
25382
- refreshToken: credential.oauthRefreshToken,
25383
- resource: credential.oauthResource,
25384
- fetch: loginFetch(ctx)
25385
- });
25386
- const rotatedRefreshToken = requireRefreshToken(refreshed);
25387
- await persistMcpGrantIfCurrent(options, source, storedValue, serializeStoredCliOAuthCredential({
25388
- ...credential,
25389
- oauthRefreshToken: rotatedRefreshToken
25390
- }));
25391
- return {
25392
- token: refreshed.accessToken,
25393
- expiresAtMs: Date.now() + (refreshed.expiresIn ?? 0) * 1000
25394
- };
25395
- } catch (error2) {
25396
- if (isStoredRefreshRejected(error2)) {
25397
- await clearMcpGrantIfCurrent(options, source, storedValue);
25289
+ const httpStatus = toolResultHttpStatus(value);
25290
+ const failed = value["success"] === false || Object.hasOwn(value, "error") || Object.hasOwn(value, "errorMessage") || Object.hasOwn(value, "error_message") || Object.hasOwn(value, "errorCode") || Object.hasOwn(value, "error_code") || Object.hasOwn(value, "code") || httpStatus !== undefined && httpStatus >= 400;
25291
+ if (!failed) {
25292
+ return;
25293
+ }
25294
+ const errorCode = stringField(value, ["errorCode", "error_code", "code"]);
25295
+ const toolId = stringField(value, ["toolId", "tool_id"]);
25296
+ const message = stringField(value, ["errorMessage", "error_message", "error", "message"]) ?? `${toolId === undefined ? "Tool operation" : `Tool ${toolId}`} failed`;
25297
+ const details = [
25298
+ errorCode === undefined ? undefined : `[${errorCode}]`,
25299
+ httpStatus === undefined ? undefined : `(HTTP ${httpStatus})`
25300
+ ].filter((detail) => detail !== undefined);
25301
+ const tip = stringField(value, ["tip"]);
25302
+ const errorId = stringField(value, ["errorId", "error_id"]);
25303
+ const serverDetails = value["details"] ?? value["errorDetails"];
25304
+ throw new CliError(`${message}${details.length === 0 ? "" : ` ${details.join(" ")}`}`, {
25305
+ ...tip === undefined ? {} : { tip },
25306
+ code: httpStatus === 409 ? ExitCode.Conflict : httpStatus === 401 || httpStatus === 403 ? ExitCode.AuthRequired : ExitCode.Failure,
25307
+ ...errorCode === undefined ? {} : { errorCode },
25308
+ ...errorId === undefined ? {} : { errorId },
25309
+ ...httpStatus === undefined ? {} : { httpStatus },
25310
+ ...isTransientFailure(httpStatus ?? 0, value) ? { retryable: true } : {},
25311
+ ...isJsonObject2(serverDetails) ? { details: serverDetails } : {}
25312
+ });
25313
+ }
25314
+ function isToolResultEnvelope2(value) {
25315
+ return typeof value["success"] === "boolean" && (typeof value["toolId"] === "string" || typeof value["tool_id"] === "string" || typeof value["executionTimeMs"] === "number" || typeof value["execution_time_ms"] === "number");
25316
+ }
25317
+ function toolResultHttpStatus(value) {
25318
+ const status = value["httpStatus"] ?? value["http_status"];
25319
+ return typeof status === "number" && Number.isFinite(status) ? status : undefined;
25320
+ }
25321
+ function normalizeError(error2) {
25322
+ if (error2 instanceof CliError) {
25323
+ return error2;
25324
+ }
25325
+ if (isAbortError(error2)) {
25326
+ return new CliError("Cancelled.", { code: ExitCode.Cancelled });
25327
+ }
25328
+ return new CliError(error2 instanceof Error ? error2.message : "Unknown error");
25329
+ }
25330
+ function isAbortError(error2) {
25331
+ if (!(error2 instanceof Error)) {
25332
+ return false;
25333
+ }
25334
+ return error2.name === "AbortError" || error2.message === "This operation was aborted";
25335
+ }
25336
+ function findSourceRevisionId(value) {
25337
+ let found;
25338
+ visitJson(value, (candidate) => {
25339
+ if (!isJsonObject2(candidate)) {
25340
+ return;
25341
+ }
25342
+ const valueAtKey = stringField(candidate, [
25343
+ "currentSourceRevisionId",
25344
+ "current_source_revision_id",
25345
+ "sourceRevisionId",
25346
+ "source_revision_id"
25347
+ ]);
25348
+ if (valueAtKey !== undefined) {
25349
+ found = valueAtKey;
25350
+ }
25351
+ });
25352
+ return found;
25353
+ }
25354
+ function visitJson(value, visitor) {
25355
+ visitor(value);
25356
+ if (Array.isArray(value)) {
25357
+ for (const item of value) {
25358
+ visitJson(item, visitor);
25359
+ }
25360
+ return;
25361
+ }
25362
+ if (!isJsonObject2(value)) {
25363
+ return;
25364
+ }
25365
+ for (const item of Object.values(value)) {
25366
+ visitJson(item, visitor);
25367
+ }
25368
+ }
25369
+
25370
+ // src/local-lock.ts
25371
+ import { execFileSync } from "node:child_process";
25372
+ import { createHash, randomUUID } from "node:crypto";
25373
+ import { constants, readFileSync } from "node:fs";
25374
+ import { link, mkdir, open, rename, rm } from "node:fs/promises";
25375
+ import { homedir, userInfo } from "node:os";
25376
+ import { dirname as dirname2, join } from "node:path";
25377
+ var LOCK_TIMEOUT_MS = 1e4;
25378
+ var LOCK_RETRY_MS = 10;
25379
+ var LOCK_STALE_MS = 30000;
25380
+ var RECOVERY_SUFFIX = ".recovery";
25381
+ var PROCESS_QUERY_TIMEOUT_MS = 1000;
25382
+ async function withLocalLock(path, action, timeoutErrorCode, timeoutMessage, signal) {
25383
+ assertNotAborted(signal);
25384
+ const lockPath = `${path}.lock`;
25385
+ const recoveryPath = `${lockPath}${RECOVERY_SUFFIX}`;
25386
+ await mkdir(dirname2(path), { recursive: true });
25387
+ const deadline = Date.now() + LOCK_TIMEOUT_MS;
25388
+ while (true) {
25389
+ assertNotAborted(signal);
25390
+ const recovery = await readLockObservation(recoveryPath);
25391
+ if (recovery !== null) {
25392
+ if (lockIsStale(recovery)) {
25393
+ await removeLockIfMatches(recoveryPath, recovery);
25394
+ continue;
25395
+ }
25396
+ await waitForLock(deadline, timeoutErrorCode, timeoutMessage, signal);
25397
+ continue;
25398
+ }
25399
+ let handle = null;
25400
+ let ownLock = null;
25401
+ try {
25402
+ handle = await open(lockPath, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, constants.S_IRUSR | constants.S_IWUSR);
25403
+ } catch (error2) {
25404
+ if (!isNodeError(error2) || error2.code !== "EEXIST") {
25405
+ throw error2;
25406
+ }
25407
+ const observation = await readLockObservation(lockPath);
25408
+ if (observation !== null && lockIsStale(observation)) {
25409
+ const recovered = await recoverStaleLock(lockPath, recoveryPath, observation, deadline, timeoutErrorCode, timeoutMessage, signal);
25410
+ if (recovered) {
25411
+ continue;
25412
+ }
25413
+ }
25414
+ await waitForLock(deadline, timeoutErrorCode, timeoutMessage, signal, error2);
25415
+ continue;
25416
+ }
25417
+ try {
25418
+ const contents = `${process.pid}
25419
+ ${PROCESS_IDENTITY}
25420
+ ${randomUUID()}
25421
+ `;
25422
+ await handle.writeFile(contents, "utf8");
25423
+ await handle.sync();
25424
+ ownLock = {
25425
+ contents,
25426
+ inode: String((await handle.stat()).ino)
25427
+ };
25428
+ } catch (error2) {
25429
+ await handle.close().catch(() => {
25430
+ return;
25431
+ });
25432
+ if (ownLock !== null) {
25433
+ await removeLockIfMatches(lockPath, ownLock).catch(() => {
25434
+ return;
25435
+ });
25436
+ }
25437
+ throw error2;
25438
+ }
25439
+ try {
25440
+ await handle.close();
25441
+ handle = null;
25442
+ } catch (error2) {
25443
+ if (ownLock !== null) {
25444
+ await removeLockIfMatches(lockPath, ownLock).catch(() => {
25445
+ return;
25446
+ });
25447
+ }
25448
+ throw error2;
25449
+ }
25450
+ try {
25451
+ assertNotAborted(signal);
25452
+ return await action();
25453
+ } finally {
25454
+ if (ownLock !== null) {
25455
+ await removeLockIfMatches(lockPath, ownLock).catch(() => {
25456
+ return;
25457
+ });
25458
+ }
25459
+ }
25460
+ }
25461
+ }
25462
+ function withCredentialLock(stateHome, apiUrl, action, signal) {
25463
+ return withLocalLock(configMutationLockBasePath(stateHome), () => withLocalLock(keychainMutationLockBasePath(apiUrl), action, "credential_lock_timeout", "Cannot update the saved CLI credential because another CLI process kept its credential lock. Retry the command.", signal), "credential_lock_timeout", "Cannot update the saved CLI configuration because another CLI process kept its configuration lock. Retry the command.", signal);
25464
+ }
25465
+ function configMutationLockBasePath(stateHome) {
25466
+ return join(stateHome, ".uru-config-mutation");
25467
+ }
25468
+ function keychainMutationLockBasePath(apiUrl) {
25469
+ const apiOrigin = new URL(apiUrl).origin;
25470
+ const fingerprint = createHash("sha256").update(apiOrigin).digest("hex");
25471
+ return join(credentialAuthorityHome(), ".config", "uru", `.uru-keychain-${fingerprint}`);
25472
+ }
25473
+ function credentialAuthorityHome() {
25474
+ try {
25475
+ return userInfo().homedir;
25476
+ } catch {
25477
+ return homedir();
25478
+ }
25479
+ }
25480
+ async function waitForLock(deadline, errorCode, message, signal, cause) {
25481
+ assertNotAborted(signal);
25482
+ if (Date.now() >= deadline) {
25483
+ throw new CliError(message, {
25484
+ errorCode,
25485
+ ...cause === undefined ? {} : { cause }
25486
+ });
25487
+ }
25488
+ await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_MS));
25489
+ assertNotAborted(signal);
25490
+ }
25491
+ async function recoverStaleLock(lockPath, recoveryPath, expected, deadline, errorCode, message, signal) {
25492
+ while (Date.now() < deadline) {
25493
+ assertNotAborted(signal);
25494
+ const ownRecovery = await tryCreateLock(recoveryPath);
25495
+ if (ownRecovery === null) {
25496
+ const currentRecovery = await readLockObservation(recoveryPath);
25497
+ if (currentRecovery !== null && lockIsStale(currentRecovery)) {
25498
+ await removeLockIfMatches(recoveryPath, currentRecovery);
25499
+ continue;
25500
+ }
25501
+ return false;
25502
+ }
25503
+ try {
25504
+ const current = await readLockObservation(lockPath);
25505
+ if (current === null)
25506
+ return true;
25507
+ if (current.inode !== expected.inode || current.contents !== expected.contents || !lockIsStale(current)) {
25508
+ return false;
25509
+ }
25510
+ await removeLockIfMatches(lockPath, current);
25511
+ return true;
25512
+ } finally {
25513
+ await removeLockIfMatches(recoveryPath, ownRecovery).catch(() => {
25514
+ return;
25515
+ });
25516
+ }
25517
+ }
25518
+ throw new CliError(message, { errorCode });
25519
+ }
25520
+ async function tryCreateLock(path) {
25521
+ let handle = null;
25522
+ let ownLock = null;
25523
+ try {
25524
+ handle = await open(path, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, constants.S_IRUSR | constants.S_IWUSR);
25525
+ } catch (error2) {
25526
+ if (isNodeError(error2) && error2.code === "EEXIST")
25527
+ return null;
25528
+ throw error2;
25529
+ }
25530
+ try {
25531
+ const contents = `${process.pid}
25532
+ ${PROCESS_IDENTITY}
25533
+ ${randomUUID()}
25534
+ `;
25535
+ await handle.writeFile(contents, "utf8");
25536
+ await handle.sync();
25537
+ ownLock = {
25538
+ contents,
25539
+ inode: String((await handle.stat()).ino)
25540
+ };
25541
+ return ownLock;
25542
+ } catch (error2) {
25543
+ await handle.close().catch(() => {
25544
+ return;
25545
+ });
25546
+ await removeLockIfMatches(path, ownLock ?? { contents: "", inode: "" }).catch(() => {
25547
+ return;
25548
+ });
25549
+ throw error2;
25550
+ } finally {
25551
+ await handle.close().catch(() => {
25552
+ return;
25553
+ });
25554
+ }
25555
+ }
25556
+ function lockIsStale(observation) {
25557
+ const [pidText, ownerIdentity] = observation.contents.split(/\s+/u);
25558
+ const pid = Number.parseInt(pidText ?? "", 10);
25559
+ if (Number.isSafeInteger(pid) && pid > 0) {
25560
+ if (ownerIdentity?.startsWith("proc:") === true || ownerIdentity?.startsWith("started:") === true || ownerIdentity?.startsWith("win:") === true) {
25561
+ const currentIdentity = processIdentityForPid(pid);
25562
+ if (currentIdentity !== undefined) {
25563
+ return currentIdentity !== ownerIdentity;
25564
+ }
25565
+ }
25566
+ try {
25567
+ process.kill(pid, 0);
25568
+ return false;
25569
+ } catch (error2) {
25570
+ return isNodeError(error2) && error2.code === "ESRCH";
25571
+ }
25572
+ }
25573
+ return Date.now() - observation.mtimeMs > LOCK_STALE_MS;
25574
+ }
25575
+ async function readLockObservation(path) {
25576
+ let handle = null;
25577
+ try {
25578
+ handle = await open(path, constants.O_RDONLY);
25579
+ const contents = await handle.readFile("utf8");
25580
+ const details = await handle.stat();
25581
+ return {
25582
+ contents,
25583
+ inode: String(details.ino),
25584
+ mtimeMs: details.mtimeMs
25585
+ };
25586
+ } catch (error2) {
25587
+ if (isNodeError(error2) && error2.code === "ENOENT")
25588
+ return null;
25589
+ throw error2;
25590
+ } finally {
25591
+ await handle?.close().catch(() => {
25592
+ return;
25593
+ });
25594
+ }
25595
+ }
25596
+ async function removeLockIfMatches(path, expected) {
25597
+ const quarantinePath = `${path}.${process.pid}.${randomUUID()}.quarantine`;
25598
+ try {
25599
+ await rename(path, quarantinePath);
25600
+ await syncParentDirectory(path);
25601
+ } catch (error2) {
25602
+ if (isNodeError(error2) && error2.code === "ENOENT")
25603
+ return false;
25604
+ throw error2;
25605
+ }
25606
+ let quarantine;
25607
+ try {
25608
+ const handle = await open(quarantinePath, constants.O_RDONLY);
25609
+ try {
25610
+ quarantine = {
25611
+ contents: await handle.readFile("utf8"),
25612
+ inode: String((await handle.stat()).ino)
25613
+ };
25614
+ } finally {
25615
+ await handle.close();
25616
+ }
25617
+ } catch (error2) {
25618
+ await restoreLock(quarantinePath, path).catch(() => {
25619
+ return;
25620
+ });
25621
+ throw error2;
25622
+ }
25623
+ if (quarantine.inode === expected.inode && quarantine.contents === expected.contents) {
25624
+ await rm(quarantinePath, { force: true });
25625
+ await syncParentDirectory(path);
25626
+ return true;
25627
+ }
25628
+ await restoreLock(quarantinePath, path);
25629
+ return false;
25630
+ }
25631
+ async function restoreLock(quarantinePath, path) {
25632
+ try {
25633
+ await link(quarantinePath, path);
25634
+ } catch (error2) {
25635
+ if (!(isNodeError(error2) && error2.code === "EEXIST"))
25636
+ throw error2;
25637
+ }
25638
+ await rm(quarantinePath, { force: true });
25639
+ await syncParentDirectory(path);
25640
+ }
25641
+ function isNodeError(error2) {
25642
+ return error2 instanceof Error && "code" in error2;
25643
+ }
25644
+ async function syncParentDirectory(path) {
25645
+ let directory = null;
25646
+ try {
25647
+ directory = await open(dirname2(path), constants.O_RDONLY | (constants.O_DIRECTORY ?? 0));
25648
+ await directory.sync();
25649
+ } catch (error2) {
25650
+ if (isNodeError(error2) && (error2.code === "EPERM" || error2.code === "ENOTSUP" || error2.code === "EINVAL")) {
25651
+ return;
25652
+ }
25653
+ throw error2;
25654
+ } finally {
25655
+ await directory?.close();
25656
+ }
25657
+ }
25658
+ function assertNotAborted(signal) {
25659
+ if (signal?.aborted !== true)
25660
+ return;
25661
+ const reason = signal.reason;
25662
+ if (reason instanceof CliError)
25663
+ throw reason;
25664
+ throw new CliError("Cancelled.", {
25665
+ code: ExitCode.Cancelled,
25666
+ errorCode: "cancelled",
25667
+ cause: reason
25668
+ });
25669
+ }
25670
+ var PROCESS_IDENTITY = processIdentityForPid(process.pid) ?? `unverified:${randomUUID()}`;
25671
+ function processIdentityForPid(pid) {
25672
+ const procStart = readProcStartTicks(pid);
25673
+ if (procStart !== undefined)
25674
+ return `proc:${procStart}`;
25675
+ if (process.platform === "win32") {
25676
+ const windowsStart = readWindowsProcessStart(pid);
25677
+ if (windowsStart !== undefined)
25678
+ return `win:${windowsStart}`;
25679
+ return;
25680
+ }
25681
+ try {
25682
+ const output = execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], {
25683
+ encoding: "utf8",
25684
+ stdio: ["ignore", "pipe", "ignore"],
25685
+ timeout: PROCESS_QUERY_TIMEOUT_MS
25686
+ }).trim();
25687
+ const startedAt = Date.parse(output);
25688
+ return Number.isFinite(startedAt) ? `started:${startedAt}` : undefined;
25689
+ } catch {
25690
+ return;
25691
+ }
25692
+ }
25693
+ function readWindowsProcessStart(pid) {
25694
+ try {
25695
+ const output = execFileSync("powershell.exe", [
25696
+ "-NoLogo",
25697
+ "-NoProfile",
25698
+ "-NonInteractive",
25699
+ "-Command",
25700
+ `(Get-Process -Id ${pid} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks`
25701
+ ], {
25702
+ encoding: "utf8",
25703
+ stdio: ["ignore", "pipe", "ignore"],
25704
+ timeout: PROCESS_QUERY_TIMEOUT_MS
25705
+ }).trim();
25706
+ return /^\d+$/u.test(output) ? output : undefined;
25707
+ } catch {
25708
+ return;
25709
+ }
25710
+ }
25711
+ function readProcStartTicks(pid) {
25712
+ try {
25713
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
25714
+ const closeParen = stat.lastIndexOf(")");
25715
+ if (closeParen < 0)
25716
+ return;
25717
+ const fields = stat.slice(closeParen + 2).trim().split(/\s+/u);
25718
+ const startTicks = fields[19];
25719
+ return startTicks === undefined || startTicks === "" ? undefined : startTicks;
25720
+ } catch {
25721
+ return;
25722
+ }
25723
+ }
25724
+
25725
+ // src/oauth.ts
25726
+ import { createHash as createHash2, randomBytes } from "node:crypto";
25727
+ import { setTimeout as sleepTimer } from "node:timers/promises";
25728
+ var DEFAULT_PKCE_VERIFIER_BYTES = 32;
25729
+ var DEFAULT_STATE_BYTES = 24;
25730
+ var OAUTH_DEVICE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
25731
+ var DEVICE_POLL_SLOW_DOWN_SECONDS = 5;
25732
+ function generatePkcePair() {
25733
+ const verifier = tokenUrlSafe(DEFAULT_PKCE_VERIFIER_BYTES);
25734
+ return {
25735
+ verifier,
25736
+ challenge: pkceChallengeS256(verifier),
25737
+ method: "S256"
25738
+ };
25739
+ }
25740
+ function generateOAuthState() {
25741
+ return tokenUrlSafe(DEFAULT_STATE_BYTES);
25742
+ }
25743
+ function pkceChallengeS256(verifier) {
25744
+ if (!isValidPkceVerifier(verifier)) {
25745
+ throw new CliError("PKCE code verifier must be 43-128 RFC7636 unreserved characters.");
25746
+ }
25747
+ return createHash2("sha256").update(verifier).digest("base64url");
25748
+ }
25749
+ function buildLoopbackRedirectUri(args) {
25750
+ const host = args.host.trim();
25751
+ if (host === "") {
25752
+ throw new CliError("Callback host cannot be empty.");
25753
+ }
25754
+ if (!Number.isInteger(args.port) || args.port < 1 || args.port > 65535) {
25755
+ throw new CliError("Callback port must be between 1 and 65535.");
25756
+ }
25757
+ const path = args.path ?? "/oauth/callback";
25758
+ const normalizedPath = path.startsWith("/") ? path : `/${path}`;
25759
+ return `http://${host}:${args.port}${normalizedPath}`;
25760
+ }
25761
+ function buildAuthorizationUrl(args) {
25762
+ const url2 = new URL(args.authorizationEndpoint);
25763
+ url2.searchParams.set("response_type", "code");
25764
+ url2.searchParams.set("client_id", args.clientId);
25765
+ url2.searchParams.set("redirect_uri", args.redirectUri);
25766
+ url2.searchParams.set("scope", args.scope);
25767
+ url2.searchParams.set("state", args.state);
25768
+ url2.searchParams.set("code_challenge", args.codeChallenge);
25769
+ url2.searchParams.set("code_challenge_method", "S256");
25770
+ if (args.resource !== undefined && args.resource.trim() !== "") {
25771
+ url2.searchParams.set("resource", args.resource);
25772
+ }
25773
+ return url2.toString();
25774
+ }
25775
+ function parseOAuthCallbackUrl(callbackUrl, expectedState, expectedIssuer, issuerRequired = false) {
25776
+ const url2 = new URL(callbackUrl);
25777
+ const state = url2.searchParams.get("state") ?? "";
25778
+ if (state === "" || state !== expectedState) {
25779
+ throw new CliError("OAuth callback state did not match.", {
25780
+ code: ExitCode.AuthRequired,
25781
+ errorCode: "oauth_state_mismatch"
25782
+ });
25783
+ }
25784
+ const issuers = url2.searchParams.getAll("iss");
25785
+ if (issuerRequired && issuers.length === 0 || issuers.length > 1 || issuers.length === 1 && issuers[0] !== expectedIssuer) {
25786
+ throw new CliError("OAuth callback issuer did not match the sign-in server.", {
25787
+ code: ExitCode.AuthRequired,
25788
+ errorCode: "oauth_issuer_mismatch"
25789
+ });
25790
+ }
25791
+ const error2 = url2.searchParams.get("error");
25792
+ if (error2 !== null && error2 !== "") {
25793
+ throw new CliError("OAuth authorization failed. Start sign-in again and approve access.", { code: ExitCode.AuthRequired, errorCode: "oauth_authorization_failed" });
25794
+ }
25795
+ const code = url2.searchParams.get("code") ?? "";
25796
+ if (code === "") {
25797
+ throw new CliError("OAuth callback did not include an authorization code.", {
25798
+ code: ExitCode.AuthRequired,
25799
+ errorCode: "oauth_missing_code"
25800
+ });
25801
+ }
25802
+ return { code, state };
25803
+ }
25804
+ async function resolveOAuthClientMetadata(args) {
25805
+ const clientId = `${normalizeApiUrl(args.apiUrl)}/oauth/client-metadata/uru-cli.json`;
25806
+ const response = await fetchOAuthGet({
25807
+ apiUrl: args.apiUrl,
25808
+ path: "/oauth/client-metadata/uru-cli.json",
25809
+ ...args.fetch === undefined ? {} : { fetch: args.fetch }
25810
+ });
25811
+ if (!isRecord(response)) {
25812
+ throw new CliError("Unexpected OAuth Client ID Metadata Document.");
25813
+ }
25814
+ const declaredClientId = stringField2(response, "client_id");
25815
+ if (declaredClientId !== clientId) {
25816
+ throw new CliError("OAuth Client ID Metadata Document did not match its URL.");
25817
+ }
25818
+ const redirectUris = response["redirect_uris"];
25819
+ if (!Array.isArray(redirectUris) || !redirectUris.some((value) => value === args.redirectUri)) {
25820
+ throw new CliError("OAuth Client ID Metadata Document did not allow this callback.");
25821
+ }
25822
+ return {
25823
+ clientId: declaredClientId,
25824
+ scope: optionalStringField(response, "scope") ?? "mcp offline_access"
25825
+ };
25826
+ }
25827
+ async function discoverOAuthIssuer(args) {
25828
+ const expectedIssuer = normalizeApiUrl(args.apiUrl);
25829
+ const metadata = await fetchOAuthGet({
25830
+ apiUrl: args.apiUrl,
25831
+ path: "/.well-known/oauth-authorization-server",
25832
+ ...args.fetch === undefined ? {} : { fetch: args.fetch }
25833
+ });
25834
+ if (!isRecord(metadata) || metadata["issuer"] !== expectedIssuer) {
25835
+ throw new CliError("OAuth discovery issuer did not match the sign-in server.", {
25836
+ code: ExitCode.AuthRequired,
25837
+ errorCode: "oauth_issuer_mismatch"
25838
+ });
25839
+ }
25840
+ return {
25841
+ issuer: expectedIssuer,
25842
+ issuerRequired: metadata["authorization_response_iss_parameter_supported"] === true
25843
+ };
25844
+ }
25845
+ async function discoverOAuthResource(args) {
25846
+ const response = await fetchOAuthGet({
25847
+ apiUrl: args.apiUrl,
25848
+ path: "/.well-known/oauth-protected-resource",
25849
+ ...args.fetch === undefined ? {} : { fetch: args.fetch }
25850
+ });
25851
+ if (!isRecord(response)) {
25852
+ throw new CliError("Unexpected OAuth protected-resource metadata response.");
25853
+ }
25854
+ const resource = stringField2(response, "resource");
25855
+ assertHttpUrl(resource, "OAuth protected resource");
25856
+ return resource;
25857
+ }
25858
+ async function exchangeAuthorizationCode(args) {
25859
+ const body = new URLSearchParams;
25860
+ body.set("grant_type", "authorization_code");
25861
+ body.set("client_id", args.clientId);
25862
+ body.set("code", args.code);
25863
+ body.set("redirect_uri", args.redirectUri);
25864
+ body.set("code_verifier", args.codeVerifier);
25865
+ if (args.resource !== undefined && args.resource.trim() !== "") {
25866
+ body.set("resource", args.resource);
25867
+ }
25868
+ const response = await fetchOAuthForm({
25869
+ apiUrl: args.apiUrl,
25870
+ path: "/oauth/token",
25871
+ body,
25872
+ ...args.fetch === undefined ? {} : { fetch: args.fetch }
25873
+ });
25874
+ return toOAuthTokenResponse(zOAuthTokenResponse.parse(response));
25875
+ }
25876
+ async function refreshOAuthToken(args) {
25877
+ const body = new URLSearchParams;
25878
+ body.set("grant_type", "refresh_token");
25879
+ body.set("client_id", args.clientId);
25880
+ body.set("refresh_token", args.refreshToken);
25881
+ body.set("resource", args.resource);
25882
+ const response = await fetchOAuthForm({
25883
+ apiUrl: args.apiUrl,
25884
+ path: "/oauth/token",
25885
+ body,
25886
+ rejectedGrantErrorCode: "oauth_refresh_invalid",
25887
+ ...args.fetch === undefined ? {} : { fetch: args.fetch }
25888
+ });
25889
+ return toOAuthTokenResponse(zOAuthTokenResponse.parse(response));
25890
+ }
25891
+ async function revokeOAuthToken(args) {
25892
+ const body = new URLSearchParams;
25893
+ body.set("token", args.token);
25894
+ body.set("token_type_hint", "refresh_token");
25895
+ body.set("client_id", args.clientId);
25896
+ await fetchOAuthForm({
25897
+ apiUrl: args.apiUrl,
25898
+ path: "/oauth/revoke",
25899
+ body,
25900
+ ...args.fetch === undefined ? {} : { fetch: args.fetch }
25901
+ });
25902
+ }
25903
+ async function exchangeOAuthForCliSession(args) {
25904
+ const body = {};
25905
+ if (args.workspaceId !== undefined && args.workspaceId.trim() !== "") {
25906
+ body["workspace_id"] = args.workspaceId;
25907
+ }
25908
+ const response = await fetchOAuthJson({
25909
+ apiUrl: args.apiUrl,
25910
+ path: "/api/oauth/cli-session",
25911
+ body,
25912
+ authorization: `Bearer ${args.oauthAccessToken}`,
25913
+ ...args.fetch === undefined ? {} : { fetch: args.fetch }
25914
+ });
25915
+ return toCliSessionResponse(zCliSessionResponse.parse(response));
25916
+ }
25917
+ async function startDeviceAuthorization(args) {
25918
+ const body = new URLSearchParams;
25919
+ body.set("client_id", args.clientId);
25920
+ body.set("scope", args.scope);
25921
+ if (args.resource !== undefined && args.resource.trim() !== "") {
25922
+ body.set("resource", args.resource);
25923
+ }
25924
+ const response = await fetchOAuthForm({
25925
+ apiUrl: args.apiUrl,
25926
+ path: "/oauth/device/code",
25927
+ body,
25928
+ ...args.fetch === undefined ? {} : { fetch: args.fetch }
25929
+ });
25930
+ return toDeviceAuthorization(zDeviceAuthorizationResponse.parse(response));
25931
+ }
25932
+ async function pollDeviceToken(args) {
25933
+ let intervalSeconds = Math.max(1, args.intervalSeconds);
25934
+ const sleep = args.sleep ?? ((milliseconds) => sleepTimer(milliseconds, undefined, { signal: args.signal }));
25935
+ for (let attempt = 0;attempt < args.maxPolls; attempt += 1) {
25936
+ args.signal?.throwIfAborted();
25937
+ if (attempt > 0) {
25938
+ await sleep(intervalSeconds * 1000);
25939
+ }
25940
+ const body = new URLSearchParams;
25941
+ body.set("grant_type", OAUTH_DEVICE_GRANT_TYPE);
25942
+ body.set("client_id", args.clientId);
25943
+ body.set("device_code", args.deviceCode);
25944
+ const response = await fetchOAuthForm({
25945
+ apiUrl: args.apiUrl,
25946
+ path: "/oauth/token",
25947
+ body,
25948
+ allowOAuthError: true,
25949
+ ...args.fetch === undefined ? {} : { fetch: args.fetch }
25950
+ });
25951
+ if (isRecord(response) && typeof response["error"] === "string") {
25952
+ const error2 = response["error"];
25953
+ if (error2 === "authorization_pending") {
25954
+ continue;
25955
+ }
25956
+ if (error2 === "slow_down") {
25957
+ intervalSeconds += DEVICE_POLL_SLOW_DOWN_SECONDS;
25958
+ continue;
25959
+ }
25960
+ throw new CliError(`OAuth device login failed: ${error2}`, {
25961
+ code: ExitCode.AuthRequired,
25962
+ errorCode: "oauth_device_failed"
25963
+ });
25964
+ }
25965
+ args.signal?.throwIfAborted();
25966
+ return toOAuthTokenResponse(zOAuthTokenResponse.parse(response));
25967
+ }
25968
+ throw new CliError("OAuth device login timed out before authorization completed.", {
25969
+ code: ExitCode.AuthRequired,
25970
+ errorCode: "oauth_device_timeout"
25971
+ });
25972
+ }
25973
+ async function fetchOAuthJson(args) {
25974
+ const fetchImpl = args.fetch ?? fetch;
25975
+ const response = await fetchImpl(oauthEndpoint(args.apiUrl, args.path), {
25976
+ method: "POST",
25977
+ signal: AbortSignal.timeout(30000),
25978
+ headers: {
25979
+ Accept: "application/json",
25980
+ "Content-Type": "application/json",
25981
+ ...args.authorization === undefined ? {} : { Authorization: args.authorization }
25982
+ },
25983
+ body: JSON.stringify(args.body)
25984
+ });
25985
+ const payload = parseJsonResponse(await response.text());
25986
+ if (!response.ok) {
25987
+ throw new CliError(errorMessage2(payload) ?? `OAuth request failed: HTTP ${response.status}`, {
25988
+ code: response.status === 401 || response.status === 403 || response.status === 409 ? ExitCode.AuthRequired : ExitCode.Failure,
25989
+ errorCode: "oauth_request_failed"
25990
+ });
25991
+ }
25992
+ return payload;
25993
+ }
25994
+ async function fetchOAuthGet(args) {
25995
+ const fetchImpl = args.fetch ?? fetch;
25996
+ const response = await fetchImpl(oauthEndpoint(args.apiUrl, args.path), {
25997
+ method: "GET",
25998
+ signal: AbortSignal.timeout(30000),
25999
+ headers: { Accept: "application/json" }
26000
+ });
26001
+ const payload = parseJsonResponse(await response.text());
26002
+ if (!response.ok) {
26003
+ throw oauthHttpError(response.status, payload);
26004
+ }
26005
+ return payload;
26006
+ }
26007
+ function tokenUrlSafe(byteLength) {
26008
+ return randomBytes(byteLength).toString("base64url");
26009
+ }
26010
+ function isValidPkceVerifier(verifier) {
26011
+ return /^[A-Za-z0-9._~-]{43,128}$/.test(verifier);
26012
+ }
26013
+ async function fetchOAuthForm(args) {
26014
+ const fetchImpl = args.fetch ?? fetch;
26015
+ const response = await fetchImpl(oauthEndpoint(args.apiUrl, args.path), {
26016
+ method: "POST",
26017
+ signal: AbortSignal.timeout(30000),
26018
+ headers: {
26019
+ Accept: "application/json",
26020
+ "Content-Type": "application/x-www-form-urlencoded"
26021
+ },
26022
+ body: args.body.toString()
26023
+ });
26024
+ const payload = parseJsonResponse(await response.text());
26025
+ if (!response.ok && !(args.allowOAuthError === true && isOAuthError(payload))) {
26026
+ throw oauthHttpError(response.status, payload, args.rejectedGrantErrorCode);
26027
+ }
26028
+ return payload;
26029
+ }
26030
+ function oauthEndpoint(apiUrl, path) {
26031
+ let endpoint;
26032
+ try {
26033
+ endpoint = new URL(normalizeApiUrl(apiUrl));
26034
+ } catch (error2) {
26035
+ throw invalidOAuthApiUrl(error2);
26036
+ }
26037
+ if (endpoint.username !== "" || endpoint.password !== "" || endpoint.search !== "" || endpoint.hash !== "" || endpoint.protocol !== "https:" && !(endpoint.protocol === "http:" && isLoopbackHostname(endpoint.hostname))) {
26038
+ throw invalidOAuthApiUrl();
26039
+ }
26040
+ endpoint.pathname = `${endpoint.pathname.replace(/\/$/u, "")}${path}`;
26041
+ return endpoint;
26042
+ }
26043
+ function isLoopbackHostname(hostname) {
26044
+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]";
26045
+ }
26046
+ function invalidOAuthApiUrl(cause) {
26047
+ return new CliError("OAuth API URL must use HTTPS, except for a local loopback server.", {
26048
+ code: ExitCode.AuthRequired,
26049
+ errorCode: "oauth_invalid_api_url",
26050
+ ...cause === undefined ? {} : { cause }
26051
+ });
26052
+ }
26053
+ function parseJsonResponse(text) {
26054
+ if (text.trim() === "") {
26055
+ return null;
26056
+ }
26057
+ const parsed = JSON.parse(text);
26058
+ if (!isJsonValue2(parsed)) {
26059
+ throw new CliError("OAuth endpoint returned non-JSON data.", {
26060
+ errorCode: "oauth_invalid_response"
26061
+ });
26062
+ }
26063
+ return parsed;
26064
+ }
26065
+ function isJsonValue2(value) {
26066
+ if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
26067
+ return true;
26068
+ }
26069
+ if (Array.isArray(value)) {
26070
+ return value.every(isJsonValue2);
26071
+ }
26072
+ if (isRecord(value)) {
26073
+ return Object.values(value).every(isJsonValue2);
26074
+ }
26075
+ return false;
26076
+ }
26077
+ function isOAuthError(value) {
26078
+ return isRecord(value) && typeof value["error"] === "string";
26079
+ }
26080
+ function toCliSessionResponse(response) {
26081
+ return {
26082
+ accessToken: response.access_token,
26083
+ tokenType: response.token_type,
26084
+ expiresIn: response.expires_in,
26085
+ oauthResource: response.oauth_resource,
26086
+ ...response.workspace_id.trim() === "" ? {} : { workspaceId: response.workspace_id }
26087
+ };
26088
+ }
26089
+ function toDeviceAuthorization(response) {
26090
+ return {
26091
+ deviceCode: response.device_code,
26092
+ userCode: response.user_code,
26093
+ verificationUri: response.verification_uri,
26094
+ verificationUriComplete: response.verification_uri_complete,
26095
+ expiresIn: response.expires_in,
26096
+ interval: response.interval
26097
+ };
26098
+ }
26099
+ function toOAuthTokenResponse(response) {
26100
+ return {
26101
+ accessToken: response.access_token,
26102
+ tokenType: response.token_type,
26103
+ expiresIn: response.expires_in,
26104
+ refreshToken: response.refresh_token,
26105
+ scope: response.scope
26106
+ };
26107
+ }
26108
+ function oauthHttpError(status, payload, rejectedGrantErrorCode) {
26109
+ const oauthError = isRecord(payload) && typeof payload["error"] === "string" ? payload["error"] : null;
26110
+ const authRequired = status === 400 || status === 401 || status === 403 || status === 409;
26111
+ const grantRejected = rejectedGrantErrorCode !== undefined && (oauthError === "invalid_grant" || oauthError === "invalid_target" || oauthError === "invalid_client");
26112
+ return new CliError(errorMessage2(payload) ?? `OAuth request failed: HTTP ${status}`, {
26113
+ code: authRequired ? ExitCode.AuthRequired : ExitCode.Failure,
26114
+ errorCode: grantRejected ? rejectedGrantErrorCode : "oauth_request_failed"
26115
+ });
26116
+ }
26117
+ function assertHttpUrl(value, label) {
26118
+ let url2;
26119
+ try {
26120
+ url2 = new URL(value);
26121
+ } catch (error2) {
26122
+ throw new CliError(`${label} is not a valid URL.`, {
26123
+ errorCode: "oauth_invalid_response",
26124
+ cause: error2
26125
+ });
26126
+ }
26127
+ const loopbackHostname = url2.hostname === "localhost" || url2.hostname === "127.0.0.1" || url2.hostname === "[::1]";
26128
+ if (url2.protocol !== "https:" && !(url2.protocol === "http:" && loopbackHostname)) {
26129
+ throw new CliError(`${label} must use HTTPS except on loopback.`, {
26130
+ errorCode: "oauth_invalid_response"
26131
+ });
26132
+ }
26133
+ }
26134
+ function stringField2(value, key) {
26135
+ const field = value[key];
26136
+ if (typeof field !== "string" || field.trim() === "") {
26137
+ throw new CliError(`OAuth response missing ${key}.`);
26138
+ }
26139
+ return field;
26140
+ }
26141
+ function optionalStringField(value, key) {
26142
+ const field = value[key];
26143
+ return typeof field === "string" && field.trim() !== "" ? field : undefined;
26144
+ }
26145
+ function errorMessage2(payload) {
26146
+ if (!isRecord(payload)) {
26147
+ return;
26148
+ }
26149
+ const error2 = payload["error"];
26150
+ switch (error2) {
26151
+ case "access_denied":
26152
+ return "Authorization was denied. Start sign-in again.";
26153
+ case "invalid_grant":
26154
+ return "Authorization expired or was revoked. Sign in again.";
26155
+ case "invalid_client":
26156
+ return "The sign-in client is not accepted by the server.";
26157
+ case "expired_token":
26158
+ return "The sign-in request expired. Start sign-in again.";
26159
+ case "temporarily_unavailable":
26160
+ return "The sign-in service is temporarily unavailable.";
26161
+ default:
26162
+ return;
26163
+ }
26164
+ }
26165
+
26166
+ // src/auth-commands.ts
26167
+ var DEVICE_MAX_POLLS = 120;
26168
+ var CIMD_CALLBACK_PORT = 8765;
26169
+ function configLoginAuthority(config2) {
26170
+ return {
26171
+ apiUrl: config2.apiUrl === undefined ? undefined : normalizeApiUrl(config2.apiUrl),
26172
+ token: config2.token,
26173
+ insecureStorage: config2.insecureStorage === true
26174
+ };
26175
+ }
26176
+ function sameConfigLoginAuthority(left, right) {
26177
+ return left.apiUrl === right.apiUrl && left.token === right.token && left.insecureStorage === right.insecureStorage;
26178
+ }
26179
+ function configLoginBelongsToApi(config2, apiUrl) {
26180
+ return normalizeApiUrl(config2.apiUrl ?? DEFAULT_API_URL) === normalizeApiUrl(apiUrl);
26181
+ }
26182
+ function selectStoredLoginValue(config2, apiUrl, keychainValue) {
26183
+ if (config2.insecureStorage === true && configLoginBelongsToApi(config2, apiUrl)) {
26184
+ return { source: "config", value: config2.token };
26185
+ }
26186
+ return {
26187
+ source: keychainValue === undefined ? "none" : "keychain",
26188
+ value: keychainValue
26189
+ };
26190
+ }
26191
+ async function readStoredLoginValueForConfig(args) {
26192
+ const keychainValue = args.config.insecureStorage === true && configLoginBelongsToApi(args.config, args.apiUrl) ? undefined : await args.credentialStore.readToken(args.apiUrl);
26193
+ return selectStoredLoginValue(args.config, args.apiUrl, keychainValue);
26194
+ }
26195
+ async function resolveStoredToken(options) {
26196
+ const stored = await readStoredLoginValueForConfig({
26197
+ credentialStore: options.credentialStore,
26198
+ apiUrl: options.apiUrl,
26199
+ config: options.config
26200
+ });
26201
+ const source = stored.source === "none" ? "config" : stored.source;
26202
+ const storedValue = stored.value;
26203
+ if (storedValue === undefined) {
26204
+ return;
26205
+ }
26206
+ let credential;
26207
+ try {
26208
+ credential = parseStoredCliOAuthCredential(storedValue);
26209
+ } catch (error2) {
26210
+ if (options.recoverInvalidCredential === true) {
26211
+ return;
26212
+ }
26213
+ throw error2;
26214
+ }
26215
+ if (credential === null) {
26216
+ return storedValue;
26217
+ }
26218
+ if (!cliOAuthCredentialNeedsRefresh(credential, Date.now(), {
26219
+ ...options.forceRefresh === undefined ? {} : { forceRefresh: options.forceRefresh }
26220
+ })) {
26221
+ return credential.sessionAccessToken;
26222
+ }
26223
+ try {
26224
+ const refreshed = await refreshOAuthToken({
26225
+ apiUrl: options.apiUrl,
26226
+ clientId: credential.oauthClientId,
26227
+ refreshToken: credential.oauthRefreshToken,
26228
+ resource: credential.oauthResource,
26229
+ ...options.fetch === undefined ? {} : { fetch: options.fetch }
26230
+ });
26231
+ const rotatedRefreshToken = requireRefreshToken(refreshed);
26232
+ let sessionTransitionPending = true;
26233
+ try {
26234
+ const nextCredential = await exchangeRefreshedCliCredential({
26235
+ apiUrl: options.apiUrl,
26236
+ oauthAccessToken: refreshed.accessToken,
26237
+ oauthRefreshToken: rotatedRefreshToken,
26238
+ oauthClientId: credential.oauthClientId,
26239
+ oauthResource: credential.oauthResource,
26240
+ ...options.workspaceId === undefined ? {} : { workspaceId: options.workspaceId },
26241
+ ...options.fetch === undefined ? {} : { fetch: options.fetch }
26242
+ });
26243
+ sessionTransitionPending = false;
26244
+ await persistMcpGrantIfCurrent(options, source, storedValue, serializeStoredCliOAuthCredential(nextCredential));
26245
+ return nextCredential.sessionAccessToken;
26246
+ } catch (error2) {
26247
+ if (sessionTransitionPending) {
26248
+ try {
26249
+ await persistMcpGrantIfCurrent(options, source, storedValue, serializeStoredCliOAuthCredential(credentialWithExpiredSession(credential, rotatedRefreshToken)));
26250
+ } catch (recoveryError) {
26251
+ throw preserveCredentialFailure(error2, recoveryError);
26252
+ }
26253
+ }
26254
+ throw error2;
26255
+ }
26256
+ } catch (error2) {
26257
+ if (!isStoredRefreshRejected(error2)) {
26258
+ throw error2;
26259
+ }
26260
+ try {
26261
+ await clearMcpGrantIfCurrent(options, source, storedValue);
26262
+ } catch (recoveryError) {
26263
+ throw preserveCredentialFailure(error2, recoveryError);
26264
+ }
26265
+ return;
26266
+ }
26267
+ }
26268
+ async function resolveMcpCallBearer(ctx, mcpUrl, expectedSessionAccessToken) {
26269
+ if (ctx.token === undefined) {
26270
+ throw new CliError("Authentication required. Run `uru login` first.", {
26271
+ code: ExitCode.AuthRequired
26272
+ });
26273
+ }
26274
+ if (ctx.tokenIsExplicit || ctx.token.startsWith("uru_")) {
26275
+ return {
26276
+ token: ctx.token,
26277
+ expiresAtMs: null,
26278
+ sessionAccessToken: ctx.token
26279
+ };
26280
+ }
26281
+ const currentConfig = await ctx.store.read();
26282
+ const options = {
26283
+ credentialStore: ctx.credentialStore,
26284
+ store: ctx.store,
26285
+ apiUrl: ctx.apiUrl,
26286
+ config: currentConfig,
26287
+ abortSignal: ctx.abortSignal,
26288
+ ...ctx.workspace === undefined ? {} : { workspaceId: ctx.workspace },
26289
+ ...ctx.fetch === undefined ? {} : { fetch: ctx.fetch }
26290
+ };
26291
+ const stored = await readStoredLoginValueForConfig({
26292
+ credentialStore: ctx.credentialStore,
26293
+ apiUrl: ctx.apiUrl,
26294
+ config: currentConfig
26295
+ });
26296
+ const source = stored.source === "none" ? "config" : stored.source;
26297
+ const storedValue = stored.value;
26298
+ const credential = storedValue === undefined ? null : parseStoredCliOAuthCredential(storedValue);
26299
+ if (storedValue === undefined || credential === null) {
26300
+ throw new CliError("The saved CLI login has no MCP grant. Run `uru login` again.", {
26301
+ code: ExitCode.AuthRequired,
26302
+ errorCode: "auth_required"
26303
+ });
26304
+ }
26305
+ const expectedToken = expectedSessionAccessToken ?? ctx.token;
26306
+ if (expectedToken === undefined || credential.sessionAccessToken !== expectedToken) {
26307
+ throw new CliError("The saved CLI sign-in changed. Retry the command.", {
26308
+ code: ExitCode.AuthRequired,
26309
+ errorCode: "auth_required"
26310
+ });
26311
+ }
26312
+ if (credential.oauthResource !== mcpUrl) {
26313
+ throw new CliError("The saved MCP grant is for a different proxy URL.", {
26314
+ code: ExitCode.AuthRequired,
26315
+ errorCode: "oauth_resource_mismatch"
26316
+ });
26317
+ }
26318
+ let rotatedRefreshToken;
26319
+ let sessionTransitionPending = false;
26320
+ try {
26321
+ const refreshed = await refreshOAuthToken({
26322
+ apiUrl: ctx.apiUrl,
26323
+ clientId: credential.oauthClientId,
26324
+ refreshToken: credential.oauthRefreshToken,
26325
+ resource: credential.oauthResource,
26326
+ fetch: loginFetch(ctx)
26327
+ });
26328
+ rotatedRefreshToken = requireRefreshToken(refreshed);
26329
+ sessionTransitionPending = true;
26330
+ const nextCredential = await exchangeRefreshedCliCredential({
26331
+ apiUrl: ctx.apiUrl,
26332
+ oauthAccessToken: refreshed.accessToken,
26333
+ oauthRefreshToken: rotatedRefreshToken,
26334
+ oauthClientId: credential.oauthClientId,
26335
+ oauthResource: credential.oauthResource,
26336
+ ...ctx.workspace === undefined ? {} : { workspaceId: ctx.workspace },
26337
+ fetch: loginFetch(ctx)
26338
+ });
26339
+ sessionTransitionPending = false;
26340
+ await persistMcpGrantIfCurrent(options, source, storedValue, serializeStoredCliOAuthCredential(nextCredential));
26341
+ return {
26342
+ token: refreshed.accessToken,
26343
+ expiresAtMs: Date.now() + (refreshed.expiresIn ?? 0) * 1000,
26344
+ sessionAccessToken: nextCredential.sessionAccessToken
26345
+ };
26346
+ } catch (error2) {
26347
+ if (isStoredRefreshRejected(error2)) {
26348
+ try {
26349
+ await clearMcpGrantIfCurrent(options, source, storedValue);
26350
+ } catch (recoveryError) {
26351
+ throw preserveCredentialFailure(error2, recoveryError);
26352
+ }
26353
+ } else if (sessionTransitionPending && rotatedRefreshToken !== undefined) {
26354
+ try {
26355
+ await persistMcpGrantIfCurrent(options, source, storedValue, serializeStoredCliOAuthCredential(credentialWithExpiredSession(credential, rotatedRefreshToken)));
26356
+ } catch (recoveryError) {
26357
+ throw preserveCredentialFailure(error2, recoveryError);
26358
+ }
25398
26359
  }
25399
26360
  throw error2;
25400
26361
  }
25401
26362
  }
26363
+ async function captureStoredOAuthLogin(args) {
26364
+ const stored = await readStoredLoginValueForConfig(args);
26365
+ return {
26366
+ config: args.config,
26367
+ configAuthority: configLoginAuthority(args.config),
26368
+ source: stored.source,
26369
+ storedValue: stored.value,
26370
+ keychainValue: stored.source === "keychain" ? stored.value : undefined
26371
+ };
26372
+ }
26373
+ async function clearStoredOAuthLoginIfCurrent(args) {
26374
+ const config2 = await args.store.read();
26375
+ const configMatches = sameConfigLoginAuthority(configLoginAuthority(config2), args.expectedConfigAuthority);
26376
+ if (args.source === "config") {
26377
+ if (!configMatches || !configLoginBelongsToApi(config2, args.apiUrl) || config2.token !== args.expectedStoredValue) {
26378
+ return false;
26379
+ }
26380
+ assertNotAborted(args.abortSignal);
26381
+ await args.store.clear();
26382
+ return true;
26383
+ }
26384
+ const keychainValue = await args.credentialStore.readToken(args.apiUrl);
26385
+ if (keychainValue !== args.expectedStoredValue)
26386
+ return false;
26387
+ const clearConfig = configMatches && configLoginBelongsToApi(config2, args.apiUrl);
26388
+ if (!configMatches && keychainValue === undefined)
26389
+ return false;
26390
+ assertNotAborted(args.abortSignal);
26391
+ if (keychainValue !== undefined) {
26392
+ await args.credentialStore.clearToken(args.apiUrl);
26393
+ }
26394
+ if (clearConfig) {
26395
+ await args.store.clear();
26396
+ }
26397
+ return true;
26398
+ }
25402
26399
  async function revokeStoredOAuthLogin(args) {
25403
- const storedValue = await args.credentialStore.readToken(args.apiUrl) ?? (args.config.insecureStorage === true ? args.config.token : undefined);
26400
+ const storedValue = args.storedValue;
25404
26401
  if (storedValue === undefined) {
25405
26402
  return;
25406
26403
  }
@@ -25459,7 +26456,23 @@ async function resolveFlagToken(flags, stdin) {
25459
26456
  }
25460
26457
  async function login(ctx, options = {}) {
25461
26458
  const existingToken = ctx.token === undefined || ctx.token.trim() === "" ? undefined : ctx.token;
25462
- const existingStoredValue = existingToken !== undefined && !ctx.tokenIsExplicit ? await readStoredLoginValue(ctx) : undefined;
26459
+ let existingStoredLogin = existingToken !== undefined && !ctx.tokenIsExplicit ? await captureStoredOAuthLogin({
26460
+ credentialStore: ctx.credentialStore,
26461
+ apiUrl: ctx.apiUrl,
26462
+ config: ctx.config
26463
+ }) : undefined;
26464
+ if (existingStoredLogin?.source === "config" && !ctx.insecureStorage) {
26465
+ existingStoredLogin = {
26466
+ ...existingStoredLogin,
26467
+ keychainValue: await ctx.credentialStore.readToken(ctx.apiUrl)
26468
+ };
26469
+ }
26470
+ const existingStoredValue = existingStoredLogin?.storedValue;
26471
+ if (existingStoredLogin !== undefined) {
26472
+ const savedSessionToken = parseStoredCliOAuthCredential(existingStoredValue ?? "")?.sessionAccessToken ?? existingStoredValue;
26473
+ if (savedSessionToken !== existingToken)
26474
+ throw changedMcpGrantError();
26475
+ }
25463
26476
  let usedExistingToken = existingToken !== undefined;
25464
26477
  let loginToken = existingToken === undefined ? await obtainLoginSessionToken(ctx) : {
25465
26478
  accessToken: existingToken,
@@ -25478,7 +26491,7 @@ async function login(ctx, options = {}) {
25478
26491
  result = await validateSessionToken(ctx, loginToken.accessToken);
25479
26492
  }
25480
26493
  const selectedWorkspace = result.workspaceId;
25481
- await persistLoginToken(ctx, loginToken.storedValue, selectedWorkspace);
26494
+ await persistLoginToken(ctx, loginToken.storedValue, selectedWorkspace, usedExistingToken ? existingStoredLogin : undefined);
25482
26495
  if (options.silentSuccess === true) {
25483
26496
  return;
25484
26497
  }
@@ -25497,9 +26510,6 @@ async function login(ctx, options = {}) {
25497
26510
  writeText(ctx.io, paint(visualFromTerminal(ctx.terminal, ctx.outputFormat), "green", ctx.insecureStorage ? "Logged in (token stored in local config)" : "Logged in"));
25498
26511
  }
25499
26512
  }
25500
- async function readStoredLoginValue(ctx) {
25501
- return await ctx.credentialStore.readToken(ctx.apiUrl) ?? (ctx.config.insecureStorage === true ? ctx.config.token : undefined);
25502
- }
25503
26513
  async function validateSessionToken(ctx, token) {
25504
26514
  const leftoverWorkspace = ctx.config.workspace;
25505
26515
  const requestedWorkspace = ctx.workspace;
@@ -25668,29 +26678,73 @@ async function exchangeOAuthTokenForSession(ctx, token, clientId, resource) {
25668
26678
  storedValue: serializeStoredCliOAuthCredential(credential)
25669
26679
  };
25670
26680
  }
25671
- async function persistLoginToken(ctx, token, selectedWorkspace) {
25672
- const nextConfig = loginConfigWithoutLeftoverWorkspace(ctx, selectedWorkspace);
25673
- if (ctx.insecureStorage) {
25674
- await ctx.store.write({
25675
- ...nextConfig,
25676
- token,
25677
- insecureStorage: true
26681
+ async function persistLoginToken(ctx, token, selectedWorkspace, expectedLogin) {
26682
+ await withCredentialLock(dirname3(ctx.store.path), ctx.apiUrl, async () => {
26683
+ const currentConfig = await ctx.store.read();
26684
+ if (expectedLogin !== undefined) {
26685
+ const keychainValue = expectedLogin.source === "config" && ctx.insecureStorage ? undefined : await ctx.credentialStore.readToken(ctx.apiUrl);
26686
+ if (!sameConfigLoginAuthority(configLoginAuthority(currentConfig), expectedLogin.configAuthority) || keychainValue !== expectedLogin.keychainValue) {
26687
+ throw changedMcpGrantError();
26688
+ }
26689
+ }
26690
+ const nextConfig = loginConfigWithoutLeftoverWorkspace(currentConfig, ctx.apiUrl, selectedWorkspace);
26691
+ if (ctx.insecureStorage) {
26692
+ assertNotAborted(ctx.abortSignal);
26693
+ await ctx.store.write({
26694
+ ...nextConfig,
26695
+ token,
26696
+ insecureStorage: true
26697
+ });
26698
+ if (expectedLogin?.source !== "config") {
26699
+ await ctx.credentialStore.clearToken(ctx.apiUrl);
26700
+ }
26701
+ return;
26702
+ }
26703
+ assertNotAborted(ctx.abortSignal);
26704
+ await ctx.credentialStore.writeToken(ctx.apiUrl, token);
26705
+ await ctx.store.write(nextConfig);
26706
+ }, ctx.abortSignal);
26707
+ }
26708
+ function preserveCredentialFailure(original, recovery) {
26709
+ const cause = new AggregateError([original, recovery], "Stored CLI credential recovery failed.");
26710
+ if (original instanceof CliError) {
26711
+ return new CliError(original.message, {
26712
+ code: original.exitCode,
26713
+ errorCode: original.errorCode,
26714
+ cause,
26715
+ ...original.errorId === undefined ? {} : { errorId: original.errorId },
26716
+ ...original.httpStatus === undefined ? {} : { httpStatus: original.httpStatus },
26717
+ ...original.confirmationRequired === true ? { confirmationRequired: true } : {},
26718
+ ...original.suggestedCommand === undefined ? {} : { suggestedCommand: original.suggestedCommand },
26719
+ ...original.retryable === true ? { retryable: true } : {},
26720
+ ...original.tip === undefined ? {} : { tip: original.tip },
26721
+ ...original.details === undefined ? {} : { details: original.details }
25678
26722
  });
25679
- return;
25680
26723
  }
25681
- await ctx.credentialStore.writeToken(ctx.apiUrl, token);
25682
- await ctx.store.write(nextConfig);
26724
+ const normalized = normalizeError(original);
26725
+ if (normalized.exitCode === ExitCode.Cancelled) {
26726
+ return new CliError(normalized.message, {
26727
+ code: normalized.exitCode,
26728
+ errorCode: normalized.errorCode,
26729
+ cause
26730
+ });
26731
+ }
26732
+ return new CliError("Authentication failed and the saved CLI login could not be updated.", {
26733
+ code: ExitCode.AuthRequired,
26734
+ errorCode: "auth_required",
26735
+ cause
26736
+ });
25683
26737
  }
25684
- function loginConfigWithoutLeftoverWorkspace(ctx, selectedWorkspace) {
26738
+ function loginConfigWithoutLeftoverWorkspace(config2, apiUrl, selectedWorkspace) {
25685
26739
  const {
25686
26740
  token: _token,
25687
26741
  insecureStorage: _insecureStorage,
25688
26742
  workspace: _leftoverWorkspace,
25689
26743
  ...safeConfig
25690
- } = ctx.config;
26744
+ } = config2;
25691
26745
  return {
25692
26746
  ...safeConfig,
25693
- apiUrl: ctx.apiUrl,
26747
+ apiUrl,
25694
26748
  ...selectedWorkspace !== undefined ? { workspace: selectedWorkspace } : {}
25695
26749
  };
25696
26750
  }
@@ -25704,6 +26758,35 @@ function requireRefreshToken(token) {
25704
26758
  }
25705
26759
  return refreshToken;
25706
26760
  }
26761
+ async function exchangeRefreshedCliCredential(args) {
26762
+ const session = await exchangeOAuthForCliSession({
26763
+ apiUrl: args.apiUrl,
26764
+ oauthAccessToken: args.oauthAccessToken,
26765
+ ...args.workspaceId === undefined ? {} : { workspaceId: args.workspaceId },
26766
+ ...args.fetch === undefined ? {} : { fetch: args.fetch }
26767
+ });
26768
+ if (session.oauthResource !== args.oauthResource) {
26769
+ throw new CliError("Refreshed CLI session OAuth resource did not match the stored credential.", {
26770
+ code: ExitCode.AuthRequired,
26771
+ errorCode: "oauth_resource_mismatch"
26772
+ });
26773
+ }
26774
+ return createStoredCliOAuthCredential({
26775
+ sessionAccessToken: session.accessToken,
26776
+ sessionExpiresIn: session.expiresIn,
26777
+ oauthRefreshToken: args.oauthRefreshToken,
26778
+ oauthClientId: args.oauthClientId,
26779
+ oauthResource: session.oauthResource,
26780
+ ...session.workspaceId === undefined ? {} : { workspaceId: session.workspaceId }
26781
+ });
26782
+ }
26783
+ function credentialWithExpiredSession(credential, oauthRefreshToken) {
26784
+ return {
26785
+ ...credential,
26786
+ oauthRefreshToken,
26787
+ sessionExpiresAt: Math.max(1, Date.now())
26788
+ };
26789
+ }
25707
26790
  async function persistResolvedCredential(options, source, storedValue) {
25708
26791
  if (source === "keychain") {
25709
26792
  await options.credentialStore.writeToken(options.apiUrl, storedValue);
@@ -25716,10 +26799,14 @@ async function persistResolvedCredential(options, source, storedValue) {
25716
26799
  insecureStorage: true
25717
26800
  });
25718
26801
  }
25719
- async function currentMcpGrant(options, source) {
26802
+ async function currentMcpGrant(options) {
25720
26803
  const config2 = await options.store.read();
25721
- const storedValue = source === "keychain" ? await options.credentialStore.readToken(options.apiUrl) : config2.insecureStorage === true ? config2.token : undefined;
25722
- return { config: config2, storedValue };
26804
+ const stored = await readStoredLoginValueForConfig({
26805
+ credentialStore: options.credentialStore,
26806
+ apiUrl: options.apiUrl,
26807
+ config: config2
26808
+ });
26809
+ return { config: config2, storedValue: stored.value };
25723
26810
  }
25724
26811
  function changedMcpGrantError() {
25725
26812
  return new CliError("The saved CLI sign-in changed. Retry the command.", {
@@ -25728,18 +26815,23 @@ function changedMcpGrantError() {
25728
26815
  });
25729
26816
  }
25730
26817
  async function persistMcpGrantIfCurrent(options, source, expectedValue, nextValue) {
25731
- const current = await currentMcpGrant(options, source);
25732
- if (current.storedValue !== expectedValue) {
25733
- throw changedMcpGrantError();
25734
- }
25735
- await persistResolvedCredential({ ...options, config: current.config }, source, nextValue);
26818
+ await withCredentialLock(dirname3(options.store.path), options.apiUrl, async () => {
26819
+ const current = await currentMcpGrant(options);
26820
+ if (!sameConfigLoginAuthority(configLoginAuthority(current.config), configLoginAuthority(options.config)) || current.storedValue !== expectedValue) {
26821
+ throw changedMcpGrantError();
26822
+ }
26823
+ await persistResolvedCredential({ ...options, config: current.config }, source, nextValue);
26824
+ });
25736
26825
  }
25737
26826
  async function clearMcpGrantIfCurrent(options, source, expectedValue) {
25738
- const current = await currentMcpGrant(options, source);
25739
- if (current.storedValue !== expectedValue) {
25740
- throw changedMcpGrantError();
25741
- }
25742
- await clearResolvedCredential({ ...options, config: current.config }, source);
26827
+ await withCredentialLock(dirname3(options.store.path), options.apiUrl, async () => {
26828
+ const current = await currentMcpGrant(options);
26829
+ if (!sameConfigLoginAuthority(configLoginAuthority(current.config), configLoginAuthority(options.config)) || current.storedValue !== expectedValue) {
26830
+ throw changedMcpGrantError();
26831
+ }
26832
+ assertNotAborted(options.abortSignal);
26833
+ await clearResolvedCredential({ ...options, config: current.config }, source);
26834
+ }, options.abortSignal);
25743
26835
  }
25744
26836
  async function clearResolvedCredential(options, source) {
25745
26837
  if (source === "keychain") {
@@ -25900,651 +26992,144 @@ function boundedIntegerFlag(flags, name, fallback, maximum) {
25900
26992
  }
25901
26993
  return Math.min(value, maximum);
25902
26994
  }
25903
- function parseLocalFlags(args, commandPath) {
25904
- const flagGrammar = localFlagGrammarFor(commandPath);
25905
- const values = {};
25906
- const booleans = new Set;
25907
- const positionals = [];
25908
- const occurrences = [];
25909
- let parsingFlags = true;
25910
- for (let index = 0;index < args.length; index += 1) {
25911
- const arg = args[index];
25912
- if (arg === undefined) {
25913
- continue;
25914
- }
25915
- if (parsingFlags && arg === "--") {
25916
- parsingFlags = false;
25917
- continue;
25918
- }
25919
- if (!parsingFlags || !arg.startsWith("-")) {
25920
- positionals.push(arg);
25921
- continue;
25922
- }
25923
- const parsedFlag = parseLocalFlagToken(arg, flagGrammar);
25924
- const flag = parsedFlag?.token ?? arg;
25925
- const inlineValue = parsedFlag?.inlineValue;
25926
- const flagSpec = parsedFlag?.spec;
25927
- if (flagSpec === undefined) {
25928
- const rejection = flagGrammar.rejected.get(flag);
25929
- if (rejection !== undefined) {
25930
- throw new CliError(rejection);
25931
- }
25932
- throw new CliError(`Unknown flag: ${flag}`);
25933
- }
25934
- if (flagSpec.value === "none") {
25935
- if (inlineValue !== undefined) {
25936
- throw new CliError(`${flag} does not take a value`);
25937
- }
25938
- booleans.add(flagSpec.token);
25939
- occurrences.push({ token: flagSpec.token });
25940
- continue;
25941
- }
25942
- if (inlineValue !== undefined) {
25943
- if (inlineValue === "") {
25944
- throw new CliError(`${flag} requires a value`);
25945
- }
25946
- assertEnumLocalFlagValue(flagSpec, inlineValue);
25947
- values[flagSpec.token] = inlineValue;
25948
- occurrences.push({ token: flagSpec.token, value: inlineValue });
25949
- continue;
25950
- }
25951
- const next = args[index + 1];
25952
- if (next !== undefined && next !== "--" && !next.startsWith("--")) {
25953
- assertEnumLocalFlagValue(flagSpec, next);
25954
- values[flagSpec.token] = next;
25955
- occurrences.push({ token: flagSpec.token, value: next });
25956
- index += 1;
25957
- continue;
25958
- }
25959
- throw new CliError(`${flag} requires a value`);
25960
- }
25961
- return Object.defineProperty({ values, booleans, positionals }, "occurrences", {
25962
- value: occurrences
25963
- });
25964
- }
25965
- function parseLocalFlagToken(arg, grammar) {
25966
- const equals = arg.indexOf("=");
25967
- const token = equals === -1 ? arg : arg.slice(0, equals);
25968
- const exact = grammar.accepted.get(token);
25969
- if (exact !== undefined) {
25970
- return {
25971
- token,
25972
- spec: exact,
25973
- ...equals === -1 ? {} : { inlineValue: arg.slice(equals + 1) }
25974
- };
25975
- }
25976
- for (const candidate of grammar.attachedValueTokens) {
25977
- if (arg.startsWith(candidate.token) && arg.length > candidate.token.length) {
25978
- return {
25979
- token: candidate.token,
25980
- spec: candidate.spec,
25981
- inlineValue: arg.slice(candidate.token.length)
25982
- };
25983
- }
25984
- }
25985
- return;
25986
- }
25987
- function assertEnumLocalFlagValue(spec2, value) {
25988
- if (spec2.value !== "one_of") {
25989
- return;
25990
- }
25991
- if (!spec2.values?.includes(value)) {
25992
- throw new CliError(`${spec2.token} must be one of ${spec2.values?.join(", ") ?? "the declared values"}.`);
25993
- }
25994
- }
25995
- function integerFlag(flags, name, fallback) {
25996
- const raw = flags.values[name];
25997
- if (raw === undefined) {
25998
- return fallback;
25999
- }
26000
- const value = Number.parseInt(raw, 10);
26001
- if (!Number.isFinite(value) || value < 0) {
26002
- throw new CliError(`${name} must be a non-negative integer`);
26003
- }
26004
- return value;
26005
- }
26006
- function copyStringFlag(flags, target, flagName, paramName) {
26007
- const value = flags.values[flagName];
26008
- if (value !== undefined) {
26009
- target[paramName] = value;
26010
- }
26011
- }
26012
- function isJsonRequested(argv) {
26013
- for (let index = 0;index < argv.length; index += 1) {
26014
- const arg = argv[index];
26015
- if (arg === "--json") {
26016
- return true;
26017
- }
26018
- if (arg === "--output-format=json" || arg === "--output-format=stream-json" || arg === "--output=json" || arg === "--output=stream-json") {
26019
- return true;
26020
- }
26021
- if (arg === "--output-format" || arg === "--output") {
26022
- const value = argv[index + 1];
26023
- if (value === "json" || value === "stream-json") {
26024
- return true;
26025
- }
26026
- }
26027
- }
26028
- return false;
26029
- }
26030
- function nonEmptyString(value) {
26031
- if (value === undefined) {
26032
- return;
26033
- }
26034
- const trimmed = value.trim();
26035
- return trimmed === "" ? undefined : trimmed;
26036
- }
26037
-
26038
- // src/cli-runtime.ts
26039
- import { dirname } from "node:path";
26040
-
26041
- // src/tool-failure-guidance.ts
26042
- async function explainToolFailure(input) {
26043
- const { error: error2, operation, params } = input;
26044
- if (error2.errorCode === "invalid_tool_arguments") {
26045
- const lines = invalidArgumentLines(operation, params, error2.details, await input.loadInputSchema());
26046
- return refineCliError(error2, {
26047
- ...lines.length === 0 ? {} : { message: `${error2.message} ${lines.join(" ")}` },
26048
- tip: `Run \`uru operations inspect ${operation.id}\` to read this operation's exact input schema, then send its field names unchanged.`
26049
- });
26050
- }
26051
- if (error2.retryable === true) {
26052
- return error2.tip === undefined ? refineCliError(error2, { tip: retryTip(operation, params) }) : error2;
26053
- }
26054
- return error2;
26055
- }
26056
- function retryTip(operation, params) {
26057
- if (operation.safety === "read") {
26058
- return "This failure is temporary. This operation only reads, so it is safe to run the same command again. Wait a few seconds first.";
26059
- }
26060
- const key = params["idempotency_key"];
26061
- if (typeof key === "string" && key !== "") {
26062
- 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.`;
26063
- }
26064
- 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.`;
26065
- }
26066
- function invalidArgumentLines(operation, params, details, schema) {
26067
- const fields = operationFields(schema);
26068
- const lines = [];
26069
- if (fields !== undefined) {
26070
- const missing = fields.required.filter((name) => name !== "op" && !Object.hasOwn(params, name));
26071
- const unknown2 = Object.keys(params).filter((name) => name !== "op" && !fields.properties.has(name));
26072
- if (missing.length > 0) {
26073
- lines.push(`Missing required fields: ${missing.join(", ")}.`);
26074
- }
26075
- if (unknown2.length > 0) {
26076
- lines.push(`Fields not in this operation's input schema: ${unknown2.join(", ")}.`);
26077
- }
26078
- }
26079
- const pathLine = mismatchPathLine(details, fields);
26080
- if (pathLine !== undefined) {
26081
- lines.push(pathLine);
26082
- }
26083
- return lines.length > 0 ? lines : serverReportLines(operation, details);
26084
- }
26085
- function operationFields(schema) {
26086
- const properties = schema?.["properties"];
26087
- if (schema === undefined || !isSchemaObject2(properties)) {
26088
- return;
26089
- }
26090
- const required3 = schema["required"];
26091
- return {
26092
- properties: new Set(Object.keys(properties)),
26093
- required: Array.isArray(required3) ? required3.filter((name) => typeof name === "string") : []
26094
- };
26095
- }
26096
- function mismatchPathLine(details, fields) {
26097
- const path = stringDetail(details, "first_mismatch_path");
26098
- const keyword = stringDetail(details, "first_mismatch_keyword");
26099
- if (path === undefined || path === "" || path === "/" || keyword === undefined) {
26100
- return;
26101
- }
26102
- const topField = path.split("/")[1];
26103
- if (fields !== undefined && (topField === undefined || !fields.properties.has(topField))) {
26104
- return;
26105
- }
26106
- const property = stringDetail(details, "first_mismatch_property");
26107
- return keyword === "required" && property !== undefined ? `Field ${path} is missing required field "${property}".` : `Field ${path} failed the schema rule "${keyword}".`;
26108
- }
26109
- function serverReportLines(operation, details) {
26110
- const lines = [];
26111
- const path = stringDetail(details, "first_mismatch_path");
26112
- const property = stringDetail(details, "first_mismatch_property");
26113
- if ((path === "/" || path === "") && stringDetail(details, "first_mismatch_keyword") === "required" && property !== undefined) {
26114
- lines.push(`First failing field: ${property} (required).`);
26115
- } else {
26116
- const pathLine = mismatchPathLine(details, undefined);
26117
- if (pathLine !== undefined) {
26118
- lines.push(pathLine);
26119
- }
26120
- }
26121
- const missing = details?.["missing_required"];
26122
- const missingNames = Array.isArray(missing) ? missing.filter((name) => typeof name === "string") : [];
26123
- if (missingNames.length > 0) {
26124
- 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(", ")}.`);
26125
- }
26126
- return lines;
26127
- }
26128
- function stringDetail(details, key) {
26129
- const value = details?.[key];
26130
- return typeof value === "string" ? value : undefined;
26131
- }
26132
- function isSchemaObject2(value) {
26133
- return typeof value === "object" && value !== null && !Array.isArray(value);
26134
- }
26135
-
26136
- // src/cli-runtime.ts
26137
- function cliStateHome(ctx) {
26138
- return dirname(ctx.store.path);
26139
- }
26140
- async function withWorkspace(ctx) {
26141
- if (ctx.workspace !== undefined && ctx.workspace.trim() !== "") {
26142
- return;
26143
- }
26144
- const identity = await client(ctx).validateToken();
26145
- if (identity.workspaceSelectionRequired) {
26146
- throw new CliError(`${identity.workspaceSelectionMessage ?? "Workspace selection required"} Run \`uru switch <workspace-id>\`, \`uru link --workspace <workspace-id>\`, or pass --workspace.`, { code: ExitCode.AuthRequired });
26147
- }
26148
- }
26149
- function client(ctx) {
26150
- return new UruApiClient({
26151
- apiUrl: ctx.apiUrl,
26152
- ...ctx.token !== undefined ? { token: ctx.token } : {},
26153
- ...ctx.workspace !== undefined ? { workspaceId: ctx.workspace } : {},
26154
- ...ctx.fetch !== undefined ? { fetch: ctx.fetch } : {},
26155
- signal: ctx.abortSignal
26156
- });
26157
- }
26158
- function assertWorkspaceAvailable(identity, workspaceId) {
26159
- if (identity.workspaceId === workspaceId || identity.workspaces.some((workspace2) => workspace2.id === workspaceId)) {
26160
- return;
26161
- }
26162
- throw new CliError(`Workspace ${workspaceId} is not available for the current token. Run \`uru switch\` to list available workspaces.`);
26163
- }
26164
- async function emitGemTool(ctx, operationId, params, options = {}) {
26165
- return emitTool(ctx, operationId, params, options);
26166
- }
26167
- async function emitTool(ctx, operationId, params, options = {}) {
26168
- try {
26169
- return await emitToolOutput(ctx, operationId, params, options);
26170
- } catch (error2) {
26171
- throw await explainOperationFailure(ctx, operationId, params, error2);
26172
- }
26173
- }
26174
- async function explainOperationFailure(ctx, operationId, params, error2) {
26175
- const operation = getPlatformOperation(operationId);
26176
- if (!(error2 instanceof CliError) || operation === undefined) {
26177
- return error2;
26178
- }
26179
- return explainToolFailure({
26180
- error: error2,
26181
- operation,
26182
- params,
26183
- loadInputSchema: () => narrowedOperationInputSchema(ctx, operation)
26184
- });
26185
- }
26186
- async function narrowedOperationInputSchema(ctx, operation) {
26187
- if (getCliNativeOperationContract(operation.id) !== undefined) {
26188
- return;
26189
- }
26190
- let rawSchema;
26191
- try {
26192
- rawSchema = await client(ctx).getToolSchema(operation.backendToolName);
26193
- } catch {
26194
- return;
26195
- }
26196
- const inputSchema = isJsonObject2(rawSchema) ? rawSchema["inputSchema"] : undefined;
26197
- return isJsonObject2(inputSchema) ? narrowToolInputSchemaToOperation(inputSchema, operation.backendOp) : undefined;
26198
- }
26199
- async function emitToolOutput(ctx, operationId, params, options) {
26200
- if (ctx.outputFormat === "stream-json" && options.streamStart !== undefined) {
26201
- writeStreamJson(ctx.io, "started", options.streamStart);
26202
- writeStreamJson(ctx.io, "phase", {
26203
- operation: options.streamStart["operation"] ?? operationId,
26204
- phase: "requesting"
26205
- });
26206
- const streamed = await executeOperationStream(ctx, operationId, params, (event) => {
26207
- writeStreamJsonEvent(ctx.io, event);
26208
- });
26209
- if (streamed.streamed) {
26210
- return null;
26211
- }
26212
- const payload2 = toolOutputPayload(streamed.payload ?? null);
26213
- const output2 = options.transform?.(payload2) ?? payload2;
26214
- writeStreamJson(ctx.io, "result", output2);
26215
- writeStreamJson(ctx.io, "done", {
26216
- operation: options.streamStart["operation"] ?? operationId
26217
- });
26218
- return payload2;
26219
- }
26220
- const result = await executeOperation(ctx, operationId, params);
26221
- const payload = toolOutputPayload(result);
26222
- const output = options.transform?.(payload) ?? payload;
26223
- if (ctx.outputFormat === "stream-json") {
26224
- writeStreamJson(ctx.io, "result", output);
26225
- if (options.streamStart !== undefined) {
26226
- writeStreamJson(ctx.io, "done", {
26227
- operation: options.streamStart["operation"] ?? operationId
26228
- });
26229
- }
26230
- } else if (ctx.json) {
26231
- writeJson(ctx.io, output);
26232
- } else {
26233
- writeText(ctx.io, options.textExtractor?.(output) ?? JSON.stringify(output, null, 2));
26234
- }
26235
- return payload;
26236
- }
26237
- async function executeOperationStream(ctx, operationId, params, onEvent) {
26238
- const operation = getPlatformOperation(operationId);
26239
- if (operation === undefined) {
26240
- throw new CliError(`Unknown operation registry id: ${operationId}`);
26241
- }
26242
- requireOperationConfirmation(ctx, operation, params);
26243
- const nativeResult = await executeCliNativeOperation(ctx, operationId, params);
26244
- if (nativeResult !== undefined) {
26245
- return { streamed: false, payload: nativeResult };
26246
- }
26247
- const toolParams = { ...params };
26248
- if (operation.backendOp !== undefined) {
26249
- toolParams["op"] = operation.backendOp;
26250
- }
26251
- const streamed = isGemOperation(operation.backendToolName) ? await client(ctx).streamGemTool(operation.backendToolName, toolParams, operation.backendOp ?? operationId, onEvent) : await client(ctx).streamTool(operation.backendToolName, toolParams, onEvent, operationId);
26252
- if (streamed.streamed) {
26253
- return streamed;
26254
- }
26255
- const payload = streamed.payload ?? null;
26256
- return { streamed: false, payload };
26257
- }
26258
- async function executeOperation(ctx, operationId, params) {
26259
- const operation = getPlatformOperation(operationId);
26260
- if (operation === undefined) {
26261
- throw new CliError(`Unknown operation registry id: ${operationId}`);
26262
- }
26263
- requireOperationConfirmation(ctx, operation, params);
26264
- const nativeResult = await executeCliNativeOperation(ctx, operationId, params);
26265
- if (nativeResult !== undefined) {
26266
- return nativeResult;
26267
- }
26268
- const toolParams = { ...params };
26269
- if (operation.backendOp !== undefined) {
26270
- toolParams["op"] = operation.backendOp;
26271
- }
26272
- const result = isGemOperation(operation.backendToolName) ? await client(ctx).runGemTool(operation.backendToolName, toolParams, operation.backendOp ?? operationId) : await client(ctx).runTool(operation.backendToolName, toolParams, operationId);
26273
- return result;
26274
- }
26275
- async function executeCliNativeOperation(ctx, operationId, params) {
26276
- const contract = getCliNativeOperationContract(operationId);
26277
- if (contract === undefined)
26278
- return;
26279
- switch (contract.kind) {
26280
- case "list_platform_tools":
26281
- requireExactKeys(operationId, params, []);
26282
- return client(ctx).listTools().then(toJsonValue);
26283
- case "get_platform_tool_schema": {
26284
- requireExactKeys(operationId, params, ["tool_name"]);
26285
- return client(ctx).getToolSchema(requireStringParam(params, "tool_name"));
26286
- }
26287
- case "execute_platform_tool": {
26288
- requireExactKeys(operationId, params, ["tool_name", "parameters"]);
26289
- const parameters = params["parameters"];
26290
- if (!isJsonObject2(parameters)) {
26291
- throw new CliError(`${operationId} parameters must be an object.`);
26292
- }
26293
- return client(ctx).runTool(requireStringParam(params, "tool_name"), parameters);
26294
- }
26295
- }
26296
- }
26297
- function requireExactKeys(operationId, params, expected) {
26298
- const expectedKeys = new Set(expected);
26299
- const unexpected = Object.keys(params).filter((key) => !expectedKeys.has(key));
26300
- const missing = expected.filter((key) => !Object.hasOwn(params, key));
26301
- if (unexpected.length === 0 && missing.length === 0)
26302
- return;
26303
- throw new CliError(`${operationId} parameters do not match its operation contract.`);
26304
- }
26305
- function requireStringParam(params, key) {
26306
- const value = params[key];
26307
- if (typeof value !== "string" || value.trim() === "") {
26308
- throw new CliError(`${key} must be a non-empty string.`);
26309
- }
26310
- return value;
26311
- }
26312
- function toJsonValue(value) {
26313
- if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
26314
- return value;
26315
- }
26316
- if (Array.isArray(value))
26317
- return value.map(toJsonValue);
26318
- if (isUnknownRecord(value)) {
26319
- return Object.fromEntries(Object.entries(value).map(([key, member]) => [key, toJsonValue(member)]));
26320
- }
26321
- throw new CliError("Platform tool command returned a non-JSON value.");
26322
- }
26323
- function isUnknownRecord(value) {
26324
- return typeof value === "object" && value !== null && !Array.isArray(value);
26325
- }
26326
- function requireOperationConfirmation(ctx, operation, params) {
26327
- if (operation === undefined) {
26328
- throw new CliError("Unknown platform operation. Refusing to execute without a registered safety policy.");
26329
- }
26330
- if (ctx.yes || !operationRequiresExplicitConfirmation(operation, params)) {
26331
- return;
26332
- }
26333
- if (operation.id === "library.rm" && params["permanent"] === true) {
26334
- throw confirmationRequiredError(ctx, "Permanent Library deletion cannot be undone. Re-run with --yes to confirm.");
26335
- }
26336
- throw confirmationRequiredError(ctx, `${operation.id} is destructive. Re-run with --yes to confirm.`);
26337
- }
26338
- function confirmationRequiredError(ctx, message) {
26339
- throw new CliError(message, {
26340
- errorCode: "confirmation_required",
26341
- confirmationRequired: true,
26342
- suggestedCommand: suggestCommandWithYes(ctx.argv)
26343
- });
26344
- }
26345
- var SECRET_VALUE_FLAGS = new Set(["--token", "--api-key"]);
26346
- function suggestCommandWithYes(argv) {
26347
- const sanitized = stripSecretFlagValues(argv);
26348
- const withYes = sanitized.includes("--yes") ? sanitized : [...sanitized, "--yes"];
26349
- return `uru ${withYes.map(shellQuoteArg).join(" ")}`;
26350
- }
26351
- function stripSecretFlagValues(argv) {
26352
- const out = [];
26353
- for (let i = 0;i < argv.length; i += 1) {
26354
- const arg = argv[i];
26995
+ function parseLocalFlags(args, commandPath) {
26996
+ const flagGrammar = localFlagGrammarFor(commandPath);
26997
+ const values = {};
26998
+ const booleans = new Set;
26999
+ const positionals = [];
27000
+ const occurrences = [];
27001
+ let parsingFlags = true;
27002
+ for (let index = 0;index < args.length; index += 1) {
27003
+ const arg = args[index];
26355
27004
  if (arg === undefined) {
26356
27005
  continue;
26357
27006
  }
26358
- const equals = arg.indexOf("=");
26359
- if (equals !== -1 && SECRET_VALUE_FLAGS.has(arg.slice(0, equals))) {
26360
- out.push(`${arg.slice(0, equals)}=[redacted]`);
27007
+ if (parsingFlags && arg === "--") {
27008
+ parsingFlags = false;
26361
27009
  continue;
26362
27010
  }
26363
- if (SECRET_VALUE_FLAGS.has(arg)) {
26364
- out.push(arg);
26365
- const next = argv[i + 1];
26366
- if (next !== undefined && !next.startsWith("--")) {
26367
- out.push("[redacted]");
26368
- i += 1;
27011
+ if (!parsingFlags || !arg.startsWith("-")) {
27012
+ positionals.push(arg);
27013
+ continue;
27014
+ }
27015
+ const parsedFlag = parseLocalFlagToken(arg, flagGrammar);
27016
+ const flag = parsedFlag?.token ?? arg;
27017
+ const inlineValue = parsedFlag?.inlineValue;
27018
+ const flagSpec = parsedFlag?.spec;
27019
+ if (flagSpec === undefined) {
27020
+ const rejection = flagGrammar.rejected.get(flag);
27021
+ if (rejection !== undefined) {
27022
+ throw new CliError(rejection);
27023
+ }
27024
+ throw new CliError(`Unknown flag: ${flag}`);
27025
+ }
27026
+ if (flagSpec.value === "none") {
27027
+ if (inlineValue !== undefined) {
27028
+ throw new CliError(`${flag} does not take a value`);
26369
27029
  }
27030
+ booleans.add(flagSpec.token);
27031
+ occurrences.push({ token: flagSpec.token });
26370
27032
  continue;
26371
27033
  }
26372
- out.push(arg);
26373
- }
26374
- return out;
26375
- }
26376
- function shellQuoteArg(arg) {
26377
- if (/^[A-Za-z0-9_./:@%+=,-]+$/.test(arg)) {
26378
- return arg;
26379
- }
26380
- return `'${arg.replace(/'/g, "'\\''")}'`;
26381
- }
26382
- function emit(ctx, value, text) {
26383
- emitValue(ctx, value, text);
26384
- }
26385
- function emitValue(ctx, value, text) {
26386
- if (ctx.outputFormat === "stream-json") {
26387
- writeStreamJson(ctx.io, "result", value);
26388
- return;
26389
- }
26390
- if (ctx.json) {
26391
- writeJson(ctx.io, value);
26392
- return;
26393
- }
26394
- writeText(ctx.io, text ?? (typeof value === "string" ? value : JSON.stringify(value, null, 2)));
26395
- }
26396
- function delegatedPayload(value) {
26397
- if (isJsonObject2(value) && isJsonObject2(value["payload"])) {
26398
- return value["payload"];
27034
+ if (inlineValue !== undefined) {
27035
+ if (inlineValue === "") {
27036
+ throw new CliError(`${flag} requires a value`);
27037
+ }
27038
+ assertEnumLocalFlagValue(flagSpec, inlineValue);
27039
+ values[flagSpec.token] = inlineValue;
27040
+ occurrences.push({ token: flagSpec.token, value: inlineValue });
27041
+ continue;
27042
+ }
27043
+ const next = args[index + 1];
27044
+ if (next !== undefined && next !== "--" && !next.startsWith("--")) {
27045
+ assertEnumLocalFlagValue(flagSpec, next);
27046
+ values[flagSpec.token] = next;
27047
+ occurrences.push({ token: flagSpec.token, value: next });
27048
+ index += 1;
27049
+ continue;
27050
+ }
27051
+ throw new CliError(`${flag} requires a value`);
26399
27052
  }
26400
- return value;
26401
- }
26402
- function gemPathFromArgs(flags, linkedProject) {
26403
- return flags.values["--path"] ?? flags.values["--gem"] ?? flags.positionals.find((value) => value.startsWith("library/")) ?? linkedProject.libraryPath ?? linkedProject.gemId ?? (() => {
26404
- throw new CliError("Gem path required. Pass library/<name>.gem or run `uru link --path library/<name>.gem`.");
26405
- })();
27053
+ return Object.defineProperty({ values, booleans, positionals }, "occurrences", {
27054
+ value: occurrences
27055
+ });
26406
27056
  }
26407
- function tokenGemRefParams(flags, linkedProject, options = {}) {
26408
- const explicitPath = flags.values["--path"];
26409
- if (explicitPath !== undefined) {
26410
- return { path: explicitPath };
26411
- }
26412
- const explicitGem = flags.values["--gem"];
26413
- if (explicitGem !== undefined) {
26414
- return explicitGem.startsWith("library/") ? { path: explicitGem } : { gem_id: explicitGem };
26415
- }
26416
- const positional = flags.positionals[0];
26417
- if (positional !== undefined) {
26418
- return positional.startsWith("library/") ? { path: positional } : { gem_id: positional };
26419
- }
26420
- if (linkedProject.libraryPath !== undefined) {
26421
- return { path: linkedProject.libraryPath };
26422
- }
26423
- if (linkedProject.gemId !== undefined) {
26424
- return { gem_id: linkedProject.gemId };
26425
- }
26426
- if (options.required === true) {
26427
- throw new CliError(options.usage ?? "Gem reference required. Pass library/<name>.gem, --path, --gem, or run `uru link`.");
27057
+ function parseLocalFlagToken(arg, grammar) {
27058
+ const equals = arg.indexOf("=");
27059
+ const token = equals === -1 ? arg : arg.slice(0, equals);
27060
+ const exact = grammar.accepted.get(token);
27061
+ if (exact !== undefined) {
27062
+ return {
27063
+ token,
27064
+ spec: exact,
27065
+ ...equals === -1 ? {} : { inlineValue: arg.slice(equals + 1) }
27066
+ };
26428
27067
  }
26429
- return {};
26430
- }
26431
- function shiftPositionals(flags, count) {
26432
- return {
26433
- values: flags.values,
26434
- booleans: flags.booleans,
26435
- positionals: flags.positionals.slice(count)
26436
- };
26437
- }
26438
- function stringField2(record2, keys) {
26439
- for (const key of keys) {
26440
- const value = record2[key];
26441
- if (typeof value === "string" && value.trim() !== "") {
26442
- return value.trim();
27068
+ for (const candidate of grammar.attachedValueTokens) {
27069
+ if (arg.startsWith(candidate.token) && arg.length > candidate.token.length) {
27070
+ return {
27071
+ token: candidate.token,
27072
+ spec: candidate.spec,
27073
+ inlineValue: arg.slice(candidate.token.length)
27074
+ };
26443
27075
  }
26444
27076
  }
26445
27077
  return;
26446
27078
  }
26447
- function isGemOperation(toolName) {
26448
- return toolName === "gem_control_plane" || toolName === "gem_query";
26449
- }
26450
- function toolOutputPayload(value) {
26451
- return unwrapToolResult(value);
26452
- }
26453
- function isJsonObject2(value) {
26454
- return value !== null && typeof value === "object" && !Array.isArray(value);
26455
- }
26456
- function unwrapToolResult(value) {
26457
- assertToolResultSuccess(value);
26458
- if (isJsonObject2(value) && Object.hasOwn(value, "result") && (isToolResultEnvelope2(value) || isJsonObject2(value["result"]))) {
26459
- return value["result"] ?? value;
26460
- }
26461
- return value;
26462
- }
26463
- function assertToolResultSuccess(value) {
26464
- if (!isJsonObject2(value) || !isToolResultEnvelope2(value)) {
27079
+ function assertEnumLocalFlagValue(spec2, value) {
27080
+ if (spec2.value !== "one_of") {
26465
27081
  return;
26466
27082
  }
26467
- const httpStatus = toolResultHttpStatus(value);
26468
- const failed = value["success"] === false || Object.hasOwn(value, "error") || Object.hasOwn(value, "errorMessage") || Object.hasOwn(value, "error_message") || Object.hasOwn(value, "errorCode") || Object.hasOwn(value, "error_code") || Object.hasOwn(value, "code") || httpStatus !== undefined && httpStatus >= 400;
26469
- if (!failed) {
26470
- return;
27083
+ if (!spec2.values?.includes(value)) {
27084
+ throw new CliError(`${spec2.token} must be one of ${spec2.values?.join(", ") ?? "the declared values"}.`);
26471
27085
  }
26472
- const errorCode = stringField2(value, ["errorCode", "error_code", "code"]);
26473
- const toolId = stringField2(value, ["toolId", "tool_id"]);
26474
- const message = stringField2(value, ["errorMessage", "error_message", "error", "message"]) ?? `${toolId === undefined ? "Tool operation" : `Tool ${toolId}`} failed`;
26475
- const details = [
26476
- errorCode === undefined ? undefined : `[${errorCode}]`,
26477
- httpStatus === undefined ? undefined : `(HTTP ${httpStatus})`
26478
- ].filter((detail) => detail !== undefined);
26479
- const tip = stringField2(value, ["tip"]);
26480
- const errorId = stringField2(value, ["errorId", "error_id"]);
26481
- const serverDetails = value["details"] ?? value["errorDetails"];
26482
- throw new CliError(`${message}${details.length === 0 ? "" : ` ${details.join(" ")}`}`, {
26483
- ...tip === undefined ? {} : { tip },
26484
- code: httpStatus === 409 ? ExitCode.Conflict : httpStatus === 401 || httpStatus === 403 ? ExitCode.AuthRequired : ExitCode.Failure,
26485
- ...errorCode === undefined ? {} : { errorCode },
26486
- ...errorId === undefined ? {} : { errorId },
26487
- ...httpStatus === undefined ? {} : { httpStatus },
26488
- ...isTransientFailure(httpStatus ?? 0, value) ? { retryable: true } : {},
26489
- ...isJsonObject2(serverDetails) ? { details: serverDetails } : {}
26490
- });
26491
- }
26492
- function isToolResultEnvelope2(value) {
26493
- return typeof value["success"] === "boolean" && (typeof value["toolId"] === "string" || typeof value["tool_id"] === "string" || typeof value["executionTimeMs"] === "number" || typeof value["execution_time_ms"] === "number");
26494
27086
  }
26495
- function toolResultHttpStatus(value) {
26496
- const status = value["httpStatus"] ?? value["http_status"];
26497
- return typeof status === "number" && Number.isFinite(status) ? status : undefined;
26498
- }
26499
- function normalizeError(error2) {
26500
- if (error2 instanceof CliError) {
26501
- return error2;
27087
+ function integerFlag(flags, name, fallback) {
27088
+ const raw = flags.values[name];
27089
+ if (raw === undefined) {
27090
+ return fallback;
26502
27091
  }
26503
- if (isAbortError(error2)) {
26504
- return new CliError("Cancelled.", { code: ExitCode.Cancelled });
27092
+ const value = Number.parseInt(raw, 10);
27093
+ if (!Number.isFinite(value) || value < 0) {
27094
+ throw new CliError(`${name} must be a non-negative integer`);
26505
27095
  }
26506
- return new CliError(error2 instanceof Error ? error2.message : "Unknown error");
27096
+ return value;
26507
27097
  }
26508
- function isAbortError(error2) {
26509
- if (!(error2 instanceof Error)) {
26510
- return false;
27098
+ function copyStringFlag(flags, target, flagName, paramName) {
27099
+ const value = flags.values[flagName];
27100
+ if (value !== undefined) {
27101
+ target[paramName] = value;
26511
27102
  }
26512
- return error2.name === "AbortError" || error2.message === "This operation was aborted";
26513
27103
  }
26514
- function findSourceRevisionId(value) {
26515
- let found;
26516
- visitJson(value, (candidate) => {
26517
- if (!isJsonObject2(candidate)) {
26518
- return;
27104
+ function isJsonRequested(argv) {
27105
+ for (let index = 0;index < argv.length; index += 1) {
27106
+ const arg = argv[index];
27107
+ if (arg === "--json") {
27108
+ return true;
26519
27109
  }
26520
- const valueAtKey = stringField2(candidate, [
26521
- "currentSourceRevisionId",
26522
- "current_source_revision_id",
26523
- "sourceRevisionId",
26524
- "source_revision_id"
26525
- ]);
26526
- if (valueAtKey !== undefined) {
26527
- found = valueAtKey;
27110
+ if (arg === "--output-format=json" || arg === "--output-format=stream-json" || arg === "--output=json" || arg === "--output=stream-json") {
27111
+ return true;
26528
27112
  }
26529
- });
26530
- return found;
26531
- }
26532
- function visitJson(value, visitor) {
26533
- visitor(value);
26534
- if (Array.isArray(value)) {
26535
- for (const item of value) {
26536
- visitJson(item, visitor);
27113
+ if (arg === "--output-format" || arg === "--output") {
27114
+ const value = argv[index + 1];
27115
+ if (value === "json" || value === "stream-json") {
27116
+ return true;
27117
+ }
26537
27118
  }
26538
- return;
26539
27119
  }
26540
- if (!isJsonObject2(value)) {
27120
+ return false;
27121
+ }
27122
+ function nonEmptyString(value) {
27123
+ if (value === undefined) {
26541
27124
  return;
26542
27125
  }
26543
- for (const item of Object.values(value)) {
26544
- visitJson(item, visitor);
26545
- }
27126
+ const trimmed = value.trim();
27127
+ return trimmed === "" ? undefined : trimmed;
26546
27128
  }
26547
27129
 
27130
+ // src/command-runtime-bindings.ts
27131
+ import { dirname as dirname10 } from "node:path";
27132
+
26548
27133
  // src/auth-status.ts
26549
27134
  async function authStatus(ctx) {
26550
27135
  const local = await inspectLocalAuth(ctx);
@@ -26586,21 +27171,16 @@ async function inspectLocalAuth(ctx) {
26586
27171
  ...expiryFromToken(ctx.token)
26587
27172
  };
26588
27173
  }
26589
- const keychainValue = await ctx.credentialStore.readToken(ctx.apiUrl).catch(() => {
26590
- return;
27174
+ const stored = await readStoredLoginValueForConfig({
27175
+ credentialStore: ctx.credentialStore,
27176
+ apiUrl: ctx.apiUrl,
27177
+ config: ctx.config
26591
27178
  });
26592
- if (keychainValue !== undefined) {
26593
- return {
26594
- storage: "keychain",
26595
- insecureStorage: false,
26596
- ...expiryFromStoredValue(keychainValue)
26597
- };
26598
- }
26599
- if (ctx.config.insecureStorage === true && ctx.config.token !== undefined) {
27179
+ if (stored.value !== undefined) {
26600
27180
  return {
26601
- storage: "insecure_file",
26602
- insecureStorage: true,
26603
- ...expiryFromStoredValue(ctx.config.token)
27181
+ storage: stored.source === "config" ? "insecure_file" : "keychain",
27182
+ insecureStorage: stored.source === "config",
27183
+ ...expiryFromStoredValue(stored.value)
26604
27184
  };
26605
27185
  }
26606
27186
  if (ctx.token !== undefined && ctx.token.trim() !== "") {
@@ -26712,7 +27292,7 @@ class UruSdkError extends Error {
26712
27292
  }
26713
27293
 
26714
27294
  // src/local-commands.ts
26715
- import { randomUUID } from "node:crypto";
27295
+ import { randomUUID as randomUUID2 } from "node:crypto";
26716
27296
  import { readFile as readFile3, stat } from "node:fs/promises";
26717
27297
  import { basename, resolve as resolve2 } from "node:path";
26718
27298
  import { setTimeout as sleep } from "node:timers/promises";
@@ -26890,10 +27470,10 @@ function formatLibraryList(value) {
26890
27470
  return "No Library items found";
26891
27471
  }
26892
27472
  return renderTable(["PATH", "TYPE", "NAME", "ID"], rows.map((row) => [
26893
- stringField2(row, ["path"]) ?? "",
26894
- stringField2(row, ["resourceType", "resource_type", "type"]) ?? "",
26895
- stringField2(row, ["name", "title", "resourceSlug", "resource_slug"]) ?? "",
26896
- stringField2(row, ["itemId", "item_id", "id", "resourceId", "resource_id"]) ?? ""
27473
+ stringField(row, ["path"]) ?? "",
27474
+ stringField(row, ["resourceType", "resource_type", "type"]) ?? "",
27475
+ stringField(row, ["name", "title", "resourceSlug", "resource_slug"]) ?? "",
27476
+ stringField(row, ["itemId", "item_id", "id", "resourceId", "resource_id"]) ?? ""
26897
27477
  ]));
26898
27478
  }
26899
27479
  function formatAutomationRunList(value) {
@@ -26905,10 +27485,10 @@ function formatAutomationRunList(value) {
26905
27485
  return "No automation runs found";
26906
27486
  }
26907
27487
  return renderTable(["RUN", "STATUS", "AUTOMATION", "STARTED"], rows.map((row) => [
26908
- stringField2(row, ["run_id", "runId", "id"]) ?? "",
26909
- stringField2(row, ["status"]) ?? "",
26910
- stringField2(row, ["automation_id", "automationId"]) ?? "",
26911
- stringField2(row, ["started_at", "startedAt", "created_at", "createdAt"]) ?? ""
27488
+ stringField(row, ["run_id", "runId", "id"]) ?? "",
27489
+ stringField(row, ["status"]) ?? "",
27490
+ stringField(row, ["automation_id", "automationId"]) ?? "",
27491
+ stringField(row, ["started_at", "startedAt", "created_at", "createdAt"]) ?? ""
26912
27492
  ]));
26913
27493
  }
26914
27494
  function formatGemResourceList(kind, value) {
@@ -26921,41 +27501,41 @@ function formatGemResourceList(kind, value) {
26921
27501
  }
26922
27502
  if (kind === "versions") {
26923
27503
  return renderTable(["VERSION", "NAME", "CREATED"], rows.map((row) => [
26924
- stringField2(row, ["version_id", "versionId", "id"]) ?? "",
26925
- stringField2(row, ["name", "label"]) ?? "",
26926
- stringField2(row, ["created_at", "createdAt"]) ?? ""
27504
+ stringField(row, ["version_id", "versionId", "id"]) ?? "",
27505
+ stringField(row, ["name", "label"]) ?? "",
27506
+ stringField(row, ["created_at", "createdAt"]) ?? ""
26927
27507
  ]));
26928
27508
  }
26929
27509
  if (kind === "releases") {
26930
27510
  return renderTable(["RELEASE", "VERSION", "STATUS", "CREATED"], rows.map((row) => [
26931
- stringField2(row, ["release_id", "releaseId", "id"]) ?? "",
26932
- stringField2(row, ["version_id", "versionId"]) ?? "",
26933
- stringField2(row, ["status"]) ?? "",
26934
- stringField2(row, ["created_at", "createdAt"]) ?? ""
27511
+ stringField(row, ["release_id", "releaseId", "id"]) ?? "",
27512
+ stringField(row, ["version_id", "versionId"]) ?? "",
27513
+ stringField(row, ["status"]) ?? "",
27514
+ stringField(row, ["created_at", "createdAt"]) ?? ""
26935
27515
  ]));
26936
27516
  }
26937
27517
  if (kind === "edits") {
26938
27518
  return renderTable(["EDIT", "MESSAGE", "CREATED"], rows.map((row) => [
26939
- stringField2(row, ["edit_id", "editId", "id"]) ?? "",
26940
- stringField2(row, ["message", "name", "summary"]) ?? "",
26941
- stringField2(row, ["created_at", "createdAt"]) ?? ""
27519
+ stringField(row, ["edit_id", "editId", "id"]) ?? "",
27520
+ stringField(row, ["message", "name", "summary"]) ?? "",
27521
+ stringField(row, ["created_at", "createdAt"]) ?? ""
26942
27522
  ]));
26943
27523
  }
26944
27524
  if (kind === "shares") {
26945
27525
  return renderTable(["SHARE", "NAME", "ROLE", "VERSION", "PEOPLE", "STATUS", "URL"], rows.map((row) => [
26946
- stringField2(row, ["id"]) ?? "",
26947
- stringField2(row, ["name"]) ?? "",
26948
- stringField2(row, ["kind"]) ?? "",
27526
+ stringField(row, ["id"]) ?? "",
27527
+ stringField(row, ["name"]) ?? "",
27528
+ stringField(row, ["kind"]) ?? "",
26949
27529
  shareVersionCell(row),
26950
27530
  numberCell(row["recipient_count"]),
26951
- stringField2(row, ["status"]) ?? "",
26952
- stringField2(row, ["url"]) ?? ""
27531
+ stringField(row, ["status"]) ?? "",
27532
+ stringField(row, ["url"]) ?? ""
26953
27533
  ]));
26954
27534
  }
26955
27535
  return renderTable(["RUN", "STATUS", "STARTED"], rows.map((row) => [
26956
- stringField2(row, ["run_id", "runId", "id"]) ?? "",
26957
- stringField2(row, ["status"]) ?? "",
26958
- stringField2(row, ["started_at", "startedAt", "created_at", "createdAt"]) ?? ""
27536
+ stringField(row, ["run_id", "runId", "id"]) ?? "",
27537
+ stringField(row, ["status"]) ?? "",
27538
+ stringField(row, ["started_at", "startedAt", "created_at", "createdAt"]) ?? ""
26959
27539
  ]));
26960
27540
  }
26961
27541
  function shareVersionCell(row) {
@@ -26964,7 +27544,7 @@ function shareVersionCell(row) {
26964
27544
  return "";
26965
27545
  }
26966
27546
  const number3 = version2["gem_version_number"];
26967
- const mode = stringField2(version2, ["mode"]) ?? "";
27547
+ const mode = stringField(version2, ["mode"]) ?? "";
26968
27548
  const label = typeof number3 === "number" || typeof number3 === "string" ? String(number3) : "";
26969
27549
  return [label, mode].filter((part) => part !== "").join(" ");
26970
27550
  }
@@ -27771,7 +28351,7 @@ async function dispatchDatasetSourceCommand(ctx, verb, args) {
27771
28351
  const explicitParams = flags.values["--params-json"];
27772
28352
  const params = explicitParams === undefined ? {} : parseParamsJson(await readParamsJsonSource(explicitParams, paramsJsonOptions(ctx)), "--params-json");
27773
28353
  params["dataset_id"] = datasetId;
27774
- params["idempotency_key"] ??= flags.values["--idempotency-key"] ?? randomUUID();
28354
+ params["idempotency_key"] ??= flags.values["--idempotency-key"] ?? randomUUID2();
27775
28355
  if (params["expected_dataset_revision"] === undefined || params["expected_schema_revision"] === undefined) {
27776
28356
  const dataset = unwrapToolResult(await executeOperation(ctx, "dataset.get", { dataset_id: datasetId }));
27777
28357
  if (!isJsonObject2(dataset)) {
@@ -28530,9 +29110,9 @@ function distributionParams(flags) {
28530
29110
  }
28531
29111
 
28532
29112
  // src/mcp-commands.ts
28533
- import { mkdir, readFile as readFile4, writeFile } from "node:fs/promises";
28534
- import { homedir } from "node:os";
28535
- import { dirname as dirname2, resolve as resolve3 } from "node:path";
29113
+ import { mkdir as mkdir2, readFile as readFile4, writeFile } from "node:fs/promises";
29114
+ import { homedir as homedir2 } from "node:os";
29115
+ import { dirname as dirname4, resolve as resolve3 } from "node:path";
28536
29116
  var DEFAULT_MCP_PACKAGE2 = package_default.uru.mcpPackage;
28537
29117
  var DEFAULT_SERVER_NAME = "uru";
28538
29118
  var MCP_TARGET_IDS = ["cursor", "claude"];
@@ -28557,7 +29137,7 @@ async function dispatchMcp(ctx, sub, args) {
28557
29137
  }
28558
29138
  throw new CliError("Usage: uru mcp list|config|install|add|remove [--target cursor|claude] [--path <mcp-config.json>]");
28559
29139
  }
28560
- async function probeMcpTargets(home = homedir()) {
29140
+ async function probeMcpTargets(home = homedir2()) {
28561
29141
  const probes = [];
28562
29142
  for (const target of MCP_TARGET_IDS) {
28563
29143
  const path = defaultMcpTargetPath(target, home);
@@ -28565,7 +29145,7 @@ async function probeMcpTargets(home = homedir()) {
28565
29145
  }
28566
29146
  return probes;
28567
29147
  }
28568
- function defaultMcpTargetPath(target, home = homedir()) {
29148
+ function defaultMcpTargetPath(target, home = homedir2()) {
28569
29149
  if (target === "cursor") {
28570
29150
  return resolve3(home, ".cursor", "mcp.json");
28571
29151
  }
@@ -28598,7 +29178,7 @@ async function installMcpConfig(ctx, args, verb) {
28598
29178
  const path = resolveMcpWritePath(ctx, flags, verb);
28599
29179
  const existing = await readMcpClientFile(path);
28600
29180
  const next = mergeMcpServers(existing?.document ?? {}, config2);
28601
- await mkdir(dirname2(path), { recursive: true });
29181
+ await mkdir2(dirname4(path), { recursive: true });
28602
29182
  await writeFile(path, `${JSON.stringify(next, null, 2)}
28603
29183
  `, { mode: 384 });
28604
29184
  emit(ctx, { ok: true, path }, `Wrote MCP config to ${path}`);
@@ -28806,24 +29386,24 @@ function formatMcpTargetTable(probes) {
28806
29386
  }
28807
29387
 
28808
29388
  // src/project.ts
28809
- import { createHash as createHash2 } from "node:crypto";
28810
- import { mkdir as mkdir2, readFile as readFile5, readdir, rm, writeFile as writeFile2 } from "node:fs/promises";
28811
- import { dirname as dirname3, join, relative, resolve as resolve4, sep } from "node:path";
29389
+ import { createHash as createHash3 } from "node:crypto";
29390
+ import { mkdir as mkdir3, readFile as readFile5, readdir, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
29391
+ import { dirname as dirname5, join as join2, relative, resolve as resolve4, sep } from "node:path";
28812
29392
  function projectDir(cwd) {
28813
- return join(resolve4(cwd), ".uru");
29393
+ return join2(resolve4(cwd), ".uru");
28814
29394
  }
28815
29395
  function projectPath(cwd) {
28816
- return join(projectDir(cwd), "project.json");
29396
+ return join2(projectDir(cwd), "project.json");
28817
29397
  }
28818
29398
  function sourceLockPath(cwd) {
28819
- return join(projectDir(cwd), "source-lock.json");
29399
+ return join2(projectDir(cwd), "source-lock.json");
28820
29400
  }
28821
29401
  async function readLinkedProject(cwd) {
28822
29402
  try {
28823
29403
  const parsed = JSON.parse(await readFile5(projectPath(cwd), "utf8"));
28824
29404
  return sanitizeLinkedProject(parsed);
28825
29405
  } catch (error2) {
28826
- if (isNodeError(error2) && error2.code === "ENOENT") {
29406
+ if (isNodeError2(error2) && error2.code === "ENOENT") {
28827
29407
  return {};
28828
29408
  }
28829
29409
  throw error2;
@@ -28835,12 +29415,12 @@ async function writeLinkedProject(cwd, project) {
28835
29415
  throw new CliError("Nothing to link. Pass --workspace and --gem or --path.");
28836
29416
  }
28837
29417
  const path = projectPath(cwd);
28838
- await mkdir2(dirname3(path), { recursive: true });
29418
+ await mkdir3(dirname5(path), { recursive: true });
28839
29419
  await writeFile2(path, `${JSON.stringify(sanitized, null, 2)}
28840
29420
  `, { mode: 384 });
28841
29421
  }
28842
29422
  async function unlinkProject(cwd) {
28843
- await rm(projectPath(cwd), { force: true });
29423
+ await rm2(projectPath(cwd), { force: true });
28844
29424
  }
28845
29425
  async function readSourceLock(cwd) {
28846
29426
  try {
@@ -28860,7 +29440,7 @@ async function readSourceLock(cwd) {
28860
29440
  }
28861
29441
  return lock;
28862
29442
  } catch (error2) {
28863
- if (isNodeError(error2) && error2.code === "ENOENT") {
29443
+ if (isNodeError2(error2) && error2.code === "ENOENT") {
28864
29444
  return {};
28865
29445
  }
28866
29446
  throw error2;
@@ -28873,7 +29453,7 @@ async function writeSourceLock(cwd, lock) {
28873
29453
  files: stableStringRecord(lock.files ?? {}),
28874
29454
  ...lock.checkedOutAt === undefined ? {} : { checkedOutAt: lock.checkedOutAt }
28875
29455
  };
28876
- await mkdir2(dirname3(path), { recursive: true });
29456
+ await mkdir3(dirname5(path), { recursive: true });
28877
29457
  await writeFile2(path, `${JSON.stringify(sanitized, null, 2)}
28878
29458
  `, { mode: 384 });
28879
29459
  }
@@ -28899,7 +29479,7 @@ function sourceHashesFromLocalFiles(files) {
28899
29479
  return stableStringRecord(Object.fromEntries(Object.entries(files).map(([path, file]) => [path, file.sha256])));
28900
29480
  }
28901
29481
  function sha256Hex(content) {
28902
- return createHash2("sha256").update(content).digest("hex");
29482
+ return createHash3("sha256").update(content).digest("hex");
28903
29483
  }
28904
29484
  function sanitizeLinkedProject(value) {
28905
29485
  if (!isRecord(value)) {
@@ -28923,7 +29503,7 @@ function sanitizeLinkedProject(value) {
28923
29503
  async function collectLocalSourceFilesInto(root, directory, files) {
28924
29504
  const entries = await readdir(directory, { withFileTypes: true });
28925
29505
  for (const entry of entries) {
28926
- const absolutePath = join(directory, entry.name);
29506
+ const absolutePath = join2(directory, entry.name);
28927
29507
  const projectPathValue = toProjectPath(root, absolutePath);
28928
29508
  if (shouldSkipProjectPath(projectPathValue)) {
28929
29509
  continue;
@@ -28984,7 +29564,7 @@ function stableStringRecord(record2) {
28984
29564
  function compareStrings(left, right) {
28985
29565
  return left.localeCompare(right);
28986
29566
  }
28987
- function isNodeError(error2) {
29567
+ function isNodeError2(error2) {
28988
29568
  return error2 instanceof Error && "code" in error2;
28989
29569
  }
28990
29570
 
@@ -29121,10 +29701,12 @@ async function checkTokenStorage(ctx, checks3) {
29121
29701
  });
29122
29702
  return;
29123
29703
  }
29124
- const inCredentialStore = await ctx.credentialStore.readToken(ctx.apiUrl).catch(() => {
29125
- return;
29704
+ const stored = await readStoredLoginValueForConfig({
29705
+ credentialStore: ctx.credentialStore,
29706
+ apiUrl: ctx.apiUrl,
29707
+ config: ctx.config
29126
29708
  });
29127
- if (inCredentialStore !== undefined) {
29709
+ if (stored.source === "keychain" && stored.value !== undefined) {
29128
29710
  checks3.push({
29129
29711
  name: "token storage",
29130
29712
  status: "ok",
@@ -29132,7 +29714,7 @@ async function checkTokenStorage(ctx, checks3) {
29132
29714
  });
29133
29715
  return;
29134
29716
  }
29135
- const inPlaintextConfig = ctx.config.insecureStorage === true && ctx.config.token !== undefined;
29717
+ const inPlaintextConfig = stored.source === "config" && stored.value !== undefined;
29136
29718
  checks3.push(inPlaintextConfig ? {
29137
29719
  name: "token storage",
29138
29720
  status: "warn",
@@ -29235,8 +29817,8 @@ function describeError(error2) {
29235
29817
  }
29236
29818
 
29237
29819
  // src/gem-lifecycle-commands.ts
29238
- import { mkdir as mkdir4, readFile as readFile8, writeFile as writeFile3 } from "node:fs/promises";
29239
- import { join as join3, resolve as resolve6 } from "node:path";
29820
+ import { mkdir as mkdir5, readFile as readFile8, writeFile as writeFile3 } from "node:fs/promises";
29821
+ import { join as join4, resolve as resolve6 } from "node:path";
29240
29822
  import { setTimeout as sleep2 } from "node:timers/promises";
29241
29823
 
29242
29824
  // ../../packages/types/src/artifacts/gemRequestWaterfall.ts
@@ -29513,7 +30095,7 @@ async function dispatchGemFs(ctx, verb, args, linkedProject) {
29513
30095
  }
29514
30096
 
29515
30097
  // src/gem-git-source-commands.ts
29516
- import { randomUUID as randomUUID2 } from "node:crypto";
30098
+ import { randomUUID as randomUUID3 } from "node:crypto";
29517
30099
  var GIT_SOURCE_PATH = "/api/v1/artifacts";
29518
30100
  async function dispatchGemGitSource(ctx, verb, args, linkedProject) {
29519
30101
  if (verb === undefined || verb === "help") {
@@ -29550,7 +30132,7 @@ function commandFromFlags(verb, flags) {
29550
30132
  return toJsonCommand({
29551
30133
  action: "retry",
29552
30134
  importId: requiredImportId(flags, "retry"),
29553
- idempotencyKey: flags.values["--idempotency-key"]?.trim() || randomUUID2()
30135
+ idempotencyKey: flags.values["--idempotency-key"]?.trim() || randomUUID3()
29554
30136
  });
29555
30137
  case "cancel":
29556
30138
  return toJsonCommand({
@@ -29596,7 +30178,7 @@ async function resolveArtifactReference(ctx, flags, linkedProject) {
29596
30178
  }
29597
30179
  function findArtifactId(value) {
29598
30180
  if (isJsonObject2(value)) {
29599
- const id = stringField2(value, [
30181
+ const id = stringField(value, [
29600
30182
  "artifact_id",
29601
30183
  "artifactId",
29602
30184
  "gem_id",
@@ -29717,14 +30299,14 @@ function formatGitSourceState(value) {
29717
30299
  if (!isJsonObject2(value)) {
29718
30300
  return JSON.stringify(value, null, 2);
29719
30301
  }
29720
- const artifactId = stringField2(value, ["artifactId", "artifact_id"]);
30302
+ const artifactId = stringField(value, ["artifactId", "artifact_id"]);
29721
30303
  const binding = isJsonObject2(value["binding"]) ? value["binding"] : undefined;
29722
30304
  const policy = isJsonObject2(value["policy"]) ? value["policy"] : undefined;
29723
30305
  const lines = [
29724
30306
  artifactId === undefined ? undefined : `Artifact: ${artifactId}`,
29725
30307
  binding === undefined ? "Source binding: none" : `Source binding: ${binding["active"] === true ? "active" : "inactive"}`,
29726
- binding === undefined ? undefined : stringField2(binding, ["ref"]) === undefined ? undefined : `Ref: ${stringField2(binding, ["ref"])}`,
29727
- binding === undefined ? undefined : stringField2(binding, ["currentCommitSha", "current_commit_sha"]) === undefined ? undefined : `Current commit: ${stringField2(binding, [
30308
+ binding === undefined ? undefined : stringField(binding, ["ref"]) === undefined ? undefined : `Ref: ${stringField(binding, ["ref"])}`,
30309
+ binding === undefined ? undefined : stringField(binding, ["currentCommitSha", "current_commit_sha"]) === undefined ? undefined : `Current commit: ${stringField(binding, [
29728
30310
  "currentCommitSha",
29729
30311
  "current_commit_sha"
29730
30312
  ])}`,
@@ -29735,9 +30317,9 @@ function formatGitSourceState(value) {
29735
30317
  }
29736
30318
  function formatCopyResult(value) {
29737
30319
  const record2 = isJsonObject2(value) ? value : undefined;
29738
- const artifactId = record2 === undefined ? undefined : stringField2(record2, ["artifactId", "artifact_id", "id"]);
29739
- const title = record2 === undefined ? undefined : stringField2(record2, ["title"]);
29740
- const commitSha = record2 === undefined ? undefined : stringField2(record2, ["copiedFromCommitSha", "copied_from_commit_sha"]);
30320
+ const artifactId = record2 === undefined ? undefined : stringField(record2, ["artifactId", "artifact_id", "id"]);
30321
+ const title = record2 === undefined ? undefined : stringField(record2, ["title"]);
30322
+ const commitSha = record2 === undefined ? undefined : stringField(record2, ["copiedFromCommitSha", "copied_from_commit_sha"]);
29741
30323
  if (artifactId === undefined && title === undefined) {
29742
30324
  return JSON.stringify(value, null, 2);
29743
30325
  }
@@ -29754,22 +30336,18 @@ function formatCopyResult(value) {
29754
30336
  var GEM_SHARE_LINK_OFF_CONFIRMATION_REQUIRED_CODE = "gem_share_link_off_confirmation_required";
29755
30337
 
29756
30338
  // src/held-idempotency-keys.ts
29757
- import { createHash as createHash3, randomUUID as randomUUID3 } from "node:crypto";
29758
- import { constants } from "node:fs";
29759
- import { chmod, link, mkdir as mkdir3, open, readFile as readFile7, rename, rm as rm2 } from "node:fs/promises";
29760
- import { dirname as dirname4, join as join2 } from "node:path";
29761
- var HELD_KEYS_LOCK_TIMEOUT_MS = 1e4;
29762
- var HELD_KEYS_LOCK_RETRY_MS = 10;
29763
- var HELD_KEYS_LOCK_STALE_MS = 30000;
29764
- var HELD_KEYS_RECOVERY_SUFFIX = ".recovery";
30339
+ import { createHash as createHash4, randomUUID as randomUUID4 } from "node:crypto";
30340
+ import { constants as constants2 } from "node:fs";
30341
+ import { chmod, mkdir as mkdir4, open as open2, readFile as readFile7, rename as rename2, rm as rm3 } from "node:fs/promises";
30342
+ import { dirname as dirname6, join as join3 } from "node:path";
29765
30343
  var HELD_KEYS_FILE = "held-idempotency-keys.json";
29766
30344
  async function holdIdempotencyKey(io, stateHome, intent, now = new Date) {
29767
- const path = join2(stateHome, HELD_KEYS_FILE);
30345
+ const path = join3(stateHome, HELD_KEYS_FILE);
29768
30346
  const fingerprint = fingerprintIntent(intent);
29769
30347
  return withHeldEntriesLock(path, async () => {
29770
30348
  const stored = await readHeldEntries(path);
29771
30349
  const existing = stored[fingerprint];
29772
- const owner = `${process.pid}:${randomUUID3()}`;
30350
+ const owner = `${process.pid}:${randomUUID4()}`;
29773
30351
  if (existing !== undefined) {
29774
30352
  const updated = {
29775
30353
  ...existing,
@@ -29781,7 +30359,7 @@ async function holdIdempotencyKey(io, stateHome, intent, now = new Date) {
29781
30359
  release: () => releaseHold(io, path, fingerprint, existing.key, owner)
29782
30360
  };
29783
30361
  }
29784
- const key = randomUUID3();
30362
+ const key = randomUUID4();
29785
30363
  await writeHeldEntries(path, {
29786
30364
  ...stored,
29787
30365
  [fingerprint]: { key, heldAt: now.toISOString(), owners: [owner] }
@@ -29793,7 +30371,7 @@ async function holdIdempotencyKey(io, stateHome, intent, now = new Date) {
29793
30371
  });
29794
30372
  }
29795
30373
  function fingerprintIntent(intent) {
29796
- return createHash3("sha256").update(canonicalJson(intent)).digest("hex");
30374
+ return createHash4("sha256").update(canonicalJson(intent)).digest("hex");
29797
30375
  }
29798
30376
  function canonicalJson(value) {
29799
30377
  if (value === null || typeof value !== "object") {
@@ -29810,7 +30388,7 @@ async function readHeldEntries(path) {
29810
30388
  try {
29811
30389
  raw = await readFile7(path, "utf8");
29812
30390
  } catch (error2) {
29813
- if (isNodeError2(error2) && error2.code === "ENOENT") {
30391
+ if (isNodeError3(error2) && error2.code === "ENOENT") {
29814
30392
  return {};
29815
30393
  }
29816
30394
  throw unreadable(path, error2);
@@ -29850,265 +30428,33 @@ async function readHeldEntries(path) {
29850
30428
  return entries;
29851
30429
  }
29852
30430
  async function withHeldEntriesLock(path, action) {
29853
- const lockPath = `${path}.lock`;
29854
- const recoveryPath = `${lockPath}${HELD_KEYS_RECOVERY_SUFFIX}`;
29855
- await mkdir3(dirname4(path), { recursive: true });
29856
- const deadline = Date.now() + HELD_KEYS_LOCK_TIMEOUT_MS;
29857
- while (true) {
29858
- const recovery = await readHeldLockObservation(recoveryPath);
29859
- if (recovery !== null) {
29860
- if (heldEntriesLockIsStale(recovery)) {
29861
- await removeHeldLockIfMatches(recoveryPath, recovery);
29862
- continue;
29863
- }
29864
- if (Date.now() >= deadline) {
29865
- throw new CliError(`Cannot access the held retry keys in ${path} because another CLI process kept its recovery lock for too long. Retry the command.`, { errorCode: "held_idempotency_keys_lock_timeout" });
29866
- }
29867
- await waitForHeldEntriesLock();
29868
- continue;
29869
- }
29870
- let handle = null;
29871
- let ownLock = null;
29872
- try {
29873
- handle = await open(lockPath, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, constants.S_IRUSR | constants.S_IWUSR);
29874
- } catch (error2) {
29875
- if (!isNodeError2(error2) || error2.code !== "EEXIST") {
29876
- throw error2;
29877
- }
29878
- const observation = await readHeldLockObservation(lockPath);
29879
- if (observation !== null && heldEntriesLockIsStale(observation)) {
29880
- const recovered = await recoverStaleHeldEntriesLock(lockPath, recoveryPath, observation, deadline);
29881
- if (recovered)
29882
- continue;
29883
- }
29884
- if (Date.now() >= deadline) {
29885
- throw new CliError(`Cannot access the held retry keys in ${path} because another CLI process kept its lock for too long. Retry the command.`, {
29886
- errorCode: "held_idempotency_keys_lock_timeout",
29887
- cause: error2
29888
- });
29889
- }
29890
- await waitForHeldEntriesLock();
29891
- continue;
29892
- }
29893
- try {
29894
- const lockToken = randomUUID3();
29895
- const contents = `${process.pid}
29896
- ${lockToken}
29897
- `;
29898
- await handle.writeFile(contents, "utf8");
29899
- await handle.sync();
29900
- ownLock = {
29901
- contents,
29902
- inode: String((await handle.stat()).ino)
29903
- };
29904
- } catch (error2) {
29905
- await handle.close().catch(() => {
29906
- return;
29907
- });
29908
- if (ownLock !== null) {
29909
- await removeHeldLockIfMatches(lockPath, ownLock).catch(() => {
29910
- return;
29911
- });
29912
- }
29913
- throw error2;
29914
- }
29915
- try {
29916
- await handle.close();
29917
- handle = null;
29918
- } catch (error2) {
29919
- if (ownLock !== null) {
29920
- await removeHeldLockIfMatches(lockPath, ownLock).catch(() => {
29921
- return;
29922
- });
29923
- }
29924
- throw error2;
29925
- }
29926
- try {
29927
- return await action();
29928
- } finally {
29929
- if (ownLock !== null) {
29930
- await removeHeldLockIfMatches(lockPath, ownLock).catch(() => {
29931
- return;
29932
- });
29933
- }
29934
- }
29935
- }
29936
- }
29937
- async function recoverStaleHeldEntriesLock(lockPath, recoveryPath, expected, deadline) {
29938
- while (Date.now() < deadline) {
29939
- const ownRecovery = await tryCreateHeldLock(recoveryPath);
29940
- if (ownRecovery === null) {
29941
- const currentRecovery = await readHeldLockObservation(recoveryPath);
29942
- if (currentRecovery !== null && heldEntriesLockIsStale(currentRecovery)) {
29943
- await removeHeldLockIfMatches(recoveryPath, currentRecovery);
29944
- continue;
29945
- }
29946
- return false;
29947
- }
29948
- try {
29949
- const current = await readHeldLockObservation(lockPath);
29950
- if (current === null)
29951
- return true;
29952
- if (current.inode !== expected.inode || current.contents !== expected.contents || !heldEntriesLockIsStale(current)) {
29953
- return false;
29954
- }
29955
- await removeHeldLockIfMatches(lockPath, current);
29956
- return true;
29957
- } finally {
29958
- await removeHeldLockIfMatches(recoveryPath, ownRecovery).catch(() => {
29959
- return;
29960
- });
29961
- }
29962
- }
29963
- return false;
29964
- }
29965
- async function tryCreateHeldLock(path) {
29966
- let handle = null;
29967
- let ownLock = null;
29968
- try {
29969
- handle = await open(path, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, constants.S_IRUSR | constants.S_IWUSR);
29970
- } catch (error2) {
29971
- if (isNodeError2(error2) && error2.code === "EEXIST")
29972
- return null;
29973
- throw error2;
29974
- }
29975
- try {
29976
- const contents = `${process.pid}
29977
- ${randomUUID3()}
29978
- `;
29979
- await handle.writeFile(contents, "utf8");
29980
- await handle.sync();
29981
- ownLock = {
29982
- contents,
29983
- inode: String((await handle.stat()).ino)
29984
- };
29985
- return ownLock;
29986
- } catch (error2) {
29987
- await handle.close().catch(() => {
29988
- return;
29989
- });
29990
- await removeHeldLockIfMatches(path, ownLock ?? { contents: "", inode: "" }).catch(() => {
29991
- return;
29992
- });
29993
- throw error2;
29994
- } finally {
29995
- await handle.close().catch(() => {
29996
- return;
29997
- });
29998
- }
29999
- }
30000
- function heldEntriesLockIsStale(observation) {
30001
- const owner = observation.contents;
30002
- const pid = Number.parseInt(owner.split(/\s+/u)[0] ?? "", 10);
30003
- if (Number.isSafeInteger(pid) && pid > 0) {
30004
- try {
30005
- process.kill(pid, 0);
30006
- return false;
30007
- } catch (error2) {
30008
- return isNodeError2(error2) && error2.code === "ESRCH";
30009
- }
30010
- }
30011
- return Date.now() - observation.mtimeMs > HELD_KEYS_LOCK_STALE_MS;
30012
- }
30013
- async function readHeldLockObservation(path) {
30014
- let handle = null;
30015
- try {
30016
- handle = await open(path, constants.O_RDONLY);
30017
- const contents = await handle.readFile("utf8");
30018
- const details = await handle.stat();
30019
- return {
30020
- contents,
30021
- inode: String(details.ino),
30022
- mtimeMs: details.mtimeMs
30023
- };
30024
- } catch (error2) {
30025
- if (isNodeError2(error2) && error2.code === "ENOENT") {
30026
- return null;
30027
- }
30028
- throw error2;
30029
- } finally {
30030
- await handle?.close().catch(() => {
30031
- return;
30032
- });
30033
- }
30034
- }
30035
- async function removeHeldLockIfMatches(path, expected) {
30036
- const quarantinePath = `${path}.${process.pid}.${randomUUID3()}.quarantine`;
30037
- try {
30038
- await rename(path, quarantinePath);
30039
- await syncParentDirectory(path);
30040
- } catch (error2) {
30041
- if (isNodeError2(error2) && error2.code === "ENOENT") {
30042
- return false;
30043
- }
30044
- throw error2;
30045
- }
30046
- let quarantine;
30047
- try {
30048
- const details = await open(quarantinePath, constants.O_RDONLY);
30049
- try {
30050
- quarantine = {
30051
- contents: await details.readFile("utf8"),
30052
- inode: String((await details.stat()).ino)
30053
- };
30054
- } finally {
30055
- await details.close();
30056
- }
30057
- } catch (error2) {
30058
- await restoreQuarantinedLock(quarantinePath, path).catch(() => {
30059
- return;
30060
- });
30061
- throw error2;
30062
- }
30063
- if (quarantine.inode === expected.inode && quarantine.contents === expected.contents) {
30064
- await rm2(quarantinePath, { force: true });
30065
- await syncParentDirectory(path);
30066
- return true;
30067
- }
30068
- await restoreQuarantinedLock(quarantinePath, path);
30069
- return false;
30070
- }
30071
- async function restoreQuarantinedLock(quarantinePath, path) {
30072
- try {
30073
- await link(quarantinePath, path);
30074
- } catch (error2) {
30075
- if (!(isNodeError2(error2) && error2.code === "EEXIST")) {
30076
- throw error2;
30077
- }
30078
- }
30079
- await rm2(quarantinePath, { force: true });
30080
- await syncParentDirectory(path);
30081
- }
30082
- function waitForHeldEntriesLock() {
30083
- return new Promise((resolve6) => {
30084
- setTimeout(resolve6, HELD_KEYS_LOCK_RETRY_MS);
30085
- });
30431
+ return withLocalLock(path, action, "held_idempotency_keys_lock_timeout", `Cannot access the held retry keys in ${path} because another CLI process kept its lock for too long. Retry the command.`);
30086
30432
  }
30087
30433
  async function writeHeldEntries(path, entries) {
30088
- await mkdir3(dirname4(path), { recursive: true });
30434
+ await mkdir4(dirname6(path), { recursive: true });
30089
30435
  if (Object.keys(entries).length === 0) {
30090
- await rm2(path, { force: true });
30091
- await syncParentDirectory(path);
30436
+ await rm3(path, { force: true });
30437
+ await syncParentDirectory2(path);
30092
30438
  return;
30093
30439
  }
30094
30440
  const body = `${JSON.stringify(entries, null, 2)}
30095
30441
  `;
30096
- const temporaryPath = `${path}.${process.pid}.${randomUUID3()}.tmp`;
30442
+ const temporaryPath = `${path}.${process.pid}.${randomUUID4()}.tmp`;
30097
30443
  let handle = null;
30098
30444
  try {
30099
- handle = await open(temporaryPath, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, constants.S_IRUSR | constants.S_IWUSR);
30445
+ handle = await open2(temporaryPath, constants2.O_CREAT | constants2.O_EXCL | constants2.O_WRONLY, constants2.S_IRUSR | constants2.S_IWUSR);
30100
30446
  await handle.writeFile(body, "utf8");
30101
30447
  await handle.sync();
30102
30448
  await handle.close();
30103
30449
  handle = null;
30104
- await rename(temporaryPath, path);
30105
- await chmod(path, constants.S_IRUSR | constants.S_IWUSR);
30106
- await syncParentDirectory(path);
30450
+ await rename2(temporaryPath, path);
30451
+ await chmod(path, constants2.S_IRUSR | constants2.S_IWUSR);
30452
+ await syncParentDirectory2(path);
30107
30453
  } finally {
30108
30454
  await handle?.close().catch(() => {
30109
30455
  return;
30110
30456
  });
30111
- await rm2(temporaryPath, { force: true });
30457
+ await rm3(temporaryPath, { force: true });
30112
30458
  }
30113
30459
  }
30114
30460
  async function releaseHold(io, path, fingerprint, key, owner) {
@@ -30147,7 +30493,7 @@ function removeDeadOwners(owners) {
30147
30493
  process.kill(pid, 0);
30148
30494
  return true;
30149
30495
  } catch (error2) {
30150
- return !(isNodeError2(error2) && error2.code === "ESRCH");
30496
+ return !(isNodeError3(error2) && error2.code === "ESRCH");
30151
30497
  }
30152
30498
  });
30153
30499
  }
@@ -30162,13 +30508,13 @@ function ownerProcessId(owner) {
30162
30508
  function unreadable(path, cause) {
30163
30509
  return new CliError(`Cannot read the held retry keys in ${path} (${describe2(cause)}). Repair this state file, or pass --idempotency-key to supply the retry key yourself.`, { errorCode: "held_idempotency_keys_unreadable", cause });
30164
30510
  }
30165
- async function syncParentDirectory(path) {
30511
+ async function syncParentDirectory2(path) {
30166
30512
  let directory = null;
30167
30513
  try {
30168
- directory = await open(dirname4(path), constants.O_RDONLY | (constants.O_DIRECTORY ?? 0));
30514
+ directory = await open2(dirname6(path), constants2.O_RDONLY | (constants2.O_DIRECTORY ?? 0));
30169
30515
  await directory.sync();
30170
30516
  } catch (error2) {
30171
- if (isNodeError2(error2) && (error2.code === "EPERM" || error2.code === "ENOTSUP" || error2.code === "EINVAL")) {
30517
+ if (isNodeError3(error2) && (error2.code === "EPERM" || error2.code === "ENOTSUP" || error2.code === "EINVAL")) {
30172
30518
  return;
30173
30519
  }
30174
30520
  throw error2;
@@ -30179,7 +30525,7 @@ async function syncParentDirectory(path) {
30179
30525
  function describe2(error2) {
30180
30526
  return error2 instanceof Error ? error2.message : String(error2);
30181
30527
  }
30182
- function isNodeError2(error2) {
30528
+ function isNodeError3(error2) {
30183
30529
  return error2 instanceof Error && "code" in error2;
30184
30530
  }
30185
30531
 
@@ -30421,6 +30767,7 @@ async function dispatchGemShare(ctx, args, linkedProject) {
30421
30767
  params2["consents"] = shareConsentList(consent, "--consent");
30422
30768
  }
30423
30769
  copyStringFlag(flags, params2, "--message", "message");
30770
+ copyNoNotifyFlag(flags, params2);
30424
30771
  await emitShareWrite(ctx, flags, "gem.share_create", params2, extractShareCreateSummary);
30425
30772
  return;
30426
30773
  }
@@ -30438,6 +30785,7 @@ async function dispatchGemShare(ctx, args, linkedProject) {
30438
30785
  copyStringFlag(flags, params, "--message", "message");
30439
30786
  copyStringFlag(flags, params, "--expires-at", "expires_at");
30440
30787
  copyStringFlag(flags, params, "--notify-on-open", "notify_on_open");
30788
+ copyNoNotifyFlag(flags, params);
30441
30789
  const retryKey = await gemMutationRetryKey(ctx, flags, "gem.share_create", params);
30442
30790
  params["idempotency_key"] = retryKey.key;
30443
30791
  await emitGemTool(ctx, "gem.share_create", params, {
@@ -30504,16 +30852,18 @@ async function dispatchGemShare(ctx, args, linkedProject) {
30504
30852
  }
30505
30853
  if (verb === "add-people") {
30506
30854
  const flags = parseLocalFlags(rest, ["gems", "share", "add-people"]);
30507
- const shareId = lifecycleResourceArg(flags, "Usage: uru gems share add-people [library/name.gem] <share> --people <email,email>");
30855
+ const shareId = lifecycleResourceArg(flags, "Usage: uru gems share add-people [library/name.gem] <share> --people <email,email> [--no-notify]");
30508
30856
  const people = sharePeopleParams(flags);
30509
30857
  if (people["people"] === undefined) {
30510
30858
  throw new CliError("share add-people requires --people <email,email>");
30511
30859
  }
30512
- await emitShareWrite(ctx, flags, "gem.share_add_people", {
30860
+ const params = {
30513
30861
  path: gemPathFromArgs(flags, linkedProject),
30514
30862
  share_id: shareId,
30515
30863
  ...people
30516
- }, extractShareAddPeopleSummary);
30864
+ };
30865
+ copyNoNotifyFlag(flags, params);
30866
+ await emitShareWrite(ctx, flags, "gem.share_add_people", params, extractShareAddPeopleSummary);
30517
30867
  return;
30518
30868
  }
30519
30869
  if (verb === "remove-person") {
@@ -30992,14 +31342,22 @@ function releaseIsReady(value) {
30992
31342
  function extractShareCreateSummary(value) {
30993
31343
  const share = directResultObject(value, "share");
30994
31344
  const name = stringField3(share, ["name"]);
31345
+ const recipients = share?.["recipients"];
31346
+ const emailed = shareEmailedLine(value, Array.isArray(recipients) && recipients.length > 0);
30995
31347
  if (stringField3(share, ["kind"]) === "editor") {
30996
31348
  const people = share?.["recipient_count"];
30997
31349
  const count = typeof people === "number" ? people : 0;
30998
- return `${name === null ? "Created an editor share." : `Created editor share ${name}.`} ${count} ${count === 1 ? "person" : "people"} can edit the Gem from their Library. Other shares did not change.`;
31350
+ const created2 = `${name === null ? "Created an editor share." : `Created editor share ${name}.`} ${count} ${count === 1 ? "person" : "people"} can edit the Gem from their Library. Other shares did not change.`;
31351
+ return [created2, emailed].filter((line) => line !== null).join(`
31352
+ `);
30999
31353
  }
31000
31354
  const version2 = shareVersionLabel(share);
31001
31355
  const created = `${name === null ? "Created a share." : `Created share ${name}.`} It opens Version${version2 === null ? "" : ` ${version2}`}. Other shares did not change.`;
31002
- const lines = [created, ...recipientUrlLines(share)];
31356
+ const lines = [
31357
+ created,
31358
+ ...emailed === null ? [] : [emailed],
31359
+ ...recipientUrlLines(share)
31360
+ ];
31003
31361
  const url2 = stringField3(share, ["url"]);
31004
31362
  if (url2 !== null) {
31005
31363
  lines.push(url2);
@@ -31026,9 +31384,26 @@ function extractShareAddPeopleSummary(value) {
31026
31384
  const url2 = stringField3(recipient, ["url"]);
31027
31385
  return email3 === null || url2 === null ? [] : [`${email3} ${url2}`];
31028
31386
  });
31029
- return [`Added ${lines.length} ${lines.length === 1 ? "person" : "people"}.`, ...lines].join(`
31387
+ return [
31388
+ `Added ${lines.length} ${lines.length === 1 ? "person" : "people"}.`,
31389
+ shareEmailedLine(value, true),
31390
+ ...lines
31391
+ ].filter((line) => line !== null).join(`
31030
31392
  `);
31031
31393
  }
31394
+ function shareEmailedLine(value, namedPeople) {
31395
+ const emailed = jsonObjectOrNull(value)?.["emailed"];
31396
+ const addresses = Array.isArray(emailed) ? emailed.filter((address) => typeof address === "string") : [];
31397
+ if (addresses.length > 0) {
31398
+ return `Share email queued for ${addresses.join(", ")}.`;
31399
+ }
31400
+ return namedPeople ? "Sent no email." : null;
31401
+ }
31402
+ function copyNoNotifyFlag(flags, params) {
31403
+ if (flags.booleans.has("--no-notify")) {
31404
+ params["notify"] = false;
31405
+ }
31406
+ }
31032
31407
  function extractShareConsentsSummary(value) {
31033
31408
  const share = directResultObject(value, "share");
31034
31409
  const name = stringField3(share, ["name"]) ?? "The share";
@@ -31590,7 +31965,7 @@ async function enqueueGemHostedJob(ctx, flags, linkedProject, options) {
31590
31965
  await emitGemHostedJob(ctx, ack, options.outdir);
31591
31966
  return;
31592
31967
  }
31593
- const hostedJobId = stringField2(ack, ["hosted_job_id", "hostedJobId"]);
31968
+ const hostedJobId = stringField(ack, ["hosted_job_id", "hostedJobId"]);
31594
31969
  const initialStatus = typeof ack["status"] === "string" ? ack["status"].trim() : "";
31595
31970
  if (hostedJobId === undefined) {
31596
31971
  if (GEM_BUILD_TERMINAL_STATUSES.has(initialStatus)) {
@@ -31644,15 +32019,15 @@ async function enqueueGemHostedJob(ctx, flags, linkedProject, options) {
31644
32019
  }
31645
32020
  }
31646
32021
  function gemHostedJobFailureReason(job) {
31647
- const failureKind = stringField2(job, ["failure_kind", "failureKind"]);
31648
- const lastError = stringField2(job, ["last_error", "lastError"]);
32022
+ const failureKind = stringField(job, ["failure_kind", "failureKind"]);
32023
+ const lastError = stringField(job, ["last_error", "lastError"]);
31649
32024
  const parts = [failureKind, lastError].filter((part) => part !== undefined);
31650
32025
  return parts.length === 0 ? "" : ` ${parts.join(": ").slice(0, 500)}`;
31651
32026
  }
31652
32027
  async function emitSettledGemHostedJob(ctx, job, status, outdir) {
31653
32028
  await emitGemHostedJob(ctx, job, outdir);
31654
32029
  if (GEM_BUILD_FAILED_STATUSES.has(status)) {
31655
- const hostedJobId = stringField2(job, ["hosted_job_id", "hostedJobId"]) ?? "unknown";
32030
+ const hostedJobId = stringField(job, ["hosted_job_id", "hostedJobId"]) ?? "unknown";
31656
32031
  throw new CliError(`Gem compile ${hostedJobId} ${status}.${gemHostedJobFailureReason(job)}`, {
31657
32032
  errorCode: `gem_build_${status}`
31658
32033
  });
@@ -31676,7 +32051,7 @@ function emitGemHostedJobSync(ctx, job) {
31676
32051
  writeJson(ctx.io, job);
31677
32052
  return;
31678
32053
  }
31679
- const hostedJobId = stringField2(job, ["hosted_job_id", "hostedJobId"]);
32054
+ const hostedJobId = stringField(job, ["hosted_job_id", "hostedJobId"]);
31680
32055
  const status = typeof job["status"] === "string" ? job["status"] : "";
31681
32056
  if (hostedJobId === undefined) {
31682
32057
  writeText(ctx.io, JSON.stringify(job, null, 2));
@@ -32049,10 +32424,10 @@ async function writeBuildManifest(ctx, outdir, buildResult) {
32049
32424
  const manifest = gemBuildManifestFromBuildResult(buildResult);
32050
32425
  const providerDecision = gemProviderDecisionFromBuildResult(buildResult, manifest);
32051
32426
  const absoluteOutdir = resolve6(ctx.cwd, outdir);
32052
- await mkdir4(absoluteOutdir, { recursive: true });
32053
- await writeFile3(join3(absoluteOutdir, "gem-build-manifest.json"), `${JSON.stringify(manifest, null, 2)}
32427
+ await mkdir5(absoluteOutdir, { recursive: true });
32428
+ await writeFile3(join4(absoluteOutdir, "gem-build-manifest.json"), `${JSON.stringify(manifest, null, 2)}
32054
32429
  `, { mode: 384 });
32055
- await writeFile3(join3(absoluteOutdir, "gem-provider-decision.json"), `${JSON.stringify(providerDecision, null, 2)}
32430
+ await writeFile3(join4(absoluteOutdir, "gem-provider-decision.json"), `${JSON.stringify(providerDecision, null, 2)}
32056
32431
  `, { mode: 384 });
32057
32432
  }
32058
32433
  function gemBuildManifestFromBuildResult(buildResult) {
@@ -32251,8 +32626,8 @@ function stringField4(entry, keys) {
32251
32626
  }
32252
32627
 
32253
32628
  // src/gem-source-commands.ts
32254
- import { mkdir as mkdir5, mkdtemp, rename as rename2, rm as rm3, writeFile as writeFile4 } from "node:fs/promises";
32255
- import { dirname as dirname5, join as join4, resolve as resolve7 } from "node:path";
32629
+ import { mkdir as mkdir6, mkdtemp, rename as rename3, rm as rm4, writeFile as writeFile4 } from "node:fs/promises";
32630
+ import { dirname as dirname7, join as join5, resolve as resolve7 } from "node:path";
32256
32631
  async function gemSourcePull(ctx, args, linkedProject) {
32257
32632
  const flags = parseLocalFlags(args, ["pull"]);
32258
32633
  const gemPath = gemPathFromArgs(flags, linkedProject);
@@ -32431,7 +32806,7 @@ async function pruneRemoteDeletedSourceFiles(cwd, previousLock, localFilesBefore
32431
32806
  preserved.push(projectPath2);
32432
32807
  continue;
32433
32808
  }
32434
- await rm3(join4(resolve7(cwd), ...safePath.split("/")), { force: true });
32809
+ await rm4(join5(resolve7(cwd), ...safePath.split("/")), { force: true });
32435
32810
  deleted.push(projectPath2);
32436
32811
  }
32437
32812
  return { deleted, preserved };
@@ -32618,7 +32993,7 @@ function extractRemoteTreeFilePaths(treeResult) {
32618
32993
  if (!isJsonObject2(item)) {
32619
32994
  continue;
32620
32995
  }
32621
- const rawPath = stringField2(item, ["path", "file_path", "filePath"]);
32996
+ const rawPath = stringField(item, ["path", "file_path", "filePath"]);
32622
32997
  if (rawPath === undefined) {
32623
32998
  continue;
32624
32999
  }
@@ -32626,7 +33001,7 @@ function extractRemoteTreeFilePaths(treeResult) {
32626
33001
  if (path === null) {
32627
33002
  continue;
32628
33003
  }
32629
- const type = stringField2(item, ["type", "kind"]);
33004
+ const type = stringField(item, ["type", "kind"]);
32630
33005
  if (type === "directory" || type === "dir") {
32631
33006
  continue;
32632
33007
  }
@@ -32687,27 +33062,27 @@ async function writePulledSourceFile(cwd, projectPath2, content) {
32687
33062
  if (safePath === null) {
32688
33063
  throw new CliError(`Refusing to write unsafe Gem source path: ${projectPath2}`);
32689
33064
  }
32690
- const localPath = join4(resolve7(cwd), ...safePath.split("/"));
32691
- const localDirectory = dirname5(localPath);
32692
- await mkdir5(localDirectory, { recursive: true });
32693
- const temporaryDirectory = await mkdtemp(join4(localDirectory, ".uru-pull-"));
32694
- const temporaryPath = join4(temporaryDirectory, "source");
33065
+ const localPath = join5(resolve7(cwd), ...safePath.split("/"));
33066
+ const localDirectory = dirname7(localPath);
33067
+ await mkdir6(localDirectory, { recursive: true });
33068
+ const temporaryDirectory = await mkdtemp(join5(localDirectory, ".uru-pull-"));
33069
+ const temporaryPath = join5(temporaryDirectory, "source");
32695
33070
  try {
32696
33071
  await writeFile4(temporaryPath, content, { mode: 384 });
32697
33072
  await replaceFile(temporaryPath, localPath);
32698
33073
  } finally {
32699
- await rm3(temporaryDirectory, { force: true, recursive: true });
33074
+ await rm4(temporaryDirectory, { force: true, recursive: true });
32700
33075
  }
32701
33076
  }
32702
33077
  async function replaceFile(sourcePath, destinationPath) {
32703
33078
  try {
32704
- await rename2(sourcePath, destinationPath);
33079
+ await rename3(sourcePath, destinationPath);
32705
33080
  } catch (error2) {
32706
33081
  if (!isWindowsRenameConflict(error2)) {
32707
33082
  throw error2;
32708
33083
  }
32709
- await rm3(destinationPath, { force: true });
32710
- await rename2(sourcePath, destinationPath);
33084
+ await rm4(destinationPath, { force: true });
33085
+ await rename3(sourcePath, destinationPath);
32711
33086
  }
32712
33087
  }
32713
33088
  function isWindowsRenameConflict(error2) {
@@ -33667,11 +34042,13 @@ async function toolsRun(ctx, args) {
33667
34042
  assertServing(tool);
33668
34043
  const proxyUrl = isPlatformTool(tool) ? null : resolveMcpUrl({ apiUrl: ctx.apiUrl, explicit: flags.values["--mcp-url"] });
33669
34044
  let cachedBearer = null;
34045
+ let expectedSessionAccessToken = ctx.token;
33670
34046
  const mcpCall = proxyUrl === null ? null : {
33671
34047
  url: proxyUrl,
33672
34048
  async bearer() {
33673
34049
  if (cachedBearer === null || cachedBearer.expiresAtMs !== null && cachedBearer.expiresAtMs <= Date.now() + 60000) {
33674
- cachedBearer = await resolveMcpCallBearer(ctx, proxyUrl);
34050
+ cachedBearer = await resolveMcpCallBearer(ctx, proxyUrl, expectedSessionAccessToken);
34051
+ expectedSessionAccessToken = cachedBearer.sessionAccessToken;
33675
34052
  }
33676
34053
  return cachedBearer.token;
33677
34054
  }
@@ -33833,8 +34210,8 @@ function unmappedPlatformToolCallMessage(toolName, params) {
33833
34210
 
33834
34211
  // src/token-env-secret-commands.ts
33835
34212
  import { spawn } from "node:child_process";
33836
- import { chmod as chmod2, mkdir as mkdir6, readFile as readFile9, writeFile as writeFile5 } from "node:fs/promises";
33837
- import { dirname as dirname6, resolve as resolve8 } from "node:path";
34213
+ import { chmod as chmod2, mkdir as mkdir7, readFile as readFile9, writeFile as writeFile5 } from "node:fs/promises";
34214
+ import { dirname as dirname8, resolve as resolve8 } from "node:path";
33838
34215
  import { StringDecoder } from "node:string_decoder";
33839
34216
  async function dispatchTokens(ctx, sub, args, linkedProject) {
33840
34217
  if (sub === "create") {
@@ -33951,7 +34328,7 @@ async function dispatchEnv(ctx, sub, args, linkedProject) {
33951
34328
  const secrets = extractSecretRows(result);
33952
34329
  const content = formatEnvTemplate(secrets);
33953
34330
  const absolutePath = resolve8(ctx.cwd, outputPath);
33954
- await mkdir6(dirname6(absolutePath), { recursive: true });
34331
+ await mkdir7(dirname8(absolutePath), { recursive: true });
33955
34332
  await writeFile5(absolutePath, content, { mode: 384 });
33956
34333
  await chmod2(absolutePath, 384);
33957
34334
  emit(ctx, {
@@ -34003,13 +34380,13 @@ function extractSecretRows(value) {
34003
34380
  if (!isJsonObject2(secret)) {
34004
34381
  continue;
34005
34382
  }
34006
- const name = stringField2(secret, ["secret_name", "name"]);
34383
+ const name = stringField(secret, ["secret_name", "name"]);
34007
34384
  if (name === undefined) {
34008
34385
  continue;
34009
34386
  }
34010
34387
  rows.push({
34011
34388
  name,
34012
- status: stringField2(secret, ["status"]) ?? "unknown",
34389
+ status: stringField(secret, ["status"]) ?? "unknown",
34013
34390
  valueConfigured: secret["value_configured"] === true
34014
34391
  });
34015
34392
  }
@@ -34210,26 +34587,26 @@ function formatCreatedTokenJson(value) {
34210
34587
  const metadata = isJsonObject2(payload["token_metadata"]) ? payload["token_metadata"] : isJsonObject2(payload["tokenMetadata"]) ? payload["tokenMetadata"] : undefined;
34211
34588
  const token = typeof payload["token"] === "string" ? payload["token"] : undefined;
34212
34589
  const formatted = {};
34213
- const id = metadata === undefined ? undefined : stringField2(metadata, ["id"]);
34590
+ const id = metadata === undefined ? undefined : stringField(metadata, ["id"]);
34214
34591
  if (id !== undefined) {
34215
34592
  formatted["id"] = id;
34216
34593
  }
34217
34594
  if (token !== undefined) {
34218
34595
  formatted["token"] = token;
34219
34596
  }
34220
- const keyPrefix = metadata === undefined ? undefined : stringField2(metadata, ["key_prefix", "keyPrefix"]);
34597
+ const keyPrefix = metadata === undefined ? undefined : stringField(metadata, ["key_prefix", "keyPrefix"]);
34221
34598
  if (keyPrefix !== undefined) {
34222
34599
  formatted["key_prefix"] = keyPrefix;
34223
34600
  }
34224
- const expiresAt = metadata === undefined ? undefined : stringField2(metadata, ["expires_at", "expiresAt"]);
34601
+ const expiresAt = metadata === undefined ? undefined : stringField(metadata, ["expires_at", "expiresAt"]);
34225
34602
  if (expiresAt !== undefined) {
34226
34603
  formatted["expires_at"] = expiresAt;
34227
34604
  }
34228
- const gemId = metadata === undefined ? undefined : stringField2(metadata, ["gem_id", "artifact_id", "gemId", "artifactId"]);
34605
+ const gemId = metadata === undefined ? undefined : stringField(metadata, ["gem_id", "artifact_id", "gemId", "artifactId"]);
34229
34606
  if (gemId !== undefined) {
34230
34607
  formatted["gem_id"] = gemId;
34231
34608
  }
34232
- const name = metadata === undefined ? undefined : stringField2(metadata, ["name"]);
34609
+ const name = metadata === undefined ? undefined : stringField(metadata, ["name"]);
34233
34610
  if (name !== undefined) {
34234
34611
  formatted["name"] = name;
34235
34612
  }
@@ -34247,12 +34624,12 @@ function formatTokenList(value) {
34247
34624
  if (!isJsonObject2(token)) {
34248
34625
  return JSON.stringify(token);
34249
34626
  }
34250
- const id = stringField2(token, ["id"]) ?? "unknown";
34251
- const name = stringField2(token, ["name"]) ?? "Unnamed token";
34252
- const gemId = stringField2(token, ["gem_id", "artifact_id"]) ?? "unknown-gem";
34253
- const prefix = stringField2(token, ["key_prefix"]) ?? "unknown-prefix";
34254
- const status = stringField2(token, ["revoked_at"]) === undefined ? "active" : "revoked";
34255
- const expiresAt = stringField2(token, ["expires_at"]) ?? "never";
34627
+ const id = stringField(token, ["id"]) ?? "unknown";
34628
+ const name = stringField(token, ["name"]) ?? "Unnamed token";
34629
+ const gemId = stringField(token, ["gem_id", "artifact_id"]) ?? "unknown-gem";
34630
+ const prefix = stringField(token, ["key_prefix"]) ?? "unknown-prefix";
34631
+ const status = stringField(token, ["revoked_at"]) === undefined ? "active" : "revoked";
34632
+ const expiresAt = stringField(token, ["expires_at"]) ?? "never";
34256
34633
  return `${id} ${name} ${gemId} ${prefix} ${status} expires=${expiresAt}`;
34257
34634
  }).join(`
34258
34635
  `);
@@ -34263,7 +34640,7 @@ function formatTokenRevoke(value) {
34263
34640
  return;
34264
34641
  }
34265
34642
  const metadata = payload["token_metadata"];
34266
- const id = isJsonObject2(metadata) ? stringField2(metadata, ["id"]) : undefined;
34643
+ const id = isJsonObject2(metadata) ? stringField(metadata, ["id"]) : undefined;
34267
34644
  return `Revoked ${id ?? "Gem runtime token"}`;
34268
34645
  }
34269
34646
  function formatSecretPut(value) {
@@ -34271,7 +34648,7 @@ function formatSecretPut(value) {
34271
34648
  if (!isJsonObject2(payload)) {
34272
34649
  return;
34273
34650
  }
34274
- const name = stringField2(payload, ["secret_name"]) ?? "secret";
34651
+ const name = stringField(payload, ["secret_name"]) ?? "secret";
34275
34652
  return `Stored ${name}`;
34276
34653
  }
34277
34654
  function formatSecretsList(value) {
@@ -34287,10 +34664,10 @@ function formatSecretsList(value) {
34287
34664
  if (!isJsonObject2(secret)) {
34288
34665
  return JSON.stringify(secret);
34289
34666
  }
34290
- const name = stringField2(secret, ["secret_name", "name"]) ?? "unknown";
34291
- const status = stringField2(secret, ["status"]) ?? "unknown";
34667
+ const name = stringField(secret, ["secret_name", "name"]) ?? "unknown";
34668
+ const status = stringField(secret, ["status"]) ?? "unknown";
34292
34669
  const configured = secret["value_configured"] === true ? "configured" : "missing_value";
34293
- const updatedAt = stringField2(secret, ["value_updated_at", "updated_at"]) ?? "never";
34670
+ const updatedAt = stringField(secret, ["value_updated_at", "updated_at"]) ?? "never";
34294
34671
  return `${name} ${status} ${configured} updated=${updatedAt}`;
34295
34672
  }).join(`
34296
34673
  `);
@@ -34300,12 +34677,13 @@ function formatSecretRemove(value) {
34300
34677
  if (!isJsonObject2(payload)) {
34301
34678
  return;
34302
34679
  }
34303
- const name = stringField2(payload, ["secret_name"]) ?? "secret";
34680
+ const name = stringField(payload, ["secret_name"]) ?? "secret";
34304
34681
  return `Removed ${name}`;
34305
34682
  }
34306
34683
 
34307
34684
  // src/workspace-commands.ts
34308
34685
  import { access } from "node:fs/promises";
34686
+ import { dirname as dirname9 } from "node:path";
34309
34687
  var STATUS_MARK = {
34310
34688
  ok: "ok ",
34311
34689
  warn: "warn",
@@ -34472,18 +34850,50 @@ function describeError2(error2) {
34472
34850
  return error2 instanceof Error ? error2.message : String(error2);
34473
34851
  }
34474
34852
  async function switchWorkspace(ctx, workspaceId) {
34853
+ const expectedLogin = await captureStoredOAuthLogin({
34854
+ credentialStore: ctx.credentialStore,
34855
+ apiUrl: ctx.apiUrl,
34856
+ config: ctx.config
34857
+ });
34475
34858
  const identity = await client(ctx).validateToken();
34476
34859
  assertWorkspaceAvailable(identity, workspaceId);
34477
- const nextConfig = {
34478
- ...ctx.config,
34479
- apiUrl: ctx.apiUrl,
34480
- workspace: workspaceId
34481
- };
34482
- if (ctx.config.insecureStorage !== true) {
34483
- delete nextConfig.token;
34484
- delete nextConfig.insecureStorage;
34485
- }
34486
- await ctx.store.write(nextConfig);
34860
+ await withCredentialLock(dirname9(ctx.store.path), ctx.apiUrl, async () => {
34861
+ const currentConfig = await ctx.store.read();
34862
+ const keychainValue = expectedLogin.source === "config" ? undefined : await ctx.credentialStore.readToken(ctx.apiUrl);
34863
+ if (!sameConfigLoginAuthority(configLoginAuthority(currentConfig), expectedLogin.configAuthority) || keychainValue !== expectedLogin.keychainValue) {
34864
+ throw new CliError("The saved CLI sign-in changed. Retry the command.", {
34865
+ code: ExitCode.AuthRequired,
34866
+ errorCode: "auth_required"
34867
+ });
34868
+ }
34869
+ if (currentConfig.apiUrl !== undefined && normalizeApiUrl(currentConfig.apiUrl) !== normalizeApiUrl(ctx.apiUrl)) {
34870
+ throw new CliError("The saved CLI sign-in belongs to another API. Retry the command.", {
34871
+ code: ExitCode.AuthRequired,
34872
+ errorCode: "auth_required"
34873
+ });
34874
+ }
34875
+ if (!ctx.tokenIsExplicit) {
34876
+ const storedValue = expectedLogin.storedValue;
34877
+ const storedSessionToken = parseStoredCliOAuthCredential(storedValue ?? "")?.sessionAccessToken ?? storedValue;
34878
+ if (storedSessionToken !== ctx.token) {
34879
+ throw new CliError("The saved CLI sign-in changed. Retry the command.", {
34880
+ code: ExitCode.AuthRequired,
34881
+ errorCode: "auth_required"
34882
+ });
34883
+ }
34884
+ }
34885
+ assertNotAborted(ctx.abortSignal);
34886
+ const nextConfig = {
34887
+ ...currentConfig,
34888
+ apiUrl: ctx.apiUrl,
34889
+ workspace: workspaceId
34890
+ };
34891
+ if (nextConfig.insecureStorage !== true) {
34892
+ delete nextConfig.token;
34893
+ delete nextConfig.insecureStorage;
34894
+ }
34895
+ await ctx.store.write(nextConfig);
34896
+ }, ctx.abortSignal);
34487
34897
  emit(ctx, { ok: true, workspaceId }, `Switched to workspace ${workspaceId}`);
34488
34898
  }
34489
34899
 
@@ -34632,19 +35042,37 @@ async function dispatchCliCommand(ctx, command, linkedProject) {
34632
35042
  });
34633
35043
  }
34634
35044
  async function dispatchLogout({ ctx }) {
35045
+ const captured = await withCredentialLock(dirname10(ctx.store.path), ctx.apiUrl, async () => captureStoredOAuthLogin({
35046
+ credentialStore: ctx.credentialStore,
35047
+ apiUrl: ctx.apiUrl,
35048
+ config: await ctx.store.read()
35049
+ }), ctx.abortSignal);
34635
35050
  let revocationFailure;
34636
35051
  try {
34637
35052
  await revokeStoredOAuthLogin({
34638
35053
  credentialStore: ctx.credentialStore,
34639
35054
  apiUrl: ctx.apiUrl,
34640
- config: ctx.config,
35055
+ config: captured.config,
35056
+ storedValue: captured.storedValue,
34641
35057
  ...ctx.fetch === undefined ? {} : { fetch: ctx.fetch }
34642
35058
  });
34643
35059
  } catch (error2) {
34644
35060
  revocationFailure = error2;
34645
- } finally {
34646
- await ctx.credentialStore.clearToken(ctx.apiUrl);
34647
- await ctx.store.clear();
35061
+ }
35062
+ const cleared = await withCredentialLock(dirname10(ctx.store.path), ctx.apiUrl, () => clearStoredOAuthLoginIfCurrent({
35063
+ credentialStore: ctx.credentialStore,
35064
+ store: ctx.store,
35065
+ apiUrl: ctx.apiUrl,
35066
+ expectedConfigAuthority: captured.configAuthority,
35067
+ source: captured.source,
35068
+ expectedStoredValue: captured.storedValue,
35069
+ abortSignal: ctx.abortSignal
35070
+ }), ctx.abortSignal);
35071
+ if (!cleared && revocationFailure === undefined) {
35072
+ throw new CliError("The saved CLI sign-in changed. Retry the command.", {
35073
+ code: ExitCode.AuthRequired,
35074
+ errorCode: "auth_required"
35075
+ });
34648
35076
  }
34649
35077
  if (revocationFailure !== undefined) {
34650
35078
  throw new CliError("Logged out locally, but server-side credential revocation could not be confirmed.", {
@@ -34691,11 +35119,11 @@ async function dispatchRegistryFamilyCommand({
34691
35119
  }
34692
35120
 
34693
35121
  // src/config.ts
34694
- import { chmod as chmod3, mkdir as mkdir7, open as open2, readFile as readFile10, rename as rename3, rm as rm4 } from "node:fs/promises";
34695
- import { constants as constants2 } from "node:fs";
34696
- import { randomUUID as randomUUID4 } from "node:crypto";
34697
- import { homedir as homedir2 } from "node:os";
34698
- import { dirname as dirname7, join as join5 } from "node:path";
35122
+ import { chmod as chmod3, mkdir as mkdir8, open as open3, readFile as readFile10, rename as rename4, rm as rm5 } from "node:fs/promises";
35123
+ import { constants as constants3 } from "node:fs";
35124
+ import { randomUUID as randomUUID5 } from "node:crypto";
35125
+ import { homedir as homedir3 } from "node:os";
35126
+ import { dirname as dirname11, join as join6 } from "node:path";
34699
35127
  function resolveConfigHome(env = process.env) {
34700
35128
  const explicit = env["URU_CONFIG_HOME"]?.trim();
34701
35129
  if (explicit) {
@@ -34703,12 +35131,12 @@ function resolveConfigHome(env = process.env) {
34703
35131
  }
34704
35132
  const xdg = env["XDG_CONFIG_HOME"]?.trim();
34705
35133
  if (xdg) {
34706
- return join5(xdg, "uru");
35134
+ return join6(xdg, "uru");
34707
35135
  }
34708
- return join5(env["HOME"]?.trim() || homedir2(), ".config", "uru");
35136
+ return join6(env["HOME"]?.trim() || homedir3(), ".config", "uru");
34709
35137
  }
34710
35138
  function configPath(env = process.env) {
34711
- return join5(resolveConfigHome(env), "config.json");
35139
+ return join6(resolveConfigHome(env), "config.json");
34712
35140
  }
34713
35141
  function createConfigStore(path = configPath()) {
34714
35142
  return {
@@ -34719,36 +35147,36 @@ function createConfigStore(path = configPath()) {
34719
35147
  const parsed = JSON.parse(raw);
34720
35148
  return sanitizeConfig(parsed);
34721
35149
  } catch (error2) {
34722
- if (isNodeError3(error2) && error2.code === "ENOENT") {
35150
+ if (isNodeError4(error2) && error2.code === "ENOENT") {
34723
35151
  return {};
34724
35152
  }
34725
35153
  throw error2;
34726
35154
  }
34727
35155
  },
34728
35156
  async write(config2) {
34729
- await mkdir7(dirname7(path), { recursive: true });
35157
+ await mkdir8(dirname11(path), { recursive: true });
34730
35158
  const body = `${JSON.stringify(sanitizeConfig(config2), null, 2)}
34731
35159
  `;
34732
- const temporaryPath = `${path}.${process.pid}.${randomUUID4()}.tmp`;
35160
+ const temporaryPath = `${path}.${process.pid}.${randomUUID5()}.tmp`;
34733
35161
  let handle = null;
34734
35162
  try {
34735
- handle = await open2(temporaryPath, constants2.O_CREAT | constants2.O_EXCL | constants2.O_WRONLY, constants2.S_IRUSR | constants2.S_IWUSR);
35163
+ handle = await open3(temporaryPath, constants3.O_CREAT | constants3.O_EXCL | constants3.O_WRONLY, constants3.S_IRUSR | constants3.S_IWUSR);
34736
35164
  await handle.writeFile(body, "utf8");
34737
35165
  await handle.sync();
34738
35166
  await handle.close();
34739
35167
  handle = null;
34740
- await chmod3(temporaryPath, constants2.S_IRUSR | constants2.S_IWUSR);
34741
- await rename3(temporaryPath, path);
34742
- await chmod3(path, constants2.S_IRUSR | constants2.S_IWUSR);
35168
+ await chmod3(temporaryPath, constants3.S_IRUSR | constants3.S_IWUSR);
35169
+ await rename4(temporaryPath, path);
35170
+ await chmod3(path, constants3.S_IRUSR | constants3.S_IWUSR);
34743
35171
  } finally {
34744
35172
  await handle?.close().catch(() => {
34745
35173
  return;
34746
35174
  });
34747
- await rm4(temporaryPath, { force: true });
35175
+ await rm5(temporaryPath, { force: true });
34748
35176
  }
34749
35177
  },
34750
35178
  async clear() {
34751
- await rm4(path, { force: true });
35179
+ await rm5(path, { force: true });
34752
35180
  }
34753
35181
  };
34754
35182
  }
@@ -34780,7 +35208,7 @@ function sanitizeConfig(value) {
34780
35208
  }
34781
35209
  return config2;
34782
35210
  }
34783
- function isNodeError3(error2) {
35211
+ function isNodeError4(error2) {
34784
35212
  return error2 instanceof Error && "code" in error2;
34785
35213
  }
34786
35214
 
@@ -35258,6 +35686,7 @@ function terminalWidth(stream, env) {
35258
35686
  }
35259
35687
 
35260
35688
  // src/update-notifier.ts
35689
+ import { dirname as dirname12 } from "node:path";
35261
35690
  var UPDATE_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
35262
35691
  async function maybeNotifyCliUpdate(ctx, options = {}) {
35263
35692
  if (!shouldCheckForUpdate(ctx, options.env ?? process.env)) {
@@ -35270,11 +35699,13 @@ async function maybeNotifyCliUpdate(ctx, options = {}) {
35270
35699
  }
35271
35700
  const checkedConfig = withUpdateCheckTimestamp(currentConfig, now);
35272
35701
  await writeConfigBestEffort(ctx, checkedConfig);
35702
+ if (ctx.abortSignal.aborted)
35703
+ return;
35273
35704
  const latestVersion = await fetchLatestCliVersion({
35274
35705
  fetchImpl: ctx.fetch ?? fetch,
35275
35706
  parentSignal: ctx.abortSignal
35276
35707
  });
35277
- if (latestVersion === undefined) {
35708
+ if (ctx.abortSignal.aborted || latestVersion === undefined) {
35278
35709
  return;
35279
35710
  }
35280
35711
  if (!isValidRegistryVersion(latestVersion)) {
@@ -35287,7 +35718,7 @@ async function maybeNotifyCliUpdate(ctx, options = {}) {
35287
35718
  latestVersion
35288
35719
  }
35289
35720
  });
35290
- if (!isCliVersionNewer(latestVersion, CLI_VERSION)) {
35721
+ if (ctx.abortSignal.aborted || !isCliVersionNewer(latestVersion, CLI_VERSION)) {
35291
35722
  return;
35292
35723
  }
35293
35724
  ctx.io.stderr.write(`A newer Uru CLI is available: ${CLI_VERSION} → ${latestVersion}. ` + `Run npm install -g ${CLI_PACKAGE_NAME}@latest
@@ -35301,7 +35732,7 @@ async function readConfigBestEffort(ctx) {
35301
35732
  }
35302
35733
  }
35303
35734
  function shouldCheckForUpdate(ctx, env) {
35304
- return ctx.outputFormat === "text" && ctx.terminal.stderrIsTty && !ctx.terminal.ci && env["NO_UPDATE_NOTIFIER"] === undefined && env["URU_NO_UPDATE_NOTIFIER"] === undefined;
35735
+ return !ctx.abortSignal.aborted && ctx.outputFormat === "text" && ctx.terminal.stderrIsTty && !ctx.terminal.ci && env["NO_UPDATE_NOTIFIER"] === undefined && env["URU_NO_UPDATE_NOTIFIER"] === undefined;
35305
35736
  }
35306
35737
  function isUpdateCheckDue(config2, now) {
35307
35738
  const raw = config2.update?.lastCheckedAt;
@@ -35322,7 +35753,14 @@ function withUpdateCheckTimestamp(config2, now) {
35322
35753
  }
35323
35754
  async function writeConfigBestEffort(ctx, config2) {
35324
35755
  try {
35325
- await ctx.store.write(config2);
35756
+ await withCredentialLock(dirname12(ctx.store.path), ctx.apiUrl, async () => {
35757
+ const current = await ctx.store.read().catch(() => ctx.config);
35758
+ assertNotAborted(ctx.abortSignal);
35759
+ await ctx.store.write({
35760
+ ...current,
35761
+ ...config2.update === undefined ? {} : { update: config2.update }
35762
+ });
35763
+ }, ctx.abortSignal);
35326
35764
  } catch {}
35327
35765
  }
35328
35766
  function isValidRegistryVersion(version2) {
@@ -35370,6 +35808,7 @@ async function runCli(options) {
35370
35808
  store,
35371
35809
  apiUrl,
35372
35810
  config: config2,
35811
+ abortSignal: cancellation.signal,
35373
35812
  ...workspace2 === undefined ? {} : { workspaceId: workspace2 },
35374
35813
  ...options.fetch === undefined ? {} : { fetch: options.fetch },
35375
35814
  ...parsed.command[0] === "login" ? { recoverInvalidCredential: true } : {}
@@ -35397,7 +35836,7 @@ async function runCli(options) {
35397
35836
  tokenIsExplicit: credentialSource === "explicit",
35398
35837
  ...workspace2 !== undefined ? { workspace: workspace2 } : {},
35399
35838
  cwd,
35400
- home: nonEmptyString(options.env?.["HOME"]) ?? homedir3(),
35839
+ home: nonEmptyString(options.env?.["HOME"]) ?? homedir4(),
35401
35840
  json: outputFormat === "json",
35402
35841
  outputFormat,
35403
35842
  noInput: parsed.flags.noInput,
@@ -35507,6 +35946,7 @@ async function dispatchWithImplicitLogin(ctx, command, linkedProject) {
35507
35946
  store: activeCtx.store,
35508
35947
  apiUrl: activeCtx.apiUrl,
35509
35948
  config: nextConfig2,
35949
+ abortSignal: activeCtx.abortSignal,
35510
35950
  forceRefresh: true,
35511
35951
  ...selectedWorkspace2 === undefined ? {} : { workspaceId: selectedWorkspace2 },
35512
35952
  ...activeCtx.fetch === undefined ? {} : { fetch: activeCtx.fetch }
@@ -35536,6 +35976,7 @@ async function dispatchWithImplicitLogin(ctx, command, linkedProject) {
35536
35976
  store: activeCtx.store,
35537
35977
  apiUrl: activeCtx.apiUrl,
35538
35978
  config: nextConfig,
35979
+ abortSignal: activeCtx.abortSignal,
35539
35980
  ...selectedWorkspace === undefined ? {} : { workspaceId: selectedWorkspace },
35540
35981
  ...activeCtx.fetch === undefined ? {} : { fetch: activeCtx.fetch }
35541
35982
  });