Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

Move shared Prime HTTP helpers into core/prime-http.ts (#2510)

Sebastian Müller1ae4c62ba5e5
diff --git a/packages/coding-agent/.changes/dedupe-prime-http-helpers.md b/packages/coding-agent/.changes/dedupe-prime-http-helpers.md
new file mode 100644
index 0000000000..e1cae6d081
--- /dev/null
+++ b/packages/coding-agent/.changes/dedupe-prime-http-helpers.md
@@ -0,0 +1 @@
+- Prime Inference login and agent trace uploads now share one set of HTTP helpers (request timeout, error-body parsing, field readers). A Prime Inference request that is still waiting on its timeout no longer keeps the process alive on its own.
diff --git a/packages/coding-agent/src/core/agent-traces.ts b/packages/coding-agent/src/core/agent-traces.ts
index 58fb2b6beb..2981a5c31f 100644
--- a/packages/coding-agent/src/core/agent-traces.ts
+++ b/packages/coding-agent/src/core/agent-traces.ts
@@ -6,6 +6,15 @@ import { dirname, isAbsolute, join, resolve } from "node:path";
import { appendRotatingLog, getAgentDir, getAgentTracesLogPath, getSessionsDir, VERSION } from "../config.js";
import { readFirstLineSync } from "../utils/file-lines.js";
import type { AuthStorage } from "./auth-storage.js";
+import {
+ fetchWithTimeout,
+ isRecord,
+ numberField,
+ parseResponseObject,
+ readResponseMessage,
+ stringEnv,
+ stringField,
+} from "./prime-http.js";
import {
PRIME_AGENT_TRACES_PROVIDER_ID,
PRIME_INFERENCE_PROVIDER_ID,
@@ -157,15 +166,6 @@ export interface AgentTraceUploadAllResult {
results: Array<{ sessionFile: string; result: AgentTraceUploadResult }>;
}
-function stringEnv(name: string): string | undefined {
- const value = process.env[name];
- return typeof value === "string" && value.trim() ? value.trim() : undefined;
-}
-
-function isRecord(value: unknown): value is Record<string, unknown> {
- return typeof value === "object" && value !== null && !Array.isArray(value);
-}
-
function describeError(error: unknown): string {
if (!(error instanceof Error)) {
return String(error);
@@ -216,16 +216,6 @@ function isRetriableNetworkError(error: unknown): boolean {
return isRecord(cause) && typeof cause.code === "string" && RETRIABLE_NETWORK_CODES.has(cause.code);
}
-function stringField(data: Record<string, unknown>, key: string): string | undefined {
- const value = data[key];
- return typeof value === "string" && value.trim() ? value.trim() : undefined;
-}
-
-function numberField(data: Record<string, unknown>, key: string): number | undefined {
- const value = data[key];
- return typeof value === "number" && Number.isFinite(value) ? value : undefined;
-}
-
function isSessionHeader(value: unknown): value is SessionHeader {
return (
isRecord(value) &&
@@ -320,75 +310,6 @@ function resolveTraceContext(
return { traceId, parentSessionId };
}
-function parseResponseObject(text: string): Record<string, unknown> | undefined {
- if (!text.trim()) {
- return undefined;
- }
- try {
- const parsed = JSON.parse(text) as unknown;
- return isRecord(parsed) ? parsed : undefined;
- } catch {
- return undefined;
- }
-}
-
-async function readResponseMessage(response: Response): Promise<string> {
- const text = await response.text().catch(() => "");
- if (!text.trim()) {
- return response.statusText || "Unknown error";
- }
-
- const parsed = parseResponseObject(text);
- if (parsed) {
- const error = parsed.error;
- if (isRecord(error)) {
- const message = stringField(error, "message");
- if (message) return message;
- }
- const detail = stringField(parsed, "detail");
- if (detail) return detail;
- const message = stringField(parsed, "message");
- if (message) return message;
- }
-
- return text.trim();
-}
-
-async function fetchWithTimeout(
- fetchFn: typeof fetch,
- url: string,
- init: RequestInit,
- timeoutMs: number,
- signal?: AbortSignal,
-): Promise<Response> {
- const controller = new AbortController();
- const timeoutError = new TraceUploadTimeoutError(timeoutMs);
- let timedOut = false;
- const timeout = setTimeout(() => {
- timedOut = true;
- controller.abort(timeoutError);
- }, timeoutMs);
- timeout.unref();
- const onAbort = () => controller.abort(signal?.reason);
- if (signal?.aborted) {
- onAbort();
- } else {
- signal?.addEventListener("abort", onAbort, { once: true });
- }
-
- try {
- return await fetchFn(url, { ...init, signal: controller.signal });
- } catch (error) {
- if (timedOut) {
- throw timeoutError;
- }
- throw error;
- } finally {
- clearTimeout(timeout);
- signal?.removeEventListener("abort", onAbort);
- }
-}
-
function delay(ms: number, signal?: AbortSignal): Promise<void> {
return new Promise((resolve) => {
if (signal?.aborted) {
@@ -450,7 +371,10 @@ async function fetchWithRetry(request: TraceUploadRequest): Promise<Response> {
if (signal?.aborted) {
throw signal.reason ?? new Error("Trace upload cancelled");
}
- const response = await fetchWithTimeout(fetchFn, url, init, timeoutMs, signal);
+ const response = await fetchWithTimeout(fetchFn, url, init, timeoutMs, {
+ timeoutError: new TraceUploadTimeoutError(timeoutMs),
+ signal,
+ });
if (attempt >= TRACE_UPLOAD_MAX_RETRIES || !RETRIABLE_HTTP_STATUSES.has(response.status)) {
return response;
}
diff --git a/packages/coding-agent/src/core/prime-http.ts b/packages/coding-agent/src/core/prime-http.ts
new file mode 100644
index 0000000000..dec2e693dc
--- /dev/null
+++ b/packages/coding-agent/src/core/prime-http.ts
@@ -0,0 +1,104 @@
+/** Shared helpers for the Prime HTTP boundary used by agent traces and Prime Inference auth. */
+
+export function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+export function stringField(data: Record<string, unknown>, key: string): string | undefined {
+ const value = data[key];
+ return typeof value === "string" && value.trim() ? value.trim() : undefined;
+}
+
+export function numberField(data: Record<string, unknown>, key: string): number | undefined {
+ const value = data[key];
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
+}
+
+export function stringEnv(name: string): string | undefined {
+ const value = process.env[name];
+ return typeof value === "string" && value.trim() ? value.trim() : undefined;
+}
+
+export function parseResponseObject(text: string): Record<string, unknown> | undefined {
+ if (!text.trim()) {
+ return undefined;
+ }
+ try {
+ const parsed = JSON.parse(text) as unknown;
+ return isRecord(parsed) ? parsed : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+export async function readResponseMessage(response: Response): Promise<string> {
+ const text = await response.text().catch(() => "");
+ if (!text.trim()) {
+ return response.statusText || "Unknown error";
+ }
+
+ const parsed = parseResponseObject(text);
+ if (parsed) {
+ const error = parsed.error;
+ if (isRecord(error)) {
+ const message = stringField(error, "message");
+ if (message) return message;
+ }
+ const detail = stringField(parsed, "detail");
+ if (detail) return detail;
+ const message = stringField(parsed, "message");
+ if (message) return message;
+ }
+
+ return text.trim();
+}
+
+export interface PrimeFetchTimeoutOptions {
+ /** Thrown when the request timer fires, and used as the abort reason. */
+ timeoutError: Error;
+ signal?: AbortSignal;
+ /** Thrown instead of the caller abort reason when `signal` aborts. */
+ cancelledError?: Error;
+}
+
+export async function fetchWithTimeout(
+ fetchFn: typeof fetch,
+ url: string | URL,
+ init: RequestInit,
+ timeoutMs: number,
+ options: PrimeFetchTimeoutOptions,
+): Promise<Response> {
+ const { timeoutError, signal, cancelledError } = options;
+ if (cancelledError && signal?.aborted) {
+ throw cancelledError;
+ }
+
+ const controller = new AbortController();
+ let timedOut = false;
+ const timeout = setTimeout(() => {
+ timedOut = true;
+ controller.abort(timeoutError);
+ }, timeoutMs);
+ timeout.unref();
+ const onAbort = () => controller.abort(signal?.reason);
+ if (signal?.aborted) {
+ onAbort();
+ } else {
+ signal?.addEventListener("abort", onAbort, { once: true });
+ }
+
+ try {
+ return await fetchFn(url, { ...init, signal: controller.signal });
+ } catch (error) {
+ if (cancelledError && signal?.aborted) {
+ throw cancelledError;
+ }
+ if (timedOut) {
+ throw timeoutError;
+ }
+ throw error;
+ } finally {
+ clearTimeout(timeout);
+ signal?.removeEventListener("abort", onAbort);
+ }
+}
diff --git a/packages/coding-agent/src/core/prime-inference-auth.ts b/packages/coding-agent/src/core/prime-inference-auth.ts
index a4911ed165..febe843ce8 100644
--- a/packages/coding-agent/src/core/prime-inference-auth.ts
+++ b/packages/coding-agent/src/core/prime-inference-auth.ts
@@ -4,6 +4,7 @@ import { existsSync, readFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
import type { OAuthAuthInfo } from "@earendil-works/pi-ai";
+import { fetchWithTimeout, isRecord, numberField, readResponseMessage, stringEnv, stringField } from "./prime-http.js";
export const PRIME_INFERENCE_PROVIDER_ID = "prime-inference";
export const PRIME_INFERENCE_PROVIDER_NAME = "Prime Inference";
@@ -89,25 +90,6 @@ function normalizeUrl(value: string | undefined, fallback: string): string {
return (value || fallback).trim().replace(/\/+$/, "");
}
-function stringField(data: Record<string, unknown>, key: string): string | undefined {
- const value = data[key];
- return typeof value === "string" && value.trim() ? value.trim() : undefined;
-}
-
-function stringEnv(name: string): string | undefined {
- const value = process.env[name];
- return typeof value === "string" && value.trim() ? value.trim() : undefined;
-}
-
-function numberField(data: Record<string, unknown>, key: string): number | undefined {
- const value = data[key];
- return typeof value === "number" && Number.isFinite(value) ? value : undefined;
-}
-
-function isRecord(value: unknown): value is Record<string, unknown> {
- return typeof value === "object" && value !== null && !Array.isArray(value);
-}
-
function readPrimeCliConfigData(configPath: string): Record<string, unknown> {
let data: Record<string, unknown> = {};
if (existsSync(configPath)) {
@@ -200,60 +182,18 @@ function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {
});
}
-async function fetchWithTimeout(
+function fetchPrimeAuth(
fetchFn: typeof fetch,
url: string | URL,
init: RequestInit,
timeoutMs: number,
signal?: AbortSignal,
): Promise<Response> {
- throwIfCancelled(signal);
-
- const controller = new AbortController();
- const timeout = setTimeout(() => controller.abort(), timeoutMs);
- const onAbort = () => controller.abort();
- signal?.addEventListener("abort", onAbort, { once: true });
-
- try {
- return await fetchFn(url, { ...init, signal: controller.signal });
- } catch (error) {
- if (signal?.aborted) {
- throw new Error("Login cancelled");
- }
- if (controller.signal.aborted) {
- throw new Error("Prime Inference request timed out");
- }
- throw error;
- } finally {
- clearTimeout(timeout);
- signal?.removeEventListener("abort", onAbort);
- }
-}
-
-async function readResponseMessage(response: Response): Promise<string> {
- const text = await response.text().catch(() => "");
- if (!text.trim()) {
- return response.statusText || "Unknown error";
- }
-
- try {
- const parsed = JSON.parse(text) as unknown;
- if (isRecord(parsed)) {
- const error = parsed.error;
- if (isRecord(error)) {
- const message = stringField(error, "message");
- if (message) return message;
- }
- const detail = stringField(parsed, "detail");
- if (detail) return detail;
- const message = stringField(parsed, "message");
- if (message) return message;
- }
- } catch {
- // Fall back to raw text.
- }
-
- return text.trim();
+ return fetchWithTimeout(fetchFn, url, init, timeoutMs, {
+ timeoutError: new Error("Prime Inference request timed out"),
+ cancelledError: new Error("Login cancelled"),
+ signal,
+ });
}
async function readJsonObject(response: Response, context: string): Promise<Record<string, unknown>> {
@@ -316,7 +256,7 @@ export async function fetchPrimeTeams(
const url = new URL(`${normalizeBaseUrl(baseUrl)}/api/v1/user/teams`);
url.searchParams.set("offset", String(offset));
url.searchParams.set("limit", String(limit));
- const response = await fetchWithTimeout(
+ const response = await fetchPrimeAuth(
fetchFn,
url,
{
@@ -392,7 +332,7 @@ async function generatePrimeChallenge(
timeoutMs: number,
signal?: AbortSignal,
): Promise<PrimeChallengeResponse> {
- const response = await fetchWithTimeout(
+ const response = await fetchPrimeAuth(
fetchFn,
`${config.baseUrl}/api/v1/auth_challenge/generate`,
{
@@ -432,7 +372,7 @@ async function pollPrimeChallengeResult(
const statusUrl = new URL(`${config.baseUrl}/api/v1/auth_challenge/status`);
statusUrl.searchParams.set("challenge", challenge.challenge);
- const response = await fetchWithTimeout(
+ const response = await fetchPrimeAuth(
fetchFn,
statusUrl,
{
@@ -493,7 +433,7 @@ async function checkPrimeScopeAccess(
const fetchFn = options.fetchFn ?? fetch;
const requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
const url = `${normalizeBaseUrl(baseUrl)}/api/v1/user/whoami`;
- const response = await fetchWithTimeout(
+ const response = await fetchPrimeAuth(
fetchFn,
url,
{