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

add progressive tool exposure for the Persistent Mind (#7624)

[._.]/ Adam Eivy380c452eb00a
diff --git a/client/src/components/cos/PersistentMindToolExposureControls.jsx b/client/src/components/cos/PersistentMindToolExposureControls.jsx
new file mode 100644
index 0000000000..11c2259314
--- /dev/null
+++ b/client/src/components/cos/PersistentMindToolExposureControls.jsx
@@ -0,0 +1,105 @@
+import { useEffect, useId, useState } from 'react';
+import * as api from '../../services/api';
+import toast from '../ui/Toast';
+
+const MIN_RETENTION_TURNS = 0;
+const MAX_RETENTION_TURNS = 20;
+const DEFAULT_RETENTION_TURNS = 3;
+
+const clampRetentionTurns = (value) => {
+ const parsed = Number(value);
+ if (!Number.isFinite(parsed)) return DEFAULT_RETENTION_TURNS;
+ return Math.min(MAX_RETENTION_TURNS, Math.max(MIN_RETENTION_TURNS, Math.round(parsed)));
+};
+
+/**
+ * Progressive tool exposure settings (#7624): how many extra user turns an
+ * activated tool family stays at full schema, and the all-schemas escape
+ * hatch that reproduces the pre-#7624 behavior for debugging. Neither field
+ * changes what the mind is ALLOWED to do — only what it is shown each turn.
+ */
+export default function PersistentMindToolExposureControls({
+ capabilities,
+ disabled = false,
+ onSaved,
+ onSavingChange,
+}) {
+ const idPrefix = useId();
+ const [retentionTurns, setRetentionTurns] = useState(() => clampRetentionTurns(capabilities?.toolExposureRetentionTurns ?? DEFAULT_RETENTION_TURNS));
+ const [allSchemas, setAllSchemas] = useState(capabilities?.toolExposureAllSchemas === true);
+ const [saving, setSaving] = useState(false);
+
+ useEffect(() => {
+ if (saving) return;
+ setRetentionTurns(clampRetentionTurns(capabilities?.toolExposureRetentionTurns ?? DEFAULT_RETENTION_TURNS));
+ setAllSchemas(capabilities?.toolExposureAllSchemas === true);
+ }, [capabilities?.toolExposureRetentionTurns, capabilities?.toolExposureAllSchemas, saving]);
+
+ const save = async (patch, { successMessage }) => {
+ setSaving(true);
+ onSavingChange?.(true);
+ try {
+ await api.updateCosConfig({ persistentMindCapabilities: patch }, { silent: true });
+ onSaved?.({ ...capabilities, ...patch });
+ toast.success(successMessage);
+ } catch (error) {
+ setRetentionTurns(clampRetentionTurns(capabilities?.toolExposureRetentionTurns ?? DEFAULT_RETENTION_TURNS));
+ setAllSchemas(capabilities?.toolExposureAllSchemas === true);
+ toast.error(error.message);
+ } finally {
+ setSaving(false);
+ onSavingChange?.(false);
+ }
+ };
+
+ const retentionId = `${idPrefix}-retention`;
+ const allSchemasId = `${idPrefix}-all-schemas`;
+
+ return (
+ <div className="space-y-4 border-t border-port-border pt-4">
+ <div>
+ <p className="text-sm text-port-text">Progressive tool exposure</p>
+ <p className="mt-0.5 text-xs text-port-text-muted">Full tool schemas cost context. Only the small always-on core is shown by default; everything else is a one-line index until the mind calls tools.activate for its family. This changes only what is shown — every capability grant above still applies.</p>
+ </div>
+ <div className="flex items-start justify-between gap-4">
+ <div>
+ <label htmlFor={retentionId} className="text-sm text-port-text">Retention window (extra turns)</label>
+ <p className="mt-0.5 text-xs text-port-text-muted">How many additional user turns an activated family stays fully expanded after the turn that activated it. 0 is one-turn-only.</p>
+ </div>
+ <input
+ id={retentionId}
+ type="number"
+ min={MIN_RETENTION_TURNS}
+ max={MAX_RETENTION_TURNS}
+ step={1}
+ value={retentionTurns}
+ disabled={disabled || saving || allSchemas}
+ onChange={(event) => setRetentionTurns(clampRetentionTurns(event.target.value))}
+ onBlur={() => {
+ if (retentionTurns === clampRetentionTurns(capabilities?.toolExposureRetentionTurns ?? DEFAULT_RETENTION_TURNS)) return;
+ save({ toolExposureRetentionTurns: retentionTurns }, { successMessage: `Tool retention window set to ${retentionTurns} turn${retentionTurns === 1 ? '' : 's'}` });
+ }}
+ className="w-20 rounded border border-port-border bg-port-bg px-2 py-1 text-sm text-port-text disabled:opacity-50"
+ />
+ </div>
+ <div className="flex items-start justify-between gap-4">
+ <div>
+ <label htmlFor={allSchemasId} className="text-sm text-port-text">Send every schema on every turn (debug escape hatch)</label>
+ <p className="mt-0.5 text-xs text-port-text-muted">Restores the pre-progressive-exposure behavior: every granted tool's full schema, every turn. Use this only to debug a routing problem — it costs the most context.</p>
+ </div>
+ <input
+ id={allSchemasId}
+ type="checkbox"
+ checked={allSchemas}
+ disabled={disabled || saving}
+ onChange={(event) => {
+ const next = event.target.checked;
+ setAllSchemas(next);
+ save({ toolExposureAllSchemas: next }, { successMessage: `Full-schema exposure ${next ? 'enabled' : 'disabled'}` });
+ }}
+ className="mt-1 h-4 w-4 accent-port-accent disabled:opacity-50"
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/pages/PersistentMindTools.jsx b/client/src/pages/PersistentMindTools.jsx
index 228bc42407..f7ff304c08 100644
--- a/client/src/pages/PersistentMindTools.jsx
+++ b/client/src/pages/PersistentMindTools.jsx
@@ -7,6 +7,7 @@ import Banner from '../components/ui/Banner';
import PersistentMindRecipeLibrary from '../components/cos/PersistentMindRecipeLibrary';
import PersistentMindTaskAccessControls from '../components/cos/PersistentMindTaskAccessControls';
import PersistentMindTaskModelAllowlistControls from '../components/cos/PersistentMindTaskModelAllowlistControls';
+import PersistentMindToolExposureControls from '../components/cos/PersistentMindToolExposureControls';
export default function PersistentMindTools({ onCapabilitiesChange, onSavingChange }) {
const [data, setData] = useState(null);
@@ -88,7 +89,14 @@ export default function PersistentMindTools({ onCapabilitiesChange, onSavingChan
<div className="mt-3 grid gap-2 md:grid-cols-2">
{(data.semanticTools || []).map((tool) => (
<details key={tool.name} className="min-w-0 rounded border border-port-border p-2 text-xs">
- <summary className="cursor-pointer break-words font-medium text-port-text">{tool.name} · {tool.granted ? 'Granted' : 'Disabled'}</summary>
+ <summary className="cursor-pointer break-words font-medium text-port-text">
+ {tool.name} · {tool.granted ? 'Granted' : 'Disabled'}
+ {tool.family && (
+ <span className={`ml-2 rounded-full border px-2 py-0.5 text-[10px] font-normal normal-case ${tool.family === 'core' ? 'border-port-accent/40 text-port-accent' : 'border-port-border text-port-text-muted'}`}>
+ {tool.family === 'core' ? 'core' : `${tool.family} family`}
+ </span>
+ )}
+ </summary>
<p className="mt-2 text-port-text-muted">{tool.description}</p>
{tool.recipe && (
<div className="mt-2 rounded border border-port-border bg-port-bg p-2 text-port-text-muted">
@@ -141,6 +149,12 @@ export default function PersistentMindTools({ onCapabilitiesChange, onSavingChan
onSavingChange={handleCapabilitiesSavingChange}
/>
</div>
+ <PersistentMindToolExposureControls
+ capabilities={data.capabilities}
+ disabled={capabilitiesSaving}
+ onSaved={updateCapabilities}
+ onSavingChange={handleCapabilitiesSavingChange}
+ />
</section>
{taskCatalog && (
diff --git a/client/src/pages/PersistentMindTools.test.jsx b/client/src/pages/PersistentMindTools.test.jsx
index 3e835baaec..09418e458a 100644
--- a/client/src/pages/PersistentMindTools.test.jsx
+++ b/client/src/pages/PersistentMindTools.test.jsx
@@ -19,7 +19,7 @@ import PersistentMindTools from './PersistentMindTools';
const response = (overrides = {}) => ({
schemaVersion: 1,
- capabilities: { schemaVersion: 1, createTasks: false },
+ capabilities: { schemaVersion: 1, createTasks: false, toolExposureRetentionTurns: 3, toolExposureAllSchemas: false },
tools: [{
id: 'cos.create-task',
capability: 'createTasks',
@@ -254,6 +254,34 @@ describe('PersistentMindTools', () => {
));
});
+ it('saves the progressive tool-exposure retention window on blur and shows its current value', async () => {
+ const user = userEvent.setup();
+ renderPage();
+
+ const retentionInput = await screen.findByLabelText('Retention window (extra turns)');
+ expect(retentionInput).toHaveValue(3);
+ await user.clear(retentionInput);
+ await user.type(retentionInput, '5');
+ await user.tab();
+
+ await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith({
+ persistentMindCapabilities: { toolExposureRetentionTurns: 5 },
+ }, { silent: true }));
+ });
+
+ it('saves the all-schemas escape hatch as its own toggle without disturbing other grants', async () => {
+ const user = userEvent.setup();
+ renderPage();
+
+ const allSchemasToggle = await screen.findByRole('checkbox', { name: /Send every schema on every turn/ });
+ expect(allSchemasToggle).not.toBeChecked();
+ await user.click(allSchemasToggle);
+
+ await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith({
+ persistentMindCapabilities: { toolExposureAllSchemas: true },
+ }, { silent: true }));
+ });
+
it('keeps the failure visible instead of presenting an empty inventory', async () => {
api.getPersistentMindTools.mockRejectedValue(new Error('Server unreachable'));
renderPage();
diff --git a/server/lib/README.md b/server/lib/README.md
index c34dc6486d..f2292823c4 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -76,6 +76,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `persistentMindChosenName.js` | Validate and resolve an authoritative chosen-name identity memory, frame first-wake naming, and extract legacy chosen names from protected identity memories (`extractPersistentMindChosenName`, `resolvePersistentMindChosenName`) to drive the Eidoverse CoS join id (e.g. Helm). Presence reconnects on its next world action when the chosen name changes.
| `persistentMindUsageLimit.js` | Hard provider usage-limit / quota classifier for Persistent Mind wakes (`classifyPersistentMindProviderError`, `isHardProviderUsageLimitError`), the dedicated autopause reason string, and probe-backoff helpers so a usage-limit pause can auto-recover when the pinned provider is usable again without treating user pauses the same way.
| `persistentMindContextBudget.js` | Local context-budget / known-window-below-request-budget classifier for Persistent Mind wakes (`isContextBudgetFitnessError`, `publicContextBudgetReason`), plus actionable pause copy that keeps token counts and a numCtx recovery hint without exposing prompts or secrets.
+| `persistentMindToolActivation.js` | Pure lease-state helpers for progressive Persistent Mind tool exposure: the `TOOL_ACTIVATION_FAMILIES` vocabulary, `tools.activate`/`tools.deactivate` input schemas, and default/normalize/age/activate/renew/deactivate over a `{family: turnsLeft}` lease map. Retention is a selection hint only — every consumer still re-checks the real capability grant.
| `heavyJobClaim.js` | Cross-process, machine-wide accelerator claim: `claimHeavyLocalJob({ kind, id, timeoutMs? })` either acquires an ephemeral `data/` lock or reports its active holder; dead-PID claims are reclaimed, and a spawned child can take over the recorded PID across a server restart. |
| `agentValidation.js` | Social-bot agent schemas (personality, Moltbook/Moltworld accounts, automation schedules, agent tools + Moltworld payloads) and CoS Feature Agent definitions. |
| `autonomousJobTask.js` | `generatedJobTaskFields` — flattens a `generateTaskFromJob` result into the top-level keys the non-raw `cos.addTask` path maps onto metadata. One allowlist shared by the manual "Run now" endpoint and the quota-burn lane, so a key added to the generator cannot reach one and not the other. Pure. |
diff --git a/server/lib/index.js b/server/lib/index.js
index d1801f9541..1c07cd97b8 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -337,6 +337,7 @@ export * from './persistentMindThinkingPresets.js';
export * from './persistentMindChosenName.js';
export * from './persistentMindUsageLimit.js';
export * from './persistentMindContextBudget.js';
+export * from './persistentMindToolActivation.js';
export * from './agentScratchPaths.js';
export * from './agentSentinel.js';
export * from './bareUrl.js';
diff --git a/server/lib/mindToolRecipes.test.js b/server/lib/mindToolRecipes.test.js
index 50df1f0e37..52fbbb12d6 100644
--- a/server/lib/mindToolRecipes.test.js
+++ b/server/lib/mindToolRecipes.test.js
@@ -74,6 +74,6 @@ describe('closed, governed recipe definition boundary', () => {
it('defaults the definition grant off and preserves it across old capability updates', () => {
expect(createDefaultPersistentMindCapabilities().manageToolRecipes).toBe(false);
expect(persistentMindCapabilitiesSchema.safeParse({ schemaVersion: 8, readPortos: true }).success).toBe(true);
- expect(mergePersistentMindCapabilities({ manageToolRecipes: true }, { schemaVersion: 3, readPortos: false })).toMatchObject({ schemaVersion: 12, manageToolRecipes: true, readPortos: false });
+ expect(mergePersistentMindCapabilities({ manageToolRecipes: true }, { schemaVersion: 3, readPortos: false })).toMatchObject({ schemaVersion: 13, manageToolRecipes: true, readPortos: false });
});
});
diff --git a/server/lib/persistentMind.js b/server/lib/persistentMind.js
index 12588deeb6..a43e3a305a 100644
--- a/server/lib/persistentMind.js
+++ b/server/lib/persistentMind.js
@@ -17,6 +17,10 @@ import {
normalizePersistentMindThinkingRequests,
normalizePersistentMindThinkingSelection,
} from './persistentMindThinkingPresets.js';
+import {
+ createDefaultPersistentMindToolActivation,
+ normalizePersistentMindToolActivation,
+} from './persistentMindToolActivation.js';
import { trimTo } from './textUtils.js';
export const PERSISTENT_MIND_SCHEMA_VERSION = 8;
@@ -345,6 +349,12 @@ export function createDefaultPersistentMindState() {
recentMessageFingerprints: [],
callHistory: [],
thinkingRequests: normalizePersistentMindThinkingRequests(),
+ // Progressive tool exposure (#7624): which families' full schemas are
+ // still on lease from a prior turn's tools.activate/renewal, plus the
+ // turn id the lease was last aged against so a within-turn tool-round
+ // loop never ages it twice. A selection hint only — see
+ // persistentMindToolActivation.js for the "never authority" invariant.
+ toolActivation: createDefaultPersistentMindToolActivation(),
lastCompletedTurnId: null,
lastCompletedAt: null,
nextEligibleWakeAt: null,
@@ -453,6 +463,7 @@ export function normalizePersistentMindState(raw) {
recentMessageIds: recentMessageIds.slice(-PERSISTENT_MIND_LIMITS.MAX_RECENT_MESSAGE_IDS),
recentMessageFingerprints: recentMessageFingerprints.slice(-PERSISTENT_MIND_LIMITS.MAX_RECENT_MESSAGE_IDS),
thinkingRequests,
+ toolActivation: normalizePersistentMindToolActivation(source.toolActivation),
callHistory: callHistory.slice(-PERSISTENT_MIND_LIMITS.MAX_CALL_HISTORY),
lastCompletedTurnId: asId(source.lastCompletedTurnId) || null,
lastCompletedAt: asIso(source.lastCompletedAt),
diff --git a/server/lib/persistentMindCapabilities.js b/server/lib/persistentMindCapabilities.js
index a6f7f89432..674b4f05c8 100644
--- a/server/lib/persistentMindCapabilities.js
+++ b/server/lib/persistentMindCapabilities.js
@@ -13,13 +13,17 @@ import {
normalizePortosSemanticToolGrants,
portosSemanticToolGrantsSchema,
} from './cosToolContracts.js';
+import {
+ DEFAULT_TOOL_ACTIVATION_RETENTION_TURNS,
+ TOOL_ACTIVATION_LIMITS,
+} from './persistentMindToolActivation.js';
-export const PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION = 12;
+export const PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION = 13;
// Every wire version this server still accepts on input. Installs upgrade on
// their own schedule, so a browser bundle (or a route caller) pinned at an
// older version must keep being able to toggle the grants it already knows
// about; normalization always writes the current version forward.
-const ACCEPTED_CAPABILITIES_SCHEMA_VERSIONS = Object.freeze([2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
+const ACCEPTED_CAPABILITIES_SCHEMA_VERSIONS = Object.freeze([2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]);
export const PERSISTENT_MIND_TASK_MODEL_ALLOWLIST_LIMITS = Object.freeze({
MAX_ENTRIES: 200,
@@ -265,6 +269,17 @@ export const persistentMindCapabilitiesSchema = portosSemanticToolGrantsSchema.e
callUser: z.boolean().optional(),
chooseThinkingPreset: z.boolean().optional(),
adjustLocalContext: z.boolean().optional(),
+ // Progressive tool exposure (#7624): how many ADDITIONAL user turns after
+ // the one that called tools.activate a family's full schemas stay shown.
+ // 0 is deliberately one-turn-only. This is a selection hint, never an
+ // authority grant — it never widens what a granted tool may do.
+ toolExposureRetentionTurns: z.number().int()
+ .min(TOOL_ACTIVATION_LIMITS.MIN_RETENTION_TURNS)
+ .max(TOOL_ACTIVATION_LIMITS.MAX_RETENTION_TURNS)
+ .optional(),
+ // Escape hatch for debugging: reproduces the pre-#7624 behavior of sending
+ // every granted tool's full schema on every turn.
+ toolExposureAllSchemas: z.boolean().optional(),
thinkingPresetAllowlist: z.array(z.string().trim().min(1).max(64)).max(20).optional(),
// An empty list preserves the legacy unrestricted task catalog. Once any
// entries are configured, requests must name one of these exact pairs.
@@ -342,6 +357,8 @@ export function createDefaultPersistentMindCapabilities() {
callUser: false,
chooseThinkingPreset: false,
adjustLocalContext: false,
+ toolExposureRetentionTurns: DEFAULT_TOOL_ACTIVATION_RETENTION_TURNS,
+ toolExposureAllSchemas: false,
thinkingPresetAllowlist: [],
thinkingPresetGrants: {},
readPortos: false,
@@ -403,6 +420,12 @@ export function normalizePersistentMindCapabilities(raw) {
callUser: source.callUser === true,
chooseThinkingPreset: source.chooseThinkingPreset === true,
adjustLocalContext: source.adjustLocalContext === true,
+ toolExposureRetentionTurns: Number.isSafeInteger(source.toolExposureRetentionTurns)
+ && source.toolExposureRetentionTurns >= TOOL_ACTIVATION_LIMITS.MIN_RETENTION_TURNS
+ && source.toolExposureRetentionTurns <= TOOL_ACTIVATION_LIMITS.MAX_RETENTION_TURNS
+ ? source.toolExposureRetentionTurns
+ : DEFAULT_TOOL_ACTIVATION_RETENTION_TURNS,
+ toolExposureAllSchemas: source.toolExposureAllSchemas === true,
thinkingPresetAllowlist: z.array(z.string().min(1).max(64)).max(20).safeParse(source.thinkingPresetAllowlist).data || [],
thinkingPresetGrants: z.record(z.string(), z.string().regex(/^[a-f0-9]{64}$/)).safeParse(source.thinkingPresetGrants).data || {},
...semanticGrants,
diff --git a/server/lib/persistentMindCapabilities.test.js b/server/lib/persistentMindCapabilities.test.js
index d993138060..986a3dbee6 100644
--- a/server/lib/persistentMindCapabilities.test.js
+++ b/server/lib/persistentMindCapabilities.test.js
@@ -48,6 +48,18 @@ describe('persistent mind capabilities', () => {
expect(normalizePersistentMindCapabilities({ createTasks: 'true', readPortos: 'true' })).toMatchObject({ createTasks: false, readPortos: false });
});
+ it('defaults the progressive tool-exposure retention window and clamps hand-edited values', () => {
+ expect(createDefaultPersistentMindCapabilities()).toMatchObject({ toolExposureRetentionTurns: 3, toolExposureAllSchemas: false });
+ expect(normalizePersistentMindCapabilities({ toolExposureRetentionTurns: 0 })).toMatchObject({ toolExposureRetentionTurns: 0 });
+ expect(normalizePersistentMindCapabilities({ toolExposureRetentionTurns: 5, toolExposureAllSchemas: true }))
+ .toMatchObject({ toolExposureRetentionTurns: 5, toolExposureAllSchemas: true });
+ // Out-of-range or malformed values fall back to the default rather than
+ // silently clamping to the nearest bound, which would hide a corrupt file.
+ expect(normalizePersistentMindCapabilities({ toolExposureRetentionTurns: -1 })).toMatchObject({ toolExposureRetentionTurns: 3 });
+ expect(normalizePersistentMindCapabilities({ toolExposureRetentionTurns: 21 })).toMatchObject({ toolExposureRetentionTurns: 3 });
+ expect(normalizePersistentMindCapabilities({ toolExposureRetentionTurns: 'three' })).toMatchObject({ toolExposureRetentionTurns: 3 });
+ });
+
it('validates and merges the explicit task-creation grant', () => {
expect(persistentMindCapabilitiesSchema.safeParse({ createTasks: true, manageMind: true, manageEidoverse: true, readPortos: true, writePortos: false }).success).toBe(true);
expect(persistentMindCapabilitiesSchema.safeParse({ schemaVersion: 2, createTasks: true }).success).toBe(true);
@@ -56,10 +68,11 @@ describe('persistent mind capabilities', () => {
expect(persistentMindCapabilitiesSchema.safeParse({ schemaVersion: 8 }).success).toBe(true);
expect(persistentMindCapabilitiesSchema.safeParse({ schemaVersion: 11 }).success).toBe(true);
expect(persistentMindCapabilitiesSchema.safeParse({ schemaVersion: 12 }).success).toBe(true);
- expect(persistentMindCapabilitiesSchema.safeParse({ schemaVersion: 13 }).success).toBe(false);
+ expect(persistentMindCapabilitiesSchema.safeParse({ schemaVersion: 13 }).success).toBe(true);
+ expect(persistentMindCapabilitiesSchema.safeParse({ schemaVersion: 14 }).success).toBe(false);
expect(persistentMindCapabilitiesSchema.safeParse({ taskModelAllowlist: [{ providerId: 'ollama', model: 'example-local' }] }).success).toBe(true);
expect(normalizePersistentMindCapabilities({ schemaVersion: 2, createTasks: true }))
- .toMatchObject({ schemaVersion: 12, createTasks: true, fileIssues: false, manageMind: false, manageEidoverse: false, callUser: false, adjustLocalContext: false });
+ .toMatchObject({ schemaVersion: 13, createTasks: true, fileIssues: false, manageMind: false, manageEidoverse: false, callUser: false, adjustLocalContext: false });
expect(persistentMindCapabilitiesSchema.safeParse({ allowedAppIds: ['example-app', 'second-app'] }).success).toBe(true);
expect(persistentMindCapabilitiesSchema.safeParse({ allowedAppIds: Array.from({ length: 51 }, (_, index) => `app-${index}`) }).success).toBe(false);
expect(persistentMindCapabilitiesSchema.safeParse({ createTasks: true, shell: true }).success).toBe(false);
diff --git a/server/lib/persistentMindToolActivation.js b/server/lib/persistentMindToolActivation.js
new file mode 100644
index 0000000000..15ab4d836a
--- /dev/null
+++ b/server/lib/persistentMindToolActivation.js
@@ -0,0 +1,124 @@
+/**
+ * Pure state helpers for the Persistent Mind's progressive tool exposure
+ * (issue #7624): a small always-on core plus family-scoped explicit
+ * activation with a short, turn-scoped retention lease.
+ *
+ * Retention here is a SELECTION HINT, never an authority grant. Every helper
+ * in this module only decides what tool schemas are SHOWN to the mind on its
+ * next prompt. The capability/`granted` gate in cosToolRegistry.js runs
+ * independently at both selection and execution time, so a lease can never
+ * widen what the mind is allowed to do — a revoked capability drops a leased
+ * tool immediately regardless of anything recorded here.
+ */
+
+import { z } from 'zod';
+
+// Families mirror the existing capability/scope groupings already declared
+// per tool in cosToolRegistry.js (the precedent is TOOL_GROUPS/GROUP_INTENT
+// in server/services/voice/tools.js) — no new vocabulary.
+export const TOOL_ACTIVATION_FAMILIES = Object.freeze(['tasks', 'issues', 'mind', 'eidoverse', 'recipes', 'voice']);
+
+export const TOOL_ACTIVATION_LIMITS = Object.freeze({
+ MIN_RETENTION_TURNS: 0,
+ MAX_RETENTION_TURNS: 20,
+});
+
+// 0 is deliberately "one-turn behaviour": activating a family only expands it
+// for the turn that activated it, with nothing persisted for the next one.
+export const DEFAULT_TOOL_ACTIVATION_RETENTION_TURNS = 3;
+
+export const toolActivationFamilySchema = z.enum(TOOL_ACTIVATION_FAMILIES);
+
+export const toolsActivateInputSchema = z.object({
+ families: z.array(toolActivationFamilySchema).min(1).max(TOOL_ACTIVATION_FAMILIES.length),
+}).strict();
+
+export const toolsDeactivateInputSchema = z.object({
+ // Omitted clears every currently-selected/leased family.
+ families: z.array(toolActivationFamilySchema).min(1).max(TOOL_ACTIVATION_FAMILIES.length).optional(),
+}).strict();
+
+const isValidFamily = (value) => TOOL_ACTIVATION_FAMILIES.includes(value);
+// A lease VALUE of 0 is meaningful — it means "this is the family's last
+// turn, still fully exposed" (see agePersistentMindToolActivation) — so
+// stored leases accept zero. Only a fresh ACTIVATION (below) requires a
+// strictly positive retention count; activating with 0 persists nothing.
+const isNonNegativeInt = (value) => Number.isSafeInteger(value) && value >= 0;
+const isPositiveInt = (value) => Number.isSafeInteger(value) && value > 0;
+
+export function createDefaultPersistentMindToolActivation() {
+ return { leases: {}, lastAgedTurnId: null };
+}
+
+/** Normalize hand-edited or legacy state: unknown families and negative/non-integer counts are dropped. */
+export function normalizePersistentMindToolActivation(raw) {
+ const leases = {};
+ const source = raw?.leases;
+ if (source && typeof source === 'object' && !Array.isArray(source)) {
+ for (const family of TOOL_ACTIVATION_FAMILIES) {
+ if (isNonNegativeInt(source[family])) leases[family] = source[family];
+ }
+ }
+ const lastAgedTurnId = typeof raw?.lastAgedTurnId === 'string' && raw.lastAgedTurnId.trim()
+ ? raw.lastAgedTurnId.trim().slice(0, 200)
+ : null;
+ return { leases, lastAgedTurnId };
+}
+
+/**
+ * Age every existing lease by exactly one USER turn. Call this at most once
+ * per user turn — never per tool-round loop within a single turn, or a
+ * multi-step sequence would lose its own tools mid-flow — and never at all
+ * for a self-directed wake.
+ *
+ * A family already at 0 (its floor, set by a PRIOR aging pass) is dropped:
+ * that prior turn was its last one. Everything else decrements with a floor
+ * of 0 rather than being deleted immediately, so a family that just reached
+ * its floor THIS aging pass stays present — and therefore still exposed —
+ * for every remaining tool-round rebuild within the turn being aged, not
+ * only the first one.
+ */
+export function agePersistentMindToolActivation(leases) {
+ const normalized = normalizePersistentMindToolActivation({ leases }).leases;
+ const nextLeases = {};
+ for (const [family, turnsLeft] of Object.entries(normalized)) {
+ if (turnsLeft <= 0) continue;
+ nextLeases[family] = Math.max(turnsLeft - 1, 0);
+ }
+ return { leases: nextLeases };
+}
+
+/**
+ * Activate one or more families for a fresh `retentionTurns`-turn window.
+ * `retentionTurns <= 0` persists nothing — the family is still exposed for
+ * whatever turn calls this (the caller re-reads `leases` afterward), but
+ * ages away immediately rather than surviving into the next user turn.
+ */
+export function activatePersistentMindToolActivationFamilies(leases, families, retentionTurns) {
+ const normalized = normalizePersistentMindToolActivation({ leases }).leases;
+ const next = { ...normalized };
+ if (isPositiveInt(retentionTurns)) {
+ for (const family of Array.isArray(families) ? families : []) {
+ if (isValidFamily(family)) next[family] = retentionTurns;
+ }
+ }
+ return next;
+}
+
+/**
+ * Renew a single family's lease back to the full retention window because a
+ * tool from it was just used — extending only the family actually exercised,
+ * never every family the turn happens to have activated.
+ */
+export function renewPersistentMindToolActivationFamily(leases, family, retentionTurns) {
+ return activatePersistentMindToolActivationFamilies(leases, [family], retentionTurns);
+}
+
+/** Clear one or more families (or all, when `families` is omitted/empty) — tools.deactivate. */
+export function deactivatePersistentMindToolActivationFamilies(leases, families) {
+ const normalized = normalizePersistentMindToolActivation({ leases }).leases;
+ if (!Array.isArray(families) || families.length === 0) return {};
+ const next = { ...normalized };
+ for (const family of families) delete next[family];
+ return next;
+}
diff --git a/server/lib/persistentMindToolActivation.test.js b/server/lib/persistentMindToolActivation.test.js
new file mode 100644
index 0000000000..6ec9ff5d46
--- /dev/null
+++ b/server/lib/persistentMindToolActivation.test.js
@@ -0,0 +1,74 @@
+import { describe, expect, it } from 'vitest';
+import {
+ DEFAULT_TOOL_ACTIVATION_RETENTION_TURNS,
+ activatePersistentMindToolActivationFamilies,
+ agePersistentMindToolActivation,
+ createDefaultPersistentMindToolActivation,
+ deactivatePersistentMindToolActivationFamilies,
+ normalizePersistentMindToolActivation,
+ renewPersistentMindToolActivationFamily,
+ toolsActivateInputSchema,
+ toolsDeactivateInputSchema,
+} from './persistentMindToolActivation.js';
+
+describe('persistentMindToolActivation', () => {
+ it('defaults to no leases and drops unknown families or non-integer/negative counts on normalize', () => {
+ expect(createDefaultPersistentMindToolActivation()).toEqual({ leases: {}, lastAgedTurnId: null });
+ expect(normalizePersistentMindToolActivation(null)).toEqual({ leases: {}, lastAgedTurnId: null });
+ expect(normalizePersistentMindToolActivation({
+ leases: { mind: 2, bogus: 5, eidoverse: -1, voice: 1.5, tasks: '3' },
+ lastAgedTurnId: 'turn-1',
+ })).toEqual({ leases: { mind: 2 }, lastAgedTurnId: 'turn-1' });
+ });
+
+ it('activates a family for exactly the configured retention window and skips persisting a zero-turn activation', () => {
+ expect(activatePersistentMindToolActivationFamilies({}, ['mind', 'eidoverse'], 3)).toEqual({ mind: 3, eidoverse: 3 });
+ // 0 is deliberately one-turn-only: nothing survives for a future turn.
+ expect(activatePersistentMindToolActivationFamilies({}, ['mind'], 0)).toEqual({});
+ // An unknown family name is silently ignored rather than corrupting the map.
+ expect(activatePersistentMindToolActivationFamilies({}, ['not-a-family'], 3)).toEqual({});
+ });
+
+ it('ages a lease down to its floor, keeps it visible on its last turn, and drops it only the turn after', () => {
+ // Activated with a 1-turn window: still present (at floor 0) for exactly
+ // one more aging pass — visible through every round-refresh of that
+ // turn — then gone on the next.
+ const leases = activatePersistentMindToolActivationFamilies({}, ['mind'], 1);
+ const afterFirstAge = agePersistentMindToolActivation(leases);
+ expect(afterFirstAge.leases).toEqual({ mind: 0 });
+ const afterSecondAge = agePersistentMindToolActivation(afterFirstAge.leases);
+ expect(afterSecondAge.leases).toEqual({});
+ });
+
+ it('ages a multi-turn lease down by exactly one turn per call', () => {
+ const leases = activatePersistentMindToolActivationFamilies({}, ['eidoverse'], 3);
+ const once = agePersistentMindToolActivation(leases);
+ expect(once.leases).toEqual({ eidoverse: 2 });
+ const twice = agePersistentMindToolActivation(once.leases);
+ expect(twice.leases).toEqual({ eidoverse: 1 });
+ });
+
+ it('renews only the family actually used, leaving an unrelated activated family to keep aging', () => {
+ const leases = activatePersistentMindToolActivationFamilies({}, ['mind', 'eidoverse'], 3);
+ const aged = agePersistentMindToolActivation(leases).leases; // { mind: 2, eidoverse: 2 }
+ const renewed = renewPersistentMindToolActivationFamily(aged, 'mind', DEFAULT_TOOL_ACTIVATION_RETENTION_TURNS);
+ expect(renewed).toEqual({ mind: DEFAULT_TOOL_ACTIVATION_RETENTION_TURNS, eidoverse: 2 });
+ });
+
+ it('deactivate clears named families or, with none given, every lease', () => {
+ const leases = activatePersistentMindToolActivationFamilies({}, ['mind', 'eidoverse', 'voice'], 3);
+ expect(deactivatePersistentMindToolActivationFamilies(leases, ['mind'])).toEqual({ eidoverse: 3, voice: 3 });
+ expect(deactivatePersistentMindToolActivationFamilies(leases, undefined)).toEqual({});
+ expect(deactivatePersistentMindToolActivationFamilies(leases, [])).toEqual({});
+ });
+
+ it('validates tools.activate/tools.deactivate input against the exact family vocabulary', () => {
+ expect(toolsActivateInputSchema.safeParse({ families: ['mind', 'eidoverse'] }).success).toBe(true);
+ expect(toolsActivateInputSchema.safeParse({ families: [] }).success).toBe(false);
+ expect(toolsActivateInputSchema.safeParse({ families: ['not-a-family'] }).success).toBe(false);
+ expect(toolsActivateInputSchema.safeParse({}).success).toBe(false);
+ expect(toolsDeactivateInputSchema.safeParse({}).success).toBe(true);
+ expect(toolsDeactivateInputSchema.safeParse({ families: ['voice'] }).success).toBe(true);
+ expect(toolsDeactivateInputSchema.safeParse({ families: ['not-a-family'] }).success).toBe(false);
+ });
+});
diff --git a/server/routes/cosMindRoutes.test.js b/server/routes/cosMindRoutes.test.js
index 2065883e0d..2840c5b7ec 100644
--- a/server/routes/cosMindRoutes.test.js
+++ b/server/routes/cosMindRoutes.test.js
@@ -227,7 +227,7 @@ describe('persistent mind routes', () => {
thinkingInterface: 'text',
wakeIntervalMinutes: 30,
},
- capabilities: { schemaVersion: 12, createTasks: true, fileIssues: false, manageMind: false, manageEidoverse: false, visitEidoversePeers: false, promoteEidoverseFoundations: false, callUser: false, adjustLocalContext: false, readPortos: false, writePortos: false, taskModelAllowlist: [] },
+ capabilities: { schemaVersion: 13, createTasks: true, fileIssues: false, manageMind: false, manageEidoverse: false, visitEidoversePeers: false, promoteEidoverseFoundations: false, callUser: false, adjustLocalContext: false, readPortos: false, writePortos: false, taskModelAllowlist: [], toolExposureRetentionTurns: 3, toolExposureAllSchemas: false },
harness: { type: 'api', recommendation: 'recommended' },
imageCapability: { status: 'unknown' },
autonomyMode: 'execute',
@@ -321,8 +321,8 @@ describe('persistent mind routes', () => {
expect.objectContaining({ name: 'eidoverse.status', granted: false, input_schema: expect.any(Object) }),
expect.objectContaining({ name: 'cos.create-task', granted: true }),
]),
- schemaVersion: 12,
- capabilities: { schemaVersion: 12, createTasks: true, fileIssues: false, manageMind: false, manageEidoverse: false, visitEidoversePeers: false, promoteEidoverseFoundations: false, callUser: false, adjustLocalContext: false, readPortos: false, writePortos: false, taskModelAllowlist: [] },
+ schemaVersion: 13,
+ capabilities: { schemaVersion: 13, createTasks: true, fileIssues: false, manageMind: false, manageEidoverse: false, visitEidoversePeers: false, promoteEidoverseFoundations: false, callUser: false, adjustLocalContext: false, readPortos: false, writePortos: false, taskModelAllowlist: [], toolExposureRetentionTurns: 3, toolExposureAllSchemas: false },
boundaries: expect.arrayContaining([expect.stringMatching(/arbitrary shell/i)]),
tools: expect.arrayContaining([
expect.objectContaining({ id: 'cos.create-task', capability: 'createTasks', granted: true, defaultEnabled: false }),
diff --git a/server/services/cosToolRegistry.js b/server/services/cosToolRegistry.js
index 5369afb383..f5d5b80bdf 100644
--- a/server/services/cosToolRegistry.js
+++ b/server/services/cosToolRegistry.js
@@ -15,9 +15,20 @@ import { canonicalStringify } from '../lib/objects.js';
import { sha256Text } from '../lib/fileUtils.js';
import { ServerError } from '../lib/errorHandler.js';
import {
+ normalizePersistentMindCapabilities,
persistentMindCleanupRequestSchema,
persistentMindTaskRequestSchema,
} from '../lib/persistentMindCapabilities.js';
+import {
+ TOOL_ACTIVATION_FAMILIES,
+ activatePersistentMindToolActivationFamilies,
+ agePersistentMindToolActivation,
+ deactivatePersistentMindToolActivationFamilies,
+ normalizePersistentMindToolActivation,
+ renewPersistentMindToolActivationFamily,
+ toolsActivateInputSchema,
+ toolsDeactivateInputSchema,
+} from '../lib/persistentMindToolActivation.js';
import {
persistentMindIssueFileSchema,
persistentMindIssueListSchema,
@@ -241,6 +252,53 @@ const mindChooseNameTool = Object.freeze({
adapter: { kind: 'persistent-mind-name' },
});
+// Progressive tool exposure (#7624): a small always-on core (this pair, plus
+// user-actions.query below) is the only thing every mind turn sees at full
+// schema by default. Everything else is grouped into a family and shown only
+// as a one-line discoverable index until the mind calls tools.activate for
+// it — see buildPersistentMindToolPrompt. Neither tool requires a capability:
+// they only ever change what is SHOWN, never what a granted tool may do, so
+// gating them on a grant would make that invariant harder to see, not easier.
+const toolsActivateTool = Object.freeze({
+ type: 'portos_tool',
+ name: 'tools.activate',
+ 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.`,
+ input_schema: zodToOpenApiSchema(toolsActivateInputSchema),
+ output_schema: objectOutputSchema,
+ policy: {
+ scopes: ['mind'],
+ requiredCapabilities: [],
+ sideEffect: 'write',
+ idempotent: true,
+ async: false,
+ confirmation: 'none',
+ },
+ adapter: { kind: 'tools-activate' },
+});
+
+const toolsDeactivateTool = Object.freeze({
+ type: 'portos_tool',
+ name: 'tools.deactivate',
+ version: COS_TOOL_SCHEMA_VERSION,
+ providerName: providerToolName('tools.deactivate'),
+ aliases: [providerToolName('tools.deactivate')],
+ description: 'Collapse one or more tool families back to their one-line discoverable index. Clears both this turn\'s selection and any retained lease. Omit families to clear all of them.',
+ input_schema: zodToOpenApiSchema(toolsDeactivateInputSchema),
+ output_schema: objectOutputSchema,
+ policy: {
+ scopes: ['mind'],
+ requiredCapabilities: [],
+ sideEffect: 'write',
+ idempotent: true,
+ async: false,
+ confirmation: 'none',
+ },
+ adapter: { kind: 'tools-deactivate' },
+});
+
// One mind turn must not be able to dump the whole ledger into context — the
// store's own list cap (500) is sized for the HTTP API, not a prompt.
export const USER_ACTIONS_QUERY_MAX_RESULTS = 100;
@@ -501,10 +559,54 @@ const localContextTools = (() => {
},
];
})();
-const toolCatalog = (intent) => [...recipeManagementTools, ...thinkingTools, ...localContextTools, taskTool, ...issueTools, mindCleanupTool, mindProtectMemoryTool, mindChooseNameTool, userActionsQueryTool, ...eidoverseTools, ...voiceTools(intent)];
+// Everything except the voice tools, which are sourced dynamically per intent
+// from voice/tools.js. Kept separate so the fail-fast family check below can
+// validate it without forcing voiceTools() (and the module it lazily depends
+// on) to evaluate at cosToolRegistry.js's own import time.
+const staticToolCatalog = [toolsActivateTool, toolsDeactivateTool, ...recipeManagementTools, ...thinkingTools, ...localContextTools, taskTool, ...issueTools, mindCleanupTool, mindProtectMemoryTool, mindChooseNameTool, userActionsQueryTool, ...eidoverseTools];
+const toolCatalog = (intent) => [...staticToolCatalog, ...voiceTools(intent)];
const toolCalls = new Map();
const toolCallFingerprints = new Map();
+// Family membership per tool (#7624), mirroring the TOOL_GROUPS/GROUP_INTENT
+// shape in voice/tools.js: a lookup table rather than a field on every tool
+// literal, so the mapping and the fail-fast guard below can't drift apart
+// silently. 'core' tools are always shown at full schema; everything else is
+// hidden behind its family until tools.activate names it.
+const CORE_TOOL_NAMES = Object.freeze(new Set(['tools.activate', 'tools.deactivate', 'user-actions.query']));
+const MIND_FAMILY_BY_TOOL_NAME = Object.freeze({
+ 'cos.create-task': 'tasks',
+ 'issues.list': 'issues',
+ 'issues.file': 'issues',
+ 'mind.cleanup': 'mind',
+ 'mind.protect-memory': 'mind',
+ 'mind.choose-name': 'mind',
+ 'mind.thinking-presets': 'mind',
+ 'mind.request-thinking-preset': 'mind',
+ 'mind.local-context': 'mind',
+ 'mind.adjust-local-context': 'mind',
+});
+
+const familyForTool = (tool) => {
+ if (!tool) return null;
+ if (CORE_TOOL_NAMES.has(tool.name)) return 'core';
+ if (tool.recipe || tool.adapter?.kind === 'recipe-management' || tool.adapter?.kind === 'recipe') return 'recipes';
+ if (tool.adapter?.kind === 'voice-tool') return 'voice';
+ if (tool.name.startsWith('eidoverse.')) return 'eidoverse';
+ return MIND_FAMILY_BY_TOOL_NAME[tool.name] || null;
+};
+
+// Fail-fast at import time: every mind-scope tool must resolve to a real
+// family or a forgotten mapping would silently make that tool
+// undiscoverable — never shown even by name — once progressive exposure
+// hides its schema. Saved recipes are exempt: they arrive at runtime from
+// outside toolCatalog() and are always classified 'recipes' via `tool.recipe`.
+for (const tool of staticToolCatalog) {
+ if (tool.policy.scopes.includes('mind') && !familyForTool(tool)) {
+ throw new Error(`cosToolRegistry: no tool-activation family mapped for mind-scope tool "${tool.name}"`);
+ }
+}
+
const normalizeToolCapabilities = (raw) => ({
...normalizePortosSemanticToolGrants(raw),
createTasks: raw?.createTasks === true,
@@ -536,6 +638,10 @@ const publicTool = (tool, { scope, capabilities }) => {
input_schema: tool.input_schema,
output_schema: tool.output_schema,
policy: tool.policy,
+ // 'core' for the small always-on set, a family name for everything else
+ // gated behind tools.activate, or null for a tool outside mind/agent
+ // scope that progressive exposure never applies to. See #7624.
+ family: familyForTool(tool),
availableInScope: scope === 'all' || tool.policy.scopes.includes(scope),
granted: !['agent', 'mind'].includes(scope)
? null
@@ -599,24 +705,146 @@ export const readCosToolRecipeCatalog = async ({ scope = 'mind' } = {}) => {
return readRecipeToolsForScope(scope, getCosToolCatalog({ scope }).tools);
};
-export const buildPersistentMindToolPrompt = (capabilities, recipes = []) => {
+const TOOL_EXPOSURE_HEADER = 'You may request up to five calls from the exact catalog below. These are semantic actions, not raw HTTP routes. Never invent a name, route, or argument. Use a stable requestId when practical and never submit the same action in both toolCalls and taskRequests.';
+const TOOL_EXPOSURE_FOOTER = 'Calls without requestId are coalesced by canonical tool name and arguments within this turn. Supply distinct requestId values only when two intentionally identical actions must both run.';
+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')}`
+ : '';
+ return `# PortOS semantic tools
+${TOOL_EXPOSURE_HEADER}
+
+${JSON.stringify(tools)}${discoverableBlock}
+
+${TOOL_EXPOSURE_FOOTER}`;
+};
+
+// First sentence, hard-capped: the whole point of the discoverable index is
+// spending far fewer tokens per hidden tool than its full schema would.
+const toolPurpose = (description) => {
+ const text = String(description || '').replace(/\s+/g, ' ').trim();
+ const firstSentence = (text.match(/^.*?[.!?](?:\s|$)/)?.[0] || text).trim();
+ return firstSentence.length > TOOL_PURPOSE_MAX_CHARS
+ ? `${firstSentence.slice(0, TOOL_PURPOSE_MAX_CHARS - 1)}…`
+ : firstSentence;
+};
+
+const fullSchemaShape = (tool) => ({
+ name: tool.name,
+ description: tool.description,
+ input_schema: tool.input_schema,
+ sideEffect: tool.policy.sideEffect,
+});
+
+// One aggregate, tool-name-free line per turn (never per intermediate tool
+// round — see the `trace` option below) so the exposure/retention behavior is
+// observable in logs without ever naming a tool, an argument, or user text.
+const logToolExposureTrace = (stats) => {
+ const excluded = Object.entries(stats.excludedByReason)
+ .filter(([, count]) => count > 0)
+ .map(([reason, count]) => `${reason}=${count}`)
+ .join(' ') || 'none';
+ console.log(`🧰 Mind tool exposure: registered=${stats.registered} eligible=${stats.eligible} core=${stats.core} activated=${stats.activated} retained=${stats.retained} excluded(${excluded})`);
+};
+
+/**
+ * Build the Persistent Mind's tool-catalog prompt section.
+ *
+ * Progressive exposure (#7624): a small always-on core plus family-scoped
+ * explicit activation with a short turn-scoped retention lease, so a small
+ * local model is never handed every granted tool's full JSON Schema on every
+ * turn. `turnId`/`isUserTurn` age the lease at most once per USER turn — pass
+ * `isUserTurn: false` (or omit it) for a self-directed wake and for every
+ * intermediate tool-round rebuild within one turn. `trace: true` on exactly
+ * one call per turn (the first) logs the one aggregate line for it.
+ *
+ * `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 } = {}) => {
+ const grants = normalizePersistentMindCapabilities(capabilities);
const catalog = getCosToolCatalog({ scope: 'mind', capabilities, recipes });
- const tools = catalog.tools.filter((tool) => tool.granted).map((tool) => ({
- name: tool.name,
- description: tool.description,
- input_schema: tool.input_schema,
- sideEffect: tool.policy.sideEffect,
- }));
- if (tools.length === 0) {
+ const granted = catalog.tools.filter((tool) => tool.granted);
+ // tools.activate/tools.deactivate are withheld along with everything else
+ // when there is nothing else granted to activate — matching the pre-#7624
+ // "semantic tool access is OFF" contract exactly for a fully ungranted mind.
+ const meaningful = granted.filter((tool) => !['tools.activate', 'tools.deactivate'].includes(tool.name));
+ if (meaningful.length === 0) {
+ if (trace) {
+ logToolExposureTrace({
+ registered: catalog.tools.length, eligible: 0, core: 0, activated: 0, retained: 0,
+ excludedByReason: { ungranted: catalog.tools.length },
+ });
+ }
return `# PortOS semantic tools
Semantic tool access is OFF. Return an empty toolCalls array. Never invent a tool name or claim that a PortOS action ran.`;
}
- return `# PortOS semantic tools
-You may request up to five calls from the exact catalog below. These are semantic actions, not raw HTTP routes. Never invent a name, route, or argument. Use a stable requestId when practical and never submit the same action in both toolCalls and taskRequests.
-${JSON.stringify(tools)}
+ if (grants.toolExposureAllSchemas) {
+ if (trace) {
+ logToolExposureTrace({
+ registered: catalog.tools.length, eligible: granted.length, core: granted.length, activated: 0, retained: 0,
+ excludedByReason: { ungranted: catalog.tools.length - granted.length },
+ });
+ }
+ return renderToolPrompt(granted.map(fullSchemaShape));
+ }
-Calls without requestId are coalesced by canonical tool name and arguments within this turn. Supply distinct requestId values only when two intentionally identical actions must both run.`;
+ const { loadState, saveState, withStateLock } = await import('./cosState.js');
+ const readCurrentLeases = async () => normalizePersistentMindToolActivation((await loadState()).persistentMind?.toolActivation);
+ let activation = await readCurrentLeases();
+ if (isUserTurn && turnId && activation.lastAgedTurnId !== turnId) {
+ activation = await withStateLock(async () => {
+ const root = await loadState();
+ const latest = normalizePersistentMindToolActivation(root.persistentMind.toolActivation);
+ if (latest.lastAgedTurnId === turnId) return latest;
+ const { leases } = agePersistentMindToolActivation(latest.leases);
+ const next = { leases, lastAgedTurnId: turnId };
+ root.persistentMind = { ...root.persistentMind, toolActivation: next };
+ await saveState(root);
+ return next;
+ });
+ }
+
+ 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)) {
+ exposedTools.push(tool);
+ } else {
+ if (!discoverableByFamily.has(tool.family)) discoverableByFamily.set(tool.family, []);
+ discoverableByFamily.get(tool.family).push(tool);
+ }
+ }
+
+ if (trace) {
+ // A family sitting at its full retention value looks freshly
+ // (re)activated; one that has aged down is coasting on retention alone.
+ // This distinguishes the two counts without any extra persisted state.
+ const leaseValues = Object.values(activation.leases);
+ const activated = leaseValues.filter((turnsLeft) => turnsLeft === grants.toolExposureRetentionTurns).length;
+ logToolExposureTrace({
+ registered: catalog.tools.length,
+ eligible: granted.length,
+ core: controlTools.length + meaningful.filter((tool) => tool.family === 'core').length,
+ activated,
+ retained: leaseValues.length - activated,
+ excludedByReason: {
+ ungranted: catalog.tools.length - granted.length,
+ notActivated: [...discoverableByFamily.values()].reduce((sum, tools) => sum + tools.length, 0),
+ },
+ });
+ }
+
+ const discoverableLines = [...discoverableByFamily.entries()].map(([family, tools]) => (
+ `- ${family} (${tools.length}): ${tools.map((tool) => `${tool.name} — ${toolPurpose(tool.description)}`).join('; ')}`
+ ));
+
+ return renderToolPrompt([...controlTools, ...exposedTools].map(fullSchemaShape), discoverableLines);
};
export const readPersistentMindRecipeCatalog = (capabilities) => readMindRecipeTools(capabilities, getCosToolCatalog({ scope: 'mind' }).tools);
@@ -661,6 +889,22 @@ const validateArguments = (tool, args) => {
const executeAdapter = async (tool, args, context, authority) => {
if (tool.adapter.kind === 'recipe-management') return executeRecipeManagement(tool, args, context);
if (tool.adapter.kind === 'recipe') return executeRecipe(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);
+ return withStateLock(async () => {
+ const root = await loadState();
+ const current = normalizePersistentMindToolActivation(root.persistentMind.toolActivation);
+ const leases = tool.adapter.kind === 'tools-activate'
+ ? activatePersistentMindToolActivationFamilies(current.leases, args.families, grants.toolExposureRetentionTurns)
+ : deactivatePersistentMindToolActivationFamilies(current.leases, args.families);
+ 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) };
+ });
+ }
if (tool.adapter.kind.startsWith('thinking-')) {
const { getPersistentMindThinkingRequestCatalog, requestPersistentMindThinkingPreset } = await import('./persistentMindThinkingRequests.js');
return tool.adapter.kind === 'thinking-catalog'
@@ -871,6 +1115,28 @@ const normalizeAdapterResult = ({ parsedCall, tool, result }) => {
};
};
+// A successful mind-scope call from a leased/activatable family renews only
+// that family's window — an unrelated activated-but-unused family still ages
+// normally. Never runs for 'core'/unclassified tools (nothing to renew) or
+// under the all-schemas escape hatch (leases are inert there). Errors are
+// swallowed: a lease-bookkeeping failure must never turn a completed tool
+// call into a failed one.
+const renewToolActivationLeaseOnUse = async (tool, authority, succeeded) => {
+ if (!succeeded || authority?.scope !== 'mind') return;
+ const family = familyForTool(tool);
+ if (!family || family === 'core') return;
+ const grants = normalizePersistentMindCapabilities(authority.capabilities);
+ if (grants.toolExposureAllSchemas || !(grants.toolExposureRetentionTurns > 0)) return;
+ const { loadState, saveState, withStateLock } = await import('./cosState.js');
+ await withStateLock(async () => {
+ const root = await loadState();
+ const current = normalizePersistentMindToolActivation(root.persistentMind.toolActivation);
+ const leases = renewPersistentMindToolActivationFamily(current.leases, family, grants.toolExposureRetentionTurns);
+ root.persistentMind = { ...root.persistentMind, toolActivation: { leases, lastAgedTurnId: current.lastAgedTurnId } };
+ await saveState(root);
+ });
+};
+
export const executeCosToolCall = async ({ call, authority, context = {} }) => {
const parsedCall = cosToolCallSchema.parse(call);
let tool = resolveTool(parsedCall.name);
@@ -921,7 +1187,11 @@ export const executeCosToolCall = async ({ call, authority, context = {} }) => {
duplicate: false,
error: String(error?.message || error || 'Tool execution failed').slice(0, 500),
}),
- );
+ )
+ .then(async (normalized) => {
+ await renewToolActivationLeaseOnUse(tool, authority, normalized.state === 'completed').catch(() => {});
+ return normalized;
+ });
toolCallFingerprints.set(parsedCall.requestId, {
fingerprint,
expiresAt: Date.now() + IDEMPOTENCY_RETENTION_MS,
diff --git a/server/services/cosToolRegistry.test.js b/server/services/cosToolRegistry.test.js
index f635ba17f6..a273651540 100644
--- a/server/services/cosToolRegistry.test.js
+++ b/server/services/cosToolRegistry.test.js
@@ -1,6 +1,7 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
+ root: { persistentMind: { toolActivation: { leases: {}, lastAgedTurnId: null } } },
dispatch: vi.fn(),
executeTasks: vi.fn(),
cleanupMind: vi.fn(),
@@ -83,7 +84,17 @@ vi.mock('./instanceIdentity.js', () => ({
vi.mock('./userActions.js', () => ({
listUserActions: (...args) => mocks.listUserActions(...args),
}));
+// Only the progressive tool-exposure lease (#7624) reaches cosState.js
+// directly — every other adapter's own state access goes through a mock
+// above. A bare, mutable in-memory root keeps every existing executeCosToolCall
+// test hermetic instead of touching the real state file.
+vi.mock('./cosState.js', () => ({
+ loadState: vi.fn(async () => mocks.root),
+ saveState: vi.fn(async (root) => { mocks.root = root; }),
+ withStateLock: vi.fn(async (fn) => fn()),
+}));
+import { DEFAULT_TOOL_ACTIVATION_RETENTION_TURNS } from '../lib/persistentMindToolActivation.js';
import {
__testing,
buildPersistentMindToolPrompt,
@@ -96,6 +107,7 @@ beforeEach(() => {
vi.clearAllMocks();
__testing.toolCalls.clear();
__testing.toolCallFingerprints.clear();
+ mocks.root = { persistentMind: { toolActivation: { leases: {}, lastAgedTurnId: null } } };
mocks.dispatch.mockResolvedValue({ ok: true });
mocks.executeTasks.mockResolvedValue([{ success: true, task: { id: 'task-1' }, duplicate: false }]);
mocks.cleanupMind.mockResolvedValue({ ok: true, success: true, state: 'completed', historyEventsCleared: 8 });
@@ -229,7 +241,7 @@ describe('cosToolRegistry', () => {
await expect(executeCosToolCall({ call, authority: { scope: 'mind', capabilities: { writePortos: true, createTasks: true } } })).rejects.toMatchObject({ code: 'TOOL_CAPABILITY_DENIED' });
await expect(executeCosToolCall({ call: { ...call, arguments: { ...call.arguments, endpoint: 'https://example.com' } }, authority: { scope: 'mind', capabilities: { chooseThinkingPreset: true } } })).rejects.toMatchObject({ code: 'TOOL_VALIDATION_ERROR' });
await expect(executeCosToolCall({ call, authority: { scope: 'agent', capabilities: { chooseThinkingPreset: true } } })).rejects.toMatchObject({ code: 'TOOL_SCOPE_DENIED' });
- expect(getCosToolCatalog({ scope: 'mind', capabilities: { chooseThinkingPreset: true } }).tools.filter((tool) => tool.granted).map((tool) => tool.name)).toEqual(['mind.thinking-presets', 'mind.request-thinking-preset']);
+ expect(getCosToolCatalog({ scope: 'mind', capabilities: { chooseThinkingPreset: true } }).tools.filter((tool) => tool.granted).map((tool) => tool.name)).toEqual(['tools.activate', 'tools.deactivate', 'mind.thinking-presets', 'mind.request-thinking-preset']);
});
it('gates the forge-issue tools on their own grant and routes them to the issue adapter', async () => {
@@ -246,12 +258,13 @@ describe('cosToolRegistry', () => {
expect(result).toMatchObject({ name: 'issues.file', state: 'completed', result: { number: 42 } });
expect(mocks.fileIssue).toHaveBeenCalledWith(call.arguments);
expect(getCosToolCatalog({ scope: 'mind', capabilities: { fileIssues: true } }).tools.filter((tool) => tool.granted).map((tool) => tool.name))
- .toEqual(['issues.list', 'issues.file']);
+ .toEqual(['tools.activate', 'tools.deactivate', 'issues.list', 'issues.file']);
});
it('exports a compact canonical catalog and provider translations', () => {
const catalog = getCosToolCatalog({ scope: 'mind', capabilities: { readPortos: true } });
expect(catalog.tools.map((tool) => tool.name)).toEqual([
+ 'tools.activate', 'tools.deactivate',
'mind.recipes.create', 'mind.recipes.list', 'mind.recipes.read', 'mind.recipes.update', 'mind.recipes.archive', 'mind.recipes.restore',
'mind.thinking-presets',
'mind.request-thinking-preset',
@@ -292,17 +305,19 @@ describe('cosToolRegistry', () => {
expect(catalog.tools.find((tool) => tool.name === 'brain.capture').granted).toBe(false);
const openai = formatCosToolCatalog(catalog, 'openai');
expect(openai.tools).toEqual([
+ expect.objectContaining({ type: 'function', function: expect.objectContaining({ name: 'tools_activate' }) }),
+ expect.objectContaining({ type: 'function', function: expect.objectContaining({ name: 'tools_deactivate' }) }),
expect.objectContaining({ type: 'function', function: expect.objectContaining({ name: 'user_actions_query' }) }),
expect.objectContaining({ type: 'function', function: expect.objectContaining({ name: 'eidoverse_chat' }) }),
expect.objectContaining({ type: 'function', function: expect.objectContaining({ name: 'eidoverse_status' }) }),
expect.objectContaining({ type: 'function', function: expect.objectContaining({ name: 'brain_search' }) }),
]);
const mcp = formatCosToolCatalog(catalog, 'mcp');
- expect(mcp.tools[0].annotations).toMatchObject({ readOnlyHint: true, openWorldHint: false });
+ expect(mcp.tools.find((tool) => tool.name === 'user_actions_query').annotations).toMatchObject({ readOnlyHint: true, openWorldHint: false });
});
- it('includes only granted tools in the Persistent Mind prompt', () => {
- const prompt = buildPersistentMindToolPrompt({ readPortos: true });
+ it('includes only granted tools in the Persistent Mind prompt when the all-schemas escape hatch is on', async () => {
+ const prompt = await buildPersistentMindToolPrompt({ readPortos: true, toolExposureAllSchemas: true });
// Catalog entries are JSON.stringified as `"name":"<tool>"`. A granted
// tool's input schema may list the same token as an enum (user-actions.query
// type `brain.capture`, #5596) — that must not be mistaken for advertising
@@ -575,4 +590,132 @@ describe('cosToolRegistry', () => {
result: { ok: false, state: 'failed', error: 'Queue unavailable' },
});
});
+
+ describe('progressive tool exposure (#7624)', () => {
+ it('hides a family behind a one-line discoverable index until tools.activate expands it', async () => {
+ const capabilities = { manageMind: true };
+ const before = await buildPersistentMindToolPrompt(capabilities, [], { turnId: 'turn-1', isUserTurn: true });
+ expect(before).not.toContain('"name":"mind.cleanup"');
+ expect(before).toContain('mind.cleanup');
+ expect(before).toContain('tools.activate');
+
+ const activated = await executeCosToolCall({
+ call: { requestId: 'activate-mind', name: 'tools.activate', arguments: { families: ['mind'] } },
+ authority: { scope: 'mind', capabilities },
+ });
+ expect(activated).toMatchObject({ state: 'completed', result: { activated: ['mind'], retentionTurns: 3 } });
+
+ const after = await buildPersistentMindToolPrompt(capabilities, [], { turnId: 'turn-1' });
+ expect(after).toContain('"name":"mind.cleanup"');
+ });
+
+ 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' });
+ expect(prompt).not.toContain('mind.cleanup');
+ });
+
+ it('drops a leased tool immediately once its capability grant is revoked between turns', async () => {
+ mocks.root.persistentMind.toolActivation = { leases: { mind: 3 }, lastAgedTurnId: 'turn-1' };
+ const stillGranted = await buildPersistentMindToolPrompt({ manageMind: true }, [], { turnId: 'turn-1' });
+ expect(stillGranted).toContain('"name":"mind.cleanup"');
+
+ const revoked = await buildPersistentMindToolPrompt({ manageMind: false }, [], { turnId: 'turn-2', isUserTurn: true });
+ expect(revoked).not.toContain('mind.cleanup');
+ });
+
+ it('does not age the lease across tool-round loops within one turn, only across a new user turn', async () => {
+ mocks.root.persistentMind.toolActivation = { leases: { mind: 2 }, lastAgedTurnId: null };
+ const capabilities = { manageMind: true };
+ // Round 0 of turn-1 ages it (2 -> 1); rounds 1 and 2 of the SAME turn
+ // must reuse that aged value rather than aging it again each call.
+ await buildPersistentMindToolPrompt(capabilities, [], { turnId: 'turn-1', isUserTurn: true });
+ expect(mocks.root.persistentMind.toolActivation.leases.mind).toBe(1);
+ await buildPersistentMindToolPrompt(capabilities, [], { turnId: 'turn-1' });
+ await buildPersistentMindToolPrompt(capabilities, [], { turnId: 'turn-1' });
+ expect(mocks.root.persistentMind.toolActivation.leases.mind).toBe(1);
+ // A genuinely new user turn ages it exactly once more.
+ await buildPersistentMindToolPrompt(capabilities, [], { turnId: 'turn-2', isUserTurn: true });
+ expect(mocks.root.persistentMind.toolActivation.leases.mind).toBe(0);
+ });
+
+ it('keeps a family exposed through every round-refresh of the turn it ages to its floor', async () => {
+ mocks.root.persistentMind.toolActivation = { leases: { mind: 1 }, lastAgedTurnId: null };
+ const capabilities = { manageMind: true };
+ const round0 = await buildPersistentMindToolPrompt(capabilities, [], { turnId: 'turn-1', isUserTurn: true });
+ expect(round0).toContain('"name":"mind.cleanup"');
+ // A later round of the SAME turn re-reads persisted state (no
+ // isUserTurn) and must still see the family the first round exposed.
+ const round1 = await buildPersistentMindToolPrompt(capabilities, [], { turnId: 'turn-1' });
+ expect(round1).toContain('"name":"mind.cleanup"');
+ // The turn after that is the one that actually drops it back to the
+ // discoverable index (still named, but without its full schema).
+ const nextTurn = await buildPersistentMindToolPrompt(capabilities, [], { turnId: 'turn-2', isUserTurn: true });
+ expect(nextTurn).not.toContain('"name":"mind.cleanup"');
+ expect(nextTurn).toContain('mind.cleanup');
+ });
+
+ it('tools.deactivate clears both this turn\'s selection and the persisted lease', async () => {
+ const capabilities = { manageMind: true };
+ await executeCosToolCall({
+ call: { requestId: 'activate-mind-2', name: 'tools.activate', arguments: { families: ['mind'] } },
+ authority: { scope: 'mind', capabilities },
+ });
+ expect(mocks.root.persistentMind.toolActivation.leases.mind).toBe(3);
+
+ const deactivated = await executeCosToolCall({
+ call: { requestId: 'deactivate-mind', name: 'tools.deactivate', arguments: { families: ['mind'] } },
+ authority: { scope: 'mind', capabilities },
+ });
+ expect(deactivated).toMatchObject({ state: 'completed', result: { deactivated: ['mind'] } });
+ expect(mocks.root.persistentMind.toolActivation.leases.mind).toBeUndefined();
+
+ const prompt = await buildPersistentMindToolPrompt(capabilities, [], { turnId: 'turn-3', isUserTurn: true });
+ expect(prompt).not.toContain('"name":"mind.cleanup"');
+ });
+
+ it('renews only the family a successful call actually used', async () => {
+ const capabilities = { manageMind: true };
+ mocks.root.persistentMind.toolActivation = { leases: { mind: 1 }, lastAgedTurnId: null };
+ mocks.protectMemory.mockResolvedValue({ ok: true, success: true, protection: 'core-identity' });
+ await executeCosToolCall({
+ call: { requestId: 'protect-renew', name: 'mind.protect-memory', arguments: { memoryId: 'memory-1', protection: 'core-identity' } },
+ authority: { scope: 'mind', capabilities },
+ });
+ // mind.protect-memory's family is 'mind' — using it renews 'mind' back
+ // to the full default retention window rather than leaving it decayed.
+ expect(mocks.root.persistentMind.toolActivation.leases.mind).toBe(DEFAULT_TOOL_ACTIVATION_RETENTION_TURNS);
+ });
+
+ it('reproduces the pre-#7624 catalog exactly under the all-schemas escape hatch', async () => {
+ const capabilities = { manageMind: true, toolExposureAllSchemas: true };
+ // Even with no lease at all, every granted tool's full schema is sent —
+ // family exposure never applies under the escape hatch.
+ const prompt = await buildPersistentMindToolPrompt(capabilities, []);
+ expect(prompt).toContain('"name":"mind.cleanup"');
+ expect(prompt).not.toContain('Discoverable-only families');
+ });
+
+ 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
+Semantic tool access is OFF. Return an empty toolCalls array. Never invent a tool name or claim that a PortOS action ran.`);
+ });
+
+ it('logs one aggregate trace line per turn with no tool name or user text', async () => {
+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ try {
+ await buildPersistentMindToolPrompt({ manageMind: true }, [], { turnId: 'turn-trace', isUserTurn: true, trace: true });
+ // A mid-turn refresh must not log a second line for the same turn.
+ await buildPersistentMindToolPrompt({ manageMind: true }, [], { turnId: 'turn-trace' });
+ const traceLines = logSpy.mock.calls.map(([line]) => line).filter((line) => line.includes('Mind tool exposure'));
+ expect(traceLines).toHaveLength(1);
+ expect(traceLines[0]).toMatch(/registered=\d+ eligible=\d+ core=\d+ activated=\d+ retained=\d+ excluded\(/);
+ expect(traceLines[0]).not.toContain('mind.cleanup');
+ expect(traceLines[0]).not.toContain('secret text');
+ } finally {
+ logSpy.mockRestore();
+ }
+ });
+ });
});
diff --git a/server/services/mindToolRecipeRuntime.test.js b/server/services/mindToolRecipeRuntime.test.js
index 8c68cfbe9a..60f56ec242 100644
--- a/server/services/mindToolRecipeRuntime.test.js
+++ b/server/services/mindToolRecipeRuntime.test.js
@@ -1,7 +1,14 @@
import { beforeEach, expect, it, vi } from 'vitest';
import { randomUUID } from 'node:crypto';
const mock = vi.hoisted(() => ({ capabilities: {}, agentContext: {}, recipes: [], dispatch: vi.fn(), runPrompt: vi.fn(), mutations: [] }));
-vi.mock('./cosState.js', () => ({ loadState: async () => ({ config: { persistentMindCapabilities: mock.capabilities } }) }));
+vi.mock('./cosState.js', () => ({
+ loadState: async () => ({
+ config: { persistentMindCapabilities: mock.capabilities },
+ persistentMind: { toolActivation: { leases: {}, lastAgedTurnId: null } },
+ }),
+ saveState: async () => {},
+ withStateLock: async (fn) => fn(),
+}));
vi.mock('./settings.js', () => ({ getSettings: async () => ({ agentContext: mock.agentContext }) }));
vi.mock('./voice/tools.js', () => ({
getToolSpecs: () => [{ function: { name: 'brain_search', description: 'Search records.', parameters: { type: 'object', properties: { query: { type: 'string' } }, required: ['query'] } } }],
diff --git a/server/services/persistentMindAdapter.js b/server/services/persistentMindAdapter.js
index 07f512cf84..2c2f7b49cd 100644
--- a/server/services/persistentMindAdapter.js
+++ b/server/services/persistentMindAdapter.js
@@ -414,7 +414,12 @@ export function createPersistentMindTurnAdapter() {
// already redacted, no grant required. Deeper lookbacks use the
// readPortos-gated user-actions.query tool.
const userActionsPrompt = await readPersistentMindUserActionsPrompt();
- const toolCapabilityPrompt = buildPersistentMindToolPrompt(taskAccess, await readPersistentMindRecipeCatalog(taskAccess));
+ // Only the very first build of the turn ages the lease and traces —
+ // every later rebuild (after a tool round) reuses the same turnId with
+ // isUserTurn omitted so a multi-round turn can't age its own tools out
+ // from under itself.
+ const isUserTurn = wake?.kind === 'message';
+ const toolCapabilityPrompt = await buildPersistentMindToolPrompt(taskAccess, await readPersistentMindRecipeCatalog(taskAccess), { turnId, isUserTurn, trace: true });
const callCapabilityPrompt = buildPersistentMindCallCapabilityPrompt({ enabled: taskAccess.callUser });
const screenshots = (Array.isArray(wake?.message?.images) ? wake.message.images : []).map((image) => {
const path = resolveScreenshot(image?.filename);
@@ -567,8 +572,12 @@ export function createPersistentMindTurnAdapter() {
});
completedToolResults.push(...toolResults);
const liveCapabilities = normalizePersistentMindCapabilities((await loadState()).config?.persistentMindCapabilities);
+ // 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 again
+ // or log a second trace line for the same turn.
basePrompt = buildPersistentMindTurnPrompt({ context, wake, taskCapabilityPrompt, issueCapabilityPrompt, visibilityPrompt, userActionsPrompt, callCapabilityPrompt,
- toolCapabilityPrompt: buildPersistentMindToolPrompt(liveCapabilities, await readPersistentMindRecipeCatalog(liveCapabilities)),
+ toolCapabilityPrompt: await buildPersistentMindToolPrompt(liveCapabilities, await readPersistentMindRecipeCatalog(liveCapabilities), { turnId }),
});
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.'}`;