Files
simstudioai--sim/apps/sim/providers/streaming-tool-loop-shared.ts
WeHub Mirror 6bf8bebf51
CI / Test and Build (push) Failing after 1s
CI / Migrate Dev DB (push) Has been skipped
CI / Migrate DB (push) Has been skipped
CodeQL / Analyze actions (push) Has been cancelled
CodeQL / Analyze javascript-typescript (push) Has been cancelled
CI / Detect Version (push) Has been cancelled
CI / Detect Desktop Changes (push) Has been cancelled
CI / Build AMD64 (blacksmith-2vcpu-ubuntu-2404, ./docker/cron.Dockerfile, ubuntu-latest, ghcr.io/simstudioai/cron) (push) Has been cancelled
CI / Build AMD64 (blacksmith-2vcpu-ubuntu-2404, ./docker/db.Dockerfile, ECR_MIGRATIONS, ubuntu-latest, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build AMD64 (blacksmith-4vcpu-ubuntu-2404, ./docker/pii.Dockerfile, ECR_PII, ubuntu-latest, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build AMD64 (blacksmith-4vcpu-ubuntu-2404, ./docker/realtime.Dockerfile, ECR_REALTIME, ubuntu-latest, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build AMD64 (blacksmith-8vcpu-ubuntu-2404, ./docker/app.Dockerfile, ECR_APP, linux-x64-8-core, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (blacksmith-4vcpu-ubuntu-2404-arm, ./docker/cron.Dockerfile, ubuntu-24.04-arm, ghcr.io/simstudioai/cron) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (blacksmith-4vcpu-ubuntu-2404-arm, ./docker/db.Dockerfile, ubuntu-24.04-arm, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (blacksmith-4vcpu-ubuntu-2404-arm, ./docker/pii.Dockerfile, ubuntu-24.04-arm, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (blacksmith-4vcpu-ubuntu-2404-arm, ./docker/realtime.Dockerfile, ubuntu-24.04-arm, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (blacksmith-8vcpu-ubuntu-2404-arm, ./docker/app.Dockerfile, linux-arm64-8-core, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Check Docs Changes (push) Has been cancelled
Publish CLI Package / publish-npm (push) Has been cancelled
Publish Python SDK / publish-pypi (push) Has been cancelled
CI / Deploy Trigger.dev (Dev) (push) Has been cancelled
Helm Chart / Lint, test, and validate chart (push) Has been cancelled
Helm Chart / Chart version bumped (push) Has been cancelled
Publish TypeScript SDK / publish-npm (push) Has been cancelled
CI / Build Dev ECR (blacksmith-8vcpu-ubuntu-2404, ./docker/app.Dockerfile, ECR_APP, linux-x64-8-core) (push) Has been cancelled
CI / Promote Images (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/cron) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build Dev ECR (blacksmith-2vcpu-ubuntu-2404, ./docker/db.Dockerfile, ECR_MIGRATIONS, ubuntu-latest) (push) Has been cancelled
CI / Build Dev ECR (blacksmith-4vcpu-ubuntu-2404, ./docker/pii.Dockerfile, ECR_PII, ubuntu-latest) (push) Has been cancelled
CI / Build Dev ECR (blacksmith-4vcpu-ubuntu-2404, ./docker/realtime.Dockerfile, ECR_REALTIME, ubuntu-latest) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Process Docs (push) Has been cancelled
CI / Create GitHub Release (push) Has been cancelled
CI / Check Desktop Signing Secrets (push) Has been cancelled
CI / Desktop Release (push) Has been cancelled
CI / Create Desktop Prerelease (push) Has been cancelled
CI / Desktop Prerelease Build (push) Has been cancelled
CI / Publish Desktop Prerelease (push) Has been cancelled
CI / Prune Desktop Prereleases (push) Has been cancelled
Helm Chart / Install on kind and run helm test (push) Has been cancelled
WeHub snapshot of cb28d14c6f2c081de7a0d8729a8c816c9adef67a
2026-08-10 11:17:50 +08:00

129 lines
4.1 KiB
TypeScript

/**
* Shared plumbing for the per-provider live streaming tool loops
* (`providers/{anthropic,openai-compat,gemini,bedrock}/streaming-tool-loop.ts`).
*
* The wire handling in each loop is provider-specific; everything here is the
* provider-agnostic contract they share.
*/
import { toError } from '@sim/utils/errors'
import { isRecordLike } from '@sim/utils/object'
import type { NormalizedBlockOutput } from '@/executor/types'
import type { AgentStreamEvent, ToolCallEndStatus } from '@/providers/stream-events'
/**
* Providers with a live streaming tool loop wired. Generated documentation and
* capability reporting consume this set; providers select their own internal
* loop from request shape. Event exposure is controlled separately.
*/
export const STREAMING_TOOL_CALL_PROVIDERS: ReadonlySet<string> = new Set([
'openai',
'anthropic',
'azure-anthropic',
'groq',
'deepseek',
'google',
'vertex',
'bedrock',
])
/** Aggregate result reported by a streaming tool loop when its stream closes. */
export interface StreamingToolLoopComplete {
content: string
tokens: { input: number; output: number; total: number }
cost: NormalizedBlockOutput['cost']
toolCalls?: { list: unknown[]; count: number }
modelTime: number
toolsTime: number
firstResponseTime: number
iterations: number
}
/** True for user/SDK abort errors raised when a run is cancelled mid-stream. */
export function isAbortError(error: unknown): boolean {
if (!error || typeof error !== 'object') return false
const name = (error as { name?: string }).name
return name === 'AbortError' || name === 'APIUserAbortError'
}
/** Parse provider-supplied tool arguments without accepting non-object JSON values. */
export function parseToolArguments(
argumentsJson: string,
toolName: string
): Record<string, unknown> {
let parsed: unknown
try {
parsed = JSON.parse(argumentsJson)
} catch (error) {
throw new Error(`Invalid JSON arguments for tool "${toolName}"`, { cause: error })
}
if (!isRecordLike(parsed)) {
throw new Error(`Arguments for tool "${toolName}" must be a JSON object`)
}
return parsed
}
/**
* Settle every open tool with a terminal status and clear the tracking map.
* Called when a loop aborts, errors, or drains with tools still running so no
* consumer is left with a perpetually "running" tool chip.
*/
export function settleOpenTools(
controller: ReadableStreamDefaultController<AgentStreamEvent>,
openTools: Map<string, string>,
status: ToolCallEndStatus
): void {
for (const [id, name] of openTools) {
controller.enqueue({ type: 'tool_call_end', id, name, status })
}
openTools.clear()
}
interface TerminateToolLoopOptions {
controller: ReadableStreamDefaultController<AgentStreamEvent>
/** Tools that emitted `tool_call_start` without a matching end. */
openTools: Map<string, string>
/** The loop's abort controller fired — request abort or consumer cancel. */
aborted: boolean
/** The stream consumer called `cancel()`; the controller is already closed. */
consumerCancelled: boolean
error: unknown
/** Invoked only for a genuine failure, before the stream is errored. */
onUnexpectedError?: (error: unknown) => void
}
/**
* Terminates a streaming tool loop that threw, settling any still-open tools.
*
* A consumer `cancel()` leaves the controller in the *closed* state, where
* `enqueue` and `close` both throw `TypeError: Invalid state`. That state is
* indistinguishable via `desiredSize` — it reports `0` when closed and `null`
* only when errored — so loops must track the cancel explicitly and stop
* writing. Every provider loop routes its catch block through here so the
* five of them cannot drift.
*/
export function terminateToolLoop({
controller,
openTools,
aborted,
consumerCancelled,
error,
onUnexpectedError,
}: TerminateToolLoopOptions): void {
if (consumerCancelled) {
return
}
if (aborted) {
settleOpenTools(controller, openTools, 'cancelled')
controller.close()
return
}
settleOpenTools(controller, openTools, 'error')
onUnexpectedError?.(error)
controller.error(toError(error))
}