@omniralph/agent 0.3.2 → 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
@@ -3465,8 +3465,8 @@ function problemWith(error) {
3465
3465
  return `invalid structured result: ${issue?.path.length ? `\`${issue.path.join(".")}\` ` : ""}${issue?.message ?? "doesn't match the schema"}`;
3466
3466
  }
3467
3467
  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."
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."
3470
3470
  ),
3471
3471
  summary: z11.string().describe(
3472
3472
  "Posted to Linear: what you did, or precisely what is in the way and what would unblock it."
@@ -3487,6 +3487,9 @@ var StoryAgentOutput = z11.object({
3487
3487
  "Work outside this story's scope for the orchestrator to file as new stories. Empty when there is none."
3488
3488
  )
3489
3489
  });
3490
+ function isWaitingStory(structured) {
3491
+ return structured?.status === "waiting";
3492
+ }
3490
3493
  var STORY_OUTPUT_SCHEMA = jsonSchema(StoryAgentOutput);
3491
3494
  function readStoryOutcome(structured) {
3492
3495
  const parsed = structured === void 0 ? void 0 : StoryAgentOutput.safeParse(structured);
@@ -3535,8 +3538,14 @@ var RequestAgentOutput = z11.object({
3535
3538
  })
3536
3539
  ).optional().describe(
3537
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."
3538
3544
  )
3539
3545
  });
3546
+ function isWaitingRequest(structured) {
3547
+ return structured?.waiting === true;
3548
+ }
3540
3549
  var REQUEST_OUTPUT_SCHEMA = jsonSchema(RequestAgentOutput);
3541
3550
  var MAX_FINDING_OUTCOMES = 50;
3542
3551
  var MAX_FINDING_COMMENT = 2e3;
@@ -3583,7 +3592,8 @@ function normalizeCommand(cmd) {
3583
3592
  var RALPH_SYSTEM_APPEND = `You are "Omniralph", an autonomous engineer working a Linear epic one user story at a time (the Ralph loop).
3584
3593
  - Work only on the single story you are given; other stories get their own sessions.
3585
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.
3586
- - 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.`;
3587
3597
  var DEFAULT_STORY_TEMPLATE = `You are working through a PRD epic from Linear, one user story per session.
3588
3598
  Each session starts with a fresh context: the PRD, the progress log and the repository are your memory.
3589
3599
 
@@ -3697,6 +3707,7 @@ Your session ends with a structured result (the JSON schema you were given). It
3697
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.
3698
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 }\`.
3699
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.
3700
3711
  - \`summary\` is posted to Linear: what you did, or what is in the way.
3701
3712
  {{#if followUps}}
3702
3713
 
@@ -3853,7 +3864,8 @@ function requestSystemAppend(historyRewrite = "when-asked") {
3853
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.
3854
3865
  - Only push the epic branch you are on. Never push to, or force-push, the base branch or any other branch.
3855
3866
  ${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).`;
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.`;
3857
3869
  }
3858
3870
  function capitalize(text) {
3859
3871
  return text.charAt(0).toUpperCase() + text.slice(1);
@@ -4140,6 +4152,9 @@ function readOnlyCommandGuard(commands) {
4140
4152
  // src/capabilities/ralph/session.ts
4141
4153
  var SESSION_IDLE_TIMEOUT_MS = 5 * 6e4;
4142
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.";
4143
4158
  var RATE_LIMIT_TEXT2 = /rate[_ ]limit|usage limit|\b429\b|too many requests/i;
4144
4159
  function retryAfter2(resetsAt) {
4145
4160
  if (resetsAt === void 0) return void 0;
@@ -4221,6 +4236,18 @@ function createSessionRunner(query = sdkQuery2) {
4221
4236
  return seen.sessionId ? { ...result, sessionId: seen.sessionId } : result;
4222
4237
  };
4223
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
+ }
4224
4251
  async function runQuery(query, request, seen) {
4225
4252
  const controller = new AbortController();
4226
4253
  const onAbort = () => controller.abort(request.signal.reason);
@@ -4259,6 +4286,48 @@ async function runQuery(query, request, seen) {
4259
4286
  return true;
4260
4287
  });
4261
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
+ };
4262
4331
  const texts = [];
4263
4332
  const last = () => texts.at(-1) ?? "";
4264
4333
  let rateLimited = false;
@@ -4266,6 +4335,7 @@ async function runQuery(query, request, seen) {
4266
4335
  let answered;
4267
4336
  const stopped = () => {
4268
4337
  if (request.signal.aborted) return { stop: "aborted", output: last(), usage };
4338
+ if (waitStopped && answered) return { ...answered, error: waitStopped };
4269
4339
  if (idle) {
4270
4340
  return {
4271
4341
  stop: "idle",
@@ -4280,8 +4350,17 @@ async function runQuery(query, request, seen) {
4280
4350
  try {
4281
4351
  const messages = query({ prompt: input, options: sessionOptions(request, controller) });
4282
4352
  for await (const message of messages) {
4283
- clearTimeout(injectionTimer);
4284
- 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
+ }
4285
4364
  if ("session_id" in message && message.session_id) seen.sessionId = message.session_id;
4286
4365
  switch (message.type) {
4287
4366
  case "assistant": {
@@ -4323,10 +4402,12 @@ async function runQuery(query, request, seen) {
4323
4402
  };
4324
4403
  const ids = message.user_message_uuids ?? (message.user_message_uuid ? [message.user_message_uuid] : [...outstanding]);
4325
4404
  for (const id of ids) outstanding.delete(id);
4326
- if (outstanding.size === 0) return result;
4405
+ const waits = request.isWaiting?.(message.structured_output) === true;
4406
+ if (!waits && outstanding.size === 0) return result;
4327
4407
  answered = result;
4328
4408
  clearTimeout(idleTimer);
4329
- injectionTimer = setTimeout(finishInput, injectionIdleTimeoutMs);
4409
+ if (waits) startWaiting();
4410
+ else injectionTimer = setTimeout(finishInput, injectionIdleTimeoutMs);
4330
4411
  break;
4331
4412
  }
4332
4413
  const detail = message.subtype === "success" ? message.result : [message.subtype, ...message.errors].join(": ");
@@ -4367,6 +4448,7 @@ async function runQuery(query, request, seen) {
4367
4448
  return { stop: "error", output: last(), error: text, usage };
4368
4449
  } finally {
4369
4450
  clearTimeout(idleTimer);
4451
+ endWaiting();
4370
4452
  finishInput();
4371
4453
  request.signal.removeEventListener("abort", onAbort);
4372
4454
  controller.signal.removeEventListener("abort", finishInput);
@@ -4820,6 +4902,7 @@ async function runStory(job, ctx, options = {}) {
4820
4902
  policy: RALPH_TOOL_POLICY,
4821
4903
  systemAppend: RALPH_SYSTEM_APPEND,
4822
4904
  outputSchema: STORY_OUTPUT_SCHEMA,
4905
+ isWaiting: isWaitingStory,
4823
4906
  model: payload.settings.model ?? DEFAULT_STORY_MODEL,
4824
4907
  ...payload.settings.fallbackModel && {
4825
4908
  fallbackModel: payload.settings.fallbackModel
@@ -4910,6 +4993,15 @@ Its work so far is committed on the branch as \`${kept.sha.slice(0, 10)}\`.`,
4910
4993
  commitSha: kept.sha
4911
4994
  });
4912
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
+ }
4913
5005
  if (outcome.status === "incomplete") {
4914
5006
  return notDone(
4915
5007
  "incomplete",
@@ -5469,6 +5561,7 @@ async function runRequest(job, ctx, options = {}) {
5469
5561
  policy: RALPH_TOOL_POLICY,
5470
5562
  systemAppend: requestSystemAppend(payload.historyRewrite),
5471
5563
  outputSchema: REQUEST_OUTPUT_SCHEMA,
5564
+ isWaiting: isWaitingRequest,
5472
5565
  model: payload.settings.model ?? DEFAULT_STORY_MODEL,
5473
5566
  ...payload.settings.fallbackModel && {
5474
5567
  fallbackModel: payload.settings.fallbackModel
@@ -5516,8 +5609,9 @@ async function runRequest(job, ctx, options = {}) {
5516
5609
  usage: session.usage,
5517
5610
  durationMs: Date.now() - started
5518
5611
  };
5519
- if (!read || "problem" in read) {
5520
- 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);
5521
5615
  return {
5522
5616
  ...base,
5523
5617
  summary: clip3(tail4(session.output, 2e3)),