Source snapshot bcc79fcc · Declared package version 17.2.5. This page combines the checked-in package guide and manifest; commands and runtime behavior were not executed in this review.
Core AI agent runtime for ContractSpec with tool orchestration, MCP integration, session state, memory, and telemetry.
The ./agent/runner and ./agent/task-tree entries own the existing synchronous task-tree execution and validation, including cancellation and failure propagation.
./agent/contracts and ./acp/contracts expose the existing explicit registry registration helpers using canonical AI Agent declarations. Agent and ACP command, event, feature and UI declarations preserve their original SchemaModel schemas, budgets and policies; readonly vocabulary remains in AgentProtocol. Registration is caller initiated; these entries grant no execution or approval authority.
The ./operations/agent/* leaves own the original agent lifecycle and tool assignment operation declarations, shared schemas, error contracts and idempotency requirements. They retain the existing policy and approval metadata; declaring an operation does not execute it or authorize a transition.
Protocol V1 agents require an exact qualified model route and a verified, provenance-aware compiled context. Legacy static or dynamic knowledge adapters and unclassified per-call system overrides are not admitted into Protocol V1 runs; retrieved material remains data-only context.
What It Provides
@lssm-tech/lib.ai-agent/chat owns the canonical headless ChatService,
InMemoryConversationStore, workspace context, and existing planner/workflow helpers. The chat module forwards to the same constructors and functions. This entry requires the existing surface runtime peer and preserves legacy behavior; it does not grant Protocol V1, provider, workflow or runtime authority. Named chat/<leaf> entries retain narrow imports for existing module forwarders; pure storage/context entries do not load chat providers or planner adapters.
Provides the central agent runtime used by chat, automation, and higher-level orchestration packages.
Supports tools, sessions, memory, approvals, providers, telemetry, and MCP-aware workflows.
Subagent-backed tools support additive dispatch grants for selected history, tool subsets, budgets/timeouts, replay/provenance refs, and fail-closed independent approvals.
Publishes canonical sandbox workspace, execution, secret-reference, and artifact contracts via @lssm-tech/lib.ai-agent/sandbox.
Acts as the stable public API for agent execution across multiple runtimes and delivery surfaces.
Consumes agent definitions from @lssm-tech/lib.contracts-spec/agent.
src/providers/ contains provider integrations and provider-facing adapters.
Installation
npm install @lssm-tech/lib.ai-agent
or
bun add @lssm-tech/lib.ai-agent
Usage
Define agents in @lssm-tech/lib.contracts-spec/agent, then run or export them with @lssm-tech/lib.ai-agent.
AgentSpec.runtime can declare checkpointing, suspend/resume, and approval-gateway capabilities.
AgentFactory and ContractSpecAgent accept optional runtime adapter bundles for LangGraph/LangChain-style integrations.
Session state now persists workflow, thread, trace, checkpoint, and approval metadata for replay-safe resumes.
Escalation policies can raise approval requests on timeout, tool failure, or confidence thresholds without coupling core contracts to a vendor runtime.
Protocol V1 agents fail admission when required static knowledge is missing, unsupported, empty, or unavailable. Retrieved knowledge is delimited as evidence with instructionEligible=false; it never becomes an instruction.
Protocol V1 agents require a qualified run-scoped model route. Static models and ranking-only selectors remain available to legacy agents, but cannot be used as a production fallback for protocol V1.
UnifiedAgent admits Protocol V1 only through its AI SDK backend with both a qualified run-scoped route and compiled context. Direct provider instances, raw provider configuration, ranking-only selectors, external SDK backends, and ambient backend fallback are rejected; fallback must be represented by a qualified model-route decision.
Production-shaped V2 calls receive a Host-verified resolver backed by the persisted selection and accepted fallback. The exact invocation profile sets output limits and sampling on the AI SDK call, resolves a digest-bound output validator, and rejects ambient/caller overrides. Streaming fails closed when a bound final-output validator cannot be applied.
Protocol step samples are reduced to an allowlisted, route-aware numeric/ref projection before any telemetry collector receives them. Custom collectors, composite collectors, and PostHog therefore cannot observe prompts, model text/reasoning, tool inputs/results, provider metadata, headers, bodies, raw errors, or direct tenant/actor identities.
compileAgentContextV1 deterministically hashes, classifies, bounds, and freezes context manifests. Missing, expired, substituted, or over-budget required sources fail admission; optional sources produce typed warnings.
AgentProtocolRuntimeV1 executes the ContractSpec Plan–Act–Reflect protocol through durable compare-and-swap state. It checkpoints every action and material transition, binds effects to Connect-approved Runtime Node work orders and receipts, suspends ambiguous outcomes for reconciliation, enforces bounded epochs and budgets, escalates repeated/no-progress failure, and accepts completion only with exact independent verifier evidence.
Help responses are accepted only through an injected authority verifier that binds the pending request, responder principal, authority decision, safe option, response evidence, expiry, and durable response digest. A response clears the wait state but never expands the plan, grants, tools, or budget.
Protocol V1 memory tools emit immutable proposals through a run-scoped port; they never receive a memory mutation port. governAgentMemoryProposalV1
accepts only exact PersonalOS/CompanyOS owner decisions and receipts. Legacy direct Anthropic memory CRUD remains compatible for non-Protocol-V1 agents.
Durable Plan–Act–Reflect
Import the portable kernel from @lssm-tech/lib.ai-agent/protocol-runtime and provide an AgentProtocolArtifactPortV1. The in-memory port is intended for tests; production hosts should use the Postgres implementation from
@lssm-tech/integration.agent-durable-store.
The artifact port also accepts immutable application_binding records. Agent Host uses them to bind a run to the exact installation, manifest, permission summary, release, configuration, and qualification admitted before execution; the AI runtime does not interpret them or grant application authority. Protocol run state may also bind the exact persisted model_selection artifact. Resume compares its reference and digest with the host-qualified selection and requires a replan when the route decision changes or disappears.
recordModelFallback admits an allowed fallback only at the current durable checkpoint, revalidates the original selection and every hard constraint, rejects indeterminate provider outcomes, persists the exact decision before a new checkpoint, and makes an identical retry idempotent. Resume also binds the last accepted fallback decision. V2 routing views discriminate wire versions and reject mixed artifacts.
recordModelReselectionV2 persists replacement plan, validation, and selection as inactive artifacts, then activates them in one run-state CAS while clearing fallback and applying safe replan resets. Qualification and canary heads remain append-only mutable artifacts with optimistic concurrency and historical reads.
The runtime never constructs credentials, grants authority, or invokes a provider itself. Plans must already bind required context, budgets, Connect decisions, and Runtime Node work orders. Effect results are accepted only when their exact work order and receipt are present as evidence. Reflection accepts typed artifacts only and has no effect port, so it cannot execute work or widen authority. A crash between artifact writes is replay-safe: the state points to exact historical revisions, and an identical retry is idempotent while a different retry fails closed.
respondToHelp requires an AgentProtocolHelpResponseAuthorityPortV1 supplied by the host. Plain model output, channel text, or an unverified principal cannot resume a waiting run. The authorized response is persisted before the next bounded epoch can start.
Bounded epochs
@lssm-tech/lib.ai-agent/epochs runs a long-running task as a finite sequence of bounded epochs (runAgentBoundedEpochsV1) under an
agentBoundedEpochPolicyV1Schema policy. An epoch ends when the work is done, a token, wall-time or tool-call budget is exhausted, or the run is cancelled, and the runner then renews, completes or stops with a typed reason. Both boundaries are checkpointed, effects run through a write-ahead journal (context.effect) and replay after a restart, and the open epoch's token and tool-call spend is stored with the open epoch, together with the number of steps it counts and the number of steps that had reached a journaled effect (admittedSteps, written with each step's first journal entry).
A restarted process continues those counters instead of starting from zero. It runs the admitted steps again without a budget check or the wall-time abort (cancellation still applies), so each one replays its recorded effects, or stops the run as effect_indeterminate at its pending one, even when the budget ran out before the restart: a journaled step is never refused and sent again in a later epoch. Later steps, including unjournaled steps that run again, are checked against the restored counters. An epoch that ends on its budget or a cancellation while a journal entry is still pending stops as
effect_indeterminate instead of renewing, and the run result's stopDetail
names the effect.
Steps report their spend as before. A step whose effects all replay may report their recorded spend, and the runner counts it once; a restored step that also runs a new effect is counted in full, replayed part included. Spend made outside context.effect is not journaled, so an admitted step repeats it, unchecked, after a restart. Records written before that spend was stored stay readable and resume their open epoch from zero.
createAgentEpochCheckpointStoreV1 persists runs through any durable
AgentCheckpointPort. @lssm-tech/lib.ai-agent/agent/bounded-epoch-step
binds a generate loop to epoch steps; it does not journal tool calls, so a host that needs replay safety journals each generate call (Agent Host's
createAgentHostBoundedAgentRunnerV1 does).
Governed self-improvement
@lssm-tech/lib.ai-agent/improvement-loop provides a replay-safe improvement lifecycle: propose, evaluate, approve, canary, apply, observe, roll back, and expire. Policy is rechecked at every sensitive transition, effects are idempotent, approvals are scope-bound and expiring, kill switches are fail-closed, and scheduled sweeps recover due work without silently promoting it. This is controlled software change, not unconstrained prompt mutation.
The additive V2 runtime accepts sanitized operational signals and persists an explicit canary observation stage. A failed evaluation is rejected and can never reach canary or promotion. Policy approvals or a qualified auto-apply policy may run the canary only; production promotion requires a plan-bound, fully sampled healthy result and an explicit human approval (approving a held work order re-observes the canary, then promotes). Stale, incomplete, malformed, or degraded observations roll back or return to review according to the observation plan. V1 remains available for existing consumers. V2 proposal adapters may also return a validated PatchRunReceiptV1; the runtime binds it to the work order before evaluation so downstream staging workflows can verify the exact base, head, provider, checks, Connect decisions, risk verdict, and rollback reference.
Architecture
src/agent/, src/session/, and src/memory/ contain the runtime core for execution state and persistence hooks.
src/tools/, src.providers/, and src.interop/ connect providers, tools, and MCP-aware runtime surfaces.
src.telemetry/, src.approval/, src.knowledge/, and src.schema/ round out runtime policy and observability surfaces.
src/sandbox/ defines additive sandbox and artifact contracts for runtime adapters.
src/telemetry/economic-evidence.ts captures safe agent-run usage/cost refs without persisting prompts, messages, or tool payloads.
src/index.ts is the root public barrel and package entrypoint.
src/types.ts is shared public type definitions.
Public Entry Points
Large multi-subpath library exporting agent runtime, approval, memory, knowledge, providers, schema, telemetry, tools, and types.
Export . resolves through ./src/index.ts.
Export ./agent resolves through ./src/agent/index.ts.
Export ./agent/agent-factory resolves through ./src/agent/agent-factory.ts.
Export ./agent/contract-spec-agent resolves through ./src/agent/contract-spec-agent.ts.
Export ./agent/json-runner resolves through ./src/agent/json-runner.ts.
Export ./agent/unified-agent resolves through ./src/agent/unified-agent.ts.
Export ./approval resolves through ./src/approval/index.ts.
Export ./context resolves through ./src/context/index.ts.
Export ./context/compiler resolves through ./src/context/compiler.ts.
Export ./context/render resolves through ./src/context/render.ts.
Export ./improvement-loop resolves through
./src/improvement-loop/index.ts.
Export ./approval/workflow resolves through ./src/approval/workflow.ts.
Export ./protocol-runtime resolves through ./src/protocol-runtime/index.ts.
Export ./protocol-runtime/model-fallback-operation resolves through
./src/protocol-runtime/model-fallback-operation.ts.
Export ./tools/subagent-protocol resolves through
./src/tools/subagent-protocol.ts.
Export ./tools/subagent-protocol-result resolves through
./src/tools/subagent-protocol-result.ts.
Export ./exporters resolves through ./src/exporters/index.ts.
Export ./exporters/claude-agent-exporter resolves through ./src/exporters/claude-agent-exporter.ts.
Export ./exporters/export-artifacts resolves through
./src/exporters/export-artifacts.ts: agentExportArtifacts(spec, format)
maps a Claude or OpenCode export to relative file artifacts (CLAUDE.md;
agent.json + <key>.md) so CLI and IDE hosts only write them.
Export ./telemetry/economic-evidence resolves through ./src/telemetry/economic-evidence.ts.
Additional runtime subpaths are published through package.json; keep docs aligned with the manifest.
Economic Evidence
Agent runs now emit neutral @lssm-tech/lib.economic-evidence refs for token usage, provider receipts, model-cost estimates, budget decisions, lifecycle phases, and redaction decisions. Configure economicEvidence on ContractSpecAgent to attach provider/model/operation/budget context; generated run results and agent.step.completed events carry economicEvidenceRefs. UnifiedAgent forwards AI SDK provider context and creates external-provider run-completion refs. Budget policy blocks only explicit pre_execution gates; post-execution overages and pricing-unavailable paths remain reviewable evidence. Prompt text, messages, tool call arguments, and tool outputs remain redacted/reference-only.
Model qualification and canary heads
./protocol-runtime/model-route-lifecycle-v2 appends the next model qualification head (canonical digest, unchanged subject identity, only
simulated -> live_verified | revoked or live_verified -> revoked) and the next model canary head (verified with @lssm-tech/lib.agent-evalsverifyAgentModelCanaryStateV2, starting offline at revision 1 or extending the current history by one step), both under revision CAS on
AgentProtocolArtifactPortV1. This subpath is the only one that loads
@lssm-tech/lib.agent-evals; it is not re-exported from ./protocol-runtime.
Model route V2 admission
./protocol-runtime/model-route-admission-v2 is the single model routing V2 admission path for admission, resume and the V1 -> V2 upcast:
admitAgentModelRouteV2 validates the candidate artifacts and their canonical digests, the evaluation-decision and production-canary bindings, the selection binding against the plan and application model policy, and the run budget, then verifies the live connection projection and the exact Connect route decision through injected ports before persisting every model artifact idempotently (allowCreate: false requires them to exist). Supporting subpaths: ./protocol-runtime/model-route-artifacts-v2 (idempotent artifact persistence and identity checks), ./protocol-runtime/model-route-authority-v2
(the Connect route authority port) and
./protocol-runtime/model-connection-verification
(AgentModelConnectionPortV1 over a structural AgentModelConnectionRecordV1
that IntegrationConnection satisfies, with a secret-free allow-listed projection digest). These subpaths load @lssm-tech/lib.agent-evals.
Application qualification port
./protocol-runtime/application-qualification-port builds an
AgentApplicationQualificationPortV1 for one signed application:
createAgentApplicationQualificationPortV1 verifies the signature through an injected AgentApplicationSignatureVerifierV1 (hosts supply the Ed25519 trust-root check, so this entry stays runtime-neutral), binds the signature material to the manifest, permission summary, source digest, release SHA and signing time, and returns the digest-bound qualification record from
@lssm-tech/lib.agent-protocol-spec/protocol/application-qualification, or a
rejected record.
Governed automation runtime
./automation-runtime/claim, ./automation-runtime/transition and
./automation-runtime/complete run the automation run lifecycle over the durable AgentProtocolArtifactPortV1 and the
@lssm-tech/lib.agent-protocol-spec/protocol/automation validators: due-window and maxRuns checks, deterministic occurrence/run identity, injected claim, transition and follow-up authority, revision-CAS state commits with race re-reads, receipt-first idempotent completion and indeterminate-outcome reconciliation. ./automation-runtime/types declares the host-neutral ports (AgentAutomationRunAuthorityPortV1, and AgentAutomationAuthorityPortV1<TApplication>
for hosts that also materialize automations), ./automation-runtime/store the schema-checked automation artifact loaders and ./automation-runtime/helpers
the clock, identity and blocked-result helpers. Materialization from a host's installed application stays with that host. Blocked results keep their existing agent_host.automation_* codes.
Protocol V1 delegation
Protocol-enabled subagent registrations load immutable task-graph, context projection, delegation, parent-budget, and result artifacts through the same durable artifact port as Plan–Act–Reflect. Dispatch requires an injected authority verifier bound to the exact scope, principal, delegation, grants, tools, approval receipts, and expiry. The child receives only the canonical task and projected context; parent conversation history and ad-hoc model task text are not forwarded.
Completed, failed, cancelled, timed-out, and handoff wrapper states must match a durable AgentTaskResultV1 bound to the exact graph, delegation, producer, artifacts, evidence requirements, and completion criteria. Legacy subagent registrations remain compatible and do not silently become Protocol V1 proof.
Migration Note
@lssm-tech/lib.ai-agent no longer owns the agent-definition contract layer.
Removed: @lssm-tech/lib.ai-agent/spec
Removed: @lssm-tech/lib.ai-agent/spec/spec
Removed: @lssm-tech/lib.ai-agent/spec/registry
Use @lssm-tech/lib.contracts-spec/agent For AgentSpec, AgentToolConfig,
AgentRegistry, createAgentRegistry, and defineAgent
Local Commands
bun run dev — contractspec-bun-build dev
bun run build — contractspec-bun-build build
bun run test — bun test
bun run lint — bun lint:fix
bun run lint:check — biome check .
bun run lint:fix — biome check --write --unsafe --only=nursery/useSortedClasses . && biome check --write .
bun run typecheck — tsgo --noEmit
bun run publish:pkg — bun publish --tolerate-republish --ignore-scripts --verbose
bun run publish:pkg:canary — bun publish:pkg --tag canary
bun run clean — rimraf dist .turbo
bun run build:bundle — contractspec-bun-build transpile
bun run build:types — contractspec-bun-build types
bun run prebuild — contractspec-bun-build prebuild
Recent Updates
Missing dependencies (thanks to knip).
Replace eslint+prettier by biomejs to optimize speed.
Agentic workflows — subagents, memory tools, and next steps.
Vnext ai-native.
Backend operations + frontend rendering support.
Add latest models and align defaults.
Add first-class agent-run economic evidence capture for usage, cost estimates, provider receipts, and replay-safe redaction refs.
Add the approval-gated, canary-first, rollback-capable governed improvement loop.
Notes
High blast radius — used by multiple bundles and libs.
Agent definitions are owned by @lssm-tech/lib.agent-protocol-spec/agent/spec.
This package is runtime-focused: execution, exporters, MCP/tool bridges, sessions, memory, approvals, providers, and telemetry.
MCP transport adapters must stay runtime-agnostic (no Node/browser-specific globals).
The additive ./agent/registry entry owns the complete original AgentRegistry class and createAgentRegistry factory. Historical ContractSpec exports forward to this same class. Operation registry and handler-context public defaults use the complete RuntimeCore host specialization, preserving nominal telemetry, event registries and resolved host configuration types.
The canonical imports require the complete AgentProtocol model family, Jobs queue contract, orchestration workflow model and utility sanitizer owners. Their resulting-tree producer and consumer qualification remains pending; this Source candidate grants no provider execution or model-call authority.
The ./protocol-runtime/model-selection-validation-v2 and ./protocol-runtime/model-fallback-validation-v2 entries preserve the historical optional now API. They resolve the default clock only at the original guarded qualification-expiry branch, and retain fallback candidate order and short-circuiting. AgentProtocol owns the complete structural validation phases and its pure validation entrypoints require an explicit Date. Historical ContractSpec validation exports forward to these runtime wrappers.
Agentic interaction contracts
The agentic-interaction and agentic-interaction/contracts subpaths own the existing inbound-message safety query, capability and registration helpers. Wire shapes, deny-only controls and supplied registry identities are unchanged. Portable signal definitions live in AgentProtocol; the legacy ContractSpec subpaths forward to these canonical objects. These declarations grant no execution or approval authority.
Canonical compatibility leaves: ./operations/registry.agent. These leaves preserve the original implementations and object/class identity; legacy ContractSpec imports forward to these owners.
Declared capabilities.
Lib Ai Agent
AI agent orchestration with MCP and tool support
Use it to
Adopt ai agent orchestration with mcp and tool support
Requires
TypeScript
Choose another boundary when
The @lssm-tech/lib.ai-agent package constraints do not match the target runtime or platform.
These are package-manifest entry points. Named symbols listed above come from the capability catalogue; this is not an exhaustive TypeScript symbol reference.