@omniralph/agent 0.4.0 → 0.6.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(),
@@ -852,7 +860,13 @@ var RalphPrepareResult = z10.object({
852
860
  headSha: CommitSha,
853
861
  durationMs: z10.int().min(0)
854
862
  });
863
+ var RALPH_REQUEST_SOURCES = ["linear", "chat"];
855
864
  var RalphRequestPayload = RalphJobBase.extend({
865
+ /**
866
+ * Where the requests come from. Older control panels don't send it (Linear);
867
+ * older agents ignore it and prompt as for Linear.
868
+ */
869
+ source: z10.enum(RALPH_REQUEST_SOURCES).default("linear"),
856
870
  epic: RalphIssue.extend({
857
871
  kind: z10.enum(RALPH_EPIC_KINDS).default("children"),
858
872
  url: z10.url().nullable().default(null),
@@ -877,7 +891,12 @@ var RalphRequestPayload = RalphJobBase.extend({
877
891
  */
878
892
  resumeSessionId: z10.string().min(1).max(200).nullable().default(null),
879
893
  /** Every Linear attachment of the run (the epic, its stories and the thread). */
880
- attachments: RalphAttachments
894
+ attachments: RalphAttachments,
895
+ /**
896
+ * `/ship`: the session prepares one commit and describes it; the job
897
+ * commits, pushes the branch, and opens the PR/MR when there is none.
898
+ */
899
+ ship: z10.boolean().default(false)
881
900
  });
882
901
  var RALPH_PULL_REQUEST_ACTIONS = ["open", "update", "ready"];
883
902
  var RalphPullRequestAction = z10.object({
@@ -903,6 +922,10 @@ var RalphRequestResult = z10.object({
903
922
  findings: z10.array(RalphFindingOutcome).max(50).optional(),
904
923
  /** What the session left uncommitted, stashed. */
905
924
  stashSha: CommitSha.optional(),
925
+ /** `/ship`: the commit the job made (absent when there was nothing to commit). */
926
+ commitSha: CommitSha.optional(),
927
+ /** `/ship`: whether the job pushed the branch. */
928
+ pushed: z10.boolean().optional(),
906
929
  usage: TokenUsage,
907
930
  durationMs: z10.int().min(0)
908
931
  });
@@ -963,6 +986,24 @@ var RalphCleanupResult = z10.object({
963
986
  handled: z10.int().min(0).default(0),
964
987
  durationMs: z10.int().min(0)
965
988
  });
989
+ var RalphPermissionRequest = z10.object({
990
+ /** Chosen by the agent; the answer is read back with it. */
991
+ requestId: z10.uuid(),
992
+ /** The tool, e.g. `Bash`. */
993
+ tool: z10.string().trim().min(1).max(200),
994
+ /** What the call does, e.g. the command. */
995
+ detail: z10.string().max(4e3).default(""),
996
+ /** Why Claude Code asks (its decision reason), if it said. */
997
+ reason: z10.string().max(1e3).optional(),
998
+ /** How long the agent waits for an answer before it denies the call. */
999
+ timeoutSeconds: z10.int().min(1).max(86400)
1000
+ });
1001
+ var RALPH_PERMISSION_STATUSES = ["pending", "allowed", "denied", "expired"];
1002
+ var RalphPermissionAnswer = z10.object({
1003
+ status: z10.enum(RALPH_PERMISSION_STATUSES),
1004
+ /** Who answered in Linear, when known. */
1005
+ answeredBy: z10.string().nullable().default(null)
1006
+ });
966
1007
  var RalphActivity = z10.object({
967
1008
  type: z10.enum(["thought", "action"]),
968
1009
  /** A thought's text, or an action's name (e.g. the tool). */
@@ -3314,6 +3355,73 @@ var RALPH_PREPARE_TOOL_POLICY = {
3314
3355
  };
3315
3356
  var RALPH_CLEANUP_TOOL_POLICY = RALPH_PREPARE_TOOL_POLICY;
3316
3357
 
3358
+ // src/capabilities/ralph/git-access.ts
3359
+ import { mkdtemp, rename, rm, writeFile } from "node:fs/promises";
3360
+ import { tmpdir } from "node:os";
3361
+ import path from "node:path";
3362
+
3363
+ // src/job-env.ts
3364
+ import { spawn } from "node:child_process";
3365
+ var JOB_TOKEN_ENV = "OMNIRALPH_JOB_TOKEN";
3366
+ var JOB_ID_ENV = "OMNIRALPH_JOB_ID";
3367
+ var SERVER_ENV = "OMNIRALPH_SERVER";
3368
+ var JOB_TOKEN_FILE_ENV = "OMNIRALPH_JOB_TOKEN_FILE";
3369
+ function jobProcessEnv(job, base = process.env, extra = {}) {
3370
+ const env = {};
3371
+ for (const [name, value] of Object.entries({ ...base, ...extra })) {
3372
+ if (name.startsWith("OMNIRALPH_")) continue;
3373
+ env[name] = value;
3374
+ }
3375
+ env[JOB_TOKEN_ENV] = job.jobToken;
3376
+ env[JOB_ID_ENV] = job.jobId;
3377
+ env[SERVER_ENV] = job.server;
3378
+ return env;
3379
+ }
3380
+ function withoutJobEnv(env) {
3381
+ return Object.fromEntries(Object.entries(env).filter(([name]) => !name.startsWith("OMNIRALPH_")));
3382
+ }
3383
+ function spawnJobProcess(job, command, args, options = {}) {
3384
+ return spawn(command, args, { ...options, env: jobProcessEnv(job, process.env, options.env) });
3385
+ }
3386
+
3387
+ // src/capabilities/ralph/git-access.ts
3388
+ var REFRESH_MS = 3e4;
3389
+ async function jobGitAccess(ctx, options = {}) {
3390
+ const dir = await mkdtemp(path.join(tmpdir(), "omniralph-job-token-"));
3391
+ const file = path.join(dir, "token");
3392
+ let written = ctx.jobToken();
3393
+ await writeFile(file, written, { mode: 384 });
3394
+ let pending = Promise.resolve();
3395
+ const timer = setInterval(() => {
3396
+ const token = ctx.jobToken();
3397
+ if (token === written) return;
3398
+ written = token;
3399
+ pending = pending.then(async () => {
3400
+ const tmp = `${file}.tmp`;
3401
+ await writeFile(tmp, token, { mode: 384 });
3402
+ await rename(tmp, file);
3403
+ }).catch(() => {
3404
+ });
3405
+ }, options.refreshMs ?? REFRESH_MS);
3406
+ timer.unref();
3407
+ return {
3408
+ env: {
3409
+ ...withoutJobEnv(ctx.env()),
3410
+ [SERVER_ENV]: ctx.server,
3411
+ [JOB_TOKEN_FILE_ENV]: file
3412
+ },
3413
+ async close() {
3414
+ clearInterval(timer);
3415
+ await pending;
3416
+ await rm(dir, { recursive: true, force: true });
3417
+ }
3418
+ };
3419
+ }
3420
+ async function sessionGitAccess(ctx, options = {}) {
3421
+ const access = await jobGitAccess(ctx, options);
3422
+ return { ...access, env: ctx.repos.gitEnv(access.env) };
3423
+ }
3424
+
3317
3425
  // src/capabilities/ralph/cleanup.ts
3318
3426
  var errorText = (error) => error instanceof Error ? error.message : String(error);
3319
3427
  async function runCleanup(job, ctx) {
@@ -3327,7 +3435,8 @@ async function runCleanup(job, ctx) {
3327
3435
  branch,
3328
3436
  action: action.kind
3329
3437
  });
3330
- const git2 = { env: ctx.env(), signal: ctx.signal };
3438
+ const access = await jobGitAccess(ctx);
3439
+ const git2 = { env: access.env, signal: ctx.signal };
3331
3440
  const result = (fields) => RalphCleanupResult.parse({ ...fields, durationMs: Date.now() - started });
3332
3441
  try {
3333
3442
  if (action.kind === "cleanup") {
@@ -3376,6 +3485,8 @@ async function runCleanup(job, ctx) {
3376
3485
  ctx.signal.throwIfAborted();
3377
3486
  log.warn({ err: error }, "cleanup failed");
3378
3487
  return result({ error: errorText(error).slice(0, 2e4) });
3488
+ } finally {
3489
+ await access.close();
3379
3490
  }
3380
3491
  }
3381
3492
 
@@ -3541,6 +3652,13 @@ var RequestAgentOutput = z11.object({
3541
3652
  ),
3542
3653
  waiting: z11.boolean().optional().describe(
3543
3654
  "True only when you are ending your turn to wait for background work you started; you are resumed when it finishes."
3655
+ ),
3656
+ commit: z11.object({
3657
+ message: z11.string().describe(
3658
+ "The commit message: a one-line subject (imperative mood, at most ~72 characters), a blank line, then a short body saying what changed and why."
3659
+ )
3660
+ }).optional().describe(
3661
+ "Only when shipping (`/ship`): the message the orchestrator commits the worktree's changes with before it pushes the branch."
3544
3662
  )
3545
3663
  });
3546
3664
  function isWaitingRequest(structured) {
@@ -3554,6 +3672,7 @@ function readRequestResult(structured) {
3554
3672
  const parsed = structured === void 0 ? void 0 : RequestAgentOutput.safeParse(structured);
3555
3673
  if (!parsed?.success) return { problem: problemWith(parsed?.error) };
3556
3674
  const { pullRequest } = parsed.data;
3675
+ const message = parsed.data.commit?.message.trim();
3557
3676
  const title = pullRequest?.title?.replace(/\s+/g, " ").trim();
3558
3677
  const body = pullRequest?.body?.trim();
3559
3678
  const findings = [];
@@ -3569,7 +3688,8 @@ function readRequestResult(structured) {
3569
3688
  ...pullRequest && {
3570
3689
  pullRequest: { action: pullRequest.action, ...title && { title }, ...body && { body } }
3571
3690
  },
3572
- ...findings.length > 0 && { findings: findings.slice(0, MAX_FINDING_OUTCOMES) }
3691
+ ...findings.length > 0 && { findings: findings.slice(0, MAX_FINDING_OUTCOMES) },
3692
+ ...message && { commit: { message } }
3573
3693
  }
3574
3694
  };
3575
3695
  }
@@ -3589,11 +3709,13 @@ function uniqueCommands(commands) {
3589
3709
  function normalizeCommand(cmd) {
3590
3710
  return cmd.trim().replace(/\s+/g, " ");
3591
3711
  }
3712
+ 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
3713
  var RALPH_SYSTEM_APPEND = `You are "Omniralph", an autonomous engineer working a Linear epic one user story at a time (the Ralph loop).
3593
3714
  - Work only on the single story you are given; other stories get their own sessions.
3594
3715
  - 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
3716
  - 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.`;
3717
+ - 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.
3718
+ ${GOOD_NEIGHBOR_RULE}`;
3597
3719
  var DEFAULT_STORY_TEMPLATE = `You are working through a PRD epic from Linear, one user story per session.
3598
3720
  Each session starts with a fresh context: the PRD, the progress log and the repository are your memory.
3599
3721
 
@@ -3857,15 +3979,28 @@ function buildDescribePrPrompt(ctx) {
3857
3979
  ].join("\n");
3858
3980
  }
3859
3981
  var REQUEST_HEADING = "## Request from your team";
3860
- function requestSystemAppend(historyRewrite = "when-asked") {
3982
+ function requestSystemAppend(historyRewrite = "when-asked", source = "linear", options = {}) {
3983
+ if (options.ship) return shipSystemAppend(source);
3861
3984
  const rewrite = historyRewrite === "when-asked" ? "- Don't rewrite history on your own initiative. When the request explicitly asks for it (rebase, squash, amend, reword), do it on the epic branch and push with `git push --force-with-lease`. That is allowed here." : "- Never rewrite published history or force-push in this repository. If asked to rebase or squash, explain that it is disabled here and offer to merge the base branch instead.";
3862
- return `You are "Omniralph", an autonomous engineer responding to a request in a Linear agent session about a PRD epic.
3985
+ const where = source === "chat" ? "a request in a chat thread about a repository" : "a request in a Linear agent session about a PRD epic";
3986
+ const thread = source === "chat" ? "the chat thread" : "the Linear thread";
3987
+ return `You are "Omniralph", an autonomous engineer responding to ${where}.
3863
3988
  - Do what the request asks. You may use git (commit, push) when the request calls for it.
3864
3989
  - Don't run \`gh\` or \`glab\`: they aren't set up here. Ask for pull/merge request changes (open, update, mark ready) through \`pullRequest\` in your structured result; the orchestrator makes them.
3865
3990
  - Only push the epic branch you are on. Never push to, or force-push, the base branch or any other branch.
3866
3991
  ${rewrite}
3867
- - 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.`;
3992
+ - The \`summary\` of your structured result is posted to ${thread}: summarise what you did, with links (e.g. the PR/MR URL).
3993
+ - 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.
3994
+ ${GOOD_NEIGHBOR_RULE}`;
3995
+ }
3996
+ function shipSystemAppend(source) {
3997
+ const where = source === "chat" ? "a chat thread" : "a Linear agent session";
3998
+ const thread = source === "chat" ? "the chat thread" : "the Linear thread";
3999
+ return `You are "Omniralph", an autonomous engineer shipping the work on a branch for ${where}.
4000
+ - Don't run \`git commit\`, \`git push\`, \`git stash pop\`/\`drop\` or any command that rewrites history: the orchestrator commits everything left in the worktree with the \`commit.message\` of your structured result, then pushes the branch.
4001
+ - Don't run \`gh\` or \`glab\`: they aren't set up here. Ask for pull/merge request changes (open, update) through \`pullRequest\` in your structured result; the orchestrator makes them after it pushes.
4002
+ - The \`summary\` of your structured result is posted to ${thread}.
4003
+ ${GOOD_NEIGHBOR_RULE}`;
3869
4004
  }
3870
4005
  function capitalize(text) {
3871
4006
  return text.charAt(0).toUpperCase() + text.slice(1);
@@ -3878,12 +4013,19 @@ function buildRequestPrompt(ctx) {
3878
4013
  ).length;
3879
4014
  const prd = epic.kind === "single" ? "" : epic.description.trim();
3880
4015
  const gates = uniqueCommands(ctx.qualityGates);
3881
- const lines = [
4016
+ const chat = ctx.source === "chat";
4017
+ const intro = chat ? [
4018
+ `You are working on a request from a chat thread: ${epic.title}.`,
4019
+ `It is implemented on branch \`${ctx.branch}\` (base \`${ctx.baseBranch}\`) in this git worktree.`
4020
+ ] : [
3882
4021
  `You are working on Linear ${epic.identifier}: ${epic.title}.`,
3883
4022
  epic.kind === "single" ? `It is implemented on branch \`${ctx.branch}\` (base \`${ctx.baseBranch}\`) in this git worktree.` : `It is a PRD epic implemented one story per commit on branch \`${ctx.branch}\` (base \`${ctx.baseBranch}\`) in this git worktree.`,
3884
4023
  "",
3885
4024
  `## Status: ${done}/${epic.stories.length} stories complete`,
3886
- formatStoryList(epic),
4025
+ formatStoryList(epic)
4026
+ ];
4027
+ const lines = [
4028
+ ...intro,
3887
4029
  "",
3888
4030
  `- Git remote \`origin\`: ${ctx.remoteUrl ? `\`${ctx.remoteUrl}\`` : "none configured"}`,
3889
4031
  `- ${capitalize(term)}: ${ctx.prUrl ?? "none opened yet"}`,
@@ -3899,24 +4041,53 @@ function buildRequestPrompt(ctx) {
3899
4041
  ...ctx.attachments ? [
3900
4042
  "",
3901
4043
  "## Attachments",
3902
- "Files attached in Linear. Open the ones relevant to the request with the Read tool (it shows images):",
4044
+ `Files attached ${chat ? "to the request" : "in Linear"}. Open the ones relevant to the request with the Read tool (it shows images):`,
3903
4045
  ctx.attachments
3904
4046
  ] : [],
3905
4047
  "",
3906
4048
  REQUEST_HEADING,
3907
4049
  ...ctx.requests.map((r) => `> ${r.trim().replace(/\n/g, "\n> ")}
3908
4050
  `),
4051
+ ...ctx.ship ? shipInstructions(ctx, term, gates) : requestInstructions(ctx, term),
4052
+ ...ctx.appendInstruction?.trim() ? ["", ctx.appendInstruction.trim()] : []
4053
+ ];
4054
+ return lines.join("\n").trim();
4055
+ }
4056
+ function requestInstructions(ctx, term) {
4057
+ const chat = ctx.source === "chat";
4058
+ const thread = chat ? "chat thread" : "Linear thread";
4059
+ return [
3909
4060
  "## How to handle it",
3910
4061
  "- This is a direct request, not a story. Do what it asks, and nothing beyond it.",
3911
4062
  `- You may commit, and push \`${ctx.branch}\` to \`origin\` (\`git push -u origin ${ctx.branch}\`), when the request calls for it. Never push to \`${ctx.baseBranch}\` or any other branch.`,
3912
4063
  (ctx.historyRewrite ?? "when-asked") === "when-asked" ? `- History rewrites are allowed on \`${ctx.branch}\` when the request asks for one. For a rebase: \`git fetch origin && git rebase origin/${ctx.baseBranch}\`, resolve conflicts, run the quality gates, then \`git push --force-with-lease origin ${ctx.branch}\`. Do the rebase that was asked for; don't substitute a merge. If the lease is rejected (someone else pushed), stop and report it instead of overwriting their work.` : `- History rewrites (rebase, squash, force-push) are disabled for this repository. If the request asks for one, say so and offer to merge \`${ctx.baseBranch}\` into \`${ctx.branch}\` instead.`,
3913
- ctx.remoteUrl ? `- For the ${term}, don't run \`gh\` or \`glab\`. Push \`${ctx.branch}\` first, then set \`pullRequest\` in your structured result: \`open\` opens it into \`${ctx.baseBranch}\` as a draft, \`update\` changes the open one's title or description, \`ready\` marks it ready for review. Give \`open\` a title summarising the change itself and a description of the deliverable written for reviewers who can't see Linear: what it does and why, notable changes, and any breaking changes or judgement calls. Don't list the user stories.` : "- There is no `origin` remote yet, so pushing or opening a pull/merge request isn't possible until one is added.",
4064
+ ctx.remoteUrl ? `- For the ${term}, don't run \`gh\` or \`glab\`. Push \`${ctx.branch}\` first, then set \`pullRequest\` in your structured result: \`open\` opens it into \`${ctx.baseBranch}\` as a draft, \`update\` changes the open one's title or description, \`ready\` marks it ready for review. Give \`open\` a title summarising the change itself and a description of the deliverable written for reviewers who can't see ${chat ? "the chat thread" : "Linear"}: what it does and why, notable changes, and any breaking changes or judgement calls.${chat ? "" : " Don't list the user stories."}` : "- There is no `origin` remote yet, so pushing or opening a pull/merge request isn't possible until one is added.",
3914
4065
  "- If you change code, run the quality gates and commit with a clear message.",
3915
4066
  "- If the request is ambiguous or can't be done (e.g. missing credentials), say exactly what's missing instead of guessing.",
3916
- `- Finish with a short summary for the Linear thread of what you did, including any ${term} URL, as the \`summary\` of your structured result.`,
3917
- ...ctx.appendInstruction?.trim() ? ["", ctx.appendInstruction.trim()] : []
4067
+ `- Finish with a short summary for the ${thread} of what you did, including any ${term} URL, as the \`summary\` of your structured result.`
4068
+ ];
4069
+ }
4070
+ function shipInstructions(ctx, term, gates) {
4071
+ const stashes = ctx.ship?.stashes ?? [];
4072
+ const chat = ctx.source === "chat";
4073
+ return [
4074
+ "## How to handle it",
4075
+ `This is \`/ship\`: the work on \`${ctx.branch}\` is to be committed, pushed and put up for review. You prepare the commit; the orchestrator makes it with your message, pushes \`${ctx.branch}\` to \`origin\` and makes the ${term} change you ask for. Don't commit or push yourself.`,
4076
+ "",
4077
+ "1. See what the worktree has: `git status` and `git diff` (uncommitted changes), and `git log --oneline origin/" + ctx.branch + "..HEAD` (commits not pushed yet; the ref may not exist if the branch was never pushed).",
4078
+ ...stashes.length > 0 ? [
4079
+ "2. Earlier request sessions on this branch left uncommitted work, which was stashed (newest first):",
4080
+ ...stashes.map((s) => ` - \`${s.sha}\` (${s.date}): ${s.label}`),
4081
+ " Review each with `git stash show -p --include-untracked <sha>` and bring back what belongs in this commit with `git stash apply <sha>`. Never `pop` or `drop` them: the stash list is shared with other worktrees."
4082
+ ] : ["2. No earlier request session left stashed work on this branch."],
4083
+ "3. If the request above says more than `/ship` (notes, a last fix), do that first.",
4084
+ gates.length > 0 ? `4. Run the quality gates (${gates.map((g) => `\`${g}\``).join(", ")}) and fix any failures.` : "4. Check that the change builds and its tests pass, as far as the repository lets you.",
4085
+ "5. Leave in the worktree only what belongs in the commit: everything left (including untracked files) is committed with `git add -A`. Delete scratch files; add generated ones to `.gitignore`.",
4086
+ "6. Report `commit.message` in your structured result: a one-line subject, a blank line, and a short body saying what changed and why. Leave `commit` out when there's nothing to commit (the orchestrator still pushes commits that aren't on `origin` yet).",
4087
+ ctx.prUrl ? `7. The ${term} is open (${ctx.prUrl}). If its title or description no longer match the branch, set \`pullRequest\` to \`update\` with a new title and description; otherwise leave \`pullRequest\` out.` : `7. No ${term} is open yet: set \`pullRequest\` to \`open\` with a title summarising the change itself and a description written for reviewers who can't see ${chat ? "the chat thread" : "Linear"} (what it does and why, notable changes, breaking changes or judgement calls).${chat ? "" : " Don't list the user stories."}`,
4088
+ "- If something stops you (failing gates you can't fix, a conflict, missing credentials), leave `commit` out and say exactly what's wrong in `summary`: nothing is committed or pushed then.",
4089
+ `- \`summary\` is posted to the ${chat ? "chat" : "Linear"} thread: say what is being committed and pushed, in a sentence or two.`
3918
4090
  ];
3919
- return lines.join("\n").trim();
3920
4091
  }
3921
4092
 
3922
4093
  // ../../packages/ralph/src/replies.ts
@@ -4156,6 +4327,7 @@ var BACKGROUND_WAIT_TIMEOUT_MS = 60 * 6e4;
4156
4327
  var WAIT_NUDGE_DELAY_MS = 3e4;
4157
4328
  var WAIT_NUDGE_TEXT = "Nothing is running in the background any more, so there is nothing left to wait for. Check the results of the background work you started, finish the task, and report your structured result.";
4158
4329
  var RATE_LIMIT_TEXT2 = /rate[_ ]limit|usage limit|\b429\b|too many requests/i;
4330
+ var PERMISSION_DENIED_TEXT = "A person had to approve this in Linear (the repository's Claude Code settings ask about it) and denied it or didn't answer in time. Don't retry it: carry on without it, or report what it blocks.";
4159
4331
  function retryAfter2(resetsAt) {
4160
4332
  if (resetsAt === void 0) return void 0;
4161
4333
  const ms = resetsAt < 1e12 ? resetsAt * 1e3 : resetsAt;
@@ -4171,7 +4343,7 @@ function resultUsage(message) {
4171
4343
  { inputTokens: 0, outputTokens: 0 }
4172
4344
  );
4173
4345
  }
4174
- function sessionOptions(request, abortController) {
4346
+ function sessionOptions(request, abortController, canUseTool) {
4175
4347
  return {
4176
4348
  ...narrowPermissions(
4177
4349
  sdkPermissions(request.policy)({ cwd: request.cwd, allowExploration: true }),
@@ -4185,7 +4357,8 @@ function sessionOptions(request, abortController) {
4185
4357
  ...request.additionalDirectories?.length ? { additionalDirectories: request.additionalDirectories } : {},
4186
4358
  persistSession: request.persistSession === true,
4187
4359
  ...request.resume && { resume: request.resume },
4188
- env: { ...request.env, CLAUDE_AGENT_SDK_CLIENT_APP: "omniralph-agent" }
4360
+ env: { ...request.env, CLAUDE_AGENT_SDK_CLIENT_APP: "omniralph-agent" },
4361
+ ...canUseTool && { canUseTool }
4189
4362
  };
4190
4363
  }
4191
4364
  var InputQueue = class {
@@ -4258,8 +4431,10 @@ async function runQuery(query, request, seen) {
4258
4431
  let idleTimer;
4259
4432
  const idleTimeoutMs = request.idleTimeoutMs ?? SESSION_IDLE_TIMEOUT_MS;
4260
4433
  const injectionIdleTimeoutMs = request.injectionIdleTimeoutMs ?? INJECTION_IDLE_TIMEOUT_MS;
4434
+ let asking = 0;
4261
4435
  const resetIdle = () => {
4262
4436
  clearTimeout(idleTimer);
4437
+ if (asking > 0) return;
4263
4438
  idleTimer = setTimeout(() => {
4264
4439
  idle = true;
4265
4440
  controller.abort(new Error("the session was idle"));
@@ -4346,9 +4521,35 @@ async function runQuery(query, request, seen) {
4346
4521
  }
4347
4522
  return void 0;
4348
4523
  };
4524
+ const askPermission = request.askPermission;
4525
+ const canUseTool = askPermission ? async (toolName, toolInput, options) => {
4526
+ asking++;
4527
+ clearTimeout(idleTimer);
4528
+ let allowed = false;
4529
+ try {
4530
+ const rule = options.matchedAskRule;
4531
+ const reason = [
4532
+ options.title ?? options.decisionReason,
4533
+ rule && `It matches \`${rule.toolName}${rule.ruleContent ? `(${rule.ruleContent})` : ""}\` in the ${rule.source} settings.`
4534
+ ].filter(Boolean).join("\n");
4535
+ allowed = await askPermission(
4536
+ { tool: toolName, input: toolInput, ...reason && { reason } },
4537
+ options.signal
4538
+ );
4539
+ } catch {
4540
+ allowed = false;
4541
+ } finally {
4542
+ asking--;
4543
+ if (!waiting) resetIdle();
4544
+ }
4545
+ return allowed ? { behavior: "allow", updatedInput: toolInput } : { behavior: "deny", message: PERMISSION_DENIED_TEXT };
4546
+ } : void 0;
4349
4547
  resetIdle();
4350
4548
  try {
4351
- const messages = query({ prompt: input, options: sessionOptions(request, controller) });
4549
+ const messages = query({
4550
+ prompt: input,
4551
+ options: sessionOptions(request, controller, canUseTool)
4552
+ });
4352
4553
  for await (const message of messages) {
4353
4554
  if (message.type === "system" && message.subtype === "background_tasks_changed") {
4354
4555
  live.clear();
@@ -4456,33 +4657,9 @@ async function runQuery(query, request, seen) {
4456
4657
  }
4457
4658
 
4458
4659
  // 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
- }
4660
+ import { mkdtemp as mkdtemp2, readFile as readFile2, rm as rm2, writeFile as writeFile3 } from "node:fs/promises";
4661
+ import { tmpdir as tmpdir2 } from "node:os";
4662
+ import path3 from "node:path";
4486
4663
 
4487
4664
  // src/workspace/git.ts
4488
4665
  import { spawn as spawn2 } from "node:child_process";
@@ -4597,8 +4774,8 @@ function runProcess(file, args, options) {
4597
4774
 
4598
4775
  // src/capabilities/ralph/attachments.ts
4599
4776
  import { existsSync } from "node:fs";
4600
- import { mkdir, readFile, writeFile } from "node:fs/promises";
4601
- import path from "node:path";
4777
+ import { mkdir, readFile, writeFile as writeFile2 } from "node:fs/promises";
4778
+ import path2 from "node:path";
4602
4779
  var ATTACHMENTS_DIR = ".attachments";
4603
4780
  var DOWNLOAD_TIMEOUT_MS = 12e4;
4604
4781
  async function readCapped(res, max) {
@@ -4649,14 +4826,14 @@ function controlPanelFetcher(options) {
4649
4826
  }
4650
4827
  function attachmentsDir(workspaceRoot, epicIdentifier) {
4651
4828
  const safe = epicIdentifier.replace(/[^A-Za-z0-9_-]/g, "_") || "epic";
4652
- return path.join(workspaceRoot, ATTACHMENTS_DIR, safe);
4829
+ return path2.join(workspaceRoot, ATTACHMENTS_DIR, safe);
4653
4830
  }
4654
4831
  async function collectAttachments(options) {
4655
4832
  const { dir, fetcher } = options;
4656
4833
  const max = options.max ?? MAX_ATTACHMENT_DOWNLOADS_PER_JOB;
4657
4834
  if (options.attachments.length === 0) return { dir, files: [] };
4658
4835
  await mkdir(dir, { recursive: true });
4659
- const indexPath = path.join(dir, ".index.json");
4836
+ const indexPath = path2.join(dir, ".index.json");
4660
4837
  let index = { files: {} };
4661
4838
  try {
4662
4839
  index = JSON.parse(await readFile(indexPath, "utf8"));
@@ -4670,8 +4847,8 @@ async function collectAttachments(options) {
4670
4847
  for (const attachment of options.attachments) {
4671
4848
  const entry = { id: attachment.id, title: attachment.title, sources: attachment.sources };
4672
4849
  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) });
4850
+ if (cached && existsSync(path2.join(dir, cached.file))) {
4851
+ files.push({ ...entry, path: path2.join(dir, cached.file) });
4675
4852
  continue;
4676
4853
  }
4677
4854
  if (fetched >= max) {
@@ -4690,9 +4867,9 @@ async function collectAttachments(options) {
4690
4867
  );
4691
4868
  if (!attachment.title) unnamed++;
4692
4869
  used.add(file);
4693
- await writeFile(path.join(dir, file), result.data);
4870
+ await writeFile2(path2.join(dir, file), result.data);
4694
4871
  index.files[attachment.id] = { file, contentType: result.contentType };
4695
- files.push({ ...entry, path: path.join(dir, file) });
4872
+ files.push({ ...entry, path: path2.join(dir, file) });
4696
4873
  }
4697
4874
  const failed = files.filter((f) => !f.path);
4698
4875
  const unreported = failed.filter((f) => !reported.has(f.id));
@@ -4701,7 +4878,7 @@ async function collectAttachments(options) {
4701
4878
  else reported.add(f.id);
4702
4879
  }
4703
4880
  index.reported = [...reported];
4704
- await writeFile(indexPath, JSON.stringify(index, null, 2));
4881
+ await writeFile2(indexPath, JSON.stringify(index, null, 2));
4705
4882
  if (failed.length > 0) {
4706
4883
  options.logger?.warn(
4707
4884
  { failed: failed.map((f) => ({ id: f.id, error: f.error })) },
@@ -4834,8 +5011,8 @@ async function runStory(job, ctx, options = {}) {
4834
5011
  ...options.fetch && { fetch: options.fetch }
4835
5012
  });
4836
5013
  const runSession = options.runSession ?? createSessionRunner();
4837
- const env = ctx.env();
4838
- const plainEnv = sessionEnv(env);
5014
+ const plainEnv = sessionEnv(ctx.env());
5015
+ const git2 = await jobGitAccess(ctx, { refreshMs: options.tokenRefreshMs });
4839
5016
  const prefix = stashPrefix(payload);
4840
5017
  const label = (reason) => `${prefix}${reason} (attempt ${payload.attempt})`;
4841
5018
  try {
@@ -4845,7 +5022,7 @@ async function runStory(job, ctx, options = {}) {
4845
5022
  branch: payload.branch,
4846
5023
  baseBranch: payload.baseBranch,
4847
5024
  ...payload.settings.setupCommand && { setupCommand: payload.settings.setupCommand },
4848
- env,
5025
+ env: git2.env,
4849
5026
  signal: ctx.signal
4850
5027
  },
4851
5028
  async (worktree) => {
@@ -4873,10 +5050,10 @@ async function runStory(job, ctx, options = {}) {
4873
5050
  logger: log,
4874
5051
  report: (body) => relay.post({ type: "thought", body, ephemeral: false })
4875
5052
  });
4876
- const progressDir = await mkdtemp(path2.join(tmpdir(), "omniralph-progress-"));
4877
- const progressFile = path2.join(progressDir, "progress.md");
5053
+ const progressDir = await mkdtemp2(path3.join(tmpdir2(), "omniralph-progress-"));
5054
+ const progressFile = path3.join(progressDir, "progress.md");
4878
5055
  try {
4879
- await writeFile2(progressFile, payload.progress);
5056
+ await writeFile3(progressFile, payload.progress);
4880
5057
  const { epic, story } = promptEpic(payload);
4881
5058
  const prompt = buildStoryPrompt({
4882
5059
  epic,
@@ -5057,11 +5234,12 @@ ${tail(errorText2(error), MAX_FEEDBACK_OUTPUT)}
5057
5234
  if (ctx.signal.aborted) await stashQuietly(worktree, label("stopped"), log);
5058
5235
  throw error;
5059
5236
  } finally {
5060
- await rm(progressDir, { recursive: true, force: true });
5237
+ await rm2(progressDir, { recursive: true, force: true });
5061
5238
  }
5062
5239
  }
5063
5240
  );
5064
5241
  } finally {
5242
+ await git2.close();
5065
5243
  await relay.flush();
5066
5244
  }
5067
5245
  }
@@ -5402,42 +5580,119 @@ import { mkdtemp as mkdtemp3, rm as rm3, writeFile as writeFile4 } from "node:fs
5402
5580
  import { tmpdir as tmpdir3 } from "node:os";
5403
5581
  import path4 from "node:path";
5404
5582
 
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 });
5583
+ // src/capabilities/ralph/permissions.ts
5584
+ import { randomUUID as randomUUID2 } from "node:crypto";
5585
+ import { z as z13 } from "zod";
5586
+ var PERMISSION_TIMEOUT_MS = 30 * 6e4;
5587
+ var PERMISSION_POLL_INTERVAL_MS = 5e3;
5588
+ var REQUEST_TIMEOUT_MS2 = 3e4;
5589
+ function sleep(ms, signal) {
5590
+ return new Promise((resolve2, reject) => {
5591
+ if (signal.aborted) {
5592
+ reject(signal.reason);
5593
+ return;
5438
5594
  }
5439
- };
5595
+ const onAbort = () => {
5596
+ clearTimeout(timer);
5597
+ reject(signal.reason);
5598
+ };
5599
+ const timer = setTimeout(() => {
5600
+ signal.removeEventListener("abort", onAbort);
5601
+ resolve2();
5602
+ }, ms);
5603
+ signal.addEventListener("abort", onAbort, { once: true });
5604
+ });
5440
5605
  }
5606
+ var PermissionRelay = class {
5607
+ constructor(options) {
5608
+ this.options = options;
5609
+ this.base = `${options.server}/api/agent/jobs/${encodeURIComponent(options.jobId)}/permissions`;
5610
+ }
5611
+ options;
5612
+ chain = Promise.resolve();
5613
+ base;
5614
+ /** Whether the call may run. */
5615
+ ask(call, signal) {
5616
+ const turn = this.chain.then(() => this.askNow(call, signal));
5617
+ this.chain = turn.catch(() => {
5618
+ });
5619
+ return turn;
5620
+ }
5621
+ async askNow(call, signal) {
5622
+ if (signal.aborted) return false;
5623
+ const log = this.options.logger.child({ tool: call.tool });
5624
+ const requestId = randomUUID2();
5625
+ const timeoutMs = this.options.timeoutMs ?? PERMISSION_TIMEOUT_MS;
5626
+ try {
5627
+ await postJson(
5628
+ this.options.fetch ?? fetch,
5629
+ this.base,
5630
+ {
5631
+ requestId,
5632
+ tool: call.tool,
5633
+ detail: toolParameter(call.input),
5634
+ ...call.reason && { reason: call.reason.slice(0, 1e3) },
5635
+ timeoutSeconds: Math.max(1, Math.ceil(timeoutMs / 1e3))
5636
+ },
5637
+ z13.unknown(),
5638
+ this.options.jobToken()
5639
+ );
5640
+ } catch (error) {
5641
+ log.warn({ err: error }, "asking for a tool permission failed; denying the call");
5642
+ return false;
5643
+ }
5644
+ log.info({ requestId }, "asked for a tool permission in Linear");
5645
+ const deadline = Date.now() + timeoutMs;
5646
+ const interval = this.options.pollIntervalMs ?? PERMISSION_POLL_INTERVAL_MS;
5647
+ let failures = 0;
5648
+ try {
5649
+ while (Date.now() < deadline) {
5650
+ await sleep(Math.min(interval, Math.max(0, deadline - Date.now())), signal);
5651
+ let answer;
5652
+ try {
5653
+ answer = await this.read(requestId);
5654
+ failures = 0;
5655
+ } catch (error) {
5656
+ if (++failures >= 10) throw error;
5657
+ continue;
5658
+ }
5659
+ if (answer.status === "pending") continue;
5660
+ log.info({ requestId, status: answer.status }, "tool permission answered");
5661
+ return answer.status === "allowed";
5662
+ }
5663
+ log.info({ requestId }, "nobody answered the tool permission in time; denying the call");
5664
+ } catch (error) {
5665
+ if (!signal.aborted) log.warn({ err: error }, "reading a tool permission failed; denying it");
5666
+ }
5667
+ await this.close(requestId, log);
5668
+ return false;
5669
+ }
5670
+ async read(requestId) {
5671
+ const res = await (this.options.fetch ?? fetch)(
5672
+ `${this.base}/${encodeURIComponent(requestId)}`,
5673
+ {
5674
+ headers: { authorization: `Bearer ${this.options.jobToken()}` },
5675
+ redirect: "error",
5676
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS2)
5677
+ }
5678
+ );
5679
+ if (!res.ok) throw new Error(`reading the permission answer failed with ${res.status}`);
5680
+ return RalphPermissionAnswer.parse(await res.json());
5681
+ }
5682
+ /** Closes the question (best effort), so a late answer isn't taken for a live one. */
5683
+ async close(requestId, log) {
5684
+ try {
5685
+ await (this.options.fetch ?? fetch)(`${this.base}/${encodeURIComponent(requestId)}`, {
5686
+ method: "DELETE",
5687
+ headers: { authorization: `Bearer ${this.options.jobToken()}` },
5688
+ redirect: "error",
5689
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS2)
5690
+ });
5691
+ } catch (error) {
5692
+ log.warn({ err: error }, "closing a tool permission question failed");
5693
+ }
5694
+ }
5695
+ };
5441
5696
 
5442
5697
  // src/capabilities/ralph/request.ts
5443
5698
  var MAX_TEXT2 = 2e4;
@@ -5497,6 +5752,19 @@ async function runRequest(job, ctx, options = {}) {
5497
5752
  logger: log,
5498
5753
  ...options.fetch && { fetch: options.fetch }
5499
5754
  });
5755
+ const permissions = new PermissionRelay({
5756
+ server: ctx.server,
5757
+ jobId: job.id,
5758
+ jobToken: ctx.jobToken,
5759
+ logger: log,
5760
+ ...options.fetch && { fetch: options.fetch },
5761
+ ...options.permissionTimeoutMs !== void 0 && {
5762
+ timeoutMs: options.permissionTimeoutMs
5763
+ },
5764
+ ...options.permissionPollIntervalMs !== void 0 && {
5765
+ pollIntervalMs: options.permissionPollIntervalMs
5766
+ }
5767
+ });
5500
5768
  const runSession = options.runSession ?? createSessionRunner();
5501
5769
  const env = ctx.env();
5502
5770
  const git2 = await sessionGitAccess(ctx);
@@ -5512,7 +5780,7 @@ async function runRequest(job, ctx, options = {}) {
5512
5780
  signal: ctx.signal
5513
5781
  },
5514
5782
  async (worktree) => {
5515
- const leftover = await worktree.stashWork(label("pre-run"));
5783
+ const leftover = payload.ship ? null : await worktree.stashWork(label("pre-run"));
5516
5784
  if (leftover) {
5517
5785
  log.info({ stash: leftover }, "stashed leftover work");
5518
5786
  relay.post({
@@ -5539,9 +5807,11 @@ async function runRequest(job, ctx, options = {}) {
5539
5807
  const progressFile = path4.join(progressDir, "progress.md");
5540
5808
  try {
5541
5809
  await writeFile4(progressFile, payload.progress);
5810
+ const shipStashes = payload.ship ? await requestStashes(worktree, payload) : [];
5542
5811
  const prompt = buildRequestPrompt({
5543
5812
  epic: requestEpic(payload),
5544
5813
  requests: payload.requests.map((r) => r.text),
5814
+ source: payload.source,
5545
5815
  branch: payload.branch,
5546
5816
  baseBranch: payload.baseBranch,
5547
5817
  remoteUrl: payload.repository.cloneUrl,
@@ -5553,13 +5823,16 @@ async function runRequest(job, ctx, options = {}) {
5553
5823
  ...attachments.prompt && { attachments: attachments.prompt },
5554
5824
  ...payload.settings.appendInstruction && {
5555
5825
  appendInstruction: payload.settings.appendInstruction
5556
- }
5826
+ },
5827
+ ...payload.ship && { ship: { stashes: shipStashes } }
5557
5828
  });
5558
5829
  const request = {
5559
5830
  prompt,
5560
5831
  cwd: worktree.path,
5561
5832
  policy: RALPH_TOOL_POLICY,
5562
- systemAppend: requestSystemAppend(payload.historyRewrite),
5833
+ systemAppend: requestSystemAppend(payload.historyRewrite, payload.source, {
5834
+ ship: payload.ship
5835
+ }),
5563
5836
  outputSchema: REQUEST_OUTPUT_SCHEMA,
5564
5837
  isWaiting: isWaitingRequest,
5565
5838
  model: payload.settings.model ?? DEFAULT_STORY_MODEL,
@@ -5581,7 +5854,9 @@ async function runRequest(job, ctx, options = {}) {
5581
5854
  // Replies from the Linear thread reach the live session (see `jobMessages`).
5582
5855
  onInjector: (inject) => ctx.setMessageInjector?.(inject),
5583
5856
  // Follow-ups continue this conversation, like Cyrus resuming its Claude session.
5584
- persistSession: true
5857
+ persistSession: true,
5858
+ // The repository's Claude Code settings may `ask` about calls (e.g. `git commit`).
5859
+ askPermission: (call, signal) => permissions.ask(call, signal)
5585
5860
  };
5586
5861
  const resume = payload.resumeSessionId ?? void 0;
5587
5862
  let session = await runSession({ ...request, ...resume && { resume } });
@@ -5601,15 +5876,22 @@ async function runRequest(job, ctx, options = {}) {
5601
5876
  Math.min(Math.max(seconds, 1), MAX_LEASE_SECONDS)
5602
5877
  );
5603
5878
  }
5604
- const stashSha = await stashQuietly2(worktree, label("unfinished"), log);
5605
5879
  const read = session.stop === "completed" ? readRequestResult(session.structured) : void 0;
5880
+ const stoppedWaiting = session.stop === "completed" && isWaitingRequest(session.structured);
5881
+ const valid = read && !("problem" in read) && !stoppedWaiting ? read.result : void 0;
5882
+ const shipped = payload.ship && valid ? await ship(worktree, payload, valid, log) : void 0;
5883
+ const stashSha = await stashQuietly2(worktree, label("unfinished"), log);
5606
5884
  const base = {
5607
5885
  sessionId: session.sessionId ?? null,
5608
5886
  ...stashSha && { stashSha },
5887
+ ...shipped?.commitSha && { commitSha: shipped.commitSha },
5888
+ ...shipped && { pushed: shipped.pushed },
5609
5889
  usage: session.usage,
5610
5890
  durationMs: Date.now() - started
5611
5891
  };
5612
- const stoppedWaiting = session.stop === "completed" && isWaitingRequest(session.structured);
5892
+ if (shipped?.error) {
5893
+ return { ...base, summary: clip3(valid?.summary ?? ""), error: clip3(shipped.error) };
5894
+ }
5613
5895
  if (!read || "problem" in read || stoppedWaiting) {
5614
5896
  const why = stoppedWaiting ? `the session was stopped while it waited for background work: ${session.error ?? "it gave up waiting"}` : read && "problem" in read ? `it ended without a valid structured result (${read.problem})` : sessionError(session);
5615
5897
  return {
@@ -5625,19 +5907,16 @@ async function runRequest(job, ctx, options = {}) {
5625
5907
  },
5626
5908
  "request done"
5627
5909
  );
5910
+ const pullRequest = read.result.pullRequest ?? shipped?.pullRequest;
5628
5911
  return {
5629
5912
  ...base,
5630
5913
  summary: clip3(read.result.summary),
5631
5914
  error: null,
5632
- ...read.result.pullRequest && {
5915
+ ...pullRequest && {
5633
5916
  pullRequest: {
5634
- action: read.result.pullRequest.action,
5635
- ...read.result.pullRequest.title && {
5636
- title: clip3(read.result.pullRequest.title, 500)
5637
- },
5638
- ...read.result.pullRequest.body && {
5639
- body: clip3(read.result.pullRequest.body, 6e4)
5640
- }
5917
+ action: pullRequest.action,
5918
+ ...pullRequest.title && { title: clip3(pullRequest.title, 500) },
5919
+ ...pullRequest.body && { body: clip3(pullRequest.body, 6e4) }
5641
5920
  }
5642
5921
  },
5643
5922
  ...read.result.findings && {
@@ -5661,6 +5940,111 @@ async function runRequest(job, ctx, options = {}) {
5661
5940
  await relay.flush();
5662
5941
  }
5663
5942
  }
5943
+ async function requestStashes(worktree, payload) {
5944
+ const prefix = requestStashPrefix(payload);
5945
+ const entries = await worktree.listStashes();
5946
+ return entries.filter((e) => e.label.startsWith(prefix)).slice(0, 20).map((e) => ({ sha: e.sha, label: e.label, date: e.date }));
5947
+ }
5948
+ var FALLBACK_IDENTITY2 = ["-c", "user.name=Omniralph", "-c", "user.email=omniralph@localhost"];
5949
+ async function ship(worktree, payload, result, log) {
5950
+ const state = {};
5951
+ try {
5952
+ return await shipSteps(worktree, payload, result, log, state);
5953
+ } catch (error) {
5954
+ log.warn({ err: error }, "shipping failed");
5955
+ if (state.unpushedCommit) {
5956
+ await worktree.git(["reset", "--quiet", "HEAD~1"]).catch(() => {
5957
+ });
5958
+ }
5959
+ return {
5960
+ pushed: false,
5961
+ error: `shipping failed${state.unpushedCommit ? " (the commit was undone)" : ""}:
5962
+
5963
+ \`\`\`
5964
+ ${tail4(errorText3(error), 4e3)}
5965
+ \`\`\``
5966
+ };
5967
+ }
5968
+ }
5969
+ async function shipSteps(worktree, payload, result, log, state) {
5970
+ const git2 = (args) => worktree.git(args);
5971
+ const tryGit = (args) => git2(args).then(
5972
+ (out) => out.trim(),
5973
+ () => null
5974
+ );
5975
+ const remoteHead = () => tryGit(["rev-parse", "--verify", "--quiet", `refs/remotes/origin/${payload.branch}`]);
5976
+ let commitSha;
5977
+ await git2(["add", "-A"]);
5978
+ const staged = (await git2(["diff", "--cached", "--name-only"])).trim();
5979
+ if (staged) {
5980
+ const message = result.commit?.message;
5981
+ if (!message) {
5982
+ await git2(["reset", "--quiet"]);
5983
+ return {
5984
+ pushed: false,
5985
+ error: "the session left uncommitted changes but no commit message, so nothing was committed or pushed"
5986
+ };
5987
+ }
5988
+ const identity = await tryGit(["config", "--get", "user.email"]) ? [] : FALLBACK_IDENTITY2;
5989
+ try {
5990
+ await git2([...identity, "commit", "--quiet", "-m", message]);
5991
+ } catch (error) {
5992
+ await git2(["reset", "--quiet"]).catch(() => {
5993
+ });
5994
+ return {
5995
+ pushed: false,
5996
+ error: `committing the work failed (e.g. a git hook rejected it):
5997
+
5998
+ \`\`\`
5999
+ ${tail4(errorText3(error), 4e3)}
6000
+ \`\`\``
6001
+ };
6002
+ }
6003
+ state.unpushedCommit = "HEAD";
6004
+ commitSha = (await git2(["rev-parse", "HEAD"])).trim();
6005
+ state.unpushedCommit = commitSha;
6006
+ log.info({ commit: commitSha }, "committed the shipped work");
6007
+ }
6008
+ const head = (await git2(["rev-parse", "HEAD"])).trim();
6009
+ let pushed = false;
6010
+ if (await remoteHead() !== head) {
6011
+ try {
6012
+ await git2(["push", "--quiet", "-u", "origin", payload.branch]);
6013
+ delete state.unpushedCommit;
6014
+ pushed = true;
6015
+ log.info({ head }, "pushed the shipped branch");
6016
+ } catch (error) {
6017
+ if (commitSha) await git2(["reset", "--quiet", "HEAD~1"]).catch(() => {
6018
+ });
6019
+ delete state.unpushedCommit;
6020
+ return {
6021
+ pushed: false,
6022
+ error: `${commitSha ? "the work was committed, but pushing it failed, so the commit was undone" : "pushing the branch failed"}:
6023
+
6024
+ \`\`\`
6025
+ ${tail4(errorText3(error), 4e3)}
6026
+ \`\`\``
6027
+ };
6028
+ }
6029
+ }
6030
+ let pullRequest;
6031
+ if (!payload.prUrl && !result.pullRequest) {
6032
+ const ahead = await tryGit(["rev-list", "--count", `origin/${payload.baseBranch}..HEAD`]);
6033
+ if (ahead !== null && Number(ahead) > 0) {
6034
+ const [subject, ...rest] = (result.commit?.message ?? "").split("\n");
6035
+ const body = rest.join("\n").trim();
6036
+ pullRequest = {
6037
+ action: "open",
6038
+ ...subject?.trim() && { title: subject.trim() },
6039
+ ...body && { body }
6040
+ };
6041
+ }
6042
+ }
6043
+ return { ...commitSha && { commitSha }, pushed, ...pullRequest && { pullRequest } };
6044
+ }
6045
+ function errorText3(error) {
6046
+ return error instanceof Error ? error.message : String(error);
6047
+ }
5664
6048
  async function stashQuietly2(worktree, label, log) {
5665
6049
  try {
5666
6050
  const sha = await worktree.stashWork(label, { signal: null });
@@ -6040,13 +6424,13 @@ import { randomBytes } from "node:crypto";
6040
6424
  import { mkdir as mkdir2, open, readFile as readFile3, rename as rename2, rm as rm6, stat } from "node:fs/promises";
6041
6425
  import { homedir } from "node:os";
6042
6426
  import path7 from "node:path";
6043
- import { z as z13 } from "zod";
6044
- var AgentConfig = z13.object({
6045
- server: z13.string(),
6046
- agentId: z13.string(),
6427
+ import { z as z14 } from "zod";
6428
+ var AgentConfig = z14.object({
6429
+ server: z14.string(),
6430
+ agentId: z14.string(),
6047
6431
  /** Rotated on every `/api/agent/token` call; reusing an old one revokes the agent. */
6048
- refreshToken: z13.string(),
6049
- workspaceRoot: z13.string()
6432
+ refreshToken: z14.string(),
6433
+ workspaceRoot: z14.string()
6050
6434
  });
6051
6435
  function defaultConfigPath() {
6052
6436
  return path7.join(homedir(), ".config", "omniralph", "agent.json");
@@ -6133,8 +6517,18 @@ async function writePrivateJson(file, value) {
6133
6517
  }
6134
6518
 
6135
6519
  // src/workspace/repoCache.ts
6136
- 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";
6520
+ import { randomUUID as randomUUID3 } from "node:crypto";
6521
+ import {
6522
+ chmod,
6523
+ mkdir as mkdir3,
6524
+ readdir,
6525
+ readFile as readFile4,
6526
+ rename as rename3,
6527
+ rm as rm7,
6528
+ rmdir,
6529
+ stat as stat2,
6530
+ writeFile as writeFile5
6531
+ } from "node:fs/promises";
6138
6532
  import path8 from "node:path";
6139
6533
  import lockfile from "proper-lockfile";
6140
6534
  var WORKTREES_DIR = ".worktrees";
@@ -6144,6 +6538,7 @@ var FETCH_REFSPEC = "+refs/heads/*:refs/remotes/origin/*";
6144
6538
  var SETUP_PENDING = "omniralph-setup-pending";
6145
6539
  var TMP_DIR = ".tmp";
6146
6540
  var PROVIDERS = ["github", "gitlab"];
6541
+ var HOST_CONFIG = "omniralph.hostDir";
6147
6542
  var PUSH_GUARD_HOOK = `#!/bin/sh
6148
6543
  # Installed by the Omniralph agent: a branch worktree only pushes its own branch.
6149
6544
  common=$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null) || exit 0
@@ -6162,7 +6557,7 @@ exit $status
6162
6557
  `;
6163
6558
  var SHA = /^[0-9a-f]{40}([0-9a-f]{24})?$/;
6164
6559
  var JOB_ID = /^[A-Za-z0-9_-]{1,64}$/;
6165
- var FALLBACK_IDENTITY2 = ["-c", "user.name=Omniralph", "-c", "user.email=omniralph@localhost"];
6560
+ var FALLBACK_IDENTITY3 = ["-c", "user.name=Omniralph", "-c", "user.email=omniralph@localhost"];
6166
6561
  var BranchDivergedError = class extends Error {
6167
6562
  constructor(branch, ahead, behind) {
6168
6563
  super(
@@ -6208,6 +6603,19 @@ function withCall(job, call) {
6208
6603
  if (!call || !("signal" in call)) return job;
6209
6604
  return { env: job.env, signal: call.signal ?? void 0 };
6210
6605
  }
6606
+ function hostDir(cloneUrl) {
6607
+ let url;
6608
+ try {
6609
+ url = new URL(cloneUrl);
6610
+ } catch {
6611
+ throw new Error(`invalid clone URL ${cloneUrl}`);
6612
+ }
6613
+ const dir = url.host || url.protocol.replace(/:$/, "");
6614
+ if (!dir || dir.startsWith(".") || /[/\\\0]/.test(dir)) {
6615
+ throw new Error(`invalid clone URL ${cloneUrl}`);
6616
+ }
6617
+ return dir;
6618
+ }
6211
6619
  function hostEnv() {
6212
6620
  return Object.fromEntries(
6213
6621
  Object.entries(process.env).filter(([name]) => !name.startsWith("OMNIRALPH_"))
@@ -6230,7 +6638,7 @@ var RepoCache = class {
6230
6638
  this.lockRetryMs = options.lockRetryMs ?? 250;
6231
6639
  this.lockStaleMs = options.lockStaleMs ?? 3e4;
6232
6640
  }
6233
- /** `<workspaceRoot>/<provider>/<repo path>` */
6641
+ /** `<workspaceRoot>/<provider>/<host>/<repo path>` (host with its port, if any) */
6234
6642
  repoDir(repo) {
6235
6643
  const segments = repo.fullPath.split("/");
6236
6644
  if (!PROVIDERS.includes(repo.provider) || segments.some(
@@ -6238,7 +6646,7 @@ var RepoCache = class {
6238
6646
  )) {
6239
6647
  throw new Error(`invalid repository path ${repo.provider}/${repo.fullPath}`);
6240
6648
  }
6241
- return path8.join(this.workspaceRoot, repo.provider, ...segments);
6649
+ return path8.join(this.workspaceRoot, repo.provider, hostDir(repo.cloneUrl), ...segments);
6242
6650
  }
6243
6651
  /**
6244
6652
  * Environment for git commands run by others in a worktree (e.g. the
@@ -6253,7 +6661,7 @@ var RepoCache = class {
6253
6661
  if (!JOB_ID.test(jobId)) throw new Error(`invalid job ID ${jobId}`);
6254
6662
  return path8.join(this.workspaceRoot, WORKTREES_DIR, jobId);
6255
6663
  }
6256
- /** `<workspaceRoot>/.branches/<provider>/<repo path>/<branch with "/" → "__">` */
6664
+ /** `<workspaceRoot>/.branches/<provider>/<host>/<repo path>/<branch with "/" → "__">` */
6257
6665
  branchWorktreePath(repo, branch) {
6258
6666
  const relative2 = path8.relative(this.workspaceRoot, this.repoDir(repo));
6259
6667
  return path8.join(this.workspaceRoot, BRANCHES_DIR, relative2, branch.replaceAll("/", "__"));
@@ -6396,10 +6804,10 @@ var RepoCache = class {
6396
6804
  );
6397
6805
  let tip = existing;
6398
6806
  const identity = await git2(["config", "--get", "user.email"]).then(
6399
- (email) => email ? [] : FALLBACK_IDENTITY2,
6400
- () => FALLBACK_IDENTITY2
6807
+ (email) => email ? [] : FALLBACK_IDENTITY3,
6808
+ () => FALLBACK_IDENTITY3
6401
6809
  );
6402
- const index = path8.join(this.workspaceRoot, TMP_DIR, `stash-index-${randomUUID2()}`);
6810
+ const index = path8.join(this.workspaceRoot, TMP_DIR, `stash-index-${randomUUID3()}`);
6403
6811
  await mkdir3(path8.dirname(index), { recursive: true });
6404
6812
  try {
6405
6813
  for (const entry of [...entries].reverse()) {
@@ -6519,7 +6927,9 @@ Stash ${entry.sha} from ${entry.date}, made on top of ${base}.`;
6519
6927
  }
6520
6928
  /**
6521
6929
  * 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
6930
+ * (branch worktrees under `.branches` are kept) and leftover partial clones,
6931
+ * moves repositories cached before the host was part of their path (see
6932
+ * `migrateLegacyRepos`), then runs `git worktree prune` in each cached
6523
6933
  * repository. Only call it while no job is running. Returns the removed
6524
6934
  * worktree paths.
6525
6935
  */
@@ -6532,6 +6942,7 @@ Stash ${entry.sha} from ${entry.date}, made on top of ${base}.`;
6532
6942
  removed.push(stale);
6533
6943
  }
6534
6944
  await rm7(path8.join(this.workspaceRoot, TMP_DIR), { recursive: true, force: true });
6945
+ await this.migrateLegacyRepos();
6535
6946
  for (const provider of PROVIDERS) {
6536
6947
  for (const dir of await this.findRepos(path8.join(this.workspaceRoot, provider), 0)) {
6537
6948
  await this.withLock(
@@ -6547,6 +6958,96 @@ Stash ${entry.sha} from ${entry.date}, made on top of ${base}.`;
6547
6958
  return removed;
6548
6959
  }
6549
6960
  // --- internals --------------------------------------------------------------------------
6961
+ /**
6962
+ * Moves repositories cached as `<provider>/<repo path>` (before the host
6963
+ * was part of the path) to `<provider>/<host>/<repo path>`, with their
6964
+ * branch worktrees from `.branches/<provider>/<repo path>/` to
6965
+ * `.branches/<provider>/<host>/<repo path>/`, and repairs git's links
6966
+ * between them. The host comes from the repository's `origin` URL. A
6967
+ * repository that can't be moved is left in place (and cloned again at its
6968
+ * new path when next needed).
6969
+ */
6970
+ async migrateLegacyRepos() {
6971
+ for (const provider of PROVIDERS) {
6972
+ const providerDir = path8.join(this.workspaceRoot, provider);
6973
+ for (const dir of await this.findRepos(providerDir, 0)) {
6974
+ await this.withLock(
6975
+ dir,
6976
+ void 0,
6977
+ () => this.migrateLegacyRepo(provider, providerDir, dir)
6978
+ ).catch(
6979
+ (error) => this.logger?.warn({ err: error, repo: dir }, "moving a cached repository failed")
6980
+ );
6981
+ }
6982
+ }
6983
+ }
6984
+ /** Called with the (legacy) repo lock held. */
6985
+ async migrateLegacyRepo(provider, providerDir, dir) {
6986
+ const options = { env: hostEnv(), cwd: dir };
6987
+ const config = (key) => this.runGit(["config", "--get", key], options).then(
6988
+ (value) => value.trim(),
6989
+ () => ""
6990
+ );
6991
+ if (!await exists(path8.join(dir, "HEAD")) || await config(HOST_CONFIG)) return;
6992
+ const cloneUrl = await config("remote.origin.url");
6993
+ const fullPath = path8.relative(providerDir, dir).split(path8.sep).join("/");
6994
+ const target = this.repoDir({ provider, fullPath, cloneUrl });
6995
+ if (await exists(target)) {
6996
+ throw new Error(`${target} already exists`);
6997
+ }
6998
+ const legacyBranches = path8.join(
6999
+ this.workspaceRoot,
7000
+ BRANCHES_DIR,
7001
+ provider,
7002
+ ...fullPath.split("/")
7003
+ );
7004
+ const targetBranches = path8.join(
7005
+ this.workspaceRoot,
7006
+ BRANCHES_DIR,
7007
+ path8.relative(this.workspaceRoot, target)
7008
+ );
7009
+ const worktrees = (await this.runGit(["worktree", "list", "--porcelain"], options)).split("\n").filter((line) => line.startsWith("worktree ")).map((line) => line.slice("worktree ".length)).slice(1);
7010
+ await mkdir3(path8.dirname(target), { recursive: true });
7011
+ await rename3(dir, target);
7012
+ const repaired = { env: hostEnv(), cwd: target };
7013
+ try {
7014
+ await this.runGit(["config", HOST_CONFIG, hostDir(cloneUrl)], repaired);
7015
+ } catch (error) {
7016
+ await rename3(target, dir).catch(() => void 0);
7017
+ throw error;
7018
+ }
7019
+ const moved = [];
7020
+ let moveError;
7021
+ for (const worktree of worktrees) {
7022
+ if (!await exists(worktree)) continue;
7023
+ const relative2 = path8.relative(legacyBranches, worktree);
7024
+ if (relative2.startsWith("..") || path8.isAbsolute(relative2)) {
7025
+ moved.push(worktree);
7026
+ continue;
7027
+ }
7028
+ const to = path8.join(targetBranches, relative2);
7029
+ try {
7030
+ await mkdir3(path8.dirname(to), { recursive: true });
7031
+ await rename3(worktree, to);
7032
+ moved.push(to);
7033
+ } catch (error) {
7034
+ moveError ??= error;
7035
+ moved.push(worktree);
7036
+ }
7037
+ }
7038
+ if (moved.length > 0) await this.runGit(["worktree", "repair", ...moved], repaired);
7039
+ if (moveError !== void 0) throw moveError;
7040
+ await this.removeEmptyDirs(path8.dirname(dir), providerDir);
7041
+ await this.removeEmptyDirs(legacyBranches, path8.join(this.workspaceRoot, BRANCHES_DIR));
7042
+ this.logger?.info({ from: dir, to: target, worktrees: moved }, "moved a cached repository");
7043
+ }
7044
+ /** Removes `dir` and its parents up to (not including) `stop`, while they're empty. */
7045
+ async removeEmptyDirs(dir, stop) {
7046
+ for (let current = dir; current.startsWith(stop + path8.sep); current = path8.dirname(current)) {
7047
+ if ((await readdir(current).catch(() => null))?.length !== 0) return;
7048
+ await rmdir(current).catch(() => void 0);
7049
+ }
7050
+ }
6550
7051
  async checkBranchName(branch) {
6551
7052
  const valid = await runGit(["check-ref-format", "--branch", branch], {
6552
7053
  env: hostEnv(),
@@ -6775,7 +7276,7 @@ Stash ${entry.sha} from ${entry.date}, made on top of ${base}.`;
6775
7276
  return { dir, cloned: false, fetched: true };
6776
7277
  }
6777
7278
  async clone(repo, dir, options) {
6778
- const tmp = path8.join(this.workspaceRoot, TMP_DIR, randomUUID2());
7279
+ const tmp = path8.join(this.workspaceRoot, TMP_DIR, randomUUID3());
6779
7280
  await mkdir3(path8.dirname(tmp), { recursive: true });
6780
7281
  this.logger?.info({ repo: `${repo.provider}/${repo.fullPath}` }, "cloning repository");
6781
7282
  try {
@@ -6784,6 +7285,7 @@ Stash ${entry.sha} from ${entry.date}, made on top of ${base}.`;
6784
7285
  options
6785
7286
  );
6786
7287
  await this.runGit(["config", "remote.origin.fetch", FETCH_REFSPEC], { ...options, cwd: tmp });
7288
+ await this.runGit(["config", HOST_CONFIG, hostDir(repo.cloneUrl)], { ...options, cwd: tmp });
6787
7289
  await this.runGit(["fetch", "--quiet", "--filter=blob:none", "--no-tags", "origin"], {
6788
7290
  ...options,
6789
7291
  cwd: tmp
@@ -7649,32 +8151,71 @@ function createQueueReceiver(server, region, currentToken) {
7649
8151
 
7650
8152
  // src/update.ts
7651
8153
  import { execFile as execFile2 } from "node:child_process";
7652
- import { readFile as readFile6 } from "node:fs/promises";
8154
+ import { randomUUID as randomUUID4 } from "node:crypto";
8155
+ import { readFile as readFile6, rm as rm8 } from "node:fs/promises";
7653
8156
  import path9 from "node:path";
7654
- import { z as z14 } from "zod";
8157
+ import { z as z15 } from "zod";
7655
8158
  var UPDATE_STATE_FILE = "update-state.json";
8159
+ var UPDATE_REQUEST_FILE = "update-request.json";
7656
8160
  var MAX_STARTS_SINCE_PENDING = 3;
7657
8161
  var CONFIRM_AFTER_MS = 6e4;
7658
8162
  var DRAIN_TIMEOUT_MS = 2 * 60 * 60 * 1e3;
7659
8163
  var INSTALL_TIMEOUT_MS = 15 * 60 * 1e3;
7660
8164
  var FAILED_VERSIONS_KEPT = 100;
7661
- var UpdateStateFile = z14.object({
8165
+ var UpdateStateFile = z15.object({
7662
8166
  /** The version running before the last update (the rollback target). */
7663
- previous: z14.string().nullable().default(null),
8167
+ previous: z15.string().nullable().default(null),
7664
8168
  /** The version installed by the last update, until it's confirmed. */
7665
- pending: z14.string().nullable().default(null),
8169
+ pending: z15.string().nullable().default(null),
7666
8170
  /** Starts of `pending` so far. */
7667
- startsSincePending: z14.int().min(0).default(0),
7668
- failed: z14.array(z14.string()).default([]),
8171
+ startsSincePending: z15.int().min(0).default(0),
8172
+ failed: z15.array(z15.string()).default([]),
7669
8173
  /** Why the last update or rollback failed. */
7670
- lastError: z14.string().nullable().default(null)
8174
+ lastError: z15.string().nullable().default(null),
8175
+ /** The control panel's last `updateRequest` acted on (reported back so it's cleared). */
8176
+ handledRequestId: z15.string().nullable().default(null)
7671
8177
  });
7672
8178
  function emptyState() {
7673
- return { previous: null, pending: null, startsSincePending: 0, failed: [], lastError: null };
8179
+ return {
8180
+ previous: null,
8181
+ pending: null,
8182
+ startsSincePending: 0,
8183
+ failed: [],
8184
+ lastError: null,
8185
+ handledRequestId: null
8186
+ };
7674
8187
  }
7675
8188
  function updateStatePath(configPath) {
7676
8189
  return path9.join(path9.dirname(configPath), UPDATE_STATE_FILE);
7677
8190
  }
8191
+ function updateRequestPath(configPath) {
8192
+ return path9.join(path9.dirname(configPath), UPDATE_REQUEST_FILE);
8193
+ }
8194
+ var LocalUpdateRequest = z15.object({
8195
+ id: z15.string(),
8196
+ requestedAt: z15.string()
8197
+ });
8198
+ async function writeUpdateRequest(file, now = /* @__PURE__ */ new Date()) {
8199
+ const request = { id: randomUUID4(), requestedAt: now.toISOString() };
8200
+ await writePrivateJson(file, request);
8201
+ return request;
8202
+ }
8203
+ async function readUpdateRequest(file) {
8204
+ let text;
8205
+ try {
8206
+ text = await readFile6(file, "utf8");
8207
+ } catch (error) {
8208
+ if (error.code === "ENOENT") return null;
8209
+ throw error;
8210
+ }
8211
+ try {
8212
+ const parsed = LocalUpdateRequest.safeParse(JSON.parse(text));
8213
+ if (parsed.success) return parsed.data;
8214
+ } catch {
8215
+ }
8216
+ await rm8(file, { force: true });
8217
+ return null;
8218
+ }
7678
8219
  async function readUpdateState(file) {
7679
8220
  let text;
7680
8221
  try {
@@ -7695,6 +8236,18 @@ function writeUpdateState(file, state) {
7695
8236
  }
7696
8237
  function npmInstaller(env = process.env) {
7697
8238
  return {
8239
+ latest: () => new Promise((resolve2, reject) => {
8240
+ execFile2(
8241
+ "npm",
8242
+ ["view", AGENT_PACKAGE, "version"],
8243
+ { env, timeout: 6e4 },
8244
+ (error, stdout, stderr) => {
8245
+ if (!error) return resolve2(String(stdout).trim());
8246
+ const tail5 = String(stderr).trim().split("\n").slice(-5).join("\n");
8247
+ reject(new Error(`npm view ${AGENT_PACKAGE} version failed: ${tail5 || error.message}`));
8248
+ }
8249
+ );
8250
+ }),
7698
8251
  install: (version) => new Promise((resolve2, reject) => {
7699
8252
  execFile2(
7700
8253
  "npm",
@@ -7728,6 +8281,8 @@ var SelfUpdater = class {
7728
8281
  target = null;
7729
8282
  /** Start of the current run of successful heartbeats while confirming. */
7730
8283
  okSince = null;
8284
+ /** A heartbeat is being handled (they're not awaited, so the next may come meanwhile). */
8285
+ busy = false;
7731
8286
  now;
7732
8287
  drainTimeoutMs;
7733
8288
  confirmAfterMs;
@@ -7786,26 +8341,86 @@ var SelfUpdater = class {
7786
8341
  return {
7787
8342
  selfUpdate: this.support,
7788
8343
  update,
7789
- failedVersions: this.state.failed.slice(-FAILED_VERSIONS_KEPT)
8344
+ failedVersions: this.state.failed.slice(-FAILED_VERSIONS_KEPT),
8345
+ handledUpdateRequestId: this.state.handledRequestId
7790
8346
  };
7791
8347
  }
7792
8348
  /**
7793
8349
  * 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.
8350
+ * version after `confirmAfterMs` of successful heartbeats, then starts an
8351
+ * update when one was asked for or the desired version calls for one.
7796
8352
  */
7797
8353
  async onHeartbeat(response, daemon) {
7798
8354
  if (!response) {
7799
8355
  this.okSince = null;
7800
8356
  return;
7801
8357
  }
7802
- if (this.phase === "confirming") {
7803
- this.okSince ??= this.now();
7804
- if (this.now() - this.okSince < this.confirmAfterMs) return;
7805
- await this.confirm();
8358
+ if (this.busy) return;
8359
+ this.busy = true;
8360
+ try {
8361
+ if (this.phase === "confirming") {
8362
+ this.okSince ??= this.now();
8363
+ if (this.now() - this.okSince < this.confirmAfterMs) return;
8364
+ await this.confirm();
8365
+ }
8366
+ if (this.phase !== "idle") return;
8367
+ if (await this.onRequest(response, daemon)) return;
8368
+ const version = this.wantedVersion(response.desiredVersion);
8369
+ if (version) await this.update(version, daemon);
8370
+ } finally {
8371
+ this.busy = false;
8372
+ }
8373
+ }
8374
+ /**
8375
+ * Acts on an update the control panel or the host asked for; false when
8376
+ * none was. The request is handled (reported, or its file removed) before
8377
+ * anything is installed, so a failing one isn't retried.
8378
+ */
8379
+ async onRequest(response, daemon) {
8380
+ const fromPanel = response.updateRequest && response.updateRequest.id !== this.state.handledRequestId ? response.updateRequest : null;
8381
+ const local = !fromPanel && this.options.requestPath ? await readUpdateRequest(this.options.requestPath) : null;
8382
+ if (!fromPanel && !local) return false;
8383
+ const log = this.options.logger;
8384
+ if (fromPanel) this.state.handledRequestId = fromPanel.id;
8385
+ else await rm8(this.options.requestPath, { force: true });
8386
+ const source = fromPanel ? "the control panel" : "omniralph-agent update";
8387
+ if (!this.options.underPm2) {
8388
+ this.state.lastError = `An update was requested (${source}), but this agent isn't running under pm2, so it can't update itself`;
8389
+ log.warn({ source }, "an update was requested, but only agents under pm2 update themselves");
8390
+ await this.save();
8391
+ return true;
8392
+ }
8393
+ let version = fromPanel?.version ?? response.desiredVersion;
8394
+ if (!version) {
8395
+ try {
8396
+ if (!this.options.installer.latest) throw new Error("no way to look it up");
8397
+ version = await this.options.installer.latest();
8398
+ } catch (error) {
8399
+ this.state.lastError = `An update was requested, but reading the latest version failed: ${errorMessage(error)}`;
8400
+ log.error(
8401
+ { err: error, source },
8402
+ "reading the latest version for a requested update failed"
8403
+ );
8404
+ await this.save();
8405
+ return true;
8406
+ }
8407
+ }
8408
+ if (!AgentVersion.safeParse(version).success) {
8409
+ this.state.lastError = `An update was requested, but ${JSON.stringify(version.slice(0, 64))} isn't a version`;
8410
+ await this.save();
8411
+ return true;
8412
+ }
8413
+ if (version === this.options.runningVersion) {
8414
+ log.info({ version, source }, "an update was requested; already running that version");
8415
+ await this.save();
8416
+ return true;
7806
8417
  }
7807
- const version = this.wantedVersion(response.desiredVersion);
7808
- if (version) await this.update(version, daemon);
8418
+ this.state.failed = this.state.failed.filter((failed) => failed !== version);
8419
+ this.state.lastError = null;
8420
+ await this.save();
8421
+ log.info({ version, source }, "an update was requested");
8422
+ await this.update(version, daemon);
8423
+ return true;
7809
8424
  }
7810
8425
  /** The version to update to now, or null. */
7811
8426
  wantedVersion(desired) {
@@ -7855,10 +8470,10 @@ var SelfUpdater = class {
7855
8470
  return;
7856
8471
  }
7857
8472
  this.state = {
8473
+ ...this.state,
7858
8474
  previous: this.options.runningVersion,
7859
8475
  pending: version,
7860
8476
  startsSincePending: 0,
7861
- failed: this.state.failed,
7862
8477
  lastError: null
7863
8478
  };
7864
8479
  await this.save();
@@ -7892,6 +8507,9 @@ Commands:
7892
8507
  --workspace-root <dir> Repo cache directory (default: ~/.omniralph/repos)
7893
8508
  start Run the agent daemon
7894
8509
  --healthz-port <port> Serve GET /healthz on 127.0.0.1:<port>
8510
+ update Ask the running agent (under pm2) to update with its next heartbeat:
8511
+ to the desired version, else the latest on npm, even one that
8512
+ failed before
7895
8513
  git-credential Git credential helper for job git commands (\`get\` only; reads
7896
8514
  OMNIRALPH_JOB_TOKEN, set by the agent for in-job processes)
7897
8515
 
@@ -7948,6 +8566,8 @@ ${USAGE}`);
7948
8566
  return await runEnroll(values, configPath, deps);
7949
8567
  case "start":
7950
8568
  return await runStart(values, configPath, deps);
8569
+ case "update":
8570
+ return await runUpdate(configPath, deps);
7951
8571
  case "git-credential":
7952
8572
  return await runGitCredential(
7953
8573
  positionals[1],
@@ -8018,6 +8638,19 @@ Run 'omniralph-agent start' to start the agent.
8018
8638
  );
8019
8639
  return 0;
8020
8640
  }
8641
+ async function runUpdate(configPath, deps) {
8642
+ await readConfig(configPath);
8643
+ const file = updateRequestPath(configPath);
8644
+ await writeUpdateRequest(file, deps.now ? new Date(deps.now()) : void 0);
8645
+ deps.io.stdout(
8646
+ `Update requested (${file}).
8647
+ The running agent picks it up with its next heartbeat: it stops taking jobs, lets running ones
8648
+ finish, installs the desired version (or the latest on npm when none is set) and restarts.
8649
+ Only agents under pm2 update themselves; others log a warning and keep running.
8650
+ `
8651
+ );
8652
+ return 0;
8653
+ }
8021
8654
  async function runStart(values, configPath, deps) {
8022
8655
  let healthzPort;
8023
8656
  if (values["healthz-port"] !== void 0) {
@@ -8033,6 +8666,7 @@ async function runStart(values, configPath, deps) {
8033
8666
  const version = deps.version ?? AGENT_VERSION;
8034
8667
  const updater = new SelfUpdater({
8035
8668
  statePath: updateStatePath(configPath),
8669
+ requestPath: updateRequestPath(configPath),
8036
8670
  runningVersion: version,
8037
8671
  underPm2: runningUnderPm2(deps.env),
8038
8672
  installer: deps.installer ?? npmInstaller(deps.env),