Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(hooks): keep the PowerShell 7 and Bun TypeScript requests off environment proxies (#1517)
AkitaOnRails6869b2841f81
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 33d482ac..2cabc857 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -223,14 +223,6 @@ version in [`docs/changelog/`](docs/changelog/):relay and wiki sync companions take the same `rustls-webpki` bump.### Fixed-- The staged POSIX shell hook bundle no longer sends its requests through- `HTTP_PROXY`, `HTTPS_PROXY` or `ALL_PROXY`, as the native hook client and the- bridge already did. In a sandbox that exports a proxy with an empty- `NO_PROXY`, the filtering proxy answered the loopback event POST with a 4xx,- which the bundle treats as a permanent rejection, so the observation was- dropped instead of spooled and a resuming session got no handoff.- ([#1517](https://github.com/akitaonrails/ai-memory/pull/1517))-- Reserved local-embedding capacity for interactive search queries instead ofallowing concurrent page writes and backfill work to occupy every inferenceslot. Excess queries fall back immediately to non-vector retrieval, and a@@ -245,6 +237,17 @@ version in [`docs/changelog/`](docs/changelog/):with no profile digest, brief or inbox notice at all. The refusal now costsonly the claim, and the handoff stays open.+- The POSIX shell hook bundle, the PowerShell bundle under PowerShell 7 and the+ generated TypeScript integrations under Bun (OpenCode) no longer send+ their requests through an environment proxy (`http_proxy`, `HTTPS_PROXY`,+ `ALL_PROXY`), as the native hook client and the bridge already did. In a+ sandbox that exports a proxy with an empty `NO_PROXY`, the filtering proxy+ answered the loopback event POST with a 4xx, which the hooks treat as a+ permanent rejection, so the observation was dropped instead of spooled and a+ resuming session got no handoff. A server reachable only through a forward+ proxy needs a direct route; see `docs/https-via-proxy.md`.+ ([#1517](https://github.com/akitaonrails/ai-memory/pull/1517))+- `mcp-bridge` and the `setup` self-check no longer send requests to theserver through `HTTP_PROXY`, `HTTPS_PROXY` or `ALL_PROXY`, as the hooksalready did. A sandbox such as ai-jail exports a proxy with an emptydiff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex a469ed9f..503ebb6a 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -4903,6 +4903,7 @@ function gitRepoProject(cwd: string): string | undefined {fn add_hook_spooling(source: String) -> Result<String> {const FETCH_BLOCK: &str = r#" try {await fetch(item.url, {+ proxy: false,method: "POST",headers: { "Content-Type": "application/json", ...authHeaders() },body: JSON.stringify(item.payload),@@ -4913,6 +4914,7 @@ fn add_hook_spooling(source: String) -> Result<String> {}"#;const FETCH_REPLACEMENT: &str = r#" try {const resp = await fetch(item.url, {+ proxy: false,method: "POST",headers: { "Content-Type": "application/json", ...authHeaders() },body: JSON.stringify(item.payload),@@ -5070,6 +5072,7 @@ async function drainHookQueue(): Promise<void> {{if (!item) break;try {{await fetch(item.url, {{+ proxy: false,method: "POST",headers: {{ "Content-Type": "application/json", ...authHeaders() }},body: JSON.stringify(item.payload),@@ -5220,6 +5223,7 @@ async function fetchHandoff(cwd: string, id: string | undefined): Promise<stringif (!applyMarkerParams(url, cwd)) return undefined;try {{const response = await fetch(url, {{+ proxy: false,headers: authHeaders(),signal: timeoutSignal(1000),}});@@ -5239,6 +5243,7 @@ async function fetchRecap(cwd: string, id: string): Promise<string | undefined>if (!applyMarkerParams(url, cwd)) return undefined;try {{const response = await fetch(url, {{+ proxy: false,headers: authHeaders(),signal: timeoutSignal(1000),}});@@ -5693,6 +5698,7 @@ function mcpHeaders(ctx?: any): Record<string, string> {async function mcpRpc(method: string, params?: unknown, ctx?: any, signal?: AbortSignal): Promise<any> {const id = ++mcpRequestId;const response = await fetch(MCP_SERVER, {+ proxy: false,method: "POST",headers: mcpHeaders(ctx),body: JSON.stringify({ jsonrpc: "2.0", id, method, params: params ?? {} }),@@ -5707,6 +5713,7 @@ async function mcpRpc(method: string, params?: unknown, ctx?: any, signal?: Aborasync function mcpNotify(method: string, params?: unknown, ctx?: any, signal?: AbortSignal): Promise<void> {const response = await fetch(MCP_SERVER, {+ proxy: false,method: "POST",headers: mcpHeaders(ctx),body: JSON.stringify({ jsonrpc: "2.0", method, params: params ?? {} }),@@ -5853,6 +5860,7 @@ async function drainHookQueue(): Promise<void> {{if (!item) break;try {{await fetch(item.url, {{+ proxy: false,method: "POST",headers: {{ "Content-Type": "application/json", ...authHeaders() }},body: JSON.stringify(item.payload),@@ -6004,6 +6012,7 @@ async function fetchHandoff(cwd: string, id: string | undefined): Promise<stringif (!applyMarkerParams(url, cwd)) return undefined;try {{const response = await fetch(url, {{+ proxy: false,headers: authHeaders(),signal: timeoutSignal(1000),}});diff --git a/crates/ai-memory-cli/src/commands/openclaw_plugin.rs b/crates/ai-memory-cli/src/commands/openclaw_plugin.rsindex ebf07e13..76a0fff9 100644--- a/crates/ai-memory-cli/src/commands/openclaw_plugin.rs+++ b/crates/ai-memory-cli/src/commands/openclaw_plugin.rs@@ -384,6 +384,7 @@ function postPreCompact(event: any, ctx: any): void {{// Tracked in pendingHookRequests so session_end can await a bounded// flush instead of letting teardown kill the in-flight fetch (#676).const request = fetch(url, {{+ proxy: false,method: "POST",headers: {{ "Content-Type": "application/json", ...authHeaders() }},body: JSON.stringify(policy.payload),@@ -410,6 +411,7 @@ async function fetchHandoff(event: any, ctx: any): Promise<string | undefined> {if (!applyMarkerParams(url, currentCwd)) return undefined;try {{const response = await fetch(url, {{+ proxy: false,headers: authHeaders(),signal: timeoutSignal(1000),}});diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rsindex 8b26e310..4c3bbc2f 100644--- a/crates/ai-memory-cli/src/commands/render_shared.rs+++ b/crates/ai-memory-cli/src/commands/render_shared.rs@@ -3035,7 +3035,10 @@ async function drainHookSpool(): Promise<void> {"X-AI-Memory-Client": AGENT,};if (entry.token) headers["Authorization"] = `Bearer ${entry.token}`;+ // Bun reads HTTP(S)_PROXY and ALL_PROXY even for a loopback URL;+ // `proxy: false` connects directly. Node's fetch ignores the key.const resp = await fetch(entry.url, {+ proxy: false,method: "POST",headers,body: entry.body,@@ -3165,6 +3168,13 @@ fn assert_every_ts_request_carries_client_marker(name: &str, source: &str) {|| call.contains(" headers,\n"),"{name}: a fetch without the client marker:\n{call}");+ // Bun's fetch sends even a loopback request through an environment+ // proxy, which a sandbox with an empty NO_PROXY (ai-jail) answers+ // with a 4xx; the native hook and the shell bundle skip proxies too.+ assert!(+ call.contains("proxy: false,"),+ "{name}: a fetch that can reach an environment proxy:\n{call}"+ );}assert!(requests >= 3,diff --git a/docs/https-via-proxy.md b/docs/https-via-proxy.mdindex 45b26cca..6d55a618 100644--- a/docs/https-via-proxy.md+++ b/docs/https-via-proxy.md@@ -559,6 +559,16 @@ public hostname**, not just `localhost`. The host-allowlist middlewareruns before any header rewriting, so it sees the proxy's forwarded`Host: memory.example.com` and would reject it otherwise.+### Clients connect directly, never through a forward proxy++The hooks (native, shell, PowerShell 7 and the TypeScript integrations) and+`ai-memory mcp-bridge` ignore `HTTP_PROXY`, `HTTPS_PROXY` and `ALL_PROXY`, so a+sandbox that exports a filtering proxy cannot swallow their requests. A+server that a client machine can reach only through an outbound forward proxy+is therefore out of reach for them. Give the server an address the client can+reach directly, such as a reverse proxy on the network edge or a tunnel like+Path 3.+## Don't paper over the security gapThree things to actively avoid:diff --git a/hooks/lib/ai-memory-hook.ps1 b/hooks/lib/ai-memory-hook.ps1index 73bff607..788600be 100644--- a/hooks/lib/ai-memory-hook.ps1+++ b/hooks/lib/ai-memory-hook.ps1@@ -785,8 +785,9 @@ function Invoke-AiMemoryDrainSpool {$headers["Authorization"] = "Bearer $($entry.token)"}$code = 0+ $NoProxy = Get-AiMemoryNoProxytry {- Invoke-WebRequest `+ Invoke-WebRequest @NoProxy `-UseBasicParsing `-TimeoutSec 3 `-Method Post `@@ -897,6 +898,17 @@ function Clear-AiMemorySessionId {Remove-Item -Force -ErrorAction SilentlyContinue $Path}+# PowerShell 7 hands Invoke-WebRequest the HTTP_PROXY, HTTPS_PROXY and+# ALL_PROXY proxy even for a loopback URL, so a sandbox with an empty NO_PROXY+# (ai-jail) routes the hook to a proxy that answers 4xx. -NoProxy (PowerShell+# 6+) connects directly, as the native hook and the shell bundle do. Windows+# PowerShell 5.1 reads no environment proxy and has no -NoProxy. Splat the+# result into every Invoke-WebRequest.+function Get-AiMemoryNoProxy {+ if ($PSVersionTable.PSVersion.Major -ge 6) { return @{ NoProxy = $true } }+ return @{}+}+function Read-AiMemoryStdin {try {if (-not [Console]::IsInputRedirected) { return "" }@@ -1060,8 +1072,9 @@ function Invoke-AiMemoryHook {# reason the shell bundle mints `ai_memory_ingest_key`. `ps` plus a# GUID's hex fits the server's key grammar.$HookUrl = "$Server/hook?event=$Event&agent=$Agent$QS$SessionQS&ingest_key=ps$([Guid]::NewGuid().ToString('N').Substring(0, 16))"+ $NoProxy = Get-AiMemoryNoProxytry {- Invoke-WebRequest `+ Invoke-WebRequest @NoProxy `-UseBasicParsing `-TimeoutSec 3 `-Method Post `@@ -1177,8 +1190,9 @@ function Invoke-AiMemoryHook {if ($Event -eq "session-start" -and -not $BriefingOncePerSession) {$BriefQS = Get-AiMemoryBriefingQuery -Cwd $Cwd}+ $NoProxy = Get-AiMemoryNoProxytry {- $Response = Invoke-WebRequest `+ $Response = Invoke-WebRequest @NoProxy `-UseBasicParsing `-TimeoutSec 2 `-Uri "$Server/handoff?agent=$Agent$QS$NativeSessionQS$BriefQS$ProfileQS" `diff --git a/tests/hooks/test_lib.sh b/tests/hooks/test_lib.shindex 5050600c..5fee1161 100755--- a/tests/hooks/test_lib.sh+++ b/tests/hooks/test_lib.sh@@ -1348,12 +1348,18 @@ unset AI_MEMORY_DATA_DIRPS_HELPER=hooks/lib/ai-memory-hook.ps1PS_HEADER_TABLES=$(grep -Ec '^[[:space:]]*\$[Hh]eaders = @\{\}' "$PS_HELPER")PS_MARKED_TABLES=$(grep -Ec '^[[:space:]]*\$[Hh]eaders\["X-AI-Memory-Client"\] = "hook-ps"' "$PS_HELPER")-PS_REQUESTS=$(grep -c 'Invoke-WebRequest `' "$PS_HELPER")-PS_REQUESTS_WITH_HEADERS=$(grep -A6 'Invoke-WebRequest `' "$PS_HELPER" | grep -Ec -- '-Headers \$[Hh]eaders')+PS_REQUESTS=$(grep -Ec '^[^#]*Invoke-WebRequest( @NoProxy)? `$' "$PS_HELPER")+PS_REQUESTS_WITH_HEADERS=$(grep -E -A6 '^[^#]*Invoke-WebRequest( @NoProxy)? `$' "$PS_HELPER" | grep -Ec -- '-Headers \$[Hh]eaders')+PS_REQUESTS_NO_PROXY=$(grep -Ec '^[^#]*Invoke-WebRequest @NoProxy `$' "$PS_HELPER")assert_eq "powershell: header tables found" "yes" \"$([ "$PS_HEADER_TABLES" -ge 2 ] && printf 'yes' || printf 'no (%s)' "$PS_HEADER_TABLES")"assert_eq "powershell: every header table carries the client marker" "$PS_HEADER_TABLES" "$PS_MARKED_TABLES"assert_eq "powershell: every request passes the header table" "$PS_REQUESTS" "$PS_REQUESTS_WITH_HEADERS"+assert_eq "powershell: every request call site found" "yes" \+ "$([ "$PS_REQUESTS" -ge 3 ] && [ "$PS_REQUESTS" -eq "$(grep -Ec '^[^#]*Invoke-WebRequest' "$PS_HELPER")" ] && printf 'yes' || printf 'no (%s)' "$PS_REQUESTS")"+# PowerShell 7 reads HTTP_PROXY/HTTPS_PROXY/ALL_PROXY for Invoke-WebRequest;+# `Get-AiMemoryNoProxy` supplies -NoProxy there, like the curl branches above.+assert_eq "powershell: every request skips environment proxies" "$PS_REQUESTS" "$PS_REQUESTS_NO_PROXY"# A spooled fixture event names this run's temp tree or targets the fake# `memory.test` host. Live sessions share the spool and may mention that host