Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
fix(agent-providers): bring running sessions in step with granted services (#857)
Louis Amaudruz6793cc15c53c
diff --git a/console/packages/agent-providers/src/host/agent-host.test.ts b/console/packages/agent-providers/src/host/agent-host.test.tsindex 12a293b59..2b6c4d2ff 100644--- a/console/packages/agent-providers/src/host/agent-host.test.ts+++ b/console/packages/agent-providers/src/host/agent-host.test.ts@@ -21,6 +21,7 @@ import {import type { Handoff } from './handoff';import { ensureSharedProcess, type Supervision } from './launch';import { type SessionRequest, SessionLinks } from './session-channel';+import type * as sessionServices from './session-services';import { sharedConfigSchema } from './shared-config';import { clearTakenOver, recordTakenOver } from './taken-over';import { SESSION_STARTING_MESSAGE, WatcherControl } from './watcher-tools';@@ -36,6 +37,13 @@ vi.mock('./launch', () => ({liveSupervisor: (root: string) => Promise.resolve(supervisors.get(root) ?? null),ensureSharedProcess: vi.fn(),}));+/** The shape of the agent's grants as the watcher reads them; null reads as unknown. */+const grantsNow = vi.hoisted(() => ({ shape: null as string | null }));+vi.mock('./session-services', async (importOriginal) => ({+ ...(await importOriginal<typeof sessionServices>()),+ GRANTS_CHECK_MS: 20,+ currentServicesShape: async () => grantsNow.shape,+}));const streams = vi.hoisted(() => [] as SwitchEventStreamDeps[]);const declarations = vi.hoisted(() => [] as boolean[]);/** Every placements map the watcher stated to Switch, in order. */@@ -1638,6 +1646,162 @@ it('brings live sessions in step with a rewritten definition, each once its turnexpect(restarted).toHaveLength(2);});+/** Records, as a session's host does as it starts, the shape of the grants it started with. */+async function startedWith(sessionRoot: string, shape: string): Promise<void> {+ await writeFile(join(sessionRoot, 'services.json'), JSON.stringify({ shape }));+}++it('restarts live sessions once a service is granted to their agent, each once its turn has ended', async () => {+ const root = await mkdtemp(join(tmpdir(), 'shared-watch-regranted-'));+ roots.push(root);+ paths.root = root;+ const config = await spawning(root);+ const working = await existing(root, config);+ const idle = await existing(root, config);+ const unrecorded = await existing(root, config);+ await assignTo(root, config, 1, 'room', working.sessionId);+ await assignTo(root, config, 2, 'elsewhere', idle.sessionId);+ await assignTo(root, config, 3, 'third', unrecorded.sessionId);+ await startedWith(working.sessionRoot, '[]');+ await startedWith(idle.sessionRoot, '[]');+ grantsNow.shape = '[]';+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ const hosts = sessionHosts();+ for (const session of [working, idle, unrecorded]) await hosts.start(session.sessionRoot);+ hosts.busy(working.sessionRoot, true);+ hosts.busy(idle.sessionRoot, false);+ hosts.busy(unrecorded.sessionRoot, false);+ const restarted: { root: string; resuming: boolean; restart: boolean }[] = [];+ vi.mocked(ensureSharedProcess).mockImplementation(+ async ({ root: sessionRoot, resuming, restart }) => {+ restarted.push({ root: sessionRoot, resuming, restart });+ // The new host records the grants it started with, as `shared-daemon` does.+ await startedWith(sessionRoot, grantsNow.shape!);+ return { created: false };+ }+ );++ const abort = new AbortController();+ const run = runAgentHost(+ root,+ config,+ abort.signal,+ hosts.supervision,+ new WatcherControl(),+ openSwitchStream+ );+ try {+ await eventually(() => streams.length === 1);+ // Nothing granted or taken away: every check leaves the sessions alone.+ await new Promise((resolve) => setTimeout(resolve, 100));+ expect(restarted).toEqual([]);+ grantsNow.shape = '[{"service":"google-workspace"}]';+ await eventually(() => restarted.length === 1);+ // The session in the middle of a turn is left to finish it, and one whose+ // host recorded nothing is not restarted on a guess.+ expect(restarted).toEqual([{ root: idle.sessionRoot, resuming: true, restart: true }]);+ hosts.busy(working.sessionRoot, false);+ await eventually(() => restarted.length === 2);+ expect(restarted[1]).toEqual({ root: working.sessionRoot, resuming: true, restart: true });+ await new Promise((resolve) => setTimeout(resolve, 100));+ } finally {+ abort.abort();+ await run;+ grantsNow.shape = null;+ }+ expect(restarted).toHaveLength(2);+});++it('restarts a session for its agent’s granted services once, even if it comes back without them', async () => {+ const root = await mkdtemp(join(tmpdir(), 'shared-watch-regranted-once-'));+ roots.push(root);+ paths.root = root;+ const config = await spawning(root);+ const session = await existing(root, config);+ await assignTo(root, config, 1, 'room', session.sessionId);+ await startedWith(session.sessionRoot, '[]');+ grantsNow.shape = '[{"service":"google-workspace"}]';+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ const hosts = sessionHosts();+ await hosts.start(session.sessionRoot);+ hosts.busy(session.sessionRoot, false);+ // The new host fails to read the grants itself, so it records the old ones.+ vi.mocked(ensureSharedProcess).mockImplementation(async () => ({ created: false }));++ const abort = new AbortController();+ const run = runAgentHost(+ root,+ config,+ abort.signal,+ hosts.supervision,+ new WatcherControl(),+ openSwitchStream+ );+ try {+ await eventually(() => vi.mocked(ensureSharedProcess).mock.calls.length === 1);+ await new Promise((resolve) => setTimeout(resolve, 150));+ } finally {+ abort.abort();+ await run;+ grantsNow.shape = null;+ }+ expect(ensureSharedProcess).toHaveBeenCalledTimes(1);+});++it('restarts a session’s host before handing it a reset, when its agent’s services changed', async () => {+ const root = await mkdtemp(join(tmpdir(), 'shared-watch-reset-regranted-'));+ roots.push(root);+ paths.root = root;+ const config = await spawning(root);+ const granted = await existing(root, config);+ const unchanged = await existing(root, config);+ await startedWith(granted.sessionRoot, '[]');+ await startedWith(unchanged.sessionRoot, '[{"service":"google-workspace"}]');+ grantsNow.shape = '[{"service":"google-workspace"}]';+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ const hosts = sessionHosts();+ await hosts.start(granted.sessionRoot);+ await hosts.start(unchanged.sessionRoot);+ const order: string[] = [];+ vi.mocked(ensureSharedProcess).mockImplementation(async ({ root: sessionRoot, restart }) => {+ order.push(`restart ${sessionRoot} ${restart}`);+ await startedWith(sessionRoot, grantsNow.shape!);+ return { created: false };+ });+ const reset = (sessionId: string) => ({+ sessionId,+ commandId: `reset-${sessionId}`,+ body: { type: 'session.reset' },+ });++ const abort = new AbortController();+ const run = runAgentHost(+ root,+ config,+ abort.signal,+ hosts.supervision,+ new WatcherControl(),+ openSwitchStream+ );+ try {+ await eventually(() => streams.length === 1);+ await streams[0]!.onSessionCommand!(reset(granted.sessionId));+ order.push(...hosts.to(granted.sessionRoot).map((request) => request.type));+ await streams[0]!.onSessionCommand!(reset(unchanged.sessionId));+ } finally {+ abort.abort();+ await run;+ grantsNow.shape = null;+ }+ expect(order.slice(0, 2)).toEqual([`restart ${granted.sessionRoot} true`, 'command']);+ expect(hosts.to(unchanged.sessionRoot)).toEqual([+ { type: 'command', command: reset(unchanged.sessionId), requesterName: null },+ ]);+ expect(vi.mocked(ensureSharedProcess).mock.calls.map(([input]) => input.root)).toEqual([+ granted.sessionRoot,+ ]);+});+it('gives a room a new session once the one serving it has been stopped', async () => {const root = await mkdtemp(join(tmpdir(), 'shared-watch-stopped-owner-'));roots.push(root);diff --git a/console/packages/agent-providers/src/host/agent-host.ts b/console/packages/agent-providers/src/host/agent-host.tsindex d92bc923a..99ba3551d 100644--- a/console/packages/agent-providers/src/host/agent-host.ts+++ b/console/packages/agent-providers/src/host/agent-host.ts@@ -27,6 +27,12 @@ import {type SessionRequest,SessionUnavailableError,} from './session-channel';+import {+ currentServicesShape,+ GRANTS_CHECK_MS,+ recordedServicesShape,+ servicesChanged,+} from './session-services';import { readSharedCredentials, sharedConfigSchema, type SharedHostConfig } from './shared-config';import { readTakenOver, recordTakenOver } from './taken-over';import { awaitWatchChange, onConfigReplaced, readWatchFlags } from './watch-flags';@@ -113,6 +119,11 @@ function isReleased(record: WatchRecord): record is z.infer<typeof releasedSchemreturn 'released' in record;}+/** Whether a relayed room control is a reset (`!reset`). */+function isReset(command: Record<string, unknown>): boolean {+ return z.object({ type: z.literal('session.reset') }).safeParse(command.body).success;+}+function isAssignment(record: WatchRecord): record is Assignment {return 'config' in record;}@@ -651,6 +662,7 @@ export async function runAgentHost(let fault: Error | null = null;let pending: Promise<void> = Promise.resolve();let retry: NodeJS.Timeout | null = null;+ let grantsCheck: NodeJS.Timeout | null = null;const unbind: (() => void)[] = [];const fail = (error: Error) => {fault = error;@@ -814,6 +826,65 @@ export async function runAgentHost(/** The watcher's template as it stands now, which admitting a room reads too. */const currentTemplate = async (): Promise<SharedHostConfig> =>sharedConfigSchema.parse(JSON.parse(await readFile(join(root, 'config.json'), 'utf8')));+ /**+ * The shape of the agent's grants as last read (`servicesShape`), which+ * every session's host is compared against: null until first read.+ */+ let servicesNow: string | null = null;+ const startedServices = async (sessionRoot: string): Promise<string | null | undefined> => {+ try {+ return await recordedServicesShape(sessionRoot);+ } catch (error) {+ console.warn(+ `Could not read which services the session at ${sessionRoot} started with, so it is not restarted for a change to them: ${error instanceof Error ? error.message : String(error)}`+ );+ return undefined;+ }+ };+ /**+ * The grants each session's host was last restarted for. A host that comes+ * back recording other grants still (its own read of them failing, say) is+ * not restarted for the same grants again: once is a fix, more is a loop.+ */+ const restartedFor = new Map<string, string>();+ const servicesStale = async (sessionRoot: string, current: string | null) => {+ if (current === null || restartedFor.get(sessionRoot) === current) return false;+ return servicesChanged(await startedServices(sessionRoot), current);+ };+ /**+ * Restarts a session's host, on its own conversation, when it started+ * under other granted services than the agent has now. True when it did.+ */+ const restartForServices = async (sessionId: string): Promise<boolean> => {+ const sessionRoot = sharedSessionRoot(sessionId);+ if (!links.ready(sessionRoot)) return false;+ const saved = await sessionConfigAt(sessionRoot);+ const current = await currentTemplate();+ if (+ !saved ||+ saved.session.agentId !== agentId ||+ saved.start.provider !== current.start.provider ||+ saved.start.input.cwd !== current.start.input.cwd+ )+ return false;+ const shape = await currentServicesShape(current);+ if (shape !== null) servicesNow = shape;+ if (!(await servicesStale(sessionRoot, shape))) return false;+ restartedFor.set(sessionRoot, shape!);+ console.warn(+ `Session ${sessionId} is being reset with other services granted to its agent than it started with; restarting its host first so the new conversation has them.`+ );+ await ensureSharedProcess({+ root: sessionRoot,+ config: reachableBy(withDefinitionOf(saved, current), connectionId),+ resuming: true,+ watcher: false,+ restart: true,+ supervision,+ startSource: null,+ });+ return true;+ };const launch = async (config: SharedHostConfig) => {// Both flags are re-read here rather than taken from whoever asked for the// launch. Everything that reaches this point was admitted earlier and may@@ -857,11 +928,16 @@ export async function runAgentHost(* Ask the host of one of this agent's sessions, if it runs here. False* when it is not this agent's, or nothing is running it.*/- const askSession = async (sessionId: string, request: SessionRequest, what: string) => {+ const askSession = async (+ sessionId: string,+ request: SessionRequest,+ what: string,+ waitMs: number+ ) => {const sessionRoot = sharedSessionRoot(sessionId);if (!(await sessionConfig(sessionId))) return false;try {- await links.request(sessionRoot, request, 0);+ await links.request(sessionRoot, request, waitMs);return true;} catch (error) {console.warn(`Could not pass ${what} to session ${sessionId}: ${String(error)}`);@@ -1132,7 +1208,7 @@ export async function runAgentHost(});},onApprovalOutcome: async (outcome) => {- await askSession(outcome.session_id, { type: 'approvals' }, 'an approval answer');+ await askSession(outcome.session_id, { type: 'approvals' }, 'an approval answer', 0);},// A room control (!reset, !interrupt) typed in one of the agent's rooms,// which only Switch sees. Handed to the session's host like any other.@@ -1147,6 +1223,16 @@ export async function runAgentHost(return;}const command = { ...rest, sessionId };+ // A reset runs in the host the session has, which keeps the tools it+ // started with: one granted or taken away since needs a new host first.+ const restarted =+ isReset(command) &&+ (await restartForServices(sessionId).catch((error: unknown) => {+ console.warn(+ `Could not restart session ${sessionId} for its agent's granted services before its reset, so it is reset with the tools it has: ${error instanceof Error ? error.message : String(error)}`+ );+ return false;+ }));const taken = await askSession(sessionId,{@@ -1154,7 +1240,8 @@ export async function runAgentHost(command,requesterName: typeof requesterName === 'string' ? requesterName : null,},- `command ${command.commandId}`+ `command ${command.commandId}`,+ restarted ? HOST_START_MS : 0);if (!taken)console.warn(@@ -1303,6 +1390,11 @@ export async function runAgentHost(* `redefinitionDue` until its host says it is done. One saved under another* provider or directory belongs to an earlier identity of the agent and is* left alone.+ *+ * A session whose host started under other granted services than the+ * agent has now (`servicesNow`, read every `GRANTS_CHECK_MS`) is restarted+ * the same way: its tools are built as its host starts, so a service+ * granted or taken away reaches it only through a new host.*/const redefinitionDue = new Set<string>();let redefining = false;@@ -1320,21 +1412,23 @@ export async function runAgentHost(!saved ||saved.session.agentId !== agentId ||saved.start.provider !== current.start.provider ||- saved.start.input.cwd !== current.start.input.cwd ||- !definitionChanged(saved, current)+ saved.start.input.cwd !== current.start.input.cwd)continue;+ if (!definitionChanged(saved, current) && !(await servicesStale(sessionRoot, servicesNow)))+ continue;if (links.busy(sessionRoot)?.busy !== false) redefinitionDue.add(sessionRoot);else idle.push({ root: sessionRoot, saved });}if (idle.length === 0 && redefinitionDue.size === 0) return;console.warn(- `Agent ${agentId}'s definition changed: restarting ${idle.length} idle session(s) under it now; ${redefinitionDue.size} more once their turn ends.`+ `Agent ${agentId}'s definition or granted services changed: restarting ${idle.length} idle session(s) under them now; ${redefinitionDue.size} more once their turn ends.`);for (const { root: sessionRoot, saved } of idle) {console.warn(- `Session ${saved.session.sessionId} runs under an earlier definition of its agent (model, instructions, advanced configuration or approval mode); restarting it on the same conversation under the current one.`+ `Session ${saved.session.sessionId} runs under an earlier definition of its agent (model, instructions, advanced configuration or approval mode) or its granted services; restarting it on the same conversation under the current ones.`);+ if (servicesNow !== null) restartedFor.set(sessionRoot, servicesNow);try {await ensureSharedProcess({root: sessionRoot,@@ -1378,6 +1472,33 @@ export async function runAgentHost(redefinitionDue.delete(exitedRoot);}));+ /** Whether any session of this agent's has a host running here. */+ const anyLive = (): boolean => {+ const ours = new Set(+ assignments.sessions().map((config) => sharedSessionRoot(config.session.sessionId))+ );+ return links.live().some((sessionRoot) => ours.has(sessionRoot));+ };+ let checkingGrants = false;+ grantsCheck = setInterval(() => {+ if (checkingGrants || !anyLive()) return;+ checkingGrants = true;+ void (async () => {+ const shape = await currentServicesShape(await currentTemplate());+ if (shape === null) return;+ servicesNow = shape;+ redefine();+ })()+ .catch((error: unknown) => {+ console.warn(+ `Could not check agent ${agentId}'s granted services: ${error instanceof Error ? error.message : String(error)}`+ );+ })+ .finally(() => {+ checkingGrants = false;+ });+ }, GRANTS_CHECK_MS);+ grantsCheck.unref();while (!stop.signal.aborted) {const changed = await awaitWatchChange(root, flags, stop.signal);if (!changed) break;@@ -1404,6 +1525,7 @@ export async function runAgentHost(for (const release of unbind) release();stop.abort();if (retry) clearInterval(retry);+ if (grantsCheck) clearInterval(grantsCheck);signal.removeEventListener('abort', abort);await pending.catch(() => {});const failure = fault ?? thrown;diff --git a/console/packages/agent-providers/src/host/service-access.ts b/console/packages/agent-providers/src/host/service-access.tsindex f1e5407cf..2b99ce9c6 100644--- a/console/packages/agent-providers/src/host/service-access.ts+++ b/console/packages/agent-providers/src/host/service-access.ts@@ -9,8 +9,10 @@ import { validServiceToken } from './service-github';* agent's own Switch endpoint: its own key, or the agents controller's relay,* which forwards `/agents/{id}/...` as the controller. A grant gives the* session its service's skill and, through the agent host, the service's- * tokens. A change of skills reaches a session when it next starts; a change- * of access reaches its tokens within half a minute (`AgentServiceTokens`).+ * tokens. A change of access reaches its tokens within half a minute+ * (`AgentServiceTokens`); a service granted or taken away needs new tools, so+ * the agent's watcher restarts the session's host on its own conversation+ * once it is idle (`session-services.ts`).*/const SLUG = /^[a-z0-9][a-z0-9-]{0,62}$/;diff --git a/console/packages/agent-providers/src/host/session-services.test.ts b/console/packages/agent-providers/src/host/session-services.test.tsnew file mode 100644index 000000000..294b7cbdc--- /dev/null+++ b/console/packages/agent-providers/src/host/session-services.test.ts@@ -0,0 +1,97 @@+import { mkdtemp, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { describe, expect, it } from 'vitest';+import type { ServiceGrant } from './service-access';+import {+ recordedServicesShape,+ recordSessionServices,+ servicesChanged,+ servicesShape,+} from './session-services';++const grant = (service: string, overrides: Partial<ServiceGrant> = {}): ServiceGrant => ({+ service,+ access: 'read',+ tool_mode: 'allow',+ tools: [],+ resources: {},+ revision: 1,+ skill: { name: service, content: `# ${service}` },+ mcp_servers: [],+ cli_tools: [],+ ...overrides,+});++describe('the shape of a session’s grants', () => {+ it('changes when a service is granted or taken away', () => {+ const before = servicesShape({ grants: [grant('github')], unavailable: null });+ const after = servicesShape({+ grants: [grant('github'), grant('google-workspace')],+ unavailable: null,+ });+ expect(after).not.toBe(before);+ expect(servicesShape({ grants: [], unavailable: null })).not.toBe(before);+ });++ it('leaves out what tokens carry: access, resources and revision', () => {+ const before = servicesShape({ grants: [grant('github')], unavailable: null });+ const widened = grant('github', {+ access: 'write',+ resources: { repository_ids: [1] },+ revision: 2,+ });+ expect(servicesShape({ grants: [widened], unavailable: null })).toBe(before);+ });++ it('follows which tools may be called, whatever order the grants come in', () => {+ const a = grant('atlassian', { tool_mode: 'deny', tools: ['b', 'a'] });+ const g = grant('github');+ const shape = servicesShape({ grants: [a, g], unavailable: null });+ expect(servicesShape({ grants: [g, { ...a, tools: ['a', 'b'] }], unavailable: null })).toBe(+ shape+ );+ expect(servicesShape({ grants: [g, { ...a, tools: ['a'] }], unavailable: null })).not.toBe(+ shape+ );+ });++ it('is unknown when the grants could not be read', () => {+ expect(servicesShape({ grants: [], unavailable: 'HTTP 503' })).toBeNull();+ });+});++describe('a session’s recorded grants', () => {+ it('reads back what its host recorded, and nothing for a host that recorded none', async () => {+ const root = await mkdtemp(join(tmpdir(), 'session-services-'));+ expect(await recordedServicesShape(root)).toBeUndefined();+ await recordSessionServices(root, { grants: [grant('github')], unavailable: null });+ expect(await recordedServicesShape(root)).toBe(+ servicesShape({ grants: [grant('github')], unavailable: null })+ );+ await recordSessionServices(root, { grants: [], unavailable: 'HTTP 503' });+ expect(await recordedServicesShape(root)).toBeNull();+ });++ it('refuses a record it cannot read', async () => {+ const root = await mkdtemp(join(tmpdir(), 'session-services-'));+ await writeFile(join(root, 'services.json'), '{"shape": 1}');+ await expect(recordedServicesShape(root)).rejects.toThrow();+ });+});++describe('whether a session’s grants changed', () => {+ it('is a change when both sides are known and differ', () => {+ expect(servicesChanged('[]', '[1]')).toBe(true);+ expect(servicesChanged('[1]', '[1]')).toBe(false);+ });++ it('is a change for a host that started without its grants, once they can be read', () => {+ expect(servicesChanged(null, '[]')).toBe(true);+ });++ it('is never a change on a guess', () => {+ expect(servicesChanged(undefined, '[1]')).toBe(false);+ expect(servicesChanged('[]', null)).toBe(false);+ });+});diff --git a/console/packages/agent-providers/src/host/session-services.ts b/console/packages/agent-providers/src/host/session-services.tsnew file mode 100644index 000000000..422b8caf8--- /dev/null+++ b/console/packages/agent-providers/src/host/session-services.ts@@ -0,0 +1,87 @@+import { readFile, rename, writeFile } from 'node:fs/promises';+import { join } from 'node:path';+import { z } from 'zod';+import type { ServiceGrant } from './service-access';+import { type SessionServices, type SharedHostConfig, sessionServiceGrants } from './shared-config';++/**+ * How often a watcher with live sessions reads its agent's grants again, so a+ * service granted or taken away while they run reaches them.+ */+export const GRANTS_CHECK_MS = 30_000;++const FILE = 'services.json';+const recordSchema = z.strictObject({ shape: z.string().nullable() });++/**+ * What of an agent's grants a session builds its tools from as it starts: each+ * granted service, its skill, its vendor MCP servers and command-line tools,+ * and which of their tools it may call. A change here needs a new session+ * host. The access level, resources and revision are not part of it: tokens+ * carry those, and a running session's tokens follow them within half a+ * minute (`AgentServiceTokens`). Null when the grants could not be read.+ */+export function servicesShape(services: SessionServices): string | null {+ if (services.unavailable !== null) return null;+ return JSON.stringify(+ [...services.grants]+ .sort((a, b) => a.service.localeCompare(b.service))+ .map((grant: ServiceGrant) => ({+ service: grant.service,+ tool_mode: grant.tool_mode,+ tools: [...grant.tools].sort(),+ skill: grant.skill,+ mcp_servers: grant.mcp_servers,+ cli_tools: grant.cli_tools,+ }))+ );+}++/** Records, at a session's root, the shape of the grants its host started with. */+export async function recordSessionServices(+ sessionRoot: string,+ services: SessionServices+): Promise<void> {+ const path = join(sessionRoot, FILE);+ const temporary = `${path}.next`;+ await writeFile(temporary, JSON.stringify({ shape: servicesShape(services) }), {+ mode: 0o600,+ });+ await rename(temporary, path);+}++/**+ * The shape a session's host recorded as it started: null when it started+ * without its grants, undefined when it recorded none (a host from before+ * the record).+ */+export async function recordedServicesShape(+ sessionRoot: string+): Promise<string | null | undefined> {+ let text: string;+ try {+ text = await readFile(join(sessionRoot, FILE), 'utf8');+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined;+ throw error;+ }+ return recordSchema.parse(JSON.parse(text)).shape;+}++/**+ * Whether a session started under other grants than `current`'s. Unknown on+ * either side (a host that recorded nothing, grants that cannot be read now)+ * is not a change: restarting on it would cost a conversation its tools for+ * nothing.+ */+export function servicesChanged(+ recorded: string | null | undefined,+ current: string | null+): boolean {+ return recorded !== undefined && current !== null && recorded !== current;+}++/** The shape of the agent's grants as they stand now, read as the watcher's template reaches Switch. */+export async function currentServicesShape(template: SharedHostConfig): Promise<string | null> {+ return servicesShape(await sessionServiceGrants(template));+}diff --git a/console/packages/agent-providers/src/host/shared-daemon.ts b/console/packages/agent-providers/src/host/shared-daemon.tsindex 43eff8292..dd7c3703c 100644--- a/console/packages/agent-providers/src/host/shared-daemon.ts+++ b/console/packages/agent-providers/src/host/shared-daemon.ts@@ -16,6 +16,7 @@ import { adapterFor } from './server';import { grantedSkills } from './service-access';import { runGitCredentialHelper, runGitHubCli } from './service-github';import { HOST_EXIT_GRACE_MS, SessionLinks } from './session-channel';+import { recordSessionServices } from './session-services';import {readProviderLogin,readSharedCredentials,@@ -205,6 +206,9 @@ async function main(): Promise<void> {process.on('disconnect', () => stop.abort());try {const services = await sessionServiceGrants(config);+ // What the watcher compares the agent's grants against, to restart this+ // host when a service is granted or taken away (`servicesChanged`).+ await recordSessionServices(resolve(root), services);await hostSessionProcess({root,config,diff --git a/docs/design/controller-contract-v1.md b/docs/design/controller-contract-v1.mdindex 656886037..ad4c64ae8 100644--- a/docs/design/controller-contract-v1.md+++ b/docs/design/controller-contract-v1.md@@ -304,7 +304,7 @@ type ServiceResources =```- **Who gets a token.** Core issues only for an agent that holds a grant to its owner's own connection. A controller must belong to that owner and be bound to the agent (§7); an agent's own key works only while it has no binding.-- **When grants are read.** The agent's host reads its grants when a session starts, and a change of skills applies from the next session. No stream frame announces a change. While it holds a token, the host reads the grants again at most every 30 seconds, when a token is asked for, and drops the token once its grant's `revision` is not the token's `grant_revision`, so a widened, narrowed or removed grant reaches running sessions within that. A removed grant also fails the next fetch, and a GitHub token already issued is revoked at once. A pass-through service's token is its owner's own and cannot be revoked alone: a token already handed out stays valid at the vendor until it expires, and while the host cannot read the grants a removed grant stops a running session by `use_until`, within the hour.+- **When grants are read.** The agent's host reads its grants when a session starts. No stream frame announces a change: the agent's watcher reads the grants every 30 seconds while it has live sessions, and restarts a session on its own conversation (once idle) when a service was granted or taken away, or its tools changed. While it holds a token, the host reads the grants again at most every 30 seconds, when a token is asked for, and drops the token once its grant's `revision` is not the token's `grant_revision`, so a widened, narrowed or removed grant reaches running sessions within that. A removed grant also fails the next fetch, and a GitHub token already issued is revoked at once. A pass-through service's token is its owner's own and cannot be revoked alone: a token already handed out stays valid at the vendor until it expires, and while the host cannot read the grants a removed grant stops a running session by `use_until`, within the hour.- **`credential.revoked` is not used for grants.** It revokes the controller itself.- **Templates and key tokens.** A template's `{token}` is the token as handed out; any other `{name}` is a field of a key service's token. A key service (catalog `adapter: api_key`) hands out its token as compact JSON, `{"public": {...}, "secret": {...}}`: the fields the owner pasted (`secret`) and picked (`public`, the only ones a URL may name). The host renders each server's `url` and `headers`, or a tool's `env`, from it, and redacts every `secret` value on its own as well as the whole token.- **Where tokens go.** The controller keeps tokens in memory and serves them to a session's tools and helpers. It never writes one to disk, a CLI's arguments or its environment, except GitHub's, which `git` receives from its credential helper and `gh` from its wrapper. A service with `mcp_servers` never reaches the CLI at all: the session's host serves each of them to the CLI on loopback, behind a key made for the run, asks for the token on each call and calls the vendor itself. A service with `cli_tools` is the same: the host serves each tool on loopback, checks every command against `allow`, `deny` and `path_flags`, asks for the token on each run, and runs `binary` itself with the token only in `token_env` of that run's environment.diff --git a/docs/design/service-connections-v1.md b/docs/design/service-connections-v1.mdindex 9a770cebb..9942acf90 100644--- a/docs/design/service-connections-v1.md+++ b/docs/design/service-connections-v1.md@@ -366,6 +366,17 @@ through `runAgentHost`.session starts without them, the log says why, and the session is told inits context that its granted services are not set up and are loaded againwhen it next starts.+- **Grants changing under a running session** (`host/session-services.ts`):+ the session host records the shape of the grants it started with (services,+ skills, vendor MCP servers and CLI tools, allowed tools; not access,+ resources or revision, which tokens carry). The agent's watcher reads the+ grants every 30 seconds while it has live sessions and restarts, on their own+ conversation, each session whose host started under another shape: an idle+ one at once, a busy one once its turn ends, the same path as a definition+ change. A `!reset` restarts the host first when the shape changed, so the+ fresh conversation has the new tools. A host that recorded nothing, or grants+ that cannot be read, is never a change; a session is restarted at most once+ for the same grants.- **Skills:** granted skills are added when a session is prepared(`prepareSharedConfig`), after the agent's template is applied, so resumingneither drops nor repeats them. They join `execution.context` for Claude