@timmyjl12/pi-subagents 0.0.0-stage → 0.20.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 +827 -0
- package/CONTRIBUTING.md +72 -0
- package/LICENSE +21 -0
- package/README.md +1079 -2
- package/SECURITY.md +97 -0
- package/dist/abortable.d.ts +12 -0
- package/dist/abortable.js +42 -0
- package/dist/active-agents-prompt.d.ts +18 -0
- package/dist/active-agents-prompt.js +34 -0
- package/dist/advisor-status.d.ts +16 -0
- package/dist/advisor-status.js +74 -0
- package/dist/agent-color.d.ts +35 -0
- package/dist/agent-color.js +123 -0
- package/dist/agent-file-toggle.d.ts +125 -0
- package/dist/agent-file-toggle.js +264 -0
- package/dist/agent-manager.d.ts +485 -0
- package/dist/agent-manager.js +1380 -0
- package/dist/agent-runner.d.ts +319 -0
- package/dist/agent-runner.js +1128 -0
- package/dist/agent-types.d.ts +119 -0
- package/dist/agent-types.js +286 -0
- package/dist/child-context.d.ts +15 -0
- package/dist/child-context.js +181 -0
- package/dist/child-session-shutdown.d.ts +3 -0
- package/dist/child-session-shutdown.js +48 -0
- package/dist/context.d.ts +12 -0
- package/dist/context.js +56 -0
- package/dist/cross-extension-rpc.d.ts +66 -0
- package/dist/cross-extension-rpc.js +138 -0
- package/dist/custom-agents.d.ts +54 -0
- package/dist/custom-agents.js +386 -0
- package/dist/default-agents.d.ts +7 -0
- package/dist/default-agents.js +125 -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/error-log.d.ts +58 -0
- package/dist/error-log.js +168 -0
- package/dist/group-join.d.ts +32 -0
- package/dist/group-join.js +116 -0
- package/dist/index.d.ts +52 -0
- package/dist/index.js +3896 -0
- package/dist/invocation-config.d.ts +137 -0
- package/dist/invocation-config.js +129 -0
- package/dist/memory.d.ts +53 -0
- package/dist/memory.js +165 -0
- package/dist/mention-clone.d.ts +87 -0
- package/dist/mention-clone.js +178 -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 +55 -0
- package/dist/nested-tools.js +299 -0
- package/dist/output-diagnostics.d.ts +11 -0
- package/dist/output-diagnostics.js +64 -0
- package/dist/output-file.d.ts +53 -0
- package/dist/output-file.js +248 -0
- package/dist/prompts.d.ts +61 -0
- package/dist/prompts.js +94 -0
- package/dist/recovery.d.ts +56 -0
- package/dist/recovery.js +341 -0
- package/dist/schedule-store.d.ts +44 -0
- package/dist/schedule-store.js +210 -0
- package/dist/schedule.d.ts +109 -0
- package/dist/schedule.js +359 -0
- package/dist/settings.d.ts +360 -0
- package/dist/settings.js +251 -0
- package/dist/skill-loader.d.ts +24 -0
- package/dist/skill-loader.js +93 -0
- package/dist/standalone-fallback.d.ts +30 -0
- package/dist/standalone-fallback.js +239 -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/terminal-progress.d.ts +115 -0
- package/dist/terminal-progress.js +206 -0
- package/dist/types.d.ts +382 -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 +235 -0
- package/dist/ui/agent-widget.js +652 -0
- package/dist/ui/conversation-viewer.d.ts +105 -0
- package/dist/ui/conversation-viewer.js +540 -0
- package/dist/ui/fleet-list.d.ts +183 -0
- package/dist/ui/fleet-list.js +494 -0
- package/dist/ui/fleet-overlay.d.ts +172 -0
- package/dist/ui/fleet-overlay.js +691 -0
- package/dist/ui/native-transcript.d.ts +33 -0
- package/dist/ui/native-transcript.js +230 -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/tool-progress.d.ts +22 -0
- package/dist/ui/tool-progress.js +56 -0
- package/dist/ui/viewer-keys.d.ts +20 -0
- package/dist/ui/viewer-keys.js +17 -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 +363 -0
- package/dist/workflow/journal.d.ts +97 -0
- package/dist/workflow/journal.js +120 -0
- package/dist/workflow/json-schema.d.ts +51 -0
- package/dist/workflow/json-schema.js +111 -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 +90 -0
- package/dist/workflow/saved.js +203 -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/FORK.md +40 -0
- package/docs/recovery.md +62 -0
- package/docs/rpc.md +189 -0
- package/docs/workflows.md +437 -0
- package/examples/agent-tool-description.md +43 -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 +75 -6
- package/src/abortable.ts +43 -0
- package/src/active-agents-prompt.ts +39 -0
- package/src/advisor-status.ts +74 -0
- package/src/agent-color.ts +161 -0
- package/src/agent-file-toggle.ts +273 -0
- package/src/agent-manager.ts +1601 -0
- package/src/agent-runner.ts +1372 -0
- package/src/agent-types.ts +345 -0
- package/src/child-context.ts +173 -0
- package/src/child-session-shutdown.ts +46 -0
- package/src/context.ts +58 -0
- package/src/cross-extension-rpc.ts +198 -0
- package/src/custom-agents.ts +417 -0
- package/src/default-agents.ts +129 -0
- package/src/enabled-models.ts +180 -0
- package/src/env.ts +33 -0
- package/src/error-log.ts +193 -0
- package/src/group-join.ts +141 -0
- package/src/index.ts +4218 -0
- package/src/invocation-config.ts +230 -0
- package/src/memory.ts +179 -0
- package/src/mention-clone.ts +221 -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 +422 -0
- package/src/output-diagnostics.ts +68 -0
- package/src/output-file.ts +258 -0
- package/src/prompts.ts +151 -0
- package/src/recovery.ts +320 -0
- package/src/schedule-store.ts +201 -0
- package/src/schedule.ts +386 -0
- package/src/settings.ts +587 -0
- package/src/skill-loader.ts +102 -0
- package/src/standalone-fallback.ts +195 -0
- package/src/status-note.ts +90 -0
- package/src/structured-output.ts +130 -0
- package/src/terminal-progress.ts +215 -0
- package/src/types.ts +394 -0
- package/src/ui/agent-mention.ts +216 -0
- package/src/ui/agent-widget.ts +732 -0
- package/src/ui/conversation-viewer.ts +523 -0
- package/src/ui/fleet-list.ts +563 -0
- package/src/ui/fleet-overlay.ts +847 -0
- package/src/ui/native-transcript.ts +220 -0
- package/src/ui/schedule-menu.ts +105 -0
- package/src/ui/select-item.ts +45 -0
- package/src/ui/tool-progress.ts +67 -0
- package/src/ui/viewer-keys.ts +39 -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 +404 -0
- package/src/workflow/journal.ts +164 -0
- package/src/workflow/json-schema.ts +128 -0
- package/src/workflow/meta.ts +325 -0
- package/src/workflow/progress.ts +550 -0
- package/src/workflow/runtime.ts +1219 -0
- package/src/workflow/saved.ts +217 -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
package/src/recovery.ts
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
/** Child-local recovery: the producer owns retries whenever installed/observed. */
|
|
2
|
+
import type { AssistantMessage } from "@earendil-works/pi-ai";
|
|
3
|
+
import type { AgentSession, EventBus, ExtensionError } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
import { logSubagentIssue } from "./error-log.js";
|
|
5
|
+
import { isTransientProviderFailure, STANDALONE_CONTINUATION, type StandalonePolicy } from "./standalone-fallback.js";
|
|
6
|
+
|
|
7
|
+
export const RECOVERY_CHANNEL = "pi-fallback-chains:recovery";
|
|
8
|
+
|
|
9
|
+
type RecoveryPhase = "idle" | "pending" | "switching" | "compacting" | "retrying" | "settled" | "cancelled" | "failed";
|
|
10
|
+
|
|
11
|
+
export interface RecoverySnapshot {
|
|
12
|
+
version: 1;
|
|
13
|
+
sessionId: string;
|
|
14
|
+
epoch: number;
|
|
15
|
+
requestId: string;
|
|
16
|
+
revision: number;
|
|
17
|
+
phase: RecoveryPhase;
|
|
18
|
+
pending: boolean;
|
|
19
|
+
model?: string;
|
|
20
|
+
reason?: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const PHASES = new Set<RecoveryPhase>(["idle", "pending", "switching", "compacting", "retrying", "settled", "cancelled", "failed"]);
|
|
24
|
+
const controllers = new WeakMap<AgentSession, ChildRecovery>();
|
|
25
|
+
|
|
26
|
+
function isSnapshot(value: unknown): value is RecoverySnapshot {
|
|
27
|
+
if (!value || typeof value !== "object") return false;
|
|
28
|
+
const s = value as Partial<RecoverySnapshot>;
|
|
29
|
+
return s.version === 1 && typeof s.sessionId === "string" && typeof s.requestId === "string"
|
|
30
|
+
&& Number.isSafeInteger(s.epoch) && s.epoch! >= 0 && Number.isSafeInteger(s.revision) && s.revision! >= 0
|
|
31
|
+
&& PHASES.has(s.phase!) && typeof s.pending === "boolean"
|
|
32
|
+
&& s.pending === ["pending", "switching", "compacting", "retrying"].includes(s.phase!)
|
|
33
|
+
&& (s.model === undefined || typeof s.model === "string")
|
|
34
|
+
&& (s.reason === undefined || typeof s.reason === "string");
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export class ChildRecovery {
|
|
38
|
+
private session?: AgentSession;
|
|
39
|
+
private snapshot?: RecoverySnapshot;
|
|
40
|
+
private cancelled = false;
|
|
41
|
+
private disposed = false;
|
|
42
|
+
private waiters = new Set<() => void>();
|
|
43
|
+
private unsubscribe: () => void;
|
|
44
|
+
private onModelChange?: (session: AgentSession) => void;
|
|
45
|
+
private standalone?: StandalonePolicy;
|
|
46
|
+
private ownerObserved = false;
|
|
47
|
+
private generation = 0;
|
|
48
|
+
private attempted = false;
|
|
49
|
+
private prompting = false;
|
|
50
|
+
private unfinishedTools = new Set<string>();
|
|
51
|
+
private unsafeTools = false;
|
|
52
|
+
|
|
53
|
+
configureStandalone(policy: StandalonePolicy): void { this.standalone = policy; }
|
|
54
|
+
|
|
55
|
+
/** A managed prompt — the run itself or its recovery continuation — is active. */
|
|
56
|
+
isPrompting(): boolean { return this.prompting && !this.disposed; }
|
|
57
|
+
|
|
58
|
+
/** Only managed request boundaries reset cancellation and the one-attempt budget. */
|
|
59
|
+
beginRequest(): void {
|
|
60
|
+
if (this.disposed || this.prompting) throw new Error("Child recovery request is still active or disposed");
|
|
61
|
+
this.generation++;
|
|
62
|
+
this.cancelled = false;
|
|
63
|
+
this.attempted = false;
|
|
64
|
+
this.unsafeTools = false;
|
|
65
|
+
this.unfinishedTools.clear();
|
|
66
|
+
if (!this.standalone) return;
|
|
67
|
+
// Prior unfinished calls cannot safely be replayed by a resumed request.
|
|
68
|
+
for (const message of this.session?.messages ?? []) {
|
|
69
|
+
if (message.role === "assistant") {
|
|
70
|
+
for (const part of message.content) if (part.type === "toolCall") this.unfinishedTools.add(part.id);
|
|
71
|
+
} else if (message.role === "toolResult") this.unfinishedTools.delete(message.toolCallId);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Construct before loading extensions, attach before bindExtensions/session_start. */
|
|
76
|
+
constructor(private bus: EventBus) {
|
|
77
|
+
this.unsubscribe = bus.on(RECOVERY_CHANNEL, data => this.receive(data));
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
attach(session: AgentSession, onModelChange?: (session: AgentSession) => void): void {
|
|
81
|
+
this.session = session;
|
|
82
|
+
this.onModelChange = onModelChange;
|
|
83
|
+
controllers.set(session, this);
|
|
84
|
+
const dispose = session.dispose?.bind(session);
|
|
85
|
+
if (dispose) session.dispose = () => { this.dispose(); dispose(); };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
private receive(data: unknown): void {
|
|
89
|
+
if (this.disposed || !isSnapshot(data) || data.sessionId !== this.session?.sessionId) return;
|
|
90
|
+
// Ownership is sticky and independent of lease state, age, or cancellation.
|
|
91
|
+
this.ownerObserved = true;
|
|
92
|
+
const previous = this.snapshot;
|
|
93
|
+
if (previous && (data.epoch < previous.epoch || data.revision <= previous.revision)) return;
|
|
94
|
+
if (previous && data.epoch === previous.epoch && data.requestId !== previous.requestId) return;
|
|
95
|
+
if (this.cancelled && data.pending) return;
|
|
96
|
+
// Copy: a producer mutating its next snapshot must not mutate our observed generation.
|
|
97
|
+
this.snapshot = { ...data };
|
|
98
|
+
this.onModelChange?.(this.session);
|
|
99
|
+
this.wake();
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
private query(): void {
|
|
103
|
+
if (this.disposed || !this.session) return;
|
|
104
|
+
this.bus.emit(`${RECOVERY_CHANNEL}:query`, {
|
|
105
|
+
version: 1,
|
|
106
|
+
sessionId: this.session.sessionId,
|
|
107
|
+
reply: (snapshot: unknown) => this.receive(snapshot),
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
private wake(): void {
|
|
112
|
+
for (const resolve of this.waiters) resolve();
|
|
113
|
+
this.waiters.clear();
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
cancel(reason: string): void {
|
|
117
|
+
if (this.cancelled || this.disposed) return;
|
|
118
|
+
this.cancelled = true;
|
|
119
|
+
this.generation++;
|
|
120
|
+
if (this.session) {
|
|
121
|
+
this.bus.emit(`${RECOVERY_CHANNEL}:cancel`, { version: 1, sessionId: this.session.sessionId, reason });
|
|
122
|
+
}
|
|
123
|
+
this.wake();
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
executionError(error: ExtensionError): void {
|
|
127
|
+
if (this.disposed || !this.session) return;
|
|
128
|
+
this.unsafeTools = true; // Extension/tool exceptions are not provider failures.
|
|
129
|
+
if (error.event !== "send_user_message") return;
|
|
130
|
+
// Provider errors can contain credentials or entire requests. The protocol needs
|
|
131
|
+
// the category, not the raw exception; the normal Pi error path still owns it.
|
|
132
|
+
this.bus.emit(`${RECOVERY_CHANNEL}:execution-error`, {
|
|
133
|
+
version: 1,
|
|
134
|
+
sessionId: this.session.sessionId,
|
|
135
|
+
event: error.event,
|
|
136
|
+
message: "Recovery prompt submission failed (send_user_message).",
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async prompt(text: string, signal?: AbortSignal): Promise<string | undefined> {
|
|
141
|
+
const session = this.session;
|
|
142
|
+
if (!session || this.disposed) throw new Error("Child recovery session is disposed");
|
|
143
|
+
if (signal?.aborted || this.cancelled) return undefined;
|
|
144
|
+
if (this.prompting) throw new Error("Child recovery prompt is already active");
|
|
145
|
+
this.prompting = true;
|
|
146
|
+
const generation = this.generation;
|
|
147
|
+
const current = () => !this.disposed && !this.cancelled && !signal?.aborted && generation === this.generation;
|
|
148
|
+
const abort = () => this.cancel("aborted");
|
|
149
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
150
|
+
let finalMessage: AssistantMessage | undefined;
|
|
151
|
+
const unsubscribe = this.standalone ? session.subscribe(event => {
|
|
152
|
+
if (!current()) return;
|
|
153
|
+
if (event.type === "message_end") {
|
|
154
|
+
if (event.message.role === "assistant") {
|
|
155
|
+
finalMessage = event.message;
|
|
156
|
+
for (const part of event.message.content) if (part.type === "toolCall") this.unfinishedTools.add(part.id);
|
|
157
|
+
} else if (event.message.role === "toolResult") {
|
|
158
|
+
this.unfinishedTools.delete(event.message.toolCallId);
|
|
159
|
+
if (event.message.isError) this.unsafeTools = true;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
if (event.type === "tool_execution_start") this.unfinishedTools.add(event.toolCallId);
|
|
163
|
+
if (event.type === "tool_execution_end" && event.isError) this.unsafeTools = true;
|
|
164
|
+
}) : () => {};
|
|
165
|
+
this.query();
|
|
166
|
+
const revision = this.snapshot?.revision ?? -1;
|
|
167
|
+
try {
|
|
168
|
+
await session.prompt(text);
|
|
169
|
+
if (!current()) return undefined;
|
|
170
|
+
this.query();
|
|
171
|
+
if (this.snapshot) await this.waitForSettlement(session);
|
|
172
|
+
if (!current()) return undefined;
|
|
173
|
+
this.query();
|
|
174
|
+
const policy = this.standalone;
|
|
175
|
+
const ownsLocally = () => {
|
|
176
|
+
this.query();
|
|
177
|
+
return current() && !this.ownerObserved && policy?.ownership() === "absent";
|
|
178
|
+
};
|
|
179
|
+
if (policy && !this.attempted && isTransientProviderFailure(finalMessage)
|
|
180
|
+
&& !this.unsafeTools && this.unfinishedTools.size === 0 && ownsLocally()) {
|
|
181
|
+
this.attempted = true; // Consume before resolution, switching, or any await.
|
|
182
|
+
const failed = session.model;
|
|
183
|
+
if (!failed || finalMessage?.provider !== failed.provider || finalMessage.model !== failed.id) return undefined;
|
|
184
|
+
// This layer has no agentId (records live in agent-manager); the
|
|
185
|
+
// sessionId is the correlation handle on the persistent aggregate log.
|
|
186
|
+
const logOutcome = (outcome: "success" | "blocked" | "failed", reason?: string,
|
|
187
|
+
to?: { provider: string; model: string }) =>
|
|
188
|
+
logSubagentIssue({ kind: "standalone_fallback", sessionId: session.sessionId,
|
|
189
|
+
from: { provider: failed.provider, model: failed.id }, to, outcome, reason });
|
|
190
|
+
let target: ReturnType<StandalonePolicy["resolve"]>;
|
|
191
|
+
try { target = policy.resolve(session, failed); } catch {
|
|
192
|
+
logOutcome("failed", "Standalone fallback target could not be resolved.");
|
|
193
|
+
return "Standalone fallback target could not be resolved.";
|
|
194
|
+
}
|
|
195
|
+
if (!target) logOutcome("blocked", "No eligible standalone fallback target.");
|
|
196
|
+
if (target && ownsLocally() && session.isIdle && !session.isCompacting) {
|
|
197
|
+
try {
|
|
198
|
+
await session.setModel(target, { persist: false });
|
|
199
|
+
} catch {
|
|
200
|
+
logOutcome("failed", "Standalone fallback model switch failed.", { provider: target.provider, model: target.id });
|
|
201
|
+
if (!current()) return undefined;
|
|
202
|
+
this.query();
|
|
203
|
+
if (this.snapshot) await this.waitForSettlement(session);
|
|
204
|
+
if (!current()) return undefined;
|
|
205
|
+
return "Standalone fallback model switch failed.";
|
|
206
|
+
}
|
|
207
|
+
if (!current()) return undefined;
|
|
208
|
+
this.onModelChange?.(session);
|
|
209
|
+
// A producer, scope change, cancellation, or manual switch can win
|
|
210
|
+
// while setModel awaits auth/model_select. Never undo that decision.
|
|
211
|
+
if (ownsLocally() && session.model?.provider === target.provider && session.model.id === target.id
|
|
212
|
+
&& session.isIdle && !session.isCompacting && !this.unsafeTools && this.unfinishedTools.size === 0) {
|
|
213
|
+
let allowed: ReturnType<StandalonePolicy["resolve"]>;
|
|
214
|
+
try { allowed = policy.resolve(session, failed); } catch {
|
|
215
|
+
logOutcome("failed", "Standalone fallback scope could not be checked.", { provider: target.provider, model: target.id });
|
|
216
|
+
return "Standalone fallback scope could not be checked.";
|
|
217
|
+
}
|
|
218
|
+
if (allowed?.provider === target.provider && allowed.id === target.id && ownsLocally()) {
|
|
219
|
+
await session.prompt(STANDALONE_CONTINUATION, { source: "extension", expandPromptTemplates: false });
|
|
220
|
+
logOutcome("success", undefined, { provider: target.provider, model: target.id });
|
|
221
|
+
if (!current()) return undefined;
|
|
222
|
+
this.query();
|
|
223
|
+
} else {
|
|
224
|
+
logOutcome("blocked", "Post-switch scope re-check refused the standalone fallback target.",
|
|
225
|
+
{ provider: target.provider, model: target.id });
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
// An owner arriving during switching/continuation still retains its slot.
|
|
229
|
+
if (this.snapshot) await this.waitForSettlement(session);
|
|
230
|
+
if (!current()) return undefined;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
// A query/resolver can discover ownership even when no local switch ran.
|
|
234
|
+
if (this.snapshot?.pending) await this.waitForSettlement(session);
|
|
235
|
+
if (!current()) return undefined;
|
|
236
|
+
this.onModelChange?.(session);
|
|
237
|
+
if (this.snapshot?.phase === "failed" && this.snapshot.revision > revision) {
|
|
238
|
+
return this.snapshot.reason || "Automatic recovery failed.";
|
|
239
|
+
}
|
|
240
|
+
return undefined;
|
|
241
|
+
} catch (error) {
|
|
242
|
+
if (current()) this.cancel("prompt_failed");
|
|
243
|
+
throw error;
|
|
244
|
+
} finally {
|
|
245
|
+
unsubscribe();
|
|
246
|
+
signal?.removeEventListener("abort", abort);
|
|
247
|
+
this.prompting = false;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
private async waitForSettlement(session: AgentSession): Promise<void> {
|
|
252
|
+
const unsubscribe = session.subscribe(event => {
|
|
253
|
+
if (event.type === "agent_settled" || event.type === "agent_start" || event.type === "compaction_end") this.wake();
|
|
254
|
+
});
|
|
255
|
+
try {
|
|
256
|
+
while (!this.disposed) {
|
|
257
|
+
this.query();
|
|
258
|
+
if ((!this.cancelled && this.snapshot?.pending) || session.isCompacting) {
|
|
259
|
+
await new Promise<void>(resolve => this.waiters.add(resolve));
|
|
260
|
+
continue;
|
|
261
|
+
}
|
|
262
|
+
const observed = this.snapshot;
|
|
263
|
+
let changed!: () => void;
|
|
264
|
+
const change = new Promise<void>(resolve => { changed = resolve; this.waiters.add(resolve); });
|
|
265
|
+
try {
|
|
266
|
+
await Promise.race([session.waitForIdle(), change]);
|
|
267
|
+
} finally {
|
|
268
|
+
this.waiters.delete(changed);
|
|
269
|
+
}
|
|
270
|
+
if (this.disposed) return;
|
|
271
|
+
this.query();
|
|
272
|
+
// A new lease can be claimed inside waitForIdle/agent_settled. Check the
|
|
273
|
+
// same snapshot generation AND session state, never just agent_end.
|
|
274
|
+
if ((this.cancelled || observed === this.snapshot) && (this.cancelled || !this.snapshot?.pending)
|
|
275
|
+
&& session.isIdle && !session.isCompacting) return;
|
|
276
|
+
}
|
|
277
|
+
} finally {
|
|
278
|
+
unsubscribe();
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
dispose(): void {
|
|
283
|
+
if (this.disposed) return;
|
|
284
|
+
this.cancel("shutdown");
|
|
285
|
+
this.disposed = true;
|
|
286
|
+
this.unsubscribe();
|
|
287
|
+
if (this.session) controllers.delete(this.session);
|
|
288
|
+
this.wake();
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** True while a managed prompt (including fallback recovery) is still in flight. */
|
|
293
|
+
export function isChildRequestActive(session: AgentSession): boolean {
|
|
294
|
+
return controllers.get(session)?.isPrompting() === true;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
export function beginChildRequest(session: AgentSession): void {
|
|
298
|
+
controllers.get(session)?.beginRequest();
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
export async function promptWithRecovery(session: AgentSession, text: string, signal?: AbortSignal): Promise<string | undefined> {
|
|
302
|
+
const recovery = controllers.get(session);
|
|
303
|
+
if (recovery) return recovery.prompt(text, signal);
|
|
304
|
+
if (!signal?.aborted) await session.prompt(text);
|
|
305
|
+
return undefined;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** Invalidate extension timers/continuations synchronously BEFORE Pi aborts. */
|
|
309
|
+
export async function abortChildSession(session: AgentSession, reason = "aborted"): Promise<void> {
|
|
310
|
+
controllers.get(session)?.cancel(reason);
|
|
311
|
+
if (session.isCompacting) {
|
|
312
|
+
session.abortCompaction();
|
|
313
|
+
session.abortBranchSummary();
|
|
314
|
+
}
|
|
315
|
+
await session.abort();
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
export function disposeChildRecovery(session: AgentSession): void {
|
|
319
|
+
controllers.get(session)?.dispose();
|
|
320
|
+
}
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* schedule-store.ts — File-backed store for scheduled subagents.
|
|
3
|
+
*
|
|
4
|
+
* Session-scoped: each pi session owns its own schedules at
|
|
5
|
+
* `<cwd>/.pi/subagent-schedules/<sessionId>.json`. `/new` starts a fresh
|
|
6
|
+
* empty store; `/resume` reloads.
|
|
7
|
+
*
|
|
8
|
+
* Concurrency model lifted from pi-chonky-tasks/src/task-store.ts: every
|
|
9
|
+
* mutation acquires a PID-based exclusion lock, re-reads the latest state
|
|
10
|
+
* from disk, applies the change, atomic-writes via temp+rename, releases.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { randomBytes } from "node:crypto";
|
|
14
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
15
|
+
import { dirname, join } from "node:path";
|
|
16
|
+
import type { ScheduledSubagent, ScheduleStoreData } from "./types.js";
|
|
17
|
+
|
|
18
|
+
const LOCK_RETRY_MS = 50;
|
|
19
|
+
/** Total synchronous wait for the lock. Mutations run on the UI thread. */
|
|
20
|
+
const LOCK_MAX_WAIT_MS = 1000;
|
|
21
|
+
/**
|
|
22
|
+
* A lock older than this is stale whatever its PID says: Windows reuses PIDs
|
|
23
|
+
* aggressively, so "that process is alive" does not mean it holds the lock.
|
|
24
|
+
* A mutation holds the lock for a few milliseconds.
|
|
25
|
+
*/
|
|
26
|
+
export const LOCK_STALE_MS = 30_000;
|
|
27
|
+
const RENAME_RETRIES = 5;
|
|
28
|
+
const RENAME_RETRY_MS = 20;
|
|
29
|
+
|
|
30
|
+
/** Block the thread without spinning the CPU. */
|
|
31
|
+
function sleepSync(ms: number): void {
|
|
32
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function isProcessRunning(pid: number): boolean {
|
|
36
|
+
try { process.kill(pid, 0); return true; } catch { return false; }
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function errorCode(e: unknown): string | undefined {
|
|
40
|
+
const code = (e as { code?: unknown } | null)?.code;
|
|
41
|
+
return typeof code === "string" ? code : undefined;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** True when the existing lock file can be broken: too old, or its owner is gone. */
|
|
45
|
+
function isLockStale(lockPath: string): boolean {
|
|
46
|
+
try {
|
|
47
|
+
if (Date.now() - statSync(lockPath).mtimeMs > LOCK_STALE_MS) return true;
|
|
48
|
+
const pid = parseInt(readFileSync(lockPath, "utf-8"), 10);
|
|
49
|
+
return Number.isInteger(pid) && pid > 0 && !isProcessRunning(pid);
|
|
50
|
+
} catch (e) {
|
|
51
|
+
// Vanished between our write attempt and this check: retry the write.
|
|
52
|
+
return errorCode(e) === "ENOENT";
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function acquireLock(lockPath: string): void {
|
|
57
|
+
const deadline = Date.now() + LOCK_MAX_WAIT_MS;
|
|
58
|
+
for (;;) {
|
|
59
|
+
try {
|
|
60
|
+
writeFileSync(lockPath, `${process.pid}`, { flag: "wx" });
|
|
61
|
+
return;
|
|
62
|
+
} catch (e) {
|
|
63
|
+
if (errorCode(e) !== "EEXIST") throw e;
|
|
64
|
+
}
|
|
65
|
+
if (isLockStale(lockPath)) {
|
|
66
|
+
try { unlinkSync(lockPath); } catch (e) {
|
|
67
|
+
if (errorCode(e) !== "ENOENT") throw e;
|
|
68
|
+
}
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
if (Date.now() >= deadline) break;
|
|
72
|
+
sleepSync(LOCK_RETRY_MS);
|
|
73
|
+
}
|
|
74
|
+
throw new Error(`Failed to acquire schedule lock: ${lockPath}`);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** rename with a bounded retry: Windows reports EPERM/EBUSY while AV or an indexer holds the target. */
|
|
78
|
+
function renameWithRetry(from: string, to: string): void {
|
|
79
|
+
for (let attempt = 0; ; attempt++) {
|
|
80
|
+
try {
|
|
81
|
+
renameSync(from, to);
|
|
82
|
+
return;
|
|
83
|
+
} catch (e) {
|
|
84
|
+
const code = errorCode(e);
|
|
85
|
+
const transient = code === "EPERM" || code === "EBUSY" || code === "EACCES";
|
|
86
|
+
if (!transient || attempt >= RENAME_RETRIES) {
|
|
87
|
+
try { unlinkSync(from); } catch { /* best effort: the rename error below is the one that matters */ }
|
|
88
|
+
throw e;
|
|
89
|
+
}
|
|
90
|
+
sleepSync(RENAME_RETRY_MS * (attempt + 1));
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function releaseLock(lockPath: string): void {
|
|
96
|
+
try { unlinkSync(lockPath); } catch { /* ignore */ }
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Resolve the storage path for a session-scoped store. */
|
|
100
|
+
export function resolveStorePath(cwd: string, sessionId: string): string {
|
|
101
|
+
return join(cwd, ".pi", "subagent-schedules", `${sessionId}.json`);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export class ScheduleStore {
|
|
105
|
+
private filePath: string;
|
|
106
|
+
private lockPath: string;
|
|
107
|
+
private jobs = new Map<string, ScheduledSubagent>();
|
|
108
|
+
|
|
109
|
+
constructor(filePath: string) {
|
|
110
|
+
this.filePath = filePath;
|
|
111
|
+
this.lockPath = filePath + ".lock";
|
|
112
|
+
this.load();
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Create the backing directory lazily — only when we're about to persist. */
|
|
116
|
+
private ensureDir(): void {
|
|
117
|
+
mkdirSync(dirname(this.filePath), { recursive: true });
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Load from disk into the in-memory cache. Silent on parse errors. */
|
|
121
|
+
private load(): void {
|
|
122
|
+
if (!existsSync(this.filePath)) return;
|
|
123
|
+
try {
|
|
124
|
+
const data: ScheduleStoreData = JSON.parse(readFileSync(this.filePath, "utf-8"));
|
|
125
|
+
this.jobs.clear();
|
|
126
|
+
for (const j of data.jobs ?? []) this.jobs.set(j.id, j);
|
|
127
|
+
} catch { /* corrupt — start fresh, next save rewrites */ }
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Atomic write via temp file + rename (POSIX-atomic). */
|
|
131
|
+
private save(): void {
|
|
132
|
+
const data: ScheduleStoreData = { version: 1, jobs: [...this.jobs.values()] };
|
|
133
|
+
// Unique per write, so two writers can never clobber each other's temp file.
|
|
134
|
+
const tmp = `${this.filePath}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
|
|
135
|
+
writeFileSync(tmp, JSON.stringify(data, null, 2));
|
|
136
|
+
renameWithRetry(tmp, this.filePath);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Acquire lock → reload → mutate → save → release. */
|
|
140
|
+
private withLock<T>(fn: () => T): T {
|
|
141
|
+
this.ensureDir();
|
|
142
|
+
acquireLock(this.lockPath);
|
|
143
|
+
try {
|
|
144
|
+
this.load();
|
|
145
|
+
const result = fn();
|
|
146
|
+
this.save();
|
|
147
|
+
return result;
|
|
148
|
+
} finally {
|
|
149
|
+
releaseLock(this.lockPath);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Read-only — returns a snapshot of the in-memory cache. */
|
|
154
|
+
list(): ScheduledSubagent[] {
|
|
155
|
+
return [...this.jobs.values()];
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Read-only check — uses the cache. */
|
|
159
|
+
hasName(name: string, exceptId?: string): boolean {
|
|
160
|
+
for (const j of this.jobs.values()) {
|
|
161
|
+
if (j.id !== exceptId && j.name === name) return true;
|
|
162
|
+
}
|
|
163
|
+
return false;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
get(id: string): ScheduledSubagent | undefined {
|
|
167
|
+
return this.jobs.get(id);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
add(job: ScheduledSubagent): void {
|
|
171
|
+
this.withLock(() => {
|
|
172
|
+
this.jobs.set(job.id, job);
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
update(id: string, patch: Partial<ScheduledSubagent>): ScheduledSubagent | undefined {
|
|
177
|
+
// No-op fast path — an unknown id changes nothing, so don't lock or touch
|
|
178
|
+
// disk (which would otherwise lazily create the backing directory).
|
|
179
|
+
if (!this.jobs.has(id)) return undefined;
|
|
180
|
+
return this.withLock(() => {
|
|
181
|
+
const existing = this.jobs.get(id);
|
|
182
|
+
if (!existing) return undefined;
|
|
183
|
+
const updated = { ...existing, ...patch };
|
|
184
|
+
this.jobs.set(id, updated);
|
|
185
|
+
return updated;
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
remove(id: string): boolean {
|
|
190
|
+
// No-op fast path — see update().
|
|
191
|
+
if (!this.jobs.has(id)) return false;
|
|
192
|
+
return this.withLock(() => this.jobs.delete(id));
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** Delete the backing file (used when no jobs remain, optional cleanup). */
|
|
196
|
+
deleteFileIfEmpty(): void {
|
|
197
|
+
if (this.jobs.size === 0 && existsSync(this.filePath)) {
|
|
198
|
+
try { unlinkSync(this.filePath); } catch { /* ignore */ }
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
}
|