@aidy-dev/react 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1692 @@
1
+ import { createContext, useCallback, useContext, useEffect, useId, useMemo, useReducer, useRef, useState } from "react";
2
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
3
+ import { AidyRequestError, answerApproval, answerForm, appendUserMessage, cancelAll, initialThreadState, reduceThread } from "@aidy-dev/client";
4
+ import { checkAnswers } from "@aidy-dev/spec/protocol";
5
+ import ReactMarkdown from "react-markdown";
6
+ import remarkGfm from "remark-gfm";
7
+ const strings = {
8
+ en: {
9
+ assistant: "Aidy",
10
+ openAssistant: "Open Aidy",
11
+ close: "Close",
12
+ history: "History",
13
+ newChat: "New chat",
14
+ noThreads: "No conversations yet.",
15
+ untitled: "Untitled",
16
+ deleteThread: "Delete",
17
+ loadMore: "Load more",
18
+ welcome: "Ask about anything in this product. I can look things up and act for you.",
19
+ composerPlaceholder: "Message Aidy…",
20
+ composerLabel: "Message",
21
+ send: "Send",
22
+ stop: "Stop",
23
+ thinking: "Thinking…",
24
+ retrying: "Model busy, retrying ({attempt}/{max})…",
25
+ cancelled: "Stopped.",
26
+ contextUsed: "{percent}% of context used",
27
+ lookups: "Looked up {count} things",
28
+ lookup: "Looked up 1 thing",
29
+ toolRunning: "Running",
30
+ toolAwaitingApproval: "Awaiting approval",
31
+ toolSucceeded: "Done",
32
+ toolFailed: "Did not succeed",
33
+ toolDeduplicated: "Already done",
34
+ sources: "Sources",
35
+ "error.model_unavailable": "The model is unavailable right now. Try again later.",
36
+ "error.max_steps": "This took too many steps, so I stopped. Try a narrower request.",
37
+ "error.open_interrupts": "Answer or dismiss the open request first.",
38
+ "error.history_conflict": "This conversation changed elsewhere. Reload it.",
39
+ "error.invalid_interaction": "That answer was not accepted.",
40
+ "error.internal": "Something went wrong.",
41
+ "error.request": "Could not reach Aidy.",
42
+ approvalNeeded: "Needs your approval",
43
+ approve: "Approve",
44
+ reject: "Reject",
45
+ expired: "This request expired. Ask again to retry.",
46
+ expiresAt: "Expires {time}",
47
+ target: "Target",
48
+ risk: "Risk",
49
+ "risk.low": "Low",
50
+ "risk.medium": "Medium",
51
+ "risk.high": "High",
52
+ cost: "Cost",
53
+ changes: "Changes",
54
+ arguments: "Details",
55
+ "effect.read": "Read",
56
+ "effect.create": "Create",
57
+ "effect.update": "Update",
58
+ "effect.delete": "Delete",
59
+ "effect.external": "External",
60
+ submit: "Submit",
61
+ required: "Required",
62
+ optional: "optional",
63
+ recommended: "Recommended",
64
+ other: "Other",
65
+ otherPlaceholder: "Your own answer",
66
+ "issue.required": "This is required.",
67
+ "issue.one": "Choose only one.",
68
+ taskRunning: "Waiting for {op} to finish",
69
+ cancelTask: "Cancel",
70
+ searchPlaceholder: "Search or ask Aidy…",
71
+ searchLabel: "Search",
72
+ searching: "Searching…",
73
+ noResults: "No results.",
74
+ failedSources: "Some sources did not answer: {sources}",
75
+ askAidy: "Ask Aidy",
76
+ loading: "Loading…",
77
+ loadFailed: "Could not load this page.",
78
+ models: "Models",
79
+ modelsHint: "Models are tried in order. A model that is rate-limited or out of credit rests, and the next one answers.",
80
+ provider: "Provider",
81
+ model: "Model",
82
+ baseURL: "Base URL",
83
+ apiKey: "API key",
84
+ apiKeySaved: "Saved — leave empty to keep",
85
+ vision: "Images",
86
+ moveUp: "Move up",
87
+ moveDown: "Move down",
88
+ remove: "Remove",
89
+ addModel: "Add model",
90
+ save: "Save",
91
+ saved: "Saved.",
92
+ saveFailed: "Could not save: {status}"
93
+ },
94
+ "zh-CN": {
95
+ assistant: "Aidy",
96
+ openAssistant: "打开 Aidy",
97
+ close: "关闭",
98
+ history: "历史",
99
+ newChat: "新对话",
100
+ noThreads: "还没有对话。",
101
+ untitled: "未命名",
102
+ deleteThread: "删除",
103
+ loadMore: "加载更多",
104
+ welcome: "问问这个产品里的任何事。我可以帮你查找,也可以替你操作。",
105
+ composerPlaceholder: "给 Aidy 发消息…",
106
+ composerLabel: "消息",
107
+ send: "发送",
108
+ stop: "停止",
109
+ thinking: "思考中…",
110
+ retrying: "模型繁忙,重试中({attempt}/{max})…",
111
+ cancelled: "已停止。",
112
+ contextUsed: "已用上下文 {percent}%",
113
+ lookups: "查询了 {count} 项",
114
+ lookup: "查询了 1 项",
115
+ toolRunning: "进行中",
116
+ toolAwaitingApproval: "等待确认",
117
+ toolSucceeded: "完成",
118
+ toolFailed: "未成功",
119
+ toolDeduplicated: "已完成过",
120
+ sources: "来源",
121
+ "error.model_unavailable": "模型暂时不可用,请稍后再试。",
122
+ "error.max_steps": "步骤太多,已停止。请把请求说得更具体些。",
123
+ "error.open_interrupts": "请先回答或放弃待处理的请求。",
124
+ "error.history_conflict": "对话已在别处更改,请重新加载。",
125
+ "error.invalid_interaction": "该回答未被接受。",
126
+ "error.internal": "出错了。",
127
+ "error.request": "无法连接 Aidy。",
128
+ approvalNeeded: "需要你确认",
129
+ approve: "确认",
130
+ reject: "拒绝",
131
+ expired: "该请求已过期,请重新发起。",
132
+ expiresAt: "{time} 过期",
133
+ target: "对象",
134
+ risk: "风险",
135
+ "risk.low": "低",
136
+ "risk.medium": "中",
137
+ "risk.high": "高",
138
+ cost: "费用",
139
+ changes: "变更",
140
+ arguments: "详情",
141
+ "effect.read": "读取",
142
+ "effect.create": "创建",
143
+ "effect.update": "修改",
144
+ "effect.delete": "删除",
145
+ "effect.external": "外部",
146
+ submit: "提交",
147
+ required: "必填",
148
+ optional: "选填",
149
+ recommended: "推荐",
150
+ other: "其他",
151
+ otherPlaceholder: "自己填写",
152
+ "issue.required": "此项必填。",
153
+ "issue.one": "只能选一项。",
154
+ taskRunning: "等待 {op} 完成",
155
+ cancelTask: "取消",
156
+ searchPlaceholder: "搜索或问 Aidy…",
157
+ searchLabel: "搜索",
158
+ searching: "搜索中…",
159
+ noResults: "没有结果。",
160
+ failedSources: "部分来源未响应:{sources}",
161
+ askAidy: "问 Aidy",
162
+ loading: "加载中…",
163
+ loadFailed: "无法加载此页面。",
164
+ models: "模型",
165
+ modelsHint: "按顺序使用模型。被限流或余额不足的模型会暂停,由下一个接替。",
166
+ provider: "提供方",
167
+ model: "模型",
168
+ baseURL: "Base URL",
169
+ apiKey: "API 密钥",
170
+ apiKeySaved: "已保存,留空则不变",
171
+ vision: "图片",
172
+ moveUp: "上移",
173
+ moveDown: "下移",
174
+ remove: "移除",
175
+ addModel: "添加模型",
176
+ save: "保存",
177
+ saved: "已保存。",
178
+ saveFailed: "保存失败:{status}"
179
+ }
180
+ };
181
+ function translator(locale) {
182
+ const table = strings[locale];
183
+ return (key, vars) => table[key].replace(/\{(\w+)\}/g, (match, name) => String(vars?.[name] ?? match));
184
+ }
185
+ // src/context.tsx
186
+ const AidyContext = createContext(null);
187
+ /** The same-origin path of `href`, or null when it leaves the page's origin. */
188
+ function samePath(href) {
189
+ const url = new URL(href, window.location.href);
190
+ if (url.origin !== window.location.origin) return null;
191
+ return `${url.pathname}${url.search}${url.hash}`;
192
+ }
193
+ function AidyProvider({ client, locale = "en", onOpen, theme = "system", children }) {
194
+ const [dockOpen, setDockOpen] = useState(false);
195
+ const [ask, setAsk] = useState(null);
196
+ const navigate = useCallback((href) => {
197
+ const path = samePath(href);
198
+ if (path === null) window.open(href, "_blank", "noopener,noreferrer");
199
+ else if (onOpen) onOpen(path);
200
+ else window.location.assign(path);
201
+ }, [onOpen]);
202
+ const askAidy = useCallback((query) => {
203
+ setAsk((current) => ({
204
+ id: (current?.id ?? 0) + 1,
205
+ query
206
+ }));
207
+ setDockOpen(true);
208
+ }, []);
209
+ const value = useMemo(() => ({
210
+ client,
211
+ locale,
212
+ t: translator(locale),
213
+ theme,
214
+ navigate,
215
+ dockOpen,
216
+ setDockOpen,
217
+ ask,
218
+ askAidy
219
+ }), [
220
+ client,
221
+ locale,
222
+ theme,
223
+ navigate,
224
+ dockOpen,
225
+ ask,
226
+ askAidy
227
+ ]);
228
+ return /* @__PURE__ */ jsx(AidyContext, {
229
+ value,
230
+ children
231
+ });
232
+ }
233
+ function useAidy() {
234
+ const value = useContext(AidyContext);
235
+ if (!value) throw new Error("aidy components must be inside <AidyProvider>");
236
+ return value;
237
+ }
238
+ /** Controls the dock from the host page, e.g. an "Ask Aidy" button. */
239
+ function useDock() {
240
+ const { dockOpen, setDockOpen, askAidy } = useAidy();
241
+ return {
242
+ open: dockOpen,
243
+ setOpen: setDockOpen,
244
+ ask: askAidy
245
+ };
246
+ }
247
+ /** Attributes for a component's outermost element, which carries the theme variables. */
248
+ function useRoot(className) {
249
+ const { theme, locale } = useAidy();
250
+ return {
251
+ className: `aidy-root ${className}`,
252
+ "data-aidy-theme": theme,
253
+ lang: locale
254
+ };
255
+ }
256
+ // src/approval.tsx
257
+ function useExpired(expiresAt) {
258
+ const deadline = expiresAt ? Date.parse(expiresAt) : NaN;
259
+ const [expired, setExpired] = useState(() => deadline <= Date.now());
260
+ useEffect(() => {
261
+ if (Number.isNaN(deadline)) return;
262
+ const left = deadline - Date.now();
263
+ if (left <= 0) {
264
+ setExpired(true);
265
+ return;
266
+ }
267
+ const timer = setTimeout(() => setExpired(true), Math.min(left, 2 ** 31 - 1));
268
+ return () => clearTimeout(timer);
269
+ }, [deadline]);
270
+ return expired;
271
+ }
272
+ function display(value) {
273
+ if (value === null || value === void 0 || value === "") return "—";
274
+ if (typeof value === "string") return value;
275
+ return JSON.stringify(value);
276
+ }
277
+ /** Asks the user to approve one write, showing exactly what will run. */
278
+ function ApprovalCard({ interrupt, onAnswer }) {
279
+ const { t, locale } = useAidy();
280
+ const { impact, arguments: args } = interrupt.meta;
281
+ const expired = useExpired(interrupt.interrupt.expiresAt);
282
+ const [answered, setAnswered] = useState(false);
283
+ const titleId = useId();
284
+ const answer = (approved) => {
285
+ setAnswered(true);
286
+ onAnswer(approved);
287
+ };
288
+ const expiresAt = interrupt.interrupt.expiresAt;
289
+ return /* @__PURE__ */ jsxs("section", {
290
+ className: "aidy-card aidy-approval",
291
+ "data-risk": impact.risk ?? void 0,
292
+ "data-effect": impact.effect,
293
+ "aria-labelledby": titleId,
294
+ children: [
295
+ /* @__PURE__ */ jsx("p", {
296
+ className: "aidy-card-eyebrow",
297
+ children: t("approvalNeeded")
298
+ }),
299
+ /* @__PURE__ */ jsx("h3", {
300
+ id: titleId,
301
+ className: "aidy-card-title",
302
+ children: impact.title
303
+ }),
304
+ /* @__PURE__ */ jsxs("div", {
305
+ className: "aidy-badges",
306
+ children: [/* @__PURE__ */ jsx("span", {
307
+ className: "aidy-badge",
308
+ "data-effect": impact.effect,
309
+ children: t(`effect.${impact.effect}`)
310
+ }), impact.risk ? /* @__PURE__ */ jsxs("span", {
311
+ className: "aidy-badge",
312
+ "data-risk": impact.risk,
313
+ children: [
314
+ t("risk"),
315
+ ": ",
316
+ t(`risk.${impact.risk}`)
317
+ ]
318
+ }) : null]
319
+ }),
320
+ /* @__PURE__ */ jsxs("dl", {
321
+ className: "aidy-facts",
322
+ children: [impact.target ? /* @__PURE__ */ jsxs("div", {
323
+ className: "aidy-fact",
324
+ children: [/* @__PURE__ */ jsx("dt", { children: t("target") }), /* @__PURE__ */ jsx("dd", { children: impact.target })]
325
+ }) : null, impact.costHint ? /* @__PURE__ */ jsxs("div", {
326
+ className: "aidy-fact",
327
+ children: [/* @__PURE__ */ jsx("dt", { children: t("cost") }), /* @__PURE__ */ jsx("dd", { children: impact.costHint })]
328
+ }) : null]
329
+ }),
330
+ impact.changes.length > 0 ? /* @__PURE__ */ jsx("ul", {
331
+ className: "aidy-changes",
332
+ "aria-label": t("changes"),
333
+ children: impact.changes.map((change) => /* @__PURE__ */ jsx("li", { children: change }, change))
334
+ }) : null,
335
+ Object.keys(args).length > 0 ? /* @__PURE__ */ jsxs("details", {
336
+ className: "aidy-arguments",
337
+ children: [/* @__PURE__ */ jsx("summary", { children: t("arguments") }), /* @__PURE__ */ jsx("dl", {
338
+ className: "aidy-facts aidy-mono",
339
+ children: Object.entries(args).map(([key, value]) => /* @__PURE__ */ jsxs("div", {
340
+ className: "aidy-fact",
341
+ children: [/* @__PURE__ */ jsx("dt", { children: key }), /* @__PURE__ */ jsx("dd", { children: display(value) })]
342
+ }, key))
343
+ })]
344
+ }) : null,
345
+ expired ? /* @__PURE__ */ jsx("p", {
346
+ className: "aidy-note",
347
+ role: "status",
348
+ children: t("expired")
349
+ }) : /* @__PURE__ */ jsxs("div", {
350
+ className: "aidy-actions",
351
+ children: [
352
+ expiresAt ? /* @__PURE__ */ jsx("span", {
353
+ className: "aidy-muted aidy-small",
354
+ children: t("expiresAt", { time: new Date(expiresAt).toLocaleTimeString(locale, {
355
+ hour: "2-digit",
356
+ minute: "2-digit"
357
+ }) })
358
+ }) : null,
359
+ /* @__PURE__ */ jsx("button", {
360
+ type: "button",
361
+ className: "aidy-button",
362
+ disabled: answered,
363
+ onClick: () => answer(false),
364
+ children: t("reject")
365
+ }),
366
+ /* @__PURE__ */ jsx("button", {
367
+ type: "button",
368
+ className: "aidy-button aidy-primary",
369
+ "data-danger": impact.risk === "high" || impact.effect === "delete" || void 0,
370
+ disabled: answered,
371
+ onClick: () => answer(true),
372
+ children: t("approve")
373
+ })
374
+ ]
375
+ })
376
+ ]
377
+ });
378
+ }
379
+ // src/hooks.ts
380
+ function threadReducer(state, action) {
381
+ if (action.type === "reset") return initialThreadState;
382
+ if (action.type === "user") return appendUserMessage(state, action.item);
383
+ return reduceThread(state, action.event);
384
+ }
385
+ /** Sends a run and detaches once it started; its events arrive through `follow`. */
386
+ async function start(run) {
387
+ const events = run[Symbol.asyncIterator]();
388
+ await events.next();
389
+ await events.return?.();
390
+ }
391
+ /**
392
+ * A thread's live state: it replays the thread's events and follows them, and opens the pages
393
+ * (`aidy.ui.open`) that runs started here ask for.
394
+ */
395
+ function useThread(threadId) {
396
+ const { client, navigate } = useAidy();
397
+ const [createdId, setCreatedId] = useState(null);
398
+ const [shownProp, setShownProp] = useState(threadId);
399
+ if (shownProp !== threadId) {
400
+ setShownProp(threadId);
401
+ setCreatedId(null);
402
+ }
403
+ const id = threadId ?? createdId;
404
+ const [state, dispatch] = useReducer(threadReducer, initialThreadState);
405
+ const [error, setError] = useState(null);
406
+ const created = useRef(null);
407
+ /** Opens with a seq above this were asked by a run started here and not yet shown. */
408
+ const openAfter = useRef(Number.POSITIVE_INFINITY);
409
+ const stateRef = useRef(state);
410
+ stateRef.current = state;
411
+ useEffect(() => {
412
+ if (id !== created.current) dispatch({ type: "reset" });
413
+ setError(null);
414
+ if (!id) return;
415
+ const controller = new AbortController();
416
+ (async () => {
417
+ for await (const event of client.follow(id, {
418
+ after: 0,
419
+ signal: controller.signal
420
+ })) dispatch({
421
+ type: "event",
422
+ event
423
+ });
424
+ })().catch((reason) => {
425
+ if (!controller.signal.aborted) setError(reason);
426
+ });
427
+ return () => controller.abort();
428
+ }, [client, id]);
429
+ useEffect(() => {
430
+ for (const open of state.opens) if (open.seq > openAfter.current) {
431
+ openAfter.current = open.seq;
432
+ navigate(open.path);
433
+ }
434
+ }, [state.opens, navigate]);
435
+ return {
436
+ threadId: id,
437
+ state,
438
+ error,
439
+ send: useCallback(async (text) => {
440
+ setError(null);
441
+ try {
442
+ let target = id;
443
+ if (!target) {
444
+ target = (await client.createThread()).id;
445
+ created.current = target;
446
+ setCreatedId(target);
447
+ }
448
+ const open = stateRef.current.interrupts;
449
+ const run = client.run(target, {
450
+ message: text,
451
+ ...open.length > 0 ? { resume: cancelAll(open) } : {}
452
+ });
453
+ if (run.messageId) dispatch({
454
+ type: "user",
455
+ item: {
456
+ kind: "user",
457
+ id: run.messageId,
458
+ text
459
+ }
460
+ });
461
+ openAfter.current = stateRef.current.lastSeq;
462
+ await start(run);
463
+ } catch (reason) {
464
+ setError(reason);
465
+ }
466
+ }, [client, id]),
467
+ resume: useCallback(async (entries) => {
468
+ if (!id) return;
469
+ setError(null);
470
+ openAfter.current = stateRef.current.lastSeq;
471
+ await start(client.run(id, { resume: entries })).catch(setError);
472
+ }, [client, id]),
473
+ cancel: useCallback(async () => {
474
+ const runId = stateRef.current.runId;
475
+ if (runId) await client.cancel(runId).catch(setError);
476
+ }, [client])
477
+ };
478
+ }
479
+ /** The user's threads, newest first. */
480
+ function useThreads() {
481
+ const { client } = useAidy();
482
+ const [threads, setThreads] = useState([]);
483
+ const [next, setNext] = useState();
484
+ const [loading, setLoading] = useState(true);
485
+ const [error, setError] = useState(null);
486
+ const [version, setVersion] = useState(0);
487
+ const load = useCallback(async (cursor, append) => {
488
+ setLoading(true);
489
+ try {
490
+ const page = await client.listThreads(cursor);
491
+ setThreads((current) => append ? [...current, ...page.items] : page.items);
492
+ setNext(page.next);
493
+ setError(null);
494
+ } catch (reason) {
495
+ setError(reason);
496
+ } finally {
497
+ setLoading(false);
498
+ }
499
+ }, [client]);
500
+ useEffect(() => {
501
+ load(void 0, false);
502
+ }, [load, version]);
503
+ return {
504
+ threads,
505
+ loading,
506
+ error,
507
+ hasMore: next !== void 0,
508
+ reload: useCallback(() => setVersion((v) => v + 1), []),
509
+ loadMore: useCallback(() => {
510
+ if (next !== void 0) load(next, true);
511
+ }, [load, next]),
512
+ remove: useCallback(async (threadId) => {
513
+ await client.deleteThread(threadId);
514
+ setThreads((current) => current.filter((thread) => thread.id !== threadId));
515
+ }, [client])
516
+ };
517
+ }
518
+ const SEARCH_DEBOUNCE_MS = 150;
519
+ /** Federated search, debounced; a newer query aborts the older request. */
520
+ function useSearch(query) {
521
+ const { client } = useAidy();
522
+ const [result, setResult] = useState(null);
523
+ const [loading, setLoading] = useState(false);
524
+ const [error, setError] = useState(null);
525
+ useEffect(() => {
526
+ const q = query.trim();
527
+ setResult(null);
528
+ setError(null);
529
+ if (!q) {
530
+ setLoading(false);
531
+ return;
532
+ }
533
+ setLoading(true);
534
+ const controller = new AbortController();
535
+ const timer = setTimeout(() => {
536
+ client.search(q, { signal: controller.signal }).then(setResult, (reason) => {
537
+ if (!controller.signal.aborted) setError(reason);
538
+ }).finally(() => {
539
+ if (!controller.signal.aborted) setLoading(false);
540
+ });
541
+ }, SEARCH_DEBOUNCE_MS);
542
+ return () => {
543
+ clearTimeout(timer);
544
+ controller.abort();
545
+ };
546
+ }, [client, query]);
547
+ return {
548
+ result,
549
+ loading,
550
+ error
551
+ };
552
+ }
553
+ /** The operations visible to this user. */
554
+ function useCatalog() {
555
+ const { client } = useAidy();
556
+ const [operations, setOperations] = useState([]);
557
+ const [loading, setLoading] = useState(true);
558
+ const [error, setError] = useState(null);
559
+ useEffect(() => {
560
+ let live = true;
561
+ client.catalog().then((list) => live && setOperations(list), (reason) => live && setError(reason)).finally(() => live && setLoading(false));
562
+ return () => {
563
+ live = false;
564
+ };
565
+ }, [client]);
566
+ return {
567
+ operations,
568
+ loading,
569
+ error
570
+ };
571
+ }
572
+ // src/form.tsx
573
+ function initial(question) {
574
+ if (question.kind === "text") return { text: question.default ?? "" };
575
+ return {
576
+ selected: question.default === void 0 ? [] : typeof question.default === "string" ? [question.default] : question.default,
577
+ custom: ""
578
+ };
579
+ }
580
+ /** Answers as `checkAnswers` expects them; untouched optional questions are left out. */
581
+ function collect(form, values) {
582
+ const answers = {};
583
+ for (const question of form.questions) {
584
+ const value = values[question.id];
585
+ if (!value) continue;
586
+ if ("text" in value) {
587
+ if (value.text.trim() || question.required) answers[question.id] = value.text;
588
+ } else {
589
+ const custom = value.custom.trim();
590
+ if (value.selected.length > 0 || custom || question.required) answers[question.id] = {
591
+ selected: value.selected,
592
+ ...custom ? { custom } : {}
593
+ };
594
+ }
595
+ }
596
+ return answers;
597
+ }
598
+ const ISSUE_KEYS = {
599
+ required: "issue.required",
600
+ "only one answer is allowed": "issue.one"
601
+ };
602
+ /** A form the agent or an operation asks the user to fill in. */
603
+ function AidyForm({ form, onSubmit }) {
604
+ const { t } = useAidy();
605
+ const baseId = useId();
606
+ const formRef = useRef(null);
607
+ const [values, setValues] = useState(() => Object.fromEntries(form.questions.map((question) => [question.id, initial(question)])));
608
+ const [issues, setIssues] = useState({});
609
+ const [submitted, setSubmitted] = useState(false);
610
+ const set = (id, value) => {
611
+ setValues((current) => ({
612
+ ...current,
613
+ [id]: value
614
+ }));
615
+ setIssues(({ [id]: _, ...rest }) => rest);
616
+ };
617
+ const submit = (event) => {
618
+ event.preventDefault();
619
+ const answers = collect(form, values);
620
+ const found = checkAnswers(form, answers);
621
+ if (found.length > 0) {
622
+ const messages = {};
623
+ for (const issue of found) {
624
+ const key = ISSUE_KEYS[issue.message];
625
+ messages[issue.question] ??= key ? t(key) : issue.message;
626
+ }
627
+ setIssues(messages);
628
+ const first = form.questions.find((question) => messages[question.id]);
629
+ formRef.current?.querySelector(`[data-question="${first?.id}"] input`)?.focus();
630
+ return;
631
+ }
632
+ setSubmitted(true);
633
+ onSubmit(answers);
634
+ };
635
+ return /* @__PURE__ */ jsxs("form", {
636
+ ref: formRef,
637
+ className: "aidy-card aidy-form",
638
+ onSubmit: submit,
639
+ noValidate: true,
640
+ "aria-labelledby": `${baseId}-title`,
641
+ children: [
642
+ /* @__PURE__ */ jsx("h3", {
643
+ id: `${baseId}-title`,
644
+ className: "aidy-card-title",
645
+ children: form.prompt
646
+ }),
647
+ form.questions.map((question) => {
648
+ const id = `${baseId}-${question.id}`;
649
+ const value = values[question.id] ?? initial(question);
650
+ const issue = issues[question.id];
651
+ const describedBy = issue ? `${id}-issue` : void 0;
652
+ const label = /* @__PURE__ */ jsxs(Fragment, { children: [question.prompt, question.required ? /* @__PURE__ */ jsxs("span", {
653
+ className: "aidy-required",
654
+ "aria-hidden": "true",
655
+ children: [" ", "*"]
656
+ }) : /* @__PURE__ */ jsxs("span", {
657
+ className: "aidy-muted",
658
+ children: [
659
+ " (",
660
+ t("optional"),
661
+ ")"
662
+ ]
663
+ })] });
664
+ return /* @__PURE__ */ jsxs("div", {
665
+ className: "aidy-question",
666
+ "data-question": question.id,
667
+ children: [question.kind === "text" || !("selected" in value) ? /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("label", {
668
+ htmlFor: id,
669
+ className: "aidy-label",
670
+ children: label
671
+ }), /* @__PURE__ */ jsx("input", {
672
+ id,
673
+ className: "aidy-input",
674
+ value: "text" in value ? value.text : "",
675
+ placeholder: question.kind === "text" ? question.placeholder : void 0,
676
+ required: question.required,
677
+ "aria-invalid": issue ? true : void 0,
678
+ "aria-describedby": describedBy,
679
+ onChange: (event) => set(question.id, { text: event.target.value })
680
+ })] }) : /* @__PURE__ */ jsxs("fieldset", {
681
+ className: "aidy-choices",
682
+ "aria-describedby": describedBy,
683
+ "aria-invalid": issue ? true : void 0,
684
+ children: [
685
+ /* @__PURE__ */ jsx("legend", {
686
+ className: "aidy-label",
687
+ children: label
688
+ }),
689
+ question.options.map((option) => {
690
+ const checked = value.selected.includes(option.id);
691
+ return /* @__PURE__ */ jsxs("label", {
692
+ className: "aidy-choice",
693
+ children: [/* @__PURE__ */ jsx("input", {
694
+ type: question.multiple ? "checkbox" : "radio",
695
+ name: id,
696
+ checked,
697
+ onChange: () => set(question.id, {
698
+ custom: question.multiple ? value.custom : "",
699
+ selected: question.multiple ? checked ? value.selected.filter((selected) => selected !== option.id) : [...value.selected, option.id] : [option.id]
700
+ })
701
+ }), /* @__PURE__ */ jsxs("span", { children: [
702
+ option.label,
703
+ option.recommended ? /* @__PURE__ */ jsx("span", {
704
+ className: "aidy-badge aidy-recommended",
705
+ children: t("recommended")
706
+ }) : null,
707
+ option.description ? /* @__PURE__ */ jsx("span", {
708
+ className: "aidy-choice-description",
709
+ children: option.description
710
+ }) : null
711
+ ] })]
712
+ }, option.id);
713
+ }),
714
+ question.allowCustom ? /* @__PURE__ */ jsx("input", {
715
+ className: "aidy-input",
716
+ "aria-label": `${question.prompt}: ${t("other")}`,
717
+ placeholder: t("otherPlaceholder"),
718
+ value: value.custom,
719
+ onChange: (event) => set(question.id, {
720
+ custom: event.target.value,
721
+ selected: question.multiple || !event.target.value ? value.selected : []
722
+ })
723
+ }) : null
724
+ ]
725
+ }), issue ? /* @__PURE__ */ jsx("p", {
726
+ id: `${id}-issue`,
727
+ className: "aidy-issue",
728
+ role: "alert",
729
+ children: issue
730
+ }) : null]
731
+ }, question.id);
732
+ }),
733
+ /* @__PURE__ */ jsx("div", {
734
+ className: "aidy-actions",
735
+ children: /* @__PURE__ */ jsx("button", {
736
+ type: "submit",
737
+ className: "aidy-button aidy-primary",
738
+ disabled: submitted,
739
+ children: t("submit")
740
+ })
741
+ })
742
+ ]
743
+ });
744
+ }
745
+ // src/markdown.tsx
746
+ const CITE = "#aidy-cite-";
747
+ /** Turns `[n]` markers into links the renderer shows as citations; code spans are left alone. */
748
+ function linkCitations(text, count) {
749
+ return text.split(/(`+[^`]*`+)/).map((part, index) => index % 2 === 1 ? part : part.replace(/\[(\d{1,3})\](?!\()/g, (match, n, offset) => {
750
+ return !((offset === 0 || part[offset - 1] === "\n") && part[offset + match.length] === ":") && Number(n) >= 1 && Number(n) <= count ? `[${n}](${CITE}${n})` : match;
751
+ })).join("");
752
+ }
753
+ /** Safe Markdown: raw HTML is not rendered, and same-origin links route through `onOpen`. */
754
+ function Markdown({ text, citations = [], baseUrl }) {
755
+ const { navigate } = useAidy();
756
+ const resolve = (href) => baseUrl ? new URL(href, baseUrl).href : href;
757
+ const follow = (event, href) => {
758
+ if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
759
+ if (href.startsWith("#")) return;
760
+ event.preventDefault();
761
+ navigate(href);
762
+ };
763
+ return /* @__PURE__ */ jsx("div", {
764
+ className: "aidy-markdown",
765
+ children: /* @__PURE__ */ jsx(ReactMarkdown, {
766
+ remarkPlugins: [remarkGfm],
767
+ components: {
768
+ a({ href = "", children }) {
769
+ if (href.startsWith(CITE)) {
770
+ const n = Number(href.slice(11));
771
+ const hit = citations[n - 1];
772
+ if (!hit) return /* @__PURE__ */ jsx(Fragment, { children });
773
+ return /* @__PURE__ */ jsx("a", {
774
+ className: "aidy-cite",
775
+ href: hit.url,
776
+ title: hit.title,
777
+ "aria-label": `${n}: ${hit.title}`,
778
+ onClick: (event) => follow(event, hit.url),
779
+ children: n
780
+ });
781
+ }
782
+ const target = resolve(href);
783
+ const external = samePath(target) === null;
784
+ return /* @__PURE__ */ jsx("a", {
785
+ href: target,
786
+ ...external ? {
787
+ target: "_blank",
788
+ rel: "noopener noreferrer"
789
+ } : {},
790
+ onClick: (event) => follow(event, target),
791
+ children
792
+ });
793
+ },
794
+ img({ src, alt }) {
795
+ return typeof src === "string" ? /* @__PURE__ */ jsx("img", {
796
+ src: resolve(src),
797
+ alt: alt ?? ""
798
+ }) : null;
799
+ }
800
+ },
801
+ children: linkCitations(text, citations.length)
802
+ })
803
+ });
804
+ }
805
+ // src/thread.tsx
806
+ /** Consecutive reads fold into one row; every write gets its own. */
807
+ function blocks(items) {
808
+ const out = [];
809
+ for (const item of items) {
810
+ const last = out.at(-1);
811
+ if (item.kind !== "tool") out.push({
812
+ kind: "item",
813
+ item
814
+ });
815
+ else if ((item.meta?.effect ?? "read") !== "read") out.push({
816
+ kind: "write",
817
+ tool: item
818
+ });
819
+ else if (last?.kind === "lookups") last.tools.push(item);
820
+ else out.push({
821
+ kind: "lookups",
822
+ tools: [item]
823
+ });
824
+ }
825
+ return out;
826
+ }
827
+ function StatusDot({ status }) {
828
+ return /* @__PURE__ */ jsx("span", {
829
+ className: "aidy-status",
830
+ "data-status": status,
831
+ "aria-hidden": "true"
832
+ });
833
+ }
834
+ function toolStatus(tool) {
835
+ if (tool.deduplicated) return "toolDeduplicated";
836
+ if (tool.status === "running") return "toolRunning";
837
+ return tool.status === "failed" ? "toolFailed" : "toolSucceeded";
838
+ }
839
+ function Lookups({ tools }) {
840
+ const { t } = useAidy();
841
+ const running = tools.findLast((tool) => tool.status === "running");
842
+ return /* @__PURE__ */ jsxs("details", {
843
+ className: "aidy-lookups",
844
+ children: [/* @__PURE__ */ jsxs("summary", { children: [/* @__PURE__ */ jsx(StatusDot, { status: running ? "running" : tools.some((x) => x.status === "failed") ? "failed" : "succeeded" }), running ? running.meta?.title ?? running.name : tools.length === 1 ? t("lookup") : t("lookups", { count: tools.length })] }), /* @__PURE__ */ jsx("ul", { children: tools.map((tool) => /* @__PURE__ */ jsxs("li", { children: [
845
+ /* @__PURE__ */ jsx(StatusDot, { status: tool.status }),
846
+ /* @__PURE__ */ jsx("span", { children: tool.meta?.title ?? tool.name }),
847
+ /* @__PURE__ */ jsx("span", {
848
+ className: "aidy-muted aidy-small",
849
+ children: t(toolStatus(tool))
850
+ })
851
+ ] }, tool.id)) })]
852
+ });
853
+ }
854
+ function Write({ tool, awaiting }) {
855
+ const { t } = useAidy();
856
+ return /* @__PURE__ */ jsxs("div", {
857
+ className: "aidy-tool",
858
+ "data-status": tool.status,
859
+ children: [
860
+ /* @__PURE__ */ jsx(StatusDot, { status: tool.status }),
861
+ /* @__PURE__ */ jsx("span", {
862
+ className: "aidy-tool-title",
863
+ children: tool.meta?.title ?? tool.name
864
+ }),
865
+ /* @__PURE__ */ jsx("span", {
866
+ className: "aidy-muted aidy-small",
867
+ title: tool.error?.code,
868
+ children: awaiting ? t("toolAwaitingApproval") : t(toolStatus(tool))
869
+ })
870
+ ]
871
+ });
872
+ }
873
+ function Interrupt({ open, thread }) {
874
+ const { t } = useAidy();
875
+ switch (open.kind) {
876
+ case "approval": return /* @__PURE__ */ jsx(ApprovalCard, {
877
+ interrupt: open,
878
+ onAnswer: (approved) => void thread.resume([answerApproval(open, approved)])
879
+ });
880
+ case "input": return /* @__PURE__ */ jsx(AidyForm, {
881
+ form: open.form,
882
+ onSubmit: (answers) => void thread.resume([answerForm(open, answers)])
883
+ });
884
+ case "task": return /* @__PURE__ */ jsxs("div", {
885
+ className: "aidy-card aidy-task",
886
+ role: "status",
887
+ children: [
888
+ /* @__PURE__ */ jsx("span", {
889
+ className: "aidy-spinner",
890
+ "aria-hidden": "true"
891
+ }),
892
+ /* @__PURE__ */ jsx("span", { children: open.progress?.message ?? t("taskRunning", { op: open.op }) }),
893
+ /* @__PURE__ */ jsx("button", {
894
+ type: "button",
895
+ className: "aidy-button",
896
+ onClick: () => void thread.resume(cancelAll([open])),
897
+ children: t("cancelTask")
898
+ })
899
+ ]
900
+ });
901
+ default: return null;
902
+ }
903
+ }
904
+ function errorKey(code) {
905
+ switch (code) {
906
+ case "model_unavailable":
907
+ case "max_steps":
908
+ case "open_interrupts":
909
+ case "history_conflict":
910
+ case "invalid_interaction": return `error.${code}`;
911
+ default: return "error.internal";
912
+ }
913
+ }
914
+ function Composer({ thread }) {
915
+ const { t } = useAidy();
916
+ const [text, setText] = useState("");
917
+ const running = thread.state.status === "running";
918
+ const send = () => {
919
+ const message = text.trim();
920
+ if (!message || running) return;
921
+ setText("");
922
+ thread.send(message);
923
+ };
924
+ const onKeyDown = (event) => {
925
+ if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing) {
926
+ event.preventDefault();
927
+ send();
928
+ }
929
+ };
930
+ const context = thread.state.context;
931
+ return /* @__PURE__ */ jsxs("form", {
932
+ className: "aidy-composer",
933
+ onSubmit: (event) => {
934
+ event.preventDefault();
935
+ send();
936
+ },
937
+ children: [/* @__PURE__ */ jsx("textarea", {
938
+ className: "aidy-input",
939
+ rows: 2,
940
+ "aria-label": t("composerLabel"),
941
+ placeholder: t("composerPlaceholder"),
942
+ value: text,
943
+ onChange: (event) => setText(event.target.value),
944
+ onKeyDown,
945
+ "data-aidy-autofocus": ""
946
+ }), /* @__PURE__ */ jsxs("div", {
947
+ className: "aidy-composer-bar",
948
+ children: [/* @__PURE__ */ jsx("span", {
949
+ className: "aidy-muted aidy-small",
950
+ children: context ? t("contextUsed", { percent: Math.round(context.usedTokens / context.budgetTokens * 100) }) : null
951
+ }), running ? /* @__PURE__ */ jsx("button", {
952
+ type: "button",
953
+ className: "aidy-button",
954
+ onClick: () => void thread.cancel(),
955
+ children: t("stop")
956
+ }) : /* @__PURE__ */ jsx("button", {
957
+ type: "submit",
958
+ className: "aidy-button aidy-primary",
959
+ disabled: !text.trim(),
960
+ children: t("send")
961
+ })]
962
+ })]
963
+ });
964
+ }
965
+ /** One conversation: messages, tool activity, open requests and the composer. */
966
+ function AidyThread({ threadId, onThreadCreated, initialMessage }) {
967
+ const { t } = useAidy();
968
+ const thread = useThread(threadId);
969
+ const { state } = thread;
970
+ const scroller = useRef(null);
971
+ const sentInitial = useRef(false);
972
+ useEffect(() => {
973
+ if (initialMessage && !sentInitial.current) {
974
+ sentInitial.current = true;
975
+ thread.send(initialMessage);
976
+ }
977
+ }, [initialMessage, thread.send]);
978
+ useEffect(() => {
979
+ if (threadId === null && thread.threadId) onThreadCreated?.(thread.threadId);
980
+ }, [
981
+ thread.threadId,
982
+ threadId,
983
+ onThreadCreated
984
+ ]);
985
+ const lastItem = state.items.at(-1);
986
+ useEffect(() => {
987
+ const element = scroller.current;
988
+ if (element) element.scrollTop = element.scrollHeight;
989
+ }, [
990
+ state.items.length,
991
+ lastItem,
992
+ state.interrupts.length,
993
+ state.status
994
+ ]);
995
+ const running = state.status === "running";
996
+ return /* @__PURE__ */ jsxs("div", {
997
+ className: "aidy-thread",
998
+ children: [/* @__PURE__ */ jsxs("div", {
999
+ className: "aidy-messages",
1000
+ ref: scroller,
1001
+ role: "log",
1002
+ "aria-live": "polite",
1003
+ children: [
1004
+ state.items.length === 0 && !running ? /* @__PURE__ */ jsx("p", {
1005
+ className: "aidy-welcome",
1006
+ children: t("welcome")
1007
+ }) : null,
1008
+ blocks(state.items).map((block) => {
1009
+ if (block.kind === "lookups") return /* @__PURE__ */ jsx(Lookups, { tools: block.tools }, block.tools[0]?.id);
1010
+ if (block.kind === "write") {
1011
+ const awaiting = state.interrupts.some((open) => open.kind === "approval" && open.interrupt.toolCallId === block.tool.id);
1012
+ return /* @__PURE__ */ jsx(Write, {
1013
+ tool: block.tool,
1014
+ awaiting
1015
+ }, block.tool.id);
1016
+ }
1017
+ const { item } = block;
1018
+ if (item.kind === "user") return /* @__PURE__ */ jsx("div", {
1019
+ className: "aidy-message aidy-user",
1020
+ children: item.text
1021
+ }, item.id);
1022
+ if (item.kind === "progress") return /* @__PURE__ */ jsxs("p", {
1023
+ className: "aidy-progress",
1024
+ "data-active": running && item === lastItem,
1025
+ children: [running && item === lastItem ? /* @__PURE__ */ jsx("span", {
1026
+ className: "aidy-spinner",
1027
+ "aria-hidden": "true"
1028
+ }) : null, item.message]
1029
+ }, item.id);
1030
+ return /* @__PURE__ */ jsx("div", {
1031
+ className: "aidy-message aidy-assistant",
1032
+ "aria-busy": item.streaming || void 0,
1033
+ children: /* @__PURE__ */ jsx(Markdown, {
1034
+ text: item.text,
1035
+ citations: state.citations[item.id] ?? []
1036
+ })
1037
+ }, item.id);
1038
+ }),
1039
+ state.interrupts.map((open) => /* @__PURE__ */ jsx(Interrupt, {
1040
+ open,
1041
+ thread
1042
+ }, open.id)),
1043
+ running && lastItem?.kind !== "progress" && !(lastItem?.kind === "assistant" && lastItem.streaming) ? /* @__PURE__ */ jsxs("p", {
1044
+ className: "aidy-progress",
1045
+ "data-active": "true",
1046
+ children: [/* @__PURE__ */ jsx("span", {
1047
+ className: "aidy-spinner",
1048
+ "aria-hidden": "true"
1049
+ }), state.retry ? t("retrying", {
1050
+ attempt: state.retry.attempt,
1051
+ max: state.retry.maxAttempts
1052
+ }) : t("thinking")]
1053
+ }) : null,
1054
+ state.status === "cancelled" ? /* @__PURE__ */ jsx("p", {
1055
+ className: "aidy-note",
1056
+ children: t("cancelled")
1057
+ }) : null,
1058
+ state.status === "failed" && state.error ? /* @__PURE__ */ jsx("p", {
1059
+ className: "aidy-error",
1060
+ role: "alert",
1061
+ children: t(errorKey(state.error.code))
1062
+ }) : null,
1063
+ thread.error ? /* @__PURE__ */ jsx("p", {
1064
+ className: "aidy-error",
1065
+ role: "alert",
1066
+ children: t("error.request")
1067
+ }) : null
1068
+ ]
1069
+ }), /* @__PURE__ */ jsx(Composer, { thread })]
1070
+ });
1071
+ }
1072
+ // src/dock.tsx
1073
+ function History({ current, onPick }) {
1074
+ const { t, locale } = useAidy();
1075
+ const { threads, loading, hasMore, loadMore, remove } = useThreads();
1076
+ return /* @__PURE__ */ jsxs("nav", {
1077
+ className: "aidy-history",
1078
+ "aria-label": t("history"),
1079
+ children: [
1080
+ threads.length === 0 && !loading ? /* @__PURE__ */ jsx("p", {
1081
+ className: "aidy-muted",
1082
+ children: t("noThreads")
1083
+ }) : null,
1084
+ /* @__PURE__ */ jsx("ul", { children: threads.map((thread) => /* @__PURE__ */ jsxs("li", {
1085
+ className: "aidy-history-row",
1086
+ children: [/* @__PURE__ */ jsxs("button", {
1087
+ type: "button",
1088
+ className: "aidy-history-item",
1089
+ "aria-current": thread.id === current || void 0,
1090
+ onClick: () => onPick(thread.id),
1091
+ children: [/* @__PURE__ */ jsx("span", {
1092
+ className: "aidy-history-title",
1093
+ children: thread.title ?? t("untitled")
1094
+ }), /* @__PURE__ */ jsx("time", {
1095
+ className: "aidy-muted aidy-small",
1096
+ dateTime: thread.createdAt,
1097
+ children: new Date(thread.createdAt).toLocaleDateString(locale, {
1098
+ month: "short",
1099
+ day: "numeric"
1100
+ })
1101
+ })]
1102
+ }), /* @__PURE__ */ jsx("button", {
1103
+ type: "button",
1104
+ className: "aidy-icon-button",
1105
+ "aria-label": `${t("deleteThread")}: ${thread.title ?? t("untitled")}`,
1106
+ onClick: () => void remove(thread.id),
1107
+ children: "×"
1108
+ })]
1109
+ }, thread.id)) }),
1110
+ loading ? /* @__PURE__ */ jsx("p", {
1111
+ className: "aidy-muted",
1112
+ children: t("loading")
1113
+ }) : null,
1114
+ hasMore && !loading ? /* @__PURE__ */ jsx("button", {
1115
+ type: "button",
1116
+ className: "aidy-button",
1117
+ onClick: loadMore,
1118
+ children: t("loadMore")
1119
+ }) : null
1120
+ ]
1121
+ });
1122
+ }
1123
+ /**
1124
+ * The side panel: a launcher, the conversation and its history. ⌘J / Ctrl+J toggles it, Escape
1125
+ * closes it; it fills the screen on narrow viewports.
1126
+ */
1127
+ function AidyDock() {
1128
+ const { t, dockOpen, setDockOpen, ask } = useAidy();
1129
+ const root = useRoot("aidy-dock-root");
1130
+ const [threadId, setThreadId] = useState(null);
1131
+ const [view, setView] = useState("thread");
1132
+ const [session, setSession] = useState(0);
1133
+ const [pendingAsk, setPendingAsk] = useState(null);
1134
+ const panel = useRef(null);
1135
+ const returnFocus = useRef(null);
1136
+ const titleId = useId();
1137
+ useEffect(() => {
1138
+ const onKey = (event) => {
1139
+ if (event.key.toLowerCase() === "j" && (event.metaKey || event.ctrlKey) && !event.altKey) {
1140
+ event.preventDefault();
1141
+ setDockOpen((open) => !open);
1142
+ }
1143
+ };
1144
+ window.addEventListener("keydown", onKey);
1145
+ return () => window.removeEventListener("keydown", onKey);
1146
+ }, [setDockOpen]);
1147
+ useEffect(() => {
1148
+ if (!ask) return;
1149
+ setPendingAsk(ask.query);
1150
+ setThreadId(null);
1151
+ setView("thread");
1152
+ setSession((n) => n + 1);
1153
+ }, [ask]);
1154
+ useEffect(() => {
1155
+ if (dockOpen) {
1156
+ if (document.activeElement instanceof HTMLElement && !panel.current?.contains(document.activeElement)) returnFocus.current = document.activeElement;
1157
+ panel.current?.querySelector("[data-aidy-autofocus]")?.focus();
1158
+ } else if (returnFocus.current) {
1159
+ returnFocus.current.focus();
1160
+ returnFocus.current = null;
1161
+ }
1162
+ }, [dockOpen]);
1163
+ const newChat = () => {
1164
+ setPendingAsk(null);
1165
+ setThreadId(null);
1166
+ setView("thread");
1167
+ setSession((n) => n + 1);
1168
+ };
1169
+ if (!dockOpen) return /* @__PURE__ */ jsx("div", {
1170
+ ...root,
1171
+ children: /* @__PURE__ */ jsx("button", {
1172
+ type: "button",
1173
+ className: "aidy-launcher",
1174
+ "aria-label": t("openAssistant"),
1175
+ "aria-keyshortcuts": "Meta+J Control+J",
1176
+ onClick: () => setDockOpen(true),
1177
+ children: /* @__PURE__ */ jsx("span", {
1178
+ "aria-hidden": "true",
1179
+ children: "✦"
1180
+ })
1181
+ })
1182
+ });
1183
+ return /* @__PURE__ */ jsx("div", {
1184
+ ...root,
1185
+ children: /* @__PURE__ */ jsxs("aside", {
1186
+ ref: panel,
1187
+ className: "aidy-dock",
1188
+ "aria-labelledby": titleId,
1189
+ onKeyDown: (event) => {
1190
+ if (event.key === "Escape" && !event.defaultPrevented) {
1191
+ event.preventDefault();
1192
+ setDockOpen(false);
1193
+ }
1194
+ },
1195
+ children: [/* @__PURE__ */ jsxs("header", {
1196
+ className: "aidy-dock-header",
1197
+ children: [
1198
+ /* @__PURE__ */ jsx("h2", {
1199
+ id: titleId,
1200
+ className: "aidy-dock-title",
1201
+ children: t("assistant")
1202
+ }),
1203
+ /* @__PURE__ */ jsx("button", {
1204
+ type: "button",
1205
+ className: "aidy-button aidy-ghost",
1206
+ "aria-pressed": view === "history",
1207
+ onClick: () => setView(view === "history" ? "thread" : "history"),
1208
+ children: t("history")
1209
+ }),
1210
+ /* @__PURE__ */ jsx("button", {
1211
+ type: "button",
1212
+ className: "aidy-button aidy-ghost",
1213
+ onClick: newChat,
1214
+ children: t("newChat")
1215
+ }),
1216
+ /* @__PURE__ */ jsx("button", {
1217
+ type: "button",
1218
+ className: "aidy-icon-button",
1219
+ "aria-label": t("close"),
1220
+ onClick: () => setDockOpen(false),
1221
+ children: "×"
1222
+ })
1223
+ ]
1224
+ }), view === "history" ? /* @__PURE__ */ jsx(History, {
1225
+ current: threadId,
1226
+ onPick: (id) => {
1227
+ setPendingAsk(null);
1228
+ setThreadId(id);
1229
+ setView("thread");
1230
+ }
1231
+ }) : /* @__PURE__ */ jsx(AidyThread, {
1232
+ threadId,
1233
+ onThreadCreated: (id) => {
1234
+ setPendingAsk(null);
1235
+ setThreadId(id);
1236
+ },
1237
+ ...pendingAsk ? { initialMessage: pendingAsk } : {}
1238
+ }, session)]
1239
+ })
1240
+ });
1241
+ }
1242
+ // src/help.tsx
1243
+ /** Fetches and renders one Markdown help page. */
1244
+ function HelpViewer({ url }) {
1245
+ const { t } = useAidy();
1246
+ const root = useRoot("aidy-help");
1247
+ const [page, setPage] = useState();
1248
+ useEffect(() => {
1249
+ const controller = new AbortController();
1250
+ fetch(url, {
1251
+ signal: controller.signal,
1252
+ headers: { Accept: "text/markdown, text/plain" }
1253
+ }).then(async (response) => {
1254
+ if (!response.ok) throw new Error(String(response.status));
1255
+ setPage({
1256
+ url,
1257
+ text: await response.text()
1258
+ });
1259
+ }).catch(() => {
1260
+ if (!controller.signal.aborted) setPage({
1261
+ url,
1262
+ failed: true
1263
+ });
1264
+ });
1265
+ return () => controller.abort();
1266
+ }, [url]);
1267
+ const absolute = new URL(url, window.location.href).href;
1268
+ return /* @__PURE__ */ jsx("article", {
1269
+ ...root,
1270
+ "aria-busy": page?.url !== url || void 0,
1271
+ children: page?.url !== url ? /* @__PURE__ */ jsx("p", {
1272
+ className: "aidy-muted",
1273
+ children: t("loading")
1274
+ }) : "failed" in page ? /* @__PURE__ */ jsx("p", {
1275
+ className: "aidy-error",
1276
+ role: "alert",
1277
+ children: t("loadFailed")
1278
+ }) : /* @__PURE__ */ jsx(Markdown, {
1279
+ text: page.text,
1280
+ baseUrl: absolute
1281
+ })
1282
+ });
1283
+ }
1284
+ // src/palette.tsx
1285
+ /** Renders an excerpt with its `«…»` matches highlighted. */
1286
+ function Excerpt({ text }) {
1287
+ const parts = text.split(/«([^»]*)»/).map((part, index) => index % 2 === 1 ? /* @__PURE__ */ jsx("mark", { children: part }, index) : part);
1288
+ return /* @__PURE__ */ jsx("span", {
1289
+ className: "aidy-hit-excerpt",
1290
+ children: parts
1291
+ });
1292
+ }
1293
+ function group(hits) {
1294
+ const groups = /* @__PURE__ */ new Map();
1295
+ for (const hit of hits) groups.set(hit.type, [...groups.get(hit.type) ?? [], hit]);
1296
+ return [...groups];
1297
+ }
1298
+ /**
1299
+ * ⌘K / Ctrl+K search over every source, grouped by type. Arrow keys move, Enter opens, and the
1300
+ * last row hands the query to Aidy in the dock.
1301
+ */
1302
+ function SearchPalette() {
1303
+ const { t, navigate, askAidy } = useAidy();
1304
+ const root = useRoot("aidy-palette-root");
1305
+ const [open, setOpen] = useState(false);
1306
+ const [query, setQuery] = useState("");
1307
+ const [active, setActive] = useState(0);
1308
+ const { result, loading } = useSearch(open ? query : "");
1309
+ const input = useRef(null);
1310
+ const returnFocus = useRef(null);
1311
+ const listId = useId();
1312
+ useEffect(() => {
1313
+ const onKey = (event) => {
1314
+ if (event.key.toLowerCase() === "k" && (event.metaKey || event.ctrlKey) && !event.altKey) {
1315
+ event.preventDefault();
1316
+ setOpen((current) => !current);
1317
+ }
1318
+ };
1319
+ window.addEventListener("keydown", onKey);
1320
+ return () => window.removeEventListener("keydown", onKey);
1321
+ }, []);
1322
+ useEffect(() => {
1323
+ if (open) {
1324
+ returnFocus.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;
1325
+ input.current?.focus();
1326
+ } else {
1327
+ setQuery("");
1328
+ returnFocus.current?.focus();
1329
+ returnFocus.current = null;
1330
+ }
1331
+ }, [open]);
1332
+ useEffect(() => setActive(0), [result]);
1333
+ if (!open) return null;
1334
+ const groups = group(result?.hits ?? []);
1335
+ const rows = [...groups.flatMap(([, hits]) => hits.map((hit) => ({
1336
+ kind: "hit",
1337
+ hit
1338
+ }))), ...query.trim() ? [{ kind: "ask" }] : []];
1339
+ const optionId = (index) => `${listId}-${index}`;
1340
+ const choose = (row) => {
1341
+ if (!row) return;
1342
+ setOpen(false);
1343
+ if (row.kind === "ask") askAidy(query.trim());
1344
+ else navigate(row.hit.url);
1345
+ };
1346
+ const onKeyDown = (event) => {
1347
+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {
1348
+ event.preventDefault();
1349
+ if (rows.length === 0) return;
1350
+ const step = event.key === "ArrowDown" ? 1 : -1;
1351
+ setActive((current) => (current + step + rows.length) % rows.length);
1352
+ } else if (event.key === "Enter" && !event.nativeEvent.isComposing) {
1353
+ event.preventDefault();
1354
+ choose(rows[active]);
1355
+ } else if (event.key === "Escape") {
1356
+ event.preventDefault();
1357
+ setOpen(false);
1358
+ }
1359
+ };
1360
+ let index = -1;
1361
+ const option = (row, content) => {
1362
+ index += 1;
1363
+ const at = index;
1364
+ return /* @__PURE__ */ jsx("div", {
1365
+ id: optionId(at),
1366
+ role: "option",
1367
+ tabIndex: -1,
1368
+ "aria-selected": at === active,
1369
+ className: "aidy-option",
1370
+ onMouseMove: () => setActive(at),
1371
+ onMouseDown: (event) => event.preventDefault(),
1372
+ onClick: () => choose(row),
1373
+ children: content
1374
+ }, row.kind === "ask" ? "ask" : `${row.hit.type}:${row.hit.id}`);
1375
+ };
1376
+ return /* @__PURE__ */ jsxs("div", {
1377
+ ...root,
1378
+ children: [/* @__PURE__ */ jsx("div", {
1379
+ className: "aidy-overlay",
1380
+ onMouseDown: () => setOpen(false)
1381
+ }), /* @__PURE__ */ jsxs("div", {
1382
+ className: "aidy-palette",
1383
+ role: "dialog",
1384
+ "aria-modal": "true",
1385
+ "aria-label": t("searchLabel"),
1386
+ children: [
1387
+ /* @__PURE__ */ jsx("input", {
1388
+ ref: input,
1389
+ className: "aidy-palette-input",
1390
+ role: "combobox",
1391
+ "aria-expanded": rows.length > 0,
1392
+ "aria-controls": listId,
1393
+ "aria-activedescendant": rows.length > 0 ? optionId(active) : void 0,
1394
+ "aria-autocomplete": "list",
1395
+ "aria-label": t("searchLabel"),
1396
+ placeholder: t("searchPlaceholder"),
1397
+ value: query,
1398
+ onChange: (event) => setQuery(event.target.value),
1399
+ onKeyDown
1400
+ }),
1401
+ /* @__PURE__ */ jsxs("div", {
1402
+ id: listId,
1403
+ role: "listbox",
1404
+ className: "aidy-options",
1405
+ "aria-label": t("searchLabel"),
1406
+ children: [groups.map(([type, hits]) => /* @__PURE__ */ jsxs("div", {
1407
+ role: "group",
1408
+ "aria-label": type,
1409
+ children: [/* @__PURE__ */ jsx("p", {
1410
+ className: "aidy-group",
1411
+ "aria-hidden": "true",
1412
+ children: type
1413
+ }), hits.map((hit) => option({
1414
+ kind: "hit",
1415
+ hit
1416
+ }, /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("span", {
1417
+ className: "aidy-hit-title",
1418
+ children: hit.title
1419
+ }), hit.excerpt ? /* @__PURE__ */ jsx(Excerpt, { text: hit.excerpt }) : null] })))]
1420
+ }, type)), query.trim() ? option({ kind: "ask" }, /* @__PURE__ */ jsxs("span", {
1421
+ className: "aidy-ask",
1422
+ children: [
1423
+ /* @__PURE__ */ jsx("span", {
1424
+ "aria-hidden": "true",
1425
+ children: "✦ "
1426
+ }),
1427
+ t("askAidy"),
1428
+ ": ",
1429
+ /* @__PURE__ */ jsx("q", { children: query.trim() })
1430
+ ]
1431
+ })) : null]
1432
+ }),
1433
+ /* @__PURE__ */ jsxs("div", {
1434
+ className: "aidy-palette-status",
1435
+ role: "status",
1436
+ children: [
1437
+ loading ? t("searching") : null,
1438
+ !loading && result && result.hits.length === 0 ? t("noResults") : null,
1439
+ result && result.failed.length > 0 ? /* @__PURE__ */ jsxs("span", {
1440
+ className: "aidy-muted",
1441
+ children: [" ", t("failedSources", { sources: result.failed.map((failure) => failure.source).join(", ") })]
1442
+ }) : null
1443
+ ]
1444
+ })
1445
+ ]
1446
+ })]
1447
+ });
1448
+ }
1449
+ // src/settings.tsx
1450
+ const PROVIDERS = [
1451
+ "openai-compatible",
1452
+ "openai",
1453
+ "anthropic"
1454
+ ];
1455
+ let nextKey = 0;
1456
+ const row = (endpoint) => ({
1457
+ key: nextKey++,
1458
+ endpoint,
1459
+ apiKey: ""
1460
+ });
1461
+ function update({ endpoint, apiKey }) {
1462
+ const { hasApiKey: _, ...fields } = endpoint;
1463
+ return apiKey ? {
1464
+ ...fields,
1465
+ apiKey
1466
+ } : fields;
1467
+ }
1468
+ /** The admin form for the model chain. Keys are write-only: it shows whether one is stored. */
1469
+ function ModelSettings() {
1470
+ const { client, t } = useAidy();
1471
+ const root = useRoot("aidy-settings");
1472
+ const baseId = useId();
1473
+ const [rows, setRows] = useState(null);
1474
+ const [status, setStatus] = useState("idle");
1475
+ useEffect(() => {
1476
+ let live = true;
1477
+ client.getSettings().then((settings) => live && setRows(settings.models.chain.map(row)), (error) => live && setStatus({ failed: error instanceof AidyRequestError ? String(error.status) : "—" }));
1478
+ return () => {
1479
+ live = false;
1480
+ };
1481
+ }, [client]);
1482
+ const edit = (index, change) => {
1483
+ setStatus("idle");
1484
+ setRows((current) => (current ?? []).map((item, at) => at === index ? change(item) : item));
1485
+ };
1486
+ const field = (index, fields) => edit(index, (item) => ({
1487
+ ...item,
1488
+ endpoint: {
1489
+ ...item.endpoint,
1490
+ ...fields
1491
+ }
1492
+ }));
1493
+ const move = (index, by) => {
1494
+ setStatus("idle");
1495
+ setRows((current) => {
1496
+ const next = [...current ?? []];
1497
+ const [item] = next.splice(index, 1);
1498
+ if (item) next.splice(index + by, 0, item);
1499
+ return next;
1500
+ });
1501
+ };
1502
+ const save = async (event) => {
1503
+ event.preventDefault();
1504
+ if (!rows) return;
1505
+ setStatus("saving");
1506
+ try {
1507
+ const saved = await client.putSettings({ models: { chain: rows.map(update) } });
1508
+ setRows(saved.models.chain.map(row));
1509
+ setStatus("saved");
1510
+ } catch (error) {
1511
+ setStatus({ failed: error instanceof AidyRequestError ? String(error.status) : "—" });
1512
+ }
1513
+ };
1514
+ return /* @__PURE__ */ jsxs("form", {
1515
+ ...root,
1516
+ onSubmit: save,
1517
+ "aria-labelledby": `${baseId}-title`,
1518
+ children: [
1519
+ /* @__PURE__ */ jsx("h2", {
1520
+ id: `${baseId}-title`,
1521
+ className: "aidy-settings-title",
1522
+ children: t("models")
1523
+ }),
1524
+ /* @__PURE__ */ jsx("p", {
1525
+ className: "aidy-muted",
1526
+ children: t("modelsHint")
1527
+ }),
1528
+ rows === null && status === "idle" ? /* @__PURE__ */ jsx("p", {
1529
+ className: "aidy-muted",
1530
+ children: t("loading")
1531
+ }) : null,
1532
+ /* @__PURE__ */ jsx("ol", {
1533
+ className: "aidy-chain",
1534
+ children: (rows ?? []).map((item, index) => {
1535
+ const id = `${baseId}-${item.key}`;
1536
+ const { endpoint } = item;
1537
+ return /* @__PURE__ */ jsxs("li", {
1538
+ className: "aidy-card aidy-endpoint",
1539
+ children: [/* @__PURE__ */ jsxs("div", {
1540
+ className: "aidy-endpoint-head",
1541
+ children: [
1542
+ /* @__PURE__ */ jsx("span", {
1543
+ className: "aidy-endpoint-index",
1544
+ children: index + 1
1545
+ }),
1546
+ /* @__PURE__ */ jsx("span", {
1547
+ className: "aidy-endpoint-name",
1548
+ children: endpoint.model || "—"
1549
+ }),
1550
+ /* @__PURE__ */ jsx("button", {
1551
+ type: "button",
1552
+ className: "aidy-icon-button",
1553
+ "aria-label": `${t("moveUp")}: ${endpoint.model}`,
1554
+ disabled: index === 0,
1555
+ onClick: () => move(index, -1),
1556
+ children: "↑"
1557
+ }),
1558
+ /* @__PURE__ */ jsx("button", {
1559
+ type: "button",
1560
+ className: "aidy-icon-button",
1561
+ "aria-label": `${t("moveDown")}: ${endpoint.model}`,
1562
+ disabled: index === (rows?.length ?? 0) - 1,
1563
+ onClick: () => move(index, 1),
1564
+ children: "↓"
1565
+ }),
1566
+ /* @__PURE__ */ jsx("button", {
1567
+ type: "button",
1568
+ className: "aidy-icon-button",
1569
+ "aria-label": `${t("remove")}: ${endpoint.model}`,
1570
+ onClick: () => {
1571
+ setStatus("idle");
1572
+ setRows((current) => (current ?? []).filter((_, at) => at !== index));
1573
+ },
1574
+ children: "×"
1575
+ })
1576
+ ]
1577
+ }), /* @__PURE__ */ jsxs("div", {
1578
+ className: "aidy-fields",
1579
+ children: [
1580
+ /* @__PURE__ */ jsx("label", {
1581
+ htmlFor: `${id}-provider`,
1582
+ className: "aidy-label",
1583
+ children: t("provider")
1584
+ }),
1585
+ /* @__PURE__ */ jsx("select", {
1586
+ id: `${id}-provider`,
1587
+ className: "aidy-input",
1588
+ value: endpoint.provider,
1589
+ onChange: (event) => field(index, { provider: event.target.value }),
1590
+ children: PROVIDERS.map((provider) => /* @__PURE__ */ jsx("option", {
1591
+ value: provider,
1592
+ children: provider
1593
+ }, provider))
1594
+ }),
1595
+ /* @__PURE__ */ jsx("label", {
1596
+ htmlFor: `${id}-model`,
1597
+ className: "aidy-label",
1598
+ children: t("model")
1599
+ }),
1600
+ /* @__PURE__ */ jsx("input", {
1601
+ id: `${id}-model`,
1602
+ className: "aidy-input",
1603
+ required: true,
1604
+ value: endpoint.model,
1605
+ onChange: (event) => field(index, { model: event.target.value })
1606
+ }),
1607
+ /* @__PURE__ */ jsx("label", {
1608
+ htmlFor: `${id}-base`,
1609
+ className: "aidy-label",
1610
+ children: t("baseURL")
1611
+ }),
1612
+ /* @__PURE__ */ jsx("input", {
1613
+ id: `${id}-base`,
1614
+ className: "aidy-input",
1615
+ type: "url",
1616
+ value: endpoint.baseURL ?? "",
1617
+ onChange: (event) => {
1618
+ const value = event.target.value;
1619
+ edit(index, (other) => {
1620
+ const { baseURL: _, ...rest } = other.endpoint;
1621
+ return {
1622
+ ...other,
1623
+ endpoint: value ? {
1624
+ ...rest,
1625
+ baseURL: value
1626
+ } : rest
1627
+ };
1628
+ });
1629
+ }
1630
+ }),
1631
+ /* @__PURE__ */ jsx("label", {
1632
+ htmlFor: `${id}-key`,
1633
+ className: "aidy-label",
1634
+ children: t("apiKey")
1635
+ }),
1636
+ /* @__PURE__ */ jsx("input", {
1637
+ id: `${id}-key`,
1638
+ className: "aidy-input",
1639
+ type: "password",
1640
+ autoComplete: "off",
1641
+ placeholder: endpoint.hasApiKey ? t("apiKeySaved") : "",
1642
+ value: item.apiKey,
1643
+ onChange: (event) => edit(index, (other) => ({
1644
+ ...other,
1645
+ apiKey: event.target.value
1646
+ }))
1647
+ }),
1648
+ /* @__PURE__ */ jsx("span", {}),
1649
+ /* @__PURE__ */ jsxs("label", {
1650
+ className: "aidy-choice",
1651
+ children: [/* @__PURE__ */ jsx("input", {
1652
+ type: "checkbox",
1653
+ checked: endpoint.vision ?? false,
1654
+ onChange: (event) => field(index, { vision: event.target.checked })
1655
+ }), /* @__PURE__ */ jsx("span", { children: t("vision") })]
1656
+ })
1657
+ ]
1658
+ })]
1659
+ }, item.key);
1660
+ })
1661
+ }),
1662
+ /* @__PURE__ */ jsxs("div", {
1663
+ className: "aidy-actions",
1664
+ children: [
1665
+ /* @__PURE__ */ jsx("span", {
1666
+ className: "aidy-small",
1667
+ role: "status",
1668
+ children: status === "saved" ? t("saved") : typeof status === "object" ? t("saveFailed", { status: status.failed }) : null
1669
+ }),
1670
+ /* @__PURE__ */ jsx("button", {
1671
+ type: "button",
1672
+ className: "aidy-button",
1673
+ disabled: rows === null,
1674
+ onClick: () => setRows((current) => [...current ?? [], row({
1675
+ provider: "openai-compatible",
1676
+ model: "",
1677
+ hasApiKey: false
1678
+ })]),
1679
+ children: t("addModel")
1680
+ }),
1681
+ /* @__PURE__ */ jsx("button", {
1682
+ type: "submit",
1683
+ className: "aidy-button aidy-primary",
1684
+ disabled: rows === null || status === "saving",
1685
+ children: t("save")
1686
+ })
1687
+ ]
1688
+ })
1689
+ ]
1690
+ });
1691
+ }
1692
+ export { AidyDock, AidyForm, AidyProvider, AidyThread, ApprovalCard, HelpViewer, Markdown, ModelSettings, SearchPalette, useCatalog, useDock, useSearch, useThread, useThreads };