just-another-sdk

API reference

Every export, grouped by entry point.

The package has seven entry points. Anything not listed here is internal and may change in a patch release.

just-another-sdk

Agents

ExportKindDescription
Agentclassnew Agent(config), .run(), .stream(), .session(), .resumable(), .resume(), .resumeApproval(), .clone(), .withTools(), .withHandoffs()
AgentSessiontypeWhat .session(id) returns: run, stream, messages(), pop(), clear(), store
runfunctionrun(config, input, options) — shorthand for a one-shot agent
runAgentfunctionThe loop itself, if you want it without the Agent wrapper
AGENT_DEFAULTSconstmaxTurns: 10, maxHandoffs: 5, toolTimeoutMs: 30000, modelTimeoutMs: 120000, onToolError: 'return', maxRetries: 2, retryDelayMs: 250, maxRetryDelayMs: 10000, maxOutputRetries: 1
AgentConfigtypeConstructor options — see Agents
RunOptionstypePer-run options
AgentInputtypestring | ModelMessage[]
ToolErrorPolicytype'return' | 'throw'

Tools

ExportKindDescription
toolfunctionDefines a tool. Overloaded for schema and no-argument forms
ToolRegistryclassName-indexed view over an agent's tools
Tool, AnyTooltypeA defined tool
ToolSpec, NullaryToolSpectypeArguments to tool()
ToolContexttypeSecond argument to a handler: runId, toolCallId, agentName, turn, signal
ToolHandlertype(input, context) => output

Built-in tools

just-another-sdk/tools — see Built-in tools.

ExportKindDescription
webToolsfunctionAll four keyless tools at once
getWeather, geocode, wikipedia, currencyConvertfunctionIndividually. No API key; fixed endpoints
httpFetch, readUrlfunctionArbitrary URLs. allow list required
webSearchfunctionwebSearch(client) — you supply the vendor
extractTextfunctionThe HTML → prose scrub readUrl uses
PURE_BUILTINSconstThe five automatic tools, for composing with builtins: false
calculate, currentTime, dateMath, unitConvert, thinkconstThe automatic tools individually
UrlPolicy, BlockedUrlErrortype/class{ allow, maxBytes?, maxRedirects?, methods?, headers?, fetch? }
SearchClient, SearchQuery, SearchResulttypeThe search interface you implement
WebToolOptionstype{ baseUrl?, fetch?, timeoutMs?, userAgent? }

just-another-sdk/tools/fs — a separate entry so node:fs stays out of edge bundles.

ExportKindDescription
fileToolsfunctionread_file, list_directory, search_files, and with write two more
FileToolsOptionstype{ root, write?, maxReadBytes?, maxWriteBytes?, maxEntries? }
PathEscapeErrorclassThrown when a path would leave the root

Handoffs

ExportKindDescription
HandoffTargettypeAn Agent, an AgentConfig, or a HandoffSpec
HandoffSpectype{ agent, filter?, describe?, toolName?, description? }
HandoffRefusaltype'max_handoffs' | 'cycle' | 'already_transferring'
AgentLiketypeAnything with toConfig() — how a target is accepted without a runtime import

See Handoffs.

Results

ExportKindDescription
RunResulttypeWhat run() resolves with. Includes agentName and agentPath
RunSteptypeOne model call: kind (turn/repair/resume), agentName, text, tool calls, results, usage, timing
StopReasontype'finish' | 'max_turns'
isCompletefunctionresult.stopReason === 'finish'

Streaming

ExportKindDescription
streamAgentfunctionstreamAgent(config, input, options) — the functional form of .stream()
StreamedRuntypeAsync-iterable and awaitable. .runId, .completed, .textStream(), .toTextStream(), .toResponse(), .toEventStream(), .toEventResponse(), .abort()

See Streaming.

Streaming over HTTP

ExportKindDescription
readEventStreamfunctionClient side: parses toEventResponse() back into events
ReadEventStreamOptionstype{ cursor } — tracks the last id: for reconnecting
EventStreamOptionstypeinclude, fromIndex

Resumable streams

ExportKindDescription
memoryStreamStorefunctionBounded in-memory recordings. One process only
StreamStoretypeappend, read, finish, status
StreamStatustype{ count, done, outcome? }
StreamOutcometype'finish' | 'error'
ResumableRuntypeWhat .resumable() returns
ResumableOptionstypeRunOptions plus streamId
FollowOptionstypestartTimeoutMs, idleTimeoutMs, plus the above

The Redis adapter is in just-another-sdk/streams.

Sessions

ExportKindDescription
memorySessionfunctionBounded in-memory store. { maxSessions, maxMessagesPerSession }
SessionStoretypeload(id, options?), append, clear, and optional pop
LoadOptionstype{ limit } — a hint the store may honour
ContextPolicytypemaxMessages, maxTokens, countTokens, summarize
SummarizeOptionstypemodel, prompt, keepRecent, maxOutputTokens, timeoutMs
trimHistoryfunctionApplies a ContextPolicy to a message list
estimateTokensfunctionThe default characters / 4 estimator
isSummaryMessagefunctionWhether a message is a stored recap
MemorySessionOptionstype

Configured as session and context on AgentConfig, and sessionId on RunOptions. The backed adapters are in just-another-sdk/sessions. See Sessions.

Reliability

ExportKindDescription
RetryPolicytypemaxRetries, retryDelayMs, maxRetryDelayMs, retryOn

Configured as flat fields on AgentConfig, alongside fallbacks: ModelProvider[]. See Errors → Retries.

Events

ExportKindDescription
consoleTracerfunctionReady-made listener that prints a readable trace
ConsoleTracerOptionstypeverbose, color, write, maxValueLength
EventEmitterclassThe run's event bus
AgentEventtypeUnion of every event
AgentEventTypetype'run.start' | 'model.request' | …
EventOfType<T>typeNarrows AgentEvent by type
EventListenertype(event: AgentEvent) => void
RunStartEventRunErrorEventtypeIndividual event shapes
ModelRetryEventtypeattempt, maxAttempts, delayMs, discardedText
ModelFallbackEventtypefromModelId, toModelId, index, error
OutputInvalidEventtypeattempt, maxAttempts, issues, repairing
GuardrailTriggeredEventtypeguardrail, stage, action, toolName?, reason?
HandoffStartEventtypefrom, to, toolName, reason?, carriedCount
HandoffRefusedEventtypefrom, to, cause, reason
ApprovalRequiredEventtypeturn, calls
ApprovalResolvedEventtypetoolCallId, toolName, approved, reason?
SessionLoadEventtypesessionId, messageCount, droppedCount, truncated
SessionSummarizeEventtypecoveredCount, foldedCount, keptCount, error?
SessionSaveEventtypesessionId, appendedCount

Errors

ExportCode
AgentErrorbase class for all of the below
ConfigurationErrorconfiguration_error
AuthenticationErrorauthentication_error
RateLimitErrorrate_limit_error — carries retryAfterMs
ProviderErrorprovider_error — carries status
NetworkErrornetwork_error
TimeoutErrortimeout_error
AbortErroraborted
InvalidToolInputErrorinvalid_tool_input — carries issues
ToolExecutionErrortool_execution_error
ToolNotFoundErrortool_not_found
InvalidSchemaErrorinvalid_schema
InvalidOutputErrorinvalid_output — carries issues, rawText, attempts
GuardrailErrorguardrail_blocked — carries guardrail, stage, subject
ApprovalRequiredErrorapproval_required — carries suspension
isAgentErrornarrowing helper
toAgentErrorwraps any thrown value as an AgentError
AgentErrorCode, SchemaIssuetypes

Messages

ExportKindDescription
userMessage, assistantMessage, toolMessage, textPartfunctionConstructors
isTextPart, isToolCallPart, isToolResultPartfunctionNarrowing
messageTextfunctionConcatenated text of a message
addUsage, ZERO_USAGEfunction/constUsage arithmetic
ModelMessage, SystemMessage, UserMessage, AssistantMessage, ToolMessagetypeMessage shapes
ContentPart, TextPart, ToolCallPart, ToolResultParttypeContent shapes
Usage, MessageRoletype

Schema interop

ExportKindDescription
validatefunctionValidate a value against any Standard Schema
resolveJsonSchemafunctionDerive JSON Schema from a validator schema
SchemaSubjecttypeWhose schema is being converted, for error wording
registerJsonSchemaConverterfunctionTeach the SDK a validator's converter
isStandardSchemafunctionRuntime guard
StandardSchemaV1, InferSchemaOutput, ValidationResulttype
JsonSchema, ObjectJsonSchematype

Guardrails

ExportKindDescription
InputGuardrail, OutputGuardrail<T>, ToolGuardrail<T>, AnyToolGuardrailtypeThe three kinds — see Guardrails
GuardrailVerdict<T>, ToolGuardrailVerdicttypeallow · replace · reject · requireApproval
GuardrailAllow, GuardrailRewrite<T>, GuardrailReject, GuardrailRequireApprovaltypeThe individual verdict shapes
GuardrailContext, OutputGuardrailContext, ToolGuardrailSubject<T>typeWhat a check receives
ApprovalSuspension, PendingApproval, PendingToolCalltypeA suspended run, as plain JSON
ApprovalDecisiontype{ toolCallId, approved, reason? }

Provider contract

Re-exported from the root so writing a provider needs only one import: ModelProvider, ModelRequest, ModelResponse, ModelCallOptions, ModelStreamChunk, ToolDefinition, ToolChoice, FinishReason, ResponseFormat, plus the helpers textOf and toolCallsOf.

Utilities

ExportDescription
createIdSortable prefixed id, e.g. run_m9x2k1p_a7f3z9
redact, redactHeaders, redactStringSecret redaction — see Errors

just-another-sdk/providers

ExportDescription
anthropic(modelId, options?)Claude, natively
google(modelId, options?)Gemini, natively
gemini(modelId, options?)Alias of google
openai(modelId, options?)OpenAI Chat Completions
openrouter(modelId, options?)OpenRouter
compatible(modelId, options)Any OpenAI-compatible endpoint
createOpenAICompatibleProvider(config)The shared OpenAI transport, for building on

Option types are exported alongside each: AnthropicOptions, GoogleOptions, OpenAIOptions, OpenRouterOptions, CompatibleOptions, and OpenAICompatibleConfig.

just-another-sdk/sessions

Runtime-neutral: every adapter here takes a client you already have, so nothing in this entry point imports a Node builtin.

ExportDescription
redisSession(client | options)node-redis or ioredis, detected
postgresSession(client | options)pg, postgres.js, Drizzle, Prisma, or a query function
drizzleSession(db | options)Drizzle, via db.$client
prismaSession(client | options)Prisma, via $queryRawUnsafe / $executeRawUnsafe
memorySession, trimHistory, estimateTokensRe-exported from the root
assertValidSessionIdThe guard every adapter applies to an untrusted id
SessionStore, ContextPolicytypes
RedisClient, NodeRedisLike, IoRedisLike, RedisSessionOptionstypes
PostgresClient, PgClientLike, PostgresJsLike, PrismaLike, DrizzleLike, SqlQuery, PostgresSessionOptionstypes

just-another-sdk/sessions/file

ExportDescription
fileSession(dir | options)One JSONL file per session. Needs node:fs
FileSessionOptionstype

just-another-sdk/sessions/sqlite

ExportDescription
sqliteSession(path | options)Needs node:sqlite, so Node ≥ 22.5
SqliteSessionOptionstype

just-another-sdk/streams

ExportDescription
memoryStreamStore(options?)Default recordings store. One process only
redisStreamStore(client | options)Multi-instance. node-redis or ioredis
startResumable, resumeStreamFunctional forms of .resumable() / .resume()
StreamStore, StreamStatus, StreamOutcome, ResumableRun, ResumableOptions, FollowOptionstypes
RedisStreamClient, NodeRedisStreamLike, IoRedisStreamLike, RedisStreamStoreOptionstypes

just-another-sdk/testing

ExportDescription
mockProvider(script, options?)A scripted, offline provider
collectEvents()Records a run's events for assertions
MockProvider, MockTurn, MockToolCall, MockProviderOptions, EventCollectortypes

See Testing for usage.

Version policy

While the package is 0.x, minor versions may contain breaking changes; they are documented in the changelog. New members are added to the AgentEvent and AgentErrorCode unions in minor releases, so switch on them with a default branch.

On this page