@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,89 @@
1
+ import {DEFAULT_MAX_LINES} from '@earendil-works/pi-coding-agent'
2
+
3
+ import type {Guard} from './guard'
4
+ import {noop} from './guard'
5
+
6
+ type ReadCall = {path: string; from: number; to: number}
7
+
8
+ type Visited = Guard & {list: () => string}
9
+
10
+ // MAGIC NUMBER: past a screenful of paths the tail costs prefill and is not read.
11
+ const shownPaths = 40
12
+
13
+ // pi coerces a numeric string to a number before the tool runs, but the start event carries the
14
+ // raw arguments, and a small model sends "2001" as often as 2001.
15
+ const asNumber = (value: unknown): number | undefined => {
16
+ const parsed = typeof value === 'string' && value.trim() !== '' ? Number(value) : value
17
+ return typeof parsed === 'number' && Number.isFinite(parsed) ? parsed : undefined
18
+ }
19
+
20
+ const readCall = (name: string, args: unknown): ReadCall | undefined => {
21
+ if (name !== 'read' || typeof args !== 'object' || args === null) return undefined
22
+ const {path} = args as {path?: unknown}
23
+ const offset = asNumber((args as {offset?: unknown}).offset)
24
+ const limit = asNumber((args as {limit?: unknown}).limit)
25
+
26
+ if (typeof path !== 'string') return undefined
27
+ const from = offset !== undefined && offset >= 1 ? Math.floor(offset) : 1
28
+ // pi's read stops at its line cap, so a read with no limit reaches that far, not the end.
29
+ const lines = limit !== undefined && limit > 0 ? Math.floor(limit) : DEFAULT_MAX_LINES
30
+ return {path, from, to: from + lines - 1}
31
+ }
32
+
33
+ // What the read actually returned. An error or an over-long first line returns no lines, and pi
34
+ // cuts a read at its byte cap, so the lines can fall short of those asked for.
35
+ const readEnd = (call: ReadCall, result: unknown, isError: boolean): ReadCall | undefined => {
36
+ if (isError) return undefined
37
+ const truncation = (result as {details?: {truncation?: {outputLines?: unknown}}} | undefined)
38
+ ?.details?.truncation
39
+ const lines = truncation?.outputLines
40
+
41
+ if (typeof lines !== 'number') return call
42
+ if (lines < 1) return undefined
43
+ return {...call, to: Math.min(call.to, call.from + lines - 1)}
44
+ }
45
+
46
+ const span = ({from, to}: ReadCall): string => `${from}-${to}`
47
+
48
+ const createVisited = (): Visited => {
49
+ const spans = new Map<string, Set<string>>()
50
+ const pending = new Map<string, ReadCall>()
51
+
52
+ const add = (call: ReadCall): void => {
53
+ const known = spans.get(call.path) ?? new Set<string>()
54
+ known.add(span(call))
55
+ spans.set(call.path, known)
56
+ }
57
+
58
+ // A read counts once it returns. One that never came back read nothing.
59
+ return {
60
+ onEvent: event => {
61
+ if (event.type === 'tool_execution_start') {
62
+ const call = readCall(event.toolName, event.args)
63
+ if (call !== undefined) pending.set(event.toolCallId, call)
64
+ }
65
+
66
+ if (event.type !== 'tool_execution_end') return
67
+ const call = pending.get(event.toolCallId)
68
+ pending.delete(event.toolCallId)
69
+ const actual =
70
+ call === undefined ? undefined : readEnd(call, event.result, event.isError)
71
+ if (actual !== undefined) add(actual)
72
+ },
73
+ dispose: noop,
74
+ list: () => {
75
+ if (spans.size === 0) return ''
76
+ const shown = [...spans].slice(0, shownPaths)
77
+ const rest = spans.size - shown.length
78
+ const paths = shown.map(([path, lines]) => `${path} (lines ${[...lines].join(', ')})`)
79
+ return (
80
+ ` Its reads, gone with it: ${paths.join(', ')}`
81
+ + (rest > 0 ? `, and ${rest} more` : '')
82
+ + '.'
83
+ )
84
+ }
85
+ }
86
+ }
87
+
88
+ export {createVisited, readCall, readEnd}
89
+ export type {ReadCall, Visited}
@@ -0,0 +1,81 @@
1
+ import {spawn} from 'node:child_process'
2
+ import type {ChildProcess} from 'node:child_process'
3
+ import {existsSync, realpathSync, statSync} from 'node:fs'
4
+ import {delimiter, isAbsolute, join} from 'node:path'
5
+
6
+ // pi falls back the same way when SystemRoot is unset.
7
+ const system32 = join(process.env.SystemRoot ?? 'C:\\Windows', 'System32')
8
+ // Git for Windows puts GNU tar on PATH, which reads C:\ as a remote host. System32 has bsdtar.
9
+ const tar = process.platform === 'win32' ? join(system32, 'tar.exe') : 'tar'
10
+ const notFound = (command: string): string => `${command} was not found`
11
+
12
+ // A spawn in a folder that is gone fails with ENOENT too, and that is not a missing command.
13
+ const missing = (command: string, error: unknown, cwd?: string): unknown =>
14
+ isNotFound(error) && (cwd === undefined || existsSync(cwd)) ?
15
+ new Error(notFound(command))
16
+ : error
17
+
18
+ const isNotFound = (error: unknown): boolean =>
19
+ error instanceof Error && 'code' in error && error.code === 'ENOENT'
20
+
21
+ // An offline share or a folder the user may not list throws; Windows skips it, so this does too.
22
+ const isFile = (path: string): boolean => {
23
+ try {
24
+ return statSync(path, {throwIfNoEntry: false})?.isFile() === true
25
+ } catch {
26
+ return false
27
+ }
28
+ }
29
+
30
+ // On Windows which, libuv and cmd.exe search the current folder first, so a repo's own copy would run.
31
+ const onPath = (name: string, runnable = process.env.PATHEXT ?? '.COM;.EXE;.BAT;.CMD'): string => {
32
+ if (process.platform !== 'win32' || isAbsolute(name)) return name
33
+
34
+ // Windows allows a quoted PATH entry, and which reads it the same way.
35
+ const dirs = (process.env.PATH ?? '')
36
+ .split(delimiter)
37
+ .map(dir => dir.replace(/^"(.*)"$/, '$1'))
38
+ .filter(dir => isAbsolute(dir))
39
+ // An empty PATHEXT entry would match Node's extensionless npm shell script.
40
+ const extensions = runnable.split(delimiter).filter(extension => extension !== '')
41
+ const found = dirs
42
+ .flatMap(dir => extensions.map(extension => join(dir, name + extension)))
43
+ .find(isFile)
44
+
45
+ if (found === undefined) throw Object.assign(new Error(notFound(name)), {code: 'ENOENT'})
46
+ return found
47
+ }
48
+
49
+ // cmd.exe looks for a bare command, like the node an upgraded npm.cmd calls, in the current folder first.
50
+ const childEnv = (): NodeJS.ProcessEnv => ({
51
+ ...process.env,
52
+ NoDefaultCurrentDirectoryInExePath: '1'
53
+ })
54
+
55
+ // cross-spawn runs npm.cmd under cmd.exe, and killing cmd.exe alone leaves npm running.
56
+ const stop = (child: ChildProcess): void => {
57
+ // An exited child's PID may already belong to another process tree.
58
+ if (child.exitCode !== null || child.signalCode !== null) return
59
+
60
+ if (process.platform !== 'win32' || child.pid === undefined) {
61
+ child.kill()
62
+ return
63
+ }
64
+
65
+ spawn(join(system32, 'taskkill.exe'), ['/F', '/T', '/PID', String(child.pid)], {
66
+ stdio: 'ignore'
67
+ })
68
+ .once('error', () => child.kill())
69
+ .once('exit', code => code === 0 || child.kill())
70
+ }
71
+
72
+ // Native, as TypeScript resolves on Windows, falling back where native throws, as TypeScript does.
73
+ const realpath = (path: string): string => {
74
+ try {
75
+ return realpathSync.native(path)
76
+ } catch {
77
+ return realpathSync(path)
78
+ }
79
+ }
80
+
81
+ export {childEnv, missing, onPath, realpath, stop, tar}
@@ -0,0 +1,34 @@
1
+ import type {SessionStats} from '@earendil-works/pi-coding-agent'
2
+ import type {AssistantMessage} from '@earendil-works/pi-ai'
3
+
4
+ type SubagentDetails = SessionStats
5
+ & Pick<AssistantMessage, 'model' | 'provider' | 'stopReason' | 'timestamp'> & {
6
+ task: string
7
+ lastAssistantText: string
8
+ elapsedMs: number
9
+ restarts: number
10
+ }
11
+
12
+ type SubagentProgress =
13
+ | {type: 'queued'}
14
+ | {type: 'started'}
15
+ | {type: 'turn'; text: string; details: SubagentDetails}
16
+ | {type: 'restarting'; guard: string}
17
+
18
+ type SubagentUpdate = ((event: SubagentProgress) => void) | undefined
19
+
20
+ const progressLabel = (event: SubagentProgress): string => {
21
+ switch (event.type) {
22
+ case 'queued':
23
+ return 'queued…'
24
+ case 'started':
25
+ return ''
26
+ case 'turn':
27
+ return event.text
28
+ case 'restarting':
29
+ return `restarting: ${event.guard}`
30
+ }
31
+ }
32
+
33
+ export {progressLabel}
34
+ export type {SubagentDetails, SubagentProgress, SubagentUpdate}
@@ -0,0 +1,42 @@
1
+ type Slots = {
2
+ setCap: (limit: number) => void
3
+ run: <T>(fn: () => Promise<T>, onWait: () => void) => Promise<T>
4
+ }
5
+
6
+ const createSlots = (): Slots => {
7
+ let cap = Number.POSITIVE_INFINITY
8
+ let active = 0
9
+ const queue: Array<() => void> = []
10
+
11
+ const drain = (): void => {
12
+ while (active < cap) {
13
+ const start = queue.shift()
14
+ if (start === undefined) return
15
+ active += 1
16
+ start()
17
+ }
18
+ }
19
+
20
+ const release = (): void => {
21
+ active -= 1
22
+ drain()
23
+ }
24
+
25
+ return {
26
+ setCap: limit => {
27
+ cap = limit
28
+ drain()
29
+ },
30
+ run: (fn, onWait) =>
31
+ new Promise((resolve, reject) => {
32
+ queue.push(() => void fn().then(resolve, reject).finally(release))
33
+ if (active >= cap) onWait()
34
+ drain()
35
+ })
36
+ }
37
+ }
38
+
39
+ // One gate for every subagent run, so a local model server sees at most `cap` runs at once.
40
+ const slots = createSlots()
41
+
42
+ export {createSlots, slots}