@howaboua/pi-shepherdr 0.1.2 → 0.1.4
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 +52 -0
- package/README.md +55 -50
- package/biome.json +1 -1
- package/changelog.ts +337 -0
- package/index.ts +95 -5
- package/package.json +24 -12
- package/profiles/explorer/profile.json +8 -0
- package/profiles/explorer/prompt.md +1 -0
- package/profiles/general/profile.json +8 -0
- package/profiles/general/prompt.md +1 -0
- package/profiles/reviewer/prepare.mjs +170 -0
- package/profiles/reviewer/profile.json +9 -0
- package/profiles/reviewer/prompt.md +1 -0
- package/src/activity.ts +20 -1
- package/src/agents-contract.ts +142 -0
- package/src/agents-operations.ts +338 -0
- package/src/agents-tool.ts +440 -0
- package/src/ask-answer.ts +297 -0
- package/src/controller.ts +180 -0
- package/src/delivery.ts +68 -0
- package/src/herdr.ts +13 -1
- package/src/launch.ts +62 -8
- package/src/machine-menu.ts +158 -0
- package/src/messages.ts +108 -5
- package/src/monitor-record.ts +34 -1
- package/src/monitor-state.ts +40 -4
- package/src/monitor.ts +63 -6
- package/src/profiles.ts +291 -0
- package/src/remote/shepherdr.mjs +148 -28
- package/src/remote-client.ts +11 -5
- package/src/session-reader.ts +178 -50
- package/src/settlement.ts +228 -33
- package/src/types.ts +31 -1
- package/src/master-config.ts +0 -61
- package/src/master-mode.ts +0 -295
- package/src/tool.ts +0 -234
package/src/session-reader.ts
CHANGED
|
@@ -1,72 +1,194 @@
|
|
|
1
1
|
import { open, stat } from "node:fs/promises";
|
|
2
|
-
import type {
|
|
2
|
+
import type {
|
|
3
|
+
LatestAssistant,
|
|
4
|
+
LatestUser,
|
|
5
|
+
PendingAsk,
|
|
6
|
+
SessionView,
|
|
7
|
+
} from "./types.js";
|
|
3
8
|
|
|
4
9
|
const READ_CHUNK_BYTES = 64 * 1024;
|
|
5
10
|
|
|
6
|
-
function
|
|
7
|
-
|
|
11
|
+
function record(value: unknown): Record<string, unknown> | undefined {
|
|
12
|
+
return typeof value === "object" && value !== null && !Array.isArray(value)
|
|
13
|
+
? (value as Record<string, unknown>)
|
|
14
|
+
: undefined;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function assistantFromMessage(
|
|
18
|
+
id: string,
|
|
19
|
+
message: Record<string, unknown>,
|
|
8
20
|
): LatestAssistant | undefined {
|
|
9
|
-
|
|
10
|
-
if (
|
|
11
|
-
typeof message !== "object" ||
|
|
12
|
-
message === null ||
|
|
13
|
-
!("role" in message) ||
|
|
14
|
-
message.role !== "assistant"
|
|
15
|
-
) {
|
|
16
|
-
return undefined;
|
|
17
|
-
}
|
|
21
|
+
if (message["role"] !== "assistant") return undefined;
|
|
18
22
|
const text: string[] = [];
|
|
19
|
-
if (
|
|
20
|
-
text.push(message
|
|
21
|
-
} else if (
|
|
22
|
-
for (const
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
part
|
|
26
|
-
"type" in part &&
|
|
27
|
-
part.type === "text" &&
|
|
28
|
-
"text" in part &&
|
|
29
|
-
typeof part.text === "string"
|
|
30
|
-
) {
|
|
31
|
-
text.push(part.text);
|
|
23
|
+
if (typeof message["content"] === "string") {
|
|
24
|
+
text.push(message["content"]);
|
|
25
|
+
} else if (Array.isArray(message["content"])) {
|
|
26
|
+
for (const value of message["content"]) {
|
|
27
|
+
const part = record(value);
|
|
28
|
+
if (part?.["type"] === "text" && typeof part["text"] === "string") {
|
|
29
|
+
text.push(part["text"]);
|
|
32
30
|
}
|
|
33
31
|
}
|
|
34
32
|
}
|
|
35
33
|
const joined = text.join("");
|
|
36
34
|
const stopReason =
|
|
37
|
-
|
|
38
|
-
? message
|
|
35
|
+
typeof message["stopReason"] === "string"
|
|
36
|
+
? message["stopReason"]
|
|
39
37
|
: undefined;
|
|
40
38
|
if (!joined && stopReason !== "error") return undefined;
|
|
41
39
|
return {
|
|
42
|
-
id
|
|
40
|
+
id,
|
|
43
41
|
text: joined,
|
|
44
42
|
...(stopReason ? { stopReason } : {}),
|
|
45
43
|
};
|
|
46
44
|
}
|
|
47
45
|
|
|
48
|
-
|
|
46
|
+
function userFromMessage(
|
|
47
|
+
id: string,
|
|
48
|
+
message: Record<string, unknown>,
|
|
49
|
+
): LatestUser | undefined {
|
|
50
|
+
if (message["role"] !== "user") return undefined;
|
|
51
|
+
const text: string[] = [];
|
|
52
|
+
if (typeof message["content"] === "string") {
|
|
53
|
+
text.push(message["content"]);
|
|
54
|
+
} else if (Array.isArray(message["content"])) {
|
|
55
|
+
for (const value of message["content"]) {
|
|
56
|
+
const part = record(value);
|
|
57
|
+
if (part?.["type"] === "text" && typeof part["text"] === "string") {
|
|
58
|
+
text.push(part["text"]);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
const joined = text.join("");
|
|
63
|
+
return joined ? { id, text: joined } : undefined;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function askChoice(
|
|
67
|
+
value: unknown,
|
|
68
|
+
): PendingAsk["prompts"][number]["choices"][number] | undefined {
|
|
69
|
+
const choice = record(value);
|
|
70
|
+
if (!choice || typeof choice["label"] !== "string") return undefined;
|
|
71
|
+
return {
|
|
72
|
+
label: choice["label"],
|
|
73
|
+
...(typeof choice["description"] === "string"
|
|
74
|
+
? { description: choice["description"] }
|
|
75
|
+
: {}),
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function askPrompt(value: unknown): PendingAsk["prompts"][number] | undefined {
|
|
80
|
+
const prompt = record(value);
|
|
81
|
+
if (!prompt || typeof prompt["title"] !== "string") return undefined;
|
|
82
|
+
return {
|
|
83
|
+
title: prompt["title"],
|
|
84
|
+
multiple: prompt["multiple"] === true,
|
|
85
|
+
choices: (Array.isArray(prompt["choices"]) ? prompt["choices"] : [])
|
|
86
|
+
.map(askChoice)
|
|
87
|
+
.filter((choice): choice is NonNullable<typeof choice> =>
|
|
88
|
+
Boolean(choice),
|
|
89
|
+
),
|
|
90
|
+
...(typeof prompt["body"] === "string" ? { body: prompt["body"] } : {}),
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function askCall(value: unknown): PendingAsk | undefined {
|
|
95
|
+
const part = record(value);
|
|
96
|
+
if (
|
|
97
|
+
!part ||
|
|
98
|
+
part["type"] !== "toolCall" ||
|
|
99
|
+
part["name"] !== "ask" ||
|
|
100
|
+
typeof part["id"] !== "string"
|
|
101
|
+
) {
|
|
102
|
+
return undefined;
|
|
103
|
+
}
|
|
104
|
+
const args = record(part["arguments"]);
|
|
105
|
+
if (!args) return undefined;
|
|
106
|
+
const prompts = (Array.isArray(args["prompts"]) ? args["prompts"] : [])
|
|
107
|
+
.map(askPrompt)
|
|
108
|
+
.filter((prompt): prompt is NonNullable<typeof prompt> => Boolean(prompt));
|
|
109
|
+
if (prompts.length === 0) return undefined;
|
|
110
|
+
return {
|
|
111
|
+
toolCallId: part["id"],
|
|
112
|
+
handoff: args["handoff"] === true,
|
|
113
|
+
prompts,
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function resolvedToolCallId(
|
|
118
|
+
message: Record<string, unknown>,
|
|
119
|
+
): string | undefined {
|
|
120
|
+
if (message["role"] !== "toolResult" && message["role"] !== "tool") {
|
|
121
|
+
return undefined;
|
|
122
|
+
}
|
|
123
|
+
const value = message["toolCallId"] ?? message["tool_call_id"];
|
|
124
|
+
return typeof value === "string" ? value : undefined;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function readSessionView(
|
|
49
128
|
path: string,
|
|
50
129
|
size: number,
|
|
51
|
-
): Promise<
|
|
130
|
+
): Promise<SessionView> {
|
|
52
131
|
const file = await open(path, "r");
|
|
53
132
|
let targetId: string | undefined;
|
|
54
|
-
|
|
55
|
-
|
|
133
|
+
let assistant: LatestAssistant | undefined;
|
|
134
|
+
let assistantDepth: number | undefined;
|
|
135
|
+
let ask: PendingAsk | undefined;
|
|
136
|
+
let depth = 0;
|
|
137
|
+
let user: LatestUser | undefined;
|
|
138
|
+
let userDepth: number | undefined;
|
|
139
|
+
const resolved = new Set<string>();
|
|
140
|
+
const result = (): SessionView => ({
|
|
141
|
+
...(assistant ? { assistant } : {}),
|
|
142
|
+
...(ask ? { ask } : {}),
|
|
143
|
+
...(user ? { user } : {}),
|
|
144
|
+
...(assistantDepth !== undefined && userDepth !== undefined
|
|
145
|
+
? { assistantAfterUser: assistantDepth < userDepth }
|
|
146
|
+
: {}),
|
|
147
|
+
});
|
|
148
|
+
const inspect = (line: Buffer): boolean => {
|
|
149
|
+
if (line.length === 0) return false;
|
|
56
150
|
let entry: Record<string, unknown>;
|
|
57
151
|
try {
|
|
58
152
|
entry = JSON.parse(line.toString("utf8")) as Record<string, unknown>;
|
|
59
153
|
} catch {
|
|
60
|
-
return
|
|
154
|
+
return false;
|
|
61
155
|
}
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
156
|
+
const id = entry["id"];
|
|
157
|
+
if (typeof id !== "string") return false;
|
|
158
|
+
targetId ??= id;
|
|
159
|
+
if (id !== targetId) return false;
|
|
160
|
+
const currentDepth = depth;
|
|
161
|
+
depth += 1;
|
|
162
|
+
const message = record(entry["message"]);
|
|
163
|
+
if (message) {
|
|
164
|
+
const resolvedId = resolvedToolCallId(message);
|
|
165
|
+
if (resolvedId) resolved.add(resolvedId);
|
|
166
|
+
if (!assistant) {
|
|
167
|
+
assistant = assistantFromMessage(id, message);
|
|
168
|
+
if (assistant) assistantDepth = currentDepth;
|
|
169
|
+
}
|
|
170
|
+
if (!user) {
|
|
171
|
+
user = userFromMessage(id, message);
|
|
172
|
+
if (user) userDepth = currentDepth;
|
|
173
|
+
}
|
|
174
|
+
if (
|
|
175
|
+
!ask &&
|
|
176
|
+
message["role"] === "assistant" &&
|
|
177
|
+
Array.isArray(message["content"])
|
|
178
|
+
) {
|
|
179
|
+
ask = [...message["content"]]
|
|
180
|
+
.reverse()
|
|
181
|
+
.map(askCall)
|
|
182
|
+
.find(
|
|
183
|
+
(candidate) =>
|
|
184
|
+
candidate !== undefined && !resolved.has(candidate.toolCallId),
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
const parentId = entry["parentId"];
|
|
189
|
+
if (typeof parentId !== "string") return true;
|
|
190
|
+
targetId = parentId;
|
|
191
|
+
return false;
|
|
70
192
|
};
|
|
71
193
|
|
|
72
194
|
try {
|
|
@@ -81,14 +203,15 @@ async function latestAssistant(
|
|
|
81
203
|
let lineEnd = data.length;
|
|
82
204
|
for (let index = data.length - 1; index >= 0; index -= 1) {
|
|
83
205
|
if (data[index] !== 0x0a) continue;
|
|
84
|
-
|
|
85
|
-
|
|
206
|
+
if (inspect(data.subarray(index + 1, lineEnd))) {
|
|
207
|
+
return result();
|
|
208
|
+
}
|
|
86
209
|
lineEnd = index;
|
|
87
210
|
}
|
|
88
211
|
partial = data.subarray(0, lineEnd);
|
|
89
212
|
}
|
|
90
|
-
|
|
91
|
-
return result
|
|
213
|
+
inspect(partial);
|
|
214
|
+
return result();
|
|
92
215
|
} finally {
|
|
93
216
|
await file.close();
|
|
94
217
|
}
|
|
@@ -97,23 +220,23 @@ async function latestAssistant(
|
|
|
97
220
|
export class SessionReader {
|
|
98
221
|
private readonly cache = new Map<
|
|
99
222
|
string,
|
|
100
|
-
{ mtimeMs: number; result:
|
|
223
|
+
{ mtimeMs: number; result: SessionView; size: number }
|
|
101
224
|
>();
|
|
102
225
|
|
|
103
|
-
async
|
|
104
|
-
if (!path) return
|
|
226
|
+
async view(path?: string): Promise<SessionView> {
|
|
227
|
+
if (!path) return {};
|
|
105
228
|
let metadata;
|
|
106
229
|
try {
|
|
107
230
|
metadata = await stat(path);
|
|
108
231
|
} catch (error) {
|
|
109
|
-
if ((error as NodeJS.ErrnoException).code === "ENOENT") return
|
|
232
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return {};
|
|
110
233
|
throw error;
|
|
111
234
|
}
|
|
112
235
|
const cached = this.cache.get(path);
|
|
113
236
|
if (cached?.size === metadata.size && cached.mtimeMs === metadata.mtimeMs) {
|
|
114
237
|
return cached.result;
|
|
115
238
|
}
|
|
116
|
-
const result = await
|
|
239
|
+
const result = await readSessionView(path, metadata.size);
|
|
117
240
|
this.cache.set(path, {
|
|
118
241
|
mtimeMs: metadata.mtimeMs,
|
|
119
242
|
result,
|
|
@@ -121,8 +244,13 @@ export class SessionReader {
|
|
|
121
244
|
});
|
|
122
245
|
return result;
|
|
123
246
|
}
|
|
247
|
+
|
|
248
|
+
async latest(path?: string): Promise<LatestAssistant | undefined> {
|
|
249
|
+
return (await this.view(path)).assistant;
|
|
250
|
+
}
|
|
124
251
|
}
|
|
125
252
|
|
|
126
253
|
export interface AssistantReader {
|
|
127
254
|
latest(path?: string): Promise<LatestAssistant | undefined>;
|
|
255
|
+
view(path?: string): Promise<SessionView>;
|
|
128
256
|
}
|
package/src/settlement.ts
CHANGED
|
@@ -2,16 +2,23 @@ import type {
|
|
|
2
2
|
ExtensionAPI,
|
|
3
3
|
ExtensionContext,
|
|
4
4
|
} from "@earendil-works/pi-coding-agent";
|
|
5
|
-
import {
|
|
5
|
+
import {
|
|
6
|
+
activityAttemptId,
|
|
7
|
+
activityExpectedUser,
|
|
8
|
+
activityTask,
|
|
9
|
+
isSettledStatus,
|
|
10
|
+
} from "./activity.js";
|
|
6
11
|
import { getAgent, getSnapshot, sessionPath } from "./herdr.js";
|
|
7
12
|
import type { HerdrConnection } from "./herdr-client.js";
|
|
8
13
|
import { injectAgentEvent } from "./messages.js";
|
|
9
|
-
import type { MonitorState } from "./monitor-state.js";
|
|
14
|
+
import type { MonitorState, WorkAttempt } from "./monitor-state.js";
|
|
10
15
|
import { type AssistantReader, SessionReader } from "./session-reader.js";
|
|
11
16
|
import type {
|
|
12
17
|
LatestAssistant,
|
|
13
18
|
MonitoredAgent,
|
|
14
19
|
PaneInfo,
|
|
20
|
+
PendingAsk,
|
|
21
|
+
SessionView,
|
|
15
22
|
SettledAgentStatus,
|
|
16
23
|
} from "./types.js";
|
|
17
24
|
|
|
@@ -20,13 +27,39 @@ interface SettlementLabels {
|
|
|
20
27
|
workspace?: string;
|
|
21
28
|
}
|
|
22
29
|
|
|
23
|
-
|
|
30
|
+
interface CollectedSettlement {
|
|
24
31
|
agent: PaneInfo;
|
|
32
|
+
ask?: PendingAsk;
|
|
25
33
|
labels: SettlementLabels;
|
|
26
34
|
reply?: LatestAssistant;
|
|
27
35
|
status: SettledAgentStatus;
|
|
28
36
|
}
|
|
29
37
|
|
|
38
|
+
interface CollectedSettlementWithSession extends CollectedSettlement {
|
|
39
|
+
session: SessionView;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface ClaimedSettlement extends CollectedSettlement {
|
|
43
|
+
blockedMessage?: string;
|
|
44
|
+
record: MonitoredAgent;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
interface SettlementClaim {
|
|
48
|
+
cleanup(): void;
|
|
49
|
+
reject(error: Error): void;
|
|
50
|
+
resolve(settlement: ClaimedSettlement): void;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
interface SettlementRetry {
|
|
54
|
+
attemptId: string | undefined;
|
|
55
|
+
count: number;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const SETTLEMENT_RETRY_DELAYS_MS = [250, 500, 1_000, 2_000, 4_000] as const;
|
|
59
|
+
const SETTLEMENT_RETRY_WINDOW_SECONDS = Math.ceil(
|
|
60
|
+
SETTLEMENT_RETRY_DELAYS_MS.reduce((total, delay) => total + delay, 0) / 1_000,
|
|
61
|
+
);
|
|
62
|
+
|
|
30
63
|
export interface SettlementRequest {
|
|
31
64
|
blockedMessage?: string;
|
|
32
65
|
record: MonitoredAgent;
|
|
@@ -57,9 +90,13 @@ export class SettlementCollector {
|
|
|
57
90
|
return this.reader.latest(sessionPath(panel));
|
|
58
91
|
}
|
|
59
92
|
|
|
93
|
+
view(panel: PaneInfo): Promise<SessionView> {
|
|
94
|
+
return this.reader.view(sessionPath(panel));
|
|
95
|
+
}
|
|
96
|
+
|
|
60
97
|
async collect(
|
|
61
98
|
record: MonitoredAgent,
|
|
62
|
-
): Promise<
|
|
99
|
+
): Promise<CollectedSettlementWithSession | undefined> {
|
|
63
100
|
const [current, snapshot] = await Promise.all([
|
|
64
101
|
getAgent(this.client, record.paneId),
|
|
65
102
|
getSnapshot(this.client),
|
|
@@ -71,7 +108,7 @@ export class SettlementCollector {
|
|
|
71
108
|
) {
|
|
72
109
|
return undefined;
|
|
73
110
|
}
|
|
74
|
-
const
|
|
111
|
+
const view = await this.reader.view(sessionPath(current));
|
|
75
112
|
const workspace = snapshot.workspaces.find(
|
|
76
113
|
(candidate) => candidate.workspace_id === current.workspace_id,
|
|
77
114
|
)?.label;
|
|
@@ -84,7 +121,11 @@ export class SettlementCollector {
|
|
|
84
121
|
...(workspace ? { workspace } : {}),
|
|
85
122
|
...(tab ? { tab } : {}),
|
|
86
123
|
},
|
|
87
|
-
...(
|
|
124
|
+
...(view.assistant ? { reply: view.assistant } : {}),
|
|
125
|
+
...(current.agent_status === "blocked" && view.ask
|
|
126
|
+
? { ask: view.ask }
|
|
127
|
+
: {}),
|
|
128
|
+
session: view,
|
|
88
129
|
status: current.agent_status,
|
|
89
130
|
};
|
|
90
131
|
}
|
|
@@ -97,6 +138,7 @@ export class SettlementReporter {
|
|
|
97
138
|
private readonly machine: string;
|
|
98
139
|
private readonly operatorPrefix: string;
|
|
99
140
|
private readonly reporting = new Set<string>();
|
|
141
|
+
private readonly claims = new Map<string, SettlementClaim>();
|
|
100
142
|
private readonly retries = new Map<string, NodeJS.Timeout>();
|
|
101
143
|
private readonly state: MonitorState;
|
|
102
144
|
|
|
@@ -121,18 +163,76 @@ export class SettlementReporter {
|
|
|
121
163
|
return this.collector.latest(panel);
|
|
122
164
|
}
|
|
123
165
|
|
|
166
|
+
view(panel: PaneInfo): Promise<SessionView> {
|
|
167
|
+
return this.collector.view(panel);
|
|
168
|
+
}
|
|
169
|
+
|
|
124
170
|
stop(): void {
|
|
125
171
|
this.reporting.clear();
|
|
172
|
+
for (const claim of this.claims.values()) {
|
|
173
|
+
claim.cleanup();
|
|
174
|
+
claim.reject(new Error("Shepherdr monitor stopped"));
|
|
175
|
+
}
|
|
176
|
+
this.claims.clear();
|
|
126
177
|
for (const timer of this.retries.values()) clearTimeout(timer);
|
|
127
178
|
this.retries.clear();
|
|
128
179
|
}
|
|
129
180
|
|
|
181
|
+
claim(attempt: WorkAttempt, signal: AbortSignal): Promise<ClaimedSettlement> {
|
|
182
|
+
signal.throwIfAborted();
|
|
183
|
+
if (this.claims.has(attempt.attemptId)) {
|
|
184
|
+
throw new Error(`work attempt ${attempt.attemptId} is already claimed`);
|
|
185
|
+
}
|
|
186
|
+
return new Promise<ClaimedSettlement>((resolve, reject) => {
|
|
187
|
+
const abort = () => {
|
|
188
|
+
const claim = this.claims.get(attempt.attemptId);
|
|
189
|
+
if (!claim) return;
|
|
190
|
+
this.claims.delete(attempt.attemptId);
|
|
191
|
+
claim.cleanup();
|
|
192
|
+
reject(
|
|
193
|
+
signal.reason instanceof Error
|
|
194
|
+
? signal.reason
|
|
195
|
+
: new Error("Shepherdr wait aborted"),
|
|
196
|
+
);
|
|
197
|
+
};
|
|
198
|
+
const claim: SettlementClaim = {
|
|
199
|
+
cleanup: () => signal.removeEventListener("abort", abort),
|
|
200
|
+
reject,
|
|
201
|
+
resolve,
|
|
202
|
+
};
|
|
203
|
+
this.claims.set(attempt.attemptId, claim);
|
|
204
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
releaseClaim(attempt: WorkAttempt | undefined, error: unknown): void {
|
|
209
|
+
if (!attempt) return;
|
|
210
|
+
this.releaseAttempt(attempt.attemptId, error);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
releaseAgentClaim(record: MonitoredAgent, error: unknown): void {
|
|
214
|
+
const attemptId = activityAttemptId(record.activity);
|
|
215
|
+
if (attemptId) this.releaseAttempt(attemptId, error);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
private releaseAttempt(attemptId: string, error: unknown): void {
|
|
219
|
+
const claim = this.claims.get(attemptId);
|
|
220
|
+
if (!claim) return;
|
|
221
|
+
this.claims.delete(attemptId);
|
|
222
|
+
claim.cleanup();
|
|
223
|
+
claim.reject(error instanceof Error ? error : new Error(String(error)));
|
|
224
|
+
}
|
|
225
|
+
|
|
130
226
|
async report(
|
|
131
227
|
lifecycle: SettlementLifecycle,
|
|
132
228
|
request: SettlementRequest,
|
|
133
|
-
|
|
229
|
+
retry?: SettlementRetry,
|
|
134
230
|
): Promise<void> {
|
|
135
231
|
const task = request.task ?? activityTask(request.record.activity);
|
|
232
|
+
const retryState = retry ?? {
|
|
233
|
+
attemptId: activityAttemptId(request.record.activity),
|
|
234
|
+
count: 0,
|
|
235
|
+
};
|
|
136
236
|
const key = `${lifecycle.generation}:${request.record.terminalId}`;
|
|
137
237
|
if (this.reporting.has(key)) return;
|
|
138
238
|
this.reporting.add(key);
|
|
@@ -141,24 +241,46 @@ export class SettlementReporter {
|
|
|
141
241
|
if (!settlement || !lifecycle.isCurrent()) return;
|
|
142
242
|
const current = this.state.byPane(settlement.agent.pane_id);
|
|
143
243
|
if (!current || current.terminalId !== request.record.terminalId) return;
|
|
244
|
+
if (activityTask(current.activity) !== task) return;
|
|
245
|
+
if (activityAttemptId(current.activity) !== retryState.attemptId) return;
|
|
246
|
+
const retryRequest = task ? { ...request, task } : request;
|
|
247
|
+
const expectedUser = activityExpectedUser(current.activity);
|
|
248
|
+
// Pi persists expanded skills/templates, not the submitted command text.
|
|
249
|
+
if (
|
|
250
|
+
expectedUser &&
|
|
251
|
+
(settlement.session.assistantAfterUser !== true ||
|
|
252
|
+
!settlement.session.user ||
|
|
253
|
+
settlement.session.user.id === expectedUser.after)
|
|
254
|
+
) {
|
|
255
|
+
if (!this.retry(lifecycle, retryRequest, retryState)) {
|
|
256
|
+
this.failReconciliation(
|
|
257
|
+
lifecycle,
|
|
258
|
+
current,
|
|
259
|
+
"the submitted user message and reply were not persisted",
|
|
260
|
+
);
|
|
261
|
+
}
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
144
264
|
const newReply =
|
|
145
265
|
settlement.reply?.id !== current.lastAssistantId
|
|
146
266
|
? settlement.reply
|
|
147
267
|
: undefined;
|
|
148
|
-
if (request.requireNewReply && !newReply)
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
268
|
+
if (request.requireNewReply && !newReply && !settlement.ask) {
|
|
269
|
+
if (!this.retry(lifecycle, retryRequest, retryState)) {
|
|
270
|
+
this.failReconciliation(
|
|
271
|
+
lifecycle,
|
|
272
|
+
current,
|
|
273
|
+
"the new assistant reply was not persisted",
|
|
274
|
+
);
|
|
275
|
+
}
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
const blockedMessage =
|
|
279
|
+
settlement.status === request.status
|
|
280
|
+
? request.blockedMessage
|
|
281
|
+
: undefined;
|
|
282
|
+
const attemptId = activityAttemptId(current.activity);
|
|
283
|
+
const claim = attemptId ? this.claims.get(attemptId) : undefined;
|
|
162
284
|
if (
|
|
163
285
|
this.state.complete(
|
|
164
286
|
current.terminalId,
|
|
@@ -169,14 +291,57 @@ export class SettlementReporter {
|
|
|
169
291
|
) {
|
|
170
292
|
this.clearRetry(current.terminalId);
|
|
171
293
|
this.persist();
|
|
294
|
+
if (claim && attemptId) {
|
|
295
|
+
this.claims.delete(attemptId);
|
|
296
|
+
claim.cleanup();
|
|
297
|
+
const {
|
|
298
|
+
reply: _latestReply,
|
|
299
|
+
session: _session,
|
|
300
|
+
...claimedSettlement
|
|
301
|
+
} = settlement;
|
|
302
|
+
claim.resolve({
|
|
303
|
+
...claimedSettlement,
|
|
304
|
+
record: current,
|
|
305
|
+
...(blockedMessage ? { blockedMessage } : {}),
|
|
306
|
+
...(newReply ? { reply: newReply } : {}),
|
|
307
|
+
});
|
|
308
|
+
} else {
|
|
309
|
+
injectAgentEvent(this.pi, lifecycle.context, {
|
|
310
|
+
agent: settlement.agent,
|
|
311
|
+
agentToolName: "agents",
|
|
312
|
+
...(settlement.ask ? { ask: settlement.ask } : {}),
|
|
313
|
+
machine: this.machine,
|
|
314
|
+
operatorPrefix: this.operatorPrefix,
|
|
315
|
+
...(blockedMessage ? { blockedMessage } : {}),
|
|
316
|
+
labels: settlement.labels,
|
|
317
|
+
record: current,
|
|
318
|
+
...(newReply ? { reply: newReply } : {}),
|
|
319
|
+
status: settlement.status,
|
|
320
|
+
});
|
|
321
|
+
}
|
|
172
322
|
}
|
|
173
323
|
} catch (error) {
|
|
174
|
-
lifecycle.
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
324
|
+
if (!lifecycle.isCurrent()) return;
|
|
325
|
+
if (retryState.count === 0) {
|
|
326
|
+
lifecycle.context.ui.notify(
|
|
327
|
+
`Could not collect ${request.record.name ?? request.record.paneId}: ${error instanceof Error ? error.message : String(error)}`,
|
|
328
|
+
"warning",
|
|
329
|
+
);
|
|
330
|
+
}
|
|
331
|
+
const retryRequest = task ? { ...request, task } : request;
|
|
332
|
+
if (!this.retry(lifecycle, retryRequest, retryState)) {
|
|
333
|
+
const current = this.state.byTerminal(request.record.terminalId);
|
|
334
|
+
if (
|
|
335
|
+
current &&
|
|
336
|
+
activityTask(current.activity) === task &&
|
|
337
|
+
activityAttemptId(current.activity) === retryState.attemptId
|
|
338
|
+
) {
|
|
339
|
+
this.failReconciliation(
|
|
340
|
+
lifecycle,
|
|
341
|
+
current,
|
|
342
|
+
"the settlement snapshot remained unavailable",
|
|
343
|
+
);
|
|
344
|
+
}
|
|
180
345
|
}
|
|
181
346
|
} finally {
|
|
182
347
|
this.reporting.delete(key);
|
|
@@ -192,22 +357,52 @@ export class SettlementReporter {
|
|
|
192
357
|
private retry(
|
|
193
358
|
lifecycle: SettlementLifecycle,
|
|
194
359
|
request: SettlementRequest,
|
|
195
|
-
|
|
360
|
+
retry: SettlementRetry,
|
|
361
|
+
): boolean {
|
|
362
|
+
const delay = SETTLEMENT_RETRY_DELAYS_MS[retry.count];
|
|
363
|
+
if (delay === undefined) return false;
|
|
364
|
+
const current = this.state.byTerminal(request.record.terminalId);
|
|
196
365
|
if (
|
|
197
366
|
!lifecycle.isCurrent() ||
|
|
198
|
-
!
|
|
199
|
-
|
|
367
|
+
!current ||
|
|
368
|
+
activityTask(current.activity) !==
|
|
369
|
+
(request.task ?? activityTask(request.record.activity)) ||
|
|
370
|
+
activityAttemptId(current.activity) !== retry.attemptId
|
|
200
371
|
) {
|
|
201
|
-
return;
|
|
372
|
+
return false;
|
|
202
373
|
}
|
|
374
|
+
if (this.retries.has(request.record.terminalId)) return true;
|
|
203
375
|
const timer = setTimeout(() => {
|
|
204
376
|
this.retries.delete(request.record.terminalId);
|
|
205
377
|
if (!lifecycle.isCurrent()) return;
|
|
206
378
|
const current = this.state.byTerminal(request.record.terminalId);
|
|
207
379
|
if (!current) return;
|
|
208
|
-
void this.report(
|
|
209
|
-
|
|
380
|
+
void this.report(
|
|
381
|
+
lifecycle,
|
|
382
|
+
{ ...request, record: current },
|
|
383
|
+
{ ...retry, count: retry.count + 1 },
|
|
384
|
+
);
|
|
385
|
+
}, delay);
|
|
210
386
|
this.retries.set(request.record.terminalId, timer);
|
|
211
387
|
timer.unref();
|
|
388
|
+
return true;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
private failReconciliation(
|
|
392
|
+
lifecycle: SettlementLifecycle,
|
|
393
|
+
record: MonitoredAgent,
|
|
394
|
+
reason: string,
|
|
395
|
+
): void {
|
|
396
|
+
this.clearRetry(record.terminalId);
|
|
397
|
+
const message =
|
|
398
|
+
(record.name ?? record.paneId) +
|
|
399
|
+
" settled, but " +
|
|
400
|
+
reason +
|
|
401
|
+
" after " +
|
|
402
|
+
SETTLEMENT_RETRY_WINDOW_SECONDS +
|
|
403
|
+
" seconds";
|
|
404
|
+
const attemptId = activityAttemptId(record.activity);
|
|
405
|
+
if (attemptId) this.releaseAttempt(attemptId, new Error(message));
|
|
406
|
+
lifecycle.context.ui.notify(message, "warning");
|
|
212
407
|
}
|
|
213
408
|
}
|