@mjasnikovs/pi-nop 0.0.0-stage → 0.1.2
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/LICENSE +21 -0
- package/README.md +116 -2
- package/package.json +87 -5
- package/src/config/box.ts +29 -0
- package/src/config/command.ts +138 -0
- package/src/config/config.ts +238 -0
- package/src/config/sections.ts +58 -0
- package/src/index.ts +17 -0
- package/src/plan/ask.ts +226 -0
- package/src/plan/goal.ts +43 -0
- package/src/plan/panel.ts +567 -0
- package/src/plan/plan.ts +581 -0
- package/src/plan/steps.ts +192 -0
- package/src/plan/track.ts +131 -0
- package/src/search/brave.ts +56 -0
- package/src/search/ddg.ts +67 -0
- package/src/search/engines.ts +63 -0
- package/src/search/exa.ts +74 -0
- package/src/search/search.ts +58 -0
- package/src/subagent/answer.ts +151 -0
- package/src/subagent/budget.ts +19 -0
- package/src/subagent/describe.ts +8 -0
- package/src/subagent/docs/docs.ts +123 -0
- package/src/subagent/docs/files.ts +90 -0
- package/src/subagent/docs/header.ts +60 -0
- package/src/subagent/docs/locate.ts +262 -0
- package/src/subagent/docs/manifest.ts +43 -0
- package/src/subagent/docs/npm.ts +287 -0
- package/src/subagent/fetch/digest.ts +379 -0
- package/src/subagent/fetch/errors.ts +10 -0
- package/src/subagent/fetch/fetch.ts +176 -0
- package/src/subagent/fetch/pdf.ts +120 -0
- package/src/subagent/guards/churn.ts +37 -0
- package/src/subagent/guards/circle.ts +49 -0
- package/src/subagent/guards/ground.ts +75 -0
- package/src/subagent/guards/guard.ts +24 -0
- package/src/subagent/guards/guards.ts +107 -0
- package/src/subagent/guards/key.ts +13 -0
- package/src/subagent/guards/leak.ts +42 -0
- package/src/subagent/guards/lines.ts +24 -0
- package/src/subagent/guards/loop.ts +77 -0
- package/src/subagent/guards/repeat.ts +70 -0
- package/src/subagent/guards/stale.ts +38 -0
- package/src/subagent/guards/toolCall.ts +46 -0
- package/src/subagent/guards/visited.ts +89 -0
- package/src/subagent/platform.ts +81 -0
- package/src/subagent/progress.ts +34 -0
- package/src/subagent/slots.ts +42 -0
- package/src/subagent/subagent.ts +537 -0
- package/src/subagent/subagentTui.ts +292 -0
- package/src/tui/hidden.ts +16 -0
- package/src/tui/spinner.ts +64 -0
- package/src/types/turndown-plugin-gfm.d.ts +5 -0
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
import {formatSize} from '@earendil-works/pi-coding-agent'
|
|
2
|
+
import {isProbablyReaderable, Readability} from '@mozilla/readability'
|
|
3
|
+
import {parseHTML} from 'linkedom'
|
|
4
|
+
import TurndownService from 'turndown'
|
|
5
|
+
import {tables} from 'turndown-plugin-gfm'
|
|
6
|
+
|
|
7
|
+
import type {Source} from '../answer'
|
|
8
|
+
import {FetchErrors} from './errors'
|
|
9
|
+
import {pdfText, quotable} from './pdf'
|
|
10
|
+
|
|
11
|
+
enum ContentKind {
|
|
12
|
+
Html,
|
|
13
|
+
Text,
|
|
14
|
+
Sniff,
|
|
15
|
+
Pdf,
|
|
16
|
+
Unsupported
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** The fields read off a turndown node. Its DOM types are not in this tsconfig lib. */
|
|
20
|
+
type RuleNode = {
|
|
21
|
+
nodeName: string
|
|
22
|
+
textContent: string | null
|
|
23
|
+
firstChild: {nodeName: string} | null
|
|
24
|
+
getAttribute(name: string): string | null
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const fields = new Set(['INPUT', 'SELECT', 'TEXTAREA'])
|
|
28
|
+
const isField = (node: RuleNode): boolean => fields.has(node.nodeName)
|
|
29
|
+
const field = (node: RuleNode): string =>
|
|
30
|
+
`[${node.nodeName.toLowerCase()} name="${node.getAttribute('name') ?? ''}"]`
|
|
31
|
+
|
|
32
|
+
const formLine = (node: RuleNode): string => {
|
|
33
|
+
const method = (node.getAttribute('method') ?? 'get').toLowerCase()
|
|
34
|
+
return `Form (method=${method}, action=${node.getAttribute('action') ?? ''})`
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const blank = (node: RuleNode): string => {
|
|
38
|
+
if (isField(node)) return field(node)
|
|
39
|
+
return node.nodeName === 'FORM' ? `\n\n${formLine(node)}\n\n` : ''
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const turndown = new TurndownService({
|
|
43
|
+
codeBlockStyle: 'fenced',
|
|
44
|
+
headingStyle: 'atx',
|
|
45
|
+
bulletListMarker: '-',
|
|
46
|
+
// Turndown drops empty elements before rules run, and fields are usually empty.
|
|
47
|
+
blankReplacement: (_content, node: RuleNode) => blank(node)
|
|
48
|
+
}).use(tables)
|
|
49
|
+
turndown.remove(['script', 'style', 'noscript', 'template'])
|
|
50
|
+
// Turndown only fences <pre><code>; a bare <pre> would be escaped as prose.
|
|
51
|
+
turndown.addRule('barePre', {
|
|
52
|
+
filter: (node: RuleNode) => node.nodeName === 'PRE' && node.firstChild?.nodeName !== 'CODE',
|
|
53
|
+
replacement: (_content, node: RuleNode) => `\n\n\`\`\`\n${node.textContent ?? ''}\n\`\`\`\n\n`
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
turndown.addRule('form', {
|
|
57
|
+
filter: 'form',
|
|
58
|
+
replacement: (content, node: RuleNode) => `\n\n${formLine(node)}\n\n${content}\n\n`
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
turndown.addRule('field', {
|
|
62
|
+
filter: (node: RuleNode) => isField(node),
|
|
63
|
+
replacement: (_content, node: RuleNode) => field(node)
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
const textMimes = new Set([
|
|
67
|
+
'application/json',
|
|
68
|
+
'application/xml',
|
|
69
|
+
'application/javascript',
|
|
70
|
+
'application/x-javascript',
|
|
71
|
+
'application/ecmascript',
|
|
72
|
+
'application/yaml',
|
|
73
|
+
'application/x-yaml',
|
|
74
|
+
'application/toml',
|
|
75
|
+
'application/x-sh',
|
|
76
|
+
'application/x-ndjson',
|
|
77
|
+
'application/sql'
|
|
78
|
+
])
|
|
79
|
+
|
|
80
|
+
// The names freedesktop shared-mime-info lists for PDF.
|
|
81
|
+
const pdfMimes = new Set([
|
|
82
|
+
'application/pdf',
|
|
83
|
+
'application/x-pdf',
|
|
84
|
+
'application/acrobat',
|
|
85
|
+
'application/nappdf',
|
|
86
|
+
'image/pdf'
|
|
87
|
+
])
|
|
88
|
+
|
|
89
|
+
const mimeOf = (contentType: string): string => contentType.split(';')[0].trim().toLowerCase()
|
|
90
|
+
|
|
91
|
+
const classify = (contentType: string): ContentKind => {
|
|
92
|
+
const mime = mimeOf(contentType)
|
|
93
|
+
|
|
94
|
+
if (mime === 'text/html' || mime === 'application/xhtml+xml') return ContentKind.Html
|
|
95
|
+
if (mime === '' || mime.startsWith('text/')) return ContentKind.Text
|
|
96
|
+
if (mime.endsWith('+json') || mime.endsWith('+xml')) return ContentKind.Text
|
|
97
|
+
if (textMimes.has(mime)) return ContentKind.Text
|
|
98
|
+
if (pdfMimes.has(mime)) return ContentKind.Pdf
|
|
99
|
+
if (mime === 'application/octet-stream') return ContentKind.Sniff
|
|
100
|
+
return ContentKind.Unsupported
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
type Charset = ConstructorParameters<typeof TextDecoder>[0]
|
|
104
|
+
|
|
105
|
+
const headerCharset = /charset=["']?([^;"'\s>]+)/i
|
|
106
|
+
const metaCharset = /<meta[^>]+charset=["']?([^;"'\s>]+)/i
|
|
107
|
+
|
|
108
|
+
const charsetIn = (pattern: RegExp, source: string): Charset | undefined =>
|
|
109
|
+
pattern.exec(source)?.[1] as Charset | undefined
|
|
110
|
+
|
|
111
|
+
const utf8 = (bytes: Uint8Array): string | undefined => {
|
|
112
|
+
try {
|
|
113
|
+
return new TextDecoder('utf-8', {fatal: true}).decode(bytes)
|
|
114
|
+
} catch {
|
|
115
|
+
return undefined
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// Undeclared non-UTF-8 text is nearly always Latin-1, which windows-1252 covers.
|
|
120
|
+
const decodeUndeclared = (bytes: Uint8Array): string =>
|
|
121
|
+
utf8(bytes) ?? new TextDecoder('windows-1252').decode(bytes)
|
|
122
|
+
|
|
123
|
+
const decode = (bytes: Uint8Array, charset: Charset | undefined): string => {
|
|
124
|
+
if (charset === undefined) return decodeUndeclared(bytes)
|
|
125
|
+
|
|
126
|
+
try {
|
|
127
|
+
return new TextDecoder(charset).decode(bytes)
|
|
128
|
+
} catch {
|
|
129
|
+
return decodeUndeclared(bytes)
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const decodeBody = (bytes: Uint8Array, contentType: string, kind: ContentKind): string => {
|
|
134
|
+
const charset = charsetIn(headerCharset, contentType)
|
|
135
|
+
const body = decode(bytes, charset)
|
|
136
|
+
|
|
137
|
+
if (charset !== undefined || kind !== ContentKind.Html) return body
|
|
138
|
+
|
|
139
|
+
const declared = charsetIn(metaCharset, body)
|
|
140
|
+
return declared === undefined ? body : decode(bytes, declared)
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const looksLikeText = (bytes: Uint8Array): boolean =>
|
|
144
|
+
!bytes.includes(0) && utf8(bytes) !== undefined
|
|
145
|
+
|
|
146
|
+
// PDF readers look for the header in the first 1024 bytes and for %%EOF in the last 1024.
|
|
147
|
+
const pdfMarkWindow = 1024
|
|
148
|
+
const hasPdfHeader = (bytes: Uint8Array): boolean =>
|
|
149
|
+
Buffer.from(bytes.subarray(0, pdfMarkWindow)).includes('%PDF-')
|
|
150
|
+
const hasPdfMarks = (bytes: Uint8Array): boolean =>
|
|
151
|
+
hasPdfHeader(bytes) && Buffer.from(bytes.subarray(-pdfMarkWindow)).includes('%%EOF')
|
|
152
|
+
|
|
153
|
+
const sniffsAsPdf = (kind: ContentKind, contentType: string, bytes: Uint8Array): boolean => {
|
|
154
|
+
const undeclared = kind === ContentKind.Sniff || mimeOf(contentType) === ''
|
|
155
|
+
return undeclared && hasPdfMarks(bytes)
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** The fields read off the parsed document. Its DOM types are not in this tsconfig lib. */
|
|
159
|
+
type ParsedChild = {
|
|
160
|
+
nodeName: string
|
|
161
|
+
nodeType: number
|
|
162
|
+
nodeValue: string | null
|
|
163
|
+
childNodes: ParsedChild[]
|
|
164
|
+
firstChild: ParsedChild | null
|
|
165
|
+
}
|
|
166
|
+
type ParsedElement = ParsedChild & {
|
|
167
|
+
textContent: string
|
|
168
|
+
remove(): void
|
|
169
|
+
getAttribute(name: string): string | null
|
|
170
|
+
replaceChildren(...nodes: ParsedChild[]): void
|
|
171
|
+
}
|
|
172
|
+
type ParsedNode = {querySelectorAll(selector: string): ParsedElement[]}
|
|
173
|
+
type ParsedDocument = ParsedNode & {
|
|
174
|
+
title: string
|
|
175
|
+
body: ParsedElement & ParsedNode & {innerHTML: string}
|
|
176
|
+
createTextNode(text: string): ParsedChild
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const textNode = 3
|
|
180
|
+
// Tags whose default display is not inline, per the HTML standard. innerText breaks the
|
|
181
|
+
// line around these, and textContent does not.
|
|
182
|
+
const lineTags = new Set([
|
|
183
|
+
'ADDRESS',
|
|
184
|
+
'ARTICLE',
|
|
185
|
+
'ASIDE',
|
|
186
|
+
'BLOCKQUOTE',
|
|
187
|
+
'CAPTION',
|
|
188
|
+
'DD',
|
|
189
|
+
'DETAILS',
|
|
190
|
+
'DIV',
|
|
191
|
+
'DL',
|
|
192
|
+
'DT',
|
|
193
|
+
'FIELDSET',
|
|
194
|
+
'FIGCAPTION',
|
|
195
|
+
'FIGURE',
|
|
196
|
+
'FOOTER',
|
|
197
|
+
'FORM',
|
|
198
|
+
'H1',
|
|
199
|
+
'H2',
|
|
200
|
+
'H3',
|
|
201
|
+
'H4',
|
|
202
|
+
'H5',
|
|
203
|
+
'H6',
|
|
204
|
+
'HEADER',
|
|
205
|
+
'HR',
|
|
206
|
+
'LI',
|
|
207
|
+
'MAIN',
|
|
208
|
+
'NAV',
|
|
209
|
+
'OL',
|
|
210
|
+
'P',
|
|
211
|
+
'PRE',
|
|
212
|
+
'SECTION',
|
|
213
|
+
'SUMMARY',
|
|
214
|
+
'TABLE',
|
|
215
|
+
'TBODY',
|
|
216
|
+
'TFOOT',
|
|
217
|
+
'THEAD',
|
|
218
|
+
'TR',
|
|
219
|
+
'UL'
|
|
220
|
+
])
|
|
221
|
+
|
|
222
|
+
const endLine = (text: string): string => (text === '' || text.endsWith('\n') ? text : text + '\n')
|
|
223
|
+
|
|
224
|
+
// A structural break is folded into a newline the text already carries.
|
|
225
|
+
const codeText = (node: ParsedChild): string => {
|
|
226
|
+
let text = ''
|
|
227
|
+
let broke = false
|
|
228
|
+
|
|
229
|
+
for (const child of node.childNodes) {
|
|
230
|
+
if (child.nodeType === textNode) {
|
|
231
|
+
const value = child.nodeValue ?? ''
|
|
232
|
+
text += broke && value.startsWith('\n') ? value.slice(1) : value
|
|
233
|
+
broke = false
|
|
234
|
+
} else if (child.nodeName === 'BR') {
|
|
235
|
+
text += '\n'
|
|
236
|
+
broke = false
|
|
237
|
+
} else if (lineTags.has(child.nodeName)) {
|
|
238
|
+
text = endLine(endLine(text) + codeText(child))
|
|
239
|
+
broke = true
|
|
240
|
+
} else {
|
|
241
|
+
text += codeText(child)
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
return text
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// Highlighters mark code lines with tags, and turndown reads the block's textContent.
|
|
249
|
+
// The <code> child stays, so turndown still sees its language class.
|
|
250
|
+
const flattenCode = (document: ParsedDocument): void => {
|
|
251
|
+
for (const block of document.body.querySelectorAll('pre, pre > code'))
|
|
252
|
+
if (block.nodeName === 'CODE' || block.firstChild?.nodeName !== 'CODE')
|
|
253
|
+
block.replaceChildren(document.createTextNode(codeText(block).replace(/\n$/, '')))
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
const parse = (html: string): ParsedDocument => {
|
|
257
|
+
const {document} = parseHTML(html)
|
|
258
|
+
return document as unknown as ParsedDocument
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
const structureTags = /<\/?(html|head|body)[^>]*>/gi
|
|
262
|
+
const wrap = (html: string): string => `<html><body>${html}</body></html>`
|
|
263
|
+
|
|
264
|
+
// linkedom leaves `body` empty unless <html>, <head> and <body> appear in textbook order,
|
|
265
|
+
// so anything else is flattened and wrapped again.
|
|
266
|
+
const parseLenient = (html: string): ParsedDocument => {
|
|
267
|
+
const framed = /<html[\s>]/i.test(html) && /<body[\s>]/i.test(html)
|
|
268
|
+
const document = parse(framed ? html : wrap(html))
|
|
269
|
+
|
|
270
|
+
if (document.body.textContent.trim() !== '') return document
|
|
271
|
+
return parse(wrap(html.replace(structureTags, '')))
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// A <title> outside <head> lands in the body, where it would read as prose.
|
|
275
|
+
const takeTitle = (document: ParsedDocument): string => {
|
|
276
|
+
const stray = document.body.querySelectorAll('title')
|
|
277
|
+
const title = document.title || (stray[0]?.textContent ?? '')
|
|
278
|
+
|
|
279
|
+
for (const node of stray) node.remove()
|
|
280
|
+
return title.trim()
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
const refreshUrl = /url\s*=\s*["']?([^"']+)/i
|
|
284
|
+
|
|
285
|
+
const refreshTarget = (document: ParsedDocument): string | undefined => {
|
|
286
|
+
const meta = document
|
|
287
|
+
.querySelectorAll('meta')
|
|
288
|
+
.find(node => node.getAttribute('http-equiv')?.toLowerCase() === 'refresh')
|
|
289
|
+
return refreshUrl.exec(meta?.getAttribute('content') ?? '')?.[1].trim()
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
const mainContent = (document: ParsedDocument): string => {
|
|
293
|
+
if (!isProbablyReaderable(document as never)) return document.body.innerHTML
|
|
294
|
+
return new Readability(document as never).parse()?.content ?? document.body.innerHTML
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
type Digest = {
|
|
298
|
+
text: string
|
|
299
|
+
/** Where a meta refresh sends the reader, as written in the page. */
|
|
300
|
+
refresh?: string
|
|
301
|
+
/** More ways a quote may match the text, such as a PDF word split at a line end. */
|
|
302
|
+
sources?: Source[]
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
const htmlToMarkdown = (html: string): Digest => {
|
|
306
|
+
const document = parseLenient(html)
|
|
307
|
+
flattenCode(document)
|
|
308
|
+
const refresh = refreshTarget(document)
|
|
309
|
+
const title = takeTitle(document)
|
|
310
|
+
const markdown = turndown.turndown(mainContent(document)).trim()
|
|
311
|
+
const text = [title === '' ? '' : `Title: ${title}`, markdown]
|
|
312
|
+
.filter(part => part !== '')
|
|
313
|
+
.join('\n\n')
|
|
314
|
+
|
|
315
|
+
return refresh === undefined ? {text} : {text, refresh}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
// MAGIC NUMBER: download cap. Claude Code WebFetch and mcp-fetch both stop at 10 MB.
|
|
319
|
+
// It fits large docs pages and most PDFs, and bounds memory before the token check runs.
|
|
320
|
+
const maxBytes = 10 * 1024 * 1024
|
|
321
|
+
|
|
322
|
+
const readBody = async (response: Response): Promise<Uint8Array> => {
|
|
323
|
+
const chunks: Uint8Array[] = []
|
|
324
|
+
let size = 0
|
|
325
|
+
|
|
326
|
+
if (response.body === null) return Buffer.concat(chunks)
|
|
327
|
+
|
|
328
|
+
const stream: AsyncIterable<Uint8Array> = response.body
|
|
329
|
+
|
|
330
|
+
for await (const chunk of stream) {
|
|
331
|
+
size += chunk.byteLength
|
|
332
|
+
|
|
333
|
+
if (size > maxBytes)
|
|
334
|
+
throw new Error(FetchErrors.Failed + `page over ${formatSize(maxBytes)}`)
|
|
335
|
+
chunks.push(chunk)
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
return Buffer.concat(chunks)
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
const unsupported = (contentType: string): Error =>
|
|
342
|
+
new Error(FetchErrors.Failed + `unsupported content type ${contentType}`)
|
|
343
|
+
|
|
344
|
+
const pdfDigest = async (
|
|
345
|
+
bytes: Uint8Array,
|
|
346
|
+
contentType: string,
|
|
347
|
+
signal?: AbortSignal
|
|
348
|
+
): Promise<Digest> => {
|
|
349
|
+
if (!hasPdfHeader(bytes))
|
|
350
|
+
throw new Error(FetchErrors.Failed + `served as ${contentType} but the body is not a PDF`)
|
|
351
|
+
|
|
352
|
+
const text = await pdfText(bytes, maxBytes, signal)
|
|
353
|
+
return {text, sources: [quotable(text)]}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
const digest = async (response: Response, signal?: AbortSignal): Promise<Digest> => {
|
|
357
|
+
const contentType = response.headers.get('content-type') ?? ''
|
|
358
|
+
const kind = classify(contentType)
|
|
359
|
+
|
|
360
|
+
if (kind === ContentKind.Unsupported) {
|
|
361
|
+
await response.body?.cancel()
|
|
362
|
+
throw unsupported(contentType)
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
const bytes = await readBody(response)
|
|
366
|
+
|
|
367
|
+
if (kind === ContentKind.Pdf || sniffsAsPdf(kind, contentType, bytes))
|
|
368
|
+
return pdfDigest(bytes, contentType, signal)
|
|
369
|
+
if (kind === ContentKind.Sniff && !looksLikeText(bytes)) throw unsupported(contentType)
|
|
370
|
+
|
|
371
|
+
const body = decodeBody(bytes, contentType, kind)
|
|
372
|
+
const page = kind === ContentKind.Html ? htmlToMarkdown(body) : {text: body.trim()}
|
|
373
|
+
|
|
374
|
+
if (page.text === '') throw new Error(FetchErrors.Failed + 'page has no readable text')
|
|
375
|
+
return page
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
export {digest, maxBytes}
|
|
379
|
+
export type {Digest}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
enum FetchErrors {
|
|
2
|
+
Failed = 'Fetch failed: ',
|
|
3
|
+
PageTooBig = 'Fetch failed: page too big for the subagent model context window. Tell the user; no query and no retry can read it',
|
|
4
|
+
NoPdfReader = 'Fetch failed: PDF needs pdftotext (poppler) on PATH',
|
|
5
|
+
OldPdfReader = 'Fetch failed: pdftotext is too old, it needs the -remove-hyphens option of a newer poppler',
|
|
6
|
+
NoTextLayer = 'Fetch failed: PDF has no text layer',
|
|
7
|
+
Locked = 'Fetch failed: PDF is password protected'
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export {FetchErrors}
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import type {ExtensionAPI} from '@earendil-works/pi-coding-agent'
|
|
2
|
+
import type {Api, Model} from '@earendil-works/pi-ai'
|
|
3
|
+
import {Type} from 'typebox'
|
|
4
|
+
|
|
5
|
+
import {layoutPrompt, parseAnswer, verifyAnswer} from '../answer'
|
|
6
|
+
import {fits} from '../budget'
|
|
7
|
+
import {describe} from '../describe'
|
|
8
|
+
import {registerSubagentTool, SubagentErrors, unlessAborted} from '../subagent'
|
|
9
|
+
import {digest} from './digest'
|
|
10
|
+
import type {Digest} from './digest'
|
|
11
|
+
import {FetchErrors} from './errors'
|
|
12
|
+
|
|
13
|
+
type Target = {
|
|
14
|
+
url: string
|
|
15
|
+
headers: Record<string, string>
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// fetch rejects a URL that carries credentials, so they move into the auth header.
|
|
19
|
+
const parseTarget = (url: string): Target => {
|
|
20
|
+
const parsed = new URL(url)
|
|
21
|
+
|
|
22
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')
|
|
23
|
+
throw new Error(FetchErrors.Failed + `unsupported protocol ${parsed.protocol}`)
|
|
24
|
+
if (parsed.username === '' && parsed.password === '') return {url: parsed.href, headers: {}}
|
|
25
|
+
|
|
26
|
+
const user = decodeURIComponent(parsed.username)
|
|
27
|
+
const pass = decodeURIComponent(parsed.password)
|
|
28
|
+
const token = Buffer.from(`${user}:${pass}`).toString('base64')
|
|
29
|
+
parsed.username = ''
|
|
30
|
+
parsed.password = ''
|
|
31
|
+
return {url: parsed.href, headers: {authorization: `Basic ${token}`}}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const fetchPage = async (target: Target, signal: AbortSignal | undefined): Promise<Response> =>
|
|
35
|
+
fetch(target.url, {signal, headers: target.headers}).catch((error: unknown) => {
|
|
36
|
+
unlessAborted(signal, error)
|
|
37
|
+
throw new Error(FetchErrors.Failed + describe(error), {cause: error})
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
const status = (response: Response, requested: string): string => {
|
|
41
|
+
const where = response.url === '' || response.url === requested ? '' : ` at ${response.url}`
|
|
42
|
+
const retryAfter = response.headers.get('retry-after')
|
|
43
|
+
const wait = retryAfter === null ? '' : `, Retry-After: ${retryAfter}`
|
|
44
|
+
return `${response.status} ${response.statusText}${where}${wait}`
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
type Page = Pick<Digest, 'text' | 'sources'> & {
|
|
48
|
+
url: string
|
|
49
|
+
/** Set when the server answered with an error status. */
|
|
50
|
+
failure?: string
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// MAGIC NUMBER: the Fetch Standard fails a request at its twentieth redirect. A refresh
|
|
54
|
+
// chain is followed like redirects, so it gets the same cap.
|
|
55
|
+
const maxRefreshes = 20
|
|
56
|
+
const origin = (url: string): string => new URL(url).origin
|
|
57
|
+
|
|
58
|
+
// Like fetch on a redirect: credentials stay within their origin. A refresh that cannot
|
|
59
|
+
// be fetched is ignored, as a browser would, and the current page stands.
|
|
60
|
+
const refreshTarget = (page: Digest, from: Target, base: string): Target | undefined => {
|
|
61
|
+
if (page.refresh === undefined) return undefined
|
|
62
|
+
|
|
63
|
+
try {
|
|
64
|
+
const next = parseTarget(new URL(page.refresh, base).href)
|
|
65
|
+
if (origin(next.url) !== origin(from.url)) return next
|
|
66
|
+
return {...next, headers: {...from.headers, ...next.headers}}
|
|
67
|
+
} catch {
|
|
68
|
+
return undefined
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Meta refreshes are followed like redirects; a target seen before ends the chain.
|
|
73
|
+
const loadPage = async (requested: string, signal: AbortSignal | undefined): Promise<Page> => {
|
|
74
|
+
const seen = new Set<string>()
|
|
75
|
+
let target = parseTarget(requested)
|
|
76
|
+
|
|
77
|
+
for (;;) {
|
|
78
|
+
seen.add(target.url)
|
|
79
|
+
const response = await fetchPage(target, signal)
|
|
80
|
+
const url = response.url === '' ? target.url : response.url
|
|
81
|
+
const failure = response.ok ? undefined : status(response, target.url)
|
|
82
|
+
const page: Digest = await digest(response, signal).catch((error: unknown) => {
|
|
83
|
+
unlessAborted(signal, error)
|
|
84
|
+
if (failure === undefined) throw error
|
|
85
|
+
return {text: ''}
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
if (failure !== undefined) return {url, text: page.text, failure}
|
|
89
|
+
|
|
90
|
+
const next = seen.size > maxRefreshes ? undefined : refreshTarget(page, target, url)
|
|
91
|
+
|
|
92
|
+
if (next === undefined || seen.has(next.url))
|
|
93
|
+
return {url, text: page.text, sources: page.sources}
|
|
94
|
+
target = next
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const pagePrompt = layoutPrompt({
|
|
99
|
+
source: 'page text',
|
|
100
|
+
subject: 'page',
|
|
101
|
+
unit: 'page line',
|
|
102
|
+
answerNotes: ['If the page states when it was written or updated, include that.']
|
|
103
|
+
})
|
|
104
|
+
|
|
105
|
+
const buildTask = (query: string, url: string, page: string, failure?: string): string =>
|
|
106
|
+
[
|
|
107
|
+
`<query>${query}</query>`,
|
|
108
|
+
`<url>${url}</url>`,
|
|
109
|
+
...(failure === undefined ? [] : [`<status>${failure}</status>`]),
|
|
110
|
+
`<page>\n${page}\n</page>`
|
|
111
|
+
].join('\n')
|
|
112
|
+
|
|
113
|
+
// The status leads and the layout goes, or the caller reads "COVERED: yes" as a success.
|
|
114
|
+
// Text not in the layout is dropped, as verifyAnswer would reject it.
|
|
115
|
+
const describeFailure = (failure: string, text: string): string => {
|
|
116
|
+
const lead = FetchErrors.Failed + `${failure}. Report this status.`
|
|
117
|
+
const answer = parseAnswer(text)?.answer
|
|
118
|
+
|
|
119
|
+
if (answer === undefined) return lead
|
|
120
|
+
return `${lead} The error page adds:\n${answer}`
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// An oversized error page still reports its status; the size is the lesser fact.
|
|
124
|
+
const assertFits = (task: string, model: Model<Api> | undefined, failure?: string): void => {
|
|
125
|
+
if (model === undefined) throw new Error(SubagentErrors.NoModel)
|
|
126
|
+
if (fits(task, model)) return
|
|
127
|
+
if (failure === undefined) throw new Error(FetchErrors.PageTooBig)
|
|
128
|
+
throw new Error(FetchErrors.Failed + failure)
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export default function (pi: ExtensionAPI) {
|
|
132
|
+
registerSubagentTool(pi, {
|
|
133
|
+
name: 'subagent-fetch',
|
|
134
|
+
label: 'Subagent Fetch',
|
|
135
|
+
description:
|
|
136
|
+
'Fetch a web page and hand it to an isolated subagent that extracts ONLY '
|
|
137
|
+
+ 'content answering `query`. Returns the focused answer, never the raw page. '
|
|
138
|
+
+ 'REACH FOR THIS when you need to know how an external library, tool, '
|
|
139
|
+
+ 'framework, or service is CONFIGURED, WIRED, or INTEGRATED: fetch its README '
|
|
140
|
+
+ 'or official documentation page and extract the setup you need, instead of '
|
|
141
|
+
+ 'guessing from memory. Also use it to read any known URL without stuffing '
|
|
142
|
+
+ 'raw content into the main context. If the result says the page does not '
|
|
143
|
+
+ 'cover the query, report that as the answer; do not fill the gap from memory. '
|
|
144
|
+
+ 'A failed fetch is final: do not retry the same URL, and do not guess what '
|
|
145
|
+
+ 'the page or server would have said.',
|
|
146
|
+
parameters: Type.Object({
|
|
147
|
+
url: Type.String({
|
|
148
|
+
description:
|
|
149
|
+
'URL to fetch. Must be http or https. Use the host exactly as given. '
|
|
150
|
+
+ 'Do not add or drop www. A user:password@ prefix is fine: it is sent '
|
|
151
|
+
+ 'as basic auth and never shown.'
|
|
152
|
+
}),
|
|
153
|
+
query: Type.String({description: 'What to extract from the page.'})
|
|
154
|
+
}),
|
|
155
|
+
// Pi renders while the call is still streaming, so either field may be missing.
|
|
156
|
+
title: args => [args?.query, args?.url].filter(part => part !== undefined).join(' '),
|
|
157
|
+
prepare: async (params, signal, configured) => {
|
|
158
|
+
const options = {...configured, prompt: pagePrompt, tools: []}
|
|
159
|
+
const page = await loadPage(params.url, signal)
|
|
160
|
+
const failure = page.failure
|
|
161
|
+
|
|
162
|
+
if (failure !== undefined && page.text === '')
|
|
163
|
+
throw new Error(FetchErrors.Failed + failure)
|
|
164
|
+
|
|
165
|
+
const task = buildTask(params.query, page.url, page.text, failure)
|
|
166
|
+
assertFits(task, options.model, failure)
|
|
167
|
+
const sources = [{text: page.text, wholeLines: false}, ...(page.sources ?? [])]
|
|
168
|
+
const verify = (text: string) => verifyAnswer(text, sources)
|
|
169
|
+
|
|
170
|
+
if (failure === undefined) return {task, options, verify}
|
|
171
|
+
return {task, options, verify, failure: text => describeFailure(failure, text)}
|
|
172
|
+
}
|
|
173
|
+
})
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export {buildTask, pagePrompt, parseTarget, status}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import {spawn} from 'node:child_process'
|
|
2
|
+
|
|
3
|
+
import {normalize} from '../answer'
|
|
4
|
+
import type {Source} from '../answer'
|
|
5
|
+
import {createLineReader} from '../guards/lines'
|
|
6
|
+
import {onPath} from '../platform'
|
|
7
|
+
import {FetchErrors} from './errors'
|
|
8
|
+
|
|
9
|
+
// `soft` keeps a hyphen that ends a line: the default joins `VX-` / `4471` into `VX4471`.
|
|
10
|
+
// pdftotext on Windows ends lines with \r\n, which the split patterns would miss.
|
|
11
|
+
const args = ['-remove-hyphens', 'soft', '-eol', 'unix', '-', '-']
|
|
12
|
+
|
|
13
|
+
const startFailure = (error: Error & {code?: string}): Error =>
|
|
14
|
+
error.code === 'ENOENT' ?
|
|
15
|
+
new Error(FetchErrors.NoPdfReader, {cause: error})
|
|
16
|
+
: new Error(FetchErrors.Failed + error.message, {cause: error})
|
|
17
|
+
|
|
18
|
+
const exitFailure = (
|
|
19
|
+
usage: boolean,
|
|
20
|
+
said: string,
|
|
21
|
+
code: number | null,
|
|
22
|
+
signal: string | null
|
|
23
|
+
): Error => {
|
|
24
|
+
if (usage) return new Error(FetchErrors.OldPdfReader)
|
|
25
|
+
// A crash ends mid-run, so the last line is only a warning.
|
|
26
|
+
if (signal !== null) return new Error(FetchErrors.Failed + `pdftotext stopped on ${signal}`)
|
|
27
|
+
if (said.endsWith('Incorrect password')) return new Error(FetchErrors.Locked)
|
|
28
|
+
return new Error(FetchErrors.Failed + (said || `pdftotext exited with ${code}`))
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// Not execFile: its maxBuffer caps stderr too, and a damaged PDF can warn past the page cap.
|
|
32
|
+
const convert = (bytes: Uint8Array, maxBuffer: number, signal?: AbortSignal): Promise<string> =>
|
|
33
|
+
new Promise<string>((resolve, reject) => {
|
|
34
|
+
// A plain spawn runs only an .exe or .com; a .cmd needs cmd.exe.
|
|
35
|
+
const child = spawn(onPath('pdftotext', '.EXE;.COM'), args, {signal})
|
|
36
|
+
const chunks: Buffer[] = []
|
|
37
|
+
const lines = createLineReader()
|
|
38
|
+
let size = 0
|
|
39
|
+
let said = ''
|
|
40
|
+
// Usage text answers a bad command line. With these fixed options only an old pdftotext prints it.
|
|
41
|
+
let usage = false
|
|
42
|
+
|
|
43
|
+
const hear = (text: string) => {
|
|
44
|
+
for (const line of lines.take(text)) {
|
|
45
|
+
usage ||= line.startsWith('Usage:')
|
|
46
|
+
said = line
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
child.stdout.on('data', (chunk: Buffer) => {
|
|
50
|
+
size += chunk.byteLength
|
|
51
|
+
chunks.push(chunk)
|
|
52
|
+
|
|
53
|
+
if (size <= maxBuffer) return
|
|
54
|
+
child.kill()
|
|
55
|
+
reject(new Error(FetchErrors.PageTooBig))
|
|
56
|
+
})
|
|
57
|
+
child.stderr.setEncoding('utf8')
|
|
58
|
+
child.stderr.on('data', hear)
|
|
59
|
+
child.on('error', reject)
|
|
60
|
+
child.on('close', (code, killedBy) => {
|
|
61
|
+
if (code === 0) return resolve(Buffer.concat(chunks).toString())
|
|
62
|
+
hear('\n')
|
|
63
|
+
reject(exitFailure(usage, said, code, killedBy))
|
|
64
|
+
})
|
|
65
|
+
// A child that exits or is aborted before reading its input closes stdin; the EPIPE kills pi.
|
|
66
|
+
child.stdin.on('error', () => undefined)
|
|
67
|
+
child.stdin.end(bytes)
|
|
68
|
+
}).catch((error: Error & {code?: string}) => {
|
|
69
|
+
// Our own failures carry no code; a failed spawn, or onPath finding nothing, does.
|
|
70
|
+
throw error.code === undefined ? error : startFailure(error)
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
const pageBreak = '\f'
|
|
74
|
+
const softHyphen = '\u00AD'
|
|
75
|
+
// Only the Latin ligatures: full NFKC also turns m² into m2.
|
|
76
|
+
const foldLigatures = (text: string): string =>
|
|
77
|
+
text.replace(/[\uFB00-\uFB06]/g, ligature => ligature.normalize('NFKC'))
|
|
78
|
+
|
|
79
|
+
const clean = (text: string): string =>
|
|
80
|
+
foldLigatures(text.replaceAll(pageBreak, '').replaceAll(softHyphen, '')).trim()
|
|
81
|
+
|
|
82
|
+
const pdfText = async (
|
|
83
|
+
bytes: Uint8Array,
|
|
84
|
+
maxBuffer: number,
|
|
85
|
+
signal?: AbortSignal
|
|
86
|
+
): Promise<string> => {
|
|
87
|
+
const text = clean(await convert(bytes, maxBuffer, signal))
|
|
88
|
+
|
|
89
|
+
if (text === '') throw new Error(FetchErrors.NoTextLayer)
|
|
90
|
+
return text
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Between letters a split may be a compound or a split word, so a quote may drop that hyphen.
|
|
94
|
+
const wordMark = '\0'
|
|
95
|
+
const codeMark = '\u0001'
|
|
96
|
+
// U+2010 is the hyphen a browser prints. \p{M} lets a word end in a Hindi vowel sign.
|
|
97
|
+
const wordSplits = /(?<=[\p{L}\p{M}])[-\u2010]\n+(?=\p{L})/gu
|
|
98
|
+
const codeSplits = /(?<=[\p{L}\p{M}\p{N}])[-\u2010]\n+(?=[\p{L}\p{N}])/gu
|
|
99
|
+
const hyphens = /[-\u2010] ?|[^]/gu
|
|
100
|
+
// Not RegExp.escape: it needs Node 24, and pi supports Node 22.
|
|
101
|
+
const literal = (char: string): string => `\\u{${char.codePointAt(0)?.toString(16)}}`
|
|
102
|
+
|
|
103
|
+
// A quote that copies the line break as a space has `- ` where the split was.
|
|
104
|
+
const token = (part: string): string => {
|
|
105
|
+
const [first = '', space] = [...part]
|
|
106
|
+
if (space !== undefined) return `(?:${literal(first)} |${wordMark}|${codeMark})`
|
|
107
|
+
if (first === '-' || first === '\u2010') return `[${literal(first)}${wordMark}${codeMark}]`
|
|
108
|
+
return `${wordMark}?${literal(first)}`
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// The marks sit only between letters or digits, so the pattern needs no such check of its own.
|
|
112
|
+
const quotePattern = (prose: string): RegExp =>
|
|
113
|
+
new RegExp((prose.match(hyphens) ?? []).map(token).join(''), 'u')
|
|
114
|
+
|
|
115
|
+
const quotable = (text: string): Source => {
|
|
116
|
+
const flat = normalize(text.replace(wordSplits, wordMark).replace(codeSplits, codeMark))
|
|
117
|
+
return {holds: prose => quotePattern(prose).test(flat)}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export {pdfText, quotable}
|