@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,284 @@
1
+ 'use client';
2
+ /**
3
+ * Text comments on every Space page (SPC-118 text mode): Comment on selected words (the shared selection bar, next to
4
+ * Cite) and the highlights of the page's open text comments. Both need the host comment store
5
+ * (`runtime.spaceComments`, on while `unified_comments` is); without it the page shows Cite alone and no highlights.
6
+ *
7
+ * A text comment keeps its words with up to 40 characters before and after them. The highlights find those words
8
+ * again in the page as it is now (white space ignored, the surrounding words telling apart several matches); words
9
+ * that are gone are reported to the host (`passagesChanged`) and the thread card reads Passage changed. A thread is
10
+ * never closed for it. A click on a highlight opens its thread in the host Comments panel (`revealComment`).
11
+ *
12
+ * Words inside a Space's own commentable text (`CommentableText`, `CommentableRichText`) keep their own Comment button
13
+ * and their own highlights: the page bar offers Cite alone there, and comments on a named field are not drawn here.
14
+ */
15
+
16
+ import { useEffect, useId, useMemo, useRef, useState, type RefObject } from 'react';
17
+ import type { NotisRuntime } from '../runtime';
18
+ import type { SpaceCommentAnchor, SpaceCommentRow, SpaceCommentsTransport } from '../space';
19
+ import { PASSAGE_COMMENT_EVENT, locatePassage, passageAt } from '../ui/comments/passageModel';
20
+ import { setChangedPassages } from '../ui/comments/textHighlights';
21
+
22
+ /** Text a passage is never read from: styles, scripts and the selection bar. */
23
+ const SKIP_TEXT = 'style, script, noscript, template, [data-notis-selection-ui], [data-notis-comment-skip]';
24
+ /** A Space's own commentable text: it has its own Comment button and highlights. */
25
+ export const OWN_PASSAGE_TEXT = '.nui-passage-text-field, .nui-passage-rich-text';
26
+ /** A Space's own commentable rich text: the page's selection bar offers Comment on it (SPC-487). */
27
+ const OWN_RICH_TEXT = '.nui-passage-rich-text';
28
+
29
+ export interface PageText { text: string; nodes: Array<{ node: Text; start: number }> }
30
+
31
+ /** The text of a page, in reading order, with where each text node starts in it. */
32
+ export function pageTextOf(root: Node): PageText {
33
+ const owner = root.ownerDocument ?? (root as Document);
34
+ const walker = owner.createTreeWalker(root, 4 /* NodeFilter.SHOW_TEXT */);
35
+ const nodes: PageText['nodes'] = [];
36
+ let text = '';
37
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
38
+ const parent = (node as Text).parentElement;
39
+ if (parent?.closest(SKIP_TEXT)) continue;
40
+ nodes.push({ node: node as Text, start: text.length });
41
+ text += (node as Text).data;
42
+ }
43
+ return { text, nodes };
44
+ }
45
+
46
+ /** Where a range boundary falls in the page text. */
47
+ function offsetOf(page: PageText, container: Node, offset: number): number {
48
+ if (container.nodeType === 3) {
49
+ const hit = page.nodes.find(item => item.node === container);
50
+ if (hit) return hit.start + Math.min(offset, hit.node.data.length);
51
+ }
52
+ const owner = container.ownerDocument ?? (container as Document);
53
+ const point = owner.createRange();
54
+ try {
55
+ point.setStart(container, offset);
56
+ point.collapse(true);
57
+ } catch {
58
+ return page.text.length;
59
+ }
60
+ // The first text node at or after the boundary starts there; none: the end of the text.
61
+ for (const item of page.nodes) {
62
+ try {
63
+ if (point.comparePoint(item.node, 0) >= 0) return item.start;
64
+ } catch { /* another tree */ }
65
+ }
66
+ return page.text.length;
67
+ }
68
+
69
+ /**
70
+ * A text comment's place for the selected `range` of `root`: the selected words (white space collapsed, at most 1000
71
+ * characters) with up to 40 characters before and after them. Null when only white space is selected.
72
+ */
73
+ export function textCommentAnchor(root: Node, range: Range): SpaceCommentAnchor | null {
74
+ const page = pageTextOf(root);
75
+ const start = offsetOf(page, range.startContainer, range.startOffset);
76
+ const end = offsetOf(page, range.endContainer, range.endOffset);
77
+ if (end <= start) return null;
78
+ const passage = passageAt(page.text, start, end);
79
+ return passage ? { mode: 'text', quote: passage.quote, prefix: passage.prefix, suffix: passage.suffix } : null;
80
+ }
81
+
82
+ /** The page's open text comments drawn here: first comments in text mode on no named field, of this view. */
83
+ export function openTextComments(rows: readonly SpaceCommentRow[], view: string | null): SpaceCommentRow[] {
84
+ return rows.filter(row => row && !row.thread_root_id && row.mode === 'text' && row.status === 'open' && !row.field
85
+ && Boolean(row.quote?.trim()) && (!row.view || !view || row.view === view));
86
+ }
87
+
88
+ function lastNode(page: PageText, test: (item: PageText['nodes'][number]) => boolean): PageText['nodes'][number] | undefined {
89
+ for (let index = page.nodes.length - 1; index >= 0; index -= 1) if (test(page.nodes[index]!)) return page.nodes[index];
90
+ return undefined;
91
+ }
92
+
93
+ /** The ranges of each comment's words in the page, and the comments whose words are gone. */
94
+ export function locateTextComments(root: Node, rows: readonly SpaceCommentRow[]): { found: Map<string, Range>; missing: string[] } {
95
+ const page = pageTextOf(root);
96
+ const found = new Map<string, Range>();
97
+ const missing: string[] = [];
98
+ const owner = root.ownerDocument ?? (root as Document);
99
+ for (const row of rows) {
100
+ const hit = locatePassage(page.text, { quote: row.quote ?? '', prefix: row.prefix ?? '', suffix: row.suffix ?? '' });
101
+ if (!hit) { missing.push(row.id); continue; }
102
+ const from = lastNode(page, item => item.start <= hit.start);
103
+ const to = lastNode(page, item => item.start < hit.end);
104
+ if (!from || !to) { missing.push(row.id); continue; }
105
+ const range = owner.createRange();
106
+ try {
107
+ range.setStart(from.node, Math.min(hit.start - from.start, from.node.data.length));
108
+ range.setEnd(to.node, Math.min(hit.end - to.start, to.node.data.length));
109
+ found.set(row.id, range);
110
+ } catch {
111
+ missing.push(row.id);
112
+ }
113
+ }
114
+ return { found, missing };
115
+ }
116
+
117
+ /** The CSS Custom Highlight registry, where the browser has one. */
118
+ type HighlightRegistry = { set(name: string, value: unknown): void; delete(name: string): boolean };
119
+ function highlightApi(view: Window | null | undefined): { registry: HighlightRegistry; Highlight: new (...ranges: Range[]) => unknown } | null {
120
+ const css = (view as unknown as { CSS?: { highlights?: HighlightRegistry } } | null)?.CSS;
121
+ const Highlight = (view as unknown as { Highlight?: new (...ranges: Range[]) => unknown } | null)?.Highlight;
122
+ return css?.highlights && Highlight ? { registry: css.highlights, Highlight } : null;
123
+ }
124
+
125
+ /**
126
+ * The open text comments of the page the host shows, read through the comment store and listed again whenever the
127
+ * host says they may have changed.
128
+ */
129
+ function usePageTextComments(transport: SpaceCommentsTransport | undefined): SpaceCommentRow[] {
130
+ const page = transport?.page?.recordKey ?? null;
131
+ const view = transport?.page?.view ?? null;
132
+ const [rows, setRows] = useState<SpaceCommentRow[]>([]);
133
+ const transportRef = useRef(transport);
134
+ transportRef.current = transport;
135
+ const hasTransport = Boolean(transport);
136
+ useEffect(() => {
137
+ const store = transportRef.current;
138
+ if (!store) { setRows([]); return undefined; }
139
+ let live = true;
140
+ let seq = 0;
141
+ const read = () => {
142
+ const mine = ++seq;
143
+ store.list({ page }).then(answer => {
144
+ if (live && mine === seq) setRows(Array.isArray(answer?.comments) ? answer.comments : []);
145
+ }, () => undefined);
146
+ };
147
+ // The first read waits for the page to go idle: a Space open never contends with the highlights' read and drawing
148
+ // (SPC-859). A change the host announces reads at once.
149
+ const idleWindow = typeof window !== 'undefined' && typeof window.requestIdleCallback === 'function'
150
+ && typeof window.cancelIdleCallback === 'function' ? window : null;
151
+ const cancelIdle = idleWindow?.cancelIdleCallback;
152
+ const idleRead = idleWindow ? idleWindow.requestIdleCallback(read, { timeout: 1500 }) : null;
153
+ const timer = idleWindow ? null : setTimeout(read, 0);
154
+ let stop: (() => void) | undefined;
155
+ try { stop = store.subscribe({ page }, read); } catch { /* no live feed */ }
156
+ return () => {
157
+ live = false;
158
+ if (idleRead !== null) cancelIdle?.call(idleWindow, idleRead);
159
+ if (timer !== null) clearTimeout(timer);
160
+ stop?.();
161
+ };
162
+ }, [hasTransport, page]);
163
+ return useMemo(() => openTextComments(rows, view), [rows, view]);
164
+ }
165
+
166
+ /**
167
+ * Draws the page's open text comments as highlights in `root`, reports the ones whose words are gone, and opens a
168
+ * thread when its highlight is clicked. Renders only its highlight style.
169
+ */
170
+ export function SpaceTextComments({ root, runtime }: { root: RefObject<HTMLElement | null>; runtime: NotisRuntime }) {
171
+ const transport = runtime.spaceComments;
172
+ const rows = usePageTextComments(transport);
173
+ const name = `notis-comment-${useId().replace(/[^a-zA-Z0-9_-]/g, '')}`;
174
+ const located = useRef<Map<string, Range>>(new Map());
175
+ const transportRef = useRef(transport);
176
+ transportRef.current = transport;
177
+ const page = transport?.page?.recordKey ?? null;
178
+
179
+ useEffect(() => {
180
+ const element = root.current;
181
+ if (!element || !transport) return undefined;
182
+ const view = element.ownerDocument.defaultView;
183
+ const api = highlightApi(view);
184
+ let frame = 0;
185
+ let reported = '';
186
+ const draw = () => {
187
+ frame = 0;
188
+ const { found, missing } = locateTextComments(element, rows);
189
+ located.current = found;
190
+ if (api) {
191
+ if (found.size) api.registry.set(name, new api.Highlight(...found.values()));
192
+ else api.registry.delete(name);
193
+ }
194
+ setChangedPassages(missing);
195
+ const key = [...missing].sort().join('|');
196
+ if (key !== reported) {
197
+ reported = key;
198
+ try { transportRef.current?.passagesChanged?.({ page, ids: missing }); } catch { /* the host may not listen */ }
199
+ }
200
+ };
201
+ draw();
202
+ // The page changes under the comments (an edit, a page of results): find the words again once per frame.
203
+ const Observer = view?.MutationObserver;
204
+ const observer = Observer ? new Observer(() => {
205
+ if (!frame) frame = view?.requestAnimationFrame?.(draw) ?? 0;
206
+ if (!frame) draw();
207
+ }) : null;
208
+ observer?.observe(element, { childList: true, subtree: true, characterData: true });
209
+ return () => {
210
+ observer?.disconnect();
211
+ if (frame) view?.cancelAnimationFrame?.(frame);
212
+ api?.registry.delete(name);
213
+ located.current = new Map();
214
+ };
215
+ }, [root, transport, rows, name, page]);
216
+
217
+ // A click on highlighted words (not the end of a selection) opens their thread in the host Comments panel.
218
+ useEffect(() => {
219
+ const element = root.current;
220
+ if (!element || !transport?.revealComment) return undefined;
221
+ const onClick = (event: MouseEvent) => {
222
+ if (event.button !== 0 || event.defaultPrevented) return;
223
+ const selection = element.ownerDocument.getSelection?.();
224
+ if (selection && !selection.isCollapsed) return;
225
+ for (const [id, range] of located.current) {
226
+ const hit = Array.from(range.getClientRects?.() ?? []).some(rect => event.clientX >= rect.left
227
+ && event.clientX <= rect.right && event.clientY >= rect.top && event.clientY <= rect.bottom);
228
+ if (hit) { transportRef.current?.revealComment?.(id); return; }
229
+ }
230
+ };
231
+ element.addEventListener('click', onClick);
232
+ return () => element.removeEventListener('click', onClick);
233
+ }, [root, transport]);
234
+
235
+ if (!transport || !rows.length) return null;
236
+ // Theme tokens only: the page's primary color, see-through.
237
+ return <style data-notis-comment-highlights>{`::highlight(${name}) { background-color: hsl(var(--primary) / .18); }`}</style>;
238
+ }
239
+
240
+ /** The Space's own commentable text a selection lies in, if any. */
241
+ function ownTextOf(range: Range): Element | null {
242
+ const container = range.commonAncestorContainer;
243
+ const element = container.nodeType === 1 ? container as Element : container.parentElement;
244
+ return element?.closest(OWN_PASSAGE_TEXT) ?? null;
245
+ }
246
+
247
+ /**
248
+ * Whether the bar's Comment may start a comment on this selection: page text, and a Space's own commentable rich text
249
+ * (the bar hands it the selection, SPC-487), never a text field (its own Comment button stays).
250
+ */
251
+ export function canCommentOnPage(range: Range): boolean {
252
+ const own = ownTextOf(range);
253
+ return !own || own.matches(OWN_RICH_TEXT);
254
+ }
255
+
256
+ /**
257
+ * The bar's Comment on a selection: inside a Space's own commentable rich text that text starts its own new comment
258
+ * on the words; elsewhere the host's new text comment opens on them. False when nothing took it.
259
+ */
260
+ export function commentOnSelection(runtime: NotisRuntime, root: Node | null, range: Range): boolean {
261
+ const own = ownTextOf(range);
262
+ if (own) {
263
+ if (!own.matches(OWN_RICH_TEXT)) return false;
264
+ const view = own.ownerDocument?.defaultView;
265
+ const Custom = view?.CustomEvent ?? CustomEvent;
266
+ // Cancelled by the text once it opened the comment.
267
+ return !own.dispatchEvent(new Custom(PASSAGE_COMMENT_EVENT, { detail: { range }, cancelable: true }));
268
+ }
269
+ return startTextComment(runtime, root, range);
270
+ }
271
+
272
+ /** Hands a selection to the host's new text comment. False when there is nothing to comment on or no host for it. */
273
+ export function startTextComment(runtime: NotisRuntime, root: Node | null, range: Range): boolean {
274
+ const transport = runtime.spaceComments;
275
+ if (!transport?.startComment || !root) return false;
276
+ const anchor = textCommentAnchor(root, range);
277
+ if (!anchor) return false;
278
+ transport.startComment({
279
+ ...anchor,
280
+ page_key: transport.page?.recordKey ?? null,
281
+ view: transport.page?.view ?? null,
282
+ });
283
+ return true;
284
+ }
@@ -1,6 +1,8 @@
1
1
  export { defineSpace, defineSpaces } from './space';
2
- export type { SpaceDefinition, SpacesWorkspace, SpaceActionTemplate, SpaceResourceReference, SpaceDatabaseCreate } from './space';
2
+ export type { SpaceDefinition, SpacesWorkspace, SpaceActionTemplate, SpaceResourceReference, SpaceDatabaseCreate, SpaceStore } from './space';
3
3
  export type { SpaceViewParam, SpaceViewParamType, SpaceShows, SpaceMemoryPolicy, SpaceMemorySnapshot, SpaceChrome, SpaceMarkdownInput } from './space';
4
+ export { threadHookInput, threadSettleInput, commentOptionInput } from './functions';
5
+ export type { SpaceFunctionDeclaration, SpaceFunctionHandler, SpaceFunctionContext } from './functions';
4
6
 
5
7
  /**
6
8
  * Configuration utilities for notis.config.ts and Space definitions.
@@ -0,0 +1,203 @@
1
+ /**
2
+ * Space functions: server code a Space declares once in `defineSpace({ functions })` and Notis calls from the
3
+ * Space's views (`useFunction`), its HTTP API and MCP server, Notis agents, thread items, thread hooks and comment
4
+ * options. A handler never reaches the browser, has no network and no secrets, and reaches only what `uses` lists.
5
+ *
6
+ * ```ts
7
+ * // space.config.ts
8
+ * functions: {
9
+ * count_open: {
10
+ * description: 'Count the open pull requests of a repository.',
11
+ * kind: 'read',
12
+ * input: { type: 'object', additionalProperties: false, required: ['repo'], properties: { repo: { type: 'string' } } },
13
+ * expose: ['page', 'api', 'agents'],
14
+ * access: ['viewer', 'editor', 'key'],
15
+ * uses: { actions: ['list_pull_requests'] },
16
+ * handler: './functions/count-open.ts',
17
+ * },
18
+ * },
19
+ *
20
+ * // functions/count-open.ts
21
+ * import type { SpaceFunctionHandler } from '@notis/sdk';
22
+ * const handler: SpaceFunctionHandler<{ repo: string }, { open: number }> = async (input, ctx) => {
23
+ * const pulls = await ctx.actions.list_pull_requests({ repo: input.repo }) as { items: unknown[] };
24
+ * return { open: pulls.items.length };
25
+ * };
26
+ * export default handler;
27
+ * ```
28
+ *
29
+ * A handler module imports types only from `@notis/sdk`: the SDK's code is for the page, not for functions.
30
+ */
31
+ import type { SpaceCloudComputerLevel, SpaceThreadItemText } from './space';
32
+
33
+ /** What a call does: `read` changes nothing, `write` changes this Space's data, `action` reaches further. */
34
+ export type SpaceFunctionKind = 'read' | 'write' | 'action';
35
+ /** The ways in from outside the Space's own declarations: its views, its API and MCP server, Notis agents. */
36
+ export type SpaceFunctionExposure = 'page' | 'api' | 'agents';
37
+ /** Who may call: a Site or link visitor, a signed-in person who can open the Space, an editor, a Space key. */
38
+ export type SpaceFunctionRole = 'public' | 'viewer' | 'editor' | 'key';
39
+ /** Notis's built-in thread actions a function may run, only on a thread one of the Space's items is attached to. */
40
+ export type SpaceThreadOperation = 'archive' | 'unarchive' | 'read' | 'unread' | 'star' | 'unstar' | 'later' | 'back';
41
+ /** The built-in thread actions a Space can follow with a function (`threadHooks`). */
42
+ export type SpaceThreadHookEvent = SpaceThreadOperation | 'delete';
43
+
44
+ export interface SpaceFunctionUses {
45
+ /** This Space's declared `actions`, run through the sealed action pipeline with the caller as the actor. */
46
+ actions?: string[];
47
+ /** The caller's own cloud computer, at most the level the Space declares, once that person allowed it. */
48
+ cloudComputer?: SpaceCloudComputerLevel;
49
+ /** Built-in thread actions on a thread holding one of this Space's items. Needs `threadItems`. */
50
+ threads?: SpaceThreadOperation[];
51
+ }
52
+
53
+ export interface SpaceFunctionDeclaration {
54
+ /** What the function does and when to call it: agents read it as the tool's description. */
55
+ description: string;
56
+ kind: SpaceFunctionKind;
57
+ /** A closed object schema (`additionalProperties: false`), checked before the handler runs. */
58
+ input: { type: 'object'; additionalProperties: false; properties?: Record<string, unknown>; required?: readonly string[];
59
+ [key: string]: unknown };
60
+ /** Checked on what the handler returns, and given to agents as the tool's output schema. */
61
+ output?: Record<string, unknown>;
62
+ /** Default: none. A closed function still runs from this Space's thread items, thread hooks and comment options. */
63
+ expose?: SpaceFunctionExposure[];
64
+ /** Default: editors only. The handler reads the caller's role in `ctx.caller.role`. */
65
+ access?: SpaceFunctionRole[];
66
+ /** Everything the handler can reach. Undeclared: the handler only computes. */
67
+ uses?: SpaceFunctionUses;
68
+ /** Source-relative module whose default export is the handler. */
69
+ handler: string;
70
+ }
71
+
72
+ /** A comment option that runs a function when a person answers a choice comment with it (`commentOptions`). */
73
+ export interface SpaceCommentOption {
74
+ /** The option as people read it; an agent offers it by writing this label in a choice comment's options. */
75
+ label: SpaceThreadItemText;
76
+ /** A function whose `input` is `commentOptionInput`. */
77
+ function: string;
78
+ }
79
+
80
+ /** The `input` of a function a thread hook runs (`threadHooks`): copy it as written. */
81
+ export const threadHookInput = {
82
+ type: 'object', additionalProperties: false, required: ['event', 'thread', 'items', 'actor'],
83
+ properties: {
84
+ event: { type: 'string', enum: ['archive', 'unarchive', 'read', 'unread', 'star', 'unstar', 'later', 'back', 'delete'] },
85
+ actor: { type: 'string', enum: ['person', 'agent', 'notis'] },
86
+ thread: { type: 'object', additionalProperties: false, required: ['id', 'thread_id'], properties: {
87
+ id: { type: 'string' }, thread_id: { type: 'string' }, title: { type: ['string', 'null'] },
88
+ archived: { type: 'boolean' }, starred: { type: 'boolean' }, read: { type: 'boolean' },
89
+ later_until: { type: ['string', 'null'] } } },
90
+ items: { type: 'array', items: { type: 'object', additionalProperties: false,
91
+ required: ['id', 'kind', 'inputs'], properties: {
92
+ id: { type: 'string' }, kind: { type: 'string' }, inputs: { type: 'object' },
93
+ state: { type: ['string', 'null'] }, title: { type: ['string', 'null'] },
94
+ url: { type: ['string', 'null'] } } } },
95
+ },
96
+ } satisfies SpaceFunctionDeclaration['input'];
97
+
98
+ /**
99
+ * The `input` of the function a thread item kind settles with (`threadItems.<kind>.settle`): copy it as written.
100
+ * Notis runs it once when an item of that kind first reaches a final state, with the item and its thread.
101
+ */
102
+ export const threadSettleInput = {
103
+ type: 'object', additionalProperties: false, required: ['item', 'thread'],
104
+ properties: {
105
+ item: { type: 'object', additionalProperties: false, required: ['id', 'kind', 'inputs'], properties: {
106
+ id: { type: 'string' }, kind: { type: 'string' }, inputs: { type: 'object' },
107
+ state: { type: ['string', 'null'] }, title: { type: ['string', 'null'] },
108
+ url: { type: ['string', 'null'] } } },
109
+ thread: { type: 'object', additionalProperties: false, required: ['id', 'thread_id'], properties: {
110
+ id: { type: 'string' }, thread_id: { type: 'string' }, title: { type: ['string', 'null'] },
111
+ archived: { type: 'boolean' }, starred: { type: 'boolean' }, read: { type: 'boolean' },
112
+ later_until: { type: ['string', 'null'] } } },
113
+ },
114
+ } satisfies SpaceFunctionDeclaration['input'];
115
+
116
+ /** The `input` of a function a comment option runs (`commentOptions`): copy it as written. */
117
+ export const commentOptionInput = {
118
+ type: 'object', additionalProperties: false, required: ['option', 'comment'],
119
+ properties: {
120
+ option: { type: 'string' },
121
+ comment: { type: 'object', additionalProperties: false, required: ['id'], properties: {
122
+ id: { type: 'string' }, body: { type: 'string' }, view: { type: ['string', 'null'] },
123
+ page_key: { type: ['string', 'null'] },
124
+ anchor_keys: { type: 'array', items: { type: 'string' } } } },
125
+ },
126
+ } satisfies SpaceFunctionDeclaration['input'];
127
+
128
+ /** One of the Space's items on a thread, as a hook or an item action receives it. */
129
+ export interface SpaceFunctionThreadItem {
130
+ id: string; kind: string; inputs: Record<string, unknown>;
131
+ state?: string | null; title?: string | null; url?: string | null;
132
+ }
133
+ /** A thread as a function sees it. `id` is what `ctx.threads` takes. */
134
+ export interface SpaceFunctionThread {
135
+ id: string; thread_id: string; title?: string | null;
136
+ archived?: boolean; starred?: boolean; read?: boolean; later_until?: string | null;
137
+ }
138
+ /** What a thread hook's function receives: the built-in action that just happened, and who did it. */
139
+ export interface SpaceThreadHookInput {
140
+ event: SpaceThreadHookEvent;
141
+ /** The person, one of their agents, or Notis itself (an automatic change, or another function's thread action). */
142
+ actor: 'person' | 'agent' | 'notis';
143
+ thread: SpaceFunctionThread;
144
+ /** This Space's items attached to the thread. */
145
+ items: SpaceFunctionThreadItem[];
146
+ }
147
+ /** What a thread item kind's settle function receives: the item that reached a final state, and its thread. */
148
+ export interface SpaceThreadSettleInput {
149
+ item: SpaceFunctionThreadItem;
150
+ thread: SpaceFunctionThread;
151
+ }
152
+ /** What a comment option's function receives. */
153
+ export interface SpaceCommentOptionInput {
154
+ /** The id of the declared option. */
155
+ option: string;
156
+ comment: { id: string; body?: string; view?: string | null; page_key?: string | null; anchor_keys?: string[] };
157
+ }
158
+
159
+ export interface SpaceFunctionCloudComputer {
160
+ facts(): Promise<Record<string, unknown>>;
161
+ /** Needs `uses.cloudComputer: 'shell'`. `cwd` is a folder inside the machine's workspace. */
162
+ run(input: { command: string; cwd?: string; timeoutMs?: number }): Promise<{ exit_code: number | null; output: string;
163
+ [key: string]: unknown }>;
164
+ }
165
+
166
+ /** What a handler can reach: nothing beyond the function's declared `uses`. */
167
+ export interface SpaceFunctionContext {
168
+ /** Who is calling. `userId` is null for a Site or link visitor and for a Space key. */
169
+ caller: { role: SpaceFunctionRole; userId: string | null };
170
+ space: { id: string; revision: number };
171
+ /** The way this call came in. */
172
+ via: SpaceFunctionExposure | 'thread_item' | 'thread_hook' | 'thread_settle' | 'comment_option';
173
+ /** One method per action named in `uses.actions`: the action's result, or a thrown error. */
174
+ actions: Record<string, (inputs?: Record<string, unknown>) => Promise<unknown>>;
175
+ /** The caller's own cloud computer. Calls throw until that person allowed this Space to use it. */
176
+ cloudComputer: SpaceFunctionCloudComputer;
177
+ /**
178
+ * Built-in thread actions named in `uses.threads`, by thread `id`. Notis refuses a thread none of this Space's
179
+ * items is attached to. `later` takes the time the thread comes back, as an ISO date with its zone.
180
+ */
181
+ threads: { [Operation in SpaceThreadOperation]: Operation extends 'later'
182
+ ? (threadId: string, until: string) => Promise<void> : (threadId: string) => Promise<void> };
183
+ /** Set when a thread item's action or settle runs the function: the item and its thread. */
184
+ item?: SpaceFunctionThreadItem & { thread: SpaceFunctionThread };
185
+ }
186
+
187
+ export type SpaceFunctionHandler<TInput = Record<string, unknown>, TOutput = unknown> =
188
+ (input: TInput, ctx: SpaceFunctionContext) => TOutput | Promise<TOutput>;
189
+
190
+ /** A function the page can call, as the host describes it (`runtime.space.functions`). */
191
+ export interface SpaceFunctionDescriptor {
192
+ kind: SpaceFunctionKind;
193
+ description?: string;
194
+ inputSchema: Record<string, unknown>;
195
+ outputSchema?: Record<string, unknown>;
196
+ /** True when visitors may call it too: what "view as the public" keeps. */
197
+ public?: boolean;
198
+ }
199
+
200
+ export interface SpaceFunctionCallOptions {
201
+ /** A caller-controlled idempotency key, kept across a deliberate retry of a write or an action. */
202
+ requestId?: string;
203
+ }
@@ -1,6 +1,6 @@
1
1
  'use client';
2
2
 
3
- import { useCallback, useEffect } from 'react';
3
+ import { useCallback, useEffect, useRef } from 'react';
4
4
  import { useQuery } from './useQuery';
5
5
  import { useNotisRuntime } from '../provider';
6
6
  import { pick, w, type Words } from '../words/types';
@@ -13,11 +13,8 @@ export const AGENT_QUEUE_WORDS = Object.freeze({
13
13
  idle: w('Idle', 'Inactif'),
14
14
  queued: w('Queued', 'En file d’attente'),
15
15
  working: w('Working', 'En cours'),
16
- waiting: w('Waiting for you', 'Attend ta réponse'),
17
16
  failed: w('Failed', 'Échec'),
18
17
  done: w('Done', 'Terminé'),
19
- approvalRequired: w('Allow this agent to answer your comments', 'Autorise cet agent à répondre à tes commentaires'),
20
- approve: w('Allow', 'Autoriser'),
21
18
  openThread: w('Open the conversation', 'Ouvrir la conversation'),
22
19
  unavailable: w('Agents are not available here', 'Les agents ne sont pas disponibles ici'),
23
20
  } satisfies Record<string, Words>);
@@ -28,19 +25,12 @@ export interface UseAgentQueueResult {
28
25
  label: string;
29
26
  /** The thread the agent works in for this scope; null until it first woke. */
30
27
  threadId: string | null;
31
- /** Items waiting in the quiet window (or for approval). */
28
+ /** Items waiting in the quiet window. */
32
29
  pending: number;
33
- /** True until the viewer allows this version's agents; offer `approve()`. */
34
- approvalRequired: boolean;
35
- /** Ask the viewer's permission for this Space version's agents. Held comments then wake their thread. */
36
- approve: () => Promise<boolean>;
37
30
  /** Open the agent's thread in the side chat. Resolves false when there is none or the host has no side chat. */
38
31
  openThread: () => Promise<boolean>;
39
32
  /** The link label in the viewer's language. */
40
33
  openLabel: string;
41
- /** Why to allow (`approvalRequired`) and the Allow button, in the viewer's language. */
42
- approvalLabel: string;
43
- approveLabel: string;
44
34
  loading: boolean;
45
35
  error: Error | null;
46
36
  /** False on hosts without agents (Sites, links, the dev harness). */
@@ -48,7 +38,7 @@ export interface UseAgentQueueResult {
48
38
  refresh: () => Promise<Error | null>;
49
39
  }
50
40
 
51
- const IDLE: SpaceAgentQueue = { status: 'idle', thread_id: null, pending: 0, approval_required: false, updated_at: null };
41
+ const IDLE: SpaceAgentQueue = { status: 'idle', thread_id: null, pending: 0, updated_at: null };
52
42
  const ACTIVE_POLL_MS = 4_000;
53
43
  const IDLE_POLL_MS = 15_000;
54
44
 
@@ -58,14 +48,13 @@ function visible(): boolean {
58
48
 
59
49
  /**
60
50
  * One declared agent's latest wake-up for the signed-in viewer: Queued (in the 20 second quiet window),
61
- * Working, Waiting for you, Failed or Done, with a link to its thread.
51
+ * Working, Failed or Done, with a link to its thread. A comment wakes its agent with no approval first.
62
52
  *
63
53
  * ```tsx
64
54
  * const queue = useAgentQueue('editor', deckKey);
65
55
  * return (
66
56
  * <span>
67
57
  * {queue.label}
68
- * {queue.approvalRequired ? <Button onClick={() => void queue.approve()}>{queue.approveLabel}</Button> : null}
69
58
  * {queue.threadId ? <Button onClick={() => void queue.openThread()}>{queue.openLabel}</Button> : null}
70
59
  * </span>
71
60
  * );
@@ -83,40 +72,40 @@ export function useAgentQueue(agentId: string, scope?: string | null): UseAgentQ
83
72
  const query = useQuery<SpaceAgentQueue>(['agent-queue', agentId, scopeKey], async () => {
84
73
  if (!transport) return IDLE;
85
74
  const status = await transport.agentStatus(agentId, scopeKey ?? undefined);
86
- return status.queue ? { ...IDLE, ...status.queue } : { ...IDLE, approval_required: !status.approved };
75
+ return status.queue ? { ...IDLE, ...status.queue } : IDLE;
87
76
  }, { readOnly: true, enabled: Boolean(transport) && Boolean(agentId), staleTimeMs: 2_000 });
88
77
  const queue = query.data ?? IDLE;
89
78
  const active = queue.status === 'queued' || queue.status === 'working' || queue.pending > 0;
90
79
  const refetch = query.refetch;
80
+ // A read still on its way is never replaced by the next tick: a refetch drops the read in flight, so a status read
81
+ // slower than the 4 second tick (a busy account) never landed and the label kept its first answer for good.
82
+ const fetching = useRef(false);
83
+ fetching.current = query.isFetching;
91
84
  // An interval, not a timeout keyed on the answer: a run reads the same "working" for minutes, and a
92
85
  // timeout that waits for a changed answer stopped after one read and left "Working" on screen. While
93
86
  // idle it still reads now and then, so a comment (yours or someone else's) shows "Queued" without a reload.
94
87
  useEffect(() => {
95
88
  if (!transport) return undefined;
96
- const timer = setInterval(() => { if (visible()) void refetch(); }, active ? ACTIVE_POLL_MS : IDLE_POLL_MS);
89
+ let reading = false;
90
+ const timer = setInterval(() => {
91
+ if (!visible() || reading || fetching.current) return;
92
+ reading = true;
93
+ void refetch().finally(() => { reading = false; });
94
+ }, active ? ACTIVE_POLL_MS : IDLE_POLL_MS);
97
95
  return () => clearInterval(timer);
98
96
  }, [active, refetch, transport]);
99
- const approve = useCallback(async () => {
100
- if (!transport) return false;
101
- const result = await transport.approveAgents();
102
- await refetch();
103
- return result.approved === true;
104
- }, [refetch, transport]);
105
97
  const openThread = useCallback(async () => {
106
98
  if (!transport || !queue.thread_id) return false;
107
99
  return transport.open(queue.thread_id);
108
100
  }, [queue.thread_id, transport]);
109
101
  return {
110
102
  status: queue.status,
111
- label: pick(transport ? AGENT_QUEUE_WORDS[queue.status] : AGENT_QUEUE_WORDS.unavailable, locale),
103
+ // A status this SDK has no word for (an older API's 'waiting', or none) reads as idle, never a crash.
104
+ label: pick(transport ? (AGENT_QUEUE_WORDS[queue.status] ?? AGENT_QUEUE_WORDS.idle) : AGENT_QUEUE_WORDS.unavailable, locale),
112
105
  threadId: queue.thread_id,
113
106
  pending: queue.pending,
114
- approvalRequired: queue.approval_required,
115
- approve,
116
107
  openThread,
117
108
  openLabel: pick(AGENT_QUEUE_WORDS.openThread, locale),
118
- approvalLabel: pick(AGENT_QUEUE_WORDS.approvalRequired, locale),
119
- approveLabel: pick(AGENT_QUEUE_WORDS.approve, locale),
120
109
  loading: query.loading,
121
110
  error: query.error,
122
111
  available: Boolean(transport),
@@ -123,6 +123,8 @@ export interface CollectionInteractionController<T> {
123
123
  * that removes the active item continues this way (iOS Photos), else the other way at the edge.
124
124
  */
125
125
  travelDirection: () => TravelDirection;
126
+ /** Moves the active item one step, as J/K or the arrows do (a swipe between open items on a phone). */
127
+ move: (direction: CollectionNavigationDirection) => void;
126
128
  getActionBarProps: () => Pick<MultiSelectActionBarProps, 'selectedCount' | 'actions' | 'collectionOwnerId' | 'isAvailable' | 'shortcutsEnabled' | 'onClearSelection'>;
127
129
 
128
130
  isSelected: (id: string) => boolean;
@@ -325,7 +327,7 @@ export function useCollectionInteractions<T>(
325
327
  const next = id && selectableIdsRef.current.includes(id) ? id : null;
326
328
  if (activeIdRef.current === next) return;
327
329
  // A click or focus further up or down sets the way; keys set it themselves (moveActive), a wrap included.
328
- const travel = reason === 'items-changed' ? null : travelBetween(selectableIdsRef.current, activeIdRef.current, next);
330
+ const travel = reason === 'items-changed' || reason === 'navigate' ? null : travelBetween(selectableIdsRef.current, activeIdRef.current, next);
329
331
  if (travel) travelRef.current = travel;
330
332
  activeIdRef.current = next;
331
333
  if (controlledActiveId === undefined) setUncontrolledActiveId(next);
@@ -515,8 +517,9 @@ export function useCollectionInteractions<T>(
515
517
  keyboardRangeBaseRef.current = new Set();
516
518
  setAnchor(next, 'navigate');
517
519
  }
518
- setActive(next, extend ? 'range' : 'navigate');
520
+ // Set before the change is reported, so the page reads the way of this very move (a wrap included).
519
521
  travelRef.current = forward ? 'next' : 'previous';
522
+ setActive(next, extend ? 'range' : 'navigate');
520
523
  const nextId = next;
521
524
  requestAnimationFrame(() => focusItem(nextId));
522
525
  }, [focusItem, replaceRange, setActive, setAnchor]);
@@ -689,6 +692,7 @@ export function useCollectionInteractions<T>(
689
692
 
690
693
  const getSelectedItems = useCallback(() => getItemsForIds(selectedIdsRef.current), [getItemsForIds]);
691
694
  const travelDirection = useCallback(() => travelRef.current, []);
695
+ const move = useCallback((direction: CollectionNavigationDirection) => moveActive(direction), [moveActive]);
692
696
  const isSelected = useCallback((id: string) => selectedIds.has(id), [selectedIds]);
693
697
 
694
698
  const actionContext = useMemo<CollectionActionContext<T>>(() => ({
@@ -757,6 +761,7 @@ export function useCollectionInteractions<T>(
757
761
  dragRect,
758
762
  actions: resolvedActions,
759
763
  travelDirection,
764
+ move,
760
765
  getActionBarProps,
761
766
  isSelected,
762
767
  getSelectedItems,