@hollis-labs/surface-page 0.0.0-stage → 0.1.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 (47) hide show
  1. package/README.md +24 -2
  2. package/dist/chunks/chunk-ZT6LTRMY.js +220 -0
  3. package/dist/gallery.js +1016 -0
  4. package/dist/index.js +2000 -0
  5. package/dist/registry-items.json +36 -0
  6. package/dist/sdk.js +24 -0
  7. package/dist/types/ade/Overlay.d.ts +4 -0
  8. package/dist/types/ade/hub.d.ts +5 -0
  9. package/dist/types/agent/AgentPanel.d.ts +24 -0
  10. package/dist/types/agent/api.d.ts +57 -0
  11. package/dist/types/agent/index.d.ts +2 -0
  12. package/dist/types/agent/items.d.ts +25 -0
  13. package/dist/types/boot.d.ts +12 -0
  14. package/dist/types/cards/renderers.d.ts +22 -0
  15. package/dist/types/cards/store.d.ts +41 -0
  16. package/dist/types/cards/views.d.ts +9 -0
  17. package/dist/types/desk/Confirm.d.ts +2 -0
  18. package/dist/types/desk/Desktop.d.ts +6 -0
  19. package/dist/types/desk/Palette.d.ts +9 -0
  20. package/dist/types/desk/commands.d.ts +9 -0
  21. package/dist/types/desk/coreViews.d.ts +2 -0
  22. package/dist/types/desk/keys.d.ts +12 -0
  23. package/dist/types/desk/moduleApi.d.ts +3 -0
  24. package/dist/types/desk/store.d.ts +107 -0
  25. package/dist/types/gallery/Gallery.d.ts +49 -0
  26. package/dist/types/gallery/Specimen.d.ts +12 -0
  27. package/dist/types/gallery/ade.d.ts +1 -0
  28. package/dist/types/gallery/cards.d.ts +1 -0
  29. package/dist/types/gallery/chat.d.ts +1 -0
  30. package/dist/types/gallery/controls.d.ts +1 -0
  31. package/dist/types/gallery/display.d.ts +1 -0
  32. package/dist/types/gallery/genui.d.ts +1 -0
  33. package/dist/types/gallery/index.d.ts +9 -0
  34. package/dist/types/gallery/overlays.d.ts +1 -0
  35. package/dist/types/gallery/windows.d.ts +1 -0
  36. package/dist/types/genui/card.d.ts +2 -0
  37. package/dist/types/index.d.ts +15 -0
  38. package/dist/types/sdk/anchors.d.ts +8 -0
  39. package/dist/types/sdk/hooks.d.ts +11 -0
  40. package/dist/types/sdk/icon.d.ts +5 -0
  41. package/dist/types/sdk/index.d.ts +9 -0
  42. package/dist/types/sdk/marks.d.ts +10 -0
  43. package/dist/types/sdk/runtime.d.ts +40 -0
  44. package/dist/types/sdk/types.d.ts +99 -0
  45. package/package.json +70 -4
  46. package/vite.d.ts +3 -0
  47. package/vite.js +42 -0
package/dist/index.js ADDED
@@ -0,0 +1,2000 @@
1
+ import {
2
+ ApiError,
3
+ Icon,
4
+ allSettings,
5
+ anchorElement,
6
+ call,
7
+ connect,
8
+ getSetting,
9
+ isConnected,
10
+ loadSettings,
11
+ onConnection,
12
+ onEvent,
13
+ replyMark,
14
+ resolveMark,
15
+ setSetting,
16
+ useEvent,
17
+ useSetting
18
+ } from "./chunks/chunk-ZT6LTRMY.js";
19
+
20
+ // ../../web/src/boot.tsx
21
+ import { StrictMode, useEffect as useEffect9, useState as useState8 } from "react";
22
+ import { createRoot } from "react-dom/client";
23
+
24
+ // ../../web/src/cards/views.tsx
25
+ import { useCallback, useEffect as useEffect2, useState } from "react";
26
+ import { Button } from "@/components/ui/button";
27
+ import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog";
28
+ import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
29
+
30
+ // ../../web/src/cards/renderers.tsx
31
+ import {
32
+ classifyPriorResponse,
33
+ compileFormSchema,
34
+ createCardRegistry,
35
+ validateForm
36
+ } from "@hollis-labs/surface-cards";
37
+ import { Component, useMemo as useMemo2 } from "react";
38
+ import { CardApproval } from "@/components/ui/card-approval";
39
+ import { CardChoice } from "@/components/ui/card-choice";
40
+ import { CardConfirm } from "@/components/ui/card-confirm";
41
+ import { CardForm } from "@/components/ui/card-form";
42
+ import { CardMiss } from "@/components/ui/card-miss";
43
+ import { CardNotice } from "@/components/ui/card-notice";
44
+ import { CardPlan } from "@/components/ui/card-plan";
45
+ import { CardProgress } from "@/components/ui/card-progress";
46
+ import { CardPrompt } from "@/components/ui/card-prompt";
47
+
48
+ // ../../web/src/genui/card.tsx
49
+ import {
50
+ draftErrors,
51
+ GenuiController,
52
+ parseRecovery
53
+ } from "@hollis-labs/surface-genui";
54
+ import { useEffect, useMemo, useSyncExternalStore } from "react";
55
+ import { GenuiSurface } from "@/components/ui/genui-surface";
56
+ import { jsx } from "react/jsx-runtime";
57
+ async function send(method, path, body, signal) {
58
+ const res = await fetch(path, {
59
+ method,
60
+ body,
61
+ signal,
62
+ headers: body ? { "Content-Type": "application/json" } : void 0
63
+ });
64
+ const text = await res.text();
65
+ if (!res.ok) throw new Error(`${res.status} ${text}`);
66
+ return text;
67
+ }
68
+ var transport = {
69
+ submit: (call3, signal) => send("POST", "/api/genui/actions", call3, signal),
70
+ recover: async ({ actionId, functionCallId }, signal) => parseRecovery(
71
+ await send(
72
+ "GET",
73
+ `/api/genui/actions/${encodeURIComponent(actionId)}?functionCallId=${encodeURIComponent(functionCallId)}`,
74
+ void 0,
75
+ signal
76
+ ),
77
+ functionCallId
78
+ ),
79
+ // The owner pressing Confirm is the host's confirmation step here: it issues the proof.
80
+ confirm: async ({ call: call3 }, signal) => JSON.parse(await send("POST", "/api/genui/confirm", call3, signal)).proof
81
+ };
82
+ function patternOf(envelope) {
83
+ const root = envelope.data.createSurface.components[0];
84
+ switch (root.component) {
85
+ case "GenuiApproval":
86
+ return {
87
+ kind: "approval",
88
+ title: root.props.title,
89
+ summary: root.props.summary,
90
+ changes: root.props.changes,
91
+ choices: root.props.choices.map((c) => ({ label: c.label, risk: c.callFunction.args.genui_action.risk }))
92
+ };
93
+ case "GenuiForm":
94
+ return {
95
+ kind: "form",
96
+ title: root.props.title,
97
+ fields: root.props.fields,
98
+ draft: envelope.data.createSurface.dataModel.draft,
99
+ submitLabel: root.props.submit.label
100
+ };
101
+ default:
102
+ return {
103
+ kind: "list_detail",
104
+ title: root.props.title,
105
+ items: root.props.items,
106
+ selectedId: root.props.selectedId,
107
+ detail: root.props.detail
108
+ };
109
+ }
110
+ }
111
+ function actionIdOf(envelope) {
112
+ const root = envelope.data.createSurface.components[0];
113
+ if (root.component === "GenuiApproval") return root.props.choices[0]?.callFunction.args.genui_action.id;
114
+ if (root.component === "GenuiForm") return root.props.submit.callFunction.args.genui_action.id;
115
+ return void 0;
116
+ }
117
+ function GenuiCard({ card }) {
118
+ const raw = useMemo(() => JSON.stringify(card.payload?.envelope ?? null), [card.payload]);
119
+ const controller = useMemo(() => new GenuiController(raw, transport), [raw]);
120
+ useEffect(() => () => controller.dispose(), [controller]);
121
+ const snap = useSyncExternalStore(controller.subscribe, controller.getSnapshot);
122
+ const envelope = snap.envelope;
123
+ const root = envelope.data.createSurface.components[0];
124
+ const closed = !!card.status;
125
+ useEffect(() => {
126
+ const action = actionIdOf(envelope);
127
+ if (closed && action && controller.getSnapshot().phase === "ready") void controller.recover(action);
128
+ }, [closed, controller, envelope]);
129
+ const observation = snap.observation;
130
+ const status = observation?.kind === "known" ? observation.outcome.status : observation?.kind === "unknown" ? observation.status : closed && card.status !== "submitted" ? card.status : void 0;
131
+ const select = root.component === "GenuiListDetail" && !closed ? (id) => void send(
132
+ "POST",
133
+ `/api/genui/surfaces/${encodeURIComponent(envelope.id)}/select`,
134
+ JSON.stringify({ id })
135
+ ).catch(() => {
136
+ }) : void 0;
137
+ return /* @__PURE__ */ jsx(
138
+ GenuiSurface,
139
+ {
140
+ pattern: patternOf(envelope),
141
+ view: root.props.state,
142
+ phase: closed && snap.phase === "ready" ? "terminal" : snap.phase,
143
+ status,
144
+ message: snap.message,
145
+ confirmation: observation?.kind === "known" && observation.outcome.status === "needs_confirmation" ? observation.outcome.confirm.what : void 0,
146
+ canConfirm: snap.canConfirm,
147
+ validate: (draft) => root.component === "GenuiForm" ? { ...draftErrors(root.props.fields, draft) } : {},
148
+ onChoose: (index, draft) => void controller.submit(index, draft).catch(() => {
149
+ }),
150
+ onConfirm: () => void controller.confirm(),
151
+ onCheck: () => void controller.recover(),
152
+ onSelect: select
153
+ }
154
+ );
155
+ }
156
+
157
+ // ../../web/src/cards/store.ts
158
+ import {
159
+ createCardEngine
160
+ } from "@hollis-labs/surface-cards";
161
+ import { useSyncExternalStore as useSyncExternalStore2 } from "react";
162
+ var ANSWERABLE = ["confirm", "prompt", "choice", "form", "approval"];
163
+ var answer = [{ id: "answer", label: "Answer" }];
164
+ var rules = [
165
+ { id: "agent-asks", match: { source: "agent", kind: ANSWERABLE }, surface: "inline", actions: answer },
166
+ { id: "agent-shows", match: { source: "agent" }, surface: "inline" },
167
+ { id: "asks", match: { kind: ANSWERABLE }, surface: "toast", actions: answer, escalateBlocking: true },
168
+ { id: "work", match: { kind: ["progress", "plan"] }, surface: "tray" },
169
+ { id: "notices", match: {}, surface: "toast", ttlMs: 12e3 }
170
+ ];
171
+ var engine = createCardEngine({ rules, now: () => Date.now() });
172
+ var cards = /* @__PURE__ */ new Map();
173
+ var stale = /* @__PURE__ */ new Set();
174
+ var subs = /* @__PURE__ */ new Set();
175
+ var version = 0;
176
+ var emit = () => {
177
+ version++;
178
+ for (const fn of subs) fn();
179
+ };
180
+ engine.subscribe(emit);
181
+ function take(c) {
182
+ const have = cards.get(c.id);
183
+ if (have && (have.revision ?? 0) > (c.revision ?? 0)) return;
184
+ cards.set(c.id, c);
185
+ const expiresAt = c.expires_at ? Date.parse(c.expires_at) : void 0;
186
+ engine.ingest({
187
+ id: c.id,
188
+ kind: c.kind,
189
+ source: c.source,
190
+ subject: c.subject,
191
+ risk: c.risk,
192
+ blocking: c.blocking,
193
+ revision: c.revision,
194
+ expiresAt: Number.isFinite(expiresAt) ? expiresAt : void 0
195
+ });
196
+ if (c.status) engine.applyServerState(c.id, c.status, { supersededBy: c.superseded_by });
197
+ emit();
198
+ }
199
+ var started = false;
200
+ function startCards() {
201
+ if (started) return;
202
+ started = true;
203
+ onEvent("cards.changed", (ev) => take(ev.data));
204
+ void call("GET", "/api/cards").then((open) => open.forEach(take)).catch(() => {
205
+ });
206
+ window.setInterval(() => engine.dismissExpiredToasts(), 2e3);
207
+ }
208
+ async function respond(id, outcome) {
209
+ try {
210
+ take(await call("POST", `/api/cards/${encodeURIComponent(id)}/response`, outcome));
211
+ } catch (err) {
212
+ if (err instanceof ApiError && err.status === 409) {
213
+ const now = await call("GET", `/api/cards/${encodeURIComponent(id)}`).catch(() => null);
214
+ if (now) take(now);
215
+ else {
216
+ stale.add(id);
217
+ emit();
218
+ }
219
+ return;
220
+ }
221
+ throw err;
222
+ }
223
+ }
224
+ var dismissToast = (id) => engine.dismissToast(id);
225
+ var isStale = (id) => stale.has(id);
226
+ var subscribe = (fn) => {
227
+ subs.add(fn);
228
+ return () => {
229
+ subs.delete(fn);
230
+ };
231
+ };
232
+ var cache = /* @__PURE__ */ new Map();
233
+ function shown(surface) {
234
+ const hit = cache.get(surface);
235
+ if (hit && hit.at === version) return hit.list;
236
+ const list2 = engine.select(surface).flatMap((view) => {
237
+ const card = cards.get(view.id);
238
+ return card ? [{ card, view }] : [];
239
+ });
240
+ cache.set(surface, { at: version, list: list2 });
241
+ return list2;
242
+ }
243
+ function useCards(surface) {
244
+ return useSyncExternalStore2(subscribe, () => shown(surface));
245
+ }
246
+ function useCard(id) {
247
+ return useSyncExternalStore2(subscribe, () => cards.get(id));
248
+ }
249
+
250
+ // ../../web/src/cards/renderers.tsx
251
+ import { jsx as jsx2 } from "react/jsx-runtime";
252
+ var registry = createCardRegistry();
253
+ var registerCard = (kind, version3, component) => registry.register(kind, version3, component);
254
+ var str = (v) => typeof v === "string" && v !== "" ? v : void 0;
255
+ var list = (v) => Array.isArray(v) ? v : [];
256
+ function describeOutcome(card) {
257
+ const o = card.outcome;
258
+ if (o?.status !== "submitted") return void 0;
259
+ if (o.decisions?.length) return o.decisions.map((d) => d.action).join(", ");
260
+ if (o.answers?.length) {
261
+ const options = list(card.payload?.options);
262
+ const label = (v) => options.find((x) => x.id === v)?.label ?? String(v);
263
+ return o.answers.map((a) => {
264
+ const picked = Array.isArray(a.value) ? a.value.map(label).join(", ") : label(a.value);
265
+ return a.note ? `${picked}: ${a.note}` : picked;
266
+ }).join("; ");
267
+ }
268
+ if (o.data) {
269
+ const n = Object.keys(o.data).length;
270
+ return `${n} ${n === 1 ? "field" : "fields"}`;
271
+ }
272
+ return void 0;
273
+ }
274
+ var clock = new Intl.DateTimeFormat(void 0, { hour: "2-digit", minute: "2-digit" });
275
+ function answerable({ card, respond: send2 }) {
276
+ const state2 = classifyPriorResponse(card.status);
277
+ const at = card.expires_at ? Date.parse(card.expires_at) : Number.NaN;
278
+ return {
279
+ title: card.title,
280
+ state: state2.kind,
281
+ stale: isStale(card.id),
282
+ receipt: describeOutcome(card),
283
+ expires: state2.kind === "open" && Number.isFinite(at) ? `at ${clock.format(at)}` : void 0,
284
+ onRespond: send2
285
+ };
286
+ }
287
+ registerCard("info", "1", ({ card, respond: send2 }) => /* @__PURE__ */ jsx2(
288
+ CardNotice,
289
+ {
290
+ title: card.title,
291
+ body: str(card.payload?.body),
292
+ tone: str(card.payload?.tone) ?? "info",
293
+ state: classifyPriorResponse(card.status).kind,
294
+ onDismiss: () => void send2({ status: "canceled" })
295
+ }
296
+ ));
297
+ registerCard("error", "1", ({ card, respond: send2 }) => /* @__PURE__ */ jsx2(
298
+ CardNotice,
299
+ {
300
+ title: card.title,
301
+ body: str(card.payload?.body),
302
+ detail: str(card.payload?.detail),
303
+ tone: "error",
304
+ state: classifyPriorResponse(card.status).kind,
305
+ onDismiss: () => void send2({ status: "canceled" })
306
+ }
307
+ ));
308
+ registerCard("confirm", "1", (p) => /* @__PURE__ */ jsx2(
309
+ CardConfirm,
310
+ {
311
+ ...answerable(p),
312
+ body: str(p.card.payload?.body),
313
+ confirmLabel: str(p.card.payload?.confirm_label),
314
+ cancelLabel: str(p.card.payload?.cancel_label),
315
+ danger: p.card.payload?.danger === true
316
+ }
317
+ ));
318
+ registerCard("prompt", "1", (p) => /* @__PURE__ */ jsx2(
319
+ CardPrompt,
320
+ {
321
+ ...answerable(p),
322
+ question: str(p.card.payload?.question) ?? "",
323
+ body: str(p.card.payload?.body),
324
+ placeholder: str(p.card.payload?.placeholder),
325
+ multiline: p.card.payload?.multiline === true
326
+ }
327
+ ));
328
+ registerCard("choice", "1", (p) => /* @__PURE__ */ jsx2(
329
+ CardChoice,
330
+ {
331
+ ...answerable(p),
332
+ question: str(p.card.payload?.question) ?? "",
333
+ body: str(p.card.payload?.body),
334
+ options: list(p.card.payload?.options),
335
+ multiple: p.card.payload?.multiple === true,
336
+ allowOther: p.card.payload?.allow_other === true
337
+ }
338
+ ));
339
+ registerCard("form", "1", function FormRenderer(p) {
340
+ const schema = p.card.payload?.schema;
341
+ const form = useMemo2(() => compileFormSchema(schema), [schema]);
342
+ return /* @__PURE__ */ jsx2(
343
+ CardForm,
344
+ {
345
+ ...answerable(p),
346
+ body: str(p.card.payload?.body),
347
+ fields: form.fields,
348
+ issues: form.issues,
349
+ values: p.card.payload?.values,
350
+ validate: (values) => ({ ...validateForm(form.fields, values) }),
351
+ submitLabel: str(p.card.payload?.submit_label)
352
+ }
353
+ );
354
+ });
355
+ registerCard("approval", "1", (p) => /* @__PURE__ */ jsx2(
356
+ CardApproval,
357
+ {
358
+ ...answerable(p),
359
+ summary: str(p.card.payload?.summary),
360
+ risk: p.card.risk || "low",
361
+ changes: list(p.card.payload?.changes),
362
+ requestedBy: str(p.card.payload?.requested_by),
363
+ phrase: str(p.card.payload?.phrase)
364
+ }
365
+ ));
366
+ registerCard("progress", "1", ({ card }) => /* @__PURE__ */ jsx2(
367
+ CardProgress,
368
+ {
369
+ title: card.title,
370
+ label: str(card.payload?.label),
371
+ value: typeof card.payload?.value === "number" ? card.payload.value : void 0,
372
+ max: typeof card.payload?.max === "number" ? card.payload.max : void 0,
373
+ status: str(card.payload?.status) ?? (card.status ? "done" : "running"),
374
+ detail: str(card.payload?.detail)
375
+ }
376
+ ));
377
+ registerCard("plan", "1", ({ card }) => /* @__PURE__ */ jsx2(CardPlan, { title: card.title, steps: list(card.payload?.steps) }));
378
+ registerCard("genui", "1", GenuiCard);
379
+ var Boundary = class extends Component {
380
+ state = { error: null };
381
+ static getDerivedStateFromError(error) {
382
+ return { error };
383
+ }
384
+ render() {
385
+ const { card } = this.props;
386
+ if (this.state.error) {
387
+ return /* @__PURE__ */ jsx2(
388
+ CardMiss,
389
+ {
390
+ kind: card.kind,
391
+ version: card.version,
392
+ reason: "failed",
393
+ title: card.title,
394
+ detail: this.state.error.message,
395
+ payload: card.payload
396
+ }
397
+ );
398
+ }
399
+ return this.props.children;
400
+ }
401
+ };
402
+ function CardView({ card }) {
403
+ const found = registry.resolve(card.kind, card.version || "1");
404
+ if (!found.ok) {
405
+ return /* @__PURE__ */ jsx2(
406
+ CardMiss,
407
+ {
408
+ kind: card.kind,
409
+ version: card.version,
410
+ reason: found.miss.code,
411
+ title: card.title,
412
+ payload: card.payload
413
+ }
414
+ );
415
+ }
416
+ const Draw = found.component;
417
+ return /* @__PURE__ */ jsx2(Boundary, { card, children: /* @__PURE__ */ jsx2(Draw, { card, respond: (outcome) => respond(card.id, outcome) }) }, `${card.kind}@${card.version ?? "1"}`);
418
+ }
419
+
420
+ // ../../web/src/cards/views.tsx
421
+ import { Fragment, jsx as jsx3, jsxs } from "react/jsx-runtime";
422
+ var isOpen = (c) => !c.status;
423
+ function CardDock() {
424
+ useEffect2(startCards, []);
425
+ const open = useCards("inline").filter((s) => isOpen(s.card));
426
+ if (open.length === 0) return null;
427
+ return /* @__PURE__ */ jsx3(
428
+ "div",
429
+ {
430
+ "data-slot": "card-dock",
431
+ className: "flex max-h-[60%] shrink-0 flex-col gap-2 overflow-y-auto border-t p-2.5 *:shrink-0",
432
+ children: open.map((s) => /* @__PURE__ */ jsx3(CardView, { card: s.card }, s.card.id))
433
+ }
434
+ );
435
+ }
436
+ function CardHost() {
437
+ useEffect2(startCards, []);
438
+ const toasts = useCards("toast").filter((s) => isOpen(s.card) && !s.view.toastDismissed);
439
+ const blocking = useCards("modal").filter((s) => isOpen(s.card));
440
+ const [hidden, setHidden] = useState(null);
441
+ const front = blocking.find((s) => s.card.id !== hidden);
442
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
443
+ toasts.length > 0 && /* @__PURE__ */ jsx3(
444
+ "div",
445
+ {
446
+ "data-slot": "card-toasts",
447
+ className: "pointer-events-none fixed bottom-3 left-3 z-40 flex w-[min(24rem,calc(100vw-1.5rem))] flex-col gap-2",
448
+ children: toasts.slice(-4).map((s) => /* @__PURE__ */ jsxs("div", { className: "pointer-events-auto relative shadow-lg", children: [
449
+ /* @__PURE__ */ jsx3(CardView, { card: s.card }),
450
+ s.view.answerable && /* @__PURE__ */ jsx3(
451
+ Button,
452
+ {
453
+ variant: "ghost",
454
+ size: "xs",
455
+ className: "absolute -top-2 -right-2 bg-background shadow-sm",
456
+ title: "Hide for now. It stays in the Cards window.",
457
+ onClick: () => dismissToast(s.card.id),
458
+ children: "Later"
459
+ }
460
+ )
461
+ ] }, s.card.id))
462
+ }
463
+ ),
464
+ /* @__PURE__ */ jsx3(Dialog, { open: !!front, onOpenChange: (open) => !open && front && setHidden(front.card.id), children: /* @__PURE__ */ jsxs(DialogContent, { className: "max-w-md gap-0 p-0 ring-0", showCloseButton: false, children: [
465
+ /* @__PURE__ */ jsx3(DialogTitle, { className: "sr-only", children: front?.card.title ?? "A question" }),
466
+ /* @__PURE__ */ jsx3(DialogDescription, { className: "sr-only", children: "Something is waiting on your answer." }),
467
+ front && /* @__PURE__ */ jsx3(CardView, { card: front.card })
468
+ ] }) })
469
+ ] });
470
+ }
471
+ function CardsWindow(_) {
472
+ useEffect2(startCards, []);
473
+ const [all, setAll] = useState([]);
474
+ const refresh = useCallback(() => void call("GET", "/api/cards?all=1").then(setAll), []);
475
+ useEffect2(refresh, [refresh]);
476
+ useEvent("cards.changed", refresh);
477
+ const open = all.filter(isOpen);
478
+ const closed = all.filter((c) => !isOpen(c)).reverse();
479
+ return /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-3 p-4", children: [
480
+ /* @__PURE__ */ jsx3("p", { className: "text-muted-foreground", children: "Cards are what the app puts in front of you outside a window: a question, a request to approve, progress on work. The open ones wait here until they are answered." }),
481
+ all.length === 0 && /* @__PURE__ */ jsx3(Empty, { children: /* @__PURE__ */ jsxs(EmptyHeader, { children: [
482
+ /* @__PURE__ */ jsx3(EmptyTitle, { children: "No cards yet" }),
483
+ /* @__PURE__ */ jsx3(EmptyDescription, { children: "The agent and the app's modules show them as they need you." })
484
+ ] }) }),
485
+ open.map((c) => /* @__PURE__ */ jsx3(Sourced, { card: c }, c.id)),
486
+ closed.length > 0 && /* @__PURE__ */ jsx3("h3", { className: "pt-2 font-medium text-muted-foreground text-xs uppercase tracking-wider", children: "Closed" }),
487
+ closed.map((c) => /* @__PURE__ */ jsx3(Sourced, { card: c }, c.id))
488
+ ] });
489
+ }
490
+ function Sourced({ card }) {
491
+ return /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1", children: [
492
+ /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-1.5 text-muted-foreground text-xs", children: [
493
+ /* @__PURE__ */ jsx3(Icon, { name: card.source === "agent" ? "bot" : "puzzle", size: 12 }),
494
+ card.source || "app"
495
+ ] }),
496
+ /* @__PURE__ */ jsx3(CardView, { card })
497
+ ] });
498
+ }
499
+
500
+ // ../../web/src/desk/coreViews.tsx
501
+ import { useCallback as useCallback2, useEffect as useEffect3, useState as useState2 } from "react";
502
+ import { Badge } from "@/components/ui/badge";
503
+ import { Button as Button2 } from "@/components/ui/button";
504
+ import { Input } from "@/components/ui/input";
505
+ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
506
+ import { Switch } from "@/components/ui/switch";
507
+
508
+ // ../../web/src/desk/store.ts
509
+ import { useSyncExternalStore as useSyncExternalStore3 } from "react";
510
+ var manifest = null;
511
+ var state = { wins: [], focus: "", tree: { root: { type: "row" } }, layout: "tile", ratio: 0.56, rev: -1 };
512
+ var subs2 = /* @__PURE__ */ new Set();
513
+ var emit2 = () => {
514
+ for (const fn of subs2) fn();
515
+ };
516
+ onEvent("desk.changed", (ev) => {
517
+ const next = ev.data;
518
+ if (next && next.rev >= state.rev) {
519
+ state = next;
520
+ emit2();
521
+ }
522
+ });
523
+ async function loadManifest() {
524
+ manifest = await call("GET", "/api/app");
525
+ return manifest;
526
+ }
527
+ var app = () => {
528
+ if (!manifest) throw new Error("the app manifest is not loaded yet");
529
+ return manifest;
530
+ };
531
+ var viewById = (id) => manifest?.views.find((v) => v.id === id);
532
+ function viewForFile(name) {
533
+ const base2 = name.toLowerCase().split("/").pop() ?? "";
534
+ const matches2 = (pattern) => {
535
+ const p = pattern.toLowerCase();
536
+ if (p.startsWith("*")) return base2.endsWith(p.slice(1));
537
+ return base2 === p;
538
+ };
539
+ return manifest?.views.find((v) => v.opens?.some(matches2));
540
+ }
541
+ var deskState = () => state;
542
+ var subscribe2 = (fn) => {
543
+ subs2.add(fn);
544
+ return () => {
545
+ subs2.delete(fn);
546
+ };
547
+ };
548
+ function useDeskState() {
549
+ return useSyncExternalStore3(subscribe2, deskState);
550
+ }
551
+ async function act(action) {
552
+ const res = await call("POST", "/api/desk/actions", action);
553
+ return res.window;
554
+ }
555
+ var toWin = (w, focus) => ({
556
+ id: w.id,
557
+ view: w.view,
558
+ module: w.module,
559
+ title: w.title,
560
+ key: w.key,
561
+ args: w.args ?? {},
562
+ state: w.state,
563
+ focused: w.id === focus
564
+ });
565
+ var pendingReports = /* @__PURE__ */ new Map();
566
+ var reportTimer;
567
+ function flushReports() {
568
+ reportTimer = void 0;
569
+ for (const [id, st] of pendingReports) {
570
+ void act({ type: "state", id, state: st }).catch(() => {
571
+ });
572
+ }
573
+ pendingReports.clear();
574
+ }
575
+ var confirmImpl = async (q) => window.confirm(q.title);
576
+ var setConfirm = (fn) => {
577
+ confirmImpl = fn;
578
+ };
579
+ var clientRunner = () => void 0;
580
+ var setClientRunner = (fn) => {
581
+ clientRunner = fn;
582
+ };
583
+ async function runCommand(id, args) {
584
+ const local = clientRunner(id, args);
585
+ if (local !== void 0) return await local;
586
+ const res = await call("POST", `/api/commands/${encodeURIComponent(id)}`, { args: args ?? {} });
587
+ return res.result;
588
+ }
589
+ async function closeWindow(id) {
590
+ const w = state.wins.find((x) => x.id === id);
591
+ if (w?.dirty && getSetting("surface.confirm_close_dirty") === false) {
592
+ await act({ type: "close", id, force: true });
593
+ return;
594
+ }
595
+ if (w?.dirty) {
596
+ const yes = await confirmImpl({
597
+ title: `Close \u201C${w.title}\u201D?`,
598
+ message: "It holds unsaved work.",
599
+ confirmLabel: "Close anyway",
600
+ danger: true
601
+ });
602
+ if (!yes) return;
603
+ await act({ type: "close", id, force: true });
604
+ return;
605
+ }
606
+ await act({ type: "close", id });
607
+ }
608
+ function unlessGone(err) {
609
+ if (err instanceof ApiError && /no window/.test(err.message)) return void 0;
610
+ throw err;
611
+ }
612
+ var desk = {
613
+ async open(view, opts) {
614
+ const w = await act({ type: "open", view, ...opts });
615
+ if (!w) throw new Error(`could not open ${view}`);
616
+ return toWin(w, w.id);
617
+ },
618
+ async openFile(name, opts) {
619
+ const view = viewForFile(name);
620
+ return view ? desk.open(view.id, opts) : null;
621
+ },
622
+ close: closeWindow,
623
+ async focus(id) {
624
+ await act({ type: "focus", id }).catch(unlessGone);
625
+ },
626
+ async setTitle(id, title) {
627
+ await act({ type: "title", id, title }).catch(unlessGone);
628
+ },
629
+ async setArgs(id, args) {
630
+ await act({ type: "args", id, args }).catch(unlessGone);
631
+ },
632
+ report(id, st) {
633
+ pendingReports.set(id, st);
634
+ if (reportTimer === void 0) reportTimer = window.setTimeout(flushReports, 250);
635
+ },
636
+ setDirty(id, dirty) {
637
+ const w = state.wins.find((x) => x.id === id);
638
+ if (w && !!w.dirty !== dirty) void act({ type: "dirty", id, dirty }).catch(() => {
639
+ });
640
+ },
641
+ run: runCommand,
642
+ confirm: (q) => confirmImpl(q),
643
+ windows: () => state.wins.map((w) => toWin(w, state.focus))
644
+ };
645
+ var listLayouts = () => call("GET", "/api/layouts");
646
+ var saveLayout = (name, about) => call("POST", "/api/layouts", { name, about });
647
+ var loadLayout = (name) => call("POST", `/api/layouts/${encodeURIComponent(name)}/load`);
648
+ var deleteLayout = (name) => call("DELETE", `/api/layouts/${encodeURIComponent(name)}`);
649
+
650
+ // ../../web/src/desk/coreViews.tsx
651
+ import { jsx as jsx4, jsxs as jsxs2 } from "react/jsx-runtime";
652
+ function Settings(_) {
653
+ const [entries, setEntries] = useState2(allSettings());
654
+ const [error, setError] = useState2("");
655
+ const refresh = useCallback2(() => void loadSettings().then(setEntries), []);
656
+ useEffect3(refresh, [refresh]);
657
+ useEvent("config.changed", refresh);
658
+ const change = (e, value) => {
659
+ setError("");
660
+ setSetting(e.full_key, value).catch((err) => setError(`${e.title}: ${err.message}`));
661
+ };
662
+ const reset = (e) => void call("DELETE", `/api/settings/${encodeURIComponent(e.full_key)}`).then(refresh);
663
+ const scopes = [...new Set(entries.map((e) => e.scope))];
664
+ const title = (scope) => scope === "surface" ? "Desk" : app().modules.find((m) => m.id === scope)?.title ?? scope;
665
+ return /* @__PURE__ */ jsxs2("div", { className: "flex flex-col gap-3 p-4", children: [
666
+ /* @__PURE__ */ jsx4("p", { className: "text-muted-foreground", children: "Settings are kept in the app's database and take effect as you change them. Nothing restarts." }),
667
+ error && /* @__PURE__ */ jsx4("p", { className: "text-destructive", children: error }),
668
+ scopes.map((scope) => /* @__PURE__ */ jsxs2("section", { className: "flex flex-col", children: [
669
+ /* @__PURE__ */ jsx4("h3", { className: "pt-2 pb-1.5 font-medium text-muted-foreground text-xs uppercase tracking-wider", children: title(scope) }),
670
+ entries.filter((e) => e.scope === scope).map((e) => /* @__PURE__ */ jsxs2("div", { className: "flex items-center justify-between gap-4 border-t py-2.5", children: [
671
+ /* @__PURE__ */ jsxs2("span", { className: "flex min-w-0 flex-col gap-0.5", children: [
672
+ /* @__PURE__ */ jsx4("span", { className: "font-medium", children: e.title }),
673
+ e.about && /* @__PURE__ */ jsx4("span", { className: "text-muted-foreground text-xs", children: e.about }),
674
+ /* @__PURE__ */ jsx4("code", { className: "font-mono text-muted-foreground text-xs", children: e.full_key })
675
+ ] }),
676
+ /* @__PURE__ */ jsxs2("span", { className: "flex shrink-0 items-center gap-2", children: [
677
+ e.type === "bool" && /* @__PURE__ */ jsx4(Switch, { checked: !!e.value, onCheckedChange: (on) => change(e, on), "aria-label": e.title }),
678
+ e.type === "enum" && /* @__PURE__ */ jsxs2(Select, { value: String(e.value), onValueChange: (v) => change(e, v), children: [
679
+ /* @__PURE__ */ jsx4(SelectTrigger, { size: "sm", "aria-label": e.title, children: /* @__PURE__ */ jsx4(SelectValue, {}) }),
680
+ /* @__PURE__ */ jsx4(SelectContent, { children: e.options?.map((o) => /* @__PURE__ */ jsx4(SelectItem, { value: o, children: o }, o)) })
681
+ ] }),
682
+ e.type === "int" && /* @__PURE__ */ jsx4(
683
+ Input,
684
+ {
685
+ className: "w-24",
686
+ type: "number",
687
+ "aria-label": e.title,
688
+ value: Number(e.value),
689
+ onChange: (ev) => {
690
+ const n = Number.parseInt(ev.target.value, 10);
691
+ if (Number.isFinite(n)) change(e, n);
692
+ }
693
+ }
694
+ ),
695
+ e.type === "string" && /* @__PURE__ */ jsx4(
696
+ Input,
697
+ {
698
+ className: "w-64",
699
+ "aria-label": e.title,
700
+ defaultValue: String(e.value ?? ""),
701
+ onBlur: (ev) => {
702
+ if (ev.target.value !== e.value) change(e, ev.target.value);
703
+ }
704
+ },
705
+ String(e.value)
706
+ ),
707
+ e.set && /* @__PURE__ */ jsx4(Button2, { variant: "link", size: "xs", title: "Back to the default", onClick: () => reset(e), children: "reset" })
708
+ ] })
709
+ ] }, e.full_key))
710
+ ] }, scope))
711
+ ] });
712
+ }
713
+ function Layouts(_) {
714
+ const [layouts, setLayouts] = useState2([]);
715
+ const [name, setName] = useState2("");
716
+ const [error, setError] = useState2("");
717
+ const refresh = useCallback2(() => void listLayouts().then(setLayouts), []);
718
+ useEffect3(refresh, [refresh]);
719
+ useEvent("desk.layouts", refresh);
720
+ const active = deskState().active;
721
+ const save = (n) => {
722
+ setError("");
723
+ saveLayout(n).then(() => setName("")).catch((err) => setError(err.message));
724
+ };
725
+ return /* @__PURE__ */ jsxs2("div", { className: "flex flex-col gap-3 p-4", children: [
726
+ /* @__PURE__ */ jsx4("p", { className: "text-muted-foreground", children: "A layout is an arrangement you can come back to: which windows are open, how they sit, and the setup that goes with them (your mode, the agent's standing instructions, the reflexes that are on)." }),
727
+ /* @__PURE__ */ jsxs2(
728
+ "form",
729
+ {
730
+ className: "flex items-center gap-2",
731
+ onSubmit: (e) => {
732
+ e.preventDefault();
733
+ if (name.trim()) save(name.trim());
734
+ },
735
+ children: [
736
+ /* @__PURE__ */ jsx4(
737
+ Input,
738
+ {
739
+ className: "flex-1",
740
+ placeholder: "Save the desk as it is now, as\u2026",
741
+ value: name,
742
+ onChange: (e) => setName(e.target.value)
743
+ }
744
+ ),
745
+ /* @__PURE__ */ jsx4(Button2, { type: "submit", disabled: !name.trim(), children: "Save" })
746
+ ]
747
+ }
748
+ ),
749
+ error && /* @__PURE__ */ jsx4("p", { className: "text-destructive", children: error }),
750
+ layouts.length === 0 && /* @__PURE__ */ jsx4("p", { className: "text-muted-foreground text-xs", children: "No saved layouts yet." }),
751
+ layouts.map((l) => /* @__PURE__ */ jsxs2(
752
+ "div",
753
+ {
754
+ className: "flex flex-col gap-2 rounded-lg border bg-card p-3 data-[on=true]:border-ring",
755
+ "data-on": l.name === active,
756
+ children: [
757
+ /* @__PURE__ */ jsxs2("div", { className: "flex items-center gap-2", children: [
758
+ /* @__PURE__ */ jsx4(Icon, { name: "layout-dashboard", size: 15 }),
759
+ /* @__PURE__ */ jsx4("strong", { children: l.name }),
760
+ l.name === active && /* @__PURE__ */ jsx4(Badge, { variant: "secondary", children: "in use" }),
761
+ /* @__PURE__ */ jsx4("span", { className: "flex-1" }),
762
+ /* @__PURE__ */ jsx4(Button2, { variant: "outline", size: "sm", onClick: () => void loadLayout(l.name), children: "Arrange" }),
763
+ /* @__PURE__ */ jsx4(
764
+ Button2,
765
+ {
766
+ variant: "outline",
767
+ size: "sm",
768
+ title: "Replace it with the desk as it is now",
769
+ onClick: () => save(l.name),
770
+ children: "Update"
771
+ }
772
+ ),
773
+ /* @__PURE__ */ jsx4(Button2, { variant: "destructive", size: "sm", onClick: () => void deleteLayout(l.name).then(refresh), children: "Delete" })
774
+ ] }),
775
+ l.about && /* @__PURE__ */ jsx4("p", { className: "text-muted-foreground", children: l.about }),
776
+ /* @__PURE__ */ jsxs2("p", { className: "text-muted-foreground text-xs", children: [
777
+ l.mode,
778
+ " \xB7 ",
779
+ l.windows.map((w) => w.title || w.view).join(", ") || "no windows"
780
+ ] }),
781
+ l.setup && Object.keys(l.setup).length > 0 && /* @__PURE__ */ jsx4("dl", { className: "grid gap-1 text-xs [&_dd]:text-muted-foreground [&_div]:flex [&_div]:gap-2 [&_dt]:w-24 [&_dt]:shrink-0 [&_dt]:text-muted-foreground", children: Object.entries(l.setup).map(([k, v]) => /* @__PURE__ */ jsxs2("div", { children: [
782
+ /* @__PURE__ */ jsx4("dt", { children: k }),
783
+ /* @__PURE__ */ jsx4("dd", { children: typeof v === "string" ? v : JSON.stringify(v) })
784
+ ] }, k)) })
785
+ ]
786
+ },
787
+ l.name
788
+ ))
789
+ ] });
790
+ }
791
+ function Marks(_) {
792
+ const [marks, setMarks] = useState2([]);
793
+ const refresh = useCallback2(() => void call("GET", "/api/marks").then(setMarks), []);
794
+ useEffect3(refresh, [refresh]);
795
+ useEvent("marks.changed", refresh);
796
+ return /* @__PURE__ */ jsxs2("div", { className: "flex flex-col gap-3 p-4", children: [
797
+ /* @__PURE__ */ jsx4("p", { className: "text-muted-foreground", children: "Marks are notes pinned to a part of something, by you or the agent. These are the open ones, across every module." }),
798
+ marks.length === 0 && /* @__PURE__ */ jsx4("p", { className: "text-muted-foreground text-xs", children: "No open marks." }),
799
+ marks.map((m) => /* @__PURE__ */ jsx4(MarkCard, { mark: m }, m.id))
800
+ ] });
801
+ }
802
+ function MarkCard({ mark }) {
803
+ const [reply, setReply] = useState2("");
804
+ return /* @__PURE__ */ jsxs2(
805
+ "div",
806
+ {
807
+ className: "flex flex-col gap-2 rounded-lg border bg-card p-3 data-[author=agent]:border-l-2 data-[author=agent]:border-l-primary",
808
+ "data-author": mark.author,
809
+ children: [
810
+ /* @__PURE__ */ jsxs2("div", { className: "flex items-center gap-2", children: [
811
+ /* @__PURE__ */ jsx4(Icon, { name: mark.author === "agent" ? "bot" : "user", size: 14 }),
812
+ /* @__PURE__ */ jsx4("code", { className: "truncate font-mono text-muted-foreground text-xs", title: mark.ref, children: mark.ref }),
813
+ /* @__PURE__ */ jsx4("span", { className: "flex-1" }),
814
+ /* @__PURE__ */ jsx4(Button2, { variant: "link", size: "xs", onClick: () => void resolveMark(mark.id), children: "resolve" })
815
+ ] }),
816
+ mark.quote && /* @__PURE__ */ jsx4("blockquote", { className: "border-l-2 pl-2.5 text-muted-foreground italic", children: mark.quote }),
817
+ /* @__PURE__ */ jsx4("p", { children: mark.body }),
818
+ mark.replies?.map((r) => /* @__PURE__ */ jsxs2("p", { className: "flex items-center gap-1.5 pl-2 text-muted-foreground", children: [
819
+ /* @__PURE__ */ jsx4(Icon, { name: r.author === "agent" ? "bot" : "user", size: 12 }),
820
+ " ",
821
+ r.body
822
+ ] }, r.created + r.body)),
823
+ /* @__PURE__ */ jsx4(
824
+ "form",
825
+ {
826
+ className: "flex items-center gap-2",
827
+ onSubmit: (e) => {
828
+ e.preventDefault();
829
+ if (reply.trim()) void replyMark(mark.id, reply.trim()).then(() => setReply(""));
830
+ },
831
+ children: /* @__PURE__ */ jsx4(Input, { className: "flex-1", placeholder: "Reply\u2026", value: reply, onChange: (e) => setReply(e.target.value) })
832
+ }
833
+ )
834
+ ]
835
+ }
836
+ );
837
+ }
838
+ var coreWeb = {
839
+ views: {
840
+ "surface/settings": Settings,
841
+ "surface/layouts": Layouts,
842
+ "surface/marks": Marks,
843
+ "surface/cards": CardsWindow
844
+ }
845
+ };
846
+
847
+ // ../../web/src/desk/Desktop.tsx
848
+ import { Component as Component2, useCallback as useCallback4, useEffect as useEffect8, useMemo as useMemo4, useState as useState7 } from "react";
849
+ import { AppFrame } from "@/components/ui/app-frame";
850
+ import { Badge as Badge3 } from "@/components/ui/badge";
851
+ import { Button as Button4 } from "@/components/ui/button";
852
+ import {
853
+ DropdownMenu,
854
+ DropdownMenuContent,
855
+ DropdownMenuItem,
856
+ DropdownMenuShortcut,
857
+ DropdownMenuTrigger
858
+ } from "@/components/ui/dropdown-menu";
859
+ import { Empty as Empty2, EmptyDescription as EmptyDescription2, EmptyHeader as EmptyHeader2, EmptyTitle as EmptyTitle2 } from "@/components/ui/empty";
860
+ import { Kbd } from "@/components/ui/kbd";
861
+ import { WindowManager } from "@/components/ui/window-manager";
862
+
863
+ // ../../web/src/ade/Overlay.tsx
864
+ import { useEffect as useEffect4, useState as useState3, useSyncExternalStore as useSyncExternalStore4 } from "react";
865
+ import { AttentionLayer } from "@/components/ui/attention-layer";
866
+ import { GuideBar } from "@/components/ui/guide-bar";
867
+
868
+ // ../../web/src/ade/hub.ts
869
+ import { createHub } from "@hollis-labs/ade-core";
870
+ var hub = createHub();
871
+ var toAnchor = (p) => ({
872
+ surface: "desk",
873
+ target: p.anchor ? { kind: "anchor", id: `${p.window}/${p.anchor}` } : { kind: "window", id: p.window },
874
+ ...p.label ? { label: p.label } : {}
875
+ });
876
+ function rectOf(el) {
877
+ if (!el) return null;
878
+ const r = el.getBoundingClientRect();
879
+ return r.width && r.height ? { x: r.x, y: r.y, w: r.width, h: r.height } : null;
880
+ }
881
+ function windowRect(id) {
882
+ const body = document.querySelector(`[data-window="${CSS.escape(id)}"]`);
883
+ if (!rectOf(body)) return null;
884
+ const path = body?.closest(".flexlayout__tab")?.getAttribute("data-layout-path");
885
+ const set = path ? document.querySelector(`.flexlayout__tabset[data-layout-path="${CSS.escape(path.replace(/\/t\d+$/, ""))}"]`) : null;
886
+ return rectOf(set) ?? rectOf(body);
887
+ }
888
+ var viewTitle = (view) => viewById(view)?.title ?? view;
889
+ function toGuide(g) {
890
+ return {
891
+ id: g.id,
892
+ title: g.title,
893
+ surface: "desk",
894
+ steps: g.steps.map((s) => ({
895
+ id: s.id,
896
+ say: s.say,
897
+ ...s.point?.length ? { anchors: s.point.map(toAnchor) } : {},
898
+ ...s.style ? { style: s.style } : {},
899
+ ...s.hint ? { hint: s.hint } : {},
900
+ ...s.await ? {
901
+ await: {
902
+ kind: "state",
903
+ check: s.await.kind === "open" ? "window_open" : "focused",
904
+ args: {
905
+ view: s.await.view,
906
+ text: s.await.kind === "open" ? `Open ${viewTitle(s.await.view)}.` : `Bring ${viewTitle(s.await.view)} to the front.`
907
+ }
908
+ }
909
+ } : {}
910
+ }))
911
+ };
912
+ }
913
+ function applyAttention(a) {
914
+ if (!a) {
915
+ hub.clearAttention("agent", "point");
916
+ return;
917
+ }
918
+ const ttl = a.until ? a.until - Date.now() : void 0;
919
+ if (ttl !== void 0 && ttl <= 0) return;
920
+ hub.attend({
921
+ actor: "agent",
922
+ style: a.style,
923
+ anchors: a.targets.map(toAnchor),
924
+ ...a.from ? { from: toAnchor(a.from) } : {},
925
+ ...a.note ? { note: a.note } : {},
926
+ ...ttl ? { ttl } : {},
927
+ slot: "point"
928
+ });
929
+ }
930
+ function applyGuide(g, report) {
931
+ if (!g) {
932
+ if (hub.guideState()) hub.guideDo("stop", "agent");
933
+ return;
934
+ }
935
+ const guide = toGuide(g);
936
+ if (report && report.guide === g.id && report.index > 0 && (report.status === "running" || report.status === "paused")) {
937
+ const state2 = { guide, index: report.index, status: report.status, controller: "agent", history: [] };
938
+ if (hub.restoreGuide(state2)) return;
939
+ }
940
+ try {
941
+ hub.startGuide(guide, "agent");
942
+ } catch (err) {
943
+ console.warn("ade: the guide could not start", err);
944
+ }
945
+ }
946
+ var started2 = false;
947
+ function startAde() {
948
+ if (started2) return;
949
+ started2 = true;
950
+ const desk2 = hub.register({
951
+ info: { id: "desk", app: "surface", title: "Desk" },
952
+ observe: () => ({
953
+ actions: [],
954
+ checks: [
955
+ {
956
+ name: "window_open",
957
+ description: "A window of the view is open.",
958
+ args_schema: { type: "object", properties: { view: { type: "string" } } }
959
+ },
960
+ {
961
+ name: "focused",
962
+ description: "A window of the view is in front.",
963
+ args_schema: { type: "object", properties: { view: { type: "string" } } }
964
+ }
965
+ ],
966
+ targets: deskState().wins.map((w) => ({ kind: "window", id: w.id, label: w.title }))
967
+ }),
968
+ act: () => ({ outcome: "rejected", code: "invalid", reason: "The desk is changed through the desk's own tools." }),
969
+ resolve: (a) => {
970
+ const t = a.target;
971
+ if (!t) return null;
972
+ if (t.kind === "window") return windowRect(t.id);
973
+ if (t.kind === "anchor") {
974
+ const cut = t.id.indexOf("/");
975
+ return rectOf(anchorElement(t.id.slice(0, cut), t.id.slice(cut + 1)));
976
+ }
977
+ return null;
978
+ },
979
+ bounds: () => rectOf(document.querySelector("[data-slot=app-frame-content]")),
980
+ has: (t) => t.kind === "window" ? deskState().wins.some((w) => w.id === t.id) : t.kind === "anchor" && !!anchorElement(t.id.split("/")[0] ?? "", t.id.slice(t.id.indexOf("/") + 1)),
981
+ check: (name, args) => {
982
+ const s = deskState();
983
+ const view = String(args.view ?? "");
984
+ if (name === "window_open") return s.wins.some((w) => w.view === view);
985
+ if (name === "focused") return s.wins.find((w) => w.id === s.focus)?.view === view;
986
+ return false;
987
+ }
988
+ });
989
+ onEvent("desk", () => setTimeout(() => desk2.changed(), 0));
990
+ onEvent("ade.attention", (ev) => applyAttention(ev.data.attention));
991
+ onEvent("ade.guide", (ev) => applyGuide(ev.data.guide));
992
+ hub.subscribe((e) => {
993
+ if (e.type !== "guide" || !e.state) return;
994
+ const g = e.state;
995
+ void call("POST", "/api/ade/guide", {
996
+ guide: g.guide.id,
997
+ index: g.index,
998
+ step: g.guide.steps[g.index]?.id ?? "",
999
+ status: g.status,
1000
+ ...g.stalled ? { stalled: g.stalled.reason } : {}
1001
+ }).catch(() => {
1002
+ });
1003
+ });
1004
+ void call("GET", "/api/ade").then((s) => {
1005
+ applyAttention(s.attention);
1006
+ applyGuide(s.guide, s.report);
1007
+ }).catch(() => {
1008
+ });
1009
+ }
1010
+ var dismissAttention = () => {
1011
+ hub.clearAttention("agent", "point");
1012
+ void call("DELETE", "/api/ade/attention").catch(() => {
1013
+ });
1014
+ };
1015
+
1016
+ // ../../web/src/ade/Overlay.tsx
1017
+ import { jsx as jsx5 } from "react/jsx-runtime";
1018
+ var version2 = () => hub.getVersion();
1019
+ var subscribe3 = (fn) => hub.subscribe(fn);
1020
+ function useTick(on) {
1021
+ const [, set] = useState3(0);
1022
+ useEffect4(() => {
1023
+ if (!on) return;
1024
+ const again = () => set((t) => t + 1);
1025
+ const timer = window.setInterval(again, 200);
1026
+ window.addEventListener("resize", again);
1027
+ window.addEventListener("scroll", again, true);
1028
+ return () => {
1029
+ window.clearInterval(timer);
1030
+ window.removeEventListener("resize", again);
1031
+ window.removeEventListener("scroll", again, true);
1032
+ };
1033
+ }, [on]);
1034
+ }
1035
+ function marksOf(list2) {
1036
+ return list2.map((a) => ({
1037
+ id: `${a.actor}:${a.style}:${a.seq}`,
1038
+ actor: a.actor,
1039
+ style: a.style === "cursor" ? "highlight" : a.style,
1040
+ rects: a.anchors.map((x) => hub.resolve(x)).filter((r) => !!r),
1041
+ from: a.from ? hub.resolve(a.from) : null,
1042
+ note: a.note,
1043
+ by: a.actor === "agent" ? "Agent" : "You"
1044
+ }));
1045
+ }
1046
+ function AdeAttention() {
1047
+ useEffect4(startAde, []);
1048
+ useSyncExternalStore4(subscribe3, version2);
1049
+ const list2 = hub.attentionNow();
1050
+ useTick(list2.length > 0);
1051
+ const spot = list2.find((a) => a.style === "spotlight");
1052
+ const area = spot ? hub.bounds(spot.anchors[0]?.surface ?? "") : null;
1053
+ return /* @__PURE__ */ jsx5(
1054
+ AttentionLayer,
1055
+ {
1056
+ marks: marksOf(list2),
1057
+ area,
1058
+ onDismiss: (id) => id.startsWith("agent:") ? dismissAttention() : hub.clearAttention("user")
1059
+ }
1060
+ );
1061
+ }
1062
+ function AdeGuide() {
1063
+ useSyncExternalStore4(subscribe3, version2);
1064
+ const g = hub.guideState();
1065
+ if (!g || g.status === "stopped") return null;
1066
+ const step = g.guide.steps[g.index];
1067
+ if (!step) return null;
1068
+ const a = step.await;
1069
+ const wait = g.status === "done" || !a || a.kind === "ack" ? void 0 : a.kind === "state" && typeof a.args?.text === "string" ? a.args.text : "Do what the step asks.";
1070
+ return /* @__PURE__ */ jsx5("div", { className: "pointer-events-none absolute inset-x-0 bottom-4 z-40 flex justify-center px-4", children: /* @__PURE__ */ jsx5(
1071
+ GuideBar,
1072
+ {
1073
+ className: "pointer-events-auto",
1074
+ title: g.guide.title,
1075
+ say: step.say,
1076
+ step: g.index + 1,
1077
+ steps: g.guide.steps.length,
1078
+ status: g.status === "done" ? "done" : g.status,
1079
+ waiting: wait,
1080
+ hint: g.stalled ? `The guide could not do its own part: ${g.stalled.reason}` : wait ? step.hint : void 0,
1081
+ onBack: () => hub.guideDo("back"),
1082
+ onNext: () => hub.guideDo(wait ? "skip" : "next"),
1083
+ onPause: () => hub.guideDo("pause"),
1084
+ onResume: () => hub.guideDo("resume"),
1085
+ onStop: () => hub.guideDo("stop")
1086
+ }
1087
+ ) });
1088
+ }
1089
+
1090
+ // ../../web/src/agent/AgentPanel.tsx
1091
+ import {
1092
+ createChatStore,
1093
+ useChat,
1094
+ useChatBusy,
1095
+ useChatIds,
1096
+ useChatItem,
1097
+ useStickToBottom
1098
+ } from "@hollis-labs/surface-chat";
1099
+ import { Bot, Check, ChevronDown, ChevronUp, Copy } from "lucide-react";
1100
+ import { memo, useCallback as useCallback3, useEffect as useEffect5, useLayoutEffect, useMemo as useMemo3, useState as useState4 } from "react";
1101
+ import { Badge as Badge2 } from "@/components/ui/badge";
1102
+ import { Button as Button3 } from "@/components/ui/button";
1103
+ import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
1104
+ import {
1105
+ Conversation,
1106
+ ConversationContent,
1107
+ ConversationEmptyState,
1108
+ ConversationScrollButton,
1109
+ ConversationViewport
1110
+ } from "@/components/ui/conversation";
1111
+ import { Item, ItemContent, ItemDescription, ItemFooter, ItemTitle } from "@/components/ui/item";
1112
+ import { Label } from "@/components/ui/label";
1113
+ import { MessageNotice as MessageNotice2 } from "@/components/ui/message";
1114
+ import { PromptInput, PromptInputFooter, PromptInputSubmit, PromptInputTextarea } from "@/components/ui/prompt-input";
1115
+ import { Select as Select2, SelectContent as SelectContent2, SelectItem as SelectItem2, SelectTrigger as SelectTrigger2, SelectValue as SelectValue2 } from "@/components/ui/select";
1116
+
1117
+ // ../../web/src/agent/api.ts
1118
+ var base = "/api/agent";
1119
+ async function call2(method, path, body) {
1120
+ const res = await fetch(base + path, {
1121
+ method,
1122
+ credentials: "same-origin",
1123
+ headers: body === void 0 ? void 0 : { "Content-Type": "application/json" },
1124
+ body: body === void 0 ? void 0 : JSON.stringify(body)
1125
+ });
1126
+ if (!res.ok) {
1127
+ let msg = res.statusText;
1128
+ try {
1129
+ msg = (await res.json()).message ?? msg;
1130
+ } catch {
1131
+ }
1132
+ throw new Error(msg);
1133
+ }
1134
+ return await res.json();
1135
+ }
1136
+ var agentApi = {
1137
+ context: () => call2("GET", "/context"),
1138
+ setup: () => call2("GET", "/setup"),
1139
+ slots: () => call2("GET", "/slots"),
1140
+ /** Pin a slot; "" lets the window in front choose again. */
1141
+ pin: (slot) => call2("POST", "/slots/pin", { slot })
1142
+ };
1143
+
1144
+ // ../../web/src/agent/items.tsx
1145
+ import { Markdown } from "@/components/ui/markdown";
1146
+ import { Message, MessageContent, MessageNotice } from "@/components/ui/message";
1147
+ import { Spinner } from "@/components/ui/spinner";
1148
+ import { Tool, ToolContent, ToolHeader, ToolInput, ToolOutput } from "@/components/ui/tool";
1149
+ import { jsx as jsx6, jsxs as jsxs3 } from "react/jsx-runtime";
1150
+ function AskedCard({ item }) {
1151
+ const input = item.input ?? {};
1152
+ let result = {};
1153
+ try {
1154
+ if (item.result) result = JSON.parse(item.result);
1155
+ } catch {
1156
+ }
1157
+ const live = useCard(result.id ?? "");
1158
+ if (item.status === "error") return /* @__PURE__ */ jsx6(ToolRow, { item });
1159
+ if (item.status === "running" || !input.kind) {
1160
+ return /* @__PURE__ */ jsxs3(MessageNotice, { className: "flex items-center gap-1.5", children: [
1161
+ /* @__PURE__ */ jsx6(Spinner, { className: "size-3" }),
1162
+ " Waiting on your answer",
1163
+ input.title ? `: ${input.title}` : ""
1164
+ ] });
1165
+ }
1166
+ const card = live ?? {
1167
+ id: result.id ?? item.id,
1168
+ kind: input.kind,
1169
+ title: input.title,
1170
+ risk: input.risk,
1171
+ payload: input.payload,
1172
+ status: result.status || "submitted",
1173
+ outcome: result.status === "submitted" ? { status: "submitted", data: result.data, answers: result.answers, decisions: result.decisions } : void 0
1174
+ };
1175
+ return /* @__PURE__ */ jsx6(CardView, { card });
1176
+ }
1177
+ function ShownCard({ item }) {
1178
+ const input = item.input ?? {};
1179
+ if (item.status === "error") return /* @__PURE__ */ jsx6(ToolRow, { item });
1180
+ const what = item.name === "card_update" ? input.end ? "Closed a card" : "Updated a card" : `Showed a ${input.kind ?? ""} card`;
1181
+ return /* @__PURE__ */ jsxs3(MessageNotice, { children: [
1182
+ what,
1183
+ input.title ? `: ${input.title}` : ""
1184
+ ] });
1185
+ }
1186
+ function GeneratedSurface({ item }) {
1187
+ const input = item.input ?? {};
1188
+ let result = {};
1189
+ try {
1190
+ if (item.result) result = JSON.parse(item.result);
1191
+ } catch {
1192
+ }
1193
+ const live = useCard(result.id ?? "");
1194
+ if (item.status === "error") return /* @__PURE__ */ jsx6(ToolRow, { item });
1195
+ const title = input.params?.title;
1196
+ if (item.status === "running") {
1197
+ return /* @__PURE__ */ jsxs3(MessageNotice, { className: "flex items-center gap-1.5", children: [
1198
+ /* @__PURE__ */ jsx6(Spinner, { className: "size-3" }),
1199
+ " Showing you",
1200
+ title ? `: ${title}` : " something"
1201
+ ] });
1202
+ }
1203
+ if (live) return /* @__PURE__ */ jsx6(CardView, { card: live });
1204
+ return /* @__PURE__ */ jsxs3(MessageNotice, { children: [
1205
+ "Showed you",
1206
+ title ? `: ${title}` : " a generated surface",
1207
+ result.status ? ` (${result.status})` : ""
1208
+ ] });
1209
+ }
1210
+ var toolCards = {
1211
+ card_ask: AskedCard,
1212
+ card_show: ShownCard,
1213
+ card_update: ShownCard,
1214
+ genui_show: GeneratedSurface
1215
+ };
1216
+ function ToolRow({ item }) {
1217
+ return /* @__PURE__ */ jsxs3(Tool, { children: [
1218
+ /* @__PURE__ */ jsx6(ToolHeader, { title: item.name, status: item.status }),
1219
+ /* @__PURE__ */ jsxs3(ToolContent, { children: [
1220
+ /* @__PURE__ */ jsx6(ToolInput, { input: item.input }),
1221
+ /* @__PURE__ */ jsx6(ToolOutput, { output: item.result, error: item.status === "error" })
1222
+ ] })
1223
+ ] });
1224
+ }
1225
+ var renderers = {
1226
+ user: ({ item }) => item.auto ? /* @__PURE__ */ jsx6(MessageNotice, { children: item.auto }) : /* @__PURE__ */ jsx6(Message, { from: "user", children: /* @__PURE__ */ jsx6(MessageContent, { children: item.text }) }),
1227
+ text: ({ item }) => item.text ? /* @__PURE__ */ jsx6(Message, { from: "assistant", children: /* @__PURE__ */ jsx6(MessageContent, { children: /* @__PURE__ */ jsx6(Markdown, { streaming: item.streaming, children: item.text }) }) }) : item.streaming ? /* @__PURE__ */ jsxs3(MessageNotice, { className: "flex items-center gap-1.5", children: [
1228
+ /* @__PURE__ */ jsx6(Spinner, { className: "size-3" }),
1229
+ " Writing\u2026"
1230
+ ] }) : null,
1231
+ tool: ({ item }) => {
1232
+ const Card2 = toolCards[item.name] ?? ToolRow;
1233
+ return /* @__PURE__ */ jsx6(Card2, { item });
1234
+ },
1235
+ notice: ({ item }) => /* @__PURE__ */ jsx6(MessageNotice, { tone: item.tone, children: item.text })
1236
+ };
1237
+ function ItemView({ item }) {
1238
+ const Draw = renderers[item.kind];
1239
+ return /* @__PURE__ */ jsx6(Draw, { item });
1240
+ }
1241
+
1242
+ // ../../web/src/agent/AgentPanel.tsx
1243
+ import { Fragment as Fragment2, jsx as jsx7, jsxs as jsxs4 } from "react/jsx-runtime";
1244
+ var shared = null;
1245
+ function agentSession() {
1246
+ if (!shared) {
1247
+ shared = createChatStore({ base: "/api/agent" });
1248
+ void shared.start();
1249
+ }
1250
+ return shared;
1251
+ }
1252
+ function useCommits(id) {
1253
+ useLayoutEffect(() => {
1254
+ if (!import.meta.env?.DEV) return;
1255
+ const w = window;
1256
+ w.__chatRenders ??= {};
1257
+ w.__chatRenders[id] = (w.__chatRenders[id] ?? 0) + 1;
1258
+ });
1259
+ }
1260
+ function AgentPanel({ title = "Agent" }) {
1261
+ const store = useMemo3(agentSession, []);
1262
+ useEvent(
1263
+ "agent.turn",
1264
+ (ev) => store.turnElsewhere(String(ev.data?.run_id ?? ""))
1265
+ );
1266
+ return /* @__PURE__ */ jsxs4("div", { className: "flex h-full min-h-0 flex-col bg-background text-foreground", children: [
1267
+ /* @__PURE__ */ jsx7(ContextStrip, { store }),
1268
+ /* @__PURE__ */ jsx7(ChatHeader, { store, title }),
1269
+ /* @__PURE__ */ jsx7(Thread, { store }),
1270
+ /* @__PURE__ */ jsx7(CardDock, {}),
1271
+ /* @__PURE__ */ jsx7(ApprovalBar, { store }),
1272
+ /* @__PURE__ */ jsx7(Composer, { store })
1273
+ ] });
1274
+ }
1275
+ function ContextStrip({ store }) {
1276
+ const [asm, setAsm] = useState4(null);
1277
+ const [setup, setSetup] = useState4(null);
1278
+ const [slots, setSlots] = useState4([]);
1279
+ const [open, setOpen] = useState4(false);
1280
+ const [err, setErr] = useState4("");
1281
+ const refresh = useCallback3(() => {
1282
+ agentApi.context().then(setAsm, (e) => setErr(e.message));
1283
+ agentApi.slots().then(setSlots, () => {
1284
+ });
1285
+ }, []);
1286
+ useEffect5(() => {
1287
+ refresh();
1288
+ agentApi.setup().then(setSetup, () => {
1289
+ });
1290
+ }, [refresh]);
1291
+ useEvent("agent.context", (ev) => setAsm(ev.data));
1292
+ useEvent("agent.note", refresh);
1293
+ useEvent("agent.turn", refresh);
1294
+ useEffect5(() => store.onRunEnd(() => refresh()), [store, refresh]);
1295
+ const pin = (name) => agentApi.pin(name).then(setAsm, (e) => setErr(e.message));
1296
+ const top = asm?.top_of_mind ?? [];
1297
+ const why = asm?.why === "pinned" ? "pinned" : asm?.focused ? `from ${asm.focused.title}` : "";
1298
+ return /* @__PURE__ */ jsxs4(
1299
+ "section",
1300
+ {
1301
+ className: "flex flex-col gap-1.5 border-b border-border px-2.5 py-2 text-xs",
1302
+ "aria-label": "What the agent has in mind",
1303
+ children: [
1304
+ /* @__PURE__ */ jsxs4("div", { className: "flex flex-wrap items-center gap-2", children: [
1305
+ /* @__PURE__ */ jsx7(Label, { htmlFor: "agent-slot", children: "Slot" }),
1306
+ /* @__PURE__ */ jsxs4(
1307
+ Select2,
1308
+ {
1309
+ value: asm?.slot ?? null,
1310
+ onValueChange: (v) => void pin(String(v ?? "")),
1311
+ items: slots.map((s) => ({ value: s.name, label: s.name })),
1312
+ children: [
1313
+ /* @__PURE__ */ jsx7(SelectTrigger2, { id: "agent-slot", size: "sm", title: asm ? `${asm.slots[0]?.about ?? ""} (${asm.why})` : "", children: /* @__PURE__ */ jsx7(SelectValue2, {}) }),
1314
+ /* @__PURE__ */ jsx7(SelectContent2, { children: slots.map((s) => /* @__PURE__ */ jsx7(SelectItem2, { value: s.name, children: s.name }, s.name)) })
1315
+ ]
1316
+ }
1317
+ ),
1318
+ /* @__PURE__ */ jsx7("span", { className: "min-w-0 flex-1 truncate text-muted-foreground", children: why }),
1319
+ asm?.why === "pinned" && /* @__PURE__ */ jsx7(Button3, { variant: "link", size: "xs", onClick: () => void pin(""), children: "unpin" }),
1320
+ /* @__PURE__ */ jsxs4(Button3, { variant: "ghost", size: "xs", "aria-expanded": open, onClick: () => setOpen(!open), children: [
1321
+ open ? /* @__PURE__ */ jsx7(ChevronUp, {}) : /* @__PURE__ */ jsx7(ChevronDown, {}),
1322
+ "context"
1323
+ ] })
1324
+ ] }),
1325
+ asm && asm.slots.length > 1 && /* @__PURE__ */ jsxs4("div", { className: "text-muted-foreground", children: [
1326
+ "also:",
1327
+ " ",
1328
+ asm.slots.slice(1).map((s) => s.name).join(", ")
1329
+ ] }),
1330
+ top.length > 0 && /* @__PURE__ */ jsx7("div", { className: "flex flex-wrap gap-1", title: "Top of mind", children: top.map((t) => /* @__PURE__ */ jsx7(Badge2, { variant: "secondary", className: "font-mono", children: t }, t)) }),
1331
+ open && asm && /* @__PURE__ */ jsx7("pre", { className: "m-0 max-h-[40vh] overflow-auto rounded-md bg-muted p-2 font-mono break-words whitespace-pre-wrap", children: asm.block }),
1332
+ setup && !setup.ready && /* @__PURE__ */ jsx7(SetupCard, { path: setup.config_path, reason: setup.reason }),
1333
+ err && /* @__PURE__ */ jsx7("div", { className: "text-destructive", children: err })
1334
+ ]
1335
+ }
1336
+ );
1337
+ }
1338
+ function ChatHeader({ store, title }) {
1339
+ const busy = useChatBusy(store);
1340
+ const model = useChat(store, (s) => s.host?.model ?? "");
1341
+ const empty = useChat(store, (s) => s.ids.length === 0);
1342
+ return /* @__PURE__ */ jsxs4("div", { className: "flex items-center gap-2 border-b border-border px-2.5 py-1.5", children: [
1343
+ /* @__PURE__ */ jsx7("span", { className: "text-sm font-semibold", children: title }),
1344
+ /* @__PURE__ */ jsx7("span", { className: "min-w-0 flex-1 truncate text-xs text-muted-foreground", children: busy ? "working\u2026" : model }),
1345
+ /* @__PURE__ */ jsx7(Button3, { variant: "ghost", size: "xs", disabled: busy || empty, onClick: () => void store.newThread(), children: "New" })
1346
+ ] });
1347
+ }
1348
+ var Thread = memo(function Thread2({ store }) {
1349
+ const ids = useChatIds(store);
1350
+ const off = useChat(store, (s) => s.loaded && s.host !== null && (!s.host.available || !s.host.ready));
1351
+ const error = useChat(store, (s) => s.error);
1352
+ const { viewportRef, contentRef, atBottom, scrollToBottom } = useStickToBottom();
1353
+ useCommits("thread");
1354
+ return /* @__PURE__ */ jsxs4(Conversation, { children: [
1355
+ /* @__PURE__ */ jsx7(ConversationViewport, { ref: viewportRef, children: /* @__PURE__ */ jsxs4(ConversationContent, { ref: contentRef, children: [
1356
+ off && /* @__PURE__ */ jsx7(MessageNotice2, { children: "No model is connected. The desk still works by hand." }),
1357
+ !off && ids.length === 0 && /* @__PURE__ */ jsx7(
1358
+ ConversationEmptyState,
1359
+ {
1360
+ icon: /* @__PURE__ */ jsx7(Bot, {}),
1361
+ title: "Ask the agent",
1362
+ description: "It sees the window in front and can work the desk for you."
1363
+ }
1364
+ ),
1365
+ ids.map((id) => /* @__PURE__ */ jsx7(Row, { store, id }, id)),
1366
+ error && /* @__PURE__ */ jsx7(MessageNotice2, { tone: "error", children: error })
1367
+ ] }) }),
1368
+ !atBottom && /* @__PURE__ */ jsx7(ConversationScrollButton, { onClick: scrollToBottom })
1369
+ ] });
1370
+ });
1371
+ var Row = memo(function Row2({ store, id }) {
1372
+ const item = useChatItem(store, id);
1373
+ useCommits(`row:${id}`);
1374
+ return item ? /* @__PURE__ */ jsx7(ItemView, { item }) : null;
1375
+ });
1376
+ function ApprovalBar({ store }) {
1377
+ const q = useChat(store, (s) => s.approval);
1378
+ if (!q) return null;
1379
+ const input = q.input === void 0 ? "" : JSON.stringify(q.input);
1380
+ return /* @__PURE__ */ jsx7("div", { role: "alertdialog", "aria-label": "Permission", className: "border-t border-border p-2.5", children: /* @__PURE__ */ jsxs4(Item, { variant: "outline", size: "sm", children: [
1381
+ /* @__PURE__ */ jsxs4(ItemContent, { className: "min-w-0", children: [
1382
+ /* @__PURE__ */ jsx7(ItemTitle, { children: q.description || `Allow ${q.tool}?` }),
1383
+ !q.description && input && /* @__PURE__ */ jsx7(ItemDescription, { className: "font-mono text-xs", children: input })
1384
+ ] }),
1385
+ /* @__PURE__ */ jsxs4(ItemFooter, { className: "flex-wrap justify-start", children: [
1386
+ /* @__PURE__ */ jsx7(Button3, { size: "xs", onClick: () => void store.answer("once"), children: "Allow" }),
1387
+ q.standing && /* @__PURE__ */ jsxs4(Fragment2, { children: [
1388
+ /* @__PURE__ */ jsx7(Button3, { variant: "outline", size: "xs", onClick: () => void store.answer("session"), children: "This session" }),
1389
+ /* @__PURE__ */ jsx7(Button3, { variant: "outline", size: "xs", onClick: () => void store.answer("always"), children: "Always" })
1390
+ ] }),
1391
+ /* @__PURE__ */ jsx7(Button3, { variant: "ghost", size: "xs", onClick: () => void store.answer("deny"), children: "Don't" })
1392
+ ] })
1393
+ ] }) });
1394
+ }
1395
+ var Composer = memo(function Composer2({ store }) {
1396
+ const [draft, setDraft] = useState4("");
1397
+ const busy = useChatBusy(store);
1398
+ useCommits("composer");
1399
+ const submit = (e) => {
1400
+ e.preventDefault();
1401
+ const text = draft.trim();
1402
+ if (!text || busy) return;
1403
+ setDraft("");
1404
+ void store.send(text).then((ok) => {
1405
+ if (!ok) setDraft(text);
1406
+ });
1407
+ };
1408
+ return /* @__PURE__ */ jsx7("div", { className: "border-t border-border p-2.5", children: /* @__PURE__ */ jsxs4(PromptInput, { onSubmit: submit, children: [
1409
+ /* @__PURE__ */ jsx7(
1410
+ PromptInputTextarea,
1411
+ {
1412
+ value: draft,
1413
+ "aria-label": "Message",
1414
+ placeholder: "Ask, or /open, /layout, /run",
1415
+ onChange: (e) => setDraft(e.target.value)
1416
+ }
1417
+ ),
1418
+ /* @__PURE__ */ jsxs4(PromptInputFooter, { children: [
1419
+ /* @__PURE__ */ jsx7("span", { className: "text-xs text-muted-foreground", children: "Enter sends, Shift+Enter breaks the line" }),
1420
+ /* @__PURE__ */ jsx7(
1421
+ PromptInputSubmit,
1422
+ {
1423
+ status: busy ? "streaming" : "ready",
1424
+ onStop: store.stop,
1425
+ disabled: !busy && !draft.trim()
1426
+ }
1427
+ )
1428
+ ] })
1429
+ ] }) });
1430
+ });
1431
+ var example = (path) => `{
1432
+ "model": "your-model-name",
1433
+ "gateway_url": "https://your-gateway.example",
1434
+ "key_file": "${path.replace(/[^/]*$/, "") || "./"}agent-key"
1435
+ }`;
1436
+ function SetupCard({ path, reason }) {
1437
+ const [copied, setCopied] = useState4(false);
1438
+ const text = example(path);
1439
+ const copy = () => {
1440
+ void navigator.clipboard?.writeText(text).then(() => {
1441
+ setCopied(true);
1442
+ setTimeout(() => setCopied(false), 1500);
1443
+ });
1444
+ };
1445
+ return /* @__PURE__ */ jsxs4(Card, { size: "sm", children: [
1446
+ /* @__PURE__ */ jsxs4(CardHeader, { children: [
1447
+ /* @__PURE__ */ jsx7(CardTitle, { children: "The agent is not set up yet" }),
1448
+ reason && /* @__PURE__ */ jsx7("p", { className: "text-sm text-destructive", children: reason }),
1449
+ /* @__PURE__ */ jsxs4(CardDescription, { children: [
1450
+ "Everything else works by hand. To talk to the agent, write ",
1451
+ /* @__PURE__ */ jsx7("code", { className: "break-all", children: path }),
1452
+ ":"
1453
+ ] })
1454
+ ] }),
1455
+ /* @__PURE__ */ jsxs4(CardContent, { className: "flex flex-col gap-2 text-muted-foreground", children: [
1456
+ /* @__PURE__ */ jsx7("pre", { className: "m-0 overflow-x-auto rounded-md bg-muted p-2 font-mono text-xs text-foreground", children: text }),
1457
+ /* @__PURE__ */ jsx7("p", { children: "The gateway is any Anthropic-compatible endpoint; the key file holds its key. Restart the app after writing it." })
1458
+ ] }),
1459
+ /* @__PURE__ */ jsx7(CardFooter, { children: /* @__PURE__ */ jsxs4(Button3, { variant: "outline", size: "xs", onClick: copy, children: [
1460
+ copied ? /* @__PURE__ */ jsx7(Check, {}) : /* @__PURE__ */ jsx7(Copy, {}),
1461
+ copied ? "Copied" : "Copy the example"
1462
+ ] }) })
1463
+ ] });
1464
+ }
1465
+
1466
+ // ../../web/src/desk/Confirm.tsx
1467
+ import { useEffect as useEffect6, useState as useState5 } from "react";
1468
+ import {
1469
+ AlertDialog,
1470
+ AlertDialogAction,
1471
+ AlertDialogCancel,
1472
+ AlertDialogContent,
1473
+ AlertDialogDescription,
1474
+ AlertDialogFooter,
1475
+ AlertDialogHeader,
1476
+ AlertDialogTitle
1477
+ } from "@/components/ui/alert-dialog";
1478
+ import { jsx as jsx8, jsxs as jsxs5 } from "react/jsx-runtime";
1479
+ function ConfirmHost() {
1480
+ const [q, setQ] = useState5(null);
1481
+ useEffect6(() => {
1482
+ setConfirm((question) => new Promise((resolve) => setQ({ ...question, resolve })));
1483
+ }, []);
1484
+ const answer2 = (yes) => {
1485
+ q?.resolve(yes);
1486
+ setQ(null);
1487
+ };
1488
+ return /* @__PURE__ */ jsx8(
1489
+ AlertDialog,
1490
+ {
1491
+ open: !!q,
1492
+ onOpenChange: (open) => {
1493
+ if (!open) answer2(false);
1494
+ },
1495
+ children: /* @__PURE__ */ jsxs5(AlertDialogContent, { size: "sm", children: [
1496
+ /* @__PURE__ */ jsxs5(AlertDialogHeader, { children: [
1497
+ /* @__PURE__ */ jsx8(AlertDialogTitle, { children: q?.title }),
1498
+ q?.message && /* @__PURE__ */ jsx8(AlertDialogDescription, { children: q.message })
1499
+ ] }),
1500
+ /* @__PURE__ */ jsxs5(AlertDialogFooter, { children: [
1501
+ /* @__PURE__ */ jsx8(AlertDialogCancel, { children: "Cancel" }),
1502
+ /* @__PURE__ */ jsx8(AlertDialogAction, { variant: q?.danger ? "destructive" : "default", onClick: () => answer2(true), children: q?.confirmLabel ?? "OK" })
1503
+ ] })
1504
+ ] })
1505
+ }
1506
+ );
1507
+ }
1508
+
1509
+ // ../../web/src/desk/commands.ts
1510
+ var clientCommands = [
1511
+ {
1512
+ id: "palette.toggle",
1513
+ title: "Command palette",
1514
+ section: "System",
1515
+ keys: "cmd+k",
1516
+ hidden: true,
1517
+ module: "surface",
1518
+ server: false
1519
+ },
1520
+ {
1521
+ id: "agent.toggle",
1522
+ title: "Show or hide the agent",
1523
+ section: "Agent",
1524
+ keys: "cmd+j",
1525
+ keywords: "assistant panel chat",
1526
+ module: "surface",
1527
+ server: false
1528
+ },
1529
+ { id: "agent.ask", title: "Ask the agent", section: "Agent", hidden: true, module: "surface", server: false },
1530
+ { id: "menu.toggle", title: "Apps menu", section: "System", hidden: true, module: "surface", server: false }
1531
+ ];
1532
+ function runClient(id, ui, args) {
1533
+ switch (id) {
1534
+ case "palette.toggle":
1535
+ ui.togglePalette();
1536
+ return Promise.resolve(null);
1537
+ case "agent.toggle":
1538
+ ui.toggleAgent(typeof args?.open === "boolean" ? args.open : void 0);
1539
+ return Promise.resolve(null);
1540
+ case "agent.ask": {
1541
+ const text = typeof args?.text === "string" ? args.text.trim() : "";
1542
+ if (!text) return Promise.resolve(false);
1543
+ ui.toggleAgent(true);
1544
+ return agentSession().send(text);
1545
+ }
1546
+ case "menu.toggle":
1547
+ ui.toggleMenu();
1548
+ return Promise.resolve(null);
1549
+ }
1550
+ return void 0;
1551
+ }
1552
+
1553
+ // ../../web/src/desk/keys.ts
1554
+ var ALIASES = {
1555
+ return: "enter",
1556
+ esc: "escape",
1557
+ space: " ",
1558
+ left: "arrowleft",
1559
+ right: "arrowright",
1560
+ up: "arrowup",
1561
+ down: "arrowdown"
1562
+ };
1563
+ function parseKeys(keys) {
1564
+ const parts = keys.toLowerCase().split("+").map((p) => p.trim()).filter(Boolean);
1565
+ if (!parts.length) return null;
1566
+ const key = parts[parts.length - 1];
1567
+ const mods = new Set(parts.slice(0, -1));
1568
+ return {
1569
+ key: ALIASES[key] ?? key,
1570
+ ctrl: mods.has("ctrl") || mods.has("control"),
1571
+ alt: mods.has("alt") || mods.has("option"),
1572
+ shift: mods.has("shift"),
1573
+ meta: mods.has("cmd") || mods.has("meta") || mods.has("super")
1574
+ };
1575
+ }
1576
+ function matches(c, e) {
1577
+ if (e.ctrlKey !== c.ctrl || e.altKey !== c.alt || e.shiftKey !== c.shift || e.metaKey !== c.meta) return false;
1578
+ const key = e.key.toLowerCase();
1579
+ if (key === c.key) return true;
1580
+ const code = e.code.toLowerCase();
1581
+ if (code === `key${c.key}` || code === `digit${c.key}`) return true;
1582
+ if (c.key === "`" && code === "backquote") return true;
1583
+ return false;
1584
+ }
1585
+ var isMac = typeof navigator !== "undefined" && /mac/i.test(navigator.platform);
1586
+ function showKeys(keys) {
1587
+ if (!keys) return "";
1588
+ const c = parseKeys(keys);
1589
+ if (!c) return "";
1590
+ const out = [];
1591
+ if (c.ctrl) out.push(isMac ? "\u2303" : "Ctrl+");
1592
+ if (c.alt) out.push(isMac ? "\u2325" : "Alt+");
1593
+ if (c.shift) out.push(isMac ? "\u21E7" : "Shift+");
1594
+ if (c.meta) out.push(isMac ? "\u2318" : "Win+");
1595
+ const names = {
1596
+ enter: "\u21B5",
1597
+ escape: "Esc",
1598
+ arrowleft: "\u2190",
1599
+ arrowright: "\u2192",
1600
+ arrowup: "\u2191",
1601
+ arrowdown: "\u2193",
1602
+ " ": "Space"
1603
+ };
1604
+ out.push(names[c.key] ?? c.key.toUpperCase());
1605
+ return out.join("");
1606
+ }
1607
+
1608
+ // ../../web/src/desk/moduleApi.ts
1609
+ var cache2 = /* @__PURE__ */ new Map();
1610
+ function moduleApi(id) {
1611
+ const hit = cache2.get(id);
1612
+ if (hit) return hit;
1613
+ const base2 = `/api/m/${id}/`;
1614
+ const url = (path) => base2 + path.replace(/^\//, "");
1615
+ const api = {
1616
+ get: (p) => call("GET", url(p)),
1617
+ post: (p, body) => call("POST", url(p), body ?? {}),
1618
+ put: (p, body) => call("PUT", url(p), body ?? {}),
1619
+ del: (p) => call("DELETE", url(p)),
1620
+ url
1621
+ };
1622
+ cache2.set(id, api);
1623
+ return api;
1624
+ }
1625
+
1626
+ // ../../web/src/desk/Palette.tsx
1627
+ import { useEffect as useEffect7, useState as useState6 } from "react";
1628
+ import {
1629
+ Command,
1630
+ CommandDialog,
1631
+ CommandEmpty,
1632
+ CommandGroup,
1633
+ CommandInput,
1634
+ CommandItem,
1635
+ CommandList,
1636
+ CommandShortcut
1637
+ } from "@/components/ui/command";
1638
+ import { jsx as jsx9, jsxs as jsxs6 } from "react/jsx-runtime";
1639
+ function Palette({ open, onOpenChange, commands }) {
1640
+ const [layouts, setLayouts] = useState6([]);
1641
+ useEffect7(() => {
1642
+ if (!open) return;
1643
+ void listLayouts().then(setLayouts).catch(() => {
1644
+ });
1645
+ }, [open]);
1646
+ const rows = [];
1647
+ for (const c of commands) {
1648
+ if (c.hidden) continue;
1649
+ const viewId = c.id.startsWith("open.") ? c.id.slice(5) : "";
1650
+ rows.push({
1651
+ id: c.id,
1652
+ title: c.title,
1653
+ section: c.section ?? "Commands",
1654
+ icon: viewId ? app().views.find((v) => v.id === viewId)?.icon : void 0,
1655
+ hint: showKeys(c.keys),
1656
+ keywords: [c.keywords ?? "", c.section ?? "", c.id],
1657
+ run: () => runCommand(c.id)
1658
+ });
1659
+ }
1660
+ for (const l of layouts) {
1661
+ rows.push({
1662
+ id: `layout:${l.name}`,
1663
+ title: `Layout: ${l.name}`,
1664
+ section: "Layouts",
1665
+ icon: "layout-dashboard",
1666
+ keywords: ["layout", "arrange", "saved", l.about ?? ""],
1667
+ run: () => loadLayout(l.name)
1668
+ });
1669
+ }
1670
+ const sections = [...new Set(rows.map((r) => r.section))];
1671
+ const pick = (row) => {
1672
+ onOpenChange(false);
1673
+ void Promise.resolve(row.run()).catch((err) => console.warn("palette: failed", row.id, err));
1674
+ };
1675
+ return /* @__PURE__ */ jsx9(
1676
+ CommandDialog,
1677
+ {
1678
+ open,
1679
+ onOpenChange,
1680
+ title: "Command palette",
1681
+ description: "Run a command, open a window or load a layout.",
1682
+ children: /* @__PURE__ */ jsxs6(Command, { children: [
1683
+ /* @__PURE__ */ jsx9(CommandInput, { placeholder: "Run a command, open a window, load a layout\u2026" }),
1684
+ /* @__PURE__ */ jsxs6(CommandList, { children: [
1685
+ /* @__PURE__ */ jsx9(CommandEmpty, { children: "Nothing matches." }),
1686
+ sections.map((section) => /* @__PURE__ */ jsx9(CommandGroup, { heading: section, children: rows.filter((r) => r.section === section).map((r) => /* @__PURE__ */ jsxs6(CommandItem, { value: r.title, keywords: r.keywords, onSelect: () => pick(r), children: [
1687
+ /* @__PURE__ */ jsx9(Icon, { name: r.icon ?? "chevron-right" }),
1688
+ /* @__PURE__ */ jsx9("span", { children: r.title }),
1689
+ r.hint && /* @__PURE__ */ jsx9(CommandShortcut, { children: r.hint })
1690
+ ] }, r.id)) }, section))
1691
+ ] })
1692
+ ] })
1693
+ }
1694
+ );
1695
+ }
1696
+
1697
+ // ../../web/src/desk/Desktop.tsx
1698
+ import { Fragment as Fragment3, jsx as jsx10, jsxs as jsxs7 } from "react/jsx-runtime";
1699
+ function Desktop({ modules }) {
1700
+ const state2 = useDeskState();
1701
+ const manifest2 = app();
1702
+ const [palette, setPalette] = useState7(false);
1703
+ const [menu, setMenu] = useState7(false);
1704
+ const [agentOpen, setAgentOpen] = useState7(() => localStorage.getItem("surface.agent.open") !== "0");
1705
+ const [up, setUp] = useState7(isConnected());
1706
+ const gap = useSetting("surface.gap") ?? 10;
1707
+ const theme = useSetting("surface.theme") ?? "dark";
1708
+ const panelWidth = useSetting("surface.agent_panel_width") ?? 420;
1709
+ useEffect8(() => {
1710
+ setUp(isConnected());
1711
+ return onConnection(setUp);
1712
+ }, []);
1713
+ useEffect8(() => {
1714
+ const root = document.documentElement;
1715
+ root.classList.toggle("dark", theme !== "light");
1716
+ }, [theme]);
1717
+ useEffect8(() => {
1718
+ document.title = manifest2.title;
1719
+ }, [manifest2.title]);
1720
+ const toggleAgent = useCallback4((open) => {
1721
+ setAgentOpen((was) => {
1722
+ const next = open ?? !was;
1723
+ localStorage.setItem("surface.agent.open", next ? "1" : "0");
1724
+ return next;
1725
+ });
1726
+ }, []);
1727
+ const ui = useMemo4(
1728
+ () => ({
1729
+ togglePalette: (o) => setPalette((p) => o ?? !p),
1730
+ toggleAgent,
1731
+ toggleMenu: () => setMenu((m) => !m)
1732
+ }),
1733
+ [toggleAgent]
1734
+ );
1735
+ useEffect8(() => {
1736
+ setClientRunner((id, args) => runClient(id, ui, args));
1737
+ }, [ui]);
1738
+ const commands = useMemo4(() => [...clientCommands, ...manifest2.commands], [manifest2.commands]);
1739
+ useEffect8(() => {
1740
+ const chords = commands.flatMap((c) => {
1741
+ const chord = c.keys ? parseKeys(c.keys) : null;
1742
+ return chord ? [{ chord, id: c.id }] : [];
1743
+ });
1744
+ const onKey = (e) => {
1745
+ for (const { chord, id } of chords) {
1746
+ if (matches(chord, e)) {
1747
+ e.preventDefault();
1748
+ e.stopPropagation();
1749
+ void runCommand(id).catch((err) => console.warn("command failed", id, err));
1750
+ return;
1751
+ }
1752
+ }
1753
+ };
1754
+ window.addEventListener("keydown", onKey, true);
1755
+ return () => window.removeEventListener("keydown", onKey, true);
1756
+ }, [commands]);
1757
+ const windows = useMemo4(
1758
+ () => state2.wins.map((w) => ({
1759
+ id: w.id,
1760
+ title: w.title,
1761
+ dirty: w.dirty,
1762
+ icon: /* @__PURE__ */ jsx10(Icon, { name: viewById(w.view)?.icon, size: 13 })
1763
+ })),
1764
+ [state2.wins]
1765
+ );
1766
+ const arrange = useCallback4((tree, focus) => act({ type: "tree", tree, focus }), []);
1767
+ const menuViews = manifest2.views.filter((v) => v.menu);
1768
+ const bar = /* @__PURE__ */ jsxs7(Fragment3, { children: [
1769
+ /* @__PURE__ */ jsxs7("div", { className: "flex h-full min-w-0 flex-1 items-center gap-1", children: [
1770
+ /* @__PURE__ */ jsxs7(DropdownMenu, { open: menu, onOpenChange: setMenu, children: [
1771
+ /* @__PURE__ */ jsx10(
1772
+ DropdownMenuTrigger,
1773
+ {
1774
+ render: /* @__PURE__ */ jsxs7(Button4, { variant: "ghost", size: "sm", title: "Apps", children: [
1775
+ /* @__PURE__ */ jsx10(Icon, { name: "layout-grid" }),
1776
+ /* @__PURE__ */ jsx10("span", { className: "font-semibold", children: manifest2.title })
1777
+ ] })
1778
+ }
1779
+ ),
1780
+ /* @__PURE__ */ jsx10(DropdownMenuContent, { className: "min-w-56", children: menuViews.map((v) => /* @__PURE__ */ jsxs7(DropdownMenuItem, { onClick: () => void desk.open(v.id), children: [
1781
+ /* @__PURE__ */ jsx10(Icon, { name: v.icon }),
1782
+ /* @__PURE__ */ jsx10("span", { children: v.title }),
1783
+ v.module !== "surface" && /* @__PURE__ */ jsx10(DropdownMenuShortcut, { children: v.module })
1784
+ ] }, v.id)) })
1785
+ ] }),
1786
+ /* @__PURE__ */ jsx10("div", { className: "ml-1 flex min-w-0 gap-0.5 overflow-hidden", children: state2.wins.map((w) => /* @__PURE__ */ jsxs7(
1787
+ Button4,
1788
+ {
1789
+ variant: w.id === state2.focus ? "secondary" : "ghost",
1790
+ size: "sm",
1791
+ className: "min-w-0 max-w-44 shrink",
1792
+ title: w.title,
1793
+ "aria-pressed": w.id === state2.focus,
1794
+ onClick: () => void act({ type: "focus", id: w.id }),
1795
+ onAuxClick: (e) => {
1796
+ if (e.button === 1) void closeWindow(w.id);
1797
+ },
1798
+ children: [
1799
+ /* @__PURE__ */ jsx10(Icon, { name: viewById(w.view)?.icon }),
1800
+ /* @__PURE__ */ jsx10("span", { className: "truncate", children: w.dirty ? `\u25CF ${w.title}` : w.title })
1801
+ ]
1802
+ },
1803
+ w.id
1804
+ )) })
1805
+ ] }),
1806
+ /* @__PURE__ */ jsxs7("div", { className: "flex h-full shrink-0 items-center gap-1", children: [
1807
+ state2.active && /* @__PURE__ */ jsxs7(
1808
+ Button4,
1809
+ {
1810
+ variant: "ghost",
1811
+ size: "sm",
1812
+ title: "The saved layout in use",
1813
+ onClick: () => void desk.open("surface.layouts"),
1814
+ children: [
1815
+ /* @__PURE__ */ jsx10(Icon, { name: "layout-dashboard" }),
1816
+ /* @__PURE__ */ jsx10("span", { children: state2.active })
1817
+ ]
1818
+ }
1819
+ ),
1820
+ state2.mode && /* @__PURE__ */ jsx10(Badge3, { variant: "secondary", title: "Your mode", children: state2.mode }),
1821
+ /* @__PURE__ */ jsxs7(
1822
+ Button4,
1823
+ {
1824
+ variant: "ghost",
1825
+ size: "sm",
1826
+ title: "Tile every window, or float them all",
1827
+ onClick: () => void runCommand("layout.toggle"),
1828
+ children: [
1829
+ /* @__PURE__ */ jsx10(Icon, { name: state2.layout === "tile" ? "columns-2" : "picture-in-picture-2" }),
1830
+ /* @__PURE__ */ jsx10("span", { children: state2.layout })
1831
+ ]
1832
+ }
1833
+ ),
1834
+ /* @__PURE__ */ jsxs7(Button4, { variant: "ghost", size: "sm", title: "Command palette", onClick: () => setPalette(true), children: [
1835
+ /* @__PURE__ */ jsx10(Icon, { name: "search" }),
1836
+ /* @__PURE__ */ jsx10(Kbd, { children: showKeys("cmd+k") })
1837
+ ] }),
1838
+ /* @__PURE__ */ jsx10(
1839
+ Button4,
1840
+ {
1841
+ variant: agentOpen ? "secondary" : "ghost",
1842
+ size: "icon-sm",
1843
+ title: `Agent ${showKeys("cmd+j")}`,
1844
+ "aria-pressed": agentOpen,
1845
+ onClick: () => toggleAgent(),
1846
+ children: /* @__PURE__ */ jsx10(Icon, { name: "bot" })
1847
+ }
1848
+ ),
1849
+ /* @__PURE__ */ jsx10(
1850
+ "span",
1851
+ {
1852
+ className: `mx-1.5 size-2 rounded-full ${up ? "bg-success" : "bg-warning"}`,
1853
+ title: up ? "Connected" : "Reconnecting\u2026"
1854
+ }
1855
+ )
1856
+ ] })
1857
+ ] });
1858
+ return /* @__PURE__ */ jsxs7(Fragment3, { children: [
1859
+ /* @__PURE__ */ jsxs7(
1860
+ AppFrame,
1861
+ {
1862
+ className: "fixed inset-0 text-sm",
1863
+ "data-layout": state2.layout,
1864
+ bar,
1865
+ side: /* @__PURE__ */ jsx10(AgentPanel, { desk, title: "Agent" }),
1866
+ showSide: agentOpen,
1867
+ sideSize: panelWidth,
1868
+ onSideResize: keepPanelWidth,
1869
+ children: [
1870
+ /* @__PURE__ */ jsx10(
1871
+ "div",
1872
+ {
1873
+ className: "relative isolate size-full overflow-hidden bg-muted/40",
1874
+ style: { "--window-gap": `${gap}px` },
1875
+ children: /* @__PURE__ */ jsx10(
1876
+ WindowManager,
1877
+ {
1878
+ tree: state2.tree,
1879
+ windows,
1880
+ focus: state2.focus,
1881
+ onArrange: arrange,
1882
+ onClose: (id) => void closeWindow(id),
1883
+ empty: /* @__PURE__ */ jsx10(Empty2, { className: "size-full", children: /* @__PURE__ */ jsxs7(EmptyHeader2, { children: [
1884
+ /* @__PURE__ */ jsx10(EmptyTitle2, { children: manifest2.title }),
1885
+ /* @__PURE__ */ jsxs7(EmptyDescription2, { children: [
1886
+ "Open something from the menu, press ",
1887
+ /* @__PURE__ */ jsx10(Kbd, { children: showKeys("cmd+k") }),
1888
+ " for the palette, or ask the agent."
1889
+ ] })
1890
+ ] }) }),
1891
+ children: (id) => /* @__PURE__ */ jsx10(WindowBody, { id, modules })
1892
+ }
1893
+ )
1894
+ }
1895
+ ),
1896
+ /* @__PURE__ */ jsx10(AdeGuide, {})
1897
+ ]
1898
+ }
1899
+ ),
1900
+ /* @__PURE__ */ jsx10(AdeAttention, {}),
1901
+ /* @__PURE__ */ jsx10(Palette, { open: palette, onOpenChange: setPalette, commands }),
1902
+ /* @__PURE__ */ jsx10(ConfirmHost, {})
1903
+ ] });
1904
+ }
1905
+ var widthTimer;
1906
+ function keepPanelWidth(px) {
1907
+ clearTimeout(widthTimer);
1908
+ widthTimer = setTimeout(() => {
1909
+ if (px > 0 && px !== getSetting("surface.agent_panel_width"))
1910
+ void setSetting("surface.agent_panel_width", px).catch(() => {
1911
+ });
1912
+ }, 400);
1913
+ }
1914
+ function WindowBody({ id, modules }) {
1915
+ const state2 = useDeskState();
1916
+ const win = state2.wins.find((w) => w.id === id);
1917
+ const focused = state2.focus === id;
1918
+ const module = win?.module ?? "";
1919
+ const api = useMemo4(() => moduleApi(module), [module]);
1920
+ const pub = useMemo4(() => win ? toWin(win, focused ? win.id : "") : null, [win, focused]);
1921
+ if (!win || !pub) return null;
1922
+ const view = viewById(win.view);
1923
+ const Cmp = view ? modules[view.module]?.views[view.render.entry] : void 0;
1924
+ return /* @__PURE__ */ jsx10(
1925
+ "div",
1926
+ {
1927
+ className: "relative size-full min-h-0 overflow-auto data-[bare=true]:flex data-[bare=true]:flex-col data-[bare=true]:overflow-hidden",
1928
+ "data-bare": !!view?.bare,
1929
+ "data-window": win.id,
1930
+ children: /* @__PURE__ */ jsx10(Boundary2, { children: Cmp ? /* @__PURE__ */ jsx10(Cmp, { win: pub, desk, api }) : /* @__PURE__ */ jsxs7("p", { className: "p-4 text-muted-foreground", children: [
1931
+ "This app's page was built without the view \u201C",
1932
+ win.view,
1933
+ "\u201D. Rebuild the page with the module's web entry."
1934
+ ] }) }, win.view)
1935
+ }
1936
+ );
1937
+ }
1938
+ var Boundary2 = class extends Component2 {
1939
+ state = { error: null };
1940
+ static getDerivedStateFromError(error) {
1941
+ return { error };
1942
+ }
1943
+ render() {
1944
+ if (this.state.error) {
1945
+ return /* @__PURE__ */ jsxs7("div", { className: "flex flex-col items-start gap-3 p-4", children: [
1946
+ /* @__PURE__ */ jsx10("p", { children: "This window failed to draw." }),
1947
+ /* @__PURE__ */ jsx10("pre", { className: "whitespace-pre-wrap text-destructive text-xs", children: this.state.error.message }),
1948
+ /* @__PURE__ */ jsx10(Button4, { variant: "outline", size: "sm", onClick: () => this.setState({ error: null }), children: "Try again" })
1949
+ ] });
1950
+ }
1951
+ return this.props.children;
1952
+ }
1953
+ };
1954
+
1955
+ // ../../web/src/boot.tsx
1956
+ import { Fragment as Fragment4, jsx as jsx11, jsxs as jsxs8 } from "react/jsx-runtime";
1957
+ function Page({ modules, core }) {
1958
+ const [ready, setReady] = useState8(false);
1959
+ const [error, setError] = useState8("");
1960
+ useEffect9(() => {
1961
+ let live = true;
1962
+ Promise.all([loadManifest(), loadSettings()]).then(() => {
1963
+ if (!live) return;
1964
+ connect();
1965
+ setReady(true);
1966
+ void call("POST", "/api/events", { topic: "page.ready", data: {} }).catch(() => {
1967
+ });
1968
+ }).catch((err) => live && setError(err.message));
1969
+ return () => {
1970
+ live = false;
1971
+ };
1972
+ }, []);
1973
+ if (error)
1974
+ return /* @__PURE__ */ jsxs8("div", { className: "grid h-full place-items-center text-muted-foreground", children: [
1975
+ "The app's server did not answer: ",
1976
+ error
1977
+ ] });
1978
+ if (!ready) return /* @__PURE__ */ jsx11("div", { className: "grid h-full place-items-center text-muted-foreground", children: "\u2026" });
1979
+ return /* @__PURE__ */ jsxs8(Fragment4, { children: [
1980
+ /* @__PURE__ */ jsx11(Desktop, { modules: { ...modules, surface: { ...coreWeb, views: { ...coreWeb.views, ...core } } } }),
1981
+ /* @__PURE__ */ jsx11(CardHost, {})
1982
+ ] });
1983
+ }
1984
+ function mountPage(props, element = document.getElementById("root")) {
1985
+ if (!element) throw new Error("mountPage: no element to draw into (#root not found)");
1986
+ const root = createRoot(element);
1987
+ root.render(
1988
+ /* @__PURE__ */ jsx11(StrictMode, { children: /* @__PURE__ */ jsx11(Page, { ...props }) })
1989
+ );
1990
+ return root;
1991
+ }
1992
+ export {
1993
+ CardHost,
1994
+ CardsWindow,
1995
+ Desktop,
1996
+ Page,
1997
+ coreWeb,
1998
+ mountPage,
1999
+ registerCard
2000
+ };