Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.
feat(memory): size knowledge results by the model's context window
LeoXing4eab7356e57e
diff --git a/apps/node-services/src/memory/README.md b/apps/node-services/src/memory/README.mdindex bf704b7f..f07103d8 100644--- a/apps/node-services/src/memory/README.md+++ b/apps/node-services/src/memory/README.md@@ -270,9 +270,12 @@ with all `alternates`. It adds no model call and no network round trip while theThe top 6 sources carry limited text: a long Chunk gives only a window of about 800 characters from its best querymatch, keeping the time and speaker heading of its message; Raw candidates also keep a bounded directory of thematching and adjacent Chunks for a follow-up read of missing facts or truncated text.-Memory keeps every search and read result within 12,000 bytes of JSON; the CLI passes results through-unchanged. A Runtime cuts the middle out of a tool result above its output limit, which Codex sets as low-as 4,000 tokens of four bytes each for a small model window, so a bounded result reaches the Agent whole.+Memory keeps every search and read result within an output budget of JSON bytes; the CLI passes results+through unchanged. The budget is 15% of the context window of the model the owner's calls run on, at four+bytes per token, and at most 100,000 bytes; the window comes from the owner's Computer through the model+call layer. An unknown window, or an offline Computer, keeps 12,000 bytes. A Runtime cuts the middle out+of a tool result above its own output limit, which the Daemon sets to a sixteenth of the window, between+4,000 and 12,000 tokens, so a budget above that limit reaches the Agent cut.Session facts take at most a quarter of the budget, the best-ranked first. If the result is still toolarge, inline chunks go from the lowest rank up until only the top candidate's best chunk is left, thencandidates go from the lowest rank up, then that chunk; the top candidate always stays, and every keptdiff --git a/apps/node-services/src/memory/knowledge-query.ts b/apps/node-services/src/memory/knowledge-query.tsindex 4078a0e0..03a05861 100644--- a/apps/node-services/src/memory/knowledge-query.ts+++ b/apps/node-services/src/memory/knowledge-query.ts@@ -33,12 +33,17 @@ const INLINE_CONTENT_SOURCES = 6;const INLINE_CONTENT_CHARS = 800;const INLINE_CONTENT_BUDGET_CHARS = 6_000;const INLINE_CONTENT_SEPARATOR = "\n\n…\n\n";-// A Runtime cuts the middle out of a tool result above its output limit, and-// Codex sets that limit as low as 4,000 tokens of four bytes each for a small-// model window. Search and read results stay within this many bytes of JSON,-// leaving room for the CLI's labels, so the Agent sees each result whole.-const KNOWLEDGE_OUTPUT_BUDGET_BYTES = 12_000;-const FACT_BUDGET_BYTES = KNOWLEDGE_OUTPUT_BUDGET_BYTES / 4;+// One search or read result may take this share of the model's context+// window, measured at four bytes per token as Codex estimates tool output.+// The rest of the window holds the instructions, the history and other tool+// results of the same turn.+const WINDOW_OUTPUT_SHARE = 0.15;+const BYTES_PER_TOKEN = 4;+// A large window still keeps one result this small.+const MAX_KNOWLEDGE_OUTPUT_BYTES = 100_000;+// The budget when the model's window is unknown: Codex's smallest tool output+// limit for a small window, 4,000 tokens of four bytes, less the CLI's labels.+const DEFAULT_KNOWLEDGE_OUTPUT_BYTES = 12_000;// A section that does not fit still returns a page this large, so every read// makes progress.const MIN_SECTION_PAGE_BYTES = 512;@@ -60,11 +65,29 @@ export class PersonalKnowledgeEvidenceNotFoundError extends Error {* My pages, mail, Pocket Notes, the Profile, the published Wiki and Daily and* Weekly reports. Each item names its source kind.*/+/**+ * The most bytes of JSON one search or read result may take for a model with+ * this context window in tokens. An unknown window gets the default.+ */+export function knowledgeOutputBudget(+ contextWindow: number | undefined,+): number {+ if (contextWindow === undefined) return DEFAULT_KNOWLEDGE_OUTPUT_BYTES;+ return Math.min(+ Math.floor(contextWindow * WINDOW_OUTPUT_SHARE * BYTES_PER_TOKEN),+ MAX_KNOWLEDGE_OUTPUT_BYTES,+ );+}+export async function queryPersonalKnowledge(dataRoot: string,input: PersonalKnowledgeQueryRequest,- options: { chunkSearch?: ChunkSearchProvider } = {},+ options: {+ chunkSearch?: ChunkSearchProvider;+ outputBudgetBytes?: number;+ } = {},): Promise<PersonalKnowledgeQueryResponse> {+ const budget = options.outputBudgetBytes ?? DEFAULT_KNOWLEDGE_OUTPUT_BYTES;const workspaceRoot = agentWorkspaceRoot(dataRoot, input.agent_id);// Facts rank in their own channel so they never displace Raw candidates.const [rawResult, facts] = await Promise.all([@@ -130,7 +153,8 @@ export async function queryPersonalKnowledge(fittingPrefix(facts.length,(count) => outputBytes(facts.slice(0, count)),- FACT_BUDGET_BYTES,+ // Facts take at most a quarter, so they never crowd out candidates.+ budget / 4,),);let itemCount = selected.length;@@ -199,15 +223,17 @@ export async function queryPersonalKnowledge(}return last !== undefined && contentChunks.delete(last);};- while (outputBytes(response()) > KNOWLEDGE_OUTPUT_BUDGET_BYTES && dropOne())- trimmed = true;+ while (outputBytes(response()) > budget && dropOne()) trimmed = true;return response();}export async function readPersonalKnowledgeEvidence(dataRoot: string,input: PersonalKnowledgeEvidenceReadRequest,- options: { rawSourceProvider?: ChunkSearchProvider } = {},+ options: {+ rawSourceProvider?: ChunkSearchProvider;+ outputBudgetBytes?: number;+ } = {},): Promise<PersonalKnowledgeEvidenceReadResponse> {if (!input.evidence_id.startsWith("raw_")) {throw new PersonalKnowledgeEvidenceNotFoundError();@@ -215,6 +241,7 @@ export async function readPersonalKnowledgeEvidence(return readRawEvidence(agentWorkspaceRoot(dataRoot, input.agent_id),input,+ options.outputBudgetBytes ?? DEFAULT_KNOWLEDGE_OUTPUT_BYTES,options.rawSourceProvider,);}@@ -267,6 +294,7 @@ function rawDirectory(chunks: SourceChunk[]) {async function readRawEvidence(workspaceRoot: string,input: PersonalKnowledgeEvidenceReadRequest,+ budget: number,rawSourceProvider?: ChunkSearchProvider,): Promise<PersonalKnowledgeEvidenceReadResponse> {const { sources } = await resolveSearchRawSources(@@ -318,7 +346,7 @@ async function readRawEvidence(};// Sections share what the rest of the response leaves in request order; a// section's unused share carries over to the ones after it.- let remaining = KNOWLEDGE_OUTPUT_BUDGET_BYTES - outputBytes(response);+ let remaining = budget - outputBytes(response);pages.forEach(({ chunk, offset }, index) => {const share = Math.max(Math.floor(remaining / (pages.length - index)),diff --git a/apps/node-services/src/memory/server.ts b/apps/node-services/src/memory/server.tsindex 002dd1bf..46f7c023 100644--- a/apps/node-services/src/memory/server.ts+++ b/apps/node-services/src/memory/server.ts@@ -24,10 +24,12 @@ import {PersonalKnowledgeGraphNotFoundError,} from "./graph-visualization.js";import {+ knowledgeOutputBudget,PersonalKnowledgeEvidenceNotFoundError,queryPersonalKnowledge,readPersonalKnowledgeEvidence,} from "./knowledge-query.js";+import { memoryContextWindow } from "./llm.js";import {MemoryRebuildUnavailableError,type MemoryScheduler,@@ -65,6 +67,7 @@ export async function startMemoryServer(options: {graphVisualization?: typeof getPersonalKnowledgeGraphVisualization;query?: typeof queryPersonalKnowledge;evidenceRead?: typeof readPersonalKnowledgeEvidence;+ contextWindow?: typeof memoryContextWindow;listMemoryEntries?: typeof listMemoryEntries;getMemoryEntry?: typeof getMemoryEntry;chunkSearch?: ChunkSearchProvider;@@ -346,6 +349,19 @@ export async function startMemoryServer(options: {}},);+ // Results are sized for the model the owner's calls run on, which the+ // owner's Computer reports; an unknown model or an offline Computer keeps+ // the default size, since a search needs no model.+ const outputBudgetBytes = async (input: {+ tenant_id: string;+ user_artifact_owner_actor_id: string;+ }) =>+ knowledgeOutputBudget(+ await (options.contextWindow ?? memoryContextWindow)({+ tenantId: input.tenant_id,+ ownerActorId: input.user_artifact_owner_actor_id,+ }).catch(() => undefined),+ );app.post("/internal/v1/query", requireAuth, async (context) => {const input = parseQueryRequest(await readJsonBody(context));return respondJson(@@ -353,6 +369,7 @@ export async function startMemoryServer(options: {200,await (options.query ?? queryPersonalKnowledge)(options.dataRoot, input, {chunkSearch: options.chunkSearch,+ outputBudgetBytes: await outputBudgetBytes(input),}),);});@@ -366,6 +383,7 @@ export async function startMemoryServer(options: {options.evidenceRead ?? readPersonalKnowledgeEvidence)(options.dataRoot, input, {rawSourceProvider: options.chunkSearch,+ outputBudgetBytes: await outputBudgetBytes(input),});return respondJson(context, 200, result);} catch (error) {diff --git a/apps/node-services/tests/memory/raw-knowledge-query.test.ts b/apps/node-services/tests/memory/raw-knowledge-query.test.tsindex 9d8d4433..01daf3fb 100644--- a/apps/node-services/tests/memory/raw-knowledge-query.test.ts+++ b/apps/node-services/tests/memory/raw-knowledge-query.test.ts@@ -9,6 +9,7 @@ import {import { startMemoryServer } from "../../src/memory/server.js";import { MemoryScheduler } from "../../src/memory/scheduler.js";import {+ knowledgeOutputBudget,queryPersonalKnowledge as queryWithDatabase,readPersonalKnowledgeEvidence as readWithDatabase,} from "../../src/memory/knowledge-query.js";@@ -1118,6 +1119,45 @@ describe("knowledge output budget", () => {}});+ it("sizes the budget by the model's context window", () => {+ expect(knowledgeOutputBudget(undefined)).toBe(12_000);+ expect(knowledgeOutputBudget(8_192)).toBe(4_915);+ expect(knowledgeOutputBudget(64_896)).toBe(38_937);+ expect(knowledgeOutputBudget(1_000_000)).toBe(100_000);+ });++ it("keeps more of a result within a larger budget", async () => {+ const fixtureData = await fixture();+ const matches = Array.from({ length: 6 }, (_, index) => {+ const { input, markdown } = document(index, [wide(index, 1_200)]);+ const source = storeDocumentSource(fixtureData.root, input);+ const chunk = chunkSource(markdown).at(-1)!;+ return {+ chunkId: chunk.id,+ mergedChunkIds: [chunk.id],+ sourceId: source.id,+ score: 1 / (61 + index),+ };+ });+ const search = (outputBudgetBytes: number) =>+ queryPersonalKnowledge(fixtureData.root, request("Report"), {+ chunkSearch: { search: async () => matches },+ outputBudgetBytes,+ });++ const small = await search(12_000);+ const large = await search(knowledgeOutputBudget(64_896));+ expect(small.gaps.map((gap) => gap.code)).toContain("results_trimmed");+ expect(large.gaps).toEqual([]);+ expect(large.status).toBe("grounded");+ expect(Buffer.byteLength(JSON.stringify(large))).toBeLessThanOrEqual(+ knowledgeOutputBudget(64_896),+ );+ expect(large.items.filter((item) => item.content).length).toBeGreaterThan(+ small.items.filter((item) => item.content).length,+ );+ });+it("keeps a result that fits whole", async () => {const fixtureData = await fixture();const source = storeDocumentSource(fixtureData.root, meetingDocument);diff --git a/apps/node-services/tests/memory/server.test.ts b/apps/node-services/tests/memory/server.test.tsindex f7c8413a..cd7e7770 100644--- a/apps/node-services/tests/memory/server.test.ts+++ b/apps/node-services/tests/memory/server.test.ts@@ -364,14 +364,25 @@ describe("Memory server", () => {const dataRoot = await fs.mkdtemp(path.join(os.tmpdir(), "memory-server-"));roots.push(dataRoot);const received: unknown[] = [];+ const budgets: unknown[] = [];const server = await startMemoryServer({dataRoot,host: "127.0.0.1",port: 0,scheduler: new MemoryScheduler(schedule, async () => undefined),serviceToken: "memory-token",- query: async (_root, input) => {+ contextWindow: async (owner) => {+ if (owner.ownerActorId === "human_offline")+ throw new Error("computer_offline");+ expect(owner).toEqual({+ tenantId: "tenant_1",+ ownerActorId: "human_1",+ });+ return 64_896;+ },+ query: async (_root, input, options) => {received.push(input);+ budgets.push(options?.outputBudgetBytes);return {gaps: [{ code: "no_relevant_evidence" }],indexedAt: null,@@ -406,6 +417,13 @@ describe("Memory server", () => {status: "empty",});expect(received).toEqual([body]);+ // 15% of the owner's model window, at four bytes per token.+ expect(budgets).toEqual([38_937]);+ await post(+ { ...body, user_artifact_owner_actor_id: "human_offline" },+ "memory-token",+ );+ expect(budgets.at(-1)).toBe(12_000);for (const removed of [{ source: "personal_knowledge" },{ node_types: ["Session"] },