@thinkrun/cli 0.1.39 → 0.1.42
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +27 -0
- package/dist/bin/thinkrun.js +9 -2
- package/dist/bin/thinkrun.js.map +1 -1
- package/dist/scripts/browse.sh +40 -7
- package/dist/shared/analysis-plans.d.ts +10 -0
- package/dist/shared/analysis-plans.js +12 -0
- package/dist/shared/batch-steps.d.ts +49 -0
- package/dist/shared/batch-steps.js +171 -0
- package/dist/shared/batch-steps.test.js +127 -0
- package/dist/shared/group-binding-key.d.ts +5 -0
- package/dist/shared/group-binding-key.js +15 -0
- package/dist/shared/group-binding-key.test.js +50 -0
- package/dist/shared/issue-report.d.ts +10 -0
- package/dist/shared/issue-report.js +126 -0
- package/dist/shared/issue-report.test.ts +110 -0
- package/dist/shared/native-type-budget.d.ts +16 -0
- package/dist/shared/native-type-budget.js +28 -0
- package/dist/shared/navigation-retry.d.ts +2 -0
- package/dist/shared/navigation-retry.js +26 -0
- package/dist/shared/navigation-retry.test.js +25 -0
- package/dist/shared/onboarding-drips.d.ts +13 -0
- package/dist/shared/onboarding-drips.js +100 -0
- package/dist/shared/onboarding-metrics.d.ts +4 -0
- package/dist/shared/onboarding-metrics.js +53 -0
- package/dist/shared/selector-hints.d.ts +1 -0
- package/dist/shared/selector-hints.js +43 -0
- package/dist/shared/selector-hints.test.js +31 -0
- package/dist/shared/slack-report.d.ts +21 -0
- package/dist/shared/slack-report.js +381 -0
- package/dist/src/adapters/cloud.d.ts +2 -0
- package/dist/src/adapters/cloud.d.ts.map +1 -1
- package/dist/src/adapters/cloud.js +112 -17
- package/dist/src/adapters/cloud.js.map +1 -1
- package/dist/src/adapters/index.d.ts.map +1 -1
- package/dist/src/adapters/index.js +30 -5
- package/dist/src/adapters/index.js.map +1 -1
- package/dist/src/adapters/local.d.ts +3 -0
- package/dist/src/adapters/local.d.ts.map +1 -1
- package/dist/src/adapters/local.js +52 -13
- package/dist/src/adapters/local.js.map +1 -1
- package/dist/src/commands/actions.d.ts +12 -0
- package/dist/src/commands/actions.d.ts.map +1 -1
- package/dist/src/commands/actions.js +115 -28
- package/dist/src/commands/actions.js.map +1 -1
- package/dist/src/commands/analyze.d.ts.map +1 -1
- package/dist/src/commands/analyze.js +29 -1
- package/dist/src/commands/analyze.js.map +1 -1
- package/dist/src/commands/audit.d.ts.map +1 -1
- package/dist/src/commands/audit.js +5 -4
- package/dist/src/commands/audit.js.map +1 -1
- package/dist/src/commands/cloud.d.ts.map +1 -1
- package/dist/src/commands/cloud.js +3 -1
- package/dist/src/commands/cloud.js.map +1 -1
- package/dist/src/commands/config.d.ts.map +1 -1
- package/dist/src/commands/config.js +15 -0
- package/dist/src/commands/config.js.map +1 -1
- package/dist/src/commands/evaluate-helpers.d.ts.map +1 -1
- package/dist/src/commands/evaluate-helpers.js +10 -2
- package/dist/src/commands/evaluate-helpers.js.map +1 -1
- package/dist/src/commands/install-skills.d.ts +27 -0
- package/dist/src/commands/install-skills.d.ts.map +1 -0
- package/dist/src/commands/install-skills.js +81 -0
- package/dist/src/commands/install-skills.js.map +1 -0
- package/dist/src/commands/install.d.ts.map +1 -1
- package/dist/src/commands/install.js +44 -1
- package/dist/src/commands/install.js.map +1 -1
- package/dist/src/commands/login.d.ts +3 -0
- package/dist/src/commands/login.d.ts.map +1 -0
- package/dist/src/commands/login.js +62 -0
- package/dist/src/commands/login.js.map +1 -0
- package/dist/src/commands/setup.d.ts.map +1 -1
- package/dist/src/commands/setup.js +8 -16
- package/dist/src/commands/setup.js.map +1 -1
- package/dist/src/config/store.d.ts.map +1 -1
- package/dist/src/config/store.js +1 -0
- package/dist/src/config/store.js.map +1 -1
- package/dist/src/local-bridge-timing.d.ts +3 -0
- package/dist/src/local-bridge-timing.d.ts.map +1 -1
- package/dist/src/local-bridge-timing.js +3 -0
- package/dist/src/local-bridge-timing.js.map +1 -1
- package/dist/src/session/account-guidance.d.ts +10 -0
- package/dist/src/session/account-guidance.d.ts.map +1 -0
- package/dist/src/session/account-guidance.js +32 -0
- package/dist/src/session/account-guidance.js.map +1 -0
- package/dist/src/session/browser-login.d.ts +6 -0
- package/dist/src/session/browser-login.d.ts.map +1 -0
- package/dist/src/session/browser-login.js +83 -0
- package/dist/src/session/browser-login.js.map +1 -0
- package/dist/src/types.d.ts +3 -1
- package/dist/src/types.d.ts.map +1 -1
- package/dist/src/utils.d.ts +9 -3
- package/dist/src/utils.d.ts.map +1 -1
- package/dist/src/utils.js +24 -3
- package/dist/src/utils.js.map +1 -1
- package/dist/src/working-location.d.ts +1 -1
- package/dist/src/working-location.d.ts.map +1 -1
- package/dist/src/working-location.js +89 -67
- package/dist/src/working-location.js.map +1 -1
- package/package.json +3 -2
- package/skills/thinkrun/SKILL.md +66 -0
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deterministic projection of an approved Markdown report into one Slack message.
|
|
3
|
+
* The backend posts exactly `message`; the frontend preview renders the same blocks.
|
|
4
|
+
*
|
|
5
|
+
* Safety model: Markdown is parsed with a CommonMark parser, never with ad hoc regexes.
|
|
6
|
+
* User text only ever becomes `plain_text` (header) or rich_text `text` elements, which
|
|
7
|
+
* Slack does not interpret as mrkdwn, mentions, broadcasts or emoji shortcodes. No user,
|
|
8
|
+
* channel, usergroup or broadcast elements are ever produced. Only valid HTTPS links
|
|
9
|
+
* without credentials become link elements; nothing is fetched, uploaded or unfurled.
|
|
10
|
+
*
|
|
11
|
+
* The CommonMark parser (`mdast-util-from-markdown`) is supplied by each consumer, which
|
|
12
|
+
* declares the same pinned version, so resolution never depends on this package's location.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
export const SLACK_REPORT_TITLE_LIMIT = 256;
|
|
16
|
+
export const SLACK_REPORT_BODY_LIMIT = 12000;
|
|
17
|
+
export const SLACK_REPORT_MODES = ['compact', 'full'];
|
|
18
|
+
const HEADER_LIMIT = 150; // Slack header blocks accept at most 150 characters.
|
|
19
|
+
const BLOCK_LIMIT = 50; // Slack messages accept at most 50 blocks.
|
|
20
|
+
const BLOCK_TEXT_BUDGET = 2900;
|
|
21
|
+
const EXCERPT_LIMIT = 700;
|
|
22
|
+
const EVIDENCE_LIMIT = 10;
|
|
23
|
+
const NESTING_LIMIT = 12;
|
|
24
|
+
const LIST_INDENT_LIMIT = 6;
|
|
25
|
+
const CONTEXT_NOTE = 'Summary view of a ThinkRun report; the full report is not included.';
|
|
26
|
+
const RECORDING_NOTE = ' The recording link opens the source recording and its analysis, not this edited report.';
|
|
27
|
+
|
|
28
|
+
export class SlackReportError extends Error {
|
|
29
|
+
constructor(code, message) { super(message); this.name = 'SlackReportError'; this.code = code; }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function safeSlackLinkUrl(value) {
|
|
33
|
+
if (typeof value !== 'string' || !value || value.length > 2000) return undefined;
|
|
34
|
+
try {
|
|
35
|
+
const url = new URL(value);
|
|
36
|
+
return url.protocol === 'https:' && url.hostname && !url.username && !url.password && url.href.length <= 2000 ? url.href : undefined;
|
|
37
|
+
} catch { return undefined; }
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const styled = style => Object.keys(style).length ? { style: { ...style } } : {};
|
|
41
|
+
const sameStyle = (a, b) => JSON.stringify(a.style || {}) === JSON.stringify(b.style || {});
|
|
42
|
+
function pushText(out, text, style = {}) {
|
|
43
|
+
if (!text) return;
|
|
44
|
+
const last = out[out.length - 1];
|
|
45
|
+
if (last?.type === 'text' && sameStyle(last, styled(style))) last.text += text;
|
|
46
|
+
else out.push({ type: 'text', text, ...styled(style) });
|
|
47
|
+
}
|
|
48
|
+
const inlineText = element => element.type === 'link' ? element.text || element.url : element.text || '';
|
|
49
|
+
const textLength = element => Array.isArray(element.elements) ? element.elements.reduce((n, child) => n + textLength(child), 0) : inlineText(element).length;
|
|
50
|
+
|
|
51
|
+
/** Visible text of any subtree, iteratively, so hostile nesting cannot exhaust the stack. */
|
|
52
|
+
function plainText(node) {
|
|
53
|
+
let out = '';
|
|
54
|
+
const stack = [node];
|
|
55
|
+
while (stack.length) {
|
|
56
|
+
const current = stack.pop();
|
|
57
|
+
if (typeof current === 'string') { out += current; continue; }
|
|
58
|
+
if (!current) continue;
|
|
59
|
+
if (current.type === 'image' || current.type === 'imageReference') out += current.alt || '';
|
|
60
|
+
else if (typeof current.value === 'string') out += current.value;
|
|
61
|
+
if (Array.isArray(current.children)) {
|
|
62
|
+
const separator = ['root', 'blockquote', 'list', 'listItem'].includes(current.type) ? '\n' : '';
|
|
63
|
+
for (let i = current.children.length - 1; i >= 0; i--) { stack.push(current.children[i]); if (separator && i) stack.push(separator); }
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return out;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function createConverter(definitions) {
|
|
70
|
+
const target = node => node.type === 'linkReference' || node.type === 'imageReference' ? definitions.get(node.identifier)?.url : node.url;
|
|
71
|
+
function inline(nodes, style = {}, out = [], depth = 0) {
|
|
72
|
+
for (const node of nodes) {
|
|
73
|
+
if (depth > NESTING_LIMIT) { pushText(out, plainText(node), style); continue; }
|
|
74
|
+
switch (node.type) {
|
|
75
|
+
case 'text': case 'html': pushText(out, node.value, style); break;
|
|
76
|
+
case 'inlineCode': pushText(out, node.value, { ...style, code: true }); break;
|
|
77
|
+
case 'break': pushText(out, '\n', style); break;
|
|
78
|
+
case 'strong': inline(node.children, { ...style, bold: true }, out, depth + 1); break;
|
|
79
|
+
case 'emphasis': inline(node.children, { ...style, italic: true }, out, depth + 1); break;
|
|
80
|
+
case 'image': case 'imageReference': {
|
|
81
|
+
const url = safeSlackLinkUrl(target(node));
|
|
82
|
+
const label = node.alt || 'Image';
|
|
83
|
+
if (url) out.push({ type: 'link', url, text: label, ...styled(linkStyle(style)) }); else pushText(out, label, style);
|
|
84
|
+
break;
|
|
85
|
+
}
|
|
86
|
+
case 'link': case 'linkReference': {
|
|
87
|
+
const raw = target(node) || '';
|
|
88
|
+
const url = safeSlackLinkUrl(raw);
|
|
89
|
+
const label = plainText({ children: node.children });
|
|
90
|
+
if (!url) {
|
|
91
|
+
// Unsafe or malformed targets stay visible as text and are never linked.
|
|
92
|
+
inline(node.children, style, out, depth + 1);
|
|
93
|
+
if (raw && raw !== label) pushText(out, ` (${raw})`, style);
|
|
94
|
+
break;
|
|
95
|
+
}
|
|
96
|
+
out.push({ type: 'link', url, text: label || url, ...styled(linkStyle(style)) });
|
|
97
|
+
// A linked screenshot keeps both destinations: the outer moment and the image itself.
|
|
98
|
+
for (const image of images(node)) {
|
|
99
|
+
const imageUrl = safeSlackLinkUrl(target(image));
|
|
100
|
+
if (imageUrl && imageUrl !== url) { pushText(out, ' (', style); out.push({ type: 'link', url: imageUrl, text: 'image' }); pushText(out, ')', style); }
|
|
101
|
+
}
|
|
102
|
+
break;
|
|
103
|
+
}
|
|
104
|
+
default:
|
|
105
|
+
if (Array.isArray(node.children)) inline(node.children, style, out, depth + 1);
|
|
106
|
+
else if (typeof node.value === 'string') pushText(out, node.value, style);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return out;
|
|
110
|
+
}
|
|
111
|
+
const linkStyle = style => Object.fromEntries(Object.entries(style).filter(([name]) => name === 'bold' || name === 'italic'));
|
|
112
|
+
const section = (elements, extra = {}) => ({ type: 'rich_text_section', elements, ...extra });
|
|
113
|
+
|
|
114
|
+
/** mdast blocks → rich_text elements. Headings are tagged so callers can start a new Slack block. */
|
|
115
|
+
function blocks(nodes, depth = 0, out = []) {
|
|
116
|
+
for (const node of nodes) {
|
|
117
|
+
if (depth > NESTING_LIMIT) { addParagraph(out, [{ type: 'text', text: plainText(node) }]); continue; }
|
|
118
|
+
switch (node.type) {
|
|
119
|
+
case 'heading': { const elements = inline(node.children, { bold: true }); if (elements.length) out.push(section(elements, { heading: true })); break; }
|
|
120
|
+
case 'paragraph': addParagraph(out, inline(node.children)); break;
|
|
121
|
+
case 'html': addParagraph(out, node.value ? [{ type: 'text', text: node.value }] : []); break;
|
|
122
|
+
case 'code': if (node.value) out.push({ type: 'rich_text_preformatted', elements: [{ type: 'text', text: node.value }] }); break;
|
|
123
|
+
case 'blockquote': {
|
|
124
|
+
const elements = [];
|
|
125
|
+
node.children.forEach((child, i) => {
|
|
126
|
+
if (i) pushText(elements, '\n');
|
|
127
|
+
if (child.type === 'paragraph' || child.type === 'heading') inline(child.children, {}, elements, depth + 1); else pushText(elements, plainText(child));
|
|
128
|
+
});
|
|
129
|
+
if (elements.length) out.push({ type: 'rich_text_quote', elements });
|
|
130
|
+
break;
|
|
131
|
+
}
|
|
132
|
+
case 'list': list(node, 0, out, depth); break;
|
|
133
|
+
case 'thematicBreak': out.push({ type: 'divider' }); break;
|
|
134
|
+
case 'definition': break;
|
|
135
|
+
default: { const text = plainText(node); if (text) addParagraph(out, [{ type: 'text', text }]); }
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return out;
|
|
139
|
+
}
|
|
140
|
+
function addParagraph(out, elements) {
|
|
141
|
+
if (!elements.length) return;
|
|
142
|
+
const last = out[out.length - 1];
|
|
143
|
+
// Consecutive paragraphs share one section separated by a blank line, as Slack itself does.
|
|
144
|
+
if (last?.type === 'rich_text_section' && !last.heading) { pushText(last.elements, '\n\n'); for (const element of elements) element.type === 'text' ? pushText(last.elements, element.text, element.style) : last.elements.push(element); }
|
|
145
|
+
else out.push(section(elements));
|
|
146
|
+
}
|
|
147
|
+
function list(node, indent, out, depth) {
|
|
148
|
+
const style = node.ordered ? 'ordered' : 'bullet';
|
|
149
|
+
const start = node.ordered && Number.isInteger(node.start) ? node.start : 1;
|
|
150
|
+
let current, count = 0;
|
|
151
|
+
const open = () => { current = { type: 'rich_text_list', style, indent: Math.min(indent, LIST_INDENT_LIMIT), elements: [], ...(node.ordered && start + count - 1 > 0 ? { offset: start + count - 1 } : {}) }; out.push(current); };
|
|
152
|
+
for (const item of node.children) {
|
|
153
|
+
// Keep source order: text after a nested list or code block follows it as an unbulleted continuation.
|
|
154
|
+
let elements = [], bulleted = false;
|
|
155
|
+
const flush = () => {
|
|
156
|
+
if (!elements.length) return;
|
|
157
|
+
if (bulleted) out.push(section(elements));
|
|
158
|
+
else { if (!current || out[out.length - 1] !== current) open(); current.elements.push(section(elements)); count++; bulleted = true; }
|
|
159
|
+
elements = [];
|
|
160
|
+
};
|
|
161
|
+
for (const child of item.children || []) {
|
|
162
|
+
if (child.type === 'paragraph' || child.type === 'heading') { if (elements.length) pushText(elements, '\n'); inline(child.children, {}, elements, depth + 1); continue; }
|
|
163
|
+
flush();
|
|
164
|
+
// Slack lists hold only sections: nested lists follow with deeper indent, other blocks follow the list.
|
|
165
|
+
if (child.type === 'list' && depth < NESTING_LIMIT) list(child, indent + 1, out, depth + 1); else blocks([child], depth + 1, out);
|
|
166
|
+
}
|
|
167
|
+
flush();
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
return { inline, blocks };
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function images(node) {
|
|
174
|
+
const found = [];
|
|
175
|
+
const stack = [node];
|
|
176
|
+
while (stack.length) {
|
|
177
|
+
const current = stack.pop();
|
|
178
|
+
if (current.type === 'image' || current.type === 'imageReference') found.push(current);
|
|
179
|
+
if (Array.isArray(current.children)) for (let i = current.children.length - 1; i >= 0; i--) stack.push(current.children[i]);
|
|
180
|
+
}
|
|
181
|
+
return found;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function parse(fromMarkdown, body) {
|
|
185
|
+
let root;
|
|
186
|
+
try { root = fromMarkdown(body); } catch { root = { type: 'root', children: [{ type: 'paragraph', children: [{ type: 'text', value: body }] }] }; }
|
|
187
|
+
const definitions = new Map();
|
|
188
|
+
const stack = [root];
|
|
189
|
+
while (stack.length) {
|
|
190
|
+
const node = stack.pop();
|
|
191
|
+
if (node.type === 'definition' && !definitions.has(node.identifier)) definitions.set(node.identifier, node);
|
|
192
|
+
if (Array.isArray(node.children)) stack.push(...node.children);
|
|
193
|
+
}
|
|
194
|
+
return { root, convert: createConverter(definitions) };
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Groups elements into rich_text blocks: a heading starts a block, as does exceeding the text budget. */
|
|
198
|
+
function toSlackBlocks(elements) {
|
|
199
|
+
const out = [];
|
|
200
|
+
let current, used = 0;
|
|
201
|
+
for (const element of elements) {
|
|
202
|
+
if (element.type === 'divider') { out.push({ type: 'divider' }); current = undefined; continue; }
|
|
203
|
+
const size = textLength(element);
|
|
204
|
+
if (!current || element.heading || used + size > BLOCK_TEXT_BUDGET) { current = { type: 'rich_text', elements: [] }; out.push(current); used = 0; }
|
|
205
|
+
const { heading, ...clean } = element;
|
|
206
|
+
current.elements.push(clean); used += size;
|
|
207
|
+
}
|
|
208
|
+
return out;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function titleBlock(title) {
|
|
212
|
+
return title.length <= HEADER_LIMIT ? { type: 'header', text: { type: 'plain_text', text: title, emoji: false } }
|
|
213
|
+
: { type: 'rich_text', elements: [{ type: 'rich_text_section', elements: [{ type: 'text', text: title, style: { bold: true } }] }] };
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Cuts inline elements at the best boundary within `limit`: paragraph, sentence, then word. Links are kept whole or dropped. */
|
|
217
|
+
function clipInline(elements, limit) {
|
|
218
|
+
const all = elements.map(inlineText).join('');
|
|
219
|
+
const window = all.slice(0, limit);
|
|
220
|
+
let cut = window.lastIndexOf('\n\n');
|
|
221
|
+
if (cut < limit * 0.4) cut = Math.max(...['. ', '! ', '? ', '.\n'].map(mark => window.lastIndexOf(mark))) + 1;
|
|
222
|
+
if (cut < limit * 0.4) cut = window.search(/\s\S*$/);
|
|
223
|
+
if (cut < limit * 0.4) cut = limit;
|
|
224
|
+
if (/[\uD800-\uDBFF]/.test(all[cut - 1] || '')) cut--;
|
|
225
|
+
const out = [];
|
|
226
|
+
let used = 0;
|
|
227
|
+
for (const element of elements) {
|
|
228
|
+
const text = inlineText(element);
|
|
229
|
+
if (used + text.length <= cut) { out.push(element); used += text.length; continue; }
|
|
230
|
+
if (element.type === 'text') { const part = text.slice(0, cut - used).trimEnd(); if (part) out.push({ ...element, text: part }); }
|
|
231
|
+
break;
|
|
232
|
+
}
|
|
233
|
+
while (out.length && out[out.length - 1].type === 'text' && !out[out.length - 1].text.trim()) out.pop();
|
|
234
|
+
pushText(out, '…');
|
|
235
|
+
return out;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** Keeps whole elements while they fit; shortens at most one, then stops. */
|
|
239
|
+
function excerpt(elements, limit) {
|
|
240
|
+
const out = [];
|
|
241
|
+
let used = 0, shortened = false;
|
|
242
|
+
for (const element of elements) {
|
|
243
|
+
if (element.type === 'divider') continue;
|
|
244
|
+
const size = textLength(element);
|
|
245
|
+
if (used + size <= limit) { out.push(element); used += size; continue; }
|
|
246
|
+
shortened = true;
|
|
247
|
+
const remaining = limit - used;
|
|
248
|
+
if (element.type === 'rich_text_list') {
|
|
249
|
+
const items = [];
|
|
250
|
+
let left = remaining;
|
|
251
|
+
for (const item of element.elements) {
|
|
252
|
+
const length = textLength(item);
|
|
253
|
+
if (length <= left) { items.push(item); left -= length; continue; }
|
|
254
|
+
if (left > 80 || !items.length) items.push({ ...item, elements: clipInline(item.elements, Math.max(left, 80)) });
|
|
255
|
+
break;
|
|
256
|
+
}
|
|
257
|
+
out.push({ ...element, elements: items });
|
|
258
|
+
} else if (remaining > 80 || !out.length) out.push({ ...element, elements: clipInline(element.elements, Math.max(remaining, 80)) });
|
|
259
|
+
break;
|
|
260
|
+
}
|
|
261
|
+
const shown = out.reduce((n, element) => n + textLength(element), 0);
|
|
262
|
+
return { elements: out, shortened, shown, total: elements.reduce((n, element) => n + textLength(element), 0) };
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
const key = node => plainText(node).replace(/\s+/g, ' ').trim().toLowerCase();
|
|
266
|
+
function sectionsOf(root) {
|
|
267
|
+
const sections = [{ heading: undefined, nodes: [] }];
|
|
268
|
+
for (const node of root.children) {
|
|
269
|
+
if (node.type === 'heading') sections.push({ heading: node, key: key(node), nodes: [] });
|
|
270
|
+
else sections[sections.length - 1].nodes.push(node);
|
|
271
|
+
}
|
|
272
|
+
return sections;
|
|
273
|
+
}
|
|
274
|
+
const hasText = nodes => nodes.some(node => plainText(node).trim());
|
|
275
|
+
// Generated sections a summary leaves out; Source is represented by the recording link.
|
|
276
|
+
const OMITTED = new Set(['user feedback', 'observations', 'suggestions', 'context and limitations', 'visual evidence']);
|
|
277
|
+
const SUMMARY_TOTAL_LIMIT = 2000;
|
|
278
|
+
const SUMMARY_SECTION_LIMIT = 8;
|
|
279
|
+
const inlineTextOutsideLinks = element => element.type === 'link' ? '' : Array.isArray(element.elements) ? element.elements.map(inlineTextOutsideLinks).join('') : element.text || '';
|
|
280
|
+
const linksIn = elements => elements.flatMap(element => element.type === 'link' ? [element] : Array.isArray(element.elements) ? linksIn(element.elements) : []);
|
|
281
|
+
|
|
282
|
+
function momentLabel(url) {
|
|
283
|
+
const seconds = Number(new URL(url).searchParams.get('t'));
|
|
284
|
+
return Number.isFinite(seconds) && seconds >= 0 && new URL(url).searchParams.has('t') ? `Recording at ${Math.floor(seconds / 60)}:${String(Math.floor(seconds % 60)).padStart(2, '0')}` : 'Recording moment';
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function compact(root, convert) {
|
|
288
|
+
const notices = [];
|
|
289
|
+
const sections = sectionsOf(root);
|
|
290
|
+
const elements = [];
|
|
291
|
+
const omitted = [];
|
|
292
|
+
let used = 0, included = 0;
|
|
293
|
+
const hasSummary = sections.some(section => section.key === 'summary' && hasText(section.nodes));
|
|
294
|
+
// Known summary content plus every custom section, in source order, each as a bounded excerpt.
|
|
295
|
+
for (const section of sections) {
|
|
296
|
+
if (!hasText(section.nodes)) continue;
|
|
297
|
+
const name = section.heading ? plainText(section.heading).replace(/\s+/g, ' ').trim() : 'Introduction';
|
|
298
|
+
// Above a Summary, skip only a links-only preamble such as the recording cover; its links still reach Evidence.
|
|
299
|
+
if (!section.heading && hasSummary && !convert.blocks(section.nodes).some(element => inlineTextOutsideLinks(element).trim())) continue;
|
|
300
|
+
if (section.key === 'source') continue;
|
|
301
|
+
if (OMITTED.has(section.key)) { omitted.push(name); continue; }
|
|
302
|
+
if (section.key === 'expected behavior') {
|
|
303
|
+
const text = plainText({ children: section.nodes }).trim();
|
|
304
|
+
if (/^Needs reporter input\b/i.test(text)) continue;
|
|
305
|
+
if (/^From source analysis\b/i.test(text)) { notices.push('Expected behavior suggested by source analysis is not included in the summary. Choose Full report to include it.'); continue; }
|
|
306
|
+
}
|
|
307
|
+
const budget = Math.min(EXCERPT_LIMIT, SUMMARY_TOTAL_LIMIT - used);
|
|
308
|
+
if (budget < 80 || included >= SUMMARY_SECTION_LIMIT) { omitted.push(name); continue; }
|
|
309
|
+
included++;
|
|
310
|
+
if (section.heading && section.key !== 'summary') elements.push(...convert.blocks([section.heading]));
|
|
311
|
+
const clipped = excerpt(convert.blocks(section.nodes), budget);
|
|
312
|
+
elements.push(...clipped.elements);
|
|
313
|
+
used += clipped.shown;
|
|
314
|
+
if (clipped.shortened) notices.push(`${section.key === 'summary' ? 'The summary' : `“${name}”`} is shortened to ${clipped.shown.toLocaleString('en-US')} of ${clipped.total.toLocaleString('en-US')} characters. Choose Full report to send all of it.`);
|
|
315
|
+
}
|
|
316
|
+
if (omitted.length) notices.push(`Not included in the summary: ${omitted.join(', ')}. Choose Full report to send ${omitted.length === 1 ? 'it' : 'them'}.`);
|
|
317
|
+
const seen = new Set(linksIn(elements).map(link => link.url));
|
|
318
|
+
const links = [];
|
|
319
|
+
const recording = linksIn(sections.filter(section => section.key === 'source').flatMap(section => convert.blocks(section.nodes)))[0];
|
|
320
|
+
if (recording && !seen.has(recording.url)) links.push({ type: 'rich_text_section', elements: [{ type: 'link', url: recording.url, text: recording.text }] });
|
|
321
|
+
if (recording) seen.add(recording.url);
|
|
322
|
+
// Screenshots and explicit links elsewhere in the report, in source order, each URL once.
|
|
323
|
+
const evidence = [];
|
|
324
|
+
let invalid = 0;
|
|
325
|
+
const firstLink = node => convert.inline([node]).find(element => element.type === 'link');
|
|
326
|
+
const stack = [{ node: root, parent: undefined }];
|
|
327
|
+
while (stack.length) {
|
|
328
|
+
const { node, parent } = stack.pop();
|
|
329
|
+
if (node.type === 'image' || node.type === 'imageReference') {
|
|
330
|
+
const imageUrl = firstLink(node)?.url;
|
|
331
|
+
const momentUrl = parent ? firstLink({ ...parent, children: [{ type: 'text', value: 'moment' }] })?.url : undefined;
|
|
332
|
+
const primary = imageUrl || momentUrl;
|
|
333
|
+
if (!primary) { invalid++; continue; }
|
|
334
|
+
if (seen.has(primary)) continue;
|
|
335
|
+
seen.add(primary);
|
|
336
|
+
const item = [{ type: 'link', url: primary, text: node.alt || 'Screenshot' }];
|
|
337
|
+
if (imageUrl && momentUrl && !seen.has(momentUrl)) item.push({ type: 'text', text: ' · ' }, { type: 'link', url: momentUrl, text: momentLabel(momentUrl) });
|
|
338
|
+
if (momentUrl) seen.add(momentUrl);
|
|
339
|
+
evidence.push({ type: 'rich_text_section', elements: item });
|
|
340
|
+
continue;
|
|
341
|
+
}
|
|
342
|
+
if ((node.type === 'link' || node.type === 'linkReference') && !images(node).length) {
|
|
343
|
+
const link = firstLink(node);
|
|
344
|
+
if (link && !seen.has(link.url)) { seen.add(link.url); evidence.push({ type: 'rich_text_section', elements: [{ type: 'link', url: link.url, text: link.text }] }); }
|
|
345
|
+
continue;
|
|
346
|
+
}
|
|
347
|
+
if (Array.isArray(node.children)) {
|
|
348
|
+
const nextParent = node.type === 'link' || node.type === 'linkReference' ? node : parent;
|
|
349
|
+
for (let i = node.children.length - 1; i >= 0; i--) stack.push({ node: node.children[i], parent: nextParent });
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
if (evidence.length > EVIDENCE_LIMIT) notices.push(`${evidence.length - EVIDENCE_LIMIT} more link(s) are only in the full report.`);
|
|
353
|
+
if (invalid) notices.push(`${invalid} screenshot(s) without a valid HTTPS link are not included.`);
|
|
354
|
+
if (links.length || evidence.length) {
|
|
355
|
+
elements.push({ type: 'rich_text_section', heading: true, elements: [{ type: 'text', text: 'Evidence', style: { bold: true } }] }, ...links);
|
|
356
|
+
if (evidence.length) elements.push({ type: 'rich_text_list', style: 'bullet', indent: 0, elements: evidence.slice(0, EVIDENCE_LIMIT) });
|
|
357
|
+
}
|
|
358
|
+
elements.push({ type: 'rich_text_section', elements: [{ type: 'text', text: CONTEXT_NOTE + (recording ? RECORDING_NOTE : ''), style: { italic: true } }] });
|
|
359
|
+
return { elements, notices };
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/** @param {(markdown: string) => unknown} fromMarkdown CommonMark parser from `mdast-util-from-markdown` */
|
|
363
|
+
export function createSlackReportProjector(fromMarkdown) {
|
|
364
|
+
return (title, body, mode) => projectSlackReport(fromMarkdown, title, body, mode);
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
function projectSlackReport(fromMarkdown, title, body, mode) {
|
|
368
|
+
if (!SLACK_REPORT_MODES.includes(mode)) throw new SlackReportError('INVALID_MODE', 'Choose a Slack message format.');
|
|
369
|
+
if (typeof title !== 'string' || typeof body !== 'string' || !title.trim() || title.length > SLACK_REPORT_TITLE_LIMIT || body.length > SLACK_REPORT_BODY_LIMIT) {
|
|
370
|
+
throw new SlackReportError('REPORT_TOO_LARGE', 'Slack reports support a title up to 256 characters and a body up to 12,000 characters.');
|
|
371
|
+
}
|
|
372
|
+
const { root, convert } = parse(fromMarkdown, body);
|
|
373
|
+
const projected = mode === 'full' ? { elements: convert.blocks(root.children), notices: [] } : compact(root, convert);
|
|
374
|
+
const blocks = [titleBlock(title), ...toSlackBlocks(projected.elements)];
|
|
375
|
+
if (blocks.length > BLOCK_LIMIT) throw new SlackReportError('REPORT_TOO_LARGE', `This report needs ${blocks.length} Slack blocks; one message supports ${BLOCK_LIMIT}. Use the summary message or shorten the report.`);
|
|
376
|
+
const escape = value => value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
377
|
+
return {
|
|
378
|
+
message: { text: escape(title), blocks, mrkdwn: false, parse: 'none', link_names: false, unfurl_links: false, unfurl_media: false },
|
|
379
|
+
notices: projected.notices,
|
|
380
|
+
};
|
|
381
|
+
}
|
|
@@ -9,6 +9,7 @@ export declare class CloudAdapter implements BrowserAdapter {
|
|
|
9
9
|
private defaultTimeout;
|
|
10
10
|
constructor(apiKey?: string, baseUrl?: string);
|
|
11
11
|
private request;
|
|
12
|
+
private isTransientReadFailure;
|
|
12
13
|
private sleep;
|
|
13
14
|
private getActiveSessionId;
|
|
14
15
|
/**
|
|
@@ -36,6 +37,7 @@ export declare class CloudAdapter implements BrowserAdapter {
|
|
|
36
37
|
waitForSessionReady(sessionId: string, timeout?: number): Promise<Session>;
|
|
37
38
|
stopSession(sessionId?: string): Promise<void>;
|
|
38
39
|
getSession(sessionId: string): Promise<Session>;
|
|
40
|
+
private readSession;
|
|
39
41
|
listSessions(): Promise<Session[]>;
|
|
40
42
|
listArtifacts(sessionId: string): Promise<any>;
|
|
41
43
|
navigate(url: string, options?: NavigateOptions): Promise<ActionResult>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cloud.d.ts","sourceRoot":"","sources":["../../../src/adapters/cloud.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AACjD,OAAO,KAAK,EACV,OAAO,EACP,cAAc,EACd,YAAY,EACZ,eAAe,EACf,YAAY,EACZ,cAAc,EACd,WAAW,EACX,iBAAiB,EACjB,cAAc,EACd,WAAW,EACX,YAAY,EACZ,aAAa,EACb,aAAa,EACd,MAAM,aAAa,CAAC;AAyBrB,qBAAa,YAAa,YAAW,cAAc;IACjD,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,cAAc,CAAS;gBAEnB,MAAM,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM;YAuB/B,OAAO;
|
|
1
|
+
{"version":3,"file":"cloud.d.ts","sourceRoot":"","sources":["../../../src/adapters/cloud.ts"],"names":[],"mappings":"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"}
|
|
@@ -34,15 +34,45 @@ export class CloudAdapter {
|
|
|
34
34
|
}
|
|
35
35
|
async request(path, options = {}, retries = 3) {
|
|
36
36
|
const url = `${this.baseUrl}${path}`;
|
|
37
|
+
const method = (options.method || 'GET').toUpperCase();
|
|
38
|
+
const canRetry = method === 'GET' || method === 'HEAD';
|
|
37
39
|
const headers = {
|
|
38
40
|
'Content-Type': 'application/json',
|
|
39
41
|
'x-api-key': this.apiKey,
|
|
40
42
|
...options.headers,
|
|
41
43
|
};
|
|
42
|
-
const
|
|
44
|
+
const bodyTimeout = (() => {
|
|
45
|
+
if (!options.body)
|
|
46
|
+
return undefined;
|
|
47
|
+
try {
|
|
48
|
+
const body = JSON.parse(options.body);
|
|
49
|
+
if (!body || typeof body !== 'object' || Array.isArray(body))
|
|
50
|
+
return undefined;
|
|
51
|
+
const timeout = body.timeout;
|
|
52
|
+
return typeof timeout === 'number' && Number.isFinite(timeout) && timeout > 0
|
|
53
|
+
? timeout
|
|
54
|
+
: undefined;
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
return undefined;
|
|
58
|
+
}
|
|
59
|
+
})();
|
|
60
|
+
// Match MCP's caller budget: callers may specify a browser-action timeout
|
|
61
|
+
// in the JSON body, while an explicit transport timeout (for example the
|
|
62
|
+
// typing and fingerprint budgets) remains authoritative.
|
|
63
|
+
const selectedFetchTimeout = options.timeoutMs ?? (bodyTimeout === undefined
|
|
64
|
+
? this.defaultTimeout
|
|
65
|
+
: Math.min(615_000, Math.max(this.defaultTimeout, bodyTimeout + 15_000)));
|
|
66
|
+
// Node's AbortSignal.timeout requires an integer, whereas Bun accepts a
|
|
67
|
+
// fractional duration. Round valid budgets up so both runtimes can carry
|
|
68
|
+
// the same finite-positive caller timeout without losing milliseconds.
|
|
69
|
+
// Invalid explicit values pass through and retain AbortSignal's errors.
|
|
70
|
+
const fetchTimeout = Number.isFinite(selectedFetchTimeout) && selectedFetchTimeout >= 0
|
|
71
|
+
? Math.ceil(selectedFetchTimeout)
|
|
72
|
+
: selectedFetchTimeout;
|
|
43
73
|
try {
|
|
44
74
|
const response = await fetch(url, {
|
|
45
|
-
method
|
|
75
|
+
method,
|
|
46
76
|
headers,
|
|
47
77
|
body: options.body,
|
|
48
78
|
signal: AbortSignal.timeout(fetchTimeout),
|
|
@@ -90,7 +120,14 @@ export class CloudAdapter {
|
|
|
90
120
|
}
|
|
91
121
|
const hint = typeof data.hint === 'string' ? data.hint : undefined;
|
|
92
122
|
const errMessage = errStr || msgStr || 'API request failed';
|
|
93
|
-
|
|
123
|
+
const storageErrorIdentity = codeStr === 'STORAGE_UNAVAILABLE'
|
|
124
|
+
|| errStr === 'STORAGE_UNAVAILABLE';
|
|
125
|
+
const knownPreDispatchStorageError = !canRetry
|
|
126
|
+
&& response.status === 503
|
|
127
|
+
&& storageErrorIdentity
|
|
128
|
+
&& data.retryable === true
|
|
129
|
+
&& data.outcomeUnknown !== true;
|
|
130
|
+
throw new ApiError(errMessage, response.status, hint, knownPreDispatchStorageError ? 'STORAGE_UNAVAILABLE' : codeStr || undefined, knownPreDispatchStorageError ? true : undefined);
|
|
94
131
|
}
|
|
95
132
|
if (!text) {
|
|
96
133
|
return {};
|
|
@@ -103,18 +140,47 @@ export class CloudAdapter {
|
|
|
103
140
|
}
|
|
104
141
|
}
|
|
105
142
|
catch (error) {
|
|
106
|
-
//
|
|
107
|
-
|
|
143
|
+
// Only replay safe reads. A timed out or failed mutation may already have
|
|
144
|
+
// reached the browser, so replaying it could duplicate an action.
|
|
145
|
+
const status = error instanceof ApiError ? error.statusCode : error.status;
|
|
146
|
+
const ambiguousServerError = status === 408
|
|
147
|
+
|| (status !== undefined && status >= 500 && status <= 599);
|
|
148
|
+
const code = error?.code || error?.cause?.code;
|
|
149
|
+
const transientNetwork = code === 'ECONNRESET' || code === 'ETIMEDOUT'
|
|
150
|
+
|| error?.name === 'TimeoutError' || error?.name === 'AbortError';
|
|
151
|
+
if (canRetry && retries > 0 && this.isTransientReadFailure(error)) {
|
|
108
152
|
await this.sleep(Math.pow(2, 3 - retries) * 1000);
|
|
109
153
|
return this.request(path, options, retries - 1);
|
|
110
154
|
}
|
|
111
155
|
// Re-throw our custom errors
|
|
112
156
|
if (error instanceof ApiError || error instanceof SessionError) {
|
|
157
|
+
if (error instanceof ApiError && !canRetry && (transientNetwork || ambiguousServerError)) {
|
|
158
|
+
// The routing middleware's exact 503 STORAGE_UNAVAILABLE response
|
|
159
|
+
// guarantees pre-dispatch failure. Preserve that one structured
|
|
160
|
+
// retry signal; a generic retryable flag on a 5xx is not sufficient.
|
|
161
|
+
if (error.nativeCode === 'STORAGE_UNAVAILABLE' && error.retryable === true)
|
|
162
|
+
throw error;
|
|
163
|
+
throw new ApiError(error.message, error.statusCode, 'Check the browser/session state before retrying this command; its outcome may be unknown.', error.nativeCode, false);
|
|
164
|
+
}
|
|
113
165
|
throw error;
|
|
114
166
|
}
|
|
115
|
-
//
|
|
116
|
-
throw new ApiError(error.message || 'Network request failed', undefined,
|
|
117
|
-
|
|
167
|
+
// Network failures and timeouts leave mutation outcomes unknown.
|
|
168
|
+
throw new ApiError(error.message || 'Network request failed', undefined, canRetry
|
|
169
|
+
? 'Check your internet connection'
|
|
170
|
+
: 'Check the browser/session state before retrying this command; its outcome may be unknown.', canRetry && (error?.name === 'TimeoutError' || error?.name === 'AbortError')
|
|
171
|
+
? error.name
|
|
172
|
+
: code, canRetry ? undefined : false);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
isTransientReadFailure(error) {
|
|
176
|
+
const candidate = error;
|
|
177
|
+
if (!candidate)
|
|
178
|
+
return false;
|
|
179
|
+
const status = candidate instanceof ApiError ? candidate.statusCode : candidate.status ?? candidate.statusCode;
|
|
180
|
+
const transientCodes = [candidate.nativeCode, candidate.code, candidate.cause?.code];
|
|
181
|
+
return status === 502 || status === 503
|
|
182
|
+
|| transientCodes.some((code) => code === 'ECONNRESET' || code === 'ETIMEDOUT' || code === 'TimeoutError' || code === 'AbortError')
|
|
183
|
+
|| candidate.name === 'TimeoutError' || candidate.name === 'AbortError';
|
|
118
184
|
}
|
|
119
185
|
sleep(ms) {
|
|
120
186
|
return new Promise(resolve => setTimeout(resolve, ms));
|
|
@@ -238,6 +304,12 @@ export class CloudAdapter {
|
|
|
238
304
|
status: status,
|
|
239
305
|
createdAt: new Date().toISOString(),
|
|
240
306
|
};
|
|
307
|
+
const browserReady = typeof response.browserReady === 'boolean'
|
|
308
|
+
? response.browserReady
|
|
309
|
+
: response.data?.browserReady;
|
|
310
|
+
if (typeof browserReady === 'boolean') {
|
|
311
|
+
session.browserReady = browserReady;
|
|
312
|
+
}
|
|
241
313
|
if (!setCloudSessionContext(session.sessionId)) {
|
|
242
314
|
try {
|
|
243
315
|
await this.request(`/api/sessions/${session.sessionId}`, { method: 'DELETE' });
|
|
@@ -251,17 +323,37 @@ export class CloudAdapter {
|
|
|
251
323
|
}
|
|
252
324
|
async waitForSessionReady(sessionId, timeout = 90000) {
|
|
253
325
|
const pollInterval = 2000;
|
|
254
|
-
const
|
|
255
|
-
const
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
326
|
+
const deadline = performance.now() + timeout;
|
|
327
|
+
const readyStatuses = ['active', 'ready', 'running'];
|
|
328
|
+
const terminalStatuses = ['error', 'failed', 'terminated', 'closed', 'completed', 'cancelled'];
|
|
329
|
+
while (performance.now() < deadline) {
|
|
330
|
+
const remainingMs = deadline - performance.now();
|
|
331
|
+
let session;
|
|
332
|
+
try {
|
|
333
|
+
session = await this.readSession(sessionId, remainingMs, 0);
|
|
334
|
+
}
|
|
335
|
+
catch (error) {
|
|
336
|
+
if (performance.now() >= deadline)
|
|
337
|
+
break;
|
|
338
|
+
if (this.isTransientReadFailure(error)) {
|
|
339
|
+
const sleepMs = Math.min(pollInterval, Math.max(0, deadline - performance.now()));
|
|
340
|
+
if (sleepMs > 0)
|
|
341
|
+
await this.sleep(sleepMs);
|
|
342
|
+
continue;
|
|
261
343
|
}
|
|
344
|
+
throw error;
|
|
345
|
+
}
|
|
346
|
+
if (performance.now() >= deadline)
|
|
347
|
+
break;
|
|
348
|
+
if (terminalStatuses.includes(session.status)) {
|
|
349
|
+
throw new SessionError(`Session entered ${session.status} state during provisioning`, 'Try creating a new session with: thinkrun cloud start');
|
|
350
|
+
}
|
|
351
|
+
if (readyStatuses.includes(session.status) && session.browserReady === true) {
|
|
262
352
|
return session;
|
|
263
353
|
}
|
|
264
|
-
|
|
354
|
+
const sleepMs = Math.min(pollInterval, Math.max(0, deadline - performance.now()));
|
|
355
|
+
if (sleepMs > 0)
|
|
356
|
+
await this.sleep(sleepMs);
|
|
265
357
|
}
|
|
266
358
|
throw new SessionError('Session provisioning timed out', 'The session may still be starting. Check with: thinkrun cloud status');
|
|
267
359
|
}
|
|
@@ -275,7 +367,10 @@ export class CloudAdapter {
|
|
|
275
367
|
}
|
|
276
368
|
}
|
|
277
369
|
async getSession(sessionId) {
|
|
278
|
-
|
|
370
|
+
return this.readSession(sessionId);
|
|
371
|
+
}
|
|
372
|
+
async readSession(sessionId, timeoutMs, retries = 3) {
|
|
373
|
+
const response = await this.request(`/api/sessions/${sessionId}`, timeoutMs === undefined ? {} : { timeoutMs }, retries);
|
|
279
374
|
if (response?.data)
|
|
280
375
|
return response.data;
|
|
281
376
|
return response;
|