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

feat: expose saved read recipes to Agent Tools (#7196)

[._.]/ Adam Eivye5975199f2a7
diff --git a/client/src/components/settings/ApiAccessTab.jsx b/client/src/components/settings/ApiAccessTab.jsx
index 23e3d4e0e5..0a00b240b3 100644
--- a/client/src/components/settings/ApiAccessTab.jsx
+++ b/client/src/components/settings/ApiAccessTab.jsx
@@ -11,7 +11,7 @@ const DEFAULT_AGENT_CONTEXT = {
enabled: false,
profile: 'metadata',
scopes: ['navigation', 'workspaces'],
- actions: { readPortos: false, writePortos: false, manageEidoverse: false, visitEidoversePeers: false },
+ actions: { readPortos: false, writePortos: false, callToolRecipes: false, manageEidoverse: false, visitEidoversePeers: false },
};
const AGENT_CONTEXT_SCOPES = [
{ id: 'navigation', label: 'Navigation', hint: 'PortOS page labels, aliases, and paths.' },
@@ -314,6 +314,14 @@ export function ApiAccessTab() {
label="Allow semantic PortOS updates"
hint="Typed Brain, journal, goals, health-log, and feed-state actions; no raw routes or shell."
/>
+ <Toggle
+ id="agent-context-action-recipes"
+ checked={agentContext.actions.callToolRecipes}
+ disabled={savingId !== null}
+ onChange={(value) => patchAgentContextAction('callToolRecipes', value)}
+ label="Allow saved read recipes"
+ hint="Invoke eligible Persistent Mind recipes with these Agent Tools grants. Recipe authoring stays Mind-only."
+ />
<Toggle
id="agent-context-action-eidoverse-travel"
checked={agentContext.actions.visitEidoversePeers}
diff --git a/client/src/components/settings/ApiAccessTab.test.jsx b/client/src/components/settings/ApiAccessTab.test.jsx
index c18d583cb1..48eb428ca7 100644
--- a/client/src/components/settings/ApiAccessTab.test.jsx
+++ b/client/src/components/settings/ApiAccessTab.test.jsx
@@ -169,6 +169,7 @@ describe('ApiAccessTab', () => {
expect(screen.getByLabelText('Disclosure profile').value).toBe('metadata');
expect(screen.getByLabelText('Allow semantic PortOS reads').checked).toBe(false);
expect(screen.getByLabelText('Allow semantic PortOS updates').checked).toBe(false);
+ expect(screen.getByLabelText('Allow saved read recipes').checked).toBe(false);
expect(screen.getByLabelText('Allow private Eidoverse world management').checked).toBe(false);
});
@@ -181,7 +182,7 @@ describe('ApiAccessTab', () => {
enabled: true,
profile: 'metadata',
scopes: ['navigation', 'workspaces'],
- actions: { readPortos: false, writePortos: false, manageEidoverse: false, visitEidoversePeers: false },
+ actions: { readPortos: false, writePortos: false, callToolRecipes: false, manageEidoverse: false, visitEidoversePeers: false },
},
}, { silent: true }));
});
@@ -192,7 +193,7 @@ describe('ApiAccessTab', () => {
enabled: true,
profile: 'metadata',
scopes: ['navigation'],
- actions: { readPortos: false, writePortos: false, manageEidoverse: false },
+ actions: { readPortos: false, writePortos: false, callToolRecipes: false, manageEidoverse: false },
},
});
await renderTab();
@@ -202,7 +203,7 @@ describe('ApiAccessTab', () => {
enabled: true,
profile: 'metadata',
scopes: ['navigation'],
- actions: { readPortos: true, writePortos: false, manageEidoverse: false, visitEidoversePeers: false },
+ actions: { readPortos: true, writePortos: false, callToolRecipes: false, manageEidoverse: false, visitEidoversePeers: false },
},
}, { silent: true }));
});
@@ -216,7 +217,21 @@ describe('ApiAccessTab', () => {
enabled: false,
profile: 'metadata',
scopes: ['navigation', 'workspaces'],
- actions: { readPortos: false, writePortos: false, manageEidoverse: true, visitEidoversePeers: false },
+ actions: { readPortos: false, writePortos: false, callToolRecipes: false, manageEidoverse: true, visitEidoversePeers: false },
+ },
+ }, { silent: true }));
+ });
+
+ it('persists the saved-recipe MCP grant independently', async () => {
+ getSettings.mockResolvedValue({});
+ await renderTab();
+ fireEvent.click(screen.getByLabelText('Allow saved read recipes'));
+ await waitFor(() => expect(updateSettings).toHaveBeenCalledWith({
+ agentContext: {
+ enabled: false,
+ profile: 'metadata',
+ scopes: ['navigation', 'workspaces'],
+ actions: { readPortos: false, writePortos: false, callToolRecipes: true, manageEidoverse: false, visitEidoversePeers: false },
},
}, { silent: true }));
});
diff --git a/client/src/pages/ApiExplorer.jsx b/client/src/pages/ApiExplorer.jsx
index 6b1207bda0..9d692d9a48 100644
--- a/client/src/pages/ApiExplorer.jsx
+++ b/client/src/pages/ApiExplorer.jsx
@@ -470,6 +470,16 @@ function AgentToolsView() {
<span className="rounded bg-port-bg px-2 py-0.5 text-xs text-gray-500">{tool.providerName}</span>
</div>
<p className="text-sm text-gray-400">{tool.description}</p>
+ {tool.recipe && (
+ <div className="rounded border border-port-border bg-port-bg p-2 text-xs text-gray-400">
+ <p>Saved recipe · Persistent Mind library · revision {tool.recipe.revision}</p>
+ <p className="mt-1">Read actions: {tool.recipe.underlyingTools?.join(', ') || 'unavailable'}</p>
+ {!tool.granted && tool.recipe.disabledReason && <p className="mt-1 text-port-warning">Mind: {tool.recipe.disabledReason}</p>}
+ {agentToolsByName.get(tool.name)?.granted === false && agentToolsByName.get(tool.name)?.recipe?.disabledReason && (
+ <p className="mt-1 text-port-warning">CoS MCP: {agentToolsByName.get(tool.name).recipe.disabledReason}</p>
+ )}
+ </div>
+ )}
<details className="text-xs text-gray-500">
<summary className="cursor-pointer">Input contract</summary>
<pre className="mt-2 overflow-x-auto rounded border border-port-border bg-port-bg p-3 text-[11px] text-gray-300">{JSON.stringify(tool.input_schema, null, 2)}</pre>
diff --git a/client/src/pages/ApiExplorer.test.jsx b/client/src/pages/ApiExplorer.test.jsx
index 64be8f1173..fa363ab48c 100644
--- a/client/src/pages/ApiExplorer.test.jsx
+++ b/client/src/pages/ApiExplorer.test.jsx
@@ -128,6 +128,22 @@ describe('ApiExplorer', () => {
expect(screen.getByText('CoS Agent MCP')).toBeTruthy();
});
+ it('shows saved recipe provenance, revision, read actions, and the agent disabled reason', async () => {
+ const recipe = {
+ name: 'recipe.project-check', providerName: 'recipe_project_check', description: 'Read a project check-in.', granted: true,
+ input_schema: { type: 'object', properties: {} }, policy: { sideEffect: 'read' },
+ recipe: { source: 'persistent-mind-library', revision: 3, underlyingTools: ['brain.search'] },
+ };
+ api.getCosToolCatalog.mockImplementation(({ scope }) => Promise.resolve(scope === 'agent'
+ ? { stats: { total: 1, granted: 0 }, tools: [{ ...recipe, granted: false, recipe: { ...recipe.recipe, disabledReason: 'Saved recipe access is disabled for CoS Agent MCP.' } }] }
+ : { stats: { total: 1, granted: 1 }, tools: [recipe] }));
+ renderPage('/api-reference/tools');
+ expect(await screen.findByText('recipe.project-check')).toBeTruthy();
+ expect(screen.getByText(/Persistent Mind library · revision 3/)).toBeTruthy();
+ expect(screen.getByText(/Read actions: brain.search/)).toBeTruthy();
+ expect(screen.getByText(/CoS MCP: Saved recipe access is disabled/)).toBeTruthy();
+ });
+
it('keeps the current REST surface when earlier reads succeed or fail late', async () => {
let finishInternal;
let failPublic;
diff --git a/client/src/pages/PersistentMindTools.jsx b/client/src/pages/PersistentMindTools.jsx
index 0af9c3c9fb..39217c7c62 100644
--- a/client/src/pages/PersistentMindTools.jsx
+++ b/client/src/pages/PersistentMindTools.jsx
@@ -57,7 +57,8 @@ export default function PersistentMindTools({ onCapabilitiesChange, onSavingChan
} : null,
semanticTools: (current.semanticTools || []).map((tool) => ({
...tool,
- granted: tool.policy.requiredCapabilities.every((capability) => capabilities[capability] === true),
+ granted: tool.recipe?.available !== false
+ && tool.policy.requiredCapabilities.every((capability) => capabilities[capability] === true),
})),
tools: (current.tools || []).map((tool) => ({
...tool,
@@ -86,6 +87,13 @@ export default function PersistentMindTools({ onCapabilitiesChange, onSavingChan
<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>
<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">
+ <p>Saved recipe · Persistent Mind library · revision {tool.recipe.revision}</p>
+ <p className="mt-1">Read actions: {tool.recipe.underlyingTools?.join(', ') || 'unavailable'}</p>
+ {!tool.granted && tool.recipe.disabledReason && <p className="mt-1 text-port-warning">{tool.recipe.disabledReason}</p>}
+ </div>
+ )}
<pre className="mt-2 max-h-48 overflow-auto whitespace-pre-wrap break-words text-port-text-muted">{JSON.stringify(tool.input_schema, null, 2)}</pre>
</details>
))}
diff --git a/docs/API_TOOL_CONTRACT.md b/docs/API_TOOL_CONTRACT.md
index 6b4c86da7f..0ee6e50cbb 100644
--- a/docs/API_TOOL_CONTRACT.md
+++ b/docs/API_TOOL_CONTRACT.md
@@ -1,7 +1,7 @@
# PortOS API and MCP Unified Tool Contract
Status: current implementation audit
-Date: 2026-08-28
+Date: 2026-09-12
This document is the implementation-facing bridge between PortOS's exhaustive
HTTP inventory, the governed semantic registry, Persistent Mind, and Agent
@@ -21,8 +21,8 @@ The current source contains:
- 22 provider-neutral semantic tools: one `cos.create-task` tool and 21
semantic adapters inherited from the voice registry.
- Five read-only context tools on the Agent Tools MCP transport. The MCP
- transport may additionally advertise the 21 semantic adapters when its
- separate read/write grants are enabled.
+ transport may additionally advertise the 21 semantic adapters and eligible
+ machine-local saved read recipes when their independent grants are enabled.
The route catalog is the exhaustive HTTP map. Both it and the Socket.IO
inventory are derived directly from their source declarations, so there is no
@@ -47,7 +47,7 @@ step; the server derives and caches both inventories from source.
| Method | Endpoint | Request and response behavior |
|---|---|---|
-| `GET` | `/api/cos/tools` | Query: `scope=all\|agent\|mind\|ui\|voice`, optional `intent` (trimmed, ≤500 characters), and `format=portos\|openai\|anthropic\|mcp`. Returns a catalog with an `ETag`; `If-None-Match` returns `304`. |
+| `GET` | `/api/cos/tools` | Query: `scope=all\|agent\|mind\|ui\|voice`, optional `intent` (trimmed, ≤500 characters), and `format=portos\|openai\|anthropic\|mcp`. Mind and agent scopes refresh saved recipe availability. Returns a catalog with an `ETag`; recipe revision/archive/restore changes alter it, and `If-None-Match` returns `304`. |
| `POST` | `/api/cos/tools/call` | Body is a strict `portos_tool_call`. Optional `Idempotency-Key` must equal `requestId`. Authority is derived as the HTTP `ui` principal from the server auth context. |
| `GET` | `/api/cos/tools/calls/:requestId` | Returns the retained normalized result for a process-local call, or `404 TOOL_CALL_NOT_FOUND`. Retention is in memory, so callers must not treat this as durable job history. |
@@ -65,14 +65,15 @@ input schema, checks scope and capabilities, then invokes a named adapter.
The transport accepts loopback socket addresses only and rejects a non-loopback
`Origin`. The normal PortOS authentication gate still applies when an instance
-password is configured. Context tools remain read-only. Semantic actions are a
-separate default-off grant and are executed through the same registry as the
-HTTP and Persistent Mind paths.
+password is configured. Context tools remain read-only. Semantic actions and
+saved recipe invocation are separate default-off grants and execute through
+the same registry as the HTTP and Persistent Mind paths.
### Persistent Mind authority inventory
`GET /api/cos/mind/tools` remains a separate authority view. It reports the
-Persistent Mind capability schema, boundaries, task catalog, and grant state;
+Persistent Mind capability schema, boundaries, task catalog, grant state, and
+current saved recipe descriptors;
it is not the generic semantic catalog. Persistent Mind execution uses the
same registry internally and has a five-call semantic/tool budget plus a
five-task-per-turn budget. No new authority is implied by the broader HTTP
@@ -155,6 +156,25 @@ task tool is not in the Agent MCP catalog. It is a Persistent Mind-only
capability and validates its app, provider, model, effort, mode, required
checks, tracker, readiness, and landing policy before queueing.
+### Saved read recipes
+
+Saved `recipe.*` tools come from the versioned Persistent Mind recipe library.
+They are discovered on each Mind/agent catalog read rather than added to the
+static adapter list. The native catalog exposes provenance, active revision,
+underlying canonical read-tool names, availability, and a bounded disabled
+reason. It never exposes definition literals, bindings, revision history, or
+execution results. Provider formats carry only the purpose, invocation schema,
+and a bounded local-recipe revision suffix.
+
+Agent MCP has its own `callToolRecipes` grant; it never inherits Persistent
+Mind's `manageToolRecipes` authority and cannot author, update, archive, or
+restore definitions. An agent recipe must validate entirely against the agent
+scope, requires every underlying semantic grant, refreshes settings before
+each child, and uses at most five child calls even outside a Mind turn. A
+Mind-only primitive therefore remains unavailable to an agent even when the
+recipe author could use it. Normal catalog reads and calls re-resolve the
+active revision, so revocation, archive, restore, and schema drift fail closed.
+
## MCP context tool definitions
These five tools are advertised from `server/lib/agentContextValidation.js`
@@ -224,6 +244,10 @@ Provider translations are mechanical projections of the same entry:
- MCP uses `name`, `description`, `inputSchema`, `outputSchema`, and standard
read-only/destructive/idempotent/open-world annotations.
+For a saved recipe, each provider description also carries a bounded
+machine-local origin and active-revision suffix because those formats have no
+native recipe metadata field.
+
## Authority and bridge
```text
@@ -239,7 +263,7 @@ REST/OpenAPI route inventory ──> discovery only; raw routes are never tools
| Caller | Server-derived authority | Default | Allowed mutation path |
|---|---|---|---|
| Persistent Mind | `scope: mind`, persisted capability grant | off | `cos.create-task`, semantic writes when separately granted |
-| Agent MCP | `scope: agent`, Agent Tools action grant | off | semantic writes when separately granted |
+| Agent MCP | `scope: agent`, Agent Tools action and saved-recipe grants | off | semantic writes when separately granted; saved recipes can orchestrate only granted agent-scope reads |
| HTTP registry | `scope: ui`, PortOS auth context | reads may be anonymous on a passwordless install | writes require an authenticated PortOS session |
| Voice adapter | existing voice pipeline context | existing voice policy | existing voice-side confirmation/pipeline controls |
@@ -270,10 +294,11 @@ exposable merely because they appear in the internal OpenAPI inventory.
confirm, or durable result endpoint. Those routes remain proposed design
backlog and must not be advertised by a client generated from this current
contract.
-4. **The five-call budget is a Persistent Mind budget.** It is enforced by the
- Persistent Mind adapter across its bounded turn loop. It is not a generic
- HTTP/MCP rate limit; callers using those transports must rely on grants,
- typed adapters, idempotency, and the deployment trust boundary.
+4. **Recipe calls are bounded on both agent surfaces.** Persistent Mind charges
+ every recipe child to its shared five-call turn budget. Agent MCP has no
+ turn loop, so each recipe invocation receives its own five-child budget.
+ This is not a generic HTTP/MCP rate limit; ordinary calls continue to rely
+ on grants, typed adapters, idempotency, and the deployment trust boundary.
5. **Disabled MCP manifest nuance.** The MCP execution route is blocked while
the feature is disabled, but a previously saved semantic action grant can
still appear in the readable manifest because advertised semantic tools are
diff --git a/docs/features/agent-context.md b/docs/features/agent-context.md
index fcbc1446c7..d50ee6e748 100644
--- a/docs/features/agent-context.md
+++ b/docs/features/agent-context.md
@@ -1,10 +1,10 @@
# Agent Tools (MCP)
-PortOS can expose bounded context and governed semantic tools to CoS agents running on the same machine. The surface uses MCP Streamable HTTP, is disabled by default, and never initiates an LLM request. Context scopes, semantic reads, and semantic writes are independently granted.
+PortOS can expose bounded context, governed semantic tools, and saved read recipes to CoS agents running on the same machine. The surface uses MCP Streamable HTTP, is disabled by default, and never initiates an LLM request. Context scopes, semantic reads, semantic writes, and recipe invocation are independently granted.
## Enable it
-Open **Settings → API Access → Agent Tools (MCP)** and enable **local MCP context**. The setting is stored machine-locally in the existing `settings.json` store; no context data is copied into a new store. Enabling the transport does not grant semantic reads or writes; both action grants default off.
+Open **Settings → API Access → Agent Tools (MCP)** and enable **local MCP context**. The setting is stored machine-locally in the existing `settings.json` store; no context data is copied into a new store. Enabling the transport does not grant semantic reads, writes, or saved recipes; every action grant defaults off.
The endpoint is:
@@ -64,9 +64,14 @@ The same MCP endpoint can advertise the curated `portos_tool` catalog used by Pe
|---|---|---|
| Semantic PortOS reads | Off | Bounded Brain, goals, journal, calendar, health-summary, feed, catalog, time/weather, process-status, and CoS-status adapters. |
| Semantic PortOS updates | Off | Typed Brain capture, journal append, goal progress/notes, health logging, and feed-state actions. |
+| Saved read recipes | Off | Invoke eligible recipes from the machine-local Persistent Mind library. Recipe authoring remains Mind-only, and every underlying semantic read grant is still required. |
Every semantic tool has a stable namespaced ID, a provider-safe MCP name, a closed input schema, side-effect/idempotency annotations, and a normalized result. MCP `tools/list` includes only actions granted in Settings. Shell/filesystem access, raw HTTP, arbitrary URLs, SQL, browser control, process control, paid generation, external messaging, credentials, and Persistent Mind task creation are not part of the CoS-agent MCP catalog.
+Saved recipes are re-read on every stateless `tools/list`, manifest, HTTP catalog, and invocation. A recipe is advertised only when its active revision contains one to five read steps that are all available in agent scope and the agent holds the recipe grant plus every underlying read grant. Each child executes with freshly loaded Agent Tools authority; revoking access stops later children and immediately denies a cached recipe name. Agent calls receive a local five-child budget when no Persistent Mind turn budget exists.
+
+Native catalog records expose only recipe provenance, active revision, underlying tool names, availability, and a bounded disabled reason. OpenAI, Anthropic, and MCP formats receive the recipe purpose, input schema, and a short local-recipe revision suffix. Definition literals, bindings, revision history, and execution results are never included. Updating, archiving, or restoring a recipe changes the HTTP catalog `ETag` so stateless clients can re-list without session notifications.
+
For retry-safe semantic writes, send an `Idempotency-Key` header with the MCP POST. PortOS binds it to the normalized tool call; a repeated key with different content fails rather than executing a different action.
## Context contract evaluation
diff --git a/server/lib/agentContextValidation.js b/server/lib/agentContextValidation.js
index 9316e378dc..a4ed597b30 100644
--- a/server/lib/agentContextValidation.js
+++ b/server/lib/agentContextValidation.js
@@ -1,10 +1,11 @@
import { z } from 'zod';
import {
createDefaultPortosSemanticToolGrants,
+ normalizePortosSemanticToolGrants,
portosSemanticToolGrantsSchema,
} from './cosToolContracts.js';
-export const AGENT_CONTEXT_SCHEMA_VERSION = 4;
+export const AGENT_CONTEXT_SCHEMA_VERSION = 5;
export const AGENT_CONTEXT_PROTOCOL_VERSION = '2025-11-25';
export const AGENT_CONTEXT_SUPPORTED_PROTOCOL_VERSIONS = Object.freeze([
'2025-03-26',
@@ -15,7 +16,18 @@ export const AGENT_CONTEXT_SUPPORTED_PROTOCOL_VERSIONS = Object.freeze([
export const AGENT_CONTEXT_SCOPES = Object.freeze(['navigation', 'workspaces', 'brain', 'identity']);
export const AGENT_CONTEXT_PROFILES = Object.freeze(['metadata', 'summary']);
export const AGENT_CONTEXT_DEFAULT_SCOPES = Object.freeze(['navigation', 'workspaces']);
-export const AGENT_CONTEXT_DEFAULT_ACTIONS = Object.freeze(createDefaultPortosSemanticToolGrants());
+export const agentContextActionGrantsSchema = portosSemanticToolGrantsSchema.extend({
+ callToolRecipes: z.boolean().optional(),
+}).strict();
+export const createDefaultAgentContextActionGrants = () => ({
+ ...createDefaultPortosSemanticToolGrants(),
+ callToolRecipes: false,
+});
+export const normalizeAgentContextActionGrants = (raw) => ({
+ ...normalizePortosSemanticToolGrants(raw),
+ callToolRecipes: raw?.callToolRecipes === true,
+});
+export const AGENT_CONTEXT_DEFAULT_ACTIONS = Object.freeze(createDefaultAgentContextActionGrants());
export const AGENT_CONTEXT_LIMITS = Object.freeze({
defaultResults: 10,
maxResults: 25,
@@ -37,7 +49,7 @@ export const agentContextSettingsSchema = z.object({
.max(AGENT_CONTEXT_SCOPES.length)
.refine(uniqueScopes, 'Scopes must be unique')
.optional(),
- actions: portosSemanticToolGrantsSchema.optional(),
+ actions: agentContextActionGrantsSchema.optional(),
}).strict();
const requestedScopesSchema = z.array(z.enum(AGENT_CONTEXT_SCOPES))
diff --git a/server/lib/agentContextValidation.test.js b/server/lib/agentContextValidation.test.js
index 440ebce3b9..64dfac91be 100644
--- a/server/lib/agentContextValidation.test.js
+++ b/server/lib/agentContextValidation.test.js
@@ -19,12 +19,12 @@ describe('agentContextValidation', () => {
enabled: true,
profile: 'metadata',
scopes: ['navigation', 'brain'],
- actions: { readPortos: true, writePortos: false, manageEidoverse: true },
+ actions: { readPortos: true, writePortos: false, callToolRecipes: true, manageEidoverse: true },
})).toEqual({
enabled: true,
profile: 'metadata',
scopes: ['navigation', 'brain'],
- actions: { readPortos: true, writePortos: false, manageEidoverse: true },
+ actions: { readPortos: true, writePortos: false, callToolRecipes: true, manageEidoverse: true },
});
expect(agentContextSettingsSchema.safeParse({ scopes: ['brain', 'brain'] }).success).toBe(false);
expect(agentContextSettingsSchema.safeParse({ scopes: ['privacy-vault'] }).success).toBe(false);
diff --git a/server/lib/mindToolRecipes.js b/server/lib/mindToolRecipes.js
index fb2fcb363a..48746af7aa 100644
--- a/server/lib/mindToolRecipes.js
+++ b/server/lib/mindToolRecipes.js
@@ -110,7 +110,7 @@ const walkOutput = (schema, segments, field, step, runtimeChecks) => {
};
/** Validate against the current catalog without reading any private tool result. */
-export function validateMindToolRecipe(candidate, catalog) {
+export function validateMindToolRecipe(candidate, catalog, { scope = 'mind' } = {}) {
const value = parseDefinition(candidate);
const runtimeChecks = [];
const names = new Set(catalog.flatMap((tool) => [tool.name, tool.providerName, ...(tool.aliases || [])]));
@@ -141,7 +141,7 @@ export function validateMindToolRecipe(candidate, catalog) {
const field = `steps.${index}`;
if (earlier.has(step.id)) fail(`${field}.id`, 'step ids must be unique', step.id);
const tool = catalog.find((entry) => entry.name === step.tool);
- if (!tool || tool.policy.sideEffect !== 'read' || !tool.policy.scopes.includes('mind') || (tool.name.startsWith('recipe.') || tool.name.startsWith('mind.recipes.'))) fail(`${field}.tool`, 'select a current canonical read tool in mind scope', step.id);
+ if (!tool || tool.policy.sideEffect !== 'read' || !tool.policy.scopes.includes(scope) || (tool.name.startsWith('recipe.') || tool.name.startsWith('mind.recipes.'))) fail(`${field}.tool`, `select a current canonical read tool in ${scope} scope`, step.id);
const contract = tool.input_schema;
for (const required of contract.required || []) if (!Object.hasOwn(step.arguments, required)) fail(`${field}.arguments.${required}`, 'required argument is missing', step.id);
for (const [name, binding] of Object.entries(step.arguments)) {
diff --git a/server/routes/cosMindRoutes.js b/server/routes/cosMindRoutes.js
index c29dbea391..381db6575e 100644
--- a/server/routes/cosMindRoutes.js
+++ b/server/routes/cosMindRoutes.js
@@ -271,9 +271,10 @@ router.get('/mind/tools', asyncHandler(async (_req, res) => {
granted: !allowed || allowed.has(app.id),
}));
}
- const { getCosToolCatalog } = await import('../services/cosToolRegistry.js');
+ const { getCosToolCatalog, readCosToolRecipeCatalog } = await import('../services/cosToolRegistry.js');
+ const recipes = await readCosToolRecipeCatalog({ scope: 'mind' });
res.json({
- semanticTools: getCosToolCatalog({ scope: 'mind', capabilities }).tools,
+ semanticTools: getCosToolCatalog({ scope: 'mind', capabilities, recipes }).tools,
schemaVersion: PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION,
capabilities,
boundaries: PERSISTENT_MIND_TOOL_BOUNDARIES,
diff --git a/server/routes/cosToolRoutes.js b/server/routes/cosToolRoutes.js
index 727c1a9198..1d0124993a 100644
--- a/server/routes/cosToolRoutes.js
+++ b/server/routes/cosToolRoutes.js
@@ -17,6 +17,7 @@ import {
formatCosToolCatalog,
getCosToolCall,
getCosToolCatalog,
+ readCosToolRecipeCatalog,
} from '../services/cosToolRegistry.js';
const router = Router();
@@ -26,12 +27,15 @@ const etagFor = (value) => `"${createHash('sha256').update(canonicalStringify(va
router.get('/tools', asyncHandler(async (req, res) => {
const query = validateRequest(cosToolCatalogQuerySchema, req.query);
const [state, settings] = await Promise.all([loadState(), getSettings()]);
+ const capabilities = query.scope === 'agent'
+ ? settings.agentContext?.actions
+ : state.config?.persistentMindCapabilities;
+ const recipes = await readCosToolRecipeCatalog({ scope: query.scope });
const catalog = getCosToolCatalog({
scope: query.scope,
intent: query.intent,
- capabilities: query.scope === 'agent'
- ? settings.agentContext?.actions
- : state.config?.persistentMindCapabilities,
+ capabilities,
+ recipes,
});
const response = formatCosToolCatalog(catalog, query.format);
const etag = etagFor(response);
diff --git a/server/routes/cosToolRoutes.test.js b/server/routes/cosToolRoutes.test.js
index bf33df528b..6abb7c74fa 100644
--- a/server/routes/cosToolRoutes.test.js
+++ b/server/routes/cosToolRoutes.test.js
@@ -8,6 +8,7 @@ const mocks = vi.hoisted(() => ({
format: vi.fn(),
execute: vi.fn(),
getCall: vi.fn(),
+ readRecipes: vi.fn(),
}));
vi.mock('../services/cosState.js', () => ({
@@ -21,6 +22,7 @@ vi.mock('../services/cosToolRegistry.js', () => ({
formatCosToolCatalog: (...args) => mocks.format(...args),
executeCosToolCall: (...args) => mocks.execute(...args),
getCosToolCall: (...args) => mocks.getCall(...args),
+ readCosToolRecipeCatalog: (...args) => mocks.readRecipes(...args),
}));
import routes from './cosToolRoutes.js';
@@ -41,6 +43,7 @@ beforeEach(() => {
vi.clearAllMocks();
mocks.catalog.mockReturnValue({ type: 'portos_tool_catalog', schemaVersion: 1, tools: [] });
mocks.format.mockImplementation((catalog) => catalog);
+ mocks.readRecipes.mockResolvedValue([]);
mocks.execute.mockResolvedValue({ type: 'portos_tool_result', requestId: 'call-1', state: 'completed' });
mocks.getCall.mockResolvedValue({ type: 'portos_tool_result', requestId: 'call-1', state: 'completed' });
});
@@ -65,6 +68,16 @@ describe('CoS tool routes', () => {
}));
});
+ it('changes the catalog ETag when a saved recipe revision changes', async () => {
+ mocks.readRecipes.mockResolvedValueOnce([{ name: 'recipe.check', recipe: { revision: 1 } }])
+ .mockResolvedValueOnce([{ name: 'recipe.check', recipe: { revision: 2 } }]);
+ mocks.catalog.mockImplementation(({ recipes }) => ({ type: 'portos_tool_catalog', schemaVersion: 1, tools: recipes }));
+ const first = await request(buildApp()).get('/api/cos/tools?scope=agent');
+ const second = await request(buildApp()).get('/api/cos/tools?scope=agent');
+ expect(first.headers.etag).not.toBe(second.headers.etag);
+ expect(mocks.readRecipes).toHaveBeenCalledWith({ scope: 'agent' });
+ });
+
it('derives UI authority from the server auth context and checks idempotency headers', async () => {
const body = { requestId: 'call-1', name: 'brain.search', arguments: { query: 'example' } };
const res = await request(buildApp({ authenticated: true }))
diff --git a/server/services/agentContextMcp.js b/server/services/agentContextMcp.js
index 01a67bdbc9..761ba6f544 100644
--- a/server/services/agentContextMcp.js
+++ b/server/services/agentContextMcp.js
@@ -13,12 +13,13 @@ import {
AGENT_CONTEXT_TOOL_REGISTRY,
advertiseAgentContextTools,
agentContextSettingsSchema,
+ normalizeAgentContextActionGrants,
} from '../lib/agentContextValidation.js';
-import { normalizePortosSemanticToolGrants } from '../lib/cosToolContracts.js';
import {
executeCosToolCall,
formatCosToolCatalog,
getCosToolCatalog,
+ readCosToolRecipeCatalog,
} from './cosToolRegistry.js';
export const AGENT_CONTEXT_EXCLUSIONS = Object.freeze([
@@ -63,7 +64,7 @@ export function resolveAgentContextConfig(settings = {}) {
enabled: parsed.data.enabled ?? false,
profile: parsed.data.profile ?? 'metadata',
scopes: parsed.data.scopes ?? [...AGENT_CONTEXT_DEFAULT_SCOPES],
- actions: normalizePortosSemanticToolGrants(parsed.data.actions),
+ actions: normalizeAgentContextActionGrants(parsed.data.actions),
invalid: false,
};
}
@@ -296,15 +297,16 @@ const successToolResult = (output) => ({
structuredContent: output,
});
-const semanticToolsForConfig = (config) => {
- const catalog = getCosToolCatalog({ scope: 'agent', capabilities: config.actions });
+const semanticToolsForConfig = async (config) => {
+ const recipes = await readCosToolRecipeCatalog({ scope: 'agent' });
+ const catalog = getCosToolCatalog({ scope: 'agent', capabilities: config.actions, recipes });
return {
...catalog,
tools: catalog.tools.filter((tool) => tool.granted === true),
};
};
-const semanticMcpToolsForConfig = (config) => formatCosToolCatalog(semanticToolsForConfig(config), 'mcp').tools;
+const semanticMcpToolsForConfig = async (config) => formatCosToolCatalog(await semanticToolsForConfig(config), 'mcp').tools;
export function createAgentContextContract({
readSettings = getSettings,
@@ -348,7 +350,7 @@ export function createAgentContextContract({
actions: config.actions,
tools: [
...advertiseAgentContextTools(config.scopes),
- ...semanticMcpToolsForConfig(config),
+ ...await semanticMcpToolsForConfig(config),
],
};
};
@@ -360,7 +362,7 @@ export function createAgentContextContract({
const tool = AGENT_CONTEXT_TOOL_REGISTRY.find((candidate) => candidate.name === name);
if (!tool || !TOOL_HANDLERS[name]) {
- const semanticTool = semanticToolsForConfig(config).tools.find((candidate) =>
+ const semanticTool = (await semanticToolsForConfig(config)).tools.find((candidate) =>
candidate.name === name || candidate.providerName === name || candidate.aliases.includes(name));
if (!semanticTool) return errorToolResult(`Unknown or ungranted tool: ${cap(name, 120)}`);
return executeCosToolCall({
diff --git a/server/services/agentContextMcp.test.js b/server/services/agentContextMcp.test.js
index 764d991b66..c4fce84473 100644
--- a/server/services/agentContextMcp.test.js
+++ b/server/services/agentContextMcp.test.js
@@ -7,6 +7,7 @@ const mocks = vi.hoisted(() => ({
previewLegacyExport: vi.fn(),
executeCosToolCall: vi.fn(),
getCosToolCatalog: vi.fn(),
+ readCosToolRecipeCatalog: vi.fn(),
}));
vi.mock('./settings.js', () => ({ getSettings: vi.fn(async () => mocks.settings) }));
@@ -28,6 +29,7 @@ vi.mock('../lib/navManifest.js', () => ({
vi.mock('./cosToolRegistry.js', () => ({
executeCosToolCall: mocks.executeCosToolCall,
getCosToolCatalog: mocks.getCosToolCatalog,
+ readCosToolRecipeCatalog: mocks.readCosToolRecipeCatalog,
formatCosToolCatalog: (catalog) => ({
tools: catalog.tools.map((tool) => ({
name: tool.providerName,
@@ -53,8 +55,9 @@ describe('agentContextMcp service', () => {
mocks.listContexts.mockResolvedValue([]);
mocks.getBrainProjections.mockResolvedValue([]);
mocks.previewLegacyExport.mockResolvedValue({ sections: {} });
- mocks.getCosToolCatalog.mockImplementation(({ capabilities }) => ({
- tools: capabilities?.readPortos ? [{
+ mocks.readCosToolRecipeCatalog.mockResolvedValue([]);
+ mocks.getCosToolCatalog.mockImplementation(({ capabilities, recipes = [] }) => ({
+ tools: [...(capabilities?.readPortos ? [{
name: 'brain.search',
providerName: 'brain_search',
aliases: ['brain_search'],
@@ -63,7 +66,11 @@ describe('agentContextMcp service', () => {
output_schema: { type: 'object' },
policy: { sideEffect: 'read' },
granted: true,
- }] : [],
+ }] : []), ...recipes.map((tool) => ({
+ ...tool,
+ granted: tool.recipe?.available !== false
+ && tool.policy.requiredCapabilities.every((capability) => capabilities?.[capability] === true),
+ }))],
}));
mocks.executeCosToolCall.mockResolvedValue({
type: 'portos_tool_result', requestId: 'agent-mcp:test', name: 'brain.search', state: 'completed', result: { ok: true },
@@ -77,8 +84,8 @@ describe('agentContextMcp service', () => {
expect(manifest.scopes).toEqual(['navigation', 'workspaces']);
expect(manifest.transport).toMatchObject({ loopbackOnly: true, stateful: false });
expect(manifest).toMatchObject({
- schemaVersion: 4,
- actions: { readPortos: false, writePortos: false, manageEidoverse: false },
+ schemaVersion: 5,
+ actions: { readPortos: false, writePortos: false, callToolRecipes: false, manageEidoverse: false },
limits: { maxApproxTokens: 5_000 },
});
expect(manifest.exclusions.join(' ')).toMatch(/Privacy Vault/);
@@ -107,11 +114,31 @@ describe('agentContextMcp service', () => {
call: expect.objectContaining({ requestId: 'agent-mcp:test', name: 'brain.search' }),
authority: {
scope: 'agent',
- capabilities: { readPortos: true, writePortos: false, manageEidoverse: true, visitEidoversePeers: false },
+ capabilities: { readPortos: true, writePortos: false, callToolRecipes: false, manageEidoverse: true, visitEidoversePeers: false },
},
}));
});
+ it('discovers saved recipes only with the independent grant and denies a cached name after revocation', async () => {
+ mocks.readCosToolRecipeCatalog.mockResolvedValue([{
+ name: 'recipe.project-check', providerName: 'recipe_project_check', aliases: [], description: 'Read a project check-in.',
+ input_schema: { type: 'object', properties: { project: { type: 'string' } }, required: ['project'], additionalProperties: false },
+ output_schema: { type: 'object' }, policy: { sideEffect: 'read', requiredCapabilities: ['callToolRecipes', 'readPortos'] },
+ recipe: { available: true, revision: 2, underlyingTools: ['brain.search'] },
+ }]);
+ mocks.settings = { agentContext: { enabled: true, scopes: ['navigation'], actions: { readPortos: true } } };
+ expect((await getAgentContextManifest()).tools.map((tool) => tool.name)).not.toContain('recipe_project_check');
+
+ mocks.settings.agentContext.actions.callToolRecipes = true;
+ expect((await getAgentContextManifest()).tools.map((tool) => tool.name)).toContain('recipe_project_check');
+ expect((await callAgentContextTool('recipe_project_check', { project: 'Example' })).isError).toBeUndefined();
+
+ mocks.settings.agentContext.actions.callToolRecipes = false;
+ const revoked = await callAgentContextTool('recipe_project_check', { project: 'Example' });
+ expect(revoked.isError).toBe(true);
+ expect(mocks.executeCosToolCall).toHaveBeenCalledTimes(1);
+ });
+
it('metadata profile can match private workspace text without returning it', async () => {
mocks.settings = { agentContext: { enabled: true, profile: 'metadata', scopes: ['workspaces'] } };
mocks.listContexts.mockResolvedValue([{
diff --git a/server/services/cosToolRegistry.js b/server/services/cosToolRegistry.js
index bd58744dfb..1891cec123 100644
--- a/server/services/cosToolRegistry.js
+++ b/server/services/cosToolRegistry.js
@@ -31,7 +31,16 @@ import { dispatchTool, getToolSpecs, getToolSpecsForIntent } from './voice/tools
import { executePersistentMindTaskRequests } from './persistentMindTaskCapability.js';
import { cleanupPersistentMind } from './persistentMindMaintenance.js';
-import { recipeManagementTools, resolveMindRecipeInvocation, readMindRecipeTools, currentMindAuthority, executeRecipeManagement, executeRecipe } from './mindToolRecipeRuntime.js';
+import {
+ currentAgentAuthority,
+ currentMindAuthority,
+ executeRecipe,
+ executeRecipeManagement,
+ readMindRecipeTools,
+ readRecipeToolsForScope,
+ recipeManagementTools,
+ resolveRecipeInvocation,
+} from './mindToolRecipeRuntime.js';
const MAX_CALL_RESULTS = 500;
const MAX_IDEMPOTENCY_TOMBSTONES = 10_000;
@@ -350,27 +359,41 @@ const normalizeToolCapabilities = (raw) => ({
manageMind: raw?.manageMind === true,
chooseThinkingPreset: raw?.chooseThinkingPreset === true,
adjustLocalContext: raw?.adjustLocalContext === true,
+ callToolRecipes: raw?.callToolRecipes === true,
});
-const publicTool = (tool, { scope, capabilities }) => ({
- type: tool.type,
- name: tool.name,
- version: tool.version,
- providerName: tool.providerName,
- aliases: tool.aliases,
- description: tool.description,
- input_schema: tool.input_schema,
- output_schema: tool.output_schema,
- policy: tool.policy,
- availableInScope: scope === 'all' || tool.policy.scopes.includes(scope),
- granted: !['agent', 'mind'].includes(scope)
- ? null
- : tool.policy.requiredCapabilities.every((capability) => capabilities[capability] === true),
-});
+const publicTool = (tool, { scope, capabilities }) => {
+ const missingCapabilities = tool.policy.requiredCapabilities
+ .filter((capability) => capabilities[capability] !== true);
+ const recipeAvailable = tool.recipe?.available !== false;
+ const recipeDisabledReason = tool.recipe?.disabledReason
+ || (missingCapabilities.includes('callToolRecipes') ? 'Saved recipe access is disabled for CoS Agent MCP.' : null)
+ || (missingCapabilities.includes('manageToolRecipes') ? 'Saved recipe access is disabled for Persistent Mind.' : null)
+ || (missingCapabilities.length ? `Requires ${missingCapabilities.join(', ')}.` : null);
+ return {
+ type: tool.type,
+ name: tool.name,
+ version: tool.version,
+ providerName: tool.providerName,
+ aliases: tool.aliases,
+ description: tool.description,
+ input_schema: tool.input_schema,
+ output_schema: tool.output_schema,
+ policy: tool.policy,
+ availableInScope: scope === 'all' || tool.policy.scopes.includes(scope),
+ granted: !['agent', 'mind'].includes(scope)
+ ? null
+ : recipeAvailable && missingCapabilities.length === 0,
+ ...(tool.recipe ? { recipe: {
+ ...tool.recipe,
+ ...(recipeDisabledReason ? { disabledReason: recipeDisabledReason } : {}),
+ } } : {}),
+ };
+};
export const getCosToolCatalog = ({ scope = 'all', intent, capabilities, recipes = [] } = {}) => {
const grants = normalizeToolCapabilities(capabilities);
- const tools = [...toolCatalog(intent), ...(scope === 'mind' ? recipes : [])]
+ const tools = [...toolCatalog(intent), ...(['mind', 'agent'].includes(scope) ? recipes : [])]
.filter((tool) => scope === 'all' || tool.policy.scopes.includes(scope))
.map((tool) => publicTool(tool, { scope, capabilities: grants }));
return {
@@ -390,15 +413,18 @@ export const getCosToolCatalog = ({ scope = 'all', intent, capabilities, recipes
export const formatCosToolCatalog = (catalog, format = 'portos') => {
if (format === 'portos') return catalog;
const tools = catalog.tools.filter((tool) => tool.granted !== false).map((tool) => {
+ const description = tool.recipe
+ ? `${tool.description} Saved local Persistent Mind recipe revision ${tool.recipe.revision}.`.slice(0, 500)
+ : tool.description;
if (format === 'openai') {
- return { type: 'function', function: { name: tool.providerName, description: tool.description, parameters: tool.input_schema } };
+ return { type: 'function', function: { name: tool.providerName, description, parameters: tool.input_schema } };
}
if (format === 'anthropic') {
- return { name: tool.providerName, description: tool.description, input_schema: tool.input_schema };
+ return { name: tool.providerName, description, input_schema: tool.input_schema };
}
return {
name: tool.providerName,
- description: tool.description,
+ description,
inputSchema: tool.input_schema,
outputSchema: tool.output_schema,
annotations: {
@@ -412,6 +438,11 @@ export const formatCosToolCatalog = (catalog, format = 'portos') => {
return { type: `${format}_tool_catalog`, schemaVersion: catalog.schemaVersion, scope: catalog.scope, tools };
};
+export const readCosToolRecipeCatalog = async ({ scope = 'mind' } = {}) => {
+ if (!['agent', 'mind'].includes(scope)) return [];
+ return readRecipeToolsForScope(scope, getCosToolCatalog({ scope }).tools);
+};
+
export const buildPersistentMindToolPrompt = (capabilities, recipes = []) => {
const catalog = getCosToolCatalog({ scope: 'mind', capabilities, recipes });
const tools = catalog.tools.filter((tool) => tool.granted).map((tool) => ({
@@ -613,11 +644,15 @@ export const executeCosToolCall = async ({ call, authority, context = {} }) => {
const parsedCall = cosToolCallSchema.parse(call);
let tool = resolveTool(parsedCall.name);
if (parsedCall.name.startsWith('recipe.')) {
- if (authority?.scope !== 'mind') throw new ServerError('Recipes require mind scope', { status: 403, code: 'TOOL_SCOPE_DENIED' });
- authority = await currentMindAuthority(authority);
- if (authority.capabilities.manageToolRecipes !== true) throw new ServerError('Recipe access is not granted', { status: 403, code: 'TOOL_CAPABILITY_DENIED' });
+ const scope = authority?.scope;
+ if (!['agent', 'mind'].includes(scope)) throw new ServerError('Recipes require mind or agent scope', { status: 403, code: 'TOOL_SCOPE_DENIED' });
+ authority = scope === 'agent'
+ ? await currentAgentAuthority(authority)
+ : await currentMindAuthority(authority);
+ const accessCapability = scope === 'agent' ? 'callToolRecipes' : 'manageToolRecipes';
+ if (authority.capabilities[accessCapability] !== true) throw new ServerError('Recipe access is not granted', { status: 403, code: 'TOOL_CAPABILITY_DENIED' });
const { getRecipeByName } = await import('./mindToolRecipes.js');
- tool = await resolveMindRecipeInvocation(await getRecipeByName(parsedCall.name), getCosToolCatalog({ scope: 'mind' }).tools);
+ tool = await resolveRecipeInvocation(await getRecipeByName(parsedCall.name), getCosToolCatalog({ scope }).tools, { scope });
} else if (tool?.adapter.kind === 'recipe-management' && authority?.scope === 'mind') {
authority = await currentMindAuthority(authority);
}
diff --git a/server/services/mindToolRecipeRuntime.js b/server/services/mindToolRecipeRuntime.js
index 7bdfeb0a17..ab0aa4a8e7 100644
--- a/server/services/mindToolRecipeRuntime.js
+++ b/server/services/mindToolRecipeRuntime.js
@@ -3,6 +3,11 @@ import { z } from 'zod';
import { COS_TOOL_SCHEMA_VERSION, COS_TOOL_CALL_LIMITS, providerToolName } from '../lib/cosToolContracts.js';
import { validateMindToolRecipe, resolveMindToolRecipeBinding } from '../lib/mindToolRecipes.js';
import { zodToOpenApiSchema } from '../lib/apiContractSchemas.js';
+import {
+ agentContextSettingsSchema,
+ createDefaultAgentContextActionGrants,
+ normalizeAgentContextActionGrants,
+} from '../lib/agentContextValidation.js';
import { ServerError } from '../lib/errorHandler.js';
import { sha256Text } from '../lib/fileUtils.js';
@@ -17,53 +22,93 @@ const managementSchemas = {
archive: z.object({ id, expectedRevision: revision }).strict(),
restore: z.object({ id, revision, expectedRevision: revision }).strict(),
};
-const descriptor = (name, description, input_schema, adapter, requiredCapabilities, sideEffect = 'read') => ({
+const descriptor = (name, description, input_schema, adapter, requiredCapabilities, sideEffect = 'read', {
+ scopes = ['mind'],
+ recipe,
+} = {}) => ({
type: 'portos_tool', name, version: COS_TOOL_SCHEMA_VERSION, providerName: providerToolName(name), aliases: [],
description, input_schema, output_schema: { type: 'object', additionalProperties: true },
- policy: { scopes: ['mind'], requiredCapabilities, sideEffect, idempotent: true, async: false, confirmation: 'capability-grant' },
+ policy: { scopes, requiredCapabilities, sideEffect, idempotent: true, async: false, confirmation: 'capability-grant' },
adapter,
+ ...(recipe ? { recipe } : {}),
});
export const recipeManagementTools = Object.entries(managementSchemas).map(([operation, schema]) => descriptor(
`mind.recipes.${operation}`, `${operation} saved read-tool recipe definitions. Read/list return paged definitions/history only. Create/update require schemaVersion:1, recipe.* name, purpose, closed parameters, 1-5 steps with {id,tool,arguments}, and outputs. Bindings are {literal:value}, {input:parameter}, or {step:id,path:[field]}.`,
zodToOpenApiSchema(schema), { kind: 'recipe-management', operation }, ['manageToolRecipes'], ['list', 'read'].includes(operation) ? 'read' : 'write',
));
-export const recipeTool = (recipe, primitives) => {
+const recipeAccessCapability = (scope) => scope === 'agent' ? 'callToolRecipes' : 'manageToolRecipes';
+const recipeMetadata = (recipe, definition, { scope, available = true, disabledReason } = {}) => ({
+ id: recipe.id,
+ source: 'persistent-mind-library',
+ revision: recipe.activeRevision,
+ scope,
+ available,
+ underlyingTools: [...new Set((definition?.steps || []).map((step) => step.tool))],
+ ...(disabledReason ? { disabledReason: String(disabledReason).slice(0, 500) } : {}),
+});
+
+export const recipeTool = (recipe, primitives, { scope = 'mind' } = {}) => {
if (recipe.archived) throw new ServerError('Recipe is archived. Restore a revision before calling it.', { code: 'RECIPE_ARCHIVED', status: 409 });
- const { definition } = validateMindToolRecipe(recipe.definition, primitives);
- const required = [...new Set(['manageToolRecipes', ...definition.steps.flatMap((step) => primitives.find((tool) => tool.name === step.tool).policy.requiredCapabilities)])];
+ const { definition } = validateMindToolRecipe(recipe.definition, primitives, { scope });
+ const required = [...new Set([recipeAccessCapability(scope), ...definition.steps.flatMap((step) => primitives.find((tool) => tool.name === step.tool).policy.requiredCapabilities)])];
return descriptor(definition.name, definition.purpose.slice(0, 280), definition.parameters,
- { kind: 'recipe', recipe: { id: recipe.id, activeRevision: recipe.activeRevision, definition } }, required);
+ { kind: 'recipe', recipe: { id: recipe.id, activeRevision: recipe.activeRevision, definition }, scope }, required, 'read', {
+ scopes: [scope], recipe: recipeMetadata(recipe, definition, { scope }),
+ });
};
// Even an incompatible revision gets a replay fingerprint and structured failure.
// A repair must never silently reinterpret the same invocation requestId.
-export const resolveMindRecipeInvocation = (recipe, primitives) => Promise.resolve()
- .then(() => recipeTool(recipe, primitives))
+export const resolveRecipeInvocation = (recipe, primitives, { scope = 'mind' } = {}) => Promise.resolve()
+ .then(() => recipeTool(recipe, primitives, { scope }))
.catch((error) => descriptor(recipe.name, 'Unavailable saved recipe', { type: 'object', additionalProperties: true },
- { kind: 'recipe', recipe, validationError: { message: error.message, step: error.context?.step || 'definition' } }, ['manageToolRecipes']));
+ { kind: 'recipe', recipe, scope, validationError: { message: error.message, step: error.context?.step || 'definition' } }, [recipeAccessCapability(scope)], 'read', {
+ scopes: [scope], recipe: recipeMetadata(recipe, recipe.definition, { scope, available: false, disabledReason: error.message }),
+ }));
-export async function readMindRecipeTools(capabilities, primitives) {
- if (capabilities?.manageToolRecipes !== true) return [];
+export const resolveMindRecipeInvocation = (recipe, primitives) => resolveRecipeInvocation(recipe, primitives, { scope: 'mind' });
+
+export async function readRecipeToolsForScope(scope, primitives) {
+ if (!['agent', 'mind'].includes(scope)) return [];
const { listRecipes } = await import('./mindToolRecipes.js');
const { recipes } = await listRecipes({ limit: 20 });
- const checked = await Promise.allSettled(recipes.map(async (recipe) => recipeTool(recipe, primitives)));
+ const checked = await Promise.all(recipes.map((recipe) => resolveRecipeInvocation(recipe, primitives, { scope })));
let chars = 0;
- return checked.flatMap((entry) => {
- if (entry.status !== 'fulfilled' || !entry.value.policy.requiredCapabilities.every((key) => capabilities[key] === true)) return [];
- const size = JSON.stringify(entry.value.input_schema).length + entry.value.description.length;
+ return checked.flatMap((tool) => {
+ const size = JSON.stringify(tool.input_schema).length + tool.description.length;
if (chars + size > 24000) return [];
chars += size;
- return [entry.value];
+ return [tool];
});
}
+export async function readMindRecipeTools(capabilities, primitives) {
+ if (capabilities?.manageToolRecipes !== true) return [];
+ const tools = await readRecipeToolsForScope('mind', primitives);
+ return tools.filter((tool) => tool.recipe?.available === true
+ && tool.policy.requiredCapabilities.every((key) => capabilities[key] === true));
+}
+
export async function currentMindAuthority(authority) {
const { loadState } = await import('./cosState.js');
const root = await loadState();
return { ...authority, capabilities: root.config?.persistentMindCapabilities || {} };
}
+export async function currentAgentAuthority(authority) {
+ const { getSettings } = await import('./settings.js');
+ const settings = await getSettings();
+ const parsed = agentContextSettingsSchema.safeParse(settings.agentContext ?? {});
+ const storedCapabilities = parsed.success && parsed.data.enabled === true
+ ? normalizeAgentContextActionGrants(parsed.data.actions)
+ : createDefaultAgentContextActionGrants();
+ const requestedCapabilities = normalizeAgentContextActionGrants(authority?.capabilities);
+ const capabilities = Object.fromEntries(Object.keys(storedCapabilities)
+ .map((key) => [key, storedCapabilities[key] === true && requestedCapabilities[key] === true]));
+ return { ...authority, scope: 'agent', capabilities };
+}
+
export async function executeRecipeManagement(tool, args, context) {
const recipes = await import('./mindToolRecipes.js');
const { operation } = tool.adapter;
@@ -81,6 +126,9 @@ export async function executeRecipeManagement(tool, args, context) {
export async function executeRecipe(tool, inputs, context, authority) {
const { executeCosToolCall, getCosToolCatalog } = await import('./cosToolRegistry.js');
const { id: recipeId, activeRevision: revision, definition } = tool.adapter.recipe;
+ const scope = tool.adapter.scope || authority?.scope || 'mind';
+ const accessCapability = recipeAccessCapability(scope);
+ const toolBudget = context.toolBudget || (scope === 'agent' ? { used: 0 } : null);
const results = {};
const outcomes = [];
let failingStep = tool.adapter.validationError?.step || null;
@@ -89,15 +137,17 @@ export async function executeRecipe(tool, inputs, context, authority) {
for (const step of definition.steps) {
failingStep = step.id;
if (context.signal?.aborted) throw new Error('Recipe interrupted by turn cancellation');
- const liveAuthority = await currentMindAuthority(authority);
+ const liveAuthority = scope === 'agent'
+ ? await currentAgentAuthority(authority)
+ : await currentMindAuthority(authority);
if (context.signal?.aborted) throw new Error('Recipe interrupted by turn cancellation');
- if (!liveAuthority.capabilities.manageToolRecipes) throw new Error('Recipe management grant was revoked; remaining steps were stopped');
- validateMindToolRecipe(definition, getCosToolCatalog({ scope: 'mind' }).tools);
- if (!context.toolBudget || context.toolBudget.used >= COS_TOOL_CALL_LIMITS.maxCallsPerTurn) throw new Error('Shared turn tool-call budget exhausted; remaining steps were stopped');
- context.toolBudget.used += 1;
+ if (!liveAuthority.capabilities[accessCapability]) throw new Error('Recipe access was revoked; remaining steps were stopped');
+ validateMindToolRecipe(definition, getCosToolCatalog({ scope }).tools, { scope });
+ if (!toolBudget || toolBudget.used >= COS_TOOL_CALL_LIMITS.maxCallsPerTurn) throw new Error('Shared turn tool-call budget exhausted; remaining steps were stopped');
+ toolBudget.used += 1;
const args = Object.fromEntries(Object.entries(step.arguments).map(([key, binding]) => [key, resolveMindToolRecipeBinding(binding, inputs, results, `steps.${step.id}.${key}`)]));
const requestId = `recipe-${sha256Text(`${context.requestId}:${recipeId}:${revision}:${step.id}`).slice(0, 48)}`;
- const outcome = await executeCosToolCall({ call: { requestId, name: step.tool, arguments: args }, authority: liveAuthority, context });
+ const outcome = await executeCosToolCall({ call: { requestId, name: step.tool, arguments: args }, authority: liveAuthority, context: { ...context, toolBudget } });
outcomes.push({ step: step.id, state: outcome.state });
await context.recordCapabilityEvent?.({ kind: 'result', id: `recipe-step:${requestId}`, data: {
displayText: `Recipe step ${step.id} ${outcome.state}`, recipeId, revision, step: step.id, success: outcome.state === 'completed',
diff --git a/server/services/mindToolRecipeRuntime.test.js b/server/services/mindToolRecipeRuntime.test.js
index e34596130d..a5255834d1 100644
--- a/server/services/mindToolRecipeRuntime.test.js
+++ b/server/services/mindToolRecipeRuntime.test.js
@@ -1,7 +1,8 @@
import { beforeEach, expect, it, vi } from 'vitest';
import { randomUUID } from 'node:crypto';
-const mock = vi.hoisted(() => ({ capabilities: {}, recipes: [], dispatch: vi.fn(), runPrompt: vi.fn(), mutations: [] }));
+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('./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'] } } }],
getToolSpecsForIntent: () => ({ specs: [] }),
@@ -43,7 +44,7 @@ vi.mock('./mindToolRecipes.js', async () => {
},
};
});
-import { executeCosToolCall, readPersistentMindRecipeCatalog, getCosToolCatalog, __testing } from './cosToolRegistry.js';
+import { executeCosToolCall, readCosToolRecipeCatalog, readPersistentMindRecipeCatalog, getCosToolCatalog, __testing } from './cosToolRegistry.js';
import { createPersistentMindTurnAdapter } from './persistentMindAdapter.js';
const definition = (steps = 2) => ({
schemaVersion: 1, name: 'recipe.project-check', purpose: 'Read a project check-in',
@@ -55,7 +56,9 @@ const authority = () => ({ scope: 'mind', capabilities: mock.capabilities });
const call = (name, args = {}, context = {}, requestId = randomUUID()) => executeCosToolCall({ call: { name, arguments: args, requestId }, authority: authority(), context });
const save = () => call('mind.recipes.create', { definition: definition() });
beforeEach(() => {
- vi.clearAllMocks(); mock.capabilities = { manageToolRecipes: true, readPortos: true }; mock.recipes = []; mock.mutations = [];
+ vi.clearAllMocks(); mock.capabilities = { manageToolRecipes: true, readPortos: true };
+ mock.agentContext = { enabled: true, scopes: ['navigation'], actions: { callToolRecipes: true, readPortos: true } };
+ mock.recipes = []; mock.mutations = [];
__testing.toolCalls.clear(); __testing.toolCallFingerprints.clear(); mock.dispatch.mockResolvedValue({ summary: 'Synthetic private result' });
});
it('creates, discovers and runs a two-read recipe on the next continuation, then reuses it on a later wake', async () => {
@@ -90,6 +93,65 @@ it('cannot multiply the adapter turn budget through a five-step wrapper or later
expect(mock.runPrompt.mock.calls[1][0].prompt).toContain('budget is exhausted');
expect(mock.runPrompt.mock.calls[1][0].prompt).toContain('"state":"partial"');
});
+it('exposes only agent-eligible recipes and enforces a fresh grant with a local five-child budget', async () => {
+ await call('mind.recipes.create', { definition: definition(5) });
+ const recipes = await readCosToolRecipeCatalog({ scope: 'agent' });
+ const agentCatalog = getCosToolCatalog({ scope: 'agent', capabilities: mock.agentContext.actions, recipes });
+ const advertised = agentCatalog.tools.find((tool) => tool.name === 'recipe.project-check');
+ expect(advertised).toMatchObject({
+ granted: true,
+ recipe: { source: 'persistent-mind-library', revision: 1, underlyingTools: ['brain.search'] },
+ });
+ expect(JSON.stringify(advertised)).not.toContain('arguments');
+ const result = await executeCosToolCall({
+ call: { name: 'recipe.project-check', arguments: { project: 'Example' }, requestId: randomUUID() },
+ authority: { scope: 'agent', capabilities: mock.agentContext.actions },
+ });
+ expect(result).toMatchObject({ state: 'completed', result: { revision: 1, outcomes: expect.any(Array) } });
+ expect(result.result.outcomes).toHaveLength(5);
+ expect(mock.dispatch).toHaveBeenCalledTimes(5);
+
+ mock.agentContext.actions.callToolRecipes = false;
+ await expect(executeCosToolCall({
+ call: { name: 'recipe.project-check', arguments: { project: 'Example' }, requestId: randomUUID() },
+ authority: { scope: 'agent', capabilities: { callToolRecipes: true, readPortos: true } },
+ })).rejects.toMatchObject({ code: 'TOOL_CAPABILITY_DENIED' });
+});
+it('marks a recipe using a Mind-only primitive unavailable to agents', async () => {
+ mock.capabilities.chooseThinkingPreset = true;
+ const mindOnly = definition(1);
+ mindOnly.steps[0].tool = 'mind.thinking-presets';
+ mindOnly.steps[0].arguments = {};
+ mindOnly.outputs = { presets: { step: 'read0', path: [] } };
+ await call('mind.recipes.create', { definition: mindOnly });
+ const recipes = await readCosToolRecipeCatalog({ scope: 'agent' });
+ const catalog = getCosToolCatalog({ scope: 'agent', capabilities: mock.agentContext.actions, recipes });
+ expect(catalog.tools.find((tool) => tool.name === mindOnly.name)).toMatchObject({
+ granted: false,
+ recipe: { available: false, disabledReason: expect.stringMatching(/agent scope/) },
+ });
+});
+it('re-reads agent authority before every child and stops a recipe after revocation', async () => {
+ await save();
+ mock.dispatch.mockImplementationOnce(async () => {
+ mock.agentContext.actions.callToolRecipes = false;
+ return { summary: 'Private' };
+ });
+ const result = await executeCosToolCall({
+ call: { name: 'recipe.project-check', arguments: { project: 'Example' }, requestId: randomUUID() },
+ authority: { scope: 'agent', capabilities: { callToolRecipes: true, readPortos: true } },
+ });
+ expect(result).toMatchObject({ state: 'failed', result: { state: 'partial', failingStep: 'read1' } });
+ expect(mock.dispatch).toHaveBeenCalledTimes(1);
+});
+it('intersects fresh Agent Tools grants with the original caller authority', async () => {
+ await save();
+ await expect(executeCosToolCall({
+ call: { name: 'recipe.project-check', arguments: { project: 'Example' }, requestId: randomUUID() },
+ authority: { scope: 'agent', capabilities: { callToolRecipes: true, readPortos: false } },
+ })).rejects.toMatchObject({ code: 'TOOL_CAPABILITY_DENIED' });
+ expect(mock.dispatch).not.toHaveBeenCalled();
+});
it('stops after revocation, removes discovery, and keeps already completed reads marked partial', async () => {
await save();
mock.dispatch.mockImplementationOnce(async () => { mock.capabilities.readPortos = false; return { summary: 'Private' }; });