Skip to content

About

a mirror of pi agent

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

32 Commits

Folders and files

Repository files navigation

my-harness

A minimal harness agent built from scratch, for learning how agent runtimes work.

This is not a copy of pi-agent. It's a stripped-down re-implementation designed to make the core loop legible. The full pi-agent harness is ~80k LOC; this project targets ~3000 LOC and stops there.

What is a "harness"?

A harness is the runtime around an LLM: it owns the message history, calls the model, streams responses, executes tool calls, persists state, and recovers from errors. Claude Code, Cursor CLI, Aider, and Continue all have one. The shape:

user message
   |
   v
[transform + convert] ---> [LLM API] ---> [stream events]
   ^                                            |
   |                                            v
   |                                     [text / tool calls]
   |                                            |
   +--- (after tool result) <---- [execute tool(s)]
   |
   v
[maybe compact, maybe inject queue, repeat]

Status

All planned features complete. 63 unit tests + 3 end-to-end DeepSeek tests passing. Typecheck clean.

Stage Description Commits
1 Minimal bash-only skeleton, Anthropic + DeepSeek providers 13
2 read/write/edit tools, JsonlSession persistence, before/after tool hooks 3
3 Compaction (prepareCompaction + auto-firing in loop) 1
4 Steer/followUp queues, Provider registry, richer streaming UI 3
5 Retry policy, tool timeouts 1
post withRetry stream-consumption bug fix; UI shows real tool args 1
post REPL mode for interactive multi-turn CLI 1

Quick start

Single-shot

cd my-harness
npm install --ignore-scripts
export $(grep -v '^#' .env | xargs)   # load DEEPSEEK_API_KEY=sk-... from .env

# DeepSeek (default for this user's .env)
npm run dev -- --provider deepseek --model deepseek-chat "list files in the current directory"

# Anthropic
ANTHROPIC_API_KEY=... npm run dev -- --model claude-sonnet-4-5 "list files"

REPL (multi-turn interactive)

The REPL reads prompts from stdin, one per line. There are four ways to feed it input.

1. Interactive typing (TTY)

Just run --repl and type. Each non-empty line is a turn:

export $(grep -v '^#' .env | xargs)
npm run dev -- --provider deepseek --model deepseek-chat --repl --session ./s.jsonl
my-harness REPL — provider=deepseek model=deepseek-chat. Ctrl-D to exit, empty line to send.
> 读 package.json 告诉我依赖
● read({"path":"package.json"})
  ▷ running read
  ◀ done
{"dependencies": {...}, ...}
> 把 devDependencies 列出来
● read({"path":"package.json"})
  ▷ running read
  ◀ done
- vitest@^2.1.0
- tsx@^4.19.0
- typescript@^5.6.0
> ^D
[bye]

Keys:

  • Enter — send the line as a turn
  • Empty line — skipped
  • Ctrl-D or /exit — end the session
  • Ctrl-C — abort the current turn (the REPL itself stays alive)

2. Pipe a string (printf)

printf 'read package.json\nexit\n' | npm run dev -- --provider deepseek --repl

The trailing \nexit\n sends two turns and ends. Drop \nexit to keep the REPL open waiting for more stdin (but the pipe will close and the REPL will exit on EOF).

3. Heredoc

npm run dev -- --provider deepseek --repl --session ./s.jsonl <<'EOF'
create /tmp/notes.md with a hello world message
add a JSDoc comment to the function in /tmp/notes.md
list the files in /tmp
/exit
EOF

The <<'EOF' (with quotes) prevents the shell from expanding variables in your prompt.

4. From a file

cat prompts.txt | npm run dev -- --provider deepseek --repl --session ./s.jsonl

Where prompts.txt is one prompt per line. Last line should be /exit or just leave the file with a trailing newline (EOF closes the REPL).

5. Initial prompt + REPL

You can pass a positional prompt before --repl; it runs as the first turn, then stdin takes over:

echo 'remember the secret is 42' | npm run dev -- --provider deepseek --repl --session ./s.jsonl "你好,"

The output 你好, runs first, then the pipe contents run as subsequent turns.

REPL behavior in summary

  • State lives in memory across turns (fast turn-to-turn — no model reconnect)
  • --session adds JSONL persistence on top
  • Output goes to stdout (agent text + tool events)
  • Prompts and [my-harness REPL ...] log line go to stderr (so the REPL log doesn't pollute piped output)
stderr: log lines, the "[my-harness REPL ...]" banner
stdout: agent responses, tool call/exec lines, "[done ...]" summary

CLI flags

Flag Alias Description
--provider <name> -p Provider: anthropic | deepseek | openai-compatible. Default: anthropic
--model <id> -m Model id. Falls back to provider's default
--session <path> -s JSONL session file. Persists messages on every turn
--repl -i Interactive mode: read prompts from stdin
<prompt> — Single-shot prompt (positional, required unless --repl)

How to use as a library

import { runAgentLoop } from "./src/loop.ts";
import { convertToLlm } from "./src/convert.ts";
import { getProvider } from "./src/providers.ts";
import { withRetry, DEFAULT_RETRY_POLICY } from "./src/retry.ts";
import { createBuiltinTools } from "./src/tools.ts";
import { InMemorySession } from "./src/session.ts";

const provider = getProvider("anthropic");
const model = provider.model("claude-sonnet-4-5");
const streamFn = withRetry(provider.streamFn(process.env.ANTHROPIC_API_KEY!), DEFAULT_RETRY_POLICY);

const newMessages = await runAgentLoop({
	config: {
		model,
		convertToLlm,
		streamFn,
		// optional: beforeToolCall, afterToolCall, getSteeringMessages,
		// getFollowUpMessages, compactionSettings
	},
	context: {
		systemPrompt: "You are a helpful assistant.",
		messages: [{ role: "user", content: [{ type: "text", text: "hi" }], timestamp: Date.now() }],
		tools: createBuiltinTools(),
	},
	listener: (ev) => console.log(ev.type),
});

Architecture

src/
  types.ts          — AgentMessage, AgentTool, AgentLoopConfig, AgentEvent, StreamFn
  convert.ts        — convertToLlm: AgentMessage[] -> Message[]
  session.ts        — InMemorySession
  jsonl-session.ts  — JsonlSession (append-only, same surface)
  tools.ts          — bash, read, write, edit
  stream.ts         — Anthropic streamFn
  openai-stream.ts  — OpenAI-compatible streamFn (DeepSeek uses baseURL swap)
  providers.ts      — Provider registry (anthropic, deepseek, openai-compatible)
  retry.ts          — withRetry wrapper (exponential backoff, stream-buffering)
  signal.ts         — withTimeout, anySignal
  compaction.ts     — shouldCompact, findCutPoint, prepareCompaction, compact
  loop.ts           — runAgentLoop (single-while + stage 3/4 hooks)
  main.ts           — CLI (single-shot + REPL)
Concern File Lines (approx)
Type contracts types.ts 290
Loop / state machine loop.ts 350
Tooling tools.ts 290
Provider registry providers.ts 100
Stream (Anthropic) stream.ts 360
Stream (OpenAI-compatible) openai-stream.ts 380
Compaction compaction.ts 440
Retry retry.ts 110
Signal signal.ts 50
CLI main.ts 200

End-to-end test results (DeepSeek)

After stage 5, three end-to-end tests were run with DeepSeek Chat (--provider deepseek --model deepseek-chat). All three passed.

Test Task DeepSeek did Verified
1. Generate code "Write merge_sorted_lists(a, b) in Python and run on [1,3,5]+[2,4,6]" Wrote merge_sorted.py with two-pointer merge, ran it, reported [1, 2, 3, 4, 5, 6] python3 merge_sorted.py → [1, 2, 3, 4, 5, 6] ✓
2. Write file "Create /tmp/reverse_string.js with reverse(s) and export it" Wrote file with module.exports = { reverse } node -e "require(...).reverse('hello')" → 'olleh' ✓
3. Multi-step "Read /tmp/reverse_string.js, add JSDoc, run reverse('hello world')" read → edit → bash → reported 'dlrow olleh' JSDoc valid; 'dlrow olleh' ✓

REPL test: piped 2 commands (create /tmp/greeter.js + add JSDoc), state preserved across turns, session JSONL has 8 lines, file runs and returns 'Hello, World!'.

A bug surfaced during testing: withRetry was consuming the inner stream to detect errors but returning the same consumed stream. Fix: drain events into a buffer during the attempt, then return a fresh stream that re-yields the buffered events.

What we kept vs. what we cut

Kept (and why)

  • The agent loop with hooks — runAgentLoop is the irreducible core. The Agent class in pi-agent is a 1700-line wrapper; we keep hooks as callbacks in AgentLoopConfig.
  • Tree-of-entries for sessions — Stage 2 minimum is a flat list, but the JSONL format is forward-compatible (each line is self-describing).
  • Stream + provider split — StreamFn is the abstraction; providers compose it with model metadata and key management. Adding a new backend is a one-line registerProvider(...).
  • Compaction — prepareCompaction is the same algorithm as pi-agent: estimate tokens, walk back to the recent tail, cut at a user/assistant boundary, summarize via the LLM, support split-turn.
  • REPL mode — main.ts supports interactive stdin; works with --session.

Cut (and why)

  • The Agent class — wrappers around the loop with queues, abort, idle. We pass the same data via AgentLoopConfig callbacks; the consumer holds its own queue. ~1700 lines saved.
  • Session tree (parentId, branch summaries) — flat list suffices. JSONL can be extended later.
  • Extension system — not needed at this size. Hooks via AgentLoopConfig cover the use cases.
  • TUI / interactive mode beyond basic REPL — out of scope. The CLI's REPL is line-based.
  • Project trust / multi-project — depends on UX.
  • Concurrent tool execution — sequential only.

Known limitations

  • Sequential tool execution only. Each turn's tool calls run one after the other. Pi-agent supports parallel execution; we don't.
  • No image content. Image blocks pass through as empty.
  • No request retries on individual tool calls. Retry wraps the stream (LLM call), not the tool call.
  • Compaction heuristic is character/4. No real tokenizer. Off for multi-byte content.
  • No prompt caching accounting. Providers return cache stats; the loop reads them but doesn't optimize for them.
  • Single-process. No distributed run, no shared session.
  • REPL is line-based, no multi-line input. Pipes work but newlines inside a prompt are treated as a new turn.

Verification

npm test           # 63 unit tests
npm run typecheck  # tsc --noEmit, no errors

End-to-end verification (requires an API key) is in the Quick Start above.

License

Same as pi-agent (the project this was modeled from).

About

a mirror of pi agent

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages