@timmyjl12/pi-subagents 0.20.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 +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 +3612 -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 +4130 -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
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* force-main-model.ts — Session-only "subagents off" switch behind `/subagents`.
|
|
3
|
+
*
|
|
4
|
+
* When on, every later spawn is a main-model twin: agent-type pins, caller
|
|
5
|
+
* overrides and scheduled-job models all give way to the parent context's model,
|
|
6
|
+
* so delegation never leaves the model the session is actually running.
|
|
7
|
+
*
|
|
8
|
+
* State lives in `process.env` rather than a module variable: subagent sessions
|
|
9
|
+
* bind their own copy of this extension, and only process env reaches a child
|
|
10
|
+
* constructed after the flip (the same channel as `PI_SUBAGENT_CHILD`). Workflow
|
|
11
|
+
* worker threads receive a copy at creation.
|
|
12
|
+
*
|
|
13
|
+
* "Session-only" means the pi process: the flag survives `/new` and `/reload`
|
|
14
|
+
* (same process, new session), reaches anything the bash tool spawns while set,
|
|
15
|
+
* and dies with pi — nothing is ever written to subagents.json.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
export const FORCE_MAIN_MODEL_ENV = "PI_SUBAGENTS_FORCE_MAIN_MODEL";
|
|
19
|
+
|
|
20
|
+
/** Live read, so a `/subagents` flip applies to the very next spawn — nested included. */
|
|
21
|
+
export function isForceMainModel(): boolean {
|
|
22
|
+
return process.env[FORCE_MAIN_MODEL_ENV] === "1";
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Set or clear the flag. Session-only: process env never outlives pi. */
|
|
26
|
+
export function setForceMainModel(on: boolean): void {
|
|
27
|
+
if (on) process.env[FORCE_MAIN_MODEL_ENV] = "1";
|
|
28
|
+
else delete process.env[FORCE_MAIN_MODEL_ENV];
|
|
29
|
+
}
|
|
@@ -0,0 +1,468 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* goal-bridge.ts — optional goal-orchestration bridge for pi-subagents (v1).
|
|
3
|
+
*
|
|
4
|
+
* Additive, session-scoped and read-only except for one acknowledged steering
|
|
5
|
+
* path that still goes through the ORIGINAL `steer_subagent` tool's permission
|
|
6
|
+
* hooks. The bridge:
|
|
7
|
+
*
|
|
8
|
+
* - answers `goal:agents:request` with a bounded snapshot of the live session's
|
|
9
|
+
* TOP-LEVEL agents (exact `rootSessionId`, no `parentAgentId`/`workflowId`),
|
|
10
|
+
* never touching the process-global manager registry;
|
|
11
|
+
* - emits advisory `goal:agents:ready` / `goal:agents:changed` hints;
|
|
12
|
+
* - validates an optional `goalGuard` for the original steering tool and
|
|
13
|
+
* delivers through `manager.steerAcknowledged`, so a rejected SDK steer is a
|
|
14
|
+
* real error rather than optimistic text.
|
|
15
|
+
*
|
|
16
|
+
* There are deliberately no spawn/resume/stop/consume verbs on the bus, and an
|
|
17
|
+
* observed agent result is never consumed here.
|
|
18
|
+
*
|
|
19
|
+
* Protocol reference: .plan/goal-orchestration/protocol.md.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import { isTopLevelAgent } from "./agent-manager.ts";
|
|
23
|
+
|
|
24
|
+
/** Provider id used in hints and by consumers that filter replies. */
|
|
25
|
+
export const AGENT_PROVIDER_ID = "pi-subagents";
|
|
26
|
+
export const GOAL_AGENTS_REQUEST = "goal:agents:request";
|
|
27
|
+
export const GOAL_AGENTS_READY = "goal:agents:ready";
|
|
28
|
+
export const GOAL_AGENTS_CHANGED = "goal:agents:changed";
|
|
29
|
+
export const STEER_TOOL_NAME = "steer_subagent";
|
|
30
|
+
|
|
31
|
+
/** Structural binding a consumer uses to reach the ORIGINAL steering tool. */
|
|
32
|
+
export const STEER_TOOL_BINDING = { kind: "steer-tool-v1", toolName: STEER_TOOL_NAME } as const;
|
|
33
|
+
|
|
34
|
+
const MAX_ID = 200;
|
|
35
|
+
const MAX_MESSAGE = 20_000;
|
|
36
|
+
const MAX_SNAPSHOT_TEXT = 4_000;
|
|
37
|
+
const MAX_DESCRIPTION = 500;
|
|
38
|
+
const MAX_AGENTS = 200;
|
|
39
|
+
const MAX_APPLIED_STEERS = 512;
|
|
40
|
+
const TRUNCATION_MARKER = "…[truncated]";
|
|
41
|
+
|
|
42
|
+
/** In-process event bus surface (pi.events). */
|
|
43
|
+
export interface GoalAgentEventBus {
|
|
44
|
+
emit(channel: string, data: unknown): void;
|
|
45
|
+
on(channel: string, handler: (data: unknown) => void): () => void;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The subset of an agent record this bridge reads (structurally AgentRecord). */
|
|
49
|
+
export interface GoalAgentRecord {
|
|
50
|
+
id: string;
|
|
51
|
+
type: string;
|
|
52
|
+
description: string;
|
|
53
|
+
status: string;
|
|
54
|
+
handle?: string;
|
|
55
|
+
result?: string;
|
|
56
|
+
error?: string;
|
|
57
|
+
runGeneration?: number;
|
|
58
|
+
rootSessionId?: string;
|
|
59
|
+
parentAgentId?: string;
|
|
60
|
+
workflowId?: string;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Narrow manager surface; never the process-global registry. */
|
|
64
|
+
export interface GoalAgentSource {
|
|
65
|
+
listAgents(): readonly GoalAgentRecord[];
|
|
66
|
+
getRecord(id: string): GoalAgentRecord | undefined;
|
|
67
|
+
steerAcknowledged(id: string, message: string): Promise<boolean>;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Validated `goalGuard` carried by the ORIGINAL steer_subagent tool. */
|
|
71
|
+
export interface GoalAgentGuard {
|
|
72
|
+
version: 1;
|
|
73
|
+
sessionId: string;
|
|
74
|
+
goalId: string;
|
|
75
|
+
runGeneration: number;
|
|
76
|
+
operationId: string;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export type GoalAgentGuardErrorCode =
|
|
80
|
+
| "invalid-guard"
|
|
81
|
+
| "unavailable"
|
|
82
|
+
| "session-mismatch"
|
|
83
|
+
| "agent-not-found"
|
|
84
|
+
| "not-top-level"
|
|
85
|
+
| "generation-mismatch"
|
|
86
|
+
| "not-steerable"
|
|
87
|
+
| "aborted"
|
|
88
|
+
| "duplicate-operation"
|
|
89
|
+
| "not-delivered";
|
|
90
|
+
|
|
91
|
+
/** Guard refusal. The original tool throws it, so callers see a real error. */
|
|
92
|
+
export class GoalAgentGuardError extends Error {
|
|
93
|
+
readonly code: GoalAgentGuardErrorCode;
|
|
94
|
+
|
|
95
|
+
constructor(code: GoalAgentGuardErrorCode, message: string) {
|
|
96
|
+
super(message);
|
|
97
|
+
this.name = "GoalAgentGuardError";
|
|
98
|
+
this.code = code;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export interface GoalAgentSnapshotEntry {
|
|
103
|
+
id: string;
|
|
104
|
+
type: string;
|
|
105
|
+
description: string;
|
|
106
|
+
status: string;
|
|
107
|
+
runGeneration: number;
|
|
108
|
+
handle?: string;
|
|
109
|
+
result?: string;
|
|
110
|
+
error?: string;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export interface GoalAgentSnapshot {
|
|
114
|
+
success: true;
|
|
115
|
+
version: 1;
|
|
116
|
+
sessionId: string;
|
|
117
|
+
/** Echo of the request envelope id (the consumer rejects replies without it). */
|
|
118
|
+
requestId: string;
|
|
119
|
+
agents: GoalAgentSnapshotEntry[];
|
|
120
|
+
steerBinding: typeof STEER_TOOL_BINDING;
|
|
121
|
+
/** Additive: the roster exceeded the bounded snapshot size. */
|
|
122
|
+
truncated?: true;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export interface GoalAgentSnapshotFailure {
|
|
126
|
+
success: false;
|
|
127
|
+
version: 1;
|
|
128
|
+
sessionId: string;
|
|
129
|
+
requestId: string;
|
|
130
|
+
error: string;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export type GoalAgentSnapshotReply = GoalAgentSnapshot | GoalAgentSnapshotFailure;
|
|
134
|
+
|
|
135
|
+
/** Receipt of one acknowledged guarded steer. */
|
|
136
|
+
export interface GuardedSteerReceipt {
|
|
137
|
+
agentId: string;
|
|
138
|
+
runGeneration: number;
|
|
139
|
+
operationId: string;
|
|
140
|
+
/** The caller's signal was aborted after delivery — it could not be unsent. */
|
|
141
|
+
abortedAfterDelivery?: true;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
145
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function boundedId(value: unknown, max: number): string | undefined {
|
|
149
|
+
if (typeof value !== "string" || value.length === 0 || value.length > max) return undefined;
|
|
150
|
+
for (let index = 0; index < value.length; index++) {
|
|
151
|
+
const code = value.charCodeAt(index);
|
|
152
|
+
if (code < 32 || code === 127) return undefined;
|
|
153
|
+
}
|
|
154
|
+
return value;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Strict `unknown` → `GoalAgentGuard`; undefined means malformed. */
|
|
158
|
+
export function parseGoalAgentGuard(value: unknown): GoalAgentGuard | undefined {
|
|
159
|
+
if (!isRecord(value) || value.version !== 1) return undefined;
|
|
160
|
+
const sessionId = boundedId(value.sessionId, MAX_ID);
|
|
161
|
+
const goalId = boundedId(value.goalId, MAX_ID);
|
|
162
|
+
const operationId = boundedId(value.operationId, MAX_ID);
|
|
163
|
+
const runGeneration = value.runGeneration;
|
|
164
|
+
if (!sessionId || !goalId || !operationId) return undefined;
|
|
165
|
+
if (typeof runGeneration !== "number" || !Number.isSafeInteger(runGeneration) || runGeneration < 0) return undefined;
|
|
166
|
+
return { version: 1, sessionId, goalId, runGeneration, operationId };
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function truncate(value: string, max: number): string {
|
|
170
|
+
return value.length > max ? `${value.slice(0, max)}${TRUNCATION_MARKER}` : value;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
interface Binding {
|
|
174
|
+
sessionId: string;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export interface SubagentsGoalBridgeOptions {
|
|
178
|
+
source: GoalAgentSource;
|
|
179
|
+
events?: GoalAgentEventBus;
|
|
180
|
+
/** Bounded agent rows (default 200). */
|
|
181
|
+
maxAgents?: number;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Live bridge. `bind` runs from the original `session_start` (never the
|
|
186
|
+
* factory) once the manager and the session id exist; `unbind` runs
|
|
187
|
+
* synchronously at `session_shutdown`, before awaited child disposal.
|
|
188
|
+
*/
|
|
189
|
+
export class SubagentsGoalBridge {
|
|
190
|
+
private readonly source: GoalAgentSource;
|
|
191
|
+
private readonly events: GoalAgentEventBus | undefined;
|
|
192
|
+
private readonly maxAgents: number;
|
|
193
|
+
private binding: Binding | undefined;
|
|
194
|
+
private busCleanup: Array<() => void> = [];
|
|
195
|
+
private revision = 0;
|
|
196
|
+
private readonly appliedSteers = new Set<string>();
|
|
197
|
+
|
|
198
|
+
constructor(options: SubagentsGoalBridgeOptions) {
|
|
199
|
+
this.source = options.source;
|
|
200
|
+
this.events = options.events;
|
|
201
|
+
this.maxAgents = Math.max(1, options.maxAgents ?? MAX_AGENTS);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** Bound live session id, or undefined before bind/after unbind. */
|
|
205
|
+
get sessionId(): string | undefined {
|
|
206
|
+
return this.binding?.sessionId;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
get bound(): boolean {
|
|
210
|
+
return this.binding !== undefined;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** Bind the live session. Rebinding releases prior listeners first. */
|
|
214
|
+
bind(sessionId: string): void {
|
|
215
|
+
this.unbind();
|
|
216
|
+
this.revision += 1;
|
|
217
|
+
this.appliedSteers.clear();
|
|
218
|
+
this.binding = { sessionId };
|
|
219
|
+
this.installBus();
|
|
220
|
+
this.emit(GOAL_AGENTS_READY);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** Release bus listeners synchronously; no hint can follow. */
|
|
224
|
+
unbind(): void {
|
|
225
|
+
for (const cleanup of this.busCleanup) {
|
|
226
|
+
try {
|
|
227
|
+
cleanup();
|
|
228
|
+
} catch (error) {
|
|
229
|
+
console.warn(
|
|
230
|
+
"pi-subagents goal listener cleanup failed",
|
|
231
|
+
error instanceof Error ? error.name : "unknown error",
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
this.busCleanup = [];
|
|
236
|
+
this.binding = undefined;
|
|
237
|
+
this.appliedSteers.clear();
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** Plain cloned, bounded, filtered snapshot of THIS session's top-level agents. */
|
|
241
|
+
snapshot(requestId: string): GoalAgentSnapshot | undefined {
|
|
242
|
+
const binding = this.binding;
|
|
243
|
+
if (!binding) return undefined;
|
|
244
|
+
const owned = this.source
|
|
245
|
+
.listAgents()
|
|
246
|
+
.filter((record) => record.rootSessionId === binding.sessionId && isTopLevelAgent(record));
|
|
247
|
+
const agents: GoalAgentSnapshotEntry[] = owned.slice(0, this.maxAgents).map((record) => ({
|
|
248
|
+
id: record.id,
|
|
249
|
+
type: record.type,
|
|
250
|
+
description: truncate(record.description, MAX_DESCRIPTION),
|
|
251
|
+
status: record.status,
|
|
252
|
+
runGeneration: record.runGeneration ?? 0,
|
|
253
|
+
...(record.handle ? { handle: truncate(record.handle, MAX_ID) } : {}),
|
|
254
|
+
...(record.result === undefined ? {} : { result: truncate(record.result, MAX_SNAPSHOT_TEXT) }),
|
|
255
|
+
...(record.error === undefined ? {} : { error: truncate(record.error, MAX_SNAPSHOT_TEXT) }),
|
|
256
|
+
}));
|
|
257
|
+
return {
|
|
258
|
+
success: true,
|
|
259
|
+
version: 1,
|
|
260
|
+
sessionId: binding.sessionId,
|
|
261
|
+
requestId,
|
|
262
|
+
agents,
|
|
263
|
+
steerBinding: { ...STEER_TOOL_BINDING },
|
|
264
|
+
...(owned.length > this.maxAgents ? { truncated: true as const } : {}),
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
private installBus(): void {
|
|
269
|
+
const events = this.events;
|
|
270
|
+
if (!events || this.busCleanup.length > 0) return;
|
|
271
|
+
this.busCleanup = [events.on(GOAL_AGENTS_REQUEST, (data) => this.handleRequest(data))];
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
private emit(channel: string): void {
|
|
275
|
+
const binding = this.binding;
|
|
276
|
+
if (!binding || !this.events) return;
|
|
277
|
+
this.events.emit(channel, {
|
|
278
|
+
version: 1,
|
|
279
|
+
sessionId: binding.sessionId,
|
|
280
|
+
providerId: AGENT_PROVIDER_ID,
|
|
281
|
+
revision: this.revision,
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
private failure(binding: Binding, requestId: string, error: string): GoalAgentSnapshotFailure {
|
|
286
|
+
return { success: false, version: 1, sessionId: binding.sessionId, requestId, error };
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
private handleRequest(data: unknown): void {
|
|
290
|
+
const binding = this.binding;
|
|
291
|
+
if (!binding || !isRecord(data)) return;
|
|
292
|
+
// Foreign sessions, unknown versions and other provider ids are ignored.
|
|
293
|
+
if (data.version !== 1 || data.sessionId !== binding.sessionId) return;
|
|
294
|
+
if (data.providerId !== undefined && data.providerId !== AGENT_PROVIDER_ID) return;
|
|
295
|
+
const reply = data.reply;
|
|
296
|
+
if (typeof reply !== "function") return;
|
|
297
|
+
const respond = (result: GoalAgentSnapshot | GoalAgentSnapshotFailure): void => {
|
|
298
|
+
Reflect.apply(reply, data, [result]);
|
|
299
|
+
};
|
|
300
|
+
const requestId = boundedId(data.requestId, MAX_ID);
|
|
301
|
+
if (!requestId) {
|
|
302
|
+
// Echo the raw value when it is a string; a consumer with a valid
|
|
303
|
+
// request id never matches this reply, which is correct.
|
|
304
|
+
respond(
|
|
305
|
+
this.failure(
|
|
306
|
+
binding,
|
|
307
|
+
typeof data.requestId === "string" ? truncate(data.requestId, MAX_ID) : "",
|
|
308
|
+
"requestId must be a nonempty bounded string",
|
|
309
|
+
),
|
|
310
|
+
);
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
313
|
+
const signal = data.signal;
|
|
314
|
+
if (isRecord(signal) && signal.aborted === true) {
|
|
315
|
+
respond(this.failure(binding, requestId, "request aborted"));
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
// The v1 client sends no `operation` for this read-only channel, so an
|
|
319
|
+
// omitted operation means snapshot. Anything explicitly named other than
|
|
320
|
+
// "snapshot" is a refused write/edit verb.
|
|
321
|
+
const operation = data.operation;
|
|
322
|
+
if (operation !== undefined && operation !== "snapshot") {
|
|
323
|
+
respond(
|
|
324
|
+
this.failure(
|
|
325
|
+
binding,
|
|
326
|
+
requestId,
|
|
327
|
+
`unsupported operation: '${String(operation)}': the agent bus is read-only (only 'snapshot')`,
|
|
328
|
+
),
|
|
329
|
+
);
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
respond(this.snapshot(requestId) as GoalAgentSnapshot);
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
private releaseSteer(key: string): void {
|
|
336
|
+
this.appliedSteers.delete(key);
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
private trimSteers(): void {
|
|
340
|
+
while (this.appliedSteers.size > MAX_APPLIED_STEERS) {
|
|
341
|
+
const oldest = this.appliedSteers.values().next();
|
|
342
|
+
if (oldest.done) break;
|
|
343
|
+
this.appliedSteers.delete(oldest.value);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* Validate and deliver one guarded steer through `steerAcknowledged`.
|
|
349
|
+
*
|
|
350
|
+
* Every session/ownership/generation/state/signal check runs synchronously
|
|
351
|
+
* after the host's permission hooks and immediately before the one effect
|
|
352
|
+
* call. A rejected delivery releases its operationId and throws, so a retry
|
|
353
|
+
* is allowed; a delivered one keeps the id reserved (per run generation) and
|
|
354
|
+
* a duplicate is refused rather than delivered twice.
|
|
355
|
+
*/
|
|
356
|
+
async steer(
|
|
357
|
+
guardRaw: unknown,
|
|
358
|
+
agentIdRaw: string,
|
|
359
|
+
message: string,
|
|
360
|
+
signal?: AbortSignal,
|
|
361
|
+
): Promise<GuardedSteerReceipt> {
|
|
362
|
+
const binding = this.binding;
|
|
363
|
+
if (!binding) {
|
|
364
|
+
throw new GoalAgentGuardError(
|
|
365
|
+
"unavailable",
|
|
366
|
+
"Goal guard unavailable: no live pi-subagents session is bound. Nothing was steered.",
|
|
367
|
+
);
|
|
368
|
+
}
|
|
369
|
+
const guard = parseGoalAgentGuard(guardRaw);
|
|
370
|
+
if (!guard) {
|
|
371
|
+
throw new GoalAgentGuardError(
|
|
372
|
+
"invalid-guard",
|
|
373
|
+
"goalGuard is malformed: version 1 and nonempty bounded sessionId, goalId, operationId plus a nonnegative runGeneration are required. Nothing was steered.",
|
|
374
|
+
);
|
|
375
|
+
}
|
|
376
|
+
if (guard.sessionId !== binding.sessionId) {
|
|
377
|
+
throw new GoalAgentGuardError(
|
|
378
|
+
"session-mismatch",
|
|
379
|
+
`Goal guard session '${guard.sessionId}' is not this live session. Nothing was steered.`,
|
|
380
|
+
);
|
|
381
|
+
}
|
|
382
|
+
if (signal?.aborted) {
|
|
383
|
+
throw new GoalAgentGuardError("aborted", "Goal guard was cancelled before delivery. Nothing was steered.");
|
|
384
|
+
}
|
|
385
|
+
const message_ = message.trim();
|
|
386
|
+
if (message_.length === 0 || message.length > MAX_MESSAGE) {
|
|
387
|
+
throw new GoalAgentGuardError(
|
|
388
|
+
"invalid-guard",
|
|
389
|
+
`Guarded steering requires a nonempty message of at most ${MAX_MESSAGE} characters. Nothing was steered.`,
|
|
390
|
+
);
|
|
391
|
+
}
|
|
392
|
+
const agentId = boundedId(agentIdRaw, MAX_ID);
|
|
393
|
+
if (!agentId) {
|
|
394
|
+
throw new GoalAgentGuardError("agent-not-found", `Agent not found: "${agentIdRaw}". Nothing was steered.`);
|
|
395
|
+
}
|
|
396
|
+
// Exact id only: a handle could be rebound to another run between the
|
|
397
|
+
// goal snapshot and this call.
|
|
398
|
+
const record = this.source.getRecord(agentId);
|
|
399
|
+
if (!record || record.id !== agentId) {
|
|
400
|
+
throw new GoalAgentGuardError("agent-not-found", `Agent not found: "${agentId}". Nothing was steered.`);
|
|
401
|
+
}
|
|
402
|
+
if (!isTopLevelAgent(record)) {
|
|
403
|
+
throw new GoalAgentGuardError(
|
|
404
|
+
"not-top-level",
|
|
405
|
+
`Agent ${agentId} is owned by another agent or workflow; guarded steering only reaches this session's top-level agents. Nothing was steered.`,
|
|
406
|
+
);
|
|
407
|
+
}
|
|
408
|
+
if (record.rootSessionId !== binding.sessionId) {
|
|
409
|
+
throw new GoalAgentGuardError(
|
|
410
|
+
"session-mismatch",
|
|
411
|
+
`Agent ${agentId} does not belong to this session (root ${record.rootSessionId ?? "unknown"}). Nothing was steered.`,
|
|
412
|
+
);
|
|
413
|
+
}
|
|
414
|
+
const generation = record.runGeneration ?? 0;
|
|
415
|
+
if (generation !== guard.runGeneration) {
|
|
416
|
+
throw new GoalAgentGuardError(
|
|
417
|
+
"generation-mismatch",
|
|
418
|
+
`Agent ${agentId} is on run generation ${generation}, not ${guard.runGeneration}; refresh the agent snapshot before retrying. Nothing was steered.`,
|
|
419
|
+
);
|
|
420
|
+
}
|
|
421
|
+
if (record.status !== "running" && record.status !== "queued") {
|
|
422
|
+
throw new GoalAgentGuardError(
|
|
423
|
+
"not-steerable",
|
|
424
|
+
`Agent ${agentId} is not running (status: ${record.status}). Nothing was steered.`,
|
|
425
|
+
);
|
|
426
|
+
}
|
|
427
|
+
const key = `${agentId}\u0000${generation}\u0000${guard.operationId}`;
|
|
428
|
+
if (this.appliedSteers.has(key)) {
|
|
429
|
+
throw new GoalAgentGuardError(
|
|
430
|
+
"duplicate-operation",
|
|
431
|
+
`operationId '${guard.operationId}' was already delivered to agent ${agentId} on run ${generation}; refusing to deliver it twice. Nothing new was steered.`,
|
|
432
|
+
);
|
|
433
|
+
}
|
|
434
|
+
// Reserve before awaiting: concurrent duplicate calls must not both deliver.
|
|
435
|
+
this.appliedSteers.add(key);
|
|
436
|
+
this.trimSteers();
|
|
437
|
+
// Re-check cancellation immediately before the effect, after all awaits
|
|
438
|
+
// that could have occurred in the permission pipeline.
|
|
439
|
+
if (signal?.aborted) {
|
|
440
|
+
this.releaseSteer(key);
|
|
441
|
+
throw new GoalAgentGuardError("aborted", "Goal guard was cancelled before delivery. Nothing was steered.");
|
|
442
|
+
}
|
|
443
|
+
let delivered = false;
|
|
444
|
+
let failureText = "";
|
|
445
|
+
try {
|
|
446
|
+
delivered = await this.source.steerAcknowledged(agentId, message);
|
|
447
|
+
} catch (error) {
|
|
448
|
+
failureText = error instanceof Error ? error.message : String(error);
|
|
449
|
+
delivered = false;
|
|
450
|
+
}
|
|
451
|
+
if (!delivered) {
|
|
452
|
+
this.releaseSteer(key);
|
|
453
|
+
throw new GoalAgentGuardError(
|
|
454
|
+
"not-delivered",
|
|
455
|
+
`Steering message NOT delivered to agent ${agentId}: the session rejected it${
|
|
456
|
+
failureText ? ` (${truncate(failureText, 300)})` : ""
|
|
457
|
+
}. Nothing is pretended; retry only after confirming the agent is still running.`,
|
|
458
|
+
);
|
|
459
|
+
}
|
|
460
|
+
this.emit(GOAL_AGENTS_CHANGED);
|
|
461
|
+
return {
|
|
462
|
+
agentId,
|
|
463
|
+
runGeneration: generation,
|
|
464
|
+
operationId: guard.operationId,
|
|
465
|
+
...(signal?.aborted ? { abortedAfterDelivery: true as const } : {}),
|
|
466
|
+
};
|
|
467
|
+
}
|
|
468
|
+
}
|
package/src/group-join.ts
CHANGED
|
@@ -6,20 +6,31 @@
|
|
|
6
6
|
* then a single consolidated notification is sent.
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
|
-
import type { AgentRecord } from "./types.
|
|
9
|
+
import type { AgentRecord } from "./types.ts";
|
|
10
10
|
|
|
11
11
|
export type DeliveryCallback = (records: AgentRecord[], partial: boolean) => void;
|
|
12
12
|
|
|
13
13
|
interface AgentGroup {
|
|
14
14
|
groupId: string;
|
|
15
15
|
agentIds: Set<string>;
|
|
16
|
-
completedRecords: Map<string,
|
|
16
|
+
completedRecords: Map<string, CompletedRecord>;
|
|
17
17
|
timeoutHandle?: ReturnType<typeof setTimeout>;
|
|
18
18
|
delivered: boolean;
|
|
19
19
|
/** Shorter timeout for stragglers after a partial delivery. */
|
|
20
20
|
isStraggler: boolean;
|
|
21
21
|
}
|
|
22
22
|
|
|
23
|
+
/** A completion, paired with the run generation it belongs to. */
|
|
24
|
+
interface CompletedRecord {
|
|
25
|
+
record: AgentRecord;
|
|
26
|
+
runGeneration: number;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Whether the record still belongs to the run that completed. */
|
|
30
|
+
function isCurrentRun(entry: CompletedRecord): boolean {
|
|
31
|
+
return (entry.record.runGeneration ?? 0) === entry.runGeneration;
|
|
32
|
+
}
|
|
33
|
+
|
|
23
34
|
/** Default timeout: 30s after first completion in a group. */
|
|
24
35
|
const DEFAULT_TIMEOUT = 30_000;
|
|
25
36
|
/** Straggler re-batch timeout: 15s. */
|
|
@@ -63,7 +74,9 @@ export class GroupJoinManager {
|
|
|
63
74
|
const group = this.groups.get(groupId);
|
|
64
75
|
if (!group || group.delivered) return 'pass';
|
|
65
76
|
|
|
66
|
-
|
|
77
|
+
// Captured now: the record is mutated in place by a later resume, and this
|
|
78
|
+
// completion must not be delivered against the run that replaced it.
|
|
79
|
+
group.completedRecords.set(record.id, { record, runGeneration: record.runGeneration ?? 0 });
|
|
67
80
|
|
|
68
81
|
// All done — deliver immediately
|
|
69
82
|
if (group.completedRecords.size >= group.agentIds.size) {
|
|
@@ -86,19 +99,22 @@ export class GroupJoinManager {
|
|
|
86
99
|
if (group.delivered) return;
|
|
87
100
|
group.timeoutHandle = undefined;
|
|
88
101
|
|
|
89
|
-
// Partial delivery — some agents still running
|
|
102
|
+
// Partial delivery — some agents still running. A completion whose record
|
|
103
|
+
// has since started a newer run counts as still pending: its new run has
|
|
104
|
+
// its own completion to deliver.
|
|
90
105
|
const remaining = new Set<string>();
|
|
91
106
|
for (const id of group.agentIds) {
|
|
92
|
-
|
|
107
|
+
const entry = group.completedRecords.get(id);
|
|
108
|
+
if (!entry || !isCurrentRun(entry)) remaining.add(id);
|
|
93
109
|
}
|
|
94
110
|
|
|
95
111
|
// Clean up agentToGroup for delivered agents (they won't complete again)
|
|
96
|
-
for (const id of group.
|
|
97
|
-
this.agentToGroup.delete(id);
|
|
112
|
+
for (const id of group.agentIds) {
|
|
113
|
+
if (!remaining.has(id)) this.agentToGroup.delete(id);
|
|
98
114
|
}
|
|
99
115
|
|
|
100
116
|
// Deliver what we have
|
|
101
|
-
this.deliverCb(
|
|
117
|
+
this.deliverCb(this.liveRecords(group.completedRecords), true);
|
|
102
118
|
|
|
103
119
|
// Set up straggler group for remaining agents
|
|
104
120
|
group.completedRecords.clear();
|
|
@@ -113,19 +129,50 @@ export class GroupJoinManager {
|
|
|
113
129
|
group.timeoutHandle = undefined;
|
|
114
130
|
}
|
|
115
131
|
group.delivered = true;
|
|
116
|
-
this.deliverCb(
|
|
132
|
+
this.deliverCb(this.liveRecords(group.completedRecords), partial);
|
|
117
133
|
this.cleanupGroup(group.groupId);
|
|
118
134
|
}
|
|
119
135
|
|
|
136
|
+
/** Completed records still belonging to the run that completed. */
|
|
137
|
+
private liveRecords(completed: Map<string, CompletedRecord>): AgentRecord[] {
|
|
138
|
+
return [...completed.values()].filter(isCurrentRun).map(entry => entry.record);
|
|
139
|
+
}
|
|
140
|
+
|
|
120
141
|
private cleanupGroup(groupId: string): void {
|
|
121
142
|
const group = this.groups.get(groupId);
|
|
122
143
|
if (!group) return;
|
|
144
|
+
if (group.timeoutHandle) clearTimeout(group.timeoutHandle);
|
|
123
145
|
for (const id of group.agentIds) {
|
|
124
146
|
this.agentToGroup.delete(id);
|
|
125
147
|
}
|
|
126
148
|
this.groups.delete(groupId);
|
|
127
149
|
}
|
|
128
150
|
|
|
151
|
+
/** Discard selected unsent results while retaining every surviving member. */
|
|
152
|
+
discard(agentIds: Iterable<string>): void {
|
|
153
|
+
const discarded = new Set(agentIds);
|
|
154
|
+
for (const id of discarded) this.agentToGroup.delete(id);
|
|
155
|
+
for (const group of [...this.groups.values()]) {
|
|
156
|
+
let changed = false;
|
|
157
|
+
for (const id of discarded) {
|
|
158
|
+
if (!group.agentIds.delete(id)) continue;
|
|
159
|
+
group.completedRecords.delete(id);
|
|
160
|
+
changed = true;
|
|
161
|
+
}
|
|
162
|
+
if (!changed) continue;
|
|
163
|
+
if (group.agentIds.size === 0) {
|
|
164
|
+
this.cleanupGroup(group.groupId);
|
|
165
|
+
} else if (this.liveRecords(group.completedRecords).length === group.agentIds.size) {
|
|
166
|
+
this.deliver(group, false);
|
|
167
|
+
} else if (group.completedRecords.size === 0 && group.timeoutHandle) {
|
|
168
|
+
// No held result remains to start a partial-delivery window. A later
|
|
169
|
+
// survivor completion will arm its own normal/straggler timeout.
|
|
170
|
+
clearTimeout(group.timeoutHandle);
|
|
171
|
+
group.timeoutHandle = undefined;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
129
176
|
/** Check if an agent is in a group. */
|
|
130
177
|
isGrouped(agentId: string): boolean {
|
|
131
178
|
return this.agentToGroup.has(agentId);
|