Commit Graph
52 Commits
Author SHA1 Message Date
sausheong 1da0584530 perf(runtime): hoist tool-def filter/sort/normalize out of the turn loop (P3) 2026-06-13 09:57:39 +08:00
sausheong 7151562d99 perf(runtime): drop dead resultIDs map and mid-loop tool-result injection (P2) 2026-06-13 09:55:58 +08:00
sausheong 86ad622144 Merge branch 'reliability/round2': pre-first-token stream-error recovery (R1)
EventError delivered before the first token now runs the same reactive
compaction + fallback-model recovery as the synchronous ChatStream-error
path, via recoverFromPreTokenError (single-shot per turn). Fixes the
primary Anthropic/Gemini path where 429/overflow aborted the turn.
2026-06-13 01:52:25 +08:00
sausheong 7052a66e38 fix(runtime): recover from pre-first-token stream errors (compaction/fallback) — R1 2026-06-13 01:46:38 +08:00
sausheong de23ad986a Merge branch 'harden/safe-defaults': atomic file writes + 0600 perms
WriteFileAtomic helper; write_file/edit_file atomic + restrictive perms;
spill files 0600. Part of the cross-repo safe-by-default hardening.
2026-06-13 01:13:06 +08:00
sausheong 27fecf4588 feat(runtime): spill files 0600 via atomic write 2026-06-13 00:53:22 +08:00
sausheong 87f77c76ba feat(tools/file): edit_file atomic + preserve existing mode 2026-06-13 00:51:57 +08:00
sausheong 7ae944f0eb feat(tools/file): write_file atomic + 0600 2026-06-13 00:50:46 +08:00
sausheong c4750347e6 feat(tool): add WriteFileAtomic helper 2026-06-13 00:49:50 +08:00
sausheong 7fa3e75ad1 feat(llm): PromptCachingProvider capability — cache on renamed providers
providerSupportsCaching gated on the provider NAME being literally
'anthropic', so an Anthropic-shaped provider registered under a custom
config name (platformai, bedrock, any relay) never set
CacheLastMessage — every turn re-processed the full conversation
history uncached (~120K input tokens and 4-6s TTFT per turn on a
large session).

Add llm.PromptCachingProvider capability interface; AnthropicProvider
declares it; runtime gates providerSupportsCaching and
providerSupportsMidLoopCompaction on the capability first, with the
name check kept as legacy fallback for custom impls.
2026-06-11 22:02:37 +08:00
sausheong d5e8abf492 feat(runtime): surface and recover from model refusals
Claude Fable 5 safety classifiers decline requests with HTTP 200 +
stop_reason=refusal and empty content. The Anthropic stream parser
never read stop_reason, so a refused turn looked like a successful
empty response — the UI showed nothing and the agent appeared hung.

- llm: ChatEvent carries StopReason/StopCategory on EventDone;
  StopReasonRefusal constant
- anthropic: parse stop_reason + stop_details.category from
  message_delta (streaming) and the message (non-streaming); WARN log
  on refusal
- runtime Run + RunTurn: on refusal, retry the turn once on
  FallbackModel (refusals are model-specific; Opus-tier has no
  bio/cyber classifiers), discarding any partial output; without a
  fallback (or if the fallback also refuses) synthesize a visible
  'model declined this request' message with the policy category
  instead of silent emptiness
2026-06-10 21:13:48 +08:00
sausheong 3064a0da14 fix(tokens): 1M context window for Fable 5 / Mythos 5 / Opus 4.6+ / Sonnet 4.6
The blanket claude→200k rule predates the 1M-window generation. With
a 200k detected window, preventive compaction (threshold 0.6) fired
at ~120k tokens on models that actually hold 1M — 5x too early.

Match the 1M family explicitly (claude-fable, claude-mythos,
claude-opus-4-6/7/8/9, claude-sonnet-4-6) before the 200k fallback;
older Claude models (3.x, 4.0-4.5 era, Haiku 4.5) keep 200k.
2026-06-10 19:32:09 +08:00
sausheong cf47b2fca8 feat(mcp): expose session Ping on Client
Gateway supervisors need a cheap liveness probe to detect mid-flight
upstream death (crashed stdio child, restarted HTTP server). Client.Ping
forwards to the SDK session's MCP ping; a non-nil error means the
session is no longer usable.

Also moves examples/minimal's keep-import-live statement above the REPL
loop — it sat after an infinite for loop, tripping go vet's unreachable
code check.
2026-06-10 12:44:21 +08:00
sausheong 6f0040f606 fix(anthropic): adaptive thinking for Fable 5 / Mythos 5 / Opus 4.7+
These models reject the legacy thinking config — sending
{type:"enabled", budget_tokens:N} returns HTTP 400
("thinking.type.enabled is not supported for this model"), and
sampling params (temperature) are removed too.

For adaptive-only models (matched by substring so gateway model-group
names like claude-fable-5-global and Bedrock-style IDs are covered):
- emit thinking: {type:"adaptive"} plus output_config.effort
  (low/medium/high mapped from the unified ReasoningMode)
- omit thinking entirely when reasoning is off (Fable 5 also rejects
  an explicit {type:"disabled"})
- drop temperature

Pre-4.7 models keep the existing enabled+budget_tokens behavior.
2026-06-10 12:41:01 +08:00
sausheong 0341628068 Merge: wire KnowledgeGraph (recall+ingest) into RunTurn
RunTurn now consults r.KG — bounded-synchronous semantic recall folded into
the prompt on the first round of an exchange, async auto-ingest on the
completing round. Fixes the gap where the KG seam was inert on the runtime's
serve path (RunTurn never read r.KG). Interface + BuildRuntime unchanged.
2026-06-10 00:23:53 +08:00
sausheong 5d6326981e docs(runtime): update RunTurn contract — it now does KG recall/ingest 2026-06-09 23:58:21 +08:00
sausheong b7cbfc584c docs(runtime): note IngestSource/growth-gate rationale at RunTurn ingest 2026-06-09 23:42:58 +08:00
sausheong 8f8d75cd06 feat(runtime): KG ingest on RunTurn exchange completion 2026-06-09 23:39:26 +08:00
sausheong fe71e7b36d feat(runtime): bounded-synchronous KG recall in RunTurn 2026-06-09 23:34:44 +08:00
sausheong f35070594f test(runtime): strengthen sessionThread compaction-skip + undecodable coverage 2026-06-09 23:32:30 +08:00
sausheong 67178e018a feat(runtime): sessionThread helper for KG ingest in RunTurn 2026-06-09 23:28:16 +08:00
sausheong ecdf97ca79 Merge feat/run-turn-api: add RunTurn single-turn API 2026-06-08 01:04:42 +08:00
sausheong b7f4cfcf4a refactor(runtime): serial tool dispatch in RunTurn + error/abort tests
- Drop the wasted partitionToolCalls call; RunTurn dispatches serially by
  design (deterministic ordering for durable replay), so loop toolCalls directly.
- Fix doc-comment overclaim: RunTurn is headless and does not emit Run's
  trace/slog tool-result lines nor parallelize batches.
- Make TurnResult.Err consistent: mid-dispatch abort now passes ctx.Err().
- Document single-active-turn invariant on turnSlice.
- Add TestRunTurn_LLMError and TestRunTurn_PreCancelledContext.
2026-06-07 23:47:32 +08:00
sausheong 35896d215a feat(runtime): add single-turn RunTurn API
RunTurn executes exactly one turn of the agent loop against the current
session and returns the SessionEntries it produced, enabling external
platforms to drive the loop one turn at a time (e.g. for durable
per-turn checkpointing). Purely additive: Run() is unchanged.

RunTurn reuses the existing tested helpers (assembleMessages,
dispatchTool, partitionToolCalls) and deliberately omits compaction,
knowledge-graph, and streaming-tool kickoff, which remain in Run.
2026-06-07 23:40:07 +08:00
Chang Sau Sheong 1c6a05c0d8 Merge pull request #1 from sausheong/feat/configurable-tool-result-cap
feat(runtime): configurable per-tool-result truncation cap
2026-05-21 07:55:33 +08:00
sausheong e5c9b5dbb5 feat(runtime): configurable per-tool-result truncation cap
Adds LoopConfig.MaxToolResultLen with the same config > env > default precedence as the existing MaxToolConcurrency / MaxAgentDepth knobs:

  1. Runtime.AgentLoop.MaxToolResultLen (>0) — config wins
  2. HARNESS_MAX_TOOL_RESULT_LEN env (>0) — env fallback
  3. defaultMaxToolResultLen (4000) — unchanged for back-compat

The previous 4000-char cap was conservative for agents doing real engineering work (read_file, web_fetch, browser, bash output). Setting MaxToolResultLen to 16000-25000 lets a typical source file or test run land in-context without hitting spillover; spill remains the safety net for genuinely large outputs.

No behaviour change for callers that don't set the field.
2026-05-21 07:55:16 +08:00
sausheong 65021e1fe2 fix(file tools): resolve relative paths against WorkDir before workspace validation
When the agent supplies a relative path (e.g. "app.py"), filepath.Abs resolves
it against the process CWD, not the workspace — causing ValidatePathInWorkDir
to reject paths that are legitimately inside the workspace.

Join relative paths with WorkDir before resolution so the agent can use bare
filenames without hitting the outside-workspace error.
v0.3.0
2026-05-12 17:10:32 +08:00
sausheong c2af8f389d examples: add self-improving-agent + v0.2.0 README updates v0.2.0 2026-05-09 16:34:44 +08:00
sausheong c7acd5a30e runtime: add Review integration test (memory save round-trip via fake LLM) 2026-05-09 16:34:40 +08:00
sausheong d9580eee8f runtime: implement Review with snapshot/build/run/extract/origin + spec-override tests 2026-05-09 16:34:36 +08:00
sausheong fd16dcefee runtime: add Review interface (spec, result, sentinel, prompts) 2026-05-09 16:33:57 +08:00
sausheong 53a7986fa0 skills: add end-to-end integration tests + polish 2026-05-09 15:42:45 +08:00
sausheong 7e394276da skills: add SkillTool with six actions (create/patch/replace/remove/list/get) 2026-05-09 15:42:42 +08:00
sausheong c884ef130a skills/disk: add disk-backed Store with full CRUD, frontmatter parser, concurrent-safe writes, and provider adapter 2026-05-09 15:42:37 +08:00
sausheong e9eea7c842 skills: add SkillStore interface, Skill type, OriginKey, name validation 2026-05-09 15:42:33 +08:00
sausheong 4877db85ae memory: add end-to-end integration tests + polish 2026-05-09 06:54:16 +08:00
sausheong 9381b2b661 memory: add MemoryTool with five actions (save/update/remove/list/get) 2026-05-09 06:54:12 +08:00
sausheong d2491dc90f memory/jsonl: add disk-backed Store with full CRUD, Compact, flock, and provider adapter 2026-05-09 06:54:07 +08:00
sausheong 1acf0d48a3 memory: add MemoryStore interface, Entry type, OriginKey 2026-05-09 06:53:58 +08:00
sausheong 0ca0fed9f7 fix(browser): reap orphaned Chromes when parent dies hard
chromedp launches Chrome as detached subprocesses; on SIGKILL, OOM, or
any path that bypasses our cleanup chain they reparent to PID 1 and
survive indefinitely. Each launch now allocates a known harness-browser-*
user-data-dir and registers it with a single detached /bin/sh watchdog
spawned via Setsid. When the parent dies the watchdog detects stdin EOF
and pkills + rm -rfs every still-tracked path. Clean teardown untracks
the path so a later hard exit can't kill the next session sharing the
process.
2026-05-08 22:08:58 +08:00
sausheong cc0406d30c Sharpen README: when to use Harness, and for what
Removes the standalone comparison.md (analysis kept locally only) and
folds its key positioning insights into the README without naming
specific competitors.

Why-Harness section:
- Reframes the substrate-vs-DSL distinction more directly: the
  runtime is treated as strategic infrastructure you own, not as
  plumbing hidden behind a graph builder.
- Capitalises 'Harness' in prose to match the project name.

New 'What Harness is for' section enumerates the use cases the
runtime is shaped around:
  - coding agents
  - infrastructure-automation agents
  - long-running autonomous loops
  - local-first agents
  - tool-heavy agents
  - developer-tooling agents
Plus a one-paragraph note on why Go's operational profile (static
binary, low memory, native concurrency, embeddability) matters
for these.

New 'When Harness is the wrong fit' section names the workflow
shapes the package isn't optimised for — visual / declarative
workflows, role-based crews, RAG-first products, notebook research,
heavily-regulated enterprise orchestration — without naming any
competing framework.

The existing 'Non-goals' section still covers what the library
doesn't ship (CLI, UI, channel adapters, etc.); the two sections
serve adjacent purposes.
2026-05-08 15:06:24 +08:00
sausheong 4df84b76d0 Add comparison.md surveying Harness against the agent-framework landscape
New top-level document comparing Harness's approach against LangGraph,
CrewAI, AutoGen/AG2, Semantic Kernel, OpenAI Agents SDK, Claude Agent
SDK, LlamaIndex, Mastra, and the Go peers eino + langchaingo.

Frames Harness as a runtime-centric, in-process Go library closer in
spirit to coding-agent runtimes (Claude Code, OpenClaw, OpenHands)
than to graph-based or role-based orchestration frameworks. Includes
current GitHub stats, per-framework architectural comparisons, the
language-choice tradeoff, the abstraction-fatigue trend, and where
Harness is the right (and wrong) pick.

README links to it next to the developer.md pointer; .gitignore
whitelists comparison.md alongside the other tracked docs.
2026-05-08 14:59:39 +08:00
sausheong 7e9801bf9c Remove upstream-project attribution from docs and code comments
Strips references to the upstream npm-package agent harness from
README design notes, developer.md, the compaction package, the
runtime context/streaming comments, and the tools/mcp adapter
doc-comments. The technical patterns being described stand on their
own; the attribution chain isn't needed.

Remaining mentions of the word in the providers/anthropic package
are literal Anthropic model identifiers (the 'claude-…' API model
strings) — those are functional product names, not attribution.
2026-05-08 13:43:10 +08:00
sausheong fa61dbdf77 Prepare for v0.1.0 release
Update Status section to reflect first tagged release: switch the
top-of-README badge to "v0.1.0" and the bottom Status block to a
go-get install hint plus pointer to GitHub releases for the changelog.
v0.1.0
2026-05-08 13:34:00 +08:00
sausheong 50cbc74865 minor update 2026-05-08 13:34:00 +08:00
sausheong 76c03019c8 Add hooks and MCP as first-class components; expand docs
Promotes the two remaining "deliberately not in scope" components from
the harness model to first-class subsystems, and overhauls the docs.

Hooks (runtime/types.go, runtime/runtime.go, runtime/hooks_test.go):
- New runtime.LifecycleHooks struct on LoopConfig.Hooks with five
  Go callbacks: OnUserPromptSubmit (may rewrite prompt),
  OnSessionStart, BeforeToolUse (gating with same shape as
  PermissionChecker), AfterToolUse (observe), OnStop (with reason:
  completed/max_turns/error/aborted).
- Wired into Run, dispatchTool, executeToolKickoff at all 8 exit
  points + both tool-execution paths.
- 8 tests covering each hook firing.

MCP (tools/mcp/, runtime/builder.go, runtime/types.go):
- New tools/mcp package using the official
  github.com/modelcontextprotocol/go-sdk v1.5.0. Stdio and
  Streamable HTTP transports.
- ServerConfig now exposes Headers + HTTPClient for HTTP auth
  (static bearer, OAuth via oauth2.NewClient, mTLS, custom
  RoundTripper). Header injection clones requests so SDK retries
  see clean params.
- First-class AgentSpec.MCPServers — BuildRuntime connects each
  server, registers adapter tools (mcp__<server>__<tool>), stashes
  clients on Runtime.
- New Runtime.Close() releases sessions; idempotent.
- 14 tests including end-to-end header propagation through the SDK
  via httptest.Server.

Examples:
- support-agent now demonstrates Skills + Permission + LifecycleHooks
  together. Audit log via AfterToolUse + OnStop, JSONL output.
- defer rt.Close() added to all four examples (no-op without MCP,
  idiomatic).

Docs:
- README expanded: Why harness, Requirements, Install, Examples
  table, Configuration (env vars), Non-goals, Testing, expanded
  Status. Quick Start fixed to use real BuildRuntime API.
- developer.md mental-model diagram replaced with two correct ones:
  composition (how a Runtime is wired) and per-Run sequence (what
  rt.Run actually does, including hook fan-out and the tool batch
  loop).
- developer.md gains Lifecycle hooks + MCP servers subsections with
  full snippets, including Streamable HTTP auth and OAuth recipes
  (clientcredentials + authcode flows via golang.org/x/oauth2).
- LICENSE file added (MIT).

All 18 packages build and test green.
2026-05-08 13:34:00 +08:00
sausheong 4b2f645f16 Document harness components and design notes in README 2026-05-08 00:44:55 +08:00
sausheong 123a233cb7 Drop Felix references; harness stands as a platform on its own
Removes every Felix mention from public-facing surfaces so the framework
reads as a standalone agent platform rather than an extracted module.

User-visible changes:
- HTTP User-Agent on web_fetch / web_search: Felix/1.0 → harness/1.0
- bash tool path-substitution prefix: '[felix]' → '[harness]'
- On-disk paths: <workspace>/.felix/ → <workspace>/.harness/
  (todos.json + spill/ tree); tests updated in lockstep.
- OTel trace attributes: felix.trace_id / felix.total_ms /
  felix.phase_count → harness.* equivalents.

Doc-comment changes:
- Examples (lta-agent, data-agent) lose 'non-Felix consumer' framing.
- README drops the 'extracted from Felix' lede and the 'What was lifted
  from Felix' section, replaced with a 'Design' overview that points
  to developer.md.
- Runtime / tool / compaction doc comments rewritten so behaviour
  notes describe what the harness does without naming the prior origin.
- Test-fixture text 'you are felix' → 'you are an assistant'.

Verified: zero 'felix' (case-insensitive) in tracked .go / .md files.
All 16 packages build and pass tests.
2026-05-08 00:24:06 +08:00
sausheong 8ed38d7b66 Add support-agent example: mock customer-support agent
Demonstrates two harness surfaces the previous examples skipped:

- SkillProvider: KB articles in examples/support-agent/kb/ are exposed
  via runtime.SkillProvider. The runtime auto-registers load_skill and
  inlines a compact article index into the static (cacheable) system
  prompt; full bodies load on demand.

- PermissionChecker: tickets_update and escalate_to_human are gated on
  a 'supervisor' flag. FilterToolDefs hides the gated tools from the
  LLM tool list in non-supervisor mode so it doesn't waste turns
  inventing calls that would just be denied.

Five concrete tools (kb_search, tickets_get, tickets_create,
tickets_update, escalate_to_human) plus the auto-registered load_skill.
Five seed KB articles cover refund policy, escalation matrix, account
recovery, password reset, and API rate limits — chosen to exercise the
common support patterns each tool involves.

In-memory ticket store (examples/support-agent/store.go) seeded with
four tickets in different states. Webhook delivery for escalations is
optional via SUPPORT_AGENT_WEBHOOK; when unset the tool prints the
escalation banner to stdout, so the demo runs with only
ANTHROPIC_API_KEY set.

Tests (support_test.go) cover store CRUD, defensive copying, the
permission checker's read/write split, and KB indexing/search — all
offline, no API needed.
2026-05-08 00:10:49 +08:00
sausheong 152f653dd7 Add developer.md guide and ignore compiled example binaries
developer.md: practical guide to writing agents on harness — mental
model, minimum-viable agent, tool authoring rules, provider table,
session persistence, streaming events, LoopConfig knobs, subagents,
and the four optional plug points (Permission, Compaction, Skills/
Memory, KnowledgeGraph). Whitelisted in .gitignore alongside README.md.

Also ignore /examples/<dir>/<binary> so 'go build ./examples/...'
doesn't leave artifacts the next 'git status' has to step around.
2026-05-07 21:24:45 +08:00