@ymy88/pi-subagents 0.0.0-stage → 0.24.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 +904 -0
- package/CONTRIBUTING.md +72 -0
- package/LICENSE +21 -0
- package/README.md +1170 -2
- package/SECURITY.md +95 -0
- package/dist/abortable.d.ts +12 -0
- package/dist/abortable.js +42 -0
- package/dist/agent-color.d.ts +35 -0
- package/dist/agent-color.js +123 -0
- package/dist/agent-file-toggle.d.ts +133 -0
- package/dist/agent-file-toggle.js +287 -0
- package/dist/agent-manager.d.ts +552 -0
- package/dist/agent-manager.js +1466 -0
- package/dist/agent-record-entry.d.ts +96 -0
- package/dist/agent-record-entry.js +121 -0
- package/dist/agent-runner.d.ts +310 -0
- package/dist/agent-runner.js +1195 -0
- package/dist/agent-source-badge.d.ts +50 -0
- package/dist/agent-source-badge.js +74 -0
- package/dist/agent-types.d.ts +119 -0
- package/dist/agent-types.js +286 -0
- package/dist/child-context.d.ts +2 -0
- package/dist/child-context.js +12 -0
- package/dist/completion-outbox.d.ts +63 -0
- package/dist/completion-outbox.js +104 -0
- package/dist/context.d.ts +12 -0
- package/dist/context.js +56 -0
- package/dist/cross-extension-rpc.d.ts +72 -0
- package/dist/cross-extension-rpc.js +153 -0
- package/dist/custom-agents.d.ts +77 -0
- package/dist/custom-agents.js +396 -0
- package/dist/default-agents.d.ts +7 -0
- package/dist/default-agents.js +121 -0
- package/dist/enabled-models.d.ts +49 -0
- package/dist/enabled-models.js +145 -0
- package/dist/env.d.ts +6 -0
- package/dist/env.js +28 -0
- package/dist/group-join.d.ts +32 -0
- package/dist/group-join.js +116 -0
- package/dist/index.d.ts +50 -0
- package/dist/index.js +4111 -0
- package/dist/invocation-config.d.ts +108 -0
- package/dist/invocation-config.js +83 -0
- package/dist/memory.d.ts +53 -0
- package/dist/memory.js +165 -0
- package/dist/mention-clone.d.ts +79 -0
- package/dist/mention-clone.js +155 -0
- package/dist/mention.d.ts +81 -0
- package/dist/mention.js +131 -0
- package/dist/model-resolver.d.ts +36 -0
- package/dist/model-resolver.js +95 -0
- package/dist/model-scope.d.ts +49 -0
- package/dist/model-scope.js +48 -0
- package/dist/nested-tools.d.ts +57 -0
- package/dist/nested-tools.js +303 -0
- package/dist/output-file.d.ts +43 -0
- package/dist/output-file.js +153 -0
- package/dist/package-resources.d.ts +240 -0
- package/dist/package-resources.js +519 -0
- package/dist/prompts.d.ts +76 -0
- package/dist/prompts.js +121 -0
- package/dist/schedule-store.d.ts +38 -0
- package/dist/schedule-store.js +155 -0
- package/dist/schedule.d.ts +109 -0
- package/dist/schedule.js +359 -0
- package/dist/settings.d.ts +398 -0
- package/dist/settings.js +282 -0
- package/dist/skill-loader.d.ts +24 -0
- package/dist/skill-loader.js +93 -0
- package/dist/status-note.d.ts +61 -0
- package/dist/status-note.js +85 -0
- package/dist/structured-output.d.ts +61 -0
- package/dist/structured-output.js +112 -0
- package/dist/types.d.ts +391 -0
- package/dist/types.js +5 -0
- package/dist/ui/agent-mention.d.ts +82 -0
- package/dist/ui/agent-mention.js +187 -0
- package/dist/ui/agent-widget.d.ts +219 -0
- package/dist/ui/agent-widget.js +585 -0
- package/dist/ui/conversation-viewer.d.ts +177 -0
- package/dist/ui/conversation-viewer.js +905 -0
- package/dist/ui/fleet-list.d.ts +211 -0
- package/dist/ui/fleet-list.js +489 -0
- package/dist/ui/schedule-menu.d.ts +16 -0
- package/dist/ui/schedule-menu.js +94 -0
- package/dist/ui/select-item.d.ts +27 -0
- package/dist/ui/select-item.js +34 -0
- package/dist/ui/viewer-keys.d.ts +22 -0
- package/dist/ui/viewer-keys.js +18 -0
- package/dist/ui/workflow-card.d.ts +175 -0
- package/dist/ui/workflow-card.js +332 -0
- package/dist/ui/workflow-dialog.d.ts +305 -0
- package/dist/ui/workflow-dialog.js +843 -0
- package/dist/ui/workflow-menu.d.ts +60 -0
- package/dist/ui/workflow-menu.js +147 -0
- package/dist/usage.d.ts +135 -0
- package/dist/usage.js +120 -0
- package/dist/workflow/collisions.d.ts +95 -0
- package/dist/workflow/collisions.js +88 -0
- package/dist/workflow/entry.d.ts +32 -0
- package/dist/workflow/entry.js +29 -0
- package/dist/workflow/host.d.ts +62 -0
- package/dist/workflow/host.js +419 -0
- package/dist/workflow/journal.d.ts +97 -0
- package/dist/workflow/journal.js +120 -0
- package/dist/workflow/json-schema.d.ts +52 -0
- package/dist/workflow/json-schema.js +112 -0
- package/dist/workflow/meta.d.ts +67 -0
- package/dist/workflow/meta.js +317 -0
- package/dist/workflow/progress.d.ts +224 -0
- package/dist/workflow/progress.js +361 -0
- package/dist/workflow/runtime.d.ts +334 -0
- package/dist/workflow/runtime.js +830 -0
- package/dist/workflow/saved.d.ts +102 -0
- package/dist/workflow/saved.js +247 -0
- package/dist/workflow/task.d.ts +136 -0
- package/dist/workflow/task.js +207 -0
- package/dist/workflow/tool-description.d.ts +38 -0
- package/dist/workflow/tool-description.js +199 -0
- package/dist/workflow/worker-source.d.ts +47 -0
- package/dist/workflow/worker-source.js +778 -0
- package/dist/worktree.d.ts +52 -0
- package/dist/worktree.js +164 -0
- package/dist/xml.d.ts +10 -0
- package/dist/xml.js +12 -0
- package/docs/packages.md +211 -0
- package/docs/rpc.md +192 -0
- package/docs/workflows.md +447 -0
- package/examples/agent-tool-description.md +42 -0
- package/examples/workflows/compose.js +51 -0
- package/examples/workflows/fan-out-audit.js +47 -0
- package/examples/workflows/gated-fix.js +60 -0
- package/examples/workflows/lib/count-child.js +27 -0
- package/examples/workflows/review-panel.js +63 -0
- package/examples/workflows/structured-findings.js +78 -0
- package/package.json +74 -4
- package/src/abortable.ts +43 -0
- package/src/agent-color.ts +161 -0
- package/src/agent-file-toggle.ts +297 -0
- package/src/agent-manager.ts +1735 -0
- package/src/agent-record-entry.ts +153 -0
- package/src/agent-runner.ts +1468 -0
- package/src/agent-source-badge.ts +75 -0
- package/src/agent-types.ts +346 -0
- package/src/child-context.ts +15 -0
- package/src/completion-outbox.ts +116 -0
- package/src/context.ts +58 -0
- package/src/cross-extension-rpc.ts +221 -0
- package/src/custom-agents.ts +452 -0
- package/src/default-agents.ts +125 -0
- package/src/enabled-models.ts +180 -0
- package/src/env.ts +33 -0
- package/src/group-join.ts +141 -0
- package/src/index.ts +4433 -0
- package/src/invocation-config.ts +155 -0
- package/src/memory.ts +179 -0
- package/src/mention-clone.ts +195 -0
- package/src/mention.ts +141 -0
- package/src/model-resolver.ts +118 -0
- package/src/model-scope.ts +70 -0
- package/src/nested-tools.ts +426 -0
- package/src/output-file.ts +164 -0
- package/src/package-resources.ts +652 -0
- package/src/prompts.ts +171 -0
- package/src/schedule-store.ts +153 -0
- package/src/schedule.ts +386 -0
- package/src/settings.ts +650 -0
- package/src/skill-loader.ts +102 -0
- package/src/status-note.ts +90 -0
- package/src/structured-output.ts +130 -0
- package/src/types.ts +404 -0
- package/src/ui/agent-mention.ts +216 -0
- package/src/ui/agent-widget.ts +661 -0
- package/src/ui/conversation-viewer.ts +928 -0
- package/src/ui/fleet-list.ts +559 -0
- package/src/ui/schedule-menu.ts +105 -0
- package/src/ui/select-item.ts +45 -0
- package/src/ui/viewer-keys.ts +43 -0
- package/src/ui/workflow-card.ts +470 -0
- package/src/ui/workflow-dialog.ts +1115 -0
- package/src/ui/workflow-menu.ts +193 -0
- package/src/usage.ts +167 -0
- package/src/workflow/collisions.ts +123 -0
- package/src/workflow/entry.ts +47 -0
- package/src/workflow/host.ts +467 -0
- package/src/workflow/journal.ts +164 -0
- package/src/workflow/json-schema.ts +129 -0
- package/src/workflow/meta.ts +325 -0
- package/src/workflow/progress.ts +551 -0
- package/src/workflow/runtime.ts +1219 -0
- package/src/workflow/saved.ts +259 -0
- package/src/workflow/task.ts +302 -0
- package/src/workflow/tool-description.ts +200 -0
- package/src/workflow/worker-source.ts +781 -0
- package/src/worktree.ts +205 -0
- package/src/xml.ts +13 -0
|
@@ -0,0 +1,104 @@
|
|
|
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
|
+
dispose() {
|
|
66
|
+
if (this.timer)
|
|
67
|
+
clearTimeout(this.timer);
|
|
68
|
+
this.timer = undefined;
|
|
69
|
+
this.items = [];
|
|
70
|
+
}
|
|
71
|
+
/** Not reset by later items: the first completion is never pushed back. */
|
|
72
|
+
arm() {
|
|
73
|
+
this.timer ??= setTimeout(() => {
|
|
74
|
+
this.timer = undefined;
|
|
75
|
+
this.flush();
|
|
76
|
+
}, NOTIFICATION_HOLD_MS);
|
|
77
|
+
}
|
|
78
|
+
flush() {
|
|
79
|
+
if (this.timer)
|
|
80
|
+
clearTimeout(this.timer);
|
|
81
|
+
this.timer = undefined;
|
|
82
|
+
const items = this.items;
|
|
83
|
+
this.items = [];
|
|
84
|
+
const messages = items.map(item => item.build(item.ids));
|
|
85
|
+
if (messages.length === 0)
|
|
86
|
+
return;
|
|
87
|
+
// A send from a timer can outlive the session it was meant for (pi -p
|
|
88
|
+
// tearing down): pi throws on the stale context, and nothing is left to tell.
|
|
89
|
+
try {
|
|
90
|
+
this.send(combine(messages));
|
|
91
|
+
}
|
|
92
|
+
catch { /* stale context */ }
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
/** One message stays as it was built; several become one message with every agent's details. */
|
|
96
|
+
function combine(messages) {
|
|
97
|
+
if (messages.length === 1)
|
|
98
|
+
return messages[0];
|
|
99
|
+
const [first, ...rest] = messages.flatMap(({ details: { others, ...own } }) => [own, ...(others ?? [])]);
|
|
100
|
+
return {
|
|
101
|
+
content: `${messages.length} background tasks finished.\n\n${messages.map(m => m.content).join("\n\n")}`,
|
|
102
|
+
details: { ...first, others: rest },
|
|
103
|
+
};
|
|
104
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* context.ts — Extract parent conversation context for subagent inheritance.
|
|
3
|
+
*/
|
|
4
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
/** Extract text from a message content block array. */
|
|
6
|
+
export declare function extractText(content: unknown[]): string;
|
|
7
|
+
/**
|
|
8
|
+
* Build a text representation of the parent conversation context.
|
|
9
|
+
* Used when inherit_context is true to give the subagent visibility
|
|
10
|
+
* into what has been discussed/done so far.
|
|
11
|
+
*/
|
|
12
|
+
export declare function buildParentContext(ctx: ExtensionContext): string;
|
package/dist/context.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* context.ts — Extract parent conversation context for subagent inheritance.
|
|
3
|
+
*/
|
|
4
|
+
/** Extract text from a message content block array. */
|
|
5
|
+
export function extractText(content) {
|
|
6
|
+
return content
|
|
7
|
+
.filter((c) => c.type === "text")
|
|
8
|
+
.map((c) => c.text ?? "")
|
|
9
|
+
.join("\n");
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Build a text representation of the parent conversation context.
|
|
13
|
+
* Used when inherit_context is true to give the subagent visibility
|
|
14
|
+
* into what has been discussed/done so far.
|
|
15
|
+
*/
|
|
16
|
+
export function buildParentContext(ctx) {
|
|
17
|
+
const entries = ctx.sessionManager.getBranch();
|
|
18
|
+
if (!entries || entries.length === 0)
|
|
19
|
+
return "";
|
|
20
|
+
const parts = [];
|
|
21
|
+
for (const entry of entries) {
|
|
22
|
+
if (entry.type === "message") {
|
|
23
|
+
const msg = entry.message;
|
|
24
|
+
if (msg.role === "user") {
|
|
25
|
+
const text = typeof msg.content === "string"
|
|
26
|
+
? msg.content
|
|
27
|
+
: extractText(msg.content);
|
|
28
|
+
if (text.trim())
|
|
29
|
+
parts.push(`[User]: ${text.trim()}`);
|
|
30
|
+
}
|
|
31
|
+
else if (msg.role === "assistant") {
|
|
32
|
+
const text = extractText(msg.content);
|
|
33
|
+
if (text.trim())
|
|
34
|
+
parts.push(`[Assistant]: ${text.trim()}`);
|
|
35
|
+
}
|
|
36
|
+
// Skip toolResult messages — too verbose for context
|
|
37
|
+
}
|
|
38
|
+
else if (entry.type === "compaction") {
|
|
39
|
+
// Include compaction summaries — they're already condensed
|
|
40
|
+
if (entry.summary) {
|
|
41
|
+
parts.push(`[Summary]: ${entry.summary}`);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
if (parts.length === 0)
|
|
46
|
+
return "";
|
|
47
|
+
return `# Parent Conversation Context
|
|
48
|
+
The following is the conversation history from the parent session that spawned you.
|
|
49
|
+
Use this context to understand what has been discussed and decided so far.
|
|
50
|
+
|
|
51
|
+
${parts.join("\n\n")}
|
|
52
|
+
|
|
53
|
+
---
|
|
54
|
+
# Your Task (below)
|
|
55
|
+
`;
|
|
56
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cross-extension RPC handlers for the subagents extension.
|
|
3
|
+
*
|
|
4
|
+
* Exposes ping, spawn, stop, consume, and steer RPCs over the pi.events event bus,
|
|
5
|
+
* using per-request scoped reply channels.
|
|
6
|
+
*
|
|
7
|
+
* Reply envelope follows pi-mono convention:
|
|
8
|
+
* success → { success: true, data?: T }
|
|
9
|
+
* error → { success: false, error: string }
|
|
10
|
+
*
|
|
11
|
+
* @see docs/rpc.md — the caller-facing integration reference: spawn options
|
|
12
|
+
* (including the fields spawnTopLevel strips), every error string, the
|
|
13
|
+
* completion-notification race, and what protocol version 2 does not promise.
|
|
14
|
+
*/
|
|
15
|
+
import type { AgentRecord } from "./types.js";
|
|
16
|
+
/** Minimal event bus interface needed by the RPC handlers. */
|
|
17
|
+
export interface EventBus {
|
|
18
|
+
on(event: string, handler: (data: unknown) => void): () => void;
|
|
19
|
+
emit(event: string, data: unknown): void;
|
|
20
|
+
}
|
|
21
|
+
/** RPC reply envelope — matches pi-mono's RpcResponse shape. */
|
|
22
|
+
export type RpcReply<T = void> = {
|
|
23
|
+
success: true;
|
|
24
|
+
data?: T;
|
|
25
|
+
} | {
|
|
26
|
+
success: false;
|
|
27
|
+
error: string;
|
|
28
|
+
};
|
|
29
|
+
/** RPC protocol version — bumped when the envelope or method contracts change. */
|
|
30
|
+
export declare const PROTOCOL_VERSION = 2;
|
|
31
|
+
/** Minimal AgentManager interface needed by the spawn/stop/consume RPCs. */
|
|
32
|
+
export interface SpawnCapable {
|
|
33
|
+
spawn(pi: unknown, ctx: unknown, type: string, prompt: string, options: any): string;
|
|
34
|
+
/** Resolves once the spawned agent is running; rejects on a startup failure. */
|
|
35
|
+
awaitStartup(id: string): Promise<void>;
|
|
36
|
+
abort(id: string): boolean;
|
|
37
|
+
/**
|
|
38
|
+
* The record behind an id, for the stop handler's ownership check. Narrowed
|
|
39
|
+
* to the two fields `isTopLevelAgent` reads, so the RPC layer keeps its
|
|
40
|
+
* deliberately shallow view of the manager.
|
|
41
|
+
*/
|
|
42
|
+
getRecord(id: string): Pick<AgentRecord, "parentAgentId" | "workflowId"> | undefined;
|
|
43
|
+
/**
|
|
44
|
+
* Mark a settled agent's result as read by the caller, suppressing the
|
|
45
|
+
* completion notification — what `get_subagent_result` does when it returns
|
|
46
|
+
* one. False when there is no such agent, or it has not settled yet.
|
|
47
|
+
*/
|
|
48
|
+
consumeResult(id: string): boolean;
|
|
49
|
+
/**
|
|
50
|
+
* Deliver a message to a running or queued agent's conversation — what
|
|
51
|
+
* `steer_subagent` does. False when the agent is unknown or has settled.
|
|
52
|
+
*/
|
|
53
|
+
steer(id: string, message: string): boolean;
|
|
54
|
+
}
|
|
55
|
+
export interface RpcDeps {
|
|
56
|
+
events: EventBus;
|
|
57
|
+
pi: unknown;
|
|
58
|
+
getCtx: () => unknown | undefined;
|
|
59
|
+
manager: SpawnCapable;
|
|
60
|
+
}
|
|
61
|
+
export interface RpcHandle {
|
|
62
|
+
unsubPing: () => void;
|
|
63
|
+
unsubSpawn: () => void;
|
|
64
|
+
unsubStop: () => void;
|
|
65
|
+
unsubConsume: () => void;
|
|
66
|
+
unsubSteer: () => void;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Register ping, spawn, stop, consume, and steer RPC handlers on the event bus.
|
|
70
|
+
* Returns unsub functions for cleanup.
|
|
71
|
+
*/
|
|
72
|
+
export declare function registerRpcHandlers(deps: RpcDeps): RpcHandle;
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cross-extension RPC handlers for the subagents extension.
|
|
3
|
+
*
|
|
4
|
+
* Exposes ping, spawn, stop, consume, and steer RPCs over the pi.events event bus,
|
|
5
|
+
* using per-request scoped reply channels.
|
|
6
|
+
*
|
|
7
|
+
* Reply envelope follows pi-mono convention:
|
|
8
|
+
* success → { success: true, data?: T }
|
|
9
|
+
* error → { success: false, error: string }
|
|
10
|
+
*
|
|
11
|
+
* @see docs/rpc.md — the caller-facing integration reference: spawn options
|
|
12
|
+
* (including the fields spawnTopLevel strips), every error string, the
|
|
13
|
+
* completion-notification race, and what protocol version 2 does not promise.
|
|
14
|
+
*/
|
|
15
|
+
import { isTopLevelAgent } from "./agent-manager.js";
|
|
16
|
+
import { resolveModel } from "./model-resolver.js";
|
|
17
|
+
import { checkModelScope } from "./model-scope.js";
|
|
18
|
+
/** RPC protocol version — bumped when the envelope or method contracts change. */
|
|
19
|
+
export const PROTOCOL_VERSION = 2;
|
|
20
|
+
/**
|
|
21
|
+
* Wire a single RPC handler: listen on `channel`, run `fn(params)`,
|
|
22
|
+
* emit the reply envelope on `channel:reply:${requestId}`.
|
|
23
|
+
*/
|
|
24
|
+
function handleRpc(events, channel, fn) {
|
|
25
|
+
return events.on(channel, async (raw) => {
|
|
26
|
+
const params = raw;
|
|
27
|
+
try {
|
|
28
|
+
const data = await fn(params);
|
|
29
|
+
const reply = { success: true };
|
|
30
|
+
if (data !== undefined)
|
|
31
|
+
reply.data = data;
|
|
32
|
+
events.emit(`${channel}:reply:${params.requestId}`, reply);
|
|
33
|
+
}
|
|
34
|
+
catch (err) {
|
|
35
|
+
events.emit(`${channel}:reply:${params.requestId}`, {
|
|
36
|
+
success: false, error: err?.message ?? String(err),
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Register ping, spawn, stop, consume, and steer RPC handlers on the event bus.
|
|
43
|
+
* Returns unsub functions for cleanup.
|
|
44
|
+
*/
|
|
45
|
+
export function registerRpcHandlers(deps) {
|
|
46
|
+
const { events, pi, getCtx, manager } = deps;
|
|
47
|
+
const unsubPing = handleRpc(events, "subagents:rpc:ping", () => {
|
|
48
|
+
return { version: PROTOCOL_VERSION };
|
|
49
|
+
});
|
|
50
|
+
const unsubSpawn = handleRpc(events, "subagents:rpc:spawn", async ({ type, prompt, options }) => {
|
|
51
|
+
const ctx = getCtx();
|
|
52
|
+
if (!ctx)
|
|
53
|
+
throw new Error("No active session");
|
|
54
|
+
// Cross-extension RPC callers (e.g. pi-tasks TaskExecute) naturally
|
|
55
|
+
// forward serializable values, so options.model can be a string like
|
|
56
|
+
// "openai-codex/gpt-5.5". Resolve it to a real Model instance here
|
|
57
|
+
// — same pattern the scheduler path already uses — so the spawned
|
|
58
|
+
// agent's auth lookup doesn't crash with "No API key found for
|
|
59
|
+
// undefined".
|
|
60
|
+
let normalizedOptions = options ?? {};
|
|
61
|
+
// `!= null` on purpose: a JSON-forwarding caller can serialize an unset
|
|
62
|
+
// field as null, and the runner reads `options.model ?? default`, so null
|
|
63
|
+
// means "inherit" — not an override to resolve or scope-check.
|
|
64
|
+
const override = normalizedOptions.model;
|
|
65
|
+
if (override != null) {
|
|
66
|
+
const { modelRegistry, cwd } = ctx;
|
|
67
|
+
// Names the override the same way in both messages below; an object
|
|
68
|
+
// override would otherwise interpolate as "[object Object]".
|
|
69
|
+
const label = typeof override === "string" ? override : `${override.provider}/${override.id}`;
|
|
70
|
+
if (!modelRegistry) {
|
|
71
|
+
throw new Error(`Model override "${label}" provided but ctx.modelRegistry is unavailable`);
|
|
72
|
+
}
|
|
73
|
+
let model = override;
|
|
74
|
+
if (typeof override === "string") {
|
|
75
|
+
const resolved = resolveModel(override, modelRegistry);
|
|
76
|
+
if (typeof resolved === "string") {
|
|
77
|
+
// resolveModel returns a human-readable error string when the
|
|
78
|
+
// input doesn't match any available model. Surface it instead of
|
|
79
|
+
// silently falling back so the caller sees the auth/typo issue.
|
|
80
|
+
throw new Error(resolved);
|
|
81
|
+
}
|
|
82
|
+
model = resolved;
|
|
83
|
+
normalizedOptions = { ...normalizedOptions, model: resolved };
|
|
84
|
+
}
|
|
85
|
+
// A model on the RPC payload is an orchestrator-level choice, exactly
|
|
86
|
+
// like Agent({ model }) — so it gets the Agent tool's hard error, never
|
|
87
|
+
// the frontmatter warn (#240). The check reads the RESOLVED model:
|
|
88
|
+
// resolveModel is fuzzy, so a bare "sonnet" can land on a provider the
|
|
89
|
+
// caller never named. Frontmatter-pinned and parent-inherited models are
|
|
90
|
+
// resolved later, in agent-runner, and keep warn-and-proceed.
|
|
91
|
+
const verdict = checkModelScope({
|
|
92
|
+
model,
|
|
93
|
+
cwd: cwd ?? process.cwd(),
|
|
94
|
+
modelRegistry,
|
|
95
|
+
callerSupplied: true,
|
|
96
|
+
agentLabel: type,
|
|
97
|
+
modelInput: label,
|
|
98
|
+
});
|
|
99
|
+
if (verdict.kind === "error")
|
|
100
|
+
throw new Error(verdict.message);
|
|
101
|
+
}
|
|
102
|
+
const id = manager.spawn(pi, ctx, type, prompt, normalizedOptions);
|
|
103
|
+
// With isolation: "worktree" the agent starts asynchronously — wait for
|
|
104
|
+
// it, so a strict-isolation failure is still an error envelope rather
|
|
105
|
+
// than an id for an agent that never ran.
|
|
106
|
+
await manager.awaitStartup(id);
|
|
107
|
+
return { id };
|
|
108
|
+
});
|
|
109
|
+
// Only the session's own agents are this RPC's to stop or steer. A nested
|
|
110
|
+
// child or a workflow's agent is owned by something that is *waiting on it*,
|
|
111
|
+
// and aborting or redirecting it out from under that owner turns another
|
|
112
|
+
// extension's request into a failed step here. Defence in depth rather than
|
|
113
|
+
// a live hole: no RPC hands out agent ids, so a caller has no ordinary way to
|
|
114
|
+
// name one it does not own — but the guard is cheap and the id may leak some
|
|
115
|
+
// other way. Same refuse-what-we-should-not-touch stance as `consume` below.
|
|
116
|
+
const assertOwned = (agentId) => {
|
|
117
|
+
const record = manager.getRecord(agentId);
|
|
118
|
+
if (!record)
|
|
119
|
+
throw new Error("Agent not found");
|
|
120
|
+
if (!isTopLevelAgent(record))
|
|
121
|
+
throw new Error("Agent is owned by another agent or workflow");
|
|
122
|
+
};
|
|
123
|
+
const unsubStop = handleRpc(events, "subagents:rpc:stop", ({ agentId }) => {
|
|
124
|
+
assertOwned(agentId);
|
|
125
|
+
// Not "not found" — the lookup above already proved it exists. `abort`
|
|
126
|
+
// returns false only for a record that is neither running nor queued,
|
|
127
|
+
// which is an agent that has already finished.
|
|
128
|
+
if (!manager.abort(agentId))
|
|
129
|
+
throw new Error("Agent is not running");
|
|
130
|
+
});
|
|
131
|
+
// A caller that has already shown the model an agent's result — pi-tasks'
|
|
132
|
+
// TaskOutput is the one in practice — says so here, so the completion
|
|
133
|
+
// notification for that same result is not delivered on top of it and does
|
|
134
|
+
// not cost the parent a turn. Deliberately outside the ping version
|
|
135
|
+
// handshake: an extension built against protocol v2 simply never calls it.
|
|
136
|
+
const unsubConsume = handleRpc(events, "subagents:rpc:consume", ({ agentId }) => {
|
|
137
|
+
if (!manager.consumeResult(agentId))
|
|
138
|
+
throw new Error("Agent not found or still running");
|
|
139
|
+
});
|
|
140
|
+
// An extension that spawned an agent over the bus and then learns something
|
|
141
|
+
// that agent needs — a second CI failure on the head it is already fixing, a
|
|
142
|
+
// review that landed mid-run — can hand it over instead of spawning a second
|
|
143
|
+
// agent for the same work or dropping the fact. Outside the ping version
|
|
144
|
+
// handshake, like consume: additive and best-effort.
|
|
145
|
+
const unsubSteer = handleRpc(events, "subagents:rpc:steer", ({ agentId, message }) => {
|
|
146
|
+
if (typeof message !== "string" || message.trim().length === 0)
|
|
147
|
+
throw new Error("Steer message must be a non-empty string");
|
|
148
|
+
assertOwned(agentId);
|
|
149
|
+
if (!manager.steer(agentId, message))
|
|
150
|
+
throw new Error("Agent is not running");
|
|
151
|
+
});
|
|
152
|
+
return { unsubPing, unsubSpawn, unsubStop, unsubConsume, unsubSteer };
|
|
153
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
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, plus any installed pi package that declares them (see package-resources.ts).
|
|
3
|
+
*/
|
|
4
|
+
import type { AgentConfig } from "./types.js";
|
|
5
|
+
/** Answers whether a `!` entry in some package manifest excludes this path. */
|
|
6
|
+
type Excluder = (path: string) => boolean;
|
|
7
|
+
/**
|
|
8
|
+
* Overrides for the package tier. The gate and project-trust state normally come
|
|
9
|
+
* from the session values in package-resources.ts, so these exist for tests and
|
|
10
|
+
* for a caller that has to pin a scan it already performed.
|
|
11
|
+
*/
|
|
12
|
+
export interface LoadCustomAgentsOptions {
|
|
13
|
+
/** Explicit package directories, bypassing discovery. */
|
|
14
|
+
packageDirs?: string[];
|
|
15
|
+
/** Explicit package files, bypassing discovery. */
|
|
16
|
+
packageFiles?: string[];
|
|
17
|
+
/** Explicit `!` exclusion predicate, bypassing discovery. */
|
|
18
|
+
packageExcluded?: Excluder;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Scan for custom agent .md files from multiple locations.
|
|
22
|
+
* Discovery hierarchy (higher priority wins):
|
|
23
|
+
* 1. Project: <cwd>/.pi/agents/*.md (authoritative — also where /agents writes)
|
|
24
|
+
* 2. Workspace: <cwd>/.agents/agents/*.md (shared cross-tool .agents workspace, read-only)
|
|
25
|
+
* 3. Global: $PI_CODING_AGENT_DIR/agents/*.md (default: ~/.pi/agent/agents/*.md)
|
|
26
|
+
* 4. Package: paths declared by an installed pi package (read-only)
|
|
27
|
+
*
|
|
28
|
+
* Project-level agents override global ones with the same name. On a name clash
|
|
29
|
+
* between the two project locations, .pi/agents wins — .pi stays the project
|
|
30
|
+
* authority; .agents/agents is an additional read location.
|
|
31
|
+
* Any name is allowed — names matching defaults (e.g. "Explore") override them.
|
|
32
|
+
*
|
|
33
|
+
* Package agents load *first*, so everything the user or project wrote outranks
|
|
34
|
+
* them. That is what makes them safe to adopt: a package can offer a `reviewer`,
|
|
35
|
+
* and a `.pi/agents/reviewer.md` silently takes it back. It mirrors pi's own
|
|
36
|
+
* resource precedence, where package-provided skills rank below every user and
|
|
37
|
+
* project one, and Claude Code's, where a plugin agent is the lowest tier.
|
|
38
|
+
*
|
|
39
|
+
* An agent's type comes from its frontmatter `name:`, falling back to the
|
|
40
|
+
* filename — Claude Code's rule, where "the filename doesn't have to match".
|
|
41
|
+
* Because the type is now declared rather than derived from a unique path, two
|
|
42
|
+
* files can claim the same one; the later load wins, as it always has for a
|
|
43
|
+
* filename clash, and `warnSkippedOverride` reports the substitution.
|
|
44
|
+
*/
|
|
45
|
+
export declare function loadCustomAgents(cwd: string, strict?: boolean, opts?: LoadCustomAgentsOptions): Map<string, AgentConfig>;
|
|
46
|
+
/**
|
|
47
|
+
* Read and parse one agent file, or warn and return undefined for the caller to
|
|
48
|
+
* skip. One bad file must not take the whole extension down with it — an
|
|
49
|
+
* unparseable `.md` used to abort activation, so pi exited before the TUI.
|
|
50
|
+
*
|
|
51
|
+
* The path is as much of the fix as the recovery: a bare YAML error ("line 2,
|
|
52
|
+
* column 14") is unactionable when agents come from three directories at once,
|
|
53
|
+
* and the only other symptom is `Unknown agent type`, which reads like a typo.
|
|
54
|
+
*
|
|
55
|
+
* Under `strict` the same failure rethrows, still naming the path, so callers
|
|
56
|
+
* that opted into failing closed stop rather than run a substituted agent.
|
|
57
|
+
*/
|
|
58
|
+
/**
|
|
59
|
+
* Parse an agent file's frontmatter, tolerating a leading UTF-8 BOM.
|
|
60
|
+
*
|
|
61
|
+
* Editors across the Windows/CJK world write UTF-8 with a BOM by default, and
|
|
62
|
+
* pi's parser did not look past one before 0.84.3: the fence never matched, so
|
|
63
|
+
* the frontmatter came back empty and the *whole file* — YAML and all — became
|
|
64
|
+
* the body. An agent authored that way silently lost every field. `tools: none`
|
|
65
|
+
* going missing is the sharp edge: the agent registers with the default
|
|
66
|
+
* toolset rather than none, which is a wider grant than its author wrote.
|
|
67
|
+
*
|
|
68
|
+
* Stripped here rather than detected per pi version, because this is the only
|
|
69
|
+
* place agent files are read and the BOM is a file-encoding artifact, not
|
|
70
|
+
* content — normalising it at the boundary keeps one behaviour across the whole
|
|
71
|
+
* supported peer range instead of forking on what happens to be installed.
|
|
72
|
+
*/
|
|
73
|
+
export declare function parseAgentFrontmatter<T extends Record<string, unknown>>(content: string): {
|
|
74
|
+
frontmatter: T;
|
|
75
|
+
body: string;
|
|
76
|
+
};
|
|
77
|
+
export {};
|