@assistant-ui/appos 0.0.0-stage → 0.0.2

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 (41) hide show
  1. package/LICENSE +21 -0
  2. package/dist/chunks/ai-call.js +71 -0
  3. package/dist/chunks/ai-sdk.js +66 -0
  4. package/dist/chunks/src.js +1468 -0
  5. package/dist/index.js +1662 -0
  6. package/dist/next-page.js +150 -0
  7. package/dist/next-runtime.js +102 -0
  8. package/dist/next-server.js +50 -0
  9. package/dist/next.js +215 -0
  10. package/dist/pack.js +112 -0
  11. package/dist/server.js +77 -0
  12. package/dist/types/packages/appos-client/src/ai-sdk.d.ts +7 -0
  13. package/dist/types/packages/appos-client/src/index.d.ts +661 -0
  14. package/dist/types/packages/appos-client/src/theme.d.ts +16 -0
  15. package/dist/types/packages/appos-client/src/update-text.d.ts +13 -0
  16. package/dist/types/packages/appos-host/src/AppOSApp.d.ts +20 -0
  17. package/dist/types/packages/appos-host/src/ai-call.d.ts +31 -0
  18. package/dist/types/packages/appos-host/src/ai.d.ts +61 -0
  19. package/dist/types/packages/appos-host/src/embed.d.ts +119 -0
  20. package/dist/types/packages/appos-host/src/index.d.ts +6 -0
  21. package/dist/types/packages/appos-host/src/next/adapter.d.ts +43 -0
  22. package/dist/types/packages/appos-host/src/next/page.d.ts +1 -0
  23. package/dist/types/packages/appos-host/src/next/routes.d.ts +2 -0
  24. package/dist/types/packages/appos-host/src/next/runtime.d.ts +11 -0
  25. package/dist/types/packages/appos-host/src/next/server.d.ts +22 -0
  26. package/dist/types/packages/appos-host/src/pack.d.ts +16 -0
  27. package/dist/types/packages/appos-host/src/server.d.ts +23 -0
  28. package/dist/types/src/lib/ai-spend.d.ts +51 -0
  29. package/dist/types/src/lib/bundle-meta.d.ts +13 -0
  30. package/dist/types/src/lib/color-scheme.d.ts +17 -0
  31. package/dist/types/src/lib/external-link.d.ts +5 -0
  32. package/dist/types/src/lib/frame-pinch.d.ts +6 -0
  33. package/dist/types/src/lib/pack.d.ts +17 -0
  34. package/dist/types/src/lib/swbn/cbor.d.ts +16 -0
  35. package/dist/types/src/lib/swbn/identity.d.ts +121 -0
  36. package/dist/types/src/lib/swbn/integrity.d.ts +51 -0
  37. package/dist/types/src/lib/swbn/keys.d.ts +25 -0
  38. package/dist/types/src/lib/swbn/manifest.d.ts +144 -0
  39. package/dist/types/src/lib/swbn/release.d.ts +39 -0
  40. package/package.json +43 -4
  41. package/README.md +0 -3
@@ -0,0 +1,1468 @@
1
+ // packages/appos-client/src/update-text.ts
2
+ /** "0.0.1 (3)", "build 3", "1.0.0", or undefined when nothing usable came. */
3
+ function releaseText(details) {
4
+ const version = typeof details.version === "string" && details.version.trim() ? details.version.trim() : void 0;
5
+ const build = typeof details.build === "number" && Number.isInteger(details.build) && details.build > 0 ? details.build : void 0;
6
+ if (build === void 0) return version;
7
+ return version ? `${version} (${build})` : `build ${build}`;
8
+ }
9
+ /** The sheet's text for update-required. Never prints a missing version. */
10
+ function updateRequiredText(appName, details) {
11
+ const runs = releaseText(details);
12
+ return runs ? `This live file runs ${appName} ${runs}. Update to join.` : `This live file needs a newer ${appName}. Update to join.`;
13
+ }
14
+ /**
15
+ * The sheet for upgrade-pending / upgrade-denied. The owner (`canApprove`) gets
16
+ * Approve (and Deny while it is pending); anyone else gets the server's words.
17
+ */
18
+ function upgradeSheet(appName, code, message, details) {
19
+ if (details.canApprove !== true) return {
20
+ title: code === "upgrade-pending" ? "Waiting for the owner" : "Update declined",
21
+ text: message,
22
+ actions: []
23
+ };
24
+ const runs = releaseText({
25
+ version: details.running,
26
+ build: details.runningBuild
27
+ });
28
+ const wants = releaseText({
29
+ version: details.requested,
30
+ build: details.requestedBuild
31
+ }) ?? "the newer version";
32
+ return {
33
+ title: `Update ${appName}?`,
34
+ text: `${runs ? `This file runs ${appName} ${runs}. ` : ""}Approve ${wants} to update it for everyone.`,
35
+ actions: code === "upgrade-pending" ? ["deny", "approve"] : ["approve"]
36
+ };
37
+ }
38
+ // packages/appos-client/src/theme.ts
39
+ var EVENT = "appos:color-scheme";
40
+ var DARK_QUERY = "(prefers-color-scheme: dark)";
41
+ var hasDom = typeof document !== "undefined" && !!document.documentElement && typeof window !== "undefined" && typeof window.addEventListener === "function";
42
+ function isScheme(v) {
43
+ return v === "light" || v === "dark";
44
+ }
45
+ /** The shell's scheme, if the sandbox has set one on this page. */
46
+ function fromShell() {
47
+ const v = hasDom ? document.documentElement.dataset.apposColorScheme : void 0;
48
+ return isScheme(v) ? v : void 0;
49
+ }
50
+ function fromSystem() {
51
+ return hasDom && typeof matchMedia === "function" && matchMedia(DARK_QUERY).matches ? "dark" : "light";
52
+ }
53
+ function get() {
54
+ return fromShell() ?? fromSystem();
55
+ }
56
+ var manual = () => document.documentElement.dataset.apposTheme === "manual";
57
+ function apply(scheme) {
58
+ if (!hasDom || manual()) return;
59
+ const root = document.documentElement;
60
+ root.classList.toggle("dark", scheme === "dark");
61
+ root.style.colorScheme = scheme;
62
+ }
63
+ /** Calls `fn` with the new scheme on every change. Returns an unsubscribe. */
64
+ function onChange(fn) {
65
+ if (!hasDom) return () => {};
66
+ let last = get();
67
+ const check = () => {
68
+ const now = get();
69
+ if (now === last) return;
70
+ last = now;
71
+ fn(now);
72
+ };
73
+ window.addEventListener(EVENT, check);
74
+ const query = typeof matchMedia === "function" ? matchMedia(DARK_QUERY) : void 0;
75
+ query?.addEventListener("change", check);
76
+ return () => {
77
+ window.removeEventListener(EVENT, check);
78
+ query?.removeEventListener("change", check);
79
+ };
80
+ }
81
+ /**
82
+ * Whether the SDK keeps <html>'s "dark" class and color-scheme in step
83
+ * (default true). false leaves them as they are: style from get() and
84
+ * onChange() yourself. Same as <html data-appos-theme="manual">.
85
+ */
86
+ function autoApply(on) {
87
+ if (!hasDom) return;
88
+ if (on) {
89
+ delete document.documentElement.dataset.apposTheme;
90
+ apply(get());
91
+ } else document.documentElement.dataset.apposTheme = "manual";
92
+ }
93
+ if (hasDom && !fromShell()) {
94
+ apply(get());
95
+ onChange(apply);
96
+ }
97
+ var theme = {
98
+ get,
99
+ onChange,
100
+ autoApply
101
+ };
102
+ // packages/appos-client/src/index.ts
103
+ var VERSION_KEY = "appos:version";
104
+ /** Request bodies through the handle, like the cloud's own cap. */
105
+ var MAX_BODY = 1048576;
106
+ var CloudError = class extends Error {
107
+ code;
108
+ status;
109
+ details;
110
+ constructor(code, message, status = 0, details = {}) {
111
+ super(message);
112
+ this.code = code;
113
+ this.status = status;
114
+ this.details = details;
115
+ this.name = "CloudError";
116
+ }
117
+ };
118
+ function parentOrigin() {
119
+ if (window.parent === window) return void 0;
120
+ try {
121
+ const a = location.ancestorOrigins?.[0];
122
+ if (a) return a;
123
+ } catch {}
124
+ try {
125
+ return document.referrer ? new URL(document.referrer).origin : void 0;
126
+ } catch {
127
+ return;
128
+ }
129
+ }
130
+ var seq = 0;
131
+ /** Asks the appOS shell; it answers only frames it opened, on their own origin. */
132
+ function ask(type, data = {}, timeoutMs = 2e4, transfer = []) {
133
+ if (window.parent === window) return Promise.reject(new CloudError("no-shell", "Open this app from appOS."));
134
+ const id = `${Date.now()}-${++seq}`;
135
+ const origin = parentOrigin();
136
+ return new Promise((resolve, reject) => {
137
+ const timer = setTimeout(() => {
138
+ removeEventListener("message", onMessage);
139
+ reject(new CloudError("timeout", `appOS did not answer ${type}.`));
140
+ }, timeoutMs);
141
+ const onMessage = (e) => {
142
+ if (e.source !== window.parent || origin && e.origin !== origin) return;
143
+ const d = e.data;
144
+ if (d?.type !== `${type}:reply` || d.id !== id) return;
145
+ clearTimeout(timer);
146
+ removeEventListener("message", onMessage);
147
+ if (d.error) reject(new CloudError(d.error, d.message ?? d.error, 0, d));
148
+ else resolve(d);
149
+ };
150
+ addEventListener("message", onMessage);
151
+ window.parent.postMessage({
152
+ type,
153
+ id,
154
+ ...data
155
+ }, origin ?? "*", transfer);
156
+ });
157
+ }
158
+ /** Tells the shell something it doesn't answer (appos:badge). Outside a shell, nothing. */
159
+ function tell(type, data) {
160
+ if (window.parent === window) return;
161
+ try {
162
+ window.parent.postMessage({
163
+ type,
164
+ ...data
165
+ }, parentOrigin() ?? "*");
166
+ } catch {}
167
+ }
168
+ async function openFiles(arg = {}) {
169
+ if (typeof arg === "string") {
170
+ await ask("appos:files-open-address", { address: arg }, 6e4);
171
+ return;
172
+ }
173
+ const { multiple = false, kind } = arg;
174
+ try {
175
+ return await ask("appos:files-open", {
176
+ multiple,
177
+ ...kind ? { kind } : {}
178
+ }, 864e5);
179
+ } catch (e) {
180
+ if (e instanceof CloudError && e.code === "cancelled") return null;
181
+ throw e;
182
+ }
183
+ }
184
+ var hello;
185
+ var getHello = () => hello ??= ask("appos:hello").then((h) => {
186
+ if (h.removed?.length) for (const fn of removedListeners) fn(h.removed);
187
+ removedSeen = h.removed ?? [];
188
+ if (h.embedded) shownBy(h.selection ?? null);
189
+ return h;
190
+ }, (e) => (hello = void 0, Promise.reject(e)));
191
+ var removedListeners = [];
192
+ var removedSeen;
193
+ /** "0.0.1 (12)" for apps with builds, else the version. */
194
+ var labelOf = (h) => h.build === void 0 ? h.version : `${h.version} (${h.build})`;
195
+ var embedSeq = 0;
196
+ /**
197
+ * Shows the page at `path` of the app with DID `app` in `slot`, a box of this page's that is the page's place: as wide
198
+ * as the slot, and as tall as the page's content (the slot's height is set to it). The shell runs the page as a frame of
199
+ * its own app, laid over the slot, so it keeps its own storage, files and grants, and this page never reaches into it.
200
+ * The app has to list `path` in its manifest's appos.embeddable. `remove()` takes it away. Outside a shell, nothing.
201
+ */
202
+ function embed(slot, app, path) {
203
+ if (typeof app !== "string" || !app || typeof path !== "string" || !path.startsWith("/")) throw new TypeError("appos.embed takes an element, an app's DID and a path starting with /.");
204
+ if (window.parent === window) return { remove() {} };
205
+ const id = `embed-${++embedSeq}`;
206
+ let sent = "";
207
+ let frame = 0;
208
+ const send = () => {
209
+ frame = 0;
210
+ const r = slot.getBoundingClientRect();
211
+ const rect = {
212
+ x: r.left,
213
+ y: r.top,
214
+ width: r.width,
215
+ height: r.height
216
+ };
217
+ const key = JSON.stringify(rect);
218
+ if (key === sent) return;
219
+ sent = key;
220
+ tell("appos:embed", {
221
+ id,
222
+ app,
223
+ path,
224
+ rect
225
+ });
226
+ };
227
+ const later = () => void (frame ||= requestAnimationFrame(send));
228
+ const sizes = new ResizeObserver(later);
229
+ sizes.observe(slot);
230
+ sizes.observe(document.documentElement);
231
+ addEventListener("scroll", later, {
232
+ capture: true,
233
+ passive: true
234
+ });
235
+ addEventListener("resize", later);
236
+ const onSize = (e) => {
237
+ const d = e.data;
238
+ if (e.source !== window.parent || d?.type !== "appos:embed-size" || d.id !== id || typeof d.height !== "number") return;
239
+ slot.style.height = `${d.height}px`;
240
+ };
241
+ addEventListener("message", onSize);
242
+ send();
243
+ return { remove() {
244
+ if (frame) cancelAnimationFrame(frame);
245
+ sizes.disconnect();
246
+ removeEventListener("scroll", later, { capture: true });
247
+ removeEventListener("resize", later);
248
+ removeEventListener("message", onSize);
249
+ tell("appos:embed-end", { id });
250
+ } };
251
+ }
252
+ /**
253
+ * Tells the pages this one shows (appos.embed) what is selected here, as it changes: the words, the address of what
254
+ * they are in, and their lines there. null: nothing is selected. Nothing comes back.
255
+ */
256
+ function setSelection(selection) {
257
+ if (selection !== null && (typeof selection?.address !== "string" || typeof selection.text !== "string")) throw new TypeError("appos.setSelection takes { address, lines?, text } or null.");
258
+ tell("appos:selection", { selection: selection && {
259
+ address: selection.address,
260
+ ...selection.lines && { lines: [selection.lines[0], selection.lines[1]] },
261
+ text: selection.text
262
+ } });
263
+ }
264
+ var shownSelection = null;
265
+ var shown = false;
266
+ var selectionListeners = /* @__PURE__ */ new Set();
267
+ /** This frame is a page another app shows: its selection from now on, and the page's height for the slot. */
268
+ function shownBy(first) {
269
+ if (shown) return;
270
+ shown = true;
271
+ shownSelection = first;
272
+ for (const fn of [...selectionListeners]) fn(shownSelection);
273
+ addEventListener("message", (e) => {
274
+ const d = e.data;
275
+ if (e.source !== window.parent || d?.type !== "appos:selection") return;
276
+ shownSelection = d.selection ?? null;
277
+ for (const fn of [...selectionListeners]) fn(shownSelection);
278
+ });
279
+ reportHeight();
280
+ }
281
+ /** The page's height is its body's: sent as it changes, for the slot. A page that is shown keeps its body as tall as what it shows. */
282
+ function reportHeight() {
283
+ let last = -1;
284
+ const send = () => {
285
+ const body = document.body;
286
+ if (!body) return;
287
+ const height = Math.ceil(body.getBoundingClientRect().bottom + scrollY + (parseFloat(getComputedStyle(body).marginBottom) || 0));
288
+ if (height === last) return;
289
+ last = height;
290
+ tell("appos:embed-size", { height });
291
+ };
292
+ const watch = () => {
293
+ new ResizeObserver(send).observe(document.body);
294
+ send();
295
+ };
296
+ if (document.body) watch();
297
+ else addEventListener("DOMContentLoaded", watch, { once: true });
298
+ }
299
+ /**
300
+ * For a page another app shows (appos.embed): `fn` hears what is selected in that app, now and each time it changes
301
+ * (null for nothing), with the app. Never called in a page no app shows. Returns the unsubscribe.
302
+ */
303
+ function onSelection(fn) {
304
+ selectionListeners.add(fn);
305
+ if (shown) queueMicrotask(() => selectionListeners.has(fn) && fn(shownSelection));
306
+ else if (window.parent !== window) getHello().catch(() => {});
307
+ return () => void selectionListeners.delete(fn);
308
+ }
309
+ var current;
310
+ var upgradeListeners = [];
311
+ async function ready() {
312
+ if (current) return current;
313
+ const h = await getHello();
314
+ const label = labelOf(h);
315
+ let stored = null;
316
+ try {
317
+ stored = localStorage.getItem(VERSION_KEY);
318
+ localStorage.setItem(VERSION_KEY, label);
319
+ } catch {}
320
+ current = {
321
+ version: h.version,
322
+ ...h.build !== void 0 ? { build: h.build } : {},
323
+ ...stored && stored !== label ? {
324
+ previousVersion: stored,
325
+ upgrade: {
326
+ from: stored,
327
+ to: label
328
+ }
329
+ } : {}
330
+ };
331
+ if (current.upgrade) for (const fn of upgradeListeners) fn(current.upgrade.from, current.upgrade.to);
332
+ return current;
333
+ }
334
+ var sheetHost;
335
+ function closeSheet() {
336
+ sheetHost?.remove();
337
+ sheetHost = void 0;
338
+ }
339
+ /** A small modal sheet inside the app's frame. */
340
+ function showSheet(opts) {
341
+ closeSheet();
342
+ const host = document.createElement("div");
343
+ host.setAttribute("data-appos-sheet", "");
344
+ const root = host.attachShadow({ mode: "open" });
345
+ root.innerHTML = `<style>
346
+ :host { all: initial; }
347
+ .scrim { position: fixed; inset: 0; z-index: 2147483647; display: grid; place-items: end center;
348
+ background: rgb(0 0 0 / .35); font: 14px/1.4 ui-sans-serif, system-ui, sans-serif; }
349
+ .sheet { box-sizing: border-box; width: min(420px, calc(100vw - 24px)); margin: 12px; padding: 18px;
350
+ border-radius: 14px; background: #fff; color: #111; box-shadow: 0 10px 40px rgb(0 0 0 / .25); }
351
+ h2 { margin: 0 0 6px; font-size: 16px; } p { margin: 0 0 14px; color: #555; }
352
+ .row { display: flex; gap: 8px; justify-content: flex-end; flex-wrap: wrap; }
353
+ button { font: inherit; padding: 8px 14px; border-radius: 9px; border: 1px solid #ccc; background: transparent; color: inherit; cursor: pointer; }
354
+ button.primary { background: #111; color: #fff; border-color: #111; }
355
+ @media (prefers-color-scheme: dark) { .sheet { background: #1b1b1b; color: #eee; } p { color: #aaa; }
356
+ button { border-color: #444; } button.primary { background: #eee; color: #111; border-color: #eee; } }
357
+ </style><div class="scrim" role="dialog" aria-modal="true"><div class="sheet"><h2></h2><p></p><div class="row"></div></div></div>`;
358
+ root.querySelector("h2").textContent = opts.title;
359
+ root.querySelector("p").textContent = opts.text;
360
+ const row = root.querySelector(".row");
361
+ const actions = [...opts.actions ?? []];
362
+ if (opts.dismissable !== false) actions.unshift({
363
+ label: "Not now",
364
+ run: () => {}
365
+ });
366
+ for (const a of actions) {
367
+ const b = document.createElement("button");
368
+ b.textContent = a.label;
369
+ if (a.primary) b.className = "primary";
370
+ b.onclick = async () => {
371
+ b.disabled = true;
372
+ try {
373
+ await a.run();
374
+ } finally {
375
+ closeSheet();
376
+ }
377
+ };
378
+ row.append(b);
379
+ }
380
+ document.body.append(host);
381
+ sheetHost = host;
382
+ }
383
+ var appName = document.title || "this app";
384
+ /** The LiveWorker a backend path belongs to ("/actor/<id>"), if any. */
385
+ var liveWorkerPathOf = (path) => /^\/actor\/[^/?#]+/.exec(path)?.[0];
386
+ /** Shows the built-in sheet for a cloud problem the user can act on (`liveWorkerPath`: the LiveWorker the call went to). */
387
+ function explain(error, liveWorkerPath) {
388
+ switch (error.code) {
389
+ case "signed-out":
390
+ showSheet({
391
+ title: "Sign in to continue",
392
+ text: `Sign in to appOS Cloud to use ${appName}'s shared data.`,
393
+ actions: [{
394
+ label: "Sign in to appOS Cloud",
395
+ primary: true,
396
+ run: () => void ask("appos:sign-in").catch(() => {})
397
+ }]
398
+ });
399
+ break;
400
+ case "update-required":
401
+ showSheet({
402
+ title: "Update to join",
403
+ text: updateRequiredText(appName, error.details),
404
+ dismissable: false,
405
+ actions: [{
406
+ label: "Update",
407
+ primary: true,
408
+ run: () => void ask("appos:update-from-cloud", typeof error.details.hash === "string" ? { hash: error.details.hash } : {}, 12e4).catch((e) => showSheet({
409
+ title: "Couldn't update",
410
+ text: e instanceof Error && e.message ? e.message : `${appName} did not update.`
411
+ }))
412
+ }]
413
+ });
414
+ break;
415
+ case "upgrade-pending":
416
+ case "upgrade-denied": {
417
+ const sheet = upgradeSheet(appName, error.code, error.message, error.details);
418
+ const decide = async (approve) => {
419
+ try {
420
+ await liveWorkerJson(`${liveWorkerPath}/_upgrade`, {
421
+ method: "POST",
422
+ json: { approve }
423
+ });
424
+ if (approve) location.reload();
425
+ } catch {}
426
+ };
427
+ showSheet({
428
+ title: sheet.title,
429
+ text: sheet.text,
430
+ actions: liveWorkerPath ? sheet.actions.map((a) => a === "approve" ? {
431
+ label: "Approve",
432
+ primary: true,
433
+ run: () => decide(true)
434
+ } : {
435
+ label: "Deny",
436
+ run: () => decide(false)
437
+ }) : []
438
+ });
439
+ break;
440
+ }
441
+ }
442
+ }
443
+ var port;
444
+ var nextId = 0;
445
+ var pending = /* @__PURE__ */ new Map();
446
+ function onWire(e) {
447
+ const m = e.data;
448
+ const p = pending.get(m?.id);
449
+ if (!p) return;
450
+ switch (m.op) {
451
+ case "head": {
452
+ const stream = new ReadableStream({
453
+ start: (c) => void (p.stream = c),
454
+ cancel: () => {
455
+ pending.delete(m.id);
456
+ port?.then((pt) => pt.postMessage({
457
+ op: "abort",
458
+ id: m.id
459
+ }));
460
+ }
461
+ });
462
+ const nullBody = m.status === 204 || m.status === 205 || m.status === 304;
463
+ p.head?.(new Response(nullBody ? null : stream, {
464
+ status: m.status,
465
+ statusText: m.statusText,
466
+ headers: m.headers
467
+ }));
468
+ p.head = p.fail = void 0;
469
+ break;
470
+ }
471
+ case "chunk":
472
+ p.stream?.enqueue(m.data);
473
+ break;
474
+ case "end":
475
+ pending.delete(m.id);
476
+ try {
477
+ p.stream?.close();
478
+ } catch {}
479
+ break;
480
+ case "error": {
481
+ pending.delete(m.id);
482
+ const err = new CloudError(m.code, m.message);
483
+ if (p.fail) p.fail(err);
484
+ else p.stream?.error(err);
485
+ p.socket?._closed(1006, m.message, false);
486
+ break;
487
+ }
488
+ case "ws-open":
489
+ p.socket?._opened(m.protocol);
490
+ break;
491
+ case "ws-message":
492
+ p.socket?._message(m.data);
493
+ break;
494
+ case "ws-close":
495
+ pending.delete(m.id);
496
+ p.socket?._closed(m.code, m.reason, m.clean);
497
+ }
498
+ }
499
+ /** The port to the shell, set up on first use. */
500
+ function bridge() {
501
+ port ??= (async () => {
502
+ const channel = new MessageChannel();
503
+ channel.port1.onmessage = onWire;
504
+ await ask("appos:backend", {}, 2e4, [channel.port2]);
505
+ return channel.port1;
506
+ })().catch((e) => {
507
+ port = void 0;
508
+ throw e;
509
+ });
510
+ return port;
511
+ }
512
+ /** A backend path: "/actors", "/actor/cloud-Board-x/sw". Never a URL. */
513
+ function backendPath(input) {
514
+ let path;
515
+ if (typeof input === "string") path = input;
516
+ else {
517
+ const u = new URL(input.url);
518
+ if (u.origin !== location.origin) throw new TypeError("backend.fetch takes a backend path, not another site's URL.");
519
+ path = u.pathname + u.search;
520
+ }
521
+ if (!path.startsWith("/") || path.startsWith("//")) throw new TypeError(`backend.fetch takes a path like "/actor/<id>/x", not ${JSON.stringify(path)}.`);
522
+ return path;
523
+ }
524
+ async function bodyBytes(body) {
525
+ if (body === null || body === void 0) return void 0;
526
+ const buf = await new Response(body).arrayBuffer();
527
+ if (buf.byteLength > MAX_BODY) throw new CloudError("too-big", "Request bodies are capped at 1 MB.", 413);
528
+ return buf;
529
+ }
530
+ /**
531
+ * The app's backend. It has no URL: `fetch()` can't reach it, so a URL that
532
+ * came from anywhere (a link, a message, another site) never becomes a call
533
+ * to it. Paths name a LiveWorker and what to send it:
534
+ *
535
+ * /whoami
536
+ * /actors GET: the user's LiveWorkers; POST /actors/<Class>: a new one
537
+ * /actor/<id>/<path> one LiveWorker
538
+ */
539
+ var backend = {
540
+ /** Sends a request to the backend; resolves to its streamed response. */
541
+ async fetch(input, init = {}) {
542
+ const path = backendPath(input);
543
+ const req = typeof input === "string" ? void 0 : input;
544
+ const method = (init.method ?? req?.method ?? "GET").toUpperCase();
545
+ const headers = new Headers(init.headers ?? req?.headers);
546
+ const body = await bodyBytes(init.body !== void 0 ? init.body : req && !["GET", "HEAD"].includes(method) ? await req.arrayBuffer() : void 0);
547
+ const signal = init.signal ?? req?.signal;
548
+ signal?.throwIfAborted();
549
+ const pt = await bridge();
550
+ const id = ++nextId;
551
+ return new Promise((resolve, reject) => {
552
+ pending.set(id, {
553
+ head: resolve,
554
+ fail: reject
555
+ });
556
+ signal?.addEventListener("abort", () => {
557
+ const p = pending.get(id);
558
+ pending.delete(id);
559
+ pt.postMessage({
560
+ op: "abort",
561
+ id
562
+ });
563
+ const reason = signal.reason ?? new DOMException("Aborted", "AbortError");
564
+ if (p?.fail) p.fail(reason);
565
+ else try {
566
+ p?.stream?.error(reason);
567
+ } catch {}
568
+ }, { once: true });
569
+ pt.postMessage({
570
+ op: "fetch",
571
+ id,
572
+ method,
573
+ path,
574
+ headers: [...headers],
575
+ body
576
+ }, body ? [body] : []);
577
+ });
578
+ },
579
+ /** A WebSocket to the backend, relayed by the shell. */
580
+ async connect(path, protocols = []) {
581
+ const p = backendPath(path);
582
+ const pt = await bridge();
583
+ const id = ++nextId;
584
+ const socket = new BackendSocket(pt, id);
585
+ pending.set(id, { socket });
586
+ pt.postMessage({
587
+ op: "ws",
588
+ id,
589
+ path: p,
590
+ protocols: typeof protocols === "string" ? [protocols] : protocols
591
+ });
592
+ return socket;
593
+ }
594
+ };
595
+ /** A WebSocket-like socket over the handle: send, close, open/message/close/error events. */
596
+ var BackendSocket = class extends EventTarget {
597
+ port;
598
+ id;
599
+ static CONNECTING = 0;
600
+ static OPEN = 1;
601
+ static CLOSING = 2;
602
+ static CLOSED = 3;
603
+ readyState = 0;
604
+ protocol = "";
605
+ binaryType = "arraybuffer";
606
+ onopen = null;
607
+ onmessage = null;
608
+ onclose = null;
609
+ onerror = null;
610
+ constructor(port, id) {
611
+ super();
612
+ this.port = port;
613
+ this.id = id;
614
+ }
615
+ send(data) {
616
+ if (this.readyState !== 1) throw new DOMException("The socket is not open.", "InvalidStateError");
617
+ const out = typeof data === "string" || data instanceof ArrayBuffer ? data : data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
618
+ this.port.postMessage({
619
+ op: "ws-send",
620
+ id: this.id,
621
+ data: out
622
+ });
623
+ }
624
+ close(code, reason) {
625
+ if (this.readyState >= 2) return;
626
+ this.readyState = 2;
627
+ this.port.postMessage({
628
+ op: "ws-close",
629
+ id: this.id,
630
+ code,
631
+ reason
632
+ });
633
+ }
634
+ #emit(e) {
635
+ this.dispatchEvent(e);
636
+ this[`on${e.type}`]?.call(this, e);
637
+ }
638
+ /** @internal */
639
+ _opened(protocol) {
640
+ this.readyState = 1;
641
+ this.protocol = protocol;
642
+ this.#emit(new Event("open"));
643
+ }
644
+ /** @internal */
645
+ _message(data) {
646
+ this.#emit(new MessageEvent("message", { data }));
647
+ }
648
+ /** @internal */
649
+ _closed(code, reason, clean) {
650
+ if (this.readyState === 3) return;
651
+ const wasOpen = this.readyState === 1 || this.readyState === 2;
652
+ this.readyState = 3;
653
+ pending.delete(this.id);
654
+ if (!clean && !wasOpen) this.#emit(new Event("error"));
655
+ this.#emit(new CloseEvent("close", {
656
+ code,
657
+ reason,
658
+ wasClean: clean
659
+ }));
660
+ }
661
+ };
662
+ async function errorOf(res) {
663
+ try {
664
+ const b = await res.json();
665
+ if (typeof b.error === "string") return new CloudError(b.error, b.message ?? b.error, res.status, b);
666
+ } catch {}
667
+ }
668
+ /** A file link's data (/a/<did>/<name>#d=<data>), as the shell passes it: base64url text. */
669
+ function launchDataOnce() {
670
+ const m = /^#appos-data=([A-Za-z0-9_-]+)$/.exec(location.hash);
671
+ if (!m) return void 0;
672
+ history.replaceState(history.state, "", location.pathname + location.search);
673
+ return m[1];
674
+ }
675
+ /** The LiveWorker a share link opened this app on, and the link's key, as the shell passes them. */
676
+ function launchLinkOnce() {
677
+ const m = /^#appos-actor=([^&]+)&k=([A-Za-z0-9_-]+)$/.exec(location.hash);
678
+ if (!m) return void 0;
679
+ history.replaceState(history.state, "", location.pathname + location.search);
680
+ return {
681
+ actor: decodeURIComponent(m[1]),
682
+ key: m[2]
683
+ };
684
+ }
685
+ async function liveWorkerJson(path, init = {}) {
686
+ const headers = new Headers(init.headers);
687
+ let body = init.body;
688
+ if (init.json !== void 0) {
689
+ body = JSON.stringify(init.json);
690
+ headers.set("content-type", "application/json");
691
+ }
692
+ const { json: _, ...rest } = init;
693
+ const res = await backend.fetch(path, {
694
+ ...rest,
695
+ headers,
696
+ body
697
+ });
698
+ if (!res.ok) {
699
+ const err = await errorOf(res) ?? new CloudError("error", `${path} failed (${res.status})`, res.status);
700
+ explain(err, liveWorkerPathOf(path));
701
+ throw err;
702
+ }
703
+ return await res.json();
704
+ }
705
+ /** A connection to one LiveWorker: RPC, fetch and a live socket, each with the user's claims. */
706
+ var LiveWorker = class {
707
+ id;
708
+ path;
709
+ /** The signed-in user's roles, as of open(). */
710
+ roles = [];
711
+ constructor(id) {
712
+ this.id = id;
713
+ this.path = `/actor/${encodeURIComponent(id)}`;
714
+ }
715
+ /** backend.fetch() to the LiveWorker's own fetch handler, at `sub` under it. Problems the user can act on get the SDK's sheets. */
716
+ async fetch(sub = "/", init = {}) {
717
+ const res = await backend.fetch(this.path + (sub.startsWith("/") ? sub : `/${sub}`).replace(/^\/$/, ""), init);
718
+ if (!res.ok) {
719
+ const err = await errorOf(res.clone());
720
+ if (err) explain(err, this.path);
721
+ }
722
+ return res;
723
+ }
724
+ /** Calls a method of the LiveWorker's class. Throws CloudError on failure. */
725
+ async call(method, ...args) {
726
+ return (await liveWorkerJson(`${this.path}/_rpc`, {
727
+ method: "POST",
728
+ json: {
729
+ method,
730
+ args
731
+ }
732
+ })).result;
733
+ }
734
+ /** A WebSocket to the LiveWorker's fetch handler. */
735
+ websocket(sub = "/", protocols = []) {
736
+ return backend.connect(this.path + (sub.startsWith("/") ? sub : `/${sub}`), protocols);
737
+ }
738
+ /**
739
+ * The owner and members to show: [{ id, role, name?, image? }]. `name` and
740
+ * `image` (an https avatar URL) come from each person's assistant-ui
741
+ * account; someone who never signed in to appOS has only id and role.
742
+ * The backend reads the same list with env.appos.profiles(). Cloud LiveWorkers only.
743
+ */
744
+ async profiles() {
745
+ return (await liveWorkerJson(`${this.path}/_profiles`)).profiles;
746
+ }
747
+ /** Owner, roles, the build it runs. Shows the owner a newer build a member asked for (Approve / Deny). */
748
+ async info() {
749
+ const info = await liveWorkerJson(`${this.path}/_info`);
750
+ this.roles = info.roles;
751
+ const p = info.pending;
752
+ if (info.isOwner && p && !p.denied) {
753
+ const decide = (approve) => void liveWorkerJson(`${this.path}/_upgrade`, {
754
+ method: "POST",
755
+ json: { approve }
756
+ }).catch(() => {});
757
+ showSheet({
758
+ title: "Update this board?",
759
+ text: `Someone wants to update ${appName} to ${p.version}. It runs ${info.running?.version ?? "?"} now.`,
760
+ dismissable: false,
761
+ actions: [{
762
+ label: "Deny",
763
+ run: () => decide(false)
764
+ }, {
765
+ label: "Approve",
766
+ primary: true,
767
+ run: () => decide(true)
768
+ }]
769
+ });
770
+ }
771
+ return info;
772
+ }
773
+ };
774
+ var liveWorkers = {
775
+ /**
776
+ * A new LiveWorker of class `name`, owned by the user, on their default host.
777
+ * `host` says where it went: "cloud" or the host's name.
778
+ */
779
+ create(name) {
780
+ return liveWorkerJson(`/actors/${encodeURIComponent(name)}`, { method: "POST" });
781
+ },
782
+ /** A connection to a LiveWorker the user holds a role in. Rejects with "not-member" otherwise. */
783
+ async open(id) {
784
+ const a = new LiveWorker(id);
785
+ await a.info();
786
+ return a;
787
+ },
788
+ /** The LiveWorkers the user owns or holds a role in, on every host. */
789
+ async list() {
790
+ return (await liveWorkerJson("/actors")).actors;
791
+ },
792
+ /** Owner only: gives `user` a role in LiveWorker `id`. */
793
+ /** Owner only: gives `user` (their appOS ID) a role in LiveWorker `id`. */
794
+ async grant(id, user, role) {
795
+ await liveWorkerJson(`${new LiveWorker(id).path}/_members`, {
796
+ method: "POST",
797
+ json: {
798
+ user,
799
+ role
800
+ }
801
+ });
802
+ },
803
+ /** Owner only: takes `user`'s role in LiveWorker `id` away. */
804
+ async revoke(id, user) {
805
+ await liveWorkerJson(`${new LiveWorker(id).path}/_members`, {
806
+ method: "DELETE",
807
+ json: { user }
808
+ });
809
+ },
810
+ /**
811
+ * The LiveWorker a share link opened this app on, joined with the link's key
812
+ * (once per launch). Undefined when the app was not opened from one.
813
+ */
814
+ async launched() {
815
+ const l = launchLink;
816
+ launchLink = void 0;
817
+ if (!l) return void 0;
818
+ const a = new LiveWorker(l.actor);
819
+ await liveWorkerJson(`${a.path}/_join`, {
820
+ method: "POST",
821
+ json: { key: l.key }
822
+ });
823
+ await a.info();
824
+ return a;
825
+ }
826
+ };
827
+ /**
828
+ * A link that opens this app on LiveWorker `id` and gives whoever opens it `role`
829
+ * (editor by default; viewers can share only as viewers). The app shows it
830
+ * in its own share sheet.
831
+ */
832
+ async function share(id, role = "editor") {
833
+ const { key } = await liveWorkerJson(`${new LiveWorker(id).path}/_invite?role=${role}`);
834
+ return (await ask("appos:share-link", {
835
+ actor: id,
836
+ key
837
+ })).url;
838
+ }
839
+ /**
840
+ * Opens appOS's Share sheet for LiveWorker `id`: the people on it with their role
841
+ * and the link each joined by, and, for its owner, the share links (new,
842
+ * copy, revoke). The same sheet for every app; resolves once it is shown.
843
+ */
844
+ async function openShare(id) {
845
+ await ask("appos:share-sheet", { actor: id });
846
+ }
847
+ /**
848
+ * Calls `fn` when appOS finds the signed-in person's access to a LiveWorker
849
+ * changed (revoked, or they left on another device). Returns an unsubscribe.
850
+ */
851
+ function onAccess(fn) {
852
+ const origin = parentOrigin();
853
+ const listener = (e) => {
854
+ if (e.source !== window.parent || origin && e.origin !== origin) return;
855
+ const d = e.data;
856
+ if (d?.type !== "appos:access" || typeof d.actor !== "string") return;
857
+ fn({
858
+ actor: d.actor,
859
+ role: d.role === "owner" || d.role === "editor" || d.role === "viewer" ? d.role : null
860
+ });
861
+ };
862
+ addEventListener("message", listener);
863
+ return () => removeEventListener("message", listener);
864
+ }
865
+ /** The text of the live file this frame runs, when it is shared by link (appos.liveText()). */
866
+ var LiveText = class {
867
+ /** The link that opens this file, to copy and send. */
868
+ url;
869
+ #port;
870
+ #data;
871
+ #rev = 0;
872
+ /** The newest local write the cloud hasn't confirmed. */
873
+ #pending;
874
+ #sent = 0;
875
+ #acked = 0;
876
+ #first;
877
+ #resolveFirst;
878
+ #changeFns = /* @__PURE__ */ new Set();
879
+ #statusFns = /* @__PURE__ */ new Set();
880
+ #status = { state: "connecting" };
881
+ /** @internal */
882
+ constructor(port, url) {
883
+ this.url = url;
884
+ this.#port = port;
885
+ this.#first = new Promise((r) => this.#resolveFirst = r);
886
+ port.onmessage = (e) => this.#onMessage(e.data);
887
+ port.start();
888
+ }
889
+ /** The file's text as this frame last saw it; undefined until loaded(). */
890
+ get data() {
891
+ return this.#data;
892
+ }
893
+ get rev() {
894
+ return this.#rev;
895
+ }
896
+ get status() {
897
+ return this.#status;
898
+ }
899
+ /** Resolves with the file's text once the cloud has sent it. */
900
+ loaded() {
901
+ return this.#first;
902
+ }
903
+ /** Runs `fn` with the text whenever someone else changed the file. */
904
+ onChange(fn) {
905
+ this.#changeFns.add(fn);
906
+ return () => void this.#changeFns.delete(fn);
907
+ }
908
+ /** Runs `fn` when the connection changes (connecting, live with N people, offline). */
909
+ onStatus(fn) {
910
+ this.#statusFns.add(fn);
911
+ return () => void this.#statusFns.delete(fn);
912
+ }
913
+ /** Replaces the file's text for everyone. Resent after a reconnect until the cloud confirms it. */
914
+ save(data) {
915
+ this.#data = data;
916
+ this.#pending = data;
917
+ this.#put(data);
918
+ }
919
+ /** True while a local write is not yet in the cloud. */
920
+ get saving() {
921
+ return this.#pending !== void 0;
922
+ }
923
+ close() {
924
+ this.#port.postMessage({ t: "close" });
925
+ this.#port.close();
926
+ }
927
+ #put(data) {
928
+ this.#sent++;
929
+ this.#port.postMessage({
930
+ t: "put",
931
+ data
932
+ });
933
+ }
934
+ #setStatus(s) {
935
+ this.#status = s;
936
+ for (const fn of this.#statusFns) fn(s);
937
+ }
938
+ #changed(data) {
939
+ if (data === this.#data) return;
940
+ this.#data = data;
941
+ for (const fn of this.#changeFns) fn(data);
942
+ }
943
+ #onMessage(m) {
944
+ switch (m.t) {
945
+ case "welcome": {
946
+ this.#sent = this.#acked = 0;
947
+ this.#rev = m.rev;
948
+ const data = m.data;
949
+ const first = this.#data === void 0;
950
+ if (this.#pending !== void 0 && this.#pending !== data) this.#put(this.#pending);
951
+ else {
952
+ this.#pending = void 0;
953
+ if (first) this.#data = data;
954
+ else this.#changed(data);
955
+ }
956
+ this.#setStatus({
957
+ state: "live",
958
+ peers: m.peers
959
+ });
960
+ if (first) this.#resolveFirst(this.#data ?? data);
961
+ break;
962
+ }
963
+ case "ack":
964
+ this.#rev = m.rev;
965
+ if (++this.#acked >= this.#sent) this.#pending = void 0;
966
+ break;
967
+ case "data":
968
+ this.#rev = m.rev;
969
+ if (this.#pending === void 0) this.#changed(m.data);
970
+ break;
971
+ case "peers":
972
+ if (this.#status.state === "live") this.#setStatus({
973
+ state: "live",
974
+ peers: m.peers
975
+ });
976
+ break;
977
+ case "error": if (m.code === "offline") this.#setStatus({
978
+ state: "offline",
979
+ message: String(m.message)
980
+ });
981
+ else this.#setStatus({
982
+ state: "error",
983
+ code: String(m.code),
984
+ message: String(m.message)
985
+ });
986
+ }
987
+ }
988
+ };
989
+ async function liveText() {
990
+ const channel = new MessageChannel();
991
+ try {
992
+ const r = await ask("appos:live-file", {}, 2e4, [channel.port2]);
993
+ return new LiveText(channel.port1, r.url);
994
+ } catch (e) {
995
+ channel.port1.close();
996
+ if (e instanceof CloudError && e.code === "not-live") return void 0;
997
+ throw e;
998
+ }
999
+ }
1000
+ /**
1001
+ * Moves the file this frame runs to the appOS cloud as a live file holding
1002
+ * `data` (text, at most 512 KB), and returns its link. Anyone with the link
1003
+ * opens the file and edits it live; no sign-in. Already live: its link.
1004
+ * Afterwards appos.liveText() connects to it.
1005
+ */
1006
+ async function shareFile(data) {
1007
+ return ask("appos:share-file", { data }, 3e4);
1008
+ }
1009
+ /** A port to the shell for one AI call or voice session. */
1010
+ function shellPort(type) {
1011
+ if (window.parent === window) throw new CloudError("no-shell", "Open this app from appOS.");
1012
+ const ch = new MessageChannel();
1013
+ window.parent.postMessage({ type }, parentOrigin() ?? "*", [ch.port2]);
1014
+ ch.port1.start();
1015
+ return ch.port1;
1016
+ }
1017
+ function postPlain(port, msg) {
1018
+ try {
1019
+ port.postMessage(msg);
1020
+ } catch {
1021
+ port.postMessage(JSON.parse(JSON.stringify(msg)));
1022
+ }
1023
+ }
1024
+ var capError = (e) => new CloudError(e.code ?? "error", e.message ?? "The call failed.");
1025
+ /**
1026
+ * One AI call to the shell (the "appos:ai" port): AI SDK LanguageModelV4
1027
+ * call options in (prompt, tools, maxOutputTokens…; no headers or signal),
1028
+ * its stream parts out. `model` is a hint: the provider the user set up
1029
+ * decides. Errors with code "not-configured" mean no AI is set up; offer
1030
+ * appos.openSettings(). The AI SDK model on top is appos-client/ai-sdk.
1031
+ */
1032
+ function aiCall(options, model, signal) {
1033
+ const port = shellPort("appos:ai");
1034
+ const abort = () => {
1035
+ postPlain(port, { op: "abort" });
1036
+ port.close();
1037
+ };
1038
+ signal?.addEventListener("abort", abort, { once: true });
1039
+ return new ReadableStream({
1040
+ start(controller) {
1041
+ port.onmessage = (e) => {
1042
+ const d = e.data;
1043
+ if (d.part) {
1044
+ const p = d.part;
1045
+ controller.enqueue(p.type === "error" ? {
1046
+ type: "error",
1047
+ error: capError(p.error)
1048
+ } : p);
1049
+ } else if (d.done) {
1050
+ controller.close();
1051
+ port.close();
1052
+ } else if (d.error) {
1053
+ controller.error(capError(d.error));
1054
+ port.close();
1055
+ }
1056
+ };
1057
+ postPlain(port, {
1058
+ op: "stream",
1059
+ model,
1060
+ options
1061
+ });
1062
+ },
1063
+ cancel: abort
1064
+ });
1065
+ }
1066
+ /** Text deltas for one prompt: `for await (const t of appos.ai.stream({ prompt: "Hi" }))`. */
1067
+ async function* aiStream(opts) {
1068
+ const reader = aiCall({
1069
+ prompt: [...opts.system ? [{
1070
+ role: "system",
1071
+ content: opts.system
1072
+ }] : [], {
1073
+ role: "user",
1074
+ content: [{
1075
+ type: "text",
1076
+ text: opts.prompt
1077
+ }]
1078
+ }],
1079
+ maxOutputTokens: opts.maxOutputTokens ?? 4096
1080
+ }, opts.model).getReader();
1081
+ for (;;) {
1082
+ const { done, value } = await reader.read();
1083
+ if (done) return;
1084
+ if (value.type === "text-delta") yield value.delta;
1085
+ else if (value.type === "error") throw value.error;
1086
+ }
1087
+ }
1088
+ /**
1089
+ * Live transcription. The shell holds the mic and the provider; the app gets
1090
+ * text. Times are seconds since listening started. Ends with an "end" event
1091
+ * (after an "error" one when it failed).
1092
+ */
1093
+ function transcribe(options, onEvent) {
1094
+ let port;
1095
+ try {
1096
+ port = shellPort("appos:voice");
1097
+ } catch (e) {
1098
+ const err = e;
1099
+ queueMicrotask(() => {
1100
+ onEvent({
1101
+ event: "error",
1102
+ code: err.code,
1103
+ message: err.message
1104
+ });
1105
+ onEvent({ event: "end" });
1106
+ });
1107
+ return {
1108
+ stop() {},
1109
+ ended: Promise.resolve()
1110
+ };
1111
+ }
1112
+ const ended = new Promise((resolve) => {
1113
+ port.onmessage = (e) => {
1114
+ const ev = e.data;
1115
+ onEvent(ev);
1116
+ if (ev.event === "end") {
1117
+ port.close();
1118
+ resolve();
1119
+ }
1120
+ };
1121
+ });
1122
+ postPlain(port, {
1123
+ op: "start",
1124
+ options
1125
+ });
1126
+ return {
1127
+ stop: () => postPlain(port, { op: "stop" }),
1128
+ ended
1129
+ };
1130
+ }
1131
+ var permissions = {
1132
+ /** The grant now: "prompt" until the user has answered. */
1133
+ async query(cap) {
1134
+ return (await ask("appos:permission", { cap })).state;
1135
+ },
1136
+ /** Asks the user (the shell's prompt) if they never have; the answer is remembered per app. */
1137
+ async request(cap) {
1138
+ return (await ask("appos:permission", {
1139
+ cap,
1140
+ request: true
1141
+ }, 6e5)).state;
1142
+ }
1143
+ };
1144
+ var launchLink = launchLinkOnce();
1145
+ var launchedData = launchDataOnce();
1146
+ var appos = {
1147
+ /** The app's backend: backend.fetch(path), backend.connect(path). No URL reaches it. */
1148
+ backend,
1149
+ /** The app's LiveWorkers: create, open, list, grant, revoke, launched (appos.actors in the manifest). */
1150
+ liveWorkers,
1151
+ /** A share link to a LiveWorker for a role: share(id, "viewer"). */
1152
+ share,
1153
+ /** appOS's Share sheet for a LiveWorker: openShare(id). */
1154
+ openShare,
1155
+ /** Hears when the person's access to a LiveWorker changed: onAccess(({ LiveWorker, role }) => …). */
1156
+ onAccess,
1157
+ /** { version, previousVersion }: previousVersion only on the first launch after an update. */
1158
+ ready,
1159
+ /** This build's manifest version (after ready()). */
1160
+ get version() {
1161
+ return current?.version;
1162
+ },
1163
+ /** This build's appos.build, if the app has builds (after ready()). */
1164
+ get build() {
1165
+ return current?.build;
1166
+ },
1167
+ /**
1168
+ * Asks the shell for this app's newest build now (the app's server said it
1169
+ * is too old, or the app came back into view): the shell checks the app's
1170
+ * update feed and applies what it lists at once, relaunching this frame.
1171
+ * Answers when there was nothing to apply ("none"), or the check failed.
1172
+ */
1173
+ checkForUpdate() {
1174
+ return ask("appos:check-update", {}, 12e4);
1175
+ },
1176
+ /**
1177
+ * What this origin ran before, on the first launch after an update (after
1178
+ * ready()): the version, or "0.0.1 (12)" for apps with builds.
1179
+ */
1180
+ get previousVersion() {
1181
+ return current?.previousVersion;
1182
+ },
1183
+ /** Runs once, on the first launch after an update: migrate local data here. */
1184
+ onUpgrade(fn) {
1185
+ upgradeListeners.push(fn);
1186
+ if (current?.upgrade) fn(current.upgrade.from, current.upgrade.to);
1187
+ else ready().catch(() => {});
1188
+ },
1189
+ /**
1190
+ * The data a file link opened this app with (/a/<did>/<name>#d=<data>),
1191
+ * the first time it is asked: base64url text in the app's own format. The
1192
+ * file is local and the link reopens it, so fill the file only when it is
1193
+ * new. It came from a link: treat it as untrusted input.
1194
+ */
1195
+ launchData() {
1196
+ const d = launchedData;
1197
+ launchedData = void 0;
1198
+ return d;
1199
+ },
1200
+ /**
1201
+ * The live file this frame runs, connected: load with loaded(), write with
1202
+ * save(), hear others with onChange(). Undefined when the file is not live
1203
+ * (see shareFile()).
1204
+ */
1205
+ liveText,
1206
+ /** Moves this frame's file to the cloud as a live file; resolves to its link. */
1207
+ shareFile,
1208
+ /** The live file this frame runs; undefined in appOS from before live files. */
1209
+ async liveFile() {
1210
+ return (await getHello()).grain;
1211
+ },
1212
+ /** The person's files of this app: the shell's Open and New dialogs, and this app's own list of them. */
1213
+ files: {
1214
+ /** The shell's Open dialog, or with an address, one of this app's own files in its tab (see openFiles). */
1215
+ open: openFiles,
1216
+ /**
1217
+ * This app's files the person owns or that are shared with them, on every host the shell is signed in to and this
1218
+ * device, by name: what each is and where, never its data. Only this app's own type: other apps' files come only
1219
+ * through the shell's Open dialog. `folder`: only those in that folder ("" the top, "Work/Plans" deeper).
1220
+ */
1221
+ async list({ folder } = {}) {
1222
+ return (await ask("appos:files-list", folder === void 0 ? {} : { folder }, 6e4)).files;
1223
+ },
1224
+ /** This app's files the person opened on this device lately, newest first: `limit` of them (10; at most 50). */
1225
+ async recent({ limit } = {}) {
1226
+ return (await ask("appos:files-recent", limit === void 0 ? {} : { limit }, 6e4)).files;
1227
+ },
1228
+ /**
1229
+ * The shell's New dialog: the user picks a host, a folder and a name, and the shell makes a file of this app
1230
+ * there (of `kind`, one of the app's LiveWorker classes, when given). Resolves to its LiveWorker id (open it with
1231
+ * appos.liveWorkers.open(id)), or null when the user cancelled. The app never sees the user's other files.
1232
+ */
1233
+ async create({ kind } = {}) {
1234
+ try {
1235
+ const { actor } = await ask("appos:files-new", { ...kind ? { kind } : {} }, 864e5);
1236
+ return { id: actor };
1237
+ } catch (e) {
1238
+ if (e instanceof CloudError && e.code === "cancelled") return null;
1239
+ throw e;
1240
+ }
1241
+ },
1242
+ /**
1243
+ * The Files app only (did:web:appos.assistant-ui.workers.dev:apps:files):
1244
+ * every file of every app, on this device and every host, read-only:
1245
+ * where each is, never its data. Other apps get CloudError "forbidden".
1246
+ */
1247
+ all() {
1248
+ return ask("appos:files-all", {}, 6e4);
1249
+ },
1250
+ /** The Files app only: opens a file all() listed in its own app, in a tab. */
1251
+ openInApp(key) {
1252
+ return ask("appos:files-open-in", { key }, 6e4);
1253
+ },
1254
+ /** The Files app only: closes a file all() listed as openWeb to the web. */
1255
+ closeOpenWeb(key) {
1256
+ return ask("appos:files-close-open-web", { key }, 6e4);
1257
+ },
1258
+ /**
1259
+ * The Files app only: renames a file. Names are unique in a folder by name alone; a taken one rejects with
1260
+ * CloudError "name-taken". Resolves to the name it has now.
1261
+ */
1262
+ async rename(key, name) {
1263
+ return (await ask("appos:files-do", {
1264
+ op: "rename",
1265
+ key,
1266
+ name
1267
+ }, 6e4)).title;
1268
+ },
1269
+ /** The Files app only: moves a file into a folder on its host ("" for the top). */
1270
+ async move(key, folder) {
1271
+ await ask("appos:files-do", {
1272
+ op: "move",
1273
+ key,
1274
+ folder
1275
+ }, 6e4);
1276
+ },
1277
+ /**
1278
+ * The Files app only: deletes a file. Its owner's goes to Trash where its host has one ("trash") and for good
1279
+ * elsewhere ("delete"); anyone else's leaves their view on this device ("remove") and stays for its owner.
1280
+ */
1281
+ async delete(key) {
1282
+ return (await ask("appos:files-do", {
1283
+ op: "delete",
1284
+ key
1285
+ }, 6e4)).kind;
1286
+ },
1287
+ /** The Files app only: opens the shell's Share sheet on a file (its people, roles and links). */
1288
+ async share(key) {
1289
+ await ask("appos:files-do", {
1290
+ op: "share",
1291
+ key
1292
+ }, 6e4);
1293
+ },
1294
+ /** The Files app only: the files in Trash, newest first. */
1295
+ async trash() {
1296
+ return (await ask("appos:files-do", { op: "trash" }, 6e4)).files;
1297
+ },
1298
+ /** The Files app only: back from Trash, in its folder (or at the top), its name suffixed if it was taken. */
1299
+ async restore(key) {
1300
+ await ask("appos:files-do", {
1301
+ op: "restore",
1302
+ key
1303
+ }, 6e4);
1304
+ },
1305
+ /** The Files app only: deletes a file in Trash for good, for everyone. */
1306
+ async purge(key) {
1307
+ await ask("appos:files-do", {
1308
+ op: "purge",
1309
+ key
1310
+ }, 6e4);
1311
+ },
1312
+ /** The Files app only: the shell's New dialog at a host and folder; the user picks the app. The file opens in it. */
1313
+ async newFile(host, folder = "") {
1314
+ try {
1315
+ await ask("appos:files-do", {
1316
+ op: "new",
1317
+ host,
1318
+ folder
1319
+ }, 864e5);
1320
+ return true;
1321
+ } catch (e) {
1322
+ if (e instanceof CloudError && e.code === "cancelled") return false;
1323
+ throw e;
1324
+ }
1325
+ },
1326
+ /** The Files app only: deletes every file in Trash for good. */
1327
+ async emptyTrash() {
1328
+ await ask("appos:files-do", { op: "empty" }, 3e5);
1329
+ },
1330
+ /** The Files app only: a host's folders. Folders only organize; sharing is per file. */
1331
+ folders: {
1332
+ async create(host, name, parent = "") {
1333
+ return (await ask("appos:files-do", {
1334
+ op: "mkdir",
1335
+ host,
1336
+ name,
1337
+ parent
1338
+ }, 6e4)).folder;
1339
+ },
1340
+ async rename(host, id, name) {
1341
+ return (await ask("appos:files-do", {
1342
+ op: "folder",
1343
+ host,
1344
+ id,
1345
+ name
1346
+ }, 6e4)).folder;
1347
+ },
1348
+ async move(host, id, parent) {
1349
+ return (await ask("appos:files-do", {
1350
+ op: "folder",
1351
+ host,
1352
+ id,
1353
+ parent
1354
+ }, 6e4)).folder;
1355
+ },
1356
+ /** An empty folder only (CloudError "not-empty" otherwise). */
1357
+ async delete(host, id) {
1358
+ await ask("appos:files-do", {
1359
+ op: "rmdir",
1360
+ host,
1361
+ id
1362
+ }, 6e4);
1363
+ }
1364
+ }
1365
+ },
1366
+ /**
1367
+ * Makes a new file of this app and opens it in its own tab: through the shell's New dialog (host, folder, name)
1368
+ * when the app has LiveWorkers, else on this device. Null when the user cancelled the dialog.
1369
+ */
1370
+ async newLiveFile() {
1371
+ try {
1372
+ const r = await ask("appos:new-grain", {}, 864e5);
1373
+ return {
1374
+ id: r.file,
1375
+ kind: r.kind
1376
+ };
1377
+ } catch (e) {
1378
+ if (e instanceof CloudError && e.code === "cancelled") return null;
1379
+ throw e;
1380
+ }
1381
+ },
1382
+ /**
1383
+ * Opens another of this app's files (its id from liveFile()) in its own tab, as App info does: an app that
1384
+ * lists its own files opens one this way. Rejects with CloudError "no-file" for an id that isn't this app's.
1385
+ */
1386
+ async openLiveFile(id) {
1387
+ await ask("appos:open-grain", { file: id });
1388
+ },
1389
+ /**
1390
+ * Asks appOS to open the file this frame runs (a LiveWorker in the appOS cloud) to the open web, for an app whose
1391
+ * manifest declares appos.openWeb. appOS shows its own prompt to the file's owner; the app never sets it. Answers
1392
+ * { open: true, url } (already open: no prompt), or { open: false } when the owner said no. `url` is the file's
1393
+ * address plus ".git" (none while the file has no address yet): git's smart HTTP there (`<url>/info/refs`,
1394
+ * `/git-upload-pack`, `/git-receive-pack`) reaches the LiveWorker's fetch() at that route, with no user the platform
1395
+ * vouches for (caller() is { roles: [], web: true }) and Authorization untouched: the app checks who they are. Every
1396
+ * refusal there answers as an address that names nothing. The owner closes it in App info or the Files app.
1397
+ */
1398
+ requestOpenWeb() {
1399
+ return ask("appos:open-web", {}, 864e5);
1400
+ },
1401
+ /**
1402
+ * Local live files the user deleted since the app last ran: delete their data
1403
+ * (it shares this origin). Called once per launch with the ids.
1404
+ */
1405
+ onLiveFileRemoved(fn) {
1406
+ removedListeners.push(fn);
1407
+ if (removedSeen?.length) fn(removedSeen);
1408
+ else getHello().catch(() => {});
1409
+ },
1410
+ /** Names the app in the SDK's sheets. */
1411
+ setName(name) {
1412
+ appName = name;
1413
+ },
1414
+ /** Names the file this frame runs, as Home and the tab show it. */
1415
+ async setTitle(title) {
1416
+ await ask("appos:set-title", { title });
1417
+ },
1418
+ /**
1419
+ * A count for the shell to show on this app's tile or tab (unread items, say); 0 clears it. A whole number,
1420
+ * 0 or more. Nothing comes back, and a shell may show it or ignore it (appOS itself doesn't show it yet).
1421
+ * Outside a shell it does nothing.
1422
+ */
1423
+ setBadge(count) {
1424
+ if (!Number.isSafeInteger(count) || count < 0) throw new RangeError("appos.setBadge takes a whole number, 0 or more.");
1425
+ tell("appos:badge", { count });
1426
+ },
1427
+ /** Another app's page in this one: embed(slot, did, path); see appos.embeddable in that app's manifest. */
1428
+ embed,
1429
+ /** What is selected here, for the pages this one shows: setSelection({ address, lines?, text }) or null. */
1430
+ setSelection,
1431
+ /** In a page another app shows: what is selected in that app, now and as it changes. */
1432
+ onSelection,
1433
+ /**
1434
+ * How many CSS px of the shell's own chrome (a host page's mark, say) cover the start of the app's header, from
1435
+ * the shell's hello: pad the header's start by it. 0 when the shell says nothing (appOS itself) or outside a shell.
1436
+ */
1437
+ async markSpace() {
1438
+ if (window.parent === window) return 0;
1439
+ const m = (await getHello()).markSpace;
1440
+ return typeof m === "number" && Number.isFinite(m) && m > 0 ? m : 0;
1441
+ },
1442
+ /**
1443
+ * Opens a web page (https) as a new top-level page with no opener: sign-in pages, docs, anything outside the
1444
+ * app. Call it from the tap or click itself. A popup the app's sandboxed frame opens inherits the sandbox,
1445
+ * and browsers won't show pages that send Cross-Origin-Opener-Policy there; the shell opens it instead.
1446
+ * Outside appOS it opens the page itself.
1447
+ */
1448
+ async openExternal(url) {
1449
+ if (window.parent === window) {
1450
+ window.open(url, "_blank", "noopener,noreferrer");
1451
+ return;
1452
+ }
1453
+ await ask("appos:open-external", { url });
1454
+ },
1455
+ /** Opens appOS Settings (AI & voice, permissions), e.g. after a "not-configured" error. */
1456
+ async openSettings() {
1457
+ await ask("appos:open-settings");
1458
+ },
1459
+ permissions,
1460
+ /** Language models through the shell (the "ai" capability). */
1461
+ /** Text deltas for one prompt. For the AI SDK, use apposModel() from appos-client/ai-sdk. */
1462
+ ai: { stream: aiStream },
1463
+ /** Live transcription through the shell (the "microphone" capability). */
1464
+ voice: { transcribe },
1465
+ /** Light or dark, from the shell: get(), onChange(fn), autoApply(false). Applied to <html> by default. */
1466
+ theme
1467
+ };
1468
+ export { BackendSocket, CloudError, LiveText, LiveWorker, aiCall, appos, appos as default, backend, explain, showSheet, theme };