@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.
Files changed (53) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +116 -2
  3. package/package.json +87 -5
  4. package/src/config/box.ts +29 -0
  5. package/src/config/command.ts +138 -0
  6. package/src/config/config.ts +238 -0
  7. package/src/config/sections.ts +58 -0
  8. package/src/index.ts +17 -0
  9. package/src/plan/ask.ts +226 -0
  10. package/src/plan/goal.ts +43 -0
  11. package/src/plan/panel.ts +567 -0
  12. package/src/plan/plan.ts +581 -0
  13. package/src/plan/steps.ts +192 -0
  14. package/src/plan/track.ts +131 -0
  15. package/src/search/brave.ts +56 -0
  16. package/src/search/ddg.ts +67 -0
  17. package/src/search/engines.ts +63 -0
  18. package/src/search/exa.ts +74 -0
  19. package/src/search/search.ts +58 -0
  20. package/src/subagent/answer.ts +151 -0
  21. package/src/subagent/budget.ts +19 -0
  22. package/src/subagent/describe.ts +8 -0
  23. package/src/subagent/docs/docs.ts +123 -0
  24. package/src/subagent/docs/files.ts +90 -0
  25. package/src/subagent/docs/header.ts +60 -0
  26. package/src/subagent/docs/locate.ts +262 -0
  27. package/src/subagent/docs/manifest.ts +43 -0
  28. package/src/subagent/docs/npm.ts +287 -0
  29. package/src/subagent/fetch/digest.ts +379 -0
  30. package/src/subagent/fetch/errors.ts +10 -0
  31. package/src/subagent/fetch/fetch.ts +176 -0
  32. package/src/subagent/fetch/pdf.ts +120 -0
  33. package/src/subagent/guards/churn.ts +37 -0
  34. package/src/subagent/guards/circle.ts +49 -0
  35. package/src/subagent/guards/ground.ts +75 -0
  36. package/src/subagent/guards/guard.ts +24 -0
  37. package/src/subagent/guards/guards.ts +107 -0
  38. package/src/subagent/guards/key.ts +13 -0
  39. package/src/subagent/guards/leak.ts +42 -0
  40. package/src/subagent/guards/lines.ts +24 -0
  41. package/src/subagent/guards/loop.ts +77 -0
  42. package/src/subagent/guards/repeat.ts +70 -0
  43. package/src/subagent/guards/stale.ts +38 -0
  44. package/src/subagent/guards/toolCall.ts +46 -0
  45. package/src/subagent/guards/visited.ts +89 -0
  46. package/src/subagent/platform.ts +81 -0
  47. package/src/subagent/progress.ts +34 -0
  48. package/src/subagent/slots.ts +42 -0
  49. package/src/subagent/subagent.ts +537 -0
  50. package/src/subagent/subagentTui.ts +292 -0
  51. package/src/tui/hidden.ts +16 -0
  52. package/src/tui/spinner.ts +64 -0
  53. package/src/types/turndown-plugin-gfm.d.ts +5 -0
@@ -0,0 +1,192 @@
1
+ import {createReadTool} from '@earendil-works/pi-coding-agent'
2
+ import {stripTerminalSequences} from '@earendil-works/pi-tui'
3
+
4
+ import type {SendBack} from '../subagent/subagent'
5
+ import {regularFile} from './ask'
6
+ import {goalTask} from './goal'
7
+
8
+ const stepsLabel = 'STEPS:'
9
+ const filesLabel = 'FILES:'
10
+ const verifyLabel = 'VERIFY:'
11
+ const labels = [stepsLabel, filesLabel, verifyLabel]
12
+ const stepsLayout = `${stepsLabel}
13
+ 1. <one line per step>
14
+ ${filesLabel}
15
+ - <path> (existing|new)
16
+ ${verifyLabel}
17
+ - <the project's test command, nothing else on the line>`
18
+
19
+ // Every string the model sees here was measured as written (PLANNING_MODE.md, sections 12, 14).
20
+ const stepsRules = `The questions are done.
21
+ You are planning, not implementing. Do not change any file.
22
+ Now plan the steps that reach the goal, in order. Read the code you need.
23
+ Answer with this layout and nothing else:
24
+ ${stepsLayout}`
25
+ const currentLabel = 'Current steps:'
26
+
27
+ const note = (text: string): string =>
28
+ `[SYSTEM NOTE: ${text} Answer again with this layout and nothing else:\n${stepsLayout}]`
29
+ const layoutNote = note('Your reply did not follow the layout, so it was not accepted.')
30
+
31
+ type PlanFile = {path: string; state: 'existing' | 'new'}
32
+ type Steps = {steps: string[]; files: PlanFile[]; verify: string[]}
33
+
34
+ const misplacedNotes: Record<PlanFile['state'], (path: string) => string> = {
35
+ existing: path =>
36
+ note(`${path} is marked existing but is not on disk. Mark a file the plan creates as new.`),
37
+ new: path => note(`${path} is marked new but is on disk. Mark it existing.`)
38
+ }
39
+
40
+ const stepRow = /^\d+[.)]\s+(.+)$/
41
+ const fileRow = /^-\s*(\S.*)\((existing|new)\)$/
42
+ const unmarked = (row: string): string => row.replace(/[`*]/g, '').trim()
43
+
44
+ const fileOf = (row: string): PlanFile | undefined => {
45
+ const [, path, state] = fileRow.exec(row.replaceAll('`', '').trim()) ?? []
46
+
47
+ if (path === undefined || (state !== 'existing' && state !== 'new')) return undefined
48
+ // A path with a star is a glob: never on disk, so the new tag would let it through.
49
+ return path.includes('*') ? undefined : {path: path.trim(), state}
50
+ }
51
+
52
+ // The space keeps a row like --coverage whole.
53
+ const dash = /^-(?:\s+|$)/
54
+ const wrapped = /^`([^`]*)`$/
55
+ const noCommand = /^(?:none|\(none\))?$/i
56
+ const fence = '```'
57
+ // Qwen ends a reply on a leaked closing tag, whole or cut: </parameter>, </tool_call>, </
58
+ const closingTag = /^<\/[\w-]*>?$/
59
+ const undashed = (row: string): string => row.replace(dash, '')
60
+ const notCommand = (row: string): boolean =>
61
+ labels.includes(unmarked(row)) || undashed(row).startsWith(fence)
62
+
63
+ // A bare row beside dashed ones is text after the commands, not one more command.
64
+ const mixed = (rows: string[]): boolean => {
65
+ const dashed = rows.filter(row => dash.test(row)).length
66
+
67
+ return dashed > 0 && dashed < rows.length
68
+ }
69
+
70
+ const commandOf = (row: string): string => {
71
+ const bare = undashed(row)
72
+
73
+ return (wrapped.exec(bare)?.[1] ?? bare).trim()
74
+ }
75
+
76
+ const parseSteps = (text: string): Steps | undefined => {
77
+ const rows = text
78
+ .split('\n')
79
+ .map(row => stripTerminalSequences(row).trim())
80
+ .filter(row => row !== '')
81
+ const start = rows.findIndex(row => unmarked(row) === stepsLabel)
82
+ const end = rows.findIndex((row, index) => index > start && unmarked(row) === filesLabel)
83
+ const last = rows.findIndex((row, index) => index > end && unmarked(row) === verifyLabel)
84
+
85
+ if (start === -1 || end === -1 || last === -1) return undefined
86
+
87
+ // A step keeps its backticks and stars: `export * from` must reach the main model whole.
88
+ const steps = rows.slice(start + 1, end).map(row => stepRow.exec(row)?.[1])
89
+ const files = rows.slice(end + 1, last).map(fileOf)
90
+ const commands = rows.slice(last + 1).filter(row => !closingTag.test(row))
91
+ const read = {
92
+ steps: steps.filter(step => step !== undefined),
93
+ files: files.filter(file => file !== undefined),
94
+ verify: commands.map(commandOf).filter(command => !noCommand.test(command))
95
+ }
96
+
97
+ if (read.steps.length === 0 || read.steps.length < steps.length) return undefined
98
+ if (read.files.length < files.length || commands.some(notCommand)) return undefined
99
+ return mixed(commands) ? undefined : read
100
+ }
101
+
102
+ const onDisk = async (
103
+ cwd: string,
104
+ path: string,
105
+ signal: AbortSignal | undefined
106
+ ): Promise<boolean> => {
107
+ // pi's read tool finds the file as the model's read did. It is not opened, so reading costs
108
+ // nothing and a file the user may not read still counts.
109
+ const read = createReadTool(cwd, {
110
+ operations: {access: regularFile, readFile: () => Promise.resolve(Buffer.alloc(0))}
111
+ })
112
+
113
+ try {
114
+ await read.execute(stepsLabel, {path}, signal)
115
+ return true
116
+ } catch {
117
+ return false
118
+ }
119
+ }
120
+
121
+ const misplaced = async (
122
+ cwd: string,
123
+ files: PlanFile[],
124
+ signal: AbortSignal | undefined
125
+ ): Promise<PlanFile | undefined> => {
126
+ const there = await Promise.all(files.map(file => onDisk(cwd, file.path, signal)))
127
+
128
+ // An aborted read fails like a missing file, so its answer says nothing about the disk.
129
+ if (signal?.aborted) return undefined
130
+ return files.find((file, index) => there[index] !== (file.state === 'existing'))
131
+ }
132
+
133
+ const sendBackSteps =
134
+ (cwd: string, signal: AbortSignal | undefined): SendBack =>
135
+ async answer => {
136
+ const plan = parseSteps(answer)
137
+
138
+ if (plan === undefined) return layoutNote
139
+
140
+ const wrong = await misplaced(cwd, plan.files, signal)
141
+ return wrong === undefined ? undefined : misplacedNotes[wrong.state](wrong.path)
142
+ }
143
+
144
+ // No label for an empty list: a plan saved before the part hands over as it did.
145
+ const verifyText = (verify: string[]): string[] =>
146
+ verify.length === 0 ? [] : [verifyLabel, ...verify.map(command => `- ${command}`)]
147
+
148
+ const stepsText = ({steps, files, verify}: Steps): string => {
149
+ if (steps.length === 0) return ''
150
+ return [
151
+ stepsLabel,
152
+ ...steps.map((step, index) => `${String(index + 1)}. ${step}`),
153
+ filesLabel,
154
+ ...files.map(({path, state}) => `- ${path} (${state})`),
155
+ ...verifyText(verify)
156
+ ].join('\n')
157
+ }
158
+
159
+ // parseSteps refuses text with no VERIFY label, so an edit keeps it even with no command.
160
+ const editText = (plan: Steps): string =>
161
+ plan.verify.length === 0 ? `${stepsText(plan)}\n${verifyLabel}` : stepsText(plan)
162
+
163
+ /** head is what a fresh session must be told first; a session that knows the goal gets none. */
164
+ const stepsTask = (
165
+ head: string[],
166
+ current: Steps & {changes: string[]},
167
+ change?: string
168
+ ): string => {
169
+ const asked = change === undefined ? [] : [goalTask({change})]
170
+ const earlier = current.changes.map(typed => goalTask({change: typed}))
171
+ const known =
172
+ head.length === 0 || change === undefined ?
173
+ []
174
+ : [currentLabel, stepsText(current), ...earlier]
175
+ const lead = [...head, ...known, ...asked]
176
+
177
+ if (lead.length === 0) return stepsRules
178
+ return [...lead, '', stepsRules].join('\n')
179
+ }
180
+
181
+ export {
182
+ editText,
183
+ layoutNote,
184
+ misplaced,
185
+ parseSteps,
186
+ sendBackSteps,
187
+ stepsLayout,
188
+ stepsRules,
189
+ stepsTask,
190
+ stepsText
191
+ }
192
+ export type {PlanFile, Steps}
@@ -0,0 +1,131 @@
1
+ import {stat} from 'node:fs/promises'
2
+ import {relative, sep} from 'node:path'
3
+
4
+ import {createReadTool} from '@earendil-works/pi-coding-agent'
5
+ import type {SessionEntry} from '@earendil-works/pi-coding-agent'
6
+
7
+ import type {Steps} from './steps'
8
+
9
+ const writeTools = new Set(['edit', 'write'])
10
+ // A command can change a plan file with no edit or write call: `bun add` writes package.json.
11
+ const diskTools = new Set([...writeTools, 'bash'])
12
+ const resolveLabel = 'plan-track'
13
+
14
+ type StepMark = 'done' | 'open' | 'untracked'
15
+ type Progress = {
16
+ /** One per FILES row, in order. */
17
+ files: boolean[]
18
+ steps: StepMark[]
19
+ outside: string[]
20
+ written: number
21
+ total: number
22
+ }
23
+
24
+ // A failed call counts: a write aborted after it reached the disk still reports an error.
25
+ const writes = (entries: SessionEntry[]): string[] => [
26
+ ...new Set(
27
+ entries.flatMap(entry => {
28
+ if (entry.type !== 'message' || entry.message.role !== 'assistant') return []
29
+ return entry.message.content.flatMap(block => {
30
+ if (block.type !== 'toolCall' || !writeTools.has(block.name)) return []
31
+
32
+ const path: unknown = block.arguments.path
33
+ return typeof path === 'string' ? [path] : []
34
+ })
35
+ })
36
+ )
37
+ ]
38
+
39
+ // pi exports no path resolver. Its read tool hands the resolved path to access.
40
+ const resolved = async (cwd: string, path: string): Promise<string> => {
41
+ const found = {path}
42
+
43
+ const stop = (at: string): Promise<never> => {
44
+ found.path = at
45
+ return Promise.reject(new Error(at))
46
+ }
47
+
48
+ const read = createReadTool(cwd, {operations: {access: stop, readFile: stop}})
49
+ await read.execute(resolveLabel, {path}, undefined).catch(() => undefined)
50
+ return found.path
51
+ }
52
+
53
+ const stamp = async (path: string): Promise<string> => {
54
+ const found = await stat(path).catch(() => undefined)
55
+
56
+ return found === undefined ? '' : `${String(found.mtimeMs)}:${String(found.size)}`
57
+ }
58
+
59
+ /** One per FILES row: what is on disk now. */
60
+ const stamps = async (cwd: string, plan: Steps): Promise<string[]> =>
61
+ Promise.all(plan.files.map(async file => stamp(await resolved(cwd, file.path))))
62
+
63
+ const endsInPath = /[\w./-]$/
64
+ const goesOn = /^(?:[\w/-]|\.\w)/
65
+
66
+ /** True when the step text holds the path whole, not as a piece of a longer path. */
67
+ const names = (step: string, path: string): boolean => {
68
+ const parts = step.split(path)
69
+
70
+ return parts
71
+ .slice(1)
72
+ .some((after, index) => !endsInPath.test(parts[index] ?? '') && !goesOn.test(after))
73
+ }
74
+
75
+ const stepMark = (written: boolean[]): StepMark => {
76
+ if (written.length === 0) return 'untracked'
77
+ return written.every(Boolean) ? 'done' : 'open'
78
+ }
79
+
80
+ // A FILES row can be a folder, and a file written inside it is that row's work.
81
+ const holds = (row: string, path: string): boolean => path === row || path.startsWith(row + sep)
82
+
83
+ // An entry saved before the stamps has none, and then no row counts as changed.
84
+ const changedRows = async (rows: string[], handed: string[]): Promise<string[]> => {
85
+ const now = await Promise.all(handed.map(async (_, index) => stamp(rows[index] ?? '')))
86
+
87
+ return rows.filter((_, index) => now[index] !== handed[index])
88
+ }
89
+
90
+ const progress = async (
91
+ cwd: string,
92
+ plan: Steps,
93
+ calls: string[],
94
+ handed: string[] = []
95
+ ): Promise<Progress> => {
96
+ const [planned, called] = await Promise.all([
97
+ Promise.all(plan.files.map(file => resolved(cwd, file.path))),
98
+ Promise.all(calls.map(path => resolved(cwd, path)))
99
+ ])
100
+ const written = [...new Set(called)]
101
+ const wanted = [...new Set(planned)]
102
+ const changed = await changedRows(planned, handed)
103
+ const done = (row: string): boolean =>
104
+ changed.includes(row) || written.some(path => holds(row, path))
105
+ const files = planned.map(done)
106
+
107
+ return {
108
+ files,
109
+ steps: plan.steps.map(step =>
110
+ stepMark(
111
+ plan.files.flatMap((file, index) =>
112
+ names(step, file.path) ? [files[index] === true] : []
113
+ )
114
+ )
115
+ ),
116
+ outside: written
117
+ .filter(path => !wanted.some(row => holds(row, path)))
118
+ .map(path => relative(cwd, path).split(sep).join('/')),
119
+ written: wanted.filter(done).length,
120
+ total: wanted.length
121
+ }
122
+ }
123
+
124
+ const statusText = ({written, total, outside}: Progress): string => {
125
+ const files = `plan: files ${String(written)}/${String(total)}`
126
+
127
+ return outside.length === 0 ? files : `${files} · outside ${String(outside.length)}`
128
+ }
129
+
130
+ export {diskTools, names, progress, stamps, statusText, writes}
131
+ export type {Progress, StepMark}
@@ -0,0 +1,56 @@
1
+ import {parseHTML} from 'linkedom'
2
+ import {Type} from 'typebox'
3
+ import Value from 'typebox/value'
4
+
5
+ import type {Engine} from './engines'
6
+ import {endpoint, request, resultCount, SearchErrors, squash} from './engines'
7
+
8
+ /** The fields used to read a description. Its DOM types are not in this tsconfig lib. */
9
+ type Fragment = {body: {innerHTML: string; textContent: string | null}}
10
+
11
+ const braveEndpoint = 'https://api.search.brave.com/res/v1/web/search'
12
+ const braveKey = 'BRAVE_SEARCH_API_KEY'
13
+
14
+ const bodySchema = Type.Object({
15
+ web: Type.Optional(
16
+ Type.Object({
17
+ results: Type.Array(
18
+ Type.Object({
19
+ title: Type.String(),
20
+ url: Type.String(),
21
+ description: Type.Optional(Type.String())
22
+ })
23
+ )
24
+ })
25
+ )
26
+ })
27
+
28
+ // Descriptions come as HTML, with the query words in <strong> and entities encoded.
29
+ const plain = (html: string): string => {
30
+ const {document} = parseHTML('<html><body></body></html>') as {document: Fragment}
31
+ document.body.innerHTML = html
32
+ return squash(document.body.textContent ?? '')
33
+ }
34
+
35
+ const brave: Engine = async (query, signal) => {
36
+ const key = process.env[braveKey]
37
+
38
+ if (key === undefined || key === '')
39
+ throw new Error(`${SearchErrors.Failed}${braveKey} is not set`)
40
+
41
+ const params = new URLSearchParams({q: query, count: String(resultCount)})
42
+ const reply = await request(
43
+ 'brave',
44
+ `${endpoint(braveEndpoint)}?${params}`,
45
+ {headers: {accept: 'application/json', 'x-subscription-token': key}},
46
+ signal
47
+ )
48
+ const body = Value.Parse(bodySchema, JSON.parse(reply.text))
49
+ return (body.web?.results ?? []).map(result => ({
50
+ title: result.title,
51
+ url: result.url,
52
+ description: plain(result.description ?? '')
53
+ }))
54
+ }
55
+
56
+ export {brave, braveKey}
@@ -0,0 +1,67 @@
1
+ import {parseHTML} from 'linkedom'
2
+
3
+ import type {Engine, SearchResult} from './engines'
4
+ import {endpoint, request, SearchErrors, squash} from './engines'
5
+
6
+ const ddgEndpoint = 'https://html.duckduckgo.com/html/'
7
+ // Without a browser user agent the endpoint answers a challenge page instead of results.
8
+ const browserAgent = 'Mozilla/5.0 (X11; Linux x86_64; rv:127.0) Gecko/20100101 Firefox/127.0'
9
+ const challenged = 202
10
+
11
+ /** The fields read off the parsed document. Its DOM types are not in this tsconfig lib. */
12
+ type Row = {
13
+ querySelector(selector: string): Row | null
14
+ getAttribute(name: string): string | null
15
+ textContent: string | null
16
+ }
17
+
18
+ type Document = {
19
+ querySelectorAll(selector: string): Iterable<Row>
20
+ }
21
+
22
+ // Result links go through a duckduckgo.com redirect that carries the destination in uddg.
23
+ const destination = (href: string): string | undefined => {
24
+ try {
25
+ const link = new URL(href, ddgEndpoint)
26
+
27
+ if (!link.hostname.endsWith('duckduckgo.com')) return link.href
28
+ return link.searchParams.get('uddg') ?? undefined
29
+ } catch {
30
+ return undefined
31
+ }
32
+ }
33
+
34
+ const parseRow = (row: Row): SearchResult | undefined => {
35
+ const anchor = row.querySelector('a.result__a')
36
+ const url = destination(anchor?.getAttribute('href') ?? '')
37
+
38
+ if (anchor === null || url === undefined) return undefined
39
+ return {
40
+ title: squash(anchor.textContent ?? '') || url,
41
+ url,
42
+ description: squash(row.querySelector('.result__snippet')?.textContent ?? '')
43
+ }
44
+ }
45
+
46
+ const parseResults = (html: string): SearchResult[] => {
47
+ const {document} = parseHTML(html) as unknown as {document: Document}
48
+ return [...document.querySelectorAll('.result:not(.result--ad)')]
49
+ .map(parseRow)
50
+ .filter(result => result !== undefined)
51
+ }
52
+
53
+ const ddg: Engine = async (query, signal) => {
54
+ const params = new URLSearchParams({q: query})
55
+ const reply = await request(
56
+ 'ddg',
57
+ `${endpoint(ddgEndpoint)}?${params}`,
58
+ {headers: {accept: 'text/html', 'user-agent': browserAgent}},
59
+ signal
60
+ )
61
+
62
+ if (reply.status === challenged)
63
+ throw new Error(`${SearchErrors.Failed}ddg answered a bot challenge instead of results`)
64
+ return parseResults(reply.text)
65
+ }
66
+
67
+ export {browserAgent, ddg, parseResults}
@@ -0,0 +1,63 @@
1
+ import {describe} from '../subagent/describe'
2
+ import {parseTarget, status} from '../subagent/fetch/fetch'
3
+
4
+ enum SearchErrors {
5
+ Failed = 'Search failed: ',
6
+ Aborted = 'Search aborted'
7
+ }
8
+
9
+ type SearchResult = {
10
+ title: string
11
+ url: string
12
+ description: string
13
+ }
14
+
15
+ type Engine = (query: string, signal: AbortSignal | undefined) => Promise<SearchResult[]>
16
+
17
+ // MAGIC NUMBER: results per search. What every engine serves by default, and one screen for the
18
+ // model that reads the list.
19
+ const resultCount = 10
20
+ const endpointOverride = 'PI_NOP_SEARCH_ENDPOINT'
21
+ // Read per call so the eval can point every engine at its fixture server.
22
+ const endpoint = (fallback: string): string => process.env[endpointOverride] ?? fallback
23
+
24
+ type Reply = {
25
+ status: number
26
+ text: string
27
+ }
28
+
29
+ // The body is read here too, so a cancel while it streams in is still an abort.
30
+ const request = async (
31
+ engine: string,
32
+ url: string,
33
+ init: RequestInit,
34
+ signal: AbortSignal | undefined
35
+ ): Promise<Reply> => {
36
+ const failed = (error: unknown): never => {
37
+ if (signal?.aborted) throw new Error(SearchErrors.Aborted, {cause: error})
38
+ throw new Error(SearchErrors.Failed + describe(error), {cause: error})
39
+ }
40
+
41
+ const response = await fetch(url, {...init, signal}).catch(failed)
42
+
43
+ if (!response.ok) throw new Error(`${SearchErrors.Failed}${engine} ${status(response, url)}`)
44
+ return {status: response.status, text: await response.text().catch(failed)}
45
+ }
46
+
47
+ const squash = (text: string): string => text.replace(/\s+/g, ' ').trim()
48
+
49
+ // The same rule subagent-fetch applies, so every listed URL is one it will open.
50
+ const fetchable = (url: string): boolean => {
51
+ try {
52
+ parseTarget(url)
53
+ return true
54
+ } catch {
55
+ return false
56
+ }
57
+ }
58
+
59
+ const httpOnly = (results: SearchResult[]): SearchResult[] =>
60
+ results.filter(result => fetchable(result.url))
61
+
62
+ export {endpoint, endpointOverride, httpOnly, request, resultCount, SearchErrors, squash}
63
+ export type {Engine, SearchResult}
@@ -0,0 +1,74 @@
1
+ import {Type} from 'typebox'
2
+ import Value from 'typebox/value'
3
+
4
+ import type {Engine, SearchResult} from './engines'
5
+ import {endpoint, request, resultCount, SearchErrors, squash} from './engines'
6
+
7
+ const exaEndpoint = 'https://mcp.exa.ai/mcp'
8
+
9
+ const rpcSchema = Type.Object({
10
+ result: Type.Optional(
11
+ Type.Object({
12
+ content: Type.Array(
13
+ Type.Object({type: Type.String(), text: Type.Optional(Type.String())})
14
+ ),
15
+ isError: Type.Optional(Type.Boolean())
16
+ })
17
+ ),
18
+ error: Type.Optional(Type.Object({message: Type.String()}))
19
+ })
20
+
21
+ // The endpoint answers as an event stream. The whole reply sits in its one data frame.
22
+ const rpcText = (body: string): string => {
23
+ const frame = body.split('\n').find(line => line.startsWith('data:'))
24
+ const rpc = Value.Parse(rpcSchema, JSON.parse(frame === undefined ? body : frame.slice(5)))
25
+ const text = rpc.result?.content.find(part => part.type === 'text')?.text
26
+
27
+ if (rpc.error !== undefined) throw new Error(`${SearchErrors.Failed}exa: ${rpc.error.message}`)
28
+ if (rpc.result?.isError === true || text === undefined)
29
+ throw new Error(`${SearchErrors.Failed}exa: ${text ?? 'no result'}`)
30
+ return text
31
+ }
32
+
33
+ // A block is "Title:", "URL:", some labelled lines, then "Highlights:" or "Text:" and the
34
+ // content. Highlights are several excerpts split by "..." lines; the first one is the snippet,
35
+ // so every engine hands over one snippet per result.
36
+ const parseBlock = (block: string): SearchResult | undefined => {
37
+ const title = /^Title: (.*)$/m.exec(block)?.[1]
38
+ const url = /^URL: (.*)$/m.exec(block)?.[1]
39
+ const content = /^(?:Highlights|Text):[ \t]*\n?([\s\S]*)$/m.exec(block)?.[1] ?? ''
40
+ const [snippet] = content.split(/^\.\.\.$/m)
41
+
42
+ if (url === undefined) return undefined
43
+ return {title: squash(title ?? '') || url, url, description: squash(snippet ?? '')}
44
+ }
45
+
46
+ const parseBlocks = (text: string): SearchResult[] =>
47
+ text
48
+ .split(/^---$/m)
49
+ .map(parseBlock)
50
+ .filter(result => result !== undefined)
51
+
52
+ const exa: Engine = async (query, signal) => {
53
+ const reply = await request(
54
+ 'exa',
55
+ endpoint(exaEndpoint),
56
+ {
57
+ method: 'POST',
58
+ headers: {
59
+ 'content-type': 'application/json',
60
+ accept: 'application/json, text/event-stream'
61
+ },
62
+ body: JSON.stringify({
63
+ jsonrpc: '2.0',
64
+ id: 1,
65
+ method: 'tools/call',
66
+ params: {name: 'web_search_exa', arguments: {query, numResults: resultCount}}
67
+ })
68
+ },
69
+ signal
70
+ )
71
+ return parseBlocks(rpcText(reply.text))
72
+ }
73
+
74
+ export {exa, parseBlocks}
@@ -0,0 +1,58 @@
1
+ import type {ExtensionAPI} from '@earendil-works/pi-coding-agent'
2
+ import {Type} from 'typebox'
3
+ import Value from 'typebox/value'
4
+
5
+ import {engine, read, safeConfig, searchTool} from '../config/config'
6
+ import type {EngineName} from '../config/config'
7
+ import {brave} from './brave'
8
+ import {ddg} from './ddg'
9
+ import {exa} from './exa'
10
+ import type {Engine, SearchResult} from './engines'
11
+ import {httpOnly} from './engines'
12
+
13
+ const engineOverride = 'PI_NOP_SEARCH_ENGINE'
14
+ const engines: Record<EngineName, Engine> = {exa, brave, ddg}
15
+
16
+ const formatResult = (result: SearchResult, index: number): string => {
17
+ const lead = `${index + 1}. [${result.title}](${result.url})`
18
+ return result.description === '' ? lead : `${lead} — ${result.description}`
19
+ }
20
+
21
+ const formatResults = (query: string, results: SearchResult[]): string =>
22
+ results.length === 0 ? `No results for: ${query}` : results.map(formatResult).join('\n')
23
+
24
+ export default function (pi: ExtensionAPI) {
25
+ pi.registerTool({
26
+ name: searchTool,
27
+ label: 'Web Search',
28
+ description:
29
+ 'Search the live web. CALL THIS BEFORE ANSWERING any question about current or '
30
+ + 'version-specific external facts: library/framework versions and their APIs, '
31
+ + 'latest releases, recently shipped features, current events, prices, or who '
32
+ + 'currently holds a role. Your built-in knowledge is out of date — do NOT answer '
33
+ + 'such questions from memory and do NOT shell out with bash to guess. Returns a '
34
+ + 'numbered list of up to 10 results (title, URL, snippet); then call '
35
+ + '`subagent-fetch` on the URL you want to read. A snippet is a teaser, not the '
36
+ + 'page: when the detail matters, fetch the page.',
37
+ parameters: Type.Object({
38
+ query: Type.String({
39
+ description:
40
+ 'What to search for. Keywords or a short question; name the product '
41
+ + 'and version when known.'
42
+ })
43
+ }),
44
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
45
+ const name = Value.Parse(
46
+ engine.schema,
47
+ process.env[engineOverride] ?? read(safeConfig(ctx), engine)
48
+ )
49
+ const results = httpOnly(await engines[name](params.query, signal))
50
+ return {
51
+ content: [{type: 'text', text: formatResults(params.query, results)}],
52
+ details: {engine: name, results: results.length}
53
+ }
54
+ }
55
+ })
56
+ }
57
+
58
+ export {engineOverride, formatResults}