fix(providers): Enforce stream silence, channel, trust and container-browser deadlines (#1752)

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Luka ZivkovicandClaude Fable 5.2 authored and GitHub committed 2026-12-03 10:21:20 +01:00
1 parent e5f7e558ba
commit 1533a1d2a5
19 files changed
+452 -92

No files matched your search

+4
View File
@@ -2,6 +2,7 @@ name: nod-local
services:
postgres:
image: postgres:17-alpine
restart: unless-stopped
environment:
POSTGRES_USER: nod
POSTGRES_PASSWORD: ${NOD_POSTGRES_PASSWORD:?Run pnpm start from the repository root to set up and start Nod.}
@@ -21,6 +22,7 @@ services:
dockerfile: Dockerfile.browser
container_name: nod-browser
hostname: nod-browser
restart: unless-stopped
init: true
cap_drop: [ALL]
security_opt: [no-new-privileges:true]
@@ -51,6 +53,7 @@ services:
dockerfile: Dockerfile.workspace
image: nod-local-workspace
container_name: nod-workspace
restart: unless-stopped
init: true
cap_drop: [ALL]
security_opt: [no-new-privileges:true]
@@ -68,6 +71,7 @@ services:
command: ['sleep', 'infinity']
workspace-network:
image: nod-local-workspace
restart: unless-stopped
pull_policy: never
dns: [1.1.1.1, 8.8.8.8]
user: root
+4
View File
@@ -869,6 +869,8 @@ exec "$docker" "$@"
names.workspace,
image('workspace'),
[
'--restart',
'unless-stopped',
'--network',
`nod-workspace-${identity}`,
'--init',
@@ -894,6 +896,8 @@ exec "$docker" "$@"
status('starting', 'Preparing your browser…', 'browser');
await images.browser;
await replaceContainer(runDocker, names.browser, image('browser'), [
'--restart',
'unless-stopped',
'--network',
`nod-browser-${identity}`,
'--init',
+1 -1
View File
@@ -293,7 +293,7 @@ You can also tell Nod, for example "Run my schedules on the light model" or "Use
A change applies from the next turn; work that's already running keeps its model until then. Checking what Nod may do, writing the questions it asks you and reading your answers always use your model. If a model you chose for some work is no longer available, that work fails with the reason instead of switching models, and **Settings > Models** shows it as unavailable so you can choose another. Removing a connection returns the work that used it to its default: the model for its kind of work, else your model. An audio model's **Text support** label names its companion from the same connection. Requests without recordings use that companion; follow-ups that still include recordings use the audio model. Both use the smaller context and output limits of the pair. Your saved model choice stays unchanged.
Without [backup models](#backup-models), a failed model request doesn't move to another connection; the notice above the chat box offers one when you have it. Nod retries a temporary provider error up to three times, waiting 4, 8 and 16 seconds, or once when you have backups. Temporary errors include an overload, a rate limit, and, for hosted providers, a request that gets no response within 90 seconds of being sent, cache warming included. Requests to a model server you run have no such limit, because local models can take minutes to start answering.
Without [backup models](#backup-models), a failed model request doesn't move to another connection; the notice above the chat box offers one when you have it. Nod retries a temporary provider error up to three times, waiting 4, 8 and 16 seconds, or once when you have backups. Temporary errors include an overload, a rate limit, and, for hosted providers other than OpenAI-compatible connections, a request that gets no response within 90 seconds of being sent, cache warming included, or that starts answering and then sends nothing for 10 minutes, a window that restarts on each streamed event. Requests to a model server you run, including OpenAI-compatible connections, use a longer silence limit, because local models can take minutes to start answering.
Background work, such as memory upkeep, uses a smaller model from the same connection when it has one, such as `gpt-6-luna` or `claude-haiku-5-5`. Otherwise it uses your model or, for an audio model, its text companion. The short line about your request in the app's chat status line uses only that smaller model. Without one, or without a known price for it, Nod skips the line. Background work uses the lightest reasoning its model offers: off, minimal, low or medium in that order. The trust check and the approval questions it writes use medium, because a check without reasoning makes mistakes. Either falls back to the model's first effort level if it doesn't offer the levels named here.
@@ -149,7 +149,7 @@ The main **Stop** control aborts running turns, cancels queued and waiting turns
An aborted database transaction stops waiting for a free connection at once. If the pool supplies a connection later, Nod closes it without running the transaction.
Turns and tool calls are never retried. A message Nod sends to you is posted as soon as its call finishes streaming. If the model request that wrote it then fails or is cut off, Pi doesn't retry or compact that request, so the message is never sent twice. Pi retries a model request that fails with a temporary provider error up to three times with backoff, and leaves the failed attempt out of the model context. With [backup models](/connect/models/#backup-models), Pi retries a temporary error once, and a request that fails before the model answers then continues on the next backup. A refusal doesn't move. A request to a hosted provider that gets no response within 90 seconds counts as a temporary error. Any other error, or a restart during execution, ends the turn `failed`. When an agent model request fails, the error identifies the model and provider and keeps the provider's specific reason, HTTP status and error codes when supplied. This includes any retry delay or limit source the provider reports. Nod does not replace a quota or rate limit with a generic billing warning. It removes secrets and limits the displayed error to 2,000 characters. Structured errors show their messages and error metadata without unrelated response fields. Diagnostic logs retain the provider error with known secrets removed. For work you started (a chat turn, a task, a reply to a task, or work that continues after you answer or approve), Nod posts the error in the main chat or as a reply to the task's message, and a restart posts an interruption notice instead. A model failure is posted as the plain error, because the model that failed can't write it, and names another connection you can switch to when one is set up. When a request to a hosted provider found no network (`ENOTFOUND`, `EAI_AGAIN`, `ENETUNREACH`, `EHOSTUNREACH` or `ENETDOWN`), the error names the provider and says Nod couldn't reach it because the computer had no internet connection, with that code. The provider's raw error stays in the diagnostic logs. The error and the notice above the chat box leave out the switch and the **Settings → Models** link, unless the notice is still showing an earlier model problem; the notice still offers **Try again**. An OpenAI-compatible, Azure OpenAI or Amazon Bedrock connection keeps the usual error and link, because its address or Region may be wrong or its server stopped. A provider whose adapter reports no transport cause, such as Google's, also keeps them. In the desktop app's local assistant, a schedule run or a task Nod started that fails this way also says that scheduled tasks need the computer awake and online, and links to [running Nod on a server](/deploy/self-host/). A schedule run's own model failure also carries a run track that the server writes from the run's record: due and start times, skipped runs, the cause and code, the next run and the schedule revision the run started with, which **Run now** sends. See [Schedules](/use/schedules/#keep-nod-running). Other errors are written by the model, or posted as the plain error when the model can't write them. A reply the model cut off at its output limit, or a stop after five failed calls to one tool whose last call Nod couldn't accept, also names another connection you can switch to when one is set up; your message stays in the session's model context, so you can say continue. When the disk is full (`ENOSPC` or `EDQUOT`), the error says the computer is out of disk space and asks you to free up space. When a connection to this computer's own address (`127.0.0.1` or `::1`) fails, the error says Nod lost the connection to a service it runs on the computer and asks you to restart Nod. Both keep the original error. A failed schedule run, or a task Nod started, posts the error naming that work; an event turn posts nothing. Errors also show in **Usage**, and a schedule's in its run history. The session's next turn receives the error as `previousFailure`, so Nod can work around it or tell you what to fix. When a turn's model request fails, a provider refusal included, Nod removes what that request added since the last answered one, such as your message or a tool result, from the session's model context, so the session doesn't send it again. A tool call whose result was removed is marked with an unknown outcome, so Nod checks before it runs that call again. Your message stays in the chat, and the saved transcript keeps everything removed. A restart keeps saved task sessions and waiting questions.
Turns and tool calls are never retried. A message Nod sends to you is posted as soon as its call finishes streaming. If the model request that wrote it then fails or is cut off, Pi doesn't retry or compact that request, so the message is never sent twice. Pi retries a model request that fails with a temporary provider error up to three times with backoff, and leaves the failed attempt out of the model context. With [backup models](/connect/models/#backup-models), Pi retries a temporary error once, and a request that fails before the model answers then continues on the next backup. A refusal doesn't move. A request to a hosted provider other than an OpenAI-compatible connection that gets no response within 90 seconds of being sent, cache warming included, or that starts answering and then sends nothing for 10 minutes, counts as a temporary error; the 10-minute window restarts on each streamed event. Any other error, or a restart during execution, ends the turn `failed`. When an agent model request fails, the error identifies the model and provider and keeps the provider's specific reason, HTTP status and error codes when supplied. This includes any retry delay or limit source the provider reports. Nod does not replace a quota or rate limit with a generic billing warning. It removes secrets and limits the displayed error to 2,000 characters. Structured errors show their messages and error metadata without unrelated response fields. Diagnostic logs retain the provider error with known secrets removed. For work you started (a chat turn, a task, a reply to a task, or work that continues after you answer or approve), Nod posts the error in the main chat or as a reply to the task's message, and a restart posts an interruption notice instead. A model failure is posted as the plain error, because the model that failed can't write it, and names another connection you can switch to when one is set up. When a request to a hosted provider found no network (`ENOTFOUND`, `EAI_AGAIN`, `ENETUNREACH`, `EHOSTUNREACH` or `ENETDOWN`), the error names the provider and says Nod couldn't reach it because the computer had no internet connection, with that code. The provider's raw error stays in the diagnostic logs. The error and the notice above the chat box leave out the switch and the **Settings → Models** link, unless the notice is still showing an earlier model problem; the notice still offers **Try again**. An OpenAI-compatible, Azure OpenAI or Amazon Bedrock connection keeps the usual error and link, because its address or Region may be wrong or its server stopped. A provider whose adapter reports no transport cause, such as Google's, also keeps them. In the desktop app's local assistant, a schedule run or a task Nod started that fails this way also says that scheduled tasks need the computer awake and online, and links to [running Nod on a server](/deploy/self-host/). A schedule run's own model failure also carries a run track that the server writes from the run's record: due and start times, skipped runs, the cause and code, the next run and the schedule revision the run started with, which **Run now** sends. See [Schedules](/use/schedules/#keep-nod-running). Other errors are written by the model, or posted as the plain error when the model can't write them. A reply the model cut off at its output limit, or a stop after five failed calls to one tool whose last call Nod couldn't accept, also names another connection you can switch to when one is set up; your message stays in the session's model context, so you can say continue. When the disk is full (`ENOSPC` or `EDQUOT`), the error says the computer is out of disk space and asks you to free up space. When a connection to this computer's own address (`127.0.0.1` or `::1`) fails, the error says Nod lost the connection to a service it runs on the computer and asks you to restart Nod. Both keep the original error. A failed schedule run, or a task Nod started, posts the error naming that work; an event turn posts nothing. Errors also show in **Usage**, and a schedule's in its run history. The session's next turn receives the error as `previousFailure`, so Nod can work around it or tell you what to fix. When a turn's model request fails, a provider refusal included, Nod removes what that request added since the last answered one, such as your message or a tool result, from the session's model context, so the session doesn't send it again. A tool call whose result was removed is marked with an unknown outcome, so Nod checks before it runs that call again. Your message stays in the chat, and the saved transcript keeps everything removed. A restart keeps saved task sessions and waiting questions.
When a turn that carries your message fails at the model provider, that turn is _withdrawn_. Dismissing a pending choice prompt also withdraws only the waiting turn that asked it, leaving earlier turns in the session intact. When you cancel work with **Stop**, `/stop`, a task's **Stop** or reset, the whole request is withdrawn: the stopped turn and the earlier turns it continues in that session, such as the turn that asked you a question or for a sign-in. A waiting turn that a later turn had already replaced isn't. Work that carries none of your words, such as an app check, has nothing to withdraw. When Nod stops tasks for you with `task stop`, or cancels a turn for another reason, nothing is withdrawn.
+6 -1
View File
@@ -817,7 +817,11 @@ export function createAgentBrowserComputer(options: {
run(
executable,
[...attach, ...(action === 'close' ? ['close'] : ['open', String(request.url)])],
{ ...environment, timeoutMs: options.timeoutMs ?? daemonDeadline(request) + 30_000 },
{
...environment,
timeoutMs: options.timeoutMs ?? daemonDeadline(request) + 30_000,
maxBytes: options.maxBytes ?? 16 * 1024 * 1024,
},
),
);
let response: { success?: boolean; data?: Record<string, unknown>; error?: unknown };
@@ -2501,6 +2505,7 @@ export function createAgentBrowserComputer(options: {
const results = await Promise.allSettled([...browsers.keys()].map((id) => closeBrowser(id)));
owner.watch?.close();
if (owner.cdpUrl) await ownerCommand(['close']).catch(() => {});
await rm(cacheRoot, { recursive: true, force: true }).catch(() => {});
await owner.proxy?.dispose();
if (results.some((result) => result.status === 'rejected'))
throw new Error('The browser service could not finish closing its sessions.');
+80 -23
View File
@@ -93,25 +93,43 @@ class TelegramMarkdown extends TelegramFormatConverter {
}
}
const defaultRequestTimeoutMs = 30_000;
const defaultUploadTimeoutMs = 60_000;
class Telegram extends TelegramAdapter {
protected override readonly formatConverter = new TelegramMarkdown();
private readonly requestTimeoutMs: number;
private readonly uploadTimeoutMs: number;
constructor(...options: ConstructorParameters<typeof TelegramAdapter>) {
super(...options);
constructor(
options: ConstructorParameters<typeof TelegramAdapter>[0],
timeouts: { requestTimeoutMs: number; uploadTimeoutMs: number },
) {
super(options);
Reflect.set(this, 'richMessagesAvailable', false);
this.requestTimeoutMs = timeouts.requestTimeoutMs;
this.uploadTimeoutMs = timeouts.uploadTimeoutMs;
}
protected override telegramFetch<TResult>(
method: string,
payload?: Record<string, unknown> | FormData,
request?: { signal?: AbortSignal },
request?: { timeoutMs?: number; signal?: AbortSignal },
) {
const defaultTimeoutMs =
method === 'getUpdates'
? undefined
: payload instanceof FormData
? this.uploadTimeoutMs
: this.requestTimeoutMs;
return super.telegramFetch<TResult>(
method,
payload && !(payload instanceof FormData) && 'text' in payload
? { ...payload, link_preview_options: { is_disabled: true } }
: payload,
request,
defaultTimeoutMs === undefined || request?.timeoutMs !== undefined
? request
: { ...request, timeoutMs: defaultTimeoutMs },
);
}
@@ -266,6 +284,35 @@ class Telegram extends TelegramAdapter {
class WhatsAppUploadError extends Error {}
class WhatsApp extends WhatsAppAdapter {
constructor(
options: ConstructorParameters<typeof WhatsAppAdapter>[0],
timeouts: { requestTimeoutMs: number; uploadTimeoutMs: number },
) {
super(options);
const originalFetchJson = Reflect.get(WhatsAppAdapter.prototype, 'graphFetchJson') as (
url: string,
init: RequestInit | undefined,
label: string,
context: Record<string, unknown>,
) => Promise<unknown>;
Reflect.set(
this,
'graphFetchJson',
(
url: string,
init: RequestInit | undefined,
label: string,
context: Record<string, unknown>,
) => {
const ms =
init?.body instanceof FormData ? timeouts.uploadTimeoutMs : timeouts.requestTimeoutMs;
const timeout = AbortSignal.timeout(ms);
const signal = init?.signal ? AbortSignal.any([init.signal, timeout]) : timeout;
return originalFetchJson.call(this, url, { ...init, signal }, label, context);
},
);
}
protected override async uploadMedia(file: { data: Buffer; filename: string; mimeType: string }) {
try {
return await super.uploadMedia(file);
@@ -405,11 +452,15 @@ function channelConfiguration(env: Environment) {
export function createChatSdkTransport(
pool: Pool,
environment: Environment,
options: { fetch?: typeof fetch } = {},
options: { fetch?: typeof fetch; requestTimeoutMs?: number; uploadTimeoutMs?: number } = {},
): MessagingTransport {
const env = { ...environment };
const request = options.fetch ?? fetch;
const mediaRequest = request;
const timeouts = {
requestTimeoutMs: options.requestTimeoutMs ?? defaultRequestTimeoutMs,
uploadTimeoutMs: options.uploadTimeoutMs ?? defaultUploadTimeoutMs,
};
const telegramAccountId = env.TELEGRAM_BOT_TOKEN?.split(':')[0];
const configuration = channelConfiguration(env);
const configured = (provider: string) =>
@@ -417,26 +468,32 @@ export function createChatSdkTransport(
(channel) => channel.provider === provider && channel.status === 'configured',
);
const telegram = configured('telegram')
? new Telegram({
botToken: env.TELEGRAM_BOT_TOKEN!,
secretToken: env.TELEGRAM_WEBHOOK_SECRET_TOKEN!,
allowedUserIds: [env.TELEGRAM_ALLOWED_USER_ID ?? ''],
mode: 'webhook',
allowUnverifiedWebhooks: false,
apiUrl: 'https://api.telegram.org',
logger,
})
? new Telegram(
{
botToken: env.TELEGRAM_BOT_TOKEN!,
secretToken: env.TELEGRAM_WEBHOOK_SECRET_TOKEN!,
allowedUserIds: [env.TELEGRAM_ALLOWED_USER_ID ?? ''],
mode: 'webhook',
allowUnverifiedWebhooks: false,
apiUrl: 'https://api.telegram.org',
logger,
},
timeouts,
)
: undefined;
const whatsapp = configured('whatsapp')
? new WhatsApp({
userName: 'nod',
accessToken: env.WHATSAPP_ACCESS_TOKEN!,
appSecret: env.WHATSAPP_APP_SECRET!,
phoneNumberId: env.WHATSAPP_PHONE_NUMBER_ID!,
verifyToken: env.WHATSAPP_VERIFY_TOKEN!,
apiUrl: 'https://graph.facebook.com',
logger,
})
? new WhatsApp(
{
userName: 'nod',
accessToken: env.WHATSAPP_ACCESS_TOKEN!,
appSecret: env.WHATSAPP_APP_SECRET!,
phoneNumberId: env.WHATSAPP_PHONE_NUMBER_ID!,
verifyToken: env.WHATSAPP_VERIFY_TOKEN!,
apiUrl: 'https://graph.facebook.com',
logger,
},
timeouts,
)
: undefined;
const state = createPostgresState({ client: pool, keyPrefix: 'nod-channels', logger });
const bot = new Chat({
+17 -1
View File
@@ -529,8 +529,24 @@ export function createBridgeComputer(options: {
let settled = false;
let cancelling = false;
let drainTimer: ReturnType<typeof setTimeout> | undefined;
const effectiveTimeoutMs =
options.timeoutMs ??
(signal === undefined &&
[
'currentPage',
'cardDestinations',
'checkoutImage',
'hold',
'close',
'clear',
'discard',
].includes(input.method)
? 60_000
: undefined);
const timer =
options.timeoutMs === undefined ? undefined : setTimeout(() => cancel(), options.timeoutMs);
effectiveTimeoutMs === undefined
? undefined
: setTimeout(() => cancel(), effectiveTimeoutMs);
const cleanup = () => {
clearTimeout(timer);
clearTimeout(drainTimer);
+2 -2
View File
@@ -71,13 +71,13 @@ const browserAction = z
x: z.number().min(0).max(1).optional(),
y: z.number().min(0).max(1).optional(),
points: z.array(point).min(2).optional(),
durationMs: z.number().int().min(0).optional(),
durationMs: z.number().int().min(0).max(120_000).optional(),
text: z.string().optional(),
key: z.string().optional(),
load: z.enum(['load', 'domcontentloaded', 'networkidle']).optional(),
direction: z.enum(['up', 'down']).optional(),
amount: z.number().int().min(1).optional(),
waitMs: z.number().int().min(0).optional(),
waitMs: z.number().int().min(0).max(120_000).optional(),
offset: z.number().int().min(0).optional(),
timeZone: z.string().max(100).optional(),
locale: z.string().max(35).optional(),
+3 -1
View File
@@ -131,12 +131,14 @@ export function createDiscoveredOAuth(
const { clientInformation, discovery } = saved;
if (!refreshToken || !clientInformation || !discovery) throw new DiscoveredSignInRequired();
signal?.throwIfAborted();
const timeout = AbortSignal.timeout(30_000);
const deadline = signal ? AbortSignal.any([signal, timeout]) : timeout;
const tokens = await refreshAuthorization(discovery.authorizationServerUrl, {
metadata: discovery.authorizationServerMetadata as OAuthMetadata | undefined,
clientInformation: clientInformation as OAuthClientInformationMixed,
refreshToken,
resource: discovery.resourceMetadata?.resource as URL | undefined,
fetchFn: bound(signal),
fetchFn: bound(deadline),
}).catch((cause: unknown) => {
if (!(cause instanceof OAuthError)) throw cause;
const reason = [cause.errorCode, cause.message].filter(Boolean).join(': ').slice(0, 500);
+67 -53
View File
@@ -69,6 +69,7 @@ const reconnectChatGpt = `Reconnect your ChatGPT account in ${appPages['/setting
export const localModelSilenceMs = 30 * 60_000;
export const modelFirstEventMs = 90_000;
export const modelStreamSilenceMs = 10 * 60_000;
function supportedModel(model: Model<Api>): Model<Api> {
if (model.provider === 'groq' && model.id.startsWith('qwen/'))
@@ -1297,8 +1298,21 @@ export async function createPiModelRuntime(
let completeRequest: ((error?: string, status?: number) => Promise<void>) | undefined;
let settleBudget: ((spentUsd: number | null) => Promise<void>) | undefined;
const silence = new AbortController();
const quiet = { ms: 0, streaming: false };
let silenceTimer: ReturnType<typeof setTimeout> | undefined;
const heard = () => clearTimeout(silenceTimer);
const armSilence = (streaming: boolean) => {
heard();
quiet.streaming = streaming;
quiet.ms =
access.provider === 'compatible'
? localModelSilenceMs
: streaming
? modelStreamSilenceMs
: modelFirstEventMs;
silenceTimer = setTimeout(() => silence.abort(), quiet.ms);
silenceTimer.unref?.();
};
const guardedFetch =
usesServerAddress(access.provider) ||
access.provider === 'radius' ||
@@ -1324,7 +1338,7 @@ export async function createPiModelRuntime(
await options?.onResponse?.(response, model);
},
onProviderStreamEvent: async (event, model) => {
heard();
armSilence(true);
phase = 'stream';
if (model.api === 'openai-completions') textContentParts(event);
await options?.onProviderStreamEvent?.(event, model);
@@ -1473,66 +1487,66 @@ export async function createPiModelRuntime(
: null;
});
phase = 'payload';
if (access.provider !== 'compatible') {
heard();
silenceTimer = setTimeout(() => silence.abort(), modelFirstEventMs);
silenceTimer.unref?.();
}
armSilence(false);
return prepared;
},
});
const events = createAssistantMessageEventStream();
void (async () => {
for await (const event of upstream) {
if (usage && (event.type === 'done' || event.type === 'error'))
usage.apply(event.type === 'done' ? event.message.usage : event.error.usage);
if (event.type === 'error')
Object.assign(
event.error,
JSON.parse(
JSON.stringify(event.error, (_key, value) => {
if (typeof value !== 'string') return value;
for (const secret of secrets) value = value.replaceAll(secret, '[redacted]');
return value;
}),
),
);
if (event.type === 'done' || event.type === 'error') heard();
if (event.type === 'error' && silence.signal.aborted && !options?.signal?.aborted) {
event.error.stopReason = 'error';
event.error.errorMessage = `${modelProviderNames[access.provider]} sent no response for ${modelFirstEventMs / 1000} seconds, so the request timed out.`;
}
if (event.type === 'error') {
const error = event.error;
error.errorMessage = `${error.errorMessage || 'The provider gave no reason.'}${status ? ` (HTTP ${status})` : ''}${transportCause ? ` (transport cause: ${transportCause})` : ''} [request phase: ${phase}]`;
}
if ((event.type === 'done' || event.type === 'error') && phase !== 'prepare') {
const message = event.type === 'done' ? event.message : event.error;
if (
message.stopReason !== 'aborted' &&
!options?.signal?.aborted &&
(message.stopReason !== 'error' ||
!(
isRetryableAssistantError(message) ||
isContextOverflow(message, target.contextWindow)
))
)
await completeRequest?.(
message.stopReason === 'error' ? message.errorMessage : undefined,
status,
try {
for await (const event of upstream) {
if (usage && (event.type === 'done' || event.type === 'error'))
usage.apply(event.type === 'done' ? event.message.usage : event.error.usage);
if (event.type === 'error')
Object.assign(
event.error,
JSON.parse(
JSON.stringify(event.error, (_key, value) => {
if (typeof value !== 'string') return value;
for (const secret of secrets) value = value.replaceAll(secret, '[redacted]');
return value;
}),
),
);
if (event.type === 'done' || event.type === 'error') heard();
if (event.type === 'error' && silence.signal.aborted && !options?.signal?.aborted) {
event.error.stopReason = 'error';
event.error.errorMessage = `${modelProviderNames[access.provider]} ${quiet.streaming ? 'stopped responding' : 'sent no response'} for ${quiet.ms / 1000} seconds, so the request timed out.`;
}
if (event.type === 'error') {
const error = event.error;
error.errorMessage = `${error.errorMessage || 'The provider gave no reason.'}${status ? ` (HTTP ${status})` : ''}${transportCause ? ` (transport cause: ${transportCause})` : ''} [request phase: ${phase}]`;
}
if ((event.type === 'done' || event.type === 'error') && phase !== 'prepare') {
const message = event.type === 'done' ? event.message : event.error;
if (
message.stopReason !== 'aborted' &&
!options?.signal?.aborted &&
(message.stopReason !== 'error' ||
!(
isRetryableAssistantError(message) ||
isContextOverflow(message, target.contextWindow)
))
)
await completeRequest?.(
message.stopReason === 'error' ? message.errorMessage : undefined,
status,
);
}
if (event.type === 'done' || event.type === 'error') {
const message = event.type === 'done' ? event.message : event.error;
await settleBudget?.(piUsageMetrics(message.usage).costUsd ?? null);
requestFacts.set(message, {
requestPhase: phase,
requestKind: cacheWarm ? 'cache_warm' : 'regular',
});
}
events.push(event);
}
if (event.type === 'done' || event.type === 'error') {
const message = event.type === 'done' ? event.message : event.error;
await settleBudget?.(piUsageMetrics(message.usage).costUsd ?? null);
requestFacts.set(message, {
requestPhase: phase,
requestKind: cacheWarm ? 'cache_warm' : 'regular',
});
}
events.push(event);
events.end(await upstream.result());
} finally {
heard();
}
events.end(await upstream.result());
})();
if (reportCacheUsage && options?.maxTokens === 1 && options.maxRetries === 0) {
const id = randomUUID();
+22 -2
View File
@@ -6,6 +6,7 @@ export interface ProcessOptions {
input?: string;
signal?: AbortSignal;
timeoutMs?: number;
maxBytes?: number;
}
export class RuntimeTimeLimitError extends Error {
@@ -14,6 +15,12 @@ export class RuntimeTimeLimitError extends Error {
}
}
export class RuntimeOutputLimitError extends Error {
constructor() {
super('Runtime command output exceeded its size limit.');
}
}
export function serviceEnvironment(): NodeJS.ProcessEnv {
return Object.fromEntries(
[
@@ -48,21 +55,34 @@ export function runProcess(
});
const chunks: Buffer[] = [];
const errors: Buffer[] = [];
let receivedBytes = 0;
let stopped = false;
let overflowed = false;
const stop = () => {
stopped = true;
child.kill('SIGKILL');
};
const recordChunk = (target: Buffer[], chunk: Buffer) => {
if (overflowed) return;
receivedBytes += chunk.length;
if (options.maxBytes !== undefined && receivedBytes > options.maxBytes) {
overflowed = true;
child.kill('SIGKILL');
return;
}
target.push(chunk);
};
const timer = options.timeoutMs === undefined ? undefined : setTimeout(stop, options.timeoutMs);
const abort = () => stop();
options.signal?.addEventListener('abort', abort, { once: true });
child.stdout.on('data', (chunk) => chunks.push(chunk));
child.stderr.on('data', (chunk) => errors.push(chunk));
child.stdout.on('data', (chunk: Buffer) => recordChunk(chunks, chunk));
child.stderr.on('data', (chunk: Buffer) => recordChunk(errors, chunk));
child.on('error', () => reject(new Error('The required runtime executable is unavailable.')));
child.on('close', (code) => {
clearTimeout(timer);
options.signal?.removeEventListener('abort', abort);
if (options.signal?.aborted) return reject(new Error('Task cancelled.'));
if (overflowed) return reject(new RuntimeOutputLimitError());
if (stopped) return reject(new RuntimeTimeLimitError());
resolve({
stdout: Buffer.concat(chunks).toString('utf8'),
+5 -3
View File
@@ -81,6 +81,7 @@ export interface ChatConfirmationInput {
clientMessageId?: string;
sourceId?: string;
hasAttachments?: boolean;
signal?: AbortSignal;
answer?: { approvalId: string; approved?: boolean };
clicked?: true;
}
@@ -335,7 +336,7 @@ export async function createApprovals(
expectedRevision?: number,
client?: PoolClient,
) => Promise<void>,
interpret?: (reply: string) => Promise<boolean | undefined>,
interpret?: (reply: string, signal?: AbortSignal) => Promise<boolean | undefined>,
describe?: (
proposal: ApprovalDescription,
signal?: AbortSignal,
@@ -907,9 +908,10 @@ export async function createApprovals(
const approvalId = approval.id as string;
if (input.hasAttachments) return { approvalId };
try {
const approved = await interpret(input.text);
const approved = await interpret(input.text, input.signal);
return approved === undefined ? { approvalId } : { approvalId, approved };
} catch {
} catch (error) {
if (input.signal?.aborted) throw error;
return undefined;
}
}
+1 -1
View File
@@ -2034,7 +2034,7 @@ async function initializeApplication(
await personal.validateReview(action.slice('NOD_'.length), args, expectedRevision, client);
} else await integrations.prepare(ownerId, action, args, undefined, undefined, false, client);
},
(reply) => ledger.forOwner(() => trust.answer(reply)),
(reply, signal) => ledger.forOwner(() => trust.answer(reply, signal)),
communication.describe,
captureAnalytics,
createErrorRedactor(secrets),
+1
View File
@@ -851,6 +851,7 @@ async function readAnswer(
replyToMessageId: options.replyToMessageId,
seenMessageId: options.seenMessageId,
hasAttachments,
signal: arrival,
});
}
+5 -2
View File
@@ -361,7 +361,7 @@ export function createTrust(options: {
return (result as { readOnly?: unknown } | undefined)?.readOnly === true;
}
async function answer(reply: string) {
async function answer(reply: string, signal?: AbortSignal) {
const thumb = /^(👍|👎)\uFE0F?\p{Emoji_Modifier}?$/u.exec(reply.trim());
if (thumb) return thumb[1] === '👍';
const question: DecisionQuestion = {
@@ -377,7 +377,10 @@ export function createTrust(options: {
},
],
};
const result = await review(answerInstructions, { reply }, undefined, question);
const timeout = AbortSignal.timeout(10_000);
const deadline = signal ? AbortSignal.any([signal, timeout]) : timeout;
const result = await review(answerInstructions, { reply }, deadline, question);
deadline.throwIfAborted();
const value = result && typeof result === 'object' && (result as { answer?: unknown }).answer;
return value === 'yes' ? true : value === 'no' ? false : undefined;
}
+40
View File
@@ -6016,3 +6016,43 @@ test(
}
},
);
test('trust.answer bounds reply interpretation with a timeout and honors caller cancellation', async () => {
const { setTimeout: delay } = await import('node:timers/promises');
const { createTrust } = await import('../src/server/trust.ts');
let receivedSignal: AbortSignal | undefined;
let releaseCurate = () => {};
const trust = createTrust({
review: (_instructions: string, _input: unknown, signal?: AbortSignal) => {
receivedSignal = signal;
return new Promise((_resolve, reject) => {
const onAbort = () => reject(signal?.reason ?? new DOMException('Cancelled', 'AbortError'));
releaseCurate = onAbort;
if (signal?.aborted) return onAbort();
signal?.addEventListener('abort', onAbort, { once: true });
});
},
ownerWords: async () => ({ current: '', recent: [], rules: '', schedule: null }),
} as unknown as Parameters<typeof createTrust>[0]);
const stop = new AbortController();
const pending = (
trust.answer as (reply: string, signal?: AbortSignal) => Promise<boolean | undefined>
)('Yes, send the synthetic report now.', stop.signal);
pending.catch(() => {});
try {
await delay(10);
assert.ok(receivedSignal);
stop.abort(new DOMException('Stopped by owner', 'AbortError'));
const outcome = await Promise.race([
pending.then(
() => 'resolved',
() => 'aborted',
),
delay(200).then(() => 'hung'),
]);
assert.equal(outcome, 'aborted');
} finally {
releaseCurate();
}
});
+25 -1
View File
@@ -2,7 +2,7 @@ import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
import { createHash, randomUUID } from 'node:crypto';
import { EventEmitter, once } from 'node:events';
import { constants } from 'node:fs';
import { constants, existsSync } from 'node:fs';
import {
mkdir,
mkdtemp,
@@ -10101,3 +10101,27 @@ describe('interface components', { concurrency: interfaceLanes }, () => {
assert.equal(result.exitCode, 0, result.stderr || result.stdout);
});
});
test('a child process that writes more than its output limit rejects with an output-limit error', async () => {
const { runProcess, RuntimeOutputLimitError } = await import('../src/providers/process.ts');
await assert.rejects(
runProcess(process.execPath, ['-e', 'process.stdout.write("x".repeat(131072))'], {
maxBytes: 8192,
}),
RuntimeOutputLimitError,
);
});
test('disposing the browser service removes its namespaced disk cache', async () => {
const { createAgentBrowserComputer } = await import('../src/providers/agent-browser/index.ts');
const dataRoot = await mkdtemp(join(tmpdir(), 'nod-browser-dispose-'));
const runtimeRoot = join(dataRoot, 'runtime');
const namespace = `sk-${createHash('sha256').update(runtimeRoot).digest('hex').slice(0, 12)}`;
const cacheRoot = join('/tmp/nod-browser-cache', namespace);
await mkdir(cacheRoot, { recursive: true });
await writeFile(join(cacheRoot, 'entry'), 'synthetic');
const computer = createAgentBrowserComputer({ dataRoot });
await computer.dispose();
assert.equal(existsSync(cacheRoot), false);
await rm(dataRoot, { recursive: true, force: true });
});
+99
View File
@@ -6310,3 +6310,102 @@ test(
);
},
);
test(
'Telegram and WhatsApp Cloud outbound requests abort on stalled upstream connections',
{ skip: !process.env.TEST_DATABASE_URL },
async (t) => {
const { setTimeout: delay } = await import('node:timers/promises');
const { createChatSdkTransport } = await import('../src/providers/chat-sdk/index.ts');
const schema = `test_channels_timeout_${randomUUID().replaceAll('-', '')}`;
const admin = new pg.Pool({ connectionString: process.env.TEST_DATABASE_URL });
await admin.query(`CREATE SCHEMA ${schema}`);
const pool = new pg.Pool({
connectionString: process.env.TEST_DATABASE_URL,
options: `-c search_path=${schema}`,
});
const releasePending: Array<() => void> = [];
t.after(async () => {
for (const release of releasePending) release();
await transport.close().catch(() => {});
await pool.end();
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
await admin.end();
});
const seenSignals: Array<boolean> = [];
t.mock.method(globalThis, 'fetch', (input: RequestInfo | URL, init?: RequestInit) => {
const url = input instanceof Request ? input.url : String(input);
if (url.endsWith('/getMe'))
return Promise.resolve(
Response.json({
ok: true,
result: { id: 123456, is_bot: true, first_name: 'Fixture', username: 'fixture_bot' },
}),
);
if (
new URL(url).hostname === 'graph.facebook.com' &&
(!init?.method || init.method === 'GET')
)
return Promise.resolve(Response.json({ verified_name: 'Fixture' }));
seenSignals.push(Boolean(init?.signal));
return new Promise<Response>((_resolve, reject) => {
const abort = () =>
reject(init?.signal?.reason ?? new DOMException('Request timed out', 'TimeoutError'));
releasePending.push(abort);
if (init?.signal?.aborted) return abort();
init?.signal?.addEventListener('abort', abort, { once: true });
});
});
const transport = createChatSdkTransport(
pool,
{
TELEGRAM_ENABLED: 'true',
TELEGRAM_BOT_TOKEN: '123456:synthetic-bot-token',
TELEGRAM_WEBHOOK_SECRET_TOKEN: 'synthetic-webhook-secret-token',
TELEGRAM_ALLOWED_USER_ID: '777000',
WHATSAPP_ENABLED: 'true',
WHATSAPP_MODE: 'cloud',
WHATSAPP_POLICY_CONFIRMED: 'true',
WHATSAPP_ACCESS_TOKEN: 'synthetic-wa-token',
WHATSAPP_APP_SECRET: 'synthetic-wa-secret',
WHATSAPP_PHONE_NUMBER_ID: '15550001',
WHATSAPP_VERIFY_TOKEN: 'synthetic-wa-verify',
WHATSAPP_ALLOWED_NUMBER: '4915123456789',
},
{ requestTimeoutMs: 50 },
);
const tgOutcome = await Promise.race([
transport
.post({
channelId: 'telegram',
accountId: '123456',
threadId: 'telegram:777000',
text: 'Synthetic hello',
})
.then(
() => 'resolved',
() => 'aborted',
),
delay(300).then(() => 'hung'),
]);
assert.equal(tgOutcome, 'aborted');
const waOutcome = await Promise.race([
transport
.post({
channelId: 'whatsapp',
accountId: '15550001',
threadId: 'whatsapp:15550001:4915123456789',
text: 'Synthetic hello',
})
.then(
() => 'resolved',
() => 'aborted',
),
delay(300).then(() => 'hung'),
]);
assert.equal(waOutcome, 'aborted');
assert.deepEqual(seenSignals, [true, true]);
},
);
+69
View File
@@ -14718,3 +14718,72 @@ test('Ollama discovery uses the loaded context for model registration and comple
await backend.catalog('compatible', 'api_key', credential);
assert.ok(!calls.includes('/api/ps'));
});
test('a model stream that stalls after its first event outlasts the first-event limit and times out on the longer silence limit', async (t) => {
const { setImmediate } = await import('node:timers/promises');
const { createPiModelBackend, createPiModelRuntime, modelFirstEventMs, modelStreamSilenceMs } =
await import('../src/providers/pi/models.ts');
const backend = createPiModelBackend({
fetch: async () => {
throw new Error('No live catalog request is allowed.');
},
});
const definition = (await backend.catalog('openai', 'api_key')).find(
({ choice }) => choice.id === 'gpt-6.1-sol',
)!;
const { runtime, model } = await createPiModelRuntime({
provider: 'openai',
method: 'api_key',
definition,
effort: 'low',
read: async () => ({ type: 'api_key', key: 'fixture-key' }),
});
t.mock.timers.enable({ apis: ['setTimeout'] });
let firstChunkDelivered!: () => void;
const started = new Promise<void>((resolve) => {
firstChunkDelivered = resolve;
});
let streamAborted = false;
const encoder = new TextEncoder();
const completion = runtime.completeSimple(
model,
{ messages: [{ role: 'user', content: 'Synthetic mid-stream stall', timestamp: 1 }] },
{
fetch: async (_input, init) => {
const stream = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(
encoder.encode(
'event: response.created\ndata: {"type":"response.created","response":{"id":"resp_stall","object":"response","created_at":1,"status":"in_progress","model":"gpt-6.1-sol","output":[]}}\n\n: keepalive\n\n',
),
);
setImmediate().then(firstChunkDelivered);
const abort = () => {
streamAborted = true;
try {
controller.error(new DOMException('Stream aborted', 'AbortError'));
} catch {}
};
if (init?.signal?.aborted) abort();
else init?.signal?.addEventListener('abort', abort, { once: true });
},
});
return new Response(stream, {
status: 200,
headers: { 'content-type': 'text/event-stream' },
});
},
},
);
await started;
await setImmediate();
t.mock.timers.tick(modelFirstEventMs);
await setImmediate();
assert.equal(streamAborted, false);
t.mock.timers.tick(modelStreamSilenceMs);
await setImmediate();
assert.equal(streamAborted, true);
const reply = await completion;
assert.equal(reply.stopReason, 'error');
assert.match(reply.errorMessage!, /stopped responding for 600 seconds, so the request timed out/);
});