Skip to content

Latest commit

 

History

History
379 lines (287 loc) · 15.4 KB

sdk.md

File metadata and controls

379 lines (287 loc) · 15.4 KB

SDK Reference

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.

Install

npm install @bradygaster/squad-sdk

The 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

Configuration

defineConfig(config): SquadConfig

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, and plugins: optional team capabilities.

loadConfig(squadPath) and loadConfigSync(squadPath)

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.

SDK-First Builders

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.

Model Selection

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.5

Automatic 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 policy

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

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.

Client and Sessions

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.

Coordinator

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.

Tools and Hooks

Custom tools

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.

Hook pipeline

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.

Casting and Roles

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.

Telemetry and Streaming

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.

Client host adapters

@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).

  • HostProjection is a pure workspace projection (project(ctx)) for copilot, claude, kiro, opencode, cursor, codex, and antigravity. Get one with getHostProjection(id); apply with installClients(ids, ctx) or remove with uninstallClients(ids, ctx).
  • createClientAdapter({ host, ctx, runtime? }) returns the spec-level ClientAdapter facade: describe(), projectWorkspace() and getCapabilities() work locally; submit, subscribe, cancel and respondApproval delegate to a bound RuntimeBinding and otherwise throw AdapterUnboundError.
  • Capabilities are canonical string tokens (CAPABILITY_TOKENS_BY_HOST); the boolean ClientCapabilities flags are a derived view, and passing conflicting flags throws. Advertised capabilities stay separate from negotiated effectiveCapabilities (client ∩ backend ∩ policy).
  • JSON and TOML config merges only touch Squad's own keys; normalizeClientIds() / assertPortableClients() keep clients[] free of credentials and paths.

Experimental backend and harness SPI (@bradygaster/squad-sdk/backend)

Experimental Preview — Bring Your Own Server: @bradygaster/squad-sdk/backend is an experimental extension contract (BACKEND_CONTRACT_STAGE = 'experimental'). Squad ships the SquadBackend / HarnessAdapter interfaces, the local file/state-store backend, and the outbound durable-http client — it does not bundle a remote DurableSquad server, and server-side DurableSquad Phase 2 integration (remote durable approvals and lease-epoch coordination) is pending. Use durable-http when connecting to your own external or managed /v1/conversations server.

  • createSquadBackend(options) builds a SquadBackend for kind: 'local', kind: 'mcp', or kind: 'durable-http'. SDK callers using kind: 'durable-http' (or new DurableHttpSquadBackend(options)) must explicitly pass an https:// baseUrl (plain http:// is allowed only for localhost / 127.0.0.1 / ::1) and, when needed, an optional bearer token; redirects are never followed. Neither createSquadBackend nor DurableHttpSquadBackend reads SQUAD_BACKEND_URL or SQUAD_BACKEND_TOKEN from the environment — automatic environment-variable lookup applies only to the CLI's squad state-mcp bridge (createMcpBackend()) when the experimental backend tools are enabled.
  • SquadBackend exposes negotiate, createConversation, sendMessage, getTranscript, getTurn, readEvents, getApprovals, respondApproval, cancelTurn, cancelRun, and health.
  • HarnessAdapter and DefaultHarnessRegistry let custom execution runtimes plug into the broker (submit, subscribe, cancel, respondApproval, describe), with validateExtensions() enforcing x-<harness>.* extension namespaces.
  • In squad state-mcp, the 11 squad_backend_* MCP conversation tools are opt-in via --experimental-backend or SQUAD_EXPERIMENTAL_BACKEND=1. SQUAD_BACKEND_URL alone does not enable them. The bridge ships no execution harness: squad_backend_health / squad_backend_negotiate report executionAvailable: false, and squad_backend_send_message refuses instead of queueing (unavailable when no harness is registered; auto-selects a single registered in-process harness when harness is omitted, or refuses with invalid-request when multiple harnesses are registered), so over MCP the bundled backend is a transcript and event-log surface.

Other Public Modules

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.

See Also