xopc
AGENTS.md37 starsChanged 2 months agoMITView on GitHub
Guide for AI assistants working on this repository. xopc (@xopcai/xopc) is a personal AI assistant on Node.js + TypeScript: CLI, HTTP/realtime gateway (REST + WebSocket), and a React gateway console (web/). Channels (e.g. Telegram) load as extensions; additional backends appear in config/registry as the project evolves. Examples: pnpm run dev -- agent -i · pnpm run dev -- agent -m "Hello" Runtime (src/) — main areas agents touch: Also present (follow local patterns): auth/, automations/, chat-commands/ (in-chat slash commands), daemon/,…
- Reads credentials
- Installs packages
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about checking a change actually works.
Of the AGENTS.md files we read, the 11,773 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository20 other files it gives its agents.
- .claude/CLAUDE.mdCLAUDE.md
- .cursor/rules/deveco-flow.mdcCursor rule
- frontend-designSkill
- hatch-petSkill
- theme-factorySkill
- doc-coauthoringSkill
- docxSkill
- pdfSkill
- pptxSkill
- xlsxSkill
- build-xopc-local-appSkill
- define-taskSkill
- design-recurring-workSkill
- diagnoseSkill
- tddSkill
- workflow-authoringSkill
- find-skillsSkill
- githubSkill
- summarizeSkill
- webapp-testingSkill
The file
We split this AGENTS.md into the rules it gives an agent
9 rules. About 0 are common, 3 are distinctive, and 6 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈3
Distinctive · estimate
This author's own choices. Worth a look.
6
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 118
Use createLogger('Prefix') from src/utils/logger.ts (Pino under the hood).
- Distinctive: line 143
Spam: do not emit the same warn/error on every iteration once a condition is true (e.g.
- Very specific: line 144
Secrets: avoid logging raw tokens, API keys, or full Authorization headers.
- Very specific: line 236
Use xopc agents list, xopc agents add, xopc agents delete to manage agents.list and initialize directories — there is no separate agent …
- Very specific: line 349
Select controls: Use the project-owned select components from web/src/components/ui/popover-select.tsx (Select, SelectOption, or …
- Distinctive: line 363
New logs: follow Logging conventions.
- Very specific: line 392
Add positive mapping assertions for every new route family and at least one nearby negative/non-overlap assertion in …
- Distinctive: line 393
Before considering the route complete, test the real path through a running Gateway with authentication.
- Very specific: line 401
Model input: Use SessionStore.loadMessages / sessionStore.load (they apply buildSessionContextForLlm).
≈ “Common” is an estimate: at least 1 in 5 of the 16,595 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
AGENTS.md - xopc Development Guide
Guide for AI assistants working on this repository.
Table of Contents
- Project Overview
- Quick Start
- Tech Stack
- Project Structure
- Model Registry
- Code Style
- Logging conventions
- Key Patterns
- Common Tasks
- Configuration
- Environment Variables
- Testing
- Web UI
- Debugging
- Troubleshooting
- When Making Changes
Project Overview
xopc (@xopcai/xopc) is a personal AI assistant on Node.js + TypeScript: CLI, HTTP/realtime gateway (REST + WebSocket), and a React gateway console (web/). Channels (e.g. Telegram) load as extensions; additional backends appear in config/registry as the project evolves.
| Metric | Value |
| Core | TypeScript on Node.js >= 22.22.3 |
| LLM layer | ~23 built-in providers via @earendil-works/pi-ai (KnownProvider); more via models.json |
| Tests | vitest (src/**/__tests__/*.test.ts) |
Quick Start
pnpm install
pnpm run dev -- <command> # no build required for dev CLI
pnpm run build # Node: tsdown (`tsdown.config.ts`) + web; types: `pnpm run typecheck`
pnpm test # fast unit suite
pnpm run test:all # complete regression suiteExamples: pnpm run dev -- agent -i · pnpm run dev -- agent -m "Hello"
Tech Stack
| Area | Stack |
| Agent | @earendil-works/pi-agent-core, @earendil-works/pi-ai |
| CLI | commander |
| Config | zod |
| Tools (schemas) | @sinclair/typebox |
| Gateway console | React + Vite + Tailwind v4 (web/ package) |
| Tests | vitest |
Project Structure
Runtime (src/) — main areas agents touch:
| Path | Role |
agent/ | AgentService, tools, memory, orchestration (core entry files at root; helpers grouped under context/, lifecycle/, prompt/, transcript/ — transcript hygiene, thinking-level types, etc.) |
agent/mcp/ | Outbound bundle-MCP: session runtimes, transports, tool materialize (server__tool names) |
mcp/ | Inbound channel bridge (xopc mcp serve) — stdio MCP server + gateway REST/realtime client |
channels/ | ChannelPlugin, manager, inbound/outbound, attachments/, plugins/bundled.ts |
gateway/ | HTTP + realtime WebSocket server, API for UI; heartbeat/ keep-alive service |
cli/ | Commands (self-registration via registry) |
config/ | Schema, loader, paths |
providers/ | resolveModel, API keys, pi-ai bridge |
session/ | Conversation session store |
infra/ | Infrastructure primitives (retry, rate-limit, bus/ message bus) |
extensions/ | Extension runtime; extensions/sdk/ re-exports @xopcai/xopc/extension-sdk |
Also present (follow local patterns): auth/, automations/, chat-commands/ (in-chat slash commands), daemon/, routing/, voice/stt/, voice/tts/, utils/ (logger.ts barrel → logger/ implementation + helpers.ts), markdown/, errors/, etc.
Gateway console (web/) — React SPA (Vite + Tailwind v4): hash router, REST + realtime WebSocket to the gateway, Zustand + SWR. Production build outputs to dist/gateway/static/root (same static root the gateway serves).
Extensions (extensions/) — optional add-ons; Telegram / Weixin channel sources live in extensions/telegram and extensions/weixin but are private workspace packages (not published). tsdown (Rolldown) unbundle mode emits dist/src/** and dist/extensions/** in one pass. Wiring: src/generated/bundled-channel-plugins.ts (pnpm run generate:bundled-channels) and src/channels/plugins/bundled.ts.
Model Registry Architecture
src/providers/index.ts sits on @earendil-works/pi-ai: resolve models, map API keys from config/env, expose provider lists to CLI/UI. The built-in provider id set matches upstream KnownProvider; PROVIDER_META adds display names and categories (common / specialty / enterprise / oauth). Extra vendors are added only when present in models.json. Keys load at process start—restart after credential changes.
| Function | Purpose |
resolveModel(ref) | Model id + optional provider/ prefix |
getApiKey / isProviderConfigured | Auth from config or env |
getAllProviders / getModelsByProvider | Discovery for UI |
Details: docs/models.md.
Code Style Guidelines
- Comments: English only; minimal—non-obvious logic, edge cases, exported APIs (JSDoc).
- Naming:
camelCase(code),PascalCase(types/classes),UPPER_SNAKE_CASE(constants),_unusedfor unused params,_privateMethodfor private helpers. - Imports: external deps → internal absolute → relative (blank lines between groups). Example in repo:
src/agent/tools/*.ts. - Files:
camelCase.tssources;*.test.tstests;*.types.tsfor dedicated type modules.
Logging conventions
Use createLogger('Prefix') from src/utils/logger.ts (Pino under the hood). Prefer a stable module prefix (e.g. AgentService, Hono:Auth) so gateway Log Manager and file logs filter cleanly.
Shape: object first, message second
const log = createLogger('MyModule');
log.info({ conversationId, durationMs }, 'Session saved');
log.warn({ path, errorMessage: em }, `Config read failed: ${em}`);
log.error({ err, requestId, phase: 'outbound_consume' }, `Outbound pipeline failed: ${em}`);- First argument: structured fields (
err,conversationId,path,tool,phase, counts, ids). PassErrorinstances aserrso the formatter keeps name / message / stack. - Second argument (
msg): a short, scannable sentence for humans and UIs that mostly show the message column. Repeat the one-line outcome there (e.g. failure reason), not only in fields. - For non-
Errorthrows, adderrorMessage: String(x)(and/or embed the text inmsg) so logs stay grep-friendly.
What to include for debugging
- Identity:
conversationId,channel,chatId,requestId(often injected via async context—see below), filepath,tool/toolName,modelReforprovider+modelId. - Operation: a
phaseor verb inmsg(inbound_consume,publishOutbound,lifecycle emit llm_request, …). - Bounded previews: long strings as
contentPreview/linePreview/goalPreview(truncated), not full payloads.
What to avoid
- Vague
msgonly ('failed','Error') with no structured context. - Spam: do not emit the same warn/error on every iteration once a condition is true (e.g. “approaching limit” on each LLM call). Log once when crossing the threshold or once per logical phase.
- Secrets: avoid logging raw tokens, API keys, or full
Authorizationheaders. Structured redaction runs insrc/utils/logger/redact.ts; disable only with care viaXOPC_LOG_REDACTION=false.
Request correlation (gateway / agent)
HTTP and request-stream paths attach context via runWithLogContext / updateAsyncLogContext (src/utils/logger/context.ts) and gateway middleware (src/gateway/hono/middleware/log-context.ts). Prefer keeping requestId (and related keys) in async context so logs tie to a single API call without threading an argument through every function.
Reference
- Implementation:
src/utils/logger/(index.ts,context.ts,log-store.ts,redact.ts, …). - Longer notes:
src/utils/README.logger.md.
Key Patterns
CLI self-registration
src/cli/commands/<name>.ts calls register({ id, factory, metadata }); wire the module from src/cli/index.ts.
Tools (Typebox)
const MyToolSchema = Type.Object({ param: Type.String() });
export const myTool: AgentTool<typeof MyToolSchema, {}> = {
name: 'my_tool',
parameters: MyToolSchema,
async execute(toolCallId, params, signal, onUpdate) {
return { content: [{ type: 'text', text: '…' }], details: {} };
},
};Register in AgentService / tools index as existing tools do.
AgentService
MessageBus + AgentService with workspace, model, and config (including tools.web.search for web search); await agent.start().
Channels
Implement ChannelPlugin (src/channels/plugin-types.ts). Bundled list: src/channels/plugins/bundled.ts (imports src/generated/bundled-channel-plugins.ts). Telegram / Weixin: sources under extensions/telegram, extensions/weixin; stable imports from src/channels/telegram/index.js, src/channels/weixin/index.js.
Access: DM policies pairing | allowlist | open | disabled; group open | disabled | allowlist. See Configuration.
Telegram draft streaming
import { DraftStreamManager } from '@xopcai/xopc/channels/telegram/draft-stream.js';Common Tasks
| Task | Steps |
| New CLI command | src/cli/commands/<name>.ts + register + import in src/cli/index.ts |
| Package / gateway update | src/infra/update-runner.ts (runGatewayUpdateWithPostSteps), src/extensions/update.ts, src/infra/update-restart.ts; CLI update, gateway POST /api/update/* — see docs/update.md |
| New tool | src/agent/tools/<area>.ts → export from src/agent/tools/index.ts → wire in AgentService |
| New provider | Prefer upstream pi-ai; else OpenRouter / Vercel AI Gateway for custom bases. See pi-ai. |
| New channel plugin | ChannelPlugin + optional defineChannelPluginEntry → bundled.ts if shipping in core |
| New gateway console screen | web/src/pages/<name>.tsx or web/src/features/<area>/; register route in web/src/app.tsx; follow Web UI. |
| New authenticated Gateway API | Add the handler to its route module, then always add or verify its matcher in src/gateway/hono/routes/lazy-bundles.ts and add a mapping assertion in src/gateway/hono/routes/__tests__/lazy-bundles.test.ts. |
| MCP servers / channel bridge | Config: mcp.servers in xopc.json; outbound runtime src/agent/mcp/; inbound src/mcp/ + xopc mcp serve; UI #/settings/agent-mcp. See docs/cli/mcp.md. |
| Dependencies | pnpm only — never commit package-lock.json (use pnpm-lock.yaml). |
| GitHub issues / PRs | Templates under .github/ISSUE_TEMPLATE/; process in CONTRIBUTING.md; sync labels with ./scripts/sync-github-labels.sh |
| Electron desktop | Packaged app: pnpm run build && pnpm run electron:build. The main process keeps Electron shell data in userData, but xopc config/state/workspace use the shared ~/.xopc root (XOPC_STATE_DIR, XOPC_CONFIG_PATH, XOPC_WORKSPACE). First-time shared config init uses Zod (ConfigSchema) only via initWorkspace({ skipChannelPluginValidation: true }) so it does not load bundled channel plugins. Channel plugin configSchema.validate still runs when the gateway subprocess (out/server/index.js) starts. |
Configuration
Default path: ~/.xopc/xopc.json (override with XOPC_CONFIG or XOPC_CONFIG_PATH).
| Section | Purpose |
providers | LLM API keys |
agents.default | Default agent id for routing/session creation |
agents.defaults | One global model, skill, tool, workflow, and runtime policy inherited by every agent |
userContext | Global user understanding, memory, privacy, provider routing, and dreaming settings shared by every agent |
agents.list | Agent ids, personality, workspace, and optional capability overrides |
channels | Telegram and other channel configs |
gateway | HTTP + realtime WebSocket |
mcp | Outbound MCP server registry (mcp.servers) + session idle TTL |
extensions | Enable/disable extensions |
Multiple agents (agents.list)
Runtime configuration has exactly two layers: agents.defaults, then the matching entry in agents.list. The selected conversation metadata agent id resolves to one enabled entry; its explicitly configured fields override or merge with the global defaults according to that field's schema. There is no preset graph, generic recursive merge, lock, or compatibility layer. Default agent id: agents.default, else the first enabled entry, else main. On-disk paths (~/.xopc/agents/<id>/ including profile Markdown and Markdown workspace roots) resolve via src/agent/agent-scope.ts.
Model selection uses fixed intents under models.intents: fast, reasoning, coding, review, vision, and understanding. Workflows may reference one of these intents or a direct provider/model ref. Resolution: src/config/agent-model-intents.ts.
Use xopc agents list, xopc agents add, xopc agents delete to manage agents.list and initialize directories — there is no separate agent registry outside config.
Telegram (multi-account sketch)
{
"channels": {
"telegram": {
"enabled": true,
"accounts": {
"personal": {
"botToken": "…",
"dmPolicy": "allowlist",
"groupPolicy": "open",
"allowFrom": [123456789],
"streamMode": "partial"
}
}
}
}
}dmPolicy / groupPolicy / streamMode (off | partial | block) — full examples in repo docs or tests.
Environment Variables
| Variable | Purpose |
| Per-provider env vars | See src/providers/env-keys.ts PROVIDER_ENV_MAP (aligned with pi-ai, e.g. OPENAI_API_KEY, ANTHROPIC_OAUTH_TOKEN / ANTHROPIC_API_KEY, AI_GATEWAY_API_KEY / VERCEL_AI_GATEWAY_API_KEY, …). DashScope (image, speech, STT): DASHSCOPE_API_KEY (dashscope service id). Custom OpenAI-compatible vendors: configure in models.json. |
TELEGRAM_BOT_TOKEN | Telegram (if not only in config) |
XOPC_CONFIG, XOPC_CONFIG_PATH | Config file path |
XOPC_SKILLS_STORE_URL | Overrides gateway.skillsStoreBaseUrl (skills marketplace REST base) |
XOPC_WORKSPACE | Workspace directory |
XOPC_LOG_LEVEL | trace … fatal (default info) |
XOPC_LOG_DIR, XOPC_LOG_CONSOLE, XOPC_LOG_FILE, XOPC_LOG_RETENTION_DAYS | Logging |
XOPC_PRETTY_LOGS | Dev-friendly log formatting |
XOPC_GOOGLE_ANTIGRAVITY_OAUTH_CLIENT_ID, XOPC_GOOGLE_ANTIGRAVITY_OAUTH_CLIENT_SECRET | Google Antigravity OAuth (Cloud Code–style desktop client; required for xopc auth / gateway OAuth on that provider — set locally, never commit) |
XOPC_GOOGLE_GEMINI_CLI_OAUTH_CLIENT_ID, XOPC_GOOGLE_GEMINI_CLI_OAUTH_CLIENT_SECRET | Google Gemini CLI (Cloud Code Assist) OAuth — same as above |
Testing
pnpm test # unit tests
pnpm run test:integration
pnpm run test:web
pnpm run test:extensions
pnpm run test:packages
pnpm run test:all # every Vitest project
pnpm vitest run src/agent/tools/__tests__/send-media.test.ts
pnpm vitest --watch
pnpm vitest run --coverageCo-located tests: src/**/__tests__/*.test.ts. Use describe / it / expect / vi.mock like existing files.
See Testing.
Remote access
Gateway defaults to loopback. External access layers:
| Layer | Config / CLI | Docs |
| Tailscale Serve | gateway.tailscale.mode=serve, xopc gateway --tailscale serve | docs/gateway/tailscale.md |
| SSH tunnel | xopc gateway ssh-tunnel --target user@host | docs/gateway/remote.md |
| FRP public tunnel | tunnel.*, #/settings/remote-access | docs/remote-access.md · tunnel-security |
| CLI remote mode | gateway.mode=remote, gateway.remote.* | docs/network.md |
Key paths: src/infra/tailscale.ts, src/gateway/tailscale-lifecycle.ts, src/remote-access/, src/tunnel/.
Web UI
Gateway console (React)
The gateway console is the web/ package: React 19, React Router 7 (createHashRouter), Vite, Tailwind CSS v4 (@import "tailwindcss" in app CSS), Zustand (gateway/theme/locale stores), SWR (SwrProvider), Lucide icons, Radix primitives where needed (e.g. Dialog). Roadmap and parity notes: docs/web-migration-plan.md.
cd web && pnpm install && pnpm run dev # Vite dev server
cd web && pnpm run build # → ../dist/gateway/static/root (gateway static root)| Area | Location / convention |
| App shell, nav | web/src/components/shell/ (app-shell.tsx, sidebar.tsx, …) |
| Routes | web/src/app.tsx (createHashRouter); pages under web/src/pages/ |
| Feature modules | web/src/features/<domain>/ (e.g. chat/, gateway/, sessions/) |
| Component primitives | web/src/components/ui/ (Radix-oriented building blocks) |
| API access | web/src/lib/fetch.ts (apiFetch / fetchJson) + apiUrl(); sends Authorization: Bearer <token> from gateway-store |
| Gateway token / URL | web/src/stores/gateway-store.ts |
| i18n | web/src/i18n/messages.ts (en / zh) |
| Global styles + tokens | web/src/styles/globals.css (@theme { … } for semantic colors) |
Routing (hash): / → /chat; chat /chat, /chat/new, /chat/:conversationId. The capability center owns discovery, Agent profiles, skills, connectors, messaging channels, and extensions under /capabilities/{discover|agents|skills|connectors|channels|extensions}; Agent and channel details append /:detailId. Global inherited Agent capabilities remain at /settings/agent-defaults; browser setup lives at /settings/agent-browser. Other full-screen settings include /settings/gateway, /settings/appearance, /settings/capabilities/{models|image|voice|search}, /settings/heartbeat, /settings/sessions, and /settings/logs, plus top-level /tasks, /projects, /automations, and /workflows.
Gateway integration:
- REST: same origin
fetchviaapiUrl('/api/...'); 401 →gateway-storeonUnauthorized. - Agent streaming: submit input with
POST /api/sessions/:conversationId/inputs, then subscribe torun:<runId>on the shared realtime connection. Seeweb/src/features/chat/. - Realtime events: issue a one-time ticket with
POST /api/realtime/tickets, then connect toWS /api/realtime/v1/ws; the bridge lives inweb/src/features/gateway/gateway-realtime-bridge.tsx. Dots in event names become hyphenatedwindowevents (e.g.config.reload→config-reload). - Navigate to chat from other pages:
window.dispatchEvent(new CustomEvent('navigate-to-chat', { detail: { conversationId } }))— handled inAppShell.
Design system: Follow docs/design/ui-design-system.md — calm slate neutrals, blue only for primary actions / links / AI hints; prefer borders over heavy shadows in dark mode; short copy. Implement with web/src/styles/globals.css semantic tokens (bg-surface-*, text-fg*, border-edge, accent, etc.) and Tailwind utilities—do not add a second token system under web/ unless extending @theme there.
- Loading states: Data-loading UI in the gateway console must use skeleton screens instead of plain loading text or page-level spinners. Use
web/src/components/ui/skeleton.tsxfor local placeholders, and reuseweb/src/features/settings/settings-loading-skeleton.tsxfor settings page/panel/list loading states. Keep button-level spinners only for short user-triggered actions such as save, refresh, OAuth, and diagnostics. - Select controls: Use the project-owned select components from
web/src/components/ui/popover-select.tsx(Select,SelectOption, orPopoverSelect) for dropdowns and option picking. Do not introduce raw native<select>styling or third-party select widgets unless there is a strong compatibility reason.
Modal sizing: Complex modals and detail dialogs must use a fixed responsive outer size (h-[min(...)] + fixed width) with overflow-hidden; keep header/footer fixed and put variable content in an internal min-h-0 flex-1 overflow-y-auto region. Do not let modal height shrink/grow based on content, because different records should not cause visual jumps.
Lint / typecheck: cd web && pnpm run lint · pnpm run type-check. Tests: when added, colocate web/src/**/__tests__/*.test.ts and run with root vitest if wired; until then, rely on pnpm run build for the web project.
Debugging
- Level:
XOPC_LOG_LEVEL=debug(ortrace). - CLI:
pnpm run dev -- config show·config validate· (config --show/config --validatelegacy aliases). - Code:
runWithLogContext/updateAsyncLogContextinsrc/utils/logger/context.ts;queryLogs/getFileLogStatsinsrc/utils/logger/log-store.ts;getRuntimeLogStatsinsrc/utils/logger/stats.ts. - Console logs: gateway + Log Manager tab (default dev URL is project-specific—use your configured gateway port).
- New logs: follow Logging conventions.
Troubleshooting
| Symptom | Check |
ERR_MODULE_NOT_FOUND | pnpm install |
@vscode/ripgrep missing at runtime | allowBuilds in pnpm-workspace.yaml must include @vscode/ripgrep (ships the rg binary); re-run pnpm install |
@xopc/... not found | pnpm run build |
| Tests timeout | API keys / network for live calls |
| Bad config | JSON syntax of ~/.xopc/xopc.json |
| Console unreachable | Gateway running; browser origin matches gateway URL (REST/WebSocket) |
package-lock.json | Remove; use pnpm only |
| Telegram silent | Token, BotFather, policies |
| No logs in console | XOPC_LOG_LEVEL, file logging flags |
| Automation idle | Check #/automations, /api/automations/metrics, and gateway logs |
browser_use tool error at first use | Set agents.defaults.tools.browser_use.mode (or the agent override) to allow; install Chromium once with npx playwright install chromium (playwright-core does not ship browsers) |
When Making Changes
Authenticated Gateway route lazy loading
- Authenticated routes are loaded on demand through
src/gateway/hono/routes/lazy-bundles.ts. Adding a handler tosrc/gateway/hono/routes/*.tsalone does not make the endpoint reachable. - Whenever an authenticated API route is added, renamed, or moved, update the corresponding lazy-bundle matcher in the same change. Include every new route prefix and parameterized route shape.
- Matchers are evaluated in registry order. Check for overlap with broader prefixes such as
/api/notes; either place the more specific matcher first or explicitly exclude it from the broader matcher so the correct bundle wins. - Add positive mapping assertions for every new route family and at least one nearby negative/non-overlap assertion in
src/gateway/hono/routes/__tests__/lazy-bundles.test.ts. - Before considering the route complete, test the real path through a running Gateway with authentication. A direct unit test of the route module is insufficient because it bypasses lazy-bundle selection.
Session transcript (LLM vs on-disk rows)
- Conversation identity: Stable UUID
conversationId; Agent and channel routing come from stored metadata, never ID parsing.sessions.active_transcript_idpoints to the currenttranscriptId; reset preserves the conversation UUID. Create throughsrc/storage/sqlite/conversation-repository.ts. Schema v178 performs the one-time historical conversion; old-key decoding belongs only in migration modules. - Authoritative storage:
~/.xopc/xopc.db(SQLite). Session metadata, transcripts, per-session config, compaction checkpoints, and FTS5 search all live insrc/storage/sqlite/. Gateway opens the DB on start viaopenXopcDatabase(). - Runtime write path: Gateway, channels, and CLI turns use
runXopcEmbeddedTurn→openSqliteHydratingSessionManager(in-memory piSessionManagerhydrated from SQLite) →guardSessionManagerappends →emitSessionTranscriptUpdate→SessionStore.syncEmbeddedTranscriptUpdate→appendTranscriptEntry(SQLite). Do not add turn-endSessionStore.save/saveMessageson agent paths. - Index:
SessionIndex(src/session/manager.ts) delegates toSessionStore;onSessionTranscriptUpdatebumps counts after appends. - Model input: Use
SessionStore.loadMessages/sessionStore.load(they applybuildSessionContextForLlm). If you parse transcript rows yourself, runbuildSessionContextForLlm(rows)before passing history to the LLM. - Webchat abort cutoff:
POST /api/agentaccepts optionalclientCreatedAtMs. When it is omitted,abortCutoffTimestampdoes not drop stale POSTs (clients must send send-time for skip semantics). Abort usesabortEmbeddedRun+ context rows viaappendCustomEntry. - Audit rows:
kind: 'context'entries persist for ops/UI viaGET /api/sessions/:key?include=transcriptRows(comma-separated withtranscriptif you also wanttranscriptSummary). - JSON export:
SessionStore.exportSession(..., 'json')includestranscriptRows(full stored order) alongside API-shapedmessages(LLM-only). Session text search uses FTS5 over transcript content. - Reset (
/new, TUI/reset):performSessionReset(src/gateway/session-reset-service.ts) archives the active transcript row in SQLite, assigns a newtranscriptIdfor the same conversation UUID, and keeps per-session overrides (session_config, thinking/verbose on the session row). Gateway:POST /api/sessions/:key/reset. Delete (DELETE /api/sessions/:key) removes the key from the index — do not use delete for/new. - Integrity:
xopc doctor --deepruns SQLite session linkage checks andPRAGMA integrity_check.
| Area | Primary locations |
| Agent | src/agent/service.ts, src/agent/tools/, src/agent/context/, src/agent/lifecycle/ |
| CLI | src/cli/commands/ |
| In-chat slash commands | src/chat-commands/ |
| Config | src/config/schema.ts (and related) |
| Gateway / API | src/gateway/ |
| Models & providers | src/providers/index.ts |
| Channels | src/channels/ (+ extensions/telegram, extensions/weixin sources → dist/extensions/) |
| Gateway console (React) | web/src/, ui-design-system.md |
| Logging | src/utils/logger.ts (barrel) → src/utils/logger/; conventions: Logging conventions |
| Log Manager | web/src/ (logs feature / pages) |
| Tests | Colocated __tests__ |
| Session store / SQLite | src/session/store.ts, src/storage/sqlite/, src/session/session-context-for-llm.ts, src/gateway/session-reset-service.ts |
Last updated: 2026-09-09
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

