Documentation
Bridge SDK
Context Injection

Context Injection

The NityContext interface lets you inject memory, previous episodes, and skill hints into prompts sent to Nity. This gives the sub-agent background on the task without re-explaining history.

The NityContext Interface

interface NityContext {
  episodes?: Array<{ id: string; summary: string; outcome: string }>;
  memory?: {
    goal?: string;
    discoveries?: string[];
    workingSet?: string[];
  };
  skillHints?: Array<{ name: string; successRate: number }>;
  metadata?: Record<string, string>;
}

Passing Context to a Task

import { createNitySession } from '@mariozechner/pi-coding-agent/extensions/nity/bridge';
 
const session = await createNitySession({ costTier: 'free' });
 
const result = await session.sendTask('execute', 'Fix the flaky test in auth.spec.ts', {
  episodes: [
    { id: 'ep-041', summary: 'Identified race condition in token refresh', outcome: 'Added mutex lock' },
    { id: 'ep-038', summary: 'Tested retry logic under load', outcome: 'Found timeout gap' },
  ],
  memory: {
    goal: 'Achieve 100% test pass rate on CI',
    discoveries: ['Token refresh races when two requests arrive within 5ms', 'Test DB teardown is not awaited'],
    workingSet: ['src/auth/refresh.ts', 'tests/auth.spec.ts'],
  },
  skillHints: [
    { name: 'test-debugging', successRate: 0.85 },
    { name: 'race-condition-fix', successRate: 0.72 },
  ],
  metadata: {
    branch: 'fix/flaky-auth-test',
    priority: 'high',
  },
});

How Context Is Formatted

The Bridge SDK formats context into a structured section appended to the prompt. Given the example above, Nity receives:

[Coder Mode — Focus on implementation, correctness, and code quality.]
Use the nity_execute tool to implement the following task.
Apply quality gates and self-reflection after execution.

Task: Fix the flaky test in auth.spec.ts

---
Context from previous work:
Relevant episodes:
  - [ep-041] Identified race condition in token refresh → Added mutex lock
  - [ep-038] Tested retry logic under load → Found timeout gap

Memory context:
  Goal: Achieve 100% test pass rate on CI
  Discoveries: Token refresh races when two requests arrive within 5ms; Test DB teardown is not awaited
  Working set: src/auth/refresh.ts, tests/auth.spec.ts

Applicable skills:
  - test-debugging (85% success)
  - race-condition-fix (72% success)

Additional context:
  branch: fix/flaky-auth-test
  priority: high

Each field maps to a labeled section. Empty or omitted fields are excluded.

Field Reference

episodes

Previous work episodes relevant to the current task. Each episode has:

FieldTypeDescription
idstringEpisode identifier (e.g., ep-041)
summarystringWhat was done
outcomestringWhat was found or decided

Use episodes to reference prior analysis, decisions, or investigation results that inform the current task.

memory

Current working memory / brain state:

FieldTypeDescription
goalstringThe high-level objective driving the work
discoveriesstring[]Key findings from previous exploration
workingSetstring[]Files or modules currently in focus

Use memory to persist state across task dispatches within a session.

skillHints

Skills or patterns from previous runs that may apply:

FieldTypeDescription
namestringSkill identifier
successRatenumberHistorical success rate (0–1)

Use skill hints to guide Nity toward proven approaches. Nity's nity_skills tool can also discover applicable skills, but pre-supplying hints skips that discovery step.

metadata

Arbitrary key-value pairs for additional context. Formatted as key: value lines. Use for branch names, priority levels, ticket IDs, or any domain-specific context.

Auto-Injection via contextProvider

Instead of passing context manually on every sendTask call, configure a contextProvider in the session config. The provider is called automatically when no explicit context is given:

import { createNitySession } from '@mariozechner/pi-coding-agent/extensions/nity/bridge';
 
const session = await createNitySession({
  costTier: 'hybrid',
  contextProvider: async () => {
    // Fetch context from your own systems
    const recentEpisodes = await fetchRecentEpisodes();
    const currentGoal = await loadCurrentGoal();
 
    return {
      episodes: recentEpisodes.map(ep => ({
        id: ep.id,
        summary: ep.summary,
        outcome: ep.outcome,
      })),
      memory: {
        goal: currentGoal,
        workingSet: getActiveFiles(),
      },
    };
  },
});
 
// Context is injected automatically — no need to pass it here
const result = await session.sendTask('analyze', 'Review the caching layer');

The contextProvider is only called when sendTask is invoked without an explicit context argument. If you pass context directly, the provider is skipped.

Provider Error Handling

If the contextProvider throws, the error is silently caught and the task proceeds without injected context. Provider failures are non-fatal.

When to Use Each Field

ScenarioRecommended Fields
Continuing work from a previous analysisepisodes, memory.goal
Debugging with prior findingsmemory.discoveries, episodes
Focusing on specific filesmemory.workingSet
Reusing proven approachesskillHints
Passing domain-specific contextmetadata
Long-running multi-task sessionscontextProvider for auto-injection
⚠️

Large context increases token usage. Use maxPromptTokens in the session config or optimizePrompt to enforce a token budget. The SDK estimates 1 token ≈ 4 characters for truncation.