@notis_ai/cli 0.2.26 → 0.2.28

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 (51) hide show
  1. package/README.md +2 -2
  2. package/config/notis_app_design_rules.json +5 -123
  3. package/dist/agent-hooks/notis-agent-hook.mjs +84 -14
  4. package/dist/base-skills/notis-spaces/.notis-base-skill.json +1 -1
  5. package/dist/base-skills/notis-spaces/SKILL.md +13 -19
  6. package/dist/base-skills/notis-spaces/references/context.md +3 -0
  7. package/dist/base-skills/notis-spaces/references/design.md +11 -45
  8. package/dist/base-skills/notis-spaces/references/sdk.md +86 -67
  9. package/dist/base-skills/notis-spaces/references/views.md +12 -1
  10. package/dist/sdk/src/components/NotisCommentBoundary.tsx +43 -16
  11. package/dist/sdk/src/components/NotisSelectionBoundary.tsx +105 -26
  12. package/dist/sdk/src/components/SelectionActionBar.tsx +262 -0
  13. package/dist/sdk/src/hooks/useCollectionInteractions.ts +5 -2
  14. package/dist/sdk/src/space.ts +4 -0
  15. package/dist/sdk/src/ui/icons.tsx +11 -2
  16. package/dist/sdk/src/words/actions.ts +9 -1
  17. package/dist/sdk/src/words/keymap.ts +3 -0
  18. package/dist/skill-sync/index.js +81 -11
  19. package/dist/skill-sync-worker.mjs +87 -12
  20. package/dist/space-harness/host.js +172 -134
  21. package/dist/space-sdk/dist/{chunk-BWHAORT4.js → chunk-BFGB6XXC.js} +2 -2
  22. package/dist/space-sdk/dist/index.js +2 -2
  23. package/dist/space-sdk/dist/ui.js +14 -11
  24. package/dist/space-sdk/src/components/NotisSelectionBoundary.d.ts +26 -2
  25. package/dist/space-sdk/src/space.ts +4 -0
  26. package/dist/space-sdk/src/tailwind-candidates.d.ts +124 -14
  27. package/dist/space-sdk/src/ui/blocks/DataTable.d.ts +86 -0
  28. package/dist/space-sdk/src/ui/blocks/InfoTip.d.ts +25 -0
  29. package/dist/space-sdk/src/ui/blocks/Meter.d.ts +39 -0
  30. package/dist/space-sdk/src/ui/blocks/blocks.d.ts +1 -1
  31. package/dist/space-sdk/src/ui/blocks/index.d.ts +6 -0
  32. package/dist/space-sdk/src/ui/charts/Chart.d.ts +15 -2
  33. package/dist/space-sdk/src/ui/charts/StatRow.d.ts +4 -3
  34. package/dist/space-sdk/src/ui/charts/chartData.d.ts +6 -0
  35. package/dist/space-sdk/src/ui/icons.d.ts +1 -1
  36. package/dist/space-sdk/src/ui/index.d.ts +2 -2
  37. package/dist/space-sdk/src/ui/list/Row.d.ts +10 -3
  38. package/dist/space-sdk/src/ui/period/dateFormat.d.ts +14 -0
  39. package/dist/space-sdk/src/words/actions.ts +9 -1
  40. package/dist/space-sdk/src/words/keymap.ts +3 -0
  41. package/dist/view-renderer/dist/host.js +243 -205
  42. package/dist/view-renderer/src/dom.js +15 -2
  43. package/package.json +3 -3
  44. package/skills/notis-cli/AGENT_INSTRUCTIONS.md +1 -1
  45. package/src/command-specs/computer.js +3 -3
  46. package/src/runtime/skill-sync/cloud-client.ts +98 -15
  47. package/src/runtime/skill-sync/index.ts +22 -3
  48. package/src/runtime/skill-sync/types.ts +4 -0
  49. package/src/skill-sync-worker.js +5 -1
  50. package/template/components/ui/button.tsx +1 -1
  51. package/template/components/ui/native-select.tsx +1 -1
@@ -0,0 +1,262 @@
1
+ 'use client';
2
+ import React, { useCallback, useEffect, useLayoutEffect, useRef, useState, type ReactNode, type RefObject } from 'react';
3
+ import type { Words } from '../words/types';
4
+
5
+ /**
6
+ * The floating bar on selected text (truths PRT-087, PRT-090, PRT-094): one dark labelled pill at the end of the
7
+ * selection, with Cite and, where a surface takes comments, Comment. Chat, every Space view, Skills and automations
8
+ * draw the same bar; each surface decides what Cite quotes and where the quote goes.
9
+ */
10
+
11
+ /** Cmd+Shift+C (Ctrl+Shift+C off a Mac) cites the selection: the host dispatches this on the document, and the bar on screen answers. */
12
+ export const CITE_SELECTION_EVENT = 'notis:cite-selection';
13
+
14
+ export const SELECTION_BAR_WORDS = Object.freeze({
15
+ cite: Object.freeze({ en: 'Cite', fr: 'Citer' }),
16
+ citeHint: Object.freeze({ en: 'Cite in chat', fr: 'Citer dans le chat' }),
17
+ comment: Object.freeze({ en: 'Comment', fr: 'Commenter' }),
18
+ }) satisfies Readonly<Record<string, Words>>;
19
+
20
+ export interface SelectionBarAction {
21
+ key: string;
22
+ label: string;
23
+ title?: string;
24
+ icon: ReactNode;
25
+ onSelect(): void;
26
+ }
27
+
28
+ export interface SelectionAnchor {
29
+ top: number;
30
+ left: number;
31
+ /** The selected text, trimmed. */
32
+ text: string;
33
+ /** A copy of the selected range, still valid after the browser collapses the live selection. */
34
+ range: Range;
35
+ }
36
+
37
+ type Rect = Pick<DOMRect, 'left' | 'right' | 'top' | 'bottom'>;
38
+ const GAP = 8;
39
+ const TOUCH_GAP = 14;
40
+
41
+ /**
42
+ * Where the bar goes: after the last selected line when it fits there and no text follows on that line, otherwise
43
+ * just below where the selection ends (above it near the bottom of the viewport). On a touch screen it always goes
44
+ * below, so the system's own Copy menu keeps the space above the selection.
45
+ */
46
+ export function getSelectionBarPosition(
47
+ rects: Rect[],
48
+ viewport: { width: number; height: number },
49
+ bar: { width: number; height: number },
50
+ options: { rightBoundary?: number; trailing?: Rect[]; coarse?: boolean } = {},
51
+ ): { top: number; left: number } {
52
+ const last = rects[rects.length - 1];
53
+ const { width, height } = bar;
54
+ const rightBoundary = options.rightBoundary ?? viewport.width;
55
+ const clampX = (x: number) => Math.max(GAP, Math.min(viewport.width - width - GAP, x));
56
+ const clampY = (y: number) => Math.max(GAP, Math.min(viewport.height - height - GAP, y));
57
+ if (!options.coarse) {
58
+ const beside = { left: last.right + GAP, top: clampY((last.top + last.bottom - height) / 2) };
59
+ const overlapsText = (options.trailing ?? []).some(rect => rect.left < beside.left + width && rect.right > beside.left
60
+ && rect.top < beside.top + height && rect.bottom > beside.top);
61
+ if (beside.left + width <= Math.min(viewport.width, rightBoundary) - GAP && !overlapsText) return beside;
62
+ }
63
+ const gap = options.coarse ? TOUCH_GAP : GAP;
64
+ const below = last.bottom + gap;
65
+ const left = clampX(options.coarse ? (last.left + last.right - width) / 2 : last.right - width);
66
+ return { left, top: clampY(below + height <= viewport.height - GAP ? below : last.top - height - gap) };
67
+ }
68
+
69
+ function isCoarsePointer(view: Window | null): boolean {
70
+ return Boolean(view?.matchMedia?.('(pointer: coarse)').matches);
71
+ }
72
+
73
+ const EDITABLE = 'input,textarea,select,[contenteditable]:not([contenteditable="false"]),[data-notis-selection-ui]';
74
+
75
+ function elementOf(node: Node): Element | null {
76
+ return node.nodeType === Node.ELEMENT_NODE ? node as Element : node.parentElement;
77
+ }
78
+
79
+ export interface UseSelectionAnchorOptions {
80
+ /** Off while the surface has nowhere to send a quote (a public Site, a chat that cannot send). */
81
+ enabled?: boolean;
82
+ /** Refuse a selection the surface does not quote (inside a nested surface with its own bar). */
83
+ accept?(range: Range, root: HTMLElement): boolean;
84
+ /** Clip the selection to the surface instead of refusing one that spills over its edge. */
85
+ clip?(range: Range, root: HTMLElement): Range | null;
86
+ /** The bar's size, measured once it shows; used to keep it inside the viewport. */
87
+ barSize?: { width: number; height: number };
88
+ }
89
+
90
+ /**
91
+ * Follows the text selected inside `root` and returns where the bar shows, or null. A mouse or keyboard selection
92
+ * shows the bar when it ends (mouse up, Shift+arrow up); a touch selection once it has stopped moving.
93
+ */
94
+ export function useSelectionAnchor(root: RefObject<HTMLElement | null>, options: UseSelectionAnchorOptions = {}) {
95
+ const { enabled = true } = options;
96
+ const [anchor, setAnchor] = useState<SelectionAnchor | null>(null);
97
+ const optionsRef = useRef(options);
98
+ optionsRef.current = options;
99
+ const settle = useRef<number | undefined>(undefined);
100
+
101
+ const read = useCallback((): SelectionAnchor | null => {
102
+ const node = root.current;
103
+ if (!node) return null;
104
+ const scope = node.getRootNode() as ShadowRoot & { getSelection?: () => Selection | null };
105
+ const view = node.ownerDocument.defaultView;
106
+ const selection = scope.getSelection?.() || view?.getSelection();
107
+ if (!selection?.rangeCount || selection.isCollapsed || !selection.toString().trim()) return null;
108
+ let range: Range | null = selection.getRangeAt(0).cloneRange();
109
+ if (!node.contains(range.startContainer) || !node.contains(range.endContainer)) {
110
+ range = optionsRef.current.clip?.(range, node) ?? null;
111
+ if (!range) return null;
112
+ }
113
+ const start = elementOf(range.startContainer);
114
+ const end = elementOf(range.endContainer);
115
+ if (start?.closest(EDITABLE) || end?.closest(EDITABLE)) return null;
116
+ if (optionsRef.current.accept && !optionsRef.current.accept(range, node)) return null;
117
+ const text = range.toString().trim();
118
+ if (!text) return null;
119
+ const lines = Array.from(range.getClientRects?.() || []).filter(line => line.width > 0 && line.height > 0);
120
+ const rect = range.getBoundingClientRect();
121
+ const trailing: DOMRect[] = [];
122
+ const endBlock = end?.closest('p,li,h1,h2,h3,h4,h5,h6,td,th,pre,blockquote,div');
123
+ if (endBlock && node.contains(endBlock)) {
124
+ const remainder = range.cloneRange();
125
+ remainder.selectNodeContents(endBlock);
126
+ remainder.setStart(range.endContainer, range.endOffset);
127
+ if (remainder.toString().trim()) trailing.push(...Array.from(remainder.getClientRects?.() || []).filter(line => line.width > 0 && line.height > 0));
128
+ }
129
+ const bounds = node.getBoundingClientRect();
130
+ const position = getSelectionBarPosition(lines.length ? lines : [rect],
131
+ { width: view?.innerWidth ?? 1024, height: view?.innerHeight ?? 768 },
132
+ optionsRef.current.barSize ?? { width: 80, height: 32 },
133
+ { rightBoundary: bounds.width ? bounds.right : undefined, trailing, coarse: isCoarsePointer(view) });
134
+ return { ...position, text, range };
135
+ }, [root]);
136
+
137
+ const dismiss = useCallback(() => setAnchor(null), []);
138
+
139
+ // The bar measured itself: place it again with its real width, so its edge lines up with the selection.
140
+ const barWidth = options.barSize?.width;
141
+ const barHeight = options.barSize?.height;
142
+ useEffect(() => { setAnchor(current => current ? read() : current); }, [barWidth, barHeight, read]);
143
+
144
+ useEffect(() => {
145
+ const node = root.current;
146
+ if (!enabled || !node) { setAnchor(null); return; }
147
+ const document = node.ownerDocument;
148
+ const view = document.defaultView;
149
+ const scope = node.getRootNode() as ShadowRoot | Document;
150
+ const capture = (event: Event) => {
151
+ if (event.target instanceof Element && event.target.closest('[data-notis-selection-ui]')) return;
152
+ // Let the browser finish the selection (a double click selects the word after mouseup).
153
+ view?.setTimeout(() => setAnchor(read()), 0);
154
+ };
155
+ const onKeyUp = (event: KeyboardEvent) => {
156
+ if (event.shiftKey || event.key === 'Shift' || ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'a')) capture(event);
157
+ };
158
+ const onSelectionChange = () => {
159
+ const next = read();
160
+ if (!next) { setAnchor(null); return; }
161
+ // A touch selection has no mouse up: show the bar once its handles stop moving.
162
+ if (isCoarsePointer(view)) {
163
+ view?.clearTimeout(settle.current);
164
+ setAnchor(null);
165
+ settle.current = view?.setTimeout(() => setAnchor(read()), 450);
166
+ }
167
+ };
168
+ const onScroll = () => setAnchor(current => current ? read() : current);
169
+ node.addEventListener('mouseup', capture);
170
+ node.addEventListener('dblclick', capture);
171
+ node.addEventListener('keyup', onKeyUp);
172
+ document.addEventListener('selectionchange', onSelectionChange);
173
+ if (scope !== document) scope.addEventListener('selectionchange', onSelectionChange);
174
+ view?.addEventListener('scroll', onScroll, true);
175
+ view?.addEventListener('resize', onScroll);
176
+ return () => {
177
+ view?.clearTimeout(settle.current);
178
+ node.removeEventListener('mouseup', capture);
179
+ node.removeEventListener('dblclick', capture);
180
+ node.removeEventListener('keyup', onKeyUp);
181
+ document.removeEventListener('selectionchange', onSelectionChange);
182
+ if (scope !== document) scope.removeEventListener('selectionchange', onSelectionChange);
183
+ view?.removeEventListener('scroll', onScroll, true);
184
+ view?.removeEventListener('resize', onScroll);
185
+ };
186
+ }, [enabled, read, root]);
187
+
188
+ return { anchor, dismiss, refresh: () => setAnchor(read()) };
189
+ }
190
+
191
+ /** Clears the page's selection once its text was cited, so the bar does not linger over it. */
192
+ export function clearSelectionIn(node: Node | null | undefined): void {
193
+ if (!node) return;
194
+ const scope = node.getRootNode() as ShadowRoot & { getSelection?: () => Selection | null };
195
+ (scope.getSelection?.() || node.ownerDocument?.defaultView?.getSelection())?.removeAllRanges();
196
+ }
197
+
198
+ export const QUOTE_GLYPH = <svg aria-hidden="true" width="14" height="14" viewBox="0 0 256 256" fill="currentColor"><path d="M100,56H40A16,16,0,0,0,24,72v64a16,16,0,0,0,16,16h60v8a32,32,0,0,1-32,32,8,8,0,0,0,0,16,48.05,48.05,0,0,0,48-48V72A16,16,0,0,0,100,56Zm0,80H40V72h60ZM216,56H156a16,16,0,0,0-16,16v64a16,16,0,0,0,16,16h60v8a32,32,0,0,1-32,32,8,8,0,0,0,0,16,48.05,48.05,0,0,0,48-48V72A16,16,0,0,0,216,56Zm0,80H156V72h60Z" /></svg>;
199
+ export const COMMENT_GLYPH = <svg aria-hidden="true" width="14" height="14" viewBox="0 0 256 256" fill="currentColor"><path d="M216,48H40A16,16,0,0,0,24,64V224a15.85,15.85,0,0,0,9.24,14.5A16.13,16.13,0,0,0,40,240a15.89,15.89,0,0,0,10.25-3.78l.09-.07L83,208H216a16,16,0,0,0,16-16V64A16,16,0,0,0,216,48ZM40,224h0ZM216,192H80a8,8,0,0,0-5.23,1.95L40,224V64H216ZM88,112a8,8,0,0,1,8-8h64a8,8,0,0,1,0,16H96A8,8,0,0,1,88,112Zm0,32a8,8,0,0,1,8-8h64a8,8,0,1,1,0,16H96A8,8,0,0,1,88,144Z" /></svg>;
200
+
201
+ const BAR_STYLE: React.CSSProperties = {
202
+ position: 'fixed', zIndex: 60, display: 'inline-flex', alignItems: 'center', gap: 2, padding: 3, borderRadius: 999,
203
+ background: 'hsl(var(--sidebar-background, 0 0% 7.5%))', color: 'hsl(var(--sidebar-foreground, 240 4.8% 95.9%))',
204
+ boxShadow: '0 0 0 1px rgb(255 255 255 / 0.15), 0 6px 18px rgb(0 0 0 / 0.28)', colorScheme: 'dark',
205
+ fontFamily: 'inherit', fontSize: 13, lineHeight: '18px', fontWeight: 500, whiteSpace: 'nowrap',
206
+ };
207
+
208
+ /**
209
+ * The dark labelled pill itself. It never takes focus or moves the selection (mouse down is cancelled), and it
210
+ * answers the Cite key while it shows: the first action is Cite.
211
+ */
212
+ export function SelectionActionBar({ anchor, actions, onSize }: {
213
+ anchor: Pick<SelectionAnchor, 'top' | 'left'>;
214
+ actions: SelectionBarAction[];
215
+ onSize?(size: { width: number; height: number }): void;
216
+ }) {
217
+ const bar = useRef<HTMLDivElement>(null);
218
+ const first = useRef(actions[0]);
219
+ first.current = actions[0];
220
+ const [left, setLeft] = useState(anchor.left);
221
+ // A finger needs a bigger target than the 26 px a pointer gets.
222
+ const coarse = typeof window !== 'undefined' && isCoarsePointer(window);
223
+ useLayoutEffect(() => {
224
+ const node = bar.current;
225
+ const view = node?.ownerDocument.defaultView;
226
+ if (!node || !view) { setLeft(anchor.left); return; }
227
+ const width = node.offsetWidth;
228
+ onSize?.({ width, height: node.offsetHeight });
229
+ setLeft(Math.max(GAP, Math.min(view.innerWidth - width - GAP, anchor.left)));
230
+ }, [anchor.left, anchor.top, onSize, actions.length]);
231
+ useEffect(() => {
232
+ const document = bar.current?.ownerDocument;
233
+ if (!document) return;
234
+ const onCite = (event: Event) => {
235
+ if ((event as CustomEvent<{ handled?: boolean }>).detail?.handled) return;
236
+ const detail = (event as CustomEvent<{ handled?: boolean }>).detail;
237
+ if (detail) detail.handled = true;
238
+ first.current?.onSelect();
239
+ };
240
+ document.addEventListener(CITE_SELECTION_EVENT, onCite);
241
+ return () => document.removeEventListener(CITE_SELECTION_EVENT, onCite);
242
+ }, []);
243
+ return <div ref={bar} data-notis-selection-ui role="toolbar" style={{ ...BAR_STYLE, top: anchor.top, left }}
244
+ onMouseDown={event => event.preventDefault()} onPointerDown={event => event.stopPropagation()}>
245
+ {actions.map((action, index) => <React.Fragment key={action.key}>
246
+ {index > 0 && <span aria-hidden="true" style={{ width: 1, height: 16, background: 'rgb(255 255 255 / 0.14)', margin: '0 1px' }} />}
247
+ <button type="button" title={action.title ?? action.label} onClick={action.onSelect} data-selection-action={action.key}
248
+ className="notis-selection-action"
249
+ style={{ all: 'unset', boxSizing: 'border-box', display: 'inline-flex', alignItems: 'center', gap: 6, height: coarse ? 36 : 26,
250
+ padding: coarse ? '0 14px 0 12px' : '0 11px 0 9px', borderRadius: 999, cursor: 'pointer', background: index === 0 ? 'rgb(255 255 255 / 0.08)' : undefined }}>
251
+ {action.icon}<span>{action.label}</span>
252
+ </button>
253
+ </React.Fragment>)}
254
+ </div>;
255
+ }
256
+
257
+ /** Fires the Cite key: the bar on screen cites its selection. Returns whether one did. */
258
+ export function dispatchCiteSelection(document: Document): boolean {
259
+ const detail = { handled: false };
260
+ document.dispatchEvent(new CustomEvent(CITE_SELECTION_EVENT, { detail }));
261
+ return detail.handled;
262
+ }
@@ -285,6 +285,9 @@ export function useCollectionInteractions<T>(
285
285
  );
286
286
  const selectableIdsRef = useRef(selectableIds);
287
287
  selectableIdsRef.current = selectableIds;
288
+ const selectableIdSet = useMemo(() => new Set(selectableIds), [selectableIds]);
289
+ const selectableIdSetRef = useRef(selectableIdSet);
290
+ selectableIdSetRef.current = selectableIdSet;
288
291
  // The list as it was when it last held the active item: J/K from an item that left the list go on from its place.
289
292
  const activePlaceRef = useRef<{ id: string; ids: string[] } | null>(null);
290
293
  const droppedActiveIdRef = useRef<string | null>(null);
@@ -647,7 +650,7 @@ export function useCollectionInteractions<T>(
647
650
  [LEGACY_ROW_ATTRIBUTE]: id,
648
651
  tabIndex: activeIdRef.current === id || (!activeIdRef.current && selectableIdsRef.current[0] === id) ? 0 : -1,
649
652
  'aria-selected': selectedIdsRef.current.has(id),
650
- 'aria-disabled': !selectableIdsRef.current.includes(id),
653
+ 'aria-disabled': !selectableIdSetRef.current.has(id),
651
654
  'data-notis-active': (activeIdRef.current === id ? 'true' : 'false') as 'true' | 'false',
652
655
  onFocus: () => {
653
656
  activateCollectionShortcuts();
@@ -680,7 +683,7 @@ export function useCollectionInteractions<T>(
680
683
 
681
684
  const getCheckboxProps = useCallback((id: string) => ({
682
685
  isSelected: selectedIdsRef.current.has(id),
683
- disabled: !enabled || !selectableIdsRef.current.includes(id),
686
+ disabled: !enabled || !selectableIdSetRef.current.has(id),
684
687
  onClick: onCheckboxClick(id),
685
688
  }), [enabled, onCheckboxClick]);
686
689
 
@@ -537,6 +537,10 @@ export interface SpaceDefinition {
537
537
  * moment, once that person allowed this Space's agents. Agents' own writes never wake anything.
538
538
  */
539
539
  agents?: SpaceAgentDeclaration[];
540
+ /**
541
+ * Lists the database's records as sidebar rows under this Space. Only for a short list people navigate
542
+ * like pages (folders, chapters); a database that keeps growing belongs in the view's `shows` instead.
543
+ */
540
544
  collection?: { database: string; titleProperty: string; parentProperty?: string; allowCreate?: boolean };
541
545
  /** Reproducible source dependencies not discovered by the module graph. */
542
546
  sourceIncludes?: string[];
@@ -74,10 +74,19 @@ export function hasIcon(name: string): boolean {
74
74
  return Object.prototype.hasOwnProperty.call(SHAPES, name);
75
75
  }
76
76
 
77
- /** A built-in icon by name; an unknown name renders nothing. Decorative: the control carries the label. */
77
+ const warned = new Set<string>();
78
+
79
+ /** Names the set lacks, warned once each: an unknown name renders nothing, so a typo would otherwise go unseen. */
80
+ function warnUnknown(name: string): void {
81
+ if (warned.has(name) || typeof console === 'undefined') return;
82
+ warned.add(name);
83
+ console.warn(`[notis/ui] Unknown icon "${name}": it renders nothing. Use a name from the toolkit set (${Object.keys(SHAPES).length} icons, listed in the design system) or pass a Phosphor component.`);
84
+ }
85
+
86
+ /** A built-in icon by name; an unknown name renders nothing and warns once. Decorative: the control carries the label. */
78
87
  export function Icon({ name, className }: { name: string; className?: string }) {
79
88
  const shape = SHAPES[name];
80
- if (!shape) return null;
89
+ if (!shape) { warnUnknown(name); return null; }
81
90
  return (
82
91
  <svg className={className ? `nui-icon ${className}` : 'nui-icon'} viewBox="0 0 16 16" aria-hidden="true" focusable="false">
83
92
  {shape}
@@ -67,7 +67,15 @@ export class ActionError extends Error {
67
67
  /** The reason an ActionError carries, else null. A Space bundles its own copy of the words, so this reads the shape. */
68
68
  export function actionErrorReason(error: unknown): Words | string | null {
69
69
  if (!error || typeof error !== 'object') return null;
70
- const { name, code, reason } = error as { name?: unknown; code?: unknown; reason?: unknown };
70
+ const { name, code, reason, status } = error as { name?: unknown; code?: unknown; reason?: unknown; status?: unknown };
71
+ // A confirmed host refusal can explain how to unblock the action. These words are
72
+ // ours: never display an arbitrary Space/server error's message as a toast reason.
73
+ if (name === 'SpaceActionError' && code === 'document_has_spaces' && status === 'refused') {
74
+ return {
75
+ en: 'This document is used by a Space. Move or trash its linked Spaces first.',
76
+ fr: 'Ce document est utilisé par un Space. Déplace ou mets à la corbeille ses Spaces liés d’abord.',
77
+ };
78
+ }
71
79
  if (name !== 'ActionError' || code !== 'notis_action_error') return null;
72
80
  return typeof reason === 'string' || isWords(reason) ? reason : null;
73
81
  }
@@ -52,6 +52,9 @@ export const DEFAULT_KEYMAP = Object.freeze({
52
52
  'host.search': entry('host.search', ['/'], 'app', 'Search', 'Rechercher', { host: true }),
53
53
  'host.newChat': entry('host.newChat', ['c'], 'app', 'New conversation', 'Nouvelle conversation', { host: true }),
54
54
  'host.call': entry('host.call', ['shift+c'], 'app', 'Open voice call', 'Ouvrir l’appel vocal', { host: true }),
55
+ // Cites the selected text in chat, like the Cite button on the selection (truth PRT-089).
56
+ 'host.cite': entry('host.cite', ['mod+shift+c'], 'app', 'Cite selected text in chat', 'Citer le texte sélectionné dans le chat',
57
+ { host: true }),
55
58
  'host.toggleSidebar': entry('host.toggleSidebar', ['mod+s'], 'app', 'Toggle sidebar',
56
59
  'Afficher ou masquer la barre latérale', { host: true }),
57
60
  'host.voiceMessage': entry('host.voiceMessage', ['mod+d'], 'app', 'Voice message', 'Message vocal', { host: true }),
@@ -1092,10 +1092,24 @@ async function requestJson(url, jwt, options = {}) {
1092
1092
  });
1093
1093
  if (!response.ok) {
1094
1094
  const text = await response.text();
1095
- throw new Error(`${options.method || "POST"} ${url} \u2192 ${response.status}: ${text}`);
1095
+ throw new SkillSyncHttpError(
1096
+ `${options.method || "POST"} ${url} \u2192 ${response.status}: ${text}`,
1097
+ response.status,
1098
+ response.headers.get("content-type")
1099
+ );
1096
1100
  }
1097
1101
  return response.json();
1098
1102
  }
1103
+ var SkillSyncHttpError = class extends Error {
1104
+ status;
1105
+ code;
1106
+ constructor(message, status, contentType) {
1107
+ super(message);
1108
+ this.name = "SkillSyncHttpError";
1109
+ this.status = status;
1110
+ this.code = status === 403 && /text\/html/i.test(contentType || "") ? "edge_blocked" : `http_${status}`;
1111
+ }
1112
+ };
1099
1113
  async function fetchSyncSettings(serverUrl, jwt) {
1100
1114
  return requestJson(`${serverUrl}/portal_skills/sync-settings`, jwt, {
1101
1115
  body: {}
@@ -1106,8 +1120,9 @@ async function pullSkills(serverUrl, jwt) {
1106
1120
  body: { skill_sync_protocol: 2 }
1107
1121
  });
1108
1122
  }
1109
- async function pushChangedSkills(serverUrl, jwt, changedSkills) {
1110
- const payloadSkills = await Promise.all(changedSkills.map(async (skill) => ({
1123
+ var MAX_SYNC_PUSH_BODY_BYTES = 2 * 1024 * 1024;
1124
+ async function skillPushPayload(skill) {
1125
+ return {
1111
1126
  name: skill.name,
1112
1127
  description: skill.description,
1113
1128
  skill_md: skill.skillMd,
@@ -1120,13 +1135,58 @@ async function pushChangedSkills(serverUrl, jwt, changedSkills) {
1120
1135
  display_name: skill.displayName,
1121
1136
  native_scope: skill.nativeScope
1122
1137
  } : {}
1123
- })));
1124
- return requestJson(`${serverUrl}/portal_skills/sync-push`, jwt, {
1125
- body: {
1126
- skill_sync_protocol: 2,
1127
- skills: payloadSkills
1138
+ };
1139
+ }
1140
+ var SYNC_PUSH_ENVELOPE_BYTES = Buffer.byteLength(JSON.stringify({ skill_sync_protocol: 2, skills: [] }));
1141
+ function pushBatches(payloads, maxBodyBytes) {
1142
+ const batches = [];
1143
+ let batch = [];
1144
+ let batchBytes = SYNC_PUSH_ENVELOPE_BYTES;
1145
+ for (const payload of payloads) {
1146
+ const bytes = Buffer.byteLength(JSON.stringify(payload)) + 1;
1147
+ if (batch.length > 0 && batchBytes + bytes > maxBodyBytes) {
1148
+ batches.push(batch);
1149
+ batch = [];
1150
+ batchBytes = SYNC_PUSH_ENVELOPE_BYTES;
1151
+ }
1152
+ batch.push(payload);
1153
+ batchBytes += bytes;
1154
+ }
1155
+ if (batch.length > 0) batches.push(batch);
1156
+ return batches;
1157
+ }
1158
+ function pushFailure(name, error) {
1159
+ if (error instanceof SkillSyncHttpError) {
1160
+ return {
1161
+ name,
1162
+ error: error.code === "edge_blocked" ? `Upload blocked before reaching Notis (HTTP ${error.status}); sync will retry` : `Upload failed (HTTP ${error.status}); sync will retry`,
1163
+ status: error.status,
1164
+ code: error.code
1165
+ };
1166
+ }
1167
+ const code = typeof error?.code === "string" ? error.code : "push_failed";
1168
+ return { name, error: "Upload failed; sync will retry", code };
1169
+ }
1170
+ async function pushChangedSkills(serverUrl, jwt, changedSkills, options = {}) {
1171
+ const payloadSkills = await Promise.all(changedSkills.map(skillPushPayload));
1172
+ const saved = [];
1173
+ const failed = [];
1174
+ for (const batch of pushBatches(payloadSkills, options.maxBodyBytes ?? MAX_SYNC_PUSH_BODY_BYTES)) {
1175
+ try {
1176
+ const result = await requestJson(`${serverUrl}/portal_skills/sync-push`, jwt, {
1177
+ body: {
1178
+ skill_sync_protocol: 2,
1179
+ skills: batch
1180
+ }
1181
+ });
1182
+ saved.push(...result.skills || []);
1183
+ if (Array.isArray(result.failed)) failed.push(...result.failed);
1184
+ } catch (error) {
1185
+ if (error instanceof SkillSyncHttpError && error.status === 401) throw error;
1186
+ for (const payload of batch) failed.push(pushFailure(String(payload.name), error));
1128
1187
  }
1129
- });
1188
+ }
1189
+ return { skills: saved, ...failed.length ? { failed } : {} };
1130
1190
  }
1131
1191
  async function downloadSkillBundle(bundleUrl) {
1132
1192
  const response = await fetch(bundleUrl, { signal: AbortSignal.timeout(9e4) });
@@ -1752,6 +1812,15 @@ function buildSyncState(pullResponse, localSkills, lastSyncedAt, verifiedAgentLi
1752
1812
  skills
1753
1813
  });
1754
1814
  }
1815
+ function keepFailedPushesPending(state, previousState, failedPushes) {
1816
+ for (const { name } of failedPushes) {
1817
+ const row = state.skills[name];
1818
+ const previous = previousState.skills[name];
1819
+ if (!row || !previous || row.nativeReference || previous.nativeReference) continue;
1820
+ state.skills[name] = { ...row, folderHash: previous.folderHash };
1821
+ }
1822
+ return state;
1823
+ }
1755
1824
  function buildLocalSymlinkCandidates(pullResponse, localSkills, previousState) {
1756
1825
  const cloudSkillNames = new Set(
1757
1826
  pullResponse.skills.map((skill) => skill.name)
@@ -2176,7 +2245,7 @@ async function runSkillSync(serverUrl, jwt, dependencies = {}, options = {}) {
2176
2245
  for (const failure of failedDownloads) delete verifiedLinks[failure.name];
2177
2246
  const lastSyncedAt = pullResponse.last_synced_at || (/* @__PURE__ */ new Date()).toISOString();
2178
2247
  await deps.writeSyncState(
2179
- buildSyncState(
2248
+ keepFailedPushesPending(buildSyncState(
2180
2249
  pullResponse,
2181
2250
  finalLocalSkills,
2182
2251
  lastSyncedAt,
@@ -2185,7 +2254,7 @@ async function runSkillSync(serverUrl, jwt, dependencies = {}, options = {}) {
2185
2254
  collectAppliedCloudRevisions(pullResponse, previousState, writtenSkillNames),
2186
2255
  collectAppliedFiles(pullResponse, previousState, appliedFilesByName),
2187
2256
  previousState
2188
- ),
2257
+ ), previousState, failedPushes),
2189
2258
  syncPaths
2190
2259
  );
2191
2260
  return {
@@ -2209,6 +2278,7 @@ export {
2209
2278
  fetchSyncSettings,
2210
2279
  isolatedLinkOptions,
2211
2280
  materializeCloudSkillsForLocalShell,
2281
+ pushChangedSkills,
2212
2282
  runSkillSync,
2213
2283
  shouldWriteCloudSkill
2214
2284
  };
@@ -2688,10 +2688,24 @@ async function requestJson(url, jwt, options = {}) {
2688
2688
  });
2689
2689
  if (!response.ok) {
2690
2690
  const text = await response.text();
2691
- throw new Error(`${options.method || "POST"} ${url} \u2192 ${response.status}: ${text}`);
2691
+ throw new SkillSyncHttpError(
2692
+ `${options.method || "POST"} ${url} \u2192 ${response.status}: ${text}`,
2693
+ response.status,
2694
+ response.headers.get("content-type")
2695
+ );
2692
2696
  }
2693
2697
  return response.json();
2694
2698
  }
2699
+ var SkillSyncHttpError = class extends Error {
2700
+ status;
2701
+ code;
2702
+ constructor(message, status, contentType) {
2703
+ super(message);
2704
+ this.name = "SkillSyncHttpError";
2705
+ this.status = status;
2706
+ this.code = status === 403 && /text\/html/i.test(contentType || "") ? "edge_blocked" : `http_${status}`;
2707
+ }
2708
+ };
2695
2709
  async function fetchSyncSettings(serverUrl, jwt) {
2696
2710
  return requestJson(`${serverUrl}/portal_skills/sync-settings`, jwt, {
2697
2711
  body: {}
@@ -2702,8 +2716,9 @@ async function pullSkills(serverUrl, jwt) {
2702
2716
  body: { skill_sync_protocol: 2 }
2703
2717
  });
2704
2718
  }
2705
- async function pushChangedSkills(serverUrl, jwt, changedSkills) {
2706
- const payloadSkills = await Promise.all(changedSkills.map(async (skill) => ({
2719
+ var MAX_SYNC_PUSH_BODY_BYTES = 2 * 1024 * 1024;
2720
+ async function skillPushPayload(skill) {
2721
+ return {
2707
2722
  name: skill.name,
2708
2723
  description: skill.description,
2709
2724
  skill_md: skill.skillMd,
@@ -2716,13 +2731,58 @@ async function pushChangedSkills(serverUrl, jwt, changedSkills) {
2716
2731
  display_name: skill.displayName,
2717
2732
  native_scope: skill.nativeScope
2718
2733
  } : {}
2719
- })));
2720
- return requestJson(`${serverUrl}/portal_skills/sync-push`, jwt, {
2721
- body: {
2722
- skill_sync_protocol: 2,
2723
- skills: payloadSkills
2734
+ };
2735
+ }
2736
+ var SYNC_PUSH_ENVELOPE_BYTES = Buffer.byteLength(JSON.stringify({ skill_sync_protocol: 2, skills: [] }));
2737
+ function pushBatches(payloads, maxBodyBytes) {
2738
+ const batches = [];
2739
+ let batch = [];
2740
+ let batchBytes = SYNC_PUSH_ENVELOPE_BYTES;
2741
+ for (const payload of payloads) {
2742
+ const bytes = Buffer.byteLength(JSON.stringify(payload)) + 1;
2743
+ if (batch.length > 0 && batchBytes + bytes > maxBodyBytes) {
2744
+ batches.push(batch);
2745
+ batch = [];
2746
+ batchBytes = SYNC_PUSH_ENVELOPE_BYTES;
2747
+ }
2748
+ batch.push(payload);
2749
+ batchBytes += bytes;
2750
+ }
2751
+ if (batch.length > 0) batches.push(batch);
2752
+ return batches;
2753
+ }
2754
+ function pushFailure(name, error) {
2755
+ if (error instanceof SkillSyncHttpError) {
2756
+ return {
2757
+ name,
2758
+ error: error.code === "edge_blocked" ? `Upload blocked before reaching Notis (HTTP ${error.status}); sync will retry` : `Upload failed (HTTP ${error.status}); sync will retry`,
2759
+ status: error.status,
2760
+ code: error.code
2761
+ };
2762
+ }
2763
+ const code = typeof error?.code === "string" ? error.code : "push_failed";
2764
+ return { name, error: "Upload failed; sync will retry", code };
2765
+ }
2766
+ async function pushChangedSkills(serverUrl, jwt, changedSkills, options = {}) {
2767
+ const payloadSkills = await Promise.all(changedSkills.map(skillPushPayload));
2768
+ const saved = [];
2769
+ const failed = [];
2770
+ for (const batch of pushBatches(payloadSkills, options.maxBodyBytes ?? MAX_SYNC_PUSH_BODY_BYTES)) {
2771
+ try {
2772
+ const result = await requestJson(`${serverUrl}/portal_skills/sync-push`, jwt, {
2773
+ body: {
2774
+ skill_sync_protocol: 2,
2775
+ skills: batch
2776
+ }
2777
+ });
2778
+ saved.push(...result.skills || []);
2779
+ if (Array.isArray(result.failed)) failed.push(...result.failed);
2780
+ } catch (error) {
2781
+ if (error instanceof SkillSyncHttpError && error.status === 401) throw error;
2782
+ for (const payload of batch) failed.push(pushFailure(String(payload.name), error));
2724
2783
  }
2725
- });
2784
+ }
2785
+ return { skills: saved, ...failed.length ? { failed } : {} };
2726
2786
  }
2727
2787
  async function downloadSkillBundle(bundleUrl) {
2728
2788
  const response = await fetch(bundleUrl, { signal: AbortSignal.timeout(9e4) });
@@ -3337,6 +3397,15 @@ function buildSyncState(pullResponse, localSkills, lastSyncedAt, verifiedAgentLi
3337
3397
  skills
3338
3398
  });
3339
3399
  }
3400
+ function keepFailedPushesPending(state, previousState, failedPushes) {
3401
+ for (const { name } of failedPushes) {
3402
+ const row = state.skills[name];
3403
+ const previous = previousState.skills[name];
3404
+ if (!row || !previous || row.nativeReference || previous.nativeReference) continue;
3405
+ state.skills[name] = { ...row, folderHash: previous.folderHash };
3406
+ }
3407
+ return state;
3408
+ }
3340
3409
  function buildLocalSymlinkCandidates(pullResponse, localSkills, previousState) {
3341
3410
  const cloudSkillNames = new Set(
3342
3411
  pullResponse.skills.map((skill) => skill.name)
@@ -3664,7 +3733,7 @@ async function runSkillSync(serverUrl, jwt, dependencies = {}, options = {}) {
3664
3733
  for (const failure of failedDownloads) delete verifiedLinks[failure.name];
3665
3734
  const lastSyncedAt = pullResponse.last_synced_at || (/* @__PURE__ */ new Date()).toISOString();
3666
3735
  await deps.writeSyncState(
3667
- buildSyncState(
3736
+ keepFailedPushesPending(buildSyncState(
3668
3737
  pullResponse,
3669
3738
  finalLocalSkills,
3670
3739
  lastSyncedAt,
@@ -3673,7 +3742,7 @@ async function runSkillSync(serverUrl, jwt, dependencies = {}, options = {}) {
3673
3742
  collectAppliedCloudRevisions(pullResponse, previousState, writtenSkillNames),
3674
3743
  collectAppliedFiles(pullResponse, previousState, appliedFilesByName),
3675
3744
  previousState
3676
- ),
3745
+ ), previousState, failedPushes),
3677
3746
  syncPaths
3678
3747
  );
3679
3748
  return {
@@ -3937,7 +4006,13 @@ async function main(args = process.argv.slice(2), {
3937
4006
  record(await run({ profile, apiBase, userId }));
3938
4007
  } catch (error) {
3939
4008
  const code = error.code || "sync_failed";
3940
- record({ status: "error", code, ...REJECTED_SIGN_IN_CODES.has(code) && signIn ? { sign_in: signIn } : {} });
4009
+ const httpStatus = Number.isInteger(error.status) ? { http_status: error.status } : {};
4010
+ record({
4011
+ status: "error",
4012
+ code,
4013
+ ...httpStatus,
4014
+ ...REJECTED_SIGN_IN_CODES.has(code) && signIn ? { sign_in: signIn } : {}
4015
+ });
3941
4016
  process.exitCode = 1;
3942
4017
  } finally {
3943
4018
  clearTimeout(deadline);