@notis_ai/cli 0.2.32 → 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 (81) hide show
  1. package/README.md +74 -9
  2. package/dist/agent-hooks/notis-agent-hook.mjs +4330 -891
  3. package/dist/base-skills/notis-cli/.notis-base-skill.json +1 -1
  4. package/dist/base-skills/notis-cli/SKILL.md +7 -3
  5. package/dist/base-skills/notis-spaces/.notis-base-skill.json +1 -1
  6. package/dist/base-skills/notis-spaces/SKILL.md +5 -3
  7. package/dist/base-skills/notis-spaces/references/comments.md +94 -0
  8. package/dist/base-skills/notis-spaces/references/context.md +20 -19
  9. package/dist/base-skills/notis-spaces/references/design.md +3 -2
  10. package/dist/base-skills/notis-spaces/references/sdk.md +135 -83
  11. package/dist/base-skills/notis-spaces/references/store.md +24 -1
  12. package/dist/sdk/src/components/SelectionActionBar.tsx +42 -7
  13. package/dist/sdk/src/components/SpaceTextComments.tsx +284 -0
  14. package/dist/sdk/src/config.ts +3 -1
  15. package/dist/sdk/src/functions.ts +203 -0
  16. package/dist/sdk/src/hooks/useAgentQueue.ts +17 -28
  17. package/dist/sdk/src/hooks/useCollectionInteractions.ts +7 -2
  18. package/dist/sdk/src/hooks/useConnection.ts +102 -0
  19. package/dist/sdk/src/hooks/useFunction.ts +42 -0
  20. package/dist/sdk/src/hooks/useNotisSettings.ts +101 -0
  21. package/dist/sdk/src/index.ts +15 -4
  22. package/dist/sdk/src/runtime.ts +16 -1
  23. package/dist/sdk/src/space.ts +333 -33
  24. package/dist/sdk/src/ui/comments/passageModel.ts +99 -0
  25. package/dist/sdk/src/ui/comments/textHighlights.ts +33 -0
  26. package/dist/skill-sync/index.js +239 -30
  27. package/dist/skill-sync-worker.mjs +453 -124
  28. package/dist/space-harness/host.js +213 -92
  29. package/dist/space-sdk/dist/chunk-4GWS2IFO.js +3 -0
  30. package/dist/space-sdk/dist/index.js +3 -3
  31. package/dist/space-sdk/dist/ui.js +8 -7
  32. package/dist/space-sdk/src/config.ts +3 -1
  33. package/dist/space-sdk/src/functions.ts +203 -0
  34. package/dist/space-sdk/src/hooks/useAgentQueue.d.ts +2 -13
  35. package/dist/space-sdk/src/hooks/useCollectionInteractions.d.ts +2 -0
  36. package/dist/space-sdk/src/hooks/useConnection.d.ts +42 -0
  37. package/dist/space-sdk/src/hooks/useFunction.d.ts +20 -0
  38. package/dist/space-sdk/src/hooks/useNotisSettings.d.ts +48 -0
  39. package/dist/space-sdk/src/index.d.ts +10 -4
  40. package/dist/space-sdk/src/runtime.d.ts +14 -1
  41. package/dist/space-sdk/src/space.ts +333 -33
  42. package/dist/space-sdk/src/tailwind-candidates.d.ts +185 -152
  43. package/dist/space-sdk/src/ui/comments/CommentPane.d.ts +7 -4
  44. package/dist/space-sdk/src/ui/comments/agentRuntime.d.ts +10 -2
  45. package/dist/space-sdk/src/ui/comments/commentModel.d.ts +55 -88
  46. package/dist/space-sdk/src/ui/comments/commentWords.d.ts +9 -0
  47. package/dist/space-sdk/src/ui/comments/hostComments.d.ts +13 -9
  48. package/dist/space-sdk/src/ui/comments/index.d.ts +1 -1
  49. package/dist/space-sdk/src/ui/comments/paneParts.d.ts +27 -5
  50. package/dist/space-sdk/src/ui/comments/passageModel.d.ts +12 -36
  51. package/dist/space-sdk/src/ui/comments/useCommentRouting.d.ts +26 -4
  52. package/dist/space-sdk/src/ui/comments/useComments.d.ts +64 -74
  53. package/dist/space-sdk/src/ui/comments/usePassageComments.d.ts +8 -4
  54. package/dist/space-sdk/src/ui/index.d.ts +1 -1
  55. package/dist/space-sdk/src/ui/layout/SidePane.d.ts +3 -4
  56. package/dist/space-sdk/src/ui/period/dateFormat.d.ts +27 -8
  57. package/dist/view-renderer/dist/host.js +280 -159
  58. package/package.json +3 -3
  59. package/skills/notis-cli/AGENT_INSTRUCTIONS.md +2 -2
  60. package/skills/notis-spaces/cli.md +3 -3
  61. package/src/cli.js +2 -1
  62. package/src/command-specs/index.js +3 -0
  63. package/src/command-specs/repository-secrets.js +171 -0
  64. package/src/command-specs/spaces.js +3 -3
  65. package/src/runtime/agent-credential.js +175 -0
  66. package/src/runtime/agent-identity.js +92 -15
  67. package/src/runtime/app-platform.js +8 -0
  68. package/src/runtime/auth-recovery.js +14 -0
  69. package/src/runtime/profiles.js +15 -0
  70. package/src/runtime/skill-sync/index.ts +3 -2
  71. package/src/runtime/skill-sync/symlink-manager.ts +354 -35
  72. package/src/runtime/skill-sync/types.ts +10 -1
  73. package/src/runtime/space-functions.js +211 -0
  74. package/src/runtime/space-platform.js +12 -3
  75. package/src/runtime/space-source.js +116 -13
  76. package/src/runtime/space-test-server.js +22 -4
  77. package/src/runtime/space-verification.js +3 -1
  78. package/src/runtime/transport.js +15 -0
  79. package/dist/sdk/src/components/NotisCommentBoundary.tsx +0 -132
  80. package/dist/space-sdk/dist/chunk-I4Z4UFGB.js +0 -3
  81. package/dist/space-sdk/src/components/NotisCommentBoundary.d.ts +0 -26
@@ -293,6 +293,15 @@ export interface CiteSelectionBarProps {
293
293
  root: RefObject<HTMLElement | null>;
294
294
  /** Receives the cited text once the bar has cleared the selection. */
295
295
  onCite(range: Range, text: string): void;
296
+ /** False hides Cite (a surface with nowhere to send a quote). Default true. */
297
+ cite?: boolean;
298
+ /**
299
+ * Adds Comment after Cite (a Space page while the host takes comments): receives the selected range and text once
300
+ * the bar has cleared the selection.
301
+ */
302
+ onComment?(range: Range, text: string): void;
303
+ /** Whether this selection may be commented on with the bar's Comment (default: any it shows for). */
304
+ canComment?(range: Range): boolean;
296
305
  enabled?: boolean;
297
306
  accept?: UseSelectionAnchorOptions['accept'];
298
307
  /**
@@ -304,15 +313,39 @@ export interface CiteSelectionBarProps {
304
313
  }
305
314
 
306
315
  /**
307
- * The Cite-only bar every quoting surface shows (chat, Space views, Skills and automations; truth PRT-087): it follows
308
- * the selection in `root`, measures itself, and hands the cited text to `onCite`.
316
+ * The Comment action of a selection bar: the same words and glyph everywhere; it clears the selection and hides the
317
+ * bar before handing over the selected range and text.
318
+ */
319
+ export function commentSelectionAction(locale: keyof typeof SELECTION_BAR_WORDS.comment, anchor: SelectionAnchor,
320
+ root: RefObject<HTMLElement | null>, dismiss: () => void, onComment: (range: Range, text: string) => void): SelectionBarAction {
321
+ return {
322
+ key: 'comment', label: SELECTION_BAR_WORDS.comment[locale], icon: COMMENT_GLYPH,
323
+ onSelect: () => {
324
+ const { range, text } = anchor;
325
+ clearSelectionIn(root.current);
326
+ dismiss();
327
+ onComment(range, text);
328
+ },
329
+ };
330
+ }
331
+
332
+ /**
333
+ * The bar every quoting surface shows (chat, Space views, Skills and automations; truth PRT-087): it follows the
334
+ * selection in `root`, measures itself, and hands the cited text to `onCite`. With `onComment` (a Space page while the
335
+ * host takes comments) it also offers Comment.
309
336
  */
310
- export function CiteSelectionBar({ root, onCite, enabled = true, accept, portal }: CiteSelectionBarProps) {
337
+ export function CiteSelectionBar({ root, onCite, cite = true, onComment, canComment, enabled = true, accept, portal }: CiteSelectionBarProps) {
311
338
  const locale = useToolkitLocale();
312
339
  const [barSize, setBarSize] = useState({ width: 72, height: 32 });
313
- const { anchor, dismiss } = useSelectionAnchor(root, { enabled, accept, barSize });
340
+ const { anchor, dismiss } = useSelectionAnchor(root, { enabled: enabled && (cite || Boolean(onComment)), accept, barSize });
314
341
  if (!anchor) return null;
315
- const bar = <SelectionActionBar anchor={anchor} onSize={setBarSize} actions={[citeSelectionAction(locale, anchor, root, dismiss, onCite)]} />;
342
+ const actions: SelectionBarAction[] = [];
343
+ if (cite) actions.push(citeSelectionAction(locale, anchor, root, dismiss, onCite));
344
+ if (onComment && (!canComment || canComment(anchor.range))) {
345
+ actions.push(commentSelectionAction(locale, anchor, root, dismiss, onComment));
346
+ }
347
+ if (!actions.length) return null;
348
+ const bar = <SelectionActionBar anchor={anchor} onSize={setBarSize} actions={actions} />;
316
349
  return portal ? portal(bar) : bar;
317
350
  }
318
351
 
@@ -336,8 +369,10 @@ export function SelectionActionBar({ anchor, actions, onSize }: {
336
369
  onSize?(size: { width: number; height: number }): void;
337
370
  }) {
338
371
  const bar = useRef<HTMLDivElement>(null);
339
- const first = useRef(actions[0]);
340
- first.current = actions[0];
372
+ // The Cite key cites: never another action (a bar without Cite ignores it).
373
+ const citeAction = actions.find(action => action.key === 'cite') ?? (actions[0]?.key === 'comment' ? undefined : actions[0]);
374
+ const first = useRef(citeAction);
375
+ first.current = citeAction;
341
376
  const [left, setLeft] = useState(anchor.left);
342
377
  // A finger needs a bigger target than the 26 px a pointer gets.
343
378
  const coarse = typeof window !== 'undefined' && isCoarsePointer(window);
@@ -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
+ }