@ilya-lesikov/pi-pi 0.9.0 → 0.10.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/3p/pi-ask-user/index.ts +71 -124
- package/3p/pi-ask-user/single-select-layout.ts +3 -14
- package/3p/pi-subagents/package.json +13 -7
- package/3p/pi-subagents/src/agent-manager.ts +243 -79
- package/3p/pi-subagents/src/agent-runner.ts +501 -365
- package/3p/pi-subagents/src/agent-types.ts +46 -57
- package/3p/pi-subagents/src/cross-extension-rpc.ts +52 -46
- package/3p/pi-subagents/src/custom-agents.ts +30 -6
- package/3p/pi-subagents/src/default-agents.ts +25 -43
- package/3p/pi-subagents/src/enabled-models.ts +180 -0
- package/3p/pi-subagents/src/index.ts +599 -839
- package/3p/pi-subagents/src/model-resolver.ts +26 -7
- package/3p/pi-subagents/src/output-file.ts +21 -2
- package/3p/pi-subagents/src/prompts.ts +17 -3
- package/3p/pi-subagents/src/schedule-store.ts +153 -0
- package/3p/pi-subagents/src/schedule.ts +365 -0
- package/3p/pi-subagents/src/settings.ts +261 -0
- package/3p/pi-subagents/src/skill-loader.ts +77 -54
- package/3p/pi-subagents/src/status-note.ts +25 -0
- package/3p/pi-subagents/src/types.ts +97 -6
- package/3p/pi-subagents/src/ui/agent-widget.ts +94 -21
- package/3p/pi-subagents/src/ui/conversation-viewer.ts +147 -35
- package/3p/pi-subagents/src/ui/schedule-menu.ts +104 -0
- package/3p/pi-subagents/src/ui/viewer-keys.ts +39 -0
- package/3p/pi-subagents/src/usage.ts +60 -0
- package/3p/pi-subagents/src/worktree.ts +49 -20
- package/extensions/orchestrator/agents/advisor.ts +13 -8
- package/extensions/orchestrator/agents/brainstorm-reviewer.ts +8 -3
- package/extensions/orchestrator/agents/code-reviewer.ts +8 -3
- package/extensions/orchestrator/agents/constraints.test.ts +26 -0
- package/extensions/orchestrator/agents/constraints.ts +12 -2
- package/extensions/orchestrator/agents/deep-debugger.ts +13 -8
- package/extensions/orchestrator/agents/explore.ts +12 -6
- package/extensions/orchestrator/agents/librarian.ts +13 -5
- package/extensions/orchestrator/agents/plan-reviewer.ts +8 -3
- package/extensions/orchestrator/agents/planner.ts +8 -3
- package/extensions/orchestrator/agents/pools.test.ts +56 -0
- package/extensions/orchestrator/agents/prompts.test.ts +52 -10
- package/extensions/orchestrator/agents/registry.test.ts +245 -0
- package/extensions/orchestrator/agents/registry.ts +145 -10
- package/extensions/orchestrator/agents/reviewer.ts +14 -8
- package/extensions/orchestrator/agents/task.ts +12 -6
- package/extensions/orchestrator/agents/tool-routing.ts +213 -85
- package/extensions/orchestrator/agents/wait-for-completion.test.ts +171 -0
- package/extensions/orchestrator/ast-search.test.ts +124 -0
- package/extensions/orchestrator/billing-spoof.test.ts +67 -0
- package/extensions/orchestrator/billing-spoof.ts +95 -0
- package/extensions/orchestrator/cbm.more.test.ts +358 -0
- package/extensions/orchestrator/command-handlers.ts +6 -0
- package/extensions/orchestrator/commands.test.ts +15 -2
- package/extensions/orchestrator/commands.ts +1 -1
- package/extensions/orchestrator/config.test.ts +89 -1
- package/extensions/orchestrator/config.ts +102 -19
- package/extensions/orchestrator/context.test.ts +46 -0
- package/extensions/orchestrator/context.ts +18 -5
- package/extensions/orchestrator/custom-footer.test.ts +24 -10
- package/extensions/orchestrator/custom-footer.ts +4 -2
- package/extensions/orchestrator/doctor.more.test.ts +315 -0
- package/extensions/orchestrator/doctor.ts +6 -2
- package/extensions/orchestrator/event-handlers.more.test.ts +561 -0
- package/extensions/orchestrator/event-handlers.test.ts +96 -9
- package/extensions/orchestrator/event-handlers.ts +344 -151
- package/extensions/orchestrator/exa.more.test.ts +118 -0
- package/extensions/orchestrator/flant-infra.more.test.ts +326 -0
- package/extensions/orchestrator/flant-infra.test.ts +127 -0
- package/extensions/orchestrator/flant-infra.ts +113 -39
- package/extensions/orchestrator/index.test.ts +76 -0
- package/extensions/orchestrator/index.ts +2 -0
- package/extensions/orchestrator/integration.test.ts +183 -65
- package/extensions/orchestrator/model-registry.test.ts +2 -1
- package/extensions/orchestrator/model-registry.ts +12 -2
- package/extensions/orchestrator/orchestrator.test.ts +67 -0
- package/extensions/orchestrator/orchestrator.ts +119 -27
- package/extensions/orchestrator/phases/brainstorm.test.ts +30 -1
- package/extensions/orchestrator/phases/brainstorm.ts +43 -6
- package/extensions/orchestrator/phases/implementation.ts +2 -0
- package/extensions/orchestrator/phases/machine.test.ts +17 -1
- package/extensions/orchestrator/phases/machine.ts +4 -1
- package/extensions/orchestrator/phases/planning.test.ts +47 -1
- package/extensions/orchestrator/phases/planning.ts +18 -3
- package/extensions/orchestrator/phases/review-task.ts +5 -0
- package/extensions/orchestrator/phases/review.test.ts +10 -0
- package/extensions/orchestrator/phases/review.ts +22 -7
- package/extensions/orchestrator/phases/spawn-blocking.test.ts +1 -0
- package/extensions/orchestrator/phases/verdict.ts +6 -5
- package/extensions/orchestrator/plannotator-open-failure.test.ts +67 -0
- package/extensions/orchestrator/plannotator.test.ts +38 -1
- package/extensions/orchestrator/plannotator.ts +50 -3
- package/extensions/orchestrator/pp-menu.leaves.test.ts +590 -0
- package/extensions/orchestrator/pp-menu.more.test.ts +524 -0
- package/extensions/orchestrator/pp-menu.test.ts +114 -7
- package/extensions/orchestrator/pp-menu.ts +579 -90
- package/extensions/orchestrator/pp-state-tools.test.ts +80 -0
- package/extensions/orchestrator/pp-state-tools.ts +65 -0
- package/extensions/orchestrator/rate-limit-fallback.more.test.ts +241 -0
- package/extensions/orchestrator/rate-limit-fallback.test.ts +20 -1
- package/extensions/orchestrator/rate-limit-fallback.ts +12 -0
- package/extensions/orchestrator/review-files.test.ts +26 -0
- package/extensions/orchestrator/review-files.ts +3 -0
- package/extensions/orchestrator/state.test.ts +73 -1
- package/extensions/orchestrator/state.ts +95 -23
- package/extensions/orchestrator/suppress-pierre-theme-spam.test.ts +56 -0
- package/extensions/orchestrator/suppress-pierre-theme-spam.ts +45 -0
- package/extensions/orchestrator/validate-artifacts.ts +1 -1
- package/package.json +6 -2
- package/scripts/test-3p.sh +52 -0
|
@@ -2,135 +2,136 @@
|
|
|
2
2
|
* agent-runner.ts — Core execution engine: creates sessions, runs agents, collects results.
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
|
-
import {
|
|
5
|
+
import { homedir } from "node:os";
|
|
6
|
+
import { basename, dirname, isAbsolute, resolve } from "node:path";
|
|
6
7
|
import type { Model } from "@earendil-works/pi-ai";
|
|
7
|
-
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
8
|
+
import type { ExtensionContext, LoadExtensionsResult } from "@earendil-works/pi-coding-agent";
|
|
8
9
|
import {
|
|
9
10
|
type AgentSession,
|
|
10
11
|
type AgentSessionEvent,
|
|
11
12
|
createAgentSession,
|
|
12
13
|
DefaultResourceLoader,
|
|
13
14
|
type ExtensionAPI,
|
|
15
|
+
getAgentDir,
|
|
14
16
|
SessionManager,
|
|
15
17
|
SettingsManager,
|
|
16
18
|
} from "@earendil-works/pi-coding-agent";
|
|
17
|
-
import { getAgentConfig, getConfig,
|
|
19
|
+
import { BUILTIN_TOOL_NAMES, getAgentConfig, getConfig, getMemoryToolNames, getReadOnlyMemoryToolNames, getToolNamesForType } from "./agent-types.js";
|
|
18
20
|
import { buildParentContext, extractText } from "./context.js";
|
|
21
|
+
import { DEFAULT_AGENTS } from "./default-agents.js";
|
|
19
22
|
import { detectEnv } from "./env.js";
|
|
20
23
|
import { buildMemoryBlock, buildReadOnlyMemoryBlock } from "./memory.js";
|
|
21
24
|
import { buildAgentPrompt, type PromptExtras } from "./prompts.js";
|
|
22
25
|
import { preloadSkills } from "./skill-loader.js";
|
|
23
26
|
import type { SubagentType, ThinkingLevel } from "./types.js";
|
|
24
27
|
|
|
28
|
+
/**
|
|
29
|
+
* Tool names registered by THIS extension. Single source of truth so the
|
|
30
|
+
* registration sites (index.ts) and the subagent exclusion list below can't
|
|
31
|
+
* drift apart. These are our own tools, not pi built-ins, so they can't be
|
|
32
|
+
* derived from pi — but they only need defining once.
|
|
33
|
+
*/
|
|
34
|
+
export const SUBAGENT_TOOL_NAMES = {
|
|
35
|
+
AGENT: "Agent",
|
|
36
|
+
GET_RESULT: "get_subagent_result",
|
|
37
|
+
STEER: "steer_subagent",
|
|
38
|
+
} as const;
|
|
39
|
+
|
|
25
40
|
/** Names of tools registered by this extension that subagents must NOT inherit. */
|
|
26
|
-
const EXCLUDED_TOOL_NAMES
|
|
27
|
-
|
|
28
|
-
const TRACER_KEY = Symbol.for("pi-pi:tracer");
|
|
29
|
-
const SUBAGENT_SESSION_KEY = Symbol.for("pi-pi:subagent-session");
|
|
30
|
-
|
|
31
|
-
// Concurrency-safe subagent lineage. The previous approach derived parent/depth
|
|
32
|
-
// from the mutable process-global SUBAGENT_SESSION_KEY, which is racy for
|
|
33
|
-
// CONCURRENT siblings: MAIN spawns opus/gpt/gemini in parallel, each runAgent's
|
|
34
|
-
// synchronous prologue read whatever the *previous sibling* had just written to
|
|
35
|
-
// the global — so gpt recorded opus as its parent, gemini recorded gpt, forming a
|
|
36
|
-
// bogus opus→gpt→gemini chain with depth 3-6 instead of three depth-1 children of
|
|
37
|
-
// MAIN. AsyncLocalStorage instead propagates DOWN the async call chain (a nested
|
|
38
|
-
// spawn inherits its true parent's store) but NOT ACROSS sibling promises (each
|
|
39
|
-
// sibling started from MAIN sees no store → parent=undefined, depth=1).
|
|
40
|
-
interface SubagentLineage {
|
|
41
|
-
depth: number;
|
|
42
|
-
subagentId?: string;
|
|
43
|
-
}
|
|
44
|
-
const subagentLineage = new AsyncLocalStorage<SubagentLineage>();
|
|
45
|
-
|
|
46
|
-
// The process-global SUBAGENT_SESSION_KEY marker is read elsewhere purely for
|
|
47
|
-
// truthiness ("is any subagent running in this process?", e.g. orchestrator nudge
|
|
48
|
-
// gates). Manage it with a ref-count so concurrent in-process siblings set/clear
|
|
49
|
-
// it correctly regardless of completion order (a plain save/restore would leak a
|
|
50
|
-
// stale marker whenever the last sibling to finish wasn't the last to start).
|
|
51
|
-
let activeSubagentRuns = 0;
|
|
52
|
-
let markerBeforeFirstRun: unknown;
|
|
53
|
-
function enterSubagentMarker(): void {
|
|
54
|
-
if (activeSubagentRuns === 0) {
|
|
55
|
-
// Snapshot whatever was there before our first concurrent run (undefined in
|
|
56
|
-
// the main process; the orchestrator's persistent bootstrap { depth: 1 } in a
|
|
57
|
-
// subagent process) so we can restore it exactly when the last run exits.
|
|
58
|
-
markerBeforeFirstRun = (globalThis as any)[SUBAGENT_SESSION_KEY];
|
|
59
|
-
}
|
|
60
|
-
activeSubagentRuns++;
|
|
61
|
-
const marker = (globalThis as any)[SUBAGENT_SESSION_KEY];
|
|
62
|
-
if (typeof marker !== "object" || marker === null) {
|
|
63
|
-
(globalThis as any)[SUBAGENT_SESSION_KEY] = { depth: 1 };
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
function exitSubagentMarker(): void {
|
|
67
|
-
activeSubagentRuns = Math.max(0, activeSubagentRuns - 1);
|
|
68
|
-
if (activeSubagentRuns === 0) {
|
|
69
|
-
if (markerBeforeFirstRun === undefined) {
|
|
70
|
-
delete (globalThis as any)[SUBAGENT_SESSION_KEY];
|
|
71
|
-
} else {
|
|
72
|
-
(globalThis as any)[SUBAGENT_SESSION_KEY] = markerBeforeFirstRun;
|
|
73
|
-
}
|
|
74
|
-
markerBeforeFirstRun = undefined;
|
|
75
|
-
}
|
|
76
|
-
}
|
|
41
|
+
const EXCLUDED_TOOL_NAMES: string[] = Object.values(SUBAGENT_TOOL_NAMES);
|
|
77
42
|
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
43
|
+
/**
|
|
44
|
+
* Canonical name of an extension for `extensions: [...]` allowlist matching.
|
|
45
|
+
* Lowercased — extension names match case-insensitively so `extensions: [Mcp]`
|
|
46
|
+
* resolves the same as `[mcp]`. Tool names within `ext:foo/bar` are not affected.
|
|
47
|
+
* Directory extensions (`foo/index.ts`) resolve to the parent directory name;
|
|
48
|
+
* single-file extensions to the basename minus `.ts`/`.js`.
|
|
49
|
+
*/
|
|
50
|
+
export function extensionCanonicalName(extPath: string): string {
|
|
51
|
+
const base = basename(extPath);
|
|
52
|
+
const name = base === "index.ts" || base === "index.js"
|
|
53
|
+
? basename(dirname(extPath))
|
|
54
|
+
: base.replace(/\.(ts|js)$/, "");
|
|
55
|
+
return name.toLowerCase();
|
|
90
56
|
}
|
|
91
57
|
|
|
92
|
-
|
|
93
|
-
|
|
58
|
+
/**
|
|
59
|
+
* Classify `extensions: string[]` frontmatter entries for the loader-level filter.
|
|
60
|
+
*
|
|
61
|
+
* An entry is a PATH iff it contains a path separator or starts with `~`; otherwise
|
|
62
|
+
* it is a NAME. `"*"` sets the wildcard flag (keep all default-discovered extensions).
|
|
63
|
+
*
|
|
64
|
+
* Path entries are resolved (`~` expanded, made absolute against `cwd`) into `paths`
|
|
65
|
+
* — and their canonical name is also added to `names`. The loader override matches
|
|
66
|
+
* everything by canonical name, so path-loaded extensions are matched via their name
|
|
67
|
+
* rather than their post-staging `Extension.path`.
|
|
68
|
+
*/
|
|
69
|
+
export function parseExtensionsSpec(
|
|
70
|
+
entries: string[],
|
|
71
|
+
cwd: string,
|
|
72
|
+
): { names: Set<string>; paths: string[]; wildcard: boolean } {
|
|
73
|
+
const names = new Set<string>();
|
|
74
|
+
const paths: string[] = [];
|
|
75
|
+
let wildcard = false;
|
|
76
|
+
for (const entry of entries) {
|
|
77
|
+
if (!entry) continue;
|
|
78
|
+
if (entry === "*") {
|
|
79
|
+
wildcard = true;
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
const isPathEntry = entry.includes("/") || entry.includes("\\") || entry.startsWith("~");
|
|
83
|
+
if (!isPathEntry) {
|
|
84
|
+
names.add(entry.toLowerCase());
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
let p = entry;
|
|
88
|
+
if (p === "~" || p.startsWith("~/") || p.startsWith("~\\")) {
|
|
89
|
+
p = homedir() + p.slice(1);
|
|
90
|
+
}
|
|
91
|
+
const abs = isAbsolute(p) ? p : resolve(cwd, p);
|
|
92
|
+
paths.push(abs);
|
|
93
|
+
names.add(extensionCanonicalName(abs));
|
|
94
|
+
}
|
|
95
|
+
return { names, paths, wildcard };
|
|
94
96
|
}
|
|
95
97
|
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
case "tool_execution_end":
|
|
130
|
-
tracer.traceSubagent(subagentId, "tool_execution_end", { turnIndex, toolCallId: (event as any).toolCallId, toolName: (event as any).toolName, result: (event as any).result, isError: (event as any).isError });
|
|
131
|
-
break;
|
|
98
|
+
/**
|
|
99
|
+
* Parse raw `ext:` selector strings (from the `tools:` CSV) into the set of
|
|
100
|
+
* extension names to keep loaded and a per-extension tool-narrowing map.
|
|
101
|
+
*
|
|
102
|
+
* `ext:foo` → `extNames` has `foo`, no narrowing entry (all of foo's tools).
|
|
103
|
+
* `ext:foo/bar` → `extNames` has `foo`, `narrowing.foo` has `bar` (only `bar`).
|
|
104
|
+
* A name lands in `narrowing` only when a `/tool` form is seen, so a bare
|
|
105
|
+
* `ext:foo` alongside `ext:foo/bar` leaves narrowing in effect (narrowing wins).
|
|
106
|
+
* The split is on the first `/`; extension canonical names never contain `/`.
|
|
107
|
+
*/
|
|
108
|
+
export function parseExtSelectors(entries: string[]): {
|
|
109
|
+
extNames: Set<string>;
|
|
110
|
+
narrowing: Map<string, Set<string>>;
|
|
111
|
+
} {
|
|
112
|
+
const extNames = new Set<string>();
|
|
113
|
+
const narrowing = new Map<string, Set<string>>();
|
|
114
|
+
for (const raw of entries) {
|
|
115
|
+
if (!raw) continue;
|
|
116
|
+
const body = raw.slice("ext:".length);
|
|
117
|
+
const slash = body.indexOf("/");
|
|
118
|
+
// Extension name matches case-insensitively (matches the loader-side canonical
|
|
119
|
+
// name). Tool names are case-preserved — they're matched against pi-mono's
|
|
120
|
+
// registered identifiers, which are case-sensitive.
|
|
121
|
+
const name = (slash === -1 ? body : body.slice(0, slash)).trim().toLowerCase();
|
|
122
|
+
if (!name) continue;
|
|
123
|
+
extNames.add(name);
|
|
124
|
+
if (slash === -1) continue;
|
|
125
|
+
const tool = body.slice(slash + 1).trim();
|
|
126
|
+
if (!tool) continue;
|
|
127
|
+
let set = narrowing.get(name);
|
|
128
|
+
if (!set) {
|
|
129
|
+
set = new Set();
|
|
130
|
+
narrowing.set(name, set);
|
|
132
131
|
}
|
|
133
|
-
|
|
132
|
+
set.add(tool);
|
|
133
|
+
}
|
|
134
|
+
return { extNames, narrowing };
|
|
134
135
|
}
|
|
135
136
|
|
|
136
137
|
/** Default max turns. undefined = unlimited (no turn limit). */
|
|
@@ -195,6 +196,8 @@ export interface ToolActivity {
|
|
|
195
196
|
export interface RunOptions {
|
|
196
197
|
/** ExtensionAPI instance — used for pi.exec() instead of execSync. */
|
|
197
198
|
pi: ExtensionAPI;
|
|
199
|
+
/** Manager-assigned id; suffixes session name to disambiguate parallel spawns (e.g. `Explore#a1b2c3d4`). */
|
|
200
|
+
agentId?: string;
|
|
198
201
|
model?: Model<any>;
|
|
199
202
|
maxTurns?: number;
|
|
200
203
|
signal?: AbortSignal;
|
|
@@ -203,6 +206,20 @@ export interface RunOptions {
|
|
|
203
206
|
thinkingLevel?: ThinkingLevel;
|
|
204
207
|
/** Override working directory (e.g. for worktree isolation). */
|
|
205
208
|
cwd?: string;
|
|
209
|
+
/**
|
|
210
|
+
* Where .pi config is discovered (project extensions, skills, pi settings,
|
|
211
|
+
* agent memory). Default: same as the working directory. The manager sets
|
|
212
|
+
* this to the parent session's cwd when `SpawnOptions.cwd` points the
|
|
213
|
+
* working directory elsewhere — the agent works *there* but carries the
|
|
214
|
+
* parent project's config (the target's `.pi` extensions never execute).
|
|
215
|
+
*
|
|
216
|
+
* WARNING for future callers: if you pass `cwd` pointing at a directory the
|
|
217
|
+
* user didn't open, you almost certainly must pass `configCwd` too —
|
|
218
|
+
* omitting it makes the target's `.pi` extensions execute in this process.
|
|
219
|
+
* (Worktree isolation is the one intentional exception: its copy IS the
|
|
220
|
+
* parent's repo, so config resolving inside it is correct.)
|
|
221
|
+
*/
|
|
222
|
+
configCwd?: string;
|
|
206
223
|
/** Called on tool start/end with activity info. */
|
|
207
224
|
onToolActivity?: (activity: ToolActivity) => void;
|
|
208
225
|
/** Called on streaming text deltas from the assistant response. */
|
|
@@ -211,18 +228,16 @@ export interface RunOptions {
|
|
|
211
228
|
/** Called at the end of each agentic turn with the cumulative count. */
|
|
212
229
|
onTurnEnd?: (turnCount: number) => void;
|
|
213
230
|
/**
|
|
214
|
-
* Called
|
|
215
|
-
*
|
|
216
|
-
*
|
|
217
|
-
* Called up to maxValidationRetries times (default: 2).
|
|
231
|
+
* Called once per assistant message_end with that message's usage delta.
|
|
232
|
+
* Lets callers maintain a lifetime accumulator that survives compaction
|
|
233
|
+
* (which replaces session.state.messages and resets stats-derived sums).
|
|
218
234
|
*/
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
parentToolCallId?: string;
|
|
235
|
+
onAssistantUsage?: (usage: { input: number; output: number; cacheWrite: number }) => void;
|
|
236
|
+
/**
|
|
237
|
+
* Called when the session successfully compacts. `tokensBefore` is upstream's
|
|
238
|
+
* pre-compaction context size estimate. Aborted compactions don't fire.
|
|
239
|
+
*/
|
|
240
|
+
onCompaction?: (info: { reason: "manual" | "threshold" | "overflow"; tokensBefore: number }) => void;
|
|
226
241
|
}
|
|
227
242
|
|
|
228
243
|
export interface RunResult {
|
|
@@ -273,6 +288,12 @@ function forwardAbortSignal(session: AgentSession, signal?: AbortSignal): () =>
|
|
|
273
288
|
return () => signal.removeEventListener("abort", onAbort);
|
|
274
289
|
}
|
|
275
290
|
|
|
291
|
+
function resolveConfiguredSessionDir(sessionDir: string | undefined, cwd: string): string | undefined {
|
|
292
|
+
if (!sessionDir) return undefined;
|
|
293
|
+
if (sessionDir === "~" || sessionDir.startsWith("~/")) return resolve(homedir(), sessionDir.slice(2));
|
|
294
|
+
if (isAbsolute(sessionDir)) return sessionDir;
|
|
295
|
+
return resolve(cwd, sessionDir);
|
|
296
|
+
}
|
|
276
297
|
|
|
277
298
|
export async function runAgent(
|
|
278
299
|
ctx: ExtensionContext,
|
|
@@ -285,264 +306,374 @@ export async function runAgent(
|
|
|
285
306
|
|
|
286
307
|
// Resolve working directory: worktree override > parent cwd
|
|
287
308
|
const effectiveCwd = options.cwd ?? ctx.cwd;
|
|
288
|
-
|
|
289
|
-
//
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
const
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
const
|
|
296
|
-
|
|
297
|
-
//
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
//
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
// Resolve extensions/skills: isolated overrides to false
|
|
314
|
-
const extensions = options.isolated ? false : config.extensions;
|
|
315
|
-
const skills = options.isolated ? false : config.skills;
|
|
316
|
-
|
|
317
|
-
// Skill preloading: when skills is string[], preload their content into prompt
|
|
318
|
-
if (Array.isArray(skills)) {
|
|
319
|
-
const loaded = preloadSkills(skills, effectiveCwd);
|
|
320
|
-
if (loaded.length > 0) {
|
|
321
|
-
extras.skillBlocks = loaded;
|
|
322
|
-
}
|
|
323
|
-
}
|
|
324
|
-
|
|
325
|
-
let tools = getToolsForType(type, effectiveCwd);
|
|
326
|
-
|
|
327
|
-
// Persistent memory: detect write capability and branch accordingly.
|
|
328
|
-
// Account for disallowedTools — a tool in the base set but on the denylist is not truly available.
|
|
329
|
-
if (agentConfig?.memory) {
|
|
330
|
-
const existingNames = new Set(tools.map(t => t.name));
|
|
331
|
-
const denied = agentConfig.disallowedTools ? new Set(agentConfig.disallowedTools) : undefined;
|
|
332
|
-
const effectivelyHas = (name: string) => existingNames.has(name) && !denied?.has(name);
|
|
333
|
-
const hasWriteTools = effectivelyHas("write") || effectivelyHas("edit");
|
|
334
|
-
|
|
335
|
-
if (hasWriteTools) {
|
|
336
|
-
const memTools = getMemoryTools(effectiveCwd, existingNames);
|
|
337
|
-
if (memTools.length > 0) tools = [...tools, ...memTools];
|
|
338
|
-
extras.memoryBlock = buildMemoryBlock(agentConfig.name, agentConfig.memory, effectiveCwd);
|
|
339
|
-
} else {
|
|
340
|
-
if (!existingNames.has("read")) {
|
|
341
|
-
const readTools = getReadOnlyMemoryTools(effectiveCwd, existingNames);
|
|
342
|
-
if (readTools.length > 0) tools = [...tools, ...readTools];
|
|
343
|
-
}
|
|
344
|
-
extras.memoryBlock = buildReadOnlyMemoryBlock(agentConfig.name, agentConfig.memory, effectiveCwd);
|
|
345
|
-
}
|
|
309
|
+
// Filesystem work happens in effectiveCwd; config discovery in configCwd.
|
|
310
|
+
// They differ only for SpawnOptions.cwd spawns (config stays with the parent).
|
|
311
|
+
const configCwd = options.configCwd ?? effectiveCwd;
|
|
312
|
+
|
|
313
|
+
const env = await detectEnv(options.pi, effectiveCwd);
|
|
314
|
+
|
|
315
|
+
// Get parent system prompt for append-mode agents
|
|
316
|
+
const parentSystemPrompt = ctx.getSystemPrompt();
|
|
317
|
+
|
|
318
|
+
// Build prompt extras (memory, skill preloading)
|
|
319
|
+
const extras: PromptExtras = {};
|
|
320
|
+
|
|
321
|
+
// Resolve extensions/skills: isolated overrides to false
|
|
322
|
+
const extensions = options.isolated ? false : config.extensions;
|
|
323
|
+
// Nulling excludes under isolated also suppresses the orphaned-exclude warning —
|
|
324
|
+
// isolation is an intentional override, not a misconfiguration.
|
|
325
|
+
const excludeExtensions = options.isolated ? undefined : config.excludeExtensions;
|
|
326
|
+
const skills = options.isolated ? false : config.skills;
|
|
327
|
+
|
|
328
|
+
// Skill preloading: when skills is string[], preload their content into prompt
|
|
329
|
+
if (Array.isArray(skills)) {
|
|
330
|
+
const loaded = preloadSkills(skills, configCwd);
|
|
331
|
+
if (loaded.length > 0) {
|
|
332
|
+
extras.skillBlocks = loaded;
|
|
346
333
|
}
|
|
334
|
+
}
|
|
347
335
|
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
336
|
+
let toolNames = getToolNamesForType(type);
|
|
337
|
+
|
|
338
|
+
// Persistent memory: detect write capability and branch accordingly.
|
|
339
|
+
// Account for disallowedTools — a tool in the base set but on the denylist is not truly available.
|
|
340
|
+
if (agentConfig?.memory) {
|
|
341
|
+
const existingNames = new Set(toolNames);
|
|
342
|
+
const denied = agentConfig.disallowedTools ? new Set(agentConfig.disallowedTools) : undefined;
|
|
343
|
+
const effectivelyHas = (name: string) => existingNames.has(name) && !denied?.has(name);
|
|
344
|
+
const hasWriteTools = effectivelyHas("write") || effectivelyHas("edit");
|
|
345
|
+
|
|
346
|
+
if (hasWriteTools) {
|
|
347
|
+
// Read-write memory: add any missing memory tool names (read/write/edit)
|
|
348
|
+
const extraNames = getMemoryToolNames(existingNames);
|
|
349
|
+
if (extraNames.length > 0) toolNames = [...toolNames, ...extraNames];
|
|
350
|
+
extras.memoryBlock = buildMemoryBlock(agentConfig.name, agentConfig.memory, configCwd);
|
|
352
351
|
} else {
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
promptMode: "append",
|
|
358
|
-
extensions: true,
|
|
359
|
-
skills: true,
|
|
360
|
-
inheritContext: false,
|
|
361
|
-
runInBackground: false,
|
|
362
|
-
isolated: false,
|
|
363
|
-
}, effectiveCwd, env, parentSystemPrompt, extras);
|
|
352
|
+
// Read-only memory: only add read tool name, use read-only prompt
|
|
353
|
+
const extraNames = getReadOnlyMemoryToolNames(existingNames);
|
|
354
|
+
if (extraNames.length > 0) toolNames = [...toolNames, ...extraNames];
|
|
355
|
+
extras.memoryBlock = buildReadOnlyMemoryBlock(agentConfig.name, agentConfig.memory, configCwd);
|
|
364
356
|
}
|
|
357
|
+
}
|
|
365
358
|
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
await loader.reload();
|
|
378
|
-
|
|
379
|
-
const model = options.model ?? resolveDefaultModel(
|
|
380
|
-
ctx.model, ctx.modelRegistry, agentConfig?.model,
|
|
381
|
-
);
|
|
382
|
-
|
|
383
|
-
const thinkingLevel = options.thinkingLevel ?? agentConfig?.thinking;
|
|
384
|
-
|
|
385
|
-
const sessionOpts: Record<string, unknown> = {
|
|
386
|
-
cwd: effectiveCwd,
|
|
387
|
-
sessionManager: SessionManager.inMemory(effectiveCwd),
|
|
388
|
-
settingsManager: SettingsManager.create(effectiveCwd, `${effectiveCwd}/.pi/agents`),
|
|
389
|
-
modelRegistry: ctx.modelRegistry,
|
|
390
|
-
model,
|
|
391
|
-
tools: tools.map((tool) => tool.name),
|
|
392
|
-
customTools: tools,
|
|
393
|
-
resourceLoader: loader,
|
|
394
|
-
};
|
|
395
|
-
if (thinkingLevel) {
|
|
396
|
-
sessionOpts.thinkingLevel = thinkingLevel;
|
|
397
|
-
}
|
|
359
|
+
// Build system prompt from agent config
|
|
360
|
+
let systemPrompt: string;
|
|
361
|
+
if (agentConfig) {
|
|
362
|
+
systemPrompt = buildAgentPrompt(agentConfig, effectiveCwd, env, parentSystemPrompt, extras);
|
|
363
|
+
} else {
|
|
364
|
+
// Unknown type fallback: spread the canonical general-purpose config (defensive —
|
|
365
|
+
// unreachable in practice since index.ts resolves unknown types before calling runAgent).
|
|
366
|
+
const fallback = DEFAULT_AGENTS.get("general-purpose");
|
|
367
|
+
if (!fallback) throw new Error(`No fallback config available for unknown type "${type}"`);
|
|
368
|
+
systemPrompt = buildAgentPrompt({ ...fallback, name: type }, effectiveCwd, env, parentSystemPrompt, extras);
|
|
369
|
+
}
|
|
398
370
|
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
371
|
+
// When skills is string[], we've already preloaded them into the prompt.
|
|
372
|
+
// Still pass noSkills: true since we don't need the skill loader to load them again.
|
|
373
|
+
const noSkills = skills === false || Array.isArray(skills);
|
|
374
|
+
|
|
375
|
+
const agentDir = getAgentDir();
|
|
376
|
+
|
|
377
|
+
// Extension loading:
|
|
378
|
+
// - true → all default-discovered extensions
|
|
379
|
+
// - false → none (noExtensions)
|
|
380
|
+
// - string[] → loader-level allowlist. Bare names keep the matching
|
|
381
|
+
// default-discovered extension; path entries load that extension fresh;
|
|
382
|
+
// "*" keeps all default-discovered extensions. Excluded extensions never
|
|
383
|
+
// bind handlers or register tools (their factory still runs once).
|
|
384
|
+
//
|
|
385
|
+
// Suppress AGENTS.md/CLAUDE.md and APPEND_SYSTEM.md — upstream's
|
|
386
|
+
// buildSystemPrompt() re-appends both AFTER systemPromptOverride, which
|
|
387
|
+
// would defeat prompt_mode: replace and isolated: true. Parent context, if
|
|
388
|
+
// wanted, reaches the subagent via prompt_mode: append (parentSystemPrompt
|
|
389
|
+
// is embedded in systemPromptOverride) or inherit_context (conversation).
|
|
390
|
+
// `ext:` selectors from the `tools:` CSV narrow which extension tools surface to
|
|
391
|
+
// the LLM. They do NOT control loading — `extensions:` is the sole authority for
|
|
392
|
+
// which extensions load. `ext:foo` against an extension that `extensions:` excluded
|
|
393
|
+
// is an orphan and warns after reload. `isolated` means no extension tools at all.
|
|
394
|
+
const { extNames, narrowing } = parseExtSelectors(
|
|
395
|
+
options.isolated ? [] : (agentConfig?.extSelectors ?? []),
|
|
396
|
+
);
|
|
397
|
+
const noExtensions = extensions === false;
|
|
398
|
+
|
|
399
|
+
const extensionsSpec = Array.isArray(extensions)
|
|
400
|
+
? parseExtensionsSpec(extensions, configCwd)
|
|
401
|
+
: undefined;
|
|
402
|
+
const keepNames = extensionsSpec?.names ?? new Set<string>();
|
|
403
|
+
// `exclude_extensions:` is a denylist applied AFTER the include set — exclude wins.
|
|
404
|
+
// Plain canonical names only (case-insensitive). Note: excluded extensions'
|
|
405
|
+
// factories still run once during reload() (see comment above) — exclusion
|
|
406
|
+
// suppresses handler binding and tool registration; it is not a sandbox.
|
|
407
|
+
const excludeNames = new Set((excludeExtensions ?? []).map((n) => n.toLowerCase()));
|
|
408
|
+
const hasExcludes = excludeNames.size > 0;
|
|
409
|
+
// The override filters loaded extensions down to `keepNames` minus `excludeNames`.
|
|
410
|
+
// It's only needed when we're neither loading everything without excludes
|
|
411
|
+
// (`extensions: true` or a `"*"` wildcard) nor nothing (`noExtensions`).
|
|
412
|
+
const loadAll = extensions === true || extensionsSpec?.wildcard === true;
|
|
413
|
+
const additionalExtensionPaths = extensionsSpec?.paths.length ? extensionsSpec.paths : undefined;
|
|
414
|
+
// Pre-filter discovered set, captured by the override — the exclude-typo warning
|
|
415
|
+
// must compare against this, not the surviving set (absence from survivors is
|
|
416
|
+
// an exclude *succeeding*).
|
|
417
|
+
let discoveredNames: Set<string> | undefined;
|
|
418
|
+
const extensionsOverride: ((base: LoadExtensionsResult) => LoadExtensionsResult) | undefined =
|
|
419
|
+
noExtensions || (loadAll && !hasExcludes)
|
|
420
|
+
? undefined
|
|
421
|
+
: (base) => {
|
|
422
|
+
discoveredNames = new Set(base.extensions.map((e) => extensionCanonicalName(e.path)));
|
|
423
|
+
return {
|
|
424
|
+
...base,
|
|
425
|
+
extensions: base.extensions.filter((e) => {
|
|
426
|
+
const name = extensionCanonicalName(e.path);
|
|
427
|
+
if (excludeNames.has(name)) return false; // exclude wins
|
|
428
|
+
return loadAll || keepNames.has(name);
|
|
429
|
+
}),
|
|
430
|
+
};
|
|
431
|
+
};
|
|
432
|
+
|
|
433
|
+
const loader = new DefaultResourceLoader({
|
|
434
|
+
cwd: configCwd,
|
|
435
|
+
agentDir,
|
|
436
|
+
noExtensions,
|
|
437
|
+
additionalExtensionPaths,
|
|
438
|
+
extensionsOverride,
|
|
439
|
+
noSkills,
|
|
440
|
+
noPromptTemplates: true,
|
|
441
|
+
noThemes: true,
|
|
442
|
+
noContextFiles: true,
|
|
443
|
+
systemPromptOverride: () => systemPrompt,
|
|
444
|
+
appendSystemPromptOverride: () => [],
|
|
445
|
+
});
|
|
446
|
+
await loader.reload();
|
|
447
|
+
|
|
448
|
+
// Plain entries in `tools:` are expected to be built-in names (extension tools
|
|
449
|
+
// go through `ext:`), so an unknown name there is unambiguously a typo. Previously
|
|
450
|
+
// this produced a silently broken agent (#75) — pi-mono accepted the bogus name
|
|
451
|
+
// into the allowlist, then dropped it at registration with no signal back.
|
|
452
|
+
if (agentConfig?.builtinToolNames?.length) {
|
|
453
|
+
const knownBuiltins = new Set(BUILTIN_TOOL_NAMES);
|
|
454
|
+
for (const name of agentConfig.builtinToolNames) {
|
|
455
|
+
if (!knownBuiltins.has(name)) {
|
|
456
|
+
options.onToolActivity?.({
|
|
457
|
+
type: "end",
|
|
458
|
+
toolName: `tools-error:tool "${name}" requested by agent "${type}" is not a known built-in`,
|
|
459
|
+
});
|
|
460
|
+
}
|
|
426
461
|
}
|
|
462
|
+
}
|
|
427
463
|
|
|
428
|
-
|
|
429
|
-
|
|
464
|
+
// A subagent spawns mid-task, so a bad `extensions:`/`ext:` entry warns rather
|
|
465
|
+
// than aborts. Two distinct misconfigurations to catch:
|
|
466
|
+
// - `extensions: [foo]` but no extension named foo was discovered (typo or
|
|
467
|
+
// path that failed to load — path entries fold their canonical name into
|
|
468
|
+
// `keepNames`, so this covers them too).
|
|
469
|
+
// - `tools: ext:foo` but foo isn't in the loaded set (because `extensions:`
|
|
470
|
+
// didn't include it). Since v0.9, `ext:` no longer pulls extensions in;
|
|
471
|
+
// loading is `extensions:`-authoritative.
|
|
472
|
+
// An exclude_extensions: alongside extensions: false is contradictory — nothing
|
|
473
|
+
// loads, so there is nothing to exclude.
|
|
474
|
+
if (hasExcludes && noExtensions) {
|
|
475
|
+
options.onToolActivity?.({
|
|
476
|
+
type: "end",
|
|
477
|
+
toolName: `extension-error:exclude_extensions has no effect for agent "${type}" — extensions: false loads nothing`,
|
|
478
|
+
});
|
|
479
|
+
}
|
|
480
|
+
// Exclude typo check: compares against the PRE-filter discovered set (an excluded
|
|
481
|
+
// name absent from the surviving set is the exclude working as intended). Also
|
|
482
|
+
// flags path-like and "*" entries — excludes are plain names only.
|
|
483
|
+
if (hasExcludes && discoveredNames) {
|
|
484
|
+
for (const name of excludeNames) {
|
|
485
|
+
if (!discoveredNames.has(name)) {
|
|
430
486
|
options.onToolActivity?.({
|
|
431
487
|
type: "end",
|
|
432
|
-
toolName: `extension-error
|
|
488
|
+
toolName: `extension-error:exclude_extensions: "${name}" for agent "${type}" did not match any discovered extension`,
|
|
433
489
|
});
|
|
434
|
-
},
|
|
435
|
-
});
|
|
436
|
-
|
|
437
|
-
options.onSessionCreated?.(session);
|
|
438
|
-
try {
|
|
439
|
-
const originalDispose = session.dispose?.bind(session);
|
|
440
|
-
if (originalDispose) {
|
|
441
|
-
session.dispose = (() => {
|
|
442
|
-
return originalDispose();
|
|
443
|
-
}) as typeof session.dispose;
|
|
444
|
-
}
|
|
445
|
-
} catch {}
|
|
446
|
-
|
|
447
|
-
let turnCount = 0;
|
|
448
|
-
const maxTurns = normalizeMaxTurns(options.maxTurns ?? agentConfig?.maxTurns ?? defaultMaxTurns);
|
|
449
|
-
let softLimitReached = false;
|
|
450
|
-
let aborted = false;
|
|
451
|
-
let lastTurnError: string | undefined;
|
|
452
|
-
|
|
453
|
-
let currentMessageText = "";
|
|
454
|
-
const unsubTurns = session.subscribe((event: AgentSessionEvent) => {
|
|
455
|
-
traceSubagentEvent(options.subagentId, event, turnCount);
|
|
456
|
-
if (event.type === "turn_end") {
|
|
457
|
-
turnCount++;
|
|
458
|
-
const msg = (event as any).message;
|
|
459
|
-
if (msg?.stopReason === "error") {
|
|
460
|
-
lastTurnError = msg.errorMessage || "Model API error";
|
|
461
|
-
}
|
|
462
|
-
options.onTurnEnd?.(turnCount);
|
|
463
|
-
if (maxTurns != null) {
|
|
464
|
-
if (!softLimitReached && turnCount >= maxTurns) {
|
|
465
|
-
softLimitReached = true;
|
|
466
|
-
session.steer("You have reached your turn limit. Wrap up immediately — provide your final answer now.");
|
|
467
|
-
} else if (softLimitReached && turnCount >= maxTurns + graceTurns) {
|
|
468
|
-
aborted = true;
|
|
469
|
-
session.abort();
|
|
470
|
-
}
|
|
471
|
-
}
|
|
472
|
-
}
|
|
473
|
-
if (event.type === "message_start") {
|
|
474
|
-
currentMessageText = "";
|
|
475
490
|
}
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
if (keepNames.size > 0 || extNames.size > 0) {
|
|
494
|
+
const survivingNames = new Set(
|
|
495
|
+
loader.getExtensions().extensions.map((e) => extensionCanonicalName(e.path)),
|
|
496
|
+
);
|
|
497
|
+
for (const name of keepNames) {
|
|
498
|
+
if (!survivingNames.has(name)) {
|
|
499
|
+
options.onToolActivity?.({
|
|
500
|
+
type: "end",
|
|
501
|
+
toolName: excludeNames.has(name)
|
|
502
|
+
? `extension-error:extension "${name}" is in both extensions: and exclude_extensions: for agent "${type}" — exclude wins`
|
|
503
|
+
: `extension-error:extension "${name}" requested by agent "${type}" was not loaded`,
|
|
504
|
+
});
|
|
482
505
|
}
|
|
483
|
-
|
|
484
|
-
|
|
506
|
+
}
|
|
507
|
+
for (const name of extNames) {
|
|
508
|
+
if (!survivingNames.has(name)) {
|
|
509
|
+
options.onToolActivity?.({
|
|
510
|
+
type: "end",
|
|
511
|
+
toolName: `extension-error:ext:${name} referenced by agent "${type}" but extension "${name}" is not loaded (check extensions:/exclude_extensions:)`,
|
|
512
|
+
});
|
|
485
513
|
}
|
|
486
|
-
}
|
|
487
|
-
|
|
488
|
-
const collector = collectResponseText(session);
|
|
489
|
-
const cleanupAbort = forwardAbortSignal(session, options.signal);
|
|
514
|
+
}
|
|
515
|
+
}
|
|
490
516
|
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
517
|
+
// Resolve model: explicit option > config.model > parent model
|
|
518
|
+
const model = options.model ?? resolveDefaultModel(
|
|
519
|
+
ctx.model, ctx.modelRegistry, agentConfig?.model,
|
|
520
|
+
);
|
|
521
|
+
|
|
522
|
+
// Resolve thinking level: explicit option > agent config > undefined (inherit)
|
|
523
|
+
const thinkingLevel = options.thinkingLevel ?? agentConfig?.thinking;
|
|
524
|
+
|
|
525
|
+
const disallowedSet = agentConfig?.disallowedTools
|
|
526
|
+
? new Set(agentConfig.disallowedTools)
|
|
527
|
+
: undefined;
|
|
528
|
+
|
|
529
|
+
// Enumerate extension-registered tool names from the loaded resource loader.
|
|
530
|
+
// Extensions populate `extension.tools` during `loader.reload()` and the set
|
|
531
|
+
// is stable afterwards — `bindExtensions` does not register new tools.
|
|
532
|
+
//
|
|
533
|
+
// Opt-in flip: when any `ext:` selector is present, extension tools become an
|
|
534
|
+
// explicit allowlist — a loaded extension not named by a selector contributes
|
|
535
|
+
// no tools (its handlers still ran), and `ext:foo/bar` narrows `foo` to `bar`.
|
|
536
|
+
const extensionToolNames: string[] = [];
|
|
537
|
+
if (!noExtensions) {
|
|
538
|
+
const optInActive = extNames.size > 0;
|
|
539
|
+
for (const extension of loader.getExtensions().extensions) {
|
|
540
|
+
const canon = extensionCanonicalName(extension.path);
|
|
541
|
+
if (optInActive && !extNames.has(canon)) continue;
|
|
542
|
+
const narrowed = narrowing.get(canon);
|
|
543
|
+
for (const toolName of extension.tools.keys()) {
|
|
544
|
+
if (narrowed && !narrowed.has(toolName)) continue;
|
|
545
|
+
extensionToolNames.push(toolName);
|
|
496
546
|
}
|
|
497
547
|
}
|
|
548
|
+
}
|
|
498
549
|
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
550
|
+
// Build the master tool allowlist applied at session construction.
|
|
551
|
+
// pi-mono's `allowedToolNames` gates BOTH registration and the initial active
|
|
552
|
+
// set, so listing the exact final set here means the session is correctly
|
|
553
|
+
// scoped from the first instant — no post-construction narrowing required.
|
|
554
|
+
const builtinToolNameSet = new Set(toolNames);
|
|
555
|
+
const allowedTools = [...toolNames, ...extensionToolNames].filter((t) => {
|
|
556
|
+
if (EXCLUDED_TOOL_NAMES.includes(t)) return false;
|
|
557
|
+
if (disallowedSet?.has(t)) return false;
|
|
558
|
+
if (builtinToolNameSet.has(t)) return true;
|
|
559
|
+
// Reached only for extension tools. The extension set was already filtered
|
|
560
|
+
// at the loader (extensionsOverride / noExtensions) and at enumeration
|
|
561
|
+
// (`ext:` opt-in flip), so any extension tool in `extensionToolNames` is allowed.
|
|
562
|
+
return !noExtensions;
|
|
563
|
+
});
|
|
513
564
|
|
|
514
|
-
|
|
515
|
-
|
|
565
|
+
const settingsManager = SettingsManager.create(configCwd, agentDir);
|
|
566
|
+
const configuredSessionDir = resolveConfiguredSessionDir(agentConfig?.sessionDir, effectiveCwd);
|
|
567
|
+
const defaultSessionDir = process.env.PI_CODING_AGENT_SESSION_DIR ?? settingsManager.getSessionDir?.();
|
|
568
|
+
const sessionManager = agentConfig?.persistSession
|
|
569
|
+
? SessionManager.create(effectiveCwd, configuredSessionDir ?? defaultSessionDir)
|
|
570
|
+
: SessionManager.inMemory(effectiveCwd);
|
|
571
|
+
|
|
572
|
+
const sessionOpts: Parameters<typeof createAgentSession>[0] = {
|
|
573
|
+
cwd: effectiveCwd,
|
|
574
|
+
agentDir,
|
|
575
|
+
sessionManager,
|
|
576
|
+
settingsManager,
|
|
577
|
+
modelRegistry: ctx.modelRegistry,
|
|
578
|
+
model,
|
|
579
|
+
tools: allowedTools,
|
|
580
|
+
resourceLoader: loader,
|
|
581
|
+
};
|
|
582
|
+
if (thinkingLevel) {
|
|
583
|
+
sessionOpts.thinkingLevel = thinkingLevel;
|
|
584
|
+
}
|
|
516
585
|
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
586
|
+
const { session } = await createAgentSession(sessionOpts);
|
|
587
|
+
|
|
588
|
+
const baseSessionName = agentConfig?.name ?? type;
|
|
589
|
+
session.setSessionName(
|
|
590
|
+
options.agentId ? `${baseSessionName}#${options.agentId.slice(0, 8)}` : baseSessionName,
|
|
591
|
+
);
|
|
592
|
+
|
|
593
|
+
// Bind extensions so that session_start fires and extensions can initialize
|
|
594
|
+
// (e.g. loading credentials, setting up state). Tool gating already happened
|
|
595
|
+
// at session construction via the `tools:` allowlist above — no separate
|
|
596
|
+
// post-bind filter is needed. All ExtensionBindings fields are optional.
|
|
597
|
+
await session.bindExtensions({
|
|
598
|
+
onError: (err) => {
|
|
599
|
+
options.onToolActivity?.({
|
|
600
|
+
type: "end",
|
|
601
|
+
toolName: `extension-error:${err.extensionPath}`,
|
|
602
|
+
});
|
|
603
|
+
},
|
|
604
|
+
});
|
|
605
|
+
|
|
606
|
+
options.onSessionCreated?.(session);
|
|
607
|
+
|
|
608
|
+
// Track turns for graceful max_turns enforcement
|
|
609
|
+
let turnCount = 0;
|
|
610
|
+
const maxTurns = normalizeMaxTurns(options.maxTurns ?? agentConfig?.maxTurns ?? defaultMaxTurns);
|
|
611
|
+
let softLimitReached = false;
|
|
612
|
+
let aborted = false;
|
|
613
|
+
|
|
614
|
+
let currentMessageText = "";
|
|
615
|
+
const unsubTurns = session.subscribe((event: AgentSessionEvent) => {
|
|
616
|
+
if (event.type === "turn_end") {
|
|
617
|
+
turnCount++;
|
|
618
|
+
options.onTurnEnd?.(turnCount);
|
|
619
|
+
if (maxTurns != null) {
|
|
620
|
+
if (!softLimitReached && turnCount >= maxTurns) {
|
|
621
|
+
softLimitReached = true;
|
|
622
|
+
session.steer("You have reached your turn limit. Wrap up immediately — provide your final answer now.");
|
|
623
|
+
} else if (softLimitReached && turnCount >= maxTurns + graceTurns) {
|
|
624
|
+
aborted = true;
|
|
625
|
+
session.abort();
|
|
524
626
|
}
|
|
525
627
|
}
|
|
526
|
-
} finally {
|
|
527
|
-
unsubTurns();
|
|
528
|
-
collector.unsubscribe();
|
|
529
|
-
cleanupAbort();
|
|
530
628
|
}
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
629
|
+
if (event.type === "message_start") {
|
|
630
|
+
currentMessageText = "";
|
|
631
|
+
}
|
|
632
|
+
if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") {
|
|
633
|
+
currentMessageText += event.assistantMessageEvent.delta;
|
|
634
|
+
options.onTextDelta?.(event.assistantMessageEvent.delta, currentMessageText);
|
|
635
|
+
}
|
|
636
|
+
if (event.type === "tool_execution_start") {
|
|
637
|
+
options.onToolActivity?.({ type: "start", toolName: event.toolName });
|
|
534
638
|
}
|
|
639
|
+
if (event.type === "tool_execution_end") {
|
|
640
|
+
options.onToolActivity?.({ type: "end", toolName: event.toolName });
|
|
641
|
+
}
|
|
642
|
+
if (event.type === "message_end" && event.message.role === "assistant") {
|
|
643
|
+
const u = (event.message as any).usage;
|
|
644
|
+
if (u) options.onAssistantUsage?.({
|
|
645
|
+
input: u.input ?? 0,
|
|
646
|
+
output: u.output ?? 0,
|
|
647
|
+
cacheWrite: u.cacheWrite ?? 0,
|
|
648
|
+
});
|
|
649
|
+
}
|
|
650
|
+
if (event.type === "compaction_end" && !event.aborted && event.result) {
|
|
651
|
+
options.onCompaction?.({ reason: event.reason, tokensBefore: event.result.tokensBefore });
|
|
652
|
+
}
|
|
653
|
+
});
|
|
654
|
+
|
|
655
|
+
const collector = collectResponseText(session);
|
|
656
|
+
const cleanupAbort = forwardAbortSignal(session, options.signal);
|
|
535
657
|
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
658
|
+
// Build the effective prompt: optionally prepend parent context
|
|
659
|
+
let effectivePrompt = prompt;
|
|
660
|
+
if (options.inheritContext) {
|
|
661
|
+
const parentContext = buildParentContext(ctx);
|
|
662
|
+
if (parentContext) {
|
|
663
|
+
effectivePrompt = parentContext + prompt;
|
|
540
664
|
}
|
|
541
|
-
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
try {
|
|
668
|
+
await session.prompt(effectivePrompt);
|
|
542
669
|
} finally {
|
|
543
|
-
|
|
670
|
+
unsubTurns();
|
|
671
|
+
collector.unsubscribe();
|
|
672
|
+
cleanupAbort();
|
|
544
673
|
}
|
|
545
|
-
|
|
674
|
+
|
|
675
|
+
const responseText = collector.getText().trim() || getLastAssistantText(session);
|
|
676
|
+
return { responseText, session, aborted, steered: softLimitReached };
|
|
546
677
|
}
|
|
547
678
|
|
|
548
679
|
/**
|
|
@@ -551,34 +682,39 @@ export async function runAgent(
|
|
|
551
682
|
export async function resumeAgent(
|
|
552
683
|
session: AgentSession,
|
|
553
684
|
prompt: string,
|
|
554
|
-
options: {
|
|
685
|
+
options: {
|
|
686
|
+
onToolActivity?: (activity: ToolActivity) => void;
|
|
687
|
+
onAssistantUsage?: (usage: { input: number; output: number; cacheWrite: number }) => void;
|
|
688
|
+
onCompaction?: (info: { reason: "manual" | "threshold" | "overflow"; tokensBefore: number }) => void;
|
|
689
|
+
signal?: AbortSignal;
|
|
690
|
+
} = {},
|
|
555
691
|
): Promise<string> {
|
|
556
692
|
const collector = collectResponseText(session);
|
|
557
693
|
const cleanupAbort = forwardAbortSignal(session, options.signal);
|
|
558
694
|
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
695
|
+
const unsubEvents = (options.onToolActivity || options.onAssistantUsage || options.onCompaction)
|
|
696
|
+
? session.subscribe((event: AgentSessionEvent) => {
|
|
697
|
+
if (event.type === "tool_execution_start") options.onToolActivity?.({ type: "start", toolName: event.toolName });
|
|
698
|
+
if (event.type === "tool_execution_end") options.onToolActivity?.({ type: "end", toolName: event.toolName });
|
|
699
|
+
if (event.type === "message_end" && event.message.role === "assistant") {
|
|
700
|
+
const u = (event.message as any).usage;
|
|
701
|
+
if (u) options.onAssistantUsage?.({
|
|
702
|
+
input: u.input ?? 0,
|
|
703
|
+
output: u.output ?? 0,
|
|
704
|
+
cacheWrite: u.cacheWrite ?? 0,
|
|
705
|
+
});
|
|
706
|
+
}
|
|
707
|
+
if (event.type === "compaction_end" && !event.aborted && event.result) {
|
|
708
|
+
options.onCompaction?.({ reason: event.reason, tokensBefore: event.result.tokensBefore });
|
|
709
|
+
}
|
|
710
|
+
})
|
|
711
|
+
: () => {};
|
|
576
712
|
|
|
577
713
|
try {
|
|
578
714
|
await session.prompt(prompt);
|
|
579
715
|
} finally {
|
|
580
716
|
collector.unsubscribe();
|
|
581
|
-
|
|
717
|
+
unsubEvents();
|
|
582
718
|
cleanupAbort();
|
|
583
719
|
}
|
|
584
720
|
|