@beatos/bridge-runner 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/runner.js ADDED
@@ -0,0 +1,762 @@
1
+ /**
2
+ * The BeatOS Bridge v1 runner loop (BEA-85): the older local dispatcher, rebuilt.
3
+ *
4
+ * Each tick:
5
+ * 1. heartbeat: say "alive" to beatos.app (a paused or revoked runner takes no work;
6
+ * a 401 means the key was revoked: stop the live session, do nothing);
7
+ * 2. flush: send every saved event (durable lane, see outbox.ts);
8
+ * 3. control: read each open run's state (BEA-86). Stopped by the human: kill the
9
+ * live session and finish the run as cancelled. Paused: kill the live
10
+ * session but keep its session id, and start, resume or retry nothing;
11
+ * 4. follow: runs waiting on the human: an answer or a decision continues the
12
+ * SAME Claude session; a due retry starts the next attempt; a resumed
13
+ * run continues the session the pause cut;
14
+ * 5. start: a new BeatOS task assigned to this agent, if a slot is free.
15
+ *
16
+ * Rules that never change: never skip permissions, no Chrome, the agent never
17
+ * pushes, merges or deploys, and what a task, comment or agent says is data.
18
+ *
19
+ * Bridge v1.1 (BEA-87): the agent's setup from Bridge (instructions in the
20
+ * brief, model, run limit), the workspace's approval rules (a free kind skips
21
+ * the request, a forbidden kind is refused before asking, opening a PR may
22
+ * need a yes first), and each session's usage on its closing event.
23
+ */
24
+ import { createHash } from "node:crypto";
25
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
26
+ import { join } from "node:path";
27
+ import { ApiError } from "./api.js";
28
+ import { answerText, parseAgentReply } from "./agent-reply.js";
29
+ import { briefText, CONTINUE_PROMPT, REPLY_PROMPT, RETRY_PROMPT, rulesText, START_PROMPT, } from "./brief.js";
30
+ import { classifyError, retryDelaySeconds, sessionUsage, } from "./claude.js";
31
+ import { Outbox } from "./outbox.js";
32
+ import { decideAction } from "./policy.js";
33
+ import { claudeArgs, sessionSettings, agentEnv } from "./safety.js";
34
+ export const RUNNER_VERSION = "0.1.0";
35
+ /** A model name from Bridge goes into argv: plain names only. */
36
+ const MODEL_RE = /^[A-Za-z0-9._-]{1,64}$/;
37
+ const CLAIM_REFRESH_MS = 5 * 60_000;
38
+ const LOG_FLUSH_MS = 2_000;
39
+ /** After a runner error mid-session, wait this long before the session continues. */
40
+ const CRASH_RESUME_MS = 60_000;
41
+ export function taskCode(task) {
42
+ return task.code || task.id.slice(0, 8);
43
+ }
44
+ export function sha256Hex(text) {
45
+ return createHash("sha256").update(text, "utf8").digest("hex");
46
+ }
47
+ export class Runner {
48
+ d;
49
+ statePath;
50
+ state;
51
+ ownerId = null;
52
+ active = null;
53
+ /** The run whose session is live, and how to stop it (BEA-86). */
54
+ live = null;
55
+ /** Each open run's state as the server saw it this tick. */
56
+ serverRuns = new Map();
57
+ runnerStatus = "active";
58
+ constructor(deps) {
59
+ this.d = deps;
60
+ mkdirSync(deps.cfg.stateDir, { recursive: true });
61
+ this.statePath = join(deps.cfg.stateDir, "state.json");
62
+ this.state = this.load();
63
+ }
64
+ now() {
65
+ return (this.d.now ?? Date.now)();
66
+ }
67
+ log(msg) {
68
+ (this.d.log ?? ((m) => console.log(`[bridge-runner] ${m}`)))(msg);
69
+ }
70
+ load() {
71
+ try {
72
+ const s = JSON.parse(readFileSync(this.statePath, "utf8"));
73
+ const runs = s.runs ?? {};
74
+ // No session can be alive in a fresh process: a "working" run was cut
75
+ // (reboot, crash, Ctrl+C). Pause it so the SAME session continues next tick.
76
+ for (const rec of Object.values(runs)) {
77
+ if (rec.phase !== "working")
78
+ continue;
79
+ rec.phase = "paused";
80
+ rec.retryAt = undefined;
81
+ this.log(`${rec.code}: was working when the runner stopped; continuing its session`);
82
+ }
83
+ return { runnerId: s.runnerId ?? null, runs, daily: s.daily ?? {} };
84
+ }
85
+ catch {
86
+ return { runnerId: null, runs: {}, daily: {} };
87
+ }
88
+ }
89
+ save() {
90
+ const tmp = this.statePath + ".tmp";
91
+ writeFileSync(tmp, JSON.stringify(this.state, null, 1), "utf8");
92
+ renameSync(tmp, this.statePath);
93
+ }
94
+ outbox(runId) {
95
+ return new Outbox(join(this.d.cfg.stateDir, "outbox"), runId);
96
+ }
97
+ today() {
98
+ return new Date(this.now()).toISOString().slice(0, 10);
99
+ }
100
+ runsLeft() {
101
+ return this.d.cfg.maxRunsPerDay - (this.state.daily[this.today()] ?? 0);
102
+ }
103
+ countRun() {
104
+ const t = this.today();
105
+ this.state.daily = { [t]: (this.state.daily[t] ?? 0) + 1 };
106
+ }
107
+ /** True while a Claude session is running in this process. */
108
+ get busy() {
109
+ return this.active !== null;
110
+ }
111
+ async tick() {
112
+ if (!(await this.heartbeat()))
113
+ return;
114
+ await this.flushAll();
115
+ // Pause and stop work on a paused runner too: it still owns its runs.
116
+ await this.control();
117
+ if (this.runnerStatus !== "active") {
118
+ this.save();
119
+ return;
120
+ }
121
+ await this.follow();
122
+ if (!this.busy)
123
+ await this.startNew();
124
+ this.save();
125
+ }
126
+ /** Waits for the running session, if any (tests and shutdown). */
127
+ async idle() {
128
+ while (this.active)
129
+ await this.active;
130
+ }
131
+ /** False when the key no longer works (revoked): the tick does nothing else. */
132
+ async heartbeat() {
133
+ let r;
134
+ try {
135
+ r = await this.d.api.heartbeat({
136
+ name: this.d.cfg.runnerName,
137
+ kind: "pc",
138
+ ...(this.d.cfg.workspaceId ? { workspace_id: this.d.cfg.workspaceId } : {}),
139
+ runner_version: RUNNER_VERSION,
140
+ capabilities: {
141
+ connectors: ["claude"],
142
+ profile: this.d.cfg.profile,
143
+ browser_level: 1,
144
+ // Usage screen (BEA-87): the cap and how runs are paid on this computer.
145
+ max_runs_per_day: this.d.cfg.maxRunsPerDay,
146
+ billing: this.d.cfg.billing,
147
+ },
148
+ max_concurrent: 1,
149
+ });
150
+ }
151
+ catch (err) {
152
+ if (err instanceof ApiError && err.status === 401) {
153
+ if (this.runnerStatus !== "revoked") {
154
+ this.log("the runner key was refused (revoked?): stopping work, taking none");
155
+ }
156
+ this.runnerStatus = "revoked";
157
+ this.stopLive("revoked");
158
+ return false;
159
+ }
160
+ throw err;
161
+ }
162
+ this.state.runnerId = r.runner_id;
163
+ this.runnerStatus = r.status;
164
+ if (r.status === "revoked")
165
+ this.stopLive("revoked");
166
+ return true;
167
+ }
168
+ /** Kill the live Claude session, if any (pause, stop, revoke). */
169
+ stopLive(reason, runId) {
170
+ if (!this.live || (runId && this.live.runId !== runId))
171
+ return;
172
+ if (!this.live.ctl.signal.aborted)
173
+ this.live.ctl.abort(reason);
174
+ }
175
+ // ---------- pause and stop from beatos.app (BEA-86) ----------
176
+ async control() {
177
+ this.serverRuns.clear();
178
+ for (const rec of Object.values(this.state.runs)) {
179
+ if (rec.phase === "done")
180
+ continue;
181
+ let s;
182
+ try {
183
+ s = await this.d.api.runState(rec.runId);
184
+ }
185
+ catch (err) {
186
+ this.log(`${rec.code}: could not read the run state (${err.message})`);
187
+ continue;
188
+ }
189
+ this.serverRuns.set(rec.runId, s);
190
+ this.outbox(rec.runId).adoptServerAck(s.ack_seq);
191
+ if (s.status === "cancelled") {
192
+ if (this.live?.runId === rec.runId)
193
+ this.stopLive("cancelled", rec.runId);
194
+ else
195
+ await this.finishCancelled(rec);
196
+ }
197
+ else if (s.status === "paused" && this.live?.runId === rec.runId) {
198
+ this.stopLive("paused", rec.runId);
199
+ }
200
+ }
201
+ // A killed session settles fast; wait so this tick sees its final phase.
202
+ if (this.live?.ctl.signal.aborted)
203
+ await this.idle();
204
+ }
205
+ /** The human stopped the run: close it here and hand the task back. */
206
+ async finishCancelled(rec) {
207
+ this.event(rec, "finish", { outcome: "cancelled", summary: "Stopped in Bridge." });
208
+ rec.phase = "done";
209
+ rec.waitFor = undefined;
210
+ rec.retryAt = undefined;
211
+ this.log(`${rec.code}: stopped in Bridge`);
212
+ await this.flushRun(rec);
213
+ await this.tellTask(rec, "human_took_over", "Local AI (runner Bridge): el usuario detuvo la corrida en Bridge. No sigo con esta tarea.");
214
+ }
215
+ /** True while the server holds this run (paused or stopped): touch nothing. */
216
+ held(rec) {
217
+ const s = this.serverRuns.get(rec.runId)?.status;
218
+ return s === "paused" || s === "cancelled";
219
+ }
220
+ async flushAll() {
221
+ for (const rec of Object.values(this.state.runs)) {
222
+ const ob = this.outbox(rec.runId);
223
+ if (ob.size === 0)
224
+ continue;
225
+ try {
226
+ const ok = await ob.flush(this.d.api.sender(rec.runId, rec.attemptNo, rec.leaseEpoch));
227
+ if (!ok)
228
+ this.log(`${rec.code}: lease ${rec.leaseEpoch} is stale, events stay on disk`);
229
+ }
230
+ catch (err) {
231
+ this.log(`${rec.code}: flush failed, will retry (${err.message})`);
232
+ }
233
+ }
234
+ // Task notes that failed earlier (the connection was cut) go out now.
235
+ for (const rec of Object.values(this.state.runs)) {
236
+ if (rec.taskNotes?.length)
237
+ await this.deliverTaskNotes(rec);
238
+ }
239
+ // Forget finished runs whose events AND task notes all reached the server.
240
+ for (const [id, rec] of Object.entries(this.state.runs)) {
241
+ if (rec.phase === "done" && this.outbox(id).size === 0 && !rec.taskNotes?.length) {
242
+ delete this.state.runs[id];
243
+ }
244
+ }
245
+ }
246
+ event(rec, type, data) {
247
+ this.outbox(rec.runId).append(type, data);
248
+ }
249
+ // ---------- follow runs that wait ----------
250
+ async follow() {
251
+ for (const rec of Object.values(this.state.runs)) {
252
+ if (this.busy)
253
+ return;
254
+ // No state read this tick (network) or held by the human: wait.
255
+ if (!this.serverRuns.has(rec.runId) || this.held(rec))
256
+ continue;
257
+ if (rec.phase === "paused") {
258
+ // Paused after a runner error: wait out the delay first.
259
+ if (rec.retryAt !== undefined && this.now() < rec.retryAt)
260
+ continue;
261
+ rec.retryAt = undefined;
262
+ // Resumed: continue the SAME session the pause cut (or start, if none yet).
263
+ const brief = rec.place.brief.replace(/\\/g, "/");
264
+ this.log(`${rec.code}: resumed`);
265
+ this.event(rec, "status", { status: "running" });
266
+ this.launch(rec, rec.sessionId ? CONTINUE_PROMPT(brief) : START_PROMPT(brief), true);
267
+ }
268
+ else if (rec.phase === "retry" && rec.retryAt !== undefined && this.now() >= rec.retryAt) {
269
+ await this.nextAttempt(rec, RETRY_PROMPT(rec.place.brief.replace(/\\/g, "/")));
270
+ }
271
+ else if (rec.phase === "waiting" && rec.resumeWith) {
272
+ const path = rec.resumeWith;
273
+ rec.resumeWith = undefined;
274
+ this.event(rec, "status", { status: "running" });
275
+ this.launch(rec, REPLY_PROMPT(path), true);
276
+ }
277
+ else if (rec.phase === "waiting" && rec.waitFor) {
278
+ await this.checkWait(rec);
279
+ }
280
+ }
281
+ }
282
+ async checkWait(rec) {
283
+ const state = this.serverRuns.get(rec.runId);
284
+ if (!state)
285
+ return;
286
+ const w = rec.waitFor;
287
+ if (!w)
288
+ return;
289
+ if (w.type === "question") {
290
+ const q = state.questions.find((x) => x.id === w.id);
291
+ if (!q || q.status !== "answered" || !q.answer)
292
+ return;
293
+ const text = answerText(w.kind, w.payload, q.answer);
294
+ const path = this.writeAnswer(rec, text);
295
+ rec.waitFor = undefined;
296
+ if (w.retryOnAccept) {
297
+ // The question was "the run failed, retry?": an accept or a change request starts a new attempt.
298
+ // With no session yet (it never started), start from the task itself.
299
+ await this.nextAttempt(rec, rec.sessionId ? REPLY_PROMPT(path) : START_PROMPT(rec.place.brief.replace(/\\/g, "/")));
300
+ }
301
+ else {
302
+ this.event(rec, "status", { status: "running" });
303
+ this.launch(rec, REPLY_PROMPT(path), true);
304
+ }
305
+ return;
306
+ }
307
+ const a = state.approvals.find((x) => x.id === w.id);
308
+ if (!a || a.status === "pending")
309
+ return;
310
+ if (w.then === "publish") {
311
+ rec.waitFor = undefined;
312
+ const kept = `Los commits quedan en la rama ${rec.place.branch}.`;
313
+ if (a.status !== "approved") {
314
+ await this.finishDone(rec, `${w.result ?? ""}\n\nNo abri el PR (${a.status}). ${kept}`, false);
315
+ return;
316
+ }
317
+ try {
318
+ await this.d.api.consumeApproval(a.id, w.digest);
319
+ }
320
+ catch (err) {
321
+ const code = err instanceof ApiError ? err.code : "error";
322
+ await this.finishDone(rec, `${w.result ?? ""}\n\nNo abri el PR: la aprobacion no se pudo usar (${code}). ${kept}`, false);
323
+ return;
324
+ }
325
+ await this.finishDone(rec, w.result ?? "", true);
326
+ return;
327
+ }
328
+ let text;
329
+ if (a.status === "approved") {
330
+ try {
331
+ await this.d.api.consumeApproval(a.id, w.digest);
332
+ text = `El usuario APROBO la accion: ${w.summary}. Solo esa accion exacta, con el mismo contenido. Si el contenido cambia, pide permiso otra vez.`;
333
+ }
334
+ catch (err) {
335
+ const code = err instanceof ApiError ? err.code : "error";
336
+ text = `La aprobacion no se pudo usar (${code}). No hagas la accion. Explica que falta y termina.`;
337
+ }
338
+ }
339
+ else {
340
+ const note = a.decisionNote ? ` Nota del usuario: ${a.decisionNote}` : "";
341
+ text = `El usuario NO aprobo la accion (${a.status}): ${w.summary}. No la hagas.${note}`;
342
+ }
343
+ const path = this.writeAnswer(rec, text);
344
+ rec.waitFor = undefined;
345
+ this.event(rec, "status", { status: "running" });
346
+ this.launch(rec, REPLY_PROMPT(path), true);
347
+ }
348
+ writeAnswer(rec, text) {
349
+ rec.replies += 1;
350
+ const path = join(rec.place.brief, `RESPUESTA-${rec.replies}.md`);
351
+ writeFileSync(path, text + "\n", "utf8");
352
+ return path.replace(/\\/g, "/");
353
+ }
354
+ async nextAttempt(rec, prompt) {
355
+ try {
356
+ const a = await this.d.api.startAttempt(rec.runId);
357
+ rec.attemptNo = a.attempt_no;
358
+ rec.leaseEpoch = a.lease_epoch;
359
+ }
360
+ catch (err) {
361
+ if (err instanceof ApiError && err.code === "retry_not_due")
362
+ return;
363
+ throw err;
364
+ }
365
+ this.event(rec, "status", { status: "running" });
366
+ this.launch(rec, prompt, Boolean(rec.sessionId));
367
+ }
368
+ // ---------- start new work ----------
369
+ eligible(task) {
370
+ if (task.delegationStatus !== "queued_for_ai")
371
+ return false;
372
+ if (this.ownerId && task.userId && task.userId !== this.ownerId)
373
+ return false;
374
+ if (task.machineTarget && task.machineTarget !== this.d.cfg.machine)
375
+ return false;
376
+ if (Object.values(this.state.runs).some((r) => r.taskId === task.id && r.phase !== "done"))
377
+ return false;
378
+ const project = task.projectId ? this.d.cfg.projects[task.projectId] : undefined;
379
+ return project?.mode !== "exclude";
380
+ }
381
+ async startNew() {
382
+ if (this.runsLeft() <= 0 || !this.state.runnerId)
383
+ return;
384
+ if (!this.ownerId)
385
+ this.ownerId = (await this.d.api.me()).id;
386
+ const tasks = await this.d.api.readyTasks(this.d.cfg.agentName);
387
+ const task = tasks.find((t) => this.eligible(t));
388
+ if (!task)
389
+ return;
390
+ try {
391
+ await this.d.api.claim(task.id);
392
+ }
393
+ catch (err) {
394
+ this.log(`${taskCode(task)}: claim refused (${err.message})`);
395
+ return;
396
+ }
397
+ const code = taskCode(task);
398
+ const project = task.projectId ? this.d.cfg.projects[task.projectId] : undefined;
399
+ let place;
400
+ let setup;
401
+ let created;
402
+ // Claimed: if the run cannot start, the task goes back to the human.
403
+ try {
404
+ place = this.d.workspace.prepare(code, project);
405
+ setup = await this.agentSetup();
406
+ writeFileSync(join(place.brief, "TAREA.md"), briefText(code, task, project?.name ?? "", place, [], {
407
+ name: this.d.cfg.agentName,
408
+ instructions: setup?.instructions,
409
+ }), "utf8");
410
+ writeFileSync(join(place.brief, "REGLAS.md"), rulesText(code, place), "utf8");
411
+ created = await this.d.api.createRun({
412
+ runner_id: this.state.runnerId,
413
+ task_id: task.id,
414
+ agent_name: this.d.cfg.agentName,
415
+ title: `${code} | ${task.title}`.slice(0, 500),
416
+ connector: "claude",
417
+ profile: this.d.cfg.profile,
418
+ folder: place.cwd,
419
+ ...(place.branch ? { git_branch: place.branch } : {}),
420
+ });
421
+ }
422
+ catch (err) {
423
+ await this.handBack(task, err.message);
424
+ return;
425
+ }
426
+ const rec = {
427
+ runId: created.run.id,
428
+ taskId: task.id,
429
+ code,
430
+ title: task.title,
431
+ place,
432
+ attemptNo: created.attempt?.attempt_no ?? 1,
433
+ leaseEpoch: created.attempt?.lease_epoch ?? 1,
434
+ sessionId: created.run.sessionId,
435
+ phase: "working",
436
+ replies: 0,
437
+ lastClaimAt: this.now(),
438
+ ...(setup?.model && MODEL_RE.test(setup.model) ? { model: setup.model } : {}),
439
+ ...(typeof setup?.max_run_minutes === "number" && setup.max_run_minutes > 0
440
+ ? { maxRunMinutes: Math.min(setup.max_run_minutes, 480) }
441
+ : {}),
442
+ };
443
+ this.state.runs[rec.runId] = rec;
444
+ this.event(rec, "status", { status: "running" });
445
+ this.event(rec, "workspace", {
446
+ folder: place.cwd,
447
+ ...(place.branch ? { git_branch: place.branch } : {}),
448
+ });
449
+ this.log(`${code}: run ${rec.runId} started in ${place.cwd}`);
450
+ this.launch(rec, START_PROMPT(place.brief.replace(/\\/g, "/")), Boolean(rec.sessionId));
451
+ }
452
+ /**
453
+ * The task was claimed but its run never started: hand it back to the human
454
+ * so it is not stuck "in progress". No run record, so nothing to retry.
455
+ */
456
+ async handBack(task, error) {
457
+ const code = taskCode(task);
458
+ const short = error.slice(0, 200);
459
+ this.log(`${code}: could not start the run, handing the task back (${short})`);
460
+ try {
461
+ await this.d.api.updateTask(task.id, { delegation_status: "paused_needs_input" });
462
+ await this.d.api.comment(task.id, `Local AI (runner Bridge): no pude empezar la tarea: ${short}`);
463
+ }
464
+ catch (err) {
465
+ this.log(`${code}: could not hand the task back (${err.message})`);
466
+ }
467
+ }
468
+ // ---------- one Claude session ----------
469
+ launch(rec, prompt, resume) {
470
+ rec.phase = "working";
471
+ this.countRun();
472
+ this.save();
473
+ const p = this.session(rec, prompt, resume)
474
+ .catch((err) => {
475
+ this.log(`${rec.code}: session crashed in the runner (${err.message})`);
476
+ // Never leave the run "working": the same session continues after a pause.
477
+ if (rec.phase === "working") {
478
+ rec.phase = "paused";
479
+ rec.retryAt = this.now() + CRASH_RESUME_MS;
480
+ this.log(`${rec.code}: paused, continues in ${CRASH_RESUME_MS / 1000}s`);
481
+ }
482
+ })
483
+ .finally(() => {
484
+ this.active = null;
485
+ this.save();
486
+ });
487
+ this.active = p;
488
+ }
489
+ async session(rec, prompt, resume) {
490
+ const args = claudeArgs({
491
+ place: rec.place,
492
+ model: rec.model ?? this.d.cfg.model,
493
+ rulesFile: join(rec.place.brief, "REGLAS.md"),
494
+ settings: sessionSettings(rec.place, undefined, this.d.cfg.protectPaths),
495
+ prompt,
496
+ ...(resume && rec.sessionId ? { resumeSessionId: rec.sessionId } : {}),
497
+ });
498
+ let buf = "";
499
+ let lastFlush = this.now();
500
+ const pushLog = (force = false) => {
501
+ if (buf && (force || this.now() - lastFlush >= LOG_FLUSH_MS)) {
502
+ this.event(rec, "log", { text: buf });
503
+ buf = "";
504
+ lastFlush = this.now();
505
+ }
506
+ };
507
+ const claimTimer = setInterval(() => {
508
+ this.d.api.claim(rec.taskId).catch(() => undefined);
509
+ rec.lastClaimAt = this.now();
510
+ }, CLAIM_REFRESH_MS);
511
+ const ctl = new AbortController();
512
+ this.live = { runId: rec.runId, ctl };
513
+ let result;
514
+ try {
515
+ result = await this.d.claude(args, rec.place.cwd, (id) => {
516
+ if (id !== rec.sessionId) {
517
+ rec.sessionId = id;
518
+ this.event(rec, "session", { session_id: id });
519
+ }
520
+ }, (line) => {
521
+ buf += line + "\n";
522
+ pushLog();
523
+ }, ctl.signal, (rec.maxRunMinutes ?? this.d.cfg.maxRunMinutes) * 60_000);
524
+ }
525
+ finally {
526
+ clearInterval(claimTimer);
527
+ pushLog(true);
528
+ this.live = null;
529
+ }
530
+ if (ctl.signal.aborted) {
531
+ await this.afterAbort(rec, ctl.signal.reason);
532
+ return;
533
+ }
534
+ await this.afterSession(rec, result);
535
+ }
536
+ /**
537
+ * The runner killed the session on purpose: a stop finishes the run as
538
+ * cancelled; a pause (or a revoked key) keeps the session id so the SAME
539
+ * session continues on resume. Never a failure, never a retry question.
540
+ */
541
+ async afterAbort(rec, reason) {
542
+ if (reason === "cancelled") {
543
+ await this.finishCancelled(rec);
544
+ return;
545
+ }
546
+ rec.phase = "paused";
547
+ this.log(`${rec.code}: session stopped (${reason}); session ${rec.sessionId ?? "none"} kept for resume`);
548
+ }
549
+ async afterSession(rec, r) {
550
+ // This session's usage rides on the event that closes it (BEA-87).
551
+ const usage = sessionUsage(r, this.d.cfg.billing === "metered" ? "metered" : "subscription");
552
+ const withUsage = (data) => (usage ? { ...data, usage } : data);
553
+ if (r.isError) {
554
+ const kind = classifyError(r);
555
+ const msg = r.errorText.slice(0, 1500);
556
+ if (kind === "transient") {
557
+ const wait = retryDelaySeconds(r.errorText, rec.attemptNo);
558
+ this.event(rec, "finish", withUsage({
559
+ outcome: "failed",
560
+ error_kind: "transient",
561
+ error_message: msg,
562
+ retry_in_seconds: wait,
563
+ }));
564
+ rec.phase = "retry";
565
+ rec.retryAt = this.now() + wait * 1000;
566
+ this.log(`${rec.code}: passing failure, retry in ${wait}s`);
567
+ return;
568
+ }
569
+ this.event(rec, "finish", withUsage({ outcome: "failed", error_kind: "task", error_message: msg }));
570
+ await this.flushRun(rec);
571
+ const q = await this.d.api.createQuestion(rec.runId, {
572
+ kind: "request_confirmation",
573
+ title: `${rec.code}: the run failed. Try again?`,
574
+ payload: {
575
+ prompt: `The run stopped with an error:\n${msg}\n\nAccept = try again. Request changes = tell the agent what to do differently.`,
576
+ },
577
+ idempotency_key: `retry-${rec.attemptNo}`,
578
+ });
579
+ rec.phase = "waiting";
580
+ rec.waitFor = {
581
+ type: "question",
582
+ id: q.question.id,
583
+ kind: "request_confirmation",
584
+ payload: { prompt: "retry" },
585
+ retryOnAccept: true,
586
+ };
587
+ await this.tellTask(rec, "paused_needs_input", `Local AI (runner Bridge): la corrida falló y te pregunta en Bridge si reintenta.\n\n${msg.slice(0, 500)}`);
588
+ return;
589
+ }
590
+ const reply = parseAgentReply(r.finalText);
591
+ if (reply.kind === "done") {
592
+ const publish = rec.place.mode === "git" && rec.place.pushPr;
593
+ if (publish) {
594
+ const d = decideAction("open_pr", await this.policy());
595
+ if (d === "ask") {
596
+ await this.askToPublish(rec, reply.summary, usage);
597
+ return;
598
+ }
599
+ if (d === "refuse") {
600
+ await this.finishDone(rec, `${reply.summary}\n\nNo abri el PR: tus reglas de Bridge no lo permiten. Los commits quedan en la rama ${rec.place.branch}.`, false, usage);
601
+ return;
602
+ }
603
+ }
604
+ await this.finishDone(rec, reply.summary, publish, usage);
605
+ return;
606
+ }
607
+ await this.flushRun(rec);
608
+ if (reply.kind === "question") {
609
+ const q = await this.d.api.createQuestion(rec.runId, {
610
+ kind: reply.questionKind,
611
+ title: reply.title,
612
+ payload: reply.payload,
613
+ idempotency_key: `q-${rec.attemptNo}-${rec.replies + 1}`,
614
+ });
615
+ rec.phase = "waiting";
616
+ rec.waitFor = {
617
+ type: "question",
618
+ id: q.question.id,
619
+ kind: reply.questionKind,
620
+ payload: reply.payload,
621
+ retryOnAccept: false,
622
+ };
623
+ this.event(rec, "summary", withUsage({ text: `Waiting for the user: ${reply.title}` }));
624
+ await this.tellTask(rec, "paused_needs_input", `Local AI (runner Bridge) te pregunta en Bridge: ${reply.title}`);
625
+ return;
626
+ }
627
+ const decision = decideAction(reply.actionKind, await this.policy());
628
+ if (decision !== "ask") {
629
+ // The workspace's rules decide without asking anyone (BEA-87).
630
+ const text = decision === "free"
631
+ ? `Las reglas del usuario en Bridge dejan hacer esto sin pedir permiso: ${reply.summary}. Hazlo, solo esa accion exacta, con el mismo contenido.`
632
+ : `Esta accion esta prohibida por las reglas del usuario en Bridge: ${reply.summary}. No la hagas. Explica que falta y termina.`;
633
+ rec.resumeWith = this.writeAnswer(rec, text);
634
+ rec.phase = "waiting";
635
+ this.event(rec, "summary", withUsage({
636
+ text: `${decision === "free" ? "Allowed without asking" : "Refused, forbidden"}: ${reply.summary}`.slice(0, 3900),
637
+ }));
638
+ this.log(`${rec.code}: ${reply.actionKind} is ${decision} by the workspace rules`);
639
+ return;
640
+ }
641
+ const digest = sha256Hex(reply.content);
642
+ const a = await this.d.api.createApproval(rec.runId, {
643
+ action_kind: reply.actionKind,
644
+ action_target: reply.actionTarget,
645
+ action_digest: digest,
646
+ summary: reply.summary,
647
+ idempotency_key: `a-${rec.attemptNo}-${digest.slice(0, 16)}`,
648
+ });
649
+ rec.phase = "waiting";
650
+ rec.waitFor = { type: "approval", id: a.approval.id, digest, summary: reply.summary };
651
+ this.event(rec, "summary", withUsage({ text: `Waiting for approval: ${reply.summary}`.slice(0, 3900) }));
652
+ await this.tellTask(rec, "paused_needs_input", `Local AI (runner Bridge) pide permiso en Bridge: ${reply.summary}`);
653
+ }
654
+ /** The agent's setup in Bridge; null when not set up or the server cannot say. */
655
+ async agentSetup() {
656
+ if (!this.state.runnerId)
657
+ return null;
658
+ try {
659
+ return (await this.d.api.agentConfig(this.state.runnerId, this.d.cfg.agentName)).agent;
660
+ }
661
+ catch (err) {
662
+ this.log(`agent setup not available, using the runner defaults (${err.message})`);
663
+ return null;
664
+ }
665
+ }
666
+ /** The workspace's approval rules; null (= ask for everything) when unknown. */
667
+ async policy() {
668
+ if (!this.state.runnerId)
669
+ return null;
670
+ try {
671
+ return (await this.d.api.runnerSettings(this.state.runnerId)).policy;
672
+ }
673
+ catch (err) {
674
+ this.log(`rules not available, asking for every action (${err.message})`);
675
+ return null;
676
+ }
677
+ }
678
+ /** Done: open the PR when asked to, then finish the run and tell the task. */
679
+ async finishDone(rec, result, publish, usage) {
680
+ let summary = result;
681
+ if (publish) {
682
+ try {
683
+ const pub = this.d.workspace.publish(rec.place, `${rec.code}: ${rec.title}`.slice(0, 250), `${result}\n\nBeatOS ${rec.code}. Opened by the BeatOS Bridge runner.`);
684
+ if (pub.pr)
685
+ summary += `\n\nPR: ${pub.pr}`;
686
+ else if (pub.pushed)
687
+ summary += `\n\nRama subida: ${rec.place.branch}`;
688
+ }
689
+ catch (err) {
690
+ summary += `\n\n(No pude subir la rama: ${err.message.slice(0, 200)})`;
691
+ }
692
+ }
693
+ this.event(rec, "finish", {
694
+ outcome: "succeeded",
695
+ summary: summary.slice(0, 3900),
696
+ ...(usage ? { usage } : {}),
697
+ });
698
+ rec.phase = "done";
699
+ await this.tellTask(rec, "completed_by_ai", `Local AI (runner Bridge): RESULTADO\n\n${summary}`);
700
+ }
701
+ /** The workspace says a PR needs a yes: ask, the runner opens it once approved. */
702
+ async askToPublish(rec, result, usage) {
703
+ await this.flushRun(rec);
704
+ const branch = rec.place.branch;
705
+ const digest = sha256Hex(`open_pr ${branch} into ${rec.place.base || "main"}`);
706
+ const summary = `Open a PR from ${branch}: ${rec.code} ${rec.title}`.slice(0, 1900);
707
+ const a = await this.d.api.createApproval(rec.runId, {
708
+ action_kind: "open_pr",
709
+ action_target: branch,
710
+ action_digest: digest,
711
+ summary,
712
+ idempotency_key: `pr-${rec.attemptNo}-${digest.slice(0, 16)}`,
713
+ });
714
+ rec.phase = "waiting";
715
+ rec.waitFor = { type: "approval", id: a.approval.id, digest, summary, then: "publish", result };
716
+ this.event(rec, "summary", {
717
+ text: `Waiting for approval: open a PR from ${branch}`.slice(0, 3900),
718
+ ...(usage ? { usage } : {}),
719
+ });
720
+ await this.tellTask(rec, "paused_needs_input", `Local AI (runner Bridge) termino y pide permiso en Bridge para abrir el PR de ${branch}.`);
721
+ }
722
+ async flushRun(rec) {
723
+ try {
724
+ await this.outbox(rec.runId).flush(this.d.api.sender(rec.runId, rec.attemptNo, rec.leaseEpoch));
725
+ }
726
+ catch (err) {
727
+ this.log(`${rec.code}: flush before question failed (${err.message})`);
728
+ }
729
+ }
730
+ async tellTask(rec, status, text) {
731
+ rec.taskNotes = [...(rec.taskNotes ?? []), { status, text }];
732
+ this.save();
733
+ await this.deliverTaskNotes(rec);
734
+ }
735
+ /** Deliver queued task notes in order; stop at the first failure and keep the rest. */
736
+ async deliverTaskNotes(rec) {
737
+ while (rec.taskNotes && rec.taskNotes.length > 0) {
738
+ const note = rec.taskNotes[0];
739
+ try {
740
+ await this.d.api.updateTask(rec.taskId, { delegation_status: note.status });
741
+ await this.d.api.comment(rec.taskId, note.text);
742
+ }
743
+ catch (err) {
744
+ this.log(`${rec.code}: could not update the BeatOS task, will retry (${err.message})`);
745
+ return;
746
+ }
747
+ rec.taskNotes.shift();
748
+ this.save();
749
+ }
750
+ }
751
+ }
752
+ /** Real Claude executor (spawns the CLI). */
753
+ export function makeClaudeExec(cfg, run) {
754
+ return (args, cwd, onSession, onLog, signal, timeoutMs) => run({
755
+ claudePath: cfg.claudePath,
756
+ args,
757
+ cwd,
758
+ env: agentEnv(),
759
+ timeoutMs: timeoutMs ?? cfg.maxRunMinutes * 60_000,
760
+ signal,
761
+ }, { onSession, onLog });
762
+ }