# packages/agent

`@earendil-works/pi-agent-core` provides the stateful agent loop and a publicly exported optional harness for compaction, sessions, skills, prompts, and execution environments.

## STRUCTURE

```text
src/agent.ts                 Agent state, prompt queue, subscriptions, abort
src/agent-loop.ts            Provider/tool loop, scheduling, cursor-exec bridging
src/assistant-terminal-state.ts  Terminal-state classification for assistant turns
src/empty-assistant-recovery.ts  Recovery for empty assistant responses
src/stream-fn.ts             Injectable stream function abstraction
src/types.ts                 App messages, events, state, conversion boundary
src/proxy.ts                 Remote stream proxy
src/index.ts                 Browser-safe public exports
src/node.ts                  Node harness public exports
src/search/                  Scanning session search over readable storage
src/harness/                 AgentHarness: lanes, sessions (own AGENTS.md),
                             tools (own AGENTS.md), compaction, skills, prompt
                             templates, env adapters
src/harness/reducer.ts       Record-log validation and lane state reduction
src/harness/telemetry.ts     Schema-first AI/harness telemetry spans
src/harness/messages.ts      Harness message helpers
src/harness/prompt-templates.ts  Prompt template expansion
src/harness/system-prompt.ts System prompt assembly
src/harness/skills.ts        Skill discovery and loading
src/changes.md               Fork-specific behavior record
scripts/generate-telemetry-docs.ts  Regenerates docs/telemetry-schema.md
```

## WHERE TO LOOK

| Task | File |
|---|---|
| Tool scheduling or terminal states | `src/agent-loop.ts` |
| Agent lifecycle or abort | `src/agent.ts` |
| Public message/event contract | `src/types.ts` |
| Harness orchestration | `src/harness/agent-harness.ts` |
| Node process and filesystem behavior | `src/harness/env/nodejs.ts` |
| Session persistence | `src/harness/session/` (`session.ts`, `state.ts`, `context.ts`, `types.ts`, `jsonl/`, `memory.ts`; own AGENTS.md) |
| Session search | `src/search/scanning.ts`, contracts in `src/search/index.ts`; see `docs/search.md` |
| Built-in tool behavior | `src/harness/tools/` (own AGENTS.md) |
| SQLite session storage | `packages/session-backends/sqlite-node` (`@earendil-works/pi-storage-sqlite-node`) |
| Compaction | `src/harness/compaction/` |

## INVARIANTS

- Keep `AgentMessage` as app state and convert to the AI package `Message` only through `convertToLlm`.
- Core files `agent.ts`, `agent-loop.ts`, and `types.ts` remain browser-safe; Node filesystem/process behavior belongs behind `src/node.ts` and `src/harness/env/`.
- Tool preparation/finalization may complete concurrently, but returned `toolResults` remain in assistant source order.
- The active run owns idle-timeout and abort cleanup. Abort produces terminal behavior once; do not emit or settle a run twice.
- Subscribers receive events; messages remain state. Preserve discriminated streaming event shapes.
- Keep harness interfaces injectable so tests can use memory storage and fake execution environments.

## ANTI-PATTERNS

- Sequentializing independent tool calls.
- Importing Node-only modules into browser-safe entry points.
- Storing provider-shaped messages directly as app state.
- Adding harness behavior without exporting and documenting the matching public surface.

## VALIDATION

- Run `npm test` from this package for agent-loop coverage.
- Run `npm run test:harness` for harness/session/env changes.
- Telemetry schema changes: `npm run generate-telemetry-docs` to rewrite `docs/telemetry-schema.md`, then `npm run check:telemetry-docs`; the generated file must never be edited by hand.
- Runtime changes also require root `npm run check` and the root QA evidence gate.
- Keep `README.md`, `docs/harness.md`, `docs/search.md`, and `src/changes.md` aligned with public or fork-specific changes.

## NOTES

- Session storage: `SessionStorage` implementations (`jsonl/` `JsonlSessionStorage`/`JsonlSessionRepo`, `memory.ts` `InMemorySessionStorage`/`InMemorySessionRepo`) behind `Session` tree semantics in `session.ts`; SQLite backend in `packages/session-backends/sqlite-node`. New backends must pass `createSessionBackendConformance`, published as the `@earendil-works/pi-agent-core/session/testing` subpath.
- Cursor exec bridging: `execHandlers`/`onToolResult` are installed only when `config.cursorExecHandlers` is set. Assistant `toolCall` blocks stamped `kCursorExecResolved` (`packages/ai/src/utils/block-symbols.ts`) were executed server-side and are never re-run locally; their buffered `toolResult`s are appended right after the assistant message, including on error/abort paths. Local exec work re-arms the idle watchdog via `AssistantMessageEventStream.trackLocalWork`.

---
Generated: 2026-08-24 | Commit `baf15a54d`
