@omniralph/agent 0.4.0 → 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.
package/dist/cli.js CHANGED
@@ -112,6 +112,10 @@ var AgentUpdateReport = z3.object({
112
112
  /** Why the last update failed, if it did. */
113
113
  error: z3.string().max(2e3).nullable()
114
114
  });
115
+ var AgentUpdateRequest = z3.object({
116
+ id: z3.uuid(),
117
+ version: AgentVersion
118
+ });
115
119
  var Heartbeat = z3.object({
116
120
  version: z3.string().min(1).max(64),
117
121
  /** Capabilities the host can run (it may know ones the control panel doesn't yet). */
@@ -128,7 +132,9 @@ var Heartbeat = z3.object({
128
132
  /** The agent's self-update progress. */
129
133
  update: AgentUpdateReport.optional(),
130
134
  /** Versions that failed to install or to stay up; the agent never retries them. */
131
- failedVersions: z3.array(z3.string().max(64)).max(100).default([])
135
+ failedVersions: z3.array(z3.string().max(64)).max(100).default([]),
136
+ /** The last `updateRequest` the agent acted on; the control panel then clears it. */
137
+ handledUpdateRequestId: z3.uuid().nullable().optional()
132
138
  });
133
139
  var JobToken = z3.object({
134
140
  jobId: z3.uuid(),
@@ -168,7 +174,9 @@ var HeartbeatResponse = z3.object({
168
174
  * The version the agent should run (the agent's override, else its
169
175
  * organization's setting); null when none is chosen. Agents under pm2 update themselves to it.
170
176
  */
171
- desiredVersion: AgentVersion.nullable().default(null)
177
+ desiredVersion: AgentVersion.nullable().default(null),
178
+ /** An update an admin asked for and the agent hasn't acted on yet. */
179
+ updateRequest: AgentUpdateRequest.nullable().default(null)
172
180
  });
173
181
  var JobPayload = z3.object({
174
182
  id: z3.uuid(),
@@ -3314,6 +3322,73 @@ var RALPH_PREPARE_TOOL_POLICY = {
3314
3322
  };
3315
3323
  var RALPH_CLEANUP_TOOL_POLICY = RALPH_PREPARE_TOOL_POLICY;
3316
3324
 
3325
+ // src/capabilities/ralph/git-access.ts
3326
+ import { mkdtemp, rename, rm, writeFile } from "node:fs/promises";
3327
+ import { tmpdir } from "node:os";
3328
+ import path from "node:path";
3329
+
3330
+ // src/job-env.ts
3331
+ import { spawn } from "node:child_process";
3332
+ var JOB_TOKEN_ENV = "OMNIRALPH_JOB_TOKEN";
3333
+ var JOB_ID_ENV = "OMNIRALPH_JOB_ID";
3334
+ var SERVER_ENV = "OMNIRALPH_SERVER";
3335
+ var JOB_TOKEN_FILE_ENV = "OMNIRALPH_JOB_TOKEN_FILE";
3336
+ function jobProcessEnv(job, base = process.env, extra = {}) {
3337
+ const env = {};
3338
+ for (const [name, value] of Object.entries({ ...base, ...extra })) {
3339
+ if (name.startsWith("OMNIRALPH_")) continue;
3340
+ env[name] = value;
3341
+ }
3342
+ env[JOB_TOKEN_ENV] = job.jobToken;
3343
+ env[JOB_ID_ENV] = job.jobId;
3344
+ env[SERVER_ENV] = job.server;
3345
+ return env;
3346
+ }
3347
+ function withoutJobEnv(env) {
3348
+ return Object.fromEntries(Object.entries(env).filter(([name]) => !name.startsWith("OMNIRALPH_")));
3349
+ }
3350
+ function spawnJobProcess(job, command, args, options = {}) {
3351
+ return spawn(command, args, { ...options, env: jobProcessEnv(job, process.env, options.env) });
3352
+ }
3353
+
3354
+ // src/capabilities/ralph/git-access.ts
3355
+ var REFRESH_MS = 3e4;
3356
+ async function jobGitAccess(ctx, options = {}) {
3357
+ const dir = await mkdtemp(path.join(tmpdir(), "omniralph-job-token-"));
3358
+ const file = path.join(dir, "token");
3359
+ let written = ctx.jobToken();
3360
+ await writeFile(file, written, { mode: 384 });
3361
+ let pending = Promise.resolve();
3362
+ const timer = setInterval(() => {
3363
+ const token = ctx.jobToken();
3364
+ if (token === written) return;
3365
+ written = token;
3366
+ pending = pending.then(async () => {
3367
+ const tmp = `${file}.tmp`;
3368
+ await writeFile(tmp, token, { mode: 384 });
3369
+ await rename(tmp, file);
3370
+ }).catch(() => {
3371
+ });
3372
+ }, options.refreshMs ?? REFRESH_MS);
3373
+ timer.unref();
3374
+ return {
3375
+ env: {
3376
+ ...withoutJobEnv(ctx.env()),
3377
+ [SERVER_ENV]: ctx.server,
3378
+ [JOB_TOKEN_FILE_ENV]: file
3379
+ },
3380
+ async close() {
3381
+ clearInterval(timer);
3382
+ await pending;
3383
+ await rm(dir, { recursive: true, force: true });
3384
+ }
3385
+ };
3386
+ }
3387
+ async function sessionGitAccess(ctx, options = {}) {
3388
+ const access = await jobGitAccess(ctx, options);
3389
+ return { ...access, env: ctx.repos.gitEnv(access.env) };
3390
+ }
3391
+
3317
3392
  // src/capabilities/ralph/cleanup.ts
3318
3393
  var errorText = (error) => error instanceof Error ? error.message : String(error);
3319
3394
  async function runCleanup(job, ctx) {
@@ -3327,7 +3402,8 @@ async function runCleanup(job, ctx) {
3327
3402
  branch,
3328
3403
  action: action.kind
3329
3404
  });
3330
- const git2 = { env: ctx.env(), signal: ctx.signal };
3405
+ const access = await jobGitAccess(ctx);
3406
+ const git2 = { env: access.env, signal: ctx.signal };
3331
3407
  const result = (fields) => RalphCleanupResult.parse({ ...fields, durationMs: Date.now() - started });
3332
3408
  try {
3333
3409
  if (action.kind === "cleanup") {
@@ -3376,6 +3452,8 @@ async function runCleanup(job, ctx) {
3376
3452
  ctx.signal.throwIfAborted();
3377
3453
  log.warn({ err: error }, "cleanup failed");
3378
3454
  return result({ error: errorText(error).slice(0, 2e4) });
3455
+ } finally {
3456
+ await access.close();
3379
3457
  }
3380
3458
  }
3381
3459
 
@@ -3589,11 +3667,13 @@ function uniqueCommands(commands) {
3589
3667
  function normalizeCommand(cmd) {
3590
3668
  return cmd.trim().replace(/\s+/g, " ");
3591
3669
  }
3670
+ var GOOD_NEIGHBOR_RULE = `- Be a good neighbor: always assume you share this machine's CPU, memory, disk and network with other sessions and workloads, and never assume what resources are available. Run tests and builds the usual way, one at a time. Never stress test by saturating all cores, running several instances of a test suite at once, or otherwise exhausting the machine's resources.`;
3592
3671
  var RALPH_SYSTEM_APPEND = `You are "Omniralph", an autonomous engineer working a Linear epic one user story at a time (the Ralph loop).
3593
3672
  - Work only on the single story you are given; other stories get their own sessions.
3594
3673
  - Never run git commit, git push, or open pull requests: the orchestrator handles version control and Linear updates. If guidance asks for a push or a PR/MR, skip that part without comment; the orchestrator does it.
3595
3674
  - Be precise and verifiable. Only report the status "complete" in your structured result when the story truly meets its acceptance criteria.
3596
- - You may run subagents and commands in the background. To wait for them, end your turn with the status "waiting": the session stays open, you are resumed as each finishes (for up to an hour), and only your last structured result counts. Stop background processes you no longer need (e.g. dev servers) before you finish.`;
3675
+ - You may run subagents and commands in the background. To wait for them, end your turn with the status "waiting": the session stays open, you are resumed as each finishes (for up to an hour), and only your last structured result counts. Stop background processes you no longer need (e.g. dev servers) before you finish.
3676
+ ${GOOD_NEIGHBOR_RULE}`;
3597
3677
  var DEFAULT_STORY_TEMPLATE = `You are working through a PRD epic from Linear, one user story per session.
3598
3678
  Each session starts with a fresh context: the PRD, the progress log and the repository are your memory.
3599
3679
 
@@ -3865,7 +3945,8 @@ function requestSystemAppend(historyRewrite = "when-asked") {
3865
3945
  - Only push the epic branch you are on. Never push to, or force-push, the base branch or any other branch.
3866
3946
  ${rewrite}
3867
3947
  - The \`summary\` of your structured result is posted to the Linear thread: summarise what you did, with links (e.g. the PR/MR URL).
3868
- - You may run subagents and commands in the background. To wait for them, end your turn with \`waiting: true\` in your structured result: the session stays open, you are resumed as each finishes (for up to an hour), and only your last structured result counts. Stop background processes you no longer need (e.g. dev servers) before you finish.`;
3948
+ - You may run subagents and commands in the background. To wait for them, end your turn with \`waiting: true\` in your structured result: the session stays open, you are resumed as each finishes (for up to an hour), and only your last structured result counts. Stop background processes you no longer need (e.g. dev servers) before you finish.
3949
+ ${GOOD_NEIGHBOR_RULE}`;
3869
3950
  }
3870
3951
  function capitalize(text) {
3871
3952
  return text.charAt(0).toUpperCase() + text.slice(1);
@@ -4456,33 +4537,9 @@ async function runQuery(query, request, seen) {
4456
4537
  }
4457
4538
 
4458
4539
  // src/capabilities/ralph/story.ts
4459
- import { mkdtemp, readFile as readFile2, rm, writeFile as writeFile2 } from "node:fs/promises";
4460
- import { tmpdir } from "node:os";
4461
- import path2 from "node:path";
4462
-
4463
- // src/job-env.ts
4464
- import { spawn } from "node:child_process";
4465
- var JOB_TOKEN_ENV = "OMNIRALPH_JOB_TOKEN";
4466
- var JOB_ID_ENV = "OMNIRALPH_JOB_ID";
4467
- var SERVER_ENV = "OMNIRALPH_SERVER";
4468
- var JOB_TOKEN_FILE_ENV = "OMNIRALPH_JOB_TOKEN_FILE";
4469
- function jobProcessEnv(job, base = process.env, extra = {}) {
4470
- const env = {};
4471
- for (const [name, value] of Object.entries({ ...base, ...extra })) {
4472
- if (name.startsWith("OMNIRALPH_")) continue;
4473
- env[name] = value;
4474
- }
4475
- env[JOB_TOKEN_ENV] = job.jobToken;
4476
- env[JOB_ID_ENV] = job.jobId;
4477
- env[SERVER_ENV] = job.server;
4478
- return env;
4479
- }
4480
- function withoutJobEnv(env) {
4481
- return Object.fromEntries(Object.entries(env).filter(([name]) => !name.startsWith("OMNIRALPH_")));
4482
- }
4483
- function spawnJobProcess(job, command, args, options = {}) {
4484
- return spawn(command, args, { ...options, env: jobProcessEnv(job, process.env, options.env) });
4485
- }
4540
+ import { mkdtemp as mkdtemp2, readFile as readFile2, rm as rm2, writeFile as writeFile3 } from "node:fs/promises";
4541
+ import { tmpdir as tmpdir2 } from "node:os";
4542
+ import path3 from "node:path";
4486
4543
 
4487
4544
  // src/workspace/git.ts
4488
4545
  import { spawn as spawn2 } from "node:child_process";
@@ -4597,8 +4654,8 @@ function runProcess(file, args, options) {
4597
4654
 
4598
4655
  // src/capabilities/ralph/attachments.ts
4599
4656
  import { existsSync } from "node:fs";
4600
- import { mkdir, readFile, writeFile } from "node:fs/promises";
4601
- import path from "node:path";
4657
+ import { mkdir, readFile, writeFile as writeFile2 } from "node:fs/promises";
4658
+ import path2 from "node:path";
4602
4659
  var ATTACHMENTS_DIR = ".attachments";
4603
4660
  var DOWNLOAD_TIMEOUT_MS = 12e4;
4604
4661
  async function readCapped(res, max) {
@@ -4649,14 +4706,14 @@ function controlPanelFetcher(options) {
4649
4706
  }
4650
4707
  function attachmentsDir(workspaceRoot, epicIdentifier) {
4651
4708
  const safe = epicIdentifier.replace(/[^A-Za-z0-9_-]/g, "_") || "epic";
4652
- return path.join(workspaceRoot, ATTACHMENTS_DIR, safe);
4709
+ return path2.join(workspaceRoot, ATTACHMENTS_DIR, safe);
4653
4710
  }
4654
4711
  async function collectAttachments(options) {
4655
4712
  const { dir, fetcher } = options;
4656
4713
  const max = options.max ?? MAX_ATTACHMENT_DOWNLOADS_PER_JOB;
4657
4714
  if (options.attachments.length === 0) return { dir, files: [] };
4658
4715
  await mkdir(dir, { recursive: true });
4659
- const indexPath = path.join(dir, ".index.json");
4716
+ const indexPath = path2.join(dir, ".index.json");
4660
4717
  let index = { files: {} };
4661
4718
  try {
4662
4719
  index = JSON.parse(await readFile(indexPath, "utf8"));
@@ -4670,8 +4727,8 @@ async function collectAttachments(options) {
4670
4727
  for (const attachment of options.attachments) {
4671
4728
  const entry = { id: attachment.id, title: attachment.title, sources: attachment.sources };
4672
4729
  const cached = index.files[attachment.id];
4673
- if (cached && existsSync(path.join(dir, cached.file))) {
4674
- files.push({ ...entry, path: path.join(dir, cached.file) });
4730
+ if (cached && existsSync(path2.join(dir, cached.file))) {
4731
+ files.push({ ...entry, path: path2.join(dir, cached.file) });
4675
4732
  continue;
4676
4733
  }
4677
4734
  if (fetched >= max) {
@@ -4690,9 +4747,9 @@ async function collectAttachments(options) {
4690
4747
  );
4691
4748
  if (!attachment.title) unnamed++;
4692
4749
  used.add(file);
4693
- await writeFile(path.join(dir, file), result.data);
4750
+ await writeFile2(path2.join(dir, file), result.data);
4694
4751
  index.files[attachment.id] = { file, contentType: result.contentType };
4695
- files.push({ ...entry, path: path.join(dir, file) });
4752
+ files.push({ ...entry, path: path2.join(dir, file) });
4696
4753
  }
4697
4754
  const failed = files.filter((f) => !f.path);
4698
4755
  const unreported = failed.filter((f) => !reported.has(f.id));
@@ -4701,7 +4758,7 @@ async function collectAttachments(options) {
4701
4758
  else reported.add(f.id);
4702
4759
  }
4703
4760
  index.reported = [...reported];
4704
- await writeFile(indexPath, JSON.stringify(index, null, 2));
4761
+ await writeFile2(indexPath, JSON.stringify(index, null, 2));
4705
4762
  if (failed.length > 0) {
4706
4763
  options.logger?.warn(
4707
4764
  { failed: failed.map((f) => ({ id: f.id, error: f.error })) },
@@ -4834,8 +4891,8 @@ async function runStory(job, ctx, options = {}) {
4834
4891
  ...options.fetch && { fetch: options.fetch }
4835
4892
  });
4836
4893
  const runSession = options.runSession ?? createSessionRunner();
4837
- const env = ctx.env();
4838
- const plainEnv = sessionEnv(env);
4894
+ const plainEnv = sessionEnv(ctx.env());
4895
+ const git2 = await jobGitAccess(ctx, { refreshMs: options.tokenRefreshMs });
4839
4896
  const prefix = stashPrefix(payload);
4840
4897
  const label = (reason) => `${prefix}${reason} (attempt ${payload.attempt})`;
4841
4898
  try {
@@ -4845,7 +4902,7 @@ async function runStory(job, ctx, options = {}) {
4845
4902
  branch: payload.branch,
4846
4903
  baseBranch: payload.baseBranch,
4847
4904
  ...payload.settings.setupCommand && { setupCommand: payload.settings.setupCommand },
4848
- env,
4905
+ env: git2.env,
4849
4906
  signal: ctx.signal
4850
4907
  },
4851
4908
  async (worktree) => {
@@ -4873,10 +4930,10 @@ async function runStory(job, ctx, options = {}) {
4873
4930
  logger: log,
4874
4931
  report: (body) => relay.post({ type: "thought", body, ephemeral: false })
4875
4932
  });
4876
- const progressDir = await mkdtemp(path2.join(tmpdir(), "omniralph-progress-"));
4877
- const progressFile = path2.join(progressDir, "progress.md");
4933
+ const progressDir = await mkdtemp2(path3.join(tmpdir2(), "omniralph-progress-"));
4934
+ const progressFile = path3.join(progressDir, "progress.md");
4878
4935
  try {
4879
- await writeFile2(progressFile, payload.progress);
4936
+ await writeFile3(progressFile, payload.progress);
4880
4937
  const { epic, story } = promptEpic(payload);
4881
4938
  const prompt = buildStoryPrompt({
4882
4939
  epic,
@@ -5057,11 +5114,12 @@ ${tail(errorText2(error), MAX_FEEDBACK_OUTPUT)}
5057
5114
  if (ctx.signal.aborted) await stashQuietly(worktree, label("stopped"), log);
5058
5115
  throw error;
5059
5116
  } finally {
5060
- await rm(progressDir, { recursive: true, force: true });
5117
+ await rm2(progressDir, { recursive: true, force: true });
5061
5118
  }
5062
5119
  }
5063
5120
  );
5064
5121
  } finally {
5122
+ await git2.close();
5065
5123
  await relay.flush();
5066
5124
  }
5067
5125
  }
@@ -5401,45 +5459,6 @@ async function currentHead(worktree, before) {
5401
5459
  import { mkdtemp as mkdtemp3, rm as rm3, writeFile as writeFile4 } from "node:fs/promises";
5402
5460
  import { tmpdir as tmpdir3 } from "node:os";
5403
5461
  import path4 from "node:path";
5404
-
5405
- // src/capabilities/ralph/git-access.ts
5406
- import { mkdtemp as mkdtemp2, rename, rm as rm2, writeFile as writeFile3 } from "node:fs/promises";
5407
- import { tmpdir as tmpdir2 } from "node:os";
5408
- import path3 from "node:path";
5409
- var REFRESH_MS = 3e4;
5410
- async function sessionGitAccess(ctx, options = {}) {
5411
- const dir = await mkdtemp2(path3.join(tmpdir2(), "omniralph-job-token-"));
5412
- const file = path3.join(dir, "token");
5413
- let written = ctx.jobToken();
5414
- await writeFile3(file, written, { mode: 384 });
5415
- let pending = Promise.resolve();
5416
- const timer = setInterval(() => {
5417
- const token = ctx.jobToken();
5418
- if (token === written) return;
5419
- written = token;
5420
- pending = pending.then(async () => {
5421
- const tmp = `${file}.tmp`;
5422
- await writeFile3(tmp, token, { mode: 384 });
5423
- await rename(tmp, file);
5424
- }).catch(() => {
5425
- });
5426
- }, options.refreshMs ?? REFRESH_MS);
5427
- timer.unref();
5428
- return {
5429
- env: {
5430
- ...ctx.repos.gitEnv(withoutJobEnv(ctx.env())),
5431
- [SERVER_ENV]: ctx.server,
5432
- [JOB_TOKEN_FILE_ENV]: file
5433
- },
5434
- async close() {
5435
- clearInterval(timer);
5436
- await pending;
5437
- await rm2(dir, { recursive: true, force: true });
5438
- }
5439
- };
5440
- }
5441
-
5442
- // src/capabilities/ralph/request.ts
5443
5462
  var MAX_TEXT2 = 2e4;
5444
5463
  function tail4(text, max) {
5445
5464
  const trimmed = text.trim();
@@ -6134,7 +6153,17 @@ async function writePrivateJson(file, value) {
6134
6153
 
6135
6154
  // src/workspace/repoCache.ts
6136
6155
  import { randomUUID as randomUUID2 } from "node:crypto";
6137
- import { chmod, mkdir as mkdir3, readdir, readFile as readFile4, rename as rename3, rm as rm7, stat as stat2, writeFile as writeFile5 } from "node:fs/promises";
6156
+ import {
6157
+ chmod,
6158
+ mkdir as mkdir3,
6159
+ readdir,
6160
+ readFile as readFile4,
6161
+ rename as rename3,
6162
+ rm as rm7,
6163
+ rmdir,
6164
+ stat as stat2,
6165
+ writeFile as writeFile5
6166
+ } from "node:fs/promises";
6138
6167
  import path8 from "node:path";
6139
6168
  import lockfile from "proper-lockfile";
6140
6169
  var WORKTREES_DIR = ".worktrees";
@@ -6144,6 +6173,7 @@ var FETCH_REFSPEC = "+refs/heads/*:refs/remotes/origin/*";
6144
6173
  var SETUP_PENDING = "omniralph-setup-pending";
6145
6174
  var TMP_DIR = ".tmp";
6146
6175
  var PROVIDERS = ["github", "gitlab"];
6176
+ var HOST_CONFIG = "omniralph.hostDir";
6147
6177
  var PUSH_GUARD_HOOK = `#!/bin/sh
6148
6178
  # Installed by the Omniralph agent: a branch worktree only pushes its own branch.
6149
6179
  common=$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null) || exit 0
@@ -6208,6 +6238,19 @@ function withCall(job, call) {
6208
6238
  if (!call || !("signal" in call)) return job;
6209
6239
  return { env: job.env, signal: call.signal ?? void 0 };
6210
6240
  }
6241
+ function hostDir(cloneUrl) {
6242
+ let url;
6243
+ try {
6244
+ url = new URL(cloneUrl);
6245
+ } catch {
6246
+ throw new Error(`invalid clone URL ${cloneUrl}`);
6247
+ }
6248
+ const dir = url.host || url.protocol.replace(/:$/, "");
6249
+ if (!dir || dir.startsWith(".") || /[/\\\0]/.test(dir)) {
6250
+ throw new Error(`invalid clone URL ${cloneUrl}`);
6251
+ }
6252
+ return dir;
6253
+ }
6211
6254
  function hostEnv() {
6212
6255
  return Object.fromEntries(
6213
6256
  Object.entries(process.env).filter(([name]) => !name.startsWith("OMNIRALPH_"))
@@ -6230,7 +6273,7 @@ var RepoCache = class {
6230
6273
  this.lockRetryMs = options.lockRetryMs ?? 250;
6231
6274
  this.lockStaleMs = options.lockStaleMs ?? 3e4;
6232
6275
  }
6233
- /** `<workspaceRoot>/<provider>/<repo path>` */
6276
+ /** `<workspaceRoot>/<provider>/<host>/<repo path>` (host with its port, if any) */
6234
6277
  repoDir(repo) {
6235
6278
  const segments = repo.fullPath.split("/");
6236
6279
  if (!PROVIDERS.includes(repo.provider) || segments.some(
@@ -6238,7 +6281,7 @@ var RepoCache = class {
6238
6281
  )) {
6239
6282
  throw new Error(`invalid repository path ${repo.provider}/${repo.fullPath}`);
6240
6283
  }
6241
- return path8.join(this.workspaceRoot, repo.provider, ...segments);
6284
+ return path8.join(this.workspaceRoot, repo.provider, hostDir(repo.cloneUrl), ...segments);
6242
6285
  }
6243
6286
  /**
6244
6287
  * Environment for git commands run by others in a worktree (e.g. the
@@ -6253,7 +6296,7 @@ var RepoCache = class {
6253
6296
  if (!JOB_ID.test(jobId)) throw new Error(`invalid job ID ${jobId}`);
6254
6297
  return path8.join(this.workspaceRoot, WORKTREES_DIR, jobId);
6255
6298
  }
6256
- /** `<workspaceRoot>/.branches/<provider>/<repo path>/<branch with "/" → "__">` */
6299
+ /** `<workspaceRoot>/.branches/<provider>/<host>/<repo path>/<branch with "/" → "__">` */
6257
6300
  branchWorktreePath(repo, branch) {
6258
6301
  const relative2 = path8.relative(this.workspaceRoot, this.repoDir(repo));
6259
6302
  return path8.join(this.workspaceRoot, BRANCHES_DIR, relative2, branch.replaceAll("/", "__"));
@@ -6519,7 +6562,9 @@ Stash ${entry.sha} from ${entry.date}, made on top of ${base}.`;
6519
6562
  }
6520
6563
  /**
6521
6564
  * Startup cleanup after a crash: deletes every worktree under `.worktrees`
6522
- * (branch worktrees under `.branches` are kept) and leftover partial clones, then runs `git worktree prune` in each cached
6565
+ * (branch worktrees under `.branches` are kept) and leftover partial clones,
6566
+ * moves repositories cached before the host was part of their path (see
6567
+ * `migrateLegacyRepos`), then runs `git worktree prune` in each cached
6523
6568
  * repository. Only call it while no job is running. Returns the removed
6524
6569
  * worktree paths.
6525
6570
  */
@@ -6532,6 +6577,7 @@ Stash ${entry.sha} from ${entry.date}, made on top of ${base}.`;
6532
6577
  removed.push(stale);
6533
6578
  }
6534
6579
  await rm7(path8.join(this.workspaceRoot, TMP_DIR), { recursive: true, force: true });
6580
+ await this.migrateLegacyRepos();
6535
6581
  for (const provider of PROVIDERS) {
6536
6582
  for (const dir of await this.findRepos(path8.join(this.workspaceRoot, provider), 0)) {
6537
6583
  await this.withLock(
@@ -6547,6 +6593,96 @@ Stash ${entry.sha} from ${entry.date}, made on top of ${base}.`;
6547
6593
  return removed;
6548
6594
  }
6549
6595
  // --- internals --------------------------------------------------------------------------
6596
+ /**
6597
+ * Moves repositories cached as `<provider>/<repo path>` (before the host
6598
+ * was part of the path) to `<provider>/<host>/<repo path>`, with their
6599
+ * branch worktrees from `.branches/<provider>/<repo path>/` to
6600
+ * `.branches/<provider>/<host>/<repo path>/`, and repairs git's links
6601
+ * between them. The host comes from the repository's `origin` URL. A
6602
+ * repository that can't be moved is left in place (and cloned again at its
6603
+ * new path when next needed).
6604
+ */
6605
+ async migrateLegacyRepos() {
6606
+ for (const provider of PROVIDERS) {
6607
+ const providerDir = path8.join(this.workspaceRoot, provider);
6608
+ for (const dir of await this.findRepos(providerDir, 0)) {
6609
+ await this.withLock(
6610
+ dir,
6611
+ void 0,
6612
+ () => this.migrateLegacyRepo(provider, providerDir, dir)
6613
+ ).catch(
6614
+ (error) => this.logger?.warn({ err: error, repo: dir }, "moving a cached repository failed")
6615
+ );
6616
+ }
6617
+ }
6618
+ }
6619
+ /** Called with the (legacy) repo lock held. */
6620
+ async migrateLegacyRepo(provider, providerDir, dir) {
6621
+ const options = { env: hostEnv(), cwd: dir };
6622
+ const config = (key) => this.runGit(["config", "--get", key], options).then(
6623
+ (value) => value.trim(),
6624
+ () => ""
6625
+ );
6626
+ if (!await exists(path8.join(dir, "HEAD")) || await config(HOST_CONFIG)) return;
6627
+ const cloneUrl = await config("remote.origin.url");
6628
+ const fullPath = path8.relative(providerDir, dir).split(path8.sep).join("/");
6629
+ const target = this.repoDir({ provider, fullPath, cloneUrl });
6630
+ if (await exists(target)) {
6631
+ throw new Error(`${target} already exists`);
6632
+ }
6633
+ const legacyBranches = path8.join(
6634
+ this.workspaceRoot,
6635
+ BRANCHES_DIR,
6636
+ provider,
6637
+ ...fullPath.split("/")
6638
+ );
6639
+ const targetBranches = path8.join(
6640
+ this.workspaceRoot,
6641
+ BRANCHES_DIR,
6642
+ path8.relative(this.workspaceRoot, target)
6643
+ );
6644
+ const worktrees = (await this.runGit(["worktree", "list", "--porcelain"], options)).split("\n").filter((line) => line.startsWith("worktree ")).map((line) => line.slice("worktree ".length)).slice(1);
6645
+ await mkdir3(path8.dirname(target), { recursive: true });
6646
+ await rename3(dir, target);
6647
+ const repaired = { env: hostEnv(), cwd: target };
6648
+ try {
6649
+ await this.runGit(["config", HOST_CONFIG, hostDir(cloneUrl)], repaired);
6650
+ } catch (error) {
6651
+ await rename3(target, dir).catch(() => void 0);
6652
+ throw error;
6653
+ }
6654
+ const moved = [];
6655
+ let moveError;
6656
+ for (const worktree of worktrees) {
6657
+ if (!await exists(worktree)) continue;
6658
+ const relative2 = path8.relative(legacyBranches, worktree);
6659
+ if (relative2.startsWith("..") || path8.isAbsolute(relative2)) {
6660
+ moved.push(worktree);
6661
+ continue;
6662
+ }
6663
+ const to = path8.join(targetBranches, relative2);
6664
+ try {
6665
+ await mkdir3(path8.dirname(to), { recursive: true });
6666
+ await rename3(worktree, to);
6667
+ moved.push(to);
6668
+ } catch (error) {
6669
+ moveError ??= error;
6670
+ moved.push(worktree);
6671
+ }
6672
+ }
6673
+ if (moved.length > 0) await this.runGit(["worktree", "repair", ...moved], repaired);
6674
+ if (moveError !== void 0) throw moveError;
6675
+ await this.removeEmptyDirs(path8.dirname(dir), providerDir);
6676
+ await this.removeEmptyDirs(legacyBranches, path8.join(this.workspaceRoot, BRANCHES_DIR));
6677
+ this.logger?.info({ from: dir, to: target, worktrees: moved }, "moved a cached repository");
6678
+ }
6679
+ /** Removes `dir` and its parents up to (not including) `stop`, while they're empty. */
6680
+ async removeEmptyDirs(dir, stop) {
6681
+ for (let current = dir; current.startsWith(stop + path8.sep); current = path8.dirname(current)) {
6682
+ if ((await readdir(current).catch(() => null))?.length !== 0) return;
6683
+ await rmdir(current).catch(() => void 0);
6684
+ }
6685
+ }
6550
6686
  async checkBranchName(branch) {
6551
6687
  const valid = await runGit(["check-ref-format", "--branch", branch], {
6552
6688
  env: hostEnv(),
@@ -6784,6 +6920,7 @@ Stash ${entry.sha} from ${entry.date}, made on top of ${base}.`;
6784
6920
  options
6785
6921
  );
6786
6922
  await this.runGit(["config", "remote.origin.fetch", FETCH_REFSPEC], { ...options, cwd: tmp });
6923
+ await this.runGit(["config", HOST_CONFIG, hostDir(repo.cloneUrl)], { ...options, cwd: tmp });
6787
6924
  await this.runGit(["fetch", "--quiet", "--filter=blob:none", "--no-tags", "origin"], {
6788
6925
  ...options,
6789
6926
  cwd: tmp
@@ -7649,10 +7786,12 @@ function createQueueReceiver(server, region, currentToken) {
7649
7786
 
7650
7787
  // src/update.ts
7651
7788
  import { execFile as execFile2 } from "node:child_process";
7652
- import { readFile as readFile6 } from "node:fs/promises";
7789
+ import { randomUUID as randomUUID3 } from "node:crypto";
7790
+ import { readFile as readFile6, rm as rm8 } from "node:fs/promises";
7653
7791
  import path9 from "node:path";
7654
7792
  import { z as z14 } from "zod";
7655
7793
  var UPDATE_STATE_FILE = "update-state.json";
7794
+ var UPDATE_REQUEST_FILE = "update-request.json";
7656
7795
  var MAX_STARTS_SINCE_PENDING = 3;
7657
7796
  var CONFIRM_AFTER_MS = 6e4;
7658
7797
  var DRAIN_TIMEOUT_MS = 2 * 60 * 60 * 1e3;
@@ -7667,14 +7806,51 @@ var UpdateStateFile = z14.object({
7667
7806
  startsSincePending: z14.int().min(0).default(0),
7668
7807
  failed: z14.array(z14.string()).default([]),
7669
7808
  /** Why the last update or rollback failed. */
7670
- lastError: z14.string().nullable().default(null)
7809
+ lastError: z14.string().nullable().default(null),
7810
+ /** The control panel's last `updateRequest` acted on (reported back so it's cleared). */
7811
+ handledRequestId: z14.string().nullable().default(null)
7671
7812
  });
7672
7813
  function emptyState() {
7673
- return { previous: null, pending: null, startsSincePending: 0, failed: [], lastError: null };
7814
+ return {
7815
+ previous: null,
7816
+ pending: null,
7817
+ startsSincePending: 0,
7818
+ failed: [],
7819
+ lastError: null,
7820
+ handledRequestId: null
7821
+ };
7674
7822
  }
7675
7823
  function updateStatePath(configPath) {
7676
7824
  return path9.join(path9.dirname(configPath), UPDATE_STATE_FILE);
7677
7825
  }
7826
+ function updateRequestPath(configPath) {
7827
+ return path9.join(path9.dirname(configPath), UPDATE_REQUEST_FILE);
7828
+ }
7829
+ var LocalUpdateRequest = z14.object({
7830
+ id: z14.string(),
7831
+ requestedAt: z14.string()
7832
+ });
7833
+ async function writeUpdateRequest(file, now = /* @__PURE__ */ new Date()) {
7834
+ const request = { id: randomUUID3(), requestedAt: now.toISOString() };
7835
+ await writePrivateJson(file, request);
7836
+ return request;
7837
+ }
7838
+ async function readUpdateRequest(file) {
7839
+ let text;
7840
+ try {
7841
+ text = await readFile6(file, "utf8");
7842
+ } catch (error) {
7843
+ if (error.code === "ENOENT") return null;
7844
+ throw error;
7845
+ }
7846
+ try {
7847
+ const parsed = LocalUpdateRequest.safeParse(JSON.parse(text));
7848
+ if (parsed.success) return parsed.data;
7849
+ } catch {
7850
+ }
7851
+ await rm8(file, { force: true });
7852
+ return null;
7853
+ }
7678
7854
  async function readUpdateState(file) {
7679
7855
  let text;
7680
7856
  try {
@@ -7695,6 +7871,18 @@ function writeUpdateState(file, state) {
7695
7871
  }
7696
7872
  function npmInstaller(env = process.env) {
7697
7873
  return {
7874
+ latest: () => new Promise((resolve2, reject) => {
7875
+ execFile2(
7876
+ "npm",
7877
+ ["view", AGENT_PACKAGE, "version"],
7878
+ { env, timeout: 6e4 },
7879
+ (error, stdout, stderr) => {
7880
+ if (!error) return resolve2(String(stdout).trim());
7881
+ const tail5 = String(stderr).trim().split("\n").slice(-5).join("\n");
7882
+ reject(new Error(`npm view ${AGENT_PACKAGE} version failed: ${tail5 || error.message}`));
7883
+ }
7884
+ );
7885
+ }),
7698
7886
  install: (version) => new Promise((resolve2, reject) => {
7699
7887
  execFile2(
7700
7888
  "npm",
@@ -7728,6 +7916,8 @@ var SelfUpdater = class {
7728
7916
  target = null;
7729
7917
  /** Start of the current run of successful heartbeats while confirming. */
7730
7918
  okSince = null;
7919
+ /** A heartbeat is being handled (they're not awaited, so the next may come meanwhile). */
7920
+ busy = false;
7731
7921
  now;
7732
7922
  drainTimeoutMs;
7733
7923
  confirmAfterMs;
@@ -7786,26 +7976,86 @@ var SelfUpdater = class {
7786
7976
  return {
7787
7977
  selfUpdate: this.support,
7788
7978
  update,
7789
- failedVersions: this.state.failed.slice(-FAILED_VERSIONS_KEPT)
7979
+ failedVersions: this.state.failed.slice(-FAILED_VERSIONS_KEPT),
7980
+ handledUpdateRequestId: this.state.handledRequestId
7790
7981
  };
7791
7982
  }
7792
7983
  /**
7793
7984
  * Called after every heartbeat: `null` when it failed. Confirms a pending
7794
- * version after `confirmAfterMs` of successful heartbeats, and starts an
7795
- * update when the desired version calls for one.
7985
+ * version after `confirmAfterMs` of successful heartbeats, then starts an
7986
+ * update when one was asked for or the desired version calls for one.
7796
7987
  */
7797
7988
  async onHeartbeat(response, daemon) {
7798
7989
  if (!response) {
7799
7990
  this.okSince = null;
7800
7991
  return;
7801
7992
  }
7802
- if (this.phase === "confirming") {
7803
- this.okSince ??= this.now();
7804
- if (this.now() - this.okSince < this.confirmAfterMs) return;
7805
- await this.confirm();
7993
+ if (this.busy) return;
7994
+ this.busy = true;
7995
+ try {
7996
+ if (this.phase === "confirming") {
7997
+ this.okSince ??= this.now();
7998
+ if (this.now() - this.okSince < this.confirmAfterMs) return;
7999
+ await this.confirm();
8000
+ }
8001
+ if (this.phase !== "idle") return;
8002
+ if (await this.onRequest(response, daemon)) return;
8003
+ const version = this.wantedVersion(response.desiredVersion);
8004
+ if (version) await this.update(version, daemon);
8005
+ } finally {
8006
+ this.busy = false;
7806
8007
  }
7807
- const version = this.wantedVersion(response.desiredVersion);
7808
- if (version) await this.update(version, daemon);
8008
+ }
8009
+ /**
8010
+ * Acts on an update the control panel or the host asked for; false when
8011
+ * none was. The request is handled (reported, or its file removed) before
8012
+ * anything is installed, so a failing one isn't retried.
8013
+ */
8014
+ async onRequest(response, daemon) {
8015
+ const fromPanel = response.updateRequest && response.updateRequest.id !== this.state.handledRequestId ? response.updateRequest : null;
8016
+ const local = !fromPanel && this.options.requestPath ? await readUpdateRequest(this.options.requestPath) : null;
8017
+ if (!fromPanel && !local) return false;
8018
+ const log = this.options.logger;
8019
+ if (fromPanel) this.state.handledRequestId = fromPanel.id;
8020
+ else await rm8(this.options.requestPath, { force: true });
8021
+ const source = fromPanel ? "the control panel" : "omniralph-agent update";
8022
+ if (!this.options.underPm2) {
8023
+ this.state.lastError = `An update was requested (${source}), but this agent isn't running under pm2, so it can't update itself`;
8024
+ log.warn({ source }, "an update was requested, but only agents under pm2 update themselves");
8025
+ await this.save();
8026
+ return true;
8027
+ }
8028
+ let version = fromPanel?.version ?? response.desiredVersion;
8029
+ if (!version) {
8030
+ try {
8031
+ if (!this.options.installer.latest) throw new Error("no way to look it up");
8032
+ version = await this.options.installer.latest();
8033
+ } catch (error) {
8034
+ this.state.lastError = `An update was requested, but reading the latest version failed: ${errorMessage(error)}`;
8035
+ log.error(
8036
+ { err: error, source },
8037
+ "reading the latest version for a requested update failed"
8038
+ );
8039
+ await this.save();
8040
+ return true;
8041
+ }
8042
+ }
8043
+ if (!AgentVersion.safeParse(version).success) {
8044
+ this.state.lastError = `An update was requested, but ${JSON.stringify(version.slice(0, 64))} isn't a version`;
8045
+ await this.save();
8046
+ return true;
8047
+ }
8048
+ if (version === this.options.runningVersion) {
8049
+ log.info({ version, source }, "an update was requested; already running that version");
8050
+ await this.save();
8051
+ return true;
8052
+ }
8053
+ this.state.failed = this.state.failed.filter((failed) => failed !== version);
8054
+ this.state.lastError = null;
8055
+ await this.save();
8056
+ log.info({ version, source }, "an update was requested");
8057
+ await this.update(version, daemon);
8058
+ return true;
7809
8059
  }
7810
8060
  /** The version to update to now, or null. */
7811
8061
  wantedVersion(desired) {
@@ -7855,10 +8105,10 @@ var SelfUpdater = class {
7855
8105
  return;
7856
8106
  }
7857
8107
  this.state = {
8108
+ ...this.state,
7858
8109
  previous: this.options.runningVersion,
7859
8110
  pending: version,
7860
8111
  startsSincePending: 0,
7861
- failed: this.state.failed,
7862
8112
  lastError: null
7863
8113
  };
7864
8114
  await this.save();
@@ -7892,6 +8142,9 @@ Commands:
7892
8142
  --workspace-root <dir> Repo cache directory (default: ~/.omniralph/repos)
7893
8143
  start Run the agent daemon
7894
8144
  --healthz-port <port> Serve GET /healthz on 127.0.0.1:<port>
8145
+ update Ask the running agent (under pm2) to update with its next heartbeat:
8146
+ to the desired version, else the latest on npm, even one that
8147
+ failed before
7895
8148
  git-credential Git credential helper for job git commands (\`get\` only; reads
7896
8149
  OMNIRALPH_JOB_TOKEN, set by the agent for in-job processes)
7897
8150
 
@@ -7948,6 +8201,8 @@ ${USAGE}`);
7948
8201
  return await runEnroll(values, configPath, deps);
7949
8202
  case "start":
7950
8203
  return await runStart(values, configPath, deps);
8204
+ case "update":
8205
+ return await runUpdate(configPath, deps);
7951
8206
  case "git-credential":
7952
8207
  return await runGitCredential(
7953
8208
  positionals[1],
@@ -8018,6 +8273,19 @@ Run 'omniralph-agent start' to start the agent.
8018
8273
  );
8019
8274
  return 0;
8020
8275
  }
8276
+ async function runUpdate(configPath, deps) {
8277
+ await readConfig(configPath);
8278
+ const file = updateRequestPath(configPath);
8279
+ await writeUpdateRequest(file, deps.now ? new Date(deps.now()) : void 0);
8280
+ deps.io.stdout(
8281
+ `Update requested (${file}).
8282
+ The running agent picks it up with its next heartbeat: it stops taking jobs, lets running ones
8283
+ finish, installs the desired version (or the latest on npm when none is set) and restarts.
8284
+ Only agents under pm2 update themselves; others log a warning and keep running.
8285
+ `
8286
+ );
8287
+ return 0;
8288
+ }
8021
8289
  async function runStart(values, configPath, deps) {
8022
8290
  let healthzPort;
8023
8291
  if (values["healthz-port"] !== void 0) {
@@ -8033,6 +8301,7 @@ async function runStart(values, configPath, deps) {
8033
8301
  const version = deps.version ?? AGENT_VERSION;
8034
8302
  const updater = new SelfUpdater({
8035
8303
  statePath: updateStatePath(configPath),
8304
+ requestPath: updateRequestPath(configPath),
8036
8305
  runningVersion: version,
8037
8306
  underPm2: runningUnderPm2(deps.env),
8038
8307
  installer: deps.installer ?? npmInstaller(deps.env),