@xzzpig/pi-subagents 0.19.0 → 0.21.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 +214 -0
- package/README.md +1 -1
- package/agents/oracle.md +8 -19
- package/agents/researcher.md +0 -3
- package/agents/reviewer.md +17 -61
- package/agents/scout.md +1 -4
- package/agents/worker.md +8 -25
- package/docs/agents.md +86 -11
- package/docs/configuration.md +68 -7
- package/docs/extension-api.md +37 -12
- package/docs/fork-extensions.md +1 -0
- package/docs/missions.md +48 -17
- package/docs/models.md +7 -3
- package/docs/observability.md +18 -8
- package/docs/tool-reference.md +138 -80
- package/docs/watchdog.md +8 -6
- package/docs/workflows.md +18 -9
- package/index.ts +5 -0
- package/package.json +5 -3
- package/prompts/council.md +1 -1
- package/skills/pi-subagents/SKILL.md +1 -1
- package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
- package/skills/pi-subagents/references/execution-controls.md +16 -16
- package/skills/pi-subagents/references/management-authoring-rpc.md +16 -12
- package/skills/pi-subagents/references/prompting-and-roles.md +3 -3
- package/src/agents/advertised-agent-prompt.ts +9 -1
- package/src/agents/agent-management.ts +4 -0
- package/src/agents/agent-memory.ts +3 -3
- package/src/agents/agent-scope.ts +4 -0
- package/src/agents/agent-serializer.ts +8 -1
- package/src/agents/agents.ts +224 -122
- package/src/api/preflight.ts +50 -5
- package/src/extension/config.ts +24 -2
- package/src/extension/context-injection.ts +6 -1
- package/src/extension/control-notices.ts +1 -9
- package/src/extension/declaration-pinning.ts +164 -0
- package/src/extension/doctor.ts +7 -10
- package/src/extension/fanout-child.ts +7 -8
- package/src/extension/index.ts +134 -145
- package/src/extension/public-execution.ts +3 -0
- package/src/extension/reply-workflow-script.ts +21 -12
- package/src/extension/rpc.ts +12 -7
- package/src/extension/schemas.ts +39 -33
- package/src/extension/subagent-guide.ts +86 -6
- package/src/extension/subagent-options.ts +47 -0
- package/src/extension/tool-activation.ts +3 -2
- package/src/extension/tool-description.ts +51 -68
- package/src/inspectors/actions.ts +37 -11
- package/src/inspectors/plugins.ts +3 -2
- package/src/inspectors/tmux/actions.ts +204 -0
- package/src/inspectors/tmux/client.ts +85 -0
- package/src/inspectors/tmux/plugin.ts +21 -0
- package/src/integrations/herdr-status.ts +18 -49
- package/src/integrations/program-status.ts +215 -0
- package/src/intercom/native-supervisor-channel.ts +77 -4
- package/src/intercom/result-intercom.ts +3 -2
- package/src/intercom/supervisor-ui.ts +2 -174
- package/src/missions/goal-driver.ts +44 -31
- package/src/missions/store.ts +35 -6
- package/src/profiles/profiles.ts +29 -23
- package/src/runs/background/active-async-capacity.ts +58 -8
- package/src/runs/background/async-execution.ts +231 -44
- package/src/runs/background/async-job-tracker.ts +12 -4
- package/src/runs/background/async-resume.ts +5 -2
- package/src/runs/background/await-async-run.ts +18 -11
- package/src/runs/background/binary-bootstrap.ts +2 -1
- package/src/runs/background/calendar-schedule.ts +90 -0
- package/src/runs/background/chain-root-attachment.ts +9 -5
- package/src/runs/background/control-channel.ts +43 -0
- package/src/runs/background/fleet-view.ts +5 -5
- package/src/runs/background/notify.ts +185 -12
- package/src/runs/background/result-files.ts +116 -5
- package/src/runs/background/result-watcher.ts +99 -66
- package/src/runs/background/resume-guidance.ts +2 -2
- package/src/runs/background/run-child-session.ts +29 -8
- package/src/runs/background/run-id-resolver.ts +8 -5
- package/src/runs/background/run-status.ts +21 -16
- package/src/runs/background/runner-aliases.ts +7 -4
- package/src/runs/background/runner-child-launch.ts +1 -0
- package/src/runs/background/runner-http-dispatcher.ts +3 -0
- package/src/runs/background/scheduled-runs.ts +282 -72
- package/src/runs/background/stale-run-reconciler.ts +13 -2
- package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
- package/src/runs/background/subagent-runner.ts +75 -16
- package/src/runs/background/subagent-wait.ts +38 -19
- package/src/runs/background/terminal-run-index.ts +46 -1
- package/src/runs/background/wait-completions.ts +1 -0
- package/src/runs/background/wait-tool.ts +33 -23
- package/src/runs/background/workflow-terminal-proof.ts +39 -22
- package/src/runs/foreground/async-stop-action.ts +48 -22
- package/src/runs/foreground/command-action.ts +41 -0
- package/src/runs/foreground/execution.ts +109 -58
- package/src/runs/foreground/foreground-history.ts +1 -0
- package/src/runs/foreground/subagent-executor.ts +270 -89
- package/src/runs/shared/child-commands.ts +229 -0
- package/src/runs/shared/child-hooks.ts +4 -3
- package/src/runs/shared/child-launch.ts +3 -0
- package/src/runs/shared/child-session.ts +131 -40
- package/src/runs/shared/child-tool-plan.ts +14 -27
- package/src/runs/shared/claude-code-adapter.ts +157 -2
- package/src/runs/shared/dynamic-fanout.ts +2 -2
- package/src/runs/shared/external-cli-preflight.ts +54 -6
- package/src/runs/shared/external-cli-runner.ts +5 -1
- package/src/runs/shared/fork-command-result.ts +10 -0
- package/src/runs/shared/herdr-placed-run.ts +5 -4
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +8 -5
- package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
- package/src/runs/shared/model-resolution.ts +39 -2
- package/src/runs/shared/nested-events.ts +5 -0
- package/src/runs/shared/parallel-handoff.ts +56 -8
- package/src/runs/shared/parallel-utils.ts +4 -0
- package/src/runs/shared/partial-output.ts +48 -0
- package/src/runs/shared/run-history.ts +87 -0
- package/src/runs/shared/runner-launcher.ts +25 -0
- package/src/runs/shared/single-output.ts +53 -0
- package/src/runs/shared/structured-output.ts +14 -7
- package/src/runs/shared/subagent-control.ts +33 -18
- package/src/runs/shared/subagent-prompt-runtime.ts +59 -30
- package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
- package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
- package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
- package/src/runs/shared/worktree-lock.ts +29 -0
- package/src/runs/shared/worktree.ts +12 -1
- package/src/shared/atomic-json.ts +4 -2
- package/src/shared/edit-distance.ts +33 -0
- package/src/shared/file-lease.ts +74 -0
- package/src/shared/formatters.ts +1 -5
- package/src/shared/model-info.ts +22 -0
- package/src/shared/package-version.ts +17 -0
- package/src/shared/parent-wake.ts +79 -0
- package/src/shared/pruned-fork.ts +7 -1
- package/src/shared/required-child-extensions.ts +39 -5
- package/src/shared/runtime-module-path.ts +19 -0
- package/src/shared/settings-file-lease.ts +36 -0
- package/src/shared/types.ts +42 -3
- package/src/shared/utils.ts +8 -6
- package/src/slash/slash-commands.ts +3 -3
- package/src/slash/subagent-cost.ts +9 -5
- package/src/slash/subagents-admin.ts +2 -1
- package/src/tui/fleet-native-transcript.ts +2 -0
- package/src/tui/fleet-transcript.ts +12 -3
- package/src/tui/fleet.ts +11 -8
- package/src/tui/render.ts +28 -20
- package/src/tui/subagent-messages.ts +305 -0
- package/src/watchdog/diff-tool.ts +2 -2
- package/src/watchdog/register-main.ts +2 -22
- package/src/watchdog/render.ts +2 -24
- package/src/watchdog/runtime.ts +6 -4
- package/src/watchdog/settings.ts +18 -13
- package/src/watchdog/tool-actions.ts +2 -2
- package/src/workflows/scripted-workflow.ts +20 -6
- package/src/workflows/workflow-receipt.ts +2 -2
- package/src/workflows/workflow-resources.ts +18 -4
package/src/api/preflight.ts
CHANGED
|
@@ -2,10 +2,11 @@ import * as fs from "node:fs";
|
|
|
2
2
|
import * as path from "node:path";
|
|
3
3
|
import { fileURLToPath } from "node:url";
|
|
4
4
|
import { discoverAgentSnapshot, findBlockingAgentDiagnostic, formatUnknownAgentError, resolveAgentName, unknownAgentDiagnosticContext, type AgentConfig, type AgentDiscoveryAllResult, type AgentScope, type AgentSource } from "../agents/agents.ts";
|
|
5
|
-
import { resolveExecutionAgentScope } from "../agents/agent-scope.ts";
|
|
5
|
+
import { projectScopeRequiresTrustMessage, resolveExecutionAgentScope } from "../agents/agent-scope.ts";
|
|
6
6
|
import { normalizeSkillInput, resolveSkillsWithFallback } from "../agents/skills.ts";
|
|
7
7
|
import { inheritsParentModel, resolveEffectiveSubagentModel, resolveModelOrigin, resolveModelSelection, type AvailableModelInfo, type ParentModel } from "../runs/shared/model-resolution.ts";
|
|
8
8
|
import { resolveModelScopesForAgent } from "../runs/shared/model-scope.ts";
|
|
9
|
+
import { assertClaudeCodeModelScope, isClaudeCodeAdapterId, resolveClaudeCodeOverride } from "../runs/shared/claude-code-adapter.ts";
|
|
9
10
|
import { applyThinkingSuffix, resolvePiLaunchToolPlan, type PiLaunchToolPlan } from "../runs/shared/child-tool-plan.ts";
|
|
10
11
|
import { buildEffectiveSystemPrompt } from "../runs/shared/effective-system-prompt.ts";
|
|
11
12
|
import { normalizeSingleOutputOverride, resolveSingleOutputPath } from "../runs/shared/single-output.ts";
|
|
@@ -27,7 +28,7 @@ import { resultFilePath } from "../runs/background/result-files.ts";
|
|
|
27
28
|
import { nestedResultsPath } from "../runs/shared/nested-events.ts";
|
|
28
29
|
import { normalizeExtensionBindings, type ExtensionBindings } from "../runs/shared/extension-bindings.ts";
|
|
29
30
|
import { projectScopedProfileTrustError } from "../runs/shared/sandbox-profile-guard.ts";
|
|
30
|
-
import { resolveRequiredChildExtensions } from "../shared/required-child-extensions.ts";
|
|
31
|
+
import { assertRequiredChildExtensionsAdmitted, resolveRequiredChildExtensions } from "../shared/required-child-extensions.ts";
|
|
31
32
|
|
|
32
33
|
// v3: the contract reports the resolved Intercom bridge state and binds its
|
|
33
34
|
// prompt and tools into launchContractDigest, matching execution (#2127).
|
|
@@ -46,6 +47,7 @@ export type SubagentLaunchContractReasonCode =
|
|
|
46
47
|
| "unsupported_mode"
|
|
47
48
|
| "restricted_agent"
|
|
48
49
|
| "thinking_ceiling"
|
|
50
|
+
| "model_scope"
|
|
49
51
|
| "invalid_extension_bindings"
|
|
50
52
|
| "untrusted_project"
|
|
51
53
|
| "sandbox_unavailable"
|
|
@@ -65,6 +67,8 @@ export interface SubagentLaunchContractInput {
|
|
|
65
67
|
cwd: string;
|
|
66
68
|
task?: string;
|
|
67
69
|
agentScope?: AgentScope;
|
|
70
|
+
/** False when the parent session declined project trust; project agents and project subagent settings are then ignored. Defaults to true. */
|
|
71
|
+
projectTrusted?: boolean;
|
|
68
72
|
context?: "fresh" | "fork";
|
|
69
73
|
model?: string;
|
|
70
74
|
fast?: boolean;
|
|
@@ -96,8 +100,6 @@ export interface SubagentLaunchContractInput {
|
|
|
96
100
|
nestedRootRunId?: string;
|
|
97
101
|
capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
|
|
98
102
|
inheritedCapabilityCeiling?: ResolvedSubagentCapabilityCeiling;
|
|
99
|
-
/** Host-affirmed trust state for a project-scoped profile selection. */
|
|
100
|
-
projectTrusted?: boolean;
|
|
101
103
|
/** Exact trusted project cwd. When omitted, an affirmative trust assertion applies only to `cwd`. */
|
|
102
104
|
trustedProjectCwd?: string;
|
|
103
105
|
/** Builtin tool names the host runtime provides; used to intersect agent-declared tools. */
|
|
@@ -216,6 +218,17 @@ export type SubagentLaunchContractResult =
|
|
|
216
218
|
| { ok: true; contract: SubagentLaunchContract }
|
|
217
219
|
| { ok: false; code: SubagentLaunchContractReasonCode; message: string; diagnostics: SubagentLaunchContractDiagnostic[] };
|
|
218
220
|
|
|
221
|
+
/**
|
|
222
|
+
* Classify a Claude Code override failure for the launch contract. The messages
|
|
223
|
+
* are owned by the adapter and the scope check, so this maps them explicitly
|
|
224
|
+
* instead of defaulting every rejection to the ceiling.
|
|
225
|
+
*/
|
|
226
|
+
function claudeCodeFailureCode(message: string): SubagentLaunchContractReasonCode {
|
|
227
|
+
if (message.includes("subagent model scope")) return "model_scope";
|
|
228
|
+
if (message.startsWith("Thinking level '")) return "thinking_ceiling";
|
|
229
|
+
return "unsupported_mode";
|
|
230
|
+
}
|
|
231
|
+
|
|
219
232
|
function packageVersion(): string {
|
|
220
233
|
const packagePath = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "package.json");
|
|
221
234
|
try {
|
|
@@ -310,8 +323,12 @@ export async function resolveSubagentLaunchContract(input: SubagentLaunchContrac
|
|
|
310
323
|
return { ok: false, code: "invalid_intercom_bridge", message: "orchestratorTarget must be a non-empty string when provided.", diagnostics };
|
|
311
324
|
}
|
|
312
325
|
const scope = resolveExecutionAgentScope(input.agentScope);
|
|
326
|
+
if (input.projectTrusted === false && scope === "project") {
|
|
327
|
+
const message = projectScopeRequiresTrustMessage(effectiveCwd);
|
|
328
|
+
return { ok: false, code: "restricted_agent", message, diagnostics: [...diagnostics, { code: "restricted_agent", severity: "error", message }] };
|
|
329
|
+
}
|
|
313
330
|
const parentProvider = input.preferredProvider ?? input.parentModel?.provider;
|
|
314
|
-
const discovery = discoverAgentSnapshot(effectiveCwd, scope, parentProvider, { includeChains: false });
|
|
331
|
+
const discovery = discoverAgentSnapshot(effectiveCwd, scope, parentProvider, { includeChains: false, projectTrusted: input.projectTrusted });
|
|
315
332
|
const discovered = discovery.effective;
|
|
316
333
|
const resolvedAgent = resolveAgentName(input.agent, discovered.agents);
|
|
317
334
|
const ambiguousCandidates = resolvedAgent.error
|
|
@@ -413,6 +430,13 @@ export async function resolveSubagentLaunchContract(input: SubagentLaunchContrac
|
|
|
413
430
|
if (resolvedSkills.missing.length > 0) diagnostics.push({ code: "missing_skill", severity: "error", message: `Missing skills: ${resolvedSkills.missing.join(", ")}` });
|
|
414
431
|
|
|
415
432
|
const externalRunner = agent.runner?.type === "external-cli" || agent.runner?.type === "external-job";
|
|
433
|
+
// Machine placement has no preflight input; execution enforces it. Preview the runner-type admission here.
|
|
434
|
+
try {
|
|
435
|
+
assertRequiredChildExtensionsAdmitted([resolveRequiredChildExtensions(input.parentSessionId)], { agent: agent.name, runnerType: agent.runner?.type });
|
|
436
|
+
} catch (error) {
|
|
437
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
438
|
+
return { ok: false, code: "unsupported_mode", message, diagnostics };
|
|
439
|
+
}
|
|
416
440
|
if (externalRunner && behavior.outputSchema) {
|
|
417
441
|
return { ok: false, code: "unsupported_mode", message: `Agent '${agent.name}' uses runner.type='${agent.runner?.type}' and does not support: structured output.`, diagnostics };
|
|
418
442
|
}
|
|
@@ -446,6 +470,27 @@ export async function resolveSubagentLaunchContract(input: SubagentLaunchContrac
|
|
|
446
470
|
return { ok: false, code: "thinking_ceiling", message, diagnostics };
|
|
447
471
|
}
|
|
448
472
|
}
|
|
473
|
+
// The Claude Code adapters accept a model and a level that never become a Pi child
|
|
474
|
+
// model, so validate has to run the same two checks the launch runs, or validate
|
|
475
|
+
// would report ok for a launch that then fails.
|
|
476
|
+
if (agent.runner?.type === "external-cli" && isClaudeCodeAdapterId(agent.runner.adapter)) {
|
|
477
|
+
try {
|
|
478
|
+
const override = resolveClaudeCodeOverride({
|
|
479
|
+
model: typeof input.model === "string" ? input.model : undefined,
|
|
480
|
+
agent,
|
|
481
|
+
thinking: typeof effectiveThinkingConfig === "string" ? effectiveThinkingConfig : undefined,
|
|
482
|
+
thinkingCeiling: intersectThinkingCeilings(discovered.maxThinking, input.thinkingCeiling, input.inheritedThinkingCeiling),
|
|
483
|
+
agentName: agent.name,
|
|
484
|
+
runId,
|
|
485
|
+
});
|
|
486
|
+
assertClaudeCodeModelScope({ scopes: modelScopes, model: override?.model, agent: agent.name, runId });
|
|
487
|
+
} catch (error) {
|
|
488
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
489
|
+
const code = claudeCodeFailureCode(message);
|
|
490
|
+
diagnostics.push({ code, severity: "error", message });
|
|
491
|
+
return { ok: false, code, message, diagnostics };
|
|
492
|
+
}
|
|
493
|
+
}
|
|
449
494
|
let toolPlan: PiLaunchToolPlan;
|
|
450
495
|
const permissionRules = resolvePermissionRules(loadConfig().permissions, agent.permissions);
|
|
451
496
|
const fast = input.fast ?? agent.fast;
|
package/src/extension/config.ts
CHANGED
|
@@ -2,7 +2,7 @@ import * as fs from "node:fs";
|
|
|
2
2
|
import * as os from "node:os";
|
|
3
3
|
import * as path from "node:path";
|
|
4
4
|
import { Key } from "@earendil-works/pi-tui";
|
|
5
|
-
import { FLEET_KEYBINDING_ACTIONS, type ArtifactDirPreference, type ExtensionConfig } from "../shared/types.ts";
|
|
5
|
+
import { FLEET_KEYBINDING_ACTIONS, RUNNER_LAUNCHER_NAME_PATTERN, RUNNER_LAUNCHER_NAME_RULE, type ArtifactDirPreference, type ExtensionConfig } from "../shared/types.ts";
|
|
6
6
|
import { validateMissionStoreConfig } from "../missions/store.ts";
|
|
7
7
|
import { validateAuthorityPolicy } from "../policy/authority.ts";
|
|
8
8
|
import { getAgentDir } from "../shared/utils.ts";
|
|
@@ -14,7 +14,7 @@ import { validateDisabledFeatures } from "../shared/disabled-features.ts";
|
|
|
14
14
|
|
|
15
15
|
// Explicit route identity, worktree, checkpoint, and tool-surface policies must not be silently
|
|
16
16
|
// discarded and replaced by the built-in defaults after validation fails.
|
|
17
|
-
const FAIL_CLOSED_CONFIG_KEYS = ["worktreeProvider", "worktreeBranchPrefix", "modelResponseAliases", "modelExclusions", "checkpointBeforeDeadlineMs", "disabledFeatures", "scheduledRuns", "toolActivation"];
|
|
17
|
+
const FAIL_CLOSED_CONFIG_KEYS = ["worktreeProvider", "worktreeBranchPrefix", "modelResponseAliases", "modelExclusions", "checkpointBeforeDeadlineMs", "disabledFeatures", "scheduledRuns", "toolActivation", "authorityPolicy", "permissions", "toolBudget", "runnerLaunchers"];
|
|
18
18
|
|
|
19
19
|
const ARTIFACT_DIR_PREFERENCES = new Set<ArtifactDirPreference>(["project", "session", "temp"]);
|
|
20
20
|
const FLEET_KEYBINDING_ACTION_SET = new Set<string>(FLEET_KEYBINDING_ACTIONS);
|
|
@@ -103,6 +103,18 @@ function validateCapacityConfig(value: unknown): void {
|
|
|
103
103
|
}
|
|
104
104
|
}
|
|
105
105
|
|
|
106
|
+
function validateRunnerLaunchersConfig(value: unknown): void {
|
|
107
|
+
if (value === undefined) return;
|
|
108
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("config.runnerLaunchers must be a JSON object mapping launcher names to argv arrays");
|
|
109
|
+
for (const [name, argv] of Object.entries(value)) {
|
|
110
|
+
const label = `config.runnerLaunchers[${JSON.stringify(name)}]`;
|
|
111
|
+
if (!RUNNER_LAUNCHER_NAME_PATTERN.test(name)) throw new Error(`${label} has an invalid name; launcher names ${RUNNER_LAUNCHER_NAME_RULE}`);
|
|
112
|
+
if (!Array.isArray(argv) || argv.length === 0 || argv.some((arg) => typeof arg !== "string" || !arg.trim() || arg.includes("\u0000"))) {
|
|
113
|
+
throw new Error(`${label} must be a non-empty argv array of non-blank strings without NUL characters`);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
106
118
|
function validateOrcaProgressTabsConfig(value: unknown): void {
|
|
107
119
|
if (value === undefined) return;
|
|
108
120
|
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("config.orcaProgressTabs must be a JSON object");
|
|
@@ -172,6 +184,15 @@ function validateConfig(config: Record<string, unknown>): void {
|
|
|
172
184
|
if (config.resultScanLogging !== undefined && config.resultScanLogging !== "all" && config.resultScanLogging !== "activity" && config.resultScanLogging !== "off") {
|
|
173
185
|
throw new Error('config.resultScanLogging must be "all", "activity", or "off"');
|
|
174
186
|
}
|
|
187
|
+
if (config.asyncWidgetCollapsed !== undefined && typeof config.asyncWidgetCollapsed !== "boolean") {
|
|
188
|
+
throw new Error("config.asyncWidgetCollapsed must be a boolean");
|
|
189
|
+
}
|
|
190
|
+
if (config.asyncWidgetLayout !== undefined && config.asyncWidgetLayout !== "adaptive" && config.asyncWidgetLayout !== "rows") {
|
|
191
|
+
throw new Error('config.asyncWidgetLayout must be "adaptive" or "rows"');
|
|
192
|
+
}
|
|
193
|
+
if (config.programStatus !== undefined && typeof config.programStatus !== "boolean") {
|
|
194
|
+
throw new Error("config.programStatus must be a boolean");
|
|
195
|
+
}
|
|
175
196
|
if (config.toolActivation !== undefined && config.toolActivation !== "auto" && config.toolActivation !== "dynamic" && config.toolActivation !== "eager") {
|
|
176
197
|
throw new Error('config.toolActivation must be "auto", "dynamic", or "eager"');
|
|
177
198
|
}
|
|
@@ -187,6 +208,7 @@ function validateConfig(config: Record<string, unknown>): void {
|
|
|
187
208
|
validateModelResponseAliases(config.modelResponseAliases);
|
|
188
209
|
validateMainWindowRendererConfig(config.mainWindowRenderer);
|
|
189
210
|
validateOrcaProgressTabsConfig(config.orcaProgressTabs);
|
|
211
|
+
validateRunnerLaunchersConfig(config.runnerLaunchers);
|
|
190
212
|
}
|
|
191
213
|
|
|
192
214
|
export function getConfigPath(): string {
|
|
@@ -89,8 +89,13 @@ export function resolveInjectableAgents(input: ResolveInjectableAgentsInput): Re
|
|
|
89
89
|
* Returns `undefined` when nothing should change: empty block, or a prompt
|
|
90
90
|
* that already carries the marker (forked/resumed chains replaying history).
|
|
91
91
|
*/
|
|
92
|
-
export function applyInjectionBlock(input: { systemPrompt: string; block: string }): string | undefined {
|
|
92
|
+
export function applyInjectionBlock(input: { systemPrompt: string; block: string; replaceExisting?: boolean }): string | undefined {
|
|
93
93
|
const { systemPrompt, block } = input;
|
|
94
|
+
if (input.replaceExisting) {
|
|
95
|
+
const base = systemPrompt.replace(/\n*<available_subagents>[\s\S]*<\/available_subagents>/g, "");
|
|
96
|
+
const next = block ? `${base}\n\n${block}` : base;
|
|
97
|
+
return next === systemPrompt ? undefined : next;
|
|
98
|
+
}
|
|
94
99
|
if (!block) return undefined;
|
|
95
100
|
if (systemPrompt.includes(SUBAGENT_INJECTION_MARKER)) return undefined;
|
|
96
101
|
return `${systemPrompt}\n\n${block}`;
|
|
@@ -14,20 +14,12 @@ export interface SubagentControlMessageDetails {
|
|
|
14
14
|
noticeDeferred?: boolean;
|
|
15
15
|
}
|
|
16
16
|
|
|
17
|
-
export function controlNoticeTarget(details: SubagentControlMessageDetails): string | undefined {
|
|
18
|
-
return details.childIntercomTarget;
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
export function formatSubagentControlNotice(details: SubagentControlMessageDetails, content?: string): string {
|
|
22
|
-
return details.noticeText ?? content ?? formatControlNoticeMessage(details.event, controlNoticeTarget(details));
|
|
23
|
-
}
|
|
24
|
-
|
|
25
17
|
function deliverControlNotice(input: {
|
|
26
18
|
pi: Pick<ExtensionAPI, "sendMessage">;
|
|
27
19
|
visibleControlNotices: Set<string>;
|
|
28
20
|
details: SubagentControlMessageDetails;
|
|
29
21
|
}): void {
|
|
30
|
-
const childIntercomTarget =
|
|
22
|
+
const childIntercomTarget = input.details.childIntercomTarget;
|
|
31
23
|
const key = controlNotificationKey(input.details.event, childIntercomTarget);
|
|
32
24
|
if (input.visibleControlNotices.has(key)) return;
|
|
33
25
|
input.visibleControlNotices.add(key);
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import { declarationsEqual, getCurrentSystemMessage, toToolDeclaration, type Message, type SystemMessage, type Tool } from "@earendil-works/pi-ai";
|
|
2
|
+
import type { ExtensionAPI, ExtensionContext, ToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import type { TSchema } from "typebox";
|
|
4
|
+
|
|
5
|
+
// Pi records each declared tool definition and prompt section in the session transcript and
|
|
6
|
+
// re-declares any difference before the next request. A changed tool or prompt section makes
|
|
7
|
+
// the provider re-read the whole conversation without its prompt cache, so a session keeps the
|
|
8
|
+
// pi-subagents definitions and prompt text it already declared. Only a session that never
|
|
9
|
+
// declared a tool gets its current definition.
|
|
10
|
+
|
|
11
|
+
type PinnableTool = ToolDefinition<TSchema, unknown>;
|
|
12
|
+
|
|
13
|
+
/** What a session declared for one tool; an absent snippet or guidelines keeps the current value. */
|
|
14
|
+
interface DeclaredPin {
|
|
15
|
+
declaration: Tool;
|
|
16
|
+
snippet?: { text?: string };
|
|
17
|
+
guidelines?: string[];
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
interface Pins {
|
|
21
|
+
current: Map<string, PinnableTool>;
|
|
22
|
+
declared: Map<string, DeclaredPin>;
|
|
23
|
+
registered: Map<string, string>;
|
|
24
|
+
/** The prompt sections the session transcript recorded, read on session events only. */
|
|
25
|
+
sections: Record<string, string | null>;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const pinsByApi = new WeakMap<ExtensionAPI, Pins>();
|
|
29
|
+
const GUIDELINES_PLACEHOLDER = "\u0000pi-subagents guidelines";
|
|
30
|
+
|
|
31
|
+
function pinnedDefinition(tool: PinnableTool, pin: DeclaredPin | undefined): PinnableTool {
|
|
32
|
+
const { constrainedSampling, promptSnippet, promptGuidelines, ...rest } = tool;
|
|
33
|
+
// An unchanged declaration keeps the registered schema object rather than its JSON copy.
|
|
34
|
+
const declaration = pin && !declarationsEqual(pin.declaration, tool) ? pin.declaration : undefined;
|
|
35
|
+
const definition: PinnableTool = { ...rest, description: declaration?.description ?? rest.description, parameters: declaration?.parameters ?? rest.parameters };
|
|
36
|
+
const sampling = declaration ? declaration.constrainedSampling : constrainedSampling;
|
|
37
|
+
if (sampling !== undefined) definition.constrainedSampling = sampling;
|
|
38
|
+
const snippet = pin?.snippet ? pin.snippet.text : promptSnippet;
|
|
39
|
+
if (snippet !== undefined) definition.promptSnippet = snippet;
|
|
40
|
+
const guidelines = pin?.guidelines ?? promptGuidelines;
|
|
41
|
+
if (guidelines !== undefined) definition.promptGuidelines = guidelines;
|
|
42
|
+
return definition;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function register(pi: ExtensionAPI, pins: Pins, name: string): void {
|
|
46
|
+
const definition = pinnedDefinition(pins.current.get(name)!, pins.declared.get(name));
|
|
47
|
+
const key = JSON.stringify([toToolDeclaration(definition), definition.promptSnippet, definition.promptGuidelines]);
|
|
48
|
+
if (pins.registered.get(name) === key) return;
|
|
49
|
+
pins.registered.set(name, key);
|
|
50
|
+
pi.registerTool(definition);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function sectionLines(text: string | undefined, name: string): string[] | undefined {
|
|
54
|
+
const lines = text?.split("\n") ?? [];
|
|
55
|
+
const start = lines.indexOf(`<${name}>`);
|
|
56
|
+
const end = lines.indexOf(`</${name}>`, start + 1);
|
|
57
|
+
return start >= 0 && end > start ? lines.slice(start + 1, end) : undefined;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Mirrors the unexported buildRules of Pi's default system prompt, without prompt-level guidelines. */
|
|
61
|
+
function ruleLines(activeTools: string[], guidelines: Map<string, string[]>): string[] {
|
|
62
|
+
const lines: string[] = [];
|
|
63
|
+
const add = (rule: string): void => {
|
|
64
|
+
const line = `- ${rule.trim()}`;
|
|
65
|
+
if (line !== "- " && !lines.includes(line)) lines.push(line);
|
|
66
|
+
};
|
|
67
|
+
const active = (name: string) => activeTools.includes(name);
|
|
68
|
+
if ((active("bash") || active("powershell")) && !active("grep") && !active("find") && !active("ls")) {
|
|
69
|
+
if (active("bash") && active("powershell")) add("Use bash or PowerShell for file operations like listing, searching, and finding files");
|
|
70
|
+
else if (active("powershell")) add("Use PowerShell for file operations like listing, searching, and finding files");
|
|
71
|
+
else add("Use bash for file operations like ls, rg, find");
|
|
72
|
+
}
|
|
73
|
+
for (const name of activeTools) for (const rule of guidelines.get(name) ?? []) add(rule);
|
|
74
|
+
add("Be concise in your responses");
|
|
75
|
+
add("Show file paths clearly when working with files");
|
|
76
|
+
return lines;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const sameLines = (left: string[], right: string[]) => left.length === right.length && left.every((line, index) => line === right[index]);
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* The rules section does not say which tool contributed a bullet, so a declared tool's guidelines
|
|
83
|
+
* are recovered by rebuilding the recorded rules with candidate bullets at that tool's position.
|
|
84
|
+
* Nothing is recovered unless the rebuild first reproduces Pi's current rules.
|
|
85
|
+
*/
|
|
86
|
+
function recordedGuidelines(pi: ExtensionAPI, ctx: ExtensionContext, recorded: string[], names: string[]): Map<string, string[]> {
|
|
87
|
+
const recovered = new Map<string, string[]>();
|
|
88
|
+
const activeTools = pi.getActiveTools();
|
|
89
|
+
const guidelines = new Map(pi.getAllTools().map((tool) => [tool.name, tool.promptGuidelines ?? []]));
|
|
90
|
+
const current = sectionLines(ctx.getSystemPrompt(), "rules");
|
|
91
|
+
if (!current || !sameLines(ruleLines(activeTools, guidelines), current)) return recovered;
|
|
92
|
+
const rebuild = (name: string, candidate: string[]) => ruleLines(activeTools, new Map(guidelines).set(name, candidate));
|
|
93
|
+
for (const name of names) {
|
|
94
|
+
const start = rebuild(name, [GUIDELINES_PLACEHOLDER]).indexOf(`- ${GUIDELINES_PLACEHOLDER}`);
|
|
95
|
+
if (start < 0) continue;
|
|
96
|
+
const candidate = recorded.slice(start, start + recorded.length - rebuild(name, []).length).map((line) => line.slice(2));
|
|
97
|
+
if (!sameLines(rebuild(name, candidate), recorded)) continue;
|
|
98
|
+
guidelines.set(name, candidate);
|
|
99
|
+
recovered.set(name, candidate);
|
|
100
|
+
}
|
|
101
|
+
return recovered;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function recordedSystemMessage(ctx: ExtensionContext | undefined): SystemMessage | undefined {
|
|
105
|
+
// SAFETY: Pi's session manager exposes buildSessionContext, but its read-only extension type omits it.
|
|
106
|
+
const sessionManager = ctx?.sessionManager as (ExtensionContext["sessionManager"] & { buildSessionContext?(): { messages: Message[] } }) | undefined;
|
|
107
|
+
// A host without a readable transcript, such as a test double, declares nothing to keep.
|
|
108
|
+
if (typeof sessionManager?.buildSessionContext !== "function") return undefined;
|
|
109
|
+
return getCurrentSystemMessage(sessionManager.buildSessionContext().messages);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function declaredPins(pi: ExtensionAPI, pins: Pins, ctx: ExtensionContext | undefined, system: SystemMessage | undefined): Map<string, DeclaredPin> {
|
|
113
|
+
if (!ctx || !system) return new Map();
|
|
114
|
+
const declarations = system.toolsAdded ?? [];
|
|
115
|
+
const snippets = sectionLines(system.sections?.tools ?? undefined, "tools");
|
|
116
|
+
const rules = sectionLines(system.sections?.rules ?? undefined, "rules");
|
|
117
|
+
const guidelines = rules ? recordedGuidelines(pi, ctx, rules, declarations.map((tool) => tool.name).filter((name) => pins.current.has(name))) : new Map<string, string[]>();
|
|
118
|
+
return new Map(declarations.map((declaration) => {
|
|
119
|
+
const pin: DeclaredPin = { declaration };
|
|
120
|
+
// Pi renders each snippet on one line as "- <tool>: <snippet>".
|
|
121
|
+
if (snippets) pin.snippet = { text: snippets.find((line) => line.startsWith(`- ${declaration.name}: `))?.slice(declaration.name.length + 4) };
|
|
122
|
+
const recovered = guidelines.get(declaration.name);
|
|
123
|
+
if (recovered) pin.guidelines = recovered;
|
|
124
|
+
return [declaration.name, pin];
|
|
125
|
+
}));
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function pinsFor(pi: ExtensionAPI): Pins {
|
|
129
|
+
const existing = pinsByApi.get(pi);
|
|
130
|
+
if (existing) return existing;
|
|
131
|
+
const pins: Pins = { current: new Map(), declared: new Map(), registered: new Map(), sections: {} };
|
|
132
|
+
pinsByApi.set(pi, pins);
|
|
133
|
+
// Pi restores the transcript's active tools before both events, so handler order does not matter.
|
|
134
|
+
const refresh = (ctx: ExtensionContext | undefined) => {
|
|
135
|
+
const system = recordedSystemMessage(ctx);
|
|
136
|
+
pins.sections = system?.sections ?? {};
|
|
137
|
+
pins.declared = declaredPins(pi, pins, ctx, system);
|
|
138
|
+
for (const name of pins.current.keys()) register(pi, pins, name);
|
|
139
|
+
};
|
|
140
|
+
pi.on("session_start", (_event, ctx) => refresh(ctx));
|
|
141
|
+
pi.on("session_tree", (_event, ctx) => refresh(ctx));
|
|
142
|
+
return pins;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* The text, without its tags, that the session transcript recorded for one of the prompt sections
|
|
147
|
+
* pi-subagents adds, so that section can keep the wording the session already sent.
|
|
148
|
+
* A session that never recorded the section gets undefined.
|
|
149
|
+
*/
|
|
150
|
+
export function recordedPromptSection(pi: ExtensionAPI, name: string): string | undefined {
|
|
151
|
+
return sectionLines(pinsFor(pi).sections[name] ?? undefined, name)?.join("\n");
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Register a pi-subagents tool so a session keeps the definition, prompt snippet and guidelines
|
|
156
|
+
* its transcript already declared. Only a session that never declared the tool gets this definition.
|
|
157
|
+
*/
|
|
158
|
+
export function registerPinnedTool<TParams extends TSchema, TDetails>(pi: ExtensionAPI, tool: ToolDefinition<TParams, TDetails>): void {
|
|
159
|
+
const pins = pinsFor(pi);
|
|
160
|
+
// SAFETY: Pinning reads only model-facing fields and re-registers every runtime field unchanged.
|
|
161
|
+
pins.current.set(tool.name, tool as unknown as PinnableTool);
|
|
162
|
+
pins.registered.delete(tool.name);
|
|
163
|
+
register(pi, pins, tool.name);
|
|
164
|
+
}
|
package/src/extension/doctor.ts
CHANGED
|
@@ -4,16 +4,16 @@ import { discoverAgentsAll, type AgentSource } from "../agents/agents.ts";
|
|
|
4
4
|
import { mergeAgentsForScope } from "../agents/agent-selection.ts";
|
|
5
5
|
import { resolveInjectableAgents } from "./context-injection.ts";
|
|
6
6
|
import { isAsyncAvailable } from "../runs/background/async-execution.ts";
|
|
7
|
-
import { formatSpawnBudgetSummary
|
|
8
|
-
import { getActiveAsyncCapacitySnapshot, resolveAbandonedSlotReleaseAfterMs, resolveMaxActiveAsyncRunsPerSession } from "../runs/background/active-async-capacity.ts";
|
|
9
|
-
|
|
7
|
+
import { formatSpawnBudgetSummary } from "../runs/shared/spawn-budget.ts";
|
|
10
8
|
import { diagnoseIntercomBridge, type IntercomBridgeDiagnostic } from "../intercom/intercom-bridge.ts";
|
|
11
9
|
import { discoverAvailableSkills, type SkillSource } from "../agents/skills.ts";
|
|
12
10
|
import {
|
|
13
11
|
DIRS,
|
|
14
12
|
CHAIN_RUNS_DIR,
|
|
15
13
|
TEMP_ROOT_DIR,
|
|
14
|
+
type ActiveAsyncCapacitySnapshot,
|
|
16
15
|
type ExtensionConfig,
|
|
16
|
+
type SpawnBudgetSnapshot,
|
|
17
17
|
type SubagentState,
|
|
18
18
|
normalizeMaxSubagentSpawnsPerRun,
|
|
19
19
|
resolveMaxSubagentSpawnsPerRun,
|
|
@@ -41,6 +41,8 @@ interface DoctorReportInput {
|
|
|
41
41
|
requestedSessionDir?: string;
|
|
42
42
|
currentSessionFile?: string | null;
|
|
43
43
|
currentSessionId?: string | null;
|
|
44
|
+
spawnBudget: SpawnBudgetSnapshot;
|
|
45
|
+
activeAsyncCapacity: ActiveAsyncCapacitySnapshot;
|
|
44
46
|
orchestratorTarget?: string;
|
|
45
47
|
sessionError?: string;
|
|
46
48
|
expandTilde?: (value: string) => string;
|
|
@@ -178,7 +180,7 @@ function formatIntercomDiagnostic(diagnostic: IntercomBridgeDiagnostic, context:
|
|
|
178
180
|
}
|
|
179
181
|
|
|
180
182
|
function formatSpawnBudgetSection(input: DoctorReportInput): string[] {
|
|
181
|
-
const snapshot =
|
|
183
|
+
const snapshot = input.spawnBudget;
|
|
182
184
|
return [
|
|
183
185
|
`- usage: ${formatSpawnBudgetSummary(snapshot)}`,
|
|
184
186
|
`- recent grants: ${snapshot.grantHistory.length === 0
|
|
@@ -197,12 +199,7 @@ function formatRunFanoutSection(input: DoctorReportInput): string[] {
|
|
|
197
199
|
}
|
|
198
200
|
|
|
199
201
|
function formatActiveAsyncCapacitySection(input: DoctorReportInput): string[] {
|
|
200
|
-
const
|
|
201
|
-
const sessionId = input.currentSessionId ?? input.state.currentSessionId;
|
|
202
|
-
const snapshot = sessionId
|
|
203
|
-
? getActiveAsyncCapacitySnapshot(sessionId, limit, { liveWorkflowRunIds: new Set(input.state.workflowControllers?.keys() ?? []), abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(input.config.capacity?.abandonedSlotReleaseAfterMs) })
|
|
204
|
-
: { used: 0, limit: limit ?? 0 };
|
|
205
|
-
input.state.activeAsyncCapacity = snapshot;
|
|
202
|
+
const snapshot = input.activeAsyncCapacity;
|
|
206
203
|
return [
|
|
207
204
|
`- usage: ${snapshot.used}/${snapshot.limit || "unlimited"} used`,
|
|
208
205
|
"- scope: top-level async runs in the current parent session; foreground and nested workflow children are not charged again",
|
|
@@ -4,18 +4,19 @@ import * as path from "node:path";
|
|
|
4
4
|
import type { ExtensionAPI, ToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
5
5
|
import { discoverAgents } from "../agents/agents.ts";
|
|
6
6
|
import { getArtifactsDir } from "../shared/artifacts.ts";
|
|
7
|
-
import { createSubagentExecutor
|
|
7
|
+
import { createSubagentExecutor } from "../runs/foreground/subagent-executor.ts";
|
|
8
8
|
import { resolveWaitToolConfig } from "../runs/background/wait-config.ts";
|
|
9
9
|
import type { ChildRuntimeConfig } from "../runs/shared/child-runtime-config.ts";
|
|
10
|
-
import { readNestedControlRequests, resolveInheritedNestedRoute, type NestedRoute, writeNestedControlResult } from "../runs/shared/nested-events.ts";
|
|
10
|
+
import { nestedRunNotActiveMessage, readNestedControlRequests, resolveInheritedNestedRoute, type NestedRoute, writeNestedControlResult } from "../runs/shared/nested-events.ts";
|
|
11
11
|
import { deliverSubagentIntercomMessageEvent } from "../intercom/result-intercom.ts";
|
|
12
12
|
import { createNativeSupervisorChannel, NATIVE_SUPERVISOR_TOOL_NAME, resolveSupervisorChannelDir } from "../intercom/native-supervisor-channel.ts";
|
|
13
13
|
import { readStatus } from "../shared/utils.ts";
|
|
14
14
|
import { resolveSubagentIntercomTarget } from "../intercom/intercom-bridge.ts";
|
|
15
15
|
import { createSubagentParamsSchema } from "./schemas.ts";
|
|
16
|
+
import { registerPinnedTool } from "./declaration-pinning.ts";
|
|
16
17
|
import { resolveDisabledFeatureSurface } from "../shared/disabled-features.ts";
|
|
17
18
|
import { finalizeToolResult } from "./tool-result.ts";
|
|
18
|
-
import {
|
|
19
|
+
import { flattenSubagentToolOptions } from "./subagent-options.ts";
|
|
19
20
|
import { loadConfig, resolveAsyncByDefault } from "./config.ts";
|
|
20
21
|
import { SUBAGENT_ASYNC_STARTED_EVENT, type AsyncStartedEvent, type Details, type SubagentState } from "../shared/types.ts";
|
|
21
22
|
import { createChildExternalJobBridgeSweeper } from "../runs/shared/external-job-bridge.ts";
|
|
@@ -95,7 +96,7 @@ function startNestedControlInboxListener(pi: ExtensionAPI, state: SubagentState,
|
|
|
95
96
|
try {
|
|
96
97
|
const control = state.foregroundControls.get(request.targetRunId);
|
|
97
98
|
if (!control) {
|
|
98
|
-
message =
|
|
99
|
+
message = nestedRunNotActiveMessage(request.targetRunId);
|
|
99
100
|
} else if (request.action === "interrupt") {
|
|
100
101
|
ok = control.interrupt?.() === true;
|
|
101
102
|
message = ok
|
|
@@ -229,13 +230,11 @@ export default function registerFanoutChildSubagentExtension(pi: ExtensionAPI, c
|
|
|
229
230
|
].join("\n"),
|
|
230
231
|
parameters: params,
|
|
231
232
|
async execute(id, params, signal, onUpdate, ctx) {
|
|
232
|
-
|
|
233
|
-
if (removedField) throw new Error(removedField);
|
|
234
|
-
return finalizeToolResult(await executor.executePublic(id, params as SubagentParamsLike, signal ?? new AbortController().signal, onUpdate, ctx));
|
|
233
|
+
return finalizeToolResult(await executor.executePublic(id, flattenSubagentToolOptions(params, disabledFeatures), signal ?? new AbortController().signal, onUpdate, ctx));
|
|
235
234
|
},
|
|
236
235
|
};
|
|
237
236
|
|
|
238
|
-
pi
|
|
237
|
+
registerPinnedTool(pi, tool);
|
|
239
238
|
const bridgeSweeper = createChildExternalJobBridgeSweeper();
|
|
240
239
|
const unsubscribeBridgeStarted = pi.events.on(SUBAGENT_ASYNC_STARTED_EVENT, (payload: unknown) => {
|
|
241
240
|
const info = payload as AsyncStartedEvent;
|