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.
fix(memory): size knowledge results in characters that fit both Runtimes
LeoXingbe73e08ec099
diff --git a/apps/computer/local-daemon/internal/provider/native/claude_policy.go b/apps/computer/local-daemon/internal/provider/native/claude_policy.goindex 9bb38979..7426c434 100644--- a/apps/computer/local-daemon/internal/provider/native/claude_policy.go+++ b/apps/computer/local-daemon/internal/provider/native/claude_policy.go@@ -148,12 +148,14 @@ func claudeSettings(contextWindow int) string {if contextWindow > 0 {limit := toolOutputTokenLimit(contextWindow)// One tool result keeps the share of the window Codex gives it.- // Claude measures Bash output in characters, and one character can be- // a whole token, so the token limit bounds characters too. Longer- // Bash output is saved to a file the model reads from, a longer Read- // is refused so the model reads a range, and longer MCP output is cut- // with a note to page.- settings["bashOutputMaxChars"] = limit+ // Claude measures Bash output in characters. Codex counts four bytes+ // per token, so it keeps limit×4/3 characters of three-byte text such+ // as CJK, where one character is about one token; Bash keeps as many,+ // so the same text stays inline on both. Longer Bash output is saved+ // to a file the model reads from, a longer Read is refused so the+ // model reads a range, and longer MCP output is cut with a note to+ // page.+ settings["bashOutputMaxChars"] = limit * 4 / 3settingsEnv["CLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS"] = strconv.Itoa(limit)settingsEnv["MAX_MCP_OUTPUT_TOKENS"] = strconv.Itoa(limit)}diff --git a/apps/computer/local-daemon/internal/provider/native/claude_runtime_test.go b/apps/computer/local-daemon/internal/provider/native/claude_runtime_test.goindex 6a904ae6..f8c5cdc9 100644--- a/apps/computer/local-daemon/internal/provider/native/claude_runtime_test.go+++ b/apps/computer/local-daemon/internal/provider/native/claude_runtime_test.go@@ -331,7 +331,7 @@ func TestClaudeSettingsFollowContextWindow(t *testing.T) {return settings, env}small, env := settingsFor(64896)- if small["autoCompactWindow"] != float64(200000) || small["bashOutputMaxChars"] != float64(9734) ||+ if small["autoCompactWindow"] != float64(200000) || small["bashOutputMaxChars"] != float64(12978) ||env["CLAUDE_CODE_MAX_CONTEXT_TOKENS"] != "64896" || env["CLAUDE_CODE_DISABLE_1M_CONTEXT"] != "1" ||env["CLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS"] != "9734" || env["MAX_MCP_OUTPUT_TOKENS"] != "9734" ||env["CLAUDE_CODE_DISABLE_BACKGROUND_TASKS"] != "1" {@@ -340,7 +340,7 @@ func TestClaudeSettingsFollowContextWindow(t *testing.T) {// A large window caps tool output at Claude's own Read and MCP limit;// only a 1M one keeps the [1m] variants.large, env := settingsFor(400000)- if large["bashOutputMaxChars"] != float64(25000) || env["CLAUDE_CODE_MAX_CONTEXT_TOKENS"] != "400000" ||+ if large["bashOutputMaxChars"] != float64(33333) || env["CLAUDE_CODE_MAX_CONTEXT_TOKENS"] != "400000" ||env["CLAUDE_CODE_DISABLE_1M_CONTEXT"] != "1" || env["MAX_MCP_OUTPUT_TOKENS"] != "25000" {t.Fatalf("400k settings = %v", large)}diff --git a/apps/node-services/src/memory/README.md b/apps/node-services/src/memory/README.mdindex f9ff701c..a7117271 100644--- a/apps/node-services/src/memory/README.md+++ b/apps/node-services/src/memory/README.md@@ -270,12 +270,15 @@ 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 an output budget of JSON bytes; the CLI passes results-through unchanged. A Runtime cuts the middle out of a tool result above its output limit, which the Daemon-sets to 15% of the model's context window, between 4,000 and 25,000 tokens of four bytes each. The budget-is 90% of that limit for the model the owner's calls run on, leaving room for the CLI's labels, so a-bounded result reaches the Agent whole; the window comes from the owner's Computer through the model call-layer. An unknown window, or an offline Computer, keeps 12,000 bytes.+Memory keeps every search and read result within an output budget of JSON characters (UTF-16 units); the+CLI passes results through unchanged. The Daemon limits one tool result to 15% of the model's context+window, between 4,000 and 25,000 tokens, and to 12,000 tokens when the window is unknown. Codex counts four+bytes per token and cuts the middle out of a longer result, so it keeps limit×4/3 characters of three-byte+text such as CJK; Claude's Bash keeps the same number of characters and saves a longer result to a file.+The budget is 90% of those characters for the model the owner's calls run on, leaving room for the CLI's+labels; at no more than three bytes per character, a bounded result reaches the Agent whole on either+Runtime. The window comes from the owner's Computer through the model call layer; an unknown window, or an+offline Computer, gets the unknown-window limit.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 63067498..be65b94b 100644--- a/apps/node-services/src/memory/knowledge-query.ts+++ b/apps/node-services/src/memory/knowledge-query.ts@@ -33,20 +33,21 @@ 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";-// The Daemon limits one tool result to 15% of the model's context window and-// at most 25,000 tokens, which Codex counts at four bytes each; a Runtime cuts-// the middle out of a result above it. A search or read result stays within-// 90% of that limit, since the CLI's labels add about 2% to the JSON.+// The Daemon limits one tool result to 15% of the model's context window, at+// most 25,000 tokens, and to 12,000 tokens when the window is unknown; a+// Runtime cuts the middle out of a longer result or saves it to a file.+// Codex counts four bytes per token, so the limit admits limit×4/3 characters+// of three-byte text such as CJK, and the Daemon gives Claude's Bash output as+// many characters. A search or read result is measured in UTF-16 characters+// of JSON, at most three bytes each, so it fits both Runtimes; it keeps 90% of+// that, since the CLI's labels add about 2%.const WINDOW_OUTPUT_SHARE = 0.15;const MAX_TOOL_OUTPUT_TOKENS = 25_000;-const BYTES_PER_TOKEN = 4;+const UNKNOWN_WINDOW_TOOL_OUTPUT_TOKENS = 12_000;const CLI_LABEL_ROOM = 0.9;-// The budget when the model's window is unknown, within the Daemon's smallest-// tool output limit, 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;+const MIN_SECTION_PAGE_CHARS = 200;const RESULTS_TRIMMED_GAP = {code: "results_trimmed",detail:@@ -61,34 +62,35 @@ export class PersonalKnowledgeEvidenceNotFoundError extends Error {}/**- * One search over every source of the Agent's index: Sessions, recordings,- * 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.+ * The most UTF-16 characters of JSON one search or read result may take for a+ * model with this context window in tokens, or with an unknown one.*/export function knowledgeOutputBudget(contextWindow: number | undefined,): number {- if (contextWindow === undefined) return DEFAULT_KNOWLEDGE_OUTPUT_BYTES;- const toolOutputTokens = Math.min(- contextWindow * WINDOW_OUTPUT_SHARE,- MAX_TOOL_OUTPUT_TOKENS,- );- return Math.floor(toolOutputTokens * BYTES_PER_TOKEN * CLI_LABEL_ROOM);+ const toolOutputTokens =+ contextWindow === undefined+ ? UNKNOWN_WINDOW_TOOL_OUTPUT_TOKENS+ : Math.min(contextWindow * WINDOW_OUTPUT_SHARE, MAX_TOOL_OUTPUT_TOKENS);+ // limit×4/3 characters, multiplied before dividing so round limits stay+ // exact.+ return Math.floor((toolOutputTokens * 4 * CLI_LABEL_ROOM) / 3);}+/**+ * One search over every source of the Agent's index: Sessions, recordings,+ * My pages, mail, Pocket Notes, the Profile, the published Wiki and Daily and+ * Weekly reports. Each item names its source kind.+ */export async function queryPersonalKnowledge(dataRoot: string,input: PersonalKnowledgeQueryRequest,options: {chunkSearch?: ChunkSearchProvider;- outputBudgetBytes?: number;+ outputBudgetChars?: number;} = {},): Promise<PersonalKnowledgeQueryResponse> {- const budget = options.outputBudgetBytes ?? DEFAULT_KNOWLEDGE_OUTPUT_BYTES;+ const budget = options.outputBudgetChars ?? knowledgeOutputBudget(undefined);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([@@ -153,7 +155,7 @@ export async function queryPersonalKnowledge(0,fittingPrefix(facts.length,- (count) => outputBytes(facts.slice(0, count)),+ (count) => outputChars(facts.slice(0, count)),// Facts take at most a quarter, so they never crowd out candidates.budget / 4,),@@ -224,7 +226,7 @@ export async function queryPersonalKnowledge(}return last !== undefined && contentChunks.delete(last);};- while (outputBytes(response()) > budget && dropOne()) trimmed = true;+ while (outputChars(response()) > budget && dropOne()) trimmed = true;return response();}@@ -233,7 +235,7 @@ export async function readPersonalKnowledgeEvidence(input: PersonalKnowledgeEvidenceReadRequest,options: {rawSourceProvider?: ChunkSearchProvider;- outputBudgetBytes?: number;+ outputBudgetChars?: number;} = {},): Promise<PersonalKnowledgeEvidenceReadResponse> {if (!input.evidence_id.startsWith("raw_")) {@@ -242,7 +244,7 @@ export async function readPersonalKnowledgeEvidence(return readRawEvidence(agentWorkspaceRoot(dataRoot, input.agent_id),input,- options.outputBudgetBytes ?? DEFAULT_KNOWLEDGE_OUTPUT_BYTES,+ options.outputBudgetChars ?? knowledgeOutputBudget(undefined),options.rawSourceProvider,);}@@ -347,11 +349,11 @@ 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 = budget - outputBytes(response);+ let remaining = budget - outputChars(response);pages.forEach(({ chunk, offset }, index) => {const share = Math.max(Math.floor(remaining / (pages.length - index)),- MIN_SECTION_PAGE_BYTES,+ MIN_SECTION_PAGE_CHARS,);const section = (length: number) => {const content = chunk.content.slice(offset, offset + length);@@ -368,7 +370,7 @@ async function readRawEvidence(};let length = fittingPrefix(chunk.content.length - offset,- (count) => outputBytes(section(count)) + 1,+ (count) => outputChars(section(count)) + 1,share,);// A page never ends inside a surrogate pair, and never ends empty while@@ -379,7 +381,7 @@ async function readRawEvidence(length = isHighSurrogate(chunk.content.charCodeAt(offset)) ? 2 : 1;const page = section(length);response.sections.push(page);- remaining -= outputBytes(page) + 1;+ remaining -= outputChars(page) + 1;});response.complete =missingSections.length === 0 &&@@ -387,8 +389,8 @@ async function readRawEvidence(return response;}-function outputBytes(value: unknown): number {- return Buffer.byteLength(JSON.stringify(value));+function outputChars(value: unknown): number {+ return JSON.stringify(value).length;}/** The largest count in [0, total] whose measured size stays within budget. */diff --git a/apps/node-services/src/memory/server.ts b/apps/node-services/src/memory/server.tsindex 46f7c023..2977194c 100644--- a/apps/node-services/src/memory/server.ts+++ b/apps/node-services/src/memory/server.ts@@ -352,7 +352,7 @@ 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: {+ const outputBudgetChars = async (input: {tenant_id: string;user_artifact_owner_actor_id: string;}) =>@@ -369,7 +369,7 @@ export async function startMemoryServer(options: {200,await (options.query ?? queryPersonalKnowledge)(options.dataRoot, input, {chunkSearch: options.chunkSearch,- outputBudgetBytes: await outputBudgetBytes(input),+ outputBudgetChars: await outputBudgetChars(input),}),);});@@ -383,7 +383,7 @@ export async function startMemoryServer(options: {options.evidenceRead ?? readPersonalKnowledgeEvidence)(options.dataRoot, input, {rawSourceProvider: options.chunkSearch,- outputBudgetBytes: await outputBudgetBytes(input),+ outputBudgetChars: await outputBudgetChars(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 c3a7e0e3..a5724767 100644--- a/apps/node-services/tests/memory/raw-knowledge-query.test.ts+++ b/apps/node-services/tests/memory/raw-knowledge-query.test.ts@@ -1035,8 +1035,9 @@ describe("Raw Chunk search with PG Raw BM25 fallback", () => {});describe("knowledge output budget", () => {- const OUTPUT_BUDGET_BYTES = 12_000;- const bytes = (value: unknown) => Buffer.byteLength(JSON.stringify(value));+ // Small enough that these fixtures always overflow it.+ const OUTPUT_BUDGET_CHARS = 4_000;+ const chars = (value: unknown) => JSON.stringify(value).length;// Unspaced text of three UTF-8 bytes per character, as in CJK sources.const wide = (seed: number, length: number) =>Array.from({ length }, (_, index) =>@@ -1094,10 +1095,11 @@ describe("knowledge output budget", () => {search: async () => ranked,searchFacts: async () => facts,},+ outputBudgetChars: OUTPUT_BUDGET_CHARS,},);- expect(bytes(result)).toBeLessThanOrEqual(OUTPUT_BUDGET_BYTES);+ expect(chars(result)).toBeLessThanOrEqual(OUTPUT_BUDGET_CHARS);expect(result.gaps.map((gap) => gap.code)).toContain("results_trimmed");expect(result.status).toBe("partial");expect(result.facts!.length).toBeGreaterThan(0);@@ -1120,10 +1122,34 @@ 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_423);- expect(knowledgeOutputBudget(64_896)).toBe(35_043);- expect(knowledgeOutputBudget(1_000_000)).toBe(90_000);+ expect(knowledgeOutputBudget(undefined)).toBe(14_400);+ expect(knowledgeOutputBudget(8_192)).toBe(1_474);+ expect(knowledgeOutputBudget(64_896)).toBe(11_681);+ expect(knowledgeOutputBudget(1_000_000)).toBe(30_000);+ });++ it("stays within the Daemon's tool output limit", async () => {+ // Memory cannot import the Daemon, so this reads its constants: a change+ // on one side that the other misses would let a Runtime cut results.+ const source = await fs.readFile(+ new URL(+ "../../../computer/local-daemon/internal/provider/native/tool_output.go",+ import.meta.url,+ ),+ "utf8",+ );+ const constant = (name: string) =>+ Number(new RegExp(`\\b${name} = (\\d+)`).exec(source)?.[1]);+ const percent = constant("toolOutputWindowPercent");+ const unknown = constant("toolOutputTokens");+ const max = constant("maxToolOutputTokens");+ // The Daemon's limit admits limit×4/3 characters; Memory keeps 90%.+ const charsFor = (tokens: number) => Math.floor((tokens * 4 * 0.9) / 3);+ expect(knowledgeOutputBudget(undefined)).toBe(charsFor(unknown));+ expect(knowledgeOutputBudget(64_896)).toBe(+ charsFor((64_896 * percent) / 100),+ );+ expect(knowledgeOutputBudget(10_000_000)).toBe(charsFor(max));});it("keeps more of a result within a larger budget", async () => {@@ -1139,19 +1165,19 @@ describe("knowledge output budget", () => {score: 1 / (61 + index),};});- const search = (outputBudgetBytes: number) =>+ const search = (outputBudgetChars: number) =>queryPersonalKnowledge(fixtureData.root, request("Report"), {chunkSearch: { search: async () => matches },- outputBudgetBytes,+ outputBudgetChars,});- const small = await search(12_000);- const large = await search(knowledgeOutputBudget(64_896));+ const small = await search(OUTPUT_BUDGET_CHARS);+ const large = await search(knowledgeOutputBudget(131_072));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(JSON.stringify(large).length).toBeLessThanOrEqual(+ knowledgeOutputBudget(131_072),);expect(large.items.filter((item) => item.content).length).toBeGreaterThan(small.items.filter((item) => item.content).length,@@ -1214,13 +1240,17 @@ describe("knowledge output budget", () => {.slice(0, 8);expect(chunks).toHaveLength(8);- const read = await readPersonalKnowledgeEvidence(fixtureData.root, {- ...identity,- evidence_id: evidenceId,- section_requests: chunks.map((chunk) => ({ section_id: chunk.id })),- });+ const read = await readPersonalKnowledgeEvidence(+ fixtureData.root,+ {+ ...identity,+ evidence_id: evidenceId,+ section_requests: chunks.map((chunk) => ({ section_id: chunk.id })),+ },+ { outputBudgetChars: OUTPUT_BUDGET_CHARS },+ );- expect(bytes(read)).toBeLessThanOrEqual(OUTPUT_BUDGET_BYTES);+ expect(chars(read)).toBeLessThanOrEqual(OUTPUT_BUDGET_CHARS);expect(read.complete).toBe(false);expect(read.missingSections).toEqual([]);expect(read.sections.map((section) => section.id)).toEqual(diff --git a/apps/node-services/tests/memory/server.test.ts b/apps/node-services/tests/memory/server.test.tsindex 64700ce9..9ad3590c 100644--- a/apps/node-services/tests/memory/server.test.ts+++ b/apps/node-services/tests/memory/server.test.ts@@ -382,7 +382,7 @@ describe("Memory server", () => {},query: async (_root, input, options) => {received.push(input);- budgets.push(options?.outputBudgetBytes);+ budgets.push(options?.outputBudgetChars);return {gaps: [{ code: "no_relevant_evidence" }],indexedAt: null,@@ -417,13 +417,13 @@ describe("Memory server", () => {status: "empty",});expect(received).toEqual([body]);- // 90% of 15% of the owner's model window, at four bytes per token.- expect(budgets).toEqual([35_043]);+ // 90% of the Daemon's limit for the owner's model window, in characters.+ expect(budgets).toEqual([11_681]);await post({ ...body, user_artifact_owner_actor_id: "human_offline" },"memory-token",);- expect(budgets.at(-1)).toBe(12_000);+ expect(budgets.at(-1)).toBe(14_400);for (const removed of [{ source: "personal_knowledge" },{ node_types: ["Session"] },