@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,151 @@
1
+ type Layout = {
2
+ /** What the model may read: "page text", "package files". */
3
+ source: string
4
+ /** The thing that covers the query: "page", "package". */
5
+ subject: string
6
+ /** What one evidence line is: "page line", "file line". */
7
+ unit: string
8
+ answerNotes?: string[]
9
+ evidenceNotes?: string[]
10
+ }
11
+
12
+ // The subagent answers in a fixed layout so the tool can check it instead of trusting it.
13
+ const layoutPrompt = ({
14
+ source,
15
+ subject,
16
+ unit,
17
+ answerNotes = [],
18
+ evidenceNotes = []
19
+ }: Layout): string =>
20
+ [
21
+ `Answer the query using only the ${source}.`,
22
+ 'Reply in exactly this layout and nothing else. No code fence around it.',
23
+ `COVERED: yes, partial or no. partial when the ${subject} answers only some of the query.`,
24
+ 'ANSWER:',
25
+ `the answer, any length. When COVERED is partial or no, say what is missing and what the ${subject} holds instead.`,
26
+ ...answerNotes,
27
+ 'EVIDENCE:',
28
+ [
29
+ `one ${unit} per line, every line the answer rests on, copied exactly, character for character.`,
30
+ ...evidenceNotes
31
+ ].join(' '),
32
+ 'At least one line when COVERED is yes or partial. Nothing when COVERED is no and there is nothing to cite.'
33
+ ].join('\n')
34
+
35
+ enum AnswerErrors {
36
+ Layout = 'Subagent answer failed verification: not in the answer layout',
37
+ NoEvidence = 'Subagent answer failed verification: no evidence for a covered answer',
38
+ Invented = 'Subagent answer failed verification: evidence not in the source: '
39
+ }
40
+
41
+ const coverages = ['yes', 'partial', 'no'] as const
42
+ type Coverage = (typeof coverages)[number]
43
+
44
+ type Answer = {
45
+ covered: Coverage
46
+ answer: string
47
+ evidence: string[]
48
+ }
49
+
50
+ const isCoverage = (value: string): value is Coverage =>
51
+ (coverages as readonly string[]).includes(value)
52
+
53
+ const labelled = (line: string | undefined, label: string): string | undefined =>
54
+ line?.startsWith(label) ? line.slice(label.length).trim() : undefined
55
+
56
+ // Labels are found on trimmed lines, but the answer keeps its raw lines: blank lines and
57
+ // indentation are part of a copied code block.
58
+ const parseAnswer = (text: string): Answer | undefined => {
59
+ const lines = text.replaceAll('\r\n', '\n').split('\n')
60
+ const trimmed = lines.map(line => line.trim())
61
+ const coveredAt = trimmed.findIndex(line => line !== '')
62
+ const answerAt = trimmed.findIndex((line, index) => index > coveredAt && line !== '')
63
+ const divider = trimmed.findIndex(
64
+ (line, index) => index > answerAt && line.startsWith('EVIDENCE:')
65
+ )
66
+ const covered = labelled(trimmed[coveredAt], 'COVERED:')?.toLowerCase()
67
+ const first = labelled(trimmed[answerAt], 'ANSWER:')
68
+
69
+ if (covered === undefined || !isCoverage(covered)) return undefined
70
+ if (first === undefined || divider === -1) return undefined
71
+
72
+ const answer = [first, ...lines.slice(answerAt + 1, divider)].join('\n').trim()
73
+
74
+ if (answer === '') return undefined
75
+
76
+ const evidence = [labelled(trimmed[divider], 'EVIDENCE:') ?? '', ...trimmed.slice(divider + 1)]
77
+ return {covered, answer, evidence: evidence.filter(line => line !== '')}
78
+ }
79
+
80
+ // Models drop backticks and emphasis when copying; that is not invention.
81
+ const normalize = (text: string): string => text.replace(/[`*]/g, '').replace(/\s+/g, ' ').trim()
82
+ // A code line may also lose its comment markers or list marker; the `*` of `/** */` is already gone.
83
+ const normalizeLine = (line: string): string =>
84
+ normalize(line)
85
+ .replace(/^\/+\s*/, '')
86
+ .replace(/\s*\/+$/, '')
87
+ .replace(/^(?:[-+]|\d+\.)\s+/, '')
88
+
89
+ type TextSource = {
90
+ text: string
91
+ /** Code: a quote must be a whole line. `string;` is in every declaration file. Prose: any run. */
92
+ wholeLines: boolean
93
+ }
94
+
95
+ /** A source that matches a quote its own way. It takes the quote normalized. */
96
+ type QuoteMatcher = {holds: (prose: string) => boolean}
97
+
98
+ type Source = TextSource | QuoteMatcher
99
+
100
+ type Quote = {line: string; prose: string; code: string}
101
+
102
+ const matcher = (source: Source): ((quote: Quote) => boolean) => {
103
+ if ('holds' in source) return quote => source.holds(quote.prose)
104
+
105
+ if (!source.wholeLines) {
106
+ const flat = normalize(source.text)
107
+ return quote => flat.includes(quote.prose)
108
+ }
109
+
110
+ const lines = new Set(source.text.split('\n').map(normalizeLine))
111
+ return quote => lines.has(quote.code)
112
+ }
113
+
114
+ const missingFrom = (evidence: string[], sources: Source[]): string[] => {
115
+ let pending: Quote[] = evidence.map(line => ({
116
+ line,
117
+ prose: normalize(line),
118
+ code: normalizeLine(line)
119
+ }))
120
+
121
+ for (const source of sources) {
122
+ if (pending.length === 0) break
123
+ const holds = matcher(source)
124
+ pending = pending.filter(quote => !holds(quote))
125
+ }
126
+
127
+ return pending.map(({line}) => line)
128
+ }
129
+
130
+ // A fence, a lone `}` or an emphasis-only line claims nothing, so it is dropped, not failed.
131
+ const substantive = (evidence: string[]): string[] =>
132
+ evidence.filter(line => /[\p{L}\p{N}]/u.test(normalize(line)))
133
+
134
+ // The layout is returned as is, so the caller sees the coverage and the evidence too.
135
+ const verifyAnswer = (text: string, sources: Source[]): string => {
136
+ const answer = parseAnswer(text)
137
+
138
+ if (answer === undefined) throw new Error(AnswerErrors.Layout)
139
+
140
+ const evidence = substantive(answer.evidence)
141
+
142
+ if (answer.covered !== 'no' && evidence.length === 0) throw new Error(AnswerErrors.NoEvidence)
143
+
144
+ const invented = missingFrom(evidence, sources)
145
+
146
+ if (invented.length > 0) throw new Error(AnswerErrors.Invented + invented.join(' | '))
147
+ return text
148
+ }
149
+
150
+ export {AnswerErrors, layoutPrompt, missingFrom, normalize, parseAnswer, substantive, verifyAnswer}
151
+ export type {Answer, Coverage, Source, TextSource}
@@ -0,0 +1,19 @@
1
+ import {estimateTokens} from '@earendil-works/pi-coding-agent'
2
+ import type {Api, Model} from '@earendil-works/pi-ai'
3
+
4
+ // MAGIC NUMBER: share of the context window the task may take. The rest is headroom for
5
+ // the system prompt, the answer and the rough 4 chars per token estimate pi uses.
6
+ const taskShare = 0.75
7
+
8
+ // pi counts 4 chars per token, which holds for ASCII only. Other scripts run near one
9
+ // token per character, and the plain estimate let CJK pages through that then overflowed.
10
+ const estimateTaskTokens = (task: string): number => {
11
+ const nonAscii = task.match(/[\u0080-\uffff]/g)?.length ?? 0
12
+ const base = estimateTokens({role: 'user', content: task, timestamp: Date.now()})
13
+ return base + nonAscii - Math.floor(nonAscii / 4)
14
+ }
15
+
16
+ const fits = (task: string, model: Model<Api>): boolean =>
17
+ estimateTaskTokens(task) <= model.contextWindow * taskShare
18
+
19
+ export {fits, taskShare}
@@ -0,0 +1,8 @@
1
+ // Node wraps network errors as a bare "fetch failed" TypeError with the reason in `cause`.
2
+ const describe = (error: unknown): string => {
3
+ if (!(error instanceof Error)) return String(error)
4
+ if (error.cause instanceof Error) return `${error.message}: ${error.cause.message}`
5
+ return error.message
6
+ }
7
+
8
+ export {describe}
@@ -0,0 +1,123 @@
1
+ import type {ExtensionAPI} from '@earendil-works/pi-coding-agent'
2
+ import {Type} from 'typebox'
3
+
4
+ import {layoutPrompt, verifyAnswer} from '../answer'
5
+ import {fits} from '../budget'
6
+ import {registerSubagentTool, SubagentErrors} from '../subagent'
7
+ import {corpusOf} from './files'
8
+ import type {CorpusFile} from './files'
9
+ import {header} from './header'
10
+ import {locate, packageName, projectOf} from './locate'
11
+ import type {Located, Project} from './locate'
12
+ import {spec} from './manifest'
13
+ import {facts as registryFacts, fromRegistry} from './npm'
14
+ import type {Facts} from './npm'
15
+
16
+ enum DocsErrors {
17
+ TooBig = 'Docs failed: package too big for the subagent model context window, even as a file list. Files: '
18
+ }
19
+
20
+ const filesPrompt = layoutPrompt({
21
+ source: 'package files',
22
+ subject: 'package',
23
+ unit: 'file line',
24
+ evidenceNotes: ['No line numbers, no file names.']
25
+ })
26
+ const toolsPrompt = [
27
+ 'Read and grep the files listed; nothing else counts, and do not answer from memory.',
28
+ filesPrompt
29
+ ].join('\n')
30
+
31
+ const render = (files: CorpusFile[]): string =>
32
+ files.map(file => `<file path="${file.label}">\n${file.text}\n</file>`).join('\n')
33
+
34
+ // Tools mode reads the same files inline mode is handed, so a quote from anywhere else fails.
35
+ const renderPaths = (files: CorpusFile[]): string =>
36
+ files.map(file => `<file>${file.path}</file>`).join('\n')
37
+
38
+ // For node:fs the declaration to report is @types/node's, looked up again only then.
39
+ const projectFor = (located: Located, asked: Project, cwd: string): Project =>
40
+ located.source === 'runtime' ? projectOf(located.pkg.manifest.name, cwd) : asked
41
+
42
+ // The registry knows the package asked about, not @types/x. A runtime module is not on npm.
43
+ const factsFor = async (
44
+ located: Located,
45
+ project: Project,
46
+ cwd: string,
47
+ signal?: AbortSignal
48
+ ): Promise<Facts> => {
49
+ if (located.source === 'runtime' || !fromRegistry(project.range)) return {}
50
+ if (located.source === 'types-only') return registryFacts(located.asked, undefined, cwd, signal)
51
+ return registryFacts(located.pkg.manifest.name, located.pkg.manifest.version, cwd, signal)
52
+ }
53
+
54
+ export default function (pi: ExtensionAPI) {
55
+ registerSubagentTool(pi, {
56
+ name: 'subagent-docs',
57
+ label: 'Subagent Docs',
58
+ description:
59
+ 'Look up an npm package and return a focused, version-pinned answer from its type '
60
+ + 'declarations and README, plus the latest published version. USE THIS BEFORE '
61
+ + 'ANSWERING any question about how to use a JavaScript or TypeScript library, what '
62
+ + 'it exports, its types, options or config, or which version to install. Do NOT '
63
+ + 'answer package APIs from memory and do NOT run npm view or read node_modules '
64
+ + 'yourself. Reads the installed copy when there is one, else downloads the declared '
65
+ + 'range or the latest release. If the result says the package does not cover the '
66
+ + 'query, report that; do not fill the gap from memory.',
67
+ parameters: Type.Object({
68
+ module: Type.String({
69
+ description:
70
+ 'Package name or subpath, as you would import it: "zod", "@scope/name", "hono/client". No version here.'
71
+ }),
72
+ query: Type.String({description: 'What to find out about the package.'}),
73
+ version: Type.Optional(
74
+ Type.String({
75
+ description:
76
+ 'Exact version to read. The installed copy is used when it matches; otherwise that version is read from npm. Omit to read what is installed, or the declared range or latest when nothing is.'
77
+ })
78
+ )
79
+ }),
80
+ title: args => [args?.module, args?.query].filter(part => part !== undefined).join(' '),
81
+ prepare: async (params, signal, configured) => {
82
+ const model = configured.model
83
+
84
+ if (model === undefined) throw new Error(SubagentErrors.NoModel)
85
+
86
+ const cwd = configured.cwd
87
+ const name = packageName(params.module)
88
+ const asked = projectOf(name, cwd)
89
+ const located = await locate(
90
+ params.module,
91
+ cwd,
92
+ {version: params.version, range: asked.range},
93
+ signal
94
+ )
95
+ const corpus = corpusOf(located)
96
+ const ask = [
97
+ `<query>${params.query}</query>`,
98
+ `<module>${params.module}</module>`,
99
+ `<package>${spec(located.pkg.manifest)}</package>`,
100
+ ...(located.entry === undefined ? [] : [`<entry>${located.entry}</entry>`])
101
+ ]
102
+ const inline = [...ask, render(corpus.files)].join('\n')
103
+ const listed = [...ask, renderPaths(corpus.files)].join('\n')
104
+ const whole = fits(inline, model)
105
+
106
+ if (!whole && !fits(listed, model))
107
+ throw new Error(DocsErrors.TooBig + corpus.files.length)
108
+
109
+ const project = projectFor(located, asked, cwd)
110
+ const facts = await factsFor(located, project, cwd, signal)
111
+ const lead = header(located, project, facts, corpus) + '\n'
112
+ const verify = (text: string) => lead + verifyAnswer(text, corpus.files)
113
+
114
+ if (whole)
115
+ return {
116
+ task: inline,
117
+ options: {...configured, prompt: filesPrompt, tools: []},
118
+ verify
119
+ }
120
+ return {task: listed, options: {...configured, prompt: toolsPrompt}, verify}
121
+ }
122
+ })
123
+ }
@@ -0,0 +1,90 @@
1
+ import {readdirSync, readFileSync} from 'node:fs'
2
+ import {join, relative, sep} from 'node:path'
3
+
4
+ import type {TextSource} from '../answer'
5
+ import {packages} from './locate'
6
+ import type {Located, Package} from './locate'
7
+
8
+ type CorpusFile = TextSource & {
9
+ /** Package-qualified, so x and @types/x never clash. */
10
+ label: string
11
+ /** Absolute. */
12
+ path: string
13
+ }
14
+
15
+ type Corpus = {
16
+ files: CorpusFile[]
17
+ declared: boolean
18
+ /** The entry source file, when nothing declares types and it stands in for them. */
19
+ standIn?: string
20
+ }
21
+
22
+ const isDeclaration = (name: string): boolean => /\.d\.[mc]?ts$/.test(name)
23
+ const isReadme = (name: string): boolean => name.toLowerCase().startsWith('readme')
24
+ const majorFolder = (path: string): string | undefined => /^v\d+\//.exec(path)?.[0]
25
+
26
+ // npm never packs a symlink, and a nested node_modules is another package.
27
+ const walk = (dir: string, rel = ''): string[] =>
28
+ readdirSync(join(dir, rel), {withFileTypes: true}).flatMap(entry => {
29
+ const path = rel === '' ? entry.name : `${rel}/${entry.name}`
30
+
31
+ if (entry.isSymbolicLink() || entry.name === 'node_modules') return []
32
+ if (entry.isDirectory()) return walk(dir, path)
33
+ return entry.isFile() ? [path] : []
34
+ })
35
+
36
+ // zod 4 ships v3/ beside v4/, and a v3 quote would pass under a zod@4 header. A package with a
37
+ // folder for its own major is read as layered; without one, vN/ folders are plain namespaces.
38
+ const packageFiles = (pkg: Package, keepFolder?: string): string[] => {
39
+ const all = walk(pkg.dir)
40
+ const major = pkg.manifest.version?.split('.')[0]
41
+ const own = `v${major ?? ''}/`
42
+ const layered = major !== undefined && all.some(path => majorFolder(path) === own)
43
+ const keep = (folder: string | undefined): boolean =>
44
+ !layered || folder === undefined || folder === own || folder === keepFolder
45
+ return all
46
+ .filter(path => keep(majorFolder(path)))
47
+ .filter(
48
+ path =>
49
+ isDeclaration(path)
50
+ || path === 'package.json'
51
+ || (!path.includes('/') && isReadme(path))
52
+ )
53
+ .sort()
54
+ }
55
+
56
+ // A README line is often longer than the sentence a model copies from it.
57
+ const readFile = (pkg: Package, path: string): CorpusFile => ({
58
+ label: `${pkg.manifest.name}/${path}`,
59
+ path: join(pkg.dir, path),
60
+ text: readFileSync(join(pkg.dir, path), 'utf8'),
61
+ wholeLines: !isReadme(path)
62
+ })
63
+
64
+ // Dual ESM and CJS declarations are the same text twice and would double the corpus.
65
+ const readAll = (pkg: Package, paths: string[]): CorpusFile[] => {
66
+ const byText = new Map<string, CorpusFile>()
67
+
68
+ for (const path of paths) {
69
+ const file = readFile(pkg, path)
70
+ if (!byText.has(file.text)) byText.set(file.text, file)
71
+ }
72
+
73
+ return [...byText.values()]
74
+ }
75
+
76
+ // What the model is handed, and what its quotes are checked against.
77
+ const corpusOf = (located: Located): Corpus => {
78
+ const entry = located.entry
79
+ const entryPath =
80
+ entry === undefined ? undefined : relative(located.pkg.dir, entry).split(sep).join('/')
81
+ const keepFolder = entryPath === undefined ? undefined : majorFolder(entryPath)
82
+ const files = packages(located).flatMap(pkg => readAll(pkg, packageFiles(pkg, keepFolder)))
83
+ const declared = files.some(file => isDeclaration(file.label))
84
+
85
+ if (declared || entryPath === undefined) return {files, declared}
86
+ return {files: [...files, readFile(located.pkg, entryPath)], declared, standIn: entryPath}
87
+ }
88
+
89
+ export {corpusOf, packageFiles}
90
+ export type {Corpus, CorpusFile}
@@ -0,0 +1,60 @@
1
+ import type {Corpus} from './files'
2
+ import type {Located, Project} from './locate'
3
+ import {spec} from './manifest'
4
+ import type {Manifest} from './manifest'
5
+ import type {Facts} from './npm'
6
+
7
+ // A manifest field or a deprecation notice could carry a fake "COVERED:" line.
8
+ const headerLine = (label: string, value: string | undefined): string[] =>
9
+ value === undefined ? [] : [`${label}: ${value.replace(/\s+/g, ' ').trim()}`]
10
+
11
+ const packageLine = (located: Located): string => {
12
+ const read = spec(located.pkg.manifest)
13
+
14
+ switch (located.source) {
15
+ case 'downloaded':
16
+ if (located.installed === undefined) return `${read} (not installed, read from npm)`
17
+ return `${read} (read from npm; installed is ${located.pkg.manifest.name}@${located.installed})`
18
+ case 'types-only':
19
+ return `${located.asked} (not installed); read from ${read} (installed)`
20
+ case 'runtime':
21
+ return `${located.asked} (runtime module); read from ${read} (installed)`
22
+ case 'installed':
23
+ if (located.asked === located.pkg.manifest.name) return `${read} (installed)`
24
+ return `${located.asked} (installed as ${read})`
25
+ }
26
+ }
27
+
28
+ const typesLine = (located: Located, corpus: Corpus): string => {
29
+ if (located.types.length > 0)
30
+ return `from ${located.types.map(pkg => spec(pkg.manifest)).join(', ')}`
31
+ if (corpus.declared) return 'shipped in the package'
32
+ if (corpus.standIn === undefined) return 'none; no entry file to read either'
33
+ return `none; ${corpus.standIn} stands in`
34
+ }
35
+
36
+ const declaredLine = (project: Project): string | undefined => {
37
+ if (project.path === undefined) return undefined
38
+ if (project.range === undefined) return `no, not in ${project.path}`
39
+ return `${project.range} in ${project.path}`
40
+ }
41
+
42
+ const latestLine = (facts: Facts): string | undefined =>
43
+ facts.error === undefined ? facts.latest : `unknown, registry error: ${facts.error}`
44
+
45
+ const repositoryUrl = (manifest: Manifest): string | undefined =>
46
+ typeof manifest.repository === 'string' ? manifest.repository : manifest.repository?.url
47
+
48
+ // Every line is copied from package.json or the registry. The subagent never sees it.
49
+ const header = (located: Located, project: Project, facts: Facts, corpus: Corpus): string =>
50
+ [
51
+ ...headerLine('PACKAGE', packageLine(located)),
52
+ ...headerLine('DECLARED', declaredLine(project)),
53
+ ...headerLine('LATEST', latestLine(facts)),
54
+ ...headerLine('DEPRECATED', facts.deprecated),
55
+ ...headerLine('TYPES', typesLine(located, corpus)),
56
+ ...headerLine('HOMEPAGE', located.pkg.manifest.homepage),
57
+ ...headerLine('REPOSITORY', repositoryUrl(located.pkg.manifest))
58
+ ].join('\n')
59
+
60
+ export {header}