@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
@@ -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
@@ -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');
@@ -5,12 +5,33 @@ import { usageError } from './errors.js';
5
5
  const object = value => value && typeof value === 'object' && !Array.isArray(value);
6
6
  const exact = (value, keys) => object(value) && Object.keys(value).sort().join(',') === [...keys].sort().join(',');
7
7
 
8
+ /** At most this many extra param sets are measured for loading skeletons. */
9
+ export const SKELETON_PARAM_SETS_MAX = 4;
10
+
11
+ /**
12
+ * The extra view params whose loading skeletons are measured too (fixtures `context.skeletonParams`): each is a
13
+ * flat object of string values, such as a tab the view opens on. Anything else is ignored.
14
+ */
15
+ export function fixtureSkeletonParams(release) {
16
+ let list;
17
+ try { list = createSpaceFixtureEngine(release).context.skeletonParams; } catch { return []; }
18
+ if (!Array.isArray(list)) return [];
19
+ return list.filter(item => object(item) && Object.values(item).every(value => typeof value === 'string'))
20
+ .slice(0, SKELETON_PARAM_SETS_MAX).map(item => structuredClone(item));
21
+ }
22
+
23
+ /**
24
+ * `audience: 'public'` draws the view as the public sees it: the editor's descriptor with View as the public on, so
25
+ * the page applies the public floors itself (no editor-only lists, actions, params or columns), as in the Portal.
26
+ */
8
27
  export function createSpaceFixtureBroker({ release, capabilities, width, outputs = ['markdown', 'screenshot'],
9
- authorizationMode = 'authorize_missing', unavailableActions = [], onFailure }) {
28
+ authorizationMode = 'authorize_missing', unavailableActions = [], onFailure, params: paramsOverride, audience = 'editor' }) {
10
29
  const engine = createSpaceFixtureEngine(release);
11
30
  const frozen = spaceHarnessSnapshot(release, capabilities, engine, { authorizationMode, unavailableActions });
31
+ if (audience === 'public') frozen.descriptor.space.viewAs = 'public';
12
32
  const calls = [];
13
- const params = structuredClone(engine.context.params || {});
33
+ // Skeleton capture may open the view with other params (a tab), on top of the fixture's own.
34
+ const params = structuredClone({ ...(engine.context.params || {}), ...(paramsOverride || {}) });
14
35
  // The fixture's own "now" pins the browser clock, so a view that asks for the
15
36
  // last hour sends the exact inputs its fixtures recorded.
16
37
  const now = engine.context.now;
@@ -32,6 +32,8 @@ export function generateSpaceManifest(selection) {
32
32
  ...(definition.cloudComputer ? { cloud_computer: definition.cloudComputer } : {}),
33
33
  // Agents its database changes wake; absent when undeclared.
34
34
  ...(definition.agents?.length ? { agents: definition.agents } : {}),
35
+ // Live items agents attach to threads; absent when undeclared.
36
+ ...(definition.threadItems && Object.keys(definition.threadItems).length ? { thread_items: definition.threadItems } : {}),
35
37
  // Absent when nothing is editor-only (SPC-073: unmarked means public).
36
38
  ...(editorsOnly ? { editors_only: editorsOnly } : {}),
37
39
  readable_context: definition.readableContext || '', collection: definition.collection || null,
@@ -7,7 +7,7 @@ import { usageError } from './errors.js';
7
7
  import { VIEW_DEFINITION_FIELDS, viewManifestFields } from './space-view-manifest.js';
8
8
  import { editorOnlyColumns, editorsOnlyFlag, withoutMarker } from './space-audience.js';
9
9
 
10
- const CONFIG_FIELDS = new Set(['name', 'description', 'icon', 'accent', 'entry', 'layout', 'readableContext', 'resources', 'actions', 'navigation', 'viewerReads', 'cloudComputer', 'agents', 'collection', 'sourceIncludes', 'verificationFixtures', 'editorsOnly', ...VIEW_DEFINITION_FIELDS]);
10
+ const CONFIG_FIELDS = new Set(['name', 'description', 'icon', 'accent', 'entry', 'layout', 'readableContext', 'resources', 'actions', 'navigation', 'viewerReads', 'cloudComputer', 'agents', 'threadItems', 'collection', 'sourceIncludes', 'verificationFixtures', 'editorsOnly', ...VIEW_DEFINITION_FIELDS]);
11
11
  /** Reads with each signed-in viewer's own authority (never an issuer grant); see docs/notis-spaces-platform.md. */
12
12
  export const VIEWER_READ_FAMILIES = Object.freeze(['databases', 'skills']);
13
13
  const WORKSPACE_INDEXES = new Set(['notis.config.ts', 'notis.config.js', 'notis.config.mjs']);
@@ -226,6 +226,7 @@ export async function loadSelectedSpace(projectDir, selectedKey) {
226
226
  if (definition.cloudComputer != null) validateCloudComputer(definition.cloudComputer);
227
227
  if (definition.cloudComputer != null && !entry) throw usageError('A container has no page, so it cannot use the cloud computer.');
228
228
  if (definition.agents != null) validateSpaceAgents(definition.agents, resources);
229
+ if (definition.threadItems != null) validateThreadItems(definition.threadItems, definition.actions || {});
229
230
  if (definition.collection && (resources[definition.collection.database]?.kind !== 'database' || !definition.collection.titleProperty)) {
230
231
  throw usageError('A collection needs a declared database binding and title property.');
231
232
  }
@@ -386,3 +387,67 @@ export function validateSpaceAgents(agents, resources = {}) {
386
387
  }
387
388
  }
388
389
  }
390
+
391
+ const THREAD_ITEM_FIELDS = ['label', 'description', 'inputs', 'read', 'title', 'url', 'states', 'checks', 'actions', 'page'];
392
+ const THREAD_ITEM_STATE_FIELDS = ['id', 'label', 'icon', 'when', 'needsYou', 'final'];
393
+ const THREAD_ITEM_ACTION_FIELDS = ['label', 'tool', 'arguments', 'confirm', 'states', 'primary'];
394
+ const REFUSED_ITEM_TOOL = /^(LOCAL_|COMPOSIO_|NOTIS_|CUSTOM_|MCP_)/;
395
+
396
+ function threadItemLabel(value) {
397
+ if (typeof value === 'string') return value.trim().length > 0;
398
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value) && typeof value.en === 'string' && value.en.trim().length > 0
399
+ && Object.keys(value).every(name => ['en', 'fr'].includes(name) && typeof value[name] === 'string' && value[name].trim());
400
+ }
401
+
402
+ /**
403
+ * The live item kinds agents attach to threads (`threadItems`). The shape is checked here so a
404
+ * mistake fails before the build; server/lib/space_thread_items.py repeats every check, including
405
+ * placeholders and conditions, when the Space is published.
406
+ */
407
+ export function validateThreadItems(threadItems, actions = {}) {
408
+ const kinds = threadItems && typeof threadItems === 'object' && !Array.isArray(threadItems) ? Object.entries(threadItems) : null;
409
+ if (!kinds || kinds.length < 1 || kinds.length > 8) throw usageError('Declare threadItems as 1 to 8 item kinds.');
410
+ for (const [kind, spec] of kinds) {
411
+ if (!/^[a-z][a-z0-9_]{0,39}$/.test(kind)) throw usageError('Each thread item kind needs a short id: lowercase letters, digits and _.');
412
+ if (!spec || typeof spec !== 'object' || Array.isArray(spec) || Object.keys(spec).some(name => !THREAD_ITEM_FIELDS.includes(name))) {
413
+ throw usageError(`Thread item ${kind} takes ${THREAD_ITEM_FIELDS.join(', ')} only.`);
414
+ }
415
+ if (!threadItemLabel(spec.label)) throw usageError(`Thread item ${kind} needs a label.`);
416
+ if (spec.inputs?.type !== 'object' || spec.inputs?.additionalProperties !== false || !spec.inputs.properties
417
+ || !Array.isArray(spec.inputs.required) || !spec.inputs.required.length) {
418
+ throw usageError(`Thread item ${kind} declares its inputs as a closed object with the fields an agent must give in required.`);
419
+ }
420
+ if (!spec.read || typeof spec.read.action !== 'string' || !Object.hasOwn(actions, spec.read.action)) {
421
+ throw usageError(`Thread item ${kind} reads through one of this Space's actions: read: { action: '<id>' }.`);
422
+ }
423
+ if (typeof spec.title !== 'string' && !threadItemLabel(spec.title)) throw usageError(`Thread item ${kind} needs a title template.`);
424
+ if (!Array.isArray(spec.states) || spec.states.length < 1 || spec.states.length > 12) {
425
+ throw usageError(`Thread item ${kind} lists 1 to 12 states in the order they are checked.`);
426
+ }
427
+ const stateIds = new Set();
428
+ for (const state of spec.states) {
429
+ if (!state || typeof state !== 'object' || Object.keys(state).some(name => !THREAD_ITEM_STATE_FIELDS.includes(name))
430
+ || typeof state.id !== 'string' || !/^[a-z][a-z0-9_-]{0,39}$/.test(state.id) || stateIds.has(state.id)) {
431
+ throw usageError(`Each state of thread item ${kind} has its own id and takes ${THREAD_ITEM_STATE_FIELDS.join(', ')} only.`);
432
+ }
433
+ stateIds.add(state.id);
434
+ if (!threadItemLabel(state.label)) throw usageError(`State ${state.id} of thread item ${kind} needs a label.`);
435
+ if (typeof state.icon !== 'string' || !/^phosphor:[a-z0-9]+(-[a-z0-9]+)*$/.test(state.icon)) {
436
+ throw usageError(`State ${state.id} of thread item ${kind} needs a Phosphor icon, written phosphor:<name>.`);
437
+ }
438
+ }
439
+ if (spec.states.at(-1).when != null) throw usageError(`The last state of thread item ${kind} has no condition, so every item has a state.`);
440
+ for (const [actionId, action] of Object.entries(spec.actions || {})) {
441
+ if (!action || typeof action !== 'object' || Object.keys(action).some(name => !THREAD_ITEM_ACTION_FIELDS.includes(name))) {
442
+ throw usageError(`Action ${actionId} of thread item ${kind} takes ${THREAD_ITEM_ACTION_FIELDS.join(', ')} only.`);
443
+ }
444
+ if (!threadItemLabel(action.label)) throw usageError(`Action ${actionId} of thread item ${kind} needs a label.`);
445
+ if (typeof action.tool !== 'string' || !/^[A-Z][A-Z0-9]*(_[A-Z0-9]+)+$/.test(action.tool) || REFUSED_ITEM_TOOL.test(action.tool)) {
446
+ throw usageError(`Action ${actionId} of thread item ${kind} runs one connected app tool, such as GITHUB_MERGE_A_PULL_REQUEST.`);
447
+ }
448
+ if (action.states != null && (!Array.isArray(action.states) || action.states.some(id => !stateIds.has(id)))) {
449
+ throw usageError(`Action ${actionId} of thread item ${kind} lists states this item declares.`);
450
+ }
451
+ }
452
+ }
453
+ }
@@ -60,6 +60,21 @@ function recordViewExample(operation,key) {
60
60
  }
61
61
  const VIEWER_READS={list_databases:'databases',get_database:'databases',query_database:'databases',list_skills:'skills',get_skill:'skills'};
62
62
 
63
+ /**
64
+ * A shown fixture holds the whole list; a read asks for one page of it (page_size rows from offset), as the host
65
+ * does live. Without this a view reading every page (useShown allPages) got all rows on each page and counted
66
+ * them once per page.
67
+ */
68
+ function shownPage(result,options) {
69
+ if(!object(options) || !object(result) || !Array.isArray(result.rows)) return result;
70
+ const offset=Number.isSafeInteger(options.offset) && options.offset>0 ? options.offset : 0;
71
+ // An offset with no page size reads one page of the live default size (100, server/lib/space_view_manifest.py).
72
+ const size=Number.isSafeInteger(options.page_size) && options.page_size>0 ? options.page_size : offset ? 100 : null;
73
+ if(size===null) return result;
74
+ result.rows=result.rows.slice(offset,offset+size);
75
+ return result;
76
+ }
77
+
63
78
  export function createSpaceFixtureEngine(release) {
64
79
  const bodyTemplates=structuredClone(release.manifest.actions || {});
65
80
  const bodyResources=structuredClone(release.manifest.resources || {});
@@ -203,12 +218,12 @@ export function createSpaceFixtureEngine(release) {
203
218
  if(!matched) throw usageError('Add an explicit synthetic document body fixture.');
204
219
  return structuredClone(matched.result);
205
220
  },
206
- executeShown(name,params) {
221
+ executeShown(name,params,options={}) {
207
222
  if(!Object.hasOwn(declaredLists,name)) throw usageError('This view does not declare that list.');
208
223
  if(!object(params)) throw usageError('List params must be an object.');
209
224
  const matched=shownCases[name]?.find(entry=>isDeepStrictEqual(entry.params,params));
210
225
  if(!matched) throw usageError(`Add an explicit synthetic shown fixture for ${name} and these params.`);
211
- return structuredClone(matched.result);
226
+ return shownPage(structuredClone(matched.result),options);
212
227
  },
213
228
  executeViewerRead(operation,input) {
214
229
  if(!Object.hasOwn(VIEWER_READS,operation) || !declaredReads.includes(VIEWER_READS[operation])) throw usageError('This Space does not declare that viewer read.');
@@ -318,8 +333,9 @@ export async function startSpaceTestServer({release,capabilities,port=0,authoriz
318
333
  const input=JSON.parse(Buffer.concat(chunks).toString('utf8'));
319
334
  if(object(input) && Object.keys(input).length===1 && Object.hasOwn(input,'shown')) {
320
335
  const list=input.shown;
321
- if(!object(list) || Object.keys(list).sort().join(',')!=='name,params') return response(400,'{}');
322
- try {return response(200,JSON.stringify({result:engine.executeShown(list.name,list.params)}));}
336
+ const keys=object(list) ? Object.keys(list).sort().join(',') : '';
337
+ if(keys!=='name,params' && keys!=='name,options,params') return response(400,'{}');
338
+ try {return response(200,JSON.stringify({result:engine.executeShown(list.name,list.params,list.options)}));}
323
339
  catch(error) {return response(400,JSON.stringify({message:error.message}));}
324
340
  }
325
341
  if(object(input) && Object.keys(input).length===1 && Object.hasOwn(input,'viewer_read')) {