@mlola/browser-core 0.2.11 → 0.5.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.
@@ -9,12 +9,13 @@ import { checkAnswer } from "./answer.js";
9
9
  * The loop is deliberately boring: every step is observable, every effect is
10
10
  * verified, and no model has direct browser authority.
11
11
  */
12
- import { DEFAULT_BROWSER_CONFIG, DEFAULT_POLICY, RuntimeError, actionSignature, addFact, addFailedAttempt, asRuntimeError, createMemory, describeAction, failureRecord, isSecretNode, looksSecretField, newRunId, newSessionId, newStepId, } from "@mlola/browser-protocol";
12
+ import { DEFAULT_BROWSER_CONFIG, DEFAULT_POLICY, RuntimeError, actionSignature, addFact, addFailedAttempt, asRuntimeError, createMemory, describeAction, failureRecord, isSecretNode, looksSecretField, newRunId, newSessionId, newStepId, outcomeOf, } from "@mlola/browser-protocol";
13
13
  import { ApprovalBroker, PolicyEngine, assessRisk, isSafeNavigationUrl, mergePolicy, quarantineCandidates, } from "@mlola/browser-policy";
14
14
  import { ArtifactRegistry } from "@mlola/browser-artifacts";
15
15
  import { HumanHelpBroker, UnavailableHumanHelpHost } from "@mlola/browser-takeover";
16
16
  import { EventLog, ensureRunDirs, resolveHome, writeRunMeta, writeRunSummary, } from "@mlola/browser-trace";
17
17
  import { LoopDetector, nextStrategy } from "@mlola/browser-recovery";
18
+ import { DeadlineExceededError, withDeadline } from "@mlola/browser-backend";
18
19
  import { buildActionSpace, spaceSummary } from "./action-space.js";
19
20
  import { validateDecision } from "./decision-validation.js";
20
21
  import { BudgetManager } from "./budget.js";
@@ -24,6 +25,28 @@ import { inferDocumentTypeHint, verifyCompletion } from "./verifier.js";
24
25
  import { looksComplex, summarizeSnapshot } from "./state.js";
25
26
  import { packageVersion } from "./version.js";
26
27
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
28
+ /** Orchestrator-level observation retries, on top of the backend's own. */
29
+ const OBSERVE_ATTEMPTS = 3;
30
+ const OBSERVE_RETRY_MS = 400;
31
+ /** Slack over the backend's observation deadline before the runtime gives up on it. */
32
+ const OBSERVE_DEADLINE_SLACK_MS = 5000;
33
+ /**
34
+ * The duration budget is checked between steps; the watchdog is the backstop
35
+ * for a step that never returns. The grace (a quarter of the budget, capped)
36
+ * lets a step that is merely slow finish and be recorded normally.
37
+ */
38
+ const WATCHDOG_GRACE_MS = 15_000;
39
+ const watchdogGrace = (budgetMs) => Math.min(WATCHDOG_GRACE_MS, Math.max(250, Math.round(budgetMs / 4)));
40
+ const SESSION_START_DEADLINE_MS = 60_000;
41
+ const MAX_TIMER_MS = 2 ** 31 - 1;
42
+ const SESSION_START_LABEL = "browser session start";
43
+ const SESSION_STOP_DEADLINE_MS = 30_000;
44
+ /** A failure screenshot is evidence, not a reason to keep a finished run waiting. */
45
+ const SCREENSHOT_DEADLINE_MS = 5000;
46
+ /** Labels that close an overlay without agreeing to anything. */
47
+ const DISMISSIVE_LABEL = /^\s*(?:×|✕|x)\s*$|\b(close|dismiss|no thanks|not now|maybe later|skip|reject all|decline|tutup|nanti saja|lewati|tolak)\b/i;
48
+ /** Labels that accept something; recovery uses them only on a cookie banner. */
49
+ const AFFIRMATIVE_LABEL = /\b(accept|allow|agree|ok|got it|terima|setuju|izinkan)\b/i;
27
50
  export class TaskOrchestrator {
28
51
  #opts;
29
52
  #backend;
@@ -61,23 +84,38 @@ export class TaskOrchestrator {
61
84
  #fallbackAttempts = 0;
62
85
  #stepNumber = 0;
63
86
  #screenshotPolicy;
87
+ #observeTimeoutMs = DEFAULT_BROWSER_CONFIG.observeTimeoutMs ?? 10_000;
88
+ #started = false;
89
+ #sessionStart;
90
+ /**
91
+ * Set once by cancel() or the watchdog. The run resolves immediately; work
92
+ * still in flight (a decision request, a human wait, a wedged page call) is
93
+ * abandoned and cannot act on the browser afterwards (#assertLive).
94
+ */
95
+ #interrupted;
96
+ #onInterrupt;
97
+ #interruptedOutcome;
98
+ #interruption = new Promise((resolve) => {
99
+ this.#onInterrupt = resolve;
100
+ });
64
101
  constructor(opts) {
65
102
  this.#opts = opts;
66
103
  this.#backend = opts.backend;
67
104
  this.#screenshotPolicy = opts.screenshot ?? "off";
68
105
  this.#policy = new PolicyEngine(mergePolicy(DEFAULT_POLICY, opts.policy));
69
106
  this.#humanAvailable = opts.humanHelp !== undefined;
70
- this.#approvals =
71
- opts.approvals ??
72
- new ApprovalBroker({
73
- onRequest: (request) => this.#events?.emit("APPROVAL_REQUESTED", {
74
- approvalId: request.id,
75
- summary: request.summary,
76
- risk: request.risk,
77
- url: request.url,
78
- }),
79
- onResolved: (request, resolution) => this.#events?.emit("APPROVAL_RESOLVED", { approvalId: request.id, resolution }),
80
- });
107
+ this.#approvals = opts.approvals ?? new ApprovalBroker();
108
+ // Attached to host-supplied brokers too: an approval nobody can see is an
109
+ // approval that silently times out as "denied".
110
+ this.#approvals.listen({
111
+ onRequest: (request) => this.#events?.emit("APPROVAL_REQUESTED", {
112
+ approvalId: request.id,
113
+ summary: request.summary,
114
+ risk: request.risk,
115
+ url: request.url,
116
+ }),
117
+ onResolved: (request, resolution) => this.#events?.emit("APPROVAL_RESOLVED", { approvalId: request.id, resolution }),
118
+ });
81
119
  }
82
120
  get status() {
83
121
  return this.#status;
@@ -105,9 +143,29 @@ export class TaskOrchestrator {
105
143
  }
106
144
  cancel(reason = "cancelled by user") {
107
145
  this.#cancelled = reason;
146
+ this.#interrupt({ status: "cancelled", code: "CANCELLED", reason });
147
+ }
148
+ #interrupt(interruption) {
149
+ if (this.#interrupted)
150
+ return;
151
+ this.#interrupted = interruption;
152
+ // Release anything the run is waiting on, so nothing keeps a person, an
153
+ // approval or a daemon client hanging on a run that is already over.
154
+ this.#human?.cancelAll();
155
+ this.#approvals.cancelAll("denied");
156
+ this.#onInterrupt?.(interruption);
157
+ }
158
+ /** Abandoned work stops at the next boundary instead of touching the browser. */
159
+ #assertLive() {
160
+ if (this.#interrupted)
161
+ throw new RuntimeError("CANCELLED", this.#interrupted.reason, { retryable: false });
108
162
  }
109
163
  /* ─────────────────────────────── main run ─────────────────────────────── */
110
164
  async run(task) {
165
+ // Run state (memory, history, help keys, loop detector) is per task.
166
+ if (this.#started)
167
+ throw new Error("a TaskOrchestrator runs one task; create a new one per run");
168
+ this.#started = true;
111
169
  const startedAt = Date.now();
112
170
  const runId = newRunId();
113
171
  const sessionId = newSessionId();
@@ -118,6 +176,7 @@ export class TaskOrchestrator {
118
176
  const paths = ensureRunDirs(runId, home);
119
177
  this.#paths = paths;
120
178
  const browser = { ...DEFAULT_BROWSER_CONFIG, ...(task.browser ?? {}) };
179
+ this.#observeTimeoutMs = browser.observeTimeoutMs ?? this.#observeTimeoutMs;
121
180
  if (task.screenshot)
122
181
  this.#screenshotPolicy = task.screenshot;
123
182
  this.#events = new EventLog({
@@ -158,46 +217,115 @@ export class TaskOrchestrator {
158
217
  backend: browser.backend,
159
218
  startedAt,
160
219
  version: packageVersion(),
220
+ pid: process.pid,
161
221
  }, home);
162
222
  this.#events.emit("RUN_CREATED", {
163
223
  goal: task.goal,
164
224
  ...(task.startUrl !== undefined ? { startUrl: task.startUrl } : {}),
165
225
  backend: browser.backend,
166
226
  });
227
+ const budget = this.#budget;
228
+ const watchdogMs = budget.budgets.maxDurationMs + watchdogGrace(budget.budgets.maxDurationMs);
229
+ // setTimeout fires at once beyond 2^31-1 ms; a budget that long is "no
230
+ // deadline", so no watchdog is armed rather than one that fires immediately.
231
+ const watchdog = watchdogMs <= MAX_TIMER_MS
232
+ ? setTimeout(() => {
233
+ this.#interrupt({
234
+ status: "failed",
235
+ code: "BUDGET_EXHAUSTED",
236
+ reason: `duration budget exhausted (hard deadline ${Math.round(watchdogMs / 1000)}s; a step did not return)`,
237
+ });
238
+ }, watchdogMs)
239
+ : undefined;
240
+ watchdog?.unref?.();
241
+ // A cancel that arrived before run() started still wins.
242
+ if (this.#cancelled)
243
+ this.#interrupt({ status: "cancelled", code: "CANCELLED", reason: this.#cancelled });
244
+ // Cancelled before it started: no browser is launched only to be closed again.
245
+ const work = this.#interrupted
246
+ ? Promise.resolve(this.#interruptedResult(this.#interrupted, startedAt))
247
+ : this.#work(task, startedAt, browser, paths);
248
+ const interrupted = this.#interruption.then((interruption) => this.#interruptedResult(interruption, startedAt));
249
+ let result;
250
+ try {
251
+ result = await Promise.race([work, interrupted]);
252
+ }
253
+ finally {
254
+ clearTimeout(watchdog);
255
+ // The losing side may still settle later; it must not surface as an
256
+ // unhandled rejection or overwrite the result.
257
+ void work.catch(() => undefined);
258
+ result = await this.#cleanup(result);
259
+ }
260
+ writeRunSummary(runId, result, home);
261
+ return result;
262
+ }
263
+ #interruptedResult(interruption, startedAt) {
264
+ // Both sides of the race can reach this; the outcome is recorded once.
265
+ if (this.#interruptedOutcome)
266
+ return this.#interruptedOutcome;
267
+ const events = this.#events;
268
+ try {
269
+ if (interruption.status === "cancelled") {
270
+ events?.emit("RUN_CANCELLED", { reason: interruption.reason });
271
+ }
272
+ else {
273
+ events?.emit("BUDGET_EXHAUSTED", { reason: interruption.reason });
274
+ events?.emit("RUN_FAILED", {
275
+ failure: failureRecord(new RuntimeError(interruption.code, interruption.reason, { retryable: false })),
276
+ status: this.#status,
277
+ });
278
+ }
279
+ }
280
+ catch {
281
+ /* the log may already be closed; the result below still records the outcome */
282
+ }
283
+ this.#status = interruption.status;
284
+ this.#interruptedOutcome = this.#buildResult(interruption.status, interruption.reason, startedAt);
285
+ return this.#interruptedOutcome;
286
+ }
287
+ async #work(task, startedAt, browser, paths) {
288
+ const runId = this.#runId;
289
+ const sessionId = this.#sessionId;
290
+ const events = this.#requireEvents();
167
291
  let result;
168
292
  try {
169
- this.#session = await this.#backend.startSession({
293
+ this.#sessionStart = withDeadline(this.#backend.startSession({
170
294
  runId,
171
295
  sessionId,
172
296
  browser,
173
297
  artifactsDir: paths.artifactsDir,
174
298
  screenshotsDir: paths.screenshotsDir,
175
- });
299
+ }), SESSION_START_DEADLINE_MS, SESSION_START_LABEL);
300
+ this.#session = await this.#sessionStart;
301
+ this.#assertLive();
176
302
  this.#executor = new Executor({
177
303
  backend: this.#backend,
178
- events: this.#events,
179
- artifacts: this.#artifacts,
304
+ events,
305
+ artifacts: this.#requireArtifacts(),
180
306
  sessionId,
181
307
  runId,
182
308
  });
183
- this.#events.emit("SESSION_CREATED", { sessionId, backend: this.#session.backend });
184
- this.#events.emit("SESSION_CONNECTED", {
309
+ events.emit("SESSION_CREATED", { sessionId, backend: this.#session.backend });
310
+ events.emit("SESSION_CONNECTED", {
185
311
  sessionId,
186
312
  ...(this.#session.agentWindowId !== undefined ? { agentWindowId: this.#session.agentWindowId } : {}),
187
313
  });
188
- this.#events.emit("RUN_STARTED", { runId });
314
+ events.emit("RUN_STARTED", { runId });
189
315
  this.#status = "running";
190
316
  result = await this.#mainLoop(task, startedAt);
191
317
  }
192
318
  catch (err) {
193
- const runtimeError = asRuntimeError(err);
194
- this.#events.emit("RUN_FAILED", { failure: failureRecord(runtimeError), status: this.#status });
319
+ if (this.#interrupted)
320
+ return this.#interruptedResult(this.#interrupted, startedAt);
321
+ const runtimeError = err instanceof DeadlineExceededError && err.label === SESSION_START_LABEL
322
+ ? new RuntimeError("BROWSER_CRASHED", `${err.message}; the browser did not start`, { cause: err, retryable: false })
323
+ : err instanceof DeadlineExceededError
324
+ ? new RuntimeError("PAGE_UNRESPONSIVE", err.message, { cause: err, retryable: false })
325
+ : asRuntimeError(err);
326
+ events.emit("RUN_FAILED", { failure: failureRecord(runtimeError), status: this.#status });
195
327
  result = this.#buildResult("failed", runtimeError.message, startedAt);
196
328
  }
197
- finally {
198
- result = await this.#cleanup(result);
199
- }
200
- writeRunSummary(runId, result, home);
201
329
  return result;
202
330
  }
203
331
  /* ────────────────────────────── main loop ─────────────────────────────── */
@@ -234,15 +362,9 @@ export class TaskOrchestrator {
234
362
  await this.#plan(task, "initial", snapshot);
235
363
  }
236
364
  while (true) {
237
- if (this.#cancelled) {
238
- events.emit("RUN_CANCELLED", { reason: this.#cancelled });
239
- return this.#buildResult("cancelled", this.#cancelled, startedAt);
240
- }
365
+ this.#assertLive();
241
366
  await this.#waitIfPaused();
242
- if (this.#cancelled) {
243
- events.emit("RUN_CANCELLED", { reason: this.#cancelled });
244
- return this.#buildResult("cancelled", this.#cancelled, startedAt);
245
- }
367
+ this.#assertLive();
246
368
  for (const warning of budget.warnings()) {
247
369
  events.emit("BUDGET_WARNING", { reason: warning.reason, snapshot: numericSnapshot(budget) });
248
370
  }
@@ -290,6 +412,7 @@ export class TaskOrchestrator {
290
412
  toolsAllowed: typeof this.#backend.callTool === "function",
291
413
  goal: task.goal,
292
414
  escalation: this.#opts.providers.fallbackDecision !== undefined,
415
+ answering: this.#opts.providers.decision.answers !== false || this.#opts.providers.fallbackDecision !== undefined,
293
416
  });
294
417
  const { space } = quarantineCandidates(baseSpace);
295
418
  events.emit("ACTION_SPACE_BUILT", spaceSummary(space));
@@ -302,6 +425,7 @@ export class TaskOrchestrator {
302
425
  const runtimeError = asRuntimeError(err);
303
426
  return this.#recover(task, runtimeError, snapshot, stepId);
304
427
  }
428
+ this.#assertLive();
305
429
  // 3. The fast path can ask a stronger model for the decision. The escalated
306
430
  // answer is validated against the same action space, so it has no extra
307
431
  // authority.
@@ -346,13 +470,23 @@ export class TaskOrchestrator {
346
470
  const boundary = stopBeforeMatch(task.stopBefore, action, snapshot);
347
471
  if (boundary) {
348
472
  events.emit("NOTE", { text: `stop boundary reached: ${boundary}`, level: "info" });
473
+ // Reaching the boundary is not evidence that the work before it was done;
474
+ // the same oracle as DONE decides what the run proves.
475
+ const verification = verifyCompletion(task, {
476
+ snapshot,
477
+ artifacts: this.#artifacts?.summaries() ?? [],
478
+ events: events.events,
479
+ });
480
+ events.emit("VERIFICATION_RESULT", { verification });
349
481
  return {
350
482
  kind: "complete",
351
483
  detail: `stopped at the requested boundary (${boundary})`,
484
+ verification,
352
485
  pendingSnapshot: snapshot,
353
486
  };
354
487
  }
355
488
  // 7. Execute + verify.
489
+ this.#assertLive();
356
490
  const decided = { action, decision, snapshotId: snapshot.snapshotId, stepId };
357
491
  const result = await executor.execute(decided, snapshot);
358
492
  const signature = actionSignature(action);
@@ -432,6 +566,7 @@ export class TaskOrchestrator {
432
566
  step: this.#stepNumber,
433
567
  goal: task.goal,
434
568
  ...(subgoal ? { subgoal: subgoal.description } : {}),
569
+ ...(task.inputs ? { inputFields: Object.keys(task.inputs) } : {}),
435
570
  snapshot,
436
571
  actionSpace: space,
437
572
  memory: this.#memory,
@@ -577,6 +712,7 @@ export class TaskOrchestrator {
577
712
  literals: [],
578
713
  }, {
579
714
  ...(this.#opts.providers.text ? { provider: this.#opts.providers.text } : {}),
715
+ ...(task.inputs ? { inputs: task.inputs } : {}),
580
716
  maxLength: this.#policy.config.maxTypedLength,
581
717
  });
582
718
  if (resolved.source === "model") {
@@ -818,6 +954,7 @@ export class TaskOrchestrator {
818
954
  detail: "the same help was requested twice; stopping instead of asking again",
819
955
  });
820
956
  }
957
+ this.#assertLive();
821
958
  this.#helpAsked.set(key, 1);
822
959
  budget.humanHelp();
823
960
  this.#status = "human_control";
@@ -1007,6 +1144,7 @@ export class TaskOrchestrator {
1007
1144
  }
1008
1145
  async #applyRecoveryStrategy(task, strategy, snapshot, stepId) {
1009
1146
  const events = this.#requireEvents();
1147
+ this.#assertLive();
1010
1148
  switch (strategy.kind) {
1011
1149
  case "reobserve":
1012
1150
  case "retry_action":
@@ -1016,7 +1154,7 @@ export class TaskOrchestrator {
1016
1154
  return { kind: "no_effect", pendingSnapshot: await this.#observe(), detail: strategy.reason };
1017
1155
  case "scroll_into_view":
1018
1156
  case "dismiss_overlay": {
1019
- const target = this.#findOverlayDismiss(snapshot);
1157
+ const target = this.#findOverlayDismiss(snapshot, stepId);
1020
1158
  if (target) {
1021
1159
  const action = {
1022
1160
  op: "CLICK",
@@ -1075,12 +1213,43 @@ export class TaskOrchestrator {
1075
1213
  return { kind: "fatal", failure: new RuntimeError("INTERNAL", "unknown recovery strategy") };
1076
1214
  }
1077
1215
  }
1078
- #findOverlayDismiss(snapshot) {
1216
+ /**
1217
+ * The control recovery may click to clear an overlay, without a model
1218
+ * decision. Recovery acts on its own authority, so it is held to a narrower
1219
+ * rule than a decided click: dismissive controls (close, not now, …) are
1220
+ * preferred; affirmative ones (OK, agree, allow, …) only clear a cookie
1221
+ * banner, because on a confirm dialog or a permission prompt "OK" is the
1222
+ * very action that needed approval. The chosen click must also be one the
1223
+ * policy allows outright; anything that would need approval is left to the
1224
+ * decision loop, where approval happens.
1225
+ */
1226
+ #findOverlayDismiss(snapshot, stepId) {
1079
1227
  const blocking = snapshot.blockingUi;
1080
- return snapshot.nodes.find((n) => n.operations.includes("CLICK") &&
1081
- n.flags.visible &&
1082
- (blocking?.nodeIndexes.includes(n.index) ||
1083
- /\b(accept|allow|agree|ok|got it|close|dismiss|no thanks|not now|terima|tutup)\b/i.test(n.label)));
1228
+ const clickable = snapshot.nodes.filter((n) => n.operations.includes("CLICK") && n.flags.visible && !isSecretNode(n));
1229
+ const inBlockingUi = (n) => blocking?.nodeIndexes.includes(n.index) ?? false;
1230
+ const dismissive = clickable.filter((n) => DISMISSIVE_LABEL.test(n.label));
1231
+ const affirmative = blocking?.kind === "cookie_consent"
1232
+ ? clickable.filter((n) => inBlockingUi(n) && AFFIRMATIVE_LABEL.test(n.label))
1233
+ : [];
1234
+ const candidates = [
1235
+ ...dismissive.filter(inBlockingUi),
1236
+ ...dismissive.filter((n) => !inBlockingUi(n)),
1237
+ ...affirmative,
1238
+ ];
1239
+ const origin = originOf(snapshot.url);
1240
+ return candidates.find((n) => {
1241
+ const risk = assessRisk({ operation: "CLICK", targetLabel: n.label }).refined;
1242
+ const outcome = this.#policy.evaluate({
1243
+ runId: this.#runId,
1244
+ stepId,
1245
+ operation: "CLICK",
1246
+ risk,
1247
+ origin,
1248
+ url: snapshot.url,
1249
+ targetLabel: n.label,
1250
+ });
1251
+ return outcome.mode === "allow";
1252
+ });
1084
1253
  }
1085
1254
  /* ─────────────────────────────── planning ─────────────────────────────── */
1086
1255
  async #plan(task, reason, snapshot) {
@@ -1132,9 +1301,34 @@ export class TaskOrchestrator {
1132
1301
  }
1133
1302
  }
1134
1303
  /* ─────────────────────────────── helpers ──────────────────────────────── */
1304
+ /**
1305
+ * Observation with bounded retries. A page that is mid-navigation or briefly
1306
+ * busy is normal on real sites; one failed read must not end the run. What is
1307
+ * not retryable (a crashed browser) fails at once with its own reason.
1308
+ */
1135
1309
  async #observe() {
1310
+ for (let attempt = 1;; attempt += 1) {
1311
+ this.#assertLive();
1312
+ try {
1313
+ return await this.#observeOnce();
1314
+ }
1315
+ catch (err) {
1316
+ const failure = err instanceof DeadlineExceededError
1317
+ ? new RuntimeError("PAGE_UNRESPONSIVE", err.message, { cause: err })
1318
+ : asRuntimeError(err);
1319
+ if (!failure.retryable || attempt >= OBSERVE_ATTEMPTS || this.#interrupted)
1320
+ throw failure;
1321
+ this.#events?.emit("NOTE", {
1322
+ text: `observation failed (${failure.code}: ${failure.message}); retrying (${attempt}/${OBSERVE_ATTEMPTS - 1})`,
1323
+ level: "warn",
1324
+ });
1325
+ await sleep(OBSERVE_RETRY_MS * attempt);
1326
+ }
1327
+ }
1328
+ }
1329
+ async #observeOnce() {
1136
1330
  const started = Date.now();
1137
- const snapshot = await this.#backend.observe(this.#sessionId);
1331
+ const snapshot = await withDeadline(this.#backend.observe(this.#sessionId), this.#observeTimeoutMs + Math.min(OBSERVE_DEADLINE_SLACK_MS, this.#observeTimeoutMs), "observation");
1138
1332
  this.#events?.emit("SNAPSHOT_CAPTURED", {
1139
1333
  snapshotId: snapshot.snapshotId,
1140
1334
  generation: snapshot.generation,
@@ -1163,7 +1357,7 @@ export class TaskOrchestrator {
1163
1357
  return snapshot;
1164
1358
  }
1165
1359
  async #waitIfPaused() {
1166
- while (this.#paused && !this.#cancelled)
1360
+ while (this.#paused && !this.#interrupted)
1167
1361
  await sleep(200);
1168
1362
  }
1169
1363
  #currentSubgoal() {
@@ -1190,12 +1384,20 @@ export class TaskOrchestrator {
1190
1384
  }
1191
1385
  async #cleanup(result) {
1192
1386
  const events = this.#events;
1387
+ if (!this.#session && this.#sessionStart) {
1388
+ // Interrupted while the browser was still starting: wait for it so it can
1389
+ // be stopped, rather than leaving an orphaned browser behind.
1390
+ this.#session = await this.#sessionStart.catch(() => undefined);
1391
+ }
1193
1392
  try {
1194
1393
  if (this.#session) {
1195
- if (this.#screenshotPolicy === "always" ||
1196
- (this.#screenshotPolicy === "on-failure" && result.status !== "completed")) {
1394
+ // A cancelled run is stopped on request: the person wants it gone, not documented.
1395
+ if (result.status !== "cancelled" &&
1396
+ (this.#screenshotPolicy === "always" ||
1397
+ (this.#screenshotPolicy === "on-failure" && result.status !== "completed"))) {
1197
1398
  try {
1198
- const shot = await this.#backend.screenshot?.(this.#sessionId, `${result.status}-${result.reason}`);
1399
+ const capture = this.#backend.screenshot?.(this.#sessionId, `${result.status}-${result.reason}`);
1400
+ const shot = capture ? await withDeadline(capture, SCREENSHOT_DEADLINE_MS, "screenshot") : undefined;
1199
1401
  if (shot) {
1200
1402
  events?.emit("SCREENSHOT_CAPTURED", {
1201
1403
  path: shot.path,
@@ -1209,7 +1411,7 @@ export class TaskOrchestrator {
1209
1411
  }
1210
1412
  }
1211
1413
  events?.emit("SESSION_STOPPING", { reason: result.reason });
1212
- const report = await this.#backend.stopSession(this.#sessionId);
1414
+ const report = await withDeadline(this.#backend.stopSession(this.#sessionId), SESSION_STOP_DEADLINE_MS, "session stop");
1213
1415
  events?.emit("SESSION_STOPPED", {
1214
1416
  cleanup: {
1215
1417
  closedTabs: report.closedTabs,
@@ -1232,14 +1434,18 @@ export class TaskOrchestrator {
1232
1434
  }
1233
1435
  #buildResult(status, reason, startedAt, verification) {
1234
1436
  const budget = this.#budget;
1437
+ // A completed run carries the verification of the step that completed it,
1438
+ // never an earlier one: a DONE refuted at step 3 says nothing about a
1439
+ // boundary reached at step 9. Runs that did not complete report the last
1440
+ // verification as context for why they failed.
1441
+ const evidence = verification ?? (status === "completed" ? undefined : this.#verificationFromEvents());
1235
1442
  return {
1236
1443
  runId: this.#runId,
1237
1444
  status,
1445
+ outcome: outcomeOf(status, evidence),
1238
1446
  reason,
1239
1447
  steps: this.#stepNumber,
1240
- ...(verification ? { verification } : this.#verificationFromEvents()
1241
- ? { verification: this.#verificationFromEvents() }
1242
- : {}),
1448
+ ...(evidence ? { verification: evidence } : {}),
1243
1449
  artifacts: this.#artifacts?.summaries() ?? [],
1244
1450
  durationMs: Date.now() - startedAt,
1245
1451
  usage: {
@@ -1273,6 +1479,11 @@ export class TaskOrchestrator {
1273
1479
  throw new Error("orchestrator is not running");
1274
1480
  return this.#budget;
1275
1481
  }
1482
+ #requireArtifacts() {
1483
+ if (!this.#artifacts)
1484
+ throw new Error("orchestrator is not running");
1485
+ return this.#artifacts;
1486
+ }
1276
1487
  #requireExecutor() {
1277
1488
  if (!this.#executor)
1278
1489
  throw new Error("orchestrator is not running");