@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.
Files changed (159) hide show
  1. package/CHANGELOG.md +862 -827
  2. package/README.md +1125 -1080
  3. package/dist/active-agents-prompt.d.ts +31 -9
  4. package/dist/active-agents-prompt.js +73 -9
  5. package/dist/agent-color.js +9 -1
  6. package/dist/agent-file-toggle.d.ts +1 -1
  7. package/dist/agent-manager.d.ts +405 -18
  8. package/dist/agent-manager.js +1661 -131
  9. package/dist/agent-runner.d.ts +45 -6
  10. package/dist/agent-runner.js +109 -18
  11. package/dist/agent-types.d.ts +30 -7
  12. package/dist/agent-types.js +38 -9
  13. package/dist/awaited-result.d.ts +37 -0
  14. package/dist/awaited-result.js +150 -0
  15. package/dist/child-session-shutdown.d.ts +19 -1
  16. package/dist/child-session-shutdown.js +60 -11
  17. package/dist/cleanup-plans.d.ts +10 -0
  18. package/dist/cleanup-plans.js +112 -0
  19. package/dist/cross-extension-rpc.d.ts +8 -1
  20. package/dist/cross-extension-rpc.js +59 -5
  21. package/dist/custom-agents.d.ts +34 -9
  22. package/dist/custom-agents.js +308 -111
  23. package/dist/default-agents.d.ts +1 -1
  24. package/dist/env.d.ts +1 -1
  25. package/dist/error-log.d.ts +6 -0
  26. package/dist/error-log.js +8 -0
  27. package/dist/force-main-model.d.ts +21 -0
  28. package/dist/force-main-model.js +28 -0
  29. package/dist/goal-bridge.d.ts +155 -0
  30. package/dist/goal-bridge.js +305 -0
  31. package/dist/group-join.d.ts +5 -1
  32. package/dist/group-join.js +52 -7
  33. package/dist/index.d.ts +5 -5
  34. package/dist/index.js +2827 -333
  35. package/dist/invocation-config.d.ts +30 -3
  36. package/dist/invocation-config.js +30 -1
  37. package/dist/memory.d.ts +1 -1
  38. package/dist/mention-clone.d.ts +1 -1
  39. package/dist/model-scope.d.ts +1 -1
  40. package/dist/nested-tools.d.ts +22 -1
  41. package/dist/nested-tools.js +120 -26
  42. package/dist/output-file.d.ts +15 -4
  43. package/dist/output-file.js +146 -43
  44. package/dist/prompts.d.ts +1 -1
  45. package/dist/recovery.d.ts +1 -1
  46. package/dist/report-cleanup.d.ts +204 -0
  47. package/dist/report-cleanup.js +1632 -0
  48. package/dist/report-store.d.ts +738 -0
  49. package/dist/report-store.js +3616 -0
  50. package/dist/schedule-store.d.ts +14 -6
  51. package/dist/schedule-store.js +88 -58
  52. package/dist/schedule.d.ts +20 -8
  53. package/dist/schedule.js +135 -74
  54. package/dist/settings.d.ts +39 -11
  55. package/dist/settings.js +22 -5
  56. package/dist/status-note.d.ts +1 -1
  57. package/dist/structured-output.d.ts +1 -1
  58. package/dist/types.d.ts +32 -3
  59. package/dist/ui/agent-mention.d.ts +2 -2
  60. package/dist/ui/agent-widget.d.ts +82 -13
  61. package/dist/ui/agent-widget.js +155 -37
  62. package/dist/ui/cleanup-preview.d.ts +59 -0
  63. package/dist/ui/cleanup-preview.js +466 -0
  64. package/dist/ui/conversation-viewer.d.ts +4 -4
  65. package/dist/ui/conversation-viewer.js +10 -6
  66. package/dist/ui/fleet-list.d.ts +3 -3
  67. package/dist/ui/fleet-list.js +3 -3
  68. package/dist/ui/fleet-overlay.d.ts +37 -6
  69. package/dist/ui/fleet-overlay.js +214 -18
  70. package/dist/ui/hub-feed.d.ts +52 -0
  71. package/dist/ui/hub-feed.js +148 -0
  72. package/dist/ui/native-transcript.js +5 -1
  73. package/dist/ui/schedule-menu.d.ts +1 -1
  74. package/dist/ui/schedule-menu.js +1 -1
  75. package/dist/ui/workflow-card.d.ts +4 -4
  76. package/dist/ui/workflow-dialog.d.ts +4 -4
  77. package/dist/ui/workflow-dialog.js +8 -3
  78. package/dist/ui/workflow-menu.d.ts +2 -2
  79. package/dist/usage.d.ts +12 -0
  80. package/dist/usage.js +28 -1
  81. package/dist/workflow/entry.d.ts +3 -3
  82. package/dist/workflow/host.d.ts +7 -4
  83. package/dist/workflow/host.js +162 -48
  84. package/dist/workflow/journal.d.ts +23 -7
  85. package/dist/workflow/journal.js +80 -23
  86. package/dist/workflow/progress.d.ts +1 -1
  87. package/dist/workflow/runtime.d.ts +45 -6
  88. package/dist/workflow/runtime.js +105 -16
  89. package/dist/workflow/task.d.ts +13 -4
  90. package/dist/workflow/task.js +7 -1
  91. package/dist/workflow/tool-description.d.ts +7 -2
  92. package/dist/workflow/tool-description.js +10 -5
  93. package/docs/{FORK.md → DEVELOPMENT.md} +4 -4
  94. package/docs/artifacts.md +93 -0
  95. package/docs/rpc.md +252 -189
  96. package/docs/runtime-performance.md +53 -0
  97. package/docs/workflows.md +48 -18
  98. package/examples/agent-tool-description.md +2 -2
  99. package/examples/workflows/review-panel.js +6 -3
  100. package/package.json +5 -5
  101. package/src/active-agents-prompt.ts +115 -39
  102. package/src/agent-color.ts +10 -2
  103. package/src/agent-file-toggle.ts +2 -2
  104. package/src/agent-manager.ts +3312 -1601
  105. package/src/agent-runner.ts +164 -36
  106. package/src/agent-types.ts +56 -11
  107. package/src/awaited-result.ts +187 -0
  108. package/src/child-session-shutdown.ts +114 -46
  109. package/src/cleanup-plans.ts +112 -0
  110. package/src/cross-extension-rpc.ts +68 -9
  111. package/src/custom-agents.ts +384 -112
  112. package/src/default-agents.ts +1 -1
  113. package/src/enabled-models.ts +1 -1
  114. package/src/env.ts +1 -1
  115. package/src/error-log.ts +10 -1
  116. package/src/force-main-model.ts +29 -0
  117. package/src/goal-bridge.ts +468 -0
  118. package/src/group-join.ts +56 -9
  119. package/src/index.ts +2987 -349
  120. package/src/invocation-config.ts +50 -4
  121. package/src/memory.ts +1 -1
  122. package/src/mention-clone.ts +3 -3
  123. package/src/model-scope.ts +1 -1
  124. package/src/nested-tools.ts +164 -33
  125. package/src/output-file.ts +168 -46
  126. package/src/prompts.ts +1 -1
  127. package/src/recovery.ts +2 -2
  128. package/src/report-cleanup.ts +2044 -0
  129. package/src/report-store.ts +4133 -0
  130. package/src/schedule-store.ts +244 -201
  131. package/src/schedule.ts +144 -80
  132. package/src/settings.ts +61 -16
  133. package/src/skill-loader.ts +1 -1
  134. package/src/standalone-fallback.ts +2 -2
  135. package/src/status-note.ts +1 -1
  136. package/src/structured-output.ts +1 -1
  137. package/src/types.ts +33 -3
  138. package/src/ui/agent-mention.ts +3 -3
  139. package/src/ui/agent-widget.ts +179 -45
  140. package/src/ui/cleanup-preview.ts +518 -0
  141. package/src/ui/conversation-viewer.ts +19 -15
  142. package/src/ui/fleet-list.ts +7 -7
  143. package/src/ui/fleet-overlay.ts +1048 -847
  144. package/src/ui/hub-feed.ts +179 -0
  145. package/src/ui/native-transcript.ts +7 -3
  146. package/src/ui/schedule-menu.ts +4 -4
  147. package/src/ui/workflow-card.ts +4 -4
  148. package/src/ui/workflow-dialog.ts +10 -6
  149. package/src/ui/workflow-menu.ts +4 -4
  150. package/src/usage.ts +53 -3
  151. package/src/workflow/collisions.ts +1 -1
  152. package/src/workflow/entry.ts +3 -3
  153. package/src/workflow/host.ts +174 -54
  154. package/src/workflow/journal.ts +80 -23
  155. package/src/workflow/progress.ts +1 -1
  156. package/src/workflow/runtime.ts +146 -23
  157. package/src/workflow/saved.ts +3 -3
  158. package/src/workflow/task.ts +18 -7
  159. package/src/workflow/tool-description.ts +10 -5
@@ -0,0 +1,155 @@
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
+ /** Provider id used in hints and by consumers that filter replies. */
22
+ export declare const AGENT_PROVIDER_ID = "pi-subagents";
23
+ export declare const GOAL_AGENTS_REQUEST = "goal:agents:request";
24
+ export declare const GOAL_AGENTS_READY = "goal:agents:ready";
25
+ export declare const GOAL_AGENTS_CHANGED = "goal:agents:changed";
26
+ export declare const STEER_TOOL_NAME = "steer_subagent";
27
+ /** Structural binding a consumer uses to reach the ORIGINAL steering tool. */
28
+ export declare const STEER_TOOL_BINDING: {
29
+ readonly kind: "steer-tool-v1";
30
+ readonly toolName: "steer_subagent";
31
+ };
32
+ /** In-process event bus surface (pi.events). */
33
+ export interface GoalAgentEventBus {
34
+ emit(channel: string, data: unknown): void;
35
+ on(channel: string, handler: (data: unknown) => void): () => void;
36
+ }
37
+ /** The subset of an agent record this bridge reads (structurally AgentRecord). */
38
+ export interface GoalAgentRecord {
39
+ id: string;
40
+ type: string;
41
+ description: string;
42
+ status: string;
43
+ handle?: string;
44
+ result?: string;
45
+ error?: string;
46
+ runGeneration?: number;
47
+ rootSessionId?: string;
48
+ parentAgentId?: string;
49
+ workflowId?: string;
50
+ }
51
+ /** Narrow manager surface; never the process-global registry. */
52
+ export interface GoalAgentSource {
53
+ listAgents(): readonly GoalAgentRecord[];
54
+ getRecord(id: string): GoalAgentRecord | undefined;
55
+ steerAcknowledged(id: string, message: string): Promise<boolean>;
56
+ }
57
+ /** Validated `goalGuard` carried by the ORIGINAL steer_subagent tool. */
58
+ export interface GoalAgentGuard {
59
+ version: 1;
60
+ sessionId: string;
61
+ goalId: string;
62
+ runGeneration: number;
63
+ operationId: string;
64
+ }
65
+ export type GoalAgentGuardErrorCode = "invalid-guard" | "unavailable" | "session-mismatch" | "agent-not-found" | "not-top-level" | "generation-mismatch" | "not-steerable" | "aborted" | "duplicate-operation" | "not-delivered";
66
+ /** Guard refusal. The original tool throws it, so callers see a real error. */
67
+ export declare class GoalAgentGuardError extends Error {
68
+ readonly code: GoalAgentGuardErrorCode;
69
+ constructor(code: GoalAgentGuardErrorCode, message: string);
70
+ }
71
+ export interface GoalAgentSnapshotEntry {
72
+ id: string;
73
+ type: string;
74
+ description: string;
75
+ status: string;
76
+ runGeneration: number;
77
+ handle?: string;
78
+ result?: string;
79
+ error?: string;
80
+ }
81
+ export interface GoalAgentSnapshot {
82
+ success: true;
83
+ version: 1;
84
+ sessionId: string;
85
+ /** Echo of the request envelope id (the consumer rejects replies without it). */
86
+ requestId: string;
87
+ agents: GoalAgentSnapshotEntry[];
88
+ steerBinding: typeof STEER_TOOL_BINDING;
89
+ /** Additive: the roster exceeded the bounded snapshot size. */
90
+ truncated?: true;
91
+ }
92
+ export interface GoalAgentSnapshotFailure {
93
+ success: false;
94
+ version: 1;
95
+ sessionId: string;
96
+ requestId: string;
97
+ error: string;
98
+ }
99
+ export type GoalAgentSnapshotReply = GoalAgentSnapshot | GoalAgentSnapshotFailure;
100
+ /** Receipt of one acknowledged guarded steer. */
101
+ export interface GuardedSteerReceipt {
102
+ agentId: string;
103
+ runGeneration: number;
104
+ operationId: string;
105
+ /** The caller's signal was aborted after delivery — it could not be unsent. */
106
+ abortedAfterDelivery?: true;
107
+ }
108
+ /** Strict `unknown` → `GoalAgentGuard`; undefined means malformed. */
109
+ export declare function parseGoalAgentGuard(value: unknown): GoalAgentGuard | undefined;
110
+ export interface SubagentsGoalBridgeOptions {
111
+ source: GoalAgentSource;
112
+ events?: GoalAgentEventBus;
113
+ /** Bounded agent rows (default 200). */
114
+ maxAgents?: number;
115
+ }
116
+ /**
117
+ * Live bridge. `bind` runs from the original `session_start` (never the
118
+ * factory) once the manager and the session id exist; `unbind` runs
119
+ * synchronously at `session_shutdown`, before awaited child disposal.
120
+ */
121
+ export declare class SubagentsGoalBridge {
122
+ private readonly source;
123
+ private readonly events;
124
+ private readonly maxAgents;
125
+ private binding;
126
+ private busCleanup;
127
+ private revision;
128
+ private readonly appliedSteers;
129
+ constructor(options: SubagentsGoalBridgeOptions);
130
+ /** Bound live session id, or undefined before bind/after unbind. */
131
+ get sessionId(): string | undefined;
132
+ get bound(): boolean;
133
+ /** Bind the live session. Rebinding releases prior listeners first. */
134
+ bind(sessionId: string): void;
135
+ /** Release bus listeners synchronously; no hint can follow. */
136
+ unbind(): void;
137
+ /** Plain cloned, bounded, filtered snapshot of THIS session's top-level agents. */
138
+ snapshot(requestId: string): GoalAgentSnapshot | undefined;
139
+ private installBus;
140
+ private emit;
141
+ private failure;
142
+ private handleRequest;
143
+ private releaseSteer;
144
+ private trimSteers;
145
+ /**
146
+ * Validate and deliver one guarded steer through `steerAcknowledged`.
147
+ *
148
+ * Every session/ownership/generation/state/signal check runs synchronously
149
+ * after the host's permission hooks and immediately before the one effect
150
+ * call. A rejected delivery releases its operationId and throws, so a retry
151
+ * is allowed; a delivered one keeps the id reserved (per run generation) and
152
+ * a duplicate is refused rather than delivered twice.
153
+ */
154
+ steer(guardRaw: unknown, agentIdRaw: string, message: string, signal?: AbortSignal): Promise<GuardedSteerReceipt>;
155
+ }
@@ -0,0 +1,305 @@
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
+ import { isTopLevelAgent } from "./agent-manager.js";
22
+ /** Provider id used in hints and by consumers that filter replies. */
23
+ export const AGENT_PROVIDER_ID = "pi-subagents";
24
+ export const GOAL_AGENTS_REQUEST = "goal:agents:request";
25
+ export const GOAL_AGENTS_READY = "goal:agents:ready";
26
+ export const GOAL_AGENTS_CHANGED = "goal:agents:changed";
27
+ export const STEER_TOOL_NAME = "steer_subagent";
28
+ /** Structural binding a consumer uses to reach the ORIGINAL steering tool. */
29
+ export const STEER_TOOL_BINDING = { kind: "steer-tool-v1", toolName: STEER_TOOL_NAME };
30
+ const MAX_ID = 200;
31
+ const MAX_MESSAGE = 20_000;
32
+ const MAX_SNAPSHOT_TEXT = 4_000;
33
+ const MAX_DESCRIPTION = 500;
34
+ const MAX_AGENTS = 200;
35
+ const MAX_APPLIED_STEERS = 512;
36
+ const TRUNCATION_MARKER = "…[truncated]";
37
+ /** Guard refusal. The original tool throws it, so callers see a real error. */
38
+ export class GoalAgentGuardError extends Error {
39
+ code;
40
+ constructor(code, message) {
41
+ super(message);
42
+ this.name = "GoalAgentGuardError";
43
+ this.code = code;
44
+ }
45
+ }
46
+ function isRecord(value) {
47
+ return typeof value === "object" && value !== null && !Array.isArray(value);
48
+ }
49
+ function boundedId(value, max) {
50
+ if (typeof value !== "string" || value.length === 0 || value.length > max)
51
+ return undefined;
52
+ for (let index = 0; index < value.length; index++) {
53
+ const code = value.charCodeAt(index);
54
+ if (code < 32 || code === 127)
55
+ return undefined;
56
+ }
57
+ return value;
58
+ }
59
+ /** Strict `unknown` → `GoalAgentGuard`; undefined means malformed. */
60
+ export function parseGoalAgentGuard(value) {
61
+ if (!isRecord(value) || value.version !== 1)
62
+ return undefined;
63
+ const sessionId = boundedId(value.sessionId, MAX_ID);
64
+ const goalId = boundedId(value.goalId, MAX_ID);
65
+ const operationId = boundedId(value.operationId, MAX_ID);
66
+ const runGeneration = value.runGeneration;
67
+ if (!sessionId || !goalId || !operationId)
68
+ return undefined;
69
+ if (typeof runGeneration !== "number" || !Number.isSafeInteger(runGeneration) || runGeneration < 0)
70
+ return undefined;
71
+ return { version: 1, sessionId, goalId, runGeneration, operationId };
72
+ }
73
+ function truncate(value, max) {
74
+ return value.length > max ? `${value.slice(0, max)}${TRUNCATION_MARKER}` : value;
75
+ }
76
+ /**
77
+ * Live bridge. `bind` runs from the original `session_start` (never the
78
+ * factory) once the manager and the session id exist; `unbind` runs
79
+ * synchronously at `session_shutdown`, before awaited child disposal.
80
+ */
81
+ export class SubagentsGoalBridge {
82
+ source;
83
+ events;
84
+ maxAgents;
85
+ binding;
86
+ busCleanup = [];
87
+ revision = 0;
88
+ appliedSteers = new Set();
89
+ constructor(options) {
90
+ this.source = options.source;
91
+ this.events = options.events;
92
+ this.maxAgents = Math.max(1, options.maxAgents ?? MAX_AGENTS);
93
+ }
94
+ /** Bound live session id, or undefined before bind/after unbind. */
95
+ get sessionId() {
96
+ return this.binding?.sessionId;
97
+ }
98
+ get bound() {
99
+ return this.binding !== undefined;
100
+ }
101
+ /** Bind the live session. Rebinding releases prior listeners first. */
102
+ bind(sessionId) {
103
+ this.unbind();
104
+ this.revision += 1;
105
+ this.appliedSteers.clear();
106
+ this.binding = { sessionId };
107
+ this.installBus();
108
+ this.emit(GOAL_AGENTS_READY);
109
+ }
110
+ /** Release bus listeners synchronously; no hint can follow. */
111
+ unbind() {
112
+ for (const cleanup of this.busCleanup) {
113
+ try {
114
+ cleanup();
115
+ }
116
+ catch (error) {
117
+ console.warn("pi-subagents goal listener cleanup failed", error instanceof Error ? error.name : "unknown error");
118
+ }
119
+ }
120
+ this.busCleanup = [];
121
+ this.binding = undefined;
122
+ this.appliedSteers.clear();
123
+ }
124
+ /** Plain cloned, bounded, filtered snapshot of THIS session's top-level agents. */
125
+ snapshot(requestId) {
126
+ const binding = this.binding;
127
+ if (!binding)
128
+ return undefined;
129
+ const owned = this.source
130
+ .listAgents()
131
+ .filter((record) => record.rootSessionId === binding.sessionId && isTopLevelAgent(record));
132
+ const agents = owned.slice(0, this.maxAgents).map((record) => ({
133
+ id: record.id,
134
+ type: record.type,
135
+ description: truncate(record.description, MAX_DESCRIPTION),
136
+ status: record.status,
137
+ runGeneration: record.runGeneration ?? 0,
138
+ ...(record.handle ? { handle: truncate(record.handle, MAX_ID) } : {}),
139
+ ...(record.result === undefined ? {} : { result: truncate(record.result, MAX_SNAPSHOT_TEXT) }),
140
+ ...(record.error === undefined ? {} : { error: truncate(record.error, MAX_SNAPSHOT_TEXT) }),
141
+ }));
142
+ return {
143
+ success: true,
144
+ version: 1,
145
+ sessionId: binding.sessionId,
146
+ requestId,
147
+ agents,
148
+ steerBinding: { ...STEER_TOOL_BINDING },
149
+ ...(owned.length > this.maxAgents ? { truncated: true } : {}),
150
+ };
151
+ }
152
+ installBus() {
153
+ const events = this.events;
154
+ if (!events || this.busCleanup.length > 0)
155
+ return;
156
+ this.busCleanup = [events.on(GOAL_AGENTS_REQUEST, (data) => this.handleRequest(data))];
157
+ }
158
+ emit(channel) {
159
+ const binding = this.binding;
160
+ if (!binding || !this.events)
161
+ return;
162
+ this.events.emit(channel, {
163
+ version: 1,
164
+ sessionId: binding.sessionId,
165
+ providerId: AGENT_PROVIDER_ID,
166
+ revision: this.revision,
167
+ });
168
+ }
169
+ failure(binding, requestId, error) {
170
+ return { success: false, version: 1, sessionId: binding.sessionId, requestId, error };
171
+ }
172
+ handleRequest(data) {
173
+ const binding = this.binding;
174
+ if (!binding || !isRecord(data))
175
+ return;
176
+ // Foreign sessions, unknown versions and other provider ids are ignored.
177
+ if (data.version !== 1 || data.sessionId !== binding.sessionId)
178
+ return;
179
+ if (data.providerId !== undefined && data.providerId !== AGENT_PROVIDER_ID)
180
+ return;
181
+ const reply = data.reply;
182
+ if (typeof reply !== "function")
183
+ return;
184
+ const respond = (result) => {
185
+ Reflect.apply(reply, data, [result]);
186
+ };
187
+ const requestId = boundedId(data.requestId, MAX_ID);
188
+ if (!requestId) {
189
+ // Echo the raw value when it is a string; a consumer with a valid
190
+ // request id never matches this reply, which is correct.
191
+ respond(this.failure(binding, typeof data.requestId === "string" ? truncate(data.requestId, MAX_ID) : "", "requestId must be a nonempty bounded string"));
192
+ return;
193
+ }
194
+ const signal = data.signal;
195
+ if (isRecord(signal) && signal.aborted === true) {
196
+ respond(this.failure(binding, requestId, "request aborted"));
197
+ return;
198
+ }
199
+ // The v1 client sends no `operation` for this read-only channel, so an
200
+ // omitted operation means snapshot. Anything explicitly named other than
201
+ // "snapshot" is a refused write/edit verb.
202
+ const operation = data.operation;
203
+ if (operation !== undefined && operation !== "snapshot") {
204
+ respond(this.failure(binding, requestId, `unsupported operation: '${String(operation)}': the agent bus is read-only (only 'snapshot')`));
205
+ return;
206
+ }
207
+ respond(this.snapshot(requestId));
208
+ }
209
+ releaseSteer(key) {
210
+ this.appliedSteers.delete(key);
211
+ }
212
+ trimSteers() {
213
+ while (this.appliedSteers.size > MAX_APPLIED_STEERS) {
214
+ const oldest = this.appliedSteers.values().next();
215
+ if (oldest.done)
216
+ break;
217
+ this.appliedSteers.delete(oldest.value);
218
+ }
219
+ }
220
+ /**
221
+ * Validate and deliver one guarded steer through `steerAcknowledged`.
222
+ *
223
+ * Every session/ownership/generation/state/signal check runs synchronously
224
+ * after the host's permission hooks and immediately before the one effect
225
+ * call. A rejected delivery releases its operationId and throws, so a retry
226
+ * is allowed; a delivered one keeps the id reserved (per run generation) and
227
+ * a duplicate is refused rather than delivered twice.
228
+ */
229
+ async steer(guardRaw, agentIdRaw, message, signal) {
230
+ const binding = this.binding;
231
+ if (!binding) {
232
+ throw new GoalAgentGuardError("unavailable", "Goal guard unavailable: no live pi-subagents session is bound. Nothing was steered.");
233
+ }
234
+ const guard = parseGoalAgentGuard(guardRaw);
235
+ if (!guard) {
236
+ throw new GoalAgentGuardError("invalid-guard", "goalGuard is malformed: version 1 and nonempty bounded sessionId, goalId, operationId plus a nonnegative runGeneration are required. Nothing was steered.");
237
+ }
238
+ if (guard.sessionId !== binding.sessionId) {
239
+ throw new GoalAgentGuardError("session-mismatch", `Goal guard session '${guard.sessionId}' is not this live session. Nothing was steered.`);
240
+ }
241
+ if (signal?.aborted) {
242
+ throw new GoalAgentGuardError("aborted", "Goal guard was cancelled before delivery. Nothing was steered.");
243
+ }
244
+ const message_ = message.trim();
245
+ if (message_.length === 0 || message.length > MAX_MESSAGE) {
246
+ throw new GoalAgentGuardError("invalid-guard", `Guarded steering requires a nonempty message of at most ${MAX_MESSAGE} characters. Nothing was steered.`);
247
+ }
248
+ const agentId = boundedId(agentIdRaw, MAX_ID);
249
+ if (!agentId) {
250
+ throw new GoalAgentGuardError("agent-not-found", `Agent not found: "${agentIdRaw}". Nothing was steered.`);
251
+ }
252
+ // Exact id only: a handle could be rebound to another run between the
253
+ // goal snapshot and this call.
254
+ const record = this.source.getRecord(agentId);
255
+ if (!record || record.id !== agentId) {
256
+ throw new GoalAgentGuardError("agent-not-found", `Agent not found: "${agentId}". Nothing was steered.`);
257
+ }
258
+ if (!isTopLevelAgent(record)) {
259
+ throw new GoalAgentGuardError("not-top-level", `Agent ${agentId} is owned by another agent or workflow; guarded steering only reaches this session's top-level agents. Nothing was steered.`);
260
+ }
261
+ if (record.rootSessionId !== binding.sessionId) {
262
+ throw new GoalAgentGuardError("session-mismatch", `Agent ${agentId} does not belong to this session (root ${record.rootSessionId ?? "unknown"}). Nothing was steered.`);
263
+ }
264
+ const generation = record.runGeneration ?? 0;
265
+ if (generation !== guard.runGeneration) {
266
+ throw new GoalAgentGuardError("generation-mismatch", `Agent ${agentId} is on run generation ${generation}, not ${guard.runGeneration}; refresh the agent snapshot before retrying. Nothing was steered.`);
267
+ }
268
+ if (record.status !== "running" && record.status !== "queued") {
269
+ throw new GoalAgentGuardError("not-steerable", `Agent ${agentId} is not running (status: ${record.status}). Nothing was steered.`);
270
+ }
271
+ const key = `${agentId}\u0000${generation}\u0000${guard.operationId}`;
272
+ if (this.appliedSteers.has(key)) {
273
+ throw new GoalAgentGuardError("duplicate-operation", `operationId '${guard.operationId}' was already delivered to agent ${agentId} on run ${generation}; refusing to deliver it twice. Nothing new was steered.`);
274
+ }
275
+ // Reserve before awaiting: concurrent duplicate calls must not both deliver.
276
+ this.appliedSteers.add(key);
277
+ this.trimSteers();
278
+ // Re-check cancellation immediately before the effect, after all awaits
279
+ // that could have occurred in the permission pipeline.
280
+ if (signal?.aborted) {
281
+ this.releaseSteer(key);
282
+ throw new GoalAgentGuardError("aborted", "Goal guard was cancelled before delivery. Nothing was steered.");
283
+ }
284
+ let delivered = false;
285
+ let failureText = "";
286
+ try {
287
+ delivered = await this.source.steerAcknowledged(agentId, message);
288
+ }
289
+ catch (error) {
290
+ failureText = error instanceof Error ? error.message : String(error);
291
+ delivered = false;
292
+ }
293
+ if (!delivered) {
294
+ this.releaseSteer(key);
295
+ throw new GoalAgentGuardError("not-delivered", `Steering message NOT delivered to agent ${agentId}: the session rejected it${failureText ? ` (${truncate(failureText, 300)})` : ""}. Nothing is pretended; retry only after confirming the agent is still running.`);
296
+ }
297
+ this.emit(GOAL_AGENTS_CHANGED);
298
+ return {
299
+ agentId,
300
+ runGeneration: generation,
301
+ operationId: guard.operationId,
302
+ ...(signal?.aborted ? { abortedAfterDelivery: true } : {}),
303
+ };
304
+ }
305
+ }
@@ -5,7 +5,7 @@
5
5
  * agents in a group are held until all complete (or a timeout fires),
6
6
  * then a single consolidated notification is sent.
7
7
  */
8
- import type { AgentRecord } from "./types.js";
8
+ import type { AgentRecord } from "./types.ts";
9
9
  export type DeliveryCallback = (records: AgentRecord[], partial: boolean) => void;
10
10
  export declare class GroupJoinManager {
11
11
  private deliverCb;
@@ -25,7 +25,11 @@ export declare class GroupJoinManager {
25
25
  onAgentComplete(record: AgentRecord): 'delivered' | 'held' | 'pass';
26
26
  private onTimeout;
27
27
  private deliver;
28
+ /** Completed records still belonging to the run that completed. */
29
+ private liveRecords;
28
30
  private cleanupGroup;
31
+ /** Discard selected unsent results while retaining every surviving member. */
32
+ discard(agentIds: Iterable<string>): void;
29
33
  /** Check if an agent is in a group. */
30
34
  isGrouped(agentId: string): boolean;
31
35
  dispose(): void;
@@ -5,6 +5,10 @@
5
5
  * agents in a group are held until all complete (or a timeout fires),
6
6
  * then a single consolidated notification is sent.
7
7
  */
8
+ /** Whether the record still belongs to the run that completed. */
9
+ function isCurrentRun(entry) {
10
+ return (entry.record.runGeneration ?? 0) === entry.runGeneration;
11
+ }
8
12
  /** Default timeout: 30s after first completion in a group. */
9
13
  const DEFAULT_TIMEOUT = 30_000;
10
14
  /** Straggler re-batch timeout: 15s. */
@@ -46,7 +50,9 @@ export class GroupJoinManager {
46
50
  const group = this.groups.get(groupId);
47
51
  if (!group || group.delivered)
48
52
  return 'pass';
49
- group.completedRecords.set(record.id, record);
53
+ // Captured now: the record is mutated in place by a later resume, and this
54
+ // completion must not be delivered against the run that replaced it.
55
+ group.completedRecords.set(record.id, { record, runGeneration: record.runGeneration ?? 0 });
50
56
  // All done — deliver immediately
51
57
  if (group.completedRecords.size >= group.agentIds.size) {
52
58
  this.deliver(group, false);
@@ -65,18 +71,22 @@ export class GroupJoinManager {
65
71
  if (group.delivered)
66
72
  return;
67
73
  group.timeoutHandle = undefined;
68
- // Partial delivery — some agents still running
74
+ // Partial delivery — some agents still running. A completion whose record
75
+ // has since started a newer run counts as still pending: its new run has
76
+ // its own completion to deliver.
69
77
  const remaining = new Set();
70
78
  for (const id of group.agentIds) {
71
- if (!group.completedRecords.has(id))
79
+ const entry = group.completedRecords.get(id);
80
+ if (!entry || !isCurrentRun(entry))
72
81
  remaining.add(id);
73
82
  }
74
83
  // Clean up agentToGroup for delivered agents (they won't complete again)
75
- for (const id of group.completedRecords.keys()) {
76
- this.agentToGroup.delete(id);
84
+ for (const id of group.agentIds) {
85
+ if (!remaining.has(id))
86
+ this.agentToGroup.delete(id);
77
87
  }
78
88
  // Deliver what we have
79
- this.deliverCb([...group.completedRecords.values()], true);
89
+ this.deliverCb(this.liveRecords(group.completedRecords), true);
80
90
  // Set up straggler group for remaining agents
81
91
  group.completedRecords.clear();
82
92
  group.agentIds = remaining;
@@ -89,18 +99,53 @@ export class GroupJoinManager {
89
99
  group.timeoutHandle = undefined;
90
100
  }
91
101
  group.delivered = true;
92
- this.deliverCb([...group.completedRecords.values()], partial);
102
+ this.deliverCb(this.liveRecords(group.completedRecords), partial);
93
103
  this.cleanupGroup(group.groupId);
94
104
  }
105
+ /** Completed records still belonging to the run that completed. */
106
+ liveRecords(completed) {
107
+ return [...completed.values()].filter(isCurrentRun).map(entry => entry.record);
108
+ }
95
109
  cleanupGroup(groupId) {
96
110
  const group = this.groups.get(groupId);
97
111
  if (!group)
98
112
  return;
113
+ if (group.timeoutHandle)
114
+ clearTimeout(group.timeoutHandle);
99
115
  for (const id of group.agentIds) {
100
116
  this.agentToGroup.delete(id);
101
117
  }
102
118
  this.groups.delete(groupId);
103
119
  }
120
+ /** Discard selected unsent results while retaining every surviving member. */
121
+ discard(agentIds) {
122
+ const discarded = new Set(agentIds);
123
+ for (const id of discarded)
124
+ this.agentToGroup.delete(id);
125
+ for (const group of [...this.groups.values()]) {
126
+ let changed = false;
127
+ for (const id of discarded) {
128
+ if (!group.agentIds.delete(id))
129
+ continue;
130
+ group.completedRecords.delete(id);
131
+ changed = true;
132
+ }
133
+ if (!changed)
134
+ continue;
135
+ if (group.agentIds.size === 0) {
136
+ this.cleanupGroup(group.groupId);
137
+ }
138
+ else if (this.liveRecords(group.completedRecords).length === group.agentIds.size) {
139
+ this.deliver(group, false);
140
+ }
141
+ else if (group.completedRecords.size === 0 && group.timeoutHandle) {
142
+ // No held result remains to start a partial-delivery window. A later
143
+ // survivor completion will arm its own normal/straggler timeout.
144
+ clearTimeout(group.timeoutHandle);
145
+ group.timeoutHandle = undefined;
146
+ }
147
+ }
148
+ }
104
149
  /** Check if an agent is in a group. */
105
150
  isGrouped(agentId) {
106
151
  return this.agentToGroup.has(agentId);
package/dist/index.d.ts CHANGED
@@ -12,11 +12,11 @@
12
12
  */
13
13
  import { type ExtensionAPI } from "@earendil-works/pi-coding-agent";
14
14
  import { Container } from "@earendil-works/pi-tui";
15
- import { type AdvisorStatus } from "./advisor-status.js";
16
- import { type AgentConfig } from "./types.js";
17
- import { type Theme } from "./ui/agent-widget.js";
18
- import { FOREIGN_WORKFLOW_TOOL_NAMES } from "./workflow/collisions.js";
19
- import { WORKFLOW_ENTRY_TYPE, type WorkflowEntryData, workflowEntryData } from "./workflow/entry.js";
15
+ import { type AdvisorStatus } from "./advisor-status.ts";
16
+ import { type AgentConfig } from "./types.ts";
17
+ import { type Theme } from "./ui/agent-widget.ts";
18
+ import { FOREIGN_WORKFLOW_TOOL_NAMES } from "./workflow/collisions.ts";
19
+ import { WORKFLOW_ENTRY_TYPE, type WorkflowEntryData, workflowEntryData } from "./workflow/entry.ts";
20
20
  export declare function renderRunningAgentStatus(frame: string, statsText: string, activity: string, theme: Pick<Theme, "fg">, advisorStatus?: AdvisorStatus): Container;
21
21
  /**
22
22
  * Format an agent's tool scope for the Agent tool description.