Skip to content

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

Rust

fix(ts): isolate shared probe cancellation

AkitaOnRails73b9a29c366e
diff --git a/companions/ai-memory-ts/CHANGELOG.md b/companions/ai-memory-ts/CHANGELOG.md
index 9b60093a..3d27abe6 100644
--- a/companions/ai-memory-ts/CHANGELOG.md
+++ b/companions/ai-memory-ts/CHANGELOG.md
@@ -10,6 +10,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- Capability initialization is owned by the client rather than its first
+ caller. Concurrent callers now wait with independent abort signals and
+ deadlines; cancelling one does not fail or delay the others. (#1815)
+
- Initialized the MCP session before the first `callTool`, so raw tool calls
work with `--http-stateful` without a preceding wrapped call. Raw calls
still skip `tools/list` and schema checks. (#1816)
diff --git a/companions/ai-memory-ts/src/core.ts b/companions/ai-memory-ts/src/core.ts
index e8587c4d..58450ddc 100644
--- a/companions/ai-memory-ts/src/core.ts
+++ b/companions/ai-memory-ts/src/core.ts
@@ -13,7 +13,7 @@ import {
type SessionInfo,
type ToolIndex,
} from "./capabilities.js";
-import { ArgumentError, ProtocolError, ToolError } from "./errors.js";
+import { AbortError, ArgumentError, ConfigError, ProtocolError, TimeoutError, ToolError } from "./errors.js";
import { resolveScope, type Scope } from "./scope.js";
import type { CallOptions, Transport } from "./transport.js";
@@ -43,6 +43,55 @@ export function argsObject<T extends object>(value: T | undefined, where: string
return value;
}
+const MAX_TIMEOUT_MS = 2_147_483_647;
+
+/** Wait for client-owned initialization without lending it a caller's cancellation. */
+function waitForShared<T>(shared: Promise<T>, options?: CallOptions): Promise<T> {
+ const signal = options?.signal;
+ if (signal?.aborted === true) {
+ return Promise.reject(new AbortError("aborted by the caller while waiting for initialization", false));
+ }
+ const timeoutMs = options?.timeoutMs;
+ if (
+ timeoutMs !== undefined &&
+ (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > MAX_TIMEOUT_MS)
+ ) {
+ return Promise.reject(
+ new ConfigError(`timeoutMs must be an integer between 1 and ${MAX_TIMEOUT_MS}`),
+ );
+ }
+ if (signal === undefined && timeoutMs === undefined) return shared;
+
+ return new Promise<T>((resolve, reject) => {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const cleanup = (): void => {
+ if (timer !== undefined) clearTimeout(timer);
+ signal?.removeEventListener("abort", aborted);
+ };
+ const aborted = (): void => {
+ cleanup();
+ reject(new AbortError("aborted by the caller while waiting for initialization", false));
+ };
+ signal?.addEventListener("abort", aborted, { once: true });
+ if (timeoutMs !== undefined) {
+ timer = setTimeout(() => {
+ cleanup();
+ reject(new TimeoutError(`initialization got no response within ${timeoutMs} ms`, false));
+ }, timeoutMs);
+ }
+ shared.then(
+ (value) => {
+ cleanup();
+ resolve(value);
+ },
+ (error: unknown) => {
+ cleanup();
+ reject(error);
+ },
+ );
+ });
+}
+
/** The first `{ type: "text", text }` item of a tool result's content. */
function firstText(content: unknown): string | undefined {
if (!Array.isArray(content)) return undefined;
@@ -73,23 +122,27 @@ export class Core {
/** The handshake is needed even by calls that skip schema checks. */
#initialize(options?: CallOptions): Promise<SessionInfo> {
+ if (options?.signal?.aborted === true) {
+ return Promise.reject(new AbortError("aborted by the caller before initialization", false));
+ }
if (this.#session === undefined) {
- const session = initialize(this.transport, options);
+ const session = initialize(this.transport);
this.#session = session;
session.catch(() => {
if (this.#session === session) this.#session = undefined;
});
}
- return this.#session;
+ return waitForShared(this.#session, options);
}
/** `initialize` + `tools/list`, probed once per client and cached. */
toolIndex(options?: CallOptions): Promise<ToolIndex> {
+ if (options?.signal?.aborted === true) {
+ return Promise.reject(new AbortError("aborted by the caller before initialization", false));
+ }
if (this.#index === undefined) {
- const session = this.#initialize(options);
- const probe = session.then((info) =>
- probeTools(this.transport, info, options),
- );
+ const session = this.#initialize();
+ const probe = session.then((info) => probeTools(this.transport, info));
this.#index = probe;
// A failed probe is not cached: the next call probes again.
probe.catch(() => {
@@ -101,7 +154,7 @@ export class Core {
}
});
}
- return this.#index;
+ return waitForShared(this.#index, options);
}
/** Drop the handshake and tool index so refresh opens a new session. */
diff --git a/companions/ai-memory-ts/test/unit/client.test.ts b/companions/ai-memory-ts/test/unit/client.test.ts
index f63a0fbf..da562eff 100644
--- a/companions/ai-memory-ts/test/unit/client.test.ts
+++ b/companions/ai-memory-ts/test/unit/client.test.ts
@@ -4,6 +4,7 @@ import { describe, it } from "node:test";
import { AiMemoryClient } from "../../src/client.js";
import { TOOL_COVERAGE } from "../../src/coverage.js";
import {
+ AbortError,
ArgumentError,
PreconditionFailedError,
ProtocolError,
@@ -437,6 +438,66 @@ describe("reads", () => {
});
describe("capability gating", () => {
+ it("cancels concurrent capability waits independently", async () => {
+ for (const heldMethod of ["initialize", "tools/list"] as const) {
+ for (const cancelled of ["first", "second"] as const) {
+ const server = new FakeServer();
+ let announce!: () => void;
+ let release!: () => void;
+ const started = new Promise<void>((resolve) => { announce = resolve; });
+ const held = new Promise<void>((resolve) => { release = resolve; });
+ server.mcp = async (request) => {
+ const body = request.body as { id?: number; method: string };
+ const reply = (result: unknown) => json({ jsonrpc: "2.0", id: body.id, result });
+ if (body.method === "initialize") {
+ if (heldMethod === "initialize") {
+ announce();
+ await held;
+ }
+ return reply({
+ protocolVersion: "2025-03-26",
+ serverInfo: { name: "ai-memory", version: "3.2.10" },
+ capabilities: {},
+ });
+ }
+ if (body.method === "tools/list") {
+ if (heldMethod === "tools/list") {
+ announce();
+ await held;
+ }
+ return reply({
+ tools: [{
+ name: "memory_status",
+ inputSchema: { properties: { workspace: {}, project: {} } },
+ }],
+ });
+ }
+ if (body.method === "tools/call") {
+ return reply({ content: [{ type: "text", text: JSON.stringify(payloads.status) }] });
+ }
+ throw new Error(`unexpected method ${body.method}`);
+ };
+ const memory = new AiMemoryClient({
+ serverUrl: "http://127.0.0.1:49374",
+ scope: SCOPE,
+ fetch: server.fetch,
+ });
+ const firstController = new AbortController();
+ const secondController = new AbortController();
+ const first = memory.status({}, { signal: firstController.signal });
+ await started;
+ const second = memory.status({}, { signal: secondController.signal });
+
+ (cancelled === "first" ? firstController : secondController).abort();
+ const cancelledCall = cancelled === "first" ? first : second;
+ await assert.rejects(cancelledCall, AbortError);
+ release();
+ const survivingCall = cancelled === "first" ? second : first;
+ assert.equal((await survivingCall).scope.project, "app");
+ }
+ }
+ });
+
it("a server without expected_page_id refuses a conditional write before tools/call", async () => {
const { server, memory } = setup();
const write = server.schemas["memory_write_page"];