@esso0428/pi-subagents 0.15.0
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.
- package/CHANGELOG.md +638 -0
- package/CONTRIBUTING.md +68 -0
- package/LICENSE +21 -0
- package/README.md +745 -0
- package/SECURITY.md +95 -0
- package/dist/agent-manager.d.ts +144 -0
- package/dist/agent-manager.js +542 -0
- package/dist/agent-runner.d.ts +212 -0
- package/dist/agent-runner.js +850 -0
- package/dist/agent-types.d.ts +67 -0
- package/dist/agent-types.js +168 -0
- package/dist/context.d.ts +12 -0
- package/dist/context.js +56 -0
- package/dist/cross-extension-rpc.d.ts +46 -0
- package/dist/cross-extension-rpc.js +76 -0
- package/dist/custom-agents.d.ts +17 -0
- package/dist/custom-agents.js +156 -0
- package/dist/default-agents.d.ts +7 -0
- package/dist/default-agents.js +122 -0
- package/dist/enabled-models.d.ts +49 -0
- package/dist/enabled-models.js +145 -0
- package/dist/env.d.ts +6 -0
- package/dist/env.js +28 -0
- package/dist/group-join.d.ts +32 -0
- package/dist/group-join.js +116 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.js +2209 -0
- package/dist/invocation-config.d.ts +22 -0
- package/dist/invocation-config.js +15 -0
- package/dist/memory.d.ts +53 -0
- package/dist/memory.js +165 -0
- package/dist/model-resolver.d.ts +19 -0
- package/dist/model-resolver.js +80 -0
- package/dist/nico-overrides.d.ts +53 -0
- package/dist/nico-overrides.js +169 -0
- package/dist/output-file.d.ts +24 -0
- package/dist/output-file.js +101 -0
- package/dist/prompts.d.ts +32 -0
- package/dist/prompts.js +73 -0
- package/dist/schedule-store.d.ts +38 -0
- package/dist/schedule-store.js +155 -0
- package/dist/schedule.d.ts +109 -0
- package/dist/schedule.js +338 -0
- package/dist/settings.d.ts +141 -0
- package/dist/settings.js +162 -0
- package/dist/skill-loader.d.ts +24 -0
- package/dist/skill-loader.js +93 -0
- package/dist/status-note.d.ts +13 -0
- package/dist/status-note.js +24 -0
- package/dist/types.d.ts +197 -0
- package/dist/types.js +5 -0
- package/dist/ui/agent-widget.d.ts +160 -0
- package/dist/ui/agent-widget.js +484 -0
- package/dist/ui/conversation-viewer.d.ts +57 -0
- package/dist/ui/conversation-viewer.js +354 -0
- package/dist/ui/fleet-list.d.ts +106 -0
- package/dist/ui/fleet-list.js +345 -0
- package/dist/ui/schedule-menu.d.ts +16 -0
- package/dist/ui/schedule-menu.js +95 -0
- package/dist/ui/viewer-keys.d.ts +20 -0
- package/dist/ui/viewer-keys.js +17 -0
- package/dist/usage.d.ts +50 -0
- package/dist/usage.js +49 -0
- package/dist/worktree.d.ts +45 -0
- package/dist/worktree.js +160 -0
- package/examples/agent-tool-description.md +42 -0
- package/package.json +56 -0
- package/src/agent-manager.ts +631 -0
- package/src/agent-runner.ts +1014 -0
- package/src/agent-types.ts +202 -0
- package/src/context.ts +58 -0
- package/src/cross-extension-rpc.ts +122 -0
- package/src/custom-agents.ts +167 -0
- package/src/default-agents.ts +126 -0
- package/src/enabled-models.ts +180 -0
- package/src/env.ts +33 -0
- package/src/group-join.ts +141 -0
- package/src/index.ts +2400 -0
- package/src/invocation-config.ts +40 -0
- package/src/memory.ts +179 -0
- package/src/model-resolver.ts +100 -0
- package/src/nico-overrides.ts +235 -0
- package/src/output-file.ts +110 -0
- package/src/prompts.ts +99 -0
- package/src/schedule-store.ts +153 -0
- package/src/schedule.ts +365 -0
- package/src/settings.ts +288 -0
- package/src/skill-loader.ts +102 -0
- package/src/status-note.ts +25 -0
- package/src/types.ts +208 -0
- package/src/ui/agent-widget.ts +566 -0
- package/src/ui/conversation-viewer.ts +362 -0
- package/src/ui/fleet-list.ts +380 -0
- package/src/ui/schedule-menu.ts +104 -0
- package/src/ui/viewer-keys.ts +39 -0
- package/src/usage.ts +60 -0
- package/src/worktree.ts +191 -0
- package/vitest.config.ts +18 -0
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { AgentConfig, IsolationMode, JoinMode, ThinkingLevel } from "./types.js";
|
|
2
|
+
|
|
3
|
+
interface AgentInvocationParams {
|
|
4
|
+
model?: string;
|
|
5
|
+
thinking?: string;
|
|
6
|
+
max_turns?: number;
|
|
7
|
+
run_in_background?: boolean;
|
|
8
|
+
inherit_context?: boolean;
|
|
9
|
+
isolated?: boolean;
|
|
10
|
+
isolation?: IsolationMode;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function resolveAgentInvocationConfig(
|
|
14
|
+
agentConfig: AgentConfig | undefined,
|
|
15
|
+
params: AgentInvocationParams,
|
|
16
|
+
): {
|
|
17
|
+
modelInput?: string;
|
|
18
|
+
modelFromParams: boolean;
|
|
19
|
+
thinking?: ThinkingLevel;
|
|
20
|
+
maxTurns?: number;
|
|
21
|
+
inheritContext: boolean;
|
|
22
|
+
runInBackground: boolean;
|
|
23
|
+
isolated: boolean;
|
|
24
|
+
isolation?: IsolationMode;
|
|
25
|
+
} {
|
|
26
|
+
return {
|
|
27
|
+
modelInput: agentConfig?.model ?? params.model,
|
|
28
|
+
modelFromParams: agentConfig?.model == null && params.model != null,
|
|
29
|
+
thinking: (agentConfig?.thinking ?? params.thinking) as ThinkingLevel | undefined,
|
|
30
|
+
maxTurns: agentConfig?.maxTurns ?? params.max_turns,
|
|
31
|
+
inheritContext: agentConfig?.inheritContext ?? params.inherit_context ?? false,
|
|
32
|
+
runInBackground: agentConfig?.runInBackground ?? params.run_in_background ?? false,
|
|
33
|
+
isolated: agentConfig?.isolated ?? params.isolated ?? false,
|
|
34
|
+
isolation: agentConfig?.isolation ?? params.isolation,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function resolveJoinMode(defaultJoinMode: JoinMode, runInBackground: boolean): JoinMode | undefined {
|
|
39
|
+
return runInBackground ? defaultJoinMode : undefined;
|
|
40
|
+
}
|
package/src/memory.ts
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* memory.ts — Persistent agent memory: per-agent memory directories that persist across sessions.
|
|
3
|
+
*
|
|
4
|
+
* Memory scopes:
|
|
5
|
+
* - "user" → getAgentDir()/agent-memory/{agent-name}/ (default ~/.pi/agent/agent-memory/, honors $PI_CODING_AGENT_DIR)
|
|
6
|
+
* - "project" → .pi/agent-memory/{agent-name}/
|
|
7
|
+
* - "local" → .pi/agent-memory-local/{agent-name}/
|
|
8
|
+
*
|
|
9
|
+
* The user scope previously hardcoded ~/.pi/agent-memory/. That legacy location
|
|
10
|
+
* is still honored (read + write) when it exists and the new location doesn't,
|
|
11
|
+
* so existing memories aren't orphaned.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { existsSync, lstatSync, mkdirSync, readFileSync } from "node:fs";
|
|
15
|
+
import { homedir } from "node:os";
|
|
16
|
+
import { join, } from "node:path";
|
|
17
|
+
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
18
|
+
import type { MemoryScope } from "./types.js";
|
|
19
|
+
|
|
20
|
+
/** Maximum lines to read from MEMORY.md */
|
|
21
|
+
const MAX_MEMORY_LINES = 200;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Returns true if a name contains characters not allowed in agent/skill names.
|
|
25
|
+
* Uses a whitelist: only alphanumeric, hyphens, underscores, and dots (no leading dot).
|
|
26
|
+
*/
|
|
27
|
+
export function isUnsafeName(name: string): boolean {
|
|
28
|
+
if (!name || name.length > 128) return true;
|
|
29
|
+
return !/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(name);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Returns true if the given path is a symlink (defense against symlink attacks).
|
|
34
|
+
*/
|
|
35
|
+
export function isSymlink(filePath: string): boolean {
|
|
36
|
+
try {
|
|
37
|
+
return lstatSync(filePath).isSymbolicLink();
|
|
38
|
+
} catch {
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Safely read a file, rejecting symlinks.
|
|
45
|
+
* Returns undefined if the file doesn't exist, is a symlink, or can't be read.
|
|
46
|
+
*/
|
|
47
|
+
export function safeReadFile(filePath: string): string | undefined {
|
|
48
|
+
if (!existsSync(filePath)) return undefined;
|
|
49
|
+
if (isSymlink(filePath)) return undefined;
|
|
50
|
+
try {
|
|
51
|
+
return readFileSync(filePath, "utf-8");
|
|
52
|
+
} catch {
|
|
53
|
+
return undefined;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Resolve the memory directory path for a given agent + scope + cwd.
|
|
59
|
+
* Throws if agentName contains path traversal characters.
|
|
60
|
+
*/
|
|
61
|
+
export function resolveMemoryDir(agentName: string, scope: MemoryScope, cwd: string): string {
|
|
62
|
+
if (isUnsafeName(agentName)) {
|
|
63
|
+
throw new Error(`Unsafe agent name for memory directory: "${agentName}"`);
|
|
64
|
+
}
|
|
65
|
+
switch (scope) {
|
|
66
|
+
case "user": {
|
|
67
|
+
const current = join(getAgentDir(), "agent-memory", agentName);
|
|
68
|
+
// Legacy location from when this path was hardcoded. Keep using it if it
|
|
69
|
+
// already holds this agent's memory and the new location hasn't been
|
|
70
|
+
// created yet — otherwise existing memories would be silently orphaned.
|
|
71
|
+
const legacy = join(homedir(), ".pi", "agent-memory", agentName);
|
|
72
|
+
if (!existsSync(current) && existsSync(legacy) && !isSymlink(legacy)) {
|
|
73
|
+
return legacy;
|
|
74
|
+
}
|
|
75
|
+
return current;
|
|
76
|
+
}
|
|
77
|
+
case "project":
|
|
78
|
+
return join(cwd, ".pi", "agent-memory", agentName);
|
|
79
|
+
case "local":
|
|
80
|
+
return join(cwd, ".pi", "agent-memory-local", agentName);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Ensure the memory directory exists, creating it if needed.
|
|
86
|
+
* Refuses to create directories if any component in the path is a symlink
|
|
87
|
+
* to prevent symlink-based directory traversal attacks.
|
|
88
|
+
*/
|
|
89
|
+
export function ensureMemoryDir(memoryDir: string): void {
|
|
90
|
+
// If the directory already exists, verify it's not a symlink
|
|
91
|
+
if (existsSync(memoryDir)) {
|
|
92
|
+
if (isSymlink(memoryDir)) {
|
|
93
|
+
throw new Error(`Refusing to use symlinked memory directory: ${memoryDir}`);
|
|
94
|
+
}
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
mkdirSync(memoryDir, { recursive: true });
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Read the first N lines of MEMORY.md from the memory directory, if it exists.
|
|
102
|
+
* Returns undefined if no MEMORY.md exists or if the path is a symlink.
|
|
103
|
+
*/
|
|
104
|
+
export function readMemoryIndex(memoryDir: string): string | undefined {
|
|
105
|
+
// Reject symlinked memory directories
|
|
106
|
+
if (isSymlink(memoryDir)) return undefined;
|
|
107
|
+
|
|
108
|
+
const memoryFile = join(memoryDir, "MEMORY.md");
|
|
109
|
+
const content = safeReadFile(memoryFile);
|
|
110
|
+
if (content === undefined) return undefined;
|
|
111
|
+
|
|
112
|
+
const lines = content.split("\n");
|
|
113
|
+
if (lines.length > MAX_MEMORY_LINES) {
|
|
114
|
+
return lines.slice(0, MAX_MEMORY_LINES).join("\n") + "\n... (truncated at 200 lines)";
|
|
115
|
+
}
|
|
116
|
+
return content;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Build the memory block to inject into the agent's system prompt.
|
|
121
|
+
* Also ensures the memory directory exists (creates it if needed).
|
|
122
|
+
*/
|
|
123
|
+
export function buildMemoryBlock(agentName: string, scope: MemoryScope, cwd: string): string {
|
|
124
|
+
const memoryDir = resolveMemoryDir(agentName, scope, cwd);
|
|
125
|
+
// Create the memory directory so the agent can immediately write to it
|
|
126
|
+
ensureMemoryDir(memoryDir);
|
|
127
|
+
|
|
128
|
+
const existingMemory = readMemoryIndex(memoryDir);
|
|
129
|
+
|
|
130
|
+
const header = `# Agent Memory
|
|
131
|
+
|
|
132
|
+
You have a persistent memory directory at: ${memoryDir}/
|
|
133
|
+
Memory scope: ${scope}
|
|
134
|
+
|
|
135
|
+
This memory persists across sessions. Use it to build up knowledge over time.`;
|
|
136
|
+
|
|
137
|
+
const memoryContent = existingMemory
|
|
138
|
+
? `\n\n## Current MEMORY.md\n${existingMemory}`
|
|
139
|
+
: `\n\nNo MEMORY.md exists yet. Create one at ${join(memoryDir, "MEMORY.md")} to start building persistent memory.`;
|
|
140
|
+
|
|
141
|
+
const instructions = `
|
|
142
|
+
|
|
143
|
+
## Memory Instructions
|
|
144
|
+
- MEMORY.md is an index file — keep it concise (under 200 lines). Lines after 200 are truncated.
|
|
145
|
+
- Store detailed memories in separate files within ${memoryDir}/ and link to them from MEMORY.md.
|
|
146
|
+
- Each memory file should use this frontmatter format:
|
|
147
|
+
\`\`\`markdown
|
|
148
|
+
---
|
|
149
|
+
name: <memory name>
|
|
150
|
+
description: <one-line description>
|
|
151
|
+
type: <user|feedback|project|reference>
|
|
152
|
+
---
|
|
153
|
+
<memory content>
|
|
154
|
+
\`\`\`
|
|
155
|
+
- Update or remove memories that become outdated. Check for existing memories before creating duplicates.
|
|
156
|
+
- You have Read, Write, and Edit tools available for managing memory files.`;
|
|
157
|
+
|
|
158
|
+
return header + memoryContent + instructions;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Build a read-only memory block for agents that lack write/edit tools.
|
|
163
|
+
* Does NOT create the memory directory — agents can only consume existing memory.
|
|
164
|
+
*/
|
|
165
|
+
export function buildReadOnlyMemoryBlock(agentName: string, scope: MemoryScope, cwd: string): string {
|
|
166
|
+
const memoryDir = resolveMemoryDir(agentName, scope, cwd);
|
|
167
|
+
const existingMemory = readMemoryIndex(memoryDir);
|
|
168
|
+
|
|
169
|
+
const header = `# Agent Memory (read-only)
|
|
170
|
+
|
|
171
|
+
Memory scope: ${scope}
|
|
172
|
+
You have read-only access to memory. You can reference existing memories but cannot create or modify them.`;
|
|
173
|
+
|
|
174
|
+
const memoryContent = existingMemory
|
|
175
|
+
? `\n\n## Current MEMORY.md\n${existingMemory}`
|
|
176
|
+
: `\n\nNo memory is available yet. Other agents or sessions with write access can create memories for you to consume.`;
|
|
177
|
+
|
|
178
|
+
return header + memoryContent;
|
|
179
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Model resolution: exact match ("provider/modelId") with fuzzy fallback.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
export interface ModelEntry {
|
|
6
|
+
id: string;
|
|
7
|
+
name: string;
|
|
8
|
+
provider: string;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface ModelRegistry {
|
|
12
|
+
find(provider: string, modelId: string): any;
|
|
13
|
+
getAll(): any[];
|
|
14
|
+
getAvailable?(): any[];
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Resolve a model string to a Model instance.
|
|
19
|
+
* Tries exact match first ("provider/modelId"), then fuzzy match against all available models.
|
|
20
|
+
* Returns the Model on success, or an error message string on failure.
|
|
21
|
+
*/
|
|
22
|
+
export function resolveModel(
|
|
23
|
+
input: string,
|
|
24
|
+
registry: ModelRegistry,
|
|
25
|
+
): any | string {
|
|
26
|
+
// Available models (those with auth configured)
|
|
27
|
+
const all = (registry.getAvailable?.() ?? registry.getAll()) as ModelEntry[];
|
|
28
|
+
const availableSet = new Set(all.map(m => `${m.provider}/${m.id}`.toLowerCase()));
|
|
29
|
+
|
|
30
|
+
// 1. Exact match: "provider/modelId" — only if available (has auth)
|
|
31
|
+
const slashIdx = input.indexOf("/");
|
|
32
|
+
if (slashIdx !== -1) {
|
|
33
|
+
const provider = input.slice(0, slashIdx);
|
|
34
|
+
const modelId = input.slice(slashIdx + 1);
|
|
35
|
+
if (availableSet.has(input.toLowerCase())) {
|
|
36
|
+
const found = registry.find(provider, modelId);
|
|
37
|
+
if (found) return found;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// 2. Fuzzy match against available models. Normalize separators so cosmetic
|
|
42
|
+
// punctuation differences still match — e.g. "claude-haiku-4.5" and
|
|
43
|
+
// "claude-haiku-4-5" (dot vs dash in the version) resolve to the same model.
|
|
44
|
+
const normalize = (s: string) => s.toLowerCase().replace(/\./g, "-");
|
|
45
|
+
const query = normalize(input);
|
|
46
|
+
|
|
47
|
+
// Score each model: prefer exact id match > id contains > name contains > provider+id contains
|
|
48
|
+
let bestMatch: ModelEntry | undefined;
|
|
49
|
+
let bestScore = 0;
|
|
50
|
+
|
|
51
|
+
for (const m of all) {
|
|
52
|
+
const id = normalize(m.id);
|
|
53
|
+
const name = normalize(m.name);
|
|
54
|
+
const full = normalize(`${m.provider}/${m.id}`);
|
|
55
|
+
|
|
56
|
+
let score = 0;
|
|
57
|
+
if (id === query || full === query) {
|
|
58
|
+
score = 100; // exact
|
|
59
|
+
} else if (id.includes(query) || full.includes(query)) {
|
|
60
|
+
score = 60 + (query.length / id.length) * 30; // substring, prefer tighter matches
|
|
61
|
+
} else if (name.includes(query)) {
|
|
62
|
+
score = 40 + (query.length / name.length) * 20;
|
|
63
|
+
} else if (
|
|
64
|
+
// A trailing date-stamp token (e.g. "20251001") is optional, so a
|
|
65
|
+
// date-pinned config like "claude-haiku-4-5-20251001" still matches an
|
|
66
|
+
// undated registry id like "claude-haiku-4-5".
|
|
67
|
+
query
|
|
68
|
+
.split(/[\s\-/]+/)
|
|
69
|
+
.every(part => /^\d{8}$/.test(part) || id.includes(part) || name.includes(part) || m.provider.toLowerCase().includes(part))
|
|
70
|
+
) {
|
|
71
|
+
score = 20; // all parts present somewhere
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
if (score > bestScore) {
|
|
75
|
+
bestScore = score;
|
|
76
|
+
bestMatch = m;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
if (bestMatch && bestScore >= 20) {
|
|
81
|
+
const found = registry.find(bestMatch.provider, bestMatch.id);
|
|
82
|
+
if (found) return found;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// 3. Provider fallback: a "provider/modelId" query that didn't match under the
|
|
86
|
+
// named provider (exact or fuzzy above) retries against all providers. The
|
|
87
|
+
// named provider is preferred when present; this only kicks in when it isn't,
|
|
88
|
+
// so the same model from another provider beats falling back to "inherit".
|
|
89
|
+
if (slashIdx !== -1) {
|
|
90
|
+
const bare = resolveModel(input.slice(slashIdx + 1), registry);
|
|
91
|
+
if (typeof bare !== "string") return bare;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// 4. No match — list available models
|
|
95
|
+
const modelList = all
|
|
96
|
+
.map(m => ` ${m.provider}/${m.id}`)
|
|
97
|
+
.sort()
|
|
98
|
+
.join("\n");
|
|
99
|
+
return `Model not found: "${input}".\n\nAvailable models:\n${modelList}`;
|
|
100
|
+
}
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* nico-overrides.ts — Read and apply agent overrides from `npm:pi-subagents`-style
|
|
3
|
+
* `settings.json` (`subagents.agentOverrides`).
|
|
4
|
+
*
|
|
5
|
+
* Priority (after `@tintinweb/pi-subagents` has resolved its own .md chain):
|
|
6
|
+
* 1. Local JSON (.pi/settings.json) ← highest
|
|
7
|
+
* 2. Global JSON (~/.pi/agent/settings.json)
|
|
8
|
+
*
|
|
9
|
+
* Overrides are applied to matching agents in the registry. If an agent name
|
|
10
|
+
* from the overrides does not exist in the registry, it is auto-registered
|
|
11
|
+
* using the override fields as the full definition (no .md file needed).
|
|
12
|
+
*
|
|
13
|
+
* Skill mapping (Nico string[] → tintinweb true | string[] | false):
|
|
14
|
+
* ["*"] → true (all skills)
|
|
15
|
+
* ["foo"] → ["foo"] (only listed)
|
|
16
|
+
* [] | false → false (none)
|
|
17
|
+
* omitted → true (all, fallback)
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
21
|
+
import { join } from "node:path";
|
|
22
|
+
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
23
|
+
import { BUILTIN_TOOL_NAMES } from "./agent-types.js";
|
|
24
|
+
import type { AgentConfig } from "./types.js";
|
|
25
|
+
|
|
26
|
+
// ============================================================================
|
|
27
|
+
// Types matching npm:pi-subagents's settings.json schema
|
|
28
|
+
// ============================================================================
|
|
29
|
+
|
|
30
|
+
export interface NicoAgentOverride {
|
|
31
|
+
model?: string | false;
|
|
32
|
+
thinking?: string | false;
|
|
33
|
+
fallbackModels?: string[];
|
|
34
|
+
systemPrompt?: string;
|
|
35
|
+
systemPromptMode?: "append" | "replace";
|
|
36
|
+
inheritProjectContext?: boolean;
|
|
37
|
+
inheritSkills?: boolean;
|
|
38
|
+
defaultContext?: "fresh" | "fork" | false;
|
|
39
|
+
disabled?: boolean;
|
|
40
|
+
skills?: string[] | false;
|
|
41
|
+
tools?: string[] | false;
|
|
42
|
+
completionGuard?: boolean;
|
|
43
|
+
toolBudget?: Record<string, unknown>;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
interface NicoSubagentsSettings {
|
|
47
|
+
defaultModel?: string;
|
|
48
|
+
disableBuiltins?: boolean;
|
|
49
|
+
disableThinking?: boolean;
|
|
50
|
+
agentOverrides?: Record<string, NicoAgentOverride>;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
interface NicoSettingsFile {
|
|
54
|
+
subagents?: NicoSubagentsSettings;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// ============================================================================
|
|
58
|
+
// Reader
|
|
59
|
+
// ============================================================================
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Read subagents.agentOverrides and subagents.defaultModel from both local
|
|
63
|
+
* and global Nico-style settings.json. Local overrides global on key collision.
|
|
64
|
+
*/
|
|
65
|
+
export function readNicoAgentOverrides(cwd: string): {
|
|
66
|
+
overrides: Record<string, NicoAgentOverride>;
|
|
67
|
+
defaultModel: string | undefined;
|
|
68
|
+
} {
|
|
69
|
+
const merged: Record<string, NicoAgentOverride> = {};
|
|
70
|
+
let defaultModel: string | undefined;
|
|
71
|
+
|
|
72
|
+
// Global: ~/.pi/agent/settings.json
|
|
73
|
+
const globalPath = join(getAgentDir(), "settings.json");
|
|
74
|
+
const globalSettings = readNicoSettingsFile(globalPath);
|
|
75
|
+
if (globalSettings) {
|
|
76
|
+
mergeOverrides(merged, globalSettings.agentOverrides);
|
|
77
|
+
if (defaultModel === undefined) defaultModel = globalSettings.defaultModel;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// Local: .pi/settings.json
|
|
81
|
+
const localPath = join(cwd, ".pi", "settings.json");
|
|
82
|
+
if (existsSync(localPath)) {
|
|
83
|
+
const localSettings = readNicoSettingsFile(localPath);
|
|
84
|
+
if (localSettings) {
|
|
85
|
+
mergeOverrides(merged, localSettings.agentOverrides);
|
|
86
|
+
if (localSettings.defaultModel !== undefined) defaultModel = localSettings.defaultModel;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
return { overrides: merged, defaultModel };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function readNicoSettingsFile(filePath: string): NicoSubagentsSettings | undefined {
|
|
94
|
+
if (!existsSync(filePath)) return undefined;
|
|
95
|
+
try {
|
|
96
|
+
const raw = JSON.parse(readFileSync(filePath, "utf-8")) as NicoSettingsFile;
|
|
97
|
+
const sub = raw?.subagents;
|
|
98
|
+
if (!sub || typeof sub !== "object") return undefined;
|
|
99
|
+
return sub;
|
|
100
|
+
} catch {
|
|
101
|
+
// Silently skip — bad Nico config must not break tintinweb
|
|
102
|
+
return undefined;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function mergeOverrides(
|
|
107
|
+
target: Record<string, NicoAgentOverride>,
|
|
108
|
+
source: Record<string, NicoAgentOverride> | undefined,
|
|
109
|
+
): void {
|
|
110
|
+
if (!source) return;
|
|
111
|
+
for (const [name, override] of Object.entries(source)) {
|
|
112
|
+
target[name] = { ...target[name], ...override };
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// ============================================================================
|
|
117
|
+
// Skill converter: Nico string[] → tintinweb true | string[] | false
|
|
118
|
+
// ============================================================================
|
|
119
|
+
|
|
120
|
+
export function resolveNicoSkills(
|
|
121
|
+
skills: string[] | false | undefined,
|
|
122
|
+
): true | string[] | false {
|
|
123
|
+
// Not set → inherit all (tintinweb default)
|
|
124
|
+
if (skills === undefined) return true;
|
|
125
|
+
|
|
126
|
+
// Explicit false / empty array → none
|
|
127
|
+
if (skills === false || skills.length === 0) return false;
|
|
128
|
+
|
|
129
|
+
// ["*"] → all skills
|
|
130
|
+
if (skills.length === 1 && skills[0] === "*") return true;
|
|
131
|
+
|
|
132
|
+
// Specific list
|
|
133
|
+
return [...skills];
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// ============================================================================
|
|
137
|
+
// Applier — override existing agent
|
|
138
|
+
// ============================================================================
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Apply a Nico-style override to an existing tintinweb AgentConfig.
|
|
142
|
+
* JSON values directly overwrite the config (highest priority).
|
|
143
|
+
*/
|
|
144
|
+
export function applyNicoOverride(
|
|
145
|
+
agent: AgentConfig,
|
|
146
|
+
override: NicoAgentOverride,
|
|
147
|
+
nicoDefaultModel?: string,
|
|
148
|
+
): AgentConfig {
|
|
149
|
+
let modified = false;
|
|
150
|
+
let next: AgentConfig = agent;
|
|
151
|
+
|
|
152
|
+
// model: explicit override wins; else use defaultModel when agent has none
|
|
153
|
+
if (override.model !== undefined) {
|
|
154
|
+
next = { ...next, model: override.model === false ? undefined : override.model };
|
|
155
|
+
modified = true;
|
|
156
|
+
} else if (nicoDefaultModel !== undefined && next.model === undefined) {
|
|
157
|
+
next = { ...next, model: nicoDefaultModel };
|
|
158
|
+
modified = true;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
if (override.thinking !== undefined) {
|
|
162
|
+
next = { ...next, thinking: override.thinking === false ? undefined : override.thinking as AgentConfig["thinking"] };
|
|
163
|
+
modified = true;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
if (override.systemPrompt !== undefined) {
|
|
167
|
+
next = { ...next, systemPrompt: override.systemPrompt };
|
|
168
|
+
modified = true;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
if (override.disabled !== undefined) {
|
|
172
|
+
next = { ...next, enabled: !override.disabled };
|
|
173
|
+
modified = true;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
if (override.tools !== undefined) {
|
|
177
|
+
next = { ...next, builtinToolNames: override.tools === false ? [] : [...override.tools] };
|
|
178
|
+
modified = true;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
return modified ? next : agent;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// ============================================================================
|
|
185
|
+
// Auto-register — create AgentConfig from override when agent doesn't exist
|
|
186
|
+
// ============================================================================
|
|
187
|
+
|
|
188
|
+
function createAgentFromOverride(
|
|
189
|
+
name: string,
|
|
190
|
+
override: NicoAgentOverride,
|
|
191
|
+
defaultModel?: string,
|
|
192
|
+
): AgentConfig {
|
|
193
|
+
return {
|
|
194
|
+
name,
|
|
195
|
+
displayName: name,
|
|
196
|
+
description: `Auto-registered from npm:pi-subagents JSON settings`,
|
|
197
|
+
builtinToolNames: override.tools !== undefined
|
|
198
|
+
? (override.tools === false ? [] : [...override.tools])
|
|
199
|
+
: [...BUILTIN_TOOL_NAMES],
|
|
200
|
+
extensions: true,
|
|
201
|
+
skills: resolveNicoSkills(override.skills),
|
|
202
|
+
model: override.model !== undefined ? (override.model === false ? undefined : override.model) : defaultModel,
|
|
203
|
+
thinking: override.thinking !== undefined
|
|
204
|
+
? (override.thinking === false ? undefined : override.thinking as AgentConfig["thinking"])
|
|
205
|
+
: undefined,
|
|
206
|
+
systemPrompt: override.systemPrompt ?? "",
|
|
207
|
+
promptMode: override.systemPromptMode === "append" ? "append" : "replace",
|
|
208
|
+
enabled: !(override.disabled ?? false),
|
|
209
|
+
source: "global",
|
|
210
|
+
isDefault: false,
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// ============================================================================
|
|
215
|
+
// Bulk apply
|
|
216
|
+
// ============================================================================
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Apply all Nico overrides to a map of agents (mutating in-place).
|
|
220
|
+
* Agents that don't exist yet are auto-registered from the override.
|
|
221
|
+
*/
|
|
222
|
+
export function applyNicoOverridesToMap(
|
|
223
|
+
agents: Map<string, AgentConfig>,
|
|
224
|
+
overrides: Record<string, NicoAgentOverride>,
|
|
225
|
+
defaultModel?: string,
|
|
226
|
+
): void {
|
|
227
|
+
for (const [name, override] of Object.entries(overrides)) {
|
|
228
|
+
const existing = agents.get(name);
|
|
229
|
+
if (existing) {
|
|
230
|
+
agents.set(name, applyNicoOverride(existing, override, defaultModel));
|
|
231
|
+
} else {
|
|
232
|
+
agents.set(name, createAgentFromOverride(name, override, defaultModel));
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* output-file.ts — Streaming JSONL output file for agent transcripts.
|
|
3
|
+
*
|
|
4
|
+
* Creates a per-agent output file that streams conversation turns as JSONL,
|
|
5
|
+
* matching Claude Code's task output file format.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { appendFileSync, chmodSync, mkdirSync, writeFileSync } from "node:fs";
|
|
9
|
+
import { tmpdir } from "node:os";
|
|
10
|
+
import { join } from "node:path";
|
|
11
|
+
import type { AgentSession, AgentSessionEvent } from "@earendil-works/pi-coding-agent";
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Encode a cwd path as a filesystem-safe directory name. Handles:
|
|
15
|
+
* - POSIX: "/home/user/project" → "home-user-project"
|
|
16
|
+
* - Windows: "C:\Users\foo\project" → "Users-foo-project"
|
|
17
|
+
* - UNC: "\\\\server\\share\\project" → "server-share-project"
|
|
18
|
+
*/
|
|
19
|
+
export function encodeCwd(cwd: string): string {
|
|
20
|
+
return cwd
|
|
21
|
+
.replace(/[/\\]/g, "-") // both separators → dash
|
|
22
|
+
.replace(/^[A-Za-z]:-/, "") // strip Windows drive prefix ("C:-")
|
|
23
|
+
.replace(/^-+/, ""); // strip leading dashes (POSIX root, UNC)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Create the output file path, ensuring the directory exists.
|
|
27
|
+
* Mirrors Claude Code's layout: /tmp/{prefix}-{uid}/{encoded-cwd}/{sessionId}/tasks/{agentId}.output */
|
|
28
|
+
export function createOutputFilePath(cwd: string, agentId: string, sessionId: string): string {
|
|
29
|
+
const encoded = encodeCwd(cwd);
|
|
30
|
+
const root = join(tmpdir(), `pi-subagents-${process.getuid?.() ?? 0}`);
|
|
31
|
+
mkdirSync(root, { recursive: true, mode: 0o700 });
|
|
32
|
+
// chmod is a no-op on Windows and throws on some Windows filesystems.
|
|
33
|
+
// On Unix we still want to enforce 0o700 past umask, so only swallow on Windows.
|
|
34
|
+
try {
|
|
35
|
+
chmodSync(root, 0o700);
|
|
36
|
+
} catch (err) {
|
|
37
|
+
if (process.platform !== "win32") throw err;
|
|
38
|
+
}
|
|
39
|
+
const dir = join(root, encoded, sessionId, "tasks");
|
|
40
|
+
mkdirSync(dir, { recursive: true });
|
|
41
|
+
return join(dir, `${agentId}.output`);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Write the initial user prompt entry. */
|
|
45
|
+
export function writeInitialEntry(path: string, agentId: string, prompt: string, cwd: string): void {
|
|
46
|
+
const entry = {
|
|
47
|
+
isSidechain: true,
|
|
48
|
+
agentId,
|
|
49
|
+
type: "user",
|
|
50
|
+
message: { role: "user", content: prompt },
|
|
51
|
+
timestamp: new Date().toISOString(),
|
|
52
|
+
cwd,
|
|
53
|
+
};
|
|
54
|
+
writeFileSync(path, JSON.stringify(entry) + "\n", "utf-8");
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Subscribe to session events and flush new messages to the output file on each turn_end.
|
|
59
|
+
* Returns a cleanup function that does a final flush and unsubscribes.
|
|
60
|
+
*/
|
|
61
|
+
export function streamToOutputFile(
|
|
62
|
+
session: AgentSession,
|
|
63
|
+
path: string,
|
|
64
|
+
agentId: string,
|
|
65
|
+
cwd: string,
|
|
66
|
+
): () => void {
|
|
67
|
+
let writtenCount = 1; // initial user prompt already written
|
|
68
|
+
|
|
69
|
+
const flush = () => {
|
|
70
|
+
const messages = session.messages;
|
|
71
|
+
while (writtenCount < messages.length) {
|
|
72
|
+
const msg = messages[writtenCount];
|
|
73
|
+
const entry = {
|
|
74
|
+
isSidechain: true,
|
|
75
|
+
agentId,
|
|
76
|
+
type: msg.role === "assistant" ? "assistant" : msg.role === "user" ? "user" : "toolResult",
|
|
77
|
+
message: msg,
|
|
78
|
+
timestamp: new Date().toISOString(),
|
|
79
|
+
cwd,
|
|
80
|
+
};
|
|
81
|
+
try {
|
|
82
|
+
appendFileSync(path, JSON.stringify(entry) + "\n", "utf-8");
|
|
83
|
+
} catch { /* ignore write errors */ }
|
|
84
|
+
writtenCount++;
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
const unsubscribe = session.subscribe((event: AgentSessionEvent) => {
|
|
89
|
+
if (event.type === "turn_end") flush();
|
|
90
|
+
// Compaction replaces session.messages with a shorter, summarized array,
|
|
91
|
+
// leaving writtenCount past the new end — without re-anchoring, the flush
|
|
92
|
+
// loop would never match again and streaming would halt for good (#145).
|
|
93
|
+
// Flush before it runs so any not-yet-flushed tail still reaches the file,
|
|
94
|
+
// then re-anchor to the rebuilt array once it lands. The re-anchor is
|
|
95
|
+
// deferred a microtask because on the overflow-retry path pi trims the
|
|
96
|
+
// trailing error assistant message AFTER emitting compaction_end —
|
|
97
|
+
// anchoring synchronously would sit one past the trimmed array and skip
|
|
98
|
+
// the first post-compaction message. Aborted/failed compactions leave
|
|
99
|
+
// session.messages untouched, so only successful ones re-anchor.
|
|
100
|
+
if (event.type === "compaction_start") flush();
|
|
101
|
+
if (event.type === "compaction_end" && !event.aborted && event.result) {
|
|
102
|
+
queueMicrotask(() => { writtenCount = session.messages.length; });
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
return () => {
|
|
107
|
+
flush();
|
|
108
|
+
unsubscribe();
|
|
109
|
+
};
|
|
110
|
+
}
|