This is the curated quick reference for @bradygaster/squad-sdk. The SDK provides configuration builders, model selection, agent lifecycle APIs, routing, tools, storage, telemetry, and platform integrations.
For every public type and export, see the generated API reference.
npm install @bradygaster/squad-sdkThe package uses ESM and exposes a root entrypoint plus focused subpath entrypoints:
| Import path | Use for |
|---|---|
@bradygaster/squad-sdk |
Resolution, configuration, builders, models, roles, storage, telemetry, and shared types |
@bradygaster/squad-sdk/client |
SquadClient, SquadClientWithPool, SessionPool, client events, and multi-host HostProjection / ClientAdapter APIs (@bradygaster/squad-sdk/clients is a deprecated alias) |
@bradygaster/squad-sdk/backend |
Experimental SquadBackend (local, mcp, durable-http), HarnessAdapter, and capability/extension helpers |
@bradygaster/squad-sdk/coordinator |
SquadCoordinator, fan-out, and response-tier orchestration |
@bradygaster/squad-sdk/tools |
defineTool and ToolRegistry |
@bradygaster/squad-sdk/hooks |
HookPipeline and hook policy types |
@bradygaster/squad-sdk/config |
Configuration schema and model registry APIs |
@bradygaster/squad-sdk/casting |
Persona casting and casting history |
@bradygaster/squad-sdk/platform |
GitHub, Azure DevOps, and communication adapters |
@bradygaster/squad-sdk/state |
State collections and handles |
Create a typed configuration object with defaults and editor autocomplete.
import { defineConfig } from '@bradygaster/squad-sdk';
export default defineConfig({
version: '1.0.0',
team: {
name: 'Platform Squad',
projectContext: 'TypeScript monorepo with a REST API',
},
agents: [
{
name: 'backend',
role: 'Backend Engineer',
model: 'gpt-5.6-terra',
tools: ['route', 'memory', 'decision'],
},
],
routing: {
rules: [
{ pattern: 'api|backend', agents: ['backend'], tier: 'standard' },
],
fallbackBehavior: 'coordinator',
},
models: {
default: 'gpt-5.6-terra',
defaultTier: 'standard',
tiers: {
premium: ['gpt-5.6-sol', 'claude-opus-5'],
standard: ['gpt-5.6-terra', 'claude-sonnet-5'],
fast: ['gpt-5.6-luna', 'claude-haiku-4.5'],
},
},
});The configuration schema includes:
team: name, description, project context, and optional issue source.agents: named agents with roles, models, tools, status, reasoning effort, and context tier.routing: ordered rules, fallback behavior, and optional priorities.models: default model, default tier, tier lists, agent overrides, task mappings, and cost policy.hooks,ceremonies, andplugins: optional team capabilities.
Load and validate Squad configuration asynchronously or synchronously.
import { loadConfig } from '@bradygaster/squad-sdk';
const result = await loadConfig('./.squad');
console.log(result.config.models.defaultModel);Use result.errors and result.warnings when presenting validation results. The runtime loader uses defaultModel, defaultTier, and fallbackChains; defineConfig uses the public schema fields default, defaultTier, and tiers shown above.
Builders validate typed team definitions before they are written to .squad/ by squad build.
import {
defineAgent,
defineBudget,
defineDefaults,
defineRouting,
defineSquad,
defineTeam,
} from '@bradygaster/squad-sdk';
const squad = defineSquad({
version: '1.0.0',
team: defineTeam({
name: 'Platform Squad',
members: ['backend', 'tester'],
}),
agents: [
defineAgent({
name: 'backend',
role: 'Backend Engineer',
model: 'gpt-5.6-terra',
budget: defineBudget({ perSession: 100_000 }),
}),
defineAgent({ name: 'tester', role: 'Test Engineer' }),
],
defaults: defineDefaults({ model: 'gpt-5.6-luna' }),
routing: defineRouting({
rules: [{ pattern: 'test-*', agents: ['tester'], tier: 'standard' }],
fallback: 'coordinator',
}),
});Available builders are defineTeam, defineAgent, defineBudget, defineDefaults, defineRouting, defineCeremony, defineHooks, defineCasting, defineTelemetry, defineSkill, and defineSquad.
MODELS is the runtime source of truth for defaults and fallback chains.
import { MODELS } from '@bradygaster/squad-sdk';
MODELS.DEFAULT; // gpt-5.6-terra, env-overridable
MODELS.SELECTOR_DEFAULT; // gpt-5.6-luna
MODELS.SELECTOR_DEFAULT_TIER; // fast
MODELS.FALLBACK_CHAINS.premium; // starts with gpt-5.6-sol
MODELS.FALLBACK_CHAINS.standard; // starts with gpt-5.6-terra
MODELS.FALLBACK_CHAINS.fast; // starts with gpt-5.6-luna
MODELS.NUCLEAR_FALLBACK; // claude-haiku-4.5Automatic task-aware selection uses Terra for code and prompt architecture, Luna for docs, planning, triage, and other non-code work, and Sol for visual or design work. Persistent model preferences and per-agent overrides take precedence over automatic selection.
The default model can be changed with SQUAD_DEFAULT_MODEL. The fallback chains are tier-preserving; a failed fast or standard selection does not upgrade to premium.
Cost ceilings are separate from quality tiers. Use maxCategory with lightweight, versatile, or powerful when automatic selection must stay within a billing category.
import { defineConfig } from '@bradygaster/squad-sdk';
export default defineConfig({
models: {
costPolicy: { maxCategory: 'versatile' },
},
});Resolution helpers locate project, global, and shared Squad state.
import {
ensureSquadPath,
resolveSquad,
scratchDir,
} from '@bradygaster/squad-sdk';
const projectSquad = resolveSquad();
const ensured = ensureSquadPath();
const scratch = scratchDir();The root package also exports project-key helpers, preset/state resolution, directory config loading, and cache management. See the generated API reference for signatures.
Import client APIs from the client subpath.
import { SquadClientWithPool } from '@bradygaster/squad-sdk/client';
const squad = new SquadClientWithPool({
pool: { maxConcurrent: 5 },
});
await squad.connect();
const session = await squad.createSession({
model: 'gpt-5.6-terra',
});
const response = await session.sendMessage('Implement the /users endpoint');
console.log(response);
await squad.shutdown();Use SquadClient when you need connection management without the integrated session pool. SquadClientWithPool adds capacity limits, session lifecycle management, and an eventBus for session and pool events.
Import the coordinator from its subpath. It accepts a validated SquadConfig and handles direct responses, route matching, and optional fan-out.
import { defineConfig } from '@bradygaster/squad-sdk';
import { SquadCoordinator } from '@bradygaster/squad-sdk/coordinator';
const config = defineConfig({
team: { name: 'Platform Squad' },
agents: [{ name: 'backend', role: 'Backend Engineer' }],
routing: {
rules: [{ pattern: 'api', agents: ['backend'], tier: 'standard' }],
},
});
const coordinator = new SquadCoordinator({ config });
const result = await coordinator.handleMessage('Fix the API timeout', {
sessionId: 'example-session',
config,
});The coordinator subpath also exports spawnParallel, DirectResponseHandler, spawn backend helpers, selectResponseTier, and getTier.
import { defineTool, ToolRegistry } from '@bradygaster/squad-sdk/tools';
const searchTool = defineTool<{ query: string }>({
name: 'search_docs',
description: 'Search project documentation',
parameters: {
type: 'object',
properties: { query: { type: 'string' } },
required: ['query'],
},
handler: async (args) => ({
textResultForLlm: `Search requested for ${args.query}`,
resultType: 'success',
}),
});
const registry = new ToolRegistry('./.squad');
registry.getTools();
registry.getTool('squad_route');The built-in tools are squad_route, squad_decide, squad_memory, squad_status, and squad_skill. squad_route requires fan-out dependencies to create sessions and validates agent names before spawning.
import { HookPipeline } from '@bradygaster/squad-sdk/hooks';
const hooks = new HookPipeline();
hooks.addPreToolHook(async (context) => ({
action: context.toolName === 'shell' ? 'block' : 'allow',
reason: context.toolName === 'shell' ? 'Shell access is disabled' : undefined,
}));Hook actions are allow, block, and modify. The hook package also exports pre-tool, post-tool, session, error, and policy types.
import { CastingEngine } from '@bradygaster/squad-sdk';
const engine = new CastingEngine({
universes: ['The Wire'],
activeUniverse: 'The Wire',
});
const members = await engine.castTeam([
{ role: 'lead', title: 'Lead Developer' },
{ role: 'backend', title: 'Backend Engineer' },
]);The root package exports the built-in role catalogs, CastingEngine, and CastingHistory.
import {
getMeter,
getTracer,
initSquadTelemetry,
initializeOTel,
shutdownOTel,
} from '@bradygaster/squad-sdk';
await initializeOTel({
endpoint: 'http://localhost:4318',
serviceName: 'my-squad',
});
const tracer = getTracer('my-component');
const meter = getMeter('my-component');
const telemetry = await initSquadTelemetry({
endpoint: 'http://localhost:4318',
serviceName: 'my-squad',
});
await telemetry.shutdown();
await shutdownOTel();StreamingPipeline can also track the latest context-window occupancy for each attached session. Runtime context_usage events are exact; regular usage events provide an estimate when a model context-window resolver is configured.
import { RuntimeEventBus, StreamingPipeline } from '@bradygaster/squad-sdk';
const eventBus = new RuntimeEventBus();
const pipeline = new StreamingPipeline({
eventBus,
contextWarningThreshold: 0.8,
resolveContextWindow: model => model === 'gpt-5.4' ? 200_000 : undefined,
});
pipeline.onContextUtilization(snapshot => {
if (snapshot.thresholdCrossed) {
console.warn(`${snapshot.sessionId} context is ${(snapshot.utilization * 100).toFixed(1)}% full`);
}
});Every accepted sample is also emitted as a typed context:utilization event and recorded in the squad.context.utilization OpenTelemetry gauge. Exact runtime samples take precedence over later estimates for the same session.
The root package also exports cost tracking, offline mode, runtime events, OpenTelemetry metrics, and internationalization helpers.
@bradygaster/squad-sdk/client (and the deprecated alias @bradygaster/squad-sdk/clients) projects the host-agnostic Squad coordinator into the files each AI host loads natively across all 7 supported hosts (GitHub Copilot, Claude Code, Kiro, OpenCode, Cursor, OpenAI Codex, and Google Antigravity).
HostProjectionis a pure workspace projection (project(ctx)) forcopilot,claude,kiro,opencode,cursor,codex, andantigravity. Get one withgetHostProjection(id); apply withinstallClients(ids, ctx)or remove withuninstallClients(ids, ctx).createClientAdapter({ host, ctx, runtime? })returns the spec-levelClientAdapterfacade:describe(),projectWorkspace()andgetCapabilities()work locally;submit,subscribe,cancelandrespondApprovaldelegate to a boundRuntimeBindingand otherwise throwAdapterUnboundError.- Capabilities are canonical string tokens (
CAPABILITY_TOKENS_BY_HOST); the booleanClientCapabilitiesflags are a derived view, and passing conflicting flags throws. Advertised capabilities stay separate from negotiatedeffectiveCapabilities(client ∩ backend ∩ policy). - JSON and TOML config merges only touch Squad's own keys;
normalizeClientIds()/assertPortableClients()keepclients[]free of credentials and paths.
Experimental Preview — Bring Your Own Server:
@bradygaster/squad-sdk/backendis an experimental extension contract (BACKEND_CONTRACT_STAGE = 'experimental'). Squad ships theSquadBackend/HarnessAdapterinterfaces, the local file/state-store backend, and the outbounddurable-httpclient — it does not bundle a remote DurableSquad server, and server-side DurableSquad Phase 2 integration (remote durable approvals and lease-epoch coordination) is pending. Usedurable-httpwhen connecting to your own external or managed/v1/conversationsserver.
createSquadBackend(options)builds aSquadBackendforkind: 'local',kind: 'mcp', orkind: 'durable-http'. SDK callers usingkind: 'durable-http'(ornew DurableHttpSquadBackend(options)) must explicitly pass anhttps://baseUrl(plainhttp://is allowed only forlocalhost/127.0.0.1/::1) and, when needed, an optional bearertoken; redirects are never followed. NeithercreateSquadBackendnorDurableHttpSquadBackendreadsSQUAD_BACKEND_URLorSQUAD_BACKEND_TOKENfrom the environment — automatic environment-variable lookup applies only to the CLI'ssquad state-mcpbridge (createMcpBackend()) when the experimental backend tools are enabled.SquadBackendexposesnegotiate,createConversation,sendMessage,getTranscript,getTurn,readEvents,getApprovals,respondApproval,cancelTurn,cancelRun, andhealth.HarnessAdapterandDefaultHarnessRegistrylet custom execution runtimes plug into the broker (submit,subscribe,cancel,respondApproval,describe), withvalidateExtensions()enforcingx-<harness>.*extension namespaces.- In
squad state-mcp, the 11squad_backend_*MCP conversation tools are opt-in via--experimental-backendorSQUAD_EXPERIMENTAL_BACKEND=1.SQUAD_BACKEND_URLalone does not enable them. The bridge ships no execution harness:squad_backend_health/squad_backend_negotiatereportexecutionAvailable: false, andsquad_backend_send_messagerefuses instead of queueing (unavailablewhen no harness is registered; auto-selects a single registered in-process harness whenharnessis omitted, or refuses withinvalid-requestwhen multiple harnesses are registered), so over MCP the bundled backend is a transcript and event-log surface.
The root package exports or re-exports APIs for:
- Storage providers and in-memory state.
- Git-native state backends and state collections.
- Upstream inheritance and shared context.
- Marketplace packaging, extensions, and discovery.
- GitHub and Azure DevOps platform adapters.
- Ralph capabilities, triage, and rate limiting.
- Sharing, remote bridges, memory, skills, and presets.
Use the generated API reference for the complete list of current exports and signatures.
- Generated API reference - exhaustive TypeDoc output
- Configuration reference - file format and migration details
- Tools and hooks - focused orchestration examples
- SDK-First Mode - builder workflow and
squad build