@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
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Edgars Mjasnikovs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,117 @@
1
- # Temporary Holding Version
1
+ <div align="center">
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ ![pi-nop. Your daily driver. Minimal, read-only, guarded. Files, a web page and npm docs go into a guarded subagent. One answer goes back to pi.](https://raw.githubusercontent.com/mjasnikovs/pi-nop/master/assets/hero.svg)
4
+
5
+ # pi-nop
6
+
7
+ **Read-only subagents for [pi](https://pi.dev): repo search, web fetch, npm package docs, web
8
+ search, and a `/plan` panel.**
9
+
10
+ [![npm](https://img.shields.io/npm/v/@mjasnikovs/pi-nop?color=cb3837&logo=npm)](https://www.npmjs.com/package/@mjasnikovs/pi-nop)
11
+ [![license](https://img.shields.io/badge/license-MIT-blue.svg)](#license)
12
+ [![pi extension](https://img.shields.io/badge/pi-extension-7c3aed)](https://pi.dev/packages)
13
+ [![types](https://img.shields.io/badge/TypeScript-strict-3178c6?logo=typescript&logoColor=white)](#development)
14
+
15
+ </div>
16
+
17
+ ## What it does
18
+
19
+ When pi reads a big file, a web page or a package's types, all of that text stays in its
20
+ context. pi-nop hands the reading to a subagent with its own session. Only the answer comes back.
21
+
22
+ No subagent can edit, write or run commands. Each tool can use its own model, so a small local
23
+ model can do the reading. Guards stop a run that loops or stalls and start it again. Tested on
24
+ Gemma 12B and Qwen 3.8.
25
+
26
+ ## Install
27
+
28
+ ```bash
29
+ pi install npm:@mjasnikovs/pi-nop
30
+ ```
31
+
32
+ Needs pi 1.6.0 or later. `subagent-docs` needs `npm` on PATH, and `tar` too outside Windows.
33
+ Windows 10 1803 and Server 2019 or later ship the `tar.exe` it uses. `subagent-fetch` needs
34
+ `pdftotext` from poppler 26.05.0 or later on PATH for PDF pages.
35
+
36
+ ## Tools
37
+
38
+ The main agent calls these on its own. Name a tool in your prompt to make it use one.
39
+
40
+ | Tool | What it returns |
41
+ |---|---|
42
+ | `subagent` | Findings from reading many files, not the files. It uses read, grep, find and ls. |
43
+ | `subagent-fetch` | What a query asks for from one web page, not the page. |
44
+ | `subagent-docs` | An answer from an npm package's types and README, with the latest version. Reads the installed copy, or downloads one. |
45
+ | `web-search` | Up to 10 results with title, URL and snippet. `exa` and `ddg` need no key. `brave` needs `BRAVE_SEARCH_API_KEY`. |
46
+
47
+ A page or package has to fit in 75% of the subagent model's context window. A bigger one fails
48
+ the call. On a small local model, pick a model with a larger window for `subagent-fetch` and
49
+ `subagent-docs`.
50
+
51
+ ## Plan
52
+
53
+ `/plan [request]` opens a panel with four steps. It needs the interactive UI. Plain `/plan`
54
+ reopens the current plan. `/plan` with text starts a new one and drops the current one.
55
+
56
+ 1. Goal. The subagent writes one `GOAL:` line. Type to change it, or accept it.
57
+ 2. Questions. It asks one at a time. Pick an option or type your own answer.
58
+ 3. Steps. It writes the steps, the files to touch and the test commands. Type a change, or pick
59
+ "Edit plan" to change it by hand.
60
+ 4. Hand over. "Send to main context" sends the plan to the main agent.
61
+
62
+ After hand over the footer shows `plan: files 3/4 · outside 1`. That's 3 of 4 plan files written,
63
+ and 1 file written outside the plan. Run `/plan` again to see which steps are done.
64
+
65
+ ## Config
66
+
67
+ `/nop-config` opens the panel. The file is `~/.pi/agent/pi-nop.json`.
68
+
69
+ | Key | Values | Default | Meaning |
70
+ |---|---|---|---|
71
+ | `subagent`, `subagent-fetch`, `subagent-docs` | `{model, thinkingLevel}` | pi's current one | Model per tool. `/plan` uses the `subagent` one. |
72
+ | `web-search.engine` | `exa`, `brave`, `ddg` | `exa` | Search engine. |
73
+ | `concurrency` | 1 to 4 | unlimited | Subagents running at once. |
74
+ | `staleMinutes` | `off`, 5, 10, 20, 30 | 10 | Kill a run when the model sends nothing this long. |
75
+ | `toolCallMinutes` | `off`, 5, 10, 15, 30 | 15 | Kill a run when one tool call takes this long. |
76
+ | `restarts` | 0 to 3 | 2 | How many times a killed run goes again. Also how often `/plan` sends a bad answer back. |
77
+
78
+ ```json
79
+ {
80
+ "subagent": {"model": "llama-server/qwen3.8", "thinkingLevel": "low"},
81
+ "web-search": {"engine": "ddg"},
82
+ "restarts": 1
83
+ }
84
+ ```
85
+
86
+ `model` is `provider/id`, as pi lists it. `thinkingLevel` is `off`, `minimal`, `low`, `medium`,
87
+ `high`, `xhigh` or `max`. One unknown key or bad value makes pi-nop ignore the whole file, with a
88
+ warning. A model pi no longer lists falls back to pi's current one, with a warning.
89
+
90
+ `PI_NOP_SEARCH_ENGINE` overrides the engine. `PI_NOP_SEARCH_ENDPOINT` overrides its URL.
91
+
92
+ ### Guards
93
+
94
+ A guard that trips kills the run and starts it again with a note. Past `restarts` the run fails.
95
+
96
+ | Guard | Trips on |
97
+ |---|---|
98
+ | loop | The same tool call five times in twenty, or one file re-read five times with no new lines. |
99
+ | stale | No output for `staleMinutes`. The clock pauses while a tool runs. |
100
+ | tool-call | One tool call past `toolCallMinutes`. |
101
+ | ground | Eight tool calls in a row that repeat or fail. |
102
+ | churn | Tool results past twice the context window. |
103
+ | leak | Tool call markup in the final answer. |
104
+ | repeat | The same block of lines eight times in a row. One line alone does not count. |
105
+ | circle | Two sentences said eight times each in one thinking block. |
106
+
107
+ ## Development
108
+
109
+ ```bash
110
+ bun install
111
+ bun run test
112
+ npm run lint
113
+ ```
114
+
115
+ ## License
116
+
117
+ [MIT](./LICENSE) © Edgars Mjasnikovs
package/package.json CHANGED
@@ -1,6 +1,88 @@
1
1
  {
2
- "name": "@mjasnikovs/pi-nop",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@mjasnikovs/pi-nop",
3
+ "version": "0.1.2",
4
+ "description": "Read-only subagents for pi: repo search, web fetch, npm package docs, web search, and a /plan panel.",
5
+ "keywords": [
6
+ "pi-package",
7
+ "pi",
8
+ "pi-extension",
9
+ "pi-coding-agent",
10
+ "pi.dev",
11
+ "coding-agent",
12
+ "ai-agent",
13
+ "agent",
14
+ "subagent",
15
+ "read-only",
16
+ "local-llm",
17
+ "llm",
18
+ "llama-server",
19
+ "web-search",
20
+ "web-fetch",
21
+ "npm-docs",
22
+ "planning"
23
+ ],
24
+ "license": "MIT",
25
+ "author": "Edgars Mjasnikovs",
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "git+https://github.com/mjasnikovs/pi-nop.git"
29
+ },
30
+ "homepage": "https://github.com/mjasnikovs/pi-nop#readme",
31
+ "bugs": {
32
+ "url": "https://github.com/mjasnikovs/pi-nop/issues"
33
+ },
34
+ "type": "module",
35
+ "module": "./src/index.ts",
36
+ "files": [
37
+ "src",
38
+ "README.md",
39
+ "LICENSE"
40
+ ],
41
+ "scripts": {
42
+ "test": "bun test --isolate",
43
+ "lint": "prettier --log-level warn --write \"{src,test,eval}/**/*.ts\" && eslint --fix . && tsc --noEmit",
44
+ "lint:check": "prettier --check \"{src,test,eval}/**/*.ts\" && eslint . --max-warnings 0 && tsc --noEmit",
45
+ "eval": "bun eval/fetch.eval.ts",
46
+ "eval:search": "bun eval/search.eval.ts",
47
+ "eval:docs": "bun eval/docs.eval.ts"
48
+ },
49
+ "dependencies": {
50
+ "@mozilla/readability": "0.6.0",
51
+ "cross-spawn": "7.0.6",
52
+ "linkedom": "0.18.13",
53
+ "turndown": "7.2.4",
54
+ "turndown-plugin-gfm": "1.0.2",
55
+ "typescript": "6.0.3"
56
+ },
57
+ "devDependencies": {
58
+ "@earendil-works/pi-agent-core": "1.0.0",
59
+ "@earendil-works/pi-ai": "1.0.0",
60
+ "@earendil-works/pi-coding-agent": "1.0.0",
61
+ "@earendil-works/pi-tui": "1.0.0",
62
+ "@eslint/js": "10.0.1",
63
+ "@stylistic/eslint-plugin": "5.10.0",
64
+ "@types/bun": "1.4.2",
65
+ "@types/cross-spawn": "6.0.6",
66
+ "@types/turndown": "5.0.6",
67
+ "eslint": "10.11.0",
68
+ "eslint-config-prettier": "10.1.8",
69
+ "globals": "17.12.0",
70
+ "jiti": "2.7.0",
71
+ "prettier": "3.9.8",
72
+ "typebox": "1.3.27",
73
+ "typescript-eslint": "8.70.0"
74
+ },
75
+ "peerDependencies": {
76
+ "@earendil-works/pi-agent-core": "*",
77
+ "@earendil-works/pi-ai": "*",
78
+ "@earendil-works/pi-coding-agent": "*",
79
+ "@earendil-works/pi-tui": "*",
80
+ "typebox": "*"
81
+ },
82
+ "pi": {
83
+ "extensions": [
84
+ "./src/index.ts"
85
+ ],
86
+ "image": "https://raw.githubusercontent.com/mjasnikovs/pi-nop/master/assets/hero.png"
87
+ }
88
+ }
@@ -0,0 +1,29 @@
1
+ import type {Component} from '@earendil-works/pi-tui'
2
+ import {truncateToWidth, visibleWidth} from '@earendil-works/pi-tui'
3
+
4
+ type Paint = (text: string) => string
5
+ type Focusable = Component & {handleInput(data: string): void}
6
+
7
+ const edges = 4
8
+ const frameRows = 3
9
+
10
+ const boxed = (child: Focusable, title: string, border: Paint, accent: Paint): Focusable => ({
11
+ render: width => {
12
+ const inner = width - edges
13
+ const tag = ` ${title} `
14
+ const top =
15
+ border('╭─')
16
+ + accent(tag)
17
+ + border('─'.repeat(Math.max(0, width - 3 - visibleWidth(tag))) + '╮')
18
+ const bottom = border('╰' + '─'.repeat(width - 2) + '╯')
19
+ const row = (text: string) =>
20
+ border('│ ') + truncateToWidth(text, inner, '…', true) + border(' │')
21
+
22
+ return [top, ...['', ...child.render(inner)].map(row), bottom]
23
+ },
24
+ invalidate: () => child.invalidate(),
25
+ handleInput: data => child.handleInput(data)
26
+ })
27
+
28
+ export {boxed, frameRows}
29
+ export type {Focusable}
@@ -0,0 +1,138 @@
1
+ import type {ExtensionAPI, ExtensionCommandContext} from '@earendil-works/pi-coding-agent'
2
+ import {getSelectListTheme, getSettingsListTheme} from '@earendil-works/pi-coding-agent'
3
+ import type {SettingItem} from '@earendil-works/pi-tui'
4
+ import {SelectList, SettingsList} from '@earendil-works/pi-tui'
5
+ import {readFileSync} from 'node:fs'
6
+
7
+ import {boxed} from './box'
8
+ import {
9
+ applyChange,
10
+ inherit,
11
+ modelOf,
12
+ modelSpec,
13
+ read,
14
+ safeConfig,
15
+ saveConfig,
16
+ settings,
17
+ tools
18
+ } from './config'
19
+ import type {NopConfig, Setting} from './config'
20
+ import {gap, header, settable, skipInert} from './sections'
21
+
22
+ const maxVisible = 10
23
+ const packageJson = new URL('../../package.json', import.meta.url)
24
+ const title = (): string =>
25
+ `pi-nop v${(JSON.parse(readFileSync(packageJson, 'utf8')) as {version: string}).version}`
26
+
27
+ const modelPicker =
28
+ (options: string[]) =>
29
+ (current: string, done: (selected?: string) => void): SelectList => {
30
+ const list = new SelectList(
31
+ options.map(value => ({value, label: value})),
32
+ Math.min(options.length, maxVisible),
33
+ getSelectListTheme()
34
+ )
35
+ list.setSelectedIndex(options.indexOf(current))
36
+ list.onSelect = item => done(item.value)
37
+ list.onCancel = () => done()
38
+ return list
39
+ }
40
+
41
+ const offered = (setting: Setting): string[] => {
42
+ const levels = (setting.levels ?? []).map(String)
43
+ const fallback = String(setting.fallback)
44
+ return levels.includes(fallback) ? levels : [fallback, ...levels]
45
+ }
46
+
47
+ const row = (config: NopConfig, models: string[], setting: Setting): SettingItem => ({
48
+ id: setting.id,
49
+ label: setting.label,
50
+ description: setting.description,
51
+ currentValue: String(read(config, setting)),
52
+ ...(setting.levels === undefined ?
53
+ {submenu: modelPicker([String(setting.fallback), ...models])}
54
+ : {values: offered(setting)})
55
+ })
56
+
57
+ const sections = [...new Set(settings.map(setting => setting.section))]
58
+ const same = (text: string): string => text
59
+
60
+ const panelItems = (config: NopConfig, models: string[], paint = same): SettingItem[] =>
61
+ sections.flatMap((section, index) => [
62
+ ...(index === 0 ? [] : [gap(section)]),
63
+ header(section, paint),
64
+ ...settings
65
+ .filter(setting => setting.section === section)
66
+ .map(setting => row(config, models, setting))
67
+ ])
68
+
69
+ // An empty registry says nothing about the saved models, so they are left alone.
70
+ const dropStaleModels = (config: NopConfig, models: string[]): NopConfig =>
71
+ tools.reduce((fixed, tool) => {
72
+ if (models.length === 0) return fixed
73
+ const model = read(fixed, modelOf(tool))
74
+ return model === inherit || models.includes(model) ?
75
+ fixed
76
+ : applyChange(fixed, modelOf(tool).id, inherit)
77
+ }, config)
78
+
79
+ const availableModels = (ctx: ExtensionCommandContext): string[] =>
80
+ ctx.modelRegistry.getAvailable().map(modelSpec)
81
+
82
+ // The picker follows the session's model scope, as pi's own picker does. Staleness does not:
83
+ // the tools resolve a saved model against every available one, so a scoped-out model still runs.
84
+ const offeredModels = (ctx: ExtensionCommandContext, available: string[]): string[] => {
85
+ const scoped = ctx.scopedModels.map(entry => modelSpec(entry.model))
86
+ return scoped.length > 0 ? scoped : available
87
+ }
88
+
89
+ export default function (pi: ExtensionAPI) {
90
+ pi.registerCommand('nop-config', {
91
+ description:
92
+ 'Choose the model and thinking level for each subagent tool, the web search engine, '
93
+ + 'how many subagents run at once, and the guards that stop a stuck run',
94
+ handler: async (_args, ctx) => {
95
+ const available = availableModels(ctx)
96
+ const models = offeredModels(ctx, available)
97
+ let config = dropStaleModels(safeConfig(ctx), available)
98
+
99
+ if (ctx.mode !== 'tui') {
100
+ ctx.ui.notify(
101
+ panelItems(config, models)
102
+ .filter(settable)
103
+ .map(item => `${item.id}: ${item.currentValue}`)
104
+ .join('\n'),
105
+ 'info'
106
+ )
107
+ return
108
+ }
109
+
110
+ // Not awaited: a reload drops the overlay unsettled, and a waiting handler blocks pi.
111
+ const opened = ctx.ui.custom<undefined>(
112
+ (_tui, theme, _keybindings, done) => {
113
+ const items = panelItems(config, models, text => theme.fg('muted', text))
114
+ const list = new SettingsList(
115
+ items,
116
+ Math.min(items.length, maxVisible),
117
+ getSettingsListTheme(),
118
+ (id, value) => {
119
+ config = applyChange(config, id, value)
120
+ saveConfig(config)
121
+ },
122
+ () => done(undefined)
123
+ )
124
+ return boxed(
125
+ skipInert(list, items),
126
+ title(),
127
+ text => theme.fg('border', text),
128
+ text => theme.fg('accent', text)
129
+ )
130
+ },
131
+ {overlay: true}
132
+ )
133
+ opened.catch((failure: unknown) => ctx.ui.notify(String(failure), 'error'))
134
+ }
135
+ })
136
+ }
137
+
138
+ export {dropStaleModels, panelItems}
@@ -0,0 +1,238 @@
1
+ import {existsSync, mkdirSync, readFileSync, writeFileSync} from 'node:fs'
2
+ import {join} from 'node:path'
3
+ import type {ExtensionContext, ModelRegistry} from '@earendil-works/pi-coding-agent'
4
+ import {getAgentDir} from '@earendil-works/pi-coding-agent'
5
+ import type {ThinkingLevel} from '@earendil-works/pi-agent-core'
6
+ import type {Api, Model} from '@earendil-works/pi-ai'
7
+ import {type Static, type TSchema, Type} from 'typebox'
8
+ import Value from 'typebox/value'
9
+
10
+ const configFile = 'pi-nop.json'
11
+ const tools = ['subagent', 'subagent-fetch', 'subagent-docs'] as const
12
+ const searchTool = 'web-search'
13
+ const engines = ['exa', 'brave', 'ddg'] as const
14
+ const thinkingLevels = [
15
+ 'off',
16
+ 'minimal',
17
+ 'low',
18
+ 'medium',
19
+ 'high',
20
+ 'xhigh',
21
+ 'max'
22
+ ] as const satisfies readonly ThinkingLevel[]
23
+ const inherit = 'inherit'
24
+ const unlimited = 'unlimited'
25
+ const off = 'off'
26
+ const brokenConfig =
27
+ 'pi-nop config is broken, using the host model and thinking level. Run /nop-config to fix it.'
28
+ const missingModel = (spec: string): string =>
29
+ `pi-nop model ${spec} is not available, using the host model. Run /nop-config to pick another.`
30
+
31
+ type NopTool = (typeof tools)[number]
32
+ type EngineName = (typeof engines)[number]
33
+ type Level = string | number
34
+
35
+ // The id, split on '.', is the setting's path in the file and its row id in the panel. The
36
+ // fallback is what a reader gets when the file has no value; picking it in the panel clears the key.
37
+ type Setting = {
38
+ id: string
39
+ section: string
40
+ label: string
41
+ description?: string
42
+ levels?: readonly Level[]
43
+ fallback: Level
44
+ schema: TSchema
45
+ }
46
+
47
+ type Choice<L extends Level[], F extends Level> = Omit<Setting, 'levels' | 'schema'> & {
48
+ levels: readonly [...L]
49
+ fallback: F
50
+ }
51
+
52
+ const choice = <const L extends Level[], const F extends Level>(spec: Choice<L, F>) => ({
53
+ ...spec,
54
+ schema: Type.Enum(spec.levels)
55
+ })
56
+
57
+ const modelOf = (tool: NopTool) => ({
58
+ id: `${tool}.model`,
59
+ section: tool,
60
+ label: 'model',
61
+ fallback: inherit,
62
+ schema: Type.String()
63
+ })
64
+
65
+ const thinkingOf = (tool: NopTool) =>
66
+ choice({
67
+ id: `${tool}.thinkingLevel`,
68
+ section: tool,
69
+ label: 'thinking',
70
+ levels: thinkingLevels,
71
+ fallback: inherit
72
+ })
73
+
74
+ const engine = choice({
75
+ id: `${searchTool}.engine`,
76
+ section: searchTool,
77
+ label: 'engine',
78
+ levels: engines,
79
+ fallback: 'exa'
80
+ })
81
+
82
+ const concurrency = choice({
83
+ id: 'concurrency',
84
+ section: 'concurrency',
85
+ label: 'subagents at once',
86
+ levels: [1, 2, 3, 4],
87
+ fallback: unlimited
88
+ })
89
+
90
+ // MAGIC NUMBER: pi-task's defaults. Ten idle minutes outlasts a local model's prefill of a long
91
+ // page, fifteen covers a grep over a large tree, and a third restart stopped helping there.
92
+ const staleMinutes = choice({
93
+ id: 'staleMinutes',
94
+ section: 'guards',
95
+ label: 'no model output for',
96
+ description:
97
+ 'Kill the run when the model sends nothing for this long. Includes the time a local '
98
+ + 'model spends reading a long prompt.',
99
+ levels: [off, 5, 10, 20, 30],
100
+ fallback: 10
101
+ })
102
+
103
+ const toolCallMinutes = choice({
104
+ id: 'toolCallMinutes',
105
+ section: 'guards',
106
+ label: 'one tool call runs for',
107
+ description: 'Kill the run when a single read, grep, find or ls does not return in this time.',
108
+ levels: [off, 5, 10, 15, 30],
109
+ fallback: 15
110
+ })
111
+
112
+ const restarts = choice({
113
+ id: 'restarts',
114
+ section: 'guards',
115
+ label: 'restarts',
116
+ description:
117
+ 'How many times a run goes again: after a kill, with a hint about what went wrong, or '
118
+ + 'after /plan sends a goal or steps answer back. 0 keeps the guards, fails on the first '
119
+ + 'kill and sends nothing back.',
120
+ levels: [0, 1, 2, 3],
121
+ fallback: 2
122
+ })
123
+
124
+ const settings: Setting[] = [
125
+ ...tools.flatMap(tool => [modelOf(tool), thinkingOf(tool)]),
126
+ engine,
127
+ concurrency,
128
+ staleMinutes,
129
+ toolCallMinutes,
130
+ restarts
131
+ ]
132
+
133
+ const strict = {additionalProperties: false}
134
+ const path = (id: string): [string, string?] => id.split('.') as [string, string?]
135
+
136
+ const fileSchema = () => {
137
+ const properties: Record<string, TSchema> = {}
138
+ const nested: Record<string, Record<string, TSchema>> = {}
139
+
140
+ for (const setting of settings) {
141
+ const [head, tail] = path(setting.id)
142
+
143
+ if (tail === undefined) properties[head] = Type.Optional(setting.schema)
144
+ else {
145
+ nested[head] ??= {}
146
+ nested[head][tail] = Type.Optional(setting.schema)
147
+ }
148
+ }
149
+
150
+ for (const [head, fields] of Object.entries(nested))
151
+ properties[head] = Type.Optional(Type.Object(fields, strict))
152
+ return Type.Object(properties, strict)
153
+ }
154
+
155
+ const configSchema = fileSchema()
156
+
157
+ type NopConfig = Static<typeof configSchema>
158
+
159
+ const configPath = (): string => join(getAgentDir(), configFile)
160
+
161
+ const loadConfig = (): NopConfig =>
162
+ existsSync(configPath()) ?
163
+ Value.Parse(configSchema, JSON.parse(readFileSync(configPath(), 'utf8')))
164
+ : {}
165
+
166
+ const saveConfig = (config: NopConfig): void => {
167
+ mkdirSync(getAgentDir(), {recursive: true})
168
+ writeFileSync(configPath(), JSON.stringify(config, null, 2) + '\n')
169
+ }
170
+
171
+ const safeConfig = (ctx?: ExtensionContext): NopConfig => {
172
+ try {
173
+ return loadConfig()
174
+ } catch {
175
+ ctx?.ui.notify(brokenConfig, 'warning')
176
+ return {}
177
+ }
178
+ }
179
+
180
+ const stored = (config: NopConfig, id: string): unknown =>
181
+ id.split('.').reduce<unknown>((node, key) => (node as NopConfig | undefined)?.[key], config)
182
+
183
+ const read = <S extends Setting>(
184
+ config: NopConfig,
185
+ setting: S
186
+ ): Static<S['schema']> | S['fallback'] =>
187
+ (stored(config, setting.id) as Static<S['schema']> | undefined) ?? setting.fallback
188
+
189
+ const put = (config: NopConfig, id: string, value: unknown): NopConfig => {
190
+ const [head, tail] = path(id)
191
+ const {[head]: current, ...rest} = config
192
+ if (tail === undefined) return value === undefined ? rest : {...rest, [head]: value}
193
+
194
+ const {[tail]: _dropped, ...entry} = (current ?? {}) as NopConfig
195
+ const next = value === undefined ? entry : {...entry, [tail]: value}
196
+ return Object.keys(next).length === 0 ? rest : {...rest, [head]: next}
197
+ }
198
+
199
+ const applyChange = (config: NopConfig, id: string, value: string): NopConfig => {
200
+ const setting = settings.find(entry => entry.id === id)
201
+ if (setting === undefined) throw new Error(`Unknown setting: ${id}`)
202
+ if (value === String(setting.fallback)) return put(config, id, undefined)
203
+
204
+ const level = setting.levels?.find(entry => String(entry) === value) ?? value
205
+ return put(config, id, Value.Parse(setting.schema, level))
206
+ }
207
+
208
+ const modelSpec = (model: Model<Api>): string => `${model.provider}/${model.id}`
209
+
210
+ const findModel = (registry: ModelRegistry, spec?: string): Model<Api> | undefined =>
211
+ registry.getAvailable().find(model => modelSpec(model) === spec)
212
+
213
+ export {
214
+ applyChange,
215
+ brokenConfig,
216
+ concurrency,
217
+ engine,
218
+ engines,
219
+ findModel,
220
+ inherit,
221
+ loadConfig,
222
+ missingModel,
223
+ modelOf,
224
+ modelSpec,
225
+ off,
226
+ read,
227
+ restarts,
228
+ safeConfig,
229
+ saveConfig,
230
+ searchTool,
231
+ settings,
232
+ staleMinutes,
233
+ thinkingOf,
234
+ toolCallMinutes,
235
+ tools,
236
+ unlimited
237
+ }
238
+ export type {EngineName, NopConfig, NopTool, Setting}