From e04ba88819c365c9acf9d6661ea802143e728bd6 Mon Sep 17 00:00:00 2001 From: Rohit Ghumare <48523873+rohitg00@users.noreply.github.com> Date: Sun, 23 Aug 2026 15:54:08 +0100 Subject: [PATCH 01/57] fix(cli): make fresh installs portable and persistent (#892) * fix(cli): anchor engine cwd and rewrite bundled config with absolute paths The bundled iii-config.yaml uses cwd-relative paths and the engine was spawned without a cwd, so on global and npx installs ./data/state_store.db and ./data/stream_store landed in whatever directory the user ran the CLI from, and the iii-exec supervision block (src/**/*.ts watch, node dist/index.mjs exec) never resolved, meaning the engine never supervised a worker and nothing respawned it after the in-process worker died. That surfaced as all data gone reports against a live REST port. startIiiBin now prepares the launch: when the resolved config is the bundled one it writes ~/.agentmemory/iii-config.runtime.yaml (regenerated each boot) with absolute data paths under ~/.agentmemory/data and an absolute node exec line for the installed worker entry, copies any legacy ./data stores from the invocation directory on first run, and spawns the engine with cwd anchored at ~/.agentmemory. Repo checkouts keep the cwd config and repo-root cwd, so dev behavior is unchanged. User overrides via env or ~/.agentmemory/iii-config.yaml are passed through verbatim. agentmemory remove gains a plan item for the generated runtime config. Covered by test/engine-launch.test.ts including a drift guard that rewrites the repo's real iii-config.yaml and asserts no relative paths remain. * fix: make fresh installs portable and persistent * docs: refresh generated config reference --- .env.example | 40 +- INSTALL_FOR_AGENTS.md | 151 ++- README.md | 172 ++- docker-compose.yml | 23 +- iii-config.docker.yaml | 16 +- plugin/skills/agentmemory-config/REFERENCE.md | 7 +- src/cli.ts | 1179 ++++++++++++++--- src/cli/engine-config.ts | 121 ++ src/cli/engine-launch.ts | 189 +++ src/cli/process-state.ts | 3 + src/cli/remove-plan.ts | 75 +- src/cli/startup-stderr.ts | 23 + src/config.ts | 6 +- src/index.ts | 17 +- src/runtime-paths.ts | 19 + src/types.ts | 1 + test/cli-data-dir.test.ts | 15 + test/cli-engine-startup.test.ts | 149 +++ test/cli-lifecycle-safety.test.ts | 356 +++++ test/cli-remove.test.ts | 47 + test/docker-port-config.test.ts | 67 + test/engine-config.test.ts | 54 + test/engine-launch.test.ts | 178 +++ test/multi-instance-port.test.ts | 10 + test/process-state.test.ts | 14 + test/runtime-paths.test.ts | 29 + test/startup-stderr.test.ts | 13 + test/stop-worker-pidfile.test.ts | 24 +- 28 files changed, 2651 insertions(+), 347 deletions(-) create mode 100644 src/cli/engine-config.ts create mode 100644 src/cli/engine-launch.ts create mode 100644 src/cli/process-state.ts create mode 100644 src/cli/startup-stderr.ts create mode 100644 src/runtime-paths.ts create mode 100644 test/cli-engine-startup.test.ts create mode 100644 test/cli-lifecycle-safety.test.ts create mode 100644 test/docker-port-config.test.ts create mode 100644 test/engine-config.test.ts create mode 100644 test/engine-launch.test.ts create mode 100644 test/process-state.test.ts create mode 100644 test/runtime-paths.test.ts create mode 100644 test/startup-stderr.test.ts diff --git a/.env.example b/.env.example index 9d346ea191..2143098484 100644 --- a/.env.example +++ b/.env.example @@ -9,9 +9,9 @@ # LLM key, no embedding key, and no API auth. Set keys here only when you # want to enable the corresponding feature. # -# Run `npx @agentmemory/agentmemory init` to copy this file into place -# automatically. Run `npx @agentmemory/agentmemory doctor` to verify that -# the daemon reads the env you expect. +# Run `npx -y @agentmemory/agentmemory@latest init` to copy this file into +# place automatically. Run `npx -y @agentmemory/agentmemory@latest doctor` +# to verify that the daemon reads the env you expect. # # Defaults shown in comments. Listed in priority order — the first key # present wins on the LLM detection path (see src/config.ts::detectProvider). @@ -21,8 +21,10 @@ # ----------------------------------------------------------------------------- # # Without a provider key, agentmemory runs in noop mode: observations are -# indexed via zero-LLM synthetic compression, hybrid search still works, +# indexed via zero-LLM synthetic compression and BM25 recall still works, # but LLM-backed summarisation / reflection / consolidation are disabled. +# A provider key alone does not enable LLM-written observation compression; +# that path also requires AGENTMEMORY_AUTO_COMPRESS=true. # The detection order is OPENAI_API_KEY → MINIMAX_API_KEY → ANTHROPIC_API_KEY # → GEMINI_API_KEY → OPENROUTER_API_KEY → noop. @@ -64,10 +66,14 @@ # 2. Embedding provider — auto-detected, override via EMBEDDING_PROVIDER # ----------------------------------------------------------------------------- # -# Without an embedding key, agentmemory runs in BM25-only mode for hybrid -# search. Detection order: EMBEDDING_PROVIDER override → GEMINI_API_KEY → +# Without an embedding provider, vector embeddings are disabled. `mem::search` +# uses BM25; `mem::smart-search` can also fuse structural graph matches when +# graph data exists. Remote +# provider detection order: EMBEDDING_PROVIDER override → GEMINI_API_KEY → # OPENAI_API_KEY → VOYAGE_API_KEY → COHERE_API_KEY → OPENROUTER_API_KEY → -# local (Xenova/all-MiniLM-L6-v2, 384-dim). +# BM25-only. Local embeddings are an explicit opt-in, not the keyless default. +# `EMBEDDING_PROVIDER=local` uses Xenova/all-MiniLM-L6-v2 (384-dim) on-device; +# the first embedding request downloads the model and needs network access. # EMBEDDING_PROVIDER=local # local | openai | voyage | cohere | gemini | openrouter @@ -107,7 +113,7 @@ # 5. Behaviour flags # ----------------------------------------------------------------------------- -# AGENTMEMORY_AUTO_COMPRESS=true # Run LLM compression on every observation batch (requires a provider key). Default off — synthetic compression handles most cases. +# AGENTMEMORY_AUTO_COMPRESS=true # Run LLM-written compression on every observation batch. Requires BOTH this flag and a configured provider; a provider alone leaves synthetic compression active. # AGENTMEMORY_INJECT_CONTEXT=true # Inject recalled memories back into agent prompts (#143). Default off — hooks capture observations but do not modify conversation. # CONSOLIDATION_ENABLED=true # Run the 4-tier consolidation pipeline (memories → semantic → procedural). Default off — opt in once you've measured the LLM cost. # CONSOLIDATION_DECAY_DAYS=30 # Age (days) after which non-reinforced memories decay during consolidation @@ -135,6 +141,13 @@ # AGENTMEMORY_PROBE_TIMEOUT_MS=2000 # MCP shim livez probe timeout # AGENTMEMORY_URL=http://localhost:3111 # REST base URL — honored by status, doctor, MCP shim # AGENTMEMORY_VIEWER_URL=http://localhost:3113 # Override the viewer URL printed by `agentmemory status` +# Persistent iii state; same override as `--data-dir`, used by native and +# Docker starts. Explicit flag/env wins. Otherwise instance 0 reuses an +# existing ./data/state_store.db or ./data/iii-config.yaml before defaults: macOS +# ~/Library/Application Support/agentmemory; Linux $XDG_DATA_HOME/agentmemory +# or ~/.local/share/agentmemory; Windows %APPDATA%\agentmemory. +# AGENTMEMORY_DATA_DIR=/absolute/path +# AGENTMEMORY_USE_DOCKER=1 # Prefer bundled Docker even when a compatible native iii binary exists # AGENTMEMORY_EXPORT_ROOT=~/agentmemory-backup # Default destination for `agentmemory export` # STANDALONE_MCP=1 # MCP shim only — bypass the worker and run @agentmemory/mcp in-process @@ -154,9 +167,14 @@ # 7. Ports # ----------------------------------------------------------------------------- -# III_REST_PORT=3111 # REST API port (also affects viewer at +2) -# III_STREAMS_PORT=3112 # Streams API port -# III_ENGINE_URL=ws://localhost:49134 # iii-engine WebSocket URL (used by the worker) +# III_REST_PORT=3111 # REST API + MCP HTTP anchor +# III_STREAM_PORT=3112 # Preferred streams override; defaults to REST + 1 +# III_STREAMS_PORT=3112 # Legacy alias for III_STREAM_PORT +# III_VIEWER_PORT=3113 # Viewer bind port; defaults to REST + 2 +# III_ENGINE_PORT=49134 # Engine bind port; defaults to REST + 46023 +# III_ENGINE_URL=ws://localhost:49134 # Explicit/remote worker WebSocket URL; takes precedence over derived engine port +# Derivation applies only while the corresponding explicit port/URL is unset. +# `--instance 1` selects 3211/3212/3213/49234 and an instance-1 data subdir. # ----------------------------------------------------------------------------- # 8. iii engine pin diff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.md index 18c78d3bf8..fd140d21cd 100644 --- a/INSTALL_FOR_AGENTS.md +++ b/INSTALL_FOR_AGENTS.md @@ -4,83 +4,116 @@ You are a coding agent. Follow this runbook top to bottom to install agentmemory ## What you are installing -agentmemory is a local memory server for coding agents. It runs on your machine, exposes a REST API on port 3111 and an MCP server, and stores memories on disk under `~/.agentmemory`. It is built on the iii engine, which agentmemory downloads and manages for you as a pinned binary under `~/.agentmemory/bin`. You do not install iii separately. +agentmemory is a local memory server for coding agents. It exposes a REST API and MCP HTTP routes on port 3111, streams on 3112, a viewer on 3113, and connects its worker to iii-engine on 49134. It is built on the iii engine, which agentmemory manages as a pinned v0.11.2 binary under `~/.agentmemory/bin` on macOS/Linux or `%USERPROFILE%\.agentmemory\bin` on Windows. -Default mode needs no API key and no cloud account. Out of the box it runs hybrid retrieval (BM25 keyword search plus local on-device embeddings), so a full install proves real semantic recall with zero credentials. An LLM provider key is optional and only unlocks richer summaries and auto-injection (see "Optional: richer features"). +Configuration and the managed iii binary live under `~/.agentmemory`. Persistent iii state uses the platform data directory: `~/Library/Application Support/agentmemory` on macOS, `$XDG_DATA_HOME/agentmemory` or `~/.local/share/agentmemory` on Linux, and `%APPDATA%\agentmemory` on Windows. Override it with `--data-dir ` or `AGENTMEMORY_DATA_DIR`; use the same override on every restart. For instance 0, an existing `./data/state_store.db` or `./data/iii-config.yaml` takes precedence over the platform default, while an explicit flag or environment override still wins. Native and Docker starts use the same resolved host data directory. + +Default keyless mode needs no API key or cloud account and disables vector embeddings. `memory_recall` (`mem::search`) uses BM25, while `memory_smart_search` can also fuse structural graph matches when graph data exists. Semantic vector recall is an explicit opt-in: set `EMBEDDING_PROVIDER=local` for on-device `Xenova/all-MiniLM-L6-v2`, or configure a supported remote embedding provider. Local inference is free, but the first embedding request downloads the model and therefore needs network access and extra startup time. An LLM provider is separate; LLM-written observation compression requires both a provider and `AGENTMEMORY_AUTO_COMPRESS=true`. ## Prerequisites -- Node.js >= 20 and npm. Check with `node -v`. -- macOS or Linux for the one-command path. On Windows, use WSL2; native Windows engine setup is manual and `agentmemory connect` is not supported there. +- Node.js >= 20 with npm and npx. Check with `node -v`, `npm -v`, and `npx -v`. +- macOS/Linux automatic iii installation also requires `curl`, a POSIX `sh`, and `tar`. Check with `command -v curl sh tar`. Minimal images such as `node:20-slim` may not include them. +- Windows: WSL2 follows the Linux path above. Native Windows requires a manually downloaded, pinned iii-engine v0.11.2 `iii.exe`, or Docker Desktop; the CLI does not auto-extract the Windows ZIP. Native automated `connect` supports only `copilot-cli`. Other Windows agents need manual MCP configuration; WSL `connect` applies only to agents installed in that same WSL environment. - Ports 3111 (REST), 3112 (streams), 3113 (viewer), and 49134 (engine) free. If any are taken, stop whatever is using them before starting (see Troubleshooting). ## Running non-interactively -Several commands prompt on a TTY (for example the first-run "install globally?" question). As an agent you usually want no prompts. Either set `CI=1` in the environment for the commands below, or rely on the fact that agentmemory skips all prompts automatically when stdin/stdout are not a TTY. Prompts are also never-nag: once answered they persist and are not asked again. Re-run onboarding any time with `agentmemory --reset`. +Use `npx -y @agentmemory/agentmemory@latest` as the canonical command. `-y` accepts npx's package prompt and `@latest` avoids running a stale cached release. Several agentmemory onboarding choices can still prompt on a TTY; set `CI=1` for unattended runs or use non-TTY stdin. Re-run onboarding any time with `npx -y @agentmemory/agentmemory@latest --reset`. -## 1. Install globally +## 1. Verify the runtime prerequisites ```bash -npm install -g @agentmemory/agentmemory +node -v +npm -v +npx -v + +# macOS/Linux only +command -v curl sh tar ``` -`npm install -g` already fetches the latest published release. If you hit `EACCES` on a system Node install (macOS/Linux), retry with `sudo npm install -g @agentmemory/agentmemory`. +Expect: Node prints v20 or newer, npm succeeds, and macOS/Linux prints a path for each automatic-installer dependency. -No-install alternative: skip this step and run the server with `npx -y @agentmemory/agentmemory@latest` everywhere this runbook says `agentmemory`. The `@latest` and `-y` flags matter because npx caches per version and a bare `npx @agentmemory/agentmemory` can serve a stale release. +For native Windows, install the engine before continuing: -Expect: the install completes without errors. +```powershell +# Download the archive that matches your CPU from the pinned release: +# https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2 +# Extract iii.exe to $HOME\.agentmemory\bin\iii.exe, then verify the pin: +& "$HOME\.agentmemory\bin\iii.exe" --version +``` -## 2. Verify the install +Expect: exactly `0.11.2`. Do not install the latest unpinned iii release. Alternatively, use WSL2 or start Docker Desktop and choose the Docker path when agentmemory starts. -```bash -agentmemory --version -``` +## 2. Start the server -Expect: a version string is printed. If `command not found`, the global bin is not on `PATH`; use the `npx -y @agentmemory/agentmemory@latest` form instead. +The canonical command downloads the npm package and, on macOS/Linux, auto-installs its pinned iii-engine into the private agentmemory bin directory. Run it in a dedicated terminal: -## 3. Start the server +```bash +npx -y @agentmemory/agentmemory@latest +``` -The server listens on port 3111 and auto-starts its pinned iii engine on first run (this can take a few seconds the first time while the engine binary is fetched into `~/.agentmemory/bin`). Run it in the background or in a separate terminal so the rest of the runbook can talk to it. +To prefer Docker even when a compatible native binary is present, set `AGENTMEMORY_USE_DOCKER=1` for the same command. To choose persistent storage, pass an absolute path and reuse it on every start: ```bash -agentmemory & +npx -y @agentmemory/agentmemory@latest --data-dir /absolute/path/to/agentmemory-data ``` -Or run `agentmemory` in the foreground in a dedicated terminal. +Docker bind-mounts that same resolved host directory at `/data`. For a second isolated daemon, add `--instance 1`; it stores data and lifecycle metadata under `instance-1` and defaults to ports 3211, 3212, 3213, and 49234. Do not use `--port` alone for concurrent daemons: it changes the ports but keeps instance 0's canonical lifecycle ownership. Use `--instance` for isolation. + +Expect: iii-engine v0.11.2 starts, the agentmemory worker registers with iii, and the ready panel lists REST, viewer, streams, and engine addresses. First boot can take longer while the engine binary is downloaded. + +## 3. Validate the server and all four ports + +| Port | Owner | Validation | +|---|---|---| +| 3111 | agentmemory REST/MCP | `/agentmemory/livez` and `/agentmemory/health` return 200 | +| 3112 | iii streams | listed in the ready panel; must be free at startup | +| 3113 | agentmemory viewer | opening the URL returns the viewer | +| 49134 | iii engine WebSocket | listed in the ready panel and worker registration succeeds | -Wait until it is reachable, then continue: +From a second terminal, run: ```bash curl -fsS http://localhost:3111/agentmemory/livez +curl -fsS http://localhost:3111/agentmemory/health +curl -fsS -o /dev/null http://localhost:3113/ +npx -y @agentmemory/agentmemory@latest status ``` -Expect: a `200` response. Retry for up to ~15 seconds on first run while the engine warms up. +Expect: both REST checks return JSON, the viewer request succeeds, the startup ready panel has listed all four addresses, and `status` reports healthy agentmemory state. In keyless mode, status should report vectors disabled or `bm25-only`; `mem::search` uses BM25, while smart search may also include existing graph matches. Native PowerShell users can use `Invoke-RestMethod` instead of `curl`. -## 4. Prove recall in one command +## 4. Exercise default recall and optional local semantics ```bash -agentmemory demo --serve +npx -y @agentmemory/agentmemory@latest demo ``` -`--serve` boots the server, seeds three realistic sessions (JWT auth, an N+1 query fix, rate limiting), runs semantic searches against them, prints the results, and tears everything down. No second terminal needed. +The demo seeds three realistic sessions and searches them. In default keyless mode, vectors are disabled and the `mem::search` keyword queries such as `jwt auth middleware` and `rate limiting` should return BM25 hits. The deliberately semantic query `database performance optimization` can return zero because no embedding provider is active. Smart search can still add structural graph matches if graph data already exists. + +To opt into on-device semantic recall, add this line to `~/.agentmemory/.env`, restart the server, and rerun the demo: -Expect: the demo finds the "N+1 query fix" memory when it searches for "database performance optimization", which keyword matching alone cannot do. Open `http://localhost:3113` while it runs to watch the memory build live. +```env +EMBEDDING_PROVIDER=local +``` + +The first embedding request downloads `Xenova/all-MiniLM-L6-v2`; wait for that download to finish. Afterward, inference runs locally and the semantic query should find the N+1 memory. Open `http://localhost:3113` to watch the memory build live. ## 5. Wire MCP into the calling agent -Detect which agent is running this runbook, then wire its MCP config: +Detect which agent is running this runbook, then wire its MCP config. On native Windows, run this automated step only for `copilot-cli`: ```bash -agentmemory connect +npx -y @agentmemory/agentmemory@latest connect ``` `connect` merges agentmemory into that agent's MCP config and preserves any existing servers. Supported agent names: `claude-code`, `copilot-cli`, `codex`, `cursor`, `gemini-cli`, `opencode`, `cline`, `continue`, `droid`, `hermes`, `openclaw`, `openhuman`, `pi`, `qwen`, `warp`, `zed`, `antigravity`, `kiro`. -If you cannot tell which agent you are, default to `claude-code`. After wiring, restart the agent or run its MCP reload command (for example `/mcp` in Claude Code) so it picks up the server. +If you cannot tell which agent you are, default to `claude-code` on macOS/Linux. On native Windows, `copilot-cli` is the only automated adapter; configure all other agents with the manual MCP block in the README. Run `connect` inside WSL only when the target agent is installed inside the same WSL environment. After wiring, restart the agent or run its MCP reload command (for example `/mcp` in Claude Code) so it picks up the server. -Expect: the agent now lists agentmemory's tools. With the server running you should see the full set of 54 tools (for example `memory_save`, `memory_smart_search`, `memory_sessions`). If you see only 7 tools, the MCP shim could not reach a server, see Troubleshooting. +Expect: the agent now lists agentmemory's tools. With the server running you should see the full set of 54 tools (for example `memory_save`, `memory_smart_search`, `memory_sessions`). If you see only 7 tools, the MCP shim could not reach the server; see Troubleshooting. ## 6. Install native skills @@ -92,7 +125,7 @@ This installs the native skills so the agent knows when to call the memory tools Expect: the skills are installed for the detected agent. -## 7. Verify a save and recall round-trip +## 7. Verify save, recall, and restart persistence Confirm health first: @@ -118,13 +151,33 @@ Expect: the first call returns `201`, the second returns `200` with results that If `AGENTMEMORY_SECRET` is set in the environment, the REST API requires it. Add `-H "Authorization: Bearer $AGENTMEMORY_SECRET"` to both calls. By default no secret is set and localhost is open. +Now stop and restart the processes, using the same `--data-dir` value if you set one: + +```bash +npx -y @agentmemory/agentmemory@latest stop +npx -y @agentmemory/agentmemory@latest +``` + +After `/agentmemory/livez` returns 200 again, repeat the `smart-search` request above. Expect: the saved probe is still returned. This restart check proves the selected platform data directory is persistent rather than only proving the in-memory index. + +## Optional: install a global command + +The npx form above is the canonical fresh-install path. If you want the shorter `agentmemory` command afterward: + +```bash +npm install -g @agentmemory/agentmemory@latest +agentmemory --version +``` + +If a system Node install returns `EACCES` on macOS/Linux, use a user-owned npm prefix rather than changing repository permissions. The npx form remains available without a global install. + ## Optional: richer features These are off by default because they spend tokens. Enable them only if the user wants them. Put configuration in `~/.agentmemory/.env` (no `export` prefix), then restart the server. - `AGENTMEMORY_INJECT_CONTEXT=true` makes the SessionStart and PreToolUse hooks inject past memory into the agent's context automatically. Cost: spends session tokens proportional to tool-call frequency. -- `AGENTMEMORY_AUTO_COMPRESS=true` sends each observation to your LLM provider for a richer summary. Cost: spends API tokens proportional to tool-use frequency. Requires a provider key. -- Provider key: set one of `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `GEMINI_API_KEY`, and similar, in the same file. Without a key, agentmemory stays in zero-LLM mode and still indexes and recalls via BM25 plus local embeddings. +- LLM-written observation compression requires both `AGENTMEMORY_AUTO_COMPRESS=true` and a configured provider. A provider alone leaves synthetic compression active. When both are set, each observation is sent to the provider for a richer summary, spending API tokens proportional to tool-use frequency. +- Provider key: set one of `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `GEMINI_API_KEY`, and similar, in the same file. Without a key, agentmemory stays in zero-LLM mode and recalls via BM25. Local embeddings remain available as the separate `EMBEDDING_PROVIDER=local` opt-in above. ## Tool surface @@ -132,33 +185,37 @@ The MCP server exposes 54 tools by default (`--tools all`). Use `--tools core` ( ## Lifecycle commands -- `agentmemory status` shows server and engine state. -- `agentmemory doctor` runs diagnostics and reports what is misconfigured. -- `agentmemory stop` stops the engine this CLI started (`stop --force` bypasses the Docker guard). -- `agentmemory upgrade` upgrades agentmemory and the iii runtime, best effort. -- `agentmemory --reset` wipes onboarding preferences and re-runs the wizard. -- `agentmemory import-jsonl ` imports prior Claude Code session logs as memories. +- `npx -y @agentmemory/agentmemory@latest status` shows server health, viewer, provider, and embedding state. +- `npx -y @agentmemory/agentmemory@latest doctor` runs diagnostics and reports what is misconfigured. +- `npx -y @agentmemory/agentmemory@latest stop` stops the engine this CLI started. Docker mode validates and preserves the exact container and `/data` mount for the next restart; `stop --force` applies only to native ownership checks. +- `npx -y @agentmemory/agentmemory@latest upgrade` upgrades agentmemory and the iii runtime, best effort. +- `npx -y @agentmemory/agentmemory@latest --reset` wipes onboarding preferences and re-runs the wizard. +- `npx -y @agentmemory/agentmemory@latest import-jsonl ` imports prior Claude Code session logs as memories. ## Troubleshooting -- `command not found: agentmemory`: the global bin is not on `PATH`. Use `npx -y @agentmemory/agentmemory@latest`. -- `EACCES` during global install: retry with `sudo`, or use the npx form. -- Stale npx version: run `npx -y @agentmemory/agentmemory@latest`, or clear the cache with `rm -rf ~/.npm/_npx` (macOS/Linux). +- `command not found: agentmemory`: the optional global bin is not on `PATH`. Use `npx -y @agentmemory/agentmemory@latest`. +- Automatic iii install fails on macOS/Linux: verify `command -v curl sh tar`; install the missing prerequisite or use Docker. +- Stale npx version: include both `-y` and `@latest` as shown throughout this runbook. - Port already in use: another process holds 3111, 3112, 3113, or 49134. Stop that process, then re-run. -- Server starts but `livez` never returns 200: re-run with `agentmemory --verbose` to see engine stderr. +- Custom REST port: `--port ` derives streams as `N+1`, viewer as `N+2`, and the iii worker WebSocket as `N+46023` only when their explicit port/URL variables are unset (`III_STREAM_PORT` or legacy `III_STREAMS_PORT`, `III_VIEWER_PORT` or `AGENTMEMORY_VIEWER_URL`, and `III_ENGINE_PORT` or `III_ENGINE_URL`). +- Server starts but `livez` never returns 200: re-run with `npx -y @agentmemory/agentmemory@latest --verbose` to see engine stderr. +- `The engine process started but the REST API never responded.`: inspect all four derived ports, confirm the pinned iii process stayed alive, and use `--verbose` for captured engine stderr. - Engine version warning on start: harmless. agentmemory uses its own pinned engine in `~/.agentmemory/bin` regardless of any `iii` on `PATH`. Set `AGENTMEMORY_III_VERSION` only to override deliberately. -- "engine conflict" / another iii engine already running: if a different iii version is already serving the port (common if you run your own iii), agentmemory will not adopt it and stops with an "engine conflict" note. Stop that engine (`agentmemory stop --force`, or however you started it), then re-run `agentmemory` — it installs and runs the pinned engine in `~/.agentmemory/bin`, leaving your own iii untouched. -- Only 7 tools visible in the agent: the MCP shim is in local fallback because it could not reach a server. Start `npx @agentmemory/agentmemory` and ensure `AGENTMEMORY_URL` points at it (default `http://localhost:3111`), then reload MCP. -- Windows: use WSL2 for the path above. Native Windows runs the server but `connect` and the automated engine install are not supported. +- "engine conflict" / another iii engine already running: if a different iii version is already serving the port, agentmemory will not adopt it. Stop that engine (`npx -y @agentmemory/agentmemory@latest stop --force`, or however you started it), then rerun the canonical command. Its private v0.11.2 binary does not replace a user-managed `iii` on `PATH`. +- Only 7 tools visible in the agent: the MCP shim is in local fallback because it could not reach a server. Start `npx -y @agentmemory/agentmemory@latest`, ensure `AGENTMEMORY_URL` points at it (default `http://localhost:3111`), then reload MCP. +- Native Windows: the CLI does not auto-extract the ZIP. Install the pinned v0.11.2 `iii.exe` manually, use WSL2, or run with Docker Desktop and `AGENTMEMORY_USE_DOCKER=1`. Automated `connect` supports only `copilot-cli`; configure other native agents manually. +- Semantic demo query returns zero hits: this is expected with vectors disabled in default keyless mode. Set `EMBEDDING_PROVIDER=local`, restart, allow the first model download to complete, and rerun the demo. ## Report success Report back to the user: - agentmemory installed, version, and the server running on port 3111 +- iii-engine v0.11.2 running, the selected platform data directory, and all four ports accounted for - which agent was wired via `agentmemory connect`, and the tool count the agent now sees -- the save and recall round-trip returned the probe memory +- the save and recall round-trip returned the probe memory after a full stop/start - the viewer is available at `http://localhost:3113` -- whether any optional features were enabled +- whether vectors were disabled (`mem::search` BM25, with optional graph matches in smart search) or an embedding provider was enabled If any step failed, report which step, the exact command, and the error output. diff --git a/README.md b/README.md index 6a6462d566..959d68c7e4 100644 --- a/README.md +++ b/README.md @@ -75,21 +75,33 @@ ## Install -One command: +Requirements: + +- Node.js 20 or newer with npm and npx (`node -v`, `npm -v`, and `npx -v`). +- macOS/Linux automatic iii-engine installation also needs `curl`, a POSIX `sh`, and `tar`. Minimal images such as `node:20-slim` may not include them. +- Native Windows requires the pinned iii-engine v0.11.2 `iii.exe` to be installed manually. WSL2 or Docker Desktop are the other supported paths. + +Canonical fresh-install command: ```bash -npx @agentmemory/agentmemory +npx -y @agentmemory/agentmemory@latest ``` -The first run is an interactive setup: pick the agents to wire (Claude Code, Cursor, Codex, Gemini CLI, OpenCode, ...), pick an LLM provider or stay keyless, and it seeds the config, starts the memory server on `:3111`, and offers to install globally so the bare `agentmemory` command works everywhere afterwards. +The first run is an interactive setup: pick the agents to wire (Claude Code, Cursor, Codex, Gemini CLI, OpenCode, ...), pick an LLM provider or stay keyless, and it seeds the config, starts the memory server and its pinned iii engine, and offers to install globally so the bare `agentmemory` command works everywhere afterward. `-y` accepts npx's package prompt and `@latest` avoids a stale cached release. A provider makes LLM features available, but LLM-written observation compression starts only when `AGENTMEMORY_AUTO_COMPRESS=true` is also set. + +Keyless mode disables vector embeddings. `memory_recall` (the `mem::search` path) uses BM25, while `memory_smart_search` can also fuse structural graph matches when graph data already exists. For free on-device semantic recall, set `EMBEDDING_PROVIDER=local` in `~/.agentmemory/.env` and restart. The first embedding request downloads `Xenova/all-MiniLM-L6-v2`; inference runs locally after that initial model download. + +The local runtime uses four ports: `3111` for REST/MCP HTTP, `3112` for iii streams, `3113` for the viewer, and `49134` for the iii worker WebSocket. Persistent iii state lives in `~/Library/Application Support/agentmemory` on macOS, `$XDG_DATA_HOME/agentmemory` or `~/.local/share/agentmemory` on Linux, and `%APPDATA%\agentmemory` on Windows. Use `--data-dir ` or `AGENTMEMORY_DATA_DIR` to override it, and reuse the same value on every restart. For backward compatibility, an existing `./data/state_store.db` or `./data/iii-config.yaml` takes precedence over the platform default for instance 0; an explicit flag or environment override still wins. Then prove recall works and give your agent its skills: ```bash -agentmemory demo --serve # seed sample sessions + watch recall find them +npx -y @agentmemory/agentmemory@latest demo # seed sample sessions + exercise recall npx skills add rohitg00/agentmemory -y # 17 native skills so your agent knows when to reach for memory ``` +The keyword searches should hit in default keyless mode through BM25. The demo's `database performance optimization` query is intentionally semantic and can return zero until an embedding provider is configured. + Prefer to let a coding agent do the whole thing? Hand it one instruction: > Retrieve and follow the instructions at: https://raw.githubusercontent.com/rohitg00/agentmemory/main/INSTALL_FOR_AGENTS.md @@ -99,7 +111,7 @@ Wire more agents any time with `agentmemory connect ` — 20 adapters lis
Windows -The fast path is WSL2. Native Windows engine setup is manual (about 10 to 20 minutes) and `agentmemory connect` is currently unsupported there. See the [Windows notes](#windows) for the step-by-step. +The fast path is WSL2. Native Windows engine setup requires the pinned v0.11.2 ZIP to be downloaded and `iii.exe` extracted manually; the CLI does not auto-extract it. Docker Desktop is also supported. See the [Windows notes](#windows) for the step-by-step.
@@ -107,11 +119,11 @@ The fast path is WSL2. Native Windows engine setup is manual (about 10 to 20 min Global install / EACCES ```bash -npm install -g @agentmemory/agentmemory -# If you hit EACCES on macOS/Linux system Node installs: -sudo npm install -g @agentmemory/agentmemory +npm install -g @agentmemory/agentmemory@latest ``` +The npx command above remains the canonical fresh-install path and avoids global-prefix permission issues. +
@@ -244,16 +256,18 @@ You explain the same architecture every session. You re-discover the same bugs. **What changes:** Session 1 you set up JWT auth. Session 2 you ask for rate limiting. The agent already knows your auth uses jose middleware in `src/middleware/auth.ts`, your tests cover token validation, and you chose jose over jsonwebtoken for Edge compatibility, with no re-explaining and no copy-pasting. ```bash -npx @agentmemory/agentmemory +npx -y @agentmemory/agentmemory@latest ``` -By default, agentmemory stores iii-engine state outside the repository you start it from: `~/Library/Application Support/agentmemory` on macOS, `$XDG_DATA_HOME/agentmemory` or `~/.local/share/agentmemory` on Linux, and `%APPDATA%\agentmemory` on Windows. To choose a location, pass `--data-dir ` or set `AGENTMEMORY_DATA_DIR`: +By default, agentmemory stores iii-engine state outside the repository you start it from: `~/Library/Application Support/agentmemory` on macOS, `$XDG_DATA_HOME/agentmemory` or `~/.local/share/agentmemory` on Linux, and `%APPDATA%\agentmemory` on Windows. An existing legacy `./data/state_store.db` or `./data/iii-config.yaml` is reused for instance 0 before that platform default. To choose a location explicitly, pass `--data-dir ` or set `AGENTMEMORY_DATA_DIR`; either explicit setting takes precedence over legacy discovery: ```bash -npx @agentmemory/agentmemory --data-dir ~/.agentmemory-projects/main -AGENTMEMORY_DATA_DIR=~/.agentmemory-projects/main npx @agentmemory/agentmemory +npx -y @agentmemory/agentmemory@latest --data-dir ~/.agentmemory-projects/main +AGENTMEMORY_DATA_DIR=~/.agentmemory-projects/main npx -y @agentmemory/agentmemory@latest ``` +Native and Docker launches use this same resolved host directory; Docker bind-mounts it at `/data`. `--instance 1` appends `instance-1` to the resolved directory and selects the separate default port quartet `3211/3212/3213/49234`. + Latest release notes: [CHANGELOG.md](CHANGELOG.md). --- @@ -482,29 +496,54 @@ None of these auto-capture from coding-agent hooks, ship a local-first viewer, o

Quick Start

-Compatibility: this release targets stable `iii-sdk` `^0.11.0` and iii-engine v0.11.x. +Compatibility: this release targets `iii-sdk` 0.11.2 and pins iii-engine v0.11.2. ### Try it in 30 seconds ```bash # Terminal 1: start the server -npx @agentmemory/agentmemory +npx -y @agentmemory/agentmemory@latest # Terminal 2: seed sample data and see recall in action -npx @agentmemory/agentmemory demo +npx -y @agentmemory/agentmemory@latest demo ``` -`demo` seeds 3 realistic sessions (JWT auth, N+1 query fix, rate limiting) and runs semantic searches against them. You'll see it find "N+1 query fix" when you search "database performance optimization", which keyword matching cannot do. +`demo` seeds 3 realistic sessions (JWT auth, N+1 query fix, rate limiting) and runs searches against them. Keyless installs disable vectors, so the `mem::search` keyword queries should hit through BM25 while `database performance optimization` can return zero. `smart-search` may additionally return structural graph matches when graph data exists. To make the semantic query find the N+1 fix through vectors, set `EMBEDDING_PROVIDER=local`, restart, and allow the first model download to finish. Open `http://localhost:3113` to watch the memory build live. +### Validate a fresh install and restart persistence + +With the server running, validate REST, health, the viewer, and the iii-backed runtime status: + +```bash +curl -fsS http://localhost:3111/agentmemory/livez +curl -fsS http://localhost:3111/agentmemory/health +curl -fsS -o /dev/null http://localhost:3113/ +npx -y @agentmemory/agentmemory@latest status +``` + +The startup ready panel accounts for all four ports: REST/MCP HTTP on 3111, iii streams on 3112, the viewer on 3113, and the iii worker WebSocket on 49134. `status` confirms agentmemory health and the active provider/embedding mode. Save a probe and confirm it is searchable: + +```bash +curl -fsS -X POST http://localhost:3111/agentmemory/remember \ + -H 'Content-Type: application/json' \ + -d '{"content":"agentmemory restart persistence probe","concepts":["install-check"]}' + +curl -fsS -X POST http://localhost:3111/agentmemory/smart-search \ + -H 'Content-Type: application/json' \ + -d '{"query":"restart persistence probe","limit":5}' +``` + +Then run `npx -y @agentmemory/agentmemory@latest stop`, start the canonical command again in Terminal 1, wait for `/agentmemory/livez`, and repeat the search. The probe must still be returned. If you selected a custom `--data-dir`, pass the same directory on the restart. + ### Everyday commands Install and setup live in [Install](#install) above (the first run walks you through it). Day to day: ```bash agentmemory # start the server -agentmemory stop # tear it down +agentmemory stop # stop it cleanly agentmemory connect # wire another agent agentmemory doctor # interactive diagnostics + fix prompts agentmemory remove # uninstall everything we created @@ -518,10 +557,10 @@ To bring in older Claude Code JSONL transcripts: ```bash # Import everything under the default ~/.claude/projects -npx @agentmemory/agentmemory import-jsonl +npx -y @agentmemory/agentmemory@latest import-jsonl # Or import a single file -npx @agentmemory/agentmemory import-jsonl ~/.claude/projects/-my-project/abc123.jsonl +npx -y @agentmemory/agentmemory@latest import-jsonl ~/.claude/projects/-my-project/abc123.jsonl ``` Imported sessions show up in the Replay picker alongside native ones. Under the hood each entry routes through the `mem::replay::load`, `mem::replay::sessions`, and `mem::replay::import-jsonl` iii functions, with no side-channel servers. Each imported transcript is indexed for search, stamped with origin channel `import`, and mined for a session crystal and lessons. @@ -533,7 +572,7 @@ Imported sessions show up in the Replay picker alongside native ones. Under the Use the maintenance command when you intentionally want to update your local runtime: ```bash -npx @agentmemory/agentmemory upgrade +npx -y @agentmemory/agentmemory@latest upgrade ``` Warning: this command mutates the current workspace/runtime. It can update JavaScript dependencies and pull the pinned `iiidev/iii:0.11.2` Docker image. It never installs an unpinned or newer iii engine. @@ -543,7 +582,7 @@ Implementation details live in `src/cli.ts` (see `runUpgrade` around the `src/cl ### Claude Code (one block, paste it) ```text -Install agentmemory: run `npx @agentmemory/agentmemory` in a separate terminal to start the memory server. Then run `/plugin marketplace add rohitg00/agentmemory` and `/plugin install agentmemory` — the plugin registers all 12 hooks, 17 skills, AND auto-wires the `@agentmemory/mcp` stdio server via its `.mcp.json`, so you get 54 MCP tools (memory_smart_search, memory_save, memory_sessions, memory_governance_delete, etc.) without any extra config step. Verify with `curl http://localhost:3111/agentmemory/health`. The real-time viewer is at http://localhost:3113. +Install agentmemory: run `npx -y @agentmemory/agentmemory@latest` in a separate terminal to start the memory server and its pinned iii engine. Then run `/plugin marketplace add rohitg00/agentmemory` and `/plugin install agentmemory` — the plugin registers all 12 hooks, 17 skills, AND auto-wires the `@agentmemory/mcp` stdio server via its `.mcp.json`, so you get 54 MCP tools (memory_smart_search, memory_save, memory_sessions, memory_governance_delete, etc.) without any extra config step. Verify with `curl http://localhost:3111/agentmemory/health`. The real-time viewer is at http://localhost:3113. Keyless mode disables vectors: `memory_recall` uses BM25, and `memory_smart_search` can also use existing structural graph data. Set `EMBEDDING_PROVIDER=local` in `~/.agentmemory/.env` and restart to opt into on-device semantic recall. ``` #### Claude Code without the plugin install (MCP-standalone path) @@ -563,7 +602,7 @@ For remote or protected deployments, launch Claude Code with `AGENTMEMORY_URL` a ```bash # 1. start the memory server in a separate terminal -npx @agentmemory/agentmemory +npx -y @agentmemory/agentmemory@latest # 2. register the agentmemory marketplace and install the plugin codex plugin marketplace add rohitg00/agentmemory @@ -600,13 +639,13 @@ agentmemory connect copilot-cli copilot plugin install rohitg00/agentmemory:plugin ``` -`agentmemory connect copilot-cli` merges `mcpServers.agentmemory` into `~/.copilot/mcp-config.json` (or `$COPILOT_HOME/mcp-config.json` when `COPILOT_HOME` is set) and preserves existing servers. This adapter is Windows-safe even though other `connect` adapters still require manual Windows setup. Copilot picks up the MCP server on next launch or after `/mcp`. Install the plugin as well when you want the full hook/skill experience. +`agentmemory connect copilot-cli` merges `mcpServers.agentmemory` into `~/.copilot/mcp-config.json` (or `$COPILOT_HOME/mcp-config.json` when `COPILOT_HOME` is set) and preserves existing servers. On native Windows this is the only automated `connect` adapter; configure every other native Windows agent manually. WSL `connect` is supported only when the target agent is installed in that same WSL environment. Copilot picks up the MCP server on next launch or after `/mcp`. Install the plugin as well when you want the full hook/skill experience.
OpenClaw (paste this prompt) ```text -Install agentmemory for OpenClaw. Run `npx @agentmemory/agentmemory` in a separate terminal to start the memory server on localhost:3111. Then add this to my OpenClaw MCP config so agentmemory is available with all 54 memory tools: +Install agentmemory for OpenClaw. Run `npx -y @agentmemory/agentmemory@latest` in a separate terminal to start the memory server on localhost:3111. Then add this to my OpenClaw MCP config so agentmemory is available with all 54 memory tools: { "mcpServers": { @@ -631,7 +670,7 @@ Full guide: [`integrations/openclaw/`](integrations/openclaw/) Hermes Agent (paste this prompt) ```text -Install agentmemory for Hermes. Run `npx @agentmemory/agentmemory` in a separate terminal to start the memory server on localhost:3111. Then add this to ~/.hermes/config.yaml so Hermes can use agentmemory as an MCP server with all 54 memory tools: +Install agentmemory for Hermes. Run `npx -y @agentmemory/agentmemory@latest` in a separate terminal to start the memory server on localhost:3111. Then add this to ~/.hermes/config.yaml so Hermes can use agentmemory as an MCP server with all 54 memory tools: mcp_servers: agentmemory: @@ -650,7 +689,7 @@ Full guide: [`integrations/hermes/`](integrations/hermes/) ### Other agents -Start the memory server: `npx @agentmemory/agentmemory` +Start the memory server: `npx -y @agentmemory/agentmemory@latest` #### Native skills via `npx skills add` (50+ agents) @@ -752,7 +791,7 @@ git clone https://github.com/rohitg00/agentmemory.git && cd agentmemory npm install && npm run build && npm start ``` -This starts agentmemory with a local `iii-engine` if `iii` is already installed, or falls back to Docker Compose if Docker is available. REST, streams, and the viewer bind to `127.0.0.1` by default. +This starts agentmemory with a local `iii-engine` if the pinned binary is already installed, or uses Docker Compose when selected. REST, streams, and the viewer bind to `127.0.0.1` by default. The automatic macOS/Linux binary path requires `curl`, a POSIX `sh`, and `tar`. Install `iii-engine` manually. **agentmemory currently pins `iii-engine` to `v0.11.2`**. `v0.11.6` introduces a new sandbox-everything-via-`iii worker add` model that agentmemory hasn't been refactored for yet. Pin lifts once the refactor lands. Override with `AGENTMEMORY_III_VERSION=` if you've migrated to the sandbox model manually. @@ -760,13 +799,15 @@ Install `iii-engine` manually. **agentmemory currently pins `iii-engine` to `v0. - **macOS x64:** swap `aarch64-apple-darwin` for `x86_64-apple-darwin` - **Linux x64:** swap for `x86_64-unknown-linux-gnu` - **Linux arm64:** swap for `aarch64-unknown-linux-gnu` -- **Windows:** download `iii-x86_64-pc-windows-msvc.zip` from [iii-hq/iii releases v0.11.2](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2), extract `iii.exe`, add to PATH +- **Windows:** download `iii-x86_64-pc-windows-msvc.zip` from [iii-hq/iii releases v0.11.2](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2) and extract `iii.exe` to `%USERPROFILE%\.agentmemory\bin\iii.exe` Or use Docker (the bundled `docker-compose.yml` pulls `iiidev/iii:0.11.2`). Full docs: [iii.dev/docs](https://iii.dev/docs). ### Windows -agentmemory runs on Windows 10/11, but the Node.js package alone isn't enough; you also need the `iii-engine` runtime (a separate native binary) as a background process. The official upstream installer is a `sh` script and there is no PowerShell installer or scoop/winget package today, so Windows users have two paths: +agentmemory runs on Windows 10/11, but the Node.js package alone isn't enough; you also need the pinned iii-engine v0.11.2 runtime as a background process. The CLI does not auto-extract the Windows ZIP, so native Windows users must install `iii.exe` manually, use WSL2, or choose Docker Desktop. + +Native Windows automated MCP wiring supports only `agentmemory connect copilot-cli`. For Claude Code, Codex, Cursor, and every other native Windows agent, copy the manual MCP block from [Other agents](#other-agents) into that agent's Windows config. Running `connect` in WSL is appropriate only when the target agent is also installed in the same WSL environment; it does not edit a Windows-host agent's configuration. **Option A: prebuilt Windows binary (recommended)** @@ -776,15 +817,15 @@ agentmemory runs on Windows 10/11, but the Node.js package alone isn't enough; y # model that engine v0.11.6+ requires) # 2. Download iii-x86_64-pc-windows-msvc.zip # (or iii-aarch64-pc-windows-msvc.zip if you're on an ARM machine) -# 3. Extract iii.exe somewhere on PATH, or place it at: -# %USERPROFILE%\.local\bin\iii.exe -# (agentmemory checks that location automatically) +# 3. Extract iii.exe to agentmemory's private engine directory: +New-Item -ItemType Directory -Force "$HOME\.agentmemory\bin" +# Copy iii.exe to $HOME\.agentmemory\bin\iii.exe # 4. Verify: -iii --version +& "$HOME\.agentmemory\bin\iii.exe" --version # Should print: 0.11.2 # 5. Then run agentmemory as usual: -npx -y @agentmemory/agentmemory +npx -y @agentmemory/agentmemory@latest ``` **Option B: Docker Desktop** @@ -792,28 +833,29 @@ npx -y @agentmemory/agentmemory ```powershell # 1. Install Docker Desktop for Windows # 2. Start Docker Desktop and make sure the engine is running -# 3. Run agentmemory — it will auto-start the bundled compose file: -npx -y @agentmemory/agentmemory +# 3. Select Docker explicitly and run agentmemory: +$env:AGENTMEMORY_USE_DOCKER = "1" +npx -y @agentmemory/agentmemory@latest ``` **Option C: standalone MCP only (no engine).** If you only need the MCP tools for your agent and don't need the REST API, viewer, or cron jobs, skip the engine entirely: ```powershell -npx -y @agentmemory/agentmemory mcp +npx -y @agentmemory/agentmemory@latest mcp # or via the shim package: npx -y @agentmemory/mcp ``` -**Diagnostics for Windows:** if `npx @agentmemory/agentmemory` fails, re-run with `--verbose` to see the actual engine stderr. Common failure modes: +**Diagnostics for Windows:** if `npx -y @agentmemory/agentmemory@latest` fails, re-run it with `--verbose` to see the actual engine stderr. Common failure modes: | Symptom | Fix | |---|---| -| `iii-engine process started` then `did not become ready within 15s` | Engine crashed on startup; re-run with `--verbose`, check stderr | +| `The engine process started but the REST API never responded.` | Confirm all four derived ports are free, verify the pinned `iii.exe` stayed alive, then re-run with `--verbose` and inspect the captured engine stderr | | `Could not start iii-engine` | Neither `iii.exe` nor Docker is installed. See Option A or B above | | Port conflict | `netstat -ano \| findstr :3111` to see what's bound, then kill it or use `--port ` | | Docker fallback skipped even though Docker is installed | Make sure Docker Desktop is actually running (system tray icon) | -> Note: the iii **engine** is a prebuilt binary, not a cargo crate, so don't try to `cargo install` it. (The iii **SDKs** are published on crates.io, npm, and PyPI, but agentmemory doesn't need them.) Supported engine install methods, all pinned to v0.11.2: the prebuilt v0.11.2 binary above, the upstream sh install script **with the version pin** `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.11.2 sh` (macOS/Linux), and the Docker image `iiidev/iii:0.11.2`. A bare `install.sh | sh` installs the **latest** engine, which agentmemory does not support; always pass `VERSION=0.11.2`. Easiest of all: just run `npx @agentmemory/agentmemory`, which fetches the pinned engine into `~/.agentmemory/bin` for you. +> Note: the iii **engine** is a prebuilt binary, not a cargo crate, so don't try to `cargo install` it. (The iii **SDKs** are published on crates.io, npm, and PyPI, but agentmemory doesn't need them.) Supported engine install methods are all pinned to v0.11.2: the prebuilt binary above, agentmemory's macOS/Linux auto-install path (`curl`, POSIX `sh`, and `tar` required), and the Docker image `iiidev/iii:0.11.2`. A bare upstream `install.sh | sh` installs the latest engine, which agentmemory does not support. Use `npx -y @agentmemory/agentmemory@latest`; on macOS/Linux it fetches the pinned engine into `~/.agentmemory/bin`. --- @@ -897,9 +939,10 @@ PostToolUse hook fires -> SHA-256 dedup (5min window) -> Privacy filter (strip secrets, API keys) -> Store raw observation - -> LLM compress -> structured facts + concepts + narrative - -> Vector embedding (6 providers + local) - -> Index in BM25 + vector + -> Synthetic compression by default + (LLM-written compression only with a provider + AGENTMEMORY_AUTO_COMPRESS=true) + -> Vector embedding when an embedding provider is active + -> Index in BM25, plus vectors when enabled Stop / SessionEnd hook fires -> Summarize session @@ -974,21 +1017,23 @@ Triple-stream retrieval combining three signals: Fused with Reciprocal Rank Fusion (RRF, k=60) and session-diversified (max 3 results per session). -Hybrid ranking applies to the primary recall path, not just `smart-search`: `mem::search` (behind `memory_recall`) ranks through the same BM25 + vector + graph fusion once the vector index is populated. Lesson recall runs on a dedicated in-memory BM25 index instead of scanning the whole corpus per query. Superseded memory versions are excluded from every recall path; the version chain keeps their history. +When a vector index is populated, `mem::search` (behind `memory_recall`) uses the hybrid BM25 + vector ranker. Without embeddings it uses BM25. `smart-search` can additionally fuse structural graph matches when graph data exists, including in keyless mode. Lesson recall runs on a dedicated in-memory BM25 index instead of scanning the whole corpus per query. Superseded memory versions are excluded from every recall path; the version chain keeps their history. BM25 tokenizes Greek, Cyrillic, Hebrew, Arabic, and accented Latin out of the box. For Chinese / Japanese / Korean memories, install the optional segmenters (`npm install @node-rs/jieba tiny-segmenter`) to split CJK runs into word-level tokens; without them, agentmemory soft-falls to whole-run tokenization and prints a one-time hint on stderr. ### Embedding providers -agentmemory auto-detects your provider. For best results, install local embeddings (free): +Keyless installs disable vector embeddings: `mem::search` uses BM25, while `smart-search` can also use existing structural graph data. To opt into free on-device semantic embeddings, add this to `~/.agentmemory/.env` and restart agentmemory: -```bash -npm install @huggingface/transformers +```env +EMBEDDING_PROVIDER=local ``` +The normal npm install includes the optional `@huggingface/transformers` runtime. The first embedding request downloads `Xenova/all-MiniLM-L6-v2`, so it needs network access and can take longer; subsequent inference runs on-device. Remote providers are auto-detected from their keys unless `EMBEDDING_PROVIDER` overrides them. + | Provider | Model | Cost | Notes | |---|---|---|---| -| **Local (recommended)** | `all-MiniLM-L6-v2` | Free | Offline, +8pp recall over BM25-only | +| **Local (recommended opt-in)** | `all-MiniLM-L6-v2` | Free | On-device after the first model download, +8pp recall over BM25-only | | Gemini | `gemini-embedding-001` | Free tier | 100+ languages, 768/1536/3072 dims (MRL), 2048-token input. Replaces `text-embedding-004` ([deprecated, shutdown Jan 14, 2026](https://ai.google.dev/gemini-api/docs/deprecations)) | | OpenAI | `text-embedding-3-small` | $0.02/1M | Highest quality | | Voyage AI | `voyage-code-3` | Paid | Optimized for code | @@ -1001,7 +1046,7 @@ npm install @huggingface/transformers 54 tools, 6 resources, 3 prompts, and 17 skills. -> **MCP shim vs full server:** the published `@agentmemory/mcp` package is a thin shim. It exposes the full 54-tool surface **only when it can reach a running agentmemory server** via `AGENTMEMORY_URL` (proxy mode). With no server reachable, the shim falls back to a 7-tool local set (`memory_save`, `memory_recall`, `memory_smart_search`, `memory_sessions`, `memory_export`, `memory_audit`, `memory_governance_delete`). The `AGENTMEMORY_TOOLS=core|all` env var is a *server-side* flag; setting it in the shim's `env` block has no effect. If you see only 7 tools in Cursor / OpenCode / Gemini CLI, start `npx @agentmemory/agentmemory` (or the Docker stack) and set `AGENTMEMORY_URL=http://localhost:3111`. +> **MCP shim vs full server:** the published `@agentmemory/mcp` package is a thin shim. It exposes the full 54-tool surface **only when it can reach a running agentmemory server** via `AGENTMEMORY_URL` (proxy mode). With no server reachable, the shim falls back to a 7-tool local set (`memory_save`, `memory_recall`, `memory_smart_search`, `memory_sessions`, `memory_export`, `memory_audit`, `memory_governance_delete`). The `AGENTMEMORY_TOOLS=core|all` env var is a *server-side* flag; setting it in the shim's `env` block has no effect. If you see only 7 tools in Cursor / OpenCode / Gemini CLI, start `npx -y @agentmemory/agentmemory@latest` (or the Docker stack) and set `AGENTMEMORY_URL=http://localhost:3111`. ### 54 Tools @@ -1093,7 +1138,7 @@ The table shows the four core skills. The full set is 9 invocable skills plus 8 Run without the full server, for any MCP client. Either of these works: ```bash -npx -y @agentmemory/agentmemory mcp # canonical (always available) +npx -y @agentmemory/agentmemory@latest mcp # canonical (always available) npx -y @agentmemory/mcp # shim package alias ``` @@ -1268,11 +1313,11 @@ Full registry: [workers.iii.dev](https://workers.iii.dev). Every worker there co ### LLM Providers -agentmemory auto-detects from your environment. By default, no LLM calls are made unless you configure a provider or explicitly opt in to the Claude subscription fallback. +agentmemory auto-detects providers from your environment. A provider makes LLM-backed operations available, but provider configuration alone does not enable LLM-written observation compression. That path requires both a provider and `AGENTMEMORY_AUTO_COMPRESS=true`. | Provider | Config | Notes | |----------|--------|-------| -| **No-op (default)** | No config needed | LLM-backed compress/summarize is DISABLED. Synthetic BM25 compression + recall still work. See `AGENTMEMORY_ALLOW_AGENT_SDK` below if you used to rely on the Claude-subscription fallback. | +| **No-op (default)** | No config needed | LLM-backed compress/summarize is disabled. Synthetic compression and BM25 recall still work. See `AGENTMEMORY_ALLOW_AGENT_SDK` below if you used to rely on the Claude-subscription fallback. | | Anthropic API | `ANTHROPIC_API_KEY` | Per-token billing | | MiniMax | `MINIMAX_API_KEY` | Anthropic-compatible | | Gemini | `GEMINI_API_KEY` | Also enables embeddings | @@ -1326,11 +1371,11 @@ Qwen 3 models think by default and can burn the whole token budget on reasoning Reasoning-class models (`o1`-style with `` blocks) can return empty `content` with a `reasoning` field your local server may not surface. If extractions come back blank, switch to a non-reasoning model first. The `OPENAI_REASONING_EFFORT=none` env can also disable thinking on Ollama Cloud thinking models that mirror the OpenAI reasoning schema. -Local embeddings ship out of the box via `@huggingface/transformers`: `EMBEDDING_PROVIDER=local` (default) gives you `Xenova/all-MiniLM-L6-v2` (384-dim) entirely on-device. No extra config needed. +Local embeddings ship as an optional dependency but are not enabled by default. Set `EMBEDDING_PROVIDER=local` to opt into `Xenova/all-MiniLM-L6-v2` (384-dim). The first embedding request downloads the model; inference is on-device afterward. Without that setting or a remote embedding key, vectors stay disabled, `mem::search` uses BM25, and `smart-search` can still add existing graph matches. ### Cost-aware model selection -Background compression runs on every observation, so model choice meaningfully changes monthly spend. Captured workload data: 635 requests / 888K tokens / 35 hours of active use, run against three OpenRouter models at 2026-05-23 pricing. +When LLM-written background compression is enabled with both a provider and `AGENTMEMORY_AUTO_COMPRESS=true`, it runs on every observation, so model choice meaningfully changes monthly spend. Captured workload data: 635 requests / 888K tokens / 35 hours of active use, run against three OpenRouter models at 2026-05-23 pricing. | Tier | Model | Input / 1M | Output / 1M | Cost for the captured 35h | Notes | |------|-------|------------|-------------|---------------------------|-------| @@ -1382,9 +1427,11 @@ agentmemory + iii-engine bind four ports by default. If a restart fails with `po | Port | Process | Purpose | Env override | |------|---------|---------|--------------| | `3111` | agentmemory | REST API + MCP HTTP + `/agentmemory/health` + `/agentmemory/livez` | `III_REST_PORT` | -| `3112` | iii-engine | Internal streams worker (consumed by agentmemory + viewer) | `III_STREAMS_PORT` | -| `3113` | agentmemory | Real-time viewer (`http://localhost:3113`) | `AGENTMEMORY_VIEWER_PORT` | -| `49134` | iii-engine | WebSocket; workers register here, OTel telemetry flows over it | `III_ENGINE_URL` (full URL, default `ws://localhost:49134`) | +| `3112` | iii-engine | Internal streams worker (consumed by agentmemory + viewer) | `III_STREAM_PORT` (preferred) or legacy `III_STREAMS_PORT` | +| `3113` | agentmemory | Real-time viewer (`http://localhost:3113`) | `III_VIEWER_PORT` or `AGENTMEMORY_VIEWER_URL` for the reported URL | +| `49134` | iii-engine | WebSocket; workers register here, OTel telemetry flows over it | `III_ENGINE_PORT` or `III_ENGINE_URL` | + +`--port ` changes the REST anchor and derives streams `N+1`, viewer `N+2`, and engine WebSocket `N+46023` only where the corresponding explicit port or URL above is unset. It does not create an isolated lifecycle namespace. Use `--instance 1` for a second daemon; it uses anchor 3211, defaults to `3211/3212/3213/49234`, and receives a separate `instance-1` data and lifecycle directory. Instances 1 through 50 follow the same pattern. Stale-process cleanup when ports stay bound after a crashed run: @@ -1399,7 +1446,7 @@ netstat -ano | findstr ":3111 :3112 :3113 :49134" taskkill /F /PID ``` -`agentmemory stop` reaps both the worker and the engine pidfile cleanly on graceful shutdown. In Docker mode it tears down only agentmemory's own compose services and reaps the native worker before the Docker teardown; the CLI also refuses to adopt or signal Docker or VM port holders (Docker backend, vpnkit, colima) as the native engine unless `--force` is passed. The manual cleanup above is only for the post-crash case where neither pidfile is left behind. +`agentmemory stop` reaps both the worker and the engine pidfile cleanly on graceful native shutdown. In Docker mode it flushes the native worker, stops the exact validated engine container, and preserves both the container and its `/data` mount for a lossless restart; the next start validates and resumes that same container. Docker-backed uninstall requires `agentmemory remove --keep-data`: it removes shared agentmemory-managed files while preserving the validated container, its data mount, and the lifecycle record needed to recover them. Destructive Docker data deletion is intentionally left to the operator after a backup. The CLI also refuses to adopt or signal Docker or VM port holders (Docker backend, vpnkit, colima) as the native engine unless `--force` is passed. The manual cleanup above is only for the post-crash case where neither pidfile is left behind. ### Config File @@ -1421,6 +1468,8 @@ AGENTMEMORY_ALLOW_AGENT_SDK=true AGENTMEMORY_AUTO_COMPRESS=true ``` +LLM-written observation compression requires both lines: access to an LLM provider (including this explicit subscription fallback) and `AGENTMEMORY_AUTO_COMPRESS=true`. A provider by itself leaves the default synthetic compression path in place. + Consolidation (graph nodes, lessons, crystals) is on by default whenever an LLM provider is configured. Explicitly opt out with `CONSOLIDATION_ENABLED=false` if you want LLM-free operation. Graph extraction is a separate flag: ```env @@ -1467,7 +1516,7 @@ Create `~/.agentmemory/.env`: # leave OFF unless you understand the Stop-hook recursion risk: # AGENTMEMORY_ALLOW_AGENT_SDK=true -# Embedding provider (auto-detected, or override) +# Embedding provider (BM25-only when unset; local is an explicit opt-in) # EMBEDDING_PROVIDER=local # VOYAGE_API_KEY=... # OPENAI_API_KEY=sk-... @@ -1498,7 +1547,8 @@ Create `~/.agentmemory/.env`: # III_REST_PORT=3111 # Features -# AGENTMEMORY_AUTO_COMPRESS=false # OFF by default. When on, +# AGENTMEMORY_AUTO_COMPRESS=false # OFF by default. Requires an LLM + # provider as well. When both are on, # every PostToolUse hook calls your # LLM provider to compress the # observation — expect significant @@ -1597,7 +1647,7 @@ npm test # 1,674 tests npm run test:integration # API tests (requires running services) ``` -**Prerequisites:** Node.js >= 20, [iii-engine](https://iii.dev/docs) or Docker +**Prerequisites:** Node.js >= 20 with npm/npx; [iii-engine](https://iii.dev/docs) v0.11.2 or Docker. The macOS/Linux automatic engine install also requires `curl`, a POSIX `sh`, and `tar`; native Windows uses the manual pinned `iii.exe`, WSL2, or Docker Desktop.

License

diff --git a/docker-compose.yml b/docker-compose.yml index a74cd82a1a..66abc86966 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -8,14 +8,18 @@ services: iii-init: image: busybox:1.36 user: "0:0" + environment: + AGENTMEMORY_DOCKER_UID: "${AGENTMEMORY_DOCKER_UID:-65532}" + AGENTMEMORY_DOCKER_GID: "${AGENTMEMORY_DOCKER_GID:-65532}" + AGENTMEMORY_DOCKER_SKIP_CHOWN: "${AGENTMEMORY_DOCKER_SKIP_CHOWN:-0}" volumes: - "${AGENTMEMORY_DATA_DIR:-iii-data}:/data" - entrypoint: ["sh", "-c", "chown -R 65532:65532 /data && chmod 755 /data"] + entrypoint: ["sh", "-c", "if [ \"$${AGENTMEMORY_DOCKER_SKIP_CHOWN}\" = \"1\" ]; then exit 0; fi; chown -R $${AGENTMEMORY_DOCKER_UID}:$${AGENTMEMORY_DOCKER_GID} /data && chmod 755 /data"] restart: "no" iii-engine: # Pinned to v0.11.2 — the last engine that runs agentmemory's current - # worker model cleanly. v0.11.6 introduces a new sandbox-everything- + # direct-registration worker cleanly. v0.11.6 introduces a new sandbox-everything- # via-`iii worker add` model that agentmemory hasn't been refactored # for yet; the architectural mismatch surfaces as EPIPE reconnect # loops and empty search after save. Bump only after agentmemory is @@ -24,15 +28,20 @@ services: # Override per-shell or via .env file: # AGENTMEMORY_III_VERSION=0.11.7 docker compose up image: iiidev/iii:${AGENTMEMORY_III_VERSION:-0.11.2} - user: "65532:65532" + user: "${AGENTMEMORY_DOCKER_UID:-65532}:${AGENTMEMORY_DOCKER_GID:-65532}" depends_on: iii-init: condition: service_completed_successfully + environment: + III_REST_PORT: "${III_REST_PORT:-3111}" + III_STREAM_PORT: "${III_STREAM_PORT:-3112}" + III_VIEWER_PORT: "${III_VIEWER_PORT:-3113}" + III_ENGINE_PORT: "${III_ENGINE_PORT:-49134}" ports: - - "127.0.0.1:49134:49134" - - "127.0.0.1:3111:3111" - - "127.0.0.1:3112:3112" - - "127.0.0.1:9464:9464" + - "127.0.0.1:${III_ENGINE_PORT:-49134}:${III_ENGINE_PORT:-49134}" + - "127.0.0.1:${III_REST_PORT:-3111}:${III_REST_PORT:-3111}" + - "127.0.0.1:${III_STREAM_PORT:-3112}:${III_STREAM_PORT:-3112}" + - "127.0.0.1:${AGENTMEMORY_METRICS_PORT:-9464}:9464" volumes: - "${AGENTMEMORY_DATA_DIR:-iii-data}:/data" - ./iii-config.docker.yaml:/app/config.yaml:ro diff --git a/iii-config.docker.yaml b/iii-config.docker.yaml index 682236ec37..302b914542 100644 --- a/iii-config.docker.yaml +++ b/iii-config.docker.yaml @@ -1,12 +1,16 @@ workers: - name: iii-http config: - port: 3111 + port: ${III_REST_PORT:3111} host: 0.0.0.0 default_timeout: 180000 cors: - allowed_origins: ["http://localhost:3111", "http://localhost:3113", "http://127.0.0.1:3111", "http://127.0.0.1:3113"] + allowed_origins: ["http://localhost:${III_REST_PORT:3111}", "http://localhost:${III_VIEWER_PORT:3113}", "http://127.0.0.1:${III_REST_PORT:3111}", "http://127.0.0.1:${III_VIEWER_PORT:3113}"] allowed_methods: [GET, POST, PUT, DELETE, OPTIONS] + - name: iii-worker-manager + config: + port: ${III_ENGINE_PORT:49134} + host: 0.0.0.0 - name: iii-state config: adapter: @@ -28,7 +32,7 @@ workers: name: kv - name: iii-stream config: - port: 3112 + port: ${III_STREAM_PORT:3112} host: 0.0.0.0 adapter: name: kv @@ -45,9 +49,3 @@ workers: metrics_enabled: true logs_enabled: true logs_console_output: false - - name: iii-exec - config: - watch: - - src/**/*.ts - exec: - - node dist/index.mjs diff --git a/plugin/skills/agentmemory-config/REFERENCE.md b/plugin/skills/agentmemory-config/REFERENCE.md index d12aaed73d..ed128793dc 100644 --- a/plugin/skills/agentmemory-config/REFERENCE.md +++ b/plugin/skills/agentmemory-config/REFERENCE.md @@ -3,7 +3,7 @@ Generated by scanning `src/` for `AGENTMEMORY_*` usage. Do not edit the block below by hand; run `npm run skills:gen` after adding or removing a variable. Internal markers ending in two underscores are excluded. -Configuration is read from the environment and from `~/.agentmemory/.env` (no `export` prefix). 37 recognized variables: +Configuration is read from the environment and from `~/.agentmemory/.env` (no `export` prefix). 42 recognized variables: - `AGENTMEMORY_AGENT_SCOPE` - `AGENTMEMORY_ALLOW_AGENT_SDK` @@ -14,6 +14,9 @@ Configuration is read from the environment and from `~/.agentmemory/.env` (no `e - `AGENTMEMORY_CWD` - `AGENTMEMORY_DATA_DIR` - `AGENTMEMORY_DEBUG` +- `AGENTMEMORY_DOCKER_GID` +- `AGENTMEMORY_DOCKER_SKIP_CHOWN` +- `AGENTMEMORY_DOCKER_UID` - `AGENTMEMORY_DROP_STALE_INDEX` - `AGENTMEMORY_EXPORT_ROOT` - `AGENTMEMORY_FOLLOWUP_WINDOW_SECONDS` @@ -27,10 +30,12 @@ Configuration is read from the environment and from `~/.agentmemory/.env` (no `e - `AGENTMEMORY_LLM_NOTHINK` - `AGENTMEMORY_LLM_TIMEOUT_MS` - `AGENTMEMORY_MCP_BLOCK` +- `AGENTMEMORY_METRICS_PORT` - `AGENTMEMORY_PROBE_TIMEOUT_MS` - `AGENTMEMORY_PROJECT_NAME` - `AGENTMEMORY_PROVIDER` - `AGENTMEMORY_REFLECT` +- `AGENTMEMORY_RUNTIME_DIR` - `AGENTMEMORY_SDK_CHILD` - `AGENTMEMORY_SECRET` - `AGENTMEMORY_SESSION_ID` diff --git a/src/cli.ts b/src/cli.ts index 8bbdda9322..1e5fb6b78c 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -7,6 +7,7 @@ import { type ChildProcess, } from "node:child_process"; import { + cpSync, existsSync, mkdirSync, readdirSync, @@ -17,7 +18,7 @@ import { unlinkSync, writeFileSync, } from "node:fs"; -import { join, dirname, delimiter as PATH_DELIMITER } from "node:path"; +import { join, dirname, resolve, delimiter as PATH_DELIMITER } from "node:path"; import { fileURLToPath } from "node:url"; import { homedir, platform } from "node:os"; import * as p from "@clack/prompts"; @@ -54,6 +55,19 @@ import { type ConnectManifest, type RemoveOptions, } from "./cli/remove-plan.js"; +import { + dockerComposeArgs, + dockerProjectName, + isBundledConfig, + legacyDataMigrations, + resolveEngineCwd, + rewriteBundledConfig, + runtimeConfigPath, +} from "./cli/engine-launch.js"; +import { runtimeMetadataPath } from "./runtime-paths.js"; +import { createStartupStderrCapture } from "./cli/startup-stderr.js"; +import { renderEngineConfig } from "./cli/engine-config.js"; +import { processStatIsRunning } from "./cli/process-state.js"; import { renderSplash } from "./cli/splash.js"; import { isFirstRun, readPrefs, resetPrefs, writePrefs } from "./cli/preferences.js"; import { runOnboarding } from "./cli/onboarding.js"; @@ -102,7 +116,7 @@ if (args.includes("--version") || args.includes("-V")) { // script tracks `latest`, which made every fresh agentmemory install pull // engine 0.11.6 — and 0.11.6 introduces a new sandbox-everything-via- // `iii worker add` worker model that agentmemory hasn't been refactored -// for yet (we still use the old `iii-exec watch` config-file model). The +// for yet (the CLI still registers its worker directly through the SDK). The // architectural mismatch surfaces as EPIPE reconnect loops and empty // search results after save. Pin to v0.11.2 — the last engine that runs // agentmemory's current worker model cleanly — until the refactor lands. @@ -242,9 +256,21 @@ if (toolsIdx !== -1 && args[toolsIdx + 1]) { process.env["AGENTMEMORY_TOOLS"] = toolsMode; } -const portIdx = args.indexOf("--port"); -if (portIdx !== -1 && args[portIdx + 1]) { - process.env["III_REST_PORT"] = args[portIdx + 1]; +const URL_CLIENT_COMMANDS = new Set(["status", "doctor", "mcp"]); +let hasExplicitLocalPortOverride = false; +let selectedInstance = 0; + +function cliArgValue(name: string): string | undefined { + const inline = args.find((arg) => arg.startsWith(`${name}=`)); + if (inline) return inline.slice(name.length + 1); + const index = args.indexOf(name); + return index === -1 ? undefined : args[index + 1]; +} + +const portValue = cliArgValue("--port"); +if (portValue) { + process.env["III_REST_PORT"] = portValue; + hasExplicitLocalPortOverride = true; } // `--instance N` picks a 100-port block off the 3111 base so multiple @@ -253,26 +279,63 @@ if (portIdx !== -1 && args[portIdx + 1]) { // quartet; `--instance 1` → 3211/3212/3213/49234; etc. REST acts as the // anchor — streams/viewer/engine derive from it via fixed offsets below // unless an env explicitly pins each one. -const instanceIdx = args.indexOf("--instance"); -if (instanceIdx !== -1 && args[instanceIdx + 1]) { - const n = parseInt(args[instanceIdx + 1] || "", 10); - if (Number.isFinite(n) && n >= 0 && n <= 50) { - const base = 3111 + n * 100; - if (!process.env["III_REST_PORT"]) { - process.env["III_REST_PORT"] = String(base); - } +const instanceValue = cliArgValue("--instance"); +const hasInstanceArgument = args.some( + (arg) => arg === "--instance" || arg.startsWith("--instance="), +); +if (hasInstanceArgument) { + if (instanceValue === undefined || !/^\d+$/.test(instanceValue)) { + p.log.error("--instance must be an integer between 0 and 50."); + process.exit(1); } + const n = Number(instanceValue); + if (!Number.isInteger(n) || n > 50) { + p.log.error("--instance must be an integer between 0 and 50."); + process.exit(1); + } + selectedInstance = n; + const base = 3111 + n * 100; + if (!hasExplicitLocalPortOverride) { + process.env["III_REST_PORT"] = String(base); + } + hasExplicitLocalPortOverride = true; } -const dataDirResolution = resolveDataDir({ args }); -if (dataDirResolution.source !== "default") { - process.env["AGENTMEMORY_DATA_DIR"] = dataDirResolution.dataDir; +const restPort = parseInt(process.env["III_REST_PORT"] || "3111", 10); +if (Number.isFinite(restPort) && restPort > 0) { + process.env["III_STREAM_PORT"] ??= + process.env["III_STREAMS_PORT"] ?? String(restPort + 1); + process.env["III_VIEWER_PORT"] ??= String(restPort + 2); + const configuredEngineUrl = process.env["III_ENGINE_URL"]; + if (configuredEngineUrl) { + try { + const parsedEnginePort = new URL(configuredEngineUrl).port; + if (parsedEnginePort) { + process.env["III_ENGINE_PORT"] = parsedEnginePort; + } + } catch {} + } else { + process.env["III_ENGINE_PORT"] ??= String(restPort + 46023); + } + process.env["AGENTMEMORY_METRICS_PORT"] ??= String(restPort + 6353); } +const dataDirResolution = resolveDataDir({ args }); +process.env["AGENTMEMORY_DATA_DIR"] = dataDirResolution.dataDir; +process.env["AGENTMEMORY_RUNTIME_DIR"] = selectedInstance > 0 + ? dataDirResolution.dataDir + : join(homedir(), ".agentmemory"); + const skipEngine = args.includes("--no-engine"); +function shouldUseAgentmemoryUrl(): boolean { + return !hasExplicitLocalPortOverride && URL_CLIENT_COMMANDS.has(args[0] ?? ""); +} + function getRestPort(): number { - const url = process.env["AGENTMEMORY_URL"]; + const url = shouldUseAgentmemoryUrl() + ? process.env["AGENTMEMORY_URL"] + : undefined; if (url) { try { const parsed = new URL(url).port; @@ -283,11 +346,20 @@ function getRestPort(): number { } function getBaseUrl(): string { - const url = process.env["AGENTMEMORY_URL"]; + const url = shouldUseAgentmemoryUrl() + ? process.env["AGENTMEMORY_URL"] + : undefined; if (url) return url.replace(/\/+$/, ""); return `http://localhost:${getRestPort()}`; } +function getConfiguredViewerPort(): number { + return ( + parseInt(process.env["III_VIEWER_PORT"] || "", 10) || + getRestPort() + 2 + ); +} + let discoveredViewerPort: number | null = null; export async function discoverViewerPort(): Promise { @@ -320,14 +392,10 @@ function getViewerUrl(): string { try { const u = new URL(getBaseUrl()); - const vPort = - parseInt(process.env["III_VIEWER_PORT"] || "", 10) || - (parseInt(u.port || "3111", 10) || 3111) + 2; + const vPort = getConfiguredViewerPort(); return `${u.protocol}//${u.hostname}:${vPort}`; } catch { - const vPort = - parseInt(process.env["III_VIEWER_PORT"] || "", 10) || - getRestPort() + 2; + const vPort = getConfiguredViewerPort(); return `http://localhost:${vPort}`; } } @@ -352,8 +420,6 @@ function getStreamPort(): number { // second-instance collision. Overridable via // `III_ENGINE_PORT` or the legacy `III_ENGINE_URL=ws://host:port`. function getEnginePort(): number { - const explicit = parseInt(process.env["III_ENGINE_PORT"] || "", 10); - if (explicit) return explicit; const url = process.env["III_ENGINE_URL"]; if (url) { try { @@ -361,6 +427,8 @@ function getEnginePort(): number { if (parsed) return parseInt(parsed, 10); } catch {} } + const explicit = parseInt(process.env["III_ENGINE_PORT"] || "", 10); + if (explicit) return explicit; return getRestPort() + 46023; } @@ -412,37 +480,11 @@ function findIiiConfig(): string { join(__dirname, "..", "iii-config.yaml"), ]; for (const c of candidates) { - if (existsSync(c)) return c; + if (existsSync(c)) return resolve(c); } return ""; } -function yamlSingleQuoted(value: string): string { - return `'${value.replace(/'/g, "''")}'`; -} - -function renderIiiConfig(template: string, dataDir: string): string { - return template - .replace( - "file_path: ./data/state_store.db", - `file_path: ${yamlSingleQuoted(join(dataDir, "state_store.db"))}`, - ) - .replace( - "file_path: ./data/stream_store", - `file_path: ${yamlSingleQuoted(join(dataDir, "stream_store"))}`, - ); -} - -function writeRuntimeIiiConfig(configPath: string, dataDir: string): string { - mkdirSync(dataDir, { recursive: true }); - const runtimeConfigPath = join(dataDir, "iii-config.yaml"); - writeFileSync( - runtimeConfigPath, - renderIiiConfig(readFileSync(configPath, "utf8"), dataDir), - ); - return runtimeConfigPath; -} - function warnIfRelocatedDataDir(): void { if (!dataDirResolution.relocatedFrom) return; @@ -568,16 +610,36 @@ function resolveCompatibleIii(iiiBinPath: string | null | undefined): string | n } function enginePidfilePath(): string { - return join(homedir(), ".agentmemory", "iii.pid"); + return runtimeMetadataPath("iii.pid"); } function engineStatePath(): string { - return join(homedir(), ".agentmemory", "engine-state.json"); + return runtimeMetadataPath("engine-state.json"); } -type EngineState = - | { kind: "native"; configPath: string; attached?: boolean; binPath?: string } - | { kind: "docker"; composeFile: string }; +type NativeEngineState = { + kind: "native"; + configPath: string; + attached?: boolean; + binPath?: string; + restPort?: number; +}; + +type DockerEngineState = { + kind: "docker"; + schemaVersion?: 2; + composeFile: string; + projectName?: string; + engineVersion?: string; + restPort?: number; + dataDir?: string; + containerId?: string; + dataMountType?: "bind" | "volume"; + dataMountSource?: string; + preserveContainer?: boolean; +}; + +type EngineState = NativeEngineState | DockerEngineState; function writeEnginePidfile(pid: number): void { try { @@ -605,15 +667,8 @@ function clearEnginePidfile(): void { } catch {} } -// Worker pidfile: the agentmemory worker process -// (`node dist/index.mjs`) is spawned by iii-exec inside the engine. When -// `agentmemory stop` kills only the engine pid, the worker can survive -// (detached spawn, signal not propagated, or kept alive by a wrapper -// script). On the next start, the orphaned worker reconnects to the new -// engine and shows up as a duplicate registration. We write the worker -// pid from src/index.ts on boot so stop can find and reap it. function workerPidfilePath(): string { - return join(homedir(), ".agentmemory", "worker.pid"); + return runtimeMetadataPath("worker.pid"); } function readWorkerPidfile(): number | null { @@ -636,7 +691,14 @@ function writeEngineState(state: EngineState): void { try { const statePath = engineStatePath(); mkdirSync(dirname(statePath), { recursive: true }); - writeFileSync(statePath, `${JSON.stringify(state)}\n`, { encoding: "utf-8" }); + const normalized = state.kind === "docker" && state.schemaVersion === 2 + ? { + ...state, + restPort: state.restPort ?? getRestPort(), + dataDir: state.dataDir ?? dataDirResolution.dataDir, + } + : { ...state, restPort: state.restPort ?? getRestPort() }; + writeFileSync(statePath, `${JSON.stringify(normalized)}\n`, { encoding: "utf-8" }); } catch (err) { vlog(`writeEngineState: ${err instanceof Error ? err.message : String(err)}`); } @@ -661,6 +723,55 @@ function clearEngineState(): void { } catch {} } +function engineStateRestPort(state: EngineState): number { + if (state.restPort && Number.isFinite(state.restPort)) return state.restPort; + if (state.kind === "docker") { + const projectPort = state.projectName?.match(/^agentmemory-(\d+)$/)?.[1]; + if (projectPort) return parseInt(projectPort, 10); + return 3111; + } + try { + const raw = readFileSync(state.configPath, "utf-8"); + const httpBlock = raw.match( + /- name:\s*iii-http([\s\S]*?)(?=\n\s*- name:|$)/, + )?.[1]; + const configuredPort = httpBlock?.match(/\n\s*port:\s*(\d+)/)?.[1]; + if (configuredPort) return parseInt(configuredPort, 10); + } catch {} + return 3111; +} + +async function startWorkerForEngineState(): Promise { + const workerPid = readWorkerPidfile(); + if (workerPid && pidAlive(workerPid)) return; + if (configuredEngineMayStartWorker() && await waitForConfiguredWorker(5000)) { + return; + } + await import("./index.js"); +} + +function configuredEngineMayStartWorker(): boolean { + const state = readEngineState(); + if (state?.kind !== "native") return false; + try { + const raw = readFileSync(state.configPath, "utf-8"); + return raw.includes("- name: iii-exec"); + } catch { + return false; + } +} + +async function waitForConfiguredWorker(timeoutMs: number): Promise { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + const workerPid = readWorkerPidfile(); + if (workerPid && pidAlive(workerPid)) return true; + if (await isAgentmemoryReady()) return true; + await new Promise((resolve) => setTimeout(resolve, 100)); + } + return false; +} + function discoverComposeFile(): string | null { const candidates = [ join(__dirname, "..", "docker-compose.yml"), @@ -670,6 +781,401 @@ function discoverComposeFile(): string | null { return candidates.find((c) => existsSync(c)) ?? null; } +type DockerEngineInspection = + | { + status: "running" | "stopped"; + composeFile: string; + projectName: string; + containerId: string; + dataMountType: "bind" | "volume"; + dataMountSource: string; + preserveContainer: boolean; + } + | { status: "missing"; composeFile: string; projectName?: string } + | { status: "unavailable"; reason: string }; + +type DockerInspectRecord = { + Id?: string; + State?: { Running?: boolean }; + Config?: { Image?: string; Labels?: Record }; + HostConfig?: { + PortBindings?: Record< + string, + Array<{ HostIp?: string; HostPort?: string }> | null + >; + }; + Mounts?: Array<{ + Type?: string; + Name?: string; + Source?: string; + Destination?: string; + }>; +}; + +function sameDockerMountSource( + type: "bind" | "volume", + left: string, + right: string, +): boolean { + return type === "bind" ? resolve(left) === resolve(right) : left === right; +} + +function inspectDockerContainer( + dockerBin: string, + containerId: string, + state: DockerEngineState, + ownerPort: number, +): DockerEngineInspection { + const result = spawnSync(dockerBin, ["inspect", containerId], { + encoding: "utf-8", + stdio: ["ignore", "pipe", "ignore"], + maxBuffer: 1024 * 1024, + }); + if (result.status !== 0) { + return { status: "unavailable", reason: `docker inspect failed for ${containerId}` }; + } + let record: DockerInspectRecord; + try { + record = (JSON.parse(result.stdout) as DockerInspectRecord[])[0] ?? {}; + } catch { + return { status: "unavailable", reason: `docker inspect returned invalid JSON for ${containerId}` }; + } + + const image = record.Config?.Image ?? ""; + const expectedImage = `iiidev/iii:${state.engineVersion ?? IIPINNED_VERSION}`; + if (image !== expectedImage) { + return { + status: "unavailable", + reason: `saved container uses ${image || "an unknown image"}, expected ${expectedImage}`, + }; + } + + const labels = record.Config?.Labels ?? {}; + const projectName = labels["com.docker.compose.project"] ?? ""; + if (labels["com.docker.compose.service"] !== "iii-engine" || !projectName) { + return { + status: "unavailable", + reason: "saved container is not the iii-engine service of a Compose project", + }; + } + if (state.projectName && state.projectName !== projectName) { + return { + status: "unavailable", + reason: `saved Docker project ${state.projectName} does not match container project ${projectName}`, + }; + } + if (state.schemaVersion === 2 && projectName !== dockerProjectName(ownerPort)) { + return { + status: "unavailable", + reason: `Docker project ${projectName} does not match REST port ${ownerPort}`, + }; + } + + const restBindings = record.HostConfig?.PortBindings?.[`${ownerPort}/tcp`] ?? []; + if (!restBindings.some((binding) => binding.HostPort === String(ownerPort))) { + return { + status: "unavailable", + reason: `saved container does not publish REST port ${ownerPort}`, + }; + } + + const dataMount = record.Mounts?.find((mount) => mount.Destination === "/data"); + const dataMountType = dataMount?.Type; + const dataMountSource = dataMountType === "volume" + ? dataMount?.Name ?? dataMount?.Source ?? "" + : dataMount?.Source ?? ""; + if ( + (dataMountType !== "bind" && dataMountType !== "volume") || + !dataMountSource + ) { + return { + status: "unavailable", + reason: "saved container has no verifiable /data bind or volume mount", + }; + } + if ( + state.dataMountType && + state.dataMountType !== dataMountType + ) { + return { + status: "unavailable", + reason: `saved /data mount type ${state.dataMountType} changed to ${dataMountType}`, + }; + } + if ( + state.dataMountSource && + !sameDockerMountSource(dataMountType, state.dataMountSource, dataMountSource) + ) { + return { + status: "unavailable", + reason: "saved container /data mount source changed", + }; + } + if (!state.dataMountSource) { + if ( + dataMountType === "bind" && + resolve(dataMountSource) !== resolve(dataDirResolution.dataDir) + ) { + return { + status: "unavailable", + reason: `container /data bind ${dataMountSource} does not match ${dataDirResolution.dataDir}`, + }; + } + if (dataMountType === "volume" && dataDirResolution.source !== "default") { + return { + status: "unavailable", + reason: "legacy container uses a named volume but this invocation selects an explicit data directory", + }; + } + } + if ( + state.dataDir && + resolve(state.dataDir) !== resolve(dataDirResolution.dataDir) + ) { + return { + status: "unavailable", + reason: `saved data directory ${state.dataDir} does not match ${dataDirResolution.dataDir}`, + }; + } + + return { + status: record.State?.Running ? "running" : "stopped", + composeFile: existsSync(state.composeFile) + ? state.composeFile + : discoverComposeFile() ?? state.composeFile, + projectName, + containerId: record.Id ?? containerId, + dataMountType, + dataMountSource, + preserveContainer: + state.preserveContainer === true || + (state.schemaVersion !== 2 && dataMountType === "volume"), + }; +} + +function inspectOwnedDockerEngine(state: EngineState): DockerEngineInspection { + if (state.kind !== "docker") { + return { status: "unavailable", reason: "engine state is not Docker" }; + } + const ownerPort = engineStateRestPort(state); + if (state.schemaVersion === 2 && state.projectName !== dockerProjectName(ownerPort)) { + return { + status: "unavailable", + reason: `saved Docker project ${state.projectName} does not match REST port ${ownerPort}`, + }; + } + + const dockerBin = whichBinary("docker"); + if (!dockerBin) { + return { status: "unavailable", reason: "docker is not on PATH" }; + } + + const discoveryFailures: string[] = []; + if (state.containerId) { + const direct = inspectDockerContainer(dockerBin, state.containerId, state, ownerPort); + if (direct.status !== "unavailable") return direct; + if (state.preserveContainer) return direct; + discoveryFailures.push(direct.reason); + } + + const composeFile = existsSync(state.composeFile) + ? state.composeFile + : discoverComposeFile() ?? state.composeFile; + const candidateIds = new Set(); + try { + if (existsSync(composeFile)) { + const composeText = readFileSync(composeFile, "utf-8"); + if (!/^\s+iii-engine:/m.test(composeText)) { + return { + status: "unavailable", + reason: `${composeFile} does not define iii-engine`, + }; + } + const psResult = spawnSync( + dockerBin, + dockerComposeArgs(composeFile, state.projectName, [ + "ps", + "-q", + "--all", + "iii-engine", + ]), + { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] }, + ); + if (psResult.status === 0) { + for (const id of (psResult.stdout ?? "").trim().split(/\s+/)) { + if (id) candidateIds.add(id); + } + } else { + discoveryFailures.push( + `docker compose ps failed for project ${state.projectName ?? ""}`, + ); + } + } + + const scanArgs = [ + "ps", + "-aq", + "--filter", + "label=com.docker.compose.service=iii-engine", + "--filter", + `ancestor=iiidev/iii:${state.engineVersion ?? IIPINNED_VERSION}`, + ...(state.projectName + ? ["--filter", `label=com.docker.compose.project=${state.projectName}`] + : []), + ]; + const scanResult = spawnSync( + dockerBin, + scanArgs, + { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] }, + ); + if (scanResult.status === 0) { + for (const id of (scanResult.stdout ?? "").trim().split(/\s+/)) { + if (id) candidateIds.add(id); + } + } else { + discoveryFailures.push("docker container scan failed"); + } + + const matches: DockerEngineInspection[] = []; + for (const containerId of candidateIds) { + const inspected = inspectDockerContainer(dockerBin, containerId, state, ownerPort); + if (inspected.status === "running" || inspected.status === "stopped") { + if ( + !matches.some( + (match) => + (match.status === "running" || match.status === "stopped") && + match.containerId === inspected.containerId, + ) + ) { + matches.push(inspected); + } + } else if (inspected.status === "unavailable") { + discoveryFailures.push(inspected.reason); + } + } + if (matches.length === 1) return matches[0]!; + if (matches.length > 1) { + return { + status: "unavailable", + reason: `multiple Docker iii-engine containers match REST port ${ownerPort}`, + }; + } + if (discoveryFailures.length > 0) { + return { + status: "unavailable", + reason: [...new Set(discoveryFailures)].join("; "), + }; + } + if (state.schemaVersion !== 2 || state.preserveContainer) { + return { + status: "unavailable", + reason: `legacy Docker ownership exists for REST port ${ownerPort}, but no unique container can be verified`, + }; + } + return { + status: "missing", + composeFile, + projectName: state.projectName, + }; + } catch (err) { + return { + status: "unavailable", + reason: err instanceof Error ? err.message : String(err), + }; + } +} + +function persistDockerInspection( + state: DockerEngineState, + inspection: DockerEngineInspection, +): DockerEngineState { + if (inspection.status !== "running" && inspection.status !== "stopped") { + return state; + } + const resolved: DockerEngineState = { + ...state, + composeFile: inspection.composeFile, + projectName: inspection.projectName, + containerId: inspection.containerId, + dataMountType: inspection.dataMountType, + dataMountSource: inspection.dataMountSource, + preserveContainer: inspection.preserveContainer, + }; + writeEngineState(resolved); + return resolved; +} + +async function assertRuntimePortOwnership(): Promise { + const state = readEngineState(); + if (!state) return; + const ownerPort = engineStateRestPort(state); + const requestedPort = getRestPort(); + if (ownerPort === requestedPort) return; + + if (state.kind === "docker") { + const inspection = inspectOwnedDockerEngine(state); + if (inspection.status === "unavailable") { + p.log.error( + `The data directory contains Docker ownership for REST port ${ownerPort}, but it cannot be verified: ${inspection.reason}. Refusing to overwrite its lifecycle state.`, + ); + process.exit(1); + } + if (inspection.status === "running" || inspection.status === "stopped") { + persistDockerInspection(state, inspection); + p.log.error( + `The canonical lifecycle state is owned by a ${inspection.status} Docker engine on REST port ${ownerPort}. Refusing to reuse it for port ${requestedPort}. Use the original port, or use --instance for an isolated daemon.`, + ); + process.exit(1); + } + p.log.error( + `The canonical lifecycle state still records a Docker engine for REST port ${ownerPort}, but its container is missing. Refusing to overwrite that ownership from port ${requestedPort}. Re-run \`agentmemory stop\` with the original port to reconcile it.`, + ); + process.exit(1); + } + + const enginePid = readEnginePidfile(); + const workerPid = readWorkerPidfile(); + let active = Boolean( + (enginePid && + pidAlive(enginePid) && + !isForeignPortHolder(pidCommand(enginePid))) || + (workerPid && pidAlive(workerPid)), + ); + if (!active) { + try { + await fetch(`http://127.0.0.1:${ownerPort}/`, { + signal: AbortSignal.timeout(750), + }); + active = true; + } catch {} + } + if (active) { + p.log.error( + `The canonical lifecycle state is owned by a live agentmemory engine on REST port ${ownerPort}. Refusing to reuse it for port ${requestedPort}. Use the original port, or use --instance for an isolated daemon.`, + ); + process.exit(1); + } + clearEnginePidfile(); + clearWorkerPidfile(); + clearEngineState(); +} + +function configureDockerHostUser(): void { + if (typeof process.getuid !== "function" || typeof process.getgid !== "function") { + return; + } + const hostUid = String(process.getuid()); + const hostGid = String(process.getgid()); + process.env["AGENTMEMORY_DOCKER_UID"] ??= hostUid; + process.env["AGENTMEMORY_DOCKER_GID"] ??= hostGid; + if ( + process.env["AGENTMEMORY_DOCKER_UID"] === hostUid && + process.env["AGENTMEMORY_DOCKER_GID"] === hostGid + ) { + process.env["AGENTMEMORY_DOCKER_SKIP_CHOWN"] ??= "1"; + } +} + function isInvokedViaNpx(): boolean { if (process.env["npm_lifecycle_event"] === "npx") return true; const argv1 = process.argv[1] ?? ""; @@ -884,8 +1390,12 @@ async function runIiiInstaller(): Promise<{ ok: boolean; binPath: string | null const shBin = whichBinary("sh"); const curlBin = whichBinary("curl"); - if (!shBin || !curlBin) { - p.log.warn("curl or sh not found. Cannot auto-install iii-engine."); + const tarBin = whichBinary("tar"); + if (!shBin || !curlBin || !tarBin) { + const missing = [!shBin && "sh", !curlBin && "curl", !tarBin && "tar"] + .filter(Boolean) + .join(", "); + p.log.warn(`${missing} not found. Cannot auto-install iii-engine.`); return { ok: false, binPath: null }; } @@ -916,6 +1426,40 @@ type StartupFailure = { }; let startupFailure: StartupFailure | null = null; +let activeStartupStderr = createStartupStderrCapture(); + +function printCapturedStartupStderr(): void { + const stderr = activeStartupStderr.text().trim(); + if (IS_VERBOSE && stderr) { + p.note(stderr, "engine stderr"); + } +} + +function printDockerStartupLogs(): void { + const state = readEngineState(); + if (state?.kind !== "docker") return; + const inspection = inspectOwnedDockerEngine(state); + if (inspection.status !== "running" && inspection.status !== "stopped") return; + const dockerBin = whichBinary("docker"); + if (!dockerBin) return; + const result = spawnSync( + dockerBin, + [ + "logs", + "--tail", + "80", + inspection.containerId, + ], + { + encoding: "utf-8", + stdio: ["ignore", "pipe", "pipe"], + timeout: 5000, + maxBuffer: 64 * 1024, + }, + ); + const output = `${result.stdout ?? ""}${result.stderr ?? ""}`.trim(); + if (output) p.note(output.slice(-16 * 1024), "docker engine logs"); +} // Spawn a background engine and collect any startup stderr for a short // window. The process is unref'd so the CLI parent can exit cleanly; we @@ -925,31 +1469,28 @@ function spawnEngineBackground( bin: string, spawnArgs: string[], label: string, + cwd?: string, ): ChildProcess { - vlog(`spawn: ${bin} ${spawnArgs.join(" ")}`); + vlog(`spawn: ${bin} ${spawnArgs.join(" ")}${cwd ? ` (cwd: ${cwd})` : ""}`); + activeStartupStderr = createStartupStderrCapture(); const child = spawn(bin, spawnArgs, { detached: true, stdio: ["ignore", "ignore", "pipe"], windowsHide: true, + ...(cwd ? { cwd } : {}), }); const isDocker = label.includes("Docker"); if (!isDocker && typeof child.pid === "number") { writeEnginePidfile(child.pid); } - const stderrChunks: Buffer[] = []; - let stderrBytes = 0; - const MAX_STDERR_CAPTURE = 16 * 1024; child.stderr?.on("data", (chunk: Buffer) => { - if (stderrBytes >= MAX_STDERR_CAPTURE) return; - const slice = chunk.subarray(0, MAX_STDERR_CAPTURE - stderrBytes); - stderrChunks.push(slice); - stderrBytes += slice.length; + activeStartupStderr.append(chunk); }); child.on("exit", (code, signal) => { const abnormal = (code !== null && code !== 0) || (code === null && signal !== null); if (abnormal) { - const stderr = Buffer.concat(stderrChunks).toString("utf-8"); + const stderr = activeStartupStderr.text(); startupFailure = { kind: isDocker ? "docker-crashed" : "engine-crashed", stderr: @@ -963,19 +1504,93 @@ function spawnEngineBackground( if (IS_VERBOSE && stderr.trim()) { p.log.error(`engine stderr:\n${stderr}`); } - if (!isDocker) clearEnginePidfile(); - clearEngineState(); + if (!isDocker) { + clearEnginePidfile(); + clearEngineState(); + } } }); child.unref(); return child; } +function prepareEngineLaunch(configPath: string): { + configPath: string; + cwd: string; +} { + const home = homedir(); + const bundledConfig = isBundledConfig(configPath, __dirname); + const cwd = resolveEngineCwd( + configPath, + process.cwd(), + home, + bundledConfig, + ); + try { + mkdirSync(cwd, { recursive: true }); + } catch { + return { configPath, cwd: process.cwd() }; + } + try { + const rawConfig = readFileSync(configPath, "utf-8"); + const options = { + dataDir: dataDirResolution.dataDir, + ports: { + restPort: getRestPort(), + streamPort: getStreamPort(), + viewerPort: getConfiguredViewerPort(), + enginePort: getEnginePort(), + }, + }; + const rewritten = bundledConfig + ? rewriteBundledConfig( + rawConfig, + home, + process.execPath, + join(__dirname, "index.mjs"), + options, + ) + : renderEngineConfig(rawConfig, options); + const runtimePath = runtimeConfigPath(dataDirResolution.dataDir); + mkdirSync(dirname(runtimePath), { recursive: true }); + writeFileSync(runtimePath, rewritten, "utf-8"); + if (selectedInstance === 0 && dataDirResolution.source === "default") { + for (const m of legacyDataMigrations( + process.cwd(), + home, + dataDirResolution.dataDir, + )) { + if (existsSync(m.from) && !existsSync(m.to)) { + try { + mkdirSync(dirname(m.to), { recursive: true }); + cpSync(m.from, m.to, { recursive: true }); + p.log.info(`Copied existing data: ${m.from} -> ${m.to}`); + } catch (err) { + vlog(`data copy failed for ${m.from}: ${String(err)}`); + } + } + } + } + return { + configPath: runtimePath, + cwd, + }; + } catch (err) { + vlog(`runtime config generation failed, using bundled config verbatim: ${String(err)}`); + return { configPath, cwd }; + } +} + function startIiiBin(iiiBin: string, configPath: string): boolean { const s = p.spinner(); s.start(`Starting iii-engine: ${iiiBin}`); - writeEngineState({ kind: "native", configPath, binPath: iiiBin }); - spawnEngineBackground(iiiBin, ["--config", configPath], "iii-engine"); + const launch = prepareEngineLaunch(configPath); + writeEngineState({ + kind: "native", + configPath: launch.configPath, + binPath: iiiBin, + }); + spawnEngineBackground(iiiBin, ["--config", launch.configPath], "iii-engine", launch.cwd); s.stop(c.ok("iii-engine process started")); return true; } @@ -995,13 +1610,44 @@ function pickCompatibleIii(candidates: Array): string } async function startEngine(): Promise { + await assertRuntimePortOwnership(); + const persistedState = readEngineState(); + if (persistedState?.kind === "docker") { + const inspection = inspectOwnedDockerEngine(persistedState); + if (inspection.status === "unavailable" || inspection.status === "missing") { + const detail = inspection.status === "unavailable" + ? inspection.reason + : "container is missing"; + p.log.error( + `A saved Docker engine owns this lifecycle state, but it cannot be resumed safely (${detail}). Run \`agentmemory stop\` to reconcile that project before starting another engine.`, + ); + return false; + } + persistDockerInspection(persistedState, inspection); + if (inspection.status === "running") return true; + const dockerBin = whichBinary("docker"); + return Boolean( + dockerBin && + runCommand(dockerBin, ["start", inspection.containerId], { + label: `Restarting owned Docker container ${inspection.containerId}`, + }), + ); + } const configPath = findIiiConfig(); warnIfRelocatedDataDir(); - const runtimeConfigPath = configPath - ? writeRuntimeIiiConfig(configPath, dataDirResolution.dataDir) - : ""; const pathIii = whichBinary("iii"); - vlog(`iii binary: ${pathIii ?? "(not on PATH)"}, config: ${runtimeConfigPath || "(not found)"}`); + vlog(`iii binary: ${pathIii ?? "(not on PATH)"}, config: ${configPath || "(not found)"}`); + + const dockerBin = whichBinary("docker"); + const dockerComposeCandidates = [ + join(__dirname, "..", "docker-compose.yml"), + join(__dirname, "docker-compose.yml"), + join(process.cwd(), "docker-compose.yml"), + ]; + const composeFile = dockerComposeCandidates.find((c) => existsSync(c)); + const dockerOptIn = + process.env["AGENTMEMORY_USE_DOCKER"] === "1" || + process.env["AGENTMEMORY_USE_DOCKER"] === "true"; const fallbacks = fallbackIiiPaths().filter((p) => existsSync(p)); for (const f of fallbacks) { @@ -1011,12 +1657,12 @@ async function startEngine(): Promise { let iiiBin = pickCompatibleIii([pathIii, ...fallbacks]); - if (iiiBin && runtimeConfigPath) { + if (iiiBin && configPath && !(dockerOptIn && dockerBin && composeFile)) { if (iiiBin !== pathIii) { p.log.info(`Using iii at: ${c.dim(iiiBin)} (v${c.accent(IIPINNED_VERSION)})`); process.env["PATH"] = `${dirname(iiiBin)}${PATH_DELIMITER}${process.env["PATH"] ?? ""}`; } - return startIiiBin(iiiBin, runtimeConfigPath); + return startIiiBin(iiiBin, configPath); } if (pathIii && !iiiBin) { @@ -1032,20 +1678,9 @@ async function startEngine(): Promise { return false; } - const dockerBin = whichBinary("docker"); vlog(`docker binary: ${dockerBin ?? "(not on PATH)"}`); mkdirSync(dataDirResolution.dataDir, { recursive: true }); - const dockerComposeCandidates = [ - join(__dirname, "..", "docker-compose.yml"), - join(__dirname, "docker-compose.yml"), - join(process.cwd(), "docker-compose.yml"), - ]; - const composeFile = dockerComposeCandidates.find((c) => existsSync(c)); vlog(`docker-compose.yml: ${composeFile ?? "(not found)"}`); - - const dockerOptIn = - process.env["AGENTMEMORY_USE_DOCKER"] === "1" || - process.env["AGENTMEMORY_USE_DOCKER"] === "true"; const interactive = !!process.stdin.isTTY && !process.env["CI"]; type Choice = "install" | "docker" | "manual"; @@ -1125,10 +1760,21 @@ async function startEngine(): Promise { if (choice === "docker" && dockerBin && composeFile) { const s = p.spinner(); s.start("Starting iii-engine via Docker..."); - writeEngineState({ kind: "docker", composeFile }); + configureDockerHostUser(); + const projectName = dockerProjectName(getRestPort()); + writeEngineState({ + kind: "docker", + schemaVersion: 2, + composeFile, + projectName, + engineVersion: IIPINNED_VERSION, + dataMountType: "bind", + dataMountSource: dataDirResolution.dataDir, + preserveContainer: false, + }); spawnEngineBackground( dockerBin, - ["compose", "-f", composeFile, "up", "-d"], + dockerComposeArgs(composeFile, projectName, ["up", "-d"]), "iii-engine via Docker", ); s.stop("Docker compose started"); @@ -1152,6 +1798,53 @@ async function waitForEngine(timeoutMs: number): Promise { return false; } +async function reconcilePersistedDockerEngine(): Promise { + const state = readEngineState(); + if (state?.kind !== "docker") return false; + const inspection = inspectOwnedDockerEngine(state); + if (inspection.status === "unavailable") { + p.log.error( + `The saved Docker engine cannot be verified: ${inspection.reason}. Refusing to overwrite its lifecycle state. Run \`agentmemory stop\` after restoring Docker/compose access.`, + ); + process.exit(1); + } + if (inspection.status === "missing") { + p.log.error( + "The saved Docker project no longer has an iii-engine container. Run `agentmemory stop` to remove its stale project state, then start agentmemory again.", + ); + process.exit(1); + } + persistDockerInspection(state, inspection); + if (inspection.status === "stopped") { + const dockerBin = whichBinary("docker"); + if ( + !dockerBin || + !runCommand(dockerBin, ["start", inspection.containerId], { + label: `Restarting owned Docker container ${inspection.containerId}`, + }) + ) { + p.log.error("The owned Docker container could not be restarted; lifecycle state was preserved."); + process.exit(1); + } + } + if (!(await waitForEngine(5000))) { + printDockerStartupLogs(); + p.log.error( + `The owned Docker container is running, but its REST API on port ${getRestPort()} is unhealthy. The saved project was preserved; inspect the Docker logs above or run \`agentmemory stop\`.`, + ); + process.exit(1); + } + await startWorkerForEngineState(); + if (!(await waitForAgentmemoryReady(15000))) { + p.log.error("agentmemory worker did not become ready within 15s."); + process.exit(1); + } + const consoleState = await ensureIiiConsole(); + await maybeOfferGlobalInstall(); + printReadyHint(consoleState); + return true; +} + function installInstructions(): string[] { const releaseUrl = iiiReleaseUrl(); if (IS_WINDOWS) { @@ -1211,7 +1904,10 @@ async function waitForAgentmemoryReady(timeoutMs: number): Promise { // `III_ENGINE_URL=ws://my-host:49134` doesn't print misleading // localhost addresses. Falls back to localhost. function getEngineHost(): string { - for (const envKey of ["III_ENGINE_URL", "AGENTMEMORY_URL"]) { + const envKeys = shouldUseAgentmemoryUrl() + ? ["III_ENGINE_URL", "AGENTMEMORY_URL"] + : ["III_ENGINE_URL"]; + for (const envKey of envKeys) { const raw = process.env[envKey]; if (!raw) continue; try { @@ -1267,6 +1963,7 @@ function printReadyHint(consoleState: IiiConsoleState): void { } async function main() { + await assertRuntimePortOwnership(); // Booting a second instance next to a live daemon registers a duplicate // worker on the running engine, and on iii 0.11.2 the second instance's // shutdown tears down the daemon's HTTP trigger routing (every @@ -1318,6 +2015,8 @@ async function main() { return; } + if (await reconcilePersistedDockerEngine()) return; + if (await isEngineRunning()) { if (IS_VERBOSE) p.log.success("iii-engine is running"); // Prefer the binary path persisted at launch time over whatever's on @@ -1344,12 +2043,14 @@ async function main() { // the pinned engine, never a silent loop. if (detected === IIPINNED_VERSION) { adoptRunningEngine(); - await import("./index.js"); - if (await waitForAgentmemoryReady(15000)) { - const consoleState = await ensureIiiConsole(); - await maybeOfferGlobalInstall(); - printReadyHint(consoleState); + await startWorkerForEngineState(); + if (!(await waitForAgentmemoryReady(15000))) { + p.log.error("agentmemory worker did not become ready within 15s."); + process.exit(1); } + const consoleState = await ensureIiiConsole(); + await maybeOfferGlobalInstall(); + printReadyHint(consoleState); return; } @@ -1410,6 +2111,7 @@ async function main() { if (!ready) { const port = getRestPort(); s.stop("iii-engine did not become ready within 15s"); + printDockerStartupLogs(); if (startupFailure?.kind === "engine-crashed" || startupFailure?.kind === "docker-crashed") { p.log.error("The iii-engine process crashed on startup."); @@ -1435,6 +2137,7 @@ async function main() { ); } else { p.log.error("The engine process started but the REST API never responded."); + printCapturedStartupStderr(); p.note( [ `Check whether port ${port} is already bound by another process:`, @@ -1452,12 +2155,14 @@ async function main() { } s.stop(c.ok("iii-engine is ready")); - await import("./index.js"); - if (await waitForAgentmemoryReady(15000)) { - const consoleState = await ensureIiiConsole(); - await maybeOfferGlobalInstall(); - printReadyHint(consoleState); + await startWorkerForEngineState(); + if (!(await waitForAgentmemoryReady(15000))) { + p.log.error("agentmemory worker did not become ready within 15s."); + process.exit(1); } + const consoleState = await ensureIiiConsole(); + await maybeOfferGlobalInstall(); + printReadyHint(consoleState); // Mark splash as something to skip on subsequent runs. This is a // no-op if onboarding already flipped the flag (idempotent merge). writePrefs({ skipSplash: true }); @@ -1833,7 +2538,7 @@ async function passiveServerChecks(): Promise { ok: hasEmbed, hint: hasEmbed ? undefined - : "Running BM25-only. Add OPENAI_API_KEY / VOYAGE_API_KEY / COHERE_API_KEY / OLLAMA_HOST", + : "Running BM25-only. Set EMBEDDING_PROVIDER=local for on-device semantic search, or add OPENAI_API_KEY / VOYAGE_API_KEY / COHERE_API_KEY / OLLAMA_HOST", }, ); @@ -2271,6 +2976,7 @@ async function runInit() { } async function startServerForDemo(): Promise<() => Promise> { + await assertRuntimePortOwnership(); if (await isAgentmemoryReady()) { return async () => {}; } @@ -2284,12 +2990,14 @@ async function startServerForDemo(): Promise<() => Promise> { process.exit(1); } if (!(await waitForEngine(15000))) { + printCapturedStartupStderr(); + printDockerStartupLogs(); p.log.error("iii-engine did not become ready within 15s."); process.exit(1); } } - await import("./index.js"); + await startWorkerForEngineState(); if (!(await waitForAgentmemoryReady(15000))) { p.log.error("agentmemory worker did not become ready within 15s."); process.exit(1); @@ -2300,7 +3008,7 @@ async function startServerForDemo(): Promise<() => Promise> { const port = getRestPort(); const state = readEngineState(); if (state?.kind === "docker") { - await stopDockerEngine(state.composeFile, port).catch(() => {}); + await stopDockerEngine(state, port).catch(() => {}); return; } const pids = new Set(findEnginePidsByPort(port)); @@ -2398,8 +3106,8 @@ async function runDemoBody(base: string) { ] : [ c.dim(`Note: "database performance optimization" found nothing —`), - c.dim(`semantic recall needs an embedding provider key (e.g.`), - c.dim(`OPENAI_API_KEY or GEMINI_API_KEY in ~/.agentmemory/.env).`), + c.dim(`set EMBEDDING_PROVIDER=local for on-device semantic recall,`), + c.dim(`or add an embedding API key in ~/.agentmemory/.env.`), ]), "", `Viewer: ${c.url(getViewerUrl())}`, @@ -2528,6 +3236,15 @@ async function runUpgrade() { function pidAlive(pid: number): boolean { try { process.kill(pid, 0); + if (!IS_WINDOWS) { + try { + const stat = execFileSync("ps", ["-p", String(pid), "-o", "stat="], { + encoding: "utf-8", + stdio: ["ignore", "pipe", "ignore"], + }); + if (stat.trim() && !processStatIsRunning(stat)) return false; + } catch {} + } return true; } catch (err) { return (err as NodeJS.ErrnoException)?.code === "EPERM"; @@ -2579,6 +3296,57 @@ async function stopWorkerPid(pid: number, graceMs: number): Promise { return ok; } +type NativeRemovalStopResult = + | { ok: true; stoppedEnginePids: number } + | { ok: false; reason: string }; + +async function stopNativeEngineForRemoval(): Promise { + const port = getRestPort(); + const workerPid = readWorkerPidfile(); + const enginePids = new Set(findEnginePidsByPort(port)); + const pidfilePid = readEnginePidfile(); + if (pidfilePid) enginePids.add(pidfilePid); + if (workerPid) enginePids.delete(workerPid); + + const foreign = [...enginePids] + .map((pid) => ({ pid, comm: pidCommand(pid) })) + .filter(({ comm }) => isForeignPortHolder(comm)); + if (foreign.length > 0) { + return { + ok: false, + reason: `refusing to signal non-iii process(es): ${foreign.map(({ pid, comm }) => `${pid} (${comm})`).join(", ")}`, + }; + } + + if (workerPid) { + if (!(await stopWorkerPid(workerPid, 5000))) { + return { + ok: false, + reason: `worker pid ${workerPid} could not be stopped; no engine or files were removed`, + }; + } + clearWorkerPidfile(); + } + + for (const pid of enginePids) { + const s = p.spinner(); + s.start(`Stopping iii-engine (pid ${pid})...`); + const ok = await signalAndWait(pid, "SIGTERM", 3000); + s.stop(ok ? `Stopped pid ${pid}` : `Failed to stop pid ${pid}`); + if (!ok) { + return { + ok: false, + reason: `engine pid ${pid} survived shutdown; lifecycle state and files were preserved`, + }; + } + } + + clearEnginePidfile(); + clearEngineState(); + clearWorkerPidfile(); + return { ok: true, stoppedEnginePids: enginePids.size }; +} + function pidCommand(pid: number): string { if (IS_WINDOWS) return ""; try { @@ -2627,73 +3395,113 @@ function findEnginePidsByPort(port: number): number[] { } } -async function stopDockerEngine(composeFile: string, port: number): Promise { +async function stopDockerEngine( + state: DockerEngineState, + port: number, + suppressOutro = false, +): Promise { const dockerBin = whichBinary("docker"); if (!dockerBin) { p.log.error( - `Engine was started via Docker compose, but \`docker\` is no longer on PATH. Stop it manually:\n docker compose -f ${composeFile} down`, + "Engine was started via Docker, but `docker` is no longer on PATH. Lifecycle state was preserved.", ); process.exit(1); } - if (!existsSync(composeFile)) { + + const inspection = inspectOwnedDockerEngine(state); + if (inspection.status === "unavailable") { p.log.error( - `Engine state references ${composeFile}, but the file is gone. Stop it manually:\n docker compose down (from the dir holding the original docker-compose.yml)`, + `The saved Docker engine cannot be verified: ${inspection.reason}. Refusing to stop or clear ownership state.`, ); process.exit(1); } + const resolvedState = persistDockerInspection(state, inspection); - // Reap the native worker first so its shutdown flush (BM25/vector - // snapshots via iii state::set) lands while the engine is still up — - // same ordering as the native stop path. Previously the worker pidfile - // was cleared without ever signaling the process, leaking a worker on - // every Docker-mode stop. const workerPid = readWorkerPidfile(); - let workerStopped = true; - if (workerPid) { - workerStopped = await stopWorkerPid(workerPid, 5000); + if (workerPid && !(await stopWorkerPid(workerPid, 5000))) { + p.log.error("The agentmemory worker could not be stopped; Docker ownership state was preserved."); + process.exit(1); } + clearWorkerPidfile(); - // Scope teardown to agentmemory's own services. A bare `down` against a - // user-owned compose file tears down every service in it. `rm -s -f` - // stops and removes only the named containers. - let composeText = ""; - try { - composeText = readFileSync(composeFile, "utf-8"); - } catch { - composeText = ""; + if (inspection.status === "running" || inspection.status === "stopped") { + if ( + inspection.status === "running" && + !runCommand( + dockerBin, + ["stop", "--time", "10", inspection.containerId], + { label: `Stopping preserved Docker container ${inspection.containerId}` }, + ) + ) { + p.log.error("The Docker container could not be stopped; ownership state was preserved."); + process.exit(1); + } + clearEnginePidfile(); + writeEngineState(resolvedState); + if (!suppressOutro) { + p.outro( + "Stopped. The validated Docker container and data mount were preserved for a lossless restart.", + ); + } + return; + } + + const projectName = inspection.projectName ?? resolvedState.projectName; + if (!projectName) { + p.log.error("No verified Docker Compose project name is available. Refusing an unscoped stop."); + process.exit(1); } - const ownServices = ["iii-engine", "iii-init"].filter((svc) => - new RegExp(`^\\s+${svc}:`, "m").test(composeText), + const effectiveComposeFile = existsSync(inspection.composeFile) + ? inspection.composeFile + : discoverComposeFile(); + if (!effectiveComposeFile) { + p.log.error("No agentmemory compose file is available. Docker ownership state was preserved."); + process.exit(1); + } + const composeText = readFileSync(effectiveComposeFile, "utf-8"); + const ownServices = ["iii-engine", "iii-init"].filter((service) => + new RegExp(`^\\s+${service}:`, "m").test(composeText), ); if (ownServices.length === 0) { - p.log.error( - `${composeFile} does not define the agentmemory services (iii-engine/iii-init). Refusing to run an unscoped \`docker compose down\` against it — that would tear down every service in the file.\n\nStop the engine service manually:\n docker compose -f ${composeFile} stop `, - ); + p.log.error(`${effectiveComposeFile} does not define iii-engine or iii-init. Refusing an unscoped stop.`); process.exit(1); } + + const composeCommand = [ + "docker", + ...dockerComposeArgs(effectiveComposeFile, projectName, []), + ].join(" "); + const ok = runCommand( dockerBin, - ["compose", "-f", composeFile, "rm", "-s", "-f", ...ownServices], + dockerComposeArgs(effectiveComposeFile, projectName, [ + "rm", + "-s", + "-f", + ...ownServices, + ]), { - label: `docker compose -f ${composeFile} rm -s -f ${ownServices.join(" ")}`, + label: `${composeCommand} rm -s -f ${ownServices.join(" ")}`, }, ); // Clear each piece of state only after its shutdown succeeded, so a // failed stop stays retryable. - if (workerStopped) clearWorkerPidfile(); if (ok) { clearEnginePidfile(); clearEngineState(); } else { p.log.error( - `docker compose rm failed. The engine may still be running on :${port}. Inspect with:\n docker compose -f ${composeFile} ps`, + `docker compose rm failed. The engine may still be running on :${port}. Inspect with:\n ${composeCommand} ps`, ); process.exit(1); } - p.outro("Stopped. Memories persisted to disk; restart anytime with: npx @agentmemory/agentmemory"); + if (!suppressOutro) { + p.outro("Stopped. Memories persisted to disk; restart anytime with: npx @agentmemory/agentmemory"); + } } async function runStop(): Promise { + await assertRuntimePortOwnership(); p.intro("agentmemory stop"); const port = getRestPort(); const state = readEngineState(); @@ -2703,13 +3511,8 @@ async function runStop(): Promise { if (state?.kind === "docker") { if (!running) { p.log.info(`No engine responding on port ${port}.`); - clearEnginePidfile(); - clearEngineState(); - clearWorkerPidfile(); - p.outro("Nothing to stop."); - return; } - await stopDockerEngine(state.composeFile, port); + await stopDockerEngine(state, port); return; } @@ -3071,18 +3874,53 @@ function safeDelete(path: string): { ok: boolean; message: string } { } async function runRemove(): Promise { + if (selectedInstance !== 0) { + p.intro("agentmemory remove"); + p.log.error( + `remove is a global uninstall and cannot target instance ${selectedInstance}. Stop that daemon with \`agentmemory stop --instance ${selectedInstance}\`, then run \`agentmemory remove\` without --instance when you intend to uninstall shared assets.`, + ); + process.exit(1); + } + await assertRuntimePortOwnership(); p.intro("agentmemory remove"); const force = args.includes("--force"); const keepData = args.includes("--keep-data"); + const ownedState = readEngineState(); + if (ownedState?.kind === "docker") { + const inspection = inspectOwnedDockerEngine(ownedState); + if (inspection.status === "running" || inspection.status === "stopped") { + persistDockerInspection(ownedState, inspection); + if (!keepData) { + p.log.error( + `Docker-backed removal requires --keep-data so the validated ${inspection.dataMountType} data mount (${inspection.dataMountSource}) and its recovery metadata remain usable. Re-run \`agentmemory remove --keep-data\`; destructive Docker data deletion is intentionally not automated.`, + ); + process.exit(1); + } + } else { + const detail = inspection.status === "unavailable" + ? inspection.reason + : "the owned container is missing"; + p.log.error( + `remove cannot safely reconcile the saved Docker ownership (${detail}). Lifecycle state was preserved for manual recovery.`, + ); + process.exit(1); + } + } const home = homedir(); const connectManifest = loadConnectManifest(home); const localBinIiiVersion = probeLocalBinIiiVersion(home); - const options: RemoveOptions = { force, keepData }; + const options: RemoveOptions = { + force, + keepData, + preserveRuntimeState: ownedState?.kind === "docker", + }; const plan = buildRemovePlan( { home, + runtimeDir: dirname(engineStatePath()), + dataDir: dataDirResolution.dataDir, pinnedVersion: IIPINNED_VERSION, localBinIiiVersion, connectManifest, @@ -3133,26 +3971,21 @@ async function runRemove(): Promise { } if (item.id === "stop-engine") { - try { - const port = getRestPort(); - const portPids = findEnginePidsByPort(port); - const pidfilePid = readEnginePidfile(); - const cands = new Set(); - if (pidfilePid) cands.add(pidfilePid); - for (const pid of portPids) cands.add(pid); - for (const pid of cands) await signalAndWait(pid, "SIGTERM", 3000); - clearEnginePidfile(); - clearEngineState(); - p.log.success( - cands.size > 0 - ? `stopped engine (${cands.size} pid${cands.size === 1 ? "" : "s"})` - : "no engine running", - ); - } catch (err) { - p.log.warn( - `engine stop best-effort: ${err instanceof Error ? err.message : String(err)}`, - ); + if (ownedState?.kind === "docker") { + await stopDockerEngine(ownedState, getRestPort(), true); + p.log.success("stopped Docker engine; container, data mount, and recovery state preserved"); + continue; } + const stopped = await stopNativeEngineForRemoval(); + if (!stopped.ok) { + p.log.error(`Removal aborted: ${stopped.reason}.`); + process.exit(1); + } + p.log.success( + stopped.stoppedEnginePids > 0 + ? `stopped engine (${stopped.stoppedEnginePids} pid${stopped.stoppedEnginePids === 1 ? "" : "s"})` + : "no engine running", + ); continue; } diff --git a/src/cli/engine-config.ts b/src/cli/engine-config.ts new file mode 100644 index 0000000000..e20484a790 --- /dev/null +++ b/src/cli/engine-config.ts @@ -0,0 +1,121 @@ +import { join } from "node:path"; + +export interface EngineConfigOptions { + dataDir: string; + ports?: EngineRuntimePorts; +} + +export interface EngineRuntimePorts { + restPort: number; + streamPort: number; + viewerPort: number; + enginePort: number; +} + +function yamlSingleQuote(value: string): string { + return `'${value.replace(/'/g, "''")}'`; +} + +function workerBlock( + lines: string[], + name: string, +): { start: number; end: number; indent: string } | null { + const marker = `- name: ${name}`; + const start = lines.findIndex((line) => line.trim() === marker); + if (start === -1) return null; + const indent = lines[start]!.match(/^\s*/)?.[0] ?? ""; + let end = lines.length; + for (let i = start + 1; i < lines.length; i++) { + const line = lines[i]!; + if (line.startsWith(indent) && line.trim().startsWith("- name: ")) { + end = i; + break; + } + } + return { start, end, indent }; +} + +function setWorkerPort(lines: string[], name: string, port: number): void { + let block = workerBlock(lines, name); + if (!block && name === "iii-worker-manager") { + const workersIndex = lines.findIndex((line) => line.trim() === "workers:"); + if (workersIndex === -1) return; + lines.splice( + workersIndex + 1, + 0, + " - name: iii-worker-manager", + " config:", + ` port: ${port}`, + " host: 127.0.0.1", + ); + return; + } + if (!block) return; + + const portIndex = lines.findIndex( + (line, index) => + index > block!.start && + index < block!.end && + line.trim().startsWith("port:"), + ); + if (portIndex !== -1) { + const indent = lines[portIndex]!.match(/^\s*/)?.[0] ?? `${block.indent} `; + lines[portIndex] = `${indent}port: ${port}`; + return; + } + + const configIndex = lines.findIndex( + (line, index) => + index > block!.start && index < block!.end && line.trim() === "config:", + ); + if (configIndex !== -1) { + const configIndent = lines[configIndex]!.match(/^\s*/)?.[0] ?? `${block.indent} `; + lines.splice(configIndex + 1, 0, `${configIndent} port: ${port}`); + } +} + +function setManagedCorsOrigins( + lines: string[], + restPort: number, + viewerPort: number, +): void { + const block = workerBlock(lines, "iii-http"); + if (!block) return; + const originsIndex = lines.findIndex( + (line, index) => + index > block.start && + index < block.end && + line.trim().startsWith("allowed_origins:"), + ); + if (originsIndex === -1) return; + const indent = lines[originsIndex]!.match(/^\s*/)?.[0] ?? " "; + lines[originsIndex] = + `${indent}allowed_origins: [` + + `"http://localhost:${restPort}", ` + + `"http://localhost:${viewerPort}", ` + + `"http://127.0.0.1:${restPort}", ` + + `"http://127.0.0.1:${viewerPort}"]`; +} + +export function renderEngineConfig( + template: string, + options: EngineConfigOptions, +): string { + const rendered = template + .replace( + "file_path: ./data/state_store.db", + `file_path: ${yamlSingleQuote(join(options.dataDir, "state_store.db"))}`, + ) + .replace( + "file_path: ./data/stream_store", + `file_path: ${yamlSingleQuote(join(options.dataDir, "stream_store"))}`, + ); + if (!options.ports) return rendered; + + const lines = rendered.split("\n"); + setWorkerPort(lines, "iii-http", options.ports.restPort); + setWorkerPort(lines, "iii-stream", options.ports.streamPort); + setWorkerPort(lines, "iii-worker-manager", options.ports.enginePort); + setManagedCorsOrigins(lines, options.ports.restPort, options.ports.viewerPort); + return lines.join("\n"); +} diff --git a/src/cli/engine-launch.ts b/src/cli/engine-launch.ts new file mode 100644 index 0000000000..b162e7f5c5 --- /dev/null +++ b/src/cli/engine-launch.ts @@ -0,0 +1,189 @@ +import { dirname, isAbsolute, join, resolve } from "node:path"; +import { + renderEngineConfig, + type EngineConfigOptions, +} from "./engine-config.js"; + +export function agentmemoryHome(home: string): string { + return join(home, ".agentmemory"); +} + +export function runtimeConfigPath(dataDir: string): string { + return join(dataDir, "iii-config.runtime.yaml"); +} + +export function dockerProjectName(restPort: number): string { + return `agentmemory-${restPort}`; +} + +export function dockerComposeArgs( + composeFile: string, + projectName: string | undefined, + command: string[], +): string[] { + return [ + "compose", + ...(projectName ? ["-p", projectName] : []), + "-f", + composeFile, + ...command, + ]; +} + +export function isBundledConfig(configPath: string, packageDir: string): boolean { + const resolved = resolve(configPath); + return ( + resolved === resolve(join(packageDir, "iii-config.yaml")) || + resolved === resolve(join(packageDir, "..", "iii-config.yaml")) + ); +} + +export function resolveEngineCwd( + configPath: string, + invocationCwd: string, + home: string, + bundledConfig = false, +): string { + if (bundledConfig) return agentmemoryHome(home); + const absoluteConfigPath = isAbsolute(configPath) + ? configPath + : resolve(invocationCwd, configPath); + return dirname(absoluteConfigPath); +} + +function indentation(line: string): number { + return line.length - line.trimStart().length; +} + +function yamlScalar(value: string): string { + const trimmed = value.trim(); + const first = trimmed[0]; + const last = trimmed.at(-1); + if ((first === '"' && last === '"') || (first === "'" && last === "'")) { + return trimmed.slice(1, -1); + } + return trimmed; +} + +function isAgentmemoryExecCommand( + line: string, + nodeBin: string, + workerEntry: string, +): boolean { + const match = line.match(/^\s*-\s+(.+?)\s*$/); + if (!match) return false; + const command = yamlScalar(match[1]!).replaceAll("\\", "/"); + const explicitCommand = `${nodeBin} ${workerEntry}`.replaceAll("\\", "/"); + return ( + command === explicitCommand || + /^(?:node|node\.exe)\s+\.\/dist\/index\.mjs$/.test(command) || + /^(?:node|node\.exe)\s+dist\/index\.mjs$/.test(command) + ); +} + +function removeAgentmemoryExecCommand( + raw: string, + nodeBin: string, + workerEntry: string, +): string { + const lines = raw.split("\n"); + const output: string[] = []; + let index = 0; + + while (index < lines.length) { + const line = lines[index]!; + if (line.trim() !== "- name: iii-exec") { + output.push(line); + index++; + continue; + } + + const blockIndent = indentation(line); + let blockEnd = index + 1; + while (blockEnd < lines.length) { + const candidate = lines[blockEnd]!; + if (candidate.trim() !== "") { + const candidateIndent = indentation(candidate); + if ( + candidateIndent < blockIndent || + (candidateIndent === blockIndent && candidate.trim().startsWith("- name: ")) + ) { + break; + } + } + blockEnd++; + } + + const block = lines.slice(index, blockEnd); + const execIndex = block.findIndex((candidate) => candidate.trim() === "exec:"); + if (execIndex === -1) { + output.push(...block); + index = blockEnd; + continue; + } + + const execIndent = indentation(block[execIndex]!); + let execEnd = execIndex + 1; + while (execEnd < block.length) { + const candidate = block[execEnd]!; + if (candidate.trim() !== "" && indentation(candidate) <= execIndent) break; + execEnd++; + } + + const beforeExec = block.slice(0, execIndex + 1); + const execLines = block.slice(execIndex + 1, execEnd); + const afterExec = block.slice(execEnd); + const remainingExecLines = execLines.filter( + (candidate) => !isAgentmemoryExecCommand(candidate, nodeBin, workerEntry), + ); + const removed = remainingExecLines.length !== execLines.length; + const hasExecCommand = remainingExecLines.some( + (candidate) => /^\s*-\s+/.test(candidate) && indentation(candidate) > execIndent, + ); + + if (!removed) { + output.push(...block); + } else if (hasExecCommand) { + output.push(...beforeExec, ...remainingExecLines, ...afterExec); + } + index = blockEnd; + } + + return output.join("\n"); +} + +export function rewriteBundledConfig( + raw: string, + home: string, + nodeBin: string, + workerEntry: string, + options?: EngineConfigOptions, +): string { + const rendered = renderEngineConfig(raw, { + dataDir: options?.dataDir ?? join(agentmemoryHome(home), "data"), + ...(options?.ports ? { ports: options.ports } : {}), + }); + return removeAgentmemoryExecCommand(rendered, nodeBin, workerEntry); +} + +export interface DataMigration { + from: string; + to: string; +} + +export function legacyDataMigrations( + invocationCwd: string, + home: string, + resolvedDataDir = join(agentmemoryHome(home), "data"), +): DataMigration[] { + return [ + { + from: join(invocationCwd, "data", "state_store.db"), + to: join(resolvedDataDir, "state_store.db"), + }, + { + from: join(invocationCwd, "data", "stream_store"), + to: join(resolvedDataDir, "stream_store"), + }, + ]; +} diff --git a/src/cli/process-state.ts b/src/cli/process-state.ts new file mode 100644 index 0000000000..41badf9f57 --- /dev/null +++ b/src/cli/process-state.ts @@ -0,0 +1,3 @@ +export function processStatIsRunning(stat: string): boolean { + return !stat.trimStart().startsWith("Z"); +} diff --git a/src/cli/remove-plan.ts b/src/cli/remove-plan.ts index fbc64de1be..662e378352 100644 --- a/src/cli/remove-plan.ts +++ b/src/cli/remove-plan.ts @@ -13,6 +13,7 @@ import { existsSync, statSync } from "node:fs"; import { join } from "node:path"; +import { runtimeConfigPath } from "./engine-launch.js"; export type RemovePlanItem = { /** Stable id, used in tests and CLI output. */ @@ -34,11 +35,17 @@ export type RemoveOptions = { force: boolean; /** Keep ~/.agentmemory/* user data; only remove binaries/symlinks. */ keepData: boolean; + /** Keep engine ownership metadata needed to recover retained Docker data. */ + preserveRuntimeState?: boolean; }; export type RemoveContext = { /** $HOME (so tests can sandbox). */ home: string; + /** Resolved directory containing pidfiles and engine ownership state. */ + runtimeDir: string; + /** Resolved iii-engine data directory selected for this invocation. */ + dataDir: string; /** Pinned engine version we expect ~/.local/bin/iii to match. */ pinnedVersion: string; /** @@ -66,12 +73,16 @@ export type ConnectManifest = { }>; }; -export function pidfilePath(home: string): string { - return join(home, ".agentmemory", "iii.pid"); +export function pidfilePath(runtimeDir: string): string { + return join(runtimeDir, "iii.pid"); } -export function enginePath(home: string): string { - return join(home, ".agentmemory", "engine-state.json"); +export function workerPidfilePath(runtimeDir: string): string { + return join(runtimeDir, "worker.pid"); +} + +export function enginePath(runtimeDir: string): string { + return join(runtimeDir, "engine-state.json"); } export function envPath(home: string): string { @@ -86,10 +97,6 @@ export function backupsDir(home: string): string { return join(home, ".agentmemory", "backups"); } -export function dataDir(home: string): string { - return join(home, ".agentmemory", "data"); -} - // Platform-aware binary name. Windows requires the .exe suffix or the // existsSync probe misses the installed binary. function iiiBinFile(): string { @@ -138,7 +145,14 @@ export function buildRemovePlan( ctx: RemoveContext, options: RemoveOptions, ): RemovePlanItem[] { - const { home, pinnedVersion, localBinIiiVersion, connectManifest } = ctx; + const { + home, + runtimeDir, + dataDir, + pinnedVersion, + localBinIiiVersion, + connectManifest, + } = ctx; const plan: RemovePlanItem[] = []; plan.push({ @@ -146,26 +160,39 @@ export function buildRemovePlan( description: "Stop running iii-engine (if any) cleanly", path: null, alwaysAsk: false, - applicable: pathExists(pidfilePath(home)) || pathExists(enginePath(home)), + applicable: + pathExists(pidfilePath(runtimeDir)) || + pathExists(workerPidfilePath(runtimeDir)) || + pathExists(enginePath(runtimeDir)), sizeBytes: -1, }); plan.push({ id: "pidfile", description: "Delete pidfile", - path: pidfilePath(home), + path: pidfilePath(runtimeDir), + alwaysAsk: false, + applicable: pathExists(pidfilePath(runtimeDir)), + sizeBytes: safeSize(pidfilePath(runtimeDir)), + }); + + plan.push({ + id: "worker-pidfile", + description: "Delete worker pidfile", + path: workerPidfilePath(runtimeDir), alwaysAsk: false, - applicable: pathExists(pidfilePath(home)), - sizeBytes: safeSize(pidfilePath(home)), + applicable: pathExists(workerPidfilePath(runtimeDir)), + sizeBytes: safeSize(workerPidfilePath(runtimeDir)), }); plan.push({ id: "engine-state", description: "Delete engine-state.json", - path: enginePath(home), + path: enginePath(runtimeDir), alwaysAsk: false, - applicable: pathExists(enginePath(home)), - sizeBytes: safeSize(enginePath(home)), + applicable: + !options.preserveRuntimeState && pathExists(enginePath(runtimeDir)), + sizeBytes: safeSize(enginePath(runtimeDir)), }); // .env holds the user's API keys. Always ask before deleting, even on @@ -197,6 +224,15 @@ export function buildRemovePlan( sizeBytes: -1, }); + plan.push({ + id: "runtime-config", + description: "Delete generated iii-config.runtime.yaml", + path: runtimeConfigPath(dataDir), + alwaysAsk: false, + applicable: pathExists(runtimeConfigPath(dataDir)), + sizeBytes: safeSize(runtimeConfigPath(dataDir)), + }); + // Iterate over connect-installed agent symlinks. We always honor these // (even with --keep-data, since they're outside ~/.agentmemory/). if (connectManifest?.installed?.length) { @@ -252,11 +288,10 @@ export function buildRemovePlan( // behavior is keep. plan.push({ id: "data-dir", - description: - "Delete memory data directory (~/.agentmemory/data/) — will ask separately", - path: dataDir(home), + description: `Delete memory data directory (${dataDir}) — will ask separately`, + path: dataDir, alwaysAsk: true, - applicable: !options.keepData && pathExists(dataDir(home)), + applicable: !options.keepData && pathExists(dataDir), sizeBytes: -1, }); diff --git a/src/cli/startup-stderr.ts b/src/cli/startup-stderr.ts new file mode 100644 index 0000000000..d240dfd23f --- /dev/null +++ b/src/cli/startup-stderr.ts @@ -0,0 +1,23 @@ +export interface StartupStderrCapture { + append(chunk: Buffer): void; + text(): string; +} + +export function createStartupStderrCapture( + maxBytes = 16 * 1024, +): StartupStderrCapture { + const chunks: Buffer[] = []; + let capturedBytes = 0; + + return { + append(chunk: Buffer): void { + if (capturedBytes >= maxBytes) return; + const slice = chunk.subarray(0, maxBytes - capturedBytes); + chunks.push(slice); + capturedBytes += slice.length; + }, + text(): string { + return Buffer.concat(chunks).toString("utf8"); + }, + }; +} diff --git a/src/config.ts b/src/config.ts index 426ca20c92..a6c62ce55e 100644 --- a/src/config.ts +++ b/src/config.ts @@ -160,7 +160,8 @@ function detectProvider(env: Record): ProviderConfig { if (!allowAgentSdk) { process.stderr.write( pc.dim( - "[agentmemory] No LLM provider key set — running zero-LLM (BM25 + on-device embeddings). " + + "[agentmemory] No LLM provider key set — running zero-LLM with BM25 search. " + + "Set EMBEDDING_PROVIDER=local for on-device semantic embeddings. " + "Set ANTHROPIC_API_KEY (or GEMINI/OPENAI/OPENROUTER/MINIMAX) in ~/.agentmemory/.env for LLM compression and summaries. " + "Agent-SDK fallback stays off by default to avoid a Stop-hook recursion loop; opt in with AGENTMEMORY_AUTO_COMPRESS=true + AGENTMEMORY_ALLOW_AGENT_SDK=true.\n", ), @@ -198,6 +199,8 @@ export function loadConfig(): AgentMemoryConfig { const streamsPort = parseInt(env["III_STREAM_PORT"] || env["III_STREAMS_PORT"] || "", 10) || restPort + 1; + const viewerPort = + parseInt(env["III_VIEWER_PORT"] || "", 10) || restPort + 2; const engineUrl = env["III_ENGINE_URL"] || `ws://localhost:${ @@ -208,6 +211,7 @@ export function loadConfig(): AgentMemoryConfig { engineUrl, restPort, streamsPort, + viewerPort, provider, tokenBudget: safeParseInt(env["TOKEN_BUDGET"], 2000), maxObservationsPerSession: safeParseInt(env["MAX_OBS_PER_SESSION"], 500), diff --git a/src/index.ts b/src/index.ts index 26e5a6343e..717419f7df 100644 --- a/src/index.ts +++ b/src/index.ts @@ -102,18 +102,12 @@ import { registerHealthMonitor } from "./health/monitor.js"; import { initMetrics, OTEL_CONFIG } from "./telemetry/setup.js"; import { VERSION } from "./version.js"; import { bootLog } from "./logger.js"; +import { runtimeMetadataPath } from "./runtime-paths.js"; import { mkdirSync, writeFileSync, unlinkSync } from "node:fs"; -import { dirname, join } from "node:path"; -import { homedir } from "node:os"; - -// #640 + #474: the worker process (this file) is spawned by iii-exec -// inside the engine. When `agentmemory stop` kills only the engine pid, -// this worker can survive (detached spawn, signal not propagated, or a -// wrapper script keeps it running) and reconnects to the next engine as -// a duplicate worker. Write the worker pid alongside iii.pid so -// `agentmemory stop` can reap us too. +import { dirname } from "node:path"; + function workerPidfilePath(): string { - return join(homedir(), ".agentmemory", "worker.pid"); + return runtimeMetadataPath("worker.pid"); } function writeWorkerPidfile(): void { try { @@ -548,9 +542,8 @@ async function main() { `MCP surface (opt-in via \`npx @agentmemory/mcp\`): ${getAllTools().length} tools · 6 resources · 3 prompts`, ); - const viewerPort = config.restPort + 2; const viewerServer = startViewerServer( - viewerPort, + config.viewerPort, kv, sdk, secret, diff --git a/src/runtime-paths.ts b/src/runtime-paths.ts new file mode 100644 index 0000000000..9bea8e7f0e --- /dev/null +++ b/src/runtime-paths.ts @@ -0,0 +1,19 @@ +import { homedir } from "node:os"; +import { join, resolve } from "node:path"; + +interface RuntimeMetadataPathOptions { + env?: NodeJS.ProcessEnv; + home?: string; +} + +export function runtimeMetadataPath( + name: string, + options: RuntimeMetadataPathOptions = {}, +): string { + const env = options.env ?? process.env; + const home = options.home ?? homedir(); + const baseDir = env["AGENTMEMORY_RUNTIME_DIR"] + ? resolve(env["AGENTMEMORY_RUNTIME_DIR"]) + : join(home, ".agentmemory"); + return join(baseDir, name); +} diff --git a/src/types.ts b/src/types.ts index 1118b3f999..d2c63efa61 100644 --- a/src/types.ts +++ b/src/types.ts @@ -180,6 +180,7 @@ export interface AgentMemoryConfig { engineUrl: string; restPort: number; streamsPort: number; + viewerPort: number; provider: ProviderConfig; tokenBudget: number; maxObservationsPerSession: number; diff --git a/test/cli-data-dir.test.ts b/test/cli-data-dir.test.ts index faf453676f..d4058645a7 100644 --- a/test/cli-data-dir.test.ts +++ b/test/cli-data-dir.test.ts @@ -73,6 +73,21 @@ describe("resolveDataDir", () => { }); }); + it("accepts both instance flag forms", () => { + const options = { + env: {}, + cwd: "/repo/project", + home: "/home/alex", + platform: "linux" as const, + }; + expect(resolveDataDir({ ...options, args: ["--instance", "2"] })).toEqual( + resolveDataDir({ ...options, args: ["--instance=2"] }), + ); + expect(resolveDataDir({ ...options, args: ["--instance=2"] }).dataDir).toBe( + join("/home/alex", ".local", "share", "agentmemory", "instance-2"), + ); + }); + it("adopts legacy data without sharing it with another instance", () => { const cwd = mkdtempSync(join(tmpdir(), "agentmemory-data-")); mkdirSync(join(cwd, ".git")); diff --git a/test/cli-engine-startup.test.ts b/test/cli-engine-startup.test.ts new file mode 100644 index 0000000000..ceaeeacbe6 --- /dev/null +++ b/test/cli-engine-startup.test.ts @@ -0,0 +1,149 @@ +import { readFileSync } from "node:fs"; +import { describe, expect, it } from "vitest"; + +describe("fresh native engine startup", () => { + const source = readFileSync("src/cli.ts", "utf8"); + + it("routes existing and newly installed engines through one runtime config", () => { + const prepareStart = source.indexOf("function prepareEngineLaunch"); + const prepareEnd = source.indexOf("function startIiiBin", prepareStart); + const prepareBody = source.slice(prepareStart, prepareEnd); + expect(prepareBody).toContain("dataDir: dataDirResolution.dataDir"); + expect(prepareBody).toContain("restPort: getRestPort()"); + expect(prepareBody).toContain("streamPort: getStreamPort()"); + expect(prepareBody).toContain("viewerPort: getConfiguredViewerPort()"); + expect(prepareBody).toContain("enginePort: getEnginePort()"); + + const engineStart = source.indexOf("async function startEngine"); + const engineEnd = source.indexOf("async function waitForEngine", engineStart); + const engineBody = source.slice(engineStart, engineEnd); + expect(engineBody).not.toContain("writeRuntimeIiiConfig"); + expect(engineBody.match(/startIiiBin\(iiiBin, configPath\)/g)).toHaveLength(2); + }); + + it("reports buffered engine stderr when a verbose startup times out", () => { + const spawnStart = source.indexOf("function spawnEngineBackground"); + const spawnEnd = source.indexOf("function prepareEngineLaunch", spawnStart); + const spawnBody = source.slice(spawnStart, spawnEnd); + expect(spawnBody).toContain( + "activeStartupStderr = createStartupStderrCapture()", + ); + expect(spawnBody).toContain("activeStartupStderr.append(chunk)"); + + const timeoutStart = source.indexOf("const ready = await waitForEngine(15000)"); + const timeoutEnd = source.indexOf('s.stop(c.ok("iii-engine is ready"))', timeoutStart); + expect(source.slice(timeoutStart, timeoutEnd)).toContain( + "printCapturedStartupStderr()", + ); + + const demoTimeoutStart = source.indexOf("await waitForEngine(15000)", timeoutEnd); + const demoTimeoutEnd = source.indexOf("await import(\"./index.js\")", demoTimeoutStart); + expect(source.slice(demoTimeoutStart, demoTimeoutEnd)).toContain( + "printCapturedStartupStderr()", + ); + }); + + it("exports the complete derived port set for Docker and native launchers", () => { + expect(source).toContain( + 'process.env["III_STREAM_PORT"] ??=\n process.env["III_STREAMS_PORT"] ?? String(restPort + 1)', + ); + expect(source).toContain( + 'process.env["III_VIEWER_PORT"] ??= String(restPort + 2)', + ); + expect(source).toContain( + 'process.env["III_ENGINE_PORT"] ??= String(restPort + 46023)', + ); + expect(source).toContain("new URL(configuredEngineUrl).port"); + expect(source).toContain( + 'process.env["III_ENGINE_PORT"] = parsedEnginePort', + ); + expect(source).toContain( + 'process.env["AGENTMEMORY_METRICS_PORT"] ??= String(restPort + 6353)', + ); + expect(source).toContain( + 'process.env["AGENTMEMORY_DATA_DIR"] = dataDirResolution.dataDir', + ); + }); + + it("checks every Unix engine installer prerequisite before downloading", () => { + const installerStart = source.indexOf("async function runIiiInstaller"); + const installerEnd = source.indexOf("type StartupFailure", installerStart); + const installerBody = source.slice(installerStart, installerEnd); + expect(installerBody).toContain('whichBinary("sh")'); + expect(installerBody).toContain('whichBinary("curl")'); + expect(installerBody).toContain('whichBinary("tar")'); + }); + + it("lets the CLI own one bundled worker and reuses a live worker", () => { + const prepareStart = source.indexOf("function prepareEngineLaunch"); + const prepareEnd = source.indexOf("function startIiiBin", prepareStart); + const prepareBody = source.slice(prepareStart, prepareEnd); + expect(prepareBody).toContain( + "rewriteBundledConfig(", + ); + expect(prepareBody).toContain(": renderEngineConfig(rawConfig, options)"); + + const workerStart = source.indexOf("async function startWorkerForEngineState"); + const workerEnd = source.indexOf("async function startEngine", workerStart); + const workerBody = source.slice(workerStart, workerEnd); + expect(workerBody).toContain("readWorkerPidfile()"); + expect(workerBody).toContain("pidAlive(workerPid)"); + expect(workerBody).toContain("waitForConfiguredWorker"); + expect(workerBody).toContain('await import("./index.js")'); + + expect(source.match(/await startWorkerForEngineState\(\)/g)).toHaveLength(4); + expect(source).toContain("agentmemory worker did not become ready within 15s"); + }); + + it("stores lifecycle metadata per resolved instance and scopes Docker", () => { + expect(source).toContain('runtimeMetadataPath("iii.pid")'); + expect(source).toContain('runtimeMetadataPath("engine-state.json")'); + expect(source).toContain('runtimeMetadataPath("worker.pid")'); + expect(source).toContain('process.env["AGENTMEMORY_RUNTIME_DIR"] = selectedInstance > 0'); + expect(source).toContain("dockerProjectName(getRestPort())"); + expect(source).toContain("dockerComposeArgs("); + }); + + it("keeps AGENTMEMORY_URL client-only and lets local port flags win", () => { + expect(source).toContain('const URL_CLIENT_COMMANDS = new Set(["status", "doctor", "mcp"])'); + expect(source).toContain("hasExplicitLocalPortOverride"); + expect(source).toContain("shouldUseAgentmemoryUrl()"); + expect(source).toContain('process.env["III_REST_PORT"] = String(base)'); + }); + + it("recovers the host worker for a validated Docker engine", () => { + expect(source).toContain("function inspectOwnedDockerEngine"); + expect(source).toMatch(/"ps",\s*"-q",\s*"--all",\s*"iii-engine"/); + expect(source).toContain('"com.docker.compose.service"'); + expect(source).toContain('record.HostConfig?.PortBindings'); + expect(source).toContain('mount.Destination === "/data"'); + expect(source).toContain('["start", inspection.containerId]'); + expect(source).toContain('["stop", "--time", "10", inspection.containerId]'); + + const mainStart = source.indexOf("async function main()"); + const mainEnd = source.indexOf("async function apiFetch", mainStart); + const mainBody = source.slice(mainStart, mainEnd); + expect(mainBody).toContain("reconcilePersistedDockerEngine()"); + expect(mainBody.indexOf("reconcilePersistedDockerEngine()")) + .toBeLessThan(mainBody.indexOf("if (await isEngineRunning())")); + }); + + it("keeps canonical compatibility and rejects Docker ownership on another port", () => { + expect(source).toContain('function cliArgValue(name: string)'); + expect(source).toContain('arg.startsWith(`${name}=`)'); + expect(source).toContain("async function assertRuntimePortOwnership"); + expect(source).toContain("restPort: getRestPort()"); + expect(source).toContain('inspection.status === "running" || inspection.status === "stopped"'); + expect(source).not.toContain("migrateLegacyRuntimeMetadata"); + expect(source).not.toContain("clearLegacyRuntimeMetadata"); + }); + + it("preserves Docker ownership when compose startup fails", () => { + const spawnStart = source.indexOf("function spawnEngineBackground"); + const spawnEnd = source.indexOf("function prepareEngineLaunch", spawnStart); + const spawnBody = source.slice(spawnStart, spawnEnd); + expect(spawnBody).toContain("if (!isDocker)"); + expect(spawnBody).toContain("clearEngineState()"); + expect(spawnBody).not.toContain("if (!isDocker) clearEnginePidfile();\n clearEngineState();"); + }); +}); diff --git a/test/cli-lifecycle-safety.test.ts b/test/cli-lifecycle-safety.test.ts new file mode 100644 index 0000000000..7d19949267 --- /dev/null +++ b/test/cli-lifecycle-safety.test.ts @@ -0,0 +1,356 @@ +import { spawnSync } from "node:child_process"; +import { + chmodSync, + existsSync, + mkdtempSync, + mkdirSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; + +const sandboxes: string[] = []; +const FULL_CONTAINER_ID = + "a348133fe52fc5ba49b74cb0a4e36a1ec1d64827d79dc120940a96054bbe87c4"; + +function sandbox(): string { + const path = mkdtempSync(join(tmpdir(), "agentmemory-lifecycle-")); + sandboxes.push(path); + return path; +} + +function installFakeDocker(binDir: string): void { + mkdirSync(binDir, { recursive: true }); + const dockerPath = join(binDir, "docker"); + writeFileSync( + dockerPath, + `#!/usr/bin/env node +const { appendFileSync } = require("node:fs"); +const args = process.argv.slice(2); +appendFileSync(process.env.DOCKER_LOG, args.join(" ") + "\\n"); +const isComposePs = args[0] === "compose" && args.includes("ps"); +const isGlobalPs = args[0] === "ps"; +if (process.env.DOCKER_FAILURE_MODE === "scan" && (isComposePs || isGlobalPs)) { + process.exit(1); +} +if (isComposePs || isGlobalPs) { + if (process.env.DOCKER_FAILURE_MODE === "duplicate") { + process.stdout.write((isComposePs ? process.env.FULL_CONTAINER_ID.slice(0, 12) : process.env.FULL_CONTAINER_ID) + "\\n"); + } else { + process.stdout.write("candidate-id\\n"); + } + process.exit(0); +} +if (args[0] === "inspect") { + if (process.env.DOCKER_FAILURE_MODE === "duplicate") { + process.stdout.write(JSON.stringify([{ + Id: process.env.FULL_CONTAINER_ID, + State: { Running: false }, + Config: { + Image: "iiidev/iii:0.11.2", + Labels: { + "com.docker.compose.project": "agentmemory-3111", + "com.docker.compose.service": "iii-engine" + } + }, + HostConfig: { PortBindings: { "3111/tcp": [{ HostPort: "3111" }] } }, + Mounts: [{ Type: "bind", Source: process.env.DOCKER_DATA_DIR, Destination: "/data" }] + }])); + process.exit(0); + } + process.exit(1); +} +process.exit(0); +`, + ); + chmodSync(dockerPath, 0o755); +} + +function runDockerStop( + failureMode: "scan" | "inspect" | "duplicate", + command: "stop" | "remove" = "stop", +) { + const root = sandbox(); + const home = join(root, "home"); + const runtimeDir = join(home, ".agentmemory"); + const dataDir = join(root, "data"); + const binDir = join(root, "bin"); + const composeFile = join(root, "docker-compose.yml"); + const dockerLog = join(root, "docker.log"); + const privateBin = join(runtimeDir, "bin", "iii"); + mkdirSync(runtimeDir, { recursive: true }); + mkdirSync(dataDir, { recursive: true }); + if (command === "remove") { + mkdirSync(join(runtimeDir, "bin"), { recursive: true }); + writeFileSync(privateBin, "owned binary"); + } + installFakeDocker(binDir); + writeFileSync( + composeFile, + "services:\n iii-engine:\n image: iiidev/iii:0.11.2\n iii-init:\n image: busybox\n", + ); + const statePath = join(runtimeDir, "engine-state.json"); + writeFileSync( + statePath, + JSON.stringify({ + kind: "docker", + schemaVersion: 2, + composeFile, + projectName: "agentmemory-3111", + engineVersion: "0.11.2", + restPort: 3111, + dataDir, + ...(failureMode === "inspect" ? { containerId: "candidate-id" } : {}), + dataMountType: "bind", + dataMountSource: dataDir, + preserveContainer: false, + }), + ); + + const result = spawnSync( + process.execPath, + [ + "--import", + "tsx", + "src/cli.ts", + command, + ...(command === "remove" ? ["--force", "--keep-data"] : []), + "--data-dir", + dataDir, + ], + { + cwd: process.cwd(), + encoding: "utf-8", + env: { + ...process.env, + HOME: home, + USERPROFILE: home, + CI: "1", + PATH: `${binDir}:${process.env.PATH ?? ""}`, + DOCKER_LOG: dockerLog, + DOCKER_FAILURE_MODE: failureMode, + DOCKER_DATA_DIR: dataDir, + FULL_CONTAINER_ID, + }, + }, + ); + + return { + result, + statePath, + privateBin, + dockerLog: existsSync(dockerLog) ? readFileSync(dockerLog, "utf-8") : "", + }; +} + +function runInstanceRemove(instanceArgs = ["--instance", "1"]) { + const root = sandbox(); + const home = join(root, "home"); + const privateBin = join(home, ".agentmemory", "bin", "iii"); + const dataBase = join(root, "data"); + mkdirSync(join(home, ".agentmemory", "bin"), { recursive: true }); + writeFileSync(privateBin, "shared binary"); + + const result = spawnSync( + process.execPath, + [ + "--import", + "tsx", + "src/cli.ts", + "remove", + ...instanceArgs, + "--data-dir", + dataBase, + "--force", + "--keep-data", + ], + { + cwd: process.cwd(), + encoding: "utf-8", + env: { + ...process.env, + HOME: home, + USERPROFILE: home, + CI: "1", + }, + }, + ); + return { result, privateBin }; +} + +function runNativeRemoveWithWorkerFailure() { + const root = sandbox(); + const home = join(root, "home"); + const runtimeDir = join(home, ".agentmemory"); + const privateBin = join(runtimeDir, "bin", "iii"); + const engineState = join(runtimeDir, "engine-state.json"); + const enginePidfile = join(runtimeDir, "iii.pid"); + const workerPidfile = join(runtimeDir, "worker.pid"); + const killLog = join(root, "kill.log"); + const preload = join(root, "deny-worker-signal.mjs"); + mkdirSync(join(runtimeDir, "bin"), { recursive: true }); + writeFileSync(privateBin, "owned binary"); + writeFileSync(enginePidfile, "424243\n"); + writeFileSync(workerPidfile, "424242\n"); + writeFileSync( + engineState, + JSON.stringify({ + kind: "native", + configPath: join(root, "iii-config.runtime.yaml"), + restPort: 3111, + }), + ); + writeFileSync( + preload, + `import { appendFileSync } from "node:fs"; +const originalKill = process.kill.bind(process); +process.kill = (pid, signal) => { + if (pid === 424242 || pid === 424243) { + appendFileSync(process.env.KILL_LOG, String(pid) + ":" + String(signal) + "\\n"); + const error = new Error(pid === 424242 ? "worker denied" : "engine missing"); + error.code = pid === 424242 ? "EPERM" : "ESRCH"; + throw error; + } + return originalKill(pid, signal); +}; +`, + ); + + const result = spawnSync( + process.execPath, + [ + "--import", + preload, + "--import", + "tsx", + "src/cli.ts", + "remove", + "--force", + "--keep-data", + ], + { + cwd: process.cwd(), + encoding: "utf-8", + env: { + ...process.env, + HOME: home, + USERPROFILE: home, + CI: "1", + KILL_LOG: killLog, + }, + }, + ); + + return { + result, + privateBin, + engineState, + enginePidfile, + workerPidfile, + killLog: existsSync(killLog) ? readFileSync(killLog, "utf-8") : "", + }; +} + +afterEach(() => { + for (const path of sandboxes.splice(0)) { + rmSync(path, { recursive: true, force: true }); + } +}); + +describe("Docker lifecycle discovery", () => { + it.each(["scan", "inspect"] as const)( + "preserves ownership and performs no cleanup when Docker %s fails", + (failureMode) => { + const { result, statePath, dockerLog } = runDockerStop(failureMode); + + expect(result.status).toBe(1); + expect(existsSync(statePath)).toBe(true); + expect(dockerLog).not.toMatch(/\bcompose\b.*\brm\b/); + expect(`${result.stdout}\n${result.stderr}`).toContain("cannot be verified"); + }, + ); + + it("deduplicates short and full IDs for the same inspected container", () => { + const { result, statePath, dockerLog } = runDockerStop("duplicate"); + + expect(result.status).toBe(0); + expect(existsSync(statePath)).toBe(true); + expect(dockerLog).not.toMatch(/\bcompose\b.*\brm\b/); + expect(JSON.parse(readFileSync(statePath, "utf-8")).containerId).toBe( + FULL_CONTAINER_ID, + ); + }); + + it("removes shared assets while preserving validated Docker recovery state with --keep-data", () => { + const { result, statePath, privateBin, dockerLog } = runDockerStop( + "duplicate", + "remove", + ); + + expect(result.status).toBe(0); + expect(existsSync(statePath)).toBe(true); + expect(existsSync(privateBin)).toBe(false); + expect(dockerLog).not.toMatch(/\bcompose\b.*\brm\b/); + }); +}); + +describe("native removal shutdown", () => { + it("stops the worker first and aborts all cleanup when it cannot stop", () => { + const result = runNativeRemoveWithWorkerFailure(); + + expect(result.result.status).toBe(1); + expect(result.killLog).toBe("424242:SIGTERM\n"); + expect(existsSync(result.workerPidfile)).toBe(true); + expect(existsSync(result.enginePidfile)).toBe(true); + expect(existsSync(result.engineState)).toBe(true); + expect(existsSync(result.privateBin)).toBe(true); + }); + + it("refuses an instance-scoped global uninstall before deleting shared assets", () => { + const { result, privateBin } = runInstanceRemove(); + + expect(result.status).toBe(1); + expect(existsSync(privateBin)).toBe(true); + expect(`${result.stdout}\n${result.stderr}`).toContain("stop --instance 1"); + }); + + it.each([ + ["out-of-range", ["--instance", "51"]], + ["non-integer", ["--instance", "nope"]], + ["partial integer", ["--instance", "1nope"]], + ["missing value", ["--instance"]], + ["missing inline value", ["--instance="]], + ])( + "rejects an %s instance before deleting shared assets", + (_label, instanceArgs) => { + const { result, privateBin } = runInstanceRemove(instanceArgs); + + expect(result.status).toBe(1); + expect(existsSync(privateBin)).toBe(true); + expect(`${result.stdout}\n${result.stderr}`).toContain( + "--instance must be an integer between 0 and 50", + ); + }, + ); + + it.each([ + ["separate", ["--instance", "0"]], + ["inline", ["--instance=0"]], + ])("accepts valid instance zero in %s form", (_label, instanceArgs) => { + const { result, privateBin } = runInstanceRemove(instanceArgs); + + expect(result.status).toBe(0); + expect(existsSync(privateBin)).toBe(false); + }); + + it("accepts a valid nonzero inline instance", () => { + const { result, privateBin } = runInstanceRemove(["--instance=1"]); + + expect(result.status).toBe(1); + expect(existsSync(privateBin)).toBe(true); + expect(`${result.stdout}\n${result.stderr}`).toContain("stop --instance 1"); + }); +}); diff --git a/test/cli-remove.test.ts b/test/cli-remove.test.ts index 2484d4f882..27a3feea4c 100644 --- a/test/cli-remove.test.ts +++ b/test/cli-remove.test.ts @@ -20,6 +20,8 @@ let sandbox: string; function ctx(overrides: Partial = {}): RemoveContext { return { home: sandbox, + runtimeDir: join(sandbox, ".agentmemory"), + dataDir: join(sandbox, ".agentmemory", "data"), pinnedVersion: "0.11.2", localBinIiiVersion: null, connectManifest: null, @@ -147,6 +149,51 @@ describe("buildRemovePlan", () => { expect(item.alwaysAsk).toBe(false); expect(item.description).toContain("private install"); }); + + it.each([ + { + label: "instance", + runtimeDir: "instance-2", + selectedDataDir: "instance-2", + }, + { + label: "custom data", + runtimeDir: ".agentmemory", + selectedDataDir: "custom-data", + }, + ])("targets the resolved $label runtime and data roots", ({ runtimeDir, selectedDataDir }) => { + const resolvedRuntimeDir = join(sandbox, runtimeDir); + const resolvedDataDir = join(sandbox, selectedDataDir); + mkdirSync(resolvedRuntimeDir, { recursive: true }); + mkdirSync(resolvedDataDir, { recursive: true }); + writeFileSync(join(resolvedRuntimeDir, "iii.pid"), "101\n"); + writeFileSync(join(resolvedRuntimeDir, "worker.pid"), "102\n"); + writeFileSync(join(resolvedRuntimeDir, "engine-state.json"), "{}"); + writeFileSync(join(resolvedDataDir, "iii-config.runtime.yaml"), "# generated"); + + const context = { + ...ctx(), + runtimeDir: resolvedRuntimeDir, + dataDir: resolvedDataDir, + } as RemoveContext & { runtimeDir: string; dataDir: string }; + const plan = buildRemovePlan(context, { force: false, keepData: false }); + + expect(plan.find((item) => item.id === "pidfile")?.path).toBe( + join(resolvedRuntimeDir, "iii.pid"), + ); + expect(plan.find((item) => item.id === "worker-pidfile")?.path).toBe( + join(resolvedRuntimeDir, "worker.pid"), + ); + expect(plan.find((item) => item.id === "engine-state")?.path).toBe( + join(resolvedRuntimeDir, "engine-state.json"), + ); + expect(plan.find((item) => item.id === "runtime-config")?.path).toBe( + join(resolvedDataDir, "iii-config.runtime.yaml"), + ); + expect(plan.find((item) => item.id === "data-dir")?.path).toBe( + resolvedDataDir, + ); + }); }); describe("formatPlan", () => { diff --git a/test/docker-port-config.test.ts b/test/docker-port-config.test.ts new file mode 100644 index 0000000000..2bcc55b62a --- /dev/null +++ b/test/docker-port-config.test.ts @@ -0,0 +1,67 @@ +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; + +const root = join(import.meta.dirname, ".."); +const compose = readFileSync(join(root, "docker-compose.yml"), "utf8"); +const engineConfig = readFileSync(join(root, "iii-config.docker.yaml"), "utf8"); + +function workerBlock(name: string): string { + const start = engineConfig.indexOf(` - name: ${name}`); + if (start === -1) return ""; + const next = engineConfig.indexOf("\n - name:", start + 1); + return engineConfig.slice(start, next === -1 ? undefined : next); +} + +describe("Docker engine port configuration", () => { + it("passes the resolved port quartet into the engine container", () => { + expect(compose).toContain('III_REST_PORT: "${III_REST_PORT:-3111}"'); + expect(compose).toContain('III_STREAM_PORT: "${III_STREAM_PORT:-3112}"'); + expect(compose).toContain('III_VIEWER_PORT: "${III_VIEWER_PORT:-3113}"'); + expect(compose).toContain('III_ENGINE_PORT: "${III_ENGINE_PORT:-49134}"'); + }); + + it("publishes the configured host and container ports", () => { + expect(compose).toContain( + '"127.0.0.1:${III_REST_PORT:-3111}:${III_REST_PORT:-3111}"', + ); + expect(compose).toContain( + '"127.0.0.1:${III_STREAM_PORT:-3112}:${III_STREAM_PORT:-3112}"', + ); + expect(compose).toContain( + '"127.0.0.1:${III_ENGINE_PORT:-49134}:${III_ENGINE_PORT:-49134}"', + ); + expect(compose).toContain( + '"127.0.0.1:${AGENTMEMORY_METRICS_PORT:-9464}:9464"', + ); + }); + + it("runs CLI-managed bind mounts as the host user without recursive chown", () => { + expect(compose).toContain( + 'user: "${AGENTMEMORY_DOCKER_UID:-65532}:${AGENTMEMORY_DOCKER_GID:-65532}"', + ); + expect(compose).toContain("AGENTMEMORY_DOCKER_SKIP_CHOWN"); + }); + + it("configures every iii listener from the same environment", () => { + expect(workerBlock("iii-http")).toContain("port: ${III_REST_PORT:3111}"); + expect(workerBlock("iii-stream")).toContain("port: ${III_STREAM_PORT:3112}"); + + const manager = workerBlock("iii-worker-manager"); + expect(manager).toContain("port: ${III_ENGINE_PORT:49134}"); + expect(manager).toContain("host: 0.0.0.0"); + }); + + it("leaves worker ownership to the host CLI", () => { + expect(engineConfig).not.toContain("- name: iii-exec"); + expect(engineConfig).not.toContain("node dist/index.mjs"); + }); + + it("keeps REST and viewer CORS aligned with overridden ports", () => { + const http = workerBlock("iii-http"); + expect(http).toContain("http://localhost:${III_REST_PORT:3111}"); + expect(http).toContain("http://127.0.0.1:${III_REST_PORT:3111}"); + expect(http).toContain("http://localhost:${III_VIEWER_PORT:3113}"); + expect(http).toContain("http://127.0.0.1:${III_VIEWER_PORT:3113}"); + }); +}); diff --git a/test/engine-config.test.ts b/test/engine-config.test.ts new file mode 100644 index 0000000000..e929d1fc30 --- /dev/null +++ b/test/engine-config.test.ts @@ -0,0 +1,54 @@ +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { renderEngineConfig } from "../src/cli/engine-config.js"; + +describe("renderEngineConfig", () => { + it("stores engine state in the resolved data directory", () => { + const source = readFileSync( + join(import.meta.dirname, "..", "iii-config.yaml"), + "utf8", + ); + const dataDir = join("/var", "lib", "agentmemory"); + + const rendered = renderEngineConfig(source, { dataDir }); + + expect(rendered).toContain( + `file_path: '${join(dataDir, "state_store.db")}'`, + ); + expect(rendered).toContain( + `file_path: '${join(dataDir, "stream_store")}'`, + ); + expect(rendered).not.toContain("./data/"); + }); + + it("moves the complete native port quartet from one REST override", () => { + const source = readFileSync( + join(import.meta.dirname, "..", "iii-config.yaml"), + "utf8", + ); + + const rendered = renderEngineConfig(source, { + dataDir: "/tmp/agentmemory", + ports: { + restPort: 3211, + streamPort: 3212, + viewerPort: 3213, + enginePort: 49234, + }, + }); + + expect(rendered).toMatch( + /- name: iii-http\n\s+config:\n\s+port: 3211/, + ); + expect(rendered).toMatch( + /- name: iii-stream\n\s+config:\n\s+port: 3212/, + ); + expect(rendered).toContain( + 'allowed_origins: ["http://localhost:3211", "http://localhost:3213", "http://127.0.0.1:3211", "http://127.0.0.1:3213"]', + ); + expect(rendered).toMatch( + /- name: iii-worker-manager\n\s+config:\n\s+port: 49234\n\s+host: 127\.0\.0\.1/, + ); + }); +}); diff --git a/test/engine-launch.test.ts b/test/engine-launch.test.ts new file mode 100644 index 0000000000..cf12f687cd --- /dev/null +++ b/test/engine-launch.test.ts @@ -0,0 +1,178 @@ +import { describe, it, expect } from "vitest"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { + agentmemoryHome, + dockerComposeArgs, + dockerProjectName, + isBundledConfig, + legacyDataMigrations, + resolveEngineCwd, + rewriteBundledConfig, + runtimeConfigPath, +} from "../src/cli/engine-launch.js"; + +const HOME = "/Users/test"; + +describe("engine-launch path resolution", () => { + it("agentmemoryHome anchors config and runtimeConfigPath scopes instance state", () => { + expect(agentmemoryHome(HOME)).toBe(join(HOME, ".agentmemory")); + expect(runtimeConfigPath("/var/lib/agentmemory/instance-1")).toBe( + join("/var/lib/agentmemory/instance-1", "iii-config.runtime.yaml"), + ); + }); + + it("isBundledConfig matches both package config locations", () => { + const dist = "/opt/pkg/dist"; + expect(isBundledConfig(join(dist, "iii-config.yaml"), dist)).toBe(true); + expect(isBundledConfig(join(dist, "..", "iii-config.yaml"), dist)).toBe(true); + expect(isBundledConfig("/opt/pkg/iii-config.yaml", dist)).toBe(true); + expect(isBundledConfig(join(HOME, ".agentmemory", "iii-config.yaml"), dist)).toBe(false); + expect(isBundledConfig("/some/project/iii-config.yaml", dist)).toBe(false); + }); + + it("resolveEngineCwd keeps the invocation cwd for repo-local configs", () => { + const repo = "/work/agentmemory"; + expect(resolveEngineCwd(join(repo, "iii-config.yaml"), repo, HOME)).toBe(repo); + }); + + it("resolveEngineCwd anchors bundled configs and preserves custom config roots", () => { + const repo = "/work/some-project"; + expect(resolveEngineCwd("/opt/pkg/dist/iii-config.yaml", repo, HOME, true)).toBe( + join(HOME, ".agentmemory"), + ); + expect( + resolveEngineCwd(join(HOME, ".agentmemory", "iii-config.yaml"), repo, HOME), + ).toBe(join(HOME, ".agentmemory")); + expect(resolveEngineCwd("/etc/custom-iii.yaml", repo, HOME)).toBe( + "/etc", + ); + expect(resolveEngineCwd("custom-iii.yaml", repo, HOME)).toBe(repo); + }); + + it("scopes Docker compose commands by REST-port project", () => { + expect(dockerProjectName(3211)).toBe("agentmemory-3211"); + expect( + dockerComposeArgs("/opt/agentmemory/docker-compose.yml", "agentmemory-3211", [ + "up", + "-d", + ]), + ).toEqual([ + "compose", + "-p", + "agentmemory-3211", + "-f", + "/opt/agentmemory/docker-compose.yml", + "up", + "-d", + ]); + }); + + it("legacyDataMigrations targets the resolved platform data dir", () => { + const resolvedDataDir = "/var/lib/agentmemory"; + const migrations = legacyDataMigrations("/work/proj", HOME, resolvedDataDir); + expect(migrations).toEqual([ + { + from: join("/work/proj", "data", "state_store.db"), + to: join(resolvedDataDir, "state_store.db"), + }, + { + from: join("/work/proj", "data", "stream_store"), + to: join(resolvedDataDir, "stream_store"), + }, + ]); + }); +}); + +describe("rewriteBundledConfig", () => { + const SAMPLE = [ + " file_path: ./data/state_store.db", + " file_path: ./data/stream_store", + " - name: iii-exec", + " config:", + " watch:", + " - src/**/*.ts", + " exec:", + " - node dist/index.mjs", + ].join("\n"); + + it("substitutes data paths and removes bundled worker supervision", () => { + const out = rewriteBundledConfig(SAMPLE, HOME, "/usr/bin/node", "/opt/pkg/dist/index.mjs"); + expect(out).toContain( + `file_path: '${join(HOME, ".agentmemory", "data", "state_store.db")}'`, + ); + expect(out).toContain( + `file_path: '${join(HOME, ".agentmemory", "data", "stream_store")}'`, + ); + expect(out).not.toContain("./data/"); + expect(out).not.toContain("- name: iii-exec"); + expect(out).not.toContain("src/**/*.ts"); + }); + + it("preserves unrelated commands in the bundled iii-exec worker", () => { + const bundled = [ + "workers:", + " - name: iii-exec", + " config:", + " exec:", + " - node dist/index.mjs", + " - node scripts/other-worker.mjs", + ].join("\n"); + + const out = rewriteBundledConfig( + bundled, + HOME, + "/usr/bin/node", + "/opt/pkg/dist/index.mjs", + ); + expect(out).toContain("- name: iii-exec"); + expect(out).toContain("- node scripts/other-worker.mjs"); + expect(out).not.toContain("- node dist/index.mjs"); + }); + + it("escapes apostrophes in paths for single-quoted YAML", () => { + const out = rewriteBundledConfig( + SAMPLE, + "/Users/o'brien", + "/usr/bin/node", + "/opt/pkg/dist/index.mjs", + ); + expect(out).toContain("o''brien"); + }); + + it("rewrites the real bundled config with no relative paths left", () => { + const raw = readFileSync(join(import.meta.dirname, "..", "iii-config.yaml"), "utf-8"); + const out = rewriteBundledConfig(raw, HOME, process.execPath, "/opt/pkg/dist/index.mjs"); + expect(out).not.toContain("./data/"); + expect(out).not.toContain("src/**/*.ts"); + expect(out).not.toContain("- node dist/index.mjs"); + expect(out).not.toContain("- name: iii-exec"); + expect(out).toContain(join(HOME, ".agentmemory", "data", "state_store.db")); + expect(out).toContain(join(HOME, ".agentmemory", "data", "stream_store")); + }); + + it("uses the CLI-resolved data directory and port quartet", () => { + const raw = readFileSync(join(import.meta.dirname, "..", "iii-config.yaml"), "utf-8"); + const dataDir = "/var/lib/agentmemory"; + const out = rewriteBundledConfig( + raw, + HOME, + process.execPath, + "/opt/pkg/dist/index.mjs", + { + dataDir, + ports: { + restPort: 3211, + streamPort: 3212, + viewerPort: 3213, + enginePort: 49234, + }, + }, + ); + + expect(out).toContain(join(dataDir, "state_store.db")); + expect(out).toContain("port: 3211"); + expect(out).toContain("port: 3212"); + expect(out).toContain("port: 49234"); + }); +}); diff --git a/test/multi-instance-port.test.ts b/test/multi-instance-port.test.ts index 4343365b3e..8c8723265c 100644 --- a/test/multi-instance-port.test.ts +++ b/test/multi-instance-port.test.ts @@ -5,6 +5,7 @@ const PORT_ENVS = [ "III_REST_PORT", "III_STREAM_PORT", "III_STREAMS_PORT", + "III_VIEWER_PORT", "III_ENGINE_PORT", "III_ENGINE_URL", ] as const; @@ -33,6 +34,7 @@ describe("multi-instance port auto-derive (#750)", () => { const cfg = loadConfig(); expect(cfg.restPort).toBe(3111); expect(cfg.streamsPort).toBe(3112); + expect(cfg.viewerPort).toBe(3113); expect(cfg.engineUrl).toBe("ws://localhost:49134"); }); @@ -41,6 +43,7 @@ describe("multi-instance port auto-derive (#750)", () => { const cfg = loadConfig(); expect(cfg.restPort).toBe(3211); expect(cfg.streamsPort).toBe(3212); + expect(cfg.viewerPort).toBe(3213); expect(cfg.engineUrl).toBe("ws://localhost:49234"); }); @@ -76,6 +79,13 @@ describe("multi-instance port auto-derive (#750)", () => { expect(cfg.engineUrl).toBe("ws://localhost:55555"); }); + it("explicit III_VIEWER_PORT pins the viewer", () => { + process.env["III_REST_PORT"] = "3211"; + process.env["III_VIEWER_PORT"] = "7777"; + const cfg = loadConfig(); + expect(cfg.viewerPort).toBe(7777); + }); + it("legacy III_ENGINE_URL overrides derivation entirely", () => { process.env["III_REST_PORT"] = "3211"; process.env["III_ENGINE_URL"] = "ws://remote-host:49999"; diff --git a/test/process-state.test.ts b/test/process-state.test.ts new file mode 100644 index 0000000000..d4c599d0aa --- /dev/null +++ b/test/process-state.test.ts @@ -0,0 +1,14 @@ +import { describe, expect, it } from "vitest"; +import { processStatIsRunning } from "../src/cli/process-state.js"; + +describe("processStatIsRunning", () => { + it("treats zombie processes as stopped", () => { + expect(processStatIsRunning("Z+")).toBe(false); + expect(processStatIsRunning(" Z ")).toBe(false); + }); + + it("keeps active process states running", () => { + expect(processStatIsRunning("S+")).toBe(true); + expect(processStatIsRunning("R")).toBe(true); + }); +}); diff --git a/test/runtime-paths.test.ts b/test/runtime-paths.test.ts new file mode 100644 index 0000000000..231fb8ca32 --- /dev/null +++ b/test/runtime-paths.test.ts @@ -0,0 +1,29 @@ +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { runtimeMetadataPath } from "../src/runtime-paths.js"; + +describe("runtime metadata paths", () => { + it("uses an explicit runtime directory so instances do not share metadata", () => { + expect( + runtimeMetadataPath("engine-state.json", { + env: { AGENTMEMORY_RUNTIME_DIR: "/var/lib/agentmemory/instance-2" }, + home: "/home/test", + }), + ).toBe(join("/var/lib/agentmemory/instance-2", "engine-state.json")); + }); + + it("keeps instance-zero lifecycle state canonical across data-dir changes", () => { + expect( + runtimeMetadataPath("engine-state.json", { + env: { AGENTMEMORY_DATA_DIR: "/var/lib/agentmemory/custom" }, + home: "/home/test", + }), + ).toBe(join("/home/test", ".agentmemory", "engine-state.json")); + }); + + it("keeps the legacy home fallback for direct worker launches", () => { + expect(runtimeMetadataPath("worker.pid", { env: {}, home: "/home/test" })).toBe( + join("/home/test", ".agentmemory", "worker.pid"), + ); + }); +}); diff --git a/test/startup-stderr.test.ts b/test/startup-stderr.test.ts new file mode 100644 index 0000000000..ee3edaacb4 --- /dev/null +++ b/test/startup-stderr.test.ts @@ -0,0 +1,13 @@ +import { describe, expect, it } from "vitest"; +import { createStartupStderrCapture } from "../src/cli/startup-stderr.js"; + +describe("startup stderr capture", () => { + it("exposes bounded stderr before the child process exits", () => { + const capture = createStartupStderrCapture(5); + + capture.append(Buffer.from("abc")); + capture.append(Buffer.from("def")); + + expect(capture.text()).toBe("abcde"); + }); +}); diff --git a/test/stop-worker-pidfile.test.ts b/test/stop-worker-pidfile.test.ts index c70aaf1af9..fe018fca3c 100644 --- a/test/stop-worker-pidfile.test.ts +++ b/test/stop-worker-pidfile.test.ts @@ -3,8 +3,8 @@ import { readFileSync } from "node:fs"; // #640 + #474: stop must also kill the worker process, not just the // iii engine. We expose the worker pidfile from src/index.ts and read it -// from src/cli.ts. Static check that both files agree on the path -// (~/.agentmemory/worker.pid) and that stop reads it. +// from src/cli.ts. Static check that both files use the resolved runtime +// metadata directory and that stop reads it. describe("stop reaps the worker process (#640, #474)", () => { it("src/index.ts writes worker.pid alongside iii.pid", () => { const source = readFileSync("src/index.ts", "utf-8"); @@ -26,10 +26,24 @@ describe("stop reaps the worker process (#640, #474)", () => { expect(source).toMatch(/Stopping agentmemory worker/); }); - it("both files agree on the pidfile path: ~/.agentmemory/worker.pid", () => { + it("both files agree on the instance-scoped worker pidfile", () => { const indexSrc = readFileSync("src/index.ts", "utf-8"); const cliSrc = readFileSync("src/cli.ts", "utf-8"); - expect(indexSrc).toMatch(/\.agentmemory["'].*worker\.pid|"worker\.pid"/); - expect(cliSrc).toMatch(/\.agentmemory["'].*worker\.pid|"worker\.pid"/); + expect(indexSrc).toContain('runtimeMetadataPath("worker.pid")'); + expect(cliSrc).toContain('runtimeMetadataPath("worker.pid")'); + }); + + it("validates Docker ownership and flushes the worker before stopping the container", () => { + const source = readFileSync("src/cli.ts", "utf-8"); + const start = source.indexOf("async function stopDockerEngine"); + const end = source.indexOf("async function runStop", start); + const body = source.slice(start, end); + + expect(body.indexOf("inspectOwnedDockerEngine(state)")) + .toBeLessThan(body.indexOf("readWorkerPidfile()")); + expect(body.indexOf("readWorkerPidfile()")) + .toBeLessThan(body.indexOf('["stop", "--time", "10", inspection.containerId]')); + expect(body).toContain("persistDockerInspection(state, inspection)"); + expect(body).toContain("writeEngineState(resolvedState)"); }); }); From d54788361b89452a812315960676b0c6040b9329 Mon Sep 17 00:00:00 2001 From: Rohit Ghumare <48523873+rohitg00@users.noreply.github.com> Date: Thu, 24 Sep 2026 17:35:36 +0530 Subject: [PATCH 02/57] chore(engine): pin iii-sdk and engine at 0.19.7 (#1396) * chore(engine): pin iii-sdk and engine at 0.19.7 Move the iii-sdk dependency and the pinned iii-engine from 0.11.2 to 0.19.7, the last engine before the 0.20 SDK reorganization. It carries the upstream route-ownership fix, so /agentmemory/* no longer answers 404 after the engine reconnects (#1013). Engines from 0.19.4 persist each builtin worker's config block into data/configuration on first boot and ignore the config file afterwards, which made --port, --instance and data-dir changes silently ineffective. The CLI now clears those persisted entries before every engine spawn so the runtime config rendered from the environment is the seed each time. Also: agentmemory upgrade pins the SDK to the same constant instead of a hardcoded version, Dependabot ignores iii-sdk, and every pin mention in docs, translations, deploy templates, the eval harness and .env.example is updated. * fix(cli): harden the engine pin follow-ups from review agentmemory upgrade now pins iii-sdk to the version this package was built against instead of whatever AGENTMEMORY_III_VERSION overrides the engine to. A persisted builtin config entry that exists but cannot be removed is surfaced as a warning naming the directory, rather than silently leaving the engine on stale ports; a test covers it. The bundled docker-compose.yml keeps the engine's persisted builtin config on a tmpfs so every container start re-seeds from config.yaml and the III_* env vars, matching the native CLI path. The deploy templates go back to the engine pair of the published npm package; they move together with AGENTMEMORY_VERSION at release time. * fix(index): persist the search snapshot continuously and bound worker shutdown The BM25/vector snapshot was written only by a graceful shutdown, after a full rebuild, or by delete paths. Live observation, compression and memory writes added to the in-memory index without ever scheduling the debounced save, so a crash, SIGKILL or power loss booted the previous snapshot; the rebuild was skipped because that snapshot was not empty, and every observation captured since the last clean stop stayed invisible to search. Every live add now schedules the 5 s debounced save, bulk indexing does the same, and on boot the worker compares the loaded snapshot with each session's observation count and re-indexes what is missing. The SIGTERM handler awaited a state write that cannot land while the SDK is reconnecting, so a worker whose engine had already gone never exited and `agentmemory stop` fell through to SIGKILL. The final flush and the SDK shutdown are now time-boxed at 4 s each with a hard exit at 8 s, open viewer connections are closed instead of awaited, and the CLI's orphan reap grace matches that budget. Review follow-ups: the compose tmpfs now targets the engine image's real working directory (/home/nonroot/data/configuration; the previous path never received the persisted entries), a persisted builtin config entry that cannot be removed aborts `agentmemory start` instead of launching an engine that would ignore the requested ports, and the deploy Dockerfiles refuse to build when III_VERSION and III_SDK_VERSION differ. Verified against the containerized 0.19.7 engine: SIGKILL 1 s after an observation is healed by the boot reconcile, SIGKILL 8 s after is covered by the debounced save, SIGTERM with the engine stopped exits in about 5 s instead of hanging, no persisted config survives a container restart, and the Fly image builds with matching versions and fails with mismatched ones. * fix(index): replace on re-add, widen the boot reconcile, surface SDK shutdown errors SearchIndex.add on an id that is already indexed now removes the old document first. Before, the entry was overwritten but the old postings and the old term count stayed behind, which skewed BM25 scoring every time compression replaced a synthetic observation under the same id, and would have done the same for a reconcile racing a live write. The boot reconcile also treats a session whose observationCount is 0 or missing as unknown and reads it instead of skipping it, and re-checks membership right before it indexes what it collected. settleWithin no longer turns a rejected promise into a successful settlement; the SDK shutdown call site logs the failure and still exits. * fix(cli): clear persisted builtin config under a custom configuration directory The engine's configuration worker accepts an fs adapter directory; a custom engine config that sets it makes the engine persist the builtin entries there instead of data/configuration, so the CLI's cleanup missed them and the rendered ports were ignored on the next start. The cleanup now reads the configuration worker block of the rendered runtime config and clears that directory too, resolved against the engine working directory the way the engine resolves it. * fix: stop the viewer listener before dropping its connections on shutdown closeAllConnections ran before close, so a request accepted in between kept the shutdown waiting on a connection nothing was going to drain. The listener now closes first and the open connections are dropped while it winds down. --- .env.example | 10 +- .github/dependabot.yml | 2 + CHANGELOG.md | 14 ++ INSTALL_FOR_AGENTS.md | 16 +-- README.md | 32 ++--- READMEs/README.de-DE.md | 24 ++-- READMEs/README.es-ES.md | 24 ++-- READMEs/README.fr-FR.md | 24 ++-- READMEs/README.hi-IN.md | 24 ++-- READMEs/README.ja-JP.md | 24 ++-- READMEs/README.ko-KR.md | 24 ++-- READMEs/README.pt-BR.md | 24 ++-- READMEs/README.ru-RU.md | 24 ++-- READMEs/README.tr-TR.md | 24 ++-- READMEs/README.zh-CN.md | 24 ++-- READMEs/README.zh-TW.md | 24 ++-- deploy/coolify/Dockerfile | 2 + deploy/fly/Dockerfile | 10 +- deploy/railway/Dockerfile | 10 +- deploy/render/Dockerfile | 10 +- docker-compose.yml | 25 ++-- eval/README.md | 4 +- eval/scripts/sandbox.sh | 6 +- package.json | 2 +- src/cli.ts | 62 +++++---- src/cli/doctor-diagnostics.ts | 2 +- src/cli/engine-config.ts | 63 ++++++++- src/functions/compress.ts | 3 +- src/functions/observe.ts | 3 +- src/functions/remember.ts | 3 +- src/functions/search.ts | 20 +++ src/index.ts | 41 +++++- src/shutdown.ts | 17 +++ src/state/search-index.ts | 10 ++ test/cli-second-instance-guard.test.ts | 2 +- test/engine-config.test.ts | 97 +++++++++++++- test/index-live-persist.test.ts | 110 ++++++++++++++++ test/index-reconcile.test.ts | 175 +++++++++++++++++++++++++ test/multimodal.test.ts | 1 + test/shutdown.test.ts | 32 +++++ 40 files changed, 823 insertions(+), 225 deletions(-) create mode 100644 src/shutdown.ts create mode 100644 test/index-live-persist.test.ts create mode 100644 test/index-reconcile.test.ts create mode 100644 test/shutdown.test.ts diff --git a/.env.example b/.env.example index 2143098484..153aef4d9a 100644 --- a/.env.example +++ b/.env.example @@ -180,12 +180,12 @@ # 8. iii engine pin # ----------------------------------------------------------------------------- # -# agentmemory currently pins iii-engine to v0.11.2 — v0.11.6 introduces a -# new sandbox-everything-via-`iii worker add` model that agentmemory -# hasn't been refactored for yet. Override with AGENTMEMORY_III_VERSION -# only after migrating to the sandbox model manually. +# agentmemory pins iii-engine to the same release as its iii-sdk dependency +# (v0.19.7). The worker speaks the wire protocol of that engine, so the two move +# together in agentmemory releases. Override with AGENTMEMORY_III_VERSION only +# if you run your own engine and know it matches. -# AGENTMEMORY_III_VERSION=0.11.2 +# AGENTMEMORY_III_VERSION=0.19.7 # ----------------------------------------------------------------------------- # 9. Claude Code bridge (opt-in) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index e0a74e99e9..067c45313d 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -14,6 +14,8 @@ updates: commit-message: prefix: deps include: scope + ignore: + - dependency-name: iii-sdk groups: minor-and-patch: update-types: diff --git a/CHANGELOG.md b/CHANGELOG.md index 85df068d7a..340d46ddfd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,20 @@ All notable changes to agentmemory will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Changed + +- **iii engine and `iii-sdk` move from 0.11.2 to 0.19.7.** Same release on both sides, as before; the CLI downloads the pinned engine into `~/.agentmemory/bin`, the bundled `docker-compose.yml` pulls `iiidev/iii:0.19.7`, and `agentmemory upgrade` pins the SDK to the version this package was built against. The deploy templates under `deploy/` install the published npm package, so their engine pair moves together with `AGENTMEMORY_VERSION` at release time. 0.19.7 is the last engine before the 0.20 SDK reorganization and carries the upstream fix that keeps HTTP routes owned by the reconnecting worker, so `/agentmemory/*` no longer answers 404 after the engine reconnects (#1013). Existing state stores load unchanged. +- **Runtime config is re-seeded on every start.** Engines from 0.19.4 on persist each builtin worker's `config:` block into `data/configuration/.yaml` on first boot and treat that copy as the source of truth afterwards, which would have made `--port`, `--instance` and data-dir changes silently ineffective after the first run. The CLI now clears those persisted builtin entries right before it spawns the engine, so the runtime config it renders from your environment is the seed every time. If one of them cannot be removed, `agentmemory start` stops with the path instead of launching an engine that would ignore the requested ports. The bundled `docker-compose.yml` keeps the same directory on a tmpfs so container starts behave the same way. +- Dependabot no longer proposes `iii-sdk` bumps; the engine pin and the SDK version are updated together by hand. +- The deploy Dockerfiles (`deploy/fly`, `railway`, `render`, `coolify`) refuse to build when `III_VERSION` and `III_SDK_VERSION` differ, so overriding the engine tag alone can no longer produce a worker that speaks the wrong wire protocol. + +### Fixed + +- **The search index snapshot is written continuously, not only on clean shutdown.** Every observation, compression result and memory save now schedules the debounced snapshot write, and bulk indexing (import, replay, rebuild) does the same. Before, the BM25/vector snapshot was written only by a graceful shutdown; after a crash, `kill -9` or power loss the worker booted the stale snapshot, skipped the rebuild because the snapshot was not empty, and every observation captured since the last clean stop stayed invisible to search for good. On boot the worker now also compares the loaded snapshot against each session's observation count and re-indexes whatever is missing. Re-adding an observation under an id that is already indexed (compression replacing the synthetic entry) now replaces the index document instead of stacking postings on top of the old ones. +- **Worker shutdown no longer hangs when the engine is already gone.** The SIGTERM handler waited on a state write that can never land while the SDK is reconnecting, so `agentmemory stop` had to SIGKILL an orphaned worker after its grace period. The final index flush and the SDK shutdown are now time-boxed at 4 s each, with a hard exit at 8 s, and open viewer connections are closed instead of awaited. `agentmemory stop` gives an orphaned worker that full budget before escalating to SIGKILL. + ## [0.9.29] — 2026-08-16 Release wave in two parts. Recall quality: hybrid ranking reaches the primary recall path, lessons get a real index, every record learns where it came from, the knowledge graph populates keyless, and agent scoping threads through all save paths — plus connector parity for pi and Codex, a new DeepSeek Harness connector, current provider model defaults, and a viewer clarity pass. Foundation: the `.env` file now applies everywhere, imports become searchable, consolidation runs on session stop, twelve MCP-only agents get activated on connect, and every capture surface agrees on what "project" means. No breaking changes; read the upgrade notes for behavior changes you will notice. diff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.md index fd140d21cd..b10e993425 100644 --- a/INSTALL_FOR_AGENTS.md +++ b/INSTALL_FOR_AGENTS.md @@ -4,7 +4,7 @@ You are a coding agent. Follow this runbook top to bottom to install agentmemory ## What you are installing -agentmemory is a local memory server for coding agents. It exposes a REST API and MCP HTTP routes on port 3111, streams on 3112, a viewer on 3113, and connects its worker to iii-engine on 49134. It is built on the iii engine, which agentmemory manages as a pinned v0.11.2 binary under `~/.agentmemory/bin` on macOS/Linux or `%USERPROFILE%\.agentmemory\bin` on Windows. +agentmemory is a local memory server for coding agents. It exposes a REST API and MCP HTTP routes on port 3111, streams on 3112, a viewer on 3113, and connects its worker to iii-engine on 49134. It is built on the iii engine, which agentmemory manages as a pinned v0.19.7 binary under `~/.agentmemory/bin` on macOS/Linux or `%USERPROFILE%\.agentmemory\bin` on Windows. Configuration and the managed iii binary live under `~/.agentmemory`. Persistent iii state uses the platform data directory: `~/Library/Application Support/agentmemory` on macOS, `$XDG_DATA_HOME/agentmemory` or `~/.local/share/agentmemory` on Linux, and `%APPDATA%\agentmemory` on Windows. Override it with `--data-dir ` or `AGENTMEMORY_DATA_DIR`; use the same override on every restart. For instance 0, an existing `./data/state_store.db` or `./data/iii-config.yaml` takes precedence over the platform default, while an explicit flag or environment override still wins. Native and Docker starts use the same resolved host data directory. @@ -14,7 +14,7 @@ Default keyless mode needs no API key or cloud account and disables vector embed - Node.js >= 20 with npm and npx. Check with `node -v`, `npm -v`, and `npx -v`. - macOS/Linux automatic iii installation also requires `curl`, a POSIX `sh`, and `tar`. Check with `command -v curl sh tar`. Minimal images such as `node:20-slim` may not include them. -- Windows: WSL2 follows the Linux path above. Native Windows requires a manually downloaded, pinned iii-engine v0.11.2 `iii.exe`, or Docker Desktop; the CLI does not auto-extract the Windows ZIP. Native automated `connect` supports only `copilot-cli`. Other Windows agents need manual MCP configuration; WSL `connect` applies only to agents installed in that same WSL environment. +- Windows: WSL2 follows the Linux path above. Native Windows requires a manually downloaded, pinned iii-engine v0.19.7 `iii.exe`, or Docker Desktop; the CLI does not auto-extract the Windows ZIP. Native automated `connect` supports only `copilot-cli`. Other Windows agents need manual MCP configuration; WSL `connect` applies only to agents installed in that same WSL environment. - Ports 3111 (REST), 3112 (streams), 3113 (viewer), and 49134 (engine) free. If any are taken, stop whatever is using them before starting (see Troubleshooting). ## Running non-interactively @@ -38,12 +38,12 @@ For native Windows, install the engine before continuing: ```powershell # Download the archive that matches your CPU from the pinned release: -# https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2 +# https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7 # Extract iii.exe to $HOME\.agentmemory\bin\iii.exe, then verify the pin: & "$HOME\.agentmemory\bin\iii.exe" --version ``` -Expect: exactly `0.11.2`. Do not install the latest unpinned iii release. Alternatively, use WSL2 or start Docker Desktop and choose the Docker path when agentmemory starts. +Expect: exactly `0.19.7`. Do not install the latest unpinned iii release. Alternatively, use WSL2 or start Docker Desktop and choose the Docker path when agentmemory starts. ## 2. Start the server @@ -61,7 +61,7 @@ npx -y @agentmemory/agentmemory@latest --data-dir /absolute/path/to/agentmemory- Docker bind-mounts that same resolved host directory at `/data`. For a second isolated daemon, add `--instance 1`; it stores data and lifecycle metadata under `instance-1` and defaults to ports 3211, 3212, 3213, and 49234. Do not use `--port` alone for concurrent daemons: it changes the ports but keeps instance 0's canonical lifecycle ownership. Use `--instance` for isolation. -Expect: iii-engine v0.11.2 starts, the agentmemory worker registers with iii, and the ready panel lists REST, viewer, streams, and engine addresses. First boot can take longer while the engine binary is downloaded. +Expect: iii-engine v0.19.7 starts, the agentmemory worker registers with iii, and the ready panel lists REST, viewer, streams, and engine addresses. First boot can take longer while the engine binary is downloaded. ## 3. Validate the server and all four ports @@ -202,9 +202,9 @@ The MCP server exposes 54 tools by default (`--tools all`). Use `--tools core` ( - Server starts but `livez` never returns 200: re-run with `npx -y @agentmemory/agentmemory@latest --verbose` to see engine stderr. - `The engine process started but the REST API never responded.`: inspect all four derived ports, confirm the pinned iii process stayed alive, and use `--verbose` for captured engine stderr. - Engine version warning on start: harmless. agentmemory uses its own pinned engine in `~/.agentmemory/bin` regardless of any `iii` on `PATH`. Set `AGENTMEMORY_III_VERSION` only to override deliberately. -- "engine conflict" / another iii engine already running: if a different iii version is already serving the port, agentmemory will not adopt it. Stop that engine (`npx -y @agentmemory/agentmemory@latest stop --force`, or however you started it), then rerun the canonical command. Its private v0.11.2 binary does not replace a user-managed `iii` on `PATH`. +- "engine conflict" / another iii engine already running: if a different iii version is already serving the port, agentmemory will not adopt it. Stop that engine (`npx -y @agentmemory/agentmemory@latest stop --force`, or however you started it), then rerun the canonical command. Its private v0.19.7 binary does not replace a user-managed `iii` on `PATH`. - Only 7 tools visible in the agent: the MCP shim is in local fallback because it could not reach a server. Start `npx -y @agentmemory/agentmemory@latest`, ensure `AGENTMEMORY_URL` points at it (default `http://localhost:3111`), then reload MCP. -- Native Windows: the CLI does not auto-extract the ZIP. Install the pinned v0.11.2 `iii.exe` manually, use WSL2, or run with Docker Desktop and `AGENTMEMORY_USE_DOCKER=1`. Automated `connect` supports only `copilot-cli`; configure other native agents manually. +- Native Windows: the CLI does not auto-extract the ZIP. Install the pinned v0.19.7 `iii.exe` manually, use WSL2, or run with Docker Desktop and `AGENTMEMORY_USE_DOCKER=1`. Automated `connect` supports only `copilot-cli`; configure other native agents manually. - Semantic demo query returns zero hits: this is expected with vectors disabled in default keyless mode. Set `EMBEDDING_PROVIDER=local`, restart, allow the first model download to complete, and rerun the demo. ## Report success @@ -212,7 +212,7 @@ The MCP server exposes 54 tools by default (`--tools all`). Use `--tools core` ( Report back to the user: - agentmemory installed, version, and the server running on port 3111 -- iii-engine v0.11.2 running, the selected platform data directory, and all four ports accounted for +- iii-engine v0.19.7 running, the selected platform data directory, and all four ports accounted for - which agent was wired via `agentmemory connect`, and the tool count the agent now sees - the save and recall round-trip returned the probe memory after a full stop/start - the viewer is available at `http://localhost:3113` diff --git a/README.md b/README.md index 959d68c7e4..730342b24b 100644 --- a/README.md +++ b/README.md @@ -79,7 +79,7 @@ Requirements: - Node.js 20 or newer with npm and npx (`node -v`, `npm -v`, and `npx -v`). - macOS/Linux automatic iii-engine installation also needs `curl`, a POSIX `sh`, and `tar`. Minimal images such as `node:20-slim` may not include them. -- Native Windows requires the pinned iii-engine v0.11.2 `iii.exe` to be installed manually. WSL2 or Docker Desktop are the other supported paths. +- Native Windows requires the pinned iii-engine v0.19.7 `iii.exe` to be installed manually. WSL2 or Docker Desktop are the other supported paths. Canonical fresh-install command: @@ -111,7 +111,7 @@ Wire more agents any time with `agentmemory connect ` — 20 adapters lis
Windows -The fast path is WSL2. Native Windows engine setup requires the pinned v0.11.2 ZIP to be downloaded and `iii.exe` extracted manually; the CLI does not auto-extract it. Docker Desktop is also supported. See the [Windows notes](#windows) for the step-by-step. +The fast path is WSL2. Native Windows engine setup requires the pinned v0.19.7 ZIP to be downloaded and `iii.exe` extracted manually; the CLI does not auto-extract it. Docker Desktop is also supported. See the [Windows notes](#windows) for the step-by-step.
@@ -136,7 +136,7 @@ npx caches per version. Force the latest with `npx -y @agentmemory/agentmemory@l
Already running your own iii engine -agentmemory pins iii-engine v0.11.2 and won't attach to a different version (the worker can't speak another engine's protocol). Stop the other engine, then run `npx -y @agentmemory/agentmemory@latest`. It installs and runs the pinned v0.11.2 in `~/.agentmemory/bin`, leaving your own `iii` untouched. +agentmemory pins iii-engine v0.19.7 and won't attach to a different version (the worker can't speak another engine's protocol). Stop the other engine, then run `npx -y @agentmemory/agentmemory@latest`. It installs and runs the pinned v0.19.7 in `~/.agentmemory/bin`, leaving your own `iii` untouched.
@@ -496,7 +496,7 @@ None of these auto-capture from coding-agent hooks, ship a local-first viewer, o

Quick Start

-Compatibility: this release targets `iii-sdk` 0.11.2 and pins iii-engine v0.11.2. +Compatibility: this release targets `iii-sdk` 0.19.7 and pins iii-engine v0.19.7. ### Try it in 30 seconds @@ -575,7 +575,7 @@ Use the maintenance command when you intentionally want to update your local run npx -y @agentmemory/agentmemory@latest upgrade ``` -Warning: this command mutates the current workspace/runtime. It can update JavaScript dependencies and pull the pinned `iiidev/iii:0.11.2` Docker image. It never installs an unpinned or newer iii engine. +Warning: this command mutates the current workspace/runtime. It can update JavaScript dependencies and pull the pinned `iiidev/iii:0.19.7` Docker image. It never installs an unpinned or newer iii engine. Implementation details live in `src/cli.ts` (see `runUpgrade` around the `src/cli.ts:544-595` region). @@ -793,28 +793,28 @@ npm install && npm run build && npm start This starts agentmemory with a local `iii-engine` if the pinned binary is already installed, or uses Docker Compose when selected. REST, streams, and the viewer bind to `127.0.0.1` by default. The automatic macOS/Linux binary path requires `curl`, a POSIX `sh`, and `tar`. -Install `iii-engine` manually. **agentmemory currently pins `iii-engine` to `v0.11.2`**. `v0.11.6` introduces a new sandbox-everything-via-`iii worker add` model that agentmemory hasn't been refactored for yet. Pin lifts once the refactor lands. Override with `AGENTMEMORY_III_VERSION=` if you've migrated to the sandbox model manually. +Install `iii-engine` manually. **agentmemory currently pins `iii-engine` to `v0.19.7`**, the same release as its `iii-sdk` dependency; the worker speaks that engine's wire protocol, and 0.20.0 reorganized the SDK surface, so the two move together in agentmemory releases. Override with `AGENTMEMORY_III_VERSION=` if you run your own engine and know it matches. -- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.11.2/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` +- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.19.7/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` - **macOS x64:** swap `aarch64-apple-darwin` for `x86_64-apple-darwin` - **Linux x64:** swap for `x86_64-unknown-linux-gnu` - **Linux arm64:** swap for `aarch64-unknown-linux-gnu` -- **Windows:** download `iii-x86_64-pc-windows-msvc.zip` from [iii-hq/iii releases v0.11.2](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2) and extract `iii.exe` to `%USERPROFILE%\.agentmemory\bin\iii.exe` +- **Windows:** download `iii-x86_64-pc-windows-msvc.zip` from [iii-hq/iii releases v0.19.7](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7) and extract `iii.exe` to `%USERPROFILE%\.agentmemory\bin\iii.exe` -Or use Docker (the bundled `docker-compose.yml` pulls `iiidev/iii:0.11.2`). Full docs: [iii.dev/docs](https://iii.dev/docs). +Or use Docker (the bundled `docker-compose.yml` pulls `iiidev/iii:0.19.7`). Full docs: [iii.dev/docs](https://iii.dev/docs). ### Windows -agentmemory runs on Windows 10/11, but the Node.js package alone isn't enough; you also need the pinned iii-engine v0.11.2 runtime as a background process. The CLI does not auto-extract the Windows ZIP, so native Windows users must install `iii.exe` manually, use WSL2, or choose Docker Desktop. +agentmemory runs on Windows 10/11, but the Node.js package alone isn't enough; you also need the pinned iii-engine v0.19.7 runtime as a background process. The CLI does not auto-extract the Windows ZIP, so native Windows users must install `iii.exe` manually, use WSL2, or choose Docker Desktop. Native Windows automated MCP wiring supports only `agentmemory connect copilot-cli`. For Claude Code, Codex, Cursor, and every other native Windows agent, copy the manual MCP block from [Other agents](#other-agents) into that agent's Windows config. Running `connect` in WSL is appropriate only when the target agent is also installed in the same WSL environment; it does not edit a Windows-host agent's configuration. **Option A: prebuilt Windows binary (recommended)** ```powershell -# 1. Open https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2 in your browser -# (we pin to v0.11.2 until agentmemory refactors for the new sandbox -# model that engine v0.11.6+ requires) +# 1. Open https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7 in your browser +# (agentmemory pins the engine to the same release as its iii-sdk; +# v0.19.7 is the current pair) # 2. Download iii-x86_64-pc-windows-msvc.zip # (or iii-aarch64-pc-windows-msvc.zip if you're on an ARM machine) # 3. Extract iii.exe to agentmemory's private engine directory: @@ -822,7 +822,7 @@ New-Item -ItemType Directory -Force "$HOME\.agentmemory\bin" # Copy iii.exe to $HOME\.agentmemory\bin\iii.exe # 4. Verify: & "$HOME\.agentmemory\bin\iii.exe" --version -# Should print: 0.11.2 +# Should print: 0.19.7 # 5. Then run agentmemory as usual: npx -y @agentmemory/agentmemory@latest @@ -855,7 +855,7 @@ npx -y @agentmemory/mcp | Port conflict | `netstat -ano \| findstr :3111` to see what's bound, then kill it or use `--port ` | | Docker fallback skipped even though Docker is installed | Make sure Docker Desktop is actually running (system tray icon) | -> Note: the iii **engine** is a prebuilt binary, not a cargo crate, so don't try to `cargo install` it. (The iii **SDKs** are published on crates.io, npm, and PyPI, but agentmemory doesn't need them.) Supported engine install methods are all pinned to v0.11.2: the prebuilt binary above, agentmemory's macOS/Linux auto-install path (`curl`, POSIX `sh`, and `tar` required), and the Docker image `iiidev/iii:0.11.2`. A bare upstream `install.sh | sh` installs the latest engine, which agentmemory does not support. Use `npx -y @agentmemory/agentmemory@latest`; on macOS/Linux it fetches the pinned engine into `~/.agentmemory/bin`. +> Note: the iii **engine** is a prebuilt binary, not a cargo crate, so don't try to `cargo install` it. (The iii **SDKs** are published on crates.io, npm, and PyPI, but agentmemory doesn't need them.) Supported engine install methods are all pinned to v0.19.7: the prebuilt binary above, agentmemory's macOS/Linux auto-install path (`curl`, POSIX `sh`, and `tar` required), and the Docker image `iiidev/iii:0.19.7`. A bare upstream `install.sh | sh` installs the latest engine, which agentmemory does not support. Use `npx -y @agentmemory/agentmemory@latest`; on macOS/Linux it fetches the pinned engine into `~/.agentmemory/bin`. --- @@ -1647,7 +1647,7 @@ npm test # 1,674 tests npm run test:integration # API tests (requires running services) ``` -**Prerequisites:** Node.js >= 20 with npm/npx; [iii-engine](https://iii.dev/docs) v0.11.2 or Docker. The macOS/Linux automatic engine install also requires `curl`, a POSIX `sh`, and `tar`; native Windows uses the manual pinned `iii.exe`, WSL2, or Docker Desktop. +**Prerequisites:** Node.js >= 20 with npm/npx; [iii-engine](https://iii.dev/docs) v0.19.7 or Docker. The macOS/Linux automatic engine install also requires `curl`, a POSIX `sh`, and `tar`; native Windows uses the manual pinned `iii.exe`, WSL2, or Docker Desktop.

License

diff --git a/READMEs/README.de-DE.md b/READMEs/README.de-DE.md index 2f95ce63f7..3ea4fc9a1c 100644 --- a/READMEs/README.de-DE.md +++ b/READMEs/README.de-DE.md @@ -124,7 +124,7 @@ npx cached pro Version. Erzwingen Sie die neueste mit `npx -y @agentmemory/agent
Sie betreiben bereits eine eigene iii-Engine -agentmemory pinnt iii-engine v0.11.2 und verbindet sich nicht mit einer anderen Version (der Worker kann das Protokoll einer anderen Engine nicht sprechen). Stoppen Sie die andere Engine und führen Sie dann `npx -y @agentmemory/agentmemory@latest` aus. Es installiert und startet das gepinnte v0.11.2 in `~/.agentmemory/bin` und lässt Ihre eigene `iii` unangetastet. +agentmemory pinnt iii-engine v0.19.7 und verbindet sich nicht mit einer anderen Version (der Worker kann das Protokoll einer anderen Engine nicht sprechen). Stoppen Sie die andere Engine und führen Sie dann `npx -y @agentmemory/agentmemory@latest` aus. Es installiert und startet das gepinnte v0.19.7 in `~/.agentmemory/bin` und lässt Ihre eigene `iii` unangetastet.
@@ -463,7 +463,7 @@ Keines davon erfasst automatisch aus Coding-Agent-Hooks, liefert einen local-fir

Schnellstart

-Kompatibilität: Diese Version zielt auf stabiles `iii-sdk` `^0.11.0` und iii-engine v0.11.x ab. +Kompatibilität: Diese Version zielt auf `iii-sdk` 0.19.7 und pinnt iii-engine v0.19.7. ### In 30 Sekunden ausprobieren @@ -517,7 +517,7 @@ Verwenden Sie den Wartungsbefehl, wenn Sie Ihr lokales Runtime bewusst aktualisi npx @agentmemory/agentmemory upgrade ``` -Achtung: Dieser Befehl verändert den aktuellen Workspace/Runtime. Er kann JavaScript-Abhängigkeiten aktualisieren und das gepinnte Docker-Image `iiidev/iii:0.11.2` ziehen. Er installiert niemals eine ungepinnte oder neuere iii-Engine. +Achtung: Dieser Befehl verändert den aktuellen Workspace/Runtime. Er kann JavaScript-Abhängigkeiten aktualisieren und das gepinnte Docker-Image `iiidev/iii:0.19.7` ziehen. Er installiert niemals eine ungepinnte oder neuere iii-Engine. Implementierungsdetails in `src/cli.ts` (siehe `runUpgrade` rund um den Bereich `src/cli.ts:544-595`). @@ -721,15 +721,15 @@ npm install && npm run build && npm start Das startet agentmemory mit einer lokalen `iii-engine`, falls `iii` bereits installiert ist, oder fällt auf Docker Compose zurück, falls Docker vorhanden ist. REST, Streams und der Viewer binden sich standardmäßig an `127.0.0.1`. -`iii-engine` manuell installieren. **agentmemory pinnt `iii-engine` derzeit auf `v0.11.2`**. `v0.11.6` führt ein neues Modell ein, alles per `iii worker add` zu sandboxen, für das agentmemory noch nicht refaktoriert wurde. Der Pin wird aufgehoben, sobald die Refaktorierung erfolgt ist. Überschreiben Sie mit `AGENTMEMORY_III_VERSION=`, wenn Sie manuell auf das Sandbox-Modell migriert sind. +`iii-engine` manuell installieren. **agentmemory pinnt `iii-engine` derzeit auf `v0.19.7`**, dieselbe Version wie seine `iii-sdk`-Abhängigkeit; der Worker spricht das Wire-Protokoll genau dieser Engine, und 0.20.0 hat die SDK-Oberfläche neu organisiert, daher werden beide in agentmemory-Releases gemeinsam angehoben. Mit `AGENTMEMORY_III_VERSION=` überschreiben, wenn du eine eigene Engine betreibst und weißt, dass sie passt. -- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.11.2/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` +- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.19.7/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` - **macOS x64:** `aarch64-apple-darwin` durch `x86_64-apple-darwin` ersetzen - **Linux x64:** durch `x86_64-unknown-linux-gnu` ersetzen - **Linux arm64:** durch `aarch64-unknown-linux-gnu` ersetzen -- **Windows:** `iii-x86_64-pc-windows-msvc.zip` von [iii-hq/iii releases v0.11.2](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2) herunterladen, `iii.exe` extrahieren, zum PATH hinzufügen +- **Windows:** `iii-x86_64-pc-windows-msvc.zip` von [iii-hq/iii releases v0.19.7](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7) herunterladen, `iii.exe` extrahieren, zum PATH hinzufügen -Oder Docker verwenden (die mitgelieferte `docker-compose.yml` zieht `iiidev/iii:0.11.2`). Vollständige Doku: [iii.dev/docs](https://iii.dev/docs). +Oder Docker verwenden (die mitgelieferte `docker-compose.yml` zieht `iiidev/iii:0.19.7`). Vollständige Doku: [iii.dev/docs](https://iii.dev/docs). ### Windows @@ -738,9 +738,9 @@ agentmemory läuft auf Windows 10/11, aber das Node.js-Paket allein genügt nich **Option A: vorgebautes Windows-Binary (empfohlen)** ```powershell -# 1. Open https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2 in your browser -# (we pin to v0.11.2 until agentmemory refactors for the new sandbox -# model that engine v0.11.6+ requires) +# 1. Open https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7 in your browser +# (agentmemory pins the engine to the same release as its iii-sdk; +# v0.19.7 is the current pair) # 2. Download iii-x86_64-pc-windows-msvc.zip # (or iii-aarch64-pc-windows-msvc.zip if you're on an ARM machine) # 3. Extract iii.exe somewhere on PATH, or place it at: @@ -748,7 +748,7 @@ agentmemory läuft auf Windows 10/11, aber das Node.js-Paket allein genügt nich # (agentmemory checks that location automatically) # 4. Verify: iii --version -# Should print: 0.11.2 +# Should print: 0.19.7 # 5. Then run agentmemory as usual: npx -y @agentmemory/agentmemory @@ -780,7 +780,7 @@ npx -y @agentmemory/mcp | Port-Konflikt | `netstat -ano \| findstr :3111`, um zu sehen, was gebunden ist, dann beenden oder `--port ` verwenden | | Docker-Fallback wird übersprungen, obwohl Docker installiert ist | Stellen Sie sicher, dass Docker Desktop tatsächlich läuft (Taskleisten-Icon) | -> Hinweis: Die iii-**Engine** ist ein vorgebautes Binary, kein Cargo-Crate, versuche also nicht, sie per `cargo install` zu installieren. (Die iii-**SDKs** sind auf crates.io, npm und PyPI veröffentlicht, aber agentmemory benötigt sie nicht.) Unterstützte Engine-Installationsmethoden, alle auf v0.11.2 gepinnt: das vorgebaute v0.11.2-Binary oben, das Upstream-`sh`-Installationsskript **mit dem Versions-Pin** `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.11.2 sh` (macOS/Linux) und das Docker-Image `iiidev/iii:0.11.2`. Ein bloßes `install.sh | sh` installiert die **neueste** Engine, die agentmemory nicht unterstützt; übergib immer `VERSION=0.11.2`. Am einfachsten von allen: Führe einfach `npx @agentmemory/agentmemory` aus, das die gepinnte Engine für dich nach `~/.agentmemory/bin` holt. +> Hinweis: Die iii-**Engine** ist ein vorgebautes Binary, kein Cargo-Crate, versuche also nicht, sie per `cargo install` zu installieren. (Die iii-**SDKs** sind auf crates.io, npm und PyPI veröffentlicht, aber agentmemory benötigt sie nicht.) Unterstützte Engine-Installationsmethoden, alle auf v0.19.7 gepinnt: das vorgebaute v0.19.7-Binary oben, das Upstream-`sh`-Installationsskript **mit dem Versions-Pin** `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.19.7 sh` (macOS/Linux) und das Docker-Image `iiidev/iii:0.19.7`. Ein bloßes `install.sh | sh` installiert die **neueste** Engine, die agentmemory nicht unterstützt; übergib immer `VERSION=0.19.7`. Am einfachsten von allen: Führe einfach `npx @agentmemory/agentmemory` aus, das die gepinnte Engine für dich nach `~/.agentmemory/bin` holt. --- diff --git a/READMEs/README.es-ES.md b/READMEs/README.es-ES.md index 88438e4403..dfb7030946 100644 --- a/READMEs/README.es-ES.md +++ b/READMEs/README.es-ES.md @@ -124,7 +124,7 @@ npx cachea por versión. Fuerza la última con `npx -y @agentmemory/agentmemory@
Ya ejecutas tu propio engine iii -agentmemory fija iii-engine a v0.11.2 y no se conectará a una versión distinta (el worker no puede hablar el protocolo de otro engine). Detén el otro engine y ejecuta `npx -y @agentmemory/agentmemory@latest`. Instala y ejecuta la v0.11.2 fijada en `~/.agentmemory/bin`, dejando tu propio `iii` intacto. +agentmemory fija iii-engine a v0.19.7 y no se conectará a una versión distinta (el worker no puede hablar el protocolo de otro engine). Detén el otro engine y ejecuta `npx -y @agentmemory/agentmemory@latest`. Instala y ejecuta la v0.19.7 fijada en `~/.agentmemory/bin`, dejando tu propio `iii` intacto.
@@ -463,7 +463,7 @@ Ninguno de estos captura automáticamente desde hooks de agentes de codificació

Inicio rápido

-Compatibilidad: esta release apunta a `iii-sdk` estable `^0.11.0` e iii-engine v0.11.x. +Compatibilidad: esta release apunta a `iii-sdk` 0.19.7 y fija iii-engine v0.19.7. ### Pruébalo en 30 segundos @@ -517,7 +517,7 @@ Usa el comando de mantenimiento cuando intencionadamente quieras actualizar tu r npx @agentmemory/agentmemory upgrade ``` -Aviso: este comando muta el workspace/runtime actual. Puede actualizar dependencias de JavaScript y traer la imagen Docker fijada `iiidev/iii:0.11.2`. Nunca instala un motor iii sin fijar ni más nuevo. +Aviso: este comando muta el workspace/runtime actual. Puede actualizar dependencias de JavaScript y traer la imagen Docker fijada `iiidev/iii:0.19.7`. Nunca instala un motor iii sin fijar ni más nuevo. Los detalles de implementación están en `src/cli.ts` (ver `runUpgrade` en torno a la región `src/cli.ts:544-595`). @@ -721,15 +721,15 @@ npm install && npm run build && npm start Esto arranca agentmemory con un `iii-engine` local si `iii` ya está instalado, o cae a Docker Compose si hay Docker disponible. REST, streams y el visor se enlazan a `127.0.0.1` por defecto. -Instala `iii-engine` manualmente. **agentmemory actualmente fija `iii-engine` a `v0.11.2`**. `v0.11.6` introduce un nuevo modelo que sandboxea todo vía `iii worker add`, y agentmemory aún no se ha refactorizado para él. La fijación se levantará cuando aterrice el refactor. Sobrescribe con `AGENTMEMORY_III_VERSION=` si has migrado al modelo sandbox manualmente. +Instala `iii-engine` manualmente. **agentmemory actualmente fija `iii-engine` a `v0.19.7`**, la misma release que su dependencia `iii-sdk`; el worker habla el protocolo de ese engine, y 0.20.0 reorganizó la superficie del SDK, así que ambos avanzan juntos en cada release de agentmemory. Sobrescribe con `AGENTMEMORY_III_VERSION=` si ejecutas tu propio engine y sabes que coincide. -- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.11.2/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` +- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.19.7/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` - **macOS x64:** cambia `aarch64-apple-darwin` por `x86_64-apple-darwin` - **Linux x64:** cambia por `x86_64-unknown-linux-gnu` - **Linux arm64:** cambia por `aarch64-unknown-linux-gnu` -- **Windows:** descarga `iii-x86_64-pc-windows-msvc.zip` desde [iii-hq/iii releases v0.11.2](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2), extrae `iii.exe`, añádelo al PATH +- **Windows:** descarga `iii-x86_64-pc-windows-msvc.zip` desde [iii-hq/iii releases v0.19.7](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7), extrae `iii.exe`, añádelo al PATH -O usa Docker (el `docker-compose.yml` empaquetado descarga `iiidev/iii:0.11.2`). Documentación completa: [iii.dev/docs](https://iii.dev/docs). +O usa Docker (el `docker-compose.yml` empaquetado descarga `iiidev/iii:0.19.7`). Documentación completa: [iii.dev/docs](https://iii.dev/docs). ### Windows @@ -738,9 +738,9 @@ agentmemory funciona en Windows 10/11, pero el paquete de Node.js por sí solo n **Opción A: binario Windows preconstruido (recomendado)** ```powershell -# 1. Open https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2 in your browser -# (we pin to v0.11.2 until agentmemory refactors for the new sandbox -# model that engine v0.11.6+ requires) +# 1. Open https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7 in your browser +# (agentmemory pins the engine to the same release as its iii-sdk; +# v0.19.7 is the current pair) # 2. Download iii-x86_64-pc-windows-msvc.zip # (or iii-aarch64-pc-windows-msvc.zip if you're on an ARM machine) # 3. Extract iii.exe somewhere on PATH, or place it at: @@ -748,7 +748,7 @@ agentmemory funciona en Windows 10/11, pero el paquete de Node.js por sí solo n # (agentmemory checks that location automatically) # 4. Verify: iii --version -# Should print: 0.11.2 +# Should print: 0.19.7 # 5. Then run agentmemory as usual: npx -y @agentmemory/agentmemory @@ -780,7 +780,7 @@ npx -y @agentmemory/mcp | Conflicto de puerto | `netstat -ano \| findstr :3111` para ver qué está vinculado, mátalo o usa `--port ` | | Se omite el fallback a Docker aunque Docker esté instalado | Asegúrate de que Docker Desktop esté efectivamente en ejecución (icono en la bandeja del sistema) | -> Nota: el **motor** iii es un binario preconstruido, no un crate de cargo, así que no intentes instalarlo con `cargo install`. (Los **SDK** de iii sí están publicados en crates.io, npm y PyPI, pero agentmemory no los necesita.) Métodos de instalación del motor soportados, todos fijados a v0.11.2: el binario preconstruido v0.11.2 de arriba, el script de instalación `sh` upstream **con el pin de versión** `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.11.2 sh` (macOS/Linux) y la imagen Docker `iiidev/iii:0.11.2`. Un simple `install.sh | sh` instala el motor **más reciente**, que agentmemory no soporta; pasa siempre `VERSION=0.11.2`. Lo más fácil de todo: simplemente ejecuta `npx @agentmemory/agentmemory`, que obtiene el motor fijado en `~/.agentmemory/bin` por ti. +> Nota: el **motor** iii es un binario preconstruido, no un crate de cargo, así que no intentes instalarlo con `cargo install`. (Los **SDK** de iii sí están publicados en crates.io, npm y PyPI, pero agentmemory no los necesita.) Métodos de instalación del motor soportados, todos fijados a v0.19.7: el binario preconstruido v0.19.7 de arriba, el script de instalación `sh` upstream **con el pin de versión** `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.19.7 sh` (macOS/Linux) y la imagen Docker `iiidev/iii:0.19.7`. Un simple `install.sh | sh` instala el motor **más reciente**, que agentmemory no soporta; pasa siempre `VERSION=0.19.7`. Lo más fácil de todo: simplemente ejecuta `npx @agentmemory/agentmemory`, que obtiene el motor fijado en `~/.agentmemory/bin` por ti. --- diff --git a/READMEs/README.fr-FR.md b/READMEs/README.fr-FR.md index 3b1cd8bdc4..175d4e2259 100644 --- a/READMEs/README.fr-FR.md +++ b/READMEs/README.fr-FR.md @@ -124,7 +124,7 @@ npx met en cache par version. Forcez la dernière avec `npx -y @agentmemory/agen
Vous faites déjà tourner votre propre moteur iii -agentmemory épingle iii-engine v0.11.2 et ne s'attachera pas à une autre version (le worker ne peut pas parler le protocole d'un autre moteur). Arrêtez l'autre moteur, puis lancez `npx -y @agentmemory/agentmemory@latest`. Il installe et exécute le v0.11.2 épinglé dans `~/.agentmemory/bin`, sans toucher à votre propre `iii`. +agentmemory épingle iii-engine v0.19.7 et ne s'attachera pas à une autre version (le worker ne peut pas parler le protocole d'un autre moteur). Arrêtez l'autre moteur, puis lancez `npx -y @agentmemory/agentmemory@latest`. Il installe et exécute le v0.19.7 épinglé dans `~/.agentmemory/bin`, sans toucher à votre propre `iii`.
@@ -463,7 +463,7 @@ Aucun d'eux ne capture automatiquement depuis les hooks d'agents de codage, ne l

Démarrage rapide

-Compatibilité : cette version cible `iii-sdk` stable `^0.11.0` et iii-engine v0.11.x. +Compatibilité : cette version cible `iii-sdk` 0.19.7 et épingle iii-engine v0.19.7. ### Essayez en 30 secondes @@ -517,7 +517,7 @@ Utilisez la commande de maintenance lorsque vous voulez intentionnellement mettr npx @agentmemory/agentmemory upgrade ``` -Avertissement : cette commande modifie l'espace de travail / runtime courant. Elle peut mettre à jour les dépendances JavaScript et tirer l'image Docker épinglée `iiidev/iii:0.11.2`. Elle n'installe jamais un moteur iii non épinglé ou plus récent. +Avertissement : cette commande modifie l'espace de travail / runtime courant. Elle peut mettre à jour les dépendances JavaScript et tirer l'image Docker épinglée `iiidev/iii:0.19.7`. Elle n'installe jamais un moteur iii non épinglé ou plus récent. Détails d'implémentation dans `src/cli.ts` (voir `runUpgrade` autour de la zone `src/cli.ts:544-595`). @@ -721,15 +721,15 @@ npm install && npm run build && npm start Cela démarre agentmemory avec un `iii-engine` local si `iii` est déjà installé, ou retombe sur Docker Compose si Docker est disponible. REST, streams et visualiseur se lient à `127.0.0.1` par défaut. -Installer `iii-engine` manuellement. **agentmemory épingle actuellement `iii-engine` à `v0.11.2`**. `v0.11.6` introduit un nouveau modèle de sandboxing systématique via `iii worker add` pour lequel agentmemory n'a pas encore été refactorisé. L'épinglage sera levé une fois la refonte effectuée. Surchargez avec `AGENTMEMORY_III_VERSION=` si vous avez migré au modèle sandbox manuellement. +Installer `iii-engine` manuellement. **agentmemory épingle actuellement `iii-engine` à `v0.19.7`**, la même version que sa dépendance `iii-sdk` ; le worker parle le protocole de ce moteur précis, et 0.20.0 a réorganisé la surface du SDK, donc les deux évoluent ensemble dans les versions d'agentmemory. Remplacez avec `AGENTMEMORY_III_VERSION=` si vous exécutez votre propre moteur et savez qu'il correspond. -- **macOS arm64 :** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.11.2/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` +- **macOS arm64 :** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.19.7/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` - **macOS x64 :** remplacez `aarch64-apple-darwin` par `x86_64-apple-darwin` - **Linux x64 :** remplacez par `x86_64-unknown-linux-gnu` - **Linux arm64 :** remplacez par `aarch64-unknown-linux-gnu` -- **Windows :** téléchargez `iii-x86_64-pc-windows-msvc.zip` depuis [iii-hq/iii releases v0.11.2](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2), extrayez `iii.exe`, ajoutez-le au PATH +- **Windows :** téléchargez `iii-x86_64-pc-windows-msvc.zip` depuis [iii-hq/iii releases v0.19.7](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7), extrayez `iii.exe`, ajoutez-le au PATH -Ou utilisez Docker (le `docker-compose.yml` fourni tire `iiidev/iii:0.11.2`). Documentation complète : [iii.dev/docs](https://iii.dev/docs). +Ou utilisez Docker (le `docker-compose.yml` fourni tire `iiidev/iii:0.19.7`). Documentation complète : [iii.dev/docs](https://iii.dev/docs). ### Windows @@ -738,9 +738,9 @@ agentmemory tourne sur Windows 10/11, mais le paquet Node.js seul ne suffit pas **Option A : binaire Windows précompilé (recommandé)** ```powershell -# 1. Open https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2 in your browser -# (we pin to v0.11.2 until agentmemory refactors for the new sandbox -# model that engine v0.11.6+ requires) +# 1. Open https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7 in your browser +# (agentmemory pins the engine to the same release as its iii-sdk; +# v0.19.7 is the current pair) # 2. Download iii-x86_64-pc-windows-msvc.zip # (or iii-aarch64-pc-windows-msvc.zip if you're on an ARM machine) # 3. Extract iii.exe somewhere on PATH, or place it at: @@ -748,7 +748,7 @@ agentmemory tourne sur Windows 10/11, mais le paquet Node.js seul ne suffit pas # (agentmemory checks that location automatically) # 4. Verify: iii --version -# Should print: 0.11.2 +# Should print: 0.19.7 # 5. Then run agentmemory as usual: npx -y @agentmemory/agentmemory @@ -780,7 +780,7 @@ npx -y @agentmemory/mcp | Conflit de port | `netstat -ano \| findstr :3111` pour voir ce qui est lié, puis tuez-le ou utilisez `--port ` | | Fallback Docker ignoré bien que Docker soit installé | Assurez-vous que Docker Desktop tourne effectivement (icône de la barre d'état système) | -> Note : le **moteur** iii est un binaire précompilé, pas un crate cargo, donc n'essayez pas de l'installer avec `cargo install`. (Les **SDK** iii sont bien publiés sur crates.io, npm et PyPI, mais agentmemory n'en a pas besoin.) Méthodes d'installation du moteur supportées, toutes épinglées à v0.11.2 : le binaire précompilé v0.11.2 ci-dessus, le script d'installation `sh` amont **avec l'épingle de version** `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.11.2 sh` (macOS/Linux) et l'image Docker `iiidev/iii:0.11.2`. Un simple `install.sh | sh` installe le moteur **le plus récent**, que agentmemory ne supporte pas ; passez toujours `VERSION=0.11.2`. Le plus simple de tout : exécutez simplement `npx @agentmemory/agentmemory`, qui récupère le moteur épinglé dans `~/.agentmemory/bin` pour vous. +> Note : le **moteur** iii est un binaire précompilé, pas un crate cargo, donc n'essayez pas de l'installer avec `cargo install`. (Les **SDK** iii sont bien publiés sur crates.io, npm et PyPI, mais agentmemory n'en a pas besoin.) Méthodes d'installation du moteur supportées, toutes épinglées à v0.19.7 : le binaire précompilé v0.19.7 ci-dessus, le script d'installation `sh` amont **avec l'épingle de version** `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.19.7 sh` (macOS/Linux) et l'image Docker `iiidev/iii:0.19.7`. Un simple `install.sh | sh` installe le moteur **le plus récent**, que agentmemory ne supporte pas ; passez toujours `VERSION=0.19.7`. Le plus simple de tout : exécutez simplement `npx @agentmemory/agentmemory`, qui récupère le moteur épinglé dans `~/.agentmemory/bin` pour vous. --- diff --git a/READMEs/README.hi-IN.md b/READMEs/README.hi-IN.md index 47ee3b54f0..20395845e7 100644 --- a/READMEs/README.hi-IN.md +++ b/READMEs/README.hi-IN.md @@ -124,7 +124,7 @@ npx प्रति-वर्ज़न कैश करता है। नव
पहले से अपना iii engine चला रहे हैं -agentmemory iii-engine v0.11.2 को pin करता है और किसी भिन्न version से attach नहीं होगा (worker किसी दूसरे engine का protocol नहीं बोल सकता)। दूसरे engine को रोकें, फिर `npx -y @agentmemory/agentmemory@latest` चलाएँ। यह pinned v0.11.2 को `~/.agentmemory/bin` में install और run करता है, आपके अपने `iii` को अछूता छोड़ते हुए। +agentmemory iii-engine v0.19.7 को pin करता है और किसी भिन्न version से attach नहीं होगा (worker किसी दूसरे engine का protocol नहीं बोल सकता)। दूसरे engine को रोकें, फिर `npx -y @agentmemory/agentmemory@latest` चलाएँ। यह pinned v0.19.7 को `~/.agentmemory/bin` में install और run करता है, आपके अपने `iii` को अछूता छोड़ते हुए।
@@ -463,7 +463,7 @@ npx @agentmemory/agentmemory

Quick Start

-संगतता: यह रिलीज़ stable `iii-sdk` `^0.11.0` और iii-engine v0.11.x को टार्गेट करता है। +संगतता: यह रिलीज़ `iii-sdk` 0.19.7 को टार्गेट करता है और iii-engine को v0.19.7 पर pin करता है। ### 30 सेकंड में आज़माएँ @@ -515,7 +515,7 @@ Imported सेशंस native ones के साथ Replay picker में npx @agentmemory/agentmemory upgrade ``` -चेतावनी: यह कमांड वर्तमान workspace/runtime को mutate करता है। यह JavaScript निर्भरताएँ update कर सकता है और pinned Docker image `iiidev/iii:0.11.2` खींच सकता है। यह कभी भी unpinned या नया iii engine install नहीं करता। +चेतावनी: यह कमांड वर्तमान workspace/runtime को mutate करता है। यह JavaScript निर्भरताएँ update कर सकता है और pinned Docker image `iiidev/iii:0.19.7` खींच सकता है। यह कभी भी unpinned या नया iii engine install नहीं करता। Implementation विवरण `src/cli.ts` में हैं (`src/cli.ts:544-595` क्षेत्र के आसपास `runUpgrade` देखें)। @@ -700,15 +700,15 @@ npm install && npm run build && npm start यह agentmemory को local `iii-engine` के साथ शुरू करता है अगर `iii` पहले से installed है, या Docker उपलब्ध होने पर Docker Compose पर fallback करता है। REST, streams, और व्यूअर default रूप से `127.0.0.1` से bind करते हैं। -`iii-engine` मैनुअली इंस्टॉल करें। **agentmemory वर्तमान में `iii-engine` को `v0.11.2` पर pin करता है**। `v0.11.6` एक नया sandbox-everything-via-`iii worker add` model introduce करता है जिसके लिए agentmemory को अभी refactor नहीं किया गया है। Refactor land होने के बाद pin हटा दी जाती है। अगर आपने sandbox model पर मैनुअली migrate किया है तो `AGENTMEMORY_III_VERSION=` से override करें। +`iii-engine` मैनुअली इंस्टॉल करें। **agentmemory वर्तमान में `iii-engine` को `v0.19.7` पर pin करता है**, जो इसकी `iii-sdk` dependency वाला ही release है; worker उसी engine का wire protocol बोलता है, और 0.20.0 ने SDK surface को reorganize किया, इसलिए दोनों agentmemory releases में साथ बढ़ते हैं। यदि आप अपना engine चलाते हैं और जानते हैं कि वह मेल खाता है तो `AGENTMEMORY_III_VERSION=` से override करें। -- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.11.2/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` +- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.19.7/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` - **macOS x64:** `aarch64-apple-darwin` को `x86_64-apple-darwin` के साथ बदलें - **Linux x64:** `x86_64-unknown-linux-gnu` के साथ बदलें - **Linux arm64:** `aarch64-unknown-linux-gnu` के साथ बदलें -- **Windows:** [iii-hq/iii releases v0.11.2](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2) से `iii-x86_64-pc-windows-msvc.zip` download करें, `iii.exe` extract करें, PATH में जोड़ें +- **Windows:** [iii-hq/iii releases v0.19.7](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7) से `iii-x86_64-pc-windows-msvc.zip` download करें, `iii.exe` extract करें, PATH में जोड़ें -या Docker का उपयोग करें (bundled `docker-compose.yml` `iiidev/iii:0.11.2` खींचता है)। पूर्ण docs: [iii.dev/docs](https://iii.dev/docs)। +या Docker का उपयोग करें (bundled `docker-compose.yml` `iiidev/iii:0.19.7` खींचता है)। पूर्ण docs: [iii.dev/docs](https://iii.dev/docs)। ### Windows @@ -717,9 +717,9 @@ agentmemory Windows 10/11 पर चलता है, लेकिन केव **विकल्प A: prebuilt Windows binary (अनुशंसित)** ```powershell -# 1. अपने browser में https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2 खोलें -# (हम v0.11.2 पर pin करते हैं जब तक agentmemory नए sandbox -# model के लिए refactor नहीं हो जाता जो engine v0.11.6+ की आवश्यकता है) +# 1. अपने browser में https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7 खोलें +# (agentmemory engine को अपनी iii-sdk वाले ही release पर pin करता है; +# वर्तमान pair v0.19.7 है) # 2. iii-x86_64-pc-windows-msvc.zip download करें # (या ARM machine पर हैं तो iii-aarch64-pc-windows-msvc.zip) # 3. PATH पर कहीं iii.exe extract करें, या यहाँ रखें: @@ -727,7 +727,7 @@ agentmemory Windows 10/11 पर चलता है, लेकिन केव # (agentmemory उस location को automatically check करता है) # 4. Verify करें: iii --version -# Print होना चाहिए: 0.11.2 +# Print होना चाहिए: 0.19.7 # 5. फिर agentmemory को सामान्य की तरह चलाएँ: npx -y @agentmemory/agentmemory @@ -759,7 +759,7 @@ npx -y @agentmemory/mcp | Port conflict | `netstat -ano \| findstr :3111` से देखें कि क्या bind है, फिर उसे kill करें या `--port ` का उपयोग करें | | Docker installed होने पर भी Docker fallback skip हो रहा है | सुनिश्चित करें कि Docker Desktop वास्तव में चल रहा है (system tray icon) | -> नोट: iii **engine** एक prebuilt binary है, cargo crate नहीं, इसलिए इसे `cargo install` से install करने की कोशिश न करें। (iii **SDKs** crates.io, npm, और PyPI पर publish हैं, लेकिन agentmemory को उनकी ज़रूरत नहीं है।) समर्थित engine install methods, सभी v0.11.2 पर pinned: ऊपर वाला prebuilt v0.11.2 binary, version pin **के साथ** upstream `sh` install script `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.11.2 sh` (macOS/Linux), और Docker image `iiidev/iii:0.11.2`। केवल `install.sh | sh` **latest** engine install करता है, जिसे agentmemory support नहीं करता; हमेशा `VERSION=0.11.2` पास करें। सबसे आसान: बस `npx @agentmemory/agentmemory` चलाएँ, जो pinned engine को आपके लिए `~/.agentmemory/bin` में ले आता है। +> नोट: iii **engine** एक prebuilt binary है, cargo crate नहीं, इसलिए इसे `cargo install` से install करने की कोशिश न करें। (iii **SDKs** crates.io, npm, और PyPI पर publish हैं, लेकिन agentmemory को उनकी ज़रूरत नहीं है।) समर्थित engine install methods, सभी v0.19.7 पर pinned: ऊपर वाला prebuilt v0.19.7 binary, version pin **के साथ** upstream `sh` install script `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.19.7 sh` (macOS/Linux), और Docker image `iiidev/iii:0.19.7`। केवल `install.sh | sh` **latest** engine install करता है, जिसे agentmemory support नहीं करता; हमेशा `VERSION=0.19.7` पास करें। सबसे आसान: बस `npx @agentmemory/agentmemory` चलाएँ, जो pinned engine को आपके लिए `~/.agentmemory/bin` में ले आता है। --- diff --git a/READMEs/README.ja-JP.md b/READMEs/README.ja-JP.md index 04bb829ea1..624cc33c3a 100644 --- a/READMEs/README.ja-JP.md +++ b/READMEs/README.ja-JP.md @@ -124,7 +124,7 @@ npx はバージョン単位でキャッシュします。`npx -y @agentmemory/a
自前の iii エンジンを既に動かしている -agentmemory は iii-engine v0.11.2 にピン留めしており、異なるバージョンにはアタッチしません(worker は別のエンジンのプロトコルを話せません)。他のエンジンを停止してから `npx -y @agentmemory/agentmemory@latest` を実行してください。ピン留めされた v0.11.2 を `~/.agentmemory/bin` にインストールして実行し、あなた自身の `iii` には触れません。 +agentmemory は iii-engine v0.19.7 にピン留めしており、異なるバージョンにはアタッチしません(worker は別のエンジンのプロトコルを話せません)。他のエンジンを停止してから `npx -y @agentmemory/agentmemory@latest` を実行してください。ピン留めされた v0.19.7 を `~/.agentmemory/bin` にインストールして実行し、あなた自身の `iii` には触れません。
@@ -463,7 +463,7 @@ npx @agentmemory/agentmemory

Quick Start

-互換性:このリリースは安定版の `iii-sdk` `^0.11.0` と iii-engine v0.11.x を対象とします。 +互換性:このリリースは `iii-sdk` 0.19.7 を対象とし、iii-engine v0.19.7 にピン留めします。 ### 30 秒で試す @@ -517,7 +517,7 @@ npx @agentmemory/agentmemory import-jsonl ~/.claude/projects/-my-project/abc123. npx @agentmemory/agentmemory upgrade ``` -警告: このコマンドは現在のワークスペース/ランタイムを変更します。JavaScript 依存を更新したり、ピン留めされた Docker イメージ `iiidev/iii:0.11.2` を pull したりすることがあります。ピン留めされていない、あるいは新しい iii エンジンをインストールすることは決してありません。 +警告: このコマンドは現在のワークスペース/ランタイムを変更します。JavaScript 依存を更新したり、ピン留めされた Docker イメージ `iiidev/iii:0.19.7` を pull したりすることがあります。ピン留めされていない、あるいは新しい iii エンジンをインストールすることは決してありません。 実装の詳細は `src/cli.ts` を参照(`src/cli.ts:544-595` 付近の `runUpgrade`)。 @@ -722,15 +722,15 @@ npm install && npm run build && npm start `iii` が既にインストールされていれば、これでローカルの `iii-engine` で agentmemory が起動します。Docker が使える場合は Docker Compose にフォールバックします。REST、ストリーム、ビューワーはデフォルトで `127.0.0.1` にバインドします。 -`iii-engine` を手動でインストールしてください。**agentmemory は現在 `iii-engine` を `v0.11.2` にピン留めしています** — `v0.11.6` では `iii worker add` で何でもサンドボックス化する新モデルが導入されましたが、agentmemory はまだそれ向けにリファクタリングされていません。リファクタが完了次第ピンは解除されます。サンドボックスモデルへ手動移行済みなら `AGENTMEMORY_III_VERSION=` でオーバーライドできます。 +`iii-engine` を手動でインストールしてください。**agentmemory は現在 `iii-engine` を `v0.19.7` にピン留めしています** — `iii-sdk` 依存関係と同じリリースです。worker はそのエンジンの wire プロトコルを話し、0.20.0 で SDK の API 面が再編されたため、両者は agentmemory のリリースで一緒に更新されます。自前のエンジンを運用していて一致していると分かっている場合は `AGENTMEMORY_III_VERSION=` で上書きできます。 -- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.11.2/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` +- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.19.7/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` - **macOS x64:** `aarch64-apple-darwin` を `x86_64-apple-darwin` に置換 - **Linux x64:** `x86_64-unknown-linux-gnu` に置換 - **Linux arm64:** `aarch64-unknown-linux-gnu` に置換 -- **Windows:** [iii-hq/iii releases v0.11.2](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2) から `iii-x86_64-pc-windows-msvc.zip` をダウンロード、`iii.exe` を展開し PATH に追加 +- **Windows:** [iii-hq/iii releases v0.19.7](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7) から `iii-x86_64-pc-windows-msvc.zip` をダウンロード、`iii.exe` を展開し PATH に追加 -または Docker を使用(同梱の `docker-compose.yml` が `iiidev/iii:0.11.2` を pull します)。詳細ドキュメント:[iii.dev/docs](https://iii.dev/docs)。 +または Docker を使用(同梱の `docker-compose.yml` が `iiidev/iii:0.19.7` を pull します)。詳細ドキュメント:[iii.dev/docs](https://iii.dev/docs)。 ### Windows @@ -739,9 +739,9 @@ agentmemory は Windows 10/11 で動作しますが、Node.js パッケージだ **選択肢 A: ビルド済み Windows バイナリ(推奨)** ```powershell -# 1. ブラウザで https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2 を開く -# (engine v0.11.6+ が要求する新しいサンドボックスモデルへ -# agentmemory がリファクタリングされるまで v0.11.2 にピン留め) +# 1. ブラウザで https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7 を開く +# (agentmemory はエンジンを iii-sdk と同じリリースにピン留めしています。 +# 現在のペアは v0.19.7) # 2. iii-x86_64-pc-windows-msvc.zip をダウンロード # (ARM マシンの場合は iii-aarch64-pc-windows-msvc.zip) # 3. iii.exe を PATH 上のどこかに展開、または以下に配置: @@ -749,7 +749,7 @@ agentmemory は Windows 10/11 で動作しますが、Node.js パッケージだ # (agentmemory はこの場所を自動でチェックします) # 4. 確認: iii --version -# 出力: 0.11.2 +# 出力: 0.19.7 # 5. その後 agentmemory を通常通り起動: npx -y @agentmemory/agentmemory @@ -781,7 +781,7 @@ npx -y @agentmemory/mcp | ポート競合 | `netstat -ano \| findstr :3111` でバインドを確認、kill するか `--port ` を使用 | | Docker をインストール済みなのにフォールバックがスキップされる | Docker Desktop が実際に動作している(システムトレイアイコン)ことを確認 | -> 注意: iii **エンジン** はビルド済みバイナリであり、cargo クレートではありません — `cargo install` でインストールしようとしないでください。(iii **SDK** は crates.io、npm、PyPI に公開されていますが、agentmemory には不要です。)サポートされるエンジンのインストール方法はすべて v0.11.2 にピン留めされています: 上記のビルド済み v0.11.2 バイナリ、バージョンピン**付き**の上流 `sh` インストールスクリプト `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.11.2 sh`(macOS/Linux)、および Docker イメージ `iiidev/iii:0.11.2`。単なる `install.sh | sh` は **最新** のエンジンをインストールしますが、agentmemory はそれをサポートしていません — 必ず `VERSION=0.11.2` を渡してください。最も簡単なのは、`npx @agentmemory/agentmemory` を実行するだけです。これがピン留めされたエンジンを `~/.agentmemory/bin` に取得してくれます。 +> 注意: iii **エンジン** はビルド済みバイナリであり、cargo クレートではありません — `cargo install` でインストールしようとしないでください。(iii **SDK** は crates.io、npm、PyPI に公開されていますが、agentmemory には不要です。)サポートされるエンジンのインストール方法はすべて v0.19.7 にピン留めされています: 上記のビルド済み v0.19.7 バイナリ、バージョンピン**付き**の上流 `sh` インストールスクリプト `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.19.7 sh`(macOS/Linux)、および Docker イメージ `iiidev/iii:0.19.7`。単なる `install.sh | sh` は **最新** のエンジンをインストールしますが、agentmemory はそれをサポートしていません — 必ず `VERSION=0.19.7` を渡してください。最も簡単なのは、`npx @agentmemory/agentmemory` を実行するだけです。これがピン留めされたエンジンを `~/.agentmemory/bin` に取得してくれます。 --- diff --git a/READMEs/README.ko-KR.md b/READMEs/README.ko-KR.md index b73fa49e10..3c6843ac8a 100644 --- a/READMEs/README.ko-KR.md +++ b/READMEs/README.ko-KR.md @@ -124,7 +124,7 @@ npx는 버전별로 캐싱합니다. `npx -y @agentmemory/agentmemory@latest`로
이미 자체 iii 엔진을 실행 중인 경우 -agentmemory는 iii-engine v0.11.2를 고정하며 다른 버전에는 연결되지 않습니다(워커가 다른 엔진의 프로토콜을 말할 수 없습니다). 다른 엔진을 중지한 후 `npx -y @agentmemory/agentmemory@latest`를 실행하십시오. 고정된 v0.11.2를 `~/.agentmemory/bin`에 설치·실행하며, 기존 `iii`는 건드리지 않습니다. +agentmemory는 iii-engine v0.19.7를 고정하며 다른 버전에는 연결되지 않습니다(워커가 다른 엔진의 프로토콜을 말할 수 없습니다). 다른 엔진을 중지한 후 `npx -y @agentmemory/agentmemory@latest`를 실행하십시오. 고정된 v0.19.7를 `~/.agentmemory/bin`에 설치·실행하며, 기존 `iii`는 건드리지 않습니다.
@@ -463,7 +463,7 @@ npx @agentmemory/agentmemory

빠른 시작

-호환성: 이 릴리스는 안정 버전 `iii-sdk` `^0.11.0`과 iii-engine v0.11.x를 대상으로 합니다. +호환성: 이 릴리스는 `iii-sdk` 0.19.7을 대상으로 하며 iii-engine을 v0.19.7로 고정합니다. ### 30초 만에 사용해 보기 @@ -515,7 +515,7 @@ npx @agentmemory/agentmemory import-jsonl ~/.claude/projects/-my-project/abc123. npx @agentmemory/agentmemory upgrade ``` -경고: 이 명령은 현재 workspace/런타임을 변경합니다. JavaScript 의존성을 업데이트할 수 있으며, 고정된 Docker 이미지 `iiidev/iii:0.11.2`를 pull할 수 있습니다. 고정되지 않았거나 더 새로운 iii 엔진을 설치하는 일은 절대 없습니다. +경고: 이 명령은 현재 workspace/런타임을 변경합니다. JavaScript 의존성을 업데이트할 수 있으며, 고정된 Docker 이미지 `iiidev/iii:0.19.7`를 pull할 수 있습니다. 고정되지 않았거나 더 새로운 iii 엔진을 설치하는 일은 절대 없습니다. 구현 세부 사항은 `src/cli.ts`에 있습니다 (`runUpgrade`는 `src/cli.ts:544-595` 부근 참고). @@ -719,15 +719,15 @@ npm install && npm run build && npm start `iii`가 이미 설치되어 있으면 로컬 `iii-engine`으로 agentmemory를 시작하고, Docker가 사용 가능하면 Docker Compose로 폴백합니다. REST, 스트림, 뷰어는 기본적으로 `127.0.0.1`에 바인딩됩니다. -`iii-engine`을 수동으로 설치하십시오. **agentmemory는 현재 `iii-engine`을 `v0.11.2`로 고정합니다**. `v0.11.6`은 모든 것을 `iii worker add`를 통해 샌드박스화하는 새 모델을 도입했는데 agentmemory는 아직 이를 위해 리팩터링되지 않았기 때문입니다. 리팩터링이 완료되면 고정이 풀립니다. 수동으로 sandbox 모델로 마이그레이션했다면 `AGENTMEMORY_III_VERSION=`으로 덮어쓰십시오. +`iii-engine`을 수동으로 설치하십시오. **agentmemory는 현재 `iii-engine`을 `v0.19.7`로 고정합니다**. `iii-sdk` 의존성과 같은 릴리스입니다. 워커는 해당 엔진의 wire 프로토콜을 사용하고 0.20.0에서 SDK 표면이 재구성되었으므로, 둘은 agentmemory 릴리스에서 함께 올라갑니다. 직접 운영하는 엔진이 일치한다고 확신한다면 `AGENTMEMORY_III_VERSION=`으로 재정의하세요. -- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.11.2/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` +- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.19.7/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` - **macOS x64:** `aarch64-apple-darwin`을 `x86_64-apple-darwin`으로 교체 - **Linux x64:** `x86_64-unknown-linux-gnu`로 교체 - **Linux arm64:** `aarch64-unknown-linux-gnu`로 교체 -- **Windows:** [iii-hq/iii releases v0.11.2](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2)에서 `iii-x86_64-pc-windows-msvc.zip`을 다운로드하고 `iii.exe`를 추출한 후 PATH에 추가 +- **Windows:** [iii-hq/iii releases v0.19.7](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7)에서 `iii-x86_64-pc-windows-msvc.zip`을 다운로드하고 `iii.exe`를 추출한 후 PATH에 추가 -또는 Docker 사용 (번들된 `docker-compose.yml`이 `iiidev/iii:0.11.2`를 pull). 전체 문서: [iii.dev/docs](https://iii.dev/docs). +또는 Docker 사용 (번들된 `docker-compose.yml`이 `iiidev/iii:0.19.7`를 pull). 전체 문서: [iii.dev/docs](https://iii.dev/docs). ### Windows @@ -736,9 +736,9 @@ agentmemory는 Windows 10/11에서 실행되지만, Node.js 패키지만으로 **옵션 A: 사전 빌드된 Windows 바이너리 (권장)** ```powershell -# 1. Open https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2 in your browser -# (we pin to v0.11.2 until agentmemory refactors for the new sandbox -# model that engine v0.11.6+ requires) +# 1. Open https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7 in your browser +# (agentmemory pins the engine to the same release as its iii-sdk; +# v0.19.7 is the current pair) # 2. Download iii-x86_64-pc-windows-msvc.zip # (or iii-aarch64-pc-windows-msvc.zip if you're on an ARM machine) # 3. Extract iii.exe somewhere on PATH, or place it at: @@ -746,7 +746,7 @@ agentmemory는 Windows 10/11에서 실행되지만, Node.js 패키지만으로 # (agentmemory checks that location automatically) # 4. Verify: iii --version -# Should print: 0.11.2 +# Should print: 0.19.7 # 5. Then run agentmemory as usual: npx -y @agentmemory/agentmemory @@ -778,7 +778,7 @@ npx -y @agentmemory/mcp | 포트 충돌 | `netstat -ano \| findstr :3111`로 무엇이 바인딩되어 있는지 확인하고 종료하거나 `--port ` 사용 | | Docker가 설치되어 있어도 Docker 폴백을 건너뜀 | Docker Desktop이 실제로 실행 중인지 확인 (시스템 트레이 아이콘) | -> 참고: iii **엔진**은 사전 빌드된 바이너리이며 cargo 크레이트가 아니므로, `cargo install`로 설치하려 하지 마세요. (iii **SDK**는 crates.io, npm, PyPI에 게시되어 있지만 agentmemory에는 필요하지 않습니다.) 지원되는 엔진 설치 방법은 모두 v0.11.2에 고정되어 있습니다: 위의 사전 빌드된 v0.11.2 바이너리, 버전 핀**을 포함한** 업스트림 `sh` 설치 스크립트 `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.11.2 sh` (macOS/Linux), 그리고 Docker 이미지 `iiidev/iii:0.11.2`. 그냥 `install.sh | sh`를 실행하면 **최신** 엔진이 설치되는데, agentmemory는 이를 지원하지 않습니다; 항상 `VERSION=0.11.2`를 전달하세요. 가장 쉬운 방법은 그냥 `npx @agentmemory/agentmemory`를 실행하는 것입니다. 이 명령이 고정된 엔진을 `~/.agentmemory/bin`에 가져다 줍니다. +> 참고: iii **엔진**은 사전 빌드된 바이너리이며 cargo 크레이트가 아니므로, `cargo install`로 설치하려 하지 마세요. (iii **SDK**는 crates.io, npm, PyPI에 게시되어 있지만 agentmemory에는 필요하지 않습니다.) 지원되는 엔진 설치 방법은 모두 v0.19.7에 고정되어 있습니다: 위의 사전 빌드된 v0.19.7 바이너리, 버전 핀**을 포함한** 업스트림 `sh` 설치 스크립트 `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.19.7 sh` (macOS/Linux), 그리고 Docker 이미지 `iiidev/iii:0.19.7`. 그냥 `install.sh | sh`를 실행하면 **최신** 엔진이 설치되는데, agentmemory는 이를 지원하지 않습니다; 항상 `VERSION=0.19.7`를 전달하세요. 가장 쉬운 방법은 그냥 `npx @agentmemory/agentmemory`를 실행하는 것입니다. 이 명령이 고정된 엔진을 `~/.agentmemory/bin`에 가져다 줍니다. --- diff --git a/READMEs/README.pt-BR.md b/READMEs/README.pt-BR.md index fb245e9370..30f5d8e2a5 100644 --- a/READMEs/README.pt-BR.md +++ b/READMEs/README.pt-BR.md @@ -124,7 +124,7 @@ O npx faz cache por versão. Force a mais recente com `npx -y @agentmemory/agent
Já roda seu próprio engine iii -agentmemory fixa o iii-engine em v0.11.2 e não se conecta a uma versão diferente (o worker não fala o protocolo de outro engine). Pare o outro engine e rode `npx -y @agentmemory/agentmemory@latest`. Ele instala e executa a v0.11.2 fixada em `~/.agentmemory/bin`, deixando o seu próprio `iii` intocado. +agentmemory fixa o iii-engine em v0.19.7 e não se conecta a uma versão diferente (o worker não fala o protocolo de outro engine). Pare o outro engine e rode `npx -y @agentmemory/agentmemory@latest`. Ele instala e executa a v0.19.7 fixada em `~/.agentmemory/bin`, deixando o seu próprio `iii` intocado.
@@ -463,7 +463,7 @@ Nenhum deles faz captura automática a partir de hooks de agentes de codificaç

Início rápido

-Compatibilidade: este release tem como alvo o `iii-sdk` estável `^0.11.0` e o iii-engine v0.11.x. +Compatibilidade: este release tem como alvo o `iii-sdk` 0.19.7 e fixa o iii-engine em v0.19.7. ### Experimente em 30 segundos @@ -517,7 +517,7 @@ Use o comando de manutenção quando você intencionalmente quiser atualizar seu npx @agentmemory/agentmemory upgrade ``` -Aviso: este comando muta o workspace/runtime atual. Pode atualizar dependências JavaScript e puxar a imagem Docker fixada `iiidev/iii:0.11.2`. Nunca instala um engine iii sem fixação ou mais recente. +Aviso: este comando muta o workspace/runtime atual. Pode atualizar dependências JavaScript e puxar a imagem Docker fixada `iiidev/iii:0.19.7`. Nunca instala um engine iii sem fixação ou mais recente. Detalhes de implementação estão em `src/cli.ts` (veja `runUpgrade` na região `src/cli.ts:544-595`). @@ -721,15 +721,15 @@ npm install && npm run build && npm start Isso inicia o agentmemory com um `iii-engine` local se `iii` já estiver instalado, ou cai para Docker Compose se o Docker estiver disponível. REST, streams e o viewer fazem bind em `127.0.0.1` por padrão. -Instale o `iii-engine` manualmente. **O agentmemory atualmente fixa o `iii-engine` em `v0.11.2`**. A `v0.11.6` introduz um novo modelo que faz sandbox de tudo via `iii worker add` que o agentmemory ainda não foi refatorado para usar. O pin sai assim que o refactor cair. Sobrescreva com `AGENTMEMORY_III_VERSION=` se você migrou manualmente para o modelo de sandbox. +Instale o `iii-engine` manualmente. **O agentmemory atualmente fixa o `iii-engine` em `v0.19.7`**, o mesmo release da sua dependência `iii-sdk`; o worker fala o protocolo desse engine, e a 0.20.0 reorganizou a superfície do SDK, então os dois avançam juntos a cada release do agentmemory. Sobrescreva com `AGENTMEMORY_III_VERSION=` se você roda seu próprio engine e sabe que ele corresponde. -- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.11.2/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` +- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.19.7/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` - **macOS x64:** troque `aarch64-apple-darwin` por `x86_64-apple-darwin` - **Linux x64:** troque por `x86_64-unknown-linux-gnu` - **Linux arm64:** troque por `aarch64-unknown-linux-gnu` -- **Windows:** baixe `iii-x86_64-pc-windows-msvc.zip` de [iii-hq/iii releases v0.11.2](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2), extraia `iii.exe`, adicione ao PATH +- **Windows:** baixe `iii-x86_64-pc-windows-msvc.zip` de [iii-hq/iii releases v0.19.7](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7), extraia `iii.exe`, adicione ao PATH -Ou use Docker (o `docker-compose.yml` empacotado puxa `iiidev/iii:0.11.2`). Docs completas: [iii.dev/docs](https://iii.dev/docs). +Ou use Docker (o `docker-compose.yml` empacotado puxa `iiidev/iii:0.19.7`). Docs completas: [iii.dev/docs](https://iii.dev/docs). ### Windows @@ -738,9 +738,9 @@ agentmemory roda em Windows 10/11, mas só o pacote Node.js não é suficiente; **Opção A: binário Windows pré-compilado (recomendado)** ```powershell -# 1. Open https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2 in your browser -# (we pin to v0.11.2 until agentmemory refactors for the new sandbox -# model that engine v0.11.6+ requires) +# 1. Open https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7 in your browser +# (agentmemory pins the engine to the same release as its iii-sdk; +# v0.19.7 is the current pair) # 2. Download iii-x86_64-pc-windows-msvc.zip # (or iii-aarch64-pc-windows-msvc.zip if you're on an ARM machine) # 3. Extract iii.exe somewhere on PATH, or place it at: @@ -748,7 +748,7 @@ agentmemory roda em Windows 10/11, mas só o pacote Node.js não é suficiente; # (agentmemory checks that location automatically) # 4. Verify: iii --version -# Should print: 0.11.2 +# Should print: 0.19.7 # 5. Then run agentmemory as usual: npx -y @agentmemory/agentmemory @@ -780,7 +780,7 @@ npx -y @agentmemory/mcp | Conflito de porta | `netstat -ano \| findstr :3111` para ver o que está em bind, mate o processo ou use `--port ` | | Fallback do Docker é pulado mesmo com Docker instalado | Confira se o Docker Desktop está de fato rodando (ícone na bandeja do sistema) | -> Nota: o **engine** iii é um binário pré-compilado, não um crate do cargo, então não tente instalá-lo com `cargo install`. (Os **SDKs** do iii são publicados no crates.io, npm e PyPI, mas o agentmemory não precisa deles.) Métodos de instalação do engine suportados, todos fixados em v0.11.2: o binário pré-compilado v0.11.2 acima, o script de instalação `sh` upstream **com a fixação de versão** `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.11.2 sh` (macOS/Linux) e a imagem Docker `iiidev/iii:0.11.2`. Um simples `install.sh | sh` instala o engine **mais recente**, que o agentmemory não suporta; sempre passe `VERSION=0.11.2`. O mais fácil de tudo: basta rodar `npx @agentmemory/agentmemory`, que busca o engine fixado em `~/.agentmemory/bin` para você. +> Nota: o **engine** iii é um binário pré-compilado, não um crate do cargo, então não tente instalá-lo com `cargo install`. (Os **SDKs** do iii são publicados no crates.io, npm e PyPI, mas o agentmemory não precisa deles.) Métodos de instalação do engine suportados, todos fixados em v0.19.7: o binário pré-compilado v0.19.7 acima, o script de instalação `sh` upstream **com a fixação de versão** `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.19.7 sh` (macOS/Linux) e a imagem Docker `iiidev/iii:0.19.7`. Um simples `install.sh | sh` instala o engine **mais recente**, que o agentmemory não suporta; sempre passe `VERSION=0.19.7`. O mais fácil de tudo: basta rodar `npx @agentmemory/agentmemory`, que busca o engine fixado em `~/.agentmemory/bin` para você. --- diff --git a/READMEs/README.ru-RU.md b/READMEs/README.ru-RU.md index 0e6f43df53..1c349f591f 100644 --- a/READMEs/README.ru-RU.md +++ b/READMEs/README.ru-RU.md @@ -124,7 +124,7 @@ npx кеширует пакеты по версиям. Принудительн
Уже запущен собственный движок iii -agentmemory закреплён на iii-engine v0.11.2 и не подключится к другой версии (воркер не умеет говорить на протоколе другого движка). Остановите другой движок и запустите `npx -y @agentmemory/agentmemory@latest` — он установит и запустит закреплённый v0.11.2 в `~/.agentmemory/bin`, не трогая ваш собственный `iii`. +agentmemory закреплён на iii-engine v0.19.7 и не подключится к другой версии (воркер не умеет говорить на протоколе другого движка). Остановите другой движок и запустите `npx -y @agentmemory/agentmemory@latest` — он установит и запустит закреплённый v0.19.7 в `~/.agentmemory/bin`, не трогая ваш собственный `iii`.
@@ -463,7 +463,7 @@ npx @agentmemory/agentmemory

Быстрый старт

-Совместимость: этот релиз нацелен на стабильный `iii-sdk` `^0.11.0` и iii-engine v0.11.x. +Совместимость: этот релиз нацелен на `iii-sdk` 0.19.7 и закрепляет iii-engine v0.19.7. ### Попробуйте за 30 секунд @@ -517,7 +517,7 @@ npx @agentmemory/agentmemory import-jsonl ~/.claude/projects/-my-project/abc123. npx @agentmemory/agentmemory upgrade ``` -Внимание: команда меняет текущее рабочее окружение / runtime. Она может обновлять JavaScript-зависимости и стянуть закреплённый Docker-образ `iiidev/iii:0.11.2`. Она никогда не устанавливает незакреплённый или более новый движок iii. +Внимание: команда меняет текущее рабочее окружение / runtime. Она может обновлять JavaScript-зависимости и стянуть закреплённый Docker-образ `iiidev/iii:0.19.7`. Она никогда не устанавливает незакреплённый или более новый движок iii. Детали реализации — в `src/cli.ts` (см. `runUpgrade` в районе `src/cli.ts:544-595`). @@ -721,15 +721,15 @@ npm install && npm run build && npm start Это поднимает agentmemory с локальным `iii-engine`, если `iii` уже установлен, либо откатывается к Docker Compose, если есть Docker. REST, стримы и просмотрщик по умолчанию слушают на `127.0.0.1`. -Установите `iii-engine` вручную. **agentmemory сейчас зафиксирован на `iii-engine` `v0.11.2`** — `v0.11.6` вводит новую модель «всё через `iii worker add` в sandbox», под которую agentmemory ещё не отрефакторен. Закрепление снимется, как только рефакторинг будет завершён. Переопределите через `AGENTMEMORY_III_VERSION=`, если вы вручную перешли на sandbox-модель. +Установите `iii-engine` вручную. **agentmemory сейчас зафиксирован на `iii-engine` `v0.19.7`** — той же версии, что и его зависимость `iii-sdk`; воркер говорит на wire-протоколе именно этого движка, а 0.20.0 перестроил поверхность SDK, поэтому оба обновляются вместе в релизах agentmemory. Переопределите через `AGENTMEMORY_III_VERSION=`, если запускаете собственный движок и уверены, что версии совпадают. -- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.11.2/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` +- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.19.7/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` - **macOS x64:** замените `aarch64-apple-darwin` на `x86_64-apple-darwin` - **Linux x64:** замените на `x86_64-unknown-linux-gnu` - **Linux arm64:** замените на `aarch64-unknown-linux-gnu` -- **Windows:** скачайте `iii-x86_64-pc-windows-msvc.zip` из [iii-hq/iii releases v0.11.2](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2), распакуйте `iii.exe`, добавьте в PATH +- **Windows:** скачайте `iii-x86_64-pc-windows-msvc.zip` из [iii-hq/iii releases v0.19.7](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7), распакуйте `iii.exe`, добавьте в PATH -Либо используйте Docker (входящий в комплект `docker-compose.yml` тянет `iiidev/iii:0.11.2`). Полная документация: [iii.dev/docs](https://iii.dev/docs). +Либо используйте Docker (входящий в комплект `docker-compose.yml` тянет `iiidev/iii:0.19.7`). Полная документация: [iii.dev/docs](https://iii.dev/docs). ### Windows @@ -738,9 +738,9 @@ agentmemory работает на Windows 10/11, но одного Node.js-па **Вариант A: готовый Windows-бинарь (рекомендуется)** ```powershell -# 1. Open https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2 in your browser -# (we pin to v0.11.2 until agentmemory refactors for the new sandbox -# model that engine v0.11.6+ requires) +# 1. Open https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7 in your browser +# (agentmemory pins the engine to the same release as its iii-sdk; +# v0.19.7 is the current pair) # 2. Download iii-x86_64-pc-windows-msvc.zip # (or iii-aarch64-pc-windows-msvc.zip if you're on an ARM machine) # 3. Extract iii.exe somewhere on PATH, or place it at: @@ -748,7 +748,7 @@ agentmemory работает на Windows 10/11, но одного Node.js-па # (agentmemory checks that location automatically) # 4. Verify: iii --version -# Should print: 0.11.2 +# Should print: 0.19.7 # 5. Then run agentmemory as usual: npx -y @agentmemory/agentmemory @@ -780,7 +780,7 @@ npx -y @agentmemory/mcp | Конфликт порта | `netstat -ano \| findstr :3111`, чтобы понять, что занимает порт, затем убить процесс или использовать `--port ` | | Откат на Docker пропускается, хотя Docker установлен | Убедитесь, что Docker Desktop действительно запущен (иконка в трее) | -> Примечание: **движок** iii — это готовый бинарь, а не cargo-крейт, не пытайтесь установить его через `cargo install`. (**SDK** iii опубликованы на crates.io, npm и PyPI, но agentmemory они не нужны.) Поддерживаемые способы установки движка, все закреплены на v0.11.2: готовый бинарь v0.11.2 выше, upstream-`sh`-скрипт **с закреплением версии** `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.11.2 sh` (macOS/Linux) и Docker-образ `iiidev/iii:0.11.2`. Простой `install.sh | sh` устанавливает **последний** движок, который agentmemory не поддерживает, — всегда передавайте `VERSION=0.11.2`. Самый простой вариант: просто запустите `npx @agentmemory/agentmemory`, который сам загрузит закреплённый движок в `~/.agentmemory/bin`. +> Примечание: **движок** iii — это готовый бинарь, а не cargo-крейт, не пытайтесь установить его через `cargo install`. (**SDK** iii опубликованы на crates.io, npm и PyPI, но agentmemory они не нужны.) Поддерживаемые способы установки движка, все закреплены на v0.19.7: готовый бинарь v0.19.7 выше, upstream-`sh`-скрипт **с закреплением версии** `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.19.7 sh` (macOS/Linux) и Docker-образ `iiidev/iii:0.19.7`. Простой `install.sh | sh` устанавливает **последний** движок, который agentmemory не поддерживает, — всегда передавайте `VERSION=0.19.7`. Самый простой вариант: просто запустите `npx @agentmemory/agentmemory`, который сам загрузит закреплённый движок в `~/.agentmemory/bin`. --- diff --git a/READMEs/README.tr-TR.md b/READMEs/README.tr-TR.md index 90544a2668..1c122190db 100644 --- a/READMEs/README.tr-TR.md +++ b/READMEs/README.tr-TR.md @@ -124,7 +124,7 @@ npx sürüm bazında önbelleğe alır. En güncelini `npx -y @agentmemory/agent
Zaten kendi iii engine'inizi çalıştırıyorsanız -agentmemory iii-engine'i v0.11.2'ye sabitler ve farklı bir sürüme bağlanmaz (worker başka bir engine'in protokolünü konuşamaz). Diğer engine'i durdurun, ardından `npx -y @agentmemory/agentmemory@latest` çalıştırın. Sabitlenmiş v0.11.2'yi `~/.agentmemory/bin` içine kurup çalıştırır ve kendi `iii`'nizi olduğu gibi bırakır. +agentmemory iii-engine'i v0.19.7'ye sabitler ve farklı bir sürüme bağlanmaz (worker başka bir engine'in protokolünü konuşamaz). Diğer engine'i durdurun, ardından `npx -y @agentmemory/agentmemory@latest` çalıştırın. Sabitlenmiş v0.19.7'yi `~/.agentmemory/bin` içine kurup çalıştırır ve kendi `iii`'nizi olduğu gibi bırakır.
@@ -463,7 +463,7 @@ Bunların hiçbiri kodlama-ajanı hook'larından otomatik yakalama yapmaz, yerel

Quick Start

-Uyumluluk: bu sürüm kararlı `iii-sdk` `^0.11.0` ve iii-engine v0.11.x'i hedefler. +Uyumluluk: bu sürüm `iii-sdk` 0.19.7'yi hedefler ve iii-engine'i v0.19.7'ye sabitler. ### 30 saniyede deneyin @@ -515,7 +515,7 @@ Yerel runtime'ınızı bilinçli olarak güncellemek istediğinizde bakım komut npx @agentmemory/agentmemory upgrade ``` -Uyarı: bu komut mevcut çalışma alanını/runtime'ı değiştirir. JavaScript bağımlılıklarını güncelleyebilir ve sabitlenmiş `iiidev/iii:0.11.2` Docker imajını çekebilir. Asla sabitlenmemiş ya da daha yeni bir iii motoru kurmaz. +Uyarı: bu komut mevcut çalışma alanını/runtime'ı değiştirir. JavaScript bağımlılıklarını güncelleyebilir ve sabitlenmiş `iiidev/iii:0.19.7` Docker imajını çekebilir. Asla sabitlenmemiş ya da daha yeni bir iii motoru kurmaz. Uygulama detayları `src/cli.ts` içinde (`src/cli.ts:544-595` bölgesi civarında `runUpgrade`'a bakın). @@ -719,15 +719,15 @@ npm install && npm run build && npm start Bu, `iii` zaten kuruluysa yerel bir `iii-engine` ile agentmemory'yi başlatır veya Docker mevcutsa Docker Compose'a düşer. REST, stream'ler ve görüntüleyici varsayılan olarak `127.0.0.1`'e bağlanır. -`iii-engine`'i manuel olarak kurun. **agentmemory şu anda `iii-engine`'i `v0.11.2`'ye sabitliyor**. `v0.11.6`, agentmemory'nin henüz refactor edilmediği yeni bir sandbox-her-şey-üzerinden-`iii worker add` modelini tanıtıyor. Refactor geldiğinde sabitleme kaldırılır. Sandbox modeline manuel olarak geçtiyseniz `AGENTMEMORY_III_VERSION=` ile override edin. +`iii-engine`'i manuel olarak kurun. **agentmemory şu anda `iii-engine`'i `v0.19.7`'ye sabitliyor**; bu, `iii-sdk` bağımlılığıyla aynı sürümdür. Worker tam olarak o engine'in wire protokolünü konuşur ve 0.20.0 SDK yüzeyini yeniden düzenlediği için ikisi agentmemory sürümlerinde birlikte yükseltilir. Kendi engine'inizi çalıştırıyor ve eşleştiğinden eminseniz `AGENTMEMORY_III_VERSION=` ile geçersiz kılın. -- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.11.2/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` +- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.19.7/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` - **macOS x64:** `aarch64-apple-darwin`'i `x86_64-apple-darwin` ile değiştirin - **Linux x64:** `x86_64-unknown-linux-gnu` ile değiştirin - **Linux arm64:** `aarch64-unknown-linux-gnu` ile değiştirin -- **Windows:** [iii-hq/iii releases v0.11.2](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2)'den `iii-x86_64-pc-windows-msvc.zip`'i indirin, `iii.exe`'yi çıkarın, PATH'e ekleyin +- **Windows:** [iii-hq/iii releases v0.19.7](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7)'den `iii-x86_64-pc-windows-msvc.zip`'i indirin, `iii.exe`'yi çıkarın, PATH'e ekleyin -Veya Docker kullanın (paketli `docker-compose.yml` `iiidev/iii:0.11.2`'yi çeker). Tam dokümanlar: [iii.dev/docs](https://iii.dev/docs). +Veya Docker kullanın (paketli `docker-compose.yml` `iiidev/iii:0.19.7`'yi çeker). Tam dokümanlar: [iii.dev/docs](https://iii.dev/docs). ### Windows @@ -736,9 +736,9 @@ agentmemory Windows 10/11'de çalışır, ancak yalnızca Node.js paketi yeterli **Seçenek A: önceden derlenmiş Windows ikiliği (önerilen)** ```powershell -# 1. Tarayıcınızda https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2 açın -# (engine v0.11.6+'nın gerektirdiği yeni sandbox modeli için -# agentmemory refactor edilene kadar v0.11.2'ye sabitliyoruz) +# 1. Tarayıcınızda https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7 açın +# (agentmemory, engine'i iii-sdk ile aynı sürüme sabitler; +# mevcut çift v0.19.7) # 2. iii-x86_64-pc-windows-msvc.zip indirin # (veya ARM makinedeyseniz iii-aarch64-pc-windows-msvc.zip) # 3. iii.exe'yi PATH'te bir yere çıkarın veya şuraya yerleştirin: @@ -746,7 +746,7 @@ agentmemory Windows 10/11'de çalışır, ancak yalnızca Node.js paketi yeterli # (agentmemory bu konumu otomatik kontrol eder) # 4. Doğrulayın: iii --version -# Şunu yazmalı: 0.11.2 +# Şunu yazmalı: 0.19.7 # 5. Ardından agentmemory'yi her zamanki gibi çalıştırın: npx -y @agentmemory/agentmemory @@ -778,7 +778,7 @@ npx -y @agentmemory/mcp | Port çakışması | `netstat -ano \| findstr :3111` ile neyin bağlı olduğunu görün, ardından öldürün veya `--port ` kullanın | | Docker kurulu olsa bile Docker fallback atlanıyor | Docker Desktop'ın gerçekten çalıştığından emin olun (sistem tepsisi simgesi) | -> Not: iii **motoru** önceden derlenmiş bir ikiliktir, bir cargo crate'i değildir, bu yüzden onu `cargo install` ile kurmaya çalışmayın. (iii **SDK'ları** crates.io, npm ve PyPI'de yayımlanmıştır, ancak agentmemory bunlara ihtiyaç duymaz.) Desteklenen motor kurulum yöntemleri, hepsi v0.11.2'ye sabitlenmiştir: yukarıdaki önceden derlenmiş v0.11.2 ikiliği, sürüm sabitlemesi **ile** upstream `sh` kurulum scripti `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.11.2 sh` (macOS/Linux) ve Docker imajı `iiidev/iii:0.11.2`. Yalın bir `install.sh | sh`, agentmemory'nin desteklemediği **en son** motoru kurar; her zaman `VERSION=0.11.2` geçirin. Hepsinden kolayı: sadece `npx @agentmemory/agentmemory` çalıştırın; bu, sabitlenmiş motoru sizin için `~/.agentmemory/bin` dizinine indirir. +> Not: iii **motoru** önceden derlenmiş bir ikiliktir, bir cargo crate'i değildir, bu yüzden onu `cargo install` ile kurmaya çalışmayın. (iii **SDK'ları** crates.io, npm ve PyPI'de yayımlanmıştır, ancak agentmemory bunlara ihtiyaç duymaz.) Desteklenen motor kurulum yöntemleri, hepsi v0.19.7'ye sabitlenmiştir: yukarıdaki önceden derlenmiş v0.19.7 ikiliği, sürüm sabitlemesi **ile** upstream `sh` kurulum scripti `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.19.7 sh` (macOS/Linux) ve Docker imajı `iiidev/iii:0.19.7`. Yalın bir `install.sh | sh`, agentmemory'nin desteklemediği **en son** motoru kurar; her zaman `VERSION=0.19.7` geçirin. Hepsinden kolayı: sadece `npx @agentmemory/agentmemory` çalıştırın; bu, sabitlenmiş motoru sizin için `~/.agentmemory/bin` dizinine indirir. --- diff --git a/READMEs/README.zh-CN.md b/READMEs/README.zh-CN.md index bac81588f2..1030e02d42 100644 --- a/READMEs/README.zh-CN.md +++ b/READMEs/README.zh-CN.md @@ -124,7 +124,7 @@ npx 会按版本缓存。用 `npx -y @agentmemory/agentmemory@latest` 强制拉
已在运行自己的 iii 引擎 -agentmemory 固定 iii-engine v0.11.2,不会挂接到其他版本(worker 无法使用其他引擎的协议)。停止另一个引擎,然后运行 `npx -y @agentmemory/agentmemory@latest`。它会在 `~/.agentmemory/bin` 安装并运行固定的 v0.11.2,不动你自己的 `iii`。 +agentmemory 固定 iii-engine v0.19.7,不会挂接到其他版本(worker 无法使用其他引擎的协议)。停止另一个引擎,然后运行 `npx -y @agentmemory/agentmemory@latest`。它会在 `~/.agentmemory/bin` 安装并运行固定的 v0.19.7,不动你自己的 `iii`。
@@ -463,7 +463,7 @@ npx @agentmemory/agentmemory

Quick Start

-兼容性:此版本面向稳定的 `iii-sdk` `^0.11.0` 和 iii-engine v0.11.x。 +兼容性:此版本面向 `iii-sdk` 0.19.7,并将 iii-engine 固定在 v0.19.7。 ### 30 秒体验 @@ -515,7 +515,7 @@ npx @agentmemory/agentmemory import-jsonl ~/.claude/projects/-my-project/abc123. npx @agentmemory/agentmemory upgrade ``` -警告:此命令会变更当前工作空间/运行时。它可能更新 JavaScript 依赖,并拉取固定版本的 Docker 镜像 `iiidev/iii:0.11.2`。它绝不会安装未固定版本或更新的 iii 引擎。 +警告:此命令会变更当前工作空间/运行时。它可能更新 JavaScript 依赖,并拉取固定版本的 Docker 镜像 `iiidev/iii:0.19.7`。它绝不会安装未固定版本或更新的 iii 引擎。 实现细节见 `src/cli.ts`(参考 `src/cli.ts:544-595` 附近的 `runUpgrade`)。 @@ -720,15 +720,15 @@ npm install && npm run build && npm start 如果已经安装 `iii`,这会以本地 `iii-engine` 启动 agentmemory;如果 Docker 可用,则回退到 Docker Compose。REST、流和查看器默认绑定到 `127.0.0.1`。 -手动安装 `iii-engine`。**agentmemory 当前将 `iii-engine` 固定在 `v0.11.2`**。`v0.11.6` 引入了新的「通过 `iii worker add` 沙盒化一切」模型,agentmemory 尚未为此重构。重构落地后即解除固定。如果你已经手动迁移到沙盒模型,可用 `AGENTMEMORY_III_VERSION=` 覆盖。 +手动安装 `iii-engine`。**agentmemory 当前将 `iii-engine` 固定在 `v0.19.7`**,与其 `iii-sdk` 依赖是同一个版本;worker 使用的是该引擎的 wire 协议,而 0.20.0 重组了 SDK 接口,因此两者在 agentmemory 的每个版本中一起升级。如果你运行自己的引擎并确定版本匹配,可用 `AGENTMEMORY_III_VERSION=` 覆盖。 -- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.11.2/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` +- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.19.7/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` - **macOS x64:** 把 `aarch64-apple-darwin` 换成 `x86_64-apple-darwin` - **Linux x64:** 换成 `x86_64-unknown-linux-gnu` - **Linux arm64:** 换成 `aarch64-unknown-linux-gnu` -- **Windows:** 从 [iii-hq/iii releases v0.11.2](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2) 下载 `iii-x86_64-pc-windows-msvc.zip`,提取 `iii.exe`,加入 PATH +- **Windows:** 从 [iii-hq/iii releases v0.19.7](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7) 下载 `iii-x86_64-pc-windows-msvc.zip`,提取 `iii.exe`,加入 PATH -或使用 Docker(捆绑的 `docker-compose.yml` 会拉取 `iiidev/iii:0.11.2`)。完整文档:[iii.dev/docs](https://iii.dev/docs)。 +或使用 Docker(捆绑的 `docker-compose.yml` 会拉取 `iiidev/iii:0.19.7`)。完整文档:[iii.dev/docs](https://iii.dev/docs)。 ### Windows @@ -737,9 +737,9 @@ agentmemory 可在 Windows 10/11 运行,但仅 Node.js 包不够;你还需要 `i **选项 A:预构建 Windows 二进制(推荐)** ```powershell -# 1. 在浏览器打开 https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2 -# (我们固定在 v0.11.2,直到 agentmemory 为 v0.11.6+ 引擎要求的 -# 新沙盒模型完成重构) +# 1. 在浏览器打开 https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7 +# (agentmemory 将引擎固定在与其 iii-sdk 相同的版本; +# 当前配对为 v0.19.7) # 2. 下载 iii-x86_64-pc-windows-msvc.zip # (如果是 ARM 机器则下载 iii-aarch64-pc-windows-msvc.zip) # 3. 把 iii.exe 解压到 PATH 上的某处,或放在: @@ -747,7 +747,7 @@ agentmemory 可在 Windows 10/11 运行,但仅 Node.js 包不够;你还需要 `i # (agentmemory 会自动检查该位置) # 4. 验证: iii --version -# 应输出:0.11.2 +# 应输出:0.19.7 # 5. 然后照常运行 agentmemory: npx -y @agentmemory/agentmemory @@ -779,7 +779,7 @@ npx -y @agentmemory/mcp | 端口冲突 | `netstat -ano \| findstr :3111` 查看占用,然后 kill 或用 `--port ` | | Docker 已安装但仍跳过回退 | 确保 Docker Desktop 确实在运行(系统托盘图标) | -> 注意:iii **引擎** 是预构建的二进制文件,而非 cargo crate,所以不要尝试用 `cargo install` 安装它。(iii 的 **SDK** 确实已发布到 crates.io、npm 和 PyPI,但 agentmemory 并不需要它们。)受支持的引擎安装方式均固定为 v0.11.2:上面的预构建 v0.11.2 二进制、**带版本固定** 的上游 `sh` 安装脚本 `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.11.2 sh`(macOS/Linux),以及 Docker 镜像 `iiidev/iii:0.11.2`。直接运行 `install.sh | sh` 会安装 **最新** 引擎,而 agentmemory 不支持该版本;请务必传入 `VERSION=0.11.2`。最简单的方式:直接运行 `npx @agentmemory/agentmemory`,它会为你把固定版本的引擎获取到 `~/.agentmemory/bin`。 +> 注意:iii **引擎** 是预构建的二进制文件,而非 cargo crate,所以不要尝试用 `cargo install` 安装它。(iii 的 **SDK** 确实已发布到 crates.io、npm 和 PyPI,但 agentmemory 并不需要它们。)受支持的引擎安装方式均固定为 v0.19.7:上面的预构建 v0.19.7 二进制、**带版本固定** 的上游 `sh` 安装脚本 `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.19.7 sh`(macOS/Linux),以及 Docker 镜像 `iiidev/iii:0.19.7`。直接运行 `install.sh | sh` 会安装 **最新** 引擎,而 agentmemory 不支持该版本;请务必传入 `VERSION=0.19.7`。最简单的方式:直接运行 `npx @agentmemory/agentmemory`,它会为你把固定版本的引擎获取到 `~/.agentmemory/bin`。 --- diff --git a/READMEs/README.zh-TW.md b/READMEs/README.zh-TW.md index 9d89496377..80ea3af89f 100644 --- a/READMEs/README.zh-TW.md +++ b/READMEs/README.zh-TW.md @@ -124,7 +124,7 @@ npx 會依版本快取。用 `npx -y @agentmemory/agentmemory@latest` 強制使
已在執行你自己的 iii 引擎 -agentmemory 把 iii-engine 釘在 v0.11.2,不會附掛到其他版本(worker 無法使用另一個引擎的協定)。停止另一個引擎,然後執行 `npx -y @agentmemory/agentmemory@latest`。它會在 `~/.agentmemory/bin` 安裝並執行釘住的 v0.11.2,不動你自己的 `iii`。 +agentmemory 把 iii-engine 釘在 v0.19.7,不會附掛到其他版本(worker 無法使用另一個引擎的協定)。停止另一個引擎,然後執行 `npx -y @agentmemory/agentmemory@latest`。它會在 `~/.agentmemory/bin` 安裝並執行釘住的 v0.19.7,不動你自己的 `iii`。
@@ -463,7 +463,7 @@ npx @agentmemory/agentmemory

Quick Start

-相容性:此版本面向穩定的 `iii-sdk` `^0.11.0` 和 iii-engine v0.11.x。 +相容性:此版本面向 `iii-sdk` 0.19.7,並將 iii-engine 釘在 v0.19.7。 ### 30 秒體驗 @@ -515,7 +515,7 @@ npx @agentmemory/agentmemory import-jsonl ~/.claude/projects/-my-project/abc123. npx @agentmemory/agentmemory upgrade ``` -警告:此指令會變更目前工作區/執行階段。它可能更新 JavaScript 相依,並拉取固定版本的 Docker 鏡像 `iiidev/iii:0.11.2`。它絕不會安裝未固定版本或更新的 iii 引擎。 +警告:此指令會變更目前工作區/執行階段。它可能更新 JavaScript 相依,並拉取固定版本的 Docker 鏡像 `iiidev/iii:0.19.7`。它絕不會安裝未固定版本或更新的 iii 引擎。 實作細節見 `src/cli.ts`(參考 `src/cli.ts:544-595` 附近的 `runUpgrade`)。 @@ -720,15 +720,15 @@ npm install && npm run build && npm start 若 `iii` 已安裝,這會以本地 `iii-engine` 啟動 agentmemory;若 Docker 可用,則回退到 Docker Compose。REST、串流和檢視器預設繫結到 `127.0.0.1`。 -手動安裝 `iii-engine`。**agentmemory 目前把 `iii-engine` 釘在 `v0.11.2`**。`v0.11.6` 引入了新的「透過 `iii worker add` 沙盒化一切」模型,agentmemory 尚未為此重構。重構落地後即解除釘版。若你已手動遷移到沙盒模型,可用 `AGENTMEMORY_III_VERSION=` 覆寫。 +手動安裝 `iii-engine`。**agentmemory 目前把 `iii-engine` 釘在 `v0.19.7`**,與其 `iii-sdk` 相依是同一個版本;worker 使用該引擎的 wire 協定,而 0.20.0 重組了 SDK 介面,因此兩者在 agentmemory 的每個版本中一起升級。若你執行自己的引擎並確定版本相符,可用 `AGENTMEMORY_III_VERSION=` 覆寫。 -- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.11.2/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` +- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.19.7/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` - **macOS x64:** 把 `aarch64-apple-darwin` 換成 `x86_64-apple-darwin` - **Linux x64:** 換成 `x86_64-unknown-linux-gnu` - **Linux arm64:** 換成 `aarch64-unknown-linux-gnu` -- **Windows:** 從 [iii-hq/iii releases v0.11.2](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2) 下載 `iii-x86_64-pc-windows-msvc.zip`,擷取 `iii.exe`,加入 PATH +- **Windows:** 從 [iii-hq/iii releases v0.19.7](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7) 下載 `iii-x86_64-pc-windows-msvc.zip`,擷取 `iii.exe`,加入 PATH -或使用 Docker(捆綁的 `docker-compose.yml` 會拉取 `iiidev/iii:0.11.2`)。完整文件:[iii.dev/docs](https://iii.dev/docs)。 +或使用 Docker(捆綁的 `docker-compose.yml` 會拉取 `iiidev/iii:0.19.7`)。完整文件:[iii.dev/docs](https://iii.dev/docs)。 ### Windows @@ -737,9 +737,9 @@ agentmemory 可在 Windows 10/11 執行,但僅 Node.js 套件不夠;你還需要 **選項 A:預建 Windows 二進位(推薦)** ```powershell -# 1. 在瀏覽器打開 https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2 -# (我們釘在 v0.11.2,直到 agentmemory 為 v0.11.6+ 引擎需求的 -# 新沙盒模型完成重構) +# 1. 在瀏覽器打開 https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7 +# (agentmemory 將引擎釘在與其 iii-sdk 相同的版本; +# 目前配對為 v0.19.7) # 2. 下載 iii-x86_64-pc-windows-msvc.zip # (若是 ARM 機器則下載 iii-aarch64-pc-windows-msvc.zip) # 3. 把 iii.exe 解壓到 PATH 上的某處,或放在: @@ -747,7 +747,7 @@ agentmemory 可在 Windows 10/11 執行,但僅 Node.js 套件不夠;你還需要 # (agentmemory 會自動檢查該位置) # 4. 驗證: iii --version -# 應輸出:0.11.2 +# 應輸出:0.19.7 # 5. 然後照常執行 agentmemory: npx -y @agentmemory/agentmemory @@ -779,7 +779,7 @@ npx -y @agentmemory/mcp | 連接埠衝突 | `netstat -ano \| findstr :3111` 查看佔用,然後 kill 或用 `--port ` | | Docker 已安裝但仍跳過回退 | 確保 Docker Desktop 確實在執行(系統匣圖示) | -> 注意:iii **引擎** 是預建的二進位檔,而非 cargo crate,請勿嘗試以 `cargo install` 安裝它。(iii 的 **SDK** 確實已發布到 crates.io、npm 和 PyPI,但 agentmemory 並不需要它們。)受支援的引擎安裝方式皆固定為 v0.11.2:上述預建的 v0.11.2 二進位、**帶版本固定** 的上游 `sh` 安裝指令稿 `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.11.2 sh`(macOS/Linux),以及 Docker 鏡像 `iiidev/iii:0.11.2`。直接執行 `install.sh | sh` 會安裝 **最新** 引擎,而 agentmemory 並不支援該版本;請務必傳入 `VERSION=0.11.2`。最簡單的方式:直接執行 `npx @agentmemory/agentmemory`,它會為你把固定版本的引擎取得到 `~/.agentmemory/bin`。 +> 注意:iii **引擎** 是預建的二進位檔,而非 cargo crate,請勿嘗試以 `cargo install` 安裝它。(iii 的 **SDK** 確實已發布到 crates.io、npm 和 PyPI,但 agentmemory 並不需要它們。)受支援的引擎安裝方式皆固定為 v0.19.7:上述預建的 v0.19.7 二進位、**帶版本固定** 的上游 `sh` 安裝指令稿 `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.19.7 sh`(macOS/Linux),以及 Docker 鏡像 `iiidev/iii:0.19.7`。直接執行 `install.sh | sh` 會安裝 **最新** 引擎,而 agentmemory 並不支援該版本;請務必傳入 `VERSION=0.19.7`。最簡單的方式:直接執行 `npx @agentmemory/agentmemory`,它會為你把固定版本的引擎取得到 `~/.agentmemory/bin`。 --- diff --git a/deploy/coolify/Dockerfile b/deploy/coolify/Dockerfile index c0a6bb6c9c..c6ac809d8b 100644 --- a/deploy/coolify/Dockerfile +++ b/deploy/coolify/Dockerfile @@ -15,6 +15,8 @@ RUN apt-get update \ COPY --from=iii-image /app/iii /usr/local/bin/iii WORKDIR /opt/agentmemory +RUN [ "${III_VERSION}" = "${III_SDK_VERSION}" ] \ + || { echo "III_VERSION=${III_VERSION} and III_SDK_VERSION=${III_SDK_VERSION} must be the same release: the agentmemory worker speaks the wire protocol of the engine it was built against, so override both together" >&2; exit 1; } RUN printf '{"name":"agentmemory-deploy","version":"1.0.0","private":true,"overrides":{"iii-sdk":"%s"}}\n' "${III_SDK_VERSION}" > package.json \ && npm install "@agentmemory/agentmemory@${AGENTMEMORY_VERSION}" --omit=optional --no-fund --no-audit \ && ln -s /opt/agentmemory/node_modules/.bin/agentmemory /usr/local/bin/agentmemory diff --git a/deploy/fly/Dockerfile b/deploy/fly/Dockerfile index e094699881..4fa61c4874 100644 --- a/deploy/fly/Dockerfile +++ b/deploy/fly/Dockerfile @@ -15,12 +15,12 @@ RUN apt-get update \ COPY --from=iii-image /app/iii /usr/local/bin/iii # Install agentmemory into a dedicated prefix so the local package.json's -# `overrides` field pins iii-sdk down to match the engine (agentmemory's -# caret range `^0.11.2` otherwise resolves to 0.11.6, the version that -# requires the new sandbox-everything worker model the agentmemory CLI -# is not refactored for yet). `npm install -g` ignores overrides, hence -# the local prefix. +# `overrides` field pins iii-sdk to the exact engine release in this image +# (the worker speaks that engine's wire protocol, so the two must match). +# `npm install -g` ignores overrides, hence the local prefix. WORKDIR /opt/agentmemory +RUN [ "${III_VERSION}" = "${III_SDK_VERSION}" ] \ + || { echo "III_VERSION=${III_VERSION} and III_SDK_VERSION=${III_SDK_VERSION} must be the same release: the agentmemory worker speaks the wire protocol of the engine it was built against, so override both together" >&2; exit 1; } RUN printf '{"name":"agentmemory-deploy","version":"1.0.0","private":true,"overrides":{"iii-sdk":"%s"}}\n' "${III_SDK_VERSION}" > package.json \ && npm install "@agentmemory/agentmemory@${AGENTMEMORY_VERSION}" --omit=optional --no-fund --no-audit \ && ln -s /opt/agentmemory/node_modules/.bin/agentmemory /usr/local/bin/agentmemory diff --git a/deploy/railway/Dockerfile b/deploy/railway/Dockerfile index e094699881..4fa61c4874 100644 --- a/deploy/railway/Dockerfile +++ b/deploy/railway/Dockerfile @@ -15,12 +15,12 @@ RUN apt-get update \ COPY --from=iii-image /app/iii /usr/local/bin/iii # Install agentmemory into a dedicated prefix so the local package.json's -# `overrides` field pins iii-sdk down to match the engine (agentmemory's -# caret range `^0.11.2` otherwise resolves to 0.11.6, the version that -# requires the new sandbox-everything worker model the agentmemory CLI -# is not refactored for yet). `npm install -g` ignores overrides, hence -# the local prefix. +# `overrides` field pins iii-sdk to the exact engine release in this image +# (the worker speaks that engine's wire protocol, so the two must match). +# `npm install -g` ignores overrides, hence the local prefix. WORKDIR /opt/agentmemory +RUN [ "${III_VERSION}" = "${III_SDK_VERSION}" ] \ + || { echo "III_VERSION=${III_VERSION} and III_SDK_VERSION=${III_SDK_VERSION} must be the same release: the agentmemory worker speaks the wire protocol of the engine it was built against, so override both together" >&2; exit 1; } RUN printf '{"name":"agentmemory-deploy","version":"1.0.0","private":true,"overrides":{"iii-sdk":"%s"}}\n' "${III_SDK_VERSION}" > package.json \ && npm install "@agentmemory/agentmemory@${AGENTMEMORY_VERSION}" --omit=optional --no-fund --no-audit \ && ln -s /opt/agentmemory/node_modules/.bin/agentmemory /usr/local/bin/agentmemory diff --git a/deploy/render/Dockerfile b/deploy/render/Dockerfile index e094699881..4fa61c4874 100644 --- a/deploy/render/Dockerfile +++ b/deploy/render/Dockerfile @@ -15,12 +15,12 @@ RUN apt-get update \ COPY --from=iii-image /app/iii /usr/local/bin/iii # Install agentmemory into a dedicated prefix so the local package.json's -# `overrides` field pins iii-sdk down to match the engine (agentmemory's -# caret range `^0.11.2` otherwise resolves to 0.11.6, the version that -# requires the new sandbox-everything worker model the agentmemory CLI -# is not refactored for yet). `npm install -g` ignores overrides, hence -# the local prefix. +# `overrides` field pins iii-sdk to the exact engine release in this image +# (the worker speaks that engine's wire protocol, so the two must match). +# `npm install -g` ignores overrides, hence the local prefix. WORKDIR /opt/agentmemory +RUN [ "${III_VERSION}" = "${III_SDK_VERSION}" ] \ + || { echo "III_VERSION=${III_VERSION} and III_SDK_VERSION=${III_SDK_VERSION} must be the same release: the agentmemory worker speaks the wire protocol of the engine it was built against, so override both together" >&2; exit 1; } RUN printf '{"name":"agentmemory-deploy","version":"1.0.0","private":true,"overrides":{"iii-sdk":"%s"}}\n' "${III_SDK_VERSION}" > package.json \ && npm install "@agentmemory/agentmemory@${AGENTMEMORY_VERSION}" --omit=optional --no-fund --no-audit \ && ln -s /opt/agentmemory/node_modules/.bin/agentmemory /usr/local/bin/agentmemory diff --git a/docker-compose.yml b/docker-compose.yml index 66abc86966..7eb37ae25a 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -18,16 +18,15 @@ services: restart: "no" iii-engine: - # Pinned to v0.11.2 — the last engine that runs agentmemory's current - # direct-registration worker cleanly. v0.11.6 introduces a new sandbox-everything- - # via-`iii worker add` model that agentmemory hasn't been refactored - # for yet; the architectural mismatch surfaces as EPIPE reconnect - # loops and empty search after save. Bump only after agentmemory is - # refactored to register as a sandboxed worker. + # Pinned to the same release as agentmemory's iii-sdk dependency + # (package.json). The worker speaks this engine's wire protocol, so + # bump the image tag and the SDK together, never one of them alone. + # v0.19.7 is the last engine before the 0.20 SDK reorganization and + # keeps HTTP routes owned by the reconnecting worker. # # Override per-shell or via .env file: - # AGENTMEMORY_III_VERSION=0.11.7 docker compose up - image: iiidev/iii:${AGENTMEMORY_III_VERSION:-0.11.2} + # AGENTMEMORY_III_VERSION=0.19.7 docker compose up + image: iiidev/iii:${AGENTMEMORY_III_VERSION:-0.19.7} user: "${AGENTMEMORY_DOCKER_UID:-65532}:${AGENTMEMORY_DOCKER_GID:-65532}" depends_on: iii-init: @@ -45,6 +44,16 @@ services: volumes: - "${AGENTMEMORY_DATA_DIR:-iii-data}:/data" - ./iii-config.docker.yaml:/app/config.yaml:ro + # The engine persists each builtin worker's seeded config block under + # data/configuration of its working directory (/home/nonroot in the + # image) on first boot and treats that copy as the source of truth + # afterwards. Keeping it on a tmpfs means every + # container start re-seeds from config.yaml and the III_* env vars, + # the same behavior the native CLI path has. + - type: tmpfs + target: /home/nonroot/data/configuration + tmpfs: + mode: 01777 restart: unless-stopped logging: driver: json-file diff --git a/eval/README.md b/eval/README.md index 7f29536705..0e274ad040 100644 --- a/eval/README.md +++ b/eval/README.md @@ -26,11 +26,11 @@ source eval/scripts/sandbox.sh npm run eval:coding-life -- --adapters grep,agentmemory ``` -Requires iii v0.11.2 on PATH (agentmemory pin). If you already have a different version installed, install the pinned build into `~/.local/bin` and make sure that directory comes first on `PATH`: +Requires iii v0.19.7 on PATH (agentmemory pin). If you already have a different version installed, install the pinned build into `~/.local/bin` and make sure that directory comes first on `PATH`: ```sh mkdir -p ~/.local/bin -curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.11.2/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin +curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.19.7/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin export PATH="$HOME/.local/bin:$PATH" # add to ~/.zshrc or ~/.bashrc for persistence ``` diff --git a/eval/scripts/sandbox.sh b/eval/scripts/sandbox.sh index 5d4023300f..f192393492 100755 --- a/eval/scripts/sandbox.sh +++ b/eval/scripts/sandbox.sh @@ -14,13 +14,13 @@ REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" if ! command -v iii >/dev/null 2>&1; then echo "iii binary not on PATH. Install pinned version:" - echo " curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.11.2/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin" + echo " curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.19.7/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin" exit 1 fi iii_ver=$(iii --version 2>&1 | head -1) -if [[ "$iii_ver" != "0.11.2" ]]; then - echo "warning: iii version on PATH is $iii_ver; agentmemory pins 0.11.2" +if [[ "$iii_ver" != "0.19.7" ]]; then + echo "warning: iii version on PATH is $iii_ver; agentmemory pins 0.19.7" fi if [[ ! -f "$REPO_ROOT/dist/index.mjs" ]]; then diff --git a/package.json b/package.json index ed9b5325d5..7bca837e12 100644 --- a/package.json +++ b/package.json @@ -65,7 +65,7 @@ "@anthropic-ai/sdk": "^0.100.1", "@clack/prompts": "^1.2.0", "dotenv": "^17.4.2", - "iii-sdk": "0.11.2", + "iii-sdk": "0.19.7", "picocolors": "^1.1.1", "zod": "^4.0.0" }, diff --git a/src/cli.ts b/src/cli.ts index 1e5fb6b78c..b192172021 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -66,7 +66,11 @@ import { } from "./cli/engine-launch.js"; import { runtimeMetadataPath } from "./runtime-paths.js"; import { createStartupStderrCapture } from "./cli/startup-stderr.js"; -import { renderEngineConfig } from "./cli/engine-config.js"; +import { + clearPersistedBuiltinConfig, + renderEngineConfig, +} from "./cli/engine-config.js"; +import { SHUTDOWN_HARD_EXIT_MS } from "./shutdown.js"; import { processStatIsRunning } from "./cli/process-state.js"; import { renderSplash } from "./cli/splash.js"; import { isFirstRun, readPrefs, resetPrefs, writePrefs } from "./cli/preferences.js"; @@ -112,18 +116,17 @@ if (args.includes("--version") || args.includes("-V")) { process.exit(0); } -// Pinned iii-engine version. The unpinned `install.iii.dev/iii/main/install.sh` -// script tracks `latest`, which made every fresh agentmemory install pull -// engine 0.11.6 — and 0.11.6 introduces a new sandbox-everything-via- -// `iii worker add` worker model that agentmemory hasn't been refactored -// for yet (the CLI still registers its worker directly through the SDK). The -// architectural mismatch surfaces as EPIPE reconnect loops and empty -// search results after save. Pin to v0.11.2 — the last engine that runs -// agentmemory's current worker model cleanly — until the refactor lands. -// Override env var AGENTMEMORY_III_VERSION lets users on the sandbox -// model already point at a newer engine without us cutting a release. +// Pinned iii-engine version. The engine and the iii-sdk in package.json must +// stay on the same release: the worker speaks that engine's wire protocol and +// the unpinned installer tracks `latest`. 0.19.7 is the last release before +// the 0.20.0 SDK reorganization (ISdk -> IIIClient, helpers package) and the +// first line that keeps HTTP routes owned by the reconnecting worker, which +// stops the REST 404s after an engine reconnect. Bump this constant and the +// package.json dependency together. AGENTMEMORY_III_VERSION overrides the pin +// for anyone running a self-managed engine. +const IIPINNED_DEFAULT_VERSION = "0.19.7"; const IIPINNED_VERSION = - process.env["AGENTMEMORY_III_VERSION"] || "0.11.2"; + process.env["AGENTMEMORY_III_VERSION"] || IIPINNED_DEFAULT_VERSION; // Map Node platform/arch → the asset name iii-hq/iii ships under // https://github.com/iii-hq/iii/releases/download/iii/v/ @@ -150,7 +153,7 @@ function iiiReleaseAsset(): string | null { function iiiReleaseUrl(): string | null { const asset = iiiReleaseAsset(); if (!asset) return null; - // Tag name is monorepo-prefixed: `iii/v0.11.2`. Slash is URL-encoded + // Tag name is monorepo-prefixed: `iii/v0.19.7`. Slash is URL-encoded // by GitHub when serving the download path, hence `iii/v...` not `iii%2Fv...`. return `https://github.com/iii-hq/iii/releases/download/iii/v${IIPINNED_VERSION}/${asset}`; } @@ -525,7 +528,7 @@ function whichBinary(name: string): string | null { // isolated from a user-managed iii on PATH or in ~/.local/bin. A // fresh box with iii 0.16.1 already on PATH refused to boot because the // hard-pin enforcer told users to overwrite their global install with -// v0.11.2. Private install resolves the conflict without touching their +// the pinned version. Private install resolves the conflict without touching their // existing iii. function agentmemoryBinDir(): string { if (IS_WINDOWS) { @@ -578,8 +581,8 @@ function iiiBinVersion(binPath: string): string | null { // Resolve a compatible iii binary for the pinned engine version. // // Soft-warn lets the worker boot against a mismatched engine and crash at -// runtime (state::list-not-found on v0.13.0+, sandbox-everything trap on -// v0.11.6+). Hard-pin without a fallback leaves the user stuck — they +// runtime (the SDK and engine wire protocol move together; 0.20+ renamed the +// SDK surface entirely). Hard-pin without a fallback leaves the user stuck — they // either downgrade their global iii (breaking other consumers) or set // AGENTMEMORY_III_VERSION and hope it works. // @@ -1554,6 +1557,19 @@ function prepareEngineLaunch(configPath: string): { const runtimePath = runtimeConfigPath(dataDirResolution.dataDir); mkdirSync(dirname(runtimePath), { recursive: true }); writeFileSync(runtimePath, rewritten, "utf-8"); + try { + const cleared = clearPersistedBuiltinConfig(cwd, rewritten); + if (cleared.length > 0) { + vlog( + `cleared ${cleared.length} persisted builtin config entries so the rendered runtime config seeds the engine again`, + ); + } + } catch (err) { + p.log.error( + `${String(err instanceof Error ? err.message : err)}. The engine would ignore the rendered runtime config and keep its previously persisted ports and timeouts. Fix the permissions under ${join(cwd, "data", "configuration")} and run agentmemory start again.`, + ); + process.exit(1); + } if (selectedInstance === 0 && dataDirResolution.source === "default") { for (const m of legacyDataMigrations( process.cwd(), @@ -1965,8 +1981,8 @@ function printReadyHint(consoleState: IiiConsoleState): void { async function main() { await assertRuntimePortOwnership(); // Booting a second instance next to a live daemon registers a duplicate - // worker on the running engine, and on iii 0.11.2 the second instance's - // shutdown tears down the daemon's HTTP trigger routing (every + // worker on the running engine, and before iii 0.19.2 the second instance's + // shutdown tore down the daemon's HTTP trigger routing (every // /agentmemory/* route 404s until a full engine restart). Refuse instead. // A different --instance resolves to a different port, so multi-instance // setups are unaffected. @@ -3177,8 +3193,8 @@ async function runUpgrade() { label: "Refreshing dependencies (pnpm install)", }); requireSuccess(installOk, "pnpm install"); - runCommand(pnpmBin, ["up", "iii-sdk@0.11.2"], { - label: "Pinning iii-sdk@0.11.2", + runCommand(pnpmBin, ["up", `iii-sdk@${IIPINNED_DEFAULT_VERSION}`], { + label: `Pinning iii-sdk@${IIPINNED_DEFAULT_VERSION}`, optional: true, }); } else if (npmBin) { @@ -3186,8 +3202,8 @@ async function runUpgrade() { label: "Refreshing dependencies (npm install)", }); requireSuccess(installOk, "npm install"); - runCommand(npmBin, ["install", "iii-sdk@0.11.2"], { - label: "Pinning iii-sdk@0.11.2", + runCommand(npmBin, ["install", `iii-sdk@${IIPINNED_DEFAULT_VERSION}`], { + label: `Pinning iii-sdk@${IIPINNED_DEFAULT_VERSION}`, optional: true, }); } else { @@ -3536,7 +3552,7 @@ async function runStop(): Promise { // instead of preserving for manual cleanup. const s = p.spinner(); s.start(`Stopping orphaned agentmemory worker (pid ${workerPid})...`); - const ok = await signalAndWait(workerPid, "SIGTERM", 3000); + const ok = await signalAndWait(workerPid, "SIGTERM", SHUTDOWN_HARD_EXIT_MS + 1000); s.stop(ok ? `Stopped worker pid ${workerPid}` : `Failed to stop worker pid ${workerPid}`); clearEnginePidfile(); clearEngineState(); diff --git a/src/cli/doctor-diagnostics.ts b/src/cli/doctor-diagnostics.ts index 10d95136d7..bab2fd2919 100644 --- a/src/cli/doctor-diagnostics.ts +++ b/src/cli/doctor-diagnostics.ts @@ -38,7 +38,7 @@ export type DoctorContext = { pidfilePath: string; /** Path to ~/.agentmemory/engine-state.json */ enginePath: string; - /** Pinned engine version (e.g. "0.11.2"). */ + /** Pinned engine version (e.g. "0.19.7"). */ pinnedVersion: string; }; diff --git a/src/cli/engine-config.ts b/src/cli/engine-config.ts index e20484a790..7e5121ed58 100644 --- a/src/cli/engine-config.ts +++ b/src/cli/engine-config.ts @@ -1,4 +1,65 @@ -import { join } from "node:path"; +import { rmSync } from "node:fs"; +import { join, resolve } from "node:path"; + +const SEEDED_BUILTIN_WORKERS = [ + "iii-http", + "iii-state", + "iii-queue", + "iii-pubsub", + "iii-cron", + "iii-stream", + "iii-observability", + "iii-worker-manager", +]; + +export function configuredPersistDir(renderedConfig: string): string | null { + const lines = renderedConfig.split("\n"); + const block = workerBlock(lines, "configuration"); + if (!block) return null; + for (let i = block.start + 1; i < block.end; i++) { + const match = lines[i]!.trim().match(/^directory:\s*(.+?)\s*$/); + if (match) return match[1]!.replace(/^(['"])(.*)\1$/, "$2"); + } + return null; +} + +export function persistedBuiltinConfigDirs( + engineCwd: string, + renderedConfig?: string, +): string[] { + const dirs = [join(engineCwd, "data", "configuration")]; + const custom = renderedConfig ? configuredPersistDir(renderedConfig) : null; + if (custom) dirs.unshift(resolve(engineCwd, custom)); + return [...new Set(dirs)]; +} + +export function persistedBuiltinConfigPaths( + engineCwd: string, + renderedConfig?: string, +): string[] { + return persistedBuiltinConfigDirs(engineCwd, renderedConfig).flatMap((dir) => + SEEDED_BUILTIN_WORKERS.map((id) => join(dir, `${id}.yaml`)), + ); +} + +export function clearPersistedBuiltinConfig( + engineCwd: string, + renderedConfig?: string, +): string[] { + const cleared: string[] = []; + for (const path of persistedBuiltinConfigPaths(engineCwd, renderedConfig)) { + try { + rmSync(path); + cleared.push(path); + } catch (err) { + if ((err as NodeJS.ErrnoException).code === "ENOENT") continue; + throw new Error( + `could not remove persisted engine config ${path}: ${String(err)}`, + ); + } + } + return cleared; +} export interface EngineConfigOptions { dataDir: string; diff --git a/src/functions/compress.ts b/src/functions/compress.ts index c2019e7d68..c94d856e3a 100644 --- a/src/functions/compress.ts +++ b/src/functions/compress.ts @@ -15,7 +15,7 @@ import { } from "../prompts/compression.js"; import { VISION_DESCRIPTION_PROMPT } from "../prompts/vision.js"; import { getXmlTag, getXmlChildren } from "../prompts/xml.js"; -import { getSearchIndex, vectorIndexAddGuarded } from "./search.js"; +import { getSearchIndex, scheduleIndexSave, vectorIndexAddGuarded } from "./search.js"; import { CompressOutputSchema } from "../eval/schemas.js"; import { validateOutput } from "../eval/validator.js"; import { scoreCompression } from "../eval/quality.js"; @@ -177,6 +177,7 @@ export function registerCompressFunction( try { getSearchIndex().add(compressed); + scheduleIndexSave(); } catch (err) { logger.warn("Failed to index compressed observation into BM25", { obsId: compressed.id, diff --git a/src/functions/observe.ts b/src/functions/observe.ts index c1c9f499b7..e9b0f314e4 100644 --- a/src/functions/observe.ts +++ b/src/functions/observe.ts @@ -9,7 +9,7 @@ import { DedupMap } from "./dedup.js"; import { withKeyedLock } from "../state/keyed-mutex.js"; import { isAutoCompressEnabled } from "../config.js"; import { buildSyntheticCompression } from "./compress-synthetic.js"; -import { getSearchIndex, vectorIndexAddGuarded } from "./search.js"; +import { getSearchIndex, scheduleIndexSave, vectorIndexAddGuarded } from "./search.js"; import { getAgentId } from "../config.js"; import { logger } from "../logger.js"; import { saveImageToDisk } from "../utils/image-store.js"; @@ -321,6 +321,7 @@ export function registerObserveFunction( synthetic, ); getSearchIndex().add(synthetic); + scheduleIndexSave(); await vectorIndexAddGuarded( synthetic.id, synthetic.sessionId, diff --git a/src/functions/remember.ts b/src/functions/remember.ts index 9422269457..e7a1793cd4 100644 --- a/src/functions/remember.ts +++ b/src/functions/remember.ts @@ -6,7 +6,7 @@ import { withKeyedLock } from "../state/keyed-mutex.js"; import { memoryToObservation } from "../state/memory-utils.js"; import { deleteAccessLog } from "./access-tracker.js"; import { recordAudit } from "./audit.js"; -import { getSearchIndex, isMemoryIndexReady, vectorIndexAddGuarded, vectorIndexRemove, flushIndexSave } from "./search.js"; +import { getSearchIndex, isMemoryIndexReady, scheduleIndexSave, vectorIndexAddGuarded, vectorIndexRemove, flushIndexSave } from "./search.js"; import { getAgentId } from "../config.js"; import { logger } from "../logger.js"; @@ -197,6 +197,7 @@ export function registerRememberFunction(sdk: ISdk, kv: StateKV): void { // restart-time rebuild will pick the memory up either way. try { getSearchIndex().add(memoryToObservation(memory)); + scheduleIndexSave(); } catch (err) { logger.warn("Failed to index saved memory into BM25", { memId: memory.id, diff --git a/src/functions/search.ts b/src/functions/search.ts index 9508289531..2f44273c1e 100644 --- a/src/functions/search.ts +++ b/src/functions/search.ts @@ -305,9 +305,29 @@ export async function indexRecords( count++ } await flush() + if (count > 0) scheduleIndexSave() return count } +export async function reconcileIndex(kv: StateKV): Promise { + const idx = getSearchIndex() + const sessions = await kv.list(KV.sessions) + const indexed = idx.observationCountsBySession() + const missing: CompressedObservation[] = [] + for (const session of sessions) { + const known = session.observationCount ?? 0 + if (known > 0 && known <= (indexed.get(session.id) ?? 0)) continue + const observations = await kv.list(KV.observations(session.id)) + for (const obs of observations) { + if (!obs.title || !obs.narrative || idx.has(obs.id)) continue + missing.push(obs) + } + } + const stillMissing = missing.filter((obs) => !idx.has(obs.id)) + if (stillMissing.length === 0) return 0 + return indexRecords(stillMissing, []) +} + export async function rebuildIndex(kv: StateKV): Promise { const idx = getSearchIndex() idx.clear() diff --git a/src/index.ts b/src/index.ts index 717419f7df..2cef745163 100644 --- a/src/index.ts +++ b/src/index.ts @@ -25,6 +25,7 @@ import { KV } from "./state/schema.js"; import { VectorIndex } from "./state/vector-index.js"; import { HybridSearch } from "./state/hybrid-search.js"; import { IndexPersistence } from "./state/index-persistence.js"; +import { SHUTDOWN_FLUSH_TIMEOUT_MS, SHUTDOWN_HARD_EXIT_MS, settleWithin } from "./shutdown.js"; import { registerPrivacyFunction } from "./functions/privacy.js"; import { registerObserveFunction } from "./functions/observe.js"; import { registerImageQuotaCleanup } from "./functions/image-quota-cleanup.js"; @@ -35,6 +36,7 @@ import { registerCompressFunction } from "./functions/compress.js"; import { registerSearchFunction, rebuildIndex, + reconcileIndex, getSearchIndex, setVectorIndex, setEmbeddingProvider, @@ -526,6 +528,17 @@ async function main() { err, ); } + void reconcileIndex(kv) + .then((count) => { + if (count > 0) { + bootLog( + `Search index reconciled: ${count} observations missing from the persisted snapshot were re-indexed`, + ); + } + }) + .catch((err) => { + console.warn(`[agentmemory] Failed to reconcile search index:`, err); + }); } // Ready / Endpoints lines are emitted via `bootLog` so they're @@ -608,14 +621,34 @@ async function main() { const shutdown = async () => { console.log(`\n[agentmemory] Shutting down...`); + const hardExit = setTimeout(() => { + console.warn( + `[agentmemory] Shutdown still blocked after ${SHUTDOWN_HARD_EXIT_MS}ms; exiting now.`, + ); + clearWorkerPidfile(); + process.exit(1); + }, SHUTDOWN_HARD_EXIT_MS); + hardExit.unref(); healthMonitor.stop(); dedupMap.stop(); indexPersistence.stop(); - await new Promise((resolve) => viewerServer.close(() => resolve())); - await indexPersistence.save().catch((err) => { - console.warn(`[agentmemory] Failed to save index on shutdown:`, err); + const viewerClosed = new Promise((resolve) => + viewerServer.close(() => resolve()), + ); + viewerServer.closeAllConnections(); + await viewerClosed; + const flushed = await settleWithin( + indexPersistence.save(), + SHUTDOWN_FLUSH_TIMEOUT_MS, + ); + if (!flushed) { + console.warn( + `[agentmemory] Search index flush did not finish within ${SHUTDOWN_FLUSH_TIMEOUT_MS}ms; the engine is probably gone. Observations are already in the engine's state store and the index reconciles them on the next boot.`, + ); + } + await settleWithin(sdk.shutdown(), SHUTDOWN_FLUSH_TIMEOUT_MS).catch((err) => { + console.warn(`[agentmemory] SDK shutdown failed:`, err); }); - await sdk.shutdown(); clearWorkerPidfile(); process.exit(0); }; diff --git a/src/shutdown.ts b/src/shutdown.ts new file mode 100644 index 0000000000..512d5a588d --- /dev/null +++ b/src/shutdown.ts @@ -0,0 +1,17 @@ +export const SHUTDOWN_FLUSH_TIMEOUT_MS = 4000; +export const SHUTDOWN_HARD_EXIT_MS = 8000; + +export async function settleWithin( + work: Promise, + ms: number, +): Promise { + let timer: ReturnType | undefined; + const expiry = new Promise((resolve) => { + timer = setTimeout(() => resolve(false), ms); + }); + try { + return await Promise.race([work.then(() => true), expiry]); + } finally { + clearTimeout(timer); + } +} diff --git a/src/state/search-index.ts b/src/state/search-index.ts index 67f3e2ef8f..a1ae6cf278 100644 --- a/src/state/search-index.ts +++ b/src/state/search-index.ts @@ -20,6 +20,7 @@ export class SearchIndex { private readonly b = 0.75; add(obs: CompressedObservation): void { + if (this.entries.has(obs.id)) this.remove(obs.id); const terms = this.extractTerms(obs); const termFreq = new Map(); let termCount = 0; @@ -51,6 +52,15 @@ export class SearchIndex { return this.entries.has(id); } + observationCountsBySession(): Map { + const counts = new Map(); + for (const entry of this.entries.values()) { + if (entry.obsId.startsWith("mem_")) continue; + counts.set(entry.sessionId, (counts.get(entry.sessionId) ?? 0) + 1); + } + return counts; + } + remove(id: string): void { const entry = this.entries.get(id); if (!entry) return; diff --git a/test/cli-second-instance-guard.test.ts b/test/cli-second-instance-guard.test.ts index 1767341570..3336b55912 100644 --- a/test/cli-second-instance-guard.test.ts +++ b/test/cli-second-instance-guard.test.ts @@ -2,7 +2,7 @@ import { describe, it, expect } from "vitest"; import { readFileSync } from "node:fs"; // A second full instance next to a live daemon registers a duplicate worker -// on the running engine, and on iii 0.11.2 its shutdown tears down the +// on the running engine, and before iii 0.19.2 its shutdown tore down the // daemon's HTTP trigger routing (every /agentmemory/* route 404s until a full // engine restart). Two guards prevent that: unknown subcommands error instead // of falling through to the server boot, and the boot path probes livez and diff --git a/test/engine-config.test.ts b/test/engine-config.test.ts index e929d1fc30..43ab278373 100644 --- a/test/engine-config.test.ts +++ b/test/engine-config.test.ts @@ -1,7 +1,28 @@ -import { readFileSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; import { join } from "node:path"; import { describe, expect, it } from "vitest"; -import { renderEngineConfig } from "../src/cli/engine-config.js"; +import { + clearPersistedBuiltinConfig, + persistedBuiltinConfigDirs, + persistedBuiltinConfigPaths, + renderEngineConfig, +} from "../src/cli/engine-config.js"; + +const customDirConfig = [ + "workers:", + " - name: iii-http", + " config:", + " port: 3111", + " - name: configuration", + " config:", + " adapter:", + " name: fs", + " config:", + " directory: ./custom-cfg", + " - name: iii-state", + " config: {}", +].join("\n"); describe("renderEngineConfig", () => { it("stores engine state in the resolved data directory", () => { @@ -52,3 +73,75 @@ describe("renderEngineConfig", () => { ); }); }); + +describe("clearPersistedBuiltinConfig", () => { + it("lists one persisted entry per seeded builtin under data/configuration", () => { + const paths = persistedBuiltinConfigPaths("/srv/engine"); + + expect(paths).toContain( + join("/srv/engine", "data", "configuration", "iii-http.yaml"), + ); + expect(paths).toContain( + join("/srv/engine", "data", "configuration", "iii-worker-manager.yaml"), + ); + expect(paths.every((p) => p.endsWith(".yaml"))).toBe(true); + }); + + it("adds the directory a configuration worker entry names, resolved against the engine cwd", () => { + expect(persistedBuiltinConfigDirs("/srv/engine", customDirConfig)).toEqual([ + join("/srv", "engine", "custom-cfg"), + join("/srv", "engine", "data", "configuration"), + ]); + expect( + persistedBuiltinConfigDirs( + "/srv/engine", + customDirConfig.replace("./custom-cfg", "'/var/lib/iii-cfg'"), + )[0], + ).toBe(join("/var", "lib", "iii-cfg")); + expect( + persistedBuiltinConfigDirs("/srv/engine", "workers:\n - name: iii-http\n"), + ).toEqual([join("/srv", "engine", "data", "configuration")]); + }); + + it("removes persisted builtin entries and leaves everything else in place", () => { + const cwd = mkdtempSync(join(tmpdir(), "agentmemory-engine-")); + const dir = join(cwd, "data", "configuration"); + mkdirSync(dir, { recursive: true }); + writeFileSync(join(dir, "iii-http.yaml"), "id: iii-http\nvalue:\n port: 3111\n"); + writeFileSync(join(dir, "iii-state.yaml"), "id: iii-state\nvalue: {}\n"); + writeFileSync(join(dir, "agentmemory.yaml"), "id: agentmemory\nvalue: {}\n"); + + const cleared = clearPersistedBuiltinConfig(cwd); + + expect(cleared).toHaveLength(2); + expect(existsSync(join(dir, "iii-http.yaml"))).toBe(false); + expect(existsSync(join(dir, "iii-state.yaml"))).toBe(false); + expect(existsSync(join(dir, "agentmemory.yaml"))).toBe(true); + }); + + it("removes the entries the engine persisted under a custom configuration directory", () => { + const cwd = mkdtempSync(join(tmpdir(), "agentmemory-engine-")); + const dir = join(cwd, "custom-cfg"); + mkdirSync(dir, { recursive: true }); + writeFileSync(join(dir, "iii-http.yaml"), "id: iii-http\nvalue:\n port: 3111\n"); + writeFileSync(join(dir, "agentmemory.yaml"), "id: agentmemory\nvalue: {}\n"); + + const cleared = clearPersistedBuiltinConfig(cwd, customDirConfig); + + expect(cleared).toEqual([join(dir, "iii-http.yaml")]); + expect(existsSync(join(dir, "agentmemory.yaml"))).toBe(true); + }); + + it("is a no-op when the engine has never persisted anything", () => { + const cwd = mkdtempSync(join(tmpdir(), "agentmemory-engine-")); + + expect(clearPersistedBuiltinConfig(cwd)).toEqual([]); + }); + + it("fails loudly when a persisted entry exists but cannot be removed", () => { + const cwd = mkdtempSync(join(tmpdir(), "agentmemory-engine-")); + mkdirSync(join(cwd, "data", "configuration", "iii-http.yaml"), { recursive: true }); + + expect(() => clearPersistedBuiltinConfig(cwd)).toThrow(/iii-http\.yaml/); + }); +}); diff --git a/test/index-live-persist.test.ts b/test/index-live-persist.test.ts new file mode 100644 index 0000000000..82f7c21eae --- /dev/null +++ b/test/index-live-persist.test.ts @@ -0,0 +1,110 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; + +vi.mock("../src/logger.js", () => ({ + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, +})); + +import { getSearchIndex, setIndexPersistence } from "../src/functions/search.js"; +import { registerObserveFunction } from "../src/functions/observe.js"; +import { registerRememberFunction } from "../src/functions/remember.js"; + +function mockKV() { + const store = new Map>(); + return { + store, + get: async (scope: string, key: string): Promise => + (store.get(scope)?.get(key) as T) ?? null, + set: async (scope: string, key: string, data: T): Promise => { + if (!store.has(scope)) store.set(scope, new Map()); + store.get(scope)!.set(key, data); + return data; + }, + update: async ( + scope: string, + key: string, + updates: Array<{ path: string; value: unknown }>, + ) => { + const m = store.get(scope); + if (!m) return; + const v = (m.get(key) as Record) ?? {}; + for (const u of updates) v[u.path] = u.value; + m.set(key, v); + }, + delete: async (scope: string, key: string) => { + store.get(scope)?.delete(key); + }, + list: async (scope: string): Promise => { + const m = store.get(scope); + return m ? (Array.from(m.values()) as T[]) : []; + }, + }; +} + +function mockSdk() { + const fns = new Map(); + return { + registerFunction: (idOrOpts: string | { id: string }, fn: Function) => { + fns.set(typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id, fn); + }, + registerTrigger: () => {}, + trigger: async (input: { function_id: string; payload: unknown }) => { + const fn = fns.get(input.function_id); + return fn ? fn(input.payload) : null; + }, + }; +} + +describe("live index writes schedule the persisted snapshot", () => { + const persistence = { scheduleSave: vi.fn(), save: vi.fn(async () => {}) }; + + beforeEach(() => { + getSearchIndex().clear(); + persistence.scheduleSave.mockClear(); + setIndexPersistence(persistence); + }); + + afterEach(() => { + setIndexPersistence(null); + }); + + it("after a synthetic observation", async () => { + const sdk = mockSdk(); + const kv = mockKV(); + registerObserveFunction(sdk as never, kv as never); + + const result = (await sdk.trigger({ + function_id: "mem::observe", + payload: { + sessionId: "ses_live", + project: "agentmemory", + cwd: "/tmp/agentmemory", + hookType: "post_tool_use", + timestamp: new Date().toISOString(), + data: { + tool_name: "Bash", + tool_input: { command: "echo persist-probe" }, + tool_output: "persist-probe output", + }, + }, + })) as { observationId: string }; + + expect(result.observationId).toBeTruthy(); + expect(getSearchIndex().has(result.observationId)).toBe(true); + expect(persistence.scheduleSave).toHaveBeenCalled(); + }); + + it("after a memory save", async () => { + const sdk = mockSdk(); + const kv = mockKV(); + registerRememberFunction(sdk as never, kv as never); + + const result = (await sdk.trigger({ + function_id: "mem::remember", + payload: { content: "persisted snapshot follows every live add", type: "fact" }, + })) as { success: boolean; memory: { id: string } }; + + expect(result.success).toBe(true); + expect(getSearchIndex().has(result.memory.id)).toBe(true); + expect(persistence.scheduleSave).toHaveBeenCalled(); + }); +}); diff --git a/test/index-reconcile.test.ts b/test/index-reconcile.test.ts new file mode 100644 index 0000000000..e96a7d4e89 --- /dev/null +++ b/test/index-reconcile.test.ts @@ -0,0 +1,175 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { + getSearchIndex, + reconcileIndex, + setIndexPersistence, +} from "../src/functions/search.js"; +import { SearchIndex } from "../src/state/search-index.js"; +import type { CompressedObservation, Session } from "../src/types.js"; + +function mockKV() { + const store = new Map>(); + const list = vi.fn(async (scope: string): Promise => { + const entries = store.get(scope); + return entries ? (Array.from(entries.values()) as T[]) : []; + }); + return { + list, + get: async (scope: string, key: string): Promise => + (store.get(scope)?.get(key) as T) ?? null, + set: async (scope: string, key: string, data: T): Promise => { + if (!store.has(scope)) store.set(scope, new Map()); + store.get(scope)!.set(key, data); + return data; + }, + delete: async (scope: string, key: string): Promise => { + store.get(scope)?.delete(key); + }, + }; +} + +function makeObs(id: string, sessionId: string): CompressedObservation { + return { + id, + sessionId, + timestamp: new Date().toISOString(), + type: "decision", + title: `observation ${id}`, + facts: [`fact about ${id}`], + narrative: `narrative for ${id}`, + concepts: ["reconcile"], + files: [], + importance: 5, + }; +} + +function makeSession(id: string, observationCount: number): Session { + return { + id, + project: "agentmemory", + cwd: "/tmp", + startedAt: new Date().toISOString(), + status: "active", + observationCount, + }; +} + +describe("reconcileIndex", () => { + const persistence = { scheduleSave: vi.fn(), save: vi.fn(async () => {}) }; + + beforeEach(() => { + getSearchIndex().clear(); + persistence.scheduleSave.mockClear(); + setIndexPersistence(persistence); + }); + + afterEach(() => { + setIndexPersistence(null); + }); + + it("re-indexes observations missing from the loaded snapshot and schedules a save", async () => { + const kv = mockKV(); + await kv.set("mem:sessions", "s1", makeSession("s1", 2)); + await kv.set("mem:obs:s1", "obs_a", makeObs("obs_a", "s1")); + await kv.set("mem:obs:s1", "obs_b", makeObs("obs_b", "s1")); + getSearchIndex().add(makeObs("obs_a", "s1")); + + const added = await reconcileIndex(kv as never); + + expect(added).toBe(1); + expect(getSearchIndex().has("obs_b")).toBe(true); + expect(getSearchIndex().size).toBe(2); + expect(persistence.scheduleSave).toHaveBeenCalled(); + }); + + it("does not list observations for sessions the snapshot already covers", async () => { + const kv = mockKV(); + await kv.set("mem:sessions", "s1", makeSession("s1", 2)); + await kv.set("mem:obs:s1", "obs_a", makeObs("obs_a", "s1")); + await kv.set("mem:obs:s1", "obs_b", makeObs("obs_b", "s1")); + getSearchIndex().add(makeObs("obs_a", "s1")); + getSearchIndex().add(makeObs("obs_b", "s1")); + + const added = await reconcileIndex(kv as never); + + expect(added).toBe(0); + expect(kv.list).toHaveBeenCalledTimes(1); + expect(kv.list).toHaveBeenCalledWith("mem:sessions"); + expect(persistence.scheduleSave).not.toHaveBeenCalled(); + }); + + it("does not let indexed memories mask a missing observation", async () => { + const kv = mockKV(); + await kv.set("mem:sessions", "s1", makeSession("s1", 1)); + await kv.set("mem:obs:s1", "obs_a", makeObs("obs_a", "s1")); + getSearchIndex().add(makeObs("mem_x", "s1")); + + const added = await reconcileIndex(kv as never); + + expect(added).toBe(1); + expect(getSearchIndex().has("obs_a")).toBe(true); + }); + + it("skips observations that are already indexed or not indexable", async () => { + const kv = mockKV(); + await kv.set("mem:sessions", "s1", makeSession("s1", 3)); + await kv.set("mem:obs:s1", "obs_a", makeObs("obs_a", "s1")); + await kv.set("mem:obs:s1", "obs_b", { ...makeObs("obs_b", "s1"), narrative: "" }); + await kv.set("mem:obs:s1", "obs_c", makeObs("obs_c", "s1")); + getSearchIndex().add(makeObs("obs_a", "s1")); + + const added = await reconcileIndex(kv as never); + + expect(added).toBe(1); + expect(getSearchIndex().has("obs_c")).toBe(true); + expect(getSearchIndex().has("obs_b")).toBe(false); + }); + + it("treats a zero observation count as unknown and still checks the session", async () => { + const kv = mockKV(); + await kv.set("mem:sessions", "s1", makeSession("s1", 0)); + await kv.set("mem:obs:s1", "obs_a", makeObs("obs_a", "s1")); + + const added = await reconcileIndex(kv as never); + + expect(added).toBe(1); + expect(getSearchIndex().has("obs_a")).toBe(true); + }); + + it("does not re-add an observation a live write indexed while it was collecting", async () => { + const kv = mockKV(); + await kv.set("mem:sessions", "s1", makeSession("s1", 1)); + await kv.set("mem:sessions", "s2", makeSession("s2", 1)); + await kv.set("mem:obs:s1", "obs_a", makeObs("obs_a", "s1")); + await kv.set("mem:obs:s2", "obs_b", makeObs("obs_b", "s2")); + const realList = kv.list; + kv.list = vi.fn(async (scope: string) => { + if (scope === "mem:obs:s2") getSearchIndex().add(makeObs("obs_a", "s1")); + return realList(scope); + }) as typeof kv.list; + + const added = await reconcileIndex(kv as never); + + expect(added).toBe(1); + expect(getSearchIndex().size).toBe(2); + }); +}); + +describe("SearchIndex.add on an existing id", () => { + it("replaces the document instead of stacking postings and doc length", () => { + const first = { ...makeObs("obs_a", "s1"), title: "alpha token", narrative: "alpha token", facts: [] }; + const second = { ...makeObs("obs_a", "s1"), title: "bravo token", narrative: "bravo token", facts: [] }; + const idx = new SearchIndex(); + idx.add(first); + idx.add(second); + const fresh = new SearchIndex(); + fresh.add(second); + + expect(idx.size).toBe(1); + expect(idx.search("alpha").map((r) => r.obsId)).toEqual([]); + expect(idx.search("bravo").map((r) => r.obsId)).toEqual(["obs_a"]); + expect(JSON.parse(idx.serialize()).totalDocLength).toBe( + JSON.parse(fresh.serialize()).totalDocLength, + ); + }); +}); diff --git a/test/multimodal.test.ts b/test/multimodal.test.ts index 8f61f88744..b2792db147 100644 --- a/test/multimodal.test.ts +++ b/test/multimodal.test.ts @@ -16,6 +16,7 @@ vi.mock("../src/functions/search.js", () => ({ add: vi.fn(), }), vectorIndexAddGuarded: vi.fn().mockResolvedValue(false), + scheduleIndexSave: vi.fn(), })); const mockTrigger = vi.fn().mockResolvedValue(undefined); diff --git a/test/shutdown.test.ts b/test/shutdown.test.ts new file mode 100644 index 0000000000..d2dafafafa --- /dev/null +++ b/test/shutdown.test.ts @@ -0,0 +1,32 @@ +import { describe, it, expect, vi } from "vitest"; +import { + SHUTDOWN_FLUSH_TIMEOUT_MS, + SHUTDOWN_HARD_EXIT_MS, + settleWithin, +} from "../src/shutdown.js"; + +describe("settleWithin", () => { + it("resolves true when the work settles in time", async () => { + expect(await settleWithin(Promise.resolve("ok"), 1000)).toBe(true); + }); + + it("propagates a rejection instead of reporting success", async () => { + await expect(settleWithin(Promise.reject(new Error("boom")), 1000)).rejects.toThrow("boom"); + }); + + it("resolves false when the work never settles", async () => { + vi.useFakeTimers(); + try { + const pending = settleWithin(new Promise(() => {}), 50); + await vi.advanceTimersByTimeAsync(50); + expect(await pending).toBe(false); + } finally { + vi.useRealTimers(); + } + }); + + it("keeps the flush budget under the CLI's 5s worker grace, with the hard exit after it", () => { + expect(SHUTDOWN_FLUSH_TIMEOUT_MS).toBeLessThan(5000); + expect(SHUTDOWN_HARD_EXIT_MS).toBeGreaterThan(SHUTDOWN_FLUSH_TIMEOUT_MS); + }); +}); From bb6cef38990bddb2af14e98464628f76fb043cc7 Mon Sep 17 00:00:00 2001 From: Rohit Ghumare <48523873+rohitg00@users.noreply.github.com> Date: Thu, 24 Sep 2026 18:15:52 +0530 Subject: [PATCH 03/57] chore(engine): move iii-sdk and the engine pin to 0.22.1 (#1397) * chore(engine): move iii-sdk and the engine pin to 0.22.1 Stage 2 of the engine upgrade, on top of 0.19.7. The 0.20 SDK reorganization renames the client handle (ISdk to IIIClient) and moves the buffered HTTP request type to @iii-dev/helpers/http (ApiRequest to HttpRequest); those are the only source changes the SDK needs, so helpers becomes a pinned dependency next to iii-sdk and `agentmemory upgrade` pins both. Engine 0.22.1 persists each builtin worker's config under config/ in its working directory instead of data/configuration/, so the pre-spawn cleanup now covers the engine cwd, the directory of the runtime config file, and the legacy location, for both the prefixed and the unprefixed entry names. The bundled compose file keeps /app/config on a tmpfs for the same reason. The bundled configs keep the iii- prefixed builtin names: on 0.22.1 an unprefixed http/state/queue/pubsub/cron entry resolves to the standalone registry worker and fails to boot without iii-worker, which is the 0.23 migration, not this one. The in-engine queue stays listed explicitly as iii-queue so durable:subscriber triggers keep working. Verified against engine 0.22.1: standalone worker (boot, observe, search, engine restart with REST back in 1 s, clean SIGTERM), the real CLI on a fresh HOME (engine download, port change across restarts through the persisted-config cleanup), a copy of a real store, the Docker compose path, and the crash-safety and shutdown probes from stage 1. * docs: sweep the remaining engine references for 0.22.1 Full-repo pass after the pin: the contributor guide (AGENTS.md) now names the 0.22 client and request types and where HttpRequest is imported from; the Python examples pin iii-sdk to the same release as the engine; the README and its eleven translations describe the shipped observability sampling ratio (0.1, not 1.0). Checked and left alone: every engine function id and trigger type the worker uses is registered by 0.22.1 (state, stream, mcp, engine::workers, http, durable:subscriber); no workflow, script, plugin or package other than the root package.json references the SDK or the engine version; the "Invalid function id format: publish" line in the engine log is the engine's own pubsub builtin at shutdown and appears on 0.19.7 as well. * feat(cli): agentmemory console through the pinned engine Engine 0.22 ships the iii web console as a subcommand of the engine binary and downloads the console on first use, so the separate install prompt on start (an engine installer piped to sh) and the skipConsoleInstall preference are gone. `agentmemory console` resolves the pinned iii (PATH if it matches the pin, else the private install) and runs `iii console` against the REST, streams and bridge ports agentmemory resolved, serving one port above the viewer by default; --console-port overrides, --port and --instance pick the instance, other flags pass through. The ready panel points at the command instead of a binary path or an install hint. Verified on an isolated HOME: the console serves with the engine ports injected, registers its functions on the agentmemory engine, and warns but still starts when no engine answers. * chore(engine): start the pinned engine quiet and align the deploy configs The CLI spawns the pinned engine with --no-update-check, so a pinned release never looks up newer releases or advisories on GitHub at boot, and with iii's anonymous usage telemetry off unless the user exported III_TELEMETRY_ENABLED themselves; the bundled compose file passes the same flag and variable. The deploy entrypoints generated sampling_ratio 1.0 with console log output on, the combination behind the log feedback loop the bundled config already avoids; they now ship the bundled values. README: the "extend with one command" section listed builtins that already ship in iii-config.yaml and linked a registry page that no longer exists (iii-database is database); it now names the running builtins, the current registry names, where a custom config lives (~/.agentmemory/iii-config.yaml) and how the worker runtime is installed. The translations only get the link fix; their prose is resynced in the usual batch. * docs: pin .env.example to 0.22.1 and place the engine note under the port table .env.example still named 0.19.7 in the engine pin block and lacked III_TELEMETRY_ENABLED next to the pin. The README paragraph about the quiet engine start had landed above the banner; it now follows the port table where the engine flags are described. * docs: describe trace spans as sampled in the observability paragraph The README and the translations kept promising a trace span for every memory operation next to sampling_ratio: 0.1; the sentence now says every operation emits a structured log and one in ten also carries a span. * fix(cli): only remove engine-written config entries, and let console find every pinned iii With a custom engine config the engine's working directory is the config file's directory, so the persisted-config cleanup looked for the seeded builtin names under a project's own config/ folder and would have removed files such as http.yaml or state.yaml that belong to the project. Every entry the engine writes starts with an `id: ` line (0.19.7 and 0.22.1 both), so the cleanup now reads each candidate and removes it only when that line matches the file name. agentmemory console resolved iii from PATH or the private install only; it now walks the same candidate list as engine start, so it finds a compatible engine from the fallback locations as well. --- .env.example | 7 +- AGENTS.md | 6 +- CHANGELOG.md | 11 +- INSTALL_FOR_AGENTS.md | 16 +- README.md | 79 ++++--- READMEs/README.de-DE.md | 28 +-- READMEs/README.es-ES.md | 28 +-- READMEs/README.fr-FR.md | 28 +-- READMEs/README.hi-IN.md | 28 +-- READMEs/README.ja-JP.md | 28 +-- READMEs/README.ko-KR.md | 28 +-- READMEs/README.pt-BR.md | 28 +-- READMEs/README.ru-RU.md | 28 +-- READMEs/README.tr-TR.md | 28 +-- READMEs/README.zh-CN.md | 28 +-- READMEs/README.zh-TW.md | 28 +-- deploy/coolify/entrypoint.sh | 4 +- deploy/fly/entrypoint.sh | 4 +- deploy/railway/entrypoint.sh | 4 +- deploy/render/entrypoint.sh | 4 +- docker-compose.yml | 21 +- eval/README.md | 4 +- eval/scripts/sandbox.sh | 6 +- examples/python/README.md | 2 +- examples/python/observe_and_recall.py | 2 +- examples/python/quickstart.py | 2 +- package.json | 3 +- src/cli.ts | 262 +++++++++++------------ src/cli/console.ts | 66 ++++++ src/cli/doctor-diagnostics.ts | 2 +- src/cli/engine-config.ts | 29 ++- src/cli/engine-launch.ts | 4 + src/cli/preferences.ts | 7 +- src/functions/actions.ts | 4 +- src/functions/auto-forget.ts | 4 +- src/functions/branch-aware.ts | 4 +- src/functions/cascade.ts | 4 +- src/functions/checkpoints.ts | 4 +- src/functions/claude-bridge.ts | 4 +- src/functions/compress-file.ts | 4 +- src/functions/compress.ts | 4 +- src/functions/consolidate.ts | 4 +- src/functions/consolidation-pipeline.ts | 4 +- src/functions/context.ts | 4 +- src/functions/crystallize.ts | 4 +- src/functions/diagnostics.ts | 4 +- src/functions/disk-size-manager.ts | 4 +- src/functions/enrich.ts | 4 +- src/functions/evict.ts | 8 +- src/functions/export-import.ts | 4 +- src/functions/facets.ts | 4 +- src/functions/file-index.ts | 4 +- src/functions/flow-compress.ts | 4 +- src/functions/frontier.ts | 4 +- src/functions/governance.ts | 4 +- src/functions/graph-import.ts | 4 +- src/functions/graph.ts | 4 +- src/functions/image-quota-cleanup.ts | 4 +- src/functions/image-refs.ts | 4 +- src/functions/leases.ts | 4 +- src/functions/lessons.ts | 4 +- src/functions/mesh.ts | 4 +- src/functions/migrate.ts | 4 +- src/functions/observe.ts | 4 +- src/functions/obsidian-export.ts | 4 +- src/functions/patterns.ts | 4 +- src/functions/privacy.ts | 4 +- src/functions/profile.ts | 4 +- src/functions/query-expansion.ts | 4 +- src/functions/recent-searches-sweep.ts | 4 +- src/functions/reflect.ts | 4 +- src/functions/relations.ts | 4 +- src/functions/remember.ts | 4 +- src/functions/replay.ts | 4 +- src/functions/retention.ts | 4 +- src/functions/routines.ts | 4 +- src/functions/search.ts | 4 +- src/functions/sentinels.ts | 4 +- src/functions/signals.ts | 4 +- src/functions/sketches.ts | 4 +- src/functions/skill-extract.ts | 4 +- src/functions/sliding-window.ts | 4 +- src/functions/slots.ts | 4 +- src/functions/smart-search.ts | 6 +- src/functions/snapshot.ts | 4 +- src/functions/summarize.ts | 4 +- src/functions/team.ts | 4 +- src/functions/temporal-graph.ts | 4 +- src/functions/timeline.ts | 4 +- src/functions/verify.ts | 4 +- src/functions/vision-search.ts | 4 +- src/functions/working-memory.ts | 4 +- src/health/monitor.ts | 4 +- src/mcp/server.ts | 19 +- src/state/kv.ts | 4 +- src/triggers/api.ts | 265 ++++++++++++------------ src/triggers/events.ts | 4 +- test/cli-console.test.ts | 60 ++++++ test/context-lessons.test.ts | 2 +- test/context-slots.test.ts | 2 +- test/docker-port-config.test.ts | 7 + test/engine-child-env.test.ts | 16 ++ test/engine-config.test.ts | 115 +++++++--- test/slots.test.ts | 2 +- test/vision-search.test.ts | 4 +- 105 files changed, 917 insertions(+), 682 deletions(-) create mode 100644 src/cli/console.ts create mode 100644 test/cli-console.test.ts create mode 100644 test/engine-child-env.test.ts diff --git a/.env.example b/.env.example index 153aef4d9a..9219a338a1 100644 --- a/.env.example +++ b/.env.example @@ -181,11 +181,14 @@ # ----------------------------------------------------------------------------- # # agentmemory pins iii-engine to the same release as its iii-sdk dependency -# (v0.19.7). The worker speaks the wire protocol of that engine, so the two move +# (v0.22.1). The worker speaks the wire protocol of that engine, so the two move # together in agentmemory releases. Override with AGENTMEMORY_III_VERSION only # if you run your own engine and know it matches. -# AGENTMEMORY_III_VERSION=0.19.7 +# AGENTMEMORY_III_VERSION=0.22.1 + +# Engine usage telemetry (iii). Off unless you set it; true opts in. +# III_TELEMETRY_ENABLED=false # ----------------------------------------------------------------------------- # 9. Claude Code bridge (opt-in) diff --git a/AGENTS.md b/AGENTS.md index dc08f431ca..a22269033c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,7 +4,7 @@ agentmemory is a persistent memory system for AI coding agents, built on iii-engine's three primitives (Worker/Function/Trigger). Everything goes through `registerFunction`/`registerTrigger`/`sdk.trigger()` — never bypass iii-engine with standalone SQLite or in-process alternatives. -- **Engine**: iii-sdk (WebSocket to iii-engine on port 49134) +- **Engine**: iii-sdk 0.22.1 with @iii-dev/helpers 0.22.1 (WebSocket to iii-engine 0.22.1 on port 49134; the client type is `IIIClient`, HTTP requests are `HttpRequest` from `@iii-dev/helpers/http`) - **State**: File-based SQLite via iii-engine's StateModule (`./data/state_store.db`) - **Build**: TypeScript → ESM via tsdown, output to `dist/` - **Test**: vitest (`npm test` excludes integration tests) @@ -59,7 +59,9 @@ sdk.registerFunction( ### REST Endpoint Registration ```typescript -sdk.registerFunction("api::your-endpoint", async (req: ApiRequest) => { +import type { HttpRequest } from "@iii-dev/helpers/http"; + +sdk.registerFunction("api::your-endpoint", async (req: HttpRequest) => { const denied = checkAuth(req, secret); if (denied) return denied; const body = req.body as Record; diff --git a/CHANGELOG.md b/CHANGELOG.md index 340d46ddfd..a95daedac5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,10 +8,17 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), ### Changed -- **iii engine and `iii-sdk` move from 0.11.2 to 0.19.7.** Same release on both sides, as before; the CLI downloads the pinned engine into `~/.agentmemory/bin`, the bundled `docker-compose.yml` pulls `iiidev/iii:0.19.7`, and `agentmemory upgrade` pins the SDK to the version this package was built against. The deploy templates under `deploy/` install the published npm package, so their engine pair moves together with `AGENTMEMORY_VERSION` at release time. 0.19.7 is the last engine before the 0.20 SDK reorganization and carries the upstream fix that keeps HTTP routes owned by the reconnecting worker, so `/agentmemory/*` no longer answers 404 after the engine reconnects (#1013). Existing state stores load unchanged. -- **Runtime config is re-seeded on every start.** Engines from 0.19.4 on persist each builtin worker's `config:` block into `data/configuration/.yaml` on first boot and treat that copy as the source of truth afterwards, which would have made `--port`, `--instance` and data-dir changes silently ineffective after the first run. The CLI now clears those persisted builtin entries right before it spawns the engine, so the runtime config it renders from your environment is the seed every time. If one of them cannot be removed, `agentmemory start` stops with the path instead of launching an engine that would ignore the requested ports. The bundled `docker-compose.yml` keeps the same directory on a tmpfs so container starts behave the same way. +- **iii engine and `iii-sdk` move from 0.11.2 to 0.22.1, with `@iii-dev/helpers` 0.22.1 alongside.** Same release on both sides, as before; the CLI downloads the pinned engine into `~/.agentmemory/bin`, the bundled `docker-compose.yml` pulls `iiidev/iii:0.22.1`, and `agentmemory upgrade` pins both packages to the version this package was built against. The deploy templates under `deploy/` install the published npm package, so their engine pair moves together with `AGENTMEMORY_VERSION` at release time. 0.22.x is the last engine line before 0.23 removes the `config.yaml` worker lifecycle the CLI relies on; it carries the upstream fix that keeps HTTP routes owned by the reconnecting worker, so `/agentmemory/*` no longer answers 404 after the engine reconnects (#1013), and its Node SDK bounds WebSocket connect attempts and detects half-open sockets. The bundled configs keep the `iii-` prefixed builtin workers (`iii-http`, `iii-state`, `iii-queue`, `iii-pubsub`, `iii-cron`): on 0.22.1 the unprefixed names resolve to the standalone registry workers, which is the 0.23 migration. Existing state stores load unchanged. +- **Runtime config is re-seeded on every start.** Engines from 0.19.4 on persist each builtin worker's `config:` block on first boot (0.22 writes `config/.yaml` next to the config file; earlier engines wrote `data/configuration/` under the working directory) and treat that copy as the source of truth afterwards, which would have made `--port`, `--instance` and data-dir changes silently ineffective after the first run. The CLI now clears those persisted entries in both locations right before it spawns the engine, so the runtime config it renders from your environment is the seed every time. If one of them cannot be removed, `agentmemory start` stops with the path instead of launching an engine that would ignore the requested ports. The bundled `docker-compose.yml` keeps the same directory on a tmpfs so container starts behave the same way. - Dependabot no longer proposes `iii-sdk` bumps; the engine pin and the SDK version are updated together by hand. - The deploy Dockerfiles (`deploy/fly`, `railway`, `render`, `coolify`) refuse to build when `III_VERSION` and `III_SDK_VERSION` differ, so overriding the engine tag alone can no longer produce a worker that speaks the wrong wire protocol. +- **The pinned engine starts quiet.** The CLI spawns it with `--no-update-check` (no update or security-advisory lookups against GitHub at boot) and with iii's anonymous usage telemetry off (`III_TELEMETRY_ENABLED=false` unless you export the variable yourself); the bundled compose file passes the same flag and variable. +- The deploy entrypoints (`deploy/*/entrypoint.sh`) generate the same observability settings as the bundled `iii-config.yaml` (`sampling_ratio: 0.1`, console log output off) instead of full sampling with console logs, the combination behind the log feedback loop fixed in 0.9.22. +- The README section on extending agentmemory with registry workers no longer lists builtins that already ship in `iii-config.yaml`, uses the current registry names (`database` replaced `iii-database`), and says where a custom config lives (`~/.agentmemory/iii-config.yaml`). + +### Added + +- **`agentmemory console`** launches the iii web console (workers, functions, triggers, queues, traces) through the pinned engine, against the ports agentmemory resolved, one port above the viewer by default (`--console-port` overrides). Engine 0.22 ships the console as part of `iii` and downloads it on first use, so the "install iii console?" prompt on start and the `skipConsoleInstall` preference are gone; the ready panel now points at the command instead. ### Fixed diff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.md index b10e993425..6bb1d1119b 100644 --- a/INSTALL_FOR_AGENTS.md +++ b/INSTALL_FOR_AGENTS.md @@ -4,7 +4,7 @@ You are a coding agent. Follow this runbook top to bottom to install agentmemory ## What you are installing -agentmemory is a local memory server for coding agents. It exposes a REST API and MCP HTTP routes on port 3111, streams on 3112, a viewer on 3113, and connects its worker to iii-engine on 49134. It is built on the iii engine, which agentmemory manages as a pinned v0.19.7 binary under `~/.agentmemory/bin` on macOS/Linux or `%USERPROFILE%\.agentmemory\bin` on Windows. +agentmemory is a local memory server for coding agents. It exposes a REST API and MCP HTTP routes on port 3111, streams on 3112, a viewer on 3113, and connects its worker to iii-engine on 49134. It is built on the iii engine, which agentmemory manages as a pinned v0.22.1 binary under `~/.agentmemory/bin` on macOS/Linux or `%USERPROFILE%\.agentmemory\bin` on Windows. Configuration and the managed iii binary live under `~/.agentmemory`. Persistent iii state uses the platform data directory: `~/Library/Application Support/agentmemory` on macOS, `$XDG_DATA_HOME/agentmemory` or `~/.local/share/agentmemory` on Linux, and `%APPDATA%\agentmemory` on Windows. Override it with `--data-dir ` or `AGENTMEMORY_DATA_DIR`; use the same override on every restart. For instance 0, an existing `./data/state_store.db` or `./data/iii-config.yaml` takes precedence over the platform default, while an explicit flag or environment override still wins. Native and Docker starts use the same resolved host data directory. @@ -14,7 +14,7 @@ Default keyless mode needs no API key or cloud account and disables vector embed - Node.js >= 20 with npm and npx. Check with `node -v`, `npm -v`, and `npx -v`. - macOS/Linux automatic iii installation also requires `curl`, a POSIX `sh`, and `tar`. Check with `command -v curl sh tar`. Minimal images such as `node:20-slim` may not include them. -- Windows: WSL2 follows the Linux path above. Native Windows requires a manually downloaded, pinned iii-engine v0.19.7 `iii.exe`, or Docker Desktop; the CLI does not auto-extract the Windows ZIP. Native automated `connect` supports only `copilot-cli`. Other Windows agents need manual MCP configuration; WSL `connect` applies only to agents installed in that same WSL environment. +- Windows: WSL2 follows the Linux path above. Native Windows requires a manually downloaded, pinned iii-engine v0.22.1 `iii.exe`, or Docker Desktop; the CLI does not auto-extract the Windows ZIP. Native automated `connect` supports only `copilot-cli`. Other Windows agents need manual MCP configuration; WSL `connect` applies only to agents installed in that same WSL environment. - Ports 3111 (REST), 3112 (streams), 3113 (viewer), and 49134 (engine) free. If any are taken, stop whatever is using them before starting (see Troubleshooting). ## Running non-interactively @@ -38,12 +38,12 @@ For native Windows, install the engine before continuing: ```powershell # Download the archive that matches your CPU from the pinned release: -# https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7 +# https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.22.1 # Extract iii.exe to $HOME\.agentmemory\bin\iii.exe, then verify the pin: & "$HOME\.agentmemory\bin\iii.exe" --version ``` -Expect: exactly `0.19.7`. Do not install the latest unpinned iii release. Alternatively, use WSL2 or start Docker Desktop and choose the Docker path when agentmemory starts. +Expect: exactly `0.22.1`. Do not install the latest unpinned iii release. Alternatively, use WSL2 or start Docker Desktop and choose the Docker path when agentmemory starts. ## 2. Start the server @@ -61,7 +61,7 @@ npx -y @agentmemory/agentmemory@latest --data-dir /absolute/path/to/agentmemory- Docker bind-mounts that same resolved host directory at `/data`. For a second isolated daemon, add `--instance 1`; it stores data and lifecycle metadata under `instance-1` and defaults to ports 3211, 3212, 3213, and 49234. Do not use `--port` alone for concurrent daemons: it changes the ports but keeps instance 0's canonical lifecycle ownership. Use `--instance` for isolation. -Expect: iii-engine v0.19.7 starts, the agentmemory worker registers with iii, and the ready panel lists REST, viewer, streams, and engine addresses. First boot can take longer while the engine binary is downloaded. +Expect: iii-engine v0.22.1 starts, the agentmemory worker registers with iii, and the ready panel lists REST, viewer, streams, and engine addresses. First boot can take longer while the engine binary is downloaded. ## 3. Validate the server and all four ports @@ -202,9 +202,9 @@ The MCP server exposes 54 tools by default (`--tools all`). Use `--tools core` ( - Server starts but `livez` never returns 200: re-run with `npx -y @agentmemory/agentmemory@latest --verbose` to see engine stderr. - `The engine process started but the REST API never responded.`: inspect all four derived ports, confirm the pinned iii process stayed alive, and use `--verbose` for captured engine stderr. - Engine version warning on start: harmless. agentmemory uses its own pinned engine in `~/.agentmemory/bin` regardless of any `iii` on `PATH`. Set `AGENTMEMORY_III_VERSION` only to override deliberately. -- "engine conflict" / another iii engine already running: if a different iii version is already serving the port, agentmemory will not adopt it. Stop that engine (`npx -y @agentmemory/agentmemory@latest stop --force`, or however you started it), then rerun the canonical command. Its private v0.19.7 binary does not replace a user-managed `iii` on `PATH`. +- "engine conflict" / another iii engine already running: if a different iii version is already serving the port, agentmemory will not adopt it. Stop that engine (`npx -y @agentmemory/agentmemory@latest stop --force`, or however you started it), then rerun the canonical command. Its private v0.22.1 binary does not replace a user-managed `iii` on `PATH`. - Only 7 tools visible in the agent: the MCP shim is in local fallback because it could not reach a server. Start `npx -y @agentmemory/agentmemory@latest`, ensure `AGENTMEMORY_URL` points at it (default `http://localhost:3111`), then reload MCP. -- Native Windows: the CLI does not auto-extract the ZIP. Install the pinned v0.19.7 `iii.exe` manually, use WSL2, or run with Docker Desktop and `AGENTMEMORY_USE_DOCKER=1`. Automated `connect` supports only `copilot-cli`; configure other native agents manually. +- Native Windows: the CLI does not auto-extract the ZIP. Install the pinned v0.22.1 `iii.exe` manually, use WSL2, or run with Docker Desktop and `AGENTMEMORY_USE_DOCKER=1`. Automated `connect` supports only `copilot-cli`; configure other native agents manually. - Semantic demo query returns zero hits: this is expected with vectors disabled in default keyless mode. Set `EMBEDDING_PROVIDER=local`, restart, allow the first model download to complete, and rerun the demo. ## Report success @@ -212,7 +212,7 @@ The MCP server exposes 54 tools by default (`--tools all`). Use `--tools core` ( Report back to the user: - agentmemory installed, version, and the server running on port 3111 -- iii-engine v0.19.7 running, the selected platform data directory, and all four ports accounted for +- iii-engine v0.22.1 running, the selected platform data directory, and all four ports accounted for - which agent was wired via `agentmemory connect`, and the tool count the agent now sees - the save and recall round-trip returned the probe memory after a full stop/start - the viewer is available at `http://localhost:3113` diff --git a/README.md b/README.md index 730342b24b..8c376dddcc 100644 --- a/README.md +++ b/README.md @@ -79,7 +79,7 @@ Requirements: - Node.js 20 or newer with npm and npx (`node -v`, `npm -v`, and `npx -v`). - macOS/Linux automatic iii-engine installation also needs `curl`, a POSIX `sh`, and `tar`. Minimal images such as `node:20-slim` may not include them. -- Native Windows requires the pinned iii-engine v0.19.7 `iii.exe` to be installed manually. WSL2 or Docker Desktop are the other supported paths. +- Native Windows requires the pinned iii-engine v0.22.1 `iii.exe` to be installed manually. WSL2 or Docker Desktop are the other supported paths. Canonical fresh-install command: @@ -111,7 +111,7 @@ Wire more agents any time with `agentmemory connect ` — 20 adapters lis
Windows -The fast path is WSL2. Native Windows engine setup requires the pinned v0.19.7 ZIP to be downloaded and `iii.exe` extracted manually; the CLI does not auto-extract it. Docker Desktop is also supported. See the [Windows notes](#windows) for the step-by-step. +The fast path is WSL2. Native Windows engine setup requires the pinned v0.22.1 ZIP to be downloaded and `iii.exe` extracted manually; the CLI does not auto-extract it. Docker Desktop is also supported. See the [Windows notes](#windows) for the step-by-step.
@@ -136,7 +136,7 @@ npx caches per version. Force the latest with `npx -y @agentmemory/agentmemory@l
Already running your own iii engine -agentmemory pins iii-engine v0.19.7 and won't attach to a different version (the worker can't speak another engine's protocol). Stop the other engine, then run `npx -y @agentmemory/agentmemory@latest`. It installs and runs the pinned v0.19.7 in `~/.agentmemory/bin`, leaving your own `iii` untouched. +agentmemory pins iii-engine v0.22.1 and won't attach to a different version (the worker can't speak another engine's protocol). Stop the other engine, then run `npx -y @agentmemory/agentmemory@latest`. It installs and runs the pinned v0.22.1 in `~/.agentmemory/bin`, leaving your own `iii` untouched.
@@ -496,7 +496,7 @@ None of these auto-capture from coding-agent hooks, ship a local-first viewer, o

Quick Start

-Compatibility: this release targets `iii-sdk` 0.19.7 and pins iii-engine v0.19.7. +Compatibility: this release targets `iii-sdk` 0.22.1 and pins iii-engine v0.22.1. ### Try it in 30 seconds @@ -575,7 +575,7 @@ Use the maintenance command when you intentionally want to update your local run npx -y @agentmemory/agentmemory@latest upgrade ``` -Warning: this command mutates the current workspace/runtime. It can update JavaScript dependencies and pull the pinned `iiidev/iii:0.19.7` Docker image. It never installs an unpinned or newer iii engine. +Warning: this command mutates the current workspace/runtime. It can update JavaScript dependencies and pull the pinned `iiidev/iii:0.22.1` Docker image. It never installs an unpinned or newer iii engine. Implementation details live in `src/cli.ts` (see `runUpgrade` around the `src/cli.ts:544-595` region). @@ -793,28 +793,28 @@ npm install && npm run build && npm start This starts agentmemory with a local `iii-engine` if the pinned binary is already installed, or uses Docker Compose when selected. REST, streams, and the viewer bind to `127.0.0.1` by default. The automatic macOS/Linux binary path requires `curl`, a POSIX `sh`, and `tar`. -Install `iii-engine` manually. **agentmemory currently pins `iii-engine` to `v0.19.7`**, the same release as its `iii-sdk` dependency; the worker speaks that engine's wire protocol, and 0.20.0 reorganized the SDK surface, so the two move together in agentmemory releases. Override with `AGENTMEMORY_III_VERSION=` if you run your own engine and know it matches. +Install `iii-engine` manually. **agentmemory currently pins `iii-engine` to `v0.22.1`**, the same release as its `iii-sdk` dependency; the worker speaks that engine's wire protocol, and 0.20.0 reorganized the SDK surface, so the two move together in agentmemory releases. Override with `AGENTMEMORY_III_VERSION=` if you run your own engine and know it matches. -- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.19.7/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` +- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.22.1/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` - **macOS x64:** swap `aarch64-apple-darwin` for `x86_64-apple-darwin` - **Linux x64:** swap for `x86_64-unknown-linux-gnu` - **Linux arm64:** swap for `aarch64-unknown-linux-gnu` -- **Windows:** download `iii-x86_64-pc-windows-msvc.zip` from [iii-hq/iii releases v0.19.7](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7) and extract `iii.exe` to `%USERPROFILE%\.agentmemory\bin\iii.exe` +- **Windows:** download `iii-x86_64-pc-windows-msvc.zip` from [iii-hq/iii releases v0.22.1](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.22.1) and extract `iii.exe` to `%USERPROFILE%\.agentmemory\bin\iii.exe` -Or use Docker (the bundled `docker-compose.yml` pulls `iiidev/iii:0.19.7`). Full docs: [iii.dev/docs](https://iii.dev/docs). +Or use Docker (the bundled `docker-compose.yml` pulls `iiidev/iii:0.22.1`). Full docs: [iii.dev/docs](https://iii.dev/docs). ### Windows -agentmemory runs on Windows 10/11, but the Node.js package alone isn't enough; you also need the pinned iii-engine v0.19.7 runtime as a background process. The CLI does not auto-extract the Windows ZIP, so native Windows users must install `iii.exe` manually, use WSL2, or choose Docker Desktop. +agentmemory runs on Windows 10/11, but the Node.js package alone isn't enough; you also need the pinned iii-engine v0.22.1 runtime as a background process. The CLI does not auto-extract the Windows ZIP, so native Windows users must install `iii.exe` manually, use WSL2, or choose Docker Desktop. Native Windows automated MCP wiring supports only `agentmemory connect copilot-cli`. For Claude Code, Codex, Cursor, and every other native Windows agent, copy the manual MCP block from [Other agents](#other-agents) into that agent's Windows config. Running `connect` in WSL is appropriate only when the target agent is also installed in the same WSL environment; it does not edit a Windows-host agent's configuration. **Option A: prebuilt Windows binary (recommended)** ```powershell -# 1. Open https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7 in your browser +# 1. Open https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.22.1 in your browser # (agentmemory pins the engine to the same release as its iii-sdk; -# v0.19.7 is the current pair) +# v0.22.1 is the current pair) # 2. Download iii-x86_64-pc-windows-msvc.zip # (or iii-aarch64-pc-windows-msvc.zip if you're on an ARM machine) # 3. Extract iii.exe to agentmemory's private engine directory: @@ -822,7 +822,7 @@ New-Item -ItemType Directory -Force "$HOME\.agentmemory\bin" # Copy iii.exe to $HOME\.agentmemory\bin\iii.exe # 4. Verify: & "$HOME\.agentmemory\bin\iii.exe" --version -# Should print: 0.19.7 +# Should print: 0.22.1 # 5. Then run agentmemory as usual: npx -y @agentmemory/agentmemory@latest @@ -855,7 +855,7 @@ npx -y @agentmemory/mcp | Port conflict | `netstat -ano \| findstr :3111` to see what's bound, then kill it or use `--port ` | | Docker fallback skipped even though Docker is installed | Make sure Docker Desktop is actually running (system tray icon) | -> Note: the iii **engine** is a prebuilt binary, not a cargo crate, so don't try to `cargo install` it. (The iii **SDKs** are published on crates.io, npm, and PyPI, but agentmemory doesn't need them.) Supported engine install methods are all pinned to v0.19.7: the prebuilt binary above, agentmemory's macOS/Linux auto-install path (`curl`, POSIX `sh`, and `tar` required), and the Docker image `iiidev/iii:0.19.7`. A bare upstream `install.sh | sh` installs the latest engine, which agentmemory does not support. Use `npx -y @agentmemory/agentmemory@latest`; on macOS/Linux it fetches the pinned engine into `~/.agentmemory/bin`. +> Note: the iii **engine** is a prebuilt binary, not a cargo crate, so don't try to `cargo install` it. (The iii **SDKs** are published on crates.io, npm, and PyPI, but agentmemory doesn't need them.) Supported engine install methods are all pinned to v0.22.1: the prebuilt binary above, agentmemory's macOS/Linux auto-install path (`curl`, POSIX `sh`, and `tar` required), and the Docker image `iiidev/iii:0.22.1`. A bare upstream `install.sh | sh` installs the latest engine, which agentmemory does not support. Use `npx -y @agentmemory/agentmemory@latest`; on macOS/Linux it fetches the pinned engine into `~/.agentmemory/bin`. --- @@ -1210,22 +1210,20 @@ agentmemory ships this for free because every function call and trigger fires th Workers page: every connected worker, including agentmemory itself, with PID, function count, runtime, and last-seen.

-**Already installed.** The console ships with `iii`; no separate installer. +**Already installed.** The console ships with the pinned `iii` engine (0.22+); nothing separate to install. The first launch downloads the console binary next to the engine. **Launch alongside agentmemory:** ```bash -# agentmemory viewer holds port 3113, so run the console on 3114. -# Engine REST (3111), WebSocket (3112), and bridge (49134) defaults match agentmemory. -iii console --port 3114 +agentmemory console ``` -Then open `http://localhost:3114`. Add `--enable-flow` for the experimental architecture-graph page. +This runs the pinned engine's `iii console` against the ports agentmemory resolved (REST, streams, bridge) and serves it one port above the viewer, `http://localhost:3114` by default. `--console-port N` picks another port; `--port` and `--instance` select the agentmemory instance the same way they do for `stop`; any other flag is passed through, for example `--enable-flow` for the experimental architecture-graph page. -Override engine endpoints only if you've moved them: +The same thing by hand, useful when `agentmemory` is not on PATH: ```bash -iii console --port 3114 \ +~/.agentmemory/bin/iii console --port 3114 \ --engine-port 3111 \ --ws-port 3112 \ --bridge-port 49134 @@ -1254,7 +1252,7 @@ iii console --port 3114 \ **Traces are already on:** -`iii-config.yaml` ships with the `iii-observability` worker enabled (`exporter: memory`, `sampling_ratio: 1.0`, metrics + logs). No extra config needed; the moment agentmemory starts, every memory operation emits a trace span and a structured log the console can read. +`iii-config.yaml` ships with the `iii-observability` worker enabled (`exporter: memory`, `sampling_ratio: 0.1`, metrics + logs). No extra config needed; the moment agentmemory starts, every memory operation emits a structured log the console can read, and one in ten of them (`sampling_ratio: 0.1`) also emits a trace span. If you want to export to Jaeger/Honeycomb/Grafana Tempo instead, change `exporter: memory` to `exporter: otlp` and set the collector endpoint per iii's observability docs. @@ -1268,30 +1266,26 @@ agentmemory is **already a running [iii](https://iii.dev) instance**. Three prim That means one more command extends agentmemory with an entire new capability. -### Extend agentmemory with one command +### Extend agentmemory with more workers -```bash -iii worker add iii-pubsub # fan memory writes out to every connected instance -iii worker add iii-cron # scheduled consolidation, decay sweeps, snapshot rotation -iii worker add iii-queue # durable retries for embedding + compression jobs -iii worker add iii-observability # OTEL traces on every memory op (default on) -iii worker add iii-sandbox # run recalled code inside an isolated microVM -iii worker add iii-database # swap in a SQL-backed state adapter -iii worker add mcp # generic MCP host alongside the agentmemory MCP -``` +The builtins agentmemory needs are already in `iii-config.yaml` and boot with it: `iii-state` (KV), `iii-queue` (durable retries for the event subscribers), `iii-pubsub`, `iii-cron`, `iii-stream`, and `iii-observability` (OTEL traces, metrics and logs on every function). Anything else from the [iii worker registry](https://workers.iii.dev) plugs into the same engine: copy `iii-config.yaml` to `~/.agentmemory/iii-config.yaml` (the CLI prefers that file over the bundled one and still renders ports and data paths into it), add the entry, install the worker runtime once with `~/.agentmemory/bin/iii update worker`, and restart agentmemory. -Each `iii worker add` registers new functions and triggers into the same engine agentmemory is already running on. The viewer and console pick them up immediately: no reload, no new integration, no new container. +```yaml +workers: + # ...the bundled entries... + - name: database # SQL-backed state adapter when you outgrow the KV defaults + - name: iii-sandbox # run code that came out of memory_recall inside a throwaway VM + - name: mcp # extra MCP servers next to agentmemory's, same engine +``` -| `iii worker add` | What you get on top of agentmemory | +| Worker | What you get on top of agentmemory | |---|---| -| [`iii-pubsub`](https://workers.iii.dev/workers/iii-pubsub) | Multi-instance memory: every `remember` fans out, every `search` reads the union | -| [`iii-cron`](https://workers.iii.dev/workers/iii-cron) | Scheduled lifecycle: nightly consolidation, weekly snapshots, decay on a fixed clock | -| [`iii-queue`](https://workers.iii.dev/workers/iii-queue) | Durable retries: failed embedding + compression jobs survive restart, no lost observations | -| [`iii-observability`](https://workers.iii.dev/workers/iii-observability) | OTEL traces, metrics, logs on every function, wired in `iii-config.yaml` from day one | +| [`database`](https://workers.iii.dev/workers/database) | SQL-backed state adapter when you outgrow the in-memory KV defaults | | [`iii-sandbox`](https://workers.iii.dev/workers/iii-sandbox) | Code that came out of `memory_recall` runs inside a throwaway VM, not your shell | -| [`iii-database`](https://workers.iii.dev/workers/iii-database) | SQL-backed state adapter when you outgrow the in-memory KV defaults | | [`mcp`](https://workers.iii.dev/workers/mcp) | Stand up extra MCP servers next to agentmemory's, share the same engine | +On engine 0.22.x keep the `iii-` prefixed names for the builtins above; the unprefixed `http`, `state`, `queue`, `pubsub` and `cron` entries are the standalone registry workers agentmemory moves to with the 0.23 migration. + Full registry: [workers.iii.dev](https://workers.iii.dev). Every worker there composes through the same primitives agentmemory uses, and the agentmemory you already have is one of them. ### What iii replaces @@ -1433,6 +1427,8 @@ agentmemory + iii-engine bind four ports by default. If a restart fails with `po `--port ` changes the REST anchor and derives streams `N+1`, viewer `N+2`, and engine WebSocket `N+46023` only where the corresponding explicit port or URL above is unset. It does not create an isolated lifecycle namespace. Use `--instance 1` for a second daemon; it uses anchor 3211, defaults to `3211/3212/3213/49234`, and receives a separate `instance-1` data and lifecycle directory. Instances 1 through 50 follow the same pattern. +The pinned engine starts with `--no-update-check` (no update or security-advisory lookups against GitHub at boot) and with iii's anonymous usage telemetry off: agentmemory sets `III_TELEMETRY_ENABLED=false` for the engine it spawns unless you export the variable yourself, and the bundled compose file does the same. + Stale-process cleanup when ports stay bound after a crashed run: ```bash @@ -1546,6 +1542,9 @@ Create `~/.agentmemory/.env`: # Ports (defaults: 3111 API, 3113 viewer) # III_REST_PORT=3111 +# Engine usage telemetry (iii). Off unless you set it; true opts in. +# III_TELEMETRY_ENABLED=false + # Features # AGENTMEMORY_AUTO_COMPRESS=false # OFF by default. Requires an LLM # provider as well. When both are on, @@ -1647,7 +1646,7 @@ npm test # 1,674 tests npm run test:integration # API tests (requires running services) ``` -**Prerequisites:** Node.js >= 20 with npm/npx; [iii-engine](https://iii.dev/docs) v0.19.7 or Docker. The macOS/Linux automatic engine install also requires `curl`, a POSIX `sh`, and `tar`; native Windows uses the manual pinned `iii.exe`, WSL2, or Docker Desktop. +**Prerequisites:** Node.js >= 20 with npm/npx; [iii-engine](https://iii.dev/docs) v0.22.1 or Docker. The macOS/Linux automatic engine install also requires `curl`, a POSIX `sh`, and `tar`; native Windows uses the manual pinned `iii.exe`, WSL2, or Docker Desktop.

License

diff --git a/READMEs/README.de-DE.md b/READMEs/README.de-DE.md index 3ea4fc9a1c..02631d18af 100644 --- a/READMEs/README.de-DE.md +++ b/READMEs/README.de-DE.md @@ -124,7 +124,7 @@ npx cached pro Version. Erzwingen Sie die neueste mit `npx -y @agentmemory/agent
Sie betreiben bereits eine eigene iii-Engine -agentmemory pinnt iii-engine v0.19.7 und verbindet sich nicht mit einer anderen Version (der Worker kann das Protokoll einer anderen Engine nicht sprechen). Stoppen Sie die andere Engine und führen Sie dann `npx -y @agentmemory/agentmemory@latest` aus. Es installiert und startet das gepinnte v0.19.7 in `~/.agentmemory/bin` und lässt Ihre eigene `iii` unangetastet. +agentmemory pinnt iii-engine v0.22.1 und verbindet sich nicht mit einer anderen Version (der Worker kann das Protokoll einer anderen Engine nicht sprechen). Stoppen Sie die andere Engine und führen Sie dann `npx -y @agentmemory/agentmemory@latest` aus. Es installiert und startet das gepinnte v0.22.1 in `~/.agentmemory/bin` und lässt Ihre eigene `iii` unangetastet.
@@ -463,7 +463,7 @@ Keines davon erfasst automatisch aus Coding-Agent-Hooks, liefert einen local-fir

Schnellstart

-Kompatibilität: Diese Version zielt auf `iii-sdk` 0.19.7 und pinnt iii-engine v0.19.7. +Kompatibilität: Diese Version zielt auf `iii-sdk` 0.22.1 und pinnt iii-engine v0.22.1. ### In 30 Sekunden ausprobieren @@ -517,7 +517,7 @@ Verwenden Sie den Wartungsbefehl, wenn Sie Ihr lokales Runtime bewusst aktualisi npx @agentmemory/agentmemory upgrade ``` -Achtung: Dieser Befehl verändert den aktuellen Workspace/Runtime. Er kann JavaScript-Abhängigkeiten aktualisieren und das gepinnte Docker-Image `iiidev/iii:0.19.7` ziehen. Er installiert niemals eine ungepinnte oder neuere iii-Engine. +Achtung: Dieser Befehl verändert den aktuellen Workspace/Runtime. Er kann JavaScript-Abhängigkeiten aktualisieren und das gepinnte Docker-Image `iiidev/iii:0.22.1` ziehen. Er installiert niemals eine ungepinnte oder neuere iii-Engine. Implementierungsdetails in `src/cli.ts` (siehe `runUpgrade` rund um den Bereich `src/cli.ts:544-595`). @@ -721,15 +721,15 @@ npm install && npm run build && npm start Das startet agentmemory mit einer lokalen `iii-engine`, falls `iii` bereits installiert ist, oder fällt auf Docker Compose zurück, falls Docker vorhanden ist. REST, Streams und der Viewer binden sich standardmäßig an `127.0.0.1`. -`iii-engine` manuell installieren. **agentmemory pinnt `iii-engine` derzeit auf `v0.19.7`**, dieselbe Version wie seine `iii-sdk`-Abhängigkeit; der Worker spricht das Wire-Protokoll genau dieser Engine, und 0.20.0 hat die SDK-Oberfläche neu organisiert, daher werden beide in agentmemory-Releases gemeinsam angehoben. Mit `AGENTMEMORY_III_VERSION=` überschreiben, wenn du eine eigene Engine betreibst und weißt, dass sie passt. +`iii-engine` manuell installieren. **agentmemory pinnt `iii-engine` derzeit auf `v0.22.1`**, dieselbe Version wie seine `iii-sdk`-Abhängigkeit; der Worker spricht das Wire-Protokoll genau dieser Engine, und 0.20.0 hat die SDK-Oberfläche neu organisiert, daher werden beide in agentmemory-Releases gemeinsam angehoben. Mit `AGENTMEMORY_III_VERSION=` überschreiben, wenn du eine eigene Engine betreibst und weißt, dass sie passt. -- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.19.7/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` +- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.22.1/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` - **macOS x64:** `aarch64-apple-darwin` durch `x86_64-apple-darwin` ersetzen - **Linux x64:** durch `x86_64-unknown-linux-gnu` ersetzen - **Linux arm64:** durch `aarch64-unknown-linux-gnu` ersetzen -- **Windows:** `iii-x86_64-pc-windows-msvc.zip` von [iii-hq/iii releases v0.19.7](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7) herunterladen, `iii.exe` extrahieren, zum PATH hinzufügen +- **Windows:** `iii-x86_64-pc-windows-msvc.zip` von [iii-hq/iii releases v0.22.1](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.22.1) herunterladen, `iii.exe` extrahieren, zum PATH hinzufügen -Oder Docker verwenden (die mitgelieferte `docker-compose.yml` zieht `iiidev/iii:0.19.7`). Vollständige Doku: [iii.dev/docs](https://iii.dev/docs). +Oder Docker verwenden (die mitgelieferte `docker-compose.yml` zieht `iiidev/iii:0.22.1`). Vollständige Doku: [iii.dev/docs](https://iii.dev/docs). ### Windows @@ -738,9 +738,9 @@ agentmemory läuft auf Windows 10/11, aber das Node.js-Paket allein genügt nich **Option A: vorgebautes Windows-Binary (empfohlen)** ```powershell -# 1. Open https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7 in your browser +# 1. Open https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.22.1 in your browser # (agentmemory pins the engine to the same release as its iii-sdk; -# v0.19.7 is the current pair) +# v0.22.1 is the current pair) # 2. Download iii-x86_64-pc-windows-msvc.zip # (or iii-aarch64-pc-windows-msvc.zip if you're on an ARM machine) # 3. Extract iii.exe somewhere on PATH, or place it at: @@ -748,7 +748,7 @@ agentmemory läuft auf Windows 10/11, aber das Node.js-Paket allein genügt nich # (agentmemory checks that location automatically) # 4. Verify: iii --version -# Should print: 0.19.7 +# Should print: 0.22.1 # 5. Then run agentmemory as usual: npx -y @agentmemory/agentmemory @@ -780,7 +780,7 @@ npx -y @agentmemory/mcp | Port-Konflikt | `netstat -ano \| findstr :3111`, um zu sehen, was gebunden ist, dann beenden oder `--port ` verwenden | | Docker-Fallback wird übersprungen, obwohl Docker installiert ist | Stellen Sie sicher, dass Docker Desktop tatsächlich läuft (Taskleisten-Icon) | -> Hinweis: Die iii-**Engine** ist ein vorgebautes Binary, kein Cargo-Crate, versuche also nicht, sie per `cargo install` zu installieren. (Die iii-**SDKs** sind auf crates.io, npm und PyPI veröffentlicht, aber agentmemory benötigt sie nicht.) Unterstützte Engine-Installationsmethoden, alle auf v0.19.7 gepinnt: das vorgebaute v0.19.7-Binary oben, das Upstream-`sh`-Installationsskript **mit dem Versions-Pin** `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.19.7 sh` (macOS/Linux) und das Docker-Image `iiidev/iii:0.19.7`. Ein bloßes `install.sh | sh` installiert die **neueste** Engine, die agentmemory nicht unterstützt; übergib immer `VERSION=0.19.7`. Am einfachsten von allen: Führe einfach `npx @agentmemory/agentmemory` aus, das die gepinnte Engine für dich nach `~/.agentmemory/bin` holt. +> Hinweis: Die iii-**Engine** ist ein vorgebautes Binary, kein Cargo-Crate, versuche also nicht, sie per `cargo install` zu installieren. (Die iii-**SDKs** sind auf crates.io, npm und PyPI veröffentlicht, aber agentmemory benötigt sie nicht.) Unterstützte Engine-Installationsmethoden, alle auf v0.22.1 gepinnt: das vorgebaute v0.22.1-Binary oben, das Upstream-`sh`-Installationsskript **mit dem Versions-Pin** `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.22.1 sh` (macOS/Linux) und das Docker-Image `iiidev/iii:0.22.1`. Ein bloßes `install.sh | sh` installiert die **neueste** Engine, die agentmemory nicht unterstützt; übergib immer `VERSION=0.22.1`. Am einfachsten von allen: Führe einfach `npx @agentmemory/agentmemory` aus, das die gepinnte Engine für dich nach `~/.agentmemory/bin` holt. --- @@ -1176,7 +1176,7 @@ iii console --port 3114 \ **Traces sind bereits aktiv:** -`iii-config.yaml` wird mit aktiviertem `iii-observability`-Worker ausgeliefert (`exporter: memory`, `sampling_ratio: 1.0`, Metriken + Logs). Keine zusätzliche Konfig nötig; in dem Moment, in dem agentmemory startet, emittiert jede Memory-Operation einen Trace-Span und ein strukturiertes Log, das die Console lesen kann. +`iii-config.yaml` wird mit aktiviertem `iii-observability`-Worker ausgeliefert (`exporter: memory`, `sampling_ratio: 0.1`, Metriken + Logs). Keine zusätzliche Konfig nötig; in dem Moment, in dem agentmemory startet, emittiert jede Memory-Operation ein strukturiertes Log, das die Console lesen kann, und jede zehnte (`sampling_ratio: 0.1`) zusätzlich einen Trace-Span. Wenn Sie stattdessen zu Jaeger/Honeycomb/Grafana Tempo exportieren wollen, ändern Sie `exporter: memory` zu `exporter: otlp` und setzen den Collector-Endpunkt gemäß der iii-Observability-Doku. @@ -1198,7 +1198,7 @@ iii worker add iii-cron # scheduled consolidation, decay sweeps, snap iii worker add iii-queue # durable retries for embedding + compression jobs iii worker add iii-observability # OTEL traces on every memory op (default on) iii worker add iii-sandbox # run recalled code inside an isolated microVM -iii worker add iii-database # swap in a SQL-backed state adapter +iii worker add database # swap in a SQL-backed state adapter iii worker add mcp # generic MCP host alongside the agentmemory MCP ``` @@ -1211,7 +1211,7 @@ Jedes `iii worker add` registriert neue Funktionen und Trigger im selben Engine, | [`iii-queue`](https://workers.iii.dev/workers/iii-queue) | Durable Retries: fehlgeschlagene Embedding-/Kompressions-Jobs überleben den Neustart, keine verlorenen Beobachtungen | | [`iii-observability`](https://workers.iii.dev/workers/iii-observability) | OTEL-Traces, Metriken, Logs auf jeder Funktion, in `iii-config.yaml` ab dem ersten Tag verdrahtet | | [`iii-sandbox`](https://workers.iii.dev/workers/iii-sandbox) | Code, der aus `memory_recall` kommt, läuft in einer wegwerf-VM, nicht in Ihrer Shell | -| [`iii-database`](https://workers.iii.dev/workers/iii-database) | SQL-gestützter State-Adapter, wenn Sie die In-Memory-KV-Voreinstellungen überwachsen | +| [`database`](https://workers.iii.dev/workers/database) | SQL-gestützter State-Adapter, wenn Sie die In-Memory-KV-Voreinstellungen überwachsen | | [`mcp`](https://workers.iii.dev/workers/mcp) | Zusätzliche MCP-Server neben dem von agentmemory aufstellen, die sich denselben Engine teilen | Volle Registry: [workers.iii.dev](https://workers.iii.dev). Jeder Worker dort komponiert sich über dieselben Primitiven wie agentmemory, und das agentmemory, das Sie bereits haben, ist einer davon. diff --git a/READMEs/README.es-ES.md b/READMEs/README.es-ES.md index dfb7030946..a01a1618c1 100644 --- a/READMEs/README.es-ES.md +++ b/READMEs/README.es-ES.md @@ -124,7 +124,7 @@ npx cachea por versión. Fuerza la última con `npx -y @agentmemory/agentmemory@
Ya ejecutas tu propio engine iii -agentmemory fija iii-engine a v0.19.7 y no se conectará a una versión distinta (el worker no puede hablar el protocolo de otro engine). Detén el otro engine y ejecuta `npx -y @agentmemory/agentmemory@latest`. Instala y ejecuta la v0.19.7 fijada en `~/.agentmemory/bin`, dejando tu propio `iii` intacto. +agentmemory fija iii-engine a v0.22.1 y no se conectará a una versión distinta (el worker no puede hablar el protocolo de otro engine). Detén el otro engine y ejecuta `npx -y @agentmemory/agentmemory@latest`. Instala y ejecuta la v0.22.1 fijada en `~/.agentmemory/bin`, dejando tu propio `iii` intacto.
@@ -463,7 +463,7 @@ Ninguno de estos captura automáticamente desde hooks de agentes de codificació

Inicio rápido

-Compatibilidad: esta release apunta a `iii-sdk` 0.19.7 y fija iii-engine v0.19.7. +Compatibilidad: esta release apunta a `iii-sdk` 0.22.1 y fija iii-engine v0.22.1. ### Pruébalo en 30 segundos @@ -517,7 +517,7 @@ Usa el comando de mantenimiento cuando intencionadamente quieras actualizar tu r npx @agentmemory/agentmemory upgrade ``` -Aviso: este comando muta el workspace/runtime actual. Puede actualizar dependencias de JavaScript y traer la imagen Docker fijada `iiidev/iii:0.19.7`. Nunca instala un motor iii sin fijar ni más nuevo. +Aviso: este comando muta el workspace/runtime actual. Puede actualizar dependencias de JavaScript y traer la imagen Docker fijada `iiidev/iii:0.22.1`. Nunca instala un motor iii sin fijar ni más nuevo. Los detalles de implementación están en `src/cli.ts` (ver `runUpgrade` en torno a la región `src/cli.ts:544-595`). @@ -721,15 +721,15 @@ npm install && npm run build && npm start Esto arranca agentmemory con un `iii-engine` local si `iii` ya está instalado, o cae a Docker Compose si hay Docker disponible. REST, streams y el visor se enlazan a `127.0.0.1` por defecto. -Instala `iii-engine` manualmente. **agentmemory actualmente fija `iii-engine` a `v0.19.7`**, la misma release que su dependencia `iii-sdk`; el worker habla el protocolo de ese engine, y 0.20.0 reorganizó la superficie del SDK, así que ambos avanzan juntos en cada release de agentmemory. Sobrescribe con `AGENTMEMORY_III_VERSION=` si ejecutas tu propio engine y sabes que coincide. +Instala `iii-engine` manualmente. **agentmemory actualmente fija `iii-engine` a `v0.22.1`**, la misma release que su dependencia `iii-sdk`; el worker habla el protocolo de ese engine, y 0.20.0 reorganizó la superficie del SDK, así que ambos avanzan juntos en cada release de agentmemory. Sobrescribe con `AGENTMEMORY_III_VERSION=` si ejecutas tu propio engine y sabes que coincide. -- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.19.7/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` +- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.22.1/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` - **macOS x64:** cambia `aarch64-apple-darwin` por `x86_64-apple-darwin` - **Linux x64:** cambia por `x86_64-unknown-linux-gnu` - **Linux arm64:** cambia por `aarch64-unknown-linux-gnu` -- **Windows:** descarga `iii-x86_64-pc-windows-msvc.zip` desde [iii-hq/iii releases v0.19.7](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7), extrae `iii.exe`, añádelo al PATH +- **Windows:** descarga `iii-x86_64-pc-windows-msvc.zip` desde [iii-hq/iii releases v0.22.1](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.22.1), extrae `iii.exe`, añádelo al PATH -O usa Docker (el `docker-compose.yml` empaquetado descarga `iiidev/iii:0.19.7`). Documentación completa: [iii.dev/docs](https://iii.dev/docs). +O usa Docker (el `docker-compose.yml` empaquetado descarga `iiidev/iii:0.22.1`). Documentación completa: [iii.dev/docs](https://iii.dev/docs). ### Windows @@ -738,9 +738,9 @@ agentmemory funciona en Windows 10/11, pero el paquete de Node.js por sí solo n **Opción A: binario Windows preconstruido (recomendado)** ```powershell -# 1. Open https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7 in your browser +# 1. Open https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.22.1 in your browser # (agentmemory pins the engine to the same release as its iii-sdk; -# v0.19.7 is the current pair) +# v0.22.1 is the current pair) # 2. Download iii-x86_64-pc-windows-msvc.zip # (or iii-aarch64-pc-windows-msvc.zip if you're on an ARM machine) # 3. Extract iii.exe somewhere on PATH, or place it at: @@ -748,7 +748,7 @@ agentmemory funciona en Windows 10/11, pero el paquete de Node.js por sí solo n # (agentmemory checks that location automatically) # 4. Verify: iii --version -# Should print: 0.19.7 +# Should print: 0.22.1 # 5. Then run agentmemory as usual: npx -y @agentmemory/agentmemory @@ -780,7 +780,7 @@ npx -y @agentmemory/mcp | Conflicto de puerto | `netstat -ano \| findstr :3111` para ver qué está vinculado, mátalo o usa `--port ` | | Se omite el fallback a Docker aunque Docker esté instalado | Asegúrate de que Docker Desktop esté efectivamente en ejecución (icono en la bandeja del sistema) | -> Nota: el **motor** iii es un binario preconstruido, no un crate de cargo, así que no intentes instalarlo con `cargo install`. (Los **SDK** de iii sí están publicados en crates.io, npm y PyPI, pero agentmemory no los necesita.) Métodos de instalación del motor soportados, todos fijados a v0.19.7: el binario preconstruido v0.19.7 de arriba, el script de instalación `sh` upstream **con el pin de versión** `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.19.7 sh` (macOS/Linux) y la imagen Docker `iiidev/iii:0.19.7`. Un simple `install.sh | sh` instala el motor **más reciente**, que agentmemory no soporta; pasa siempre `VERSION=0.19.7`. Lo más fácil de todo: simplemente ejecuta `npx @agentmemory/agentmemory`, que obtiene el motor fijado en `~/.agentmemory/bin` por ti. +> Nota: el **motor** iii es un binario preconstruido, no un crate de cargo, así que no intentes instalarlo con `cargo install`. (Los **SDK** de iii sí están publicados en crates.io, npm y PyPI, pero agentmemory no los necesita.) Métodos de instalación del motor soportados, todos fijados a v0.22.1: el binario preconstruido v0.22.1 de arriba, el script de instalación `sh` upstream **con el pin de versión** `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.22.1 sh` (macOS/Linux) y la imagen Docker `iiidev/iii:0.22.1`. Un simple `install.sh | sh` instala el motor **más reciente**, que agentmemory no soporta; pasa siempre `VERSION=0.22.1`. Lo más fácil de todo: simplemente ejecuta `npx @agentmemory/agentmemory`, que obtiene el motor fijado en `~/.agentmemory/bin` por ti. --- @@ -1169,7 +1169,7 @@ iii console --port 3114 \ **Las trazas ya están activas:** -`iii-config.yaml` se sirve con el worker `iii-observability` habilitado (`exporter: memory`, `sampling_ratio: 1.0`, métricas + logs). No se necesita configuración adicional; desde el momento en que agentmemory arranca, cada operación de memoria emite una traza-span y un log estructurado que la console puede leer. +`iii-config.yaml` se sirve con el worker `iii-observability` habilitado (`exporter: memory`, `sampling_ratio: 0.1`, métricas + logs). No se necesita configuración adicional; desde el momento en que agentmemory arranca, cada operación de memoria emite un log estructurado que la console puede leer, y una de cada diez (`sampling_ratio: 0.1`) emite además una traza-span. Si quieres exportar a Jaeger/Honeycomb/Grafana Tempo en su lugar, cambia `exporter: memory` por `exporter: otlp` y define el endpoint del collector según la documentación de observabilidad de iii. @@ -1191,7 +1191,7 @@ iii worker add iii-cron # scheduled consolidation, decay sweeps, snap iii worker add iii-queue # durable retries for embedding + compression jobs iii worker add iii-observability # OTEL traces on every memory op (default on) iii worker add iii-sandbox # run recalled code inside an isolated microVM -iii worker add iii-database # swap in a SQL-backed state adapter +iii worker add database # swap in a SQL-backed state adapter iii worker add mcp # generic MCP host alongside the agentmemory MCP ``` @@ -1204,7 +1204,7 @@ Cada `iii worker add` registra nuevas funciones y triggers en el mismo engine en | [`iii-queue`](https://workers.iii.dev/workers/iii-queue) | Reintentos duraderos: los jobs de embedding + compresión fallidos sobreviven al reinicio, sin observaciones perdidas | | [`iii-observability`](https://workers.iii.dev/workers/iii-observability) | Trazas OTEL, métricas y logs en cada función, cableado en `iii-config.yaml` desde el primer día | | [`iii-sandbox`](https://workers.iii.dev/workers/iii-sandbox) | El código salido de `memory_recall` corre dentro de una VM desechable, no en tu shell | -| [`iii-database`](https://workers.iii.dev/workers/iii-database) | Adaptador de estado respaldado por SQL cuando te quedas pequeño con el KV in-memory por defecto | +| [`database`](https://workers.iii.dev/workers/database) | Adaptador de estado respaldado por SQL cuando te quedas pequeño con el KV in-memory por defecto | | [`mcp`](https://workers.iii.dev/workers/mcp) | Levanta servidores MCP adicionales junto al MCP de agentmemory, compartiendo el mismo engine | Registro completo: [workers.iii.dev](https://workers.iii.dev). Cada worker allí se compone a través de los mismos primitivos que usa agentmemory, y el agentmemory que ya tienes es uno de ellos. diff --git a/READMEs/README.fr-FR.md b/READMEs/README.fr-FR.md index 175d4e2259..7261aea409 100644 --- a/READMEs/README.fr-FR.md +++ b/READMEs/README.fr-FR.md @@ -124,7 +124,7 @@ npx met en cache par version. Forcez la dernière avec `npx -y @agentmemory/agen
Vous faites déjà tourner votre propre moteur iii -agentmemory épingle iii-engine v0.19.7 et ne s'attachera pas à une autre version (le worker ne peut pas parler le protocole d'un autre moteur). Arrêtez l'autre moteur, puis lancez `npx -y @agentmemory/agentmemory@latest`. Il installe et exécute le v0.19.7 épinglé dans `~/.agentmemory/bin`, sans toucher à votre propre `iii`. +agentmemory épingle iii-engine v0.22.1 et ne s'attachera pas à une autre version (le worker ne peut pas parler le protocole d'un autre moteur). Arrêtez l'autre moteur, puis lancez `npx -y @agentmemory/agentmemory@latest`. Il installe et exécute le v0.22.1 épinglé dans `~/.agentmemory/bin`, sans toucher à votre propre `iii`.
@@ -463,7 +463,7 @@ Aucun d'eux ne capture automatiquement depuis les hooks d'agents de codage, ne l

Démarrage rapide

-Compatibilité : cette version cible `iii-sdk` 0.19.7 et épingle iii-engine v0.19.7. +Compatibilité : cette version cible `iii-sdk` 0.22.1 et épingle iii-engine v0.22.1. ### Essayez en 30 secondes @@ -517,7 +517,7 @@ Utilisez la commande de maintenance lorsque vous voulez intentionnellement mettr npx @agentmemory/agentmemory upgrade ``` -Avertissement : cette commande modifie l'espace de travail / runtime courant. Elle peut mettre à jour les dépendances JavaScript et tirer l'image Docker épinglée `iiidev/iii:0.19.7`. Elle n'installe jamais un moteur iii non épinglé ou plus récent. +Avertissement : cette commande modifie l'espace de travail / runtime courant. Elle peut mettre à jour les dépendances JavaScript et tirer l'image Docker épinglée `iiidev/iii:0.22.1`. Elle n'installe jamais un moteur iii non épinglé ou plus récent. Détails d'implémentation dans `src/cli.ts` (voir `runUpgrade` autour de la zone `src/cli.ts:544-595`). @@ -721,15 +721,15 @@ npm install && npm run build && npm start Cela démarre agentmemory avec un `iii-engine` local si `iii` est déjà installé, ou retombe sur Docker Compose si Docker est disponible. REST, streams et visualiseur se lient à `127.0.0.1` par défaut. -Installer `iii-engine` manuellement. **agentmemory épingle actuellement `iii-engine` à `v0.19.7`**, la même version que sa dépendance `iii-sdk` ; le worker parle le protocole de ce moteur précis, et 0.20.0 a réorganisé la surface du SDK, donc les deux évoluent ensemble dans les versions d'agentmemory. Remplacez avec `AGENTMEMORY_III_VERSION=` si vous exécutez votre propre moteur et savez qu'il correspond. +Installer `iii-engine` manuellement. **agentmemory épingle actuellement `iii-engine` à `v0.22.1`**, la même version que sa dépendance `iii-sdk` ; le worker parle le protocole de ce moteur précis, et 0.20.0 a réorganisé la surface du SDK, donc les deux évoluent ensemble dans les versions d'agentmemory. Remplacez avec `AGENTMEMORY_III_VERSION=` si vous exécutez votre propre moteur et savez qu'il correspond. -- **macOS arm64 :** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.19.7/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` +- **macOS arm64 :** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.22.1/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` - **macOS x64 :** remplacez `aarch64-apple-darwin` par `x86_64-apple-darwin` - **Linux x64 :** remplacez par `x86_64-unknown-linux-gnu` - **Linux arm64 :** remplacez par `aarch64-unknown-linux-gnu` -- **Windows :** téléchargez `iii-x86_64-pc-windows-msvc.zip` depuis [iii-hq/iii releases v0.19.7](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7), extrayez `iii.exe`, ajoutez-le au PATH +- **Windows :** téléchargez `iii-x86_64-pc-windows-msvc.zip` depuis [iii-hq/iii releases v0.22.1](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.22.1), extrayez `iii.exe`, ajoutez-le au PATH -Ou utilisez Docker (le `docker-compose.yml` fourni tire `iiidev/iii:0.19.7`). Documentation complète : [iii.dev/docs](https://iii.dev/docs). +Ou utilisez Docker (le `docker-compose.yml` fourni tire `iiidev/iii:0.22.1`). Documentation complète : [iii.dev/docs](https://iii.dev/docs). ### Windows @@ -738,9 +738,9 @@ agentmemory tourne sur Windows 10/11, mais le paquet Node.js seul ne suffit pas **Option A : binaire Windows précompilé (recommandé)** ```powershell -# 1. Open https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7 in your browser +# 1. Open https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.22.1 in your browser # (agentmemory pins the engine to the same release as its iii-sdk; -# v0.19.7 is the current pair) +# v0.22.1 is the current pair) # 2. Download iii-x86_64-pc-windows-msvc.zip # (or iii-aarch64-pc-windows-msvc.zip if you're on an ARM machine) # 3. Extract iii.exe somewhere on PATH, or place it at: @@ -748,7 +748,7 @@ agentmemory tourne sur Windows 10/11, mais le paquet Node.js seul ne suffit pas # (agentmemory checks that location automatically) # 4. Verify: iii --version -# Should print: 0.19.7 +# Should print: 0.22.1 # 5. Then run agentmemory as usual: npx -y @agentmemory/agentmemory @@ -780,7 +780,7 @@ npx -y @agentmemory/mcp | Conflit de port | `netstat -ano \| findstr :3111` pour voir ce qui est lié, puis tuez-le ou utilisez `--port ` | | Fallback Docker ignoré bien que Docker soit installé | Assurez-vous que Docker Desktop tourne effectivement (icône de la barre d'état système) | -> Note : le **moteur** iii est un binaire précompilé, pas un crate cargo, donc n'essayez pas de l'installer avec `cargo install`. (Les **SDK** iii sont bien publiés sur crates.io, npm et PyPI, mais agentmemory n'en a pas besoin.) Méthodes d'installation du moteur supportées, toutes épinglées à v0.19.7 : le binaire précompilé v0.19.7 ci-dessus, le script d'installation `sh` amont **avec l'épingle de version** `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.19.7 sh` (macOS/Linux) et l'image Docker `iiidev/iii:0.19.7`. Un simple `install.sh | sh` installe le moteur **le plus récent**, que agentmemory ne supporte pas ; passez toujours `VERSION=0.19.7`. Le plus simple de tout : exécutez simplement `npx @agentmemory/agentmemory`, qui récupère le moteur épinglé dans `~/.agentmemory/bin` pour vous. +> Note : le **moteur** iii est un binaire précompilé, pas un crate cargo, donc n'essayez pas de l'installer avec `cargo install`. (Les **SDK** iii sont bien publiés sur crates.io, npm et PyPI, mais agentmemory n'en a pas besoin.) Méthodes d'installation du moteur supportées, toutes épinglées à v0.22.1 : le binaire précompilé v0.22.1 ci-dessus, le script d'installation `sh` amont **avec l'épingle de version** `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.22.1 sh` (macOS/Linux) et l'image Docker `iiidev/iii:0.22.1`. Un simple `install.sh | sh` installe le moteur **le plus récent**, que agentmemory ne supporte pas ; passez toujours `VERSION=0.22.1`. Le plus simple de tout : exécutez simplement `npx @agentmemory/agentmemory`, qui récupère le moteur épinglé dans `~/.agentmemory/bin` pour vous. --- @@ -1176,7 +1176,7 @@ iii console --port 3114 \ **Les traces sont déjà actives :** -`iii-config.yaml` est livré avec le worker `iii-observability` activé (`exporter: memory`, `sampling_ratio: 1.0`, métriques + logs). Aucune config supplémentaire ; dès qu'agentmemory démarre, chaque opération mémoire émet un span de trace et un log structuré que la console peut lire. +`iii-config.yaml` est livré avec le worker `iii-observability` activé (`exporter: memory`, `sampling_ratio: 0.1`, métriques + logs). Aucune config supplémentaire ; dès qu'agentmemory démarre, chaque opération mémoire émet un log structuré que la console peut lire, et une sur dix (`sampling_ratio: 0.1`) émet aussi un span de trace. Si vous voulez exporter vers Jaeger/Honeycomb/Grafana Tempo à la place, changez `exporter: memory` en `exporter: otlp` et définissez l'endpoint du collecteur selon la documentation d'observabilité d'iii. @@ -1198,7 +1198,7 @@ iii worker add iii-cron # scheduled consolidation, decay sweeps, snap iii worker add iii-queue # durable retries for embedding + compression jobs iii worker add iii-observability # OTEL traces on every memory op (default on) iii worker add iii-sandbox # run recalled code inside an isolated microVM -iii worker add iii-database # swap in a SQL-backed state adapter +iii worker add database # swap in a SQL-backed state adapter iii worker add mcp # generic MCP host alongside the agentmemory MCP ``` @@ -1211,7 +1211,7 @@ Chaque `iii worker add` enregistre de nouvelles fonctions et triggers dans le m | [`iii-queue`](https://workers.iii.dev/workers/iii-queue) | Retries durables : les jobs d'embedding + compression en échec survivent au redémarrage, aucune observation perdue | | [`iii-observability`](https://workers.iii.dev/workers/iii-observability) | Traces, métriques et logs OTEL sur chaque fonction, câblés dans `iii-config.yaml` dès le premier jour | | [`iii-sandbox`](https://workers.iii.dev/workers/iii-sandbox) | Le code issu de `memory_recall` s'exécute dans une VM jetable, pas dans votre shell | -| [`iii-database`](https://workers.iii.dev/workers/iii-database) | Adaptateur d'état adossé à SQL lorsque vous dépassez les valeurs par défaut KV en mémoire | +| [`database`](https://workers.iii.dev/workers/database) | Adaptateur d'état adossé à SQL lorsque vous dépassez les valeurs par défaut KV en mémoire | | [`mcp`](https://workers.iii.dev/workers/mcp) | Déployez des serveurs MCP supplémentaires à côté de celui d'agentmemory, partageant le même moteur | Registre complet : [workers.iii.dev](https://workers.iii.dev). Chaque worker là-bas se compose via les mêmes primitives qu'utilise agentmemory, et l'agentmemory que vous avez déjà en est un. diff --git a/READMEs/README.hi-IN.md b/READMEs/README.hi-IN.md index 20395845e7..aa959dd3f4 100644 --- a/READMEs/README.hi-IN.md +++ b/READMEs/README.hi-IN.md @@ -124,7 +124,7 @@ npx प्रति-वर्ज़न कैश करता है। नव
पहले से अपना iii engine चला रहे हैं -agentmemory iii-engine v0.19.7 को pin करता है और किसी भिन्न version से attach नहीं होगा (worker किसी दूसरे engine का protocol नहीं बोल सकता)। दूसरे engine को रोकें, फिर `npx -y @agentmemory/agentmemory@latest` चलाएँ। यह pinned v0.19.7 को `~/.agentmemory/bin` में install और run करता है, आपके अपने `iii` को अछूता छोड़ते हुए। +agentmemory iii-engine v0.22.1 को pin करता है और किसी भिन्न version से attach नहीं होगा (worker किसी दूसरे engine का protocol नहीं बोल सकता)। दूसरे engine को रोकें, फिर `npx -y @agentmemory/agentmemory@latest` चलाएँ। यह pinned v0.22.1 को `~/.agentmemory/bin` में install और run करता है, आपके अपने `iii` को अछूता छोड़ते हुए।
@@ -463,7 +463,7 @@ npx @agentmemory/agentmemory

Quick Start

-संगतता: यह रिलीज़ `iii-sdk` 0.19.7 को टार्गेट करता है और iii-engine को v0.19.7 पर pin करता है। +संगतता: यह रिलीज़ `iii-sdk` 0.22.1 को टार्गेट करता है और iii-engine को v0.22.1 पर pin करता है। ### 30 सेकंड में आज़माएँ @@ -515,7 +515,7 @@ Imported सेशंस native ones के साथ Replay picker में npx @agentmemory/agentmemory upgrade ``` -चेतावनी: यह कमांड वर्तमान workspace/runtime को mutate करता है। यह JavaScript निर्भरताएँ update कर सकता है और pinned Docker image `iiidev/iii:0.19.7` खींच सकता है। यह कभी भी unpinned या नया iii engine install नहीं करता। +चेतावनी: यह कमांड वर्तमान workspace/runtime को mutate करता है। यह JavaScript निर्भरताएँ update कर सकता है और pinned Docker image `iiidev/iii:0.22.1` खींच सकता है। यह कभी भी unpinned या नया iii engine install नहीं करता। Implementation विवरण `src/cli.ts` में हैं (`src/cli.ts:544-595` क्षेत्र के आसपास `runUpgrade` देखें)। @@ -700,15 +700,15 @@ npm install && npm run build && npm start यह agentmemory को local `iii-engine` के साथ शुरू करता है अगर `iii` पहले से installed है, या Docker उपलब्ध होने पर Docker Compose पर fallback करता है। REST, streams, और व्यूअर default रूप से `127.0.0.1` से bind करते हैं। -`iii-engine` मैनुअली इंस्टॉल करें। **agentmemory वर्तमान में `iii-engine` को `v0.19.7` पर pin करता है**, जो इसकी `iii-sdk` dependency वाला ही release है; worker उसी engine का wire protocol बोलता है, और 0.20.0 ने SDK surface को reorganize किया, इसलिए दोनों agentmemory releases में साथ बढ़ते हैं। यदि आप अपना engine चलाते हैं और जानते हैं कि वह मेल खाता है तो `AGENTMEMORY_III_VERSION=` से override करें। +`iii-engine` मैनुअली इंस्टॉल करें। **agentmemory वर्तमान में `iii-engine` को `v0.22.1` पर pin करता है**, जो इसकी `iii-sdk` dependency वाला ही release है; worker उसी engine का wire protocol बोलता है, और 0.20.0 ने SDK surface को reorganize किया, इसलिए दोनों agentmemory releases में साथ बढ़ते हैं। यदि आप अपना engine चलाते हैं और जानते हैं कि वह मेल खाता है तो `AGENTMEMORY_III_VERSION=` से override करें। -- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.19.7/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` +- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.22.1/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` - **macOS x64:** `aarch64-apple-darwin` को `x86_64-apple-darwin` के साथ बदलें - **Linux x64:** `x86_64-unknown-linux-gnu` के साथ बदलें - **Linux arm64:** `aarch64-unknown-linux-gnu` के साथ बदलें -- **Windows:** [iii-hq/iii releases v0.19.7](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7) से `iii-x86_64-pc-windows-msvc.zip` download करें, `iii.exe` extract करें, PATH में जोड़ें +- **Windows:** [iii-hq/iii releases v0.22.1](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.22.1) से `iii-x86_64-pc-windows-msvc.zip` download करें, `iii.exe` extract करें, PATH में जोड़ें -या Docker का उपयोग करें (bundled `docker-compose.yml` `iiidev/iii:0.19.7` खींचता है)। पूर्ण docs: [iii.dev/docs](https://iii.dev/docs)। +या Docker का उपयोग करें (bundled `docker-compose.yml` `iiidev/iii:0.22.1` खींचता है)। पूर्ण docs: [iii.dev/docs](https://iii.dev/docs)। ### Windows @@ -717,9 +717,9 @@ agentmemory Windows 10/11 पर चलता है, लेकिन केव **विकल्प A: prebuilt Windows binary (अनुशंसित)** ```powershell -# 1. अपने browser में https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7 खोलें +# 1. अपने browser में https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.22.1 खोलें # (agentmemory engine को अपनी iii-sdk वाले ही release पर pin करता है; -# वर्तमान pair v0.19.7 है) +# वर्तमान pair v0.22.1 है) # 2. iii-x86_64-pc-windows-msvc.zip download करें # (या ARM machine पर हैं तो iii-aarch64-pc-windows-msvc.zip) # 3. PATH पर कहीं iii.exe extract करें, या यहाँ रखें: @@ -727,7 +727,7 @@ agentmemory Windows 10/11 पर चलता है, लेकिन केव # (agentmemory उस location को automatically check करता है) # 4. Verify करें: iii --version -# Print होना चाहिए: 0.19.7 +# Print होना चाहिए: 0.22.1 # 5. फिर agentmemory को सामान्य की तरह चलाएँ: npx -y @agentmemory/agentmemory @@ -759,7 +759,7 @@ npx -y @agentmemory/mcp | Port conflict | `netstat -ano \| findstr :3111` से देखें कि क्या bind है, फिर उसे kill करें या `--port ` का उपयोग करें | | Docker installed होने पर भी Docker fallback skip हो रहा है | सुनिश्चित करें कि Docker Desktop वास्तव में चल रहा है (system tray icon) | -> नोट: iii **engine** एक prebuilt binary है, cargo crate नहीं, इसलिए इसे `cargo install` से install करने की कोशिश न करें। (iii **SDKs** crates.io, npm, और PyPI पर publish हैं, लेकिन agentmemory को उनकी ज़रूरत नहीं है।) समर्थित engine install methods, सभी v0.19.7 पर pinned: ऊपर वाला prebuilt v0.19.7 binary, version pin **के साथ** upstream `sh` install script `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.19.7 sh` (macOS/Linux), और Docker image `iiidev/iii:0.19.7`। केवल `install.sh | sh` **latest** engine install करता है, जिसे agentmemory support नहीं करता; हमेशा `VERSION=0.19.7` पास करें। सबसे आसान: बस `npx @agentmemory/agentmemory` चलाएँ, जो pinned engine को आपके लिए `~/.agentmemory/bin` में ले आता है। +> नोट: iii **engine** एक prebuilt binary है, cargo crate नहीं, इसलिए इसे `cargo install` से install करने की कोशिश न करें। (iii **SDKs** crates.io, npm, और PyPI पर publish हैं, लेकिन agentmemory को उनकी ज़रूरत नहीं है।) समर्थित engine install methods, सभी v0.22.1 पर pinned: ऊपर वाला prebuilt v0.22.1 binary, version pin **के साथ** upstream `sh` install script `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.22.1 sh` (macOS/Linux), और Docker image `iiidev/iii:0.22.1`। केवल `install.sh | sh` **latest** engine install करता है, जिसे agentmemory support नहीं करता; हमेशा `VERSION=0.22.1` पास करें। सबसे आसान: बस `npx @agentmemory/agentmemory` चलाएँ, जो pinned engine को आपके लिए `~/.agentmemory/bin` में ले आता है। --- @@ -1158,7 +1158,7 @@ iii console --port 3114 \ **Traces पहले से on हैं:** -`iii-config.yaml` `iii-observability` worker enabled (`exporter: memory`, `sampling_ratio: 1.0`, metrics + logs) के साथ ship होता है। कोई extra config की ज़रूरत नहीं; जैसे ही agentmemory शुरू होता है, हर memory operation एक trace span और एक structured log emit करता है जिसे console पढ़ सकता है। +`iii-config.yaml` `iii-observability` worker enabled (`exporter: memory`, `sampling_ratio: 0.1`, metrics + logs) के साथ ship होता है। कोई extra config की ज़रूरत नहीं; जैसे ही agentmemory शुरू होता है, हर memory operation एक structured log emit करता है जिसे console पढ़ सकता है, और उनमें से हर दसवाँ (`sampling_ratio: 0.1`) एक trace span भी emit करता है। अगर आप इसके बजाय Jaeger/Honeycomb/Grafana Tempo पर export करना चाहते हैं, तो `exporter: memory` को `exporter: otlp` में बदलें और iii के observability docs के अनुसार collector endpoint set करें। @@ -1180,7 +1180,7 @@ iii worker add iii-cron # scheduled consolidation, decay sweeps, snap iii worker add iii-queue # embedding + compression jobs के लिए durable retries iii worker add iii-observability # हर memory op पर OTEL traces (default on) iii worker add iii-sandbox # recalled code को isolated microVM के अंदर चलाएँ -iii worker add iii-database # एक SQL-backed state adapter में swap करें +iii worker add database # एक SQL-backed state adapter में swap करें iii worker add mcp # agentmemory MCP के साथ-साथ generic MCP host ``` @@ -1193,7 +1193,7 @@ iii worker add mcp # agentmemory MCP के साथ-साथ | [`iii-queue`](https://workers.iii.dev/workers/iii-queue) | Durable retries: failed embedding + compression jobs restart से बचते हैं, कोई lost observations नहीं | | [`iii-observability`](https://workers.iii.dev/workers/iii-observability) | हर function पर OTEL traces, metrics, logs, दिन एक से `iii-config.yaml` में wired | | [`iii-sandbox`](https://workers.iii.dev/workers/iii-sandbox) | `memory_recall` से निकला code throwaway VM के अंदर चलता है, आपके shell में नहीं | -| [`iii-database`](https://workers.iii.dev/workers/iii-database) | जब आप in-memory KV defaults से बाहर निकलते हैं तो SQL-backed state adapter | +| [`database`](https://workers.iii.dev/workers/database) | जब आप in-memory KV defaults से बाहर निकलते हैं तो SQL-backed state adapter | | [`mcp`](https://workers.iii.dev/workers/mcp) | agentmemory के साथ-साथ extra MCP servers खड़े करें, वही engine share करें | Full registry: [workers.iii.dev](https://workers.iii.dev)। वहाँ हर worker उन्हीं primitives के माध्यम से compose करता है जिनका agentmemory उपयोग करता है, और आपके पास पहले से जो agentmemory है, वह उनमें से एक है। diff --git a/READMEs/README.ja-JP.md b/READMEs/README.ja-JP.md index 624cc33c3a..0badfa5c99 100644 --- a/READMEs/README.ja-JP.md +++ b/READMEs/README.ja-JP.md @@ -124,7 +124,7 @@ npx はバージョン単位でキャッシュします。`npx -y @agentmemory/a
自前の iii エンジンを既に動かしている -agentmemory は iii-engine v0.19.7 にピン留めしており、異なるバージョンにはアタッチしません(worker は別のエンジンのプロトコルを話せません)。他のエンジンを停止してから `npx -y @agentmemory/agentmemory@latest` を実行してください。ピン留めされた v0.19.7 を `~/.agentmemory/bin` にインストールして実行し、あなた自身の `iii` には触れません。 +agentmemory は iii-engine v0.22.1 にピン留めしており、異なるバージョンにはアタッチしません(worker は別のエンジンのプロトコルを話せません)。他のエンジンを停止してから `npx -y @agentmemory/agentmemory@latest` を実行してください。ピン留めされた v0.22.1 を `~/.agentmemory/bin` にインストールして実行し、あなた自身の `iii` には触れません。
@@ -463,7 +463,7 @@ npx @agentmemory/agentmemory

Quick Start

-互換性:このリリースは `iii-sdk` 0.19.7 を対象とし、iii-engine v0.19.7 にピン留めします。 +互換性:このリリースは `iii-sdk` 0.22.1 を対象とし、iii-engine v0.22.1 にピン留めします。 ### 30 秒で試す @@ -517,7 +517,7 @@ npx @agentmemory/agentmemory import-jsonl ~/.claude/projects/-my-project/abc123. npx @agentmemory/agentmemory upgrade ``` -警告: このコマンドは現在のワークスペース/ランタイムを変更します。JavaScript 依存を更新したり、ピン留めされた Docker イメージ `iiidev/iii:0.19.7` を pull したりすることがあります。ピン留めされていない、あるいは新しい iii エンジンをインストールすることは決してありません。 +警告: このコマンドは現在のワークスペース/ランタイムを変更します。JavaScript 依存を更新したり、ピン留めされた Docker イメージ `iiidev/iii:0.22.1` を pull したりすることがあります。ピン留めされていない、あるいは新しい iii エンジンをインストールすることは決してありません。 実装の詳細は `src/cli.ts` を参照(`src/cli.ts:544-595` 付近の `runUpgrade`)。 @@ -722,15 +722,15 @@ npm install && npm run build && npm start `iii` が既にインストールされていれば、これでローカルの `iii-engine` で agentmemory が起動します。Docker が使える場合は Docker Compose にフォールバックします。REST、ストリーム、ビューワーはデフォルトで `127.0.0.1` にバインドします。 -`iii-engine` を手動でインストールしてください。**agentmemory は現在 `iii-engine` を `v0.19.7` にピン留めしています** — `iii-sdk` 依存関係と同じリリースです。worker はそのエンジンの wire プロトコルを話し、0.20.0 で SDK の API 面が再編されたため、両者は agentmemory のリリースで一緒に更新されます。自前のエンジンを運用していて一致していると分かっている場合は `AGENTMEMORY_III_VERSION=` で上書きできます。 +`iii-engine` を手動でインストールしてください。**agentmemory は現在 `iii-engine` を `v0.22.1` にピン留めしています** — `iii-sdk` 依存関係と同じリリースです。worker はそのエンジンの wire プロトコルを話し、0.20.0 で SDK の API 面が再編されたため、両者は agentmemory のリリースで一緒に更新されます。自前のエンジンを運用していて一致していると分かっている場合は `AGENTMEMORY_III_VERSION=` で上書きできます。 -- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.19.7/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` +- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.22.1/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` - **macOS x64:** `aarch64-apple-darwin` を `x86_64-apple-darwin` に置換 - **Linux x64:** `x86_64-unknown-linux-gnu` に置換 - **Linux arm64:** `aarch64-unknown-linux-gnu` に置換 -- **Windows:** [iii-hq/iii releases v0.19.7](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7) から `iii-x86_64-pc-windows-msvc.zip` をダウンロード、`iii.exe` を展開し PATH に追加 +- **Windows:** [iii-hq/iii releases v0.22.1](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.22.1) から `iii-x86_64-pc-windows-msvc.zip` をダウンロード、`iii.exe` を展開し PATH に追加 -または Docker を使用(同梱の `docker-compose.yml` が `iiidev/iii:0.19.7` を pull します)。詳細ドキュメント:[iii.dev/docs](https://iii.dev/docs)。 +または Docker を使用(同梱の `docker-compose.yml` が `iiidev/iii:0.22.1` を pull します)。詳細ドキュメント:[iii.dev/docs](https://iii.dev/docs)。 ### Windows @@ -739,9 +739,9 @@ agentmemory は Windows 10/11 で動作しますが、Node.js パッケージだ **選択肢 A: ビルド済み Windows バイナリ(推奨)** ```powershell -# 1. ブラウザで https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7 を開く +# 1. ブラウザで https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.22.1 を開く # (agentmemory はエンジンを iii-sdk と同じリリースにピン留めしています。 -# 現在のペアは v0.19.7) +# 現在のペアは v0.22.1) # 2. iii-x86_64-pc-windows-msvc.zip をダウンロード # (ARM マシンの場合は iii-aarch64-pc-windows-msvc.zip) # 3. iii.exe を PATH 上のどこかに展開、または以下に配置: @@ -749,7 +749,7 @@ agentmemory は Windows 10/11 で動作しますが、Node.js パッケージだ # (agentmemory はこの場所を自動でチェックします) # 4. 確認: iii --version -# 出力: 0.19.7 +# 出力: 0.22.1 # 5. その後 agentmemory を通常通り起動: npx -y @agentmemory/agentmemory @@ -781,7 +781,7 @@ npx -y @agentmemory/mcp | ポート競合 | `netstat -ano \| findstr :3111` でバインドを確認、kill するか `--port ` を使用 | | Docker をインストール済みなのにフォールバックがスキップされる | Docker Desktop が実際に動作している(システムトレイアイコン)ことを確認 | -> 注意: iii **エンジン** はビルド済みバイナリであり、cargo クレートではありません — `cargo install` でインストールしようとしないでください。(iii **SDK** は crates.io、npm、PyPI に公開されていますが、agentmemory には不要です。)サポートされるエンジンのインストール方法はすべて v0.19.7 にピン留めされています: 上記のビルド済み v0.19.7 バイナリ、バージョンピン**付き**の上流 `sh` インストールスクリプト `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.19.7 sh`(macOS/Linux)、および Docker イメージ `iiidev/iii:0.19.7`。単なる `install.sh | sh` は **最新** のエンジンをインストールしますが、agentmemory はそれをサポートしていません — 必ず `VERSION=0.19.7` を渡してください。最も簡単なのは、`npx @agentmemory/agentmemory` を実行するだけです。これがピン留めされたエンジンを `~/.agentmemory/bin` に取得してくれます。 +> 注意: iii **エンジン** はビルド済みバイナリであり、cargo クレートではありません — `cargo install` でインストールしようとしないでください。(iii **SDK** は crates.io、npm、PyPI に公開されていますが、agentmemory には不要です。)サポートされるエンジンのインストール方法はすべて v0.22.1 にピン留めされています: 上記のビルド済み v0.22.1 バイナリ、バージョンピン**付き**の上流 `sh` インストールスクリプト `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.22.1 sh`(macOS/Linux)、および Docker イメージ `iiidev/iii:0.22.1`。単なる `install.sh | sh` は **最新** のエンジンをインストールしますが、agentmemory はそれをサポートしていません — 必ず `VERSION=0.22.1` を渡してください。最も簡単なのは、`npx @agentmemory/agentmemory` を実行するだけです。これがピン留めされたエンジンを `~/.agentmemory/bin` に取得してくれます。 --- @@ -1179,7 +1179,7 @@ iii console --port 3114 \ **Traces は既にオン:** -`iii-config.yaml` は出荷時から `iii-observability` worker を有効化(`exporter: memory`、`sampling_ratio: 1.0`、メトリクス + ログ)。追加設定不要 — agentmemory が起動した瞬間に、すべてのメモリ操作がトレーススパンとコンソールが読み取れる構造化ログを出します。 +`iii-config.yaml` は出荷時から `iii-observability` worker を有効化(`exporter: memory`、`sampling_ratio: 0.1`、メトリクス + ログ)。追加設定不要 — agentmemory が起動した瞬間に、すべてのメモリ操作がコンソールが読み取れる構造化ログを出し、そのうち 10 分の 1(`sampling_ratio: 0.1`)はトレーススパンも出します。 代わりに Jaeger / Honeycomb / Grafana Tempo へエクスポートしたい場合は、`exporter: memory` を `exporter: otlp` に変更し、iii の可観測性ドキュメントに従ってコレクタエンドポイントを設定してください。 @@ -1201,7 +1201,7 @@ iii worker add iii-cron # スケジュール統合、減衰スイー iii worker add iii-queue # 埋め込み + 圧縮ジョブの永続リトライ iii worker add iii-observability # すべてのメモリ操作に OTEL トレース(デフォルト オン) iii worker add iii-sandbox # リコールしたコードを隔離 microVM 内で実行 -iii worker add iii-database # SQL バックエンドのステートアダプタに切り替え +iii worker add database # SQL バックエンドのステートアダプタに切り替え iii worker add mcp # agentmemory MCP の横に汎用 MCP ホストを立てる ``` @@ -1214,7 +1214,7 @@ iii worker add mcp # agentmemory MCP の横に汎用 MCP ホス | [`iii-queue`](https://workers.iii.dev/workers/iii-queue) | 永続リトライ: 失敗した埋め込み + 圧縮ジョブが再起動を生き延び、観測は失われない | | [`iii-observability`](https://workers.iii.dev/workers/iii-observability) | すべての function に OTEL トレース、メトリクス、ログ — 初日から `iii-config.yaml` に配線済み | | [`iii-sandbox`](https://workers.iii.dev/workers/iii-sandbox) | `memory_recall` から出てきたコードはあなたのシェルではなく使い捨て VM 内で実行 | -| [`iii-database`](https://workers.iii.dev/workers/iii-database) | デフォルトのインメモリ KV では足りないときの SQL バックエンドのステートアダプタ | +| [`database`](https://workers.iii.dev/workers/database) | デフォルトのインメモリ KV では足りないときの SQL バックエンドのステートアダプタ | | [`mcp`](https://workers.iii.dev/workers/mcp) | agentmemory の隣に追加の MCP サーバーを立て、同じエンジンを共有 | 完全なレジストリ:[workers.iii.dev](https://workers.iii.dev)。そこにあるすべての worker は agentmemory が使っているのと同じプリミティブで組み立てられています — そして既に手元にある agentmemory もその 1 つです。 diff --git a/READMEs/README.ko-KR.md b/READMEs/README.ko-KR.md index 3c6843ac8a..1c3ae696ae 100644 --- a/READMEs/README.ko-KR.md +++ b/READMEs/README.ko-KR.md @@ -124,7 +124,7 @@ npx는 버전별로 캐싱합니다. `npx -y @agentmemory/agentmemory@latest`로
이미 자체 iii 엔진을 실행 중인 경우 -agentmemory는 iii-engine v0.19.7를 고정하며 다른 버전에는 연결되지 않습니다(워커가 다른 엔진의 프로토콜을 말할 수 없습니다). 다른 엔진을 중지한 후 `npx -y @agentmemory/agentmemory@latest`를 실행하십시오. 고정된 v0.19.7를 `~/.agentmemory/bin`에 설치·실행하며, 기존 `iii`는 건드리지 않습니다. +agentmemory는 iii-engine v0.22.1를 고정하며 다른 버전에는 연결되지 않습니다(워커가 다른 엔진의 프로토콜을 말할 수 없습니다). 다른 엔진을 중지한 후 `npx -y @agentmemory/agentmemory@latest`를 실행하십시오. 고정된 v0.22.1를 `~/.agentmemory/bin`에 설치·실행하며, 기존 `iii`는 건드리지 않습니다.
@@ -463,7 +463,7 @@ npx @agentmemory/agentmemory

빠른 시작

-호환성: 이 릴리스는 `iii-sdk` 0.19.7을 대상으로 하며 iii-engine을 v0.19.7로 고정합니다. +호환성: 이 릴리스는 `iii-sdk` 0.22.1을 대상으로 하며 iii-engine을 v0.22.1로 고정합니다. ### 30초 만에 사용해 보기 @@ -515,7 +515,7 @@ npx @agentmemory/agentmemory import-jsonl ~/.claude/projects/-my-project/abc123. npx @agentmemory/agentmemory upgrade ``` -경고: 이 명령은 현재 workspace/런타임을 변경합니다. JavaScript 의존성을 업데이트할 수 있으며, 고정된 Docker 이미지 `iiidev/iii:0.19.7`를 pull할 수 있습니다. 고정되지 않았거나 더 새로운 iii 엔진을 설치하는 일은 절대 없습니다. +경고: 이 명령은 현재 workspace/런타임을 변경합니다. JavaScript 의존성을 업데이트할 수 있으며, 고정된 Docker 이미지 `iiidev/iii:0.22.1`를 pull할 수 있습니다. 고정되지 않았거나 더 새로운 iii 엔진을 설치하는 일은 절대 없습니다. 구현 세부 사항은 `src/cli.ts`에 있습니다 (`runUpgrade`는 `src/cli.ts:544-595` 부근 참고). @@ -719,15 +719,15 @@ npm install && npm run build && npm start `iii`가 이미 설치되어 있으면 로컬 `iii-engine`으로 agentmemory를 시작하고, Docker가 사용 가능하면 Docker Compose로 폴백합니다. REST, 스트림, 뷰어는 기본적으로 `127.0.0.1`에 바인딩됩니다. -`iii-engine`을 수동으로 설치하십시오. **agentmemory는 현재 `iii-engine`을 `v0.19.7`로 고정합니다**. `iii-sdk` 의존성과 같은 릴리스입니다. 워커는 해당 엔진의 wire 프로토콜을 사용하고 0.20.0에서 SDK 표면이 재구성되었으므로, 둘은 agentmemory 릴리스에서 함께 올라갑니다. 직접 운영하는 엔진이 일치한다고 확신한다면 `AGENTMEMORY_III_VERSION=`으로 재정의하세요. +`iii-engine`을 수동으로 설치하십시오. **agentmemory는 현재 `iii-engine`을 `v0.22.1`로 고정합니다**. `iii-sdk` 의존성과 같은 릴리스입니다. 워커는 해당 엔진의 wire 프로토콜을 사용하고 0.20.0에서 SDK 표면이 재구성되었으므로, 둘은 agentmemory 릴리스에서 함께 올라갑니다. 직접 운영하는 엔진이 일치한다고 확신한다면 `AGENTMEMORY_III_VERSION=`으로 재정의하세요. -- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.19.7/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` +- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.22.1/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` - **macOS x64:** `aarch64-apple-darwin`을 `x86_64-apple-darwin`으로 교체 - **Linux x64:** `x86_64-unknown-linux-gnu`로 교체 - **Linux arm64:** `aarch64-unknown-linux-gnu`로 교체 -- **Windows:** [iii-hq/iii releases v0.19.7](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7)에서 `iii-x86_64-pc-windows-msvc.zip`을 다운로드하고 `iii.exe`를 추출한 후 PATH에 추가 +- **Windows:** [iii-hq/iii releases v0.22.1](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.22.1)에서 `iii-x86_64-pc-windows-msvc.zip`을 다운로드하고 `iii.exe`를 추출한 후 PATH에 추가 -또는 Docker 사용 (번들된 `docker-compose.yml`이 `iiidev/iii:0.19.7`를 pull). 전체 문서: [iii.dev/docs](https://iii.dev/docs). +또는 Docker 사용 (번들된 `docker-compose.yml`이 `iiidev/iii:0.22.1`를 pull). 전체 문서: [iii.dev/docs](https://iii.dev/docs). ### Windows @@ -736,9 +736,9 @@ agentmemory는 Windows 10/11에서 실행되지만, Node.js 패키지만으로 **옵션 A: 사전 빌드된 Windows 바이너리 (권장)** ```powershell -# 1. Open https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7 in your browser +# 1. Open https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.22.1 in your browser # (agentmemory pins the engine to the same release as its iii-sdk; -# v0.19.7 is the current pair) +# v0.22.1 is the current pair) # 2. Download iii-x86_64-pc-windows-msvc.zip # (or iii-aarch64-pc-windows-msvc.zip if you're on an ARM machine) # 3. Extract iii.exe somewhere on PATH, or place it at: @@ -746,7 +746,7 @@ agentmemory는 Windows 10/11에서 실행되지만, Node.js 패키지만으로 # (agentmemory checks that location automatically) # 4. Verify: iii --version -# Should print: 0.19.7 +# Should print: 0.22.1 # 5. Then run agentmemory as usual: npx -y @agentmemory/agentmemory @@ -778,7 +778,7 @@ npx -y @agentmemory/mcp | 포트 충돌 | `netstat -ano \| findstr :3111`로 무엇이 바인딩되어 있는지 확인하고 종료하거나 `--port ` 사용 | | Docker가 설치되어 있어도 Docker 폴백을 건너뜀 | Docker Desktop이 실제로 실행 중인지 확인 (시스템 트레이 아이콘) | -> 참고: iii **엔진**은 사전 빌드된 바이너리이며 cargo 크레이트가 아니므로, `cargo install`로 설치하려 하지 마세요. (iii **SDK**는 crates.io, npm, PyPI에 게시되어 있지만 agentmemory에는 필요하지 않습니다.) 지원되는 엔진 설치 방법은 모두 v0.19.7에 고정되어 있습니다: 위의 사전 빌드된 v0.19.7 바이너리, 버전 핀**을 포함한** 업스트림 `sh` 설치 스크립트 `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.19.7 sh` (macOS/Linux), 그리고 Docker 이미지 `iiidev/iii:0.19.7`. 그냥 `install.sh | sh`를 실행하면 **최신** 엔진이 설치되는데, agentmemory는 이를 지원하지 않습니다; 항상 `VERSION=0.19.7`를 전달하세요. 가장 쉬운 방법은 그냥 `npx @agentmemory/agentmemory`를 실행하는 것입니다. 이 명령이 고정된 엔진을 `~/.agentmemory/bin`에 가져다 줍니다. +> 참고: iii **엔진**은 사전 빌드된 바이너리이며 cargo 크레이트가 아니므로, `cargo install`로 설치하려 하지 마세요. (iii **SDK**는 crates.io, npm, PyPI에 게시되어 있지만 agentmemory에는 필요하지 않습니다.) 지원되는 엔진 설치 방법은 모두 v0.22.1에 고정되어 있습니다: 위의 사전 빌드된 v0.22.1 바이너리, 버전 핀**을 포함한** 업스트림 `sh` 설치 스크립트 `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.22.1 sh` (macOS/Linux), 그리고 Docker 이미지 `iiidev/iii:0.22.1`. 그냥 `install.sh | sh`를 실행하면 **최신** 엔진이 설치되는데, agentmemory는 이를 지원하지 않습니다; 항상 `VERSION=0.22.1`를 전달하세요. 가장 쉬운 방법은 그냥 `npx @agentmemory/agentmemory`를 실행하는 것입니다. 이 명령이 고정된 엔진을 `~/.agentmemory/bin`에 가져다 줍니다. --- @@ -1158,7 +1158,7 @@ iii console --port 3114 \ **Traces는 이미 켜져 있습니다:** -`iii-config.yaml`은 `iii-observability` 워커가 활성화된 상태로 제공됩니다(`exporter: memory`, `sampling_ratio: 1.0`, metrics + logs). 추가 설정이 필요 없습니다. agentmemory가 시작되는 순간 모든 메모리 작업이 콘솔이 읽을 수 있는 trace span과 구조화된 로그를 방출합니다. +`iii-config.yaml`은 `iii-observability` 워커가 활성화된 상태로 제공됩니다(`exporter: memory`, `sampling_ratio: 0.1`, metrics + logs). 추가 설정이 필요 없습니다. agentmemory가 시작되는 순간 모든 메모리 작업이 콘솔이 읽을 수 있는 구조화된 로그를 방출하고, 그중 10분의 1(`sampling_ratio: 0.1`)은 trace span도 방출합니다. 대신 Jaeger/Honeycomb/Grafana Tempo로 내보내고 싶다면 `exporter: memory`를 `exporter: otlp`로 변경하고 iii의 가시성 문서에 따라 collector 엔드포인트를 설정하십시오. @@ -1180,7 +1180,7 @@ iii worker add iii-cron # scheduled consolidation, decay sweeps, snap iii worker add iii-queue # durable retries for embedding + compression jobs iii worker add iii-observability # OTEL traces on every memory op (default on) iii worker add iii-sandbox # run recalled code inside an isolated microVM -iii worker add iii-database # swap in a SQL-backed state adapter +iii worker add database # swap in a SQL-backed state adapter iii worker add mcp # generic MCP host alongside the agentmemory MCP ``` @@ -1193,7 +1193,7 @@ iii worker add mcp # generic MCP host alongside the agentmemory | [`iii-queue`](https://workers.iii.dev/workers/iii-queue) | 내구성 있는 재시도: 실패한 임베딩 + 압축 작업은 재시작에도 살아남아 관측 손실 없음 | | [`iii-observability`](https://workers.iii.dev/workers/iii-observability) | 모든 함수에 OTEL traces, metrics, logs, 첫날부터 `iii-config.yaml`에 연결됨 | | [`iii-sandbox`](https://workers.iii.dev/workers/iii-sandbox) | `memory_recall`에서 나온 코드를 셸이 아니라 일회용 VM 안에서 실행 | -| [`iii-database`](https://workers.iii.dev/workers/iii-database) | 인메모리 KV 기본값을 넘어설 때 SQL 기반 state adapter | +| [`database`](https://workers.iii.dev/workers/database) | 인메모리 KV 기본값을 넘어설 때 SQL 기반 state adapter | | [`mcp`](https://workers.iii.dev/workers/mcp) | agentmemory의 MCP 옆에 추가 MCP 서버를 세우고 동일한 엔진을 공유 | 전체 레지스트리: [workers.iii.dev](https://workers.iii.dev). 그곳의 모든 워커는 agentmemory가 사용하는 동일한 프리미티브로 구성되며, 이미 갖고 있는 agentmemory도 그중 하나입니다. diff --git a/READMEs/README.pt-BR.md b/READMEs/README.pt-BR.md index 30f5d8e2a5..0dc6643d57 100644 --- a/READMEs/README.pt-BR.md +++ b/READMEs/README.pt-BR.md @@ -124,7 +124,7 @@ O npx faz cache por versão. Force a mais recente com `npx -y @agentmemory/agent
Já roda seu próprio engine iii -agentmemory fixa o iii-engine em v0.19.7 e não se conecta a uma versão diferente (o worker não fala o protocolo de outro engine). Pare o outro engine e rode `npx -y @agentmemory/agentmemory@latest`. Ele instala e executa a v0.19.7 fixada em `~/.agentmemory/bin`, deixando o seu próprio `iii` intocado. +agentmemory fixa o iii-engine em v0.22.1 e não se conecta a uma versão diferente (o worker não fala o protocolo de outro engine). Pare o outro engine e rode `npx -y @agentmemory/agentmemory@latest`. Ele instala e executa a v0.22.1 fixada em `~/.agentmemory/bin`, deixando o seu próprio `iii` intocado.
@@ -463,7 +463,7 @@ Nenhum deles faz captura automática a partir de hooks de agentes de codificaç

Início rápido

-Compatibilidade: este release tem como alvo o `iii-sdk` 0.19.7 e fixa o iii-engine em v0.19.7. +Compatibilidade: este release tem como alvo o `iii-sdk` 0.22.1 e fixa o iii-engine em v0.22.1. ### Experimente em 30 segundos @@ -517,7 +517,7 @@ Use o comando de manutenção quando você intencionalmente quiser atualizar seu npx @agentmemory/agentmemory upgrade ``` -Aviso: este comando muta o workspace/runtime atual. Pode atualizar dependências JavaScript e puxar a imagem Docker fixada `iiidev/iii:0.19.7`. Nunca instala um engine iii sem fixação ou mais recente. +Aviso: este comando muta o workspace/runtime atual. Pode atualizar dependências JavaScript e puxar a imagem Docker fixada `iiidev/iii:0.22.1`. Nunca instala um engine iii sem fixação ou mais recente. Detalhes de implementação estão em `src/cli.ts` (veja `runUpgrade` na região `src/cli.ts:544-595`). @@ -721,15 +721,15 @@ npm install && npm run build && npm start Isso inicia o agentmemory com um `iii-engine` local se `iii` já estiver instalado, ou cai para Docker Compose se o Docker estiver disponível. REST, streams e o viewer fazem bind em `127.0.0.1` por padrão. -Instale o `iii-engine` manualmente. **O agentmemory atualmente fixa o `iii-engine` em `v0.19.7`**, o mesmo release da sua dependência `iii-sdk`; o worker fala o protocolo desse engine, e a 0.20.0 reorganizou a superfície do SDK, então os dois avançam juntos a cada release do agentmemory. Sobrescreva com `AGENTMEMORY_III_VERSION=` se você roda seu próprio engine e sabe que ele corresponde. +Instale o `iii-engine` manualmente. **O agentmemory atualmente fixa o `iii-engine` em `v0.22.1`**, o mesmo release da sua dependência `iii-sdk`; o worker fala o protocolo desse engine, e a 0.20.0 reorganizou a superfície do SDK, então os dois avançam juntos a cada release do agentmemory. Sobrescreva com `AGENTMEMORY_III_VERSION=` se você roda seu próprio engine e sabe que ele corresponde. -- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.19.7/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` +- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.22.1/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` - **macOS x64:** troque `aarch64-apple-darwin` por `x86_64-apple-darwin` - **Linux x64:** troque por `x86_64-unknown-linux-gnu` - **Linux arm64:** troque por `aarch64-unknown-linux-gnu` -- **Windows:** baixe `iii-x86_64-pc-windows-msvc.zip` de [iii-hq/iii releases v0.19.7](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7), extraia `iii.exe`, adicione ao PATH +- **Windows:** baixe `iii-x86_64-pc-windows-msvc.zip` de [iii-hq/iii releases v0.22.1](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.22.1), extraia `iii.exe`, adicione ao PATH -Ou use Docker (o `docker-compose.yml` empacotado puxa `iiidev/iii:0.19.7`). Docs completas: [iii.dev/docs](https://iii.dev/docs). +Ou use Docker (o `docker-compose.yml` empacotado puxa `iiidev/iii:0.22.1`). Docs completas: [iii.dev/docs](https://iii.dev/docs). ### Windows @@ -738,9 +738,9 @@ agentmemory roda em Windows 10/11, mas só o pacote Node.js não é suficiente; **Opção A: binário Windows pré-compilado (recomendado)** ```powershell -# 1. Open https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7 in your browser +# 1. Open https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.22.1 in your browser # (agentmemory pins the engine to the same release as its iii-sdk; -# v0.19.7 is the current pair) +# v0.22.1 is the current pair) # 2. Download iii-x86_64-pc-windows-msvc.zip # (or iii-aarch64-pc-windows-msvc.zip if you're on an ARM machine) # 3. Extract iii.exe somewhere on PATH, or place it at: @@ -748,7 +748,7 @@ agentmemory roda em Windows 10/11, mas só o pacote Node.js não é suficiente; # (agentmemory checks that location automatically) # 4. Verify: iii --version -# Should print: 0.19.7 +# Should print: 0.22.1 # 5. Then run agentmemory as usual: npx -y @agentmemory/agentmemory @@ -780,7 +780,7 @@ npx -y @agentmemory/mcp | Conflito de porta | `netstat -ano \| findstr :3111` para ver o que está em bind, mate o processo ou use `--port ` | | Fallback do Docker é pulado mesmo com Docker instalado | Confira se o Docker Desktop está de fato rodando (ícone na bandeja do sistema) | -> Nota: o **engine** iii é um binário pré-compilado, não um crate do cargo, então não tente instalá-lo com `cargo install`. (Os **SDKs** do iii são publicados no crates.io, npm e PyPI, mas o agentmemory não precisa deles.) Métodos de instalação do engine suportados, todos fixados em v0.19.7: o binário pré-compilado v0.19.7 acima, o script de instalação `sh` upstream **com a fixação de versão** `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.19.7 sh` (macOS/Linux) e a imagem Docker `iiidev/iii:0.19.7`. Um simples `install.sh | sh` instala o engine **mais recente**, que o agentmemory não suporta; sempre passe `VERSION=0.19.7`. O mais fácil de tudo: basta rodar `npx @agentmemory/agentmemory`, que busca o engine fixado em `~/.agentmemory/bin` para você. +> Nota: o **engine** iii é um binário pré-compilado, não um crate do cargo, então não tente instalá-lo com `cargo install`. (Os **SDKs** do iii são publicados no crates.io, npm e PyPI, mas o agentmemory não precisa deles.) Métodos de instalação do engine suportados, todos fixados em v0.22.1: o binário pré-compilado v0.22.1 acima, o script de instalação `sh` upstream **com a fixação de versão** `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.22.1 sh` (macOS/Linux) e a imagem Docker `iiidev/iii:0.22.1`. Um simples `install.sh | sh` instala o engine **mais recente**, que o agentmemory não suporta; sempre passe `VERSION=0.22.1`. O mais fácil de tudo: basta rodar `npx @agentmemory/agentmemory`, que busca o engine fixado em `~/.agentmemory/bin` para você. --- @@ -1169,7 +1169,7 @@ iii console --port 3114 \ **Traces já estão ativos:** -`iii-config.yaml` vem com o worker `iii-observability` habilitado (`exporter: memory`, `sampling_ratio: 1.0`, métricas + logs). Sem configuração extra; no momento em que o agentmemory inicia, toda operação de memória emite um trace span e um log estruturado que o console consegue ler. +`iii-config.yaml` vem com o worker `iii-observability` habilitado (`exporter: memory`, `sampling_ratio: 0.1`, métricas + logs). Sem configuração extra; no momento em que o agentmemory inicia, toda operação de memória emite um log estruturado que o console consegue ler, e uma em cada dez (`sampling_ratio: 0.1`) também emite um trace span. Se você quiser exportar para Jaeger/Honeycomb/Grafana Tempo, troque `exporter: memory` por `exporter: otlp` e configure o endpoint do collector conforme a documentação de observabilidade do iii. @@ -1191,7 +1191,7 @@ iii worker add iii-cron # scheduled consolidation, decay sweeps, snap iii worker add iii-queue # durable retries for embedding + compression jobs iii worker add iii-observability # OTEL traces on every memory op (default on) iii worker add iii-sandbox # run recalled code inside an isolated microVM -iii worker add iii-database # swap in a SQL-backed state adapter +iii worker add database # swap in a SQL-backed state adapter iii worker add mcp # generic MCP host alongside the agentmemory MCP ``` @@ -1204,7 +1204,7 @@ Cada `iii worker add` registra novas funções e triggers no mesmo engine onde o | [`iii-queue`](https://workers.iii.dev/workers/iii-queue) | Retries duráveis: jobs falhos de embedding + compressão sobrevivem a restart, sem observações perdidas | | [`iii-observability`](https://workers.iii.dev/workers/iii-observability) | Traces OTEL, métricas, logs em toda função, cabeado em `iii-config.yaml` desde o primeiro dia | | [`iii-sandbox`](https://workers.iii.dev/workers/iii-sandbox) | Código que veio do `memory_recall` roda dentro de uma VM descartável, não no seu shell | -| [`iii-database`](https://workers.iii.dev/workers/iii-database) | Adaptador de estado baseado em SQL quando você ultrapassa o KV in-memory padrão | +| [`database`](https://workers.iii.dev/workers/database) | Adaptador de estado baseado em SQL quando você ultrapassa o KV in-memory padrão | | [`mcp`](https://workers.iii.dev/workers/mcp) | Suba servidores MCP adicionais ao lado do MCP do agentmemory, compartilhando o mesmo engine | Registry completo: [workers.iii.dev](https://workers.iii.dev). Todo worker lá se compõe pelos mesmos primitivos que o agentmemory usa, e o agentmemory que você já tem é um deles. diff --git a/READMEs/README.ru-RU.md b/READMEs/README.ru-RU.md index 1c349f591f..f41b0207b7 100644 --- a/READMEs/README.ru-RU.md +++ b/READMEs/README.ru-RU.md @@ -124,7 +124,7 @@ npx кеширует пакеты по версиям. Принудительн
Уже запущен собственный движок iii -agentmemory закреплён на iii-engine v0.19.7 и не подключится к другой версии (воркер не умеет говорить на протоколе другого движка). Остановите другой движок и запустите `npx -y @agentmemory/agentmemory@latest` — он установит и запустит закреплённый v0.19.7 в `~/.agentmemory/bin`, не трогая ваш собственный `iii`. +agentmemory закреплён на iii-engine v0.22.1 и не подключится к другой версии (воркер не умеет говорить на протоколе другого движка). Остановите другой движок и запустите `npx -y @agentmemory/agentmemory@latest` — он установит и запустит закреплённый v0.22.1 в `~/.agentmemory/bin`, не трогая ваш собственный `iii`.
@@ -463,7 +463,7 @@ npx @agentmemory/agentmemory

Быстрый старт

-Совместимость: этот релиз нацелен на `iii-sdk` 0.19.7 и закрепляет iii-engine v0.19.7. +Совместимость: этот релиз нацелен на `iii-sdk` 0.22.1 и закрепляет iii-engine v0.22.1. ### Попробуйте за 30 секунд @@ -517,7 +517,7 @@ npx @agentmemory/agentmemory import-jsonl ~/.claude/projects/-my-project/abc123. npx @agentmemory/agentmemory upgrade ``` -Внимание: команда меняет текущее рабочее окружение / runtime. Она может обновлять JavaScript-зависимости и стянуть закреплённый Docker-образ `iiidev/iii:0.19.7`. Она никогда не устанавливает незакреплённый или более новый движок iii. +Внимание: команда меняет текущее рабочее окружение / runtime. Она может обновлять JavaScript-зависимости и стянуть закреплённый Docker-образ `iiidev/iii:0.22.1`. Она никогда не устанавливает незакреплённый или более новый движок iii. Детали реализации — в `src/cli.ts` (см. `runUpgrade` в районе `src/cli.ts:544-595`). @@ -721,15 +721,15 @@ npm install && npm run build && npm start Это поднимает agentmemory с локальным `iii-engine`, если `iii` уже установлен, либо откатывается к Docker Compose, если есть Docker. REST, стримы и просмотрщик по умолчанию слушают на `127.0.0.1`. -Установите `iii-engine` вручную. **agentmemory сейчас зафиксирован на `iii-engine` `v0.19.7`** — той же версии, что и его зависимость `iii-sdk`; воркер говорит на wire-протоколе именно этого движка, а 0.20.0 перестроил поверхность SDK, поэтому оба обновляются вместе в релизах agentmemory. Переопределите через `AGENTMEMORY_III_VERSION=`, если запускаете собственный движок и уверены, что версии совпадают. +Установите `iii-engine` вручную. **agentmemory сейчас зафиксирован на `iii-engine` `v0.22.1`** — той же версии, что и его зависимость `iii-sdk`; воркер говорит на wire-протоколе именно этого движка, а 0.20.0 перестроил поверхность SDK, поэтому оба обновляются вместе в релизах agentmemory. Переопределите через `AGENTMEMORY_III_VERSION=`, если запускаете собственный движок и уверены, что версии совпадают. -- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.19.7/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` +- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.22.1/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` - **macOS x64:** замените `aarch64-apple-darwin` на `x86_64-apple-darwin` - **Linux x64:** замените на `x86_64-unknown-linux-gnu` - **Linux arm64:** замените на `aarch64-unknown-linux-gnu` -- **Windows:** скачайте `iii-x86_64-pc-windows-msvc.zip` из [iii-hq/iii releases v0.19.7](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7), распакуйте `iii.exe`, добавьте в PATH +- **Windows:** скачайте `iii-x86_64-pc-windows-msvc.zip` из [iii-hq/iii releases v0.22.1](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.22.1), распакуйте `iii.exe`, добавьте в PATH -Либо используйте Docker (входящий в комплект `docker-compose.yml` тянет `iiidev/iii:0.19.7`). Полная документация: [iii.dev/docs](https://iii.dev/docs). +Либо используйте Docker (входящий в комплект `docker-compose.yml` тянет `iiidev/iii:0.22.1`). Полная документация: [iii.dev/docs](https://iii.dev/docs). ### Windows @@ -738,9 +738,9 @@ agentmemory работает на Windows 10/11, но одного Node.js-па **Вариант A: готовый Windows-бинарь (рекомендуется)** ```powershell -# 1. Open https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7 in your browser +# 1. Open https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.22.1 in your browser # (agentmemory pins the engine to the same release as its iii-sdk; -# v0.19.7 is the current pair) +# v0.22.1 is the current pair) # 2. Download iii-x86_64-pc-windows-msvc.zip # (or iii-aarch64-pc-windows-msvc.zip if you're on an ARM machine) # 3. Extract iii.exe somewhere on PATH, or place it at: @@ -748,7 +748,7 @@ agentmemory работает на Windows 10/11, но одного Node.js-па # (agentmemory checks that location automatically) # 4. Verify: iii --version -# Should print: 0.19.7 +# Should print: 0.22.1 # 5. Then run agentmemory as usual: npx -y @agentmemory/agentmemory @@ -780,7 +780,7 @@ npx -y @agentmemory/mcp | Конфликт порта | `netstat -ano \| findstr :3111`, чтобы понять, что занимает порт, затем убить процесс или использовать `--port ` | | Откат на Docker пропускается, хотя Docker установлен | Убедитесь, что Docker Desktop действительно запущен (иконка в трее) | -> Примечание: **движок** iii — это готовый бинарь, а не cargo-крейт, не пытайтесь установить его через `cargo install`. (**SDK** iii опубликованы на crates.io, npm и PyPI, но agentmemory они не нужны.) Поддерживаемые способы установки движка, все закреплены на v0.19.7: готовый бинарь v0.19.7 выше, upstream-`sh`-скрипт **с закреплением версии** `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.19.7 sh` (macOS/Linux) и Docker-образ `iiidev/iii:0.19.7`. Простой `install.sh | sh` устанавливает **последний** движок, который agentmemory не поддерживает, — всегда передавайте `VERSION=0.19.7`. Самый простой вариант: просто запустите `npx @agentmemory/agentmemory`, который сам загрузит закреплённый движок в `~/.agentmemory/bin`. +> Примечание: **движок** iii — это готовый бинарь, а не cargo-крейт, не пытайтесь установить его через `cargo install`. (**SDK** iii опубликованы на crates.io, npm и PyPI, но agentmemory они не нужны.) Поддерживаемые способы установки движка, все закреплены на v0.22.1: готовый бинарь v0.22.1 выше, upstream-`sh`-скрипт **с закреплением версии** `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.22.1 sh` (macOS/Linux) и Docker-образ `iiidev/iii:0.22.1`. Простой `install.sh | sh` устанавливает **последний** движок, который agentmemory не поддерживает, — всегда передавайте `VERSION=0.22.1`. Самый простой вариант: просто запустите `npx @agentmemory/agentmemory`, который сам загрузит закреплённый движок в `~/.agentmemory/bin`. --- @@ -1176,7 +1176,7 @@ iii console --port 3114 \ **Traces уже включены:** -`iii-config.yaml` поставляется с включённым воркером `iii-observability` (`exporter: memory`, `sampling_ratio: 1.0`, метрики + логи). Дополнительная настройка не нужна — как только agentmemory запускается, каждая операция памяти эмитит trace-span и структурированный лог, который консоль читает. +`iii-config.yaml` поставляется с включённым воркером `iii-observability` (`exporter: memory`, `sampling_ratio: 0.1`, метрики + логи). Дополнительная настройка не нужна — как только agentmemory запускается, каждая операция памяти эмитит структурированный лог, который консоль читает, а каждая десятая (`sampling_ratio: 0.1`) ещё и trace-span. Если хотите экспортировать в Jaeger/Honeycomb/Grafana Tempo, измените `exporter: memory` на `exporter: otlp` и укажите эндпоинт коллектора согласно документации по observability в iii. @@ -1198,7 +1198,7 @@ iii worker add iii-cron # scheduled consolidation, decay sweeps, snap iii worker add iii-queue # durable retries for embedding + compression jobs iii worker add iii-observability # OTEL traces on every memory op (default on) iii worker add iii-sandbox # run recalled code inside an isolated microVM -iii worker add iii-database # swap in a SQL-backed state adapter +iii worker add database # swap in a SQL-backed state adapter iii worker add mcp # generic MCP host alongside the agentmemory MCP ``` @@ -1211,7 +1211,7 @@ iii worker add mcp # generic MCP host alongside the agentmemory | [`iii-queue`](https://workers.iii.dev/workers/iii-queue) | Надёжные повторы: упавшие job'ы эмбеддинга и компрессии переживают перезапуск, наблюдения не теряются | | [`iii-observability`](https://workers.iii.dev/workers/iii-observability) | OTEL-трейсы, метрики, логи на каждой функции — подключены в `iii-config.yaml` с первого дня | | [`iii-sandbox`](https://workers.iii.dev/workers/iii-sandbox) | Код, пришедший из `memory_recall`, исполняется внутри одноразовой VM, а не в вашем shell | -| [`iii-database`](https://workers.iii.dev/workers/iii-database) | SQL-адаптер состояния, когда дефолтная in-memory KV уже мала | +| [`database`](https://workers.iii.dev/workers/database) | SQL-адаптер состояния, когда дефолтная in-memory KV уже мала | | [`mcp`](https://workers.iii.dev/workers/mcp) | Поднять дополнительные MCP-серверы рядом с MCP'ом agentmemory, на одном и том же движке | Полный реестр: [workers.iii.dev](https://workers.iii.dev). Каждый воркер там собирается из тех же примитивов, что и agentmemory — и тот agentmemory, который у вас уже есть, — один из них. diff --git a/READMEs/README.tr-TR.md b/READMEs/README.tr-TR.md index 1c122190db..ae7923d597 100644 --- a/READMEs/README.tr-TR.md +++ b/READMEs/README.tr-TR.md @@ -124,7 +124,7 @@ npx sürüm bazında önbelleğe alır. En güncelini `npx -y @agentmemory/agent
Zaten kendi iii engine'inizi çalıştırıyorsanız -agentmemory iii-engine'i v0.19.7'ye sabitler ve farklı bir sürüme bağlanmaz (worker başka bir engine'in protokolünü konuşamaz). Diğer engine'i durdurun, ardından `npx -y @agentmemory/agentmemory@latest` çalıştırın. Sabitlenmiş v0.19.7'yi `~/.agentmemory/bin` içine kurup çalıştırır ve kendi `iii`'nizi olduğu gibi bırakır. +agentmemory iii-engine'i v0.22.1'ye sabitler ve farklı bir sürüme bağlanmaz (worker başka bir engine'in protokolünü konuşamaz). Diğer engine'i durdurun, ardından `npx -y @agentmemory/agentmemory@latest` çalıştırın. Sabitlenmiş v0.22.1'yi `~/.agentmemory/bin` içine kurup çalıştırır ve kendi `iii`'nizi olduğu gibi bırakır.
@@ -463,7 +463,7 @@ Bunların hiçbiri kodlama-ajanı hook'larından otomatik yakalama yapmaz, yerel

Quick Start

-Uyumluluk: bu sürüm `iii-sdk` 0.19.7'yi hedefler ve iii-engine'i v0.19.7'ye sabitler. +Uyumluluk: bu sürüm `iii-sdk` 0.22.1'yi hedefler ve iii-engine'i v0.22.1'ye sabitler. ### 30 saniyede deneyin @@ -515,7 +515,7 @@ Yerel runtime'ınızı bilinçli olarak güncellemek istediğinizde bakım komut npx @agentmemory/agentmemory upgrade ``` -Uyarı: bu komut mevcut çalışma alanını/runtime'ı değiştirir. JavaScript bağımlılıklarını güncelleyebilir ve sabitlenmiş `iiidev/iii:0.19.7` Docker imajını çekebilir. Asla sabitlenmemiş ya da daha yeni bir iii motoru kurmaz. +Uyarı: bu komut mevcut çalışma alanını/runtime'ı değiştirir. JavaScript bağımlılıklarını güncelleyebilir ve sabitlenmiş `iiidev/iii:0.22.1` Docker imajını çekebilir. Asla sabitlenmemiş ya da daha yeni bir iii motoru kurmaz. Uygulama detayları `src/cli.ts` içinde (`src/cli.ts:544-595` bölgesi civarında `runUpgrade`'a bakın). @@ -719,15 +719,15 @@ npm install && npm run build && npm start Bu, `iii` zaten kuruluysa yerel bir `iii-engine` ile agentmemory'yi başlatır veya Docker mevcutsa Docker Compose'a düşer. REST, stream'ler ve görüntüleyici varsayılan olarak `127.0.0.1`'e bağlanır. -`iii-engine`'i manuel olarak kurun. **agentmemory şu anda `iii-engine`'i `v0.19.7`'ye sabitliyor**; bu, `iii-sdk` bağımlılığıyla aynı sürümdür. Worker tam olarak o engine'in wire protokolünü konuşur ve 0.20.0 SDK yüzeyini yeniden düzenlediği için ikisi agentmemory sürümlerinde birlikte yükseltilir. Kendi engine'inizi çalıştırıyor ve eşleştiğinden eminseniz `AGENTMEMORY_III_VERSION=` ile geçersiz kılın. +`iii-engine`'i manuel olarak kurun. **agentmemory şu anda `iii-engine`'i `v0.22.1`'ye sabitliyor**; bu, `iii-sdk` bağımlılığıyla aynı sürümdür. Worker tam olarak o engine'in wire protokolünü konuşur ve 0.20.0 SDK yüzeyini yeniden düzenlediği için ikisi agentmemory sürümlerinde birlikte yükseltilir. Kendi engine'inizi çalıştırıyor ve eşleştiğinden eminseniz `AGENTMEMORY_III_VERSION=` ile geçersiz kılın. -- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.19.7/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` +- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.22.1/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` - **macOS x64:** `aarch64-apple-darwin`'i `x86_64-apple-darwin` ile değiştirin - **Linux x64:** `x86_64-unknown-linux-gnu` ile değiştirin - **Linux arm64:** `aarch64-unknown-linux-gnu` ile değiştirin -- **Windows:** [iii-hq/iii releases v0.19.7](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7)'den `iii-x86_64-pc-windows-msvc.zip`'i indirin, `iii.exe`'yi çıkarın, PATH'e ekleyin +- **Windows:** [iii-hq/iii releases v0.22.1](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.22.1)'den `iii-x86_64-pc-windows-msvc.zip`'i indirin, `iii.exe`'yi çıkarın, PATH'e ekleyin -Veya Docker kullanın (paketli `docker-compose.yml` `iiidev/iii:0.19.7`'yi çeker). Tam dokümanlar: [iii.dev/docs](https://iii.dev/docs). +Veya Docker kullanın (paketli `docker-compose.yml` `iiidev/iii:0.22.1`'yi çeker). Tam dokümanlar: [iii.dev/docs](https://iii.dev/docs). ### Windows @@ -736,9 +736,9 @@ agentmemory Windows 10/11'de çalışır, ancak yalnızca Node.js paketi yeterli **Seçenek A: önceden derlenmiş Windows ikiliği (önerilen)** ```powershell -# 1. Tarayıcınızda https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7 açın +# 1. Tarayıcınızda https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.22.1 açın # (agentmemory, engine'i iii-sdk ile aynı sürüme sabitler; -# mevcut çift v0.19.7) +# mevcut çift v0.22.1) # 2. iii-x86_64-pc-windows-msvc.zip indirin # (veya ARM makinedeyseniz iii-aarch64-pc-windows-msvc.zip) # 3. iii.exe'yi PATH'te bir yere çıkarın veya şuraya yerleştirin: @@ -746,7 +746,7 @@ agentmemory Windows 10/11'de çalışır, ancak yalnızca Node.js paketi yeterli # (agentmemory bu konumu otomatik kontrol eder) # 4. Doğrulayın: iii --version -# Şunu yazmalı: 0.19.7 +# Şunu yazmalı: 0.22.1 # 5. Ardından agentmemory'yi her zamanki gibi çalıştırın: npx -y @agentmemory/agentmemory @@ -778,7 +778,7 @@ npx -y @agentmemory/mcp | Port çakışması | `netstat -ano \| findstr :3111` ile neyin bağlı olduğunu görün, ardından öldürün veya `--port ` kullanın | | Docker kurulu olsa bile Docker fallback atlanıyor | Docker Desktop'ın gerçekten çalıştığından emin olun (sistem tepsisi simgesi) | -> Not: iii **motoru** önceden derlenmiş bir ikiliktir, bir cargo crate'i değildir, bu yüzden onu `cargo install` ile kurmaya çalışmayın. (iii **SDK'ları** crates.io, npm ve PyPI'de yayımlanmıştır, ancak agentmemory bunlara ihtiyaç duymaz.) Desteklenen motor kurulum yöntemleri, hepsi v0.19.7'ye sabitlenmiştir: yukarıdaki önceden derlenmiş v0.19.7 ikiliği, sürüm sabitlemesi **ile** upstream `sh` kurulum scripti `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.19.7 sh` (macOS/Linux) ve Docker imajı `iiidev/iii:0.19.7`. Yalın bir `install.sh | sh`, agentmemory'nin desteklemediği **en son** motoru kurar; her zaman `VERSION=0.19.7` geçirin. Hepsinden kolayı: sadece `npx @agentmemory/agentmemory` çalıştırın; bu, sabitlenmiş motoru sizin için `~/.agentmemory/bin` dizinine indirir. +> Not: iii **motoru** önceden derlenmiş bir ikiliktir, bir cargo crate'i değildir, bu yüzden onu `cargo install` ile kurmaya çalışmayın. (iii **SDK'ları** crates.io, npm ve PyPI'de yayımlanmıştır, ancak agentmemory bunlara ihtiyaç duymaz.) Desteklenen motor kurulum yöntemleri, hepsi v0.22.1'ye sabitlenmiştir: yukarıdaki önceden derlenmiş v0.22.1 ikiliği, sürüm sabitlemesi **ile** upstream `sh` kurulum scripti `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.22.1 sh` (macOS/Linux) ve Docker imajı `iiidev/iii:0.22.1`. Yalın bir `install.sh | sh`, agentmemory'nin desteklemediği **en son** motoru kurar; her zaman `VERSION=0.22.1` geçirin. Hepsinden kolayı: sadece `npx @agentmemory/agentmemory` çalıştırın; bu, sabitlenmiş motoru sizin için `~/.agentmemory/bin` dizinine indirir. --- @@ -1178,7 +1178,7 @@ iii console --port 3114 \ **Trace'ler zaten açık:** -`iii-config.yaml` `iii-observability` worker'ı etkinleştirilmiş olarak gelir (`exporter: memory`, `sampling_ratio: 1.0`, metrikler + log'lar). Ekstra yapılandırma gerekmez; agentmemory başlar başlamaz, her bellek işlemi konsolun okuyabileceği bir trace span'ı ve yapılandırılmış bir log yayar. +`iii-config.yaml` `iii-observability` worker'ı etkinleştirilmiş olarak gelir (`exporter: memory`, `sampling_ratio: 0.1`, metrikler + log'lar). Ekstra yapılandırma gerekmez; agentmemory başlar başlamaz, her bellek işlemi konsolun okuyabileceği yapılandırılmış bir log yayar ve her on işlemden biri (`sampling_ratio: 0.1`) ayrıca bir trace span'ı yayar. Bunun yerine Jaeger/Honeycomb/Grafana Tempo'ya dışa aktarmak isterseniz, `exporter: memory`'yi `exporter: otlp` olarak değiştirin ve collector endpoint'ini iii'nin observability dokümanlarına göre ayarlayın. @@ -1200,7 +1200,7 @@ iii worker add iii-cron # zamanlanmış konsolidasyon, decay süpürm iii worker add iii-queue # embedding + sıkıştırma işleri için dayanıklı yeniden denemeler iii worker add iii-observability # her bellek op'unda OTEL trace'leri (varsayılan açık) iii worker add iii-sandbox # hatırlanan kodu izole bir microVM içinde çalıştır -iii worker add iii-database # SQL destekli bir state adaptörü tak +iii worker add database # SQL destekli bir state adaptörü tak iii worker add mcp # agentmemory MCP'sinin yanında genel MCP host'u ``` @@ -1213,7 +1213,7 @@ Her `iii worker add` agentmemory'nin zaten çalıştığı aynı engine'e yeni f | [`iii-queue`](https://workers.iii.dev/workers/iii-queue) | Dayanıklı yeniden denemeler: başarısız embedding + sıkıştırma işleri yeniden başlatmaya dayanır, kayıp gözlem yok | | [`iii-observability`](https://workers.iii.dev/workers/iii-observability) | OTEL trace'leri, metrikleri, log'ları her fonksiyonda, birinci günden itibaren `iii-config.yaml`'da bağlı | | [`iii-sandbox`](https://workers.iii.dev/workers/iii-sandbox) | `memory_recall`'dan çıkan kod, shell'inizde değil, bir kullan-at VM içinde çalışır | -| [`iii-database`](https://workers.iii.dev/workers/iii-database) | In-memory KV varsayılanlarını aştığınızda SQL destekli state adaptörü | +| [`database`](https://workers.iii.dev/workers/database) | In-memory KV varsayılanlarını aştığınızda SQL destekli state adaptörü | | [`mcp`](https://workers.iii.dev/workers/mcp) | agentmemory'ninin yanında ekstra MCP sunucuları ayağa kaldırın, aynı engine'i paylaşın | Tam kayıt defteri: [workers.iii.dev](https://workers.iii.dev). Oradaki her worker, agentmemory'nin kullandığı aynı primitifler aracılığıyla bir araya gelir ve elinizdeki agentmemory de onlardan biridir. diff --git a/READMEs/README.zh-CN.md b/READMEs/README.zh-CN.md index 1030e02d42..7f7c8a03f2 100644 --- a/READMEs/README.zh-CN.md +++ b/READMEs/README.zh-CN.md @@ -124,7 +124,7 @@ npx 会按版本缓存。用 `npx -y @agentmemory/agentmemory@latest` 强制拉
已在运行自己的 iii 引擎 -agentmemory 固定 iii-engine v0.19.7,不会挂接到其他版本(worker 无法使用其他引擎的协议)。停止另一个引擎,然后运行 `npx -y @agentmemory/agentmemory@latest`。它会在 `~/.agentmemory/bin` 安装并运行固定的 v0.19.7,不动你自己的 `iii`。 +agentmemory 固定 iii-engine v0.22.1,不会挂接到其他版本(worker 无法使用其他引擎的协议)。停止另一个引擎,然后运行 `npx -y @agentmemory/agentmemory@latest`。它会在 `~/.agentmemory/bin` 安装并运行固定的 v0.22.1,不动你自己的 `iii`。
@@ -463,7 +463,7 @@ npx @agentmemory/agentmemory

Quick Start

-兼容性:此版本面向 `iii-sdk` 0.19.7,并将 iii-engine 固定在 v0.19.7。 +兼容性:此版本面向 `iii-sdk` 0.22.1,并将 iii-engine 固定在 v0.22.1。 ### 30 秒体验 @@ -515,7 +515,7 @@ npx @agentmemory/agentmemory import-jsonl ~/.claude/projects/-my-project/abc123. npx @agentmemory/agentmemory upgrade ``` -警告:此命令会变更当前工作空间/运行时。它可能更新 JavaScript 依赖,并拉取固定版本的 Docker 镜像 `iiidev/iii:0.19.7`。它绝不会安装未固定版本或更新的 iii 引擎。 +警告:此命令会变更当前工作空间/运行时。它可能更新 JavaScript 依赖,并拉取固定版本的 Docker 镜像 `iiidev/iii:0.22.1`。它绝不会安装未固定版本或更新的 iii 引擎。 实现细节见 `src/cli.ts`(参考 `src/cli.ts:544-595` 附近的 `runUpgrade`)。 @@ -720,15 +720,15 @@ npm install && npm run build && npm start 如果已经安装 `iii`,这会以本地 `iii-engine` 启动 agentmemory;如果 Docker 可用,则回退到 Docker Compose。REST、流和查看器默认绑定到 `127.0.0.1`。 -手动安装 `iii-engine`。**agentmemory 当前将 `iii-engine` 固定在 `v0.19.7`**,与其 `iii-sdk` 依赖是同一个版本;worker 使用的是该引擎的 wire 协议,而 0.20.0 重组了 SDK 接口,因此两者在 agentmemory 的每个版本中一起升级。如果你运行自己的引擎并确定版本匹配,可用 `AGENTMEMORY_III_VERSION=` 覆盖。 +手动安装 `iii-engine`。**agentmemory 当前将 `iii-engine` 固定在 `v0.22.1`**,与其 `iii-sdk` 依赖是同一个版本;worker 使用的是该引擎的 wire 协议,而 0.20.0 重组了 SDK 接口,因此两者在 agentmemory 的每个版本中一起升级。如果你运行自己的引擎并确定版本匹配,可用 `AGENTMEMORY_III_VERSION=` 覆盖。 -- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.19.7/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` +- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.22.1/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` - **macOS x64:** 把 `aarch64-apple-darwin` 换成 `x86_64-apple-darwin` - **Linux x64:** 换成 `x86_64-unknown-linux-gnu` - **Linux arm64:** 换成 `aarch64-unknown-linux-gnu` -- **Windows:** 从 [iii-hq/iii releases v0.19.7](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7) 下载 `iii-x86_64-pc-windows-msvc.zip`,提取 `iii.exe`,加入 PATH +- **Windows:** 从 [iii-hq/iii releases v0.22.1](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.22.1) 下载 `iii-x86_64-pc-windows-msvc.zip`,提取 `iii.exe`,加入 PATH -或使用 Docker(捆绑的 `docker-compose.yml` 会拉取 `iiidev/iii:0.19.7`)。完整文档:[iii.dev/docs](https://iii.dev/docs)。 +或使用 Docker(捆绑的 `docker-compose.yml` 会拉取 `iiidev/iii:0.22.1`)。完整文档:[iii.dev/docs](https://iii.dev/docs)。 ### Windows @@ -737,9 +737,9 @@ agentmemory 可在 Windows 10/11 运行,但仅 Node.js 包不够;你还需要 `i **选项 A:预构建 Windows 二进制(推荐)** ```powershell -# 1. 在浏览器打开 https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7 +# 1. 在浏览器打开 https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.22.1 # (agentmemory 将引擎固定在与其 iii-sdk 相同的版本; -# 当前配对为 v0.19.7) +# 当前配对为 v0.22.1) # 2. 下载 iii-x86_64-pc-windows-msvc.zip # (如果是 ARM 机器则下载 iii-aarch64-pc-windows-msvc.zip) # 3. 把 iii.exe 解压到 PATH 上的某处,或放在: @@ -747,7 +747,7 @@ agentmemory 可在 Windows 10/11 运行,但仅 Node.js 包不够;你还需要 `i # (agentmemory 会自动检查该位置) # 4. 验证: iii --version -# 应输出:0.19.7 +# 应输出:0.22.1 # 5. 然后照常运行 agentmemory: npx -y @agentmemory/agentmemory @@ -779,7 +779,7 @@ npx -y @agentmemory/mcp | 端口冲突 | `netstat -ano \| findstr :3111` 查看占用,然后 kill 或用 `--port ` | | Docker 已安装但仍跳过回退 | 确保 Docker Desktop 确实在运行(系统托盘图标) | -> 注意:iii **引擎** 是预构建的二进制文件,而非 cargo crate,所以不要尝试用 `cargo install` 安装它。(iii 的 **SDK** 确实已发布到 crates.io、npm 和 PyPI,但 agentmemory 并不需要它们。)受支持的引擎安装方式均固定为 v0.19.7:上面的预构建 v0.19.7 二进制、**带版本固定** 的上游 `sh` 安装脚本 `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.19.7 sh`(macOS/Linux),以及 Docker 镜像 `iiidev/iii:0.19.7`。直接运行 `install.sh | sh` 会安装 **最新** 引擎,而 agentmemory 不支持该版本;请务必传入 `VERSION=0.19.7`。最简单的方式:直接运行 `npx @agentmemory/agentmemory`,它会为你把固定版本的引擎获取到 `~/.agentmemory/bin`。 +> 注意:iii **引擎** 是预构建的二进制文件,而非 cargo crate,所以不要尝试用 `cargo install` 安装它。(iii 的 **SDK** 确实已发布到 crates.io、npm 和 PyPI,但 agentmemory 并不需要它们。)受支持的引擎安装方式均固定为 v0.22.1:上面的预构建 v0.22.1 二进制、**带版本固定** 的上游 `sh` 安装脚本 `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.22.1 sh`(macOS/Linux),以及 Docker 镜像 `iiidev/iii:0.22.1`。直接运行 `install.sh | sh` 会安装 **最新** 引擎,而 agentmemory 不支持该版本;请务必传入 `VERSION=0.22.1`。最简单的方式:直接运行 `npx @agentmemory/agentmemory`,它会为你把固定版本的引擎获取到 `~/.agentmemory/bin`。 --- @@ -1175,7 +1175,7 @@ iii console --port 3114 \ **Traces 已开启:** -`iii-config.yaml` 出厂启用 `iii-observability` worker(`exporter: memory`、`sampling_ratio: 1.0`、指标 + 日志)。无需额外配置;agentmemory 启动那一刻,每个记忆操作都会发出一个 trace span 和一个控制台可读的结构化日志。 +`iii-config.yaml` 出厂启用 `iii-observability` worker(`exporter: memory`、`sampling_ratio: 0.1`、指标 + 日志)。无需额外配置;agentmemory 启动那一刻,每个记忆操作都会发出一个控制台可读的结构化日志,其中十分之一(`sampling_ratio: 0.1`)还会发出一个 trace span。 如果你想改为导出到 Jaeger/Honeycomb/Grafana Tempo,把 `exporter: memory` 改为 `exporter: otlp` 并按 iii 的可观测性文档设置收集器端点。 @@ -1197,7 +1197,7 @@ iii worker add iii-cron # 定时整合、衰减扫描、快照轮换 iii worker add iii-queue # 嵌入 + 压缩任务的持久重试 iii worker add iii-observability # 每个记忆操作的 OTEL traces(默认开启) iii worker add iii-sandbox # 在隔离 microVM 内运行召回到的代码 -iii worker add iii-database # 切换 SQL 后端的状态适配器 +iii worker add database # 切换 SQL 后端的状态适配器 iii worker add mcp # 在 agentmemory 的 MCP 旁开通用 MCP 宿主 ``` @@ -1210,7 +1210,7 @@ iii worker add mcp # 在 agentmemory 的 MCP 旁开通用 MCP | [`iii-queue`](https://workers.iii.dev/workers/iii-queue) | 持久重试:失败的嵌入 + 压缩任务在重启后存活,无观测丢失 | | [`iii-observability`](https://workers.iii.dev/workers/iii-observability) | 每个函数的 OTEL traces、指标、日志,从第一天起就接入 `iii-config.yaml` | | [`iii-sandbox`](https://workers.iii.dev/workers/iii-sandbox) | `memory_recall` 出来的代码在一次性 VM 中运行,不在你的 shell 中 | -| [`iii-database`](https://workers.iii.dev/workers/iii-database) | 当默认的内存 KV 不够用时,SQL 后端状态适配器 | +| [`database`](https://workers.iii.dev/workers/database) | 当默认的内存 KV 不够用时,SQL 后端状态适配器 | | [`mcp`](https://workers.iii.dev/workers/mcp) | 在 agentmemory 的旁边架设额外 MCP 服务器,共享同一引擎 | 完整注册表:[workers.iii.dev](https://workers.iii.dev)。那里的每个 worker 都通过 agentmemory 所用的同样原语组合,而你已经拥有的 agentmemory 本身就是其中之一。 diff --git a/READMEs/README.zh-TW.md b/READMEs/README.zh-TW.md index 80ea3af89f..bf7362d354 100644 --- a/READMEs/README.zh-TW.md +++ b/READMEs/README.zh-TW.md @@ -124,7 +124,7 @@ npx 會依版本快取。用 `npx -y @agentmemory/agentmemory@latest` 強制使
已在執行你自己的 iii 引擎 -agentmemory 把 iii-engine 釘在 v0.19.7,不會附掛到其他版本(worker 無法使用另一個引擎的協定)。停止另一個引擎,然後執行 `npx -y @agentmemory/agentmemory@latest`。它會在 `~/.agentmemory/bin` 安裝並執行釘住的 v0.19.7,不動你自己的 `iii`。 +agentmemory 把 iii-engine 釘在 v0.22.1,不會附掛到其他版本(worker 無法使用另一個引擎的協定)。停止另一個引擎,然後執行 `npx -y @agentmemory/agentmemory@latest`。它會在 `~/.agentmemory/bin` 安裝並執行釘住的 v0.22.1,不動你自己的 `iii`。
@@ -463,7 +463,7 @@ npx @agentmemory/agentmemory

Quick Start

-相容性:此版本面向 `iii-sdk` 0.19.7,並將 iii-engine 釘在 v0.19.7。 +相容性:此版本面向 `iii-sdk` 0.22.1,並將 iii-engine 釘在 v0.22.1。 ### 30 秒體驗 @@ -515,7 +515,7 @@ npx @agentmemory/agentmemory import-jsonl ~/.claude/projects/-my-project/abc123. npx @agentmemory/agentmemory upgrade ``` -警告:此指令會變更目前工作區/執行階段。它可能更新 JavaScript 相依,並拉取固定版本的 Docker 鏡像 `iiidev/iii:0.19.7`。它絕不會安裝未固定版本或更新的 iii 引擎。 +警告:此指令會變更目前工作區/執行階段。它可能更新 JavaScript 相依,並拉取固定版本的 Docker 鏡像 `iiidev/iii:0.22.1`。它絕不會安裝未固定版本或更新的 iii 引擎。 實作細節見 `src/cli.ts`(參考 `src/cli.ts:544-595` 附近的 `runUpgrade`)。 @@ -720,15 +720,15 @@ npm install && npm run build && npm start 若 `iii` 已安裝,這會以本地 `iii-engine` 啟動 agentmemory;若 Docker 可用,則回退到 Docker Compose。REST、串流和檢視器預設繫結到 `127.0.0.1`。 -手動安裝 `iii-engine`。**agentmemory 目前把 `iii-engine` 釘在 `v0.19.7`**,與其 `iii-sdk` 相依是同一個版本;worker 使用該引擎的 wire 協定,而 0.20.0 重組了 SDK 介面,因此兩者在 agentmemory 的每個版本中一起升級。若你執行自己的引擎並確定版本相符,可用 `AGENTMEMORY_III_VERSION=` 覆寫。 +手動安裝 `iii-engine`。**agentmemory 目前把 `iii-engine` 釘在 `v0.22.1`**,與其 `iii-sdk` 相依是同一個版本;worker 使用該引擎的 wire 協定,而 0.20.0 重組了 SDK 介面,因此兩者在 agentmemory 的每個版本中一起升級。若你執行自己的引擎並確定版本相符,可用 `AGENTMEMORY_III_VERSION=` 覆寫。 -- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.19.7/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` +- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.22.1/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` - **macOS x64:** 把 `aarch64-apple-darwin` 換成 `x86_64-apple-darwin` - **Linux x64:** 換成 `x86_64-unknown-linux-gnu` - **Linux arm64:** 換成 `aarch64-unknown-linux-gnu` -- **Windows:** 從 [iii-hq/iii releases v0.19.7](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7) 下載 `iii-x86_64-pc-windows-msvc.zip`,擷取 `iii.exe`,加入 PATH +- **Windows:** 從 [iii-hq/iii releases v0.22.1](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.22.1) 下載 `iii-x86_64-pc-windows-msvc.zip`,擷取 `iii.exe`,加入 PATH -或使用 Docker(捆綁的 `docker-compose.yml` 會拉取 `iiidev/iii:0.19.7`)。完整文件:[iii.dev/docs](https://iii.dev/docs)。 +或使用 Docker(捆綁的 `docker-compose.yml` 會拉取 `iiidev/iii:0.22.1`)。完整文件:[iii.dev/docs](https://iii.dev/docs)。 ### Windows @@ -737,9 +737,9 @@ agentmemory 可在 Windows 10/11 執行,但僅 Node.js 套件不夠;你還需要 **選項 A:預建 Windows 二進位(推薦)** ```powershell -# 1. 在瀏覽器打開 https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.19.7 +# 1. 在瀏覽器打開 https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.22.1 # (agentmemory 將引擎釘在與其 iii-sdk 相同的版本; -# 目前配對為 v0.19.7) +# 目前配對為 v0.22.1) # 2. 下載 iii-x86_64-pc-windows-msvc.zip # (若是 ARM 機器則下載 iii-aarch64-pc-windows-msvc.zip) # 3. 把 iii.exe 解壓到 PATH 上的某處,或放在: @@ -747,7 +747,7 @@ agentmemory 可在 Windows 10/11 執行,但僅 Node.js 套件不夠;你還需要 # (agentmemory 會自動檢查該位置) # 4. 驗證: iii --version -# 應輸出:0.19.7 +# 應輸出:0.22.1 # 5. 然後照常執行 agentmemory: npx -y @agentmemory/agentmemory @@ -779,7 +779,7 @@ npx -y @agentmemory/mcp | 連接埠衝突 | `netstat -ano \| findstr :3111` 查看佔用,然後 kill 或用 `--port ` | | Docker 已安裝但仍跳過回退 | 確保 Docker Desktop 確實在執行(系統匣圖示) | -> 注意:iii **引擎** 是預建的二進位檔,而非 cargo crate,請勿嘗試以 `cargo install` 安裝它。(iii 的 **SDK** 確實已發布到 crates.io、npm 和 PyPI,但 agentmemory 並不需要它們。)受支援的引擎安裝方式皆固定為 v0.19.7:上述預建的 v0.19.7 二進位、**帶版本固定** 的上游 `sh` 安裝指令稿 `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.19.7 sh`(macOS/Linux),以及 Docker 鏡像 `iiidev/iii:0.19.7`。直接執行 `install.sh | sh` 會安裝 **最新** 引擎,而 agentmemory 並不支援該版本;請務必傳入 `VERSION=0.19.7`。最簡單的方式:直接執行 `npx @agentmemory/agentmemory`,它會為你把固定版本的引擎取得到 `~/.agentmemory/bin`。 +> 注意:iii **引擎** 是預建的二進位檔,而非 cargo crate,請勿嘗試以 `cargo install` 安裝它。(iii 的 **SDK** 確實已發布到 crates.io、npm 和 PyPI,但 agentmemory 並不需要它們。)受支援的引擎安裝方式皆固定為 v0.22.1:上述預建的 v0.22.1 二進位、**帶版本固定** 的上游 `sh` 安裝指令稿 `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.22.1 sh`(macOS/Linux),以及 Docker 鏡像 `iiidev/iii:0.22.1`。直接執行 `install.sh | sh` 會安裝 **最新** 引擎,而 agentmemory 並不支援該版本;請務必傳入 `VERSION=0.22.1`。最簡單的方式:直接執行 `npx @agentmemory/agentmemory`,它會為你把固定版本的引擎取得到 `~/.agentmemory/bin`。 --- @@ -1175,7 +1175,7 @@ iii console --port 3114 \ **Traces 已開啟:** -`iii-config.yaml` 出廠啟用 `iii-observability` worker(`exporter: memory`、`sampling_ratio: 1.0`、指標 + 日誌)。無需額外設定;agentmemory 啟動那一刻,每個記憶操作都會發出一個 trace span 和一個主控台可讀的結構化日誌。 +`iii-config.yaml` 出廠啟用 `iii-observability` worker(`exporter: memory`、`sampling_ratio: 0.1`、指標 + 日誌)。無需額外設定;agentmemory 啟動那一刻,每個記憶操作都會發出一個主控台可讀的結構化日誌,其中十分之一(`sampling_ratio: 0.1`)還會發出一個 trace span。 若你想改為匯出到 Jaeger/Honeycomb/Grafana Tempo,把 `exporter: memory` 改為 `exporter: otlp` 並依 iii 的可觀測性文件設定收集器端點。 @@ -1197,7 +1197,7 @@ iii worker add iii-cron # 排程整合、衰減掃描、快照輪替 iii worker add iii-queue # 嵌入 + 壓縮工作的持久重試 iii worker add iii-observability # 每個記憶操作的 OTEL traces(預設開啟) iii worker add iii-sandbox # 在隔離 microVM 內執行召回到的程式碼 -iii worker add iii-database # 切換 SQL 後端的狀態適配器 +iii worker add database # 切換 SQL 後端的狀態適配器 iii worker add mcp # 在 agentmemory 的 MCP 旁開設通用 MCP 宿主 ``` @@ -1210,7 +1210,7 @@ iii worker add mcp # 在 agentmemory 的 MCP 旁開設通用 MCP | [`iii-queue`](https://workers.iii.dev/workers/iii-queue) | 持久重試:失敗的嵌入 + 壓縮工作在重啟後存活,無觀測遺失 | | [`iii-observability`](https://workers.iii.dev/workers/iii-observability) | 每個函式的 OTEL traces、指標、日誌,從第一天起就接入 `iii-config.yaml` | | [`iii-sandbox`](https://workers.iii.dev/workers/iii-sandbox) | `memory_recall` 出來的程式碼在一次性 VM 中執行,不在你的 shell 中 | -| [`iii-database`](https://workers.iii.dev/workers/iii-database) | 當預設的記憶體 KV 不夠用時,SQL 後端狀態適配器 | +| [`database`](https://workers.iii.dev/workers/database) | 當預設的記憶體 KV 不夠用時,SQL 後端狀態適配器 | | [`mcp`](https://workers.iii.dev/workers/mcp) | 在 agentmemory 的旁邊架設額外 MCP 伺服器,共享同一引擎 | 完整登錄表:[workers.iii.dev](https://workers.iii.dev)。那裡的每個 worker 都透過 agentmemory 所用的同樣原語組合,而你已經擁有的 agentmemory 本身就是其中之一。 diff --git a/deploy/coolify/entrypoint.sh b/deploy/coolify/entrypoint.sh index ffdd633395..c21ec1d898 100755 --- a/deploy/coolify/entrypoint.sh +++ b/deploy/coolify/entrypoint.sh @@ -70,10 +70,10 @@ workers: enabled: true service_name: agentmemory exporter: memory - sampling_ratio: 1.0 + sampling_ratio: 0.1 metrics_enabled: true logs_enabled: true - logs_console_output: true + logs_console_output: false EOF chown "$RUN_AS" "$III_CONFIG" diff --git a/deploy/fly/entrypoint.sh b/deploy/fly/entrypoint.sh index 5fd4cc2681..5b20f45113 100755 --- a/deploy/fly/entrypoint.sh +++ b/deploy/fly/entrypoint.sh @@ -70,10 +70,10 @@ workers: enabled: true service_name: agentmemory exporter: memory - sampling_ratio: 1.0 + sampling_ratio: 0.1 metrics_enabled: true logs_enabled: true - logs_console_output: true + logs_console_output: false EOF chown "$RUN_AS" "$III_CONFIG" diff --git a/deploy/railway/entrypoint.sh b/deploy/railway/entrypoint.sh index ffdd633395..c21ec1d898 100755 --- a/deploy/railway/entrypoint.sh +++ b/deploy/railway/entrypoint.sh @@ -70,10 +70,10 @@ workers: enabled: true service_name: agentmemory exporter: memory - sampling_ratio: 1.0 + sampling_ratio: 0.1 metrics_enabled: true logs_enabled: true - logs_console_output: true + logs_console_output: false EOF chown "$RUN_AS" "$III_CONFIG" diff --git a/deploy/render/entrypoint.sh b/deploy/render/entrypoint.sh index ffdd633395..c21ec1d898 100755 --- a/deploy/render/entrypoint.sh +++ b/deploy/render/entrypoint.sh @@ -70,10 +70,10 @@ workers: enabled: true service_name: agentmemory exporter: memory - sampling_ratio: 1.0 + sampling_ratio: 0.1 metrics_enabled: true logs_enabled: true - logs_console_output: true + logs_console_output: false EOF chown "$RUN_AS" "$III_CONFIG" diff --git a/docker-compose.yml b/docker-compose.yml index 7eb37ae25a..8b195e4c67 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -21,17 +21,19 @@ services: # Pinned to the same release as agentmemory's iii-sdk dependency # (package.json). The worker speaks this engine's wire protocol, so # bump the image tag and the SDK together, never one of them alone. - # v0.19.7 is the last engine before the 0.20 SDK reorganization and - # keeps HTTP routes owned by the reconnecting worker. + # 0.22.x is the last line before 0.23 removes the config.yaml worker + # lifecycle; it keeps HTTP routes owned by the reconnecting worker. # # Override per-shell or via .env file: - # AGENTMEMORY_III_VERSION=0.19.7 docker compose up - image: iiidev/iii:${AGENTMEMORY_III_VERSION:-0.19.7} + # AGENTMEMORY_III_VERSION=0.22.1 docker compose up + image: iiidev/iii:${AGENTMEMORY_III_VERSION:-0.22.1} user: "${AGENTMEMORY_DOCKER_UID:-65532}:${AGENTMEMORY_DOCKER_GID:-65532}" depends_on: iii-init: condition: service_completed_successfully + command: ["--config", "/app/config.yaml", "--no-update-check"] environment: + III_TELEMETRY_ENABLED: "${III_TELEMETRY_ENABLED:-false}" III_REST_PORT: "${III_REST_PORT:-3111}" III_STREAM_PORT: "${III_STREAM_PORT:-3112}" III_VIEWER_PORT: "${III_VIEWER_PORT:-3113}" @@ -45,13 +47,12 @@ services: - "${AGENTMEMORY_DATA_DIR:-iii-data}:/data" - ./iii-config.docker.yaml:/app/config.yaml:ro # The engine persists each builtin worker's seeded config block under - # data/configuration of its working directory (/home/nonroot in the - # image) on first boot and treats that copy as the source of truth - # afterwards. Keeping it on a tmpfs means every - # container start re-seeds from config.yaml and the III_* env vars, - # the same behavior the native CLI path has. + # config/ next to its config file (/app/config in the image) on first + # boot and treats that copy as the source of truth afterwards. Keeping + # it on a tmpfs means every container start re-seeds from config.yaml + # and the III_* env vars, the same behavior the native CLI path has. - type: tmpfs - target: /home/nonroot/data/configuration + target: /app/config tmpfs: mode: 01777 restart: unless-stopped diff --git a/eval/README.md b/eval/README.md index 0e274ad040..5b008d0d93 100644 --- a/eval/README.md +++ b/eval/README.md @@ -26,11 +26,11 @@ source eval/scripts/sandbox.sh npm run eval:coding-life -- --adapters grep,agentmemory ``` -Requires iii v0.19.7 on PATH (agentmemory pin). If you already have a different version installed, install the pinned build into `~/.local/bin` and make sure that directory comes first on `PATH`: +Requires iii v0.22.1 on PATH (agentmemory pin). If you already have a different version installed, install the pinned build into `~/.local/bin` and make sure that directory comes first on `PATH`: ```sh mkdir -p ~/.local/bin -curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.19.7/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin +curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.22.1/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin export PATH="$HOME/.local/bin:$PATH" # add to ~/.zshrc or ~/.bashrc for persistence ``` diff --git a/eval/scripts/sandbox.sh b/eval/scripts/sandbox.sh index f192393492..7d030c2d01 100755 --- a/eval/scripts/sandbox.sh +++ b/eval/scripts/sandbox.sh @@ -14,13 +14,13 @@ REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" if ! command -v iii >/dev/null 2>&1; then echo "iii binary not on PATH. Install pinned version:" - echo " curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.19.7/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin" + echo " curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.22.1/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin" exit 1 fi iii_ver=$(iii --version 2>&1 | head -1) -if [[ "$iii_ver" != "0.19.7" ]]; then - echo "warning: iii version on PATH is $iii_ver; agentmemory pins 0.19.7" +if [[ "$iii_ver" != "0.22.1" ]]; then + echo "warning: iii version on PATH is $iii_ver; agentmemory pins 0.22.1" fi if [[ ! -f "$REPO_ROOT/dist/index.mjs" ]]; then diff --git a/examples/python/README.md b/examples/python/README.md index ea284dd47e..3e4d3e5921 100644 --- a/examples/python/README.md +++ b/examples/python/README.md @@ -10,7 +10,7 @@ This example uses the official Python SDK. ## Install ```bash -pip install iii-sdk +pip install iii-sdk==0.22.1 ``` ## Quickstart diff --git a/examples/python/observe_and_recall.py b/examples/python/observe_and_recall.py index 4747bf0b52..b9c65de5b7 100644 --- a/examples/python/observe_and_recall.py +++ b/examples/python/observe_and_recall.py @@ -4,7 +4,7 @@ agentmemory to render the most relevant context back at a fixed token budget. Prerequisites: - pip install iii-sdk + pip install iii-sdk==0.22.1 npx -y @agentmemory/agentmemory Run: diff --git a/examples/python/quickstart.py b/examples/python/quickstart.py index 56e5ae11ae..0339e079dd 100644 --- a/examples/python/quickstart.py +++ b/examples/python/quickstart.py @@ -1,7 +1,7 @@ """Minimal agentmemory usage via iii-sdk. Prerequisites: - pip install iii-sdk + pip install iii-sdk==0.22.1 npx -y @agentmemory/agentmemory # daemon at ws://localhost:49134 Run: diff --git a/package.json b/package.json index 7bca837e12..4360e3ebe5 100644 --- a/package.json +++ b/package.json @@ -65,7 +65,8 @@ "@anthropic-ai/sdk": "^0.100.1", "@clack/prompts": "^1.2.0", "dotenv": "^17.4.2", - "iii-sdk": "0.19.7", + "@iii-dev/helpers": "0.22.1", + "iii-sdk": "0.22.1", "picocolors": "^1.1.1", "zod": "^4.0.0" }, diff --git a/src/cli.ts b/src/cli.ts index b192172021..de20cad94f 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -63,6 +63,7 @@ import { resolveEngineCwd, rewriteBundledConfig, runtimeConfigPath, + engineChildEnv, } from "./cli/engine-launch.js"; import { runtimeMetadataPath } from "./runtime-paths.js"; import { createStartupStderrCapture } from "./cli/startup-stderr.js"; @@ -71,6 +72,7 @@ import { renderEngineConfig, } from "./cli/engine-config.js"; import { SHUTDOWN_HARD_EXIT_MS } from "./shutdown.js"; +import { consoleArgs, defaultConsolePort, parseConsoleArgs } from "./cli/console.js"; import { processStatIsRunning } from "./cli/process-state.js"; import { renderSplash } from "./cli/splash.js"; import { isFirstRun, readPrefs, resetPrefs, writePrefs } from "./cli/preferences.js"; @@ -116,17 +118,22 @@ if (args.includes("--version") || args.includes("-V")) { process.exit(0); } -// Pinned iii-engine version. The engine and the iii-sdk in package.json must -// stay on the same release: the worker speaks that engine's wire protocol and -// the unpinned installer tracks `latest`. 0.19.7 is the last release before -// the 0.20.0 SDK reorganization (ISdk -> IIIClient, helpers package) and the -// first line that keeps HTTP routes owned by the reconnecting worker, which -// stops the REST 404s after an engine reconnect. Bump this constant and the -// package.json dependency together. AGENTMEMORY_III_VERSION overrides the pin -// for anyone running a self-managed engine. -const IIPINNED_DEFAULT_VERSION = "0.19.7"; +// Pinned iii-engine version. The engine, the iii-sdk and the @iii-dev/helpers +// packages in package.json must stay on the same release: the worker speaks +// that engine's wire protocol and the unpinned installer tracks `latest`. +// 0.22.x is the last line before 0.23 removes the config.yaml worker +// lifecycle this CLI relies on; it keeps HTTP routes owned by the +// reconnecting worker (no REST 404s after an engine reconnect). The engine +// still boots its iii- prefixed builtins from config.yaml (the unprefixed +// http/state/queue/pubsub/cron names resolve to the standalone registry +// workers, which is the 0.23 migration, not this one). Bump this +// constant and the two package.json dependencies together. +// AGENTMEMORY_III_VERSION overrides the pin for anyone running a +// self-managed engine. +const IIPINNED_DEFAULT_VERSION = "0.22.1"; const IIPINNED_VERSION = process.env["AGENTMEMORY_III_VERSION"] || IIPINNED_DEFAULT_VERSION; +const IIIENGINE_INSTALL_CMD = `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=${IIPINNED_VERSION} sh`; // Map Node platform/arch → the asset name iii-hq/iii ships under // https://github.com/iii-hq/iii/releases/download/iii/v/ @@ -153,7 +160,7 @@ function iiiReleaseAsset(): string | null { function iiiReleaseUrl(): string | null { const asset = iiiReleaseAsset(); if (!asset) return null; - // Tag name is monorepo-prefixed: `iii/v0.19.7`. Slash is URL-encoded + // Tag name is monorepo-prefixed: `iii/v0.22.1`. Slash is URL-encoded // by GitHub when serving the download path, hence `iii/v...` not `iii%2Fv...`. return `https://github.com/iii-hq/iii/releases/download/iii/v${IIPINNED_VERSION}/${asset}`; } @@ -192,6 +199,8 @@ Commands: No arg = interactive picker. --all wires every detected agent. --dry-run shows what would change. --force re-installs. status Show connection status, memory count, flags, and health + console Launch the iii web console for this engine (workers, functions, + triggers, queues, traces). --console-port N, default viewer+1 doctor Interactive diagnostic + fixer. [F]ix · [S]kip · [?]more · [Q]uit --all: apply every fix without prompting (CI) --dry-run: show what each fix would do, don't execute @@ -736,7 +745,7 @@ function engineStateRestPort(state: EngineState): number { try { const raw = readFileSync(state.configPath, "utf-8"); const httpBlock = raw.match( - /- name:\s*iii-http([\s\S]*?)(?=\n\s*- name:|$)/, + /- name:\s*(?:iii-)?http([\s\S]*?)(?=\n\s*- name:|$)/, )?.[1]; const configuredPort = httpBlock?.match(/\n\s*port:\s*(\d+)/)?.[1]; if (configuredPort) return parseInt(configuredPort, 10); @@ -1242,95 +1251,6 @@ async function maybeOfferGlobalInstall(): Promise { } } -// iii-console install state. -// "installed" — `iii-console` is on PATH or at `~/.local/bin/iii-console` -// "missing" — binary not found anywhere we look -// We deliberately do NOT probe the console's HTTP port: the binary -// being on disk is the signal we care about (it's not auto-started by -// agentmemory and its default port 3113 collides with our viewer, so -// "is it listening?" is the wrong question at boot time). -type IiiConsoleState = - | { kind: "installed"; binPath: string } - | { kind: "missing" }; - -function detectIiiConsole(): IiiConsoleState { - const onPath = whichBinary("iii-console"); - if (onPath) return { kind: "installed", binPath: onPath }; - const fallback = IS_WINDOWS - ? join(process.env["USERPROFILE"] ?? "", ".local", "bin", "iii-console.exe") - : join(homedir(), ".local", "bin", "iii-console"); - if (fallback && existsSync(fallback)) { - return { kind: "installed", binPath: fallback }; - } - return { kind: "missing" }; -} - -// The upstream install script reads `VERSION` as an env var (see -// install.iii.dev/iii/main/install.sh: `engine_version="${VERSION:-}"`). -// Pin to IIPINNED_VERSION so a fresh boot can never pull a newer iii -// console that talks a different protocol than our pinned engine -// (root cause of protocol drift). -const III_CONSOLE_INSTALL_CMD = - `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=${IIPINNED_VERSION} sh`; - -// Display-only renderer. The internal `runCommand(shBin, ["-c", ...])` -// path uses III_CONSOLE_INSTALL_CMD verbatim (POSIX shell). Anywhere -// that PRINTS the command to a user has to handle Windows separately -// since `VERSION=X sh` and the pipe-to-sh idiom aren't valid in -// cmd.exe / PowerShell. -function iiiConsoleInstallHint(): string { - if (!IS_WINDOWS) return III_CONSOLE_INSTALL_CMD; - return ( - `# PowerShell:\n` + - ` $env:VERSION = "${IIPINNED_VERSION}"\n` + - ` iwr -useb https://install.iii.dev/iii/main/install.sh -OutFile install.sh\n` + - ` bash install.sh # WSL or Git Bash required\n` + - `# Or grab the pinned release directly:\n` + - ` https://github.com/iii-hq/iii/releases/tag/iii%2Fv${IIPINNED_VERSION}` - ); -} - -async function ensureIiiConsole(): Promise { - const state = detectIiiConsole(); - if (state.kind === "installed") return state; - - // Non-interactive contexts get the panel hint but no prompt. - if (!process.stdin.isTTY || process.env["CI"]) return state; - const prefs = readPrefs(); - if (prefs.skipConsoleInstall) return state; - - const answer = await p.confirm({ - message: - "iii console gives engine-level visibility (workers, functions, queues, traces). Install now?", - initialValue: true, - }); - if (p.isCancel(answer)) return state; - if (answer === false) { - writePrefs({ skipConsoleInstall: true }); - return state; - } - - const shBin = whichBinary("sh"); - const curlBin = whichBinary("curl"); - if (!shBin || !curlBin) { - p.log.warn( - `curl or sh not found. Install manually:\n ${iiiConsoleInstallHint()}`, - ); - return state; - } - const ok = runCommand(shBin, ["-c", III_CONSOLE_INSTALL_CMD], { - label: "Installing iii console", - }); - if (!ok) { - p.log.warn( - `iii console install failed. Re-run manually:\n ${iiiConsoleInstallHint()}`, - ); - return state; - } - // Re-detect rather than trust install-script output paths. - return detectIiiConsole(); -} - function adoptRunningEngine(): void { try { const existingState = readEngineState(); @@ -1480,6 +1400,7 @@ function spawnEngineBackground( detached: true, stdio: ["ignore", "ignore", "pipe"], windowsHide: true, + env: engineChildEnv(process.env), ...(cwd ? { cwd } : {}), }); const isDocker = label.includes("Docker"); @@ -1558,7 +1479,7 @@ function prepareEngineLaunch(configPath: string): { mkdirSync(dirname(runtimePath), { recursive: true }); writeFileSync(runtimePath, rewritten, "utf-8"); try { - const cleared = clearPersistedBuiltinConfig(cwd, rewritten); + const cleared = clearPersistedBuiltinConfig(cwd, runtimePath, rewritten); if (cleared.length > 0) { vlog( `cleared ${cleared.length} persisted builtin config entries so the rendered runtime config seeds the engine again`, @@ -1566,7 +1487,7 @@ function prepareEngineLaunch(configPath: string): { } } catch (err) { p.log.error( - `${String(err instanceof Error ? err.message : err)}. The engine would ignore the rendered runtime config and keep its previously persisted ports and timeouts. Fix the permissions under ${join(cwd, "data", "configuration")} and run agentmemory start again.`, + `${String(err instanceof Error ? err.message : err)}. The engine would ignore the rendered runtime config and keep its previously persisted ports and timeouts. Fix the permissions on that file and run agentmemory start again.`, ); process.exit(1); } @@ -1606,7 +1527,12 @@ function startIiiBin(iiiBin: string, configPath: string): boolean { configPath: launch.configPath, binPath: iiiBin, }); - spawnEngineBackground(iiiBin, ["--config", launch.configPath], "iii-engine", launch.cwd); + spawnEngineBackground( + iiiBin, + ["--config", launch.configPath, "--no-update-check"], + "iii-engine", + launch.cwd, + ); s.stop(c.ok("iii-engine process started")); return true; } @@ -1855,9 +1781,8 @@ async function reconcilePersistedDockerEngine(): Promise { p.log.error("agentmemory worker did not become ready within 15s."); process.exit(1); } - const consoleState = await ensureIiiConsole(); await maybeOfferGlobalInstall(); - printReadyHint(consoleState); + printReadyHint(); return true; } @@ -1934,26 +1859,16 @@ function getEngineHost(): string { return "localhost"; } -function printReadyHint(consoleState: IiiConsoleState): void { - // REST goes through getBaseUrl which already honors AGENTMEMORY_URL - // for full host+protocol overrides. Streams/Engine are derived from - // III_ENGINE_URL so a remote bind reads correctly in the panel. +function printReadyHint(): void { const restUrl = getBaseUrl(); const viewerUrl = getViewerUrl(); const engineHost = getEngineHost(); const streamUrl = `ws://${engineHost}:${getStreamPort()}`; const engineUrl = `ws://${engineHost}:${getEnginePort()}`; + const invocation = isInvokedViaNpx() ? "npx @agentmemory/agentmemory" : "agentmemory"; + const consolePort = defaultConsolePort(getConfiguredViewerPort()); - const consoleLine = - consoleState.kind === "installed" - ? // We can't safely probe iii-console's port (default 3113 - // collides with our viewer) so we surface the binary location - // and let the user start it on a port of their choice. Use - // the detected binary path so `(run: ...)` is executable as- - // is, even when the binary isn't on PATH under the bare - // name `iii-console`. - `${c.label("iii console")} ${c.dim(consoleState.binPath)} ${c.dim(`(run: ${consoleState.binPath} -p )`)}` - : `${c.label("iii console")} ${c.dim(`(install: ${iiiConsoleInstallHint()})`)}`; + const consoleLine = `${c.label("iii console")} ${c.cmd(`${invocation} console`)} ${c.dim(`(serves on :${consolePort}; first run downloads the console next to the pinned iii)`)}`; const lines = [ `${c.label("REST API")} ${c.url(restUrl)}`, @@ -1972,9 +1887,7 @@ function printReadyHint(consoleState: IiiConsoleState): void { // (unless they accepted the global-install prompt and the npm bin // dir was already on PATH in this shell), so we suggest the npx // form for them; everyone else gets the global form. - const demoCommand = isInvokedViaNpx() - ? "npx @agentmemory/agentmemory demo" - : "agentmemory demo"; + const demoCommand = `${invocation} demo`; process.stdout.write(`\n${c.dim("Try:")} ${c.cmd(demoCommand)}\n`); } @@ -2024,9 +1937,8 @@ async function main() { if (IS_VERBOSE) p.log.info("Skipping engine check (--no-engine)"); await import("./index.js"); if (await waitForAgentmemoryReady(15000)) { - const consoleState = await ensureIiiConsole(); await maybeOfferGlobalInstall(); - printReadyHint(consoleState); + printReadyHint(); } return; } @@ -2064,9 +1976,8 @@ async function main() { p.log.error("agentmemory worker did not become ready within 15s."); process.exit(1); } - const consoleState = await ensureIiiConsole(); await maybeOfferGlobalInstall(); - printReadyHint(consoleState); + printReadyHint(); return; } @@ -2097,7 +2008,7 @@ async function main() { ` ${c.cmd(base)}`, "", c.dim(`Step 2 needs no manual install. To install iii v${IIPINNED_VERSION} yourself (replaces your global iii), curl:`), - ` ${c.cmd(III_CONSOLE_INSTALL_CMD)}`, + ` ${c.cmd(IIIENGINE_INSTALL_CMD)}`, ` ${c.dim("or download the release:")} ${c.url(`https://github.com/iii-hq/iii/releases/tag/iii%2Fv${IIPINNED_VERSION}`)}`, ].join("\n"), "engine conflict", @@ -2176,9 +2087,8 @@ async function main() { p.log.error("agentmemory worker did not become ready within 15s."); process.exit(1); } - const consoleState = await ensureIiiConsole(); await maybeOfferGlobalInstall(); - printReadyHint(consoleState); + printReadyHint(); // Mark splash as something to skip on subsequent runs. This is a // no-op if onboarding already flipped the flag (idempotent merge). writePrefs({ skipSplash: true }); @@ -3193,19 +3103,35 @@ async function runUpgrade() { label: "Refreshing dependencies (pnpm install)", }); requireSuccess(installOk, "pnpm install"); - runCommand(pnpmBin, ["up", `iii-sdk@${IIPINNED_DEFAULT_VERSION}`], { - label: `Pinning iii-sdk@${IIPINNED_DEFAULT_VERSION}`, - optional: true, - }); + runCommand( + pnpmBin, + [ + "up", + `iii-sdk@${IIPINNED_DEFAULT_VERSION}`, + `@iii-dev/helpers@${IIPINNED_DEFAULT_VERSION}`, + ], + { + label: `Pinning iii-sdk and @iii-dev/helpers at ${IIPINNED_DEFAULT_VERSION}`, + optional: true, + }, + ); } else if (npmBin) { const installOk = runCommand(npmBin, ["install"], { label: "Refreshing dependencies (npm install)", }); requireSuccess(installOk, "npm install"); - runCommand(npmBin, ["install", `iii-sdk@${IIPINNED_DEFAULT_VERSION}`], { - label: `Pinning iii-sdk@${IIPINNED_DEFAULT_VERSION}`, - optional: true, - }); + runCommand( + npmBin, + [ + "install", + `iii-sdk@${IIPINNED_DEFAULT_VERSION}`, + `@iii-dev/helpers@${IIPINNED_DEFAULT_VERSION}`, + ], + { + label: `Pinning iii-sdk and @iii-dev/helpers at ${IIPINNED_DEFAULT_VERSION}`, + optional: true, + }, + ); } else { p.log.warn("No package manager found (pnpm/npm). Skipping JS dependency upgrade."); } @@ -4016,10 +3942,72 @@ async function runRemove(): Promise { ); } +async function runConsole(): Promise { + const iiiBin = pickCompatibleIii([ + whichBinary("iii"), + ...fallbackIiiPaths().filter((candidate) => existsSync(candidate)), + ]); + if (!iiiBin) { + p.log.error( + `No iii v${IIPINNED_VERSION} found. Start agentmemory once so it installs the pinned engine into ${privateIiiPath()}, then run this again.`, + ); + process.exit(1); + } + let parsed: ReturnType; + try { + parsed = parseConsoleArgs( + args.slice(1), + defaultConsolePort(getConfiguredViewerPort()), + ); + } catch (err) { + p.log.error(err instanceof Error ? err.message : String(err)); + process.exit(1); + } + const launch = { + iiiBin, + consolePort: parsed.consolePort, + restPort: getRestPort(), + streamPort: getStreamPort(), + enginePort: getEnginePort(), + extraArgs: parsed.extraArgs, + }; + if (!(await isEngineRunning())) { + p.log.warn( + `No engine responding on port ${launch.restPort}. The console starts anyway and connects once agentmemory is up.`, + ); + } + p.log.info( + `iii console: http://127.0.0.1:${launch.consolePort} (engine REST ${launch.restPort}, streams ${launch.streamPort}, bridge ${launch.enginePort}). The first run downloads the console binary next to the pinned iii.`, + ); + const child = spawn(iiiBin, consoleArgs(launch), { + stdio: "inherit", + detached: true, + }); + const forward = (signal: NodeJS.Signals): void => { + try { + process.kill(-child.pid!, signal); + } catch { + child.kill(signal); + } + }; + for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"] as const) { + process.on(signal, () => forward(signal)); + } + const code = await new Promise((resolve) => { + child.on("exit", (status, signal) => resolve(status ?? (signal ? 1 : 0))); + child.on("error", (err) => { + p.log.error(err.message); + resolve(1); + }); + }); + process.exit(code); +} + const commands: Record Promise> = { init: runInit, connect: runConnectCmd, status: runStatus, + console: runConsole, doctor: runDoctor, demo: runDemo, upgrade: runUpgrade, diff --git a/src/cli/console.ts b/src/cli/console.ts new file mode 100644 index 0000000000..e0fb42b202 --- /dev/null +++ b/src/cli/console.ts @@ -0,0 +1,66 @@ +export interface ConsoleLaunch { + iiiBin: string; + consolePort: number; + restPort: number; + streamPort: number; + enginePort: number; + extraArgs: string[]; +} + +const GLOBAL_VALUE_FLAGS = new Set(["--port", "--instance", "--data-dir", "--tools"]); +const GLOBAL_BOOLEAN_FLAGS = new Set(["--verbose", "-v", "--no-engine"]); + +export function defaultConsolePort(viewerPort: number): number { + return viewerPort + 1; +} + +function readPort(raw: string | undefined, flag: string): number { + const port = raw === undefined ? Number.NaN : Number(raw); + if (!Number.isInteger(port) || port < 1 || port > 65535) { + throw new Error(`${flag} needs a port between 1 and 65535`); + } + return port; +} + +export function parseConsoleArgs( + tail: string[], + fallbackPort: number, +): { consolePort: number; extraArgs: string[] } { + let consolePort = fallbackPort; + const extraArgs: string[] = []; + for (let i = 0; i < tail.length; i++) { + const arg = tail[i]!; + if (arg === "--console-port") { + consolePort = readPort(tail[i + 1], arg); + i++; + continue; + } + if (arg.startsWith("--console-port=")) { + consolePort = readPort(arg.slice("--console-port=".length), "--console-port"); + continue; + } + if (GLOBAL_VALUE_FLAGS.has(arg)) { + i++; + continue; + } + if ([...GLOBAL_VALUE_FLAGS].some((flag) => arg.startsWith(`${flag}=`))) continue; + if (GLOBAL_BOOLEAN_FLAGS.has(arg)) continue; + extraArgs.push(arg); + } + return { consolePort, extraArgs }; +} + +export function consoleArgs(launch: ConsoleLaunch): string[] { + return [ + "console", + "--port", + String(launch.consolePort), + "--engine-port", + String(launch.restPort), + "--ws-port", + String(launch.streamPort), + "--bridge-port", + String(launch.enginePort), + ...launch.extraArgs, + ]; +} diff --git a/src/cli/doctor-diagnostics.ts b/src/cli/doctor-diagnostics.ts index bab2fd2919..78705d60c8 100644 --- a/src/cli/doctor-diagnostics.ts +++ b/src/cli/doctor-diagnostics.ts @@ -38,7 +38,7 @@ export type DoctorContext = { pidfilePath: string; /** Path to ~/.agentmemory/engine-state.json */ enginePath: string; - /** Pinned engine version (e.g. "0.19.7"). */ + /** Pinned engine version (e.g. "0.22.1"). */ pinnedVersion: string; }; diff --git a/src/cli/engine-config.ts b/src/cli/engine-config.ts index 7e5121ed58..b48f09dfa5 100644 --- a/src/cli/engine-config.ts +++ b/src/cli/engine-config.ts @@ -1,11 +1,16 @@ -import { rmSync } from "node:fs"; -import { join, resolve } from "node:path"; +import { readFileSync, rmSync } from "node:fs"; +import { basename, dirname, join, resolve } from "node:path"; const SEEDED_BUILTIN_WORKERS = [ + "http", "iii-http", + "state", "iii-state", + "queue", "iii-queue", + "pubsub", "iii-pubsub", + "cron", "iii-cron", "iii-stream", "iii-observability", @@ -25,9 +30,14 @@ export function configuredPersistDir(renderedConfig: string): string | null { export function persistedBuiltinConfigDirs( engineCwd: string, + configPath: string, renderedConfig?: string, ): string[] { - const dirs = [join(engineCwd, "data", "configuration")]; + const dirs = [ + join(engineCwd, "config"), + join(dirname(configPath), "config"), + join(engineCwd, "data", "configuration"), + ]; const custom = renderedConfig ? configuredPersistDir(renderedConfig) : null; if (custom) dirs.unshift(resolve(engineCwd, custom)); return [...new Set(dirs)]; @@ -35,20 +45,29 @@ export function persistedBuiltinConfigDirs( export function persistedBuiltinConfigPaths( engineCwd: string, + configPath: string, renderedConfig?: string, ): string[] { - return persistedBuiltinConfigDirs(engineCwd, renderedConfig).flatMap((dir) => + return persistedBuiltinConfigDirs(engineCwd, configPath, renderedConfig).flatMap((dir) => SEEDED_BUILTIN_WORKERS.map((id) => join(dir, `${id}.yaml`)), ); } +export function isPersistedBuiltinEntry(content: string, id: string): boolean { + const firstLine = content.split("\n").find((line) => line.trim() !== ""); + return firstLine?.trim() === `id: ${id}`; +} + export function clearPersistedBuiltinConfig( engineCwd: string, + configPath: string, renderedConfig?: string, ): string[] { const cleared: string[] = []; - for (const path of persistedBuiltinConfigPaths(engineCwd, renderedConfig)) { + for (const path of persistedBuiltinConfigPaths(engineCwd, configPath, renderedConfig)) { try { + const content = readFileSync(path, "utf8"); + if (!isPersistedBuiltinEntry(content, basename(path, ".yaml"))) continue; rmSync(path); cleared.push(path); } catch (err) { diff --git a/src/cli/engine-launch.ts b/src/cli/engine-launch.ts index b162e7f5c5..d75173600e 100644 --- a/src/cli/engine-launch.ts +++ b/src/cli/engine-launch.ts @@ -187,3 +187,7 @@ export function legacyDataMigrations( }, ]; } + +export function engineChildEnv(base: NodeJS.ProcessEnv): NodeJS.ProcessEnv { + return { ...base, III_TELEMETRY_ENABLED: base["III_TELEMETRY_ENABLED"] ?? "false" }; +} diff --git a/src/cli/preferences.ts b/src/cli/preferences.ts index 63695db623..1518e43f00 100644 --- a/src/cli/preferences.ts +++ b/src/cli/preferences.ts @@ -49,17 +49,13 @@ export interface Prefs { // globally?" prompt on first npx run. We never ask again on this // machine so the prompt stays a one-time DX nudge, not a nag. skipGlobalInstall: boolean; - // Set to true when the user declines the "install iii console?" - // prompt. iii console is first-class engine UI but optional at the - // install step — once the user says no, we stop asking. - skipConsoleInstall: boolean; // ISO timestamp of the first time onboarding completed. Set once, // never updated, so we can show "you joined agentmemory N days ago" // copy in /status later without keeping a separate file. firstRunAt: string | null; // Set to true once the user has answered the context-injection prompt // (either way). We never re-ask after this so the prompt stays a - // one-time choice, matching the skipGlobalInstall / skipConsoleInstall + // one-time choice, matching the skipGlobalInstall // never-nag pattern. injectContextChosen: boolean; } @@ -72,7 +68,6 @@ const DEFAULTS: Prefs = { skipSplash: false, skipNpxHint: false, skipGlobalInstall: false, - skipConsoleInstall: false, firstRunAt: null, injectContextChosen: false, }; diff --git a/src/functions/actions.ts b/src/functions/actions.ts index 12d12df39b..9bf583f698 100644 --- a/src/functions/actions.ts +++ b/src/functions/actions.ts @@ -1,11 +1,11 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { StateKV } from "../state/kv.js"; import { KV, generateId } from "../state/schema.js"; import { withKeyedLock } from "../state/keyed-mutex.js"; import type { Action, ActionEdge } from "../types.js"; import { recordAudit } from "./audit.js"; -export function registerActionsFunction(sdk: ISdk, kv: StateKV): void { +export function registerActionsFunction(sdk: IIIClient, kv: StateKV): void { sdk.registerFunction("mem::action-create", async (data: { title: string; diff --git a/src/functions/auto-forget.ts b/src/functions/auto-forget.ts index 74c571b980..d8f6ac7038 100644 --- a/src/functions/auto-forget.ts +++ b/src/functions/auto-forget.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { Memory, CompressedObservation, Session } from "../types.js"; import { KV } from "../state/schema.js"; import { StateKV } from "../state/kv.js"; @@ -21,7 +21,7 @@ interface AutoForgetResult { dryRun: boolean; } -export function registerAutoForgetFunction(sdk: ISdk, kv: StateKV): void { +export function registerAutoForgetFunction(sdk: IIIClient, kv: StateKV): void { sdk.registerFunction("mem::auto-forget", async (data: { dryRun?: boolean }): Promise => { const dryRun = data?.dryRun ?? false; diff --git a/src/functions/branch-aware.ts b/src/functions/branch-aware.ts index d0240f4366..68e63336f2 100644 --- a/src/functions/branch-aware.ts +++ b/src/functions/branch-aware.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { StateKV } from "../state/kv.js"; import { KV } from "../state/schema.js"; import type { Session } from "../types.js"; @@ -18,7 +18,7 @@ function execAsync( }); } -export function registerBranchAwareFunction(sdk: ISdk, kv: StateKV): void { +export function registerBranchAwareFunction(sdk: IIIClient, kv: StateKV): void { sdk.registerFunction("mem::detect-worktree", async (data: { cwd: string }) => { if (!data.cwd) { diff --git a/src/functions/cascade.ts b/src/functions/cascade.ts index fb979e65fc..2167c506d5 100644 --- a/src/functions/cascade.ts +++ b/src/functions/cascade.ts @@ -1,10 +1,10 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { StateKV } from "../state/kv.js"; import { KV } from "../state/schema.js"; import type { Memory, GraphNode, GraphEdge } from "../types.js"; import { recordAudit } from "./audit.js"; -export function registerCascadeFunction(sdk: ISdk, kv: StateKV): void { +export function registerCascadeFunction(sdk: IIIClient, kv: StateKV): void { sdk.registerFunction("mem::cascade-update", async (data: { supersededMemoryId: string }) => { if (!data.supersededMemoryId || typeof data.supersededMemoryId !== "string") { diff --git a/src/functions/checkpoints.ts b/src/functions/checkpoints.ts index efb3957a9c..525f07d935 100644 --- a/src/functions/checkpoints.ts +++ b/src/functions/checkpoints.ts @@ -1,11 +1,11 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { StateKV } from "../state/kv.js"; import { KV, generateId } from "../state/schema.js"; import { withKeyedLock } from "../state/keyed-mutex.js"; import type { Action, ActionEdge, Checkpoint } from "../types.js"; import { recordAudit } from "./audit.js"; -export function registerCheckpointsFunction(sdk: ISdk, kv: StateKV): void { +export function registerCheckpointsFunction(sdk: IIIClient, kv: StateKV): void { sdk.registerFunction("mem::checkpoint-create", async (data: { name: string; diff --git a/src/functions/claude-bridge.ts b/src/functions/claude-bridge.ts index 3aba76f567..1c7c245e12 100644 --- a/src/functions/claude-bridge.ts +++ b/src/functions/claude-bridge.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import { readFileSync, writeFileSync, mkdirSync, existsSync } from "node:fs"; import { dirname } from "node:path"; import type { Memory, ClaudeBridgeConfig } from "../types.js"; @@ -70,7 +70,7 @@ function serializeToMemoryMd( } export function registerClaudeBridgeFunction( - sdk: ISdk, + sdk: IIIClient, kv: StateKV, config: ClaudeBridgeConfig, ): void { diff --git a/src/functions/compress-file.ts b/src/functions/compress-file.ts index 0a54452b23..a1ce308fad 100644 --- a/src/functions/compress-file.ts +++ b/src/functions/compress-file.ts @@ -1,7 +1,7 @@ import { constants } from "node:fs"; import { lstat, open, readFile, writeFile } from "node:fs/promises"; import { basename, dirname, extname, join, resolve } from "node:path"; -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { MemoryProvider } from "../types.js"; import type { StateKV } from "../state/kv.js"; import { recordAudit } from "./audit.js"; @@ -93,7 +93,7 @@ function resolveBackupPath(filePath: string): string { } export function registerCompressFileFunction( - sdk: ISdk, + sdk: IIIClient, kv: StateKV, provider: MemoryProvider, ): void { diff --git a/src/functions/compress.ts b/src/functions/compress.ts index c94d856e3a..a87a5b4fd2 100644 --- a/src/functions/compress.ts +++ b/src/functions/compress.ts @@ -1,4 +1,4 @@ -import { TriggerAction, type ISdk } from "iii-sdk"; +import { TriggerAction, type IIIClient } from "iii-sdk"; import { readFileSync } from "node:fs"; import { isManagedImagePath } from "../utils/image-store.js"; import type { @@ -65,7 +65,7 @@ function parseCompressionXml( } export function registerCompressFunction( - sdk: ISdk, + sdk: IIIClient, kv: StateKV, provider: MemoryProvider, metricsStore?: MetricsStore, diff --git a/src/functions/consolidate.ts b/src/functions/consolidate.ts index d394e1766f..8924a03a1a 100644 --- a/src/functions/consolidate.ts +++ b/src/functions/consolidate.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { CompressedObservation, Memory, @@ -63,7 +63,7 @@ function parseMemoryXml( } export function registerConsolidateFunction( - sdk: ISdk, + sdk: IIIClient, kv: StateKV, provider: MemoryProvider, ): void { diff --git a/src/functions/consolidation-pipeline.ts b/src/functions/consolidation-pipeline.ts index e51ab97c86..75791148df 100644 --- a/src/functions/consolidation-pipeline.ts +++ b/src/functions/consolidation-pipeline.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { SemanticMemory, ProceduralMemory, @@ -43,7 +43,7 @@ function applyDecay( } export function registerConsolidationPipelineFunction( - sdk: ISdk, + sdk: IIIClient, kv: StateKV, provider: MemoryProvider, ): void { diff --git a/src/functions/context.ts b/src/functions/context.ts index 2d64b3f3a8..668ac61b58 100644 --- a/src/functions/context.ts +++ b/src/functions/context.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { Session, CompressedObservation, @@ -32,7 +32,7 @@ function escapeXmlAttr(s: string): string { } export function registerContextFunction( - sdk: ISdk, + sdk: IIIClient, kv: StateKV, tokenBudget: number, ): void { diff --git a/src/functions/crystallize.ts b/src/functions/crystallize.ts index 1f0b84316d..7904fee2ae 100644 --- a/src/functions/crystallize.ts +++ b/src/functions/crystallize.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { StateKV } from "../state/kv.js"; import { KV, generateId } from "../state/schema.js"; import type { Action, ActionEdge, Crystal, MemoryProvider } from "../types.js"; @@ -16,7 +16,7 @@ Extract: (1) what was accomplished in 1-2 sentences, (2) key decisions as bullet Return as JSON: { "narrative": "...", "keyOutcomes": ["..."], "filesAffected": ["..."], "lessons": ["..."] }`; export function registerCrystallizeFunction( - sdk: ISdk, + sdk: IIIClient, kv: StateKV, provider: MemoryProvider, ): void { diff --git a/src/functions/diagnostics.ts b/src/functions/diagnostics.ts index cc982883f6..33bf3f0c00 100644 --- a/src/functions/diagnostics.ts +++ b/src/functions/diagnostics.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { StateKV } from "../state/kv.js"; import { KV } from "../state/schema.js"; import { withKeyedLock } from "../state/keyed-mutex.js"; @@ -43,7 +43,7 @@ const ALL_CATEGORIES = [ const TWENTY_FOUR_HOURS_MS = 24 * 60 * 60 * 1000; const ONE_HOUR_MS = 60 * 60 * 1000; -export function registerDiagnosticsFunction(sdk: ISdk, kv: StateKV): void { +export function registerDiagnosticsFunction(sdk: IIIClient, kv: StateKV): void { sdk.registerFunction("mem::diagnose", async (data: { categories?: string[] }) => { const categories = data.categories && data.categories.length > 0 diff --git a/src/functions/disk-size-manager.ts b/src/functions/disk-size-manager.ts index 0905e83c3e..9f61d6eb95 100644 --- a/src/functions/disk-size-manager.ts +++ b/src/functions/disk-size-manager.ts @@ -1,4 +1,4 @@ -import { TriggerAction, type ISdk } from "iii-sdk"; +import { TriggerAction, type IIIClient } from "iii-sdk"; import { KV } from "../state/schema.js"; import { StateKV } from "../state/kv.js"; import { getMaxBytes } from "../utils/image-store.js"; @@ -8,7 +8,7 @@ import type { StateScope, StateScopeKey } from "../types.js"; const DISK_SIZE_KEY: StateScopeKey = "system:currentDiskSize"; -export function registerDiskSizeManager(sdk: ISdk, kv: StateKV): void { +export function registerDiskSizeManager(sdk: IIIClient, kv: StateKV): void { sdk.registerFunction( "mem::disk-size-delta", async (data: { deltaBytes: number }) => { diff --git a/src/functions/enrich.ts b/src/functions/enrich.ts index 032ec97b47..d4f900af29 100644 --- a/src/functions/enrich.ts +++ b/src/functions/enrich.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { Memory } from "../types.js"; import { KV } from "../state/schema.js"; import { StateKV } from "../state/kv.js"; @@ -15,7 +15,7 @@ function escapeXml(s: string): string { .replace(/'/g, "'"); } -export function registerEnrichFunction(sdk: ISdk, kv: StateKV): void { +export function registerEnrichFunction(sdk: IIIClient, kv: StateKV): void { sdk.registerFunction("mem::enrich", async (data: { sessionId: string; diff --git a/src/functions/evict.ts b/src/functions/evict.ts index 722606951b..b7afb20289 100644 --- a/src/functions/evict.ts +++ b/src/functions/evict.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { Session, CompressedObservation, @@ -55,7 +55,7 @@ function isCompressedObservation( } async function recoverStaleSession( - sdk: ISdk, + sdk: IIIClient, sessionId: string, ): Promise { try { @@ -82,7 +82,7 @@ async function recoverStaleSession( } } -async function runRecoveredSessionConsolidation(sdk: ISdk): Promise { +async function runRecoveredSessionConsolidation(sdk: IIIClient): Promise { // Same gate as the session-stop path: keyless installs must not fire // no-op LLM consolidation from an eviction sweep either. if (!isConsolidationEnabled()) return; @@ -105,7 +105,7 @@ async function runRecoveredSessionConsolidation(sdk: ISdk): Promise { } } -export function registerEvictFunction(sdk: ISdk, kv: StateKV): void { +export function registerEvictFunction(sdk: IIIClient, kv: StateKV): void { sdk.registerFunction("mem::evict", async (data: { dryRun?: boolean }): Promise => { const dryRun = data?.dryRun ?? false; diff --git a/src/functions/export-import.ts b/src/functions/export-import.ts index 7bdabf6125..6d0128f36a 100644 --- a/src/functions/export-import.ts +++ b/src/functions/export-import.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { Session, CompressedObservation, @@ -58,7 +58,7 @@ async function runChunked( } } -export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void { +export function registerExportImportFunction(sdk: IIIClient, kv: StateKV): void { sdk.registerFunction("mem::export", async (data?: { maxSessions?: number; offset?: number }) => { const rawMax = Number(data?.maxSessions); diff --git a/src/functions/facets.ts b/src/functions/facets.ts index cb5b37dcda..430d0a324b 100644 --- a/src/functions/facets.ts +++ b/src/functions/facets.ts @@ -1,9 +1,9 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { StateKV } from "../state/kv.js"; import { KV, generateId } from "../state/schema.js"; import type { Facet } from "../types.js"; -export function registerFacetsFunction(sdk: ISdk, kv: StateKV): void { +export function registerFacetsFunction(sdk: IIIClient, kv: StateKV): void { sdk.registerFunction("mem::facet-tag", async (data: { targetId: string; diff --git a/src/functions/file-index.ts b/src/functions/file-index.ts index a5c503185b..a52bf0356f 100644 --- a/src/functions/file-index.ts +++ b/src/functions/file-index.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { CompressedObservation, Session } from "../types.js"; import { KV } from "../state/schema.js"; import { StateKV } from "../state/kv.js"; @@ -19,7 +19,7 @@ interface FileHistory { }>; } -export function registerFileIndexFunction(sdk: ISdk, kv: StateKV): void { +export function registerFileIndexFunction(sdk: IIIClient, kv: StateKV): void { sdk.registerFunction("mem::file-context", async ( data: { sessionId?: string; files?: string[]; project?: string } | undefined, diff --git a/src/functions/flow-compress.ts b/src/functions/flow-compress.ts index d2eb5a31c1..3be1ca6e97 100644 --- a/src/functions/flow-compress.ts +++ b/src/functions/flow-compress.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { StateKV } from "../state/kv.js"; import { KV, generateId } from "../state/schema.js"; import type { Action, ActionEdge, RoutineRun, MemoryProvider } from "../types.js"; @@ -20,7 +20,7 @@ Output as XML: `; export function registerFlowCompressFunction( - sdk: ISdk, + sdk: IIIClient, kv: StateKV, provider: MemoryProvider, ): void { diff --git a/src/functions/frontier.ts b/src/functions/frontier.ts index 30f43fec60..0676f92b17 100644 --- a/src/functions/frontier.ts +++ b/src/functions/frontier.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { StateKV } from "../state/kv.js"; import { KV } from "../state/schema.js"; import type { Action, ActionEdge, Checkpoint, Lease } from "../types.js"; @@ -10,7 +10,7 @@ export interface FrontierItem { leased: boolean; } -export function registerFrontierFunction(sdk: ISdk, kv: StateKV): void { +export function registerFrontierFunction(sdk: IIIClient, kv: StateKV): void { sdk.registerFunction("mem::frontier", async (data: { project?: string; diff --git a/src/functions/governance.ts b/src/functions/governance.ts index 16d0d1c427..d8d0ab01cd 100644 --- a/src/functions/governance.ts +++ b/src/functions/governance.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { Memory, GovernanceFilter, AuditEntry } from "../types.js"; import { KV } from "../state/schema.js"; import type { StateKV } from "../state/kv.js"; @@ -7,7 +7,7 @@ import { deleteAccessLog } from "./access-tracker.js"; import { getSearchIndex, vectorIndexRemove, flushIndexSave } from "./search.js"; import { logger } from "../logger.js"; -export function registerGovernanceFunction(sdk: ISdk, kv: StateKV): void { +export function registerGovernanceFunction(sdk: IIIClient, kv: StateKV): void { sdk.registerFunction("mem::governance-delete", async (data: { memoryIds: string[]; reason?: string }) => { if ( diff --git a/src/functions/graph-import.ts b/src/functions/graph-import.ts index 520decc671..502526e8ba 100644 --- a/src/functions/graph-import.ts +++ b/src/functions/graph-import.ts @@ -1,6 +1,6 @@ import { readFile, stat } from "node:fs/promises"; import { join } from "node:path"; -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { GraphEdge, GraphEdgeType, GraphNode, GraphNodeType } from "../types.js"; import { KV, generateId } from "../state/schema.js"; import type { StateKV } from "../state/kv.js"; @@ -192,7 +192,7 @@ export function parseGraphifyGraph(raw: string): { }; } -export function registerGraphImportFunction(sdk: ISdk, kv: StateKV): void { +export function registerGraphImportFunction(sdk: IIIClient, kv: StateKV): void { sdk.registerFunction( "mem::graph::import-graphify", async (data?: { path?: string; cwd?: string }): Promise => { diff --git a/src/functions/graph.ts b/src/functions/graph.ts index 76340d60fc..62e7343e3b 100644 --- a/src/functions/graph.ts +++ b/src/functions/graph.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { GraphNode, GraphEdge, @@ -680,7 +680,7 @@ export async function persistGraphDelta( } export function registerGraphFunction( - sdk: ISdk, + sdk: IIIClient, kv: StateKV, provider: MemoryProvider, ): void { diff --git a/src/functions/image-quota-cleanup.ts b/src/functions/image-quota-cleanup.ts index d07dfa9698..12339bd658 100644 --- a/src/functions/image-quota-cleanup.ts +++ b/src/functions/image-quota-cleanup.ts @@ -1,4 +1,4 @@ -import { TriggerAction, type ISdk } from "iii-sdk"; +import { TriggerAction, type IIIClient } from "iii-sdk"; import { KV } from "../state/schema.js"; import { StateKV } from "../state/kv.js"; import { readdir, stat } from "node:fs/promises"; @@ -9,7 +9,7 @@ import { logger } from "../logger.js"; const GRACE_PERIOD_MS = 30_000; -export function registerImageQuotaCleanup(sdk: ISdk, kv: StateKV): void { +export function registerImageQuotaCleanup(sdk: IIIClient, kv: StateKV): void { sdk.registerFunction( "mem::image-quota-cleanup", async () => { diff --git a/src/functions/image-refs.ts b/src/functions/image-refs.ts index ce1661df42..918a7e7c46 100644 --- a/src/functions/image-refs.ts +++ b/src/functions/image-refs.ts @@ -1,4 +1,4 @@ -import { TriggerAction, type ISdk } from "iii-sdk"; +import { TriggerAction, type IIIClient } from "iii-sdk"; import { KV } from "../state/schema.js"; import { StateKV } from "../state/kv.js"; import { deleteImage, touchImage } from "../utils/image-store.js"; @@ -17,7 +17,7 @@ export async function incrementImageRef(kv: StateKV, filePath: string): Promise< }); } -export async function decrementImageRef(kv: StateKV, sdk: ISdk, filePath: string): Promise { +export async function decrementImageRef(kv: StateKV, sdk: IIIClient, filePath: string): Promise { return withKeyedLock(`imgRef:${filePath}`, async () => { const current = await getImageRefCount(kv, filePath); if (current <= 1) { diff --git a/src/functions/leases.ts b/src/functions/leases.ts index 1a2de33bfc..dfe1ef47de 100644 --- a/src/functions/leases.ts +++ b/src/functions/leases.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { StateKV } from "../state/kv.js"; import { KV, generateId } from "../state/schema.js"; import { withKeyedLock } from "../state/keyed-mutex.js"; @@ -8,7 +8,7 @@ import { recordAudit } from "./audit.js"; const DEFAULT_LEASE_TTL_MS = 10 * 60 * 1000; const MAX_LEASE_TTL_MS = 60 * 60 * 1000; -export function registerLeasesFunction(sdk: ISdk, kv: StateKV): void { +export function registerLeasesFunction(sdk: IIIClient, kv: StateKV): void { sdk.registerFunction("mem::lease-acquire", async (data: { actionId: string; agentId: string; ttlMs?: number }) => { if (!data.actionId || !data.agentId) { diff --git a/src/functions/lessons.ts b/src/functions/lessons.ts index d0a4a21ef3..c750b1d614 100644 --- a/src/functions/lessons.ts +++ b/src/functions/lessons.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { StateKV } from "../state/kv.js"; import { KV, fingerprintId } from "../state/schema.js"; import type { Lesson } from "../types.js"; @@ -63,7 +63,7 @@ function reinforceLesson(lesson: Lesson): void { lesson.updatedAt = now; } -export function registerLessonsFunctions(sdk: ISdk, kv: StateKV): void { +export function registerLessonsFunctions(sdk: IIIClient, kv: StateKV): void { sdk.registerFunction("mem::lesson-save", async (data: { content: string; diff --git a/src/functions/mesh.ts b/src/functions/mesh.ts index ad52e5ea73..139765adf2 100644 --- a/src/functions/mesh.ts +++ b/src/functions/mesh.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { StateKV } from "../state/kv.js"; import { KV, generateId } from "../state/schema.js"; import { withKeyedLock } from "../state/keyed-mutex.js"; @@ -137,7 +137,7 @@ async function lwwMergeGraphNodes( } export function registerMeshFunction( - sdk: ISdk, + sdk: IIIClient, kv: StateKV, meshAuthToken?: string, ): void { diff --git a/src/functions/migrate.ts b/src/functions/migrate.ts index c2039ea1c3..8cabef5315 100644 --- a/src/functions/migrate.ts +++ b/src/functions/migrate.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import { resolve } from "node:path"; import { homedir } from "node:os"; import { KV, generateId } from "../state/schema.js"; @@ -85,7 +85,7 @@ export async function inferMemoryProjects( return { updated, skipped, ambiguous }; } -export function registerMigrateFunction(sdk: ISdk, kv: StateKV): void { +export function registerMigrateFunction(sdk: IIIClient, kv: StateKV): void { sdk.registerFunction("mem::migrate", async (data: { dbPath?: string; step?: string; dryRun?: boolean }) => { // In-place KV migration steps (no SQLite dependency). diff --git a/src/functions/observe.ts b/src/functions/observe.ts index e9b0f314e4..fa45f68f2d 100644 --- a/src/functions/observe.ts +++ b/src/functions/observe.ts @@ -1,4 +1,4 @@ -import { TriggerAction, type ISdk } from "iii-sdk"; +import { TriggerAction, type IIIClient } from "iii-sdk"; import type { RawObservation, HookPayload, Origin } from "../types.js"; const TOOL_HOOKS = new Set(["pre_tool_use", "post_tool_use", "post_tool_failure"]); @@ -38,7 +38,7 @@ export function extractImage(d: unknown): string | undefined { } export function registerObserveFunction( - sdk: ISdk, + sdk: IIIClient, kv: StateKV, dedupMap?: DedupMap, maxObservationsPerSession?: number, diff --git a/src/functions/obsidian-export.ts b/src/functions/obsidian-export.ts index 0e8194813a..d55ea1bbaa 100644 --- a/src/functions/obsidian-export.ts +++ b/src/functions/obsidian-export.ts @@ -1,7 +1,7 @@ import { mkdir, writeFile } from "node:fs/promises"; import { join, resolve, sep } from "node:path"; import { homedir } from "node:os"; -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { StateKV } from "../state/kv.js"; import { KV } from "../state/schema.js"; import type { @@ -242,7 +242,7 @@ interface ExportError { } export function registerObsidianExportFunction( - sdk: ISdk, + sdk: IIIClient, kv: StateKV, ): void { sdk.registerFunction("mem::obsidian-export", diff --git a/src/functions/patterns.ts b/src/functions/patterns.ts index ef6821cbee..eef43f3099 100644 --- a/src/functions/patterns.ts +++ b/src/functions/patterns.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { CompressedObservation, Session } from "../types.js"; import { KV } from "../state/schema.js"; import { StateKV } from "../state/kv.js"; @@ -12,7 +12,7 @@ interface Pattern { sessions: string[]; } -export function registerPatternsFunction(sdk: ISdk, kv: StateKV): void { +export function registerPatternsFunction(sdk: IIIClient, kv: StateKV): void { sdk.registerFunction("mem::patterns", async (data: { project?: string }) => { const patterns: Pattern[] = []; diff --git a/src/functions/privacy.ts b/src/functions/privacy.ts index f28edd3e25..da84b6218c 100644 --- a/src/functions/privacy.ts +++ b/src/functions/privacy.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; const PRIVATE_TAG_RE = /[\s\S]*?<\/private>/gi; @@ -28,7 +28,7 @@ export function stripPrivateData(input: string): string { return result; } -export function registerPrivacyFunction(sdk: ISdk): void { +export function registerPrivacyFunction(sdk: IIIClient): void { sdk.registerFunction("mem::privacy", async (data: { input?: unknown } | undefined) => { if (!data || typeof data.input !== "string") { diff --git a/src/functions/profile.ts b/src/functions/profile.ts index 07881e9227..a27a4463ad 100644 --- a/src/functions/profile.ts +++ b/src/functions/profile.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { CompressedObservation, Session, @@ -9,7 +9,7 @@ import { StateKV } from "../state/kv.js"; import { recordAudit } from "./audit.js"; import { logger } from "../logger.js"; -export function registerProfileFunction(sdk: ISdk, kv: StateKV): void { +export function registerProfileFunction(sdk: IIIClient, kv: StateKV): void { sdk.registerFunction("mem::profile", async (data: { project: string; refresh?: boolean } | undefined) => { if (!data || typeof data.project !== "string" || !data.project.trim()) { diff --git a/src/functions/query-expansion.ts b/src/functions/query-expansion.ts index 00cfdf48c4..45e551db68 100644 --- a/src/functions/query-expansion.ts +++ b/src/functions/query-expansion.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { MemoryProvider, QueryExpansion } from "../types.js"; import { logger } from "../logger.js"; @@ -67,7 +67,7 @@ function parseExpansionXml(xml: string): QueryExpansion | null { } export function registerQueryExpansionFunction( - sdk: ISdk, + sdk: IIIClient, provider: MemoryProvider, ): void { sdk.registerFunction("mem::expand-query", diff --git a/src/functions/recent-searches-sweep.ts b/src/functions/recent-searches-sweep.ts index 03df192cfb..3b75a7e26d 100644 --- a/src/functions/recent-searches-sweep.ts +++ b/src/functions/recent-searches-sweep.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { StateKV } from "../state/kv.js"; import { KV } from "../state/schema.js"; import { logger } from "../logger.js"; @@ -12,7 +12,7 @@ import { getFollowupWindowSeconds } from "../config.js"; const RETENTION_MS = 24 * 60 * 60 * 1000; export function registerRecentSearchesSweepFunction( - sdk: ISdk, + sdk: IIIClient, kv: StateKV, ): void { sdk.registerFunction( diff --git a/src/functions/reflect.ts b/src/functions/reflect.ts index 3a2af82934..b93a5dc07c 100644 --- a/src/functions/reflect.ts +++ b/src/functions/reflect.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { StateKV } from "../state/kv.js"; import { KV, fingerprintId } from "../state/schema.js"; import type { @@ -161,7 +161,7 @@ function buildJaccardClusters( } export function registerReflectFunctions( - sdk: ISdk, + sdk: IIIClient, kv: StateKV, provider: MemoryProvider, ): void { diff --git a/src/functions/relations.ts b/src/functions/relations.ts index 7921a32834..7bde404caa 100644 --- a/src/functions/relations.ts +++ b/src/functions/relations.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { Memory, MemoryRelation } from "../types.js"; import { KV, generateId } from "../state/schema.js"; import { StateKV } from "../state/kv.js"; @@ -36,7 +36,7 @@ function computeConfidence( return Math.max(0, Math.min(1, score)); } -export function registerRelationsFunction(sdk: ISdk, kv: StateKV): void { +export function registerRelationsFunction(sdk: IIIClient, kv: StateKV): void { sdk.registerFunction("mem::relate", async (data: { sourceId: string; diff --git a/src/functions/remember.ts b/src/functions/remember.ts index e7a1793cd4..73f6e3c303 100644 --- a/src/functions/remember.ts +++ b/src/functions/remember.ts @@ -1,4 +1,4 @@ -import { TriggerAction, type ISdk } from "iii-sdk"; +import { TriggerAction, type IIIClient } from "iii-sdk"; import type { Memory } from "../types.js"; import { KV, generateId, jaccardSimilarity } from "../state/schema.js"; import { StateKV } from "../state/kv.js"; @@ -19,7 +19,7 @@ function safeSlice(text: string, length: number): string { return /[\uD800-\uDBFF]$/.test(sliced) ? sliced.slice(0, -1) : sliced; } -export function registerRememberFunction(sdk: ISdk, kv: StateKV): void { +export function registerRememberFunction(sdk: IIIClient, kv: StateKV): void { sdk.registerFunction("mem::remember", async (data: { content: string; diff --git a/src/functions/replay.ts b/src/functions/replay.ts index 246a6d61b3..aea735ff98 100644 --- a/src/functions/replay.ts +++ b/src/functions/replay.ts @@ -1,7 +1,7 @@ import { homedir } from "node:os"; import { lstat, readFile, readdir } from "node:fs/promises"; import { resolve, join } from "node:path"; -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { CompressedObservation, Crystal, @@ -261,7 +261,7 @@ async function findJsonlFiles( }; } -export function registerReplayFunctions(sdk: ISdk, kv: StateKV): void { +export function registerReplayFunctions(sdk: IIIClient, kv: StateKV): void { sdk.registerFunction( "mem::replay::load", async (data: { sessionId: string }): Promise< diff --git a/src/functions/retention.ts b/src/functions/retention.ts index fd3e64669c..fac16796f1 100644 --- a/src/functions/retention.ts +++ b/src/functions/retention.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { Memory, SemanticMemory, @@ -121,7 +121,7 @@ function computeSalience( } export function registerRetentionFunctions( - sdk: ISdk, + sdk: IIIClient, kv: StateKV, ): void { sdk.registerFunction("mem::retention-score", diff --git a/src/functions/routines.ts b/src/functions/routines.ts index d1a9135a9e..855536a24a 100644 --- a/src/functions/routines.ts +++ b/src/functions/routines.ts @@ -1,11 +1,11 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { StateKV } from "../state/kv.js"; import { KV, generateId } from "../state/schema.js"; import { withKeyedLock } from "../state/keyed-mutex.js"; import type { Action, Routine, RoutineStep, RoutineRun } from "../types.js"; import { recordAudit } from "./audit.js"; -export function registerRoutinesFunction(sdk: ISdk, kv: StateKV): void { +export function registerRoutinesFunction(sdk: IIIClient, kv: StateKV): void { sdk.registerFunction("mem::routine-create", async (data: { name: string; diff --git a/src/functions/search.ts b/src/functions/search.ts index 2f44273c1e..bb585aa071 100644 --- a/src/functions/search.ts +++ b/src/functions/search.ts @@ -1,4 +1,4 @@ -import type { ISdk } from 'iii-sdk' +import type { IIIClient } from 'iii-sdk' import type { CompactSearchResult, CompressedObservation, Memory, SearchResult, Session } from '../types.js' import { KV } from '../state/schema.js' import { StateKV } from '../state/kv.js' @@ -385,7 +385,7 @@ export async function rebuildIndex(kv: StateKV): Promise { return indexed } -export function registerSearchFunction(sdk: ISdk, kv: StateKV): void { +export function registerSearchFunction(sdk: IIIClient, kv: StateKV): void { sdk.registerFunction( 'mem::search', async (data: { diff --git a/src/functions/sentinels.ts b/src/functions/sentinels.ts index ed29aee940..17a1a20f79 100644 --- a/src/functions/sentinels.ts +++ b/src/functions/sentinels.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { StateKV } from "../state/kv.js"; import { KV, generateId } from "../state/schema.js"; import { withKeyedLock } from "../state/keyed-mutex.js"; @@ -14,7 +14,7 @@ const VALID_TYPES: Sentinel["type"][] = [ "custom", ]; -export function registerSentinelsFunction(sdk: ISdk, kv: StateKV): void { +export function registerSentinelsFunction(sdk: IIIClient, kv: StateKV): void { sdk.registerFunction("mem::sentinel-create", async (data: { name: string; diff --git a/src/functions/signals.ts b/src/functions/signals.ts index 6abf746c77..f98829ecb8 100644 --- a/src/functions/signals.ts +++ b/src/functions/signals.ts @@ -1,10 +1,10 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { StateKV } from "../state/kv.js"; import { KV, generateId } from "../state/schema.js"; import type { Signal } from "../types.js"; import { recordAudit } from "./audit.js"; -export function registerSignalsFunction(sdk: ISdk, kv: StateKV): void { +export function registerSignalsFunction(sdk: IIIClient, kv: StateKV): void { sdk.registerFunction("mem::signal-send", async (data: { from: string; diff --git a/src/functions/sketches.ts b/src/functions/sketches.ts index c617a29817..0ef329f4b6 100644 --- a/src/functions/sketches.ts +++ b/src/functions/sketches.ts @@ -1,11 +1,11 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { StateKV } from "../state/kv.js"; import { KV, generateId } from "../state/schema.js"; import { withKeyedLock } from "../state/keyed-mutex.js"; import type { Action, ActionEdge, Sketch } from "../types.js"; import { safeAudit } from "./audit.js"; -export function registerSketchesFunction(sdk: ISdk, kv: StateKV): void { +export function registerSketchesFunction(sdk: IIIClient, kv: StateKV): void { sdk.registerFunction("mem::sketch-create", async (data: { title: string; diff --git a/src/functions/skill-extract.ts b/src/functions/skill-extract.ts index d3bbbd378c..fd9dcd26af 100644 --- a/src/functions/skill-extract.ts +++ b/src/functions/skill-extract.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { CompressedObservation, SessionSummary, @@ -101,7 +101,7 @@ function parseSkillXml( } export function registerSkillExtractFunctions( - sdk: ISdk, + sdk: IIIClient, kv: StateKV, provider: MemoryProvider, ): void { diff --git a/src/functions/sliding-window.ts b/src/functions/sliding-window.ts index 1de03dfc10..b7cf8c48ca 100644 --- a/src/functions/sliding-window.ts +++ b/src/functions/sliding-window.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { CompressedObservation, EnrichedChunk, @@ -114,7 +114,7 @@ function parseEnrichedXml(xml: string): { } export function registerSlidingWindowFunction( - sdk: ISdk, + sdk: IIIClient, kv: StateKV, provider: MemoryProvider, ): void { diff --git a/src/functions/slots.ts b/src/functions/slots.ts index 47b49d496f..70b14e9ba0 100644 --- a/src/functions/slots.ts +++ b/src/functions/slots.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { MemorySlot, CompressedObservation } from "../types.js"; import { KV } from "../state/schema.js"; import { StateKV } from "../state/kv.js"; @@ -193,7 +193,7 @@ export function renderPinnedContext(slots: MemorySlot[]): string { return lines.join("\n"); } -export function registerSlotsFunctions(sdk: ISdk, kv: StateKV): void { +export function registerSlotsFunctions(sdk: IIIClient, kv: StateKV): void { void seedDefaults(kv).catch((err) => { logger.warn("slot defaults seed failed", { error: err instanceof Error ? err.message : String(err), diff --git a/src/functions/smart-search.ts b/src/functions/smart-search.ts index 5d0147d9e0..1db87ff4fe 100644 --- a/src/functions/smart-search.ts +++ b/src/functions/smart-search.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { CompactLessonResult, CompactSearchResult, @@ -73,7 +73,7 @@ export function resetFollowupStatsForTests(): void { const LESSON_CONTENT_PREVIEW_CHARS = 240; export function registerSmartSearchFunction( - sdk: ISdk, + sdk: IIIClient, kv: StateKV, searchFn: (query: string, limit: number) => Promise, ): void { @@ -288,7 +288,7 @@ export function registerSmartSearchFunction( } async function recallLessons( - sdk: ISdk, + sdk: IIIClient, query: string, limit: number, project?: string, diff --git a/src/functions/snapshot.ts b/src/functions/snapshot.ts index 99c45c061f..483240e14d 100644 --- a/src/functions/snapshot.ts +++ b/src/functions/snapshot.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import { execFile } from "node:child_process"; import { promisify } from "node:util"; import { existsSync, mkdirSync, writeFileSync, readFileSync } from "node:fs"; @@ -37,7 +37,7 @@ async function ensureGitRepo(dir: string): Promise { } export function registerSnapshotFunction( - sdk: ISdk, + sdk: IIIClient, kv: StateKV, snapshotDir: string, ): void { diff --git a/src/functions/summarize.ts b/src/functions/summarize.ts index 4c501ca8cf..b3ade48d1b 100644 --- a/src/functions/summarize.ts +++ b/src/functions/summarize.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { CompressedObservation, SessionSummary, @@ -227,7 +227,7 @@ function parseSummaryXml( } export function registerSummarizeFunction( - sdk: ISdk, + sdk: IIIClient, kv: StateKV, provider: MemoryProvider, metricsStore?: MetricsStore, diff --git a/src/functions/team.ts b/src/functions/team.ts index a6461fe61d..532e8b284e 100644 --- a/src/functions/team.ts +++ b/src/functions/team.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { TeamConfig, TeamSharedItem, @@ -13,7 +13,7 @@ import { logger } from "../logger.js"; const VALID_ITEM_TYPES = new Set(["memory", "pattern", "observation"]); export function registerTeamFunction( - sdk: ISdk, + sdk: IIIClient, kv: StateKV, config: TeamConfig, ): void { diff --git a/src/functions/temporal-graph.ts b/src/functions/temporal-graph.ts index 1e8d1df100..aed6730b5f 100644 --- a/src/functions/temporal-graph.ts +++ b/src/functions/temporal-graph.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { GraphNode, GraphEdge, @@ -150,7 +150,7 @@ function parseTemporalGraphXml( } export function registerTemporalGraphFunctions( - sdk: ISdk, + sdk: IIIClient, kv: StateKV, provider: MemoryProvider, ): void { diff --git a/src/functions/timeline.ts b/src/functions/timeline.ts index e2244fe118..2d83876aef 100644 --- a/src/functions/timeline.ts +++ b/src/functions/timeline.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { CompressedObservation, Session, @@ -9,7 +9,7 @@ import { StateKV } from "../state/kv.js"; import { recordAccessBatch } from "./access-tracker.js"; import { logger } from "../logger.js"; -export function registerTimelineFunction(sdk: ISdk, kv: StateKV): void { +export function registerTimelineFunction(sdk: IIIClient, kv: StateKV): void { sdk.registerFunction("mem::timeline", async (data: { anchor: string; diff --git a/src/functions/verify.ts b/src/functions/verify.ts index a6e393f613..398b8f622f 100644 --- a/src/functions/verify.ts +++ b/src/functions/verify.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { StateKV } from "../state/kv.js"; import { KV } from "../state/schema.js"; import type { @@ -7,7 +7,7 @@ import type { Session, } from "../types.js"; -export function registerVerifyFunction(sdk: ISdk, kv: StateKV): void { +export function registerVerifyFunction(sdk: IIIClient, kv: StateKV): void { sdk.registerFunction("mem::verify", async (data: { id: string }) => { if (!data.id || typeof data.id !== "string") { diff --git a/src/functions/vision-search.ts b/src/functions/vision-search.ts index 844ec9d5eb..bc31f6a7b3 100644 --- a/src/functions/vision-search.ts +++ b/src/functions/vision-search.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { EmbeddingProvider } from "../types.js"; import { KV } from "../state/schema.js"; import { StateKV } from "../state/kv.js"; @@ -17,7 +17,7 @@ interface StoredEmbedding { } export function registerVisionSearchFunctions( - sdk: ISdk, + sdk: IIIClient, kv: StateKV, imageProvider: EmbeddingProvider | null, ): void { diff --git a/src/functions/working-memory.ts b/src/functions/working-memory.ts index 127195e526..125d5bd84e 100644 --- a/src/functions/working-memory.ts +++ b/src/functions/working-memory.ts @@ -1,4 +1,4 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { Memory, CompressedObservation, ContextBlock } from "../types.js"; import { KV, generateId } from "../state/schema.js"; import { StateKV } from "../state/kv.js"; @@ -32,7 +32,7 @@ function scoreEntry(entry: CoreMemoryEntry, now: number): number { } export function registerWorkingMemoryFunctions( - sdk: ISdk, + sdk: IIIClient, kv: StateKV, tokenBudget: number, ): void { diff --git a/src/health/monitor.ts b/src/health/monitor.ts index 953c94a0f4..633c28b2b2 100644 --- a/src/health/monitor.ts +++ b/src/health/monitor.ts @@ -1,11 +1,11 @@ -import type { ISdk } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; import type { HealthSnapshot } from "../types.js"; import type { StateKV } from "../state/kv.js"; import { KV } from "../state/schema.js"; import { evaluateHealth } from "./thresholds.js"; export function registerHealthMonitor( - sdk: ISdk, + sdk: IIIClient, kv: StateKV, ): { stop: () => void } { let connectionState = "connected"; diff --git a/src/mcp/server.ts b/src/mcp/server.ts index ef26427aaf..75e6ba5401 100644 --- a/src/mcp/server.ts +++ b/src/mcp/server.ts @@ -1,4 +1,5 @@ -import type { ISdk, ApiRequest } from "iii-sdk"; +import type { IIIClient } from "iii-sdk"; +import type { HttpRequest } from "@iii-dev/helpers/http"; import type { StateKV } from "../state/kv.js"; import { KV } from "../state/schema.js"; import type { @@ -41,12 +42,12 @@ function parseCsvList(value: unknown): string[] { } export function registerMcpEndpoints( - sdk: ISdk, + sdk: IIIClient, kv: StateKV, secret?: string, ): void { function checkAuth( - req: ApiRequest, + req: HttpRequest, sec: string | undefined, ): McpResponse | null { if (!sec) return null; @@ -59,7 +60,7 @@ export function registerMcpEndpoints( } sdk.registerFunction("mcp::tools::list", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; return { status_code: 200, body: { tools: getVisibleTools() } }; @@ -73,7 +74,7 @@ export function registerMcpEndpoints( sdk.registerFunction("mcp::tools::call", async ( - req: ApiRequest<{ name: string; arguments: Record }>, + req: HttpRequest<{ name: string; arguments: Record }>, ): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; @@ -1335,7 +1336,7 @@ export function registerMcpEndpoints( ]; sdk.registerFunction("mcp::resources::list", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; return { status_code: 200, body: { resources: MCP_RESOURCES } }; @@ -1348,7 +1349,7 @@ export function registerMcpEndpoints( }); sdk.registerFunction("mcp::resources::read", - async (req: ApiRequest<{ uri: string }>): Promise => { + async (req: HttpRequest<{ uri: string }>): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; @@ -1621,7 +1622,7 @@ export function registerMcpEndpoints( ]; sdk.registerFunction("mcp::prompts::list", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; return { status_code: 200, body: { prompts: MCP_PROMPTS } }; @@ -1635,7 +1636,7 @@ export function registerMcpEndpoints( sdk.registerFunction("mcp::prompts::get", async ( - req: ApiRequest<{ name: string; arguments?: Record }>, + req: HttpRequest<{ name: string; arguments?: Record }>, ): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; diff --git a/src/state/kv.ts b/src/state/kv.ts index 0c0e6ccc12..a8a1707ac9 100644 --- a/src/state/kv.ts +++ b/src/state/kv.ts @@ -1,7 +1,7 @@ -import type { ISdk } from 'iii-sdk' +import type { IIIClient } from 'iii-sdk' export class StateKV { - constructor(private sdk: ISdk) {} + constructor(private sdk: IIIClient) {} async get(scope: string, key: string): Promise { return this.sdk.trigger<{ scope: string; key: string }, T | null>({ diff --git a/src/triggers/api.ts b/src/triggers/api.ts index 56fad4f0de..9130381f14 100644 --- a/src/triggers/api.ts +++ b/src/triggers/api.ts @@ -1,4 +1,5 @@ -import { TriggerAction, type ISdk, type ApiRequest } from "iii-sdk"; +import { TriggerAction, type IIIClient } from "iii-sdk"; +import type { HttpRequest } from "@iii-dev/helpers/http"; import type { Session, CompressedObservation, HookPayload, CommitLink, SessionSummary } from "../types.js"; import { withKeyedLock } from "../state/keyed-mutex.js"; import { KV } from "../state/schema.js"; @@ -39,7 +40,7 @@ function parseOptionalInt(raw: unknown): number | undefined { } function checkAuth( - req: ApiRequest, + req: HttpRequest, secret: string | undefined, ): Response | null { if (!secret) return null; @@ -138,7 +139,7 @@ function parseOptionalPositiveInt(value: unknown): number | undefined | null { } export function registerApiTriggers( - sdk: ISdk, + sdk: IIIClient, kv: StateKV, secret?: string, metricsStore?: MetricsStore, @@ -191,7 +192,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::config-flags", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; const providerKind = detectLlmProviderKind(); @@ -264,7 +265,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::health", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const health = await getLatestHealth(kv); const functionMetrics = metricsStore ? await metricsStore.getAll() : []; const circuitBreaker = @@ -298,7 +299,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::observe", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const body = (req.body ?? {}) as Record; const hookType = asNonEmptyString(body.hookType); const sessionId = asNonEmptyString(body.sessionId); @@ -338,7 +339,7 @@ export function registerApiTriggers( sdk.registerFunction("api::context", async ( - req: ApiRequest<{ + req: HttpRequest<{ sessionId: string; project: string; budget?: number; @@ -402,7 +403,7 @@ export function registerApiTriggers( sdk.registerFunction("api::search", async ( - req: ApiRequest<{ + req: HttpRequest<{ query: string; limit?: number; project?: string; @@ -488,7 +489,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::compress-file", - async (req: ApiRequest<{ filePath: string }>): Promise => { + async (req: HttpRequest<{ filePath: string }>): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; const body = (req.body ?? {}) as Record; @@ -513,7 +514,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::replay::load", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; const sessionId = asNonEmptyString(req.query_params?.["sessionId"]); @@ -534,7 +535,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::replay::sessions", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; const sessions = await kv.list(KV.sessions); @@ -552,7 +553,7 @@ export function registerApiTriggers( sdk.registerFunction("api::replay::import", async ( - req: ApiRequest<{ path?: string; maxFiles?: number }>, + req: HttpRequest<{ path?: string; maxFiles?: number }>, ): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; @@ -598,7 +599,7 @@ export function registerApiTriggers( sdk.registerFunction("api::session::start", async ( - req: ApiRequest<{ sessionId: string; project: string; cwd: string }>, + req: HttpRequest<{ sessionId: string; project: string; cwd: string }>, ): Promise => { const body = (req.body ?? {}) as Record; const sessionId = asNonEmptyString(body.sessionId); @@ -657,7 +658,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::session::end", - async (req: ApiRequest<{ sessionId: string }>): Promise => { + async (req: HttpRequest<{ sessionId: string }>): Promise => { const sessionId = asNonEmptyString((req.body as Record)?.sessionId); if (!sessionId) { return { @@ -696,7 +697,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::summarize", - async (req: ApiRequest<{ sessionId: string }>): Promise => { + async (req: HttpRequest<{ sessionId: string }>): Promise => { const sessionId = asNonEmptyString((req.body as Record)?.sessionId); if (!sessionId) { return { status_code: 400, body: { error: "sessionId is required" } }; @@ -719,7 +720,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::session::commit", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const body = (req.body ?? {}) as Record; const sha = asNonEmptyString(body.sha); if (!sha) { @@ -785,7 +786,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::session::by-commit", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; const sha = asNonEmptyString(req.query_params?.["sha"]); @@ -820,7 +821,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::commits", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; const branch = asNonEmptyString(req.query_params?.["branch"]); @@ -847,7 +848,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::sessions", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; const sessions = await kv.list(KV.sessions); @@ -893,7 +894,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::observations", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; const sessionId = asNonEmptyString(req.query_params?.["sessionId"]); @@ -927,7 +928,7 @@ export function registerApiTriggers( sdk.registerFunction("api::file-context", async ( - req: ApiRequest<{ sessionId: string; files: string[] }>, + req: HttpRequest<{ sessionId: string; files: string[] }>, ): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; @@ -943,7 +944,7 @@ export function registerApiTriggers( sdk.registerFunction("api::enrich", async ( - req: ApiRequest<{ + req: HttpRequest<{ sessionId: string; files: string[]; terms?: string[]; @@ -1007,7 +1008,7 @@ export function registerApiTriggers( sdk.registerFunction("api::remember", async ( - req: ApiRequest<{ + req: HttpRequest<{ content: string; type?: string; concepts?: string[]; @@ -1059,7 +1060,7 @@ export function registerApiTriggers( sdk.registerFunction("api::forget", async ( - req: ApiRequest<{ + req: HttpRequest<{ sessionId?: string; observationIds?: string[]; memoryId?: string; @@ -1085,7 +1086,7 @@ export function registerApiTriggers( sdk.registerFunction("api::consolidate", async ( - req: ApiRequest<{ project?: string; minObservations?: number }>, + req: HttpRequest<{ project?: string; minObservations?: number }>, ): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; @@ -1100,7 +1101,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::patterns", - async (req: ApiRequest<{ project?: string }>): Promise => { + async (req: HttpRequest<{ project?: string }>): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; const result = await sdk.trigger({ function_id: "mem::patterns", payload: req.body }); @@ -1114,7 +1115,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::generate-rules", - async (req: ApiRequest<{ project?: string }>): Promise => { + async (req: HttpRequest<{ project?: string }>): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; const result = await sdk.trigger({ function_id: "mem::generate-rules", payload: req.body }); @@ -1129,7 +1130,7 @@ export function registerApiTriggers( sdk.registerFunction("api::migrate", async ( - req: ApiRequest<{ dbPath?: string; step?: string; dryRun?: boolean }>, + req: HttpRequest<{ dbPath?: string; step?: string; dryRun?: boolean }>, ): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; @@ -1161,7 +1162,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::evict", - async (req: ApiRequest<{ dryRun?: boolean }>): Promise => { + async (req: HttpRequest<{ dryRun?: boolean }>): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; const dryRun = @@ -1178,7 +1179,7 @@ export function registerApiTriggers( sdk.registerFunction("api::smart-search", async ( - req: ApiRequest<{ + req: HttpRequest<{ query?: string; expandIds?: Array; limit?: number; @@ -1234,7 +1235,7 @@ export function registerApiTriggers( // a directional signal — overcounts on legitimate query refinement — // so help text + the CLI status line carry the same caveat. sdk.registerFunction("api::diagnostic-followup", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; const result = await sdk.trigger({ @@ -1264,7 +1265,7 @@ export function registerApiTriggers( sdk.registerFunction("api::timeline", async ( - req: ApiRequest<{ + req: HttpRequest<{ anchor: string; project?: string; before?: number; @@ -1287,7 +1288,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::profile", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; const project = req.query_params["project"] as string; @@ -1308,7 +1309,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::export", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; // mem::export already supports maxSessions/offset internally, @@ -1342,7 +1343,7 @@ export function registerApiTriggers( sdk.registerFunction("api::import", async ( - req: ApiRequest<{ + req: HttpRequest<{ exportData: unknown; strategy?: "merge" | "replace" | "skip"; }>, @@ -1364,7 +1365,7 @@ export function registerApiTriggers( sdk.registerFunction("api::relations", async ( - req: ApiRequest<{ sourceId: string; targetId: string; type: string }>, + req: HttpRequest<{ sourceId: string; targetId: string; type: string }>, ): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; @@ -1386,7 +1387,7 @@ export function registerApiTriggers( sdk.registerFunction("api::evolve", async ( - req: ApiRequest<{ + req: HttpRequest<{ memoryId: string; newContent: string; newTitle?: string; @@ -1411,7 +1412,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::auto-forget", - async (req: ApiRequest<{ dryRun?: boolean }>): Promise => { + async (req: HttpRequest<{ dryRun?: boolean }>): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; const dryRun = @@ -1427,7 +1428,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::claude-bridge-read", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; try { @@ -1448,7 +1449,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::claude-bridge-sync", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; try { @@ -1473,7 +1474,7 @@ export function registerApiTriggers( sdk.registerFunction("api::graph-query", async ( - req: ApiRequest<{ + req: HttpRequest<{ startNodeId?: string; nodeType?: string; maxDepth?: number; @@ -1509,7 +1510,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::graph-stats", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; try { @@ -1532,7 +1533,7 @@ export function registerApiTriggers( // unbounded kv.list. Operator-grade endpoint exposed for the viewer // banner action and CLI repair. sdk.registerFunction("api::graph-snapshot-rebuild", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; try { @@ -1557,7 +1558,7 @@ export function registerApiTriggers( // recall + history stay intact while the graph rebuilds incrementally // from new extracts (or a one-shot /graph/build replay). sdk.registerFunction("api::graph-reset", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; try { @@ -1578,7 +1579,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::graph-extract", - async (req: ApiRequest<{ observations: unknown[] }>): Promise => { + async (req: HttpRequest<{ observations: unknown[] }>): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; if ( @@ -1609,7 +1610,7 @@ export function registerApiTriggers( // session, collects observations that have a `title` (compressed only), // and feeds them through `mem::graph-extract` in batches. sdk.registerFunction("api::graph-build", - async (req: ApiRequest<{ batchSize?: number }>): Promise => { + async (req: HttpRequest<{ batchSize?: number }>): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; const batchSize = Math.max( @@ -1673,7 +1674,7 @@ export function registerApiTriggers( // memory graph. Deterministic, no LLM call; idempotent via the graph // name-index upsert. sdk.registerFunction("api::graph-import-graphify", - async (req: ApiRequest<{ path?: string; cwd?: string }>): Promise => { + async (req: HttpRequest<{ path?: string; cwd?: string }>): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; const { path, cwd } = req.body ?? {}; @@ -1707,7 +1708,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::consolidate-pipeline", - async (req: ApiRequest<{ tier?: string }>): Promise => { + async (req: HttpRequest<{ tier?: string }>): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; try { @@ -1730,7 +1731,7 @@ export function registerApiTriggers( sdk.registerFunction("api::team-share", async ( - req: ApiRequest<{ itemId: string; itemType: string; project?: string }>, + req: HttpRequest<{ itemId: string; itemType: string; project?: string }>, ): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; @@ -1755,7 +1756,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::team-feed", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; try { @@ -1775,7 +1776,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::team-profile", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; try { @@ -1793,7 +1794,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::audit", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; const parsedLimit = parseOptionalInt(req.query_params?.["limit"]); @@ -1812,7 +1813,7 @@ export function registerApiTriggers( sdk.registerFunction("api::governance-delete", async ( - req: ApiRequest<{ memoryIds: string[]; reason?: string }>, + req: HttpRequest<{ memoryIds: string[]; reason?: string }>, ): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; @@ -1837,7 +1838,7 @@ export function registerApiTriggers( sdk.registerFunction("api::governance-bulk", async ( - req: ApiRequest<{ + req: HttpRequest<{ type?: string[]; dateFrom?: string; dateTo?: string; @@ -1861,7 +1862,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::snapshots", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; try { @@ -1879,7 +1880,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::snapshot-create", - async (req: ApiRequest<{ message?: string }>): Promise => { + async (req: HttpRequest<{ message?: string }>): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; try { @@ -1898,7 +1899,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::snapshot-restore", - async (req: ApiRequest<{ commitHash: string }>): Promise => { + async (req: HttpRequest<{ commitHash: string }>): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; if (!req.body?.commitHash) { @@ -1919,7 +1920,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::memories", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; const memories = await kv.list(KV.memories); @@ -2003,7 +2004,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::memory-by-id", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; const id = req.path_params?.["id"]; @@ -2024,7 +2025,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::semantic-list", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; const semantic = await kv.list(KV.semantic); @@ -2038,7 +2039,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::procedural-list", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; const procedural = await kv.list(KV.procedural); @@ -2052,7 +2053,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::relations-list", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; const relations = await kv.list(KV.relations); @@ -2066,7 +2067,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::vision-search", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; const body = (req.body ?? {}) as Record; @@ -2105,7 +2106,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::vision-embed", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; const body = (req.body ?? {}) as Record; @@ -2132,7 +2133,7 @@ export function registerApiTriggers( config: { api_path: "/agentmemory/vision-embed", http_method: "POST" }, }); - sdk.registerFunction("api::slot-list", async (req: ApiRequest): Promise => { + sdk.registerFunction("api::slot-list", async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; if (!isSlotsEnabled()) return slotsDisabledResponse(); @@ -2145,7 +2146,7 @@ export function registerApiTriggers( config: { api_path: "/agentmemory/slots", http_method: "GET" }, }); - sdk.registerFunction("api::slot-get", async (req: ApiRequest): Promise => { + sdk.registerFunction("api::slot-get", async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; if (!isSlotsEnabled()) return slotsDisabledResponse(); @@ -2164,7 +2165,7 @@ export function registerApiTriggers( config: { api_path: "/agentmemory/slot", http_method: "GET" }, }); - sdk.registerFunction("api::slot-create", async (req: ApiRequest): Promise => { + sdk.registerFunction("api::slot-create", async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; if (!isSlotsEnabled()) return slotsDisabledResponse(); @@ -2214,7 +2215,7 @@ export function registerApiTriggers( config: { api_path: "/agentmemory/slot", http_method: "POST" }, }); - sdk.registerFunction("api::slot-append", async (req: ApiRequest): Promise => { + sdk.registerFunction("api::slot-append", async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; if (!isSlotsEnabled()) return slotsDisabledResponse(); @@ -2237,7 +2238,7 @@ export function registerApiTriggers( config: { api_path: "/agentmemory/slot/append", http_method: "POST" }, }); - sdk.registerFunction("api::slot-replace", async (req: ApiRequest): Promise => { + sdk.registerFunction("api::slot-replace", async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; if (!isSlotsEnabled()) return slotsDisabledResponse(); @@ -2262,7 +2263,7 @@ export function registerApiTriggers( config: { api_path: "/agentmemory/slot/replace", http_method: "POST" }, }); - sdk.registerFunction("api::slot-delete", async (req: ApiRequest): Promise => { + sdk.registerFunction("api::slot-delete", async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; if (!isSlotsEnabled()) return slotsDisabledResponse(); @@ -2281,7 +2282,7 @@ export function registerApiTriggers( config: { api_path: "/agentmemory/slot", http_method: "DELETE" }, }); - sdk.registerFunction("api::slot-reflect", async (req: ApiRequest): Promise => { + sdk.registerFunction("api::slot-reflect", async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; if (!isSlotsEnabled()) return slotsDisabledResponse(); @@ -2304,7 +2305,7 @@ export function registerApiTriggers( sdk.registerFunction("api::action-create", async ( - req: ApiRequest<{ + req: HttpRequest<{ title: string; description?: string; priority?: number; @@ -2332,7 +2333,7 @@ export function registerApiTriggers( sdk.registerFunction("api::action-update", async ( - req: ApiRequest<{ + req: HttpRequest<{ actionId: string; status?: string; title?: string; @@ -2357,7 +2358,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::action-list", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; const result = await sdk.trigger({ function_id: "mem::action-list", payload: { @@ -2375,7 +2376,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::action-get", - async (req: ApiRequest<{ actionId: string }>): Promise => { + async (req: HttpRequest<{ actionId: string }>): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; const actionId = req.query_params?.["actionId"] as string; @@ -2394,7 +2395,7 @@ export function registerApiTriggers( sdk.registerFunction("api::action-edge", async ( - req: ApiRequest<{ + req: HttpRequest<{ sourceActionId: string; targetActionId: string; type: string; @@ -2416,7 +2417,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::frontier", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; const parsedLimit = parseOptionalInt(req.query_params?.["limit"]); @@ -2435,7 +2436,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::next", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; const result = await sdk.trigger({ function_id: "mem::next", payload: { @@ -2453,7 +2454,7 @@ export function registerApiTriggers( sdk.registerFunction("api::lease-acquire", async ( - req: ApiRequest<{ actionId: string; agentId: string; ttlMs?: number }>, + req: HttpRequest<{ actionId: string; agentId: string; ttlMs?: number }>, ): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; @@ -2472,7 +2473,7 @@ export function registerApiTriggers( sdk.registerFunction("api::lease-release", async ( - req: ApiRequest<{ actionId: string; agentId: string; result?: string }>, + req: HttpRequest<{ actionId: string; agentId: string; result?: string }>, ): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; @@ -2491,7 +2492,7 @@ export function registerApiTriggers( sdk.registerFunction("api::lease-renew", async ( - req: ApiRequest<{ actionId: string; agentId: string; ttlMs?: number }>, + req: HttpRequest<{ actionId: string; agentId: string; ttlMs?: number }>, ): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; @@ -2509,7 +2510,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::routine-create", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; if (!req.body?.name || !req.body?.steps) { @@ -2529,7 +2530,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::routine-list", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; const result = await sdk.trigger({ function_id: "mem::routine-list", payload: { @@ -2546,7 +2547,7 @@ export function registerApiTriggers( sdk.registerFunction("api::routine-run", async ( - req: ApiRequest<{ routineId: string; project?: string; initiatedBy?: string }>, + req: HttpRequest<{ routineId: string; project?: string; initiatedBy?: string }>, ): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; @@ -2564,7 +2565,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::routine-status", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; const runId = req.query_params?.["runId"] as string; @@ -2583,7 +2584,7 @@ export function registerApiTriggers( sdk.registerFunction("api::signal-send", async ( - req: ApiRequest<{ + req: HttpRequest<{ from: string; to?: string; content: string; @@ -2607,7 +2608,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::signal-read", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; const agentId = req.query_params?.["agentId"] as string; @@ -2632,7 +2633,7 @@ export function registerApiTriggers( sdk.registerFunction("api::checkpoint-create", async ( - req: ApiRequest<{ + req: HttpRequest<{ name: string; description?: string; type?: string; @@ -2657,7 +2658,7 @@ export function registerApiTriggers( sdk.registerFunction("api::checkpoint-resolve", async ( - req: ApiRequest<{ + req: HttpRequest<{ checkpointId: string; status: string; resolvedBy?: string; @@ -2680,7 +2681,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::checkpoint-list", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; const result = await sdk.trigger({ function_id: "mem::checkpoint-list", payload: { @@ -2698,7 +2699,7 @@ export function registerApiTriggers( sdk.registerFunction("api::mesh-register", async ( - req: ApiRequest<{ url: string; name: string; sharedScopes?: string[] }>, + req: HttpRequest<{ url: string; name: string; sharedScopes?: string[] }>, ): Promise => { const secretErr = requireConfiguredSecret(secret, "mesh"); if (secretErr) return secretErr; @@ -2718,7 +2719,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::mesh-list", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const secretErr = requireConfiguredSecret(secret, "mesh"); if (secretErr) return secretErr; const authErr = checkAuth(req, secret); @@ -2735,7 +2736,7 @@ export function registerApiTriggers( sdk.registerFunction("api::mesh-sync", async ( - req: ApiRequest<{ peerId?: string; direction?: string }>, + req: HttpRequest<{ peerId?: string; direction?: string }>, ): Promise => { const secretErr = requireConfiguredSecret(secret, "mesh"); if (secretErr) return secretErr; @@ -2752,7 +2753,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::mesh-receive", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const secretErr = requireConfiguredSecret(secret, "mesh"); if (secretErr) return secretErr; const authErr = checkAuth(req, secret); @@ -2768,7 +2769,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::mesh-export", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const secretErr = requireConfiguredSecret(secret, "mesh"); if (secretErr) return secretErr; const authErr = checkAuth(req, secret); @@ -2827,7 +2828,7 @@ export function registerApiTriggers( sdk.registerFunction("api::flow-compress", async ( - req: ApiRequest<{ + req: HttpRequest<{ runId?: string; actionIds?: string[]; project?: string; @@ -2853,7 +2854,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::branch-detect", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; const cwd = (req.query_params?.["cwd"] as string) || process.cwd(); @@ -2868,7 +2869,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::branch-worktrees", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; const cwd = (req.query_params?.["cwd"] as string) || process.cwd(); @@ -2883,7 +2884,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::branch-sessions", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; const cwd = (req.query_params?.["cwd"] as string) || process.cwd(); @@ -2898,7 +2899,7 @@ export function registerApiTriggers( }); sdk.registerFunction("api::viewer", - async (req: ApiRequest): Promise => { + async (req: HttpRequest): Promise => { const denied = checkAuth(req, secret); if (denied) return denied; const rendered = renderViewerDocument(); @@ -2927,7 +2928,7 @@ export function registerApiTriggers( config: { api_path: "/agentmemory/viewer", http_method: "GET" }, }); - sdk.registerFunction("api::sentinel-create", async (req: ApiRequest) => { + sdk.registerFunction("api::sentinel-create", async (req: HttpRequest) => { const denied = checkAuth(req, secret); if (denied) return denied; const body = req.body as Record; @@ -2937,7 +2938,7 @@ export function registerApiTriggers( }); sdk.registerTrigger({ type: "http", function_id: "api::sentinel-create", config: { api_path: "/agentmemory/sentinels", http_method: "POST" } }); - sdk.registerFunction("api::sentinel-trigger", async (req: ApiRequest) => { + sdk.registerFunction("api::sentinel-trigger", async (req: HttpRequest) => { const denied = checkAuth(req, secret); if (denied) return denied; const body = req.body as Record; @@ -2947,7 +2948,7 @@ export function registerApiTriggers( }); sdk.registerTrigger({ type: "http", function_id: "api::sentinel-trigger", config: { api_path: "/agentmemory/sentinels/trigger", http_method: "POST" } }); - sdk.registerFunction("api::sentinel-check", async (req: ApiRequest) => { + sdk.registerFunction("api::sentinel-check", async (req: HttpRequest) => { const denied = checkAuth(req, secret); if (denied) return denied; const result = await sdk.trigger({ function_id: "mem::sentinel-check", payload: {} }); @@ -2955,7 +2956,7 @@ export function registerApiTriggers( }); sdk.registerTrigger({ type: "http", function_id: "api::sentinel-check", config: { api_path: "/agentmemory/sentinels/check", http_method: "POST" } }); - sdk.registerFunction("api::sentinel-cancel", async (req: ApiRequest) => { + sdk.registerFunction("api::sentinel-cancel", async (req: HttpRequest) => { const denied = checkAuth(req, secret); if (denied) return denied; const body = req.body as Record; @@ -2965,7 +2966,7 @@ export function registerApiTriggers( }); sdk.registerTrigger({ type: "http", function_id: "api::sentinel-cancel", config: { api_path: "/agentmemory/sentinels/cancel", http_method: "POST" } }); - sdk.registerFunction("api::sentinel-list", async (req: ApiRequest) => { + sdk.registerFunction("api::sentinel-list", async (req: HttpRequest) => { const denied = checkAuth(req, secret); if (denied) return denied; const params = req.query_params || {}; @@ -2974,7 +2975,7 @@ export function registerApiTriggers( }); sdk.registerTrigger({ type: "http", function_id: "api::sentinel-list", config: { api_path: "/agentmemory/sentinels", http_method: "GET" } }); - sdk.registerFunction("api::sketch-create", async (req: ApiRequest) => { + sdk.registerFunction("api::sketch-create", async (req: HttpRequest) => { const denied = checkAuth(req, secret); if (denied) return denied; const body = req.body as Record; @@ -2984,7 +2985,7 @@ export function registerApiTriggers( }); sdk.registerTrigger({ type: "http", function_id: "api::sketch-create", config: { api_path: "/agentmemory/sketches", http_method: "POST" } }); - sdk.registerFunction("api::sketch-add", async (req: ApiRequest) => { + sdk.registerFunction("api::sketch-add", async (req: HttpRequest) => { const denied = checkAuth(req, secret); if (denied) return denied; const body = req.body as Record; @@ -2994,7 +2995,7 @@ export function registerApiTriggers( }); sdk.registerTrigger({ type: "http", function_id: "api::sketch-add", config: { api_path: "/agentmemory/sketches/add", http_method: "POST" } }); - sdk.registerFunction("api::sketch-promote", async (req: ApiRequest) => { + sdk.registerFunction("api::sketch-promote", async (req: HttpRequest) => { const denied = checkAuth(req, secret); if (denied) return denied; const body = req.body as Record; @@ -3004,7 +3005,7 @@ export function registerApiTriggers( }); sdk.registerTrigger({ type: "http", function_id: "api::sketch-promote", config: { api_path: "/agentmemory/sketches/promote", http_method: "POST" } }); - sdk.registerFunction("api::sketch-discard", async (req: ApiRequest) => { + sdk.registerFunction("api::sketch-discard", async (req: HttpRequest) => { const denied = checkAuth(req, secret); if (denied) return denied; const body = req.body as Record; @@ -3014,7 +3015,7 @@ export function registerApiTriggers( }); sdk.registerTrigger({ type: "http", function_id: "api::sketch-discard", config: { api_path: "/agentmemory/sketches/discard", http_method: "POST" } }); - sdk.registerFunction("api::sketch-list", async (req: ApiRequest) => { + sdk.registerFunction("api::sketch-list", async (req: HttpRequest) => { const denied = checkAuth(req, secret); if (denied) return denied; const params = req.query_params || {}; @@ -3023,7 +3024,7 @@ export function registerApiTriggers( }); sdk.registerTrigger({ type: "http", function_id: "api::sketch-list", config: { api_path: "/agentmemory/sketches", http_method: "GET" } }); - sdk.registerFunction("api::sketch-gc", async (req: ApiRequest) => { + sdk.registerFunction("api::sketch-gc", async (req: HttpRequest) => { const denied = checkAuth(req, secret); if (denied) return denied; const result = await sdk.trigger({ function_id: "mem::sketch-gc", payload: {} }); @@ -3031,7 +3032,7 @@ export function registerApiTriggers( }); sdk.registerTrigger({ type: "http", function_id: "api::sketch-gc", config: { api_path: "/agentmemory/sketches/gc", http_method: "POST" } }); - sdk.registerFunction("api::crystallize", async (req: ApiRequest) => { + sdk.registerFunction("api::crystallize", async (req: HttpRequest) => { const denied = checkAuth(req, secret); if (denied) return denied; const body = req.body as Record; @@ -3041,7 +3042,7 @@ export function registerApiTriggers( }); sdk.registerTrigger({ type: "http", function_id: "api::crystallize", config: { api_path: "/agentmemory/crystals/create", http_method: "POST" } }); - sdk.registerFunction("api::crystal-list", async (req: ApiRequest) => { + sdk.registerFunction("api::crystal-list", async (req: HttpRequest) => { const denied = checkAuth(req, secret); if (denied) return denied; const params = req.query_params || {}; @@ -3057,7 +3058,7 @@ export function registerApiTriggers( }); sdk.registerTrigger({ type: "http", function_id: "api::crystal-list", config: { api_path: "/agentmemory/crystals", http_method: "GET" } }); - sdk.registerFunction("api::auto-crystallize", async (req: ApiRequest) => { + sdk.registerFunction("api::auto-crystallize", async (req: HttpRequest) => { const denied = checkAuth(req, secret); if (denied) return denied; const body = req.body as Record; @@ -3066,7 +3067,7 @@ export function registerApiTriggers( }); sdk.registerTrigger({ type: "http", function_id: "api::auto-crystallize", config: { api_path: "/agentmemory/crystals/auto", http_method: "POST" } }); - sdk.registerFunction("api::diagnose", async (req: ApiRequest) => { + sdk.registerFunction("api::diagnose", async (req: HttpRequest) => { const denied = checkAuth(req, secret); if (denied) return denied; const body = req.body as Record; @@ -3075,7 +3076,7 @@ export function registerApiTriggers( }); sdk.registerTrigger({ type: "http", function_id: "api::diagnose", config: { api_path: "/agentmemory/diagnostics", http_method: "POST" } }); - sdk.registerFunction("api::heal", async (req: ApiRequest) => { + sdk.registerFunction("api::heal", async (req: HttpRequest) => { const denied = checkAuth(req, secret); if (denied) return denied; const body = req.body as Record; @@ -3084,7 +3085,7 @@ export function registerApiTriggers( }); sdk.registerTrigger({ type: "http", function_id: "api::heal", config: { api_path: "/agentmemory/diagnostics/heal", http_method: "POST" } }); - sdk.registerFunction("api::facet-tag", async (req: ApiRequest) => { + sdk.registerFunction("api::facet-tag", async (req: HttpRequest) => { const denied = checkAuth(req, secret); if (denied) return denied; const body = req.body as Record; @@ -3094,7 +3095,7 @@ export function registerApiTriggers( }); sdk.registerTrigger({ type: "http", function_id: "api::facet-tag", config: { api_path: "/agentmemory/facets", http_method: "POST" } }); - sdk.registerFunction("api::facet-untag", async (req: ApiRequest) => { + sdk.registerFunction("api::facet-untag", async (req: HttpRequest) => { const denied = checkAuth(req, secret); if (denied) return denied; const body = req.body as Record; @@ -3104,7 +3105,7 @@ export function registerApiTriggers( }); sdk.registerTrigger({ type: "http", function_id: "api::facet-untag", config: { api_path: "/agentmemory/facets/remove", http_method: "POST" } }); - sdk.registerFunction("api::facet-query", async (req: ApiRequest) => { + sdk.registerFunction("api::facet-query", async (req: HttpRequest) => { const denied = checkAuth(req, secret); if (denied) return denied; const body = req.body as Record; @@ -3113,7 +3114,7 @@ export function registerApiTriggers( }); sdk.registerTrigger({ type: "http", function_id: "api::facet-query", config: { api_path: "/agentmemory/facets/query", http_method: "POST" } }); - sdk.registerFunction("api::facet-get", async (req: ApiRequest) => { + sdk.registerFunction("api::facet-get", async (req: HttpRequest) => { const denied = checkAuth(req, secret); if (denied) return denied; const params = req.query_params || {}; @@ -3123,7 +3124,7 @@ export function registerApiTriggers( }); sdk.registerTrigger({ type: "http", function_id: "api::facet-get", config: { api_path: "/agentmemory/facets", http_method: "GET" } }); - sdk.registerFunction("api::facet-stats", async (req: ApiRequest) => { + sdk.registerFunction("api::facet-stats", async (req: HttpRequest) => { const denied = checkAuth(req, secret); if (denied) return denied; const params = req.query_params || {}; @@ -3132,7 +3133,7 @@ export function registerApiTriggers( }); sdk.registerTrigger({ type: "http", function_id: "api::facet-stats", config: { api_path: "/agentmemory/facets/stats", http_method: "GET" } }); - sdk.registerFunction("api::verify", async (req: ApiRequest) => { + sdk.registerFunction("api::verify", async (req: HttpRequest) => { const denied = checkAuth(req, secret); if (denied) return denied; const body = req.body as Record; @@ -3142,7 +3143,7 @@ export function registerApiTriggers( }); sdk.registerTrigger({ type: "http", function_id: "api::verify", config: { api_path: "/agentmemory/verify", http_method: "POST" } }); - sdk.registerFunction("api::cascade-update", async (req: ApiRequest) => { + sdk.registerFunction("api::cascade-update", async (req: HttpRequest) => { const denied = checkAuth(req, secret); if (denied) return denied; const body = req.body as Record; @@ -3154,7 +3155,7 @@ export function registerApiTriggers( }); sdk.registerTrigger({ type: "http", function_id: "api::cascade-update", config: { api_path: "/agentmemory/cascade-update", http_method: "POST" } }); - sdk.registerFunction("api::lesson-save", async (req: ApiRequest) => { + sdk.registerFunction("api::lesson-save", async (req: HttpRequest) => { const denied = checkAuth(req, secret); if (denied) return denied; const body = req.body as Record; @@ -3176,7 +3177,7 @@ export function registerApiTriggers( }); sdk.registerTrigger({ type: "http", function_id: "api::lesson-save", config: { api_path: "/agentmemory/lessons", http_method: "POST" } }); - sdk.registerFunction("api::lesson-list", async (req: ApiRequest) => { + sdk.registerFunction("api::lesson-list", async (req: HttpRequest) => { const denied = checkAuth(req, secret); if (denied) return denied; const params = req.query_params || {}; @@ -3204,7 +3205,7 @@ export function registerApiTriggers( }); sdk.registerTrigger({ type: "http", function_id: "api::lesson-list", config: { api_path: "/agentmemory/lessons", http_method: "GET" } }); - sdk.registerFunction("api::lesson-search", async (req: ApiRequest) => { + sdk.registerFunction("api::lesson-search", async (req: HttpRequest) => { const denied = checkAuth(req, secret); if (denied) return denied; const body = req.body as Record; @@ -3214,7 +3215,7 @@ export function registerApiTriggers( }); sdk.registerTrigger({ type: "http", function_id: "api::lesson-search", config: { api_path: "/agentmemory/lessons/search", http_method: "POST" } }); - sdk.registerFunction("api::lesson-strengthen", async (req: ApiRequest) => { + sdk.registerFunction("api::lesson-strengthen", async (req: HttpRequest) => { const denied = checkAuth(req, secret); if (denied) return denied; const body = req.body as Record; @@ -3224,7 +3225,7 @@ export function registerApiTriggers( }); sdk.registerTrigger({ type: "http", function_id: "api::lesson-strengthen", config: { api_path: "/agentmemory/lessons/strengthen", http_method: "POST" } }); - sdk.registerFunction("api::lesson-delete", async (req: ApiRequest) => { + sdk.registerFunction("api::lesson-delete", async (req: HttpRequest) => { const denied = checkAuth(req, secret); if (denied) return denied; const body = req.body as Record; @@ -3239,7 +3240,7 @@ export function registerApiTriggers( }); sdk.registerTrigger({ type: "http", function_id: "api::lesson-delete", config: { api_path: "/agentmemory/lessons/delete", http_method: "POST" } }); - sdk.registerFunction("api::obsidian-export", async (req: ApiRequest) => { + sdk.registerFunction("api::obsidian-export", async (req: HttpRequest) => { const denied = checkAuth(req, secret); if (denied) return denied; const body = (req.body as Record) || {}; @@ -3256,7 +3257,7 @@ export function registerApiTriggers( }); sdk.registerTrigger({ type: "http", function_id: "api::obsidian-export", config: { api_path: "/agentmemory/obsidian/export", http_method: "POST" } }); - sdk.registerFunction("api::reflect", async (req: ApiRequest) => { + sdk.registerFunction("api::reflect", async (req: HttpRequest) => { const denied = checkAuth(req, secret); if (denied) return denied; const body = (req.body as Record) || {}; @@ -3268,7 +3269,7 @@ export function registerApiTriggers( }); sdk.registerTrigger({ type: "http", function_id: "api::reflect", config: { api_path: "/agentmemory/reflect", http_method: "POST" } }); - sdk.registerFunction("api::insight-list", async (req: ApiRequest) => { + sdk.registerFunction("api::insight-list", async (req: HttpRequest) => { const denied = checkAuth(req, secret); if (denied) return denied; const params = req.query_params || {}; @@ -3295,7 +3296,7 @@ export function registerApiTriggers( }); sdk.registerTrigger({ type: "http", function_id: "api::insight-list", config: { api_path: "/agentmemory/insights", http_method: "GET" } }); - sdk.registerFunction("api::insight-search", async (req: ApiRequest) => { + sdk.registerFunction("api::insight-search", async (req: HttpRequest) => { const denied = checkAuth(req, secret); if (denied) return denied; const body = req.body as Record; diff --git a/src/triggers/events.ts b/src/triggers/events.ts index bbf15db33f..3ce2d4bea7 100644 --- a/src/triggers/events.ts +++ b/src/triggers/events.ts @@ -1,4 +1,4 @@ -import { TriggerAction, type ISdk } from "iii-sdk"; +import { TriggerAction, type IIIClient } from "iii-sdk"; import type { CompressedObservation, HookPayload, Session } from "../types.js"; import { KV, STREAM } from "../state/schema.js"; import { StateKV } from "../state/kv.js"; @@ -40,7 +40,7 @@ function consolidationDue(kv: StateKV): Promise { return result; } -export function registerEventTriggers(sdk: ISdk, kv: StateKV): void { +export function registerEventTriggers(sdk: IIIClient, kv: StateKV): void { sdk.registerFunction( "event::session::started", async (data: { diff --git a/test/cli-console.test.ts b/test/cli-console.test.ts new file mode 100644 index 0000000000..451d39530c --- /dev/null +++ b/test/cli-console.test.ts @@ -0,0 +1,60 @@ +import { describe, expect, it } from "vitest"; +import { + consoleArgs, + defaultConsolePort, + parseConsoleArgs, +} from "../src/cli/console.js"; + +describe("agentmemory console", () => { + it("serves one port above the viewer so the two never collide", () => { + expect(defaultConsolePort(3113)).toBe(3114); + expect(defaultConsolePort(3213)).toBe(3214); + }); + + it("builds the pinned engine's console invocation against the resolved port quartet", () => { + expect( + consoleArgs({ + iiiBin: "/home/u/.agentmemory/bin/iii", + consolePort: 3114, + restPort: 3111, + streamPort: 3112, + enginePort: 49134, + extraArgs: ["--enable-flow"], + }), + ).toEqual([ + "console", + "--port", + "3114", + "--engine-port", + "3111", + "--ws-port", + "3112", + "--bridge-port", + "49134", + "--enable-flow", + ]); + }); + + it("takes --console-port in both spellings and falls back to the default", () => { + expect(parseConsoleArgs([], 3114)).toEqual({ consolePort: 3114, extraArgs: [] }); + expect(parseConsoleArgs(["--console-port", "4000"], 3114).consolePort).toBe(4000); + expect(parseConsoleArgs(["--console-port=4001"], 3114).consolePort).toBe(4001); + }); + + it("drops the CLI's own global flags and forwards everything else to iii console", () => { + const parsed = parseConsoleArgs( + ["--port", "3211", "--instance=1", "--verbose", "--enable-flow", "--host", "0.0.0.0"], + 3214, + ); + + expect(parsed).toEqual({ + consolePort: 3214, + extraArgs: ["--enable-flow", "--host", "0.0.0.0"], + }); + }); + + it("rejects an unusable console port", () => { + expect(() => parseConsoleArgs(["--console-port", "70000"], 3114)).toThrow(/between 1 and 65535/); + expect(() => parseConsoleArgs(["--console-port"], 3114)).toThrow(/--console-port/); + }); +}); diff --git a/test/context-lessons.test.ts b/test/context-lessons.test.ts index 92fcbce72b..32f26a1e0b 100644 --- a/test/context-lessons.test.ts +++ b/test/context-lessons.test.ts @@ -36,7 +36,7 @@ function wireContext(kv: ReturnType, budget = 4000) { registerFunction: vi.fn((id: string, cb: ContextHandler) => { if (id === "mem::context") handler = cb; }), - } as unknown as import("iii-sdk").ISdk; + } as unknown as import("iii-sdk").IIIClient; registerContextFunction(sdk, kv as never, budget); if (!handler) throw new Error("mem::context not registered"); return handler; diff --git a/test/context-slots.test.ts b/test/context-slots.test.ts index 808597c4c7..a6785d914b 100644 --- a/test/context-slots.test.ts +++ b/test/context-slots.test.ts @@ -35,7 +35,7 @@ function wireContext(kv: ReturnType) { registerFunction: vi.fn((id: string, cb: ContextHandler) => { if (id === "mem::context") handler = cb; }), - } as unknown as import("iii-sdk").ISdk; + } as unknown as import("iii-sdk").IIIClient; registerContextFunction(sdk, kv as never, 2000); if (!handler) throw new Error("mem::context not registered"); return handler; diff --git a/test/docker-port-config.test.ts b/test/docker-port-config.test.ts index 2bcc55b62a..f5e87b81a6 100644 --- a/test/docker-port-config.test.ts +++ b/test/docker-port-config.test.ts @@ -41,6 +41,7 @@ describe("Docker engine port configuration", () => { 'user: "${AGENTMEMORY_DOCKER_UID:-65532}:${AGENTMEMORY_DOCKER_GID:-65532}"', ); expect(compose).toContain("AGENTMEMORY_DOCKER_SKIP_CHOWN"); + expect(compose).toContain("target: /app/config"); }); it("configures every iii listener from the same environment", () => { @@ -50,6 +51,12 @@ describe("Docker engine port configuration", () => { const manager = workerBlock("iii-worker-manager"); expect(manager).toContain("port: ${III_ENGINE_PORT:49134}"); expect(manager).toContain("host: 0.0.0.0"); + expect(engineConfig).not.toMatch(/- name: (http|state|pubsub|cron|queue)$/m); + }); + + it("starts the pinned engine without update checks and with usage telemetry off by default", () => { + expect(compose).toContain('command: ["--config", "/app/config.yaml", "--no-update-check"]'); + expect(compose).toContain('III_TELEMETRY_ENABLED: "${III_TELEMETRY_ENABLED:-false}"'); }); it("leaves worker ownership to the host CLI", () => { diff --git a/test/engine-child-env.test.ts b/test/engine-child-env.test.ts new file mode 100644 index 0000000000..bdbb67d0ae --- /dev/null +++ b/test/engine-child-env.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from "vitest"; +import { engineChildEnv } from "../src/cli/engine-launch.js"; + +describe("engineChildEnv", () => { + it("turns the engine's anonymous usage telemetry off when the user has not chosen", () => { + const env = engineChildEnv({ PATH: "/usr/bin" }); + + expect(env["III_TELEMETRY_ENABLED"]).toBe("false"); + expect(env["PATH"]).toBe("/usr/bin"); + }); + + it("keeps an explicit opt-in or opt-out", () => { + expect(engineChildEnv({ III_TELEMETRY_ENABLED: "true" })["III_TELEMETRY_ENABLED"]).toBe("true"); + expect(engineChildEnv({ III_TELEMETRY_ENABLED: "false" })["III_TELEMETRY_ENABLED"]).toBe("false"); + }); +}); diff --git a/test/engine-config.test.ts b/test/engine-config.test.ts index 43ab278373..59919a72cc 100644 --- a/test/engine-config.test.ts +++ b/test/engine-config.test.ts @@ -72,76 +72,141 @@ describe("renderEngineConfig", () => { /- name: iii-worker-manager\n\s+config:\n\s+port: 49234\n\s+host: 127\.0\.0\.1/, ); }); + + it("keeps the iii- prefixed builtin names: on 0.22.1 the unprefixed names resolve to registry workers", () => { + const source = readFileSync( + join(import.meta.dirname, "..", "iii-config.yaml"), + "utf8", + ); + const names = [...source.matchAll(/^\s*- name: (\S+)$/gm)].map((m) => m[1]); + + expect(names).toEqual( + expect.arrayContaining([ + "iii-http", + "iii-state", + "iii-pubsub", + "iii-cron", + "iii-queue", + "iii-stream", + "iii-observability", + ]), + ); + for (const bare of ["http", "state", "pubsub", "cron", "queue"]) { + expect(names).not.toContain(bare); + } + }); }); describe("clearPersistedBuiltinConfig", () => { - it("lists one persisted entry per seeded builtin under data/configuration", () => { - const paths = persistedBuiltinConfigPaths("/srv/engine"); + const configPath = join("/srv", "state", "iii-config.runtime.yaml"); + it("covers the engine cwd, the config file directory and the legacy 0.19 location", () => { + expect(persistedBuiltinConfigDirs("/srv/engine", configPath)).toEqual([ + join("/srv", "engine", "config"), + join("/srv", "state", "config"), + join("/srv", "engine", "data", "configuration"), + ]); + }); + + it("lists both the unprefixed and the legacy entry name for every seeded builtin", () => { + const paths = persistedBuiltinConfigPaths("/srv/engine", configPath); + + expect(paths).toContain(join("/srv", "state", "config", "http.yaml")); + expect(paths).toContain(join("/srv", "state", "config", "iii-http.yaml")); + expect(paths).toContain(join("/srv", "state", "config", "iii-worker-manager.yaml")); expect(paths).toContain( - join("/srv/engine", "data", "configuration", "iii-http.yaml"), - ); - expect(paths).toContain( - join("/srv/engine", "data", "configuration", "iii-worker-manager.yaml"), + join("/srv", "engine", "data", "configuration", "iii-http.yaml"), ); expect(paths.every((p) => p.endsWith(".yaml"))).toBe(true); }); it("adds the directory a configuration worker entry names, resolved against the engine cwd", () => { - expect(persistedBuiltinConfigDirs("/srv/engine", customDirConfig)).toEqual([ + expect(persistedBuiltinConfigDirs("/srv/engine", configPath, customDirConfig)).toEqual([ join("/srv", "engine", "custom-cfg"), + join("/srv", "engine", "config"), + join("/srv", "state", "config"), join("/srv", "engine", "data", "configuration"), ]); expect( persistedBuiltinConfigDirs( "/srv/engine", + configPath, customDirConfig.replace("./custom-cfg", "'/var/lib/iii-cfg'"), )[0], ).toBe(join("/var", "lib", "iii-cfg")); expect( - persistedBuiltinConfigDirs("/srv/engine", "workers:\n - name: iii-http\n"), - ).toEqual([join("/srv", "engine", "data", "configuration")]); + persistedBuiltinConfigDirs("/srv/engine", configPath, "workers:\n - name: iii-http\n"), + ).toEqual(persistedBuiltinConfigDirs("/srv/engine", configPath)); }); - it("removes persisted builtin entries and leaves everything else in place", () => { + it("removes persisted builtin entries from both locations and leaves everything else in place", () => { const cwd = mkdtempSync(join(tmpdir(), "agentmemory-engine-")); - const dir = join(cwd, "data", "configuration"); + const dataDir = mkdtempSync(join(tmpdir(), "agentmemory-data-")); + const runtimeConfig = join(dataDir, "iii-config.runtime.yaml"); + const current = join(dataDir, "config"); + const legacy = join(cwd, "data", "configuration"); + mkdirSync(current, { recursive: true }); + mkdirSync(legacy, { recursive: true }); + writeFileSync(join(current, "http.yaml"), "id: http\nvalue:\n port: 3111\n"); + writeFileSync(join(current, "iii-state.yaml"), "id: iii-state\nvalue: {}\n"); + writeFileSync(join(current, "agentmemory.yaml"), "id: agentmemory\nvalue: {}\n"); + writeFileSync(join(legacy, "iii-http.yaml"), "id: iii-http\nvalue:\n port: 3111\n"); + + const cleared = clearPersistedBuiltinConfig(cwd, runtimeConfig); + + expect(cleared).toHaveLength(3); + expect(existsSync(join(current, "http.yaml"))).toBe(false); + expect(existsSync(join(current, "iii-state.yaml"))).toBe(false); + expect(existsSync(join(legacy, "iii-http.yaml"))).toBe(false); + expect(existsSync(join(current, "agentmemory.yaml"))).toBe(true); + }); + + it("removes the entries the engine persisted under a custom configuration directory", () => { + const cwd = mkdtempSync(join(tmpdir(), "agentmemory-engine-")); + const dir = join(cwd, "custom-cfg"); mkdirSync(dir, { recursive: true }); writeFileSync(join(dir, "iii-http.yaml"), "id: iii-http\nvalue:\n port: 3111\n"); - writeFileSync(join(dir, "iii-state.yaml"), "id: iii-state\nvalue: {}\n"); writeFileSync(join(dir, "agentmemory.yaml"), "id: agentmemory\nvalue: {}\n"); - const cleared = clearPersistedBuiltinConfig(cwd); + const cleared = clearPersistedBuiltinConfig( + cwd, + join(cwd, "iii-config.runtime.yaml"), + customDirConfig, + ); - expect(cleared).toHaveLength(2); - expect(existsSync(join(dir, "iii-http.yaml"))).toBe(false); - expect(existsSync(join(dir, "iii-state.yaml"))).toBe(false); + expect(cleared).toEqual([join(dir, "iii-http.yaml")]); expect(existsSync(join(dir, "agentmemory.yaml"))).toBe(true); }); - it("removes the entries the engine persisted under a custom configuration directory", () => { + it("leaves files that are not engine entries alone, even under a seeded builtin name", () => { const cwd = mkdtempSync(join(tmpdir(), "agentmemory-engine-")); - const dir = join(cwd, "custom-cfg"); + const dir = join(cwd, "config"); mkdirSync(dir, { recursive: true }); - writeFileSync(join(dir, "iii-http.yaml"), "id: iii-http\nvalue:\n port: 3111\n"); - writeFileSync(join(dir, "agentmemory.yaml"), "id: agentmemory\nvalue: {}\n"); + writeFileSync(join(dir, "http.yaml"), "host: 0.0.0.0\nport: 8080\n"); + writeFileSync(join(dir, "state.yaml"), "id: something-else\nvalue: {}\n"); + writeFileSync(join(dir, "iii-http.yaml"), "\nid: iii-http\nname: HTTP\nvalue:\n port: 3111\n"); - const cleared = clearPersistedBuiltinConfig(cwd, customDirConfig); + const cleared = clearPersistedBuiltinConfig(cwd, join(cwd, "iii-config.runtime.yaml")); expect(cleared).toEqual([join(dir, "iii-http.yaml")]); - expect(existsSync(join(dir, "agentmemory.yaml"))).toBe(true); + expect(existsSync(join(dir, "http.yaml"))).toBe(true); + expect(existsSync(join(dir, "state.yaml"))).toBe(true); }); it("is a no-op when the engine has never persisted anything", () => { const cwd = mkdtempSync(join(tmpdir(), "agentmemory-engine-")); - expect(clearPersistedBuiltinConfig(cwd)).toEqual([]); + expect( + clearPersistedBuiltinConfig(cwd, join(cwd, "iii-config.runtime.yaml")), + ).toEqual([]); }); it("fails loudly when a persisted entry exists but cannot be removed", () => { const cwd = mkdtempSync(join(tmpdir(), "agentmemory-engine-")); - mkdirSync(join(cwd, "data", "configuration", "iii-http.yaml"), { recursive: true }); + mkdirSync(join(cwd, "config", "http.yaml"), { recursive: true }); - expect(() => clearPersistedBuiltinConfig(cwd)).toThrow(/iii-http\.yaml/); + expect(() => + clearPersistedBuiltinConfig(cwd, join(cwd, "iii-config.runtime.yaml")), + ).toThrow(/http\.yaml/); }); }); diff --git a/test/slots.test.ts b/test/slots.test.ts index 70da2aed1f..31d320f01e 100644 --- a/test/slots.test.ts +++ b/test/slots.test.ts @@ -30,7 +30,7 @@ function wire() { registerFunction: vi.fn((id: string, cb) => { handlers[id] = cb; }), - } as unknown as import("iii-sdk").ISdk; + } as unknown as import("iii-sdk").IIIClient; registerSlotsFunctions(sdk, kv as never); return { kv, handlers }; } diff --git a/test/vision-search.test.ts b/test/vision-search.test.ts index 015b3e2b84..4c55cebdae 100644 --- a/test/vision-search.test.ts +++ b/test/vision-search.test.ts @@ -70,7 +70,7 @@ describe("vision-search", () => { registerFunction: vi.fn((id: string, cb) => { handlers[id] = cb; }), - } as unknown as import("iii-sdk").ISdk; + } as unknown as import("iii-sdk").IIIClient; registerVisionSearchFunctions(sdk, kv as never, fakeProvider); visionSearch = handlers["mem::vision-search"]!; visionEmbed = handlers["mem::vision-embed"]!; @@ -166,7 +166,7 @@ describe("vision-search", () => { registerFunction: vi.fn((id: string, cb) => { handlers[id] = cb; }), - } as unknown as import("iii-sdk").ISdk; + } as unknown as import("iii-sdk").IIIClient; registerVisionSearchFunctions(sdk, kv as never, null); const res = (await handlers["mem::vision-search"]!({ queryText: "login" })) as { success: boolean; From 20f26e4e1026d87125724f1ca430c8100464350c Mon Sep 17 00:00:00 2001 From: Rohit Ghumare <48523873+rohitg00@users.noreply.github.com> Date: Fri, 25 Sep 2026 08:54:40 +0530 Subject: [PATCH 04/57] feat(status): GET /agentmemory/status and a viewer Health tab (#1408) * feat(status): GET /agentmemory/status and a viewer Health tab One report of what is wrong with an install and how to fix it: health monitor state and alerts, LLM and embedding providers, the circuit breaker, functions failing on at least 20% of 5+ calls (with a provider-specific fix for summarize, compress and graph extraction), observations missing from the search index, graph snapshot age, ports, uptime, the pinned engine version and every feature flag. The missing-observation check reuses the boot reconcile scan (findUnindexedObservations, split out of reconcileIndex), so it counts exactly what search cannot find instead of comparing approximate session counters. Every probe is time-boxed at 5 s. Browsers get an HTML page with no scripts behind a strict nonce CSP; other clients get JSON, and ?format=json|html forces either. Same bearer auth as the rest of the API. The flag list moves into buildConfigFlags() so config/flags and status share it, and the engine pin moves into src/version.ts so the CLI and the status report read the same constant. * chore(skills): regenerate the REST reference for the new endpoint npm run skills:check fails CI when plugin/skills/agentmemory-rest-api/ REFERENCE.md does not list every registered REST route; regenerated with npm run skills:gen. * fix(status): report a missing health snapshot and share one index scan A status report with no health snapshot (none yet, or the probe timed out) added no problem and could read ok; it now adds an info-level health-check-unavailable finding. Every status request started its own findUnindexedObservations scan, and the 5 s probe timeout only stopped waiting, so repeated requests stacked full storage scans. singleFlight() shares one in-flight scan between overlapping requests and reuses its result for 30 s; a failed scan is dropped so the next request retries. --- AGENTS.md | 2 +- CHANGELOG.md | 1 + README.md | 2 +- .../skills/agentmemory-rest-api/REFERENCE.md | 3 +- src/cli.ts | 4 +- src/functions/search.ts | 10 +- src/functions/status.ts | 378 ++++++++++++++++++ src/index.ts | 2 +- src/triggers/api.ts | 192 ++++++--- src/version.ts | 1 + src/viewer/index.html | 116 +++++- test/status.test.ts | 237 +++++++++++ 12 files changed, 892 insertions(+), 56 deletions(-) create mode 100644 src/functions/status.ts create mode 100644 test/status.test.ts diff --git a/AGENTS.md b/AGENTS.md index a22269033c..58f7e87e96 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -119,7 +119,7 @@ Hook scripts in `src/hooks/` are standalone Node.js scripts (no iii-sdk import). ## Current Stats (v0.9.29) - 54 MCP tools (8 visible by default, `AGENTMEMORY_TOOLS=all` for all) -- 130 REST endpoints +- 131 REST endpoints - 6 MCP resources, 3 MCP prompts - 12 hooks, 17 skills - 260+ iii functions diff --git a/CHANGELOG.md b/CHANGELOG.md index a95daedac5..38fc2ba600 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), ### Added +- **`GET /agentmemory/status` and a Health tab in the viewer.** One report of what is wrong and how to fix it: the health monitor state and alerts, the LLM and embedding providers and the circuit breaker, functions failing on at least 20% of their calls (with a provider-specific fix for summarize, compress and graph extraction), observations missing from the search index (the same exact check the boot reconcile runs), graph snapshot age, ports, uptime, the pinned engine version and every feature flag with how to enable it. Browsers get an HTML page with no scripts and a strict CSP; everything else gets JSON (`?format=json` or `?format=html` force either). Every probe is time-boxed at 5 s so a slow store cannot hang the page. Uses the same bearer auth as the rest of the API. - **`agentmemory console`** launches the iii web console (workers, functions, triggers, queues, traces) through the pinned engine, against the ports agentmemory resolved, one port above the viewer by default (`--console-port` overrides). Engine 0.22 ships the console as part of `iii` and downloads it on first use, so the "install iii console?" prompt on start and the `skipConsoleInstall` preference are gone; the ready panel now points at the command instead. ### Fixed diff --git a/README.md b/README.md index 8c376dddcc..8fc014846a 100644 --- a/README.md +++ b/README.md @@ -1608,7 +1608,7 @@ Create `~/.agentmemory/.env`:

API

-130 endpoints on port `3111`. The REST API binds to `127.0.0.1` by default. Protected endpoints require `Authorization: Bearer ` when `AGENTMEMORY_SECRET` is set, and mesh sync endpoints require `AGENTMEMORY_SECRET` on both peers. +131 endpoints on port `3111`. The REST API binds to `127.0.0.1` by default. Protected endpoints require `Authorization: Bearer ` when `AGENTMEMORY_SECRET` is set, and mesh sync endpoints require `AGENTMEMORY_SECRET` on both peers.
Key endpoints diff --git a/plugin/skills/agentmemory-rest-api/REFERENCE.md b/plugin/skills/agentmemory-rest-api/REFERENCE.md index a176863c5c..bacd540f77 100644 --- a/plugin/skills/agentmemory-rest-api/REFERENCE.md +++ b/plugin/skills/agentmemory-rest-api/REFERENCE.md @@ -5,7 +5,7 @@ Generated from `src/triggers/api.ts`. Do not edit the block below by hand; run ` The REST API is the primary surface. All paths are under `http://localhost:3111` (override with `--port`). When `AGENTMEMORY_SECRET` is set, send `Authorization: Bearer $AGENTMEMORY_SECRET`; localhost is otherwise open. -130 registered endpoints: +131 registered endpoints: | Method | Path | | --- | --- | @@ -130,6 +130,7 @@ The REST API is the primary surface. All paths are under `http://localhost:3111` | POST | `/agentmemory/snapshot/create` | | POST | `/agentmemory/snapshot/restore` | | GET | `/agentmemory/snapshots` | +| GET | `/agentmemory/status` | | POST | `/agentmemory/summarize` | | GET | `/agentmemory/team/feed` | | GET | `/agentmemory/team/profile` | diff --git a/src/cli.ts b/src/cli.ts index de20cad94f..832428ebcf 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -79,7 +79,7 @@ import { isFirstRun, readPrefs, resetPrefs, writePrefs } from "./cli/preferences import { runOnboarding } from "./cli/onboarding.js"; import { setBootVerbose } from "./logger.js"; import { hydrateProcessEnvFromFile } from "./config.js"; -import { VERSION } from "./version.js"; +import { III_PINNED_VERSION, VERSION } from "./version.js"; import { getAllTools, ESSENTIAL_TOOLS } from "./mcp/tools-registry.js"; import { knownAgents } from "./cli/connect/index.js"; @@ -130,7 +130,7 @@ if (args.includes("--version") || args.includes("-V")) { // constant and the two package.json dependencies together. // AGENTMEMORY_III_VERSION overrides the pin for anyone running a // self-managed engine. -const IIPINNED_DEFAULT_VERSION = "0.22.1"; +const IIPINNED_DEFAULT_VERSION = III_PINNED_VERSION; const IIPINNED_VERSION = process.env["AGENTMEMORY_III_VERSION"] || IIPINNED_DEFAULT_VERSION; const IIIENGINE_INSTALL_CMD = `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=${IIPINNED_VERSION} sh`; diff --git a/src/functions/search.ts b/src/functions/search.ts index bb585aa071..2b8858bdc5 100644 --- a/src/functions/search.ts +++ b/src/functions/search.ts @@ -309,7 +309,9 @@ export async function indexRecords( return count } -export async function reconcileIndex(kv: StateKV): Promise { +export async function findUnindexedObservations( + kv: StateKV, +): Promise<{ sessions: number; missing: CompressedObservation[] }> { const idx = getSearchIndex() const sessions = await kv.list(KV.sessions) const indexed = idx.observationCountsBySession() @@ -323,6 +325,12 @@ export async function reconcileIndex(kv: StateKV): Promise { missing.push(obs) } } + return { sessions: sessions.length, missing } +} + +export async function reconcileIndex(kv: StateKV): Promise { + const idx = getSearchIndex() + const { missing } = await findUnindexedObservations(kv) const stillMissing = missing.filter((obs) => !idx.has(obs.id)) if (stillMissing.length === 0) return 0 return indexRecords(stillMissing, []) diff --git a/src/functions/status.ts b/src/functions/status.ts new file mode 100644 index 0000000000..552fe6c07a --- /dev/null +++ b/src/functions/status.ts @@ -0,0 +1,378 @@ +export type StatusLevel = "ok" | "info" | "warn" | "error"; + +export interface StatusProblem { + level: Exclude; + code: string; + message: string; + fix?: string; +} + +export interface FunctionMetricInput { + functionId: string; + totalCalls: number; + successCount: number; + failureCount: number; + avgLatencyMs: number; +} + +export interface StatusFlag { + key: string; + label: string; + enabled: boolean; + needsLlm: boolean; + enableHow: string; +} + +export interface GraphStatsInput { + totalNodes?: number; + totalEdges?: number; + fromSnapshot?: boolean; + updatedAt?: string; + dirty?: boolean; + warning?: string; +} + +export interface StatusInputs { + now: Date; + version: string; + engineVersion: string; + uptimeSeconds: number; + ports: { rest: number | null; streams: number | null; viewer: number | null }; + health: { + status?: string; + alerts?: string[]; + notes?: string[]; + connectionState?: string; + } | null; + circuitBreaker: { state?: string; failures?: number } | null; + functionMetrics: FunctionMetricInput[]; + provider: string; + embeddingProvider: string; + flags: StatusFlag[]; + index: { + bm25Documents: number; + vectorDocuments: number | null; + observationsIndexed: number; + missingObservations: number | null; + sessions: number | null; + }; + graph: GraphStatsInput | null; + graphExtractionEnabled: boolean; +} + +export interface StatusReport { + status: StatusLevel; + checkedAt: string; + service: { + version: string; + engineVersion: string; + uptimeSeconds: number; + ports: StatusInputs["ports"]; + }; + health: StatusInputs["health"]; + provider: { llm: string; embeddings: string; circuitBreaker: StatusInputs["circuitBreaker"] }; + index: StatusInputs["index"]; + graph: (GraphStatsInput & { ageSeconds: number | null; extractionEnabled: boolean }) | null; + functions: Array; + flags: StatusFlag[]; + problems: StatusProblem[]; +} + +const FAILURE_RATE_THRESHOLD = 0.2; +const FAILURE_MIN_CALLS = 5; +const GRAPH_SNAPSHOT_STALE_SECONDS = 24 * 60 * 60; +const LEVEL_RANK: Record = { ok: 0, info: 1, warn: 2, error: 3 }; + +const FUNCTION_FIXES: Record = { + "mem::summarize": + "Summaries come from your LLM provider. Check the provider key, model name and rate limits in ~/.agentmemory/.env, then look for provider errors in the server log.", + "mem::compress": + "Compression calls your LLM provider. Check the provider key and model, or set AGENTMEMORY_AUTO_COMPRESS=false to use zero-LLM compression.", + "mem::graph-extract": + "Graph extraction calls your LLM provider. Check the provider key and model, or set GRAPH_EXTRACTION_ENABLED=false.", +}; + +function secondsBetween(later: Date, earlierIso: string | undefined): number | null { + if (!earlierIso) return null; + const earlier = Date.parse(earlierIso); + if (Number.isNaN(earlier)) return null; + return Math.max(0, Math.round((later.getTime() - earlier) / 1000)); +} + +export function evaluateStatus(input: StatusInputs): StatusReport { + const problems: StatusProblem[] = []; + + if (!input.health) { + problems.push({ + level: "info", + code: "health-check-unavailable", + message: "The health monitor has no snapshot yet or did not answer in time, so its state was not checked.", + }); + } + const healthStatus = input.health?.status; + if (healthStatus === "critical") { + problems.push({ level: "error", code: "health-critical", message: "The health monitor reports a critical state." }); + } else if (healthStatus === "degraded") { + problems.push({ level: "warn", code: "health-degraded", message: "The health monitor reports a degraded state." }); + } + for (const alert of input.health?.alerts ?? []) { + problems.push({ level: "warn", code: "health-alert", message: alert }); + } + + if (input.circuitBreaker?.state === "open") { + problems.push({ + level: "error", + code: "provider-circuit-open", + message: `LLM provider calls are paused after ${input.circuitBreaker.failures ?? 0} consecutive failures.`, + fix: "Check the provider key and model in ~/.agentmemory/.env. Calls resume automatically once the provider answers again.", + }); + } + + if (input.provider === "noop") { + problems.push({ + level: "info", + code: "no-llm-provider", + message: "No LLM provider is configured, so summaries, consolidation and graph extraction stay off. Search still works.", + fix: "Add one provider key (for example ANTHROPIC_API_KEY or OPENAI_API_KEY) to ~/.agentmemory/.env and restart.", + }); + } + + const functions = input.functionMetrics.map((m) => ({ + ...m, + failureRate: m.totalCalls > 0 ? m.failureCount / m.totalCalls : 0, + })); + for (const fn of functions) { + if (fn.totalCalls < FAILURE_MIN_CALLS || fn.failureRate < FAILURE_RATE_THRESHOLD) continue; + problems.push({ + level: "warn", + code: "function-failing", + message: `${fn.functionId} failed ${fn.failureCount} of ${fn.totalCalls} calls (${Math.round(fn.failureRate * 100)}%).`, + fix: FUNCTION_FIXES[fn.functionId] ?? "Look for this function id in the server log to see the error.", + }); + } + + const missingObservations = input.index.missingObservations; + if (missingObservations !== null && missingObservations > 0) { + problems.push({ + level: "warn", + code: "index-missing-observations", + message: `${missingObservations} stored observations are not in the search index, so search cannot find them.`, + fix: "Restart agentmemory: the boot reconcile re-indexes observations missing from the snapshot.", + }); + } + if (missingObservations === null) { + problems.push({ + level: "info", + code: "index-check-unavailable", + message: "The session store did not answer in time, so the search index was not checked for missing observations.", + }); + } + + let graph: StatusReport["graph"] = null; + if (input.graph) { + const ageSeconds = secondsBetween(input.now, input.graph.updatedAt); + graph = { ...input.graph, ageSeconds, extractionEnabled: input.graphExtractionEnabled }; + if (input.graphExtractionEnabled && !input.graph.fromSnapshot) { + problems.push({ + level: "warn", + code: "graph-no-snapshot", + message: "Graph extraction is on but no graph snapshot exists, so graph counts read as zero.", + fix: "Use Rebuild Graph in the viewer, or POST /agentmemory/graph/snapshot-rebuild.", + }); + } else if (input.graph.fromSnapshot && ageSeconds !== null && ageSeconds > GRAPH_SNAPSHOT_STALE_SECONDS) { + const age = ageSeconds >= 2 * 86400 ? `${Math.floor(ageSeconds / 86400)} days` : `${Math.round(ageSeconds / 3600)} hours`; + problems.push({ + level: "info", + code: "graph-snapshot-stale", + message: `The graph snapshot is ${age} old, so dashboard graph counts can lag the live graph.`, + fix: "POST /agentmemory/graph/snapshot-rebuild refreshes it.", + }); + } + if (input.graph.dirty) { + problems.push({ + level: "info", + code: "graph-snapshot-dirty", + message: "The graph snapshot was read while a write was in flight; counts are eventually consistent.", + }); + } + } + + const status = problems.reduce( + (worst, p) => (LEVEL_RANK[p.level] > LEVEL_RANK[worst] ? p.level : worst), + "ok", + ); + + return { + status, + checkedAt: input.now.toISOString(), + service: { + version: input.version, + engineVersion: input.engineVersion, + uptimeSeconds: input.uptimeSeconds, + ports: input.ports, + }, + health: input.health, + provider: { + llm: input.provider, + embeddings: input.embeddingProvider, + circuitBreaker: input.circuitBreaker, + }, + index: input.index, + graph, + functions, + flags: input.flags, + problems, + }; +} + +function escapeHtml(value: unknown): string { + return String(value ?? "") + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """) + .replace(/'/g, "'"); +} + +function formatDuration(seconds: number | null): string { + if (seconds === null) return "unknown"; + if (seconds < 60) return `${seconds}s`; + const minutes = Math.floor(seconds / 60); + if (minutes < 60) return `${minutes}m`; + const hours = Math.floor(minutes / 60); + if (hours < 48) return `${hours}h ${minutes % 60}m`; + return `${Math.floor(hours / 24)}d`; +} + +function row(label: string, value: string): string { + return `${escapeHtml(label)}${value}`; +} + +export function renderStatusHtml(report: StatusReport, styleNonce: string): string { + const problems = report.problems.length + ? report.problems + .map( + (p) => + `
  • ${p.level}

    ${escapeHtml(p.message)}

    ` + + (p.fix ? `

    ${escapeHtml(p.fix)}

    ` : "") + + `
  • `, + ) + .join("") + : `
  • ok

    No problems found.

  • `; + + const functions = report.functions.length + ? report.functions + .slice() + .sort((a, b) => b.totalCalls - a.totalCalls) + .map( + (f) => + `= FAILURE_RATE_THRESHOLD && f.totalCalls >= FAILURE_MIN_CALLS ? ' class="bad"' : ""}>` + + `${escapeHtml(f.functionId)}${f.totalCalls}${f.failureCount}` + + `${Math.round(f.failureRate * 100)}%${Math.round(f.avgLatencyMs)} ms`, + ) + .join("") + : `No function calls recorded yet.`; + + const flags = report.flags + .map( + (f) => + `${escapeHtml(f.label)}${f.enabled ? "on" : "off"}` + + `${f.enabled ? "" : escapeHtml(f.enableHow)}`, + ) + .join(""); + + const idx = report.index; + const graph = report.graph; + const ports = report.service.ports; + + return ` + +agentmemory status +
    +

    agentmemory

    ${report.status} +v${escapeHtml(report.service.version)} · engine ${escapeHtml(report.service.engineVersion)} · checked ${escapeHtml(report.checkedAt)} · refresh · json
    +

    Problems

      ${problems}
    +

    Service

    +${row("Uptime", escapeHtml(formatDuration(report.service.uptimeSeconds)))} +${row("REST port", escapeHtml(ports.rest ?? "unknown"))} +${row("Streams port", escapeHtml(ports.streams ?? "unknown"))} +${row("Viewer port", escapeHtml(ports.viewer ?? "not running"))} +${row("Health monitor", escapeHtml(report.health?.status ?? "no data yet"))} +${row("Engine connection", escapeHtml(report.health?.connectionState ?? "unknown"))} +
    +

    Providers

    +${row("LLM", escapeHtml(report.provider.llm))} +${row("Embeddings", escapeHtml(report.provider.embeddings))} +${row("Circuit breaker", escapeHtml(report.provider.circuitBreaker ? `${report.provider.circuitBreaker.state ?? "unknown"} (${report.provider.circuitBreaker.failures ?? 0} failures)` : "not in use"))} +
    +

    Search index

    +${row("BM25 documents", escapeHtml(idx.bm25Documents))} +${row("Vector documents", escapeHtml(idx.vectorDocuments ?? "vector search off"))} +${row("Observations indexed", escapeHtml(idx.observationsIndexed))} +${row("Missing from index", escapeHtml(idx.missingObservations ?? "not checked"))} +${row("Sessions", escapeHtml(idx.sessions ?? "unknown"))} +
    +

    Knowledge graph

    +${graph + ? row("Extraction", graph.extractionEnabled ? "on" : "off") + + row("Nodes / edges", escapeHtml(`${graph.totalNodes ?? 0} / ${graph.totalEdges ?? 0}`)) + + row("Snapshot age", escapeHtml(graph.fromSnapshot ? formatDuration(graph.ageSeconds) : "no snapshot")) + : row("Graph", "unavailable")} +
    +

    Functions

    ${functions}
    FunctionCallsFailedFailure rateAvg latency
    +

    Features

    ${flags}
    FeatureStateHow to enable
    +

    More

    Environment checks (keys, engine binary, stale pid files) run on your machine with agentmemory doctor. This page as JSON: GET /agentmemory/status with Accept: application/json.

    +
    `; +} + +export const UNINDEXED_SCAN_REUSE_MS = 30_000; + +export function singleFlight( + run: () => Promise, + reuseMs: number, + now: () => number = Date.now, +): () => Promise { + let current: { promise: Promise; settledAt: number | null } | null = null; + return () => { + if (current && (current.settledAt === null || now() - current.settledAt < reuseMs)) { + return current.promise; + } + const entry: { promise: Promise; settledAt: number | null } = { promise: run(), settledAt: null }; + entry.promise.then( + () => { + entry.settledAt = now(); + }, + () => { + if (current === entry) current = null; + }, + ); + current = entry; + return entry.promise; + }; +} + +export function prefersHtml(accept: string | undefined, format: string | undefined): boolean { + if (format === "json") return false; + if (format === "html") return true; + if (!accept) return false; + return /\btext\/html\b/.test(accept); +} diff --git a/src/index.ts b/src/index.ts index 2cef745163..601389634d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -549,7 +549,7 @@ async function main() { `Ready. ${embeddingProvider ? "Triple-stream (BM25+Vector+Graph)" : "BM25+Graph"} search active.`, ); bootLog( - `REST API: 130 endpoints at http://localhost:${config.restPort}/agentmemory/*`, + `REST API: 131 endpoints at http://localhost:${config.restPort}/agentmemory/*`, ); bootLog( `MCP surface (opt-in via \`npx @agentmemory/mcp\`): ${getAllTools().length} tools · 6 resources · 3 prompts`, diff --git a/src/triggers/api.ts b/src/triggers/api.ts index 9130381f14..78426e8066 100644 --- a/src/triggers/api.ts +++ b/src/triggers/api.ts @@ -1,5 +1,6 @@ import { TriggerAction, type IIIClient } from "iii-sdk"; import type { HttpRequest } from "@iii-dev/helpers/http"; +import { randomBytes } from "node:crypto"; import type { Session, CompressedObservation, HookPayload, CommitLink, SessionSummary } from "../types.js"; import { withKeyedLock } from "../state/keyed-mutex.js"; import { KV } from "../state/schema.js"; @@ -8,7 +9,9 @@ import { StateKV } from "../state/kv.js"; import { getLatestHealth } from "../health/monitor.js"; import type { MetricsStore } from "../eval/metrics-store.js"; import type { ResilientProvider } from "../providers/resilient.js"; -import { VERSION } from "../version.js"; +import { III_PINNED_VERSION, VERSION } from "../version.js"; +import { UNINDEXED_SCAN_REUSE_MS, evaluateStatus, prefersHtml, renderStatusHtml, singleFlight, type GraphStatsInput } from "../functions/status.js"; +import { findUnindexedObservations, getSearchIndex, getVectorIndex } from "../functions/search.js"; import { timingSafeCompare } from "../auth.js"; import { isSlotsEnabled, isReflectEnabled } from "../functions/slots.js"; import { renderViewerDocument } from "../viewer/document.js"; @@ -138,6 +141,55 @@ function parseOptionalPositiveInt(value: unknown): number | undefined | null { return parsed; } +function buildConfigFlags() { + return [ + { + key: "GRAPH_EXTRACTION_ENABLED", + label: "Knowledge graph extraction", + enabled: isGraphExtractionEnabled(), + default: false, + affects: ["Graph", "Dashboard"], + needsLlm: true, + description: "Extracts entities and relations from observations into a knowledge graph.", + enableHow: "Set GRAPH_EXTRACTION_ENABLED=true and provide an LLM key, then restart.", + docsHref: "https://github.com/rohitg00/agentmemory#knowledge-graph", + }, + { + key: "CONSOLIDATION_ENABLED", + label: "Memory consolidation", + enabled: isConsolidationEnabled(), + default: false, + affects: ["Dashboard", "Memories", "Crystals"], + needsLlm: true, + description: "Periodically summarizes sessions into semantic facts + procedures.", + enableHow: "Set CONSOLIDATION_ENABLED=true and provide an LLM key, then restart.", + docsHref: "https://github.com/rohitg00/agentmemory#consolidation", + }, + { + key: "AGENTMEMORY_AUTO_COMPRESS", + label: "LLM-powered observation compression", + enabled: isAutoCompressEnabled(), + default: false, + affects: ["Memories", "Timeline"], + needsLlm: true, + description: "Every observation is compressed by the LLM for richer summaries (costs tokens). OFF uses zero-LLM synthetic compression.", + enableHow: "Set AGENTMEMORY_AUTO_COMPRESS=true and provide an LLM key.", + docsHref: "https://github.com/rohitg00/agentmemory/issues/138", + }, + { + key: "AGENTMEMORY_INJECT_CONTEXT", + label: "In-conversation context injection", + enabled: isContextInjectionEnabled(), + default: false, + affects: ["Hooks"], + needsLlm: false, + description: "Hooks write recalled context into Claude Code's conversation. OFF captures in the background without injecting.", + enableHow: "Set AGENTMEMORY_INJECT_CONTEXT=true and restart.", + docsHref: "https://github.com/rohitg00/agentmemory/issues/143", + }, + ]; +} + export function registerApiTriggers( sdk: IIIClient, kv: StateKV, @@ -197,52 +249,7 @@ export function registerApiTriggers( if (authErr) return authErr; const providerKind = detectLlmProviderKind(); const embeddingProvider = detectEmbeddingProvider() ? "embeddings" : "none"; - const flags = [ - { - key: "GRAPH_EXTRACTION_ENABLED", - label: "Knowledge graph extraction", - enabled: isGraphExtractionEnabled(), - default: false, - affects: ["Graph", "Dashboard"], - needsLlm: true, - description: "Extracts entities and relations from observations into a knowledge graph.", - enableHow: "Set GRAPH_EXTRACTION_ENABLED=true and provide an LLM key, then restart.", - docsHref: "https://github.com/rohitg00/agentmemory#knowledge-graph", - }, - { - key: "CONSOLIDATION_ENABLED", - label: "Memory consolidation", - enabled: isConsolidationEnabled(), - default: false, - affects: ["Dashboard", "Memories", "Crystals"], - needsLlm: true, - description: "Periodically summarizes sessions into semantic facts + procedures.", - enableHow: "Set CONSOLIDATION_ENABLED=true and provide an LLM key, then restart.", - docsHref: "https://github.com/rohitg00/agentmemory#consolidation", - }, - { - key: "AGENTMEMORY_AUTO_COMPRESS", - label: "LLM-powered observation compression", - enabled: isAutoCompressEnabled(), - default: false, - affects: ["Memories", "Timeline"], - needsLlm: true, - description: "Every observation is compressed by the LLM for richer summaries (costs tokens). OFF uses zero-LLM synthetic compression.", - enableHow: "Set AGENTMEMORY_AUTO_COMPRESS=true and provide an LLM key.", - docsHref: "https://github.com/rohitg00/agentmemory/issues/138", - }, - { - key: "AGENTMEMORY_INJECT_CONTEXT", - label: "In-conversation context injection", - enabled: isContextInjectionEnabled(), - default: false, - affects: ["Hooks"], - needsLlm: false, - description: "Hooks write recalled context into Claude Code's conversation. OFF captures in the background without injecting.", - enableHow: "Set AGENTMEMORY_INJECT_CONTEXT=true and restart.", - docsHref: "https://github.com/rohitg00/agentmemory/issues/143", - }, - ]; + const flags = buildConfigFlags(); return { status_code: 200, body: { @@ -298,6 +305,97 @@ export function registerApiTriggers( }, }); + const STATUS_CHECK_TIMEOUT_MS = 5000; + + async function valueWithin(work: Promise, ms: number): Promise { + let timer: ReturnType | undefined; + const expiry = new Promise((resolve) => { + timer = setTimeout(() => resolve(null), ms); + }); + try { + return await Promise.race([work.catch(() => null), expiry]); + } finally { + clearTimeout(timer); + } + } + + const sharedUnindexedScan = singleFlight(() => findUnindexedObservations(kv), UNINDEXED_SCAN_REUSE_MS); + + sdk.registerFunction("api::status", + async (req: HttpRequest): Promise => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const idx = getSearchIndex(); + const [health, functionMetrics, graph, unindexed] = await Promise.all([ + valueWithin(getLatestHealth(kv), STATUS_CHECK_TIMEOUT_MS), + metricsStore ? valueWithin(metricsStore.getAll(), STATUS_CHECK_TIMEOUT_MS) : Promise.resolve([]), + valueWithin( + sdk.trigger({ function_id: "mem::graph-stats", payload: {} }) as Promise, + STATUS_CHECK_TIMEOUT_MS, + ), + valueWithin(sharedUnindexedScan(), STATUS_CHECK_TIMEOUT_MS), + ]); + const observationsIndexed = [...idx.observationCountsBySession().values()].reduce((a, n) => a + n, 0); + const circuit = + provider && "circuitState" in provider + ? (provider.circuitState as { state?: string; failures?: number } | null) + : null; + const report = evaluateStatus({ + now: new Date(), + version: VERSION, + engineVersion: III_PINNED_VERSION, + uptimeSeconds: Math.round(process.uptime()), + ports: { + rest: loadConfig().restPort ?? null, + streams: bootStreamsPort ?? null, + viewer: getViewerSkipped() ? null : (getBoundViewerPort() ?? null), + }, + health: health + ? { + status: health.status, + alerts: health.alerts, + notes: health.notes, + connectionState: health.connectionState, + } + : null, + circuitBreaker: circuit, + functionMetrics: functionMetrics ?? [], + provider: detectLlmProviderKind(), + embeddingProvider: detectEmbeddingProvider() ? "embeddings" : "none", + flags: buildConfigFlags(), + index: { + bm25Documents: idx.size, + vectorDocuments: getVectorIndex()?.size ?? null, + observationsIndexed, + missingObservations: unindexed ? unindexed.missing.length : null, + sessions: unindexed ? unindexed.sessions : null, + }, + graph, + graphExtractionEnabled: isGraphExtractionEnabled(), + }); + const accept = req.headers?.["accept"] ?? req.headers?.["Accept"]; + const format = req.query_params?.["format"]; + if (prefersHtml(typeof accept === "string" ? accept : undefined, typeof format === "string" ? format : undefined)) { + const nonce = randomBytes(16).toString("base64"); + return { + status_code: 200, + headers: { + "Content-Type": "text/html; charset=utf-8", + "Content-Security-Policy": `default-src 'none'; style-src 'nonce-${nonce}'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`, + "Cache-Control": "no-store", + }, + body: renderStatusHtml(report, nonce), + }; + } + return { status_code: 200, headers: { "Cache-Control": "no-store" }, body: report }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::status", + config: { api_path: "/agentmemory/status", http_method: "GET" }, + }); + sdk.registerFunction("api::observe", async (req: HttpRequest): Promise => { const body = (req.body ?? {}) as Record; diff --git a/src/version.ts b/src/version.ts index 84d83bdcb0..2d78ca2d9d 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1 +1,2 @@ export const VERSION = "0.9.29"; +export const III_PINNED_VERSION = "0.22.1"; diff --git a/src/viewer/index.html b/src/viewer/index.html index de47f4f5f9..8fc60aded0 100644 --- a/src/viewer/index.html +++ b/src/viewer/index.html @@ -193,7 +193,7 @@ background: none; border: none; color: var(--ink-muted); - padding: 10px 20px; + padding: 10px 16px; font-size: 11px; cursor: pointer; border-bottom: 2px solid transparent; @@ -1053,6 +1053,7 @@

    agentmemory

    +
    @@ -1070,6 +1071,7 @@

    agentmemory

    +