@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
@@ -0,0 +1,66 @@
1
+ /**
2
+ * A Space workspace builds with its own packages (TypeScript, Vite, Tailwind, React, the SDK). A folder that
3
+ * has never been installed (a copy, a fresh clone, a scaffold) gets them on its first `notis spaces build`:
4
+ * `npm ci` from its lock file, `--prefer-offline` so every package this machine has already downloaded for
5
+ * another Space comes from npm's shared cache instead of the network. A workspace that is already installed
6
+ * is never touched.
7
+ */
8
+ import { spawnSync } from 'node:child_process';
9
+ import { existsSync } from 'node:fs';
10
+ import { createRequire } from 'node:module';
11
+ import { join } from 'node:path';
12
+ import { usageError } from './errors.js';
13
+ import { npmFailureReason } from './app-platform.js';
14
+
15
+ const INSTALL_TIMEOUT_MS = 10 * 60_000;
16
+ // --include=dev: a build needs the devDependencies (TypeScript, Vite, Tailwind) even under NODE_ENV=production or omit=dev.
17
+ const INSTALL_FLAGS = Object.freeze(['--include=dev', '--prefer-offline', '--no-audit', '--no-fund']);
18
+
19
+ /**
20
+ * True when the package a build loads first resolves from this workspace, the way the build resolves it:
21
+ * from its own node_modules or an ancestor's (an npm workspace member installed at the root).
22
+ */
23
+ export function spaceDependenciesInstalled(projectDir) {
24
+ const require = createRequire(join(projectDir, 'package.json'));
25
+ try { require.resolve('typescript/package.json'); return true; } catch { return false; }
26
+ }
27
+
28
+ function runNpm(args, projectDir) {
29
+ // A verbose npm config can print more than spawnSync's 1 MB default before it finishes.
30
+ return spawnSync('npm', args, { cwd: projectDir, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 64 * 1024 * 1024,
31
+ timeout: INSTALL_TIMEOUT_MS, shell: process.platform === 'win32' });
32
+ }
33
+
34
+ /**
35
+ * Install this workspace's packages when it has none yet. Returns what it did, for the build answer:
36
+ * `null` when nothing was needed, else `{ command, seconds }`.
37
+ */
38
+ export function ensureSpaceDependencies(projectDir, { log = () => {}, run = runNpm } = {}) {
39
+ if (!existsSync(join(projectDir, 'package.json')) || spaceDependenciesInstalled(projectDir)) return null;
40
+ const locked = existsSync(join(projectDir, 'package-lock.json'));
41
+ let args = [locked ? 'ci' : 'install', ...INSTALL_FLAGS];
42
+ let command = `npm ${args.join(' ')}`;
43
+ log(`This Space folder has no installed packages yet: running ${command} once (packages this machine already has come from npm's cache).`);
44
+ const started = Date.now();
45
+ let result = run(args, projectDir);
46
+ if (locked && result.status !== 0 && !result.error && /in sync/i.test(`${result.stderr || ''}\n${result.stdout || ''}`)) {
47
+ // package.json gained a package its lock file does not hold yet: npm install records it instead of refusing.
48
+ args = ['install', ...INSTALL_FLAGS];
49
+ command = `npm ${args.join(' ')}`;
50
+ log(`package-lock.json does not match package.json yet: running ${command} instead.`);
51
+ result = run(args, projectDir);
52
+ }
53
+ const seconds = Math.round((Date.now() - started) / 100) / 10;
54
+ if (result.error || result.status !== 0) {
55
+ const reason = result.error?.code === 'ETIMEDOUT' ? 'it did not finish within 10 minutes'
56
+ : result.error?.code === 'ENOENT' ? 'npm is not installed on this machine'
57
+ : npmFailureReason(`${result.stderr || ''}\n${result.stdout || ''}`) || `npm exited with code ${result.status}`;
58
+ throw usageError(`Installing this Space's packages failed (${command}: ${reason}). Nothing was built. `
59
+ + `Fix that, or run ${command} in ${projectDir} yourself, then build again.`);
60
+ }
61
+ if (!spaceDependenciesInstalled(projectDir)) {
62
+ throw usageError(`${command} finished but TypeScript is still missing from this Space's packages. Add typescript to its devDependencies, then build again.`);
63
+ }
64
+ log(`Installed this Space's packages in ${seconds} s.`);
65
+ return { command, seconds };
66
+ }
@@ -1,5 +1,5 @@
1
1
  /** Pure fixture adapter for the exact CLI/service renderer; no network client. */
2
- import { createSpaceFixtureEngine, spaceHarnessSnapshot } from './space-test-server.js';
2
+ import { createSpaceFixtureEngine, selectedFixtureContext, spaceHarnessSnapshot } from './space-test-server.js';
3
3
  import { usageError } from './errors.js';
4
4
 
5
5
  const object = value => value && typeof value === 'object' && !Array.isArray(value);
@@ -21,25 +21,38 @@ export function fixtureSkeletonParams(release) {
21
21
  }
22
22
 
23
23
  /**
24
- * `audience: 'public'` draws the view as the public sees it: the editor's descriptor with View as the public on, so
24
+ * The fixture contexts verify opens the view in, in order: `[{ name, params, open }]` (`open`: the params open a list
25
+ * item through ListReader's default `open` param). Unreadable fixtures give none; verify reports them on its own.
26
+ */
27
+ export function fixtureContexts(release) {
28
+ let engine;
29
+ try { engine = createSpaceFixtureEngine(release); } catch { return []; }
30
+ return engine.contexts.map(({ name, context }) => ({ name, params: structuredClone(context.params || {}),
31
+ open: typeof context.params?.open === 'string' && context.params.open.length > 0 }));
32
+ }
33
+
34
+ /**
35
+ * `context` names the fixture context to open the view with (default: the first). `audience: 'public'` draws the view as the public sees it: the editor's descriptor with View as the public on, so
25
36
  * the page applies the public floors itself (no editor-only lists, actions, params or columns), as in the Portal.
26
37
  */
27
38
  export function createSpaceFixtureBroker({ release, capabilities, width, outputs = ['markdown', 'screenshot'],
28
- authorizationMode = 'authorize_missing', unavailableActions = [], onFailure, params: paramsOverride, audience = 'editor' }) {
39
+ authorizationMode = 'authorize_missing', unavailableActions = [], onFailure, params: paramsOverride, audience = 'editor', context: contextName }) {
29
40
  const engine = createSpaceFixtureEngine(release);
30
- const frozen = spaceHarnessSnapshot(release, capabilities, engine, { authorizationMode, unavailableActions });
41
+ const selected = selectedFixtureContext(engine, contextName).context;
42
+ const frozen = spaceHarnessSnapshot(release, capabilities, engine, { authorizationMode, unavailableActions, context: contextName });
31
43
  if (audience === 'public') frozen.descriptor.space.viewAs = 'public';
32
44
  const calls = [];
33
45
  // 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 || {}) });
46
+ const params = structuredClone({ ...(selected.params || {}), ...(paramsOverride || {}) });
35
47
  // The fixture's own "now" pins the browser clock, so a view that asks for the
36
48
  // last hour sends the exact inputs its fixtures recorded.
37
- const now = engine.context.now;
49
+ const now = selected.now;
38
50
  const fixedClock = typeof now === 'string' && Number.isFinite(Date.parse(now)) ? { fixed_clock: now } : {};
39
51
  const value = { ...frozen, url: `https://app.notis.ai/verification/${encodeURIComponent(release.manifest.local_key)}`,
40
52
  view: { space_id: frozen.descriptor.resource.id, name: release.manifest.name, revision: 1 },
41
- locale: engine.context.locale === 'fr' ? 'fr' : 'en', params,
42
- markdownExport: release.manifest.markdown?.export_name || null, render_options: { outputs, width }, ...fixedClock };
53
+ locale: selected.locale === 'fr' ? 'fr' : 'en', params,
54
+ markdownExport: release.manifest.markdown?.export_name || null, render_options: { outputs, width }, ...fixedClock,
55
+ asset_images: [...engine.imageUrls] };
43
56
  return {
44
57
  fixtureDigest: engine.digest,
45
58
  calls,
@@ -80,6 +93,8 @@ export function createSpaceFixtureBroker({ release, capabilities, width, outputs
80
93
  } else if (request?.operation === 'document_body' && exact(request, ['operation', 'record_key', 'binding', 'read_action'])) {
81
94
  if (frozen.descriptor.space.actions[request.read_action]?.readOnly !== true) throw usageError('This document read action is unavailable.');
82
95
  result = engine.executeBody({ operation: 'read', recordKey: request.record_key, binding: request.binding, readAction: request.read_action });
96
+ } else if (request?.operation === 'asset' && exact(request, ['operation', 'url', 'kind']) && request.kind === 'image') {
97
+ result = engine.executeImage(request.url);
83
98
  } else if (['record', 'html', 'report'].includes(request?.operation) && exact(request, ['operation', 'record_key'])) {
84
99
  result = engine.executeRecordView(request.operation, request.record_key);
85
100
  } else {
@@ -8,6 +8,7 @@ import { viewManifestFields } from './space-view-manifest.js';
8
8
  import { editorsOnlySummary, manifestActions, manifestResources } from './space-audience.js';
9
9
  import { usageError } from './errors.js';
10
10
  import { assertSourceRoot } from './source-root.js';
11
+ import { ensureSpaceDependencies } from './space-dependencies.js';
11
12
 
12
13
  const SPACE_ICON = /^(phosphor:[a-z0-9]+(-[a-z0-9]+)*|https:\/\/\S{1,2000})$/;
13
14
 
@@ -32,6 +33,8 @@ export function generateSpaceManifest(selection) {
32
33
  ...(definition.cloudComputer ? { cloud_computer: definition.cloudComputer } : {}),
33
34
  // Agents its database changes wake; absent when undeclared.
34
35
  ...(definition.agents?.length ? { agents: definition.agents } : {}),
36
+ // Live items agents attach to threads; absent when undeclared.
37
+ ...(definition.threadItems && Object.keys(definition.threadItems).length ? { thread_items: definition.threadItems } : {}),
35
38
  // Absent when nothing is editor-only (SPC-073: unmarked means public).
36
39
  ...(editorsOnly ? { editors_only: editorsOnly } : {}),
37
40
  readable_context: definition.readableContext || '', collection: definition.collection || null,
@@ -100,9 +103,12 @@ function finalizeSelectedArtifact(projectDir) {
100
103
  * dependencies; it is not another authoring project or dependency installation.
101
104
  * The existing pinned freeze/receipt code owns all staging writes and cleanup.
102
105
  */
103
- export async function buildSpaceRelease(projectDir, selectedKey, { stdio = 'inherit', refreshSdk = true, runBuild, designBar = 'enforce', designLog = null } = {}) {
106
+ export async function buildSpaceRelease(projectDir, selectedKey, { stdio = 'inherit', refreshSdk = true, runBuild, designBar = 'enforce', designLog = null,
107
+ installDependencies = false, installLog } = {}) {
104
108
  projectDir = assertSourceRoot(projectDir);
105
109
  if (refreshSdk) syncSpaceSdk(projectDir);
110
+ // After the SDK sync, so the install follows the lock file that sync keeps in step with the SDK.
111
+ const installed = installDependencies ? ensureSpaceDependencies(projectDir, { log: installLog }) : null;
106
112
  const selection = await loadSelectedSpace(projectDir, selectedKey);
107
113
  const sourceFiles = collectSelectedSpaceSource(projectDir, selection);
108
114
  const sourceHash = appFilesDigest(sourceFiles);
@@ -120,7 +126,8 @@ export async function buildSpaceRelease(projectDir, selectedKey, { stdio = 'inhe
120
126
  if (sourceHash !== appFilesDigest(collectSelectedSpaceSource(projectDir, current))) throw usageError('This Space source changed during the selected build. Build again.');
121
127
  release = prepareAppRelease(staging.projectDir);
122
128
  const close = release.close;
123
- return { ...release, selectedKey, sourceHash, fixturePath: selection.fixturePath, close() { try { close(); } finally { staging.close(); } } };
129
+ return { ...release, selectedKey, sourceHash, fixturePath: selection.fixturePath, ...(installed ? { installed } : {}),
130
+ close() { try { close(); } finally { staging.close(); } } };
124
131
  } catch (error) {
125
132
  try { release?.close(); } finally { staging.close(); }
126
133
  throw error;
@@ -131,10 +138,49 @@ export async function buildSpaceArtifact(projectDir, selectedKey, options) {
131
138
  const release = await buildSpaceRelease(projectDir, selectedKey, options);
132
139
  try {
133
140
  const receiptPath = saveSelectedBuild(projectDir, selectedKey, release);
134
- return { manifest: release.manifest, receiptPath, sourceHash: release.sourceHash };
141
+ return { manifest: release.manifest, receiptPath, sourceHash: release.sourceHash, ...(release.installed ? { installed_dependencies: release.installed } : {}) };
135
142
  } finally { release.close(); }
136
143
  }
137
144
 
145
+ const SQL_READ_HEADER = /^\/\* notis-postgres-read-v\d+ \*\/\n/;
146
+
147
+ /** Declared actions whose query starts with a SQL read header line (the server's requests_read). */
148
+ export function sqlReadActions(manifest) {
149
+ return Object.fromEntries(Object.entries(manifest?.actions || {}).filter(([, template]) => {
150
+ let query = template?.arguments?.query;
151
+ if (query && typeof query === 'object') query = query.$literal ?? query.$sql?.parts?.[0];
152
+ return typeof query === 'string' && SQL_READ_HEADER.test(query);
153
+ }));
154
+ }
155
+
156
+ /**
157
+ * Check every declared SQL read with the server's compiler before verification. A compiled read
158
+ * passes unchanged; a header line and plain SELECT joins the release compiled, in memory only, so
159
+ * the source keeps the plain query and each build compiles it to the same bytes. A refused read
160
+ * stops here with the compiler's reason.
161
+ */
162
+ export async function compileSpaceSqlReads(release, call) {
163
+ const actions = sqlReadActions(release.manifest);
164
+ if (!Object.keys(actions).length) return [];
165
+ let response;
166
+ try { response = await call('sql-reads', { actions }); }
167
+ catch (error) {
168
+ // A server from before this check: compiled reads go on to its own verification.
169
+ if (error?.httpStatus !== 404) throw error;
170
+ const plain = Object.values(actions).filter(template => !JSON.stringify(template.arguments.query).includes('/* guarded-relations:'));
171
+ if (!plain.length) return [];
172
+ throw usageError('This Notis server cannot compile SQL reads yet. Write each read compiled, or verify against a newer server.');
173
+ }
174
+ const compiled = response.payload?.actions || {};
175
+ const names = Object.keys(compiled).filter(name => Object.hasOwn(actions, name));
176
+ if (!names.length) return [];
177
+ const manifest = { ...release.manifest, actions: { ...release.manifest.actions } };
178
+ for (const name of names) manifest.actions[name] = compiled[name];
179
+ release.manifest = manifest;
180
+ release.files = { ...release.files, 'manifest.json': Buffer.from(JSON.stringify(manifest, null, 2), 'utf8').toString('base64') };
181
+ return names;
182
+ }
183
+
138
184
  export async function prepareSpaceRelease(projectDir, selectedKey) {
139
185
  const selection = await loadSelectedSpace(projectDir, selectedKey);
140
186
  const source = collectSelectedSpaceSource(projectDir, selection);
@@ -4,10 +4,11 @@ import { realpathSync } from 'node:fs';
4
4
  import { dirname, extname, join, relative, resolve, sep } from 'node:path';
5
5
  import { collectSourceFiles, loadAppConfig } from './app-platform.js';
6
6
  import { usageError } from './errors.js';
7
+ import { fixtureImageEntries } from './space-test-server.js';
7
8
  import { VIEW_DEFINITION_FIELDS, viewManifestFields } from './space-view-manifest.js';
8
9
  import { editorOnlyColumns, editorsOnlyFlag, withoutMarker } from './space-audience.js';
9
10
 
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]);
11
+ 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
12
  /** Reads with each signed-in viewer's own authority (never an issuer grant); see docs/notis-spaces-platform.md. */
12
13
  export const VIEWER_READ_FAMILIES = Object.freeze(['databases', 'skills']);
13
14
  const WORKSPACE_INDEXES = new Set(['notis.config.ts', 'notis.config.js', 'notis.config.mjs']);
@@ -226,6 +227,7 @@ export async function loadSelectedSpace(projectDir, selectedKey) {
226
227
  if (definition.cloudComputer != null) validateCloudComputer(definition.cloudComputer);
227
228
  if (definition.cloudComputer != null && !entry) throw usageError('A container has no page, so it cannot use the cloud computer.');
228
229
  if (definition.agents != null) validateSpaceAgents(definition.agents, resources);
230
+ if (definition.threadItems != null) validateThreadItems(definition.threadItems, definition.actions || {});
229
231
  if (definition.collection && (resources[definition.collection.database]?.kind !== 'database' || !definition.collection.titleProperty)) {
230
232
  throw usageError('A collection needs a declared database binding and title property.');
231
233
  }
@@ -307,7 +309,15 @@ export function collectSelectedSpaceSource(projectDir, selection, { buildInputs
307
309
  if (selection.entry) add(selection.entry);
308
310
  if (selection.layout) add(selection.layout);
309
311
  if (selection.markdown) add(selection.markdown);
310
- if (selection.fixturePath) add(selection.fixturePath);
312
+ if (selection.fixturePath) {
313
+ add(selection.fixturePath);
314
+ // The image files the fixtures show travel with them; verify reports a bad entry on its own.
315
+ let fixtures;
316
+ try { fixtures = JSON.parse(Buffer.from(files[selection.fixturePath], 'base64').toString('utf8')); } catch { fixtures = null; }
317
+ let images = [];
318
+ try { images = fixtureImageEntries(fixtures, selection.fixturePath); } catch { /* Reported by verify. */ }
319
+ for (const { path } of images) if (Object.hasOwn(files, path)) try { add(path); } catch { /* Verify names the file it cannot use. */ }
320
+ }
311
321
  for (const include of selection.definition.sourceIncludes || []) {
312
322
  const path = selection.resolveDefinitionPath(include);
313
323
  const matches = Object.keys(files).filter(name => name === path || name.startsWith(path + '/'));
@@ -386,3 +396,67 @@ export function validateSpaceAgents(agents, resources = {}) {
386
396
  }
387
397
  }
388
398
  }
399
+
400
+ const THREAD_ITEM_FIELDS = ['label', 'description', 'inputs', 'read', 'title', 'url', 'states', 'checks', 'actions', 'page'];
401
+ const THREAD_ITEM_STATE_FIELDS = ['id', 'label', 'icon', 'when', 'needsYou', 'final'];
402
+ const THREAD_ITEM_ACTION_FIELDS = ['label', 'tool', 'arguments', 'confirm', 'states', 'primary'];
403
+ const REFUSED_ITEM_TOOL = /^(LOCAL_|COMPOSIO_|NOTIS_|CUSTOM_|MCP_)/;
404
+
405
+ function threadItemLabel(value) {
406
+ if (typeof value === 'string') return value.trim().length > 0;
407
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value) && typeof value.en === 'string' && value.en.trim().length > 0
408
+ && Object.keys(value).every(name => ['en', 'fr'].includes(name) && typeof value[name] === 'string' && value[name].trim());
409
+ }
410
+
411
+ /**
412
+ * The live item kinds agents attach to threads (`threadItems`). The shape is checked here so a
413
+ * mistake fails before the build; server/lib/space_thread_items.py repeats every check, including
414
+ * placeholders and conditions, when the Space is published.
415
+ */
416
+ export function validateThreadItems(threadItems, actions = {}) {
417
+ const kinds = threadItems && typeof threadItems === 'object' && !Array.isArray(threadItems) ? Object.entries(threadItems) : null;
418
+ if (!kinds || kinds.length < 1 || kinds.length > 8) throw usageError('Declare threadItems as 1 to 8 item kinds.');
419
+ for (const [kind, spec] of kinds) {
420
+ if (!/^[a-z][a-z0-9_]{0,39}$/.test(kind)) throw usageError('Each thread item kind needs a short id: lowercase letters, digits and _.');
421
+ if (!spec || typeof spec !== 'object' || Array.isArray(spec) || Object.keys(spec).some(name => !THREAD_ITEM_FIELDS.includes(name))) {
422
+ throw usageError(`Thread item ${kind} takes ${THREAD_ITEM_FIELDS.join(', ')} only.`);
423
+ }
424
+ if (!threadItemLabel(spec.label)) throw usageError(`Thread item ${kind} needs a label.`);
425
+ if (spec.inputs?.type !== 'object' || spec.inputs?.additionalProperties !== false || !spec.inputs.properties
426
+ || !Array.isArray(spec.inputs.required) || !spec.inputs.required.length) {
427
+ throw usageError(`Thread item ${kind} declares its inputs as a closed object with the fields an agent must give in required.`);
428
+ }
429
+ if (!spec.read || typeof spec.read.action !== 'string' || !Object.hasOwn(actions, spec.read.action)) {
430
+ throw usageError(`Thread item ${kind} reads through one of this Space's actions: read: { action: '<id>' }.`);
431
+ }
432
+ if (typeof spec.title !== 'string' && !threadItemLabel(spec.title)) throw usageError(`Thread item ${kind} needs a title template.`);
433
+ if (!Array.isArray(spec.states) || spec.states.length < 1 || spec.states.length > 12) {
434
+ throw usageError(`Thread item ${kind} lists 1 to 12 states in the order they are checked.`);
435
+ }
436
+ const stateIds = new Set();
437
+ for (const state of spec.states) {
438
+ if (!state || typeof state !== 'object' || Object.keys(state).some(name => !THREAD_ITEM_STATE_FIELDS.includes(name))
439
+ || typeof state.id !== 'string' || !/^[a-z][a-z0-9_-]{0,39}$/.test(state.id) || stateIds.has(state.id)) {
440
+ throw usageError(`Each state of thread item ${kind} has its own id and takes ${THREAD_ITEM_STATE_FIELDS.join(', ')} only.`);
441
+ }
442
+ stateIds.add(state.id);
443
+ if (!threadItemLabel(state.label)) throw usageError(`State ${state.id} of thread item ${kind} needs a label.`);
444
+ if (typeof state.icon !== 'string' || !/^phosphor:[a-z0-9]+(-[a-z0-9]+)*$/.test(state.icon)) {
445
+ throw usageError(`State ${state.id} of thread item ${kind} needs a Phosphor icon, written phosphor:<name>.`);
446
+ }
447
+ }
448
+ 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.`);
449
+ for (const [actionId, action] of Object.entries(spec.actions || {})) {
450
+ if (!action || typeof action !== 'object' || Object.keys(action).some(name => !THREAD_ITEM_ACTION_FIELDS.includes(name))) {
451
+ throw usageError(`Action ${actionId} of thread item ${kind} takes ${THREAD_ITEM_ACTION_FIELDS.join(', ')} only.`);
452
+ }
453
+ if (!threadItemLabel(action.label)) throw usageError(`Action ${actionId} of thread item ${kind} needs a label.`);
454
+ if (typeof action.tool !== 'string' || !/^[A-Z][A-Z0-9]*(_[A-Z0-9]+)+$/.test(action.tool) || REFUSED_ITEM_TOOL.test(action.tool)) {
455
+ throw usageError(`Action ${actionId} of thread item ${kind} runs one connected app tool, such as GITHUB_MERGE_A_PULL_REQUEST.`);
456
+ }
457
+ if (action.states != null && (!Array.isArray(action.states) || action.states.some(id => !stateIds.has(id)))) {
458
+ throw usageError(`Action ${actionId} of thread item ${kind} lists states this item declares.`);
459
+ }
460
+ }
461
+ }
462
+ }
@@ -2,12 +2,12 @@
2
2
  import { createHash } from 'node:crypto';
3
3
  import { readFileSync } from 'node:fs';
4
4
  import { createServer } from 'node:http';
5
- import { dirname, join, resolve } from 'node:path';
5
+ import { dirname, extname, join, posix, resolve } from 'node:path';
6
6
  import { isDeepStrictEqual } from 'node:util';
7
7
  import { fileURLToPath } from 'node:url';
8
8
  import Ajv2020 from 'ajv/dist/2020.js';
9
9
  import addFormats from 'ajv-formats';
10
- import { appFilesDigest } from './app-platform.js';
10
+ import { appFilesDigest, VERIFY_CONTEXT_NAME } from './app-platform.js';
11
11
  import { usageError } from './errors.js';
12
12
 
13
13
  const ROOT=resolve(dirname(fileURLToPath(import.meta.url)),'../..');
@@ -58,8 +58,100 @@ function recordViewExample(operation,key) {
58
58
  }[operation];
59
59
  return JSON.stringify({operation,record_key:key,result});
60
60
  }
61
+ const FIXTURE_CONTEXTS_MAX=4;
62
+ /**
63
+ * View params a fixture opens the view with: a flat object, as a link carries them. Numbers and true or false are
64
+ * kept (the host passes every param as text, as it always did); nested values are refused.
65
+ */
66
+ function checkContextFields(value,where) {
67
+ if(value.params!==undefined && (!object(value.params) || Object.values(value.params).some(item=>!['string','number','boolean'].includes(typeof item)))) {
68
+ throw usageError(`${where} params must be an object of text, number or true/false values, as a link carries them (for example {"period": "week"}).`);
69
+ }
70
+ if(value.now!==undefined && (typeof value.now!=='string' || !Number.isFinite(Date.parse(value.now)))) {
71
+ throw usageError(`${where} now must be a date string, such as "2026-03-01T09:00:00Z".`);
72
+ }
73
+ }
74
+ /**
75
+ * The states verify opens the view in: `contexts` (1 to 4 named ones, each with optional params, now and locale), or
76
+ * the one `context`, named default. Each entry keeps the object the view receives as its runtime context.
77
+ */
78
+ function fixtureContexts(fixtures) {
79
+ if(fixtures.contexts===undefined) {
80
+ const value=fixtures.context || {};
81
+ checkContextFields(value,'The fixture context');
82
+ return [{name:'default',context:value}];
83
+ }
84
+ if(fixtures.context!==undefined) throw usageError('Verification fixtures declare either context or contexts, not both. Move context into contexts as one named entry.');
85
+ const list=fixtures.contexts;
86
+ if(!Array.isArray(list) || !list.length || list.length>FIXTURE_CONTEXTS_MAX) throw usageError(`Declare contexts as a list of 1 to ${FIXTURE_CONTEXTS_MAX} named contexts.`);
87
+ const names=new Set();
88
+ return list.map((value,index)=>{
89
+ const where=`Fixture context ${index+1}`;
90
+ if(!object(value) || Object.keys(value).some(key=>!['name','params','now','locale'].includes(key))) {
91
+ throw usageError(`${where} takes only name, params, now and locale.`);
92
+ }
93
+ if(typeof value.name!=='string' || !VERIFY_CONTEXT_NAME.test(value.name)) {
94
+ throw usageError(`${where} needs a name of lowercase letters, digits, "-" or "_" (at most 32), such as "this-week".`);
95
+ }
96
+ if(names.has(value.name)) throw usageError(`Two fixture contexts are named ${value.name}; give each its own name.`);
97
+ names.add(value.name);
98
+ checkContextFields(value,`Fixture context ${value.name}`);
99
+ const {name,...context}=value;
100
+ return {name,context};
101
+ });
102
+ }
103
+
104
+ // Fixture images: a URL the fixture rows hold (a photo, a cover) shows an image file kept next to the fixtures.
105
+ export const FIXTURE_IMAGES_MAX=32;
106
+ export const FIXTURE_IMAGE_BYTES_MAX=2*1024*1024;
107
+ // All of them together stay under what one render may load (32 MB, view-renderer).
108
+ export const FIXTURE_IMAGES_TOTAL_BYTES_MAX=16*1024*1024;
109
+ const FIXTURE_IMAGE_TYPES={'.png':'image/png','.jpg':'image/jpeg','.jpeg':'image/jpeg','.webp':'image/webp','.gif':'image/gif','.avif':'image/avif'};
110
+
111
+ /**
112
+ * `images` of a fixture file: `{ "<https URL a row holds>": "<image file, relative to the fixture file>" }`, as
113
+ * `[{url, path, type}]` with `path` relative to the Space folder. Throws on anything else.
114
+ */
115
+ export function fixtureImageEntries(fixtures,fixturePath) {
116
+ const images=fixtures?.images;
117
+ if(images===undefined) return [];
118
+ const where=fixturePath ? ` in ${fixturePath}` : '';
119
+ if(!object(images) || Object.keys(images).length>FIXTURE_IMAGES_MAX) {
120
+ throw usageError(`Declare fixture images${where} as an object of at most ${FIXTURE_IMAGES_MAX} entries: {"https://example.com/photo.jpg": "./photos/photo.jpg"}.`);
121
+ }
122
+ const base=posix.dirname(fixturePath || 'fixtures.json');
123
+ return Object.entries(images).map(([url,file])=>{
124
+ let parsed;
125
+ try { parsed=new URL(url); } catch {}
126
+ if(!parsed || parsed.protocol!=='https:' || parsed.username || parsed.password || parsed.hash || parsed.href!==url) {
127
+ throw usageError(`Fixture image ${JSON.stringify(url)}${where} must be an https URL, written exactly as the fixture rows hold it.`);
128
+ }
129
+ const type=typeof file==='string' ? FIXTURE_IMAGE_TYPES[extname(file).toLowerCase()] : undefined;
130
+ const path=typeof file==='string' ? posix.normalize(posix.join(base,file)) : '';
131
+ if(!type || !path || posix.isAbsolute(file) || file.split(/[\\/]/).includes('..')) {
132
+ throw usageError(`Fixture image ${JSON.stringify(url)}${where} must name a .png, .jpg, .webp, .gif or .avif file in the fixture file's folder or below it.`);
133
+ }
134
+ return {url,path,type};
135
+ });
136
+ }
137
+
61
138
  const VIEWER_READS={list_databases:'databases',get_database:'databases',query_database:'databases',list_skills:'skills',get_skill:'skills'};
62
139
 
140
+ /**
141
+ * A shown fixture holds the whole list; a read asks for one page of it (page_size rows from offset), as the host
142
+ * does live. Without this a view reading every page (useShown allPages) got all rows on each page and counted
143
+ * them once per page.
144
+ */
145
+ function shownPage(result,options) {
146
+ if(!object(options) || !object(result) || !Array.isArray(result.rows)) return result;
147
+ const offset=Number.isSafeInteger(options.offset) && options.offset>0 ? options.offset : 0;
148
+ // An offset with no page size reads one page of the live default size (100, server/lib/space_view_manifest.py).
149
+ const size=Number.isSafeInteger(options.page_size) && options.page_size>0 ? options.page_size : offset ? 100 : null;
150
+ if(size===null) return result;
151
+ result.rows=result.rows.slice(offset,offset+size);
152
+ return result;
153
+ }
154
+
63
155
  export function createSpaceFixtureEngine(release) {
64
156
  const bodyTemplates=structuredClone(release.manifest.actions || {});
65
157
  const bodyResources=structuredClone(release.manifest.resources || {});
@@ -70,8 +162,18 @@ export function createSpaceFixtureEngine(release) {
70
162
  try { fixtures=JSON.parse(Buffer.from(encoded,'base64').toString('utf8')); }
71
163
  catch { throw usageError('Verification fixtures must be finite JSON objects.'); }
72
164
  }
73
- if(!object(fixtures) || Object.keys(fixtures).some(key=>!['actions','context','documentBodies','viewerReads','shown','recordViews'].includes(key)) || !object(fixtures.actions)
165
+ if(!object(fixtures) || Object.keys(fixtures).some(key=>!['actions','context','contexts','documentBodies','viewerReads','shown','recordViews','images'].includes(key)) || !object(fixtures.actions)
74
166
  || (fixtures.context!==undefined && !object(fixtures.context))) throw usageError('Verification fixtures declare actions and optional synthetic context.');
167
+ const contexts=fixtureContexts(fixtures);
168
+ const images=new Map(fixtureImageEntries(fixtures,release.fixturePath).map(entry=>{
169
+ const encoded=release.sourceFiles[entry.path];
170
+ if(typeof encoded!=='string') throw usageError(`Fixture image ${entry.path} for ${entry.url} is missing from the Space folder.`);
171
+ if(Buffer.byteLength(encoded,'base64')>FIXTURE_IMAGE_BYTES_MAX) throw usageError(`Fixture image ${entry.path} is larger than 2 MB; use a smaller picture.`);
172
+ return [entry.url,{mime_type:entry.type,data_base64:encoded}];
173
+ }));
174
+ if([...images.values()].reduce((total,image)=>total+Buffer.byteLength(image.data_base64,'base64'),0)>FIXTURE_IMAGES_TOTAL_BYTES_MAX) {
175
+ throw usageError(`Fixture images${release.fixturePath ? ` in ${release.fixturePath}` : ''} add up to more than 16 MB; use smaller pictures.`);
176
+ }
75
177
  // Viewer reads have no grant: fixtures stand in for what a signed-in viewer could open.
76
178
  const declaredReads=release.manifest.viewer_reads || [];
77
179
  // V4: a declared list is served from fixtures per exact params, like a signed-in Editor's read.
@@ -187,7 +289,13 @@ export function createSpaceFixtureEngine(release) {
187
289
  if(entry.operation==='html' && value.title!==undefined && value.title!==null && typeof value.title!=='string') throw usageError('HTML fixtures contain a record key, HTML and an optional title.');
188
290
  if(entry.operation==='report' && (typeof value.source!=='string' || typeof value.export_name!=='string')) throw usageError('Report fixtures contain an explicit readonly source and export.');
189
291
  }
190
- return { context:fixtures.context || {}, digest:createHash('sha256').update(JSON.stringify(fixtures)).digest('hex'),
292
+ return { context:fixtures.context || {}, contexts, digest:[...images.values()].reduce((hash,image)=>hash.update(image.data_base64),createHash('sha256').update(JSON.stringify(fixtures))).digest('hex'),
293
+ imageUrls:[...images.keys()],
294
+ executeImage(url) {
295
+ const image=images.get(url);
296
+ if(!image) throw usageError(`The view shows the image ${url}, which its fixtures do not provide. Add it to images in ${release.fixturePath || 'its fixtures'}.`);
297
+ return {...image};
298
+ },
191
299
  executeRecordView(operation,key) {
192
300
  const match=recordViews.find(value=>value.operation===operation && value.record_key===key);
193
301
  if(!match) {
@@ -203,12 +311,12 @@ export function createSpaceFixtureEngine(release) {
203
311
  if(!matched) throw usageError('Add an explicit synthetic document body fixture.');
204
312
  return structuredClone(matched.result);
205
313
  },
206
- executeShown(name,params) {
314
+ executeShown(name,params,options={}) {
207
315
  if(!Object.hasOwn(declaredLists,name)) throw usageError('This view does not declare that list.');
208
316
  if(!object(params)) throw usageError('List params must be an object.');
209
317
  const matched=shownCases[name]?.find(entry=>isDeepStrictEqual(entry.params,params));
210
318
  if(!matched) throw usageError(`Add an explicit synthetic shown fixture for ${name} and these params.`);
211
- return structuredClone(matched.result);
319
+ return shownPage(structuredClone(matched.result),options);
212
320
  },
213
321
  executeViewerRead(operation,input) {
214
322
  if(!Object.hasOwn(VIEWER_READS,operation) || !declaredReads.includes(VIEWER_READS[operation])) throw usageError('This Space does not declare that viewer read.');
@@ -226,7 +334,13 @@ export function createSpaceFixtureEngine(release) {
226
334
  } };
227
335
  }
228
336
 
229
- export function spaceHarnessSnapshot(release,capabilities,engine,{authorizationMode='authorize_missing',unavailableActions=[]}={}) {
337
+ /** The fixture context a render opens with: the named one of `contexts`, else the first (the only `context`). */
338
+ export function selectedFixtureContext(engine,name) {
339
+ const list=engine.contexts || [{name:'default',context:engine.context || {}}];
340
+ return (name===undefined ? list[0] : list.find(item=>item.name===name)) || (()=>{ throw usageError(`The fixtures have no context named ${JSON.stringify(String(name))}.`); })();
341
+ }
342
+
343
+ export function spaceHarnessSnapshot(release,capabilities,engine,{authorizationMode='authorize_missing',unavailableActions=[],context:contextName}={}) {
230
344
  if(release.manifest.kind!=='presentation') throw usageError('Containers do not have an executable preview.');
231
345
  const manifest=release.manifest;
232
346
  const names=Object.keys(manifest.actions || {}).sort();
@@ -273,7 +387,7 @@ export function spaceHarnessSnapshot(release,capabilities,engine,{authorizationM
273
387
  ...(viewerReads.length?{viewerReads}:{}),...viewDeclarations(manifest),
274
388
  // A local verification renders as an Editor, with the editor-only summary the server gives Editors.
275
389
  audience:'editor',...(manifest.editors_only?{editorsOnly:editorsOnlyDescriptor(manifest.editors_only)}:{})},
276
- app:{id:identity,name:manifest.name},route:{slug:'view',path:'/',name:manifest.name},context:engine.context} };
390
+ app:{id:identity,name:manifest.name},route:{slug:'view',path:'/',name:manifest.name},context:selectedFixtureContext(engine,contextName).context} };
277
391
  }
278
392
 
279
393
  /** Existing CLI theme only; the legacy executable/JWT HTML is never served. */
@@ -318,8 +432,9 @@ export async function startSpaceTestServer({release,capabilities,port=0,authoriz
318
432
  const input=JSON.parse(Buffer.concat(chunks).toString('utf8'));
319
433
  if(object(input) && Object.keys(input).length===1 && Object.hasOwn(input,'shown')) {
320
434
  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)}));}
435
+ const keys=object(list) ? Object.keys(list).sort().join(',') : '';
436
+ if(keys!=='name,params' && keys!=='name,options,params') return response(400,'{}');
437
+ try {return response(200,JSON.stringify({result:engine.executeShown(list.name,list.params,list.options)}));}
323
438
  catch(error) {return response(400,JSON.stringify({message:error.message}));}
324
439
  }
325
440
  if(object(input) && Object.keys(input).length===1 && Object.hasOwn(input,'viewer_read')) {