@omniralph/agent 2.0.0 → 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
@@ -61,7 +61,8 @@ var EnrollResponse = z2.object({
61
61
  refreshToken: z2.string()
62
62
  });
63
63
  var TokenRequest = z2.object({
64
- refreshToken: z2.string().min(1).max(256)
64
+ /** An opaque `orr_` token (before TOOL-856) or a signed one (a JWT, ~700 characters). */
65
+ refreshToken: z2.string().min(1).max(4096)
65
66
  });
66
67
  var TokenResponse = z2.object({
67
68
  accessToken: z2.string(),
@@ -3195,6 +3196,18 @@ var AgentHostReport = z12.object({
3195
3196
  workspace: z12.string().min(1).max(AGENT_HOST_NAME_MAX)
3196
3197
  }).nullable()
3197
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
+ });
3198
3211
  var HostToolPath = z12.string().max(4096).refine((path25) => path25.startsWith("/"), "must be an absolute path");
3199
3212
  var HOST_TOOL_SOURCES = ["configured", "discovered"];
3200
3213
  var HOST_TOOL_PROBLEMS = ["missing", "not_executable", "blocked"];
@@ -3243,7 +3256,9 @@ var Heartbeat = z12.object({
3243
3256
  /** The machine the agent runs on. Absent from older agents: the last report is kept. */
3244
3257
  host: AgentHostReport.optional(),
3245
3258
  /** The agent's machine settings in force. */
3246
- 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()
3247
3262
  });
3248
3263
  function agentWakeChannel(agentId) {
3249
3264
  return `agent:${agentId}`;
@@ -7940,7 +7955,7 @@ async function runQuery(query, request, seen) {
7940
7955
  // src/tools/activities.ts
7941
7956
  import { z as z28 } from "zod";
7942
7957
  var MAX_BODY = 1e4;
7943
- var MAX_PARAMETER = 500;
7958
+ var MAX_PARAMETER = 1e4;
7944
7959
  var SKIPPED_TOOLS = /* @__PURE__ */ new Set(["TodoWrite"]);
7945
7960
  var PARAMETER_KEYS = [
7946
7961
  "command",
@@ -8292,6 +8307,25 @@ var ReenrollmentRequiredError = class extends Error {
8292
8307
  code;
8293
8308
  name = "ReenrollmentRequiredError";
8294
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
+ }
8295
8329
  var defaultRetryDelayMs = (failures) => Math.min(6e4, 5e3 * 2 ** (failures - 1));
8296
8330
  var TokenManager = class {
8297
8331
  constructor(options) {
@@ -8307,6 +8341,9 @@ var TokenManager = class {
8307
8341
  timer = null;
8308
8342
  inflight = null;
8309
8343
  failures = 0;
8344
+ /** The first failure since the last successful refresh (null while healthy). */
8345
+ failingSince = null;
8346
+ lastError = null;
8310
8347
  fatal = null;
8311
8348
  stopped = false;
8312
8349
  refreshAt;
@@ -8337,6 +8374,21 @@ var TokenManager = class {
8337
8374
  });
8338
8375
  return this.inflight;
8339
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
+ }
8340
8392
  stop() {
8341
8393
  this.stopped = true;
8342
8394
  this.clearTimer();
@@ -8358,7 +8410,7 @@ var TokenManager = class {
8358
8410
  this.options.onFatal?.(this.fatal);
8359
8411
  throw this.fatal;
8360
8412
  }
8361
- this.failures++;
8413
+ this.recordFailure(refreshErrorCode(error));
8362
8414
  const delay = error instanceof ApiError && error.retryAfterSeconds ? error.retryAfterSeconds * 1e3 : this.retryDelayMs(this.failures);
8363
8415
  this.options.logger.warn({ err: error, retryInMs: delay }, "access token refresh failed");
8364
8416
  this.schedule(delay);
@@ -8368,7 +8420,7 @@ var TokenManager = class {
8368
8420
  try {
8369
8421
  await this.options.persist(this.config);
8370
8422
  } catch (error) {
8371
- this.failures++;
8423
+ this.recordFailure("persist_failed");
8372
8424
  const delay = this.retryDelayMs(this.failures);
8373
8425
  this.options.logger.error(
8374
8426
  { err: error, retryInMs: delay },
@@ -8378,12 +8430,19 @@ var TokenManager = class {
8378
8430
  throw error;
8379
8431
  }
8380
8432
  this.failures = 0;
8433
+ this.failingSince = null;
8434
+ this.lastError = null;
8381
8435
  this.accessToken = response.accessToken;
8382
8436
  this.expiresAt = Date.now() + response.expiresIn * 1e3;
8383
8437
  this.schedule(response.expiresIn * 1e3 * this.refreshAt);
8384
8438
  this.options.logger.debug({ expiresIn: response.expiresIn }, "access token refreshed");
8385
8439
  return response.accessToken;
8386
8440
  }
8441
+ recordFailure(code) {
8442
+ this.failures++;
8443
+ this.failingSince ??= /* @__PURE__ */ new Date();
8444
+ this.lastError = code;
8445
+ }
8387
8446
  schedule(delayMs) {
8388
8447
  this.clearTimer();
8389
8448
  if (this.stopped) return;
@@ -9196,8 +9255,196 @@ ${failed.map(
9196
9255
  ).join("\n")}`;
9197
9256
  }
9198
9257
 
9199
- // src/workspace/git.ts
9258
+ // src/lifecycle/commands.ts
9200
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";
9201
9448
  var GitError2 = class extends Error {
9202
9449
  constructor(args, exitCode, stderr) {
9203
9450
  super(
@@ -9212,13 +9459,13 @@ var GitError2 = class extends Error {
9212
9459
  stderr;
9213
9460
  name = "GitError";
9214
9461
  };
9215
- function shellQuote(word) {
9462
+ function shellQuote2(word) {
9216
9463
  return /^[A-Za-z0-9_@%+=:,./-]+$/.test(word) ? word : `'${word.replaceAll("'", `'\\''`)}'`;
9217
9464
  }
9218
9465
  function defaultCredentialHelper(execPath = process.execPath, execArgv = process.execArgv, script = process.argv[1]) {
9219
9466
  if (!script)
9220
9467
  throw new Error("can't determine the agent's CLI script for the git credential helper");
9221
- return `!${[execPath, ...execArgv, script, "git-credential"].map(shellQuote).join(" ")}`;
9468
+ return `!${[execPath, ...execArgv, script, "git-credential"].map(shellQuote2).join(" ")}`;
9222
9469
  }
9223
9470
  function credentialConfigArgs(credentialHelper) {
9224
9471
  return [
@@ -9282,7 +9529,7 @@ function runProcess(file, args, options) {
9282
9529
  const { signal } = options;
9283
9530
  if (signal?.aborted) return Promise.reject(signal.reason);
9284
9531
  return new Promise((resolve3, reject) => {
9285
- const child = spawn2(file, args, {
9532
+ const child = spawn3(file, args, {
9286
9533
  cwd: options.cwd,
9287
9534
  env: options.env,
9288
9535
  stdio: ["ignore", "pipe", "pipe"]
@@ -9309,7 +9556,7 @@ function runProcess(file, args, options) {
9309
9556
 
9310
9557
  // src/rpc/worktree-exec.ts
9311
9558
  var MAX_OUTPUT = 4e3;
9312
- function tail(text3, max) {
9559
+ function tail2(text3, max) {
9313
9560
  const trimmed = text3.trim();
9314
9561
  return trimmed.length > max ? `\u2026${trimmed.slice(-max)}` : trimmed;
9315
9562
  }
@@ -9326,7 +9573,7 @@ async function runApprovedCommands(payload, ctx, onCommand) {
9326
9573
  story: payload.story.identifier
9327
9574
  });
9328
9575
  const env = ctx.env();
9329
- const plainEnv = withoutJobEnv(env);
9576
+ const plainEnv = commandEnv(env);
9330
9577
  return ctx.repos.withBranchWorktree(
9331
9578
  payload.repository,
9332
9579
  {
@@ -9353,11 +9600,11 @@ async function runApprovedCommands(payload, ctx, onCommand) {
9353
9600
  signal: ctx.signal,
9354
9601
  mergeOutput: true
9355
9602
  });
9356
- ran.push({ command, exitCode: 0, output: tail(output, MAX_OUTPUT) });
9603
+ ran.push({ command, exitCode: 0, output: tail2(output, MAX_OUTPUT) });
9357
9604
  } catch (error) {
9358
9605
  ctx.signal.throwIfAborted();
9359
9606
  const failed = error instanceof CommandError ? { exitCode: error.exitCode, output: error.output } : { exitCode: null, output: error instanceof Error ? error.message : String(error) };
9360
- 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) });
9361
9608
  log.info({ command, exitCode: failed.exitCode }, "approved command failed");
9362
9609
  return result("failed", ran, await currentHead(worktree, head));
9363
9610
  }
@@ -10404,194 +10651,6 @@ function createOmniralphServer(options) {
10404
10651
  };
10405
10652
  }
10406
10653
 
10407
- // src/lifecycle/commands.ts
10408
- import { spawn as spawn3 } from "node:child_process";
10409
- var MAX_FAILURE_DETAIL = 500;
10410
- var KILL_GRACE_MS = 5e3;
10411
- var SetupCommandError = class extends Error {
10412
- constructor(commandName, detail) {
10413
- super(`setup command ${commandName} failed: ${detail}`);
10414
- this.commandName = commandName;
10415
- this.detail = detail;
10416
- this.name = "SetupCommandError";
10417
- }
10418
- commandName;
10419
- detail;
10420
- };
10421
- function commandEnv(env) {
10422
- return Object.fromEntries(
10423
- Object.entries(env).filter(
10424
- ([name]) => !name.startsWith("OMNIRALPH_") && name !== "GIT_CONFIG_COUNT" && !name.startsWith("GIT_CONFIG_KEY_") && !name.startsWith("GIT_CONFIG_VALUE_")
10425
- )
10426
- );
10427
- }
10428
- function shellQuote2(value) {
10429
- return `'${value.replace(/'/g, `'\\''`)}'`;
10430
- }
10431
- var FIRST_WORD = /^(\s*)([^\s;&|<>()]+)/;
10432
- function resolveCommand(command, commands = /* @__PURE__ */ new Map()) {
10433
- const match = FIRST_WORD.exec(command);
10434
- const resolved = match ? commands.get(match[2]) : void 0;
10435
- if (!match || resolved === void 0) return command;
10436
- return `${match[1]}${shellQuote2(resolved)}${command.slice(match[0].length)}`;
10437
- }
10438
- function commandEnvFor(command, options) {
10439
- const name = FIRST_WORD.exec(command)?.[2];
10440
- const extra = name === void 0 ? void 0 : options.executableEnv?.get(name);
10441
- return { ...commandEnv(options.env), ...extra };
10442
- }
10443
- function tail2(text3, max) {
10444
- const trimmed = text3.trim();
10445
- return trimmed.length > max ? `\u2026${trimmed.slice(-max)}` : trimmed;
10446
- }
10447
- function runCommand(command, options) {
10448
- return new Promise((resolve3) => {
10449
- const stdoutChunks = [];
10450
- let stdoutBytes = 0;
10451
- let truncated = false;
10452
- let stderr = "";
10453
- let timedOut = false;
10454
- let settled = false;
10455
- let killTimer;
10456
- const child = spawn3("sh", ["-c", command], {
10457
- cwd: options.cwd,
10458
- env: options.env,
10459
- stdio: ["ignore", "pipe", "pipe"],
10460
- detached: true
10461
- });
10462
- child.stderr.setEncoding("utf8");
10463
- child.stdout.on("data", (chunk) => {
10464
- if (truncated) return;
10465
- const room = options.maxStdoutBytes - stdoutBytes;
10466
- if (chunk.length > room) {
10467
- stdoutChunks.push(chunk.subarray(0, room));
10468
- stdoutBytes += room;
10469
- truncated = true;
10470
- } else {
10471
- stdoutChunks.push(chunk);
10472
- stdoutBytes += chunk.length;
10473
- }
10474
- });
10475
- child.stderr.on("data", (chunk) => {
10476
- stderr = (stderr + chunk).slice(-MAX_FAILURE_DETAIL * 4);
10477
- });
10478
- const killGroup = (sig) => {
10479
- try {
10480
- if (child.pid !== void 0) process.kill(-child.pid, sig);
10481
- } catch {
10482
- }
10483
- };
10484
- const stop = () => {
10485
- killGroup("SIGTERM");
10486
- killTimer ??= setTimeout(() => killGroup("SIGKILL"), KILL_GRACE_MS);
10487
- killTimer.unref();
10488
- };
10489
- const timer = setTimeout(() => {
10490
- timedOut = true;
10491
- stop();
10492
- }, options.timeoutMs);
10493
- options.signal?.addEventListener("abort", stop, { once: true });
10494
- if (options.signal?.aborted) stop();
10495
- const finish = (outcome) => {
10496
- if (settled) return;
10497
- settled = true;
10498
- clearTimeout(timer);
10499
- options.signal?.removeEventListener("abort", stop);
10500
- let stdout = Buffer.concat(stdoutChunks).toString("utf8");
10501
- if (truncated) stdout = stdout.replace(/\uFFFD$/, "");
10502
- resolve3({
10503
- exitCode: outcome.exitCode,
10504
- stdout,
10505
- truncated,
10506
- stderr: tail2(stderr, MAX_FAILURE_DETAIL),
10507
- timedOut,
10508
- ...outcome.spawnError !== void 0 && { spawnError: outcome.spawnError }
10509
- });
10510
- };
10511
- child.on("error", (error) => finish({ exitCode: null, spawnError: error.message }));
10512
- child.on("close", (code) => {
10513
- killGroup("SIGKILL");
10514
- finish({ exitCode: code });
10515
- });
10516
- });
10517
- }
10518
- function failureReason(outcome, timeoutMs) {
10519
- if (outcome.spawnError !== void 0) return `it couldn't start (${outcome.spawnError})`;
10520
- if (outcome.timedOut) {
10521
- return `it timed out after ${timeoutMs < 1e3 ? `${timeoutMs}ms` : `${Math.round(timeoutMs / 1e3)}s`}`;
10522
- }
10523
- if (outcome.exitCode === 0) return null;
10524
- if (outcome.exitCode === null) return "it was killed";
10525
- return `it exited with code ${outcome.exitCode}`;
10526
- }
10527
- function failureDetail(outcome, timeoutMs) {
10528
- const reason = failureReason(outcome, timeoutMs);
10529
- if (reason === null) return null;
10530
- return outcome.stderr ? `${reason}: ${outcome.stderr}` : reason;
10531
- }
10532
- async function runSetupCommands(commands, options) {
10533
- const setup = {};
10534
- for (const command of commands) {
10535
- options.signal.throwIfAborted();
10536
- const started = Date.now();
10537
- const timeoutMs = command.timeoutSeconds * 1e3;
10538
- const outcome = await runCommand(resolveCommand(command.command, options.executables), {
10539
- cwd: options.cwd,
10540
- env: commandEnvFor(command.command, options),
10541
- timeoutMs,
10542
- maxStdoutBytes: command.maxOutputBytes,
10543
- signal: options.signal
10544
- });
10545
- options.signal.throwIfAborted();
10546
- const log = {
10547
- name: command.name,
10548
- exitCode: outcome.exitCode,
10549
- durationMs: Date.now() - started
10550
- };
10551
- const reason = failureReason(outcome, timeoutMs);
10552
- if (reason === null) {
10553
- options.logger.info(
10554
- { ...log, truncated: outcome.truncated, stderr: outcome.stderr },
10555
- "setup command finished"
10556
- );
10557
- setup[command.name] = outcome.truncated ? `${outcome.stdout}${TRUNCATION_MARKER}` : outcome.stdout;
10558
- continue;
10559
- }
10560
- if (!command.optional) {
10561
- options.logger.info(
10562
- { ...log, stderr: outcome.stderr },
10563
- "setup command failed; failing the run"
10564
- );
10565
- throw new SetupCommandError(command.name, failureDetail(outcome, timeoutMs) ?? reason);
10566
- }
10567
- options.logger.info({ ...log, stderr: outcome.stderr }, "optional setup command failed");
10568
- setup[command.name] = `(The setup command ${command.name} failed: ${reason}.)`;
10569
- }
10570
- return setup;
10571
- }
10572
- async function runTeardownCommands(commands, options) {
10573
- for (const command of commands) {
10574
- const started = Date.now();
10575
- const timeoutMs = command.timeoutSeconds * 1e3;
10576
- const outcome = await runCommand(resolveCommand(command.command, options.executables), {
10577
- cwd: options.cwd,
10578
- env: commandEnvFor(command.command, options),
10579
- timeoutMs,
10580
- maxStdoutBytes: command.maxOutputBytes
10581
- });
10582
- const log = {
10583
- name: command.name,
10584
- exitCode: outcome.exitCode,
10585
- durationMs: Date.now() - started,
10586
- stdout: outcome.stdout,
10587
- stderr: outcome.stderr
10588
- };
10589
- const failure3 = failureDetail(outcome, timeoutMs);
10590
- if (failure3 === null) options.logger.info(log, "teardown command finished");
10591
- else options.logger.warn({ ...log, failure: failure3 }, "teardown command failed");
10592
- }
10593
- }
10594
-
10595
10654
  // src/lifecycle/executables.ts
10596
10655
  var MISSING_EXECUTABLE_RETRY_SECONDS = 60;
10597
10656
  var NO_EXECUTABLES = {
@@ -12121,6 +12180,13 @@ async function runRequestRun(spec, payload, ctx, options = {}) {
12121
12180
 
12122
12181
  // src/lifecycle/review.ts
12123
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
+ }
12124
12190
  function reviewTaskProvider(spec, ctx, logger, executables = NO_EXECUTABLES, query = sdkQuery4) {
12125
12191
  const permissions = sdkPermissions(queryToolPolicy(spec.agent, spec.task.toolSettings));
12126
12192
  const mcp = executables.mcpServers;
@@ -12166,6 +12232,20 @@ async function runReviewTask(spec, ctx, options = {}) {
12166
12232
  repo: `${repository.provider}/${repository.fullPath}`,
12167
12233
  headSha
12168
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
+ };
12169
12249
  const executables = await resolveRunExecutables(spec, ctx);
12170
12250
  await ctx.repos.sync(repository, { ...git2, shas: [baseSha, headSha] });
12171
12251
  if (previousReview?.headSha) {
@@ -12220,7 +12300,7 @@ async function runReviewTask(spec, ctx, options = {}) {
12220
12300
  const sessions = emptyReviewSessions();
12221
12301
  const [task] = context.plan.tasks;
12222
12302
  if (task && task.files.length > 0) {
12223
- 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);
12224
12304
  const budget = Math.min(task.budget, spec.tokenBudget ?? Infinity);
12225
12305
  const systemPrompt = reviewSystemPrompt(spec);
12226
12306
  const result = await provider.review({
@@ -12292,24 +12372,28 @@ async function runReviewTask(spec, ctx, options = {}) {
12292
12372
  durationMs: Date.now() - started
12293
12373
  };
12294
12374
  };
12295
- return ctx.repos.withWorktree(
12296
- repository,
12297
- headSha,
12298
- { ...git2, jobId: spec.jobId },
12299
- async (worktree) => {
12300
- try {
12301
- return await reviewed(worktree.path);
12302
- } finally {
12303
- await runTeardownCommands(spec.task.teardownCommands, {
12304
- cwd: worktree.path,
12305
- env: withoutJobEnv(ctx.env()),
12306
- logger: log,
12307
- executables: executables.commands,
12308
- executableEnv: executables.commandEnv
12309
- });
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
+ }
12310
12392
  }
12311
- }
12312
- );
12393
+ );
12394
+ } finally {
12395
+ await relay.flush();
12396
+ }
12313
12397
  }
12314
12398
 
12315
12399
  // src/rpc/install.ts
@@ -13809,6 +13893,7 @@ var AgentDaemon = class {
13809
13893
  const hostTools = await this.checkHostTools();
13810
13894
  const claude = await this.options.claude?.current();
13811
13895
  const local = this.localSettings();
13896
+ const tokenRefresh = this.options.tokens.refreshStatus();
13812
13897
  try {
13813
13898
  const response = await this.options.api.heartbeat({
13814
13899
  version: this.options.version,
@@ -13830,7 +13915,8 @@ var AgentDaemon = class {
13830
13915
  installablesAllow: local.installablesAllow
13831
13916
  },
13832
13917
  ...this.options.updater?.report(),
13833
- ...this.wakeReport()
13918
+ ...this.wakeReport(),
13919
+ ...tokenRefresh && { tokenRefresh }
13834
13920
  });
13835
13921
  this.lastHeartbeatAt = /* @__PURE__ */ new Date();
13836
13922
  this.unreachableSince = null;