create-orcha 0.1.5 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1388 +0,0 @@
1
- const state = {
2
- agents: [],
3
- agent: undefined,
4
- sessions: [],
5
- sessionId: undefined,
6
- pendingCalls: [],
7
- evaluations: [],
8
- tests: [],
9
- testReports: new Map(),
10
- operationId: 0,
11
- inputMode: "text",
12
- sessionQuery: "",
13
- running: false,
14
- rawEvents: "",
15
- children: [],
16
- };
17
-
18
- const element = Object.fromEntries(
19
- [
20
- "agent-count", "agent-list", "agent-title", "agent-description",
21
- "agent-badges", "configuration-grid", "system-instructions", "action-count", "action-list",
22
- "skill-count", "skill-list", "subagent-count", "subagent-list", "evaluation-definitions",
23
- "evaluation-session", "evaluation-results",
24
- "examples", "input-help", "prompt", "run-button", "clear-run", "run-section",
25
- "live-section", "live-session-label", "run-status", "live-timeline",
26
- "client-actions", "client-action-fields", "submit-tool-results",
27
- "run-tests", "test-summary", "test-results",
28
- "sessions-tab", "session-title", "session-summary", "session-timeline",
29
- "sessions-index", "center-session-count", "center-session-list",
30
- "session-history", "back-to-sessions",
31
- "raw-events", "copy-events", "resume-session", "refresh-sessions",
32
- "new-session", "session-count-side", "session-search", "session-list",
33
- "session-list-panel", "session-inspector", "close-session-inspector",
34
- "inspector-status", "inspector-title", "inspector-children", "inspector-evaluations", "toast",
35
- ].map((id) => [camel(id), document.querySelector(`#${id}`)]),
36
- );
37
-
38
- await loadAgents();
39
-
40
- for (const tab of document.querySelectorAll(".main-tab")) {
41
- tab.addEventListener("click", () => {
42
- showView(tab.dataset.view);
43
- if (tab.dataset.view === "sessions") {
44
- showSessionsIndex();
45
- showSessionList();
46
- }
47
- });
48
- }
49
-
50
- for (const segment of document.querySelectorAll(".segment")) {
51
- segment.addEventListener("click", () => setInputMode(segment.dataset.mode));
52
- }
53
-
54
- element.runButton.addEventListener("click", runFromComposer);
55
- element.prompt.addEventListener("keydown", (event) => {
56
- if ((event.metaKey || event.ctrlKey) && event.key === "Enter") {
57
- void runFromComposer();
58
- }
59
- });
60
- element.clearRun.addEventListener("click", clearRun);
61
- element.newSession.addEventListener("click", startNewSession);
62
- element.refreshSessions.addEventListener("click", loadSessions);
63
- element.closeSessionInspector.addEventListener("click", showSessionList);
64
- element.backToSessions.addEventListener("click", () => {
65
- showSessionsIndex();
66
- showSessionList();
67
- });
68
- element.sessionSearch.addEventListener("input", () => {
69
- state.sessionQuery = element.sessionSearch.value.trim().toLowerCase();
70
- renderSessionNavigation();
71
- });
72
- element.submitToolResults.addEventListener("click", submitToolResults);
73
- element.runTests.addEventListener("click", () => runAgentTests());
74
- element.resumeSession.addEventListener("click", () => {
75
- showView("run");
76
- element.prompt.focus();
77
- });
78
- element.copyEvents.addEventListener("click", async () => {
79
- if (!state.rawEvents) return;
80
- await navigator.clipboard.writeText(state.rawEvents);
81
- showToast("Copied session events.");
82
- });
83
-
84
- async function loadAgents() {
85
- try {
86
- const data = await requestJson("/api/agents");
87
- state.agents = data.agents;
88
- element.agentCount.textContent = String(state.agents.length);
89
- renderAgentNavigation();
90
- if (state.agents[0]) await selectAgent(state.agents[0].name);
91
- } catch (error) {
92
- showToast(error.message, true);
93
- }
94
- }
95
-
96
- function renderAgentNavigation() {
97
- element.agentList.replaceChildren(
98
- ...state.agents.map((agent) => {
99
- const button = document.createElement("button");
100
- button.className = `agent-button${state.agent?.name === agent.name ? " active" : ""}`;
101
- button.innerHTML = `
102
- <span class="agent-icon">${escapeHtml(agent.name.slice(0, 2))}</span>
103
- <span class="agent-copy">
104
- <strong>${escapeHtml(agent.displayName || agent.name)}</strong>
105
- <span>${escapeHtml(agent.provider)} · ${escapeHtml(agent.model)}</span>
106
- </span>`;
107
- button.addEventListener("click", () => selectAgent(agent.name));
108
- return button;
109
- }),
110
- );
111
- }
112
-
113
- async function selectAgent(name) {
114
- if (state.running) {
115
- showToast("Wait for the current operation to finish.");
116
- return;
117
- }
118
- state.operationId += 1;
119
- state.agent = state.agents.find((agent) => agent.name === name);
120
- state.sessions = [];
121
- state.tests = [];
122
- state.testReports = new Map();
123
- state.sessionId = undefined;
124
- state.pendingCalls = [];
125
- state.children = [];
126
- state.evaluations = [];
127
- state.sessionQuery = "";
128
- element.sessionSearch.value = "";
129
- element.evaluationSession.textContent = "Results";
130
- renderEvaluationResults();
131
- renderAgentNavigation();
132
- renderSessionNavigation();
133
- renderCenterSessionList();
134
- renderTests();
135
- element.testSummary.className = "test-summary empty";
136
- element.testSummary.textContent = "Loading registered tests…";
137
- renderOverview();
138
- clearRun();
139
- showSessionList();
140
- element.sessionTitle.textContent = "Select a session";
141
- showSessionsIndex();
142
- element.rawEvents.textContent = "";
143
- state.rawEvents = "";
144
- element.resumeSession.classList.add("hidden");
145
- showView("overview");
146
- element.sessionsTab.disabled = true;
147
- await Promise.all([loadSessions(), loadTests()]);
148
- }
149
-
150
- function renderOverview() {
151
- const agent = state.agent;
152
- if (!agent) return;
153
- element.agentTitle.textContent = agent.displayName || agent.name;
154
- element.agentDescription.textContent =
155
- agent.description || "Registered Orcha agent.";
156
- element.agentBadges.innerHTML = [
157
- badge(agent.provider), badge(agent.model), badge(agent.outputType),
158
- ].join("");
159
- element.configurationGrid.innerHTML = [
160
- configuration("Provider", agent.provider),
161
- configuration("Model", agent.model),
162
- configuration("Region", agent.region),
163
- configuration("Output", agent.outputType),
164
- configuration("Max tokens", agent.maxTokens ?? "provider default"),
165
- configuration("Reasoning", agent.reasoningLevel ?? "provider default"),
166
- ].join("");
167
- element.systemInstructions.textContent = agent.systemPrompt;
168
- renderCapabilities(
169
- element.actionList,
170
- element.actionCount,
171
- agent.actions,
172
- (action) => capability(
173
- action.name,
174
- action.description,
175
- action.execution,
176
- `${action.sideEffect ? "Side effect" : "Read only"} · ${schemaSummary(action.parameters)}`,
177
- {
178
- parameters: action.parameters,
179
- outputSchema: action.outputSchema,
180
- permissions: action.permissions,
181
- timeoutMs: action.timeoutMs,
182
- },
183
- ),
184
- );
185
- renderCapabilities(
186
- element.skillList,
187
- element.skillCount,
188
- agent.skills,
189
- (skill) => capability(
190
- skill.name,
191
- skill.description,
192
- "lazy",
193
- skill.triggers.length
194
- ? `Triggers: ${skill.triggers.join(" · ")}`
195
- : "Loaded by the model when needed",
196
- skill.instructions,
197
- ),
198
- );
199
- renderCapabilities(
200
- element.subagentList,
201
- element.subagentCount,
202
- agent.subagents || [],
203
- (subagent) => capability(
204
- subagent.name,
205
- subagent.description,
206
- "subagent",
207
- `${subagent.provider} · ${subagent.model}`,
208
- { key: subagent.key },
209
- ),
210
- );
211
- renderEvaluationDefinitions();
212
- renderExamples();
213
- }
214
-
215
- function renderEvaluationDefinitions() {
216
- const evaluations = state.agent?.evaluations || [];
217
- element.evaluationDefinitions.innerHTML = evaluations.length
218
- ? evaluations.map((evaluation) => `
219
- <article class="evaluation-definition">
220
- <header>
221
- <div>
222
- <strong>${escapeHtml(evaluation.name)}</strong>
223
- <p>${escapeHtml(evaluation.description || "Model-graded evaluation")}</p>
224
- </div>
225
- <span class="type ${evaluation.enabled ? "enabled" : "disabled"}">${evaluation.enabled ? "enabled" : "disabled"}</span>
226
- </header>
227
- <details class="evaluator-instructions">
228
- <summary>Evaluator instructions</summary>
229
- <pre>${escapeHtml(evaluation.instructions || evaluation.description || "")}</pre>
230
- </details>
231
- <div class="evaluation-subheading">
232
- <span class="overline">Scoring criteria</span>
233
- <strong>Metrics</strong>
234
- </div>
235
- <div class="evaluation-metric-definitions">
236
- ${evaluation.metrics.map((metric) => `
237
- <div class="evaluation-metric-definition">
238
- <div>
239
- <strong>${escapeHtml(metric.name)}</strong>
240
- <span>Threshold ${Number(metric.threshold).toFixed(2)}</span>
241
- </div>
242
- <p>${escapeHtml(metric.description)}</p>
243
- </div>`).join("")}
244
- </div>
245
- <details class="evaluation-configuration">
246
- <summary>Judge configuration</summary>
247
- <pre class="detail-json">${escapeHtml(JSON.stringify({
248
- provider: evaluation.provider,
249
- model: evaluation.model,
250
- maxTokens: evaluation.maxTokens,
251
- reasoningLevel: evaluation.reasoningLevel,
252
- }, null, 2))}</pre>
253
- </details>
254
- </article>`).join("")
255
- : '<div class="empty">No evaluations registered for this agent.</div>';
256
- }
257
-
258
- function renderEvaluationResults() {
259
- const evaluations = state.evaluations || [];
260
- element.evaluationResults.className = evaluations.length
261
- ? "evaluation-results"
262
- : "evaluation-results empty";
263
- element.evaluationResults.innerHTML = evaluations.length
264
- ? evaluations.map((evaluation) => `
265
- <article class="evaluation-card ${escapeHtml(evaluation.status)}">
266
- <header>
267
- <div><span class="overline">Evaluation${evaluation.run ? ` · Run ${evaluation.run}` : ""}</span><strong>${escapeHtml(evaluation.name)}</strong></div>
268
- <span class="evaluation-status">${escapeHtml(evaluation.status)}</span>
269
- </header>
270
- ${evaluation.error ? `<p class="evaluation-error">${escapeHtml(evaluation.error.message)}</p>` : ""}
271
- <div class="metric-list">
272
- ${(evaluation.metrics || []).map((metric) => `
273
- <div class="metric-card">
274
- <div class="metric-heading">
275
- <strong>${escapeHtml(metric.name)}</strong>
276
- <span class="${metric.passed ? "pass" : "fail"}">${metric.passed ? "PASS" : "FAIL"}</span>
277
- </div>
278
- <div class="metric-score">
279
- <span>Score ${Number(metric.score).toFixed(2)}</span>
280
- <span>Threshold ${Number(metric.threshold).toFixed(2)}</span>
281
- </div>
282
- <div class="score-track"><span style="width:${Math.max(0, Math.min(100, Number(metric.score) * 100))}%"></span></div>
283
- <p>${escapeHtml(metric.reasoning)}</p>
284
- <div class="evidence">
285
- <span class="overline">Evidence</span>
286
- ${(metric.evidence || []).map((item) => `<blockquote>${escapeHtml(item)}</blockquote>`).join("")}
287
- </div>
288
- </div>`).join("")}
289
- </div>
290
- </article>`).join("")
291
- : "Select or run a session to inspect evaluation results.";
292
- }
293
-
294
- function renderCapabilities(container, count, items, render) {
295
- count.textContent = String(items.length);
296
- container.innerHTML = items.length
297
- ? items.map(render).join("")
298
- : '<div class="empty">None configured.</div>';
299
- }
300
-
301
- function renderExamples() {
302
- const examples = state.agent?.examples || [];
303
- element.examples.innerHTML = examples.length
304
- ? examples.map((example, index) =>
305
- `<button class="example-button" data-example="${index}">${escapeHtml(example.label)}</button>`,
306
- ).join("")
307
- : '<span class="empty">No example prompts configured.</span>';
308
- for (const button of element.examples.querySelectorAll(".example-button")) {
309
- button.addEventListener("click", () => {
310
- const example = examples[Number(button.dataset.example)];
311
- const structured = Array.isArray(example.content);
312
- setInputMode(structured ? "json" : "text");
313
- element.prompt.value = structured
314
- ? JSON.stringify(example.content, null, 2)
315
- : example.content;
316
- element.prompt.focus();
317
- });
318
- }
319
- }
320
-
321
- function showView(name) {
322
- for (const tab of document.querySelectorAll(".main-tab")) {
323
- tab.classList.toggle("active", tab.dataset.view === name);
324
- }
325
- for (const view of document.querySelectorAll(".main-view")) {
326
- view.classList.toggle("active", view.id === `${name}-view`);
327
- }
328
- }
329
-
330
- function setInputMode(mode) {
331
- state.inputMode = mode;
332
- for (const segment of document.querySelectorAll(".segment")) {
333
- segment.classList.toggle("active", segment.dataset.mode === mode);
334
- }
335
- const structured = mode === "json";
336
- element.prompt.classList.toggle("json-mode", structured);
337
- element.prompt.placeholder = structured
338
- ? '[\n { "type": "text", "text": "Summarize these files." },\n { "filePath": "./documents/report.pdf" },\n { "url": "https://example.com/supporting.pdf" }\n]'
339
- : "Enter a message…";
340
- element.inputHelp.textContent = structured
341
- ? "Enter the complete MessageContent[] JSON array."
342
- : "Send a plain text message.";
343
- }
344
-
345
- async function runFromComposer() {
346
- if (!state.agent || state.running) return;
347
- try {
348
- const content = parseComposerInput();
349
- addLiveMessage("user", contentText(content));
350
- await execute({ content, sessionId: state.sessionId });
351
- } catch (error) {
352
- showToast(error.message, true);
353
- }
354
- }
355
-
356
- function parseComposerInput() {
357
- const value = element.prompt.value.trim();
358
- if (!value) throw new Error("Enter an agent message.");
359
- if (state.inputMode === "text") return value;
360
- const parsed = JSON.parse(value);
361
- if (!Array.isArray(parsed) || parsed.length === 0) {
362
- throw new Error("Content JSON must be a non-empty array.");
363
- }
364
- return parsed;
365
- }
366
-
367
- async function execute(payload) {
368
- const operationId = ++state.operationId;
369
- const agentName = state.agent.name;
370
- setRunning(true);
371
- element.liveSection.classList.remove("hidden");
372
- element.clientActions.classList.add("hidden");
373
- if (!payload.toolResults) {
374
- element.runSection.classList.remove("hidden");
375
- }
376
- showView("run");
377
- let assistantMessage;
378
- try {
379
- const response = await ensureResponse(await fetch(
380
- `/api/agents/${encodeURIComponent(agentName)}/executions`,
381
- {
382
- method: "POST",
383
- headers: { "content-type": "application/json" },
384
- body: JSON.stringify(payload),
385
- },
386
- ));
387
- for await (const event of readNdjson(response.body)) {
388
- if (operationId !== state.operationId) continue;
389
- if (event.type === "snapshot") {
390
- const snapshot = event.snapshot;
391
- state.sessionId = snapshot.sessionId;
392
- element.liveSessionLabel.textContent = shortId(snapshot.sessionId);
393
- renderRunStatus(snapshot.status);
394
- if (snapshot.output !== undefined) {
395
- assistantMessage = upsertLiveAssistant(
396
- assistantMessage,
397
- outputText(snapshot.output),
398
- );
399
- }
400
- if (snapshot.status === "waiting_for_client_action") {
401
- showClientActions(snapshot.clientToolCalls);
402
- }
403
- if (snapshot.status === "failed") {
404
- addLiveMessage("system", `${snapshot.error.code}: ${snapshot.error.message}`);
405
- }
406
- } else if (event.type === "result") {
407
- setRunning(false);
408
- element.prompt.value = "";
409
- renderRunStatus(event.result.status);
410
- element.runSection.classList.toggle(
411
- "hidden",
412
- event.result.status === "waiting_for_client_action",
413
- );
414
- await refreshLiveTrace(event.result.sessionId);
415
- } else if (event.type === "evaluations") {
416
- if (event.sessionId === state.sessionId) {
417
- state.evaluations = event.evaluations;
418
- element.evaluationSession.textContent = shortId(event.sessionId);
419
- renderEvaluationResults();
420
- renderInspectorEvaluations();
421
- }
422
- } else if (event.type === "error") {
423
- throw new Error(event.error);
424
- }
425
- }
426
- if (operationId !== state.operationId) return;
427
- element.prompt.value = "";
428
- await loadSessions();
429
- } catch (error) {
430
- if (operationId === state.operationId) {
431
- addLiveMessage("system", error.message);
432
- showToast(error.message, true);
433
- }
434
- } finally {
435
- if (operationId === state.operationId) {
436
- setRunning(false);
437
- }
438
- }
439
- }
440
-
441
- function clearRun() {
442
- state.pendingCalls = [];
443
- element.prompt.value = "";
444
- element.liveTimeline.replaceChildren();
445
- element.liveSection.classList.add("hidden");
446
- element.clientActions.classList.add("hidden");
447
- element.runSection.classList.remove("hidden");
448
- renderRunStatus("");
449
- }
450
-
451
- function startNewSession() {
452
- state.sessionId = undefined;
453
- state.evaluations = [];
454
- element.evaluationSession.textContent = "Results";
455
- renderEvaluationResults();
456
- renderInspectorEvaluations();
457
- clearRun();
458
- showSessionList();
459
- element.resumeSession.classList.add("hidden");
460
- renderSessionNavigation();
461
- showView("run");
462
- element.prompt.focus();
463
- }
464
-
465
- function showClientActions(calls) {
466
- state.pendingCalls = calls;
467
- element.clientActionFields.innerHTML = calls.map((call) => `
468
- <div class="tool-field">
469
- <code>${escapeHtml(call.name)}</code>
470
- <pre>${escapeHtml(JSON.stringify(call.arguments, null, 2))}</pre>
471
- <textarea data-call-id="${escapeHtml(call.callId)}">{\n "approved": true,\n "note": "Approved for this example."\n}</textarea>
472
- </div>`).join("");
473
- element.clientActions.classList.remove("hidden");
474
- element.runSection.classList.add("hidden");
475
- }
476
-
477
- async function submitToolResults() {
478
- try {
479
- const toolResults = state.pendingCalls.map((call) => {
480
- const field = document.querySelector(`[data-call-id="${CSS.escape(call.callId)}"]`);
481
- return { callId: call.callId, output: JSON.parse(field.value) };
482
- });
483
- await execute({ sessionId: state.sessionId, toolResults });
484
- } catch (error) {
485
- showToast(`Invalid tool result: ${error.message}`, true);
486
- }
487
- }
488
-
489
- async function loadSessions() {
490
- if (!state.agent) return;
491
- const agentName = state.agent.name;
492
- try {
493
- const sessions = new Map();
494
- let page = 1;
495
- let hasMore = true;
496
- while (hasMore) {
497
- const data = await requestJson(
498
- `/api/agents/${encodeURIComponent(agentName)}/sessions?page=${page}&pageSize=100`,
499
- );
500
- for (const session of data.items) {
501
- sessions.set(session.sessionId, session);
502
- }
503
- hasMore = data.hasMore;
504
- page += 1;
505
- }
506
- if (state.agent?.name !== agentName) return;
507
- state.sessions = [...sessions.values()].sort((left, right) =>
508
- right.updatedAt.localeCompare(left.updatedAt),
509
- );
510
- element.sessionsTab.disabled = state.sessions.length === 0;
511
- renderSessionNavigation();
512
- renderCenterSessionList();
513
- } catch (error) {
514
- if (state.agent?.name === agentName) {
515
- showToast(error.message, true);
516
- }
517
- }
518
- }
519
-
520
- async function loadTests() {
521
- if (!state.agent) return;
522
- const agentName = state.agent.name;
523
- try {
524
- const data = await requestJson(
525
- `/api/agents/${encodeURIComponent(agentName)}/tests`,
526
- );
527
- if (state.agent?.name !== agentName) return;
528
- state.tests = data.tests;
529
- state.testReports = new Map();
530
- element.testSummary.className = "test-summary";
531
- element.testSummary.textContent = state.tests.length
532
- ? `${state.tests.length} registered test${state.tests.length === 1 ? "" : "s"}`
533
- : "No tests registered for this agent.";
534
- renderTests();
535
- } catch (error) {
536
- if (state.agent?.name === agentName) {
537
- element.testSummary.className = "test-summary failed";
538
- element.testSummary.textContent = error.message;
539
- }
540
- }
541
- }
542
-
543
- function renderTests() {
544
- element.testResults.innerHTML = state.tests.map((test) => {
545
- const report = state.testReports.get(test.name);
546
- return `
547
- <article class="test-card ${report?.status || ""}">
548
- <header>
549
- <div>
550
- <strong>${escapeHtml(test.name)}</strong>
551
- <div class="test-meta">${escapeHtml(test.description || "Registered agent test")}</div>
552
- </div>
553
- <button class="quiet-button test-run-button" data-test="${escapeHtml(test.name)}"><span aria-hidden="true">▶</span> ${report ? "Run again" : "Run"}</button>
554
- </header>
555
- <details class="test-definition">
556
- <summary>View complete test definition</summary>
557
- <pre class="detail-json">${escapeHtml(JSON.stringify(test.configuration, null, 2))}</pre>
558
- </details>
559
- ${report ? `
560
- <div class="test-meta">${escapeHtml(report.status.toUpperCase())} · ${report.durationMs}ms${report.evaluations?.length ? ` · ${report.evaluations.length} evaluations` : ""}</div>
561
- <div class="assertions">
562
- ${report.assertions.map((assertion) =>
563
- `<div class="assertion${assertion.passed ? "" : " failed"}">${escapeHtml(assertion.message)}</div>`,
564
- ).join("")}
565
- </div>
566
- ${report.sessionId ? `<a href="#" class="session-link" data-test-session="${escapeHtml(report.sessionId)}">Open session ${escapeHtml(shortId(report.sessionId))}</a>` : ""}
567
- ` : ""}
568
- </article>`;
569
- }).join("");
570
- for (const button of element.testResults.querySelectorAll(".test-run-button")) {
571
- button.addEventListener("click", () => runAgentTests(button.dataset.test));
572
- }
573
- for (const link of element.testResults.querySelectorAll(".session-link")) {
574
- link.addEventListener("click", async (event) => {
575
- event.preventDefault();
576
- await loadSessions();
577
- await selectSession(link.dataset.testSession);
578
- });
579
- }
580
- }
581
-
582
- async function runAgentTests(testName) {
583
- if (!state.agent || state.running) return;
584
- state.running = true;
585
- element.runTests.disabled = true;
586
- element.runTests.textContent = testName ? "Test running…" : "Running all…";
587
- element.testSummary.className = "test-summary";
588
- element.testSummary.textContent =
589
- `Running ${testName || "all registered tests"} with evaluations…`;
590
- try {
591
- const query = testName ? `?test=${encodeURIComponent(testName)}` : "";
592
- const report = await requestJson(
593
- `/api/agents/${encodeURIComponent(state.agent.name)}/tests${query}`,
594
- { method: "POST" },
595
- );
596
- element.testSummary.className = `test-summary ${report.status}`;
597
- element.testSummary.textContent =
598
- `${report.passed}/${report.total} passed in ${report.durationMs}ms`;
599
- for (const testCase of report.cases) {
600
- state.testReports.set(testCase.name, testCase);
601
- }
602
- renderTests();
603
- await loadSessions();
604
- } catch (error) {
605
- element.testSummary.className = "test-summary failed";
606
- element.testSummary.textContent = error.message;
607
- showToast(error.message, true);
608
- } finally {
609
- state.running = false;
610
- element.runTests.disabled = false;
611
- element.runTests.innerHTML = '<span aria-hidden="true">▶</span> Run all tests';
612
- }
613
- }
614
-
615
- function renderSessionNavigation() {
616
- const sessions = state.sessions.filter((session) => {
617
- const searchable = `${session.name || ""} ${session.sessionId} ${session.runStatus || ""}`.toLowerCase();
618
- return searchable.includes(state.sessionQuery);
619
- });
620
- element.sessionCountSide.textContent = String(state.sessions.length);
621
- element.sessionList.innerHTML = sessions.length
622
- ? sessions.map((session) => {
623
- const status = session.runStatus || "created";
624
- return `
625
- <button class="session-button${session.sessionId === state.sessionId ? " active" : ""}" data-session="${escapeHtml(session.sessionId)}">
626
- <span class="session-row-head">
627
- <strong>${escapeHtml(session.name || "Untitled session")}</strong>
628
- <span class="session-status-dot ${escapeHtml(status)}" title="${escapeHtml(status)}"></span>
629
- </span>
630
- <span class="session-row-meta">
631
- <code>${escapeHtml(shortId(session.sessionId))}</code>
632
- <time>${escapeHtml(relativeDate(session.updatedAt))}</time>
633
- </span>
634
- </button>`;
635
- }).join("")
636
- : `<div class="empty">${state.sessions.length ? "No matching sessions." : "No sessions for this agent yet."}</div>`;
637
- for (const button of element.sessionList.querySelectorAll(".session-button")) {
638
- button.addEventListener("click", () => selectSession(button.dataset.session));
639
- }
640
- }
641
-
642
- function renderCenterSessionList() {
643
- element.centerSessionCount.textContent = String(state.sessions.length);
644
- element.centerSessionList.innerHTML = state.sessions.length
645
- ? state.sessions.map((session) => {
646
- const status = session.runStatus || "created";
647
- return `
648
- <button class="center-session-card" data-center-session="${escapeHtml(session.sessionId)}">
649
- <span>
650
- <strong>${escapeHtml(session.name || "Untitled session")}</strong>
651
- <code>${escapeHtml(shortId(session.sessionId))}</code>
652
- </span>
653
- <span class="center-session-meta">
654
- <span class="status ${escapeHtml(status)}">${escapeHtml(status)}</span>
655
- <time>${escapeHtml(formatDate(session.updatedAt))}</time>
656
- </span>
657
- </button>`;
658
- }).join("")
659
- : '<div class="empty">No sessions for this agent yet.</div>';
660
- for (const button of element.centerSessionList.querySelectorAll(".center-session-card")) {
661
- button.addEventListener("click", () =>
662
- selectSession(button.dataset.centerSession),
663
- );
664
- }
665
- }
666
-
667
- async function selectSession(sessionId) {
668
- const agentName = state.agent?.name;
669
- if (!agentName) return;
670
- state.sessionId = sessionId;
671
- element.sessionsTab.disabled = false;
672
- renderSessionNavigation();
673
- showView("sessions");
674
- element.sessionsIndex.classList.add("hidden");
675
- element.sessionHistory.classList.remove("hidden");
676
- try {
677
- const agent = encodeURIComponent(agentName);
678
- const session = encodeURIComponent(sessionId);
679
- const [snapshot, eventData, children] = await Promise.all([
680
- requestJson(`/api/agents/${agent}/sessions/${session}`),
681
- requestJson(`/api/agents/${agent}/sessions/${session}/events`),
682
- requestJson(`/api/agents/${agent}/sessions/${session}/children`),
683
- ]);
684
- if (
685
- state.agent?.name !== agentName ||
686
- state.sessionId !== sessionId
687
- ) {
688
- return;
689
- }
690
- state.children = children.items || [];
691
- renderSession(snapshot, eventData.events);
692
- renderInspectorChildren();
693
- } catch (error) {
694
- if (
695
- state.agent?.name === agentName &&
696
- state.sessionId === sessionId
697
- ) {
698
- showToast(error.message, true);
699
- }
700
- }
701
- }
702
-
703
- function renderSession(snapshot, events) {
704
- const title = snapshot.name || shortId(snapshot.sessionId);
705
- element.sessionTitle.textContent = title;
706
- element.resumeSession.classList.remove("hidden");
707
- element.inspectorTitle.textContent = title;
708
- element.inspectorStatus.textContent = snapshot.runStatus || "created";
709
- element.inspectorStatus.className = `status ${snapshot.runStatus || "created"}`;
710
- const usage = snapshot.usage;
711
- const activity = sessionActivityStats(events);
712
- element.sessionSummary.innerHTML = [
713
- inspectorFact("Session ID", snapshot.sessionId),
714
- inspectorFact("Created", formatDate(snapshot.createdAt)),
715
- inspectorFact("Updated", formatDate(snapshot.updatedAt)),
716
- inspectorFact("Input tokens", usage?.inputTokens ?? "—"),
717
- inspectorFact("Output tokens", usage?.outputTokens ?? "—"),
718
- inspectorFact("Reasoning tokens", usage?.reasoningTokens ?? "—"),
719
- inspectorFact("Model calls", activity.modelCalls),
720
- inspectorFact("Tool calls", activity.toolCalls),
721
- inspectorFact("Skills loaded", activity.skillsLoaded),
722
- inspectorFact("Pending actions", snapshot.pendingClientActions.length),
723
- inspectorFact("Metadata", JSON.stringify(snapshot.metadata, null, 2), true),
724
- ].join("");
725
- const trace = executionTraceFromEvents(events);
726
- element.sessionTimeline.innerHTML = trace.length
727
- ? trace.map(traceCard).join("")
728
- : '<div class="empty">No execution events.</div>';
729
- state.rawEvents = JSON.stringify(events, null, 2);
730
- element.rawEvents.textContent = state.rawEvents;
731
- renderLiveTrace(events);
732
- element.liveSection.classList.remove("hidden");
733
- element.liveSessionLabel.textContent = shortId(snapshot.sessionId);
734
- renderRunStatus(snapshot.runStatus || "");
735
- state.evaluations = evaluationResultsFromEvents(events);
736
- element.evaluationSession.textContent =
737
- snapshot.name || shortId(snapshot.sessionId);
738
- renderEvaluationResults();
739
- renderInspectorEvaluations();
740
- showSessionInspector();
741
- if (snapshot.runStatus === "waiting_for_client_action") {
742
- showClientActions(snapshot.pendingClientActions);
743
- } else {
744
- state.pendingCalls = [];
745
- element.clientActions.classList.add("hidden");
746
- element.runSection.classList.remove("hidden");
747
- }
748
- }
749
-
750
- function showSessionList() {
751
- element.sessionListPanel.classList.remove("hidden");
752
- element.sessionInspector.classList.add("hidden");
753
- }
754
-
755
- function showSessionsIndex() {
756
- element.sessionsIndex.classList.remove("hidden");
757
- element.sessionHistory.classList.add("hidden");
758
- }
759
-
760
- function showSessionInspector() {
761
- element.sessionListPanel.classList.add("hidden");
762
- element.sessionInspector.classList.remove("hidden");
763
- }
764
-
765
- function inspectorFact(label, value, multiline = false) {
766
- return `<div class="inspector-fact${multiline ? " multiline" : ""}">
767
- <span>${escapeHtml(label)}</span>
768
- <strong>${escapeHtml(value)}</strong>
769
- </div>`;
770
- }
771
-
772
- function renderInspectorEvaluations() {
773
- const evaluations = state.evaluations || [];
774
- element.inspectorEvaluations.className = evaluations.length
775
- ? "inspector-evaluations"
776
- : "inspector-evaluations empty";
777
- element.inspectorEvaluations.innerHTML = evaluations.length
778
- ? evaluations.map((evaluation) => `
779
- <details class="inspector-evaluation ${escapeHtml(evaluation.status)}" open>
780
- <summary>
781
- <strong>${escapeHtml(evaluation.name)}${evaluation.run ? ` · run ${evaluation.run}` : ""}</strong>
782
- <span>${escapeHtml(evaluation.status)}</span>
783
- </summary>
784
- ${evaluation.error
785
- ? `<p class="evaluation-error">${escapeHtml(evaluation.error.message)}</p>`
786
- : (evaluation.metrics || []).map((metric) => `
787
- <div class="inspector-metric">
788
- <div>
789
- <strong>${escapeHtml(metric.name)}</strong>
790
- <span>${Number(metric.score).toFixed(2)} / ${Number(metric.threshold).toFixed(2)}</span>
791
- </div>
792
- <p>${escapeHtml(metric.reasoning)}</p>
793
- </div>`).join("")}
794
- </details>`).join("")
795
- : "No evaluation results were recorded for this session.";
796
- }
797
-
798
- function renderInspectorChildren() {
799
- const children = state.children || [];
800
- element.inspectorChildren.className = children.length
801
- ? "inspector-evaluations"
802
- : "inspector-evaluations empty";
803
- element.inspectorChildren.innerHTML = children.length
804
- ? children.map((child) => `
805
- <button class="center-session-card child-session-card" data-child-session="${escapeHtml(child.sessionId)}">
806
- <span>
807
- <strong>${escapeHtml(child.agent || "Subagent")}</strong>
808
- <code>${escapeHtml(shortId(child.sessionId))}</code>
809
- </span>
810
- <span class="status ${escapeHtml(child.runStatus || child.status)}">${escapeHtml(child.runStatus || child.status)}</span>
811
- </button>`).join("")
812
- : "No child sessions were created by this session.";
813
- for (const button of element.inspectorChildren.querySelectorAll("[data-child-session]")) {
814
- button.addEventListener("click", () =>
815
- selectChildSession(button.dataset.childSession),
816
- );
817
- }
818
- }
819
-
820
- async function selectChildSession(childSessionId) {
821
- const agentName = state.agent?.name;
822
- if (!agentName) return;
823
- try {
824
- const agent = encodeURIComponent(agentName);
825
- const child = encodeURIComponent(childSessionId);
826
- const history = await requestJson(
827
- `/api/agents/${agent}/children/${child}/history?pageSize=100`,
828
- );
829
- renderChildHistory(history);
830
- element.resumeSession.classList.add("hidden");
831
- } catch (error) {
832
- showToast(error.message, true);
833
- }
834
- }
835
-
836
- function renderChildHistory(history) {
837
- const title = history.name || `${history.agent} subagent`;
838
- element.sessionTitle.textContent = title;
839
- element.inspectorTitle.textContent = title;
840
- element.inspectorStatus.textContent = history.runStatus || history.status;
841
- element.inspectorStatus.className =
842
- `status ${history.runStatus || history.status}`;
843
- element.sessionSummary.innerHTML = [
844
- inspectorFact("Child session ID", history.sessionId),
845
- inspectorFact("Agent", history.agent),
846
- inspectorFact("Parent session", history.lineage?.parentSessionId || "—"),
847
- inspectorFact("Created", formatDate(history.createdAt)),
848
- inspectorFact("Updated", formatDate(history.updatedAt)),
849
- inspectorFact("Input tokens", history.usage?.inputTokens ?? "—"),
850
- inspectorFact("Output tokens", history.usage?.outputTokens ?? "—"),
851
- inspectorFact("Reasoning tokens", history.usage?.reasoningTokens ?? "—"),
852
- ].join("");
853
- element.sessionTimeline.innerHTML = history.items.length
854
- ? history.items.map(historyCard).join("")
855
- : '<div class="empty">No projected history.</div>';
856
- state.rawEvents = JSON.stringify(history, null, 2);
857
- element.rawEvents.textContent = state.rawEvents;
858
- element.liveSection.classList.add("hidden");
859
- state.evaluations = history.items
860
- .filter((item) => item.type === "evaluation")
861
- .map((item) => ({
862
- name: item.name,
863
- status: item.status === "completed" ? "passed" : "failed",
864
- metrics: item.metrics || [],
865
- durationMs: item.durationMs,
866
- }));
867
- renderEvaluationResults();
868
- renderInspectorEvaluations();
869
- element.inspectorChildren.className = "inspector-evaluations empty";
870
- element.inspectorChildren.textContent =
871
- "Nested subagents are not available; delegation depth is limited to one.";
872
- showSessionInspector();
873
- }
874
-
875
- function historyCard(item) {
876
- return traceCard({
877
- type: item.type,
878
- label:
879
- item.type === "message"
880
- ? item.role === "user" ? "Input" : "Output"
881
- : item.type.replace("_", " "),
882
- title: item.name,
883
- status: item.status,
884
- content: item.content ? contentText(item.content) : item.summary,
885
- fields: [
886
- ...(item.childSessionId ? [["Child session", item.childSessionId]] : []),
887
- ...(typeof item.durationMs === "number"
888
- ? [["Duration", `${item.durationMs}ms`]]
889
- : []),
890
- ],
891
- });
892
- }
893
-
894
- async function refreshLiveTrace(sessionId) {
895
- const agentName = state.agent?.name;
896
- if (!agentName) return;
897
- const agent = encodeURIComponent(agentName);
898
- const session = encodeURIComponent(sessionId);
899
- const data = await requestJson(
900
- `/api/agents/${agent}/sessions/${session}/events`,
901
- );
902
- if (
903
- state.agent?.name !== agentName ||
904
- state.sessionId !== sessionId
905
- ) {
906
- return;
907
- }
908
- renderLiveTrace(data.events);
909
- }
910
-
911
- function renderLiveTrace(events) {
912
- const trace = executionTraceFromEvents(events);
913
- element.liveTimeline.replaceChildren();
914
- for (const item of trace) {
915
- addLiveMessage(item.type, item.value);
916
- }
917
- }
918
-
919
- function executionTraceFromEvents(events) {
920
- const trace = [];
921
- const actionCalls = new Map();
922
- const internalSkillCalls = new Set();
923
- for (const event of events) {
924
- if (event.type === "run.started") {
925
- trace.push({
926
- type: "run",
927
- label: "Run started",
928
- status: event.data.status,
929
- fields: [
930
- ["Run", event.run],
931
- ["Provider", event.data.provider],
932
- ["Model", event.data.model],
933
- ],
934
- });
935
- }
936
- if (event.type === "message.created" && event.data.role === "user") {
937
- trace.push({
938
- type: "input",
939
- label: "Input",
940
- content: contentText(event.data.content),
941
- });
942
- }
943
- if (event.type === "message.created" && event.data.role === "assistant") {
944
- const assistantContent = event.data.content || [];
945
- const hasReasoningText = assistantContent.some(
946
- (block) =>
947
- block.type === "reasoning" &&
948
- typeof block.text === "string" &&
949
- block.text.trim(),
950
- );
951
- if (
952
- !hasReasoningText &&
953
- event.data.usage?.reasoningTokens > 0
954
- ) {
955
- trace.push({
956
- type: "reasoning",
957
- label: "Reasoning",
958
- content: `${event.data.provider || "The provider"} returned no displayable reasoning summary.`,
959
- fields: [["Tokens used", event.data.usage.reasoningTokens]],
960
- });
961
- }
962
- for (const block of assistantContent) {
963
- if (block.type === "reasoning") {
964
- if (typeof block.text === "string" && block.text.trim()) {
965
- trace.push({
966
- type: "reasoning",
967
- label: "Reasoning",
968
- content: block.text,
969
- fields: typeof event.data.usage?.reasoningTokens === "number"
970
- ? [["Tokens used", event.data.usage?.reasoningTokens]]
971
- : [],
972
- });
973
- }
974
- } else if (block.type === "text") {
975
- trace.push({
976
- type: "output",
977
- label: "Output",
978
- content: formatStructuredText(block.text),
979
- });
980
- } else if (block.type === "tool_call") {
981
- if (block.name === "load_skill") {
982
- internalSkillCalls.add(block.callId);
983
- continue;
984
- }
985
- actionCalls.set(block.callId, {
986
- name: block.name,
987
- arguments: block.arguments,
988
- });
989
- }
990
- }
991
- }
992
- if (event.type === "action.requested") {
993
- const call = actionCalls.get(event.data.callId);
994
- trace.push({
995
- type: "action",
996
- label: "Action requested",
997
- title: event.data.name || call?.name,
998
- status: "running",
999
- fields: [["Execution", "local"]],
1000
- sections: [[
1001
- "Arguments",
1002
- JSON.stringify(event.data.arguments ?? call?.arguments, null, 2),
1003
- ]],
1004
- });
1005
- }
1006
- if (event.type === "action.completed" || event.type === "action.failed") {
1007
- const call = actionCalls.get(event.data.callId);
1008
- trace.push({
1009
- type: "action",
1010
- label:
1011
- event.type === "action.completed"
1012
- ? "Action result"
1013
- : "Action failed",
1014
- title: event.data.name || call?.name,
1015
- status:
1016
- event.type === "action.completed" ? "completed" : "failed",
1017
- fields: [
1018
- ["Execution", "local"],
1019
- ...(typeof event.data.durationMs === "number"
1020
- ? [["Duration", `${event.data.durationMs}ms`]]
1021
- : []),
1022
- ],
1023
- sections: [[
1024
- event.type === "action.completed" ? "Result" : "Error",
1025
- JSON.stringify(
1026
- event.type === "action.completed"
1027
- ? event.data.output
1028
- : event.data.error,
1029
- null,
1030
- 2,
1031
- ),
1032
- ]],
1033
- });
1034
- }
1035
- if (event.type === "client_action.requested") {
1036
- for (const call of event.data.calls || []) {
1037
- actionCalls.set(call.callId, {
1038
- name: call.name,
1039
- arguments: call.arguments,
1040
- });
1041
- trace.push({
1042
- type: "action",
1043
- label: "Client action requested",
1044
- title: call.name,
1045
- status: "waiting",
1046
- fields: [["Execution", "client"]],
1047
- sections: [[
1048
- "Arguments",
1049
- JSON.stringify(call.arguments, null, 2),
1050
- ]],
1051
- });
1052
- }
1053
- }
1054
- if (event.type === "client_action.resolved") {
1055
- for (const result of event.data.results || []) {
1056
- const call = actionCalls.get(result.callId);
1057
- trace.push({
1058
- type: "action",
1059
- label: "Client action result",
1060
- title: call?.name,
1061
- status: result.isError === true ? "failed" : "completed",
1062
- fields: [["Execution", "client"]],
1063
- sections: [[
1064
- result.isError === true ? "Error" : "Result",
1065
- JSON.stringify(result.output, null, 2),
1066
- ]],
1067
- });
1068
- }
1069
- }
1070
- if (event.type === "message.created" && event.data.role === "tool") {
1071
- for (const result of event.data.content || []) {
1072
- if (
1073
- internalSkillCalls.has(result.callId) ||
1074
- actionCalls.has(result.callId)
1075
- ) {
1076
- continue;
1077
- }
1078
- trace.push({
1079
- type: "action",
1080
- label: "Action result",
1081
- status: result.isError === true ? "failed" : "completed",
1082
- sections: [[
1083
- result.isError === true ? "Error" : "Result",
1084
- JSON.stringify(result.output, null, 2),
1085
- ]],
1086
- });
1087
- }
1088
- }
1089
- if (event.type === "skill.loaded" || event.type === "skill.failed") {
1090
- const skill = state.agent?.skills.find(
1091
- (candidate) => candidate.name === event.data.name,
1092
- );
1093
- trace.push({
1094
- type: "skill",
1095
- label: "Skill",
1096
- title: event.data.name,
1097
- status: event.type === "skill.loaded" ? "loaded" : "failed",
1098
- content: skill?.instructions,
1099
- });
1100
- }
1101
- if (event.type === "subagent.initiated") {
1102
- trace.push({
1103
- type: "action",
1104
- label: "Subagent initiated",
1105
- title: event.data.agent,
1106
- status: event.data.status,
1107
- fields: [
1108
- ["Session", event.data.sessionId],
1109
- ["Call", event.data.callId],
1110
- ],
1111
- });
1112
- }
1113
- if (event.type === "subagent.resumed") {
1114
- trace.push({
1115
- type: "action",
1116
- label: "Subagent resumed",
1117
- title: event.data.agent,
1118
- status: event.data.status,
1119
- fields: [
1120
- ["Session", event.data.sessionId],
1121
- ["Call", event.data.callId],
1122
- ],
1123
- });
1124
- }
1125
- if (
1126
- event.type === "subagent.completed" ||
1127
- event.type === "subagent.paused" ||
1128
- event.type === "subagent.failed"
1129
- ) {
1130
- trace.push({
1131
- type: "action",
1132
- label: event.type.replace(".", " "),
1133
- title: event.data.agent,
1134
- status: event.data.status,
1135
- fields: [["Session", event.data.sessionId]],
1136
- sections: [[
1137
- event.data.error ? "Error" : "Result",
1138
- JSON.stringify(event.data.error || event.data.output, null, 2),
1139
- ]],
1140
- });
1141
- }
1142
- if (
1143
- event.type === "run.completed" ||
1144
- event.type === "run.paused" ||
1145
- event.type === "run.failed"
1146
- ) {
1147
- trace.push({
1148
- type: "run",
1149
- label: event.type.replace(".", " "),
1150
- status: event.data.status,
1151
- fields: [
1152
- ...(typeof event.data.durationMs === "number"
1153
- ? [["Duration", `${event.data.durationMs}ms`]]
1154
- : []),
1155
- ],
1156
- sections: event.data.usage
1157
- ? [["Usage", JSON.stringify(event.data.usage, null, 2)]]
1158
- : [],
1159
- });
1160
- }
1161
- if (event.type === "test.completed") {
1162
- trace.push({
1163
- type: "test",
1164
- label: "Test completed",
1165
- title: event.data.test,
1166
- status: event.data.status,
1167
- fields: [
1168
- ["Suite", event.data.suiteId],
1169
- ...(typeof event.data.durationMs === "number"
1170
- ? [["Duration", `${event.data.durationMs}ms`]]
1171
- : []),
1172
- ],
1173
- sections: Array.isArray(event.data.assertions)
1174
- ? [["Assertions", JSON.stringify(event.data.assertions, null, 2)]]
1175
- : [],
1176
- });
1177
- }
1178
- }
1179
- return trace;
1180
- }
1181
-
1182
- function sessionActivityStats(events) {
1183
- let modelCalls = 0;
1184
- let toolCalls = 0;
1185
- let skillsLoaded = 0;
1186
- for (const event of events) {
1187
- if (event.type === "message.created" && event.data.role === "assistant") {
1188
- modelCalls += 1;
1189
- toolCalls += (event.data.content || []).filter(
1190
- (block) =>
1191
- block.type === "tool_call" &&
1192
- block.name !== "load_skill",
1193
- ).length;
1194
- }
1195
- if (event.type === "skill.loaded" && event.data.alreadyLoaded !== true) {
1196
- skillsLoaded += 1;
1197
- }
1198
- }
1199
- return { modelCalls, toolCalls, skillsLoaded };
1200
- }
1201
-
1202
- function traceCard(item) {
1203
- return `<article class="message ${escapeHtml(item.type)}">
1204
- <header class="event-heading">
1205
- <span>${escapeHtml(item.label || item.type)}</span>
1206
- ${item.status ? `<strong>${escapeHtml(item.status)}</strong>` : ""}
1207
- </header>
1208
- ${item.title ? `<div class="event-title">${escapeHtml(item.title)}</div>` : ""}
1209
- ${item.fields?.length ? `<dl class="event-fields">${item.fields.map(([name, value]) => `
1210
- <div><dt>${escapeHtml(name)}</dt><dd>${escapeHtml(value ?? "—")}</dd></div>`).join("")}</dl>` : ""}
1211
- ${item.content ? `<div class="event-content">${escapeHtml(item.content)}</div>` : ""}
1212
- ${item.sections?.map(([name, value]) => `
1213
- <div class="event-section">
1214
- <span>${escapeHtml(name)}</span>
1215
- <pre>${escapeHtml(value)}</pre>
1216
- </div>`).join("") || ""}
1217
- </article>`;
1218
- }
1219
-
1220
- function addLiveMessage(role, text) {
1221
- const displayRole =
1222
- role === "user" ? "input" : role === "assistant" ? "output" : role;
1223
- const message = document.createElement("div");
1224
- message.className = `message ${displayRole}`;
1225
- message.innerHTML = `
1226
- <header class="event-heading"><span>${escapeHtml(displayRole)}</span></header>
1227
- <div class="event-content"></div>`;
1228
- message.querySelector(".event-content").textContent = text;
1229
- element.liveTimeline.append(message);
1230
- return message;
1231
- }
1232
-
1233
- function upsertLiveAssistant(message, text) {
1234
- const target = message || addLiveMessage("output", "");
1235
- target.querySelector(".event-content").textContent = text;
1236
- return target;
1237
- }
1238
-
1239
- function setRunning(running) {
1240
- state.running = running;
1241
- element.runButton.disabled = running;
1242
- element.runButton.textContent = running ? "Running…" : "Try agent";
1243
- }
1244
-
1245
- function renderRunStatus(status) {
1246
- element.runStatus.className = `status ${status}`;
1247
- element.runStatus.innerHTML = status === "running"
1248
- ? '<span class="status-spinner" aria-hidden="true"></span><span>running</span>'
1249
- : escapeHtml(status);
1250
- }
1251
-
1252
- async function requestJson(url, options) {
1253
- return (await ensureResponse(await fetch(url, options))).json();
1254
- }
1255
-
1256
- async function ensureResponse(response) {
1257
- if (response.ok) return response;
1258
- let message = `Request failed with ${response.status}.`;
1259
- try { message = (await response.json()).error || message; } catch {}
1260
- throw new Error(message);
1261
- }
1262
-
1263
- async function* readNdjson(stream) {
1264
- const reader = stream.getReader();
1265
- const decoder = new TextDecoder();
1266
- let buffer = "";
1267
- while (true) {
1268
- const { done, value } = await reader.read();
1269
- buffer += decoder.decode(value, { stream: !done });
1270
- const lines = buffer.split("\n");
1271
- buffer = lines.pop() || "";
1272
- for (const line of lines) if (line.trim()) yield JSON.parse(line);
1273
- if (done) {
1274
- if (buffer.trim()) yield JSON.parse(buffer);
1275
- return;
1276
- }
1277
- }
1278
- }
1279
-
1280
- function capability(name, description, type, metadata, details) {
1281
- return `<details class="capability-card">
1282
- <summary>
1283
- <span class="capability-summary">
1284
- <strong>${escapeHtml(name)}</strong>
1285
- <span>${escapeHtml(description)}</span>
1286
- </span>
1287
- <span class="type ${escapeHtml(type)}">${escapeHtml(type)}</span>
1288
- </summary>
1289
- <div class="capability-details">
1290
- <div class="meta">${escapeHtml(metadata)}</div>
1291
- ${details === undefined
1292
- ? ""
1293
- : typeof details === "string"
1294
- ? `<div class="instruction-detail"><span class="overline">Instructions</span><pre>${escapeHtml(details)}</pre></div>`
1295
- : `<pre class="detail-json">${escapeHtml(JSON.stringify(details, null, 2))}</pre>`}
1296
- </div>
1297
- </details>`;
1298
- }
1299
-
1300
- function configuration(name, value) {
1301
- return `<div class="configuration-item"><span>${escapeHtml(name)}</span><strong title="${escapeHtml(String(value))}">${escapeHtml(String(value))}</strong></div>`;
1302
- }
1303
-
1304
- function badge(value) {
1305
- return `<span class="badge">${escapeHtml(value)}</span>`;
1306
- }
1307
-
1308
- function schemaSummary(schema) {
1309
- const required = schema?.required || [];
1310
- return required.length ? `Requires ${required.join(", ")}` : "No required arguments";
1311
- }
1312
-
1313
- function contentText(content) {
1314
- if (typeof content === "string") return content;
1315
- if (!Array.isArray(content)) return outputText(content);
1316
- if (content.some((item) => item.type !== "text")) {
1317
- return JSON.stringify(content, null, 2);
1318
- }
1319
- return content.map((item) =>
1320
- item.text,
1321
- ).join("\n");
1322
- }
1323
-
1324
- function outputText(output) {
1325
- return typeof output === "string" ? output : JSON.stringify(output, null, 2);
1326
- }
1327
-
1328
- function formatStructuredText(text) {
1329
- try {
1330
- const value = JSON.parse(text);
1331
- return typeof value === "object" && value !== null
1332
- ? JSON.stringify(value, null, 2)
1333
- : text;
1334
- } catch {
1335
- return text;
1336
- }
1337
- }
1338
-
1339
- function evaluationResultsFromEvents(events) {
1340
- return events.flatMap((event) =>
1341
- event.type === "evaluation.completed" ||
1342
- event.type === "evaluation.failed"
1343
- ? [{ ...event.data, run: event.run }]
1344
- : [],
1345
- );
1346
- }
1347
-
1348
- function shortId(value) {
1349
- return value.length > 22 ? `${value.slice(0, 12)}…${value.slice(-6)}` : value;
1350
- }
1351
-
1352
- function formatDate(value) {
1353
- return value ? new Date(value).toLocaleString() : "";
1354
- }
1355
-
1356
- function relativeDate(value) {
1357
- const timestamp = new Date(value).getTime();
1358
- const delta = Date.now() - timestamp;
1359
- if (!Number.isFinite(timestamp)) return "";
1360
- if (delta < 60_000) return "just now";
1361
- if (delta < 3_600_000) return `${Math.floor(delta / 60_000)}m ago`;
1362
- if (delta < 86_400_000) return `${Math.floor(delta / 3_600_000)}h ago`;
1363
- if (delta < 604_800_000) return `${Math.floor(delta / 86_400_000)}d ago`;
1364
- return new Date(value).toLocaleDateString();
1365
- }
1366
-
1367
- function camel(value) {
1368
- return value.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
1369
- }
1370
-
1371
- function escapeHtml(value) {
1372
- return String(value ?? "")
1373
- .replaceAll("&", "&amp;")
1374
- .replaceAll("<", "&lt;")
1375
- .replaceAll(">", "&gt;")
1376
- .replaceAll('"', "&quot;")
1377
- .replaceAll("'", "&#039;");
1378
- }
1379
-
1380
- let toastTimer;
1381
- function showToast(message, error = false) {
1382
- clearTimeout(toastTimer);
1383
- element.toast.textContent = message;
1384
- element.toast.className = `toast visible${error ? " error" : ""}`;
1385
- toastTimer = setTimeout(() => {
1386
- element.toast.className = "toast";
1387
- }, 3500);
1388
- }