@notis_ai/cli 0.2.29 → 0.2.31

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 (113) hide show
  1. package/README.md +26 -8
  2. package/dist/agent-hooks/notis-agent-hook.mjs +38399 -10883
  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-cli/references/native-databases.md +1 -1
  6. package/dist/base-skills/notis-query/.notis-base-skill.json +1 -1
  7. package/dist/base-skills/notis-query/references/query.md +6 -4
  8. package/dist/base-skills/notis-spaces/.notis-base-skill.json +1 -1
  9. package/dist/base-skills/notis-spaces/SKILL.md +8 -3
  10. package/dist/base-skills/notis-spaces/references/architecture.md +4 -1
  11. package/dist/base-skills/notis-spaces/references/design.md +7 -1
  12. package/dist/base-skills/notis-spaces/references/fixtures.md +27 -2
  13. package/dist/base-skills/notis-spaces/references/release.md +6 -5
  14. package/dist/base-skills/notis-spaces/references/sdk.md +172 -48
  15. package/dist/base-skills/notis-spaces/references/troubleshooting.md +3 -0
  16. package/dist/base-skills/notis-spaces/references/views.md +20 -0
  17. package/dist/sdk/src/hooks/useNativeDocuments.ts +50 -12
  18. package/dist/sdk/src/hooks/useThreadItem.ts +56 -0
  19. package/dist/sdk/src/index.ts +7 -2
  20. package/dist/sdk/src/runtime.ts +8 -1
  21. package/dist/sdk/src/space.ts +233 -1
  22. package/dist/sdk/src/tailwind.ts +53 -3
  23. package/dist/sdk/src/ui/icons.tsx +1 -0
  24. package/dist/sdk/src/words/types.ts +28 -0
  25. package/dist/skill-sync/index.js +10 -90
  26. package/dist/skill-sync-worker.mjs +232 -120
  27. package/dist/space-harness/host.js +309 -96
  28. package/dist/space-sdk/dist/chunk-3DFOGU26.js +3 -0
  29. package/dist/space-sdk/dist/index.js +4 -2
  30. package/dist/space-sdk/dist/ui.js +19 -14
  31. package/dist/space-sdk/src/hooks/useNativeDocuments.d.ts +23 -0
  32. package/dist/space-sdk/src/hooks/useThreadItem.d.ts +28 -0
  33. package/dist/space-sdk/src/index.d.ts +4 -2
  34. package/dist/space-sdk/src/runtime.d.ts +8 -1
  35. package/dist/space-sdk/src/space.ts +233 -1
  36. package/dist/space-sdk/src/tailwind-candidates.d.ts +765 -16
  37. package/dist/space-sdk/src/tailwind.ts +53 -3
  38. package/dist/space-sdk/src/ui/actions/useToast.d.ts +2 -0
  39. package/dist/space-sdk/src/ui/blocks/DataTable.d.ts +19 -4
  40. package/dist/space-sdk/src/ui/blocks/Meter.d.ts +12 -3
  41. package/dist/space-sdk/src/ui/blocks/Tabs.d.ts +7 -1
  42. package/dist/space-sdk/src/ui/blocks/index.d.ts +1 -1
  43. package/dist/space-sdk/src/ui/charts/CalendarHeatmap.d.ts +69 -0
  44. package/dist/space-sdk/src/ui/charts/Chart.d.ts +18 -3
  45. package/dist/space-sdk/src/ui/charts/chartData.d.ts +19 -0
  46. package/dist/space-sdk/src/ui/charts/heatmapData.d.ts +81 -0
  47. package/dist/space-sdk/src/ui/comments/CommentPane.d.ts +56 -10
  48. package/dist/space-sdk/src/ui/comments/PassageComments.d.ts +16 -7
  49. package/dist/space-sdk/src/ui/comments/agentRuntime.d.ts +59 -0
  50. package/dist/space-sdk/src/ui/comments/commentFiles.d.ts +5 -2
  51. package/dist/space-sdk/src/ui/comments/commentModel.d.ts +103 -8
  52. package/dist/space-sdk/src/ui/comments/commentWords.d.ts +82 -0
  53. package/dist/space-sdk/src/ui/comments/hostComments.d.ts +37 -0
  54. package/dist/space-sdk/src/ui/comments/index.d.ts +4 -0
  55. package/dist/space-sdk/src/ui/comments/paneParts.d.ts +119 -0
  56. package/dist/space-sdk/src/ui/comments/useCommentRouting.d.ts +75 -0
  57. package/dist/space-sdk/src/ui/comments/useComments.d.ts +147 -15
  58. package/dist/space-sdk/src/ui/comments/usePassageComments.d.ts +24 -8
  59. package/dist/space-sdk/src/ui/index.d.ts +6 -3
  60. package/dist/space-sdk/src/ui/layout/SidePane.d.ts +6 -1
  61. package/dist/space-sdk/src/ui/list/Row.d.ts +11 -1
  62. package/dist/space-sdk/src/ui/overlay/Tooltip.d.ts +8 -2
  63. package/dist/space-sdk/src/ui/period/dateFormat.d.ts +2 -0
  64. package/dist/space-sdk/src/ui/period/dateWords.d.ts +9 -0
  65. package/dist/space-sdk/src/ui/period/periods.d.ts +15 -2
  66. package/dist/space-sdk/src/ui/styles.d.ts +27 -5
  67. package/dist/space-sdk/src/words/types.ts +28 -0
  68. package/dist/view-renderer/dist/host.js +379 -166
  69. package/dist/view-renderer/src/dom.js +3 -2
  70. package/dist/view-renderer/src/errors.js +9 -0
  71. package/dist/view-renderer/src/host.tsx +18 -8
  72. package/dist/view-renderer/src/remote-broker.js +3 -1
  73. package/dist/view-renderer/src/renderer.js +87 -17
  74. package/dist/view-renderer/src/skeleton.js +70 -18
  75. package/package.json +5 -4
  76. package/skills/notis-cli/AGENT_INSTRUCTIONS.md +2 -1
  77. package/skills/notis-query/cli.md +3 -0
  78. package/skills/notis-spaces/cli.md +8 -8
  79. package/src/cli.js +10 -2
  80. package/src/command-specs/computer.js +21 -1
  81. package/src/command-specs/profile.js +12 -5
  82. package/src/command-specs/spaces.js +101 -31
  83. package/src/command-specs/tools.js +3 -0
  84. package/src/runtime/agent-identity.js +187 -0
  85. package/src/runtime/api-hosts.generated.js +35 -0
  86. package/src/runtime/api-hosts.js +109 -0
  87. package/src/runtime/app-platform.js +68 -24
  88. package/src/runtime/channel.js +3 -7
  89. package/src/runtime/http-agent.js +53 -0
  90. package/src/runtime/native-record-files.js +11 -0
  91. package/src/runtime/oauth.js +97 -5
  92. package/src/runtime/profiles.js +200 -41
  93. package/src/runtime/skill-sync/cloud-client.ts +0 -10
  94. package/src/runtime/skill-sync/index.ts +13 -15
  95. package/src/runtime/skill-sync/local-scanner.ts +0 -67
  96. package/src/runtime/skill-sync/types.ts +1 -0
  97. package/src/runtime/skill-sync/write-cloud-skill.ts +7 -23
  98. package/src/runtime/skill-sync-service.js +4 -5
  99. package/src/runtime/space-dependencies.js +66 -0
  100. package/src/runtime/space-fixture-broker.js +23 -8
  101. package/src/runtime/space-platform.js +49 -3
  102. package/src/runtime/space-source.js +76 -2
  103. package/src/runtime/space-test-server.js +125 -10
  104. package/src/runtime/space-verification.js +106 -42
  105. package/src/runtime/space-view-manifest.js +38 -5
  106. package/src/runtime/telemetry.js +14 -1
  107. package/src/runtime/transport.js +31 -4
  108. package/src/runtime/upsell.js +3 -6
  109. package/src/runtime/view-render.js +6 -1
  110. package/src/skill-sync-worker.js +13 -2
  111. package/src/space-harness-host.ts +6 -3
  112. package/template/tailwind.config.ts +2 -35
  113. package/dist/space-sdk/dist/chunk-BFGB6XXC.js +0 -5
@@ -5,6 +5,7 @@ import { homedir as homedir5 } from "node:os";
5
5
  import { join as join8 } from "node:path";
6
6
 
7
7
  // src/runtime/profiles.js
8
+ import { createHash } from "node:crypto";
8
9
  import {
9
10
  existsSync as existsSync3,
10
11
  mkdirSync as mkdirSync2,
@@ -155,13 +156,93 @@ function withConfigFileWriteLock(configFile, callback) {
155
156
  // src/runtime/channel.js
156
157
  import { existsSync as existsSync2 } from "node:fs";
157
158
  import { isAbsolute } from "node:path";
159
+
160
+ // src/runtime/api-hosts.generated.js
161
+ var CHANNEL_ORIGINS = {
162
+ stable: {
163
+ portal: "https://app.notis.ai",
164
+ api: "https://api.notis.ai",
165
+ mcp: "https://mcp.notis.ai",
166
+ realtime: "wss://realtime.notis.ai"
167
+ },
168
+ nightly: {
169
+ portal: "https://app-nightly.notis.ai",
170
+ api: "https://api-nightly.notis.ai",
171
+ mcp: "https://mcp-nightly.notis.ai",
172
+ realtime: "wss://realtime-nightly.notis.ai"
173
+ }
174
+ };
175
+ var CHANNEL_HOSTNAMES = {
176
+ stable: {
177
+ portal: ["app.notis.ai"],
178
+ api: ["api.notis.ai"],
179
+ mcp: ["mcp.notis.ai"],
180
+ realtime: ["realtime.notis.ai", "websocket-prod.onrender.com"]
181
+ },
182
+ nightly: {
183
+ portal: ["app-nightly.notis.ai"],
184
+ api: ["api-nightly.notis.ai"],
185
+ mcp: ["mcp-nightly.notis.ai"],
186
+ realtime: ["realtime-nightly.notis.ai", "notis-websocket.onrender.com"]
187
+ }
188
+ };
189
+
190
+ // src/runtime/api-hosts.js
191
+ var CLI_RETIRED_API_HOSTS = {
192
+ nightly: ["api-beta.notis.ai"]
193
+ };
194
+ var CHANNEL_APIS = channelApis(CHANNEL_HOSTNAMES, CHANNEL_ORIGINS);
195
+ function channelApis(channelHostnames, channelOrigins) {
196
+ return Object.fromEntries(Object.entries(channelHostnames).map(([channel, surfaces]) => {
197
+ const [current, ...legacy] = surfaces.api;
198
+ const retired = [.../* @__PURE__ */ new Set([...legacy, ...CLI_RETIRED_API_HOSTS[channel] || []])].filter((host) => host !== current);
199
+ return [channel, { current, retired, portal: channelOrigins[channel].portal }];
200
+ }));
201
+ }
202
+ var HOST_ROWS = Object.entries(CHANNEL_APIS).flatMap(([channel, row]) => [
203
+ { host: row.current, channel, current: true },
204
+ ...row.retired.map((host) => ({ host, channel, current: false }))
205
+ ]);
206
+ var LIVE_API_HOSTS = [
207
+ ...HOST_ROWS.filter((row) => row.current),
208
+ ...HOST_ROWS.filter((row) => !row.current)
209
+ ].map((row) => row.host);
210
+ var LIVE_API_ORIGINS = LIVE_API_HOSTS.map((host) => `https://${host}`);
211
+ function channelForApiHost(hostname) {
212
+ return HOST_ROWS.find((row) => row.host === hostname)?.channel || null;
213
+ }
214
+ function currentApiOrigin(channel) {
215
+ return `https://${CHANNEL_APIS[channel].current}`;
216
+ }
217
+ function isRetiredApiHost(hostname) {
218
+ return HOST_ROWS.some((row) => row.host === hostname && !row.current);
219
+ }
220
+ function parsedHttps(value) {
221
+ if (typeof value !== "string" || !value) return null;
222
+ try {
223
+ const parsed = new URL(value);
224
+ return parsed.protocol === "https:" ? parsed : null;
225
+ } catch {
226
+ return null;
227
+ }
228
+ }
229
+ function isLiveApiOrigin(value) {
230
+ const parsed = parsedHttps(value);
231
+ return Boolean(parsed) && LIVE_API_HOSTS.includes(parsed.hostname) && !parsed.port && /^\/*$/.test(parsed.pathname) && !parsed.search && !parsed.hash;
232
+ }
233
+ function renamedRetiredApiOrigin(value) {
234
+ if (!isLiveApiOrigin(value)) return null;
235
+ const { hostname } = new URL(value);
236
+ return isRetiredApiHost(hostname) ? currentApiOrigin(channelForApiHost(hostname)) : null;
237
+ }
238
+ function isOnRetiredApiHost(value) {
239
+ const parsed = parsedHttps(value);
240
+ return Boolean(parsed) && isRetiredApiHost(parsed.hostname);
241
+ }
242
+
243
+ // src/runtime/channel.js
158
244
  var RELEASE_CHANNELS = ["stable", "nightly"];
159
245
  var CHANNEL_TAGS = { stable: "latest", nightly: "nightly" };
160
- var API_HOST_CHANNELS = {
161
- "api.notis.ai": "stable",
162
- "api-beta.notis.ai": "nightly",
163
- "api-nightly.notis.ai": "nightly"
164
- };
165
246
  var CLI_PACKAGE_NAME = "@notis_ai/cli";
166
247
  function isReleaseChannel(value) {
167
248
  return RELEASE_CHANNELS.includes(value);
@@ -173,7 +254,7 @@ function normalizeReleaseChannel(value) {
173
254
  function channelFromApiBase(apiBase) {
174
255
  if (typeof apiBase !== "string" || !apiBase) return null;
175
256
  try {
176
- return API_HOST_CHANNELS[new URL(apiBase).hostname] || null;
257
+ return channelForApiHost(new URL(apiBase).hostname);
177
258
  } catch {
178
259
  return null;
179
260
  }
@@ -258,12 +339,35 @@ function resolveRetryEnabled(globalOptions = {}, env = process.env) {
258
339
  return FALSE_VALUES.has(String(raw).trim().toLowerCase());
259
340
  }
260
341
 
342
+ // src/runtime/agent-identity.js
343
+ var AGENT_IDENTITY_ENV = {
344
+ name: "NOTIS_AGENT_NAME",
345
+ id: "NOTIS_AGENT_ID",
346
+ thread: "NOTIS_AGENT_THREAD"
347
+ };
348
+ var AGENT_NAME_MIN = 3;
349
+ var AGENT_NAME_LIMIT = 60;
350
+ var BAND_NAME_EXAMPLE = "fred-and-the-machine";
351
+ var 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}`;
352
+ function pick(flag, variable) {
353
+ if (typeof flag === "string") return flag;
354
+ return typeof variable === "string" ? variable : void 0;
355
+ }
356
+ function readAgentIdentity(globalOptions = {}, env = process.env) {
357
+ const raw = {
358
+ name: pick(globalOptions.agentName, env[AGENT_IDENTITY_ENV.name]),
359
+ id: pick(globalOptions.agentId, env[AGENT_IDENTITY_ENV.id]),
360
+ thread: pick(globalOptions.agentThread, env[AGENT_IDENTITY_ENV.thread])
361
+ };
362
+ return Object.values(raw).some((value) => typeof value === "string" && value.trim()) ? raw : null;
363
+ }
364
+
261
365
  // src/runtime/profiles.js
262
366
  var CONFIG_DIR = join2(homedir2(), ".notis");
263
367
  var CONFIG_FILE = join2(CONFIG_DIR, "config.json");
264
368
  var WORKSPACE_DIR = join2(CONFIG_DIR, "workspace");
265
- var DEFAULT_API_BASE = "https://api.notis.ai";
266
- var NIGHTLY_API_BASE = "https://api-nightly.notis.ai";
369
+ var DEFAULT_API_BASE = currentApiOrigin("stable");
370
+ var NIGHTLY_API_BASE = currentApiOrigin("nightly");
267
371
  var DEFAULT_PROFILE = "default";
268
372
  var PROFILE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
269
373
  var LEGACY_DESKTOP_PROFILE_KEYS = [
@@ -277,8 +381,7 @@ var LEGACY_DESKTOP_PROFILE_KEYS = [
277
381
  ];
278
382
  var WORKTREE_RUNTIME_FILENAME = join2(".context", "notis-runtime.json");
279
383
  var WORKTREE_ROUTING_FILENAME = join2(".context", "notis-routing.json");
280
- var LOCAL_API_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1"]);
281
- var LIVE_API_HOSTS = /* @__PURE__ */ new Set(["api.notis.ai", "api-nightly.notis.ai", "api-beta.notis.ai"]);
384
+ var LOCAL_API_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
282
385
  function clone(value) {
283
386
  return JSON.parse(JSON.stringify(value));
284
387
  }
@@ -318,6 +421,12 @@ function normalizeProfile(rawProfile = {}) {
318
421
  oauth_refresh_token: typeof raw.oauth_refresh_token === "string" ? raw.oauth_refresh_token : void 0,
319
422
  oauth_access_expires_at: typeof raw.oauth_access_expires_at === "number" ? raw.oauth_access_expires_at : void 0,
320
423
  oauth_refresh_expires_at: typeof raw.oauth_refresh_expires_at === "number" ? raw.oauth_refresh_expires_at : void 0,
424
+ // True only when the token answer carried `refresh_expires_in`; otherwise
425
+ // oauth_refresh_expires_at is the CLI's own guess and proves nothing.
426
+ oauth_refresh_expiry_from_server: raw.oauth_refresh_expiry_from_server === true ? true : void 0,
427
+ // A fingerprint of the refresh token the sign-in server refused with
428
+ // `invalid_grant` (oauthGrantIsDead).
429
+ oauth_refresh_rejected_for: typeof raw.oauth_refresh_rejected_for === "string" ? raw.oauth_refresh_rejected_for : void 0,
321
430
  oauth_client_id: typeof raw.oauth_client_id === "string" ? raw.oauth_client_id : void 0,
322
431
  oauth_issuer: typeof raw.oauth_issuer === "string" ? raw.oauth_issuer : void 0,
323
432
  oauth_api_base: typeof raw.oauth_api_base === "string" ? raw.oauth_api_base : void 0,
@@ -561,11 +670,42 @@ function isLiveApiBase(value) {
561
670
  }
562
671
  try {
563
672
  const parsed = new URL(value);
564
- return parsed.protocol === "https:" && LIVE_API_HOSTS.has(parsed.hostname);
673
+ return parsed.protocol === "https:" && LIVE_API_HOSTS.includes(parsed.hostname);
565
674
  } catch {
566
675
  return false;
567
676
  }
568
677
  }
678
+ function routingProfile(profile = {}, env = process.env) {
679
+ if (holdsAccount(profile) || env.NOTIS_JWT) return profile;
680
+ const apiBase = profile.api_base;
681
+ const local = isLocalApiBase(apiBase);
682
+ if (apiBase && !local && !isLiveApiBase(apiBase)) return profile;
683
+ const { api_base: _apiBase, oauth_api_base: _oauthApiBase, release_channel: _releaseChannel, ...rest } = profile;
684
+ return local ? { ...rest, api_base: apiBase } : rest;
685
+ }
686
+ function holdsAccount(profile = {}) {
687
+ if (profile.dev_access_token) return true;
688
+ return Boolean(profile.oauth_access_token || profile.oauth_refresh_token) && !oauthGrantIsDead(profile);
689
+ }
690
+ function oauthGrantOnRetiredAddress(profile = {}) {
691
+ if (!profile.oauth_access_token && !profile.oauth_refresh_token) return false;
692
+ return isOnRetiredApiHost(profile.oauth_issuer) || isOnRetiredApiHost(getOAuthResource(profile));
693
+ }
694
+ function refreshTokenFingerprint(refreshToken) {
695
+ return createHash("sha256").update(String(refreshToken)).digest("hex").slice(0, 32);
696
+ }
697
+ function oauthGrantIsDead(profile = {}, nowSeconds = Math.floor(Date.now() / 1e3)) {
698
+ if (oauthGrantOnRetiredAddress(profile)) return true;
699
+ const refreshToken = profile.oauth_refresh_token;
700
+ if (!refreshToken) return false;
701
+ if (typeof profile.oauth_refresh_rejected_for === "string" && profile.oauth_refresh_rejected_for === refreshTokenFingerprint(refreshToken)) {
702
+ return true;
703
+ }
704
+ if (profile.oauth_refresh_expiry_from_server !== true) return false;
705
+ const refreshExpiry = Number(profile.oauth_refresh_expires_at);
706
+ const accessExpiry = Number(profile.oauth_access_expires_at);
707
+ return Number.isFinite(refreshExpiry) && refreshExpiry <= nowSeconds && Number.isFinite(accessExpiry) && accessExpiry <= nowSeconds;
708
+ }
569
709
  function resolveDefaultLiveApiBase(profile = {}) {
570
710
  const channel = pinnedReleaseChannel(profile) || (isLiveApiBase(profile.api_base) ? channelFromProfile({ api_base: profile.api_base }) : null);
571
711
  return channel === "nightly" ? NIGHTLY_API_BASE : DEFAULT_API_BASE;
@@ -578,10 +718,12 @@ function getApiBase(config, profileName, override) {
578
718
  if (env) {
579
719
  return env;
580
720
  }
581
- const profile = getProfile(config, profileName);
721
+ return storedApiBase(routingProfile(getProfile(config, profileName)));
722
+ }
723
+ function storedApiBase(profile = {}) {
582
724
  const profileApiBase = profile.api_base;
583
725
  if (typeof profileApiBase === "string" && profileApiBase && !isLocalApiBase(profileApiBase)) {
584
- return profileApiBase.replace(/\/+$/, "");
726
+ return renamedRetiredApiOrigin(profileApiBase) || profileApiBase.replace(/\/+$/, "");
585
727
  }
586
728
  return resolveDefaultLiveApiBase(profile);
587
729
  }
@@ -661,7 +803,7 @@ function getOAuthResource(profile = {}) {
661
803
  }
662
804
  function getOAuthApiBase(profile = {}) {
663
805
  if (typeof profile.oauth_api_base === "string" && profile.oauth_api_base) {
664
- return profile.oauth_api_base.replace(/\/+$/, "");
806
+ return renamedRetiredApiOrigin(profile.oauth_api_base) || profile.oauth_api_base.replace(/\/+$/, "");
665
807
  }
666
808
  const resource = getOAuthResource(profile);
667
809
  if (resource?.endsWith("/cli")) {
@@ -735,8 +877,8 @@ function resolveRuntimeProfile(globalOptions = {}, {
735
877
  }
736
878
  const oauthApiBase = getOAuthApiBase(profile);
737
879
  const oauthResource = getOAuthResource(profile);
738
- const normalizedRequestedApiBase = requestedApiBase ? requestedApiBase.replace(/\/+$/, "") : null;
739
- if (requireAuth && credentialKind === "oauth" && normalizedRequestedApiBase && oauthApiBase && normalizedRequestedApiBase !== oauthApiBase) {
880
+ const normalizedRequestedApiBase = requestedApiBase ? renamedRetiredApiOrigin(requestedApiBase) || requestedApiBase.replace(/\/+$/, "") : null;
881
+ if (requireAuth && credentialKind === "oauth" && !oauthGrantOnRetiredAddress(profile) && normalizedRequestedApiBase && oauthApiBase && normalizedRequestedApiBase !== oauthApiBase) {
740
882
  throw new CliError({
741
883
  code: "oauth_api_target_mismatch",
742
884
  message: `The OAuth credential for profile ${profileName} belongs to ${oauthApiBase}, not ${normalizedRequestedApiBase}`,
@@ -752,7 +894,7 @@ function resolveRuntimeProfile(globalOptions = {}, {
752
894
  }]
753
895
  });
754
896
  }
755
- if (credentialKind === "oauth" && oauthApiBase && !requestedApiBase) {
897
+ if (credentialKind === "oauth" && oauthApiBase && !requestedApiBase && !oauthGrantIsDead(profile)) {
756
898
  apiBase = oauthApiBase;
757
899
  }
758
900
  const agentMode = isAgentMode(globalOptions);
@@ -787,7 +929,7 @@ function resolveRuntimeProfile(globalOptions = {}, {
787
929
  // Which published build serves this profile. Carried on the runtime so
788
930
  // every recovery hint prints the command that will actually run.
789
931
  channel: devRuntime ? null : channelFromProfile(
790
- globalOptions.apiBase || process.env.NOTIS_API_BASE ? { api_base: apiBase } : { ...profile, api_base: apiBase }
932
+ globalOptions.apiBase || process.env.NOTIS_API_BASE ? { api_base: apiBase } : { ...routingProfile(profile), api_base: apiBase }
791
933
  ),
792
934
  apiBase,
793
935
  requestedApiBase: normalizedRequestedApiBase,
@@ -810,6 +952,8 @@ function resolveRuntimeProfile(globalOptions = {}, {
810
952
  timeoutMs,
811
953
  // Automatic retries of interrupted calls that are safe to repeat.
812
954
  retry: resolveRetryEnabled(globalOptions),
955
+ // The agent this run declares (--agent-name / NOTIS_AGENT_NAME, ...), checked and sent by httpRequest.
956
+ agentIdentity: readAgentIdentity(globalOptions),
813
957
  debugEntitlementOverride,
814
958
  worktreeRuntime: devRuntime,
815
959
  detachedWorktreeRuntime: devRuntime ? null : worktreeRuntime,
@@ -847,7 +991,7 @@ function credentialIsExpired(runtime, profile = {}, nowSeconds = Math.floor(Date
847
991
  switch (credentialKind) {
848
992
  case "oauth": {
849
993
  const expiration = Number(profile.oauth_access_expires_at);
850
- return !Number.isFinite(expiration) || expiration <= nowSeconds;
994
+ return !Number.isFinite(expiration) || expiration <= nowSeconds || oauthGrantIsDead(profile, nowSeconds);
851
995
  }
852
996
  case "env": {
853
997
  const expiration = getJwtExpiration(runtime?.jwt);
@@ -868,7 +1012,7 @@ function credentialIsExpired(runtime, profile = {}, nowSeconds = Math.floor(Date
868
1012
 
869
1013
  // src/runtime/oauth.js
870
1014
  import {
871
- createHash,
1015
+ createHash as createHash2,
872
1016
  randomBytes,
873
1017
  timingSafeEqual
874
1018
  } from "node:crypto";
@@ -1196,6 +1340,21 @@ function readRefreshAnswer(runtime, { response, text }) {
1196
1340
  }
1197
1341
  return payload;
1198
1342
  }
1343
+ function recordRefusedRefreshToken(runtime, refreshToken) {
1344
+ if (!refreshToken) return;
1345
+ try {
1346
+ updateConfig((latest) => {
1347
+ const current = latest.profiles?.[runtime.profileName];
1348
+ if (!current || current.oauth_refresh_token !== refreshToken) return latest;
1349
+ latest.profiles[runtime.profileName] = {
1350
+ ...current,
1351
+ oauth_refresh_rejected_for: refreshTokenFingerprint(refreshToken)
1352
+ };
1353
+ return latest;
1354
+ });
1355
+ } catch {
1356
+ }
1357
+ }
1199
1358
  async function persistRefreshedSignIn(runtime, metadata, tokenResponse) {
1200
1359
  let lastError = null;
1201
1360
  for (const delay2 of [0, ...OAUTH_REFRESH_SAVE_RETRY_DELAYS_MS]) {
@@ -1246,6 +1405,7 @@ function persistOAuthTokenResponse(runtime, metadata, tokenResponse) {
1246
1405
  const now = Math.floor(Date.now() / 1e3);
1247
1406
  const payload = decodeJwtPayload(tokenResponse.access_token);
1248
1407
  const oauthApiBase = (metadata.apiBase || runtime.apiBase || "").replace(/\/+$/, "");
1408
+ const refreshExpiryFromServer = Boolean(tokenResponse.refresh_token) && tokenResponse.refresh_expires_in !== null && tokenResponse.refresh_expires_in !== "" && Number.isFinite(Number(tokenResponse.refresh_expires_in));
1249
1409
  const config = updateConfig((latest) => {
1250
1410
  const next = ensureProfile(latest, runtime.profileName);
1251
1411
  const profile = next.profiles[runtime.profileName];
@@ -1266,7 +1426,12 @@ function persistOAuthTokenResponse(runtime, metadata, tokenResponse) {
1266
1426
  oauth_access_token: tokenResponse.access_token,
1267
1427
  oauth_refresh_token: tokenResponse.refresh_token || profile.oauth_refresh_token,
1268
1428
  oauth_access_expires_at: now + Number(tokenResponse.expires_in || 0),
1269
- oauth_refresh_expires_at: now + Number(tokenResponse.refresh_expires_in || DEFAULT_REFRESH_EXPIRES_IN),
1429
+ oauth_refresh_expires_at: now + (refreshExpiryFromServer ? Number(tokenResponse.refresh_expires_in) : DEFAULT_REFRESH_EXPIRES_IN),
1430
+ // Only an expiry the server sent for the refresh token it sent may later
1431
+ // prove the grant dead (oauthGrantIsDead); the default above is a guess.
1432
+ oauth_refresh_expiry_from_server: refreshExpiryFromServer || void 0,
1433
+ // A new grant or a renewed one is no longer the token the server refused.
1434
+ oauth_refresh_rejected_for: void 0,
1270
1435
  oauth_client_id: metadata.clientId,
1271
1436
  oauth_issuer: metadata.issuer,
1272
1437
  oauth_scopes: String(tokenResponse.scope || "").split(/\s+/).filter(Boolean),
@@ -1281,7 +1446,7 @@ var LISTENER_HANDSHAKE_TIMEOUT_MS = 1e4;
1281
1446
  var LISTENER_START_LOCK_STALE_MS = LISTENER_HANDSHAKE_TIMEOUT_MS * 2;
1282
1447
  var LISTENER_GLOBAL_LOCK_HEARTBEAT_MS = 5e3;
1283
1448
  function listenerStateFile(runtime) {
1284
- const profileKey = createHash("sha256").update(String(runtime.profileName || "default")).digest("hex").slice(0, 16);
1449
+ const profileKey = createHash2("sha256").update(String(runtime.profileName || "default")).digest("hex").slice(0, 16);
1285
1450
  return `${resolveConfigFile()}.login-listener.${profileKey}`;
1286
1451
  }
1287
1452
  function listenerStartLockDir(runtime) {
@@ -1446,7 +1611,7 @@ function updateRuntimeFromOAuthProfile(runtime, profile) {
1446
1611
  }
1447
1612
  }
1448
1613
  function assertOAuthApiTarget(runtime, profile) {
1449
- const requestedApiBase = String(runtime.requestedApiBase || "").replace(/\/+$/, "");
1614
+ const requestedApiBase = renamedRetiredApiOrigin(runtime.requestedApiBase) || String(runtime.requestedApiBase || "").replace(/\/+$/, "");
1450
1615
  const oauthApiBase = getOAuthApiBase(profile);
1451
1616
  if (requestedApiBase && oauthApiBase && requestedApiBase !== oauthApiBase) {
1452
1617
  throw oauthError(
@@ -1455,11 +1620,22 @@ function assertOAuthApiTarget(runtime, profile) {
1455
1620
  );
1456
1621
  }
1457
1622
  }
1623
+ function retiredAddressGrantError(runtime, profile) {
1624
+ const { hints } = getAuthRecovery(runtime);
1625
+ const retiredHost = [profile.oauth_issuer, getOAuthResource(profile)].filter(isOnRetiredApiHost).map((value) => new URL(value).hostname)[0];
1626
+ return oauthError(
1627
+ "oauth_grant_retired_address",
1628
+ `This sign-in was made on ${retiredHost}, a retired address of Notis that no longer accepts it. Sign in again: ${hints[0].command}`,
1629
+ hints,
1630
+ { retired_host: retiredHost }
1631
+ );
1632
+ }
1458
1633
  async function ensureFreshOAuthCredential(runtime, fetchImpl = fetch) {
1459
1634
  if (runtime.credentialKind !== "oauth") {
1460
1635
  return Boolean(runtime.jwt);
1461
1636
  }
1462
1637
  const profile = getProfile(loadConfig(), runtime.profileName);
1638
+ if (oauthGrantOnRetiredAddress(profile)) throw retiredAddressGrantError(runtime, profile);
1463
1639
  assertOAuthApiTarget(runtime, profile);
1464
1640
  if (!credentialIsExpired({ credentialKind: "oauth" }, profile)) {
1465
1641
  updateRuntimeFromOAuthProfile(runtime, profile);
@@ -1531,6 +1707,7 @@ async function refreshOAuthCredential(runtime, fetchImpl = fetch, tokenRequestOp
1531
1707
  stopTouchingLocks = keepLockFoldersFresh([profileLock, oauthLockDir()]);
1532
1708
  const config = loadConfig();
1533
1709
  const profile = getProfile(config, runtime.profileName);
1710
+ if (oauthGrantOnRetiredAddress(profile)) throw retiredAddressGrantError(runtime, profile);
1534
1711
  assertOAuthApiTarget(runtime, profile);
1535
1712
  if (profile.oauth_access_token && profile.oauth_access_token !== staleAccessToken && !credentialIsExpired({ credentialKind: "oauth" }, profile)) {
1536
1713
  updateRuntimeFromOAuthProfile(runtime, profile);
@@ -1568,7 +1745,15 @@ async function refreshOAuthCredential(runtime, fetchImpl = fetch, tokenRequestOp
1568
1745
  failure.cause
1569
1746
  );
1570
1747
  }
1571
- const rotatedResponse = readRefreshAnswer(runtime, answer);
1748
+ let rotatedResponse;
1749
+ try {
1750
+ rotatedResponse = readRefreshAnswer(runtime, answer);
1751
+ } catch (refusal) {
1752
+ if (refusal?.code === "invalid_grant") {
1753
+ recordRefusedRefreshToken(runtime, profile.oauth_refresh_token);
1754
+ }
1755
+ throw refusal;
1756
+ }
1572
1757
  const updated = await persistRefreshedSignIn(runtime, metadata, rotatedResponse);
1573
1758
  updateRuntimeFromOAuthProfile(runtime, updated);
1574
1759
  return true;
@@ -1605,14 +1790,14 @@ async function refreshOAuthCredential(runtime, fetchImpl = fetch, tokenRequestOp
1605
1790
  import { createHash as createHash4 } from "node:crypto";
1606
1791
  import { promises as fs3 } from "node:fs";
1607
1792
  import { dirname as dirname5, join as join5 } from "node:path";
1608
- import { createHash as createHash2 } from "node:crypto";
1793
+ import { createHash as createHash3 } from "node:crypto";
1609
1794
  import { createHash as createHash22 } from "crypto";
1610
1795
  import { execFile } from "child_process";
1611
1796
  import { promises as fs } from "fs";
1612
1797
  import os from "os";
1613
1798
  import path from "path";
1614
1799
  import { promisify } from "util";
1615
- import { createHash as createHash3 } from "node:crypto";
1800
+ import { createHash as createHash32 } from "node:crypto";
1616
1801
  import { promises as fs2 } from "fs";
1617
1802
  import os2 from "os";
1618
1803
  import path2 from "path";
@@ -1672,7 +1857,7 @@ function assertNativePull(response) {
1672
1857
  }
1673
1858
  }
1674
1859
  function nativeFileDigest(bytes) {
1675
- return createHash2("sha256").update(bytes).digest("hex");
1860
+ return createHash3("sha256").update(bytes).digest("hex");
1676
1861
  }
1677
1862
  function nativeFrontmatterName(markdown) {
1678
1863
  const header = markdown.match(/^---\s*\n([\s\S]*?)\n---/);
@@ -2410,44 +2595,6 @@ async function createZipFromDirectory(directoryPath) {
2410
2595
  await fs.rm(stagingRoot, { recursive: true, force: true });
2411
2596
  }
2412
2597
  }
2413
- async function extractZipToDirectory(zipPath, destinationDir) {
2414
- const extractRoot = await fs.mkdtemp(
2415
- path.join(os.tmpdir(), "notis-skill-extract-")
2416
- );
2417
- try {
2418
- if (process.platform === "win32") {
2419
- await execFileAsync("powershell.exe", [
2420
- "-NoProfile",
2421
- "-Command",
2422
- `Expand-Archive -Path '${zipPath.replace(/'/g, "''")}' -DestinationPath '${extractRoot.replace(/'/g, "''")}' -Force`
2423
- ]);
2424
- } else {
2425
- await execFileAsync("unzip", ["-qq", zipPath, "-d", extractRoot]);
2426
- }
2427
- const extractedEntries = await fs.readdir(extractRoot, {
2428
- withFileTypes: true
2429
- });
2430
- const extractedDirectory = extractedEntries.find(
2431
- (entry) => entry.isDirectory()
2432
- );
2433
- const sourceDir = extractedDirectory ? path.join(extractRoot, extractedDirectory.name) : extractRoot;
2434
- await fs.rm(destinationDir, { recursive: true, force: true });
2435
- await fs.mkdir(path.dirname(destinationDir), { recursive: true });
2436
- await fs.cp(sourceDir, destinationDir, { recursive: true });
2437
- return await listRelativeFiles(destinationDir);
2438
- } finally {
2439
- await fs.rm(extractRoot, { recursive: true, force: true });
2440
- }
2441
- }
2442
- async function listRelativeFiles(dirPath) {
2443
- try {
2444
- const files = await listFilesRecursive(dirPath);
2445
- return files.map((filePath) => toPosixRelativePath(dirPath, filePath)).sort();
2446
- } catch (error) {
2447
- if (error?.code === "ENOENT") return [];
2448
- throw error;
2449
- }
2450
- }
2451
2598
  function toPosixRelativePath(rootDir, filePath) {
2452
2599
  return path.relative(rootDir, filePath).split(path.sep).join("/");
2453
2600
  }
@@ -2589,7 +2736,7 @@ async function captureNativeSkillFiles(skill) {
2589
2736
  if (hash.digest("hex") !== skill.folderHash) throw new Error("Local Skill files changed before upload. Sync again with the current files.");
2590
2737
  return files;
2591
2738
  }
2592
- async function writeCloudSkillToDisk(skill, bundleBytes, paths = DEFAULT_SYNC_PATHS, options = {}) {
2739
+ async function writeCloudSkillToDisk(skill, paths = DEFAULT_SYNC_PATHS, options = {}) {
2593
2740
  if (isNativeSkill(skill)) {
2594
2741
  assertNativePull({
2595
2742
  skills: [{ ...skill, name: "native-" + skill.id }],
@@ -2598,7 +2745,6 @@ async function writeCloudSkillToDisk(skill, bundleBytes, paths = DEFAULT_SYNC_PA
2598
2745
  sync_enabled: true,
2599
2746
  last_synced_at: null
2600
2747
  });
2601
- if (bundleBytes?.length) throw new Error("Native Skills require their verified complete file response.");
2602
2748
  }
2603
2749
  const skillDir = path.join(
2604
2750
  paths.skillsDir,
@@ -2611,22 +2757,6 @@ async function writeCloudSkillToDisk(skill, bundleBytes, paths = DEFAULT_SYNC_PA
2611
2757
  // An unchanged legacy folder upgrading in place: shared files take the cloud version.
2612
2758
  legacyBaseline: isNativeSkill(skill) && options.legacyBaseline === true && options.expectedFolderHash !== void 0
2613
2759
  };
2614
- if (bundleBytes?.length) {
2615
- const bundlePath = path.join(
2616
- os.tmpdir(),
2617
- `notis-skill-download-${Date.now()}-${Math.random().toString(36).slice(2)}.zip`
2618
- );
2619
- try {
2620
- await fs.writeFile(bundlePath, bundleBytes);
2621
- let appliedFiles = [];
2622
- await replaceSkillDirectoryAtomically(skillDir, async (stagingDir) => {
2623
- appliedFiles = await extractZipToDirectory(bundlePath, stagingDir);
2624
- }, preserve);
2625
- return { written: true, appliedFiles };
2626
- } finally {
2627
- await fs.rm(bundlePath, { force: true });
2628
- }
2629
- }
2630
2760
  if (!skill.skill_md && (!skill.bundle_files || skill.bundle_files.length === 0)) {
2631
2761
  return false;
2632
2762
  }
@@ -2784,14 +2914,6 @@ async function pushChangedSkills(serverUrl, jwt, changedSkills, options = {}) {
2784
2914
  }
2785
2915
  return { skills: saved, ...failed.length ? { failed } : {} };
2786
2916
  }
2787
- async function downloadSkillBundle(bundleUrl) {
2788
- const response = await fetch(bundleUrl, { signal: AbortSignal.timeout(9e4) });
2789
- if (!response.ok) {
2790
- const text = await response.text();
2791
- throw new Error(`GET ${bundleUrl} \u2192 ${response.status}: ${text}`);
2792
- }
2793
- return Buffer.from(await response.arrayBuffer());
2794
- }
2795
2917
  async function updateAgentTargets(serverUrl, jwt, skillId, targets, expectedUpdatedAt, native) {
2796
2918
  if (native) {
2797
2919
  checkedNativeReference(native.reference, skillId);
@@ -2802,7 +2924,7 @@ async function updateAgentTargets(serverUrl, jwt, skillId, targets, expectedUpda
2802
2924
  revision: native.settingsRevision,
2803
2925
  patch: { agent_targets: Object.fromEntries(Object.entries(targets).sort(([a], [b]) => a.localeCompare(b))) }
2804
2926
  };
2805
- const requestId = "sync-settings-" + createHash3("sha256").update(JSON.stringify(payload)).digest("hex");
2927
+ const requestId = "sync-settings-" + createHash32("sha256").update(JSON.stringify(payload)).digest("hex");
2806
2928
  const saved = await requestJson(
2807
2929
  `${serverUrl}/portal_skills/native-settings`,
2808
2930
  jwt,
@@ -3153,25 +3275,7 @@ function getPushCandidates(localSkills, syncState, cloudCuratedSkillNames = /* @
3153
3275
  return { ...skill, ...skill.cloudId || previous?.cloudId ? { cloudId: skill.cloudId || previous.cloudId } : {} };
3154
3276
  });
3155
3277
  }
3156
- async function writeCloudSkillWithBundleFallback(skill, dependencies) {
3157
- if (skill.skill_source_url) {
3158
- try {
3159
- const bundleBytes = await dependencies.downloadSkillBundle(skill.skill_source_url);
3160
- const wroteBundleToDisk = await dependencies.writeCloudSkillToDisk(skill, bundleBytes);
3161
- if (wroteBundleToDisk) {
3162
- return wroteBundleToDisk;
3163
- }
3164
- dependencies.onWarning?.(
3165
- `Bundle sync for "${skill.name}" produced no local changes, falling back to SKILL.md payload.`,
3166
- new Error("Bundle write returned false")
3167
- );
3168
- } catch (error) {
3169
- dependencies.onWarning?.(
3170
- `Failed to apply bundle sync for "${skill.name}", falling back to SKILL.md payload.`,
3171
- error
3172
- );
3173
- }
3174
- }
3278
+ async function writeCloudSkill(skill, dependencies) {
3175
3279
  if (skill.bundle_hydration_failed) {
3176
3280
  dependencies.onWarning?.(
3177
3281
  `Skipping markdown fallback for synced skill "${skill.name}" because its stored bundle could not be hydrated by the server.`,
@@ -3208,7 +3312,6 @@ var DEFAULT_RUN_SKILL_SYNC_DEPS = {
3208
3312
  fetchSyncSettings,
3209
3313
  pullSkills,
3210
3314
  pushChangedSkills,
3211
- downloadSkillBundle,
3212
3315
  gatherTopLevelLocalSkills,
3213
3316
  readLegacySyncState,
3214
3317
  readSyncState,
@@ -3297,7 +3400,10 @@ function cloudContentHash(skill) {
3297
3400
  return createHash4("sha256").update(JSON.stringify({
3298
3401
  md: skill.skill_md,
3299
3402
  hash: skill.skill_folder_hash,
3300
- source: skill.skill_source_url,
3403
+ // A recorded origin is provenance, never content (SKL-059): a URL hashes as null so
3404
+ // it cannot force a rewrite, and an absent or null one hashes as before so stored
3405
+ // hashes stay valid.
3406
+ source: skill.skill_source_url ? null : skill.skill_source_url,
3301
3407
  files: skill.bundle_files?.slice().sort((a, b) => a.path.localeCompare(b.path)),
3302
3408
  hydrationFailed: skill.bundle_hydration_failed === true
3303
3409
  })).digest("hex");
@@ -3370,7 +3476,7 @@ function buildSyncState(pullResponse, localSkills, lastSyncedAt, verifiedAgentLi
3370
3476
  agentTargets: normalizeAgentTargets(skill.agent_targets),
3371
3477
  verifiedAgentLinks: skill.status === "active" ? verifiedAgentLinks[skill.name] ?? {} : {},
3372
3478
  cloudUpdatedAt: skill.updated_at,
3373
- ...!failedContentNames.has(skill.name) && !skill.skill_source_url ? { cloudContentHash: cloudContentHash(skill) } : {},
3479
+ ...!failedContentNames.has(skill.name) ? { cloudContentHash: cloudContentHash(skill) } : {},
3374
3480
  ...appliedCloudFolderHash !== void 0 ? { appliedCloudFolderHash } : {},
3375
3481
  ...appliedFileList !== void 0 ? { appliedFiles: appliedFileList } : {},
3376
3482
  syncedAt: lastSyncedAt || (/* @__PURE__ */ new Date()).toISOString()
@@ -3471,9 +3577,8 @@ async function writePulledSkillsToScopedMirror(pullResponse, localSkills, previo
3471
3577
  }
3472
3578
  continue;
3473
3579
  }
3474
- const outcome = await writeCloudSkillWithBundleFallback(cloudSkill, {
3475
- downloadSkillBundle: deps.downloadSkillBundle,
3476
- writeCloudSkillToDisk: (skill, bundleBytes) => deps.writeCloudSkillToDisk(skill, bundleBytes, syncPaths, {
3580
+ const outcome = await writeCloudSkill(cloudSkill, {
3581
+ writeCloudSkillToDisk: (skill) => deps.writeCloudSkillToDisk(skill, syncPaths, {
3477
3582
  // What the last write put there. Everything else in the folder was
3478
3583
  // produced locally and survives this one.
3479
3584
  previouslyApplied: previouslyAppliedFiles(skill, local, previousState),
@@ -3489,7 +3594,7 @@ async function writePulledSkillsToScopedMirror(pullResponse, localSkills, previo
3489
3594
  appliedFilesByName[cloudSkill.name] = outcome.appliedFiles;
3490
3595
  }
3491
3596
  } else {
3492
- failures.push({ name: cloudSkill.name, error: "Skill content could not be downloaded or written; sync will retry" });
3597
+ failures.push({ name: cloudSkill.name, error: "Skill content could not be written; sync will retry" });
3493
3598
  }
3494
3599
  }
3495
3600
  return downloaded;
@@ -3927,7 +4032,12 @@ async function withSkillSyncLock(callback, {
3927
4032
  }
3928
4033
 
3929
4034
  // src/skill-sync-worker.js
3930
- var REJECTED_SIGN_IN_CODES = /* @__PURE__ */ new Set(["invalid_grant", "invalid_client", "unauthorized_client"]);
4035
+ var REJECTED_SIGN_IN_CODES = /* @__PURE__ */ new Set([
4036
+ "invalid_grant",
4037
+ "invalid_client",
4038
+ "unauthorized_client",
4039
+ "oauth_grant_retired_address"
4040
+ ]);
3931
4041
  function currentCliProfile() {
3932
4042
  try {
3933
4043
  return getCurrentProfileName(loadConfig());
@@ -3955,7 +4065,9 @@ async function runAutomaticSkillSync({ profile, apiBase, userId }, {
3955
4065
  currentProfile = currentCliProfile
3956
4066
  } = {}) {
3957
4067
  const runtime = resolveRuntime({ profile }, { requireAuth: true });
3958
- if (runtime.credentialKind !== "oauth" || runtime.apiBase !== apiBase || runtime.oauthUserId !== userId) throw new Error("Automatic skill sync account changed; run notis skills sync to rebind");
4068
+ const current = (value) => renamedRetiredApiOrigin(value) || value;
4069
+ const boundApiBase = current(apiBase);
4070
+ if (runtime.credentialKind !== "oauth" || current(runtime.oauthApiBase || runtime.apiBase) !== boundApiBase || runtime.oauthUserId !== userId) throw new Error("Automatic skill sync account changed; run notis skills sync to rebind");
3959
4071
  await refresh(runtime);
3960
4072
  const saved = await settings(runtime.apiBase, runtime.jwt);
3961
4073
  if (saved.user_id !== userId) throw new Error("Automatic skill sync identity mismatch");