@notis_ai/cli 0.2.29 → 0.2.30

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.
Files changed (64) hide show
  1. package/README.md +25 -8
  2. package/dist/agent-hooks/notis-agent-hook.mjs +1030 -610
  3. package/dist/base-skills/notis-cli/.notis-base-skill.json +1 -1
  4. package/dist/base-skills/notis-cli/SKILL.md +11 -0
  5. package/dist/base-skills/notis-spaces/.notis-base-skill.json +1 -1
  6. package/dist/base-skills/notis-spaces/references/release.md +6 -5
  7. package/dist/base-skills/notis-spaces/references/sdk.md +82 -17
  8. package/dist/sdk/src/hooks/useThreadItem.ts +56 -0
  9. package/dist/sdk/src/index.ts +6 -1
  10. package/dist/sdk/src/runtime.ts +8 -1
  11. package/dist/sdk/src/space.ts +230 -0
  12. package/dist/skill-sync-worker.mjs +185 -30
  13. package/dist/space-harness/host.js +237 -93
  14. package/dist/space-sdk/dist/{chunk-BFGB6XXC.js → chunk-6GJ2BS7B.js} +1 -3
  15. package/dist/space-sdk/dist/index.js +4 -2
  16. package/dist/space-sdk/dist/ui.js +18 -13
  17. package/dist/space-sdk/src/hooks/useThreadItem.d.ts +28 -0
  18. package/dist/space-sdk/src/index.d.ts +3 -1
  19. package/dist/space-sdk/src/runtime.d.ts +8 -1
  20. package/dist/space-sdk/src/space.ts +230 -0
  21. package/dist/space-sdk/src/tailwind-candidates.d.ts +492 -14
  22. package/dist/space-sdk/src/ui/actions/useToast.d.ts +2 -0
  23. package/dist/space-sdk/src/ui/comments/CommentPane.d.ts +56 -10
  24. package/dist/space-sdk/src/ui/comments/PassageComments.d.ts +16 -7
  25. package/dist/space-sdk/src/ui/comments/agentRuntime.d.ts +59 -0
  26. package/dist/space-sdk/src/ui/comments/commentFiles.d.ts +5 -2
  27. package/dist/space-sdk/src/ui/comments/commentModel.d.ts +103 -8
  28. package/dist/space-sdk/src/ui/comments/commentWords.d.ts +82 -0
  29. package/dist/space-sdk/src/ui/comments/hostComments.d.ts +37 -0
  30. package/dist/space-sdk/src/ui/comments/index.d.ts +4 -0
  31. package/dist/space-sdk/src/ui/comments/paneParts.d.ts +119 -0
  32. package/dist/space-sdk/src/ui/comments/useCommentRouting.d.ts +75 -0
  33. package/dist/space-sdk/src/ui/comments/useComments.d.ts +147 -15
  34. package/dist/space-sdk/src/ui/comments/usePassageComments.d.ts +24 -8
  35. package/dist/space-sdk/src/ui/index.d.ts +2 -1
  36. package/dist/space-sdk/src/ui/layout/SidePane.d.ts +6 -1
  37. package/dist/space-sdk/src/ui/overlay/Tooltip.d.ts +8 -2
  38. package/dist/space-sdk/src/ui/styles.d.ts +27 -5
  39. package/dist/view-renderer/dist/host.js +307 -163
  40. package/dist/view-renderer/src/host.tsx +6 -3
  41. package/dist/view-renderer/src/renderer.js +25 -2
  42. package/package.json +3 -3
  43. package/skills/notis-cli/AGENT_INSTRUCTIONS.md +2 -1
  44. package/skills/notis-spaces/cli.md +8 -8
  45. package/src/cli.js +10 -2
  46. package/src/command-specs/computer.js +21 -1
  47. package/src/command-specs/profile.js +12 -5
  48. package/src/command-specs/spaces.js +30 -16
  49. package/src/runtime/agent-identity.js +187 -0
  50. package/src/runtime/api-hosts.js +92 -0
  51. package/src/runtime/channel.js +3 -7
  52. package/src/runtime/oauth.js +95 -4
  53. package/src/runtime/profiles.js +200 -41
  54. package/src/runtime/skill-sync-service.js +4 -5
  55. package/src/runtime/space-platform.js +2 -0
  56. package/src/runtime/space-source.js +66 -1
  57. package/src/runtime/space-test-server.js +20 -4
  58. package/src/runtime/space-verification.js +5 -1
  59. package/src/runtime/telemetry.js +14 -1
  60. package/src/runtime/transport.js +12 -0
  61. package/src/runtime/upsell.js +3 -6
  62. package/src/runtime/view-render.js +3 -1
  63. package/src/skill-sync-worker.js +13 -2
  64. package/src/space-harness-host.ts +6 -3
@@ -0,0 +1,92 @@
1
+ /**
2
+ * The live Notis APIs, one row per release channel: the API's current name,
3
+ * the names it answered on before (retired), and the channel's Portal.
4
+ *
5
+ * Every CLI list of live API hosts derives from this table. When a channel's
6
+ * API moves to a new name, the new name becomes `current` and the old one
7
+ * joins `retired`. A retired name stays listed after its domain is removed:
8
+ * profiles that stored it keep being recognised and renamed to `current`
9
+ * (CLI-037), and sign-ins recorded on it are known to be spent (CLI-038).
10
+ * Mirrors server/lib/release_channels.py (CHANNEL_ORIGINS, _LEGACY_HOSTNAMES).
11
+ */
12
+ const CHANNEL_APIS = {
13
+ stable: { current: 'api.notis.ai', retired: [], portal: 'https://app.notis.ai' },
14
+ nightly: { current: 'api-nightly.notis.ai', retired: ['api-beta.notis.ai'], portal: 'https://app-nightly.notis.ai' },
15
+ };
16
+
17
+ const HOST_ROWS = Object.entries(CHANNEL_APIS).flatMap(([channel, row]) => [
18
+ { host: row.current, channel, current: true },
19
+ ...row.retired.map(host => ({ host, channel, current: false })),
20
+ ]);
21
+
22
+ /** Every live API hostname, current names first. */
23
+ export const LIVE_API_HOSTS = [
24
+ ...HOST_ROWS.filter(row => row.current),
25
+ ...HOST_ROWS.filter(row => !row.current),
26
+ ].map(row => row.host);
27
+
28
+ /** Every live API origin (`https://<host>`), current names first. */
29
+ export const LIVE_API_ORIGINS = LIVE_API_HOSTS.map(host => `https://${host}`);
30
+
31
+ /** The channel a live API hostname serves, else null. */
32
+ export function channelForApiHost(hostname) {
33
+ return HOST_ROWS.find(row => row.host === hostname)?.channel || null;
34
+ }
35
+
36
+ /** The Portal of the channel a live API hostname serves, else null. */
37
+ export function portalOriginForApiHost(hostname) {
38
+ const channel = channelForApiHost(hostname);
39
+ return channel ? CHANNEL_APIS[channel].portal : null;
40
+ }
41
+
42
+ /** The current API origin of a channel (`https://api-nightly.notis.ai`). */
43
+ export function currentApiOrigin(channel) {
44
+ return `https://${CHANNEL_APIS[channel].current}`;
45
+ }
46
+
47
+ /** Whether a hostname is a retired name of a live API. */
48
+ export function isRetiredApiHost(hostname) {
49
+ return HOST_ROWS.some(row => row.host === hostname && !row.current);
50
+ }
51
+
52
+ function parsedHttps(value) {
53
+ if (typeof value !== 'string' || !value) return null;
54
+ try {
55
+ const parsed = new URL(value);
56
+ return parsed.protocol === 'https:' ? parsed : null;
57
+ } catch {
58
+ return null;
59
+ }
60
+ }
61
+
62
+ /**
63
+ * Whether a value is exactly a live API origin: `https://<live host>` with at
64
+ * most a trailing slash, no port, path, query or fragment.
65
+ */
66
+ export function isLiveApiOrigin(value) {
67
+ const parsed = parsedHttps(value);
68
+ return Boolean(parsed)
69
+ && LIVE_API_HOSTS.includes(parsed.hostname)
70
+ && !parsed.port
71
+ && /^\/*$/.test(parsed.pathname)
72
+ && !parsed.search
73
+ && !parsed.hash;
74
+ }
75
+
76
+ /**
77
+ * The current origin for a value that is exactly a retired API origin
78
+ * (`https://api-beta.notis.ai` -> `https://api-nightly.notis.ai`), else null.
79
+ * An address with a port, path or query is not the retired API and is left
80
+ * to the caller as stored.
81
+ */
82
+ export function renamedRetiredApiOrigin(value) {
83
+ if (!isLiveApiOrigin(value)) return null;
84
+ const { hostname } = new URL(value);
85
+ return isRetiredApiHost(hostname) ? currentApiOrigin(channelForApiHost(hostname)) : null;
86
+ }
87
+
88
+ /** Whether a URL of any shape points at a retired API name over HTTPS. */
89
+ export function isOnRetiredApiHost(value) {
90
+ const parsed = parsedHttps(value);
91
+ return Boolean(parsed) && isRetiredApiHost(parsed.hostname);
92
+ }
@@ -12,16 +12,11 @@
12
12
 
13
13
  import { existsSync } from 'node:fs';
14
14
  import { isAbsolute } from 'node:path';
15
+ import { channelForApiHost } from './api-hosts.js';
15
16
 
16
17
  export const RELEASE_CHANNELS = ['stable', 'nightly'];
17
18
  // Keep equal to the dist-tags in scripts/release-channels.cjs (a test checks).
18
19
  const CHANNEL_TAGS = { stable: 'latest', nightly: 'nightly' };
19
- // Live API hosts and the channel each one serves.
20
- const API_HOST_CHANNELS = {
21
- 'api.notis.ai': 'stable',
22
- 'api-beta.notis.ai': 'nightly',
23
- 'api-nightly.notis.ai': 'nightly',
24
- };
25
20
  export const CLI_PACKAGE_NAME = '@notis_ai/cli';
26
21
  // Set on the child so a build that disagrees about its own channel — a bad
27
22
  // version string, a half-published tag — cannot bounce the process forever.
@@ -49,7 +44,8 @@ export function normalizeReleaseChannel(value) {
49
44
  export function channelFromApiBase(apiBase) {
50
45
  if (typeof apiBase !== 'string' || !apiBase) return null;
51
46
  try {
52
- return API_HOST_CHANNELS[new URL(apiBase).hostname] || null;
47
+ // The live API hosts and the channel each one serves (api-hosts.js).
48
+ return channelForApiHost(new URL(apiBase).hostname);
53
49
  } catch {
54
50
  // A malformed endpoint says nothing about the channel.
55
51
  return null;
@@ -24,6 +24,7 @@ import { createInterface } from 'node:readline/promises';
24
24
 
25
25
  import { CliError, EXIT_CODES, usageError } from './errors.js';
26
26
  import { readComputerIdentity } from './computer-identity.js';
27
+ import { isOnRetiredApiHost, renamedRetiredApiOrigin } from './api-hosts.js';
27
28
  import { getAuthRecovery, getRetryRecovery, quoteShellArgument } from './auth-recovery.js';
28
29
  import {
29
30
  channelFromApiBase,
@@ -37,7 +38,11 @@ import {
37
38
  getOAuthApiBase,
38
39
  getOAuthResource,
39
40
  getProfile,
41
+ signedOutRoute,
40
42
  loadConfig,
43
+ oauthGrantIsDead,
44
+ oauthGrantOnRetiredAddress,
45
+ refreshTokenFingerprint,
41
46
  resolveConfigFile,
42
47
  updateConfig,
43
48
  } from './profiles.js';
@@ -348,6 +353,26 @@ function readRefreshAnswer(runtime, { response, text }) {
348
353
  return payload;
349
354
  }
350
355
 
356
+ // The server refused this refresh token for good: remember which one, so the
357
+ // profile routes like a signed-out one (oauthGrantIsDead) until a new grant
358
+ // replaces it. Best effort; the refusal itself is still reported.
359
+ function recordRefusedRefreshToken(runtime, refreshToken) {
360
+ if (!refreshToken) return;
361
+ try {
362
+ updateConfig((latest) => {
363
+ const current = latest.profiles?.[runtime.profileName];
364
+ if (!current || current.oauth_refresh_token !== refreshToken) return latest;
365
+ latest.profiles[runtime.profileName] = {
366
+ ...current,
367
+ oauth_refresh_rejected_for: refreshTokenFingerprint(refreshToken),
368
+ };
369
+ return latest;
370
+ });
371
+ } catch {
372
+ // The refusal is reported either way; the next refresh records it again.
373
+ }
374
+ }
375
+
351
376
  async function persistRefreshedSignIn(runtime, metadata, tokenResponse) {
352
377
  let lastError = null;
353
378
  for (const delay of [0, ...OAUTH_REFRESH_SAVE_RETRY_DELAYS_MS]) {
@@ -1030,6 +1055,10 @@ function persistOAuthTokenResponse(runtime, metadata, tokenResponse) {
1030
1055
  const now = Math.floor(Date.now() / 1000);
1031
1056
  const payload = decodeJwtPayload(tokenResponse.access_token);
1032
1057
  const oauthApiBase = (metadata.apiBase || runtime.apiBase || '').replace(/\/+$/, '');
1058
+ const refreshExpiryFromServer = Boolean(tokenResponse.refresh_token)
1059
+ && tokenResponse.refresh_expires_in !== null
1060
+ && tokenResponse.refresh_expires_in !== ''
1061
+ && Number.isFinite(Number(tokenResponse.refresh_expires_in));
1033
1062
  const config = updateConfig((latest) => {
1034
1063
  const next = ensureProfile(latest, runtime.profileName);
1035
1064
  const profile = next.profiles[runtime.profileName];
@@ -1052,8 +1081,14 @@ function persistOAuthTokenResponse(runtime, metadata, tokenResponse) {
1052
1081
  oauth_access_token: tokenResponse.access_token,
1053
1082
  oauth_refresh_token: tokenResponse.refresh_token || profile.oauth_refresh_token,
1054
1083
  oauth_access_expires_at: now + Number(tokenResponse.expires_in || 0),
1055
- oauth_refresh_expires_at:
1056
- now + Number(tokenResponse.refresh_expires_in || DEFAULT_REFRESH_EXPIRES_IN),
1084
+ oauth_refresh_expires_at: now + (
1085
+ refreshExpiryFromServer ? Number(tokenResponse.refresh_expires_in) : DEFAULT_REFRESH_EXPIRES_IN
1086
+ ),
1087
+ // Only an expiry the server sent for the refresh token it sent may later
1088
+ // prove the grant dead (oauthGrantIsDead); the default above is a guess.
1089
+ oauth_refresh_expiry_from_server: refreshExpiryFromServer || undefined,
1090
+ // A new grant or a renewed one is no longer the token the server refused.
1091
+ oauth_refresh_rejected_for: undefined,
1057
1092
  oauth_client_id: metadata.clientId,
1058
1093
  oauth_issuer: metadata.issuer,
1059
1094
  oauth_scopes: String(tokenResponse.scope || '').split(/\s+/).filter(Boolean),
@@ -2029,7 +2064,8 @@ function updateRuntimeFromOAuthProfile(runtime, profile) {
2029
2064
  }
2030
2065
 
2031
2066
  function assertOAuthApiTarget(runtime, profile) {
2032
- const requestedApiBase = String(runtime.requestedApiBase || '').replace(/\/+$/, '');
2067
+ const requestedApiBase = renamedRetiredApiOrigin(runtime.requestedApiBase)
2068
+ || String(runtime.requestedApiBase || '').replace(/\/+$/, '');
2033
2069
  const oauthApiBase = getOAuthApiBase(profile);
2034
2070
  if (requestedApiBase && oauthApiBase && requestedApiBase !== oauthApiBase) {
2035
2071
  throw oauthError(
@@ -2039,12 +2075,34 @@ function assertOAuthApiTarget(runtime, profile) {
2039
2075
  }
2040
2076
  }
2041
2077
 
2078
+ /**
2079
+ * A grant minted while the nightly API answered as api-beta.notis.ai
2080
+ * (oauthGrantOnRetiredAddress) is refused by the nightly service and its
2081
+ * refresh endpoint is the retired domain, so it is never refreshed or sent:
2082
+ * the person is told to sign in again, which starts on stable and follows the
2083
+ * account (CLI-035, CLI-038).
2084
+ */
2085
+ function retiredAddressGrantError(runtime, profile) {
2086
+ const { hints } = getAuthRecovery(runtime);
2087
+ const retiredHost = [profile.oauth_issuer, getOAuthResource(profile)]
2088
+ .filter(isOnRetiredApiHost)
2089
+ .map(value => new URL(value).hostname)[0];
2090
+ return oauthError(
2091
+ 'oauth_grant_retired_address',
2092
+ `This sign-in was made on ${retiredHost}, a retired address of Notis that no longer accepts it. `
2093
+ + `Sign in again: ${hints[0].command}`,
2094
+ hints,
2095
+ { retired_host: retiredHost },
2096
+ );
2097
+ }
2098
+
2042
2099
  export async function ensureFreshOAuthCredential(runtime, fetchImpl = fetch) {
2043
2100
  if (runtime.credentialKind !== 'oauth') {
2044
2101
  return Boolean(runtime.jwt);
2045
2102
  }
2046
2103
 
2047
2104
  const profile = getProfile(loadConfig(), runtime.profileName);
2105
+ if (oauthGrantOnRetiredAddress(profile)) throw retiredAddressGrantError(runtime, profile);
2048
2106
  assertOAuthApiTarget(runtime, profile);
2049
2107
  if (!credentialIsExpired({ credentialKind: 'oauth' }, profile)) {
2050
2108
  updateRuntimeFromOAuthProfile(runtime, profile);
@@ -2322,6 +2380,8 @@ export async function loginWithOAuth(
2322
2380
  if (
2323
2381
  storedProfile.oauth_access_token
2324
2382
  && !credentialIsExpired({ credentialKind: 'oauth' }, storedProfile)
2383
+ // A grant the server refused is no sign-in to confirm.
2384
+ && !oauthGrantIsDead(storedProfile)
2325
2385
  ) {
2326
2386
  assertOAuthApiTarget(runtime, storedProfile);
2327
2387
  updateRuntimeFromOAuthProfile(runtime, storedProfile);
@@ -2788,6 +2848,9 @@ export async function refreshOAuthCredential(runtime, fetchImpl = fetch, tokenRe
2788
2848
  stopTouchingLocks = keepLockFoldersFresh([profileLock, oauthLockDir()]);
2789
2849
  const config = loadConfig();
2790
2850
  const profile = getProfile(config, runtime.profileName);
2851
+ // Checked before the API target: a retired grant's own address is the
2852
+ // retired one, and nothing is sent with it (CLI-038).
2853
+ if (oauthGrantOnRetiredAddress(profile)) throw retiredAddressGrantError(runtime, profile);
2791
2854
  assertOAuthApiTarget(runtime, profile);
2792
2855
  if (
2793
2856
  profile.oauth_access_token
@@ -2834,7 +2897,15 @@ export async function refreshOAuthCredential(runtime, fetchImpl = fetch, tokenRe
2834
2897
  failure.cause,
2835
2898
  );
2836
2899
  }
2837
- const rotatedResponse = readRefreshAnswer(runtime, answer);
2900
+ let rotatedResponse;
2901
+ try {
2902
+ rotatedResponse = readRefreshAnswer(runtime, answer);
2903
+ } catch (refusal) {
2904
+ if (refusal?.code === 'invalid_grant') {
2905
+ recordRefusedRefreshToken(runtime, profile.oauth_refresh_token);
2906
+ }
2907
+ throw refusal;
2908
+ }
2838
2909
  const updated = await persistRefreshedSignIn(runtime, metadata, rotatedResponse);
2839
2910
  updateRuntimeFromOAuthProfile(runtime, updated);
2840
2911
  return true;
@@ -2928,6 +2999,9 @@ export async function logoutOAuth(runtime, { allProfiles = false } = {}, fetchIm
2928
2999
  revocationToken
2929
3000
  && profile.oauth_client_id
2930
3001
  && profile.oauth_issuer
3002
+ // The nightly service no longer knows a grant minted on its retired
3003
+ // name, and that name's domain is gone (CLI-038).
3004
+ && !oauthGrantOnRetiredAddress(profile)
2931
3005
  ) {
2932
3006
  try {
2933
3007
  const metadata = storedOAuthMetadata(runtime, profile);
@@ -2953,12 +3027,29 @@ export async function logoutOAuth(runtime, { allProfiles = false } = {}, fetchIm
2953
3027
  // A named pending login has no stored profile yet. Cancelling it must
2954
3028
  // not create an empty profile as a side effect of logout.
2955
3029
  if (!current) return latest;
3030
+ // Signing an account out forgets the route learned from it
3031
+ // (CLI-034, signedOutRoute). A profile with no grant, or one still
3032
+ // holding a worktree credential, keeps its route.
3033
+ const signsOutAccount = Boolean(
3034
+ (current.oauth_access_token
3035
+ || current.oauth_refresh_token
3036
+ || current.oauth_client_id
3037
+ || current.oauth_issuer
3038
+ || current.oauth_resource
3039
+ || current.oauth_user_id)
3040
+ && !current.dev_access_token
3041
+ );
2956
3042
  latest.profiles[profileName] = {
2957
3043
  ...current,
3044
+ ...(signsOutAccount
3045
+ ? { api_base: undefined, release_channel: undefined, ...signedOutRoute(current) }
3046
+ : {}),
2958
3047
  oauth_access_token: undefined,
2959
3048
  oauth_refresh_token: undefined,
2960
3049
  oauth_access_expires_at: undefined,
2961
3050
  oauth_refresh_expires_at: undefined,
3051
+ oauth_refresh_expiry_from_server: undefined,
3052
+ oauth_refresh_rejected_for: undefined,
2962
3053
  oauth_client_id: undefined,
2963
3054
  oauth_issuer: undefined,
2964
3055
  oauth_api_base: undefined,
@@ -1,3 +1,4 @@
1
+ import { createHash } from 'node:crypto';
1
2
  import {
2
3
  existsSync,
3
4
  mkdirSync,
@@ -12,12 +13,19 @@ import { withConfigFileWriteLock } from './config-lock.js';
12
13
  import { getAuthRecovery, quoteShellArgument } from './auth-recovery.js';
13
14
  import { channelFromProfile, cliCommandForChannel, pinnedReleaseChannel } from './channel.js';
14
15
  import { resolveRetryEnabled } from './retry.js';
16
+ import { readAgentIdentity } from './agent-identity.js';
17
+ import {
18
+ LIVE_API_HOSTS,
19
+ currentApiOrigin,
20
+ isOnRetiredApiHost,
21
+ renamedRetiredApiOrigin,
22
+ } from './api-hosts.js';
15
23
 
16
24
  export const CONFIG_DIR = join(homedir(), '.notis');
17
25
  export const CONFIG_FILE = join(CONFIG_DIR, 'config.json');
18
26
  export const WORKSPACE_DIR = join(CONFIG_DIR, 'workspace');
19
- export const DEFAULT_API_BASE = 'https://api.notis.ai';
20
- export const NIGHTLY_API_BASE = 'https://api-nightly.notis.ai';
27
+ export const DEFAULT_API_BASE = currentApiOrigin('stable');
28
+ export const NIGHTLY_API_BASE = currentApiOrigin('nightly');
21
29
  export const DEFAULT_PROFILE = 'default';
22
30
  const PROFILE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
23
31
  const LEGACY_DESKTOP_PROFILE_KEYS = [
@@ -31,8 +39,8 @@ const LEGACY_DESKTOP_PROFILE_KEYS = [
31
39
  ];
32
40
  const WORKTREE_RUNTIME_FILENAME = join('.context', 'notis-runtime.json');
33
41
  const WORKTREE_ROUTING_FILENAME = join('.context', 'notis-routing.json');
34
- const LOCAL_API_HOSTS = new Set(['localhost', '127.0.0.1', '::1']);
35
- const LIVE_API_HOSTS = new Set(['api.notis.ai', 'api-nightly.notis.ai', 'api-beta.notis.ai']);
42
+ // WHATWG URL keeps the brackets of an IPv6 hostname: `new URL('http://[::1]:8123').hostname` is '[::1]'.
43
+ const LOCAL_API_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '[::1]']);
36
44
 
37
45
  function clone(value) {
38
46
  return JSON.parse(JSON.stringify(value));
@@ -106,6 +114,14 @@ function normalizeProfile(rawProfile = {}) {
106
114
  typeof raw.oauth_access_expires_at === 'number' ? raw.oauth_access_expires_at : undefined,
107
115
  oauth_refresh_expires_at:
108
116
  typeof raw.oauth_refresh_expires_at === 'number' ? raw.oauth_refresh_expires_at : undefined,
117
+ // True only when the token answer carried `refresh_expires_in`; otherwise
118
+ // oauth_refresh_expires_at is the CLI's own guess and proves nothing.
119
+ oauth_refresh_expiry_from_server:
120
+ raw.oauth_refresh_expiry_from_server === true ? true : undefined,
121
+ // A fingerprint of the refresh token the sign-in server refused with
122
+ // `invalid_grant` (oauthGrantIsDead).
123
+ oauth_refresh_rejected_for:
124
+ typeof raw.oauth_refresh_rejected_for === 'string' ? raw.oauth_refresh_rejected_for : undefined,
109
125
  oauth_client_id:
110
126
  typeof raw.oauth_client_id === 'string' ? raw.oauth_client_id : undefined,
111
127
  oauth_issuer: typeof raw.oauth_issuer === 'string' ? raw.oauth_issuer : undefined,
@@ -158,34 +174,52 @@ export function profileHasCredential(profile = {}) {
158
174
  return Boolean(profile.oauth_access_token || profile.dev_access_token);
159
175
  }
160
176
 
177
+ /**
178
+ * Signed in as `notis profile list` and `profile use` report it. An OAuth
179
+ * grant is used ahead of a dev token outside its lease, so it decides: one the
180
+ * sign-in server proved dead (CLI-035) routes like a signed-out profile and
181
+ * reads as one. Without a grant, a dev token is a sign-in.
182
+ */
183
+ export function profileIsSignedIn(profile = {}, grantIsDead = oauthGrantIsDead(profile)) {
184
+ if (profile.oauth_access_token) return !grantIsDead;
185
+ return Boolean(profile.dev_access_token);
186
+ }
187
+
161
188
  /**
162
189
  * Names every profile a switch can land on, newest config order preserved.
163
190
  * `notis profile use` and `--profile` both validate against this.
164
191
  */
165
192
  export function listProfiles(config) {
166
193
  const normalized = normalizeConfig(config);
167
- return Object.entries(normalized.profiles).map(([name, profile]) => ({
168
- name,
169
- active: name === normalized.current_profile,
170
- // Report the endpoint the profile was created against, including the
171
- // loopback address of a `./dev.sh` profile. getApiBase resolves a stale
172
- // loopback value to the live API for routing; showing that here would
173
- // claim a dev profile targets production, which it must never do.
174
- // OAuth metadata owns the route for an OAuth profile. An older Desktop
175
- // release may have left a conflicting api_base behind, but commands ignore
176
- // that legacy value and so must profile inspection.
177
- api_base: profile.oauth_access_token
178
- ? getOAuthApiBase(profile) || resolveDefaultLiveApiBase(profile)
179
- : profile.api_base || resolveDefaultLiveApiBase(profile),
180
- label: profile.label || null,
181
- credential_kind: profile.oauth_access_token
182
- ? 'oauth'
183
- : profile.dev_access_token
184
- ? 'dev'
185
- : null,
186
- user_id: profile.oauth_user_id || profile.dev_user_id || null,
187
- authenticated: profileHasCredential(profile),
188
- }));
194
+ return Object.entries(normalized.profiles).map(([name, profile]) => {
195
+ // The stored profile alone: a NOTIS_JWT in this shell is not part of it.
196
+ const routed = routingProfile(profile, {});
197
+ const grantIsDead = oauthGrantIsDead(profile);
198
+ const liveGrant = Boolean(profile.oauth_access_token) && !grantIsDead;
199
+ return {
200
+ name,
201
+ active: name === normalized.current_profile,
202
+ // Report the endpoint the stored profile routes to (CLI-036).
203
+ // - A live OAuth grant: its recorded OAuth server, which commands use
204
+ // over any api_base an older Desktop release left behind; with none
205
+ // recorded, where getApiBase sends it (storedApiBase).
206
+ // - Otherwise, where the next login starts (routingProfile), keeping the
207
+ // loopback address of a `./dev.sh` profile: getApiBase resolves a
208
+ // stale loopback value to the live API for routing, and showing that
209
+ // here would claim a dev profile targets production.
210
+ api_base: liveGrant
211
+ ? getOAuthApiBase(profile) || storedApiBase(profile)
212
+ : isLocalApiBase(routed.api_base) ? routed.api_base : storedApiBase(routed),
213
+ label: profile.label || null,
214
+ credential_kind: profile.oauth_access_token
215
+ ? 'oauth'
216
+ : profile.dev_access_token
217
+ ? 'dev'
218
+ : null,
219
+ user_id: profile.oauth_user_id || profile.dev_user_id || null,
220
+ authenticated: profileIsSignedIn(profile, grantIsDead),
221
+ };
222
+ });
189
223
  }
190
224
 
191
225
  function readJsonFile(path) {
@@ -519,18 +553,119 @@ function isLocalApiBase(value) {
519
553
  }
520
554
  }
521
555
 
522
- function isLiveApiBase(value) {
556
+ export function isLiveApiBase(value) {
523
557
  if (typeof value !== 'string' || !value) {
524
558
  return false;
525
559
  }
526
560
  try {
527
561
  const parsed = new URL(value);
528
- return parsed.protocol === 'https:' && LIVE_API_HOSTS.has(parsed.hostname);
562
+ return parsed.protocol === 'https:' && LIVE_API_HOSTS.includes(parsed.hostname);
529
563
  } catch {
530
564
  return false;
531
565
  }
532
566
  }
533
567
 
568
+ /**
569
+ * What a logout or a Desktop sign-out keeps of a profile's route (CLI-034).
570
+ *
571
+ * The channel pin and a live API address were learned from the account being
572
+ * signed out; the next sign-in learns them again. A loopback address stays
573
+ * without a pin, and a custom endpoint, chosen on purpose, keeps its address
574
+ * and pin, as routingProfile reads them.
575
+ */
576
+ export function signedOutRoute(profile = {}) {
577
+ const apiBase = profile.api_base;
578
+ if (!apiBase || isLiveApiBase(apiBase)) return {};
579
+ if (isLocalApiBase(apiBase)) return { api_base: apiBase };
580
+ const releaseChannel = pinnedReleaseChannel(profile);
581
+ return releaseChannel ? { api_base: apiBase, release_channel: releaseChannel } : { api_base: apiBase };
582
+ }
583
+
584
+ /**
585
+ * The fields of a profile that may decide where it routes.
586
+ *
587
+ * A profile with no credential, or whose OAuth grant the sign-in server proved
588
+ * dead (oauthGrantIsDead), has no account behind it: its channel pin
589
+ * (`release_channel`, which normalization also fills from the older `beta`
590
+ * and `channel` keys) and its live `api_base` are leftovers of an earlier
591
+ * sign-in, which logouts and Desktop sign-outs before CLI-034 kept. The account may have
592
+ * changed channel since, so a signed-out profile starts on stable, and the
593
+ * login that follows moves a nightly account to its own API
594
+ * (followAccountReleaseChannel). A custom endpoint keeps its pin: it was
595
+ * chosen on purpose, not learned from an account. A loopback address stays
596
+ * for inspection (getApiBase never routes to it without a lease) but loses
597
+ * the pin. NOTIS_JWT supplies a credential without a route, so the profile
598
+ * keeps routing it.
599
+ */
600
+ export function routingProfile(profile = {}, env = process.env) {
601
+ if (holdsAccount(profile) || env.NOTIS_JWT) return profile;
602
+ const apiBase = profile.api_base;
603
+ const local = isLocalApiBase(apiBase);
604
+ if (apiBase && !local && !isLiveApiBase(apiBase)) return profile;
605
+ const { api_base: _apiBase, oauth_api_base: _oauthApiBase, release_channel: _releaseChannel, ...rest } = profile;
606
+ return local ? { ...rest, api_base: apiBase } : rest;
607
+ }
608
+
609
+ /**
610
+ * A dev credential or a live OAuth grant, a refresh token alone included
611
+ * (Desktop reads it so too). A grant the server proved dead is a leftover too.
612
+ */
613
+ function holdsAccount(profile = {}) {
614
+ if (profile.dev_access_token) return true;
615
+ return Boolean(profile.oauth_access_token || profile.oauth_refresh_token)
616
+ && !oauthGrantIsDead(profile);
617
+ }
618
+
619
+ /**
620
+ * Whether an OAuth grant was minted while the nightly service answered as
621
+ * `api-beta.notis.ai` (CLI-038): its issuer or the resource its tokens are for
622
+ * names a retired API host. The service now checks issuer and audience
623
+ * against its current names exactly (server/lib/cli_oauth_credentials.py
624
+ * verify_cli_access_token) and keys refresh tokens by its current issuer, so
625
+ * such a grant is refused everywhere, and its refresh endpoint is the domain
626
+ * being removed. It counts as dead without asking the server: no request is
627
+ * sent with it, and the next sign-in starts on stable (CLI-035).
628
+ * A grant recorded only through a retired `oauth_api_base` but minted for the
629
+ * current names is live and routes to the current name (getOAuthApiBase).
630
+ */
631
+ export function oauthGrantOnRetiredAddress(profile = {}) {
632
+ if (!profile.oauth_access_token && !profile.oauth_refresh_token) return false;
633
+ return isOnRetiredApiHost(profile.oauth_issuer) || isOnRetiredApiHost(getOAuthResource(profile));
634
+ }
635
+
636
+ /** A fingerprint of a refresh token that holds no part of it. */
637
+ export function refreshTokenFingerprint(refreshToken) {
638
+ return createHash('sha256').update(String(refreshToken)).digest('hex').slice(0, 32);
639
+ }
640
+
641
+ /**
642
+ * Whether the stored OAuth grant can never be renewed, on evidence from the
643
+ * sign-in server only:
644
+ * - the server refused this very refresh token with `invalid_grant`
645
+ * (`oauth_refresh_rejected_for`, written by refreshOAuthCredential), or
646
+ * - the access token lapsed and the refresh expiry the server itself sent
647
+ * (`oauth_refresh_expiry_from_server`) has passed.
648
+ * An expiry the CLI filled in by default, or none at all, is unknown and never
649
+ * makes a grant dead: such a profile keeps its route until a refresh answers.
650
+ */
651
+ export function oauthGrantIsDead(profile = {}, nowSeconds = Math.floor(Date.now() / 1000)) {
652
+ // A grant minted for a retired API name can never be used again (CLI-038).
653
+ if (oauthGrantOnRetiredAddress(profile)) return true;
654
+ const refreshToken = profile.oauth_refresh_token;
655
+ if (!refreshToken) return false;
656
+ if (
657
+ typeof profile.oauth_refresh_rejected_for === 'string'
658
+ && profile.oauth_refresh_rejected_for === refreshTokenFingerprint(refreshToken)
659
+ ) {
660
+ return true;
661
+ }
662
+ if (profile.oauth_refresh_expiry_from_server !== true) return false;
663
+ const refreshExpiry = Number(profile.oauth_refresh_expires_at);
664
+ const accessExpiry = Number(profile.oauth_access_expires_at);
665
+ return Number.isFinite(refreshExpiry) && refreshExpiry <= nowSeconds
666
+ && Number.isFinite(accessExpiry) && accessExpiry <= nowSeconds;
667
+ }
668
+
534
669
  /**
535
670
  * Pick the live Notis API for this profile.
536
671
  *
@@ -553,17 +688,25 @@ export function getApiBase(config, profileName, override) {
553
688
  if (env) {
554
689
  return env;
555
690
  }
556
- const profile = getProfile(config, profileName);
557
- const profileApiBase = profile.api_base;
691
+ return storedApiBase(routingProfile(getProfile(config, profileName)));
692
+ }
558
693
 
559
- // A loopback api_base is only meaningful while the `./dev.sh` that wrote it
560
- // is still running, and resolveRuntimeProfile checks that lease before it
561
- // routes anywhere. Here — with no lease in hand — a leftover localhost value
562
- // resolves to the live API rather than to a port nothing is listening on.
694
+ /**
695
+ * The address a profile's stored api_base routes to. A loopback api_base is
696
+ * only meaningful while the `./dev.sh` that wrote it is still running, and
697
+ * resolveRuntimeProfile checks that lease before it routes anywhere. Here —
698
+ * with no lease in hand — a leftover localhost value resolves to the live API
699
+ * rather than to a port nothing is listening on.
700
+ */
701
+ function storedApiBase(profile = {}) {
702
+ const profileApiBase = profile.api_base;
563
703
  if (typeof profileApiBase === 'string' && profileApiBase && !isLocalApiBase(profileApiBase)) {
564
- return profileApiBase.replace(/\/+$/, '');
704
+ // api-beta.notis.ai is the retired name of the nightly API and is being
705
+ // removed (docs/operations/release-channels-rollout.md): a profile that
706
+ // still stores it reaches the same API under its current name (CLI-037).
707
+ // Only the bare origin: an address with a port, path or query stays as stored.
708
+ return renamedRetiredApiOrigin(profileApiBase) || profileApiBase.replace(/\/+$/, '');
565
709
  }
566
-
567
710
  return resolveDefaultLiveApiBase(profile);
568
711
  }
569
712
 
@@ -652,7 +795,11 @@ export function getOAuthResource(profile = {}) {
652
795
 
653
796
  export function getOAuthApiBase(profile = {}) {
654
797
  if (typeof profile.oauth_api_base === 'string' && profile.oauth_api_base) {
655
- return profile.oauth_api_base.replace(/\/+$/, '');
798
+ // A live grant recorded on a retired API name (its token minted for the
799
+ // current one, see oauthGrantOnRetiredAddress) is served by the same
800
+ // service under its current name (CLI-038).
801
+ return renamedRetiredApiOrigin(profile.oauth_api_base)
802
+ || profile.oauth_api_base.replace(/\/+$/, '');
656
803
  }
657
804
  const resource = getOAuthResource(profile);
658
805
  if (resource?.endsWith('/cli')) {
@@ -757,12 +904,16 @@ export function resolveRuntimeProfile(
757
904
  }
758
905
  const oauthApiBase = getOAuthApiBase(profile);
759
906
  const oauthResource = getOAuthResource(profile);
907
+ // A requested retired API name is compared under its current name, like the
908
+ // grant's own address (CLI-038).
760
909
  const normalizedRequestedApiBase = requestedApiBase
761
- ? requestedApiBase.replace(/\/+$/, '')
910
+ ? (renamedRetiredApiOrigin(requestedApiBase) || requestedApiBase.replace(/\/+$/, ''))
762
911
  : null;
763
912
  if (
764
913
  requireAuth
765
914
  && credentialKind === 'oauth'
915
+ // A retired grant is refused with its own error when it is first used.
916
+ && !oauthGrantOnRetiredAddress(profile)
766
917
  && normalizedRequestedApiBase
767
918
  && oauthApiBase
768
919
  && normalizedRequestedApiBase !== oauthApiBase
@@ -785,7 +936,9 @@ export function resolveRuntimeProfile(
785
936
  }],
786
937
  });
787
938
  }
788
- if (credentialKind === 'oauth' && oauthApiBase && !requestedApiBase) {
939
+ // A dead grant routes like a signed-out profile (routingProfile); it stays
940
+ // the credential so its refresh still reports the server's refusal.
941
+ if (credentialKind === 'oauth' && oauthApiBase && !requestedApiBase && !oauthGrantIsDead(profile)) {
789
942
  apiBase = oauthApiBase;
790
943
  }
791
944
  const agentMode = isAgentMode(globalOptions);
@@ -837,7 +990,7 @@ export function resolveRuntimeProfile(
837
990
  // An explicit route owns this invocation even when the stored
838
991
  // profile is pinned to the opposite release channel.
839
992
  ? { api_base: apiBase }
840
- : { ...profile, api_base: apiBase },
993
+ : { ...routingProfile(profile), api_base: apiBase },
841
994
  ),
842
995
  apiBase,
843
996
  requestedApiBase: normalizedRequestedApiBase,
@@ -860,6 +1013,8 @@ export function resolveRuntimeProfile(
860
1013
  timeoutMs,
861
1014
  // Automatic retries of interrupted calls that are safe to repeat.
862
1015
  retry: resolveRetryEnabled(globalOptions),
1016
+ // The agent this run declares (--agent-name / NOTIS_AGENT_NAME, ...), checked and sent by httpRequest.
1017
+ agentIdentity: readAgentIdentity(globalOptions),
863
1018
  debugEntitlementOverride,
864
1019
  worktreeRuntime: devRuntime,
865
1020
  detachedWorktreeRuntime: devRuntime ? null : worktreeRuntime,
@@ -911,8 +1066,12 @@ export function credentialIsExpired(
911
1066
  || (runtime?.credentialSource === 'env' ? 'env' : null);
912
1067
  switch (credentialKind) {
913
1068
  case 'oauth': {
1069
+ // A grant the server proved dead (oauthGrantIsDead) is spent even while
1070
+ // its access token has time left: the next use refreshes, so the issuer
1071
+ // reports the refusal, and its token never reaches the stable route.
914
1072
  const expiration = Number(profile.oauth_access_expires_at);
915
- return !Number.isFinite(expiration) || expiration <= nowSeconds;
1073
+ return !Number.isFinite(expiration) || expiration <= nowSeconds
1074
+ || oauthGrantIsDead(profile, nowSeconds);
916
1075
  }
917
1076
  case 'env':
918
1077
  // NOTIS_JWT is a complete override. Never combine it with expiry