Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: bound persistent mind continuation tool schemas (#7831)

[._.]/ Adam Eivy12a9977b1eba
diff --git a/server/services/cosToolRegistry.js b/server/services/cosToolRegistry.js
index d13112ef75..fe5fe5842d 100644
--- a/server/services/cosToolRegistry.js
+++ b/server/services/cosToolRegistry.js
@@ -792,7 +792,9 @@ const logToolExposureTrace = (stats) => {
* `capabilities.toolExposureAllSchemas` reproduces the pre-#7624 behavior
* (every granted tool's full schema, always) for debugging.
*/
-export const buildPersistentMindToolPrompt = async (capabilities, recipes = [], { turnId = null, isUserTurn = false, trace = false } = {}) => {
+export const buildPersistentMindToolPrompt = async (capabilities, recipes = [], {
+ turnId = null, isUserTurn = false, trace = false, maxChars = Infinity, requiredToolNames = [],
+} = {}) => {
const grants = normalizePersistentMindCapabilities(capabilities);
const catalog = getCosToolCatalog({ scope: 'mind', capabilities, recipes });
const granted = catalog.tools.filter((tool) => tool.granted);
@@ -841,6 +843,7 @@ Semantic tool access is OFF. Return an empty toolCalls array. Never invent a too
const controlTools = granted.filter((tool) => ['tools.activate', 'tools.deactivate'].includes(tool.name));
const exposedTools = [];
const discoverableByFamily = new Map();
+ const budgetLimitedByFamily = new Map();
for (const tool of meaningful) {
if (tool.family === 'core' || exposedFamilies.has(tool.family)) {
exposedTools.push(tool);
@@ -869,11 +872,37 @@ Semantic tool access is OFF. Return an empty toolCalls array. Never invent a too
});
}
+ const required = new Set(requiredToolNames);
+ const prioritized = [...exposedTools].sort((left, right) => {
+ const leftRequired = required.has(left.name) ? 1 : 0;
+ const rightRequired = required.has(right.name) ? 1 : 0;
+ return rightRequired - leftRequired;
+ });
+ const selectedTools = [];
+ let selectedChars = 0;
+ for (const tool of prioritized) {
+ const rendered = JSON.stringify(fullSchemaShape(tool));
+ if (selectedTools.length > 0 && selectedChars + rendered.length > maxChars) continue;
+ selectedTools.push(tool);
+ selectedChars += rendered.length;
+ }
+ for (const tool of prioritized.filter((candidate) => !selectedTools.includes(candidate))) {
+ if (!budgetLimitedByFamily.has(tool.family)) budgetLimitedByFamily.set(tool.family, []);
+ budgetLimitedByFamily.get(tool.family).push(tool);
+ }
const discoverableLines = [...discoverableByFamily.entries()].map(([family, tools]) => (
`- ${family} (${tools.length}): ${tools.map((tool) => `${tool.name} — ${toolPurpose(tool.description)}`).join('; ')}`
- ));
+ )).concat([...budgetLimitedByFamily.entries()].map(([family, tools]) => (
+ `- ${family} (${tools.length}, budget-limited): ${tools.map((tool) => `${tool.name} — ${toolPurpose(tool.description)}`).join('; ')}`
+ )));
+
+ while (selectedTools.length > 0 && renderToolPrompt([...controlTools, ...selectedTools].map(fullSchemaShape), discoverableLines).length > maxChars) {
+ const removableIndex = [...selectedTools].reverse().findIndex((tool) => !required.has(tool.name));
+ if (removableIndex < 0) break;
+ selectedTools.splice(selectedTools.length - 1 - removableIndex, 1);
+ }
- return renderToolPrompt([...controlTools, ...exposedTools].map(fullSchemaShape), discoverableLines);
+ return renderToolPrompt([...controlTools, ...selectedTools].map(fullSchemaShape), discoverableLines);
};
export const readPersistentMindRecipeCatalog = (capabilities) => readMindRecipeTools(capabilities, getCosToolCatalog({ scope: 'mind' }).tools);
diff --git a/server/services/cosToolRegistry.test.js b/server/services/cosToolRegistry.test.js
index 0ff98a552f..55b8e9c0cb 100644
--- a/server/services/cosToolRegistry.test.js
+++ b/server/services/cosToolRegistry.test.js
@@ -771,6 +771,17 @@ describe('cosToolRegistry', () => {
expect(prompt).not.toContain('Discoverable-only families');
});
+ it('budgets leased schemas while retaining the tool that completed the prior round', async () => {
+ mocks.root.persistentMind.toolActivation = { leases: { mind: 3 }, lastAgedTurnId: 'turn-1' };
+ const prompt = await buildPersistentMindToolPrompt(
+ { manageMind: true }, [],
+ { maxChars: 100, requiredToolNames: ['mind.protect-memory'] },
+ );
+ expect(prompt).toContain('mind.protect-memory');
+ expect(prompt).toContain('mind.cleanup');
+ expect(prompt).not.toContain('"name":"mind.cleanup","description"');
+ });
+
it('reports semantic tool access as OFF exactly as before when nothing meaningful is granted', async () => {
const prompt = await buildPersistentMindToolPrompt({}, []);
expect(prompt).toBe(`# PortOS semantic tools
diff --git a/server/services/persistentMindAdapter.js b/server/services/persistentMindAdapter.js
index 0ee41de546..daaa52aea1 100644
--- a/server/services/persistentMindAdapter.js
+++ b/server/services/persistentMindAdapter.js
@@ -68,6 +68,7 @@ import {
const { HEARTBEAT_INTERVAL_MS } = PERSISTENT_MIND_LIMITS;
const MAX_TOOL_PROVIDER_ROUNDS = 4;
const MAX_TOOL_RESULT_CHARS = 4_000;
+const MAX_CONTINUATION_TOOL_PROMPT_CHARS = 24_000;
const MAX_MEMORY_CANDIDATES_PER_TURN = 5;
const memoryCandidateSchema = z.object({
@@ -610,8 +611,18 @@ export function createPersistentMindTurnAdapter() {
// call may have just activated or renewed a family, so re-read the
// live lease state, but this in-turn rebuild must never age it again
// or log a second trace line for the same turn.
+ const completedToolNames = completedToolResults
+ .filter((toolResult) => toolResult.state === 'completed')
+ .map((toolResult) => toolResult.name)
+ .filter(Boolean);
basePrompt = buildPersistentMindTurnPrompt({ context, wake, taskCapabilityPrompt, issueCapabilityPrompt, visibilityPrompt, userActionsPrompt, maintenancePrompt, callCapabilityPrompt,
- toolCapabilityPrompt: await buildPersistentMindToolPrompt(liveCapabilities, await readPersistentMindRecipeCatalog(liveCapabilities), { turnId }),
+ // A successful call proves only that its own schema was useful. Keep
+ // that schema (and the compact discovery index) for continuation;
+ // do not expand every sibling in the leased family. This bounds the
+ // complete prompt while preserving explicit activation semantics.
+ toolCapabilityPrompt: await buildPersistentMindToolPrompt(liveCapabilities, await readPersistentMindRecipeCatalog(liveCapabilities), {
+ turnId, maxChars: MAX_CONTINUATION_TOOL_PROMPT_CHARS, requiredToolNames: completedToolNames,
+ }),
});
const budgetExhausted = toolBudget.used >= COS_TOOL_CALL_LIMITS.maxCallsPerTurn || round === MAX_TOOL_PROVIDER_ROUNDS - 2;
providerPrompt = `${basePrompt}\n\n# Completed tool results\n${JSON.stringify(completedToolResults)}\n\n${parsed.taskRequests.length > 0 ? 'Task requests from this intermediate round were not queued. Include only the final desired taskRequests in a terminal response with toolCalls: [].\n' : ''}${budgetExhausted ? 'The tool-call budget is exhausted. Return a final response with toolCalls: [] and do not repeat completed actions.' : 'Use these results to continue. Do not repeat a completed requestId.'}`;