@lavitre/apps 1.49.0

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 (69) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +121 -0
  3. package/dist/Common/AiChannel.d.ts +59 -0
  4. package/dist/Common/AiChannel.js +97 -0
  5. package/dist/Common/AiChannel.js.map +1 -0
  6. package/dist/Common/BlobStore.d.ts +44 -0
  7. package/dist/Common/BlobStore.js +186 -0
  8. package/dist/Common/BlobStore.js.map +1 -0
  9. package/dist/Common/Common.Model.d.ts +1020 -0
  10. package/dist/Common/Common.Model.js +21 -0
  11. package/dist/Common/Common.Model.js.map +1 -0
  12. package/dist/Common/CrdtChannel.d.ts +198 -0
  13. package/dist/Common/CrdtChannel.js +659 -0
  14. package/dist/Common/CrdtChannel.js.map +1 -0
  15. package/dist/Common/Version.d.ts +21 -0
  16. package/dist/Common/Version.js +62 -0
  17. package/dist/Common/Version.js.map +1 -0
  18. package/dist/Common/index.d.ts +6 -0
  19. package/dist/Common/index.js +32 -0
  20. package/dist/Common/index.js.map +1 -0
  21. package/dist/CompanionConnector/CompanionConnector.Model.d.ts +85 -0
  22. package/dist/CompanionConnector/CompanionConnector.Model.js +17 -0
  23. package/dist/CompanionConnector/CompanionConnector.Model.js.map +1 -0
  24. package/dist/CompanionConnector/CompanionConnector.d.ts +28 -0
  25. package/dist/CompanionConnector/CompanionConnector.js +385 -0
  26. package/dist/CompanionConnector/CompanionConnector.js.map +1 -0
  27. package/dist/CompanionConnector/index.d.ts +2 -0
  28. package/dist/CompanionConnector/index.js +3 -0
  29. package/dist/CompanionConnector/index.js.map +1 -0
  30. package/dist/CompanionFrame/CompanionFrame.d.ts +103 -0
  31. package/dist/CompanionFrame/CompanionFrame.js +100 -0
  32. package/dist/CompanionFrame/CompanionFrame.js.map +1 -0
  33. package/dist/CompanionFrame/index.d.ts +1 -0
  34. package/dist/CompanionFrame/index.js +2 -0
  35. package/dist/CompanionFrame/index.js.map +1 -0
  36. package/dist/Connector/Connector.Model.d.ts +567 -0
  37. package/dist/Connector/Connector.Model.js +2 -0
  38. package/dist/Connector/Connector.Model.js.map +1 -0
  39. package/dist/Connector/Connector.d.ts +227 -0
  40. package/dist/Connector/Connector.js +1337 -0
  41. package/dist/Connector/Connector.js.map +1 -0
  42. package/dist/Connector/index.d.ts +2 -0
  43. package/dist/Connector/index.js +3 -0
  44. package/dist/Connector/index.js.map +1 -0
  45. package/dist/Frame/Frame.Model.d.ts +533 -0
  46. package/dist/Frame/Frame.Model.js +2 -0
  47. package/dist/Frame/Frame.Model.js.map +1 -0
  48. package/dist/Frame/Frame.d.ts +309 -0
  49. package/dist/Frame/Frame.js +1408 -0
  50. package/dist/Frame/Frame.js.map +1 -0
  51. package/dist/Frame/SyncAdapter.d.ts +75 -0
  52. package/dist/Frame/SyncAdapter.js +134 -0
  53. package/dist/Frame/SyncAdapter.js.map +1 -0
  54. package/dist/Frame/index.d.ts +3 -0
  55. package/dist/Frame/index.js +4 -0
  56. package/dist/Frame/index.js.map +1 -0
  57. package/dist/MediaLink/MediaLink.d.ts +178 -0
  58. package/dist/MediaLink/MediaLink.js +1432 -0
  59. package/dist/MediaLink/MediaLink.js.map +1 -0
  60. package/dist/MediaLink/index.d.ts +1 -0
  61. package/dist/MediaLink/index.js +2 -0
  62. package/dist/MediaLink/index.js.map +1 -0
  63. package/dist/Native/index.d.ts +170 -0
  64. package/dist/Native/index.js +19 -0
  65. package/dist/Native/index.js.map +1 -0
  66. package/dist/Version.d.ts +1 -0
  67. package/dist/Version.js +2 -0
  68. package/dist/Version.js.map +1 -0
  69. package/package.json +76 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 UCAYA
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,121 @@
1
+ # @lavitre/apps
2
+
3
+ TypeScript SDK for building la Vitre apps. An app is a small web bundle the la Vitre host loads into an iframe (or CefGlue WebView on the Vitre native client). The SDK lets the bundle declare itself to the host, drive the la Vitre menu, open frames, exchange opaque messages with peer instances, and share a Y.Doc + Awareness over la Vitre's existing WebRTC data channels.
4
+
5
+ Published to the public npm registry as [`@lavitre/apps`](https://www.npmjs.com/package/@lavitre/apps), as compiled ES modules with `.d.ts` typings (`dist/`, relative imports carry explicit `.js` extensions, so the files also load unbundled from an ESM CDN). Source of truth is `gitlab.ucaya.com/lavitre/apps` (project 23), push-mirrored to `github.com/lavitre/apps`, where GitHub Actions publishes through npm trusted publishing.
6
+
7
+ ```sh
8
+ pnpm add @lavitre/apps # no .npmrc scope mapping, no token
9
+ ```
10
+
11
+ ## Modules
12
+
13
+ The SDK is partitioned by host context. Pick the module that matches where your code runs.
14
+
15
+ | Module | Where it runs | Import path |
16
+ |--------|---------------|-------------|
17
+ | `Common` | shared types (menu entries, files, frame options) | `@lavitre/apps/Common` |
18
+ | `Connector` | Vitre-side connector iframe | `@lavitre/apps/Connector` |
19
+ | `CompanionConnector` | companion-side connector iframe | `@lavitre/apps/CompanionConnector` |
20
+ | `Frame` | inside an opened frame (Vitre or companion) | `@lavitre/apps/Frame` |
21
+ | `Native` | native-app wrapper helpers | `@lavitre/apps/Native` |
22
+
23
+ ### `Connector` vs `CompanionConnector`
24
+
25
+ The two are NOT a single API shared between hosts. They are deliberately distinct surfaces with distinct host capabilities. Use whichever matches the iframe you ship.
26
+
27
+ - `Connector` runs inside the Vitre. The host has a screen, a camera, devices in the space, full settings, share targets, notifications, voice actions. The API exposes all of that.
28
+ - `CompanionConnector` runs inside the la Vitre Companion (mobile / web). The host has none of that — no display device, no shared space awareness, no notifications, no settings persistence. The API is intentionally trimmed to what genuinely applies on the companion:
29
+
30
+ ```ts
31
+ // CompanionConnector public surface (see CompanionConnector/CompanionConnector.ts)
32
+ class CompanionConnector {
33
+ hostInformation: CompanionHostInformation
34
+ appId: string
35
+ options: CompanionConnectorOptions
36
+
37
+ // callbacks (all optional)
38
+ onMenuClicked?: (menuId, tag, isChecked) => void
39
+ onFrameLoaded?: (frameConnectorId) => void
40
+ onFrameUnloaded?: (frameConnectorId) => void
41
+ onMessageFromVitreConnector?: (message, fileData?) => void
42
+
43
+ // outbound
44
+ setMenu(menu: RootMenuEntry[]): void
45
+ openFrame(options: OpenFrameOptions): void
46
+ closeFrame(frameConnectorId: string): void
47
+ sendMessageToVitreConnector(message: string, fileData?): void
48
+ }
49
+ ```
50
+
51
+ Anything not in that list is intentionally absent. The Vitre `Connector` cannot receive `showNotification`, `setVitreSettings`, `setShareTarget`, `voiceActions`, device events, knock-knocks, etc. either way — those flow the other direction and are absent from the companion surface entirely.
52
+
53
+ `CompanionHostInformation` is similarly trimmed compared to the Vitre `HostInformation`:
54
+
55
+ ```ts
56
+ type CompanionHostInformation = {
57
+ language: 'fr' | 'en' | 'it'
58
+ origin: string
59
+ version?: string
60
+ user?: CompanionUser // optional — companion has guest sessions
61
+ connectedVitre: ConnectedVitre // always present once initialize fires
62
+ }
63
+ ```
64
+
65
+ Notably absent: `device`, `devicesInSpace`, `vitreSettings`, `displays`, `team` outside what `connectedVitre` carries, etc.
66
+
67
+ ### Companion ↔ Vitre messaging
68
+
69
+ Two symmetric channels connect a CompanionConnector to the Vitre `Connector` for the same `appId`:
70
+
71
+ - Companion → Vitre: `companionConnector.sendMessageToVitreConnector(message, fileData?)`. The Vitre `Connector` receives `messageFromCompanionConnector` with `fromCompanionId` so it can reply targeted-back.
72
+ - Vitre → Companion: `connector.sendMessageToCompanionConnector(target, message, fileData?)` where `target` is either `{ kind: 'all' }` (broadcast to every connected companion) or `{ kind: 'one', companionId }` (single companion). The CompanionConnector receives it via `onMessageFromVitreConnector(message, fileData?)`. The companion does NOT learn which Vitre user sent the message — it is always "the" Vitre connector for that app.
73
+
74
+ Messages are opaque strings. Use them for app-level coordination that does not belong in the shared Y.Doc.
75
+
76
+ ### Frame pairing (Vitre + companion in lockstep)
77
+
78
+ A menu entry with `availability.companion === true` can declare:
79
+
80
+ ```ts
81
+ {
82
+ id: 'openMyApp',
83
+ label: '…',
84
+ availability: { vitre: true, companion: true },
85
+ opensCompanionFrame: {
86
+ kind: 'normal', // or 'local'
87
+ frameConnectorId: '…', // pairs the two frames
88
+ options: { url: './frame.html', size: { … }, … },
89
+ },
90
+ }
91
+ ```
92
+
93
+ - `kind: 'local'` — the frame lives only on the companion that opened it; independent of any Vitre frame.
94
+ - `kind: 'normal'` — both sides open their own frame; per-frame messages and yjs CRDT updates flow between them transparently through `@lavitre/apps/Frame`.
95
+
96
+ > Note: `frameConnectorId` lives at the outer level of `CompanionFrameTarget`; the inner `options` type is `Omit<OpenFrameOptions, 'frameConnectorId'>` so there is exactly one source of truth.
97
+
98
+ ### `Frame` — Y.Doc + Awareness over the SDK channel
99
+
100
+ Inside a frame iframe (on either side):
101
+
102
+ ```ts
103
+ frame.crdt.doc // default Y.Doc (used by simple apps)
104
+ frame.crdt.awareness // default y-protocols Awareness
105
+ frame.crdt.attach(doc, awareness?) // swap in caller-provided ones — returns dispose handle
106
+ frame.crdt.onSynced(cb) // fires once when the initial doc snapshot lands
107
+ ```
108
+
109
+ `createVitreSyncAdapter(frame)` returns a generic Yjs `SyncAdapter` (structurally compatible with the y-sync adapter contract used by Carbone, tldraw, etc.). Calling `.connect(doc, awareness)` is shorthand for `frame.crdt.attach(doc, awareness)`. Doc and awareness updates then ride the SDK's WebRTC data channels (separate envelopes `crdtUpdate` / `crdtAwarenessUpdate` so the F# host can route, throttle, and log them independently).
110
+
111
+ ## Versioning
112
+
113
+ The package ships compiled ESM + `.d.ts` (`pnpm build` → `dist/`); import paths (`@lavitre/apps/<Module>`) are unchanged. `Version.ts` carries `apiVersion`, refreshed at build time by `replaceVersion.js`. The host enforces a minimum SDK version on initialize — bumping a breaking change requires a major-version bump in `package.json`.
114
+
115
+ ## Releasing
116
+
117
+ 1. Bump `version` in `package.json` and run `node ./replaceVersion.js` (also run by `pnpm prebuild`) so `Version.ts` matches. Commit both files.
118
+ 2. Merge to `main`.
119
+ 3. Tag the merge commit and push the tag: `git tag v1.50.0 && git push origin v1.50.0`.
120
+
121
+ GitLab push-mirrors `main` and tags to `github.com/lavitre/apps`. The `publish.yml` workflow there checks that the tag matches `package.json`, type-checks, and runs `npm publish` with trusted publishing (OIDC, no token stored anywhere). A version already on npmjs is skipped, never overwritten. The GitLab `build` job remains the pre-merge gate; nothing on gitlab.ucaya.com publishes anymore.
@@ -0,0 +1,59 @@
1
+ export type AiTool = {
2
+ /**
3
+ * Local tool name. The host namespaces it as `<appId>__<name>` before exposing it
4
+ * to the model. Must match `[A-Za-z0-9_-]+` (OpenAI / hermes3 function-name charset).
5
+ */
6
+ name: string;
7
+ description: string;
8
+ /** JSON Schema (draft-07) of the arguments object. */
9
+ parameters: Record<string, unknown>;
10
+ /** Destructive / side-effecting → the host asks the user to confirm before running. */
11
+ sensitive?: boolean;
12
+ };
13
+ export type AiToolHandler = (name: string, args: unknown) => unknown | Promise<unknown>;
14
+ export type AiOutboundMessage = {
15
+ type: 'aiRegisterTools';
16
+ tools: AiTool[];
17
+ } | {
18
+ type: 'aiUnregisterTools';
19
+ } | {
20
+ type: 'aiInvokeResult';
21
+ id: string;
22
+ ok: boolean;
23
+ content: string;
24
+ };
25
+ export type AiInboundMessage = {
26
+ type: 'aiInvoke';
27
+ id: string;
28
+ name: string;
29
+ args: unknown;
30
+ };
31
+ export type AiPostMessage = (message: AiOutboundMessage) => void;
32
+ export declare const MIN_AI_HOST_VERSION = "36.6.0";
33
+ /**
34
+ * App-side AI tool channel. Exposed as `connector.ai` / `frame.ai`. An app calls
35
+ * `registerTools(tools, handler)`; the host runs invocations against `handler` and
36
+ * the channel replies with the result. The handler's return value is sent verbatim
37
+ * if it's a string, otherwise JSON-stringified.
38
+ */
39
+ export declare class AiChannel {
40
+ private readonly post;
41
+ private handler;
42
+ private currentTools;
43
+ constructor(post: AiPostMessage);
44
+ /** The tools currently registered (local names). */
45
+ get tools(): readonly AiTool[];
46
+ /**
47
+ * Publish a tool catalog + the handler that runs invocations. Returns a dispose
48
+ * that unregisters. Safe to re-call to REPLACE the catalog (e.g. when the app's
49
+ * context changes — a board opens/closes).
50
+ */
51
+ registerTools(tools: AiTool[], handler: AiToolHandler): () => void;
52
+ /** Withdraw the catalog (the host drops these tools from the agent). */
53
+ unregisterTools(): void;
54
+ /**
55
+ * Run an incoming invocation. Called by Connector/Frame.raiseMessage on an
56
+ * `aiInvoke`. ALWAYS replies with an `aiInvokeResult` (the host/agent is waiting).
57
+ */
58
+ handleInvoke(id: string, name: string, args: unknown): Promise<void>;
59
+ }
@@ -0,0 +1,97 @@
1
+ // AI tool channel — lets an app publish a catalog of "tools" (named, JSON-Schema'd
2
+ // actions) to the la Vitre host and serve invocations of them.
3
+ //
4
+ // The host aggregates every provider's tools (the Vitre's own device tools + each
5
+ // app's), NAMESPACES them by provider (`<appId>__<tool>`, `vitre__<tool>`), forwards
6
+ // the union to the on-prem agent's LLM, and routes each tool call back to the owning
7
+ // app as an `aiInvoke` — which this channel runs against the registered handler and
8
+ // answers with an `aiInvokeResult`.
9
+ //
10
+ // Generic by design: an app registers SIMPLE LOCAL names (`createDiagram`); the HOST
11
+ // owns the `<appId>__` prefix (so apps can't collide or spoof each other). Mirrors
12
+ // CrdtChannel: one small class, shared by Connector + Frame.
13
+ // The host-side decoder + agent bridge ship in la Vitre 26.6.x. Older hosts ignore
14
+ // the unknown arms (and never send `aiInvoke` — they have no agent), so this is a
15
+ // soft gate; emission is still skipped below MIN_AI_HOST_VERSION to avoid noise.
16
+ // The companion is always HEAD → never gated (mirrors MIN_CRDT_HOST_VERSION).
17
+ export const MIN_AI_HOST_VERSION = '36.6.0';
18
+ /**
19
+ * App-side AI tool channel. Exposed as `connector.ai` / `frame.ai`. An app calls
20
+ * `registerTools(tools, handler)`; the host runs invocations against `handler` and
21
+ * the channel replies with the result. The handler's return value is sent verbatim
22
+ * if it's a string, otherwise JSON-stringified.
23
+ */
24
+ export class AiChannel {
25
+ constructor(post) {
26
+ Object.defineProperty(this, "post", {
27
+ enumerable: true,
28
+ configurable: true,
29
+ writable: true,
30
+ value: post
31
+ });
32
+ Object.defineProperty(this, "handler", {
33
+ enumerable: true,
34
+ configurable: true,
35
+ writable: true,
36
+ value: void 0
37
+ });
38
+ Object.defineProperty(this, "currentTools", {
39
+ enumerable: true,
40
+ configurable: true,
41
+ writable: true,
42
+ value: []
43
+ });
44
+ }
45
+ /** The tools currently registered (local names). */
46
+ get tools() {
47
+ return this.currentTools;
48
+ }
49
+ /**
50
+ * Publish a tool catalog + the handler that runs invocations. Returns a dispose
51
+ * that unregisters. Safe to re-call to REPLACE the catalog (e.g. when the app's
52
+ * context changes — a board opens/closes).
53
+ */
54
+ registerTools(tools, handler) {
55
+ this.currentTools = tools;
56
+ this.handler = handler;
57
+ this.post({ type: 'aiRegisterTools', tools });
58
+ return () => this.unregisterTools();
59
+ }
60
+ /** Withdraw the catalog (the host drops these tools from the agent). */
61
+ unregisterTools() {
62
+ if (this.currentTools.length === 0 && this.handler === undefined)
63
+ return;
64
+ this.currentTools = [];
65
+ this.handler = undefined;
66
+ this.post({ type: 'aiUnregisterTools' });
67
+ }
68
+ /**
69
+ * Run an incoming invocation. Called by Connector/Frame.raiseMessage on an
70
+ * `aiInvoke`. ALWAYS replies with an `aiInvokeResult` (the host/agent is waiting).
71
+ */
72
+ async handleInvoke(id, name, args) {
73
+ if (this.handler === undefined) {
74
+ this.post({
75
+ type: 'aiInvokeResult',
76
+ id,
77
+ ok: false,
78
+ content: 'No AI tools registered',
79
+ });
80
+ return;
81
+ }
82
+ try {
83
+ const result = await this.handler(name, args);
84
+ const content = typeof result === 'string' ? result : JSON.stringify(result ?? null);
85
+ this.post({ type: 'aiInvokeResult', id, ok: true, content });
86
+ }
87
+ catch (err) {
88
+ this.post({
89
+ type: 'aiInvokeResult',
90
+ id,
91
+ ok: false,
92
+ content: err instanceof Error ? err.message : String(err),
93
+ });
94
+ }
95
+ }
96
+ }
97
+ //# sourceMappingURL=AiChannel.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AiChannel.js","sourceRoot":"","sources":["../../Common/AiChannel.ts"],"names":[],"mappings":"AAAA,mFAAmF;AACnF,+DAA+D;AAC/D,EAAE;AACF,kFAAkF;AAClF,qFAAqF;AACrF,qFAAqF;AACrF,oFAAoF;AACpF,oCAAoC;AACpC,EAAE;AACF,qFAAqF;AACrF,mFAAmF;AACnF,6DAA6D;AAoC7D,mFAAmF;AACnF,kFAAkF;AAClF,iFAAiF;AACjF,8EAA8E;AAC9E,MAAM,CAAC,MAAM,mBAAmB,GAAG,QAAQ,CAAA;AAE3C;;;;;GAKG;AACH,MAAM,OAAO,SAAS;IAIpB,YAA6B,IAAmB;QAApC;;;;mBAAiB,IAAI;WAAe;QAHxC;;;;;WAAkC;QAClC;;;;mBAAyB,EAAE;WAAA;IAEgB,CAAC;IAEpD,oDAAoD;IACpD,IAAI,KAAK;QACP,OAAO,IAAI,CAAC,YAAY,CAAA;IAC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E,OAAO,EAAE,CAAC,CAAA;QAC9D,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,IAAI,CAAC,IAAI,CAAC;gBACR,IAAI,EAAE,gBAAgB;gBACtB,EAAE;gBACF,EAAE,EAAE,KAAK;gBACT,OAAO,EAAE,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC;aAC1D,CAAC,CAAA;QACJ,CAAC;IACH,CAAC;CACF","sourcesContent":["// AI tool channel — lets an app publish a catalog of \"tools\" (named, JSON-Schema'd\n// actions) to the la Vitre host and serve invocations of them.\n//\n// The host aggregates every provider's tools (the Vitre's own device tools + each\n// app's), NAMESPACES them by provider (`<appId>__<tool>`, `vitre__<tool>`), forwards\n// the union to the on-prem agent's LLM, and routes each tool call back to the owning\n// app as an `aiInvoke` — which this channel runs against the registered handler and\n// answers with an `aiInvokeResult`.\n//\n// Generic by design: an app registers SIMPLE LOCAL names (`createDiagram`); the HOST\n// owns the `<appId>__` prefix (so apps can't collide or spoof each other). Mirrors\n// CrdtChannel: one small class, shared by Connector + Frame.\n\nexport type AiTool = {\n /**\n * Local tool name. The host namespaces it as `<appId>__<name>` before exposing it\n * to the model. Must match `[A-Za-z0-9_-]+` (OpenAI / hermes3 function-name charset).\n */\n name: string\n description: string\n /** JSON Schema (draft-07) of the arguments object. */\n parameters: Record<string, unknown>\n /** Destructive / side-effecting → the host asks the user to confirm before running. */\n sensitive?: boolean\n}\n\nexport type AiToolHandler = (\n name: string,\n args: unknown,\n) => unknown | Promise<unknown>\n\n// Outbound (app → host).\nexport type AiOutboundMessage =\n | { type: 'aiRegisterTools'; tools: AiTool[] }\n | { type: 'aiUnregisterTools' }\n | { type: 'aiInvokeResult'; id: string; ok: boolean; content: string }\n\n// Inbound (host → app), delivered via Connector/Frame.raiseMessage.\nexport type AiInboundMessage = {\n type: 'aiInvoke'\n id: string\n name: string\n args: unknown\n}\n\nexport type AiPostMessage = (message: AiOutboundMessage) => void\n\n// The host-side decoder + agent bridge ship in la Vitre 26.6.x. Older hosts ignore\n// the unknown arms (and never send `aiInvoke` — they have no agent), so this is a\n// soft gate; emission is still skipped below MIN_AI_HOST_VERSION to avoid noise.\n// The companion is always HEAD → never gated (mirrors MIN_CRDT_HOST_VERSION).\nexport const MIN_AI_HOST_VERSION = '36.6.0'\n\n/**\n * App-side AI tool channel. Exposed as `connector.ai` / `frame.ai`. An app calls\n * `registerTools(tools, handler)`; the host runs invocations against `handler` and\n * the channel replies with the result. The handler's return value is sent verbatim\n * if it's a string, otherwise JSON-stringified.\n */\nexport class AiChannel {\n private handler: AiToolHandler | undefined\n private currentTools: AiTool[] = []\n\n constructor(private readonly post: AiPostMessage) {}\n\n /** The tools currently registered (local names). */\n get tools(): readonly AiTool[] {\n return this.currentTools\n }\n\n /**\n * Publish a tool catalog + the handler that runs invocations. Returns a dispose\n * that unregisters. Safe to re-call to REPLACE the catalog (e.g. when the app's\n * context changes — a board opens/closes).\n */\n registerTools(tools: AiTool[], handler: AiToolHandler): () => void {\n this.currentTools = tools\n this.handler = handler\n this.post({ type: 'aiRegisterTools', tools })\n return () => this.unregisterTools()\n }\n\n /** Withdraw the catalog (the host drops these tools from the agent). */\n unregisterTools(): void {\n if (this.currentTools.length === 0 && this.handler === undefined) return\n this.currentTools = []\n this.handler = undefined\n this.post({ type: 'aiUnregisterTools' })\n }\n\n /**\n * Run an incoming invocation. Called by Connector/Frame.raiseMessage on an\n * `aiInvoke`. ALWAYS replies with an `aiInvokeResult` (the host/agent is waiting).\n */\n async handleInvoke(id: string, name: string, args: unknown): Promise<void> {\n if (this.handler === undefined) {\n this.post({\n type: 'aiInvokeResult',\n id,\n ok: false,\n content: 'No AI tools registered',\n })\n return\n }\n try {\n const result = await this.handler(name, args)\n const content =\n typeof result === 'string' ? result : JSON.stringify(result ?? null)\n this.post({ type: 'aiInvokeResult', id, ok: true, content })\n } catch (err) {\n this.post({\n type: 'aiInvokeResult',\n id,\n ok: false,\n content: err instanceof Error ? err.message : String(err),\n })\n }\n }\n}\n"]}
@@ -0,0 +1,44 @@
1
+ import type { CrdtChannel } from './CrdtChannel.js';
2
+ /**
3
+ * Deliberately bare CRDT-backed blob store: `put` / `get` / `list` /
4
+ * `onProgress`, nothing else. NO versioning, NO quota, NO mime — those are
5
+ * application concerns. GC is "remove the key from the manifest, the subdoc
6
+ * becomes unreferenced". If you need more (custom preload strategy, version
7
+ * history, …) drop down to `crdt.attachSubdoc` and own it.
8
+ *
9
+ * This is the opinionated convenience layer; `CrdtChannel.attachSubdoc` is
10
+ * the low-level primitive it is built on. The SDK still never inspects blob
11
+ * contents — a blob is an opaque Uint8Array under a string key.
12
+ */
13
+ export declare class BlobStore {
14
+ private readonly crdt;
15
+ private _guidToKey;
16
+ private _manifestObserved;
17
+ private _manifestRebuild;
18
+ constructor(crdt: CrdtChannel);
19
+ private manifest;
20
+ /** Store (or overwrite) a blob and start transporting it. The bytes live
21
+ * in a dedicated subdoc; the manifest entry is shared immediately so
22
+ * peers know the key exists before the bytes finish streaming. */
23
+ put(key: string, bytes: Uint8Array): void;
24
+ /** Resolve the blob bytes, loading the subdoc on demand. Returns null if
25
+ * the key is unknown OR the subdoc is detached/removed before it syncs.
26
+ *
27
+ * Bounded: if the host never reports sync (network/host failure, blob
28
+ * removed mid-flight), the promise resolves to `null` after `timeoutMs`
29
+ * (default 30s) instead of hanging forever — and the listener is always
30
+ * cleaned up. An optional `AbortSignal` resolves it early to `null`. */
31
+ get(key: string, opts?: {
32
+ timeoutMs?: number;
33
+ signal?: AbortSignal;
34
+ }): Promise<Uint8Array | null>;
35
+ /** Keys currently in the manifest. */
36
+ list(): string[];
37
+ /** Drop a key from the manifest. The subdoc becomes unreferenced; we also
38
+ * detach its transport. Bytes already delivered to peers are not recalled
39
+ * (CRDT — there is no "unsend"); this just stops advertising the key. */
40
+ remove(key: string): void;
41
+ /** Progress for a streaming blob — cumulative inbound bytes, mapped from
42
+ * the subdoc guid back to its manifest key. Generic loading-bar signal. */
43
+ onProgress(cb: (key: string, receivedBytes: number) => void): () => void;
44
+ }
@@ -0,0 +1,186 @@
1
+ import * as Y from 'yjs';
2
+ // One reserved Y.Map on the ACTIVE doc (whatever `crdt.doc` currently is —
3
+ // the default doc or one swapped in via `attach()`). Keys map to yjs
4
+ // subdocuments; storing a Y.Doc as a Y.Map value makes it a subdoc of the
5
+ // parent, so the manifest (which keys exist + each subdoc's guid) is itself
6
+ // CRDT-shared. Every peer that gets the parent doc learns the blob list for
7
+ // free; the heavy bytes stream in deferred, per-subdoc, on demand.
8
+ const MANIFEST_KEY = '__lavitre_blobs__';
9
+ const BYTES_MAP = 'blob';
10
+ const BYTES_FIELD = 'bytes';
11
+ /**
12
+ * Deliberately bare CRDT-backed blob store: `put` / `get` / `list` /
13
+ * `onProgress`, nothing else. NO versioning, NO quota, NO mime — those are
14
+ * application concerns. GC is "remove the key from the manifest, the subdoc
15
+ * becomes unreferenced". If you need more (custom preload strategy, version
16
+ * history, …) drop down to `crdt.attachSubdoc` and own it.
17
+ *
18
+ * This is the opinionated convenience layer; `CrdtChannel.attachSubdoc` is
19
+ * the low-level primitive it is built on. The SDK still never inspects blob
20
+ * contents — a blob is an opaque Uint8Array under a string key.
21
+ */
22
+ export class BlobStore {
23
+ constructor(crdt) {
24
+ Object.defineProperty(this, "crdt", {
25
+ enumerable: true,
26
+ configurable: true,
27
+ writable: true,
28
+ value: crdt
29
+ });
30
+ // Reverse index guid → key, so `onProgress` is O(1) instead of scanning
31
+ // the whole manifest per inbound update. Rebuilt whenever the manifest
32
+ // changes (a remote peer can add/remove keys via CRDT sync, so a
33
+ // put/remove-only maintenance would miss those).
34
+ Object.defineProperty(this, "_guidToKey", {
35
+ enumerable: true,
36
+ configurable: true,
37
+ writable: true,
38
+ value: new Map()
39
+ });
40
+ Object.defineProperty(this, "_manifestObserved", {
41
+ enumerable: true,
42
+ configurable: true,
43
+ writable: true,
44
+ value: null
45
+ });
46
+ Object.defineProperty(this, "_manifestRebuild", {
47
+ enumerable: true,
48
+ configurable: true,
49
+ writable: true,
50
+ value: null
51
+ });
52
+ }
53
+ manifest() {
54
+ const m = this.crdt.doc.getMap(MANIFEST_KEY);
55
+ // The active doc can change under us (crdt.attach swaps it). Re-bind the
56
+ // observer + rebuild the index if we're looking at a new map. CRITICAL:
57
+ // unobserve the previous map first — otherwise each doc swap leaks a
58
+ // closure-bound observer, and a swap-back re-registers a duplicate
59
+ // observer (rebuild would then run N times per manifest change).
60
+ if (m !== this._manifestObserved) {
61
+ if (this._manifestObserved && this._manifestRebuild) {
62
+ this._manifestObserved.unobserve(this._manifestRebuild);
63
+ }
64
+ const rebuild = () => {
65
+ this._guidToKey.clear();
66
+ for (const [k, sub] of m.entries())
67
+ this._guidToKey.set(sub.guid, k);
68
+ };
69
+ this._manifestObserved = m;
70
+ this._manifestRebuild = rebuild;
71
+ rebuild();
72
+ m.observe(rebuild);
73
+ }
74
+ return m;
75
+ }
76
+ /** Store (or overwrite) a blob and start transporting it. The bytes live
77
+ * in a dedicated subdoc; the manifest entry is shared immediately so
78
+ * peers know the key exists before the bytes finish streaming. */
79
+ put(key, bytes) {
80
+ const m = this.manifest();
81
+ let sub = m.get(key);
82
+ if (!sub) {
83
+ sub = new Y.Doc();
84
+ m.set(key, sub);
85
+ }
86
+ sub.getMap(BYTES_MAP).set(BYTES_FIELD, bytes);
87
+ // We are the writer — we hold the authoritative state, so skip the
88
+ // on-demand pull request (would be a wasted round-trip).
89
+ this.crdt.attachSubdoc(sub, { requestSync: false });
90
+ }
91
+ /** Resolve the blob bytes, loading the subdoc on demand. Returns null if
92
+ * the key is unknown OR the subdoc is detached/removed before it syncs.
93
+ *
94
+ * Bounded: if the host never reports sync (network/host failure, blob
95
+ * removed mid-flight), the promise resolves to `null` after `timeoutMs`
96
+ * (default 30s) instead of hanging forever — and the listener is always
97
+ * cleaned up. An optional `AbortSignal` resolves it early to `null`. */
98
+ async get(key, opts) {
99
+ const sub = this.manifest().get(key);
100
+ if (!sub)
101
+ return null;
102
+ if (!sub.shouldLoad)
103
+ sub.load();
104
+ this.crdt.attachSubdoc(sub);
105
+ // `read()` returns null if the key was removed mid-flight (the subdoc
106
+ // object still holds its bytes in memory, so we must check manifest
107
+ // membership, not just the bytes field) — fixes the remove()/get() race.
108
+ const read = () => {
109
+ if (this.manifest().get(key) !== sub)
110
+ return null;
111
+ const v = sub.getMap(BYTES_MAP).get(BYTES_FIELD);
112
+ return v instanceof Uint8Array ? v : null;
113
+ };
114
+ const local = read();
115
+ if (local)
116
+ return local;
117
+ const timeoutMs = opts?.timeoutMs ?? 30000;
118
+ return new Promise((resolve) => {
119
+ let settled = false;
120
+ const finish = (v) => {
121
+ if (settled)
122
+ return;
123
+ settled = true;
124
+ off();
125
+ clearTimeout(timer);
126
+ sub.off('update', onUpdate);
127
+ opts?.signal?.removeEventListener('abort', onAbort);
128
+ resolve(v);
129
+ };
130
+ const tryRead = () => {
131
+ const v = read();
132
+ if (v)
133
+ finish(v);
134
+ };
135
+ // Resolve on the subdoc's OWN updates — do not hinge correctness on
136
+ // the host synthesizing crdtSubdocSyncComplete for the on-demand pull
137
+ // path (it's delivered as a plain crdtSubdocUpdate). onSubdocSynced
138
+ // still resolves the "host says done, possibly empty" case; detach
139
+ // flushes it too (read() → null for the gone subdoc).
140
+ const onUpdate = () => tryRead();
141
+ sub.on('update', onUpdate);
142
+ const off = this.crdt.onSubdocSynced(sub.guid, () => finish(read()));
143
+ const timer = setTimeout(() => finish(read()), timeoutMs);
144
+ const onAbort = () => finish(null);
145
+ if (opts?.signal) {
146
+ if (opts.signal.aborted) {
147
+ finish(null);
148
+ }
149
+ else {
150
+ opts.signal.addEventListener('abort', onAbort, { once: true });
151
+ }
152
+ }
153
+ // Bytes may have landed between attachSubdoc and the listener wiring.
154
+ tryRead();
155
+ });
156
+ }
157
+ /** Keys currently in the manifest. */
158
+ list() {
159
+ return [...this.manifest().keys()];
160
+ }
161
+ /** Drop a key from the manifest. The subdoc becomes unreferenced; we also
162
+ * detach its transport. Bytes already delivered to peers are not recalled
163
+ * (CRDT — there is no "unsend"); this just stops advertising the key. */
164
+ remove(key) {
165
+ const m = this.manifest();
166
+ const sub = m.get(key);
167
+ // Delete the manifest key BEFORE detaching: detachSubdoc synchronously
168
+ // flushes pending get() waiters, whose read() re-checks manifest
169
+ // membership — so the key must already be gone for them to resolve null.
170
+ m.delete(key);
171
+ if (sub)
172
+ this.crdt.detachSubdoc(sub.guid);
173
+ }
174
+ /** Progress for a streaming blob — cumulative inbound bytes, mapped from
175
+ * the subdoc guid back to its manifest key. Generic loading-bar signal. */
176
+ onProgress(cb) {
177
+ // Touch manifest() once so the observer/index is bound, then O(1) lookup.
178
+ this.manifest();
179
+ return this.crdt.onSubdocBytes((guid, bytes) => {
180
+ const key = this._guidToKey.get(guid);
181
+ if (key !== undefined)
182
+ cb(key, bytes);
183
+ });
184
+ }
185
+ }
186
+ //# sourceMappingURL=BlobStore.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"BlobStore.js","sourceRoot":"","sources":["../../Common/BlobStore.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,KAAK,CAAA;AAGxB,2EAA2E;AAC3E,qEAAqE;AACrE,0EAA0E;AAC1E,4EAA4E;AAC5E,4EAA4E;AAC5E,mEAAmE;AACnE,MAAM,YAAY,GAAG,mBAAmB,CAAA;AACxC,MAAM,SAAS,GAAG,MAAM,CAAA;AACxB,MAAM,WAAW,GAAG,OAAO,CAAA;AAE3B;;;;;;;;;;GAUG;AACH,MAAM,OAAO,SAAS;IASpB,YAA6B,IAAiB;QAAlC;;;;mBAAiB,IAAI;WAAa;QAR9C,wEAAwE;QACxE,uEAAuE;QACvE,iEAAiE;QACjE,iDAAiD;QACzC;;;;mBAAa,IAAI,GAAG,EAAkB;WAAA;QACtC;;;;mBAAyC,IAAI;WAAA;QAC7C;;;;mBAAwC,IAAI;WAAA;IAEH,CAAC;IAE1C,QAAQ;QACd,MAAM,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AAC;YACD,sEAAsE;YACtE,OAAO,EAAE,CAAA;QACX,CAAC,CAAC,CAAA;IACJ,CAAC;IAED,sCAAsC;IACtC,IAAI;QACF,OAAO,CAAC,GAAG,IAAI,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC,CAAA;IACpC,CAAC;IAED;;8EAE0E;IAC1E,MAAM,CAAC,GAAW;QAChB,MAAM,CAAC,GAAG,IAAI,CAAC,QAAQ,EAAE,CAAA;QACzB,MAAM,GAAG,GAAG,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;QACtB,uEAAuE;QACvE,iEAAiE;QACjE,yEAAyE;QACzE,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAA;QACb,IAAI,GAAG;YAAE,IAAI,CAAC,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,CAAA;IAC3C,CAAC;IAED;gFAC4E;IAC5E,UAAU,CAAC,EAAgD;QACzD,0EAA0E;QAC1E,IAAI,CAAC,QAAQ,EAAE,CAAA;QACf,OAAO,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE;YAC7C,MAAM,GAAG,GAAG,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,CAAA;YACrC,IAAI,GAAG,KAAK,SAAS;gBAAE,EAAE,CAAC,GAAG,EAAE,KAAK,CAAC,CAAA;QACvC,CAAC,CAAC,CAAA;IACJ,CAAC;CACF","sourcesContent":["import * as Y from 'yjs'\nimport type { CrdtChannel } from './CrdtChannel.js'\n\n// One reserved Y.Map on the ACTIVE doc (whatever `crdt.doc` currently is —\n// the default doc or one swapped in via `attach()`). Keys map to yjs\n// subdocuments; storing a Y.Doc as a Y.Map value makes it a subdoc of the\n// parent, so the manifest (which keys exist + each subdoc's guid) is itself\n// CRDT-shared. Every peer that gets the parent doc learns the blob list for\n// free; the heavy bytes stream in deferred, per-subdoc, on demand.\nconst MANIFEST_KEY = '__lavitre_blobs__'\nconst BYTES_MAP = 'blob'\nconst BYTES_FIELD = 'bytes'\n\n/**\n * Deliberately bare CRDT-backed blob store: `put` / `get` / `list` /\n * `onProgress`, nothing else. NO versioning, NO quota, NO mime — those are\n * application concerns. GC is \"remove the key from the manifest, the subdoc\n * becomes unreferenced\". If you need more (custom preload strategy, version\n * history, …) drop down to `crdt.attachSubdoc` and own it.\n *\n * This is the opinionated convenience layer; `CrdtChannel.attachSubdoc` is\n * the low-level primitive it is built on. The SDK still never inspects blob\n * contents — a blob is an opaque Uint8Array under a string key.\n */\nexport class BlobStore {\n // Reverse index guid → key, so `onProgress` is O(1) instead of scanning\n // the whole manifest per inbound update. Rebuilt whenever the manifest\n // changes (a remote peer can add/remove keys via CRDT sync, so a\n // put/remove-only maintenance would miss those).\n private _guidToKey = new Map<string, string>()\n private _manifestObserved: Y.Map<Y.Doc> | null = null\n private _manifestRebuild: (() => void) | null = null\n\n constructor(private readonly crdt: CrdtChannel) {}\n\n private manifest(): Y.Map<Y.Doc> {\n const m = this.crdt.doc.getMap<Y.Doc>(MANIFEST_KEY)\n // The active doc can change under us (crdt.attach swaps it). Re-bind the\n // observer + rebuild the index if we're looking at a new map. CRITICAL:\n // unobserve the previous map first — otherwise each doc swap leaks a\n // closure-bound observer, and a swap-back re-registers a duplicate\n // observer (rebuild would then run N times per manifest change).\n if (m !== this._manifestObserved) {\n if (this._manifestObserved && this._manifestRebuild) {\n this._manifestObserved.unobserve(this._manifestRebuild)\n }\n const rebuild = () => {\n this._guidToKey.clear()\n for (const [k, sub] of m.entries()) this._guidToKey.set(sub.guid, k)\n }\n this._manifestObserved = m\n this._manifestRebuild = rebuild\n rebuild()\n m.observe(rebuild)\n }\n return m\n }\n\n /** Store (or overwrite) a blob and start transporting it. The bytes live\n * in a dedicated subdoc; the manifest entry is shared immediately so\n * peers know the key exists before the bytes finish streaming. */\n put(key: string, bytes: Uint8Array): void {\n const m = this.manifest()\n let sub = m.get(key)\n if (!sub) {\n sub = new Y.Doc()\n m.set(key, sub)\n }\n sub.getMap(BYTES_MAP).set(BYTES_FIELD, bytes)\n // We are the writer — we hold the authoritative state, so skip the\n // on-demand pull request (would be a wasted round-trip).\n this.crdt.attachSubdoc(sub, { requestSync: false })\n }\n\n /** Resolve the blob bytes, loading the subdoc on demand. Returns null if\n * the key is unknown OR the subdoc is detached/removed before it syncs.\n *\n * Bounded: if the host never reports sync (network/host failure, blob\n * removed mid-flight), the promise resolves to `null` after `timeoutMs`\n * (default 30s) instead of hanging forever — and the listener is always\n * cleaned up. An optional `AbortSignal` resolves it early to `null`. */\n async get(\n key: string,\n opts?: { timeoutMs?: number; signal?: AbortSignal },\n ): Promise<Uint8Array | null> {\n const sub = this.manifest().get(key)\n if (!sub) return null\n if (!sub.shouldLoad) sub.load()\n this.crdt.attachSubdoc(sub)\n\n // `read()` returns null if the key was removed mid-flight (the subdoc\n // object still holds its bytes in memory, so we must check manifest\n // membership, not just the bytes field) — fixes the remove()/get() race.\n const read = (): Uint8Array | null => {\n if (this.manifest().get(key) !== sub) return null\n const v = sub.getMap(BYTES_MAP).get(BYTES_FIELD)\n return v instanceof Uint8Array ? v : null\n }\n\n const local = read()\n if (local) return local\n\n const timeoutMs = opts?.timeoutMs ?? 30_000\n return new Promise<Uint8Array | null>((resolve) => {\n let settled = false\n const finish = (v: Uint8Array | null) => {\n if (settled) return\n settled = true\n off()\n clearTimeout(timer)\n sub.off('update', onUpdate)\n opts?.signal?.removeEventListener('abort', onAbort)\n resolve(v)\n }\n const tryRead = () => {\n const v = read()\n if (v) finish(v)\n }\n // Resolve on the subdoc's OWN updates — do not hinge correctness on\n // the host synthesizing crdtSubdocSyncComplete for the on-demand pull\n // path (it's delivered as a plain crdtSubdocUpdate). onSubdocSynced\n // still resolves the \"host says done, possibly empty\" case; detach\n // flushes it too (read() → null for the gone subdoc).\n const onUpdate = () => tryRead()\n sub.on('update', onUpdate)\n const off = this.crdt.onSubdocSynced(sub.guid, () => finish(read()))\n const timer = setTimeout(() => finish(read()), timeoutMs)\n const onAbort = () => finish(null)\n if (opts?.signal) {\n if (opts.signal.aborted) {\n finish(null)\n } else {\n opts.signal.addEventListener('abort', onAbort, { once: true })\n }\n }\n // Bytes may have landed between attachSubdoc and the listener wiring.\n tryRead()\n })\n }\n\n /** Keys currently in the manifest. */\n list(): string[] {\n return [...this.manifest().keys()]\n }\n\n /** Drop a key from the manifest. The subdoc becomes unreferenced; we also\n * detach its transport. Bytes already delivered to peers are not recalled\n * (CRDT — there is no \"unsend\"); this just stops advertising the key. */\n remove(key: string): void {\n const m = this.manifest()\n const sub = m.get(key)\n // Delete the manifest key BEFORE detaching: detachSubdoc synchronously\n // flushes pending get() waiters, whose read() re-checks manifest\n // membership — so the key must already be gone for them to resolve null.\n m.delete(key)\n if (sub) this.crdt.detachSubdoc(sub.guid)\n }\n\n /** Progress for a streaming blob — cumulative inbound bytes, mapped from\n * the subdoc guid back to its manifest key. Generic loading-bar signal. */\n onProgress(cb: (key: string, receivedBytes: number) => void): () => void {\n // Touch manifest() once so the observer/index is bound, then O(1) lookup.\n this.manifest()\n return this.crdt.onSubdocBytes((guid, bytes) => {\n const key = this._guidToKey.get(guid)\n if (key !== undefined) cb(key, bytes)\n })\n }\n}\n"]}