@losoft/taube 0.1.7 → 0.1.9

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