Commit Graph

182 Commits

Author SHA1 Message Date
ollie 41eedb0c27 tools: discover prompts from ollie:prompt script headers
- Add Prompt field to tools.ToolInfo
- Add ExtractPrompt parser for ollie:prompt...ollie:end blocks
- Add DiscoverTools to scan tool scripts directory
- BuildRuntime appends discovered tool prompts to preamble

Tool scripts can now embed their usage documentation directly in
the script header. This replaces the separate tools-*.md prompt
files and ensures documentation stays co-located with implementation.
2026-07-21 13:18:38 +02:00
ollie f5298306b1 agent: layered preamble scaffolding
BuildRuntime now accepts optional baseLayers (variadic strings) that
are prepended to the agent-resolved preamble. This enables the server
to compose: system_prompt + operational_model + environment + agent_prompts.

- config.Config: add SystemPrompt field (path override)
- AgentCoreConfig: add OperationalModel and SystemPrompt fields
- BuildRuntime: prepend baseLayers before agent prompt content
- Remove debug fprintf statements from prompt resolution
2026-07-21 12:53:51 +02:00
ollie c2688a1d3d agent: cross-turn tool result cache
Move the read-safe tool result cache from a per-turn local variable
to the agent struct, persisting it across turns. This eliminates
redundant calls to file_read, lsp_*, and memory_recall when the
underlying data has not changed.

The cache is invalidated (cleared entirely) when file_write or
file_edit executes, ensuring stale results are never returned
after mutations.
2026-07-21 12:04:35 +02:00
ollie bd3b46bbed agent: debounce session persistence
saveSession() now sets a dirty flag and starts a 2-second timer
instead of immediately serializing and writing the full message
history. For a 50-step turn, this reduces 50 JSON marshals + disk
writes down to ~25 (one every 2s) plus a guaranteed flush at
turn end and on close.

flushSave() is called:
- At end of turn (after setState idle)
- On interrupt
- On Close()
- When the 2s timer fires (if still dirty)
2026-07-21 12:00:30 +02:00
Levi Neely 05e43b9a7c agent: resolve prompt from file paths and OLLIE_PROMPTS_PATH 2026-07-20 13:37:09 +02:00
ollie 663311daa0 remote: persist Remote field in session save/restore 2026-07-19 21:53:01 +02:00
ollie d501b47bf7 prompt: store PromptEnvExtra on agent for /agent reloads
Added PromptEnvExtra to AgentCoreConfig and agent struct. The /agent
command now uses stored PRIME_* vars instead of recomputing locally.
This ensures remote sessions get the correct remote host info on
every prompt rebuild.
2026-07-19 20:37:37 +02:00
ollie 6f35059d83 agent/hooks: add run/fail summary to HookResult
Track Total, Succeeded, Failed counts and FailedCmds in HookResult.
Add Summary() method producing "(N of X hooks run) (K of X failed: cmd)".
Emit hook summary as info event at all lifecycle hook call sites and
on preTool/postTool failure.
2026-07-19 10:25:09 +02:00
Levi Neely f8ed2189f1 agent: inject detached process output on exit
When a detached process exits, its output (last 2KB of ring buffer)
is queued as a prompt wrapped in <detached-process-result> tags.
The agent sees it on its next turn (or immediately if idle via Queue).

- InjectSystemEvent(content) added to Core interface
- SetOnExit(fn) added to execute.Server for external hook wiring
2026-07-17 22:07:26 +02:00
Levi Neely 5df603a9e3 agent: expose detach methods on Core interface
Adds Detach, ListDetached, SignalDetached, GetDetachedOutput,
DismissDetached to the Core interface. Implemented on agent struct
via interface type assertions to the execute server.

Also adds ListDetachedRaw() to execute.Server for cross-package
consumption without import cycles.
2026-07-17 16:49:29 +02:00
ollie 451dc96d47 agent: add SaveSession to Core interface for external persistence
- Add Backend/Model fields to PersistedSession for full restore metadata
- Add saveToFull() that includes backend/model in persisted state
- Add exported LoadPersistedSession(path) helper
- Add SaveSession(path) to Core interface, implemented on agent struct
- Existing saveTo() preserved as backward-compatible wrapper
2026-07-14 20:41:38 +02:00
ollie f05b736af9 agent: update preamble when cwd changes
SetCWD now replaces old cwd references in the system prompt,
matching the pattern used by SetSessionID. Without this, the
model continued to see the original cwd in its environment
section after a directory change.
2026-07-07 12:20:48 +02:00
ollie 331edc332d fix test 2026-07-01 21:22:16 +02:00
ollie 8e7dd60a8b agent: remove $OLLIE mount dependency from core
- Add ListHandlers map to AgentCoreConfig/agent struct; /skills and /tools
  dispatch through it instead of reading local paths directly
- Add ReadPlanStep to AgentCoreConfig; wired by 9p/ directly from sess.plan
- Export NextUncheckedStep([]byte) as pure helper
- Fix prependOlliePath to use OLLIE_CFG_PATH/scripts/x/ instead of $OLLIE/x/
- Add OLLIE_CFG_PATH to EnsureDefaults and managed env var list
2026-06-16 12:30:36 +02:00
ollie 10cbded305 token efficiency: fix tier classification, expand cold tier, add usage log and compaction model override
- Fix dead-code bug: ClassifyTier now parses inner tool names from
  call_tool/pipe arguments via ResultTierArgs
- Add file_grep, file_glob, lsp_symbols, lsp_completion, lsp_diagnostics,
  reasoning_think to cold tier
- Add append-only JSONL usage log (~/.local/share/ollie/usage.jsonl)
- Add compaction model override: config > OLLIE_COMPACTION_MODEL env >
  per-backend default (haiku/gpt-4o-mini/flash)
- Expose CompactionModel on Core interface
2026-05-28 18:44:30 +02:00
ollie 02df4b8dd5 agent: plumb image ContentBlocks from tool results through to backend messages
toolExecutor now returns (string, []ContentBlock, error).
extractToolResult parses image blocks from structured tool output.
Session.update populates ContentBlocks on tool messages.
file_read detects PNG/JPEG/GIF/WEBP and returns base64-encoded image blocks.
2026-05-25 18:02:21 +02:00
Levi Neely 47f8eed119 agent: remove unsandboxed ! shell escape
The ! prefix allowed arbitrary command execution without sandbox
protection. Since agents share the same Submit path as users, this
was a sandbox bypass vector. Remove it entirely; users who need
shell access can use execute_code (sandboxed) or run commands
directly in their terminal.
2026-05-21 15:18:02 +02:00
Levi Neely 8ae0fad8a3 session persistence: /save, /resume, cwd-scoped /sessions
- Add CWD field to PersistedSession for per-directory filtering
- /sessions now shows only sessions matching current cwd (-a for all)
- /save <name> creates a named checkpoint
- /resume <id> restores a saved session (messages + task state)
- Autosave (already existed) now persists cwd with each save
2026-05-21 15:08:16 +02:00
Levi Neely 9d4818af8d refactor agent core: extract runtime, simplify commands 2026-05-21 14:42:45 +02:00
Levi Neely fa9c98fb05 agent: add exec event role for ! command output
Shell command output uses a dedicated "exec" role instead of "info",
formatted with ``` fences in the chat log.
2026-05-20 16:49:41 +02:00
Levi Neely 1479aea274 agent: publish events on pubsub bus, self-drain queue
- Add pubsub.Bus to agent; all events published on "event" topic
- Remove EventHandler param from Submit (and internal methods)
- Queue() self-drains via goroutine when agent is idle
- /i submits directly when idle, injects when running
2026-05-20 16:45:32 +02:00
Levi Neely 09a9364b6f SetSessionID: update session ID in system prompt on rename 2026-05-20 10:47:56 +02:00
Levi Neely 1e96d4c7f4 agent: separate uname (principal) from session ID
Session identity is now a numeric UID (starting at 10000) assigned at
creation and never changed. Session names can be renamed freely without
affecting the 9P identity.

- AgentCoreConfig.Uname carries the principal
- pushSessionEnv sets OLLIE_UNAME on the execute server
- startMount gated by WithMount() option (not env var)
- Close() uses context timeout to avoid hanging on fusermount
2026-05-19 15:06:16 +02:00
Levi Neely e20f9a7a06 execute: per-session FUSE mount for 9P identity
The execute server now starts ollie-9p-mount when OLLIE_SESSION_ID is
set, giving each agent session its own FUSE proxy that attaches to
olliesrv with Uname=session_id. Tools see the full namespace through
$OLLIE but all 9P operations carry the session's identity.

Close() tears down the mount on session destroy.
2026-05-19 14:10:09 +02:00
Levi Neely 5efed7040d fix: inject OLLIE_SESSION_ID into prompt resolution subprocesses
resolveExecPrompt spawns x/prime which uses envsubst to expand
${OLLIE_SESSION_ID} in the system prompt template. The variable was
never in the process environment at resolution time — it was only
set on the execute server after the prompt was already rendered.

Add env []string parameter to resolvePrompt/resolveExecPrompt and
BuildAgentEnv so callers can inject session-scoped vars into the
subprocess environment. Generate session ID before BuildAgentEnv in
the agent-switch path so it is available at prompt resolution time.
2026-05-18 12:31:35 +02:00
Levi Neely 1207e26a07 remove trustedTools and Confirm callback; trust is implicit via allowExecutors 2026-05-17 15:21:26 +02:00
Levi Neely 7237980ff5 truncation: raise hard ceiling to 128KB, include tool name in message 2026-05-17 12:51:43 +02:00
Levi Neely 8be8b9c42d task state: read PlanStep from plan file (ground truth) with text fallback 2026-05-17 11:09:44 +02:00
Levi Neely 779b99fd9b tool results: tier classification (hot/warm/cold) with immediate cold summarization 2026-05-17 10:59:17 +02:00
Levi Neely b5b2ee43ec loop: replace plan file re-injection with structured TaskState re-injection 2026-05-17 10:14:44 +02:00
Levi Neely 283a2e24d8 state: extend interface with recentHistory/taskState; loop uses selective context 2026-05-17 10:10:33 +02:00
Levi Neely b775e5df7a agent: add TaskState — persisted structured overlay injected at each turn 2026-05-17 10:06:21 +02:00
Levi Neely 45959cb79d agent: apply config backend/model when switching agents via /agent 2026-05-17 00:19:55 +02:00
Levi Neely 22d72f143d fix: wire allowExecutors/allowTools in BuildAgentEnv; add missing IncrToolCallCount field 2026-05-17 00:05:34 +02:00
Levi Neely 3867d52689 add generation params: top_p, top_k, min_p, top_a, repetition_penalty, max_completion_tokens, response_format, reasoning_effort, include_reasoning, stop, verbosity 2026-05-16 23:54:04 +02:00
Levi Neely 6dfae368d0 fix: wire PlanFile, add missing rate-limit constants, simplify test helpers, fix regex
- Wire PlanFile from $OLLIE/s/{id}/plan into agentConfig so plan
  re-injection is no longer dead code
- Add missing failureWindow/maxFailures/blockDuration constants
- Replace hand-rolled contains() with strings.Contains
- Fix rm -rf .. regex to match end-of-string and whitespace
- Add TestPlanReinjection covering periodic plan re-surfacing
- Add loop_maxsteps_helpers_test.go with mockResponse/newState/sequentialStream
2026-05-16 23:54:04 +02:00
Levi Neely 2101a2c023 agent: add MaxSteps override in AgentCoreConfig and /maxsteps command
- AgentCoreConfig.MaxSteps: when non-zero, overrides the value loaded
  from the agent JSON (cfg.Env.maxSteps). Zero means "use the agent
  JSON value, or unlimited if absent". Callers (9p frontend, httpgw,
  CLI) can now inject a per-session limit at construction time without
  touching any agent config file.

- /maxsteps [n] command: shows the current limit (0 = unlimited) or
  sets it live during a session. Follows the same pattern as /model.
  Added to /help listing.
2026-05-16 18:56:39 +00:00
Levi Neely d8467a4f16 agent: add ToolCallCount to Core interface; wire tcct accumulator
Adds a monotonically increasing tool-call counter (tcct) to the agent.

- atomic.Int64 toolCallCount on the agent struct
- ToolCallCount() int64 on the Core interface
- IncrToolCallCount func() int64 on agentConfig, wired in executeTurn
- Incremented in execOne after the pre-tool hook returns (blocked calls
  don't count) and before cfg.Exec is called (timeout/error still counts)

The counter never resets. Consumers use modulo arithmetic:
  tcct % 10 == 0  ->  fires every 10 actual executions

The primary consumer is ollie-9p, which exposes tcct as a read-only
9P file that pre_tool / post_tool hooks can inspect via cat.
2026-05-15 20:16:43 +00:00
Levi Neely 0d9405f9bc core: read MaxSteps from config into agentConfig 2026-05-15 19:33:44 +00:00
Levi Neely b6308f1a13 agent: log prompt resolution errors to stderr 2026-05-11 14:13:44 +02:00
Levi Neely a2b6adb6cf env: add OLLIE_AGENTS_PATH with colon-separated multi-dir resolution 2026-05-08 13:01:04 +02:00
Levi Neely 0041fc77ec add OLLIE_PROMPTS_PATH env var and PromptsDirs helper 2026-05-08 11:59:16 +02:00
Levi Neely f9b2b50274 agent: preserve completed work on interrupt/error
- On interrupt or error, keep user message, assistant response, and
  completed tool results (success or error)
- Only remove cancelled/interrupted tool results
- Use deep copy for message snapshots to prevent aliasing bugs
- Snapshot now only used for context overflow retry
2026-05-04 10:23:56 +02:00
Levi Neely 3c5d92b461 agent: roll back session on interrupt, clean error message
On user interrupt (stop/CTRL+C), the session history now rolls back
to the pre-turn snapshot instead of keeping partial/cancelled tool
results in the model's context. This prevents raw errors like
'context canceled' from poisoning subsequent turns.

Tool results interrupted by cancellation now report 'tool execution
interrupted by user' instead of the raw Go error chain.
2026-05-03 21:10:28 +02:00
Levi Neely c069deccca config: add tools bool to disable tool collection per agent
When tools is false in agent config, BuildAgentEnv skips ListTools
entirely so no tool schemas are sent to the backend. Models without
tool support now work cleanly.
2026-05-03 14:58:58 +02:00
Levi Neely 1b04d6a75b agent: fix race between setState and currentAction in Submit
currentAction was stored after setState("thinking"), creating a window
where Interrupt() would see a nil action handle and return false despite
the agent being mid-turn.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-03 13:30:12 +02:00
Levi Neely b511626e4f remove stale-read pruning from context management 2026-05-02 13:50:40 +02:00
Levi Neely ed3373d3f0 add s/{sid}/context 9P endpoint
Exposes the current context window (messages sent to the backend) as a
read-only JSONL file. Each line is a serialized backend.Message with the
system prompt prepended and stale reads pruned, matching what run() sends
to ChatStream. Useful for debugging agent forgetfulness.
2026-04-29 18:03:43 +02:00
Levi Neely c812f0882e freeloader: fix 404 tool_unsupported detection and FIFO-drain recovery
- backend: add HTTP 404 and "no endpoints found" to isToolUnsupported
  so OpenRouter 404s are correctly classified as tool_unsupported
- core: drain FIFO on error return from executeTurn so freeloader's
  resubmitted prompt (queued via fifo.in while running) is picked up

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-28 18:47:34 +02:00
Levi Neely 9ce1e63788 core: allow /model switch while running; detach turnError hook context
- /model command no longer rejects switches while agent is running;
  needed for turnError hook recovery (freeloader switches model mid-error)
- TurnError hook uses context.Background()-derived context so hook can
  safely issue ctl commands without cancelling its own execution
- update TestCommand_Model_WhileRunning to expect success

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-28 17:41:43 +02:00