@notis_ai/cli 0.2.28 → 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 (72) hide show
  1. package/README.md +25 -8
  2. package/dist/agent-hooks/notis-agent-hook.mjs +1476 -712
  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 +86 -14
  8. package/dist/sdk/src/components/NotisCommentBoundary.tsx +29 -96
  9. package/dist/sdk/src/components/NotisSelectionBoundary.tsx +3 -8
  10. package/dist/sdk/src/components/SelectionActionBar.tsx +144 -23
  11. package/dist/sdk/src/components/selectionId.ts +6 -0
  12. package/dist/sdk/src/hooks/useThreadItem.ts +56 -0
  13. package/dist/sdk/src/index.ts +6 -1
  14. package/dist/sdk/src/runtime.ts +13 -1
  15. package/dist/sdk/src/space.ts +230 -0
  16. package/dist/skill-sync-worker.mjs +185 -30
  17. package/dist/space-harness/host.js +260 -114
  18. package/dist/space-sdk/dist/{chunk-BFGB6XXC.js → chunk-6GJ2BS7B.js} +1 -3
  19. package/dist/space-sdk/dist/index.js +4 -2
  20. package/dist/space-sdk/dist/ui.js +19 -14
  21. package/dist/space-sdk/src/components/NotisCommentBoundary.d.ts +0 -10
  22. package/dist/space-sdk/src/hooks/useThreadItem.d.ts +28 -0
  23. package/dist/space-sdk/src/index.d.ts +3 -1
  24. package/dist/space-sdk/src/runtime.d.ts +13 -1
  25. package/dist/space-sdk/src/space.ts +230 -0
  26. package/dist/space-sdk/src/tailwind-candidates.d.ts +505 -22
  27. package/dist/space-sdk/src/ui/actions/useToast.d.ts +2 -0
  28. package/dist/space-sdk/src/ui/comments/CommentPane.d.ts +56 -10
  29. package/dist/space-sdk/src/ui/comments/PassageComments.d.ts +16 -7
  30. package/dist/space-sdk/src/ui/comments/agentRuntime.d.ts +59 -0
  31. package/dist/space-sdk/src/ui/comments/commentFiles.d.ts +5 -2
  32. package/dist/space-sdk/src/ui/comments/commentModel.d.ts +103 -8
  33. package/dist/space-sdk/src/ui/comments/commentWords.d.ts +82 -0
  34. package/dist/space-sdk/src/ui/comments/hostComments.d.ts +37 -0
  35. package/dist/space-sdk/src/ui/comments/index.d.ts +4 -0
  36. package/dist/space-sdk/src/ui/comments/paneParts.d.ts +119 -0
  37. package/dist/space-sdk/src/ui/comments/useCommentRouting.d.ts +75 -0
  38. package/dist/space-sdk/src/ui/comments/useComments.d.ts +165 -15
  39. package/dist/space-sdk/src/ui/comments/usePassageComments.d.ts +24 -8
  40. package/dist/space-sdk/src/ui/index.d.ts +2 -1
  41. package/dist/space-sdk/src/ui/layout/SidePane.d.ts +6 -1
  42. package/dist/space-sdk/src/ui/overlay/Tooltip.d.ts +8 -2
  43. package/dist/space-sdk/src/ui/styles.d.ts +27 -5
  44. package/dist/view-renderer/dist/host.js +330 -184
  45. package/dist/view-renderer/src/host.tsx +6 -3
  46. package/dist/view-renderer/src/renderer.js +62 -3
  47. package/package.json +3 -3
  48. package/skills/notis-cli/AGENT_INSTRUCTIONS.md +2 -1
  49. package/skills/notis-spaces/cli.md +8 -8
  50. package/src/cli.js +10 -2
  51. package/src/command-specs/computer.js +21 -1
  52. package/src/command-specs/profile.js +12 -5
  53. package/src/command-specs/spaces.js +57 -23
  54. package/src/command-specs/tools.js +1 -1
  55. package/src/runtime/agent-identity.js +187 -0
  56. package/src/runtime/api-hosts.js +92 -0
  57. package/src/runtime/app-platform.js +74 -11
  58. package/src/runtime/channel.js +3 -7
  59. package/src/runtime/oauth.js +95 -4
  60. package/src/runtime/profiles.js +200 -41
  61. package/src/runtime/skill-sync-service.js +4 -5
  62. package/src/runtime/space-fixture-broker.js +23 -2
  63. package/src/runtime/space-platform.js +2 -0
  64. package/src/runtime/space-source.js +66 -1
  65. package/src/runtime/space-test-server.js +20 -4
  66. package/src/runtime/space-verification.js +66 -10
  67. package/src/runtime/telemetry.js +14 -1
  68. package/src/runtime/transport.js +12 -0
  69. package/src/runtime/upsell.js +3 -6
  70. package/src/runtime/view-render.js +3 -1
  71. package/src/skill-sync-worker.js +13 -2
  72. package/src/space-harness-host.ts +6 -3
@@ -0,0 +1,187 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
3
+ import { dirname, join } from 'node:path';
4
+
5
+ import { resolveCliConfigFile, withConfigFileWriteLock } from './config-lock.js';
6
+ import { usageError } from './errors.js';
7
+
8
+ /**
9
+ * An agent's declared identity, sent on every backend call.
10
+ *
11
+ * Any agent driving the CLI (Claude Code or Codex on a person's computer, a script, a Cloud Computer session) says
12
+ * who it is with `--agent-name`, `--agent-id` and `--agent-thread`, or the NOTIS_AGENT_NAME, NOTIS_AGENT_ID and
13
+ * NOTIS_AGENT_THREAD variables (a flag wins over its variable). The backend then treats what the call writes as that
14
+ * agent's, not the person's: a comment's Author is the declared name, it never counts as the person's comment and it
15
+ * never wakes the agent that wrote it. The declaration is self-asserted: it names the writer, it never grants access.
16
+ *
17
+ * The name is a band name: a fresh lowercase imaginary rock-band name, lowercase letters and digits in at least two
18
+ * words joined by hyphens, 3 to 60 characters, such as fred-and-the-machine. The name is only a name: the id decides
19
+ * which comments are the agent's own. Without an explicit id the CLI generates a random one the first time a name is
20
+ * used on this computer and keeps it for that name in `agents.json`, next to the CLI config file (so
21
+ * NOTIS_CLI_CONFIG_FILE moves it too), written under the config lock. An explicit id always wins.
22
+ *
23
+ * The values travel percent-encoded (encodeURIComponent) in the X-Notis-Agent-* headers. The backend applies the same
24
+ * rules (server/lib/delegated_agents/declared_agent.py) and refuses a comment written through the CLI without a name.
25
+ */
26
+ export const AGENT_NAME_HEADER = 'X-Notis-Agent-Name';
27
+ export const AGENT_ID_HEADER = 'X-Notis-Agent-Id';
28
+ export const AGENT_THREAD_HEADER = 'X-Notis-Agent-Thread';
29
+ export const AGENT_IDENTITY_ENV = {
30
+ name: 'NOTIS_AGENT_NAME',
31
+ id: 'NOTIS_AGENT_ID',
32
+ thread: 'NOTIS_AGENT_THREAD',
33
+ };
34
+ export const AGENT_NAME_MIN = 3;
35
+ export const AGENT_NAME_LIMIT = 60;
36
+ export const BAND_NAME_EXAMPLE = 'fred-and-the-machine';
37
+ export const BAND_NAME_RULE = `a fresh lowercase imaginary rock-band name: lowercase letters and digits in at least two words joined by hyphens, ${AGENT_NAME_MIN} to ${AGENT_NAME_LIMIT} characters, such as ${BAND_NAME_EXAMPLE}`;
38
+ export const AGENT_IDS_VERSION = 1;
39
+ export const AGENT_ID_LIMIT = 128;
40
+ export const AGENT_THREAD_LIMIT = 512;
41
+
42
+ const BAND_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)+$/;
43
+ const ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:@/+-]*$/;
44
+ // Printable ASCII without spaces: an id or a link.
45
+ const THREAD_PATTERN = /^[\x21-\x7e]+$/;
46
+
47
+ function pick(flag, variable) {
48
+ if (typeof flag === 'string') return flag;
49
+ return typeof variable === 'string' ? variable : undefined;
50
+ }
51
+
52
+ /** The raw declaration from the global flags and the environment, or null when nothing is declared. */
53
+ export function readAgentIdentity(globalOptions = {}, env = process.env) {
54
+ const raw = {
55
+ name: pick(globalOptions.agentName, env[AGENT_IDENTITY_ENV.name]),
56
+ id: pick(globalOptions.agentId, env[AGENT_IDENTITY_ENV.id]),
57
+ thread: pick(globalOptions.agentThread, env[AGENT_IDENTITY_ENV.thread]),
58
+ };
59
+ return Object.values(raw).some((value) => typeof value === 'string' && value.trim()) ? raw : null;
60
+ }
61
+
62
+ /** The validated declaration ({name, id?, thread?}), or null; a usage error names what to fix. */
63
+ export function validateAgentIdentity(raw) {
64
+ if (!raw) return null;
65
+ const name = String(raw.name ?? '').trim();
66
+ const id = String(raw.id ?? '').trim();
67
+ const thread = String(raw.thread ?? '').trim();
68
+ if (!name) {
69
+ throw usageError(
70
+ `Name the agent: set ${AGENT_IDENTITY_ENV.name} (or --agent-name) whenever ${AGENT_IDENTITY_ENV.id} or ${AGENT_IDENTITY_ENV.thread} is set.`,
71
+ );
72
+ }
73
+ if (!isBandName(name)) {
74
+ throw usageError(
75
+ `${AGENT_IDENTITY_ENV.name} (or --agent-name) must be ${BAND_NAME_RULE}. Pick one for this agent and keep it.`,
76
+ );
77
+ }
78
+ if (id && (id.length > AGENT_ID_LIMIT || !ID_PATTERN.test(id))) {
79
+ throw usageError(
80
+ `${AGENT_IDENTITY_ENV.id} must be at most ${AGENT_ID_LIMIT} characters: letters, digits and . _ : @ / + - , starting with a letter or digit.`,
81
+ );
82
+ }
83
+ if (thread && (thread.length > AGENT_THREAD_LIMIT || !THREAD_PATTERN.test(thread))) {
84
+ throw usageError(
85
+ `${AGENT_IDENTITY_ENV.thread} must be a thread id or link of at most ${AGENT_THREAD_LIMIT} characters, without spaces.`,
86
+ );
87
+ }
88
+ return { name, ...(id ? { id } : {}), ...(thread ? { thread } : {}) };
89
+ }
90
+
91
+ const RAW_HEADER_LIMIT = AGENT_THREAD_LIMIT;
92
+
93
+ function rawIdentityHeaders(raw) {
94
+ const headers = {};
95
+ const put = (header, value) => {
96
+ // Capped by whole characters (never splitting one, which encodeURIComponent refuses), one past the longest
97
+ // valid value, so a value too long stays too long for the backend to refuse.
98
+ const text = Array.from(String(value ?? '').trim()).slice(0, RAW_HEADER_LIMIT + 1).join('');
99
+ if (text) headers[header] = encodeURIComponent(text);
100
+ };
101
+ put(AGENT_NAME_HEADER, raw?.name);
102
+ put(AGENT_ID_HEADER, raw?.id);
103
+ put(AGENT_THREAD_HEADER, raw?.thread);
104
+ return headers;
105
+ }
106
+
107
+ /** Whether `name` follows the band-name rule (BAND_NAME_RULE). */
108
+ export function isBandName(name) {
109
+ return typeof name === 'string' && name.length >= AGENT_NAME_MIN && name.length <= AGENT_NAME_LIMIT
110
+ && BAND_NAME.test(name);
111
+ }
112
+
113
+ export function agentIdsFile(configFile = resolveCliConfigFile()) {
114
+ return join(dirname(configFile), 'agents.json');
115
+ }
116
+
117
+ function readAgentIds(file) {
118
+ try {
119
+ const raw = JSON.parse(readFileSync(file, 'utf8'));
120
+ if (raw?.version === AGENT_IDS_VERSION && raw.agents && typeof raw.agents === 'object' && !Array.isArray(raw.agents)) {
121
+ return raw.agents;
122
+ }
123
+ } catch {
124
+ // A missing or broken file holds no ids yet.
125
+ }
126
+ return {};
127
+ }
128
+
129
+ function storedId(agents, name) {
130
+ const id = Object.hasOwn(agents, name) ? agents[name] : null;
131
+ return typeof id === 'string' && id.length <= AGENT_ID_LIMIT && ID_PATTERN.test(id) ? id : null;
132
+ }
133
+
134
+ /**
135
+ * The id this computer keeps for an agent name, generated (a random UUID) the first time the name is used. Read again
136
+ * under the config lock so two first calls agree on one id.
137
+ */
138
+ export function agentIdForName(name, options = {}) {
139
+ const configFile = options.configFile ?? resolveCliConfigFile();
140
+ const file = agentIdsFile(configFile);
141
+ const known = storedId(readAgentIds(file), name);
142
+ if (known) return known;
143
+ return withConfigFileWriteLock(configFile, () => {
144
+ const agents = readAgentIds(file);
145
+ const existing = storedId(agents, name);
146
+ if (existing) return existing;
147
+ const id = randomUUID();
148
+ mkdirSync(dirname(file), { recursive: true });
149
+ const temporaryFile = `${file}.${process.pid}.${Date.now()}.tmp`;
150
+ writeFileSync(temporaryFile, `${JSON.stringify({ version: AGENT_IDS_VERSION, agents: { ...agents, [name]: id } }, null, 2)}\n`,
151
+ { mode: 0o600 });
152
+ renameSync(temporaryFile, file);
153
+ return id;
154
+ });
155
+ }
156
+
157
+ /**
158
+ * The headers that declare the runtime's agent (empty when it declares none). A name without an explicit id carries
159
+ * the id this computer keeps for it; when that id cannot be kept (a read-only disk) the name goes alone and the
160
+ * backend asks for NOTIS_AGENT_ID before a comment write.
161
+ */
162
+ export function agentIdentityHeaders(runtime, options = {}) {
163
+ const raw = runtime?.agentIdentity ?? null;
164
+ let identity;
165
+ try {
166
+ identity = validateAgentIdentity(raw);
167
+ } catch {
168
+ // A declaration that breaks the rules is sent as written, with no kept id: where declarations count (unified
169
+ // comments on) the routes that read them (tools, Space data and actions, document restores and removes) refuse
170
+ // the call with invalid_agent_identity, reads included; elsewhere it is ignored, so a stray NOTIS_AGENT_NAME never
171
+ // breaks a person without unified comments.
172
+ return rawIdentityHeaders(raw);
173
+ }
174
+ if (!identity) return {};
175
+ let id = identity.id;
176
+ if (!id) {
177
+ try {
178
+ id = agentIdForName(identity.name, options);
179
+ } catch {
180
+ id = undefined;
181
+ }
182
+ }
183
+ const headers = { [AGENT_NAME_HEADER]: encodeURIComponent(identity.name) };
184
+ if (id) headers[AGENT_ID_HEADER] = encodeURIComponent(id);
185
+ if (identity.thread) headers[AGENT_THREAD_HEADER] = encodeURIComponent(identity.thread);
186
+ return headers;
187
+ }
@@ -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
+ }
@@ -1973,9 +1973,18 @@ export function freezeSourceWorkspace(projectDir, sourceFiles) {
1973
1973
  return withAppReleaseWorkspace(projectDir, workspace => freezePinnedArtifactSnapshot(workspace, {}, sourceFiles), { create: true });
1974
1974
  }
1975
1975
 
1976
+ /** Whether a Space key is safe to put in a file name under .notis. */
1977
+ function isSpaceKey(key) {
1978
+ return typeof key === 'string' && /^[a-z][a-z0-9_-]{0,99}$/.test(key);
1979
+ }
1980
+
1981
+ function assertSpaceKey(key, message) {
1982
+ if (!isSpaceKey(key)) throw usageError(message);
1983
+ return key;
1984
+ }
1985
+
1976
1986
  function selectedBuildName(key) {
1977
- if (typeof key !== 'string' || !/^[a-z][a-z0-9_-]{0,99}$/.test(key)) throw usageError('Choose a valid selected build key.');
1978
- return `space-build-${key}.json`;
1987
+ return `space-build-${assertSpaceKey(key, 'Choose a valid selected build key.')}.json`;
1979
1988
  }
1980
1989
 
1981
1990
  /** Immutable bytes, not another authoring project or installed dependency tree. */
@@ -1988,6 +1997,8 @@ export function saveSelectedBuild(projectDir, key, release) {
1988
1997
  writeFileSync(temporary, JSON.stringify(snapshot), { flag: 'wx', mode: 0o600 });
1989
1998
  renameSync(temporary, name);
1990
1999
  } finally { rmSync(temporary, { force: true }); }
2000
+ // The verify images showed the build this one replaces.
2001
+ removeSpaceImages(key);
1991
2002
  return join(projectDir, NOTIS_DIR, name);
1992
2003
  }, { create: true });
1993
2004
  }
@@ -2022,16 +2033,68 @@ export function saveSpaceVerification(projectDir, diagnostic) {
2022
2033
  });
2023
2034
  }
2024
2035
 
2025
- /** The loading-state screenshots of the last verify, `pending-<width>-<locale>.png` beside the diagnostic. */
2026
- export function saveSpacePendingScreenshots(projectDir, screenshots) {
2036
+ /** Replace one verify image in the pinned .notis directory (the working directory) without following a planted link. */
2037
+ function replaceVerifyImage(name, png) {
2038
+ rmSync(name, { force: true });
2039
+ if (png) writeFileSync(name, png, { flag: 'wx', mode: 0o600 });
2040
+ }
2041
+
2042
+ const VERIFY_WIDTHS = [390, 1440], VERIFY_LOCALES = ['en', 'fr'];
2043
+ /** Each Space's verify images carry its key, so two Spaces verified from one folder never share a file. */
2044
+ function viewImageName(key, width) {
2045
+ if (!VERIFY_WIDTHS.includes(width)) throw usageError('Unsafe screenshot name.');
2046
+ return `view-${assertSpaceKey(key, 'Unsafe screenshot name.')}-${width}.png`;
2047
+ }
2048
+ function pendingImageName(key, width, locale) {
2049
+ if (!VERIFY_WIDTHS.includes(width) || !VERIFY_LOCALES.includes(locale)) throw usageError('Unsafe pending screenshot name.');
2050
+ return `pending-${assertSpaceKey(key, 'Unsafe pending screenshot name.')}-${width}-${locale}.png`;
2051
+ }
2052
+
2053
+ /**
2054
+ * Remove this Space's verify images before a new verify, so one that stops at any point (its build refused as stale
2055
+ * included), or a release without a loading skeleton, leaves no image of an older build. Images named before they
2056
+ * carried a key say no Space, so they go too.
2057
+ */
2058
+ export function clearSpaceScreenshots(projectDir, key) {
2059
+ // A key no build accepts has no images, and a folder never built has no .notis; the release step says why.
2060
+ if (!isSpaceKey(key) || !lstatSync(join(projectDir, NOTIS_DIR), { throwIfNoEntry: false })) return;
2061
+ withAppReleaseWorkspace(projectDir, () => removeSpaceImages(key));
2062
+ }
2063
+
2064
+ /** Remove one Space's verify images, and the unnamed ones, from the pinned .notis directory (the working directory). */
2065
+ function removeSpaceImages(key) {
2066
+ for (const width of VERIFY_WIDTHS) {
2067
+ replaceVerifyImage(viewImageName(key, width));
2068
+ replaceVerifyImage(`view-${width}.png`);
2069
+ for (const locale of VERIFY_LOCALES) {
2070
+ replaceVerifyImage(pendingImageName(key, width, locale));
2071
+ replaceVerifyImage(`pending-${width}-${locale}.png`);
2072
+ }
2073
+ }
2074
+ }
2075
+
2076
+ /** The loading-state screenshots of the last verify, `pending-<key>-<width>-<locale>.png` beside the diagnostic. */
2077
+ export function saveSpacePendingScreenshots(projectDir, key, screenshots) {
2027
2078
  if (!screenshots?.length) return [];
2028
- return withAppReleaseWorkspace(projectDir, (workspace) => screenshots.map(({ width, locale, png }) => {
2029
- if (![390, 1440].includes(width) || !['en', 'fr'].includes(locale)) throw usageError('Unsafe pending screenshot name.');
2030
- const name = `pending-${width}-${locale}.png`;
2031
- // Replace the previous verify's image without following a planted link.
2032
- rmSync(name, { force: true });
2033
- writeFileSync(name, png, { flag: 'wx', mode: 0o600 });
2034
- return join(workspace.projectDir, '.notis', name);
2079
+ // Every name is checked before any file is written.
2080
+ const names = screenshots.map(({ width, locale }) => pendingImageName(key, width, locale));
2081
+ return withAppReleaseWorkspace(projectDir, (workspace) => screenshots.map(({ png }, index) => {
2082
+ replaceVerifyImage(names[index], png);
2083
+ return join(workspace.projectDir, NOTIS_DIR, names[index]);
2084
+ }));
2085
+ }
2086
+
2087
+ /**
2088
+ * The screenshots of the last verify, `view-<key>-<width>.png` beside the diagnostic, taken once the view had loaded
2089
+ * its data (or of what it showed when it had not).
2090
+ */
2091
+ export function saveSpaceScreenshots(projectDir, key, screenshots) {
2092
+ // One image per width, every name checked before any file is written.
2093
+ const kept = new Map((screenshots || []).map(value => [value.width, value]));
2094
+ const names = new Map([...kept.keys()].map(width => [width, viewImageName(key, width)]));
2095
+ return withAppReleaseWorkspace(projectDir, (workspace) => [...kept].map(([width, { png }]) => {
2096
+ replaceVerifyImage(names.get(width), png);
2097
+ return { width, path: join(workspace.projectDir, NOTIS_DIR, names.get(width)) };
2035
2098
  }));
2036
2099
  }
2037
2100
 
@@ -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,