Commit Graph
38 Commits
Author SHA1 Message Date
sausheong 62f3424f30 feat: PDF attachments as Anthropic document blocks
Reuses llm.ImageContent/session.ImageData with MimeType
"application/pdf" rather than adding a new field: images already flow
tool result -> session entry -> reload -> provider end to end, so a
MIME check at the provider edge is the smallest change.

- Anthropic provider emits a document block (source.type=base64,
  media_type=application/pdf) for a PDF attachment in a tool result or
  a user message; images are unaffected. Cache control now also
  applies to document blocks.
- OpenAI provider replaces a PDF attachment with a text placeholder
  instead of an invalid image_url data URI; images still emitted.
  Gemini already accepts application/pdf inline and needs no change.
2026-09-26 00:41:54 +08:00
sausheong 3ca0994437 Reject empty and truncated answers and expose complete tool calls 2026-09-11 23:48:25 +08:00
sausheong 019a38f111 Fix repeated stream finishes and preserve cancellation causes 2026-09-10 16:34:12 +08:00
sausheong 0972eed3ea Harden Harness runtime, persistence and execution for Hand 2026-09-09 22:55:55 +08:00
sausheong 897643db18 Add a regression test proving a mid-session model switch is real
Verifies, at the Runtime.Run level, that mutating Model and
DynamicIdentityHint between two Run calls in the same session (exactly
what hand's tui.Controller.SwitchModel does) actually changes the
ChatRequest.Model sent on the next call, not just the system prompt
text. If this ever regressed, a caller-side "/model" fix would look
correct in its own unit tests while the model actually being queried
silently stayed the old one.
2026-09-07 00:22:07 +08:00
sausheong 0ccfdb2a24 Add Runtime.DynamicIdentityHint, a live, per-turn identity fact
Runtime.StaticSystemPrompt is cached and reused verbatim every turn —
right for anything that doesn't change mid-conversation, wrong for a
fact a caller needs to update live (e.g. after a runtime model switch)
and have the model actually notice. A model tends to just repeat what
it already told the user earlier in the same conversation over a
background instruction it read once near the top of a large cached
block, so updating only the static prompt after a switch left the
model insisting it was still whatever it started as.

DynamicIdentityHint rides the same per-turn (uncached) system prompt
slot Run/RunTurn already use for the date line and KG hint, so setting
it takes effect on the very next turn with the same recency the model
grants its own last statement.
2026-09-07 00:15:23 +08:00
sausheong eb4fa67976 fix: harden runtime against panics/races, close path-traversal and fail-open gaps
- Runtime.Run rejects concurrent invocations instead of racing on shared state; panics in tools, hooks, and permission checkers are recovered and surfaced as errors/denials instead of crashing the loop
- AgentSpec.Loop now actually overrides RuntimeDeps.AgentLoop per-agent, as documented
- session.Store validates agent ID / session key as single path components, preventing traversal outside the session directory
- ValidatePathInWorkDir resolves symlinks on the target itself, not just its parent, closing a workspace-escape gap
- bash tool now fails closed on an unrecognized ExecPolicy.Level instead of allowing everything
- browser tool rejects unknown actions instead of silently no-op'ing

Bump README to v0.3.4 and document the AgentSpec.Loop override semantics.
2026-08-02 10:14:20 +08:00
sausheong 152d8b972e feat: preserve and echo thinking blocks for extended-thinking models (DeepSeek, Claude thinking mode) 2026-07-12 20:30:48 +08:00
sausheong ef3a1d4927 test(runtime): assert addUsage returns a distinct pointer (aliasing safety) 2026-06-26 21:41:23 -07:00
sausheong 2f97b1cf78 docs(runtime): clarify EventDone.Usage is the run total 2026-06-26 21:37:28 -07:00
sausheong 69f58903eb fix(runtime): emit run-total token usage on terminal EventDone
Run accumulated only the last turn's usage into the terminal EventDone, so
multi-turn runs under-reported tokens to consumers metering AgentEvent.Usage.
Sum all four usage fields across turns; RunTurn is unchanged (one turn/call).
2026-06-26 21:33:58 -07:00
sausheong 1ec0f9cac3 feat(runtime): add pure addUsage helper for field-wise usage summation 2026-06-26 21:29:27 -07:00
sausheong 04f02c56d6 fix(runtime): RunSync returns context.Canceled on aborted run 2026-06-13 15:33:02 +08:00
sausheong e1fd4dc689 fix(runtime): recompute calibrator estimate at EventDone (P8 stale-estimate bug)
The earlier P8 change reused the pre-compaction turnEstimate at EventDone,
but mid-turn compaction reassembles msgs without recomputing it — so the
persisted calibration ratio diverged from main whenever compaction fired,
changing future compaction timing. Recompute fresh at EventDone exactly as
the pre-debounce code did; keep only the disk-write debounce (the real win).
2026-06-13 10:27:53 +08:00
sausheong c710ea5a94 perf(runtime): track spilled tool-call IDs to skip re-writing spills each turn (P1) 2026-06-13 10:04:46 +08:00
sausheong 671c10e89a perf(runtime): persist calibrator once per Run; reuse per-turn estimate (P8) 2026-06-13 10:00:52 +08:00
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 7052a66e38 fix(runtime): recover from pre-first-token stream errors (compaction/fallback) — R1 2026-06-13 01:46:38 +08:00
sausheong 27fecf4588 feat(runtime): spill files 0600 via atomic write 2026-06-13 00:53:22 +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 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 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
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 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 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 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 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 1f2c471ff9 Initial commit: Go agentic harness extracted from Felix 2026-05-07 11:31:42 +08:00