Skip to main content
NetScriptdocs Search docs ⌘K v0.0.9
Browse documentation
View as Markdown

@netscript/plugin-ai

The NetScript AI plugin: a manifest, connector and scaffolder that wire an app-owned, in-process AI chat, tool and agent surface onto @netscript/ai and @netscript/fresh/ai. Use it to add AI chat to a NetScript app; the plugin ships no runtime AI logic of its own. The engine (providers, tools, agent loop, embeddings) is @netscript/ai, the durable-chat runtime is @netscript/fresh/ai, and the versioned /v1/ai contract is @netscript/plugin-ai-core. The scaffolders emit typed userland glue that imports those dependencies directly.

Sub-path exports

Export Entrypoint Purpose
@netscript/plugin-ai ./mod.ts Plugin manifest, identifiers, and manifest types.
@netscript/plugin-ai/public ./src/public/mod.ts Curated public manifest surface (alias target of the root).
@netscript/plugin-ai/plugin ./src/public/mod.ts Plugin manifest and constants (alias of the public surface).
@netscript/plugin-ai/adapter ./src/adapter/plugin.ts NetScriptPlugin connector consumed by the CLI (install, resources, doctor).
@netscript/plugin-ai/adapter-cli ./cli.ts Published CLI entrypoint (createPluginAdapter(...).toCli()).
@netscript/plugin-ai/scaffold ./scaffold.ts Scaffolder protocol entrypoint (createPluginAdapter(...).toScaffold()).
@netscript/plugin-ai/contracts ./contracts/v1/mod.ts Re-export of the /v1/ai contract owned by @netscript/plugin-ai-core.

Plugin manifest (@netscript/plugin-ai)

The plugin manifest consumed by the NetScript host and its stable identifiers. The manifest is built with definePlugin from @netscript/plugin, which also provides inspectPlugin. It declares only its contribution axes (one runtime-config topic and one contract version) and bundles no service or background processor.

Symbol Kind Value Description
aiPlugin const PluginManifest Plugin manifest for the NetScript AI plugin.
AI_PLUGIN_ID const "@netscript/plugin-ai" Canonical plugin id used across the manifest, connector, and scaffolder.
AI_PLUGIN_VERSION const package version Plugin version, single-sourced from the package deno.json.
AI_WORKSPACE_NAME const "ai" Runtime-config topic name and generated userland workspace directory.
AiPluginManifest type alias PluginManifest Named handle consumers annotate a host plugin list with.
AiPluginId type alias "@netscript/plugin-ai" Literal type of the plugin id.
AiWorkspaceName type alias "ai" Literal type of the workspace name.

Manifest contributions:

  • type is "utility", with no contributed services and no backgroundProcessors.
  • contributions.runtimeConfigTopics includes the "ai" topic.
  • contributions.contractVersions includes { version: "v1", loader: "./contracts/v1/mod.ts" }.
  • permissions are --allow-net, --allow-env, --allow-read: the host permissions the scaffolded in-process chat route needs to reach a provider, read its API key, and materialize durable sessions.
TypeScript
import { aiPlugin } from "@netscript/plugin-ai";

console.log(aiPlugin.name); // "@netscript/plugin-ai"
console.log(aiPlugin.contributions.runtimeConfigTopics); // includes the "ai" topic

Connector (@netscript/plugin-ai/adapter)

The NetScriptPlugin connector the CLI drives to install the plugin, add resources and run doctor. Its install seams are pure data, so a host can preview what an install will emit before writing any file.

Symbol Kind Description
aiAdapterPlugin const The AI NetScriptPlugin connector (kind "ai").
aiStarterResources const The ordered starter resources emitted by the default install.

The connector declares:

Field Value
install.starterResources The six starter scaffolders emitted by a default install (see scaffolded output).
install.dependencySpecifier / update.targetSpecifier An exact jsr:@netscript/plugin-ai@<release> specifier derived from package metadata.
install.configParams ["AI_MODEL", "ANTHROPIC_API_KEY"] (see configuration).
doctor.requiredConfigKeys ["ANTHROPIC_API_KEY"] (see doctor).
resources The add-only resources tool, agent, and thread-store.
remove.strategy / update.strategy "manifest-only" / "dependency".
TypeScript
import { aiAdapterPlugin } from "@netscript/plugin-ai/adapter";
import { collectInstallArtifacts } from "@netscript/plugin/adapter";

// Paths emitted by the default (in-process) install topology.
for (const artifact of collectInstallArtifacts(aiAdapterPlugin)) {
  console.log(artifact.path); // e.g. "ai/ai.ts", "ai/routes/chat-stream.ts"
}

// Add-only resources you can scaffold incrementally.
console.log(aiAdapterPlugin.resources?.map((resource) => resource.name));
// ["tool", "agent", "thread-store"]

Contract (@netscript/plugin-ai/contracts)

Re-exports the /v1/ai oRPC contract owned by @netscript/plugin-ai-core/contracts/v1, so a host binds the AI plugin against one pinned contract. The generated stream route imports createAiRouter, aiContractV1 and AiRouterImplementation from @netscript/plugin-ai-core, implements the contract with createAiRouter(...), and exports the bound aiRouter and aiRouteContract (aiContractV1) for host integration and tests.

Route paths are relative; the /v1/ai prefix is applied where the service host mounts the router.

Procedure Route Input schema Output
describe GET /describe — AiCapabilities capability document.
chat POST /chat ChatInputSchema SSE-framed stream of ChatChunk (text, tool-call, tool-result, usage, done, error).
models GET /models ModelsInputSchema ModelsResponse (available model descriptors).
invokeTool POST /tools/{name} ToolInvokeInputSchema ToolInvokeResponse.
embed POST /embed EmbedInputSchema EmbedResponse (embeddings, model, usage).
transcribe POST /transcribe TranscribeInputSchema TranscribeResponse.

Key exported symbols; the @netscript/plugin-ai-core reference has the full surface:

Symbol Kind Description
aiContract / aiContractV1 const The versioned /v1/ai oRPC contract handle.
ChatInputSchema / ChatChunkSchema const Zod schemas for the streaming chat route IO.
ModelsInputSchema / ModelsResponseSchema const Zod schemas for the models route IO.
ToolInvokeInputSchema / ToolInvokeResponseSchema const Zod schemas for the tool-invocation route IO.
EmbedInputSchema / EmbedResponseSchema const Zod schemas for the embeddings route IO.
TranscribeInputSchema / TranscribeResponseSchema const Zod schemas for the transcription route IO.
AiContract / AiContractV1 / AiRouter type alias Contract and router types derived from the contract.

MCP servers through service discovery

Add an app-owned MCP server by its Aspire resource name:

Shell
netscript plugin ai mcp add orders --service=orders-mcp --path=/mcp --auth=ORDERS_MCP_TOKEN

This creates ai/mcp/orders.ts and updates ai/mcp/registry.ts. The generated configuration uses getServiceUrl from @netscript/sdk/discovery and joins the MCP path with Web URL. The endpoint is resolved when the configuration module loads in the app process, so generation needs no running server. Configure discovery before importing the registry. For this example, the default endpoint comes from services__orders-mcp__http__0; a missing value throws an error naming the service and expected variable. There is no fallback port.

Make the consuming app reference the MCP server resource in your Aspire AppHost so that Aspire injects its endpoint. Your app owns that server, its tools and authorization. --auth names an environment variable containing the Authorization header value (include Bearer if the server expects bearer authentication); the generated source stores the variable name, not the token. The plugin's scaffold --mcp option emits the skill-loader tool and does not create this app-data MCP server.

Option Service mode behavior
--service=<name> Logical Aspire resource name, using letters, digits and hyphens; starts with a letter.
--path=/mcp Defaults to /mcp; a root-relative path replaces any path in the discovered base URL.
--protocol=http http by default; https selects services__<name>__https__0.
--auth=<ENV> Optional existing HTTP token configuration; the value becomes the Authorization header.

Exactly one of --service, --url or --stdio is required. Empty or valueless flags, invalid protocols and ambiguous transport selections fail before changing the server file or registry. --path and --protocol require service mode. Paths cannot contain an origin, query, fragment, dot segments, whitespace or encoded separators.

Fixed URLs and stdio commands remain available:

Shell
netscript plugin ai mcp add docs --url=https://docs.example.test/mcp --auth=DOCS_MCP_TOKEN
netscript plugin ai mcp add local --stdio=mcp-local-server
netscript plugin ai mcp list

New JSR installs receive the SDK alias through the CLI's plugin import wiring. For an existing JSR project installed before service mode was added, add the SDK to the root import map before loading the new config: run deno add jsr:@netscript/sdk@<version> from the project root, replacing <version> with the exact NetScript version already used by the project. Local-source projects resolve the copied SDK workspace member and must not add a published SDK pin.

Install and variants

Install the plugin into a scaffolded NetScript app. Its officialSource.canonicalName is ai, so the bare kind resolves to @netscript/plugin-ai:

Shell
netscript plugin install ai

The command installs the JSR package, then runs the plugin's scaffolder, which emits the six default files under ai/. The default topology is fully in-process: the generated stream route calls @netscript/ai directly inside your app's Fresh server, with no AI gateway or network hop.

Variants

The plugin defines three install shapes:

Variant Intended effect Status
default Emit the six in-process starter files under ai/. Wired.
--persist-threads Also scaffold ai/thread-store.ts (a Deno.Kv-backed thread store). Available as the thread-store adapter resource; not a public install flag.
--mcp Scaffold the skill-loader tool. Separate from MCP server client configuration above.

The thread-store scaffolder is an add-only adapter resource rather than part of the default install set, so an app that does not want durable threads never receives a bundled store.

Add-only resources

The connector exposes three resources beyond the default set; each emits one artifact:

Resource Artifact Purpose
tool ai/tools/<id>.ts A Standard-Schema AI tool over @netscript/ai/tools.
agent ai/agents/<id>.ts A bounded agent loop over @netscript/ai/agent.
thread-store ai/thread-store.ts An opt-in Deno.Kv-backed durable-thread store (--persist-threads).

Each resource derives its file and exported-symbol names from a user-supplied id via the shared fileStem / exportStem helpers, so summarize emits ai/tools/summarize.ts exporting summarizeTool, and researcher emits ai/agents/researcher.ts exporting createResearcherAgent.

Configuration

The connector records two config params at install time (install.configParams):

Key Required Read by Notes
ANTHROPIC_API_KEY Yes @netscript/ai's Anthropic provider (self-registered by the @netscript/ai/anthropic side-effect import). Enforced by netscript plugin doctor — see below.
AI_MODEL No App-owned ai/models.ts (the starter pins model refs directly). Recorded as a config param; the generated models.ts resolves provider:model-id refs and can read this key if you wire it.

The scaffolded runtime resolves models by provider:model-id ref (for example anthropic:claude-sonnet-4-5), which @netscript/ai's getModel resolves against the self-registered provider. The starter ai/models.ts is app-owned; edit it to pin the providers and models your app uses.

Doctor

netscript plugin doctor <pkg> dispatches the doctor verb to the plugin's published CLI, which runs the core-owned doctor algorithm against the connector's doctor.requiredConfigKeys. For the AI plugin that is ANTHROPIC_API_KEY, producing a single config check:

Check name Passes when Failure message
config:ANTHROPIC_API_KEY ANTHROPIC_API_KEY is present in the resolved app config. Missing config key ANTHROPIC_API_KEY

An empty config reports ok: false with the missing-key message; a config carrying the key reports ok: true.

Scaffolded output

netscript plugin install ai emits these app-owned files under ai/, in this order. Every file is yours: the scaffolder writes a typed wrapper importing the installed dependency, never a copy of framework source.

File Scaffolder Purpose
ai/models.ts modelsScaffolder Provider ids + provider:model-id refs (edit freely).
ai/ai.ts barrelScaffolder Composition root: wires @netscript/ai once and re-exports the client, model resolver, and tool registry.
ai/tools/echo.ts toolResource Starter Standard-Schema tool over @netscript/ai/tools.
ai/agents/assistant.ts agentResource Starter bounded agent loop over @netscript/ai/agent.
ai/routes/chat-stream.ts streamProxyScaffolder In-process POST route: runs the agent loop directly and binds the /v1/ai router.
ai/routes/chat.tsx chatRouteScaffolder TanStack-backed chat island rendering assistant parts.

The opt-in thread store adds one more file:

File Scaffolder Purpose
ai/thread-store.ts threadStoreScaffolder App-owned ThreadStore port + starter Deno.Kv store (opt-in).
  • ai/
    • ai.ts # composition root: ai(), chatModel(), aiTools
    • models.ts # AI_PROVIDERS, AI_MODELS, DEFAULT_CHAT_MODEL
    • routes/
      • chat-stream.ts # in-process POST handler + createAiRouter(...) for /v1/ai
      • chat.tsx # chat island (streams from /api/ai/chat-stream)
    • tools/
      • echo.ts # starter defineAiTool
    • agents/
      • assistant.ts # starter createAgentLoop factory
    • thread-store.ts # opt-in Deno.Kv ThreadStore (--persist-threads)

Runtime registries

scaffold.runtime.json declares two generated registries that compiled runtimes use to statically import app-owned tools and agents:

Registry kind Source directory Generated path Item type
ai-tools ai/tools .netscript/generated/plugin-ai/tools.registry.ts AiToolDefinition (@netscript/ai/tools)
ai-agents ai/agents .netscript/generated/plugin-ai/agents.registry.ts AgentLoop (@netscript/ai/agent)

Examples

Compose the runtime and stream a reply

The generated ai/ai.ts wires @netscript/ai once and re-exports the client, model resolver, and tool registry. The starter agent and chat route build on it:

TypeScript
import { createAgentLoop, slidingWindowHistory } from "@netscript/ai/agent";
import { ai, chatModelId, DEFAULT_CHAT_MODEL } from "./ai.ts";

const loop = createAgentLoop({
  modelProvider: ai().getModelProvider(),
  history: slidingWindowHistory({ maxMessages: 32 }),
  tools: ai().tools,
});

for await (const chunk of loop.run({
  model: chatModelId(DEFAULT_CHAT_MODEL),
  messages: [{ role: "user", content: "Summarize the release notes." }],
  system: "You are the assistant. Be concise and precise.",
})) {
  // stream text/tool chunks to the client
}

Cancellable in-process chat route

The generated ai/routes/chat-stream.ts runs the agent loop directly inside the app server and hands the token stream to @netscript/fresh/ai's toNetScriptChatResponse for durable-session persistence. It threads the request's AbortSignal into the loop and exposes stop() on the connection, so a client can cancel an in-flight generation mid-stream:

TypeScript
import { toNetScriptChatResponse } from "@netscript/fresh/ai";
import { streamChat } from "./chat-stream.ts";

export async function handler(request: Request): Promise<Response> {
  const { sessionId, message } = await request.json();
  return toNetScriptChatResponse({
    target: { sessionId },
    source: streamChat({ message: message.text, signal: request.signal }),
    newMessages: [{ role: "user", text: message.text }],
    request,
  });
}

The generated chat island (ai/routes/chat.tsx) posts to /api/ai/chat-stream, renders assistant RenderPart[] through the app's copy-based Markdown component, and shows a Stop button while streaming that calls connection.stop().

Define an app-owned tool

netscript plugin ai add tool summarize (or the tool adapter resource) emits a thin Standard-Schema tool over @netscript/ai/tools:

TypeScript
import { defineAiTool } from "@netscript/ai/tools";

export const summarizeTool = defineAiTool("summarize")
  .describe("Describe what summarize does so the model knows when to call it.")
  .parameters({
    type: "object",
    properties: { query: { type: "string", description: "The primary input for summarize." } },
    required: ["query"],
  })
  .input(/* Standard-Schema validator */)
  .server(({ query }) => {
    // App-owned business logic.
    return { ok: true, echo: query };
  });
Search all documentation

Type a term to search the documentation.