coder-agent 0.1.0__py3-none-any.whl

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 (163) hide show
  1. coder_agent-0.1.0.dist-info/METADATA +262 -0
  2. coder_agent-0.1.0.dist-info/RECORD +163 -0
  3. coder_agent-0.1.0.dist-info/WHEEL +5 -0
  4. coder_agent-0.1.0.dist-info/entry_points.txt +2 -0
  5. coder_agent-0.1.0.dist-info/licenses/LICENSE.md +21 -0
  6. coder_agent-0.1.0.dist-info/top_level.txt +1 -0
  7. coderagent/__init__.py +20 -0
  8. coderagent/compat/__init__.py +27 -0
  9. coderagent/compat/cache_control.py +69 -0
  10. coderagent/compat/config_spec.py +60 -0
  11. coderagent/compat/exceptions.py +20 -0
  12. coderagent/compat/retry.py +27 -0
  13. coderagent/compat/serialize.py +31 -0
  14. coderagent/config/__init__.py +1 -0
  15. coderagent/config/defaults.yaml +103 -0
  16. coderagent/config/loader.py +264 -0
  17. coderagent/config/schema.py +548 -0
  18. coderagent/config/writer.py +218 -0
  19. coderagent/core/__init__.py +1 -0
  20. coderagent/core/budget.py +47 -0
  21. coderagent/core/capabilities.py +136 -0
  22. coderagent/core/checkpoint.py +164 -0
  23. coderagent/core/content.py +156 -0
  24. coderagent/core/context.py +618 -0
  25. coderagent/core/events.py +83 -0
  26. coderagent/core/history.py +56 -0
  27. coderagent/core/instructions.py +99 -0
  28. coderagent/core/loop.py +702 -0
  29. coderagent/core/memory.py +56 -0
  30. coderagent/core/mentions.py +81 -0
  31. coderagent/core/os_sandbox.py +191 -0
  32. coderagent/core/otel.py +214 -0
  33. coderagent/core/protocols.py +38 -0
  34. coderagent/core/redact.py +49 -0
  35. coderagent/core/sandbox.py +82 -0
  36. coderagent/core/schema.py +107 -0
  37. coderagent/core/session.py +344 -0
  38. coderagent/core/shell_env.py +74 -0
  39. coderagent/core/subagent.py +474 -0
  40. coderagent/core/summarize.py +312 -0
  41. coderagent/core/telemetry.py +209 -0
  42. coderagent/core/tokens.py +132 -0
  43. coderagent/core/trust.py +301 -0
  44. coderagent/environments/__init__.py +11 -0
  45. coderagent/environments/bubblewrap.py +150 -0
  46. coderagent/environments/contree.py +146 -0
  47. coderagent/environments/docker.py +160 -0
  48. coderagent/environments/local.py +110 -0
  49. coderagent/environments/singularity.py +138 -0
  50. coderagent/environments/swerex_docker.py +79 -0
  51. coderagent/environments/swerex_modal.py +123 -0
  52. coderagent/eval/__init__.py +1 -0
  53. coderagent/eval/compare.py +190 -0
  54. coderagent/eval/report.py +141 -0
  55. coderagent/eval/runner.py +368 -0
  56. coderagent/eval/task.py +194 -0
  57. coderagent/extensions/__init__.py +1 -0
  58. coderagent/extensions/hooks.py +121 -0
  59. coderagent/extensions/plugins.py +217 -0
  60. coderagent/extensions/reflect.py +342 -0
  61. coderagent/models/__init__.py +33 -0
  62. coderagent/models/backends.py +218 -0
  63. coderagent/models/call.py +18 -0
  64. coderagent/models/check.py +139 -0
  65. coderagent/models/gateway.py +60 -0
  66. coderagent/models/litellm_config.py +70 -0
  67. coderagent/models/provider.py +98 -0
  68. coderagent/models/reasoning.py +28 -0
  69. coderagent/models/router.py +136 -0
  70. coderagent/models/settings.py +172 -0
  71. coderagent/models/streaming.py +122 -0
  72. coderagent/models/verbosity.py +14 -0
  73. coderagent/paths.py +31 -0
  74. coderagent/run.py +454 -0
  75. coderagent/skills/__init__.py +119 -0
  76. coderagent/skills/errors.py +11 -0
  77. coderagent/skills/install.py +340 -0
  78. coderagent/skills/presets/code-review/SKILL.md +35 -0
  79. coderagent/skills/presets/codebase-onboarding/SKILL.md +33 -0
  80. coderagent/skills/presets/data-analysis/SKILL.md +35 -0
  81. coderagent/skills/presets/deep-research/SKILL.md +38 -0
  82. coderagent/skills/presets/frontend-dev/SKILL.md +32 -0
  83. coderagent/skills/presets/long-document/SKILL.md +37 -0
  84. coderagent/skills/presets/long-document/scripts/pdf_text.py +37 -0
  85. coderagent/skills/presets/office-docx/SKILL.md +36 -0
  86. coderagent/skills/presets/office-docx/scripts/docx_text.py +36 -0
  87. coderagent/skills/presets/office-pptx/SKILL.md +32 -0
  88. coderagent/skills/presets/office-xlsx/SKILL.md +34 -0
  89. coderagent/skills/presets/office-xlsx/scripts/xlsx_text.py +72 -0
  90. coderagent/skills/presets/writing/SKILL.md +31 -0
  91. coderagent/skills/sandbox.py +269 -0
  92. coderagent/skills/sites.py +177 -0
  93. coderagent/skills/source.py +404 -0
  94. coderagent/testing/__init__.py +5 -0
  95. coderagent/testing/factory.py +59 -0
  96. coderagent/testing/scripted_model.py +54 -0
  97. coderagent/tools/__init__.py +1 -0
  98. coderagent/tools/base.py +54 -0
  99. coderagent/tools/bash_policy.py +486 -0
  100. coderagent/tools/builtin/__init__.py +35 -0
  101. coderagent/tools/builtin/fs.py +283 -0
  102. coderagent/tools/builtin/patch.py +279 -0
  103. coderagent/tools/builtin/search.py +242 -0
  104. coderagent/tools/builtin/shell.py +336 -0
  105. coderagent/tools/builtin/skill.py +41 -0
  106. coderagent/tools/builtin/task.py +53 -0
  107. coderagent/tools/builtin/todo.py +63 -0
  108. coderagent/tools/executor.py +243 -0
  109. coderagent/tools/mcp.py +317 -0
  110. coderagent/tools/permissions.py +472 -0
  111. coderagent/tools/registry.py +83 -0
  112. coderagent/tools/rules.py +138 -0
  113. coderagent/ui/__init__.py +1 -0
  114. coderagent/ui/cli.py +498 -0
  115. coderagent/ui/commands/__init__.py +109 -0
  116. coderagent/ui/commands/builtin.py +778 -0
  117. coderagent/ui/commands/compact.py +12 -0
  118. coderagent/ui/commands/resume.py +26 -0
  119. coderagent/ui/commands/review.py +73 -0
  120. coderagent/ui/commands/rewind.py +28 -0
  121. coderagent/ui/custom_commands.py +179 -0
  122. coderagent/ui/notify.py +46 -0
  123. coderagent/ui/open_file.py +48 -0
  124. coderagent/ui/render.py +62 -0
  125. coderagent/ui/spinner.py +68 -0
  126. coderagent/ui/tui.py +610 -0
  127. coderagent/ui/widgets/__init__.py +29 -0
  128. coderagent/ui/widgets/approval_prompt.py +129 -0
  129. coderagent/ui/widgets/diff_view.py +97 -0
  130. coderagent/ui/widgets/file_tree.py +105 -0
  131. coderagent/ui/widgets/markdown_message.py +44 -0
  132. coderagent/ui/widgets/markup.py +10 -0
  133. coderagent/ui/widgets/message_block.py +61 -0
  134. coderagent/ui/widgets/path_suggester.py +66 -0
  135. coderagent/ui/widgets/session_picker.py +49 -0
  136. coderagent/ui/widgets/status_bar.py +44 -0
  137. coderagent/ui/widgets/todo_panel.py +40 -0
  138. coderagent/ui/widgets/tool_card.py +104 -0
  139. coderagent/ui/widgets/working_dots.py +26 -0
  140. coderagent/version.py +7 -0
  141. coderagent/web/__init__.py +5 -0
  142. coderagent/web/api.py +449 -0
  143. coderagent/web/app.py +113 -0
  144. coderagent/web/approver.py +73 -0
  145. coderagent/web/config_api.py +53 -0
  146. coderagent/web/events.py +159 -0
  147. coderagent/web/files.py +115 -0
  148. coderagent/web/i18n.py +346 -0
  149. coderagent/web/server.py +100 -0
  150. coderagent/web/sessions.py +404 -0
  151. coderagent/web/skills_api.py +376 -0
  152. coderagent/web/static/app.css +283 -0
  153. coderagent/web/static/app.js +1466 -0
  154. coderagent/web/templates/en/base.html +31 -0
  155. coderagent/web/templates/en/chat.html +60 -0
  156. coderagent/web/templates/en/macros.html +9 -0
  157. coderagent/web/templates/en/settings.html +80 -0
  158. coderagent/web/templates/en/skills.html +64 -0
  159. coderagent/web/templates/zh/base.html +31 -0
  160. coderagent/web/templates/zh/chat.html +60 -0
  161. coderagent/web/templates/zh/macros.html +9 -0
  162. coderagent/web/templates/zh/settings.html +77 -0
  163. coderagent/web/templates/zh/skills.html +61 -0
@@ -0,0 +1,1466 @@
1
+ "use strict";
2
+
3
+ const CLIENT = { "X-Coder-Client": "1" };
4
+
5
+ /* The strings of the language of the page. The template hands them over. */
6
+ function t(key, values = {}) {
7
+ const text = (window.STRINGS || {})[key] || key;
8
+ return text.replace(/\{(\w+)\}/g, (match, name) => (name in values ? values[name] : match));
9
+ }
10
+
11
+ /* The money of a session. A model without a price spends no money: the cost
12
+ is unknown, not zero. */
13
+ function money(cost, priced) {
14
+ return priced === false ? "$?" : `$${(cost || 0).toFixed(4)}`;
15
+ }
16
+
17
+ const MODE_NOTES = {
18
+ default: "mode_default",
19
+ acceptEdits: "mode_acceptEdits",
20
+ plan: "mode_plan",
21
+ readonly: "mode_readonly",
22
+ bypass: "mode_bypass",
23
+ };
24
+
25
+ /* The reasons a turn may end before the agent is done. The others end well. */
26
+ const STOP_NOTES = {
27
+ max_turns: "stop_max_turns",
28
+ cost_exceeded: "stop_cost_exceeded",
29
+ token_limit: "stop_token_limit",
30
+ interrupted: "stop_interrupted",
31
+ };
32
+
33
+ /* The dots that say the agent is still working. The server hands them over:
34
+ the same animation as in the terminal. */
35
+ const DOT_FRAMES = window.DOT_FRAMES || [".", "..", "...", ".."];
36
+
37
+ const state = {
38
+ sessionId: null,
39
+ seq: 0,
40
+ stream: null,
41
+ cards: {},
42
+ assistant: null,
43
+ current: null,
44
+ stick: true,
45
+ attention: null,
46
+ mode: "",
47
+ images: [],
48
+ working: null,
49
+ workingTimer: null,
50
+ };
51
+
52
+ function el(tag, className, text) {
53
+ const node = document.createElement(tag);
54
+ if (className) node.className = className;
55
+ if (text !== undefined) node.textContent = text;
56
+ return node;
57
+ }
58
+
59
+ async function api(path, options = {}) {
60
+ const opts = Object.assign({}, options, {
61
+ headers: Object.assign({ "X-Coder-Client": "1" }, options.headers || {}),
62
+ });
63
+ if (opts.body && typeof opts.body !== "string") {
64
+ opts.headers["Content-Type"] = "application/json";
65
+ opts.body = JSON.stringify(opts.body);
66
+ }
67
+ const response = await fetch(path, opts);
68
+ const text = await response.text();
69
+ if (!response.ok) throw new Error(detailOf(text) || `${response.status}`);
70
+ return text ? JSON.parse(text) : null;
71
+ }
72
+
73
+ /* The reason of a failure: the server says it in `detail`. */
74
+ function detailOf(text) {
75
+ try {
76
+ return JSON.parse(text).detail || "";
77
+ } catch (error) {
78
+ return "";
79
+ }
80
+ }
81
+
82
+ // -- the conversation ------------------------------------------------------
83
+
84
+ function messages() {
85
+ return document.getElementById("messages");
86
+ }
87
+
88
+ /* The items of the turn that is running. The turns before it are folded away. */
89
+ function target() {
90
+ if (!state.current) {
91
+ state.current = el("div", "turn");
92
+ messages().appendChild(state.current);
93
+ }
94
+ return state.current;
95
+ }
96
+
97
+ function foldTurn() {
98
+ const done = state.current;
99
+ state.current = null;
100
+ if (!done) return;
101
+ let history = document.getElementById("history");
102
+ if (!history) {
103
+ history = el("details", "history");
104
+ history.id = "history";
105
+ history.appendChild(el("summary", "", t("history")));
106
+ history.appendChild(el("div", "history-body"));
107
+ messages().insertBefore(history, messages().firstChild);
108
+ }
109
+ history.querySelector(".history-body").appendChild(done);
110
+ const count = history.querySelectorAll(".turn").length;
111
+ history.querySelector("summary").textContent = t("earlier_turns", { count });
112
+ /* A new turn folds the history again: the conversation of the turn that
113
+ runs is what the user looks at. */
114
+ history.open = false;
115
+ }
116
+
117
+ /* The conversation follows the newest content, unless the user scrolled up. */
118
+ function scrollToBottom(force) {
119
+ const box = messages();
120
+ if (!box) return;
121
+ /* While a card waits for an answer, the view stays with the card and not
122
+ with the newest content. */
123
+ if (state.attention) {
124
+ keepAttention();
125
+ return;
126
+ }
127
+ if (force || state.stick) box.scrollTop = box.scrollHeight;
128
+ }
129
+
130
+ /* The card that waits for an answer is put in the middle of the view, so that
131
+ the user does not have to look for it. */
132
+ function scrollToCard(card) {
133
+ const box = messages();
134
+ if (!box || !card) return;
135
+ const top = card.getBoundingClientRect().top - box.getBoundingClientRect().top + box.scrollTop;
136
+ const wanted = Math.max(0, top - (box.clientHeight - card.offsetHeight) / 2);
137
+ box.scrollTo({ top: wanted, behavior: "smooth" });
138
+ }
139
+
140
+ /* Whether the whole of a node is in the view of the conversation. */
141
+ function inView(box, node) {
142
+ const one = node.getBoundingClientRect();
143
+ const other = box.getBoundingClientRect();
144
+ return one.top >= other.top && one.bottom <= other.bottom;
145
+ }
146
+
147
+ /* The card that waits for an answer stays in view while the rest arrives. */
148
+ function keepAttention() {
149
+ const box = messages();
150
+ if (!box || !state.attention) return;
151
+ if (!inView(box, state.attention)) scrollToCard(state.attention);
152
+ }
153
+
154
+ /* The button that jumps to the newest content. It shows when the user scrolled up. */
155
+ function showLatest() {
156
+ const button = document.getElementById("to-latest");
157
+ if (button) button.hidden = state.stick;
158
+ }
159
+
160
+ function bubble(className, text) {
161
+ const node = el("div", `bubble ${className}`, text || "");
162
+ target().appendChild(node);
163
+ scrollToBottom();
164
+ return node;
165
+ }
166
+
167
+ /* The sign that the agent is still working: the dots grow and shrink. */
168
+ function showWorking() {
169
+ if (state.working) return;
170
+ state.working = bubble("working", DOT_FRAMES[0]);
171
+ let step = 0;
172
+ state.workingTimer = setInterval(() => {
173
+ step += 1;
174
+ state.working.textContent = DOT_FRAMES[step % DOT_FRAMES.length];
175
+ }, 400);
176
+ }
177
+
178
+ /* The agent said something: the dots go away. */
179
+ function hideWorking() {
180
+ if (!state.working) return;
181
+ clearInterval(state.workingTimer);
182
+ state.workingTimer = null;
183
+ state.working.remove();
184
+ state.working = null;
185
+ }
186
+
187
+ function toolCard(item) {
188
+ const card = el("div", "tool");
189
+ const header = el("header");
190
+ header.appendChild(el("strong", "", item.tool || t("tool")));
191
+ if (item.summary) header.appendChild(el("span", "", item.summary));
192
+ card.appendChild(header);
193
+ const body = el("div", "body", DOT_FRAMES[0]);
194
+ card.appendChild(body);
195
+ target().appendChild(card);
196
+ let step = 0;
197
+ /* The tool is running: the dots grow and shrink until it is done. */
198
+ card.timer = setInterval(() => {
199
+ step += 1;
200
+ body.textContent = DOT_FRAMES[step % DOT_FRAMES.length];
201
+ }, 400);
202
+ scrollToBottom();
203
+ return card;
204
+ }
205
+
206
+ function fillTool(card, item) {
207
+ if (!card) return;
208
+ if (card.timer) {
209
+ clearInterval(card.timer);
210
+ card.timer = null;
211
+ }
212
+ const body = card.querySelector(".body");
213
+ body.className = `body ${item.is_error ? "bad" : "ok"}`;
214
+ if (item.diff) {
215
+ body.innerHTML = "";
216
+ body.appendChild(diffView(item.diff));
217
+ } else {
218
+ body.textContent = item.content || "";
219
+ }
220
+ /* the output of a tool can be long: the view follows it */
221
+ scrollToBottom();
222
+ }
223
+
224
+ function diffView(diff) {
225
+ const pre = el("pre", "diff");
226
+ for (const line of diff.split("\n")) {
227
+ let cls = "";
228
+ if (line.startsWith("+")) cls = "add";
229
+ else if (line.startsWith("-")) cls = "del";
230
+ else if (line.startsWith("@@") || line.startsWith("---") || line.startsWith("+++")) cls = "meta";
231
+ pre.appendChild(el("div", cls, line));
232
+ }
233
+ return pre;
234
+ }
235
+
236
+ function renderApproval(item) {
237
+ const card = el("div", "tool approval");
238
+ const header = el("header");
239
+ header.appendChild(el("strong", "", t("approval", { tool: item.tool })));
240
+ if (item.reason) header.appendChild(el("span", "", item.reason));
241
+ card.appendChild(header);
242
+ const body = el("div", "body", JSON.stringify(item.params || {}, null, 2));
243
+ card.appendChild(body);
244
+ const buttons = el("div", "buttons");
245
+ for (const [label, decision] of [[t("allow"), "allow"], [t("deny"), "deny"], [t("always"), "always"]]) {
246
+ const button = el("button", decision === "allow" ? "primary" : "", label);
247
+ button.onclick = async () => {
248
+ buttons.innerHTML = "";
249
+ buttons.appendChild(el("span", "", t("answered")));
250
+ card.classList.remove("attention");
251
+ if (state.attention === card) state.attention = null;
252
+ try {
253
+ await api(`/api/approvals/${item.id}`, { method: "POST", body: { decision } });
254
+ } catch (error) {
255
+ buttons.appendChild(el("span", "", t("error", { message: error.message })));
256
+ }
257
+ };
258
+ buttons.appendChild(button);
259
+ }
260
+ card.appendChild(buttons);
261
+ target().appendChild(card);
262
+ state.attention = card;
263
+ card.classList.add("attention");
264
+ scrollToCard(card);
265
+ return card;
266
+ }
267
+
268
+ function renderTodos(todos) {
269
+ const turn = target();
270
+ let panel = turn.querySelector(".todos");
271
+ if (!panel) {
272
+ panel = el("div", "todos");
273
+ turn.appendChild(panel);
274
+ }
275
+ panel.innerHTML = "";
276
+ for (const todo of todos || []) {
277
+ panel.appendChild(el("div", todo.status === "completed" ? "done" : "", todo.content || ""));
278
+ }
279
+ scrollToBottom();
280
+ }
281
+
282
+ function render(item) {
283
+ switch (item.kind) {
284
+ case "user_message": {
285
+ foldTurn();
286
+ const original = item.original || "";
287
+ const node = bubble("user", original || item.text || item.content);
288
+ for (const url of item.images || []) {
289
+ const image = el("img", "attached");
290
+ image.src = url;
291
+ image.alt = "";
292
+ node.appendChild(image);
293
+ }
294
+ if (original && original !== item.content) {
295
+ /* a hook rewrote the prompt: the browser shows what the user typed, and what the model got */
296
+ const note = el("div", "rewritten", t("rewritten", { text: item.content }));
297
+ target().appendChild(note);
298
+ scrollToBottom();
299
+ }
300
+ state.assistant = null;
301
+ break;
302
+ }
303
+ case "assistant_message": {
304
+ const content = item.content || "";
305
+ hideWorking();
306
+ if (state.assistant) {
307
+ /* the answer was streamed into this bubble; the message is the whole of it */
308
+ state.assistant.textContent = content;
309
+ state.assistant = null;
310
+ scrollToBottom();
311
+ break;
312
+ }
313
+ bubble("assistant", content);
314
+ state.assistant = null;
315
+ break;
316
+ }
317
+ case "text_delta": {
318
+ hideWorking();
319
+ if (!state.assistant) {
320
+ state.assistant = bubble("assistant", "");
321
+ }
322
+ state.assistant.textContent += item.content;
323
+ scrollToBottom();
324
+ break;
325
+ }
326
+ case "reasoning_delta":
327
+ case "reasoning":
328
+ break;
329
+ case "tool_call":
330
+ hideWorking();
331
+ state.cards[item.tool_call_id] = toolCard(item);
332
+ break;
333
+ case "tool_result":
334
+ fillTool(state.cards[item.tool_call_id], item);
335
+ break;
336
+ case "approval_request":
337
+ state.cards[`approval-${item.id}`] = renderApproval(item);
338
+ break;
339
+ case "approval_response": {
340
+ const card = state.cards[`approval-${item.id}`];
341
+ if (card) {
342
+ card.classList.remove("attention");
343
+ card.querySelector(".buttons").innerHTML = "";
344
+ card.querySelector(".buttons").appendChild(
345
+ el("span", "", item.timed_out ? t("no_answer") : t("answered_decision", { decision: item.decision }))
346
+ );
347
+ }
348
+ if (state.attention === card) {
349
+ state.attention = null;
350
+ state.stick = true;
351
+ scrollToBottom(true);
352
+ showLatest();
353
+ }
354
+ break;
355
+ }
356
+ case "todos":
357
+ renderTodos(item.todos);
358
+ break;
359
+ case "state":
360
+ /* The agent is thinking: the dots say so, until it says something. */
361
+ if (item.state === "thinking") showWorking();
362
+ else hideWorking();
363
+ break;
364
+ case "command_output":
365
+ bubble("command", item.text);
366
+ break;
367
+ case "review": {
368
+ const card = el("div", "tool review");
369
+ const header = el("header");
370
+ header.appendChild(el("strong", "", t("review")));
371
+ card.appendChild(header);
372
+ const body = el("div", "body");
373
+ body.appendChild(diffView(item.diff || ""));
374
+ if ((item.untracked || []).length) {
375
+ body.appendChild(el("div", "note", t("untracked", { files: item.untracked.join(", ") })));
376
+ }
377
+ card.appendChild(body);
378
+ target().appendChild(card);
379
+ scrollToBottom();
380
+ break;
381
+ }
382
+ case "error":
383
+ bubble("error", item.error);
384
+ break;
385
+ case "compaction":
386
+ bubble("separator", t("compacted", { tokens: item.tokens }));
387
+ break;
388
+ case "recap":
389
+ bubble("separator", t("recapped"));
390
+ break;
391
+ case "side_conversation":
392
+ bubble("separator", t("side_conversation"));
393
+ break;
394
+ case "verify":
395
+ bubble("separator", t("verified", { failed: (item.failed || []).length }));
396
+ break;
397
+ case "reflection":
398
+ /* A model without a price spends no money: the cost is unknown, not zero. */
399
+ bubble(
400
+ "separator",
401
+ item.priced === false
402
+ ? t("settled_unpriced")
403
+ : t("settled", { cost: (item.cost || 0).toFixed(5) }),
404
+ );
405
+ break;
406
+ case "turn_stopped": {
407
+ /* A turn that was cut off says so: the agent went quiet and the user
408
+ has to know why. */
409
+ hideWorking();
410
+ const note = STOP_NOTES[item.stop_reason];
411
+ if (note) bubble("separator", t(note, { calls: item.calls || 0 }));
412
+ break;
413
+ }
414
+ case "reverted":
415
+ bubble("separator", t("rolled_back", { messages: item.messages }));
416
+ break;
417
+ case "session_switched":
418
+ state.sessionId = item.session_id;
419
+ break;
420
+ case "mode_changed":
421
+ refreshStatus();
422
+ break;
423
+ default:
424
+ break;
425
+ }
426
+ if (item.seq) state.seq = Math.max(state.seq, item.seq);
427
+ }
428
+
429
+ // -- the stream ------------------------------------------------------------
430
+
431
+ function openStream() {
432
+ if (state.stream) state.stream.close();
433
+ if (!state.sessionId) return;
434
+ const stream = new EventSource(`/api/sessions/${state.sessionId}/stream?since=${state.seq}`);
435
+ state.stream = stream;
436
+ stream.onmessage = (event) => {
437
+ const item = JSON.parse(event.data);
438
+ render(item);
439
+ if (item.kind === "turn_end" || item.kind === "command_end") {
440
+ stream.close();
441
+ state.stream = null;
442
+ openStream();
443
+ refreshStatus();
444
+ loadSessions();
445
+ loadChanges();
446
+ }
447
+ };
448
+ stream.onerror = () => {
449
+ stream.close();
450
+ state.stream = null;
451
+ setTimeout(openStream, 1000);
452
+ };
453
+ }
454
+
455
+ // -- the state of the session ----------------------------------------------
456
+
457
+ async function refreshStatus() {
458
+ if (!state.sessionId) return;
459
+ try {
460
+ const status = await api(`/api/sessions/${state.sessionId}/status`);
461
+ document.getElementById("status").textContent =
462
+ `${status.model} | ${status.tokens}/${status.window} | ${money(status.cost, status.priced)} | ${status.mode} | ${status.state}`;
463
+ const fields = document.getElementById("status-fields");
464
+ if (fields) {
465
+ fields.innerHTML = "";
466
+ for (const [key, value] of Object.entries(status)) {
467
+ fields.appendChild(el("dt", "", t(`field_${key}`)));
468
+ fields.appendChild(el("dd", "", key === "cost" ? money(value, status.priced) : String(value)));
469
+ }
470
+ }
471
+ showMode(status.mode);
472
+ } catch (error) {
473
+ /* the session is gone; the next poll will say so */
474
+ }
475
+ }
476
+
477
+ /* The mode of the session, in the inspector of the chat page. */
478
+ function showMode(mode) {
479
+ if (!mode) return;
480
+ state.mode = mode;
481
+ const select = document.getElementById("permission-mode");
482
+ /* The user may be picking a mode: the poll must not pull the box away. */
483
+ if (select && select.value !== mode && document.activeElement !== select) select.value = mode;
484
+ const note = document.getElementById("mode-note");
485
+ if (note) note.textContent = t(MODE_NOTES[mode] || "");
486
+ }
487
+
488
+ async function loadChanges() {
489
+ const box = document.getElementById("changes");
490
+ if (!box || !state.sessionId) return;
491
+ try {
492
+ const data = await api(`/api/sessions/${state.sessionId}/changes`);
493
+ box.innerHTML = "";
494
+ for (const change of data.changes) {
495
+ box.appendChild(el("div", "", change.path));
496
+ if (change.diff) box.appendChild(diffView(change.diff));
497
+ }
498
+ } catch (error) {
499
+ /* no changes yet */
500
+ }
501
+ }
502
+
503
+ // -- the sessions ----------------------------------------------------------
504
+
505
+ async function loadSessions() {
506
+ const list = document.getElementById("sessions");
507
+ if (!list) return;
508
+ const data = await api("/api/sessions");
509
+ list.innerHTML = "";
510
+ for (const session of data.sessions) {
511
+ /* The list shows the first question of the session. The counts are in the
512
+ tooltip: the cost of a model that has no price is not worth showing. */
513
+ const item = el("li", "", session.title);
514
+ item.title = `${session.id} ${session.turns}t ${money(session.cost, session.priced)} ${session.cwd}`;
515
+ if (session.id === state.sessionId) item.classList.add("active");
516
+ item.onclick = () => openSession(session.id);
517
+ list.appendChild(item);
518
+ }
519
+ }
520
+
521
+ async function openSession(id) {
522
+ state.sessionId = id;
523
+ state.seq = 0;
524
+ state.cards = {};
525
+ state.assistant = null;
526
+ state.current = null;
527
+ state.attention = null;
528
+ state.stick = true;
529
+ messages().innerHTML = "";
530
+ const data = await api(`/api/sessions/${id}/items`);
531
+ for (const item of data.items) render(item);
532
+ scrollToBottom(true);
533
+ openStream();
534
+ refreshStatus();
535
+ loadSessions();
536
+ loadChanges();
537
+ }
538
+
539
+ // -- the files -------------------------------------------------------------
540
+
541
+ async function listFiles(path) {
542
+ const list = document.getElementById("files");
543
+ const data = await api(`/api/files?path=${encodeURIComponent(path)}&depth=1`);
544
+ list.innerHTML = "";
545
+ for (const entry of data.entries) {
546
+ const item = el("li", entry.is_dir ? "dir" : "", entry.name + (entry.is_dir ? "/" : ""));
547
+ item.onclick = () => {
548
+ if (entry.is_dir) {
549
+ listFiles(entry.path);
550
+ } else {
551
+ showFile(entry.path);
552
+ }
553
+ };
554
+ list.appendChild(item);
555
+ }
556
+ const input = document.getElementById("file-path");
557
+ /* The panel shows where it is: the directory that was listed. */
558
+ if (input && data.path) input.value = data.path;
559
+ }
560
+
561
+ async function showFile(path) {
562
+ const view = document.getElementById("file-view");
563
+ try {
564
+ const file = await api(`/api/file?path=${encodeURIComponent(path)}`);
565
+ view.textContent = file.content;
566
+ } catch (error) {
567
+ view.textContent = t("error", { message: error.message });
568
+ }
569
+ try {
570
+ const data = await api(`/api/diff?path=${encodeURIComponent(path)}`);
571
+ if (data.diff) view.textContent += `\n\n--- diff ---\n${data.diff}`;
572
+ } catch (error) {
573
+ /* no diff */
574
+ }
575
+ }
576
+
577
+ // -- the commands ----------------------------------------------------------
578
+
579
+ async function loadCommands() {
580
+ const select = document.getElementById("command-list");
581
+ if (!select) return;
582
+ const data = await api("/api/commands");
583
+ select.innerHTML = "";
584
+ for (const command of data.commands) {
585
+ const option = el("option", "", command.usage ? `/${command.name} ${command.usage}` : `/${command.name}`);
586
+ option.value = `/${command.name}`;
587
+ option.title = command.usage ? `${command.description} — ${command.usage}` : command.description;
588
+ select.appendChild(option);
589
+ }
590
+ }
591
+
592
+ /* The sub agents of the project, with the turns they may really make. */
593
+ async function loadAgents() {
594
+ const box = document.getElementById("agents");
595
+ if (!box) return;
596
+ try {
597
+ const data = await api("/api/agents");
598
+ box.innerHTML = "";
599
+ for (const agent of data.agents) {
600
+ const item = el("div", "agent");
601
+ const head = el("div", "agent-head");
602
+ head.appendChild(el("strong", "", agent.name));
603
+ head.appendChild(el("span", "", agent.purpose));
604
+ item.appendChild(head);
605
+ item.appendChild(el("div", "agent-turns", agent.turns ? t("turns", { count: agent.turns }) : t("no_limit")));
606
+ item.appendChild(el("div", "agent-tools", agent.tools.join(", ")));
607
+ if (agent.description) item.appendChild(el("div", "agent-description", agent.description));
608
+ box.appendChild(item);
609
+ }
610
+ if (data.ceiling) box.appendChild(el("p", "note", t("turn_ceiling", { count: data.ceiling })));
611
+ } catch (error) {
612
+ /* there are no sub agents to show */
613
+ }
614
+ }
615
+
616
+ // -- the language -----------------------------------------------------------
617
+
618
+ const LANGUAGE_KEY = "coder_lang";
619
+
620
+ /* The text of a language, without leaving the page: the page of that language
621
+ is fetched and put in place, and the strings of the browser are replaced. */
622
+ async function switchLanguage(code) {
623
+ const data = await api(`/api/i18n/${encodeURIComponent(code)}`);
624
+ window.STRINGS = data.strings;
625
+ const answer = await fetch(`${location.pathname}?lang=${encodeURIComponent(code)}`);
626
+ const doc = new DOMParser().parseFromString(await answer.text(), "text/html");
627
+ document.title = doc.title;
628
+ document.documentElement.lang = doc.documentElement.lang;
629
+ const fresh = doc.body.cloneNode(true);
630
+ fresh.querySelectorAll("script").forEach((node) => node.remove());
631
+ document.body.replaceChildren(...fresh.childNodes);
632
+ /* The choice is kept in the browser and in the cookie: the server renders the
633
+ right language the next time, and the browser finds its choice again. */
634
+ document.cookie = `${LANGUAGE_KEY}=${code}; path=/; max-age=31536000; samesite=lax`;
635
+ localStorage.setItem(LANGUAGE_KEY, code);
636
+ }
637
+
638
+ /* The values of the form, so that a change of the language does not throw
639
+ away what was typed. */
640
+ function formValues() {
641
+ const values = {};
642
+ for (const node of document.querySelectorAll("input, textarea, select")) {
643
+ if (node.type !== "password" && node.id) values[node.id] = node.value;
644
+ }
645
+ return values;
646
+ }
647
+
648
+ function restoreForm(values) {
649
+ for (const [id, value] of Object.entries(values)) {
650
+ const node = document.getElementById(id);
651
+ if (node) node.value = value;
652
+ }
653
+ }
654
+
655
+ /* The page is drawn again in the new language: the conversation is read from
656
+ the log, the settings are read from the configuration. The values of the
657
+ form are the ones of before the switch, so nothing that was typed is lost. */
658
+ async function relocalize(values = {}) {
659
+ if (document.getElementById("messages")) {
660
+ wire();
661
+ await loadCommands().catch(() => {});
662
+ await loadAgents().catch(() => {});
663
+ if (state.sessionId) await openSession(state.sessionId);
664
+ return;
665
+ }
666
+ if (!document.getElementById("model-form")) {
667
+ if (document.getElementById("skills-page")) {
668
+ await startSkills();
669
+ restoreForm(values);
670
+ }
671
+ return;
672
+ }
673
+ await startSettings();
674
+ restoreForm(values);
675
+ }
676
+
677
+ async function chooseLanguage(code) {
678
+ try {
679
+ const values = formValues();
680
+ await switchLanguage(code);
681
+ await relocalize(values);
682
+ } catch (error) {
683
+ /* the page stays in the language it has */
684
+ }
685
+ }
686
+
687
+ // -- the skills -------------------------------------------------------------
688
+
689
+ const skillState = { staged: null, force: false };
690
+ const listState = { installed: { page: 0 }, builtin: { page: 0 } };
691
+ const PAGE = 10;
692
+ /* How many skills a list shows at a time. */
693
+
694
+ function skillButton(label, action) {
695
+ const button = el("button", "", label);
696
+ button.onclick = action;
697
+ return button;
698
+ }
699
+
700
+ async function loadSkills() {
701
+ if (!document.getElementById("skills-installed")) return;
702
+ const data = await api("/api/skills");
703
+ siteState.installed = new Set(data.skills.map((skill) => skill.name));
704
+ showInstalled(data.skills || []);
705
+ showBuiltin(data.builtin || []);
706
+ showRegistries(data.registries || []);
707
+ if (siteState.site) renderSite();
708
+ }
709
+
710
+ /* The installed skills, ten at a time. */
711
+ function showInstalled(skills) {
712
+ const box = document.getElementById("skills-installed");
713
+ box.innerHTML = "";
714
+ if (!skills.length) {
715
+ box.appendChild(el("div", "note", t("skills_none")));
716
+ return;
717
+ }
718
+ const state = listState.installed;
719
+ const pages = Math.max(1, Math.ceil(skills.length / PAGE));
720
+ state.page = Math.min(state.page, pages - 1);
721
+ const grid = el("div", "skill-grid");
722
+ for (const skill of skills.slice(state.page * PAGE, (state.page + 1) * PAGE)) {
723
+ const row = el("div", "skill");
724
+ const head = el("div", "skill-head");
725
+ head.appendChild(el("strong", "", skill.name));
726
+ head.appendChild(el("span", "", skill.description));
727
+ row.appendChild(head);
728
+ const meta = el("div", "skill-meta");
729
+ if (skill.source_text) meta.appendChild(el("div", "", t("skills_from", { source: skill.source_text })));
730
+ meta.appendChild(el("div", "", t("skills_files", { count: skill.files })));
731
+ if (skill.sha256) meta.appendChild(el("div", "", `${t("skills_sha256")} ${skill.sha256}`));
732
+ if (!skill.managed) meta.appendChild(el("div", "", t("skills_yours")));
733
+ row.appendChild(meta);
734
+ const buttons = el("div", "row");
735
+ buttons.appendChild(skillButton(t("skills_details"), () => showSkill(skill.name)));
736
+ if (skill.managed) {
737
+ buttons.appendChild(skillButton(t("skills_update"), () => updateSkill(skill.name)));
738
+ buttons.appendChild(skillButton(t("skills_uninstall"), () => removeSkill(skill.name)));
739
+ }
740
+ row.appendChild(buttons);
741
+ grid.appendChild(row);
742
+ }
743
+ box.appendChild(grid);
744
+ box.appendChild(makePager(state, pages, () => showInstalled(skills), "skills"));
745
+ }
746
+
747
+ /* The skills that come with the agent. They are not installed, so there is
748
+ nothing to update and nothing to remove. */
749
+ function showBuiltin(skills) {
750
+ const box = document.getElementById("skills-builtin");
751
+ if (!box) return;
752
+ box.innerHTML = "";
753
+ const state = listState.builtin;
754
+ const pages = Math.max(1, Math.ceil(skills.length / PAGE));
755
+ state.page = Math.min(state.page, pages - 1);
756
+ const grid = el("div", "skill-grid");
757
+ for (const skill of skills.slice(state.page * PAGE, (state.page + 1) * PAGE)) {
758
+ const row = el("div", "skill");
759
+ const head = el("div", "skill-head");
760
+ head.appendChild(el("strong", "", skill.name));
761
+ head.appendChild(el("span", "", skill.description));
762
+ row.appendChild(head);
763
+ const meta = el("div", "skill-meta");
764
+ meta.appendChild(el("div", "", t("skills_files", { count: skill.files })));
765
+ row.appendChild(meta);
766
+ const buttons = el("div", "row");
767
+ buttons.appendChild(skillButton(t("skills_details"), () => showSkill(skill.name)));
768
+ row.appendChild(buttons);
769
+ grid.appendChild(row);
770
+ }
771
+ box.appendChild(grid);
772
+ box.appendChild(makePager(state, pages, () => showBuiltin(skills), "skills"));
773
+ }
774
+
775
+ function showRegistries(urls) {
776
+ const box = document.getElementById("skills-registries");
777
+ box.innerHTML = "";
778
+ if (!urls.length) return;
779
+ box.appendChild(el("h2", "", t("skills_registries")));
780
+ const row = el("div", "row");
781
+ for (const url of urls) row.appendChild(skillButton(url, () => browseRegistry(url)));
782
+ box.appendChild(row);
783
+ }
784
+
785
+ async function browseRegistry(url) {
786
+ const box = document.getElementById("skills-registries");
787
+ const message = document.getElementById("skills-message");
788
+ try {
789
+ const data = await api("/api/skills/registry", { method: "POST", body: { url } });
790
+ const old = box.querySelector(".registry-entries");
791
+ if (old) old.remove();
792
+ const entries = el("div", "registry-entries");
793
+ if (!data.skills.length) entries.appendChild(el("div", "note", t("skills_none")));
794
+ for (const skill of data.skills) {
795
+ const row = el("div", "skill");
796
+ const head = el("div", "skill-head");
797
+ head.appendChild(el("strong", "", skill.name));
798
+ head.appendChild(el("span", "", skill.description));
799
+ row.appendChild(head);
800
+ row.appendChild(skillButton(t("skills_use"), () => {
801
+ document.getElementById("skill-source").value = skill.source_text;
802
+ }));
803
+ entries.appendChild(row);
804
+ }
805
+ box.appendChild(entries);
806
+ } catch (error) {
807
+ message.textContent = t("error", { message: error.message });
808
+ }
809
+ }
810
+
811
+ /* What the user is shown before the skill is installed: the whole of the
812
+ SKILL.md, the files that come with it and the warnings about them. */
813
+ function openPreview(preview, force) {
814
+ skillState.staged = preview;
815
+ skillState.force = !!force;
816
+ document.getElementById("preview-name").textContent = preview.name;
817
+ const parts = [preview.source_text, t("skills_files", { count: (preview.files || []).length })];
818
+ if (preview.sha256) parts.push(`${t("skills_sha256")} ${preview.sha256}`);
819
+ document.getElementById("preview-meta").textContent = parts.filter(Boolean).join(" · ");
820
+ const warnings = document.getElementById("preview-warnings");
821
+ warnings.innerHTML = "";
822
+ for (const warning of preview.warnings || []) warnings.appendChild(el("div", "warning", `⚠ ${warning}`));
823
+ document.getElementById("preview-body").textContent = preview.body;
824
+ const files = document.getElementById("preview-files");
825
+ files.innerHTML = "";
826
+ for (const file of preview.files || []) files.appendChild(el("div", "", `${file.path} (${file.size} B)`));
827
+ const install = document.getElementById("preview-install");
828
+ install.style.display = preview.stage_id ? "inline-block" : "none";
829
+ const dialog = document.getElementById("skills-preview");
830
+ if (!dialog.open) dialog.showModal();
831
+ }
832
+
833
+ async function showSkill(name) {
834
+ const message = document.getElementById("skills-message");
835
+ try {
836
+ openPreview(await api(`/api/skills/${encodeURIComponent(name)}`), false);
837
+ } catch (error) {
838
+ message.textContent = t("error", { message: error.message });
839
+ }
840
+ }
841
+
842
+ async function updateSkill(name) {
843
+ const message = document.getElementById("skills-message");
844
+ message.textContent = t("skills_downloading");
845
+ try {
846
+ const data = await api("/api/skills/update", { method: "POST", body: { name } });
847
+ if (data.up_to_date) {
848
+ message.textContent = t("skills_up_to_date", { name });
849
+ return;
850
+ }
851
+ message.textContent = "";
852
+ openPreview(data.preview, true);
853
+ } catch (error) {
854
+ message.textContent = t("error", { message: error.message });
855
+ }
856
+ }
857
+
858
+ async function removeSkill(name) {
859
+ if (!window.confirm(t("skills_uninstall_confirm", { name }))) return;
860
+ const message = document.getElementById("skills-message");
861
+ try {
862
+ await api(`/api/skills/${encodeURIComponent(name)}`, { method: "DELETE" });
863
+ message.textContent = t("skills_removed", { name });
864
+ await loadSkills();
865
+ } catch (error) {
866
+ message.textContent = t("error", { message: error.message });
867
+ }
868
+ }
869
+
870
+ async function installStaged() {
871
+ const message = document.getElementById("skills-message");
872
+ if (!skillState.staged || !skillState.staged.stage_id) return;
873
+ message.textContent = t("skills_downloading");
874
+ try {
875
+ await api("/api/skills/install", {
876
+ method: "POST",
877
+ body: { stage_id: skillState.staged.stage_id, force: skillState.force },
878
+ });
879
+ document.getElementById("skills-preview").close();
880
+ message.textContent = t("skills_installed_ok", { name: skillState.staged.name });
881
+ await loadSkills();
882
+ } catch (error) {
883
+ message.textContent = t("error", { message: error.message });
884
+ }
885
+ }
886
+
887
+ async function startSkills() {
888
+ const message = document.getElementById("skills-message");
889
+ const download = document.getElementById("skills-download");
890
+ document.getElementById("skills-form").onsubmit = async (event) => {
891
+ event.preventDefault();
892
+ const source = document.getElementById("skill-source").value.trim();
893
+ if (!source) return;
894
+ message.textContent = t("skills_downloading");
895
+ download.disabled = true;
896
+ try {
897
+ const preview = await api("/api/skills/preview", { method: "POST", body: { source } });
898
+ message.textContent = "";
899
+ openPreview(preview, false);
900
+ } catch (error) {
901
+ message.textContent = t("error", { message: error.message });
902
+ } finally {
903
+ download.disabled = false;
904
+ }
905
+ };
906
+ document.getElementById("preview-install").onclick = installStaged;
907
+ document.getElementById("preview-cancel").onclick = () => document.getElementById("skills-preview").close();
908
+ document.getElementById("preview-close").onclick = () => document.getElementById("skills-preview").close();
909
+ await loadSkills();
910
+ await loadSites();
911
+ }
912
+
913
+ // -- the sites of skills ----------------------------------------------------
914
+
915
+ const siteState = { site: null, skills: [], page: 0, size: 6, installed: new Set() };
916
+
917
+ const DESCRIPTION = 50;
918
+ /* How much of a description a card shows. The rest waits for the mouse. */
919
+
920
+ /* The sites are the tabs of the page: one tab for each repository, and the
921
+ skills of the repository under it. */
922
+ async function loadSites() {
923
+ const box = document.getElementById("skills-sites");
924
+ if (!box) return;
925
+ try {
926
+ const data = await api("/api/skills/sites");
927
+ box.innerHTML = "";
928
+ for (const site of data.sites || []) {
929
+ const tab = el("button", "tab", siteName(site));
930
+ tab.dataset.site = site.id;
931
+ tab.style.setProperty("--site-accent", site.accent || "#6aa9ff");
932
+ tab.onclick = () => showSite(site);
933
+ box.appendChild(tab);
934
+ }
935
+ if ((data.sites || []).length) await showSite(data.sites[0]);
936
+ } catch (error) {
937
+ box.appendChild(el("div", "note", t("error", { message: error.message })));
938
+ }
939
+ }
940
+
941
+ /* The name of a site in the language of the visitor. */
942
+ function siteName(site) {
943
+ const name = t(`skills_site_${site.id}_name`);
944
+ return name === `skills_site_${site.id}_name` ? site.repo : name;
945
+ }
946
+
947
+ async function showSite(site, refresh = false) {
948
+ const panel = document.getElementById("skills-site-panel");
949
+ siteState.site = site;
950
+ siteState.page = 0;
951
+ for (const tab of document.querySelectorAll("#skills-sites .tab")) {
952
+ tab.classList.toggle("active", tab.dataset.site === site.id);
953
+ }
954
+ panel.innerHTML = "";
955
+ panel.style.setProperty("--site-accent", site.accent || "#6aa9ff");
956
+ panel.appendChild(el("div", "note", t("skills_site_loading")));
957
+ try {
958
+ const data = await api(`/api/skills/sites/${encodeURIComponent(site.id)}${refresh ? "?refresh=true" : ""}`);
959
+ siteState.skills = data.skills || [];
960
+ siteState.size = data.page_size || 6;
961
+ renderSite();
962
+ } catch (error) {
963
+ panel.innerHTML = "";
964
+ panel.appendChild(el("div", "note", t("error", { message: error.message })));
965
+ }
966
+ }
967
+
968
+ function renderSite() {
969
+ const panel = document.getElementById("skills-site-panel");
970
+ const site = siteState.site;
971
+ panel.innerHTML = "";
972
+
973
+ const head = el("div", "site-head");
974
+ const title = el("div", "site-title");
975
+ title.appendChild(el("span", "site-dot"));
976
+ title.appendChild(el("span", "site-name", siteName(site)));
977
+ const link = el("a", "site-repo", site.repo);
978
+ link.href = site.url;
979
+ link.target = "_blank";
980
+ link.rel = "noreferrer";
981
+ title.appendChild(link);
982
+ head.appendChild(title);
983
+ head.appendChild(el("span", "badge", t("skills_site_count", { count: siteState.skills.length })));
984
+ const sync = skillButton(t("skills_site_sync"), syncSite);
985
+ sync.classList.add("ghost");
986
+ head.appendChild(sync);
987
+ panel.appendChild(head);
988
+
989
+ panel.appendChild(el("div", "note", t(`skills_site_${site.id}`)));
990
+
991
+ const grid = el("div", "site-cards");
992
+ const items = siteState.skills.slice(siteState.page * siteState.size, (siteState.page + 1) * siteState.size);
993
+ if (!items.length) grid.appendChild(el("div", "note", t("skills_site_empty")));
994
+ for (const skill of items) grid.appendChild(siteCard(skill));
995
+ panel.appendChild(grid);
996
+
997
+ const pages = Math.max(1, Math.ceil(siteState.skills.length / siteState.size));
998
+ if (pages > 1) panel.appendChild(sitePager(pages));
999
+ }
1000
+
1001
+ function siteCard(skill) {
1002
+ const card = el("div", "site-card");
1003
+ card.appendChild(el("div", "site-avatar", (skill.name || "?").slice(0, 1).toUpperCase()));
1004
+ const body = el("div", "site-card-body");
1005
+ const title = el("div", "site-card-title");
1006
+ title.appendChild(el("strong", "", skill.name));
1007
+ if (siteState.installed.has(skill.name)) title.appendChild(el("span", "badge ok", t("skills_site_installed")));
1008
+ body.appendChild(title);
1009
+ const description = el("div", "site-card-desc", shorten(skill.description || ""));
1010
+ description.title = skill.description || "";
1011
+ body.appendChild(description);
1012
+ body.appendChild(el("code", "site-card-path", skill.path));
1013
+ card.appendChild(body);
1014
+ const actions = el("div", "site-card-actions");
1015
+ actions.appendChild(skillButton(t("skills_site_download"), () => downloadSkill(skill)));
1016
+ card.appendChild(actions);
1017
+ return card;
1018
+ }
1019
+
1020
+ /* A description that fits in a card. The whole of it waits for the mouse:
1021
+ the card carries it as its title. */
1022
+ function shorten(text) {
1023
+ return text.length > DESCRIPTION ? `${text.slice(0, DESCRIPTION)}…` : text;
1024
+ }
1025
+
1026
+ function sitePager(pages) {
1027
+ return makePager(siteState, pages, renderSite, "skills_site");
1028
+ }
1029
+
1030
+ /* The pages of a list of skills: the one on the screen, the ones around it
1031
+ and the first and the last. A list may hold hundreds of skills: a button
1032
+ for every page would be a wall of numbers. */
1033
+ function makePager(state, pages, redraw, keys) {
1034
+ const box = el("div", "pager");
1035
+ const prev = skillButton(t(`${keys}_prev`), () => {
1036
+ state.page = Math.max(0, state.page - 1);
1037
+ redraw();
1038
+ });
1039
+ prev.disabled = state.page <= 0;
1040
+ box.appendChild(prev);
1041
+ let last = -1;
1042
+ for (const index of pageWindow(pages, state.page)) {
1043
+ if (last >= 0 && index > last + 1) box.appendChild(el("span", "note", "…"));
1044
+ const button = skillButton(String(index + 1), () => {
1045
+ state.page = index;
1046
+ redraw();
1047
+ });
1048
+ if (index === state.page) button.classList.add("active");
1049
+ box.appendChild(button);
1050
+ last = index;
1051
+ }
1052
+ const next = skillButton(t(`${keys}_next`), () => {
1053
+ state.page = Math.min(pages - 1, state.page + 1);
1054
+ redraw();
1055
+ });
1056
+ next.disabled = state.page >= pages - 1;
1057
+ box.appendChild(next);
1058
+ box.appendChild(el("span", "note", t(`${keys}_page`, { page: state.page + 1, count: pages })));
1059
+ return box;
1060
+ }
1061
+
1062
+ function pageWindow(pages, page) {
1063
+ const shown = new Set([0, pages - 1]);
1064
+ for (let index = page - 2; index <= page + 2; index++) {
1065
+ if (index >= 0 && index < pages) shown.add(index);
1066
+ }
1067
+ return [...shown].sort((a, b) => a - b);
1068
+ }
1069
+
1070
+ async function syncSite() {
1071
+ const message = document.getElementById("skills-message");
1072
+ message.textContent = t("skills_site_syncing");
1073
+ await showSite(siteState.site, true);
1074
+ message.textContent = "";
1075
+ }
1076
+
1077
+ async function downloadSkill(skill) {
1078
+ const message = document.getElementById("skills-message");
1079
+ message.textContent = t("skills_downloading");
1080
+ try {
1081
+ const preview = await api("/api/skills/preview", { method: "POST", body: { source: skill.source_text } });
1082
+ message.textContent = "";
1083
+ openPreview(preview, false);
1084
+ } catch (error) {
1085
+ message.textContent = t("error", { message: error.message });
1086
+ }
1087
+ }
1088
+
1089
+ async function downloadSkill(skill) {
1090
+ const message = document.getElementById("skills-message");
1091
+ message.textContent = t("skills_downloading");
1092
+ try {
1093
+ const preview = await api("/api/skills/preview", { method: "POST", body: { source: skill.source_text } });
1094
+ message.textContent = "";
1095
+ openPreview(preview, false);
1096
+ } catch (error) {
1097
+ message.textContent = t("error", { message: error.message });
1098
+ }
1099
+ }
1100
+
1101
+ // -- the images ------------------------------------------------------------
1102
+
1103
+ const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
1104
+ /* The types the server takes. The browser and the server have to agree. */
1105
+ const IMAGE_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp"];
1106
+
1107
+ /* An image that goes with the next message. The model takes a data url. */
1108
+ function addImage(file) {
1109
+ if (!IMAGE_TYPES.includes(file.type)) {
1110
+ bubble("error", t("image_bad_type"));
1111
+ return;
1112
+ }
1113
+ if (file.size > MAX_IMAGE_BYTES) {
1114
+ bubble("error", t("image_too_big"));
1115
+ return;
1116
+ }
1117
+ const reader = new FileReader();
1118
+ reader.onload = () => {
1119
+ state.images.push(String(reader.result));
1120
+ showImages();
1121
+ };
1122
+ reader.readAsDataURL(file);
1123
+ }
1124
+
1125
+ /* The images that are waiting to be sent. */
1126
+ function showImages() {
1127
+ const box = document.getElementById("attachments");
1128
+ if (!box) return;
1129
+ box.innerHTML = "";
1130
+ state.images.forEach((url, index) => {
1131
+ const item = el("div", "attachment");
1132
+ const image = el("img");
1133
+ image.src = url;
1134
+ image.alt = "";
1135
+ item.appendChild(image);
1136
+ const remove = el("button", "remove", t("remove_image"));
1137
+ remove.onclick = () => {
1138
+ state.images.splice(index, 1);
1139
+ showImages();
1140
+ };
1141
+ item.appendChild(remove);
1142
+ box.appendChild(item);
1143
+ });
1144
+ }
1145
+
1146
+ // -- the wiring ------------------------------------------------------------
1147
+
1148
+ function wire() {
1149
+ const box = messages();
1150
+ if (box) {
1151
+ box.addEventListener("scroll", () => {
1152
+ const gap = box.scrollHeight - box.scrollTop - box.clientHeight;
1153
+ state.stick = gap < 40;
1154
+ showLatest();
1155
+ });
1156
+ }
1157
+
1158
+ const toLatest = document.getElementById("to-latest");
1159
+ if (toLatest) {
1160
+ toLatest.onclick = () => {
1161
+ state.stick = true;
1162
+ scrollToBottom(true);
1163
+ showLatest();
1164
+ };
1165
+ }
1166
+
1167
+ const newSession = document.getElementById("new-session");
1168
+ if (newSession) {
1169
+ newSession.onclick = async () => {
1170
+ const data = await api("/api/sessions", { method: "POST" });
1171
+ await openSession(data.id);
1172
+ };
1173
+ }
1174
+
1175
+ const input = document.getElementById("input");
1176
+ const composer = document.getElementById("composer");
1177
+ if (composer) {
1178
+ composer.onsubmit = async (event) => {
1179
+ event.preventDefault();
1180
+ const text = input.value.trim();
1181
+ const images = state.images.slice();
1182
+ if ((!text && !images.length) || !state.sessionId) return;
1183
+ input.value = "";
1184
+ state.images = [];
1185
+ showImages();
1186
+ try {
1187
+ await api(`/api/sessions/${state.sessionId}/messages`, { method: "POST", body: { text, images } });
1188
+ } catch (error) {
1189
+ bubble("error", error.message);
1190
+ }
1191
+ };
1192
+ }
1193
+
1194
+ const attach = document.getElementById("attach");
1195
+ const attachButton = document.getElementById("attach-image");
1196
+ if (attach && attachButton) {
1197
+ attachButton.onclick = () => attach.click();
1198
+ attach.onchange = () => {
1199
+ for (const file of attach.files || []) addImage(file);
1200
+ attach.value = "";
1201
+ };
1202
+ }
1203
+
1204
+ if (input) {
1205
+ input.addEventListener("paste", (event) => {
1206
+ /* The items carry what was copied: a picture of a web page comes as an
1207
+ item of its own, not as a file. */
1208
+ const items = Array.from((event.clipboardData || {}).items || []).filter((item) => item.kind === "file");
1209
+ const files = items.map((item) => item.getAsFile()).filter(Boolean);
1210
+ if (!files.length) return;
1211
+ event.preventDefault();
1212
+ files.forEach(addImage);
1213
+ });
1214
+ }
1215
+
1216
+ const runCommand = document.getElementById("run-command");
1217
+ if (runCommand) {
1218
+ runCommand.onclick = () => {
1219
+ const select = document.getElementById("command-list");
1220
+ input.value = select.value;
1221
+ document.getElementById("composer").requestSubmit();
1222
+ };
1223
+ }
1224
+
1225
+ const review = document.getElementById("review");
1226
+ if (review) {
1227
+ review.onclick = async () => {
1228
+ if (!state.sessionId) return;
1229
+ try {
1230
+ await api(`/api/sessions/${state.sessionId}/review`, { method: "POST" });
1231
+ } catch (error) {
1232
+ bubble("error", error.message);
1233
+ }
1234
+ };
1235
+ }
1236
+
1237
+ const interrupt = document.getElementById("interrupt");
1238
+ if (interrupt) {
1239
+ interrupt.onclick = async () => {
1240
+ if (state.sessionId) await api(`/api/sessions/${state.sessionId}/interrupt`, { method: "POST" });
1241
+ };
1242
+ }
1243
+
1244
+ const listButton = document.getElementById("list-files");
1245
+ if (listButton) {
1246
+ listButton.onclick = () => {
1247
+ const path = document.getElementById("file-path").value || ".";
1248
+ listFiles(path).catch((error) => bubble("error", error.message));
1249
+ };
1250
+ }
1251
+
1252
+ const modeSelect = document.getElementById("permission-mode");
1253
+ if (modeSelect) {
1254
+ modeSelect.onchange = async () => {
1255
+ const mode = modeSelect.value;
1256
+ const previous = state.mode;
1257
+ if (!state.sessionId) {
1258
+ modeSelect.value = previous || "default";
1259
+ return;
1260
+ }
1261
+ if (mode === "bypass" && !window.confirm(t("bypass_confirm"))) {
1262
+ modeSelect.value = previous || "default";
1263
+ return;
1264
+ }
1265
+ try {
1266
+ await api(`/api/sessions/${state.sessionId}/mode`, {
1267
+ method: "POST",
1268
+ body: { mode, confirm: mode === "bypass" },
1269
+ });
1270
+ showMode(mode);
1271
+ } catch (error) {
1272
+ modeSelect.value = previous || "default";
1273
+ bubble("error", error.message);
1274
+ }
1275
+ };
1276
+ }
1277
+ }
1278
+
1279
+ // -- the settings ----------------------------------------------------------
1280
+
1281
+ function splitLines(text) {
1282
+ return (text || "")
1283
+ .split("\n")
1284
+ .map((line) => line.trim())
1285
+ .filter(Boolean);
1286
+ }
1287
+
1288
+ function keySource(resolved) {
1289
+ // Where the key comes from: the settings, or a variable of the environment.
1290
+ if (resolved.key_source === "settings") return t("key_source_settings");
1291
+ if (resolved.key_source === "env") return t("key_source_env", { var: resolved.key_env || "" });
1292
+ return t("not_set");
1293
+ }
1294
+
1295
+ function reportText(report) {
1296
+ // The report of the try-out of the model: what it resolved to, and what it did.
1297
+ const resolved = report.resolved || {};
1298
+ const lines = [];
1299
+ lines.push(`${t("field_model")}: ${resolved.model_name || ""}`);
1300
+ lines.push(t("provider_is", { provider: resolved.provider || "" }));
1301
+ if (resolved.api_base) lines.push(`${t("field_api_base")}: ${resolved.api_base}`);
1302
+ if (report.error) {
1303
+ lines.push(t("error", { message: report.error }));
1304
+ return lines.join("\n");
1305
+ }
1306
+ lines.push(t("test_latency", { ms: report.latency_ms || 0 }));
1307
+ lines.push(t("test_cost", { cost: (report.cost || 0).toFixed(6) }));
1308
+ const tools = report.tools || {};
1309
+ lines.push(tools.ok ? t("test_tools_ok") : t("test_tools_bad", { message: tools.error || "" }));
1310
+ return lines.join("\n");
1311
+ }
1312
+
1313
+ function wireApiKey(input, placeholder, note) {
1314
+ // A click shows the key of the settings, a second click hides it again.
1315
+ let revealed = false;
1316
+ input.onclick = async () => {
1317
+ if (revealed) {
1318
+ revealed = false;
1319
+ input.value = "";
1320
+ input.type = "password";
1321
+ input.placeholder = placeholder();
1322
+ return;
1323
+ }
1324
+ if (input.value.trim()) return;
1325
+ // A key that is being typed is left alone.
1326
+ try {
1327
+ const answer = await api("/api/config/model/key");
1328
+ if (!answer.api_key) {
1329
+ if (note) note.textContent = t("no_key");
1330
+ return;
1331
+ }
1332
+ input.value = answer.api_key;
1333
+ input.type = "text";
1334
+ input.select();
1335
+ revealed = true;
1336
+ } catch (error) {
1337
+ if (note) note.textContent = t("error", { message: error.message });
1338
+ }
1339
+ };
1340
+ }
1341
+
1342
+ async function startSettings() {
1343
+ const data = await api("/api/config");
1344
+ const model = data.model;
1345
+ const permissions = data.permissions || {};
1346
+ document.getElementById("config-path").textContent = data.user_config_path;
1347
+ document.getElementById("model-name").value = model.model_name || "";
1348
+ const providerNote = document.getElementById("model-provider");
1349
+ if (providerNote) {
1350
+ providerNote.textContent = model.provider ? t("provider_is", { provider: model.provider }) : "";
1351
+ }
1352
+ document.getElementById("api-base").value = model.api_base || "";
1353
+ document.getElementById("max-retries").value = model.max_retries;
1354
+
1355
+ document.getElementById("permission-mode").value = permissions.mode || "default";
1356
+ document.getElementById("deny-paths").value = (permissions.deny_paths || []).join("\n");
1357
+ document.getElementById("include-dirs").value = (permissions.include_dirs || []).join("\n");
1358
+ document.getElementById("network").value = permissions.network || "allow";
1359
+ const permissionSource = document.getElementById("source-mode");
1360
+ if (permissionSource) {
1361
+ permissionSource.textContent = t("from", { source: (permissions.source || {}).mode || "defaults" });
1362
+ }
1363
+ const networkSource = document.getElementById("source-network");
1364
+ if (networkSource) {
1365
+ networkSource.textContent = t("from", { source: (permissions.source || {}).network || "defaults" });
1366
+ }
1367
+ const serverNote = document.getElementById("server-mode-note");
1368
+ if (serverNote) {
1369
+ serverNote.textContent = permissions.server_mode
1370
+ ? t("server_mode", { mode: permissions.server_mode })
1371
+ : "";
1372
+ }
1373
+
1374
+ const keyInput = document.getElementById("api-key");
1375
+ keyInput.type = "password";
1376
+ keyInput.value = "";
1377
+ const keyPlaceholder = () =>
1378
+ model.api_key_set ? t("key_set", { hint: model.api_key_hint }) : t("key_not_set");
1379
+ keyInput.placeholder = keyPlaceholder();
1380
+ const keySourceNote = document.getElementById("model-key-source");
1381
+ if (keySourceNote) keySourceNote.textContent = keySource(model);
1382
+
1383
+ const message = document.getElementById("config-message");
1384
+ const payload = () => {
1385
+ const form = {
1386
+ model_name: document.getElementById("model-name").value.trim(),
1387
+ api_base: document.getElementById("api-base").value.trim(),
1388
+ max_retries: Number(document.getElementById("max-retries").value || 0),
1389
+ };
1390
+ const key = keyInput.value.trim();
1391
+ if (key) form.api_key = key;
1392
+ return form;
1393
+ };
1394
+
1395
+ wireApiKey(keyInput, keyPlaceholder, message);
1396
+
1397
+ document.getElementById("model-form").onsubmit = async (event) => {
1398
+ event.preventDefault();
1399
+ try {
1400
+ const answer = await api("/api/config/model", { method: "PUT", body: payload() });
1401
+ message.textContent = t("saved", { path: answer.path });
1402
+ document.getElementById("api-key").value = "";
1403
+ startSettings();
1404
+ } catch (error) {
1405
+ message.textContent = t("error", { message: error.message });
1406
+ }
1407
+ };
1408
+
1409
+ const testButton = document.getElementById("model-test");
1410
+ const testResult = document.getElementById("model-test-result");
1411
+ if (testButton && testResult) {
1412
+ /* The test tries the settings of the form out. It writes nothing: saving is
1413
+ a step of its own. */
1414
+ testButton.onclick = async () => {
1415
+ testResult.textContent = t("testing");
1416
+ try {
1417
+ const report = await api("/api/config/model/test", { method: "POST", body: payload() });
1418
+ testResult.textContent = reportText(report);
1419
+ } catch (error) {
1420
+ testResult.textContent = t("error", { message: error.message });
1421
+ }
1422
+ };
1423
+ }
1424
+
1425
+ document.getElementById("permissions-form").onsubmit = async (event) => {
1426
+ event.preventDefault();
1427
+ const note = document.getElementById("permissions-message");
1428
+ try {
1429
+ const answer = await api("/api/config/permissions", {
1430
+ method: "PUT",
1431
+ body: {
1432
+ mode: document.getElementById("permission-mode").value,
1433
+ deny_paths: splitLines(document.getElementById("deny-paths").value),
1434
+ include_dirs: splitLines(document.getElementById("include-dirs").value),
1435
+ network: document.getElementById("network").value,
1436
+ },
1437
+ });
1438
+ note.textContent = t("saved", { path: answer.path });
1439
+ startSettings();
1440
+ } catch (error) {
1441
+ note.textContent = t("error", { message: error.message });
1442
+ }
1443
+ };
1444
+ }
1445
+
1446
+ async function start() {
1447
+ wire();
1448
+ await loadCommands().catch(() => {});
1449
+ await loadAgents().catch(() => {});
1450
+ await loadSessions().catch(() => {});
1451
+ const data = await api("/api/sessions", { method: "POST" });
1452
+ await openSession(data.id);
1453
+ setInterval(refreshStatus, 2000);
1454
+ }
1455
+
1456
+ document.addEventListener("DOMContentLoaded", async () => {
1457
+ /* The language of the visitor is remembered in the browser: it wins over the
1458
+ one the server rendered, so a refresh does not change it back. */
1459
+ const saved = localStorage.getItem(LANGUAGE_KEY);
1460
+ if (saved && saved !== document.documentElement.lang) {
1461
+ await switchLanguage(saved).catch(() => {});
1462
+ }
1463
+ if (document.getElementById("messages")) start();
1464
+ if (document.getElementById("model-form")) startSettings();
1465
+ if (document.getElementById("skills-page")) startSkills();
1466
+ });