pi-squire 0.15.0 → 0.16.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 +323 -1
- package/README.md +918 -117
- package/package.json +2 -1
- package/src/agents.ts +57 -36
- package/src/child-tasks.ts +221 -0
- package/src/child.ts +35 -41
- package/src/completion-holds.ts +104 -0
- package/src/dashboard.ts +144 -0
- package/src/git.ts +6 -1
- package/src/identity.ts +152 -0
- package/src/index.ts +358 -56
- package/src/local-state.ts +21 -0
- package/src/navigator-view.ts +186 -0
- package/src/navigator.ts +152 -107
- package/src/poll.ts +1 -0
- package/src/render.ts +4 -1
- package/src/result-close.ts +37 -0
- package/src/result-restore.ts +95 -0
- package/src/result-types.ts +29 -1
- package/src/results-presentation.ts +47 -0
- package/src/results.ts +174 -108
- package/src/resume-checks.ts +14 -2
- package/src/resume-picker.ts +9 -2
- package/src/resume.ts +62 -13
- package/src/session-owner.ts +279 -0
- package/src/task-replies.ts +247 -0
- package/src/task-settlement.ts +81 -0
- package/src/task-store.ts +26 -0
- package/src/tmux.ts +134 -54
- package/src/tool-ceiling.ts +125 -0
- package/src/tracking.ts +72 -65
- package/src/tree-close.ts +236 -0
- package/src/tree-fence.ts +51 -0
- package/src/tree-lock.ts +77 -0
- package/src/tree-notice.ts +124 -0
- package/src/tree-registry.ts +365 -0
- package/src/tree-settings.ts +31 -0
- package/src/tree-types.ts +32 -0
- package/src/tree-view.ts +246 -0
- package/src/trust-control.ts +214 -0
- package/src/trust-prompt.ts +163 -0
- package/src/trust-wire.ts +203 -0
- package/src/widget-activity-join.ts +24 -0
- package/src/widget-activity-runtime.ts +104 -0
- package/src/widget-activity.ts +104 -0
- package/src/widget-ancestors.ts +142 -0
- package/src/widget-current.ts +41 -0
- package/src/widget-data.ts +147 -0
- package/src/widget-focus.ts +133 -0
- package/src/widget-live-process.ts +31 -0
- package/src/widget-live.ts +356 -0
- package/src/widget-render.ts +181 -0
- package/src/widget-selection.ts +58 -0
- package/src/widget-settings.ts +29 -0
- package/src/widget-summary.ts +51 -0
- package/src/widget-title-file.ts +127 -0
- package/src/widget-title.ts +118 -0
- package/src/widget.ts +272 -0
- package/src/window-placement.ts +30 -5
- package/src/workspace.ts +38 -90
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
// One authenticated loopback connection per trust decision, with no replay.
|
|
2
|
+
// The owner-only endpoint descriptor is squire state, not provider state.
|
|
3
|
+
import { createHash, createHmac, randomUUID } from "node:crypto";
|
|
4
|
+
import { connect, type Socket } from "node:net";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { readState } from "./local-state.ts";
|
|
7
|
+
import {
|
|
8
|
+
TRUST_TIMEOUT_MS,
|
|
9
|
+
type TrustAnswer,
|
|
10
|
+
type TrustDecision,
|
|
11
|
+
type TrustQuestion,
|
|
12
|
+
trustLifetime,
|
|
13
|
+
trustStopped,
|
|
14
|
+
} from "./trust-prompt.ts";
|
|
15
|
+
|
|
16
|
+
export type TrustEndpoint = { port: number; token: string };
|
|
17
|
+
export type TrustRequest = TrustQuestion & { token: string; root: string; id: string; expiresAt: number };
|
|
18
|
+
type TrustResponse = { id: string; answer?: TrustAnswer; error?: string };
|
|
19
|
+
const FRAME_LIMIT = 32 * 1024;
|
|
20
|
+
const CONNECT_TIMEOUT_MS = 1000;
|
|
21
|
+
|
|
22
|
+
/** Fresh client nonce proves the endpoint still holds this runtime's secret. */
|
|
23
|
+
export function trustProof(token: string, nonce: string): string {
|
|
24
|
+
return createHmac("sha256", token).update(nonce).digest("hex");
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function trustEndpointPath(agentDir: string, root: string): string {
|
|
28
|
+
const key: string = createHash("sha256").update(root).digest("hex");
|
|
29
|
+
return join(agentDir, "squire", "trust", `${key}.json`);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Bounded one-frame reader. Errors are delivered once; trailing/duplicate frames are ignored. */
|
|
33
|
+
export function readTrustFrame(socket: Socket, receive: (value: unknown) => void, fail: (error: Error) => void): void {
|
|
34
|
+
let buffer = "";
|
|
35
|
+
let done = false;
|
|
36
|
+
socket.setEncoding("utf8");
|
|
37
|
+
socket.on("data", (chunk: string) => {
|
|
38
|
+
if (done) return;
|
|
39
|
+
buffer += chunk;
|
|
40
|
+
if (Buffer.byteLength(buffer) > FRAME_LIMIT) {
|
|
41
|
+
done = true;
|
|
42
|
+
fail(new Error("project trust control frame is too large"));
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
const end: number = buffer.indexOf("\n");
|
|
46
|
+
if (end < 0) return;
|
|
47
|
+
done = true;
|
|
48
|
+
try {
|
|
49
|
+
receive(JSON.parse(buffer.slice(0, end)));
|
|
50
|
+
} catch {
|
|
51
|
+
fail(new Error("invalid project trust control frame"));
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
export function writeTrustFrame(socket: Socket, value: unknown): void {
|
|
56
|
+
socket.write(`${JSON.stringify(value)}\n`);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function endpointAt(agentDir: string, root: string): TrustEndpoint {
|
|
60
|
+
let value: TrustEndpoint | undefined;
|
|
61
|
+
try {
|
|
62
|
+
value = readState<TrustEndpoint>(trustEndpointPath(agentDir, root));
|
|
63
|
+
} catch (error) {
|
|
64
|
+
throw new Error(
|
|
65
|
+
`could not read root ${root} project trust service endpoint: ${String(error)}; nothing was launched`,
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
if (
|
|
69
|
+
!value ||
|
|
70
|
+
!Number.isInteger(value.port) ||
|
|
71
|
+
value.port < 1 ||
|
|
72
|
+
value.port > 65535 ||
|
|
73
|
+
typeof value.token !== "string"
|
|
74
|
+
)
|
|
75
|
+
throw new Error(
|
|
76
|
+
`root ${root} is not running an available project trust service; reopen that root and retry the launch`,
|
|
77
|
+
);
|
|
78
|
+
return value;
|
|
79
|
+
}
|
|
80
|
+
function responseAnswer(value: unknown, id: string): TrustAnswer {
|
|
81
|
+
const reply: TrustResponse = value as TrustResponse;
|
|
82
|
+
if (!reply || reply.id !== id) throw new Error("invalid project trust decision identity");
|
|
83
|
+
if (typeof reply.error === "string") throw new Error(reply.error);
|
|
84
|
+
const answer: TrustAnswer | undefined = reply.answer;
|
|
85
|
+
if (
|
|
86
|
+
answer &&
|
|
87
|
+
(("saved" in answer && typeof answer.saved === "boolean") ||
|
|
88
|
+
("label" in answer && typeof answer.label === "string"))
|
|
89
|
+
)
|
|
90
|
+
return answer;
|
|
91
|
+
throw new Error("invalid project trust decision");
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export async function requestRootTrust(
|
|
95
|
+
agentDir: string,
|
|
96
|
+
root: string,
|
|
97
|
+
question: TrustQuestion,
|
|
98
|
+
signal?: AbortSignal,
|
|
99
|
+
expiresAt = Date.now() + TRUST_TIMEOUT_MS,
|
|
100
|
+
): Promise<TrustDecision> {
|
|
101
|
+
trustStopped(signal);
|
|
102
|
+
const endpoint: TrustEndpoint = endpointAt(agentDir, root);
|
|
103
|
+
const lifetime: ReturnType<typeof trustLifetime> = trustLifetime(expiresAt, [signal]);
|
|
104
|
+
try {
|
|
105
|
+
return await exchange(
|
|
106
|
+
endpoint,
|
|
107
|
+
{ ...question, root, token: endpoint.token, id: randomUUID(), expiresAt },
|
|
108
|
+
lifetime.signal,
|
|
109
|
+
);
|
|
110
|
+
} finally {
|
|
111
|
+
lifetime.dispose();
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function authenticate(
|
|
116
|
+
socket: Socket,
|
|
117
|
+
token: string,
|
|
118
|
+
nonce: string,
|
|
119
|
+
ready: () => void,
|
|
120
|
+
fail: (error: Error) => void,
|
|
121
|
+
): void {
|
|
122
|
+
readTrustFrame(
|
|
123
|
+
socket,
|
|
124
|
+
(hello) => {
|
|
125
|
+
if (!hello || typeof hello !== "object" || !("proof" in hello) || hello.proof !== trustProof(token, nonce)) {
|
|
126
|
+
fail(new Error("root project trust endpoint failed authentication; nothing was launched"));
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
ready();
|
|
130
|
+
},
|
|
131
|
+
fail,
|
|
132
|
+
);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function exchange(endpoint: TrustEndpoint, request: TrustRequest, signal: AbortSignal): Promise<TrustDecision> {
|
|
136
|
+
return new Promise((resolve, reject) => {
|
|
137
|
+
const socket: Socket = connect({ host: "127.0.0.1", port: endpoint.port });
|
|
138
|
+
let settled = false;
|
|
139
|
+
const finish = (error?: Error, answer?: TrustAnswer): void => {
|
|
140
|
+
if (settled) return;
|
|
141
|
+
settled = true;
|
|
142
|
+
clearTimeout(timer);
|
|
143
|
+
signal.removeEventListener("abort", abort);
|
|
144
|
+
if (error) {
|
|
145
|
+
socket.destroy();
|
|
146
|
+
reject(error);
|
|
147
|
+
} else if (answer)
|
|
148
|
+
resolve({
|
|
149
|
+
answer,
|
|
150
|
+
assertLive: () => {
|
|
151
|
+
trustStopped(signal);
|
|
152
|
+
if (Date.now() >= request.expiresAt || socket.destroyed)
|
|
153
|
+
throw new Error("the project trust request expired or disconnected; nothing was launched");
|
|
154
|
+
},
|
|
155
|
+
release: () => socket.destroy(),
|
|
156
|
+
});
|
|
157
|
+
};
|
|
158
|
+
const abort = (): void =>
|
|
159
|
+
finish(
|
|
160
|
+
signal.reason instanceof Error ? signal.reason : new Error("the launch was aborted; nothing was launched"),
|
|
161
|
+
);
|
|
162
|
+
const timer: ReturnType<typeof setTimeout> = setTimeout(
|
|
163
|
+
() => finish(new Error(`root ${request.root} project trust service is unavailable; nothing was launched`)),
|
|
164
|
+
CONNECT_TIMEOUT_MS,
|
|
165
|
+
);
|
|
166
|
+
timer.unref();
|
|
167
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
168
|
+
if (signal.aborted) abort();
|
|
169
|
+
const nonce: string = randomUUID();
|
|
170
|
+
socket.on("connect", () => {
|
|
171
|
+
if (!settled) writeTrustFrame(socket, { nonce });
|
|
172
|
+
});
|
|
173
|
+
socket.on("error", () =>
|
|
174
|
+
finish(new Error(`root ${request.root} is not running an available project trust service; nothing was launched`)),
|
|
175
|
+
);
|
|
176
|
+
socket.on("close", () =>
|
|
177
|
+
finish(new Error(`root ${request.root} disappeared during project trust; nothing was launched`)),
|
|
178
|
+
);
|
|
179
|
+
authenticate(
|
|
180
|
+
socket,
|
|
181
|
+
endpoint.token,
|
|
182
|
+
nonce,
|
|
183
|
+
() => {
|
|
184
|
+
clearTimeout(timer);
|
|
185
|
+
if (settled) return;
|
|
186
|
+
writeTrustFrame(socket, request);
|
|
187
|
+
readTrustFrame(
|
|
188
|
+
socket,
|
|
189
|
+
(value) => {
|
|
190
|
+
try {
|
|
191
|
+
trustStopped(signal);
|
|
192
|
+
finish(undefined, responseAnswer(value, request.id));
|
|
193
|
+
} catch (error) {
|
|
194
|
+
finish(error instanceof Error ? error : new Error(String(error)));
|
|
195
|
+
}
|
|
196
|
+
},
|
|
197
|
+
(error) => finish(error),
|
|
198
|
+
);
|
|
199
|
+
},
|
|
200
|
+
(error) => finish(error),
|
|
201
|
+
);
|
|
202
|
+
});
|
|
203
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { isStarted, type Results, sessionIdOf } from "./results.ts";
|
|
2
|
+
import type { DelegateRow, MetadataViewport } from "./widget-data.ts";
|
|
3
|
+
import { LiveActivityReader } from "./widget-live.ts";
|
|
4
|
+
|
|
5
|
+
type Reader = Pick<LiveActivityReader, "read">;
|
|
6
|
+
|
|
7
|
+
/** Joins only a known viewport, never discovers membership or changes task facts. */
|
|
8
|
+
export async function joinActivities(
|
|
9
|
+
rows: DelegateRow[],
|
|
10
|
+
viewport: MetadataViewport,
|
|
11
|
+
results: Results,
|
|
12
|
+
reader: Reader = new LiveActivityReader(),
|
|
13
|
+
): Promise<void> {
|
|
14
|
+
await Promise.all(
|
|
15
|
+
rows.slice(viewport.offset, viewport.offset + viewport.limit).map(async (row) => {
|
|
16
|
+
if (!row.running) return;
|
|
17
|
+
row.activity = await reader.read(row.sessionId, row.launchId).catch(() => undefined);
|
|
18
|
+
// A terminal result/close/new launch may have arrived during I/O.
|
|
19
|
+
const current = results.running().find((record) => record.id === row.launchId);
|
|
20
|
+
const latest = results.list().findLast((record) => isStarted(record) && sessionIdOf(record) === row.sessionId);
|
|
21
|
+
if (!current || latest?.id !== row.launchId) row.activity = undefined;
|
|
22
|
+
}),
|
|
23
|
+
);
|
|
24
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { matchesSessionOwner } from "./session-owner.ts";
|
|
3
|
+
import type { TmuxClient } from "./tmux.ts";
|
|
4
|
+
import { ActivityCollector } from "./widget-activity.ts";
|
|
5
|
+
import { LIVE_LAUNCH_ENV, LiveActivityPublisher, liveLaunch } from "./widget-live.ts";
|
|
6
|
+
|
|
7
|
+
function observeLocator(
|
|
8
|
+
publisher: LiveActivityPublisher,
|
|
9
|
+
id: string,
|
|
10
|
+
token: string,
|
|
11
|
+
tmux: TmuxClient,
|
|
12
|
+
ctx: ExtensionContext,
|
|
13
|
+
): ReturnType<typeof setInterval> {
|
|
14
|
+
let reading = false;
|
|
15
|
+
const refresh = async (): Promise<void> => {
|
|
16
|
+
if (reading) return;
|
|
17
|
+
reading = true;
|
|
18
|
+
try {
|
|
19
|
+
const locator = await tmux.inspectPane?.().catch(() => undefined);
|
|
20
|
+
if (matchesSessionOwner(id, process.pid, token))
|
|
21
|
+
publisher.publishLocator(locator, token, ctx.sessionManager.getSessionFile());
|
|
22
|
+
} catch {
|
|
23
|
+
/* Optional observation cannot block task processing. */
|
|
24
|
+
} finally {
|
|
25
|
+
reading = false;
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
void refresh();
|
|
29
|
+
const timer: ReturnType<typeof setInterval> = setInterval(() => {
|
|
30
|
+
void refresh();
|
|
31
|
+
}, 1000);
|
|
32
|
+
timer.unref();
|
|
33
|
+
return timer;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Observe raw lifecycle after a positive startup owner gate; never grants task/action authority. */
|
|
37
|
+
export function registerActivityRuntime(
|
|
38
|
+
pi: ExtensionAPI,
|
|
39
|
+
canPublish: () => boolean,
|
|
40
|
+
tmux?: TmuxClient,
|
|
41
|
+
ownerToken?: string,
|
|
42
|
+
): () => void {
|
|
43
|
+
const seed: string | undefined = process.env[LIVE_LAUNCH_ENV];
|
|
44
|
+
let collector: ActivityCollector | undefined;
|
|
45
|
+
let publisher: LiveActivityPublisher | undefined;
|
|
46
|
+
let timer: ReturnType<typeof setInterval> | undefined;
|
|
47
|
+
|
|
48
|
+
const stop = (): void => {
|
|
49
|
+
if (timer) clearInterval(timer);
|
|
50
|
+
timer = undefined;
|
|
51
|
+
|
|
52
|
+
collector?.clear();
|
|
53
|
+
collector = undefined;
|
|
54
|
+
publisher?.stop();
|
|
55
|
+
publisher = undefined;
|
|
56
|
+
};
|
|
57
|
+
const publish = (immediate = true): void => publisher?.publish(collector?.snapshot(), immediate);
|
|
58
|
+
const clear = (): void => {
|
|
59
|
+
collector?.clear();
|
|
60
|
+
publish();
|
|
61
|
+
};
|
|
62
|
+
pi.on("session_start", (_event, ctx) => {
|
|
63
|
+
stop();
|
|
64
|
+
if (!canPublish()) return;
|
|
65
|
+
const id: string = ctx.sessionManager.getSessionId();
|
|
66
|
+
collector = new ActivityCollector();
|
|
67
|
+
publisher = new LiveActivityPublisher(id, liveLaunch(seed, id));
|
|
68
|
+
publish();
|
|
69
|
+
if (tmux && ownerToken) timer = observeLocator(publisher, id, ownerToken, tmux, ctx);
|
|
70
|
+
});
|
|
71
|
+
pi.on("tool_execution_start", (event) => {
|
|
72
|
+
collector?.start(event.toolCallId, event.toolName, event.parentToolCallId);
|
|
73
|
+
publish();
|
|
74
|
+
});
|
|
75
|
+
pi.on("tool_execution_end", (event) => {
|
|
76
|
+
collector?.end(event.toolCallId);
|
|
77
|
+
publish();
|
|
78
|
+
});
|
|
79
|
+
pi.on("message_start", (event) => {
|
|
80
|
+
if (event.message.role === "assistant") {
|
|
81
|
+
collector?.messageStart();
|
|
82
|
+
publish();
|
|
83
|
+
}
|
|
84
|
+
});
|
|
85
|
+
pi.on("message_update", (event) => {
|
|
86
|
+
if (event.message.role !== "assistant") return;
|
|
87
|
+
const update = event.assistantMessageEvent;
|
|
88
|
+
if (update.type === "text_delta") {
|
|
89
|
+
collector?.delta(update.delta);
|
|
90
|
+
publish(false);
|
|
91
|
+
} else if (update.type === "text_start") collector?.delta(" ");
|
|
92
|
+
});
|
|
93
|
+
pi.on("message_end", (event) => {
|
|
94
|
+
if (event.message.role === "assistant") {
|
|
95
|
+
collector?.messageEnd();
|
|
96
|
+
publish();
|
|
97
|
+
}
|
|
98
|
+
});
|
|
99
|
+
pi.on("agent_start", clear);
|
|
100
|
+
pi.on("agent_end", clear);
|
|
101
|
+
pi.on("agent_settled", clear);
|
|
102
|
+
pi.on("session_shutdown", stop);
|
|
103
|
+
return stop;
|
|
104
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
// Event-derived presentation only. No transcript replay, intent or task state.
|
|
2
|
+
import { stripVTControlCharacters } from "node:util";
|
|
3
|
+
|
|
4
|
+
export type Activity = { kind: "tools" | "response"; text: string };
|
|
5
|
+
export const ACTIVITY_TEXT_BYTES = 512;
|
|
6
|
+
const BUFFER_BYTES = 2048;
|
|
7
|
+
const MAX_CALLS = 256;
|
|
8
|
+
|
|
9
|
+
export function byteTail(value: string, max: number): string {
|
|
10
|
+
const characters: string[] = [...value.slice(-max * 2)];
|
|
11
|
+
let bytes = 0;
|
|
12
|
+
let first = characters.length;
|
|
13
|
+
while (first > 0) {
|
|
14
|
+
const size: number = Buffer.byteLength(characters[first - 1]);
|
|
15
|
+
if (bytes + size > max) break;
|
|
16
|
+
bytes += size;
|
|
17
|
+
first--;
|
|
18
|
+
}
|
|
19
|
+
return characters.slice(first).join("");
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Also applied at the reader/render boundary; foreign text never supplies terminal controls. */
|
|
23
|
+
export function activityText(value: string, max = ACTIVITY_TEXT_BYTES): string {
|
|
24
|
+
const bounded: string = byteTail(value, BUFFER_BYTES);
|
|
25
|
+
const clean: string = [...stripVTControlCharacters(bounded)]
|
|
26
|
+
.map((character) => {
|
|
27
|
+
const code: number = character.codePointAt(0) ?? 0;
|
|
28
|
+
return code < 32 || (code >= 127 && code <= 159) ? " " : character;
|
|
29
|
+
})
|
|
30
|
+
.join("")
|
|
31
|
+
.replace(/\s+/g, " ")
|
|
32
|
+
.trim();
|
|
33
|
+
return byteTail(clean, max);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
type Call = { name: string; parent?: string };
|
|
37
|
+
const LABELS: ReadonlyMap<string, string> = new Map([
|
|
38
|
+
["read", "reading…"],
|
|
39
|
+
["edit", "editing…"],
|
|
40
|
+
["write", "writing…"],
|
|
41
|
+
["bash", "command call…"],
|
|
42
|
+
]);
|
|
43
|
+
|
|
44
|
+
export class ActivityCollector {
|
|
45
|
+
private readonly calls = new Map<string, Call>();
|
|
46
|
+
private text = "";
|
|
47
|
+
private message = false;
|
|
48
|
+
private suppressed = false;
|
|
49
|
+
|
|
50
|
+
clear(): void {
|
|
51
|
+
this.calls.clear();
|
|
52
|
+
this.text = "";
|
|
53
|
+
this.message = false;
|
|
54
|
+
this.suppressed = false;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
start(id: string, name: string, parent?: string): void {
|
|
58
|
+
this.text = "";
|
|
59
|
+
if (this.calls.has(id) || this.suppressed) return;
|
|
60
|
+
if (this.calls.size >= MAX_CALLS || !this.validId(id) || (parent !== undefined && !this.validId(parent))) {
|
|
61
|
+
this.suppressed = true;
|
|
62
|
+
this.calls.clear();
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
this.calls.set(id, { name: activityText(name, 128), parent });
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
end(id: string): void {
|
|
69
|
+
this.calls.delete(id);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
messageStart(): void {
|
|
73
|
+
this.text = "";
|
|
74
|
+
this.message = true;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
delta(text: string): void {
|
|
78
|
+
if (this.message && !this.suppressed) this.text = byteTail(this.text + byteTail(text, BUFFER_BYTES), BUFFER_BYTES);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
messageEnd(): void {
|
|
82
|
+
this.text = "";
|
|
83
|
+
this.message = false;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
snapshot(): Activity | undefined {
|
|
87
|
+
if (this.suppressed) return;
|
|
88
|
+
if (this.calls.size) {
|
|
89
|
+
const parents = new Set([...this.calls.values()].map((call) => call.parent));
|
|
90
|
+
const leaves: Call[] = [...this.calls].filter(([id]) => !parents.has(id)).map(([, call]) => call);
|
|
91
|
+
const labels: string[] = [
|
|
92
|
+
...new Set(leaves.reverse().map((call) => LABELS.get(call.name) ?? `using ${call.name || "tool"}…`)),
|
|
93
|
+
];
|
|
94
|
+
return { kind: "tools", text: activityText(labels.slice(0, 2).join(" · ")) };
|
|
95
|
+
}
|
|
96
|
+
const text: string = activityText(this.text);
|
|
97
|
+
if (text) return { kind: "response", text };
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
private validId(id: string): boolean {
|
|
102
|
+
return id.length > 0 && Buffer.byteLength(id) <= 512;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
// Read-only exact-session ancestry and live navigation. No adoption or resume.
|
|
2
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import { type Identity, readIdentity } from "./identity.ts";
|
|
4
|
+
import { locateSession, recordedName } from "./results.ts";
|
|
5
|
+
import { matchesSessionOwner, sessionIsOwned } from "./session-owner.ts";
|
|
6
|
+
import type { PaneLocator, TmuxClient } from "./tmux.ts";
|
|
7
|
+
import { readTree, type TreeEntry } from "./tree-registry.ts";
|
|
8
|
+
import { LiveActivityReader, type LiveLocator } from "./widget-live.ts";
|
|
9
|
+
import { WidgetTitleMirrors } from "./widget-title.ts";
|
|
10
|
+
import { WidgetTitleFiles } from "./widget-title-file.ts";
|
|
11
|
+
import { listWindows } from "./windows.ts";
|
|
12
|
+
|
|
13
|
+
export type AncestorRow = { key: string; sessionId: string; identity: string; parent: boolean; title?: string };
|
|
14
|
+
type Ancestor = { sessionId: string; identity?: Identity };
|
|
15
|
+
|
|
16
|
+
/** Durable parent ids only. A broken/cyclic chain refuses rather than inventing ancestry. */
|
|
17
|
+
export function ancestorSessions(ctx: ExtensionContext): Ancestor[] {
|
|
18
|
+
const session: string = ctx.sessionManager.getSessionId();
|
|
19
|
+
const own: Identity | undefined = readIdentity(session);
|
|
20
|
+
if (!own) return [];
|
|
21
|
+
const found: Ancestor[] = [];
|
|
22
|
+
const seen: Set<string> = new Set([session]);
|
|
23
|
+
let child: Identity = own;
|
|
24
|
+
for (let depth: number = own.depth; depth > 0; depth--) {
|
|
25
|
+
const id: string = child.parent;
|
|
26
|
+
if (seen.has(id)) throw new Error("invalid ancestor identity chain");
|
|
27
|
+
seen.add(id);
|
|
28
|
+
if (id === own.root) {
|
|
29
|
+
if (depth !== 1) throw new Error("incomplete ancestor identity chain");
|
|
30
|
+
found.push({ sessionId: id });
|
|
31
|
+
return found.reverse();
|
|
32
|
+
}
|
|
33
|
+
const identity: Identity | undefined = readIdentity(id);
|
|
34
|
+
if (
|
|
35
|
+
!identity ||
|
|
36
|
+
identity.root !== own.root ||
|
|
37
|
+
identity.depth !== depth - 1 ||
|
|
38
|
+
identity.rootPlacement !== own.rootPlacement
|
|
39
|
+
)
|
|
40
|
+
throw new Error("ancestor identity unavailable");
|
|
41
|
+
found.push({ sessionId: id, identity });
|
|
42
|
+
child = identity;
|
|
43
|
+
}
|
|
44
|
+
throw new Error("ancestor identity chain does not reach root");
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export class AncestorView {
|
|
48
|
+
private readonly titles: WidgetTitleFiles = new WidgetTitleFiles();
|
|
49
|
+
private readonly mirrors: WidgetTitleMirrors = new WidgetTitleMirrors();
|
|
50
|
+
|
|
51
|
+
clear(): void {
|
|
52
|
+
this.titles.clear();
|
|
53
|
+
this.mirrors.clear();
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async read(ctx: ExtensionContext, reader: LiveActivityReader): Promise<AncestorRow[]> {
|
|
57
|
+
const ancestors: Ancestor[] = ancestorSessions(ctx);
|
|
58
|
+
let entries: TreeEntry[] = [];
|
|
59
|
+
try {
|
|
60
|
+
if (ancestors.length) entries = readTree(ancestors[0].sessionId, 20).entries;
|
|
61
|
+
} catch {
|
|
62
|
+
/* labels optional */
|
|
63
|
+
}
|
|
64
|
+
return Promise.all(
|
|
65
|
+
ancestors.map(async (ancestor: Ancestor, index: number): Promise<AncestorRow> => {
|
|
66
|
+
const entry: TreeEntry | undefined = entries.findLast((item) => item.sessionId === ancestor.sessionId);
|
|
67
|
+
const live: LiveLocator | undefined = await reader.locator(ancestor.sessionId);
|
|
68
|
+
const path: string | undefined =
|
|
69
|
+
live?.sessionFile ?? (entry?.launch ? locateSession(entry.launch, undefined) : undefined);
|
|
70
|
+
const name: string | undefined =
|
|
71
|
+
this.titles.read(path, ancestor.sessionId)?.name ?? this.mirrors.read(ancestor.sessionId);
|
|
72
|
+
let label = "root";
|
|
73
|
+
if (ancestor.identity) label = entry?.launch ? recordedName(entry.launch) : ancestor.identity.agent;
|
|
74
|
+
return {
|
|
75
|
+
key: `ancestor:${ancestor.sessionId}`,
|
|
76
|
+
sessionId: ancestor.sessionId,
|
|
77
|
+
identity: label,
|
|
78
|
+
parent: index === ancestors.length - 1,
|
|
79
|
+
title: name,
|
|
80
|
+
};
|
|
81
|
+
}),
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function sameServer(a: PaneLocator, b: PaneLocator): boolean {
|
|
87
|
+
return a.socket === b.socket && a.serverPid === b.serverPid && a.serverStarted === b.serverStarted;
|
|
88
|
+
}
|
|
89
|
+
function sameTarget(a: LiveLocator, b: LiveLocator): boolean {
|
|
90
|
+
return (
|
|
91
|
+
a.generation === b.generation &&
|
|
92
|
+
a.ownerToken === b.ownerToken &&
|
|
93
|
+
JSON.stringify(a.locator) === JSON.stringify(b.locator)
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Positive own-server + exact target-pane + id/name listing, not a launch snapshot. */
|
|
98
|
+
export async function verifyLiveWindow(tmux: TmuxClient, live: LiveLocator): Promise<boolean> {
|
|
99
|
+
const own: PaneLocator | undefined = await tmux.inspectPane?.();
|
|
100
|
+
if (!own || !sameServer(own, live.locator)) return false;
|
|
101
|
+
const pane: PaneLocator | undefined = await tmux.inspectPane?.(live.locator.paneId);
|
|
102
|
+
if (
|
|
103
|
+
!pane ||
|
|
104
|
+
pane.exited ||
|
|
105
|
+
!sameServer(pane, live.locator) ||
|
|
106
|
+
pane.windowId !== live.locator.windowId ||
|
|
107
|
+
pane.windowName !== live.locator.windowName
|
|
108
|
+
)
|
|
109
|
+
return false;
|
|
110
|
+
const windows = await listWindows(tmux);
|
|
111
|
+
return !!windows?.some((window) => window.id === pane.windowId && window.name === pane.windowName);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export async function switchAncestor(
|
|
115
|
+
ctx: ExtensionContext,
|
|
116
|
+
sessionId: string,
|
|
117
|
+
tmux: TmuxClient,
|
|
118
|
+
assertActive: () => void,
|
|
119
|
+
reader: LiveActivityReader = new LiveActivityReader(),
|
|
120
|
+
): Promise<void> {
|
|
121
|
+
assertActive();
|
|
122
|
+
if (!ancestorSessions(ctx).some((ancestor) => ancestor.sessionId === sessionId))
|
|
123
|
+
throw new Error("target is not a current ancestor");
|
|
124
|
+
const live: LiveLocator | undefined = await reader.locator(sessionId);
|
|
125
|
+
if (!live || !(await verifyLiveWindow(tmux, live))) throw new Error("no verified live window for this ancestor");
|
|
126
|
+
assertActive();
|
|
127
|
+
const own = await tmux.ownSession();
|
|
128
|
+
const client: string | undefined = own ? await tmux.clientFor(own.name) : undefined;
|
|
129
|
+
if (!client) throw new Error("no tmux client attached to this session");
|
|
130
|
+
const current: LiveLocator | undefined = await reader.locator(sessionId);
|
|
131
|
+
assertActive();
|
|
132
|
+
if (!current || !sameTarget(live, current) || !(await verifyLiveWindow(tmux, current)))
|
|
133
|
+
throw new Error("ancestor window changed or is unavailable");
|
|
134
|
+
assertActive();
|
|
135
|
+
if (!ancestorSessions(ctx).some((ancestor) => ancestor.sessionId === sessionId))
|
|
136
|
+
throw new Error("ancestor identity changed");
|
|
137
|
+
if (!matchesSessionOwner(sessionId, current.pid, current.ownerToken) || !sessionIsOwned(sessionId))
|
|
138
|
+
throw new Error("ancestor owner changed or is unavailable");
|
|
139
|
+
await tmux.switchTo(client, current.locator.windowId);
|
|
140
|
+
assertActive();
|
|
141
|
+
ctx.ui.notify(`delegate: switched to ancestor ${sessionId} (${current.locator.windowId})`, "info");
|
|
142
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// Optional live-window overrides for known local children, never semantic rewrites.
|
|
2
|
+
import { isStarted, type Results, type StartedRecorded, sessionIdOf } from "./results.ts";
|
|
3
|
+
import type { PaneLocator, TmuxClient, TmuxWindow } from "./tmux.ts";
|
|
4
|
+
import type { LiveActivityReader, LiveLocator } from "./widget-live.ts";
|
|
5
|
+
|
|
6
|
+
export async function currentChildWindows(
|
|
7
|
+
results: Results,
|
|
8
|
+
tmux: TmuxClient,
|
|
9
|
+
windows: TmuxWindow[] | undefined,
|
|
10
|
+
reader: LiveActivityReader,
|
|
11
|
+
): Promise<Map<string, { windowId: string; windowName: string }>> {
|
|
12
|
+
const found: Map<string, { windowId: string; windowName: string }> = new Map();
|
|
13
|
+
if (!windows?.length || !tmux.inspectPane) return found;
|
|
14
|
+
const latest: Map<string, StartedRecorded> = new Map(
|
|
15
|
+
results
|
|
16
|
+
.list()
|
|
17
|
+
.filter(isStarted)
|
|
18
|
+
.map((record) => [sessionIdOf(record), record]),
|
|
19
|
+
);
|
|
20
|
+
const candidates: StartedRecorded[] = [...latest.values()].filter((record) => !record.closed);
|
|
21
|
+
if (!candidates.length) return found;
|
|
22
|
+
const own: PaneLocator | undefined = await tmux.inspectPane().catch(() => undefined);
|
|
23
|
+
if (!own) return found;
|
|
24
|
+
await Promise.all(
|
|
25
|
+
candidates.map(async (record): Promise<void> => {
|
|
26
|
+
const live: LiveLocator | undefined = await reader.locator(sessionIdOf(record));
|
|
27
|
+
if (
|
|
28
|
+
!live ||
|
|
29
|
+
live.locator.socket !== own.socket ||
|
|
30
|
+
live.locator.serverPid !== own.serverPid ||
|
|
31
|
+
live.locator.serverStarted !== own.serverStarted
|
|
32
|
+
)
|
|
33
|
+
return;
|
|
34
|
+
const pane: PaneLocator | undefined = await tmux.inspectPane?.(live.locator.paneId).catch(() => undefined);
|
|
35
|
+
if (!pane || pane.exited || JSON.stringify(pane) !== JSON.stringify(live.locator)) return;
|
|
36
|
+
if (windows.some((window) => window.id === pane.windowId && window.name === pane.windowName))
|
|
37
|
+
found.set(record.id, { windowId: pane.windowId, windowName: pane.windowName });
|
|
38
|
+
}),
|
|
39
|
+
);
|
|
40
|
+
return found;
|
|
41
|
+
}
|