diff --git a/README.md b/README.md index 590246a..198b108 100644 --- a/README.md +++ b/README.md @@ -86,6 +86,8 @@ runDemo(options?: DemoOptions): Promise Live options require `apiKey`, `model`, and exactly one of `prompt` or a nonempty `messages` array; both operations accept `signal`, `timeoutMs`, and synchronous `onText`. Defaults are a 30,000 ms overall deadline and, for live runs, 256 maximum output tokens. No retries or automatic continuation occur. +Set `idleTimeoutMs` in either library operation or pass `--idle-timeout-ms ` to CLI `run` or `demo` to detect stalled text output. The idle timeout is disabled by default and accepts integer values from 1 to 2,147,483,647 milliseconds. The timer starts on the first nonempty text delta and resets on each subsequent nonempty delta, including while waiting for stream completion. The overall deadline still covers the entire run. Idle expiry preserves the received text and returns an `interrupted` timeout diagnostic (CLI exit 124). + Conversation input and the Workers verification below are available starting with **v0.2.0**. Earlier v0.1.1 artifacts remain prompt-only. ```typescript diff --git a/src/cli.ts b/src/cli.ts index 58b9ee8..b149f0a 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -12,6 +12,7 @@ Usage: Options: --json Emit one complete JSON result, without streamed fragments --timeout Overall deadline (default: 30000) + --idle-timeout-ms Maximum gap after a text delta (disabled by default) --max-tokens Maximum output tokens for run (default: 256) --help, -h Show this help --version, -v Show version @@ -23,6 +24,7 @@ Exit: success 0; failure 1; input 2; interrupted 3; timeout 124; Ctrl+C 130. const options = { model: { type: 'string' }, prompt: { type: 'string' }, timeout: { type: 'string' }, + 'idle-timeout-ms': { type: 'string' }, 'max-tokens': { type: 'string' }, json: { type: 'boolean' }, help: { type: 'boolean', short: 'h' }, version: { type: 'boolean', short: 'v' }, } as const; @@ -106,6 +108,7 @@ export async function main(args: string[] = process.argv.slice(2)): Promise { process.stdout.write(delta); } } : {}), }; const result = command === 'demo' diff --git a/src/runner.ts b/src/runner.ts index 83fde62..6ae5044 100644 --- a/src/runner.ts +++ b/src/runner.ts @@ -42,6 +42,10 @@ function validate(options: LiveOptions): string | null { } } if (options.timeoutMs !== undefined && (!Number.isInteger(options.timeoutMs) || options.timeoutMs <= 0 || options.timeoutMs > MAX_TIMEOUT)) return 'Timeout must be an integer from 1 to 2147483647 milliseconds'; + const idleTimeoutMs = options.idleTimeoutMs; + if (idleTimeoutMs !== undefined && (!Number.isInteger(idleTimeoutMs) || idleTimeoutMs <= 0 || idleTimeoutMs > MAX_TIMEOUT)) { + return 'Idle timeout must be an integer from 1 to 2147483647 milliseconds'; + } if (options.maxTokens !== undefined && (!Number.isSafeInteger(options.maxTokens) || options.maxTokens <= 0)) return 'Maximum tokens must be a positive safe integer'; if (options.signal !== undefined && !(options.signal instanceof AbortSignal)) return 'Signal must be an AbortSignal'; if (options.onText !== undefined && typeof options.onText !== 'function') return 'onText must be a synchronous function'; @@ -97,6 +101,8 @@ export async function runWithTransport(options: LiveOptions, fetcher?: Fetcher, // Also close the check/listen gap for signals aborted by caller-side code. if (options.signal?.aborted) onCallerAbort(); const deadline = setTimeout(() => { fail('timeout', 'Overall streaming deadline exceeded'); }, options.timeoutMs ?? DEFAULT_TIMEOUT); + const idleTimeoutMs = options.idleTimeoutMs; + let idleTimer: ReturnType | undefined; try { if (!terminal) { @@ -145,6 +151,12 @@ export async function runWithTransport(options: LiveOptions, fetcher?: Fetcher, if (typeof delta === 'string' && delta.length > 0) { if (firstTokenMs === null) firstTokenMs = performance.now() - startedAt; text += delta; + if (idleTimeoutMs !== undefined) { + clearTimeout(idleTimer); + idleTimer = setTimeout(() => { + fail('timeout', `Stream idle for ${idleTimeoutMs} ms after receiving text`); + }, idleTimeoutMs); + } try { options.onText?.(delta); } catch { fail('consumer', 'The synchronous onText callback failed'); } } @@ -192,6 +204,7 @@ export async function runWithTransport(options: LiveOptions, fetcher?: Fetcher, } } finally { clearTimeout(deadline); + clearTimeout(idleTimer); options.signal?.removeEventListener('abort', onCallerAbort); cancelReader(); await cancelling; diff --git a/src/types.ts b/src/types.ts index 1911c46..d4b5afc 100644 --- a/src/types.ts +++ b/src/types.ts @@ -6,6 +6,8 @@ export type RunSource = 'live' | 'demo'; export interface CommonOptions { /** Overall deadline, including draining. Positive integer milliseconds; default 30,000. */ timeoutMs?: number; + /** Maximum gap after a nonempty text delta, including draining. Disabled by default. */ + idleTimeoutMs?: number; signal?: AbortSignal; /** Synchronous only. The delta is accumulated before this callback runs. */ onText?: (delta: string) => void; diff --git a/tests/cli.test.ts b/tests/cli.test.ts index 9f76d3b..664c20e 100644 --- a/tests/cli.test.ts +++ b/tests/cli.test.ts @@ -43,12 +43,25 @@ it('keeps human streamed text on stdout and its summary on stderr', async () => expect(actual.err).toMatch(/Failure:\s+Provider error during streaming/); }); +it('keeps partial demo output and exits 124 on an idle timeout', async () => { + const actual = await invoke(['demo', 'success', '--idle-timeout-ms', '20', '--json']); + expect(actual.code).toBe(124); + expect(actual.err).toBe(''); + expect(JSON.parse(actual.out)).toMatchObject({ + outcome: 'interrupted', text: 'Webhooks send HTTP notifications', partialOutput: true, + error: { kind: 'timeout', message: 'Stream idle for 20 ms after receiving text' }, + }); +}); + it.each([ ['run', '--json'], ['run', '--model', '', '--prompt', 'hello', '--json'], ['demo', 'unknown', '--json'], ['demo', '--timeout', '0', '--json'], ['demo', '--timeout', 'bad', '--json'], + ['demo', '--idle-timeout-ms', '0', '--json'], + ['demo', '--idle-timeout-ms', '1.5', '--json'], + ['demo', '--idle-timeout-ms', '2147483648', '--json'], ['demo', '--model', 'unwanted', '--json'], ['demo', '--wat', '--json'], ['unknown', '--json'], diff --git a/tests/runner.test.ts b/tests/runner.test.ts index 8db6518..134bc6a 100644 --- a/tests/runner.test.ts +++ b/tests/runner.test.ts @@ -255,6 +255,51 @@ describe('validation and cancellation lifecycle', () => { expect(vi.getTimerCount()).toBe(0); }); + it('resets the idle timeout only on text and preserves partial output while draining', async () => { + vi.useFakeTimers(); + const fixture = controlledResponse(); + const pending = runWithTransport({ ...valid, idleTimeoutMs: 50 }, fixture.fetcher); + const request = await fixture.requested; + fixture.emit(chunk('Keep ')); + await vi.advanceTimersByTimeAsync(40); + fixture.emit(chunk('me', 'stop')); + await vi.advanceTimersByTimeAsync(40); + expect(request.signal.aborted).toBe(false); + fixture.emit(chunk()); + await vi.advanceTimersByTimeAsync(10); + expect(request.signal.aborted).toBe(true); + expect(await pending).toMatchObject({ + outcome: 'interrupted', text: 'Keep me', partialOutput: true, finishReason: 'stop', + error: { kind: 'timeout', phase: 'stream', message: 'Stream idle for 50 ms after receiving text' }, + }); + expect(fixture.cancellations).toBe(1); + expect(vi.getTimerCount()).toBe(0); + }); + + it.each([false, true])('keeps the overall deadline with text received: %s', async withText => { + vi.useFakeTimers(); + const fixture = controlledResponse(); + const pending = runWithTransport({ ...valid, idleTimeoutMs: 40, timeoutMs: 60 }, fixture.fetcher); + await fixture.requested; + if (withText) fixture.emit(chunk('First')); + await vi.advanceTimersByTimeAsync(30); + if (withText) fixture.emit(chunk(' second')); + await vi.advanceTimersByTimeAsync(30); + expect(await pending).toMatchObject({ + outcome: withText ? 'interrupted' : 'failed', + text: withText ? 'First second' : '', + error: { kind: 'timeout', message: 'Overall streaming deadline exceeded' }, + }); + expect(vi.getTimerCount()).toBe(0); + }); + + it('clears the idle timer on successful completion', async () => { + vi.useFakeTimers(); + const result = await runWithTransport({ ...valid, idleTimeoutMs: 50 }, fixedFetcher(sse(chunk('Done', 'stop'), '[DONE]'))); + expect(result).toMatchObject({ outcome: 'success', text: 'Done' }); + expect(vi.getTimerCount()).toBe(0); + }); + it('lets a deadline win while draining after a finish reason', async () => { vi.useFakeTimers(); const fixture = controlledResponse();