@losoft/taube 0.1.7 → 0.1.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/README.md +18 -214
- package/dist/cli.js +2778 -394
- package/package.json +3 -4
- package/plugins/taube/.claude-plugin/plugin.json +1 -1
- package/plugins/taube/.codex-plugin/plugin.json +2 -2
- package/plugins/taube/.grok-plugin/plugin.json +1 -1
- package/plugins/taube/skills/taube-dispatch/SKILL.md +21 -5
- package/.cursor-plugin/marketplace.json +0 -16
- package/plugins/taube/.cursor-plugin/plugin.json +0 -9
package/dist/cli.js
CHANGED
|
@@ -1,4 +1,18 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __returnValue = (v) => v;
|
|
4
|
+
function __exportSetter(name, newValue) {
|
|
5
|
+
this[name] = __returnValue.bind(null, newValue);
|
|
6
|
+
}
|
|
7
|
+
var __export = (target, all) => {
|
|
8
|
+
for (var name in all)
|
|
9
|
+
__defProp(target, name, {
|
|
10
|
+
get: all[name],
|
|
11
|
+
enumerable: true,
|
|
12
|
+
configurable: true,
|
|
13
|
+
set: __exportSetter.bind(all, name)
|
|
14
|
+
});
|
|
15
|
+
};
|
|
2
16
|
var __esm = (fn, res, err) => () => {
|
|
3
17
|
if (fn)
|
|
4
18
|
try {
|
|
@@ -11,6 +25,31 @@ var __esm = (fn, res, err) => () => {
|
|
|
11
25
|
return res;
|
|
12
26
|
};
|
|
13
27
|
|
|
28
|
+
// src/prompt.ts
|
|
29
|
+
import { readFile } from "node:fs/promises";
|
|
30
|
+
import { addAbortSignal } from "node:stream";
|
|
31
|
+
import { text } from "node:stream/consumers";
|
|
32
|
+
function promptSource(prompt, promptFile) {
|
|
33
|
+
if (prompt !== undefined && promptFile !== undefined)
|
|
34
|
+
throw new Error("Choose either --prompt or --prompt-file.");
|
|
35
|
+
if (promptFile !== undefined && !promptFile.trim())
|
|
36
|
+
throw new Error("--prompt-file needs a file path.");
|
|
37
|
+
return { prompt, promptFile };
|
|
38
|
+
}
|
|
39
|
+
async function readPrompt({ prompt, promptFile }, signal) {
|
|
40
|
+
let instruction;
|
|
41
|
+
if (prompt !== undefined)
|
|
42
|
+
instruction = prompt;
|
|
43
|
+
else if (promptFile !== undefined)
|
|
44
|
+
instruction = await readFile(promptFile, { encoding: "utf8", signal });
|
|
45
|
+
else
|
|
46
|
+
instruction = await text(signal ? addAbortSignal(signal, process.stdin) : process.stdin);
|
|
47
|
+
if (!instruction.trim())
|
|
48
|
+
throw new Error("Supply a non-empty instruction with --prompt, --prompt-file or stdin.");
|
|
49
|
+
return instruction;
|
|
50
|
+
}
|
|
51
|
+
var init_prompt = () => {};
|
|
52
|
+
|
|
14
53
|
// src/home.ts
|
|
15
54
|
import { homedir } from "node:os";
|
|
16
55
|
import { join, resolve } from "node:path";
|
|
@@ -19,82 +58,380 @@ function taubeHome() {
|
|
|
19
58
|
}
|
|
20
59
|
var init_home = () => {};
|
|
21
60
|
|
|
61
|
+
// src/session-channel.ts
|
|
62
|
+
import {
|
|
63
|
+
createCipheriv,
|
|
64
|
+
createDecipheriv,
|
|
65
|
+
randomBytes,
|
|
66
|
+
randomUUID
|
|
67
|
+
} from "node:crypto";
|
|
68
|
+
import { link, lstat, mkdir, readFile as readFile2, rm, writeFile } from "node:fs/promises";
|
|
69
|
+
import { connect, createServer } from "node:net";
|
|
70
|
+
import { join as join2 } from "node:path";
|
|
71
|
+
function endpointPath(id) {
|
|
72
|
+
if (!uuidPattern.test(id))
|
|
73
|
+
throw new Error("Expected a Taube session ID.");
|
|
74
|
+
return join2(taubeHome(), "channels", `${id}.json`);
|
|
75
|
+
}
|
|
76
|
+
async function checkDirectory(directory) {
|
|
77
|
+
const stat = await lstat(directory);
|
|
78
|
+
if (!stat.isDirectory() || process.getuid && (stat.uid !== process.getuid() || (stat.mode & 63) !== 0))
|
|
79
|
+
throw new Error("The session channel directory must be private to the current user.");
|
|
80
|
+
}
|
|
81
|
+
function validateText(text) {
|
|
82
|
+
if (Buffer.byteLength(text) > maxTextBytes)
|
|
83
|
+
throw new Error("Follow-up messages must be at most 1 MiB of UTF-8 text.");
|
|
84
|
+
if (!text.trim())
|
|
85
|
+
throw new Error("Follow-up messages require non-empty text.");
|
|
86
|
+
}
|
|
87
|
+
async function openSessionChannel(id, accept) {
|
|
88
|
+
const path = endpointPath(id);
|
|
89
|
+
const directory = join2(taubeHome(), "channels");
|
|
90
|
+
await mkdir(directory, { recursive: true, mode: 448 });
|
|
91
|
+
await checkDirectory(directory);
|
|
92
|
+
const key = randomBytes(32);
|
|
93
|
+
const incoming = new Set;
|
|
94
|
+
let closing = false;
|
|
95
|
+
const server = createServer((socket) => {
|
|
96
|
+
if (closing) {
|
|
97
|
+
socket.destroy();
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
incoming.add(socket);
|
|
101
|
+
const deadline = setTimeout(() => socket.destroy(), deadlineMs);
|
|
102
|
+
socket.on("error", () => socket.destroy());
|
|
103
|
+
socket.once("close", () => {
|
|
104
|
+
clearTimeout(deadline);
|
|
105
|
+
incoming.delete(socket);
|
|
106
|
+
});
|
|
107
|
+
let length;
|
|
108
|
+
async function readMessage() {
|
|
109
|
+
if (length === undefined) {
|
|
110
|
+
const header = socket.read(4);
|
|
111
|
+
if (!header)
|
|
112
|
+
return;
|
|
113
|
+
length = header.length === 4 ? header.readUInt32BE() : 0;
|
|
114
|
+
if (length < overhead || length > maxTextBytes + overhead) {
|
|
115
|
+
socket.destroy();
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
const bytes = socket.read(length);
|
|
120
|
+
if (!bytes)
|
|
121
|
+
return;
|
|
122
|
+
if (bytes.length !== length) {
|
|
123
|
+
socket.destroy();
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
socket.off("readable", readMessage);
|
|
127
|
+
try {
|
|
128
|
+
const decipher = createDecipheriv("aes-256-gcm", key, bytes.subarray(0, nonceBytes));
|
|
129
|
+
decipher.setAuthTag(bytes.subarray(-tagBytes));
|
|
130
|
+
const plain = Buffer.concat([
|
|
131
|
+
decipher.update(bytes.subarray(nonceBytes, -tagBytes)),
|
|
132
|
+
decipher.final()
|
|
133
|
+
]);
|
|
134
|
+
const text = new TextDecoder("utf-8", {
|
|
135
|
+
fatal: true,
|
|
136
|
+
ignoreBOM: true
|
|
137
|
+
}).decode(plain.subarray(receiptBytes));
|
|
138
|
+
const request = text ? { type: "message", text } : { type: "compact" };
|
|
139
|
+
if (request.type === "message")
|
|
140
|
+
validateText(request.text);
|
|
141
|
+
incoming.delete(socket);
|
|
142
|
+
const messageId = randomUUID();
|
|
143
|
+
const accepted = !closing && await accept(request, messageId);
|
|
144
|
+
socket.end(Buffer.concat([
|
|
145
|
+
Buffer.from([accepted === "unsupported" ? 2 : Number(accepted)]),
|
|
146
|
+
plain.subarray(0, receiptBytes),
|
|
147
|
+
Buffer.from(messageId)
|
|
148
|
+
]), () => socket.destroy());
|
|
149
|
+
} catch {
|
|
150
|
+
socket.destroy();
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
socket.on("readable", readMessage);
|
|
154
|
+
});
|
|
155
|
+
server.maxConnections = 32;
|
|
156
|
+
await new Promise((resolve, reject) => {
|
|
157
|
+
server.once("error", reject);
|
|
158
|
+
server.listen(0, "127.0.0.1", () => {
|
|
159
|
+
server.off("error", reject);
|
|
160
|
+
resolve();
|
|
161
|
+
});
|
|
162
|
+
});
|
|
163
|
+
function stop() {
|
|
164
|
+
closing = true;
|
|
165
|
+
const stopped = new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
|
|
166
|
+
for (const socket of incoming)
|
|
167
|
+
socket.destroy();
|
|
168
|
+
return stopped;
|
|
169
|
+
}
|
|
170
|
+
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
171
|
+
let published = false;
|
|
172
|
+
try {
|
|
173
|
+
try {
|
|
174
|
+
const { port } = server.address();
|
|
175
|
+
await writeFile(temporary, JSON.stringify({
|
|
176
|
+
port,
|
|
177
|
+
key: key.toString("hex"),
|
|
178
|
+
trackedReceipts: true,
|
|
179
|
+
compactRequests: true
|
|
180
|
+
}), { mode: 384, flag: "wx" });
|
|
181
|
+
await link(temporary, path);
|
|
182
|
+
published = true;
|
|
183
|
+
} finally {
|
|
184
|
+
await rm(temporary, { force: true });
|
|
185
|
+
}
|
|
186
|
+
} catch (error) {
|
|
187
|
+
await stop();
|
|
188
|
+
if (published)
|
|
189
|
+
await rm(path, { force: true });
|
|
190
|
+
throw error;
|
|
191
|
+
}
|
|
192
|
+
let stopped;
|
|
193
|
+
return {
|
|
194
|
+
close() {
|
|
195
|
+
stopped ??= Promise.all([stop(), rm(path, { force: true })]).then(() => {});
|
|
196
|
+
return stopped;
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
function sendSessionMessage(id, text) {
|
|
201
|
+
return sendFollowUp(id, { type: "message", text });
|
|
202
|
+
}
|
|
203
|
+
function compactSession(id) {
|
|
204
|
+
return sendFollowUp(id, { type: "compact" });
|
|
205
|
+
}
|
|
206
|
+
async function sendFollowUp(id, request) {
|
|
207
|
+
const path = endpointPath(id);
|
|
208
|
+
if (request.type === "message")
|
|
209
|
+
validateText(request.text);
|
|
210
|
+
let port;
|
|
211
|
+
let key;
|
|
212
|
+
let tracked;
|
|
213
|
+
let compactRequests;
|
|
214
|
+
try {
|
|
215
|
+
await checkDirectory(join2(taubeHome(), "channels"));
|
|
216
|
+
const endpoint = JSON.parse(await readFile2(path, "utf8"));
|
|
217
|
+
if (!Number.isInteger(endpoint.port) || endpoint.port < 1 || endpoint.port > 65535 || typeof endpoint.key !== "string" || !/^[\da-f]{64}$/.test(endpoint.key))
|
|
218
|
+
throw new Error(closedMessage);
|
|
219
|
+
port = endpoint.port;
|
|
220
|
+
key = Buffer.from(endpoint.key, "hex");
|
|
221
|
+
tracked = endpoint.trackedReceipts === true;
|
|
222
|
+
compactRequests = endpoint.compactRequests === true && tracked;
|
|
223
|
+
} catch {
|
|
224
|
+
throw new Error(closedMessage);
|
|
225
|
+
}
|
|
226
|
+
if (request.type === "compact" && !compactRequests)
|
|
227
|
+
throw new Error("This session runner does not support compact requests.");
|
|
228
|
+
const nonce = randomBytes(nonceBytes);
|
|
229
|
+
const receipt = randomBytes(receiptBytes);
|
|
230
|
+
const cipher = createCipheriv("aes-256-gcm", key, nonce);
|
|
231
|
+
const body = Buffer.concat([
|
|
232
|
+
nonce,
|
|
233
|
+
cipher.update(receipt),
|
|
234
|
+
cipher.update(request.type === "message" ? request.text : "", "utf8"),
|
|
235
|
+
cipher.final(),
|
|
236
|
+
cipher.getAuthTag()
|
|
237
|
+
]);
|
|
238
|
+
const length = Buffer.alloc(4);
|
|
239
|
+
length.writeUInt32BE(body.length);
|
|
240
|
+
return new Promise((resolve, reject) => {
|
|
241
|
+
const socket = connect(port, "127.0.0.1");
|
|
242
|
+
const deadline = setTimeout(() => socket.destroy(), deadlineMs);
|
|
243
|
+
socket.once("connect", () => socket.write(Buffer.concat([length, body])));
|
|
244
|
+
socket.on("readable", () => {
|
|
245
|
+
const length = 1 + receiptBytes + (tracked ? uuidBytes : 0);
|
|
246
|
+
const reply = socket.read(length);
|
|
247
|
+
if (!reply)
|
|
248
|
+
return;
|
|
249
|
+
if (reply.length === length && reply.subarray(1, 1 + receiptBytes).equals(receipt)) {
|
|
250
|
+
const messageId = tracked ? reply.toString("utf8", 1 + receiptBytes) : undefined;
|
|
251
|
+
if (reply[0] === 1 && (messageId === undefined || uuidPattern.test(messageId)))
|
|
252
|
+
resolve(messageId);
|
|
253
|
+
if (reply[0] === 0)
|
|
254
|
+
reject(new Error("Session declined the follow-up message."));
|
|
255
|
+
if (reply[0] === 2 && request.type === "compact")
|
|
256
|
+
reject(new Error("The adapter does not advertise /compact for this session."));
|
|
257
|
+
}
|
|
258
|
+
socket.destroy();
|
|
259
|
+
});
|
|
260
|
+
socket.once("error", (error) => {
|
|
261
|
+
reject(new Error(error.code === "ECONNREFUSED" ? closedMessage : unknownDelivery));
|
|
262
|
+
});
|
|
263
|
+
socket.once("close", () => {
|
|
264
|
+
clearTimeout(deadline);
|
|
265
|
+
reject(new Error(unknownDelivery));
|
|
266
|
+
});
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
var maxTextBytes, nonceBytes = 12, tagBytes = 16, receiptBytes = 16, uuidBytes = 36, uuidPattern, overhead, deadlineMs = 5000, closedMessage = "Session is not accepting follow-up messages.", unknownDelivery = "No queue receipt was received; delivery is unknown.";
|
|
270
|
+
var init_session_channel = __esm(() => {
|
|
271
|
+
init_home();
|
|
272
|
+
maxTextBytes = 1024 * 1024;
|
|
273
|
+
uuidPattern = /^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i;
|
|
274
|
+
overhead = nonceBytes + tagBytes + receiptBytes;
|
|
275
|
+
});
|
|
276
|
+
|
|
22
277
|
// src/sessions.ts
|
|
23
|
-
import { randomUUID } from "node:crypto";
|
|
278
|
+
import { createHash, randomUUID as randomUUID2 } from "node:crypto";
|
|
24
279
|
import {
|
|
25
|
-
|
|
280
|
+
link as link2,
|
|
281
|
+
mkdir as mkdir2,
|
|
26
282
|
readdir,
|
|
27
|
-
readFile,
|
|
283
|
+
readFile as readFile3,
|
|
284
|
+
readlink,
|
|
28
285
|
rename,
|
|
29
|
-
rm,
|
|
30
|
-
writeFile
|
|
286
|
+
rm as rm2,
|
|
287
|
+
writeFile as writeFile2
|
|
31
288
|
} from "node:fs/promises";
|
|
32
|
-
import { join as
|
|
33
|
-
|
|
289
|
+
import { join as join3 } from "node:path";
|
|
290
|
+
function initialSelection({
|
|
291
|
+
model = null,
|
|
292
|
+
effort = null
|
|
293
|
+
} = {}) {
|
|
294
|
+
return {
|
|
295
|
+
requested: { model, effort },
|
|
296
|
+
confirmed: { model: null, effort: null }
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
function sessionsDirectory() {
|
|
300
|
+
return join3(taubeHome(), "sessions");
|
|
301
|
+
}
|
|
302
|
+
function sessionRecordName({
|
|
303
|
+
id,
|
|
304
|
+
dispatcher,
|
|
305
|
+
requestId
|
|
306
|
+
}) {
|
|
307
|
+
const basename = requestId === undefined ? id : `request-${createHash("sha256").update(JSON.stringify([dispatcher, requestId])).digest("hex")}`;
|
|
308
|
+
return `${basename}.json`;
|
|
309
|
+
}
|
|
310
|
+
function sessionRecordPath(session) {
|
|
311
|
+
return join3(sessionsDirectory(), sessionRecordName(session));
|
|
312
|
+
}
|
|
313
|
+
function findSessionByRequestId(sessions, requestId, dispatcher) {
|
|
314
|
+
const matches = sessions.filter((session) => session.requestId === requestId && (dispatcher === null || session.dispatcher === dispatcher));
|
|
315
|
+
if (matches.length > 1)
|
|
316
|
+
throw new Error(`Request ID ${requestId} is ambiguous in the selected scope. Select a dispatcher with --dispatcher ID.`);
|
|
317
|
+
return matches[0];
|
|
318
|
+
}
|
|
319
|
+
function matchesStatus(session, status) {
|
|
320
|
+
return status === undefined || (status === "finished" ? session.status !== "running" : session.status === status);
|
|
321
|
+
}
|
|
322
|
+
async function linuxProcessView() {
|
|
34
323
|
if (process.platform !== "linux")
|
|
35
324
|
return;
|
|
36
325
|
try {
|
|
37
|
-
const [
|
|
38
|
-
|
|
39
|
-
|
|
326
|
+
const [boot, pidNamespace, timeNamespace, status] = await Promise.all([
|
|
327
|
+
readFile3("/proc/sys/kernel/random/boot_id", "utf8"),
|
|
328
|
+
readlink("/proc/self/ns/pid"),
|
|
329
|
+
readlink("/proc/self/ns/time").catch(() => {
|
|
330
|
+
return;
|
|
331
|
+
}),
|
|
332
|
+
readFile3("/proc/self/status", "utf8")
|
|
40
333
|
]);
|
|
41
|
-
const
|
|
334
|
+
const pids = /^NSpid:(.*)$/m.exec(status)?.[1]?.trim();
|
|
335
|
+
if (pids === String(process.pid) && boot.trim() && pidNamespace)
|
|
336
|
+
return { boot: boot.trim(), pidNamespace, timeNamespace };
|
|
337
|
+
} catch {}
|
|
338
|
+
}
|
|
339
|
+
async function linuxProcessStat(pid) {
|
|
340
|
+
const stat = await readFile3(`/proc/${pid}/stat`, "utf8");
|
|
341
|
+
const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
|
|
342
|
+
if (/^\d+$/.test(fields[19]))
|
|
42
343
|
return {
|
|
43
|
-
|
|
344
|
+
start: fields[19],
|
|
44
345
|
zombie: fields[0] === "Z" || fields[0] === "X"
|
|
45
346
|
};
|
|
46
|
-
|
|
47
|
-
|
|
347
|
+
}
|
|
348
|
+
async function currentOwner() {
|
|
349
|
+
const pid = process.pid;
|
|
350
|
+
const view = await linuxProcessView();
|
|
351
|
+
if (view) {
|
|
352
|
+
const stat = await linuxProcessStat(pid).catch(() => {
|
|
353
|
+
return;
|
|
354
|
+
});
|
|
355
|
+
if (stat)
|
|
356
|
+
return {
|
|
357
|
+
pid,
|
|
358
|
+
identity: `${view.boot}:${stat.start}`,
|
|
359
|
+
pidNamespace: view.pidNamespace,
|
|
360
|
+
timeNamespace: view.timeNamespace
|
|
361
|
+
};
|
|
48
362
|
}
|
|
363
|
+
return { pid, identity: null };
|
|
49
364
|
}
|
|
50
|
-
async function
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
365
|
+
async function ownerIsDead(owner) {
|
|
366
|
+
if (!owner?.pidNamespace || typeof owner.identity !== "string" || !Number.isSafeInteger(owner.pid) || owner.pid <= 0)
|
|
367
|
+
return false;
|
|
368
|
+
const identity = /^([^:]+):(\d+)$/.exec(owner.identity);
|
|
369
|
+
if (!identity)
|
|
370
|
+
return false;
|
|
371
|
+
const [, boot, start] = identity;
|
|
372
|
+
const view = await linuxProcessView();
|
|
373
|
+
if (!view || owner.pidNamespace !== view.pidNamespace || boot !== view.boot)
|
|
374
|
+
return false;
|
|
54
375
|
try {
|
|
55
|
-
|
|
56
|
-
return
|
|
376
|
+
const stat = await linuxProcessStat(owner.pid);
|
|
377
|
+
return !!stat && (stat.zombie || !!owner.timeNamespace && owner.timeNamespace === view.timeNamespace && start !== stat.start);
|
|
57
378
|
} catch (error) {
|
|
58
|
-
if (error.code
|
|
379
|
+
if (error.code !== "ENOENT")
|
|
59
380
|
return false;
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
381
|
+
try {
|
|
382
|
+
process.kill(owner.pid, 0);
|
|
383
|
+
} catch (error) {
|
|
384
|
+
return error.code === "ESRCH";
|
|
385
|
+
}
|
|
386
|
+
return false;
|
|
63
387
|
}
|
|
64
388
|
}
|
|
65
|
-
async function save(path, value) {
|
|
66
|
-
const temporary = `${path}.${
|
|
389
|
+
async function save(path, value, publish = rename) {
|
|
390
|
+
const temporary = `${path}.${randomUUID2()}.tmp`;
|
|
67
391
|
try {
|
|
68
|
-
await
|
|
392
|
+
await writeFile2(temporary, JSON.stringify(value), {
|
|
69
393
|
mode: 384,
|
|
70
394
|
flag: "wx"
|
|
71
395
|
});
|
|
72
|
-
await
|
|
396
|
+
await publish(temporary, path);
|
|
73
397
|
} finally {
|
|
74
|
-
await
|
|
398
|
+
await rm2(temporary, { force: true });
|
|
75
399
|
}
|
|
76
400
|
}
|
|
77
|
-
async function startSession(target, cwd, dispatcher) {
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
};
|
|
401
|
+
async function startSession(target, cwd, dispatcher, id = randomUUID2(), {
|
|
402
|
+
requestId,
|
|
403
|
+
resumedFromSessionId,
|
|
404
|
+
selection = initialSelection(),
|
|
405
|
+
dispatcherCwd,
|
|
406
|
+
dispatcherProject
|
|
407
|
+
} = {}) {
|
|
408
|
+
const directory = sessionsDirectory();
|
|
409
|
+
await mkdir2(directory, { mode: 448, recursive: true });
|
|
410
|
+
const path = sessionRecordPath({ id, dispatcher, requestId });
|
|
411
|
+
const owner = await currentOwner();
|
|
86
412
|
let session = {
|
|
87
413
|
id,
|
|
414
|
+
requestId,
|
|
415
|
+
resumedFromSessionId,
|
|
88
416
|
acpSessionId: null,
|
|
417
|
+
selection,
|
|
89
418
|
target,
|
|
90
419
|
cwd,
|
|
91
420
|
dispatcher,
|
|
421
|
+
dispatcherCwd,
|
|
422
|
+
dispatcherProject,
|
|
92
423
|
status: "running",
|
|
93
424
|
startedAt: new Date().toISOString(),
|
|
94
425
|
finishedAt: null,
|
|
95
426
|
exitCode: null
|
|
96
427
|
};
|
|
97
|
-
|
|
428
|
+
try {
|
|
429
|
+
await save(path, { session, owner }, requestId === undefined ? rename : link2);
|
|
430
|
+
} catch (error) {
|
|
431
|
+
if (requestId !== undefined && error.code === "EEXIST")
|
|
432
|
+
throw new Error(`Request ID ${requestId} already exists for this dispatcher.`);
|
|
433
|
+
throw error;
|
|
434
|
+
}
|
|
98
435
|
let pending = Promise.resolve();
|
|
99
436
|
function update(changes) {
|
|
100
437
|
session = { ...session, ...changes };
|
|
@@ -105,15 +442,42 @@ async function startSession(target, cwd, dispatcher) {
|
|
|
105
442
|
}
|
|
106
443
|
return {
|
|
107
444
|
id,
|
|
108
|
-
|
|
109
|
-
|
|
445
|
+
get acpSessionId() {
|
|
446
|
+
return session.acpSessionId;
|
|
447
|
+
},
|
|
448
|
+
get selection() {
|
|
449
|
+
return session.selection;
|
|
450
|
+
},
|
|
451
|
+
attach: (acpSessionId, confirmed = session.selection.confirmed) => update({ acpSessionId, selection: { ...session.selection, confirmed } }),
|
|
452
|
+
confirm: (confirmed) => update({ selection: { ...session.selection, confirmed } }),
|
|
453
|
+
reportContextWindow({ used, size }) {
|
|
454
|
+
if (session.status !== "running" || !Number.isSafeInteger(used) || used < 0 || !Number.isSafeInteger(size) || size <= 0 || session.contextWindow?.used === used && session.contextWindow.size === size)
|
|
455
|
+
return;
|
|
456
|
+
return update({ contextWindow: { used, size } });
|
|
457
|
+
},
|
|
458
|
+
finish: (status, exitCode, details = {}) => update({
|
|
459
|
+
status,
|
|
460
|
+
exitCode,
|
|
461
|
+
...details,
|
|
462
|
+
finishedAt: new Date().toISOString()
|
|
463
|
+
})
|
|
110
464
|
};
|
|
111
465
|
}
|
|
112
|
-
async function
|
|
113
|
-
|
|
466
|
+
async function readCurrentSession(path) {
|
|
467
|
+
let contents = await readFile3(path, "utf8");
|
|
468
|
+
while (true) {
|
|
469
|
+
const { session, owner } = JSON.parse(contents);
|
|
470
|
+
session.selection ??= initialSelection();
|
|
471
|
+
if (session.status !== "running" || !await ownerIsDead(owner))
|
|
472
|
+
return session;
|
|
473
|
+
const latest = await readFile3(path, "utf8");
|
|
474
|
+
if (latest === contents)
|
|
475
|
+
return { ...session, status: "interrupted" };
|
|
476
|
+
contents = latest;
|
|
477
|
+
}
|
|
114
478
|
}
|
|
115
479
|
async function listSessions() {
|
|
116
|
-
const directory =
|
|
480
|
+
const directory = sessionsDirectory();
|
|
117
481
|
let names;
|
|
118
482
|
try {
|
|
119
483
|
names = await readdir(directory);
|
|
@@ -126,16 +490,13 @@ async function listSessions() {
|
|
|
126
490
|
for (const name of names) {
|
|
127
491
|
if (!name.endsWith(".json"))
|
|
128
492
|
continue;
|
|
129
|
-
const path =
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
if (
|
|
134
|
-
|
|
135
|
-
await save(path, entry);
|
|
136
|
-
}
|
|
493
|
+
const path = join3(directory, name);
|
|
494
|
+
try {
|
|
495
|
+
sessions.push(await readCurrentSession(path));
|
|
496
|
+
} catch (error) {
|
|
497
|
+
if (error.code !== "ENOENT")
|
|
498
|
+
throw error;
|
|
137
499
|
}
|
|
138
|
-
sessions.push(entry.session);
|
|
139
500
|
}
|
|
140
501
|
return sessions.sort((a, b) => b.startedAt.localeCompare(a.startedAt) || a.id.localeCompare(b.id));
|
|
141
502
|
}
|
|
@@ -143,51 +504,115 @@ var init_sessions = __esm(() => {
|
|
|
143
504
|
init_home();
|
|
144
505
|
});
|
|
145
506
|
|
|
146
|
-
// src/
|
|
147
|
-
import {
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
507
|
+
// src/session-watch.ts
|
|
508
|
+
import { watch } from "node:fs";
|
|
509
|
+
async function* watchSessions({
|
|
510
|
+
dispatcher,
|
|
511
|
+
id,
|
|
512
|
+
once,
|
|
513
|
+
signal,
|
|
514
|
+
snapshots,
|
|
515
|
+
status
|
|
516
|
+
}) {
|
|
517
|
+
if (signal?.aborted)
|
|
518
|
+
return;
|
|
519
|
+
const directory = sessionsDirectory();
|
|
520
|
+
let dirty = true;
|
|
521
|
+
let resume;
|
|
522
|
+
function wake() {
|
|
523
|
+
dirty = true;
|
|
524
|
+
resume?.();
|
|
159
525
|
}
|
|
526
|
+
let watcher;
|
|
527
|
+
let reconcile;
|
|
528
|
+
function subscribe() {
|
|
529
|
+
try {
|
|
530
|
+
watcher = watch(directory, (_event, name) => {
|
|
531
|
+
if (!name || name.endsWith(".json"))
|
|
532
|
+
wake();
|
|
533
|
+
});
|
|
534
|
+
watcher.on("error", () => {
|
|
535
|
+
watcher?.close();
|
|
536
|
+
watcher = undefined;
|
|
537
|
+
clearTimeout(reconcile);
|
|
538
|
+
reconcile = setTimeout(wake, 100);
|
|
539
|
+
});
|
|
540
|
+
} catch {}
|
|
541
|
+
}
|
|
542
|
+
function close() {
|
|
543
|
+
watcher?.close();
|
|
544
|
+
clearTimeout(reconcile);
|
|
545
|
+
signal?.removeEventListener("abort", close);
|
|
546
|
+
wake();
|
|
547
|
+
}
|
|
548
|
+
signal?.addEventListener("abort", close, { once: true });
|
|
160
549
|
try {
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
550
|
+
let previous;
|
|
551
|
+
while (!signal?.aborted) {
|
|
552
|
+
if (!dirty)
|
|
553
|
+
await new Promise((resolve) => {
|
|
554
|
+
resume = resolve;
|
|
555
|
+
});
|
|
556
|
+
resume = undefined;
|
|
557
|
+
if (signal?.aborted)
|
|
558
|
+
return;
|
|
559
|
+
if (!watcher)
|
|
560
|
+
subscribe();
|
|
561
|
+
clearTimeout(reconcile);
|
|
562
|
+
reconcile = setTimeout(wake, watcher ? 5000 : 100);
|
|
563
|
+
dirty = false;
|
|
564
|
+
const sessions = (await listSessions()).filter((session) => (dispatcher === null || session.dispatcher === dispatcher) && (id === undefined || session.id === id));
|
|
565
|
+
if (signal?.aborted)
|
|
566
|
+
return;
|
|
567
|
+
if (id !== undefined && sessions.length === 0)
|
|
568
|
+
throw new Error(`Session ${id} was not found in the selected scope.`);
|
|
569
|
+
if (snapshots) {
|
|
570
|
+
yield { type: "snapshot", sessions };
|
|
571
|
+
continue;
|
|
572
|
+
}
|
|
573
|
+
const baseline = previous;
|
|
574
|
+
const current = new Map(sessions.map((session) => [session.id, session]));
|
|
575
|
+
previous = current;
|
|
576
|
+
const removed = baseline && Array.from(baseline.keys()).some((id) => !current.has(id));
|
|
577
|
+
if (!once && (!baseline || removed)) {
|
|
578
|
+
yield {
|
|
579
|
+
type: "snapshot",
|
|
580
|
+
sessions: sessions.filter((session) => matchesStatus(session, status))
|
|
581
|
+
};
|
|
582
|
+
continue;
|
|
583
|
+
}
|
|
584
|
+
for (const session of sessions) {
|
|
585
|
+
if (signal?.aborted)
|
|
586
|
+
return;
|
|
587
|
+
if (!matchesStatus(session, status)) {
|
|
588
|
+
if (once && id !== undefined && session.status !== "running")
|
|
589
|
+
throw new Error(`Session ${id} is ${session.status} and cannot match --status ${status}.`);
|
|
590
|
+
continue;
|
|
591
|
+
}
|
|
592
|
+
if (!baseline && (id === undefined || session.status === "running"))
|
|
593
|
+
continue;
|
|
594
|
+
const before = baseline?.get(session.id);
|
|
595
|
+
if (before?.status === session.status && (once || before.contextWindow?.used === session.contextWindow?.used && before.contextWindow?.size === session.contextWindow?.size))
|
|
596
|
+
continue;
|
|
597
|
+
if (once)
|
|
598
|
+
close();
|
|
599
|
+
yield { type: "status", session };
|
|
600
|
+
if (once)
|
|
601
|
+
return;
|
|
602
|
+
}
|
|
603
|
+
}
|
|
179
604
|
} finally {
|
|
180
|
-
|
|
605
|
+
close();
|
|
181
606
|
}
|
|
182
|
-
return result;
|
|
183
607
|
}
|
|
184
|
-
var
|
|
185
|
-
|
|
608
|
+
var init_session_watch = __esm(() => {
|
|
609
|
+
init_sessions();
|
|
186
610
|
});
|
|
187
611
|
|
|
188
|
-
// src/
|
|
612
|
+
// src/adapter.ts
|
|
189
613
|
import { accessSync, constants as fsConstants, statSync } from "node:fs";
|
|
190
|
-
import {
|
|
614
|
+
import { access, readFile as readFile4 } from "node:fs/promises";
|
|
615
|
+
import { delimiter, dirname, join as join4, resolve as resolve2 } from "node:path";
|
|
191
616
|
function executableOnPath(command) {
|
|
192
617
|
const extensions = process.platform === "win32" ? (process.env.PATHEXT ?? ".EXE;.CMD;.BAT").split(";") : [""];
|
|
193
618
|
for (const directory of (process.env.PATH ?? "").split(delimiter)) {
|
|
@@ -201,126 +626,6 @@ function executableOnPath(command) {
|
|
|
201
626
|
}
|
|
202
627
|
}
|
|
203
628
|
}
|
|
204
|
-
async function surfaces() {
|
|
205
|
-
const entries = await Promise.all(targets.map(async ({ id, profile, effortOption, launcher }) => ({
|
|
206
|
-
id,
|
|
207
|
-
profile,
|
|
208
|
-
effortOption,
|
|
209
|
-
launcher: {
|
|
210
|
-
command: launcher,
|
|
211
|
-
onPath: Boolean(executableOnPath(launcher))
|
|
212
|
-
},
|
|
213
|
-
...await readAuth(id)
|
|
214
|
-
})));
|
|
215
|
-
return { targets: entries };
|
|
216
|
-
}
|
|
217
|
-
var targets;
|
|
218
|
-
var init_targets = __esm(() => {
|
|
219
|
-
init_auth_state();
|
|
220
|
-
targets = [
|
|
221
|
-
{
|
|
222
|
-
id: "codex",
|
|
223
|
-
profile: "codex",
|
|
224
|
-
launcher: "codex-acp",
|
|
225
|
-
effortOption: "reasoning_effort"
|
|
226
|
-
},
|
|
227
|
-
{
|
|
228
|
-
id: "claude",
|
|
229
|
-
profile: "claude",
|
|
230
|
-
launcher: "claude-agent-acp",
|
|
231
|
-
effortOption: "effort"
|
|
232
|
-
},
|
|
233
|
-
{
|
|
234
|
-
id: "grok",
|
|
235
|
-
profile: "grok-build",
|
|
236
|
-
launcher: "grok",
|
|
237
|
-
effortOption: "reasoning_effort"
|
|
238
|
-
},
|
|
239
|
-
{
|
|
240
|
-
id: "cursor",
|
|
241
|
-
profile: "cursor",
|
|
242
|
-
launcher: "cursor-agent",
|
|
243
|
-
effortOption: null
|
|
244
|
-
}
|
|
245
|
-
];
|
|
246
|
-
});
|
|
247
|
-
|
|
248
|
-
// src/auth-check.ts
|
|
249
|
-
import { execFile } from "node:child_process";
|
|
250
|
-
import { stripVTControlCharacters } from "node:util";
|
|
251
|
-
function probe(target, command, args) {
|
|
252
|
-
return new Promise((resolve, reject) => {
|
|
253
|
-
const child = execFile(command, args, {
|
|
254
|
-
encoding: "utf8",
|
|
255
|
-
timeout: 8000,
|
|
256
|
-
killSignal: "SIGKILL",
|
|
257
|
-
maxBuffer: 128 * 1024,
|
|
258
|
-
windowsHide: true,
|
|
259
|
-
env: { ...process.env, NO_COLOR: "1" }
|
|
260
|
-
}, (error, stdout, stderr) => {
|
|
261
|
-
if (error && (error.killed || error.signal || error.code !== 1)) {
|
|
262
|
-
const reason = error.code === "ENOENT" ? "CLI not found" : "status command did not complete";
|
|
263
|
-
reject(new Error(`Could not check ${target} authentication: ${reason}.`));
|
|
264
|
-
} else {
|
|
265
|
-
resolve({ code: error ? 1 : 0, stdout, stderr });
|
|
266
|
-
}
|
|
267
|
-
});
|
|
268
|
-
child.stdin?.end();
|
|
269
|
-
});
|
|
270
|
-
}
|
|
271
|
-
function jsonObject(output) {
|
|
272
|
-
try {
|
|
273
|
-
const value = JSON.parse(output);
|
|
274
|
-
if (value !== null && typeof value === "object" && !Array.isArray(value))
|
|
275
|
-
return value;
|
|
276
|
-
} catch {}
|
|
277
|
-
}
|
|
278
|
-
function authenticated(target, code, stdout, stderr) {
|
|
279
|
-
if (target === "claude") {
|
|
280
|
-
const loggedIn = jsonObject(stdout)?.loggedIn;
|
|
281
|
-
if (loggedIn === false || code === 0 && loggedIn === true)
|
|
282
|
-
return loggedIn;
|
|
283
|
-
return;
|
|
284
|
-
}
|
|
285
|
-
const lines = stripVTControlCharacters(`${stdout}
|
|
286
|
-
${stderr}`).split(/\r?\n/).map((line) => line.trim().replace(/^[✔✓✗✘×]\s*/u, ""));
|
|
287
|
-
if (target === "grok") {
|
|
288
|
-
const report = jsonObject(stdout);
|
|
289
|
-
if (code === 0 && report && !("error" in report) && typeof report.authenticated === "boolean")
|
|
290
|
-
return report.authenticated;
|
|
291
|
-
if (code === 1 && lines.some((line) => /^(?:error:\s*)?(?:unauthenticated|unauthorized|authentication required|not (?:logged in|authenticated))\b/i.test(line)))
|
|
292
|
-
return false;
|
|
293
|
-
return;
|
|
294
|
-
}
|
|
295
|
-
if (lines.some((line) => /^(?:not (?:logged in|authenticated)|you are not logged in)\b/i.test(line)))
|
|
296
|
-
return false;
|
|
297
|
-
if (code !== 0)
|
|
298
|
-
return;
|
|
299
|
-
const signedIn = target === "codex" ? /^logged in using\s+/i : /^(?:logged in(?:\s+as\s+.+)?|authenticated(?:\s+as\s+.+)?)[.!]?$/i;
|
|
300
|
-
if (lines.some((line) => signedIn.test(line)))
|
|
301
|
-
return true;
|
|
302
|
-
}
|
|
303
|
-
async function checkAuth(target) {
|
|
304
|
-
const commands = {
|
|
305
|
-
codex: [process.env.CODEX_PATH ?? "codex", "login", "status"],
|
|
306
|
-
claude: ["claude", "auth", "status", "--json"],
|
|
307
|
-
grok: ["grok", "usage", "--json"],
|
|
308
|
-
cursor: ["cursor-agent", "status"]
|
|
309
|
-
};
|
|
310
|
-
const [command, ...args] = commands[target];
|
|
311
|
-
const { code, stdout, stderr } = await probe(target, command, args);
|
|
312
|
-
const result = authenticated(target, code, stdout, stderr);
|
|
313
|
-
if (result === undefined)
|
|
314
|
-
throw new Error(`Could not determine ${target} authentication from its status command.`);
|
|
315
|
-
return { target, ...await recordAuth(target, result) };
|
|
316
|
-
}
|
|
317
|
-
var init_auth_check = __esm(() => {
|
|
318
|
-
init_auth_state();
|
|
319
|
-
});
|
|
320
|
-
|
|
321
|
-
// src/adapter.ts
|
|
322
|
-
import { access, readFile as readFile3 } from "node:fs/promises";
|
|
323
|
-
import { dirname, join as join4 } from "node:path";
|
|
324
629
|
function isRecord(value) {
|
|
325
630
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
326
631
|
}
|
|
@@ -328,7 +633,7 @@ async function configuredArgv(cwd, profile) {
|
|
|
328
633
|
const path = join4(cwd, ".acpxrc.json");
|
|
329
634
|
let source;
|
|
330
635
|
try {
|
|
331
|
-
source = await
|
|
636
|
+
source = await readFile4(path, "utf8");
|
|
332
637
|
} catch (error) {
|
|
333
638
|
if (error.code === "ENOENT")
|
|
334
639
|
return;
|
|
@@ -385,13 +690,14 @@ async function resolveAdapter(target, cwd) {
|
|
|
385
690
|
const [command, ...args] = override;
|
|
386
691
|
if (requiresWindowsShell(command))
|
|
387
692
|
throw new Error("On Windows, set the adapter command to a native executable or an interpreter.");
|
|
388
|
-
return { command, args, env };
|
|
693
|
+
return { source: "worktree-override", command, args, env };
|
|
389
694
|
}
|
|
390
695
|
const command = executableOnPath(target.launcher);
|
|
391
696
|
if (target.id === "codex" || target.id === "claude") {
|
|
392
697
|
if (command && !requiresWindowsShell(command))
|
|
393
|
-
return { command, args: [], env };
|
|
698
|
+
return { source: "path", command, args: [], env };
|
|
394
699
|
return {
|
|
700
|
+
source: "pinned-npx",
|
|
395
701
|
...await packageLauncher(packages[target.id], target.launcher),
|
|
396
702
|
env
|
|
397
703
|
};
|
|
@@ -400,65 +706,67 @@ async function resolveAdapter(target, cwd) {
|
|
|
400
706
|
throw new Error(`Install ${target.launcher} and put it on PATH.`);
|
|
401
707
|
if (requiresWindowsShell(command))
|
|
402
708
|
throw new Error(`Install ${target.launcher} as a native Windows executable.`);
|
|
403
|
-
|
|
404
|
-
return { command, args, env };
|
|
709
|
+
return { source: "path", command, args: ["agent", "stdio"], env };
|
|
405
710
|
}
|
|
406
711
|
var packages;
|
|
407
712
|
var init_adapter = __esm(() => {
|
|
408
|
-
init_targets();
|
|
409
713
|
packages = {
|
|
410
714
|
codex: "@agentclientprotocol/codex-acp@1.13.1",
|
|
411
715
|
claude: "@agentclientprotocol/claude-agent-acp@0.95.0"
|
|
412
716
|
};
|
|
413
717
|
});
|
|
414
718
|
|
|
415
|
-
// src/
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
let options = session.configOptions ?? [];
|
|
429
|
-
if (model) {
|
|
430
|
-
const selector = options.find((option) => option.id === "model") ?? options.find((option) => option.category === "model");
|
|
431
|
-
if (!selector && session.models?.availableModels?.some((choice) => choice.modelId === model)) {
|
|
432
|
-
await agent.request("session/set_model", { sessionId, modelId: model });
|
|
433
|
-
} else {
|
|
434
|
-
options = await setOption(agent, sessionId, selector, "model", model);
|
|
435
|
-
}
|
|
719
|
+
// src/auth-state.ts
|
|
720
|
+
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
721
|
+
import { mkdir as mkdir3, readFile as readFile5, rename as rename2, rm as rm3, writeFile as writeFile3 } from "node:fs/promises";
|
|
722
|
+
import { join as join5 } from "node:path";
|
|
723
|
+
async function readAuth(target) {
|
|
724
|
+
const path = join5(taubeHome(), "auth", `${target}.json`);
|
|
725
|
+
let contents;
|
|
726
|
+
try {
|
|
727
|
+
contents = await readFile5(path, "utf8");
|
|
728
|
+
} catch (error) {
|
|
729
|
+
if (error.code === "ENOENT")
|
|
730
|
+
return { authenticated: false, checkedAt: null };
|
|
731
|
+
throw error;
|
|
436
732
|
}
|
|
437
|
-
|
|
438
|
-
const
|
|
439
|
-
|
|
733
|
+
try {
|
|
734
|
+
const { authenticated, checkedAt } = JSON.parse(contents);
|
|
735
|
+
if (typeof authenticated === "boolean" && typeof checkedAt === "string" && Number.isFinite(Date.parse(checkedAt)))
|
|
736
|
+
return { authenticated, checkedAt };
|
|
737
|
+
} catch {}
|
|
738
|
+
throw new Error(`Invalid authentication cache for ${target}.`);
|
|
739
|
+
}
|
|
740
|
+
async function recordAuth(target, authenticated) {
|
|
741
|
+
const directory = join5(taubeHome(), "auth");
|
|
742
|
+
await mkdir3(directory, { recursive: true, mode: 448 });
|
|
743
|
+
const result = { authenticated, checkedAt: new Date().toISOString() };
|
|
744
|
+
const path = join5(directory, `${target}.json`);
|
|
745
|
+
const temporary = `${path}.${randomUUID3()}.tmp`;
|
|
746
|
+
try {
|
|
747
|
+
await writeFile3(temporary, JSON.stringify(result), {
|
|
748
|
+
mode: 384,
|
|
749
|
+
flag: "wx"
|
|
750
|
+
});
|
|
751
|
+
await rename2(temporary, path);
|
|
752
|
+
} finally {
|
|
753
|
+
await rm3(temporary, { force: true });
|
|
440
754
|
}
|
|
755
|
+
return result;
|
|
441
756
|
}
|
|
757
|
+
var init_auth_state = __esm(() => {
|
|
758
|
+
init_home();
|
|
759
|
+
});
|
|
442
760
|
|
|
443
|
-
// src/
|
|
444
|
-
import { execFile
|
|
445
|
-
import { constants } from "node:os";
|
|
446
|
-
import { resolve as resolve3 } from "node:path";
|
|
447
|
-
import { Writable } from "node:stream";
|
|
448
|
-
import { text } from "node:stream/consumers";
|
|
761
|
+
// src/acp-process.ts
|
|
762
|
+
import { execFile } from "node:child_process";
|
|
449
763
|
import { setTimeout as delay } from "node:timers/promises";
|
|
450
|
-
import {
|
|
451
|
-
client,
|
|
452
|
-
ndJsonStream,
|
|
453
|
-
PROTOCOL_VERSION,
|
|
454
|
-
RequestError
|
|
455
|
-
} from "@agentclientprotocol/sdk";
|
|
456
764
|
async function stopAdapter(child, exited) {
|
|
457
765
|
if (!child.pid)
|
|
458
766
|
return;
|
|
459
767
|
if (process.platform === "win32") {
|
|
460
768
|
if (child.exitCode === null && child.signalCode === null) {
|
|
461
|
-
await new Promise((done) =>
|
|
769
|
+
await new Promise((done) => execFile("taskkill.exe", ["/PID", String(child.pid), "/T", "/F"], {
|
|
462
770
|
timeout: 2000,
|
|
463
771
|
windowsHide: true
|
|
464
772
|
}, () => done()));
|
|
@@ -485,9 +793,642 @@ async function stopAdapter(child, exited) {
|
|
|
485
793
|
signalGroup("SIGKILL");
|
|
486
794
|
}
|
|
487
795
|
}
|
|
796
|
+
function adapterOutput(stdout, beforeRead) {
|
|
797
|
+
const bytes = stdout[Symbol.asyncIterator]();
|
|
798
|
+
return new ReadableStream({
|
|
799
|
+
async pull(controller) {
|
|
800
|
+
if (beforeRead)
|
|
801
|
+
await beforeRead();
|
|
802
|
+
const next = await bytes.next();
|
|
803
|
+
if (next.done)
|
|
804
|
+
controller.close();
|
|
805
|
+
else
|
|
806
|
+
controller.enqueue(next.value);
|
|
807
|
+
},
|
|
808
|
+
cancel() {
|
|
809
|
+
stdout.destroy();
|
|
810
|
+
}
|
|
811
|
+
});
|
|
812
|
+
}
|
|
813
|
+
var shutdownGrace = 300;
|
|
814
|
+
var init_acp_process = () => {};
|
|
815
|
+
|
|
816
|
+
// src/permission.ts
|
|
817
|
+
function summarize(call, previous) {
|
|
818
|
+
const summary = { ...previous };
|
|
819
|
+
if (call.kind != null)
|
|
820
|
+
summary.toolKind = kinds.has(call.kind) ? call.kind : undefined;
|
|
821
|
+
if (call.title != null)
|
|
822
|
+
summary.toolTitle = typeof call.title === "string" ? action.exec(call.title.trimStart())?.[0] : undefined;
|
|
823
|
+
return summary;
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
class PermissionTools {
|
|
827
|
+
calls = new Map;
|
|
828
|
+
key(sessionId, call) {
|
|
829
|
+
if (typeof sessionId === "string" && sessionId.length <= 256 && typeof call.toolCallId === "string" && call.toolCallId.length <= 256)
|
|
830
|
+
return JSON.stringify([sessionId, call.toolCallId]);
|
|
831
|
+
}
|
|
832
|
+
update(sessionId, call) {
|
|
833
|
+
const key = this.key(sessionId, call);
|
|
834
|
+
if (!key)
|
|
835
|
+
return;
|
|
836
|
+
const summary = summarize(call, this.calls.get(key));
|
|
837
|
+
this.calls.delete(key);
|
|
838
|
+
if (this.calls.size >= 128) {
|
|
839
|
+
const oldest = this.calls.keys().next();
|
|
840
|
+
if (!oldest.done)
|
|
841
|
+
this.calls.delete(oldest.value);
|
|
842
|
+
}
|
|
843
|
+
this.calls.set(key, summary);
|
|
844
|
+
}
|
|
845
|
+
denied(sessionId, call) {
|
|
846
|
+
const key = this.key(sessionId, call);
|
|
847
|
+
return summarize(call, key ? this.calls.get(key) : undefined);
|
|
848
|
+
}
|
|
849
|
+
clear() {
|
|
850
|
+
this.calls.clear();
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
var ModeError, kinds, action;
|
|
854
|
+
var init_permission = __esm(() => {
|
|
855
|
+
ModeError = class ModeError extends Error {
|
|
856
|
+
failure;
|
|
857
|
+
constructor(code, acpErrorCode) {
|
|
858
|
+
super(code === "mode_unavailable" ? "Claude does not advertise the acceptEdits mode." : "Claude did not confirm the acceptEdits mode.");
|
|
859
|
+
this.failure = {
|
|
860
|
+
code,
|
|
861
|
+
acpErrorCode: Number.isSafeInteger(acpErrorCode) ? acpErrorCode : undefined
|
|
862
|
+
};
|
|
863
|
+
}
|
|
864
|
+
};
|
|
865
|
+
kinds = new Set([
|
|
866
|
+
"read",
|
|
867
|
+
"edit",
|
|
868
|
+
"delete",
|
|
869
|
+
"move",
|
|
870
|
+
"search",
|
|
871
|
+
"execute",
|
|
872
|
+
"think",
|
|
873
|
+
"fetch",
|
|
874
|
+
"switch_mode",
|
|
875
|
+
"other"
|
|
876
|
+
]);
|
|
877
|
+
action = /^(apply patch|run command|read file|write file|edit file|approve plan|load skill|web search|terminal|bash|read|write|edit|multiedit|notebookedit|delete|move|search|execute|run|fetch|glob|grep|webfetch|websearch|think)(?=$|[\s:(])/i;
|
|
878
|
+
});
|
|
879
|
+
|
|
880
|
+
// src/direct-session.ts
|
|
881
|
+
import {
|
|
882
|
+
PROTOCOL_VERSION,
|
|
883
|
+
RequestError
|
|
884
|
+
} from "@agentclientprotocol/sdk";
|
|
885
|
+
async function openSession(agent, cwd, acpSessionId) {
|
|
886
|
+
const init = await agent.request("initialize", {
|
|
887
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
888
|
+
clientCapabilities: {}
|
|
889
|
+
});
|
|
890
|
+
if (init?.protocolVersion !== PROTOCOL_VERSION)
|
|
891
|
+
throw new Error(`Unsupported ACP protocol version: ${init?.protocolVersion}.`);
|
|
892
|
+
if (acpSessionId !== undefined) {
|
|
893
|
+
if (init.agentCapabilities?.loadSession !== true)
|
|
894
|
+
throw new Error("The adapter does not support session/load.");
|
|
895
|
+
const loaded = await agent.request("session/load", {
|
|
896
|
+
cwd,
|
|
897
|
+
mcpServers: [],
|
|
898
|
+
sessionId: acpSessionId
|
|
899
|
+
});
|
|
900
|
+
return { ...loaded, sessionId: acpSessionId };
|
|
901
|
+
}
|
|
902
|
+
const session = await agent.request("session/new", { cwd, mcpServers: [] });
|
|
903
|
+
if (typeof session?.sessionId !== "string" || !session.sessionId)
|
|
904
|
+
throw new Error("The adapter did not return an ACP session ID.");
|
|
905
|
+
return session;
|
|
906
|
+
}
|
|
907
|
+
function modelSelector(options) {
|
|
908
|
+
return options.find((option) => option.id === "model") ?? options.find((option) => option.category === "model");
|
|
909
|
+
}
|
|
910
|
+
function effortSelector(options, target) {
|
|
911
|
+
return options.find((option) => option.id === target.effortOption) ?? options.find((option) => option.category === "thought_level");
|
|
912
|
+
}
|
|
913
|
+
function currentId(value) {
|
|
914
|
+
return typeof value === "string" && value.trim() ? value : null;
|
|
915
|
+
}
|
|
916
|
+
function currentValue(selector) {
|
|
917
|
+
return selector?.type === "select" ? currentId(selector.currentValue) : null;
|
|
918
|
+
}
|
|
919
|
+
function modeSelector(options, id) {
|
|
920
|
+
return options.find((option) => (id === undefined || option.id === id) && (option.category === "mode" || option.id === "mode" && option.category == null));
|
|
921
|
+
}
|
|
922
|
+
function optionValues(option) {
|
|
923
|
+
if (option.type !== "select")
|
|
924
|
+
return null;
|
|
925
|
+
return option.options.flatMap((entry) => ("group" in entry) ? entry.options.map((choice) => choice.value) : [entry.value]);
|
|
926
|
+
}
|
|
927
|
+
function advertisedModelIds(session) {
|
|
928
|
+
const selector = modelSelector(session.configOptions ?? []);
|
|
929
|
+
const values = selector ? optionValues(selector) : session.models?.availableModels?.map((choice) => choice.modelId);
|
|
930
|
+
if (!values)
|
|
931
|
+
return null;
|
|
932
|
+
if (!values.every((id) => typeof id === "string" && id.trim()))
|
|
933
|
+
throw new Error("The adapter returned invalid model IDs.");
|
|
934
|
+
return [...new Set(values)];
|
|
935
|
+
}
|
|
936
|
+
function advertisedModeIds(session) {
|
|
937
|
+
try {
|
|
938
|
+
const options = session.configOptions ?? [];
|
|
939
|
+
const selector = options.find((option) => option.category === "mode") ?? options.find((option) => option.id === "mode");
|
|
940
|
+
const values = (selector && optionValues(selector)) ?? session.modes?.availableModes.map((mode) => mode.id);
|
|
941
|
+
if (values?.every((id) => typeof id === "string" && id.trim()))
|
|
942
|
+
return [...new Set(values)];
|
|
943
|
+
} catch {}
|
|
944
|
+
}
|
|
945
|
+
function verifyValue(flag, requested, confirmed) {
|
|
946
|
+
if (requested !== null && confirmed !== null && confirmed !== requested)
|
|
947
|
+
throw new Error(`Requested --${flag} ${requested}, but the adapter confirmed ${confirmed}.`);
|
|
948
|
+
}
|
|
949
|
+
function verifySelection({ requested, confirmed }) {
|
|
950
|
+
verifyValue("model", requested.model, confirmed.model);
|
|
951
|
+
verifyValue("effort", requested.effort, confirmed.effort);
|
|
952
|
+
}
|
|
953
|
+
function sessionConfiguration(session, target) {
|
|
954
|
+
let options = session.configOptions ?? [];
|
|
955
|
+
let legacyModel = null;
|
|
956
|
+
let effectiveMode = null;
|
|
957
|
+
let modeConfigId;
|
|
958
|
+
function applyOptions(snapshot, currentModelId) {
|
|
959
|
+
options = snapshot;
|
|
960
|
+
const mode = modeSelector(options, modeConfigId);
|
|
961
|
+
if (mode || modeConfigId !== undefined)
|
|
962
|
+
effectiveMode = currentValue(mode);
|
|
963
|
+
const selector = modelSelector(options);
|
|
964
|
+
if (selector)
|
|
965
|
+
legacyModel = null;
|
|
966
|
+
else if (currentModelId !== undefined)
|
|
967
|
+
legacyModel = currentModelId;
|
|
968
|
+
return {
|
|
969
|
+
model: currentValue(selector) ?? currentModelId ?? legacyModel,
|
|
970
|
+
effort: currentValue(effortSelector(options, target))
|
|
971
|
+
};
|
|
972
|
+
}
|
|
973
|
+
async function selectOption(agent, selector, value) {
|
|
974
|
+
const before = options;
|
|
975
|
+
const result = await agent.request("session/set_config_option", {
|
|
976
|
+
sessionId: session.sessionId,
|
|
977
|
+
configId: selector.id,
|
|
978
|
+
value
|
|
979
|
+
});
|
|
980
|
+
return applyOptions(result?.configOptions ?? (options === before ? [] : options));
|
|
981
|
+
}
|
|
982
|
+
async function selectLegacyModel(agent, modelId) {
|
|
983
|
+
const before = options;
|
|
984
|
+
legacyModel = null;
|
|
985
|
+
const result = await agent.request("session/set_model", { sessionId: session.sessionId, modelId });
|
|
986
|
+
legacyModel = currentId(result?.models?.currentModelId ?? result?.currentModelId);
|
|
987
|
+
if (result?.configOptions || before !== options)
|
|
988
|
+
return applyOptions(result?.configOptions ?? options, legacyModel);
|
|
989
|
+
return { model: legacyModel, effort: null };
|
|
990
|
+
}
|
|
991
|
+
return {
|
|
992
|
+
initial: applyOptions(options, currentId(session.models?.currentModelId)),
|
|
993
|
+
applyOptions,
|
|
994
|
+
modeChanged(mode) {
|
|
995
|
+
effectiveMode = mode;
|
|
996
|
+
},
|
|
997
|
+
verifyAcceptEdits() {
|
|
998
|
+
if (effectiveMode !== "acceptEdits")
|
|
999
|
+
throw new ModeError("mode_unconfirmed");
|
|
1000
|
+
},
|
|
1001
|
+
async configureAcceptEdits(agent, report) {
|
|
1002
|
+
const modeId = "acceptEdits";
|
|
1003
|
+
const selector = modeSelector(options);
|
|
1004
|
+
if (target.id !== "claude" || !(selector ? optionValues(selector)?.includes(modeId) : session.modes?.availableModes?.some((mode) => mode.id === modeId)))
|
|
1005
|
+
throw new ModeError("mode_unavailable");
|
|
1006
|
+
effectiveMode = null;
|
|
1007
|
+
modeConfigId = selector?.id;
|
|
1008
|
+
let snapshot;
|
|
1009
|
+
try {
|
|
1010
|
+
if (selector) {
|
|
1011
|
+
const result = await agent.request("session/set_config_option", {
|
|
1012
|
+
sessionId: session.sessionId,
|
|
1013
|
+
configId: selector.id,
|
|
1014
|
+
value: modeId
|
|
1015
|
+
});
|
|
1016
|
+
snapshot = result?.configOptions;
|
|
1017
|
+
} else {
|
|
1018
|
+
await agent.request("session/set_mode", {
|
|
1019
|
+
sessionId: session.sessionId,
|
|
1020
|
+
modeId
|
|
1021
|
+
});
|
|
1022
|
+
}
|
|
1023
|
+
} catch (error) {
|
|
1024
|
+
throw new ModeError("mode_unconfirmed", error instanceof RequestError ? error.code : undefined);
|
|
1025
|
+
}
|
|
1026
|
+
if (snapshot) {
|
|
1027
|
+
const reported = currentValue(modeSelector(snapshot, modeConfigId));
|
|
1028
|
+
if (effectiveMode !== null && effectiveMode !== reported)
|
|
1029
|
+
throw new ModeError("mode_unconfirmed");
|
|
1030
|
+
await report(applyOptions(snapshot));
|
|
1031
|
+
}
|
|
1032
|
+
this.verifyAcceptEdits();
|
|
1033
|
+
},
|
|
1034
|
+
async configure(agent, { model, effort }, report) {
|
|
1035
|
+
if (model !== null) {
|
|
1036
|
+
const ids = advertisedModelIds({
|
|
1037
|
+
configOptions: options,
|
|
1038
|
+
models: session.models
|
|
1039
|
+
});
|
|
1040
|
+
if (!ids?.includes(model)) {
|
|
1041
|
+
const hint = ids?.length ? `Advertised models: ${ids.map((id) => JSON.stringify(id)).join(", ")}.` : `Run taube surfaces ${target.id} --models in the dispatch working directory.`;
|
|
1042
|
+
throw new Error(`The adapter does not advertise --model ${JSON.stringify(model)}. ${hint}`);
|
|
1043
|
+
}
|
|
1044
|
+
const selector = modelSelector(options);
|
|
1045
|
+
const confirmed = selector ? await selectOption(agent, selector, model) : await selectLegacyModel(agent, model);
|
|
1046
|
+
await report(confirmed);
|
|
1047
|
+
verifyValue("model", model, confirmed.model);
|
|
1048
|
+
}
|
|
1049
|
+
if (effort !== null) {
|
|
1050
|
+
const selector = effortSelector(options, target);
|
|
1051
|
+
if (!selector || !optionValues(selector)?.includes(effort))
|
|
1052
|
+
throw new Error(`The adapter does not advertise --effort ${effort}.`);
|
|
1053
|
+
const confirmed = await selectOption(agent, selector, effort);
|
|
1054
|
+
await report(confirmed);
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
};
|
|
1058
|
+
}
|
|
1059
|
+
var init_direct_session = __esm(() => {
|
|
1060
|
+
init_permission();
|
|
1061
|
+
});
|
|
1062
|
+
|
|
1063
|
+
// src/model-discovery.ts
|
|
1064
|
+
var exports_model_discovery = {};
|
|
1065
|
+
__export(exports_model_discovery, {
|
|
1066
|
+
discoverModels: () => discoverModels
|
|
1067
|
+
});
|
|
1068
|
+
import { spawn } from "node:child_process";
|
|
1069
|
+
import { resolve as resolve3 } from "node:path";
|
|
1070
|
+
import { Writable } from "node:stream";
|
|
1071
|
+
import { client, ndJsonStream, RequestError as RequestError2 } from "@agentclientprotocol/sdk";
|
|
1072
|
+
async function probeSession(adapter, cwd, failure) {
|
|
1073
|
+
const child = spawn(adapter.command, adapter.args, {
|
|
1074
|
+
cwd,
|
|
1075
|
+
env: adapter.env,
|
|
1076
|
+
detached: process.platform !== "win32",
|
|
1077
|
+
windowsHide: true,
|
|
1078
|
+
stdio: ["pipe", "pipe", "ignore"]
|
|
1079
|
+
});
|
|
1080
|
+
const exited = new Promise((done) => {
|
|
1081
|
+
child.once("exit", () => done());
|
|
1082
|
+
child.once("error", (error) => {
|
|
1083
|
+
failure.reject(error);
|
|
1084
|
+
done();
|
|
1085
|
+
});
|
|
1086
|
+
});
|
|
1087
|
+
child.stdin.on("error", failure.reject);
|
|
1088
|
+
child.stdout.on("error", failure.reject);
|
|
1089
|
+
try {
|
|
1090
|
+
const connection = client().connect(ndJsonStream(Writable.toWeb(child.stdin), adapterOutput(child.stdout)));
|
|
1091
|
+
try {
|
|
1092
|
+
return await Promise.race([
|
|
1093
|
+
openSession(connection.agent, cwd),
|
|
1094
|
+
failure.promise
|
|
1095
|
+
]);
|
|
1096
|
+
} finally {
|
|
1097
|
+
connection.close();
|
|
1098
|
+
}
|
|
1099
|
+
} finally {
|
|
1100
|
+
try {
|
|
1101
|
+
await stopAdapter(child, exited);
|
|
1102
|
+
} finally {
|
|
1103
|
+
child.stdin.destroy();
|
|
1104
|
+
child.stdout.destroy();
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
async function discoverModels(target, cwd, signal) {
|
|
1109
|
+
const directory = resolve3(cwd);
|
|
1110
|
+
const failure = Promise.withResolvers();
|
|
1111
|
+
const onAbort = () => failure.reject(signal?.reason);
|
|
1112
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1113
|
+
const timeoutError = new Error("Model discovery timed out after 15 seconds.");
|
|
1114
|
+
const timer = setTimeout(() => failure.reject(timeoutError), discoveryTimeout);
|
|
1115
|
+
let modelError = "Could not resolve the adapter. Check the launcher and .acpxrc.json.";
|
|
1116
|
+
let source = "unavailable";
|
|
1117
|
+
let modeIds;
|
|
1118
|
+
try {
|
|
1119
|
+
signal?.throwIfAborted();
|
|
1120
|
+
const adapter = await Promise.race([
|
|
1121
|
+
resolveAdapter(target, directory),
|
|
1122
|
+
failure.promise
|
|
1123
|
+
]);
|
|
1124
|
+
source = adapter.source;
|
|
1125
|
+
signal?.throwIfAborted();
|
|
1126
|
+
modelError = "Could not open an ACP session to discover model IDs.";
|
|
1127
|
+
const session = await probeSession(adapter, directory, failure);
|
|
1128
|
+
modeIds = advertisedModeIds(session);
|
|
1129
|
+
modelError = "The adapter returned invalid model metadata.";
|
|
1130
|
+
const modelIds = advertisedModelIds(session);
|
|
1131
|
+
return modelIds === null ? {
|
|
1132
|
+
source,
|
|
1133
|
+
modeIds,
|
|
1134
|
+
modelIds,
|
|
1135
|
+
modelError: "The adapter did not advertise model IDs."
|
|
1136
|
+
} : { source, modeIds, modelIds };
|
|
1137
|
+
} catch (error) {
|
|
1138
|
+
if (signal?.aborted)
|
|
1139
|
+
modelError = "Model discovery was interrupted.";
|
|
1140
|
+
else if (error === timeoutError)
|
|
1141
|
+
modelError = timeoutError.message;
|
|
1142
|
+
else if (error instanceof RequestError2 && error.code === -32000)
|
|
1143
|
+
modelError = `Authentication required. Sign in to ${target.id}.`;
|
|
1144
|
+
else if (error?.code === "ENOENT")
|
|
1145
|
+
modelError = "Could not start the adapter. Check the launcher and working directory.";
|
|
1146
|
+
return { source, modeIds, modelIds: null, modelError };
|
|
1147
|
+
} finally {
|
|
1148
|
+
clearTimeout(timer);
|
|
1149
|
+
signal?.removeEventListener("abort", onAbort);
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
var discoveryTimeout = 15000;
|
|
1153
|
+
var init_model_discovery = __esm(() => {
|
|
1154
|
+
init_acp_process();
|
|
1155
|
+
init_adapter();
|
|
1156
|
+
init_direct_session();
|
|
1157
|
+
});
|
|
1158
|
+
|
|
1159
|
+
// src/final-response.ts
|
|
1160
|
+
function metaField(meta, key) {
|
|
1161
|
+
if (typeof meta === "object" && meta !== null && Object.hasOwn(meta, key))
|
|
1162
|
+
return meta[key];
|
|
1163
|
+
}
|
|
1164
|
+
|
|
1165
|
+
class FinalResponseCapture {
|
|
1166
|
+
messages = new Map;
|
|
1167
|
+
parts = [];
|
|
1168
|
+
anonymousFinal = { final: true };
|
|
1169
|
+
latest;
|
|
1170
|
+
hasFinal = false;
|
|
1171
|
+
conflictingPhase = false;
|
|
1172
|
+
idsOnly = true;
|
|
1173
|
+
add({ content, messageId, _meta }) {
|
|
1174
|
+
if (metaField(_meta?.claudeCode, "parentToolUseId"))
|
|
1175
|
+
return;
|
|
1176
|
+
const phase = metaField(_meta?.codex, "phase");
|
|
1177
|
+
const identified = typeof messageId === "string" && messageId.length > 0;
|
|
1178
|
+
if (!identified || phase != null)
|
|
1179
|
+
this.idsOnly = false;
|
|
1180
|
+
let message;
|
|
1181
|
+
if (identified) {
|
|
1182
|
+
message = this.messages.get(messageId) ?? {};
|
|
1183
|
+
this.messages.set(messageId, message);
|
|
1184
|
+
this.latest = message;
|
|
1185
|
+
} else if (phase === "final_answer") {
|
|
1186
|
+
message = this.anonymousFinal;
|
|
1187
|
+
} else {
|
|
1188
|
+
return;
|
|
1189
|
+
}
|
|
1190
|
+
if (phase != null) {
|
|
1191
|
+
const final = phase === "final_answer";
|
|
1192
|
+
if (message.final !== undefined && message.final !== final)
|
|
1193
|
+
this.conflictingPhase = true;
|
|
1194
|
+
message.final = final;
|
|
1195
|
+
this.hasFinal ||= final;
|
|
1196
|
+
}
|
|
1197
|
+
if (content.type !== "text" || message.final === false)
|
|
1198
|
+
return;
|
|
1199
|
+
const last = this.parts.at(-1);
|
|
1200
|
+
if (last?.message === message)
|
|
1201
|
+
last.text += content.text;
|
|
1202
|
+
else
|
|
1203
|
+
this.parts.push({ message, text: content.text });
|
|
1204
|
+
}
|
|
1205
|
+
response() {
|
|
1206
|
+
if (this.conflictingPhase || !this.hasFinal && !this.idsOnly)
|
|
1207
|
+
return null;
|
|
1208
|
+
let response = null;
|
|
1209
|
+
for (const { message, text } of this.parts) {
|
|
1210
|
+
if (this.hasFinal ? message.final : message === this.latest)
|
|
1211
|
+
response = (response ?? "") + text;
|
|
1212
|
+
}
|
|
1213
|
+
return response;
|
|
1214
|
+
}
|
|
1215
|
+
}
|
|
1216
|
+
|
|
1217
|
+
// src/turn-journal.ts
|
|
1218
|
+
import { lstat as lstat2, mkdir as mkdir4, open } from "node:fs/promises";
|
|
1219
|
+
import { join as join6 } from "node:path";
|
|
1220
|
+
import { setTimeout as delay2 } from "node:timers/promises";
|
|
1221
|
+
async function openTurnJournal(id) {
|
|
1222
|
+
if (!/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i.test(id))
|
|
1223
|
+
throw new Error("Expected a Taube session ID.");
|
|
1224
|
+
const directory = join6(taubeHome(), "turns");
|
|
1225
|
+
await mkdir4(directory, { recursive: true, mode: 448 });
|
|
1226
|
+
const stat = await lstat2(directory);
|
|
1227
|
+
if (!stat.isDirectory() || process.getuid && (stat.uid !== process.getuid() || (stat.mode & 63) !== 0))
|
|
1228
|
+
throw new Error("The turn journal directory must be private to the current user.");
|
|
1229
|
+
const file = await open(join6(directory, `${id}.ndjson`), "ax", 384);
|
|
1230
|
+
let number = 0;
|
|
1231
|
+
let active = false;
|
|
1232
|
+
let closed = false;
|
|
1233
|
+
let stopReason = null;
|
|
1234
|
+
let finalResponse;
|
|
1235
|
+
let reportedModel;
|
|
1236
|
+
let queued = [];
|
|
1237
|
+
let queuedChars = 0;
|
|
1238
|
+
let pending;
|
|
1239
|
+
function enqueue(entry) {
|
|
1240
|
+
if (entry.type === "text")
|
|
1241
|
+
queuedChars += entry.text.length;
|
|
1242
|
+
const last = queued.at(-1);
|
|
1243
|
+
if (entry.type === "text" && last?.type === "text" && last.number === entry.number)
|
|
1244
|
+
last.text += entry.text;
|
|
1245
|
+
else
|
|
1246
|
+
queued.push(entry);
|
|
1247
|
+
pending ??= (entry.type === "text" ? delay2(textFlushMs) : Promise.resolve()).then(async () => {
|
|
1248
|
+
while (queued.length) {
|
|
1249
|
+
const batch = queued;
|
|
1250
|
+
queued = [];
|
|
1251
|
+
queuedChars = 0;
|
|
1252
|
+
await file.appendFile(`${batch.map((item) => JSON.stringify(item)).join(`
|
|
1253
|
+
`)}
|
|
1254
|
+
`);
|
|
1255
|
+
if (batch.some((item) => item.type === "queued" || item.type === "sending"))
|
|
1256
|
+
await file.sync();
|
|
1257
|
+
}
|
|
1258
|
+
pending = undefined;
|
|
1259
|
+
});
|
|
1260
|
+
return pending;
|
|
1261
|
+
}
|
|
1262
|
+
function checkActive() {
|
|
1263
|
+
if (closed || !active)
|
|
1264
|
+
throw new Error("No active journal turn.");
|
|
1265
|
+
}
|
|
1266
|
+
function end(status) {
|
|
1267
|
+
checkActive();
|
|
1268
|
+
active = false;
|
|
1269
|
+
if (status !== "completed" || stopReason !== "end_turn") {
|
|
1270
|
+
finalResponse = undefined;
|
|
1271
|
+
reportedModel = undefined;
|
|
1272
|
+
}
|
|
1273
|
+
return enqueue({
|
|
1274
|
+
type: "end",
|
|
1275
|
+
number,
|
|
1276
|
+
finishedAt: new Date().toISOString(),
|
|
1277
|
+
status,
|
|
1278
|
+
stopReason,
|
|
1279
|
+
finalResponse,
|
|
1280
|
+
reportedModel
|
|
1281
|
+
});
|
|
1282
|
+
}
|
|
1283
|
+
return {
|
|
1284
|
+
get reportedModel() {
|
|
1285
|
+
return active ? undefined : reportedModel;
|
|
1286
|
+
},
|
|
1287
|
+
get finalResponse() {
|
|
1288
|
+
return active ? undefined : finalResponse;
|
|
1289
|
+
},
|
|
1290
|
+
get backpressure() {
|
|
1291
|
+
return queuedChars >= highWaterMark ? pending : undefined;
|
|
1292
|
+
},
|
|
1293
|
+
queue(messageId) {
|
|
1294
|
+
if (closed)
|
|
1295
|
+
throw new Error("Turn journal is already closed.");
|
|
1296
|
+
return enqueue({ type: "queued", messageId });
|
|
1297
|
+
},
|
|
1298
|
+
sending(messageId) {
|
|
1299
|
+
if (closed)
|
|
1300
|
+
throw new Error("Turn journal is already closed.");
|
|
1301
|
+
return enqueue({ type: "sending", messageId });
|
|
1302
|
+
},
|
|
1303
|
+
discard(messageId) {
|
|
1304
|
+
if (closed)
|
|
1305
|
+
throw new Error("Turn journal is already closed.");
|
|
1306
|
+
return enqueue({ type: "discarded", messageId });
|
|
1307
|
+
},
|
|
1308
|
+
start(prompt, messageId) {
|
|
1309
|
+
if (closed || active)
|
|
1310
|
+
throw new Error("Cannot start a journal turn.");
|
|
1311
|
+
active = true;
|
|
1312
|
+
number++;
|
|
1313
|
+
stopReason = null;
|
|
1314
|
+
reportedModel = undefined;
|
|
1315
|
+
finalResponse = undefined;
|
|
1316
|
+
return enqueue({
|
|
1317
|
+
type: "start",
|
|
1318
|
+
number,
|
|
1319
|
+
startedAt: new Date().toISOString(),
|
|
1320
|
+
prompt,
|
|
1321
|
+
messageId
|
|
1322
|
+
});
|
|
1323
|
+
},
|
|
1324
|
+
text(text) {
|
|
1325
|
+
checkActive();
|
|
1326
|
+
return enqueue({ type: "text", number, text });
|
|
1327
|
+
},
|
|
1328
|
+
setStopReason(reason, response = null, model) {
|
|
1329
|
+
checkActive();
|
|
1330
|
+
stopReason = reason;
|
|
1331
|
+
reportedModel = model;
|
|
1332
|
+
finalResponse = response ?? undefined;
|
|
1333
|
+
},
|
|
1334
|
+
end,
|
|
1335
|
+
async close(status) {
|
|
1336
|
+
if (closed)
|
|
1337
|
+
throw new Error("Turn journal is already closed.");
|
|
1338
|
+
if (active)
|
|
1339
|
+
end(status);
|
|
1340
|
+
closed = true;
|
|
1341
|
+
try {
|
|
1342
|
+
await pending;
|
|
1343
|
+
} finally {
|
|
1344
|
+
await file.close();
|
|
1345
|
+
}
|
|
1346
|
+
}
|
|
1347
|
+
};
|
|
1348
|
+
}
|
|
1349
|
+
var textFlushMs = 20, highWaterMark;
|
|
1350
|
+
var init_turn_journal = __esm(() => {
|
|
1351
|
+
init_home();
|
|
1352
|
+
highWaterMark = 64 * 1024;
|
|
1353
|
+
});
|
|
1354
|
+
|
|
1355
|
+
// src/session-resume.ts
|
|
1356
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
1357
|
+
import { mkdir as mkdir5 } from "node:fs/promises";
|
|
1358
|
+
import { join as join7 } from "node:path";
|
|
1359
|
+
async function acquireResume(target, cwd, dispatcher, { sourceId, acpSessionId }) {
|
|
1360
|
+
const directory = join7(taubeHome(), "resume-locks");
|
|
1361
|
+
await mkdir5(directory, { recursive: true, mode: 448 });
|
|
1362
|
+
const key = createHash2("sha256").update(JSON.stringify([target, acpSessionId])).digest("hex");
|
|
1363
|
+
const { DatabaseSync } = await import("node:sqlite");
|
|
1364
|
+
const lock = new DatabaseSync(join7(directory, key));
|
|
1365
|
+
try {
|
|
1366
|
+
try {
|
|
1367
|
+
lock.exec("BEGIN IMMEDIATE");
|
|
1368
|
+
} catch (error) {
|
|
1369
|
+
if (error.errcode === 5)
|
|
1370
|
+
throw new Error("Another resume is active for this native session.");
|
|
1371
|
+
throw error;
|
|
1372
|
+
}
|
|
1373
|
+
const native = (await listSessions()).filter((entry) => entry.target === target && entry.acpSessionId === acpSessionId);
|
|
1374
|
+
const source = native.find((entry) => entry.id === sourceId);
|
|
1375
|
+
if (source?.status !== "completed" || source.cwd !== cwd || source.dispatcher !== dispatcher)
|
|
1376
|
+
throw new Error("The completed source is no longer available in the selected scope.");
|
|
1377
|
+
if (native.some((entry) => entry.status === "running"))
|
|
1378
|
+
throw new Error("The native session is already running.");
|
|
1379
|
+
const parents = new Set(native.map((entry) => entry.resumedFromSessionId));
|
|
1380
|
+
const newer = native.find((entry) => entry.resumedFromSessionId && entry.id !== sourceId && !parents.has(entry.id));
|
|
1381
|
+
if (newer)
|
|
1382
|
+
throw new Error(newer.dispatcher === dispatcher ? `A newer continuation exists: ${newer.id} (${newer.status}). Resume requires the latest completed continuation.` : "A newer continuation exists outside the selected scope.");
|
|
1383
|
+
return lock;
|
|
1384
|
+
} catch (error) {
|
|
1385
|
+
lock.close();
|
|
1386
|
+
throw error;
|
|
1387
|
+
}
|
|
1388
|
+
}
|
|
1389
|
+
var init_session_resume = __esm(() => {
|
|
1390
|
+
init_home();
|
|
1391
|
+
init_sessions();
|
|
1392
|
+
});
|
|
1393
|
+
|
|
1394
|
+
// src/direct-acp.ts
|
|
1395
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
1396
|
+
import { randomUUID as randomUUID4 } from "node:crypto";
|
|
1397
|
+
import { constants } from "node:os";
|
|
1398
|
+
import { resolve as resolve5 } from "node:path";
|
|
1399
|
+
import { setTimeout as delay3 } from "node:timers/promises";
|
|
1400
|
+
import {
|
|
1401
|
+
client as client2,
|
|
1402
|
+
ndJsonStream as ndJsonStream2,
|
|
1403
|
+
RequestError as RequestError3
|
|
1404
|
+
} from "@agentclientprotocol/sdk";
|
|
1405
|
+
|
|
1406
|
+
class FollowUpQueue {
|
|
1407
|
+
compactAvailable = false;
|
|
1408
|
+
pending = [];
|
|
1409
|
+
async accept(request, messageId, journal) {
|
|
1410
|
+
if (!this.pending || this.pending.length >= 16)
|
|
1411
|
+
return false;
|
|
1412
|
+
if (request.type === "compact" && !this.compactAvailable)
|
|
1413
|
+
return "unsupported";
|
|
1414
|
+
const ready = journal.queue(messageId);
|
|
1415
|
+
this.pending.push({ request, messageId, ready });
|
|
1416
|
+
await ready;
|
|
1417
|
+
return true;
|
|
1418
|
+
}
|
|
1419
|
+
next() {
|
|
1420
|
+
return this.pending?.shift();
|
|
1421
|
+
}
|
|
1422
|
+
close() {
|
|
1423
|
+
this.pending = null;
|
|
1424
|
+
}
|
|
1425
|
+
}
|
|
488
1426
|
function signalOutcome(signal) {
|
|
489
|
-
|
|
490
|
-
|
|
1427
|
+
return {
|
|
1428
|
+
status: "interrupted",
|
|
1429
|
+
exitCode: 128 + constants.signals[signal],
|
|
1430
|
+
error: `interrupted (${signal})`
|
|
1431
|
+
};
|
|
491
1432
|
}
|
|
492
1433
|
async function rememberAuth(target, authenticated) {
|
|
493
1434
|
try {
|
|
@@ -496,49 +1437,130 @@ async function rememberAuth(target, authenticated) {
|
|
|
496
1437
|
console.error("taube: could not update auth cache:", error instanceof Error ? error.message : String(error));
|
|
497
1438
|
}
|
|
498
1439
|
}
|
|
499
|
-
async function runDirectAcp(target, options) {
|
|
500
|
-
if (options.effort && !target.effortOption)
|
|
501
|
-
throw new Error("Cursor does not support a separate --effort setting. Use --model with an advertised Cursor model variant.");
|
|
502
|
-
const cwd = resolve3(options.cwd ?? ".");
|
|
503
|
-
const instruction = await text(process.stdin);
|
|
504
|
-
if (!instruction.trim())
|
|
505
|
-
throw new Error("Supply a non-empty instruction on stdin.");
|
|
1440
|
+
async function runDirectAcp(target, options, onRegistered) {
|
|
506
1441
|
const controller = new AbortController;
|
|
507
1442
|
const signals = ["SIGINT", "SIGTERM", "SIGHUP"];
|
|
508
1443
|
const onSignal = (signal) => controller.abort(signal);
|
|
509
1444
|
for (const signal of signals)
|
|
510
1445
|
process.on(signal, onSignal);
|
|
1446
|
+
const followUps = new FollowUpQueue;
|
|
1447
|
+
const journalReady = Promise.withResolvers();
|
|
1448
|
+
const selection = initialSelection(options);
|
|
1449
|
+
let channel;
|
|
511
1450
|
let record;
|
|
512
|
-
let
|
|
1451
|
+
let journal;
|
|
1452
|
+
let resumeLock;
|
|
1453
|
+
let registered = false;
|
|
1454
|
+
const chunks = options.output === "json" ? [] : undefined;
|
|
1455
|
+
let outcome;
|
|
513
1456
|
try {
|
|
514
|
-
|
|
515
|
-
|
|
1457
|
+
const cwd = resolve5(options.cwd ?? ".");
|
|
1458
|
+
const instruction = await readPrompt(options, controller.signal);
|
|
1459
|
+
controller.signal.throwIfAborted();
|
|
1460
|
+
if (options.resume) {
|
|
1461
|
+
await Promise.resolve().then(() => init_session_resume());
|
|
1462
|
+
resumeLock = await acquireResume(target.id, cwd, options.dispatcher ?? null, options.resume);
|
|
1463
|
+
}
|
|
1464
|
+
const id = randomUUID4();
|
|
1465
|
+
try {
|
|
1466
|
+
channel = await openSessionChannel(id, async (request, messageId) => {
|
|
1467
|
+
const writer = await journalReady.promise;
|
|
1468
|
+
return !!writer && !controller.signal.aborted && followUps.accept(request, messageId, writer);
|
|
1469
|
+
});
|
|
1470
|
+
} catch {
|
|
1471
|
+
console.error("taube: local IPC unavailable. This dispatch cannot accept follow-up messages.");
|
|
1472
|
+
}
|
|
1473
|
+
controller.signal.throwIfAborted();
|
|
1474
|
+
record = await startSession(target.id, cwd, options.dispatcher ?? null, id, {
|
|
1475
|
+
requestId: options.requestId,
|
|
1476
|
+
resumedFromSessionId: options.resume?.sourceId,
|
|
1477
|
+
selection,
|
|
1478
|
+
dispatcherCwd: options.dispatcherCwd,
|
|
1479
|
+
dispatcherProject: options.dispatcherProject
|
|
1480
|
+
});
|
|
1481
|
+
journal = await openTurnJournal(id);
|
|
1482
|
+
journalReady.resolve(journal);
|
|
1483
|
+
if (onRegistered) {
|
|
1484
|
+
controller.signal.throwIfAborted();
|
|
1485
|
+
await onRegistered(id);
|
|
1486
|
+
registered = true;
|
|
1487
|
+
}
|
|
1488
|
+
outcome = await runAdapter(target, instruction, cwd, record, controller.signal, chunks, followUps, journal, options);
|
|
516
1489
|
} catch (error) {
|
|
517
|
-
|
|
518
|
-
|
|
1490
|
+
outcome = {
|
|
1491
|
+
status: "failed",
|
|
1492
|
+
exitCode: 1,
|
|
1493
|
+
failure: error instanceof ModeError ? error.failure : undefined,
|
|
1494
|
+
error: (error instanceof Error ? error.message : String(error)) || "Dispatch failed."
|
|
1495
|
+
};
|
|
519
1496
|
} finally {
|
|
1497
|
+
followUps.close();
|
|
1498
|
+
journalReady.resolve(undefined);
|
|
1499
|
+
try {
|
|
1500
|
+
await channel?.close();
|
|
1501
|
+
} catch (error) {
|
|
1502
|
+
console.error("taube: could not close the session channel:", error instanceof Error ? error.message : String(error));
|
|
1503
|
+
}
|
|
1504
|
+
}
|
|
1505
|
+
try {
|
|
520
1506
|
if (controller.signal.aborted)
|
|
521
1507
|
outcome = signalOutcome(controller.signal.reason);
|
|
522
1508
|
try {
|
|
523
|
-
await
|
|
1509
|
+
await journal?.close(outcome.status);
|
|
524
1510
|
} catch (error) {
|
|
1511
|
+
const message = `could not finish turn journal: ${error instanceof Error ? error.message : String(error)}`;
|
|
525
1512
|
if (outcome.exitCode === 0)
|
|
526
|
-
outcome = { status: "failed", exitCode: 1 };
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
1513
|
+
outcome = { status: "failed", exitCode: 1, error: message };
|
|
1514
|
+
else
|
|
1515
|
+
console.error(`taube: ${message}`);
|
|
1516
|
+
}
|
|
1517
|
+
const reportedModel = outcome.status === "completed" ? journal?.reportedModel : undefined;
|
|
1518
|
+
try {
|
|
1519
|
+
await record?.finish(outcome.status, outcome.exitCode, {
|
|
1520
|
+
failure: outcome.failure,
|
|
1521
|
+
reportedModel
|
|
1522
|
+
});
|
|
1523
|
+
} catch (error) {
|
|
1524
|
+
const message = `could not finish session record: ${error instanceof Error ? error.message : String(error)}`;
|
|
1525
|
+
if (outcome.exitCode === 0)
|
|
1526
|
+
outcome = { status: "failed", exitCode: 1, error: message };
|
|
1527
|
+
else
|
|
1528
|
+
console.error(`taube: ${message}`);
|
|
1529
|
+
}
|
|
1530
|
+
if (outcome.status === "completed")
|
|
1531
|
+
await rememberAuth(target, true);
|
|
1532
|
+
if (onRegistered && !registered)
|
|
1533
|
+
throw new Error(outcome.error ?? "Dispatch registration failed.");
|
|
1534
|
+
if (outcome.error) {
|
|
1535
|
+
const request = options.requestId === undefined ? "" : ` requestId=${JSON.stringify(options.requestId)}`;
|
|
1536
|
+
const context = outcome.failure ? ` [${outcome.failure.code} target=${target.id}${request}]` : "";
|
|
1537
|
+
console.error(`taube: ${outcome.error}${context}`);
|
|
531
1538
|
}
|
|
1539
|
+
if (chunks)
|
|
1540
|
+
console.log(JSON.stringify({
|
|
1541
|
+
target: target.id,
|
|
1542
|
+
sessionId: record?.id ?? null,
|
|
1543
|
+
requestId: options.requestId,
|
|
1544
|
+
resumedFromSessionId: options.resume?.sourceId,
|
|
1545
|
+
acpSessionId: record?.acpSessionId ?? null,
|
|
1546
|
+
selection: record?.selection ?? selection,
|
|
1547
|
+
...outcome,
|
|
1548
|
+
text: chunks.join(""),
|
|
1549
|
+
reportedModel,
|
|
1550
|
+
finalResponse: outcome.status === "completed" ? journal?.finalResponse : undefined
|
|
1551
|
+
}));
|
|
1552
|
+
} finally {
|
|
1553
|
+
resumeLock?.close();
|
|
1554
|
+
for (const signal of signals)
|
|
1555
|
+
process.off(signal, onSignal);
|
|
532
1556
|
}
|
|
533
|
-
if (outcome.status === "completed")
|
|
534
|
-
await rememberAuth(target, true);
|
|
535
1557
|
return outcome.exitCode;
|
|
536
1558
|
}
|
|
537
|
-
async function runAdapter(target,
|
|
1559
|
+
async function runAdapter(target, instruction, cwd, record, signal, chunks, followUps, journal, { acceptEdits, resume }) {
|
|
538
1560
|
signal.throwIfAborted();
|
|
539
1561
|
const adapter = await resolveAdapter(target, cwd);
|
|
540
1562
|
signal.throwIfAborted();
|
|
541
|
-
const child =
|
|
1563
|
+
const child = spawn2(adapter.command, adapter.args, {
|
|
542
1564
|
cwd,
|
|
543
1565
|
env: {
|
|
544
1566
|
...adapter.env,
|
|
@@ -557,47 +1579,145 @@ async function runAdapter(target, options, instruction, cwd, record, signal) {
|
|
|
557
1579
|
});
|
|
558
1580
|
});
|
|
559
1581
|
let sessionId;
|
|
560
|
-
|
|
561
|
-
let
|
|
562
|
-
|
|
1582
|
+
const earlyCompact = new Set;
|
|
1583
|
+
let capture;
|
|
1584
|
+
const usageModels = new Set;
|
|
1585
|
+
let configuration;
|
|
1586
|
+
let finished = false;
|
|
1587
|
+
let saving;
|
|
1588
|
+
const report = async (confirmed) => {
|
|
1589
|
+
if (!finished) {
|
|
1590
|
+
saving = record.confirm(confirmed);
|
|
1591
|
+
await saving;
|
|
1592
|
+
}
|
|
1593
|
+
};
|
|
1594
|
+
const tools = new PermissionTools;
|
|
1595
|
+
let permissionDenied;
|
|
563
1596
|
let graceTimer;
|
|
564
1597
|
const failAfterGrace = (reason) => {
|
|
565
1598
|
graceTimer ??= setTimeout(() => fail(reason), shutdownGrace);
|
|
566
1599
|
};
|
|
567
1600
|
let flushed = Promise.resolve();
|
|
568
|
-
|
|
569
|
-
const
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
1601
|
+
let persisted = Promise.resolve();
|
|
1602
|
+
const persist = (write) => {
|
|
1603
|
+
if (persisted === write)
|
|
1604
|
+
return;
|
|
1605
|
+
persisted = write;
|
|
1606
|
+
write.catch(fail);
|
|
1607
|
+
};
|
|
1608
|
+
let pendingPrompt;
|
|
1609
|
+
let promptWrite = Promise.resolve();
|
|
1610
|
+
const writeText = (chunk) => {
|
|
1611
|
+
if (chunks) {
|
|
1612
|
+
chunks.push(chunk);
|
|
1613
|
+
return;
|
|
1614
|
+
}
|
|
1615
|
+
flushed = new Promise((done) => {
|
|
1616
|
+
process.stdout.write(chunk, (error) => {
|
|
1617
|
+
if (error)
|
|
1618
|
+
fail(error);
|
|
1619
|
+
done();
|
|
1620
|
+
});
|
|
1621
|
+
});
|
|
1622
|
+
};
|
|
1623
|
+
const input = adapterOutput(child.stdout, async () => {
|
|
1624
|
+
await Promise.all([
|
|
1625
|
+
flushed,
|
|
1626
|
+
journal.backpressure,
|
|
1627
|
+
saving,
|
|
1628
|
+
pendingPrompt?.earlyText ? promptWrite : undefined
|
|
1629
|
+
]);
|
|
1630
|
+
});
|
|
1631
|
+
const output = new WritableStream({
|
|
1632
|
+
write(bytes) {
|
|
1633
|
+
return new Promise((done, reject) => {
|
|
1634
|
+
child.stdin.write(bytes, (error) => error ? reject(error) : done());
|
|
1635
|
+
});
|
|
580
1636
|
}
|
|
581
1637
|
});
|
|
582
|
-
const
|
|
1638
|
+
const transport = ndJsonStream2(output, input);
|
|
1639
|
+
const outbound = transport.writable.getWriter();
|
|
1640
|
+
const connection = client2().onNotification("session/update", ({ params }) => {
|
|
583
1641
|
const { update } = params;
|
|
584
|
-
if (
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
1642
|
+
if (finished || sessionId !== undefined && params.sessionId !== sessionId)
|
|
1643
|
+
return;
|
|
1644
|
+
if (update.sessionUpdate === "tool_call" || update.sessionUpdate === "tool_call_update") {
|
|
1645
|
+
tools.update(params.sessionId, update);
|
|
1646
|
+
return;
|
|
1647
|
+
}
|
|
1648
|
+
if (update.sessionUpdate === "available_commands_update") {
|
|
1649
|
+
const available = Array.isArray(update.availableCommands) && update.availableCommands.some((command) => command?.name === "compact");
|
|
1650
|
+
if (sessionId !== undefined)
|
|
1651
|
+
followUps.compactAvailable = available;
|
|
1652
|
+
else if (available)
|
|
1653
|
+
earlyCompact.add(params.sessionId);
|
|
1654
|
+
else
|
|
1655
|
+
earlyCompact.delete(params.sessionId);
|
|
1656
|
+
return;
|
|
1657
|
+
}
|
|
1658
|
+
if (sessionId === undefined)
|
|
1659
|
+
return;
|
|
1660
|
+
if (update.sessionUpdate === "current_mode_update") {
|
|
1661
|
+
configuration?.modeChanged(update.currentModeId);
|
|
1662
|
+
return;
|
|
1663
|
+
}
|
|
1664
|
+
if (update.sessionUpdate === "usage_update") {
|
|
1665
|
+
const model = update._meta?.["_claude/model"];
|
|
1666
|
+
if (capture && target.id === "claude" && typeof model === "string" && /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,199}$/u.test(model) && usageModels.size < 2)
|
|
1667
|
+
usageModels.add(model);
|
|
1668
|
+
const write = record.reportContextWindow(update);
|
|
1669
|
+
if (write) {
|
|
1670
|
+
saving = write;
|
|
1671
|
+
write.catch(fail);
|
|
1672
|
+
}
|
|
1673
|
+
return;
|
|
1674
|
+
}
|
|
1675
|
+
if (configuration && update.sessionUpdate === "config_option_update") {
|
|
1676
|
+
report(configuration.applyOptions(update.configOptions)).catch(fail);
|
|
1677
|
+
return;
|
|
593
1678
|
}
|
|
594
|
-
|
|
595
|
-
|
|
1679
|
+
if (capture && update.sessionUpdate === "agent_message_chunk") {
|
|
1680
|
+
capture.add(update);
|
|
1681
|
+
if (update.content.type !== "text")
|
|
1682
|
+
return;
|
|
1683
|
+
if (pendingPrompt)
|
|
1684
|
+
pendingPrompt.earlyText += update.content.text;
|
|
1685
|
+
else
|
|
1686
|
+
persist(journal.text(update.content.text));
|
|
1687
|
+
writeText(update.content.text);
|
|
1688
|
+
}
|
|
1689
|
+
}).onRequest("session/request_permission", ({ params }) => {
|
|
1690
|
+
permissionDenied ??= params.toolCall ? tools.denied(params.sessionId, params.toolCall) : {};
|
|
1691
|
+
followUps.close();
|
|
596
1692
|
failAfterGrace(new Error("The adapter requested permission during a non-interactive dispatch."));
|
|
597
1693
|
return { outcome: { outcome: "cancelled" } };
|
|
598
|
-
}).connect(
|
|
1694
|
+
}).connect({
|
|
1695
|
+
readable: transport.readable,
|
|
1696
|
+
writable: new WritableStream({
|
|
1697
|
+
async write(message) {
|
|
1698
|
+
const prompt = "method" in message && message.method === "session/prompt" ? pendingPrompt : undefined;
|
|
1699
|
+
if (!prompt)
|
|
1700
|
+
return outbound.write(message);
|
|
1701
|
+
promptWrite = (async () => {
|
|
1702
|
+
if (finished || permissionDenied || signal.aborted)
|
|
1703
|
+
throw new Error("Dispatch stopped before issuing the prompt.");
|
|
1704
|
+
if (acceptEdits)
|
|
1705
|
+
configuration?.verifyAcceptEdits();
|
|
1706
|
+
tools.clear();
|
|
1707
|
+
capture = prompt.capture;
|
|
1708
|
+
await outbound.write(message);
|
|
1709
|
+
persist(journal.start(prompt.text, prompt.messageId));
|
|
1710
|
+
if (prompt.earlyText)
|
|
1711
|
+
persist(journal.text(prompt.earlyText));
|
|
1712
|
+
pendingPrompt = undefined;
|
|
1713
|
+
})();
|
|
1714
|
+
await promptWrite;
|
|
1715
|
+
}
|
|
1716
|
+
})
|
|
1717
|
+
});
|
|
599
1718
|
const { agent } = connection;
|
|
600
1719
|
const cancel = () => {
|
|
1720
|
+
followUps.close();
|
|
601
1721
|
if (sessionId)
|
|
602
1722
|
agent.notify("session/cancel", { sessionId }).catch(fail);
|
|
603
1723
|
failAfterGrace(new Error(`Interrupted (${signal.reason})`));
|
|
@@ -606,47 +1726,93 @@ async function runAdapter(target, options, instruction, cwd, record, signal) {
|
|
|
606
1726
|
process.stdout.on("error", fail);
|
|
607
1727
|
child.stdin.on("error", fail);
|
|
608
1728
|
child.stdout.on("error", fail);
|
|
609
|
-
let finished = false;
|
|
610
1729
|
const onExit = async () => {
|
|
611
1730
|
let pending;
|
|
1731
|
+
let writing;
|
|
1732
|
+
let savingRecord;
|
|
612
1733
|
do {
|
|
613
1734
|
pending = flushed;
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
1735
|
+
writing = persisted;
|
|
1736
|
+
savingRecord = saving;
|
|
1737
|
+
await Promise.all([pending, writing, savingRecord]).catch(fail);
|
|
1738
|
+
await delay3(shutdownGrace, undefined, { ref: false });
|
|
1739
|
+
} while (!finished && (pending !== flushed || writing !== persisted || savingRecord !== saving));
|
|
617
1740
|
if (!finished)
|
|
618
1741
|
fail(new Error("The adapter exited before completing the ACP exchange."));
|
|
619
1742
|
};
|
|
620
1743
|
child.once("exit", onExit);
|
|
621
1744
|
const run = async () => {
|
|
622
|
-
const
|
|
623
|
-
protocolVersion: PROTOCOL_VERSION,
|
|
624
|
-
clientCapabilities: {}
|
|
625
|
-
});
|
|
626
|
-
if (init?.protocolVersion !== PROTOCOL_VERSION)
|
|
627
|
-
throw new Error(`Unsupported ACP protocol version: ${init?.protocolVersion}.`);
|
|
628
|
-
const session = await agent.request("session/new", { cwd, mcpServers: [] });
|
|
629
|
-
if (typeof session?.sessionId !== "string" || !session.sessionId)
|
|
630
|
-
throw new Error("The adapter did not return an ACP session ID.");
|
|
1745
|
+
const session = await openSession(agent, cwd, resume?.acpSessionId);
|
|
631
1746
|
if (finished)
|
|
632
1747
|
return;
|
|
633
1748
|
sessionId = session.sessionId;
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
1749
|
+
followUps.compactAvailable = earlyCompact.has(sessionId);
|
|
1750
|
+
earlyCompact.clear();
|
|
1751
|
+
configuration = sessionConfiguration(session, target);
|
|
1752
|
+
saving = record.attach(sessionId, configuration.initial);
|
|
1753
|
+
await saving;
|
|
1754
|
+
if (finished || signal.aborted || permissionDenied)
|
|
637
1755
|
return;
|
|
638
|
-
await
|
|
1756
|
+
await configuration.configure(agent, record.selection.requested, report);
|
|
1757
|
+
if (acceptEdits && !finished && !signal.aborted && !permissionDenied)
|
|
1758
|
+
await configuration.configureAcceptEdits(agent, report);
|
|
639
1759
|
if (finished || signal.aborted || permissionDenied)
|
|
640
1760
|
return;
|
|
641
|
-
|
|
1761
|
+
let prompt = instruction;
|
|
1762
|
+
let messageId;
|
|
642
1763
|
try {
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
1764
|
+
for (;; ) {
|
|
1765
|
+
verifySelection(record.selection);
|
|
1766
|
+
if (acceptEdits)
|
|
1767
|
+
configuration.verifyAcceptEdits();
|
|
1768
|
+
const turnCapture = new FinalResponseCapture;
|
|
1769
|
+
usageModels.clear();
|
|
1770
|
+
pendingPrompt = {
|
|
1771
|
+
text: prompt,
|
|
1772
|
+
earlyText: "",
|
|
1773
|
+
messageId,
|
|
1774
|
+
capture: turnCapture
|
|
1775
|
+
};
|
|
1776
|
+
const result = await agent.request("session/prompt", {
|
|
1777
|
+
sessionId,
|
|
1778
|
+
prompt: [{ type: "text", text: prompt }]
|
|
1779
|
+
});
|
|
1780
|
+
capture = undefined;
|
|
1781
|
+
await promptWrite;
|
|
1782
|
+
if (finished)
|
|
1783
|
+
return;
|
|
1784
|
+
if (pendingPrompt)
|
|
1785
|
+
throw new Error("Prompt response preceded transmission.");
|
|
1786
|
+
journal.setStopReason(typeof result?.stopReason === "string" ? result.stopReason : null, result?.stopReason === "end_turn" ? turnCapture.response() : null, usageModels.size === 1 ? usageModels.values().next().value : undefined);
|
|
1787
|
+
if (result?.stopReason !== "end_turn" || signal.aborted || permissionDenied)
|
|
1788
|
+
return result?.stopReason;
|
|
1789
|
+
let next = followUps.next();
|
|
1790
|
+
if (next === undefined)
|
|
1791
|
+
return result.stopReason;
|
|
1792
|
+
await journal.end("completed");
|
|
1793
|
+
for (;; ) {
|
|
1794
|
+
await next.ready;
|
|
1795
|
+
if (finished || signal.aborted || permissionDenied)
|
|
1796
|
+
return;
|
|
1797
|
+
await journal.sending(next.messageId);
|
|
1798
|
+
if (finished || signal.aborted || permissionDenied)
|
|
1799
|
+
return;
|
|
1800
|
+
if (next.request.type === "message" || followUps.compactAvailable) {
|
|
1801
|
+
prompt = next.request.type === "message" ? next.request.text : "/compact";
|
|
1802
|
+
messageId = next.messageId;
|
|
1803
|
+
break;
|
|
1804
|
+
}
|
|
1805
|
+
await journal.discard(next.messageId);
|
|
1806
|
+
next = followUps.next();
|
|
1807
|
+
if (next === undefined)
|
|
1808
|
+
return result.stopReason;
|
|
1809
|
+
}
|
|
1810
|
+
writeText(`
|
|
1811
|
+
`);
|
|
1812
|
+
}
|
|
648
1813
|
} finally {
|
|
649
|
-
|
|
1814
|
+
followUps.close();
|
|
1815
|
+
capture = undefined;
|
|
650
1816
|
await flushed;
|
|
651
1817
|
}
|
|
652
1818
|
};
|
|
@@ -660,6 +1826,7 @@ async function runAdapter(target, options, instruction, cwd, record, signal) {
|
|
|
660
1826
|
failure = error;
|
|
661
1827
|
} finally {
|
|
662
1828
|
finished = true;
|
|
1829
|
+
followUps.close();
|
|
663
1830
|
child.off("exit", onExit);
|
|
664
1831
|
clearTimeout(graceTimer);
|
|
665
1832
|
connection.close();
|
|
@@ -667,7 +1834,7 @@ async function runAdapter(target, options, instruction, cwd, record, signal) {
|
|
|
667
1834
|
child.stdin.end();
|
|
668
1835
|
await Promise.race([
|
|
669
1836
|
exited,
|
|
670
|
-
|
|
1837
|
+
delay3(shutdownGrace, undefined, { ref: false })
|
|
671
1838
|
]);
|
|
672
1839
|
}
|
|
673
1840
|
exitSignal = child.signalCode;
|
|
@@ -678,51 +1845,842 @@ async function runAdapter(target, options, instruction, cwd, record, signal) {
|
|
|
678
1845
|
child.stdin.destroy();
|
|
679
1846
|
child.stdout.destroy();
|
|
680
1847
|
clearTimeout(graceTimer);
|
|
681
|
-
if (signal.aborted && process.stdout.writableLength)
|
|
1848
|
+
if (!chunks && signal.aborted && process.stdout.writableLength)
|
|
682
1849
|
process.stdout.destroy();
|
|
683
1850
|
process.stdout.off("error", fail);
|
|
684
1851
|
signal.removeEventListener("abort", cancel);
|
|
685
|
-
await
|
|
1852
|
+
await promptWrite.catch(() => {});
|
|
1853
|
+
await saving;
|
|
686
1854
|
}
|
|
687
1855
|
}
|
|
688
1856
|
signal.throwIfAborted();
|
|
1857
|
+
if (permissionDenied) {
|
|
1858
|
+
const tool = [permissionDenied.toolKind, permissionDenied.toolTitle].filter(Boolean).join(" / ");
|
|
1859
|
+
return {
|
|
1860
|
+
status: "failed",
|
|
1861
|
+
exitCode: 1,
|
|
1862
|
+
error: `The adapter requested permission during a non-interactive dispatch.${tool ? ` Tool: ${tool}.` : ""}`,
|
|
1863
|
+
failure: {
|
|
1864
|
+
code: "permission_required",
|
|
1865
|
+
...permissionDenied,
|
|
1866
|
+
acpErrorCode: failure instanceof RequestError3 && Number.isSafeInteger(failure.code) ? failure.code : undefined
|
|
1867
|
+
}
|
|
1868
|
+
};
|
|
1869
|
+
}
|
|
1870
|
+
if (failure instanceof ModeError)
|
|
1871
|
+
throw failure;
|
|
689
1872
|
if (exitSignal)
|
|
690
1873
|
return signalOutcome(exitSignal);
|
|
691
|
-
if (
|
|
692
|
-
throw new Error("The adapter requested permission during a non-interactive dispatch.");
|
|
693
|
-
if (failure instanceof RequestError && failure.code === -32000) {
|
|
1874
|
+
if (failure instanceof RequestError3 && failure.code === -32000) {
|
|
694
1875
|
await rememberAuth(target, false);
|
|
695
1876
|
throw new Error(`Authentication required. Sign in to ${target.id} before dispatching.`);
|
|
696
1877
|
}
|
|
697
1878
|
if (status !== null && status > 0) {
|
|
698
|
-
|
|
699
|
-
|
|
1879
|
+
return {
|
|
1880
|
+
status: "failed",
|
|
1881
|
+
exitCode: status,
|
|
1882
|
+
error: `adapter exited with status ${status}`
|
|
1883
|
+
};
|
|
700
1884
|
}
|
|
701
1885
|
if (failure)
|
|
702
1886
|
throw failure;
|
|
703
1887
|
if (!stopReason)
|
|
704
1888
|
throw new Error("The adapter returned an incomplete prompt response.");
|
|
705
1889
|
if (stopReason !== "end_turn") {
|
|
706
|
-
|
|
707
|
-
return
|
|
1890
|
+
const cancelled = stopReason === "cancelled";
|
|
1891
|
+
return {
|
|
1892
|
+
status: cancelled ? "interrupted" : "failed",
|
|
1893
|
+
exitCode: cancelled ? 130 : 1,
|
|
1894
|
+
error: `target stopped with ${stopReason}`
|
|
1895
|
+
};
|
|
708
1896
|
}
|
|
709
|
-
return { status: "completed", exitCode: 0 };
|
|
1897
|
+
return { status: "completed", exitCode: 0, error: null };
|
|
710
1898
|
}
|
|
711
|
-
var shutdownGrace = 300;
|
|
712
1899
|
var init_direct_acp = __esm(() => {
|
|
1900
|
+
init_acp_process();
|
|
713
1901
|
init_adapter();
|
|
714
1902
|
init_auth_state();
|
|
1903
|
+
init_direct_session();
|
|
715
1904
|
init_home();
|
|
1905
|
+
init_permission();
|
|
1906
|
+
init_prompt();
|
|
1907
|
+
init_session_channel();
|
|
716
1908
|
init_sessions();
|
|
1909
|
+
init_turn_journal();
|
|
1910
|
+
});
|
|
1911
|
+
|
|
1912
|
+
// src/turn-history.ts
|
|
1913
|
+
import { constants as constants2, unwatchFile, watchFile } from "node:fs";
|
|
1914
|
+
import { open as open2 } from "node:fs/promises";
|
|
1915
|
+
import { join as join8 } from "node:path";
|
|
1916
|
+
function invalidRecord() {
|
|
1917
|
+
throw new Error("Invalid record in the selected turn journal.");
|
|
1918
|
+
}
|
|
1919
|
+
|
|
1920
|
+
class TurnJournal {
|
|
1921
|
+
turns = [];
|
|
1922
|
+
lastTurn;
|
|
1923
|
+
messages = new Map;
|
|
1924
|
+
inFlight;
|
|
1925
|
+
available = false;
|
|
1926
|
+
offset = 0;
|
|
1927
|
+
partial = [];
|
|
1928
|
+
inode;
|
|
1929
|
+
decoder = new TextDecoder("utf-8", { fatal: true });
|
|
1930
|
+
view;
|
|
1931
|
+
constructor(view = "history") {
|
|
1932
|
+
this.view = view;
|
|
1933
|
+
}
|
|
1934
|
+
apply(line) {
|
|
1935
|
+
let entry;
|
|
1936
|
+
try {
|
|
1937
|
+
entry = JSON.parse(this.decoder.decode(line));
|
|
1938
|
+
} catch {
|
|
1939
|
+
invalidRecord();
|
|
1940
|
+
}
|
|
1941
|
+
const last = this.lastTurn;
|
|
1942
|
+
if (entry?.type === "queued") {
|
|
1943
|
+
const { messageId } = entry;
|
|
1944
|
+
if (typeof messageId !== "string" || !uuidPattern.test(messageId) || this.messages.has(messageId))
|
|
1945
|
+
invalidRecord();
|
|
1946
|
+
this.messages.set(messageId, null);
|
|
1947
|
+
return true;
|
|
1948
|
+
}
|
|
1949
|
+
if (entry?.type === "sending") {
|
|
1950
|
+
const { messageId } = entry;
|
|
1951
|
+
if (typeof messageId !== "string" || this.messages.get(messageId) !== null || this.inFlight)
|
|
1952
|
+
invalidRecord();
|
|
1953
|
+
this.inFlight = messageId;
|
|
1954
|
+
return false;
|
|
1955
|
+
}
|
|
1956
|
+
if (entry?.type === "discarded") {
|
|
1957
|
+
const { messageId } = entry;
|
|
1958
|
+
if (typeof messageId !== "string" || this.inFlight !== messageId)
|
|
1959
|
+
invalidRecord();
|
|
1960
|
+
this.messages.set(messageId, "discarded");
|
|
1961
|
+
this.inFlight = undefined;
|
|
1962
|
+
return true;
|
|
1963
|
+
}
|
|
1964
|
+
if (entry?.type === "start") {
|
|
1965
|
+
if (last?.status === "running" || entry.number !== (last?.number ?? 0) + 1 || typeof entry.startedAt !== "string" || typeof entry.prompt !== "string")
|
|
1966
|
+
invalidRecord();
|
|
1967
|
+
const { messageId } = entry;
|
|
1968
|
+
if (messageId !== undefined) {
|
|
1969
|
+
if (typeof messageId !== "string" || this.messages.get(messageId) !== null)
|
|
1970
|
+
invalidRecord();
|
|
1971
|
+
if (this.inFlight && this.inFlight !== messageId)
|
|
1972
|
+
invalidRecord();
|
|
1973
|
+
this.inFlight = undefined;
|
|
1974
|
+
this.messages.set(messageId, entry.number);
|
|
1975
|
+
}
|
|
1976
|
+
this.lastTurn = {
|
|
1977
|
+
number: entry.number,
|
|
1978
|
+
...messageId === undefined ? {} : { messageId },
|
|
1979
|
+
startedAt: entry.startedAt,
|
|
1980
|
+
finishedAt: null,
|
|
1981
|
+
status: "running",
|
|
1982
|
+
stopReason: null,
|
|
1983
|
+
prompt: entry.prompt,
|
|
1984
|
+
response: ""
|
|
1985
|
+
};
|
|
1986
|
+
if (this.view === "history")
|
|
1987
|
+
this.turns.push(this.lastTurn);
|
|
1988
|
+
return true;
|
|
1989
|
+
}
|
|
1990
|
+
if (last?.status !== "running" || entry?.number !== last.number)
|
|
1991
|
+
invalidRecord();
|
|
1992
|
+
if (entry.type === "text" && typeof entry.text === "string") {
|
|
1993
|
+
if (this.view !== "finalResponse")
|
|
1994
|
+
last.response += entry.text;
|
|
1995
|
+
return entry.text.length > 0;
|
|
1996
|
+
}
|
|
1997
|
+
if (entry.type !== "end" || !(entry.status === "completed" || entry.status === "failed" || entry.status === "interrupted") || typeof entry.finishedAt !== "string" || !(entry.stopReason === null || typeof entry.stopReason === "string"))
|
|
1998
|
+
invalidRecord();
|
|
1999
|
+
last.status = entry.status;
|
|
2000
|
+
last.finishedAt = entry.finishedAt;
|
|
2001
|
+
last.stopReason = entry.stopReason;
|
|
2002
|
+
if (entry.reportedModel !== undefined) {
|
|
2003
|
+
if (typeof entry.reportedModel !== "string")
|
|
2004
|
+
invalidRecord();
|
|
2005
|
+
last.reportedModel = entry.reportedModel;
|
|
2006
|
+
}
|
|
2007
|
+
if (entry.finalResponse !== undefined) {
|
|
2008
|
+
if (typeof entry.finalResponse !== "string" || entry.status !== "completed" || entry.stopReason !== "end_turn")
|
|
2009
|
+
invalidRecord();
|
|
2010
|
+
last.finalResponse = entry.finalResponse;
|
|
2011
|
+
}
|
|
2012
|
+
return true;
|
|
2013
|
+
}
|
|
2014
|
+
latestResponse() {
|
|
2015
|
+
if (this.partial.length)
|
|
2016
|
+
invalidRecord();
|
|
2017
|
+
return this.lastTurn?.response ?? null;
|
|
2018
|
+
}
|
|
2019
|
+
latestResult() {
|
|
2020
|
+
const turn = this.lastTurn;
|
|
2021
|
+
if (this.partial.length || turn?.status !== "completed" || turn.stopReason !== "end_turn")
|
|
2022
|
+
return null;
|
|
2023
|
+
if (turn.finalResponse !== undefined)
|
|
2024
|
+
return { source: "final", text: turn.finalResponse };
|
|
2025
|
+
return turn.response ? { source: "transcript", text: turn.response } : null;
|
|
2026
|
+
}
|
|
2027
|
+
latestFinalResponse() {
|
|
2028
|
+
if (this.partial.length)
|
|
2029
|
+
return null;
|
|
2030
|
+
return this.lastTurn?.finalResponse ?? null;
|
|
2031
|
+
}
|
|
2032
|
+
consume(bytes) {
|
|
2033
|
+
let start = 0;
|
|
2034
|
+
let changed = false;
|
|
2035
|
+
for (let end = bytes.indexOf(10);end !== -1; end = bytes.indexOf(10, start)) {
|
|
2036
|
+
const fragment = bytes.subarray(start, end);
|
|
2037
|
+
const line = this.partial.length ? Buffer.concat([...this.partial, fragment]) : fragment;
|
|
2038
|
+
this.partial = [];
|
|
2039
|
+
if (this.apply(line))
|
|
2040
|
+
changed = true;
|
|
2041
|
+
start = end + 1;
|
|
2042
|
+
}
|
|
2043
|
+
if (start < bytes.length)
|
|
2044
|
+
this.partial.push(bytes.subarray(start));
|
|
2045
|
+
return changed;
|
|
2046
|
+
}
|
|
2047
|
+
async drain(path) {
|
|
2048
|
+
let file;
|
|
2049
|
+
try {
|
|
2050
|
+
file = await open2(path, constants2.O_RDONLY | constants2.O_NOFOLLOW | constants2.O_NONBLOCK);
|
|
2051
|
+
} catch (error) {
|
|
2052
|
+
if (!this.available && error.code === "ENOENT")
|
|
2053
|
+
return false;
|
|
2054
|
+
throw error;
|
|
2055
|
+
}
|
|
2056
|
+
try {
|
|
2057
|
+
const stat = await file.stat();
|
|
2058
|
+
if (!stat.isFile())
|
|
2059
|
+
throw new Error("The selected turn journal must be a regular file.");
|
|
2060
|
+
if (this.available && this.inode !== stat.ino || stat.size < this.offset)
|
|
2061
|
+
throw new Error("The selected turn journal was replaced or truncated.");
|
|
2062
|
+
let changed = !this.available;
|
|
2063
|
+
this.available = true;
|
|
2064
|
+
this.inode = stat.ino;
|
|
2065
|
+
while (this.offset < stat.size) {
|
|
2066
|
+
const buffer = Buffer.allocUnsafe(Math.min(64 * 1024, stat.size - this.offset));
|
|
2067
|
+
const { bytesRead } = await file.read(buffer, 0, buffer.length, this.offset);
|
|
2068
|
+
if (!bytesRead)
|
|
2069
|
+
throw new Error("The selected turn journal was truncated while reading.");
|
|
2070
|
+
this.offset += bytesRead;
|
|
2071
|
+
if (this.consume(buffer.subarray(0, bytesRead)))
|
|
2072
|
+
changed = true;
|
|
2073
|
+
}
|
|
2074
|
+
return changed;
|
|
2075
|
+
} finally {
|
|
2076
|
+
await file.close();
|
|
2077
|
+
}
|
|
2078
|
+
}
|
|
2079
|
+
snapshot(session) {
|
|
2080
|
+
const turns = this.turns.map((turn) => ({ ...turn }));
|
|
2081
|
+
const last = turns.at(-1);
|
|
2082
|
+
if (last?.status === "running" && session.status !== "running") {
|
|
2083
|
+
last.status = session.status;
|
|
2084
|
+
last.finishedAt = session.finishedAt;
|
|
2085
|
+
}
|
|
2086
|
+
const pendingStatus = session.status === "running" ? "queued" : "discarded";
|
|
2087
|
+
const messages = Array.from(this.messages, ([messageId, turnNumber]) => {
|
|
2088
|
+
if (turnNumber === "discarded")
|
|
2089
|
+
return { messageId, status: "discarded", turnNumber: null };
|
|
2090
|
+
let status = pendingStatus;
|
|
2091
|
+
if (turnNumber !== null)
|
|
2092
|
+
status = "delivered";
|
|
2093
|
+
else if (messageId === this.inFlight && session.status === "interrupted" && session.finishedAt === null)
|
|
2094
|
+
status = "unknown";
|
|
2095
|
+
return { messageId, status, turnNumber };
|
|
2096
|
+
});
|
|
2097
|
+
return {
|
|
2098
|
+
sessionId: session.id,
|
|
2099
|
+
available: this.available,
|
|
2100
|
+
turns,
|
|
2101
|
+
...messages.length ? { messages } : {}
|
|
2102
|
+
};
|
|
2103
|
+
}
|
|
2104
|
+
}
|
|
2105
|
+
function journalPath(id) {
|
|
2106
|
+
if (!uuidPattern.test(id))
|
|
2107
|
+
throw new Error("Expected a Taube session ID.");
|
|
2108
|
+
return join8(taubeHome(), "turns", `${id}.ndjson`);
|
|
2109
|
+
}
|
|
2110
|
+
async function readLatestTurnText(id, full, final, result = false) {
|
|
2111
|
+
const journal = new TurnJournal(full || result ? "response" : "finalResponse");
|
|
2112
|
+
await journal.drain(journalPath(id));
|
|
2113
|
+
return {
|
|
2114
|
+
...full ? { response: journal.latestResponse() } : {},
|
|
2115
|
+
...final ? { finalResponse: journal.latestFinalResponse() } : {},
|
|
2116
|
+
...result ? { result: journal.latestResult() } : {}
|
|
2117
|
+
};
|
|
2118
|
+
}
|
|
2119
|
+
async function* turnHistory(selected, options) {
|
|
2120
|
+
const path = journalPath(selected.id);
|
|
2121
|
+
const journal = new TurnJournal;
|
|
2122
|
+
const { signal } = options;
|
|
2123
|
+
if (signal.aborted)
|
|
2124
|
+
return;
|
|
2125
|
+
if (!options.watch || selected.status !== "running") {
|
|
2126
|
+
await journal.drain(path);
|
|
2127
|
+
yield journal.snapshot(selected);
|
|
2128
|
+
return;
|
|
2129
|
+
}
|
|
2130
|
+
let pending = true;
|
|
2131
|
+
const metadata = sessionRecordPath(selected);
|
|
2132
|
+
let checkSession = true;
|
|
2133
|
+
let resume;
|
|
2134
|
+
function wake() {
|
|
2135
|
+
pending = true;
|
|
2136
|
+
resume?.();
|
|
2137
|
+
}
|
|
2138
|
+
watchFile(path, { interval: 100 }, wake);
|
|
2139
|
+
const reconcile = setInterval(() => {
|
|
2140
|
+
checkSession = true;
|
|
2141
|
+
wake();
|
|
2142
|
+
}, 1000);
|
|
2143
|
+
signal.addEventListener("abort", wake);
|
|
2144
|
+
try {
|
|
2145
|
+
let first = true;
|
|
2146
|
+
let session = selected;
|
|
2147
|
+
while (!signal.aborted) {
|
|
2148
|
+
if (!pending)
|
|
2149
|
+
await new Promise((resolve) => {
|
|
2150
|
+
resume = resolve;
|
|
2151
|
+
});
|
|
2152
|
+
resume = undefined;
|
|
2153
|
+
if (signal.aborted)
|
|
2154
|
+
return;
|
|
2155
|
+
pending = false;
|
|
2156
|
+
if (checkSession) {
|
|
2157
|
+
checkSession = false;
|
|
2158
|
+
session = await readCurrentSession(metadata);
|
|
2159
|
+
if (session.id !== selected.id || session.dispatcher !== selected.dispatcher)
|
|
2160
|
+
throw new Error("The selected session record changed identity.");
|
|
2161
|
+
}
|
|
2162
|
+
const changed = await journal.drain(path);
|
|
2163
|
+
if (signal.aborted)
|
|
2164
|
+
return;
|
|
2165
|
+
const terminal = session.status !== "running";
|
|
2166
|
+
if (first || changed || terminal)
|
|
2167
|
+
yield journal.snapshot(session);
|
|
2168
|
+
if (terminal)
|
|
2169
|
+
return;
|
|
2170
|
+
first = false;
|
|
2171
|
+
}
|
|
2172
|
+
} finally {
|
|
2173
|
+
clearInterval(reconcile);
|
|
2174
|
+
unwatchFile(path, wake);
|
|
2175
|
+
signal.removeEventListener("abort", wake);
|
|
2176
|
+
}
|
|
2177
|
+
}
|
|
2178
|
+
var init_turn_history = __esm(() => {
|
|
2179
|
+
init_home();
|
|
2180
|
+
init_session_channel();
|
|
2181
|
+
init_sessions();
|
|
2182
|
+
});
|
|
2183
|
+
|
|
2184
|
+
// src/sessions-wait.ts
|
|
2185
|
+
async function waitForSessions({
|
|
2186
|
+
dispatcher,
|
|
2187
|
+
ids,
|
|
2188
|
+
requestIds,
|
|
2189
|
+
any,
|
|
2190
|
+
timeout,
|
|
2191
|
+
includeResult = false,
|
|
2192
|
+
includeResponse = false,
|
|
2193
|
+
includeFinalResponse = false
|
|
2194
|
+
}) {
|
|
2195
|
+
if (ids.length === 0 && requestIds.length === 0)
|
|
2196
|
+
throw new Error("Provide a Taube session ID or --request-id NAME.");
|
|
2197
|
+
if (ids.some((id) => !id.trim()))
|
|
2198
|
+
throw new Error("Taube session IDs must be non-empty.");
|
|
2199
|
+
if (requestIds.some((id) => !id.trim()))
|
|
2200
|
+
throw new Error("--request-id needs a non-empty name.");
|
|
2201
|
+
const timeoutMs = timeout === undefined ? undefined : Number(timeout);
|
|
2202
|
+
if (timeoutMs !== undefined && (!/^\d+$/.test(timeout ?? "") || timeoutMs < 1 || timeoutMs > 2147483647))
|
|
2203
|
+
throw new Error("--timeout-ms must be a positive integer up to 2147483647.");
|
|
2204
|
+
const sessionIds = new Set(ids);
|
|
2205
|
+
const names = new Set(requestIds);
|
|
2206
|
+
const controller = new AbortController;
|
|
2207
|
+
const timer = timeoutMs === undefined ? undefined : setTimeout(() => controller.abort(), timeoutMs);
|
|
2208
|
+
let pending = "the initial session snapshot";
|
|
2209
|
+
let result;
|
|
2210
|
+
try {
|
|
2211
|
+
for await (const event of watchSessions({
|
|
2212
|
+
dispatcher,
|
|
2213
|
+
signal: controller.signal,
|
|
2214
|
+
snapshots: true
|
|
2215
|
+
})) {
|
|
2216
|
+
if (event.type !== "snapshot")
|
|
2217
|
+
continue;
|
|
2218
|
+
const byId = new Map(event.sessions.map((session) => [session.id, session]));
|
|
2219
|
+
const selected = new Map;
|
|
2220
|
+
for (const id of sessionIds) {
|
|
2221
|
+
const session = byId.get(id);
|
|
2222
|
+
if (!session)
|
|
2223
|
+
throw new Error(`Session ${id} was not found in the selected scope.`);
|
|
2224
|
+
selected.set(id, session);
|
|
2225
|
+
}
|
|
2226
|
+
const unregistered = [];
|
|
2227
|
+
for (const name of names) {
|
|
2228
|
+
const session = findSessionByRequestId(event.sessions, name, dispatcher);
|
|
2229
|
+
if (session) {
|
|
2230
|
+
selected.set(session.id, session);
|
|
2231
|
+
} else {
|
|
2232
|
+
if (dispatcher === null)
|
|
2233
|
+
throw new Error(`Request ID ${JSON.stringify(name)} was not found. Use --dispatcher ID or --mine to wait for registration.`);
|
|
2234
|
+
unregistered.push(name);
|
|
2235
|
+
}
|
|
2236
|
+
}
|
|
2237
|
+
const finished = [];
|
|
2238
|
+
const running = [];
|
|
2239
|
+
for (const session of selected.values()) {
|
|
2240
|
+
if (matchesStatus(session, "finished"))
|
|
2241
|
+
finished.push(session);
|
|
2242
|
+
else
|
|
2243
|
+
running.push(session.id);
|
|
2244
|
+
}
|
|
2245
|
+
if (any ? finished.length > 0 : !unregistered.length && !running.length) {
|
|
2246
|
+
result = any ? {
|
|
2247
|
+
sessions: finished,
|
|
2248
|
+
pendingSessionIds: running,
|
|
2249
|
+
pendingRequestIds: unregistered
|
|
2250
|
+
} : { sessions: finished };
|
|
2251
|
+
break;
|
|
2252
|
+
}
|
|
2253
|
+
pending = [
|
|
2254
|
+
unregistered.length && `request IDs ${unregistered.map((name) => JSON.stringify(name)).join(", ")} to register with dispatcher ${JSON.stringify(dispatcher)}`,
|
|
2255
|
+
running.length && `sessions ${running.join(", ")} to finish`
|
|
2256
|
+
].filter(Boolean).join(" and ");
|
|
2257
|
+
}
|
|
2258
|
+
} finally {
|
|
2259
|
+
clearTimeout(timer);
|
|
2260
|
+
}
|
|
2261
|
+
if (!result)
|
|
2262
|
+
throw new Error(`Timed out after ${timeoutMs} ms waiting for ${pending}. Check the selectors or increase --timeout-ms.`);
|
|
2263
|
+
if (!includeResponse && !includeFinalResponse && !includeResult)
|
|
2264
|
+
return result;
|
|
2265
|
+
result.sessions = await Promise.all(result.sessions.map(async (session) => {
|
|
2266
|
+
const completedResult = includeResult && session.status === "completed";
|
|
2267
|
+
if (!includeResponse && !includeFinalResponse && !completedResult)
|
|
2268
|
+
return { ...session, result: null };
|
|
2269
|
+
const text = await readLatestTurnText(session.id, includeResponse, includeFinalResponse, completedResult);
|
|
2270
|
+
return {
|
|
2271
|
+
...session,
|
|
2272
|
+
...includeResult ? { result: null } : {},
|
|
2273
|
+
...text
|
|
2274
|
+
};
|
|
2275
|
+
}));
|
|
2276
|
+
return result;
|
|
2277
|
+
}
|
|
2278
|
+
var init_sessions_wait = __esm(() => {
|
|
2279
|
+
init_session_watch();
|
|
2280
|
+
init_sessions();
|
|
2281
|
+
init_turn_history();
|
|
2282
|
+
});
|
|
2283
|
+
|
|
2284
|
+
// src/sessions-prune.ts
|
|
2285
|
+
import { randomUUID as randomUUID5 } from "node:crypto";
|
|
2286
|
+
import {
|
|
2287
|
+
closeSync,
|
|
2288
|
+
constants as constants3,
|
|
2289
|
+
fstatSync,
|
|
2290
|
+
lstatSync,
|
|
2291
|
+
openSync,
|
|
2292
|
+
readdirSync,
|
|
2293
|
+
readFileSync,
|
|
2294
|
+
realpathSync,
|
|
2295
|
+
statSync as statSync2,
|
|
2296
|
+
unlinkSync
|
|
2297
|
+
} from "node:fs";
|
|
2298
|
+
import { dirname as dirname2, join as join9 } from "node:path";
|
|
2299
|
+
import { setTimeout as delay4 } from "node:timers/promises";
|
|
2300
|
+
function missing(error) {
|
|
2301
|
+
return error.code === "ENOENT";
|
|
2302
|
+
}
|
|
2303
|
+
function storeDirectory(path) {
|
|
2304
|
+
const parent = dirname2(path);
|
|
2305
|
+
if (parent !== path && !storeDirectory(parent))
|
|
2306
|
+
return;
|
|
2307
|
+
try {
|
|
2308
|
+
const stat = lstatSync(path, { bigint: true });
|
|
2309
|
+
if (!stat.isDirectory())
|
|
2310
|
+
throw new Error(`Expected a directory without symlinks: ${path}`);
|
|
2311
|
+
return { path, dev: stat.dev, ino: stat.ino };
|
|
2312
|
+
} catch (error) {
|
|
2313
|
+
if (missing(error))
|
|
2314
|
+
return;
|
|
2315
|
+
throw error;
|
|
2316
|
+
}
|
|
2317
|
+
}
|
|
2318
|
+
function inDirectory(directory, operation) {
|
|
2319
|
+
const previous = process.cwd();
|
|
2320
|
+
try {
|
|
2321
|
+
process.chdir(directory.path);
|
|
2322
|
+
} catch (error) {
|
|
2323
|
+
if (missing(error))
|
|
2324
|
+
throw new DirectoryChanged("Session store directory disappeared.");
|
|
2325
|
+
throw error;
|
|
2326
|
+
}
|
|
2327
|
+
try {
|
|
2328
|
+
const here = statSync2(".", { bigint: true });
|
|
2329
|
+
if (here.dev !== directory.dev || here.ino !== directory.ino || realpathSync.native(".") !== directory.path)
|
|
2330
|
+
throw new DirectoryChanged("Session store directory changed.");
|
|
2331
|
+
return operation();
|
|
2332
|
+
} finally {
|
|
2333
|
+
process.chdir(previous);
|
|
2334
|
+
}
|
|
2335
|
+
}
|
|
2336
|
+
function releaseMarker(directory, name) {
|
|
2337
|
+
try {
|
|
2338
|
+
inDirectory(directory, () => unlinkSync(name));
|
|
2339
|
+
} catch (error) {
|
|
2340
|
+
if (!(error instanceof DirectoryChanged))
|
|
2341
|
+
throw error;
|
|
2342
|
+
}
|
|
2343
|
+
}
|
|
2344
|
+
async function withPruneLock(directory, work) {
|
|
2345
|
+
const owner = await currentOwner();
|
|
2346
|
+
const identity = Buffer.from(JSON.stringify(owner)).toString("base64url");
|
|
2347
|
+
const name = `.prune.${identity}.${randomUUID5()}`;
|
|
2348
|
+
for (let attempt = 0;attempt < 20; attempt++) {
|
|
2349
|
+
inDirectory(directory, () => closeSync(openSync(name, "wx", 384)));
|
|
2350
|
+
try {
|
|
2351
|
+
let busy = false;
|
|
2352
|
+
for (const other of inDirectory(directory, () => readdirSync("."))) {
|
|
2353
|
+
const match = markerPattern.exec(other);
|
|
2354
|
+
if (!match || !uuidPattern.test(match[2]) || other === name)
|
|
2355
|
+
continue;
|
|
2356
|
+
let peer;
|
|
2357
|
+
try {
|
|
2358
|
+
peer = JSON.parse(Buffer.from(match[1], "base64url").toString("utf8"));
|
|
2359
|
+
} catch {}
|
|
2360
|
+
if (!await ownerIsDead(peer)) {
|
|
2361
|
+
busy = true;
|
|
2362
|
+
break;
|
|
2363
|
+
}
|
|
2364
|
+
try {
|
|
2365
|
+
inDirectory(directory, () => {
|
|
2366
|
+
const stat = lstatSync(other);
|
|
2367
|
+
if (stat.isFile() && stat.size === 0)
|
|
2368
|
+
unlinkSync(other);
|
|
2369
|
+
});
|
|
2370
|
+
} catch (error) {
|
|
2371
|
+
if (!missing(error))
|
|
2372
|
+
throw error;
|
|
2373
|
+
}
|
|
2374
|
+
}
|
|
2375
|
+
if (!busy)
|
|
2376
|
+
return work();
|
|
2377
|
+
} finally {
|
|
2378
|
+
releaseMarker(directory, name);
|
|
2379
|
+
}
|
|
2380
|
+
await delay4(50 + Math.random() * 100);
|
|
2381
|
+
}
|
|
2382
|
+
throw new Error("Another session prune is active. Retry after it finishes.");
|
|
2383
|
+
}
|
|
2384
|
+
function storedTime(value) {
|
|
2385
|
+
if (typeof value !== "string")
|
|
2386
|
+
return NaN;
|
|
2387
|
+
const time = Date.parse(value);
|
|
2388
|
+
if (!Number.isFinite(time))
|
|
2389
|
+
return NaN;
|
|
2390
|
+
const iso = new Date(time).toISOString();
|
|
2391
|
+
return value === iso || value === iso.replace(".000Z", "Z") ? time : NaN;
|
|
2392
|
+
}
|
|
2393
|
+
function readRecord(path) {
|
|
2394
|
+
try {
|
|
2395
|
+
const file = openSync(path, constants3.O_RDONLY | constants3.O_NOFOLLOW | constants3.O_NONBLOCK);
|
|
2396
|
+
try {
|
|
2397
|
+
if (!fstatSync(file).isFile())
|
|
2398
|
+
return;
|
|
2399
|
+
return JSON.parse(readFileSync(file, "utf8"));
|
|
2400
|
+
} finally {
|
|
2401
|
+
closeSync(file);
|
|
2402
|
+
}
|
|
2403
|
+
} catch (error) {
|
|
2404
|
+
if (error instanceof SyntaxError || missing(error) || error.code === "ELOOP")
|
|
2405
|
+
return;
|
|
2406
|
+
throw error;
|
|
2407
|
+
}
|
|
2408
|
+
}
|
|
2409
|
+
function nonempty(value) {
|
|
2410
|
+
return typeof value === "string" && value.trim().length > 0;
|
|
2411
|
+
}
|
|
2412
|
+
function select(dispatcher, cutoff) {
|
|
2413
|
+
const candidates = new Map;
|
|
2414
|
+
const seen = new Set;
|
|
2415
|
+
const duplicates = new Set;
|
|
2416
|
+
function claim(id) {
|
|
2417
|
+
if (seen.has(id))
|
|
2418
|
+
duplicates.add(id);
|
|
2419
|
+
seen.add(id);
|
|
2420
|
+
}
|
|
2421
|
+
for (const entry of readdirSync(".", { withFileTypes: true })) {
|
|
2422
|
+
const { name } = entry;
|
|
2423
|
+
if (!name.endsWith(".json"))
|
|
2424
|
+
continue;
|
|
2425
|
+
const stem = name.slice(0, -5).toLowerCase();
|
|
2426
|
+
const unnamed = uuidPattern.test(stem);
|
|
2427
|
+
if (unnamed)
|
|
2428
|
+
claim(stem);
|
|
2429
|
+
else if (!/^request-[\da-f]{64}\.json$/.test(name))
|
|
2430
|
+
continue;
|
|
2431
|
+
if (!entry.isFile())
|
|
2432
|
+
continue;
|
|
2433
|
+
const record = readRecord(name);
|
|
2434
|
+
if (!record)
|
|
2435
|
+
continue;
|
|
2436
|
+
const { session } = record;
|
|
2437
|
+
if (typeof session?.id !== "string" || !uuidPattern.test(session.id))
|
|
2438
|
+
continue;
|
|
2439
|
+
const id = session.id.toLowerCase();
|
|
2440
|
+
if (!unnamed || id !== stem)
|
|
2441
|
+
claim(id);
|
|
2442
|
+
if (session.id !== id || !record.owner || !Number.isSafeInteger(record.owner.pid) || record.owner.pid < 1 || !nonempty(session.target) || !nonempty(session.cwd) || session.dispatcher !== null && !nonempty(session.dispatcher) || dispatcher !== null && dispatcher !== session.dispatcher || session.requestId !== undefined && !nonempty(session.requestId) || sessionRecordName(session) !== name || !["completed", "failed", "interrupted"].includes(session.status) || !Number.isSafeInteger(session.exitCode))
|
|
2443
|
+
continue;
|
|
2444
|
+
const finished = storedTime(session.finishedAt);
|
|
2445
|
+
if (storedTime(session.startedAt) <= finished && finished < cutoff)
|
|
2446
|
+
candidates.set(id, name);
|
|
2447
|
+
}
|
|
2448
|
+
for (const id of duplicates)
|
|
2449
|
+
candidates.delete(id);
|
|
2450
|
+
return candidates;
|
|
2451
|
+
}
|
|
2452
|
+
function removeJournal(id) {
|
|
2453
|
+
const name = `${id}.ndjson`;
|
|
2454
|
+
try {
|
|
2455
|
+
if (!lstatSync(name).isFile())
|
|
2456
|
+
throw new Error("Expected a regular turn journal.");
|
|
2457
|
+
unlinkSync(name);
|
|
2458
|
+
} catch (error) {
|
|
2459
|
+
if (!missing(error))
|
|
2460
|
+
throw error;
|
|
2461
|
+
}
|
|
2462
|
+
}
|
|
2463
|
+
async function pruneSessions(options) {
|
|
2464
|
+
const days = options.olderThan && /^([1-9]\d*)d$/.exec(options.olderThan)?.[1];
|
|
2465
|
+
const age = Number(days) * day;
|
|
2466
|
+
if (!days || !Number.isSafeInteger(age))
|
|
2467
|
+
throw new Error("--older-than requires a positive whole number of days, for example 30d.");
|
|
2468
|
+
const cutoff = Date.now() - age;
|
|
2469
|
+
const turns = join9(taubeHome(), "turns");
|
|
2470
|
+
const result = {
|
|
2471
|
+
mode: options.apply ? "applied" : "preview",
|
|
2472
|
+
selectedIds: [],
|
|
2473
|
+
selectedCount: 0,
|
|
2474
|
+
deletedCount: 0,
|
|
2475
|
+
failedIds: []
|
|
2476
|
+
};
|
|
2477
|
+
function run(directory) {
|
|
2478
|
+
const candidates = inDirectory(directory, () => select(options.dispatcher, cutoff));
|
|
2479
|
+
result.selectedIds = [...candidates.keys()].sort();
|
|
2480
|
+
result.selectedCount = result.selectedIds.length;
|
|
2481
|
+
if (options.apply) {
|
|
2482
|
+
for (const [id, name] of candidates) {
|
|
2483
|
+
try {
|
|
2484
|
+
const journals = storeDirectory(turns);
|
|
2485
|
+
if (journals)
|
|
2486
|
+
inDirectory(journals, () => removeJournal(id));
|
|
2487
|
+
inDirectory(directory, () => unlinkSync(name));
|
|
2488
|
+
result.deletedCount++;
|
|
2489
|
+
} catch (error) {
|
|
2490
|
+
result.failedIds.push(id);
|
|
2491
|
+
console.error(`taube: could not prune ${id}: ${error instanceof Error ? error.message : String(error)}`);
|
|
2492
|
+
}
|
|
2493
|
+
}
|
|
2494
|
+
}
|
|
2495
|
+
return result;
|
|
2496
|
+
}
|
|
2497
|
+
const directory = storeDirectory(sessionsDirectory());
|
|
2498
|
+
if (!directory)
|
|
2499
|
+
return result;
|
|
2500
|
+
return options.apply ? withPruneLock(directory, () => run(directory)) : run(directory);
|
|
2501
|
+
}
|
|
2502
|
+
var day = 86400000, DirectoryChanged, markerPattern;
|
|
2503
|
+
var init_sessions_prune = __esm(() => {
|
|
2504
|
+
init_home();
|
|
2505
|
+
init_session_channel();
|
|
2506
|
+
init_sessions();
|
|
2507
|
+
DirectoryChanged = class DirectoryChanged extends Error {
|
|
2508
|
+
};
|
|
2509
|
+
markerPattern = /^\.prune\.([A-Za-z0-9_-]+)\.(.+)$/;
|
|
2510
|
+
});
|
|
2511
|
+
|
|
2512
|
+
// src/detach.ts
|
|
2513
|
+
import { fork } from "node:child_process";
|
|
2514
|
+
import { on } from "node:events";
|
|
2515
|
+
import { stat } from "node:fs/promises";
|
|
2516
|
+
function send(peer, message) {
|
|
2517
|
+
return new Promise((resolve, reject) => {
|
|
2518
|
+
if (!peer.send)
|
|
2519
|
+
throw new Error("Missing dispatch IPC channel.");
|
|
2520
|
+
peer.send(message, undefined, {}, (error) => error ? reject(error) : resolve());
|
|
2521
|
+
});
|
|
2522
|
+
}
|
|
2523
|
+
function inbox(peer) {
|
|
2524
|
+
if (!peer.connected)
|
|
2525
|
+
throw new Error("Dispatch IPC channel closed.");
|
|
2526
|
+
const messages = on(peer, "message", { close: ["disconnect"] });
|
|
2527
|
+
return async function receive() {
|
|
2528
|
+
const next = await messages.next();
|
|
2529
|
+
if (next.done)
|
|
2530
|
+
throw new Error("Dispatch IPC channel closed.");
|
|
2531
|
+
return next.value[0];
|
|
2532
|
+
};
|
|
2533
|
+
}
|
|
2534
|
+
async function dispatchDetached(entry, target, options) {
|
|
2535
|
+
const prompt = await readPrompt(options);
|
|
2536
|
+
if (options.cwd && !(await stat(options.cwd)).isDirectory())
|
|
2537
|
+
throw new Error("--cwd must be a directory.");
|
|
2538
|
+
const worker = fork(new URL(entry), ["_dispatch-worker"], {
|
|
2539
|
+
detached: true,
|
|
2540
|
+
stdio: ["ignore", "ignore", "ignore", "ipc"]
|
|
2541
|
+
});
|
|
2542
|
+
try {
|
|
2543
|
+
const receive = inbox(worker);
|
|
2544
|
+
await send(worker, {
|
|
2545
|
+
target,
|
|
2546
|
+
options: { ...options, prompt, promptFile: undefined, output: "text" }
|
|
2547
|
+
});
|
|
2548
|
+
const registration = await receive();
|
|
2549
|
+
if ("error" in registration)
|
|
2550
|
+
throw new Error(registration.error);
|
|
2551
|
+
if (typeof registration.sessionId !== "string" || !registration.sessionId)
|
|
2552
|
+
throw new Error("Missing session ID from dispatch worker.");
|
|
2553
|
+
const receipt = {
|
|
2554
|
+
sessionId: registration.sessionId,
|
|
2555
|
+
requestId: options.requestId ?? null,
|
|
2556
|
+
target: target.id,
|
|
2557
|
+
dispatcher: options.dispatcher ?? null,
|
|
2558
|
+
status: "registered"
|
|
2559
|
+
};
|
|
2560
|
+
await new Promise((resolve, reject) => {
|
|
2561
|
+
process.stdout.once("error", reject);
|
|
2562
|
+
process.stdout.write(`${JSON.stringify(receipt)}
|
|
2563
|
+
`, (error) => {
|
|
2564
|
+
if (error)
|
|
2565
|
+
return reject(error);
|
|
2566
|
+
process.stdout.off("error", reject);
|
|
2567
|
+
resolve();
|
|
2568
|
+
});
|
|
2569
|
+
});
|
|
2570
|
+
await send(worker, "start");
|
|
2571
|
+
return 0;
|
|
2572
|
+
} finally {
|
|
2573
|
+
if (worker.connected)
|
|
2574
|
+
worker.disconnect();
|
|
2575
|
+
worker.unref();
|
|
2576
|
+
}
|
|
2577
|
+
}
|
|
2578
|
+
async function runDetachedWorker() {
|
|
2579
|
+
const receive = inbox(process);
|
|
2580
|
+
try {
|
|
2581
|
+
const { target, options } = await receive();
|
|
2582
|
+
await Promise.resolve().then(() => init_direct_acp());
|
|
2583
|
+
return await runDirectAcp(target, options, async (sessionId) => {
|
|
2584
|
+
await send(process, { sessionId });
|
|
2585
|
+
if (await receive() !== "start")
|
|
2586
|
+
throw new Error("Dispatch registration was not acknowledged.");
|
|
2587
|
+
if (process.connected)
|
|
2588
|
+
process.disconnect?.();
|
|
2589
|
+
});
|
|
2590
|
+
} catch (error) {
|
|
2591
|
+
if (process.connected)
|
|
2592
|
+
await send(process, {
|
|
2593
|
+
error: error instanceof Error ? error.message : String(error)
|
|
2594
|
+
});
|
|
2595
|
+
return 1;
|
|
2596
|
+
} finally {
|
|
2597
|
+
if (process.connected)
|
|
2598
|
+
process.disconnect?.();
|
|
2599
|
+
}
|
|
2600
|
+
}
|
|
2601
|
+
var init_detach = __esm(() => {
|
|
2602
|
+
init_prompt();
|
|
2603
|
+
});
|
|
2604
|
+
|
|
2605
|
+
// src/auth-check.ts
|
|
2606
|
+
import { execFile as execFile3 } from "node:child_process";
|
|
2607
|
+
import { stripVTControlCharacters } from "node:util";
|
|
2608
|
+
function probe(target, command, args) {
|
|
2609
|
+
return new Promise((resolve, reject) => {
|
|
2610
|
+
const child = execFile3(command, args, {
|
|
2611
|
+
encoding: "utf8",
|
|
2612
|
+
timeout: 8000,
|
|
2613
|
+
killSignal: "SIGKILL",
|
|
2614
|
+
maxBuffer: 128 * 1024,
|
|
2615
|
+
windowsHide: true,
|
|
2616
|
+
env: { ...process.env, NO_COLOR: "1" }
|
|
2617
|
+
}, (error, stdout, stderr) => {
|
|
2618
|
+
if (error && (error.killed || error.signal || error.code !== 1)) {
|
|
2619
|
+
const reason = error.code === "ENOENT" ? "CLI not found" : "status command did not complete";
|
|
2620
|
+
reject(new Error(`Could not check ${target} authentication: ${reason}.`));
|
|
2621
|
+
} else {
|
|
2622
|
+
resolve({ code: error ? 1 : 0, stdout, stderr });
|
|
2623
|
+
}
|
|
2624
|
+
});
|
|
2625
|
+
child.stdin?.end();
|
|
2626
|
+
});
|
|
2627
|
+
}
|
|
2628
|
+
function jsonObject(output) {
|
|
2629
|
+
try {
|
|
2630
|
+
const value = JSON.parse(output);
|
|
2631
|
+
if (value !== null && typeof value === "object" && !Array.isArray(value))
|
|
2632
|
+
return value;
|
|
2633
|
+
} catch {}
|
|
2634
|
+
}
|
|
2635
|
+
function authenticated(target, code, stdout, stderr) {
|
|
2636
|
+
if (target === "claude") {
|
|
2637
|
+
const loggedIn = jsonObject(stdout)?.loggedIn;
|
|
2638
|
+
if (loggedIn === false || code === 0 && loggedIn === true)
|
|
2639
|
+
return loggedIn;
|
|
2640
|
+
return;
|
|
2641
|
+
}
|
|
2642
|
+
const lines = stripVTControlCharacters(`${stdout}
|
|
2643
|
+
${stderr}`).split(/\r?\n/).map((line) => line.trim().replace(/^[✔✓✗✘×]\s*/u, ""));
|
|
2644
|
+
if (target === "grok") {
|
|
2645
|
+
const report = jsonObject(stdout);
|
|
2646
|
+
if (code === 0 && report && !("error" in report) && typeof report.authenticated === "boolean")
|
|
2647
|
+
return report.authenticated;
|
|
2648
|
+
if (code === 1 && lines.some((line) => /^(?:error:\s*)?(?:unauthenticated|unauthorized|authentication required|not (?:logged in|authenticated))\b/i.test(line)))
|
|
2649
|
+
return false;
|
|
2650
|
+
return;
|
|
2651
|
+
}
|
|
2652
|
+
if (lines.some((line) => /^(?:not (?:logged in|authenticated)|you are not logged in)\b/i.test(line)))
|
|
2653
|
+
return false;
|
|
2654
|
+
if (code !== 0)
|
|
2655
|
+
return;
|
|
2656
|
+
if (lines.some((line) => /^logged in using\s+/i.test(line)))
|
|
2657
|
+
return true;
|
|
2658
|
+
}
|
|
2659
|
+
async function checkAuth(target) {
|
|
2660
|
+
const commands = {
|
|
2661
|
+
codex: [process.env.CODEX_PATH ?? "codex", "login", "status"],
|
|
2662
|
+
claude: ["claude", "auth", "status", "--json"],
|
|
2663
|
+
grok: ["grok", "usage", "--json"]
|
|
2664
|
+
};
|
|
2665
|
+
const [command, ...args] = commands[target];
|
|
2666
|
+
const { code, stdout, stderr } = await probe(target, command, args);
|
|
2667
|
+
const result = authenticated(target, code, stdout, stderr);
|
|
2668
|
+
if (result === undefined)
|
|
2669
|
+
throw new Error(`Could not determine ${target} authentication from its status command.`);
|
|
2670
|
+
return { target, ...await recordAuth(target, result) };
|
|
2671
|
+
}
|
|
2672
|
+
var init_auth_check = __esm(() => {
|
|
2673
|
+
init_auth_state();
|
|
717
2674
|
});
|
|
718
2675
|
|
|
719
2676
|
// src/cli.ts
|
|
720
|
-
import {
|
|
2677
|
+
import { constants as constants4 } from "node:os";
|
|
2678
|
+
import { parseArgs as parseArgs2 } from "node:util";
|
|
721
2679
|
// package.json
|
|
722
2680
|
var package_default = {
|
|
723
2681
|
name: "@losoft/taube",
|
|
724
|
-
version: "0.1.
|
|
725
|
-
description: "Delegate a coding task to Codex, Claude Code, Grok Build
|
|
2682
|
+
version: "0.1.8",
|
|
2683
|
+
description: "Delegate a coding task to Codex, Claude Code, or Grok Build over the Agent Client Protocol.",
|
|
726
2684
|
type: "module",
|
|
727
2685
|
license: "MIT",
|
|
728
2686
|
repository: {
|
|
@@ -739,8 +2697,7 @@ var package_default = {
|
|
|
739
2697
|
"dist",
|
|
740
2698
|
"plugins",
|
|
741
2699
|
".agents/plugins",
|
|
742
|
-
".claude-plugin"
|
|
743
|
-
".cursor-plugin"
|
|
2700
|
+
".claude-plugin"
|
|
744
2701
|
],
|
|
745
2702
|
packageManager: "bun@1.4.2",
|
|
746
2703
|
engines: {
|
|
@@ -763,35 +2720,75 @@ var package_default = {
|
|
|
763
2720
|
};
|
|
764
2721
|
|
|
765
2722
|
// src/cli.ts
|
|
766
|
-
|
|
767
|
-
init_targets();
|
|
768
|
-
var targetIds = targets.map(({ id }) => id);
|
|
769
|
-
var help = `Usage:
|
|
770
|
-
taube --version
|
|
771
|
-
taube surfaces
|
|
772
|
-
taube auth check <${targetIds.join("|")}>
|
|
773
|
-
taube sessions [list] [--dispatcher ID | --mine | --all] [--status STATUS]
|
|
774
|
-
taube dispatch <${targetIds.join("|")}> [--model ID] [--effort LEVEL] [--cwd DIR] [--dispatcher ID]
|
|
2723
|
+
init_prompt();
|
|
775
2724
|
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
2725
|
+
// src/session-cli.ts
|
|
2726
|
+
init_prompt();
|
|
2727
|
+
init_session_channel();
|
|
2728
|
+
init_session_watch();
|
|
2729
|
+
init_sessions();
|
|
2730
|
+
import { execFile as execFile2 } from "node:child_process";
|
|
2731
|
+
import { isAbsolute } from "node:path";
|
|
2732
|
+
import { parseArgs } from "node:util";
|
|
782
2733
|
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
2734
|
+
// src/targets.ts
|
|
2735
|
+
init_adapter();
|
|
2736
|
+
init_auth_state();
|
|
2737
|
+
import { resolve as resolve4 } from "node:path";
|
|
2738
|
+
var targets = [
|
|
2739
|
+
{
|
|
2740
|
+
id: "codex",
|
|
2741
|
+
profile: "codex",
|
|
2742
|
+
launcher: "codex-acp",
|
|
2743
|
+
effortOption: "reasoning_effort"
|
|
2744
|
+
},
|
|
2745
|
+
{
|
|
2746
|
+
id: "claude",
|
|
2747
|
+
profile: "claude",
|
|
2748
|
+
launcher: "claude-agent-acp",
|
|
2749
|
+
effortOption: "effort"
|
|
2750
|
+
},
|
|
2751
|
+
{
|
|
2752
|
+
id: "grok",
|
|
2753
|
+
profile: "grok-build",
|
|
2754
|
+
launcher: "grok",
|
|
2755
|
+
effortOption: "reasoning_effort"
|
|
2756
|
+
}
|
|
2757
|
+
];
|
|
2758
|
+
async function surfaces(probe) {
|
|
2759
|
+
const discovery = probe ? await Promise.resolve().then(() => (init_model_discovery(), exports_model_discovery)) : null;
|
|
2760
|
+
const cwd = resolve4(probe?.cwd ?? ".");
|
|
2761
|
+
const selected = probe?.target ? [probe.target] : targets;
|
|
2762
|
+
const entries = await Promise.all(selected.map(async (target) => {
|
|
2763
|
+
const { id, profile, effortOption, launcher } = target;
|
|
2764
|
+
const onPath = Boolean(executableOnPath(launcher));
|
|
2765
|
+
const auth = await readAuth(id);
|
|
2766
|
+
const { source, ...models } = discovery ? await discovery.discoverModels(target, cwd, probe?.signal) : await resolveAdapter(target, cwd).then(({ source }) => ({ source }), () => ({ source: "unavailable" }));
|
|
2767
|
+
return {
|
|
2768
|
+
id,
|
|
2769
|
+
profile,
|
|
2770
|
+
effortOption,
|
|
2771
|
+
launcher: { command: launcher, onPath, source },
|
|
2772
|
+
...auth,
|
|
2773
|
+
...models
|
|
2774
|
+
};
|
|
2775
|
+
}));
|
|
2776
|
+
return { targets: entries };
|
|
2777
|
+
}
|
|
792
2778
|
|
|
793
|
-
|
|
794
|
-
|
|
2779
|
+
// src/session-cli.ts
|
|
2780
|
+
function findDispatcherProject(cwd) {
|
|
2781
|
+
const env = { ...process.env };
|
|
2782
|
+
delete env.GIT_DIR;
|
|
2783
|
+
delete env.GIT_WORK_TREE;
|
|
2784
|
+
delete env.GIT_COMMON_DIR;
|
|
2785
|
+
return new Promise((resolve) => {
|
|
2786
|
+
execFile2("git", ["rev-parse", "--show-toplevel"], { cwd, env, timeout: 1000 }, (error, stdout) => {
|
|
2787
|
+
const root = stdout.replace(/\n$/, "");
|
|
2788
|
+
resolve(!error && isAbsolute(root) ? root : cwd);
|
|
2789
|
+
});
|
|
2790
|
+
});
|
|
2791
|
+
}
|
|
795
2792
|
function currentDispatcher(explicit) {
|
|
796
2793
|
if (explicit !== undefined) {
|
|
797
2794
|
if (!explicit.trim())
|
|
@@ -808,14 +2805,254 @@ function currentDispatcher(explicit) {
|
|
|
808
2805
|
return `claude:${claude}`;
|
|
809
2806
|
return null;
|
|
810
2807
|
}
|
|
811
|
-
|
|
2808
|
+
var scopeOptions = {
|
|
2809
|
+
dispatcher: { type: "string" },
|
|
2810
|
+
mine: { type: "boolean" },
|
|
2811
|
+
all: { type: "boolean" }
|
|
2812
|
+
};
|
|
2813
|
+
function sessionScope(values) {
|
|
2814
|
+
if ([values.mine, values.all, values.dispatcher !== undefined].filter(Boolean).length > 1)
|
|
2815
|
+
throw new Error("Choose one of --mine, --dispatcher ID or --all.");
|
|
2816
|
+
const dispatcher = values.all ? null : currentDispatcher(values.dispatcher);
|
|
2817
|
+
if (!values.all && dispatcher === null)
|
|
2818
|
+
throw new Error("Could not identify the current dispatcher. Use --dispatcher ID to select a dispatcher or --all to include every dispatcher.");
|
|
2819
|
+
return dispatcher;
|
|
2820
|
+
}
|
|
2821
|
+
async function resolveSession(dispatcher, id, requestId) {
|
|
2822
|
+
if (requestId !== undefined && !requestId.trim())
|
|
2823
|
+
throw new Error("--request-id needs a non-empty value");
|
|
2824
|
+
const sessions = await listSessions();
|
|
2825
|
+
const session = requestId === undefined ? sessions.find((entry) => entry.id === id && (dispatcher === null || entry.dispatcher === dispatcher)) : findSessionByRequestId(sessions, requestId, dispatcher);
|
|
2826
|
+
if (!session)
|
|
2827
|
+
throw new Error(`Session ${requestId ?? id} was not found in the selected scope.`);
|
|
2828
|
+
return session;
|
|
2829
|
+
}
|
|
2830
|
+
async function resumeSession(args, help) {
|
|
2831
|
+
const { values, positionals } = parseArgs({
|
|
2832
|
+
args,
|
|
2833
|
+
allowPositionals: true,
|
|
2834
|
+
options: {
|
|
2835
|
+
dispatcher: scopeOptions.dispatcher,
|
|
2836
|
+
mine: scopeOptions.mine,
|
|
2837
|
+
"request-id": { type: "string", multiple: true },
|
|
2838
|
+
prompt: { type: "string" },
|
|
2839
|
+
"prompt-file": { type: "string" },
|
|
2840
|
+
output: { type: "string" },
|
|
2841
|
+
help: { type: "boolean", short: "h" }
|
|
2842
|
+
}
|
|
2843
|
+
});
|
|
2844
|
+
if (values.help) {
|
|
2845
|
+
console.log(help);
|
|
2846
|
+
return 0;
|
|
2847
|
+
}
|
|
2848
|
+
const output = values.output ?? "text";
|
|
2849
|
+
if (output !== "text" && output !== "json")
|
|
2850
|
+
throw new Error("--output must be text or json.");
|
|
2851
|
+
try {
|
|
2852
|
+
const ids = values["request-id"] ?? [];
|
|
2853
|
+
if (positionals.length + ids.length !== 1 || positionals[0]?.trim() === "")
|
|
2854
|
+
throw new Error("Usage: taube sessions resume (ID | --request-id NAME)");
|
|
2855
|
+
const prompt = promptSource(values.prompt, values["prompt-file"]);
|
|
2856
|
+
if (values.mine && values.dispatcher !== undefined)
|
|
2857
|
+
throw new Error("Choose one of --mine or --dispatcher ID.");
|
|
2858
|
+
const dispatcher = currentDispatcher(values.dispatcher);
|
|
2859
|
+
if (dispatcher === null)
|
|
2860
|
+
throw new Error("Could not identify the current dispatcher. Use --dispatcher ID to resume a session.");
|
|
2861
|
+
const source = await resolveSession(dispatcher, positionals[0], ids[0]);
|
|
2862
|
+
if (source.status !== "completed")
|
|
2863
|
+
throw new Error(`Session ${source.id} is ${source.status}. Resume requires a completed session.`);
|
|
2864
|
+
if (typeof source.acpSessionId !== "string" || !source.acpSessionId.trim())
|
|
2865
|
+
throw new Error("The source has no ACP session ID.");
|
|
2866
|
+
if (!isAbsolute(source.cwd))
|
|
2867
|
+
throw new Error("The source has no absolute working directory.");
|
|
2868
|
+
const target = targets.find(({ id }) => id === source.target);
|
|
2869
|
+
if (!target)
|
|
2870
|
+
throw new Error(`Unknown source target: ${source.target}.`);
|
|
2871
|
+
const dispatcherCwd = process.cwd();
|
|
2872
|
+
await Promise.resolve().then(() => init_direct_acp());
|
|
2873
|
+
return runDirectAcp(target, {
|
|
2874
|
+
...prompt,
|
|
2875
|
+
output,
|
|
2876
|
+
cwd: source.cwd,
|
|
2877
|
+
dispatcher,
|
|
2878
|
+
dispatcherCwd,
|
|
2879
|
+
dispatcherProject: await findDispatcherProject(dispatcherCwd),
|
|
2880
|
+
resume: { sourceId: source.id, acpSessionId: source.acpSessionId }
|
|
2881
|
+
});
|
|
2882
|
+
} catch (error) {
|
|
2883
|
+
if (output === "json")
|
|
2884
|
+
console.log(JSON.stringify({
|
|
2885
|
+
sessionId: null,
|
|
2886
|
+
status: "failed",
|
|
2887
|
+
exitCode: 1,
|
|
2888
|
+
error: error instanceof Error ? error.message : String(error),
|
|
2889
|
+
text: ""
|
|
2890
|
+
}));
|
|
2891
|
+
throw error;
|
|
2892
|
+
}
|
|
2893
|
+
}
|
|
2894
|
+
async function queueFollowUp(command, args, help) {
|
|
2895
|
+
const { values, positionals } = parseArgs({
|
|
2896
|
+
args,
|
|
2897
|
+
allowPositionals: true,
|
|
2898
|
+
options: {
|
|
2899
|
+
...scopeOptions,
|
|
2900
|
+
"request-id": { type: "string", multiple: true },
|
|
2901
|
+
prompt: { type: "string" },
|
|
2902
|
+
"prompt-file": { type: "string" },
|
|
2903
|
+
help: { type: "boolean", short: "h" }
|
|
2904
|
+
}
|
|
2905
|
+
});
|
|
2906
|
+
if (values.help) {
|
|
2907
|
+
console.log(help);
|
|
2908
|
+
return 0;
|
|
2909
|
+
}
|
|
2910
|
+
const [id] = positionals;
|
|
2911
|
+
const requestIds = values["request-id"] ?? [];
|
|
2912
|
+
const requestId = requestIds.at(-1);
|
|
2913
|
+
if (command === "compact" && (values.prompt !== undefined || values["prompt-file"] !== undefined))
|
|
2914
|
+
throw new Error("sessions compact takes no prompt.");
|
|
2915
|
+
if (command === "compact" && requestIds.length > 1 || (requestId === undefined ? positionals.length !== 1 || !id.trim() : positionals.length !== 0))
|
|
2916
|
+
throw new Error(`Usage: taube sessions ${command} (ID | --request-id NAME)${command === "send" ? " [--prompt TEXT | --prompt-file FILE]" : ""}`);
|
|
2917
|
+
const source = promptSource(values.prompt, values["prompt-file"]);
|
|
2918
|
+
const dispatcher = sessionScope(values);
|
|
2919
|
+
const session = await resolveSession(dispatcher, id, requestId);
|
|
2920
|
+
if (session.status !== "running")
|
|
2921
|
+
throw new Error(`Session ${requestId ?? id} is ${session.status}.`);
|
|
2922
|
+
const messageId = command === "compact" ? await compactSession(session.id) : await sendSessionMessage(session.id, await readPrompt(source));
|
|
2923
|
+
console.log(JSON.stringify({ sessionId: session.id, status: "queued", messageId }));
|
|
2924
|
+
return 0;
|
|
2925
|
+
}
|
|
2926
|
+
async function streamJson(events) {
|
|
2927
|
+
const controller = new AbortController;
|
|
2928
|
+
const close = () => controller.abort();
|
|
2929
|
+
const fail = (error) => controller.abort(error);
|
|
2930
|
+
process.stdout.once("close", close);
|
|
2931
|
+
process.stdout.on("error", fail);
|
|
2932
|
+
try {
|
|
2933
|
+
for await (const event of events(controller.signal)) {
|
|
2934
|
+
await new Promise((resolve, reject) => {
|
|
2935
|
+
process.stdout.write(`${JSON.stringify(event)}
|
|
2936
|
+
`, (error) => error ? reject(error) : resolve());
|
|
2937
|
+
});
|
|
2938
|
+
}
|
|
2939
|
+
} catch (error) {
|
|
2940
|
+
if (error?.code !== "EPIPE" && !controller.signal.aborted)
|
|
2941
|
+
throw error;
|
|
2942
|
+
} finally {
|
|
2943
|
+
process.stdout.off("close", close);
|
|
2944
|
+
process.stdout.off("error", fail);
|
|
2945
|
+
}
|
|
2946
|
+
const reason = controller.signal.reason;
|
|
2947
|
+
if (reason instanceof Error && reason.name !== "AbortError" && reason.code !== "EPIPE")
|
|
2948
|
+
throw reason;
|
|
2949
|
+
return 0;
|
|
2950
|
+
}
|
|
2951
|
+
async function showTurns(args, help) {
|
|
2952
|
+
const { values, positionals } = parseArgs({
|
|
2953
|
+
args,
|
|
2954
|
+
allowPositionals: true,
|
|
2955
|
+
options: {
|
|
2956
|
+
...scopeOptions,
|
|
2957
|
+
"request-id": { type: "string", multiple: true },
|
|
2958
|
+
watch: { type: "boolean" },
|
|
2959
|
+
help: { type: "boolean", short: "h" }
|
|
2960
|
+
}
|
|
2961
|
+
});
|
|
2962
|
+
if (values.help) {
|
|
2963
|
+
console.log(help);
|
|
2964
|
+
return 0;
|
|
2965
|
+
}
|
|
2966
|
+
const [id] = positionals;
|
|
2967
|
+
const requestIds = values["request-id"] ?? [];
|
|
2968
|
+
if (positionals.length + requestIds.length !== 1 || id !== undefined && !id.trim())
|
|
2969
|
+
throw new Error("Usage: taube sessions turns (ID | --request-id NAME) [--watch] [--dispatcher ID | --mine | --all]");
|
|
2970
|
+
const dispatcher = sessionScope(values);
|
|
2971
|
+
const session = await resolveSession(dispatcher, id, requestIds[0]);
|
|
2972
|
+
await Promise.resolve().then(() => init_turn_history());
|
|
2973
|
+
return streamJson((signal) => turnHistory(session, { watch: !!values.watch, signal }));
|
|
2974
|
+
}
|
|
2975
|
+
async function waitSessions(args, help) {
|
|
2976
|
+
const { values, positionals } = parseArgs({
|
|
2977
|
+
args,
|
|
2978
|
+
allowPositionals: true,
|
|
2979
|
+
options: {
|
|
2980
|
+
...scopeOptions,
|
|
2981
|
+
"request-id": { type: "string", multiple: true },
|
|
2982
|
+
"timeout-ms": { type: "string" },
|
|
2983
|
+
any: { type: "boolean" },
|
|
2984
|
+
"include-result": { type: "boolean" },
|
|
2985
|
+
"include-response": { type: "boolean" },
|
|
2986
|
+
"include-final-response": { type: "boolean" },
|
|
2987
|
+
help: { type: "boolean", short: "h" }
|
|
2988
|
+
}
|
|
2989
|
+
});
|
|
2990
|
+
if (values.help) {
|
|
2991
|
+
console.log(help);
|
|
2992
|
+
return 0;
|
|
2993
|
+
}
|
|
2994
|
+
await Promise.resolve().then(() => init_sessions_wait());
|
|
2995
|
+
const result = await waitForSessions({
|
|
2996
|
+
ids: positionals,
|
|
2997
|
+
requestIds: values["request-id"] ?? [],
|
|
2998
|
+
dispatcher: sessionScope(values),
|
|
2999
|
+
timeout: values["timeout-ms"],
|
|
3000
|
+
any: values.any,
|
|
3001
|
+
includeResult: values["include-result"],
|
|
3002
|
+
includeResponse: values["include-response"],
|
|
3003
|
+
includeFinalResponse: values["include-final-response"]
|
|
3004
|
+
});
|
|
3005
|
+
console.log(JSON.stringify(result));
|
|
3006
|
+
return 0;
|
|
3007
|
+
}
|
|
3008
|
+
async function prune(args, help) {
|
|
3009
|
+
const { values, tokens } = parseArgs({
|
|
3010
|
+
args,
|
|
3011
|
+
tokens: true,
|
|
3012
|
+
options: {
|
|
3013
|
+
...scopeOptions,
|
|
3014
|
+
"older-than": { type: "string" },
|
|
3015
|
+
apply: { type: "boolean" },
|
|
3016
|
+
help: { type: "boolean", short: "h" }
|
|
3017
|
+
}
|
|
3018
|
+
});
|
|
3019
|
+
if (values.help) {
|
|
3020
|
+
console.log(help);
|
|
3021
|
+
return 0;
|
|
3022
|
+
}
|
|
3023
|
+
for (const name of ["older-than", "dispatcher"]) {
|
|
3024
|
+
if (tokens.filter((t) => t.kind === "option" && t.name === name).length > 1)
|
|
3025
|
+
throw new Error(`Use --${name} only once.`);
|
|
3026
|
+
}
|
|
3027
|
+
await Promise.resolve().then(() => init_sessions_prune());
|
|
3028
|
+
const result = await pruneSessions({
|
|
3029
|
+
dispatcher: sessionScope(values),
|
|
3030
|
+
olderThan: values["older-than"],
|
|
3031
|
+
apply: !!values.apply
|
|
3032
|
+
});
|
|
3033
|
+
console.log(JSON.stringify(result));
|
|
3034
|
+
return result.failedIds.length ? 1 : 0;
|
|
3035
|
+
}
|
|
3036
|
+
async function showSessions(args, help) {
|
|
3037
|
+
if (args[0] === "resume")
|
|
3038
|
+
return resumeSession(args.slice(1), help);
|
|
3039
|
+
if (args[0] === "prune")
|
|
3040
|
+
return prune(args.slice(1), help);
|
|
3041
|
+
if (args[0] === "turns")
|
|
3042
|
+
return showTurns(args.slice(1), help);
|
|
3043
|
+
if (args[0] === "send" || args[0] === "compact")
|
|
3044
|
+
return queueFollowUp(args[0], args.slice(1), help);
|
|
3045
|
+
if (args[0] === "wait")
|
|
3046
|
+
return waitSessions(args.slice(1), help);
|
|
3047
|
+
const watching = args[0] === "watch";
|
|
812
3048
|
const { values } = parseArgs({
|
|
813
|
-
args: args[0] === "list" ? args.slice(1) : args,
|
|
3049
|
+
args: watching || args[0] === "list" ? args.slice(1) : args,
|
|
814
3050
|
options: {
|
|
815
|
-
|
|
816
|
-
mine: { type: "boolean" },
|
|
817
|
-
all: { type: "boolean" },
|
|
3051
|
+
...scopeOptions,
|
|
818
3052
|
status: { type: "string" },
|
|
3053
|
+
id: { type: "string" },
|
|
3054
|
+
"request-id": { type: "string" },
|
|
3055
|
+
once: { type: "boolean" },
|
|
819
3056
|
help: { type: "boolean", short: "h" }
|
|
820
3057
|
}
|
|
821
3058
|
});
|
|
@@ -823,11 +3060,7 @@ async function showSessions(args) {
|
|
|
823
3060
|
console.log(help);
|
|
824
3061
|
return 0;
|
|
825
3062
|
}
|
|
826
|
-
|
|
827
|
-
throw new Error("Choose one of --mine, --dispatcher ID or --all.");
|
|
828
|
-
const dispatcher = values.all ? null : currentDispatcher(values.dispatcher);
|
|
829
|
-
if (!values.all && dispatcher === null)
|
|
830
|
-
throw new Error("Could not identify the current dispatcher. Use --dispatcher ID to select a dispatcher or --all to list every session.");
|
|
3063
|
+
const dispatcher = sessionScope(values);
|
|
831
3064
|
const statuses = [
|
|
832
3065
|
"running",
|
|
833
3066
|
"finished",
|
|
@@ -838,11 +3071,129 @@ async function showSessions(args) {
|
|
|
838
3071
|
const status = values.status;
|
|
839
3072
|
if (status !== undefined && !statuses.includes(status))
|
|
840
3073
|
throw new Error(`Choose a --status: ${statuses.join(", ")}.`);
|
|
841
|
-
const
|
|
3074
|
+
const requestId = values["request-id"];
|
|
3075
|
+
if (watching) {
|
|
3076
|
+
if (values.id !== undefined && requestId !== undefined)
|
|
3077
|
+
throw new Error("Choose one of --id ID or --request-id NAME.");
|
|
3078
|
+
if (values.id !== undefined && !values.id.trim())
|
|
3079
|
+
throw new Error("--id needs a Taube session ID.");
|
|
3080
|
+
const id = requestId === undefined ? values.id : (await resolveSession(dispatcher, undefined, requestId)).id;
|
|
3081
|
+
return streamJson((signal) => watchSessions({ dispatcher, status, id, once: values.once, signal }));
|
|
3082
|
+
}
|
|
3083
|
+
if (requestId !== undefined)
|
|
3084
|
+
throw new Error("Use --request-id with taube sessions send, compact, turns, watch or wait.");
|
|
3085
|
+
if (values.id !== undefined || values.once)
|
|
3086
|
+
throw new Error("Use --id and --once with taube sessions watch.");
|
|
3087
|
+
const sessions = (await listSessions()).filter((session) => (dispatcher === null || session.dispatcher === dispatcher) && matchesStatus(session, status));
|
|
842
3088
|
console.log(JSON.stringify({ sessions }, null, 2));
|
|
843
3089
|
return 0;
|
|
844
3090
|
}
|
|
3091
|
+
|
|
3092
|
+
// src/cli.ts
|
|
3093
|
+
var targetIds = targets.map(({ id }) => id);
|
|
3094
|
+
var help = `Usage:
|
|
3095
|
+
taube --version
|
|
3096
|
+
taube surfaces [--models [--cwd DIR]]
|
|
3097
|
+
taube surfaces <${targetIds.join("|")}> --models [--cwd DIR]
|
|
3098
|
+
taube auth check <${targetIds.join("|")}>
|
|
3099
|
+
taube sessions [list] [--dispatcher ID | --mine | --all] [--status STATUS]
|
|
3100
|
+
taube sessions prune --older-than 30d [--dispatcher ID | --mine | --all] [--apply]
|
|
3101
|
+
taube sessions turns (ID | --request-id NAME) [--watch] [--dispatcher ID | --mine | --all]
|
|
3102
|
+
taube sessions wait [ID ...] [--request-id NAME ...] [--dispatcher ID | --mine | --all] [--any] [--timeout-ms MS] [--include-response] [--include-final-response] [--include-result]
|
|
3103
|
+
taube sessions watch [--id ID | --request-id NAME] [--once] [--dispatcher ID | --mine | --all] [--status STATUS]
|
|
3104
|
+
taube sessions send (ID | --request-id NAME) [--prompt TEXT | --prompt-file FILE] [--dispatcher ID | --mine | --all]
|
|
3105
|
+
taube sessions resume (ID | --request-id NAME) [--prompt TEXT | --prompt-file FILE] [--output text|json] [--dispatcher ID | --mine]
|
|
3106
|
+
taube sessions compact (ID | --request-id NAME) [--dispatcher ID | --mine | --all]
|
|
3107
|
+
taube dispatch <${targetIds.join("|")}> [--detach] [--prompt TEXT | --prompt-file FILE] [--output text|json] [--model ID] [--effort LEVEL] [--accept-edits] [--cwd DIR] [--dispatcher ID] [--request-id NAME]
|
|
3108
|
+
|
|
3109
|
+
surfaces lists the target launchers and their last known authentication status.
|
|
3110
|
+
auth check queries one target CLI and records its login status.
|
|
3111
|
+
sessions prints JSON listing dispatches started by the current dispatcher.
|
|
3112
|
+
sessions prune previews terminal sessions by recorded finish time. With --apply, it deletes their local records and transcripts.
|
|
3113
|
+
sessions turns prints one session's prompts and responses. With --watch, it streams snapshots until the session finishes.
|
|
3114
|
+
sessions wait prints a single JSON result after all selected sessions finish by default.
|
|
3115
|
+
sessions compact queues the adapter's advertised /compact command. Match the receipt's messageId to its turn in sessions turns output to check completion.
|
|
3116
|
+
dispatch sends one instruction to a fresh ACP session.
|
|
3117
|
+
Assistant text streams to stdout. Diagnostics go to stderr. Partial turns and
|
|
3118
|
+
permission requests exit nonzero.
|
|
3119
|
+
|
|
3120
|
+
--cwd DIR Run the adapter in DIR (default: current directory).
|
|
3121
|
+
--prompt TEXT Use TEXT as the instruction. With no input flag, read stdin to EOF.
|
|
3122
|
+
--prompt-file FILE Read the instruction from a UTF-8 text file.
|
|
3123
|
+
--output FORMAT Stream text (default) or emit one JSON result when dispatch ends.
|
|
3124
|
+
--detach Print a JSON registration receipt and run the dispatch in the background.
|
|
3125
|
+
--models Query the selected adapters for model and mode IDs in DIR.
|
|
3126
|
+
--model ID Select a model advertised by the adapter.
|
|
3127
|
+
--effort LEVEL Select an advertised reasoning effort for Codex, Claude or Grok.
|
|
3128
|
+
--accept-edits Request Claude's advertised acceptEdits mode before sending the prompt.
|
|
3129
|
+
--dispatcher ID Identify the caller of a dispatch, or filter sessions by caller.
|
|
3130
|
+
--mine Select sessions started by the current dispatcher (default).
|
|
3131
|
+
--all Include sessions from all dispatchers.
|
|
3132
|
+
--id ID Watch one Taube session within the selected dispatcher scope.
|
|
3133
|
+
--request-id NAME Identify a dispatch by a caller-chosen name unique to its dispatcher. Repeat with sessions wait.
|
|
3134
|
+
--once Wait for one matching status event, print it, then exit.
|
|
3135
|
+
--any Return as soon as any selected session finishes. Include all finished selections, pendingSessionIds for running sessions and pendingRequestIds for requests awaiting registration.
|
|
3136
|
+
--timeout-ms MS Limit the wait for session registration and completion.
|
|
3137
|
+
--include-result Return the latest completed turn as result {source, text}, or null.
|
|
3138
|
+
--include-response Add the latest recorded reply to each returned session (null if no turn was recorded).
|
|
3139
|
+
--include-final-response Add the final assistant message as finalResponse, or null when unavailable.
|
|
3140
|
+
--status STATUS Filter by running, finished, completed, failed or interrupted.
|
|
3141
|
+
--older-than Nd Select sessions finished more than N whole 24-hour days ago (N > 0).
|
|
3142
|
+
--apply Delete the sessions selected by prune. Omit to preview.
|
|
3143
|
+
-V, --version Print the installed Taube version.
|
|
3144
|
+
-h, --help Show this help.
|
|
3145
|
+
|
|
3146
|
+
Omit --model and --effort to use the target defaults.`;
|
|
3147
|
+
async function showSurfaces(args) {
|
|
3148
|
+
const { values, positionals } = parseArgs2({
|
|
3149
|
+
args,
|
|
3150
|
+
allowPositionals: true,
|
|
3151
|
+
options: {
|
|
3152
|
+
models: { type: "boolean" },
|
|
3153
|
+
cwd: { type: "string" },
|
|
3154
|
+
help: { type: "boolean", short: "h" }
|
|
3155
|
+
}
|
|
3156
|
+
});
|
|
3157
|
+
if (values.help) {
|
|
3158
|
+
console.log(help);
|
|
3159
|
+
return 0;
|
|
3160
|
+
}
|
|
3161
|
+
const target = targets.find(({ id }) => id === positionals[0]);
|
|
3162
|
+
if (positionals.length && (positionals.length !== 1 || !target || !values.models))
|
|
3163
|
+
throw new Error(`Usage: taube surfaces <${targetIds.join("|")}> --models [--cwd DIR]`);
|
|
3164
|
+
if (values.cwd !== undefined && (!values.models || !values.cwd.trim()))
|
|
3165
|
+
throw new Error("Usage: taube surfaces --models --cwd DIR");
|
|
3166
|
+
if (!values.models) {
|
|
3167
|
+
console.log(JSON.stringify(await surfaces(), null, 2));
|
|
3168
|
+
return 0;
|
|
3169
|
+
}
|
|
3170
|
+
const controller = new AbortController;
|
|
3171
|
+
const signals = ["SIGINT", "SIGTERM", "SIGHUP"];
|
|
3172
|
+
const interrupt = (signal) => controller.abort(signal);
|
|
3173
|
+
for (const signal of signals)
|
|
3174
|
+
process.on(signal, interrupt);
|
|
3175
|
+
try {
|
|
3176
|
+
const result = await surfaces({
|
|
3177
|
+
target,
|
|
3178
|
+
cwd: values.cwd,
|
|
3179
|
+
signal: controller.signal
|
|
3180
|
+
});
|
|
3181
|
+
if (controller.signal.aborted) {
|
|
3182
|
+
const signal = controller.signal.reason;
|
|
3183
|
+
return 128 + constants4.signals[signal];
|
|
3184
|
+
}
|
|
3185
|
+
console.log(JSON.stringify(result, null, 2));
|
|
3186
|
+
return 0;
|
|
3187
|
+
} finally {
|
|
3188
|
+
for (const signal of signals)
|
|
3189
|
+
process.off(signal, interrupt);
|
|
3190
|
+
}
|
|
3191
|
+
}
|
|
845
3192
|
async function main([command, targetId, ...args]) {
|
|
3193
|
+
if (command === "_dispatch-worker" && process.send) {
|
|
3194
|
+
await Promise.resolve().then(() => init_detach());
|
|
3195
|
+
return runDetachedWorker();
|
|
3196
|
+
}
|
|
846
3197
|
if (command === "--version" || command === "-V") {
|
|
847
3198
|
if (targetId !== undefined)
|
|
848
3199
|
throw new Error("Usage: taube --version");
|
|
@@ -853,10 +3204,8 @@ async function main([command, targetId, ...args]) {
|
|
|
853
3204
|
console.log(help);
|
|
854
3205
|
return 0;
|
|
855
3206
|
}
|
|
856
|
-
if (command === "surfaces"
|
|
857
|
-
|
|
858
|
-
return 0;
|
|
859
|
-
}
|
|
3207
|
+
if (command === "surfaces")
|
|
3208
|
+
return showSurfaces(targetId === undefined ? [] : [targetId, ...args]);
|
|
860
3209
|
if (command === "auth") {
|
|
861
3210
|
const target = targets.find(({ id }) => id === args[0]);
|
|
862
3211
|
if (targetId !== "check" || args.length !== 1 || !target)
|
|
@@ -867,19 +3216,25 @@ async function main([command, targetId, ...args]) {
|
|
|
867
3216
|
return result.authenticated ? 0 : 1;
|
|
868
3217
|
}
|
|
869
3218
|
if (command === "sessions")
|
|
870
|
-
return showSessions(targetId === undefined ? [] : [targetId, ...args]);
|
|
3219
|
+
return showSessions(targetId === undefined ? [] : [targetId, ...args], help);
|
|
871
3220
|
if (command !== "dispatch")
|
|
872
3221
|
throw new Error("Expected surfaces, auth, sessions or dispatch. See taube --help.");
|
|
873
3222
|
const target = targets.find(({ id }) => id === targetId);
|
|
874
3223
|
if (!target)
|
|
875
3224
|
throw new Error(`Choose one target: ${targetIds.join(", ")}.`);
|
|
876
|
-
const { values } =
|
|
3225
|
+
const { values } = parseArgs2({
|
|
877
3226
|
args,
|
|
878
3227
|
options: {
|
|
879
3228
|
cwd: { type: "string" },
|
|
880
3229
|
dispatcher: { type: "string" },
|
|
3230
|
+
detach: { type: "boolean" },
|
|
3231
|
+
"request-id": { type: "string" },
|
|
3232
|
+
prompt: { type: "string" },
|
|
3233
|
+
"prompt-file": { type: "string" },
|
|
3234
|
+
output: { type: "string" },
|
|
881
3235
|
model: { type: "string" },
|
|
882
3236
|
effort: { type: "string" },
|
|
3237
|
+
"accept-edits": { type: "boolean" },
|
|
883
3238
|
help: { type: "boolean", short: "h" }
|
|
884
3239
|
}
|
|
885
3240
|
});
|
|
@@ -887,15 +3242,44 @@ async function main([command, targetId, ...args]) {
|
|
|
887
3242
|
console.log(help);
|
|
888
3243
|
return 0;
|
|
889
3244
|
}
|
|
890
|
-
|
|
3245
|
+
const {
|
|
3246
|
+
prompt,
|
|
3247
|
+
"prompt-file": file,
|
|
3248
|
+
output = "text",
|
|
3249
|
+
detach,
|
|
3250
|
+
...settings
|
|
3251
|
+
} = values;
|
|
3252
|
+
const source = promptSource(prompt, file);
|
|
3253
|
+
if (output !== "text" && output !== "json")
|
|
3254
|
+
throw new Error("--output must be text or json.");
|
|
3255
|
+
for (const [name, value] of Object.entries(settings)) {
|
|
891
3256
|
if (typeof value === "string" && !value.trim())
|
|
892
3257
|
throw new Error(`--${name} needs a non-empty value`);
|
|
893
3258
|
}
|
|
3259
|
+
const {
|
|
3260
|
+
"request-id": requestId,
|
|
3261
|
+
"accept-edits": acceptEdits,
|
|
3262
|
+
...options
|
|
3263
|
+
} = settings;
|
|
3264
|
+
if (acceptEdits && target.id !== "claude")
|
|
3265
|
+
throw new Error("--accept-edits requires the claude target.");
|
|
3266
|
+
const dispatcherCwd = process.cwd();
|
|
3267
|
+
const dispatch = {
|
|
3268
|
+
...options,
|
|
3269
|
+
acceptEdits,
|
|
3270
|
+
requestId,
|
|
3271
|
+
...source,
|
|
3272
|
+
output,
|
|
3273
|
+
dispatcher: currentDispatcher(settings.dispatcher),
|
|
3274
|
+
dispatcherCwd,
|
|
3275
|
+
dispatcherProject: await findDispatcherProject(dispatcherCwd)
|
|
3276
|
+
};
|
|
3277
|
+
if (detach) {
|
|
3278
|
+
await Promise.resolve().then(() => init_detach());
|
|
3279
|
+
return dispatchDetached(import.meta.url, target, dispatch);
|
|
3280
|
+
}
|
|
894
3281
|
await Promise.resolve().then(() => init_direct_acp());
|
|
895
|
-
return runDirectAcp(target,
|
|
896
|
-
...values,
|
|
897
|
-
dispatcher: currentDispatcher(values.dispatcher)
|
|
898
|
-
});
|
|
3282
|
+
return runDirectAcp(target, dispatch);
|
|
899
3283
|
}
|
|
900
3284
|
try {
|
|
901
3285
|
process.exitCode = await main(process.argv.slice(2));
|