pi-suite 0.3.6 → 0.3.8
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/package.json +1 -1
- package/src/agents/child.ts +9 -3
- package/src/agents/history.ts +3 -3
- package/src/agents/index.ts +22 -21
- package/src/agents/manager.ts +40 -12
- package/src/agents/records.ts +4 -2
- package/src/agents/runner.ts +12 -3
- package/src/agents/runtime.ts +1 -1
- package/src/agents/schedules/menu.ts +1 -1
- package/src/agents/types.ts +2 -1
- package/src/agents/ui/runs.ts +34 -14
- package/src/agents/viewer.ts +69 -43
- package/src/agents/workflow/index.ts +32 -9
- package/src/agents/workflow/manager.ts +18 -6
- package/src/agents/workflow/ui/menu.ts +2 -2
- package/src/jobs/index.ts +49 -36
- package/src/jobs/manager-record.ts +2 -2
- package/src/jobs/manager.ts +30 -12
- package/src/jobs/monitors/runtime.ts +41 -27
- package/src/jobs/store.ts +49 -10
- package/src/jobs/tools.ts +2 -2
- package/src/jobs/types.ts +2 -0
- package/src/jobs/viewer/metadata.ts +6 -0
- package/src/jobs/viewer.ts +30 -25
- package/src/runtime/branch.ts +14 -0
- package/src/runtime/cleanup/command.ts +116 -0
- package/src/runtime/cleanup/locations.ts +91 -0
- package/src/runtime/cleanup/occupancy.ts +117 -0
- package/src/runtime/cleanup/paths.ts +44 -0
- package/src/runtime/cleanup/quarantine.ts +162 -0
- package/src/runtime/cleanup/scan.ts +297 -0
- package/src/runtime/cleanup/session-use.ts +62 -0
- package/src/runtime/cleanup/sessions.ts +119 -0
- package/src/runtime/json-store.ts +6 -0
- package/src/runtime/owner.ts +1 -1
- package/src/runtime/settings/index.ts +9 -1
- package/src/runtime/suite.ts +43 -1
- package/src/tasks/store.ts +18 -1
- package/src/tasks/viewer.ts +14 -12
- package/src/ui/actions.ts +1 -1
- package/src/ui/browser.ts +95 -43
- package/src/ui/scroll.ts +5 -1
- package/src/ui/ticker.ts +2 -2
package/package.json
CHANGED
package/src/agents/child.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { getAgentDir, type ExtensionAPI } from '@earendil-works/pi-coding-agent';
|
|
2
2
|
import { SessionBinding } from '../runtime/binding.ts';
|
|
3
3
|
import { Notifications } from '../runtime/notifications.ts';
|
|
4
4
|
import { WaitRegistry, registerWait } from '../runtime/wait.ts';
|
|
@@ -19,6 +19,8 @@ import type { AgentManager } from './manager.ts';
|
|
|
19
19
|
import type { Execution } from './types.ts';
|
|
20
20
|
import { loadConfig } from '../runtime/config.ts';
|
|
21
21
|
import { registerSuiteRenderers } from '../runtime/renderers.ts';
|
|
22
|
+
import { publishSessionReferences, registerSessionUse } from '../runtime/cleanup/session-use.ts';
|
|
23
|
+
import type { SessionUse } from '../runtime/cleanup/occupancy.ts';
|
|
22
24
|
|
|
23
25
|
/** Child tools own a private list; only an explicit assigned scope can update parent progress. */
|
|
24
26
|
export async function childSuite(pi: ExtensionAPI, run: Execution, manager: AgentManager): Promise<void> {
|
|
@@ -44,7 +46,7 @@ export async function childSuite(pi: ExtensionAPI, run: Execution, manager: Agen
|
|
|
44
46
|
if (tasks) { registerTaskTools(pi, tasks); tasks.registerReminders(pi, () => config, notices); }
|
|
45
47
|
if (jobs) {
|
|
46
48
|
const viewer = { jobs, dock, notifications: notices, keys: () => config.jobs };
|
|
47
|
-
registerJobTools(pi, jobs, viewer, { config: () => config, tasks,
|
|
49
|
+
registerJobTools(pi, jobs, viewer, { config: () => config, tasks, cleanupOwner: run.record.ownerSessionId,
|
|
48
50
|
creator: { agentId: run.record.id, runId: run.record.runId,
|
|
49
51
|
ancestors: [...run.record.ancestors, ...run.record.workflowId ? [run.record.workflowId] : []] } });
|
|
50
52
|
waits.register(jobs);
|
|
@@ -56,7 +58,10 @@ export async function childSuite(pi: ExtensionAPI, run: Execution, manager: Agen
|
|
|
56
58
|
registerAgentTools(pi, agents, waits, () => loadConfig(run.configCwd), undefined, jobs ?? new JobsModule(pi, binding, notices, status));
|
|
57
59
|
}
|
|
58
60
|
waits.register(agents); registerWait(pi, waits);
|
|
61
|
+
let use: SessionUse | undefined;
|
|
62
|
+
publishSessionReferences(pi, () => use);
|
|
59
63
|
pi.on('session_start', async (_event, ctx) => {
|
|
64
|
+
use = await registerSessionUse(getAgentDir(), ctx, run.record.ownerSessionId);
|
|
60
65
|
binding.bind(ctx);
|
|
61
66
|
recovery?.reset(ctx);
|
|
62
67
|
await tasks?.bind(ctx, { reason: 'startup' });
|
|
@@ -71,9 +76,10 @@ export async function childSuite(pi: ExtensionAPI, run: Execution, manager: Agen
|
|
|
71
76
|
return notices.beforeSettle(repair ? { ...event, ...repair } : event) ?? repair;
|
|
72
77
|
});
|
|
73
78
|
pi.on('agent_settled', () => { recovery?.settled(); waits.steeringDelivered(); notices.flush(); });
|
|
74
|
-
pi.on('session_shutdown', () => {
|
|
79
|
+
pi.on('session_shutdown', async () => {
|
|
75
80
|
// The child owns its bindings, while the shared job/agent runtimes belong to the Pi process.
|
|
76
81
|
recovery?.reset();
|
|
77
82
|
agents.detach(); jobs?.detach(); tasks?.detach(); notices.detach(); binding.revoke();
|
|
83
|
+
await use?.release(); use = undefined;
|
|
78
84
|
});
|
|
79
85
|
}
|
package/src/agents/history.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { readdir, stat } from 'node:fs/promises';
|
|
1
|
+
import { readdir, readFile, stat } from 'node:fs/promises';
|
|
2
2
|
import { join, resolve } from 'node:path';
|
|
3
3
|
import { getAgentDir, SettingsManager, type SessionEntry } from '@earendil-works/pi-coding-agent';
|
|
4
4
|
import type { SuiteConfig } from '../runtime/config.ts';
|
|
5
5
|
import { ToolError } from '../runtime/errors.ts';
|
|
6
6
|
import { agentTypes } from './catalog.ts';
|
|
7
|
-
import { AGENT_ENTRY, decodeAgentRecord,
|
|
7
|
+
import { AGENT_ENTRY, decodeAgentRecord, parseAgentSession } from './records.ts';
|
|
8
8
|
import { active, recordWorkspace, type AgentRecord, type ParentScope } from './types.ts';
|
|
9
9
|
import { resourcePath } from './resources/paths.ts';
|
|
10
10
|
import { WORKFLOW_ENTRY_TYPE, decodeWorkflowEntry } from './workflow/entry.ts';
|
|
@@ -70,7 +70,7 @@ export class AgentHistory {
|
|
|
70
70
|
file = {stamp, records: data.children.map(record => ({record, updatedAt: stats.mtimeMs})),
|
|
71
71
|
sessions: data.children.flatMap(record => record.sessionFile ? [{path: record.sessionFile, cwd: recordWorkspace(record)}] : []), workflows: []};
|
|
72
72
|
} else {
|
|
73
|
-
const manager =
|
|
73
|
+
const manager = parseAgentSession(await readFile(path, 'utf8'), path);
|
|
74
74
|
file = {...this.entries(manager.getEntries(), path), stamp, leafId: manager.getLeafId()};
|
|
75
75
|
const parent = manager.getHeader()?.parentSession;
|
|
76
76
|
if (parent) file.sessions.push({path: parent});
|
package/src/agents/index.ts
CHANGED
|
@@ -63,10 +63,9 @@ export class AgentsModule implements Waitable {
|
|
|
63
63
|
readonly stale?: string;
|
|
64
64
|
private warned = false;
|
|
65
65
|
private unsubscribe?: () => void;
|
|
66
|
-
private
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
});
|
|
66
|
+
private activityRecords: AgentRecord[] = [];
|
|
67
|
+
private executingIds: string[] = [];
|
|
68
|
+
private readonly ticker = new PresentationTicker(() => this.status.detailsVisible('agents'), () => this.publishActivities());
|
|
70
69
|
private queued = new Set<string>();
|
|
71
70
|
private saved = new Map<string, string>();
|
|
72
71
|
constructor(private pi: ExtensionAPI, private binding: SessionBinding, private notifications: Notifications,
|
|
@@ -110,12 +109,12 @@ export class AgentsModule implements Waitable {
|
|
|
110
109
|
}
|
|
111
110
|
detach(): void {
|
|
112
111
|
this.unsubscribe?.(); this.unsubscribe = undefined;
|
|
113
|
-
this.ticker.stop();
|
|
112
|
+
this.ticker.stop(); this.activityRecords = []; this.executingIds = [];
|
|
114
113
|
const current = this.binding.current;
|
|
115
114
|
if (current) for (const request of this.queued) this.notifications.cancel(current.sessionId, request);
|
|
116
115
|
this.queued.clear(); this.saved.clear(); this.status.setActivities('agents', []);
|
|
117
116
|
}
|
|
118
|
-
private
|
|
117
|
+
private captureActivities(records: AgentRecord[], scope: ParentScope): void {
|
|
119
118
|
// A consumed question is still awaiting its answer. Include workflow questions
|
|
120
119
|
// visible to this parent without exposing unrelated runs or nested descendants.
|
|
121
120
|
const visible = new Map(records.map(record => [record.runId, record]));
|
|
@@ -124,12 +123,18 @@ export class AgentsModule implements Waitable {
|
|
|
124
123
|
}
|
|
125
124
|
// Pick representatives before filtering; an unread older failure may still notify,
|
|
126
125
|
// but must not keep a row after the latest run has superseded it.
|
|
127
|
-
|
|
126
|
+
this.activityRecords = Array.from(groupAgentRuns(visible.values()).values(), ([record]) => record).filter(record => {
|
|
127
|
+
const run = this.manager.runs.get(record.runId);
|
|
128
|
+
return active(record.state) || ['failed', 'limited'].includes(record.state) && run && !run.consumed;
|
|
129
|
+
});
|
|
130
|
+
this.executingIds = records.filter(record => executing(record.state)).map(record => record.id);
|
|
131
|
+
this.publishActivities();
|
|
132
|
+
}
|
|
133
|
+
private publishActivities(): void {
|
|
128
134
|
const counts = new Map<string, number>();
|
|
129
|
-
const rows =
|
|
130
|
-
const run = this.manager.runs.get(
|
|
131
|
-
const
|
|
132
|
-
if (!active(record.state) && !failed) return [];
|
|
135
|
+
const rows = this.activityRecords.map<DockRow>(snapshot => {
|
|
136
|
+
const run = this.manager.runs.get(snapshot.runId), question = Boolean(run?.question);
|
|
137
|
+
const record = run ? this.manager.view(run) : snapshot;
|
|
133
138
|
const state = question ? 'waiting(parent)' : record.state;
|
|
134
139
|
counts.set(state, (counts.get(state) ?? 0) + 1);
|
|
135
140
|
const retry = retrySuffix(run);
|
|
@@ -137,28 +142,24 @@ export class AgentsModule implements Waitable {
|
|
|
137
142
|
const basic: DisplayField[] = [...status, {text: ` · ${elapsedText(record.elapsedMs ?? 0)}`, tone: 'dim'}];
|
|
138
143
|
const tools = `${record.toolUses ?? 0} tools`;
|
|
139
144
|
const model = record.model.slice(record.model.indexOf('/') + 1);
|
|
140
|
-
return
|
|
145
|
+
return { id: `agent:${record.runId}`, text: `${sanitizeText(record.name).replace(/[\r\n\t]/g, ' ')} (${sanitizeText(model)})`,
|
|
141
146
|
suffix: [...basic, {text: ` · ↑${countText(record.usage?.tokens.input ?? 0)} ↓${countText(record.usage?.tokens.output ?? 0)} · ${tools}`, tone: 'dim'}],
|
|
142
147
|
compactSuffixes: [[...basic, {text: ` · ${tools}`, tone: 'dim'}], basic, status],
|
|
143
|
-
priority: question ? 100 :
|
|
148
|
+
priority: question ? 100 : !active(record.state) ? 80 : record.state === 'stopping' ? 75 : record.state === 'queued' ? 15 : 25 };
|
|
144
149
|
});
|
|
145
150
|
const aside: DisplayField[] = ['starting', 'running', 'waiting', 'waiting(parent)', 'stopping', 'queued', 'failed', 'limited']
|
|
146
151
|
.filter(state => counts.has(state)).flatMap((state, index) => [
|
|
147
152
|
...index ? [{text: ' · ', tone: 'dim' as const}] : [], {text: `${counts.get(state)} ${state}`, state},
|
|
148
153
|
]);
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
private publishActivities(records: AgentRecord[], scope: ParentScope): void {
|
|
152
|
-
const {rows, aside, ticking} = this.rows(records, scope);
|
|
153
|
-
this.status.setActivities('agents', records.filter(record => executing(record.state)).map(record => record.id), rows, aside);
|
|
154
|
-
this.ticker.update(ticking);
|
|
154
|
+
this.status.setActivities('agents', this.executingIds, rows, aside);
|
|
155
|
+
this.ticker.update(this.activityRecords.some(record => active(record.state)));
|
|
155
156
|
}
|
|
156
157
|
private revision(record: AgentRecord): string { return `${record.state}:${record.background}:${record.sessionFile ?? ''}:${record.endedAt ?? ''}:${record.model}:${record.thinking}:${JSON.stringify(record.individual)}`; }
|
|
157
158
|
private refresh(): void {
|
|
158
159
|
const current = this.binding.current;
|
|
159
160
|
if (!current) return;
|
|
160
161
|
const scope = this.scope(current.ctx), records = this.manager.records().filter(record => this.manager.visible(record, scope));
|
|
161
|
-
this.
|
|
162
|
+
this.captureActivities(records, scope);
|
|
162
163
|
const unread = this.unreadNotices();
|
|
163
164
|
for (const request of this.queued) if (!unread.some(({ item }) => this.request(item) === request)) {
|
|
164
165
|
this.notifications.cancel(current.sessionId, request); this.queued.delete(request);
|
|
@@ -193,7 +194,7 @@ export class AgentsModule implements Waitable {
|
|
|
193
194
|
if (!current) return [];
|
|
194
195
|
const scope = this.scope(current.ctx);
|
|
195
196
|
return [...this.manager.runs.values()].filter(run => run.question && !run.question.seen && this.manager.questionVisible(run.record, scope)
|
|
196
|
-
||
|
|
197
|
+
|| run.settled && !run.consumed && (run.record.background || run.notifyResult) && this.manager.visible(run.record, scope)).map(run => {
|
|
197
198
|
const record = this.manager.view(run);
|
|
198
199
|
const question = run.question && !run.question.seen ? questionNotification(run) : undefined;
|
|
199
200
|
const item: Settlement = { id: record.id, runId: record.runId, state: record.state, settled: !active(record.state),
|
package/src/agents/manager.ts
CHANGED
|
@@ -6,6 +6,7 @@ import type { SuiteConfig } from '../runtime/config.ts';
|
|
|
6
6
|
import type { StopOutcome } from '../runtime/tools.ts';
|
|
7
7
|
import { requireGeneration } from '../tasks/types.ts';
|
|
8
8
|
import { ToolError } from '../runtime/errors.ts';
|
|
9
|
+
import { branchIds } from '../runtime/branch.ts';
|
|
9
10
|
import { resolveType } from './catalog.ts';
|
|
10
11
|
import { parentModelRuntime, resolveSettings } from './models.ts';
|
|
11
12
|
import { hydrate, transcript } from './records.ts';
|
|
@@ -29,9 +30,11 @@ export class AgentManager {
|
|
|
29
30
|
private limits = { background: 10, foreground: 0 };
|
|
30
31
|
private closing = false;
|
|
31
32
|
private listeners = new Set<() => void>();
|
|
33
|
+
private outputListeners = new Set<(runId: string) => void>();
|
|
32
34
|
private eventListeners = new Set<(kind: AgentEventKind, run: Execution, details: Record<string, unknown>) => void>();
|
|
33
35
|
private closedRuns = new Set<string>();
|
|
34
|
-
private stops = new Map<string, Promise<StopOutcome
|
|
36
|
+
private stops = new Map<string, {owner: string; operation: Promise<StopOutcome>}>();
|
|
37
|
+
private taskAdmissions = new Set<{ownerSessionId: string}>();
|
|
35
38
|
private retained = new Map<string, number>();
|
|
36
39
|
private cleanupTimer?: NodeJS.Timeout;
|
|
37
40
|
constructor(private execute: (run: Execution) => Promise<void>, private stopJobs: (ids: string[]) => Promise<StopOutcome['affected']>) {}
|
|
@@ -42,6 +45,12 @@ export class AgentManager {
|
|
|
42
45
|
for (const run of this.runs.values()) if (!run.settled || run.question && !run.question.seen || this.resultPending(run)) return true;
|
|
43
46
|
return false;
|
|
44
47
|
}
|
|
48
|
+
cleanupOwners(): Set<string> {
|
|
49
|
+
const ids = new Set([...this.stops.values()].map(stop => stop.owner));
|
|
50
|
+
for (const admission of this.taskAdmissions) ids.add(admission.ownerSessionId);
|
|
51
|
+
for (const run of this.runs.values()) if (!run.settled) ids.add(run.record.ownerSessionId);
|
|
52
|
+
return ids;
|
|
53
|
+
}
|
|
45
54
|
private resultPending(run: Execution): boolean {
|
|
46
55
|
const parent = run.record.parentRunId ? this.runs.get(run.record.parentRunId) : undefined;
|
|
47
56
|
// The workflow host consumes its own results; only a live nested parent can receive notices.
|
|
@@ -54,6 +63,11 @@ export class AgentManager {
|
|
|
54
63
|
}
|
|
55
64
|
subscribe(listener: () => void): () => void { this.listeners.add(listener); return () => this.listeners.delete(listener); }
|
|
56
65
|
changed = (): void => { for (const listener of [...this.listeners]) listener(); };
|
|
66
|
+
/** Partial output changes readers, not persistence, notifications or wait conditions. */
|
|
67
|
+
subscribeOutput(listener: (runId: string) => void): () => void {
|
|
68
|
+
this.outputListeners.add(listener); return () => this.outputListeners.delete(listener);
|
|
69
|
+
}
|
|
70
|
+
outputChanged(runId: string): void { for (const listener of this.outputListeners) listener(runId); }
|
|
57
71
|
subscribeEvents(listener: (kind: AgentEventKind, run: Execution, details: Record<string, unknown>) => void): () => void {
|
|
58
72
|
this.eventListeners.add(listener); return () => this.eventListeners.delete(listener);
|
|
59
73
|
}
|
|
@@ -105,7 +119,10 @@ export class AgentManager {
|
|
|
105
119
|
if (changed) this.changed();
|
|
106
120
|
}
|
|
107
121
|
records(): AgentRecord[] {
|
|
108
|
-
|
|
122
|
+
const records: AgentRecord[] = [];
|
|
123
|
+
for (const {record} of this.histories.values()) records.push(record);
|
|
124
|
+
for (const run of this.runs.values()) records.push(this.view(run));
|
|
125
|
+
return records;
|
|
109
126
|
}
|
|
110
127
|
view(run: Execution): AgentRecord {
|
|
111
128
|
const state = !run.settled && !active(run.record.state) ? run.controller.signal.aborted ? 'stopping' : 'running' : run.record.state;
|
|
@@ -113,11 +130,18 @@ export class AgentManager {
|
|
|
113
130
|
? Math.round(performance.now() - run.startedMonotonic) : run.record.elapsedMs };
|
|
114
131
|
}
|
|
115
132
|
get(id: string, runId?: string): { record: AgentRecord; run?: Execution } {
|
|
116
|
-
const
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
133
|
+
const run = runId === undefined ? undefined : this.runs.get(runId);
|
|
134
|
+
let record = run?.record ?? (runId === undefined ? undefined : this.histories.get(runId)?.record);
|
|
135
|
+
if (runId === undefined) {
|
|
136
|
+
const consider = (candidate: AgentRecord) => {
|
|
137
|
+
if (candidate.id === id && (!record || compareRunRecency(candidate, record) < 0)) record = candidate;
|
|
138
|
+
};
|
|
139
|
+
for (const history of this.histories.values()) consider(history.record);
|
|
140
|
+
for (const item of this.runs.values()) consider(item.record);
|
|
141
|
+
}
|
|
142
|
+
if (!record || record.id !== id) throw new ToolError('NOT_FOUND', `No agent ${id}${runId ? ` run ${runId}` : ''}; discover with agent_list({"scope":"workspace","state":"all"})`, id);
|
|
143
|
+
const execution = run ?? this.runs.get(record.runId);
|
|
144
|
+
return { record: execution ? this.view(execution) : record, run: execution };
|
|
121
145
|
}
|
|
122
146
|
isStopping(id: string): boolean {
|
|
123
147
|
// A stop may still own job cleanup after the run itself has settled.
|
|
@@ -131,7 +155,7 @@ export class AgentManager {
|
|
|
131
155
|
questionVisible(record: AgentRecord, scope: ParentScope): boolean {
|
|
132
156
|
return this.visible(record, scope) || !scope.run && record.workflowId !== undefined
|
|
133
157
|
&& record.parentAgentId === undefined && record.ownerSessionId === scope.ctx.sessionManager.getSessionId()
|
|
134
|
-
&& (record.anchorEntryId === null || scope.ctx.sessionManager
|
|
158
|
+
&& (record.anchorEntryId === null || branchIds(scope.ctx.sessionManager).has(record.anchorEntryId));
|
|
135
159
|
}
|
|
136
160
|
async start(request: StartAgent, scope: ParentScope, config: SuiteConfig, previous?: AgentRecord,
|
|
137
161
|
options: StartOptions = {}, continuation?: Execution): Promise<Execution> {
|
|
@@ -166,8 +190,12 @@ export class AgentManager {
|
|
|
166
190
|
if (taskId) {
|
|
167
191
|
requireGeneration(taskGeneration);
|
|
168
192
|
if (!taskStore) throw new ToolError('TASK_SCOPE', 'The direct parent has no task list. Omit taskId or enable the tasks module in the parent.');
|
|
169
|
-
const
|
|
170
|
-
|
|
193
|
+
const admission = {ownerSessionId: scope.owner!.ownerSessionId};
|
|
194
|
+
this.taskAdmissions.add(admission);
|
|
195
|
+
try {
|
|
196
|
+
const task = (await taskStore.snapshot(taskGeneration)).tasks.find(task => task.id === taskId);
|
|
197
|
+
if (!task?.parentId) throw new ToolError('NOT_FOUND', `No child task ${taskId} in the parent's current list. Use task_list to find a child task ID and its generation.`);
|
|
198
|
+
} finally { this.taskAdmissions.delete(admission); }
|
|
171
199
|
}
|
|
172
200
|
// Recheck after task I/O: stop closes subtree admission before awaiting any abort/job cleanup.
|
|
173
201
|
options.signal?.throwIfAborted();
|
|
@@ -392,7 +420,7 @@ export class AgentManager {
|
|
|
392
420
|
const roots = this.records().filter(item => item.id === id && (!runId || item.runId === runId)).map(item => item.runId);
|
|
393
421
|
const stopKey = `${id}:${[...roots].sort().join(',')}`;
|
|
394
422
|
const existing = this.stops.get(stopKey);
|
|
395
|
-
if (existing) return existing;
|
|
423
|
+
if (existing) return existing.operation;
|
|
396
424
|
for (const root of roots) this.closedRuns.add(root);
|
|
397
425
|
const targets = [...this.runs.values()].filter(item => roots.includes(item.record.runId) || item.record.ancestors.some(ancestor => roots.includes(ancestor)));
|
|
398
426
|
let requested = false;
|
|
@@ -409,7 +437,7 @@ export class AgentManager {
|
|
|
409
437
|
return { requested: requested || jobs.length > 0, state: this.get(id, record.runId).record.state,
|
|
410
438
|
cleanup: jobs.some(job => job.cleanup === 'unconfirmed' || job.cleanup === 'pending') ? 'unconfirmed' : 'confirmed', affected };
|
|
411
439
|
}).finally(() => this.stops.delete(stopKey));
|
|
412
|
-
this.stops.set(stopKey, operation);
|
|
440
|
+
this.stops.set(stopKey, {owner: record.ownerSessionId, operation});
|
|
413
441
|
const cancelled: {target: Execution; queued: boolean}[] = [];
|
|
414
442
|
for (const target of targets) if (active(target.record.state)) {
|
|
415
443
|
requested = true; this.closedRuns.add(target.record.runId);
|
package/src/agents/records.ts
CHANGED
|
@@ -30,8 +30,10 @@ export function decodeAgentRecord(value: unknown, source = 'session entry'): Age
|
|
|
30
30
|
return value as AgentRecord;
|
|
31
31
|
}
|
|
32
32
|
/** Pi's disk open can repair files. Its in-memory tree migrates and reads without writes. */
|
|
33
|
-
export function readAgentSession(path: string): SessionManager {
|
|
34
|
-
|
|
33
|
+
export function readAgentSession(path: string): SessionManager { return parseAgentSession(readFileSync(path, 'utf8'), path); }
|
|
34
|
+
|
|
35
|
+
export function parseAgentSession(content: string, path: string): SessionManager {
|
|
36
|
+
const entries = parseSessionEntries(content), header = entries[0];
|
|
35
37
|
// Pi's parser skips malformed lines. Saved suite history must report corruption rather
|
|
36
38
|
// than silently presenting an earlier result; migration/tree construction still use Pi.
|
|
37
39
|
if (entries.length !== content.split('\n').reduce((count, line) => count + (line.trim() ? 1 : 0), 0)) {
|
package/src/agents/runner.ts
CHANGED
|
@@ -12,7 +12,7 @@ import { parentModelRuntime } from './models.ts';
|
|
|
12
12
|
import { ModelRequestError } from './retry.ts';
|
|
13
13
|
|
|
14
14
|
export async function executeAgent(run: Execution, factory: ExtensionFactory, changed: () => void,
|
|
15
|
-
emitEvent: (kind: AgentEventKind, details?: Record<string, unknown>) => void): Promise<void> {
|
|
15
|
+
emitEvent: (kind: AgentEventKind, details?: Record<string, unknown>) => void, outputChanged = changed): Promise<void> {
|
|
16
16
|
const { record, parent } = run, agentDir = getAgentDir();
|
|
17
17
|
// Queued runs can survive reload. Check the registry captured at launch before loading resources.
|
|
18
18
|
const modelRuntime = parentModelRuntime(parent.ctx);
|
|
@@ -21,6 +21,12 @@ export async function executeAgent(run: Execution, factory: ExtensionFactory, ch
|
|
|
21
21
|
const manager = run.sessionManager ?? (record.sessionFile ? SessionManager.open(record.sessionFile)
|
|
22
22
|
: record.persisted ? createChildSession(record.cwd, parent.ctx.sessionManager.getSessionFile(),
|
|
23
23
|
run.type.sessionDir === undefined ? undefined : resourcePath(run.type.sessionDir, record.cwd)) : SessionManager.inMemory(record.cwd));
|
|
24
|
+
if (record.persisted && run.type.sessionDir !== undefined) {
|
|
25
|
+
try {
|
|
26
|
+
const { rememberChildRoot } = await import('../runtime/cleanup/locations.ts');
|
|
27
|
+
await rememberChildRoot(agentDir, manager.getSessionDir());
|
|
28
|
+
} catch (error) { process.emitWarning(`Cannot register child session directory for cleanup: ${String(error)}`); }
|
|
29
|
+
}
|
|
24
30
|
const capture = createStructuredCapture();
|
|
25
31
|
const { session, extensionsResult } = await createAgentSession({ cwd: record.cwd, agentDir, sessionManager: manager,
|
|
26
32
|
settingsManager, resourceLoader: loader, modelRuntime, model: run.model, thinkingLevel: record.thinking,
|
|
@@ -90,8 +96,11 @@ export async function executeAgent(run: Execution, factory: ExtensionFactory, ch
|
|
|
90
96
|
run.options.onCompaction?.(info); emitEvent('compacted', info);
|
|
91
97
|
}
|
|
92
98
|
record.lastUpdateAt = new Date().toISOString();
|
|
93
|
-
|
|
94
|
-
|
|
99
|
+
const sessionFile = manager.getSessionFile(), fileChanged = record.sessionFile !== sessionFile;
|
|
100
|
+
record.sessionFile = sessionFile;
|
|
101
|
+
// A new durable reference belongs on the lifecycle path even if first seen in a delta.
|
|
102
|
+
if (!fileChanged && (event.type === 'message_update' || event.type === 'tool_execution_update')) outputChanged();
|
|
103
|
+
else changed();
|
|
95
104
|
});
|
|
96
105
|
const abort = () => { void session.abort(); };
|
|
97
106
|
run.controller.signal.addEventListener('abort', abort, { once: true });
|
package/src/agents/runtime.ts
CHANGED
|
@@ -24,7 +24,7 @@ export function agentRuntime(): OwnerHandle<AgentManager> {
|
|
|
24
24
|
execution ??= (async () => [await import('./runner.ts'), await import('./child.ts')] as const)();
|
|
25
25
|
const [{ executeAgent }, { childSuite }] = await execution;
|
|
26
26
|
return executeAgent(run, pi => childSuite(pi, run, manager), manager.changed,
|
|
27
|
-
(kind, details) => manager.event(kind, run, details));
|
|
27
|
+
(kind, details) => manager.event(kind, run, details), () => manager.outputChanged(run.record.runId));
|
|
28
28
|
}, async ids => {
|
|
29
29
|
if (runtime.mode !== 'active') throw new Error(`Cannot stop agent jobs: ${runtime.reason}`);
|
|
30
30
|
return (await runtime.manager.stopCreatedBy(ids)).map(({ job }) => ({ id: job.id, state: job.state, cleanup: job.cleanup.state }));
|
|
@@ -23,7 +23,7 @@ export async function showSchedules(ctx: ExtensionContext, scheduler: AgentSched
|
|
|
23
23
|
let action = 'details';
|
|
24
24
|
const id = await browse(ctx, dock, { title: 'Subagents', state: page.state, pages: page.pages, navigation: page.navigation,
|
|
25
25
|
selection: item => { const job = scheduler.list().find(job => job.id === item.value)!; return {name: job.name, id: job.id}; },
|
|
26
|
-
ticking: () => scheduler.list().some(job => job.enabled || job.lastStatus === 'running'),
|
|
26
|
+
refreshOnTick: true, ticking: () => scheduler.list().some(job => job.enabled || job.lastStatus === 'running'),
|
|
27
27
|
items: () => scheduler.list().map(job => ({ value: job.id, status: job.lastStatus, label: `${job.name} · ${job.schedule}`, description: job.request.type,
|
|
28
28
|
search: `${job.id} ${job.name} ${job.schedule} ${job.request.type} ${job.request.prompt}`, details: () => details(job) })),
|
|
29
29
|
actions: (item, done) => [{ key: 'x', label: 'Cancel schedule', run: () => { action = 'cancel'; done(item.value); } }],
|
package/src/agents/types.ts
CHANGED
|
@@ -4,6 +4,7 @@ import type { AskParams, AskResult, Question } from '../ask/schema.ts';
|
|
|
4
4
|
import type { TaskStore } from '../tasks/store.ts';
|
|
5
5
|
import type { SuiteConfig } from '../runtime/config.ts';
|
|
6
6
|
import type { CompiledSchema } from './output/schema.ts';
|
|
7
|
+
import { branchIds } from '../runtime/branch.ts';
|
|
7
8
|
export type ResourceChoice = boolean | string[];
|
|
8
9
|
export type MemoryScope = 'user' | 'project' | 'local';
|
|
9
10
|
|
|
@@ -54,7 +55,7 @@ export const isTopLevelAgent = (record: Pick<AgentRecord, 'parentAgentId' | 'wor
|
|
|
54
55
|
export function visibleAgent(record: AgentRecord, scope: ParentScope): boolean {
|
|
55
56
|
if (scope.run) return record.parentRunId === scope.run.record.runId;
|
|
56
57
|
return isTopLevelAgent(record) && record.ownerSessionId === scope.ctx.sessionManager.getSessionId()
|
|
57
|
-
&& (record.anchorEntryId === null || scope.ctx.sessionManager
|
|
58
|
+
&& (record.anchorEntryId === null || branchIds(scope.ctx.sessionManager).has(record.anchorEntryId));
|
|
58
59
|
}
|
|
59
60
|
export const recordWorkspace = (record: AgentRecord): string => record.configCwd ?? record.cwd;
|
|
60
61
|
export type AgentEventKind = 'created' | 'started' | 'completed' | 'failed' | 'steered' | 'compacted' | 'usage';
|
package/src/agents/ui/runs.ts
CHANGED
|
@@ -2,7 +2,7 @@ import type { ExtensionContext } from '@earendil-works/pi-coding-agent';
|
|
|
2
2
|
import { browse, browseState, compareActivity, type BrowsePage, type BrowseState } from '../../ui/browser.ts';
|
|
3
3
|
import { showDetails } from '../../ui/details.ts';
|
|
4
4
|
import { isActive as jobActive } from '../../jobs/state.ts';
|
|
5
|
-
import {
|
|
5
|
+
import type { DisplayField } from '../../ui/browser-chrome.ts';
|
|
6
6
|
import { elapsedText } from '../../ui/format.ts';
|
|
7
7
|
import { executionRow } from '../../ui/dock/line.ts';
|
|
8
8
|
import { sanitizeText } from '../../runtime/text.ts';
|
|
@@ -39,7 +39,7 @@ export async function showRuns(ctx: ExtensionContext, deps: SubagentsDeps, state
|
|
|
39
39
|
async function openList(browser: BrowseState, history?: string): Promise<void> {
|
|
40
40
|
const scope = agents.scope(ctx);
|
|
41
41
|
const records = () => agents.manager.records().filter(record => state.workspace
|
|
42
|
-
? recordWorkspace(record) === (scope.run?.configCwd ?? ctx.cwd) && (scope.run || record.workflowId === undefined)
|
|
42
|
+
? recordWorkspace(record) === (scope.run?.configCwd ?? ctx.cwd) && (!!scope.run || record.workflowId === undefined)
|
|
43
43
|
: agents.manager.visible(record, scope));
|
|
44
44
|
const readonly = (record: AgentRecord) => {
|
|
45
45
|
const run = agents.manager.runs.get(record.runId);
|
|
@@ -56,20 +56,33 @@ export async function showRuns(ctx: ExtensionContext, deps: SubagentsDeps, state
|
|
|
56
56
|
for (; !exit.closed;) {
|
|
57
57
|
if (state.workspace && !discovered) { await agents.manager.discover(scope, config()); discovered = true; }
|
|
58
58
|
let action = 'transcript', changed = false;
|
|
59
|
-
let displayed = new Map<string, AgentRecord[]>(),
|
|
59
|
+
let displayed = new Map<string, AgentRecord[]>(), counts = {all: 0, queued: 0, finished: 0}, ticking = false;
|
|
60
|
+
const liveView = (record: AgentRecord) => {
|
|
61
|
+
const run = active(record.state) ? agents.manager.runs.get(record.runId) : undefined;
|
|
62
|
+
return run ? agents.manager.view(run) : record;
|
|
63
|
+
};
|
|
64
|
+
let liveRows = new Set<string>();
|
|
60
65
|
const selected = await browse(ctx, dock, { title: 'Subagents', pages: history ? undefined : navigation,
|
|
61
66
|
page: history ? 'Runs' : undefined, scope: history, navigation: exit, state: browser,
|
|
62
|
-
total: () =>
|
|
67
|
+
total: () => counts.all, selection: item => { const [record] = displayed.get(item.value)!; return { name: record.name, id: item.value }; },
|
|
63
68
|
controls: history ? undefined : [
|
|
64
69
|
{ key: 'w', label: 'Scope', items: () => [{ value: 'session', label: 'This session' }, { value: 'workspace', label: 'Workspace' }],
|
|
65
70
|
selected: () => state.workspace ? 'workspace' : 'session', select: (value, done) => { changed = true; change(state.filter, value === 'workspace', done); } },
|
|
66
71
|
{ key: 's', label: 'State', items: () => RUN_FILTERS.map(filter => ({ value: filter,
|
|
67
|
-
label: `${filter[0].toUpperCase()}${filter.slice(1)}`, description: String(
|
|
72
|
+
label: `${filter[0].toUpperCase()}${filter.slice(1)}`, description: String(counts[filter]) })),
|
|
68
73
|
selected: () => state.filter, select: (value, done) => { changed = true; change(value as RunFilter, state.workspace, done); } }],
|
|
69
|
-
subscribe: refresh =>
|
|
74
|
+
subscribe: refresh => {
|
|
75
|
+
const off = agents.manager.subscribe(refresh);
|
|
76
|
+
const offOutput = history ? undefined : agents.manager.subscribeOutput?.(runId => {
|
|
77
|
+
// Partial output affects list order only if another visible active row can move to the top.
|
|
78
|
+
if (liveRows.size > 1 && liveRows.has(runId) && liveRows.values().next().value !== runId) refresh(true);
|
|
79
|
+
});
|
|
80
|
+
return () => { off(); offOutput?.(); };
|
|
81
|
+
},
|
|
82
|
+
ticking: () => ticking,
|
|
70
83
|
layout: { truncatePrimary: ({item, maxWidth, theme}) => {
|
|
71
84
|
const [record] = displayed.get(item.value)!;
|
|
72
|
-
const { full, compact } = suffix(record);
|
|
85
|
+
const { full, compact } = suffix(liveView(record));
|
|
73
86
|
return executionRow(sanitizeText(name(record)).replace(/[\r\n\t]/g, ' '), full, compact, maxWidth, theme);
|
|
74
87
|
} },
|
|
75
88
|
items: () => {
|
|
@@ -77,20 +90,27 @@ export async function showRuns(ctx: ExtensionContext, deps: SubagentsDeps, state
|
|
|
77
90
|
const rows = history
|
|
78
91
|
? records().filter(record => record.id === history).sort(compareRunRecency).map<[string, AgentRecord[]]>(record => [record.runId, [record]])
|
|
79
92
|
: [...groupAgentRuns(records())];
|
|
80
|
-
|
|
93
|
+
counts = {all: rows.length, queued: 0, finished: 0};
|
|
94
|
+
for (const [, [record]] of rows) {
|
|
95
|
+
if (record.state === 'queued') counts.queued++;
|
|
96
|
+
else if (!active(record.state)) counts.finished++;
|
|
97
|
+
}
|
|
98
|
+
liveRows = new Set();
|
|
81
99
|
displayed = new Map(history ? rows : rows.filter(([, [record]]) => matches(record, state.filter))
|
|
82
100
|
.sort(([, [a]], [, [b]]) => compareActivity(a, b, record => active(record.state))));
|
|
83
|
-
|
|
101
|
+
const items = Array.from(displayed, ([value, runs]) => {
|
|
84
102
|
const [record] = runs;
|
|
85
|
-
|
|
86
|
-
return { value,
|
|
103
|
+
if (active(record.state)) liveRows.add(record.runId);
|
|
104
|
+
return { value, label: name(record),
|
|
87
105
|
search: `${record.id} ${runs.map(run => run.runId).join(' ')} ${record.name} ${record.type} ${record.state} ${record.model} ${record.prompt}`,
|
|
88
|
-
details: () => agentDetails(record, undefined, readonly(record)) };
|
|
106
|
+
details: () => agentDetails(liveView(record), undefined, readonly(record)) };
|
|
89
107
|
});
|
|
108
|
+
ticking = liveRows.size > 0;
|
|
109
|
+
return items;
|
|
90
110
|
},
|
|
91
111
|
actions: (item, done) => {
|
|
92
112
|
const runs = displayed.get(item.value)!, [record] = runs;
|
|
93
|
-
const readOnly = readonly(record), controls = agentControls(ctx, agents, record.id, record.runId, readOnly);
|
|
113
|
+
const readOnly = readonly(record), controls = agentControls(ctx, agents, record.id, () => record.runId, readOnly);
|
|
94
114
|
const run = (value: string) => () => { action = value; done(item.value); };
|
|
95
115
|
const pending = record.state === 'queued';
|
|
96
116
|
return [
|
|
@@ -102,7 +122,7 @@ export async function showRuns(ctx: ExtensionContext, deps: SubagentsDeps, state
|
|
|
102
122
|
{ key: 'b', label: 'Background', available: () => !readOnly && agents.manager.canSendToBackground(record.id, record.runId), run: run('background') },
|
|
103
123
|
{ label: pending ? 'Cancel queued' : 'Stop subtree', key: 'x', confirm: true, available: controls.canStop, run: run('stop') },
|
|
104
124
|
{ label: 'Cleanup jobs', key: 'x', confirm: true,
|
|
105
|
-
available: () => !readOnly && !active(record.state) && Boolean(jobs?.viewer.jobs.createdBy([record.runId]).
|
|
125
|
+
available: () => !readOnly && !active(record.state) && Boolean(jobs?.viewer.jobs.createdBy([record.runId], jobActive).length), run: run('stop') },
|
|
106
126
|
];
|
|
107
127
|
},
|
|
108
128
|
});
|