@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
@@ -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
@@ -149,16 +149,6 @@ export async function pushChangedSkills(
149
149
  return { skills: saved, ...(failed.length ? { failed } : {}) };
150
150
  }
151
151
 
152
- export async function downloadSkillBundle(bundleUrl: string): Promise<Buffer> {
153
- const response = await fetch(bundleUrl, { signal: AbortSignal.timeout(90_000) });
154
- if (!response.ok) {
155
- const text = await response.text();
156
- throw new Error(`GET ${bundleUrl} → ${response.status}: ${text}`);
157
- }
158
-
159
- return Buffer.from(await response.arrayBuffer());
160
- }
161
-
162
152
  export async function updateAgentTargets(
163
153
  serverUrl: string,
164
154
  jwt: string,
@@ -15,7 +15,6 @@ import { normalizeAgentTargets } from "./types";
15
15
  import { assertNativePull, checkedNativeReference, isNativeSkill, nativeState } from './native-identity';
16
16
  import { bindNativeFolders, hasNativeFolderHistory, nativeLinkRows, nativeLocalReady, pendingLegacyUpgrade, previousNativeState, retainMissingNativeState } from './native-plan';
17
17
  import {
18
- downloadSkillBundle,
19
18
  fetchSyncSettings,
20
19
  pullSkills,
21
20
  pushChangedSkills,
@@ -39,7 +38,7 @@ import {
39
38
  type DeletedAgentSymlink,
40
39
  } from "./symlink-manager";
41
40
  import { getPushCandidates, selectCloudSkillsToApply } from "./sync-plan";
42
- import { writeCloudSkillWithBundleFallback } from "./write-cloud-skill";
41
+ import { writeCloudSkill } from "./write-cloud-skill";
43
42
  export { fetchSyncSettings, pushChangedSkills } from './cloud-client';
44
43
 
45
44
  export interface RunSkillSyncResult {
@@ -115,7 +114,6 @@ interface RunSkillSyncDependencies {
115
114
  fetchSyncSettings: typeof fetchSyncSettings;
116
115
  pullSkills: typeof pullSkills;
117
116
  pushChangedSkills: typeof pushChangedSkills;
118
- downloadSkillBundle: typeof downloadSkillBundle;
119
117
  gatherTopLevelLocalSkills: typeof gatherTopLevelLocalSkills;
120
118
  readLegacySyncState: typeof readLegacySyncState;
121
119
  readSyncState: typeof readSyncState;
@@ -134,7 +132,6 @@ const DEFAULT_RUN_SKILL_SYNC_DEPS: RunSkillSyncDependencies = {
134
132
  fetchSyncSettings,
135
133
  pullSkills,
136
134
  pushChangedSkills,
137
- downloadSkillBundle,
138
135
  gatherTopLevelLocalSkills,
139
136
  readLegacySyncState,
140
137
  readSyncState,
@@ -239,7 +236,10 @@ function cloudContentHash(skill: SyncPullResponse['skills'][number]): string {
239
236
  return createHash('sha256').update(JSON.stringify({
240
237
  md: skill.skill_md,
241
238
  hash: skill.skill_folder_hash,
242
- source: skill.skill_source_url,
239
+ // A recorded origin is provenance, never content (SKL-059): a URL hashes as null so
240
+ // it cannot force a rewrite, and an absent or null one hashes as before so stored
241
+ // hashes stay valid.
242
+ source: skill.skill_source_url ? null : skill.skill_source_url,
243
243
  files: skill.bundle_files?.slice().sort((a, b) => a.path.localeCompare(b.path)),
244
244
  hydrationFailed: skill.bundle_hydration_failed === true,
245
245
  })).digest('hex');
@@ -270,8 +270,8 @@ export function shouldWriteCloudSkill(
270
270
  if (previous?.folderHash === localSkill.folderHash
271
271
  && previous.cloudContentHash === cloudContentHash(cloudSkill)) return false;
272
272
 
273
- // Without a stored content baseline (skills served through a signed source URL keep
274
- // none, because that URL changes on every pull) the only other signal is
273
+ // Without a stored content baseline (a state file written by an older client for a
274
+ // Skill it fetched through a source URL keeps none) the only other signal is
275
275
  // `skill_folder_hash`, which the server does NOT always compute the way the local
276
276
  // folder hash is computed. A bundle-entry hash can never equal the hash of the
277
277
  // extracted directory, and comparing the two replaced the folder on every sync
@@ -379,7 +379,7 @@ function buildSyncState(
379
379
  agentTargets: normalizeAgentTargets(skill.agent_targets),
380
380
  verifiedAgentLinks: skill.status === "active" ? verifiedAgentLinks[skill.name] ?? {} : {},
381
381
  cloudUpdatedAt: skill.updated_at,
382
- ...(!failedContentNames.has(skill.name) && !skill.skill_source_url
382
+ ...(!failedContentNames.has(skill.name)
383
383
  ? { cloudContentHash: cloudContentHash(skill) } : {}),
384
384
  ...(appliedCloudFolderHash !== undefined ? { appliedCloudFolderHash } : {}),
385
385
  ...(appliedFileList !== undefined ? { appliedFiles: appliedFileList } : {}),
@@ -512,7 +512,7 @@ async function writePulledSkillsToScopedMirror(
512
512
  syncPaths: ReturnType<typeof getSkillSyncPathsForUser>,
513
513
  deps: Pick<
514
514
  RunSkillSyncDependencies,
515
- "downloadSkillBundle" | "writeCloudSkillToDisk"
515
+ "writeCloudSkillToDisk"
516
516
  >,
517
517
  failures: SkillSyncFailure[] = [],
518
518
  writtenSkillNames: Set<string> = new Set(),
@@ -539,10 +539,9 @@ async function writePulledSkillsToScopedMirror(
539
539
  continue;
540
540
  }
541
541
 
542
- const outcome = await writeCloudSkillWithBundleFallback(cloudSkill, {
543
- downloadSkillBundle: deps.downloadSkillBundle,
544
- writeCloudSkillToDisk: (skill, bundleBytes) =>
545
- deps.writeCloudSkillToDisk(skill, bundleBytes, syncPaths, {
542
+ const outcome = await writeCloudSkill(cloudSkill, {
543
+ writeCloudSkillToDisk: (skill) =>
544
+ deps.writeCloudSkillToDisk(skill, syncPaths, {
546
545
  // What the last write put there. Everything else in the folder was
547
546
  // produced locally and survives this one.
548
547
  previouslyApplied: previouslyAppliedFiles(skill, local, previousState),
@@ -558,7 +557,7 @@ async function writePulledSkillsToScopedMirror(
558
557
  appliedFilesByName[cloudSkill.name] = outcome.appliedFiles;
559
558
  }
560
559
  } else {
561
- failures.push({ name: cloudSkill.name, error: "Skill content could not be downloaded or written; sync will retry" });
560
+ failures.push({ name: cloudSkill.name, error: "Skill content could not be written; sync will retry" });
562
561
  }
563
562
  }
564
563
 
@@ -589,7 +588,6 @@ export async function materializeCloudSkillsForLocalShell(
589
588
  jwt: string,
590
589
  dependencies: Partial<Pick<
591
590
  RunSkillSyncDependencies,
592
- | "downloadSkillBundle"
593
591
  | "deleteLocalSkill"
594
592
  | "pullSkills"
595
593
  | "readSyncState"
@@ -953,54 +953,6 @@ async function createZipFromDirectory(directoryPath: string): Promise<string> {
953
953
  }
954
954
  }
955
955
 
956
- async function extractZipToDirectory(
957
- zipPath: string,
958
- destinationDir: string,
959
- ): Promise<string[]> {
960
- const extractRoot = await fs.mkdtemp(
961
- path.join(os.tmpdir(), "notis-skill-extract-"),
962
- );
963
-
964
- try {
965
- if (process.platform === "win32") {
966
- await execFileAsync("powershell.exe", [
967
- "-NoProfile",
968
- "-Command",
969
- `Expand-Archive -Path '${zipPath.replace(/'/g, "''")}' -DestinationPath '${extractRoot.replace(/'/g, "''")}' -Force`,
970
- ]);
971
- } else {
972
- await execFileAsync("unzip", ["-qq", zipPath, "-d", extractRoot]);
973
- }
974
-
975
- const extractedEntries = await fs.readdir(extractRoot, {
976
- withFileTypes: true,
977
- });
978
- const extractedDirectory = extractedEntries.find((entry) =>
979
- entry.isDirectory(),
980
- );
981
- const sourceDir = extractedDirectory
982
- ? path.join(extractRoot, extractedDirectory.name)
983
- : extractRoot;
984
-
985
- await fs.rm(destinationDir, { recursive: true, force: true });
986
- await fs.mkdir(path.dirname(destinationDir), { recursive: true });
987
- await fs.cp(sourceDir, destinationDir, { recursive: true });
988
- return await listRelativeFiles(destinationDir);
989
- } finally {
990
- await fs.rm(extractRoot, { recursive: true, force: true });
991
- }
992
- }
993
-
994
- async function listRelativeFiles(dirPath: string): Promise<string[]> {
995
- try {
996
- const files = await listFilesRecursive(dirPath);
997
- return files.map((filePath) => toPosixRelativePath(dirPath, filePath)).sort();
998
- } catch (error) {
999
- if ((error as NodeJS.ErrnoException)?.code === "ENOENT") return [];
1000
- throw error;
1001
- }
1002
- }
1003
-
1004
956
  function toPosixRelativePath(rootDir: string, filePath: string): string {
1005
957
  return path.relative(rootDir, filePath).split(path.sep).join("/");
1006
958
  }
@@ -1178,14 +1130,12 @@ export async function captureNativeSkillFiles(skill: LocalSkill): Promise<Bundle
1178
1130
 
1179
1131
  export async function writeCloudSkillToDisk(
1180
1132
  skill: CloudSkill,
1181
- bundleBytes?: Buffer,
1182
1133
  paths: SkillSyncPaths = DEFAULT_SYNC_PATHS,
1183
1134
  options: { previouslyApplied?: readonly string[]; expectedFolderHash?: string; legacyBaseline?: boolean } = {},
1184
1135
  ): Promise<SkillWriteOutcome | false> {
1185
1136
  if (isNativeSkill(skill)) {
1186
1137
  assertNativePull({ skills: [{ ...skill, name: 'native-' + skill.id }], skill_sync_protocol: 2, sync_scope: skill.native_scope,
1187
1138
  sync_enabled: true, last_synced_at: null });
1188
- if (bundleBytes?.length) throw new Error('Native Skills require their verified complete file response.');
1189
1139
  }
1190
1140
  const skillDir = path.join(
1191
1141
  paths.skillsDir,
@@ -1196,23 +1146,6 @@ export async function writeCloudSkillToDisk(
1196
1146
  // An unchanged legacy folder upgrading in place: shared files take the cloud version.
1197
1147
  legacyBaseline: isNativeSkill(skill) && options.legacyBaseline === true && options.expectedFolderHash !== undefined };
1198
1148
 
1199
- if (bundleBytes?.length) {
1200
- const bundlePath = path.join(
1201
- os.tmpdir(),
1202
- `notis-skill-download-${Date.now()}-${Math.random().toString(36).slice(2)}.zip`,
1203
- );
1204
- try {
1205
- await fs.writeFile(bundlePath, bundleBytes);
1206
- let appliedFiles: string[] = [];
1207
- await replaceSkillDirectoryAtomically(skillDir, async (stagingDir) => {
1208
- appliedFiles = await extractZipToDirectory(bundlePath, stagingDir);
1209
- }, preserve);
1210
- return { written: true, appliedFiles };
1211
- } finally {
1212
- await fs.rm(bundlePath, { force: true });
1213
- }
1214
- }
1215
-
1216
1149
  if (
1217
1150
  !skill.skill_md &&
1218
1151
  (!skill.bundle_files || skill.bundle_files.length === 0)
@@ -85,6 +85,7 @@ export interface CloudSkill {
85
85
  skill_md: string | null;
86
86
  agent_targets?: Partial<AgentTargets> | null;
87
87
  skill_folder_hash?: string | null;
88
+ /** Where the Skill came from. Provenance only: sync never downloads it (SKL-059). */
88
89
  skill_source_url?: string | null;
89
90
  bundle_files?: BundleFile[] | null;
90
91
  bundle_hydration_failed?: boolean | null;
@@ -1,35 +1,19 @@
1
1
  import type { CloudSkill, SkillWriteOutcome } from './types';
2
2
 
3
3
  interface WriteCloudSkillDependencies {
4
- downloadSkillBundle: (bundleUrl: string) => Promise<Buffer>;
5
- writeCloudSkillToDisk: (skill: CloudSkill, bundleBytes?: Buffer) => Promise<SkillWriteOutcome | boolean>;
4
+ writeCloudSkillToDisk: (skill: CloudSkill) => Promise<SkillWriteOutcome | boolean>;
6
5
  onWarning?: (message: string, error: unknown) => void;
7
6
  }
8
7
 
9
- export async function writeCloudSkillWithBundleFallback(
8
+ /**
9
+ * Writes one pulled Skill from what the pull itself carries: its saved files
10
+ * (`bundle_files`) or, without them, its SKILL.md. Nothing is downloaded;
11
+ * `skill_source_url` only records where a Skill came from (SKL-059).
12
+ */
13
+ export async function writeCloudSkill(
10
14
  skill: CloudSkill,
11
15
  dependencies: WriteCloudSkillDependencies,
12
16
  ): Promise<SkillWriteOutcome | boolean> {
13
- if (skill.skill_source_url) {
14
- try {
15
- const bundleBytes = await dependencies.downloadSkillBundle(skill.skill_source_url);
16
- const wroteBundleToDisk = await dependencies.writeCloudSkillToDisk(skill, bundleBytes);
17
- if (wroteBundleToDisk) {
18
- return wroteBundleToDisk;
19
- }
20
-
21
- dependencies.onWarning?.(
22
- `Bundle sync for "${skill.name}" produced no local changes, falling back to SKILL.md payload.`,
23
- new Error('Bundle write returned false'),
24
- );
25
- } catch (error) {
26
- dependencies.onWarning?.(
27
- `Failed to apply bundle sync for "${skill.name}", falling back to SKILL.md payload.`,
28
- error,
29
- );
30
- }
31
- }
32
-
33
17
  if (skill.bundle_hydration_failed) {
34
18
  dependencies.onWarning?.(
35
19
  `Skipping markdown fallback for synced skill "${skill.name}" because its stored bundle could not be hydrated by the server.`,
@@ -4,11 +4,10 @@ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from '
4
4
  import { homedir } from 'node:os';
5
5
  import { dirname, join } from 'node:path';
6
6
  import { fileURLToPath } from 'node:url';
7
+ import { LIVE_API_ORIGINS } from './api-hosts.js';
7
8
  import { isValidProfileName, loadConfig } from './profiles.js';
8
9
  import { withSkillSyncLock } from './sync-skills.js';
9
10
 
10
- // Every live API, current names first, then the beta name nightly answered on.
11
- const LIVE_API_BASES = ['https://api.notis.ai', 'https://api-nightly.notis.ai', 'https://api-beta.notis.ai'];
12
11
 
13
12
  export const SKILL_SYNC_SERVICE_LABEL = 'ai.notis.skills-sync';
14
13
  const bundlePath = fileURLToPath(new URL('../../dist/skill-sync-worker.mjs', import.meta.url));
@@ -31,7 +30,7 @@ export async function maybeInstallSkillSyncService(runtime, {
31
30
  } = {}) {
32
31
  if (process.platform !== 'darwin' || runtime.credentialKind !== 'oauth'
33
32
  || config.current_profile !== runtime.profileName
34
- || !LIVE_API_BASES.includes(runtime.apiBase)) return;
33
+ || !LIVE_API_ORIGINS.includes(runtime.apiBase)) return;
35
34
  // Ordinary commands must not steal another explicitly bound account's job.
36
35
  const plist = join(homedir(), 'Library', 'LaunchAgents', `${SKILL_SYNC_SERVICE_LABEL}.plist`);
37
36
  if (existsSync(plist)) {
@@ -50,7 +49,7 @@ export async function maybeInstallSkillSyncService(runtime, {
50
49
  export async function installSkillSyncService(runtime, options = {}) {
51
50
  if ((options.platform || process.platform) !== 'darwin') return { status: 'unsupported_platform' };
52
51
  if (runtime.credentialKind !== 'oauth' || !runtime.oauthUserId
53
- || !LIVE_API_BASES.includes(runtime.apiBase)) {
52
+ || !LIVE_API_ORIGINS.includes(runtime.apiBase)) {
54
53
  return { status: 'skipped_non_personal_profile' };
55
54
  }
56
55
  // Registration upgrades must not kill a worker holding the filesystem lock,
@@ -68,7 +67,7 @@ async function installSkillSyncServiceLocked(runtime, {
68
67
  if (platform !== 'darwin') return { status: 'unsupported_platform' };
69
68
  if (runtime.credentialKind !== 'oauth' || runtime.envCredentialOverride
70
69
  || !isValidProfileName(runtime.profileName)
71
- || !LIVE_API_BASES.includes(runtime.apiBase)) {
70
+ || !LIVE_API_ORIGINS.includes(runtime.apiBase)) {
72
71
  return { status: 'skipped_non_personal_profile' };
73
72
  }
74
73
  const root = join(home, '.notis', 'skills', 'service');