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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: expose selected mind actions within tool schema budgets (#9820)
Adam Eivyfaa037a00427
diff --git a/server/lib/persistentMindToolActivation.js b/server/lib/persistentMindToolActivation.jsindex 91b4e213e4..0fdbd05358 100644--- a/server/lib/persistentMindToolActivation.js+++ b/server/lib/persistentMindToolActivation.js@@ -21,6 +21,7 @@ export const TOOL_ACTIVATION_FAMILIES = Object.freeze(['tasks', 'issues', 'reporexport const TOOL_ACTIVATION_LIMITS = Object.freeze({MIN_RETENTION_TURNS: 0,MAX_RETENTION_TURNS: 20,+ MAX_TARGET_TOOLS: 5,});// 0 is deliberately "one-turn behaviour": activating a family only expands it@@ -31,6 +32,7 @@ export const toolActivationFamilySchema = z.enum(TOOL_ACTIVATION_FAMILIES);export const toolsActivateInputSchema = z.object({families: z.array(toolActivationFamilySchema).min(1).max(TOOL_ACTIVATION_FAMILIES.length),+ toolNames: z.array(z.string().trim().min(1).max(200)).min(1).max(TOOL_ACTIVATION_LIMITS.MAX_TARGET_TOOLS).optional(),}).strict();export const toolsDeactivateInputSchema = z.object({diff --git a/server/services/cosToolRegistry.js b/server/services/cosToolRegistry.jsindex 86cc83fc68..23c2de19dc 100644--- a/server/services/cosToolRegistry.js+++ b/server/services/cosToolRegistry.js@@ -280,7 +280,7 @@ const toolsActivateTool = Object.freeze({version: COS_TOOL_SCHEMA_VERSION,providerName: providerToolName('tools.activate'),aliases: [providerToolName('tools.activate')],- description: `Expand full schemas for one or more tool families (${TOOL_ACTIVATION_FAMILIES.join(', ')}) for the rest of this turn, plus a short retention window afterward. This only changes which schemas you are shown here — it never grants a capability this mind does not already hold.`,+ description: `Expand full schemas for one or more tool families (${TOOL_ACTIVATION_FAMILIES.join(', ')}) for the rest of this turn, plus a short retention window afterward. Supply up to five exact toolNames from those granted families to prioritize the next actions when family schemas are budget-limited; repeating family activation alone does not resolve that limit. This only changes which schemas you are shown here — it never grants a capability this mind does not already hold.`,input_schema: zodToOpenApiSchema(toolsActivateInputSchema),output_schema: objectOutputSchema,policy: {@@ -768,7 +768,7 @@ const TOOL_PURPOSE_MAX_CHARS = 160;const renderToolPrompt = (tools, discoverableLines = []) => {const discoverableBlock = discoverableLines.length- ? `\n\nDiscoverable-only families (schemas hidden to save context; call tools.activate with a "families" array to expand one for this turn and a short retention window after):\n${discoverableLines.join('\n')}`+ ? `\n\nDiscoverable-only families (schemas hidden to save context; call tools.activate with a "families" array to expand one for this turn and a short retention window after; include "toolNames" to prioritize specific budget-limited actions):\n${discoverableLines.join('\n')}`: '';return `# PortOS semantic tools${TOOL_EXPOSURE_HEADER}@@ -822,6 +822,7 @@ const logToolExposureTrace = (stats) => {*/export const buildPersistentMindToolPrompt = async (capabilities, recipes = [], {turnId = null, isUserTurn = false, trace = false, maxChars = Infinity, requiredToolNames = [],+ requestedToolNames = [], onSelection,} = {}) => {const grants = normalizePersistentMindCapabilities(capabilities);const catalog = getCosToolCatalog({ scope: 'mind', capabilities, recipes });@@ -848,6 +849,7 @@ Semantic tool access is OFF. Return an empty toolCalls array. Never invent a tooexcludedByReason: { ungranted: catalog.tools.length - granted.length },});}+ onSelection?.(granted.map((tool) => tool.name));return renderToolPrompt(granted.map(fullSchemaShape));}@@ -867,12 +869,13 @@ Semantic tool access is OFF. Return an empty toolCalls array. Never invent a too});}+ const requested = new Set(requestedToolNames);const exposedFamilies = new Set(Object.keys(activation.leases));const controlTools = granted.filter((tool) => ['tools.activate', 'tools.deactivate'].includes(tool.name));const exposedTools = [];const discoverableByFamily = new Map();for (const tool of meaningful) {- if (tool.family === 'core' || exposedFamilies.has(tool.family)) {+ if (tool.family === 'core' || exposedFamilies.has(tool.family) || requested.has(tool.name)) {exposedTools.push(tool);} else {if (!discoverableByFamily.has(tool.family)) discoverableByFamily.set(tool.family, []);@@ -901,15 +904,15 @@ Semantic tool access is OFF. Return an empty toolCalls array. Never invent a tooconst 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;+ const leftRequired = requested.has(left.name) ? 2 : required.has(left.name) ? 1 : 0;+ const rightRequired = requested.has(right.name) ? 2 : 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;+ if (selectedChars + rendered.length > maxChars) continue;selectedTools.push(tool);selectedChars += rendered.length;}@@ -928,11 +931,12 @@ Semantic tool access is OFF. Return an empty toolCalls array. Never invent a too};while (selectedTools.length > 0 && renderSelection().length > maxChars) {- const removableIndex = [...selectedTools].reverse().findIndex((tool) => !required.has(tool.name));- if (removableIndex < 0) break;- selectedTools.splice(selectedTools.length - 1 - removableIndex, 1);+ // Priorities never override the complete schema budget. Completed action+ // receipts still identify earlier calls even when their schemas no longer fit.+ selectedTools.pop();}+ onSelection?.([...controlTools, ...selectedTools].map((tool) => tool.name));return renderSelection();};@@ -992,6 +996,19 @@ const executeAdapter = async (tool, args, context, authority) => {if (tool.adapter.kind === 'tools-activate' || tool.adapter.kind === 'tools-deactivate') {const { loadState, saveState, withStateLock } = await import('./cosState.js');const grants = normalizePersistentMindCapabilities(authority?.capabilities);+ const targeted = tool.adapter.kind === 'tools-activate' && args.toolNames+ ? [...new Set(args.toolNames)] : [];+ let targetFamilies;+ if (targeted.length) {+ const recipes = targeted.some((name) => name.startsWith('recipe.'))+ ? await readPersistentMindRecipeCatalog(authority?.capabilities) : [];+ const catalog = getCosToolCatalog({ scope: 'mind', capabilities: authority?.capabilities, recipes });+ targetFamilies = Object.fromEntries(catalog.tools.filter((entry) => targeted.includes(entry.name)).map((entry) => [entry.name, entry.family]));+ if (targeted.some((name) => !catalog.tools.some((entry) => entry.name === name+ && entry.granted && args.families.includes(entry.family)))) {+ throw new ServerError('Requested tool names must belong to the selected granted families', { status: 403, code: 'TOOL_CAPABILITY_DENIED' });+ }+ }return withStateLock(async () => {const root = await loadState();const current = normalizePersistentMindToolActivation(root.persistentMind.toolActivation);@@ -1001,8 +1018,10 @@ const executeAdapter = async (tool, args, context, authority) => {root.persistentMind = { ...root.persistentMind, toolActivation: { leases, lastAgedTurnId: current.lastAgedTurnId } };await saveState(root);return tool.adapter.kind === 'tools-activate'- ? { ok: true, activated: args.families, retentionTurns: grants.toolExposureRetentionTurns, families: Object.keys(leases) }- : { ok: true, deactivated: args.families || Object.keys(current.leases), families: Object.keys(leases) };+ ? { ok: true, activated: args.families, retentionTurns: grants.toolExposureRetentionTurns, families: Object.keys(leases),+ ...(targeted.length ? { requestedToolNames: targeted, targetFamilies } : {}),+ schemaNote: 'Family activation is budget-limited. Target exact toolNames for the next action; identical reactivation does not change the schema budget.' }+ : { ok: true, deactivated: args.families || TOOL_ACTIVATION_FAMILIES, families: Object.keys(leases) };});}if (tool.adapter.kind.startsWith('thinking-')) {diff --git a/server/services/cosToolRegistry.test.js b/server/services/cosToolRegistry.test.jsindex 04b9fcb1b6..3a78c8fbf4 100644--- a/server/services/cosToolRegistry.test.js+++ b/server/services/cosToolRegistry.test.js@@ -721,6 +721,22 @@ describe('cosToolRegistry', () => {expect(after).toContain('"name":"mind.cleanup"');});+ it.each([+ { families: ['mind'], toolNames: ['eidoverse.augment'] },+ { families: ['eidoverse'], toolNames: ['eidoverse.augment'] },+ { families: ['mind'], toolNames: ['missing.tool'] },+ { families: ['mind'], toolNames: Array(6).fill('mind.cleanup') },+ ])('rejects unauthorized, mismatched, unknown, or unbounded targets before changing leases: %j', async (arguments_) => {+ const result = await executeCosToolCall({+ call: { requestId: 'invalid-target', name: 'tools.activate', arguments: arguments_ },+ authority: { scope: 'mind', capabilities: { manageMind: true } },+ }).catch((error) => ({ state: 'failed', error: error.message }));+ expect(result).toMatchObject({ state: 'failed' });+ expect(mocks.root.persistentMind.toolActivation.leases).toEqual({});+ const prompt = await buildPersistentMindToolPrompt({ manageMind: true }, [], { requestedToolNames: ['eidoverse.augment'] });+ expect(prompt).not.toContain('eidoverse.augment');+ });+it('never exposes an ungranted tool at full schema even with a live lease for its family (fail-closed)', async () => {mocks.root.persistentMind.toolActivation = { leases: { mind: 3 }, lastAgedTurnId: 'turn-1' };const prompt = await buildPersistentMindToolPrompt({ manageMind: false, readPortos: true }, [], { turnId: 'turn-1' });diff --git a/server/services/persistentMindAdapter.js b/server/services/persistentMindAdapter.jsindex 834532f327..9649d755fc 100644--- a/server/services/persistentMindAdapter.js+++ b/server/services/persistentMindAdapter.js@@ -84,8 +84,8 @@ const LOCAL_PROMPT_TOKENIZER_MARGIN = 0.9;// history) may take on a local window; the rest is the response contract,// capabilities, tool catalog and in-wake tool results.const LOCAL_CONTEXT_PROMPT_SHARE = 0.25;-// The narrowest tool catalog a local-window rebuild may fall to. Tools that-// already ran stay in full (requiredToolNames); the rest stay discoverable.+// The narrowest tool catalog a local-window rebuild may fall to. Requested+// and completed actions are priorities; only complete schemas that fit stay.const MIN_LOCAL_TOOL_PROMPT_CHARS = 6_000;// Per-result caps tried in order when completed tool results must shrink.const TOOL_RESULT_COMPACTION_CAPS = [2_000, 1_000, 500, 200];@@ -565,30 +565,46 @@ export function createPersistentMindTurnAdapter() {const promptBudget = await resolvePersistentMindPromptBudget({ provider, model });// Set after the first tool round: what a continuation prompt carries.let continuation = null;+ const requestedToolNames = new Map();const composeRoundPrompt = async (namePrompt) => {// Rebuilds never age the lease or trace (isUserTurn/trace omitted).+ let exposedToolNames = [];const buildTools = (maxChars) => (continuation? buildPersistentMindToolPrompt(continuation.capabilities, continuation.recipes, {turnId, maxChars, requiredToolNames: continuation.requiredToolNames,+ requestedToolNames: [...requestedToolNames.keys()], onSelection: (names) => { exposedToolNames = names; },}): buildPersistentMindToolPrompt(taskAccess, recipeCatalog, { turnId, maxChars }));+ const annotateActivationResults = () => {+ for (const receipt of completedToolResults) {+ if (receipt.state !== 'completed' || !['tools.activate', 'tools_activate'].includes(receipt.name)+ || !Array.isArray(receipt.result?.requestedToolNames)) continue;+ const exposed = receipt.result.requestedToolNames.filter((name) => exposedToolNames.includes(name));+ const omitted = receipt.result.requestedToolNames.filter((name) => !exposedToolNames.includes(name));+ receipt.result = { ...receipt.result, exposedToolNames: exposed, omittedToolNames: omitted,+ schemaNote: omitted.length+ ? 'Requested schemas are omitted by the current budget or grants. Identical reactivation will not fix this; select fewer or smaller actions.'+ : 'Requested schemas are exposed in this continuation. Execute the selected action without repeating completed calls.' };+ }+ };const assemble = (toolPrompt, toolResults) => `${buildPersistentMindTurnPrompt({ ...turnPromptSections, toolCapabilityPrompt: toolPrompt })}${continuation? `\n\n# Completed tool results\n${JSON.stringify(toolResults)}\n\n${continuation.suffix}`: ''}${namePrompt}`;- // 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.+ // Prioritize explicitly requested next actions, then completed actions,+ // within the existing cap; keep other granted actions discoverable.let toolPrompt = continuation ? await buildTools(MAX_CONTINUATION_TOOL_PROMPT_CHARS) : toolCapabilityPrompt;+ if (continuation) annotateActivationResults();let toolResults = completedToolResults;let prompt = assemble(toolPrompt, toolResults);const limit = promptBudget?.maxPromptChars;if (!limit || prompt.length <= limit) return prompt;const untrimmedChars = prompt.length;- // 1. Narrow the tool catalog: schemas that already ran stay in full,- // the rest stay listed as budget-limited and can be re-requested.+ // 1. Narrow the tool catalog, preserving complete schemas that fit.+ // Receipts identify completed actions even if their schemas drop.const toolTarget = Math.max(Math.min(toolPrompt.length, MIN_LOCAL_TOOL_PROMPT_CHARS), toolPrompt.length - (prompt.length - limit));if (toolTarget < toolPrompt.length) {toolPrompt = await buildTools(toolTarget);+ annotateActivationResults();prompt = assemble(toolPrompt, toolResults);}// 2. Compact completed tool results (previews, then per-call stubs).@@ -735,7 +751,25 @@ export function createPersistentMindTurnAdapter() {toolBudget,});completedToolResults.push(...toolResults);+ for (const receipt of toolResults) {+ if (receipt.state === 'completed' && ['tools.activate', 'tools_activate'].includes(receipt.name)) {+ for (const name of receipt.result?.requestedToolNames || []) {+ requestedToolNames.set(name, receipt.result.targetFamilies?.[name]);+ }+ }+ if (receipt.state === 'completed' && ['tools.deactivate', 'tools_deactivate'].includes(receipt.name)) {+ const deactivated = new Set(receipt.result?.deactivated || []);+ for (const [name, family] of requestedToolNames) {+ if (deactivated.has(family)) requestedToolNames.delete(name);+ }+ }+ }const liveCapabilities = normalizePersistentMindCapabilities((await loadState()).config?.persistentMindCapabilities);+ // Once a targeted action completes its receipt, rather than its schema,+ // prevents replay; leave room for the next requested action.+ for (const receipt of toolResults) {+ if (receipt.state === 'completed') requestedToolNames.delete(receipt.name);+ }// Same turnId, isUserTurn/trace both omitted (default false): a tool// 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 againdiff --git a/server/services/persistentMindAdapter.test.js b/server/services/persistentMindAdapter.test.jsindex 0fa9b7a6bd..913efe134d 100644--- a/server/services/persistentMindAdapter.test.js+++ b/server/services/persistentMindAdapter.test.js@@ -17,6 +17,9 @@ const mock = vi.hoisted(() => ({readMaintenance: vi.fn(),resolveLocalPromptBudget: vi.fn(),toolPromptPadding: '',+ realToolExposure: false,+ recipeCatalog: [],+ realRegistry: null,createPersistentMindMemoryFromCandidate: vi.fn(async ({ candidateId, ...candidate }) => ({success: true,duplicate: false,@@ -24,7 +27,15 @@ const mock = vi.hoisted(() => ({})),}));-vi.mock('./cosState.js', () => ({ loadState: vi.fn(async () => mock.root) }));+vi.mock('./cosState.js', () => ({+ loadState: vi.fn(async () => mock.root),+ saveState: vi.fn(async () => {}),+ withStateLock: vi.fn(async (fn) => fn()),+}));+vi.mock('./mindToolRecipeRuntime.js', async (importOriginal) => ({+ ...await importOriginal(),+ readMindRecipeTools: async () => mock.recipeCatalog,+}));vi.mock('../lib/fileUtils.js', async (importOriginal) => ({...(await importOriginal()),resolveScreenshot: vi.fn((filename) => filename ? `/tmp/portos-screenshots/${filename}` : null),@@ -67,16 +78,23 @@ vi.mock('./persistentMindCallCapability.js', () => ({vi.mock('./persistentMindPlaybookSignals.js', () => ({resolvePersistentMindPlaybookPhase: (...args) => mock.resolvePlaybookPhase(...args),}));-vi.mock('./cosToolRegistry.js', () => ({- readPersistentMindRecipeCatalog: vi.fn(async () => []),- // Honors maxChars like the real builder, so local-window narrowing is visible.- buildPersistentMindToolPrompt: ({ readPortos, writePortos }, _recipes, { maxChars = Infinity } = {}) => {- const rendered = `PortOS tools: read=${Boolean(readPortos)} write=${Boolean(writePortos)}${mock.toolPromptPadding}`;- return rendered.length > maxChars ? rendered.slice(0, maxChars) : rendered;- },- executeCosToolCall: (...args) => mock.executeToolCall(...args),- isCosTaskToolName: (name) => name === 'cos.create-task' || name === 'cos_create_task',-}));+vi.mock('./cosToolRegistry.js', async (importOriginal) => {+ const actual = await importOriginal();+ mock.realRegistry = actual;+ return {+ readPersistentMindRecipeCatalog: vi.fn(async () => mock.realToolExposure ? mock.recipeCatalog : []),+ // Honors maxChars like the real builder, so local-window narrowing is visible.+ buildPersistentMindToolPrompt: (capabilities, recipes, options = {}) => {+ if (mock.realToolExposure) return actual.buildPersistentMindToolPrompt(capabilities, recipes, options);+ const { readPortos, writePortos } = capabilities;+ const { maxChars = Infinity } = options;+ const rendered = `PortOS tools: read=${Boolean(readPortos)} write=${Boolean(writePortos)}${mock.toolPromptPadding}`;+ return rendered.length > maxChars ? rendered.slice(0, maxChars) : rendered;+ },+ executeCosToolCall: (...args) => mock.executeToolCall(...args),+ isCosTaskToolName: (name) => name === 'cos.create-task' || name === 'cos_create_task',+ };+});const { createPersistentMindTurnAdapter, persistentMindHarnessInfo, persistentMindResponseSchema} = await import('./persistentMindAdapter.js');@@ -99,6 +117,9 @@ beforeEach(() => {mock.assertVision.mockImplementation((result, provider) => result?.provider || provider);mock.resolveLocalPromptBudget.mockResolvedValue(null);mock.toolPromptPadding = '';+ mock.realToolExposure = false;+ mock.recipeCatalog = [];+ mock.root.persistentMind = { toolActivation: { leases: {}, lastAgedTurnId: null } };mock.runPrompt.mockResolvedValue({ text: JSON.stringify({thinkingSummary: 'I connected the new request to the durable fact.',message: 'Here is the answer.',@@ -1010,3 +1031,60 @@ describe('local-window tool result compaction', () => {}});});++// A synthetic granted building catalog reproduces schema pressure without a+// live world, provider call, DB recipe, or private instance record.+describe('targeted activation through the public turn adapter', () => {+ const buildingTool = (name, schemaChars, capability = 'manageToolRecipes') => ({+ type: 'portos_tool', name, version: 1, providerName: name.replaceAll('.', '_'), aliases: [],+ description: 'Build an example structure.',+ input_schema: { type: 'object', properties: { material: { type: 'string', description: 'Example material option. '.repeat(Math.ceil(schemaChars / 25)) } }, required: ['material'], additionalProperties: false },+ output_schema: { type: 'object' },+ policy: { scopes: ['mind'], requiredCapabilities: [capability], sideEffect: 'write' },+ adapter: { kind: 'recipe' },+ });+ const schemasIn = (prompt) => JSON.parse(prompt.split('# PortOS semantic tools\n')[1].split('\n\n')[1]);++ it.each([+ { schemaChars: 18_000, contextChars: 0, exposed: true },+ { schemaChars: 30_000, contextChars: 0, exposed: false },+ { schemaChars: 18_000, contextChars: 38_000, exposed: false },+ ])('exposes a complete requested schema or explains its catalog/local-window limit: %j', async ({ schemaChars, contextChars, exposed }) => {+ mock.realToolExposure = true;+ if (contextChars) mock.resolveLocalPromptBudget.mockResolvedValue({ contextWindow: 16_384, outputReserveTokens: 2_048, maxPromptTokens: 14_336 });+ mock.root.config.persistentMindCapabilities = { manageToolRecipes: true };+ mock.recipeCatalog = [buildingTool('recipe.first', 12_000), buildingTool('recipe.build', schemaChars), buildingTool('recipe.denied', 500, 'manageEidoverse')];+ mock.root.persistentMind.toolActivation.leases = { recipes: 3 };+ const before = await mock.realRegistry.buildPersistentMindToolPrompt(mock.root.config.persistentMindCapabilities, mock.recipeCatalog, { maxChars: 24_000 });+ expect(schemasIn(before).map(({ name }) => name)).not.toContain('recipe.build');+ const prompts = [];+ mock.runPrompt.mockImplementation(async ({ prompt }) => {+ prompts.push(prompt);+ const schemas = schemasIn(prompt);+ const names = schemas.map(({ name }) => name);+ expect(names).not.toContain('recipe.denied');+ if (prompts.length === 1) return { text: JSON.stringify({ toolCalls: [{ requestId: 'activate-build', name: 'tools.activate', arguments: { families: ['recipes'], toolNames: ['recipe.build'] } }] }) };+ if (!exposed) {+ expect(names).not.toContain('recipe.build');+ expect(prompt).toContain('"omittedToolNames":["recipe.build"]');+ expect(prompt).toContain('Identical reactivation will not fix this');+ } else if (prompts.length === 2) {+ const selected = schemas.find(({ name }) => name === 'recipe.build');+ expect(selected.input_schema).toEqual(mock.recipeCatalog[1].input_schema);+ expect(prompt).toContain('"exposedToolNames":["recipe.build"]');+ return { text: JSON.stringify({ toolCalls: [{ requestId: 'build-once', name: 'recipe.build', arguments: { material: 'example-stone' } }] }) };+ } else {+ expect(prompt).toContain('"requestId":"build-once","name":"recipe.build","state":"completed"');+ }+ return { text: JSON.stringify({ message: 'Finished.', toolCalls: [] }) };+ });+ mock.executeToolCall.mockImplementation(async (request) => request.call.name === 'tools.activate'+ ? mock.realRegistry.executeCosToolCall(request)+ : { state: 'completed', name: request.call.name, result: { ok: true } });+ await createPersistentMindTurnAdapter().run({ ...profile, turnId: `target-build-${schemaChars}`, wake: { kind: 'self' }, context: { text: 'C'.repeat(contextChars) || 'Build an example structure.' } });+ expect(prompts).toHaveLength(exposed ? 3 : 2);+ if (contextChars) for (const prompt of prompts) expect(prompt.length).toBeLessThanOrEqual(Math.floor(14_336 * 0.9) * 4);+ expect(mock.executeToolCall.mock.calls.filter(([request]) => request.call.name === 'recipe.build')).toHaveLength(exposed ? 1 : 0);+ for (const prompt of prompts.slice(1)) expect(prompt.match(/# PortOS semantic tools[\s\S]*?Supply distinct requestId values only when two intentionally identical actions must both run\./)[0].length).toBeLessThanOrEqual(24_000);+ });+});