@notis_ai/cli 0.2.25 → 0.2.27

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 (163) hide show
  1. package/README.md +186 -5
  2. package/config/notis_app_design_rules.json +36 -14
  3. package/config/portal-route-roots.json +1 -0
  4. package/dist/agent-hooks/notis-agent-hook.mjs +2866 -553
  5. package/dist/base-skills/notis-cli/.notis-base-skill.json +1 -1
  6. package/dist/base-skills/notis-cli/references/intelligence.md +1 -1
  7. package/dist/base-skills/notis-query/.notis-base-skill.json +1 -1
  8. package/dist/base-skills/notis-query/SKILL.md +0 -1
  9. package/dist/base-skills/notis-query/references/documents.md +7 -0
  10. package/dist/base-skills/notis-query/references/query.md +1 -0
  11. package/dist/base-skills/notis-spaces/.notis-base-skill.json +1 -1
  12. package/dist/base-skills/notis-spaces/SKILL.md +96 -24
  13. package/dist/base-skills/notis-spaces/references/architecture.md +4 -3
  14. package/dist/base-skills/notis-spaces/references/context.md +3 -0
  15. package/dist/base-skills/notis-spaces/references/design.md +37 -18
  16. package/dist/base-skills/notis-spaces/references/reading.md +8 -1
  17. package/dist/base-skills/notis-spaces/references/reports.md +6 -6
  18. package/dist/base-skills/notis-spaces/references/sdk.md +71 -7
  19. package/dist/base-skills/notis-spaces/references/store.md +22 -13
  20. package/dist/base-skills/notis-spaces/references/views.md +99 -6
  21. package/dist/sdk/package.json +3 -0
  22. package/dist/sdk/src/cloudComputerWords.ts +53 -0
  23. package/dist/sdk/src/components/Audience.tsx +76 -0
  24. package/dist/sdk/src/components/DocumentPage.tsx +15 -4
  25. package/dist/sdk/src/components/MarkdownEditor.tsx +44 -14
  26. package/dist/sdk/src/components/MultiSelectActionBar.tsx +16 -5
  27. package/dist/sdk/src/components/NotisSelectionBoundary.tsx +79 -25
  28. package/dist/sdk/src/components/Skeleton.tsx +162 -6
  29. package/dist/sdk/src/hooks/useAction.ts +12 -2
  30. package/dist/sdk/src/hooks/useAgentQueue.ts +125 -0
  31. package/dist/sdk/src/hooks/useCloudComputerJob.ts +142 -0
  32. package/dist/sdk/src/hooks/useCloudComputerService.ts +388 -0
  33. package/dist/sdk/src/hooks/useCloudComputerShell.ts +95 -7
  34. package/dist/sdk/src/hooks/useCollectionInteractions.ts +40 -2
  35. package/dist/sdk/src/hooks/useItemThread.ts +58 -0
  36. package/dist/sdk/src/hooks/useMarqueeSelection.ts +6 -1
  37. package/dist/sdk/src/hooks/useNativeDocuments.ts +61 -8
  38. package/dist/sdk/src/hooks/useNotisNavigation.ts +31 -8
  39. package/dist/sdk/src/hooks/useQuery.ts +67 -10
  40. package/dist/sdk/src/hooks/useViewParams.ts +47 -11
  41. package/dist/sdk/src/index.ts +31 -4
  42. package/dist/sdk/src/interactions.ts +2 -0
  43. package/dist/sdk/src/nativeData.ts +2 -0
  44. package/dist/sdk/src/optimisticRows.ts +329 -0
  45. package/dist/sdk/src/perf.ts +188 -0
  46. package/dist/sdk/src/provider.tsx +2 -1
  47. package/dist/sdk/src/queryCache.ts +366 -17
  48. package/dist/sdk/src/runtime.ts +55 -4
  49. package/dist/sdk/src/skeleton.ts +103 -0
  50. package/dist/sdk/src/space.ts +662 -28
  51. package/dist/sdk/src/spacePublicUI.ts +36 -0
  52. package/dist/sdk/src/ui/engine/step.ts +54 -0
  53. package/dist/sdk/src/ui/icons.tsx +3 -1
  54. package/dist/sdk/src/words/shell.ts +1 -0
  55. package/dist/skill-sync/index.js +88 -13
  56. package/dist/skill-sync-worker.mjs +127 -38
  57. package/dist/space-harness/host.js +272 -105
  58. package/dist/space-sdk/dist/chunk-BWHAORT4.js +5 -0
  59. package/dist/space-sdk/dist/index.js +9 -4
  60. package/dist/space-sdk/dist/ui.js +12 -12
  61. package/dist/space-sdk/package.json +3 -0
  62. package/dist/space-sdk/src/cloudComputerWords.d.ts +34 -0
  63. package/dist/space-sdk/src/components/Audience.d.ts +46 -0
  64. package/dist/space-sdk/src/components/DocumentPage.d.ts +3 -1
  65. package/dist/space-sdk/src/components/MarkdownEditor.d.ts +21 -0
  66. package/dist/space-sdk/src/components/MultiSelectActionBar.d.ts +5 -1
  67. package/dist/space-sdk/src/components/NotisSelectionBoundary.d.ts +19 -2
  68. package/dist/space-sdk/src/components/Skeleton.d.ts +7 -2
  69. package/dist/space-sdk/src/hooks/useAction.d.ts +8 -1
  70. package/dist/space-sdk/src/hooks/useAgentQueue.d.ts +61 -0
  71. package/dist/space-sdk/src/hooks/useCloudComputerJob.d.ts +35 -0
  72. package/dist/space-sdk/src/hooks/useCloudComputerService.d.ts +75 -0
  73. package/dist/space-sdk/src/hooks/useCloudComputerShell.d.ts +36 -3
  74. package/dist/space-sdk/src/hooks/useCollectionInteractions.d.ts +6 -0
  75. package/dist/space-sdk/src/hooks/useItemThread.d.ts +32 -0
  76. package/dist/space-sdk/src/hooks/useMarqueeSelection.d.ts +2 -1
  77. package/dist/space-sdk/src/hooks/useNativeDocumentBody.d.ts +1 -0
  78. package/dist/space-sdk/src/hooks/useNativeDocuments.d.ts +20 -5
  79. package/dist/space-sdk/src/hooks/useNotisNavigation.d.ts +11 -2
  80. package/dist/space-sdk/src/hooks/useQuery.d.ts +24 -2
  81. package/dist/space-sdk/src/hooks/useViewParams.d.ts +2 -0
  82. package/dist/space-sdk/src/index.d.ts +24 -4
  83. package/dist/space-sdk/src/nativeData.d.ts +6 -0
  84. package/dist/space-sdk/src/queryCache.d.ts +97 -2
  85. package/dist/space-sdk/src/runtime.d.ts +53 -4
  86. package/dist/space-sdk/src/skeleton.d.ts +42 -0
  87. package/dist/space-sdk/src/space.ts +662 -28
  88. package/dist/space-sdk/src/tailwind-candidates.d.ts +761 -6
  89. package/dist/space-sdk/src/ui/cloud/CloudComputerFrame.d.ts +29 -0
  90. package/dist/space-sdk/src/ui/cloud/CloudComputerWaking.d.ts +20 -0
  91. package/dist/space-sdk/src/ui/comments/CommentPane.d.ts +15 -2
  92. package/dist/space-sdk/src/ui/comments/PassageComments.d.ts +50 -0
  93. package/dist/space-sdk/src/ui/comments/commentFiles.d.ts +64 -0
  94. package/dist/space-sdk/src/ui/comments/commentModel.d.ts +49 -1
  95. package/dist/space-sdk/src/ui/comments/commentWords.d.ts +26 -0
  96. package/dist/space-sdk/src/ui/comments/index.d.ts +4 -0
  97. package/dist/space-sdk/src/ui/comments/passageModel.d.ts +82 -0
  98. package/dist/space-sdk/src/ui/comments/useComments.d.ts +34 -4
  99. package/dist/space-sdk/src/ui/comments/usePassageComments.d.ts +67 -0
  100. package/dist/space-sdk/src/ui/engine/index.d.ts +2 -2
  101. package/dist/space-sdk/src/ui/engine/step.d.ts +9 -0
  102. package/dist/space-sdk/src/ui/fields/fields.d.ts +2 -1
  103. package/dist/space-sdk/src/ui/index.d.ts +4 -0
  104. package/dist/space-sdk/src/ui/layout/Panels.d.ts +9 -2
  105. package/dist/space-sdk/src/ui/layout/SidePane.d.ts +42 -0
  106. package/dist/space-sdk/src/ui/layout/index.d.ts +2 -1
  107. package/dist/space-sdk/src/ui/layout/panelMath.d.ts +11 -2
  108. package/dist/space-sdk/src/ui/list/ListReader.d.ts +38 -7
  109. package/dist/space-sdk/src/ui/list/Row.d.ts +4 -0
  110. package/dist/space-sdk/src/ui/list/SelectionBar.d.ts +9 -4
  111. package/dist/space-sdk/src/ui/list/useListKeys.d.ts +4 -0
  112. package/dist/space-sdk/src/words/shell.ts +1 -0
  113. package/dist/view-renderer/dist/host.js +355 -188
  114. package/dist/view-renderer/dist/theme.css +1 -1
  115. package/dist/view-renderer/src/dom.js +15 -2
  116. package/dist/view-renderer/src/host.tsx +4 -1
  117. package/dist/view-renderer/src/index.js +3 -0
  118. package/dist/view-renderer/src/pool.js +8 -4
  119. package/dist/view-renderer/src/renderer.js +92 -23
  120. package/dist/view-renderer/src/skeleton.js +450 -0
  121. package/package.json +4 -4
  122. package/skills/notis-cli/AGENT_INSTRUCTIONS.md +8 -4
  123. package/skills/notis-onboarding/BRIEF.md +15 -9
  124. package/skills/notis-spaces/cli.md +43 -4
  125. package/src/command-specs/auth.js +5 -3
  126. package/src/command-specs/cc.js +410 -0
  127. package/src/command-specs/computer.js +320 -0
  128. package/src/command-specs/diagnostics.js +2 -13
  129. package/src/command-specs/documents.js +22 -4
  130. package/src/command-specs/index.js +7 -0
  131. package/src/command-specs/onboarding.js +127 -7
  132. package/src/command-specs/skills.js +2 -2
  133. package/src/command-specs/spaces.js +162 -30
  134. package/src/command-specs/tools.js +26 -8
  135. package/src/command-specs/views.js +4 -1
  136. package/src/runtime/agent-setup.js +20 -2
  137. package/src/runtime/app-boundary-validator.js +2 -1
  138. package/src/runtime/app-platform.js +13 -0
  139. package/src/runtime/auth-recovery.js +5 -0
  140. package/src/runtime/channel.js +16 -2
  141. package/src/runtime/cloud-transfer.js +587 -0
  142. package/src/runtime/computer-ssh.js +127 -0
  143. package/src/runtime/oauth.js +50 -4
  144. package/src/runtime/skill-sync/cloud-client.ts +98 -15
  145. package/src/runtime/skill-sync/index.ts +42 -4
  146. package/src/runtime/skill-sync/local-scanner.ts +1 -0
  147. package/src/runtime/skill-sync/types.ts +6 -0
  148. package/src/runtime/space-audience.js +94 -0
  149. package/src/runtime/space-collection-scaffold.js +2 -1
  150. package/src/runtime/space-fixture-broker.js +2 -1
  151. package/src/runtime/space-lock.js +1 -4
  152. package/src/runtime/space-platform.js +18 -2
  153. package/src/runtime/space-source.js +105 -7
  154. package/src/runtime/space-test-server.js +13 -2
  155. package/src/runtime/space-verification.js +99 -6
  156. package/src/runtime/space-view-manifest.js +22 -4
  157. package/src/runtime/sync-skills.js +24 -20
  158. package/src/runtime/transport.js +19 -0
  159. package/src/runtime/view-render.js +2 -2
  160. package/src/skill-sync-worker.js +5 -1
  161. package/template/.harness/index.html.tmpl +1 -1
  162. package/dist/skill-sync/index.js.map +0 -7
  163. package/dist/space-sdk/dist/chunk-SVZATGZB.js +0 -5
@@ -0,0 +1,127 @@
1
+ // Local files for `notis computer ssh`: this device's key, the SSH config
2
+ // block for `ssh notis-computer`, the proxy wrapper and the computer's host key.
3
+ // Everything lives in ~/.ssh/notis; ~/.ssh/config only gains one Include line.
4
+
5
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
6
+ import { homedir } from 'node:os';
7
+ import { dirname, join } from 'node:path';
8
+
9
+ export const SSH_HOST_ALIAS = 'notis-computer';
10
+ export const SSH_USER = 'user';
11
+ export const INCLUDE_MARKER = '# notis-computer-ssh';
12
+ const HOST_KEY_TYPE = /^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(256|384|521)|sk-ssh-ed25519@openssh\.com|sk-ecdsa-sha2-nistp256@openssh\.com|rsa-sha2-(256|512))$/;
13
+
14
+ export function sshPaths(home = homedir()) {
15
+ const dir = join(home, '.ssh', 'notis');
16
+ return {
17
+ sshDir: join(home, '.ssh'),
18
+ dir,
19
+ userConfig: join(home, '.ssh', 'config'),
20
+ config: join(dir, 'config'),
21
+ key: join(dir, 'id_ed25519'),
22
+ publicKey: join(dir, 'id_ed25519.pub'),
23
+ proxy: join(dir, 'proxy'),
24
+ knownHosts: join(dir, 'known_hosts'),
25
+ };
26
+ }
27
+
28
+ function shellQuote(value) {
29
+ return `'${String(value).replace(/'/g, `'\\''`)}'`;
30
+ }
31
+
32
+ // ssh_config tokens are split on whitespace; a quoted path survives spaces.
33
+ function configPath(value) {
34
+ return /[\s"]/.test(value) ? `"${value.replace(/"/g, '\\"')}"` : value;
35
+ }
36
+
37
+ export function sshConfigText(paths) {
38
+ return [
39
+ '# Written by notis computer ssh --setup. Run it again to refresh this file.',
40
+ `Host ${SSH_HOST_ALIAS}`,
41
+ ` HostName ${SSH_HOST_ALIAS}`,
42
+ ` User ${SSH_USER}`,
43
+ ` IdentityFile ${configPath(paths.key)}`,
44
+ ' IdentitiesOnly yes',
45
+ // The proxy asks Notis where the computer is (and starts it when stopped),
46
+ // writes its current host key, then relays the connection.
47
+ ` ProxyCommand ${configPath(paths.proxy)}`,
48
+ ` HostKeyAlias ${SSH_HOST_ALIAS}`,
49
+ ` UserKnownHostsFile ${configPath(paths.knownHosts)}`,
50
+ ' StrictHostKeyChecking yes',
51
+ ' ServerAliveInterval 15',
52
+ ' ServerAliveCountMax 4',
53
+ '',
54
+ ].join('\n');
55
+ }
56
+
57
+ // The proxy pins this CLI, profile and config file: ssh runs it from any
58
+ // directory and apps such as T3 Desktop start it without the shell's
59
+ // environment, where a bare `notis` could pick another profile, an older CLI or
60
+ // the default config without that profile.
61
+ export function proxyScriptText({ nodePath, cliPath, profileName, configFile }) {
62
+ const profile = profileName ? ` --profile ${shellQuote(profileName)}` : '';
63
+ return [
64
+ '#!/bin/sh',
65
+ '# Written by notis computer ssh --setup.',
66
+ ...(configFile ? [`NOTIS_CLI_CONFIG_FILE=${shellQuote(configFile)}`, 'export NOTIS_CLI_CONFIG_FILE'] : []),
67
+ `NODE=${shellQuote(nodePath)}`,
68
+ `CLI=${shellQuote(cliPath)}`,
69
+ `if [ -x "$NODE" ] && [ -f "$CLI" ]; then exec "$NODE" "$CLI"${profile} computer ssh --proxy; fi`,
70
+ `if command -v notis >/dev/null 2>&1; then exec notis${profile} computer ssh --proxy; fi`,
71
+ `exec npx --yes --package @notis_ai/cli@latest -- notis${profile} computer ssh --proxy`,
72
+ '',
73
+ ].join('\n');
74
+ }
75
+
76
+ // Include only works before the first Host block, so the line goes on top.
77
+ export function withInclude(existing, paths) {
78
+ const text = existing || '';
79
+ if (text.includes(INCLUDE_MARKER)) return text;
80
+ return `Include ${configPath(paths.config)} ${INCLUDE_MARKER}\n${text ? `\n${text}` : ''}`;
81
+ }
82
+
83
+ // boat may send a bare key or a known_hosts line; ssh needs `<alias> <type> <key>`.
84
+ export function knownHostsText(hostKey) {
85
+ const lines = [];
86
+ for (const raw of String(hostKey || '').split(/\r?\n/)) {
87
+ const fields = raw.trim().split(/\s+/).filter(Boolean);
88
+ const typeIndex = fields.findIndex(field => HOST_KEY_TYPE.test(field));
89
+ if (typeIndex < 0 || !fields[typeIndex + 1]) continue;
90
+ lines.push(`${SSH_HOST_ALIAS} ${fields[typeIndex]} ${fields[typeIndex + 1]}`);
91
+ }
92
+ return lines.length ? `${lines.join('\n')}\n` : '';
93
+ }
94
+
95
+ function writeAtomic(path, text, mode) {
96
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
97
+ const temp = `${path}.${process.pid}.tmp`;
98
+ writeFileSync(temp, text, { mode });
99
+ chmodSync(temp, mode);
100
+ renameSync(temp, path);
101
+ }
102
+
103
+ export function writeSshFiles({ paths, nodePath, cliPath, profileName, configFile }) {
104
+ mkdirSync(paths.sshDir, { recursive: true, mode: 0o700 });
105
+ writeAtomic(paths.config, sshConfigText(paths), 0o600);
106
+ writeAtomic(paths.proxy, proxyScriptText({ nodePath, cliPath, profileName, configFile }), 0o700);
107
+ const existing = existsSync(paths.userConfig) ? readFileSync(paths.userConfig, 'utf8') : '';
108
+ const next = withInclude(existing, paths);
109
+ if (next !== existing) writeAtomic(paths.userConfig, next, 0o600);
110
+ }
111
+
112
+ export function writeHostKey(paths, hostKey) {
113
+ const text = knownHostsText(hostKey);
114
+ if (!text) return false;
115
+ writeAtomic(paths.knownHosts, text, 0o600);
116
+ return true;
117
+ }
118
+
119
+ // The connect reply names a host and port; ssh's own HostName is only a label.
120
+ export function parseConnectReply(payload) {
121
+ const host = typeof payload?.host === 'string' ? payload.host.trim() : '';
122
+ const port = Number(payload?.port);
123
+ if (payload?.status !== 'ready' || !host || !Number.isInteger(port) || port < 1 || port > 65535) {
124
+ return null;
125
+ }
126
+ return { host, port, user: payload.user || SSH_USER, hostKey: payload.host_key || '' };
127
+ }
@@ -913,6 +913,41 @@ function openBrowser(url) {
913
913
  }
914
914
  }
915
915
 
916
+ /**
917
+ * Whether a CLI an agent runs may open the sign-in page for the person at this computer, rather than asking them to
918
+ * click a link. Never over SSH (the page would open on a screen nobody is looking at), in CI, on Linux without a
919
+ * display, inside node's test runner, or when BROWSER=none or NOTIS_NO_BROWSER is set.
920
+ */
921
+ export function canOpenBrowser(env = process.env, platform = process.platform) {
922
+ if (env.NOTIS_NO_BROWSER || env.BROWSER === 'none' || env.NODE_TEST_CONTEXT) return false;
923
+ if (env.CI && !['0', 'false'].includes(String(env.CI).toLowerCase())) return false;
924
+ if (env.SSH_CONNECTION || env.SSH_CLIENT || env.SSH_TTY) return false;
925
+ if (platform === 'linux') return Boolean(env.DISPLAY || env.WAYLAND_DISPLAY);
926
+ return platform === 'darwin' || platform === 'win32';
927
+ }
928
+
929
+ /**
930
+ * Opens the sign-in page for an agent's run and says whether it did: the opener's exit code, or true when it is still
931
+ * running after `waitMs` (some xdg-open handlers stay up with the browser). A sandbox that refuses to launch apps
932
+ * reads as false, so the agent hands the person the link instead.
933
+ */
934
+ export function openBrowserForAgent(url, { env = process.env, platform = process.platform, spawnImpl = spawn, waitMs = 3000 } = {}) {
935
+ if (!canOpenBrowser(env, platform)) return Promise.resolve(false);
936
+ const { command, args } = browserOpenCommand(url, platform);
937
+ return new Promise((resolve) => {
938
+ let child;
939
+ try {
940
+ child = spawnImpl(command, args, { detached: true, stdio: 'ignore' });
941
+ } catch {
942
+ resolve(false);
943
+ return;
944
+ }
945
+ const timer = setTimeout(() => { child.unref?.(); resolve(true); }, waitMs);
946
+ child.on('error', () => { clearTimeout(timer); resolve(false); });
947
+ child.on('exit', (code) => { clearTimeout(timer); resolve(code === 0); });
948
+ });
949
+ }
950
+
916
951
  function storedOAuthMetadata(runtime, profile) {
917
952
  const issuer = String(profile.oauth_issuer || '').replace(/\/+$/, '');
918
953
  const apiBase = getOAuthApiBase(profile)
@@ -2333,6 +2368,8 @@ export async function loginWithOAuth(
2333
2368
  authorize_url: live.authorize_url,
2334
2369
  expires_in: Math.max(0, Number(live.expires_at) - Math.floor(Date.now() / 1000)),
2335
2370
  hand_off: 'browser_callback',
2371
+ // The page opened on the first run; opening it again on every confirmation would stack tabs.
2372
+ browser_opened: false,
2336
2373
  confirm_command: confirmCommand(
2337
2374
  runtime.profileName,
2338
2375
  authorizationChannel(metadata, runtime),
@@ -2532,6 +2569,10 @@ export async function loginWithOAuth(
2532
2569
  expires_at: Math.floor(Date.now() / 1000) + listenerTtlSeconds,
2533
2570
  });
2534
2571
  detachedListenerPublished = true;
2572
+ // The person is at this computer even when an agent runs the CLI: open the page for them.
2573
+ const browserOpened = options.browser === false
2574
+ ? false
2575
+ : await (options.openAgentBrowser || openBrowserForAgent)(authorizeUrl);
2535
2576
  return {
2536
2577
  agentAuthorization: {
2537
2578
  authorize_url: authorizeUrl,
@@ -2540,6 +2581,7 @@ export async function loginWithOAuth(
2540
2581
  // child is holding, and the credential is written before the user is
2541
2582
  // told they are connected.
2542
2583
  hand_off: 'browser_callback',
2584
+ browser_opened: browserOpened,
2543
2585
  confirm_command: confirmCommand(
2544
2586
  runtime.profileName,
2545
2587
  authorizationChannel(metadata, runtime),
@@ -2674,7 +2716,7 @@ function lockIsStale() {
2674
2716
  }
2675
2717
  }
2676
2718
 
2677
- async function acquireRefreshLock(runtime, waitMs = OAUTH_REFRESH_LOCK_WAIT_MS) {
2719
+ async function acquireRefreshLock(runtime, staleAccessToken, waitMs = OAUTH_REFRESH_LOCK_WAIT_MS) {
2678
2720
  mkdirSync(join(homedir(), '.notis'), { recursive: true });
2679
2721
  const deadline = Date.now() + waitMs;
2680
2722
  for (;;) {
@@ -2686,7 +2728,7 @@ async function acquireRefreshLock(runtime, waitMs = OAUTH_REFRESH_LOCK_WAIT_MS)
2686
2728
  const profile = getProfile(loadConfig(), runtime.profileName);
2687
2729
  if (
2688
2730
  profile.oauth_access_token
2689
- && profile.oauth_access_token !== runtime.oauthAccessToken
2731
+ && profile.oauth_access_token !== staleAccessToken
2690
2732
  && !credentialIsExpired({ credentialKind: 'oauth' }, profile)
2691
2733
  ) {
2692
2734
  updateRuntimeFromOAuthProfile(runtime, profile);
@@ -2730,6 +2772,10 @@ export async function refreshOAuthCredential(runtime, fetchImpl = fetch, tokenRe
2730
2772
  // Refresh rotates the same stored grant that login publishes and logout
2731
2773
  // removes. Join their global -> profile lock order so a token rotation can
2732
2774
  // never be mistaken for a successor authorization by a concurrent logout.
2775
+ // The token this caller found unusable. Requests running in parallel in one
2776
+ // process share `runtime`, so the first to finish updates it for all; compare
2777
+ // against what this caller saw, or every waiting request renews once more.
2778
+ const staleAccessToken = runtime.oauthAccessToken;
2733
2779
  const globalLock = await acquireListenerGlobalLock({ waitMs: OAUTH_REFRESH_LOCK_WAIT_MS });
2734
2780
  let profileLock = null;
2735
2781
  let ownsLock = false;
@@ -2737,7 +2783,7 @@ export async function refreshOAuthCredential(runtime, fetchImpl = fetch, tokenRe
2737
2783
  let metadata = null;
2738
2784
  try {
2739
2785
  profileLock = await acquireListenerStartLock(runtime);
2740
- ownsLock = await acquireRefreshLock(runtime);
2786
+ ownsLock = await acquireRefreshLock(runtime, staleAccessToken);
2741
2787
  if (!ownsLock) return true;
2742
2788
  stopTouchingLocks = keepLockFoldersFresh([profileLock, oauthLockDir()]);
2743
2789
  const config = loadConfig();
@@ -2745,7 +2791,7 @@ export async function refreshOAuthCredential(runtime, fetchImpl = fetch, tokenRe
2745
2791
  assertOAuthApiTarget(runtime, profile);
2746
2792
  if (
2747
2793
  profile.oauth_access_token
2748
- && profile.oauth_access_token !== runtime.oauthAccessToken
2794
+ && profile.oauth_access_token !== staleAccessToken
2749
2795
  && !credentialIsExpired({ credentialKind: 'oauth' }, profile)
2750
2796
  ) {
2751
2797
  updateRuntimeFromOAuthProfile(runtime, profile);
@@ -1,7 +1,7 @@
1
1
  import { captureNativeSkillFiles, createSkillBundleBase64 } from './local-scanner';
2
2
  import { createHash } from 'node:crypto';
3
3
  import { checkedNativeReference } from './native-identity';
4
- import type { AgentTargets, LocalSkill, NativeSkillReference, SyncPullResponse, SyncPushResponse, SyncSettings } from './types';
4
+ import type { AgentTargets, LocalSkill, NativeSkillReference, SkillSyncFailure, SyncPullResponse, SyncPushResponse, SyncSettings } from './types';
5
5
 
6
6
  type JsonBody = Record<string, unknown> | undefined;
7
7
 
@@ -22,12 +22,33 @@ async function requestJson<T>(
22
22
 
23
23
  if (!response.ok) {
24
24
  const text = await response.text();
25
- throw new Error(`${options.method || 'POST'} ${url} → ${response.status}: ${text}`);
25
+ throw new SkillSyncHttpError(
26
+ `${options.method || 'POST'} ${url} → ${response.status}: ${text}`,
27
+ response.status,
28
+ response.headers.get('content-type'),
29
+ );
26
30
  }
27
31
 
28
32
  return response.json() as Promise<T>;
29
33
  }
30
34
 
35
+ /**
36
+ * A non-2xx answer, classified so a status can be recorded without its body:
37
+ * `edge_blocked` for an HTML 403 (the edge in front of the API refused the
38
+ * request before it reached Notis), `http_<status>` otherwise.
39
+ */
40
+ export class SkillSyncHttpError extends Error {
41
+ readonly status: number;
42
+ readonly code: string;
43
+
44
+ constructor(message: string, status: number, contentType: string | null) {
45
+ super(message);
46
+ this.name = 'SkillSyncHttpError';
47
+ this.status = status;
48
+ this.code = status === 403 && /text\/html/i.test(contentType || '') ? 'edge_blocked' : `http_${status}`;
49
+ }
50
+ }
51
+
31
52
  export async function fetchSyncSettings(serverUrl: string, jwt: string): Promise<SyncSettings> {
32
53
  return requestJson<SyncSettings>(`${serverUrl}/portal_skills/sync-settings`, jwt, {
33
54
  body: {},
@@ -40,12 +61,11 @@ export async function pullSkills(serverUrl: string, jwt: string): Promise<SyncPu
40
61
  });
41
62
  }
42
63
 
43
- export async function pushChangedSkills(
44
- serverUrl: string,
45
- jwt: string,
46
- changedSkills: LocalSkill[],
47
- ): Promise<SyncPushResponse> {
48
- const payloadSkills = await Promise.all(changedSkills.map(async (skill) => ({
64
+ /** Largest sync-push body sent at once; a single larger skill goes alone. */
65
+ export const MAX_SYNC_PUSH_BODY_BYTES = 2 * 1024 * 1024;
66
+
67
+ async function skillPushPayload(skill: LocalSkill): Promise<Record<string, unknown>> {
68
+ return {
49
69
  name: skill.name,
50
70
  description: skill.description,
51
71
  skill_md: skill.skillMd,
@@ -56,14 +76,77 @@ export async function pushChangedSkills(
56
76
  ...(skill.cloudId ? { cloud_id: skill.cloudId } : {}),
57
77
  ...(skill.nativeReference ? { native_reference: skill.nativeReference, display_name: skill.displayName,
58
78
  native_scope: skill.nativeScope } : {}),
59
- })));
79
+ };
80
+ }
60
81
 
61
- return requestJson<SyncPushResponse>(`${serverUrl}/portal_skills/sync-push`, jwt, {
62
- body: {
63
- skill_sync_protocol: 2,
64
- skills: payloadSkills,
65
- },
66
- });
82
+ /** The request body around the skills array, counted in every batch's size. */
83
+ const SYNC_PUSH_ENVELOPE_BYTES = Buffer.byteLength(JSON.stringify({ skill_sync_protocol: 2, skills: [] }));
84
+
85
+ function pushBatches(payloads: Record<string, unknown>[], maxBodyBytes: number): Record<string, unknown>[][] {
86
+ const batches: Record<string, unknown>[][] = [];
87
+ let batch: Record<string, unknown>[] = [];
88
+ let batchBytes = SYNC_PUSH_ENVELOPE_BYTES;
89
+ for (const payload of payloads) {
90
+ // +1 for the comma between array items.
91
+ const bytes = Buffer.byteLength(JSON.stringify(payload)) + 1;
92
+ if (batch.length > 0 && batchBytes + bytes > maxBodyBytes) {
93
+ batches.push(batch);
94
+ batch = [];
95
+ batchBytes = SYNC_PUSH_ENVELOPE_BYTES;
96
+ }
97
+ batch.push(payload);
98
+ batchBytes += bytes;
99
+ }
100
+ if (batch.length > 0) batches.push(batch);
101
+ return batches;
102
+ }
103
+
104
+ function pushFailure(name: string, error: unknown): SkillSyncFailure {
105
+ if (error instanceof SkillSyncHttpError) {
106
+ return {
107
+ name,
108
+ error: error.code === 'edge_blocked'
109
+ ? `Upload blocked before reaching Notis (HTTP ${error.status}); sync will retry`
110
+ : `Upload failed (HTTP ${error.status}); sync will retry`,
111
+ status: error.status,
112
+ code: error.code,
113
+ };
114
+ }
115
+ const code = typeof (error as { code?: unknown })?.code === 'string' ? (error as { code: string }).code : 'push_failed';
116
+ return { name, error: 'Upload failed; sync will retry', code };
117
+ }
118
+
119
+ /**
120
+ * Push changed skills in bodies of at most `maxBodyBytes` (one skill when it is
121
+ * larger alone). A batch the server or the edge refuses fails only its own skills,
122
+ * recorded with the HTTP status, and the other batches still push.
123
+ */
124
+ export async function pushChangedSkills(
125
+ serverUrl: string,
126
+ jwt: string,
127
+ changedSkills: LocalSkill[],
128
+ options: { maxBodyBytes?: number } = {},
129
+ ): Promise<SyncPushResponse> {
130
+ const payloadSkills = await Promise.all(changedSkills.map(skillPushPayload));
131
+ const saved: unknown[] = [];
132
+ const failed: SkillSyncFailure[] = [];
133
+ for (const batch of pushBatches(payloadSkills, options.maxBodyBytes ?? MAX_SYNC_PUSH_BODY_BYTES)) {
134
+ try {
135
+ const result = await requestJson<SyncPushResponse>(`${serverUrl}/portal_skills/sync-push`, jwt, {
136
+ body: {
137
+ skill_sync_protocol: 2,
138
+ skills: batch,
139
+ },
140
+ });
141
+ saved.push(...(result.skills || []));
142
+ if (Array.isArray(result.failed)) failed.push(...result.failed);
143
+ } catch (error) {
144
+ // A rejected sign-in fails every batch alike: stop and let the sync report it.
145
+ if (error instanceof SkillSyncHttpError && error.status === 401) throw error;
146
+ for (const payload of batch) failed.push(pushFailure(String(payload.name), error));
147
+ }
148
+ }
149
+ return { skills: saved, ...(failed.length ? { failed } : {}) };
67
150
  }
68
151
 
69
152
  export async function downloadSkillBundle(bundleUrl: string): Promise<Buffer> {
@@ -3,6 +3,7 @@ import { promises as fs } from 'node:fs';
3
3
  import { dirname, join } from 'node:path';
4
4
  import type {
5
5
  AgentTargets,
6
+ CloudSkill,
6
7
  LocalSkill,
7
8
  NotisSyncState,
8
9
  SkillSyncFailure,
@@ -39,7 +40,7 @@ import {
39
40
  } from "./symlink-manager";
40
41
  import { getPushCandidates, selectCloudSkillsToApply } from "./sync-plan";
41
42
  import { writeCloudSkillWithBundleFallback } from "./write-cloud-skill";
42
- export { fetchSyncSettings } from './cloud-client';
43
+ export { fetchSyncSettings, pushChangedSkills } from './cloud-client';
43
44
 
44
45
  export interface RunSkillSyncResult {
45
46
  syncEnabled: boolean;
@@ -402,6 +403,25 @@ function buildSyncState(
402
403
  });
403
404
  }
404
405
 
406
+ /**
407
+ * A local edit whose upload failed keeps the previously synced folder hash, so the
408
+ * next sync still sees it as changed and pushes it again instead of recording the
409
+ * unsent edit as synced.
410
+ */
411
+ function keepFailedPushesPending(
412
+ state: NotisSyncState,
413
+ previousState: NotisSyncState,
414
+ failedPushes: readonly SkillSyncFailure[],
415
+ ): NotisSyncState {
416
+ for (const { name } of failedPushes) {
417
+ const row = state.skills[name];
418
+ const previous = previousState.skills[name];
419
+ if (!row || !previous || row.nativeReference || previous.nativeReference) continue;
420
+ state.skills[name] = { ...row, folderHash: previous.folderHash };
421
+ }
422
+ return state;
423
+ }
424
+
405
425
  function buildLocalSymlinkCandidates(
406
426
  pullResponse: SyncPullResponse,
407
427
  localSkills: LocalSkill[],
@@ -467,6 +487,24 @@ function applyLegacyFirstRunState(
467
487
  };
468
488
  }
469
489
 
490
+ /**
491
+ * The files the previous write applied. A native folder whose state row lost that
492
+ * record (state written before it existed, or a row rebuilt while the Skill was
493
+ * unavailable) still names them in its identity marker; when every one of them is
494
+ * unedited they are the previous sync's output, so a newer revision replaces them
495
+ * instead of failing as a local conflict on every sync.
496
+ */
497
+ function previouslyAppliedFiles(
498
+ skill: CloudSkill,
499
+ local: LocalSkill | undefined,
500
+ previousState: NotisSyncState,
501
+ ): readonly string[] | undefined {
502
+ const recorded = previousNativeState(previousState, skill)?.appliedFiles;
503
+ if (recorded || !isNativeSkill(skill) || !local?.nativeManagedFiles) return recorded;
504
+ return local.nativeFilesCurrent === true && local.cloudId === skill.id
505
+ && local.folderHash === local.nativeBaseFolderHash ? local.nativeManagedFiles : undefined;
506
+ }
507
+
470
508
  async function writePulledSkillsToScopedMirror(
471
509
  pullResponse: SyncPullResponse,
472
510
  localSkills: LocalSkill[],
@@ -507,7 +545,7 @@ async function writePulledSkillsToScopedMirror(
507
545
  deps.writeCloudSkillToDisk(skill, bundleBytes, syncPaths, {
508
546
  // What the last write put there. Everything else in the folder was
509
547
  // produced locally and survives this one.
510
- previouslyApplied: previousNativeState(previousState, skill)?.appliedFiles,
548
+ previouslyApplied: previouslyAppliedFiles(skill, local, previousState),
511
549
  ...(isNativeSkill(skill) && local ? { expectedFolderHash: local.folderHash } : {}),
512
550
  ...(legacyBaseline ? { legacyBaseline } : {}),
513
551
  }),
@@ -949,7 +987,7 @@ export async function runSkillSync(
949
987
  const lastSyncedAt = pullResponse.last_synced_at || new Date().toISOString();
950
988
 
951
989
  await deps.writeSyncState(
952
- buildSyncState(
990
+ keepFailedPushesPending(buildSyncState(
953
991
  pullResponse,
954
992
  finalLocalSkills,
955
993
  lastSyncedAt,
@@ -958,7 +996,7 @@ export async function runSkillSync(
958
996
  collectAppliedCloudRevisions(pullResponse, previousState, writtenSkillNames),
959
997
  collectAppliedFiles(pullResponse, previousState, appliedFilesByName),
960
998
  previousState,
961
- ),
999
+ ), previousState, failedPushes),
962
1000
  syncPaths,
963
1001
  );
964
1002
 
@@ -752,6 +752,7 @@ export async function scanLocalSkills(
752
752
  const editedName = nativeFrontmatterName(skillMd);
753
753
  Object.assign(skill, { cloudId: identity.cloudId, nativeReference: identity.reference,
754
754
  nativeScope: identity.scope, nativeBaseFolderHash: identity.folderHash, nativeFilesCurrent: current,
755
+ nativeManagedFiles: [...Object.keys(identity.files), NATIVE_IDENTITY_FILE].sort(),
755
756
  displayName: editedName && editedName !== identity.frontmatterName ? editedName : identity.displayName });
756
757
  }
757
758
  if (sourceUrls[entry.name]) {
@@ -68,6 +68,8 @@ export interface LocalSkill {
68
68
  nativeScope?: string;
69
69
  nativeFilesCurrent?: boolean;
70
70
  nativeBaseFolderHash?: string;
71
+ /** Every file the identity marker says the last native write applied, the marker included. */
72
+ nativeManagedFiles?: string[];
71
73
  }
72
74
 
73
75
  export interface BundleFile {
@@ -133,6 +135,10 @@ export interface SyncPullResponse {
133
135
  export interface SkillSyncFailure {
134
136
  name: string;
135
137
  error: string;
138
+ /** HTTP status of a refused upload, when the push itself was answered non-2xx. */
139
+ status?: number;
140
+ /** Classified cause (e.g. `edge_blocked`, `http_413`); never a response body. */
141
+ code?: string;
136
142
  }
137
143
 
138
144
  export interface SyncPushResponse {
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Editor-only parts of a Space (truths SPC-069 to SPC-074). A source marks the whole view, a list
3
+ * (`shows`), an action or a param with `editorsOnly: true`, and a database column with
4
+ * `resources[alias].columns: { Column: { editorsOnly: true } }`. Unmarked parts are public.
5
+ *
6
+ * The manifest never carries the markers on the items it copies: it carries one top-level
7
+ * `editors_only` summary instead (absent when nothing is marked, so unmarked manifests stay
8
+ * byte-identical). server/lib/space_audience.py re-checks it on every release.
9
+ */
10
+ import { usageError } from './errors.js';
11
+
12
+ const plain = value => Boolean(value) && typeof value === 'object' && !Array.isArray(value);
13
+ // Python's casefold, closely enough for property names (as space-view-manifest.js matches them).
14
+ const fold = value => String(value).toUpperCase().toLowerCase();
15
+
16
+ /** Whether `value` marks a part editor-only: absent is public, the literal true is editors only. */
17
+ export function editorsOnlyFlag(value, where) {
18
+ if (value === undefined) return false;
19
+ if (value !== true) throw usageError(`${where}: editorsOnly is true, or left out for a part the public sees.`);
20
+ return true;
21
+ }
22
+
23
+ /** A copy without the editorsOnly marker, so the manifest item reads exactly as an unmarked one. */
24
+ export function withoutMarker(value) {
25
+ if (!plain(value) || !Object.hasOwn(value, 'editorsOnly')) return value;
26
+ const { editorsOnly, ...rest } = value;
27
+ return rest;
28
+ }
29
+
30
+ /**
31
+ * The editor-only column names of one database resource (`columns`), checked against the schema of a
32
+ * database the same release creates. A linked database's schema is checked on the server at verify and deploy.
33
+ */
34
+ export function editorOnlyColumns(alias, resource) {
35
+ if (!plain(resource) || resource.columns === undefined) return [];
36
+ const columns = resource.columns;
37
+ if (resource.kind !== 'database') throw usageError(`Resource ${alias}: only a database declares editor-only columns.`);
38
+ if (!plain(columns) || !Object.keys(columns).length || Object.keys(columns).length > 200) {
39
+ throw usageError(`Database ${alias}: declare columns as { Column: { editorsOnly: true } }, naming at least one property.`);
40
+ }
41
+ const schema = resource.create?.schema;
42
+ const properties = plain(schema?.properties) ? Object.entries(schema.properties).filter(([, prop]) => plain(prop)) : null;
43
+ for (const [name, marker] of Object.entries(columns)) {
44
+ if (!name.trim() || name.length > 200) throw usageError(`Database ${alias}: a column names a property of 1 to 200 characters.`);
45
+ if (!plain(marker) || Object.keys(marker).join(',') !== 'editorsOnly' || marker.editorsOnly !== true) {
46
+ throw usageError(`Database ${alias}: column "${name}" is { editorsOnly: true }.`);
47
+ }
48
+ if (properties && !properties.some(([key, prop]) => key === name || fold(prop.name ?? key) === fold(name))) {
49
+ throw usageError(`Database ${alias}: "${name}" is not a property of the database this Space creates.`);
50
+ }
51
+ }
52
+ return Object.keys(columns).sort();
53
+ }
54
+
55
+ /** The resources as the manifest carries them: without their `columns` markers. */
56
+ export function manifestResources(resources) {
57
+ return Object.fromEntries(Object.entries(resources || {}).map(([alias, resource]) => {
58
+ if (!plain(resource) || !Object.hasOwn(resource, 'columns')) return [alias, resource];
59
+ const { columns, ...rest } = resource;
60
+ return [alias, rest];
61
+ }));
62
+ }
63
+
64
+ /** The actions as the manifest (and so the release) carries them: without their editorsOnly markers. */
65
+ export function manifestActions(actions) {
66
+ return Object.fromEntries(Object.entries(actions || {}).map(([id, template]) => [id, withoutMarker(template)]));
67
+ }
68
+
69
+ /** The view's params or shows as the manifest carries them: without their editorsOnly markers. */
70
+ export function manifestDeclarations(declarations) {
71
+ return Object.fromEntries(Object.entries(declarations).map(([name, value]) => [name, withoutMarker(value)]));
72
+ }
73
+
74
+ const marked = items => Object.entries(items || {}).filter(([, value]) => plain(value) && value.editorsOnly === true)
75
+ .map(([name]) => name).sort();
76
+
77
+ /**
78
+ * The one `editors_only` manifest key: `{ view?, shows?, actions?, params?, columns? }`, sorted and
79
+ * without empty members, or undefined when nothing is editor-only. The markers are validated where
80
+ * each part is (space-source.js and space-view-manifest.js).
81
+ */
82
+ export function editorsOnlySummary(definition) {
83
+ const columns = Object.fromEntries(Object.entries(definition.resources || {})
84
+ .map(([alias, resource]) => [alias, plain(resource?.columns) ? Object.keys(resource.columns).sort() : []])
85
+ .filter(([, names]) => names.length).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0)));
86
+ const summary = {
87
+ ...(definition.editorsOnly === true ? { view: true } : {}),
88
+ ...(marked(definition.shows).length ? { shows: marked(definition.shows) } : {}),
89
+ ...(marked(definition.actions).length ? { actions: marked(definition.actions) } : {}),
90
+ ...(marked(definition.params).length ? { params: marked(definition.params) } : {}),
91
+ ...(Object.keys(columns).length ? { columns } : {}),
92
+ };
93
+ return Object.keys(summary).length ? summary : undefined;
94
+ }
@@ -15,7 +15,8 @@ export async function scaffoldSpaceCollection({ projectDir, name, databaseKey, p
15
15
  mkdirSync(join(projectDir, 'spaces', 'collection'), { recursive: true });
16
16
  writeFileSync(join(projectDir, 'notis.config.ts'), `import { defineSpaces } from '@notis/sdk/config';
17
17
  export default defineSpaces({ spaces: { collection: { definition: 'spaces/collection/space.config.ts' } } });\n`);
18
- const definition = { specVersion: 2, name, description: `Browse and edit ${name} records.`, path, entry: './view.tsx', layout: '../../app/layout.tsx',
18
+ // icon stays empty until the agent picks one (phosphor:<kebab-name>): deploy refuses an empty icon.
19
+ const definition = { specVersion: 2, name, description: `Browse and edit ${name} records.`, icon: '', path, entry: './view.tsx', layout: '../../app/layout.tsx',
19
20
  readableContext: `Browse ${name} records. The item parameter opens one record with its properties, collaborative body and sharing controls.`,
20
21
  verificationFixtures: './verification.json',
21
22
  resources: { [databaseKey]: { kind: 'database', key: databaseKey } },
@@ -6,7 +6,7 @@ const object = value => value && typeof value === 'object' && !Array.isArray(val
6
6
  const exact = (value, keys) => object(value) && Object.keys(value).sort().join(',') === [...keys].sort().join(',');
7
7
 
8
8
  export function createSpaceFixtureBroker({ release, capabilities, width, outputs = ['markdown', 'screenshot'],
9
- authorizationMode = 'authorize_missing', unavailableActions = [] }) {
9
+ authorizationMode = 'authorize_missing', unavailableActions = [], onFailure }) {
10
10
  const engine = createSpaceFixtureEngine(release);
11
11
  const frozen = spaceHarnessSnapshot(release, capabilities, engine, { authorizationMode, unavailableActions });
12
12
  const calls = [];
@@ -33,6 +33,7 @@ export function createSpaceFixtureBroker({ release, capabilities, width, outputs
33
33
  } catch (error) {
34
34
  // Keep the reason with the call so verify reports which read failed and what the fixture lacks.
35
35
  log.error = String(error?.message || error).slice(0, 2000);
36
+ onFailure?.(log);
36
37
  throw error;
37
38
  }
38
39
  log.ok = true;
@@ -317,7 +317,7 @@ export function applyPublication({ lock, folders, result }) {
317
317
  return { lock: next, resources: resourceEntries(applied.space_links || []) };
318
318
  }
319
319
 
320
- /** One line describing what a deploy changed, with the review link of every changed Skill. */
320
+ /** One line describing what a deploy changed. */
321
321
  export function describeAppliedChanges(result) {
322
322
  const applied = result?.applied;
323
323
  if (!applied) return '';
@@ -330,8 +330,5 @@ export function describeAppliedChanges(result) {
330
330
  const removed = (applied.links || []).flatMap((link) => (link.removed || []).map((entry) => `${entry.alias} (${link.kind})`));
331
331
  if (added.length) parts.push(`Links added: ${added.join(', ')}`);
332
332
  if (removed.length) parts.push(`Links removed: ${removed.join(', ')}`);
333
- for (const review of result.reviews || []) {
334
- if (review.review_url) parts.push(`Review ${review.alias}: ${review.review_url}`);
335
- }
336
333
  return parts.length ? ` ${parts.join('. ')}.` : '';
337
334
  }