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