@nredd/pi-subagents 0.0.0-stage → 0.22.0-nredd.10
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/LICENSE +21 -0
- package/README.md +1444 -2
- package/dist/chunks/chunk-MSGGFB5Q.ts +6755 -0
- package/dist/chunks/chunk-MSGGFB5Q.ts.map +7 -0
- package/dist/chunks/conversation-viewer-A7AMRDVY.ts +15 -0
- package/dist/chunks/conversation-viewer-A7AMRDVY.ts.map +7 -0
- package/dist/index.ts +9874 -0
- package/dist/index.ts.map +7 -0
- package/package.json +82 -4
- package/src/abortable.ts +43 -0
- package/src/agent-color.ts +161 -0
- package/src/agent-file-toggle.ts +298 -0
- package/src/agent-manager.ts +2431 -0
- package/src/agent-runner.ts +1703 -0
- package/src/agent-source-badge.ts +75 -0
- package/src/agent-types.ts +346 -0
- package/src/child-context.ts +33 -0
- package/src/clock.ts +25 -0
- package/src/completion-outbox.ts +144 -0
- package/src/context.ts +58 -0
- package/src/cross-extension-rpc.ts +200 -0
- package/src/custom-agents.ts +441 -0
- package/src/default-agents.ts +126 -0
- package/src/detached-results.ts +150 -0
- package/src/enabled-models.ts +181 -0
- package/src/enterprise-local.ts +67 -0
- package/src/env.ts +33 -0
- package/src/error-message.ts +11 -0
- package/src/git-path.ts +66 -0
- package/src/group-join.ts +142 -0
- package/src/home-paths.ts +27 -0
- package/src/index.ts +5047 -0
- package/src/invocation-config.ts +158 -0
- package/src/memory.ts +179 -0
- package/src/mention-clone.ts +200 -0
- package/src/mention.ts +141 -0
- package/src/model-call.ts +83 -0
- package/src/model-resolver.ts +333 -0
- package/src/model-scope.ts +71 -0
- package/src/model-selection.ts +170 -0
- package/src/model-tiers.ts +176 -0
- package/src/nested-tools.ts +512 -0
- package/src/notification-result.ts +118 -0
- package/src/output-file.ts +186 -0
- package/src/package-resources.ts +639 -0
- package/src/plan-mode-children.ts +176 -0
- package/src/process-budget.ts +346 -0
- package/src/prompts.ts +161 -0
- package/src/quota-admission.ts +121 -0
- package/src/resource-loader.ts +65 -0
- package/src/schedule-store.ts +153 -0
- package/src/schedule.ts +514 -0
- package/src/settings.ts +851 -0
- package/src/skill-loader.ts +288 -0
- package/src/stale-ctx.ts +16 -0
- package/src/startup-error.ts +29 -0
- package/src/status-note.ts +113 -0
- package/src/structured-output.ts +130 -0
- package/src/types.ts +487 -0
- package/src/ui/agent-mention.ts +219 -0
- package/src/ui/agent-row.ts +245 -0
- package/src/ui/agent-widget.ts +722 -0
- package/src/ui/conversation-viewer.ts +837 -0
- package/src/ui/fallback-flag.ts +114 -0
- package/src/ui/fleet-list.ts +1020 -0
- package/src/ui/fleet-state.ts +154 -0
- package/src/ui/notification-view.ts +139 -0
- package/src/ui/schedule-menu.ts +105 -0
- package/src/ui/select-item.ts +45 -0
- package/src/ui/viewer-keys.ts +39 -0
- package/src/ui/workflow-card.ts +459 -0
- package/src/ui/workflow-dialog.ts +1138 -0
- package/src/ui/workflow-menu.ts +193 -0
- package/src/usage.ts +167 -0
- package/src/workflow/collisions.ts +123 -0
- package/src/workflow/entry.ts +47 -0
- package/src/workflow/host.ts +398 -0
- package/src/workflow/journal.ts +176 -0
- package/src/workflow/json-schema.ts +129 -0
- package/src/workflow/meta.ts +329 -0
- package/src/workflow/progress.ts +554 -0
- package/src/workflow/runtime.ts +1249 -0
- package/src/workflow/saved.ts +259 -0
- package/src/workflow/task.ts +317 -0
- package/src/workflow/tool-description.ts +200 -0
- package/src/workflow/worker-source.ts +903 -0
- package/src/worktree.ts +520 -0
- package/src/xml.ts +13 -0
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* default-agents.ts — Embedded default agent configurations.
|
|
3
|
+
*
|
|
4
|
+
* These are always available but can be overridden by user .md files with the same name.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type { AgentConfig } from "./types.js";
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Tool surface shared by Explore and Plan. `bash` is left out because a prompt cannot
|
|
11
|
+
* make an unrestricted shell read-only, and extensions are off because extension tools
|
|
12
|
+
* can run commands or write. A `.pi/agents/<Name>.md` override can opt back in with an
|
|
13
|
+
* explicit `extensions:` list.
|
|
14
|
+
*/
|
|
15
|
+
const READ_ONLY_SURFACE: Pick<AgentConfig, "builtinToolNames" | "extensions" | "skills"> = {
|
|
16
|
+
builtinToolNames: ["read", "grep", "find", "ls"],
|
|
17
|
+
extensions: false,
|
|
18
|
+
skills: true,
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
export const DEFAULT_AGENTS: Map<string, AgentConfig> = new Map([
|
|
22
|
+
[
|
|
23
|
+
"general-purpose",
|
|
24
|
+
{
|
|
25
|
+
name: "general-purpose",
|
|
26
|
+
displayName: "Agent",
|
|
27
|
+
description: "General-purpose agent for researching complex questions, searching for code, and executing multi-step tasks. When you are searching for a keyword or file and are not confident that you will find the right match in the first few tries use this agent to perform the search for you.",
|
|
28
|
+
// builtinToolNames omitted — means "all available tools" (resolved at lookup time)
|
|
29
|
+
// inheritContext / runInBackground / isolated omitted — strategy fields, callers decide per-call.
|
|
30
|
+
// Setting them to false would lock callsite intent (see resolveAgentInvocationConfig in invocation-config.ts).
|
|
31
|
+
extensions: true,
|
|
32
|
+
skills: true,
|
|
33
|
+
systemPrompt: "",
|
|
34
|
+
promptMode: "append",
|
|
35
|
+
isDefault: true,
|
|
36
|
+
},
|
|
37
|
+
],
|
|
38
|
+
[
|
|
39
|
+
"Explore",
|
|
40
|
+
{
|
|
41
|
+
name: "Explore",
|
|
42
|
+
displayName: "Explore",
|
|
43
|
+
description: "Fast read-only search agent for locating code. Use it to find files by pattern (eg. \"src/components/**/*.tsx\"), grep for symbols or keywords (eg. \"API endpoints\"), or answer \"where is X defined / which files reference Y.\" Do NOT use it for code review, design-doc auditing, cross-file consistency checks, or open-ended analysis — it reads excerpts rather than whole files and will miss content past its read window. When calling, specify search breadth: \"quick\" for a single targeted lookup, \"medium\" for moderate exploration, or \"very thorough\" to search across multiple locations and naming conventions.",
|
|
44
|
+
...READ_ONLY_SURFACE,
|
|
45
|
+
// Bind the role per machine, not to a provider or model generation.
|
|
46
|
+
model: "@cheap",
|
|
47
|
+
systemPrompt: `# CRITICAL: READ-ONLY MODE - NO FILE MODIFICATIONS
|
|
48
|
+
You are a file search specialist. You excel at thoroughly navigating and exploring codebases.
|
|
49
|
+
Your role is EXCLUSIVELY to search and analyze existing code. You do NOT have access to file editing tools.
|
|
50
|
+
|
|
51
|
+
You are STRICTLY PROHIBITED from:
|
|
52
|
+
- Creating new files
|
|
53
|
+
- Modifying existing files
|
|
54
|
+
- Deleting files
|
|
55
|
+
- Moving or copying files
|
|
56
|
+
- Creating temporary files anywhere, including /tmp
|
|
57
|
+
- Using redirect operators (>, >>, |) or heredocs to write to files
|
|
58
|
+
- Running ANY commands that change system state
|
|
59
|
+
|
|
60
|
+
# Tool Usage
|
|
61
|
+
- Use the find tool for file pattern matching
|
|
62
|
+
- Use the grep tool for content search
|
|
63
|
+
- Use the read tool for reading files
|
|
64
|
+
- Make independent tool calls in parallel for efficiency
|
|
65
|
+
- Adapt search approach based on thoroughness level specified
|
|
66
|
+
|
|
67
|
+
# Output
|
|
68
|
+
- Use absolute file paths in all references
|
|
69
|
+
- Report findings as regular messages
|
|
70
|
+
- Do not use emojis
|
|
71
|
+
- Be thorough and precise`,
|
|
72
|
+
promptMode: "replace",
|
|
73
|
+
isDefault: true,
|
|
74
|
+
},
|
|
75
|
+
],
|
|
76
|
+
[
|
|
77
|
+
"Plan",
|
|
78
|
+
{
|
|
79
|
+
name: "Plan",
|
|
80
|
+
displayName: "Plan",
|
|
81
|
+
description: "Software architect agent for designing implementation plans. Use this when you need to plan the implementation strategy for a task. Returns step-by-step plans, identifies critical files, and considers architectural trade-offs.",
|
|
82
|
+
...READ_ONLY_SURFACE,
|
|
83
|
+
systemPrompt: `# CRITICAL: READ-ONLY MODE - NO FILE MODIFICATIONS
|
|
84
|
+
You are a software architect and planning specialist.
|
|
85
|
+
Your role is EXCLUSIVELY to explore the codebase and design implementation plans.
|
|
86
|
+
You do NOT have access to file editing tools — attempting to edit files will fail.
|
|
87
|
+
|
|
88
|
+
You are STRICTLY PROHIBITED from:
|
|
89
|
+
- Creating new files
|
|
90
|
+
- Modifying existing files
|
|
91
|
+
- Deleting files
|
|
92
|
+
- Moving or copying files
|
|
93
|
+
- Creating temporary files anywhere, including /tmp
|
|
94
|
+
- Using redirect operators (>, >>, |) or heredocs to write to files
|
|
95
|
+
- Running ANY commands that change system state
|
|
96
|
+
|
|
97
|
+
# Planning Process
|
|
98
|
+
1. Understand requirements
|
|
99
|
+
2. Explore thoroughly (read files, find patterns, understand architecture)
|
|
100
|
+
3. Design solution based on your assigned perspective
|
|
101
|
+
4. Detail the plan with step-by-step implementation strategy
|
|
102
|
+
|
|
103
|
+
# Requirements
|
|
104
|
+
- Consider trade-offs and architectural decisions
|
|
105
|
+
- Identify dependencies and sequencing
|
|
106
|
+
- Anticipate potential challenges
|
|
107
|
+
- Follow existing patterns where appropriate
|
|
108
|
+
|
|
109
|
+
# Tool Usage
|
|
110
|
+
- Use the find tool for file pattern matching
|
|
111
|
+
- Use the grep tool for content search
|
|
112
|
+
- Use the read tool for reading files
|
|
113
|
+
|
|
114
|
+
# Output Format
|
|
115
|
+
- Use absolute file paths
|
|
116
|
+
- Do not use emojis
|
|
117
|
+
- End your response with:
|
|
118
|
+
|
|
119
|
+
### Critical Files for Implementation
|
|
120
|
+
List 3-5 files most critical for implementing this plan:
|
|
121
|
+
- /absolute/path/to/file.ts - [Brief reason]`,
|
|
122
|
+
promptMode: "replace",
|
|
123
|
+
isDefault: true,
|
|
124
|
+
},
|
|
125
|
+
],
|
|
126
|
+
]);
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* detached-results.ts -- hand completed background agents back to a session
|
|
3
|
+
* after the extension instance that spawned them is gone.
|
|
4
|
+
*
|
|
5
|
+
* `/new`, `/resume`, `/fork` and `/reload` shut the extension down but keep the
|
|
6
|
+
* process alive. Background agents are allowed to finish in the orphaned
|
|
7
|
+
* manager, which can no longer talk to pi (its `pi` handle is stale), so each
|
|
8
|
+
* result is spooled to disk keyed by the PARENT session file. The extension
|
|
9
|
+
* instance bound to that session drains the spool on `session_start`, and while
|
|
10
|
+
* it is active a process-wide sink wakes it for results that land later.
|
|
11
|
+
*/
|
|
12
|
+
import { createHash } from "node:crypto";
|
|
13
|
+
import { mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
14
|
+
import { tmpdir } from "node:os";
|
|
15
|
+
import { join } from "node:path";
|
|
16
|
+
import type { EvictedNote } from "./agent-manager.js";
|
|
17
|
+
import type { NoticeParts } from "./notification-result.js";
|
|
18
|
+
import type { AgentRecord, AgentTombstone } from "./types.js";
|
|
19
|
+
import type { AgentActivity } from "./ui/agent-widget.js";
|
|
20
|
+
|
|
21
|
+
/** One finished agent, in the shape `session_start` needs to re-announce it. */
|
|
22
|
+
export interface DetachedResult {
|
|
23
|
+
id: string;
|
|
24
|
+
/** Pre-rendered `<task-notification>` text for the LLM. */
|
|
25
|
+
content: string;
|
|
26
|
+
/** `subagent-notification` renderer details. */
|
|
27
|
+
details: unknown;
|
|
28
|
+
/** History entry for a result that finished detached; absent if already appended. */
|
|
29
|
+
record?: Record<string, unknown>;
|
|
30
|
+
/** The `subagents:completed`/`subagents:failed` event the live path would have emitted, replayed on delivery. */
|
|
31
|
+
lifecycle?: { channel: "subagents:completed" | "subagents:failed"; data: Record<string, unknown> };
|
|
32
|
+
/** What the reopened session keeps so these agents' ids still answer after their records are gone. */
|
|
33
|
+
evicted?: EvictedNote[];
|
|
34
|
+
/** Reopenable sessions among them, so a steer or resume of these ids continues the saved conversation. */
|
|
35
|
+
tombstones?: AgentTombstone[];
|
|
36
|
+
/** A full-result notice's parts, so delivery clips it against its batch's budget; `content` is the fallback. */
|
|
37
|
+
notice?: NoticeParts & { footer: string };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const SINK_KEY = Symbol.for("pi-subagents:detached-sink");
|
|
41
|
+
|
|
42
|
+
/** Per-session wake-ups, shared across every extension instance in the process. */
|
|
43
|
+
function sinks(): Map<string, () => void> {
|
|
44
|
+
const g = globalThis as Record<symbol, unknown>;
|
|
45
|
+
let map = g[SINK_KEY] as Map<string, () => void> | undefined;
|
|
46
|
+
if (!map) {
|
|
47
|
+
map = new Map();
|
|
48
|
+
g[SINK_KEY] = map;
|
|
49
|
+
}
|
|
50
|
+
return map;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Spool directory for one parent session (created on demand, owner-only). */
|
|
54
|
+
export function detachedDir(sessionFile: string): string {
|
|
55
|
+
const key = createHash("sha256").update(sessionFile).digest("hex").slice(0, 16);
|
|
56
|
+
const dir = join(tmpdir(), `pi-subagents-${process.getuid?.() ?? 0}`, "detached", key);
|
|
57
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
58
|
+
return dir;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Persist a result for `sessionFile` and wake its live extension instance, if any. */
|
|
62
|
+
export function spoolDetached(sessionFile: string, result: DetachedResult): void {
|
|
63
|
+
const dir = detachedDir(sessionFile);
|
|
64
|
+
const name = `${Date.now()}-${result.id.replace(/[^\w.-]/g, "_")}.json`;
|
|
65
|
+
// Rename into place so a concurrent drain never reads a half-written file.
|
|
66
|
+
const tmp = join(dir, `.${name}.tmp`);
|
|
67
|
+
writeFileSync(tmp, JSON.stringify(result), { mode: 0o600 });
|
|
68
|
+
renameSync(tmp, join(dir, name));
|
|
69
|
+
try {
|
|
70
|
+
sinks().get(sessionFile)?.();
|
|
71
|
+
} catch {
|
|
72
|
+
// The woken instance is already shutting down; the file stays for the next drain.
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Read and delete every spooled result for `sessionFile`, oldest first. Unreadable files are dropped. */
|
|
77
|
+
export function drainDetached(sessionFile: string): DetachedResult[] {
|
|
78
|
+
const dir = detachedDir(sessionFile);
|
|
79
|
+
const out: DetachedResult[] = [];
|
|
80
|
+
for (const name of readdirSync(dir).filter(n => n.endsWith(".json") && !n.startsWith(".")).sort()) {
|
|
81
|
+
const path = join(dir, name);
|
|
82
|
+
try {
|
|
83
|
+
out.push(JSON.parse(readFileSync(path, "utf8")) as DetachedResult);
|
|
84
|
+
} catch {
|
|
85
|
+
// Corrupt spool entry: nothing recoverable, and retrying it forever helps nobody.
|
|
86
|
+
}
|
|
87
|
+
rmSync(path, { force: true });
|
|
88
|
+
}
|
|
89
|
+
return out;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Call `onSpooled` whenever a result lands for `sessionFile`. Returns the unsubscribe. */
|
|
93
|
+
export function watchDetached(sessionFile: string, onSpooled: () => void): () => void {
|
|
94
|
+
const map = sinks();
|
|
95
|
+
map.set(sessionFile, onSpooled);
|
|
96
|
+
return () => {
|
|
97
|
+
if (map.get(sessionFile) === onSpooled) map.delete(sessionFile);
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* A background agent still running in an orphaned manager. The record and
|
|
103
|
+
* activity are the orphan's live objects, so a reloaded session can show and
|
|
104
|
+
* open them; `abort` and `steer` are bound to the orphan's manager.
|
|
105
|
+
*/
|
|
106
|
+
export interface RunningDetached {
|
|
107
|
+
record: AgentRecord;
|
|
108
|
+
activity?: AgentActivity;
|
|
109
|
+
/** `by` as for `AgentManager.abort`: `"parent"` for `stop_subagent`, omitted for a human. */
|
|
110
|
+
abort(by?: AgentRecord["stoppedBy"]): boolean;
|
|
111
|
+
steer(message: string): boolean;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const RUNNING_KEY = Symbol.for("pi-subagents:detached-running");
|
|
115
|
+
|
|
116
|
+
/** Running orphans by parent session file then agent id, shared across every extension instance. */
|
|
117
|
+
function running(): Map<string, Map<string, RunningDetached>> {
|
|
118
|
+
const g = globalThis as Record<symbol, unknown>;
|
|
119
|
+
let map = g[RUNNING_KEY] as Map<string, Map<string, RunningDetached>> | undefined;
|
|
120
|
+
if (!map) {
|
|
121
|
+
map = new Map();
|
|
122
|
+
g[RUNNING_KEY] = map;
|
|
123
|
+
}
|
|
124
|
+
return map;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Publish an orphaned, still-running agent so the session's next extension instance can list it. */
|
|
128
|
+
export function registerRunningDetached(sessionFile: string, agent: RunningDetached): void {
|
|
129
|
+
const byId = running().get(sessionFile) ?? new Map<string, RunningDetached>();
|
|
130
|
+
byId.set(agent.record.id, agent);
|
|
131
|
+
running().set(sessionFile, byId);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Drop an orphan once it settles (its result is spooled from there on). */
|
|
135
|
+
export function unregisterRunningDetached(sessionFile: string, id: string): void {
|
|
136
|
+
const byId = running().get(sessionFile);
|
|
137
|
+
byId?.delete(id);
|
|
138
|
+
if (byId?.size === 0) running().delete(sessionFile);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Every orphan still running in the process with the session file it is registered (and wakes) under. */
|
|
142
|
+
export function listAllRunningDetached(): Array<{ sessionFile: string; agent: RunningDetached }> {
|
|
143
|
+
return [...running()].flatMap(([sessionFile, byId]) => [...byId.values()].map((agent) => ({ sessionFile, agent })));
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Orphans still running for `sessionFile`, in registration order. */
|
|
147
|
+
export function listRunningDetached(sessionFile: string | undefined): RunningDetached[] {
|
|
148
|
+
if (sessionFile === undefined) return [];
|
|
149
|
+
return [...(running().get(sessionFile)?.values() ?? [])];
|
|
150
|
+
}
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reads `enabledModels` from pi's settings (global `<agentDir>/settings.json`
|
|
3
|
+
* + project-local `<cwd>/.pi/settings.json`, project wins) and resolves
|
|
4
|
+
* entries to concrete `provider/modelId` keys for scope validation.
|
|
5
|
+
*
|
|
6
|
+
* **Project overrides global**, mirroring pi's own `SettingsManager`
|
|
7
|
+
* deep-merge behavior and matching the precedence we use for our own
|
|
8
|
+
* `subagents.json` settings (see `src/settings.ts:loadSettings`). If
|
|
9
|
+
* project file has `enabledModels` set, it wholly replaces global's
|
|
10
|
+
* (array fields are replaced, not concatenated).
|
|
11
|
+
*
|
|
12
|
+
* **Limited subset of upstream's resolveModelScope.** We support exact
|
|
13
|
+
* `provider/modelId` matching only. Upstream (pi-coding-agent's
|
|
14
|
+
* `core/model-resolver.ts`) additionally supports glob patterns
|
|
15
|
+
* (`*sonnet*`, `anthropic/*`), bare model IDs without provider, and
|
|
16
|
+
* thinking-level suffixes (`provider/*:high`). Those forms are silently
|
|
17
|
+
* ignored here.
|
|
18
|
+
*
|
|
19
|
+
* In practice, pi's `/scoped-models` picker writes exact `provider/modelId`
|
|
20
|
+
* entries, so the limitation is invisible for users who configure scope
|
|
21
|
+
* through pi's UI. Hand-edited settings using globs or bare IDs will
|
|
22
|
+
* produce an empty allowed set (scope check becomes a no-op).
|
|
23
|
+
*
|
|
24
|
+
* Example:
|
|
25
|
+
* enabledModels = ["anthropic/claude-sonnet-4-6", "anthropic/claude-opus-4-6"]
|
|
26
|
+
* → resolves to { "anthropic/claude-sonnet-4-6", "anthropic/claude-opus-4-6" }
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
30
|
+
import { join } from "node:path";
|
|
31
|
+
import { resolveAgentDir } from "./home-paths.js";
|
|
32
|
+
import type { ModelEntry } from "./model-resolver.js";
|
|
33
|
+
|
|
34
|
+
/** Minimal registry shape — only the methods resolveEnabledModels actually calls. */
|
|
35
|
+
export interface ModelRegistryRef {
|
|
36
|
+
getAll(): unknown[];
|
|
37
|
+
getAvailable?(): unknown[];
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Paths to pi's settings.json files: [project, global] (project takes precedence). */
|
|
41
|
+
function settingsPaths(cwd: string, homeDir?: string): [project: string, global: string] {
|
|
42
|
+
return [
|
|
43
|
+
join(cwd, ".pi", "settings.json"),
|
|
44
|
+
join(resolveAgentDir(homeDir), "settings.json"),
|
|
45
|
+
];
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Read `enabledModels` from a single settings.json file. Undefined when missing or absent. */
|
|
49
|
+
function readField(path: string): string[] | undefined {
|
|
50
|
+
if (!existsSync(path)) return undefined;
|
|
51
|
+
try {
|
|
52
|
+
const raw = JSON.parse(readFileSync(path, "utf-8"));
|
|
53
|
+
if (Array.isArray(raw?.enabledModels)) return raw.enabledModels as string[];
|
|
54
|
+
} catch {
|
|
55
|
+
/* corrupt file — silent */
|
|
56
|
+
}
|
|
57
|
+
return undefined;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Read enabledModels from pi's settings — project-local overrides global.
|
|
62
|
+
* Mirrors pi's SettingsManager deep-merge for the `enabledModels` field
|
|
63
|
+
* (and matches our own loadSettings precedence in src/settings.ts).
|
|
64
|
+
* Returns undefined when neither file has the field.
|
|
65
|
+
*/
|
|
66
|
+
export function readEnabledModels(cwd: string, homeDir?: string): string[] | undefined {
|
|
67
|
+
const [project, global] = settingsPaths(cwd, homeDir);
|
|
68
|
+
return readField(project) ?? readField(global);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Resolve enabledModels patterns → Set<"provider/modelId"> (lowercase keys).
|
|
73
|
+
*
|
|
74
|
+
* Only exact `provider/modelId` patterns are matched (case-insensitive).
|
|
75
|
+
* Patterns without a slash, with glob characters, or with a `:thinking`
|
|
76
|
+
* suffix are silently dropped. See module-level docstring for rationale.
|
|
77
|
+
*
|
|
78
|
+
* Cache: keyed on JSON.stringify(patterns) + mtime/size of *both*
|
|
79
|
+
* project and global settings.json files. Re-resolves when either file
|
|
80
|
+
* changes or the patterns argument differs.
|
|
81
|
+
*
|
|
82
|
+
* Returns undefined when no patterns are provided or no patterns match
|
|
83
|
+
* (scope check becomes a no-op at the call site).
|
|
84
|
+
*/
|
|
85
|
+
|
|
86
|
+
// Module-level cache — invalidated when either settings.json changes or patterns differ.
|
|
87
|
+
let cachedAllowed: Set<string> | undefined;
|
|
88
|
+
let cachedHash = "";
|
|
89
|
+
let cachedPatternsKey = "";
|
|
90
|
+
|
|
91
|
+
/** mtime+size hash of one file, or "missing" if absent. */
|
|
92
|
+
function hashOf(path: string): string {
|
|
93
|
+
try {
|
|
94
|
+
const s = statSync(path);
|
|
95
|
+
return `${s.mtimeMs}-${s.size}`;
|
|
96
|
+
} catch {
|
|
97
|
+
return "missing";
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function resolveEnabledModels(
|
|
102
|
+
patterns: string[] | undefined,
|
|
103
|
+
registry: ModelRegistryRef,
|
|
104
|
+
cwd: string = process.cwd(),
|
|
105
|
+
homeDir?: string,
|
|
106
|
+
): Set<string> | undefined {
|
|
107
|
+
// Fast path: check cache (stat both project and global settings.json files)
|
|
108
|
+
const patternsKey = JSON.stringify(patterns);
|
|
109
|
+
const [project, global] = settingsPaths(cwd, homeDir);
|
|
110
|
+
const fileHash = `${project}:${hashOf(project)};${global}:${hashOf(global)}`;
|
|
111
|
+
|
|
112
|
+
if (fileHash === cachedHash && patternsKey === cachedPatternsKey) {
|
|
113
|
+
return cachedAllowed;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// Cache miss — resolve
|
|
117
|
+
if (!patterns || patterns.length === 0) {
|
|
118
|
+
cachedHash = fileHash;
|
|
119
|
+
cachedPatternsKey = patternsKey;
|
|
120
|
+
cachedAllowed = undefined;
|
|
121
|
+
return undefined;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const available = (registry.getAvailable?.() ?? registry.getAll()) as ModelEntry[];
|
|
125
|
+
const allowed = new Set<string>();
|
|
126
|
+
|
|
127
|
+
for (const pattern of patterns) {
|
|
128
|
+
const trimmed = pattern.trim();
|
|
129
|
+
if (!trimmed) continue; // skip empty/whitespace
|
|
130
|
+
resolveExact(trimmed, available, allowed);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const result = allowed.size > 0 ? allowed : undefined;
|
|
134
|
+
cachedHash = fileHash;
|
|
135
|
+
cachedPatternsKey = patternsKey;
|
|
136
|
+
cachedAllowed = result;
|
|
137
|
+
return result;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* True when `model` is in the allowed set. Centralizes the key format
|
|
144
|
+
* (`provider/id` lowercase) so callers don't have to reproduce it —
|
|
145
|
+
* both set-building (resolveExact) and lookup go through `modelKey`.
|
|
146
|
+
*/
|
|
147
|
+
export function isModelInScope(
|
|
148
|
+
model: { provider: string; id: string },
|
|
149
|
+
allowed: Set<string>,
|
|
150
|
+
): boolean {
|
|
151
|
+
return allowed.has(modelKey(model));
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Canonical lowercase `provider/id` key for the allowed set. */
|
|
155
|
+
function modelKey(model: { provider: string; id: string }): string {
|
|
156
|
+
return `${model.provider}/${model.id}`.toLowerCase();
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Resolve exact model pattern. Example: "google/gemma-4-31b-it".
|
|
161
|
+
*/
|
|
162
|
+
function resolveExact(
|
|
163
|
+
pattern: string,
|
|
164
|
+
available: ModelEntry[],
|
|
165
|
+
allowed: Set<string>,
|
|
166
|
+
): void {
|
|
167
|
+
// "provider/modelId" — exact (colon is part of id, not split)
|
|
168
|
+
const slashIdx = pattern.indexOf("/");
|
|
169
|
+
if (slashIdx === -1) return; // bare modelId not supported
|
|
170
|
+
|
|
171
|
+
const provider = pattern.slice(0, slashIdx).toLowerCase();
|
|
172
|
+
const modelId = pattern.slice(slashIdx + 1).toLowerCase();
|
|
173
|
+
const exact = available.find(
|
|
174
|
+
m => m.provider.toLowerCase() === provider && m.id.toLowerCase() === modelId,
|
|
175
|
+
);
|
|
176
|
+
if (exact) {
|
|
177
|
+
allowed.add(modelKey(exact));
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Optional machine-local enterprise overlay.
|
|
3
|
+
*
|
|
4
|
+
* This extension deliberately knows no enterprise provider, endpoint, model, or
|
|
5
|
+
* credential. A user-provisioned manifest lives beside Pi's other private state
|
|
6
|
+
* at `<agentDir>/enterprise.local.json`; it is never read from a project.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
10
|
+
import { join } from "node:path";
|
|
11
|
+
import { errorMessage } from "./error-message.js";
|
|
12
|
+
import { resolveAgentDir } from "./home-paths.js";
|
|
13
|
+
|
|
14
|
+
const MANIFEST_VERSION = 1;
|
|
15
|
+
const MANIFEST_NAME = "enterprise.local.json";
|
|
16
|
+
|
|
17
|
+
export interface EnterpriseLocalManifest {
|
|
18
|
+
version: number;
|
|
19
|
+
settings?: Record<string, unknown>;
|
|
20
|
+
models?: { providers?: Record<string, unknown> };
|
|
21
|
+
subagents?: Record<string, unknown>;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Return the target-local manifest path without reading it. */
|
|
25
|
+
export function enterpriseLocalPath(homeDir?: string): string {
|
|
26
|
+
return join(resolveAgentDir(homeDir), MANIFEST_NAME);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Read and minimally validate the machine-local manifest. It never exposes its
|
|
31
|
+
* contents in diagnostics: providers can include command-backed credentials.
|
|
32
|
+
*/
|
|
33
|
+
export function readEnterpriseLocalManifest(homeDir?: string): EnterpriseLocalManifest | undefined {
|
|
34
|
+
const path = enterpriseLocalPath(homeDir);
|
|
35
|
+
if (!existsSync(path)) return undefined;
|
|
36
|
+
|
|
37
|
+
try {
|
|
38
|
+
const mode = statSync(path).mode & 0o777;
|
|
39
|
+
if ((mode & 0o077) !== 0) {
|
|
40
|
+
console.warn(`[pi-subagents] Ignoring ${path}: permissions must not grant group or other access.`);
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
|
43
|
+
const raw: unknown = JSON.parse(readFileSync(path, "utf-8"));
|
|
44
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
|
|
45
|
+
throw new Error("expected a JSON object");
|
|
46
|
+
}
|
|
47
|
+
const manifest = raw as Record<string, unknown>;
|
|
48
|
+
if (manifest.version !== MANIFEST_VERSION) {
|
|
49
|
+
throw new Error(`unsupported manifest version (expected ${MANIFEST_VERSION})`);
|
|
50
|
+
}
|
|
51
|
+
for (const section of ["settings", "models", "subagents"] as const) {
|
|
52
|
+
const value = manifest[section];
|
|
53
|
+
if (value !== undefined && (!value || typeof value !== "object" || Array.isArray(value))) {
|
|
54
|
+
throw new Error(`section "${section}" must be an object`);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
const models = manifest.models as Record<string, unknown> | undefined;
|
|
58
|
+
if (models?.providers !== undefined && (!models.providers || typeof models.providers !== "object" || Array.isArray(models.providers))) {
|
|
59
|
+
throw new Error('section "models.providers" must be an object');
|
|
60
|
+
}
|
|
61
|
+
return manifest as unknown as EnterpriseLocalManifest;
|
|
62
|
+
} catch (error) {
|
|
63
|
+
const reason = errorMessage(error);
|
|
64
|
+
console.warn(`[pi-subagents] Ignoring invalid ${path}: ${reason}`);
|
|
65
|
+
return undefined;
|
|
66
|
+
}
|
|
67
|
+
}
|
package/src/env.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* env.ts — Detect environment info (git, platform) for subagent system prompts.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
6
|
+
import type { EnvInfo } from "./types.js";
|
|
7
|
+
|
|
8
|
+
export async function detectEnv(pi: ExtensionAPI, cwd: string): Promise<EnvInfo> {
|
|
9
|
+
let isGitRepo = false;
|
|
10
|
+
let branch = "";
|
|
11
|
+
|
|
12
|
+
try {
|
|
13
|
+
const result = await pi.exec("git", ["rev-parse", "--is-inside-work-tree"], { cwd, timeout: 5000 });
|
|
14
|
+
isGitRepo = result.code === 0 && result.stdout.trim() === "true";
|
|
15
|
+
} catch {
|
|
16
|
+
// Not a git repo or git not installed
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
if (isGitRepo) {
|
|
20
|
+
try {
|
|
21
|
+
const result = await pi.exec("git", ["branch", "--show-current"], { cwd, timeout: 5000 });
|
|
22
|
+
branch = result.code === 0 ? result.stdout.trim() : "unknown";
|
|
23
|
+
} catch {
|
|
24
|
+
branch = "unknown";
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
return {
|
|
29
|
+
isGitRepo,
|
|
30
|
+
branch,
|
|
31
|
+
platform: process.platform,
|
|
32
|
+
};
|
|
33
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* error-message.ts — the text a caught value reports.
|
|
3
|
+
*
|
|
4
|
+
* `catch` binds `unknown`: an `Error` gives its message, and anything else a
|
|
5
|
+
* caller threw (a string, a rejected non-Error) is stringified as-is.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** The message of `error` when it is an `Error`, else `String(error)`. */
|
|
9
|
+
export function errorMessage(error: unknown): string {
|
|
10
|
+
return error instanceof Error ? error.message : String(error);
|
|
11
|
+
}
|
package/src/git-path.ts
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* git-path.ts -- decode the C-style quoted paths git prints without `-z`.
|
|
3
|
+
*
|
|
4
|
+
* `pi.exec` decodes each stdout chunk as UTF-8 on its own, so a multibyte
|
|
5
|
+
* character split across two chunks becomes U+FFFD. With `core.quotePath=true`
|
|
6
|
+
* git escapes every non-ASCII byte (and control characters, `"` and `\`) as
|
|
7
|
+
* `"..."` with octal escapes, so a listing read without `-z` is pure ASCII and
|
|
8
|
+
* survives any chunking; this module turns it back into the real path.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
const SIMPLE_ESCAPES: Record<string, number> = {
|
|
12
|
+
a: 0x07,
|
|
13
|
+
b: 0x08,
|
|
14
|
+
f: 0x0c,
|
|
15
|
+
n: 0x0a,
|
|
16
|
+
r: 0x0d,
|
|
17
|
+
t: 0x09,
|
|
18
|
+
v: 0x0b,
|
|
19
|
+
'"': 0x22,
|
|
20
|
+
"\\": 0x5c,
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
const UTF8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
|
|
24
|
+
|
|
25
|
+
/** Args that make `git` quote every non-ASCII path byte; put them before the subcommand. */
|
|
26
|
+
export const QUOTE_PATH_ARGS = ["-c", "core.quotePath=true"];
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Decode one path as git prints it: a plain name is returned as is, a `"..."` name is
|
|
30
|
+
* unescaped to bytes and decoded as UTF-8. Throws on anything that cannot name a file
|
|
31
|
+
* as a JS string: raw non-ASCII (the listing was not quoted, so it may be mis-decoded),
|
|
32
|
+
* a malformed escape, or bytes that are not valid UTF-8.
|
|
33
|
+
*/
|
|
34
|
+
export function unquoteGitPath(text: string): string {
|
|
35
|
+
const quoted = text.length >= 2 && text.startsWith('"') && text.endsWith('"');
|
|
36
|
+
const body = quoted ? text.slice(1, -1) : text;
|
|
37
|
+
for (let i = 0; i < body.length; i++) {
|
|
38
|
+
if (body.charCodeAt(i) > 0x7f) throw new Error(`git printed a non-ASCII path unquoted (${JSON.stringify(text)}); it may be mis-decoded`);
|
|
39
|
+
}
|
|
40
|
+
if (!quoted) return text;
|
|
41
|
+
const bytes: number[] = [];
|
|
42
|
+
for (let i = 0; i < body.length; i++) {
|
|
43
|
+
const char = body.charAt(i);
|
|
44
|
+
if (char === '"') throw new Error(`malformed quoted git path ${JSON.stringify(text)}`);
|
|
45
|
+
if (char !== "\\") {
|
|
46
|
+
bytes.push(body.charCodeAt(i));
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
const next = body.charAt(i + 1);
|
|
50
|
+
const octal = /^[0-3][0-7]{2}$/.test(body.slice(i + 1, i + 4)) ? body.slice(i + 1, i + 4) : undefined;
|
|
51
|
+
if (octal) {
|
|
52
|
+
bytes.push(Number.parseInt(octal, 8));
|
|
53
|
+
i += 3;
|
|
54
|
+
} else if (next in SIMPLE_ESCAPES) {
|
|
55
|
+
bytes.push(SIMPLE_ESCAPES[next] as number);
|
|
56
|
+
i += 1;
|
|
57
|
+
} else {
|
|
58
|
+
throw new Error(`malformed escape in quoted git path ${JSON.stringify(text)}`);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
try {
|
|
62
|
+
return UTF8.decode(Uint8Array.from(bytes));
|
|
63
|
+
} catch {
|
|
64
|
+
throw new Error(`git path ${JSON.stringify(text)} is not valid UTF-8 and cannot be inspected`);
|
|
65
|
+
}
|
|
66
|
+
}
|