Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
buildDirectRecallResult,
buildRecallDirective,
DIRECT_RECALL_TIMEOUT_MS,
isOutOfCredits,
RecallSessionCache,
} from "./services/recall.js";
import { createMemoryActivityReporter } from "./services/activity.js";
Expand Down Expand Up @@ -284,7 +285,13 @@ export const SupermemoryPlugin: Plugin = async (ctx: PluginInput) => {
updateCheck,
]);

if (directRecall.status === "recalled") {
const profileResult = await profileRequest;
if (
directRecall.status === "out-of-credits" ||
(profileResult?.success === false && isOutOfCredits(profileResult.error))
) {
activity.outOfCredits(input.sessionID);
} else if (directRecall.status === "recalled") {
activity.recalled(directRecall.count, directRecall.tokens);
} else if (directRecall.status === "unavailable") {
activity.recallUnavailable();
Expand Down
17 changes: 17 additions & 0 deletions src/services/activity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export type ActivityKind =
| "recalling"
| "recalled"
| "recall-unavailable"
| "out-of-credits"
| "saved"
| "update-available";

Expand All @@ -25,12 +26,14 @@ export interface MemoryActivityReporter {
recalling(query?: string): void;
recalled(count: number, tokens: number): void;
recallUnavailable(): void;
outOfCredits(sessionID: string): void;
saved(): void;
updateAvailable(info: UpdateInfo): void;
}

export const ACTIVITY_TITLE = "Supermemory";
const ACTIVITY_PREFIX = "◪ supermemory · ";
const BILLING_URL = "https://console.supermemory.ai/billing";

function notice(
kind: ActivityKind,
Expand Down Expand Up @@ -62,6 +65,8 @@ export function createMemoryActivityReporterFromSink(
}
};

const creditNoticeSessions = new Set<string>();

return {
recalling(query) {
const suffix = query?.trim() ? `: ${query.trim().slice(0, 100)}` : "";
Expand All @@ -87,6 +92,18 @@ export function createMemoryActivityReporterFromSink(
),
);
},
outOfCredits(sessionID) {
if (creditNoticeSessions.has(sessionID)) return;
creditNoticeSessions.add(sessionID);
emit(
notice(
"out-of-credits",
`recall paused · You've run out of credits. Top up to continue. ${BILLING_URL}`,
"warning",
8_000,
),
);
},
saved() {
emit(notice("saved", "saved this turn", "success", 2_000));
},
Expand Down
14 changes: 12 additions & 2 deletions src/services/recall.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,9 +123,14 @@ function formatDirectRecallContext(hits: RecallHit[]): string {
].join("\n");
}

// The API answers 402 to recall at $0 credits; both SDKs keep the status in the error text.
export function isOutOfCredits(error: string | undefined): boolean {
return /^402 |Status code: 402\b/.test(error ?? "");
}

export interface DirectRecallResult {
context: string;
status: "skipped" | "empty" | "recalled" | "unavailable";
status: "skipped" | "empty" | "recalled" | "unavailable" | "out-of-credits";
count: number;
tokens: number;
}
Expand Down Expand Up @@ -159,7 +164,12 @@ export async function buildDirectRecallResult(options: {

const response = await searchPromise;
if (!response?.success) {
return { context: "", status: "unavailable", count: 0, tokens: 0 };
return {
context: "",
status: isOutOfCredits(response?.error) ? "out-of-credits" : "unavailable",
count: 0,
tokens: 0,
};
}
const hits = normalizeRecallResults(response.results ?? []);
const freshHits = options.cache.takeFresh(options.sessionID, hits);
Expand Down
24 changes: 24 additions & 0 deletions src/v2/runtime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@ interface Harness {
function harness(
config: Partial<V2RuntimeDependencies["config"]> = {},
apiVersion: "legacy" | "v5" = "legacy",
clientOverrides: Record<string, unknown> = {},
): Harness {
const tools = new Map<string, FakeTool>();
const hooks: Harness["hooks"] = {};
Expand Down Expand Up @@ -266,6 +267,7 @@ function harness(
return { success: true, id: "mem_1" };
},
deleteMemory: async () => ({ success: true }),
...clientOverrides,
};

const runtime = new V2Runtime(ctx as unknown as V2Context, {
Expand Down Expand Up @@ -395,6 +397,28 @@ describe("OpenCode 2 runtime", () => {
h.runtime.cleanup();
});

test("an out-of-credits refusal shows one notice per session and leaves the prompt untouched", async () => {
const refusal = '402 {"error":"Search query limit reached","details":"You\'ve run out of credits. Top up to continue."}';
const h = harness({}, "legacy", {
getProfileScoped: async () => ({ success: false, error: refusal, profile: null }),
searchMemoriesForRecall: async () => ({ success: false, error: refusal, results: [] }),
});
await h.runtime.register();
const prompts: Array<[string, string]> = [["s1", "u1"], ["s1", "u2"], ["s1", "u3"], ["s2", "u4"]];
for (const [sessionID, id] of prompts) {
const message = request(id, "how did we set up the database migrations?");
await h.runtime.handleContext({ sessionID, messages: [message] });
expect(texts(message)).toEqual(["how did we set up the database migrations?"]);
}
const notices = h.emitted.filter((event) => event.kind === "out-of-credits");
expect(notices).toHaveLength(2);
expect(notices[0]?.message).toBe(
"◪ supermemory · recall paused · You've run out of credits. Top up to continue. https://console.supermemory.ai/billing",
);
expect(h.emitted.some((event) => event.kind === "recall-unavailable")).toBe(false);
h.runtime.cleanup();
});

test("leaves subagent sessions alone unless captureSubagents is set", async () => {
const h = harness();
await h.runtime.register();
Expand Down
9 changes: 8 additions & 1 deletion src/v2/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ import {
buildDirectRecallResult,
buildRecallDirective,
DIRECT_RECALL_TIMEOUT_MS,
isOutOfCredits,
RecallSessionCache,
type DirectRecallResult,
} from "../services/recall.js";
Expand Down Expand Up @@ -1029,7 +1030,13 @@ export class V2Runtime {
updateCheck,
]);

if (recall.status === "recalled") {
const profileResult = await profileRequest;
if (
recall.status === "out-of-credits" ||
(profileResult?.success === false && isOutOfCredits(profileResult.error))
) {
this.#activity.outOfCredits(sessionID);
} else if (recall.status === "recalled") {
this.#activity.recalled(recall.count, recall.tokens);
} else if (recall.status === "unavailable") {
this.#activity.recallUnavailable();
Expand Down