-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathviewer.js
More file actions
320 lines (307 loc) · 11 KB
/
Copy pathviewer.js
File metadata and controls
320 lines (307 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
/**
* Rendering library for opencode-trace logs.
*
* An opencode-trace log is a sequence of jsonl lines in an unterminated `<!` + `--` comment at the end of an HTML document.
* This module extracts that log and renders each line as a collapsible tree-structure.
*
* There's a little bit of cleverness. This module uses a `render()` function to determine how nodes in the tree
* should be rendered. Normally they're rendered in the normal way (primitives as leaf nodes, objects and arrays as
* collapsible nodes whose children are recursively rendered). But if the `render()` function at any level returns
* an object with special properties `{Symbol('TITLE'): ..., Symbol('INLINE'): ..., body: ..., open: ...}`
* then that object decides how it should be rendered in the tree. Within an object/array, it will be rendered
* as "▷ TITLE: INLINE" when collapsed, or "▽ TITLE" when expanded, with 'body' an object/array/primitive for
* the contents of that expanded node. The `open` flag says whether it should be initially expanded.
*
* This module has special handling for REQUEST and RESPONSE json payloads for Opencode's communication with an LLM.
*/
const TITLE = Symbol('TITLE');
const INLINE = Symbol('INLINE');
// Invariant: the contents of [TITLE] and [INLINE] have both been escaped
/**
* Turns an html string into a DOM node
*/
function fromHTML(html) {
const t = document.createElement('template');
t.innerHTML = html.trim();
return t.content.firstElementChild;
}
/**
* Escapes string for safe insertion into HTML
*/
function esc(s) {
s = String(s ?? '');
return s
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/\n/g, '<br/>')
.replace(/\\n/g, '<br/>');
}
/**
* Given a datstring in ISO format, returns HH:MM:SS
*/
function ts(data) {
return data?._ts?.slice(11, 19) ?? '?';
}
/**
* Puts a string onto a single line and truncates to 80 chars, for display in INLINE part of a node
*/
function short(s) {
return String(s ?? '')
.replace(/\n/g, ' ')
.slice(0, 80);
}
/**
* Interprets a message-content array into text for display.
* If we're given undefined, returns an empty string.
*/
function contentText(contents) {
if (typeof contents === 'string') return contents;
if (!Array.isArray(contents)) return JSON.stringify(contents ?? '');
let r = [];
for (const c of contents ?? []) {
const type = c && typeof c === 'object' ? deltaField(c, 'type') : undefined;
const text = c && typeof c === 'object' ? deltaField(c, 'text') : c;
if (type === 'input_text') {
const raw = String(text ?? '');
const divider = '## My request for Codex:';
const i = raw.indexOf(divider);
r.push(i < 0 ? raw : raw.slice(i + divider.length).replace(/^\s+/, ''));
} else if (type === 'output_text' || type === 'text') {
r.push(String(text ?? ''));
} else r.push(`[${String(type ?? '?')}]`);
}
return r.join('\n');
}
/**
* The payload uses deltas which rename keys, so instead of r.content we might
* see r.*content or r.content+ or r.content-. This function gets whichever.
*/
function deltaField(data, key) {
return deltaFieldInfo(data, key).value;
}
function deltaFieldInfo(data, key) {
if (!data || typeof data !== 'object') return {value: undefined, marker: ''};
if (data[key] !== undefined) return {value: data[key], marker: ''};
if (data[`+${key}`] !== undefined) return {value: data[`+${key}`], marker: '[+] '};
if (data[`${key}+`] !== undefined) return {value: data[`${key}+`], marker: '[+] '};
if (data[`-${key}`] !== undefined) return {value: data[`-${key}`], marker: '[-] '};
if (data[`${key}-`] !== undefined) return {value: data[`${key}-`], marker: '[-] '};
if (data[`*${key}`] !== undefined) return {value: data[`*${key}`], marker: '[*] '};
return {value: undefined, marker: ''};
}
function deltaMarker(data) {
if (!data || typeof data !== 'object' || Array.isArray(data)) return '';
const keys = Object.keys(data);
if (keys.some(k => k.startsWith('*'))) return '[*] ';
if (keys.some(k => k.startsWith('+') || k.endsWith('+'))) return '[+] ';
if (keys.some(k => k.startsWith('-') || k.endsWith('-'))) return '[-] ';
return '';
}
/**
* Renders a sequence of payload elements from either OpenAI or Anthropic payloads.
*/
function renderPayload(elements) {
if (!Array.isArray(elements)) return [];
const payload = [];
for (const e of elements) {
const eContent = deltaField(e, 'content'); // because it might be e.content or e.*content or e.content+ or e.content-
const eText = deltaField(e, 'text');
const eOutput = deltaField(e, 'output');
const eArguments = deltaField(e, 'arguments');
const eInput = deltaField(e, 'input');
const eMessage = deltaField(e, 'message') ?? deltaField(e, 'delta');
const eName = deltaField(e, 'name');
const eType = deltaField(e, 'type');
const eRole = deltaField(e, 'role');
const marker = deltaMarker(e);
if (e === '...' || e === '...*' || e === '---') {
continue;
} else if (eMessage && typeof eMessage === 'object' && !Array.isArray(eMessage)) {
// OpenAI chat-completion choices wrap the assistant message in an object here.
payload.push(...renderPayload([eMessage]));
} else if (
eType === 'message' ||
(eType === undefined && eRole !== undefined && eContent !== undefined)
) {
const contents = Array.isArray(eContent) ? eContent : [eContent];
contents.forEach(content => {
if (content === '...' || content === '...*' || content === '---') {
return;
}
const text = contentText(Array.isArray(eContent) ? [content] : content);
payload.push({
[TITLE]: `${marker}message(${esc(eRole)}): `,
[INLINE]: esc(short(text)),
body: text,
});
});
} else if (eType === 'input_text' || eType === 'output_text' || eType === 'text') {
payload.push({
[TITLE]: `${marker}${eType}: `,
[INLINE]: esc(short(String(eText ?? ''))),
body: eText,
});
} else if (eType === 'function_call_output' || eType === 'tool_result') {
const result =
eType === 'function_call_output'
? typeof eOutput === 'string'
? eOutput
: JSON.stringify(eOutput ?? '')
: typeof eContent === 'string'
? eContent
: contentText(eContent);
payload.push({
[TITLE]: marker,
[INLINE]: `${esc(eType)}: ${esc(short(result))}`,
body: e,
});
} else if (eType === 'function_call' || eType === 'tool_use') {
let arg = '';
try {
const raw = eType === 'function_call' ? JSON.parse(eArguments) : eInput;
const rawArg = raw?.cmd ?? raw?.pattern ?? raw;
arg = typeof rawArg === 'string' ? rawArg : JSON.stringify(rawArg ?? '');
} catch {
arg = '...';
}
payload.push({
[TITLE]: marker,
[INLINE]: `${esc(eType)}: ${esc(eName ?? '???')}(${esc(short(arg))})`,
body: e,
});
} else {
payload.push({
[TITLE]: marker,
[INLINE]: esc(eType ?? '???'),
body: e,
});
}
}
return payload;
}
/**
* Renders a node in the tree.
* If it looks like a REQUEST or RESPONSE payload (has ._kind property) then pretty-prints it.
* The goal of this pretty-printing is not to be 100% faithful; instead it's solely to surface
* to the users some of the most important lines, for their attention.
* Otherwise, renders primtives, objects, arrays in the obvious way.
*/
function render(data, label) {
const id = data?._id !== undefined ? ` #${esc(String(data._id))}` : '';
const purpose = data?._purpose ? ` ${esc(String(data._purpose))}` : '';
const isPrimary =
data?._purpose === undefined ||
data?._purpose === '' ||
data?._purpose === '[turn]' ||
data?._purpose === '[/responses]';
if (data?.[TITLE] !== undefined) {
return data;
} else if (data?._kind === 'request') {
const rendered = renderPayload(deltaField(data, 'input') ?? deltaField(data, 'messages'));
const raw = {...data};
delete raw._kind;
const title = `REQUEST${id}${purpose}`;
return {
[TITLE]: `[${esc(ts(data))}] ${isPrimary ? `<b>${title}</b>` : title} `,
body: [...rendered, {[TITLE]: 'raw', body: raw}],
open: isPrimary,
};
} else if (data?._kind === 'response') {
const payload = renderPayload(
deltaField(data, 'output') ?? deltaField(data, 'content') ?? deltaField(data, 'choices'),
);
const raw = {...data};
delete raw._kind;
const title = `RESPONSE${id}${purpose}`;
return {
[TITLE]: `[${esc(ts(data))}] ${isPrimary ? `<b>${title}</b>` : title} `,
body: [...payload, {[TITLE]: 'raw', body: raw}],
open: isPrimary,
};
} else if (data?._kind === 'error') {
const raw = {...data};
return {
[TITLE]: `[${esc(ts(data))}] <b>ERROR${id}${purpose}</b> `,
[INLINE]: esc(short(data._error)),
body: [
data._error ?? '???',
...(data._stack ? [{[TITLE]: 'stack', body: data._stack}] : []),
{[TITLE]: 'raw', body: raw},
],
open: true,
};
} else if (data?._kind !== undefined && data?._ts !== undefined) {
const raw = {...data};
return {
[TITLE]: `[${esc(ts(data))}] <b>${esc(data._kind)}</b> `,
body: raw,
open: true,
};
} else {
return {
[TITLE]: esc(label),
[INLINE]: esc(
Array.isArray(data)
? `[...${data.length} items]`
: '{' +
Object.keys(data)
.map(k => `${JSON.stringify(k)}:`)
.join(',') +
'}',
),
body: data,
numbered: true,
};
}
}
function buildNode(data, label) {
if (data && typeof data === 'object') {
const r = render(data, label);
const d = fromHTML(
`<details><summary>${r[TITLE]}<output>${r[INLINE] ?? ''}</output></summary></details>`,
);
d.addEventListener(
'toggle',
() => {
if (r.body === undefined) {
// skip
} else if (Array.isArray(r.body)) {
r.body.forEach((item, i) =>
d.appendChild(buildNode(item, r?.numbered ? `${i + 1}: ` : '')),
);
} else if (r.body && typeof r.body === 'object') {
Object.keys(r.body).forEach(k =>
d.appendChild(buildNode(r.body[k], `${JSON.stringify(k)}: `)),
);
} else {
d.appendChild(buildNode(r.body, ''));
}
},
{once: true},
);
d.open = r.open;
return d;
} else {
return fromHTML(`<div>${esc(label)}${esc(JSON.stringify(data))}</div>`);
}
}
window.addEventListener('DOMContentLoaded', () => {
if (
document.lastChild &&
document.lastChild.nodeType === Node.COMMENT_NODE &&
document.lastChild.data.trim()
) {
for (const line of document.lastChild.data.split(/\r?\n/).filter(Boolean)) {
let data = '';
try {
data = JSON.parse(line);
} catch (e) {
data = {error: String(e), raw: line};
}
const node = buildNode(data, 'json:');
node.classList.add('log-entry');
document.body.appendChild(node);
}
}
});