@nanoverflow/spia 0.0.0-stage → 1.0.1

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 (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +156 -2
  3. package/package.json +31 -5
  4. package/spia.ts +218 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 nanoverflow
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,157 @@
1
- # Temporary Holding Version
1
+ # spia
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
+ **Brain & Hands model routing for [pi](https://pi.dev) coding agent.**
4
+
5
+ English | [中文](#中文)
6
+
7
+ The main model is the **brain**: it stays in the driver's seat of the main loop and never downgrades — prompt cache stays warm for the whole session and reasoning quality never drops. Mechanical work goes to **hands**: a `delegate` tool spawns cheap-model subagents in isolated pi processes with their own context windows, then reports back.
8
+
9
+ ## How it works
10
+
11
+ ```
12
+ you
13
+ │
14
+ ┌───────▼────────────────────────┐
15
+ │ Brain (strong model) │ thinking, decisions, plans,
16
+ │ prompt cache always warm │ verifying worker output
17
+ └───────┬────────────────────────┘
18
+ │ delegate(task) ┌────────────────────────┐
19
+ ├────────────────────────▶│ Hands (cheap subagent) │ bulk rewrites, boilerplate,
20
+ │◀────── result report ───│ isolated process/ctx │ batch retrieval, migrations
21
+ │ └────────────────────────┘
22
+ ```
23
+
24
+ - **The brain never downgrades**: every main-loop request routes to the strong model — zero cache misses, stable reasoning quality
25
+ - **Mechanical work is outsourced**: a `delegate` tool dispatches self-contained mechanical tasks to a cheap-model worker (the worker has read/edit/write/bash tools and runs in this repository's working tree)
26
+ - **Isolated context**: the worker is a separate pi process and cannot see the main conversation; the task description must carry everything it needs
27
+ - **Live progress**: worker activity streams back in real time; the final report (with cost) returns to the brain
28
+ - **Background requests**: compaction summaries always go to the cheap model
29
+ - **Manual override**: `/spia:plan` / `/spia:build` can still pin the main-loop model
30
+
31
+ ## Install
32
+
33
+ ```bash
34
+ # Option 1: git (recommended)
35
+ pi install git:github.com/nanoverflow/spia
36
+
37
+ # Option 2: npm
38
+ pi install npm:@nanoverflow/spia
39
+
40
+ # Option 3: try once without touching settings
41
+ pi -e git:github.com/nanoverflow/spia
42
+
43
+ # Option 4: copy spia.ts manually into
44
+ # ~/.pi/agent/extensions/ (global)
45
+ # .pi/extensions/ (project-local)
46
+ ```
47
+
48
+ Restart pi or run `/reload` afterwards.
49
+
50
+ ## Usage
51
+
52
+ ```
53
+ /model # pick spia/auto
54
+ ```
55
+
56
+ Then just work normally — the brain delegates when appropriate. You can also say explicitly: "use delegate to hand X to a worker".
57
+
58
+ | Command | Effect |
59
+ |---|---|
60
+ | `/spia:plan` | main loop on the strong model (brain mode, default) |
61
+ | `/spia:build` | pin the main loop to the cheap model (money-saving mode) |
62
+
63
+ ## Configuration
64
+
65
+ Override the model pair via environment variables (format `provider/model`; model IDs must match what `/model` shows):
66
+
67
+ ```bash
68
+ export PI_SPIA_PLANNER=zai-coding-cn/glm-5.4 # brain
69
+ export PI_SPIA_EXECUTOR=deepseek/deepseek-flash # hands
70
+ export PI_SPIA_WORKER_THINKING=high # worker default thinking level
71
+ export PI_SPIA_MAX_WORKER_CHARS=30000 # delegate result truncation
72
+ ```
73
+
74
+ Defaults can also be edited at the top of `spia.ts`.
75
+
76
+ ### Subagent thinking level
77
+
78
+ The worker's thinking level is controlled on two layers:
79
+
80
+ 1. **Global default**: `PI_SPIA_WORKER_THINKING` (one of `off` / `minimal` / `low` / `medium` / `high` / `xhigh` / `max`, default `high`) — the brain can lower it per call;
81
+ 2. **Per-call override**: the brain can pass a `thinking` parameter to `delegate` — lower it (e.g. `low` / `off`) for trivial bulk work to save tokens.
82
+
83
+ ## Model pair ideas
84
+
85
+ | Brain (strong) | Hands (cheap) | Notes |
86
+ |---|---|---|
87
+ | `zai-coding-cn/glm-5.4` | `zai-coding-cn/glm-5.3-flash` | default |
88
+ | `deepseek/deepseek-v4-pro` | `deepseek/deepseek-flash` | example |
89
+ | `opencode-go/kimi-k3` | `opencode-go/glm-5.3-flash` | same-provider mix |
90
+
91
+ ## FAQ
92
+
93
+ **Why does the brain never downgrade?**
94
+ Switching physical models busts the prompt cache and re-bills the whole context. Keeping the brain on one strong model = warm cache + stable decision quality. This is the key difference from "plan-then-switch" routers: spia doesn't save money on the main loop, it spends small money in isolated outsourced contexts.
95
+
96
+ **Can the worker see the conversation?**
97
+ No. It runs in a separate process with its own context and only knows what you put in `task`. Write exact file paths, requirements, and acceptance criteria — the brain's system-prompt guidelines remind it of this.
98
+
99
+ **Will delegate be overused?**
100
+ The tool's prompt guidelines tell the model: design decisions, subtle debugging, and anything needing conversation context stay with the brain; only bulk mechanical work is outsourced; and the brain must verify the worker's diff itself.
101
+
102
+ **Security note**
103
+ The worker process has full tool permissions (file read/write, shell), same as the main agent. Make sure you trust the task being run; project trust applies as usual.
104
+
105
+ ## 中文
106
+
107
+ English | [中文](#中文)
108
+
109
+ **pi 编码代理的"大脑 + 双手"模型分工。**
110
+
111
+ 主模型是**大脑**:主循环永远路由到强模型,从不降级——prompt cache 整个会话保持温热,推理质量不打折。机械活交给**双手**:`delegate` 工具把任务派给便宜模型的子代理(独立 pi 进程、独立上下文窗口),完成后把结果报告回传。
112
+
113
+ ### 工作方式
114
+
115
+ - **大脑不降级**:主循环每个请求都路由到强模型,零 cache miss
116
+ - **机械活外包**:worker 有 read/edit/write/bash 等工具,跑在本仓库工作区
117
+ - **隔离上下文**:worker 看不到主对话,任务描述自带一切所需信息
118
+ - **进度可见**:worker 执行进度实时流式回显,最终报告(含成本)回传大脑
119
+ - **后台请求**:compaction 摘要固定走便宜模型
120
+ - **手动兜底**:`/spia:plan`(大脑模式,默认)/ `/spia:build`(省钱模式)
121
+
122
+ ### 安装
123
+
124
+ ```bash
125
+ pi install git:github.com/nanoverflow/spia # 推荐
126
+ pi install npm:@nanoverflow/spia # npm
127
+ pi -e git:github.com/nanoverflow/spia # 临时试用
128
+ ```
129
+
130
+ 安装后重启 pi 或执行 `/reload`,`/model` 选择 `spia/auto`。
131
+
132
+ ### 配置
133
+
134
+ ```bash
135
+ export PI_SPIA_PLANNER=zai-coding-cn/glm-5.4 # 大脑(provider/model 格式)
136
+ export PI_SPIA_EXECUTOR=deepseek/deepseek-flash # 双手
137
+ export PI_SPIA_WORKER_THINKING=high # worker 默认思考等级
138
+ export PI_SPIA_MAX_WORKER_CHARS=30000 # delegate 结果截断长度
139
+ ```
140
+
141
+ worker 思考等级两层控制:环境变量设全局默认(默认 `high`);大脑调用 `delegate` 时可用 `thinking` 参数单次覆盖——琐碎批量活可调低(`low`/`off`)省 token。
142
+
143
+ ### 常见模型对
144
+
145
+ | 大脑 | 双手 | 备注 |
146
+ |---|---|---|
147
+ | `zai-coding-cn/glm-5.4` | `zai-coding-cn/glm-5.3-flash` | 默认 |
148
+ | `deepseek/deepseek-v4-pro` | `deepseek/deepseek-flash` | 示例 |
149
+ | `opencode-go/kimi-k3` | `opencode-go/glm-5.3-flash` | 同 provider 混搭 |
150
+
151
+ ### 安全提示
152
+
153
+ worker 进程拥有完整工具权限(读写文件、跑命令),与主 agent 相同。`delegate` 的任务由大脑生成,请确保信任运行中的任务;项目级信任照常生效。
154
+
155
+ ## License
156
+
157
+ MIT
package/package.json CHANGED
@@ -1,6 +1,32 @@
1
1
  {
2
- "name": "@nanoverflow/spia",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@nanoverflow/spia",
3
+ "version": "1.0.1",
4
+ "description": "Brain & Hands model routing for the pi coding agent: the strong model stays in the driver's seat, mechanical work goes to cheap-model subagents",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "keywords": [
8
+ "pi",
9
+ "pi-package",
10
+ "model-routing",
11
+ "subagent",
12
+ "virtual-model"
13
+ ],
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+ssh://git@github.com/nanoverflow/spia.git"
17
+ },
18
+ "files": [
19
+ "spia.ts",
20
+ "README.md",
21
+ "LICENSE"
22
+ ],
23
+ "peerDependencies": {
24
+ "@earendil-works/pi-ai": "*",
25
+ "@earendil-works/pi-coding-agent": "*"
26
+ },
27
+ "pi": {
28
+ "extensions": [
29
+ "./spia.ts"
30
+ ]
31
+ }
32
+ }
package/spia.ts ADDED
@@ -0,0 +1,218 @@
1
+ /**
2
+ * spia - "Brain & Hands" model routing for pi.
3
+ *
4
+ * 主模型是大脑:主循环永远路由到强模型(PLANNER),从不降级——
5
+ * prompt cache 整个会话保持温热,推理质量不打折。
6
+ * 机械活交给便宜模型:注册 `delegate` 工具,把批量、机械的任务
7
+ * (大段改写、样板代码、批量检索)外包给便宜模型的子代理
8
+ * (独立 pi 进程、独立上下文窗口),结果摘要回传给大脑。
9
+ *
10
+ * Registers `spia/auto`:
11
+ * - Main loop: PLANNER (default glm-5.4) for every request. Sticky by construction.
12
+ * - `delegate` tool: spawns a worker pi process on EXECUTOR (default glm-5.3-flash),
13
+ * streams its progress, and returns the final output to the brain.
14
+ * - Direct requests (compaction summaries) go to the cheap EXECUTOR.
15
+ *
16
+ * Manual override still available:
17
+ * - /spia:plan — main loop on the strong model (default, brain mode)
18
+ * - /spia:build — pin the main loop to the cheap model (money-saving mode)
19
+ *
20
+ * Usage: /model -> spia/auto
21
+ * Env overrides (provider/model format):
22
+ * PI_SPIA_PLANNER=zai-coding-cn/glm-5.4
23
+ * PI_SPIA_EXECUTOR=zai-coding-cn/glm-5.3-flash
24
+ * PI_SPIA_WORKER_THINKING=high (worker 默认思考等级 off/minimal/low/medium/high/xhigh/max)
25
+ * PI_SPIA_MAX_WORKER_CHARS=30000 (delegate 结果截断长度,默认 30000)
26
+ */
27
+
28
+ import { spawn } from "node:child_process";
29
+ import { createInterface } from "node:readline";
30
+ import { StringEnum, type Message } from "@earendil-works/pi-ai";
31
+ import { Type } from "typebox";
32
+ import type { ExtensionAPI, ExtensionContext, ModelRouteRequest } from "@earendil-works/pi-coding-agent";
33
+
34
+ // ============================ 配置区 ============================
35
+ // 大脑(主循环,负责思考与决策)。任何机器上都可用环境变量覆盖(格式 provider/model)
36
+ const DEFAULT_PLANNER = { provider: "zai-coding-cn", id: "glm-5.4" };
37
+ // 双手(子代理 worker,负责机械性批量工作)
38
+ const DEFAULT_EXECUTOR = { provider: "zai-coding-cn", id: "glm-5.3-flash" };
39
+ // delegate 结果回传大脑前的截断长度
40
+ const MAX_WORKER_CHARS = Number.parseInt(process.env.PI_SPIA_MAX_WORKER_CHARS ?? "30000", 10) || 30000;
41
+ // worker 默认思考等级(delegate 的 thinking 参数可单次覆盖)
42
+ const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
43
+ const DEFAULT_WORKER_THINKING = (THINKING_LEVELS as readonly string[]).includes(process.env.PI_SPIA_WORKER_THINKING ?? "")
44
+ ? (process.env.PI_SPIA_WORKER_THINKING as (typeof THINKING_LEVELS)[number])
45
+ : "high";
46
+ // ================================================================
47
+
48
+ type Phase = "plan" | "build";
49
+
50
+ function parseModelSpec(spec: string | undefined, fallback: { provider: string; id: string }) {
51
+ if (!spec) return fallback;
52
+ const slash = spec.indexOf("/");
53
+ if (slash <= 0 || slash === spec.length - 1) {
54
+ throw new Error(`spia: 模型格式应为 provider/model,收到 "${spec}"`);
55
+ }
56
+ return { provider: spec.slice(0, slash), id: spec.slice(slash + 1) };
57
+ }
58
+
59
+ const PLANNER = parseModelSpec(process.env.PI_SPIA_PLANNER, DEFAULT_PLANNER);
60
+ const EXECUTOR = parseModelSpec(process.env.PI_SPIA_EXECUTOR, DEFAULT_EXECUTOR);
61
+
62
+ function resolveModel(ctx: ExtensionContext, phase: Phase) {
63
+ const target = phase === "plan" ? PLANNER : EXECUTOR;
64
+ const model = ctx.modelRegistry.find(target.provider, target.id);
65
+ if (!model) {
66
+ throw new Error(
67
+ `spia: 找不到模型 ${target.provider}/${target.id}。请用环境变量 PI_SPIA_PLANNER / PI_SPIA_EXECUTOR(provider/model 格式)指定该机器上可用的模型,或检查凭据。`,
68
+ );
69
+ }
70
+ return model;
71
+ }
72
+
73
+ const PHASE_MESSAGE_TYPE = "spia:phase";
74
+
75
+ /** messages 里最后一条 /spia:plan|build 命令写入的相位指令(没有则 undefined) */
76
+ function forcedPhase(messages: readonly Message[]): Phase | undefined {
77
+ for (let i = messages.length - 1; i >= 0; i--) {
78
+ const message = messages[i] as (typeof messages)[number] & { customType?: string; details?: { phase?: string } };
79
+ if (message.customType === PHASE_MESSAGE_TYPE) {
80
+ return message.details?.phase === "plan" || message.details?.phase === "build" ? (message.details.phase as Phase) : undefined;
81
+ }
82
+ }
83
+ return undefined;
84
+ }
85
+
86
+ interface WorkerOutcome {
87
+ text: string;
88
+ cost: number | undefined;
89
+ code: number | null;
90
+ stderrTail: string;
91
+ }
92
+
93
+ /** 起一个便宜模型的 pi 子代理 worker,跑完任务并把最终文本带回大脑 */
94
+ function runWorker(task: string, thinking: string, signal: AbortSignal | undefined): Promise<WorkerOutcome> {
95
+ const args = [
96
+ "--mode", "json", "-p", "--no-session",
97
+ "--model", `${EXECUTOR.provider}/${EXECUTOR.id}`,
98
+ "--thinking", thinking,
99
+ task,
100
+ ];
101
+ return new Promise((resolve, reject) => {
102
+ const proc = spawn("pi", args, { cwd: process.cwd(), signal, stdio: ["ignore", "pipe", "pipe"] });
103
+ let finalText = "";
104
+ let cost: number | undefined;
105
+ let stderrTail = "";
106
+ const rl = createInterface({ input: proc.stdout });
107
+ rl.on("line", (line) => {
108
+ let event: any;
109
+ try {
110
+ event = JSON.parse(line);
111
+ } catch {
112
+ return;
113
+ }
114
+ if (event.type === "agent_end" && Array.isArray(event.messages)) {
115
+ const assistant = [...event.messages].reverse().find((m: any) => m?.role === "assistant");
116
+ if (assistant) {
117
+ const content = assistant.content;
118
+ finalText =
119
+ typeof content === "string"
120
+ ? content
121
+ : Array.isArray(content)
122
+ ? content.flatMap((b: any) => (b?.type === "text" ? [b.text] : [])).join("\n")
123
+ : "";
124
+ }
125
+ }
126
+ if (event.type === "message_update" && event.usage?.cost) cost = event.usage.cost.total ?? cost;
127
+ });
128
+ proc.stderr.on("data", (chunk: Buffer) => {
129
+ stderrTail = (stderrTail + chunk.toString()).slice(-4000);
130
+ });
131
+ proc.on("error", reject);
132
+ proc.on("close", (code) => resolve({ text: finalText, cost, code, stderrTail }));
133
+ });
134
+ }
135
+
136
+ export default function (pi: ExtensionAPI) {
137
+ // 手动切换:/spia:plan(大脑,默认)、/spia:build(省钱模式,主循环用便宜模型)
138
+ pi.registerCommand("spia:plan", {
139
+ description: "spia: 主循环用强模型(大脑模式,默认)",
140
+ handler: async (_args, ctx) => {
141
+ pi.sendMessage({ customType: PHASE_MESSAGE_TYPE, content: "[spia] 主循环 → 强模型(大脑)", display: true, details: { phase: "plan" } });
142
+ ctx.ui.notify("spia → 大脑模式(强模型)", "info");
143
+ },
144
+ });
145
+ pi.registerCommand("spia:build", {
146
+ description: "spia: 主循环固定用便宜模型(省钱模式)",
147
+ handler: async (_args, ctx) => {
148
+ pi.sendMessage({ customType: PHASE_MESSAGE_TYPE, content: "[spia] 主循环 → 便宜模型(省钱)", display: true, details: { phase: "build" } });
149
+ ctx.ui.notify("spia → 省钱模式(主循环用便宜模型)", "info");
150
+ },
151
+ });
152
+
153
+ // 子代理工具:大脑把机械活外包给便宜模型
154
+ pi.registerTool({
155
+ name: "delegate",
156
+ label: "Delegate (cheap worker)",
157
+ description:
158
+ "Delegate mechanical, self-contained work to a cheap-model worker agent running in an isolated pi process. " +
159
+ "The worker cannot see this conversation; it only knows the task you write. " +
160
+ "Returns the worker's final report text.",
161
+ promptSnippet: "Delegate bulk mechanical tasks to a cheap worker agent",
162
+ promptGuidelines: [
163
+ "Use `delegate` for mechanical bulk work: large multi-file rewrites, boilerplate generation, mass file reading/summarizing, repetitive formatting or migrations.",
164
+ "Write self-contained `task` descriptions: exact file paths, what to change, constraints, and acceptance criteria. The worker has tools (read/edit/write/bash/grep) and runs in this repository.",
165
+ "Do NOT use `delegate` for design decisions, subtle debugging, or anything requiring conversation context — do that yourself.",
166
+ "After the worker finishes, verify its diff yourself before reporting done.",
167
+ ],
168
+ parameters: Type.Object({
169
+ task: Type.String({ description: "Self-contained instructions for the worker, including exact file paths and acceptance criteria." }),
170
+ thinking: Type.Optional(
171
+ StringEnum(THINKING_LEVELS, {
172
+ description: `Worker thinking level. Omit for default (${DEFAULT_WORKER_THINKING}); lower it (e.g. "low" or "off") for trivial bulk work to save tokens.`,
173
+ }),
174
+ ),
175
+ }),
176
+ async execute(_toolCallId, params, signal, onUpdate) {
177
+ const thinking = params.thinking ?? DEFAULT_WORKER_THINKING;
178
+ onUpdate?.({ content: [{ type: "text", text: `worker(${EXECUTOR.id}, thinking:${thinking}) 启动: ${params.task.slice(0, 120)}` }], details: { status: "running" } });
179
+ let outcome: WorkerOutcome;
180
+ try {
181
+ outcome = await runWorker(params.task, thinking, signal);
182
+ } catch (err) {
183
+ const aborted = signal?.aborted ?? false;
184
+ return {
185
+ content: [{ type: "text", text: aborted ? "worker 已取消。" : `worker 启动失败: ${err instanceof Error ? err.message : String(err)}` }],
186
+ details: { status: aborted ? "aborted" : "failed" },
187
+ };
188
+ }
189
+ const failed = outcome.code !== 0 && !outcome.text;
190
+ const costLine = outcome.cost != null ? `\n(worker cost: $${outcome.cost.toFixed(4)})` : "";
191
+ const truncated = outcome.text.length > MAX_WORKER_CHARS ? `${outcome.text.slice(0, MAX_WORKER_CHARS)}\n…[已截断 ${outcome.text.length - MAX_WORKER_CHARS} 字符]` : outcome.text;
192
+ const body = failed
193
+ ? `worker 失败 (exit ${outcome.code})。\n${outcome.stderrTail}`
194
+ : truncated || "(worker 无文本输出,请自行检查工作区)";
195
+ return {
196
+ content: [{ type: "text", text: body + costLine }],
197
+ details: { status: failed ? "failed" : "done", cost: outcome.cost },
198
+ };
199
+ },
200
+ });
201
+
202
+ // 虚拟模型:主循环永远 = 大脑(强模型);省钱模式或后台请求用便宜模型
203
+ pi.registerVirtualModel<{ phase: Phase }>({
204
+ provider: "spia",
205
+ id: "auto",
206
+ name: "spia (brain)",
207
+ thinkingLevels: ["off", "low", "medium", "high"],
208
+ route(request, ctx) {
209
+ // 压缩摘要等后台请求:固定便宜模型(无状态)
210
+ if (request.reason === "direct") {
211
+ return { model: resolveModel(ctx, "build"), thinkingLevel: request.thinkingLevel };
212
+ }
213
+ // 大脑模式:默认永远强模型;/spia:build 显式省钱才降级。sticky by construction,cache 永不 miss
214
+ const phase = forcedPhase(request.messages) ?? "plan";
215
+ return { model: resolveModel(ctx, phase), thinkingLevel: request.thinkingLevel, state: { phase } };
216
+ },
217
+ });
218
+ }