octopi-agent 0.65.0 β†’ 0.70.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,244 +1,444 @@
1
- # Octopi πŸ™
2
-
3
- **The Embeddable Agent Engine**
4
-
5
- > An agent is not a class β€” it's a complete runtime.
6
- > A framework's value lies not in how many defaults it ships, but in how many clean interfaces it defines.
7
-
8
- [δΈ­ζ–‡ζ–‡ζ‘£](./README_CN.md) | [Architecture](./docs/architecture.md) | [Contributing](./docs/CONTRIBUTING.md)
9
-
10
- ---
11
-
12
- ## What is Octopi?
13
-
14
- Octopi is an embeddable agent engine for building AI-powered applications. It provides the runtime infrastructure your product needs to have AI capabilities β€” just like a car needs an engine, your product needs an agent engine.
15
-
16
- - **Embeddable** β€” Not a standalone app, but a component for your product
17
- - **4-layer architecture** β€” Loop β†’ Core β†’ Harness β†’ Integration, clean boundaries, independent layers
18
- - **10 product domains** β€” Each domain is independently understandable, testable, and replaceable
19
- - **8-layer context intelligence** β€” Wisdom, Persona, Skill, Knowledge, Cognition, Memory, Runtime, Information (see [docs/memory.md](./docs/memory.md) for Memory, [docs/knowledge.md](./docs/knowledge.md) for Knowledge)
20
- - **Security built-in** β€” Injection detection, risk evaluation, approval workflows β€” not optional, not removable
21
- - **Natively multi-agent** β€” Distributed intelligence from the ground up
22
-
23
- ---
24
-
25
- ## Architecture
26
-
27
- ```
28
- β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
29
- β”‚ Layer 3: Integration β€” External adapters β”‚
30
- β”‚ LLM Providers Β· Storage Β· Observability Β· Gateway Β· TUI Β· Web Runtime β”‚
31
- β”‚ β”‚
32
- β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”‚
33
- β”‚ β”‚ Layer 2: Harness β€” 10 product domains β”‚β”‚
34
- β”‚ β”‚ agent-building Β· context Β· security Β· reliability β”‚β”‚
35
- β”‚ β”‚ plugin-ecosystem Β· multi-agent Β· autonomous-subsystem β”‚β”‚
36
- β”‚ β”‚ session-tasks Β· run-guard Β· orchestration Β· concurrency β”‚β”‚
37
- β”‚ β”‚ execution-env Β· hitl Β· memory β”‚β”‚
38
- β”‚ β”‚ β”‚β”‚
39
- β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”‚β”‚
40
- β”‚ β”‚ β”‚ Layer 1: Core β€” Kernel Contract β”‚β”‚β”‚
41
- β”‚ β”‚ β”‚ EventBus Β· StateMachine Β· Kernel ports β”‚β”‚β”‚
42
- β”‚ β”‚ β”‚ β”‚β”‚β”‚
43
- β”‚ β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”‚β”‚β”‚
44
- β”‚ β”‚ β”‚ β”‚ Layer 0: Loop β€” Pure execution loop β”‚β”‚β”‚β”‚
45
- β”‚ β”‚ β”‚ β”‚ agentLoop Β· callModel Β· classifyError β”‚β”‚β”‚β”‚
46
- β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β”‚β”‚β”‚
47
- β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β”‚β”‚
48
- β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β”‚
49
- β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
50
- ```
51
-
52
- **Dependency direction: outer β†’ inner. Core has zero outer dependencies.**
53
-
54
- ### Layer 0: Loop β€” Pure Execution
55
-
56
- The heart of the engine. `agentLoop()` is a pure async generator: input messages β†’ LLM call β†’ tool execution β†’ protocol events. Zero state, zero external dependencies. Runnable facade is Harness `Agent.run()`.
57
-
58
- ### Layer 1: Core β€” Kernel Contract
59
-
60
- Infrastructure primitives (EventBus, StateMachine) and **Kernel ports** (ModelProvider, ErrorStrategy, SecurityGuard, RunGuard, ReliabilityHarness) plus shared vocabulary types. **Product ports** (ToolBus, SessionStore, Observer = Telemetry metrics/span) and domain contracts (ContextEngine, Memory, MCP, …) live in Harness. Run Observatory (`harness/observability/observer`) is a separate debug product surface β€” see [docs/observer-domain.md](./docs/observer-domain.md). No strategy implementations. **Does not re-export Loop.**
61
-
62
- ### Layer 2: Harness β€” Product Domains
63
-
64
- | Product Domain | Directory | Question |
65
- |----------------|-----------|----------|
66
- | **Governance** | `governance/` | Who may do what? (ACL, security policy, HITL, credentials, ledgers) |
67
- | **Session** | `session/` | How does continuity hold? (aggregate, Discourse, tasks, history) |
68
- | **Agent** | `agent/` | Who is it / how is it configured? (template, persona, builder) |
69
- | **Memory** | `memory/` | What has it learned? (Memory / Cognition / Wisdom substrate) |
70
- | **Knowledge** | `knowledge/` | What does the world write down? (exogenous sources, Knowledge Service, retrieval) |
71
- | **Activation** | `activation/` | How do stimuli become Runs? |
72
- | **Run** | `run/` | How does this episode stay safe? (RunScope, reliability, guard, budget) |
73
- | **Context** | `context/` | What does the model see? (eight-layer assembly, tokens, window) |
74
- | **Extension** | `extension/` | How are capabilities extended? (Plugin/Tool/Skill/MCP, sandbox) |
75
- | **Collaboration** | `collaboration/` | How do multi-Agents / subsystems coordinate? |
76
-
77
- Cross-cutting / foundation (not counted): `observability/`, `context/capabilities/` (summary/compact), `capabilities/document/` (Document extract Port), `shared/`.
78
- Sole count authority: [docs/domains.yaml](./docs/domains.yaml) Β· narrative: [docs/domains.md](./docs/domains.md).
79
-
80
- ### Layer 3: Integration β€” External Adapters
81
-
82
- LLM providers (OpenAI, Anthropic), storage backends (JSONL, SQLite, Memory), Telemetry observability (trace, metrics, exporters β€” config key `observability`), protocols (HTTP), Gateway, TUI, and Web Runtime.
83
-
84
- ---
85
-
86
- ## Context Intelligence β€” 8-Layer Model
87
-
88
- Octopi's unique approach to making agents smarter through better context assembly:
89
-
90
- ```
91
- Wisdom (thinking patterns) ← Highest priority, front of system prompt
92
- Persona (identity, personality)
93
- Skills (workflow guidance) ← Conditionally loaded
94
- Knowledge (external references)← Retrieved on demand
95
- Cognition (concept graph) ← Concept relationships
96
- Memory (actionable insights) ← fact / method / norm from past sessions
97
- Runtime (live run context) ← tasks / guidance / injectedContext (system side)
98
- Information (raw messages) ← Window managed + compressed (message window, not a ContextLayer)
99
- ```
100
-
101
- > Product eight layers = system ContextLayer (1–7, including Runtime) + Information (layer 8, message window).
102
-
103
- This is an **information distillation system**: raw information is refined through layers of increasing abstraction, producing progressively higher-level understanding.
104
-
105
- **Implementation**: `ContextLayer` contracts + `DefaultContextAssembler` in `harness/context/`.
106
- Default path wires Persona / Skill / Knowledge / Memory / Runtime; Wisdom / Cognition remain optional.
107
- See [docs/context-layer-contracts.md](./docs/context-layer-contracts.md).
108
-
109
- ---
110
-
111
- ## Quick Start
112
-
113
- ```typescript
114
- import { AgentBuilder, OpenAIProvider } from 'octopi-agent';
115
-
116
- const { agent, runner } = await new AgentBuilder()
117
- .model(new OpenAIProvider({ apiKey: process.env.OPENAI_API_KEY! }))
118
- .persona('./my-agent')
119
- .build();
120
-
121
- for await (const event of runner.handle('session-1', userMessage)) {
122
- if (event.type === 'llm_stream_delta') {
123
- process.stdout.write(event.data.delta);
124
- }
125
- }
126
- ```
127
-
128
- ### MCP Integration
129
-
130
- Connect any MCP Server (inject the Integration client factory):
131
-
132
- ```typescript
133
- import { AgentBuilder, createSdkMcpClient } from 'octopi-agent';
134
-
135
- const { agent, runner } = await new AgentBuilder()
136
- .model('gpt-4o')
137
- .mcpClientFactory(createSdkMcpClient)
138
- .mcp({
139
- id: 'filesystem',
140
- transport: 'stdio',
141
- command: 'npx',
142
- args: ['-y', '@modelcontextprotocol/server-filesystem', '/data'],
143
- })
144
- .build();
145
- ```
146
-
147
- ### Web Search (multi-provider)
148
-
149
- Configure in `octopi.json` / `~/.octopi/octopi.json` to register the `web_search` tool:
150
-
151
- ```json
152
- {
153
- "webSearch": {
154
- "provider": "mimo",
155
- "fallbacks": ["duckduckgo"],
156
- "defaultLimit": 5,
157
- "timeoutMs": 90000,
158
- "providers": {
159
- "mimo": { "api": "mimo", "apiKey": "${MIMO_API_KEY}", "model": "mimo-v2.5-pro" },
160
- "duckduckgo": { "api": "duckduckgo" }
161
- }
162
- }
163
- }
164
- ```
165
-
166
- Built-in providers: `duckduckgo` (no key), `tavily`, `brave`, `serper`, `mimo`. Failures and empty results fall through `fallbacks`.
167
-
168
- ---
169
-
170
- ## Core Design Principles
171
-
172
- **Agent is a runtime, not a class.** An agent is a complete runtime scope: workspace, session store, tool set, model config, persona. The framework provides mechanisms; the integrator provides policies.
173
-
174
- **Interfaces > implementations.** A framework's value is in its interfaces. `ModelProvider` lets you swap LLM vendors; `SessionStore` lets you change storage; `ContextEngine` lets you compose context management.
175
-
176
- **Security is built-in.** Injection detection, risk evaluation, approval workflows β€” these are not configuration toggles, but built-in constraints. The more powerful agents become, the less security can rely on developer discipline.
177
-
178
- **Files as configuration.** Persona, skills, wisdom, operating instructions β€” all defined as Markdown files. Extension = add a file. Composition = overlay directories.
179
-
180
- **Each domain is independently understandable.** In a vibe coding environment with limited context, you can focus on one domain without understanding the entire system.
181
-
182
- ---
183
-
184
- ## Testing
185
-
186
- ```bash
187
- npm test
188
- ```
189
-
190
- 64 test files, 1022 tests. Three-layer strategy: unit tests (mock), recording/replay, E2E with real APIs. ChaosProvider for fault injection.
191
-
192
- ---
193
-
194
- ## Project Structure
195
-
196
- npm workspaces monorepo β€” five publishable packages:
197
-
198
- ```
199
- octopi-agent Suite (CLI bin: octopi) + config IO
200
- β”œβ”€ @octopi-agent/engine Harness 10 domains + library integrations
201
- β”‚ └─ @octopi-agent/core Loop + Kernel contracts
202
- β”œβ”€ @octopi-agent/gateway HTTP/WS process plane + Web runtime
203
- └─ @octopi-agent/webui Prebuilt Web console (static)
204
-
205
- packages/
206
- core/ Layer 0–1 src/loop + src/core (agentLoop, Kernel ports)
207
- engine/ Layer 2–3 src/harness/** + integration/{providers,storage,mcp,observability,web-search,agent-runtime} + subsystems
208
- gateway/ Layer 3 gateway/, protocols/, web/{api,runtime,sdk,conversation}
209
- webui/ Product Vite React console
210
- src/ Suite cli/, init, config IO + compose, testing/, tui/
211
- tests/ Vitest (root)
212
- docs/ Public docs Β· arch/ Internal design
213
- ```
214
-
215
- Import surfaces:
216
-
217
- | Need | Import |
218
- |------|--------|
219
- | Suite / CLI | `octopi-agent` |
220
- | Runtime | `@octopi-agent/engine` |
221
- | Kernel | `@octopi-agent/core` |
222
- | Gateway / Web client | `@octopi-agent/gateway` |
223
- | Plugin SDK | `@octopi-agent/engine/plugin-sdk/plugin-entry` |
224
-
225
- Runtime config knobs (see `octopi.example.json` + `docs/KNOWN-ISSUES.md`): `toolIsolation`, `sessionAcl`, `agents[].workspace` / `maxSessionRights`, plus capability keys `summary` / `compact` / `models.level.summary`.
226
-
227
- ---
228
-
229
- ## Related Docs
230
-
231
- - [Architecture](./docs/architecture.md) β€” Full architecture design
232
- - [Package split](./arch/npm-package-split.md) β€” Five-package topology (internal handoff)
233
- - [Plugin System](./docs/plugin-system.md) β€” Plugin system details
234
- - [Session Tasks](./docs/task-system.md) β€” SessionTask design baseline
235
- - [Domain Split](./docs/domain-split.md) β€” run-guard / orchestration / AsyncTask boundaries
236
- - [Contributing](./docs/CONTRIBUTING.md) β€” Development guidelines
237
- - [Changelog](./CHANGELOG.md) β€” Version history
238
- - [Web UI Design](./packages/webui/DESIGN.md) β€” Playground visual system & eight-layer inspector
239
-
240
- ---
241
-
242
- ## License
243
-
244
- Apache-2.0 β€” see [LICENSE](./LICENSE) and [NOTICE](./NOTICE).
1
+ # Octopi πŸ™
2
+
3
+ **The Embeddable Agent Engine**
4
+
5
+ > An agent is not a class β€” it's a complete runtime.
6
+ > Runtime, continuity, and governance β€” in one constitution.
7
+
8
+ [δΈ­ζ–‡ζ–‡ζ‘£](./README_CN.md) Β· [Documentation](./docs/) Β· [Architecture](./docs/architecture.md) Β· [Contributing](./docs/CONTRIBUTING.md)
9
+
10
+ ![License](https://img.shields.io/badge/license-Apache--2.0-blue) ![Node](https://img.shields.io/badge/node-%3E%3D24-brightgreen) ![npm](https://img.shields.io/npm/v/octopi-agent?label=octopi-agent)
11
+
12
+ ---
13
+
14
+ ## A loop is not a product
15
+
16
+ An agent loop is a hundred lines of code. Shipping one inside a product is not.
17
+
18
+ Between "works in the demo" and "runs in production" stand five walls:
19
+
20
+ - **Amnesia** β€” every session starts from zero; nothing the agent learned survives.
21
+ - **Garbage memory** β€” a bolted-on vector store happily remembers things it should never have believed.
22
+ - **Context rot** β€” the window fills until the model can no longer see what matters, and nobody can say why.
23
+ - **Unenforced authority** β€” permissions are a promise in a prompt, not a constraint in the engine.
24
+ - **Unattended runs** β€” the first time a run goes sideways at 3 a.m., nothing is watching, and the only policy is `maxTurns`.
25
+
26
+ Frameworks hand you the loop and wish you luck with the walls.
27
+
28
+ **Octopi is the engine that makes the walls its job.** Session continuity as a
29
+ first-class aggregate. A learning substrate with an actual theory of how
30
+ knowledge is formed. A context pipeline you can inspect down to the token.
31
+ Governance that cannot be opted out of. Supervision that knows the difference
32
+ between a resource limit and a behavioral anomaly.
33
+
34
+ ---
35
+
36
+ ## What is Octopi
37
+
38
+ Octopi is an **embeddable agent engine** β€” a component you build AI-powered
39
+ products on, not a standalone app, not a chat wrapper, not an orchestration DSL.
40
+
41
+ - **You keep the boundary.** The Host supplies the `Principal`, maps
42
+ `conversationId ↔ sessionId`, and owns human-level IAM. The engine consumes
43
+ structured `Intent`s and never does permission NLU.
44
+ - **The engine keeps the runtime.** Session, Run, memory, context, tools,
45
+ security, budget, supervision β€” defined ontology, not glue code you invent.
46
+
47
+ ```text
48
+ Your product ── Principal / Intent / IAM ──► Octopi engine ──► Model, Tools, World
49
+ (you own the boundary) (runtime, continuity, governance)
50
+ ```
51
+
52
+ ---
53
+
54
+ ## The Constitution
55
+
56
+ Most frameworks define classes. Octopi defines **law** β€” an ontology with
57
+ exclusive definitions and enforceable invariants. A few of the laws of physics:
58
+
59
+ | Object | What it is |
60
+ |---|---|
61
+ | **Session** | The first-class aggregate of continuity (`sessionId`) |
62
+ | **Discourse** | The session's append-only authoritative log |
63
+ | **Projection** | Any derived view (status / tasks / compact / index) β€” rebuildable, never authoritative |
64
+ | **Agent** | A template: persona, tools, default model, substrate β€” never a bag of live state |
65
+ | **Run / RunScope** | One episode; **all mutable context lives only inside a RunScope** and is discarded after write-back |
66
+ | **Substrate** | What the agent has learned across sessions: Memory / Cognition / Wisdom |
67
+ | **Principal / Intent** | Who drives, and a structured request (`run` / `consult` / `handoff`…) β€” auditable, never inferred from prose |
68
+
69
+ And the invariants they imply:
70
+
71
+ - **I1** β€” Mutable context exists only in a RunScope. Agents are templates; the same agent runs many sessions concurrently without cross-talk (the lease key is `sessionId` β€” from day one).
72
+ - **I2** β€” Discourse is the single authority. Everything else is a projection that can be invalidated and rebuilt.
73
+ - **I3** β€” Accountability β‰  Agency. Being able to act is not being responsible; switching executors is not a `handoff`.
74
+ - **I5** β€” The effect plane is governed exactly like the cognition plane. Tools touch the world; their effects are policy, not trust.
75
+ - **I6** β€” The engine consumes structured Intents and keeps every Principal in the audit log. "Understanding language" belongs to the host; enforcing the law belongs to the engine.
76
+
77
+ ### Constitution-driven development
78
+
79
+ The constitution is not documentation decoration β€” **it is the development
80
+ method, and it is this project's single largest source of reliability.**
81
+
82
+ Every concept has exactly one authoritative definition. Every invariant is an
83
+ enforceable law with a named implementation site and a verification test.
84
+ Design decisions travel through change records and bilingual sync β€” never
85
+ through tribal memory. When code and constitution disagree, the code moves.
86
+
87
+ That is why the invariants above survive concurrency and growth: RunScope
88
+ isolation, Discourse authority, and the permission lattice are not aspirations
89
+ remembered by developers β€” they are **checked**: automated dependency
90
+ boundary checks, catalog single-sources-of-truth, and tests that fail when the
91
+ law is broken. New work is judged by one question first: *does it violate
92
+ the constitution?*
93
+
94
+ πŸ“– **[Read the full constitution β†’](./docs/north-star.en.md)** (δΈ­ζ–‡η‰ˆοΌš[docs/north-star.md](./docs/north-star.md))
95
+
96
+ ---
97
+
98
+ ## Five sciences you won't find in a framework
99
+
100
+ ### 1. The science of knowledge β€” the distillation chain
101
+
102
+ Octopi does not "store memories". It models **how knowledge is formed, falsified,
103
+ and retired**:
104
+
105
+ ```text
106
+ Information ──distil──► Memory ──weave──► Cognition ──condense──► Wisdom
107
+ (raw interaction) (propositions) (concept graph) (maxims)
108
+ ```
109
+
110
+ **Memory β€” propositions, not blobs.** Every entry is a typed proposition:
111
+ `fact` (what is true), `method` (what works), `norm` (what one should do).
112
+ Activity logs, statistical summaries, and persona echoes are *rejected at the
113
+ door*. Six gates (G1–G6) enforce shape, provenance, anti-patterns, retrieval
114
+ anchors, conflict/capacity, and safety. Confidence is priced by origin: a
115
+ `user_directive` enters at **0.9**, the model's own inference at **0.4** β€” and
116
+ an inference without a quotable source lands in **shadow**: searchable, but
117
+ **never injected** into context. Zero memories is a legal state; this system
118
+ would rather know nothing than know garbage.
119
+
120
+ **Cognition β€” a graph that refuses superstition.** Concepts are nodes; edges must
121
+ carry a license. A `causes` edge requires **two independent memories** of
122
+ evidence (or one strengthened memory plus a fail→fix closure) — co-occurrence
123
+ can never graduate into causation. Edges have Hebbian plasticity
124
+ (`w = 1-(1-w)(1-Ξ·Β·e)`) and per-relation decay; new edges enter a fast shadow
125
+ graph and are consolidated into the slow graph. Retrieval is **spreading
126
+ activation** along relations, not keyword matching. The design rule is
127
+ explicit: *a wrongly-strong edge costs more than a missing one.*
128
+
129
+ **Wisdom β€” judgment that can be falsified.** A wisdom entry is a *maxim* β€” "how
130
+ to think about this class of problem" β€” with scenarios, anti-scenarios, and
131
+ effects. Maxims are hypotheses: born `candidate`, proven in `trial`, promoted to
132
+ `active`, and `contested` by counter-evidence or `superseded` by better ones.
133
+ Even factory presets ship at confidence **0.7**, not 1.0. Credit assignment
134
+ shows `applied / assisted / contested` counts β€” never a fake "87% success rate".
135
+
136
+ **The rule that makes it all work:** *the LLM judges intent; code enforces
137
+ structure.* No regex guesses at meaning. No schema pretending to understand.
138
+
139
+ ### 2. The physics of context β€” eight layers Γ— scope
140
+
141
+ "Context engineering" elsewhere means a prompt template. Here it is a **typed,
142
+ owned, budgeted pipeline**:
143
+
144
+ - **Eight content layers**, assembled by priority:
145
+ `Wisdom β†’ Persona β†’ Skill β†’ Knowledge β†’ Cognition β†’ Memory β†’ Runtime β†’ Information`.
146
+ The first seven build the system prompt; the eighth is the message window.
147
+ - **Three ownership bands** β€” Agent substrate (persists across sessions) / Run
148
+ (volatile, never written back to the template) / Session (first-class
149
+ continuity). This *explains* why multiple agents can share one conversation
150
+ while never sharing personality or memory.
151
+ - **Formation β‰  assembly.** The distillation chain (how knowledge forms) and the
152
+ assembly order (what the model sees) are orthogonal axes β€” a distinction the
153
+ rest of the industry has yet to put into words.
154
+ - **Token accounting with calibration** β€” three estimation tiers (LLM-reported β†’
155
+ tokenizer β†’ heuristic, ~1.5 tokens/char for CJK), then a smoothed
156
+ `calibrationRatio` from actuals.
157
+ - **Per-layer budget competition and a manifest** β€” every layer's inclusion or
158
+ drop is reasoned and inspectable. *Why this turn's prompt looks the way it
159
+ does* is a question with an answer.
160
+ - **Compaction keyed by `(sessionId, agentId)`** β€” summaries follow the
161
+ conversation Γ— agent, never polluting the template.
162
+
163
+ ### 3. The law of authority β€” accountability you can enforce
164
+
165
+ - **Effective permission is a lattice intersection**:
166
+ `engine floor ∩ role max ∩ agent maxSessionRights ∩ binding overrides`.
167
+ An illegal grant is rejected **at grant time**, not at use time.
168
+ - **A role catalog as first-class configuration** β€” `owner / specialist /
169
+ reviewer / operator / steward` ship as seeds; your business roles join the
170
+ same catalog. Specialist can read everything and write its own memory β€” but
171
+ accountability stays with the primary.
172
+ - **`handoff` is an audited change of the Principal**, host-controlled by
173
+ default; agents cannot promote themselves. Switching who answers is
174
+ `preferred` + a grant β€” never a silent takeover.
175
+ - **Every run knows who asked.** Principal enters the run record and the audit
176
+ trail; the engine never guesses who is driving.
177
+
178
+ ### 4. The governance of power β€” security and effects as primitives
179
+
180
+ - **Two security layers**: a rule engine that is always on and has **no bypass
181
+ option** (there is no `skip`/`disable` in the guard contract), plus an
182
+ optional LLM safety agent for semantic edge cases.
183
+ - **Five guards** β€” input, output, tool call, tool output, behavior. Shell
184
+ parsing is four layers deep (quote-aware splitting β†’ command recognition β†’
185
+ redirection parsing β†’ wrapper recognition): `rm -rf /` is `critical`,
186
+ `rm -rf ./dist` is `low`. Deterministic injection patterns (`$(...)`,
187
+ backticks, `| bash`) are cut at the boundary.
188
+ - **Six degradation strategies**, not one blunt rejection: substitute command,
189
+ restrict scope, require confirmation, add guardrails, reject, defer to safety
190
+ agent.
191
+ - **Client Tools β€” devices as governed first-class tools.** Client capabilities
192
+ (`photo_capture`, `html_ui`, `mic_listen`, `voice_play`, `location_watch`, …)
193
+ register as tools the model can call like any other β€” but sensitive devices
194
+ require an explicit `purpose` and consent (`none / prompt / strict`). Red
195
+ lines: no silent collection, no forged consent, no empty success, no raw bulk
196
+ bytes in context. Identity is four orthogonal axes β€” Principal Β·
197
+ ClientInstance Β· Agent Β· Run β€” so a device belongs to a *person*, not to an
198
+ agent.
199
+ - **Retrieved knowledge is wrapped as material, not instruction** β€” grounding
200
+ blocks are labelled untrusted reference content, and audit keeps the full
201
+ text. Retrieval poisoning is defused at the wrapping layer.
202
+
203
+ ### 5. The engineering of runs β€” reliability and activation
204
+
205
+ - **Budget βŠ₯ Guard, by design.** A resource cap is not a behavioral anomaly.
206
+ Accounting **records and never kills**; policy is the deployer's opt-in;
207
+ control degrades gracefully: `observe β†’ warn β†’ compact β†’ wrap-up β†’ stop`.
208
+ The engine will not guillotine a healthy multi-tool task over nominal token
209
+ sums β€” that bug killed real runs (31 turns aborted at a phantom "2M tokens"),
210
+ and the redesign made it structurally impossible.
211
+ - **Cache-aware metering** β€” `inputUncached / inputCached / inputCacheWrite`
212
+ are first-class quantities; fabricating cache by subtraction is forbidden.
213
+ - **A taxonomy of failure** β€” Loop Β· Thrash Β· Drift Β· Stall Β· Blowup Β· Burn β€”
214
+ with a recovery escalation ladder: `inject_hint β†’ stronger hint β†’ truncate β†’
215
+ stop`. Three consecutive recoveries of the same failure kind end the run.
216
+ - **The reliability toolbox**: planning-only retry, empty-response retry, no-op
217
+ detection, tool-loop detection (Rabin–Karp fingerprinting), circuit breakers,
218
+ and a two-layer TaskSupervisor (rule detection β†’ LLM review).
219
+ - **Activation β€” stimuli become supervised runs.** Schedules, events,
220
+ escalations, agent signals and webhooks are *compiled* into runs
221
+ (Trigger β†’ Dispatch β†’ Coalesce) with de-duplication and a single session
222
+ mutex β€” no second execution queue. Between two user messages, things happen.
223
+ - **Autonomous subsystems** with a five-dimension model β€”
224
+ `Sense + Think + Act + Signal + Boundary` β€” declared as directories
225
+ (`SUBSYSTEM.md` + `config.yaml` + `handler.ts`). Four ship in the box:
226
+ `memory-steward`, `wisdom-steward`, `cognition-steward`, `safety-guard`.
227
+ The stewards are how the substrate stays clean as it grows.
228
+
229
+ ---
230
+
231
+ ## Architecture
232
+
233
+ Four layers. One dependency rule: **outer β†’ inner. Core has zero outer
234
+ dependencies.**
235
+
236
+ ```text
237
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
238
+ β”‚ Layer 3 Integration β€” providers Β· storage Β· telemetry Β· β”‚
239
+ β”‚ HTTP/WS gateway Β· TUI Β· web runtime β”‚
240
+ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”‚
241
+ β”‚ β”‚ Layer 2 Harness β€” 10 product domains + cross-cutting β”‚β”‚
242
+ β”‚ β”‚ governance Β· session Β· agent Β· memory Β· β”‚β”‚
243
+ β”‚ β”‚ knowledge Β· activation Β· run Β· context Β· β”‚β”‚
244
+ β”‚ β”‚ extension Β· collaboration β”‚β”‚
245
+ β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”‚β”‚
246
+ β”‚ β”‚ β”‚ Layer 1 Core β€” EventBus Β· StateMachine Β· β”‚β”‚β”‚
247
+ β”‚ β”‚ β”‚ Kernel ports (ModelProvider, Security- β”‚β”‚β”‚
248
+ β”‚ β”‚ β”‚ Guard, RunGuard, ErrorStrategy, …) β”‚β”‚β”‚
249
+ β”‚ β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”‚β”‚β”‚
250
+ β”‚ β”‚ β”‚ β”‚ Layer 0 Loop β€” pure async generator: β”‚β”‚β”‚β”‚
251
+ β”‚ β”‚ β”‚ β”‚ agentLoop Β· callModel Β· classifyError β”‚β”‚β”‚β”‚
252
+ β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β”‚β”‚β”‚
253
+ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β”‚β”‚
254
+ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β”‚
255
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
256
+ ```
257
+
258
+ Octopi Harness is organized as **10 product domains** β€” governance, session,
259
+ agent, memory, knowledge, activation, run, context, extension, collaboration β€”
260
+ grouped on three planes: *authority* (governance Β· session Β· agent Β· memory Β·
261
+ knowledge), *phase* (activation Β· run), and *capability* (context Β· extension Β·
262
+ collaboration). The count authority is
263
+ [docs/domains.yaml](./docs/domains.yaml); the narrative is
264
+ [docs/domains.md](./docs/domains.md).
265
+
266
+ The Loop layer is a **pure async generator** β€” zero state, zero external
267
+ dependencies β€” so the entire runtime above it is contracts you can swap:
268
+ `ModelProvider`, `SessionStore`, `ContextEngine`, `SecurityGuard`, …
269
+
270
+ ---
271
+
272
+ ## Quick Start
273
+
274
+ **Prerequisites**: Node.js β‰₯ 24.
275
+
276
+ ```bash
277
+ npm install octopi-agent
278
+ ```
279
+
280
+ ### Fastest path β€” the CLI
281
+
282
+ ```bash
283
+ npx octopi init # scaffold OCTOPI_HOME: agents/, sessions/, config
284
+ npx octopi doctor # verify the environment
285
+ npx octopi chat # talk to your agent in the terminal
286
+ npx octopi serve # start the gateway (REST + WS)
287
+ ```
288
+
289
+ ### Embed in code
290
+
291
+ ```typescript
292
+ import { AgentBuilder, OpenAIProvider } from 'octopi-agent';
293
+
294
+ const { agent, runner } = await new AgentBuilder()
295
+ .model(new OpenAIProvider({ apiKey: process.env.OPENAI_API_KEY! }))
296
+ .persona('./my-agent')
297
+ .build();
298
+
299
+ for await (const event of runner.handle('session-1', userMessage)) {
300
+ if (event.type === 'llm_stream_delta') {
301
+ process.stdout.write(event.data.delta);
302
+ }
303
+ }
304
+ ```
305
+
306
+ ### Files as configuration
307
+
308
+ Persona and skills are plain Markdown β€” diffable, reviewable, versionable.
309
+ Extension = add a file. Composition = overlay directories.
310
+
311
+ ```text
312
+ my-agent/
313
+ β”œβ”€β”€ AGENTS.md # main persona β€” loaded first
314
+ β”œβ”€β”€ persona/ # supplemental persona, alphabetical
315
+ β”‚ β”œβ”€β”€ 10-soul.md
316
+ β”‚ β”œβ”€β”€ 20-identity.md
317
+ β”‚ └── 30-user.md
318
+ └── skills/
319
+ └── deploy/
320
+ └── SKILL.md # two-stage loaded: metadata now, content on demand
321
+ ```
322
+
323
+ The learning substrate (Memory / Cognition / Wisdom) lives in a per-agent
324
+ SQLite store β€” it is *grown*, not hand-written. See [docs/memory.md](./docs/memory.md).
325
+
326
+ ### Mount MCP servers
327
+
328
+ ```typescript
329
+ import { AgentBuilder, createSdkMcpClient } from 'octopi-agent';
330
+
331
+ const { agent, runner } = await new AgentBuilder()
332
+ .model('gpt-4o')
333
+ .mcpClientFactory(createSdkMcpClient)
334
+ .mcp({
335
+ id: 'filesystem',
336
+ transport: 'stdio',
337
+ command: 'npx',
338
+ args: ['-y', '@modelcontextprotocol/server-filesystem', '/data'],
339
+ })
340
+ .build();
341
+ ```
342
+
343
+ ---
344
+
345
+ ## Capability tour
346
+
347
+ | Capability | One-liner | Details |
348
+ |---|---|---|
349
+ | **Plugins & hooks** | Interceptor + observer semantics, priority-ordered, per-handler timeout; full lifecycle coverage from model resolve to loop end | [docs/plugin-system.md](./docs/plugin-system.md) |
350
+ | **Skills** | Two-phase loading: frontmatter at boot, content on demand β€” 100 skills cost a few hundred tokens | [docs/plugin-system.md](./docs/plugin-system.md) |
351
+ | **MCP** | Native, namespaced `{serverId}__{toolName}`; stdio/SSE | [docs/architecture.md](./docs/architecture.md) |
352
+ | **Knowledge** | Sources are authority, indexes are rebuildable; two-phase indexing (searchable in minutes); Global/Project/Session scopes; independent Knowledge Service owns `knowledge.db` | [docs/knowledge.md](./docs/knowledge.md) |
353
+ | **Session tasks** | Goals and steps as session projections with task tools | [docs/task-system.md](./docs/task-system.md) |
354
+ | **Web search** | `web_search` tool; providers duckduckgo / tavily / brave / serper / mimo with ordered fallbacks | `octopi.example.json` |
355
+ | **Document port** | PDF / Office extraction as a shared capability (`documents.*`) | [docs/architecture.md](./docs/architecture.md) |
356
+ | **Multi-agent** | Swarm topologies (hierarchical / pipeline / broadcast / peer-to-peer) over governed roles | [docs/domains.md](./docs/domains.md) |
357
+ | **Human-in-the-loop** | Approval requests/decisions as engine contracts, surfaced in gateway & UI | [docs/architecture.md](./docs/architecture.md) |
358
+ | **Observability** | Telemetry (traces, metrics, exporters) + a run observatory for debugging | [docs/observer-domain.md](./docs/observer-domain.md) |
359
+ | **Surfaces** | Terminal (TUI), gateway (REST + WS), web runtime with a context inspector | [docs/architecture.md](./docs/architecture.md) |
360
+
361
+ ---
362
+
363
+ ## Design principles
364
+
365
+ 1. **An agent is a runtime, not a class.** Workspace, session store, tools,
366
+ model config, persona β€” a scope, not an object.
367
+ 2. **Mechanism, not policy.** The framework provides mechanisms; the integrator
368
+ provides policies. Defaults are opt-in, never smuggled in as engine law.
369
+ 3. **Interfaces over implementations.** Swap the model vendor, the storage, the
370
+ context engine β€” the contract stays.
371
+ 4. **Security is built in.** Not toggles. The more capable agents become, the
372
+ less safety can depend on developer discipline.
373
+ 5. **Files as configuration.** Markdown for persona, skills, commands. Git is
374
+ the editor.
375
+ 6. **The host keeps the boundary.** Human IAM, routing, and identity stay in
376
+ your product; the engine enforces, never impersonates.
377
+ 7. **Each domain is independently understandable.** You can work on one domain
378
+ without holding the whole system in your head.
379
+
380
+ ---
381
+
382
+ ## Testing & quality
383
+
384
+ ```bash
385
+ npm test
386
+ ```
387
+
388
+ 240+ test files on a three-tier discipline: unit (mocks), **record/replay**
389
+ (deterministic regressions), and E2E against real APIs β€” plus `ChaosProvider`
390
+ fault injection and architecture dependency checks. Testing is not coverage
391
+ theater; it is how the invariants stay invariant.
392
+
393
+ ---
394
+
395
+ ## Status & boundaries
396
+
397
+ Octopi is v0.7x and moving fast. Being honest about the edges:
398
+
399
+ - **Deployment assumption**: single process is the v1 reality; cross-process
400
+ requires a distributed Session Lease (in-process lease exists today).
401
+ - **Collaboration domain** ships with `status: incomplete` β€” semantics are
402
+ defined; some implementations are staged.
403
+ - **Not for everyone**: if a single-vendor SDK's loop is enough, or you need a
404
+ vertical business workflow engine, or human-level IAM inside the engine β€”
405
+ Octopi is not what you want. It is an engine for products that need
406
+ continuity, learning, and governance *below* their own product logic.
407
+
408
+ Open items live in [docs/KNOWN-ISSUES.md](./docs/KNOWN-ISSUES.md).
409
+
410
+ ---
411
+
412
+ ## Packages & import surfaces
413
+
414
+ Five publishable packages (npm workspaces):
415
+
416
+ ```text
417
+ octopi-agent Suite (CLI bin: octopi) + config IO
418
+ β”œβ”€ @octopi-agent/engine Harness 10 domains + integrations
419
+ β”‚ └─ @octopi-agent/core Loop + Kernel contracts
420
+ β”œβ”€ @octopi-agent/gateway HTTP/WS process plane + web runtime
421
+ └─ @octopi-agent/webui Prebuilt web console
422
+ ```
423
+
424
+ | Need | Import |
425
+ |---|---|
426
+ | Suite / CLI | `octopi-agent` |
427
+ | Runtime | `@octopi-agent/engine` |
428
+ | Kernel | `@octopi-agent/core` |
429
+ | Gateway / web client | `@octopi-agent/gateway` |
430
+ | Plugin SDK | `@octopi-agent/engine/plugin-sdk/plugin-entry` |
431
+
432
+ ---
433
+
434
+ ## Documentation
435
+
436
+ - **Concepts** β€” [Constitution](./docs/north-star.en.md) Β· [Domains](./docs/domains.md) Β· [Memory](./docs/memory.md) Β· [Knowledge](./docs/knowledge.md) Β· [Context layers](./docs/context-layer-contracts.md) Β· [Tasks](./docs/task-system.md) Β· [Plugins](./docs/plugin-system.md) Β· [Autonomous subsystems](./docs/autonomous-subsystem.md) Β· [Observer](./docs/observer-domain.md)
437
+ - **Guides** β€” [Contributing](./docs/CONTRIBUTING.md) Β· [Known issues](./docs/KNOWN-ISSUES.md) Β· [Example config](./octopi.example.json) Β· [JSON schema](./octopi.schema.json)
438
+ - **Reference** β€” [Architecture](./docs/architecture.md) Β· [Domain catalog](./docs/domains.yaml) Β· [Changelog](./CHANGELOG.md)
439
+
440
+ ---
441
+
442
+ ## License
443
+
444
+ Apache-2.0 β€” see [LICENSE](./LICENSE) and [NOTICE](./NOTICE).