Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

fix(install-hooks): authenticate generated TS integrations under --apply

evanmaranzano151d4dbdd7ab
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e928436e..1568d260 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Fixed
+- generated TypeScript integrations (`--agent open-code`, `omp`, `pi`,
+ `openclaw`) authenticate again under `install-hooks --apply`. Since #552
+ the bearer is deliberately omitted from the rendered file and persisted to
+ the 0600 `<data_dir>/auth-token` file, but only the native hook runtimes
+ learned to read it back: the generated TS adapters kept rendering
+ `TOKEN = null` with no runtime resolution, so every request they make
+ (hook capture, spool drain, handoff fetch) goes out unauthenticated and is
+ rejected by a Bearer-enabled server. The templates now render a
+ `resolveToken()` helper (static embed, then `AI_MEMORY_AUTH_TOKEN`, then
+ the auth-token file) used by `authHeaders()` and the spool writer.
+ `fetchHandoff()` in the same adapters also ignored `response.ok`, so a
+ 401 error body could be injected into model context as if it were a
+ handoff; non-OK responses now return `undefined` like other failures.
- `bootstrap` now retries a chunk's LLM call on a transient error before
giving up, instead of letting one blip discard the whole multi-chunk run
(#617). A provider `5xx`/`429` or a transport timeout/connect failure on
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index 078999c2..d9c45a29 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -2917,6 +2917,7 @@ fn add_hook_spooling(source: String) -> Result<String> {
}"#;
const ENQUEUE_ANCHOR: &str = "function enqueueHook(";
let runtime = crate::commands::render_shared::ts_spool_runtime();
+ let resolve_fn = crate::commands::render_shared::ts_resolve_token_fn();
if !source.contains(FETCH_BLOCK) {
anyhow::bail!(
"TS integration template drifted: the hook delivery block the \
@@ -2927,7 +2928,11 @@ fn add_hook_spooling(source: String) -> Result<String> {
anyhow::bail!("TS integration template drifted: enqueueHook anchor not unique");
}
let mut out = source.replacen(FETCH_BLOCK, FETCH_REPLACEMENT, 1);
- out = out.replacen(ENQUEUE_ANCHOR, &format!("{runtime}{ENQUEUE_ANCHOR}"), 1);
+ out = out.replacen(
+ ENQUEUE_ANCHOR,
+ &format!("{resolve_fn}{runtime}{ENQUEUE_ANCHOR}"),
+ 1,
+ );
// Drain the offline spool alongside every queue flush, and extend the
// imports the runtime needs.
let drain_anchor =
@@ -2986,7 +2991,8 @@ function timeoutSignal(ms: number): AbortSignal | undefined {{
}}
function authHeaders(): Record<string, string> {{
- return TOKEN ? {{ Authorization: `Bearer ${{TOKEN}}` }} : {{}};
+ const token = resolveToken();
+ return token ? {{ Authorization: `Bearer ${{token}}` }} : {{}};
}}
const HOOK_QUEUE_MAX = 100;
@@ -3222,6 +3228,7 @@ async function fetchHandoff(cwd: string, id: string | undefined): Promise<string
headers: authHeaders(),
signal: timeoutSignal(1000),
}});
+ if (!response.ok) return undefined;
const text = (await response.text()).trim();
return text.length > 0 ? text : undefined;
}} catch (_e) {{
@@ -3716,7 +3723,8 @@ function timeoutSignal(ms: number): AbortSignal | undefined {{
}}
function authHeaders(): Record<string, string> {{
- return TOKEN ? {{ Authorization: `Bearer ${{TOKEN}}` }} : {{}};
+ const token = resolveToken();
+ return token ? {{ Authorization: `Bearer ${{token}}` }} : {{}};
}}
const HOOK_QUEUE_MAX = 100;
@@ -3936,6 +3944,7 @@ async function fetchHandoff(cwd: string, id: string | undefined): Promise<string
headers: authHeaders(),
signal: timeoutSignal(1000),
}});
+ if (!response.ok) return undefined;
const text = (await response.text()).trim();
return text.length > 0 ? text : undefined;
}} catch (_e) {{
@@ -7612,7 +7621,7 @@ model = "gpt-5"
assert!(plugin.contains("handoffFetches.delete(id);"));
assert!(plugin.contains("preCompactLast.delete(id);"));
assert!(plugin.contains("postHook(\"user-prompt\""));
- assert!(plugin.contains("Bearer ${TOKEN}"));
+ assert!(plugin.contains("Bearer ${token}"));
assert!(plugin.contains("tok"));
assert!(
!plugin.contains(r#""session.created": async"#),
@@ -7684,6 +7693,30 @@ model = "gpt-5"
assert_generated_ts_uses_bounded_hook_queue(&plugin);
}
+ #[test]
+ fn opencode_plugin_resolves_token_at_runtime_when_not_embedded() {
+ let plugin = build_opencode_plugin("http://127.0.0.1:49374", None, None);
+ assert!(plugin.contains("function resolveToken("));
+ assert!(plugin.contains("const token = resolveToken();"));
+ assert!(plugin.contains("if (!response.ok) return undefined;"));
+ }
+
+ #[test]
+ fn omp_extension_resolves_token_at_runtime_when_not_embedded() {
+ let extension = build_omp_extension("http://127.0.0.1:49374", None, None);
+ assert!(extension.contains("function resolveToken("));
+ assert!(extension.contains("process.env.AI_MEMORY_AUTH_TOKEN"));
+ assert!(extension.contains("auth-token"));
+ assert!(extension.contains("if (!response.ok) return undefined;"));
+ }
+
+ #[test]
+ fn omp_extension_prefers_statically_embedded_token() {
+ let extension = build_omp_extension("http://127.0.0.1:49374", Some("tok"), None);
+ assert!(extension.contains("function resolveToken("));
+ assert!(extension.contains("if (TOKEN) return TOKEN;"));
+ }
+
// ----------------------------------------------------------------
// OMP tests
// ----------------------------------------------------------------
@@ -7718,7 +7751,7 @@ model = "gpt-5"
"applyMarkerParams(url, typeof payload.cwd === \"string\" ? payload.cwd : undefined);"
));
assert!(extension.contains("applyMarkerParams(url, cwd);"));
- assert!(extension.contains("Bearer ${TOKEN}"));
+ assert!(extension.contains("Bearer ${token}"));
assert!(extension.contains("tok"));
assert!(
extension
@@ -8125,7 +8158,7 @@ model = "gpt-5"
assert!(extension.contains("payload?.result?.isError"));
assert!(extension.contains("response.ok"));
assert!(extension.contains("signal: mcpSignal(signal)"));
- assert!(extension.contains("Bearer ${TOKEN}"));
+ assert!(extension.contains("Bearer ${token}"));
assert!(extension.contains("tok"));
assert!(extension.contains("import { execFileSync } from \"node:child_process\";"));
assert!(!extension.contains(".omp"));
diff --git a/crates/ai-memory-cli/src/commands/openclaw_plugin.rs b/crates/ai-memory-cli/src/commands/openclaw_plugin.rs
index e3df6881..947e65e9 100644
--- a/crates/ai-memory-cli/src/commands/openclaw_plugin.rs
+++ b/crates/ai-memory-cli/src/commands/openclaw_plugin.rs
@@ -8,7 +8,9 @@ use anyhow::{Context, Result};
use crate::cli::InstallHooksArgs;
use crate::commands::apply_shared::{ApplyOutcome, apply_atomic};
-use crate::commands::render_shared::{ts_capture_policy_v1, ts_spool_runtime, ts_string_literal};
+use crate::commands::render_shared::{
+ ts_capture_policy_v1, ts_resolve_token_fn, ts_spool_runtime, ts_string_literal,
+};
pub(crate) const PLUGIN_ID: &str = "ai-memory";
pub(crate) const PACKAGE_NAME: &str = "@ai-memory/openclaw-plugin";
@@ -302,6 +304,7 @@ fn build_plugin(
let token_line = auth_token
.map(|t| format!("const TOKEN: string | null = {};\n", ts_string_literal(t)))
.unwrap_or_else(|| "const TOKEN: string | null = null;\n".to_string());
+ let resolve_fn = ts_resolve_token_fn();
let apply_marker_params = apply_marker_params_ts(project_strategy);
let capture_policy = ts_capture_policy_v1();
format!(
@@ -317,7 +320,7 @@ import {{ homedir }} from "node:os";
const SERVER = {server_literal}.replace(/\/+$/, "");
const AGENT = "openclaw";
-{token_line}
+{token_line}{resolve_fn}
{capture_policy}
function timeoutSignal(ms: number): AbortSignal | undefined {{
@@ -327,7 +330,8 @@ function timeoutSignal(ms: number): AbortSignal | undefined {{
}}
function authHeaders(): Record<string, string> {{
- return TOKEN ? {{ Authorization: `Bearer ${{TOKEN}}` }} : {{}};
+ const token = resolveToken();
+ return token ? {{ Authorization: `Bearer ${{token}}` }} : {{}};
}}
function findMarker(cwd: string | undefined): string | undefined {{
@@ -485,6 +489,7 @@ async function fetchHandoff(event: any, ctx: any): Promise<string | undefined> {
headers: authHeaders(),
signal: timeoutSignal(1000),
}});
+ if (!response.ok) return undefined;
const text = (await response.text()).trim();
return text.length > 0 ? text : undefined;
}} catch (_e) {{
@@ -642,10 +647,18 @@ mod tests {
assert!(plugin.contains("const policy = capturePolicy(body"));
assert!(plugin.contains("body: JSON.stringify(policy.payload)"));
assert!(plugin.contains("prependContext: handoff"));
- assert!(plugin.contains("Bearer ${TOKEN}"));
+ assert!(plugin.contains("Bearer ${token}"));
assert!(plugin.contains("tok"));
}
+ #[test]
+ fn openclaw_plugin_resolves_token_at_runtime_when_not_embedded() {
+ let plugin = build_plugin("http://127.0.0.1:49374", None, None);
+ assert!(plugin.contains("function resolveToken("));
+ assert!(plugin.contains("const token = resolveToken();"));
+ assert!(plugin.contains("if (!response.ok) return undefined;"));
+ }
+
#[test]
fn openclaw_plugin_bakes_repo_root_default() {
let plugin = build_plugin("http://127.0.0.1:49374", Some("tok"), Some("repo-root"));
diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rs
index bd5bd719..1c0e246c 100644
--- a/crates/ai-memory-cli/src/commands/render_shared.rs
+++ b/crates/ai-memory-cli/src/commands/render_shared.rs
@@ -1799,6 +1799,46 @@ fn claude_code_windows_command_is_unchanged_by_the_codex_fix() {
/// `hook-spool` on-disk contract (same filenames, same `SpoolEntry` JSON,
/// same permissions) plus a self-drain. Callers only need `TOKEN`,
/// `timeoutSignal`, and the node `join`/`homedir`/fs imports in scope.
+/// Runtime credential fallback shared by every generated TypeScript
+/// integration. #552 moved the bearer out of generated files into a 0600
+/// `<data_dir>/auth-token` file and taught the native hook runtimes to read
+/// it back, but the generated TS adapters kept rendering `TOKEN = null`
+/// under `--apply` and had no equivalent read-back, so every request went
+/// out unauthenticated against a Bearer-enabled server. Generated files
+/// call this from `authHeaders()` and the spool writer. Needs `TOKEN`,
+/// `join`, `homedir`, `existsSync`, and `readFileSync` (as `readMarkerText`)
+/// in scope — the same surface `ts_spool_runtime` already assumes.
+pub(crate) fn ts_resolve_token_fn() -> &'static str {
+ r#"
+// Resolve the server bearer per request. A statically embedded token wins
+// (inline installs), then the environment, then the 0600 auth-token file
+// that `install-hooks --apply` persists under the data dir (#552).
+function resolveToken(): string | null {
+ if (TOKEN) return TOKEN;
+ const envToken = process.env.AI_MEMORY_AUTH_TOKEN;
+ if (envToken && envToken.trim()) return envToken.trim();
+ try {
+ const dataDir = process.env.AI_MEMORY_DATA_DIR?.trim();
+ const base = dataDir
+ ? dataDir
+ : process.platform === "darwin"
+ ? join(homedir(), "Library", "Application Support", "ai-memory")
+ : process.platform === "win32"
+ ? join(process.env.LOCALAPPDATA ?? join(homedir(), "AppData", "Local"), "ai-memory")
+ : join(process.env.XDG_DATA_HOME?.trim() || join(homedir(), ".local", "share"), "ai-memory");
+ const tokenPath = join(base, "auth-token");
+ if (existsSync(tokenPath)) {
+ const fromFile = readMarkerText(tokenPath, "utf-8").trim();
+ if (fromFile) return fromFile;
+ }
+ } catch {
+ // Best effort: an unreadable token file leaves auth absent.
+ }
+ return null;
+}
+"#
+}
+
pub(crate) fn ts_spool_runtime() -> &'static str {
r#"
// ---- offline spool (#580): the same on-disk contract as `ai-memory hook` ----
@@ -1831,7 +1871,7 @@ function spoolFailedHook(url: URL | string, payload: Record<string, unknown>): v
const key = `ts${createdMs.toString(16)}${Math.floor(Math.random() * 0xffffffff).toString(16)}`;
const u = new URL(String(url));
if (!u.searchParams.has("ingest_key")) u.searchParams.set("ingest_key", key);
- const token = TOKEN;
+ const token = resolveToken();
const entry = {
url: u.toString(),
body: JSON.stringify(payload),