# @aimform/ai

Portable Agent SDK with an optional persistent cognitive architecture: model adapters, tool calling, streaming, event-sourced sessions, continuity, working memory, knowledge, relationships, context policy, and durable runtime seams. Aimform's React chat UI remains available separately at `@aimform/ai/client`.

Workflow graph semantics are owned by `@aimform/workflows`. AI Functions can be
referenced by a Workflow Specification v2 definition, while this package stays
focused on cognition, model providers, tool calling, and AI runtime seams.

```sh
npm install @aimform/ai
```

## Standalone Agent

```ts
import { Agent, deepseek, tool } from "@aimform/ai";

const calculator = tool<{ a: number; b: number }>({
  name: "calculator",
  description: "Multiply two numbers",
  input: {
    type: "object",
    properties: {
      a: { type: "number" },
      b: { type: "number" },
    },
    required: ["a", "b"],
  },
  execute: ({ a, b }) => a * b,
});

const agent = new Agent({
  model: deepseek("deepseek-chat", {
    apiKey: process.env.DEEPSEEK_API_KEY!,
  }),
  tools: [calculator],
  systemPrompt: "You are a concise assistant.",
});

const result = await agent.invoke("What is 25 * 18?");
console.log(result.text);
```

No database, Cloudflare binding, organisation, profile, React application, or Aimform Identity service is required. `Agent` uses an in-process `DirectRuntime` and event-sourced `MemorySessionStore` by default.

## Perception escalation

`@aimform/ai/core` exports `escalatePerception()` and provider-neutral
perception ports. It tries semantic, DOM, accessibility, text, OCR, visual,
and model evidence in order and preserves attempts for telemetry. OCR/VLM
providers must perform their own Guard admission; the core algorithm never
calls an external provider itself and can return `human_required` when evidence
remains below policy confidence.

Intent resolutions also carry an append-only `clarificationAnswers` projection.
Hosts can use the same portable snapshot for any domain: questions are selected
from the current request and context, and applying an answer never re-infers a
domain-specific meaning from the raw text.

Structured generation remains provider-neutral at the contract boundary. The
DeepSeek Chat Completions provider maps JSON-Schema requests to its supported
JSON mode, while the portable runtime performs the final schema validation
before accepting the result.

## SDK layout

The implementation is separated under `sdk/typescript`: Agent and cognition
contracts live in `core`, wire contracts in `shared`, server execution in
`server`, model/Aim integrations in `providers`, and the React chat surface in
`bindings/react`. Existing imports such as `@aimform/ai/client` and
`@aimform/ai/server` remain compatibility entrypoints.

## Streaming

```ts
for await (const event of agent.stream("Solve the next task")) {
  if (event.type === "text_delta") process.stdout.write(event.delta);
}
```

The React bindings expose `subscribeToSharedRealtime()` for hosts that need a
single physical routed WebSocket across user activity, organisation presence,
and conversation channels. The first authenticated route opens the socket
eagerly; subsequent app and run handlers reuse it and only add a logical route.
The route capability is still checked independently by the gateway, while the
browser keeps one transport connection and reconnects with replay sequence
numbers. Organisation presence messages are forwarded only after the signed
`org:<organisationId>` route has been authorized; space-specific protocols
remain on their dedicated transport.
High-frequency delta updates are coalesced per animation frame after the first
visible event, while terminal events flush synchronously so streaming remains
responsive without causing a React render for every token.
Run-control queue commands are append-only and consumed FIFO by the durable
session controller, so messages sent during an active run remain available to
the next run in arrival order.
Hosts can call `setSharedRealtimeActivityState("idle")` when the app is hidden,
unfocused, or inactive, and switch back to `"active"` on focus or input. The
shared client keeps notification listeners live while buffering ordinary route
events in a bounded queue; queued events are delivered in order when activity
resumes. This avoids background UI churn without introducing a data-polling
timer.

### Hosted chat authorization

The hosted React identity-run handler accepts an optional
`getChatAccessToken()` callback. Applications should return a cached,
renewable organization-scoped chat capability from this callback. The normal
login/session token remains the primary credential and is not shortened by
this feature; capability refresh is silent. Chat capabilities do not grant
tool execution or other sensitive operations, which continue to authorize at
their own operation boundary.

The reusable `Chat` and `ChatWidget` bindings expose the same optional
`getChatAccessToken` prop for hosts that construct the identity handler inside
the binding. Applications may also pass an already configured
`streamHandler`.

Hosted chat telemetry includes a conversation-create request breakdown:
client header resolution, network/Worker response, response parsing, and the
API's `Server-Timing` marks. This is persisted with the run performance record
for later admin-panel analysis.

Hosted sends include an additive `traceId` for cross-service correlation.
`ChatPerformanceMetrics.stageBreakdown` keeps cumulative milestones separate
from non-overlapping intervals, while provider diagnostics can report response
headers, first byte, attempts, and retry backoff without changing the stream
contract.

Server hosts can wrap a provider with `TimedLLMAdapter` from
`@aimform/ai/server` to record request-to-first-provider-chunk and
request-to-first-visible-output independently of full response completion.
This is the correct primitive for a streaming first-response SLO.

Browser progress can also travel on the shared stream through the
`browser_session_*`, `browser_action_started`, `browser_navigation`, and
`browser_snapshot` events. These events carry only opaque screenshot artifact
references and safe session metadata; proxy credentials and browser runtime
secrets never enter the chat event contract.

Provider streams accept host-owned `signal` and `timeoutMs` fields on
`ChatCompletionConfig`, allowing latency-sensitive hosts to cancel a stalled
first-output request without changing normalized events. The streaming
DeepSeek adapter disables reasoning for no-tool requests and enables it when
tools are present, preserving the fast path without weakening tool turns.

The research entry point also exposes `parseDeterministicEcho` for explicit
literal requests such as `say back "GTA"`. Hosts can use this narrow parser to
return an echo without invoking a model; ordinary questions and generated
responses remain on the normal streamed path.

When multiple context providers are configured, the composite resolver invokes
them concurrently and flattens their fragments in priority/registration order.
This preserves deterministic prompt ordering without serializing independent
provider I/O.

Providers can also return non-sensitive resolution metrics. The Agent aggregates
these into `ResolvedAgentContext.contextResolution`, and the server receipt
preserves the optional breakdown for latency, query count, selection, prompt
size, and cache-hit analysis without exposing context contents.

For a bounded deterministic response, set `maxOutputTokens` on an `Agent`.
This limits the main streamed generation round; it should not be used as a
shortcut for truncating research or tool-driven work.

### Delegated and background work

The shared event contract supports `agent_task_event` envelopes for child-agent
progress and `background_job_completed` interrupts for work that finishes after
the originating chat run. Hosts should preserve the envelope's
`originConversationId` and optional `originMessageId` when presenting a
completion link so users can jump back to the source conversation.

### Canonical resources in chat

Runs may emit a generic `resource_created` event containing only the resource
type, stable id, and canonical URI. React bindings retain that identity on the
assistant turn and restore it from durable message metadata. Hosts choose the
resource renderer by type and load the persisted resource through its owning
API; the event is not a transport-level `skill_card` or model-generated card.

## Models

The SDK includes ergonomic constructors for the normalized provider adapters:

```ts
import { anthropic, deepseek, model, ollama, openai, qwen } from "@aimform/ai";
```

Use `model(id, customAdapter)` for any custom `LLMAdapter`.

## Structured multimodal generation

`generateStructured()` accepts text, multiple images, documents/files, or
chat messages, sends provider-native multimodal blocks where supported, and
validates the returned JSON against the supplied JSON Schema before reporting
success. Provenance includes the model/provider, instruction version, source
references, and generation timestamp.

```ts
import { generateStructured, openai } from "@aimform/ai";

const result = await generateStructured(openai("gpt-4o", { apiKey }), {
  model: "gpt-4o",
  input: [
    { type: "text", text: "Compare these product images.", metadata: { sourceRef: "text:brief-1" } },
    {
      type: "image",
      source: { type: "url", value: "https://example.com/product.png" },
      metadata: { sourceRef: "files/product-image", versionId: "snapshot-4" },
    },
  ],
  schema: {
    type: "object",
    properties: { verdict: { type: "string", enum: ["MATCH", "MISMATCH"] } },
    required: ["verdict"],
    additionalProperties: false,
  },
});

if (result.ok) console.log(result.value, result.provenance);
else console.error(result.validationErrors);
```

Cloudflare Worker hosts can select `@cf/meta/llama-3.2-11b-vision-instruct`
through `CloudflareWorkersAIAdapter` and pass the `env.AI` binding at their
composition root. The API's `/api/ai/:orgId/generate` route adds
organisation authorization and persists the result as inference evidence for
later audit and replay.

## Tools

`tool()` is intentionally validation-library agnostic. Raw JSON Schema works directly; `validatedInput()` combines model-visible JSON Schema with any parser such as Zod, Valibot, ArkType, or an application-specific validator.

```ts
import { tool, validatedInput } from "@aimform/ai";

const lookup = tool({
  name: "lookup",
  description: "Look up a record",
  input: validatedInput(
    {
      type: "object",
      properties: { id: { type: "string" } },
      required: ["id"],
    },
    (value) => mySchema.parse(value),
  ),
  execute: ({ id }, ctx) => loadRecord(id, ctx.context),
});
```

## Persistent cognition

Aimform keeps several concepts deliberately separate instead of treating everything as generic "memory":

- **Session** — append-only, reconstructible execution/message history.
- **Continuity** — identity and compact handoff across model sessions/conversations.
- **WorkingMemory** — current task findings, decisions, failures, and plan state.

Aim-aware hosts may attach a provider-neutral semantic workspace through
`@aimform/ai/shared`. It supports explicit initialization, Aim queries,
semantic object descriptions, evidence/traces, validation, incremental
reconciliation, and semantic diffs. Initialization is intentionally
independent of Git and creates the provider's visible `aim/` workspace when
the source directory has neither `.git` nor `aim/` yet.
Aim remains an external provider: this package does not embed Tree-sitter, an
LSP, or Aim graph/resolver logic.

Non-Aim coding orchestration is available from `@aimform/ai/agent`: project
profile detection, impact classification, incremental verification planning,
shared artifacts, file ownership leases, test-result caching, and adaptive
model-purpose routing. These utilities compose with the existing Session, Run,
Strategy, Workflow, Plan, and CodeWorkspace primitives.

`codingStrategy()` provides the corresponding durable workflow composition:
orient, discover, decide, edit, verify, bounded repair, review, and finalize.
Hosts inject repository/runtime operations through callbacks. The optional
`finalize` callback is the strategy-owned completion boundary and is invoked only
after verification and review pass. Hosts can use `onPhase` to project the
ordered coding lifecycle into durable task events or telemetry.

For a host that owns durable scheduling, `codingStrategy()` also implements
`ResumableAgentStrategy.runPhase()`. Pass the serialized phase name and
`CodingStrategyState` to execute exactly one lifecycle phase and receive the
next phase plus JSON-safe state. This is the boundary used by
`services/execution/workflows` for coding-agent continuation rounds.

Aimform can opt into an Aim-backed clone of that workflow:

```ts
import { aimCodingStrategy } from "@aimform/ai/agent";

const strategy = aimCodingStrategy({
  aim: semanticWorkspace,
  implement: async (request, state) => implementInWorkspace(request, state),
  verify: async (request, state) => verifyWorkspace(request, state),
});
```

## Hosted Aim client

The client entry point also provides a transport-only adapter for the hosted Aim
REST service. It does not embed Aim or choose an AI provider; it forwards the
same Space-scoped operations used by the web app and MCP gateway.

```ts
import { HostedAimClient } from "@aimform/ai/client";

const aim = new HostedAimClient({ baseUrl: "https://aim.aimform.com", token });
const preflight = await aim.plan(spaceId, organizationId);
const { job } = await aim.start(spaceId, organizationId, { planId: String(preflight.planId) });
const status = await aim.job(job.jobId);
```

The adapter exposes configuration, measure/plan, durable start/status/pause/
resume, and report retrieval. Host applications own account authentication,
UI state, retries, and permission presentation.

`aimCodingStrategy()` keeps the existing coding phases, adds bounded semantic
context before discovery, and requires Aim reconciliation and semantic-diff
checks before completion. Aim is injected by the host and does not contain the
Aimform coding loop. The standard strategy remains the default when no Aim
workspace is attached.

When the host selects `coding-aim`, the workspace also exposes Aim’s native
model-facing tools. Call `aim_capabilities` to distinguish native registration
from source-workspace attachment; do not probe for an `aim` CLI or MCP server.
The durable tools include `aim_measure`, `aim_models_list`, `aim_index_plan`,
`aim_index_start`, step claim/request/commit and publication operations,
status/diagnostics/report operations, and `aim_ensure_counterpart`. Index
planning is a hard preflight: the plan reports
accepted files, physical LOC, SLOC, source tokens, context/call estimates,
pricing, planned cost, and feasibility; starting requires that plan’s ID.
Aim-mode hosts must ensure a counterpart before returning explicit source
inspection or mutation results to the model. The deterministic counterpart is
only the evidence-bearing shell; the model still authors the meaningful
semantic declarations and must validate them before publication.

The hosted tool catalog also exposes organisation Knowledge authoring: Agents
can inspect Journeys and private Skills, create an immutable Journey after an
explicit request, and synthesize a private Skill from an existing Journey and
learning evidence. Skill creation returns structural-test, conformance,
installation, and binding gates; hosts must not report success when a gate
fails.

At the Chat UI boundary, these strategy families are presented as execution
modes: `auto`, `research`, `coding`, and `coding-aim`. `auto` is resolved by
the Aimform host from the request shape; Research is the evidence-first
strategy, Coding is the standard coding lifecycle, and Coding + Aim selects
the Aim-backed coding variant. The mode is transport data, not an instruction
for Aim to run an agent loop.

The Research question-planning contract also exports `isLowLatencyRequest()`.
Hosts may use it for deterministic greetings and explicit echo/repeat requests:
these requests are classified as retrieval-free creative work and skip the
provider-backed decomposition call. Other prompts continue through normal
planning and evidence retrieval.

Hosts that create or switch conversations immediately before sending should
pass the selected `conversationId` through the client send options. The
identity stream handler uses that explicit id and only falls back to its
conversation getter for older integrations.

When conversation creation or intent detection is slow, `useChatSession`
provides `prepareSend()` and `sendPrepared()`. Preparation renders the user
turn and optional provisional acknowledgement immediately; complete the handle
after setup or call `cancelPreparedSend()` if setup fails. A
new-conversation host can pass `resetHistory: true` and activate the server
conversation with the prepared turns to keep the optimistic timeline
continuous. The visible acknowledgement is stable for the life of that send;
late intent results may refine metadata such as the title but must not rewrite
the acknowledgement under the user.

For a first turn with no selected conversation, pass a stable `idempotencyKey`
and `conversationCreate` metadata to the Identity run handler. It uses one
authorized create-and-send command and calls `onConversationCreated` when the
server has assigned the conversation. Repeating the same key replays the
original conversation and run identifiers without duplicating rows or model
work; existing-conversation sends continue to use the workflow endpoint.

## Chat performance telemetry

The client stream handler can report durable run timing through
`IdentityRunConfig.onPerformance`:

```ts
import type { ChatPerformanceEvent } from "@aimform/ai/client";

const onPerformance = (event: ChatPerformanceEvent) =>
  persistRunTelemetry(event.runId, event.metrics);
```

The event contains client-observed workflow request and acceptance latency,
physical realtime connection, acknowledged logical route readiness, time to
the first visible signal, first response character, first browser paint, first
plan step, completion channel, completion, and terminal status. It also
identifies the execution path (`deterministic`, `direct`, or `durable`) and
realtime mode (`shared` or `conversation`) so the admin panel can compare
cohorts without mixing fundamentally different flows. The client also exports `IntentTiming`, and
`useIntentDetection` exposes the latest intent duration so a host can pass it as
`clientTiming.intentMs`. Persistence is best-effort and must not block the
stream.
New-conversation hosts can also pass `clientTiming.conversationCreateMs` so the
admin performance view can distinguish conversation creation from workflow
request latency.

Conversation subscriptions can receive an optional `refreshUrl` factory. Use it
when the URL contains a short-lived stream ticket so an automatic reconnect
mints a fresh ticket and resumes after the last replay sequence already
applied.

## Deferred capabilities and extensions

The `@aimform/ai/agent` entry point exposes a compact `AgentCapabilityCatalog`
and `capabilitiesSearchTool()`. Catalog entries keep searchable descriptors in the
model projection and load full JSON schemas only after explicit activation;
eviction removes the schema without removing the descriptor. Search is
discovery only and never grants authorization.

The same entry point defines the AI-local instruction-oriented `AgentSkill`,
`AgentPreset`, `BehaviorPack`, `PluginManifest`, and `ProjectTrust` contracts.
Generic package manifests and runtime registrations belong to
`@aimform/packages`; executable platform Skill manifests and synthesis belong
to `@aimform/skills`. Hosts remain responsible for loading executable packages
and applying policy. `resolveProjectExtensions()` calls the canonical
`@aimform/deployments` manifest reader and recognizes `.aim/` as the canonical
control source, with visible `aim/` retained as a compatibility fallback.
`aimModeStrategy` is a separate, optional mode; generic coding does not require
Aim.

`CapabilityCatalog`, `Skill`, `SkillManifest`, `ResolvedSkill`, and
`createCapabilityCatalog()` remain deprecated compatibility aliases for the
renamed AI-local contracts.

`createExtensionRegistry()` stores declarative skills, presets, behavior packs,
and plugin manifests. `canActivatePlugin()` applies the project trust level and
allow-list; it does not load or execute plugin code.
- **Knowledge** — durable learned facts, evidence, ontology, and episodic knowledge.
- **Relationships** — why an Agent is connected to users, organisations, entities, repositories, tasks, or any other resource.
- **Context** — the bounded projection selected for the current inference.
- **Policy** — what is authorized to enter context or be acted on.

All are optional interfaces:

```ts
const agent = new Agent({
  id: "reviewer",
  model,
  tools,
  session: sessionStore,
  continuity: continuityStore,
  workingMemory,
  knowledge,
  relationships,
  contextResolver,
  policy,
  hooks,
});
```

The default context resolver recalls Knowledge and direct Agent Relationships, then filters resource-backed context through the configured Policy before it enters the model request.

Server-side runs use `ContextLifecycleManager` as the bounded model projection
boundary. It keeps Session history exact while applying context, tool-schema,
and tool-result budgets; recording observation artifacts; pruning and
micro/reactively compacting history; rebuilding from semantic checkpoints;
reporting provenance; limiting read-only prefetch; and exposing a stable
provider cache-prefix descriptor. It is integrated into `ChatRunEngine` and
passes the descriptor as an optional provider cache-prefix hint, and does not
create a second model loop.

## Behavioral policy

The Agent SDK provides hard behavioral controls through `behavioralPolicy` and
per-run `mode`. Tool definitions may declare `access: "read"` or
`access: "write"`; read mode (the default) does not expose or execute write
tools. Delegation supports `continue`, `fork`, and `fresh` session semantics.
Independent review is enabled by default for hosts that use the policy, and
`decideFailure()` can produce a bounded de-anchored handoff rather than
replaying a failed plan.

```ts
const agent = new Agent({
  model,
  behavioralPolicy: { mode: "write", delegation: "fork" },
  tools: [
    { name: "readFile", access: "read", description: "Read a file", input, execute },
    { name: "writeFile", access: "write", description: "Write a file", input, execute },
  ],
});
```

## Durable runtimes

The core contract is deliberately tiny:

```ts
interface AgentRuntime {
  step<T>(
    label: string,
    options: AgentStepOptions,
    execute: () => Promise<T>,
  ): Promise<T>;
}
```

`DirectRuntime` runs steps immediately. Durable hosts can implement the same contract with Cloudflare Workflows, Temporal, Inngest, or another execution engine. The existing `@aimform/compute` workflow runtimes are structurally compatible with this contract.

For durable hosts that need one model/tool round per invocation, provide
`onPendingToolEffects` in the execution configuration. The callback receives
serializable effects after the assistant tool-call boundary is written to the
session log; the invocation raises `AgentPendingEffectsError`. Successful
results expose `continuation: "continue" | "completed"`. The host owns waiting
for effects and resumes the same session with the resulting tool messages.

## Entry points

| Entry | Import | Purpose |
|---|---|---|
| Core | `@aimform/ai` | Standalone Agent, models, tools, runtime/session/context contracts, shared protocol types |
| Agent | `@aimform/ai/agent` | Agent-only public surface |
| Server | `@aimform/ai/server` | Lower-level engines, provider registry, memory implementations, transports, plugins |
| Client | `@aimform/ai/client` | React Chat UI, store, streaming hooks and display utilities |
| Shared | `@aimform/ai/shared` | Wire events, message/tool types and protocols |

## Existing Aimform Chat

The React application continues to import UI from `@aimform/ai/client`, and the current production workflow/event contract is unchanged by the standalone Agent facade. The facade wraps the proven `ChatRunEngine`; it does not introduce a second agentic round loop.

## Aim semantic provider

`AimSemanticAdapter` and `AimSemanticHttpAdapter` are exported from
`@aimform/ai/server`. They own the provider-neutral transport boundary for
Aim's semantic workspace; hosts inject the trusted base URL and authorization
headers at service composition time.

## License

MIT © Universal Reason LLC

## Guarded provider execution

Pass a request-scoped binding when composing model providers:

```ts
const registry = new ProviderRegistry({ env, guard: aiGuard });
const model = registry.getAdapter("deepseek-chat", organizationId);
```

The registry wraps model completion, streaming, and model discovery calls with
Guard admission and usage measurement. Expensive model turns use direct
reservation so token and concurrency ceilings apply before provider execution.
