agent-relay-runner 0.125.0 → 0.126.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-relay-runner",
3
- "version": "0.125.0",
3
+ "version": "0.126.0",
4
4
  "description": "Unified provider lifecycle runner for Agent Relay",
5
5
  "type": "module",
6
6
  "bin": {
@@ -23,7 +23,7 @@
23
23
  },
24
24
  "dependencies": {
25
25
  "agent-relay-providers": "0.104.4",
26
- "agent-relay-sdk": "0.2.116",
26
+ "agent-relay-sdk": "0.2.117",
27
27
  "callmux": "0.23.0"
28
28
  },
29
29
  "devDependencies": {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "agent-relay-runner",
3
3
  "description": "Thin Agent Relay runner bridge for Claude Code",
4
- "version": "0.125.0",
4
+ "version": "0.126.0",
5
5
  "agentRelayContracts": {
6
6
  "providerPluginProtocol": 1
7
7
  }
@@ -45,17 +45,16 @@ export class CodexAgentMessageCapture {
45
45
  this.currentSegment = [];
46
46
  }
47
47
 
48
- // Deterministic turn-final response: the TRAILING agentMessage run only all items after
49
- // the LAST non-message item (tool call, file change, reasoning...) in the turn (design
50
- // #1079 §3.2). Earlier agentMessage segments are mid-work narration, already mirrored live
51
- // via `emit`, and must not be re-injected into the final (#1083 Finding 2). Codex's own
52
- // phase:"commentary" tag (see completeItem above) still trims commentary items out of
53
- // whichever segment they land in, but is not the sole guard against leading narration.
48
+ // Deterministic turn-final response: prefer the trailing structured report span, not a generic
49
+ // post-handoff coda. The original #1079/#1086 trailing-run rule correctly kept early narration
50
+ // out, but it over-trimmed Codex turns shaped "summary -> workspace ready -> Landed..." and made
51
+ // report-up deliver only the coda (#1136). We still drop leading narration; we just let structured
52
+ // report markers beat a terse final status line.
54
53
  finish(emit: EmitAgentMessage): string | undefined {
55
54
  this.closeSegment(emit);
56
- const trailingSegment = this.segments.at(-1);
55
+ const trailingSegment = selectFinalResponseSegments(this.segments);
57
56
  this.segments = [];
58
- const text = trailingSegment ? segmentBody(trailingSegment) : undefined;
57
+ const text = trailingSegment ? trailingSegment.map(segmentBody).join("\n\n").trim() : undefined;
59
58
  return truncateCapturedResponse(text);
60
59
  }
61
60
 
@@ -105,6 +104,37 @@ function segmentBody(segment: ResponseEntry[]): string {
105
104
  return segment.map((entry) => entry.body).join("\n\n").trim();
106
105
  }
107
106
 
107
+ function selectFinalResponseSegments(segments: ResponseEntry[][]): ResponseEntry[][] | undefined {
108
+ const bodies = segments.map(segmentBody).filter(Boolean);
109
+ if (!bodies.length) return undefined;
110
+ let end = bodies.length - 1;
111
+ while (end > 0 && isGenericFinalCoda(bodies[end]!) && bodies.slice(0, end).some(isSubstantiveReportSegment)) end--;
112
+ const firstReport = bodies.slice(0, end + 1).findIndex(isReportBoundarySegment);
113
+ if (firstReport >= 0) return segments.slice(firstReport, end + 1);
114
+ for (let i = end; i >= 0; i--) {
115
+ if (isSubstantiveReportSegment(bodies[i]!)) return [segments[i]!];
116
+ }
117
+ return [segments[end]!];
118
+ }
119
+
120
+ const REPORT_BOUNDARY = /(^|\n)(#{1,6}\s|\*\*(summary|what changed|rca|fix|tests?|gates?|verification|risk)\b|(?:summary|what changed|rca|fix|tests?|gates?|verification|risk):)/i;
121
+ const REPORT_STRUCTURE = /(^|\n)\s*[-*]\s+\S|`[^`]+`|\b(typecheck|bun test|tests? pass(?:ed)?|gates? green|rca|verified|implemented)\b/i;
122
+ const GENERIC_FINAL_CODA = /^(?:done|landed(?: on main)?|committed|merged|ready|no further action|nothing further|all set)\b|(?:\bno further action needed\b|\bnothing further needed\b)$/i;
123
+
124
+ function isReportBoundarySegment(body: string): boolean {
125
+ return REPORT_BOUNDARY.test(body.trim());
126
+ }
127
+
128
+ function isSubstantiveReportSegment(body: string): boolean {
129
+ const trimmed = body.trim();
130
+ return !isGenericFinalCoda(trimmed) && (trimmed.length >= 120 || isReportBoundarySegment(trimmed) || REPORT_STRUCTURE.test(trimmed));
131
+ }
132
+
133
+ function isGenericFinalCoda(body: string): boolean {
134
+ const trimmed = body.trim();
135
+ return trimmed.length <= 180 && GENERIC_FINAL_CODA.test(trimmed) && !isReportBoundarySegment(trimmed);
136
+ }
137
+
108
138
  function truncateCapturedResponse(text: string | undefined): string | undefined {
109
139
  if (!text || text.length <= MAX_CAPTURED_RESPONSE_CHARS) return text;
110
140
  return `${text.slice(0, MAX_CAPTURED_RESPONSE_CHARS).trimEnd()}\n\n${TRUNCATION_MARKER_PREFIX} showing first ${MAX_CAPTURED_RESPONSE_CHARS} of ${text.length} chars]`;
@@ -51,7 +51,7 @@ import {
51
51
  runnerAgentStatus,
52
52
  runnerBusErrorAction,
53
53
  runnerMessageMatches,
54
- runnerMessageShouldDirtyObligations,
54
+ runnerMessageShouldDirtyObligations, restartOptionsFromCommand,
55
55
  runnerShouldResolveProviderExit,
56
56
  runnerShouldRestartUnexpectedProviderExit,
57
57
  runtimeProviderCapabilities,
@@ -60,7 +60,7 @@ import {
60
60
  shouldLogDeliveryFailure,
61
61
  stripRunnerClaimedGuidance,
62
62
  taskIdFromMessage,
63
- type ProbeModelInfo,
63
+ type ProbeModelInfo, type RestartProviderOptions,
64
64
  } from "./runner-helpers";
65
65
 
66
66
  // Pre-destroy work is best-effort and must never hang teardown. Capping it keeps a slow
@@ -69,6 +69,7 @@ import {
69
69
  // short so a wedged/down server can't stall an operator-requested shutdown for long; a
70
70
  // row that still can't land is logged, not silently dropped.
71
71
  const OUTBOX_FLUSH_TIMEOUT_MS = 3_000;
72
+ const STALE_PROVIDER_TURN_BUSY_MS = 10 * 60_000;
72
73
 
73
74
  interface RunnerOptions {
74
75
  provider: string;
@@ -535,7 +536,7 @@ export class AgentRunner {
535
536
  return mode === "isolated";
536
537
  }
537
538
 
538
- private async spawnProvider(opts: { resumeId?: string; suppressPrompt?: boolean } = {}): Promise<ManagedProcess> {
539
+ private async spawnProvider(opts: RestartProviderOptions = {}): Promise<ManagedProcess> {
539
540
  this.providerSessionId = crypto.randomUUID();
540
541
  this.lastTranscriptPath = undefined;
541
542
  const includeProviderGlobals = profileUsesProviderHostGlobals(this.options);
@@ -586,7 +587,7 @@ export class AgentRunner {
586
587
  ...(this.options.profile ? { profile: this.options.profile } : {}),
587
588
  ...(this.options.agentProfile ? { agentProfile: this.options.agentProfile } : {}),
588
589
  ...(this.options.prompt && !opts.resumeId && !opts.suppressPrompt ? { prompt: this.options.prompt } : {}),
589
- ...(this.options.systemPromptAppend ? { systemPromptAppend: this.options.systemPromptAppend } : {}),
590
+ ...((opts.systemPromptAppend ?? this.options.systemPromptAppend) ? { systemPromptAppend: opts.systemPromptAppend ?? this.options.systemPromptAppend } : {}),
590
591
  ...(this.options.tmuxSession ? { tmuxSession: this.options.tmuxSession } : {}),
591
592
  providerArgs: opts.resumeId ? [...this.options.providerArgs, "--resume", opts.resumeId] : this.options.providerArgs,
592
593
  providerConfig: this.options.providerConfig,
@@ -604,7 +605,7 @@ export class AgentRunner {
604
605
  };
605
606
  const launchSeededPrompt = this.options.adapter.seedsInitialPromptAtLaunch && !opts.resumeId && !opts.suppressPrompt ? this.options.prompt?.trim() : ""; if (launchSeededPrompt) this.recordInjectedPrompt(launchSeededPrompt);
606
607
  const managedProcess = await this.options.adapter.spawn(config);
607
- const injectionEvents = runnerLaunchInjectionSessionEvents({ carried: this.options.relayInjectionEvents, provider: this.options.provider, config, providerConfig: this.options.providerConfig, agentId: this.agentId, providerSessionId: this.providerSessionId });
608
+ const injectionEvents = runnerLaunchInjectionSessionEvents({ carried: opts.relayInjectionEvents ?? this.options.relayInjectionEvents, provider: this.options.provider, config, providerConfig: this.options.providerConfig, agentId: this.agentId, providerSessionId: this.providerSessionId });
608
609
  for (const event of injectionEvents) {
609
610
  this.publishSessionEvent(event);
610
611
  }
@@ -777,7 +778,7 @@ export class AgentRunner {
777
778
  else this.lifecycleAction = undefined;
778
779
  this.publishStatus();
779
780
  let providerResult: Record<string, unknown> | void = undefined;
780
- if (type === "agent.restart") await this.restartProvider();
781
+ if (type === "agent.restart") await this.restartProvider(restartOptionsFromCommand(params));
781
782
  else if (type === "agent.reconnect") this.publishStatus();
782
783
  else if (type === "agent.compact") {
783
784
  if (!this.options.adapter.compact || !this.process) throw new Error("provider does not support compact");
@@ -927,7 +928,7 @@ export class AgentRunner {
927
928
  return attachmentText ? `${body}\n\n${attachmentText}` : body;
928
929
  }
929
930
 
930
- private async restartProvider(opts: { resumeId?: string; suppressPrompt?: boolean } = {}): Promise<void> {
931
+ private async restartProvider(opts: RestartProviderOptions = {}): Promise<void> {
931
932
  this.restartInProgress = true;
932
933
  try {
933
934
  if (this.process) {
@@ -1204,7 +1205,7 @@ export class AgentRunner {
1204
1205
  const providerSessionId = typeof update === "string" ? undefined : update.providerSessionId;
1205
1206
  if (providerSessionId && providerSessionId !== this.providerSessionId) return;
1206
1207
  const reason = typeof update === "string" ? "provider-turn" : update.reason ?? "provider-turn";
1207
- const id = typeof update === "string" ? reason : update.id ?? reason;
1208
+ let id = typeof update === "string" ? reason : update.id ?? reason;
1208
1209
  if (typeof update !== "string" && update.timeline) {
1209
1210
  this.pendingTimelineEvent = {
1210
1211
  status: update.timeline.status,
@@ -1300,8 +1301,10 @@ export class AgentRunner {
1300
1301
  this.compactionMidTurn = false;
1301
1302
  this.sessionLog(`turn started (turn ${this.currentTurnId})`);
1302
1303
  }
1304
+ id = this.currentTurnId;
1303
1305
  this.busyReconciler.arm();
1304
1306
  } else if (status === "idle" && reason === "provider-turn") {
1307
+ id = typeof update !== "string" && update.id ? update.id : this.currentTurnId ?? reason;
1305
1308
  if (this.currentTurnId) { this.completedProviderTurns += 1; this.sessionLog(`turn ended via provider idle (turn ${this.currentTurnId})`); }
1306
1309
  this.currentTurnId = undefined;
1307
1310
  this.currentTurnStartedAt = undefined;
@@ -1346,7 +1349,8 @@ export class AgentRunner {
1346
1349
  }
1347
1350
  } else if (status === "idle") {
1348
1351
  this.claims.clearTerminalStatus();
1349
- this.claims.finishWork(reason, id);
1352
+ if (reason === "provider-turn") this.claims.clearWorkKind("provider-turn");
1353
+ else this.claims.finishWork(reason, id);
1350
1354
  if (reason === "provider-turn") void this.completeObservedTaskClaims();
1351
1355
  }
1352
1356
  else if (status === "offline" || status === "error") this.claims.setTerminalStatus(status);
@@ -2007,15 +2011,25 @@ export class AgentRunner {
2007
2011
  });
2008
2012
  }
2009
2013
 
2014
+ private isStaleProviderTurnOnlyBusy(
2015
+ status: SemanticStatus,
2016
+ activeWork: Array<{ kind: string }>,
2017
+ busyReasons: string[],
2018
+ liveness: { hasLiveWork: boolean; lastProgressAt: number },
2019
+ ): boolean {
2020
+ if (status !== "busy") return false;
2021
+ if (activeWork.length === 0 || activeWork.some((work) => work.kind !== "provider-turn")) return false;
2022
+ if (busyReasons.some((reason) => reason !== "provider-turn")) return false;
2023
+ if (liveness.hasLiveWork || !liveness.lastProgressAt) return false;
2024
+ return Date.now() - liveness.lastProgressAt >= STALE_PROVIDER_TURN_BUSY_MS;
2025
+ }
2026
+
2010
2027
  private publishStatus(): void {
2011
2028
  this.claims.expire();
2012
2029
  const status = this.claims.currentStatus();
2013
- const agentStatus = runnerAgentStatus(status);
2014
2030
  const activeWork = this.claims.activeWork();
2015
2031
  const activeSubagents = activeWork.filter((item) => item.kind === "subagent");
2016
2032
  const terminalFailure = this.terminalFailure;
2017
- const providerState = terminalFailure?.providerState ?? this.rateLimitHold ?? providerStateFromActiveWork(activeWork);
2018
- this.bus.setSemanticStatus(status === "offline" || status === "error" ? "idle" : status);
2019
2033
  const timelineEvent = this.pendingTimelineEvent;
2020
2034
  this.pendingTimelineEvent = undefined;
2021
2035
  // §4.1 Runner↔provider liveness contract (#725 / #746): fold the raw transport/timeline/
@@ -2031,6 +2045,12 @@ export class AgentRunner {
2031
2045
  const liveness = this.options.adapter.liveness
2032
2046
  ? this.options.adapter.liveness(livenessInputs)
2033
2047
  : computeLivenessSignal(livenessInputs);
2048
+ const busyReasons = this.claims.reasons();
2049
+ const staleProviderTurnBusy = this.isStaleProviderTurnOnlyBusy(status, activeWork, busyReasons, liveness);
2050
+ const effectiveStatus = staleProviderTurnBusy ? "idle" : status;
2051
+ const agentStatus = runnerAgentStatus(effectiveStatus);
2052
+ const providerState = terminalFailure?.providerState ?? this.rateLimitHold ?? (staleProviderTurnBusy ? null : providerStateFromActiveWork(activeWork));
2053
+ this.bus.setSemanticStatus(effectiveStatus === "offline" || effectiveStatus === "error" ? "idle" : effectiveStatus);
2034
2054
  this.bus.status({
2035
2055
  agentStatus,
2036
2056
  ready: agentStatus !== "offline" && !this.stopped,
@@ -2062,7 +2082,7 @@ export class AgentRunner {
2062
2082
  ? { lastError: `Claude provider exited; resume id ${this.terminalProviderExit.claudeResumeId} captured for manual recovery` }
2063
2083
  : { lastError: "Claude provider exited; manual intervention required" }),
2064
2084
  } : {}),
2065
- busyReasons: this.claims.reasons(),
2085
+ busyReasons: staleProviderTurnBusy ? busyReasons.filter((reason) => reason !== "provider-turn") : busyReasons,
2066
2086
  completedProviderTurns: this.completedProviderTurns,
2067
2087
  activeWork,
2068
2088
  activeSubagents,
@@ -5,6 +5,7 @@ import { getManifest } from "agent-relay-providers";
5
5
  import type { BooleanCapabilityDefault, ProviderCapabilityCondition } from "agent-relay-providers";
6
6
  import { targetMatchesAgentIdentity } from "agent-relay-sdk/agent-target";
7
7
  import type { ProviderAdapter, ProviderConfig, RunnerSpawnConfig, SemanticStatus } from "./adapter";
8
+ import type { RunnerRelayInjectionEvent } from "./relay-injection-events";
8
9
  import { agentProfileProjectionReport } from "./profile-projection";
9
10
  import { assembleLaunch } from "./launch-assembly";
10
11
 
@@ -27,6 +28,13 @@ export interface ProbeModelInfo {
27
28
  effort?: string;
28
29
  }
29
30
 
31
+ export interface RestartProviderOptions {
32
+ resumeId?: string;
33
+ suppressPrompt?: boolean;
34
+ systemPromptAppend?: string;
35
+ relayInjectionEvents?: RunnerRelayInjectionEvent[];
36
+ }
37
+
30
38
  export function runnerMessageMatches(message: Pick<Message, "to" | "resolvedToAgent">, target: {
31
39
  agentId: string;
32
40
  label?: string;
@@ -62,6 +70,29 @@ export function stripRunnerClaimedGuidance(body: string): string {
62
70
  return body.replace(RUNNER_CLAIMED_GUIDANCE_RE, "");
63
71
  }
64
72
 
73
+ const RELAY_INJECTION_CATEGORIES = new Set(["memory", "instructions", "tools", "comms", "knowledge", "context"]);
74
+
75
+ function relayInjectionEventsFromParam(value: unknown): RunnerRelayInjectionEvent[] | undefined {
76
+ if (!Array.isArray(value)) return undefined;
77
+ const events = value.flatMap((item): RunnerRelayInjectionEvent[] => {
78
+ if (!item || typeof item !== "object" || Array.isArray(item)) return [];
79
+ const record = item as Record<string, unknown>;
80
+ const detail = record.detail;
81
+ if (typeof record.category !== "string" || !RELAY_INJECTION_CATEGORIES.has(record.category)) return [];
82
+ if (typeof record.summary !== "string" || !record.summary.trim()) return [];
83
+ if (!detail || typeof detail !== "object" || Array.isArray(detail)) return [];
84
+ return [{ category: record.category as RunnerRelayInjectionEvent["category"], summary: record.summary, detail: detail as Record<string, unknown> }];
85
+ });
86
+ return events.length ? events : undefined;
87
+ }
88
+
89
+ export function restartOptionsFromCommand(params: Record<string, unknown>): RestartProviderOptions {
90
+ return {
91
+ systemPromptAppend: typeof params.systemPromptAppend === "string" ? params.systemPromptAppend : undefined,
92
+ relayInjectionEvents: relayInjectionEventsFromParam(params.relayInjectionEvents),
93
+ };
94
+ }
95
+
65
96
  // Bound a runner's INITIAL relay registration. `connect` resolves on the first `registered`
66
97
  // frame and otherwise loops forever, so a token the relay rejects (401 at the WS upgrade)
67
98
  // hangs here silently. Race it against `timeoutMs`; on timeout, surface a fatal reason, tear