@timmyjl12/pi-subagents 0.20.0 → 0.21.1
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 +862 -827
- package/README.md +1125 -1080
- package/dist/active-agents-prompt.d.ts +31 -9
- package/dist/active-agents-prompt.js +73 -9
- package/dist/agent-color.js +9 -1
- package/dist/agent-file-toggle.d.ts +1 -1
- package/dist/agent-manager.d.ts +405 -18
- package/dist/agent-manager.js +1661 -131
- package/dist/agent-runner.d.ts +45 -6
- package/dist/agent-runner.js +109 -18
- package/dist/agent-types.d.ts +30 -7
- package/dist/agent-types.js +38 -9
- package/dist/awaited-result.d.ts +37 -0
- package/dist/awaited-result.js +150 -0
- package/dist/child-session-shutdown.d.ts +19 -1
- package/dist/child-session-shutdown.js +60 -11
- package/dist/cleanup-plans.d.ts +10 -0
- package/dist/cleanup-plans.js +112 -0
- package/dist/cross-extension-rpc.d.ts +8 -1
- package/dist/cross-extension-rpc.js +59 -5
- package/dist/custom-agents.d.ts +34 -9
- package/dist/custom-agents.js +308 -111
- package/dist/default-agents.d.ts +1 -1
- package/dist/env.d.ts +1 -1
- package/dist/error-log.d.ts +6 -0
- package/dist/error-log.js +8 -0
- package/dist/force-main-model.d.ts +21 -0
- package/dist/force-main-model.js +28 -0
- package/dist/goal-bridge.d.ts +155 -0
- package/dist/goal-bridge.js +305 -0
- package/dist/group-join.d.ts +5 -1
- package/dist/group-join.js +52 -7
- package/dist/index.d.ts +5 -5
- package/dist/index.js +2827 -333
- package/dist/invocation-config.d.ts +30 -3
- package/dist/invocation-config.js +30 -1
- package/dist/memory.d.ts +1 -1
- package/dist/mention-clone.d.ts +1 -1
- package/dist/model-scope.d.ts +1 -1
- package/dist/nested-tools.d.ts +22 -1
- package/dist/nested-tools.js +120 -26
- package/dist/output-file.d.ts +15 -4
- package/dist/output-file.js +146 -43
- package/dist/prompts.d.ts +1 -1
- package/dist/recovery.d.ts +1 -1
- package/dist/report-cleanup.d.ts +204 -0
- package/dist/report-cleanup.js +1632 -0
- package/dist/report-store.d.ts +738 -0
- package/dist/report-store.js +3616 -0
- package/dist/schedule-store.d.ts +14 -6
- package/dist/schedule-store.js +88 -58
- package/dist/schedule.d.ts +20 -8
- package/dist/schedule.js +135 -74
- package/dist/settings.d.ts +39 -11
- package/dist/settings.js +22 -5
- package/dist/status-note.d.ts +1 -1
- package/dist/structured-output.d.ts +1 -1
- package/dist/types.d.ts +32 -3
- package/dist/ui/agent-mention.d.ts +2 -2
- package/dist/ui/agent-widget.d.ts +82 -13
- package/dist/ui/agent-widget.js +155 -37
- package/dist/ui/cleanup-preview.d.ts +59 -0
- package/dist/ui/cleanup-preview.js +466 -0
- package/dist/ui/conversation-viewer.d.ts +4 -4
- package/dist/ui/conversation-viewer.js +10 -6
- package/dist/ui/fleet-list.d.ts +3 -3
- package/dist/ui/fleet-list.js +3 -3
- package/dist/ui/fleet-overlay.d.ts +37 -6
- package/dist/ui/fleet-overlay.js +214 -18
- package/dist/ui/hub-feed.d.ts +52 -0
- package/dist/ui/hub-feed.js +148 -0
- package/dist/ui/native-transcript.js +5 -1
- package/dist/ui/schedule-menu.d.ts +1 -1
- package/dist/ui/schedule-menu.js +1 -1
- package/dist/ui/workflow-card.d.ts +4 -4
- package/dist/ui/workflow-dialog.d.ts +4 -4
- package/dist/ui/workflow-dialog.js +8 -3
- package/dist/ui/workflow-menu.d.ts +2 -2
- package/dist/usage.d.ts +12 -0
- package/dist/usage.js +28 -1
- package/dist/workflow/entry.d.ts +3 -3
- package/dist/workflow/host.d.ts +7 -4
- package/dist/workflow/host.js +162 -48
- package/dist/workflow/journal.d.ts +23 -7
- package/dist/workflow/journal.js +80 -23
- package/dist/workflow/progress.d.ts +1 -1
- package/dist/workflow/runtime.d.ts +45 -6
- package/dist/workflow/runtime.js +105 -16
- package/dist/workflow/task.d.ts +13 -4
- package/dist/workflow/task.js +7 -1
- package/dist/workflow/tool-description.d.ts +7 -2
- package/dist/workflow/tool-description.js +10 -5
- package/docs/{FORK.md → DEVELOPMENT.md} +4 -4
- package/docs/artifacts.md +93 -0
- package/docs/rpc.md +252 -189
- package/docs/runtime-performance.md +53 -0
- package/docs/workflows.md +48 -18
- package/examples/agent-tool-description.md +2 -2
- package/examples/workflows/review-panel.js +6 -3
- package/package.json +5 -5
- package/src/active-agents-prompt.ts +115 -39
- package/src/agent-color.ts +10 -2
- package/src/agent-file-toggle.ts +2 -2
- package/src/agent-manager.ts +3312 -1601
- package/src/agent-runner.ts +164 -36
- package/src/agent-types.ts +56 -11
- package/src/awaited-result.ts +187 -0
- package/src/child-session-shutdown.ts +114 -46
- package/src/cleanup-plans.ts +112 -0
- package/src/cross-extension-rpc.ts +68 -9
- package/src/custom-agents.ts +384 -112
- package/src/default-agents.ts +1 -1
- package/src/enabled-models.ts +1 -1
- package/src/env.ts +1 -1
- package/src/error-log.ts +10 -1
- package/src/force-main-model.ts +29 -0
- package/src/goal-bridge.ts +468 -0
- package/src/group-join.ts +56 -9
- package/src/index.ts +2987 -349
- package/src/invocation-config.ts +50 -4
- package/src/memory.ts +1 -1
- package/src/mention-clone.ts +3 -3
- package/src/model-scope.ts +1 -1
- package/src/nested-tools.ts +164 -33
- package/src/output-file.ts +168 -46
- package/src/prompts.ts +1 -1
- package/src/recovery.ts +2 -2
- package/src/report-cleanup.ts +2044 -0
- package/src/report-store.ts +4133 -0
- package/src/schedule-store.ts +244 -201
- package/src/schedule.ts +144 -80
- package/src/settings.ts +61 -16
- package/src/skill-loader.ts +1 -1
- package/src/standalone-fallback.ts +2 -2
- package/src/status-note.ts +1 -1
- package/src/structured-output.ts +1 -1
- package/src/types.ts +33 -3
- package/src/ui/agent-mention.ts +3 -3
- package/src/ui/agent-widget.ts +179 -45
- package/src/ui/cleanup-preview.ts +518 -0
- package/src/ui/conversation-viewer.ts +19 -15
- package/src/ui/fleet-list.ts +7 -7
- package/src/ui/fleet-overlay.ts +1048 -847
- package/src/ui/hub-feed.ts +179 -0
- package/src/ui/native-transcript.ts +7 -3
- package/src/ui/schedule-menu.ts +4 -4
- package/src/ui/workflow-card.ts +4 -4
- package/src/ui/workflow-dialog.ts +10 -6
- package/src/ui/workflow-menu.ts +4 -4
- package/src/usage.ts +53 -3
- package/src/workflow/collisions.ts +1 -1
- package/src/workflow/entry.ts +3 -3
- package/src/workflow/host.ts +174 -54
- package/src/workflow/journal.ts +80 -23
- package/src/workflow/progress.ts +1 -1
- package/src/workflow/runtime.ts +146 -23
- package/src/workflow/saved.ts +3 -3
- package/src/workflow/task.ts +18 -7
- package/src/workflow/tool-description.ts +10 -5
|
@@ -1,3 +1,21 @@
|
|
|
1
1
|
import type { AgentSession } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
/**
|
|
3
|
+
* How a child session's teardown ended.
|
|
4
|
+
*
|
|
5
|
+
* The old `Promise<void>` contract could not answer the one question cleanup
|
|
6
|
+
* must ask before deleting a session's files: did every shutdown handler
|
|
7
|
+
* actually finish? A three-second timeout used to resolve exactly like a clean
|
|
8
|
+
* teardown, so "disposed" and "gave up waiting" were indistinguishable — and a
|
|
9
|
+
* cleanup that treated them alike could unlink a transcript a still-running
|
|
10
|
+
* handler was about to write.
|
|
11
|
+
*/
|
|
12
|
+
export type ChildShutdownStatus = "completed" | "timed_out" | "failed";
|
|
13
|
+
export interface ChildShutdownOutcome {
|
|
14
|
+
status: ChildShutdownStatus;
|
|
15
|
+
/** True only when the bounded handler window expired. */
|
|
16
|
+
timedOut: boolean;
|
|
17
|
+
/** Diagnostic for `failed`/`timed_out`; never proof of quiescence. */
|
|
18
|
+
reason?: string;
|
|
19
|
+
}
|
|
2
20
|
/** Close the extension lifecycle opened by bindExtensions before invalidating the session. */
|
|
3
|
-
export declare function shutdownChildSession(session: AgentSession | undefined): Promise<
|
|
21
|
+
export declare function shutdownChildSession(session: AgentSession | undefined): Promise<ChildShutdownOutcome>;
|
|
@@ -2,11 +2,15 @@ import { releaseAdvisorStatus } from "./advisor-status.js";
|
|
|
2
2
|
import { disposeChildRecovery } from "./recovery.js";
|
|
3
3
|
import { releaseToolProgress } from "./ui/tool-progress.js";
|
|
4
4
|
const CHILD_SHUTDOWN_TIMEOUT_MS = 3_000;
|
|
5
|
+
const COMPLETED = Object.freeze({
|
|
6
|
+
status: "completed",
|
|
7
|
+
timedOut: false,
|
|
8
|
+
});
|
|
5
9
|
const childShutdowns = new WeakMap();
|
|
6
10
|
/** Close the extension lifecycle opened by bindExtensions before invalidating the session. */
|
|
7
11
|
export function shutdownChildSession(session) {
|
|
8
12
|
if (!session)
|
|
9
|
-
return Promise.resolve();
|
|
13
|
+
return Promise.resolve(COMPLETED);
|
|
10
14
|
const pending = childShutdowns.get(session);
|
|
11
15
|
if (pending)
|
|
12
16
|
return pending;
|
|
@@ -18,31 +22,76 @@ async function closeChildSession(session) {
|
|
|
18
22
|
disposeChildRecovery(session);
|
|
19
23
|
releaseToolProgress(session);
|
|
20
24
|
let timeout;
|
|
25
|
+
let timedOut = false;
|
|
26
|
+
let failure;
|
|
27
|
+
let unsubscribeError;
|
|
28
|
+
const observeError = (error) => {
|
|
29
|
+
// The installed ExtensionRunner catches a throwing handler, publishes it
|
|
30
|
+
// here, and RESOLVES emit() normally. Without this subscription a failed
|
|
31
|
+
// real cleanup would be indistinguishable from a clean one.
|
|
32
|
+
if (error.event !== "session_shutdown")
|
|
33
|
+
return;
|
|
34
|
+
const where = error.extensionPath ? ` (${error.extensionPath})` : "";
|
|
35
|
+
failure ??= `session_shutdown handler failed${where}: ${error.error}`;
|
|
36
|
+
};
|
|
21
37
|
try {
|
|
22
38
|
const runner = session.extensionRunner;
|
|
23
39
|
if (runner?.hasHandlers?.("session_shutdown")) {
|
|
24
|
-
|
|
25
|
-
runner.
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
40
|
+
if (typeof runner.onError === "function") {
|
|
41
|
+
unsubscribeError = runner.onError(observeError);
|
|
42
|
+
}
|
|
43
|
+
try {
|
|
44
|
+
await Promise.race([
|
|
45
|
+
runner.emit({ type: "session_shutdown", reason: "quit" }),
|
|
46
|
+
new Promise(resolve => {
|
|
47
|
+
timeout = setTimeout(() => {
|
|
48
|
+
timedOut = true;
|
|
49
|
+
resolve();
|
|
50
|
+
}, CHILD_SHUTDOWN_TIMEOUT_MS);
|
|
51
|
+
timeout.unref?.();
|
|
52
|
+
}),
|
|
53
|
+
]);
|
|
54
|
+
}
|
|
55
|
+
finally {
|
|
56
|
+
unsubscribeError?.();
|
|
57
|
+
unsubscribeError = undefined;
|
|
58
|
+
}
|
|
31
59
|
}
|
|
32
60
|
}
|
|
33
|
-
catch {
|
|
61
|
+
catch (error) {
|
|
34
62
|
// A partially bound extension must not prevent child teardown.
|
|
63
|
+
failure = error instanceof Error ? error.message : String(error);
|
|
35
64
|
console.error("pi-subagents: child shutdown handler failed");
|
|
36
65
|
}
|
|
37
66
|
finally {
|
|
38
|
-
|
|
67
|
+
// Always drop the temporary listener, including a rejecting emit and a
|
|
68
|
+
// timeout that never returns through the emit promise.
|
|
69
|
+
unsubscribeError?.();
|
|
70
|
+
try {
|
|
71
|
+
releaseAdvisorStatus(session);
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
failure ??= error instanceof Error ? error.message : String(error);
|
|
75
|
+
}
|
|
39
76
|
if (timeout !== undefined)
|
|
40
77
|
clearTimeout(timeout);
|
|
41
78
|
try {
|
|
42
79
|
session.dispose?.();
|
|
43
80
|
}
|
|
44
|
-
catch {
|
|
81
|
+
catch (error) {
|
|
82
|
+
failure ??= error instanceof Error ? error.message : String(error);
|
|
45
83
|
console.error("pi-subagents: child session disposal failed");
|
|
46
84
|
}
|
|
47
85
|
}
|
|
86
|
+
if (timedOut) {
|
|
87
|
+
return {
|
|
88
|
+
status: "timed_out",
|
|
89
|
+
timedOut: true,
|
|
90
|
+
reason: `session_shutdown handler exceeded ${CHILD_SHUTDOWN_TIMEOUT_MS}ms`,
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
if (failure !== undefined) {
|
|
94
|
+
return { status: "failed", timedOut: false, reason: failure };
|
|
95
|
+
}
|
|
96
|
+
return COMPLETED;
|
|
48
97
|
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** Assemble one confirmed inventory without changing lease ownership or replanning. */
|
|
2
|
+
import { type CleanupPlan } from "./report-cleanup.ts";
|
|
3
|
+
/**
|
|
4
|
+
* A base global inventory sees another local store's lease as foreign. Replace
|
|
5
|
+
* only that namespace with its owning store's session inventory; never relax
|
|
6
|
+
* nonce checks, close stores, or lose global identity evidence.
|
|
7
|
+
*/
|
|
8
|
+
export declare function mergeCleanupPlans(base: CleanupPlan, overrides: ReadonlyMap<string, CleanupPlan>): CleanupPlan;
|
|
9
|
+
/** Each root stays in one apply; diagnostics is a single final partition. */
|
|
10
|
+
export declare function partitionCleanupPlan(plan: CleanupPlan): CleanupPlan[];
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/** Assemble one confirmed inventory without changing lease ownership or replanning. */
|
|
2
|
+
import { cleanupCounts, } from "./report-cleanup.js";
|
|
3
|
+
import { normalizeReportPath } from "./report-store.js";
|
|
4
|
+
function withFiles(plan, files) {
|
|
5
|
+
const agents = new Set();
|
|
6
|
+
const sessions = new Set();
|
|
7
|
+
for (const file of files) {
|
|
8
|
+
if (file.agentId !== undefined)
|
|
9
|
+
agents.add(file.agentId);
|
|
10
|
+
if (file.kind === "child-session" && file.sessionFile !== undefined)
|
|
11
|
+
sessions.add(file.sessionFile);
|
|
12
|
+
}
|
|
13
|
+
return { ...plan, files, counts: cleanupCounts(files), agentIds: [...agents].sort(), sessionFiles: [...sessions].sort() };
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* A base global inventory sees another local store's lease as foreign. Replace
|
|
17
|
+
* only that namespace with its owning store's session inventory; never relax
|
|
18
|
+
* nonce checks, close stores, or lose global identity evidence.
|
|
19
|
+
*/
|
|
20
|
+
export function mergeCleanupPlans(base, overrides) {
|
|
21
|
+
if (base.scope !== "global" && overrides.size > 0) {
|
|
22
|
+
throw new Error("Owning-store overrides require global scope");
|
|
23
|
+
}
|
|
24
|
+
const roots = new Map(base.roots.map(root => [root.rootSessionId, root]));
|
|
25
|
+
const files = new Map();
|
|
26
|
+
const conflicts = new Set();
|
|
27
|
+
const skipped = base.skipped.filter(skip => skip.rootSessionId === undefined || !overrides.has(skip.rootSessionId));
|
|
28
|
+
let identityUncertainty = base.identityUncertainty;
|
|
29
|
+
const addFile = (file) => {
|
|
30
|
+
const key = normalizeReportPath(file.path);
|
|
31
|
+
if (conflicts.has(key)) {
|
|
32
|
+
skipped.push({ path: file.path, rootSessionId: file.rootSessionId, kind: file.kind, agentId: file.agentId, workflowId: file.workflowId, reason: "conflicting-preview-ownership" });
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
const previous = files.get(key);
|
|
36
|
+
if (previous === undefined) {
|
|
37
|
+
files.set(key, file);
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
const same = previous.kind === file.kind && previous.rootSessionId === file.rootSessionId
|
|
41
|
+
&& previous.agentId === file.agentId && previous.workflowId === file.workflowId
|
|
42
|
+
&& previous.size === file.size && previous.mtimeMs === file.mtimeMs
|
|
43
|
+
&& previous.fingerprint === file.fingerprint && previous.entryGeneration === file.entryGeneration
|
|
44
|
+
&& previous.workflowUpdatedAt === file.workflowUpdatedAt && previous.legacy === file.legacy
|
|
45
|
+
&& previous.shared === file.shared && previous.sessionFile === file.sessionFile;
|
|
46
|
+
if (same) {
|
|
47
|
+
if (file.readState === "unread" || (previous.readState === "read" && file.readState === "unknown")) {
|
|
48
|
+
files.set(key, { ...previous, readState: file.readState });
|
|
49
|
+
}
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
files.delete(key);
|
|
53
|
+
conflicts.add(key);
|
|
54
|
+
for (const candidate of [previous, file]) {
|
|
55
|
+
skipped.push({ path: candidate.path, rootSessionId: candidate.rootSessionId, kind: candidate.kind, agentId: candidate.agentId, workflowId: candidate.workflowId, reason: "conflicting-preview-ownership" });
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
for (const file of base.files) {
|
|
59
|
+
if (!overrides.has(file.rootSessionId))
|
|
60
|
+
addFile(file);
|
|
61
|
+
}
|
|
62
|
+
for (const [rootSessionId, plan] of overrides) {
|
|
63
|
+
identityUncertainty ??= plan.identityUncertainty;
|
|
64
|
+
// Preserve all identities, not just the namespace whose candidates replace
|
|
65
|
+
// the base. Only its owning store may replace an existing fingerprint.
|
|
66
|
+
for (const root of plan.roots) {
|
|
67
|
+
if (root.rootSessionId === rootSessionId || !roots.has(root.rootSessionId))
|
|
68
|
+
roots.set(root.rootSessionId, root);
|
|
69
|
+
}
|
|
70
|
+
for (const file of plan.files) {
|
|
71
|
+
if (file.rootSessionId === rootSessionId)
|
|
72
|
+
addFile(file);
|
|
73
|
+
}
|
|
74
|
+
for (const skip of plan.skipped) {
|
|
75
|
+
if (skip.reason !== "legacy-outside-session-scope" && skip.rootSessionId === rootSessionId)
|
|
76
|
+
skipped.push(skip);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
const uniqueSkips = new Map();
|
|
80
|
+
for (const skip of skipped) {
|
|
81
|
+
const key = JSON.stringify([skip.path === undefined ? null : normalizeReportPath(skip.path), skip.kind, skip.rootSessionId, skip.agentId, skip.workflowId, skip.reason, skip.legacy]);
|
|
82
|
+
uniqueSkips.set(key, skip);
|
|
83
|
+
}
|
|
84
|
+
return withFiles({
|
|
85
|
+
...base,
|
|
86
|
+
roots: [...roots.values()],
|
|
87
|
+
skipped: [...uniqueSkips.values()],
|
|
88
|
+
...(identityUncertainty === undefined ? {} : { identityUncertainty }),
|
|
89
|
+
}, [...files.values()]);
|
|
90
|
+
}
|
|
91
|
+
/** Each root stays in one apply; diagnostics is a single final partition. */
|
|
92
|
+
export function partitionCleanupPlan(plan) {
|
|
93
|
+
const groups = new Map();
|
|
94
|
+
for (const file of plan.files) {
|
|
95
|
+
const key = file.kind === "diagnostics-log" ? "" : file.rootSessionId;
|
|
96
|
+
const group = groups.get(key);
|
|
97
|
+
if (group === undefined)
|
|
98
|
+
groups.set(key, [file]);
|
|
99
|
+
else
|
|
100
|
+
group.push(file);
|
|
101
|
+
}
|
|
102
|
+
const result = [];
|
|
103
|
+
const keys = [...groups.keys()].filter(key => key !== "").sort();
|
|
104
|
+
if (groups.has(""))
|
|
105
|
+
keys.push("");
|
|
106
|
+
for (const key of keys) {
|
|
107
|
+
// Keep ALL confirmed identity fingerprints and uncertainty in each part.
|
|
108
|
+
// The caller aggregates original preview skips exactly once.
|
|
109
|
+
result.push(withFiles({ ...plan, skipped: [] }, groups.get(key) ?? []));
|
|
110
|
+
}
|
|
111
|
+
return result;
|
|
112
|
+
}
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
* (including the fields spawnTopLevel strips), every error string, the
|
|
13
13
|
* completion-notification race, and what protocol version 2 does not promise.
|
|
14
14
|
*/
|
|
15
|
-
import type { AgentRecord } from "./types.
|
|
15
|
+
import type { AgentConfig, AgentRecord } from "./types.ts";
|
|
16
16
|
/** Minimal event bus interface needed by the RPC handlers. */
|
|
17
17
|
export interface EventBus {
|
|
18
18
|
on(event: string, handler: (data: unknown) => void): () => void;
|
|
@@ -52,6 +52,13 @@ export interface RpcDeps {
|
|
|
52
52
|
pi: unknown;
|
|
53
53
|
getCtx: () => unknown | undefined;
|
|
54
54
|
manager: SpawnCapable;
|
|
55
|
+
/**
|
|
56
|
+
* Refreshes the caller's scoped registry for an ordinary spawn admission.
|
|
57
|
+
* When present, the requested type is resolved against this map and the
|
|
58
|
+
* admitted definition is cloned into the spawn options. Absent keeps the
|
|
59
|
+
* legacy pass-through behaviour for callers that wire no async preparation.
|
|
60
|
+
*/
|
|
61
|
+
prepare?: () => Promise<Map<string, AgentConfig>>;
|
|
55
62
|
}
|
|
56
63
|
export interface RpcHandle {
|
|
57
64
|
unsubPing: () => void;
|
|
@@ -13,6 +13,9 @@
|
|
|
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 { getAllowPerCallTurnLimits, resolveEffectiveMaxTurns } from "./agent-runner.js";
|
|
17
|
+
import { cloneAgentDefinition, getAgentConfigIn, resolveSpawnTypeIn } from "./agent-types.js";
|
|
18
|
+
import { isForceMainModel } from "./force-main-model.js";
|
|
16
19
|
import { resolveModel } from "./model-resolver.js";
|
|
17
20
|
import { checkModelScope } from "./model-scope.js";
|
|
18
21
|
/** RPC protocol version — bumped when the envelope or method contracts change. */
|
|
@@ -51,18 +54,59 @@ export function registerRpcHandlers(deps) {
|
|
|
51
54
|
const ctx = getCtx();
|
|
52
55
|
if (!ctx)
|
|
53
56
|
throw new Error("No active session");
|
|
57
|
+
// Refresh and resolve against the caller's OWN scoped registry before
|
|
58
|
+
// anything can suspend. The clone freezes prompt, tool permissions and
|
|
59
|
+
// model/session/nesting policy through queueing, worktree setup and the
|
|
60
|
+
// runner; a later process-wide reload cannot widen or narrow this child.
|
|
61
|
+
// No `prepare` means the legacy path: the manager receives the requested
|
|
62
|
+
// type and no definition snapshot, exactly as before.
|
|
63
|
+
const registry = deps.prepare === undefined ? undefined : await deps.prepare();
|
|
64
|
+
let spawnType = type;
|
|
65
|
+
let agentDefinition;
|
|
66
|
+
if (registry !== undefined) {
|
|
67
|
+
const dispatch = resolveSpawnTypeIn(registry, type);
|
|
68
|
+
if (!dispatch.ok)
|
|
69
|
+
throw new Error(dispatch.message);
|
|
70
|
+
spawnType = dispatch.type;
|
|
71
|
+
const config = getAgentConfigIn(registry, spawnType);
|
|
72
|
+
agentDefinition = config === undefined ? undefined : cloneAgentDefinition(config);
|
|
73
|
+
}
|
|
54
74
|
// Cross-extension RPC callers (e.g. pi-tasks TaskExecute) naturally
|
|
55
75
|
// forward serializable values, so options.model can be a string like
|
|
56
76
|
// "openai-codex/gpt-5.5". Resolve it to a real Model instance here
|
|
57
77
|
// — same pattern the scheduler path already uses — so the spawned
|
|
58
78
|
// agent's auth lookup doesn't crash with "No API key found for
|
|
59
79
|
// undefined".
|
|
60
|
-
|
|
80
|
+
// Own caller options only: inherited admission fields must not reach a
|
|
81
|
+
// legacy manager when no other normalization happens to copy the object.
|
|
82
|
+
let normalizedOptions = { ...(options ?? {}) };
|
|
83
|
+
// Admission state comes only from this handler's prepared scoped registry.
|
|
84
|
+
// Never mutate the caller or trust its own/non-enumerable definition.
|
|
85
|
+
delete normalizedOptions.agentDefinition;
|
|
86
|
+
// Caller caps are a policy opt-in, and an RPC payload is unvalidated: a
|
|
87
|
+
// caller that bypasses the tool schema can still send `maxTurns`. Strip
|
|
88
|
+
// it here so the runner's low-level option contract cannot be reached
|
|
89
|
+
// around the switch. Copy first — never mutate the caller's own object.
|
|
90
|
+
if (!getAllowPerCallTurnLimits()) {
|
|
91
|
+
normalizedOptions = { ...normalizedOptions };
|
|
92
|
+
delete normalizedOptions.maxTurns;
|
|
93
|
+
const invocation = normalizedOptions.invocation;
|
|
94
|
+
if (invocation !== null && typeof invocation === "object") {
|
|
95
|
+
normalizedOptions.invocation = { ...invocation, maxTurns: resolveEffectiveMaxTurns(spawnType) };
|
|
96
|
+
}
|
|
97
|
+
}
|
|
61
98
|
// `!= null` on purpose: a JSON-forwarding caller can serialize an unset
|
|
62
99
|
// field as null, and the runner reads `options.model ?? default`, so null
|
|
63
100
|
// means "inherit" — not an override to resolve or scope-check.
|
|
64
101
|
const override = normalizedOptions.model;
|
|
65
|
-
if (override != null) {
|
|
102
|
+
if (override != null && isForceMainModel()) {
|
|
103
|
+
// Dropped, not deferred: a queued spawn reads the switch when it
|
|
104
|
+
// STARTS, and a raw string that reaches the runner after a mid-queue
|
|
105
|
+
// `/subagents on` is the "No API key found for undefined" crash this
|
|
106
|
+
// resolution exists to prevent.
|
|
107
|
+
normalizedOptions = { ...normalizedOptions, model: undefined };
|
|
108
|
+
}
|
|
109
|
+
else if (override != null) {
|
|
66
110
|
const { modelRegistry, cwd } = ctx;
|
|
67
111
|
// Names the override the same way in both messages below; an object
|
|
68
112
|
// override would otherwise interpolate as "[object Object]".
|
|
@@ -93,17 +137,27 @@ export function registerRpcHandlers(deps) {
|
|
|
93
137
|
cwd: cwd ?? process.cwd(),
|
|
94
138
|
modelRegistry,
|
|
95
139
|
callerSupplied: true,
|
|
96
|
-
agentLabel:
|
|
140
|
+
agentLabel: spawnType,
|
|
97
141
|
modelInput: label,
|
|
98
142
|
});
|
|
99
143
|
if (verdict.kind === "error")
|
|
100
144
|
throw new Error(verdict.message);
|
|
101
145
|
}
|
|
102
|
-
const
|
|
146
|
+
const spawnOptions = agentDefinition === undefined
|
|
147
|
+
? normalizedOptions
|
|
148
|
+
: { ...normalizedOptions, agentDefinition };
|
|
149
|
+
const id = manager.spawn(pi, ctx, spawnType, prompt, spawnOptions);
|
|
103
150
|
// With isolation: "worktree" the agent starts asynchronously — wait for
|
|
104
151
|
// it, so a strict-isolation failure is still an error envelope rather
|
|
105
152
|
// than an id for an agent that never ran.
|
|
106
|
-
|
|
153
|
+
try {
|
|
154
|
+
await manager.awaitStartup(id);
|
|
155
|
+
}
|
|
156
|
+
catch (error) {
|
|
157
|
+
// The error envelope is the result; do not also wake the main model.
|
|
158
|
+
manager.consumeResult(id);
|
|
159
|
+
throw error;
|
|
160
|
+
}
|
|
107
161
|
return { id };
|
|
108
162
|
});
|
|
109
163
|
const unsubStop = handleRpc(events, "subagents:rpc:stop", ({ agentId }) => {
|
package/dist/custom-agents.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* custom-agents.ts — Load user-defined agents from project (.pi/agents/, plus the shared .agents/agents/ workspace) and global ($PI_CODING_AGENT_DIR/agents/, default ~/.pi/agent/agents/) locations.
|
|
3
3
|
*/
|
|
4
|
-
import type { AgentConfig } from "./types.
|
|
4
|
+
import type { AgentConfig } from "./types.ts";
|
|
5
5
|
/**
|
|
6
6
|
* Scan for custom agent .md files from multiple locations.
|
|
7
7
|
* Discovery hierarchy (higher priority wins):
|
|
@@ -22,17 +22,22 @@ import type { AgentConfig } from "./types.js";
|
|
|
22
22
|
*/
|
|
23
23
|
export declare function loadCustomAgents(cwd: string, strict?: boolean): Map<string, AgentConfig>;
|
|
24
24
|
/**
|
|
25
|
-
*
|
|
26
|
-
* skip. One bad file must not take the whole extension down with it — an
|
|
27
|
-
* unparseable `.md` used to abort activation, so pi exited before the TUI.
|
|
25
|
+
* Async twin of {@link loadCustomAgents} for ordinary awaitable admission.
|
|
28
26
|
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
27
|
+
* Discovery and content reads are fresh every call; only the raw YAML parse is
|
|
28
|
+
* reused, and only when the bytes just read are identical. That distinction is
|
|
29
|
+
* deliberate: caching a size/mtime stamp would let a same-size edit through,
|
|
30
|
+
* and caching a validated AgentConfig would make a lenient load's skipped or
|
|
31
|
+
* coerced field authorize a strict request. Cache entries are bounded by both
|
|
32
|
+
* entry count and retained bytes, so a pathological directory cannot pin
|
|
33
|
+
* arbitrary content for the process lifetime.
|
|
32
34
|
*
|
|
33
|
-
*
|
|
34
|
-
*
|
|
35
|
+
* Concurrent callers for the same three-directory scope and strictness share
|
|
36
|
+
* one refresh. Each gets its own Map so a caller mutating its result cannot
|
|
37
|
+
* rewrite another caller's registry; warnings are collected per load and
|
|
38
|
+
* committed atomically when the shared load finishes.
|
|
35
39
|
*/
|
|
40
|
+
export declare function loadCustomAgentsAsync(cwd: string, strict?: boolean): Promise<Map<string, AgentConfig>>;
|
|
36
41
|
/**
|
|
37
42
|
* Parse an agent file's frontmatter, tolerating a leading UTF-8 BOM.
|
|
38
43
|
*
|
|
@@ -52,3 +57,23 @@ export declare function parseAgentFrontmatter<T extends Record<string, unknown>>
|
|
|
52
57
|
frontmatter: T;
|
|
53
58
|
body: string;
|
|
54
59
|
};
|
|
60
|
+
/**
|
|
61
|
+
* Bounds for the raw parse cache. `bytes` counts both the content used for
|
|
62
|
+
* exact equality and the parsed body retained beside it; it is a storage bound,
|
|
63
|
+
* not a limit on file size (a file larger than the cap simply is not cached).
|
|
64
|
+
*/
|
|
65
|
+
export declare const AGENT_PARSE_CACHE_MAX_ENTRIES = 64;
|
|
66
|
+
export declare const AGENT_PARSE_CACHE_MAX_BYTES: number;
|
|
67
|
+
export interface AgentParseCacheStats {
|
|
68
|
+
entries: number;
|
|
69
|
+
bytes: number;
|
|
70
|
+
parses: number;
|
|
71
|
+
hits: number;
|
|
72
|
+
evictions: number;
|
|
73
|
+
syncReads: number;
|
|
74
|
+
asyncReads: number;
|
|
75
|
+
}
|
|
76
|
+
/** Operation counts used by the definition-refresh tests. */
|
|
77
|
+
export declare function getAgentParseCacheStats(): AgentParseCacheStats;
|
|
78
|
+
/** Drop retained parses and counters so tests start from a known cache. */
|
|
79
|
+
export declare function resetAgentParseCache(): void;
|