@howaboua/pi-shepherdr 0.1.2 → 0.1.3
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 +34 -0
- package/README.md +54 -51
- package/biome.json +1 -1
- package/changelog.ts +337 -0
- package/index.ts +93 -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 +178 -0
- package/src/herdr.ts +13 -1
- package/src/launch.ts +62 -8
- package/src/machine-menu.ts +158 -0
- package/src/messages.ts +105 -4
- 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
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import type { AgentFleet } from "./fleet.js";
|
|
3
|
+
import {
|
|
4
|
+
isMachineName,
|
|
5
|
+
LOCAL_MACHINE,
|
|
6
|
+
readMachinesConfig,
|
|
7
|
+
writeMachinesConfig,
|
|
8
|
+
} from "./machines-config.js";
|
|
9
|
+
|
|
10
|
+
function parseSshArguments(value: string): string[] {
|
|
11
|
+
const parts: string[] = [];
|
|
12
|
+
let current = "";
|
|
13
|
+
let quote: "'" | '"' | undefined;
|
|
14
|
+
let escaped = false;
|
|
15
|
+
let started = false;
|
|
16
|
+
for (const character of value) {
|
|
17
|
+
if (escaped) {
|
|
18
|
+
current += character;
|
|
19
|
+
escaped = false;
|
|
20
|
+
started = true;
|
|
21
|
+
continue;
|
|
22
|
+
}
|
|
23
|
+
if (character === "\\" && quote !== "'") {
|
|
24
|
+
escaped = true;
|
|
25
|
+
started = true;
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
if (quote) {
|
|
29
|
+
if (character === quote) quote = undefined;
|
|
30
|
+
else current += character;
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
if (character === "'" || character === '"') {
|
|
34
|
+
quote = character;
|
|
35
|
+
started = true;
|
|
36
|
+
} else if (/\s/.test(character)) {
|
|
37
|
+
if (started) {
|
|
38
|
+
parts.push(current);
|
|
39
|
+
current = "";
|
|
40
|
+
started = false;
|
|
41
|
+
}
|
|
42
|
+
} else {
|
|
43
|
+
current += character;
|
|
44
|
+
started = true;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
if (quote) throw new Error("SSH arguments contain an unclosed quote");
|
|
48
|
+
if (escaped) throw new Error("SSH arguments end with an incomplete escape");
|
|
49
|
+
if (started) parts.push(current);
|
|
50
|
+
if (parts.length === 0) throw new Error("SSH target is required");
|
|
51
|
+
const target = parts.pop()!;
|
|
52
|
+
return [...parts, "--", target];
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export async function showMachineMenu(
|
|
56
|
+
fleet: AgentFleet,
|
|
57
|
+
ctx: ExtensionContext,
|
|
58
|
+
): Promise<void> {
|
|
59
|
+
const config = await readMachinesConfig().catch((error) => {
|
|
60
|
+
ctx.ui.notify(
|
|
61
|
+
`Shepherdr machine config is invalid: ${error instanceof Error ? error.message : String(error)}`,
|
|
62
|
+
"error",
|
|
63
|
+
);
|
|
64
|
+
return undefined;
|
|
65
|
+
});
|
|
66
|
+
if (!config) return;
|
|
67
|
+
const statuses = fleet.isActive()
|
|
68
|
+
? fleet.statuses()
|
|
69
|
+
: Object.keys(config.machines).map((name) => ({
|
|
70
|
+
local: false,
|
|
71
|
+
name,
|
|
72
|
+
status: "unavailable" as const,
|
|
73
|
+
}));
|
|
74
|
+
const selected = await ctx.ui.select("Shepherdr machines", [
|
|
75
|
+
"Add machine",
|
|
76
|
+
...statuses
|
|
77
|
+
.filter((machine) => !machine.local)
|
|
78
|
+
.map(
|
|
79
|
+
(machine) =>
|
|
80
|
+
`${machine.status === "connected" ? "●" : machine.status === "connecting" ? "◌" : "○"} ${machine.name} · ${machine.status}`,
|
|
81
|
+
),
|
|
82
|
+
]);
|
|
83
|
+
if (!selected) return;
|
|
84
|
+
if (selected === "Add machine") {
|
|
85
|
+
await addMachine(ctx, fleet);
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
const name = selected.slice(2).split(" · ", 1)[0];
|
|
89
|
+
if (!name) return;
|
|
90
|
+
const status = statuses.find((machine) => machine.name === name);
|
|
91
|
+
const action = await ctx.ui.select(name, [
|
|
92
|
+
...(status?.status !== "connected" ? ["Connect"] : []),
|
|
93
|
+
"Remove",
|
|
94
|
+
]);
|
|
95
|
+
if (action === "Connect") {
|
|
96
|
+
if (!fleet.isActive()) {
|
|
97
|
+
ctx.ui.notify("Run /herdr to activate agents first", "warning");
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
ctx.ui.notify(fleet.connect(name), "info");
|
|
101
|
+
} else if (action === "Remove") {
|
|
102
|
+
const confirmed = await ctx.ui.confirm(
|
|
103
|
+
`Remove ${name}?`,
|
|
104
|
+
"The remote Shepherdr helper will remain available for other controllers",
|
|
105
|
+
);
|
|
106
|
+
if (!confirmed) return;
|
|
107
|
+
delete config.machines[name];
|
|
108
|
+
await writeMachinesConfig(config);
|
|
109
|
+
await fleet.reload();
|
|
110
|
+
ctx.ui.notify(`Removed ${name}`, "info");
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async function addMachine(
|
|
115
|
+
ctx: ExtensionContext,
|
|
116
|
+
fleet: AgentFleet,
|
|
117
|
+
): Promise<void> {
|
|
118
|
+
const name = (await ctx.ui.input("Machine name", "desktop"))?.trim();
|
|
119
|
+
if (!name) return;
|
|
120
|
+
if (!isMachineName(name)) {
|
|
121
|
+
ctx.ui.notify("Machine name must match [a-z][a-z0-9_-]{0,31}", "error");
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
const ssh = (
|
|
125
|
+
await ctx.ui.input("SSH options and target (target last)", name)
|
|
126
|
+
)?.trim();
|
|
127
|
+
if (!ssh) return;
|
|
128
|
+
let sshArguments: string[];
|
|
129
|
+
try {
|
|
130
|
+
sshArguments = parseSshArguments(ssh);
|
|
131
|
+
} catch (error) {
|
|
132
|
+
ctx.ui.notify(
|
|
133
|
+
error instanceof Error ? error.message : String(error),
|
|
134
|
+
"error",
|
|
135
|
+
);
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
const session = (
|
|
139
|
+
await ctx.ui.input("Herdr session", "default (leave blank)")
|
|
140
|
+
)?.trim();
|
|
141
|
+
const config = await readMachinesConfig();
|
|
142
|
+
if (name === LOCAL_MACHINE || Object.hasOwn(config.machines, name)) {
|
|
143
|
+
ctx.ui.notify(`Machine ${name} already exists`, "error");
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
config.machines[name] = {
|
|
147
|
+
command: ["ssh", "-o", "BatchMode=yes", ...sshArguments],
|
|
148
|
+
herdr: "herdr",
|
|
149
|
+
node: "node",
|
|
150
|
+
...(session && session !== "default (leave blank)" ? { session } : {}),
|
|
151
|
+
};
|
|
152
|
+
const path = await writeMachinesConfig(config);
|
|
153
|
+
await fleet.reload();
|
|
154
|
+
ctx.ui.notify(
|
|
155
|
+
`Added ${name} in ${path}; Shepherdr manages ~/.pi/agent/shepherdr.mjs remotely`,
|
|
156
|
+
"info",
|
|
157
|
+
);
|
|
158
|
+
}
|
package/src/messages.ts
CHANGED
|
@@ -9,6 +9,7 @@ import type {
|
|
|
9
9
|
LatestAssistant,
|
|
10
10
|
MonitoredAgent,
|
|
11
11
|
PaneInfo,
|
|
12
|
+
PendingAsk,
|
|
12
13
|
SettledAgentStatus,
|
|
13
14
|
} from "./types.js";
|
|
14
15
|
|
|
@@ -33,6 +34,8 @@ interface AgentEventLabels {
|
|
|
33
34
|
|
|
34
35
|
interface AgentEventOptions {
|
|
35
36
|
agent: PaneInfo;
|
|
37
|
+
agentToolName: string;
|
|
38
|
+
ask?: PendingAsk;
|
|
36
39
|
blockedMessage?: string;
|
|
37
40
|
labels: AgentEventLabels;
|
|
38
41
|
machine: string;
|
|
@@ -43,6 +46,7 @@ interface AgentEventOptions {
|
|
|
43
46
|
}
|
|
44
47
|
|
|
45
48
|
interface AgentEventDetails {
|
|
49
|
+
ask?: PendingAsk;
|
|
46
50
|
blockedOn?: string;
|
|
47
51
|
cwd?: string;
|
|
48
52
|
machine: string;
|
|
@@ -55,6 +59,54 @@ interface AgentEventDetails {
|
|
|
55
59
|
workspace?: string;
|
|
56
60
|
}
|
|
57
61
|
|
|
62
|
+
function eventAsk(value: unknown): PendingAsk | undefined {
|
|
63
|
+
if (typeof value !== "object" || value === null) return undefined;
|
|
64
|
+
const record = value as Record<string, unknown>;
|
|
65
|
+
if (
|
|
66
|
+
typeof record["toolCallId"] !== "string" ||
|
|
67
|
+
typeof record["handoff"] !== "boolean" ||
|
|
68
|
+
!Array.isArray(record["prompts"])
|
|
69
|
+
) {
|
|
70
|
+
return undefined;
|
|
71
|
+
}
|
|
72
|
+
const prompts: PendingAsk["prompts"] = [];
|
|
73
|
+
for (const value of record["prompts"]) {
|
|
74
|
+
if (typeof value !== "object" || value === null) return undefined;
|
|
75
|
+
const prompt = value as Record<string, unknown>;
|
|
76
|
+
if (
|
|
77
|
+
typeof prompt["title"] !== "string" ||
|
|
78
|
+
typeof prompt["multiple"] !== "boolean" ||
|
|
79
|
+
!Array.isArray(prompt["choices"])
|
|
80
|
+
) {
|
|
81
|
+
return undefined;
|
|
82
|
+
}
|
|
83
|
+
const choices: PendingAsk["prompts"][number]["choices"] = [];
|
|
84
|
+
for (const value of prompt["choices"]) {
|
|
85
|
+
if (typeof value !== "object" || value === null) return undefined;
|
|
86
|
+
const choice = value as Record<string, unknown>;
|
|
87
|
+
if (typeof choice["label"] !== "string") return undefined;
|
|
88
|
+
choices.push({
|
|
89
|
+
label: choice["label"],
|
|
90
|
+
...(typeof choice["description"] === "string"
|
|
91
|
+
? { description: choice["description"] }
|
|
92
|
+
: {}),
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
prompts.push({
|
|
96
|
+
title: prompt["title"],
|
|
97
|
+
multiple: prompt["multiple"],
|
|
98
|
+
choices,
|
|
99
|
+
...(typeof prompt["body"] === "string" ? { body: prompt["body"] } : {}),
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
if (prompts.length === 0) return undefined;
|
|
103
|
+
return {
|
|
104
|
+
toolCallId: record["toolCallId"],
|
|
105
|
+
handoff: record["handoff"],
|
|
106
|
+
prompts,
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
58
110
|
function boundedVoicePrompt(prompt: string, truncationNotice: string): string {
|
|
59
111
|
const encoder = new TextEncoder();
|
|
60
112
|
const bytes = encoder.encode(prompt);
|
|
@@ -88,6 +140,11 @@ function agentVoicePrompt(details: AgentEventDetails): string {
|
|
|
88
140
|
"The blocked worker details above were truncated. Tell the user and ask whether they would like the rest.";
|
|
89
141
|
if (details.blockedOn?.trim())
|
|
90
142
|
lines.push(`Reason:\n${details.blockedOn.trim()}`);
|
|
143
|
+
if (details.ask) {
|
|
144
|
+
lines.push(
|
|
145
|
+
`Questions:\n${details.ask.prompts.map((prompt) => prompt.title).join(", ")}`,
|
|
146
|
+
);
|
|
147
|
+
}
|
|
91
148
|
} else {
|
|
92
149
|
instruction =
|
|
93
150
|
details.state === "failed"
|
|
@@ -123,19 +180,21 @@ function operatorCommand(operatorPrefix: string, command: string): string {
|
|
|
123
180
|
}
|
|
124
181
|
|
|
125
182
|
function blockedOperatorHint(
|
|
183
|
+
agentToolName: string,
|
|
126
184
|
machine: string,
|
|
127
185
|
operatorPrefix: string,
|
|
128
186
|
paneId: string,
|
|
129
187
|
): string {
|
|
130
|
-
return `Inspect first with ${operatorCommand(operatorPrefix, `agent read ${paneId} --source visible`)}; respond through
|
|
188
|
+
return `Inspect first with ${operatorCommand(operatorPrefix, `agent read ${paneId} --source visible`)}; respond through ${agentToolName} with machine=${JSON.stringify(machine)}, or use ${operatorCommand(operatorPrefix, `agent send-keys ${paneId} <keys>`)} for interactive controls.`;
|
|
131
189
|
}
|
|
132
190
|
|
|
133
191
|
function failedOperatorHint(
|
|
192
|
+
agentToolName: string,
|
|
134
193
|
machine: string,
|
|
135
194
|
operatorPrefix: string,
|
|
136
195
|
paneId: string,
|
|
137
196
|
): string {
|
|
138
|
-
return `Inspect with ${operatorCommand(operatorPrefix, `agent read ${paneId} --source recent-unwrapped --lines 80`)} and assess the failure. If this task has not already been retried and one simple corrective prompt could recover it, try once through
|
|
197
|
+
return `Inspect with ${operatorCommand(operatorPrefix, `agent read ${paneId} --source recent-unwrapped --lines 80`)} and assess the failure. If this task has not already been retried and one simple corrective prompt could recover it, try once through ${agentToolName} with machine=${JSON.stringify(machine)}. If it fails again or the setup looks broken, stop retrying and tell the user.`;
|
|
139
198
|
}
|
|
140
199
|
|
|
141
200
|
function eventDetails(value: unknown): AgentEventDetails | undefined {
|
|
@@ -155,11 +214,13 @@ function eventDetails(value: unknown): AgentEventDetails | undefined {
|
|
|
155
214
|
typeof details[field] === "string"
|
|
156
215
|
? { [field]: details[field] as string }
|
|
157
216
|
: {};
|
|
217
|
+
const ask = eventAsk(details["ask"]);
|
|
158
218
|
return {
|
|
159
219
|
machine:
|
|
160
220
|
typeof details["machine"] === "string" ? details["machine"] : "local",
|
|
161
221
|
paneId: details["paneId"],
|
|
162
222
|
state: details["state"],
|
|
223
|
+
...(ask ? { ask } : {}),
|
|
163
224
|
...optional("blockedOn"),
|
|
164
225
|
...optional("cwd"),
|
|
165
226
|
...optional("name"),
|
|
@@ -176,6 +237,8 @@ function agentEvent(options: AgentEventOptions): {
|
|
|
176
237
|
} {
|
|
177
238
|
const {
|
|
178
239
|
agent,
|
|
240
|
+
agentToolName,
|
|
241
|
+
ask,
|
|
179
242
|
blockedMessage,
|
|
180
243
|
labels,
|
|
181
244
|
machine,
|
|
@@ -206,14 +269,19 @@ function agentEvent(options: AgentEventOptions): {
|
|
|
206
269
|
if (blockedMessage) {
|
|
207
270
|
lines.push(`<blocked_on>${xml(blockedMessage)}</blocked_on>`);
|
|
208
271
|
}
|
|
272
|
+
if (blocked && ask) {
|
|
273
|
+
lines.push(
|
|
274
|
+
`<ask>${xml(JSON.stringify({ handoff: ask.handoff, prompts: ask.prompts }))}</ask>`,
|
|
275
|
+
);
|
|
276
|
+
}
|
|
209
277
|
if (blocked) {
|
|
210
278
|
lines.push(
|
|
211
|
-
`<operator_hint>${xml(blockedOperatorHint(machine, operatorPrefix, agent.pane_id))}</operator_hint>`,
|
|
279
|
+
`<operator_hint>${xml(blockedOperatorHint(agentToolName, machine, operatorPrefix, agent.pane_id))}</operator_hint>`,
|
|
212
280
|
);
|
|
213
281
|
}
|
|
214
282
|
if (failed) {
|
|
215
283
|
lines.push(
|
|
216
|
-
`<operator_hint>${xml(failedOperatorHint(machine, operatorPrefix, agent.pane_id))}</operator_hint>`,
|
|
284
|
+
`<operator_hint>${xml(failedOperatorHint(agentToolName, machine, operatorPrefix, agent.pane_id))}</operator_hint>`,
|
|
217
285
|
);
|
|
218
286
|
}
|
|
219
287
|
if (reply) lines.push(`<response>${xml(reply.text)}</response>`);
|
|
@@ -225,6 +293,7 @@ function agentEvent(options: AgentEventOptions): {
|
|
|
225
293
|
machine,
|
|
226
294
|
paneId: agent.pane_id,
|
|
227
295
|
state: blocked ? "blocked" : failed ? "failed" : "finished",
|
|
296
|
+
...(blocked && ask ? { ask } : {}),
|
|
228
297
|
...(record.name ? { name: record.name } : {}),
|
|
229
298
|
...(cwd ? { cwd } : {}),
|
|
230
299
|
...(labels.workspace ? { workspace: labels.workspace } : {}),
|
|
@@ -308,6 +377,38 @@ export function registerAgentEventRenderer(pi: ExtensionAPI): void {
|
|
|
308
377
|
0,
|
|
309
378
|
),
|
|
310
379
|
);
|
|
380
|
+
if (details.ask) {
|
|
381
|
+
box.addChild(
|
|
382
|
+
new Text(
|
|
383
|
+
theme.fg(
|
|
384
|
+
"muted",
|
|
385
|
+
`Questions: ${details.ask.prompts.map((prompt) => prompt.title).join(", ")}`,
|
|
386
|
+
),
|
|
387
|
+
0,
|
|
388
|
+
0,
|
|
389
|
+
),
|
|
390
|
+
);
|
|
391
|
+
if (expanded) {
|
|
392
|
+
for (const prompt of details.ask.prompts) {
|
|
393
|
+
box.addChild(new Spacer(1));
|
|
394
|
+
box.addChild(new Text(theme.fg("muted", prompt.title), 0, 0));
|
|
395
|
+
if (prompt.body) {
|
|
396
|
+
box.addChild(
|
|
397
|
+
new Markdown(prompt.body, 0, 0, getMarkdownTheme()),
|
|
398
|
+
);
|
|
399
|
+
}
|
|
400
|
+
if (prompt.choices.length > 0) {
|
|
401
|
+
box.addChild(
|
|
402
|
+
new Text(
|
|
403
|
+
`Choices: ${prompt.choices.map((choice) => choice.label).join(", ")}`,
|
|
404
|
+
0,
|
|
405
|
+
0,
|
|
406
|
+
),
|
|
407
|
+
);
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
}
|
|
311
412
|
}
|
|
312
413
|
if (expanded && details?.task) {
|
|
313
414
|
box.addChild(new Spacer(1));
|
package/src/monitor-record.ts
CHANGED
|
@@ -16,6 +16,18 @@ function optionalString(
|
|
|
16
16
|
: false;
|
|
17
17
|
}
|
|
18
18
|
|
|
19
|
+
function optionalNullableString(
|
|
20
|
+
value: Record<string, unknown>,
|
|
21
|
+
field: string,
|
|
22
|
+
): string | null | undefined | false {
|
|
23
|
+
const candidate = value[field];
|
|
24
|
+
return candidate === undefined ||
|
|
25
|
+
candidate === null ||
|
|
26
|
+
typeof candidate === "string"
|
|
27
|
+
? candidate
|
|
28
|
+
: false;
|
|
29
|
+
}
|
|
30
|
+
|
|
19
31
|
function stableActivity(value: unknown): StableAgentActivity | undefined {
|
|
20
32
|
if (typeof value !== "object" || value === null) return undefined;
|
|
21
33
|
const activity = value as Record<string, unknown>;
|
|
@@ -28,9 +40,24 @@ function stableActivity(value: unknown): StableAgentActivity | undefined {
|
|
|
28
40
|
}
|
|
29
41
|
if (activity["phase"] !== "working") return undefined;
|
|
30
42
|
const task = optionalString(activity, "task");
|
|
43
|
+
const attemptId = optionalString(activity, "attemptId");
|
|
44
|
+
const expectedUserAfter = optionalNullableString(
|
|
45
|
+
activity,
|
|
46
|
+
"expectedUserAfter",
|
|
47
|
+
);
|
|
31
48
|
return task === false
|
|
32
49
|
? undefined
|
|
33
|
-
:
|
|
50
|
+
: attemptId === false
|
|
51
|
+
? undefined
|
|
52
|
+
: expectedUserAfter === false ||
|
|
53
|
+
(expectedUserAfter !== undefined && !task)
|
|
54
|
+
? undefined
|
|
55
|
+
: {
|
|
56
|
+
phase: "working",
|
|
57
|
+
...(attemptId ? { attemptId } : {}),
|
|
58
|
+
...(expectedUserAfter !== undefined ? { expectedUserAfter } : {}),
|
|
59
|
+
...(task ? { task } : {}),
|
|
60
|
+
};
|
|
34
61
|
}
|
|
35
62
|
|
|
36
63
|
function parsedActivity(value: unknown): AgentActivity | undefined {
|
|
@@ -39,10 +66,15 @@ function parsedActivity(value: unknown): AgentActivity | undefined {
|
|
|
39
66
|
if (typeof value !== "object" || value === null) return undefined;
|
|
40
67
|
const activity = value as Record<string, unknown>;
|
|
41
68
|
const previous = stableActivity(activity["previous"]);
|
|
69
|
+
const expectedUserAfter = optionalNullableString(
|
|
70
|
+
activity,
|
|
71
|
+
"expectedUserAfter",
|
|
72
|
+
);
|
|
42
73
|
if (
|
|
43
74
|
activity["phase"] !== "submitting" ||
|
|
44
75
|
typeof activity["attemptId"] !== "string" ||
|
|
45
76
|
typeof activity["task"] !== "string" ||
|
|
77
|
+
expectedUserAfter === false ||
|
|
46
78
|
!previous
|
|
47
79
|
) {
|
|
48
80
|
return undefined;
|
|
@@ -52,6 +84,7 @@ function parsedActivity(value: unknown): AgentActivity | undefined {
|
|
|
52
84
|
phase: "submitting",
|
|
53
85
|
previous,
|
|
54
86
|
task: activity["task"],
|
|
87
|
+
...(expectedUserAfter !== undefined ? { expectedUserAfter } : {}),
|
|
55
88
|
};
|
|
56
89
|
}
|
|
57
90
|
|
package/src/monitor-state.ts
CHANGED
|
@@ -34,6 +34,7 @@ interface CompletionCandidate {
|
|
|
34
34
|
interface ReconcileResult {
|
|
35
35
|
changed: boolean;
|
|
36
36
|
completions: CompletionCandidate[];
|
|
37
|
+
removed: MonitoredAgent[];
|
|
37
38
|
}
|
|
38
39
|
|
|
39
40
|
interface StatusResult {
|
|
@@ -85,10 +86,12 @@ export class MonitorState {
|
|
|
85
86
|
watch(
|
|
86
87
|
panel: PaneInfo,
|
|
87
88
|
lastAssistantId?: string,
|
|
89
|
+
reportSettled = true,
|
|
88
90
|
): { record: MonitoredAgent; reportCurrent: boolean } {
|
|
89
91
|
const existing =
|
|
90
92
|
this.byTerminal(panel.terminal_id) ?? this.byPane(panel.pane_id);
|
|
91
93
|
const reportCurrent =
|
|
94
|
+
reportSettled &&
|
|
92
95
|
!existing &&
|
|
93
96
|
(panel.agent_status === "done" || panel.agent_status === "blocked");
|
|
94
97
|
const activity = reportCurrent
|
|
@@ -114,7 +117,11 @@ export class MonitorState {
|
|
|
114
117
|
return record;
|
|
115
118
|
}
|
|
116
119
|
|
|
117
|
-
beginWork(
|
|
120
|
+
beginWork(
|
|
121
|
+
paneId: string,
|
|
122
|
+
task: string,
|
|
123
|
+
expectedUserAfter?: string | null,
|
|
124
|
+
): WorkAttempt | undefined {
|
|
118
125
|
const record = this.byPane(paneId);
|
|
119
126
|
if (!record) return undefined;
|
|
120
127
|
if (record.activity.phase === "submitting") {
|
|
@@ -133,6 +140,7 @@ export class MonitorState {
|
|
|
133
140
|
phase: "submitting",
|
|
134
141
|
previous: record.activity,
|
|
135
142
|
task,
|
|
143
|
+
...(expectedUserAfter !== undefined ? { expectedUserAfter } : {}),
|
|
136
144
|
},
|
|
137
145
|
});
|
|
138
146
|
return attempt;
|
|
@@ -149,7 +157,14 @@ export class MonitorState {
|
|
|
149
157
|
}
|
|
150
158
|
this.agents.set(record.terminalId, {
|
|
151
159
|
...record,
|
|
152
|
-
activity: {
|
|
160
|
+
activity: {
|
|
161
|
+
attemptId: record.activity.attemptId,
|
|
162
|
+
...(record.activity.expectedUserAfter !== undefined
|
|
163
|
+
? { expectedUserAfter: record.activity.expectedUserAfter }
|
|
164
|
+
: {}),
|
|
165
|
+
phase: "working",
|
|
166
|
+
task: record.activity.task,
|
|
167
|
+
},
|
|
153
168
|
});
|
|
154
169
|
return true;
|
|
155
170
|
}
|
|
@@ -175,8 +190,18 @@ export class MonitorState {
|
|
|
175
190
|
if (!record) return { changed: false };
|
|
176
191
|
if (status === "working") {
|
|
177
192
|
const task = activityTask(record.activity);
|
|
193
|
+
const attemptId =
|
|
194
|
+
record.activity.phase === "settled"
|
|
195
|
+
? undefined
|
|
196
|
+
: record.activity.attemptId;
|
|
197
|
+
const expectedUserAfter =
|
|
198
|
+
record.activity.phase === "settled"
|
|
199
|
+
? undefined
|
|
200
|
+
: record.activity.expectedUserAfter;
|
|
178
201
|
const next: AgentActivity = {
|
|
179
202
|
phase: "working",
|
|
203
|
+
...(attemptId ? { attemptId } : {}),
|
|
204
|
+
...(expectedUserAfter !== undefined ? { expectedUserAfter } : {}),
|
|
180
205
|
...(task ? { task } : {}),
|
|
181
206
|
};
|
|
182
207
|
const changed = !sameAgentActivity(record.activity, next);
|
|
@@ -210,6 +235,7 @@ export class MonitorState {
|
|
|
210
235
|
): ReconcileResult {
|
|
211
236
|
let changed = false;
|
|
212
237
|
const completions: CompletionCandidate[] = [];
|
|
238
|
+
const removed: MonitoredAgent[] = [];
|
|
213
239
|
for (const record of this.list()) {
|
|
214
240
|
const panel =
|
|
215
241
|
snapshot.agents.find(
|
|
@@ -226,6 +252,7 @@ export class MonitorState {
|
|
|
226
252
|
);
|
|
227
253
|
if (!paneStillExists) {
|
|
228
254
|
this.agents.delete(record.terminalId);
|
|
255
|
+
removed.push(record);
|
|
229
256
|
changed = true;
|
|
230
257
|
}
|
|
231
258
|
continue;
|
|
@@ -236,7 +263,16 @@ export class MonitorState {
|
|
|
236
263
|
let completion: Omit<CompletionCandidate, "record"> | undefined;
|
|
237
264
|
if (panel.agent_status === "working") {
|
|
238
265
|
const task = activityTask(activity);
|
|
239
|
-
|
|
266
|
+
const attemptId =
|
|
267
|
+
activity.phase === "settled" ? undefined : activity.attemptId;
|
|
268
|
+
const expectedUserAfter =
|
|
269
|
+
activity.phase === "settled" ? undefined : activity.expectedUserAfter;
|
|
270
|
+
activity = {
|
|
271
|
+
phase: "working",
|
|
272
|
+
...(attemptId ? { attemptId } : {}),
|
|
273
|
+
...(expectedUserAfter !== undefined ? { expectedUserAfter } : {}),
|
|
274
|
+
...(task ? { task } : {}),
|
|
275
|
+
};
|
|
240
276
|
} else if (
|
|
241
277
|
isSettledStatus(panel.agent_status) &&
|
|
242
278
|
activity.phase !== "settled"
|
|
@@ -259,7 +295,7 @@ export class MonitorState {
|
|
|
259
295
|
this.agents.set(updated.terminalId, updated);
|
|
260
296
|
if (completion) completions.push({ ...completion, record: updated });
|
|
261
297
|
}
|
|
262
|
-
return { changed, completions };
|
|
298
|
+
return { changed, completions, removed };
|
|
263
299
|
}
|
|
264
300
|
|
|
265
301
|
movePane(
|
package/src/monitor.ts
CHANGED
|
@@ -9,8 +9,17 @@ import { parseMonitorEvent } from "./monitor-event.js";
|
|
|
9
9
|
import { MonitorEvents } from "./monitor-events.js";
|
|
10
10
|
import { MonitorState, type WorkAttempt } from "./monitor-state.js";
|
|
11
11
|
import type { AssistantReader } from "./session-reader.js";
|
|
12
|
-
import {
|
|
13
|
-
|
|
12
|
+
import {
|
|
13
|
+
type ClaimedSettlement,
|
|
14
|
+
SettlementReporter,
|
|
15
|
+
type SettlementRequest,
|
|
16
|
+
} from "./settlement.js";
|
|
17
|
+
import type {
|
|
18
|
+
HerdrEvent,
|
|
19
|
+
MonitoredAgent,
|
|
20
|
+
PaneInfo,
|
|
21
|
+
SessionView,
|
|
22
|
+
} from "./types.js";
|
|
14
23
|
|
|
15
24
|
interface AgentMonitorOptions {
|
|
16
25
|
client: HerdrConnection;
|
|
@@ -100,11 +109,26 @@ export class AgentMonitor {
|
|
|
100
109
|
}
|
|
101
110
|
|
|
102
111
|
async watch(panel: PaneInfo): Promise<MonitoredAgent> {
|
|
112
|
+
return this.watchPanel(panel, true);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async track(panel: PaneInfo): Promise<MonitoredAgent> {
|
|
116
|
+
return this.watchPanel(panel, false);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
private async watchPanel(
|
|
120
|
+
panel: PaneInfo,
|
|
121
|
+
reportSettled: boolean,
|
|
122
|
+
): Promise<MonitoredAgent> {
|
|
103
123
|
if (panel.pane_id === this.selfPaneId) {
|
|
104
124
|
throw new Error("refusing to monitor the controlling Pi session");
|
|
105
125
|
}
|
|
106
126
|
const reply = await this.settlements.latest(panel);
|
|
107
|
-
const { record, reportCurrent } = this.state.watch(
|
|
127
|
+
const { record, reportCurrent } = this.state.watch(
|
|
128
|
+
panel,
|
|
129
|
+
reply?.id,
|
|
130
|
+
reportSettled,
|
|
131
|
+
);
|
|
108
132
|
this.persist();
|
|
109
133
|
await this.events.refresh();
|
|
110
134
|
await this.reconcile(this.activationGeneration, this.context);
|
|
@@ -117,17 +141,40 @@ export class AgentMonitor {
|
|
|
117
141
|
async unwatch(paneId: string): Promise<boolean> {
|
|
118
142
|
const record = this.state.removePane(paneId);
|
|
119
143
|
if (!record) return false;
|
|
144
|
+
this.settlements.releaseAgentClaim(
|
|
145
|
+
record,
|
|
146
|
+
new Error(`${paneId} was unwatched before its work settled`),
|
|
147
|
+
);
|
|
120
148
|
this.persist();
|
|
121
149
|
await this.events.refresh();
|
|
122
150
|
return true;
|
|
123
151
|
}
|
|
124
152
|
|
|
125
|
-
beginWork(
|
|
126
|
-
|
|
153
|
+
beginWork(
|
|
154
|
+
paneId: string,
|
|
155
|
+
task: string,
|
|
156
|
+
expectedUserAfter?: string | null,
|
|
157
|
+
): WorkAttempt | undefined {
|
|
158
|
+
const attempt = this.state.beginWork(paneId, task, expectedUserAfter);
|
|
127
159
|
if (attempt) this.persist();
|
|
128
160
|
return attempt;
|
|
129
161
|
}
|
|
130
162
|
|
|
163
|
+
claimWork(
|
|
164
|
+
attempt: WorkAttempt,
|
|
165
|
+
signal: AbortSignal,
|
|
166
|
+
): Promise<ClaimedSettlement> {
|
|
167
|
+
return this.settlements.claim(attempt, signal);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
releaseWorkClaim(attempt: WorkAttempt | undefined, error: unknown): void {
|
|
171
|
+
this.settlements.releaseClaim(attempt, error);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
view(panel: PaneInfo): Promise<SessionView> {
|
|
175
|
+
return this.settlements.view(panel);
|
|
176
|
+
}
|
|
177
|
+
|
|
131
178
|
acceptWork(attempt: WorkAttempt | undefined): void {
|
|
132
179
|
if (this.state.acceptWork(attempt)) this.persist();
|
|
133
180
|
}
|
|
@@ -182,10 +229,16 @@ export class AgentMonitor {
|
|
|
182
229
|
const snapshot = await getSnapshot(this.client);
|
|
183
230
|
if (generation !== this.activationGeneration || context !== this.context)
|
|
184
231
|
return;
|
|
185
|
-
const { changed, completions } = this.state.reconcile(
|
|
232
|
+
const { changed, completions, removed } = this.state.reconcile(
|
|
186
233
|
snapshot,
|
|
187
234
|
this.selfPaneId,
|
|
188
235
|
);
|
|
236
|
+
for (const record of removed) {
|
|
237
|
+
this.settlements.releaseAgentClaim(
|
|
238
|
+
record,
|
|
239
|
+
new Error(`${record.paneId} closed before its work settled`),
|
|
240
|
+
);
|
|
241
|
+
}
|
|
189
242
|
if (changed || persistRestoration) this.persist();
|
|
190
243
|
else this.onRefresh();
|
|
191
244
|
for (const completion of completions) {
|
|
@@ -199,6 +252,10 @@ export class AgentMonitor {
|
|
|
199
252
|
if (parsed.type === "closed") {
|
|
200
253
|
const record = this.state.removePane(parsed.paneId);
|
|
201
254
|
if (record) {
|
|
255
|
+
this.settlements.releaseAgentClaim(
|
|
256
|
+
record,
|
|
257
|
+
new Error(`${parsed.paneId} closed before its work settled`),
|
|
258
|
+
);
|
|
202
259
|
this.persist();
|
|
203
260
|
void this.events.refresh();
|
|
204
261
|
}
|