Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
docs(agent-core): plan, evaluation, and contracts for the Avibe Agent (#2333)
Call Whitea7c785662568
diff --git a/docs/plans/agent-core-contracts/README.md b/docs/plans/agent-core-contracts/README.mdnew file mode 100644index 000000000..886a85bc2--- /dev/null+++ b/docs/plans/agent-core-contracts/README.md@@ -0,0 +1,32 @@+# Agent core contracts++Status: **draft**, 2026-10-02. Shapes and semantics shared by the lanes in+[`../avibe-agent-core.md`](../avibe-agent-core.md) §7. A contract is frozen on `master` before the lanes that depend+on it fork; after that, a change needs orchestrator approval and lands here first.++| ID | Contract | Producer → consumer | Files | Frozen before |+| --- | --- | --- | --- | --- |+| C-1 | Canonical message model and cross-provider rules | `ai` → `agent`, `harness`, adapter | [`message.schema.json`](message.schema.json), [`cross-provider.md`](cross-provider.md) | P1 |+| C-2 | Provider adapter interface and stream events | `ai` → `agent` | [`provider.md`](provider.md), [`provider-event.schema.json`](provider-event.schema.json) | P1 |+| C-3 | Loop control: hooks, directives, steer, follow-up, fork | `agent` → adapter, `harness`, tests | [`loop-control.md`](loop-control.md) | P1 |+| C-4 | Agent event stream and its mapping to Avibe outputs | `agent` → adapter | [`agent-event.schema.json`](agent-event.schema.json), [`loop-control.md`](loop-control.md) §6 | P2 |+| C-5 | Transcript rows, `context_seq`, projection, fork | adapter ↔ `harness` | [`transcript.md`](transcript.md), [`transcript-rows.schema.json`](transcript-rows.schema.json) | P2 |+| C-6 | Model Hub consumer extension | Model Hub → adapter | [`model-hub-consumer.md`](model-hub-consumer.md), [`hop-resolution.schema.json`](hop-resolution.schema.json) | P1 |+| C-7 | Tools, output governance, job handle | `tools` → `agent`, adapter | [`tools.md`](tools.md), [`job.schema.json`](job.schema.json) | P1 |+| C-8 | Backend registration | catalog → every backend list | [`backend-registration.md`](backend-registration.md) | P2 |+| C-5, C-7 | Recovery invariants for jobs, tool calls, and delivery, with owners and proofs | `tools`, `loop`, adapter | [`recovery.md`](recovery.md) | P1 |+| C-9 | Context management (draft, not frozen) | `harness` → `agent`, adapter | plan §5.2; rows in [`transcript-rows.schema.json`](transcript-rows.schema.json) | P3 |++Conventions:++- JSON Schema draft-07, like `../model-hub-contracts/`. Python implementations use dataclasses; the schemas describe+ the serialized form, which is what crosses a lane boundary or reaches disk.+- Persisted shapes carry `"version": 1`. Readers accept every released version (persisted-shape rule).+- Field names are `snake_case`, except the tool parameters in C-7, which keep Pi's names (`oldText`, `newText`,+ `replaceAll`).+- Every statement about existing code names its file and was checked against `master`; fields that already exist+ keep their meaning (a new meaning gets a new field).+- Contracts fix shapes that cross a lane boundary and the invariants each lane must prove. Mechanisms inside one lane+ (launch handshakes, retry loops, chunking) are that lane's code and tests, not contract text.+- Protocol names use Model Hub's vocabulary, extended by C-6: `anthropic`, `openai_chat`, `openai_responses`,+ `google`.diff --git a/docs/plans/agent-core-contracts/agent-event.schema.json b/docs/plans/agent-core-contracts/agent-event.schema.jsonnew file mode 100644index 000000000..20af67313--- /dev/null+++ b/docs/plans/agent-core-contracts/agent-event.schema.json@@ -0,0 +1,356 @@+{+ "$schema": "http://json-schema.org/draft-07/schema#",+ "$id": "agent-core/agent-event.schema.json",+ "title": "AgentEvent",+ "description": "C-4 event yielded by Agent.run. In-process only; never persisted as-is. Committed context lives in C-5 rows, which events reference by id. Mapping to Avibe outputs: loop-control.md section 6.",+ "type": "object",+ "required": [+ "type",+ "turn_id",+ "seq"+ ],+ "properties": {+ "type": {+ "enum": [+ "run_started",+ "text_delta",+ "thinking_delta",+ "message_committed",+ "tool_started",+ "tool_progress",+ "tool_finished",+ "steer_applied",+ "compaction_started",+ "compaction_finished",+ "compaction_failed",+ "run_ended",+ "error"+ ]+ },+ "turn_id": {+ "type": "string",+ "description": "`session_turns.id` of the Turn the run belongs to, the same identity as `agent_events.turn_id`. The Harness Run id (`agent_events.run_id`) is known to the adapter and not carried here."+ },+ "seq": {+ "type": "integer",+ "minimum": 0,+ "description": "Monotonic within the run."+ }+ },+ "allOf": [+ {+ "if": {+ "properties": {+ "type": {+ "enum": [+ "text_delta",+ "thinking_delta"+ ]+ }+ }+ },+ "then": {+ "required": [+ "delta"+ ],+ "properties": {+ "delta": {+ "type": "string"+ }+ }+ }+ },+ {+ "if": {+ "properties": {+ "type": {+ "const": "message_committed"+ }+ }+ },+ "then": {+ "required": [+ "message_id",+ "context_seq",+ "final"+ ],+ "properties": {+ "message_id": {+ "type": "string",+ "description": "`messages.id` of the committed assistant row."+ },+ "context_seq": {+ "type": "integer"+ },+ "final": {+ "type": "boolean",+ "description": "True for the run's final response (`result` row)."+ }+ }+ }+ },+ {+ "if": {+ "properties": {+ "type": {+ "const": "tool_started"+ }+ }+ },+ "then": {+ "required": [+ "tool_call_id",+ "name",+ "preview"+ ],+ "properties": {+ "tool_call_id": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "preview": {+ "type": "string",+ "maxLength": 500,+ "description": "Display preview of the arguments."+ },+ "job_id": {+ "type": "string"+ }+ }+ }+ },+ {+ "if": {+ "properties": {+ "type": {+ "const": "tool_progress"+ }+ }+ },+ "then": {+ "required": [+ "tool_call_id",+ "tail"+ ],+ "properties": {+ "tool_call_id": {+ "type": "string"+ },+ "tail": {+ "type": "string",+ "description": "Latest output lines, normalized."+ }+ }+ }+ },+ {+ "if": {+ "properties": {+ "type": {+ "const": "tool_finished"+ }+ }+ },+ "then": {+ "required": [+ "tool_call_id",+ "event_id",+ "is_error"+ ],+ "properties": {+ "tool_call_id": {+ "type": "string"+ },+ "event_id": {+ "type": "string",+ "description": "`agent_events.id` of the committed tool_result row."+ },+ "is_error": {+ "type": "boolean"+ },+ "watch_id": {+ "type": "string",+ "description": "Present when the job was handed to Watch."+ }+ }+ }+ },+ {+ "if": {+ "properties": {+ "type": {+ "const": "steer_applied"+ }+ }+ },+ "then": {+ "required": [+ "message_id"+ ],+ "properties": {+ "message_id": {+ "type": "string"+ }+ }+ }+ },+ {+ "if": {+ "properties": {+ "type": {+ "const": "compaction_finished"+ }+ }+ },+ "then": {+ "required": [+ "event_id",+ "reason",+ "tokens_before",+ "tokens_after_estimate"+ ],+ "properties": {+ "event_id": {+ "type": "string"+ },+ "reason": {+ "enum": [+ "manual",+ "threshold",+ "overflow"+ ]+ },+ "tokens_before": {+ "type": "integer",+ "minimum": 0+ },+ "tokens_after_estimate": {+ "type": "integer",+ "minimum": 0+ }+ }+ }+ },+ {+ "if": {+ "properties": {+ "type": {+ "const": "compaction_failed"+ }+ }+ },+ "then": {+ "required": [+ "reason",+ "error"+ ],+ "properties": {+ "reason": {+ "enum": [+ "manual",+ "threshold",+ "overflow"+ ]+ },+ "error": {+ "type": "string",+ "minLength": 1+ }+ }+ }+ },+ {+ "if": {+ "properties": {+ "type": {+ "const": "compaction_started"+ }+ }+ },+ "then": {+ "required": [+ "reason"+ ],+ "properties": {+ "reason": {+ "enum": [+ "manual",+ "threshold",+ "overflow"+ ]+ }+ }+ }+ },+ {+ "if": {+ "properties": {+ "type": {+ "const": "run_ended"+ }+ }+ },+ "then": {+ "required": [+ "reason"+ ],+ "properties": {+ "reason": {+ "enum": [+ "completed",+ "aborted",+ "error",+ "ended_by_hook",+ "context_exhausted"+ ]+ }+ }+ }+ },+ {+ "if": {+ "properties": {+ "type": {+ "const": "error"+ }+ }+ },+ "then": {+ "required": [+ "kind",+ "message"+ ],+ "properties": {+ "kind": {+ "type": "string"+ },+ "message": {+ "type": "string"+ }+ }+ }+ }+ ],+ "examples": [+ {+ "type": "tool_started",+ "turn_id": "trn_3f9c2a71",+ "seq": 14,+ "tool_call_id": "toolu_01AbC",+ "name": "bash",+ "preview": "pytest tests/test_paths.py -q",+ "job_id": "job_31c"+ },+ {+ "type": "tool_finished",+ "turn_id": "trn_3f9c2a71",+ "seq": 19,+ "tool_call_id": "toolu_01AbC",+ "event_id": "evt_0065cd1a2b",+ "is_error": false,+ "watch_id": "wch_8f2k"+ }+ ]+}diff --git a/docs/plans/agent-core-contracts/backend-registration.md b/docs/plans/agent-core-contracts/backend-registration.mdnew file mode 100644index 000000000..c11921a86--- /dev/null+++ b/docs/plans/agent-core-contracts/backend-registration.md@@ -0,0 +1,42 @@+# C-8 Backend registration++Adding `avibe` touches every place that lists backends. Today those lists are literals scattered through the tree,+and they mean two different things. This contract makes the difference explicit.++## 1. Two sets++| Set | Members | Meaning |+| --- | --- | --- |+| **Agent backends** | `claude`, `codex`, `opencode`, `avibe` | anything an Avibe Agent can run on: catalog, routing, settings, Model Hub supply and routes, turn provenance, Agent Run targets, IM agent pickers |+| **Native CLI backends** | `claude`, `codex`, `opencode` | backends that are an external CLI: CLI path discovery, CLI auth and OAuth setup, native session listing and resume, CLI process restart, Model Hub launch overlays for native CLIs |++`avibe` has no CLI, CLI auth, native session store, or native fork. It must never be added to a native-CLI list, and+it must be added to every agent-backend list.++## 2. One declaration++`modules/agents/catalog.py` declares both sets. Every other list imports them; literals of backend names are removed.+`core/vibe_agents.py`'s `SUPPORTED_AGENT_BACKENDS` folds into the catalog. Model Hub's JSON contracts keep literal+enums (JSON Schema has no imports); a contract test compares them with the catalog.++## 3. Inventory to classify (`master` at `21fb3c3ab`)++Found by searching for the three names as a list or set; the P2 adapter lane re-runs the search at its base and+classifies every hit.++- Likely agent-backend lists: `config/v2_config.py` (route backend `Literal` and validation),+ `config/v2_settings.py`, `core/controller.py` (backend registration, target backend check),+ `core/message_dispatcher.py`, `core/services/agent_run_target.py`, `modules/agents/model_hub.py`,+ `modules/im/slack.py`, `modules/im/discord.py`, `modules/im/feishu.py` (agent pickers), Model Hub contract enums+ (`agent-supply`, `agent-chain`, `probe-result`, `turn-provenance`, `resolution-event`, `source`).+- Likely native-CLI lists: `vibe/cli_paths.py`, `core/agent_auth_service.py`, `modules/agents/native_sessions/types.py`,+ `core/backend_restart.py`.++## 4. Test++One contract test over declarations that stand for a whole universe: each must equal one of the two catalog sets.+Capability-specific sets that are legitimately different, such as `core/handlers/model_hub/events.py`'s+`EventAgent` (agent backends plus `system`) or the two-vendor credential set in+`core/handlers/model_hub/migration.py`, are listed in the test with their classification (subset or superset of which+set, and why); they are checked for staying inside that relation, not for equality. An unclassified new literal list+fails the test until it imports a set or is classified.diff --git a/docs/plans/agent-core-contracts/cross-provider.md b/docs/plans/agent-core-contracts/cross-provider.mdnew file mode 100644index 000000000..dc6c87539--- /dev/null+++ b/docs/plans/agent-core-contracts/cross-provider.md@@ -0,0 +1,28 @@+# C-1 Cross-provider transform++Applied by `ai` when it builds a request for a target `(provider, api, model)` from canonical messages+(`message.schema.json`). Rules ported from Pi's `pi-ai` `transform-messages` (MIT); cases ported from tau's+cross-provider history tests (MIT).++| Input | Same origin as the target | Different origin |+| --- | --- | --- |+| Text block | kept | kept |+| Thinking block with `signature` | replayed verbatim with its signature | converted to plain assistant text; the signature is dropped |+| Thinking block, `redacted: true` | replayed verbatim | dropped |+| Thinking block without `signature` (unverified origin, C-2) | sent as plain assistant text | sent as plain assistant text |+| Tool call | kept; `id` and `signature` as stored | kept without `signature`; `id` normalized to the target's rules (below) |+| Tool result | kept | `tool_call_id` rewritten through the same id map |+| Image in a user or tool-result message | kept | kept if the target model accepts images, else `[image: <name or mime>]` |++Invariants:++- "Opaque provider payload" means any `signature` field on any block, and any redacted thinking. Every rule here+ about signatures applies to all of them. A signature is never synthesized and never sent to a different origin.+- Tool-call id normalization is deterministic: the stored id when the target accepts it; otherwise+ `call_` + the first 24 hex characters of SHA-256 of the stored id. Anthropic accepts `^[a-zA-Z0-9_-]{1,64}$`; the+ other protocols' limits are recorded in the `ai` lane's conversion tables. The map is computed per request; the+ stored transcript is never rewritten.+- Every tool call in the request has exactly one result. A call without a stored result gets a synthetic result,+ `[tool call interrupted; no result recorded]`, with `is_error: true` (C-5 settles most such calls from the job handle+ first).+- Responses API requests use `store: false` and never `previous_response_id`.diff --git a/docs/plans/agent-core-contracts/hop-resolution.schema.json b/docs/plans/agent-core-contracts/hop-resolution.schema.jsonnew file mode 100644index 000000000..148c049fb--- /dev/null+++ b/docs/plans/agent-core-contracts/hop-resolution.schema.json@@ -0,0 +1,148 @@+{+ "$schema": "http://json-schema.org/draft-07/schema#",+ "$id": "agent-core/hop-resolution.schema.json",+ "title": "HopResolution",+ "description": "C-6 answer to 'how should the avibe backend call model M now'. Produced by Model Hub; consumed by the adapter, which builds C-2 ModelEndpoint from it. The token is in-memory only.",+ "type": "object",+ "required": [+ "backend",+ "requested_model",+ "protocol",+ "base_url",+ "token",+ "runtime_model",+ "source_id",+ "provider",+ "capabilities",+ "request_headers"+ ],+ "additionalProperties": false,+ "properties": {+ "backend": {+ "const": "avibe"+ },+ "requested_model": {+ "type": "string",+ "description": "Caller-facing model id from the Avibe Agent settings."+ },+ "protocol": {+ "$ref": "message.schema.json#/definitions/Protocol",+ "description": "Native protocol of the primary hop."+ },+ "base_url": {+ "type": "string",+ "format": "uri",+ "description": "Gateway frontend for `protocol`."+ },+ "token": {+ "type": "string"+ },+ "runtime_model": {+ "type": "string",+ "description": "Model id to put in the request."+ },+ "source_id": {+ "type": "string"+ },+ "provider": {+ "type": "string",+ "description": "Vendor identity of the primary hop; becomes `origin.provider` unless the served-hop report differs."+ },+ "request_headers": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ },+ "description": "Correlation metadata the gateway needs; always present, empty when there is none."+ },+ "capabilities": {+ "type": "object",+ "required": [+ "context_window",+ "input_limit",+ "max_output_tokens",+ "supports_tools",+ "supports_images",+ "supports_reasoning",+ "reasoning_efforts"+ ],+ "additionalProperties": false,+ "properties": {+ "context_window": {+ "type": [+ "integer",+ "null"+ ],+ "minimum": 1+ },+ "input_limit": {+ "type": [+ "integer",+ "null"+ ],+ "minimum": 1,+ "description": "When the provider caps input separately from the window."+ },+ "max_output_tokens": {+ "type": [+ "integer",+ "null"+ ],+ "minimum": 1+ },+ "supports_tools": {+ "type": [+ "boolean",+ "null"+ ]+ },+ "supports_images": {+ "type": [+ "boolean",+ "null"+ ]+ },+ "supports_reasoning": {+ "type": [+ "boolean",+ "null"+ ]+ },+ "reasoning_efforts": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ },+ "description": "Null means Model Hub does not know the value; it never guesses. supports_images is null when the model declares no input modalities."+ }+ },+ "examples": [+ {+ "backend": "avibe",+ "requested_model": "claude-opus-5-5",+ "protocol": "anthropic",+ "base_url": "http://127.0.0.1:47311/avibe/v1",+ "token": "<in-memory>",+ "runtime_model": "claude-opus-5-5",+ "source_id": "src_anthropic_main",+ "provider": "anthropic",+ "request_headers": {},+ "capabilities": {+ "context_window": 1000000,+ "input_limit": null,+ "max_output_tokens": 128000,+ "supports_tools": true,+ "supports_images": true,+ "supports_reasoning": true,+ "reasoning_efforts": [+ "low",+ "medium",+ "high",+ "xhigh"+ ]+ }+ }+ ]+}diff --git a/docs/plans/agent-core-contracts/job.schema.json b/docs/plans/agent-core-contracts/job.schema.jsonnew file mode 100644index 000000000..4b5dbd646--- /dev/null+++ b/docs/plans/agent-core-contracts/job.schema.json@@ -0,0 +1,143 @@+{+ "$schema": "http://json-schema.org/draft-07/schema#",+ "$id": "agent-core/job.schema.json",+ "title": "JobMeta",+ "description": "C-7 `meta.json` of a job handle. Written by the adapter's JobHost before the spawn; recovery invariants J1–J6 are in recovery.md. Read by the tool, Watch target kind `job`, recovery, and `vibe stop`. Persisted shape.",+ "type": "object",+ "required": [+ "version",+ "job_id",+ "session_id",+ "tool_call_id",+ "backend",+ "command",+ "cwd",+ "created_at",+ "state_dir",+ "deadline_at"+ ],+ "additionalProperties": false,+ "properties": {+ "version": {+ "const": 1+ },+ "job_id": {+ "type": "string",+ "pattern": "^job_[a-z0-9]+$"+ },+ "session_id": {+ "type": "string"+ },+ "tool_call_id": {+ "type": "string"+ },+ "backend": {+ "enum": [+ "pipe",+ "pty"+ ],+ "description": "v1 writes `pipe` only."+ },+ "command": {+ "type": "string"+ },+ "cwd": {+ "type": "string"+ },+ "timeout_s": {+ "type": [+ "number",+ "null"+ ]+ },+ "created_at": {+ "type": "string",+ "format": "date-time"+ },+ "state_dir": {+ "type": "string",+ "description": "Absolute job directory holding output.log and exit."+ },+ "process": {+ "type": [+ "object",+ "null"+ ],+ "description": "The identity fields of PersistedProcessIdentity (core/process_isolation.py) plus the process group, recorded before the command can run (J2).",+ "required": [+ "pid",+ "pgid",+ "create_time",+ "worker_fingerprint"+ ],+ "additionalProperties": false,+ "properties": {+ "pid": {+ "type": "integer"+ },+ "pgid": {+ "type": "integer"+ },+ "create_time": {+ "type": "number"+ },+ "worker_fingerprint": {+ "type": "string"+ }+ }+ },+ "terminal": {+ "type": [+ "object",+ "null"+ ],+ "description": "Reserved for the `pty` backend; null for `pipe`.",+ "properties": {+ "socket": {+ "type": "string"+ },+ "target": {+ "type": "string"+ }+ }+ },+ "watch_id": {+ "type": [+ "string",+ "null"+ ],+ "description": "Set at handover."+ },+ "deadline_at": {+ "type": [+ "string",+ "null"+ ],+ "format": "date-time",+ "description": "Absolute time at which the job's process tree is killed (from `timeout`); enforced by whichever component owns the job (J3)."+ }+ },+ "examples": [+ {+ "version": 1,+ "job_id": "job_31c",+ "session_id": "ses7k2m9p4q1x",+ "tool_call_id": "toolu_01AbC",+ "backend": "pipe",+ "command": "pytest -q",+ "cwd": "/work/repo",+ "timeout_s": null,+ "created_at": "2026-10-02T04:12:09.512Z",+ "state_dir": "/home/u/.avibe/state/agent_core/jobs/job_31c",+ "process": {+ "pid": 48211,+ "pgid": 48211,+ "create_time": 1790914329.51,+ "worker_fingerprint": "sha256:5f1c…"+ },+ "terminal": null,+ "watch_id": "wch_8f2k",+ "deadline_at": null+ }+ ]+}diff --git a/docs/plans/agent-core-contracts/loop-control.md b/docs/plans/agent-core-contracts/loop-control.mdnew file mode 100644index 000000000..99c943838--- /dev/null+++ b/docs/plans/agent-core-contracts/loop-control.md@@ -0,0 +1,105 @@+# C-3 Loop control++The loop in `core/agent_core/agent/`. Semantics are the ones the bare-loop spike and Pi passed in the control matrix+(evaluation §1).++## 1. Surface++```python+class Agent:+ def __init__(self, *, models: ModelRouter, tools: Sequence[Tool], hooks: Sequence[Hooks],+ store: TranscriptStore, jobs: JobHost) -> None: ...++ def run(self, input: Input, *, turn_id: str) -> AsyncIterator[AgentEvent]: ... # one Avibe Turn+ def steer(self, input: Input) -> bool: ... # False: not accepted, the adapter keeps ownership+ def follow_up(self, input: Input) -> bool: ...+ def abort(self, reason: str) -> None: ...+ def set_tools(self, tools: Sequence[Tool]) -> None: ...+ def snapshot(self) -> Snapshot: ...+```++`Input` pairs a `UserMessage` with its `messages.id` row. `ModelRouter` returns the `ModelEndpoint` and+`ModelCapabilities` for the next call (C-2, C-6 via the adapter); `TranscriptStore` is C-5; `JobHost` is C-7. The loop+wraps the given `JobHost` (`Agent.jobs`) to track foreground jobs for `abort`; tools are constructed with that+wrapper.++## 2. One run++```text+commit input → loop:+ before_model hooks → provider stream (events out)+ if the response has tool calls:+ commit it as `assistant`+ for each call, in order: before_tool → execute → after_tool → commit tool result+ drain steers (commit each) → continue loop+ else, holding the queue lock:+ if a steer or follow-up is pending: commit the response as `assistant`, commit the pending inputs,+ release the lock → continue loop+ else: commit the response as `result` (final) and close the queues for this run, release the lock → end+```++Finality is decided before the response row is inserted, so a `result` row is always the run's last response. A final+response with `stop_reason` `refusal` or `safety` and no text is still committed as `result`; its rendered display text+is the localized explanation, written in the same transaction, so re-delivery after a crash shows it too. The run also+ends with an `error` event of that kind. Refusal text from the provider is kept as the reply. A+steer that arrives after the queues closed is refused by the running Turn, and Avibe's delivery falls back to the P3+queue, which starts the next run.++Tool calls in one response execute sequentially in call order in v1; results are always committed in call order.++## 3. Hooks++Hooks run in registration order. The first `deny` or `end` wins; rewrites compose in order.++| Hook | Receives | May return |+| --- | --- | --- |+| `before_run` | input message, run context | system prompt and tool set for this run |+| `before_model` | the `ModelRequest` about to be sent | a replacement request (transient rewrite of messages, system, tools, model, max tokens), or `end` |+| `after_model` | the committed assistant message | `skip_tools` (commit error results `[skipped by policy]` for its calls), or `end` |+| `before_tool` | the tool call | `deny(reason)` (error result with the reason), `alter_args(args)`, or `end` |+| `after_tool` | call and result | `alter_result(result)` before commit, or `end` |+| `after_run` | outcome | nothing |++A `before_model` rewrite changes only that request and is not persisted by design: a rewritten request is not+reconstructible from the rows, and A10 is stated for requests without a transient rewrite. Anything that must survive a+restart, or that context management must see, goes through C-5 rows (`context_edit`, `context_compaction`). `end` finishes the run after the current step commits.++## 4. Steer, follow-up, abort++- `steer(m)` queues `m`. It enters the context after the current tool batch and before the next model call, or, when+ the current response has no tool calls, it starts another model call in the same run. A steer never interrupts a+ running tool. Avibe P1 deliveries map to `steer`.+- `follow_up(m)` enters only when the run would otherwise end. It exists for hooks and the future tension system;+ Avibe's P3 queue starts a new run after the Turn settles instead.+- `abort(reason)` cancels the provider stream and the running tool: a foreground job's process tree is killed (Pi's+ behavior). Jobs already handed to Watch are not affected. The run ends with `run_ended{reason: "aborted"}`; what was+ committed stays committed.+- A tool result with `terminate: true` ends the run after the batch commits.++## 5. Tools per call++`set_tools` and a `before_model` rewrite take effect at the next model call. A call to a tool that is not in the set+sent with that request gets the error result `Tool <name> is not available.`++## 6. Agent events (C-4)++`run()` yields `agent-event.schema.json` events, keyed by `turn_id`. The adapter maps them onto existing Avibe concepts; no new UI nouns.++| Event | Avibe effect |+| --- | --- |+| `run_started` | none; the Turn was opened by its delivery |+| `text_delta`, `thinking_delta` | streaming progress (status bubble, Workbench live text) |+| `message_committed` | the committed `messages` row is delivered: `assistant` as activity, `result` as the reply |+| `tool_started` | `agent_events` `tool_call` trace row; IM progress line |+| `tool_progress` | status bubble update |+| `tool_finished` | the committed `tool_result` row; a handed-over job names its Watch |+| `steer_applied` | the steer delivery is accepted into the running Turn |+| `compaction_started`, `compaction_finished`, `compaction_failed` | optional status line; failures always reported |+| `run_ended` | `MessageOutput` settles the Turn |+| `error` | `notify` / `error` row; the text shown is the adapter's localized copy for the event's `kind` (`vibe/i18n`), and `message` is diagnostic detail, never display copy |++## 7. Snapshot and fork++`snapshot()` returns `(session_id, context_seq, state)`, where `state` is the JSON object hooks keep. A hook that sets+state causes an `agent_state` row at the next commit point (C-5), so a fork starting at a later `context_seq` restores+it. Forking is Avibe's existing Session fork; the child's context resolves through C-5.diff --git a/docs/plans/agent-core-contracts/message.schema.json b/docs/plans/agent-core-contracts/message.schema.jsonnew file mode 100644index 000000000..804f2de63--- /dev/null+++ b/docs/plans/agent-core-contracts/message.schema.json@@ -0,0 +1,430 @@+{+ "$schema": "http://json-schema.org/draft-07/schema#",+ "$id": "agent-core/message.schema.json",+ "title": "Message",+ "description": "C-1 canonical message. Vendor-neutral; provider adapters convert to and from the wire protocol. Produced by `ai` (assistant messages), the adapter (user messages), and `tools` via `agent` (tool results); consumed by `agent`, `harness`, and the adapter.",+ "oneOf": [+ {+ "$ref": "#/definitions/UserMessage"+ },+ {+ "$ref": "#/definitions/AssistantMessage"+ },+ {+ "$ref": "#/definitions/ToolResultMessage"+ }+ ],+ "definitions": {+ "Protocol": {+ "enum": [+ "anthropic",+ "openai_chat",+ "openai_responses",+ "google"+ ],+ "description": "Wire protocol, in Model Hub's vocabulary extended by C-6."+ },+ "Origin": {+ "type": "object",+ "required": [+ "provider",+ "api",+ "model"+ ],+ "additionalProperties": false,+ "description": "Who produced an assistant message, taken from the served-hop report (C-6), not from the request. Two origins are the same only when all three fields are equal.",+ "properties": {+ "provider": {+ "type": "string",+ "minLength": 1,+ "description": "Upstream vendor identity of the served hop, for example `anthropic`, `openai`, `google`, `deepseek`."+ },+ "api": {+ "$ref": "#/definitions/Protocol"+ },+ "model": {+ "type": "string",+ "minLength": 1,+ "description": "Upstream model id of the served hop."+ }+ }+ },+ "LargeRef": {+ "type": "object",+ "required": [+ "ref",+ "bytes"+ ],+ "additionalProperties": false,+ "description": "Reserved reference form for content stored outside the row. v1 writers never produce it; v1 readers must reject it with a clear error rather than misread it.",+ "properties": {+ "ref": {+ "type": "string",+ "pattern": "^sha256:[0-9a-f]{64}$"+ },+ "bytes": {+ "type": "integer",+ "minimum": 0+ }+ }+ },+ "TextBlock": {+ "type": "object",+ "required": [+ "type"+ ],+ "additionalProperties": false,+ "properties": {+ "type": {+ "const": "text"+ },+ "text": {+ "type": "string"+ },+ "ref": {+ "$ref": "#/definitions/LargeRef"+ }+ },+ "oneOf": [+ {+ "required": [+ "text"+ ]+ },+ {+ "required": [+ "ref"+ ]+ }+ ]+ },+ "ImageBlock": {+ "type": "object",+ "required": [+ "type",+ "mime_type",+ "media_token"+ ],+ "additionalProperties": false,+ "properties": {+ "type": {+ "const": "image"+ },+ "mime_type": {+ "enum": [+ "image/png",+ "image/jpeg",+ "image/gif",+ "image/webp"+ ]+ },+ "media_token": {+ "type": "string",+ "description": "`media_objects.token` of an immutable, content-addressed snapshot taken when the block is created; bytes are loaded by the adapter's MediaLoader at request time, never inlined in the transcript. The same block always yields the same bytes, even if the original file changes or is deleted."+ },+ "name": {+ "type": "string"+ }+ }+ },+ "ThinkingBlock": {+ "type": "object",+ "required": [+ "type",+ "text"+ ],+ "additionalProperties": false,+ "properties": {+ "type": {+ "const": "thinking"+ },+ "text": {+ "type": "string",+ "description": "Visible reasoning text or summary; may be empty for redacted reasoning."+ },+ "signature": {+ "type": [+ "string",+ "null"+ ],+ "description": "Opaque provider payload in the adapter's own encoding: the Anthropic signature, OpenAI encrypted reasoning, the Gemini thought signature, or, for a redacted block, the whole redacted payload (Anthropic `redacted_thinking.data`). Replayed only to the same origin; never synthesized."+ },+ "redacted": {+ "type": "boolean",+ "default": false,+ "description": "True for reasoning the provider returned only in opaque form; `text` is empty and `signature` holds the payload."+ }+ },+ "if": {+ "properties": {+ "redacted": {+ "const": true+ }+ },+ "required": [+ "redacted"+ ]+ },+ "then": {+ "required": [+ "signature"+ ],+ "properties": {+ "signature": {+ "type": "string",+ "minLength": 1+ },+ "text": {+ "const": ""+ }+ }+ }+ },+ "ToolCallBlock": {+ "type": "object",+ "required": [+ "type",+ "id",+ "name",+ "arguments"+ ],+ "additionalProperties": false,+ "properties": {+ "type": {+ "const": "tool_call"+ },+ "id": {+ "type": "string",+ "minLength": 1,+ "description": "Canonical id, stable for the life of the session."+ },+ "name": {+ "type": "string",+ "minLength": 1+ },+ "arguments": {+ "type": "object",+ "description": "Parsed arguments. A call whose arguments did not parse is kept with `{}` and answered with an error tool result."+ },+ "native_id": {+ "type": "string",+ "description": "The id as the provider emitted it, when it differs from `id`."+ },+ "signature": {+ "type": [+ "string",+ "null"+ ],+ "description": "Opaque provider payload attached to the call (Gemini `thoughtSignature` on a function-call part). Same rules as a thinking signature: replayed only to the same origin, never synthesized."+ }+ }+ },+ "Usage": {+ "type": "object",+ "required": [+ "input_tokens",+ "output_tokens",+ "cache_read_tokens",+ "cache_write_tokens"+ ],+ "additionalProperties": false,+ "properties": {+ "input_tokens": {+ "type": "integer",+ "minimum": 0,+ "description": "Uncached input tokens."+ },+ "output_tokens": {+ "type": "integer",+ "minimum": 0+ },+ "cache_read_tokens": {+ "type": "integer",+ "minimum": 0+ },+ "cache_write_tokens": {+ "type": "integer",+ "minimum": 0+ },+ "reasoning_tokens": {+ "type": "integer",+ "minimum": 0,+ "description": "Subset of output tokens, when the provider reports it."+ }+ }+ },+ "StopReason": {+ "enum": [+ "stop",+ "length",+ "tool_use",+ "refusal",+ "safety",+ "aborted",+ "error"+ ],+ "description": "Normalized. `refusal` and `safety` are never folded into `stop`."+ },+ "UserMessage": {+ "type": "object",+ "required": [+ "role",+ "content"+ ],+ "additionalProperties": false,+ "properties": {+ "role": {+ "const": "user"+ },+ "content": {+ "type": "array",+ "minItems": 1,+ "items": {+ "oneOf": [+ {+ "$ref": "#/definitions/TextBlock"+ },+ {+ "$ref": "#/definitions/ImageBlock"+ }+ ]+ }+ }+ }+ },+ "AssistantMessage": {+ "type": "object",+ "required": [+ "role",+ "content",+ "origin",+ "stop_reason"+ ],+ "additionalProperties": false,+ "properties": {+ "role": {+ "const": "assistant"+ },+ "content": {+ "type": "array",+ "description": "Blocks in the order the model produced them.",+ "items": {+ "oneOf": [+ {+ "$ref": "#/definitions/TextBlock"+ },+ {+ "$ref": "#/definitions/ThinkingBlock"+ },+ {+ "$ref": "#/definitions/ToolCallBlock"+ }+ ]+ }+ },+ "origin": {+ "$ref": "#/definitions/Origin"+ },+ "usage": {+ "$ref": "#/definitions/Usage"+ },+ "stop_reason": {+ "$ref": "#/definitions/StopReason"+ },+ "error_message": {+ "type": "string",+ "description": "Present when `stop_reason` is `error` or `aborted`."+ }+ }+ },+ "ToolResultMessage": {+ "type": "object",+ "required": [+ "role",+ "tool_call_id",+ "tool_name",+ "content",+ "is_error"+ ],+ "additionalProperties": false,+ "properties": {+ "role": {+ "const": "tool_result"+ },+ "tool_call_id": {+ "type": "string",+ "minLength": 1+ },+ "tool_name": {+ "type": "string",+ "minLength": 1+ },+ "content": {+ "type": "array",+ "items": {+ "oneOf": [+ {+ "$ref": "#/definitions/TextBlock"+ },+ {+ "$ref": "#/definitions/ImageBlock"+ }+ ]+ },+ "description": "Exactly what the model sees, after output governance (C-7)."+ },+ "is_error": {+ "type": "boolean"+ }+ }+ }+ },+ "examples": [+ {+ "role": "assistant",+ "content": [+ {+ "type": "thinking",+ "text": "The failing test imports a renamed helper.",+ "signature": "EqQBCkYIBxgCKkD…"+ },+ {+ "type": "text",+ "text": "运行测试看看。"+ },+ {+ "type": "tool_call",+ "id": "toolu_01AbC",+ "name": "bash",+ "arguments": {+ "command": "pytest tests/test_paths.py -q"+ }+ }+ ],+ "origin": {+ "provider": "anthropic",+ "api": "anthropic",+ "model": "claude-opus-5-5"+ },+ "usage": {+ "input_tokens": 1834,+ "output_tokens": 212,+ "cache_read_tokens": 40210,+ "cache_write_tokens": 0+ },+ "stop_reason": "tool_use"+ },+ {+ "role": "tool_result",+ "tool_call_id": "toolu_01AbC",+ "tool_name": "bash",+ "content": [+ {+ "type": "text",+ "text": "1 failed, 12 passed in 0.84s\n\nCommand exited with code 1"+ }+ ],+ "is_error": true+ }+ ]+}diff --git a/docs/plans/agent-core-contracts/model-hub-consumer.md b/docs/plans/agent-core-contracts/model-hub-consumer.mdnew file mode 100644index 000000000..a739fa838--- /dev/null+++ b/docs/plans/agent-core-contracts/model-hub-consumer.md@@ -0,0 +1,43 @@+# C-6 Model Hub consumer extension++What the Avibe Agent needs from Model Hub. Owned by Model Hub (`../model-hub-contracts/`); this file states the+consumer's requirements, and the Model Hub lane lands the change in both places.++## 1. Today++- Source `protocol` and backend `native_protocol` know `anthropic`, `openai_responses`, and `openai_chat`.+- `ModelHubLaunch` (`modules/agents/model_hub.py`) gives a consumer `gateway_base_url`, `gateway_token`,+ `gateway_request_metadata`, `runtime_model`, `context_window`, `max_output_tokens`, `supports_tools`,+ `supports_reasoning`, and `reasoning_efforts`, but not the protocol to speak.+- The gateway exposes `/<backend>/v1/{messages | chat/completions | responses}` and converts when the frontend protocol+ differs from the hop's. It fails over only before the first user-visible model output byte; after that a failure is+ terminal.++## 2. Required++1. **`google` protocol.** Gemini `generateContent` / `streamGenerateContent` joins the protocol vocabulary and gets a+ gateway frontend under the backend prefix.+2. **Backend id `avibe`** in every Model Hub enum that lists backends (C-8).+3. **Hop resolution** for the `avibe` backend returns `HopResolution` (`hop-resolution.schema.json`) through the Model+ Hub runtime router: the primary hop's protocol, the gateway URL for that protocol, the token, the runtime model,+ and capabilities. A capability Model Hub does not know is `null`, never guessed; `input_limit` is `null` until Model+ Hub stores one. The agent treats unknown values conservatively (C-2). It resolves once per run and again after a+ retryable error.+4. **Served-hop report.** Every gateway response for `avibe` carries `x-avibe-served-hop`: compact, ASCII-escaped JSON+ with exactly `provider`, `api`, `model`, taken from the winning attempt (Source vendor, Source protocol, upstream+ target) and sent before the first model byte. The gateway does not commit early keepalive headers for `avibe`;+ other backends are unchanged. The same origin is recorded on `TurnProvenance.served`. An `api` different from the+ frontend protocol means the gateway converted. The agent records it as the message `origin` (C-1). The header value is at most 4096 bytes; a hop whose origin cannot be represented within that limit is+ refused before invocation with a controlled local error (no model call, no header). Identifiers are never truncated.+5. **Conversion stays a fallback.** The agent speaks the primary hop's protocol. When failover reaches a hop with+ another protocol, the gateway converts (degraded, not broken) and the served-hop report says so.+6. **No opaque payload crosses origins at failover.** The agent builds the request for the primary hop's origin, so it+ may carry that origin's opaque payloads (C-1: any block's signature, redacted thinking). When the gateway fails+ over to a hop whose origin `(provider, api, model)` differs from the primary's, it removes every such payload+ before sending, applying the same rule as `cross-provider.md`, whether or not it converts protocols. Known limit:+ the next request targets the primary origin again, so payloads returned by a fallback origin are not replayed if a+ later request fails over to that same fallback; a provider that then rejects the call surfaces as a provider error.++## 3. Not required++Failover, credentials, quota, and Source health stay in Model Hub. The agent never contacts a vendor directly.diff --git a/docs/plans/agent-core-contracts/provider-event.schema.json b/docs/plans/agent-core-contracts/provider-event.schema.jsonnew file mode 100644index 000000000..81f0674ff--- /dev/null+++ b/docs/plans/agent-core-contracts/provider-event.schema.json@@ -0,0 +1,57 @@+{+ "$schema": "http://json-schema.org/draft-07/schema#",+ "$id": "agent-core/provider-event.schema.json",+ "title": "ProviderEvent",+ "description": "C-2 stream event yielded by ProviderAdapter.stream. A stream yields any number of deltas and ends with exactly one `done` or `error`. `index` is the position of the block in the final message content.",+ "oneOf": [+ {+ "type": "object",+ "required": ["type", "index", "delta"],+ "additionalProperties": false,+ "properties": { "type": { "enum": ["text_delta", "thinking_delta"] }, "index": { "type": "integer", "minimum": 0 }, "delta": { "type": "string" } }+ },+ {+ "type": "object",+ "required": ["type", "index", "id", "name"],+ "additionalProperties": false,+ "properties": { "type": { "const": "tool_call_start" }, "index": { "type": "integer", "minimum": 0 }, "id": { "type": "string" }, "name": { "type": "string" } }+ },+ {+ "type": "object",+ "required": ["type", "index", "arguments_delta"],+ "additionalProperties": false,+ "properties": { "type": { "const": "tool_call_delta" }, "index": { "type": "integer", "minimum": 0 }, "arguments_delta": { "type": "string", "description": "Raw JSON fragment." } }+ },+ {+ "type": "object",+ "required": ["type", "index"],+ "additionalProperties": false,+ "properties": { "type": { "const": "block_end" }, "index": { "type": "integer", "minimum": 0 } }+ },+ {+ "type": "object",+ "required": ["type", "message"],+ "additionalProperties": false,+ "properties": { "type": { "const": "done" }, "message": { "$ref": "message.schema.json#/definitions/AssistantMessage" } }+ },+ {+ "type": "object",+ "required": ["type", "kind", "retryable", "message"],+ "additionalProperties": false,+ "properties": {+ "type": { "const": "error" },+ "kind": { "enum": ["overflow", "rate_limit", "overloaded", "network", "server", "auth", "invalid_request", "aborted", "unknown"] },+ "retryable": { "type": "boolean" },+ "retry_after_s": { "type": "number", "minimum": 0 },+ "status": { "type": "integer", "description": "HTTP status, when there was one." },+ "message": { "type": "string", "description": "Provider message with credentials removed." },+ "partial": { "$ref": "message.schema.json#/definitions/AssistantMessage", "description": "What streamed before the error, with stop_reason `error` or `aborted`; never replayed as a valid response." }+ }+ }+ ],+ "examples": [+ { "type": "tool_call_start", "index": 2, "id": "toolu_01AbC", "name": "bash" },+ { "type": "tool_call_delta", "index": 2, "arguments_delta": "{\"command\":\"pytest" },+ { "type": "error", "kind": "overflow", "retryable": false, "status": 400, "message": "prompt is too long: 213042 tokens > 200000 maximum" }+ ]+}diff --git a/docs/plans/agent-core-contracts/provider.md b/docs/plans/agent-core-contracts/provider.mdnew file mode 100644index 000000000..034c6a4b7--- /dev/null+++ b/docs/plans/agent-core-contracts/provider.md@@ -0,0 +1,84 @@+# C-2 Provider adapter interface++One adapter per protocol in `core/agent_core/ai/`. Adapters speak HTTP to the endpoint they are given and know nothing+about Model Hub routing.++```python+class ProviderAdapter(Protocol):+ protocol: Literal["anthropic", "openai_chat", "openai_responses", "google"]++ def stream(self, request: ModelRequest, cancel: CancelToken) -> AsyncIterator[ProviderEvent]: ...+++@dataclass(frozen=True)+class ModelEndpoint: # built by the adapter layer from C-6 HopResolution+ protocol: str+ base_url: str+ token: str # field(repr=False): never logged or rendered, never written to the transcript+ model_id: str # the runtime model id to send+ request_headers: Mapping[str, str]+ provider: str # vendor identity of the hop (HopResolution.provider); with protocol and model it+ # forms the target origin for the cross-provider rules+++@dataclass(frozen=True)+class ModelCapabilities: # from C-6 HopResolution; None means Model Hub does not know+ context_window: int | None+ input_limit: int | None+ max_output_tokens: int | None+ supports_tools: bool | None+ supports_images: bool | None+ supports_reasoning: bool | None+ reasoning_efforts: tuple[str, ...]+++class MediaLoader(Protocol): # supplied by the adapter; reads media_objects+ async def load(self, media_token: str) -> tuple[bytes, str]: ... # bytes, mime type+++@dataclass(frozen=True)+class ModelRequest:+ endpoint: ModelEndpoint+ system: str+ messages: Sequence[Message] # canonical (C-1); the adapter applies cross-provider.md+ tools: Sequence[ToolSpec] # C-7; may differ on every call+ max_tokens: int+ reasoning_effort: str | None # one of the hop's declared efforts, or None+ cache: Literal["default", "none"] # "none" for the compaction summarizer+ supports_images: bool # resolved by the loop; unknown capability counts as False+```++The loop's `ModelRouter` returns the `ModelEndpoint` together with its `ModelCapabilities`. Every capability has a+defined effect, including when it is unknown:++| Capability | `true` / value | `false` | unknown (`null`) |+| --- | --- | --- | --- |+| `context_window` | W for C-9 | — | the configured default window (128,000) |+| `max_output_tokens` | upper bound for `max_tokens` | — | the configured default (8,192) |+| `supports_tools` | tools sent | the route is refused before the run with a clear error: the agent needs tools | tools sent; a provider rejection surfaces as an error |+| `supports_images` | images sent | placeholders | placeholders |+| `supports_reasoning` | `reasoning_effort` sent if it is one of `reasoning_efforts` | `reasoning_effort = None` | `reasoning_effort = None` | Adapters are constructed with a+`MediaLoader` and resolve each `ImageBlock`'s bytes at request time; the canonical message never carries bytes. The+token names an immutable snapshot (`message.schema.json`), so the bytes never change for a committed block.++`stream` yields `ProviderEvent`s (`provider-event.schema.json`) and always ends with exactly one `done` or one+`error`. `done.message` is the complete canonical `AssistantMessage`; its `origin` comes from the served-hop report+(C-6), which the gateway sends as the `x-avibe-served-hop` response header: compact JSON with exactly `provider`,+`api`, `model`, before the first model byte. On the direct channel (no gateway) the endpoint is the served hop. When a gateway response carries no+served-hop report, the origin is unverified: the adapter commits the message with every opaque provider payload+removed (the `signature` of every block of any kind, and redacted thinking), keeping the endpoint as `origin`, so no+opaque payload of an unknown vendor can ever be replayed. A block without a signature is always sent without one+(`cross-provider.md`).++Error classification is part of the contract because the loop branches on it:++| `kind` | Meaning | Loop action |+| --- | --- | --- |+| `overflow` | the request exceeded the model's context (Pi's overflow patterns, HTTP 413, `context_length_exceeded`) | overflow recovery (plan §5.2) |+| `rate_limit`, `overloaded`, `network`, `server` | transient | retry with backoff, honoring `retry_after_s`, only when nothing was streamed (no deltas, no `partial`), at most 3 retries within 120 s; then the run ends with that error. After streamed output the error is terminal for the request, matching Model Hub's first-byte rule |+| `auth`, `invalid_request` | not retryable | end the run with the error |+| `aborted` | cancelled by the caller | end the run as aborted |+| `unknown` | anything else | end the run with the error |++The `ai` lane adds a conversion table per protocol (request fields, stream events, stop reasons, usage fields) to this+directory with its first PR; its tests enumerate the tables.diff --git a/docs/plans/agent-core-contracts/recovery.md b/docs/plans/agent-core-contracts/recovery.mdnew file mode 100644index 000000000..4a677304f--- /dev/null+++ b/docs/plans/agent-core-contracts/recovery.md@@ -0,0 +1,48 @@+# Recovery invariants (C-5, C-7)++These are properties, not mechanisms. Each invariant names the lane that owns it and the test that proves it; the+mechanism lives in that lane's code, where the test can exercise every crash point. A contract change is needed only+when a mechanism needs a field another lane reads; those fields are listed in the last section.++General rule: every external effect records its intent durably before the effect and its outcome durably after it,+and recovery reconciles intents that have no outcome. An effect on a system without an idempotency key is+at-least-once, and that is stated where it applies.++## Jobs (`tools` lane; Watch `job` target in the adapter wave)++| ID | Invariant | Proof |+| --- | --- | --- |+| J1 | A command starts at most once, and recovery can always decide whether it may have started. A missing or late file never proves that it did not. | crash injected at every step of the launch, then recovery; the command's side effect (a counter file) is at most 1, and recovery's verdict matches it |+| J2 | Before a command can run, the job record holds an identity that distinguishes its process tree from a recycled pid, so recovery can inspect and kill exactly that tree. | kill and inspect after a simulated pid reuse |+| J3 | A `timeout` holds across handover and vibe restarts: the deadline is absolute and recorded with the job, and whichever component owns the job when it passes kills the tree. | timeout shorter than the foreground window with `watch: true`, and with a restart in between |+| J4 | Output on disk is bounded per job (head and tail kept, middle dropped beyond a fixed cap), and every result or follow-up built from a truncated log says so. | a command producing more than the cap |+| J5 | Job files are kept until the owning tool call has a durable `tool_result` and the Watch that owns the job, if any, has settled. | an exited job whose call is unsettled is never removed |+| J6 | Handover is idempotent per job: one job has at most one Watch, whatever crashes in between. | crash between Watch creation and committing the handover result, then recovery |++## Tool calls (`loop` lane)++| ID | Invariant | Proof |+| --- | --- | --- |+| T1 | `project()` reads only committed rows; the same rows always produce the same request. | projection before and after job state changes |+| T2 | At resume, before the first projection, every tool call without a committed `tool_result` gets exactly one, chosen from its job state (exited: the output; running: handover; never ran: the interrupted result). A call without job state (`write`, `edit`) gets `[tool call interrupted; it may or may not have completed; re-read the file before continuing]`. Retries settle nothing twice. | crash between settlement steps, then resume twice |+| T3 | Inputs accepted by `steer` or `follow_up` are never dropped: they enter the context or are returned to the adapter for the P3 queue, including after a crash (the adapter re-queues accepted but unconsumed inputs at resume). | a terminating tool while a steer is queued; a crash before consumption |+| T4 | An unsettled Turn found at startup is settled as interrupted after T2; the agent never continues it on its own (a hook `end`, an abort, or a crash all leave the same safe state). The user's next message starts a new Turn with the full context. | crash after an `end` hook and after a mid-turn commit |++## Delivery (adapter wave)++| ID | Invariant | Proof |+| --- | --- | --- |+| D1 | A committed response is delivered completely: every part a surface splits it into is either confirmed or retried. A partial delivery is never recorded as delivered. | failure on a later part, and a crash between parts |+| D2 | Workbench delivery is exactly once (the row is the message). IM delivery is at least once per part: `BaseIMClient.send_message` has no idempotency key, so a crash after the platform accepted a part but before its receipt was committed resends that part. | crash after accept, before receipt |++Today `core/message_dispatcher.py` swallows failures of later split chunks and returns the first chunk's id. The+adapter wave must not reuse that path as is for agent rows; D1 is the requirement it meets.++## Shared fields++The only cross-lane shapes recovery adds:++- `meta.json` (`job.schema.json`): `deadline_at` (absolute, nullable), and `process` with the identity fields of+ `PersistedProcessIdentity` (`core/process_isolation.py`), recorded before the command can run (J2).+- Watch `job` target: keyed by `job_id`, created by adopt-or-create (J6).+- Response rows: `metadata_json.delivery` with one entry per part (`transcript.md` §2).diff --git a/docs/plans/agent-core-contracts/tools.md b/docs/plans/agent-core-contracts/tools.mdnew file mode 100644index 000000000..e9f7fee96--- /dev/null+++ b/docs/plans/agent-core-contracts/tools.md@@ -0,0 +1,198 @@+# C-7 Tools++The coding tools in `core/agent_core/tools/`. Names, parameters, logic, and model-facing text follow Pi+(`packages/coding-agent/src/core/tools/` at `7fbbd5f`, MIT, Copyright (c) 2025 Mario Zechner); strings quoted below+are Pi's unless marked as an Avibe addition. tau 0.4.7 (MIT, Copyright (c) 2026 Alejandro AO) is the Python+reference. One tool set serves every model.++## 1. Constants++| Name | Value |+| --- | --- |+| `MAX_LINES` | 2,000 |+| `MAX_BYTES` | 51,200 (50 KB) |+| Foreground window for `bash` before handover to Watch | 120 s, configurable (Avibe) |++## 2. `read`++Description: `Read the contents of a file. Supports text files and images (jpg, png, gif, webp). Images are sent+as attachments. For text files, output is truncated to 2000 lines or 50KB (whichever is hit first). Use offset/limit+for large files. When you need the full file, continue with offset until complete.`++```json+{+ "type": "object",+ "required": ["path"],+ "properties": {+ "path": { "type": "string", "description": "Path to the file to read (relative or absolute)" },+ "offset": { "type": "integer", "minimum": 1, "description": "Line number to start reading from (1-indexed)" },+ "limit": { "type": "integer", "minimum": 1, "description": "Maximum number of lines to read" }+ }+}+```++Raw text, no line numbers, head kept. Model-facing suffixes:++- `[Showing lines {start}-{end} of {total}. Use offset={next} to continue.]`+- `[Showing lines {start}-{end} of {total} (50KB limit). Use offset={next} to continue.]`+- `[{remaining} more lines in file. Use offset={next} to continue.]` (an explicit `limit` stopped before the end)+- `[Line {n} is {size}, exceeds 50KB limit. Use bash: sed -n '{n}p' {quoted_path} | head -c 51200]`, where+ `{quoted_path}` is the path shell-quoted (Avibe change to Pi's text, so the suggested command is always safe to run)+- Error: `Offset {offset} is beyond end of file ({total} lines total)`++Images are attached as `ImageBlock`s (C-1); for a model without image input the result says so and omits the image.+Avibe changes to Pi's text: `bmp` is not listed because v1 does not convert it, and there is no resizing (no image+dependency); oversized images are refused with a message.++## 3. `write`++Description: `Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically+creates parent directories.`++```json+{+ "type": "object",+ "required": ["path", "content"],+ "properties": {+ "path": { "type": "string", "description": "Path to the file to write (relative or absolute)" },+ "content": { "type": "string", "description": "Content to write to the file" }+ }+}+```++Result: `Successfully wrote to {path}`. Writes are serialized per canonical path with `edit`.++## 4. `edit`++Description: `Edit a single file using exact text replacement. Every edits[].oldText must match a unique,+non-overlapping region of the original file. If two changes affect the same block or nearby lines, merge them into+one edit instead of emitting overlapping edits. Do not include large unchanged regions just to connect distant+changes.`++```json+{+ "type": "object",+ "required": ["path", "edits"],+ "properties": {+ "path": { "type": "string", "description": "Path to the file to edit (relative or absolute)" },+ "edits": {+ "type": "array",+ "minItems": 1,+ "description": "One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits. If two changes touch the same block or nearby lines, merge them into one edit instead.",+ "items": {+ "type": "object",+ "required": ["oldText", "newText"],+ "properties": {+ "oldText": { "type": "string", "description": "Exact text for one targeted replacement. It must be unique in the original file unless replaceAll is true, and must not overlap with any other edits[].oldText in the same call." },+ "newText": { "type": "string", "description": "Replacement text for this targeted edit." },+ "replaceAll": { "type": "boolean", "description": "Replace every occurrence of oldText instead of requiring exactly one. Defaults to false." }+ }+ }+ }+ }+}+```++`replaceAll` is an Avibe addition (from Claude Code and OpenCode); the `oldText` description gains "unless replaceAll+is true". Logic, from Pi's `edit-diff.ts`:++1. Read the file inside the per-path mutation lock; strip the BOM; remember the line-ending style; normalize to LF.+2. For each edit, find `oldText` exactly; if absent, find it after Pi's deterministic normalization (NFKC, trailing+ whitespace per line, smart quotes to ASCII, Unicode dashes to `-`, special spaces to a space). No similarity+ threshold.+3. Require exactly one occurrence unless `replaceAll`; reject empty `oldText`; reject overlapping spans, including+ any occurrence matched by a `replaceAll` item.+4. Apply all edits against the original, restore line endings and BOM, write once. Nothing is written if any edit+ fails.++Result: `Successfully replaced {n} block(s) in {path}.`; the diff goes to `details` for display only. Errors:++- `Could not find edits[{i}] in {path}. The oldText must match exactly including all whitespace and newlines.`+- `Found {count} occurrences of edits[{i}] in {path}. Each oldText must be unique. Please provide more context to make it unique.`+- `edits[{a}] and edits[{b}] overlap in {path}. Merge them into one edit or target disjoint regions.`+- `edits[{i}].oldText must not be empty in {path}.`++## 5. `bash`++Description: `Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated+to last 2000 lines or 50KB (whichever is hit first). If truncated, the output log is saved to a file; very large logs+keep their beginning and end. Optionally provide a timeout in seconds.` (Avibe change to Pi's last-but-one sentence,+because the on-disk log is bounded.) Avibe appends: `Commands still running after 120 seconds, or started with watch=true,+continue in the background as an Avibe Watch; you get a follow-up message when they finish.`++```json+{+ "type": "object",+ "required": ["command"],+ "properties": {+ "command": { "type": "string", "description": "Shell command to execute" },+ "timeout": { "type": "number", "description": "Timeout in seconds (optional, no default timeout)" },+ "watch": { "type": "boolean", "description": "Start the command as a background Watch and return immediately. Defaults to false." }+ }+}+```++`watch` is an Avibe addition. Behavior:++- stdin is closed; stdout and stderr are merged into the job's `output.log`; the tool follows the file for progress.+- The tail is kept: `[Showing lines {start}-{end} of {total}. Full output: {path}]`, or with ` (50KB limit)` when the+ byte cap applied, or `[Showing last {size} of line {n} (line is {size}). Full output: {path}]`. When the job's log+ itself was bounded on disk (J4), `Full output:` becomes `Output log (middle omitted beyond {cap}):`, so no result+ promises a complete file that does not exist.+- Exit 0 is a normal result; otherwise an error result ending in `Command exited with code {code}`. `(no output)` when+ empty.+- `timeout` kills the process tree: `Command timed out after {n} seconds`. Abort kills it: `Command aborted`.+- Handover (Avibe), when `watch: true` or the foreground window passes: the result is not an error and reads+ `Command is still running and is now Watch {watch_id}. You will get a follow-up message when it finishes.` followed+ by the output so far (tail rules above), `Full output: {path}`, and `Check: vibe watch show {watch_id}`,+ `Stop: vibe watch remove {watch_id}`.+- The Watch follow-up states the command, exit code, elapsed time, the tail under the same rules, and the full-output+ path.++## 6. Output normalizer++Every model-facing command output (`bash` results, job logs, Watch follow-ups) passes through one normalizer: decode+as UTF-8 with replacement, strip ANSI escape sequences, collapse carriage-return redraws to the final line state, then+apply the caps above. `read` returns file contents unchanged apart from Pi's caps: the model copies that text into+`edit`, which must match the real file. For `pipe` jobs the first steps are usually no-ops; for the future `pty`+backend they are required.++## 7. Job handle++`JobHost` is the interface `tools` uses; the adapter implements it, with Watch for handover. Persisted metadata:+[`job.schema.json`](job.schema.json).++| Operation | v1 | Meaning |+| --- | --- | --- |+| `start(command, cwd, env, timeout)` → `job_id` | yes | create the job directory and metadata, then spawn the wrapper in its own session |+| `status(job_id)` | yes | `running`, `exited{code}`, or `gone` (ended without an exit code) |+| `wait(job_id, deadline_s)` | yes | until exit, or at most `deadline_s` seconds from now (`None`: until exit) |+| `output_path(job_id)` | yes | absolute path of `output.log`, named in truncated and handover results |+| `output(job_id, since)` | yes | output after a logical offset into everything the command has produced (not a file position), plus the new offset; bytes dropped by the on-disk bound are reported as omitted, never silently skipped |+| `kill(job_id)` | yes | terminate the process tree, verified by process identity |+| `hand_over(job_id)` → `watch_id` | yes | register a once Watch with target kind `job` |+| `send(job_id, keys)`, `screen(job_id)`, `resize(job_id, cols, rows)`, `attach_info(job_id)` | reserved | `pty` backend (plan §5.4) |++Job directory: `<state>/agent_core/jobs/<job_id>/` with `meta.json`, `output.log`, and the files the `tools` lane's+launch mechanism needs. The job host meets recovery invariants J1–J6 ([`recovery.md`](recovery.md)): a command starts+at most once and recovery can always decide whether it did; its identity is recorded before it runs; `timeout` is an+absolute deadline that survives handover and restarts; output on disk is bounded; files are kept until the call is+durably settled; handover creates at most one Watch per job.++## 8. Environment section++Changing facts do not go into the system prompt, which stays stable and cacheable. When the loop consumes an input+(C-5 `ModelInput`), it renders an environment block into that message with the fields that changed since the previous+input (all fields on the first input), so the stored transcript still equals what the model saw. The first input after a checkpoint carries all fields+again, because the inputs that carried the earlier values may be summarized away:++```text+<environment>+cwd: /absolute/path+os: macOS 26.0 (arm64)+shell: /bin/zsh+date: 2026-10-02+timezone: Asia/Shanghai+watches: wch_8f2k "pytest -q" running 6m+</environment>+```diff --git a/docs/plans/agent-core-contracts/transcript-rows.schema.json b/docs/plans/agent-core-contracts/transcript-rows.schema.jsonnew file mode 100644index 000000000..f80662342--- /dev/null+++ b/docs/plans/agent-core-contracts/transcript-rows.schema.json@@ -0,0 +1,300 @@+{+ "$schema": "http://json-schema.org/draft-07/schema#",+ "$id": "agent-core/transcript-rows.schema.json",+ "title": "TranscriptRowPayloads",+ "description": "C-5 payloads of context rows (transcript.md). Written by the adapter's TranscriptStore for the `harness`; read by projection, fork, resume, and the Workbench model view. All shapes are persisted and versioned.",+ "definitions": {+ "ModelInput": {+ "description": "`messages.content_json.model` on user, harness, agent_initiated, and annotation rows, set when the loop consumes the input.",+ "type": "object",+ "required": [+ "version",+ "message"+ ],+ "additionalProperties": false,+ "properties": {+ "version": {+ "const": 1+ },+ "message": {+ "$ref": "message.schema.json#/definitions/UserMessage",+ "description": "The input exactly as sent, including the rendered time and identity prefix and attachments."+ }+ }+ },+ "ModelResponse": {+ "description": "`messages.content_json.model` on assistant and result rows.",+ "type": "object",+ "required": [+ "version",+ "message"+ ],+ "additionalProperties": false,+ "properties": {+ "version": {+ "const": 1+ },+ "message": {+ "$ref": "message.schema.json#/definitions/AssistantMessage",+ "description": "Verbatim, including quick-reply blocks and file:// links that the display copy rewrites."+ }+ }+ },+ "ToolResult": {+ "description": "`agent_events.content_json` of a `tool_result` row.",+ "type": "object",+ "required": [+ "version",+ "message"+ ],+ "additionalProperties": false,+ "properties": {+ "version": {+ "const": 1+ },+ "message": {+ "$ref": "message.schema.json#/definitions/ToolResultMessage"+ },+ "details": {+ "type": "object",+ "description": "Not sent to the model.",+ "properties": {+ "job_id": {+ "type": "string"+ },+ "watch_id": {+ "type": "string"+ },+ "exit_code": {+ "type": [+ "integer",+ "null"+ ]+ },+ "full_output_path": {+ "type": "string"+ },+ "truncated": {+ "type": "boolean"+ },+ "diff": {+ "type": "string",+ "description": "edit/write display diff."+ },+ "skill": {+ "type": "object",+ "required": [+ "name",+ "revision"+ ],+ "properties": {+ "name": {+ "type": "string"+ },+ "revision": {+ "type": "string"+ }+ },+ "description": "Set when the command loaded a skill (`vibe skill load`); used for rehydration after compaction."+ }+ }+ }+ }+ },+ "Compaction": {+ "description": "`agent_events.content_json` of a `context_compaction` row (plan §5.2).",+ "type": "object",+ "required": [+ "version",+ "summary",+ "first_kept_seq",+ "summarized_from_seq",+ "summarized_to_seq",+ "reason",+ "tokens_before",+ "tokens_after_estimate",+ "summarizer",+ "files_read",+ "files_modified"+ ],+ "additionalProperties": false,+ "properties": {+ "version": {+ "const": 1+ },+ "summary": {+ "type": "string",+ "description": "Self-contained checkpoint text, including the mechanical file lists and `<current-request>` when present."+ },+ "first_kept_seq": {+ "type": "integer"+ },+ "summarized_from_seq": {+ "type": "integer"+ },+ "summarized_to_seq": {+ "type": "integer"+ },+ "previous_compaction_id": {+ "type": [+ "string",+ "null"+ ]+ },+ "reason": {+ "enum": [+ "manual",+ "threshold",+ "overflow"+ ]+ },+ "focus": {+ "type": [+ "string",+ "null"+ ],+ "description": "Text after `/compact`."+ },+ "tokens_before": {+ "type": "integer",+ "minimum": 0+ },+ "tokens_after_estimate": {+ "type": "integer",+ "minimum": 0+ },+ "summarizer": {+ "type": "object",+ "required": [+ "origin",+ "prompt_version",+ "chunks"+ ],+ "properties": {+ "origin": {+ "$ref": "message.schema.json#/definitions/Origin"+ },+ "prompt_version": {+ "type": "string"+ },+ "chunks": {+ "type": "integer",+ "minimum": 1+ }+ }+ },+ "usage": {+ "$ref": "message.schema.json#/definitions/Usage"+ },+ "files_read": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "files_modified": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "current_request_message_id": {+ "type": [+ "string",+ "null"+ ]+ }+ }+ },+ "ContextEdit": {+ "description": "`agent_events.content_json` of a `context_edit` row.",+ "type": "object",+ "required": [+ "version",+ "target_event_id",+ "replacement",+ "reason"+ ],+ "additionalProperties": false,+ "properties": {+ "version": {+ "const": 1+ },+ "target_event_id": {+ "type": "string",+ "description": "The `tool_result` row whose content is replaced in projection."+ },+ "replacement": {+ "type": "object",+ "required": [+ "text"+ ],+ "properties": {+ "text": {+ "type": "string"+ }+ }+ },+ "reason": {+ "enum": [+ "clear_old_tool_result"+ ]+ }+ }+ },+ "AgentState": {+ "description": "`agent_events.content_json` of an `agent_state` row: hook state at a commit point (loop-control.md section 7). Not projected into messages.",+ "type": "object",+ "required": [+ "version",+ "state"+ ],+ "additionalProperties": false,+ "properties": {+ "version": {+ "const": 1+ },+ "state": {+ "type": "object"+ }+ }+ }+ },+ "examples": [+ {+ "version": 1,+ "summary": "## Objective\nFix the failing path test...\n<files-modified>\ncore/paths.py\n</files-modified>",+ "first_kept_seq": 412,+ "summarized_from_seq": 1,+ "summarized_to_seq": 411,+ "previous_compaction_id": null,+ "reason": "threshold",+ "focus": null,+ "tokens_before": 158432,+ "tokens_after_estimate": 31877,+ "summarizer": {+ "origin": {+ "provider": "anthropic",+ "api": "anthropic",+ "model": "claude-opus-5-5"+ },+ "prompt_version": "ckpt-v1",+ "chunks": 1+ },+ "usage": {+ "input_tokens": 61210,+ "output_tokens": 2304,+ "cache_read_tokens": 0,+ "cache_write_tokens": 0+ },+ "files_read": [+ "core/paths.py",+ "tests/test_paths.py"+ ],+ "files_modified": [+ "core/paths.py"+ ],+ "current_request_message_id": null+ }+ ]+}diff --git a/docs/plans/agent-core-contracts/transcript.md b/docs/plans/agent-core-contracts/transcript.mdnew file mode 100644index 000000000..d78961877--- /dev/null+++ b/docs/plans/agent-core-contracts/transcript.md@@ -0,0 +1,83 @@+# C-5 Transcript rows++The Avibe Agent's model context is stored in the existing `messages` and `agent_events` tables; there is no other+copy (plan §5.1). Row payload shapes: [`transcript-rows.schema.json`](transcript-rows.schema.json).++## 1. Membership and order++A row belongs to a Session's model context exactly when its `context_seq` is non-null. `context_seq` is an integer,+unique per Session across both tables (partial unique index on each table, plus the single-writer rule below).++| Entry | Table | `type` / `event_type` | `visibility` | Payload |+| --- | --- | --- | --- | --- |+| user or steer input | `messages` | `user` | — | `content_json.model` = `ModelInput` |+| harness input | `messages` | `harness`, `agent_initiated`, `annotation` | — | `content_json.model` = `ModelInput` |+| model response | `messages` | `assistant` (not final), `result` (final) | — | `content_json.model` = `ModelResponse` |+| tool result | `agent_events` | `tool_result` | `context` | `content_json` = `ToolResult` |+| checkpoint | `agent_events` | `context_compaction` | `context` | `content_json` = `Compaction` |+| cleared result | `agent_events` | `context_edit` | `context` | `content_json` = `ContextEdit` |+| hook state | `agent_events` | `agent_state` | `context` | `content_json` = `AgentState` |++Display-only rows keep `context_seq` null: `interim`, `notify`, `error`, `vault`, `output`, queued or removed inputs,+and the `tool_call` trace row written at tool start (its `metadata_json` carries `tool_call_id` and `job_id` so the+activity panel can pair it with the result).++## 2. Writing++- The loop is the only writer of a Session's `context_seq`, under a per-Session lock held across the transaction:+ `next = max(context_seq of the Session in both tables, fork_source_context_seq if the Session is a fork) + 1`, so a+ fork's first entry follows its inherited prefix.+- Inputs already exist as rows when they are submitted. The loop sets `context_seq` and `content_json.model` on that+ row when it consumes the input. Each entry is its own transaction; an input accepted by `steer` but not yet+ consumed when a crash happens is re-queued by the adapter at resume (`recovery.md` T3).+- A response row is inserted at `message_end` with both `content_json.model` and its rendered `content_text`.+- A tool result row is inserted at `tool_finished`. The `tool_call` trace row is inserted at tool start without a+ `context_seq`.+- Each commit is one SQLite transaction. The adapter delivers a row to surfaces only after it commits; the+ dispatcher does not persist it again.+- **Output outbox.** Every row a run produces for a surface (`assistant`, `result`, and the `notify` / `error` rows+ that report its failures) is in the outbox. Such a row is committed with `metadata_json.delivery = {"state":+ "pending", "parts": []}` in the same transaction; each part a surface sends is recorded with its receipt, and the+ row is `delivered` only when every part is (`recovery.md` D1). After the surface accepts it, the adapter sets `{"state": "delivered"}` with+ the platform receipt (`native_message_id` where the platform returns one). At startup, and before a Session+ resumes, the adapter re-delivers its `pending` rows in `context_seq` order. Nothing is lost or regenerated;+ duplicates are possible on IM in one window ([`recovery.md`](recovery.md) §Delivery).++## 3. Projection++`project(session_id, fork_point=None) -> list[Message]`, a pure function of the rows:++1. Collect the context rows: the Session's own, plus its fork ancestry (§4).+2. Order by `context_seq`.+3. If a `context_compaction` row exists, take the latest; the context becomes its checkpoint message followed by the+ rows with `context_seq >= first_kept_seq`, excluding every `context_compaction` row (including the selected one)+ and `agent_state` rows.+4. Apply `context_edit` rows: the latest edit per target replaces that tool result's content with its placeholder;+ the `context_edit` rows themselves are then removed, so the result is only messages.+5. Answer any tool call that still has no committed result with the synthetic interrupted result from+ `cross-provider.md`. Projection never consults a live job; resume settles open calls durably first+ ([`recovery.md`](recovery.md)).+6. Prepend the rebuilt system prompt and rehydrated state (plan §5.2); these are not rows.++## 4. Fork++The child Session's metadata already records its parent as top-level keys `fork_source_session_id` and+`fork_source_message_id` (written by `reserve_forked_session`, read by `fork_metadata_from_session_metadata` in+`core/services/session_fork.py`); C-5 reads those keys and adds no new fork shape.++- `anchor_seq` is resolved once, when the fork is reserved, as the largest `context_seq` in the source Session among+ rows at or before the anchor message, and persisted as the top-level metadata key `fork_source_context_seq`. Rows+ that receive a `context_seq` later can never move into or out of the prefix. A released fork without that key+ (forked from a non-`avibe` Session) has no Avibe Agent context to inherit and starts empty.+- The child's context = the source's context rows with `context_seq <= anchor_seq` (recursively through the source's+ own fork), then the child's rows.+- The child's `context_seq` continues from `anchor_seq + 1`, so the combined order stays total.+- Nothing is copied. A checkpoint in the source after `anchor_seq` is invisible to the child.++## 5. Retention and deletion++- Trace retention never selects `visibility = 'context'`; a contract test pins this.+- The context content of a row never changes after commit: `context_seq` and `content_json.model` are written once+ (on an input row, when it is consumed). Delivery state in `metadata_json.delivery` is the one field that changes+ afterwards, and only through the outbox helpers. Context rows are never deleted while a Session or a fork descendant+ references them.diff --git a/docs/plans/avibe-agent-core-evaluation.md b/docs/plans/avibe-agent-core-evaluation.mdnew file mode 100644index 000000000..f793bef74--- /dev/null+++ b/docs/plans/avibe-agent-core-evaluation.md@@ -0,0 +1,173 @@+# Avibe Agent core: evaluation summary++Evidence behind [`avibe-agent-core.md`](avibe-agent-core.md), collected 2026-09-03 to 2026-10-02. Spikes ran against+a local stub model server that recorded every request body as the record of what the model saw; no real keys or+user state were used. Sources and commits are in §6.++## 1. Control points++The goals require these eleven control points. Each option was measured against the same matrix: `NATIVE` (a public+primitive does it), `WORKAROUND` (possible with code around the framework), or missing.++| ID | Control point |+| --- | --- |+| C1 | Insert and remove tools while a run is in progress |+| C2 | Full context control: transient rewrite of what the model sees, and permanent compaction |+| C3 | Hooks at every lifecycle point, including deny, rewrite arguments, and end early |+| C4 | Another process steers a running loop |+| C5 | Snapshot a session and fork it into two independent branches |+| C6 | Resume after SIGKILL; memory strategy at 10,000+ messages |+| C7 | Three or four wire protocols, and history conversion when the model changes mid-session |+| C8 | Sub-agents inherit hooks and can be steered and forked |+| C9 | A typed event stream for IM progress bubbles |+| C10 | Cost of the Python boundary: glue code, round-trip latency, Python-side tools |+| C11 | Code and dependencies needed for a minimal coding agent |++| Option | Result | Notes |+| --- | --- | --- |+| Bare Python loop (control) | 11/11 native | 893 lines of core (159 of them cross-protocol conversion), 1,866 total; 24 packages / 51 MB; 0.08 ms to the first in-process event |+| LangGraph / LangChain 1.x `create_agent` | 7 native, 4 workaround (C4, C5, C8, C11) | steer needs a self-built mailbox read in `before_model`; no API to clone a thread; sub-agents come from `deepagents` |+| Pi, driven as the `pi` CLI over RPC | 9/11 native | steer, follow-up, session tree, events are primitives; RPC boundary 0.19 ms, Python tool round trip 59 µs |+| tau (`tau_agent` + `tau_ai`) | 3 native (C7, C9, C10), 8 workaround | no hooks around the model call; the loop ignores a tool's `terminate`; `follow_up()` is consumed before the run ends; tool set fixed at run start; `replace_messages` is memory-only |++## 2. Options not adopted++**LangGraph / LangChain.** The workarounds fall on the axis the goals care most about: steering, cloning, and+sub-agents. It brings thread, checkpoint, and interrupt concepts that overlap Avibe's Sessions, Runs, and question+UI. Messages use an append-only reducer, so permanent deletion needs `RemoveMessage` sentinels. At the version read,+middleware returning `Command(goto/resume)` raises `NotImplementedError`. `deepagents`, which supplies sub-agents,+file tools, and summarization, is pre-1.0, requires Python ≥ 3.11 (Avibe supports 3.10), and pulls in `langsmith` and+two vendor SDKs; the measured footprint with it was 62 packages / 109 MB. In its favor: in-process Python and a formal+1.x stability policy with no breaking release in six months.++**Pi (TypeScript).** In the published `pi-agent-core` 0.84.4, `AgentHarness` is a shell whose methods throw+`HarnessNotImplemented`; the full hook surface exists only one layer up, in the coding agent's extension API, so the+workable form is wrapping the whole CLI. Its control depth is real (above), but the agent's brain would live in a+TypeScript process and every Avibe signal (Memory, Harness events, context decisions) would cross a language+boundary. It has no published versioning policy and shipped nine breaking releases in six months, including a patch+release; governance moved to Earendil Inc. in April 2026; external pull requests are closed by a bot; MCP,+sub-agents, permissions, and sandboxing are deliberately out of scope.++**tau (Python port of Pi).** A healthy codebase (1,853 tests green, mypy strict, ruff clean) but a single-author+teaching project. Vendoring it would keep 5,095 lines, delete 48,400 (the TUI and CLI), and rewrite the 635 lines of+`harness.py` and `loop.py` that are exactly the control plane. Its provider layer has correctness gaps against+`pi-ai`: Gemini usage reported as zero, streaming thinking signatures lost, `redacted_thinking` treated as plain+thinking, refusal and safety stops folded into `stop`, no overflow classification, retries without `Retry-After` or+jitter, single-line SSE parsing. Python 3.10 compatibility needs only 15 PEP 695 aliases changed. Adopted as a source+to port from, not as a dependency.++**Claude Agent SDK.** It reaches Model Hub through `ANTHROPIC_BASE_URL`, but speaks only the Anthropic protocol, has no+API to read or replace the message list, cannot swap the whole tool set per call, and its hook abort signal is+reserved but unimplemented. Its control ceiling is the Claude Code CLI's.++## 3. Cross-provider portability++Switching vendors mid-session keeps the full conversation if the transcript is vendor-neutral and local. Pi's rules+(`pi-ai`, `transform-messages`), adopted in C-1:++- Every assistant message records `origin{provider, api, model}`.+- Same origin: replay thinking and its signature verbatim. Different origin: thinking becomes plain assistant text;+ redacted or encrypted reasoning and Gemini thought signatures are dropped; a signature is never synthesized.+- Tool-call ids are normalized to the target protocol's format, with the same mapping applied to their results.+- A tool call without a result gets a synthetic error result; images become a placeholder for non-vision models.+- Responses API with `store: false`, never `previous_response_id`; compaction runs on the client and produces text.++What cannot move between vendors: provider-private reasoning state (cryptographically bound), sampling behavior, and+prompt cache, which starts cold once after a switch. tau's tests include cross-provider history cases to port. Model+Hub's gateway converts protocols only as a fallback, and reasoning may degrade when it does, so the agent speaks the+primary hop's native protocol and records the served hop as `origin`.++## 4. Context management++Pi, Codex, and OpenCode were read at source level; Claude Code from its documentation.++| | Pi | Codex | OpenCode | Claude Code (docs) |+| --- | --- | --- | --- | --- |+| Trigger | context > window − 16,384 | min(config, 0.9·window); hard cap 0.95 | ≥ window − min(max output, 32K) | ≈967K on 1M windows |+| Kept verbatim | ≈20K-token tail | recent **user** messages only | a 2K–15K token tail | recent messages |+| Cut rule | only at user/assistant messages, never at a tool result | none needed (no tool items kept) | whole turns, or a turn suffix | refuses a single exchange |+| Summarizer | own system prompt + serialized transcript, no tools | same model, full history, no tools | own agent + serialized transcript, no tools | same prompt, tools, and history plus an instruction |+| Tool-output clearing | none built in | none | `prune`: protect the last 2 user turns, newest 40K tool tokens, and `skill`; only if ≥ 20K freed; off by default | "clears older tool outputs first" |+| Re-injected afterwards | system prompt; file lists in the summary | full initial context | system prompt every step; todo list lost (#5934) | CLAUDE.md, plan, git status, up to 5 recent files, invoked skills (5K each, 25K total) |+| Storage | appended `compaction` entry; originals kept | appended `compacted{replacement_history}`; originals kept | appended marker and summary; originals kept | appended boundary; originals kept |++What converged and was adopted: an append-only log with a deterministic projection; a summarized head plus a verbatim+tail; safe cut boundaries; fixed summary headings that preserve exact paths, identifiers, and error text; iterative+merge with an explicit previous-summary slot (OpenCode's rule: the prior summary is discarded, anything not carried+forward is lost, and the conversation wins conflicts); usage plus estimate for token counting; durable instructions+re-rendered on every request.++What failed in practice and the rule adopted in response:++| Failure | Evidence | Rule |+| --- | --- | --- |+| Estimate blind to reasoning payloads; compaction cannot shrink the context and the session wedges | Pi #9409 | count the bytes actually replayed; prefer provider usage |+| Trigger ignores the requested output tokens | Pi #8061 | subtract the real `max_tokens` |+| Summary request re-adds content the model never saw, then overflows | Pi #9602 | serialize from the projection actually sent; exclude reasoning |+| Summarizer overflow is terminal or unbounded | OpenCode errors out; Codex drops the oldest item and retries without limit | per-item caps plus chronological chunk-merge |+| Infinite compaction loops | OpenCode #15533, #27924 | one retry per rung, failure and ineffectiveness breakers |+| Synthetic "What did we do so far?" / "Continue…" user turns | OpenCode #13838, #15533 | no synthetic user turn; the checkpoint is framed as a record |+| Agent forgets the task after compaction | Codex #36712, #43855 | keep a verbatim tail ending at the latest tool results |+| Todo or plan lost | OpenCode #5934 | durable state re-rendered from its own store |+| Every compaction is a full cache miss | OpenCode #25120 | accepted in v1 and recorded per checkpoint; decide on cache-safe summarization from that data |++Token estimate for Chinese, measured with the o200k tokenizer: a 72-character Chinese sentence is 51 tokens;+characters / 4 gives 18 (−65%), UTF-8 bytes / 4 gives 54 (+6%). An English sentence: 39 tokens, both estimates 48.++## 5. Tools++**Pi's surface** (`packages/coding-agent/src/core/tools/`): `read{path, offset, limit}`, `write{path, content}`,+`edit{path, edits[{oldText, newText}]}`, `bash{command, timeout}` by default, with optional `grep`, `find`, `ls` off by+default. Output caps 2,000 lines / 50 KB; `read` keeps the head and returns raw text without line numbers; `bash` keeps+the tail and spills the full output to a temp file; `edit` matches exactly, then after a deterministic normalization+(NFKC, trailing whitespace, quotes, dashes, spaces; no similarity threshold). tau mirrors these names, parameters,+descriptions, and constants; its `edit` lacks the normalized tier and its `bash` buffers the whole output in memory.++**Interactive input and long-running commands.**++| Agent | stdin | Long-running commands |+| --- | --- | --- |+| Pi | closed; an extension's own comment says an agent's interactive command "will fail (which is fine)"; Pi's repository drives TUIs with `tmux send-keys` / `capture-pane` through bash | blocks until exit; no default timeout |+| OpenCode | ignored | 2-minute default timeout; no model-facing background; a TODO plans separate get/wait/cancel tools |+| Claude Code | none | `run_in_background` with an output file and a completion notice; a foreground command past its timeout moves to the background |+| Codex | `exec_command` + `write_stdin` with an optional PTY | a command running past `yield_time_ms` returns a session id; now Codex's only shell tool |++No primary source shows that dedicated search, planning, or LSP tools beat shell commands with model and prompt held+constant. Terminal-Bench's reference agent, Terminus, uses only a tmux pane: keystrokes with a wait duration, then the+captured screen.++**Portable job handle prototype** (macOS arm64, Python 3.13): the command runs under a one-line `sh` wrapper in its own+session, output goes to a file, and the wrapper writes the exit code atomically.++- The spawner was SIGKILLed right after start; another process saw the job running, waited on the handle, and got exit+ code 3 and the output tail.+- Killing by handle ended the whole group: four processes (wrapper, shell, two background sleeps) before, none after.+- Overhead: 1.8 ms per command directly, 6.4 ms through the wrapper (50 runs).++**tmux as the job base**, measured with Avibe's vendored tmux 3.6b on a private socket:++| | `sh` wrapper | tmux pane |+| --- | --- | --- |+| Per command | 6.4 ms | 24.6 ms |+| Environment | the caller's | the tmux server's at server start: a caller with `FOO=second` saw `FOO=first` |+| Interactive program | fails at once (closed stdin) | `less` waited for input indefinitely |+| Output | plain text | ANSI sequences and redraws need cleanup |+| Exit code | file | `remain-on-exit` plus `#{pane_dead_status}` (reported 7 correctly) |+| Availability | every platform with an equivalent wrapper | optional dependency; no Windows build |++tmux's distinct value is attaching to and typing into a live terminal, which is what the planned `pty` backend uses.++## 6. Sources++| Project | Revision | License |+| --- | --- | --- |+| Pi (`earendil-works/pi`) | `7fbbd5f`; npm `@earendil-works/pi-*` 0.84.4 | MIT |+| tau (`huggingface/tau`) | 0.4.1 `0a67734` (spike), 0.4.7 `e4eab0d` (tools) | MIT |+| Codex CLI (`openai/codex`) | `b707714` | Apache-2.0 |+| OpenCode (`sst/opencode`) | `a79ecfe` | MIT |+| LangChain 1.3.x, LangGraph 1.2.x, deepagents 0.7.x | PyPI releases of 2026-09 | MIT |+| Claude Code | official documentation, 2026-10 | proprietary; described, not copied |+| Terminal-Bench / Terminus | [tbench.ai/news/terminus](https://www.tbench.ai/news/terminus), [Harbor Terminus-2](https://harborframework.com/docs/agents/terminus-2) | — |++Issues cited: Pi #8061, #9409, #9602, #9904; Codex #7808, #36712, #43855; OpenCode #5934, #13838, #15533, #25120,+#27924.diff --git a/docs/plans/avibe-agent-core.md b/docs/plans/avibe-agent-core.mdnew file mode 100644index 000000000..a528b076e--- /dev/null+++ b/docs/plans/avibe-agent-core.md@@ -0,0 +1,402 @@+# Avibe Agent core++Status: **Approved direction, contracts in draft** · 2026-10-02++- Evidence: [`avibe-agent-core-evaluation.md`](avibe-agent-core-evaluation.md)+- Contracts: [`agent-core-contracts/`](agent-core-contracts/README.md), frozen per phase before parallel lanes+ fork (§7)++## 0. Decision summary++Avibe builds its own first-party Agent in Python, inside this repository, as a fourth backend next to Claude Code,+Codex, and OpenCode. Its backend id is `avibe` and its display name is "Avibe Agent". It reaches models through+Model Hub in each vendor's native protocol, and Avibe can steer, fork, resume, and manage its context directly.++Sourcing, by layer:++| Layer | Ownership | Source material |+| --- | --- | --- |+| `ai`: provider adapters | Avibe-owned code, **ported** | tau's payload and stream rules and its test fixtures (MIT); Pi's `pi-ai` as the rulebook for what tau lacks (stop reasons, overflow, retry taxonomy, multi-line SSE, Gemini usage) |+| `agent`: loop, hooks, queues | Avibe-owned, **written** | Pi, tau, and the bare-loop spike as executable references only |+| `harness`: transcript, context management | Avibe-owned, **written** | Pi compaction rules; Codex, OpenCode, and Claude Code lessons (evaluation §4) |+| `tools`: the coding tools | Avibe-owned, **ported** from Pi | Pi's tool names, parameters, logic, and model-facing text; tau as the Python reference |+| Integration: backend adapter, UI, catalog | Avibe-owned | existing `BaseAgent`, Agent catalog, Model Hub, Watch, Skills, question UI |++Not adopted as runtime dependencies or starting trees: LangGraph/LangChain, Pi (TypeScript), tau (Python). Control+does not need a framework: a bare loop passed all 11 control points in 893 lines. Every framework's reusable boundary+sits below the product boundary Avibe must own: loop semantics, persistence, and settled-turn semantics+(evaluation §1–§2).++## 1. Background and goals++- Model Hub gives Avibe vendor-independent model access, which makes a first-party agent viable.+- Today Avibe hosts only third-party agents with black-box loops. The goals need a loop Avibe controls fully:+ insert tools at will, read and rewrite the whole context, intervene at every lifecycle point, steer a running loop+ from outside, fork an agent, run for a very long time, and later add a "tension" system that wakes the agent on+ environment signals.+- v1 is a **minimal coding agent with every control seam present**, reachable from every Avibe surface (Web+ Workbench, Slack, Discord, Telegram, Feishu/Lark, WeChat), at parity with everyday work through the Claude Code and+ Codex backends. Most v1 effort goes into context management (§5.2) and the tools (§5.3).++## 2. Non-goals (v1)++- The tension system itself. v1 guarantees only the seams it will need: steer, follow-up, hooks, events.+- Any terminal UI, and any new Web UI beyond registering the backend where backends already appear.+- Becoming the default agent for new installs. v1 is opt-in; the default is decided after the P4 regression with real+ usage evidence.+- Hosting MCP servers (Avibe is an MCP client only). Sandboxing beyond Avibe's existing cwd policy.+- Failover and credentials inside the agent; they stay in Model Hub.+- Interactive terminal programs (planned, §5.4).++## 3. Hard constraints++1. Python `>=3.10` (Avibe's floor), asyncio host, no threads for the loop, no subprocess boundary for the loop.+2. No third-party agent framework at runtime. New dependencies only by recorded decision: the official `mcp` Python+ SDK enters in P3, recorded in `pyproject.toml` in the same PR. Internal types are dataclasses.+3. Native protocols: Anthropic Messages, OpenAI Chat Completions, OpenAI Responses, Google Gemini. The agent speaks+ the protocol of the route's primary hop and never flattens everything to one wire protocol.+4. **One persistence model, one copy.** The model-facing transcript is Avibe's own `messages` and `agent_events` rows+ (§5.1). There is no backend-native store, JSONL log, native session index, or native fork.+5. Hermetic tests: every engine test runs against a local stub model server; nothing reaches a vendor, the live+ `vibe` service, `~/.avibe`, or credential stores.+6. State lives under `~/.avibe/state/`; secrets never enter the transcript or logs.+7. Every acceptance criterion states a property, not a list of cases (§6).+8. **No server-side conversation state.** The transcript on disk is the whole session: the Responses API is used with+ `store: false` and never `previous_response_id`; no vendor-side compaction items; hosted-tool results are written+ into the transcript. Portability rule: another model must be able to continue without the previous provider+ having to dereference an id, decrypt a blob, remember a search result, or reconstruct a summary.++## 4. Architecture++```+modules/agents/avibe/ backend adapter: BaseAgent implementation, event → MessageOutput,+ transcript store over messages/agent_events, Watch-backed job host,+ question/permission bridge, Model Hub hop resolution+core/agent_core/+ ai/ canonical message model, provider adapters (4 protocols), stream parsing, retry+ agent/ loop, hooks, steer/follow-up queues, dynamic tools, fork snapshot, typed events+ harness/ transcript store interface, projection, context management, skills, MCP client+ tools/ read / write / edit / bash with output governance; JobHost interface+tests/agent_core/ control-point matrix (acceptance harness), conformance fixtures, stub server+tests/scenarios/agent_core/ scenario catalog (IDs cited in PRs)+docs/plans/agent-core-contracts/ frozen shapes (§5)+```++`core/agent_core/` knows nothing about IM platforms, the controller, Watch, or Model Hub's HTTP surface beyond a+`ModelEndpoint` value; `modules/agents/avibe/` is the only package that touches controller state.++One turn: `AgentRequest` → the adapter resolves the hop from Model Hub → the engine's `run()` yields typed events →+the adapter commits each context entry to Avibe's tables, then delivers it to the surfaces from the committed row →+`MessageOutput` settles the Turn. A message that arrives while the loop runs becomes a steer (`handle_message`),+and Stop becomes an abort (`handle_stop`).++## 5. Contracts++Each contract lives under `agent-core-contracts/` with exact field names, producer and consumer, and an example+payload.++| ID | Contract | Producer → consumer | File |+| --- | --- | --- | --- |+| C-1 | Canonical message model: user, assistant, and tool-result messages; text, image, thinking, and tool-call blocks; `origin`, `usage`, normalized `stop_reason`; cross-provider transform rules | `ai` → `agent`, `harness`, adapter | `message.schema.json`, `cross-provider.md` |+| C-2 | Provider adapter interface: `stream(ModelRequest) → ProviderEvent*`, error classification | `ai` → `agent` | `provider.md`, `provider-event.schema.json` |+| C-3 | Loop control: hook points, directives, steer and follow-up semantics, per-call tool set, snapshot and fork | `agent` → adapter, `harness`, tests | `loop-control.md` |+| C-4 | Typed agent event stream and its mapping to existing Avibe outputs | `agent` → adapter → Workbench and IM progress | `agent-event.schema.json` |+| C-5 | Transcript rows: what each context entry stores, `context_seq`, projection, fork by reference | adapter ↔ `harness` | `transcript.md`, `transcript-rows.schema.json` |+| C-6 | Model Hub consumer extension: `google` protocol, hop resolution, served-hop report | Model Hub → adapter | `model-hub-consumer.md`, `hop-resolution.schema.json` |+| C-7 | Tools: Pi's surface plus the owner's additions; output governance; job handle | `tools` → `agent`, adapter | `tools.md`, `job.schema.json` |+| C-8 | Backend registration: the catalog as the one declaration, and which sets must include `avibe` | catalog → every backend list | `backend-registration.md` |+| C-9 | Context management: projection tiers, trigger, cut point, checkpoint, recovery | `harness` → `agent`, adapter | §5.2 here; row shapes in `transcript-rows.schema.json` |++### 5.1 Transcript storage++Every current backend keeps its full transcript in its own store (Claude Code JSONL, Codex rollouts, OpenCode+SQLite) while Avibe keeps a display copy in `messages` and `agent_events`. On one heavily used installation, the three+native stores hold about 10 GB and Avibe's database 1.7 GB. That copy is not what the model saw:++- `agent_events` `tool_call` rows hold one display string such as `🔧 Bash {...}`, with no call id and no result.+- Agent rows are written as a side effect of display dispatch (`core/message_mirror.py`, `persist_agent_message`):+ empty-text outputs are skipped, stale-turn emits are dropped, the quick-reply block is stripped, `file://` links+ become media-proxy URLs, and citations are materialized.+- Tool-call trace rows are deleted after 30 days (`storage/agent_events_retention.py`).+- The two tables share no order key. The activity panel recovers cross-table order from microsecond id prefixes+ (`storage/agent_activity_service.py`), but a model context needs exact order: a tool result must follow its call.++For the Avibe Agent, the same rows become the transcript (C-5):++| Context entry | Row | Model-facing content | Display (consumers unchanged) |+| --- | --- | --- | --- |+| User or steer input | existing `messages` `user` row, linked by `message_deliveries` | `content_json.model`: the rendered input exactly as sent (time and identity prefix, attachments), written when the loop consumes it | `content_text` as today |+| Harness input (callback, Watch, Task, annotation) | existing `messages` `harness` / `agent_initiated` / `annotation` row | same as above | as today |+| Model response, not final | `messages` `assistant`, one row per model call, even when its text is empty | `content_json.model`: ordered text, thinking, and tool-call blocks; `origin`; `usage`; `stop_reason` | `content_text` is the narration text; the Web-only `interim` copy stays a display row and is not context |+| Final model response | `messages` `result` | same, verbatim (quick-reply block and `file://` links kept) | `content_text` is the rendered text as today |+| Tool execution start | `agent_events` `tool_call`, `visibility='trace'` | none; the call lives in the response row | short display preview as today |+| Tool result | `agent_events` `tool_result`, `visibility='context'` | the result as the model saw it, after output governance | the activity panel may show a preview |+| Compaction checkpoint | `agent_events` `context_compaction`, `visibility='context'` | §5.2 | expandable "context compacted" marker |+| Cleared tool result | `agent_events` `context_edit`, `visibility='context'` | target row and placeholder | none |++Schema delta (one Alembic migration, nullable columns, no backfill):++1. `context_seq INTEGER NULL` on `messages` and `agent_events`, with a partial unique index+ `(session_id, context_seq) WHERE context_seq IS NOT NULL`. `agent_events.sequence` stays as it is: it is a+ released, turn-local field of the storage API, and context membership is a different meaning.+2. A new `agent_events.visibility` value, `context`, never removed by trace retention. The retention filter is+ already `event_type='tool_call' AND visibility='trace'`; a contract test pins the exemption.+3. New `agent_events.event_type` values `tool_result`, `context_compaction`, `context_edit`, and `agent_state` (hook+ state for fork, C-3), registered where the activity panel reads event types.+4. For this backend, `agent_sessions.native_session_id` is the Avibe Session id.++Rules:++- The loop is the single writer of a Session's context and assigns `context_seq` when an entry enters the context:+ an input when it is consumed (a steer after the current tool batch), a response at `message_end`, a tool result at+ `tool_finished`. Queued, removed, display-only, and `interim` rows stay null.+- Commit points are SQLite transactions. After a crash the context resumes from the last committed `context_seq`.+ Every external effect meets the recovery invariants in C-5/C-7 `recovery.md`, each with an owning lane and a proof:+ open tool calls are settled durably before the first projection, commands start at most once, and responses are+ delivered completely (exactly once on Workbench, at least once per part on IM).+- Write path: the adapter commits the context row first, then hands that row to the dispatcher for delivery; the+ dispatcher must not persist it again. Display rendering (media rewrite, quick replies, citations) fills+ `content_text` and display keys of the same row. The row carries a pending delivery state committed with it, so a+ crash between commit and delivery re-delivers instead of losing or regenerating the reply: exactly once on+ Workbench, at least once on IM (C-5).+- Fork reuses the existing fork metadata (`fork_source_session_id`, `fork_source_message_id`). The child's context is the parent+ chain's rows with `context_seq` up to the anchor's, then the child's own rows. Nothing is copied. Scopes with+ history are dismissed, never deleted, so a parent's prefix cannot disappear from under a child.+- Compaction and clearing append rows; they never rewrite or delete. A fork anchored before a checkpoint sees the+ full original context.+- Every block that may be large has an inline form and a reserved reference form+ (`{"ref": "sha256:…", "bytes": n}`), so moving large tool output out of the database later is not a schema change.+ v1 writes inline; output governance (2,000 lines / 50 KB) bounds each row. Revisit with measured growth.++### 5.2 Context management (C-9)++**Draft, not frozen.** The owner deferred the context-management decisions; this section is the working design and+freezes before P3 together with those decisions. Open points recorded for that freeze: the occupancy baseline+immediately after a checkpoint or edit, before any response exists; capabilities of the served hop after a failover+to a model with smaller limits; the summarizer output cap on routes below 16K output tokens; restoring the environment+block for a request issued right after a checkpoint inside a turn; and image cost in the estimate.++Every rule names its origin in evaluation §4. One pure function, `project(rows, fork_point)`, builds every request,+resume, fork, and the UI's "model view". Three tiers, cheapest first:++1. **Output governance at write time** (C-7): no single tool result exceeds 2,000 lines / 50 KB.+2. **Clearing old tool results**, recorded as `context_edit` rows. Eligible: `read` and `bash` results, including+ terminal screen snapshots later. Protected: the last 2 user turns, the newest 5 eligible results, skill loads, and+ anything before the latest checkpoint. Applied only when it frees at least 20K tokens, and only before a request+ when the provider cache is already cold (idle longer than the cache TTL, which is normal in IM sessions) or the+ estimate passes 0.8·T. On by default. Placeholder: `[Old tool result cleared to save context. Re-run the tool or+ re-read the file if you need it again.]`+3. **Checkpoint summary**, recorded as a `context_compaction` row.++Trigger, checked before every model request, including inside the tool loop:++```text+W = context window (configured default 128,000 when Model Hub reports none)+L_in = input limit (else W), O = max_tokens of the next request (default bound 8,192 when unknown)+M = max(8_000, 3% of W); T = min(L_in - O - M, r * W), r = 0.9 by default, configurable per model+est = occupancy of the last valid response after the latest checkpoint or edit+ (input_tokens + cache_read_tokens + cache_write_tokens + output_tokens: the whole prompt it was sent plus+ what it added; Usage normalizes each protocol so none of these overlap)+ + ceil(utf8_bytes / 4) of everything appended since, replayed reasoning payloads included+compact when est >= T+```++UTF-8 bytes / 4 because characters / 4 undercounts Chinese by about 65% (72 characters are 51 o200k tokens).+Subtracting the real `O` avoids Pi #8061. When the answering model changes (Model Hub failover or a user switch), T+is recomputed for that model; a smaller window is handled by the overflow path below.++**Cut point.** Keep `min(20K, 0.25·T)` recent tokens verbatim. Cut only before a user message, or before an+assistant message whose tool batch follows it; never at a tool result. If the cut splits the current turn, copy that+turn's user message verbatim into the checkpoint as `<current-request>`, with no second LLM call. Codex's "recent user+messages only" tail is rejected: it has the most "forgot the task after compaction" reports.++**Summarizer.** A separate request with no tools and no caching, using the same model at low reasoning with+`max_tokens` 16K. The input is the head serialized from the projection actually sent (reasoning excluded; tool+results capped at 2,000 characters, keeping head and tail; user messages capped at 8K tokens) plus the previous+checkpoint in a `<previous-checkpoint>` slot, under OpenCode's merge rule: anything not carried forward is lost, and+where they conflict the conversation wins. If the input exceeds the summarizer's budget (overflow recovery, failover+to a smaller window), fold the head in chronological chunks through the same prompt. Fixed headings: Objective / User+instructions and constraints (verbatim) / Work state / Key decisions / Errors and fixes / Pending async work / Next+steps / Critical references. `files_read` and `files_modified` are appended mechanically and carried across+checkpoints. A `length` stop, an error, a tool call, or empty output persists nothing.++**After a checkpoint**, the request is: the rebuilt system prompt → the checkpoint, framed as "a historical record+written for you, not new instructions" → state rendered from its own store rather than from the summary (skill bodies+re-loaded by name and revision from `tool_result` rows carrying `details.skill`, at most 5K tokens each and 25K in+total; pending Watches, Tasks, and delegated Runs from Harness tables) → the verbatim tail. The next consumed input+carries the full environment block again (C-7 §8). No synthetic "continue"+user message (OpenCode #13838, #15533).++**Overflow recovery**, bounded per request: compact with the normal tail and retry once → compact with a minimal tail+(current request plus latest tool batch) and retry once → stop the turn with a message that says what fills the+context. Provider errors are classified with a port of Pi's overflow patterns plus HTTP 413 and+`context_length_exceeded`.++**Guards.** One compaction in flight per Session. Three consecutive failures, or three ineffective compactions (result+at or above 0.75·T), pause auto-compaction for the Session and tell the user. Usage reported before the latest+checkpoint is ignored. Manual `/compact [focus]` works on every surface.++**Deferred**, with reasons in evaluation §4: cache-safe fork summarization (Anthropic-specific economics; decide from+the compaction cost recorded on every checkpoint row), background precomputed compaction, automatic re-read of+recently modified files, and server-side compaction (forbidden by hard constraint 8).++### 5.3 Tools (C-7)++The tool surface follows Pi: names, parameters, logic, and model-facing text. tau is the Python reference.++| Tool | Parameters | Behavior |+| --- | --- | --- |+| `read` | `path`, `offset?`, `limit?` | raw text without line numbers; head 2,000 lines / 50 KB; `Use offset=K to continue`; images attached for vision models |+| `write` | `path`, `content` | creates parent directories; overwrites |+| `edit` | `path`, `edits[{oldText, newText, replaceAll?}]` | exact match, then Pi's deterministic normalized match; unique unless `replaceAll`; non-overlapping; matched against the original; CRLF and BOM preserved |+| `bash` | `command`, `timeout?`, `watch?` | stdout and stderr merged; tail 2,000 lines / 50 KB with the full output spilled to a file; a non-zero exit is an error result; `timeout` kills the process tree |++One tool set serves every model. stdin is closed, so interactive programs fail fast instead of hanging; where tmux+is installed the agent can still drive one through `bash`, as Pi's own repository does. Search, delegation,+credentials, waiting, files for the user, and questions stay on existing Avibe surfaces (`rg`/`find` through `bash`,+`vibe agent run`, Vault, `vibe watch`, `file://` links, the question UI).++Owner additions over Pi: `edit` `replaceAll` (from Claude Code and OpenCode) and Watch-backed `bash` (below). Rejected+for v1: stale-write guard, line numbers in `read`, a `workdir` parameter, head+tail failure output, `write_stdin`,+post-edit LSP diagnostics, and dedicated `grep`/`find`/`ls`. Two places where tau falls short and Pi is the source:+the normalized edit tier, and streaming, bounded output with spill.++**Long-running commands through Watch.** Watch serves as the agent's background facility. A process cannot change+owners after it starts, so every command gets a portable handle from its first moment and never has to move.++- **Job handle.** Every `bash` call starts a job: a one-line `sh` wrapper in its own session runs the command,+ stdout and stderr go to `<state>/agent_core/jobs/<job_id>/output.log`, and the exit code is written atomically to+ `exit`. `meta.json` holds the command, cwd, absolute deadline, and process identity (`job.schema.json`). The job host+ meets recovery invariants J1–J6 (C-7 `recovery.md`). No process holds a+ pipe to the job, so any holder of the id can read it, wait on it, or kill it. Prototype results: evaluation §5.+- **Foreground** waits on the handle: the tool tails `output.log` for live progress and Pi's truncation, and+ returns when `exit` appears.+- **Handover.** `watch: true` hands the handle to Watch at once. A foreground job still running after the foreground+ window (default 120 s, configurable) is handed over instead of killed. Handover registers a once Watch on the same+ handle: nothing restarts, and the command runs exactly once.+- **Watch target kind `job`.** A Watch can target a job handle instead of a waiter command, keyed by `job_id` and+ created by adopt-or-create, so one job never has two Watches. Its cycle waits on the handle, which is idempotent+ across vibe restarts, and enforces the job's deadline; the command's own exit code is reported and never read as Watch's+ 75 or 64; the Watch is displayed as the original command. The Watch owns the job: removal, disabling, lifetime+ expiry, and Session archive kill its process tree.+- **Restart and stop.** Jobs survive vibe restarts, upgrades, and crashes; an open foreground tool call is then+ settled as "still running, now Watch `<id>`". An explicit `vibe stop` ends them, matching how it already ends tool+ commands.+- **What the agent sees.** One concept, Watch; the job id is an internal detail. The tool result names the Watch, the+ output so far, the full-output path, and `vibe watch show|remove <id>`. The follow-up uses Watch's existing P1+ delivery: after the current tool batch of an active turn, or a new turn when idle. The environment block rendered+ into each consumed input (C-7) lists the Session's live Watches, so the agent keeps track of them across+ compaction.+- **Platforms.** Windows needs the equivalent wrapper (a new process group plus a job object, as+ `core/watch_worker.py` already does).+- **Engine boundary.** `core/agent_core/tools` sees a `JobHost` interface; the adapter implements handover with Watch;+ engine tests use an in-process fake.++### 5.4 Interactive terminals (planned; shapes v1, ships later)++Goal: the agent drives interactive programs the way a person does (installers with prompts, REPLs, `ssh`,+`gh auth login`, TUIs), and a person can open the same terminal and take over. The primitive is proven: Terminal-Bench's+reference agent, Terminus, has no tool other than a tmux pane; each step sends keystrokes with a wait duration and+reads back the captured screen.++Locked in v1 so the later backend needs no migration or contract change:++1. **Handle operations.** `JobHost` names `start`, `status`, `wait`, `output(since)`, and `kill`, and reserves+ `send(keys)`, `screen()`, `resize()`, and `attach_info()`. The v1 `pipe` backend implements the first five.+2. **Persisted job metadata** carries `backend` (`pipe | pty`) and a nullable `terminal{socket, target}` from the first+ release.+3. **The environment travels with the job**, not through process inheritance, so a pane created by a long-lived tmux+ server still runs with the caller's environment. A file used for this is mode 0600 and removed once read.+4. **One output normalizer** sits between every backend and the model: strip ANSI sequences, collapse carriage-return+ redraws, apply Pi's caps. It does nothing to `pipe` output and is required for `pty`.+5. **Watch targets the handle, not the backend**, so an interactive job can be watched; "wait until the screen shows+ X" is a later Watch condition on the same target.+6. **Context management** treats screen snapshots as clearable tool results.++The `pty` backend, when built: the same wrapper inside a pane of Avibe's vendored tmux on a dedicated socket+(macOS/Linux), raw output logged with `pipe-pane`, screens from `capture-pane -p`, keystrokes sent literally and chunked+under tmux's roughly 16 KB command limit, and waits that end on exit, quiet output, or a pattern rather than only a fixed+duration. The Terminal app attaches to the same pane for takeover. Windows needs a ConPTY backend. tmux is not the v1+base for the reasons measured in evaluation §5.++Open until then, decided by evaluation on Terminal-Bench through the Harbor harness (`pipe` only versus `pty`+capable): whether the agent-facing form is `bash` gaining `tty` and `session` parameters, or one dedicated terminal+tool shaped like Terminus's.++## 6. Acceptance criteria++Properties; the test suites enumerate cases.++- **A1 Control matrix.** Every control point in evaluation §1 passes natively against the hermetic stub in+ `tests/agent_core/`, with the stub's request log as evidence of what the model saw.+- **A2 Native protocol fidelity.** For every protocol in C-6's vocabulary, a session can start, call a tool, and+ continue after switching to every other protocol. Tool ids survive, provider-owned thinking is replayed only into+ its own origin, no signature is ever synthesized, and the stub sees exactly one protocol per request.+- **A3 Durability.** SIGKILL at any point resumes with no committed entry lost and no command executed twice; the+ context rebuilt from the tables is always a valid request for every protocol.+- **A4 Bounded context.** A session with more than 10,000 messages keeps every request under its model's T.+ Compaction and clearing only insert rows. A fork anchored before a checkpoint projects the full original context.+ With a provider that always overflows, one request triggers at most two compactions and then a user-visible stop.+- **A5 Egress.** With Model Hub configured, every model call goes to the resolved `base_url`: the engine itself sends+ no telemetry and never contacts a vendor directly. Network use by tools (`bash`, later MCP) is the tools' own and is+ governed by tool and workspace policy, not by this criterion.+- **A6 Surfaces.** The same turn produces equivalent user-visible outcomes on Workbench and on every IM platform in+ the Incus regression environment: progress, tool activity, final message, stop, questions, Watch follow-ups.+- **A7 Registration.** Every declaration that stands for a whole backend universe equals the catalog's set or the+ native-CLI subset, and every capability-specific set is classified with its relation to one of them (C-8); a contract+ test enforces both.+- **A8 Isolation.** Engine tests never touch `$HOME`, `~/.avibe`, or a live service.+- **A9 Portability.** Any session, rebuilt from the tables, continues on every other protocol with the original+ provider unreachable: all user, tool, and assistant text is present in the new request, no signature from another+ origin is sent, and the run completes.+- **A10 One copy.** For every request without a transient `before_model` rewrite (C-3 §3), the context rebuilt from+ `messages` and `agent_events` equals what the stub received; no other file or table holds a copy of it.+- **A11 Exactly-once commands.** A command started by `bash` runs once across foreground completion, `watch: true`,+ foreground-to-Watch handover, and a vibe restart in any of those states; Watch removal ends its process tree.+- **A12 Compaction quality.** On a scripted long-session fixture compacted twice, the agent still states the user's+ constraints, the files changed and why, the last error, and the next step. This is an LLM-in-the-loop evaluation+ tracked per prompt version, not a unit test.++## 7. Delivery plan++| Phase | Lanes | Scope | Gate |+| --- | --- | --- | --- |+| P0 | docs | this plan, the evaluation, and the contract drafts | owner approval; `pr-delivery-loop` gates |+| P1 | Model Hub extension: `core/handlers/model_hub/`, Model Hub contracts, UI types · `ai`: `core/agent_core/ai/` · `agent`: `core/agent_core/agent/` · `tools`: `core/agent_core/tools/` | C-1, C-2, C-3, C-6, C-7 frozen on `master` first | each lane in its own worktree and PR; the control points it owns pass |+| P2 | adapter: `modules/agents/avibe/`, catalog, config, and UI registration (i18n strings; any new UI element needs an approved `design.pen` frame first) · transcript and Watch `job` target: `core/agent_core/harness/`, `storage/`, `core/watches.py` | C-4, C-5, C-8 frozen | A1, A3, A7, A10, A11; Incus smoke on one platform |+| P3 | context management as the main v1 investment; skills rehydration; MCP client; permissions through the question UI (pending questions live in the controller process while Workbench answers arrive through `vibe/ui_server.py`, so this needs the controller IPC path, not the in-memory `QuestionUIHandler` alone) | C-9 frozen | A4; A12 baseline recorded |+| P4 | regression and acceptance | Incus four-platform regression; owner checklist | A6; default-agent decision |++Before P1, a few live calls through one Model Hub Source the owner names confirm the stub's fidelity. Circuit+breaker, review gates, and close-out follow the `pr-delivery-loop` skill.++## 8. Risks++| Risk | Mitigation |+| --- | --- |+| Provider edge cases become permanent maintenance | port tau's fixtures; add cases derived from `pi-ai` for stop reasons, overflow, retry, SSE; one conformance suite per protocol |+| The Model Hub extension lands late and blocks C-2 conformance | the Model Hub lane runs first in P1; the `ai` lane develops against the contract file, not the live gateway |+| A second persistence model creeps back | C-5 forbids one; A10 tests it |+| Compaction quietly loses user constraints | the fixed "User instructions and constraints" heading; A12 tracked per prompt version |+| Database growth from inline tool output | output governance bounds each row; the reserved reference form allows moving it out without a schema change |+| Scope creep toward the tension system or interactive terminals | §2 non-goals; §5.4 ships only the shape in v1 |+| Python 3.10 floor versus ported code | port with `TypeAlias`; CI already covers 3.10 |++## 9. Open review notes++Codex findings on this PR are advisory by owner decision (2026-10-02) because it is a spec-only PR; the lanes'+code reviews carry the precision. These notes from the last review round are kept for the next revision of the+contracts and checked against the implementing lane's code before they are closed.++| Priority | File | Note |+| --- | --- | --- |+| P1 | `model-hub-consumer.md` | Apply the full target transform during failover |+| P2 | `transcript.md` | Give display-only outbox rows an ordering key |+| P2 | `message.schema.json` | Preserve malformed-argument state on tool calls |+| P2 | `tools.md` | Reject nonpositive bash timeouts |+| P1 | `job.schema.json` | Require process state in every persisted job record |+| P2 | `loop-control.md` | Define the terminating tool-result field |+| P2 | `avibe-agent-core.md` | Scope portability to the current projected context |+| P1 | `avibe-agent-core.md` | Keep background descendants inside the job lifecycle |+| P2 | `loop-control.md` | Avoid delivering refusal errors twice |+| P2 | `message.schema.json` | Require content in canonical tool results |