angelia-gateway 0.3.30 → 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.
Files changed (52) hide show
  1. package/README.md +2 -1
  2. package/dist/adapters/telegram/adapter.js +12 -0
  3. package/dist/adapters/whatsapp/adapter.js +114 -14
  4. package/dist/brain/acp.js +371 -0
  5. package/dist/brain/agy-config.js +56 -0
  6. package/dist/brain/agy-history.js +31 -0
  7. package/dist/brain/agy-instructions.js +301 -0
  8. package/dist/brain/agy-login.js +52 -0
  9. package/dist/brain/agy.js +557 -0
  10. package/dist/brain/argv.js +26 -0
  11. package/dist/brain/brain.js +19 -0
  12. package/dist/brain/cache.js +13 -1
  13. package/dist/brain/catalog.js +31 -1
  14. package/dist/brain/codex-config.js +2 -2
  15. package/dist/brain/codex.js +2 -2
  16. package/dist/brain/grok-history.js +9 -4
  17. package/dist/brain/grok.js +11 -236
  18. package/dist/brain/index.js +2 -0
  19. package/dist/brain/locate.js +39 -4
  20. package/dist/brain/pi-gate.js +99 -35
  21. package/dist/brain/pi.js +4 -2
  22. package/dist/brain/tmux.js +2 -0
  23. package/dist/brain/tool-request.js +47 -0
  24. package/dist/brain/tui.js +107 -24
  25. package/dist/build.json +3 -3
  26. package/dist/capabilities/cli.js +3 -1
  27. package/dist/capabilities/compile.js +624 -49
  28. package/dist/cli/cli-args.js +2 -2
  29. package/dist/cli/cli.js +19 -6
  30. package/dist/cli/connect-cli.js +137 -0
  31. package/dist/core/deliver/text.js +10 -0
  32. package/dist/core/orchestrator.js +264 -39
  33. package/dist/core/paths.js +29 -1
  34. package/dist/core/permission-rules.js +3 -0
  35. package/dist/daemon/daemon.js +12 -15
  36. package/dist/daemon/launch-guard.js +49 -0
  37. package/dist/instance/config/load.js +2 -2
  38. package/dist/instance/config/schema.js +8 -3
  39. package/dist/instance/connect.js +303 -0
  40. package/dist/instance/export.js +41 -3
  41. package/dist/instance/guide.js +44 -3
  42. package/dist/instance/init-terminal.js +2 -0
  43. package/dist/instance/init.js +259 -3
  44. package/dist/instance/instance.js +3 -1
  45. package/dist/instance/onboard.js +30 -8
  46. package/dist/instance/profile-views.js +7 -4
  47. package/dist/instance/profiles.js +5 -2
  48. package/dist/instance/switch-backend.js +9 -3
  49. package/dist/jobs/jobs.js +11 -18
  50. package/install.sh +3 -1
  51. package/package.json +2 -2
  52. package/routing.example.yaml +1 -0
package/README.md CHANGED
@@ -189,9 +189,10 @@ Found a hole? Report it privately: [SECURITY.md](SECURITY.md).
189
189
  | Grok Build | `grok` | supported | 1.0.13 or newer, `grok login` |
190
190
  | Codex | `codex` | supported | 0.157 or newer, `codex login` |
191
191
  | pi | `pi` | supported | 0.80.4 or newer (tested on 0.86 and 0.87), macOS, a login or key for a provider |
192
+ | Antigravity CLI | `agy` | supported | 1.5.14 or newer (Gemini models), macOS, a Google sign-in (run `agy` once) |
192
193
  | OpenCode | | coming soon | |
193
194
 
194
- Each chat keeps one warm process, so a message never waits for a CLI to start. Permission prompts reach the chat on all four. Codex runs inside its own sandbox, which the operating system enforces: Angelia hands it the profile's rules, so it writes only in its folders and cannot read your credentials or the other profiles, shell commands included. pi has no sandbox of its own, so Angelia puts every pi shell command and every file read and write inside macOS's sandbox, made from the same rules. Every CLI plugs into the same small interface in `src/brain/`, and nothing else in Angelia knows which one is running.
195
+ Each chat keeps one warm process, so a message never waits for a CLI to start. Permission prompts reach the chat on all five. Codex runs inside its own sandbox, which the operating system enforces: Angelia hands it the profile's rules, so it writes only in its folders and cannot read your credentials or the other profiles, shell commands included. pi has no sandbox of its own, so Angelia puts every pi shell command and every file read and write inside macOS's sandbox, made from the same rules. agy runs whole inside macOS's sandbox the same way, and Angelia's gate answers each of its permission requests from the rules; tmux mode and `chrome: true` stay Claude Code only, and subagents are partial on agy ([what works on each backend](docs/reference.md#what-works-on-each-backend)). agy reads a `GEMINI.md` that Angelia writes from `CLAUDE.md` before each start. Every CLI plugs into the same small interface in `src/brain/`, and nothing else in Angelia knows which one is running.
195
196
 
196
197
  ---
197
198
 
@@ -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
- sock.ev.on('group-participants.update', (u) => this.groups.drop(u.id));
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
- const stream = (await downloadMediaMessage(m, 'stream', {}, { logger: pino({ level: 'silent' }), reuploadRequest: this.sock.updateMediaMessage }));
329
- const ext = p.media.fileName?.match(/\.[A-Za-z0-9]{1,5}$/)?.[0] ?? EXT[p.media.mime ?? ''] ?? '';
330
- const dest = await saveInbound(inbox, ext, stream, MAX_MEDIA);
331
- if (dest)
332
- media.push(dest);
333
- else {
334
- this.log(`whatsapp: media passed ${MAX_MEDIA >> 20} MB while downloading, dropped chat=${p.chat.slice(0, 8)}…`);
335
- note(`a ${KIND_NAME[p.media.kind] ?? p.media.kind} over ${MAX_MEDIA >> 20} MB was sent and not downloaded`);
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)}…: ${String(e.message ?? e).slice(0, 160)}`);
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;
@@ -0,0 +1,371 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { EventEmitter } from 'node:events';
3
+ import { childEnv } from './argv.js';
4
+ import { BrainExited, PermissionBook, exitReason, jsonLine, permissionPreview, stopChild, wireChild, CHILD_GROUP, signalGroup } from './brain.js';
5
+ /**
6
+ * A long-lived ACP agent (Agent Client Protocol, JSON-RPC 2.0 on stdio) per session key. Shared by
7
+ * the CLIs that speak it (grok, agy): spawn, `initialize`, a session opened by the subclass
8
+ * (`openSession`), `session/prompt` per turn with its `session/update` notifications read as the
9
+ * turn's text and progress, `session/request_permission` relayed to the chat (or decided by `gate`),
10
+ * stop and kill, and a start timeout. A subclass gives the launch line and the session handshake.
11
+ */
12
+ export class AcpBrain extends EventEmitter {
13
+ profile;
14
+ session;
15
+ opts;
16
+ /** How long `initialize` and the session handshake may take. Read from the subclass, so a test may set it per backend. */
17
+ static startTimeoutMs = 60_000;
18
+ child;
19
+ /** Lines from the child, by kind: `update`, `permission`, `exit`. */
20
+ lines = new EventEmitter();
21
+ exited = false;
22
+ /** The tail of stderr, for the reason a child that died without answering gives. */
23
+ failure = '';
24
+ nextId = 1;
25
+ replies = new Map();
26
+ permissions;
27
+ /** Pending permission id -> the JSON-RPC id and options the agent offered, and the tool's name. */
28
+ permissionRequests = new Map();
29
+ /** Tools refused in the running turn, by the owner, a timeout or `gate`. */
30
+ refusedThisTurn = [];
31
+ /** Every request `gate` blocked in this session, oldest first. */
32
+ blocked = [];
33
+ ready;
34
+ lastUsedAt = Date.now();
35
+ lastOutputAt;
36
+ version = '';
37
+ backendSessionId;
38
+ /** How many history updates the last session/load replayed (and this class dropped). */
39
+ replayedUpdates = 0;
40
+ constructor(profile, session, opts = {}) {
41
+ super();
42
+ this.profile = profile;
43
+ this.session = session;
44
+ this.opts = opts;
45
+ this.permissions = new PermissionBook(opts.permissionTimeoutMs ?? 10 * 60_000, (id) => { if (this.answerPermission(id, false))
46
+ this.emit('permission-timeout', id); });
47
+ }
48
+ /** The request in Claude Code's naming, for the profile's permission rules; undefined when it cannot be named. */
49
+ toolRequest(_toolCall) { return undefined; }
50
+ /** Work before the child is spawned (folders, files it reads at start). */
51
+ beforeSpawn() { }
52
+ /** Each tool_call update, in a turn and between turns: for a backend that watches what never asks. */
53
+ onToolCall(_u) { }
54
+ /** The child's environment. */
55
+ spawnEnv() { return childEnv(this.opts.env); }
56
+ /**
57
+ * Whether the agent may speak between turns (a background command done, agy wakes itself; ADR 0017 H).
58
+ * When true, after the first turn the stream is read on: its text goes to the chat as an `unasked`
59
+ * answer once it has been quiet for `quietMs`, and its permission requests are gated as in a turn,
60
+ * with 'ask' refused (no turn is open to ask in). False keeps the old reading: nothing between turns.
61
+ */
62
+ wakesBetweenTurns = false;
63
+ /** How long the stream must be quiet before a between-turns answer is sent. */
64
+ static quietMs = 1500;
65
+ /**
66
+ * The one place a permission request is decided before the chat is asked: 'allow' and 'block' answer
67
+ * the agent at once, 'ask' relays the request to the chat. Every request is asked by default.
68
+ */
69
+ gate(_toolCall, _request) { return 'ask'; }
70
+ /** The answer of a turn that ended with no text. `refused`: the tools refused in it, in order. */
71
+ emptyAnswer(_refused) { return ''; }
72
+ get alive() { return !!this.child && !this.exited; }
73
+ /** A turn is reading the stream; outside one, after the first, `wakesBetweenTurns` reads it. */
74
+ inTurn = false;
75
+ betweenArmed = false;
76
+ between = { text: '', refused: [], timer: undefined };
77
+ start() {
78
+ this.beforeSpawn();
79
+ const [bin, ...args] = this.argv();
80
+ const child = spawn(bin, args, { cwd: this.profile.cwd, env: this.spawnEnv(), stdio: ['pipe', 'pipe', 'pipe'], ...CHILD_GROUP });
81
+ this.child = child;
82
+ if (this.wakesBetweenTurns) {
83
+ this.lines.on('update', (u) => { if (this.betweenArmed && !this.inTurn)
84
+ this.betweenUpdate(u); });
85
+ this.lines.on('permission', (m) => { if (this.betweenArmed && !this.inTurn)
86
+ this.betweenPermission(m); });
87
+ }
88
+ const done = (code, signal) => {
89
+ if (this.exited)
90
+ return;
91
+ this.exited = true;
92
+ clearTimeout(this.between.timer);
93
+ this.permissions.clear();
94
+ for (const p of this.replies.values())
95
+ p.reject(new BrainExited(`${this.cliName} exited`));
96
+ this.replies.clear();
97
+ this.lines.emit('exit', { code, signal });
98
+ this.emit('exit', { code, signal });
99
+ };
100
+ // A spawn that never happened would otherwise leave the handshake waiting for ever (wireChild).
101
+ wireChild(child, { exit: done, failure: (t) => { this.failure = t; }, line: (m) => { this.lastOutputAt = Date.now(); this.dispatch(m); } });
102
+ // An agent that never answers initialize would hold the chat's first turn for good (Codex has the
103
+ // same guard). Stopped then, so the next message starts a fresh process; the timer is cleared as
104
+ // soon as the handshake ends, or it would kill a healthy brain later.
105
+ const limit = this.constructor.startTimeoutMs;
106
+ let timer;
107
+ this.ready = Promise.race([this.handshake(), new Promise((_, reject) => {
108
+ timer = setTimeout(() => { this.kill(); reject(new Error(`${this.cliName} did not answer within ${Math.round(limit / 1000)} s of starting; check that \`${this.cliName} --version\` runs in a terminal`)); }, limit);
109
+ timer.unref?.();
110
+ })]).finally(() => clearTimeout(timer));
111
+ this.ready.catch(() => { });
112
+ }
113
+ dispatch(m) {
114
+ if (m.id !== undefined && m.method === undefined) {
115
+ const p = this.replies.get(m.id);
116
+ if (!p)
117
+ return;
118
+ this.replies.delete(m.id);
119
+ if (m.error)
120
+ p.reject(new Error(String(m.error.message ?? JSON.stringify(m.error))));
121
+ else
122
+ p.resolve(m.result ?? {});
123
+ return;
124
+ }
125
+ if (m.method === 'session/request_permission') {
126
+ this.lines.emit('permission', m);
127
+ return;
128
+ }
129
+ if (m.method === 'session/update') {
130
+ // Another session of the same process (an agy subagent Angelia attached): its text is not this
131
+ // chat's answer; the parent reports what it did.
132
+ const other = m.params?.sessionId !== undefined && this.backendSessionId !== undefined && m.params.sessionId !== this.backendSessionId;
133
+ this.lines.emit(other ? 'other-update' : 'update', m.params?.update ?? {}, m.params?.sessionId);
134
+ return;
135
+ }
136
+ if (m.id !== undefined && m.method) {
137
+ // A client-side request we did not advertise (fs, terminal). Refuse it cleanly.
138
+ this.write({ jsonrpc: '2.0', id: m.id, error: { code: -32601, message: `unsupported: ${m.method}` } });
139
+ }
140
+ }
141
+ write(obj) {
142
+ this.child?.stdin.write(jsonLine(obj));
143
+ }
144
+ call(method, params) {
145
+ if (!this.alive)
146
+ return Promise.reject(new BrainExited('brain not running'));
147
+ const id = this.nextId++;
148
+ return new Promise((resolve, reject) => {
149
+ this.replies.set(id, { resolve, reject });
150
+ this.write({ jsonrpc: '2.0', id, method, params });
151
+ });
152
+ }
153
+ /**
154
+ * `session/load` with the history it replays dropped. ACP replays the whole conversation as
155
+ * session/update notifications before it answers. The chat already holds every one of those
156
+ * messages, so they are dropped on purpose, and counted so the decision is visible. They must be
157
+ * drained here: an update still arriving once a turn's listener is attached would be sent to the
158
+ * chat as a fresh answer.
159
+ */
160
+ async loadDroppingReplay(params) {
161
+ let replayed = 0;
162
+ const drop = () => { replayed++; };
163
+ this.lines.on('update', drop);
164
+ try {
165
+ return await this.call('session/load', params);
166
+ }
167
+ finally {
168
+ this.lines.off('update', drop);
169
+ this.replayedUpdates = replayed;
170
+ }
171
+ }
172
+ /** initialize, then open or load the session. Resolves to the ACP session id. */
173
+ async handshake() {
174
+ const init = await this.call('initialize', {
175
+ protocolVersion: 1,
176
+ clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
177
+ });
178
+ if (typeof init.agentInfo?.version === 'string')
179
+ this.version = init.agentInfo.version;
180
+ return this.openSession(init);
181
+ }
182
+ async *turn(text) {
183
+ if (!this.alive || !this.ready)
184
+ throw new BrainExited('brain not running');
185
+ this.lastUsedAt = Date.now();
186
+ let sid;
187
+ try {
188
+ sid = await this.ready;
189
+ }
190
+ catch (e) {
191
+ yield { kind: 'result', text: '', isError: true, reason: this.exited ? exitReason(this.failure) : `handshake: ${e.message}` };
192
+ return;
193
+ }
194
+ const queue = [];
195
+ let wake = null;
196
+ const push = (m) => { queue.push(m); wake?.(); };
197
+ const onUpdate = (u) => push({ __kind: 'update', u });
198
+ const onPermission = (m) => push({ __kind: 'permission', m });
199
+ const onExit = () => push({ __kind: 'exit' });
200
+ this.lines.on('update', onUpdate);
201
+ this.lines.on('permission', onPermission);
202
+ this.lines.on('exit', onExit);
203
+ this.refusedThisTurn = [];
204
+ this.inTurn = true;
205
+ // What the agent said between turns and was still waiting for quiet goes first, as its own answer.
206
+ const before = this.takeBetween();
207
+ if (before)
208
+ yield { kind: 'unasked', answer: 'self', text: before };
209
+ let done;
210
+ this.call('session/prompt', { sessionId: sid, prompt: [{ type: 'text', text }] })
211
+ .then((r) => { done = r; push({ __kind: 'done' }); }, (e) => { done = e; push({ __kind: 'done' }); });
212
+ let pendingText = '';
213
+ let lastFlushed = '';
214
+ try {
215
+ while (true) {
216
+ if (!queue.length)
217
+ await new Promise((r) => (wake = r));
218
+ wake = null;
219
+ const item = queue.shift();
220
+ if (item.__kind === 'exit') {
221
+ yield { kind: 'result', text: '', isError: true, reason: exitReason(this.failure) };
222
+ return;
223
+ }
224
+ if (item.__kind === 'update') {
225
+ const u = item.u;
226
+ if (u.sessionUpdate === 'agent_message_chunk' && u.content?.type === 'text')
227
+ pendingText += String(u.content.text ?? '');
228
+ else if (u.sessionUpdate === 'tool_call') {
229
+ this.onToolCall(u);
230
+ const t = pendingText.trim();
231
+ if (t && t !== lastFlushed) {
232
+ lastFlushed = t;
233
+ yield { kind: 'progress', text: t };
234
+ }
235
+ pendingText = '';
236
+ }
237
+ continue;
238
+ }
239
+ if (item.__kind === 'permission') {
240
+ const m = item.m;
241
+ const options = Array.isArray(m.params?.options) ? m.params.options : [];
242
+ // Only ever this one call: an allow_always would let the agent skip every later ask of its kind.
243
+ // Without an allow_once, an approval is answered as a refusal (cancelled).
244
+ const allow = options.find((o) => o.kind === 'allow_once');
245
+ const deny = options.find((o) => o.kind === 'reject_once') ?? options.find((o) => o.kind === 'reject_always');
246
+ const tc = m.params?.toolCall ?? {};
247
+ const id = String(tc.toolCallId ?? m.id);
248
+ const tool = this.toolName(tc);
249
+ const request = this.toolRequest(tc);
250
+ const shown = permissionPreview(tc.rawInput ?? tc.title ?? '');
251
+ let verdict = this.gate(tc, request);
252
+ if (verdict === 'allow' && !allow)
253
+ verdict = { action: 'block', reason: `${this.cliName} offered no allow-once answer` };
254
+ if (verdict !== 'ask') {
255
+ const reason = typeof verdict === 'object' ? verdict.reason : undefined;
256
+ if (verdict !== 'allow') {
257
+ this.refusedThisTurn.push(reason ? `${tool}: ${reason}` : tool);
258
+ this.blocked.push({ tool, preview: shown.preview, at: Date.now(), ...(reason ? { reason } : {}) });
259
+ }
260
+ this.reply(m.id, verdict === 'allow' ? allow?.optionId : deny?.optionId);
261
+ continue;
262
+ }
263
+ this.permissionRequests.set(id, { rpcId: m.id, allow: allow?.optionId, deny: deny?.optionId, tool });
264
+ this.permissions.add(id);
265
+ yield { kind: 'permission', id, tool, ...shown, ...(request ? { request } : {}) };
266
+ continue;
267
+ }
268
+ if (item.__kind === 'done') {
269
+ this.lastUsedAt = Date.now();
270
+ if (done instanceof Error) {
271
+ yield { kind: 'result', text: '', isError: true, reason: this.exited ? exitReason(this.failure) : done.message };
272
+ return;
273
+ }
274
+ const stop = String(done?.stopReason ?? 'end_turn');
275
+ const text = pendingText.trim();
276
+ if (stop === 'refusal' && !text) {
277
+ yield { kind: 'result', text: '', isError: true, reason: 'refusal' };
278
+ return;
279
+ }
280
+ yield { kind: 'result', text: text || this.emptyAnswer([...this.refusedThisTurn]), isError: false };
281
+ return;
282
+ }
283
+ }
284
+ }
285
+ finally {
286
+ this.lines.off('update', onUpdate);
287
+ this.lines.off('permission', onPermission);
288
+ this.lines.off('exit', onExit);
289
+ this.inTurn = false;
290
+ if (this.wakesBetweenTurns)
291
+ this.betweenArmed = true;
292
+ }
293
+ }
294
+ /** Between turns: the agent's text gathers until the stream has been quiet for `quietMs`. */
295
+ betweenUpdate(u) {
296
+ if (u.sessionUpdate === 'tool_call')
297
+ this.onToolCall(u);
298
+ if (u.sessionUpdate === 'agent_message_chunk' && u.content?.type === 'text')
299
+ this.between.text += String(u.content.text ?? '');
300
+ else if (u.sessionUpdate === 'tool_call' && this.between.text && !this.between.text.endsWith('\n\n'))
301
+ this.between.text += '\n\n';
302
+ else if (u.sessionUpdate === 'tool_call')
303
+ this.emit('log', `${this.cliName} between turns: tool ${this.toolName(u)} ${String(u.status ?? '')}`);
304
+ this.armQuiet();
305
+ }
306
+ /** Between turns: gate() answers; what it would ask the chat is refused, as no turn is open to ask in. */
307
+ betweenPermission(m) {
308
+ const options = Array.isArray(m.params?.options) ? m.params.options : [];
309
+ const allow = options.find((o) => o.kind === 'allow_once');
310
+ const deny = options.find((o) => o.kind === 'reject_once') ?? options.find((o) => o.kind === 'reject_always');
311
+ const tc = m.params?.toolCall ?? {};
312
+ const tool = this.toolName(tc);
313
+ const verdict = this.gate(tc, this.toolRequest(tc));
314
+ if (verdict === 'allow') {
315
+ this.reply(m.id, allow?.optionId);
316
+ this.armQuiet();
317
+ return;
318
+ }
319
+ const reason = typeof verdict === 'object' ? verdict.reason : verdict === 'ask' ? 'asked between turns, when no one could answer' : undefined;
320
+ this.blocked.push({ tool, preview: permissionPreview(tc.rawInput ?? tc.title ?? '').preview, at: Date.now(), ...(reason ? { reason } : {}), between: true });
321
+ this.between.refused.push(reason ? `${tool}: ${reason}` : tool);
322
+ this.emit('log', `${this.cliName} between turns: refused ${tool}${reason ? ` (${reason})` : ''}`);
323
+ this.reply(m.id, deny?.optionId);
324
+ this.armQuiet();
325
+ }
326
+ armQuiet() {
327
+ clearTimeout(this.between.timer);
328
+ this.between.timer = setTimeout(() => {
329
+ const text = this.takeBetween();
330
+ if (text)
331
+ this.emit('unasked', { answer: 'self', text });
332
+ }, this.constructor.quietMs);
333
+ this.between.timer.unref?.();
334
+ }
335
+ /** The between-turns answer gathered so far, emptied. */
336
+ takeBetween() {
337
+ clearTimeout(this.between.timer);
338
+ const text = this.between.text.trim() || (this.between.refused.length ? this.emptyAnswer(this.between.refused) : '');
339
+ this.between = { text: '', refused: [], timer: undefined };
340
+ return text;
341
+ }
342
+ /** Answer a permission request with an option id; none means the request was cancelled. */
343
+ reply(rpcId, optionId) {
344
+ const outcome = optionId ? { outcome: 'selected', optionId } : { outcome: 'cancelled' };
345
+ this.write({ jsonrpc: '2.0', id: rpcId, result: { outcome } });
346
+ }
347
+ answerPermission(id, allow) {
348
+ const full = this.permissions.take(id);
349
+ if (!full)
350
+ return false;
351
+ const req = this.permissionRequests.get(full);
352
+ this.permissionRequests.delete(full);
353
+ if (!req)
354
+ return false;
355
+ if (!allow)
356
+ this.refusedThisTurn.push(req.tool);
357
+ this.reply(req.rpcId, allow ? req.allow : req.deny);
358
+ return true;
359
+ }
360
+ /** The running child's pid, for a backend that ends what the child started (agy). */
361
+ get childPid() { return this.child && !this.exited ? this.child.pid : undefined; }
362
+ get pendingPermissionCount() { return this.permissions.size; }
363
+ hasPendingPermission(id) { return this.permissions.has(id); }
364
+ async stop(graceMs = 5000) {
365
+ if (this.child && !this.exited)
366
+ await stopChild(this.child, this.lines, () => this.exited, graceMs);
367
+ }
368
+ kill() { if (this.child && !this.exited)
369
+ signalGroup(this.child, 'SIGKILL'); }
370
+ }
371
+ //# sourceMappingURL=acp.js.map