@notis_ai/cli 0.2.0-beta.19.1 → 0.2.0-beta.196.1

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 (216) hide show
  1. package/README.md +822 -135
  2. package/bin/check-runtime.js +15 -0
  3. package/bin/notis.js +2 -0
  4. package/config/notis_app_boundary_rules.json +50 -0
  5. package/config/notis_app_design_rules.json +135 -0
  6. package/config/portal-route-roots.json +48 -0
  7. package/dist/agent-hooks/notis-agent-hook.mjs +45587 -0
  8. package/dist/base-skills/notis-apps/SKILL.md +93 -0
  9. package/dist/base-skills/notis-apps/references/architecture.md +114 -0
  10. package/dist/base-skills/notis-apps/references/context.md +81 -0
  11. package/dist/base-skills/notis-apps/references/design.md +97 -0
  12. package/dist/base-skills/notis-apps/references/memory.md +58 -0
  13. package/dist/base-skills/notis-apps/references/reading.md +67 -0
  14. package/dist/base-skills/notis-apps/references/release.md +107 -0
  15. package/dist/base-skills/notis-apps/references/sdk.md +116 -0
  16. package/dist/base-skills/notis-apps/references/troubleshooting.md +24 -0
  17. package/dist/base-skills/notis-apps/references/views.md +142 -0
  18. package/dist/base-skills/notis-cli/SKILL.md +154 -0
  19. package/dist/base-skills/notis-cli/references/app-delivery.md +19 -0
  20. package/dist/base-skills/notis-cli/references/intelligence.md +94 -0
  21. package/dist/base-skills/notis-cli/references/native-databases.md +21 -0
  22. package/dist/base-skills/notis-cli/references/tool-examples.md +56 -0
  23. package/dist/base-skills/notis-cli/references/troubleshooting.md +39 -0
  24. package/dist/base-skills/notis-query/SKILL.md +41 -0
  25. package/dist/base-skills/notis-query/references/database-discovery.md +60 -0
  26. package/dist/base-skills/notis-query/references/documents.md +63 -0
  27. package/dist/base-skills/notis-query/references/query.md +76 -0
  28. package/{template/packages/notis-sdk → dist/sdk}/package.json +14 -4
  29. package/dist/sdk/src/agentContext.ts +36 -0
  30. package/dist/sdk/src/bundleModule.ts +79 -0
  31. package/dist/sdk/src/components/Dialog.tsx +46 -0
  32. package/dist/sdk/src/components/DocumentEditor.tsx +106 -0
  33. package/dist/sdk/src/components/DocumentPage.tsx +141 -0
  34. package/dist/sdk/src/components/Markdown.tsx +60 -0
  35. package/dist/sdk/src/components/MarkdownEditor.tsx +121 -0
  36. package/dist/sdk/src/components/MultiSelectActionBar.tsx +285 -0
  37. package/dist/sdk/src/components/MultiSelectCheckbox.tsx +97 -0
  38. package/dist/sdk/src/components/MultiSelectDragOverlay.tsx +39 -0
  39. package/dist/sdk/src/components/NotisCommentBoundary.tsx +172 -0
  40. package/dist/sdk/src/components/NotisSelectionBoundary.tsx +59 -0
  41. package/dist/sdk/src/components/RecordComponents.tsx +33 -0
  42. package/dist/sdk/src/components/RenderChartData.tsx +19 -0
  43. package/dist/sdk/src/components/ShortcutHints.tsx +56 -0
  44. package/dist/sdk/src/components/Skeleton.tsx +24 -0
  45. package/dist/sdk/src/config.ts +239 -0
  46. package/dist/sdk/src/documents.ts +258 -0
  47. package/dist/sdk/src/hooks/useAction.ts +28 -0
  48. package/dist/sdk/src/hooks/useActiveResource.ts +19 -0
  49. package/dist/sdk/src/hooks/useAgentContext.ts +23 -0
  50. package/dist/sdk/src/hooks/useCloudComputer.ts +95 -0
  51. package/dist/sdk/src/hooks/useCloudComputerShell.ts +114 -0
  52. package/dist/sdk/src/hooks/useCollectionInteractions.ts +838 -0
  53. package/dist/sdk/src/hooks/useDatabaseSchema.ts +49 -0
  54. package/dist/sdk/src/hooks/useDatabaseSubscription.ts +76 -0
  55. package/dist/sdk/src/hooks/useDocument.ts +43 -0
  56. package/dist/sdk/src/hooks/useDocuments.ts +84 -0
  57. package/dist/sdk/src/hooks/useHandover.ts +78 -0
  58. package/dist/sdk/src/hooks/useLongPressSelection.ts +79 -0
  59. package/dist/sdk/src/hooks/useMultiSelect.ts +95 -0
  60. package/dist/sdk/src/hooks/useNativeDocumentBody.ts +50 -0
  61. package/dist/sdk/src/hooks/useNativeDocuments.ts +83 -0
  62. package/dist/sdk/src/hooks/useNotis.ts +42 -0
  63. package/dist/sdk/src/hooks/useNotisNavigation.ts +67 -0
  64. package/dist/sdk/src/hooks/useQuery.ts +74 -0
  65. package/dist/sdk/src/hooks/useTool.ts +65 -0
  66. package/dist/sdk/src/hooks/useToolQuery.ts +12 -0
  67. package/dist/sdk/src/hooks/useTopBarSearch.ts +81 -0
  68. package/dist/sdk/src/hooks/useUpsertDocument.ts +95 -0
  69. package/dist/sdk/src/hooks/useViewParams.ts +121 -0
  70. package/dist/sdk/src/hooks/useViewerReads.ts +129 -0
  71. package/dist/sdk/src/index.ts +200 -0
  72. package/dist/sdk/src/interactions/actions.ts +59 -0
  73. package/dist/sdk/src/interactions/shortcuts.tsx +740 -0
  74. package/dist/sdk/src/interactions/visibility.ts +13 -0
  75. package/dist/sdk/src/interactions.ts +45 -0
  76. package/dist/sdk/src/nativeData.ts +39 -0
  77. package/dist/sdk/src/presentation.tsx +82 -0
  78. package/dist/sdk/src/provider.tsx +49 -0
  79. package/dist/sdk/src/queryCache.ts +172 -0
  80. package/dist/sdk/src/queryErrors.ts +51 -0
  81. package/dist/sdk/src/runtime.ts +603 -0
  82. package/dist/sdk/src/space.ts +425 -0
  83. package/dist/sdk/src/styles.css +290 -0
  84. package/dist/sdk/src/tailwind.ts +66 -0
  85. package/dist/sdk/src/vite.ts +83 -0
  86. package/dist/skill-sync/index.js +2143 -0
  87. package/dist/skill-sync/index.js.map +7 -0
  88. package/dist/skill-sync-worker.mjs +3487 -0
  89. package/dist/space-harness/host.js +66 -0
  90. package/dist/view-renderer/dist/host.css +1 -0
  91. package/dist/view-renderer/dist/host.js +1042 -0
  92. package/dist/view-renderer/dist/theme.css +73 -0
  93. package/dist/view-renderer/src/dom.js +180 -0
  94. package/dist/view-renderer/src/errors.js +8 -0
  95. package/dist/view-renderer/src/host.tsx +173 -0
  96. package/dist/view-renderer/src/index.js +4 -0
  97. package/dist/view-renderer/src/pool.js +76 -0
  98. package/dist/view-renderer/src/remote-broker.js +59 -0
  99. package/dist/view-renderer/src/renderer.js +201 -0
  100. package/package.json +25 -8
  101. package/skills/notis-apps/cli.md +406 -0
  102. package/skills/notis-cli/AGENT_INSTRUCTIONS.md +39 -0
  103. package/skills/notis-onboarding/BRIEF.md +133 -0
  104. package/skills/notis-query/cli.md +39 -0
  105. package/src/agent-hook-entry.js +5 -0
  106. package/src/cli.js +294 -25
  107. package/src/command-specs/agents.js +392 -0
  108. package/src/command-specs/apps.js +1476 -203
  109. package/src/command-specs/auth.js +114 -137
  110. package/src/command-specs/diagnostics.js +730 -0
  111. package/src/command-specs/files.js +29 -0
  112. package/src/command-specs/handover.js +374 -0
  113. package/src/command-specs/helpers.js +86 -82
  114. package/src/command-specs/index.js +31 -6
  115. package/src/command-specs/meta.js +150 -18
  116. package/src/command-specs/onboarding.js +290 -0
  117. package/src/command-specs/profile.js +358 -0
  118. package/src/command-specs/skills.js +304 -0
  119. package/src/command-specs/smoke.js +386 -0
  120. package/src/command-specs/spaces.js +572 -0
  121. package/src/command-specs/tools.js +455 -139
  122. package/src/command-specs/views.js +69 -0
  123. package/src/runtime/agent-browser.js +700 -0
  124. package/src/runtime/agent-memory-state.js +126 -0
  125. package/src/runtime/agent-setup.js +383 -0
  126. package/src/runtime/app-boundary-validator.js +407 -0
  127. package/src/runtime/app-changelog.js +79 -0
  128. package/src/runtime/app-data-literals.js +82 -0
  129. package/src/runtime/app-platform.js +2752 -237
  130. package/src/runtime/app-registry-scaffolds.js +367 -0
  131. package/src/runtime/app-test-server.js +293 -0
  132. package/src/runtime/assets/store-screenshot-dark.png +0 -0
  133. package/src/runtime/auth-recovery.js +110 -0
  134. package/src/runtime/base-skills.d.ts +20 -0
  135. package/src/runtime/base-skills.js +167 -0
  136. package/src/runtime/channel.js +133 -0
  137. package/src/runtime/confined-space-build.js +74 -0
  138. package/src/runtime/confined-space-verify.js +49 -0
  139. package/src/runtime/delegated-context.js +68 -0
  140. package/src/runtime/errors.js +1 -0
  141. package/src/runtime/git.js +233 -0
  142. package/src/runtime/login-listener.js +15 -0
  143. package/src/runtime/native-record-files.js +47 -0
  144. package/src/runtime/oauth.js +2622 -0
  145. package/src/runtime/output.js +37 -5
  146. package/src/runtime/ports.js +31 -0
  147. package/src/runtime/profiles.js +906 -55
  148. package/src/runtime/retired-sdk-files.js +20 -0
  149. package/src/runtime/screenshot-framing.js +85 -0
  150. package/src/runtime/skill-sync/cloud-client.ts +121 -0
  151. package/src/runtime/skill-sync/index.ts +905 -0
  152. package/src/runtime/skill-sync/local-scanner.ts +1259 -0
  153. package/src/runtime/skill-sync/native-identity.ts +102 -0
  154. package/src/runtime/skill-sync/native-plan.ts +59 -0
  155. package/src/runtime/skill-sync/symlink-manager.ts +433 -0
  156. package/src/runtime/skill-sync/sync-plan.ts +54 -0
  157. package/src/runtime/skill-sync/types.ts +157 -0
  158. package/src/runtime/skill-sync/write-cloud-skill.ts +50 -0
  159. package/src/runtime/skill-sync-service.js +109 -0
  160. package/src/runtime/source-root.js +32 -0
  161. package/src/runtime/space-collection-scaffold.js +66 -0
  162. package/src/runtime/space-database-structures.js +229 -0
  163. package/src/runtime/space-fixture-broker.js +50 -0
  164. package/src/runtime/space-lock.js +337 -0
  165. package/src/runtime/space-platform.js +105 -0
  166. package/src/runtime/space-source.js +281 -0
  167. package/src/runtime/space-test-server.js +327 -0
  168. package/src/runtime/space-verification.js +89 -0
  169. package/src/runtime/space-verify-browser-worker.js +51 -0
  170. package/src/runtime/space-view-manifest.js +254 -0
  171. package/src/runtime/store-screenshot.js +146 -0
  172. package/src/runtime/sync-skills.d.ts +37 -0
  173. package/src/runtime/sync-skills.js +231 -0
  174. package/src/runtime/telemetry.js +92 -0
  175. package/src/runtime/transport.js +331 -45
  176. package/src/runtime/view-render.js +49 -0
  177. package/src/skill-sync-worker-entry.js +2 -0
  178. package/src/skill-sync-worker.js +50 -0
  179. package/src/space-harness-host.ts +103 -0
  180. package/template/.harness/index.html.tmpl +435 -0
  181. package/template/CHANGELOG.md +5 -0
  182. package/template/app/globals.css +29 -3
  183. package/template/app/layout.tsx +6 -3
  184. package/template/app/page.tsx +49 -42
  185. package/template/components/page-heading.tsx +23 -0
  186. package/template/components/ui/badge.tsx +7 -4
  187. package/template/components/ui/button.tsx +1 -1
  188. package/template/components/ui/card.tsx +24 -11
  189. package/template/components/ui/native-select.tsx +24 -0
  190. package/template/notis.config.ts +24 -6
  191. package/template/package-lock.json +3642 -0
  192. package/template/package.json +19 -16
  193. package/template/postcss.config.mjs +1 -1
  194. package/template/tailwind.config.ts +1 -6
  195. package/template/tsconfig.json +1 -0
  196. package/src/command-specs/db.js +0 -163
  197. package/src/runtime/app-preview-server.js +0 -312
  198. package/template/packages/notis-sdk/src/config.ts +0 -48
  199. package/template/packages/notis-sdk/src/helpers.ts +0 -131
  200. package/template/packages/notis-sdk/src/hooks/useAppState.ts +0 -50
  201. package/template/packages/notis-sdk/src/hooks/useCollectionItem.ts +0 -58
  202. package/template/packages/notis-sdk/src/hooks/useDatabase.ts +0 -87
  203. package/template/packages/notis-sdk/src/hooks/useDocument.ts +0 -61
  204. package/template/packages/notis-sdk/src/hooks/useNotis.ts +0 -31
  205. package/template/packages/notis-sdk/src/hooks/useNotisNavigation.ts +0 -49
  206. package/template/packages/notis-sdk/src/hooks/useTool.ts +0 -49
  207. package/template/packages/notis-sdk/src/hooks/useUpsertDocument.ts +0 -57
  208. package/template/packages/notis-sdk/src/index.ts +0 -47
  209. package/template/packages/notis-sdk/src/provider.tsx +0 -44
  210. package/template/packages/notis-sdk/src/runtime.ts +0 -159
  211. package/template/packages/notis-sdk/src/styles.css +0 -123
  212. package/template/packages/notis-sdk/src/vite.ts +0 -54
  213. package/template/packages/notis-sdk/tsconfig.json +0 -15
  214. /package/{template/packages/notis-sdk → dist/sdk}/src/hooks/useBackend.ts +0 -0
  215. /package/{template/packages/notis-sdk → dist/sdk}/src/hooks/useTools.ts +0 -0
  216. /package/{template/packages/notis-sdk → dist/sdk}/src/ui.ts +0 -0
@@ -0,0 +1,239 @@
1
+ export { defineSpace, defineSpaces } from './space';
2
+ export type { SpaceDefinition, SpacesWorkspace, SpaceActionTemplate, SpaceResourceReference, SpaceDatabaseCreate } from './space';
3
+ export type { SpaceViewParam, SpaceViewParamType, SpaceShows, SpaceMemoryPolicy, SpaceMemorySnapshot, SpaceChrome, SpaceMarkdownInput } from './space';
4
+
5
+ /**
6
+ * Configuration utilities for notis.config.ts.
7
+ *
8
+ * Usage:
9
+ * ```ts
10
+ * // notis.config.ts
11
+ * import { defineNotisApp } from '@notis/sdk/config';
12
+ *
13
+ * export default defineNotisApp({
14
+ * name: 'My App',
15
+ * description: 'Does things',
16
+ * icon: 'phosphor:squares-four',
17
+ * databases: ['tasks'],
18
+ * routes: [
19
+ * {
20
+ * path: '/',
21
+ * slug: 'notes',
22
+ * name: 'Notes',
23
+ * default: true,
24
+ * collection: {
25
+ * database: 'notes',
26
+ * titleProperty: 'Name',
27
+ * parentProperty: 'Parent',
28
+ * sidebar: {
29
+ * mode: 'tree',
30
+ * allowCreate: true,
31
+ * },
32
+ * },
33
+ * },
34
+ * ],
35
+ * tools: [...],
36
+ * });
37
+ * ```
38
+ */
39
+
40
+ export interface NotisRouteConfig {
41
+ path: string;
42
+ slug: string;
43
+ name: string;
44
+ icon?: string;
45
+ parentSlug?: string | null;
46
+ default?: boolean;
47
+ /**
48
+ * Allow the host to address an app-owned resource on this route through the
49
+ * canonical `?resource=<id>` deep link. Read the incoming id with
50
+ * `useNotis().resourceId`.
51
+ */
52
+ resourceDeepLinks?: boolean;
53
+ exportName?: string;
54
+ collection?: {
55
+ database: string;
56
+ titleProperty: string;
57
+ parentProperty?: string | null;
58
+ sidebar?: {
59
+ mode: 'flat-list' | 'tree';
60
+ allowCreate: boolean;
61
+ };
62
+ };
63
+ }
64
+
65
+ export const NOTIS_APP_CATEGORIES = [
66
+ 'Productivity',
67
+ 'Sales & Marketing',
68
+ 'Operations',
69
+ 'Product & Engineering',
70
+ 'Personal',
71
+ ] as const;
72
+
73
+ export type NotisAppCategory = typeof NOTIS_APP_CATEGORIES[number];
74
+
75
+ export interface NotisAppDatabaseConfig {
76
+ /** Database slug, as declared by the app. */
77
+ slug: string;
78
+ /**
79
+ * Ship this database's rows to everyone who installs the app.
80
+ *
81
+ * Off by default: declaring a database publishes its STRUCTURE, never its
82
+ * content. Turn it on only for starter content that every installer should
83
+ * receive - a default folder tree, a set of templates - and never for a
84
+ * database that accumulates the author's own data.
85
+ */
86
+ seedDocuments?: boolean;
87
+ }
88
+
89
+ export interface NotisAppAuthor {
90
+ name: string;
91
+ handle?: string;
92
+ url?: string;
93
+ }
94
+
95
+ export interface NotisAppScreenshotConfig {
96
+ /** Conventional metadata/screenshot-N.png source path. */
97
+ path: string;
98
+ /** Meaningful description used by the Store gallery and assistive technology. */
99
+ alt: string;
100
+ /** Route slug captured by `notis apps screenshot`. */
101
+ route?: string;
102
+ /**
103
+ * Named scenario from metadata/screenshot-fixtures.json. Its `tools` and
104
+ * `requests` override the file-level ones key by key for this capture, and
105
+ * its `actions` run once the route has mounted -- so one route can be shown
106
+ * in several states (populated, empty, a panel opened) without the states
107
+ * leaking into each other.
108
+ */
109
+ scenario?: string;
110
+ /** Optional CSS selector captured as the truthful focal region for this Store image. */
111
+ focus?: string;
112
+ /** Portal color scheme used while rendering this screenshot. Defaults to light. */
113
+ theme?: 'light' | 'dark';
114
+ }
115
+
116
+ /**
117
+ * Named accent tokens for an app's avatar. Keep in sync with the portal
118
+ * `ACCENT_NAMES` and the server `ACCENT_TOKENS`.
119
+ */
120
+ export const NOTIS_APP_ACCENTS = [
121
+ 'blue',
122
+ 'violet',
123
+ 'emerald',
124
+ 'amber',
125
+ 'rose',
126
+ 'sky',
127
+ 'fuchsia',
128
+ 'teal',
129
+ ] as const;
130
+
131
+ export type NotisAppAccent = typeof NOTIS_APP_ACCENTS[number];
132
+
133
+ export interface NotisAppCapabilities {
134
+ /**
135
+ * Read every database in the workspace, not only the ones this app declares
136
+ * in `databases` or created itself.
137
+ *
138
+ * An app runtime is otherwise sandboxed to its own databases, so a catalog or
139
+ * explorer app sees an empty list without this. `'read'` is the only accepted
140
+ * value and it never grants writes: `LOCAL_NOTIS_DATABASE_UPSERT_*` stays
141
+ * bound to the app's own databases.
142
+ */
143
+ workspaceDatabases?: 'read';
144
+
145
+ /**
146
+ * Read a few facts about the user's cloud computer: whether a sandbox exists
147
+ * and is running, and whether the GitHub CLI is signed in there.
148
+ *
149
+ * Without this an app has to infer them — the Workspaces app treated a
150
+ * configured repository as proof that `gh auth login` had happened, which
151
+ * cannot show an account name and cannot notice a revoked credential.
152
+ * `'read'` never creates, resumes or commands a sandbox. Read it with
153
+ * `useCloudComputer()`.
154
+ *
155
+ * `'shell'` additionally asks to command the cloud computer: it unlocks
156
+ * `LOCAL_NOTIS_RUN_SANDBOX_SHELL` and the sandbox file tools from this app's
157
+ * views (they are denied to every view otherwise), and implies the read
158
+ * facts. This is the same authority the user's own agent has on the sandbox,
159
+ * so the user is asked for it explicitly at install or in the Store grant
160
+ * step; declare it only when the app's core actions genuinely run there.
161
+ */
162
+ cloudComputer?: 'read' | 'shell';
163
+ }
164
+
165
+ /**
166
+ * Execution hint for a tool whose public name is generated by a provider.
167
+ *
168
+ * MCP public names may be truncated or deduplicated, so the upstream action
169
+ * cannot always be reconstructed from the final `LOCAL_MCP_*` name. Binding
170
+ * the two lets the host skip provider schema discovery on direct calls while
171
+ * the public name remains the user-approved permission boundary.
172
+ */
173
+ export interface NotisAppToolBinding {
174
+ /** Exact final name also present in `tools`. */
175
+ name: string;
176
+ /** Exact upstream MCP action name, for example `execute_sql`. */
177
+ providerToolName: string;
178
+ }
179
+
180
+ export interface NotisAppConfig {
181
+ /** Standalone reports share the view engine without app installation. */
182
+ kind?: 'app' | 'report';
183
+ /** Existing data sources, never owned or materialized by a report. */
184
+ databaseAccess?: Array<{ id: string; access: 'read' | 'write' }>;
185
+ /** URL-safe app slug. Existing apps may still use a display name here. */
186
+ name: string;
187
+ /** Human display title, Raycast-style. Falls back to `name`. */
188
+ title?: string;
189
+ description?: string;
190
+ /**
191
+ * App icon. A `phosphor:<name>` value (e.g. `phosphor:dice-five`) or
192
+ * `metadata/icon.png`. When unset, the app shows its two-letter initials.
193
+ */
194
+ icon?: string;
195
+ /**
196
+ * Optional accent color for the app avatar. One of {@link NOTIS_APP_ACCENTS}.
197
+ * When unset, a stable accent is derived automatically from the app id.
198
+ */
199
+ accent?: NotisAppAccent;
200
+ author?: NotisAppAuthor;
201
+ categories?: NotisAppCategory[];
202
+ tagline?: string;
203
+ /** @deprecated Add release entries to the root CHANGELOG.md instead. */
204
+ versionNotes?: string;
205
+ /** Editorial screenshot order and capture scenarios for the Store listing. */
206
+ screenshots?: NotisAppScreenshotConfig[];
207
+ /**
208
+ * Databases this app owns. A bare string publishes structure only; use the
209
+ * object form to opt a database into shipping its rows to installers.
210
+ */
211
+ databases?: (string | NotisAppDatabaseConfig)[];
212
+ /**
213
+ * Extra permissions the app asks for at install time. Everything here widens
214
+ * what the app can reach beyond its own data, so each one is surfaced to the
215
+ * user before they install.
216
+ */
217
+ capabilities?: NotisAppCapabilities;
218
+ routes?: NotisRouteConfig[];
219
+ /**
220
+ * Final tool names this app can call at runtime, enforced server-side. Use
221
+ * names returned by shared discovery, including native `LOCAL_NOTIS_*`,
222
+ * connected-service names such as `GMAIL_SEND_EMAIL`,
223
+ * `LOCAL_POSTFORME_*`, and `LOCAL_MCP_<SERVER>_<TOOL>`. App code calls
224
+ * each declared name directly with `useTool`; metered calls use the shared
225
+ * credit-cap and usage-billing path.
226
+ */
227
+ tools?: string[];
228
+ /** Optional execution bindings for provider-generated tool names. */
229
+ toolBindings?: NotisAppToolBinding[];
230
+ }
231
+
232
+ /**
233
+ * Identity function that provides type checking and autocomplete for the
234
+ * Notis app configuration. The returned object is read at build time by
235
+ * `notis apps build` to generate the manifest.
236
+ */
237
+ export function defineNotisApp(config: NotisAppConfig): NotisAppConfig {
238
+ return config;
239
+ }
@@ -0,0 +1,258 @@
1
+ /**
2
+ * Document data helpers: normalize raw tool results (Notion-shaped property
3
+ * values, snake_case fields) into the SDK's `DocumentRecord`/`DatabaseProperty`
4
+ * shapes, and derive plain-text projections from typed content.
5
+ *
6
+ * These are pure functions — safe in any context (portal, dev harness, tests).
7
+ */
8
+
9
+ import type {
10
+ DatabaseProperty,
11
+ DatabasePropertyOption,
12
+ DatabasePropertyType,
13
+ DocumentContentType,
14
+ DocumentRecord,
15
+ SecretPropertyValue,
16
+ } from './runtime';
17
+
18
+ // ---------------------------------------------------------------------------
19
+ // Value primitives
20
+ // ---------------------------------------------------------------------------
21
+
22
+ export function isPresentString(value: unknown): value is string {
23
+ return typeof value === 'string' && value.trim().length > 0;
24
+ }
25
+
26
+ export function asRecord(value: unknown): Record<string, unknown> | null {
27
+ return value && typeof value === 'object' && !Array.isArray(value)
28
+ ? (value as Record<string, unknown>)
29
+ : null;
30
+ }
31
+
32
+ export function optionalString(value: unknown): string | null {
33
+ return isPresentString(value) ? value.trim() : null;
34
+ }
35
+
36
+ /** Flattens a Notion-shaped rich_text array (or plain string) to text. */
37
+ export function extractRichText(value: unknown): string {
38
+ if (typeof value === 'string') return value;
39
+ if (!Array.isArray(value)) return '';
40
+ return value
41
+ .map((item) => {
42
+ const record = asRecord(item);
43
+ const text = asRecord(record?.text);
44
+ return optionalString(text?.content) ?? optionalString(record?.plain_text) ?? '';
45
+ })
46
+ .join('');
47
+ }
48
+
49
+ /**
50
+ * Reads a `secret` property value. The platform only ever sends the pointer
51
+ * ({present, reference, status, metadata}), so this rebuilds it field by field
52
+ * rather than passing the payload through — an app can never surface secret
53
+ * material through this helper, whatever the server sent.
54
+ */
55
+ export function getSecretValue(value: unknown): SecretPropertyValue {
56
+ const record = asRecord(value);
57
+ const metadata = asRecord(record?.metadata);
58
+ return {
59
+ present: record?.present === true,
60
+ reference: optionalString(record?.reference),
61
+ status: optionalString(record?.status),
62
+ metadata,
63
+ };
64
+ }
65
+
66
+ /** Extracts the ids of a normalized relation property value. */
67
+ export function getRelationIds(value: unknown): string[] {
68
+ if (!Array.isArray(value)) return [];
69
+ return value.filter((item): item is string => isPresentString(item));
70
+ }
71
+
72
+ // ---------------------------------------------------------------------------
73
+ // Property + document normalization
74
+ // ---------------------------------------------------------------------------
75
+
76
+ /**
77
+ * Collapses a Notion-shaped property value ({type: 'select', select: {...}})
78
+ * into a plain JS value (string, string[], number, boolean, ...). Values that
79
+ * are already plain pass through unchanged.
80
+ */
81
+ export function normalizePropertyValue(value: unknown): unknown {
82
+ const record = asRecord(value);
83
+ if (!record) return value;
84
+
85
+ const type = optionalString(record.type);
86
+ if (!type) return value;
87
+
88
+ if (type === 'title') return extractRichText(record.title);
89
+ if (type === 'rich_text') return extractRichText(record.rich_text);
90
+ if (type === 'select' || type === 'status') {
91
+ return optionalString(asRecord(record[type])?.name) ?? record[type] ?? null;
92
+ }
93
+ if (type === 'multi_select') {
94
+ const items = Array.isArray(record.multi_select) ? record.multi_select : [];
95
+ return items.map((item) => optionalString(asRecord(item)?.name) ?? item).filter(Boolean);
96
+ }
97
+ if (type === 'relation') {
98
+ const items = Array.isArray(record.relation) ? record.relation : [];
99
+ return items.map((item) => optionalString(asRecord(item)?.id) ?? item).filter(Boolean);
100
+ }
101
+ if (type === 'date') return optionalString(asRecord(record.date)?.start) ?? record.date ?? null;
102
+ // Before the `type in record` fallthrough: a secret value has no `secret`
103
+ // key, so passing it through would hand the caller the raw payload.
104
+ if (type === 'secret') return getSecretValue(record);
105
+ if (type in record) return record[type];
106
+ return value;
107
+ }
108
+
109
+ function normalizeContentType(value: unknown): DocumentContentType | null {
110
+ return value === 'markdown' || value === 'file' || value === 'view' ? value : null;
111
+ }
112
+
113
+ /**
114
+ * Normalizes a raw document from a Notis database tool result
115
+ * (LOCAL_NOTIS_DATABASE_QUERY / GET_DOCUMENT / UPSERT_*) into a
116
+ * `DocumentRecord`: camelCases fields and collapses property values.
117
+ */
118
+ export function normalizeDocumentRecord(value: unknown): DocumentRecord {
119
+ const record = asRecord(value) ?? {};
120
+ const rawProperties = asRecord(record.properties) ?? {};
121
+ const properties: Record<string, unknown> = {};
122
+ for (const [key, propertyValue] of Object.entries(rawProperties)) {
123
+ properties[key] = normalizePropertyValue(propertyValue);
124
+ }
125
+
126
+ return {
127
+ id: optionalString(record.id) ?? '',
128
+ recordKey: optionalString(record.recordKey) ?? optionalString(record.record_key) ?? undefined,
129
+ revision: typeof record.revision === 'number' ? record.revision : undefined,
130
+ title: optionalString(record.title) ?? 'Untitled',
131
+ url: optionalString(record.url),
132
+ properties,
133
+ icon: optionalString(record.icon),
134
+ cover: optionalString(record.cover),
135
+ databaseSlug: optionalString(record.databaseSlug) ?? optionalString(record.database_slug) ?? undefined,
136
+ contentType: normalizeContentType(record.contentType ?? record.content_type),
137
+ fileType: optionalString(record.fileType) ?? optionalString(record.file_type),
138
+ contentBlocknote: Array.isArray(record.contentBlocknote)
139
+ ? (record.contentBlocknote as Array<Record<string, unknown>>)
140
+ : Array.isArray(record.content_blocknote)
141
+ ? (record.content_blocknote as Array<Record<string, unknown>>)
142
+ : null,
143
+ contentMarkdown: optionalString(record.contentMarkdown) ?? optionalString(record.content_markdown),
144
+ plainText: optionalString(record.plainText) ?? optionalString(record.plain_text),
145
+ viewType: optionalString(record.viewType) ?? optionalString(record.view_type),
146
+ viewState: asRecord(record.viewState) ?? asRecord(record.view_state),
147
+ viewRevision:
148
+ typeof (record.viewRevision ?? record.view_revision) === 'number'
149
+ ? Number(record.viewRevision ?? record.view_revision)
150
+ : null,
151
+ createdAt:
152
+ optionalString(record.createdAt)
153
+ ?? optionalString(record.created_at)
154
+ ?? optionalString(record.created_time),
155
+ lastEditedTime:
156
+ optionalString(record.lastEditedTime)
157
+ ?? optionalString(record.last_edited_time)
158
+ ?? optionalString(record.updated_at),
159
+ };
160
+ }
161
+
162
+ /** Normalizes a raw schema property from LOCAL_NOTIS_DATABASE_GET_DATABASE. */
163
+ export function normalizeDatabaseProperty(value: unknown): DatabaseProperty | null {
164
+ const record = asRecord(value);
165
+ const name = optionalString(record?.name);
166
+ if (!record || !name) return null;
167
+
168
+ const rawOptions = Array.isArray(record.options) ? record.options : [];
169
+ const options = rawOptions.flatMap((option): DatabasePropertyOption[] => {
170
+ const optionRecord = asRecord(option);
171
+ const optionName = optionalString(optionRecord?.name);
172
+ if (!optionRecord || !optionName) return [];
173
+ return [{
174
+ id: optionalString(optionRecord.id),
175
+ name: optionName,
176
+ color: optionalString(optionRecord.color),
177
+ order: typeof optionRecord.order === 'number' ? optionRecord.order : undefined,
178
+ }];
179
+ });
180
+
181
+ return {
182
+ id: optionalString(record.id),
183
+ name,
184
+ type: (optionalString(record.type) ?? 'rich_text') as DatabasePropertyType,
185
+ description: optionalString(record.description),
186
+ options,
187
+ };
188
+ }
189
+
190
+ // ---------------------------------------------------------------------------
191
+ // Plain-text projections
192
+ // ---------------------------------------------------------------------------
193
+
194
+ /** Strips markdown syntax to readable plain text (previews, search). */
195
+ export function markdownToPlainText(markdown: string): string {
196
+ return markdown
197
+ // fenced code blocks: keep the code, drop the fences
198
+ .replace(/```[^\n]*\n?/g, '')
199
+ // images: keep alt text
200
+ .replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1')
201
+ // links: keep link text
202
+ .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
203
+ // html tags
204
+ .replace(/<[^>]+>/g, ' ')
205
+ // headings, blockquotes, list markers, task boxes
206
+ .replace(/^\s{0,3}(#{1,6}\s+|>\s?|[-*+]\s+(\[[ xX]\]\s+)?|\d+\.\s+)/gm, '')
207
+ // emphasis / strikethrough / inline code
208
+ .replace(/(\*\*|__|[*_~`])/g, '')
209
+ // table separators and pipes
210
+ .replace(/^\s*\|?[-:| ]+\|?\s*$/gm, '')
211
+ .replace(/\|/g, ' ')
212
+ // horizontal rules
213
+ .replace(/^\s*([-*_]\s*){3,}$/gm, '')
214
+ .replace(/\s+/g, ' ')
215
+ .trim();
216
+ }
217
+
218
+ /** Flattens BlockNote block JSON to plain text. */
219
+ export function blockNoteToPlainText(blocks: unknown): string {
220
+ const segments: string[] = [];
221
+
222
+ function visit(node: unknown): void {
223
+ if (typeof node === 'string') {
224
+ if (node.trim()) segments.push(node.trim());
225
+ return;
226
+ }
227
+ if (Array.isArray(node)) {
228
+ node.forEach(visit);
229
+ return;
230
+ }
231
+ const record = asRecord(node);
232
+ if (!record) return;
233
+ if (typeof record.text === 'string' && record.text.trim()) {
234
+ segments.push(record.text.trim());
235
+ }
236
+ visit(record.content);
237
+ visit(record.children);
238
+ }
239
+
240
+ visit(blocks);
241
+ return segments.join(' ').replace(/\s+/g, ' ').trim();
242
+ }
243
+
244
+ /**
245
+ * Best-available plain-text preview for a document:
246
+ * plainText -> contentMarkdown -> contentBlocknote -> title.
247
+ */
248
+ export function getDocumentPreview(document: DocumentRecord): string {
249
+ if (isPresentString(document.plainText)) {
250
+ return document.plainText.replace(/\s+/g, ' ').trim();
251
+ }
252
+ if (isPresentString(document.contentMarkdown)) {
253
+ return markdownToPlainText(document.contentMarkdown);
254
+ }
255
+ const fromBlocks = blockNoteToPlainText(document.contentBlocknote);
256
+ if (fromBlocks) return fromBlocks;
257
+ return isPresentString(document.title) ? document.title : 'Untitled';
258
+ }
@@ -0,0 +1,28 @@
1
+ 'use client';
2
+
3
+ import { useCallback, useState } from 'react';
4
+ import { useNotisRuntime } from '../provider';
5
+ import { useQuery, type UseQueryOptions, type UseQueryResult } from './useQuery';
6
+ import type { SpaceActionOptions } from '../space';
7
+
8
+ export function useAction<TInput extends Record<string, unknown> = Record<string, unknown>, TResult = unknown>(actionId: string): {
9
+ call: (inputs: TInput, options?: SpaceActionOptions) => Promise<TResult>; loading: boolean; error: Error | null;
10
+ } {
11
+ const runtime = useNotisRuntime();
12
+ const [pending, setPending] = useState(0);
13
+ const [error, setError] = useState<Error | null>(null);
14
+ const call = useCallback(async (inputs: TInput, options?: SpaceActionOptions) => {
15
+ if (runtime?.resource?.kind !== 'space' || !runtime.callAction) throw new Error('A Space action runtime is required.');
16
+ setPending((value) => value + 1); setError(null);
17
+ try { return await runtime.callAction<TResult>(actionId, inputs, options); }
18
+ catch (cause) { const failure = cause instanceof Error ? cause : new Error(String(cause)); setError(failure); throw failure; }
19
+ finally { setPending((value) => value - 1); }
20
+ }, [runtime, actionId]);
21
+ return { call, loading: pending > 0, error };
22
+ }
23
+
24
+ export function useActionQuery<TResult = unknown>(actionId: string, inputs: Record<string, unknown>,
25
+ options: UseQueryOptions = { readOnly: true }): UseQueryResult<TResult> {
26
+ const { call } = useAction<Record<string, unknown>, TResult>(actionId);
27
+ return useQuery(['action', actionId, inputs], () => call(inputs, { readOnly: true, dedupe: true }), options);
28
+ }
@@ -0,0 +1,19 @@
1
+ import { useEffect, useMemo } from 'react';
2
+ import { useNotisRuntime } from '../provider';
3
+ import type { ContextResource } from '../runtime';
4
+
5
+ function stableResource(resource: ContextResource | null): string {
6
+ return JSON.stringify(resource);
7
+ }
8
+
9
+ /** Keep Notis aware of the resource currently open inside an app view. */
10
+ export function useActiveResource(resource: ContextResource | null): void {
11
+ const runtime = useNotisRuntime();
12
+ const signature = stableResource(resource);
13
+ const stable = useMemo(() => resource, [signature]);
14
+
15
+ useEffect(() => {
16
+ runtime?.publishActiveResource?.(stable);
17
+ return () => runtime?.publishActiveResource?.(null);
18
+ }, [runtime, stable]);
19
+ }
@@ -0,0 +1,23 @@
1
+ 'use client';
2
+ import { useMemo } from 'react';
3
+ import { useNotisRuntime } from '../provider';
4
+ import type { AgentContextItem } from '../agentContext';
5
+
6
+ /** Share context without owning storage, opening a new thread, or sending a message. */
7
+ export function useAgentContext() {
8
+ const runtime = useNotisRuntime();
9
+ return useMemo(() => ({
10
+ add(item: AgentContextItem): Promise<boolean> {
11
+ if (!runtime?.addContext) return Promise.reject(new Error('Chat context is unavailable in this host.'));
12
+ return runtime.addContext(item);
13
+ },
14
+ update(item: AgentContextItem): Promise<boolean> {
15
+ if (!runtime?.updateContext) return Promise.reject(new Error('Chat context is unavailable in this host.'));
16
+ return runtime.updateContext(item);
17
+ },
18
+ remove(id: string): Promise<boolean> {
19
+ if (!runtime?.removeContext) return Promise.reject(new Error('Chat context is unavailable in this host.'));
20
+ return runtime.removeContext(id);
21
+ },
22
+ }), [runtime]);
23
+ }
@@ -0,0 +1,95 @@
1
+ 'use client';
2
+
3
+ import { useCallback, useRef } from 'react';
4
+ import { useQuery } from './useQuery';
5
+ import { useNotisRuntime } from '../provider';
6
+ import { queryKey } from '../queryCache';
7
+ import { spaceQueryKey } from '../space';
8
+ import type { CloudComputerFacts, NotisRuntime } from '../runtime';
9
+
10
+ /** Cache key of the facts read; re-read once the viewer allows a Space to use the cloud computer. */
11
+ export const CLOUD_COMPUTER_FACTS_KEY = ['cloud-computer-facts'] as const;
12
+
13
+ /** Marks the facts stale in the host cache so every mounted `useCloudComputer()` reads them again. */
14
+ export function invalidateCloudComputerFacts(runtime: NotisRuntime | null): void {
15
+ try {
16
+ runtime?.queryClient?.invalidate(queryKey(spaceQueryKey(runtime, CLOUD_COMPUTER_FACTS_KEY)));
17
+ } catch {
18
+ // A host without a Space access context has no shared facts cache to refresh.
19
+ }
20
+ }
21
+
22
+ export interface UseCloudComputerResult {
23
+ /**
24
+ * The facts, or null while the first read is in flight. `facts.available`
25
+ * is false when this host cannot answer — render the app's own fallback.
26
+ */
27
+ facts: CloudComputerFacts | null;
28
+ loading: boolean;
29
+ isFetching: boolean;
30
+ error: Error | null;
31
+ /** Re-read the facts. The platform caches them for a few minutes. */
32
+ refresh: () => Promise<void>;
33
+ /**
34
+ * Space only (`cloudComputer: 'read'` or `'shell'`): ask the host to show its approval prompt.
35
+ * Resolves true once the viewer allowed it (the facts are then read again), false when they did
36
+ * not, and null on hosts without the prompt (Beta Apps, Sites, previews offline).
37
+ */
38
+ requestApproval: () => Promise<boolean | null>;
39
+ }
40
+
41
+ const UNAVAILABLE: CloudComputerFacts = {
42
+ available: false,
43
+ reason: 'unsupported_host',
44
+ sandbox: null,
45
+ cli_auth: {
46
+ gh: { authenticated: null, account: null, checked_at: null, reason: 'unsupported_host' },
47
+ },
48
+ };
49
+
50
+ /**
51
+ * Read-only facts about the user's cloud computer.
52
+ *
53
+ * ```tsx
54
+ * const { facts } = useCloudComputer();
55
+ * const gh = facts?.available ? facts.cli_auth.gh : null;
56
+ *
57
+ * return gh?.authenticated
58
+ * ? <p>Signed in as {gh.account}</p>
59
+ * : <GithubConnect />;
60
+ * ```
61
+ *
62
+ * Requires `capabilities.cloudComputer: 'read'` in `notis.config.ts` and the
63
+ * user's approval at install time. In a Space, declare `cloudComputer: 'read'`
64
+ * (or `'shell'`) in `defineSpace`; until the viewer allows it the facts answer
65
+ * unavailable, so offer `requestApproval()`. It answers with state the platform already
66
+ * holds: reading it never creates, resumes or commands a sandbox, and the GitHub
67
+ * probe only runs when the sandbox is already awake. `authenticated: null`
68
+ * therefore means *unknown*, not *signed out* — keep the app's own fallback for
69
+ * that case and for hosts that answer `{ available: false }` (the dev harness,
70
+ * the vite preview).
71
+ */
72
+ export function useCloudComputer(): UseCloudComputerResult {
73
+ const runtime = useNotisRuntime();
74
+ const explicitRefresh = useRef(false);
75
+ const query = useQuery<CloudComputerFacts>(CLOUD_COMPUTER_FACTS_KEY, async () => {
76
+ const refresh = explicitRefresh.current;
77
+ explicitRefresh.current = false;
78
+ return runtime?.cloudComputerFacts ? runtime.cloudComputerFacts(refresh ? { refresh: true } : undefined) : UNAVAILABLE;
79
+ }, { readOnly: true });
80
+ const refresh = useCallback(async () => {
81
+ explicitRefresh.current = true;
82
+ await query.refetch();
83
+ }, [query.refetch]);
84
+ const transport = runtime?.spaceCloudComputer;
85
+ const requestApproval = useCallback(async () => {
86
+ if (!transport) return null;
87
+ const status = await transport.requestApproval();
88
+ if (status?.approved !== true) return false;
89
+ invalidateCloudComputerFacts(runtime);
90
+ await query.refetch();
91
+ return true;
92
+ }, [query.refetch, runtime, transport]);
93
+ return { facts: query.data ?? (query.error ? UNAVAILABLE : null), loading: query.loading,
94
+ isFetching: query.isFetching, error: query.error, refresh, requestApproval };
95
+ }