@omniralph/agent 2.0.1 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -3196,6 +3196,18 @@ var AgentHostReport = z12.object({
3196
3196
  workspace: z12.string().min(1).max(AGENT_HOST_NAME_MAX)
3197
3197
  }).nullable()
3198
3198
  });
3199
+ var TokenRefreshReport = z12.object({
3200
+ /** The first failed refresh since the last one that succeeded. */
3201
+ failingSince: z12.iso.datetime(),
3202
+ /** Failed refreshes in a row (a refresh token that couldn't be saved counts as one). */
3203
+ consecutiveFailures: z12.int().min(1),
3204
+ /** The last failure: `network`, `http_<status>`, `rate_limited` or `persist_failed`. */
3205
+ lastError: z12.string().min(1).max(64),
3206
+ /** When the agent's access token expires; null when it has none. */
3207
+ accessTokenExpiresAt: z12.iso.datetime().nullable(),
3208
+ /** The signed refresh token's `exp`; null for a legacy opaque token. */
3209
+ refreshTokenExpiresAt: z12.iso.datetime().nullable()
3210
+ });
3199
3211
  var HostToolPath = z12.string().max(4096).refine((path25) => path25.startsWith("/"), "must be an absolute path");
3200
3212
  var HOST_TOOL_SOURCES = ["configured", "discovered"];
3201
3213
  var HOST_TOOL_PROBLEMS = ["missing", "not_executable", "blocked"];
@@ -3244,7 +3256,9 @@ var Heartbeat = z12.object({
3244
3256
  /** The machine the agent runs on. Absent from older agents: the last report is kept. */
3245
3257
  host: AgentHostReport.optional(),
3246
3258
  /** The agent's machine settings in force. */
3247
- local: LocalSettingsReport
3259
+ local: LocalSettingsReport,
3260
+ /** Sent only while the agent's token refreshes are failing (absent when healthy and from older agents). */
3261
+ tokenRefresh: TokenRefreshReport.optional()
3248
3262
  });
3249
3263
  function agentWakeChannel(agentId) {
3250
3264
  return `agent:${agentId}`;
@@ -7941,7 +7955,7 @@ async function runQuery(query, request, seen) {
7941
7955
  // src/tools/activities.ts
7942
7956
  import { z as z28 } from "zod";
7943
7957
  var MAX_BODY = 1e4;
7944
- var MAX_PARAMETER = 500;
7958
+ var MAX_PARAMETER = 1e4;
7945
7959
  var SKIPPED_TOOLS = /* @__PURE__ */ new Set(["TodoWrite"]);
7946
7960
  var PARAMETER_KEYS = [
7947
7961
  "command",
@@ -8293,6 +8307,25 @@ var ReenrollmentRequiredError = class extends Error {
8293
8307
  code;
8294
8308
  name = "ReenrollmentRequiredError";
8295
8309
  };
8310
+ function refreshTokenExpiry(token) {
8311
+ const parts = token.split(".");
8312
+ if (parts.length !== 3 || !parts[1]) return null;
8313
+ try {
8314
+ const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
8315
+ if (typeof payload !== "object" || payload === null) return null;
8316
+ const exp = payload.exp;
8317
+ if (typeof exp !== "number" || !Number.isFinite(exp)) return null;
8318
+ const date = new Date(exp * 1e3);
8319
+ return Number.isNaN(date.getTime()) ? null : date;
8320
+ } catch {
8321
+ return null;
8322
+ }
8323
+ }
8324
+ function refreshErrorCode(error) {
8325
+ if (error instanceof ApiError)
8326
+ return error.status === 429 ? "rate_limited" : `http_${error.status}`;
8327
+ return "network";
8328
+ }
8296
8329
  var defaultRetryDelayMs = (failures) => Math.min(6e4, 5e3 * 2 ** (failures - 1));
8297
8330
  var TokenManager = class {
8298
8331
  constructor(options) {
@@ -8308,6 +8341,9 @@ var TokenManager = class {
8308
8341
  timer = null;
8309
8342
  inflight = null;
8310
8343
  failures = 0;
8344
+ /** The first failure since the last successful refresh (null while healthy). */
8345
+ failingSince = null;
8346
+ lastError = null;
8311
8347
  fatal = null;
8312
8348
  stopped = false;
8313
8349
  refreshAt;
@@ -8338,6 +8374,21 @@ var TokenManager = class {
8338
8374
  });
8339
8375
  return this.inflight;
8340
8376
  }
8377
+ /**
8378
+ * The current failing streak of refreshes, for the heartbeat's
8379
+ * `tokenRefresh`; null while healthy (no failure since the last success).
8380
+ */
8381
+ refreshStatus() {
8382
+ if (this.failures === 0 || !this.failingSince || !this.lastError) return null;
8383
+ const refreshExpiry = refreshTokenExpiry(this.config.refreshToken);
8384
+ return {
8385
+ failingSince: this.failingSince.toISOString(),
8386
+ consecutiveFailures: this.failures,
8387
+ lastError: this.lastError,
8388
+ accessTokenExpiresAt: this.accessToken ? new Date(this.expiresAt).toISOString() : null,
8389
+ refreshTokenExpiresAt: refreshExpiry?.toISOString() ?? null
8390
+ };
8391
+ }
8341
8392
  stop() {
8342
8393
  this.stopped = true;
8343
8394
  this.clearTimer();
@@ -8359,7 +8410,7 @@ var TokenManager = class {
8359
8410
  this.options.onFatal?.(this.fatal);
8360
8411
  throw this.fatal;
8361
8412
  }
8362
- this.failures++;
8413
+ this.recordFailure(refreshErrorCode(error));
8363
8414
  const delay = error instanceof ApiError && error.retryAfterSeconds ? error.retryAfterSeconds * 1e3 : this.retryDelayMs(this.failures);
8364
8415
  this.options.logger.warn({ err: error, retryInMs: delay }, "access token refresh failed");
8365
8416
  this.schedule(delay);
@@ -8369,7 +8420,7 @@ var TokenManager = class {
8369
8420
  try {
8370
8421
  await this.options.persist(this.config);
8371
8422
  } catch (error) {
8372
- this.failures++;
8423
+ this.recordFailure("persist_failed");
8373
8424
  const delay = this.retryDelayMs(this.failures);
8374
8425
  this.options.logger.error(
8375
8426
  { err: error, retryInMs: delay },
@@ -8379,12 +8430,19 @@ var TokenManager = class {
8379
8430
  throw error;
8380
8431
  }
8381
8432
  this.failures = 0;
8433
+ this.failingSince = null;
8434
+ this.lastError = null;
8382
8435
  this.accessToken = response.accessToken;
8383
8436
  this.expiresAt = Date.now() + response.expiresIn * 1e3;
8384
8437
  this.schedule(response.expiresIn * 1e3 * this.refreshAt);
8385
8438
  this.options.logger.debug({ expiresIn: response.expiresIn }, "access token refreshed");
8386
8439
  return response.accessToken;
8387
8440
  }
8441
+ recordFailure(code) {
8442
+ this.failures++;
8443
+ this.failingSince ??= /* @__PURE__ */ new Date();
8444
+ this.lastError = code;
8445
+ }
8388
8446
  schedule(delayMs) {
8389
8447
  this.clearTimer();
8390
8448
  if (this.stopped) return;
@@ -9197,8 +9255,196 @@ ${failed.map(
9197
9255
  ).join("\n")}`;
9198
9256
  }
9199
9257
 
9200
- // src/workspace/git.ts
9258
+ // src/lifecycle/commands.ts
9201
9259
  import { spawn as spawn2 } from "node:child_process";
9260
+ var MAX_FAILURE_DETAIL = 500;
9261
+ var KILL_GRACE_MS = 5e3;
9262
+ var SetupCommandError = class extends Error {
9263
+ constructor(commandName, detail) {
9264
+ super(`setup command ${commandName} failed: ${detail}`);
9265
+ this.commandName = commandName;
9266
+ this.detail = detail;
9267
+ this.name = "SetupCommandError";
9268
+ }
9269
+ commandName;
9270
+ detail;
9271
+ };
9272
+ function commandEnv(env) {
9273
+ return Object.fromEntries(
9274
+ Object.entries(env).filter(
9275
+ ([name]) => !name.startsWith("OMNIRALPH_") && name !== "GIT_CONFIG_COUNT" && name !== "GIT_CONFIG_PARAMETERS" && !name.startsWith("GIT_CONFIG_KEY_") && !name.startsWith("GIT_CONFIG_VALUE_")
9276
+ )
9277
+ );
9278
+ }
9279
+ function shellQuote(value) {
9280
+ return `'${value.replace(/'/g, `'\\''`)}'`;
9281
+ }
9282
+ var FIRST_WORD = /^(\s*)([^\s;&|<>()]+)/;
9283
+ function resolveCommand(command, commands = /* @__PURE__ */ new Map()) {
9284
+ const match = FIRST_WORD.exec(command);
9285
+ const resolved = match ? commands.get(match[2]) : void 0;
9286
+ if (!match || resolved === void 0) return command;
9287
+ return `${match[1]}${shellQuote(resolved)}${command.slice(match[0].length)}`;
9288
+ }
9289
+ function commandEnvFor(command, options) {
9290
+ const name = FIRST_WORD.exec(command)?.[2];
9291
+ const extra = name === void 0 ? void 0 : options.executableEnv?.get(name);
9292
+ return { ...commandEnv(options.env), ...extra };
9293
+ }
9294
+ function tail(text3, max) {
9295
+ const trimmed = text3.trim();
9296
+ return trimmed.length > max ? `\u2026${trimmed.slice(-max)}` : trimmed;
9297
+ }
9298
+ function runCommand(command, options) {
9299
+ return new Promise((resolve3) => {
9300
+ const stdoutChunks = [];
9301
+ let stdoutBytes = 0;
9302
+ let truncated = false;
9303
+ let stderr = "";
9304
+ let timedOut = false;
9305
+ let settled = false;
9306
+ let killTimer;
9307
+ const child = spawn2("sh", ["-c", command], {
9308
+ cwd: options.cwd,
9309
+ env: options.env,
9310
+ stdio: ["ignore", "pipe", "pipe"],
9311
+ detached: true
9312
+ });
9313
+ child.stderr.setEncoding("utf8");
9314
+ child.stdout.on("data", (chunk) => {
9315
+ if (truncated) return;
9316
+ const room = options.maxStdoutBytes - stdoutBytes;
9317
+ if (chunk.length > room) {
9318
+ stdoutChunks.push(chunk.subarray(0, room));
9319
+ stdoutBytes += room;
9320
+ truncated = true;
9321
+ } else {
9322
+ stdoutChunks.push(chunk);
9323
+ stdoutBytes += chunk.length;
9324
+ }
9325
+ });
9326
+ child.stderr.on("data", (chunk) => {
9327
+ stderr = (stderr + chunk).slice(-MAX_FAILURE_DETAIL * 4);
9328
+ });
9329
+ const killGroup = (sig) => {
9330
+ try {
9331
+ if (child.pid !== void 0) process.kill(-child.pid, sig);
9332
+ } catch {
9333
+ }
9334
+ };
9335
+ const stop = () => {
9336
+ killGroup("SIGTERM");
9337
+ killTimer ??= setTimeout(() => killGroup("SIGKILL"), KILL_GRACE_MS);
9338
+ killTimer.unref();
9339
+ };
9340
+ const timer = setTimeout(() => {
9341
+ timedOut = true;
9342
+ stop();
9343
+ }, options.timeoutMs);
9344
+ options.signal?.addEventListener("abort", stop, { once: true });
9345
+ if (options.signal?.aborted) stop();
9346
+ const finish = (outcome) => {
9347
+ if (settled) return;
9348
+ settled = true;
9349
+ clearTimeout(timer);
9350
+ options.signal?.removeEventListener("abort", stop);
9351
+ let stdout = Buffer.concat(stdoutChunks).toString("utf8");
9352
+ if (truncated) stdout = stdout.replace(/\uFFFD$/, "");
9353
+ resolve3({
9354
+ exitCode: outcome.exitCode,
9355
+ stdout,
9356
+ truncated,
9357
+ stderr: tail(stderr, MAX_FAILURE_DETAIL),
9358
+ timedOut,
9359
+ ...outcome.spawnError !== void 0 && { spawnError: outcome.spawnError }
9360
+ });
9361
+ };
9362
+ child.on("error", (error) => finish({ exitCode: null, spawnError: error.message }));
9363
+ child.on("close", (code) => {
9364
+ killGroup("SIGKILL");
9365
+ finish({ exitCode: code });
9366
+ });
9367
+ });
9368
+ }
9369
+ function failureReason(outcome, timeoutMs) {
9370
+ if (outcome.spawnError !== void 0) return `it couldn't start (${outcome.spawnError})`;
9371
+ if (outcome.timedOut) {
9372
+ return `it timed out after ${timeoutMs < 1e3 ? `${timeoutMs}ms` : `${Math.round(timeoutMs / 1e3)}s`}`;
9373
+ }
9374
+ if (outcome.exitCode === 0) return null;
9375
+ if (outcome.exitCode === null) return "it was killed";
9376
+ return `it exited with code ${outcome.exitCode}`;
9377
+ }
9378
+ function failureDetail(outcome, timeoutMs) {
9379
+ const reason = failureReason(outcome, timeoutMs);
9380
+ if (reason === null) return null;
9381
+ return outcome.stderr ? `${reason}: ${outcome.stderr}` : reason;
9382
+ }
9383
+ async function runSetupCommands(commands, options) {
9384
+ const setup = {};
9385
+ for (const command of commands) {
9386
+ options.signal.throwIfAborted();
9387
+ const started = Date.now();
9388
+ const timeoutMs = command.timeoutSeconds * 1e3;
9389
+ const outcome = await runCommand(resolveCommand(command.command, options.executables), {
9390
+ cwd: options.cwd,
9391
+ env: commandEnvFor(command.command, options),
9392
+ timeoutMs,
9393
+ maxStdoutBytes: command.maxOutputBytes,
9394
+ signal: options.signal
9395
+ });
9396
+ options.signal.throwIfAborted();
9397
+ const log = {
9398
+ name: command.name,
9399
+ exitCode: outcome.exitCode,
9400
+ durationMs: Date.now() - started
9401
+ };
9402
+ const reason = failureReason(outcome, timeoutMs);
9403
+ if (reason === null) {
9404
+ options.logger.info(
9405
+ { ...log, truncated: outcome.truncated, stderr: outcome.stderr },
9406
+ "setup command finished"
9407
+ );
9408
+ setup[command.name] = outcome.truncated ? `${outcome.stdout}${TRUNCATION_MARKER}` : outcome.stdout;
9409
+ continue;
9410
+ }
9411
+ if (!command.optional) {
9412
+ options.logger.info(
9413
+ { ...log, stderr: outcome.stderr },
9414
+ "setup command failed; failing the run"
9415
+ );
9416
+ throw new SetupCommandError(command.name, failureDetail(outcome, timeoutMs) ?? reason);
9417
+ }
9418
+ options.logger.info({ ...log, stderr: outcome.stderr }, "optional setup command failed");
9419
+ setup[command.name] = `(The setup command ${command.name} failed: ${reason}.)`;
9420
+ }
9421
+ return setup;
9422
+ }
9423
+ async function runTeardownCommands(commands, options) {
9424
+ for (const command of commands) {
9425
+ const started = Date.now();
9426
+ const timeoutMs = command.timeoutSeconds * 1e3;
9427
+ const outcome = await runCommand(resolveCommand(command.command, options.executables), {
9428
+ cwd: options.cwd,
9429
+ env: commandEnvFor(command.command, options),
9430
+ timeoutMs,
9431
+ maxStdoutBytes: command.maxOutputBytes
9432
+ });
9433
+ const log = {
9434
+ name: command.name,
9435
+ exitCode: outcome.exitCode,
9436
+ durationMs: Date.now() - started,
9437
+ stdout: outcome.stdout,
9438
+ stderr: outcome.stderr
9439
+ };
9440
+ const failure3 = failureDetail(outcome, timeoutMs);
9441
+ if (failure3 === null) options.logger.info(log, "teardown command finished");
9442
+ else options.logger.warn({ ...log, failure: failure3 }, "teardown command failed");
9443
+ }
9444
+ }
9445
+
9446
+ // src/workspace/git.ts
9447
+ import { spawn as spawn3 } from "node:child_process";
9202
9448
  var GitError2 = class extends Error {
9203
9449
  constructor(args, exitCode, stderr) {
9204
9450
  super(
@@ -9213,13 +9459,13 @@ var GitError2 = class extends Error {
9213
9459
  stderr;
9214
9460
  name = "GitError";
9215
9461
  };
9216
- function shellQuote(word) {
9462
+ function shellQuote2(word) {
9217
9463
  return /^[A-Za-z0-9_@%+=:,./-]+$/.test(word) ? word : `'${word.replaceAll("'", `'\\''`)}'`;
9218
9464
  }
9219
9465
  function defaultCredentialHelper(execPath = process.execPath, execArgv = process.execArgv, script = process.argv[1]) {
9220
9466
  if (!script)
9221
9467
  throw new Error("can't determine the agent's CLI script for the git credential helper");
9222
- return `!${[execPath, ...execArgv, script, "git-credential"].map(shellQuote).join(" ")}`;
9468
+ return `!${[execPath, ...execArgv, script, "git-credential"].map(shellQuote2).join(" ")}`;
9223
9469
  }
9224
9470
  function credentialConfigArgs(credentialHelper) {
9225
9471
  return [
@@ -9283,7 +9529,7 @@ function runProcess(file, args, options) {
9283
9529
  const { signal } = options;
9284
9530
  if (signal?.aborted) return Promise.reject(signal.reason);
9285
9531
  return new Promise((resolve3, reject) => {
9286
- const child = spawn2(file, args, {
9532
+ const child = spawn3(file, args, {
9287
9533
  cwd: options.cwd,
9288
9534
  env: options.env,
9289
9535
  stdio: ["ignore", "pipe", "pipe"]
@@ -9310,7 +9556,7 @@ function runProcess(file, args, options) {
9310
9556
 
9311
9557
  // src/rpc/worktree-exec.ts
9312
9558
  var MAX_OUTPUT = 4e3;
9313
- function tail(text3, max) {
9559
+ function tail2(text3, max) {
9314
9560
  const trimmed = text3.trim();
9315
9561
  return trimmed.length > max ? `\u2026${trimmed.slice(-max)}` : trimmed;
9316
9562
  }
@@ -9327,7 +9573,7 @@ async function runApprovedCommands(payload, ctx, onCommand) {
9327
9573
  story: payload.story.identifier
9328
9574
  });
9329
9575
  const env = ctx.env();
9330
- const plainEnv = withoutJobEnv(env);
9576
+ const plainEnv = commandEnv(env);
9331
9577
  return ctx.repos.withBranchWorktree(
9332
9578
  payload.repository,
9333
9579
  {
@@ -9354,11 +9600,11 @@ async function runApprovedCommands(payload, ctx, onCommand) {
9354
9600
  signal: ctx.signal,
9355
9601
  mergeOutput: true
9356
9602
  });
9357
- ran.push({ command, exitCode: 0, output: tail(output, MAX_OUTPUT) });
9603
+ ran.push({ command, exitCode: 0, output: tail2(output, MAX_OUTPUT) });
9358
9604
  } catch (error) {
9359
9605
  ctx.signal.throwIfAborted();
9360
9606
  const failed = error instanceof CommandError ? { exitCode: error.exitCode, output: error.output } : { exitCode: null, output: error instanceof Error ? error.message : String(error) };
9361
- ran.push({ command, exitCode: failed.exitCode, output: tail(failed.output, MAX_OUTPUT) });
9607
+ ran.push({ command, exitCode: failed.exitCode, output: tail2(failed.output, MAX_OUTPUT) });
9362
9608
  log.info({ command, exitCode: failed.exitCode }, "approved command failed");
9363
9609
  return result("failed", ran, await currentHead(worktree, head));
9364
9610
  }
@@ -10405,194 +10651,6 @@ function createOmniralphServer(options) {
10405
10651
  };
10406
10652
  }
10407
10653
 
10408
- // src/lifecycle/commands.ts
10409
- import { spawn as spawn3 } from "node:child_process";
10410
- var MAX_FAILURE_DETAIL = 500;
10411
- var KILL_GRACE_MS = 5e3;
10412
- var SetupCommandError = class extends Error {
10413
- constructor(commandName, detail) {
10414
- super(`setup command ${commandName} failed: ${detail}`);
10415
- this.commandName = commandName;
10416
- this.detail = detail;
10417
- this.name = "SetupCommandError";
10418
- }
10419
- commandName;
10420
- detail;
10421
- };
10422
- function commandEnv(env) {
10423
- return Object.fromEntries(
10424
- Object.entries(env).filter(
10425
- ([name]) => !name.startsWith("OMNIRALPH_") && name !== "GIT_CONFIG_COUNT" && !name.startsWith("GIT_CONFIG_KEY_") && !name.startsWith("GIT_CONFIG_VALUE_")
10426
- )
10427
- );
10428
- }
10429
- function shellQuote2(value) {
10430
- return `'${value.replace(/'/g, `'\\''`)}'`;
10431
- }
10432
- var FIRST_WORD = /^(\s*)([^\s;&|<>()]+)/;
10433
- function resolveCommand(command, commands = /* @__PURE__ */ new Map()) {
10434
- const match = FIRST_WORD.exec(command);
10435
- const resolved = match ? commands.get(match[2]) : void 0;
10436
- if (!match || resolved === void 0) return command;
10437
- return `${match[1]}${shellQuote2(resolved)}${command.slice(match[0].length)}`;
10438
- }
10439
- function commandEnvFor(command, options) {
10440
- const name = FIRST_WORD.exec(command)?.[2];
10441
- const extra = name === void 0 ? void 0 : options.executableEnv?.get(name);
10442
- return { ...commandEnv(options.env), ...extra };
10443
- }
10444
- function tail2(text3, max) {
10445
- const trimmed = text3.trim();
10446
- return trimmed.length > max ? `\u2026${trimmed.slice(-max)}` : trimmed;
10447
- }
10448
- function runCommand(command, options) {
10449
- return new Promise((resolve3) => {
10450
- const stdoutChunks = [];
10451
- let stdoutBytes = 0;
10452
- let truncated = false;
10453
- let stderr = "";
10454
- let timedOut = false;
10455
- let settled = false;
10456
- let killTimer;
10457
- const child = spawn3("sh", ["-c", command], {
10458
- cwd: options.cwd,
10459
- env: options.env,
10460
- stdio: ["ignore", "pipe", "pipe"],
10461
- detached: true
10462
- });
10463
- child.stderr.setEncoding("utf8");
10464
- child.stdout.on("data", (chunk) => {
10465
- if (truncated) return;
10466
- const room = options.maxStdoutBytes - stdoutBytes;
10467
- if (chunk.length > room) {
10468
- stdoutChunks.push(chunk.subarray(0, room));
10469
- stdoutBytes += room;
10470
- truncated = true;
10471
- } else {
10472
- stdoutChunks.push(chunk);
10473
- stdoutBytes += chunk.length;
10474
- }
10475
- });
10476
- child.stderr.on("data", (chunk) => {
10477
- stderr = (stderr + chunk).slice(-MAX_FAILURE_DETAIL * 4);
10478
- });
10479
- const killGroup = (sig) => {
10480
- try {
10481
- if (child.pid !== void 0) process.kill(-child.pid, sig);
10482
- } catch {
10483
- }
10484
- };
10485
- const stop = () => {
10486
- killGroup("SIGTERM");
10487
- killTimer ??= setTimeout(() => killGroup("SIGKILL"), KILL_GRACE_MS);
10488
- killTimer.unref();
10489
- };
10490
- const timer = setTimeout(() => {
10491
- timedOut = true;
10492
- stop();
10493
- }, options.timeoutMs);
10494
- options.signal?.addEventListener("abort", stop, { once: true });
10495
- if (options.signal?.aborted) stop();
10496
- const finish = (outcome) => {
10497
- if (settled) return;
10498
- settled = true;
10499
- clearTimeout(timer);
10500
- options.signal?.removeEventListener("abort", stop);
10501
- let stdout = Buffer.concat(stdoutChunks).toString("utf8");
10502
- if (truncated) stdout = stdout.replace(/\uFFFD$/, "");
10503
- resolve3({
10504
- exitCode: outcome.exitCode,
10505
- stdout,
10506
- truncated,
10507
- stderr: tail2(stderr, MAX_FAILURE_DETAIL),
10508
- timedOut,
10509
- ...outcome.spawnError !== void 0 && { spawnError: outcome.spawnError }
10510
- });
10511
- };
10512
- child.on("error", (error) => finish({ exitCode: null, spawnError: error.message }));
10513
- child.on("close", (code) => {
10514
- killGroup("SIGKILL");
10515
- finish({ exitCode: code });
10516
- });
10517
- });
10518
- }
10519
- function failureReason(outcome, timeoutMs) {
10520
- if (outcome.spawnError !== void 0) return `it couldn't start (${outcome.spawnError})`;
10521
- if (outcome.timedOut) {
10522
- return `it timed out after ${timeoutMs < 1e3 ? `${timeoutMs}ms` : `${Math.round(timeoutMs / 1e3)}s`}`;
10523
- }
10524
- if (outcome.exitCode === 0) return null;
10525
- if (outcome.exitCode === null) return "it was killed";
10526
- return `it exited with code ${outcome.exitCode}`;
10527
- }
10528
- function failureDetail(outcome, timeoutMs) {
10529
- const reason = failureReason(outcome, timeoutMs);
10530
- if (reason === null) return null;
10531
- return outcome.stderr ? `${reason}: ${outcome.stderr}` : reason;
10532
- }
10533
- async function runSetupCommands(commands, options) {
10534
- const setup = {};
10535
- for (const command of commands) {
10536
- options.signal.throwIfAborted();
10537
- const started = Date.now();
10538
- const timeoutMs = command.timeoutSeconds * 1e3;
10539
- const outcome = await runCommand(resolveCommand(command.command, options.executables), {
10540
- cwd: options.cwd,
10541
- env: commandEnvFor(command.command, options),
10542
- timeoutMs,
10543
- maxStdoutBytes: command.maxOutputBytes,
10544
- signal: options.signal
10545
- });
10546
- options.signal.throwIfAborted();
10547
- const log = {
10548
- name: command.name,
10549
- exitCode: outcome.exitCode,
10550
- durationMs: Date.now() - started
10551
- };
10552
- const reason = failureReason(outcome, timeoutMs);
10553
- if (reason === null) {
10554
- options.logger.info(
10555
- { ...log, truncated: outcome.truncated, stderr: outcome.stderr },
10556
- "setup command finished"
10557
- );
10558
- setup[command.name] = outcome.truncated ? `${outcome.stdout}${TRUNCATION_MARKER}` : outcome.stdout;
10559
- continue;
10560
- }
10561
- if (!command.optional) {
10562
- options.logger.info(
10563
- { ...log, stderr: outcome.stderr },
10564
- "setup command failed; failing the run"
10565
- );
10566
- throw new SetupCommandError(command.name, failureDetail(outcome, timeoutMs) ?? reason);
10567
- }
10568
- options.logger.info({ ...log, stderr: outcome.stderr }, "optional setup command failed");
10569
- setup[command.name] = `(The setup command ${command.name} failed: ${reason}.)`;
10570
- }
10571
- return setup;
10572
- }
10573
- async function runTeardownCommands(commands, options) {
10574
- for (const command of commands) {
10575
- const started = Date.now();
10576
- const timeoutMs = command.timeoutSeconds * 1e3;
10577
- const outcome = await runCommand(resolveCommand(command.command, options.executables), {
10578
- cwd: options.cwd,
10579
- env: commandEnvFor(command.command, options),
10580
- timeoutMs,
10581
- maxStdoutBytes: command.maxOutputBytes
10582
- });
10583
- const log = {
10584
- name: command.name,
10585
- exitCode: outcome.exitCode,
10586
- durationMs: Date.now() - started,
10587
- stdout: outcome.stdout,
10588
- stderr: outcome.stderr
10589
- };
10590
- const failure3 = failureDetail(outcome, timeoutMs);
10591
- if (failure3 === null) options.logger.info(log, "teardown command finished");
10592
- else options.logger.warn({ ...log, failure: failure3 }, "teardown command failed");
10593
- }
10594
- }
10595
-
10596
10654
  // src/lifecycle/executables.ts
10597
10655
  var MISSING_EXECUTABLE_RETRY_SECONDS = 60;
10598
10656
  var NO_EXECUTABLES = {
@@ -12122,6 +12180,13 @@ async function runRequestRun(spec, payload, ctx, options = {}) {
12122
12180
 
12123
12181
  // src/lifecycle/review.ts
12124
12182
  import { query as sdkQuery4 } from "@anthropic-ai/claude-agent-sdk";
12183
+ function chainTee(relay, inner) {
12184
+ if (!inner) return relay;
12185
+ return {
12186
+ runner: (runner) => inner.runner(relay.runner(runner)),
12187
+ query: (query) => inner.query(relay.query(query))
12188
+ };
12189
+ }
12125
12190
  function reviewTaskProvider(spec, ctx, logger, executables = NO_EXECUTABLES, query = sdkQuery4) {
12126
12191
  const permissions = sdkPermissions(queryToolPolicy(spec.agent, spec.task.toolSettings));
12127
12192
  const mcp = executables.mcpServers;
@@ -12167,6 +12232,20 @@ async function runReviewTask(spec, ctx, options = {}) {
12167
12232
  repo: `${repository.provider}/${repository.fullPath}`,
12168
12233
  headSha
12169
12234
  });
12235
+ const relay = new ActivityRelay({
12236
+ server: ctx.server,
12237
+ jobId: spec.jobId,
12238
+ jobToken: ctx.sessionToken,
12239
+ logger: log,
12240
+ ...options.fetch && { fetch: options.fetch }
12241
+ });
12242
+ const sessionCtx = {
12243
+ ...ctx,
12244
+ sessions: chainTee(
12245
+ sessionTee((event) => relay.event(event)),
12246
+ ctx.sessions
12247
+ )
12248
+ };
12170
12249
  const executables = await resolveRunExecutables(spec, ctx);
12171
12250
  await ctx.repos.sync(repository, { ...git2, shas: [baseSha, headSha] });
12172
12251
  if (previousReview?.headSha) {
@@ -12221,7 +12300,7 @@ async function runReviewTask(spec, ctx, options = {}) {
12221
12300
  const sessions = emptyReviewSessions();
12222
12301
  const [task] = context.plan.tasks;
12223
12302
  if (task && task.files.length > 0) {
12224
- const provider = options.provider ? options.provider(spec, ctx, log, executables) : reviewTaskProvider(spec, ctx, log, executables, options.query);
12303
+ const provider = options.provider ? options.provider(spec, sessionCtx, log, executables) : reviewTaskProvider(spec, sessionCtx, log, executables, options.query);
12225
12304
  const budget = Math.min(task.budget, spec.tokenBudget ?? Infinity);
12226
12305
  const systemPrompt = reviewSystemPrompt(spec);
12227
12306
  const result = await provider.review({
@@ -12293,24 +12372,28 @@ async function runReviewTask(spec, ctx, options = {}) {
12293
12372
  durationMs: Date.now() - started
12294
12373
  };
12295
12374
  };
12296
- return ctx.repos.withWorktree(
12297
- repository,
12298
- headSha,
12299
- { ...git2, jobId: spec.jobId },
12300
- async (worktree) => {
12301
- try {
12302
- return await reviewed(worktree.path);
12303
- } finally {
12304
- await runTeardownCommands(spec.task.teardownCommands, {
12305
- cwd: worktree.path,
12306
- env: withoutJobEnv(ctx.env()),
12307
- logger: log,
12308
- executables: executables.commands,
12309
- executableEnv: executables.commandEnv
12310
- });
12375
+ try {
12376
+ return await ctx.repos.withWorktree(
12377
+ repository,
12378
+ headSha,
12379
+ { ...git2, jobId: spec.jobId },
12380
+ async (worktree) => {
12381
+ try {
12382
+ return await reviewed(worktree.path);
12383
+ } finally {
12384
+ await runTeardownCommands(spec.task.teardownCommands, {
12385
+ cwd: worktree.path,
12386
+ env: withoutJobEnv(ctx.env()),
12387
+ logger: log,
12388
+ executables: executables.commands,
12389
+ executableEnv: executables.commandEnv
12390
+ });
12391
+ }
12311
12392
  }
12312
- }
12313
- );
12393
+ );
12394
+ } finally {
12395
+ await relay.flush();
12396
+ }
12314
12397
  }
12315
12398
 
12316
12399
  // src/rpc/install.ts
@@ -13810,6 +13893,7 @@ var AgentDaemon = class {
13810
13893
  const hostTools = await this.checkHostTools();
13811
13894
  const claude = await this.options.claude?.current();
13812
13895
  const local = this.localSettings();
13896
+ const tokenRefresh = this.options.tokens.refreshStatus();
13813
13897
  try {
13814
13898
  const response = await this.options.api.heartbeat({
13815
13899
  version: this.options.version,
@@ -13831,7 +13915,8 @@ var AgentDaemon = class {
13831
13915
  installablesAllow: local.installablesAllow
13832
13916
  },
13833
13917
  ...this.options.updater?.report(),
13834
- ...this.wakeReport()
13918
+ ...this.wakeReport(),
13919
+ ...tokenRefresh && { tokenRefresh }
13835
13920
  });
13836
13921
  this.lastHeartbeatAt = /* @__PURE__ */ new Date();
13837
13922
  this.unreachableSince = null;