@kushalkhemka/opensec-pi-subagents 0.20.2 → 0.20.3
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 +69 -0
- package/README.md +125 -7
- package/dist/agent-manager.d.ts +119 -9
- package/dist/agent-manager.js +263 -56
- package/dist/agent-runner.d.ts +11 -0
- package/dist/agent-runner.js +96 -22
- package/dist/completion-outbox.d.ts +65 -0
- package/dist/completion-outbox.js +108 -0
- package/dist/cross-extension-rpc.js +8 -0
- package/dist/env.js +3 -2
- package/dist/exec-tree.js +11 -2
- package/dist/index.d.ts +7 -1
- package/dist/index.js +827 -252
- package/dist/invocation-config.d.ts +17 -4
- package/dist/invocation-config.js +29 -2
- package/dist/nested-tools.js +10 -4
- package/dist/schedule.d.ts +1 -1
- package/dist/schedule.js +10 -4
- package/dist/session-handoff.d.ts +102 -0
- package/dist/session-handoff.js +162 -0
- package/dist/settings.d.ts +26 -0
- package/dist/settings.js +10 -0
- package/dist/types.d.ts +24 -2
- package/dist/ui/agent-widget.d.ts +4 -0
- package/dist/ui/agent-widget.js +5 -0
- package/dist/ui/conversation-viewer.d.ts +104 -3
- package/dist/ui/conversation-viewer.js +425 -52
- package/dist/ui/fleet-list.d.ts +30 -9
- package/dist/ui/fleet-list.js +37 -12
- package/dist/workflow/collisions.d.ts +3 -1
- package/dist/workflow/collisions.js +4 -1
- package/dist/workflow/host.js +30 -7
- package/dist/workflow/journal.d.ts +16 -8
- package/dist/workflow/journal.js +12 -9
- package/dist/workflow/runtime.d.ts +7 -1
- package/dist/workflow/runtime.js +38 -8
- package/dist/workflow/task.d.ts +11 -1
- package/dist/workflow/task.js +13 -1
- package/dist/workflow/tool-description.d.ts +9 -1
- package/dist/workflow/tool-description.js +21 -1
- package/docs/rpc.md +10 -10
- package/docs/workflows.md +4 -4
- package/examples/agent-tool-description.md +1 -3
- package/package.json +16 -11
- package/src/agent-manager.ts +288 -55
- package/src/agent-runner.ts +100 -21
- package/src/completion-outbox.ts +121 -0
- package/src/cross-extension-rpc.ts +8 -0
- package/src/env.ts +3 -2
- package/src/exec-tree.ts +11 -2
- package/src/index.ts +810 -237
- package/src/invocation-config.ts +44 -4
- package/src/nested-tools.ts +10 -4
- package/src/schedule.ts +10 -4
- package/src/session-handoff.ts +188 -0
- package/src/settings.ts +34 -0
- package/src/types.ts +24 -2
- package/src/ui/agent-widget.ts +8 -0
- package/src/ui/conversation-viewer.ts +419 -35
- package/src/ui/fleet-list.ts +34 -11
- package/src/workflow/collisions.ts +4 -1
- package/src/workflow/host.ts +30 -7
- package/src/workflow/journal.ts +18 -9
- package/src/workflow/runtime.ts +50 -8
- package/src/workflow/task.ts +14 -0
- package/src/workflow/tool-description.ts +27 -1
package/dist/agent-runner.d.ts
CHANGED
|
@@ -37,6 +37,16 @@ export declare function extensionCanonicalName(extPath: string): string;
|
|
|
37
37
|
* package name. The path-derived name is preserved, so it keeps matching too.
|
|
38
38
|
*/
|
|
39
39
|
export declare function extensionCanonicalNames(extPath: string): string[];
|
|
40
|
+
/**
|
|
41
|
+
* Built-ins a subagent must not load, whatever the settings say.
|
|
42
|
+
*
|
|
43
|
+
* Pi's MCP is off for subagents unless the agent asks for it by naming
|
|
44
|
+
* `builtin:mcp` in `extensions:`: with it on, every subagent would start its own
|
|
45
|
+
* set of `mcp.json` servers, one process tree per running child. Pi's CLI flags
|
|
46
|
+
* apply as in the main session: `--no-mcp` keeps MCP out even when asked for,
|
|
47
|
+
* and `--no-extensions` keeps all three out.
|
|
48
|
+
*/
|
|
49
|
+
export declare function disabledBuiltinExtensions(mcpRequested: boolean, argv?: readonly string[]): string[] | undefined;
|
|
40
50
|
/**
|
|
41
51
|
* Classify `extensions: string[]` frontmatter entries for the loader-level filter.
|
|
42
52
|
*
|
|
@@ -227,6 +237,7 @@ export interface RunOptions {
|
|
|
227
237
|
model?: Model<any>;
|
|
228
238
|
maxTurns?: number;
|
|
229
239
|
signal?: AbortSignal;
|
|
240
|
+
/** Applies only when the agent file leaves `isolated:` unset — frontmatter is authoritative. */
|
|
230
241
|
isolated?: boolean;
|
|
231
242
|
inheritContext?: boolean;
|
|
232
243
|
thinkingLevel?: ThinkingLevel;
|
package/dist/agent-runner.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
import { readFileSync } from "node:fs";
|
|
5
5
|
import { homedir } from "node:os";
|
|
6
6
|
import { basename, dirname, isAbsolute, join, resolve } from "node:path";
|
|
7
|
-
import { createAgentSession, DefaultResourceLoader, getAgentDir, SessionManager, SettingsManager, } from "@earendil-works/pi-coding-agent";
|
|
7
|
+
import { createAgentSession, createCodemodeExtension, createMcpExtension, createToolSearchExtension, DefaultResourceLoader, getAgentDir, SessionManager, SettingsManager, } from "@earendil-works/pi-coding-agent";
|
|
8
8
|
import { BUILTIN_TOOL_NAMES, getAgentConfig, getConfig, getMemoryToolNames, getReadOnlyMemoryToolNames, getToolNamesForType } from "./agent-types.js";
|
|
9
9
|
import { runInChildSessionContext } from "./child-context.js";
|
|
10
10
|
import { buildParentContext, extractText } from "./context.js";
|
|
@@ -64,6 +64,9 @@ export function extensionCanonicalName(extPath) {
|
|
|
64
64
|
* co-located file to `pi-subagents`.
|
|
65
65
|
*/
|
|
66
66
|
function extensionPackageName(extPath) {
|
|
67
|
+
// `builtin:<name>` names no file; climbing from it would read the process cwd's manifest.
|
|
68
|
+
if (extPath.startsWith("builtin:"))
|
|
69
|
+
return undefined;
|
|
67
70
|
const entry = resolve(extPath);
|
|
68
71
|
let dir = dirname(extPath);
|
|
69
72
|
for (;;) {
|
|
@@ -112,6 +115,37 @@ export function extensionCanonicalNames(extPath) {
|
|
|
112
115
|
function isExtensionPathEntry(entry) {
|
|
113
116
|
return entry.includes("/") || entry.includes("\\") || entry.startsWith("~");
|
|
114
117
|
}
|
|
118
|
+
/**
|
|
119
|
+
* Pi's built-in extensions, as its CLI hands them to the loader it builds. A
|
|
120
|
+
* subagent's loader is built here and would otherwise start with none, so a
|
|
121
|
+
* `builtin:<name>` entry matched nothing. Forwarded as `builtin:` resources they
|
|
122
|
+
* load as in the main session: default-on, disabled by `-builtin:<name>` in Pi's
|
|
123
|
+
* `extensions` setting, and filtered by the agent's `extensions:` like any other
|
|
124
|
+
* extension. Fresh factories per spawn: MCP state lives in the closure. Pi's
|
|
125
|
+
* `llama.cpp` built-in is CLI-only (not exported).
|
|
126
|
+
*/
|
|
127
|
+
const BUILTIN_EXTENSION_PATHS = new Set(["builtin:codemode", "builtin:tool-search", "builtin:mcp"]);
|
|
128
|
+
function builtinExtensionFactories() {
|
|
129
|
+
return [
|
|
130
|
+
{ name: "codemode", factory: createCodemodeExtension(), builtin: true, replaceable: true },
|
|
131
|
+
{ name: "tool-search", factory: createToolSearchExtension(), builtin: true, replaceable: true },
|
|
132
|
+
{ name: "mcp", factory: createMcpExtension(), builtin: true, replaceable: true },
|
|
133
|
+
];
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Built-ins a subagent must not load, whatever the settings say.
|
|
137
|
+
*
|
|
138
|
+
* Pi's MCP is off for subagents unless the agent asks for it by naming
|
|
139
|
+
* `builtin:mcp` in `extensions:`: with it on, every subagent would start its own
|
|
140
|
+
* set of `mcp.json` servers, one process tree per running child. Pi's CLI flags
|
|
141
|
+
* apply as in the main session: `--no-mcp` keeps MCP out even when asked for,
|
|
142
|
+
* and `--no-extensions` keeps all three out.
|
|
143
|
+
*/
|
|
144
|
+
export function disabledBuiltinExtensions(mcpRequested, argv = process.argv) {
|
|
145
|
+
if (argv.some((a) => a === "--no-extensions" || a === "-ne"))
|
|
146
|
+
return ["codemode", "tool-search", "mcp"];
|
|
147
|
+
return mcpRequested && !argv.includes("--no-mcp") ? undefined : ["mcp"];
|
|
148
|
+
}
|
|
115
149
|
/**
|
|
116
150
|
* Classify `extensions: string[]` frontmatter entries for the loader-level filter.
|
|
117
151
|
*
|
|
@@ -284,10 +318,31 @@ export function installExtensionToolScope(session, ctx) {
|
|
|
284
318
|
keep.add(name);
|
|
285
319
|
return keep;
|
|
286
320
|
};
|
|
321
|
+
// Names this agent selects explicitly: its built-ins, injected tools, and
|
|
322
|
+
// `ext:foo/bar` narrowings. Pi activates a named tool even when it is
|
|
323
|
+
// `defaultActive: false`, as `--tools` does.
|
|
324
|
+
const named = new Set([...toolNames, ...readmitToolNames, ...[...narrowing.values()].flatMap((s) => [...s])]);
|
|
325
|
+
// Activate what Pi itself would: only tools declared to the model (`direct`/
|
|
326
|
+
// `model-only` exposure), and of those only named ones or ones not opted out
|
|
327
|
+
// with `defaultActive: false`. `codemode`/`deferred` tools (Pi's MCP tools by
|
|
328
|
+
// default) stay undeclared until their extension or `tool_search` activates
|
|
329
|
+
// them — so an already-active in-scope tool is kept, or turn_end would undo that.
|
|
287
330
|
const renarrow = () => {
|
|
288
331
|
const allowed = inScope();
|
|
289
|
-
const next = session.getAllTools().map((t) => t.name).filter((n) => allowed.has(n));
|
|
290
332
|
const current = session.getActiveToolNames();
|
|
333
|
+
const active = new Set(current);
|
|
334
|
+
const next = session
|
|
335
|
+
.getAllTools()
|
|
336
|
+
.filter(({ name, exposure = "direct" }) => {
|
|
337
|
+
if (!allowed.has(name))
|
|
338
|
+
return false;
|
|
339
|
+
if (active.has(name))
|
|
340
|
+
return true;
|
|
341
|
+
if (exposure !== "direct" && exposure !== "model-only")
|
|
342
|
+
return false;
|
|
343
|
+
return named.has(name) || session.getToolDefinition(name)?.defaultActive !== false;
|
|
344
|
+
})
|
|
345
|
+
.map((t) => t.name);
|
|
291
346
|
// setActiveToolsByName unconditionally rebuilds the system prompt, so skip
|
|
292
347
|
// the no-op that steady-state turns would otherwise pay for every turn.
|
|
293
348
|
if (next.length !== current.length || next.some((n, i) => n !== current[i])) {
|
|
@@ -601,27 +656,44 @@ function resolveConfiguredSessionDir(sessionDir, cwd) {
|
|
|
601
656
|
export async function runAgent(ctx, type, prompt, options) {
|
|
602
657
|
const config = getConfig(type);
|
|
603
658
|
const agentConfig = getAgentConfig(type);
|
|
659
|
+
// Everything this run needs from the parent's context, read before the first
|
|
660
|
+
// await: a background agent keeps running across a session switch, and Pi
|
|
661
|
+
// invalidates the old session's ctx then (every read throws). The values are
|
|
662
|
+
// the parent's as of the spawn — its current model and thinking level.
|
|
663
|
+
const parent = {
|
|
664
|
+
cwd: ctx.cwd,
|
|
665
|
+
projectTrusted: isProjectTrustedBy(ctx),
|
|
666
|
+
systemPrompt: ctx.getSystemPrompt(),
|
|
667
|
+
model: ctx.model,
|
|
668
|
+
modelRegistry: ctx.modelRegistry,
|
|
669
|
+
thinkingLevel: ctx.thinkingLevel,
|
|
670
|
+
sessionFile: ctx.sessionManager?.getSessionFile?.(),
|
|
671
|
+
conversation: options.inheritContext ? buildParentContext(ctx) : "",
|
|
672
|
+
};
|
|
604
673
|
// Resolve working directory: worktree override > parent cwd
|
|
605
|
-
const effectiveCwd = options.cwd ??
|
|
674
|
+
const effectiveCwd = options.cwd ?? parent.cwd;
|
|
606
675
|
// Filesystem work happens in effectiveCwd; config discovery in configCwd.
|
|
607
676
|
// They differ only for SpawnOptions.cwd spawns (config stays with the parent).
|
|
608
677
|
const configCwd = options.configCwd ?? effectiveCwd;
|
|
609
678
|
const env = await detectEnv(options.pi, effectiveCwd);
|
|
610
|
-
const projectTrusted =
|
|
679
|
+
const projectTrusted = parent.projectTrusted;
|
|
611
680
|
// Get parent system prompt for append-mode agents
|
|
612
|
-
const parentSystemPrompt =
|
|
681
|
+
const parentSystemPrompt = parent.systemPrompt;
|
|
613
682
|
// Build prompt extras (memory, skill preloading)
|
|
614
683
|
const extras = {};
|
|
615
684
|
if (options.worktreeBase)
|
|
616
685
|
extras.worktreeBase = options.worktreeBase;
|
|
617
686
|
if (options.workflow && !options.structuredOutput)
|
|
618
687
|
extras.workflowChild = true;
|
|
688
|
+
// Resolved here, not by each caller: mention and RPC spawns pass no `isolated`,
|
|
689
|
+
// and the agent file's value must hold on every path.
|
|
690
|
+
const isolated = agentConfig?.isolated ?? options.isolated;
|
|
619
691
|
// Resolve extensions/skills: isolated overrides to false
|
|
620
|
-
const extensions =
|
|
692
|
+
const extensions = isolated ? false : config.extensions;
|
|
621
693
|
// Nulling excludes under isolated also suppresses the orphaned-exclude warning —
|
|
622
694
|
// isolation is an intentional override, not a misconfiguration.
|
|
623
|
-
const excludeExtensions =
|
|
624
|
-
const skills =
|
|
695
|
+
const excludeExtensions = isolated ? undefined : config.excludeExtensions;
|
|
696
|
+
const skills = isolated ? false : config.skills;
|
|
625
697
|
// Skill preloading: when skills is string[], preload their content into prompt
|
|
626
698
|
if (Array.isArray(skills)) {
|
|
627
699
|
const loaded = preloadSkills(skills, configCwd, { project: projectTrusted });
|
|
@@ -689,7 +761,7 @@ export async function runAgent(ctx, type, prompt, options) {
|
|
|
689
761
|
// the LLM. They do NOT control loading — `extensions:` is the sole authority for
|
|
690
762
|
// which extensions load. `ext:foo` against an extension that `extensions:` excluded
|
|
691
763
|
// is an orphan and warns after reload. `isolated` means no extension tools at all.
|
|
692
|
-
const { extNames, narrowing } = parseExtSelectors(
|
|
764
|
+
const { extNames, narrowing } = parseExtSelectors(isolated ? [] : (agentConfig?.extSelectors ?? []));
|
|
693
765
|
const noExtensions = extensions === false;
|
|
694
766
|
// A path entry loads that file as code, even where Pi itself would load no
|
|
695
767
|
// project extension. From a project agent file it is therefore honoured only
|
|
@@ -755,7 +827,11 @@ export async function runAgent(ctx, type, prompt, options) {
|
|
|
755
827
|
settingsManager,
|
|
756
828
|
noExtensions,
|
|
757
829
|
additionalExtensionPaths,
|
|
758
|
-
extensionFactories:
|
|
830
|
+
extensionFactories: [
|
|
831
|
+
...builtinExtensionFactories(),
|
|
832
|
+
...(toolScopeGuard ? [toolScopeGuard.extension] : []),
|
|
833
|
+
],
|
|
834
|
+
disabledBuiltinExtensions: disabledBuiltinExtensions(keepNames.has("builtin:mcp")),
|
|
759
835
|
extensionsOverride,
|
|
760
836
|
noSkills,
|
|
761
837
|
noPromptTemplates: true,
|
|
@@ -801,7 +877,8 @@ export async function runAgent(ctx, type, prompt, options) {
|
|
|
801
877
|
// flags path-like and "*" entries — excludes are plain names only.
|
|
802
878
|
if (hasExcludes && discoveredNames) {
|
|
803
879
|
for (const name of excludeNames) {
|
|
804
|
-
|
|
880
|
+
// A disabled built-in (MCP, by default) is never discovered, and excluding it is still valid.
|
|
881
|
+
if (!discoveredNames.has(name) && !BUILTIN_EXTENSION_PATHS.has(name)) {
|
|
805
882
|
options.onToolActivity?.({
|
|
806
883
|
type: "end",
|
|
807
884
|
toolName: `extension-error:exclude_extensions: "${name}" for agent "${type}" did not match any discovered extension`,
|
|
@@ -831,13 +908,13 @@ export async function runAgent(ctx, type, prompt, options) {
|
|
|
831
908
|
}
|
|
832
909
|
}
|
|
833
910
|
// Resolve model: explicit option > config.model > parent model
|
|
834
|
-
const model = options.model ?? resolveDefaultModel(
|
|
911
|
+
const model = options.model ?? resolveDefaultModel(parent.model, parent.modelRegistry, agentConfig?.model);
|
|
835
912
|
// Omitting this SDK option uses saved settings, not the live parent's effort.
|
|
836
913
|
// A reopened session keeps the level it ran with — saved in its file —
|
|
837
914
|
// unless explicitly overridden: neither the parent's current level nor the
|
|
838
915
|
// type's frontmatter (which may have changed since) replaces it.
|
|
839
916
|
const thinkingLevel = options.thinkingLevel
|
|
840
|
-
?? (options.resumeSessionFile ? undefined : agentConfig?.thinking ??
|
|
917
|
+
?? (options.resumeSessionFile ? undefined : agentConfig?.thinking ?? parent.thinkingLevel);
|
|
841
918
|
const disallowedSet = agentConfig?.disallowedTools
|
|
842
919
|
? new Set(agentConfig.disallowedTools)
|
|
843
920
|
: undefined;
|
|
@@ -853,7 +930,7 @@ export async function runAgent(ctx, type, prompt, options) {
|
|
|
853
930
|
const nestedRuntime = options.nestedRuntime && options.nestedRuntime.depth < effectiveMaxDepth
|
|
854
931
|
? options.nestedRuntime
|
|
855
932
|
: undefined;
|
|
856
|
-
const nestedTools = agentConfig?.allowedSubagents && nestedRuntime && !
|
|
933
|
+
const nestedTools = agentConfig?.allowedSubagents && nestedRuntime && !isolated
|
|
857
934
|
? createNestedSubagentTools({
|
|
858
935
|
manager: nestedRuntime.manager,
|
|
859
936
|
pi: options.pi,
|
|
@@ -967,19 +1044,19 @@ export async function runAgent(ctx, type, prompt, options) {
|
|
|
967
1044
|
// `persist_session: true` agent; now it runs for every spawn, so a
|
|
968
1045
|
// context without a session manager (a bare programmatic ctx) must
|
|
969
1046
|
// still persist rather than take the whole spawn down.
|
|
970
|
-
parentSession:
|
|
1047
|
+
parentSession: parent.sessionFile,
|
|
971
1048
|
})
|
|
972
1049
|
: SessionManager.inMemory(effectiveCwd);
|
|
973
1050
|
// Pi 0.80.8 replaced createAgentSession's modelRegistry option with
|
|
974
1051
|
// modelRuntime, but ExtensionContext still exposes only the registry facade.
|
|
975
1052
|
// Pass both so the full supported Pi range retains the parent's providers.
|
|
976
|
-
const parentModelRuntime =
|
|
1053
|
+
const parentModelRuntime = parent.modelRegistry.runtime;
|
|
977
1054
|
const sessionOpts = {
|
|
978
1055
|
cwd: effectiveCwd,
|
|
979
1056
|
agentDir,
|
|
980
1057
|
sessionManager,
|
|
981
1058
|
settingsManager,
|
|
982
|
-
modelRegistry:
|
|
1059
|
+
modelRegistry: parent.modelRegistry,
|
|
983
1060
|
// `as never` is what keeps this assignable across the supported Pi range:
|
|
984
1061
|
// pre-0.80.8 the field exists only via the `modelRuntime?: unknown` shim
|
|
985
1062
|
// above, while newer Pi types it as `ModelRuntime` — a shape an opaque
|
|
@@ -1031,11 +1108,8 @@ export async function runAgent(ctx, type, prompt, options) {
|
|
|
1031
1108
|
options.onSessionCreated?.(session);
|
|
1032
1109
|
// Build the effective prompt: optionally prepend parent context
|
|
1033
1110
|
let effectivePrompt = prompt;
|
|
1034
|
-
if (options.inheritContext) {
|
|
1035
|
-
|
|
1036
|
-
if (parentContext) {
|
|
1037
|
-
effectivePrompt = parentContext + prompt;
|
|
1038
|
-
}
|
|
1111
|
+
if (options.inheritContext && parent.conversation) {
|
|
1112
|
+
effectivePrompt = parent.conversation + prompt;
|
|
1039
1113
|
}
|
|
1040
1114
|
let structuredRetried = false;
|
|
1041
1115
|
const maxTurns = resolveEffectiveMaxTurns(type, options.maxTurns);
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* completion-outbox.ts — When background completions reach the parent.
|
|
3
|
+
*
|
|
4
|
+
* Claude Code queues each completion and, after every tool batch, hands the
|
|
5
|
+
* model everything that queued up in one go: a busy parent sees what finished
|
|
6
|
+
* during the batch before its next model call, and nothing waits for a sibling.
|
|
7
|
+
* pi's steering queue would split those into one model call each under its
|
|
8
|
+
* default `one-at-a-time` mode, so the outbox holds them and sends ONE message
|
|
9
|
+
* at the boundary instead.
|
|
10
|
+
*
|
|
11
|
+
* - Parent busy: held until `turn_end`, which pi emits after the tool batch and
|
|
12
|
+
* before it reads the steering queue.
|
|
13
|
+
* - Parent idle: sent after a short hold, so near-simultaneous completions
|
|
14
|
+
* share a turn and `get_subagent_result` still gets a moment to consume one.
|
|
15
|
+
* - Parent turn aborted (Esc) or failed: held through it — pi clears its own
|
|
16
|
+
* queues on Esc — and sent once the run has ended, starting a turn. Claude
|
|
17
|
+
* Code keeps an agent's completion queued through Esc the same way and runs
|
|
18
|
+
* it as soon as the interrupted turn stops.
|
|
19
|
+
*/
|
|
20
|
+
import type { NotificationDetails } from "./types.js";
|
|
21
|
+
/** How long an idle parent's notification is held before it is sent. */
|
|
22
|
+
export declare const NOTIFICATION_HOLD_MS = 200;
|
|
23
|
+
export interface OutboxMessage {
|
|
24
|
+
content: string;
|
|
25
|
+
details: NotificationDetails;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* A notification for one or more agents, built when they finished: a resume
|
|
29
|
+
* before the send must not rewrite it. Reading an agent's result cancels its
|
|
30
|
+
* id, and an item left with none is dropped; `build` gets the ids still pending.
|
|
31
|
+
*/
|
|
32
|
+
export interface OutboxItem {
|
|
33
|
+
ids: string[];
|
|
34
|
+
build(ids: readonly string[]): OutboxMessage;
|
|
35
|
+
}
|
|
36
|
+
export declare class CompletionOutbox {
|
|
37
|
+
/** Delivers one message as a steer that triggers a turn when the parent is idle. */
|
|
38
|
+
private send;
|
|
39
|
+
/** Whether the parent has a run in flight, so a `turn_end` is coming. */
|
|
40
|
+
private parentRunning;
|
|
41
|
+
private items;
|
|
42
|
+
private timer;
|
|
43
|
+
constructor(
|
|
44
|
+
/** Delivers one message as a steer that triggers a turn when the parent is idle. */
|
|
45
|
+
send: (message: OutboxMessage) => void,
|
|
46
|
+
/** Whether the parent has a run in flight, so a `turn_end` is coming. */
|
|
47
|
+
parentRunning: () => boolean);
|
|
48
|
+
/** A newer completion of the same agent (a resume) replaces its pending one. */
|
|
49
|
+
add(item: OutboxItem): void;
|
|
50
|
+
/** The parent finished a turn: its tool batch is done, the next model call is not. */
|
|
51
|
+
onTurnEnd(stopReason: string | undefined): void;
|
|
52
|
+
/** The agent's result was read: it must not also be notified. */
|
|
53
|
+
cancel(id: string): void;
|
|
54
|
+
/**
|
|
55
|
+
* Completions that landed after the run's last `turn_end` would otherwise wait for the next run.
|
|
56
|
+
* Called at `agent_end` and again at `agent_settled`: one can land while the ending run is still open.
|
|
57
|
+
*/
|
|
58
|
+
onAgentEnd(): void;
|
|
59
|
+
/** Ids of everything still waiting to be sent. */
|
|
60
|
+
pendingIds(): string[];
|
|
61
|
+
dispose(): void;
|
|
62
|
+
/** Not reset by later items: the first completion is never pushed back. */
|
|
63
|
+
private arm;
|
|
64
|
+
private flush;
|
|
65
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* completion-outbox.ts — When background completions reach the parent.
|
|
3
|
+
*
|
|
4
|
+
* Claude Code queues each completion and, after every tool batch, hands the
|
|
5
|
+
* model everything that queued up in one go: a busy parent sees what finished
|
|
6
|
+
* during the batch before its next model call, and nothing waits for a sibling.
|
|
7
|
+
* pi's steering queue would split those into one model call each under its
|
|
8
|
+
* default `one-at-a-time` mode, so the outbox holds them and sends ONE message
|
|
9
|
+
* at the boundary instead.
|
|
10
|
+
*
|
|
11
|
+
* - Parent busy: held until `turn_end`, which pi emits after the tool batch and
|
|
12
|
+
* before it reads the steering queue.
|
|
13
|
+
* - Parent idle: sent after a short hold, so near-simultaneous completions
|
|
14
|
+
* share a turn and `get_subagent_result` still gets a moment to consume one.
|
|
15
|
+
* - Parent turn aborted (Esc) or failed: held through it — pi clears its own
|
|
16
|
+
* queues on Esc — and sent once the run has ended, starting a turn. Claude
|
|
17
|
+
* Code keeps an agent's completion queued through Esc the same way and runs
|
|
18
|
+
* it as soon as the interrupted turn stops.
|
|
19
|
+
*/
|
|
20
|
+
/** How long an idle parent's notification is held before it is sent. */
|
|
21
|
+
export const NOTIFICATION_HOLD_MS = 200;
|
|
22
|
+
export class CompletionOutbox {
|
|
23
|
+
send;
|
|
24
|
+
parentRunning;
|
|
25
|
+
items = [];
|
|
26
|
+
timer;
|
|
27
|
+
constructor(
|
|
28
|
+
/** Delivers one message as a steer that triggers a turn when the parent is idle. */
|
|
29
|
+
send,
|
|
30
|
+
/** Whether the parent has a run in flight, so a `turn_end` is coming. */
|
|
31
|
+
parentRunning) {
|
|
32
|
+
this.send = send;
|
|
33
|
+
this.parentRunning = parentRunning;
|
|
34
|
+
}
|
|
35
|
+
/** A newer completion of the same agent (a resume) replaces its pending one. */
|
|
36
|
+
add(item) {
|
|
37
|
+
for (const id of item.ids)
|
|
38
|
+
this.cancel(id);
|
|
39
|
+
this.items.push(item);
|
|
40
|
+
if (!this.parentRunning())
|
|
41
|
+
this.arm();
|
|
42
|
+
}
|
|
43
|
+
/** The parent finished a turn: its tool batch is done, the next model call is not. */
|
|
44
|
+
onTurnEnd(stopReason) {
|
|
45
|
+
// An aborted turn ends its run; a failed one may be retried. Either way
|
|
46
|
+
// what is held waits for the next boundary or the run's end — sent now,
|
|
47
|
+
// it would sit in a queue pi is about to clear.
|
|
48
|
+
if (stopReason !== "aborted" && stopReason !== "error")
|
|
49
|
+
this.flush();
|
|
50
|
+
}
|
|
51
|
+
/** The agent's result was read: it must not also be notified. */
|
|
52
|
+
cancel(id) {
|
|
53
|
+
for (const item of this.items)
|
|
54
|
+
item.ids = item.ids.filter(i => i !== id);
|
|
55
|
+
this.items = this.items.filter(item => item.ids.length > 0);
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Completions that landed after the run's last `turn_end` would otherwise wait for the next run.
|
|
59
|
+
* Called at `agent_end` and again at `agent_settled`: one can land while the ending run is still open.
|
|
60
|
+
*/
|
|
61
|
+
onAgentEnd() {
|
|
62
|
+
if (this.items.length > 0)
|
|
63
|
+
this.arm();
|
|
64
|
+
}
|
|
65
|
+
/** Ids of everything still waiting to be sent. */
|
|
66
|
+
pendingIds() {
|
|
67
|
+
return this.items.flatMap(item => item.ids);
|
|
68
|
+
}
|
|
69
|
+
dispose() {
|
|
70
|
+
if (this.timer)
|
|
71
|
+
clearTimeout(this.timer);
|
|
72
|
+
this.timer = undefined;
|
|
73
|
+
this.items = [];
|
|
74
|
+
}
|
|
75
|
+
/** Not reset by later items: the first completion is never pushed back. */
|
|
76
|
+
arm() {
|
|
77
|
+
this.timer ??= setTimeout(() => {
|
|
78
|
+
this.timer = undefined;
|
|
79
|
+
this.flush();
|
|
80
|
+
}, NOTIFICATION_HOLD_MS);
|
|
81
|
+
}
|
|
82
|
+
flush() {
|
|
83
|
+
if (this.timer)
|
|
84
|
+
clearTimeout(this.timer);
|
|
85
|
+
this.timer = undefined;
|
|
86
|
+
const items = this.items;
|
|
87
|
+
this.items = [];
|
|
88
|
+
const messages = items.map(item => item.build(item.ids));
|
|
89
|
+
if (messages.length === 0)
|
|
90
|
+
return;
|
|
91
|
+
// A send from a timer can outlive the session it was meant for (pi -p
|
|
92
|
+
// tearing down): pi throws on the stale context, and nothing is left to tell.
|
|
93
|
+
try {
|
|
94
|
+
this.send(combine(messages));
|
|
95
|
+
}
|
|
96
|
+
catch { /* stale context */ }
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
/** One message stays as it was built; several become one message with every agent's details. */
|
|
100
|
+
function combine(messages) {
|
|
101
|
+
if (messages.length === 1)
|
|
102
|
+
return messages[0];
|
|
103
|
+
const [first, ...rest] = messages.flatMap(({ details: { others, ...own } }) => [own, ...(others ?? [])]);
|
|
104
|
+
return {
|
|
105
|
+
content: `${messages.length} background tasks finished.\n\n${messages.map(m => m.content).join("\n\n")}`,
|
|
106
|
+
details: { ...first, others: rest },
|
|
107
|
+
};
|
|
108
|
+
}
|
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
* completion-notification race, and what protocol version 2 does not promise.
|
|
14
14
|
*/
|
|
15
15
|
import { isTopLevelAgent } from "./agent-manager.js";
|
|
16
|
+
import { isModelOverrideAllowed } from "./invocation-config.js";
|
|
16
17
|
import { resolveModel } from "./model-resolver.js";
|
|
17
18
|
import { checkModelScope } from "./model-scope.js";
|
|
18
19
|
/** RPC protocol version — bumped when the envelope or method contracts change. */
|
|
@@ -58,6 +59,13 @@ export function registerRpcHandlers(deps) {
|
|
|
58
59
|
// agent's auth lookup doesn't crash with "No API key found for
|
|
59
60
|
// undefined".
|
|
60
61
|
let normalizedOptions = options ?? {};
|
|
62
|
+
// Per-call model and thinking choices are refused unless the user turned
|
|
63
|
+
// on `allowModelOverride`: the agent runs on the parent's current model
|
|
64
|
+
// and level (or its agent file's), on this path as on every other.
|
|
65
|
+
if (!isModelOverrideAllowed()) {
|
|
66
|
+
const { model: _model, thinkingLevel: _thinking, ...rest } = normalizedOptions;
|
|
67
|
+
normalizedOptions = rest;
|
|
68
|
+
}
|
|
61
69
|
// `!= null` on purpose: a JSON-forwarding caller can serialize an unset
|
|
62
70
|
// field as null, and the runner reads `options.model ?? default`, so null
|
|
63
71
|
// means "inherit" — not an override to resolve or scope-check.
|
package/dist/env.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* env.ts — Detect environment info (git, platform) for subagent system prompts.
|
|
3
3
|
*/
|
|
4
|
+
import { commandExec } from "./exec-tree.js";
|
|
4
5
|
/**
|
|
5
6
|
* How long a detection is reused for the same `pi` and cwd. Every spawn needs
|
|
6
7
|
* this, and it costs two sequential git processes (~25 ms), which is most of a
|
|
@@ -28,7 +29,7 @@ async function detectEnvUncached(pi, cwd) {
|
|
|
28
29
|
let isGitRepo = false;
|
|
29
30
|
let branch = "";
|
|
30
31
|
try {
|
|
31
|
-
const result = await pi
|
|
32
|
+
const result = await commandExec(pi)("git", ["rev-parse", "--is-inside-work-tree"], { cwd, timeout: 5000 });
|
|
32
33
|
isGitRepo = result.code === 0 && result.stdout.trim() === "true";
|
|
33
34
|
}
|
|
34
35
|
catch {
|
|
@@ -36,7 +37,7 @@ async function detectEnvUncached(pi, cwd) {
|
|
|
36
37
|
}
|
|
37
38
|
if (isGitRepo) {
|
|
38
39
|
try {
|
|
39
|
-
const result = await pi
|
|
40
|
+
const result = await commandExec(pi)("git", ["branch", "--show-current"], { cwd, timeout: 5000 });
|
|
40
41
|
branch = result.code === 0 ? result.stdout.trim() : "unknown";
|
|
41
42
|
}
|
|
42
43
|
catch {
|
package/dist/exec-tree.js
CHANGED
|
@@ -132,8 +132,17 @@ export function execTree(command, args, options = {}) {
|
|
|
132
132
|
timeoutId = setTimeout(kill, options.timeout);
|
|
133
133
|
});
|
|
134
134
|
}
|
|
135
|
-
/**
|
|
136
|
-
|
|
135
|
+
/**
|
|
136
|
+
* The API objects whose commands run through {@link execTree}. Process-global:
|
|
137
|
+
* Pi loads a fresh copy of this module for every session, and a background
|
|
138
|
+
* agent that outlives its session (see session-handoff.ts) still runs git with
|
|
139
|
+
* the `pi` it was spawned with — stale by then, so its own `exec` throws, while
|
|
140
|
+
* this one does not need it.
|
|
141
|
+
*/
|
|
142
|
+
const TREE_KILLING_KEY = Symbol.for("pi-subagents:tree-killing-apis");
|
|
143
|
+
const treeKillingGlobal = globalThis;
|
|
144
|
+
treeKillingGlobal[TREE_KILLING_KEY] ??= new WeakSet();
|
|
145
|
+
const treeKillingApis = treeKillingGlobal[TREE_KILLING_KEY];
|
|
137
146
|
/**
|
|
138
147
|
* Run this API object's gate and git commands through {@link execTree}.
|
|
139
148
|
*
|
package/dist/index.d.ts
CHANGED
|
@@ -11,11 +11,17 @@
|
|
|
11
11
|
*/
|
|
12
12
|
import { type ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
13
13
|
import { Container } from "@earendil-works/pi-tui";
|
|
14
|
-
import { type AgentConfig } from "./types.js";
|
|
14
|
+
import { type AgentConfig, type AgentRecord } from "./types.js";
|
|
15
15
|
import { type Theme } from "./ui/agent-widget.js";
|
|
16
16
|
import { FOREIGN_WORKFLOW_TOOL_NAMES } from "./workflow/collisions.js";
|
|
17
17
|
import { WORKFLOW_ENTRY_TYPE, type WorkflowEntryData, workflowEntryData } from "./workflow/entry.js";
|
|
18
18
|
export declare function renderRunningAgentStatus(frame: string, statsText: string, activity: string, theme: Pick<Theme, "fg">): Container;
|
|
19
|
+
/**
|
|
20
|
+
* The `pending` results among a session's entries that no later
|
|
21
|
+
* `subagents:delivered` entry covers, in order, as record-shaped objects a
|
|
22
|
+
* notification can be rendered from.
|
|
23
|
+
*/
|
|
24
|
+
export declare function pendingResultsFromEntries(entries: readonly unknown[]): AgentRecord[];
|
|
19
25
|
/**
|
|
20
26
|
* Format an agent's tool scope for the Agent tool description.
|
|
21
27
|
*
|