@netscript/ai@0.0.10Built and signed on GitHub ActionsBuilt and signed on GitHub Actions
The zero-dependency AI engine core for NetScript: domain contracts, capability ports, model and tool registries, a bounded agent loop, an MCP client stack, and a composition root — providers stay on their own subpaths until imported.
@netscript/ai
The zero-dependency AI engine core for NetScript: domain contracts, capability ports, model and tool registries, a bounded agent loop, an MCP client stack, and a composition root — providers stay on their own subpaths until imported.
The base entrypoint ships no concrete provider and takes no @netscript/* runtime
dependency. Providers self-register as an import side effect — exactly like @netscript/kv/redis
registers its adapter — so no provider SDK enters your module graph until an app opts in. The tool
system validates input with Standard Schema (bring zod, valibot,
arktype, or a hand-written schema), the agent loop is a bounded, cancellable typestate machine, and
every capability is a port with a safe default, so an unconfigured runtime is safe to hold and
inspect.
Why teams use it
- Bundle isolation, enforced —
import '@netscript/ai'pulls zero provider dependencies;@netscript/ai/anthropicpulls only@tanstack/ai-anthropic,@netscript/ai/openai-compatibleonly@tanstack/ai-openai. A test imports each subpath in a fresh subprocess and asserts the registry contains exactly that one provider. - Self-registering providers — Anthropic, OpenAI-compatible (any Chat Completions or Responses endpoint), OpenRouter, Ollama, and OpenAI-compatible embeddings and vision, each a subpath that registers its factory on import and re-exports the provider class for direct construction.
- Bounded, cancellable agent loop —
createAgentLoopdrives multi-turn conversations with amaxStepscap, a pluggable history strategy, real summed providerUsage(no estimation), andAbortSignal/loop.stop()cancellation that always unwinds cleanly. - Owned chat surface —
createChatClientreturns an ownedChatClientPortstreaming an owned event union (text|tool-call|finish|error); no provider-SDK type escapes the public surface, and per-callconnectionoptions support one-turn credential overrides. - Standard Schema tool system —
defineAiTool+createToolRegistrydefine, register, and dispatch server-executable tools with input validated before the handler runs;renderUiToolships the generative-UI wire contract consumed by@netscript/fresh-ui. - MCP client stack — streamable-HTTP and stdio transports behind owned ports, a multi-server
transport pool, and
registerMcpToolsto bridge remote MCP tools into the same registry seam the agent loop already drives. - Agent skills —
@netscript/ai/skillsvalidates a smallSKILL.mdstandard, matches by tag or opt-in embeddings, and loads full instruction bodies only on demand. - Ports with safe defaults — telemetry defaults to a no-op; capabilities that need a real
adapter throw a typed
AiNotConfiguredErroruntil injected.
Architecture
flowchart LR A["App / feature code"] --> R["createAiRuntime()<br/>composition root + ports"] A --> L["createAgentLoop()<br/>bounded typestate loop"] L --> M["Model registry"] L --> T["Tool registry<br/>(Standard Schema dispatch)"] P1["@netscript/ai/anthropic"] -. "self-register on import" .-> M P2["@netscript/ai/openai-compatible<br/>openrouter · ollama"] -. "self-register on import" .-> M MCP["@netscript/ai/mcp<br/>transport pool"] -- "registerMcpTools" --> T
The core owns contracts, registries, and the loop; providers and the MCP stack live on subpaths and
enter the module graph only when imported. Real adapters — such as the @netscript/telemetry-backed
TelemetryPort — are injected through the composition root; the core never imports them.
Install
deno add jsr:@netscript/ai@<version>
Pin <version> to match your installed CLI; bare jsr:@netscript/* specifiers do not resolve on
the pre-release line.
Quick example
import { createAiRuntime } from '@netscript/ai'; import { createToolRegistry, defineAiTool } from '@netscript/ai/tools'; import { z } from 'jsr:@zod/zod@4'; // An unconfigured runtime is safe to hold: every capability defaults to a // no-op or throwing port until a real adapter is injected. const ai = createAiRuntime(); ai.telemetry.recordEvent('agent.start'); // Define a server-executable tool; input is validated with Standard Schema // (zod here — any conforming library works). const add = defineAiTool('add') .describe('Add two numbers') .parameters({ type: 'object', properties: { a: { type: 'number' }, b: { type: 'number' } }, required: ['a', 'b'], }) .input(z.object({ a: z.number(), b: z.number() })) .server(({ a, b }) => ({ sum: a + b })); const registry = createToolRegistry([add]); // Dispatch validates input BEFORE the handler runs. const { output } = await registry.dispatch('add', { a: 2, b: 3 }); console.log(output); // { sum: 5 }
Invalid input throws ToolInputValidationError; an unknown tool name throws ToolNotFoundError —
the handler never sees either.
Providers and the model registry
Import a provider subpath for its side effect, then resolve models through the registry:
import '@netscript/ai/anthropic'; // side effect: registers 'anthropic' import { getModel, getModelProvider } from '@netscript/ai'; // Resolve a model handle through the registry. const handle = await getModel('anthropic:claude-sonnet-5-5'); // Or construct a configured provider (apiKey falls back to ANTHROPIC_API_KEY). const provider = getModelProvider('anthropic', { apiKey: Deno.env.get('ANTHROPIC_API_KEY') }); const client = provider.createChatClient?.('claude-sonnet-5-5');
The Anthropic provider also accepts models?: readonly string[] for API IDs released ahead of its
bundled SDK catalog. The same instance uses those IDs in supports, listModels, getModel, and
createChatClient; unconfigured unknown IDs still reject. Discovery and construction require no
network access. Configuration is copied per instance and never changes the SDK catalog. Added IDs
carry no inferred vision, reasoning, or token-limit metadata.
import { AnthropicModelProvider } from '@netscript/ai/anthropic'; const anthropic = new AnthropicModelProvider({ apiKey: Deno.env.get('ANTHROPIC_API_KEY'), models: ['claude-opus-5-5', 'claude-fable-5-1'], }); const opus = anthropic.createChatClient('claude-opus-5-5');
For the exact Opus 5.5 and Fable 5.1 IDs, adaptive thinking remains on: neutral
reasoningEffort: 'off' emits no disabling field. Sonnet 5.5 maps off to
thinking: { type: 'between_tools' }, its supported mode without up-front reasoning. Other IDs
retain the generic mapping. Use output_config.effort in providerOptions or per-call
modelOptions for Anthropic's native effort levels, including xhigh and max. The final merged
options are checked before IO; disabled/manual thinking, forced tool choices and non-default
sampling reject for those three IDs. Sonnet's between_tools cannot be combined with xhigh/max
or extra thinking fields. See
Anthropic's thinking modes and
Opus migration guide.
This configuration requires a release containing this change; published @netscript/ai 0.0.7
does not expose it. Workspace regressions pass with @tanstack/ai@0.52.0 and
@tanstack/ai-anthropic@0.18.3; the same regressions also pass with the reported consumer graph
@tanstack/ai@0.52.3 and @tanstack/ai-anthropic@0.18.3, retaining the compatible dependency family. When the fix is
published, pin the exact stable NetScript release and use the configuration above; do not upgrade
only the Anthropic adapter into the older peer graph. Mocked Messages tests establish transport
compatibility. Input and cache usage from message_start are retained when later cumulative deltas
report only output counts; a fresh silent usage observer is created per turn. Reported fields replace
earlier values instead of adding cumulative counts. Paid live inference and validation against a newly
published package remain release acceptance steps.
The OpenAI-compatible provider reaches any endpoint that speaks the OpenAI Chat Completions or
Responses API — point baseURL at DeepSeek, Together, vLLM, or a local gateway; with no models
configured the remote endpoint is the authority on its own catalog. Streaming is cancelled by
passing an AbortSignal, and per-call connection options override credentials and endpoints for
one turn without touching provider defaults. Configuration errors identify missing field names but
never include key or endpoint values.
Busy-provider retries
OpenAI-compatible chat preserves known busy failures (429, 503, and OpenAI's
rate_limit_exceeded) as error events with an AiRateLimitError cause. The cause carries numeric
status and the provider's retryAfterMs, when available. Unknown symbolic errors and
insufficient_quota remain ordinary terminal error events. The shared TanStack bridge applies this
classification to every provider using it; it never retains raw SDK request or header objects.
Retry is opt-in. Set the chat provider's maxRetries: 0 to disable the SDK's own retries, then wrap
its client so one policy owns the attempt budget:
import { withRetryingChatClient } from '@netscript/ai'; import { OpenAiCompatibleModelProvider } from '@netscript/ai/openai-compatible'; const provider = new OpenAiCompatibleModelProvider({ baseURL: 'https://provider.example/v1', apiKey: 'your-key', maxRetries: 0, }); const client = withRetryingChatClient(provider.createChatClient('model'), { maxAttempts: 3, maxDelayMs: 120_000, });
maxRetries is also accepted by getModelProvider('openai-compatible', config). Omitting it keeps
the SDK default. Supply a number when building registry configuration; nonnumeric registry values
fall back to that default. This configuration applies to chat; embedding SDK retry configuration is
unchanged.
The wrapper retries a busy error event or thrown failure only before any event reaches the
caller. It never replays text, reasoning or tool calls after partial output. On exhaustion, including
maxAttempts: 1, it throws AiRateLimitError with the original status/delay and actual attempt count;
the agent loop converts this back to its error chunk. Unwrapped chat clients keep error events.
Retry-After is a minimum, not a delay to shorten. For both retry wrappers (chat and embeddings), a
provider delay above maxDelayMs fails immediately without another request or a sleep; the typed
error retains that delay. The default ceiling is 5,000 ms. Raise it explicitly, as above, to honor a
120-second response. Delays within the ceiling are honored exactly. Generated backoff and server
waits have an absolute timer ceiling of 2³¹−1 ms, and all waits remain abortable. Without a provider
delay the existing exponential full-jitter policy applies. This replaces the old behavior that
clipped longer provider delays and retried too soon.
Agent loop
import { createAgentLoop, slidingWindowHistory } from '@netscript/ai/agent'; import type { ChatModelProviderPort, ToolRegistryPort } from '@netscript/ai/agent'; import type { Message } from '@netscript/ai/contracts'; declare const modelProvider: ChatModelProviderPort; declare const tools: ToolRegistryPort; declare const messages: Message[]; const loop = createAgentLoop({ modelProvider, tools, history: slidingWindowHistory({ maxMessages: 12 }), }); const abort = new AbortController(); for await ( const chunk of loop.run( { model: 'anthropic:claude-sonnet-5-5', messages }, { signal: abort.signal, maxSteps: 8 }, ) ) { if (chunk.type === 'text') Deno.stdout.writeSync(new TextEncoder().encode(chunk.delta)); if (chunk.type === 'tool-result') console.log('tool ->', chunk.result.content); if (chunk.type === 'done') console.log('usage', chunk.usage); // real, summed provider usage }
The loop is a typestate machine
(idle → running → awaiting-tool → running → done | aborted | errored, exposed as loop.state).
Exceeding maxSteps emits an error chunk carrying AgentMaxStepsExceededError; a missing tool
handler yields an error-state ToolResult rather than throwing; on abort the generator always
returns — nothing leaks. An injected TelemetryPort turns each run into a gen_ai.chat span with
per-turn spans and tool-call events.
Request context (never reaches the model)
Some state belongs to one run but must stay invisible to the model — the ids of documents just
ingested, the tenant or auth subject, a correlation id. AgentLoopInput.context is the supported
channel for it. Anything else you might reach for is a path to the provider:
GenerationOptions.providerOptions merges verbatim into the adapter's modelOptions, and message
text is, of course, exactly what the model reads.
import { createAgentLoop } from '@netscript/ai/agent'; import type { ChatModelProviderPort, ToolRegistryPort } from '@netscript/ai/agent'; import type { Message } from '@netscript/ai/contracts'; declare const modelProvider: ChatModelProviderPort; declare const tools: ToolRegistryPort; declare const messages: Message[]; for await ( const chunk of createAgentLoop({ modelProvider, tools }).run({ model: 'anthropic:claude-sonnet-5-5', messages, context: { documentIds: ['doc_41', 'doc_42'], tenantId: 'acme' }, }) ) { if (chunk.type === 'done') break; }
The bag is opaque to the engine — it reads no key and serializes it nowhere. It is delivered to exactly two places:
| Consumer | How it arrives |
|---|---|
| TanStack AI middleware | chat({ context, metadata }) — metadata is documented as never forwarded onto the provider wire request |
| Tool handlers | ToolInvocationOptions.context on a ToolHandler; AiToolInvocationContext.metadata on a defineAiTool(...).server() definition |
import { createToolRegistry, defineAiTool } from '@netscript/ai/tools'; import type { StandardSchemaV1 } from '@standard-schema/spec'; declare const schema: StandardSchemaV1<unknown, { query: string }>; const search = defineAiTool('search') .describe('Search the documents attached to this request') .input(schema) .server((input, context) => { // The run's context — the model never saw any of this. const documentIds = context.metadata?.['documentIds']; return { query: input.query, documentIds }; }); const registry = createToolRegistry([search]);
messages, system, tools, and modelOptions remain the only four things a provider adapter
puts on the wire; packages/ai/tests/request_context_test.ts pins that with a sentinel value
checked against a stubbed provider transport.
MCP client stack
import { createMcpTransportPool, registerMcpTools } from '@netscript/ai/mcp'; import { createToolRegistry } from '@netscript/ai/tools'; const pool = createMcpTransportPool({ servers: [{ kind: 'streamable-http', serverId: 'search', url: 'https://mcp.example.com', auth: { mode: 'api-token', token: 'injected-at-runtime', scheme: 'Bearer' }, }], }); const registry = createToolRegistry(); await registerMcpTools(registry, pool);
Remote MCP tools land in the same ToolRegistryPort seam as local ones, so the agent loop calls
them identically. Pooled tool results surface embedded ui:// resources as uiResources — the
payload the @netscript/fresh-ui MCP widget renders.
Treat remote MCP servers as optional infrastructure: give startup a caller-owned deadline, then
inspect the synchronous snapshot. Reading snapshot performs no network I/O, so request handling
can select ready servers without waiting on degraded peers.
import type { McpTransportPool } from '@netscript/ai/mcp'; declare const pool: McpTransportPool; const startup = AbortSignal.timeout(1_500); await pool.connect({ signal: startup }); const { statuses, readyClients } = pool.snapshot; for (const status of Object.values(statuses)) { if (status.lastError) { console.warn(`MCP ${status.serverId} is ${status.state}: ${status.lastError}`); } } const search = readyClients.search; if (search) { // Healthy peers remain usable even when another server timed out. await search.listTools({ signal: AbortSignal.timeout(500) }); }
When registering pooled tools, the optional signal passed to registerMcpTools bounds discovery and
later automatic re-sync operations for that registration. It is not reused by registered tool calls.
Use a registration-lifetime signal rather than a one-shot startup timeout; individual transport
calls accept their own operation-specific signal.
Retry only the degraded server instead of rebuilding healthy peers:
import type { McpTransportPool } from '@netscript/ai/mcp'; declare const pool: McpTransportPool; const degraded = pool.server('search'); if (degraded) { await degraded.reconnect({ signal: AbortSignal.timeout(1_500) }); } await pool.stop({ signal: AbortSignal.timeout(1_000) });
The same McpConnectOptions signal convention applies to connect, list, call, resource-read, and
close operations. A timed-out server retains its last error in snapshot.statuses; a late
connection is closed rather than inserted into readyClients.
Public surface
| Entry | What it gives you |
|---|---|
. |
createAiRuntime / getAiRuntime, model + embeddings + vision registries, composeSystemPrompt |
./contracts |
Domain types (Message, ToolDescriptor, Usage, RequestContext, …) and the typed error hierarchy |
./ports |
Capability seams (TelemetryPort, AgentMemoryPort, McpTransportPort, …) with safe defaults |
./tools |
defineAiTool, createToolRegistry, the renderUiTool wire contract |
./agent |
createAgentLoop, slidingWindowHistory, the loop's port seams |
./skills |
SKILL.md loader: metadata-only discovery, tag/embedding matching, on-demand load |
./mcp |
MCP transports, transport pool, ui:// resource extraction, tool bridging |
./testing |
Deterministic fake ports for downstream unit tests |
./anthropic |
Self-registering Anthropic provider (wraps @tanstack/ai-anthropic) |
./openai-compatible |
Self-registering OpenAI-compatible chat + vision provider |
./openrouter |
Self-registering OpenRouter provider + reasoning-model options |
./ollama |
Self-registering Ollama provider with injectable reachability port |
./openai-embeddings |
Self-registering OpenAI-compatible embeddings provider |
The always-current symbol list is
deno doc jsr:@netscript/ai@<version> (pin <version> on the
pre-release line, as above).
Docs
- Reference — runtime, registries, loop, tools, and MCP APIs: rickylabs.github.io/netscript/reference/ai/
- AI overview — how the engine, chat UI, and plugin fit together: rickylabs.github.io/netscript/ai/
- AI engine — composition, providers, and the agent loop in depth: rickylabs.github.io/netscript/ai/engine/
- API docs on JSR: jsr.io/@netscript/ai/doc
Compatibility
The core is runtime-neutral TypeScript with no permissions of its own. Provider subpaths wrap the
TanStack AI clients, perform network access (--allow-net under Deno), and read their API keys from
the environment when not passed explicitly (--allow-env). The real telemetry adapter lives in
@netscript/telemetry/ai and is injected as a TelemetryPort — this core never imports it.
License
Apache-2.0 — see LICENSE. Published to JSR with cryptographically verified provenance.
Qualified TanStack dependency family
The provider bridge and Fresh AI client are qualified together on AI core 0.65.0, Anthropic
adapter 0.19.5, OpenAI adapter 0.27.0, MCP adapter 0.8.0, and Preact adapter 0.19.5. Adapter
patch releases can change their AI core peer requirements, so these imports use exact versions.
Update the family together.
Run deno task deps:check:ai-peers before changing these declarations. The guard checks every
currently admitted adapter version against admitted core versions, then resolves a consumer without
the workspace lock or configuration and checks the resolved peers. CI includes this gate in
ci:quality. To qualify a released artifact, append --published-version <exact-version>; this
resolves the public Anthropic and OpenAI provider exports without consumer dependency overrides.
This framework repair makes EIS-Chat's application-level TanStack AI compatibility pins removable once the coordinated framework release passes published-consumer qualification. A source PR or dry-run alone does not establish that release.
The cold guard inventories every resolved npm release, including openai-base and external peer
holders; it checks metadata without an adapter-name assumption. Fresh UI maintains a separate frozen
consumer lock and must be updated when this family changes. The qualified versions respect the
default dependency-age policy.
Examples
Compose a runtime and read a no-op default
Compose a runtime and read a no-op default
import { createAiRuntime } from "@netscript/ai"; const ai = createAiRuntime(); // Telemetry defaults to a no-op port — safe to call with nothing wired. ai.telemetry.recordEvent("agent.start");
Register a provider and resolve a model
Register a provider and resolve a model
import { getModel, registerModelProvider } from "@netscript/ai"; registerModelProvider("demo", () => ({ id: "demo", listModels: () => Promise.resolve([]), getModel: (id) => Promise.resolve({ providerId: "demo", descriptor: { id, provider: "demo" } }), supports: () => true, })); const handle = await getModel("demo:some-model");
Add Package
deno add jsr:@netscript/ai
Import symbol
import * as ai from "@netscript/ai";
Import directly with a jsr specifier
import * as ai from "jsr:@netscript/ai@^0.0.10";