@hollis-labs/surface-page 0.0.0-stage → 0.2.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 (57) hide show
  1. package/README.md +24 -2
  2. package/dist/chunks/chunk-ZT6LTRMY.js +220 -0
  3. package/dist/gallery.js +1730 -0
  4. package/dist/index.js +2706 -0
  5. package/dist/registry-items.json +37 -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 +61 -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/agent/session.d.ts +34 -0
  14. package/dist/types/boot.d.ts +12 -0
  15. package/dist/types/cards/renderers.d.ts +22 -0
  16. package/dist/types/cards/store.d.ts +41 -0
  17. package/dist/types/cards/views.d.ts +9 -0
  18. package/dist/types/desk/AttentionBadge.d.ts +4 -0
  19. package/dist/types/desk/Confirm.d.ts +2 -0
  20. package/dist/types/desk/ContextInspector.d.ts +2 -0
  21. package/dist/types/desk/Desktop.d.ts +6 -0
  22. package/dist/types/desk/GhostCursor.d.ts +1 -0
  23. package/dist/types/desk/Palette.d.ts +9 -0
  24. package/dist/types/desk/ThemePicker.d.ts +3 -0
  25. package/dist/types/desk/attention.d.ts +17 -0
  26. package/dist/types/desk/commands.d.ts +13 -0
  27. package/dist/types/desk/composing.d.ts +10 -0
  28. package/dist/types/desk/coreViews.d.ts +2 -0
  29. package/dist/types/desk/keys.d.ts +12 -0
  30. package/dist/types/desk/moduleApi.d.ts +3 -0
  31. package/dist/types/desk/store.d.ts +123 -0
  32. package/dist/types/gallery/Gallery.d.ts +64 -0
  33. package/dist/types/gallery/Specimen.d.ts +22 -0
  34. package/dist/types/gallery/ade.d.ts +1 -0
  35. package/dist/types/gallery/approval.d.ts +1 -0
  36. package/dist/types/gallery/cards.d.ts +1 -0
  37. package/dist/types/gallery/chat.d.ts +1 -0
  38. package/dist/types/gallery/composer.d.ts +1 -0
  39. package/dist/types/gallery/controls.d.ts +1 -0
  40. package/dist/types/gallery/display.d.ts +1 -0
  41. package/dist/types/gallery/genui.d.ts +1 -0
  42. package/dist/types/gallery/index.d.ts +9 -0
  43. package/dist/types/gallery/overlays.d.ts +1 -0
  44. package/dist/types/gallery/theme.d.ts +19 -0
  45. package/dist/types/gallery/windows.d.ts +1 -0
  46. package/dist/types/genui/card.d.ts +2 -0
  47. package/dist/types/index.d.ts +15 -0
  48. package/dist/types/sdk/anchors.d.ts +8 -0
  49. package/dist/types/sdk/hooks.d.ts +11 -0
  50. package/dist/types/sdk/icon.d.ts +5 -0
  51. package/dist/types/sdk/index.d.ts +9 -0
  52. package/dist/types/sdk/marks.d.ts +10 -0
  53. package/dist/types/sdk/runtime.d.ts +40 -0
  54. package/dist/types/sdk/types.d.ts +99 -0
  55. package/package.json +71 -4
  56. package/vite.d.ts +3 -0
  57. package/vite.js +42 -0
package/dist/index.js ADDED
@@ -0,0 +1,2706 @@
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 useEffect13, useState as useState11 } 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/desk/store.ts
31
+ import { useSyncExternalStore } from "react";
32
+ var notYetKept = (w) => !!w.opened_by && w.opened_by !== "owner" && !w.kept;
33
+ var manifest = null;
34
+ var state = { wins: [], focus: "", tree: { root: { type: "row" } }, layout: "tile", ratio: 0.56, rev: -1 };
35
+ var subs = /* @__PURE__ */ new Set();
36
+ var emit = () => {
37
+ for (const fn of subs) fn();
38
+ };
39
+ onEvent("desk.changed", (ev) => {
40
+ const next = ev.data;
41
+ if (next && next.rev >= state.rev) {
42
+ state = next;
43
+ emit();
44
+ }
45
+ });
46
+ async function loadManifest() {
47
+ manifest = await call("GET", "/api/app");
48
+ return manifest;
49
+ }
50
+ var app = () => {
51
+ if (!manifest) throw new Error("the app manifest is not loaded yet");
52
+ return manifest;
53
+ };
54
+ var viewById = (id) => manifest?.views.find((v) => v.id === id);
55
+ function viewForFile(name) {
56
+ const base2 = name.toLowerCase().split("/").pop() ?? "";
57
+ const matches2 = (pattern) => {
58
+ const p = pattern.toLowerCase();
59
+ if (p.startsWith("*")) return base2.endsWith(p.slice(1));
60
+ return base2 === p;
61
+ };
62
+ return manifest?.views.find((v) => v.opens?.some(matches2));
63
+ }
64
+ var deskState = () => state;
65
+ var subscribe = (fn) => {
66
+ subs.add(fn);
67
+ return () => {
68
+ subs.delete(fn);
69
+ };
70
+ };
71
+ function useDeskState() {
72
+ return useSyncExternalStore(subscribe, deskState);
73
+ }
74
+ async function act(action) {
75
+ const res = await call("POST", "/api/desk/actions", action);
76
+ return res.window;
77
+ }
78
+ var toWin = (w, focus) => ({
79
+ id: w.id,
80
+ view: w.view,
81
+ module: w.module,
82
+ title: w.title,
83
+ key: w.key,
84
+ args: w.args ?? {},
85
+ state: w.state,
86
+ focused: w.id === focus
87
+ });
88
+ var pendingReports = /* @__PURE__ */ new Map();
89
+ var reportTimer;
90
+ function flushReports() {
91
+ reportTimer = void 0;
92
+ for (const [id, st] of pendingReports) {
93
+ void act({ type: "state", id, state: st }).catch(() => {
94
+ });
95
+ }
96
+ pendingReports.clear();
97
+ }
98
+ var confirmImpl = async (q) => window.confirm(q.title);
99
+ var setConfirm = (fn) => {
100
+ confirmImpl = fn;
101
+ };
102
+ var clientRunner = () => void 0;
103
+ var setClientRunner = (fn) => {
104
+ clientRunner = fn;
105
+ };
106
+ async function runCommand(id, args) {
107
+ const local = clientRunner(id, args);
108
+ if (local !== void 0) return await local;
109
+ const res = await call("POST", `/api/commands/${encodeURIComponent(id)}`, { args: args ?? {} });
110
+ return res.result;
111
+ }
112
+ async function closeWindow(id) {
113
+ const w = state.wins.find((x) => x.id === id);
114
+ if (w?.dirty && getSetting("surface.confirm_close_dirty") === false) {
115
+ await act({ type: "close", id, force: true });
116
+ return;
117
+ }
118
+ if (w?.dirty) {
119
+ const yes = await confirmImpl({
120
+ title: `Close \u201C${w.title}\u201D?`,
121
+ message: "It holds unsaved work.",
122
+ confirmLabel: "Close anyway",
123
+ danger: true
124
+ });
125
+ if (!yes) return;
126
+ await act({ type: "close", id, force: true });
127
+ return;
128
+ }
129
+ await act({ type: "close", id });
130
+ }
131
+ function unlessGone(err) {
132
+ if (err instanceof ApiError && /no window/.test(err.message)) return void 0;
133
+ throw err;
134
+ }
135
+ var desk = {
136
+ async open(view, opts) {
137
+ const w = await act({ type: "open", view, ...opts });
138
+ if (!w) throw new Error(`could not open ${view}`);
139
+ return toWin(w, w.id);
140
+ },
141
+ async openFile(name, opts) {
142
+ const view = viewForFile(name);
143
+ return view ? desk.open(view.id, opts) : null;
144
+ },
145
+ close: closeWindow,
146
+ async focus(id) {
147
+ await act({ type: "focus", id }).catch(unlessGone);
148
+ },
149
+ async setTitle(id, title) {
150
+ await act({ type: "title", id, title }).catch(unlessGone);
151
+ },
152
+ async setArgs(id, args) {
153
+ await act({ type: "args", id, args }).catch(unlessGone);
154
+ },
155
+ report(id, st) {
156
+ pendingReports.set(id, st);
157
+ if (reportTimer === void 0) reportTimer = window.setTimeout(flushReports, 250);
158
+ },
159
+ setDirty(id, dirty) {
160
+ const w = state.wins.find((x) => x.id === id);
161
+ if (w && !!w.dirty !== dirty) void act({ type: "dirty", id, dirty }).catch(() => {
162
+ });
163
+ },
164
+ run: runCommand,
165
+ confirm: (q) => confirmImpl(q),
166
+ windows: () => state.wins.map((w) => toWin(w, state.focus))
167
+ };
168
+ var listLayouts = () => call("GET", "/api/layouts");
169
+ var saveLayout = (name, about) => call("POST", "/api/layouts", { name, about });
170
+ var loadLayout = (name) => call("POST", `/api/layouts/${encodeURIComponent(name)}/load`);
171
+ var deleteLayout = (name) => call("DELETE", `/api/layouts/${encodeURIComponent(name)}`);
172
+
173
+ // ../../web/src/cards/renderers.tsx
174
+ import {
175
+ classifyPriorResponse,
176
+ compileFormSchema,
177
+ createCardRegistry,
178
+ validateForm
179
+ } from "@hollis-labs/surface-cards";
180
+ import { Component, useMemo as useMemo2 } from "react";
181
+ import { CardApproval } from "@/components/ui/card-approval";
182
+ import { CardChoice } from "@/components/ui/card-choice";
183
+ import { CardConfirm } from "@/components/ui/card-confirm";
184
+ import { CardForm } from "@/components/ui/card-form";
185
+ import { CardMiss } from "@/components/ui/card-miss";
186
+ import { CardNotice } from "@/components/ui/card-notice";
187
+ import { CardPlan } from "@/components/ui/card-plan";
188
+ import { CardProgress } from "@/components/ui/card-progress";
189
+ import { CardPrompt } from "@/components/ui/card-prompt";
190
+
191
+ // ../../web/src/genui/card.tsx
192
+ import {
193
+ draftErrors,
194
+ GenuiController,
195
+ parseRecovery
196
+ } from "@hollis-labs/surface-genui";
197
+ import { useEffect, useMemo, useSyncExternalStore as useSyncExternalStore2 } from "react";
198
+ import { GenuiSurface } from "@/components/ui/genui-surface";
199
+ import { jsx } from "react/jsx-runtime";
200
+ async function send(method, path, body, signal) {
201
+ const res = await fetch(path, {
202
+ method,
203
+ body,
204
+ signal,
205
+ headers: body ? { "Content-Type": "application/json" } : void 0
206
+ });
207
+ const text = await res.text();
208
+ if (!res.ok) throw new Error(`${res.status} ${text}`);
209
+ return text;
210
+ }
211
+ var transport = {
212
+ submit: (call3, signal) => send("POST", "/api/genui/actions", call3, signal),
213
+ recover: async ({ actionId, functionCallId }, signal) => parseRecovery(
214
+ await send(
215
+ "GET",
216
+ `/api/genui/actions/${encodeURIComponent(actionId)}?functionCallId=${encodeURIComponent(functionCallId)}`,
217
+ void 0,
218
+ signal
219
+ ),
220
+ functionCallId
221
+ ),
222
+ // The owner pressing Confirm is the host's confirmation step here: it issues the proof.
223
+ confirm: async ({ call: call3 }, signal) => JSON.parse(await send("POST", "/api/genui/confirm", call3, signal)).proof
224
+ };
225
+ function patternOf(envelope) {
226
+ const root = envelope.data.createSurface.components[0];
227
+ switch (root.component) {
228
+ case "GenuiApproval":
229
+ return {
230
+ kind: "approval",
231
+ title: root.props.title,
232
+ summary: root.props.summary,
233
+ changes: root.props.changes,
234
+ choices: root.props.choices.map((c) => ({ label: c.label, risk: c.callFunction.args.genui_action.risk }))
235
+ };
236
+ case "GenuiForm":
237
+ return {
238
+ kind: "form",
239
+ title: root.props.title,
240
+ fields: root.props.fields,
241
+ draft: envelope.data.createSurface.dataModel.draft,
242
+ submitLabel: root.props.submit.label
243
+ };
244
+ default:
245
+ return {
246
+ kind: "list_detail",
247
+ title: root.props.title,
248
+ items: root.props.items,
249
+ selectedId: root.props.selectedId,
250
+ detail: root.props.detail
251
+ };
252
+ }
253
+ }
254
+ function actionIdOf(envelope) {
255
+ const root = envelope.data.createSurface.components[0];
256
+ if (root.component === "GenuiApproval") return root.props.choices[0]?.callFunction.args.genui_action.id;
257
+ if (root.component === "GenuiForm") return root.props.submit.callFunction.args.genui_action.id;
258
+ return void 0;
259
+ }
260
+ function GenuiCard({ card }) {
261
+ const raw = useMemo(() => JSON.stringify(card.payload?.envelope ?? null), [card.payload]);
262
+ const controller = useMemo(() => new GenuiController(raw, transport), [raw]);
263
+ useEffect(() => () => controller.dispose(), [controller]);
264
+ const snap = useSyncExternalStore2(controller.subscribe, controller.getSnapshot);
265
+ const envelope = snap.envelope;
266
+ const root = envelope.data.createSurface.components[0];
267
+ const closed = !!card.status;
268
+ useEffect(() => {
269
+ const action = actionIdOf(envelope);
270
+ if (closed && action && controller.getSnapshot().phase === "ready") void controller.recover(action);
271
+ }, [closed, controller, envelope]);
272
+ const observation = snap.observation;
273
+ const status = observation?.kind === "known" ? observation.outcome.status : observation?.kind === "unknown" ? observation.status : closed && card.status !== "submitted" ? card.status : void 0;
274
+ const select = root.component === "GenuiListDetail" && !closed ? (id) => void send(
275
+ "POST",
276
+ `/api/genui/surfaces/${encodeURIComponent(envelope.id)}/select`,
277
+ JSON.stringify({ id })
278
+ ).catch(() => {
279
+ }) : void 0;
280
+ return /* @__PURE__ */ jsx(
281
+ GenuiSurface,
282
+ {
283
+ pattern: patternOf(envelope),
284
+ view: root.props.state,
285
+ phase: closed && snap.phase === "ready" ? "terminal" : snap.phase,
286
+ status,
287
+ message: snap.message,
288
+ confirmation: observation?.kind === "known" && observation.outcome.status === "needs_confirmation" ? observation.outcome.confirm.what : void 0,
289
+ canConfirm: snap.canConfirm,
290
+ validate: (draft) => root.component === "GenuiForm" ? { ...draftErrors(root.props.fields, draft) } : {},
291
+ onChoose: (index, draft) => void controller.submit(index, draft).catch(() => {
292
+ }),
293
+ onConfirm: () => void controller.confirm(),
294
+ onCheck: () => void controller.recover(),
295
+ onSelect: select
296
+ }
297
+ );
298
+ }
299
+
300
+ // ../../web/src/cards/store.ts
301
+ import {
302
+ createCardEngine
303
+ } from "@hollis-labs/surface-cards";
304
+ import { useSyncExternalStore as useSyncExternalStore3 } from "react";
305
+ var ANSWERABLE = ["confirm", "prompt", "choice", "form", "approval"];
306
+ var answer = [{ id: "answer", label: "Answer" }];
307
+ var rules = [
308
+ { id: "agent-asks", match: { source: "agent", kind: ANSWERABLE }, surface: "inline", actions: answer },
309
+ { id: "agent-shows", match: { source: "agent" }, surface: "inline" },
310
+ { id: "asks", match: { kind: ANSWERABLE }, surface: "toast", actions: answer, escalateBlocking: true },
311
+ { id: "work", match: { kind: ["progress", "plan"] }, surface: "tray" },
312
+ { id: "notices", match: {}, surface: "toast", ttlMs: 12e3 }
313
+ ];
314
+ var engine = createCardEngine({ rules, now: () => Date.now() });
315
+ var cards = /* @__PURE__ */ new Map();
316
+ var stale = /* @__PURE__ */ new Set();
317
+ var subs2 = /* @__PURE__ */ new Set();
318
+ var version = 0;
319
+ var emit2 = () => {
320
+ version++;
321
+ for (const fn of subs2) fn();
322
+ };
323
+ engine.subscribe(emit2);
324
+ function take(c) {
325
+ const have = cards.get(c.id);
326
+ if (have && (have.revision ?? 0) > (c.revision ?? 0)) return;
327
+ cards.set(c.id, c);
328
+ const expiresAt = c.expires_at ? Date.parse(c.expires_at) : void 0;
329
+ engine.ingest({
330
+ id: c.id,
331
+ kind: c.kind,
332
+ source: c.source,
333
+ subject: c.subject,
334
+ risk: c.risk,
335
+ blocking: c.blocking,
336
+ revision: c.revision,
337
+ expiresAt: Number.isFinite(expiresAt) ? expiresAt : void 0
338
+ });
339
+ if (c.status) engine.applyServerState(c.id, c.status, { supersededBy: c.superseded_by });
340
+ emit2();
341
+ }
342
+ var started = false;
343
+ function startCards() {
344
+ if (started) return;
345
+ started = true;
346
+ onEvent("cards.changed", (ev) => take(ev.data));
347
+ void call("GET", "/api/cards").then((open) => open.forEach(take)).catch(() => {
348
+ });
349
+ window.setInterval(() => engine.dismissExpiredToasts(), 2e3);
350
+ }
351
+ async function respond(id, outcome) {
352
+ try {
353
+ take(await call("POST", `/api/cards/${encodeURIComponent(id)}/response`, outcome));
354
+ } catch (err) {
355
+ if (err instanceof ApiError && err.status === 409) {
356
+ const now = await call("GET", `/api/cards/${encodeURIComponent(id)}`).catch(() => null);
357
+ if (now) take(now);
358
+ else {
359
+ stale.add(id);
360
+ emit2();
361
+ }
362
+ return;
363
+ }
364
+ throw err;
365
+ }
366
+ }
367
+ var dismissToast = (id) => engine.dismissToast(id);
368
+ var isStale = (id) => stale.has(id);
369
+ var subscribe2 = (fn) => {
370
+ subs2.add(fn);
371
+ return () => {
372
+ subs2.delete(fn);
373
+ };
374
+ };
375
+ var cache = /* @__PURE__ */ new Map();
376
+ function shown(surface) {
377
+ const hit = cache.get(surface);
378
+ if (hit && hit.at === version) return hit.list;
379
+ const list2 = engine.select(surface).flatMap((view) => {
380
+ const card = cards.get(view.id);
381
+ return card ? [{ card, view }] : [];
382
+ });
383
+ cache.set(surface, { at: version, list: list2 });
384
+ return list2;
385
+ }
386
+ function useCards(surface) {
387
+ return useSyncExternalStore3(subscribe2, () => shown(surface));
388
+ }
389
+ function useCard(id) {
390
+ return useSyncExternalStore3(subscribe2, () => cards.get(id));
391
+ }
392
+
393
+ // ../../web/src/cards/renderers.tsx
394
+ import { jsx as jsx2 } from "react/jsx-runtime";
395
+ var registry = createCardRegistry();
396
+ var registerCard = (kind, version3, component) => registry.register(kind, version3, component);
397
+ var str = (v) => typeof v === "string" && v !== "" ? v : void 0;
398
+ var list = (v) => Array.isArray(v) ? v : [];
399
+ function describeOutcome(card) {
400
+ const o = card.outcome;
401
+ if (o?.status !== "submitted") return void 0;
402
+ if (o.decisions?.length) return o.decisions.map((d) => d.action).join(", ");
403
+ if (o.answers?.length) {
404
+ const options = list(card.payload?.options);
405
+ const label = (v) => options.find((x) => x.id === v)?.label ?? String(v);
406
+ return o.answers.map((a) => {
407
+ const picked = Array.isArray(a.value) ? a.value.map(label).join(", ") : label(a.value);
408
+ return a.note ? `${picked}: ${a.note}` : picked;
409
+ }).join("; ");
410
+ }
411
+ if (o.data) {
412
+ const n = Object.keys(o.data).length;
413
+ return `${n} ${n === 1 ? "field" : "fields"}`;
414
+ }
415
+ return void 0;
416
+ }
417
+ var clock = new Intl.DateTimeFormat(void 0, { hour: "2-digit", minute: "2-digit" });
418
+ function answerable({ card, respond: send2 }) {
419
+ const state3 = classifyPriorResponse(card.status);
420
+ const at = card.expires_at ? Date.parse(card.expires_at) : Number.NaN;
421
+ return {
422
+ title: card.title,
423
+ state: state3.kind,
424
+ stale: isStale(card.id),
425
+ receipt: describeOutcome(card),
426
+ expires: state3.kind === "open" && Number.isFinite(at) ? `at ${clock.format(at)}` : void 0,
427
+ onRespond: send2
428
+ };
429
+ }
430
+ registerCard("info", "1", ({ card, respond: send2 }) => /* @__PURE__ */ jsx2(
431
+ CardNotice,
432
+ {
433
+ title: card.title,
434
+ body: str(card.payload?.body),
435
+ tone: str(card.payload?.tone) ?? "info",
436
+ state: classifyPriorResponse(card.status).kind,
437
+ onDismiss: () => void send2({ status: "canceled" })
438
+ }
439
+ ));
440
+ registerCard("error", "1", ({ card, respond: send2 }) => /* @__PURE__ */ jsx2(
441
+ CardNotice,
442
+ {
443
+ title: card.title,
444
+ body: str(card.payload?.body),
445
+ detail: str(card.payload?.detail),
446
+ tone: "error",
447
+ state: classifyPriorResponse(card.status).kind,
448
+ onDismiss: () => void send2({ status: "canceled" })
449
+ }
450
+ ));
451
+ registerCard("confirm", "1", (p) => /* @__PURE__ */ jsx2(
452
+ CardConfirm,
453
+ {
454
+ ...answerable(p),
455
+ body: str(p.card.payload?.body),
456
+ confirmLabel: str(p.card.payload?.confirm_label),
457
+ cancelLabel: str(p.card.payload?.cancel_label),
458
+ danger: p.card.payload?.danger === true
459
+ }
460
+ ));
461
+ registerCard("prompt", "1", (p) => /* @__PURE__ */ jsx2(
462
+ CardPrompt,
463
+ {
464
+ ...answerable(p),
465
+ question: str(p.card.payload?.question) ?? "",
466
+ body: str(p.card.payload?.body),
467
+ placeholder: str(p.card.payload?.placeholder),
468
+ multiline: p.card.payload?.multiline === true
469
+ }
470
+ ));
471
+ registerCard("choice", "1", (p) => /* @__PURE__ */ jsx2(
472
+ CardChoice,
473
+ {
474
+ ...answerable(p),
475
+ question: str(p.card.payload?.question) ?? "",
476
+ body: str(p.card.payload?.body),
477
+ options: list(p.card.payload?.options),
478
+ multiple: p.card.payload?.multiple === true,
479
+ allowOther: p.card.payload?.allow_other === true
480
+ }
481
+ ));
482
+ registerCard("form", "1", function FormRenderer(p) {
483
+ const schema = p.card.payload?.schema;
484
+ const form = useMemo2(() => compileFormSchema(schema), [schema]);
485
+ return /* @__PURE__ */ jsx2(
486
+ CardForm,
487
+ {
488
+ ...answerable(p),
489
+ body: str(p.card.payload?.body),
490
+ fields: form.fields,
491
+ issues: form.issues,
492
+ values: p.card.payload?.values,
493
+ validate: (values) => ({ ...validateForm(form.fields, values) }),
494
+ submitLabel: str(p.card.payload?.submit_label)
495
+ }
496
+ );
497
+ });
498
+ registerCard("approval", "1", (p) => /* @__PURE__ */ jsx2(
499
+ CardApproval,
500
+ {
501
+ ...answerable(p),
502
+ summary: str(p.card.payload?.summary),
503
+ risk: p.card.risk || "low",
504
+ changes: list(p.card.payload?.changes),
505
+ requestedBy: str(p.card.payload?.requested_by),
506
+ phrase: str(p.card.payload?.phrase)
507
+ }
508
+ ));
509
+ registerCard("progress", "1", ({ card }) => /* @__PURE__ */ jsx2(
510
+ CardProgress,
511
+ {
512
+ title: card.title,
513
+ label: str(card.payload?.label),
514
+ value: typeof card.payload?.value === "number" ? card.payload.value : void 0,
515
+ max: typeof card.payload?.max === "number" ? card.payload.max : void 0,
516
+ status: str(card.payload?.status) ?? (card.status ? "done" : "running"),
517
+ detail: str(card.payload?.detail)
518
+ }
519
+ ));
520
+ registerCard("plan", "1", ({ card }) => /* @__PURE__ */ jsx2(CardPlan, { title: card.title, steps: list(card.payload?.steps) }));
521
+ registerCard("genui", "1", GenuiCard);
522
+ var Boundary = class extends Component {
523
+ state = { error: null };
524
+ static getDerivedStateFromError(error) {
525
+ return { error };
526
+ }
527
+ render() {
528
+ const { card } = this.props;
529
+ if (this.state.error) {
530
+ return /* @__PURE__ */ jsx2(
531
+ CardMiss,
532
+ {
533
+ kind: card.kind,
534
+ version: card.version,
535
+ reason: "failed",
536
+ title: card.title,
537
+ detail: this.state.error.message,
538
+ payload: card.payload
539
+ }
540
+ );
541
+ }
542
+ return this.props.children;
543
+ }
544
+ };
545
+ function CardView({ card }) {
546
+ const found = registry.resolve(card.kind, card.version || "1");
547
+ if (!found.ok) {
548
+ return /* @__PURE__ */ jsx2(
549
+ CardMiss,
550
+ {
551
+ kind: card.kind,
552
+ version: card.version,
553
+ reason: found.miss.code,
554
+ title: card.title,
555
+ payload: card.payload
556
+ }
557
+ );
558
+ }
559
+ const Draw = found.component;
560
+ return /* @__PURE__ */ jsx2(Boundary, { card, children: /* @__PURE__ */ jsx2(Draw, { card, respond: (outcome) => respond(card.id, outcome) }) }, `${card.kind}@${card.version ?? "1"}`);
561
+ }
562
+
563
+ // ../../web/src/cards/views.tsx
564
+ import { Fragment, jsx as jsx3, jsxs } from "react/jsx-runtime";
565
+ var isOpen = (c) => !c.status;
566
+ function CardDock() {
567
+ useEffect2(startCards, []);
568
+ const open = useCards("inline").filter((s) => isOpen(s.card));
569
+ if (open.length === 0) return null;
570
+ return /* @__PURE__ */ jsx3(
571
+ "div",
572
+ {
573
+ "data-slot": "card-dock",
574
+ className: "flex max-h-[60%] shrink-0 flex-col gap-2 overflow-y-auto border-t p-2.5 *:shrink-0",
575
+ children: open.map((s) => /* @__PURE__ */ jsx3(CardView, { card: s.card }, s.card.id))
576
+ }
577
+ );
578
+ }
579
+ function CardHost() {
580
+ useEffect2(startCards, []);
581
+ const desk2 = useDeskState();
582
+ const shown2 = desk2.wins.find((w) => w.id === desk2.focus);
583
+ const inFront = shown2?.key ? `${shown2.module}:${shown2.key}` : "";
584
+ const toasts = useCards("toast").filter(
585
+ (s) => isOpen(s.card) && !s.view.toastDismissed && (s.view.answerable || !inFront || s.card.subject !== inFront)
586
+ );
587
+ const blocking = useCards("modal").filter((s) => isOpen(s.card));
588
+ const [hidden, setHidden] = useState(null);
589
+ const front = blocking.find((s) => s.card.id !== hidden);
590
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
591
+ toasts.length > 0 && /* @__PURE__ */ jsx3(
592
+ "div",
593
+ {
594
+ "data-slot": "card-toasts",
595
+ className: "pointer-events-none fixed bottom-3 left-3 z-40 flex w-[min(24rem,calc(100vw-1.5rem))] flex-col gap-2",
596
+ children: toasts.slice(-4).map((s) => /* @__PURE__ */ jsxs("div", { className: "pointer-events-auto relative shadow-lg", children: [
597
+ /* @__PURE__ */ jsx3(CardView, { card: s.card }),
598
+ s.view.answerable && /* @__PURE__ */ jsx3(
599
+ Button,
600
+ {
601
+ variant: "ghost",
602
+ size: "xs",
603
+ className: "absolute -top-2 -right-2 bg-background shadow-sm",
604
+ title: "Hide for now. It stays in the Cards window.",
605
+ onClick: () => dismissToast(s.card.id),
606
+ children: "Later"
607
+ }
608
+ )
609
+ ] }, s.card.id))
610
+ }
611
+ ),
612
+ /* @__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: [
613
+ /* @__PURE__ */ jsx3(DialogTitle, { className: "sr-only", children: front?.card.title ?? "A question" }),
614
+ /* @__PURE__ */ jsx3(DialogDescription, { className: "sr-only", children: "Something is waiting on your answer." }),
615
+ front && /* @__PURE__ */ jsx3(CardView, { card: front.card })
616
+ ] }) })
617
+ ] });
618
+ }
619
+ function CardsWindow(_) {
620
+ useEffect2(startCards, []);
621
+ const [all, setAll] = useState([]);
622
+ const refresh = useCallback(() => void call("GET", "/api/cards?all=1").then(setAll), []);
623
+ useEffect2(refresh, [refresh]);
624
+ useEvent("cards.changed", refresh);
625
+ const open = all.filter(isOpen);
626
+ const closed = all.filter((c) => !isOpen(c)).reverse();
627
+ return /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-3 p-4", children: [
628
+ /* @__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." }),
629
+ all.length === 0 && /* @__PURE__ */ jsx3(Empty, { children: /* @__PURE__ */ jsxs(EmptyHeader, { children: [
630
+ /* @__PURE__ */ jsx3(EmptyTitle, { children: "No cards yet" }),
631
+ /* @__PURE__ */ jsx3(EmptyDescription, { children: "The agent and the app's modules show them as they need you." })
632
+ ] }) }),
633
+ open.map((c) => /* @__PURE__ */ jsx3(Sourced, { card: c }, c.id)),
634
+ closed.length > 0 && /* @__PURE__ */ jsx3("h3", { className: "pt-2 font-medium text-muted-foreground text-xs uppercase tracking-wider", children: "Closed" }),
635
+ closed.map((c) => /* @__PURE__ */ jsx3(Sourced, { card: c }, c.id))
636
+ ] });
637
+ }
638
+ function Sourced({ card }) {
639
+ return /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1", children: [
640
+ /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-1.5 text-muted-foreground text-xs", children: [
641
+ /* @__PURE__ */ jsx3(Icon, { name: card.source === "agent" ? "bot" : "puzzle", size: 12 }),
642
+ card.source || "app"
643
+ ] }),
644
+ /* @__PURE__ */ jsx3(CardView, { card })
645
+ ] });
646
+ }
647
+
648
+ // ../../web/src/desk/coreViews.tsx
649
+ import { useCallback as useCallback3, useEffect as useEffect4, useState as useState3 } from "react";
650
+ import { Badge as Badge2 } from "@/components/ui/badge";
651
+ import { Button as Button3 } from "@/components/ui/button";
652
+ import { Input } from "@/components/ui/input";
653
+ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
654
+ import { Switch as Switch2 } from "@/components/ui/switch";
655
+
656
+ // ../../web/src/desk/ContextInspector.tsx
657
+ import { useCallback as useCallback2, useEffect as useEffect3, useState as useState2 } from "react";
658
+ import { Badge } from "@/components/ui/badge";
659
+ import { Button as Button2 } from "@/components/ui/button";
660
+ import { Empty as Empty2, EmptyDescription as EmptyDescription2, EmptyHeader as EmptyHeader2, EmptyTitle as EmptyTitle2 } from "@/components/ui/empty";
661
+ import { Item, ItemContent, ItemDescription, ItemTitle } from "@/components/ui/item";
662
+ import { Switch } from "@/components/ui/switch";
663
+ import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
664
+ import { Fragment as Fragment2, jsx as jsx4, jsxs as jsxs2 } from "react/jsx-runtime";
665
+ var WHY = {
666
+ focus: "the window in front belongs to it",
667
+ kept: "it stayed from before: the window in front has no slot of its own",
668
+ pinned: "it was pinned",
669
+ mode: "your mode chose it",
670
+ default: "nothing else applied (the default)"
671
+ };
672
+ var when = (iso) => {
673
+ const d = new Date(iso);
674
+ return Number.isNaN(d.getTime()) ? iso : d.toLocaleString([], { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", second: "2-digit" });
675
+ };
676
+ var byOwner = (s) => s.actor === "owner" || s.actor === "" || s.actor === void 0;
677
+ var correction = (s) => byOwner(s) && (s.kind === "pin" || s.kind === "unpin");
678
+ function Row({ label, children }) {
679
+ return /* @__PURE__ */ jsxs2("div", { className: "grid grid-cols-[9rem_1fr] gap-3 py-1.5 text-sm", children: [
680
+ /* @__PURE__ */ jsx4("span", { className: "text-muted-foreground text-xs", children: label }),
681
+ /* @__PURE__ */ jsx4("div", { className: "flex min-w-0 flex-wrap items-center gap-1", children })
682
+ ] });
683
+ }
684
+ var chips = (list2, empty = "none") => list2 && list2.length > 0 ? list2.map((x) => /* @__PURE__ */ jsx4(Badge, { variant: "outline", className: "font-mono", children: x }, x)) : /* @__PURE__ */ jsx4("span", { className: "text-muted-foreground text-xs", children: empty });
685
+ function TurnDetail({ t }) {
686
+ const corrections = (t.signals ?? []).filter(correction);
687
+ return /* @__PURE__ */ jsxs2("div", { className: "flex flex-col gap-1 p-4", children: [
688
+ /* @__PURE__ */ jsx4("p", { className: "text-sm whitespace-pre-wrap", children: t.text }),
689
+ /* @__PURE__ */ jsxs2("span", { className: "mb-2 text-xs text-muted-foreground", children: [
690
+ when(t.at),
691
+ t.run_id ? ` \xB7 run ${t.run_id}` : ""
692
+ ] }),
693
+ /* @__PURE__ */ jsxs2(Row, { label: "In front", children: [
694
+ t.view ? /* @__PURE__ */ jsx4(Badge, { variant: "secondary", children: t.view }) : /* @__PURE__ */ jsx4("span", { className: "text-xs text-muted-foreground", children: "nothing" }),
695
+ t.mode && /* @__PURE__ */ jsxs2(Badge, { variant: "outline", children: [
696
+ "mode ",
697
+ t.mode
698
+ ] }),
699
+ t.layout && /* @__PURE__ */ jsx4(Badge, { variant: "outline", children: t.layout })
700
+ ] }),
701
+ /* @__PURE__ */ jsx4(Row, { label: "Open", children: chips(t.open_views) }),
702
+ /* @__PURE__ */ jsxs2(Row, { label: "Slot", children: [
703
+ /* @__PURE__ */ jsx4(Badge, { children: t.slot || "none" }),
704
+ /* @__PURE__ */ jsxs2("span", { className: "text-xs text-muted-foreground", children: [
705
+ "because ",
706
+ WHY[t.why ?? ""] ?? t.why ?? "?"
707
+ ] })
708
+ ] }),
709
+ /* @__PURE__ */ jsx4(Row, { label: "Slots offered", children: chips(t.slots) }),
710
+ /* @__PURE__ */ jsx4(Row, { label: "Tools to mind", children: chips(t.top_of_mind) }),
711
+ /* @__PURE__ */ jsx4(Row, { label: "Routed", children: t.routed ? /* @__PURE__ */ jsx4(Badge, { variant: "outline", children: t.routed }) : /* @__PURE__ */ jsx4("span", { className: "text-xs text-muted-foreground", children: "no rule" }) }),
712
+ /* @__PURE__ */ jsxs2(Row, { label: "Reflexes", children: [
713
+ chips(t.fired),
714
+ t.halted && /* @__PURE__ */ jsx4(Badge, { variant: "destructive", children: "halted the turn" })
715
+ ] }),
716
+ /* @__PURE__ */ jsx4(Row, { label: "Context size", children: /* @__PURE__ */ jsxs2("span", { className: "font-mono text-xs", children: [
717
+ t.block_chars.toLocaleString(),
718
+ " characters"
719
+ ] }) }),
720
+ /* @__PURE__ */ jsx4(Row, { label: "Budget cut", children: chips(t.trimmed, "nothing cut") }),
721
+ /* @__PURE__ */ jsx4(Row, { label: "What followed", children: (t.signals ?? []).length === 0 ? /* @__PURE__ */ jsx4("span", { className: "text-xs text-muted-foreground", children: "nothing in the next 15 minutes" }) : /* @__PURE__ */ jsx4("ul", { className: "flex w-full flex-col gap-1", children: (t.signals ?? []).map((s) => /* @__PURE__ */ jsxs2(
722
+ "li",
723
+ {
724
+ className: "flex flex-wrap items-center gap-1.5 text-xs",
725
+ children: [
726
+ /* @__PURE__ */ jsx4("span", { className: "text-muted-foreground", children: when(s.at) }),
727
+ /* @__PURE__ */ jsx4(Badge, { variant: correction(s) ? "secondary" : "outline", children: s.kind }),
728
+ /* @__PURE__ */ jsxs2("span", { className: "text-muted-foreground", children: [
729
+ "by ",
730
+ s.actor || "owner"
731
+ ] }),
732
+ s.detail && /* @__PURE__ */ jsx4("code", { className: "font-mono text-muted-foreground", children: JSON.stringify(s.detail) })
733
+ ]
734
+ },
735
+ `${s.at}-${s.kind}-${s.actor ?? ""}-${JSON.stringify(s.detail ?? {})}`
736
+ )) }) }),
737
+ corrections.length > 0 && /* @__PURE__ */ jsxs2("p", { className: "mt-2 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-xs", children: [
738
+ "You re-pinned the context soon after this turn (",
739
+ corrections.map((c) => c.kind).join(", "),
740
+ "): the slot the agent chose was probably not the one you meant."
741
+ ] })
742
+ ] });
743
+ }
744
+ function Now() {
745
+ const [p, setP] = useState2(null);
746
+ const [error, setError] = useState2("");
747
+ const load = useCallback2(() => {
748
+ call("GET", "/api/agent/context").then((x) => {
749
+ setP(x);
750
+ setError("");
751
+ }).catch((e) => setError(e.message));
752
+ }, []);
753
+ useEffect3(load, [load]);
754
+ useEvent("desk.changed", load);
755
+ if (error) return /* @__PURE__ */ jsx4("p", { className: "p-4 text-xs text-destructive", children: error });
756
+ if (!p) return /* @__PURE__ */ jsx4("p", { className: "p-4 text-xs text-muted-foreground", children: "Reading\u2026" });
757
+ return /* @__PURE__ */ jsxs2("div", { className: "flex flex-col gap-1 p-4", children: [
758
+ /* @__PURE__ */ jsx4("p", { className: "text-xs text-muted-foreground", children: "What a message sent now would carry. It follows the window in front." }),
759
+ /* @__PURE__ */ jsx4(Row, { label: "In front", children: p.focused?.view ? /* @__PURE__ */ jsxs2(Fragment2, { children: [
760
+ /* @__PURE__ */ jsx4(Badge, { variant: "secondary", children: p.focused.view }),
761
+ /* @__PURE__ */ jsx4("span", { className: "truncate text-xs", children: p.focused.title }),
762
+ p.focused.ref && /* @__PURE__ */ jsx4(Badge, { variant: "outline", className: "font-mono", children: p.focused.ref })
763
+ ] }) : /* @__PURE__ */ jsx4("span", { className: "text-xs text-muted-foreground", children: "nothing" }) }),
764
+ /* @__PURE__ */ jsxs2(Row, { label: "Slot", children: [
765
+ /* @__PURE__ */ jsx4(Badge, { children: p.slot || "none" }),
766
+ /* @__PURE__ */ jsxs2("span", { className: "text-xs text-muted-foreground", children: [
767
+ "because ",
768
+ WHY[p.why] ?? p.why
769
+ ] })
770
+ ] }),
771
+ /* @__PURE__ */ jsx4(Row, { label: "Slots offered", children: chips(p.slots.map((s) => s.name)) }),
772
+ /* @__PURE__ */ jsx4(Row, { label: "Tools to mind", children: chips(p.top_of_mind) }),
773
+ /* @__PURE__ */ jsx4(Row, { label: "The block", children: /* @__PURE__ */ jsxs2("span", { className: "font-mono text-xs", children: [
774
+ p.block.length.toLocaleString(),
775
+ " characters"
776
+ ] }) }),
777
+ /* @__PURE__ */ jsx4("pre", { className: "mt-2 max-h-[50vh] overflow-auto rounded-md border bg-muted/40 p-3 font-mono text-xs whitespace-pre-wrap", children: p.block })
778
+ ] });
779
+ }
780
+ function History() {
781
+ const [turns, setTurns] = useState2(null);
782
+ const [on, setOn] = useState2(true);
783
+ const [open, setOpen] = useState2(null);
784
+ const [error, setError] = useState2("");
785
+ const load = useCallback2(() => {
786
+ call("GET", "/api/agent/trace?limit=200").then((r) => {
787
+ setTurns(r.turns ?? []);
788
+ setOn(r.on);
789
+ setError("");
790
+ }).catch((e) => setError(e.message));
791
+ }, []);
792
+ useEffect3(load, [load]);
793
+ const shown2 = turns?.find((t) => t.id === open) ?? turns?.[0];
794
+ return /* @__PURE__ */ jsxs2("div", { className: "flex min-h-0 flex-1 flex-col", children: [
795
+ /* @__PURE__ */ jsxs2("div", { className: "flex shrink-0 flex-wrap items-center gap-3 border-b px-3 py-2 text-xs", children: [
796
+ /* @__PURE__ */ jsxs2("span", { className: "flex items-center gap-2", children: [
797
+ /* @__PURE__ */ jsx4(
798
+ Switch,
799
+ {
800
+ checked: on,
801
+ onCheckedChange: (v) => void setSetting("surface.agent_trace", v).then(() => setOn(v)).catch((e) => setError(e.message)),
802
+ "aria-label": "Keep the trace"
803
+ }
804
+ ),
805
+ "Keep the trace"
806
+ ] }),
807
+ /* @__PURE__ */ jsx4("span", { className: "text-muted-foreground", children: "On this machine only; the newest 50,000 turns." }),
808
+ /* @__PURE__ */ jsxs2("div", { className: "ml-auto flex items-center gap-1", children: [
809
+ /* @__PURE__ */ jsx4(Button2, { size: "sm", variant: "ghost", "aria-label": "Read the trace again", onClick: load, children: /* @__PURE__ */ jsx4(Icon, { name: "refresh-cw" }) }),
810
+ /* @__PURE__ */ jsxs2(
811
+ Button2,
812
+ {
813
+ size: "sm",
814
+ variant: "outline",
815
+ render: /* @__PURE__ */ jsx4("a", { href: "/api/agent/trace/export", download: "context-trace.jsonl" }),
816
+ children: [
817
+ /* @__PURE__ */ jsx4(Icon, { name: "download" }),
818
+ "Export"
819
+ ]
820
+ }
821
+ )
822
+ ] })
823
+ ] }),
824
+ error && /* @__PURE__ */ jsx4("p", { className: "border-b px-3 py-1 text-xs text-destructive", children: error }),
825
+ turns?.length === 0 ? /* @__PURE__ */ jsx4(Empty2, { className: "h-full", children: /* @__PURE__ */ jsxs2(EmptyHeader2, { children: [
826
+ /* @__PURE__ */ jsx4(EmptyTitle2, { children: "No turns yet" }),
827
+ /* @__PURE__ */ jsx4(EmptyDescription2, { children: "Each message to the agent leaves a record here." })
828
+ ] }) }) : /* @__PURE__ */ jsxs2("div", { className: "flex min-h-0 flex-1", children: [
829
+ /* @__PURE__ */ jsx4("div", { className: "flex w-80 shrink-0 flex-col gap-0.5 overflow-auto border-r p-1.5 @max-3xl:w-56", children: turns?.map((t) => {
830
+ const fixed = (t.signals ?? []).some(correction);
831
+ return /* @__PURE__ */ jsx4(
832
+ Item,
833
+ {
834
+ size: "sm",
835
+ variant: shown2?.id === t.id ? "muted" : "default",
836
+ render: /* @__PURE__ */ jsx4("a", { href: `#turn-${t.id}` }),
837
+ onClick: (e) => {
838
+ e.preventDefault();
839
+ setOpen(t.id);
840
+ },
841
+ children: /* @__PURE__ */ jsxs2(ItemContent, { children: [
842
+ /* @__PURE__ */ jsxs2(ItemTitle, { className: "w-full", children: [
843
+ /* @__PURE__ */ jsx4(Badge, { variant: "outline", className: "font-mono", children: t.slot || "none" }),
844
+ fixed && /* @__PURE__ */ jsx4("span", { title: "You re-pinned the context soon after this turn", children: /* @__PURE__ */ jsx4(Icon, { name: "corner-down-left", size: 12 }) }),
845
+ t.halted && /* @__PURE__ */ jsx4(Badge, { variant: "destructive", children: "halted" }),
846
+ /* @__PURE__ */ jsx4("span", { className: "ml-auto shrink-0 font-normal text-muted-foreground text-xs", children: when(t.at) })
847
+ ] }),
848
+ /* @__PURE__ */ jsx4(ItemDescription, { className: "truncate", children: t.text })
849
+ ] })
850
+ },
851
+ t.id
852
+ );
853
+ }) }),
854
+ /* @__PURE__ */ jsx4("div", { className: "min-w-0 flex-1 overflow-auto", children: shown2 && /* @__PURE__ */ jsx4(TurnDetail, { t: shown2 }) })
855
+ ] })
856
+ ] });
857
+ }
858
+ function ContextInspector(_) {
859
+ const [tab, setTab] = useState2("now");
860
+ return /* @__PURE__ */ jsxs2("div", { className: "@container flex h-full min-h-0 flex-col bg-background", children: [
861
+ /* @__PURE__ */ jsxs2("div", { className: "flex shrink-0 items-center gap-2 border-b px-3 py-2", children: [
862
+ /* @__PURE__ */ jsx4("span", { className: "text-sm font-semibold", children: "Context" }),
863
+ /* @__PURE__ */ jsxs2(
864
+ ToggleGroup,
865
+ {
866
+ size: "sm",
867
+ spacing: 0,
868
+ value: [tab],
869
+ onValueChange: (v) => v[0] && setTab(v[0]),
870
+ children: [
871
+ /* @__PURE__ */ jsx4(ToggleGroupItem, { value: "now", children: "Now" }),
872
+ /* @__PURE__ */ jsx4(ToggleGroupItem, { value: "history", children: "History" })
873
+ ]
874
+ }
875
+ ),
876
+ /* @__PURE__ */ jsx4("span", { className: "text-xs text-muted-foreground", children: "Why the agent gets the context it gets." })
877
+ ] }),
878
+ tab === "now" ? /* @__PURE__ */ jsx4("div", { className: "min-h-0 flex-1 overflow-auto", children: /* @__PURE__ */ jsx4(Now, {}) }) : /* @__PURE__ */ jsx4(History, {})
879
+ ] });
880
+ }
881
+
882
+ // ../../web/src/desk/coreViews.tsx
883
+ import { jsx as jsx5, jsxs as jsxs3 } from "react/jsx-runtime";
884
+ function Settings(_) {
885
+ const [entries, setEntries] = useState3(allSettings());
886
+ const [error, setError] = useState3("");
887
+ const refresh = useCallback3(() => void loadSettings().then(setEntries), []);
888
+ useEffect4(refresh, [refresh]);
889
+ useEvent("config.changed", refresh);
890
+ const change = (e, value) => {
891
+ setError("");
892
+ setSetting(e.full_key, value).catch((err) => setError(`${e.title}: ${err.message}`));
893
+ };
894
+ const reset = (e) => void call("DELETE", `/api/settings/${encodeURIComponent(e.full_key)}`).then(refresh);
895
+ const scopes = [...new Set(entries.map((e) => e.scope))];
896
+ const title = (scope) => scope === "surface" ? "Desk" : app().modules.find((m) => m.id === scope)?.title ?? scope;
897
+ return /* @__PURE__ */ jsxs3("div", { className: "flex flex-col gap-3 p-4", children: [
898
+ /* @__PURE__ */ jsx5("p", { className: "text-muted-foreground", children: "Settings are kept in the app's database and take effect as you change them. Nothing restarts." }),
899
+ error && /* @__PURE__ */ jsx5("p", { className: "text-destructive", children: error }),
900
+ scopes.map((scope) => /* @__PURE__ */ jsxs3("section", { className: "flex flex-col", children: [
901
+ /* @__PURE__ */ jsx5("h3", { className: "pt-2 pb-1.5 font-medium text-muted-foreground text-xs uppercase tracking-wider", children: title(scope) }),
902
+ entries.filter((e) => e.scope === scope).map((e) => /* @__PURE__ */ jsxs3("div", { className: "flex items-center justify-between gap-4 border-t py-2.5", children: [
903
+ /* @__PURE__ */ jsxs3("span", { className: "flex min-w-0 flex-col gap-0.5", children: [
904
+ /* @__PURE__ */ jsx5("span", { className: "font-medium", children: e.title }),
905
+ e.about && /* @__PURE__ */ jsx5("span", { className: "text-muted-foreground text-xs", children: e.about }),
906
+ /* @__PURE__ */ jsx5("code", { className: "font-mono text-muted-foreground text-xs", children: e.full_key })
907
+ ] }),
908
+ /* @__PURE__ */ jsxs3("span", { className: "flex shrink-0 items-center gap-2", children: [
909
+ e.type === "bool" && /* @__PURE__ */ jsx5(Switch2, { checked: !!e.value, onCheckedChange: (on) => change(e, on), "aria-label": e.title }),
910
+ e.type === "enum" && /* @__PURE__ */ jsxs3(Select, { value: String(e.value), onValueChange: (v) => change(e, v), children: [
911
+ /* @__PURE__ */ jsx5(SelectTrigger, { size: "sm", "aria-label": e.title, children: /* @__PURE__ */ jsx5(SelectValue, {}) }),
912
+ /* @__PURE__ */ jsx5(SelectContent, { children: e.options?.map((o) => /* @__PURE__ */ jsx5(SelectItem, { value: o, children: o }, o)) })
913
+ ] }),
914
+ e.type === "int" && /* @__PURE__ */ jsx5(
915
+ Input,
916
+ {
917
+ className: "w-24",
918
+ type: "number",
919
+ "aria-label": e.title,
920
+ value: Number(e.value),
921
+ onChange: (ev) => {
922
+ const n = Number.parseInt(ev.target.value, 10);
923
+ if (Number.isFinite(n)) change(e, n);
924
+ }
925
+ }
926
+ ),
927
+ e.type === "string" && /* @__PURE__ */ jsx5(
928
+ Input,
929
+ {
930
+ className: "w-64",
931
+ "aria-label": e.title,
932
+ defaultValue: String(e.value ?? ""),
933
+ onBlur: (ev) => {
934
+ if (ev.target.value !== e.value) change(e, ev.target.value);
935
+ }
936
+ },
937
+ String(e.value)
938
+ ),
939
+ e.set && /* @__PURE__ */ jsx5(Button3, { variant: "link", size: "xs", title: "Back to the default", onClick: () => reset(e), children: "reset" })
940
+ ] })
941
+ ] }, e.full_key))
942
+ ] }, scope))
943
+ ] });
944
+ }
945
+ function Layouts(_) {
946
+ const [layouts, setLayouts] = useState3([]);
947
+ const [name, setName] = useState3("");
948
+ const [error, setError] = useState3("");
949
+ const refresh = useCallback3(() => void listLayouts().then(setLayouts), []);
950
+ useEffect4(refresh, [refresh]);
951
+ useEvent("desk.layouts", refresh);
952
+ const active = deskState().active;
953
+ const save = (n) => {
954
+ setError("");
955
+ saveLayout(n).then(() => setName("")).catch((err) => setError(err.message));
956
+ };
957
+ return /* @__PURE__ */ jsxs3("div", { className: "flex flex-col gap-3 p-4", children: [
958
+ /* @__PURE__ */ jsx5("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)." }),
959
+ /* @__PURE__ */ jsxs3(
960
+ "form",
961
+ {
962
+ className: "flex items-center gap-2",
963
+ onSubmit: (e) => {
964
+ e.preventDefault();
965
+ if (name.trim()) save(name.trim());
966
+ },
967
+ children: [
968
+ /* @__PURE__ */ jsx5(
969
+ Input,
970
+ {
971
+ className: "flex-1",
972
+ placeholder: "Save the desk as it is now, as\u2026",
973
+ value: name,
974
+ onChange: (e) => setName(e.target.value)
975
+ }
976
+ ),
977
+ /* @__PURE__ */ jsx5(Button3, { type: "submit", disabled: !name.trim(), children: "Save" })
978
+ ]
979
+ }
980
+ ),
981
+ error && /* @__PURE__ */ jsx5("p", { className: "text-destructive", children: error }),
982
+ layouts.length === 0 && /* @__PURE__ */ jsx5("p", { className: "text-muted-foreground text-xs", children: "No saved layouts yet." }),
983
+ layouts.map((l) => /* @__PURE__ */ jsxs3(
984
+ "div",
985
+ {
986
+ className: "flex flex-col gap-2 rounded-lg border bg-card p-3 data-[on=true]:border-ring",
987
+ "data-on": l.name === active,
988
+ children: [
989
+ /* @__PURE__ */ jsxs3("div", { className: "flex items-center gap-2", children: [
990
+ /* @__PURE__ */ jsx5(Icon, { name: "layout-dashboard", size: 15 }),
991
+ /* @__PURE__ */ jsx5("strong", { children: l.name }),
992
+ l.name === active && /* @__PURE__ */ jsx5(Badge2, { variant: "secondary", children: "in use" }),
993
+ /* @__PURE__ */ jsx5("span", { className: "flex-1" }),
994
+ /* @__PURE__ */ jsx5(Button3, { variant: "outline", size: "sm", onClick: () => void loadLayout(l.name), children: "Arrange" }),
995
+ /* @__PURE__ */ jsx5(
996
+ Button3,
997
+ {
998
+ variant: "outline",
999
+ size: "sm",
1000
+ title: "Replace it with the desk as it is now",
1001
+ onClick: () => save(l.name),
1002
+ children: "Update"
1003
+ }
1004
+ ),
1005
+ /* @__PURE__ */ jsx5(Button3, { variant: "destructive", size: "sm", onClick: () => void deleteLayout(l.name).then(refresh), children: "Delete" })
1006
+ ] }),
1007
+ l.about && /* @__PURE__ */ jsx5("p", { className: "text-muted-foreground", children: l.about }),
1008
+ /* @__PURE__ */ jsxs3("p", { className: "text-muted-foreground text-xs", children: [
1009
+ l.mode,
1010
+ " \xB7 ",
1011
+ l.windows.map((w) => w.title || w.view).join(", ") || "no windows"
1012
+ ] }),
1013
+ l.setup && Object.keys(l.setup).length > 0 && /* @__PURE__ */ jsx5("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__ */ jsxs3("div", { children: [
1014
+ /* @__PURE__ */ jsx5("dt", { children: k }),
1015
+ /* @__PURE__ */ jsx5("dd", { children: typeof v === "string" ? v : JSON.stringify(v) })
1016
+ ] }, k)) })
1017
+ ]
1018
+ },
1019
+ l.name
1020
+ ))
1021
+ ] });
1022
+ }
1023
+ function Marks(_) {
1024
+ const [marks, setMarks] = useState3([]);
1025
+ const refresh = useCallback3(() => void call("GET", "/api/marks").then(setMarks), []);
1026
+ useEffect4(refresh, [refresh]);
1027
+ useEvent("marks.changed", refresh);
1028
+ return /* @__PURE__ */ jsxs3("div", { className: "flex flex-col gap-3 p-4", children: [
1029
+ /* @__PURE__ */ jsx5("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." }),
1030
+ marks.length === 0 && /* @__PURE__ */ jsx5("p", { className: "text-muted-foreground text-xs", children: "No open marks." }),
1031
+ marks.map((m) => /* @__PURE__ */ jsx5(MarkCard, { mark: m }, m.id))
1032
+ ] });
1033
+ }
1034
+ function MarkCard({ mark }) {
1035
+ const [reply, setReply] = useState3("");
1036
+ return /* @__PURE__ */ jsxs3(
1037
+ "div",
1038
+ {
1039
+ 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",
1040
+ "data-author": mark.author,
1041
+ children: [
1042
+ /* @__PURE__ */ jsxs3("div", { className: "flex items-center gap-2", children: [
1043
+ /* @__PURE__ */ jsx5(Icon, { name: mark.author === "agent" ? "bot" : "user", size: 14 }),
1044
+ /* @__PURE__ */ jsx5("code", { className: "truncate font-mono text-muted-foreground text-xs", title: mark.ref, children: mark.ref }),
1045
+ /* @__PURE__ */ jsx5("span", { className: "flex-1" }),
1046
+ /* @__PURE__ */ jsx5(Button3, { variant: "link", size: "xs", onClick: () => void resolveMark(mark.id), children: "resolve" })
1047
+ ] }),
1048
+ mark.quote && /* @__PURE__ */ jsx5("blockquote", { className: "border-l-2 pl-2.5 text-muted-foreground italic", children: mark.quote }),
1049
+ /* @__PURE__ */ jsx5("p", { children: mark.body }),
1050
+ mark.replies?.map((r) => /* @__PURE__ */ jsxs3("p", { className: "flex items-center gap-1.5 pl-2 text-muted-foreground", children: [
1051
+ /* @__PURE__ */ jsx5(Icon, { name: r.author === "agent" ? "bot" : "user", size: 12 }),
1052
+ " ",
1053
+ r.body
1054
+ ] }, r.created + r.body)),
1055
+ /* @__PURE__ */ jsx5(
1056
+ "form",
1057
+ {
1058
+ className: "flex items-center gap-2",
1059
+ onSubmit: (e) => {
1060
+ e.preventDefault();
1061
+ if (reply.trim()) void replyMark(mark.id, reply.trim()).then(() => setReply(""));
1062
+ },
1063
+ children: /* @__PURE__ */ jsx5(Input, { className: "flex-1", placeholder: "Reply\u2026", value: reply, onChange: (e) => setReply(e.target.value) })
1064
+ }
1065
+ )
1066
+ ]
1067
+ }
1068
+ );
1069
+ }
1070
+ var coreWeb = {
1071
+ views: {
1072
+ "surface/settings": Settings,
1073
+ "surface/layouts": Layouts,
1074
+ "surface/marks": Marks,
1075
+ "surface/cards": CardsWindow,
1076
+ "surface/context": ContextInspector
1077
+ }
1078
+ };
1079
+
1080
+ // ../../web/src/desk/Desktop.tsx
1081
+ import { applyPalette, DEFAULT_PALETTE as DEFAULT_PALETTE2, paletteById as paletteById2 } from "@hollis-labs/surface-theme";
1082
+ import { Component as Component2, useCallback as useCallback5, useEffect as useEffect12, useMemo as useMemo4, useRef, useState as useState10 } from "react";
1083
+ import { AppFrame } from "@/components/ui/app-frame";
1084
+ import { Badge as Badge4 } from "@/components/ui/badge";
1085
+ import { Button as Button7 } from "@/components/ui/button";
1086
+ import {
1087
+ DropdownMenu as DropdownMenu2,
1088
+ DropdownMenuContent as DropdownMenuContent2,
1089
+ DropdownMenuItem,
1090
+ DropdownMenuShortcut,
1091
+ DropdownMenuTrigger as DropdownMenuTrigger2
1092
+ } from "@/components/ui/dropdown-menu";
1093
+ import { Empty as Empty3, EmptyDescription as EmptyDescription3, EmptyHeader as EmptyHeader3, EmptyTitle as EmptyTitle3 } from "@/components/ui/empty";
1094
+ import { Kbd } from "@/components/ui/kbd";
1095
+ import { WindowManager } from "@/components/ui/window-manager";
1096
+
1097
+ // ../../web/src/ade/Overlay.tsx
1098
+ import { useEffect as useEffect5, useState as useState4, useSyncExternalStore as useSyncExternalStore4 } from "react";
1099
+ import { AttentionLayer } from "@/components/ui/attention-layer";
1100
+ import { GuideBar } from "@/components/ui/guide-bar";
1101
+
1102
+ // ../../web/src/ade/hub.ts
1103
+ import { createHub } from "@hollis-labs/ade-core";
1104
+ var hub = createHub();
1105
+ var toAnchor = (p) => ({
1106
+ surface: "desk",
1107
+ target: p.anchor ? { kind: "anchor", id: `${p.window}/${p.anchor}` } : { kind: "window", id: p.window },
1108
+ ...p.label ? { label: p.label } : {}
1109
+ });
1110
+ function rectOf(el) {
1111
+ if (!el) return null;
1112
+ const r = el.getBoundingClientRect();
1113
+ return r.width && r.height ? { x: r.x, y: r.y, w: r.width, h: r.height } : null;
1114
+ }
1115
+ function windowRect(id) {
1116
+ const body = document.querySelector(`[data-window="${CSS.escape(id)}"]`);
1117
+ if (!rectOf(body)) return null;
1118
+ const path = body?.closest(".flexlayout__tab")?.getAttribute("data-layout-path");
1119
+ const set2 = path ? document.querySelector(`.flexlayout__tabset[data-layout-path="${CSS.escape(path.replace(/\/t\d+$/, ""))}"]`) : null;
1120
+ return rectOf(set2) ?? rectOf(body);
1121
+ }
1122
+ var viewTitle = (view) => viewById(view)?.title ?? view;
1123
+ function toGuide(g) {
1124
+ return {
1125
+ id: g.id,
1126
+ title: g.title,
1127
+ surface: "desk",
1128
+ steps: g.steps.map((s) => ({
1129
+ id: s.id,
1130
+ say: s.say,
1131
+ ...s.point?.length ? { anchors: s.point.map(toAnchor) } : {},
1132
+ ...s.style ? { style: s.style } : {},
1133
+ ...s.hint ? { hint: s.hint } : {},
1134
+ ...s.await ? {
1135
+ await: {
1136
+ kind: "state",
1137
+ check: s.await.kind === "open" ? "window_open" : "focused",
1138
+ args: {
1139
+ view: s.await.view,
1140
+ text: s.await.kind === "open" ? `Open ${viewTitle(s.await.view)}.` : `Bring ${viewTitle(s.await.view)} to the front.`
1141
+ }
1142
+ }
1143
+ } : {}
1144
+ }))
1145
+ };
1146
+ }
1147
+ function applyAttention(a) {
1148
+ if (!a) {
1149
+ hub.clearAttention("agent", "point");
1150
+ return;
1151
+ }
1152
+ const ttl = a.until ? a.until - Date.now() : void 0;
1153
+ if (ttl !== void 0 && ttl <= 0) return;
1154
+ hub.attend({
1155
+ actor: "agent",
1156
+ style: a.style,
1157
+ anchors: a.targets.map(toAnchor),
1158
+ ...a.from ? { from: toAnchor(a.from) } : {},
1159
+ ...a.note ? { note: a.note } : {},
1160
+ ...ttl ? { ttl } : {},
1161
+ slot: "point"
1162
+ });
1163
+ }
1164
+ function applyGuide(g, report) {
1165
+ if (!g) {
1166
+ if (hub.guideState()) hub.guideDo("stop", "agent");
1167
+ return;
1168
+ }
1169
+ const guide = toGuide(g);
1170
+ if (report && report.guide === g.id && report.index > 0 && (report.status === "running" || report.status === "paused")) {
1171
+ const state3 = { guide, index: report.index, status: report.status, controller: "agent", history: [] };
1172
+ if (hub.restoreGuide(state3)) return;
1173
+ }
1174
+ try {
1175
+ hub.startGuide(guide, "agent");
1176
+ } catch (err) {
1177
+ console.warn("ade: the guide could not start", err);
1178
+ }
1179
+ }
1180
+ var started2 = false;
1181
+ function startAde() {
1182
+ if (started2) return;
1183
+ started2 = true;
1184
+ const desk2 = hub.register({
1185
+ info: { id: "desk", app: "surface", title: "Desk" },
1186
+ observe: () => ({
1187
+ actions: [],
1188
+ checks: [
1189
+ {
1190
+ name: "window_open",
1191
+ description: "A window of the view is open.",
1192
+ args_schema: { type: "object", properties: { view: { type: "string" } } }
1193
+ },
1194
+ {
1195
+ name: "focused",
1196
+ description: "A window of the view is in front.",
1197
+ args_schema: { type: "object", properties: { view: { type: "string" } } }
1198
+ }
1199
+ ],
1200
+ targets: deskState().wins.map((w) => ({ kind: "window", id: w.id, label: w.title }))
1201
+ }),
1202
+ act: () => ({ outcome: "rejected", code: "invalid", reason: "The desk is changed through the desk's own tools." }),
1203
+ resolve: (a) => {
1204
+ const t = a.target;
1205
+ if (!t) return null;
1206
+ if (t.kind === "window") return windowRect(t.id);
1207
+ if (t.kind === "anchor") {
1208
+ const cut = t.id.indexOf("/");
1209
+ return rectOf(anchorElement(t.id.slice(0, cut), t.id.slice(cut + 1)));
1210
+ }
1211
+ return null;
1212
+ },
1213
+ bounds: () => rectOf(document.querySelector("[data-slot=app-frame-content]")),
1214
+ 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)),
1215
+ check: (name, args) => {
1216
+ const s = deskState();
1217
+ const view = String(args.view ?? "");
1218
+ if (name === "window_open") return s.wins.some((w) => w.view === view);
1219
+ if (name === "focused") return s.wins.find((w) => w.id === s.focus)?.view === view;
1220
+ return false;
1221
+ }
1222
+ });
1223
+ onEvent("desk", () => setTimeout(() => desk2.changed(), 0));
1224
+ onEvent("ade.attention", (ev) => applyAttention(ev.data.attention));
1225
+ onEvent("ade.guide", (ev) => applyGuide(ev.data.guide));
1226
+ hub.subscribe((e) => {
1227
+ if (e.type !== "guide" || !e.state) return;
1228
+ const g = e.state;
1229
+ void call("POST", "/api/ade/guide", {
1230
+ guide: g.guide.id,
1231
+ index: g.index,
1232
+ step: g.guide.steps[g.index]?.id ?? "",
1233
+ status: g.status,
1234
+ ...g.stalled ? { stalled: g.stalled.reason } : {}
1235
+ }).catch(() => {
1236
+ });
1237
+ });
1238
+ void call("GET", "/api/ade").then((s) => {
1239
+ applyAttention(s.attention);
1240
+ applyGuide(s.guide, s.report);
1241
+ }).catch(() => {
1242
+ });
1243
+ }
1244
+ var dismissAttention = () => {
1245
+ hub.clearAttention("agent", "point");
1246
+ void call("DELETE", "/api/ade/attention").catch(() => {
1247
+ });
1248
+ };
1249
+
1250
+ // ../../web/src/ade/Overlay.tsx
1251
+ import { jsx as jsx6 } from "react/jsx-runtime";
1252
+ var version2 = () => hub.getVersion();
1253
+ var subscribe3 = (fn) => hub.subscribe(fn);
1254
+ function useTick(on) {
1255
+ const [, set2] = useState4(0);
1256
+ useEffect5(() => {
1257
+ if (!on) return;
1258
+ const again = () => set2((t) => t + 1);
1259
+ const timer = window.setInterval(again, 200);
1260
+ window.addEventListener("resize", again);
1261
+ window.addEventListener("scroll", again, true);
1262
+ return () => {
1263
+ window.clearInterval(timer);
1264
+ window.removeEventListener("resize", again);
1265
+ window.removeEventListener("scroll", again, true);
1266
+ };
1267
+ }, [on]);
1268
+ }
1269
+ function marksOf(list2) {
1270
+ return list2.map((a) => ({
1271
+ id: `${a.actor}:${a.style}:${a.seq}`,
1272
+ actor: a.actor,
1273
+ style: a.style === "cursor" ? "highlight" : a.style,
1274
+ rects: a.anchors.map((x) => hub.resolve(x)).filter((r) => !!r),
1275
+ from: a.from ? hub.resolve(a.from) : null,
1276
+ note: a.note,
1277
+ by: a.actor === "agent" ? "Agent" : "You"
1278
+ }));
1279
+ }
1280
+ function AdeAttention() {
1281
+ useEffect5(startAde, []);
1282
+ useSyncExternalStore4(subscribe3, version2);
1283
+ const list2 = hub.attentionNow();
1284
+ useTick(list2.length > 0);
1285
+ const spot = list2.find((a) => a.style === "spotlight");
1286
+ const area = spot ? hub.bounds(spot.anchors[0]?.surface ?? "") : null;
1287
+ return /* @__PURE__ */ jsx6(
1288
+ AttentionLayer,
1289
+ {
1290
+ marks: marksOf(list2),
1291
+ area,
1292
+ onDismiss: (id) => id.startsWith("agent:") ? dismissAttention() : hub.clearAttention("user")
1293
+ }
1294
+ );
1295
+ }
1296
+ function AdeGuide() {
1297
+ useSyncExternalStore4(subscribe3, version2);
1298
+ const g = hub.guideState();
1299
+ if (!g || g.status === "stopped") return null;
1300
+ const step = g.guide.steps[g.index];
1301
+ if (!step) return null;
1302
+ const a = step.await;
1303
+ 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.";
1304
+ return /* @__PURE__ */ jsx6("div", { className: "pointer-events-none absolute inset-x-0 bottom-4 z-40 flex justify-center px-4", children: /* @__PURE__ */ jsx6(
1305
+ GuideBar,
1306
+ {
1307
+ className: "pointer-events-auto",
1308
+ title: g.guide.title,
1309
+ say: step.say,
1310
+ step: g.index + 1,
1311
+ steps: g.guide.steps.length,
1312
+ status: g.status === "done" ? "done" : g.status,
1313
+ waiting: wait,
1314
+ hint: g.stalled ? `The guide could not do its own part: ${g.stalled.reason}` : wait ? step.hint : void 0,
1315
+ onBack: () => hub.guideDo("back"),
1316
+ onNext: () => hub.guideDo(wait ? "skip" : "next"),
1317
+ onPause: () => hub.guideDo("pause"),
1318
+ onResume: () => hub.guideDo("resume"),
1319
+ onStop: () => hub.guideDo("stop")
1320
+ }
1321
+ ) });
1322
+ }
1323
+
1324
+ // ../../web/src/agent/AgentPanel.tsx
1325
+ import { useChat, useChatBusy, useChatIds, useChatItem, useStickToBottom } from "@hollis-labs/surface-chat";
1326
+ import { Bot, Check, ChevronDown, ChevronUp, Copy } from "lucide-react";
1327
+ import { memo, useCallback as useCallback4, useEffect as useEffect6, useLayoutEffect, useMemo as useMemo3, useState as useState5 } from "react";
1328
+ import { Badge as Badge3 } from "@/components/ui/badge";
1329
+ import { Button as Button4 } from "@/components/ui/button";
1330
+ import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
1331
+ import {
1332
+ Conversation,
1333
+ ConversationContent,
1334
+ ConversationEmptyState,
1335
+ ConversationScrollButton,
1336
+ ConversationViewport
1337
+ } from "@/components/ui/conversation";
1338
+ import { Item as Item2, ItemContent as ItemContent2, ItemDescription as ItemDescription2, ItemFooter, ItemTitle as ItemTitle2 } from "@/components/ui/item";
1339
+ import { Label } from "@/components/ui/label";
1340
+ import { MessageNotice as MessageNotice2 } from "@/components/ui/message";
1341
+ import { PromptInput, PromptInputFooter, PromptInputSubmit, PromptInputTextarea } from "@/components/ui/prompt-input";
1342
+ import { Select as Select2, SelectContent as SelectContent2, SelectItem as SelectItem2, SelectTrigger as SelectTrigger2, SelectValue as SelectValue2 } from "@/components/ui/select";
1343
+
1344
+ // ../../web/src/agent/api.ts
1345
+ var base = "/api/agent";
1346
+ async function call2(method, path, body) {
1347
+ const res = await fetch(base + path, {
1348
+ method,
1349
+ credentials: "same-origin",
1350
+ headers: body === void 0 ? void 0 : { "Content-Type": "application/json" },
1351
+ body: body === void 0 ? void 0 : JSON.stringify(body)
1352
+ });
1353
+ if (!res.ok) {
1354
+ let msg = res.statusText;
1355
+ try {
1356
+ msg = (await res.json()).message ?? msg;
1357
+ } catch {
1358
+ }
1359
+ throw new Error(msg);
1360
+ }
1361
+ return await res.json();
1362
+ }
1363
+ var agentApi = {
1364
+ context: () => call2("GET", "/context"),
1365
+ setup: () => call2("GET", "/setup"),
1366
+ slots: () => call2("GET", "/slots"),
1367
+ /** Pin a slot; "" lets the window in front choose again. */
1368
+ pin: (slot) => call2("POST", "/slots/pin", { slot })
1369
+ };
1370
+
1371
+ // ../../web/src/agent/items.tsx
1372
+ import { Markdown } from "@/components/ui/markdown";
1373
+ import { Message, MessageContent, MessageNotice } from "@/components/ui/message";
1374
+ import { Spinner } from "@/components/ui/spinner";
1375
+ import { Tool, ToolContent, ToolHeader, ToolInput, ToolOutput } from "@/components/ui/tool";
1376
+ import { jsx as jsx7, jsxs as jsxs4 } from "react/jsx-runtime";
1377
+ function AskedCard({ item }) {
1378
+ const input = item.input ?? {};
1379
+ let result = {};
1380
+ try {
1381
+ if (item.result) result = JSON.parse(item.result);
1382
+ } catch {
1383
+ }
1384
+ const live = useCard(result.id ?? "");
1385
+ if (item.status === "error") return /* @__PURE__ */ jsx7(ToolRow, { item });
1386
+ if (item.status === "running" || !input.kind) {
1387
+ return /* @__PURE__ */ jsxs4(MessageNotice, { className: "flex items-center gap-1.5", children: [
1388
+ /* @__PURE__ */ jsx7(Spinner, { className: "size-3" }),
1389
+ " Waiting on your answer",
1390
+ input.title ? `: ${input.title}` : ""
1391
+ ] });
1392
+ }
1393
+ const card = live ?? {
1394
+ id: result.id ?? item.id,
1395
+ kind: input.kind,
1396
+ title: input.title,
1397
+ risk: input.risk,
1398
+ payload: input.payload,
1399
+ status: result.status || "submitted",
1400
+ outcome: result.status === "submitted" ? { status: "submitted", data: result.data, answers: result.answers, decisions: result.decisions } : void 0
1401
+ };
1402
+ return /* @__PURE__ */ jsx7(CardView, { card });
1403
+ }
1404
+ function ShownCard({ item }) {
1405
+ const input = item.input ?? {};
1406
+ if (item.status === "error") return /* @__PURE__ */ jsx7(ToolRow, { item });
1407
+ const what = item.name === "card_update" ? input.end ? "Closed a card" : "Updated a card" : `Showed a ${input.kind ?? ""} card`;
1408
+ return /* @__PURE__ */ jsxs4(MessageNotice, { children: [
1409
+ what,
1410
+ input.title ? `: ${input.title}` : ""
1411
+ ] });
1412
+ }
1413
+ function GeneratedSurface({ item }) {
1414
+ const input = item.input ?? {};
1415
+ let result = {};
1416
+ try {
1417
+ if (item.result) result = JSON.parse(item.result);
1418
+ } catch {
1419
+ }
1420
+ const live = useCard(result.id ?? "");
1421
+ if (item.status === "error") return /* @__PURE__ */ jsx7(ToolRow, { item });
1422
+ const title = input.params?.title;
1423
+ if (item.status === "running") {
1424
+ return /* @__PURE__ */ jsxs4(MessageNotice, { className: "flex items-center gap-1.5", children: [
1425
+ /* @__PURE__ */ jsx7(Spinner, { className: "size-3" }),
1426
+ " Showing you",
1427
+ title ? `: ${title}` : " something"
1428
+ ] });
1429
+ }
1430
+ if (live) return /* @__PURE__ */ jsx7(CardView, { card: live });
1431
+ return /* @__PURE__ */ jsxs4(MessageNotice, { children: [
1432
+ "Showed you",
1433
+ title ? `: ${title}` : " a generated surface",
1434
+ result.status ? ` (${result.status})` : ""
1435
+ ] });
1436
+ }
1437
+ var toolCards = {
1438
+ card_ask: AskedCard,
1439
+ card_show: ShownCard,
1440
+ card_update: ShownCard,
1441
+ genui_show: GeneratedSurface
1442
+ };
1443
+ function ToolRow({ item }) {
1444
+ return /* @__PURE__ */ jsxs4(Tool, { children: [
1445
+ /* @__PURE__ */ jsx7(ToolHeader, { title: item.name, status: item.status }),
1446
+ /* @__PURE__ */ jsxs4(ToolContent, { children: [
1447
+ /* @__PURE__ */ jsx7(ToolInput, { input: item.input }),
1448
+ /* @__PURE__ */ jsx7(ToolOutput, { output: item.result, error: item.status === "error" })
1449
+ ] })
1450
+ ] });
1451
+ }
1452
+ var renderers = {
1453
+ user: ({ item }) => item.auto ? /* @__PURE__ */ jsx7(MessageNotice, { children: item.auto }) : /* @__PURE__ */ jsx7(Message, { from: "user", children: /* @__PURE__ */ jsx7(MessageContent, { children: item.text }) }),
1454
+ text: ({ item }) => item.text ? /* @__PURE__ */ jsx7(Message, { from: "assistant", children: /* @__PURE__ */ jsx7(MessageContent, { children: /* @__PURE__ */ jsx7(Markdown, { streaming: item.streaming, children: item.text }) }) }) : item.streaming ? /* @__PURE__ */ jsxs4(MessageNotice, { className: "flex items-center gap-1.5", children: [
1455
+ /* @__PURE__ */ jsx7(Spinner, { className: "size-3" }),
1456
+ " Writing\u2026"
1457
+ ] }) : null,
1458
+ tool: ({ item }) => {
1459
+ const Card2 = toolCards[item.name] ?? ToolRow;
1460
+ return /* @__PURE__ */ jsx7(Card2, { item });
1461
+ },
1462
+ notice: ({ item }) => /* @__PURE__ */ jsx7(MessageNotice, { tone: item.tone, children: item.text })
1463
+ };
1464
+ function ItemView({ item }) {
1465
+ const Draw = renderers[item.kind];
1466
+ return /* @__PURE__ */ jsx7(Draw, { item });
1467
+ }
1468
+
1469
+ // ../../web/src/agent/session.ts
1470
+ import {
1471
+ createChatStore,
1472
+ createConversationStore,
1473
+ initialState
1474
+ } from "@hollis-labs/surface-chat";
1475
+ var BASE = "/api/agent";
1476
+ function mode() {
1477
+ const want = typeof location === "undefined" ? "" : new URLSearchParams(location.search).get("chat") ?? "";
1478
+ return { role: want === "viewer" ? "viewer" : "controller", stream: want === "committed" ? "committed" : "deltas" };
1479
+ }
1480
+ function createAgentSession() {
1481
+ let run = null;
1482
+ let conv = null;
1483
+ const inner = () => conv ?? run;
1484
+ const listeners = /* @__PURE__ */ new Set();
1485
+ const ends = /* @__PURE__ */ new Set();
1486
+ const tell = () => {
1487
+ for (const fn of [...listeners]) fn();
1488
+ };
1489
+ const { role, stream } = mode();
1490
+ const boot = agentApi.setup().catch(() => null).then((setup) => {
1491
+ if (setup?.wire === "conversation" && setup.agent) {
1492
+ conv = createConversationStore({
1493
+ base: BASE,
1494
+ agent: setup.agent,
1495
+ role,
1496
+ stream,
1497
+ hostState: async () => ({ available: true, ready: setup.ready, model: setup.model })
1498
+ });
1499
+ } else {
1500
+ run = createChatStore({ base: BASE });
1501
+ }
1502
+ if (conv) {
1503
+ const leaving = conv;
1504
+ window.addEventListener("pagehide", () => leaving.dispose(), { once: true });
1505
+ }
1506
+ const store = inner();
1507
+ store.subscribe(tell);
1508
+ store.onRunEnd((id, how) => {
1509
+ for (const fn of [...ends]) fn(id, how);
1510
+ });
1511
+ tell();
1512
+ return store.start();
1513
+ });
1514
+ return {
1515
+ get: () => inner()?.get() ?? initialState,
1516
+ subscribe: (fn) => {
1517
+ listeners.add(fn);
1518
+ return () => {
1519
+ listeners.delete(fn);
1520
+ };
1521
+ },
1522
+ start: () => boot,
1523
+ send: async (text, how) => {
1524
+ await boot;
1525
+ return inner().send(text, how);
1526
+ },
1527
+ stop: () => inner()?.stop(),
1528
+ answer: async (decision) => {
1529
+ await inner()?.answer(decision);
1530
+ },
1531
+ newThread: async () => {
1532
+ await inner()?.newThread();
1533
+ },
1534
+ turnElsewhere: (id) => inner()?.turnElsewhere(id),
1535
+ onRunEnd: (fn) => {
1536
+ ends.add(fn);
1537
+ return () => {
1538
+ ends.delete(fn);
1539
+ };
1540
+ },
1541
+ durable: () => conv !== null,
1542
+ attachment: () => conv?.attachment() ?? "",
1543
+ role: () => conv ? conv.role() : "controller",
1544
+ takeover: async () => conv ? conv.takeover() : false
1545
+ };
1546
+ }
1547
+
1548
+ // ../../web/src/agent/AgentPanel.tsx
1549
+ import { Fragment as Fragment3, jsx as jsx8, jsxs as jsxs5 } from "react/jsx-runtime";
1550
+ var shared = null;
1551
+ function agentSession() {
1552
+ if (!shared) {
1553
+ shared = createAgentSession();
1554
+ void shared.start();
1555
+ }
1556
+ return shared;
1557
+ }
1558
+ function useCommits(id) {
1559
+ useLayoutEffect(() => {
1560
+ if (!import.meta.env?.DEV) return;
1561
+ const w = window;
1562
+ w.__chatRenders ??= {};
1563
+ w.__chatRenders[id] = (w.__chatRenders[id] ?? 0) + 1;
1564
+ });
1565
+ }
1566
+ function AgentPanel({ title = "Agent" }) {
1567
+ const store = useMemo3(agentSession, []);
1568
+ useEvent(
1569
+ "agent.turn",
1570
+ (ev) => store.turnElsewhere(String(ev.data?.run_id ?? ""))
1571
+ );
1572
+ return /* @__PURE__ */ jsxs5("div", { className: "flex h-full min-h-0 flex-col bg-background text-foreground", children: [
1573
+ /* @__PURE__ */ jsx8(ContextStrip, { store }),
1574
+ /* @__PURE__ */ jsx8(ChatHeader, { store, title }),
1575
+ /* @__PURE__ */ jsx8(Thread, { store }),
1576
+ /* @__PURE__ */ jsx8(CardDock, {}),
1577
+ /* @__PURE__ */ jsx8(ApprovalBar, { store }),
1578
+ /* @__PURE__ */ jsx8(InputHolder, { store }),
1579
+ /* @__PURE__ */ jsx8(Composer, { store })
1580
+ ] });
1581
+ }
1582
+ function ContextStrip({ store }) {
1583
+ const [asm, setAsm] = useState5(null);
1584
+ const [setup, setSetup] = useState5(null);
1585
+ const [slots, setSlots] = useState5([]);
1586
+ const [open, setOpen] = useState5(false);
1587
+ const [err, setErr] = useState5("");
1588
+ const refresh = useCallback4(() => {
1589
+ agentApi.context().then(setAsm, (e) => setErr(e.message));
1590
+ agentApi.slots().then(setSlots, () => {
1591
+ });
1592
+ }, []);
1593
+ useEffect6(() => {
1594
+ refresh();
1595
+ agentApi.setup().then(setSetup, () => {
1596
+ });
1597
+ }, [refresh]);
1598
+ useEvent("agent.context", (ev) => setAsm(ev.data));
1599
+ useEvent("agent.note", refresh);
1600
+ useEvent("agent.turn", refresh);
1601
+ useEffect6(() => store.onRunEnd(() => refresh()), [store, refresh]);
1602
+ const pin = (name) => agentApi.pin(name).then(setAsm, (e) => setErr(e.message));
1603
+ const top = asm?.top_of_mind ?? [];
1604
+ const why = asm?.why === "pinned" ? "pinned" : asm?.focused ? `from ${asm.focused.title}` : "";
1605
+ return /* @__PURE__ */ jsxs5(
1606
+ "section",
1607
+ {
1608
+ className: "flex flex-col gap-1.5 border-b border-border px-2.5 py-2 text-xs",
1609
+ "aria-label": "What the agent has in mind",
1610
+ children: [
1611
+ /* @__PURE__ */ jsxs5("div", { className: "flex flex-wrap items-center gap-2", children: [
1612
+ /* @__PURE__ */ jsx8(Label, { htmlFor: "agent-slot", children: "Slot" }),
1613
+ /* @__PURE__ */ jsxs5(
1614
+ Select2,
1615
+ {
1616
+ value: asm?.slot ?? null,
1617
+ onValueChange: (v) => void pin(String(v ?? "")),
1618
+ items: slots.map((s) => ({ value: s.name, label: s.name })),
1619
+ children: [
1620
+ /* @__PURE__ */ jsx8(SelectTrigger2, { id: "agent-slot", size: "sm", title: asm ? `${asm.slots[0]?.about ?? ""} (${asm.why})` : "", children: /* @__PURE__ */ jsx8(SelectValue2, {}) }),
1621
+ /* @__PURE__ */ jsx8(SelectContent2, { children: slots.map((s) => /* @__PURE__ */ jsx8(SelectItem2, { value: s.name, children: s.name }, s.name)) })
1622
+ ]
1623
+ }
1624
+ ),
1625
+ /* @__PURE__ */ jsx8("span", { className: "min-w-0 flex-1 truncate text-muted-foreground", children: why }),
1626
+ asm?.why === "pinned" && /* @__PURE__ */ jsx8(Button4, { variant: "link", size: "xs", onClick: () => void pin(""), children: "unpin" }),
1627
+ /* @__PURE__ */ jsxs5(Button4, { variant: "ghost", size: "xs", "aria-expanded": open, onClick: () => setOpen(!open), children: [
1628
+ open ? /* @__PURE__ */ jsx8(ChevronUp, {}) : /* @__PURE__ */ jsx8(ChevronDown, {}),
1629
+ "context"
1630
+ ] })
1631
+ ] }),
1632
+ asm && asm.slots.length > 1 && /* @__PURE__ */ jsxs5("div", { className: "text-muted-foreground", children: [
1633
+ "also:",
1634
+ " ",
1635
+ asm.slots.slice(1).map((s) => s.name).join(", ")
1636
+ ] }),
1637
+ top.length > 0 && /* @__PURE__ */ jsx8("div", { className: "flex flex-wrap gap-1", title: "Top of mind", children: top.map((t) => /* @__PURE__ */ jsx8(Badge3, { variant: "secondary", className: "font-mono", children: t }, t)) }),
1638
+ open && asm && /* @__PURE__ */ jsx8("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 }),
1639
+ setup && !setup.ready && /* @__PURE__ */ jsx8(SetupCard, { path: setup.config_path, reason: setup.reason }),
1640
+ err && /* @__PURE__ */ jsx8("div", { className: "text-destructive", children: err })
1641
+ ]
1642
+ }
1643
+ );
1644
+ }
1645
+ function ChatHeader({ store, title }) {
1646
+ const busy = useChatBusy(store);
1647
+ const model = useChat(store, (s) => s.host?.model ?? "");
1648
+ const empty = useChat(store, (s) => s.ids.length === 0);
1649
+ return /* @__PURE__ */ jsxs5("div", { className: "flex items-center gap-2 border-b border-border px-2.5 py-1.5", children: [
1650
+ /* @__PURE__ */ jsx8("span", { className: "text-sm font-semibold", children: title }),
1651
+ /* @__PURE__ */ jsx8("span", { className: "min-w-0 flex-1 truncate text-xs text-muted-foreground", children: busy ? "working\u2026" : model }),
1652
+ /* @__PURE__ */ jsx8(Button4, { variant: "ghost", size: "xs", disabled: busy || empty, onClick: () => void store.newThread(), children: "New" })
1653
+ ] });
1654
+ }
1655
+ var Thread = memo(function Thread2({ store }) {
1656
+ const ids = useChatIds(store);
1657
+ const off = useChat(store, (s) => s.loaded && s.host !== null && (!s.host.available || !s.host.ready));
1658
+ const error = useChat(store, (s) => s.error);
1659
+ const { viewportRef, contentRef, atBottom, scrollToBottom } = useStickToBottom();
1660
+ useCommits("thread");
1661
+ return /* @__PURE__ */ jsxs5(Conversation, { children: [
1662
+ /* @__PURE__ */ jsx8(ConversationViewport, { ref: viewportRef, children: /* @__PURE__ */ jsxs5(ConversationContent, { ref: contentRef, children: [
1663
+ off && /* @__PURE__ */ jsx8(MessageNotice2, { children: "No model is connected. The desk still works by hand." }),
1664
+ !off && ids.length === 0 && /* @__PURE__ */ jsx8(
1665
+ ConversationEmptyState,
1666
+ {
1667
+ icon: /* @__PURE__ */ jsx8(Bot, {}),
1668
+ title: "Ask the agent",
1669
+ description: "It sees the window in front and can work the desk for you."
1670
+ }
1671
+ ),
1672
+ ids.map((id) => /* @__PURE__ */ jsx8(Row2, { store, id }, id)),
1673
+ error && /* @__PURE__ */ jsx8(MessageNotice2, { tone: "error", children: error })
1674
+ ] }) }),
1675
+ !atBottom && /* @__PURE__ */ jsx8(ConversationScrollButton, { onClick: scrollToBottom })
1676
+ ] });
1677
+ });
1678
+ var Row2 = memo(function Row3({ store, id }) {
1679
+ const item = useChatItem(store, id);
1680
+ useCommits(`row:${id}`);
1681
+ return item ? /* @__PURE__ */ jsx8(ItemView, { item }) : null;
1682
+ });
1683
+ function InputHolder({ store }) {
1684
+ const holder = useChat(store, (s) => s.holder ?? null);
1685
+ useChat(store, (s) => s.error);
1686
+ useChat(store, (s) => s.loaded);
1687
+ if (!store.durable()) return null;
1688
+ const mine = store.attachment();
1689
+ const watching = store.role() === "viewer";
1690
+ const elsewhere = holder !== null && holder !== mine;
1691
+ if (!watching && !elsewhere) return null;
1692
+ return /* @__PURE__ */ jsx8("div", { role: "status", className: "border-t border-border p-2.5", children: /* @__PURE__ */ jsxs5(Item2, { variant: "muted", size: "sm", children: [
1693
+ /* @__PURE__ */ jsxs5(ItemContent2, { className: "min-w-0", children: [
1694
+ /* @__PURE__ */ jsx8(ItemTitle2, { children: elsewhere ? "Another window has the input" : "This window is watching" }),
1695
+ /* @__PURE__ */ jsx8(ItemDescription2, { className: "text-xs", children: watching ? "It shows the conversation. Take over to type here." : "What you send here is refused until you take over." })
1696
+ ] }),
1697
+ /* @__PURE__ */ jsx8(ItemFooter, { className: "justify-start", children: /* @__PURE__ */ jsx8(Button4, { variant: "outline", size: "xs", onClick: () => void store.takeover(), children: "Take over" }) })
1698
+ ] }) });
1699
+ }
1700
+ function ApprovalBar({ store }) {
1701
+ const q = useChat(store, (s) => s.approval);
1702
+ if (!q) return null;
1703
+ const input = q.input === void 0 ? "" : JSON.stringify(q.input);
1704
+ return /* @__PURE__ */ jsx8("div", { role: "alertdialog", "aria-label": "Permission", className: "border-t border-border p-2.5", children: /* @__PURE__ */ jsxs5(Item2, { variant: "outline", size: "sm", children: [
1705
+ /* @__PURE__ */ jsxs5(ItemContent2, { className: "min-w-0", children: [
1706
+ /* @__PURE__ */ jsx8(ItemTitle2, { children: q.description || `Allow ${q.tool}?` }),
1707
+ !q.description && input && /* @__PURE__ */ jsx8(ItemDescription2, { className: "font-mono text-xs", children: input })
1708
+ ] }),
1709
+ /* @__PURE__ */ jsxs5(ItemFooter, { className: "flex-wrap justify-start", children: [
1710
+ /* @__PURE__ */ jsx8(Button4, { size: "xs", onClick: () => void store.answer("once"), children: "Allow" }),
1711
+ q.standing && /* @__PURE__ */ jsxs5(Fragment3, { children: [
1712
+ /* @__PURE__ */ jsx8(Button4, { variant: "outline", size: "xs", onClick: () => void store.answer("session"), children: store.durable() ? "This conversation" : "This session" }),
1713
+ /* @__PURE__ */ jsx8(Button4, { variant: "outline", size: "xs", onClick: () => void store.answer("always"), children: "Always" })
1714
+ ] }),
1715
+ /* @__PURE__ */ jsx8(Button4, { variant: "ghost", size: "xs", onClick: () => void store.answer("deny"), children: "Don't" })
1716
+ ] })
1717
+ ] }) });
1718
+ }
1719
+ var Composer = memo(function Composer2({ store }) {
1720
+ const [draft, setDraft] = useState5("");
1721
+ const busy = useChatBusy(store);
1722
+ useCommits("composer");
1723
+ const submit = (e) => {
1724
+ e.preventDefault();
1725
+ const text = draft.trim();
1726
+ if (!text || busy) return;
1727
+ setDraft("");
1728
+ void store.send(text).then((ok) => {
1729
+ if (!ok) setDraft(text);
1730
+ });
1731
+ };
1732
+ return /* @__PURE__ */ jsx8("div", { className: "border-t border-border p-2.5", children: /* @__PURE__ */ jsxs5(PromptInput, { onSubmit: submit, children: [
1733
+ /* @__PURE__ */ jsx8(
1734
+ PromptInputTextarea,
1735
+ {
1736
+ value: draft,
1737
+ "aria-label": "Message",
1738
+ placeholder: "Ask, or /open, /layout, /run",
1739
+ onChange: (e) => setDraft(e.target.value)
1740
+ }
1741
+ ),
1742
+ /* @__PURE__ */ jsxs5(PromptInputFooter, { children: [
1743
+ /* @__PURE__ */ jsx8("span", { className: "text-xs text-muted-foreground", children: "Enter sends, Shift+Enter breaks the line" }),
1744
+ /* @__PURE__ */ jsx8(
1745
+ PromptInputSubmit,
1746
+ {
1747
+ status: busy ? "streaming" : "ready",
1748
+ onStop: store.stop,
1749
+ disabled: !busy && !draft.trim()
1750
+ }
1751
+ )
1752
+ ] })
1753
+ ] }) });
1754
+ });
1755
+ var example = (path) => `{
1756
+ "model": "your-model-name",
1757
+ "gateway_url": "https://your-gateway.example",
1758
+ "key_file": "${path.replace(/[^/]*$/, "") || "./"}agent-key"
1759
+ }`;
1760
+ function SetupCard({ path, reason }) {
1761
+ const [copied, setCopied] = useState5(false);
1762
+ const text = example(path);
1763
+ const copy = () => {
1764
+ void navigator.clipboard?.writeText(text).then(() => {
1765
+ setCopied(true);
1766
+ setTimeout(() => setCopied(false), 1500);
1767
+ });
1768
+ };
1769
+ return /* @__PURE__ */ jsxs5(Card, { size: "sm", children: [
1770
+ /* @__PURE__ */ jsxs5(CardHeader, { children: [
1771
+ /* @__PURE__ */ jsx8(CardTitle, { children: "The agent is not set up yet" }),
1772
+ reason && /* @__PURE__ */ jsx8("p", { className: "text-sm text-destructive", children: reason }),
1773
+ /* @__PURE__ */ jsxs5(CardDescription, { children: [
1774
+ "Everything else works by hand. To talk to the agent, write ",
1775
+ /* @__PURE__ */ jsx8("code", { className: "break-all", children: path }),
1776
+ ":"
1777
+ ] })
1778
+ ] }),
1779
+ /* @__PURE__ */ jsxs5(CardContent, { className: "flex flex-col gap-2 text-muted-foreground", children: [
1780
+ /* @__PURE__ */ jsx8("pre", { className: "m-0 overflow-x-auto rounded-md bg-muted p-2 font-mono text-xs text-foreground", children: text }),
1781
+ /* @__PURE__ */ jsx8("p", { children: "The gateway is any Anthropic-compatible endpoint; the key file holds its key. Restart the app after writing it." })
1782
+ ] }),
1783
+ /* @__PURE__ */ jsx8(CardFooter, { children: /* @__PURE__ */ jsxs5(Button4, { variant: "outline", size: "xs", onClick: copy, children: [
1784
+ copied ? /* @__PURE__ */ jsx8(Check, {}) : /* @__PURE__ */ jsx8(Copy, {}),
1785
+ copied ? "Copied" : "Copy the example"
1786
+ ] }) })
1787
+ ] });
1788
+ }
1789
+
1790
+ // ../../web/src/desk/AttentionBadge.tsx
1791
+ import { Button as Button5 } from "@/components/ui/button";
1792
+
1793
+ // ../../web/src/desk/attention.ts
1794
+ import { useSyncExternalStore as useSyncExternalStore5 } from "react";
1795
+ var state2 = { items: [], counts: {} };
1796
+ var subs3 = /* @__PURE__ */ new Set();
1797
+ var set = (a) => {
1798
+ state2 = { items: a?.items ?? [], counts: a?.counts ?? {} };
1799
+ for (const fn of subs3) fn();
1800
+ };
1801
+ var started3 = false;
1802
+ function start() {
1803
+ if (started3) return;
1804
+ started3 = true;
1805
+ void call("GET", "/api/attend").then(set).catch(() => {
1806
+ });
1807
+ onEvent("attend.changed", (ev) => set(ev.data));
1808
+ }
1809
+ function useAttention() {
1810
+ start();
1811
+ return useSyncExternalStore5(
1812
+ (fn) => {
1813
+ subs3.add(fn);
1814
+ return () => subs3.delete(fn);
1815
+ },
1816
+ () => state2
1817
+ );
1818
+ }
1819
+ var firstItem = (a) => a.items[0];
1820
+
1821
+ // ../../web/src/desk/commands.ts
1822
+ var clientCommands = [
1823
+ {
1824
+ id: "palette.toggle",
1825
+ title: "Command palette",
1826
+ section: "System",
1827
+ keys: "cmd+k",
1828
+ hidden: true,
1829
+ module: "surface",
1830
+ server: false
1831
+ },
1832
+ {
1833
+ id: "agent.toggle",
1834
+ title: "Show or hide the agent",
1835
+ section: "Agent",
1836
+ keys: "cmd+j",
1837
+ keywords: "assistant panel chat",
1838
+ module: "surface",
1839
+ server: false
1840
+ },
1841
+ { id: "agent.ask", title: "Ask the agent", section: "Agent", hidden: true, module: "surface", server: false },
1842
+ { id: "menu.toggle", title: "Apps menu", section: "System", hidden: true, module: "surface", server: false },
1843
+ {
1844
+ id: "attention.jump",
1845
+ title: "Jump to what needs me",
1846
+ section: "System",
1847
+ keys: "cmd+.",
1848
+ keywords: "attention waiting unseen needs answer next",
1849
+ module: "surface",
1850
+ server: false
1851
+ }
1852
+ ];
1853
+ async function jumpTo(item, ui) {
1854
+ if (!item) return false;
1855
+ if (item.window) {
1856
+ await act({ type: "focus", id: item.window });
1857
+ return true;
1858
+ }
1859
+ if (item.card) {
1860
+ if (item.by === "agent") ui.toggleAgent(true);
1861
+ else await call("POST", "/api/desk/actions", { type: "open", view: "surface.cards" });
1862
+ return true;
1863
+ }
1864
+ return false;
1865
+ }
1866
+ function runClient(id, ui, args) {
1867
+ switch (id) {
1868
+ case "palette.toggle":
1869
+ ui.togglePalette();
1870
+ return Promise.resolve(null);
1871
+ case "agent.toggle":
1872
+ ui.toggleAgent(typeof args?.open === "boolean" ? args.open : void 0);
1873
+ return Promise.resolve(null);
1874
+ case "agent.ask": {
1875
+ const text = typeof args?.text === "string" ? args.text.trim() : "";
1876
+ if (!text) return Promise.resolve(false);
1877
+ ui.toggleAgent(true);
1878
+ return agentSession().send(text);
1879
+ }
1880
+ case "menu.toggle":
1881
+ ui.toggleMenu();
1882
+ return Promise.resolve(null);
1883
+ case "attention.jump":
1884
+ return call("GET", "/api/attend").then(
1885
+ (a) => jumpTo(firstItem({ items: a.items ?? [], counts: {} }), ui)
1886
+ );
1887
+ }
1888
+ return void 0;
1889
+ }
1890
+
1891
+ // ../../web/src/desk/AttentionBadge.tsx
1892
+ import { jsx as jsx9, jsxs as jsxs6 } from "react/jsx-runtime";
1893
+ var words = { needs_you: "need you", failed: "failed", unseen: "not seen yet" };
1894
+ function AttentionBadge({ ui }) {
1895
+ const a = useAttention();
1896
+ const total = a.items.length;
1897
+ if (total === 0) return null;
1898
+ const needs = a.counts.needs_you ?? a.items.filter((i) => i.state === "needs_you").length;
1899
+ const byState = {};
1900
+ for (const i of a.items) byState[i.state] = (byState[i.state] ?? 0) + 1;
1901
+ const summary = Object.entries(byState).map(([state3, n]) => `${n} ${words[state3] ?? state3}`).join(" \xB7 ");
1902
+ const first = a.items[0];
1903
+ return /* @__PURE__ */ jsxs6(
1904
+ Button5,
1905
+ {
1906
+ variant: needs > 0 ? "secondary" : "ghost",
1907
+ size: "sm",
1908
+ "aria-pressed": needs > 0,
1909
+ "aria-label": `${total} waiting: ${summary}. Jump to the first.`,
1910
+ title: `${summary}
1911
+ Next: ${first?.title ?? first?.subject ?? ""} (\u2318.)`,
1912
+ onClick: () => void jumpTo(first, ui),
1913
+ children: [
1914
+ /* @__PURE__ */ jsx9(Icon, { name: needs > 0 ? "bell-ring" : "bell" }),
1915
+ /* @__PURE__ */ jsx9("span", { className: "tabular-nums", children: total })
1916
+ ]
1917
+ }
1918
+ );
1919
+ }
1920
+
1921
+ // ../../web/src/desk/Confirm.tsx
1922
+ import { useEffect as useEffect7, useState as useState6 } from "react";
1923
+ import {
1924
+ AlertDialog,
1925
+ AlertDialogAction,
1926
+ AlertDialogCancel,
1927
+ AlertDialogContent,
1928
+ AlertDialogDescription,
1929
+ AlertDialogFooter,
1930
+ AlertDialogHeader,
1931
+ AlertDialogTitle
1932
+ } from "@/components/ui/alert-dialog";
1933
+ import { jsx as jsx10, jsxs as jsxs7 } from "react/jsx-runtime";
1934
+ function ConfirmHost() {
1935
+ const [q, setQ] = useState6(null);
1936
+ useEffect7(() => {
1937
+ setConfirm((question) => new Promise((resolve) => setQ({ ...question, resolve })));
1938
+ }, []);
1939
+ const answer2 = (yes) => {
1940
+ q?.resolve(yes);
1941
+ setQ(null);
1942
+ };
1943
+ return /* @__PURE__ */ jsx10(
1944
+ AlertDialog,
1945
+ {
1946
+ open: !!q,
1947
+ onOpenChange: (open) => {
1948
+ if (!open) answer2(false);
1949
+ },
1950
+ children: /* @__PURE__ */ jsxs7(AlertDialogContent, { size: "sm", children: [
1951
+ /* @__PURE__ */ jsxs7(AlertDialogHeader, { children: [
1952
+ /* @__PURE__ */ jsx10(AlertDialogTitle, { children: q?.title }),
1953
+ q?.message && /* @__PURE__ */ jsx10(AlertDialogDescription, { children: q.message })
1954
+ ] }),
1955
+ /* @__PURE__ */ jsxs7(AlertDialogFooter, { children: [
1956
+ /* @__PURE__ */ jsx10(AlertDialogCancel, { children: "Cancel" }),
1957
+ /* @__PURE__ */ jsx10(AlertDialogAction, { variant: q?.danger ? "destructive" : "default", onClick: () => answer2(true), children: q?.confirmLabel ?? "OK" })
1958
+ ] })
1959
+ ] })
1960
+ }
1961
+ );
1962
+ }
1963
+
1964
+ // ../../web/src/desk/composing.ts
1965
+ import { useEffect as useEffect8 } from "react";
1966
+ var fields = 'textarea, input:not([type]), input[type="text"], input[type="search"], input[type="email"], input[type="url"], [contenteditable="true"]';
1967
+ function hasText(root) {
1968
+ for (const el of root.querySelectorAll(fields)) {
1969
+ const v = el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement ? el.value : el.textContent;
1970
+ if (v && v.trim() !== "") return true;
1971
+ }
1972
+ return false;
1973
+ }
1974
+ function useComposing(ref, id) {
1975
+ useEffect8(() => {
1976
+ const root = ref.current;
1977
+ if (!root) return;
1978
+ let last = false;
1979
+ let timer = 0;
1980
+ let poll = 0;
1981
+ const report = (now) => {
1982
+ if (now === last) return;
1983
+ last = now;
1984
+ void act({ type: "composing", ...id ? { id } : {}, composing: now }).catch(() => {
1985
+ });
1986
+ window.clearInterval(poll);
1987
+ if (now) poll = window.setInterval(() => report(hasText(root)), 3e3);
1988
+ };
1989
+ const check = () => {
1990
+ window.clearTimeout(timer);
1991
+ timer = window.setTimeout(() => report(hasText(root)), 250);
1992
+ };
1993
+ const events = ["input", "keyup", "submit", "focusout", "click"];
1994
+ for (const e of events) root.addEventListener(e, check, true);
1995
+ return () => {
1996
+ for (const e of events) root.removeEventListener(e, check, true);
1997
+ window.clearTimeout(timer);
1998
+ window.clearInterval(poll);
1999
+ if (last) void act({ type: "composing", ...id ? { id } : {}, composing: false }).catch(() => {
2000
+ });
2001
+ };
2002
+ }, [ref, id]);
2003
+ }
2004
+
2005
+ // ../../web/src/desk/GhostCursor.tsx
2006
+ import { useEffect as useEffect9, useState as useState7 } from "react";
2007
+ import { jsx as jsx11, jsxs as jsxs8 } from "react/jsx-runtime";
2008
+ function elementOf(p) {
2009
+ const win = p.window ?? deskState().wins.find((w) => w.view === p.view)?.id;
2010
+ if (!win) return null;
2011
+ if (p.anchor) {
2012
+ const a = anchorElement(win, p.anchor);
2013
+ if (a) return a;
2014
+ }
2015
+ return document.querySelector(`[data-window="${CSS.escape(win)}"]`);
2016
+ }
2017
+ function GhostCursor() {
2018
+ const [at, setAt] = useState7(null);
2019
+ useEffect9(() => {
2020
+ const desk2 = () => document.querySelector("[data-slot=app-frame-content]");
2021
+ let unzoom = 0;
2022
+ const reset = () => {
2023
+ const d = desk2();
2024
+ if (d) {
2025
+ d.style.transform = "";
2026
+ d.style.transformOrigin = "";
2027
+ }
2028
+ };
2029
+ const offStep = onEvent("script.step", (ev) => {
2030
+ const s = ev.data ?? {};
2031
+ const p = s.point?.[0];
2032
+ const el = p ? elementOf(p) : null;
2033
+ const r = el?.getBoundingClientRect();
2034
+ if (!r?.width) {
2035
+ setAt((cur) => cur ? { ...cur, say: s.say ?? "" } : null);
2036
+ return;
2037
+ }
2038
+ const x = r.x + r.width / 2;
2039
+ const y = r.y + Math.min(r.height / 2, 120);
2040
+ setAt({ x, y, label: p?.label ?? "agent", say: s.say ?? "" });
2041
+ window.clearTimeout(unzoom);
2042
+ const d = desk2();
2043
+ if (d && s.zoom) {
2044
+ d.style.transition = "transform 600ms ease";
2045
+ d.style.transformOrigin = `${x}px ${y}px`;
2046
+ d.style.transform = "scale(1.25)";
2047
+ unzoom = window.setTimeout(reset, Math.max(1500, (s.hold_ms ?? 4e3) - 400));
2048
+ } else reset();
2049
+ });
2050
+ const offDone = onEvent("script.done", () => {
2051
+ window.clearTimeout(unzoom);
2052
+ reset();
2053
+ setAt(null);
2054
+ });
2055
+ return () => {
2056
+ offStep();
2057
+ offDone();
2058
+ window.clearTimeout(unzoom);
2059
+ reset();
2060
+ };
2061
+ }, []);
2062
+ if (!at) return null;
2063
+ return /* @__PURE__ */ jsxs8(
2064
+ "div",
2065
+ {
2066
+ "data-slot": "ghost-cursor",
2067
+ "aria-hidden": true,
2068
+ className: "pointer-events-none fixed z-50 transition-[left,top] duration-700 ease-out",
2069
+ style: { left: at.x, top: at.y },
2070
+ children: [
2071
+ /* @__PURE__ */ jsx11("span", { className: "block text-primary drop-shadow-[0_0_6px_var(--p-accent)]", children: /* @__PURE__ */ jsx11(Icon, { name: "mouse-pointer-2", size: 22 }) }),
2072
+ /* @__PURE__ */ jsx11("span", { className: "ml-4 inline-block rounded-md bg-primary px-1.5 py-0.5 font-mono text-[11px] text-primary-foreground", children: at.label })
2073
+ ]
2074
+ }
2075
+ );
2076
+ }
2077
+
2078
+ // ../../web/src/desk/keys.ts
2079
+ var ALIASES = {
2080
+ return: "enter",
2081
+ esc: "escape",
2082
+ space: " ",
2083
+ left: "arrowleft",
2084
+ right: "arrowright",
2085
+ up: "arrowup",
2086
+ down: "arrowdown"
2087
+ };
2088
+ function parseKeys(keys) {
2089
+ const parts = keys.toLowerCase().split("+").map((p) => p.trim()).filter(Boolean);
2090
+ if (!parts.length) return null;
2091
+ const key = parts[parts.length - 1];
2092
+ const mods = new Set(parts.slice(0, -1));
2093
+ return {
2094
+ key: ALIASES[key] ?? key,
2095
+ ctrl: mods.has("ctrl") || mods.has("control"),
2096
+ alt: mods.has("alt") || mods.has("option"),
2097
+ shift: mods.has("shift"),
2098
+ meta: mods.has("cmd") || mods.has("meta") || mods.has("super")
2099
+ };
2100
+ }
2101
+ function matches(c, e) {
2102
+ if (e.ctrlKey !== c.ctrl || e.altKey !== c.alt || e.shiftKey !== c.shift || e.metaKey !== c.meta) return false;
2103
+ const key = e.key.toLowerCase();
2104
+ if (key === c.key) return true;
2105
+ const code = e.code.toLowerCase();
2106
+ if (code === `key${c.key}` || code === `digit${c.key}`) return true;
2107
+ if (c.key === "`" && code === "backquote") return true;
2108
+ return false;
2109
+ }
2110
+ var isMac = typeof navigator !== "undefined" && /mac/i.test(navigator.platform);
2111
+ function showKeys(keys) {
2112
+ if (!keys) return "";
2113
+ const c = parseKeys(keys);
2114
+ if (!c) return "";
2115
+ const out = [];
2116
+ if (c.ctrl) out.push(isMac ? "\u2303" : "Ctrl+");
2117
+ if (c.alt) out.push(isMac ? "\u2325" : "Alt+");
2118
+ if (c.shift) out.push(isMac ? "\u21E7" : "Shift+");
2119
+ if (c.meta) out.push(isMac ? "\u2318" : "Win+");
2120
+ const names = {
2121
+ enter: "\u21B5",
2122
+ escape: "Esc",
2123
+ arrowleft: "\u2190",
2124
+ arrowright: "\u2192",
2125
+ arrowup: "\u2191",
2126
+ arrowdown: "\u2193",
2127
+ " ": "Space"
2128
+ };
2129
+ out.push(names[c.key] ?? c.key.toUpperCase());
2130
+ return out.join("");
2131
+ }
2132
+
2133
+ // ../../web/src/desk/moduleApi.ts
2134
+ var cache2 = /* @__PURE__ */ new Map();
2135
+ function moduleApi(id) {
2136
+ const hit = cache2.get(id);
2137
+ if (hit) return hit;
2138
+ const base2 = `/api/m/${id}/`;
2139
+ const url = (path) => base2 + path.replace(/^\//, "");
2140
+ const api = {
2141
+ get: (p) => call("GET", url(p)),
2142
+ post: (p, body) => call("POST", url(p), body ?? {}),
2143
+ put: (p, body) => call("PUT", url(p), body ?? {}),
2144
+ del: (p) => call("DELETE", url(p)),
2145
+ url
2146
+ };
2147
+ cache2.set(id, api);
2148
+ return api;
2149
+ }
2150
+
2151
+ // ../../web/src/desk/Palette.tsx
2152
+ import { useEffect as useEffect10, useState as useState8 } from "react";
2153
+ import {
2154
+ Command,
2155
+ CommandDialog,
2156
+ CommandEmpty,
2157
+ CommandGroup,
2158
+ CommandInput,
2159
+ CommandItem,
2160
+ CommandList,
2161
+ CommandShortcut
2162
+ } from "@/components/ui/command";
2163
+ import { jsx as jsx12, jsxs as jsxs9 } from "react/jsx-runtime";
2164
+ function Palette({ open, onOpenChange, commands }) {
2165
+ const [layouts, setLayouts] = useState8([]);
2166
+ useEffect10(() => {
2167
+ if (!open) return;
2168
+ void listLayouts().then(setLayouts).catch(() => {
2169
+ });
2170
+ }, [open]);
2171
+ const rows = [];
2172
+ for (const c of commands) {
2173
+ if (c.hidden) continue;
2174
+ const viewId = c.id.startsWith("open.") ? c.id.slice(5) : "";
2175
+ rows.push({
2176
+ id: c.id,
2177
+ title: c.title,
2178
+ section: c.section ?? "Commands",
2179
+ icon: viewId ? app().views.find((v) => v.id === viewId)?.icon : void 0,
2180
+ hint: showKeys(c.keys),
2181
+ keywords: [c.keywords ?? "", c.section ?? "", c.id],
2182
+ run: () => runCommand(c.id)
2183
+ });
2184
+ }
2185
+ for (const l of layouts) {
2186
+ rows.push({
2187
+ id: `layout:${l.name}`,
2188
+ title: `Layout: ${l.name}`,
2189
+ section: "Layouts",
2190
+ icon: "layout-dashboard",
2191
+ keywords: ["layout", "arrange", "saved", l.about ?? ""],
2192
+ run: () => loadLayout(l.name)
2193
+ });
2194
+ }
2195
+ const sections = [...new Set(rows.map((r) => r.section))];
2196
+ const pick = (row) => {
2197
+ onOpenChange(false);
2198
+ void Promise.resolve(row.run()).catch((err) => console.warn("palette: failed", row.id, err));
2199
+ };
2200
+ return /* @__PURE__ */ jsx12(
2201
+ CommandDialog,
2202
+ {
2203
+ open,
2204
+ onOpenChange,
2205
+ title: "Command palette",
2206
+ description: "Run a command, open a window or load a layout.",
2207
+ children: /* @__PURE__ */ jsxs9(Command, { children: [
2208
+ /* @__PURE__ */ jsx12(CommandInput, { placeholder: "Run a command, open a window, load a layout\u2026" }),
2209
+ /* @__PURE__ */ jsxs9(CommandList, { children: [
2210
+ /* @__PURE__ */ jsx12(CommandEmpty, { children: "Nothing matches." }),
2211
+ sections.map((section) => /* @__PURE__ */ jsx12(CommandGroup, { heading: section, children: rows.filter((r) => r.section === section).map((r) => /* @__PURE__ */ jsxs9(CommandItem, { value: r.title, keywords: r.keywords, onSelect: () => pick(r), children: [
2212
+ /* @__PURE__ */ jsx12(Icon, { name: r.icon ?? "chevron-right" }),
2213
+ /* @__PURE__ */ jsx12("span", { children: r.title }),
2214
+ r.hint && /* @__PURE__ */ jsx12(CommandShortcut, { children: r.hint })
2215
+ ] }, r.id)) }, section))
2216
+ ] })
2217
+ ] })
2218
+ }
2219
+ );
2220
+ }
2221
+
2222
+ // ../../web/src/desk/ThemePicker.tsx
2223
+ import { DEFAULT_PALETTE, PALETTES, paletteById } from "@hollis-labs/surface-theme";
2224
+ import { useEffect as useEffect11, useState as useState9 } from "react";
2225
+ import { Button as Button6 } from "@/components/ui/button";
2226
+ import {
2227
+ DropdownMenu,
2228
+ DropdownMenuContent,
2229
+ DropdownMenuGroup,
2230
+ DropdownMenuLabel,
2231
+ DropdownMenuRadioGroup,
2232
+ DropdownMenuRadioItem,
2233
+ DropdownMenuSeparator,
2234
+ DropdownMenuTrigger
2235
+ } from "@/components/ui/dropdown-menu";
2236
+ import { jsx as jsx13, jsxs as jsxs10 } from "react/jsx-runtime";
2237
+ function Dots({ colors }) {
2238
+ return /* @__PURE__ */ jsx13("span", { className: "flex shrink-0 items-center gap-0.5", "aria-hidden": true, children: Object.entries(colors).map(([role, c]) => /* @__PURE__ */ jsx13("span", { className: "size-2 rounded-full", style: { background: c } }, role)) });
2239
+ }
2240
+ function ThemePicker() {
2241
+ const id = useSetting("surface.palette") ?? DEFAULT_PALETTE.id;
2242
+ const type = (useSetting("surface.type") ?? "mixed") === "mono" ? "mono" : "mixed";
2243
+ const palette = paletteById(id) ?? DEFAULT_PALETTE;
2244
+ const set2 = (key, value) => void setSetting(key, value).catch(() => {
2245
+ });
2246
+ return /* @__PURE__ */ jsxs10(DropdownMenu, { children: [
2247
+ /* @__PURE__ */ jsx13(
2248
+ DropdownMenuTrigger,
2249
+ {
2250
+ render: /* @__PURE__ */ jsxs10(Button6, { variant: "ghost", size: "sm", title: "Theme", "aria-label": `Theme: ${palette.name}`, children: [
2251
+ /* @__PURE__ */ jsx13(
2252
+ Dots,
2253
+ {
2254
+ colors: {
2255
+ accent: palette.accent,
2256
+ accent2: palette.accent2 ?? palette.cyan,
2257
+ red: palette.red,
2258
+ green: palette.green
2259
+ }
2260
+ }
2261
+ ),
2262
+ /* @__PURE__ */ jsx13("span", { children: palette.name })
2263
+ ] })
2264
+ }
2265
+ ),
2266
+ /* @__PURE__ */ jsxs10(DropdownMenuContent, { align: "end", className: "min-w-60", children: [
2267
+ /* @__PURE__ */ jsxs10(DropdownMenuGroup, { children: [
2268
+ /* @__PURE__ */ jsx13(DropdownMenuLabel, { children: "Palette" }),
2269
+ /* @__PURE__ */ jsx13(DropdownMenuRadioGroup, { value: palette.id, onValueChange: (v) => set2("surface.palette", String(v)), children: PALETTES.map((p) => /* @__PURE__ */ jsxs10(DropdownMenuRadioItem, { value: p.id, children: [
2270
+ /* @__PURE__ */ jsx13(
2271
+ Dots,
2272
+ {
2273
+ colors: { background: p.background, accent: p.accent, accent2: p.accent2 ?? p.cyan, red: p.red }
2274
+ }
2275
+ ),
2276
+ /* @__PURE__ */ jsx13("span", { children: p.name })
2277
+ ] }, p.id)) })
2278
+ ] }),
2279
+ /* @__PURE__ */ jsx13(DropdownMenuSeparator, {}),
2280
+ /* @__PURE__ */ jsxs10(DropdownMenuGroup, { children: [
2281
+ /* @__PURE__ */ jsx13(DropdownMenuLabel, { children: "Type" }),
2282
+ /* @__PURE__ */ jsxs10(DropdownMenuRadioGroup, { value: type, onValueChange: (v) => set2("surface.type", String(v)), children: [
2283
+ /* @__PURE__ */ jsx13(DropdownMenuRadioItem, { value: "mixed", children: "Mixed (mono chrome)" }),
2284
+ /* @__PURE__ */ jsx13(DropdownMenuRadioItem, { value: "mono", children: "Mono everywhere" })
2285
+ ] })
2286
+ ] })
2287
+ ] })
2288
+ ] });
2289
+ }
2290
+ function Clock() {
2291
+ const [now, setNow] = useState9(() => /* @__PURE__ */ new Date());
2292
+ useEffect11(() => {
2293
+ const t = setInterval(() => setNow(/* @__PURE__ */ new Date()), 15e3);
2294
+ return () => clearInterval(t);
2295
+ }, []);
2296
+ return /* @__PURE__ */ jsx13("span", { className: "px-1.5 tabular-nums text-muted-foreground", title: now.toLocaleString(), children: now.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }) });
2297
+ }
2298
+
2299
+ // ../../web/src/desk/Desktop.tsx
2300
+ import { Fragment as Fragment4, jsx as jsx14, jsxs as jsxs11 } from "react/jsx-runtime";
2301
+ function Desktop({ modules }) {
2302
+ const state3 = useDeskState();
2303
+ const manifest2 = app();
2304
+ const [palette, setPalette] = useState10(false);
2305
+ const [menu, setMenu] = useState10(false);
2306
+ const [agentOpen, setAgentOpen] = useState10(() => {
2307
+ try {
2308
+ return localStorage.getItem("surface.agent.open") === "1";
2309
+ } catch {
2310
+ return false;
2311
+ }
2312
+ });
2313
+ const [up, setUp] = useState10(isConnected());
2314
+ const gap = useSetting("surface.gap") ?? 10;
2315
+ useAnswerSeen(agentOpen);
2316
+ const paletteId = useSetting("surface.palette") ?? DEFAULT_PALETTE2.id;
2317
+ const typeStyle = (useSetting("surface.type") ?? "mixed") === "mono" ? "mono" : "mixed";
2318
+ const panelWidth = useSetting("surface.agent_panel_width") ?? 420;
2319
+ useEffect12(() => {
2320
+ setUp(isConnected());
2321
+ return onConnection(setUp);
2322
+ }, []);
2323
+ useEffect12(() => {
2324
+ applyPalette(paletteById2(paletteId) ?? DEFAULT_PALETTE2, document.documentElement, typeStyle);
2325
+ }, [paletteId, typeStyle]);
2326
+ useEffect12(() => {
2327
+ document.title = manifest2.title;
2328
+ }, [manifest2.title]);
2329
+ const toggleAgent = useCallback5((open) => {
2330
+ setAgentOpen((was) => {
2331
+ const next = open ?? !was;
2332
+ localStorage.setItem("surface.agent.open", next ? "1" : "0");
2333
+ return next;
2334
+ });
2335
+ }, []);
2336
+ const ui = useMemo4(
2337
+ () => ({
2338
+ togglePalette: (o) => setPalette((p) => o ?? !p),
2339
+ toggleAgent,
2340
+ toggleMenu: () => setMenu((m) => !m)
2341
+ }),
2342
+ [toggleAgent]
2343
+ );
2344
+ useEffect12(() => {
2345
+ setClientRunner((id, args) => runClient(id, ui, args));
2346
+ }, [ui]);
2347
+ const commands = useMemo4(() => [...clientCommands, ...manifest2.commands], [manifest2.commands]);
2348
+ useEffect12(() => {
2349
+ const chords = commands.flatMap((c) => {
2350
+ const chord = c.keys ? parseKeys(c.keys) : null;
2351
+ return chord ? [{ chord, id: c.id }] : [];
2352
+ });
2353
+ const onKey = (e) => {
2354
+ for (const { chord, id } of chords) {
2355
+ if (matches(chord, e)) {
2356
+ e.preventDefault();
2357
+ e.stopPropagation();
2358
+ void runCommand(id).catch((err) => console.warn("command failed", id, err));
2359
+ return;
2360
+ }
2361
+ }
2362
+ };
2363
+ window.addEventListener("keydown", onKey, true);
2364
+ return () => window.removeEventListener("keydown", onKey, true);
2365
+ }, [commands]);
2366
+ const windows = useMemo4(
2367
+ () => state3.wins.map((w) => ({
2368
+ id: w.id,
2369
+ title: w.title,
2370
+ dirty: w.dirty,
2371
+ icon: /* @__PURE__ */ jsx14(Icon, { name: viewById(w.view)?.icon, size: 13 }),
2372
+ // A delegate's window the owner has not made theirs: who opened it, and Keep (rule 4).
2373
+ badge: notYetKept(w) ? /* @__PURE__ */ jsx14(
2374
+ "span",
2375
+ {
2376
+ className: "text-muted-foreground",
2377
+ title: `Opened by the ${w.opened_by}${w.reason ? `: ${w.reason}` : ""}`,
2378
+ children: /* @__PURE__ */ jsx14(Icon, { name: "bot", size: 11 })
2379
+ }
2380
+ ) : void 0,
2381
+ actions: notYetKept(w) || w.held ? /* @__PURE__ */ jsxs11(Fragment4, { children: [
2382
+ w.held && /* @__PURE__ */ jsxs11(Fragment4, { children: [
2383
+ /* @__PURE__ */ jsx14(
2384
+ "span",
2385
+ {
2386
+ className: "text-warning",
2387
+ title: `The ${w.held.by} wants to change what this shows${w.held.title ? ` (${w.held.title})` : ""}. It waits until you are done here.`,
2388
+ children: /* @__PURE__ */ jsx14(Icon, { name: "git-pull-request-arrow", size: 12 })
2389
+ }
2390
+ ),
2391
+ /* @__PURE__ */ jsx14(
2392
+ Button7,
2393
+ {
2394
+ variant: "ghost",
2395
+ size: "xs",
2396
+ title: "Apply the waiting change now",
2397
+ onPointerDown: (e) => e.stopPropagation(),
2398
+ onClick: (e) => {
2399
+ e.stopPropagation();
2400
+ void act({ type: "held", id: w.id, do: "apply" });
2401
+ },
2402
+ children: "Apply"
2403
+ }
2404
+ ),
2405
+ /* @__PURE__ */ jsx14(
2406
+ Button7,
2407
+ {
2408
+ variant: "ghost",
2409
+ size: "xs",
2410
+ title: "Drop the waiting change",
2411
+ onPointerDown: (e) => e.stopPropagation(),
2412
+ onClick: (e) => {
2413
+ e.stopPropagation();
2414
+ void act({ type: "held", id: w.id, do: "drop" });
2415
+ },
2416
+ children: "Drop"
2417
+ }
2418
+ )
2419
+ ] }),
2420
+ notYetKept(w) && /* @__PURE__ */ jsx14(
2421
+ Button7,
2422
+ {
2423
+ variant: "ghost",
2424
+ size: "xs",
2425
+ title: "Keep this window: it is yours, and the agent will not close it",
2426
+ onPointerDown: (e) => e.stopPropagation(),
2427
+ onClick: (e) => {
2428
+ e.stopPropagation();
2429
+ void act({ type: "keep", id: w.id });
2430
+ },
2431
+ children: "Keep"
2432
+ }
2433
+ )
2434
+ ] }) : void 0
2435
+ })),
2436
+ [state3.wins]
2437
+ );
2438
+ const arrange = useCallback5(
2439
+ (tree, focus, grabbed) => act({ type: "tree", tree, focus, id: grabbed }),
2440
+ []
2441
+ );
2442
+ const menuViews = manifest2.views.filter((v) => v.menu);
2443
+ const bar = /* @__PURE__ */ jsxs11(Fragment4, { children: [
2444
+ /* @__PURE__ */ jsxs11("div", { className: "flex h-full min-w-0 flex-1 items-center gap-1", children: [
2445
+ /* @__PURE__ */ jsxs11(DropdownMenu2, { open: menu, onOpenChange: setMenu, children: [
2446
+ /* @__PURE__ */ jsx14(
2447
+ DropdownMenuTrigger2,
2448
+ {
2449
+ render: /* @__PURE__ */ jsxs11(Button7, { variant: "ghost", size: "sm", title: "Apps", children: [
2450
+ /* @__PURE__ */ jsx14(Icon, { name: "layout-grid" }),
2451
+ /* @__PURE__ */ jsx14("span", { className: "font-semibold", children: manifest2.title })
2452
+ ] })
2453
+ }
2454
+ ),
2455
+ /* @__PURE__ */ jsx14(DropdownMenuContent2, { className: "min-w-56", children: menuViews.map((v) => /* @__PURE__ */ jsxs11(DropdownMenuItem, { onClick: () => void desk.open(v.id), children: [
2456
+ /* @__PURE__ */ jsx14(Icon, { name: v.icon }),
2457
+ /* @__PURE__ */ jsx14("span", { children: v.title }),
2458
+ v.module !== "surface" && /* @__PURE__ */ jsx14(DropdownMenuShortcut, { children: v.module })
2459
+ ] }, v.id)) })
2460
+ ] }),
2461
+ /* @__PURE__ */ jsx14("div", { className: "ml-1 flex min-w-0 gap-0.5 overflow-hidden", children: state3.wins.map((w) => /* @__PURE__ */ jsxs11(
2462
+ Button7,
2463
+ {
2464
+ variant: w.id === state3.focus ? "secondary" : "ghost",
2465
+ size: "sm",
2466
+ className: "min-w-0 max-w-44 shrink",
2467
+ title: w.title,
2468
+ "aria-pressed": w.id === state3.focus,
2469
+ onClick: () => void act({ type: "focus", id: w.id }),
2470
+ onAuxClick: (e) => {
2471
+ if (e.button === 1) void closeWindow(w.id);
2472
+ },
2473
+ children: [
2474
+ /* @__PURE__ */ jsx14(Icon, { name: viewById(w.view)?.icon }),
2475
+ /* @__PURE__ */ jsx14("span", { className: "truncate", children: w.dirty ? `\u25CF ${w.title}` : w.title })
2476
+ ]
2477
+ },
2478
+ w.id
2479
+ )) })
2480
+ ] }),
2481
+ /* @__PURE__ */ jsxs11("div", { className: "flex h-full shrink-0 items-center gap-1", children: [
2482
+ state3.active && /* @__PURE__ */ jsxs11(
2483
+ Button7,
2484
+ {
2485
+ variant: "ghost",
2486
+ size: "sm",
2487
+ title: "The saved layout in use",
2488
+ onClick: () => void desk.open("surface.layouts"),
2489
+ children: [
2490
+ /* @__PURE__ */ jsx14(Icon, { name: "layout-dashboard" }),
2491
+ /* @__PURE__ */ jsx14("span", { children: state3.active })
2492
+ ]
2493
+ }
2494
+ ),
2495
+ state3.mode && /* @__PURE__ */ jsx14(Badge4, { variant: "secondary", title: "Your mode", children: state3.mode }),
2496
+ /* @__PURE__ */ jsxs11(
2497
+ Button7,
2498
+ {
2499
+ variant: "ghost",
2500
+ size: "sm",
2501
+ title: "Tile every window, or float them all",
2502
+ onClick: () => void runCommand("layout.toggle"),
2503
+ children: [
2504
+ /* @__PURE__ */ jsx14(Icon, { name: state3.layout === "tile" ? "columns-2" : "picture-in-picture-2" }),
2505
+ /* @__PURE__ */ jsx14("span", { children: state3.layout })
2506
+ ]
2507
+ }
2508
+ ),
2509
+ /* @__PURE__ */ jsx14(AttentionBadge, { ui }),
2510
+ /* @__PURE__ */ jsx14(ThemePicker, {}),
2511
+ /* @__PURE__ */ jsxs11(Button7, { variant: "ghost", size: "sm", title: "Command palette", onClick: () => setPalette(true), children: [
2512
+ /* @__PURE__ */ jsx14(Icon, { name: "search" }),
2513
+ /* @__PURE__ */ jsx14(Kbd, { children: showKeys("cmd+k") })
2514
+ ] }),
2515
+ /* @__PURE__ */ jsx14(
2516
+ Button7,
2517
+ {
2518
+ variant: agentOpen ? "secondary" : "ghost",
2519
+ size: "icon-sm",
2520
+ title: `Agent ${showKeys("cmd+j")}`,
2521
+ "aria-pressed": agentOpen,
2522
+ onClick: () => toggleAgent(),
2523
+ children: /* @__PURE__ */ jsx14(Icon, { name: "bot" })
2524
+ }
2525
+ ),
2526
+ /* @__PURE__ */ jsx14(Clock, {}),
2527
+ /* @__PURE__ */ jsx14(
2528
+ "span",
2529
+ {
2530
+ className: `mx-1.5 size-2 rounded-full ${up ? "bg-success" : "bg-warning"}`,
2531
+ title: up ? "Connected" : "Reconnecting\u2026"
2532
+ }
2533
+ )
2534
+ ] })
2535
+ ] });
2536
+ return /* @__PURE__ */ jsxs11(Fragment4, { children: [
2537
+ /* @__PURE__ */ jsxs11(
2538
+ AppFrame,
2539
+ {
2540
+ className: "fixed inset-0 text-sm",
2541
+ "data-layout": state3.layout,
2542
+ bar,
2543
+ side: /* @__PURE__ */ jsx14(PanelComposer, {}),
2544
+ showSide: agentOpen,
2545
+ sideSize: panelWidth,
2546
+ onSideResize: keepPanelWidth,
2547
+ children: [
2548
+ /* @__PURE__ */ jsx14(
2549
+ "div",
2550
+ {
2551
+ className: "relative isolate size-full overflow-hidden bg-desk",
2552
+ style: { "--window-gap": `${gap}px` },
2553
+ children: /* @__PURE__ */ jsx14(
2554
+ WindowManager,
2555
+ {
2556
+ tree: state3.tree,
2557
+ windows,
2558
+ focus: state3.focus,
2559
+ onArrange: arrange,
2560
+ onClose: (id) => void closeWindow(id),
2561
+ empty: /* @__PURE__ */ jsx14(Empty3, { className: "size-full", children: /* @__PURE__ */ jsxs11(EmptyHeader3, { children: [
2562
+ /* @__PURE__ */ jsx14(EmptyTitle3, { children: manifest2.title }),
2563
+ /* @__PURE__ */ jsxs11(EmptyDescription3, { children: [
2564
+ "Open something from the menu, press ",
2565
+ /* @__PURE__ */ jsx14(Kbd, { children: showKeys("cmd+k") }),
2566
+ " for the palette, or ask the agent."
2567
+ ] })
2568
+ ] }) }),
2569
+ children: (id) => /* @__PURE__ */ jsx14(WindowBody, { id, modules })
2570
+ }
2571
+ )
2572
+ }
2573
+ ),
2574
+ /* @__PURE__ */ jsx14(AdeGuide, {}),
2575
+ /* @__PURE__ */ jsx14(GhostCursor, {})
2576
+ ]
2577
+ }
2578
+ ),
2579
+ /* @__PURE__ */ jsx14(AdeAttention, {}),
2580
+ /* @__PURE__ */ jsx14(Palette, { open: palette, onOpenChange: setPalette, commands }),
2581
+ /* @__PURE__ */ jsx14(ConfirmHost, {})
2582
+ ] });
2583
+ }
2584
+ function PanelComposer() {
2585
+ const ref = useRef(null);
2586
+ useComposing(ref, "");
2587
+ return /* @__PURE__ */ jsx14("div", { ref, className: "contents", children: /* @__PURE__ */ jsx14(AgentPanel, { desk, title: "Agent" }) });
2588
+ }
2589
+ function useAnswerSeen(panelOpen) {
2590
+ const a = useAttention();
2591
+ const [focused, setFocused] = useState10(() => document.hasFocus());
2592
+ useEffect12(() => {
2593
+ const on = () => setFocused(true);
2594
+ const off = () => setFocused(false);
2595
+ window.addEventListener("focus", on);
2596
+ window.addEventListener("blur", off);
2597
+ return () => {
2598
+ window.removeEventListener("focus", on);
2599
+ window.removeEventListener("blur", off);
2600
+ };
2601
+ }, []);
2602
+ const waiting = a.items.find((i) => i.subject === "agent" && i.state === "unseen");
2603
+ useEffect12(() => {
2604
+ if (waiting && panelOpen && focused) void call("POST", "/api/attend/seen", { subject: "agent" }).catch(() => {
2605
+ });
2606
+ }, [waiting, panelOpen, focused]);
2607
+ }
2608
+ var widthTimer;
2609
+ function keepPanelWidth(px) {
2610
+ clearTimeout(widthTimer);
2611
+ widthTimer = setTimeout(() => {
2612
+ if (px > 0 && px !== getSetting("surface.agent_panel_width"))
2613
+ void setSetting("surface.agent_panel_width", px).catch(() => {
2614
+ });
2615
+ }, 400);
2616
+ }
2617
+ function WindowBody({ id, modules }) {
2618
+ const state3 = useDeskState();
2619
+ const win = state3.wins.find((w) => w.id === id);
2620
+ const focused = state3.focus === id;
2621
+ const module = win?.module ?? "";
2622
+ const api = useMemo4(() => moduleApi(module), [module]);
2623
+ const pub = useMemo4(() => win ? toWin(win, focused ? win.id : "") : null, [win, focused]);
2624
+ const body = useRef(null);
2625
+ useComposing(body, id);
2626
+ if (!win || !pub) return null;
2627
+ const view = viewById(win.view);
2628
+ const Cmp = view ? modules[view.module]?.views[view.render.entry] : void 0;
2629
+ return /* @__PURE__ */ jsx14(
2630
+ "div",
2631
+ {
2632
+ className: "relative size-full min-h-0 overflow-auto data-[bare=true]:flex data-[bare=true]:flex-col data-[bare=true]:overflow-hidden",
2633
+ ref: body,
2634
+ "data-bare": !!view?.bare,
2635
+ "data-window": win.id,
2636
+ children: /* @__PURE__ */ jsx14(Boundary2, { children: Cmp ? /* @__PURE__ */ jsx14(Cmp, { win: pub, desk, api }) : /* @__PURE__ */ jsxs11("p", { className: "p-4 text-muted-foreground", children: [
2637
+ "This app's page was built without the view \u201C",
2638
+ win.view,
2639
+ "\u201D. Rebuild the page with the module's web entry."
2640
+ ] }) }, win.view)
2641
+ }
2642
+ );
2643
+ }
2644
+ var Boundary2 = class extends Component2 {
2645
+ state = { error: null };
2646
+ static getDerivedStateFromError(error) {
2647
+ return { error };
2648
+ }
2649
+ render() {
2650
+ if (this.state.error) {
2651
+ return /* @__PURE__ */ jsxs11("div", { className: "flex flex-col items-start gap-3 p-4", children: [
2652
+ /* @__PURE__ */ jsx14("p", { children: "This window failed to draw." }),
2653
+ /* @__PURE__ */ jsx14("pre", { className: "whitespace-pre-wrap text-destructive text-xs", children: this.state.error.message }),
2654
+ /* @__PURE__ */ jsx14(Button7, { variant: "outline", size: "sm", onClick: () => this.setState({ error: null }), children: "Try again" })
2655
+ ] });
2656
+ }
2657
+ return this.props.children;
2658
+ }
2659
+ };
2660
+
2661
+ // ../../web/src/boot.tsx
2662
+ import { Fragment as Fragment5, jsx as jsx15, jsxs as jsxs12 } from "react/jsx-runtime";
2663
+ function Page({ modules, core }) {
2664
+ const [ready, setReady] = useState11(false);
2665
+ const [error, setError] = useState11("");
2666
+ useEffect13(() => {
2667
+ let live = true;
2668
+ Promise.all([loadManifest(), loadSettings()]).then(() => {
2669
+ if (!live) return;
2670
+ connect();
2671
+ setReady(true);
2672
+ void call("POST", "/api/events", { topic: "page.ready", data: {} }).catch(() => {
2673
+ });
2674
+ }).catch((err) => live && setError(err.message));
2675
+ return () => {
2676
+ live = false;
2677
+ };
2678
+ }, []);
2679
+ if (error)
2680
+ return /* @__PURE__ */ jsxs12("div", { className: "grid h-full place-items-center text-muted-foreground", children: [
2681
+ "The app's server did not answer: ",
2682
+ error
2683
+ ] });
2684
+ if (!ready) return /* @__PURE__ */ jsx15("div", { className: "grid h-full place-items-center text-muted-foreground", children: "\u2026" });
2685
+ return /* @__PURE__ */ jsxs12(Fragment5, { children: [
2686
+ /* @__PURE__ */ jsx15(Desktop, { modules: { ...modules, surface: { ...coreWeb, views: { ...coreWeb.views, ...core } } } }),
2687
+ /* @__PURE__ */ jsx15(CardHost, {})
2688
+ ] });
2689
+ }
2690
+ function mountPage(props, element = document.getElementById("root")) {
2691
+ if (!element) throw new Error("mountPage: no element to draw into (#root not found)");
2692
+ const root = createRoot(element);
2693
+ root.render(
2694
+ /* @__PURE__ */ jsx15(StrictMode, { children: /* @__PURE__ */ jsx15(Page, { ...props }) })
2695
+ );
2696
+ return root;
2697
+ }
2698
+ export {
2699
+ CardHost,
2700
+ CardsWindow,
2701
+ Desktop,
2702
+ Page,
2703
+ coreWeb,
2704
+ mountPage,
2705
+ registerCard
2706
+ };