@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,850 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* agent-runner.ts — Core execution engine: creates sessions, runs agents, collects results.
|
|
3
|
+
*/
|
|
4
|
+
import { readFileSync } from "node:fs";
|
|
5
|
+
import { homedir } from "node:os";
|
|
6
|
+
import { basename, dirname, isAbsolute, join, resolve } from "node:path";
|
|
7
|
+
import { createAgentSession, DefaultResourceLoader, getAgentDir, SessionManager, SettingsManager, } from "@earendil-works/pi-coding-agent";
|
|
8
|
+
import { BUILTIN_TOOL_NAMES, getAgentConfig, getConfig, getMemoryToolNames, getReadOnlyMemoryToolNames, getToolNamesForType } from "./agent-types.js";
|
|
9
|
+
import { buildParentContext, extractText } from "./context.js";
|
|
10
|
+
import { DEFAULT_AGENTS } from "./default-agents.js";
|
|
11
|
+
import { detectEnv } from "./env.js";
|
|
12
|
+
import { buildMemoryBlock, buildReadOnlyMemoryBlock } from "./memory.js";
|
|
13
|
+
import { buildAgentPrompt } from "./prompts.js";
|
|
14
|
+
import { preloadSkills } from "./skill-loader.js";
|
|
15
|
+
/**
|
|
16
|
+
* Tool names registered by THIS extension. Single source of truth so the
|
|
17
|
+
* registration sites (index.ts) and the subagent exclusion list below can't
|
|
18
|
+
* drift apart. These are our own tools, not pi built-ins, so they can't be
|
|
19
|
+
* derived from pi — but they only need defining once.
|
|
20
|
+
*/
|
|
21
|
+
export const SUBAGENT_TOOL_NAMES = {
|
|
22
|
+
AGENT: "Agent",
|
|
23
|
+
GET_RESULT: "get_subagent_result",
|
|
24
|
+
STEER: "steer_subagent",
|
|
25
|
+
};
|
|
26
|
+
/** Names of tools registered by this extension that subagents must NOT inherit. */
|
|
27
|
+
const EXCLUDED_TOOL_NAMES = Object.values(SUBAGENT_TOOL_NAMES);
|
|
28
|
+
/**
|
|
29
|
+
* Canonical name of an extension for `extensions: [...]` allowlist matching.
|
|
30
|
+
* Lowercased — extension names match case-insensitively so `extensions: [Mcp]`
|
|
31
|
+
* resolves the same as `[mcp]`. Tool names within `ext:foo/bar` are not affected.
|
|
32
|
+
* Directory extensions (`foo/index.ts`) resolve to the parent directory name;
|
|
33
|
+
* single-file extensions to the basename minus `.ts`/`.js`.
|
|
34
|
+
*/
|
|
35
|
+
export function extensionCanonicalName(extPath) {
|
|
36
|
+
const base = basename(extPath);
|
|
37
|
+
const name = base === "index.ts" || base === "index.js"
|
|
38
|
+
? basename(dirname(extPath))
|
|
39
|
+
: base.replace(/\.(ts|js)$/, "");
|
|
40
|
+
return name.toLowerCase();
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* The unscoped, lowercased npm short name of the pi package that DECLARES
|
|
44
|
+
* `extPath` as an extension entry — or undefined if the entry doesn't belong to
|
|
45
|
+
* such a package.
|
|
46
|
+
*
|
|
47
|
+
* Climbs from the entry's directory looking for the package that owns it, and
|
|
48
|
+
* stays strictly within that package's tree by stopping at two structural
|
|
49
|
+
* boundaries — no hardcoded depth:
|
|
50
|
+
* - the FIRST `package.json` found (the package root); the entry's own
|
|
51
|
+
* manifest always sits at the root, above the entry, below any node_modules.
|
|
52
|
+
* - a `node_modules` directory: a package never spans one (it's where OTHER
|
|
53
|
+
* packages live), so reaching it means we've climbed out of the package —
|
|
54
|
+
* stop before reading a consumer's or parent package's manifest.
|
|
55
|
+
* The name is then taken only when that root's `pi.extensions` manifest actually
|
|
56
|
+
* lists this entry. That "declares this entry" check is deliberate: our own test
|
|
57
|
+
* fixtures live under this repo, whose root manifest declares `./src/index.ts`
|
|
58
|
+
* as `@tintinweb/pi-subagents`, so a looser rule would misattribute every
|
|
59
|
+
* co-located file to `pi-subagents`.
|
|
60
|
+
*/
|
|
61
|
+
function extensionPackageName(extPath) {
|
|
62
|
+
const entry = resolve(extPath);
|
|
63
|
+
let dir = dirname(extPath);
|
|
64
|
+
for (;;) {
|
|
65
|
+
// Climbing into node_modules means we've left the owning package's tree.
|
|
66
|
+
if (basename(dir) === "node_modules")
|
|
67
|
+
return undefined;
|
|
68
|
+
let pkg;
|
|
69
|
+
try {
|
|
70
|
+
pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf-8"));
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
const parent = dirname(dir);
|
|
74
|
+
if (parent === dir)
|
|
75
|
+
return undefined; // walked to the filesystem root
|
|
76
|
+
dir = parent;
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
// First package.json wins — it's the package root; decide here.
|
|
80
|
+
const entries = pkg.pi?.extensions;
|
|
81
|
+
if (typeof pkg.name === "string" &&
|
|
82
|
+
Array.isArray(entries) &&
|
|
83
|
+
entries.some((e) => typeof e === "string" && resolve(dir, e) === entry)) {
|
|
84
|
+
const short = pkg.name.startsWith("@") ? pkg.name.slice(pkg.name.indexOf("/") + 1) : pkg.name;
|
|
85
|
+
return short.toLowerCase();
|
|
86
|
+
}
|
|
87
|
+
return undefined;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* All names an extension answers to for allowlist matching (lowercased): its
|
|
92
|
+
* path-derived {@link extensionCanonicalName} plus, when a pi package manifest
|
|
93
|
+
* declares this entry, that package's unscoped short name (`@scope/foo` → `foo`).
|
|
94
|
+
* #143: an extension installed via `pi.extensions: ["./src/index.ts"]` would
|
|
95
|
+
* otherwise only ever match as `src` (the source directory), never by its
|
|
96
|
+
* package name. The path-derived name is preserved, so it keeps matching too.
|
|
97
|
+
*/
|
|
98
|
+
export function extensionCanonicalNames(extPath) {
|
|
99
|
+
const canonical = extensionCanonicalName(extPath);
|
|
100
|
+
const pkg = extensionPackageName(extPath);
|
|
101
|
+
return pkg && pkg !== canonical ? [canonical, pkg] : [canonical];
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Classify `extensions: string[]` frontmatter entries for the loader-level filter.
|
|
105
|
+
*
|
|
106
|
+
* An entry is a PATH iff it contains a path separator or starts with `~`; otherwise
|
|
107
|
+
* it is a NAME. `"*"` sets the wildcard flag (keep all default-discovered extensions).
|
|
108
|
+
*
|
|
109
|
+
* Path entries are resolved (`~` expanded, made absolute against `cwd`) into `paths`
|
|
110
|
+
* — and their canonical name is also added to `names`. The loader override matches
|
|
111
|
+
* everything by canonical name, so path-loaded extensions are matched via their name
|
|
112
|
+
* rather than their post-staging `Extension.path`.
|
|
113
|
+
*/
|
|
114
|
+
export function parseExtensionsSpec(entries, cwd) {
|
|
115
|
+
const names = new Set();
|
|
116
|
+
const paths = [];
|
|
117
|
+
let wildcard = false;
|
|
118
|
+
for (const entry of entries) {
|
|
119
|
+
if (!entry)
|
|
120
|
+
continue;
|
|
121
|
+
if (entry === "*") {
|
|
122
|
+
wildcard = true;
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
const isPathEntry = entry.includes("/") || entry.includes("\\") || entry.startsWith("~");
|
|
126
|
+
if (!isPathEntry) {
|
|
127
|
+
names.add(entry.toLowerCase());
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
let p = entry;
|
|
131
|
+
if (p === "~" || p.startsWith("~/") || p.startsWith("~\\")) {
|
|
132
|
+
p = homedir() + p.slice(1);
|
|
133
|
+
}
|
|
134
|
+
const abs = isAbsolute(p) ? p : resolve(cwd, p);
|
|
135
|
+
paths.push(abs);
|
|
136
|
+
names.add(extensionCanonicalName(abs));
|
|
137
|
+
}
|
|
138
|
+
return { names, paths, wildcard };
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Parse raw `ext:` selector strings (from the `tools:` CSV) into the set of
|
|
142
|
+
* extension names to keep loaded and a per-extension tool-narrowing map.
|
|
143
|
+
*
|
|
144
|
+
* `ext:foo` → `extNames` has `foo`, no narrowing entry (all of foo's tools).
|
|
145
|
+
* `ext:foo/bar` → `extNames` has `foo`, `narrowing.foo` has `bar` (only `bar`).
|
|
146
|
+
* A name lands in `narrowing` only when a `/tool` form is seen, so a bare
|
|
147
|
+
* `ext:foo` alongside `ext:foo/bar` leaves narrowing in effect (narrowing wins).
|
|
148
|
+
* The split is on the first `/`; extension canonical names never contain `/`.
|
|
149
|
+
*/
|
|
150
|
+
export function parseExtSelectors(entries) {
|
|
151
|
+
const extNames = new Set();
|
|
152
|
+
const narrowing = new Map();
|
|
153
|
+
for (const raw of entries) {
|
|
154
|
+
if (!raw)
|
|
155
|
+
continue;
|
|
156
|
+
const body = raw.slice("ext:".length);
|
|
157
|
+
const slash = body.indexOf("/");
|
|
158
|
+
// Extension name matches case-insensitively (matches the loader-side canonical
|
|
159
|
+
// name). Tool names are case-preserved — they're matched against pi-mono's
|
|
160
|
+
// registered identifiers, which are case-sensitive.
|
|
161
|
+
const name = (slash === -1 ? body : body.slice(0, slash)).trim().toLowerCase();
|
|
162
|
+
if (!name)
|
|
163
|
+
continue;
|
|
164
|
+
extNames.add(name);
|
|
165
|
+
if (slash === -1)
|
|
166
|
+
continue;
|
|
167
|
+
const tool = body.slice(slash + 1).trim();
|
|
168
|
+
if (!tool)
|
|
169
|
+
continue;
|
|
170
|
+
let set = narrowing.get(name);
|
|
171
|
+
if (!set) {
|
|
172
|
+
set = new Set();
|
|
173
|
+
narrowing.set(name, set);
|
|
174
|
+
}
|
|
175
|
+
set.add(tool);
|
|
176
|
+
}
|
|
177
|
+
return { extNames, narrowing };
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Keep a subagent's tool scope correct as extensions register tools over time.
|
|
181
|
+
*
|
|
182
|
+
* Extensions may call `registerTool` long after load — pi-mcp from `session_start`,
|
|
183
|
+
* context-mode from `before_agent_start` — so scope has to be re-derived rather than
|
|
184
|
+
* snapshotted. `registerTool` writes into the very `extension.tools` maps this reads,
|
|
185
|
+
* so `inScope()` sees late arrivals on the next call.
|
|
186
|
+
*
|
|
187
|
+
* Two enforcement points, because neither covers the whole picture:
|
|
188
|
+
*
|
|
189
|
+
* - `turn_end` re-narrows the ACTIVE set. pi emits `turn_end` immediately before
|
|
190
|
+
* `prepareNextTurn` re-snapshots `agent.state.tools`, and session listeners run
|
|
191
|
+
* synchronously, so the narrow lands in time for turns 2..N.
|
|
192
|
+
* - `beforeToolCall` blocks out-of-scope calls. Turn 1 cannot be narrowed at all:
|
|
193
|
+
* `before_agent_start` fires INSIDE `prompt()` and may widen the tool set, but
|
|
194
|
+
* `createContextSnapshot()` freezes that turn's tools immediately after — there
|
|
195
|
+
* is no hook in between. A call-time check is the only correct guard there.
|
|
196
|
+
*
|
|
197
|
+
* Both are installed on the session and deliberately NOT unsubscribed: they must
|
|
198
|
+
* outlive the `runAgent` call so resumed/steered turns stay scoped. pi's `dispose()`
|
|
199
|
+
* clears `_eventListeners`, so they die with the session rather than leaking.
|
|
200
|
+
*
|
|
201
|
+
* Only meaningful when extensions are loaded — under `noExtensions`/`isolated` the
|
|
202
|
+
* static `allowedToolNames` allowlist already gates the registry itself.
|
|
203
|
+
*/
|
|
204
|
+
export function installExtensionToolScope(session, ctx) {
|
|
205
|
+
const { loader, toolNames, disallowedSet, extNames, narrowing } = ctx;
|
|
206
|
+
// The names allowed right now. Mirrors the `ext:` opt-in flip: when any `ext:`
|
|
207
|
+
// selector is present, extension tools become an explicit allowlist — a loaded
|
|
208
|
+
// extension not named by a selector contributes nothing (its handlers still ran),
|
|
209
|
+
// and `ext:foo/bar` narrows `foo` to just `bar`.
|
|
210
|
+
const inScope = () => {
|
|
211
|
+
const keep = new Set(toolNames.filter((t) => !disallowedSet?.has(t)));
|
|
212
|
+
const optInActive = extNames.size > 0;
|
|
213
|
+
for (const extension of loader.getExtensions().extensions) {
|
|
214
|
+
const canons = extensionCanonicalNames(extension.path);
|
|
215
|
+
if (optInActive && !canons.some((c) => extNames.has(c)))
|
|
216
|
+
continue;
|
|
217
|
+
// First alias that carries a narrowing set — a user won't narrow one
|
|
218
|
+
// extension under two different names, so first-match is correct.
|
|
219
|
+
const narrowed = canons.map((c) => narrowing.get(c)).find(Boolean);
|
|
220
|
+
for (const name of extension.tools.keys()) {
|
|
221
|
+
if (narrowed && !narrowed.has(name))
|
|
222
|
+
continue;
|
|
223
|
+
if (disallowedSet?.has(name))
|
|
224
|
+
continue;
|
|
225
|
+
keep.add(name);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
for (const name of EXCLUDED_TOOL_NAMES)
|
|
229
|
+
keep.delete(name);
|
|
230
|
+
return keep;
|
|
231
|
+
};
|
|
232
|
+
const renarrow = () => {
|
|
233
|
+
const allowed = inScope();
|
|
234
|
+
const next = session.getAllTools().map((t) => t.name).filter((n) => allowed.has(n));
|
|
235
|
+
const current = session.getActiveToolNames();
|
|
236
|
+
// setActiveToolsByName unconditionally rebuilds the system prompt, so skip
|
|
237
|
+
// the no-op that steady-state turns would otherwise pay for every turn.
|
|
238
|
+
if (next.length !== current.length || next.some((n, i) => n !== current[i])) {
|
|
239
|
+
session.setActiveToolsByName(next);
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
// Activate what registered during session_start (eager MCP servers); pi would
|
|
243
|
+
// otherwise leave only its four default built-ins active at turn 1.
|
|
244
|
+
renarrow();
|
|
245
|
+
session.subscribe((event) => {
|
|
246
|
+
if (event.type === "turn_end")
|
|
247
|
+
renarrow();
|
|
248
|
+
});
|
|
249
|
+
const priorBeforeToolCall = session.agent.beforeToolCall;
|
|
250
|
+
session.agent.beforeToolCall = async (context, signal) => {
|
|
251
|
+
if (!inScope().has(context.toolCall.name)) {
|
|
252
|
+
return {
|
|
253
|
+
block: true,
|
|
254
|
+
reason: `Tool "${context.toolCall.name}" is not available to this subagent.`,
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
return priorBeforeToolCall?.(context, signal);
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
/** Default max turns. undefined = unlimited (no turn limit). */
|
|
261
|
+
let defaultMaxTurns;
|
|
262
|
+
/** Normalize max turns. undefined or 0 = unlimited, otherwise minimum 1. */
|
|
263
|
+
export function normalizeMaxTurns(n) {
|
|
264
|
+
if (n == null || n === 0)
|
|
265
|
+
return undefined;
|
|
266
|
+
return Math.max(1, n);
|
|
267
|
+
}
|
|
268
|
+
/** Get the default max turns value. undefined = unlimited. */
|
|
269
|
+
export function getDefaultMaxTurns() { return defaultMaxTurns; }
|
|
270
|
+
/** Set the default max turns value. undefined or 0 = unlimited, otherwise minimum 1. */
|
|
271
|
+
export function setDefaultMaxTurns(n) { defaultMaxTurns = normalizeMaxTurns(n); }
|
|
272
|
+
/** Additional turns allowed after the soft limit steer message. */
|
|
273
|
+
let graceTurns = 5;
|
|
274
|
+
/** Get the grace turns value. */
|
|
275
|
+
export function getGraceTurns() { return graceTurns; }
|
|
276
|
+
/** Set the grace turns value (minimum 1). */
|
|
277
|
+
export function setGraceTurns(n) { graceTurns = Math.max(1, n); }
|
|
278
|
+
/**
|
|
279
|
+
* Try to find the right model for an agent type.
|
|
280
|
+
* Priority: explicit option > config.model > parent model.
|
|
281
|
+
*/
|
|
282
|
+
function resolveDefaultModel(parentModel, registry, configModel) {
|
|
283
|
+
if (configModel) {
|
|
284
|
+
const slashIdx = configModel.indexOf("/");
|
|
285
|
+
if (slashIdx !== -1) {
|
|
286
|
+
const provider = configModel.slice(0, slashIdx);
|
|
287
|
+
const modelId = configModel.slice(slashIdx + 1);
|
|
288
|
+
// Build a set of available model keys for fast lookup
|
|
289
|
+
const available = registry.getAvailable?.();
|
|
290
|
+
const availableKeys = available
|
|
291
|
+
? new Set(available.map((m) => `${m.provider}/${m.id}`))
|
|
292
|
+
: undefined;
|
|
293
|
+
const isAvailable = (p, id) => !availableKeys || availableKeys.has(`${p}/${id}`);
|
|
294
|
+
const found = registry.find(provider, modelId);
|
|
295
|
+
if (found && isAvailable(provider, modelId))
|
|
296
|
+
return found;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
return parentModel;
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* Subscribe to a session and collect the last assistant message text.
|
|
303
|
+
* Returns an object with a `getText()` getter and an `unsubscribe` function.
|
|
304
|
+
*/
|
|
305
|
+
function collectResponseText(session) {
|
|
306
|
+
let text = "";
|
|
307
|
+
const unsubscribe = session.subscribe((event) => {
|
|
308
|
+
// message_start also fires for user and toolResult messages — resetting on
|
|
309
|
+
// those would wipe assistant text already collected. Reset only when a new
|
|
310
|
+
// ASSISTANT message begins, so getText() is the last assistant message's text.
|
|
311
|
+
if (event.type === "message_start" && event.message.role === "assistant") {
|
|
312
|
+
text = "";
|
|
313
|
+
}
|
|
314
|
+
if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") {
|
|
315
|
+
text += event.assistantMessageEvent.delta;
|
|
316
|
+
}
|
|
317
|
+
});
|
|
318
|
+
return { getText: () => text, unsubscribe };
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* Get the last non-empty assistant text produced during THIS invocation.
|
|
322
|
+
* `startIndex` is the message count captured before the prompt, so the walk-back
|
|
323
|
+
* never crosses into a previous turn: on a resume whose new turn failed empty,
|
|
324
|
+
* this returns "" instead of the prior turn's answer (#144). Defaults to 0 (a
|
|
325
|
+
* fresh spawn, where the whole history belongs to this run).
|
|
326
|
+
*/
|
|
327
|
+
function getLastAssistantText(session, startIndex = 0) {
|
|
328
|
+
for (let i = session.messages.length - 1; i >= startIndex; i--) {
|
|
329
|
+
const msg = session.messages[i];
|
|
330
|
+
if (msg.role !== "assistant")
|
|
331
|
+
continue;
|
|
332
|
+
const text = extractText(msg.content).trim();
|
|
333
|
+
if (text)
|
|
334
|
+
return text;
|
|
335
|
+
}
|
|
336
|
+
return "";
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* Error message of THIS invocation's final assistant message, when that turn
|
|
340
|
+
* failed. Two failure shapes, both keyed off how the final turn STOPPED:
|
|
341
|
+
* - stopReason "error": a provider failure pi resolved instead of rejecting
|
|
342
|
+
* (any text; partial output is surfaced separately).
|
|
343
|
+
* - stopReason "length" with NO text: a silent max-token death — the run hit
|
|
344
|
+
* the output-token ceiling before writing anything, which would otherwise
|
|
345
|
+
* land as a "completed" run with an empty result (the #144 symptom).
|
|
346
|
+
* Everything else completes: a clean "stop"/"toolUse" final, and — crucially — a
|
|
347
|
+
* "length" stop that DID produce text (a legitimate truncated-but-useful answer).
|
|
348
|
+
* "aborted" is handled by the manager's abort flag / "stopped" guard, not here.
|
|
349
|
+
* Bounded by `startIndex` (like the text fallback) so a resume that produced no
|
|
350
|
+
* assistant message of its own never inherits a PRIOR turn's stop reason.
|
|
351
|
+
*/
|
|
352
|
+
function finalTurnError(session, startIndex = 0) {
|
|
353
|
+
for (let i = session.messages.length - 1; i >= startIndex; i--) {
|
|
354
|
+
const msg = session.messages[i];
|
|
355
|
+
if (msg.role !== "assistant")
|
|
356
|
+
continue;
|
|
357
|
+
if (msg.stopReason === "error") {
|
|
358
|
+
return msg.errorMessage?.trim() || "provider error with no output";
|
|
359
|
+
}
|
|
360
|
+
if (msg.stopReason === "length" && !extractText(msg.content).trim()) {
|
|
361
|
+
return "run hit the output token limit before producing any text";
|
|
362
|
+
}
|
|
363
|
+
return undefined;
|
|
364
|
+
}
|
|
365
|
+
return undefined;
|
|
366
|
+
}
|
|
367
|
+
/**
|
|
368
|
+
* Wire an AbortSignal to abort a session.
|
|
369
|
+
* Returns a cleanup function to remove the listener.
|
|
370
|
+
*/
|
|
371
|
+
function forwardAbortSignal(session, signal) {
|
|
372
|
+
if (!signal)
|
|
373
|
+
return () => { };
|
|
374
|
+
const onAbort = () => session.abort();
|
|
375
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
376
|
+
return () => signal.removeEventListener("abort", onAbort);
|
|
377
|
+
}
|
|
378
|
+
function resolveConfiguredSessionDir(sessionDir, cwd) {
|
|
379
|
+
if (!sessionDir)
|
|
380
|
+
return undefined;
|
|
381
|
+
if (sessionDir === "~" || sessionDir.startsWith("~/"))
|
|
382
|
+
return resolve(homedir(), sessionDir.slice(2));
|
|
383
|
+
if (isAbsolute(sessionDir))
|
|
384
|
+
return sessionDir;
|
|
385
|
+
return resolve(cwd, sessionDir);
|
|
386
|
+
}
|
|
387
|
+
export async function runAgent(ctx, type, prompt, options) {
|
|
388
|
+
const config = getConfig(type);
|
|
389
|
+
const agentConfig = getAgentConfig(type);
|
|
390
|
+
// Resolve working directory: worktree override > parent cwd
|
|
391
|
+
const effectiveCwd = options.cwd ?? ctx.cwd;
|
|
392
|
+
// Filesystem work happens in effectiveCwd; config discovery in configCwd.
|
|
393
|
+
// They differ only for SpawnOptions.cwd spawns (config stays with the parent).
|
|
394
|
+
const configCwd = options.configCwd ?? effectiveCwd;
|
|
395
|
+
const env = await detectEnv(options.pi, effectiveCwd);
|
|
396
|
+
// Get parent system prompt for append-mode agents
|
|
397
|
+
const parentSystemPrompt = ctx.getSystemPrompt();
|
|
398
|
+
// Build prompt extras (memory, skill preloading)
|
|
399
|
+
const extras = {};
|
|
400
|
+
// Resolve extensions/skills: isolated overrides to false
|
|
401
|
+
const extensions = options.isolated ? false : config.extensions;
|
|
402
|
+
// Nulling excludes under isolated also suppresses the orphaned-exclude warning —
|
|
403
|
+
// isolation is an intentional override, not a misconfiguration.
|
|
404
|
+
const excludeExtensions = options.isolated ? undefined : config.excludeExtensions;
|
|
405
|
+
const skills = options.isolated ? false : config.skills;
|
|
406
|
+
// Skill preloading: when skills is string[], preload their content into prompt
|
|
407
|
+
if (Array.isArray(skills)) {
|
|
408
|
+
const loaded = preloadSkills(skills, configCwd);
|
|
409
|
+
if (loaded.length > 0) {
|
|
410
|
+
extras.skillBlocks = loaded;
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
let toolNames = getToolNamesForType(type);
|
|
414
|
+
// Persistent memory: detect write capability and branch accordingly.
|
|
415
|
+
// Account for disallowedTools — a tool in the base set but on the denylist is not truly available.
|
|
416
|
+
if (agentConfig?.memory) {
|
|
417
|
+
const existingNames = new Set(toolNames);
|
|
418
|
+
const denied = agentConfig.disallowedTools ? new Set(agentConfig.disallowedTools) : undefined;
|
|
419
|
+
const effectivelyHas = (name) => existingNames.has(name) && !denied?.has(name);
|
|
420
|
+
const hasWriteTools = effectivelyHas("write") || effectivelyHas("edit");
|
|
421
|
+
if (hasWriteTools) {
|
|
422
|
+
// Read-write memory: add any missing memory tool names (read/write/edit)
|
|
423
|
+
const extraNames = getMemoryToolNames(existingNames);
|
|
424
|
+
if (extraNames.length > 0)
|
|
425
|
+
toolNames = [...toolNames, ...extraNames];
|
|
426
|
+
extras.memoryBlock = buildMemoryBlock(agentConfig.name, agentConfig.memory, configCwd);
|
|
427
|
+
}
|
|
428
|
+
else {
|
|
429
|
+
// Read-only memory: only add read tool name, use read-only prompt
|
|
430
|
+
const extraNames = getReadOnlyMemoryToolNames(existingNames);
|
|
431
|
+
if (extraNames.length > 0)
|
|
432
|
+
toolNames = [...toolNames, ...extraNames];
|
|
433
|
+
extras.memoryBlock = buildReadOnlyMemoryBlock(agentConfig.name, agentConfig.memory, configCwd);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
// Build system prompt from agent config
|
|
437
|
+
let systemPrompt;
|
|
438
|
+
if (agentConfig) {
|
|
439
|
+
systemPrompt = buildAgentPrompt(agentConfig, effectiveCwd, env, parentSystemPrompt, extras);
|
|
440
|
+
}
|
|
441
|
+
else {
|
|
442
|
+
// Unknown type fallback: spread the canonical general-purpose config (defensive —
|
|
443
|
+
// unreachable in practice since index.ts resolves unknown types before calling runAgent).
|
|
444
|
+
const fallback = DEFAULT_AGENTS.get("general-purpose");
|
|
445
|
+
if (!fallback)
|
|
446
|
+
throw new Error(`No fallback config available for unknown type "${type}"`);
|
|
447
|
+
systemPrompt = buildAgentPrompt({ ...fallback, name: type }, effectiveCwd, env, parentSystemPrompt, extras);
|
|
448
|
+
}
|
|
449
|
+
// When skills is string[], we've already preloaded them into the prompt.
|
|
450
|
+
// Still pass noSkills: true since we don't need the skill loader to load them again.
|
|
451
|
+
const noSkills = skills === false || Array.isArray(skills);
|
|
452
|
+
const agentDir = getAgentDir();
|
|
453
|
+
// Extension loading:
|
|
454
|
+
// - true → all default-discovered extensions
|
|
455
|
+
// - false → none (noExtensions)
|
|
456
|
+
// - string[] → loader-level allowlist. Bare names keep the matching
|
|
457
|
+
// default-discovered extension; path entries load that extension fresh;
|
|
458
|
+
// "*" keeps all default-discovered extensions. Excluded extensions never
|
|
459
|
+
// bind handlers or register tools (their factory still runs once).
|
|
460
|
+
//
|
|
461
|
+
// Suppress AGENTS.md/CLAUDE.md and APPEND_SYSTEM.md — upstream's
|
|
462
|
+
// buildSystemPrompt() re-appends both AFTER systemPromptOverride, which
|
|
463
|
+
// would defeat prompt_mode: replace and isolated: true. Parent context, if
|
|
464
|
+
// wanted, reaches the subagent via prompt_mode: append (parentSystemPrompt
|
|
465
|
+
// is embedded in systemPromptOverride) or inherit_context (conversation).
|
|
466
|
+
// `ext:` selectors from the `tools:` CSV narrow which extension tools surface to
|
|
467
|
+
// the LLM. They do NOT control loading — `extensions:` is the sole authority for
|
|
468
|
+
// which extensions load. `ext:foo` against an extension that `extensions:` excluded
|
|
469
|
+
// is an orphan and warns after reload. `isolated` means no extension tools at all.
|
|
470
|
+
const { extNames, narrowing } = parseExtSelectors(options.isolated ? [] : (agentConfig?.extSelectors ?? []));
|
|
471
|
+
const noExtensions = extensions === false;
|
|
472
|
+
const extensionsSpec = Array.isArray(extensions)
|
|
473
|
+
? parseExtensionsSpec(extensions, configCwd)
|
|
474
|
+
: undefined;
|
|
475
|
+
const keepNames = extensionsSpec?.names ?? new Set();
|
|
476
|
+
// `exclude_extensions:` is a denylist applied AFTER the include set — exclude wins.
|
|
477
|
+
// Plain canonical names only (case-insensitive). Note: excluded extensions'
|
|
478
|
+
// factories still run once during reload() (see comment above) — exclusion
|
|
479
|
+
// suppresses handler binding and tool registration; it is not a sandbox.
|
|
480
|
+
const excludeNames = new Set((excludeExtensions ?? []).map((n) => n.toLowerCase()));
|
|
481
|
+
const hasExcludes = excludeNames.size > 0;
|
|
482
|
+
// The override filters loaded extensions down to `keepNames` minus `excludeNames`.
|
|
483
|
+
// It's only needed when we're neither loading everything without excludes
|
|
484
|
+
// (`extensions: true` or a `"*"` wildcard) nor nothing (`noExtensions`).
|
|
485
|
+
const loadAll = extensions === true || extensionsSpec?.wildcard === true;
|
|
486
|
+
const additionalExtensionPaths = extensionsSpec?.paths.length ? extensionsSpec.paths : undefined;
|
|
487
|
+
// Pre-filter discovered set, captured by the override — the exclude-typo warning
|
|
488
|
+
// must compare against this, not the surviving set (absence from survivors is
|
|
489
|
+
// an exclude *succeeding*).
|
|
490
|
+
let discoveredNames;
|
|
491
|
+
const extensionsOverride = noExtensions || (loadAll && !hasExcludes)
|
|
492
|
+
? undefined
|
|
493
|
+
: (base) => {
|
|
494
|
+
discoveredNames = new Set(base.extensions.flatMap((e) => extensionCanonicalNames(e.path)));
|
|
495
|
+
return {
|
|
496
|
+
...base,
|
|
497
|
+
extensions: base.extensions.filter((e) => {
|
|
498
|
+
const canons = extensionCanonicalNames(e.path);
|
|
499
|
+
if (canons.some((n) => excludeNames.has(n)))
|
|
500
|
+
return false; // exclude wins
|
|
501
|
+
return loadAll || canons.some((n) => keepNames.has(n));
|
|
502
|
+
}),
|
|
503
|
+
};
|
|
504
|
+
};
|
|
505
|
+
const loader = new DefaultResourceLoader({
|
|
506
|
+
cwd: configCwd,
|
|
507
|
+
agentDir,
|
|
508
|
+
noExtensions,
|
|
509
|
+
additionalExtensionPaths,
|
|
510
|
+
extensionsOverride,
|
|
511
|
+
noSkills,
|
|
512
|
+
noPromptTemplates: true,
|
|
513
|
+
noThemes: true,
|
|
514
|
+
noContextFiles: true,
|
|
515
|
+
systemPromptOverride: () => systemPrompt,
|
|
516
|
+
appendSystemPromptOverride: () => [],
|
|
517
|
+
});
|
|
518
|
+
await loader.reload();
|
|
519
|
+
// Plain entries in `tools:` are expected to be built-in names (extension tools
|
|
520
|
+
// go through `ext:`), so an unknown name there is unambiguously a typo. Previously
|
|
521
|
+
// this produced a silently broken agent (#75) — pi-mono accepted the bogus name
|
|
522
|
+
// into the allowlist, then dropped it at registration with no signal back.
|
|
523
|
+
if (agentConfig?.builtinToolNames?.length) {
|
|
524
|
+
const knownBuiltins = new Set(BUILTIN_TOOL_NAMES);
|
|
525
|
+
for (const name of agentConfig.builtinToolNames) {
|
|
526
|
+
if (!knownBuiltins.has(name)) {
|
|
527
|
+
options.onToolActivity?.({
|
|
528
|
+
type: "end",
|
|
529
|
+
toolName: `tools-error:tool "${name}" requested by agent "${type}" is not a known built-in`,
|
|
530
|
+
});
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
// A subagent spawns mid-task, so a bad `extensions:`/`ext:` entry warns rather
|
|
535
|
+
// than aborts. Two distinct misconfigurations to catch:
|
|
536
|
+
// - `extensions: [foo]` but no extension named foo was discovered (typo or
|
|
537
|
+
// path that failed to load — path entries fold their canonical name into
|
|
538
|
+
// `keepNames`, so this covers them too).
|
|
539
|
+
// - `tools: ext:foo` but foo isn't in the loaded set (because `extensions:`
|
|
540
|
+
// didn't include it). Since v0.9, `ext:` no longer pulls extensions in;
|
|
541
|
+
// loading is `extensions:`-authoritative.
|
|
542
|
+
// An exclude_extensions: alongside extensions: false is contradictory — nothing
|
|
543
|
+
// loads, so there is nothing to exclude.
|
|
544
|
+
if (hasExcludes && noExtensions) {
|
|
545
|
+
options.onToolActivity?.({
|
|
546
|
+
type: "end",
|
|
547
|
+
toolName: `extension-error:exclude_extensions has no effect for agent "${type}" — extensions: false loads nothing`,
|
|
548
|
+
});
|
|
549
|
+
}
|
|
550
|
+
// Exclude typo check: compares against the PRE-filter discovered set (an excluded
|
|
551
|
+
// name absent from the surviving set is the exclude working as intended). Also
|
|
552
|
+
// flags path-like and "*" entries — excludes are plain names only.
|
|
553
|
+
if (hasExcludes && discoveredNames) {
|
|
554
|
+
for (const name of excludeNames) {
|
|
555
|
+
if (!discoveredNames.has(name)) {
|
|
556
|
+
options.onToolActivity?.({
|
|
557
|
+
type: "end",
|
|
558
|
+
toolName: `extension-error:exclude_extensions: "${name}" for agent "${type}" did not match any discovered extension`,
|
|
559
|
+
});
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
if (keepNames.size > 0 || extNames.size > 0) {
|
|
564
|
+
const survivingNames = new Set(loader.getExtensions().extensions.flatMap((e) => extensionCanonicalNames(e.path)));
|
|
565
|
+
for (const name of keepNames) {
|
|
566
|
+
if (!survivingNames.has(name)) {
|
|
567
|
+
options.onToolActivity?.({
|
|
568
|
+
type: "end",
|
|
569
|
+
toolName: excludeNames.has(name)
|
|
570
|
+
? `extension-error:extension "${name}" is in both extensions: and exclude_extensions: for agent "${type}" — exclude wins`
|
|
571
|
+
: `extension-error:extension "${name}" requested by agent "${type}" was not loaded`,
|
|
572
|
+
});
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
for (const name of extNames) {
|
|
576
|
+
if (!survivingNames.has(name)) {
|
|
577
|
+
options.onToolActivity?.({
|
|
578
|
+
type: "end",
|
|
579
|
+
toolName: `extension-error:ext:${name} referenced by agent "${type}" but extension "${name}" is not loaded (check extensions:/exclude_extensions:)`,
|
|
580
|
+
});
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
// Resolve model: explicit option > config.model > parent model
|
|
585
|
+
const model = options.model ?? resolveDefaultModel(ctx.model, ctx.modelRegistry, agentConfig?.model);
|
|
586
|
+
// Resolve thinking level: explicit option > agent config > undefined (inherit)
|
|
587
|
+
const thinkingLevel = options.thinkingLevel ?? agentConfig?.thinking;
|
|
588
|
+
const disallowedSet = agentConfig?.disallowedTools
|
|
589
|
+
? new Set(agentConfig.disallowedTools)
|
|
590
|
+
: undefined;
|
|
591
|
+
// ─── Tool scoping ───────────────────────────────────────────────────────
|
|
592
|
+
//
|
|
593
|
+
// Some extensions register their tools ASYNCHRONOUSLY, long after the
|
|
594
|
+
// `loader.reload()` above: pi-mcp calls registerTool from `session_start`
|
|
595
|
+
// (once its MCP servers connect), context-mode from `before_agent_start`.
|
|
596
|
+
// That is deliberate on their part — eagerly spawning an MCP bridge during
|
|
597
|
+
// extension discovery orphans child processes on pi's non-agent code paths
|
|
598
|
+
// (--help, config, trust probing).
|
|
599
|
+
//
|
|
600
|
+
// So the tool set cannot be snapshotted here. pi's `allowedToolNames` gates
|
|
601
|
+
// tool *registration* (`_refreshToolRegistry`'s `isAllowedTool`), not merely
|
|
602
|
+
// the active set, and is frozen at construction — a name absent from the
|
|
603
|
+
// snapshot is dropped forever, even once the tool actually registers (#125).
|
|
604
|
+
//
|
|
605
|
+
// Whenever extensions are in play we therefore:
|
|
606
|
+
// - leave `allowedToolNames` unset, so pi's live gate admits tools whenever
|
|
607
|
+
// they register;
|
|
608
|
+
// - express the name-stable, permanent part of the scope (our own
|
|
609
|
+
// orchestration tools, built-ins the agent didn't ask for, and
|
|
610
|
+
// `disallowedTools`) as `excludeTools`, which pi re-applies on every
|
|
611
|
+
// registry refresh;
|
|
612
|
+
// - enforce `ext:` narrowing on the ACTIVE set via the live `inScope()`
|
|
613
|
+
// predicate installed after bind — the active set is what the LLM sees,
|
|
614
|
+
// so a registry tool that is never activated is invisible and uncallable.
|
|
615
|
+
//
|
|
616
|
+
// `noExtensions`/`isolated` keeps the historical static allowlist: nothing
|
|
617
|
+
// async can appear there, and a hard registry gate is the correct boundary.
|
|
618
|
+
const builtinToolNameSet = new Set(toolNames);
|
|
619
|
+
let sessionTools;
|
|
620
|
+
let sessionExcludeTools;
|
|
621
|
+
if (noExtensions) {
|
|
622
|
+
sessionTools = toolNames.filter((t) => !EXCLUDED_TOOL_NAMES.includes(t) && !disallowedSet?.has(t));
|
|
623
|
+
}
|
|
624
|
+
else {
|
|
625
|
+
const denyTools = new Set(EXCLUDED_TOOL_NAMES);
|
|
626
|
+
// Keep only the built-ins the agent asked for — deny the rest.
|
|
627
|
+
for (const name of BUILTIN_TOOL_NAMES) {
|
|
628
|
+
if (!builtinToolNameSet.has(name))
|
|
629
|
+
denyTools.add(name);
|
|
630
|
+
}
|
|
631
|
+
if (disallowedSet) {
|
|
632
|
+
for (const name of disallowedSet)
|
|
633
|
+
denyTools.add(name);
|
|
634
|
+
}
|
|
635
|
+
sessionExcludeTools = [...denyTools];
|
|
636
|
+
}
|
|
637
|
+
const settingsManager = SettingsManager.create(configCwd, agentDir);
|
|
638
|
+
const configuredSessionDir = resolveConfiguredSessionDir(agentConfig?.sessionDir, effectiveCwd);
|
|
639
|
+
const defaultSessionDir = process.env.PI_CODING_AGENT_SESSION_DIR ?? settingsManager.getSessionDir?.();
|
|
640
|
+
const sessionManager = agentConfig?.persistSession
|
|
641
|
+
? SessionManager.create(effectiveCwd, configuredSessionDir ?? defaultSessionDir)
|
|
642
|
+
: SessionManager.inMemory(effectiveCwd);
|
|
643
|
+
// Pi 0.80.8 replaced createAgentSession's modelRegistry option with
|
|
644
|
+
// modelRuntime, but ExtensionContext still exposes only the registry facade.
|
|
645
|
+
// Pass both so the full supported Pi range retains the parent's providers.
|
|
646
|
+
const parentModelRuntime = ctx.modelRegistry.runtime;
|
|
647
|
+
const sessionOpts = {
|
|
648
|
+
cwd: effectiveCwd,
|
|
649
|
+
agentDir,
|
|
650
|
+
sessionManager,
|
|
651
|
+
settingsManager,
|
|
652
|
+
modelRegistry: ctx.modelRegistry,
|
|
653
|
+
...(parentModelRuntime !== undefined && { modelRuntime: parentModelRuntime }),
|
|
654
|
+
model,
|
|
655
|
+
tools: sessionTools,
|
|
656
|
+
resourceLoader: loader,
|
|
657
|
+
};
|
|
658
|
+
if (sessionExcludeTools) {
|
|
659
|
+
sessionOpts.excludeTools = sessionExcludeTools;
|
|
660
|
+
}
|
|
661
|
+
if (thinkingLevel) {
|
|
662
|
+
sessionOpts.thinkingLevel = thinkingLevel;
|
|
663
|
+
}
|
|
664
|
+
const { session } = await createAgentSession(sessionOpts);
|
|
665
|
+
const baseSessionName = agentConfig?.name ?? type;
|
|
666
|
+
session.setSessionName(options.agentId ? `${baseSessionName}#${options.agentId.slice(0, 8)}` : baseSessionName);
|
|
667
|
+
// Bind extensions so that session_start fires and extensions can initialize
|
|
668
|
+
// (e.g. loading credentials, setting up state). Tool gating already happened
|
|
669
|
+
// at session construction via the `tools:` allowlist above — no separate
|
|
670
|
+
// post-bind filter is needed. All ExtensionBindings fields are optional.
|
|
671
|
+
await session.bindExtensions({
|
|
672
|
+
onError: (err) => {
|
|
673
|
+
options.onToolActivity?.({
|
|
674
|
+
type: "end",
|
|
675
|
+
toolName: `extension-error:${err.extensionPath}`,
|
|
676
|
+
});
|
|
677
|
+
},
|
|
678
|
+
});
|
|
679
|
+
// With `allowedToolNames` unset, the registry is scoped by `excludeTools` but
|
|
680
|
+
// the ACTIVE set still needs managing: pi activates only its four default
|
|
681
|
+
// built-ins at turn 1, and `ext:` narrowing has no registry-level expression
|
|
682
|
+
// (we can't deny the name of a tool that hasn't registered yet). Both are
|
|
683
|
+
// handled below by re-deriving scope from the loader's live extension maps —
|
|
684
|
+
// `registerTool` writes into those same maps, so late arrivals are judged too.
|
|
685
|
+
if (!noExtensions) {
|
|
686
|
+
installExtensionToolScope(session, {
|
|
687
|
+
loader,
|
|
688
|
+
toolNames,
|
|
689
|
+
disallowedSet,
|
|
690
|
+
extNames,
|
|
691
|
+
narrowing,
|
|
692
|
+
});
|
|
693
|
+
}
|
|
694
|
+
options.onSessionCreated?.(session);
|
|
695
|
+
// Track turns for graceful max_turns enforcement
|
|
696
|
+
let turnCount = 0;
|
|
697
|
+
const maxTurns = normalizeMaxTurns(options.maxTurns ?? agentConfig?.maxTurns ?? defaultMaxTurns);
|
|
698
|
+
let softLimitReached = false;
|
|
699
|
+
let aborted = false;
|
|
700
|
+
let currentMessageText = "";
|
|
701
|
+
const unsubTurns = session.subscribe((event) => {
|
|
702
|
+
if (event.type === "turn_end") {
|
|
703
|
+
turnCount++;
|
|
704
|
+
options.onTurnEnd?.(turnCount);
|
|
705
|
+
if (maxTurns != null) {
|
|
706
|
+
if (!softLimitReached && turnCount >= maxTurns) {
|
|
707
|
+
softLimitReached = true;
|
|
708
|
+
session.steer("You have reached your turn limit. Wrap up immediately — provide your final answer now.");
|
|
709
|
+
}
|
|
710
|
+
else if (softLimitReached && turnCount >= maxTurns + graceTurns) {
|
|
711
|
+
aborted = true;
|
|
712
|
+
session.abort();
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
if (event.type === "message_start") {
|
|
717
|
+
currentMessageText = "";
|
|
718
|
+
}
|
|
719
|
+
if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") {
|
|
720
|
+
currentMessageText += event.assistantMessageEvent.delta;
|
|
721
|
+
options.onTextDelta?.(event.assistantMessageEvent.delta, currentMessageText);
|
|
722
|
+
}
|
|
723
|
+
if (event.type === "tool_execution_start") {
|
|
724
|
+
options.onToolActivity?.({ type: "start", toolName: event.toolName });
|
|
725
|
+
}
|
|
726
|
+
if (event.type === "tool_execution_end") {
|
|
727
|
+
options.onToolActivity?.({ type: "end", toolName: event.toolName });
|
|
728
|
+
}
|
|
729
|
+
if (event.type === "message_end" && event.message.role === "assistant") {
|
|
730
|
+
const u = event.message.usage;
|
|
731
|
+
if (u)
|
|
732
|
+
options.onAssistantUsage?.({
|
|
733
|
+
input: u.input ?? 0,
|
|
734
|
+
output: u.output ?? 0,
|
|
735
|
+
cacheWrite: u.cacheWrite ?? 0,
|
|
736
|
+
});
|
|
737
|
+
}
|
|
738
|
+
if (event.type === "compaction_end" && !event.aborted && event.result) {
|
|
739
|
+
options.onCompaction?.({ reason: event.reason, tokensBefore: event.result.tokensBefore });
|
|
740
|
+
}
|
|
741
|
+
});
|
|
742
|
+
const collector = collectResponseText(session);
|
|
743
|
+
const cleanupAbort = forwardAbortSignal(session, options.signal);
|
|
744
|
+
// Build the effective prompt: optionally prepend parent context
|
|
745
|
+
let effectivePrompt = prompt;
|
|
746
|
+
if (options.inheritContext) {
|
|
747
|
+
const parentContext = buildParentContext(ctx);
|
|
748
|
+
if (parentContext) {
|
|
749
|
+
effectivePrompt = parentContext + prompt;
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
// Boundary for the history fallback: only assistant text produced from here
|
|
753
|
+
// on counts as this run's output (a fresh session, so usually 0).
|
|
754
|
+
const startLen = session.messages.length;
|
|
755
|
+
try {
|
|
756
|
+
await session.prompt(effectivePrompt);
|
|
757
|
+
}
|
|
758
|
+
finally {
|
|
759
|
+
unsubTurns();
|
|
760
|
+
collector.unsubscribe();
|
|
761
|
+
cleanupAbort();
|
|
762
|
+
}
|
|
763
|
+
const responseText = collector.getText().trim() || getLastAssistantText(session, startLen);
|
|
764
|
+
return { responseText, session, aborted, steered: softLimitReached, failure: finalTurnError(session, startLen) };
|
|
765
|
+
}
|
|
766
|
+
/**
|
|
767
|
+
* Send a new prompt to an existing session (resume).
|
|
768
|
+
*/
|
|
769
|
+
export async function resumeAgent(session, prompt, options = {}) {
|
|
770
|
+
// Boundary for the history fallback: the session already holds prior turns,
|
|
771
|
+
// so only assistant text produced by THIS resume prompt counts as its output
|
|
772
|
+
// — a failed resume must not surface the previous turn's answer (#144).
|
|
773
|
+
const startLen = session.messages.length;
|
|
774
|
+
const collector = collectResponseText(session);
|
|
775
|
+
const cleanupAbort = forwardAbortSignal(session, options.signal);
|
|
776
|
+
const unsubEvents = (options.onToolActivity || options.onAssistantUsage || options.onCompaction)
|
|
777
|
+
? session.subscribe((event) => {
|
|
778
|
+
if (event.type === "tool_execution_start")
|
|
779
|
+
options.onToolActivity?.({ type: "start", toolName: event.toolName });
|
|
780
|
+
if (event.type === "tool_execution_end")
|
|
781
|
+
options.onToolActivity?.({ type: "end", toolName: event.toolName });
|
|
782
|
+
if (event.type === "message_end" && event.message.role === "assistant") {
|
|
783
|
+
const u = event.message.usage;
|
|
784
|
+
if (u)
|
|
785
|
+
options.onAssistantUsage?.({
|
|
786
|
+
input: u.input ?? 0,
|
|
787
|
+
output: u.output ?? 0,
|
|
788
|
+
cacheWrite: u.cacheWrite ?? 0,
|
|
789
|
+
});
|
|
790
|
+
}
|
|
791
|
+
if (event.type === "compaction_end" && !event.aborted && event.result) {
|
|
792
|
+
options.onCompaction?.({ reason: event.reason, tokensBefore: event.result.tokensBefore });
|
|
793
|
+
}
|
|
794
|
+
})
|
|
795
|
+
: () => { };
|
|
796
|
+
try {
|
|
797
|
+
await session.prompt(prompt);
|
|
798
|
+
}
|
|
799
|
+
finally {
|
|
800
|
+
collector.unsubscribe();
|
|
801
|
+
unsubEvents();
|
|
802
|
+
cleanupAbort();
|
|
803
|
+
}
|
|
804
|
+
return {
|
|
805
|
+
text: collector.getText().trim() || getLastAssistantText(session, startLen),
|
|
806
|
+
failure: finalTurnError(session, startLen),
|
|
807
|
+
};
|
|
808
|
+
}
|
|
809
|
+
/**
|
|
810
|
+
* Send a steering message to a running subagent.
|
|
811
|
+
* The message will interrupt the agent after its current tool execution.
|
|
812
|
+
*/
|
|
813
|
+
export async function steerAgent(session, message) {
|
|
814
|
+
await session.steer(message);
|
|
815
|
+
}
|
|
816
|
+
/**
|
|
817
|
+
* Get the subagent's conversation messages as formatted text.
|
|
818
|
+
*/
|
|
819
|
+
export function getAgentConversation(session) {
|
|
820
|
+
const parts = [];
|
|
821
|
+
for (const msg of session.messages) {
|
|
822
|
+
if (msg.role === "user") {
|
|
823
|
+
const text = typeof msg.content === "string"
|
|
824
|
+
? msg.content
|
|
825
|
+
: extractText(msg.content);
|
|
826
|
+
if (text.trim())
|
|
827
|
+
parts.push(`[User]: ${text.trim()}`);
|
|
828
|
+
}
|
|
829
|
+
else if (msg.role === "assistant") {
|
|
830
|
+
const textParts = [];
|
|
831
|
+
const toolCalls = [];
|
|
832
|
+
for (const c of msg.content) {
|
|
833
|
+
if (c.type === "text" && c.text)
|
|
834
|
+
textParts.push(c.text);
|
|
835
|
+
else if (c.type === "toolCall")
|
|
836
|
+
toolCalls.push(` Tool: ${c.name ?? c.toolName ?? "unknown"}`);
|
|
837
|
+
}
|
|
838
|
+
if (textParts.length > 0)
|
|
839
|
+
parts.push(`[Assistant]: ${textParts.join("\n")}`);
|
|
840
|
+
if (toolCalls.length > 0)
|
|
841
|
+
parts.push(`[Tool Calls]:\n${toolCalls.join("\n")}`);
|
|
842
|
+
}
|
|
843
|
+
else if (msg.role === "toolResult") {
|
|
844
|
+
const text = extractText(msg.content);
|
|
845
|
+
const truncated = text.length > 200 ? text.slice(0, 200) + "..." : text;
|
|
846
|
+
parts.push(`[Tool Result (${msg.toolName})]: ${truncated}`);
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
return parts.join("\n\n");
|
|
850
|
+
}
|