@notis_ai/cli 0.2.31 → 0.2.33

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 (92) hide show
  1. package/README.md +88 -9
  2. package/config/notis_app_design_rules.json +22 -0
  3. package/dist/agent-hooks/notis-agent-hook.mjs +4677 -913
  4. package/dist/base-skills/notis-cli/.notis-base-skill.json +1 -1
  5. package/dist/base-skills/notis-cli/SKILL.md +7 -3
  6. package/dist/base-skills/notis-spaces/.notis-base-skill.json +1 -1
  7. package/dist/base-skills/notis-spaces/SKILL.md +9 -4
  8. package/dist/base-skills/notis-spaces/references/comments.md +94 -0
  9. package/dist/base-skills/notis-spaces/references/context.md +20 -19
  10. package/dist/base-skills/notis-spaces/references/design.md +3 -2
  11. package/dist/base-skills/notis-spaces/references/fixtures.md +4 -2
  12. package/dist/base-skills/notis-spaces/references/reading.md +3 -1
  13. package/dist/base-skills/notis-spaces/references/release.md +3 -1
  14. package/dist/base-skills/notis-spaces/references/sdk.md +160 -88
  15. package/dist/base-skills/notis-spaces/references/store.md +24 -1
  16. package/dist/sdk/src/components/SelectionActionBar.tsx +42 -7
  17. package/dist/sdk/src/components/SpaceTextComments.tsx +284 -0
  18. package/dist/sdk/src/config.ts +3 -1
  19. package/dist/sdk/src/functions.ts +203 -0
  20. package/dist/sdk/src/hooks/useAgentQueue.ts +17 -28
  21. package/dist/sdk/src/hooks/useCollectionInteractions.ts +7 -2
  22. package/dist/sdk/src/hooks/useConnection.ts +102 -0
  23. package/dist/sdk/src/hooks/useFunction.ts +42 -0
  24. package/dist/sdk/src/hooks/useNotisSettings.ts +101 -0
  25. package/dist/sdk/src/index.ts +15 -4
  26. package/dist/sdk/src/runtime.ts +16 -1
  27. package/dist/sdk/src/space.ts +333 -33
  28. package/dist/sdk/src/ui/comments/passageModel.ts +99 -0
  29. package/dist/sdk/src/ui/comments/textHighlights.ts +33 -0
  30. package/dist/sdk/src/ui/icons.tsx +17 -1
  31. package/dist/skill-sync/index.js +239 -30
  32. package/dist/skill-sync-worker.mjs +453 -124
  33. package/dist/space-harness/host.js +218 -93
  34. package/dist/space-sdk/dist/chunk-4GWS2IFO.js +3 -0
  35. package/dist/space-sdk/dist/index.js +3 -3
  36. package/dist/space-sdk/dist/ui.js +9 -8
  37. package/dist/space-sdk/src/config.ts +3 -1
  38. package/dist/space-sdk/src/functions.ts +203 -0
  39. package/dist/space-sdk/src/hooks/useAgentQueue.d.ts +2 -13
  40. package/dist/space-sdk/src/hooks/useCollectionInteractions.d.ts +2 -0
  41. package/dist/space-sdk/src/hooks/useConnection.d.ts +42 -0
  42. package/dist/space-sdk/src/hooks/useFunction.d.ts +20 -0
  43. package/dist/space-sdk/src/hooks/useNotisSettings.d.ts +48 -0
  44. package/dist/space-sdk/src/index.d.ts +10 -4
  45. package/dist/space-sdk/src/runtime.d.ts +14 -1
  46. package/dist/space-sdk/src/space.ts +333 -33
  47. package/dist/space-sdk/src/tailwind-candidates.d.ts +227 -152
  48. package/dist/space-sdk/src/ui/blocks/blocks.d.ts +18 -0
  49. package/dist/space-sdk/src/ui/blocks/index.d.ts +2 -2
  50. package/dist/space-sdk/src/ui/comments/CommentPane.d.ts +7 -4
  51. package/dist/space-sdk/src/ui/comments/agentRuntime.d.ts +10 -2
  52. package/dist/space-sdk/src/ui/comments/commentModel.d.ts +55 -88
  53. package/dist/space-sdk/src/ui/comments/commentWords.d.ts +9 -0
  54. package/dist/space-sdk/src/ui/comments/hostComments.d.ts +13 -9
  55. package/dist/space-sdk/src/ui/comments/index.d.ts +1 -1
  56. package/dist/space-sdk/src/ui/comments/paneParts.d.ts +27 -5
  57. package/dist/space-sdk/src/ui/comments/passageModel.d.ts +12 -36
  58. package/dist/space-sdk/src/ui/comments/useCommentRouting.d.ts +26 -4
  59. package/dist/space-sdk/src/ui/comments/useComments.d.ts +64 -74
  60. package/dist/space-sdk/src/ui/comments/usePassageComments.d.ts +8 -4
  61. package/dist/space-sdk/src/ui/icons.d.ts +6 -0
  62. package/dist/space-sdk/src/ui/index.d.ts +2 -2
  63. package/dist/space-sdk/src/ui/layout/SidePane.d.ts +3 -4
  64. package/dist/space-sdk/src/ui/list/ListReader.d.ts +8 -0
  65. package/dist/space-sdk/src/ui/period/dateFormat.d.ts +27 -8
  66. package/dist/view-renderer/dist/host.js +285 -160
  67. package/package.json +3 -3
  68. package/skills/notis-cli/AGENT_INSTRUCTIONS.md +2 -2
  69. package/skills/notis-spaces/cli.md +17 -3
  70. package/src/cli.js +2 -1
  71. package/src/command-specs/index.js +3 -0
  72. package/src/command-specs/repository-secrets.js +171 -0
  73. package/src/command-specs/spaces.js +70 -3
  74. package/src/runtime/agent-credential.js +175 -0
  75. package/src/runtime/agent-identity.js +92 -15
  76. package/src/runtime/app-boundary-validator.js +248 -3
  77. package/src/runtime/app-data-literals.js +32 -23
  78. package/src/runtime/app-platform.js +8 -0
  79. package/src/runtime/auth-recovery.js +14 -0
  80. package/src/runtime/profiles.js +15 -0
  81. package/src/runtime/skill-sync/index.ts +3 -2
  82. package/src/runtime/skill-sync/symlink-manager.ts +354 -35
  83. package/src/runtime/skill-sync/types.ts +10 -1
  84. package/src/runtime/space-functions.js +211 -0
  85. package/src/runtime/space-platform.js +12 -3
  86. package/src/runtime/space-source.js +116 -13
  87. package/src/runtime/space-test-server.js +44 -7
  88. package/src/runtime/space-verification.js +3 -1
  89. package/src/runtime/transport.js +15 -0
  90. package/dist/sdk/src/components/NotisCommentBoundary.tsx +0 -132
  91. package/dist/space-sdk/dist/chunk-3DFOGU26.js +0 -3
  92. package/dist/space-sdk/src/components/NotisCommentBoundary.d.ts +0 -26
@@ -0,0 +1,211 @@
1
+ /**
2
+ * Space `functions`, `threadHooks` and `commentOptions`: server code a Space declares once and Notis
3
+ * calls from every side. The shape is checked here so a mistake fails before the build;
4
+ * server/lib/space_functions.py repeats every check when the Space is published.
5
+ *
6
+ * Handlers are built into one module, `.notis/output/functions/index.js`, exporting each handler
7
+ * under its function name. That file is never part of the page bundle and no route serves it.
8
+ */
9
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
10
+ import { dirname, join, relative } from 'node:path';
11
+ import { usageError } from './errors.js';
12
+
13
+ export const FUNCTIONS_BUNDLE = 'functions/index.js';
14
+ export const MAX_FUNCTIONS_BUNDLE_BYTES = 1_048_576;
15
+ const KINDS = ['read', 'write', 'action'];
16
+ const EXPOSURES = ['page', 'api', 'agents'];
17
+ const ROLES = ['public', 'viewer', 'editor', 'key'];
18
+ const LEVELS = ['read', 'shell'];
19
+ export const THREAD_OPERATIONS = Object.freeze(['archive', 'unarchive', 'read', 'unread', 'star', 'unstar', 'later', 'back']);
20
+ export const THREAD_HOOK_EVENTS = Object.freeze([...THREAD_OPERATIONS, 'delete']);
21
+ const FUNCTION_FIELDS = ['description', 'kind', 'input', 'output', 'expose', 'access', 'uses', 'handler'];
22
+ const USES_FIELDS = ['actions', 'cloudComputer', 'threads'];
23
+ // Field names a hook's or a comment option's function must take: the server compares the whole schema.
24
+ const HOOK_INPUT_FIELDS = 'actor,event,items,thread';
25
+ const COMMENT_INPUT_FIELDS = 'comment,option';
26
+
27
+ const plain = value => Boolean(value) && typeof value === 'object' && !Array.isArray(value);
28
+ const listed = (value, allowed, { empty = true } = {}) => Array.isArray(value) && (empty || value.length > 0)
29
+ && value.every(item => allowed.includes(item)) && new Set(value).size === value.length;
30
+ const inputFields = spec => Object.keys(spec?.input?.properties || {}).sort().join(',');
31
+
32
+ function label(value) {
33
+ if (typeof value === 'string') return value.trim().length > 0 && value.length <= 200;
34
+ return plain(value) && typeof value.en === 'string' && value.en.trim().length > 0
35
+ && Object.keys(value).every(name => ['en', 'fr'].includes(name) && typeof value[name] === 'string' && value[name].trim());
36
+ }
37
+
38
+ /** Check `functions`, `threadHooks` and `commentOptions` of one Space definition. */
39
+ export function validateSpaceFunctions(definition, { entry } = {}) {
40
+ const { functions, threadHooks, commentOptions } = definition;
41
+ if (functions == null && threadHooks == null && commentOptions == null) return;
42
+ if (!entry) throw usageError('A container has no built code, so it declares no functions.');
43
+ if (functions == null) throw usageError('threadHooks and commentOptions name functions: declare functions first.');
44
+ const names = plain(functions) ? Object.entries(functions) : null;
45
+ if (!names || names.length < 1 || names.length > 30) throw usageError('Declare functions as 1 to 30 named functions.');
46
+ const actions = definition.actions || {};
47
+ const cloud = typeof definition.cloudComputer === 'string' ? definition.cloudComputer : definition.cloudComputer?.access;
48
+ const hasItems = plain(definition.threadItems) && Object.keys(definition.threadItems).length > 0;
49
+ for (const [name, spec] of names) {
50
+ if (!/^[a-z][a-z0-9_]{0,59}$/.test(name)) throw usageError('Each function needs a short name: lowercase letters, digits and _.');
51
+ if (!plain(spec) || Object.keys(spec).some(field => !FUNCTION_FIELDS.includes(field))) {
52
+ throw usageError(`Function ${name} takes ${FUNCTION_FIELDS.join(', ')} only.`);
53
+ }
54
+ if (typeof spec.description !== 'string' || !spec.description.trim() || spec.description.length > 1000) {
55
+ throw usageError(`Function ${name} needs a description: agents read it to decide when to call it.`);
56
+ }
57
+ if (!KINDS.includes(spec.kind)) {
58
+ throw usageError(`Function ${name} needs kind: 'read' (changes nothing), 'write' (changes this Space's data) or 'action' (reaches a connected app, a machine or a thread).`);
59
+ }
60
+ if (spec.input?.type !== 'object' || spec.input?.additionalProperties !== false) {
61
+ throw usageError(`Function ${name} declares input as a closed object schema: type object, additionalProperties false.`);
62
+ }
63
+ if (spec.output !== undefined && !plain(spec.output)) throw usageError(`Function ${name} declares output as a JSON schema.`);
64
+ if (spec.expose !== undefined && !listed(spec.expose, EXPOSURES)) {
65
+ throw usageError(`Function ${name} lists expose from 'page', 'api' and 'agents', once each.`);
66
+ }
67
+ if (spec.access !== undefined && !listed(spec.access, ROLES, { empty: false })) {
68
+ throw usageError(`Function ${name} lists access from 'public', 'viewer', 'editor' and 'key', once each.`);
69
+ }
70
+ const uses = spec.uses ?? {};
71
+ if (!plain(uses) || Object.keys(uses).some(field => !USES_FIELDS.includes(field))) {
72
+ throw usageError(`Function ${name} declares uses as actions, cloudComputer and threads only.`);
73
+ }
74
+ const used = uses.actions ?? [];
75
+ if (!Array.isArray(used) || used.length > 20 || new Set(used).size !== used.length) {
76
+ throw usageError(`Function ${name} lists up to 20 of this Space's actions in uses.actions, once each.`);
77
+ }
78
+ const unknown = used.filter(action => typeof action !== 'string' || !Object.hasOwn(actions, action)).map(String).sort();
79
+ if (unknown.length) throw usageError(`Function ${name} uses actions this Space does not declare: ${unknown.join(', ')}.`);
80
+ const level = uses.cloudComputer;
81
+ if (level != null) {
82
+ if (!LEVELS.includes(level)) throw usageError(`Function ${name} uses the cloud computer at 'read' or 'shell'.`);
83
+ if (!LEVELS.includes(cloud) || LEVELS.indexOf(level) > LEVELS.indexOf(cloud)) {
84
+ throw usageError(`Function ${name} uses the cloud computer at ${level}: declare cloudComputer at that level on this Space first.`);
85
+ }
86
+ }
87
+ if (uses.threads != null) {
88
+ if (!listed(uses.threads, THREAD_OPERATIONS, { empty: false })) {
89
+ throw usageError(`Function ${name} lists uses.threads from ${THREAD_OPERATIONS.join(', ')}, once each.`);
90
+ }
91
+ if (!hasItems) {
92
+ throw usageError(`Function ${name} acts on threads: a Space reaches only the threads its own items are attached to, so declare threadItems first.`);
93
+ }
94
+ }
95
+ if (spec.kind === 'read' && (uses.threads || level === 'shell')) {
96
+ throw usageError(`Function ${name} is a read: it cannot run thread actions or shell commands. Use kind 'action'.`);
97
+ }
98
+ if (spec.kind === 'write' && (uses.threads || level === 'shell')) {
99
+ throw usageError(`Function ${name} reaches beyond this Space's data: use kind 'action'.`);
100
+ }
101
+ if (typeof spec.handler !== 'string' || !/\.[cm]?[jt]s$/.test(spec.handler)) {
102
+ throw usageError(`Function ${name} needs handler: the source module whose default export is its code, such as './functions/${name.replaceAll('_', '-')}.ts'.`);
103
+ }
104
+ }
105
+ if (threadHooks != null) {
106
+ if (!plain(threadHooks) || !Object.keys(threadHooks).length || Object.keys(threadHooks).some(event => !THREAD_HOOK_EVENTS.includes(event))) {
107
+ throw usageError(`Declare threadHooks as { <action>: '<function>' } for ${THREAD_HOOK_EVENTS.join(', ')}.`);
108
+ }
109
+ if (!hasItems) throw usageError("threadHooks follow the threads this Space's items are attached to: declare threadItems first.");
110
+ for (const [event, name] of Object.entries(threadHooks)) {
111
+ if (typeof name !== 'string' || !Object.hasOwn(functions, name)) throw usageError(`Thread hook ${event} names a function this Space does not declare.`);
112
+ if (inputFields(functions[name]) !== HOOK_INPUT_FIELDS) {
113
+ throw usageError(`Function ${name} runs as a thread hook: declare its input as threadHookInput from @notis/sdk.`);
114
+ }
115
+ }
116
+ }
117
+ if (commentOptions != null) {
118
+ const options = plain(commentOptions) ? Object.entries(commentOptions) : null;
119
+ if (!options || options.length < 1 || options.length > 12) throw usageError('Declare commentOptions as 1 to 12 options.');
120
+ const labels = new Set();
121
+ for (const [option, spec] of options) {
122
+ if (!/^[a-z][a-z0-9_-]{0,39}$/.test(option)) throw usageError('Each comment option needs a short id.');
123
+ if (!plain(spec) || Object.keys(spec).sort().join(',') !== 'function,label' || !label(spec.label)) {
124
+ throw usageError(`Comment option ${option} is { label, function }; the label is text or { en, fr }.`);
125
+ }
126
+ if (typeof spec.function !== 'string' || !Object.hasOwn(functions, spec.function)) {
127
+ throw usageError(`Comment option ${option} names a function this Space does not declare.`);
128
+ }
129
+ if (inputFields(functions[spec.function]) !== COMMENT_INPUT_FIELDS) {
130
+ throw usageError(`Function ${spec.function} runs for a comment option: declare its input as commentOptionInput from @notis/sdk.`);
131
+ }
132
+ for (const text of typeof spec.label === 'string' ? [spec.label] : Object.values(spec.label)) {
133
+ if (labels.has(text.trim())) throw usageError(`Comment option ${option} repeats another option's label: an answer must name one option.`);
134
+ labels.add(text.trim());
135
+ }
136
+ }
137
+ }
138
+ }
139
+
140
+ /** The manifest's `functions`: each declaration without its source `handler` path. */
141
+ export function manifestFunctions(functions) {
142
+ return Object.fromEntries(Object.entries(functions || {}).map(([name, { handler: _handler, ...declared }]) => [name, declared]));
143
+ }
144
+
145
+ /** Manifest keys for the three declarations; each absent when undeclared, so other manifests stay byte-identical. */
146
+ export function functionManifestFields(definition) {
147
+ const declared = plain(definition.functions) && Object.keys(definition.functions).length > 0;
148
+ return {
149
+ ...(declared ? { functions: manifestFunctions(definition.functions) } : {}),
150
+ ...(plain(definition.threadHooks) && Object.keys(definition.threadHooks).length ? { thread_hooks: definition.threadHooks } : {}),
151
+ ...(plain(definition.commentOptions) && Object.keys(definition.commentOptions).length ? { comment_options: definition.commentOptions } : {}),
152
+ };
153
+ }
154
+
155
+ /** { function name: workspace-relative handler path } for a loaded selection. */
156
+ export function functionHandlerPaths(definition, resolveDefinitionPath) {
157
+ return Object.fromEntries(Object.entries(definition.functions || {}).map(([name, spec]) => [name, resolveDefinitionPath(spec.handler)]));
158
+ }
159
+
160
+ /**
161
+ * Build every handler of the selected Space into `.notis/output/functions/index.js`. Without functions
162
+ * the folder is removed, so a build after the last function was deleted ships none.
163
+ */
164
+ export async function buildSpaceFunctions(projectDir, handlers) {
165
+ const outputDir = join(projectDir, '.notis/output/functions');
166
+ rmSync(outputDir, { recursive: true, force: true });
167
+ const names = Object.keys(handlers || {}).sort();
168
+ if (!names.length) return null;
169
+ const entryPath = join(projectDir, '.notis/_functions.ts');
170
+ mkdirSync(dirname(entryPath), { recursive: true });
171
+ const reference = path => JSON.stringify('./' + relative(dirname(entryPath), join(projectDir, path)).replaceAll('\\', '/'));
172
+ // A TypeScript module without a default export still bundles (the name could have been a type), so the
173
+ // source is checked here and the built module refuses to load without it.
174
+ const missing = names.filter(name => !/\bexport\s+default\b|\bas\s+default\b/.test(readFileSync(join(projectDir, handlers[name]), 'utf8')));
175
+ if (missing.length) {
176
+ throw usageError(`This Space's functions did not build:\n${missing.map(name => ` - ${handlers[name]}: export the handler of ${name} as the module's default export.`).join('\n')}`);
177
+ }
178
+ writeFileSync(entryPath, [
179
+ ...names.map((name, index) => `import * as module${index} from ${reference(handlers[name])};`),
180
+ 'const handler = (name: string, module: { default?: unknown }) => {',
181
+ " if (typeof module.default !== 'function') throw new Error(`Function ${name} needs a default export that is its handler.`);",
182
+ ' return module.default;',
183
+ '};',
184
+ // Exported by alias, so a function may carry any valid name (delete, new, import).
185
+ ...names.map((name, index) => `const handler${index} = handler(${JSON.stringify(name)}, module${index});`),
186
+ `export { ${names.map((name, index) => `handler${index} as ${name}`).join(', ')} };`,
187
+ ].join('\n') + '\n');
188
+ const { build } = await import('esbuild');
189
+ const outfile = join(projectDir, '.notis/output', FUNCTIONS_BUNDLE);
190
+ let result;
191
+ try {
192
+ result = await build({
193
+ absWorkingDir: projectDir, entryPoints: [entryPath], outfile, bundle: true, format: 'esm', platform: 'neutral',
194
+ target: 'es2022', mainFields: ['module', 'main'], conditions: ['worker', 'import'], minify: false, sourcemap: false,
195
+ legalComments: 'none', logLevel: 'silent', metafile: true, treeShaking: true, charset: 'utf8',
196
+ plugins: [{ name: 'notis-functions', setup(builder) {
197
+ // The SDK is the page's code (React, the host bridge). A handler takes its types only, which are erased.
198
+ builder.onResolve({ filter: /^@notis\/sdk(\/|$)/ }, () => ({ errors: [{ text:
199
+ 'A function handler imports types only from @notis/sdk (import type { SpaceFunctionHandler }). Its code runs on the server, without the page SDK.' }] }));
200
+ builder.onResolve({ filter: /^(node:|cloudflare:)/ }, args => ({ errors: [{ text:
201
+ `A function handler cannot import ${args.path}: it has no file system, no network and no process.` }] }));
202
+ } }],
203
+ });
204
+ } catch (error) {
205
+ const lines = (error?.errors || []).map(item => ` - ${item.location?.file ? `${item.location.file}: ` : ''}${item.text}`);
206
+ throw usageError(`This Space's functions did not build:\n${lines.join('\n') || ` - ${error?.message || error}`}`);
207
+ }
208
+ const size = Object.values(result.metafile.outputs)[0]?.bytes ?? 0;
209
+ if (size > MAX_FUNCTIONS_BUNDLE_BYTES) throw usageError('The built functions of this Space are over 1 MB. Move large data into a database.');
210
+ return { path: FUNCTIONS_BUNDLE, bytes: size };
211
+ }
@@ -3,12 +3,13 @@ import { existsSync, mkdirSync, readFileSync, symlinkSync, writeFileSync } from
3
3
  import { dirname, join, relative, resolve } from 'node:path';
4
4
  import { appFilesDigest, buildArtifact, freezeSourceWorkspace, prepareAppRelease, prepareSelectedBuild, saveSelectedBuild, syncSpaceSdk } from './app-platform.js';
5
5
  import { validateProjectBoundary, validateProjectDesign, validateSourceDesign } from './app-boundary-validator.js';
6
- import { collectSelectedSpaceSource, loadSelectedSpace } from './space-source.js';
6
+ import { checkStoreShips, collectSelectedSpaceSource, loadSelectedSpace, storeManifest } from './space-source.js';
7
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
11
  import { ensureSpaceDependencies } from './space-dependencies.js';
12
+ import { buildSpaceFunctions, functionManifestFields } from './space-functions.js';
12
13
 
13
14
  const SPACE_ICON = /^(phosphor:[a-z0-9]+(-[a-z0-9]+)*|https:\/\/\S{1,2000})$/;
14
15
 
@@ -35,8 +36,12 @@ export function generateSpaceManifest(selection) {
35
36
  ...(definition.agents?.length ? { agents: definition.agents } : {}),
36
37
  // Live items agents attach to threads; absent when undeclared.
37
38
  ...(definition.threadItems && Object.keys(definition.threadItems).length ? { thread_items: definition.threadItems } : {}),
39
+ // Server functions and what runs them; each absent when undeclared. Handler paths stay in the source.
40
+ ...functionManifestFields(definition),
38
41
  // Absent when nothing is editor-only (SPC-073: unmarked means public).
39
42
  ...(editorsOnly ? { editors_only: editorsOnly } : {}),
43
+ // What ships to the Store (SPC-150); absent when undeclared, so existing manifests stay byte-identical.
44
+ ...(definition.store ? { store: storeManifest(definition.store) } : {}),
40
45
  readable_context: definition.readableContext || '', collection: definition.collection || null,
41
46
  // V4 declarations are mandatory for every presentation; the wire schema stays v1.
42
47
  ...viewManifestFields(definition, { entry: selection.entry, resources: definition.resources || {} }),
@@ -85,7 +90,9 @@ export function assertSpaceBundleUsesHostSdk(source) {
85
90
  }
86
91
  }
87
92
 
88
- function finalizeSelectedArtifact(projectDir) {
93
+ async function finalizeSelectedArtifact(projectDir, selection) {
94
+ // The handlers of this Space's functions, as one module of their own next to the page bundle.
95
+ await buildSpaceFunctions(projectDir, selection?.functionHandlers);
89
96
  const manifestPath = join(projectDir, '.notis/output/manifest.json');
90
97
  const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
91
98
  if (manifest.bundle?.js) assertSpaceBundleUsesHostSdk(readFileSync(join(projectDir, '.notis/output', manifest.bundle.js), 'utf8'));
@@ -110,6 +117,8 @@ export async function buildSpaceRelease(projectDir, selectedKey, { stdio = 'inhe
110
117
  // After the SDK sync, so the install follows the lock file that sync keeps in step with the SDK.
111
118
  const installed = installDependencies ? ensureSpaceDependencies(projectDir, { log: installLog }) : null;
112
119
  const selection = await loadSelectedSpace(projectDir, selectedKey);
120
+ // A shipped view never uses a database that stays private (SPC-152): refused before anything is built.
121
+ await checkStoreShips(projectDir, selection);
113
122
  const sourceFiles = collectSelectedSpaceSource(projectDir, selection);
114
123
  const sourceHash = appFilesDigest(sourceFiles);
115
124
  const staging = freezeSourceWorkspace(projectDir, sourceFiles);
@@ -120,7 +129,7 @@ export async function buildSpaceRelease(projectDir, selectedKey, { stdio = 'inhe
120
129
  }
121
130
  const frozenSelection = await loadSelectedSpace(staging.projectDir, selectedKey);
122
131
  await buildArtifact(staging.projectDir, { stdio, refreshSdk: false, executable: Boolean(selection.entry),
123
- prepare: directory => prepareSelectedArtifact(directory, frozenSelection, { designBar, log: designLog }), finalize: finalizeSelectedArtifact,
132
+ prepare: directory => prepareSelectedArtifact(directory, frozenSelection, { designBar, log: designLog }), finalize: directory => finalizeSelectedArtifact(directory, frozenSelection),
124
133
  ...(runBuild ? { runBuild } : {}) });
125
134
  const current = await loadSelectedSpace(projectDir, selectedKey);
126
135
  if (sourceHash !== appFilesDigest(collectSelectedSpaceSource(projectDir, current))) throw usageError('This Space source changed during the selected build. Build again.');
@@ -7,8 +7,9 @@ import { usageError } from './errors.js';
7
7
  import { fixtureImageEntries } from './space-test-server.js';
8
8
  import { VIEW_DEFINITION_FIELDS, viewManifestFields } from './space-view-manifest.js';
9
9
  import { editorOnlyColumns, editorsOnlyFlag, withoutMarker } from './space-audience.js';
10
+ import { functionHandlerPaths, validateSpaceFunctions } from './space-functions.js';
10
11
 
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]);
12
+ const CONFIG_FIELDS = new Set(['name', 'description', 'icon', 'accent', 'entry', 'layout', 'readableContext', 'resources', 'actions', 'navigation', 'viewerReads', 'cloudComputer', 'agents', 'threadItems', 'functions', 'threadHooks', 'commentOptions', 'collection', 'sourceIncludes', 'verificationFixtures', 'editorsOnly', 'store', ...VIEW_DEFINITION_FIELDS]);
12
13
  /** Reads with each signed-in viewer's own authority (never an issuer grant); see docs/notis-spaces-platform.md. */
13
14
  export const VIEWER_READ_FAMILIES = Object.freeze(['databases', 'skills']);
14
15
  const WORKSPACE_INDEXES = new Set(['notis.config.ts', 'notis.config.js', 'notis.config.mjs']);
@@ -227,7 +228,9 @@ export async function loadSelectedSpace(projectDir, selectedKey) {
227
228
  if (definition.cloudComputer != null) validateCloudComputer(definition.cloudComputer);
228
229
  if (definition.cloudComputer != null && !entry) throw usageError('A container has no page, so it cannot use the cloud computer.');
229
230
  if (definition.agents != null) validateSpaceAgents(definition.agents, resources);
230
- if (definition.threadItems != null) validateThreadItems(definition.threadItems, definition.actions || {});
231
+ if (definition.threadItems != null) validateThreadItems(definition.threadItems, definition.actions || {}, definition.functions || {});
232
+ validateSpaceFunctions(definition, { entry });
233
+ if (definition.store != null) validateStoreShips(definition.store, selectedKey);
231
234
  if (definition.collection && (resources[definition.collection.database]?.kind !== 'database' || !definition.collection.titleProperty)) {
232
235
  throw usageError('A collection needs a declared database binding and title property.');
233
236
  }
@@ -251,7 +254,9 @@ export async function loadSelectedSpace(projectDir, selectedKey) {
251
254
  viewManifestFields(definition, { entry, resources });
252
255
  const markdown = definition.markdown ? resolveDefinitionPath(definition.markdown) : null;
253
256
  const fixturePath = definition.verificationFixtures ? resolveDefinitionPath(definition.verificationFixtures) : null;
254
- return { key: selectedKey, workspace, definition, definitionPath, entry, layout, markdown, fixturePath, resolveDefinitionPath };
257
+ // Each function's handler module, by function name: built into functions/index.js, never into the page bundle.
258
+ const functionHandlers = functionHandlerPaths(definition, resolveDefinitionPath);
259
+ return { key: selectedKey, workspace, definition, definitionPath, entry, layout, markdown, fixturePath, functionHandlers, resolveDefinitionPath };
255
260
  }
256
261
 
257
262
 
@@ -309,6 +314,7 @@ export function collectSelectedSpaceSource(projectDir, selection, { buildInputs
309
314
  if (selection.entry) add(selection.entry);
310
315
  if (selection.layout) add(selection.layout);
311
316
  if (selection.markdown) add(selection.markdown);
317
+ Object.values(selection.functionHandlers || {}).forEach(add);
312
318
  if (selection.fixturePath) {
313
319
  add(selection.fixturePath);
314
320
  // The image files the fixtures show travel with them; verify reports a bad entry on its own.
@@ -366,10 +372,67 @@ export function collectSelectedSpaceSource(projectDir, selection, { buildInputs
366
372
  } finally { compiler.close(); }
367
373
  }
368
374
 
369
- const AGENT_FIELDS = ['id', 'on', 'thread', 'runtime', 'skill', 'wake', 'columns'];
375
+ const STORE_SHIPS_LIMIT = 200;
376
+
377
+ /**
378
+ * What ships to the Store (`store: { ships: { <source key>: [<resource alias>, ...] } }`, truth SPC-150): the source
379
+ * keys of this Space and of the sub-Spaces that go to the Store, each with the aliases of the linked items that go
380
+ * with it. Everything unlisted stays private. server/lib/space_store_ships.py repeats every check.
381
+ */
382
+ export function validateStoreShips(store, selfKey) {
383
+ const shape = 'Declare store as { ships: { <source key>: [<resource alias>, ...] } }: this Space and the sub-Spaces that go to the Store, each with the aliases of its linked items that go with it.';
384
+ if (!store || typeof store !== 'object' || Array.isArray(store) || Object.keys(store).join(',') !== 'ships') throw usageError(shape);
385
+ const ships = store.ships;
386
+ if (!ships || typeof ships !== 'object' || Array.isArray(ships)) throw usageError(shape);
387
+ const keys = Object.keys(ships);
388
+ if (!keys.length || keys.length > STORE_SHIPS_LIMIT) throw usageError(`store.ships lists 1 to ${STORE_SHIPS_LIMIT} Spaces by source key.`);
389
+ for (const [spaceKey, aliases] of Object.entries(ships)) {
390
+ key(spaceKey, 'A store.ships key');
391
+ if (!Array.isArray(aliases) || aliases.length > STORE_SHIPS_LIMIT) throw usageError(`store.ships.${spaceKey} lists the aliases of the linked items that ship with it.`);
392
+ aliases.forEach(alias => key(alias, `An alias in store.ships.${spaceKey}`));
393
+ if (new Set(aliases).size !== aliases.length) throw usageError(`store.ships.${spaceKey} lists an alias twice.`);
394
+ }
395
+ if (!Object.hasOwn(ships, selfKey)) throw usageError(`store.ships must list this Space itself (${selfKey}): the root always ships.`);
396
+ }
397
+
398
+ /** The canonical store manifest field: source keys and aliases sorted, so each build writes the same bytes. */
399
+ export function storeManifest(store) {
400
+ return { ships: Object.fromEntries(Object.keys(store.ships).sort().map(name => [name, [...store.ships[name]].sort()])) };
401
+ }
402
+
403
+ /**
404
+ * A shipped view must not read or write a database that stays private (truth SPC-152), nor use a Skill, automation or
405
+ * page that does: its installed copy would break. Checks every listed Space this source workspace defines; a listed
406
+ * sub-Space from another workspace is checked by the server when the Space is published.
407
+ */
408
+ export async function checkStoreShips(projectDir, selection) {
409
+ const ships = selection.definition.store?.ships;
410
+ if (!ships) return;
411
+ for (const spaceKey of Object.keys(ships).sort()) {
412
+ if (!Object.hasOwn(selection.workspace.spaces || {}, spaceKey)) continue;
413
+ const listed = spaceKey === selection.key ? selection : await loadSelectedSpace(projectDir, spaceKey);
414
+ const shipped = new Set(ships[spaceKey]);
415
+ for (const [alias, resource] of Object.entries(listed.definition.resources || {}).sort(([a], [b]) => a.localeCompare(b))) {
416
+ if (shipped.has(alias)) continue;
417
+ const name = `${listed.definition.name} (${spaceKey})`;
418
+ // The root always ships, so its own view can only list the alias.
419
+ const fix = spaceKey === selection.key ? `Add '${alias}' to store.ships.${spaceKey}: the root always ships.`
420
+ : `Add '${alias}' to store.ships.${spaceKey}, or take ${spaceKey} out of store.ships.`;
421
+ if (resource?.kind === 'database') throw usageError(`View ${name} reads or writes the database ${alias}, which stays private. ${fix}`);
422
+ throw usageError(`View ${name} uses the ${resource?.kind || 'resource'} ${alias}, which stays private. ${fix}`);
423
+ }
424
+ }
425
+ }
426
+
427
+ const AGENT_FIELDS = ['id', 'on', 'event', 'thread', 'runtime', 'skill', 'wake', 'columns'];
428
+ const COMMENT_AGENT_FIELDS = ['id', 'on', 'event', 'thread', 'runtime', 'skill', 'wake'];
370
429
  const AGENT_COLUMNS = ['thread', 'scope', 'answer', 'author'];
371
430
 
372
- /** The `agents` a Space's database changes wake (server/lib/space_agents.py repeats every check). */
431
+ /**
432
+ * The `agents` a Space wakes (server/lib/space_agents.py repeats every check): `on: 'comments'` for the Space's
433
+ * comments (event, wake, thread, runtime and skill; no columns, comments are not database rows), or
434
+ * `on: { database: '<alias>', event? }` for changes to one of its database resources.
435
+ */
373
436
  export function validateSpaceAgents(agents, resources = {}) {
374
437
  if (!Array.isArray(agents) || agents.length < 1 || agents.length > 8) throw usageError('Declare agents as a list of 1 to 8 agents.');
375
438
  const seen = new Set();
@@ -382,10 +445,19 @@ export function validateSpaceAgents(agents, resources = {}) {
382
445
  }
383
446
  seen.add(agent.id);
384
447
  const on = agent.on;
385
- if (!on || typeof on !== 'object' || Object.keys(on).some(name => !['database', 'event'].includes(name)) || resources[on.database]?.kind !== 'database') {
386
- throw usageError(`Agent ${agent.id} watches one of this Space's database resources: on: { database: '<alias>' }.`);
448
+ let event = agent.event;
449
+ if (on === 'comments') {
450
+ const extra = Object.keys(agent).find(name => !COMMENT_AGENT_FIELDS.includes(name));
451
+ if (extra) throw usageError(`Agent ${agent.id} wakes on this Space's comments and takes ${COMMENT_AGENT_FIELDS.join(', ')} only.`);
452
+ } else {
453
+ if (!on || typeof on !== 'object' || Array.isArray(on) || Object.keys(on).some(name => !['database', 'event'].includes(name))
454
+ || resources[on.database]?.kind !== 'database') {
455
+ throw usageError(`Agent ${agent.id} wakes on this Space's comments (on: 'comments') or watches one of its database resources: on: { database: '<alias>' }.`);
456
+ }
457
+ if (event != null) throw usageError(`Agent ${agent.id} watches a database: give its event inside on: { database, event }.`);
458
+ event = on.event;
387
459
  }
388
- if (on.event != null && !['created', 'changed'].includes(on.event)) throw usageError(`Agent ${agent.id} wakes on 'created' or 'changed'.`);
460
+ if (event != null && !['created', 'changed'].includes(event)) throw usageError(`Agent ${agent.id} wakes on 'created' or 'changed'.`);
389
461
  if (agent.thread != null && !['best_match', 'space'].includes(agent.thread)) throw usageError(`Agent ${agent.id} uses thread 'best_match' or 'space'.`);
390
462
  if (agent.runtime != null && !['notis', 'cloud_computer'].includes(agent.runtime)) throw usageError(`Agent ${agent.id} runs on 'notis' or 'cloud_computer'.`);
391
463
  if (agent.wake != null && !['all', 'sent'].includes(agent.wake)) throw usageError(`Agent ${agent.id} wakes for 'all' comments or only those 'sent' to it.`);
@@ -397,9 +469,11 @@ export function validateSpaceAgents(agents, resources = {}) {
397
469
  }
398
470
  }
399
471
 
400
- const THREAD_ITEM_FIELDS = ['label', 'description', 'inputs', 'read', 'title', 'url', 'states', 'checks', 'actions', 'page'];
472
+ const THREAD_ITEM_FIELDS = ['label', 'description', 'inputs', 'read', 'title', 'url', 'states', 'checks', 'actions', 'page', 'settle'];
473
+ // Field names a kind's settle function must take: the server compares the whole schema (threadSettleInput).
474
+ const SETTLE_INPUT_FIELDS = 'item,thread';
401
475
  const THREAD_ITEM_STATE_FIELDS = ['id', 'label', 'icon', 'when', 'needsYou', 'final'];
402
- const THREAD_ITEM_ACTION_FIELDS = ['label', 'tool', 'arguments', 'confirm', 'states', 'primary'];
476
+ const THREAD_ITEM_ACTION_FIELDS = ['label', 'tool', 'function', 'arguments', 'confirm', 'states', 'primary'];
403
477
  const REFUSED_ITEM_TOOL = /^(LOCAL_|COMPOSIO_|NOTIS_|CUSTOM_|MCP_)/;
404
478
 
405
479
  function threadItemLabel(value) {
@@ -413,7 +487,7 @@ function threadItemLabel(value) {
413
487
  * mistake fails before the build; server/lib/space_thread_items.py repeats every check, including
414
488
  * placeholders and conditions, when the Space is published.
415
489
  */
416
- export function validateThreadItems(threadItems, actions = {}) {
490
+ export function validateThreadItems(threadItems, actions = {}, functions = {}) {
417
491
  const kinds = threadItems && typeof threadItems === 'object' && !Array.isArray(threadItems) ? Object.entries(threadItems) : null;
418
492
  if (!kinds || kinds.length < 1 || kinds.length > 8) throw usageError('Declare threadItems as 1 to 8 item kinds.');
419
493
  for (const [kind, spec] of kinds) {
@@ -451,12 +525,41 @@ export function validateThreadItems(threadItems, actions = {}) {
451
525
  throw usageError(`Action ${actionId} of thread item ${kind} takes ${THREAD_ITEM_ACTION_FIELDS.join(', ')} only.`);
452
526
  }
453
527
  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.`);
528
+ if (Object.hasOwn(action, 'tool') === Object.hasOwn(action, 'function')) {
529
+ throw usageError(`Action ${actionId} of thread item ${kind} runs one connected app tool (tool) or one of this Space's functions (function), not both.`);
530
+ }
531
+ if (Object.hasOwn(action, 'function')) {
532
+ if (typeof action.function !== 'string' || !Object.hasOwn(functions || {}, action.function)) {
533
+ throw usageError(`Action ${actionId} of thread item ${kind} names a function this Space does not declare.`);
534
+ }
535
+ } else if (typeof action.tool !== 'string' || !/^[A-Z][A-Z0-9]*(_[A-Z0-9]+)+$/.test(action.tool) || REFUSED_ITEM_TOOL.test(action.tool)) {
536
+ throw usageError(`Action ${actionId} of thread item ${kind} runs one connected app tool, such as GITHUB_MERGE_A_PULL_REQUEST, or one of this Space's functions.`);
456
537
  }
457
538
  if (action.states != null && (!Array.isArray(action.states) || action.states.some(id => !stateIds.has(id)))) {
458
539
  throw usageError(`Action ${actionId} of thread item ${kind} lists states this item declares.`);
459
540
  }
460
541
  }
542
+ if (spec.settle !== undefined) validateThreadItemSettle(kind, spec, functions);
543
+ }
544
+ }
545
+
546
+ /**
547
+ * `settle: { function }`: one of this Space's functions, taking threadSettleInput, that Notis runs once when an
548
+ * item of this kind first reaches a final state (truth FAC-065).
549
+ */
550
+ function validateThreadItemSettle(kind, spec, functions) {
551
+ const settle = spec.settle;
552
+ if (!settle || typeof settle !== 'object' || Array.isArray(settle) || Object.keys(settle).join(',') !== 'function'
553
+ || typeof settle.function !== 'string') {
554
+ throw usageError(`Thread item ${kind} settles with one of this Space's functions: settle: { function: '<name>' }.`);
555
+ }
556
+ if (!Object.hasOwn(functions || {}, settle.function)) {
557
+ throw usageError(`Thread item ${kind} settles with function ${settle.function}, which this Space does not declare.`);
558
+ }
559
+ if (Object.keys(functions[settle.function]?.input?.properties || {}).sort().join(',') !== SETTLE_INPUT_FIELDS) {
560
+ throw usageError(`Function ${settle.function} settles thread item ${kind}: declare its input as threadSettleInput from @notis/sdk.`);
561
+ }
562
+ if (!spec.states.some(state => state.final === true)) {
563
+ throw usageError(`Thread item ${kind} settles when an item reaches a final state: mark at least one state final.`);
461
564
  }
462
565
  }
@@ -74,12 +74,31 @@ function checkContextFields(value,where) {
74
74
  /**
75
75
  * The states verify opens the view in: `contexts` (1 to 4 named ones, each with optional params, now and locale), or
76
76
  * the one `context`, named default. Each entry keeps the object the view receives as its runtime context.
77
+ * `context.views`, the further params the Spaces review deck draws (portal/scripts/spaces-boundary), are states too:
78
+ * the first 3 that open another link than the context (key order, text or number, and a declared default do not
79
+ * count) follow default, each named view-<place in the list>, with the context's now and locale. The deck draws them all.
77
80
  */
78
- function fixtureContexts(fixtures) {
81
+ function fixtureContexts(fixtures,declared={}) {
79
82
  if(fixtures.contexts===undefined) {
80
83
  const value=fixtures.context || {};
81
84
  checkContextFields(value,'The fixture context');
82
- return [{name:'default',context:value}];
85
+ if(value.views===undefined) return [{name:'default',context:value}];
86
+ if(!Array.isArray(value.views) || value.views.some(item=>!object(item))) {
87
+ throw usageError('The fixture context views must be a list of view params, such as [{"period": "week"}].');
88
+ }
89
+ const {views,...base}=value;
90
+ // One link is one view, as the deck reads it: a declared default is left out of the link and 10 is "10".
91
+ const link=params=>JSON.stringify(Object.entries(params || {})
92
+ .filter(([name,item])=>!(object(declared[name]) && Object.hasOwn(declared[name],'default') && String(declared[name].default)===String(item)))
93
+ .map(([name,item])=>[name,String(item)]).sort(([a],[b])=>a<b ? -1 : a>b ? 1 : 0));
94
+ const seen=new Set([link(base.params)]),extra=[];
95
+ views.forEach((params,index)=>{
96
+ checkContextFields({params},`The fixture context view ${index+1}`);
97
+ if(seen.has(link(params)) || extra.length>=FIXTURE_CONTEXTS_MAX-1) return;
98
+ seen.add(link(params));
99
+ extra.push({name:`view-${index+1}`,context:{...base,params}});
100
+ });
101
+ return [{name:'default',context:base},...extra];
83
102
  }
84
103
  if(fixtures.context!==undefined) throw usageError('Verification fixtures declare either context or contexts, not both. Move context into contexts as one named entry.');
85
104
  const list=fixtures.contexts;
@@ -164,7 +183,7 @@ export function createSpaceFixtureEngine(release) {
164
183
  }
165
184
  if(!object(fixtures) || Object.keys(fixtures).some(key=>!['actions','context','contexts','documentBodies','viewerReads','shown','recordViews','images'].includes(key)) || !object(fixtures.actions)
166
185
  || (fixtures.context!==undefined && !object(fixtures.context))) throw usageError('Verification fixtures declare actions and optional synthetic context.');
167
- const contexts=fixtureContexts(fixtures);
186
+ const contexts=fixtureContexts(fixtures,release.manifest.params || {});
168
187
  const images=new Map(fixtureImageEntries(fixtures,release.fixturePath).map(entry=>{
169
188
  const encoded=release.sourceFiles[entry.path];
170
189
  if(typeof encoded!=='string') throw usageError(`Fixture image ${entry.path} for ${entry.url} is missing from the Space folder.`);
@@ -289,6 +308,9 @@ export function createSpaceFixtureEngine(release) {
289
308
  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.');
290
309
  if(entry.operation==='report' && (typeof value.source!=='string' || typeof value.export_name!=='string')) throw usageError('Report fixtures contain an explicit readonly source and export.');
291
310
  }
311
+ const declaredParams=release.manifest.params || {};
312
+ const withoutDeclaredDefaults=params=>Object.fromEntries(Object.entries(params).filter(([key,value])=>!(object(declaredParams[key])
313
+ && Object.hasOwn(declaredParams[key],'default') && String(declaredParams[key].default)===String(value))));
292
314
  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
315
  imageUrls:[...images.keys()],
294
316
  executeImage(url) {
@@ -314,26 +336,41 @@ export function createSpaceFixtureEngine(release) {
314
336
  executeShown(name,params,options={}) {
315
337
  if(!Object.hasOwn(declaredLists,name)) throw usageError('This view does not declare that list.');
316
338
  if(!object(params)) throw usageError('List params must be an object.');
317
- const matched=shownCases[name]?.find(entry=>isDeepStrictEqual(entry.params,params));
318
- if(!matched) throw usageError(`Add an explicit synthetic shown fixture for ${name} and these params.`);
339
+ const cases=shownCases[name] || [];
340
+ // A param left at its declared default is the same read as one without it (as a view link leaves it out),
341
+ // so {"status": "<its default>"} is served by the {} case. Any other param still needs its own case.
342
+ const matched=cases.find(entry=>isDeepStrictEqual(entry.params,params))
343
+ || cases.find(entry=>isDeepStrictEqual(withoutDeclaredDefaults(entry.params),withoutDeclaredDefaults(params)));
344
+ if(!matched) {
345
+ const have=cases.slice(0,5).map(entry=>fixtureJson(entry.params)).join(', ');
346
+ throw usageError(`${fixtureWhere} list ${JSON.stringify(name)} was read with params ${fixtureJson(params)}, which no shown fixture matches`
347
+ +` (${cases.length ? `it has ${have}${cases.length>5 ? ', ...' : ''}` : 'it has none'}). Add an explicit synthetic shown fixture for ${name} and these params:`
348
+ +` {"params": ${fixtureJson(params)}, "result": {"rows": []}} in shown.${name}${release.fixturePath ? ` of ${release.fixturePath}` : ''}.`);
349
+ }
319
350
  return shownPage(structuredClone(matched.result),options);
320
351
  },
321
352
  executeViewerRead(operation,input) {
322
353
  if(!Object.hasOwn(VIEWER_READS,operation) || !declaredReads.includes(VIEWER_READS[operation])) throw usageError('This Space does not declare that viewer read.');
323
354
  if(!object(input)) throw usageError('Viewer read inputs must be an object.');
324
355
  const matched=readCases[operation]?.find(entry=>isDeepStrictEqual(entry.input,input));
325
- if(!matched) throw usageError(`Add an explicit synthetic viewer read fixture for ${operation} and this input.`);
356
+ if(!matched) throw usageError(`${fixtureWhere} viewer read ${operation} was called with input ${fixtureJson(input)}, which no viewerReads fixture matches. Add an explicit synthetic viewer read fixture for ${operation} and this input.`);
326
357
  return structuredClone(matched.result);
327
358
  },
328
359
  execute(name,inputs) {
329
360
  const validate=validators.get(name);
330
361
  if(!validate || !object(inputs) || !validate(inputs)) throw usageError('The action inputs do not match this Space declaration.');
331
362
  const matched=fixtures.actions[name]?.find(entry=>isDeepStrictEqual(entry.inputs,inputs));
332
- if(!matched) throw usageError(`Add an explicit synthetic fixture for action ${name} and these inputs.`);
363
+ if(!matched) throw usageError(`${fixtureWhere} action ${name} was read with inputs ${fixtureJson(inputs)}, which no actions fixture matches. Add an explicit synthetic fixture for action ${name} and these inputs.`);
333
364
  return structuredClone(matched.result);
334
365
  } };
335
366
  }
336
367
 
368
+ /** The params or inputs a fixture lacked, as JSON an author can paste (bounded, so a huge input stays readable). */
369
+ function fixtureJson(value) {
370
+ const text=JSON.stringify(value) ?? String(value);
371
+ return text.length>600 ? `${text.slice(0,600)}...` : text;
372
+ }
373
+
337
374
  /** The fixture context a render opens with: the named one of `contexts`, else the first (the only `context`). */
338
375
  export function selectedFixtureContext(engine,name) {
339
376
  const list=engine.contexts || [{name:'default',context:engine.context || {}}];
@@ -111,7 +111,9 @@ export async function verifySpaceRelease(release, { capabilities, timeoutMs = 45
111
111
  return { ...where, mounted: false, status: 'failed', error: 'render_view_failed', loaded: false,
112
112
  message: `At ${place} the view's code failed before it showed anything${value.reason.reason ? `: ${value.reason.reason}` : '.'}` };
113
113
  }
114
- if (!shot?.data_base64) return { ...where, mounted: false, status: 'failed', error: value.reason?.code || 'render_failed',
114
+ // A read the fixtures could not serve stops the render as a lost authority; offline, that is a missing fixture.
115
+ const fixtureMissing = value.reason?.code === 'render_access_changed' && item.broker.calls.some(call => !call.ok && call.error);
116
+ if (!shot?.data_base64) return { ...where, mounted: false, status: 'failed', error: fixtureMissing ? 'fixture_missing' : value.reason?.code || 'render_failed',
115
117
  ...(Array.isArray(value.reason?.blocked) && value.reason.blocked.length ? { blocked_calls: value.reason.blocked } : {}) };
116
118
  const png = Buffer.from(shot.data_base64, 'base64');
117
119
  screenshots.push({ ...where, png });
@@ -11,8 +11,10 @@ import {
11
11
  getProfile,
12
12
  isJwtExpired,
13
13
  loadConfig,
14
+ resolveConfigFile,
14
15
  resolveWorktreeRuntime,
15
16
  } from './profiles.js';
17
+ import { AGENT_RENEW_REQUEST, renewAgentCredentialIfDue } from './agent-credential.js';
16
18
  import { createExpiredAuthError, createInvalidAuthHints } from './auth-recovery.js';
17
19
  import { refreshOAuthCredential } from './oauth.js';
18
20
  import { findUpsell, renderUpsell } from './upsell.js';
@@ -357,6 +359,19 @@ export async function httpRequest({
357
359
  reloadDevJwt(runtime, currentProfile);
358
360
  currentProfile = getActiveWorktreeCredentialProfile(runtime, currentProfile);
359
361
  }
362
+ // A Cloud Computer command's credential naming its agent is renewed once before it lapses; a failed renewal
363
+ // keeps the current token (agent-credential.js).
364
+ if (requireAuth && runtime.credentialKind === 'env' && runtime.agentEnvJwt) {
365
+ await renewAgentCredentialIfDue(runtime, {
366
+ configFile: resolveConfigFile(),
367
+ renew: async () => (await httpRequest({
368
+ runtime,
369
+ path: AGENT_RENEW_REQUEST.path,
370
+ body: AGENT_RENEW_REQUEST.body,
371
+ timeoutMs: Math.min(timeoutMs || AGENT_RENEW_REQUEST.timeoutMs, AGENT_RENEW_REQUEST.timeoutMs),
372
+ })).payload,
373
+ });
374
+ }
360
375
  if (requireAuth && credentialIsExpired(runtime, currentProfile)) {
361
376
  throw createExpiredAuthError(runtime);
362
377
  }