@omniralph/agent 0.3.1 → 0.4.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
@@ -885,6 +885,12 @@ var RalphPullRequestAction = z10.object({
885
885
  title: z10.string().trim().min(1).max(500).optional(),
886
886
  body: z10.string().trim().min(1).max(6e4).optional()
887
887
  });
888
+ var RALPH_FINDING_OUTCOMES = ["fixed", "skipped"];
889
+ var RalphFindingOutcome = z10.object({
890
+ findingId: z10.uuid(),
891
+ outcome: z10.enum(RALPH_FINDING_OUTCOMES),
892
+ comment: z10.string().trim().min(1).max(2e3)
893
+ });
888
894
  var RalphRequestResult = z10.object({
889
895
  /** For the Linear thread: what the session did, or why it couldn't (`error`). */
890
896
  summary: z10.string().max(2e4),
@@ -893,6 +899,8 @@ var RalphRequestResult = z10.object({
893
899
  /** The Claude session, resumed by the lane's next request on the same agent. */
894
900
  sessionId: z10.string().min(1).max(200).nullable(),
895
901
  pullRequest: RalphPullRequestAction.optional(),
902
+ /** The review findings the session fixed or skipped. */
903
+ findings: z10.array(RalphFindingOutcome).max(50).optional(),
896
904
  /** What the session left uncommitted, stashed. */
897
905
  stashSha: CommitSha.optional(),
898
906
  usage: TokenUsage,
@@ -3273,7 +3281,7 @@ var RALPH_TOOL_POLICY = {
3273
3281
  disallowedTools: [],
3274
3282
  fileScope: "cwd",
3275
3283
  permissionMode: "bypassPermissions",
3276
- settingSources: ["project", "local"],
3284
+ settingSources: ["user", "project", "local"],
3277
3285
  writable: true
3278
3286
  };
3279
3287
  var DESCRIBE_PR_GIT_COMMANDS = [
@@ -3457,8 +3465,8 @@ function problemWith(error) {
3457
3465
  return `invalid structured result: ${issue?.path.length ? `\`${issue.path.join(".")}\` ` : ""}${issue?.message ?? "doesn't match the schema"}`;
3458
3466
  }
3459
3467
  var StoryAgentOutput = z11.object({
3460
- status: z11.enum(["complete", "blocked", "incomplete"]).describe(
3461
- "complete: every acceptance criterion is met. blocked: a retry can't get past an obstacle. incomplete: unfinished; try again."
3468
+ status: z11.enum(["complete", "blocked", "incomplete", "waiting"]).describe(
3469
+ "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."
3462
3470
  ),
3463
3471
  summary: z11.string().describe(
3464
3472
  "Posted to Linear: what you did, or precisely what is in the way and what would unblock it."
@@ -3479,6 +3487,9 @@ var StoryAgentOutput = z11.object({
3479
3487
  "Work outside this story's scope for the orchestrator to file as new stories. Empty when there is none."
3480
3488
  )
3481
3489
  });
3490
+ function isWaitingStory(structured) {
3491
+ return structured?.status === "waiting";
3492
+ }
3482
3493
  var STORY_OUTPUT_SCHEMA = jsonSchema(StoryAgentOutput);
3483
3494
  function readStoryOutcome(structured) {
3484
3495
  const parsed = structured === void 0 ? void 0 : StoryAgentOutput.safeParse(structured);
@@ -3516,21 +3527,49 @@ var RequestAgentOutput = z11.object({
3516
3527
  body: z11.string().optional().describe("The markdown description (open, update).")
3517
3528
  }).optional().describe(
3518
3529
  "A change to the branch's pull/merge request for the orchestrator to make; push the branch first."
3530
+ ),
3531
+ findings: z11.array(
3532
+ z11.object({
3533
+ id: z11.string().describe("The finding's ID, as given in the request."),
3534
+ outcome: z11.enum(["fixed", "skipped"]).describe("fixed: you changed the code for it. skipped: it's wrong or not worth it."),
3535
+ comment: z11.string().describe(
3536
+ "Posted in the finding's thread: one or two sentences on the change, or on why you skipped it."
3537
+ )
3538
+ })
3539
+ ).optional().describe(
3540
+ "What you did with each review finding the request lists by ID. Omniralph replies in the threads and resolves the fixed ones."
3541
+ ),
3542
+ waiting: z11.boolean().optional().describe(
3543
+ "True only when you are ending your turn to wait for background work you started; you are resumed when it finishes."
3519
3544
  )
3520
3545
  });
3546
+ function isWaitingRequest(structured) {
3547
+ return structured?.waiting === true;
3548
+ }
3521
3549
  var REQUEST_OUTPUT_SCHEMA = jsonSchema(RequestAgentOutput);
3550
+ var MAX_FINDING_OUTCOMES = 50;
3551
+ var MAX_FINDING_COMMENT = 2e3;
3552
+ var FindingId = z11.uuid();
3522
3553
  function readRequestResult(structured) {
3523
3554
  const parsed = structured === void 0 ? void 0 : RequestAgentOutput.safeParse(structured);
3524
3555
  if (!parsed?.success) return { problem: problemWith(parsed?.error) };
3525
3556
  const { pullRequest } = parsed.data;
3526
3557
  const title = pullRequest?.title?.replace(/\s+/g, " ").trim();
3527
3558
  const body = pullRequest?.body?.trim();
3559
+ const findings = [];
3560
+ for (const f of parsed.data.findings ?? []) {
3561
+ const id = f.id.trim().toLowerCase();
3562
+ const comment = f.comment.trim();
3563
+ if (!comment || !FindingId.safeParse(id).success || findings.some((x) => x.id === id)) continue;
3564
+ findings.push({ id, outcome: f.outcome, comment: comment.slice(0, MAX_FINDING_COMMENT) });
3565
+ }
3528
3566
  return {
3529
3567
  result: {
3530
3568
  summary: parsed.data.summary.trim(),
3531
3569
  ...pullRequest && {
3532
3570
  pullRequest: { action: pullRequest.action, ...title && { title }, ...body && { body } }
3533
- }
3571
+ },
3572
+ ...findings.length > 0 && { findings: findings.slice(0, MAX_FINDING_OUTCOMES) }
3534
3573
  }
3535
3574
  };
3536
3575
  }
@@ -3553,7 +3592,8 @@ function normalizeCommand(cmd) {
3553
3592
  var RALPH_SYSTEM_APPEND = `You are "Omniralph", an autonomous engineer working a Linear epic one user story at a time (the Ralph loop).
3554
3593
  - Work only on the single story you are given; other stories get their own sessions.
3555
3594
  - 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.
3556
- - Be precise and verifiable. Only report the status "complete" in your structured result when the story truly meets its acceptance criteria.`;
3595
+ - 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.`;
3557
3597
  var DEFAULT_STORY_TEMPLATE = `You are working through a PRD epic from Linear, one user story per session.
3558
3598
  Each session starts with a fresh context: the PRD, the progress log and the repository are your memory.
3559
3599
 
@@ -3667,6 +3707,7 @@ Your session ends with a structured result (the JSON schema you were given). It
3667
3707
  - \`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.
3668
3708
  - \`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 }\`.
3669
3709
  - \`status: "incomplete"\` when the story is just unfinished: it gets another attempt.
3710
+ - \`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.
3670
3711
  - \`summary\` is posted to Linear: what you did, or what is in the way.
3671
3712
  {{#if followUps}}
3672
3713
 
@@ -3823,7 +3864,8 @@ function requestSystemAppend(historyRewrite = "when-asked") {
3823
3864
  - 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.
3824
3865
  - Only push the epic branch you are on. Never push to, or force-push, the base branch or any other branch.
3825
3866
  ${rewrite}
3826
- - The \`summary\` of your structured result is posted to the Linear thread: summarise what you did, with links (e.g. the PR/MR URL).`;
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.`;
3827
3869
  }
3828
3870
  function capitalize(text) {
3829
3871
  return text.charAt(0).toUpperCase() + text.slice(1);
@@ -4110,6 +4152,9 @@ function readOnlyCommandGuard(commands) {
4110
4152
  // src/capabilities/ralph/session.ts
4111
4153
  var SESSION_IDLE_TIMEOUT_MS = 5 * 6e4;
4112
4154
  var INJECTION_IDLE_TIMEOUT_MS = 5 * 6e4;
4155
+ var BACKGROUND_WAIT_TIMEOUT_MS = 60 * 6e4;
4156
+ var WAIT_NUDGE_DELAY_MS = 3e4;
4157
+ 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.";
4113
4158
  var RATE_LIMIT_TEXT2 = /rate[_ ]limit|usage limit|\b429\b|too many requests/i;
4114
4159
  function retryAfter2(resetsAt) {
4115
4160
  if (resetsAt === void 0) return void 0;
@@ -4191,6 +4236,18 @@ function createSessionRunner(query = sdkQuery2) {
4191
4236
  return seen.sessionId ? { ...result, sessionId: seen.sessionId } : result;
4192
4237
  };
4193
4238
  }
4239
+ function startsTurn(message) {
4240
+ switch (message.type) {
4241
+ case "assistant":
4242
+ case "user":
4243
+ case "stream_event":
4244
+ return message.parent_tool_use_id === null;
4245
+ case "system":
4246
+ return message.subtype === "init";
4247
+ default:
4248
+ return false;
4249
+ }
4250
+ }
4194
4251
  async function runQuery(query, request, seen) {
4195
4252
  const controller = new AbortController();
4196
4253
  const onAbort = () => controller.abort(request.signal.reason);
@@ -4229,6 +4286,48 @@ async function runQuery(query, request, seen) {
4229
4286
  return true;
4230
4287
  });
4231
4288
  controller.signal.addEventListener("abort", finishInput, { once: true });
4289
+ const live = /* @__PURE__ */ new Set();
4290
+ let waiting = false;
4291
+ let nudged = false;
4292
+ let waitStopped;
4293
+ let waitTimer;
4294
+ let nudgeTimer;
4295
+ const backgroundWaitTimeoutMs = request.backgroundWaitTimeoutMs ?? BACKGROUND_WAIT_TIMEOUT_MS;
4296
+ const waitNudgeDelayMs = request.waitNudgeDelayMs ?? WAIT_NUDGE_DELAY_MS;
4297
+ const stopWaiting = (why) => {
4298
+ waitStopped = why;
4299
+ controller.abort(new Error(why));
4300
+ };
4301
+ const watchNothingRunning = () => {
4302
+ clearTimeout(nudgeTimer);
4303
+ if (!waiting || live.size > 0) return;
4304
+ nudgeTimer = setTimeout(() => {
4305
+ if (nudged) {
4306
+ stopWaiting("the session kept waiting with nothing running in the background");
4307
+ return;
4308
+ }
4309
+ nudged = true;
4310
+ send(WAIT_NUDGE_TEXT, "next");
4311
+ watchNothingRunning();
4312
+ }, waitNudgeDelayMs);
4313
+ };
4314
+ const startWaiting = () => {
4315
+ waiting = true;
4316
+ clearTimeout(idleTimer);
4317
+ clearTimeout(waitTimer);
4318
+ waitTimer = setTimeout(
4319
+ () => stopWaiting(
4320
+ `the background work took longer than ${Math.round(backgroundWaitTimeoutMs / 6e4)} minutes`
4321
+ ),
4322
+ backgroundWaitTimeoutMs
4323
+ );
4324
+ watchNothingRunning();
4325
+ };
4326
+ const endWaiting = () => {
4327
+ waiting = false;
4328
+ clearTimeout(waitTimer);
4329
+ clearTimeout(nudgeTimer);
4330
+ };
4232
4331
  const texts = [];
4233
4332
  const last = () => texts.at(-1) ?? "";
4234
4333
  let rateLimited = false;
@@ -4236,6 +4335,7 @@ async function runQuery(query, request, seen) {
4236
4335
  let answered;
4237
4336
  const stopped = () => {
4238
4337
  if (request.signal.aborted) return { stop: "aborted", output: last(), usage };
4338
+ if (waitStopped && answered) return { ...answered, error: waitStopped };
4239
4339
  if (idle) {
4240
4340
  return {
4241
4341
  stop: "idle",
@@ -4250,8 +4350,17 @@ async function runQuery(query, request, seen) {
4250
4350
  try {
4251
4351
  const messages = query({ prompt: input, options: sessionOptions(request, controller) });
4252
4352
  for await (const message of messages) {
4253
- clearTimeout(injectionTimer);
4254
- resetIdle();
4353
+ if (message.type === "system" && message.subtype === "background_tasks_changed") {
4354
+ live.clear();
4355
+ for (const task of message.tasks) if (!task.ambient) live.add(task.task_id);
4356
+ if (live.size > 0) nudged = false;
4357
+ watchNothingRunning();
4358
+ }
4359
+ if (!waiting || startsTurn(message)) {
4360
+ clearTimeout(injectionTimer);
4361
+ endWaiting();
4362
+ resetIdle();
4363
+ }
4255
4364
  if ("session_id" in message && message.session_id) seen.sessionId = message.session_id;
4256
4365
  switch (message.type) {
4257
4366
  case "assistant": {
@@ -4293,10 +4402,12 @@ async function runQuery(query, request, seen) {
4293
4402
  };
4294
4403
  const ids = message.user_message_uuids ?? (message.user_message_uuid ? [message.user_message_uuid] : [...outstanding]);
4295
4404
  for (const id of ids) outstanding.delete(id);
4296
- if (outstanding.size === 0) return result;
4405
+ const waits = request.isWaiting?.(message.structured_output) === true;
4406
+ if (!waits && outstanding.size === 0) return result;
4297
4407
  answered = result;
4298
4408
  clearTimeout(idleTimer);
4299
- injectionTimer = setTimeout(finishInput, injectionIdleTimeoutMs);
4409
+ if (waits) startWaiting();
4410
+ else injectionTimer = setTimeout(finishInput, injectionIdleTimeoutMs);
4300
4411
  break;
4301
4412
  }
4302
4413
  const detail = message.subtype === "success" ? message.result : [message.subtype, ...message.errors].join(": ");
@@ -4337,6 +4448,7 @@ async function runQuery(query, request, seen) {
4337
4448
  return { stop: "error", output: last(), error: text, usage };
4338
4449
  } finally {
4339
4450
  clearTimeout(idleTimer);
4451
+ endWaiting();
4340
4452
  finishInput();
4341
4453
  request.signal.removeEventListener("abort", onAbort);
4342
4454
  controller.signal.removeEventListener("abort", finishInput);
@@ -4790,6 +4902,7 @@ async function runStory(job, ctx, options = {}) {
4790
4902
  policy: RALPH_TOOL_POLICY,
4791
4903
  systemAppend: RALPH_SYSTEM_APPEND,
4792
4904
  outputSchema: STORY_OUTPUT_SCHEMA,
4905
+ isWaiting: isWaitingStory,
4793
4906
  model: payload.settings.model ?? DEFAULT_STORY_MODEL,
4794
4907
  ...payload.settings.fallbackModel && {
4795
4908
  fallbackModel: payload.settings.fallbackModel
@@ -4880,6 +4993,15 @@ Its work so far is committed on the branch as \`${kept.sha.slice(0, 10)}\`.`,
4880
4993
  commitSha: kept.sha
4881
4994
  });
4882
4995
  }
4996
+ if (outcome.status === "waiting") {
4997
+ return notDone(
4998
+ "incomplete",
4999
+ `The previous session was stopped while it waited for background work (${session.error ?? "it gave up waiting"}). Its summary was:
5000
+
5001
+ ${quote(tail(summary, 3e3))}`,
5002
+ "waiting"
5003
+ );
5004
+ }
4883
5005
  if (outcome.status === "incomplete") {
4884
5006
  return notDone(
4885
5007
  "incomplete",
@@ -5439,6 +5561,7 @@ async function runRequest(job, ctx, options = {}) {
5439
5561
  policy: RALPH_TOOL_POLICY,
5440
5562
  systemAppend: requestSystemAppend(payload.historyRewrite),
5441
5563
  outputSchema: REQUEST_OUTPUT_SCHEMA,
5564
+ isWaiting: isWaitingRequest,
5442
5565
  model: payload.settings.model ?? DEFAULT_STORY_MODEL,
5443
5566
  ...payload.settings.fallbackModel && {
5444
5567
  fallbackModel: payload.settings.fallbackModel
@@ -5486,15 +5609,22 @@ async function runRequest(job, ctx, options = {}) {
5486
5609
  usage: session.usage,
5487
5610
  durationMs: Date.now() - started
5488
5611
  };
5489
- if (!read || "problem" in read) {
5490
- const why = read ? `it ended without a valid structured result (${read.problem})` : sessionError(session);
5612
+ const stoppedWaiting = session.stop === "completed" && isWaitingRequest(session.structured);
5613
+ if (!read || "problem" in read || stoppedWaiting) {
5614
+ 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);
5491
5615
  return {
5492
5616
  ...base,
5493
5617
  summary: clip3(tail4(session.output, 2e3)),
5494
5618
  error: clip3(why)
5495
5619
  };
5496
5620
  }
5497
- log.info({ pullRequest: read.result.pullRequest?.action ?? null }, "request done");
5621
+ log.info(
5622
+ {
5623
+ pullRequest: read.result.pullRequest?.action ?? null,
5624
+ findings: read.result.findings?.length ?? 0
5625
+ },
5626
+ "request done"
5627
+ );
5498
5628
  return {
5499
5629
  ...base,
5500
5630
  summary: clip3(read.result.summary),
@@ -5509,6 +5639,13 @@ async function runRequest(job, ctx, options = {}) {
5509
5639
  body: clip3(read.result.pullRequest.body, 6e4)
5510
5640
  }
5511
5641
  }
5642
+ },
5643
+ ...read.result.findings && {
5644
+ findings: read.result.findings.map((f) => ({
5645
+ findingId: f.id,
5646
+ outcome: f.outcome,
5647
+ comment: f.comment
5648
+ }))
5512
5649
  }
5513
5650
  };
5514
5651
  } catch (error) {