@omniralph/agent 0.3.2 → 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/README.md +5 -4
- package/dist/cli.js +476 -113
- package/dist/cli.js.map +1 -1
- package/package.json +3 -3
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
|
|
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
|
|
|
@@ -3465,8 +3543,8 @@ function problemWith(error) {
|
|
|
3465
3543
|
return `invalid structured result: ${issue?.path.length ? `\`${issue.path.join(".")}\` ` : ""}${issue?.message ?? "doesn't match the schema"}`;
|
|
3466
3544
|
}
|
|
3467
3545
|
var StoryAgentOutput = z11.object({
|
|
3468
|
-
status: z11.enum(["complete", "blocked", "incomplete"]).describe(
|
|
3469
|
-
"complete: every acceptance criterion is met. blocked: a retry can't get past an obstacle. incomplete: unfinished; try again."
|
|
3546
|
+
status: z11.enum(["complete", "blocked", "incomplete", "waiting"]).describe(
|
|
3547
|
+
"complete: every acceptance criterion is met. blocked: a retry can't get past an obstacle. incomplete: unfinished; try again. waiting: you are ending your turn to wait for background work you started; you are resumed when it finishes."
|
|
3470
3548
|
),
|
|
3471
3549
|
summary: z11.string().describe(
|
|
3472
3550
|
"Posted to Linear: what you did, or precisely what is in the way and what would unblock it."
|
|
@@ -3487,6 +3565,9 @@ var StoryAgentOutput = z11.object({
|
|
|
3487
3565
|
"Work outside this story's scope for the orchestrator to file as new stories. Empty when there is none."
|
|
3488
3566
|
)
|
|
3489
3567
|
});
|
|
3568
|
+
function isWaitingStory(structured) {
|
|
3569
|
+
return structured?.status === "waiting";
|
|
3570
|
+
}
|
|
3490
3571
|
var STORY_OUTPUT_SCHEMA = jsonSchema(StoryAgentOutput);
|
|
3491
3572
|
function readStoryOutcome(structured) {
|
|
3492
3573
|
const parsed = structured === void 0 ? void 0 : StoryAgentOutput.safeParse(structured);
|
|
@@ -3535,8 +3616,14 @@ var RequestAgentOutput = z11.object({
|
|
|
3535
3616
|
})
|
|
3536
3617
|
).optional().describe(
|
|
3537
3618
|
"What you did with each review finding the request lists by ID. Omniralph replies in the threads and resolves the fixed ones."
|
|
3619
|
+
),
|
|
3620
|
+
waiting: z11.boolean().optional().describe(
|
|
3621
|
+
"True only when you are ending your turn to wait for background work you started; you are resumed when it finishes."
|
|
3538
3622
|
)
|
|
3539
3623
|
});
|
|
3624
|
+
function isWaitingRequest(structured) {
|
|
3625
|
+
return structured?.waiting === true;
|
|
3626
|
+
}
|
|
3540
3627
|
var REQUEST_OUTPUT_SCHEMA = jsonSchema(RequestAgentOutput);
|
|
3541
3628
|
var MAX_FINDING_OUTCOMES = 50;
|
|
3542
3629
|
var MAX_FINDING_COMMENT = 2e3;
|
|
@@ -3580,10 +3667,13 @@ function uniqueCommands(commands) {
|
|
|
3580
3667
|
function normalizeCommand(cmd) {
|
|
3581
3668
|
return cmd.trim().replace(/\s+/g, " ");
|
|
3582
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.`;
|
|
3583
3671
|
var RALPH_SYSTEM_APPEND = `You are "Omniralph", an autonomous engineer working a Linear epic one user story at a time (the Ralph loop).
|
|
3584
3672
|
- Work only on the single story you are given; other stories get their own sessions.
|
|
3585
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.
|
|
3586
|
-
- Be precise and verifiable. Only report the status "complete" in your structured result when the story truly meets its acceptance criteria
|
|
3674
|
+
- Be precise and verifiable. Only report the status "complete" in your structured result when the story truly meets its acceptance criteria.
|
|
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}`;
|
|
3587
3677
|
var DEFAULT_STORY_TEMPLATE = `You are working through a PRD epic from Linear, one user story per session.
|
|
3588
3678
|
Each session starts with a fresh context: the PRD, the progress log and the repository are your memory.
|
|
3589
3679
|
|
|
@@ -3697,6 +3787,7 @@ Your session ends with a structured result (the JSON schema you were given). It
|
|
|
3697
3787
|
- \`status: "complete"\` only when every acceptance criterion is met and the quality gates pass. If the story is already implemented (e.g. by a previous session), verify it meets the acceptance criteria and report it complete straight away.
|
|
3698
3788
|
- \`status: "blocked"\` when something another attempt can't get past stops you (missing access or credentials, an unavailable service, a decision only a person can make). Explain in \`summary\` precisely why and what would unblock you. The story is then set aside without retries until someone replies. Changes you leave in the worktree are committed as work in progress when the quality gates pass, and stashed otherwise: describe them in one line with \`commit: { summary }\`.
|
|
3699
3789
|
- \`status: "incomplete"\` when the story is just unfinished: it gets another attempt.
|
|
3790
|
+
- \`status: "waiting"\` only to end your turn while background work you started (subagents, commands) still runs: you are resumed when it finishes, and then report one of the statuses above.
|
|
3700
3791
|
- \`summary\` is posted to Linear: what you did, or what is in the way.
|
|
3701
3792
|
{{#if followUps}}
|
|
3702
3793
|
|
|
@@ -3853,7 +3944,9 @@ function requestSystemAppend(historyRewrite = "when-asked") {
|
|
|
3853
3944
|
- 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.
|
|
3854
3945
|
- Only push the epic branch you are on. Never push to, or force-push, the base branch or any other branch.
|
|
3855
3946
|
${rewrite}
|
|
3856
|
-
- The \`summary\` of your structured result is posted to the Linear thread: summarise what you did, with links (e.g. the PR/MR URL)
|
|
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).
|
|
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}`;
|
|
3857
3950
|
}
|
|
3858
3951
|
function capitalize(text) {
|
|
3859
3952
|
return text.charAt(0).toUpperCase() + text.slice(1);
|
|
@@ -4140,6 +4233,9 @@ function readOnlyCommandGuard(commands) {
|
|
|
4140
4233
|
// src/capabilities/ralph/session.ts
|
|
4141
4234
|
var SESSION_IDLE_TIMEOUT_MS = 5 * 6e4;
|
|
4142
4235
|
var INJECTION_IDLE_TIMEOUT_MS = 5 * 6e4;
|
|
4236
|
+
var BACKGROUND_WAIT_TIMEOUT_MS = 60 * 6e4;
|
|
4237
|
+
var WAIT_NUDGE_DELAY_MS = 3e4;
|
|
4238
|
+
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.";
|
|
4143
4239
|
var RATE_LIMIT_TEXT2 = /rate[_ ]limit|usage limit|\b429\b|too many requests/i;
|
|
4144
4240
|
function retryAfter2(resetsAt) {
|
|
4145
4241
|
if (resetsAt === void 0) return void 0;
|
|
@@ -4221,6 +4317,18 @@ function createSessionRunner(query = sdkQuery2) {
|
|
|
4221
4317
|
return seen.sessionId ? { ...result, sessionId: seen.sessionId } : result;
|
|
4222
4318
|
};
|
|
4223
4319
|
}
|
|
4320
|
+
function startsTurn(message) {
|
|
4321
|
+
switch (message.type) {
|
|
4322
|
+
case "assistant":
|
|
4323
|
+
case "user":
|
|
4324
|
+
case "stream_event":
|
|
4325
|
+
return message.parent_tool_use_id === null;
|
|
4326
|
+
case "system":
|
|
4327
|
+
return message.subtype === "init";
|
|
4328
|
+
default:
|
|
4329
|
+
return false;
|
|
4330
|
+
}
|
|
4331
|
+
}
|
|
4224
4332
|
async function runQuery(query, request, seen) {
|
|
4225
4333
|
const controller = new AbortController();
|
|
4226
4334
|
const onAbort = () => controller.abort(request.signal.reason);
|
|
@@ -4259,6 +4367,48 @@ async function runQuery(query, request, seen) {
|
|
|
4259
4367
|
return true;
|
|
4260
4368
|
});
|
|
4261
4369
|
controller.signal.addEventListener("abort", finishInput, { once: true });
|
|
4370
|
+
const live = /* @__PURE__ */ new Set();
|
|
4371
|
+
let waiting = false;
|
|
4372
|
+
let nudged = false;
|
|
4373
|
+
let waitStopped;
|
|
4374
|
+
let waitTimer;
|
|
4375
|
+
let nudgeTimer;
|
|
4376
|
+
const backgroundWaitTimeoutMs = request.backgroundWaitTimeoutMs ?? BACKGROUND_WAIT_TIMEOUT_MS;
|
|
4377
|
+
const waitNudgeDelayMs = request.waitNudgeDelayMs ?? WAIT_NUDGE_DELAY_MS;
|
|
4378
|
+
const stopWaiting = (why) => {
|
|
4379
|
+
waitStopped = why;
|
|
4380
|
+
controller.abort(new Error(why));
|
|
4381
|
+
};
|
|
4382
|
+
const watchNothingRunning = () => {
|
|
4383
|
+
clearTimeout(nudgeTimer);
|
|
4384
|
+
if (!waiting || live.size > 0) return;
|
|
4385
|
+
nudgeTimer = setTimeout(() => {
|
|
4386
|
+
if (nudged) {
|
|
4387
|
+
stopWaiting("the session kept waiting with nothing running in the background");
|
|
4388
|
+
return;
|
|
4389
|
+
}
|
|
4390
|
+
nudged = true;
|
|
4391
|
+
send(WAIT_NUDGE_TEXT, "next");
|
|
4392
|
+
watchNothingRunning();
|
|
4393
|
+
}, waitNudgeDelayMs);
|
|
4394
|
+
};
|
|
4395
|
+
const startWaiting = () => {
|
|
4396
|
+
waiting = true;
|
|
4397
|
+
clearTimeout(idleTimer);
|
|
4398
|
+
clearTimeout(waitTimer);
|
|
4399
|
+
waitTimer = setTimeout(
|
|
4400
|
+
() => stopWaiting(
|
|
4401
|
+
`the background work took longer than ${Math.round(backgroundWaitTimeoutMs / 6e4)} minutes`
|
|
4402
|
+
),
|
|
4403
|
+
backgroundWaitTimeoutMs
|
|
4404
|
+
);
|
|
4405
|
+
watchNothingRunning();
|
|
4406
|
+
};
|
|
4407
|
+
const endWaiting = () => {
|
|
4408
|
+
waiting = false;
|
|
4409
|
+
clearTimeout(waitTimer);
|
|
4410
|
+
clearTimeout(nudgeTimer);
|
|
4411
|
+
};
|
|
4262
4412
|
const texts = [];
|
|
4263
4413
|
const last = () => texts.at(-1) ?? "";
|
|
4264
4414
|
let rateLimited = false;
|
|
@@ -4266,6 +4416,7 @@ async function runQuery(query, request, seen) {
|
|
|
4266
4416
|
let answered;
|
|
4267
4417
|
const stopped = () => {
|
|
4268
4418
|
if (request.signal.aborted) return { stop: "aborted", output: last(), usage };
|
|
4419
|
+
if (waitStopped && answered) return { ...answered, error: waitStopped };
|
|
4269
4420
|
if (idle) {
|
|
4270
4421
|
return {
|
|
4271
4422
|
stop: "idle",
|
|
@@ -4280,8 +4431,17 @@ async function runQuery(query, request, seen) {
|
|
|
4280
4431
|
try {
|
|
4281
4432
|
const messages = query({ prompt: input, options: sessionOptions(request, controller) });
|
|
4282
4433
|
for await (const message of messages) {
|
|
4283
|
-
|
|
4284
|
-
|
|
4434
|
+
if (message.type === "system" && message.subtype === "background_tasks_changed") {
|
|
4435
|
+
live.clear();
|
|
4436
|
+
for (const task of message.tasks) if (!task.ambient) live.add(task.task_id);
|
|
4437
|
+
if (live.size > 0) nudged = false;
|
|
4438
|
+
watchNothingRunning();
|
|
4439
|
+
}
|
|
4440
|
+
if (!waiting || startsTurn(message)) {
|
|
4441
|
+
clearTimeout(injectionTimer);
|
|
4442
|
+
endWaiting();
|
|
4443
|
+
resetIdle();
|
|
4444
|
+
}
|
|
4285
4445
|
if ("session_id" in message && message.session_id) seen.sessionId = message.session_id;
|
|
4286
4446
|
switch (message.type) {
|
|
4287
4447
|
case "assistant": {
|
|
@@ -4323,10 +4483,12 @@ async function runQuery(query, request, seen) {
|
|
|
4323
4483
|
};
|
|
4324
4484
|
const ids = message.user_message_uuids ?? (message.user_message_uuid ? [message.user_message_uuid] : [...outstanding]);
|
|
4325
4485
|
for (const id of ids) outstanding.delete(id);
|
|
4326
|
-
|
|
4486
|
+
const waits = request.isWaiting?.(message.structured_output) === true;
|
|
4487
|
+
if (!waits && outstanding.size === 0) return result;
|
|
4327
4488
|
answered = result;
|
|
4328
4489
|
clearTimeout(idleTimer);
|
|
4329
|
-
|
|
4490
|
+
if (waits) startWaiting();
|
|
4491
|
+
else injectionTimer = setTimeout(finishInput, injectionIdleTimeoutMs);
|
|
4330
4492
|
break;
|
|
4331
4493
|
}
|
|
4332
4494
|
const detail = message.subtype === "success" ? message.result : [message.subtype, ...message.errors].join(": ");
|
|
@@ -4367,6 +4529,7 @@ async function runQuery(query, request, seen) {
|
|
|
4367
4529
|
return { stop: "error", output: last(), error: text, usage };
|
|
4368
4530
|
} finally {
|
|
4369
4531
|
clearTimeout(idleTimer);
|
|
4532
|
+
endWaiting();
|
|
4370
4533
|
finishInput();
|
|
4371
4534
|
request.signal.removeEventListener("abort", onAbort);
|
|
4372
4535
|
controller.signal.removeEventListener("abort", finishInput);
|
|
@@ -4374,33 +4537,9 @@ async function runQuery(query, request, seen) {
|
|
|
4374
4537
|
}
|
|
4375
4538
|
|
|
4376
4539
|
// src/capabilities/ralph/story.ts
|
|
4377
|
-
import { mkdtemp, readFile as readFile2, rm, writeFile as
|
|
4378
|
-
import { tmpdir } from "node:os";
|
|
4379
|
-
import
|
|
4380
|
-
|
|
4381
|
-
// src/job-env.ts
|
|
4382
|
-
import { spawn } from "node:child_process";
|
|
4383
|
-
var JOB_TOKEN_ENV = "OMNIRALPH_JOB_TOKEN";
|
|
4384
|
-
var JOB_ID_ENV = "OMNIRALPH_JOB_ID";
|
|
4385
|
-
var SERVER_ENV = "OMNIRALPH_SERVER";
|
|
4386
|
-
var JOB_TOKEN_FILE_ENV = "OMNIRALPH_JOB_TOKEN_FILE";
|
|
4387
|
-
function jobProcessEnv(job, base = process.env, extra = {}) {
|
|
4388
|
-
const env = {};
|
|
4389
|
-
for (const [name, value] of Object.entries({ ...base, ...extra })) {
|
|
4390
|
-
if (name.startsWith("OMNIRALPH_")) continue;
|
|
4391
|
-
env[name] = value;
|
|
4392
|
-
}
|
|
4393
|
-
env[JOB_TOKEN_ENV] = job.jobToken;
|
|
4394
|
-
env[JOB_ID_ENV] = job.jobId;
|
|
4395
|
-
env[SERVER_ENV] = job.server;
|
|
4396
|
-
return env;
|
|
4397
|
-
}
|
|
4398
|
-
function withoutJobEnv(env) {
|
|
4399
|
-
return Object.fromEntries(Object.entries(env).filter(([name]) => !name.startsWith("OMNIRALPH_")));
|
|
4400
|
-
}
|
|
4401
|
-
function spawnJobProcess(job, command, args, options = {}) {
|
|
4402
|
-
return spawn(command, args, { ...options, env: jobProcessEnv(job, process.env, options.env) });
|
|
4403
|
-
}
|
|
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";
|
|
4404
4543
|
|
|
4405
4544
|
// src/workspace/git.ts
|
|
4406
4545
|
import { spawn as spawn2 } from "node:child_process";
|
|
@@ -4515,8 +4654,8 @@ function runProcess(file, args, options) {
|
|
|
4515
4654
|
|
|
4516
4655
|
// src/capabilities/ralph/attachments.ts
|
|
4517
4656
|
import { existsSync } from "node:fs";
|
|
4518
|
-
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
4519
|
-
import
|
|
4657
|
+
import { mkdir, readFile, writeFile as writeFile2 } from "node:fs/promises";
|
|
4658
|
+
import path2 from "node:path";
|
|
4520
4659
|
var ATTACHMENTS_DIR = ".attachments";
|
|
4521
4660
|
var DOWNLOAD_TIMEOUT_MS = 12e4;
|
|
4522
4661
|
async function readCapped(res, max) {
|
|
@@ -4567,14 +4706,14 @@ function controlPanelFetcher(options) {
|
|
|
4567
4706
|
}
|
|
4568
4707
|
function attachmentsDir(workspaceRoot, epicIdentifier) {
|
|
4569
4708
|
const safe = epicIdentifier.replace(/[^A-Za-z0-9_-]/g, "_") || "epic";
|
|
4570
|
-
return
|
|
4709
|
+
return path2.join(workspaceRoot, ATTACHMENTS_DIR, safe);
|
|
4571
4710
|
}
|
|
4572
4711
|
async function collectAttachments(options) {
|
|
4573
4712
|
const { dir, fetcher } = options;
|
|
4574
4713
|
const max = options.max ?? MAX_ATTACHMENT_DOWNLOADS_PER_JOB;
|
|
4575
4714
|
if (options.attachments.length === 0) return { dir, files: [] };
|
|
4576
4715
|
await mkdir(dir, { recursive: true });
|
|
4577
|
-
const indexPath =
|
|
4716
|
+
const indexPath = path2.join(dir, ".index.json");
|
|
4578
4717
|
let index = { files: {} };
|
|
4579
4718
|
try {
|
|
4580
4719
|
index = JSON.parse(await readFile(indexPath, "utf8"));
|
|
@@ -4588,8 +4727,8 @@ async function collectAttachments(options) {
|
|
|
4588
4727
|
for (const attachment of options.attachments) {
|
|
4589
4728
|
const entry = { id: attachment.id, title: attachment.title, sources: attachment.sources };
|
|
4590
4729
|
const cached = index.files[attachment.id];
|
|
4591
|
-
if (cached && existsSync(
|
|
4592
|
-
files.push({ ...entry, path:
|
|
4730
|
+
if (cached && existsSync(path2.join(dir, cached.file))) {
|
|
4731
|
+
files.push({ ...entry, path: path2.join(dir, cached.file) });
|
|
4593
4732
|
continue;
|
|
4594
4733
|
}
|
|
4595
4734
|
if (fetched >= max) {
|
|
@@ -4608,9 +4747,9 @@ async function collectAttachments(options) {
|
|
|
4608
4747
|
);
|
|
4609
4748
|
if (!attachment.title) unnamed++;
|
|
4610
4749
|
used.add(file);
|
|
4611
|
-
await
|
|
4750
|
+
await writeFile2(path2.join(dir, file), result.data);
|
|
4612
4751
|
index.files[attachment.id] = { file, contentType: result.contentType };
|
|
4613
|
-
files.push({ ...entry, path:
|
|
4752
|
+
files.push({ ...entry, path: path2.join(dir, file) });
|
|
4614
4753
|
}
|
|
4615
4754
|
const failed = files.filter((f) => !f.path);
|
|
4616
4755
|
const unreported = failed.filter((f) => !reported.has(f.id));
|
|
@@ -4619,7 +4758,7 @@ async function collectAttachments(options) {
|
|
|
4619
4758
|
else reported.add(f.id);
|
|
4620
4759
|
}
|
|
4621
4760
|
index.reported = [...reported];
|
|
4622
|
-
await
|
|
4761
|
+
await writeFile2(indexPath, JSON.stringify(index, null, 2));
|
|
4623
4762
|
if (failed.length > 0) {
|
|
4624
4763
|
options.logger?.warn(
|
|
4625
4764
|
{ failed: failed.map((f) => ({ id: f.id, error: f.error })) },
|
|
@@ -4752,8 +4891,8 @@ async function runStory(job, ctx, options = {}) {
|
|
|
4752
4891
|
...options.fetch && { fetch: options.fetch }
|
|
4753
4892
|
});
|
|
4754
4893
|
const runSession = options.runSession ?? createSessionRunner();
|
|
4755
|
-
const
|
|
4756
|
-
const
|
|
4894
|
+
const plainEnv = sessionEnv(ctx.env());
|
|
4895
|
+
const git2 = await jobGitAccess(ctx, { refreshMs: options.tokenRefreshMs });
|
|
4757
4896
|
const prefix = stashPrefix(payload);
|
|
4758
4897
|
const label = (reason) => `${prefix}${reason} (attempt ${payload.attempt})`;
|
|
4759
4898
|
try {
|
|
@@ -4763,7 +4902,7 @@ async function runStory(job, ctx, options = {}) {
|
|
|
4763
4902
|
branch: payload.branch,
|
|
4764
4903
|
baseBranch: payload.baseBranch,
|
|
4765
4904
|
...payload.settings.setupCommand && { setupCommand: payload.settings.setupCommand },
|
|
4766
|
-
env,
|
|
4905
|
+
env: git2.env,
|
|
4767
4906
|
signal: ctx.signal
|
|
4768
4907
|
},
|
|
4769
4908
|
async (worktree) => {
|
|
@@ -4791,10 +4930,10 @@ async function runStory(job, ctx, options = {}) {
|
|
|
4791
4930
|
logger: log,
|
|
4792
4931
|
report: (body) => relay.post({ type: "thought", body, ephemeral: false })
|
|
4793
4932
|
});
|
|
4794
|
-
const progressDir = await
|
|
4795
|
-
const progressFile =
|
|
4933
|
+
const progressDir = await mkdtemp2(path3.join(tmpdir2(), "omniralph-progress-"));
|
|
4934
|
+
const progressFile = path3.join(progressDir, "progress.md");
|
|
4796
4935
|
try {
|
|
4797
|
-
await
|
|
4936
|
+
await writeFile3(progressFile, payload.progress);
|
|
4798
4937
|
const { epic, story } = promptEpic(payload);
|
|
4799
4938
|
const prompt = buildStoryPrompt({
|
|
4800
4939
|
epic,
|
|
@@ -4820,6 +4959,7 @@ async function runStory(job, ctx, options = {}) {
|
|
|
4820
4959
|
policy: RALPH_TOOL_POLICY,
|
|
4821
4960
|
systemAppend: RALPH_SYSTEM_APPEND,
|
|
4822
4961
|
outputSchema: STORY_OUTPUT_SCHEMA,
|
|
4962
|
+
isWaiting: isWaitingStory,
|
|
4823
4963
|
model: payload.settings.model ?? DEFAULT_STORY_MODEL,
|
|
4824
4964
|
...payload.settings.fallbackModel && {
|
|
4825
4965
|
fallbackModel: payload.settings.fallbackModel
|
|
@@ -4910,6 +5050,15 @@ Its work so far is committed on the branch as \`${kept.sha.slice(0, 10)}\`.`,
|
|
|
4910
5050
|
commitSha: kept.sha
|
|
4911
5051
|
});
|
|
4912
5052
|
}
|
|
5053
|
+
if (outcome.status === "waiting") {
|
|
5054
|
+
return notDone(
|
|
5055
|
+
"incomplete",
|
|
5056
|
+
`The previous session was stopped while it waited for background work (${session.error ?? "it gave up waiting"}). Its summary was:
|
|
5057
|
+
|
|
5058
|
+
${quote(tail(summary, 3e3))}`,
|
|
5059
|
+
"waiting"
|
|
5060
|
+
);
|
|
5061
|
+
}
|
|
4913
5062
|
if (outcome.status === "incomplete") {
|
|
4914
5063
|
return notDone(
|
|
4915
5064
|
"incomplete",
|
|
@@ -4965,11 +5114,12 @@ ${tail(errorText2(error), MAX_FEEDBACK_OUTPUT)}
|
|
|
4965
5114
|
if (ctx.signal.aborted) await stashQuietly(worktree, label("stopped"), log);
|
|
4966
5115
|
throw error;
|
|
4967
5116
|
} finally {
|
|
4968
|
-
await
|
|
5117
|
+
await rm2(progressDir, { recursive: true, force: true });
|
|
4969
5118
|
}
|
|
4970
5119
|
}
|
|
4971
5120
|
);
|
|
4972
5121
|
} finally {
|
|
5122
|
+
await git2.close();
|
|
4973
5123
|
await relay.flush();
|
|
4974
5124
|
}
|
|
4975
5125
|
}
|
|
@@ -5309,45 +5459,6 @@ async function currentHead(worktree, before) {
|
|
|
5309
5459
|
import { mkdtemp as mkdtemp3, rm as rm3, writeFile as writeFile4 } from "node:fs/promises";
|
|
5310
5460
|
import { tmpdir as tmpdir3 } from "node:os";
|
|
5311
5461
|
import path4 from "node:path";
|
|
5312
|
-
|
|
5313
|
-
// src/capabilities/ralph/git-access.ts
|
|
5314
|
-
import { mkdtemp as mkdtemp2, rename, rm as rm2, writeFile as writeFile3 } from "node:fs/promises";
|
|
5315
|
-
import { tmpdir as tmpdir2 } from "node:os";
|
|
5316
|
-
import path3 from "node:path";
|
|
5317
|
-
var REFRESH_MS = 3e4;
|
|
5318
|
-
async function sessionGitAccess(ctx, options = {}) {
|
|
5319
|
-
const dir = await mkdtemp2(path3.join(tmpdir2(), "omniralph-job-token-"));
|
|
5320
|
-
const file = path3.join(dir, "token");
|
|
5321
|
-
let written = ctx.jobToken();
|
|
5322
|
-
await writeFile3(file, written, { mode: 384 });
|
|
5323
|
-
let pending = Promise.resolve();
|
|
5324
|
-
const timer = setInterval(() => {
|
|
5325
|
-
const token = ctx.jobToken();
|
|
5326
|
-
if (token === written) return;
|
|
5327
|
-
written = token;
|
|
5328
|
-
pending = pending.then(async () => {
|
|
5329
|
-
const tmp = `${file}.tmp`;
|
|
5330
|
-
await writeFile3(tmp, token, { mode: 384 });
|
|
5331
|
-
await rename(tmp, file);
|
|
5332
|
-
}).catch(() => {
|
|
5333
|
-
});
|
|
5334
|
-
}, options.refreshMs ?? REFRESH_MS);
|
|
5335
|
-
timer.unref();
|
|
5336
|
-
return {
|
|
5337
|
-
env: {
|
|
5338
|
-
...ctx.repos.gitEnv(withoutJobEnv(ctx.env())),
|
|
5339
|
-
[SERVER_ENV]: ctx.server,
|
|
5340
|
-
[JOB_TOKEN_FILE_ENV]: file
|
|
5341
|
-
},
|
|
5342
|
-
async close() {
|
|
5343
|
-
clearInterval(timer);
|
|
5344
|
-
await pending;
|
|
5345
|
-
await rm2(dir, { recursive: true, force: true });
|
|
5346
|
-
}
|
|
5347
|
-
};
|
|
5348
|
-
}
|
|
5349
|
-
|
|
5350
|
-
// src/capabilities/ralph/request.ts
|
|
5351
5462
|
var MAX_TEXT2 = 2e4;
|
|
5352
5463
|
function tail4(text, max) {
|
|
5353
5464
|
const trimmed = text.trim();
|
|
@@ -5469,6 +5580,7 @@ async function runRequest(job, ctx, options = {}) {
|
|
|
5469
5580
|
policy: RALPH_TOOL_POLICY,
|
|
5470
5581
|
systemAppend: requestSystemAppend(payload.historyRewrite),
|
|
5471
5582
|
outputSchema: REQUEST_OUTPUT_SCHEMA,
|
|
5583
|
+
isWaiting: isWaitingRequest,
|
|
5472
5584
|
model: payload.settings.model ?? DEFAULT_STORY_MODEL,
|
|
5473
5585
|
...payload.settings.fallbackModel && {
|
|
5474
5586
|
fallbackModel: payload.settings.fallbackModel
|
|
@@ -5516,8 +5628,9 @@ async function runRequest(job, ctx, options = {}) {
|
|
|
5516
5628
|
usage: session.usage,
|
|
5517
5629
|
durationMs: Date.now() - started
|
|
5518
5630
|
};
|
|
5519
|
-
|
|
5520
|
-
|
|
5631
|
+
const stoppedWaiting = session.stop === "completed" && isWaitingRequest(session.structured);
|
|
5632
|
+
if (!read || "problem" in read || stoppedWaiting) {
|
|
5633
|
+
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);
|
|
5521
5634
|
return {
|
|
5522
5635
|
...base,
|
|
5523
5636
|
summary: clip3(tail4(session.output, 2e3)),
|
|
@@ -6040,7 +6153,17 @@ async function writePrivateJson(file, value) {
|
|
|
6040
6153
|
|
|
6041
6154
|
// src/workspace/repoCache.ts
|
|
6042
6155
|
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
6043
|
-
import {
|
|
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";
|
|
6044
6167
|
import path8 from "node:path";
|
|
6045
6168
|
import lockfile from "proper-lockfile";
|
|
6046
6169
|
var WORKTREES_DIR = ".worktrees";
|
|
@@ -6050,6 +6173,7 @@ var FETCH_REFSPEC = "+refs/heads/*:refs/remotes/origin/*";
|
|
|
6050
6173
|
var SETUP_PENDING = "omniralph-setup-pending";
|
|
6051
6174
|
var TMP_DIR = ".tmp";
|
|
6052
6175
|
var PROVIDERS = ["github", "gitlab"];
|
|
6176
|
+
var HOST_CONFIG = "omniralph.hostDir";
|
|
6053
6177
|
var PUSH_GUARD_HOOK = `#!/bin/sh
|
|
6054
6178
|
# Installed by the Omniralph agent: a branch worktree only pushes its own branch.
|
|
6055
6179
|
common=$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null) || exit 0
|
|
@@ -6114,6 +6238,19 @@ function withCall(job, call) {
|
|
|
6114
6238
|
if (!call || !("signal" in call)) return job;
|
|
6115
6239
|
return { env: job.env, signal: call.signal ?? void 0 };
|
|
6116
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
|
+
}
|
|
6117
6254
|
function hostEnv() {
|
|
6118
6255
|
return Object.fromEntries(
|
|
6119
6256
|
Object.entries(process.env).filter(([name]) => !name.startsWith("OMNIRALPH_"))
|
|
@@ -6136,7 +6273,7 @@ var RepoCache = class {
|
|
|
6136
6273
|
this.lockRetryMs = options.lockRetryMs ?? 250;
|
|
6137
6274
|
this.lockStaleMs = options.lockStaleMs ?? 3e4;
|
|
6138
6275
|
}
|
|
6139
|
-
/** `<workspaceRoot>/<provider>/<repo path>` */
|
|
6276
|
+
/** `<workspaceRoot>/<provider>/<host>/<repo path>` (host with its port, if any) */
|
|
6140
6277
|
repoDir(repo) {
|
|
6141
6278
|
const segments = repo.fullPath.split("/");
|
|
6142
6279
|
if (!PROVIDERS.includes(repo.provider) || segments.some(
|
|
@@ -6144,7 +6281,7 @@ var RepoCache = class {
|
|
|
6144
6281
|
)) {
|
|
6145
6282
|
throw new Error(`invalid repository path ${repo.provider}/${repo.fullPath}`);
|
|
6146
6283
|
}
|
|
6147
|
-
return path8.join(this.workspaceRoot, repo.provider, ...segments);
|
|
6284
|
+
return path8.join(this.workspaceRoot, repo.provider, hostDir(repo.cloneUrl), ...segments);
|
|
6148
6285
|
}
|
|
6149
6286
|
/**
|
|
6150
6287
|
* Environment for git commands run by others in a worktree (e.g. the
|
|
@@ -6159,7 +6296,7 @@ var RepoCache = class {
|
|
|
6159
6296
|
if (!JOB_ID.test(jobId)) throw new Error(`invalid job ID ${jobId}`);
|
|
6160
6297
|
return path8.join(this.workspaceRoot, WORKTREES_DIR, jobId);
|
|
6161
6298
|
}
|
|
6162
|
-
/** `<workspaceRoot>/.branches/<provider>/<repo path>/<branch with "/" → "__">` */
|
|
6299
|
+
/** `<workspaceRoot>/.branches/<provider>/<host>/<repo path>/<branch with "/" → "__">` */
|
|
6163
6300
|
branchWorktreePath(repo, branch) {
|
|
6164
6301
|
const relative2 = path8.relative(this.workspaceRoot, this.repoDir(repo));
|
|
6165
6302
|
return path8.join(this.workspaceRoot, BRANCHES_DIR, relative2, branch.replaceAll("/", "__"));
|
|
@@ -6425,7 +6562,9 @@ Stash ${entry.sha} from ${entry.date}, made on top of ${base}.`;
|
|
|
6425
6562
|
}
|
|
6426
6563
|
/**
|
|
6427
6564
|
* Startup cleanup after a crash: deletes every worktree under `.worktrees`
|
|
6428
|
-
* (branch worktrees under `.branches` are kept) and leftover partial clones,
|
|
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
|
|
6429
6568
|
* repository. Only call it while no job is running. Returns the removed
|
|
6430
6569
|
* worktree paths.
|
|
6431
6570
|
*/
|
|
@@ -6438,6 +6577,7 @@ Stash ${entry.sha} from ${entry.date}, made on top of ${base}.`;
|
|
|
6438
6577
|
removed.push(stale);
|
|
6439
6578
|
}
|
|
6440
6579
|
await rm7(path8.join(this.workspaceRoot, TMP_DIR), { recursive: true, force: true });
|
|
6580
|
+
await this.migrateLegacyRepos();
|
|
6441
6581
|
for (const provider of PROVIDERS) {
|
|
6442
6582
|
for (const dir of await this.findRepos(path8.join(this.workspaceRoot, provider), 0)) {
|
|
6443
6583
|
await this.withLock(
|
|
@@ -6453,6 +6593,96 @@ Stash ${entry.sha} from ${entry.date}, made on top of ${base}.`;
|
|
|
6453
6593
|
return removed;
|
|
6454
6594
|
}
|
|
6455
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
|
+
}
|
|
6456
6686
|
async checkBranchName(branch) {
|
|
6457
6687
|
const valid = await runGit(["check-ref-format", "--branch", branch], {
|
|
6458
6688
|
env: hostEnv(),
|
|
@@ -6690,6 +6920,7 @@ Stash ${entry.sha} from ${entry.date}, made on top of ${base}.`;
|
|
|
6690
6920
|
options
|
|
6691
6921
|
);
|
|
6692
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 });
|
|
6693
6924
|
await this.runGit(["fetch", "--quiet", "--filter=blob:none", "--no-tags", "origin"], {
|
|
6694
6925
|
...options,
|
|
6695
6926
|
cwd: tmp
|
|
@@ -7555,10 +7786,12 @@ function createQueueReceiver(server, region, currentToken) {
|
|
|
7555
7786
|
|
|
7556
7787
|
// src/update.ts
|
|
7557
7788
|
import { execFile as execFile2 } from "node:child_process";
|
|
7558
|
-
import {
|
|
7789
|
+
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
7790
|
+
import { readFile as readFile6, rm as rm8 } from "node:fs/promises";
|
|
7559
7791
|
import path9 from "node:path";
|
|
7560
7792
|
import { z as z14 } from "zod";
|
|
7561
7793
|
var UPDATE_STATE_FILE = "update-state.json";
|
|
7794
|
+
var UPDATE_REQUEST_FILE = "update-request.json";
|
|
7562
7795
|
var MAX_STARTS_SINCE_PENDING = 3;
|
|
7563
7796
|
var CONFIRM_AFTER_MS = 6e4;
|
|
7564
7797
|
var DRAIN_TIMEOUT_MS = 2 * 60 * 60 * 1e3;
|
|
@@ -7573,14 +7806,51 @@ var UpdateStateFile = z14.object({
|
|
|
7573
7806
|
startsSincePending: z14.int().min(0).default(0),
|
|
7574
7807
|
failed: z14.array(z14.string()).default([]),
|
|
7575
7808
|
/** Why the last update or rollback failed. */
|
|
7576
|
-
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)
|
|
7577
7812
|
});
|
|
7578
7813
|
function emptyState() {
|
|
7579
|
-
return {
|
|
7814
|
+
return {
|
|
7815
|
+
previous: null,
|
|
7816
|
+
pending: null,
|
|
7817
|
+
startsSincePending: 0,
|
|
7818
|
+
failed: [],
|
|
7819
|
+
lastError: null,
|
|
7820
|
+
handledRequestId: null
|
|
7821
|
+
};
|
|
7580
7822
|
}
|
|
7581
7823
|
function updateStatePath(configPath) {
|
|
7582
7824
|
return path9.join(path9.dirname(configPath), UPDATE_STATE_FILE);
|
|
7583
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
|
+
}
|
|
7584
7854
|
async function readUpdateState(file) {
|
|
7585
7855
|
let text;
|
|
7586
7856
|
try {
|
|
@@ -7601,6 +7871,18 @@ function writeUpdateState(file, state) {
|
|
|
7601
7871
|
}
|
|
7602
7872
|
function npmInstaller(env = process.env) {
|
|
7603
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
|
+
}),
|
|
7604
7886
|
install: (version) => new Promise((resolve2, reject) => {
|
|
7605
7887
|
execFile2(
|
|
7606
7888
|
"npm",
|
|
@@ -7634,6 +7916,8 @@ var SelfUpdater = class {
|
|
|
7634
7916
|
target = null;
|
|
7635
7917
|
/** Start of the current run of successful heartbeats while confirming. */
|
|
7636
7918
|
okSince = null;
|
|
7919
|
+
/** A heartbeat is being handled (they're not awaited, so the next may come meanwhile). */
|
|
7920
|
+
busy = false;
|
|
7637
7921
|
now;
|
|
7638
7922
|
drainTimeoutMs;
|
|
7639
7923
|
confirmAfterMs;
|
|
@@ -7692,26 +7976,86 @@ var SelfUpdater = class {
|
|
|
7692
7976
|
return {
|
|
7693
7977
|
selfUpdate: this.support,
|
|
7694
7978
|
update,
|
|
7695
|
-
failedVersions: this.state.failed.slice(-FAILED_VERSIONS_KEPT)
|
|
7979
|
+
failedVersions: this.state.failed.slice(-FAILED_VERSIONS_KEPT),
|
|
7980
|
+
handledUpdateRequestId: this.state.handledRequestId
|
|
7696
7981
|
};
|
|
7697
7982
|
}
|
|
7698
7983
|
/**
|
|
7699
7984
|
* Called after every heartbeat: `null` when it failed. Confirms a pending
|
|
7700
|
-
* version after `confirmAfterMs` of successful heartbeats,
|
|
7701
|
-
* 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.
|
|
7702
7987
|
*/
|
|
7703
7988
|
async onHeartbeat(response, daemon) {
|
|
7704
7989
|
if (!response) {
|
|
7705
7990
|
this.okSince = null;
|
|
7706
7991
|
return;
|
|
7707
7992
|
}
|
|
7708
|
-
if (this.
|
|
7709
|
-
|
|
7710
|
-
|
|
7711
|
-
|
|
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;
|
|
7712
8007
|
}
|
|
7713
|
-
|
|
7714
|
-
|
|
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;
|
|
7715
8059
|
}
|
|
7716
8060
|
/** The version to update to now, or null. */
|
|
7717
8061
|
wantedVersion(desired) {
|
|
@@ -7761,10 +8105,10 @@ var SelfUpdater = class {
|
|
|
7761
8105
|
return;
|
|
7762
8106
|
}
|
|
7763
8107
|
this.state = {
|
|
8108
|
+
...this.state,
|
|
7764
8109
|
previous: this.options.runningVersion,
|
|
7765
8110
|
pending: version,
|
|
7766
8111
|
startsSincePending: 0,
|
|
7767
|
-
failed: this.state.failed,
|
|
7768
8112
|
lastError: null
|
|
7769
8113
|
};
|
|
7770
8114
|
await this.save();
|
|
@@ -7798,6 +8142,9 @@ Commands:
|
|
|
7798
8142
|
--workspace-root <dir> Repo cache directory (default: ~/.omniralph/repos)
|
|
7799
8143
|
start Run the agent daemon
|
|
7800
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
|
|
7801
8148
|
git-credential Git credential helper for job git commands (\`get\` only; reads
|
|
7802
8149
|
OMNIRALPH_JOB_TOKEN, set by the agent for in-job processes)
|
|
7803
8150
|
|
|
@@ -7854,6 +8201,8 @@ ${USAGE}`);
|
|
|
7854
8201
|
return await runEnroll(values, configPath, deps);
|
|
7855
8202
|
case "start":
|
|
7856
8203
|
return await runStart(values, configPath, deps);
|
|
8204
|
+
case "update":
|
|
8205
|
+
return await runUpdate(configPath, deps);
|
|
7857
8206
|
case "git-credential":
|
|
7858
8207
|
return await runGitCredential(
|
|
7859
8208
|
positionals[1],
|
|
@@ -7924,6 +8273,19 @@ Run 'omniralph-agent start' to start the agent.
|
|
|
7924
8273
|
);
|
|
7925
8274
|
return 0;
|
|
7926
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
|
+
}
|
|
7927
8289
|
async function runStart(values, configPath, deps) {
|
|
7928
8290
|
let healthzPort;
|
|
7929
8291
|
if (values["healthz-port"] !== void 0) {
|
|
@@ -7939,6 +8301,7 @@ async function runStart(values, configPath, deps) {
|
|
|
7939
8301
|
const version = deps.version ?? AGENT_VERSION;
|
|
7940
8302
|
const updater = new SelfUpdater({
|
|
7941
8303
|
statePath: updateStatePath(configPath),
|
|
8304
|
+
requestPath: updateRequestPath(configPath),
|
|
7942
8305
|
runningVersion: version,
|
|
7943
8306
|
underPm2: runningUnderPm2(deps.env),
|
|
7944
8307
|
installer: deps.installer ?? npmInstaller(deps.env),
|