angelia-gateway 0.4.0 → 0.4.1
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/adapters/telegram/adapter.js +12 -0
- package/dist/adapters/whatsapp/adapter.js +114 -14
- package/dist/brain/agy.js +9 -6
- package/dist/brain/tmux.js +2 -0
- package/dist/brain/tui.js +104 -22
- package/dist/build.json +3 -3
- package/dist/capabilities/cli.js +3 -1
- package/dist/capabilities/compile.js +348 -35
- package/dist/cli/cli-args.js +2 -2
- package/dist/cli/cli.js +13 -2
- package/dist/cli/connect-cli.js +137 -0
- package/dist/core/deliver/text.js +10 -0
- package/dist/core/orchestrator.js +207 -26
- package/dist/daemon/daemon.js +12 -15
- package/dist/daemon/launch-guard.js +49 -0
- package/dist/instance/config/schema.js +4 -0
- package/dist/instance/connect.js +303 -0
- package/dist/instance/guide.js +34 -1
- package/dist/instance/init.js +247 -3
- package/dist/instance/onboard.js +30 -8
- package/dist/instance/profiles.js +5 -2
- package/dist/instance/switch-backend.js +9 -3
- package/install.sh +3 -1
- package/package.json +2 -2
- package/routing.example.yaml +1 -0
|
@@ -75,6 +75,8 @@ export class TelegramAdapter {
|
|
|
75
75
|
// callback_query is among the update types polling asks for by default (grammY passes an empty
|
|
76
76
|
// allowed_updates: every type but chat_member and the two reaction ones).
|
|
77
77
|
this.bot.on('callback_query', (ctx) => this.onPress(ctx));
|
|
78
|
+
// my_chat_member is also among the default types: the bot's own membership changed.
|
|
79
|
+
this.bot.on('my_chat_member', (ctx) => this.onMembership(ctx));
|
|
78
80
|
// grammY rethrows anything a handler throws, and an unhandled rejection out of the polling
|
|
79
81
|
// loop takes the whole daemon down - every other chat on every other platform with it.
|
|
80
82
|
this.bot.catch((err) => this.log(`telegram: handler error ${err.message}`));
|
|
@@ -211,6 +213,16 @@ export class TelegramAdapter {
|
|
|
211
213
|
* hold every Telegram chat, `/stop` and `yes <id>` included. The download and the hand-over run on
|
|
212
214
|
* the chat's own chain instead, so a text still arrives after the photo it follows.
|
|
213
215
|
*/
|
|
216
|
+
/** The bot went from out of a group to in it: who did it, for an armed profile (connect.ts). */
|
|
217
|
+
onMembership(ctx) {
|
|
218
|
+
const u = ctx.myChatMember;
|
|
219
|
+
if (!u || !this.opts.onJoined || (u.chat.type !== 'group' && u.chat.type !== 'supergroup'))
|
|
220
|
+
return;
|
|
221
|
+
const was = u.old_chat_member.status, now = u.new_chat_member.status;
|
|
222
|
+
if (!(was === 'left' || was === 'kicked') || !(now === 'member' || now === 'administrator'))
|
|
223
|
+
return;
|
|
224
|
+
void this.opts.onJoined(String(u.chat.id), [String(u.from.id)], u.date * 1000).catch((e) => this.log(`telegram: join handler error ${e.message}`));
|
|
225
|
+
}
|
|
214
226
|
onMessage(ctx) {
|
|
215
227
|
const m = ctx.message;
|
|
216
228
|
const chat = String(m.chat.id);
|
|
@@ -3,10 +3,12 @@ import { EventEmitter } from 'node:events';
|
|
|
3
3
|
import { setTimeout as sleep } from 'node:timers/promises';
|
|
4
4
|
import pino from 'pino';
|
|
5
5
|
import { ChatChains, MAX_INBOUND, SenderQuota, saveInbound } from '../inbox.js';
|
|
6
|
-
import { makeWASocket, useMultiFileAuthState, fetchLatestBaileysVersion, downloadMediaMessage, DisconnectReason } from 'baileys';
|
|
6
|
+
import { makeWASocket, useMultiFileAuthState, fetchLatestBaileysVersion, downloadMediaMessage, DisconnectReason, WAMessageStubType } from 'baileys';
|
|
7
7
|
import qrcode from 'qrcode-terminal';
|
|
8
|
-
import { LidMap, normalizeJid } from './ids.js';
|
|
9
|
-
import { MAX_MENTIONS, parseMessage, SeenIds, toInbound, withMentions } from './parse.js';
|
|
8
|
+
import { bareId, isGroupJid, LidMap, normalizeJid } from './ids.js';
|
|
9
|
+
import { byteLength, MAX_MENTIONS, parseMessage, SeenIds, toInbound, withMentions } from './parse.js';
|
|
10
|
+
/** The stub types of a participant joining a group: Baileys emits its participants 'add' for these three. */
|
|
11
|
+
const ADD_STUBS = new Set([WAMessageStubType.GROUP_PARTICIPANT_ADD, WAMessageStubType.GROUP_PARTICIPANT_INVITE, WAMessageStubType.GROUP_PARTICIPANT_ADD_REQUEST_JOIN]);
|
|
10
12
|
import { GroupCache } from './groups.js';
|
|
11
13
|
import { SentMessages } from './sent.js';
|
|
12
14
|
import { isOpus } from '../../core/deliver/media.js';
|
|
@@ -14,6 +16,35 @@ import { asVoice } from '../../voice/opus.js';
|
|
|
14
16
|
const MAX_MEDIA = MAX_INBOUND;
|
|
15
17
|
/** How a note to the agent names a kind of file: "a photo", "a voice note", never "a image". */
|
|
16
18
|
const KIND_NAME = { image: 'photo', audio: 'voice note', video: 'video', document: 'document', sticker: 'sticker' };
|
|
19
|
+
/** A file download gives up after this long: a stalled one would hold its chat for good, /stop included. */
|
|
20
|
+
const DOWNLOAD_MS = 60_000;
|
|
21
|
+
/** A download that fails on the network is tried again after these waits, inside DOWNLOAD_MS: three tries
|
|
22
|
+
* in all. A flapping connection often has a good window seconds later. */
|
|
23
|
+
const RETRY_MS = [3_000, 10_000];
|
|
24
|
+
/** Node's and undici's codes for a connection that broke, or never came up. */
|
|
25
|
+
const NET_CODES = /^(ECONNRESET|ECONNREFUSED|ECONNABORTED|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|ENETUNREACH|ENETDOWN|EHOSTUNREACH|EPIPE|UND_ERR_[A-Z_]+)$/;
|
|
26
|
+
/** A network error worth another try: fetch's "fetch failed" (the real reason is in `cause`), a
|
|
27
|
+
* connection code, a hang-up. Not an HTTP status, an abort, or a file that is too big: those stay. */
|
|
28
|
+
export function transientNetError(e) {
|
|
29
|
+
const err = e;
|
|
30
|
+
if ([err?.code, err?.cause?.code].some((c) => typeof c === 'string' && NET_CODES.test(c)))
|
|
31
|
+
return true;
|
|
32
|
+
return /fetch failed|socket hang up|other side closed/i.test(`${String(err?.message ?? '')} ${String(err?.cause?.message ?? '')}`);
|
|
33
|
+
}
|
|
34
|
+
/** The error as one log line, with its cause: "fetch failed" alone hides what went wrong. */
|
|
35
|
+
export function errorLine(e) {
|
|
36
|
+
const err = e;
|
|
37
|
+
const cause = err?.cause ? [err.cause.code, err.cause.message].filter((x) => typeof x === 'string' && x).join(' ') : '';
|
|
38
|
+
return `${String(err?.message ?? e)}${cause ? ` (cause: ${cause})` : ''}`.slice(0, 240);
|
|
39
|
+
}
|
|
40
|
+
/** A wait that an abort cuts short. */
|
|
41
|
+
function pause(ms, signal) {
|
|
42
|
+
return before(new Promise((resolve) => { const t = setTimeout(resolve, ms); signal.addEventListener('abort', () => clearTimeout(t), { once: true }); }), signal);
|
|
43
|
+
}
|
|
44
|
+
/** `p`, or the signal's reason once it aborts, whichever comes first. */
|
|
45
|
+
function before(p, signal) {
|
|
46
|
+
return Promise.race([p, new Promise((_, reject) => signal.addEventListener('abort', () => reject(signal.reason), { once: true }))]);
|
|
47
|
+
}
|
|
17
48
|
/** Paired and not connected for this long, the adapter says 'dead' (see check()). Baileys' own keepalive turns a
|
|
18
49
|
* dead socket into a close within about a minute, and a reconnect takes seconds, so five minutes is never a
|
|
19
50
|
* working session. */
|
|
@@ -147,12 +178,14 @@ export class WhatsAppAdapter extends EventEmitter {
|
|
|
147
178
|
// close from it would start a second socket beside this one, and a late save would write its credentials.
|
|
148
179
|
const old = this.sock;
|
|
149
180
|
this.sock = sock;
|
|
181
|
+
this.catchingUp = false;
|
|
150
182
|
this.retire(old);
|
|
151
183
|
// A change made while no socket listened was never heard: a new socket starts with no cached group.
|
|
152
184
|
this.groups.clear();
|
|
153
185
|
sock.ev.on('groups.update', (us) => { for (const u of us)
|
|
154
186
|
this.groups.drop(u.id); });
|
|
155
|
-
|
|
187
|
+
// The cached members only: an add of the bot is read from its stub message below, which has a time.
|
|
188
|
+
sock.ev.on('group-participants.update', (u) => { this.groups.drop(u.id); });
|
|
156
189
|
sock.ev.on('creds.update', () => { if (sock !== this.sock)
|
|
157
190
|
return; void saveCreds(); this.lids.reload(); });
|
|
158
191
|
sock.ev.on('connection.update', (u) => { if (sock === this.sock)
|
|
@@ -160,8 +193,11 @@ export class WhatsAppAdapter extends EventEmitter {
|
|
|
160
193
|
sock.ev.on('messages.upsert', ({ messages, type }) => {
|
|
161
194
|
if (type !== 'notify' && type !== 'append')
|
|
162
195
|
return;
|
|
163
|
-
for (const m of messages)
|
|
196
|
+
for (const m of messages) {
|
|
197
|
+
if (ADD_STUBS.has(Number(m.messageStubType)))
|
|
198
|
+
this.onAddStub(m);
|
|
164
199
|
void this.onMessage(m).catch((e) => this.log(`whatsapp: message error ${e.message}`));
|
|
200
|
+
}
|
|
165
201
|
});
|
|
166
202
|
if (!this.registered && this.opts.pairing === 'qr')
|
|
167
203
|
this.say('Scan the QR below with WhatsApp > Linked devices > Link a device.');
|
|
@@ -197,6 +233,11 @@ export class WhatsAppAdapter extends EventEmitter {
|
|
|
197
233
|
}
|
|
198
234
|
}
|
|
199
235
|
async onConnection(u, sock) {
|
|
236
|
+
// Baileys says false as a socket starts and true once the notifications it missed are handled.
|
|
237
|
+
if (u.receivedPendingNotifications === false)
|
|
238
|
+
this.catchingUp = true;
|
|
239
|
+
else if (u.receivedPendingNotifications === true)
|
|
240
|
+
this.catchingUp = false;
|
|
200
241
|
if (u.qr && !this.registered) {
|
|
201
242
|
if (this.opts.pairing === 'qr') {
|
|
202
243
|
this.emit('qr', String(u.qr));
|
|
@@ -285,10 +326,47 @@ export class WhatsAppAdapter extends EventEmitter {
|
|
|
285
326
|
}
|
|
286
327
|
catch { /* already closed */ }
|
|
287
328
|
}
|
|
329
|
+
/** The socket is still handed the notifications it missed while closed (review fix L4). */
|
|
330
|
+
catchingUp = false;
|
|
288
331
|
ourIds() {
|
|
289
332
|
const u = this.sock?.user;
|
|
290
333
|
return [normalizeJid(u?.id), normalizeJid(u?.lid)].filter(Boolean);
|
|
291
334
|
}
|
|
335
|
+
/**
|
|
336
|
+
* Someone added to a group, as its stub message has it: the bot itself, and who added it, as a phone
|
|
337
|
+
* number when the lid map knows it, and as given. Read from the stub, not from Baileys'
|
|
338
|
+
* group-participants event (made from the same stub, emitted before it and with no time): the stub
|
|
339
|
+
* carries the time of the add (messageTimestamp, from the notification's `t`), so an add from before
|
|
340
|
+
* the arm, replayed after a reconnect, does not use it (review fix L5). Participants come as JSON
|
|
341
|
+
* text (Baileys 7: {id, phoneNumber}) or as bare jids (older).
|
|
342
|
+
*/
|
|
343
|
+
onAddStub(m) {
|
|
344
|
+
const chat = m.key?.remoteJid;
|
|
345
|
+
if (!this.opts.onJoined || !chat || !isGroupJid(chat) || m.key?.fromMe)
|
|
346
|
+
return;
|
|
347
|
+
const ours = this.ourIds();
|
|
348
|
+
const parse = (x) => { if (typeof x !== 'string')
|
|
349
|
+
return x; try {
|
|
350
|
+
return JSON.parse(x);
|
|
351
|
+
}
|
|
352
|
+
catch {
|
|
353
|
+
return x;
|
|
354
|
+
} };
|
|
355
|
+
const ids = (p) => (typeof p === 'string' ? [p] : [p?.id, p?.lid, p?.phoneNumber]).filter((x) => typeof x === 'string' && !!x).map(normalizeJid);
|
|
356
|
+
const added = (Array.isArray(m.messageStubParameters) ? m.messageStubParameters : []).map(parse);
|
|
357
|
+
if (!added.some((p) => ids(p).some((id) => ours.includes(id))))
|
|
358
|
+
return;
|
|
359
|
+
// A second net: one handed over while the socket catches up happened while it was closed (review
|
|
360
|
+
// fix L4). An owner's first message still connects.
|
|
361
|
+
if (this.catchingUp) {
|
|
362
|
+
this.log('whatsapp: an add of the bot arrived while catching up after a connect; not used (it may be from before the arm)');
|
|
363
|
+
return;
|
|
364
|
+
}
|
|
365
|
+
const sec = byteLength(m.messageTimestamp);
|
|
366
|
+
const at = sec && sec > 0 ? sec * 1000 : this.now();
|
|
367
|
+
const by = [...new Set([m.key?.participantAlt, m.key?.participant].filter((x) => typeof x === 'string' && !!x).flatMap((a) => [this.lids.phoneFor(a), bareId(a)]))];
|
|
368
|
+
void this.opts.onJoined(normalizeJid(chat), by, at).catch((e) => this.log(`whatsapp: join handler error ${e.message}`));
|
|
369
|
+
}
|
|
292
370
|
seen = new SeenIds();
|
|
293
371
|
chains = new ChatChains();
|
|
294
372
|
quota = new SenderQuota();
|
|
@@ -324,22 +402,44 @@ export class WhatsAppAdapter extends EventEmitter {
|
|
|
324
402
|
await this.chains.run(p.chat, async () => {
|
|
325
403
|
const media = [];
|
|
326
404
|
if (fetchIt && inbox && p.media) {
|
|
405
|
+
// Baileys' fetch takes no signal, so the wait is cut here, and a stream already flowing is
|
|
406
|
+
// destroyed, which removes its partial file. The text still goes on.
|
|
407
|
+
const halt = new AbortController();
|
|
408
|
+
const timer = setTimeout(() => halt.abort(new Error(`no answer in ${DOWNLOAD_MS / 1000} s`)), DOWNLOAD_MS);
|
|
409
|
+
const waits = this.opts.retryMs ?? RETRY_MS;
|
|
327
410
|
try {
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
411
|
+
for (let tried = 0;; tried++) {
|
|
412
|
+
try {
|
|
413
|
+
const stream = (await before((this.opts.download ?? downloadMediaMessage)(m, 'stream', {}, { logger: pino({ level: 'silent' }), reuploadRequest: this.sock.updateMediaMessage }), halt.signal));
|
|
414
|
+
// Without an error: one not yet read from would raise it with no listener, an uncaught exception.
|
|
415
|
+
halt.signal.addEventListener('abort', () => stream.destroy?.(), { once: true });
|
|
416
|
+
const ext = p.media.fileName?.match(/\.[A-Za-z0-9]{1,5}$/)?.[0] ?? EXT[p.media.mime ?? ''] ?? '';
|
|
417
|
+
const dest = await before(saveInbound(inbox, ext, stream, MAX_MEDIA), halt.signal);
|
|
418
|
+
if (dest)
|
|
419
|
+
media.push(dest);
|
|
420
|
+
else {
|
|
421
|
+
this.log(`whatsapp: media passed ${MAX_MEDIA >> 20} MB while downloading, dropped chat=${p.chat.slice(0, 8)}…`);
|
|
422
|
+
note(`a ${KIND_NAME[p.media.kind] ?? p.media.kind} over ${MAX_MEDIA >> 20} MB was sent and not downloaded`);
|
|
423
|
+
}
|
|
424
|
+
break;
|
|
425
|
+
}
|
|
426
|
+
catch (e) {
|
|
427
|
+
// Only a network error is tried again, and only while the overall limit has time left.
|
|
428
|
+
if (halt.signal.aborted || tried >= waits.length || !transientNetError(e))
|
|
429
|
+
throw e;
|
|
430
|
+
this.log(`whatsapp: media download try ${tried + 1} failed chat=${p.chat.slice(0, 8)}…: ${errorLine(e)}; again in ${Math.round(waits[tried] / 1000)} s`);
|
|
431
|
+
await pause(waits[tried], halt.signal);
|
|
432
|
+
}
|
|
336
433
|
}
|
|
337
434
|
}
|
|
338
435
|
catch (e) {
|
|
339
436
|
// Said to the agent too (#35): a file with no caption would otherwise be no turn at all.
|
|
340
|
-
this.log(`whatsapp: media download failed chat=${p.chat.slice(0, 8)}…: ${
|
|
437
|
+
this.log(`whatsapp: media download failed chat=${p.chat.slice(0, 8)}…: ${errorLine(e)}`);
|
|
341
438
|
note(`the ${KIND_NAME[p.media.kind] ?? p.media.kind} sent could not be downloaded`);
|
|
342
439
|
}
|
|
440
|
+
finally {
|
|
441
|
+
clearTimeout(timer);
|
|
442
|
+
}
|
|
343
443
|
}
|
|
344
444
|
if (!head.text && !media.length)
|
|
345
445
|
return;
|
package/dist/brain/agy.js
CHANGED
|
@@ -432,12 +432,11 @@ export class AgyBrain extends AcpBrain {
|
|
|
432
432
|
* nothing it asks can be answered.
|
|
433
433
|
*/
|
|
434
434
|
watchForChild() {
|
|
435
|
-
//
|
|
436
|
-
// are read, only their heads, until attached: a second subagent may start before the
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
this.notChildren.add(id);
|
|
435
|
+
// notChildren holds the conversations that were here when the session opened (openSession): never
|
|
436
|
+
// read. Later ones are read, only their heads, until attached: a second subagent may start before the
|
|
437
|
+
// first is found. The list is not taken here: agy can write the subagent's conversation before this
|
|
438
|
+
// client has read its invoke_subagent line, and a list taken now held the subagent itself, so it was
|
|
439
|
+
// never attached (CI 2026-11-22 and 2026-11-24, a loaded machine).
|
|
441
440
|
const before = this.children.size;
|
|
442
441
|
const scans = AgyBrain.childScanMs;
|
|
443
442
|
for (const [i, ms] of scans.entries()) {
|
|
@@ -514,6 +513,10 @@ export class AgyBrain extends AcpBrain {
|
|
|
514
513
|
this.backendSessionId = String(s.sessionId);
|
|
515
514
|
}
|
|
516
515
|
const sessionId = this.backendSessionId;
|
|
516
|
+
// Every conversation here now is another session's or an earlier one: none is a subagent of this turn.
|
|
517
|
+
for (const id of this.conversations())
|
|
518
|
+
if (id !== sessionId)
|
|
519
|
+
this.notChildren.add(id);
|
|
517
520
|
// Checked before agy is asked: an unknown id is the owner's typo, and the list says what exists.
|
|
518
521
|
const modelId = agyResolveModel(this.model, this.availableModels);
|
|
519
522
|
if (!modelId) {
|
package/dist/brain/tmux.js
CHANGED
|
@@ -313,6 +313,8 @@ const RULE_RE = /^\s*─{10,}(\s+\S.{0,80}?\s+─+)?\s*$/;
|
|
|
313
313
|
export function inputBox(pane) {
|
|
314
314
|
return inputBoxStrict(pane) ?? pane.replace(/\n+$/, '').split('\n').slice(-3).join('\n');
|
|
315
315
|
}
|
|
316
|
+
/** The screen draws an input box: false for a dialog or a menu, which replaces it. */
|
|
317
|
+
export function paneHasBox(pane) { return inputBoxStrict(pane) !== null; }
|
|
316
318
|
/** The input box, or null when the screen has none: between the last two rules, or, in the older
|
|
317
319
|
* drawing, inside the last `╭…╰` frame. A dialog draws neither. */
|
|
318
320
|
function inputBoxStrict(pane) {
|
package/dist/brain/tui.js
CHANGED
|
@@ -9,7 +9,7 @@ import { cleanText } from '../core/types.js';
|
|
|
9
9
|
import { isLimitText } from '../core/deliver/text.js';
|
|
10
10
|
import { childEnv, CLAUDE_ENV, claudeTuiArgv, MIN_CLAUDE_VERSION, remoteControlName, STRIP_ENV, versionAtLeast } from './argv.js';
|
|
11
11
|
import { PermissionBook } from './brain.js';
|
|
12
|
-
import { addDirAccepted, addDirDialog, importsAccepted, importsDialogOpen, loadBuffer, paneAboveFoot, paneBusy, paneIdle, pasteLanded, permissionDialog, submitPasted, tmux, TMUX_SOCKET, trustAccepted, trustDialogOpen } from './tmux.js';
|
|
12
|
+
import { addDirAccepted, addDirDialog, importsAccepted, importsDialogOpen, loadBuffer, paneAboveFoot, paneBusy, paneHasBox, paneIdle, pasteLanded, permissionDialog, submitPasted, tmux, TMUX_SOCKET, trustAccepted, trustDialogOpen } from './tmux.js';
|
|
13
13
|
import { paneVerdict, PermissionRelay, REJECTED, RELAY_BEAT_MS, relayedPermission, ScreenDialogs } from './tui-permissions.js';
|
|
14
14
|
import { LOST_SESSION_LINE, placeTranscript, transcriptPath } from './transcripts.js';
|
|
15
15
|
import { readRecord } from '../capabilities/compile.js';
|
|
@@ -24,7 +24,16 @@ const POLL_MS = 700;
|
|
|
24
24
|
/** How long claude's add-dir dialog must stand before keys reach it (it drops them for ~1 s, 2.1.326). */
|
|
25
25
|
const ADD_DIR_SETTLE_MS = 1500;
|
|
26
26
|
const START_TIMEOUT_MS = 90_000;
|
|
27
|
+
/** How long a message waits for the pane's prompt. Past it the message goes back to the chat as not
|
|
28
|
+
* delivered, and a pane that works or waits for a person is kept (notTyped). */
|
|
27
29
|
const PROMPT_TIMEOUT_MS = 10 * 60_000;
|
|
30
|
+
/** How long a paste may take to show in the input box before it counts as not shown. */
|
|
31
|
+
const LAND_MS = 2400;
|
|
32
|
+
/** How many times one message is pasted when it never showed in the box (nothing was submitted). */
|
|
33
|
+
const PASTE_TRIES = 3;
|
|
34
|
+
/** The reason of a turn whose message was not typed into a live pane that is kept: the chat is told to
|
|
35
|
+
* send it again (core/deliver/text.ts, notDeliveredLine), and the pane is not ended. */
|
|
36
|
+
export const NOT_TYPED = 'not delivered';
|
|
28
37
|
/** A turn has no end time: a long build or a run of subagents may take hours, and `/stop` ends a
|
|
29
38
|
* stuck one. Each full hour the chat gets one line saying so, so a silent turn is not taken for a
|
|
30
39
|
* crash. */
|
|
@@ -563,33 +572,92 @@ export class TuiBrain extends EventEmitter {
|
|
|
563
572
|
async paste(raw, submit = () => { }, gen = this.gen) {
|
|
564
573
|
// The last gate before text becomes keys: whoever called, no control character reaches the pane.
|
|
565
574
|
const text = cleanText(raw);
|
|
566
|
-
const deadline = Date.now() + PROMPT_TIMEOUT_MS;
|
|
567
|
-
while
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
575
|
+
const deadline = Date.now() + (this.opts.promptTimeoutMs ?? PROMPT_TIMEOUT_MS);
|
|
576
|
+
// Whether the screen changed while the message waited: a CLI at work redraws its spinner clock,
|
|
577
|
+
// background agents their rows. A screen that never moved for the whole wait is a hung CLI.
|
|
578
|
+
let moved = false;
|
|
579
|
+
for (let attempt = 1;; attempt++) {
|
|
580
|
+
let pane = await this.capture(30);
|
|
581
|
+
while (!paneIdle(pane)) {
|
|
582
|
+
if (!(await this.sessionAlive()))
|
|
583
|
+
return { ok: false, why: 'exit', keep: false };
|
|
584
|
+
if (gen !== this.gen)
|
|
585
|
+
return { ok: false, why: 'released', keep: true };
|
|
586
|
+
if (Date.now() > deadline)
|
|
587
|
+
return this.notTyped(pane, moved);
|
|
588
|
+
await sleep(POLL_MS);
|
|
589
|
+
const now = await this.capture(30);
|
|
590
|
+
if (now !== pane)
|
|
591
|
+
moved = true;
|
|
592
|
+
pane = now;
|
|
593
|
+
}
|
|
594
|
+
mkdirSync(this.dir, { recursive: true, mode: 0o700 });
|
|
595
|
+
if ((await loadBuffer(this.name, text, this.dir, (a) => this.tm(a))).code !== 0) {
|
|
596
|
+
this.emit('log', `tmux: the message could not be loaded into a paste buffer pane=${this.name}`);
|
|
597
|
+
return { ok: false, why: 'tmux could not load the message into the session', keep: true };
|
|
598
|
+
}
|
|
599
|
+
await this.tm(['paste-buffer', '-p', '-d', '-b', this.name, '-t', this.name]);
|
|
600
|
+
const landBy = Date.now() + (this.opts.landMs ?? LAND_MS);
|
|
601
|
+
let why = 'the pasted message never showed in the box';
|
|
602
|
+
// Nothing was submitted, so the paste may be tried again from the wait for the prompt.
|
|
603
|
+
let again = true;
|
|
604
|
+
while (Date.now() < landBy) {
|
|
605
|
+
await sleep(300);
|
|
606
|
+
const now = await this.capture(20);
|
|
607
|
+
if (!pasteLanded(now, text))
|
|
608
|
+
continue;
|
|
580
609
|
// A turn started in the app between the idle check and now: Claude would queue our text
|
|
581
610
|
// after it, and its answer would look like ours. Clear the box and say no.
|
|
582
|
-
if (gen !== this.gen || paneBusy(
|
|
611
|
+
if (gen !== this.gen || paneBusy(now)) {
|
|
612
|
+
why = 'the pane became busy before Enter';
|
|
583
613
|
break;
|
|
614
|
+
}
|
|
584
615
|
submit();
|
|
585
616
|
if (await submitPasted(text, () => this.capture(20), () => this.tm(['send-keys', '-t', this.name, 'Enter'])))
|
|
586
|
-
return true;
|
|
587
|
-
|
|
617
|
+
return { ok: true };
|
|
618
|
+
// Enter was pressed: Claude may yet take it, and a second paste would send it twice.
|
|
619
|
+
why = 'the pasted message was not taken after three Enters';
|
|
620
|
+
again = false;
|
|
588
621
|
break;
|
|
589
622
|
}
|
|
623
|
+
this.emit('log', `tmux: ${why} (attempt ${attempt}) pane=${this.name}`);
|
|
624
|
+
await this.tm(['send-keys', '-t', this.name, 'C-u']); // clear whatever landed, submit nothing
|
|
625
|
+
if (gen !== this.gen)
|
|
626
|
+
return { ok: false, why: 'released', keep: true };
|
|
627
|
+
if (!again || attempt >= PASTE_TRIES || Date.now() > deadline) {
|
|
628
|
+
return { ok: false, why: again ? 'Claude Code did not show the pasted message' : 'Claude Code did not take the message', keep: true };
|
|
629
|
+
}
|
|
630
|
+
moved = true; // it drew a prompt since the wait began
|
|
590
631
|
}
|
|
591
|
-
|
|
592
|
-
|
|
632
|
+
}
|
|
633
|
+
/** The message waited the whole bound for a prompt that never came. Kept (the chat is told to send
|
|
634
|
+
* it again, the pane goes on) unless the pane looks hung: its screen never moved, no dialog waits
|
|
635
|
+
* for a person, and no turn of this chat ever started background work in it. Only then may it be
|
|
636
|
+
* ended, as a dead one would. Never a key into what holds it: a dialog is answered by a person.
|
|
637
|
+
* Only a real permission dialog counts as one. Any other screen with no input box that is not at
|
|
638
|
+
* work (a stuck login, a menu, an error) is ended and started fresh, as before 0.4.1: kept, it
|
|
639
|
+
* would hold the chat for good (review fix L5). */
|
|
640
|
+
notTyped(pane, moved) {
|
|
641
|
+
const dialog = permissionDialog(pane) !== null;
|
|
642
|
+
// Which background tasks are still open is not tracked here: any the chat's turns started counts.
|
|
643
|
+
const tasks = this.ours.size;
|
|
644
|
+
const mins = Math.round((this.opts.promptTimeoutMs ?? PROMPT_TIMEOUT_MS) / 60_000);
|
|
645
|
+
const wait = mins >= 1 ? `${mins} minute${mins === 1 ? '' : 's'}` : 'a while';
|
|
646
|
+
this.keepScreen('not-typed.txt', `no prompt for ${wait}`);
|
|
647
|
+
if (!dialog && !paneBusy(pane) && !paneHasBox(pane)) {
|
|
648
|
+
this.emit('log', `tmux: no prompt for ${wait}, no input box and no permission dialog (a login, a menu or an error screen): the pane is ended to start fresh pane=${this.name}`);
|
|
649
|
+
return { ok: false, why: 'stuck', keep: false };
|
|
650
|
+
}
|
|
651
|
+
if (!moved && !dialog && !tasks) {
|
|
652
|
+
this.emit('log', `tmux: no prompt for ${wait} and the screen never moved, no dialog, no background work: the pane looks hung pane=${this.name}`);
|
|
653
|
+
return { ok: false, why: 'hung', keep: false };
|
|
654
|
+
}
|
|
655
|
+
this.emit('log', `tmux: no prompt for ${wait}; the message goes back to the chat and the pane is kept (screen ${moved ? 'moving' : 'still'}, ${dialog ? 'a dialog open' : 'no dialog'}, ${tasks} background task(s) started by this chat) pane=${this.name}`);
|
|
656
|
+
return {
|
|
657
|
+
ok: false, keep: true,
|
|
658
|
+
why: dialog ? 'a dialog is open in the session and waits for an answer in the Claude app or its pane'
|
|
659
|
+
: `the session stayed busy for ${wait} with work of its own (a background task's report, or a turn typed in the Claude app)`,
|
|
660
|
+
};
|
|
593
661
|
}
|
|
594
662
|
/** Keep the screen of a pane whose turn ended or was held on what the screen showed, next to its
|
|
595
663
|
* settings: the one way to see what it showed, without a terminal open at the right second. One
|
|
@@ -641,12 +709,26 @@ export class TuiBrain extends EventEmitter {
|
|
|
641
709
|
const typed = await this.paste(text, submit, gen);
|
|
642
710
|
if (left.over)
|
|
643
711
|
yield { kind: 'unasked', ...left.over };
|
|
644
|
-
if (!typed) {
|
|
712
|
+
if (!typed.ok) {
|
|
645
713
|
// Typed or not, no turn of ours runs: a marker that comes now is not this message's answer.
|
|
646
714
|
if (this.turnSentAt === sentAt)
|
|
647
715
|
this.turnSentAt = undefined;
|
|
648
716
|
this.recording = false;
|
|
649
|
-
|
|
717
|
+
if (!this.up || typed.why === 'exit') {
|
|
718
|
+
yield { kind: 'result', text: '', isError: true, reason: 'exit' };
|
|
719
|
+
return;
|
|
720
|
+
}
|
|
721
|
+
if (typed.why === 'released') {
|
|
722
|
+
yield { kind: 'result', text: '', isError: true, reason: 'released', keep: true };
|
|
723
|
+
return;
|
|
724
|
+
}
|
|
725
|
+
// A pane that is alive goes on with what it does: its background agents live in it. Only a hung
|
|
726
|
+
// one (notTyped) is given back to be ended.
|
|
727
|
+
if (typed.keep) {
|
|
728
|
+
yield { kind: 'result', text: '', isError: true, reason: `${NOT_TYPED}: ${typed.why}`, keep: true };
|
|
729
|
+
return;
|
|
730
|
+
}
|
|
731
|
+
yield { kind: 'result', text: '', isError: true, reason: 'the message could not be typed into the session (no prompt, or Claude Code did not take it)' };
|
|
650
732
|
return;
|
|
651
733
|
}
|
|
652
734
|
yield* this.watch(sentAt, false, gen, text.trimStart().startsWith('/'));
|
package/dist/build.json
CHANGED
package/dist/capabilities/cli.js
CHANGED
|
@@ -11,7 +11,9 @@ export function compileDrift(cfg, table, names = [], opts = {}) {
|
|
|
11
11
|
const stateDir = opts.stateDir ?? INSTANCE_DIR;
|
|
12
12
|
const self = (profile) => selfPrompt({ profile, table, instance: stateDir });
|
|
13
13
|
const which = names.length ? names : Object.keys(cfg.profiles).filter((n) => readRecord(resolve(cfg.profiles[n].cwd)));
|
|
14
|
-
const drift = which.map((n) => planProfile(cfg, n, { self, stateDir, home: opts.home }))
|
|
14
|
+
const drift = which.map((n) => planProfile(cfg, n, { self, stateDir, home: opts.home }))
|
|
15
|
+
// The state folder's own entries coming and going are not drift (ProfilePlan.stateOnly).
|
|
16
|
+
.filter((pl) => pl.changes.some((c) => !pl.stateOnly.includes(c)) || pl.conflicts.length);
|
|
15
17
|
if (!drift.length)
|
|
16
18
|
return '';
|
|
17
19
|
return [...drift.map((pl) => planText(pl) + '\n'), `Out of date: ${drift.map((pl) => pl.profile).join(', ')}. Run angelia compile <profile> --write.`].join('\n');
|